remove whitespace (space/tab) from empty lines

pull/1206/head
Andreas Ziegler 2016-06-04 01:08:16 +02:00
parent 5e4f09352d
commit 898ea1d97c
164 changed files with 1171 additions and 1173 deletions

View File

@ -186,7 +186,7 @@ cp -a bootstrap.default.php bootstrap.php
cp -a database.default.php database.php
cp -a core.default.php core.php
cp -a config.default.php config.php
# Configure the fields in the newly created files:
# config.php : baseurl
# database.php : login, port, password, database

View File

@ -199,7 +199,7 @@ cp -a bootstrap.default.php bootstrap.php
cp -a database.default.php database.php
cp -a core.default.php core.php
cp -a config.default.php config.php
# Configure the fields in the newly created files:
# config.php : baseurl
# database.php : login, port, password, database

View File

@ -123,7 +123,7 @@ cp /var/www/MISP/INSTALL/apache.misp.ubuntu /etc/apache2/sites-available/misp.co
# Be aware that the configuration files for apache 2.4 and up have changed.
# The configuration file has to have the .conf extension in the sites-available directory
# For more information, visit http://httpd.apache.org/docs/2.4/upgrading.html
a2dissite 000-default
# 000-default can be called default based on distribution, in which case run a2dissite default
a2ensite misp
@ -146,7 +146,7 @@ cp -a bootstrap.default.php bootstrap.php
cp -a database.default.php database.php
cp -a core.default.php core.php
cp -a config.default.php config.php
# Configure the fields in the newly created files:
# database.php : login, port, password, database

View File

@ -116,7 +116,7 @@ cp /var/www/MISP/INSTALL/apache.misp.ubuntu /etc/apache2/sites-available/misp.co
# Be aware that the configuration files for apache 2.4 and up have changed.
# The configuration file has to have the .conf extension in the sites-available directory
# For more information, visit http://httpd.apache.org/docs/2.4/upgrading.html
a2dissite 000-default
# 000-default can be called default based on distribution, in which case run a2dissite default
a2ensite misp
@ -139,7 +139,7 @@ cp -a bootstrap.default.php bootstrap.php
cp -a database.default.php database.php
cp -a core.default.php core.php
cp -a config.default.php config.php
# Configure the fields in the newly created files:
# database.php : login, port, password, database

View File

@ -6,7 +6,7 @@ Upgrade procedure from v2.1 to v2.2
- execute UPGRADE.SH in the MISP/INSTALL folder (this also includes the installation of Redis for CakeResque)
- cd /var/www/MISP/INSTALL
- ./UPGRADE.SH
- Replace your current bootstrap.php file found in /MISP/app/Config/ with bootstrap.default.php and change set your instance up to your liking
- Log in with the site admin credentials and execute the following commands by changing the url
@ -28,5 +28,5 @@ Enabling background jobs via CakeResque
- cd /var/www/MISP/app/Console/worker/
- ./start.sh
Make sure you configure your OS to start this script as boot time !
================================================================================================================================================

View File

@ -6,7 +6,7 @@ to write to a log database table.
https://github.com/eskil-saatvedt/CakePHP-Assets/blob/master/models/behaviors/LogableBehavior.php
Adds the logable Model Behavior.
http://bakery.cakephp.org/articles/rikdc/2010/06/07/syslog-component
Adds the syslog capability.

View File

@ -33,7 +33,7 @@ class AppSchema extends CakeSchema {
'username' => array('type' => 'string', 'null' => false, 'default' => null, 'collate' => 'utf8_bin', 'charset' => 'utf8'),
'expire' => array('type' => 'datetime', 'null' => false, 'default' => null),
'indexes' => array(
),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_bin', 'engine' => 'MyISAM')
);

View File

@ -92,7 +92,7 @@ if (!$relativePaths) {
if (isset($_SERVER['SERVER_NAME'])) $serverName = $_SERVER['SERVER_NAME'];
else if (isset($_SERVER['HTTP_HOST'])) $serverName = $_SERVER['HTTP_HOST'];
else if (isset($_SERVER['SERVER_ADDR'])) $serverName = $_SERVER['SERVER_ADDR'];
if (!Configure::read('MISP.baseurl') && isset($serverName)) {
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)) {
$protocol = 'https';

View File

@ -3,7 +3,7 @@ App::uses('AppShell', 'Console/Command');
class AdminShell extends AppShell
{
public $uses = array('Event');
public function jobGenerateCorrelation() {
$jobId = $this->args[0];
$this->loadModel('Job');
@ -14,7 +14,7 @@ class AdminShell extends AppShell
$this->Job->saveField('message', 'Job done.');
$this->Job->saveField('status', 4);
}
public function jobGenerateShadowAttributeCorrelation() {
$jobId = $this->args[0];
$this->loadModel('Job');
@ -22,7 +22,7 @@ class AdminShell extends AppShell
$this->loadModel('ShadowAttribute');
$this->ShadowAttribute->generateCorrelation($jobId);
}
public function jobUpgrade24() {
$jobId = $this->args[0];
$user_id = $this->args[1];

View File

@ -33,7 +33,7 @@ class EventShell extends AppShell
$this->Job->saveField('status', 1);
$this->Job->saveField('message', 'Job done.');
}
public function cachexml() {
$userId = $this->args[0];
$id = $this->args[1];
@ -64,7 +64,7 @@ class EventShell extends AppShell
$file->append('</response>' . PHP_EOL);
$file->close();
}
private function __recursiveEcho($array) {
$text = "";
foreach ($array as $k => $v) {
@ -87,7 +87,7 @@ class EventShell extends AppShell
}
return $text;
}
public function cachehids() {
$userId = $this->args[0];
$user = $this->User->getAuthUser($userId);
@ -111,7 +111,7 @@ class EventShell extends AppShell
$this->Job->saveField('progress', '100');
$this->Job->saveField('message', 'Job done.');
}
public function cacherpz() {
$userId = $this->args[0];
$user = $this->User->getAuthUser($userId);
@ -149,7 +149,7 @@ class EventShell extends AppShell
$this->Job->saveField('progress', '100');
$this->Job->saveField('message', 'Job done.');
}
public function cachecsv() {
$userId = $this->args[0];
$user = $this->User->getAuthUser($userId);
@ -185,7 +185,7 @@ class EventShell extends AppShell
$this->Job->saveField('progress', '100');
$this->Job->saveField('message', 'Job done.');
}
public function cachetext() {
$userId = $this->args[0];
$user = $this->User->getAuthUser($userId);
@ -211,7 +211,7 @@ class EventShell extends AppShell
$this->Job->saveField('progress', 100);
$this->Job->saveField('message', 'Job done.');
}
public function cachenids() {
$userId = $this->args[0];
$user = $this->User->getAuthUser($userId);
@ -244,7 +244,7 @@ class EventShell extends AppShell
$this->Job->saveField('progress', '100');
$this->Job->saveField('message', 'Job done.');
}
public function alertemail() {
$userId = $this->args[0];
$processId = $this->args[1];
@ -256,7 +256,7 @@ class EventShell extends AppShell
$job['Job']['message'] = 'Emails sent.';
$this->Job->save($job);
}
public function contactemail() {
$id = $this->args[0];
$message = $this->args[1];
@ -284,11 +284,11 @@ class EventShell extends AppShell
$job['Job']['message'] = 'Emails sent.';
$this->Job->save($job);
}
public function enqueueCaching() {
$timestamp = $this->args[0];
$task = $this->Task->findByType('cache_exports');
// If the next execution time and the timestamp don't match, it means that this task is no longer valid as the time for the execution has since being scheduled
// been updated.
if ($task['Task']['next_execution_time'] != $timestamp) return;
@ -319,9 +319,9 @@ class EventShell extends AppShell
'fields' => array('User.org_id', 'User.id')
));
$users[] = $site_admin;
if ($task['Task']['timer'] > 0) $this->Task->reQueue($task, 'cache', 'EventShell', 'enqueueCaching', false, false);
// Queue a set of exports for admins. This "ADMIN" organisation. The organisation of the admin users doesn't actually matter, it is only used to indentify
// the special cache files containing all events
$i = 0;
@ -334,7 +334,7 @@ class EventShell extends AppShell
$this->Task->id = $task['Task']['id'];
$this->Task->saveField('message', $i . ' job(s) started at ' . date('d/m/Y - H:i:s') . '.');
}
public function publish() {
$id = $this->args[0];
$passAlong = $this->args[1];

View File

@ -17,7 +17,7 @@ class PasswordShell extends AppShell {
$results['User']['password'] = $this->args[1];
$results['User']['confirm_password'] = $this->args[1];
$results['User']['change_pw'] = 1;
if (!$this->User->save($results)) {
echo 'Could not update account for User.id = ', $results['User']['id'], PHP_EOL;
debug($this->User->validationErrors);

View File

@ -5,7 +5,7 @@ require_once 'AppShell.php';
class ServerShell extends AppShell
{
public $uses = array('Server', 'Task', 'Job', 'User', 'Feed');
public function pull() {
$userId = $this->args[0];
$serverId = $this->args[1];
@ -41,11 +41,11 @@ class ServerShell extends AppShell
$this->Job->saveField('message', 'Invalid technique chosen.');
return;
break;
}
}
}
public function push() {
$serverId = $this->args[0];
$jobId = $this->args[2];
@ -70,7 +70,7 @@ class ServerShell extends AppShell
$this->Task->saveField('message', 'Job(s) started at ' . date('d/m/Y - H:i:s') . '.');
}
}
public function fetchFeed() {
$userId = $this->args[0];
@ -88,7 +88,7 @@ class ServerShell extends AppShell
'status' => 4
));
}
public function enqueuePull() {
$timestamp = $this->args[0];
$userId = $this->args[1];
@ -115,9 +115,9 @@ class ServerShell extends AppShell
);
$this->Job->save($data);
$jobId = $this->Job->id;
if ($task['Task']['timer'] > 0) $this->Task->reQueue($task, 'default', 'ServerShell', 'enqueuePull', $userId, $taskId);
App::uses('SyncTool', 'Tools');
$syncTool = new SyncTool();
$result = $this->Server->pull($user, $server['Server']['id'], 'full', $server, $jobId);
@ -141,7 +141,7 @@ class ServerShell extends AppShell
case '4' :
$this->Job->saveField('message', 'Invalid technique chosen.');
break;
}
$failCount++;
}
@ -149,7 +149,7 @@ class ServerShell extends AppShell
$this->Task->id = $task['Task']['id'];
$this->Task->saveField('message', count($servers) . ' job(s) completed at ' . date('d/m/Y - H:i:s') . '. Failed jobs: ' . $failCount . '/' . $count);
}
public function enqueuePush() {
$timestamp = $this->args[0];
$taskId = $this->args[1];
@ -160,7 +160,7 @@ class ServerShell extends AppShell
return;
}
if ($task['Task']['timer'] > 0) $this->Task->reQueue($task, 'default', 'ServerShell', 'enqueuePush', $userId, $taskId);
$this->User->recursive = -1;
$user = $this->User->getAuthUser($userId);
$servers = $this->Server->find('all', array('recursive' => -1, 'conditions' => array('push' => 1)));

View File

@ -48,7 +48,7 @@ class UserInitShell extends AppShell {
$org_id = $firstOrg['Organisation']['id'];
}
}
// populate the DB with the first user if it's empty
if ($this->User->find('count') == 0 ) {
$authkey = $this->User->generateAuthKey();

View File

@ -42,11 +42,11 @@ class AppController extends Controller {
public $defaultModel = '';
public $debugMode = false;
public $helpers = array('Utility');
private $__jsVersion = '2.4.46';
// Used for _isAutomation(), a check that returns true if the controller & action combo matches an action that is a non-xml and non-json automation method
// This is used to allow authentication via headers for methods not covered by _isRest() - as that only checks for JSON and XML formats
public $automationArray = array(
@ -75,7 +75,7 @@ class AppController extends Controller {
'Security',
'ACL'
);
public function beforeFilter() {
$this->set('jsVersion', $this->__jsVersion);
$this->loadModel('User');
@ -120,10 +120,10 @@ class AppController extends Controller {
if (isset($_SERVER['HTTP_USER_AGENT'])) {
if(preg_match('/(?i)msie [2-8]/',$_SERVER['HTTP_USER_AGENT']) && !strpos($_SERVER['HTTP_USER_AGENT'], 'Opera')) throw new MethodNotAllowedException('You are using an unsecure and outdated version of IE, please download Google Chrome, Mozilla Firefox or update to a newer version of IE. If you are running IE9 or newer and still receive this error message, please make sure that you are not running your browser in compatibility mode. If you still have issues accessing the site, get in touch with your administration team at ' . Configure::read('MISP.contact'));
}
$userLoggedIn = false;
if (Configure::read('Plugin.CustomAuth_enable')) $userLoggedIn = $this->__customAuthentication($_SERVER);
if (!$userLoggedIn) {
// REST authentication
if ($this->_isRest() || $this->_isAutomation()) {
@ -213,7 +213,7 @@ class AppController extends Controller {
if ($base_dir == '/') {
$base_dir = '';
}
if ($this->Auth->user()) {
// update script
$this->{$this->modelClass}->runUpdates();
@ -247,7 +247,7 @@ class AppController extends Controller {
} else {
if (!($this->params['controller'] === 'users' && $this->params['action'] === 'login')) $this->redirect(array('controller' => 'users', 'action' => 'login', 'admin' => false));
}
// check if MISP is live
if ($this->Auth->user() && !Configure::read('MISP.live')) {
$role = $this->getActions();
@ -324,7 +324,7 @@ class AppController extends Controller {
$this->set('notifications', $notifications);
$this->ACL->checkAccess($this->Auth->user(), Inflector::variable($this->request->params['controller']), $this->action);
}
public function queryACL($debugType='findMissingFunctionNames', $content = false) {
$this->autoRender = false;
$this->layout = false;
@ -335,7 +335,7 @@ class AppController extends Controller {
$this->response->type('json');
$this->render('/Servers/json/simple');
}
private function __convertEmailToName($email) {
$name = explode('@', $email);
$name = explode('.', $name[0]);
@ -348,7 +348,7 @@ class AppController extends Controller {
if ($type === 'csrf') throw new BadRequestException(__d('cake_dev', $type));
throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
}
public $userRole = null;
protected function _isJson($data=false) {
@ -359,14 +359,14 @@ class AppController extends Controller {
protected function _isRest() {
return (isset($this->RequestHandler) && ($this->RequestHandler->isXml() || $this->_isJson()));
}
protected function _isAutomation() {
foreach ($this->automationArray as $controllerName => $controllerActions) {
if ($this->params['controller'] == $controllerName && in_array($this->params['action'], $controllerActions)) return true;
}
return false;
}
/**
* Convert an array to the same array but with the values also as index instead of an interface_exists
*/
@ -433,7 +433,7 @@ class AppController extends Controller {
if ($user['Role']['perm_site_admin']) $user['siteadmin'] = true;
return $user;
}
public function checkExternalAuthUser($authkey) {
$this->loadModel('User');
$user = $this->User->getAuthUserByExternalAuth($authkey);
@ -461,7 +461,7 @@ class AppController extends Controller {
$this->Session->setFlash(__('All done. attribute_count generated from scratch for ' . (isset($k) ? $k : 'no') . ' events.'));
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration'));
}
public function pruneDuplicateUUIDs() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->loadModel('Attribute');
@ -488,7 +488,7 @@ class AppController extends Controller {
$this->Session->setFlash('Done. Assigned new UUIDs to ' . $counter . ' attribute(s).');
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration'));
}
public function removeDuplicateEvents() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->loadModel('Event');
@ -498,10 +498,10 @@ class AppController extends Controller {
'group' => array('Event.uuid HAVING COUNT(*) > 1'),
));
$counter = 0;
// load this so we can remove the blacklist item that will be created, this is the one case when we do not want it.
if (Configure::read('MISP.enableEventBlacklisting')) $this->EventBlacklist = ClassRegistry::init('EventBlacklist');
foreach ($duplicates as $duplicate) {
$events = $this->Event->find('all', array(
'recursive' => -1,
@ -524,7 +524,7 @@ class AppController extends Controller {
$this->Session->setFlash('Done. Removed ' . $counter . ' duplicate events.');
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration'));
}
public function updateDatabase($command) {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->loadModel('Server');
@ -532,7 +532,7 @@ class AppController extends Controller {
$this->Session->setFlash('Done.');
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration'));
}
public function upgrade2324() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->loadModel('Server');
@ -564,13 +564,13 @@ class AppController extends Controller {
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration'));
}
}
private function __preAuthException($message) {
$this->set('debugMode', (Configure::read('debug') > 1) ? 'debugOn' : 'debugOff');
$this->set('me', array());
throw new ForbiddenException($message);
}
private function __customAuthentication(&$server) {
$result = false;
if (Configure::read('Plugin.CustomAuth_enable')) {
@ -637,7 +637,7 @@ class AppController extends Controller {
}
return $result;
}
public function cleanModelCaches() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->loadModel('Server');

View File

@ -57,7 +57,7 @@ class AttributesController extends AppController {
$this->paginate = Set::merge($this->paginate, array('conditions' => $this->Attribute->buildConditions($this->Auth->user())));
}
}
/**
* index method
*
@ -99,7 +99,7 @@ class AttributesController extends AppController {
if ($this->request->is('ajax')) $this->autoRender = false;
$this->loadModel('Event');
$date = new DateTime();
// remove the published flag from the event
$this->Event->recursive = -1;
if (isset($eventId)) {
@ -168,7 +168,7 @@ class AttributesController extends AppController {
// list the ones that succeeded
$this->Session->setFlash(__('The lines' . $successes . ' have been saved', true));
}
$this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['Attribute']['event_id']));
}
} else {
@ -192,7 +192,7 @@ class AttributesController extends AppController {
$this->request->data['Attribute']['timestamp'] = $date->getTimestamp();
}
}
if (isset($this->request->data['Attribute']['base64'])) $this->request->data['Attribute']['data'] = $this->request->data['Attribute']['base64'];
//
// single attribute
@ -261,11 +261,11 @@ class AttributesController extends AppController {
$this->loadModel('SharingGroup');
$sgs = $this->SharingGroup->fetchAllAuthorised($this->Auth->user(), 'name', 1);
$this->set('sharingGroups', $sgs);
$distributionLevels = $this->Attribute->distributionLevels;
if (empty($sgs)) unset ($distributionLevels[4]);
$this->set('distributionLevels', $distributionLevels);
$this->set('attrDescriptions', $this->Attribute->fieldDescriptions);
$this->set('typeDefinitions', $this->Attribute->typeDefinitions);
$this->set('categoryDefinitions', $this->Attribute->categoryDefinitions);
@ -327,9 +327,9 @@ class AttributesController extends AppController {
$partialFails = array();
$fails = array();
$success = 0;
foreach ($this->request->data['Attribute']['values'] as $k => $value) {
// Check if there were problems with the file upload
// only keep the last part of the filename, this should prevent directory attacks
$filename = basename($value['name']);
@ -343,7 +343,7 @@ class AttributesController extends AppController {
$fails[] = $filename;
continue;
}
if ($this->request->data['Attribute']['malware']) {
$result = $this->Event->Attribute->handleMaliciousBase64($this->request->data['Attribute']['event_id'], $filename, base64_encode($tmpfile->read()), array_keys($hashes));
if (!$result['success']) {
@ -397,7 +397,7 @@ class AttributesController extends AppController {
else $success++;
}
}
$message = 'The attachment(s) have been uploaded.';
if (!empty($partialFails)) $message .= ' Some of the hashes however could not be generated.';
if (!empty($fails)) $message = 'Some of the attachments failed to upload. The failed files were: ' . implode(', ', $fails) . ' - This can be caused by the attachments already existing in the event.';
@ -413,7 +413,7 @@ class AttributesController extends AppController {
// set the event_id in the form
$this->request->data['Attribute']['event_id'] = $eventId;
}
// combobox for categories
$categories = array_keys($this->Attribute->categoryDefinitions);
// just get them with attachments..
@ -432,29 +432,29 @@ class AttributesController extends AppController {
}
$categories = $this->_arrayToValuesIndexArray($selectedCategories);
$this->set('categories',$categories);
$this->set('attrDescriptions', $this->Attribute->fieldDescriptions);
$this->set('typeDefinitions', $this->Attribute->typeDefinitions);
$this->set('categoryDefinitions', $this->Attribute->categoryDefinitions);
$this->set('zippedDefinitions', $this->Attribute->zippedDefinitions);
$this->set('uploadDefinitions', $this->Attribute->uploadDefinitions);
// combobox for distribution
$this->loadModel('Event');
$this->set('distributionDescriptions', $this->Attribute->distributionDescriptions);
$this->set('distributionLevels', $this->Event->Attribute->distributionLevels);
$this->loadModel('SharingGroup');
$sgs = $this->SharingGroup->fetchAllAuthorised($this->Auth->user(), 'name', 1);
$this->set('sharingGroups', $sgs);
$events = $this->Event->findById($eventId);
$this->set('currentDist', $events['Event']['distribution']);
$this->set('published', $events['Event']['published']);
}
/**
* Imports the CSV threatConnect file to multiple attributes
* @param int $id The id of the event
@ -505,7 +505,7 @@ class AttributesController extends AppController {
}
// verify header of the file (first row)
$required_headers = array('Type', 'Value', 'Confidence', 'Description', 'Source');
if (count(array_intersect($header, $required_headers)) != count($required_headers)) {
$this->Session->setFlash('Incorrect ThreatConnect headers. The minimum required headers are: '.implode(',', $required_headers), 'default', array(), 'error');
$this->redirect(array('controller' => 'attributes', 'action' => 'add_threatconnect', $this->request->data['Attribute']['event_id']));
@ -744,20 +744,20 @@ class AttributesController extends AppController {
$this->set('currentDist', $this->Event->data['Event']['distribution']);
// tooltip for distribution
$this->set('distributionDescriptions', $this->Attribute->distributionDescriptions);
$this->loadModel('SharingGroup');
$sgs = $this->SharingGroup->fetchAllAuthorised($this->Auth->user(), 'name', 1);
$this->set('sharingGroups', $sgs);
$distributionLevels = $this->Attribute->distributionLevels;
if (empty($sgs)) unset ($distributionLevels[4]);
$this->set('distributionLevels', $distributionLevels);
$this->set('attrDescriptions', $this->Attribute->fieldDescriptions);
$this->set('typeDefinitions', $this->Attribute->typeDefinitions);
$this->set('categoryDefinitions', $this->Attribute->categoryDefinitions);
}
// ajax edit - post a single edited field and this method will attempt to save it and return a json with the validation errors if they occur.
public function editField($id) {
if ((!$this->request->is('post') && !$this->request->is('put')) || !$this->request->is('ajax')) throw new MethodNotAllowedException();
@ -768,7 +768,7 @@ class AttributesController extends AppController {
$this->Attribute->recursive = -1;
$this->Attribute->contain('Event');
$attribute = $this->Attribute->read();
if (!$this->_isSiteAdmin()) {
if ($this->Attribute->data['Event']['orgc_id'] == $this->Auth->user('org_id')
&& (($this->userRole['perm_modify'] && $this->Attribute->data['Event']['user_id'] != $this->Auth->user('id'))
@ -778,7 +778,7 @@ class AttributesController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('fail' => false, 'errors' => 'Invalid attribute')),'status'=>200));
}
}
foreach ($this->request->data['Attribute'] as $changedKey => $changedField) {
if ($attribute['Attribute'][$changedKey] == $changedField) {
$this->autoRender = false;
@ -907,7 +907,7 @@ class AttributesController extends AppController {
}
}
/**
* unification of the actual delete for the multi-select
*
@ -931,7 +931,7 @@ class AttributesController extends AppController {
)),
));
if (empty($result)) throw new MethodNotAllowedException('Attribute not found or not authorised.');
// check for permissions
if (!$this->_isSiteAdmin()) {
if ($result['Event']['locked']) {
@ -957,7 +957,7 @@ class AttributesController extends AppController {
// We have just deleted the attribute, let's also check if there are any shadow attributes that were attached to it and delete them
$this->loadModel('ShadowAttribute');
$this->ShadowAttribute->deleteAll(array('ShadowAttribute.old_id' => $id), false);
// remove the published flag from the event
$result['Event']['timestamp'] = $date->getTimestamp();
$result['Event']['published'] = false;
@ -967,7 +967,7 @@ class AttributesController extends AppController {
return false;
}
}
public function deleteSelected($id) {
if (!$this->request->is('post') || !$this->request->is('ajax')) {
throw new MethodNotAllowedException();
@ -1004,10 +1004,10 @@ class AttributesController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => count($successes) . ' attribute' . (count($successes) != 1 ? 's' : '') . ' deleted, but ' . count($fails) . ' attribute' . (count($fails) != 1 ? 's' : '') . ' could not be deleted.')),'status'=>200));
}
}
public function editSelected($id) {
if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This method can only be accessed via AJAX.');
if ($this->request->is('post')) {
$event = $this->Attribute->Event->find('first', array(
'conditions' => array('id' => $id),
@ -1027,12 +1027,12 @@ class AttributesController extends AppController {
),
'recursive' => -1,
));
if ($this->request->data['Attribute']['to_ids'] == 2 && $this->request->data['Attribute']['distribution'] == 6 && $this->request->data['Attribute']['comment'] == null) {
$this->autoRender = false;
return new CakeResponse(array('body'=> json_encode(array('saved' => true)),'status' => 200));
}
if ($this->request->data['Attribute']['to_ids'] != 2) {
foreach ($attributes as &$attribute) {
$attribute['Attribute']['to_ids'] = ($this->request->data['Attribute']['to_ids'] == 0 ? false : true);
@ -1053,19 +1053,19 @@ class AttributesController extends AppController {
}
}
}
if ($this->request->data['Attribute']['comment'] != null) {
foreach ($attributes as &$attribute) {
$attribute['Attribute']['comment'] = $this->request->data['Attribute']['comment'];
}
}
$date = new DateTime();
$timestamp = $date->getTimestamp();
foreach ($attributes as &$attribute) {
$attribute['Attribute']['timestamp'] = $timestamp;
}
if($this->Attribute->saveMany($attributes)) {
$event['Event']['timestamp'] = $date->getTimestamp();
$event['Event']['published'] = 0;
@ -1364,7 +1364,7 @@ class AttributesController extends AppController {
$this->loadModel('Whitelist');
$attributes = $this->Whitelist->removeWhitelistedFromArray($attributes, true);
}
foreach ($attributes as &$attribute) {
$attributeIdList[] = $attribute['Attribute']['id'];
if (!in_array($attribute['Attribute']['event_id'], $idList)) {
@ -1383,7 +1383,7 @@ class AttributesController extends AppController {
$this->Session->write('paginate_conditions_category', $category);
$this->Session->write('search_find_idlist', $idList);
$this->Session->write('search_find_attributeidlist', $attributeIdList);
// set the same view as the index page
$this->render('index');
}
@ -1429,7 +1429,7 @@ class AttributesController extends AppController {
$this->render('index');
}
}
// If the checkbox for the alternate search is ticked, then this method is called to return the data to be represented
// This alternate view will show a list of events with matching search results and the percentage of those matched attributes being marked as to_ids
// events are sorted based on relevance (as in the percentage of matches being flagged as indicators for IDS)
@ -1472,7 +1472,7 @@ class AttributesController extends AppController {
if (!empty($events)) $events = $this->__subval_sort($events, 'relevance');
return $events;
}
// Sort the array of arrays based on a value of a sub-array
private function __subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
@ -1538,7 +1538,7 @@ class AttributesController extends AppController {
if ($from) $from = $this->Attribute->Event->dateFieldCheck($from);
if ($to) $to = $this->Attribute->Event->dateFieldCheck($to);
if ($last) $last = $this->Attribute->Event->resolveTimeDelta($last);
if (!isset($this->request->params['ext']) || $this->request->params['ext'] !== 'json') {
$this->response->type('xml'); // set the content type
$this->layout = 'xml/default';
@ -1602,7 +1602,7 @@ class AttributesController extends AppController {
$subcondition = array();
}
}
// If we sent any tags along, load the associated tag names for each attribute
if ($tags) {
$args = $this->Attribute->dissectArgs($tags);
@ -1619,11 +1619,11 @@ class AttributesController extends AppController {
}
$conditions['AND'][] = $temp;
}
if ($from) $conditions['AND'][] = array('Event.date >=' => $from);
if ($to) $conditions['AND'][] = array('Event.date <=' => $to);
if ($last) $conditions['AND'][] = array('Event.publish_timestamp >=' => $last);
// change the fields here for the attribute export!!!! Don't forget to check for the permissions, since you are not going through fetchevent. Maybe create fetchattribute?
$params = array(
'conditions' => $conditions,
@ -1797,7 +1797,7 @@ class AttributesController extends AppController {
$this->set('attributes', $attributes);
$this->render('/Attributes/text');
}
public function rpz($key='download', $tags=false, $eventId=false, $from=false, $to=false, $policy=false, $walled_garden = false, $ns = false, $email = false, $serial = false, $refresh = false, $retry = false, $expiry = false, $minimum_ttl = false, $ttl = false) {
// request handler for POSTed queries. If the request is a post, the parameters (apart from the key) will be ignored and replaced by the terms defined in the posted json or xml object.
// The correct format for both is a "request" root element, as shown by the examples below:
@ -1817,7 +1817,7 @@ class AttributesController extends AppController {
else ${$p} = null;
}
}
$simpleFalse = array('eventId', 'tags', 'from', 'to', 'policy', 'walled_garden', 'ns', 'email', 'serial', 'refresh', 'retry', 'expiry', 'minimum_ttl', 'ttl');
foreach ($simpleFalse as $sF) {
if (!is_array(${$sF}) && (${$sF} === 'null' || ${$sF} == '0' || ${$sF} === false || strtolower(${$sF}) === 'false')) ${$sF} = false;
@ -1880,7 +1880,7 @@ class AttributesController extends AppController {
if (!self::_isSiteAdmin()) throw new NotFoundException();
$this->set('result', $this->Attribute->reportValidationIssuesAttributes($eventId));
}
public function generateCorrelation() {
if (!self::_isSiteAdmin() || !$this->request->is('post')) throw new NotFoundException();
if (!Configure::read('MISP.background_jobs')) {
@ -1911,7 +1911,7 @@ class AttributesController extends AppController {
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'administration'));
}
}
public function fetchViewValue($id, $field = null) {
$validFields = array('value', 'comment', 'type', 'category', 'to_ids', 'distribution', 'timestamp');
if (!isset($field) || !in_array($field, $validFields)) throw new MethodNotAllowedException('Invalid field requested.');
@ -1943,7 +1943,7 @@ class AttributesController extends AppController {
$this->layout = 'ajax';
$this->render('ajax/attributeViewFieldForm');
}
public function fetchEditForm($id, $field = null) {
$validFields = array('value', 'comment', 'type', 'category', 'to_ids', 'distribution');
if (!isset($field) || !in_array($field, $validFields)) throw new MethodNotAllowedException('Invalid field requested.');
@ -1999,7 +1999,7 @@ class AttributesController extends AppController {
$fieldURL = ucfirst($field);
$this->render('ajax/attributeEdit' . $fieldURL . 'Form');
}
public function attributeReplace($id) {
if (!$this->userRole['perm_add']) {
@ -2015,7 +2015,7 @@ class AttributesController extends AppController {
if ($this->request->is('get')) {
$this->layout = 'ajax';
$this->request->data['Attribute']['event_id'] = $id;
// combobox for types
$types = array_keys($this->Attribute->typeDefinitions);
$types = $this->_arrayToValuesIndexArray($types);
@ -2030,14 +2030,14 @@ class AttributesController extends AppController {
}
if ($this->request->is('post')) {
if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This action can only be accessed via AJAX.');
$newValues = explode(PHP_EOL, $this->request->data['Attribute']['value']);
$category = $this->request->data['Attribute']['category'];
$type = $this->request->data['Attribute']['type'];
$to_ids = $this->request->data['Attribute']['to_ids'];
if (!$this->_isSiteAdmin() && $this->Auth->user('org_id') != $event['Event']['orgc_id'] && !$this->userRole['perm_add']) throw new MethodNotAllowedException('You are not authorised to do that.');
$oldAttributes = $this->Attribute->find('all', array(
'conditions' => array(
'event_id' => $id,
@ -2048,7 +2048,7 @@ class AttributesController extends AppController {
'recursive' => -1,
));
$results = array('untouched' => count($oldAttributes), 'created' => 0, 'deleted' => 0, 'createdFail' => 0, 'deletedFail' => 0);
foreach ($newValues as &$value) {
$value = trim($value);
$found = false;
@ -2074,7 +2074,7 @@ class AttributesController extends AppController {
}
}
}
foreach ($oldAttributes as &$old) {
if (!in_array($old['Attribute']['value'], $newValues)) {
if ($this->Attribute->delete($old['Attribute']['id'])) {
@ -2101,26 +2101,26 @@ class AttributesController extends AppController {
$message .= 'Update completed with some errors.';
$success = false;
}
if ($results['created']) $message .= $results['created'] . ' attribute' . $this->__checkCountForOne($results['created']) . ' created. ';
if ($results['createdFail']) $message .= $results['createdFail'] . ' attribute' . $this->__checkCountForOne($results['createdFail']) . ' could not be created. ';
if ($results['deleted']) $message .= $results['deleted'] . ' attribute' . $this->__checkCountForOne($results['deleted']) . ' deleted.';
if ($results['deletedFail']) $message .= $results['deletedFail'] . ' attribute' . $this->__checkCountForOne($results['deletedFail']) . ' could not be deleted. ';
$message .= $results['untouched'] . ' attributes left untouched. ';
$this->autoRender = false;
$this->layout = 'ajax';
if ($success) return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => $message)),'status'=>200));
else return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'errors' => $message)),'status'=>200));
}
}
private function __checkCountForOne($number) {
if ($number != 1) return 's';
return '';
}
// download a sample by passing along an md5
public function downloadSample($hash=false, $allSamples=false, $eventID=false) {
if (!$this->userRole['perm_auth']) throw new MethodNotAllowedException('This functionality requires API key access.');
@ -2137,13 +2137,13 @@ class AttributesController extends AppController {
if (!$eventID && isset($data['request']['eventID'])) $eventID = $data['request']['eventID'];
if (!$eventID && !$hash) throw new MethodNotAllowedException('No hash or event ID received. You need to set at least one of the two.');
if (!$hash) $allSamples = true;
$simpleFalse = array('hash', 'allSamples', 'eventID');
foreach ($simpleFalse as $sF) {
if (!is_array(${$sF}) && (${$sF} === 'null' || ${$sF} == '0' || ${$sF} === false || strtolower(${$sF}) === 'false')) ${$sF} = false;
}
// valid combinations of settings are:
// hash
// eventID + all samples
@ -2191,9 +2191,9 @@ class AttributesController extends AppController {
}
}
}
if (!empty($eventID)) $searchConditions['AND'][] = array('Event.id' => $eventID);
if (empty($error)) {
$attributes = $this->Attribute->fetchAttributes(
$this->Auth->user(),
@ -2209,7 +2209,7 @@ class AttributesController extends AppController {
)
);
if (empty($attributes)) $error = 'No hits with the given parameters.';
$results = array();
foreach ($attributes as $attribute) {
$found = false;
@ -2239,7 +2239,7 @@ class AttributesController extends AppController {
$this->set('_serialize', array('message'));
}
}
public function pruneOrphanedAttributes() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException('You are not authorised to do that.');
$events = array_keys($this->Attribute->Event->find('list'));
@ -2248,7 +2248,7 @@ class AttributesController extends AppController {
$this->Session->setFlash('Removed ' . count($orphans) . ' attribute(s).');
$this->redirect('/pages/display/administration');
}
public function updateAttributeValues($script) {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException('You are not authorised to do that.');
switch ($script) {
@ -2283,7 +2283,7 @@ class AttributesController extends AppController {
$this->Session->setFlash('Updated ' . $counter . ' attribute(s).');
$this->redirect('/pages/display/administration');
}
public function hoverEnrichment($id) {
$attribute = $this->Attribute->fetchAttributes($this->Auth->user(), array('conditions' => array('Attribute.id' => $id)));
if (empty($attribute)) throw new NotFoundException('Invalid Attribute');
@ -2342,7 +2342,7 @@ class AttributesController extends AppController {
$this->layout = 'ajax';
$this->render('ajax/hover_enrichment');
}
public function describeTypes() {
$result = array();
$result['types'] = array_keys($this->Attribute->typeDefinitions);
@ -2353,7 +2353,7 @@ class AttributesController extends AppController {
$this->set('result', $result);
$this->set('_serialize', array('result'));
}
public function attributeStatistics($type = 'type', $percentage = false) {
$validTypes = array('type', 'category');
if (!in_array($type, $validTypes)) throw new MethodNotAllowedException('Invalid type requested.');

View File

@ -351,7 +351,7 @@ class ACLComponent extends Component {
'index' => array('*'),
)
);
// The check works like this:
// If the user is a site admin, return true
// If the requested action has an OR-d list, iterate through the list. If any of the permissions are set for the user, return true
@ -374,7 +374,7 @@ class ACLComponent extends Component {
}
$this->__error(403, 'You do not have permission to use this functionality.');
}
private function __error($code, $message) {
switch ($code) {
case 404:
@ -386,7 +386,7 @@ class ACLComponent extends Component {
throw new InternalErrorException('Unknown error: ' . $message);
}
}
private function __findAllFunctions() {
$functionFinder = '/function[\s\n]+(\S+)[\s\n]*\(/';
$dir = new Folder(APP . 'Controller');
@ -404,7 +404,7 @@ class ACLComponent extends Component {
}
return $results;
}
public function printAllFunctionNames($content = false) {
$results = $this->__findAllFunctions();
ksort($results);
@ -423,7 +423,7 @@ class ACLComponent extends Component {
}
return $missing;
}
public function printRoleAccess($content = false) {
$results = array();
$this->Role = ClassRegistry::init('Role');
@ -440,7 +440,7 @@ class ACLComponent extends Component {
}
return $results;
}
private function __checkRoleAccess($role) {
$result = array();
foreach ($this->__aclList as $controller => &$actions) {

View File

@ -52,7 +52,7 @@ class ApacheAuthenticate extends BaseAuthenticate {
$filter = '('.Configure::read('ApacheSecureAuth.ldapSearchAttribut').'=' . $_SERVER[$envvar] . ')';
// example: mail
$getLdapUserInfo = Configure::read('ApacheSecureAuth.ldapFilter');
$result = ldap_search($ldapconn, $ldapdn, $filter, $getLdapUserInfo)
or die("Error in LDAP search query: " . ldap_error($ldapconn));
@ -90,7 +90,7 @@ class ApacheAuthenticate extends BaseAuthenticate {
);
$org_id = $firstOrg['Organisation']['id'];
}
// create user
$userData = array('User' => array(
'email' => $mispUsername,

View File

@ -70,7 +70,7 @@ class BlackListComponent extends Component {
}
}
}
public function edit($rest = false, $id) {
if (strlen($id) == 36) {
$blockEntry = $this->controller->{$this->controller->defaultModel}->find('first', array('conditions' => array('uuid' => $id)));
@ -126,7 +126,7 @@ class BlackListComponent extends Component {
if (!$this->controller->request->is('post') && !$rest) {
throw new MethodNotAllowedException();
}
$this->controller->{$this->controller->defaultModel}->id = $id;
if (!$this->controller->{$this->controller->defaultModel}->exists()) {
throw new NotFoundException(__('Invalid blacklist entry'));
@ -149,7 +149,7 @@ class BlackListComponent extends Component {
public function startup(Controller $controller) {
$this->controller = $controller;
}
public function __construct(ComponentCollection $collection, $settings = array()) {
$this->settings = Set::merge($this->settings, $settings);
parent::__construct($collection, $this->settings);

View File

@ -1,14 +1,14 @@
<?php
class IOCImportComponent extends Component {
// rework of handling composite attributes
// each entry is only triggered if an "AND" branch contains the exact list of parsed attribute types that are set in the components field
// Note that some indicators are not immediately discarded by the parser even if they cannot be turned into an attribute
// The reason for this is that they might not be convertable to an attribute, but they might be converted into a part of a composite attribute
// For example: There is no Registry value type in MISP, but there is a regkey|value type. Meaning that a Registry value can be turned into an attribute
// as long as a registry key is "AND"ed with the value in the OpenIOC file.
// notes about the format for the composition:
// - components have to be in alphabetical order
// - returnFormat has to be a valid MISP type
@ -96,7 +96,7 @@ class IOCImportComponent extends Component {
'filename|sha256' => true,
'regkey|value' => true,
);
// Set up the data that you would like to fetch from the ioc's root and add as comments.
private $iocinfo = array('info', 'uuid', 'date', 'long_info');
@ -123,7 +123,7 @@ class IOCImportComponent extends Component {
// stores the graph that will be passed back along with the event and attributes
private $graph = array();
private $filename = "";
public function readXML($data, $id, $dist, $filename) {
@ -587,7 +587,7 @@ class IOCImportComponent extends Component {
$values[] = $temp['value'];
$uuids[] = $temp['uuid'];
}
foreach ($this->attributeComposition as $composition) {
if (count($composition['components']) != count($att)) continue;
if ($keys === $composition['components']) {

View File

@ -28,7 +28,7 @@ class EventBlacklistsController extends AppController {
public function add() {
$this->BlackList->add($this->_isRest());
}
public function edit($id) {
$this->BlackList->edit($this->_isRest(), $id);
}

View File

@ -83,7 +83,7 @@ class EventDelegationsController extends AppController {
$this->render('ajax/delegate_event');
}
}
public function acceptDelegation($id) {
$delegation = $this->EventDelegation->find('first', array(
'conditions' => array('EventDelegation.id' => $id),
@ -128,7 +128,7 @@ class EventDelegationsController extends AppController {
$this->render('ajax/accept_delegation');
}
}
public function deleteDelegation($id) {
$delegation = $this->EventDelegation->find('first', array(
'conditions' => array('EventDelegation.id' => $id),
@ -145,6 +145,6 @@ class EventDelegationsController extends AppController {
$this->render('ajax/delete_delegation');
}
}
}

View File

@ -36,7 +36,7 @@ class EventsController extends AppController {
);
public $helpers = array('Js' => array('Jquery'));
public $paginationFunctions = array('index', 'proposalEventIndex');
public function beforeFilter() {
@ -107,7 +107,7 @@ class EventsController extends AppController {
$this->paginate = Set::merge($this->paginate,array('conditions' => $conditions));
}
}
private function __filterOnAttributeValue($value) {
// dissect the value
$pieces = explode('|', $value);
@ -135,13 +135,13 @@ class EventsController extends AppController {
}
$includeQuery['conditions']['AND'][] = array('Attribute.deleted' => false);
$includeHits = $this->Event->Attribute->find('all', $includeQuery);
// convert it into an array that uses the event ID as a key
foreach ($includeHits as $iH) {
$includeIDs[$iH['Attribute']['event_id']][] = array('attribute_id' => $iH['Attribute']['id'], 'distribution' => $iH['Attribute']['distribution']);
}
}
if (!empty($exclude)) {
// get all of the attributes that should be excluded
$excludeQuery = array(
@ -155,7 +155,7 @@ class EventsController extends AppController {
}
$excludeQuery['conditions']['AND'][] = array('Attribute.deleted' => false);
$excludeHits = $this->Event->Attribute->find('all', $excludeQuery);
// convert it into an array that uses the event ID as a key
foreach ($excludeHits as $eH) {
$excludeIDs[$eH['Attribute']['event_id']][] = array('attribute_id' => $eH['Attribute']['id'], 'distribution' => $eH['Attribute']['distribution']);
@ -169,7 +169,7 @@ class EventsController extends AppController {
}
return array($includeIDs, $excludeIDs);
}
private function __quickFilter($value) {
$result = array();
// get all of the attributes that have a hit on the search term, in either the value or the comment field
@ -193,18 +193,18 @@ class EventsController extends AppController {
foreach ($attributeHits as $aH) {
$eventsWithAttributeHits[$aH['Attribute']['event_id']][] = $aH['Attribute'];
}
// Using the keys from the previously obtained ordered array, let's fetch all of the events involved
$events = $this->Event->find('all', array(
'recursive' => -1,
'fields' => array('id', 'distribution', 'org_id'),
'conditions' => array('id' => array_keys($eventsWithAttributeHits)),
));
foreach ($events as $event) {
$result[] = $event['Event']['id'];
}
// we now have a list of event IDs that match on an attribute level, and the user can see it. Let's also find all of the events that match on other criteria!
// What is interesting here is that we no longer have to worry about the event's releasability. With attributes this was a different case,
// because we might run into a situation where a user can see an event but not a specific attribute
@ -372,14 +372,14 @@ class EventsController extends AppController {
'fields' => array('id', 'name'),
'recursive' => -1,
));
if (empty($tagName)) {
if ($filterString != "") $filterString .= "|";
$filterString .= '!' . $piece;
continue;
}
$block = $this->Event->EventTag->find('all', array(
'conditions' => array('EventTag.tag_id' => $tagName['Tag']['id']),
'fields' => 'event_id',
@ -397,13 +397,13 @@ class EventsController extends AppController {
} else {
$conditions = array('OR' => array('Tag.name' => $piece));
}
$tagName = $this->Event->EventTag->Tag->find('first', array(
'conditions' => $conditions,
'fields' => array('id', 'name'),
'recursive' => -1,
));
if (empty($tagName)) {
if ($filterString != "") $filterString .= "|";
$filterString .= $piece;
@ -452,7 +452,7 @@ class EventsController extends AppController {
if (!empty($users)) $test['OR'][] = array('Event.user_id' => array_keys($users));
}
}
if (!empty($test)) $this->paginate['conditions']['AND'][] = $test;
break;
case 'distribution' :
@ -552,7 +552,7 @@ class EventsController extends AppController {
if (Configure::read('MISP.showCorrelationsOnIndex')) $this->Event->attachCorrelationCountToEvents($this->Auth->user(), $events);
$this->set('events', $events);
}
if (!$this->Event->User->getPGP($this->Auth->user('id')) && Configure::read('GnuPG.onlyencrypted')) {
// No GPG
if (Configure::read('SMIME.enabled') && !$this->Event->User->getCertificate($this->Auth->user('id'))) {
@ -576,10 +576,10 @@ class EventsController extends AppController {
$this->set('shortDist', $this->Event->shortDist);
$this->set('ajax', $this->request->is('ajax'));
}
public function filterEventIndex() {
$passedArgsArray = array();
$filtering = array(
'published' => 2,
'org' => array('OR' => array(), 'NOT' => array()),
@ -592,7 +592,7 @@ class EventsController extends AppController {
'analysis' => array('OR' => array(), 'NOT' => array()),
'attribute' => array('OR' => array(), 'NOT' => array()),
);
if ($this->_isSiteAdmin()) $filtering['email'] = array('OR' => array(), 'NOT' => array());
foreach ($this->passedArgs as $k => $v) {
@ -667,7 +667,7 @@ class EventsController extends AppController {
$this->set('baseurl', Configure::read('MISP.baseurl'));
$this->layout = 'ajax';
}
public function viewEventAttributes($id, $all = false) {
$conditions = array('eventid' => $id);
if (isset($this->params['named']['deleted']) && $this->params['named']['deleted']) {
@ -706,7 +706,7 @@ class EventsController extends AppController {
$this->set('currentUri', $this->params->here);
$this->render('/Elements/eventattribute');
}
private function __viewUI($event, $continue, $fromEvent) {
// set the data for the contributors / history field
$org_ids = $this->Event->ShadowAttribute->getEventContributors($event['Event']['id']);
@ -737,7 +737,7 @@ class EventsController extends AppController {
$this->__setDeletable($pivot, $event['Event']['id'], true);
$this->set('allPivots', $this->Session->read('pivot_thread'));
$this->set('pivot', $pivot);
// set data for the view, the event is already set in view()
$dataForView = array(
'Attribute' => array('attrDescriptions' => 'fieldDescriptions', 'distributionDescriptions' => 'distributionDescriptions', 'distributionLevels' => 'distributionLevels', 'shortDist' => 'shortDist'),
@ -758,7 +758,7 @@ class EventsController extends AppController {
}
}
}
foreach ($dataForView as $m => $variables) {
if ($m === 'Event') {
$currentModel = $this->Event;
@ -797,7 +797,7 @@ class EventsController extends AppController {
'recursive' => -1,
'contain' => array('Org', 'RequesterOrg'))));
}
if (Configure::read('Plugin.Enrichment_services_enable')) {
$this->loadModel('Server');
$modules = $this->Server->getEnabledModules();
@ -806,7 +806,7 @@ class EventsController extends AppController {
$this->set('contributors', $contributors);
$this->set('typeGroups', array_keys($this->Event->Attribute->typeGroupings));
}
/**
* view method
*
@ -823,12 +823,12 @@ class EventsController extends AppController {
if ($temp == null) throw new NotFoundException('Invalid event');
$id = $temp['Event']['id'];
}
$this->Event->id = $id;
if(!$this->Event->exists()) {
throw new NotFoundException(__('Invalid event.'));
}
$conditions = array('eventid' => $id);
if (!$this->_isRest()) {
$conditions['includeAllTags'] = true;
@ -847,7 +847,7 @@ class EventsController extends AppController {
$this->set('deleted', isset($this->params['named']['deleted']) && $this->params['named']['deleted']);
if (!$this->_isRest()) $this->__viewUI($event, $continue, $fromEvent);
}
private function __startPivoting($id, $info, $date){
$this->Session->write('pivot_thread', null);
$initial_pivot = array('id' => $id, 'info' => $info, 'date' => $date, 'depth' => 0, 'height' => 0, 'children' => array(), 'deletable' => true);
@ -958,10 +958,10 @@ class EventsController extends AppController {
$sgs = $this->Event->SharingGroup->fetchAllAuthorised($this->Auth->user(), 'name', 1);
if ($this->request->is('post')) {
if ($this->_isRest()) {
// rearrange the response if the event came from an export
if(isset($this->request->data['response'])) $this->request->data = $this->request->data['response'];
// Distribution, reporter for the events pushed will be the owner of the authentication key
$this->request->data['Event']['user_id'] = $this->Auth->user('id');
}
@ -1049,7 +1049,7 @@ class EventsController extends AppController {
}
$this->request->data['Event']['date'] = date('Y-m-d');
// combobox for distribution
$distributions = array_keys($this->Event->distributionDescriptions);
$distributions = $this->_arrayToValuesIndexArray($distributions);
@ -1232,11 +1232,11 @@ class EventsController extends AppController {
// even if the SG is not local, we still want the option to select the currently assigned SG
$sgs = $this->Event->SharingGroup->fetchAllAuthorised($this->Auth->user(), 'name', 1);
$this->set('sharingGroups', $sgs);
$distributionLevels = $this->Event->distributionLevels;
if (empty($sgs)) unset ($distributionLevels[4]);
$this->set('distributionLevels', $distributionLevels);
// combobox for types
$threat_levels = $this->Event->ThreatLevel->find('all');
$this->set('threatLevels', Set::combine($threat_levels, '{n}.ThreatLevel.id', '{n}.ThreatLevel.name'));
@ -1276,7 +1276,7 @@ class EventsController extends AppController {
// find the uuid
$result = $this->Event->findById($id);
$this->Event->read();
if (!$this->_isSiteAdmin()) {
if ($this->Event->data['Event']['orgc_id'] != $this->_checkOrg() || !$this->userRole['perm_modify']) {
throw new MethodNotAllowedException();
@ -1289,7 +1289,7 @@ class EventsController extends AppController {
} else {
// delete the event from remote servers
$this->Session->setFlash(__('Event deleted'));
// if coming from index, redirect to referer (to have the filter working)
// else redirect to index
if (strpos($this->referer(), '/view') !== FALSE) {
@ -1466,7 +1466,7 @@ class EventsController extends AppController {
// Check if the background jobs are enabled - if not, fall back to old export page.
if (Configure::read('MISP.background_jobs')) {
$now = time();
// as a site admin we'll use the ADMIN identifier, not to overwrite the cached files of our own org with a file that includes too much data.
if ($this->_isSiteAdmin()) {
$useOrg = 'ADMIN';
@ -1512,7 +1512,7 @@ class EventsController extends AppController {
$this->Event->export_types[$k]['recommendation'] = 1;
}
}
$this->Event->export_types[$k]['lastModified'] = $lastModified;
if (!empty($job)) {
$this->Event->export_types[$k]['job_id'] = $job['Job']['id'];
@ -1544,7 +1544,7 @@ class EventsController extends AppController {
$path = 'tmp/cached_exports/' . $type . DS . 'misp.' . strtolower($this->Event->export_types[$type]['type']) . $extra . '.' . $org . $this->Event->export_types[$type]['extension'];
$this->response->file($path, array('download' => true));
}
private function __timeDifference($now, $then) {
$periods = array("second", "minute", "hour", "day", "week", "month", "year");
$lengths = array("60","60","24","7","4.35","12");
@ -1563,7 +1563,7 @@ class EventsController extends AppController {
App::uses('XMLConverterTool', 'Tools');
$converter = new XMLConverterTool();
$this->loadModel('Whitelist');
// request handler for POSTed queries. If the request is a post, the parameters (apart from the key) will be ignored and replaced by the terms defined in the posted xml object.
// The correct format for a posted xml is a "request" root element, as shown by the examples below:
// For XML: <request><value>7.7.7.7&amp;&amp;1.1.1.1</value><type>ip-src</type></request>
@ -1582,7 +1582,7 @@ class EventsController extends AppController {
}
}
}
$simpleFalse = array('tags', 'eventid', 'withAttachment', 'from', 'to', 'last');
foreach ($simpleFalse as $sF) {
if (!is_array(${$sF}) && (${$sF} === 'null' || ${$sF} == '0' || ${$sF} === false || strtolower(${$sF}) === 'false')) {
@ -1594,12 +1594,12 @@ class EventsController extends AppController {
if ($tags) $tags = str_replace(';', ':', $tags);
if ($last) $last = $this->Event->resolveTimeDelta($last);
$eventIdArray = array();
if ($eventid) {
if (!is_numeric($eventid)) throw new MethodNotAllowedException('Invalid Event ID.');
$eventIdArray[] = $eventid;
}
if ($key != 'download') {
// check if the key is valid -> search for users based on key
$user = $this->checkAuthUser($key);
@ -1612,7 +1612,7 @@ class EventsController extends AppController {
}
$user = $this->Auth->user();
}
if ($eventid) {
$final_filename='misp.event' . $eventid . '.export.xml';
} else {
@ -1663,7 +1663,7 @@ class EventsController extends AppController {
${$sF} = false;
}
}
if ($from) $from = $this->Event->dateFieldCheck($from);
if ($to) $to = $this->Event->dateFieldCheck($to);
if ($tags) $tags = str_replace(';', ':', $tags);
@ -1729,7 +1729,7 @@ class EventsController extends AppController {
$rules = $this->Attribute->hids($this->Auth->user(), $type, $tags, $from, $to, $last);
$this->set('rules', $rules);
}
// csv function
// Usage: csv($key, $eventid) - key can be a valid auth key or the string 'download'. Download requires the user to be logged in interactively and will generate a .csv file
// $eventid can be one of 3 options: left empty it will get all the visible to_ids attributes,
@ -1915,7 +1915,7 @@ class EventsController extends AppController {
// we've already stored these elsewhere, unset them so we can extract the event related data
unset($event['Attribute']);
unset($event['Fails']);
// add the original openIOC file as an attachment
$saveEvent['Attribute'][] = array(
'category' => 'External analysis',
@ -2008,7 +2008,7 @@ class EventsController extends AppController {
$this->loadModel('Attribute');
$this->Event->recursive = -1;
$this->Event->read(array('id', 'uuid', 'distribution'), $id);
// import XML class
App::uses('Xml', 'Utility');
// now parse it
@ -2025,7 +2025,7 @@ class EventsController extends AppController {
} else {
// TODO: need a default value for $dist or throw an exception
}
// Payload delivery -- malware-sample
$results = $parsedXml->xpath('/analysis');
foreach ($results as $result) {
@ -2038,7 +2038,7 @@ class EventsController extends AppController {
$rootDir = APP . "files" . DS . $id . DS;
$malware = $rootDir . DS . 'sample';
$this->Event->Attribute->uploadAttachment($malware, $realFileName, true, $id, null, '', $this->Event->data['Event']['uuid'] . '-sample', $dist, true);
// Network activity -- .pcap
$realFileName = 'analysis.pcap';
$rootDir = APP . "files" . DS . $id . DS;
@ -2249,7 +2249,7 @@ class EventsController extends AppController {
${$sF} = false;
}
}
if ($from) $from = $this->Event->dateFieldCheck($from);
if ($to) $to = $this->Event->dateFieldCheck($to);
if ($tags) $tags = str_replace(';', ':', $tags);
@ -2419,7 +2419,7 @@ class EventsController extends AppController {
$final = $this->IOCExport->buildAll($this->Auth->user(), $event);
$this->set('final', $final);
}
public function create_dummy_event() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException('You don\'t have the privileges to access this.');
$data['Event']['info'] = 'Test event showing every category-type combination';
@ -2485,7 +2485,7 @@ class EventsController extends AppController {
}
$this->Event->_add($data, false, $this->Auth->user());
}
// for load testing, it's slow, execution time is set at 1 hour maximum
public function create_massive_dummy_events() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException('You don\'t have the privileges to access this.');
@ -2531,7 +2531,7 @@ class EventsController extends AppController {
$this->Event->saveAssociated($data, array('validate' => false));
}
}
public function proposalEventIndex() {
$this->loadModel('ShadowAttribute');
$this->ShadowAttribute->recursive = -1;
@ -2581,7 +2581,7 @@ class EventsController extends AppController {
$this->set('analysisLevels', $this->Event->analysisLevels);
$this->set('distributionLevels', $this->Event->distributionLevels);
}
public function reportValidationIssuesEvents() {
// search for validation problems in the events
if (!self::_isSiteAdmin()) throw new NotFoundException();
@ -2591,7 +2591,7 @@ class EventsController extends AppController {
$this->set('result', $result);
$this->set('count', $count);
}
public function addTag($id = false, $tag_id = false) {
if (!$this->request->is('post')) {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'You don\'t have permission to do that.')), 'status'=>200));
@ -2614,7 +2614,7 @@ class EventsController extends AppController {
}
$this->Event->recurisve = -1;
$event = $this->Event->read(array('id', 'org_id', 'orgc_id', 'distribution', 'sharing_group_id'), $id);
if (!$this->_isSiteAdmin() && !$this->userRole['perm_sync']) {
if (!$this->userRole['perm_tagger'] || ($this->Auth->user('org_id') !== $event['Event']['org_id'] && $this->Auth->user('org_id') !== $event['Event']['orgc_id'])) {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'You don\'t have permission to do that.')), 'status'=>200));
@ -2642,7 +2642,7 @@ class EventsController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Tag could not be added.')),'status'=>200));
}
}
public function removeTag($id = false, $tag_id = false) {
if (!$this->request->is('post')) {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'You don\'t have permission to do that. Only POST requests are accepted.')), 'status'=>200));
@ -2685,7 +2685,7 @@ class EventsController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Tag could not be removed.')),'status'=>200));
}
}
public function freeTextImport($id) {
if (!$this->userRole['perm_add']) {
throw new MethodNotAllowedException('Event not found or you don\'t have permissions to create attributes');
@ -2700,7 +2700,7 @@ class EventsController extends AppController {
$this->layout = 'ajax';
$this->request->data['Attribute']['event_id'] = $id;
}
if ($this->request->is('post')) {
App::uses('ComplexTypeTool', 'Tools');
$complexTypeTool = new ComplexTypeTool();
@ -2712,7 +2712,7 @@ class EventsController extends AppController {
}
$r['types'] = $temp;
}
// remove all duplicates
foreach ($resultArray as $k => $v) {
for ($i = 0; $i < $k; $i++) {
@ -2744,7 +2744,7 @@ class EventsController extends AppController {
$this->render('resolved_attributes');
}
}
public function saveFreeText($id) {
if (!$this->userRole['perm_add']) {
throw new MethodNotAllowedException('Event not found or you don\'t have permissions to create attributes');
@ -2825,7 +2825,7 @@ class EventsController extends AppController {
throw new MethodNotAllowedException();
}
}
public function stix($key, $id = false, $withAttachments = false, $tags = false, $from = false, $to = false, $last = false) {
if ($key != 'download') {
// check if the key is valid -> search for users based on key
@ -2838,7 +2838,7 @@ class EventsController extends AppController {
throw new UnauthorizedException('You have to be logged in to do that.');
}
}
// request handler for POSTed queries. If the request is a post, the parameters (apart from the key) will be ignored and replaced by the terms defined in the posted xml object.
// The correct format for a posted xml is a "request" root element, as shown by the examples below:
// For XML: <request><id>!3&amp;!4</id><tags>OSINT</tags></request>
@ -2855,7 +2855,7 @@ class EventsController extends AppController {
else ${$p} = null;
}
}
$simpleFalse = array('id', 'withAttachments', 'tags', 'from', 'to', 'last');
foreach ($simpleFalse as $sF) {
if (!is_array(${$sF}) && (${$sF} === 'null' || ${$sF} == '0' || ${$sF} === false || strtolower(${$sF}) === 'false')) {
@ -2865,7 +2865,7 @@ class EventsController extends AppController {
if ($from) $from = $this->Event->dateFieldCheck($from);
if ($to) $to = $this->Event->dateFieldCheck($to);
if ($last) $last = $this->Event->resolveTimeDelta($last);
// set null if a null string is passed
$numeric = false;
if (is_numeric($id)) $numeric = true;
@ -2917,7 +2917,7 @@ class EventsController extends AppController {
$this->set('result', array_keys($incomingEvents));
}
}
public function checkuuid($uuid) {
if (!$this->userRole['perm_sync']) throw new MethodNotAllowedException('You do not have the permission to do that.');
$events = $this->Event->find('first', array(
@ -2927,7 +2927,7 @@ class EventsController extends AppController {
));
$this->set('result', array('result' => empty($events)));
}
public function pushProposals($uuid) {
$message= "";
$success = true;
@ -2988,7 +2988,7 @@ class EventsController extends AppController {
$this->set('_serialize', 'data');
}
}
public function exportChoice($id) {
if (!is_numeric($id)) throw new MethodNotAllowedException('Invalid ID');
$event = $this->Event->fetchEvent($this->Auth->user(), array('eventid' => $id));
@ -3085,7 +3085,7 @@ class EventsController extends AppController {
$this->set('id', $id);
$this->render('ajax/exportChoice');
}
// API for pushing samples to MISP
// Either send it to an existing event, or let MISP create a new one automatically
public function upload_sample($event_id = null) {
@ -3117,9 +3117,9 @@ class EventsController extends AppController {
} else {
throw new BadRequestException('Please POST the samples as described on the automation page.');
}
if (isset($data['request'])) $data = $data['request'];
foreach ($parameter_options as $k => $v) {
if (isset($data[$k])) {
if (isset($v['valid_options']) && !in_array($data[$k], $v['valid_options'])) {
@ -3129,7 +3129,7 @@ class EventsController extends AppController {
$data[$k] = $v['default'];
}
}
if (isset($data['files'])) {
foreach ($data['files'] as $k => $file) {
if (!isset($file['filename']) || !isset($file['data'])) {
@ -3139,7 +3139,7 @@ class EventsController extends AppController {
}
}
}
if (empty($data['files'])) {
throw new BadRequestException('No samples received, or samples not in the correct format. Please refer to the API documentation on the automation page.');
}
@ -3148,7 +3148,7 @@ class EventsController extends AppController {
$this->Event->id = $data['event_id'];
if(!$this->Event->exists()) throw new NotFoundException('Event not found');
}
// check if the user has permission to create attributes for an event, if the event ID has been passed
// If not, create an event
if (isset($data['event_id']) && !empty($data['event_id']) && is_numeric($data['event_id'])) {
@ -3289,14 +3289,14 @@ class EventsController extends AppController {
$this->view($data['event_id']);
$this->render('view');
}
public function viewGraph($id) {
$event = $this->Event->fetchEvent($this->Auth->user(), array('eventid' => $id));
if (empty($event)) throw new MethodNotAllowedException('Invalid Event.');
$this->set('event', $event[0]);
$this->set('id', $id);
}
public function updateGraph($id) {
if ($this->request->is('post')) {
$json = $this->__buildGraphJson($id, $this->request->data);
@ -3306,7 +3306,7 @@ class EventsController extends AppController {
$this->set('json', $json);
$this->set('_serialize', 'json');
}
private function __buildGraphJson($id, $json = array()) {
$event = $this->Event->fetchEvent($this->Auth->user(), array('eventid' => $id));
if (empty($event)) return $json;
@ -3392,7 +3392,7 @@ class EventsController extends AppController {
}
return $json;
}
private function __cleanLinks($json) {
if (isset($json['nodes']) && isset($json['links'])) {
$links = array();
@ -3408,14 +3408,14 @@ class EventsController extends AppController {
}
return $json;
}
private function __orgImgExists($org) {
if (file_exists(APP . 'webroot' . DS . 'img' . DS . 'orgs' . DS . $org . '.png')) {
return true;
}
return false;
}
private function __graphJsonContains($type, $att, $json) {
if (!isset($json['nodes'])) return false;
foreach ($json['nodes'] as $k => $node) {
@ -3437,7 +3437,7 @@ class EventsController extends AppController {
}
return false;
}
public function delegation_index() {
$this->loadModel('EventDelegation');
$delegatedEvents = $this->EventDelegation->find('list', array(
@ -3462,7 +3462,7 @@ class EventsController extends AppController {
'Orgc' => array('fields' => array('id', 'name')),
'SharingGroup' => array('fields' => array('id', 'name')),
'ThreatLevel' => array('fields' => array('ThreatLevel.name'))
),
'conditions' => array('Event.id' => $delegatedEvents),
);
@ -3473,7 +3473,7 @@ class EventsController extends AppController {
$this->set('eventDescriptions', $this->Event->fieldDescriptions);
$this->set('analysisLevels', $this->Event->analysisLevels);
$this->set('distributionLevels', $this->Event->distributionLevels);
$shortDist = array(0 => 'Organisation', 1 => 'Community', 2 => 'Connected', 3 => 'All', 4 => ' sharing Group');
$this->set('shortDist', $shortDist);
$this->set('ajax', false);
@ -3487,7 +3487,7 @@ class EventsController extends AppController {
$this->set('tags', $tagNames);
$this->render('index');
}
// expects an attribute ID and the module to be used
public function queryEnrichment($attribute_id, $module = false) {
if (!Configure::read('Plugin.Enrichment_services_enable')) throw new MethodNotAllowedException('Enrichment services are not enabled.');
@ -3582,7 +3582,7 @@ class EventsController extends AppController {
if (isset($r['data'])) $temp['data'] = $r['data'];
$resultArray[] = $temp;
}
}
$resultArray = array_merge($resultArray, $freetextResults);
}

View File

@ -15,7 +15,7 @@ class FavouriteTagsController extends AppController {
'FavouriteTag.id' => 'DESC'
),
);
public function toggle() {
if (!$this->request->is('post')) throw new MethodNotAllowedException('This action is only available via POST requests.');
if (!is_numeric($this->request->data['FavouriteTag']['data'])) throw new MethodNotAllowedException('Invalid tag ID.');
@ -38,7 +38,7 @@ class FavouriteTagsController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'fails' => $message . ' has failed.')), 'status'=>200));
}
}
public function getToggleField() {
if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This action is available via AJAX only.');
$this->layout = 'ajax';

View File

@ -37,11 +37,11 @@ class FeedsController extends AppController {
$this->loadModel('Event');
$this->set('distributionLevels', $this->Event->distributionLevels);
}
public function view($feedId) {
$feed = $this->Feed->find('first', array('conditions' => array('Feed.id' => $feedId)));
}
public function add() {
if ($this->request->is('post')) {
if (isset($this->request->data['Feed']['pull_rules'])) $this->request->data['Feed']['rules'] = $this->request->data['Feed']['pull_rules'];
@ -65,7 +65,7 @@ class FeedsController extends AppController {
$this->set('tags', $tags);
}
}
public function edit($feedId) {
$this->Feed->id = $feedId;
if (!$this->Feed->exists()) throw new NotFoundException('Invalid feed.');
@ -97,7 +97,7 @@ class FeedsController extends AppController {
$this->set('tags', $tags);
}
}
public function delete($feedId) {
if (!$this->request->is('post')) throw new MethodNotAllowedException('This action requires a post request.');
$this->Feed->id = $feedId;
@ -106,7 +106,7 @@ class FeedsController extends AppController {
else $this->Session->setFlash('Feed could not be deleted.');
$this->redirect(array('controller' => 'feeds', 'action' => 'index'));
}
public function fetchFromFeed($feedId) {
$this->Feed->id = $feedId;
if (!$this->Feed->exists()) throw new NotFoundException('Invalid feed.');
@ -145,7 +145,7 @@ class FeedsController extends AppController {
$this->Session->setFlash($message);
$this->redirect(array('action' => 'index'));
}
public function getEvent($feedId, $eventUuid, $all = false) {
$this->Feed->id = $feedId;
if (!$this->Feed->exists()) throw new NotFoundException('Invalid feed.');
@ -169,7 +169,7 @@ class FeedsController extends AppController {
$this->Session->setFlash($message);
$this->redirect(array('action' => 'previewIndex', $feedId));
}
public function previewIndex($feedId) {
$this->Feed->id = $feedId;
if (!$this->Feed->exists()) throw new NotFoundException('Invalid feed.');
@ -177,7 +177,7 @@ class FeedsController extends AppController {
else $currentPage = 1;
$urlparams = '';
$passedArgs = array();
App::uses('SyncTool', 'Tools');
$syncTool = new SyncTool();
$this->Feed->read();
@ -191,7 +191,7 @@ class FeedsController extends AppController {
$this->params->params['paging'] = array($this->modelClass => $params);
if (is_array($events)) $customPagination->truncateByPagination($events, $params);
else ($events = array());
$this->set('events', $events);
$this->loadModel('Event');
$threat_levels = $this->Event->ThreatLevel->find('all');
@ -207,7 +207,7 @@ class FeedsController extends AppController {
$this->set('passedArgs', json_encode($passedArgs));
$this->set('passedArgsArray', $passedArgs);
}
public function previewEvent($feedId, $eventUuid, $all = false) {
$this->Feed->id = $feedId;
@ -239,7 +239,7 @@ class FeedsController extends AppController {
else throw new NotFoundException('Could not download the selected Event');
}
}
public function enable($id) {
$result = $this->__toggleEnable($id, true);
$this->set('name', $result['message']);
@ -252,7 +252,7 @@ class FeedsController extends AppController {
$this->set('_serialize', array('name', 'message', 'url', 'errors'));
}
}
public function disable($id) {
$result = $this->__toggleEnable($id, false);
$this->set('name', $result['message']);
@ -265,7 +265,7 @@ class FeedsController extends AppController {
$this->set('_serialize', array('name', 'message', 'url', 'errors'));
}
}
private function __toggleEnable($id, $enable = true) {
if (!is_numeric($id)) throw new MethodNotAllowedException('Invalid Feed.');
$this->Feed->id = $id;

View File

@ -9,18 +9,18 @@ App::uses('AppController', 'Controller');
*/
class JobsController extends AppController {
public $components = array('Security' ,'RequestHandler', 'Session');
public $paginate = array(
'limit' => 20,
'order' => array(
'Job.id' => 'desc'
),
);
public function beforeFilter() {
parent::beforeFilter();
}
public function index($queue = false) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if (!Configure::read('MISP.background_jobs')) throw new NotFoundException('Background jobs are not enabled on this instance.');
@ -38,7 +38,7 @@ class JobsController extends AppController {
$this->set('list', $jobs);
$this->set('queue', $queue);
}
private function __jobStatusConverter($status) {
switch ($status) {
case 1:
@ -55,7 +55,7 @@ class JobsController extends AppController {
break;
}
}
public function getGenerateCorrelationProgress($id) {
if (!self::_isSiteAdmin()) throw new NotFoundException();
$progress = $this->Job->findById($id);
@ -66,7 +66,7 @@ class JobsController extends AppController {
}
return new CakeResponse(array('body' => json_encode($progress)));
}
public function getProgress($type) {
$org = $this->Auth->user('Organisation')['name'];
if ($this->_isSiteAdmin()) $org = 'ADMIN';
@ -85,7 +85,7 @@ class JobsController extends AppController {
}
return new CakeResponse(array('body' => json_encode($progress)));
}
public function cache($type) {
if ($this->_isSiteAdmin()) {
$target = 'All events.';

View File

@ -85,14 +85,14 @@ class LogsController extends AppController {
}
$this->set('published', $this->Event->data['Event']['published']);
if ($mineOrAdmin && $this->userRole['perm_modify']) $mayModify = true;
$conditions['OR'][] = array('AND' => array('Log.model LIKE' => 'Event', 'Log.model_id LIKE' => $id));
if ($org) $conditions['AND'][] = array('Log.org LIKE' => $org, 'Log.model LIKE' => 'ShadowAttribute');
// if we are not the owners of the event and we aren't site admins, then we should only see the entries for attributes that are not private
// This means that we will not be able to see deleted attributes - since those could have been private
if (!$mayModify) {
$sgs = $this->Event->SharingGroup->fetchAllAuthorised($this->Auth->user());
// get a list of the attributes that belong to the event
$this->loadModel('Attribute');
$this->Attribute->recursive = -1;
@ -149,7 +149,7 @@ class LogsController extends AppController {
// reset the paginate_conditions
$this->Session->write('paginate_conditions_log', array());
if ($this->request->is('post')) { // FIXME remove this crap check
$filters['email'] = $this->request->data['Log']['email'];
if (!$orgRestriction) {
$filters['org'] = $this->request->data['Log']['org'];
@ -207,7 +207,7 @@ class LogsController extends AppController {
$filters['title'] = $this->Session->read('paginate_conditions_log_title');
$filters['change'] = $this->Session->read('paginate_conditions_log_change');
if (Configure::read('MISP.log_client_ip')) $filters['ip'] = $this->Session->read('paginate_conditions_log_ip');
// for info on what was searched for
$this->set('emailSearch', $filters['email']);
$this->set('orgSearch', $filters['org']);
@ -218,7 +218,7 @@ class LogsController extends AppController {
$this->set('changeSearch', $filters['change']);
if (Configure::read('MISP.log_client_ip')) $this->set('ipSearch', $filters['ip']);
$this->set('isSearch', 1);
// re-get pagination
$this->{$this->defaultModel}->recursive = 0;
$this->paginate = $this->Session->read('paginate_conditions_log');
@ -226,18 +226,18 @@ class LogsController extends AppController {
$conditions = $this->__buildSearchConditions($filters);
$this->paginate['conditions'] = $conditions;
$this->set('list', $this->paginate());
// set the same view as the index page
$this->render('admin_index');
}
} else {
// no search keyword is given, show the search form
// combobox for actions
$actions = array('' => array('ALL' => 'ALL'), 'actions' => array());
$actions['actions'] = array_merge($actions['actions'], $this->_arrayToValuesIndexArray($this->{$this->defaultModel}->validate['action']['rule'][1]));
$this->set('actions', $actions);
// combobox for models
$models = array('Attribute', 'Event', 'EventBlacklist', 'EventTag', 'Organisation', 'Post', 'Regexp', 'Role', 'Server', 'ShadowAttribute', 'SharingGroup', 'Tag', 'Task', 'Taxonomy', 'Template', 'Thread', 'User', 'Whitelist');
$existing_models = $this->Log->find('list', array(
@ -281,7 +281,7 @@ class LogsController extends AppController {
}
return $conditions;
}
public function returnDates($org = 'all') {
$data = $this->Log->returnDates($org);
$this->set('data', $data);

View File

@ -34,7 +34,7 @@ class NewsController extends AppController {
$this->User->saveField('newsread', time());
$this->set('newsItems', $newsItems);
}
public function add() {
if ($this->request->is('post')) {
$this->News->create();
@ -47,7 +47,7 @@ class NewsController extends AppController {
} else $this->Session->setFlash('The news item could not be added.');
}
}
public function edit($id) {
$this->News->id = $id;
if (!$this->News->exists()) throw new NotFoundException('Invalid news item.');
@ -62,7 +62,7 @@ class NewsController extends AppController {
$this->set('newsItem', $this->request->data);
}
}
public function delete($id) {
if (!$this->request->is('post')) throw new MethodNotAllowedException();
$this->News->id = $id;

View File

@ -28,7 +28,7 @@ class OrgBlacklistsController extends AppController {
public function add() {
$this->BlackList->add($this->_isRest());
}
public function edit($id) {
$this->BlackList->edit($this->_isRest(), $id);
}

View File

@ -204,7 +204,7 @@ class OrganisationsController extends AppController {
}
return new CakeResponse(array('body'=> json_encode($orgs)));
}
public function admin_merge($id) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException('You are not authorised to do that.');
if ($this->request->is('Post')) {

View File

@ -15,7 +15,7 @@ class PostsController extends AppController {
);
public $helpers = array('Js' => array('Jquery'));
public $paginate = array(
'limit' => 60,
);
@ -23,7 +23,7 @@ class PostsController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
}
// Find the thread_id and post_id in advance. If a user clicks post comment on the event view, send the event's related thread's ID
// Usage:
// /posts/add : Creates new thread with the added post as the first post. Title set by user
@ -110,7 +110,7 @@ class PostsController extends AppController {
if (empty($thread_id) && empty($target_type)) {
$title = $this->request->data['Post']['title'];
}
if ($target_thread_id == null) {
// We have a post that was posted in a new thread. This could also mean that someone created the first post related to an event!
$this->Thread->create();
@ -176,7 +176,7 @@ class PostsController extends AppController {
}
}
}
public function edit($post_id, $context = 'thread') {
$post = $this->Post->find('first', array('conditions' => array('Post.id' => $post_id), 'recursive' => -1, 'contain' => array('Thread')));
if (empty($post)) throw new NotFoundException(__('Invalid post'));
@ -213,7 +213,7 @@ class PostsController extends AppController {
$this->set('id', $post_id);
$this->set('thread_id', $post['Post']['thread_id']);
}
public function delete($post_id, $context = 'thread') {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
@ -266,4 +266,4 @@ class PostsController extends AppController {
}
}
?>

View File

@ -220,7 +220,7 @@ class RegexpController extends AppController {
$this->Session->setFlash(__('All done! Number of changed attributes: ' . $modifications . ' Number of deletions: ' . count($deletable)));
$this->redirect(array('action' => 'index'));
}
public function cleanRegexModifiers() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();

View File

@ -70,7 +70,7 @@ class ServersController extends AppController {
$this->set('collection', $collection);
}
public function previewIndex($id) {
if (isset($this->passedArgs['pages'])) $currentPage = $this->passedArgs['pages'];
else $currentPage = 1;
@ -104,7 +104,7 @@ class ServersController extends AppController {
$this->set('eventDescriptions', $this->Event->fieldDescriptions);
$this->set('analysisLevels', $this->Event->analysisLevels);
$this->set('distributionLevels', $this->Event->distributionLevels);
$shortDist = array(0 => 'Organisation', 1 => 'Community', 2 => 'Connected', 3 => 'All', 4 => ' sharing Group');
$this->set('shortDist', $shortDist);
$this->set('ajax', $this->request->is('ajax'));
@ -114,7 +114,7 @@ class ServersController extends AppController {
$this->set('passedArgsArray', $passedArgs);
$this->set('server', $server);
}
public function previewEvent($serverId, $eventId, $all = false) {
if (!$this->_isSiteAdmin()) {
throw new MethodNotAllowedException('You are not authorised to do that.');
@ -145,7 +145,7 @@ class ServersController extends AppController {
$threat_levels = $this->Event->ThreatLevel->find('all');
$this->set('threatLevels', Set::combine($threat_levels, '{n}.ThreatLevel.id', '{n}.ThreatLevel.name'));
}
public function filterEventIndex($id) {
if (!$this->_isSiteAdmin()) {
throw new MethodNotAllowedException('You are not authorised to do that.');
@ -172,20 +172,20 @@ class ServersController extends AppController {
if (!$this->_isSiteAdmin()) $this->redirect(array('controller' => 'servers', 'action' => 'index'));
if ($this->request->is('post')) {
$json = json_decode($this->request->data['Server']['json'], true);
$fail = false;
// test the filter fields
if (!empty($this->request->data['Server']['pull_rules']) && !$this->Server->isJson($this->request->data['Server']['pull_rules'])) {
$fail = true;
$this->Session->setFlash(__('The pull filter rules must be in valid JSON format.'));
}
if (!$fail && !empty($this->request->data['Server']['push_rules']) && !$this->Server->isJson($this->request->data['Server']['push_rules'])) {
$fail = true;
$this->Session->setFlash(__('The push filter rules must be in valid JSON format.'));
}
if (!$fail) {
// force check userid and orgname to be from yourself
$this->request->data['Server']['org_id'] = $this->Auth->user('org_id');
@ -200,7 +200,7 @@ class ServersController extends AppController {
$fail = true;
$this->Session->setFlash(__('That organisation could not be created as the uuid is in use already.'));
}
if (!$fail) {
$this->Server->Organisation->create();
if (!$this->Server->Organisation->save(array(
@ -249,12 +249,12 @@ class ServersController extends AppController {
$externalOrganisations[$o['Organisation']['id']] = $o['Organisation']['name'];
$allOrgs[] = array('id' => $o['Organisation']['id'], 'name' => $o['Organisation']['name']);
}
$this->set('organisationOptions', $organisationOptions);
$this->set('localOrganisations', $localOrganisations);
$this->set('externalOrganisations', $externalOrganisations);
$this->set('allOrganisations', $allOrgs);
// list all tags for the rule picker
$this->loadModel('Tag');
$temp = $this->Tag->find('all', array('recursive' => -1));
@ -280,13 +280,13 @@ class ServersController extends AppController {
if ($this->request->is('post') || $this->request->is('put')) {
$json = json_decode($this->request->data['Server']['json'], true);
$fail = false;
// test the filter fields
if (!empty($this->request->data['Server']['pull_rules']) && !$this->Server->isJson($this->request->data['Server']['pull_rules'])) {
$fail = true;
$this->Session->setFlash(__('The pull filter rules must be in valid JSON format.'));
}
if (!$fail && !empty($this->request->data['Server']['push_rules']) && !$this->Server->isJson($this->request->data['Server']['push_rules'])) {
$fail = true;
$this->Session->setFlash(__('The push filter rules must be in valid JSON format.'));
@ -307,7 +307,7 @@ class ServersController extends AppController {
$fail = true;
$this->Session->setFlash(__('That organisation could not be created as the uuid is in use already.'));
}
if (!$fail) {
$this->Server->Organisation->create();
if (!$this->Server->Organisation->save(array(
@ -321,7 +321,7 @@ class ServersController extends AppController {
}
}
}
if (!$fail) {
// Save the data
if ($this->Server->save($this->request->data, true, $fieldList)) {
@ -366,7 +366,7 @@ class ServersController extends AppController {
$oldRemoteSetting = 0;
if (!$this->Server->data['RemoteOrg']['local']) $oldRemoteSetting = 1;
$this->set('oldRemoteSetting', $oldRemoteSetting);
$this->set('oldRemoteOrg', $this->Server->data['RemoteOrg']['id']);
@ -374,7 +374,7 @@ class ServersController extends AppController {
$this->set('localOrganisations', $localOrganisations);
$this->set('externalOrganisations', $externalOrganisations);
$this->set('allOrganisations', $allOrgs);
// list all tags for the rule picker
$this->loadModel('Tag');
$temp = $this->Tag->find('all', array('recursive' => -1));
@ -531,7 +531,7 @@ class ServersController extends AppController {
$this->redirect(array('action' => 'index'));
}
}
private function __saveCert($server, $id, $delete = false) {
if (!$delete) {
$ext = '';
@ -559,7 +559,7 @@ class ServersController extends AppController {
$this->Server->save($s);
}
}
public function serverSettingsReloadSetting($setting, $id) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
$pathToSetting = explode('.', $setting);
@ -579,7 +579,7 @@ class ServersController extends AppController {
$this->layout = false;
$this->render('/Elements/healthElements/settings_row');
}
public function serverSettings($tab=false) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if ($this->request->is('Get')) {
@ -598,7 +598,7 @@ class ServersController extends AppController {
$stixVersion = array(0 => 'Incorrect STIX version installed, found $current, expecting $expected', 1 => 'OK');
$cyboxVersion = array(0 => 'Incorrect CyBox version installed, found $current, expecting $expected', 1 => 'OK');
$sessionErrors = array(0 => 'OK', 1 => 'High', 2 => 'Alternative setting used', 3 => 'Test failed');
$finalSettings = $this->Server->serverSettingsRead();
$issues = array(
'errors' => array(
@ -671,41 +671,41 @@ class ServersController extends AppController {
'recommended' => 50,
'unit' => 'M'
)
);
foreach ($phpSettings as $setting => &$settingArray) {
$settingArray['value'] = ini_get($setting);
if ($settingArray['unit']) $settingArray['value'] = intval(rtrim($settingArray['value'], $settingArray['unit']));
else $settingArray['value'] = intval($settingArray['value']);
}
$this->set('phpSettings', $phpSettings);
if ($version && (!$version['upToDate'] || $version['upToDate'] == 'older')) $diagnostic_errors++;
// check if the STIX and Cybox libraries are working and the correct version using the test script stixtest.py
$stix = $this->Server->stixDiagnostics($diagnostic_errors, $stixVersion, $cyboxVersion);
// if GPG is set up in the settings, try to encrypt a test message
$gpgStatus = $this->Server->gpgDiagnostics($diagnostic_errors);
// if the message queue pub/sub is enabled, check whether the extension works
$zmqStatus = $this->Server->zmqDiagnostics($diagnostic_errors);
// if Proxy is set up in the settings, try to connect to a test URL
$proxyStatus = $this->Server->proxyDiagnostics($diagnostic_errors);
// check the size of the session table
$sessionCount = 0;
$sessionStatus = $this->Server->sessionDiagnostics($diagnostic_errors, $sessionCount);
$this->set('sessionCount', $sessionCount);
$additionalViewVars = array('gpgStatus', 'sessionErrors', 'proxyStatus', 'sessionStatus', 'zmqStatus', 'stixVersion', 'cyboxVersion','gpgErrors', 'proxyErrors', 'zmqErrors', 'stixOperational', 'stix');
}
// check whether the files are writeable
$writeableDirs = $this->Server->writeableDirsDiagnostics($diagnostic_errors);
$writeableFiles = $this->Server->writeableFilesDiagnostics($diagnostic_errors);
$viewVars = array(
'diagnostic_errors', 'tabs', 'tab', 'issues', 'finalSettings', 'writeableErrors', 'writeableDirs', 'writeableFiles'
);
@ -729,7 +729,7 @@ class ServersController extends AppController {
$this->response->download('MISP.report.json');
return $this->response;
}
$priorities = array(0 => 'Critical', 1 => 'Recommended', 2 => 'Optional', 3 => 'Deprecated');
$this->set('priorities', $priorities);
$this->set('workerIssueCount', $workerIssueCount);
@ -748,13 +748,13 @@ class ServersController extends AppController {
else shell_exec($prepend . APP . 'Console' . DS . 'cake ' . DS . 'CakeResque.CakeResque startscheduler -i 5 > /dev/null 2>&1 &');
$this->redirect('/servers/serverSettings/workers');
}
public function stopWorker($pid) {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->Server->killWorker($pid, $this->Auth->user());
$this->redirect('/servers/serverSettings/workers');
}
private function __checkVersion() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('SyncTool', 'Tools');
@ -768,7 +768,7 @@ class ServersController extends AppController {
}
if ($response->isOK() && !empty($tags)) {
$json_decoded_tags = json_decode($tags);
// find the latest version tag in the v[major].[minor].[hotfix] format
for ($i = 0; $i < count($json_decoded_tags); $i++) {
if (preg_match('/^v[0-9]+\.[0-9]+\.[0-9]+$/', $json_decoded_tags[$i]->name)) break;
@ -838,7 +838,7 @@ class ServersController extends AppController {
));
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'app/Config.config.php is not writeable to the apache user.')),'status'=>200));
}
if (isset($found['beforeHook'])) {
$beforeResult = call_user_func_array(array($this->Server, $found['beforeHook']), array($setting, $this->request->data['Server']['value']));
if ($beforeResult !== true) {
@ -903,7 +903,7 @@ class ServersController extends AppController {
}
}
}
public function restartWorkers() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->Server->workerRemoveDead($this->Auth->user());
@ -917,13 +917,13 @@ class ServersController extends AppController {
shell_exec($prepend . APP . 'Console' . DS . 'worker' . DS . 'start.sh > /dev/null 2>&1 &');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'workers'));
}
private function __manageFiles() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
$files = $this->Server->grabFiles();
return $files;
}
public function deleteFile($type, $filename) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if ($this->request->is('post')) {
@ -944,11 +944,11 @@ class ServersController extends AppController {
throw new MethodNotAllowedException('This action expects a POST request.');
}
}
public function uploadFile($type) {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$validItems = $this->Server->getFileRules();
// Check if there were problems with the file upload
// only keep the last part of the filename, this should prevent directory attacks
$filename = basename($this->request->data['Server']['file']['name']);
@ -960,7 +960,7 @@ class ServersController extends AppController {
$this->Session->setFlash(__('Upload failed.', true), 'default', array(), 'error');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
// check if the file already exists
App::uses('File', 'Utility');
$existingFile = new File($validItems[$type]['path'] . DS . $filename);
@ -968,7 +968,7 @@ class ServersController extends AppController {
$this->Session->setFlash(__('File already exists. If you would like to replace it, remove the old one first.', true), 'default', array(), 'error');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
$result = move_uploaded_file($this->request->data['Server']['file']['tmp_name'], $validItems[$type]['path'] . DS . $filename);
if ($result) {
$this->Session->setFlash('File uploaded.');
@ -977,7 +977,7 @@ class ServersController extends AppController {
}
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
public function fetchServersForSG($idList = '{}') {
$id_exclusion_list = json_decode($idList, true);
$temp = $this->Server->find('all', array(
@ -996,7 +996,7 @@ class ServersController extends AppController {
$this->set('servers', $servers);
$this->render('ajax/fetch_servers_for_sg');
}
public function testConnection($id = false) {
if (!$this->Auth->user('Role')['perm_sync'] && !$this->Auth->user('Role')['perm_site_admin']) throw new MethodNotAllowedException('You don\'t have permission to do that.');
$this->Server->id = $id;
@ -1033,7 +1033,7 @@ class ServersController extends AppController {
}
return new CakeResponse(array('body'=> json_encode($result)));
}
public function startZeroMQServer() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('PubSubTool', 'Tools');
@ -1042,7 +1042,7 @@ class ServersController extends AppController {
if ($result === true) return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'ZeroMQ server successfully started.')),'status'=>200));
else return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $result)),'status'=>200));
}
public function stopZeroMQServer() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('PubSubTool', 'Tools');
@ -1051,7 +1051,7 @@ class ServersController extends AppController {
if ($result === true) return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'ZeroMQ server successfully killed.')),'status'=>200));
else return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Could not kill the previous instance of the ZeroMQ script.')),'status'=>200));
}
public function statusZeroMQServer() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('PubSubTool', 'Tools');
@ -1064,7 +1064,7 @@ class ServersController extends AppController {
}
$this->render('ajax/zeromqstatus');
}
public function purgeSessions() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if ($this->Server->updateDatabase('cleanSessionTable') == false) {
@ -1072,7 +1072,7 @@ class ServersController extends AppController {
}
$this->redirect('/servers/serverSettings/diagnostics');
}
public function getVersion() {
if (!$this->userRole['perm_auth']) throw new MethodNotAllowedException('This action requires API access.');
$versionArray = $this->Server->checkMISPVersion();

View File

@ -81,7 +81,7 @@ class ShadowAttributesController extends AppController {
// Find the live attribute by the shadow attribute's uuid, so we can begin editing it
$this->Attribute->contain = 'Event';
$activeAttribute = $this->Attribute->findByUuid($shadow['uuid']);
// Send those away that shouldn't be able to see this
if (!$this->_isSiteAdmin()) {
if ($activeAttribute['Event']['orgc_id'] != $this->Auth->user('org_id') || (!$this->userRole['perm_modify'])) {
@ -136,7 +136,7 @@ class ShadowAttributesController extends AppController {
$this->Event->Behaviors->detach('SysLogLogable.SysLogLogable');
$this->Event->recursive = -1;
$event = $this->Event->read(null, $shadow['event_id']);
if (!$this->_isSiteAdmin()) {
if (($event['Event']['orgc_id'] != $this->Auth->user('org_id')) || (!$this->userRole['perm_modify'])) {
$this->Session->setFlash('You don\'t have permission to do that');
@ -147,13 +147,13 @@ class ShadowAttributesController extends AppController {
// Stuff that we won't use in its current form for the attribute
unset($shadow['email'], $shadow['org_id'], $shadow['id'], $shadow['old_id']);
$attribute = $shadow;
// set the distribution equal to that of the event
$attribute['distribution'] = 5;
$this->Attribute->create();
$this->Attribute->save($attribute);
$this->ShadowAttribute->setDeleted($toDeleteId);
$fieldList = array('proposal_email_lock', 'id', 'info', 'published');
if ($this->Auth->user('org_id') == $event['Event']['orgc_id']) {
$event['Event']['proposal_email_lock'] = 0;
@ -179,7 +179,7 @@ class ShadowAttributesController extends AppController {
}
}
}
/**
* accept method
*
@ -217,7 +217,7 @@ class ShadowAttributesController extends AppController {
}
}
private function __discard($id) {
$sa = $this->ShadowAttribute->find(
'first',
@ -260,7 +260,7 @@ class ShadowAttributesController extends AppController {
}
return false;
}
/**
* discard method
*
@ -480,7 +480,7 @@ class ShadowAttributesController extends AppController {
if (!$this->ShadowAttribute->Event->checkIfAuthorised($this->Auth->user(), $sa['Event']['id'])) throw new UnauthorizedException('You do not have the permission to view this event.');
$this->__downloadAttachment($sa['ShadowAttribute']);
}
private function __downloadAttachment($shadowAttribute) {
$path = "files" . DS . 'shadow' . DS . $shadowAttribute['event_id'] . DS;
$file = $shadowAttribute['id'];
@ -510,7 +510,7 @@ class ShadowAttributesController extends AppController {
$event = $this->ShadowAttribute->Event->fetchEvent($this->Auth->user(), array('eventid' => $eventId));
if (empty($event)) throw new NotFoundException('Invalid Event');
$event = $event[0];
if ($this->request->is('post')) {
// Check if there were problems with the file upload
// only keep the last part of the filename, this should prevent directory attacks
@ -526,7 +526,7 @@ class ShadowAttributesController extends AppController {
$this->Session->setFlash(__('There was a problem to upload the file.', true), 'default', array(), 'error');
$this->redirect(array('controller' => 'events', 'action' => 'view', $this->request->data['ShadowAttribute']['event_id']));
}
$fails = array();
$completeFail = false;
@ -644,7 +644,7 @@ class ShadowAttributesController extends AppController {
));
if (empty($existingAttribute)) throw new MethodNotAllowedException('Invalid Attribute.');
$existingAttribute = $existingAttribute[0];
// Check if the attribute is an attachment, if yes, block the type and the value fields from being edited.
if ('attachment' == $existingAttribute['Attribute']['type'] || 'malware-sample' == $existingAttribute['Attribute']['type'] ) {
$this->set('attachment', true);
@ -737,7 +737,7 @@ class ShadowAttributesController extends AppController {
$this->set('typeDefinitions', $this->ShadowAttribute->typeDefinitions);
$this->set('categoryDefinitions', $this->ShadowAttribute->Event->Attribute->categoryDefinitions);
}
public function delete($id) {
if (strlen($id) == 36) {
$this->ShadowAttribute->Event->recursive = -1;
@ -755,7 +755,7 @@ class ShadowAttributesController extends AppController {
),
'contain' => array('Event' => array('fields' => array('Event.id', 'Event.uuid', 'Event.orgc_id')))
));
if ($this->request->is('post')) {
if (empty($existingAttribute)) return new CakeResponse(array('body'=> json_encode(array('false' => true, 'errors' => 'Invalid Attribute.')),'status'=>200));
$this->ShadowAttribute->create();
@ -787,7 +787,7 @@ class ShadowAttributesController extends AppController {
$this->render('ajax/deletionProposalConfirmationForm');
}
}
public function view($id) {
$distConditions = array();
if (!$this->_isSiteAdmin()) {
@ -822,7 +822,7 @@ class ShadowAttributesController extends AppController {
$this->set('ShadowAttribute', $sa['ShadowAttribute']);
$this->set('_serialize', array('ShadowAttribute'));
}
public function index($eventId = false) {
$conditions = array();
if (!$this->_isSiteAdmin()) {
@ -869,7 +869,7 @@ class ShadowAttributesController extends AppController {
$this->set('shadowAttributes', $this->paginate());
}
}
// takes a uuid and finds all proposals that belong to an event with the given uuid. These are then returned.
public function getProposalsByUuid($uuid) {
if (!$this->_isRest() || !$this->userRole['perm_sync']) {
@ -906,7 +906,7 @@ class ShadowAttributesController extends AppController {
$this->render('get_proposals_by_uuid');
}
}
public function getProposalsByUuidList() {
if (!$this->_isRest() || !$this->userRole['perm_sync']) {
throw new MethodNotAllowedException(__('This feature is only available using the API to Sync users'));
@ -945,7 +945,7 @@ class ShadowAttributesController extends AppController {
$this->render('get_proposals_by_uuid_list');
}
}
public function fetchEditForm($id, $field = null) {
$validFields = array('value', 'comment', 'type', 'category', 'to_ids');
if (!isset($field) || !in_array($field, $validFields)) throw new MethodNotAllowedException('Invalid field requested.');
@ -954,7 +954,7 @@ class ShadowAttributesController extends AppController {
if (!$this->Attribute->exists()) {
throw new NotFoundException(__('Invalid attribute'));
}
$fields = array('id', 'distribution', 'event_id');
if ($field == 'category' || $field == 'type') {
$fields[] = 'type';
@ -997,7 +997,7 @@ class ShadowAttributesController extends AppController {
$fieldURL = ucfirst($field);
$this->render('ajax/attributeEdit' . $fieldURL . 'Form');
}
// ajax edit - post a single edited field and this method will attempt to create a proposal and return a json with the validation errors if they occur.
public function editField($id) {
if ((!$this->request->is('post') && !$this->request->is('put')) || !$this->request->is('ajax')) throw new MethodNotAllowedException();
@ -1009,7 +1009,7 @@ class ShadowAttributesController extends AppController {
$this->Attribute->recursive = -1;
$this->Attribute->contain('Event');
$attribute = $this->Attribute->read();
if (!$this->_isSiteAdmin()) {
if ($attribute['Event']['orgc_id'] != $this->Auth->user('org_id') && ($attribute['Event']['org_id'] == $this->Auth->user('org_id') || $attribute['Event']['distribution'] > 0)) {
// Allow the edit
@ -1019,7 +1019,7 @@ class ShadowAttributesController extends AppController {
}
$keys = array_flip(array('uuid', 'event_id', 'value', 'type', 'category', 'to_ids'));
$proposal = array_intersect_key($attribute['Attribute'], $keys);
$proposal['email'] = $this->Auth->user('email');
$proposal['org_id'] = $this->Auth->user('org_id');
@ -1033,7 +1033,7 @@ class ShadowAttributesController extends AppController {
}
$proposal[$changedKey] = $changedField;
}
if ($this->ShadowAttribute->save($proposal)) {
$this->autoRender = false;
return new CakeResponse(array('body'=> json_encode(array('saved' => true)),'status'=>200));
@ -1042,7 +1042,7 @@ class ShadowAttributesController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('fail' => false, 'errors' => $this->ShadowAttribute->validationErrors)),'status'=>200));
}
}
public function discardSelected($id) {
if (!$this->request->is('post') || !$this->request->is('ajax')) throw new MethodNotAllowedException();
@ -1059,7 +1059,7 @@ class ShadowAttributesController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('false' => true, 'errors' => 'You don\'t have permission to do that.')),'status'=>200));
}
}
// find all attributes from the ID list that also match the provided event ID.
$shadowAttributes = $this->ShadowAttribute->find('all', array(
'recursive' => -1,
@ -1078,10 +1078,10 @@ class ShadowAttributesController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => count($successes) . ' proposal' . (count($successes) != 1 ? 's' : '') . ' deleted, but ' . count($fails) . ' proposal' . (count($fails) != 1 ? 's' : '') . ' could not be deleted.')),'status'=>200));
}
}
public function acceptSelected($id) {
if (!$this->request->is('post') || !$this->request->is('ajax')) throw new MethodNotAllowedException();
// get a json object with a list of proposal IDs to be accepted
// check each of them and return a json object with the successful accepts and the failed ones.
$ids = json_decode($this->request->data['ShadowAttribute']['ids_accept']);
@ -1095,7 +1095,7 @@ class ShadowAttributesController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('false' => true, 'errors' => 'You don\'t have permission to do that.')),'status'=>200));
}
}
// find all attributes from the ID list that also match the provided event ID.
$shadowAttributes = $this->ShadowAttribute->find('all', array(
'recursive' => -1,
@ -1115,7 +1115,7 @@ class ShadowAttributesController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => count($successes) . ' proposal' . (count($successes) != 1 ? 's' : '') . ' accepted, but ' . count($fails) . ' proposal' . (count($fails) != 1 ? 's' : '') . ' could not be accepted.')),'status'=>200));
}
}
public function generateCorrelation() {
if (!self::_isSiteAdmin() || !$this->request->is('post')) throw new NotFoundException();
if (!Configure::read('MISP.background_jobs')) {

View File

@ -3,14 +3,14 @@ App::uses('AppController', 'Controller');
class SharingGroupsController extends AppController {
public $components = array('Session', 'RequestHandler');
public function beforeFilter() {
parent::beforeFilter();
if(!empty($this->request->params['admin']) && !$this->_isSiteAdmin()) $this->redirect('/');
$sgs = $this->SharingGroup->fetchAllAuthorised($this->Auth->user());
$this->paginate = Set::merge($this->paginate,array('conditions' => array('SharingGroup.id' => $sgs)));
}
public $paginate = array(
'limit' => 60,
'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 events <- no we won't, this is the max a user van view/page.
@ -33,7 +33,7 @@ class SharingGroupsController extends AppController {
)
),
);
public function add() {
if (!$this->userRole['perm_sharing_group']) throw new MethodNotAllowedException('You don\'t have the required privileges to do that.');
if($this->request->is('post')) {
@ -85,14 +85,14 @@ class SharingGroupsController extends AppController {
// We just pass true and allow the user to edit, since he/she is just about to create the SG. This is needed to reuse the view for the edit
$this->set('user', $this->Auth->user());
}
public function edit($id) {
if (!$this->userRole['perm_sharing_group']) throw new MethodNotAllowedException('You don\'t have the required privileges to do that.');
// add check for perm_sharing_group
$this->SharingGroup->id = $id;
if (!$this->SharingGroup->exists()) throw new NotFoundException('Invalid sharing group.');
if (!$this->_isSiteAdmin() && !$this->SharingGroup->checkIfAuthorisedExtend($this->Auth->user(), $id)) throw new MethodNotAllowedException('Action not allowed.');
// check if the user is eligible to edit the SG (original creator or extend)
$sharingGroup = $this->SharingGroup->find('first', array(
'conditions' => array('SharingGroup.id' => $id),
@ -146,7 +146,7 @@ class SharingGroupsController extends AppController {
// We just pass true and allow the user to edit, since he/she is just about to create the SG. This is needed to reuse the view for the edit
$this->set('user', $this->Auth->user());
}
public function delete($id) {
if (!$this->userRole['perm_sharing_group']) throw new MethodNotAllowedException('You don\'t have the required privileges to do that.');
if (!$this->request->is('post')) throw new MethodNotAllowedException('Action not allowed, post request expected.');
@ -162,7 +162,7 @@ class SharingGroupsController extends AppController {
if ($deletedSg['SharingGroup']['active']) $this->redirect('/SharingGroups/index');
else $this->redirect('/SharingGroups/index/true');
}
public function index($passive = false) {
if ($passive === 'true') $passive = true;
if ($passive === true) $this->paginate['conditions'][] = array('SharingGroup.active' => false);
@ -189,7 +189,7 @@ class SharingGroupsController extends AppController {
$this->set('sharingGroups', $result);
}
}
public function view($id) {
if (!$this->SharingGroup->checkIfAuthorised($this->Auth->user(), $id)) throw new MethodNotAllowedException('Sharing group doesn\'t exist or you do not have permission to access it.');
$this->SharingGroup->id = $id;
@ -206,4 +206,3 @@ class SharingGroupsController extends AppController {
$this->set('sg', $sg);
}
}

View File

@ -41,7 +41,7 @@ class SightingsController extends AppController {
}
if (!$error) $result = $this->Sighting->saveSightings($id, $values, $timestamp, $this->Auth->user());
if ($result == 0) $error = 'No valid attributes found that would match the sighting criteria.';
if ($this->request->is('ajax')) {
if ($error) {
$error_message = 'Could not add the Sighting. Reason: ' . $error;

View File

@ -17,13 +17,13 @@ class TagsController extends AppController {
'Tag.name' => 'asc'
)
);
public $helpers = array('TextColour');
public function beforeFilter() { // TODO REMOVE
parent::beforeFilter();
}
public function index($favouritesOnly = false) {
$this->loadModel('Event');
$this->loadModel('Taxonomy');
@ -94,7 +94,7 @@ class TagsController extends AppController {
}
// send perm_tagger to view for action buttons
}
public function add() {
if (!$this->_isSiteAdmin() && !$this->userRole['perm_tag_editor']) throw new NotFoundException('You don\'t have permission to do that.');
if ($this->request->is('post')) {
@ -116,7 +116,7 @@ class TagsController extends AppController {
}
}
}
public function quickAdd() {
if ((!$this->_isSiteAdmin() && !$this->userRole['perm_tag_editor']) || !$this->request->is('post')) throw new NotFoundException('You don\'t have permission to do that.');
if (isset($this->request->data['Tag']['request'])) $this->request->data['Tag'] = $this->request->data['Tag']['request'];
@ -127,7 +127,7 @@ class TagsController extends AppController {
}
$this->redirect($this->referer());
}
public function edit($id) {
if (!$this->_isSiteAdmin() && !$this->userRole['perm_tag_editor']) {
throw new NotFoundException('You don\'t have permission to do that.');
@ -155,7 +155,7 @@ class TagsController extends AppController {
}
$this->request->data = $this->Tag->read(null, $id);
}
public function delete($id) {
if (!$this->_isSiteAdmin() && !$this->userRole['perm_tag_editor']) {
throw new NotFoundException('You don\'t have permission to do that.');
@ -181,7 +181,7 @@ class TagsController extends AppController {
}
if (!$this->_isRest()) $this->redirect(array('action' => 'index'));
}
public function view($id) {
if ($this->_isRest()) {
$tag = $this->Tag->find('first', array(
@ -216,9 +216,9 @@ class TagsController extends AppController {
$this->set('Tag', $tag['Tag']);
$this->set('_serialize', 'Tag');
} else throw new MethodNotAllowedException('This action is only for REST users.');
}
public function showEventTag($id) {
$this->helpers[] = 'TextColour';
$this->loadModel('EventTag');
@ -245,7 +245,7 @@ class TagsController extends AppController {
$this->layout = 'ajax';
$this->render('/Events/ajax/ajaxTags');
}
public function viewTag($id) {
$tag = $this->Tag->find('first', array(
'conditions' => array(
@ -258,7 +258,7 @@ class TagsController extends AppController {
$this->set('id', $id);
$this->render('ajax/view_tag');
}
public function selectTaxonomy($event_id) {
if (!$this->_isSiteAdmin() && !$this->userRole['perm_tagger']) throw new NotFoundException('You don\'t have permission to do that.');
@ -274,7 +274,7 @@ class TagsController extends AppController {
$this->set('favourites', $favourites);
$this->render('ajax/taxonomy_choice');
}
public function selectTag($event_id, $taxonomy_id) {
if (!$this->_isSiteAdmin() && !$this->userRole['perm_tagger']) throw new NotFoundException('You don\'t have permission to do that.');
$this->loadModel('Taxonomy');
@ -308,7 +308,7 @@ class TagsController extends AppController {
$this->set('custom', $taxonomy_id == 0 ? true : false);
$this->render('ajax/select_tag');
}
public function tagStatistics($percentage = false, $keysort = false) {
$result = $this->Tag->EventTag->find('all', array(
'recursive' => -1,

View File

@ -9,18 +9,18 @@ App::uses('AppController', 'Controller');
*/
class TasksController extends AppController {
public $components = array('Security' ,'RequestHandler', 'Session');
public $paginate = array(
'limit' => 20,
'order' => array(
'Task.id' => 'desc'
)
);
public function beforeFilter() {
parent::beforeFilter();
}
public function index() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if (!Configure::read('MISP.background_jobs')) throw new NotFoundException('Background jobs are not enabled on this instance.');
@ -30,7 +30,7 @@ class TasksController extends AppController {
$this->set('list', $tasks);
$this->set('time', time());
}
// checks if all the mandatory tasks exist, and if not, creates them
// default tasks are:
// 'cache_exports'
@ -43,7 +43,7 @@ class TasksController extends AppController {
}
}
}
public function setTask() {
if (!$this->_isSiteAdmin()) {
throw new MethodNotAllowedException('You are not authorised to do that.');
@ -75,17 +75,17 @@ class TasksController extends AppController {
$this->redirect(array('action' => 'index'));
}
}
private function _getTodaysTimestamp() {
return strtotime(date("d/m/Y") . ' 00:00:00');
}
private function _jobScheduler($type, $timestamp, $id) {
if ($type === 'cache_exports') $this->_cacheScheduler($timestamp, $id);
if ($type === 'pull_all') $this->_pullScheduler($timestamp, $id);
if ($type === 'push_all') $this->_pushScheduler($timestamp, $id);
}
private function _cacheScheduler($timestamp, $id) {
CakeResque::enqueueAt(
$timestamp,
@ -107,7 +107,7 @@ class TasksController extends AppController {
$this->Task->id = $id;
$this->Task->saveField('job_id', $process_id);
}
private function _pullScheduler($timestamp, $id) {
$process_id = CakeResque::enqueueAt(
$timestamp,

View File

@ -37,7 +37,7 @@ class TaxonomiesController extends AppController {
}
$this->set('taxonomies', $taxonomies);
}
public function view($id) {
if (isset($this->passedArgs['pages'])) {
$currentPage = $this->passedArgs['pages'];
@ -64,7 +64,7 @@ class TaxonomiesController extends AppController {
$this->set('taxonomy', $taxonomy['Taxonomy']);
$this->set('id', $id);
}
public function enable($id) {
if (!$this->_isSiteAdmin() || !$this->request->is('Post')) throw new MethodNotAllowedException('You don\'t have permission to do that.');
$taxonomy = $this->Taxonomy->find('first', array(
@ -88,7 +88,7 @@ class TaxonomiesController extends AppController {
$this->Session->setFlash('Taxonomy enabled.');
$this->redirect($this->referer());
}
public function disable($id) {
if (!$this->_isSiteAdmin() || !$this->request->is('Post')) throw new MethodNotAllowedException('You don\'t have permission to do that.');
$taxonomy = $this->Taxonomy->find('first', array(
@ -112,7 +112,7 @@ class TaxonomiesController extends AppController {
$this->Session->setFlash('Taxonomy disabled.');
$this->redirect($this->referer());
}
public function update() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException('You don\'t have permission to do that.');
$result = $this->Taxonomy->update();
@ -176,7 +176,7 @@ class TaxonomiesController extends AppController {
}
$this->redirect(array('controller' => 'taxonomies', 'action' => 'index'));
}
public function addTag($taxonomy_id = false) {
if ((!$this->_isSiteAdmin() && !$this->userRole['perm_tagger']) || !$this->request->is('post')) throw new NotFoundException('You don\'t have permission to do that.');
if ($taxonomy_id) {
@ -198,7 +198,7 @@ class TaxonomiesController extends AppController {
}
$this->redirect($this->referer());
}
public function taxonomyMassConfirmation($id) {
if (!$this->_isSiteAdmin() && !$this->userRole['perm_tagger']) throw new NotFoundException('You don\'t have permission to do that.');
$this->set('id', $id);

View File

@ -17,13 +17,13 @@ class TemplateElementsController extends AppController {
'TemplateElement.position' => 'asc'
)
);
public function index($id) {
//check permissions
$template = $this->TemplateElement->Template->checkAuthorisation($id, $this->Auth->user(), false);
if (!$this->_isSiteAdmin() && !$template) throw new MethodNotAllowedException('No template with the provided ID exists, or you are not authorised to see it.');
$templateElements = $this->TemplateElement->find('all', array(
'conditions' => array(
'template_id' => $id,
@ -45,24 +45,24 @@ class TemplateElementsController extends AppController {
$this->set('mayModify', $mayModify);
$this->render('ajax/ajaxIndex');
}
public function templateElementAddChoices($id) {
if (!$this->_isSiteAdmin() && !$this->TemplateElement->Template->checkAuthorisation($id, $this->Auth->user(), true)) throw new MethodNotAllowedException('You are not authorised to do that.');
if (!$this->request->is('ajax')) Throw new MethodNotAllowedException('This action is for ajax requests only.');
$this->set('id', $id);
$this->layout = 'ajax';
$this->render('ajax/template_element_add_choices');
}
public function add($type, $id) {
$ModelType = 'TemplateElement' . ucfirst($type);
if (!$this->_isSiteAdmin() && !$this->TemplateElement->Template->checkAuthorisation($id, $this->Auth->user(), true)) return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'You are not authorised to do that.')), 'status' => 200));
if (!$this->request->is('ajax')) Throw new MethodNotAllowedException('This action is for ajax requests only.');
if ($this->request->is('get')) {
$this->set('id', $id);
if ($type == 'attribute') {
@ -137,7 +137,7 @@ class TemplateElementsController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $errorMessage)), 'status' => 200));
}
}
public function edit($type, $id) {
$ModelType = 'TemplateElement' . ucfirst($type);
$templateElement = $this->TemplateElement->find('first', array(
@ -146,7 +146,7 @@ class TemplateElementsController extends AppController {
));
$this->set('template_id', $templateElement['Template']['id']);
if (!$this->_isSiteAdmin() && !$this->TemplateElement->Template->checkAuthorisation($id, $this->Auth->user(), true)) return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'You are not authorised to do that.')), 'status' => 200));
if (!$this->request->is('ajax')) Throw new MethodNotAllowedException('This action is for ajax requests only.');
if ($this->request->is('get')) {
$this->set('id', $id);
@ -213,7 +213,7 @@ class TemplateElementsController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'The element could not be edited.')), 'status' => 200));
}
}
public function delete($id) {
if (!$this->request->is('ajax')) Throw new MethodNotAllowedException('This action is for ajax requests only.');
$this->TemplateElement->read(null, $id);

View File

@ -24,8 +24,8 @@ class TemplatesController extends AppController {
parent::beforeFilter();
$this->Security->unlockedActions = array('uploadFile', 'deleteTemporaryFile');
}
public function index() {
$conditions = array();
if (!$this->_isSiteAdmin()) {
@ -41,12 +41,12 @@ class TemplatesController extends AppController {
}
$this->set('list', $this->paginate());
}
public function edit($id) {
$template = $this->Template->checkAuthorisation($id, $this->Auth->user(), true);
if (!$this->_isSiteAdmin() && !$template) throw new MethodNotAllowedException('No template with the provided ID exists, or you are not authorised to edit it.');
$this->set('mayModify', true);
if ($this->request->is('post') || $this->request->is('put')) {
$this->request->data['Template']['id'] = $id;
unset($this->request->data['Template']['tagsPusher']);
@ -68,11 +68,11 @@ class TemplatesController extends AppController {
'recursive' => -1,
'conditions' => array('id' => $tagArray)
));
foreach($oldTags as $k => $oT) {
if (!in_array($oT['Tag'], $newTags)) $this->TemplateTag->delete($oT['TemplateTag']['id']);
}
foreach($newTags as $k => $nT) {
if (!in_array($nT['Tag'], $oldTags)) {
$this->TemplateTag->create();
@ -93,7 +93,7 @@ class TemplatesController extends AppController {
foreach ($tags as $tag) {
$tagArray[$tag['Tags']['id']] = $tag['Tags']['name'];
}
//get all tags currently assigned to the event
$currentTags = $this->Template->TemplateTag->find('all', array(
'recursive' => -1,
@ -106,7 +106,7 @@ class TemplatesController extends AppController {
$this->set('tags', $tagArray);
$this->set('tagInfo', $tags);
}
public function view($id) {
if (!$this->_isSiteAdmin() && !$this->Template->checkAuthorisation($id, $this->Auth->user(), false)) throw new MethodNotAllowedException('No template with the provided ID exists, or you are not authorised to see it.');
if ($this->Template->checkAuthorisation($id, $this->Auth->user(), true)) $this->set('mayModify', true);
@ -130,7 +130,7 @@ class TemplatesController extends AppController {
$this->set('id', $id);
$this->set('template', $template);
}
public function add() {
if (!$this->userRole['perm_template']) throw new MethodNotAllowedException('You are not authorised to do that.');
if ($this->request->is('post')) {
@ -167,7 +167,7 @@ class TemplatesController extends AppController {
$this->set('tags', $tagArray);
$this->set('tagInfo', $tags);
}
public function saveElementSorting() {
// check if user can edit the template
$this->autoRender = false;
@ -183,9 +183,9 @@ class TemplatesController extends AppController {
'recursive' => -1,
'fields' => array('id', 'template_id'),
));
if (!$this->_isSiteAdmin() && !$this->Template->checkAuthorisation($template_id['TemplateElement']['template_id'], $this->Auth->user(), true)) return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'You are not authorised to do that.')), 'status' => 200));
$elements = $this->Template->TemplateElement->find('all', array(
'conditions' => array('template_id' => $template_id['TemplateElement']['template_id']),
'recursive' => -1,
@ -193,7 +193,7 @@ class TemplatesController extends AppController {
if (empty($elements)) return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Something went wrong, the supplied template elements don\'t exist, or you are not eligible to edit them.')),'status'=>200));
if (count($elements) != count($orderedElements)) return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Incomplete template element list passed as argument. Expecting ' . count($elements) . ' elements, only received positions for ' . count($orderedElements) . '.')),'status'=>200));
$template_id = $elements[0]['TemplateElement']['template_id'];
foreach ($elements as &$e) {
if ($template_id !== $e['TemplateElement']['template_id']) return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Cannot sort template elements belonging to separate templates. You should never see this message during legitimate use.')),'status'=>200));
foreach ($orderedElements as $k => $orderedElement) {
@ -205,7 +205,7 @@ class TemplatesController extends AppController {
$this->Template->TemplateElement->saveMany($elements);
return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'Elements repositioned.')),'status'=>200));
}
public function delete($id) {
$template = $this->Template->checkAuthorisation($id, $this->Auth->user(), true);
if (!$this->request->is('post')) throw new MethodNotAllowedException('This action can only be invoked via a post request.');
@ -218,7 +218,7 @@ class TemplatesController extends AppController {
$this->redirect(array('action' => 'index'));
}
}
public function templateChoices($id) {
$this->loadModel('Event');
@ -228,7 +228,7 @@ class TemplatesController extends AppController {
'fields' => array('orgc_id', 'id'),
));
if (empty($event) || (!$this->_isSiteAdmin() && $event['Event']['orgc_id'] != $this->Auth->user('org_id'))) throw new NotFoundException('Event not found or you are not authorised to edit it.');
$conditions = array();
if (!$this->_isSiteAdmin) {
$conditions['OR'] = array('Template.org' => $this->Auth->user('Organisation')['name'], 'Template.share' => true);
@ -241,7 +241,7 @@ class TemplatesController extends AppController {
$this->set('id', $id);
$this->render('ajax/template_choices');
}
public function populateEventFromTemplate($template_id, $event_id) {
$template = $this->Template->find('first', array(
'conditions' => array('Template.id' => $template_id),
@ -269,7 +269,7 @@ class TemplatesController extends AppController {
if ($event['Event']['orgc_id'] != $this->Auth->user('org_id')) throw new MethodNotAllowedException('Event not found or you are not authorised to edit it.');
if ($template['Template']['org'] != $this->Auth->user('Organisation')['name'] && !$template['Template']['share']) throw new MethodNotAllowedException('Template not found or you are not authorised to use it.');
}
$this->set('template_id', $template_id);
$this->set('event_id', $event_id);
if ($this->request->is('post')) {
@ -295,8 +295,8 @@ class TemplatesController extends AppController {
$this->set('validTypeGroups', $this->Event->Attribute->validTypeGroups);
}
}
// called when the user is finished populating a template and is has finished reviewing the resulting attributes at the last stage of the process
public function submitEventPopulation($template_id, $event_id) {
if ($this->request->is('post')) {
@ -318,7 +318,7 @@ class TemplatesController extends AppController {
'contain' => 'TemplateTag',
'fields' => 'id',
));
foreach ($template['TemplateTag'] as $tag) {
$exists = false;
foreach ($event['EventTag'] as $eventTag) {
@ -329,7 +329,7 @@ class TemplatesController extends AppController {
$this->Event->EventTag->save(array('event_id' => $event_id, 'tag_id' => $tag['tag_id']));
}
}
if (isset($this->request->data['Template']['attributes'])) {
$attributes = json_decode($this->request->data['Template']['attributes'], true);
$this->loadModel('Attribute');
@ -363,7 +363,7 @@ class TemplatesController extends AppController {
throw new MethodNotAllowedException();
}
}
public function uploadFile($elementId, $batch) {
$this->layout = 'iframe';
$this->set('batch', $batch);
@ -397,13 +397,13 @@ class TemplatesController extends AppController {
} else {
$this->set('upload_error', false);
}
$this->set('result', $result);
$this->set('filenames', $filenames);
$this->set('fileArray', json_encode($fileArray));
}
}
private function __combineArrays($array, $array2) {
foreach ($array2 as $element) {
if (!in_array($element, $array)) {

View File

@ -13,9 +13,9 @@ class ThreadsController extends AppController {
'RequestHandler',
'Session',
);
public $helpers = array('Js' => array('Jquery'));
public $paginate = array(
'limit' => 60,
);
@ -23,7 +23,7 @@ class ThreadsController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
}
public function viewEvent($id) {
$this->loadModel('Event');
$result = $this->Event->fetchEvent($this->Auth->user(), array('eventid' => $id));
@ -84,8 +84,8 @@ class ThreadsController extends AppController {
$this->layout = 'ajax';
$this->render('/Elements/eventdiscussion');
}
public function view($thread_id, $eventView = false) {
$post_id = false;
if (isset($this->passedArgs['post_id'])) $post_id = $this->passedArgs['post_id'];
@ -113,13 +113,13 @@ class ThreadsController extends AppController {
} else {
$this->Thread->recursive = -1;
$this->Thread->id = $thread_id;
//If the thread doesn't exist, throw exception
if (!$this->Thread->exists()) {
throw new NotFoundException('Invalid thread.');
}
$thread = $this->Thread->read();
// If the thread belongs to an event, we have to make sure that the event's distribution level hasn't changed.
// This is also a good time to update the thread's distribution level if that did happen.
if (!empty($thread['Thread']['event_id'])) {
@ -135,7 +135,7 @@ class ThreadsController extends AppController {
}
$this->set('event_id', $thread['Thread']['event_id']);
}
// If the user shouldn't be allowed to see the event send him away.
if (!$this->_isSiteAdmin()) {
if ($thread['Thread']['distribution'] == 0 && $thread['Thread']['org_id'] != $this->Auth->user('org_id')) {
@ -183,7 +183,7 @@ class ThreadsController extends AppController {
$this->render('/Elements/eventdiscussion');
}
}
public function index() {
$this->loadModel('Posts');
$this->loadModel('SharingGroup');

View File

@ -205,7 +205,7 @@ class UsersController extends AppController {
$this->set('users', $this->paginate());
}
}
public function index($id) {
$this->autoRender = false;
$this->layout = false;
@ -260,7 +260,7 @@ class UsersController extends AppController {
$this->set('simpleFilters', $textFields);
$rules = array_merge($booleanFields, $textFields);
$this->set('showorg', $showOrg);
$filtering = array();
foreach ($booleanFields as $b) {
$filtering[$b] = '';
@ -268,7 +268,7 @@ class UsersController extends AppController {
foreach ($textFields as $t) {
$filtering[$t] = array('OR' => array(), 'NOT' => array());
}
foreach ($this->passedArgs as $k => $v) {
if (substr($k, 0, 6) === 'search') {
$searchTerm = substr($k, 6);
@ -285,7 +285,7 @@ class UsersController extends AppController {
}
}
$this->set('filtering', json_encode($filtering));
$roles = $this->User->Role->find('all', array('recursive' => -1));
$roleNames = array();
$roleJSON = array();
@ -446,7 +446,7 @@ class UsersController extends AppController {
}
$roles = $this->User->Role->find('list', $params);
$syncRoles = $this->User->Role->find('list', array('conditions' => array('perm_sync' => 1), 'recursive' => -1));
$this->set('currentId', $id);
if ($this->request->is('post') || $this->request->is('put')) {
if (!array_key_exists($this->request->data['User']['role_id'], $syncRoles)) $this->request->data['User']['server_id'] = 0;
@ -578,7 +578,7 @@ class UsersController extends AppController {
$this->Session->setFlash(__('User was not deleted'));
$this->redirect(array('action' => 'index'));
}
public function updateLoginTime() {
if (!$this->request->is('post')) throw new MethodNotAllowedException('This feature is only accessible via POST requests');
$user = $this->User->find('first', array(
@ -657,7 +657,7 @@ class UsersController extends AppController {
$org_id = $firstOrg['Organisation']['id'];
}
}
// populate the DB with the first user if it's empty
if ($this->User->find('count') == 0 ) {
$admin = array('User' => array(
@ -694,7 +694,7 @@ class UsersController extends AppController {
$this->Session->setFlash(__('Good-Bye'));
$this->redirect($this->Auth->logout());
}
public function resetauthkey($id = null) {
if (!$this->_isAdmin() && Configure::read('MISP.disableUserSelfManagement')) {
throw new MethodNotAllowedException('User self-management has been disabled on this instance.');
@ -739,7 +739,7 @@ class UsersController extends AppController {
$orgs = $this->User->find('all', $params);
$this->set('orgs', $orgs);
}
public function histogram($selected = null) {
if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This function can only be accessed via AJAX.');
if ($selected == '[]') $selected = null;
@ -786,7 +786,7 @@ class UsersController extends AppController {
$this->set('data', $data);
$this->set('max', $max);
$this->set('selectedTypes', $selectedTypes);
// Nice graphical histogram
$sigTypes = array_keys($this->Attribute->typeDefinitions);
App::uses('ColourPaletteTool', 'Tools');
@ -811,7 +811,7 @@ class UsersController extends AppController {
}
$this->set('termsaccepted', $this->Auth->user('termsaccepted'));
}
public function downloadTerms() {
if (!Configure::read('MISP.terms_file')) {
$termsFile = APP ."View/Users/terms";
@ -975,7 +975,7 @@ class UsersController extends AppController {
$this->render('ajax/passwordResetConfirmationForm');
}
}
// shows some statistics about the instance
public function statistics() {
// set all of the data up for the heatmaps
@ -995,24 +995,24 @@ class UsersController extends AppController {
$stats[2] = $this->User->Event->Attribute->find('count', array('conditions' => array('Attribute.deleted' => false)));
$stats[3] = $this->User->Event->Attribute->find('count', array('conditions' => array('Attribute.timestamp >' => $this_month, 'Attribute.deleted' => false)));
$this->loadModel('Correlation');
$this->Correlation->recursive = -1;
$stats[4] = $this->Correlation->find('count', null);
$stats[4] = $stats[4] / 2;
$stats[5] = $this->User->Event->ShadowAttribute->find('count', null);
$stats[6] = $this->User->find('count', null);
$stats[7] = count($orgs);
$this->loadModel('Thread');
$stats[8] = $this->Thread->find('count', array('conditions' => array('Thread.post_count >' => 0)));
$stats[9] = $this->Thread->find('count', array('conditions' => array('Thread.date_created >' => date("Y-m-d H:i:s",$this_month), 'Thread.post_count >' => 0)));
$stats[10] = $this->Thread->Post->find('count', null);
$stats[11] = $this->Thread->Post->find('count', array('conditions' => array('Post.date_created >' => date("Y-m-d H:i:s",$this_month))));
$this->set('stats', $stats);
$this->set('orgs', $orgs);
$this->set('start', strtotime(date('Y-m-d H:i:s') . ' -5 months'));
@ -1046,7 +1046,7 @@ class UsersController extends AppController {
unset($newUser['Organisation'], $newUser['Role']);
$this->Auth->login($newUser['User']);
}
public function fetchPGPKey($email) {
if (!$this->_isAdmin()) throw new Exception('Administrators only.');
$keys = $this->User->fetchPGPKey($email);
@ -1058,7 +1058,7 @@ class UsersController extends AppController {
$this->layout = false;
$this->render('ajax/fetchpgpkey');
}
public function dashboard() {
$events = array();
// the last login in the session is not updated after the login - only in the db, so let's fetch it.

View File

@ -35,7 +35,7 @@ class WarninglistsController extends AppController {
$this->set('warninglists', $warninglists);
}
}
public function update() {
if (!$this->request->is('post')) throw new MethodNotAllowedException('This action is only accessible via POST requests.');
$result = $this->Warninglist->update();
@ -99,7 +99,7 @@ class WarninglistsController extends AppController {
}
$this->redirect(array('controller' => 'warninglists', 'action' => 'index'));
}
public function toggleEnable() {
$id = $this->request->data['Warninglist']['data'];
if (!is_numeric($id)) return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Warninglist not found.')), 'status' => 200));
@ -118,7 +118,7 @@ class WarninglistsController extends AppController {
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Warninglist could not be enabled.')), 'status' => 200));
}
}
public function enableWarninglist($id, $enable = false) {
$this->Warninglist->id = $id;
debug($id);
@ -127,13 +127,13 @@ class WarninglistsController extends AppController {
$this->Session->setFlash('Warninglist enabled');
$this->redirect(array('controller' => 'warninglists', 'action' => 'view', $id));
}
public function getToggleField() {
if (!$this->request->is('ajax')) throw new MethodNotAllowedException('This action is available via AJAX only.');
$this->layout = 'ajax';
$this->render('ajax/getToggleField');
}
public function view($id) {
if (!is_numeric($id)) throw new NotFoundException('Invalid ID.');
$warninglist = $this->Warninglist->find('first', array('contain' => array('WarninglistEntry', 'WarninglistType'), 'conditions' => array('id' => $id)));

View File

@ -19,7 +19,7 @@ class HidsExport {
if (!empty($items)) {
foreach ($items as &$item) {
$attribute = &$item['Attribute'];
switch ($attribute['type']) {
case 'md5':
case 'sha1':

View File

@ -1,7 +1,7 @@
<?php
class RPZExport {
private $__policies = array(
'walled-garden' => array(
'explanation' => 'returns the defined alternate location.',
@ -24,17 +24,17 @@ class RPZExport {
'setting_id' => 0,
),
);
public function getPolicyById($id) {
foreach ($this->__policies as $k => $v) {
if ($id == $v['setting_id']) return $k;
}
}
public function getIdByPolicy($policy) {
return $this->__policies[$policy]['setting_id'];
}
public function explain($type, $policy) {
$explanations = array(
'ip' => '; The following list of IP addresses will ',
@ -49,7 +49,7 @@ class RPZExport {
);
return $explanations[$type] . $this->__policies[$policy]['explanation'] . PHP_EOL;
}
public function buildHeader($rpzSettings) {
$rpzSettings['serial'] = str_replace('$date', date('Ymd'), $rpzSettings['serial']);
$header = '';
@ -58,13 +58,13 @@ class RPZExport {
$header .= ' NS ' . $rpzSettings['ns'] . PHP_EOL . PHP_EOL;
return $header;
}
public function export($items, $rpzSettings) {
$result = $this->buildHeader($rpzSettings);
$policy = $this->getPolicyById($rpzSettings['policy']);
$action = $this->__policies[$policy]['action'];
if ($policy == 'walled-garden') $action = str_replace('$walled_garden', $rpzSettings['walled_garden'], $action);
if (isset($items['ip'])) {
$result .= $this->explain('ip', $policy);
foreach ($items['ip'] as $item) {
@ -72,7 +72,7 @@ class RPZExport {
}
$result .= PHP_EOL;
}
if (isset($items['domain'])) {
$result .= $this->explain('domain', $policy);
foreach ($items['domain'] as $item) {
@ -80,7 +80,7 @@ class RPZExport {
}
$result .= PHP_EOL;
}
if (isset($items['hostname'])) {
$result .= $this->explain('hostname', $policy);
foreach ($items['hostname'] as $item) {
@ -94,11 +94,11 @@ class RPZExport {
private function __convertdomain($input, $action) {
return $input . ' CNAME ' . $action . PHP_EOL . '*.' . $input . ' CNAME ' . $action . PHP_EOL;
}
private function __converthostname($input, $action) {
return $input . ' CNAME ' . $action . PHP_EOL;
}
private function __convertip($input, $action) {
$type = filter_var($input, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? 'ipv6' : 'ipv4';
if ($type == 'ipv6') $prefix = '128';
@ -108,14 +108,14 @@ class RPZExport {
}
return $prefix . '.' . $this->{'__' . $type}($input) . '.rpz-ip CNAME ' . $action . PHP_EOL;
}
private function __ipv6($input) {
return implode('.', array_reverse(preg_split('/:/', str_replace('::', ':zz:', $input), NULL, PREG_SPLIT_NO_EMPTY)));
}
private function __ipv4($input) {
return implode('.', array_reverse(explode('.', $input)));
}
}

View File

@ -1,6 +1,6 @@
<?php
class ColourPaletteTool {
// pass the number of distinct colours to receive an array of colours
function createColourPalette($count) {
$interval = 1 / $count;
@ -10,7 +10,7 @@ class ColourPaletteTool {
}
return $colours;
}
function HSVtoRGB(array $hsv) {
list($H,$S,$V) = $hsv;
//1
@ -46,7 +46,7 @@ class ColourPaletteTool {
}
return $this->convertToHex(array($R, $G, $B));
}
function convertToHex($channels) {
$colour = '#';
foreach ($channels as &$channel) {
@ -56,7 +56,7 @@ class ColourPaletteTool {
}
return $colour;
}
// pass the element's id from the list along to get a colour for a single item
function generatePaletteFromString($string, $items, $onlySpecific = false) {
$hue = $this->__stringToNumber($string);
@ -74,7 +74,7 @@ class ColourPaletteTool {
}
return $results;
}
private function __stringToNumber($string) {
$string = mb_convert_encoding($string, 'ASCII');
$number = 0;

View File

@ -1,7 +1,7 @@
<?php
class ComplexTypeTool {
private $__refangRegexTable = array(
'/^hxxp/i' => 'http',
'/\[\.\]/' => '.',
@ -9,7 +9,7 @@ class ComplexTypeTool {
'/\\\./' => '.',
'/\.+/' => '.'
);
public function checkComplexRouter($input, $type) {
switch ($type) {
case 'File':
@ -25,7 +25,7 @@ class ComplexTypeTool {
return false;
}
}
// checks if the passed input matches a valid file description attribute's pattern (filename, md5, sha1, sha256, filename|md5, filename|sha1, filename|sha256)
public function checkComplexFile($input) {
$original = $input;
@ -46,7 +46,7 @@ class ComplexTypeTool {
if ($type == '') $type = 'other';
return array('type' => $type, 'value' => $original);
}
public function checkComplexCnC($input) {
$type = '';
$toReturn = array();
@ -62,21 +62,21 @@ class ComplexTypeTool {
}
return array('type' => 'domain', 'value' => $input);
}
if (!preg_match("#\n#", $input)) return array('type' => 'url', 'value' => $input);
return array('type' => 'other', 'value' => $input);
}
private function __returnOddElements(&$array) {
foreach ($array as $k => &$v) if ($k % 2 != 1) unset($array[$k]);
return array_values($array);
}
public function checkFreeText($input) {
$iocArray = preg_split("/\r\n|\n|\r|\s|\s+|,|;/", $input);
$quotedText = explode('"', $input);
$iocArray = array_merge($iocArray, $this->__returnOddElements($quotedText));
$resultArray = array();
if (!empty($iocArray)) {
foreach ($iocArray as $ioc) {
@ -102,7 +102,7 @@ class ComplexTypeTool {
96 => array('single' => array('sha384'), 'composite' => array('filename|sha384')),
128 => array('single' => array('sha512'), 'composite' => array('filename|sha512'))
);
private function __resolveType($input) {
$result = array();
$input = trim($input);
@ -117,7 +117,7 @@ class ComplexTypeTool {
}
}
}
// check for hashes
foreach ($this->__hexHashTypes as $k => &$v) {
if (strlen($input) == $k && preg_match("#[0-9a-f]{" . $k . "}$#i", $input)) return array('types' => $v['single'], 'to_ids' => true, 'default_type' => $v['single'][0]);
@ -144,7 +144,7 @@ class ComplexTypeTool {
if (filter_var($temp[0], FILTER_VALIDATE_IP) && is_numeric($temp[1])) return array('types' => array('ip-dst', 'ip-src', 'ip-src/ip-dst'), 'to_ids' => true, 'default_type' => 'ip-dst', 'comment' => $comment, 'value' => $inputRefangedNoPort);
}
}
// check for domain name, hostname, filename
if (strpos($inputRefanged, '.') !== false) {
$temp = explode('.', $inputRefanged);
@ -167,7 +167,7 @@ class ComplexTypeTool {
if ($this->__resolveFilename($input)) return array('types' => array('filename'), 'to_ids' => true, 'default_type' => 'filename');
}
}
if (strpos($input, '\\') !== false) {
$temp = explode('\\', $input);
if (strpos($temp[count($temp)-1], '.')) {
@ -176,13 +176,13 @@ class ComplexTypeTool {
return array('types' => array('regkey'), 'to_ids' => false, 'default_type' => 'regkey');
}
}
// check for CVE
if (preg_match("#^cve-[0-9]{4}-[0-9]{4,9}$#i", $input)) return array('types' => array('vulnerability'), 'category' => 'External analysis', 'to_ids' => false, 'default_type' => 'vulnerability');
return false;
}
private function __resolveFilename($input) {
if (
strpos($input, '.') != 0 &&

View File

@ -1,6 +1,6 @@
<?php
class CustomPaginationTool {
function createPaginationRules(&$items, $options, $model, $sort = 'id') {
$params = array(
'model' => $model,
@ -37,12 +37,12 @@ class CustomPaginationTool {
$params['pageCount'] = $maxPage;
return $params;
}
function truncateByPagination(&$items, $params) {
if (empty($items)) return;
$items = array_slice($items, $params['current'] - 1, $params['current'] + $params['limit']);
}
function applyRulesOnArray(&$items, $options, $model, $sort = 'id') {
$params = $this->createPaginationRules($items, $options, $model, $sort);
$direction = 'asc';
@ -54,7 +54,7 @@ class CustomPaginationTool {
$this->truncateByPagination($items, $params);
return $params;
}
function cmp($a, $b) {
$multiplier = 1;
if ($this->direction == 'desc') $multiplier = -1;

View File

@ -87,7 +87,7 @@ class FinancialTool {
'VG' => '24',
'XK' => '20'
);
public function validateRouter($type, $value) {
$validationRoutes = array(
'cc-number' => 'CC',
@ -99,7 +99,7 @@ class FinancialTool {
if (in_array($type, array_keys($validationRoutes))) return $this->{'validate' . strtoupper($validationRoutes[$type])}($value);
return true;
}
// validating using method described on wikipedia @ https://en.wikipedia.org/wiki/International_Bank_Account_Number#Algorithms
public function validateIBAN($iban) {
if (strlen($iban) < 15 || strlen($iban) > 32) return false;
@ -112,17 +112,17 @@ class FinancialTool {
$temp = bcmod($temp2, 97);
return intval($temp)===1 ? true : false;
}
public function validateBIC($bic) {
if (preg_match('/^([A-Z]{4})([A-Z]){2}([0-9A-Z]){2}([0-9A-Z]{3})?$/i', $bic)) return true;
return false;
}
public function validateBIN($bin) {
if (is_numeric($bin) && strlen($bin) == 6) return true;
return false;
}
// based on the explanation at www.freeformatter.com/credit-card-number-generator-validator.html#validate
public function validateCC($cc) {
if (is_numeric($cc) && strlen($cc) > 12 && strlen($cc) < 20) {
@ -143,26 +143,26 @@ class FinancialTool {
}
return false;
}
// based on the php implementation of the BTC address validation example from
// http://rosettacode.org/wiki/Bitcoin/address_validation
public function validateBTC($address){
if (strlen($address) < 26 || strlen($address) > 35) return false;
$decoded = $this->__decodeBase58($address);
if ($decoded === false) return false;
$d1 = hash("sha256", substr($decoded,0,21), true);
$d2 = hash("sha256", $d1, true);
if(substr_compare($decoded, $d2, 21, 4)){
return false;
}
return true;
}
private function __decodeBase58($input) {
$alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
$out = array_fill(0, 25, 0);
for($i=0;$i<strlen($input);$i++){
if(($p=strpos($alphabet, $input[$i]))===false){
@ -179,12 +179,12 @@ class FinancialTool {
return false;
}
}
$result = "";
foreach($out as $val){
$result .= chr($val);
}
return $result;
}
}

View File

@ -17,13 +17,13 @@ class JSONConverterTool {
$event['Event']['Attribute'] = $event['Attribute'];
$event['Event']['ShadowAttribute'] = $event['ShadowAttribute'];
$event['Event']['RelatedEvent'] = $event['RelatedEvent'];
if (isset($event['EventTag'])) {
foreach ($event['EventTag'] as $k => $tag) {
$event['Event']['Tag'][$k] = $tag['Tag'];
}
}
if (isset($event['RelatedAttribute'])) $event['Event']['RelatedAttribute'] = $event['RelatedAttribute'];
else $event['Event']['RelatedAttribute'] = array();
//
@ -36,7 +36,7 @@ class JSONConverterTool {
unset($event['Event']['orgc']);
unset($event['Event']['from']);
}
if (isset($event['Event']['Attribute'])) {
// remove value1 and value2 from the output and remove invalid utf8 characters for the xml parser
foreach ($event['Event']['Attribute'] as $key => $value) {
@ -65,7 +65,7 @@ class JSONConverterTool {
if (isset($event['errors'])) $result = array_merge($result, array('errors' => $event['errors']));
return json_encode($result, JSON_PRETTY_PRINT);
}
public function arrayPrinter($array, $root = true) {
if (is_array($array)) {
$resultArray = array();
@ -84,13 +84,13 @@ class JSONConverterTool {
return $text;
} else return $resultArray;
}
public function eventCollection2Format($events, $isSiteAdmin=false) {
$results = array();
foreach ($events as &$event) $results[] = $this->event2JSON($event, $isSiteAdmin);
return implode(',' . PHP_EOL, $results);
}
public function frameCollection($input, $mispVersion = false) {
$result = '{"response":[';
$result .= $input;

View File

@ -1,6 +1,6 @@
<?php
class PubSubTool {
private function __getSetSettings() {
$settings = array(
'redis_host' => 'localhost',
@ -19,7 +19,7 @@ class PubSubTool {
$settingsFile->close();
return $settings;
}
// read the pid file, if it exists, check if the process is actually running
// if either the pid file doesn't exists or the process is not running return false
// otherwise return the pid
@ -32,7 +32,7 @@ class PubSubTool {
if (empty($result)) return false;
return $pid;
}
public function statusCheck() {
$redis = new Redis();
$settings = $this->__getSetSettings();
@ -43,13 +43,13 @@ class PubSubTool {
$response = trim($redis->lPop($settings['redis_namespace'] . ':status'));
return json_decode($response, true);
}
public function checkIfPythonLibInstalled() {
$result = trim(shell_exec('python ' . APP . 'files' . DS . 'scripts' . DS . 'mispzmq' . DS . 'mispzmqtest.py'));
if ($result === "OK") return true;
return false;
}
private function __setupPubServer() {
App::uses('File', 'Utility');
$settings = $this->__getSetSettings();
@ -58,7 +58,7 @@ class PubSubTool {
}
return $settings;
}
public function publishEvent($event) {
$settings = $this->__setupPubServer();
App::uses('JSONConverterTool', 'Tools');
@ -70,7 +70,7 @@ class PubSubTool {
$redis->rPush($settings['redis_namespace'] . ':misp_json', $json);
return true;
}
public function killService($settings = false) {
$redis = new Redis();
if ($this->checkIfRunning()) {
@ -85,7 +85,7 @@ class PubSubTool {
}
return true;
}
// reload the server if it is running, if not, start it
public function reloadServer() {
if (!$this->checkIfRunning()) {
@ -100,7 +100,7 @@ class PubSubTool {
if (!$this->checkIfRunning()) return 'Setting saved, but something is wrong with the ZeroMQ server. Please check the diagnostics page for more information.';
return true;
}
public function restartServer() {
if (!$this->killService()) {
return 'Could not kill the previous instance of the ZeroMQ script.';

View File

@ -15,7 +15,7 @@ class SyncTool {
if (isset($proxy['host']) && !empty($proxy['host'])) $HttpSocket->configProxy($proxy['host'], $proxy['port'], $proxy['method'], $proxy['user'], $proxy['password']);
return $HttpSocket;
}
public function setupHttpSocketFeed($feed = null) {
App::uses('HttpSocket', 'Network/Http');
$HttpSocket = new HttpSocket();

View File

@ -1,9 +1,9 @@
<?php
class XMLConverterTool {
private $__toEscape = array("&", "<", ">", "\"", "'");
private $__escapeWith = array('&amp;', '&lt;', '&gt;', '&quot;', '&apos;');
public function recursiveEcho($array) {
$text = "";
if (is_array($array)) foreach ($array as $k => $v) {
@ -26,7 +26,7 @@ class XMLConverterTool {
}
return $text;
}
public function event2xmlArray($event, $isSiteAdmin=false) {
$event['Event']['Org'][0] = $event['Org'];
$event['Event']['Orgc'][0] = $event['Orgc'];
@ -49,11 +49,11 @@ class XMLConverterTool {
unset($event['ShadowAttribute']);
}
if (isset($event['RelatedEvent'])) if (isset($event['RelatedEvent'])) $event['Event']['RelatedEvent'] = $event['RelatedEvent'];
// legacy
unset($event['Event']['org']);
unset($event['Event']['orgc']);
if (isset($event['EventTag'])) {
foreach ($event['EventTag'] as $k => $tag) {
$event['Event']['Tag'][$k] = $tag['Tag'];
@ -79,7 +79,7 @@ class XMLConverterTool {
if (!Configure::read('MISP.showorg') && !$isSiteAdmin) {
unset($event['Event']['Org'], $event['Event']['Orgc'], $event['Event']['from']);
}
if (isset($event['Event']['Attribute'])) {
// remove value1 and value2 from the output and remove invalid utf8 characters for the xml parser
foreach ($event['Event']['Attribute'] as $key => $value) {
@ -148,25 +148,25 @@ class XMLConverterTool {
if (isset($event['errors']) && !empty($event['errors'])) $result['errors'] = $event['errors'];
return $result;
}
public function event2XML($event, $isSiteAdmin=false) {
$xmlArray = $this->event2xmlArray($event, $isSiteAdmin);
$result = array('Event' => array(0 => $xmlArray['Event']));
if (isset($xmlArray['errors']) && !empty($xmlArray['errors'])) $result['errors'] = array($xmlArray['errors']);
return $this->recursiveEcho($result);
}
private function __sanitizeField(&$field) {
$field = preg_replace ('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $field);
$field = str_replace($this->__toEscape, $this->__escapeWith, $field);
}
public function eventCollection2Format($events, $isSiteAdmin=false) {
$result = "";
foreach ($events as $event) $result .= $this->event2XML($event) . PHP_EOL;
return $result;
}
public function frameCollection($input, $mispVersion = false) {
$result = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL . '<response>' . PHP_EOL;
$result .= $input;

View File

@ -45,14 +45,14 @@ class AppModel extends Model {
$this->name = get_class($this);
}
// major -> minor -> hotfix -> requires_logout
public $db_changes = array(
2 => array(
4 => array(18 => false, 19 => false, 20 => false, 25 => false, 27 => false, 32 => false, 33 => true, 38 => true, 39 => true, 40 => false, 42 => false, 44 => false, 45 => false)
)
);
// Generic update script
// add special cases where the upgrade does more than just update the DB
// this could become useful in the future
@ -81,7 +81,7 @@ class AppModel extends Model {
break;
}
}
private function __addNewFeeds($feeds) {
$this->Feed = ClassRegistry::init('Feed');
$this->Log = ClassRegistry::init('Log');
@ -106,7 +106,7 @@ class AppModel extends Model {
}
$this->Log->save($entry);
}
// SQL scripts for updates
public function updateDatabase($command) {
$sql = '';
@ -167,9 +167,9 @@ class AppModel extends Model {
case '24betaupdates':
$sqlArray = array();
$sqlArray[] = "ALTER TABLE `shadow_attributes` ADD `proposal_to_delete` tinyint(1) NOT NULL DEFAULT '0';";
$sqlArray[] = 'ALTER TABLE `logs` MODIFY `change` text COLLATE utf8_bin NOT NULL;';
$sqlArray[] = "CREATE TABLE IF NOT EXISTS `taxonomies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`namespace` varchar(255) COLLATE utf8_bin NOT NULL,
@ -178,7 +178,7 @@ class AppModel extends Model {
`enabled` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ;";
$sqlArray[] = "CREATE TABLE IF NOT EXISTS `taxonomy_entries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taxonomy_predicate_id` int(11) NOT NULL,
@ -187,7 +187,7 @@ class AppModel extends Model {
PRIMARY KEY (`id`),
KEY `taxonomy_predicate_id` (`taxonomy_predicate_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;";
$sqlArray[] = "CREATE TABLE IF NOT EXISTS `taxonomy_predicates` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`taxonomy_id` int(11) NOT NULL,
@ -196,19 +196,19 @@ class AppModel extends Model {
PRIMARY KEY (`id`),
KEY `taxonomy_id` (`taxonomy_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;";
$sqlArray[] = 'ALTER TABLE `jobs` ADD `org` text COLLATE utf8_bin NOT NULL;';
$sqlArray[] = 'ALTER TABLE `servers` ADD `name` varchar(255) NOT NULL;';
$sqlArray[] = 'ALTER TABLE `sharing_groups` ADD `sync_user_id` INT( 11 ) NOT NULL DEFAULT \'0\' AFTER `org_id`;';
$sqlArray[] = 'ALTER TABLE `users` ADD `disabled` BOOLEAN NOT NULL;';
$sqlArray[] = 'ALTER TABLE `users` ADD `expiration` datetime DEFAULT NULL;';
$sqlArray[] = 'UPDATE `roles` SET `perm_template` = 1 WHERE `perm_site_admin` = 1 OR `perm_admin` = 1';
$sqlArray[] = 'UPDATE `roles` SET `perm_sharing_group` = 1 WHERE `perm_site_admin` = 1 OR `perm_sync` = 1';
//create indexes
break;
case 'indexTables':
@ -228,7 +228,7 @@ class AppModel extends Model {
'threads' => array(array('user_id', 'INDEX'), array('event_id', 'INDEX'), array('org_id', 'INDEX'), array('sharing_group_id', 'INDEX')),
'users' => array(array('org_id', 'INDEX'), array('server_id', 'INDEX'), array('email', 'INDEX')),
);
$version = $this->query('select version();');
$version = $version[0][0]['version()'];
$version = explode('.', $version);
@ -236,7 +236,7 @@ class AppModel extends Model {
$version[1] = intval($version[1]);
$downgrade = true;
if ($version[0] > 5 || ($version[0] == 5 && $version[1] > 5)) $downgrade = false;
// keep the fulltext for now, we can change it later to actually use it once we require MySQL 5.6 / or if we decide to move some tables to MyISAM
foreach ($fieldsToIndex as $table => $fields) {
@ -433,7 +433,7 @@ class AppModel extends Model {
if ($clean) $this->cleanCacheFiles();
return true;
}
private function __dropIndex($table, $field) {
$this->Log = ClassRegistry::init('Log');
$indexCheck = "SELECT INDEX_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='" . $table . "' AND index_name LIKE '" . $field . "%'";
@ -459,7 +459,7 @@ class AppModel extends Model {
));
}
}
public function cleanCacheFiles() {
Cache::clear();
clearCache();
@ -472,7 +472,7 @@ class AppModel extends Model {
}
}
}
public function checkMISPVersion() {
App::uses('Folder', 'Utility');
$file = new File(ROOT . DS . 'VERSION.json', true);
@ -480,7 +480,7 @@ class AppModel extends Model {
$file->close();
return $version_array;
}
// wrapper for UUID generation, compatible with cakephp <= 2.6 and cakephp and cakephp >= 2.7
public function generateUuid() {
$version = Configure::version();
@ -489,7 +489,7 @@ class AppModel extends Model {
else $uuid = CakeText::uuid();
return $uuid;
}
// alternative to the build in notempty/notblank validation functions, compatible with cakephp <= 2.6 and cakephp and cakephp >= 2.7
public function valueNotEmpty($value) {
$field = array_keys($value);
@ -498,7 +498,7 @@ class AppModel extends Model {
if (!empty($value[$field])) return true;
return ucfirst($field) . ' cannot be empty.';
}
public function stringNotEmpty($value) {
$field = array_keys($value);
$field = $field[0];
@ -506,7 +506,7 @@ class AppModel extends Model {
if (!isset($value[$field]) || ($value[$field] == false && $value[$field] !== "0")) return ucfirst($field) . ' cannot be empty.';
return true;
}
public function runUpdates() {
$this->AdminSetting = ClassRegistry::init('AdminSetting');
$db = ConnectionManager::getDataSource('default');
@ -534,7 +534,7 @@ class AppModel extends Model {
$this->updateDatabase('destroyAllSessions');
}
}
private function __queueCleanDB() {
$this->AdminSetting = ClassRegistry::init('AdminSetting');
$cleanDB = $this->AdminSetting->find('first', array('conditions' => array('setting' => 'clean_db')));
@ -546,7 +546,7 @@ class AppModel extends Model {
}
$this->AdminSetting->save($cleanDB);
}
private function __runCleanDB() {
$this->AdminSetting = ClassRegistry::init('AdminSetting');
$cleanDB = $this->AdminSetting->find('first', array('conditions' => array('setting' => 'clean_db')));
@ -561,7 +561,7 @@ class AppModel extends Model {
$this->AdminSetting->save($cleanDB);
}
}
private function __findUpgrades($db_version) {
$version = explode('.', $db_version);
$updates = array();
@ -582,7 +582,7 @@ class AppModel extends Model {
}
return $updates;
}
public function populateNotifications($user) {
$notifications = array();
@ -598,7 +598,7 @@ class AppModel extends Model {
}
return $notifications;
}
private function _getProposalCount($user) {
$this->ShadowAttribute = ClassRegistry::init('ShadowAttribute');
@ -619,7 +619,7 @@ class AppModel extends Model {
$results[1] = count($eventIds);
return $results;
}
private function _getDelegationCount($user) {
$this->EventDelegation = ClassRegistry::init('EventDelegation');
$delegations = $this->EventDelegation->find('count', array(

View File

@ -67,7 +67,7 @@ class Attribute extends AppModel {
public $distributionLevels = array(
0 => 'Your organisation only', 1 => 'This community only', 2 => 'Connected communities', 3 => 'All communities', 4 => 'Sharing group', 5 => 'Inherit event'
);
public $shortDist = array(0 => 'Organisation', 1 => 'Community', 2 => 'Connected', 3 => 'All', 4 => ' sharing Group', 5 => 'Inherit');
// these are definitions of possible types + their descriptions and maybe later other behaviors
@ -82,7 +82,7 @@ class Attribute extends AppModel {
public $uploadDefinitions = array(
'attachment'
);
// skip Correlation for the following types
public $nonCorrelatingTypes = array(
'vulnerability',
@ -246,7 +246,7 @@ class Attribute extends AppModel {
'types' => array('comment', 'text', 'other')
)
);
public $defaultCategories = array(
'md5' => 'Payload delivery',
'sha1' => 'Payload delivery',
@ -276,7 +276,7 @@ class Attribute extends AppModel {
'attachment' => 'External analysis',
'malware-sample' => 'Payload delivery'
);
// typeGroupings are a mapping to high level groups for attributes
// for example, IP addresses, domain names, hostnames and e-mail addresses are network related attribute types
// whilst filenames and hashes are file related attribute types
@ -375,7 +375,7 @@ class Attribute extends AppModel {
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
);
// automatic resolution of complex types
// If the complex type "file" is chosen for example, then the system will try to categorise the values entered into a complex template field based
// on the regular expression rules
@ -389,7 +389,7 @@ class Attribute extends AppModel {
'types' => array('url', 'domain', 'hostname', 'ip-dst'),
),
);
public $typeGroupCategoryMapping = array(
'Payload delviery' => array('File', 'CnC'),
'Payload installation' => array('File'),
@ -423,7 +423,7 @@ class Attribute extends AppModel {
'foreignKey' => 'sharing_group_id'
)
);
public $hashTypes = array(
'md5' => array(
'length' => 32,
@ -467,9 +467,9 @@ class Attribute extends AppModel {
$this->data['Attribute']['value2'] = '';
}
}
if ($this->data['Attribute']['distribution'] != 4) $this->data['Attribute']['sharing_group_id'] = 0;
// update correlation... (only needed here if there's an update)
if ($this->id || !empty($this->data['Attribute']['id'])) {
$this->__beforeSaveCorrelation($this->data['Attribute']);
@ -557,7 +557,7 @@ class Attribute extends AppModel {
if (in_array($fields['category'], $validCategories)) return true;
return false;
}
public function valueIsUnique ($fields) {
if (isset($this->data['Attribute']['deleted']) && $this->data['Attribute']['deleted']) return true;
$value = $fields['value'];
@ -600,7 +600,7 @@ class Attribute extends AppModel {
$value = $fields['value'];
return $this->runValidation($value, $this->data['Attribute']['type']);
}
private $__hexHashLengths = array(
'authentihash' => 64,
'md5' => 32,
@ -615,7 +615,7 @@ class Attribute extends AppModel {
'sha512/224' => 56,
'sha512/256' => 64,
);
public function runValidation($value, $type) {
$returnValue = false;
// check data validation
@ -899,7 +899,7 @@ class Attribute extends AppModel {
}
return $returnValue;
}
// do some last second modifications before the validation
public function modifyBeforeValidation($type, $value) {
switch($type) {
@ -1253,7 +1253,7 @@ class Attribute extends AppModel {
}
return $fails;
}
public function hids($user, $type, $tags = '', $from = false, $to = false, $last = false) {
if (empty($user)) throw new MethodNotAllowedException('Could not read user.');
@ -1298,11 +1298,11 @@ class Attribute extends AppModel {
return $rules;
}
public function nids($user, $format, $id = false, $continue = false, $tags = false, $from = false, $to = false, $last = false) {
if (empty($user)) throw new MethodNotAllowedException('Could not read user.');
$eventIds = $this->Event->fetchEventIds($user, $from, $to, $last);
// If we sent any tags along, load the associated tag names for each attribute
if ($tags) {
$tag = ClassRegistry::init('Tag');
@ -1319,7 +1319,7 @@ class Attribute extends AppModel {
}
}
}
if ($id) {
foreach ($eventIds as $k => $v) {
if ($v['Event']['id'] !== $id) unset($eventIds[$k]);
@ -1328,13 +1328,13 @@ class Attribute extends AppModel {
if ($format == 'suricata') App::uses('NidsSuricataExport', 'Export');
else App::uses('NidsSnortExport', 'Export');
$rules = array();
foreach ($eventIds as $event) {
$conditions['AND'] = array('Attribute.to_ids' => 1, "Event.published" => 1, 'Attribute.event_id' => $event['Event']['id']);
$valid_types = array('ip-dst', 'ip-src', 'email-src', 'email-dst', 'email-subject', 'email-attachment', 'domain', 'hostname', 'url', 'user-agent', 'snort');
$conditions['AND']['Attribute.type'] = $valid_types;
$params = array(
'conditions' => $conditions, // array of conditions
'recursive' => -1, // int
@ -1396,7 +1396,7 @@ class Attribute extends AppModel {
))));
return $attributes;
}
public function rpz($user, $tags = false, $eventId = false, $from = false, $to = false) {
// we can group hostname and domain as well as ip-src and ip-dst in this case
$conditions['AND'] = array('Attribute.to_ids' => 1, 'Event.published' => 1);
@ -1456,7 +1456,7 @@ class Attribute extends AppModel {
}
return $values;
}
public function generateCorrelation($jobId = false, $startPercentage = 0) {
$this->Correlation = ClassRegistry::init('Correlation');
$this->Correlation->deleteAll(array('id !=' => 0), false);
@ -1488,11 +1488,11 @@ class Attribute extends AppModel {
if ($jobId && Configure::read('MISP.background_jobs')) $this->Job->saveField('message', 'Job done.');
return $attributeCount;
}
public function reportValidationIssuesAttributes($eventId) {
$conditions = array();
if ($eventId && is_numeric($eventId)) $conditions = array('event_id' => $eventId);
// get all attributes..
$attributes = $this->find('all', array('recursive' => -1, 'fields' => array('id'), 'conditions' => $conditions));
// for all attributes..
@ -1514,7 +1514,7 @@ class Attribute extends AppModel {
}
return $result;
}
// This method takes a string from an argument with several elements (separated by '&&' and negated by '!') and returns 2 arrays
// array 1 will have all of the non negated terms and array 2 all the negated terms
public function dissectArgs($args) {
@ -1537,7 +1537,7 @@ class Attribute extends AppModel {
$result[1] = $reject;
return $result;
}
public function checkForValidationIssues($attribute) {
$this->set($attribute);
if ($this->validates()) {
@ -1546,8 +1546,8 @@ class Attribute extends AppModel {
return $this->validationErrors;
}
}
public function checkTemplateAttributes($template, &$data, $event_id) {
$result = array();
$errors = array();
@ -1589,7 +1589,7 @@ class Attribute extends AppModel {
}
return array('attributes' => $attributes, 'errors' => $errors);
}
private function __resolveElementAttribute($element, $value) {
$attributes = array();
@ -1619,7 +1619,7 @@ class Attribute extends AppModel {
}
return array('attributes' => $results, 'errors' => $errors);
}
private function __resolveElementFile($element, $files) {
$attributes = array();
$errors = null;
@ -1695,7 +1695,7 @@ class Attribute extends AppModel {
}
return $attribute;
}
public function buildConditions($user) {
$conditions = array();
if (!$user['Role']['perm_site_admin']) {
@ -1727,7 +1727,7 @@ class Attribute extends AppModel {
}
return $conditions;
}
// Method that fetches all attributes for the various exports
// very flexible, it's basically a replacement for find, with the addition that it restricts access based on user
// options:
@ -1766,7 +1766,7 @@ class Attribute extends AppModel {
}
return $results;
}
// Method gets and converts the contents of a file passed along as a base64 encoded string with the original filename into a zip archive
// The zip archive is then passed back as a base64 encoded string along with the md5 hash and a flag whether the transaction was successful
// The archive is password protected using the "infected" password
@ -1798,7 +1798,7 @@ class Attribute extends AppModel {
$contentsFile->delete();
return $result;
}
private function __hashRouter($hashType, $file) {
$validHashes = array('md5', 'sha1', 'sha256');
if (!in_array($hashType, $validHashes)) return false;
@ -1811,7 +1811,7 @@ class Attribute extends AppModel {
}
return false;
}
public function generateRandomFileName() {
$length = 12;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
@ -1822,7 +1822,7 @@ class Attribute extends AppModel {
}
return $fn;
}
public function resolveHashType($hash) {
$hashTypes = $this->hashTypes;
$validTypes = array();
@ -1833,7 +1833,7 @@ class Attribute extends AppModel {
}
return $validTypes;
}
public function validateAttribute($attribute, $context = true) {
$this->set($attribute);
if (!$context) {
@ -1845,7 +1845,7 @@ class Attribute extends AppModel {
return $this->validationErrors;
}
}
public function restore($id, $user) {
$this->id = $id;
if (!$this->exists()) return 'Attribute doesn\'t exist, or you lack the permission to edit it.';

View File

@ -7,9 +7,9 @@ App::uses('Regexp', 'Model');
*
*/
class RegexpBehavior extends ModelBehavior {
private $__allRegexp = array();
public function setup(Model $model, $config = null) {
$regexp = new Regexp();
$this->__allRegexp = $regexp->find('all');

View File

@ -28,7 +28,7 @@ class Event extends AppModel {
public $displayField = 'id';
public $virtualFields = array();
public $mispVersion = '2.4.0';
/**
@ -57,7 +57,7 @@ class Event extends AppModel {
2 => array('desc' => 'This field determines the current distribution of the event', 'formdesc' => "Users that are part of your MISP community will be able to see the event. This includes all organisations on this MISP server, all organisations on MISP servers synchronising with this server and the hosting organisations of servers that connect to those afore mentioned servers (so basically any server that is 2 hops away from this one). Any other organisations connected to linked servers that are 2 hops away from this will be restricted from seeing the event. Use this option if this server isn't the central MISP hub of the community but is connected to it."),
3 => array('desc' => 'This field determines the current distribution of the event', 'formdesc' => "This will share the event with all MISP communities, allowing the event to be freely propagated from one server to the next."),
4 => array('desc' => 'This field determines the current distribution of the event', 'formdesc' => "This distribution of this event will be handled by the selected sharing group."),
);
public $analysisLevels = array(
@ -67,7 +67,7 @@ class Event extends AppModel {
public $distributionLevels = array(
0 => 'Your organisation only', 1 => 'This community only', 2 => 'Connected communities', 3 => 'All communities', 4 => 'Sharing group'
);
public $shortDist = array(0 => 'Organisation', 1 => 'Community', 2 => 'Connected', 3 => 'All', 4 => ' sharing Group');
public $export_types = array(
@ -117,7 +117,7 @@ class Event extends AppModel {
'description' => 'Click on one of the buttons below to download all the attributes with the matching type. This list can be used to feed forensic software when searching for susipicious files. Only published events and attributes marked as IDS Signature are exported.'
),
);
public $csv_event_context_fields_to_fetch = array(
'event_info' => array('object' => false, 'var' => 'info'),
'event_member_org' => array('object' => 'Org', 'var' => 'name'),
@ -128,7 +128,7 @@ class Event extends AppModel {
'event_date' => array('object' => false, 'var' => 'date'),
'event_tag' => array('object' => 'Tag', 'var' => 'name')
);
/**
* Validation rules
*
@ -177,14 +177,14 @@ class Event extends AppModel {
//'on' => 'create', // Limit validation to 'create' or 'update' operations
)
),
'sharing_group_id' => array(
'rule' => array('sharingGroupRequired'),
'message' => 'If the distribution is set to "Sharing Group", a sharing group has to be selected.',
//'required' => true,
//'allowEmpty' => true
),
'analysis' => array(
'rule' => array('inList', array('0', '1', '2')),
'message' => 'Options : 0, 1, 2 (for Initial, Ongoing, Completed)',
@ -325,10 +325,10 @@ class Event extends AppModel {
$orgc = $this->Orgc->find('first', array('conditions' => array('Orgc.id' => $this->data['Event']['orgc_id']), 'recursive' => -1, 'fields' => array('Orgc.name')));
$this->EventBlacklist->save(array('event_uuid' => $this->data['Event']['uuid'], 'event_info' => $this->data['Event']['info'], 'event_orgc' => $orgc['Orgc']['name']));
}
// delete all of the event->tag combinations that involve the deleted event
$this->EventTag->deleteAll(array('event_id' => $this->id));
// FIXME secure this filesystem access/delete by not allowing to change directories or go outside of the directory container.
// only delete the file if it exists
$filepath = APP . "files" . DS . $this->id;
@ -380,14 +380,14 @@ class Event extends AppModel {
$date = new DateTime();
$this->data['Event']['timestamp'] = $date->getTimestamp();
}
if (empty($this->data['Event']['date'])) {
$this->data['Event']['date'] = date('Y-m-d');
}
if (!isset($this->data['Event']['distribution']) || $this->data['Event']['distribution'] != 4) $this->data['Event']['sharing_group_id'] = 0;
}
public function afterSave($created, $options = array()) {
if (!$created) {
$this->Correlation = ClassRegistry::init('Correlation');
@ -406,7 +406,7 @@ class Event extends AppModel {
public function isOwnedByOrg($eventid, $org) {
return $this->field('id', array('id' => $eventid, 'org_id' => $org)) === $eventid;
}
// gets the logged in user + an array of events, attaches the correlation count to each
public function attachCorrelationCountToEvents($user, &$events) {
$sgids = $this->SharingGroup->fetchAllAuthorised($user);
@ -423,7 +423,7 @@ class Event extends AppModel {
$correlations = Hash::combine($correlations, '{n}.Correlation.1_event_id', '{n}.0.count');
foreach ($events as &$event) $event['Event']['correlation_count'] = (isset($correlations[$event['Event']['id']])) ? $correlations[$event['Event']['id']] : 0;
}
private function __buildEventConditionsCorrelation($user, $eventIds, $sgids) {
if (!is_array($eventIds)) $eventIds = array($eventIds);
if (!$user['Role']['perm_site_admin']) {
@ -526,7 +526,7 @@ class Event extends AppModel {
);
return $relatedEvents;
}
public function getRelatedAttributes($user, $id = null, $sgids, $shadowAttribute = false) {
$context = $shadowAttribute ? 'ShadowAttribute' : 'Attribute';
$settings = array(
@ -580,7 +580,7 @@ class Event extends AppModel {
),
)
)
)
);
} else {
@ -634,7 +634,7 @@ class Event extends AppModel {
}
return $data;
}
private function __resolveErrorCode($code, &$event, &$server) {
$error = false;
switch ($code) {
@ -661,7 +661,7 @@ class Event extends AppModel {
}
return $error;
}
public function uploadEventToServer($event, $server, $HttpSocket = null) {
$this->Server = ClassRegistry::init('Server');
$push = $this->Server->checkVersionCompatibility($server['Server']['id']);
@ -773,8 +773,8 @@ class Event extends AppModel {
}
return true;
}
/**
* Uploads the event and the associated Attributes to another Server
* TODO move this to a component
@ -863,7 +863,7 @@ class Event extends AppModel {
}
}
}
private function __updateEventForSync($event, $server) {
$mangle = isset($event['mangle']);
if (!$mangle) {
@ -875,13 +875,13 @@ class Event extends AppModel {
unset($event[$o]);
}
}
// cleanup the array from things we do not want to expose
foreach (array('Org', 'org_id', 'orgc_id', 'proposal_email_lock', 'org', 'orgc') as $field) unset($event['Event'][$field]);
foreach ($event['Event']['EventTag'] as $kt => $tag) {
if (!$tag['Tag']['exportable']) unset($event['Event']['EventTag'][$kt]);
}
// Add the local server to the list of instances in the SG
if (isset($event['Event']['SharingGroup']) && isset($event['Event']['SharingGroup']['SharingGroupServer'])) {
foreach ($event['Event']['SharingGroup']['SharingGroupServer'] as &$s) {
@ -906,7 +906,7 @@ class Event extends AppModel {
if ($attribute['distribution'] == 2) {
$attribute['distribution'] = 1;
}
// If the attribute has a sharing group attached, make sure it can be transfered
if ($attribute['distribution'] == 4) {
if ($this->checkDistributionForPush(array('Attribute' => $attribute), $server, 'Attribute') === false) {
@ -922,7 +922,7 @@ class Event extends AppModel {
}
}
}
// remove value1 and value2 from the output
unset($attribute['value1']);
unset($attribute['value2']);
@ -938,7 +938,7 @@ class Event extends AppModel {
unset($attribute['id']);
}
}
if ($mangle) {
$event['Event']['timestamp'] = $event['Event']['timestamp'] -1;
if (isset($event['Attribute'])) {
@ -969,14 +969,14 @@ class Event extends AppModel {
}
}
}
// Downgrade the event from connected communities to community only
if ($event['Event']['distribution'] == 2) {
$event['Event']['distribution'] = 1;
}
return $event;
}
/**
* Deletes the event and the associated Attributes from another Server
@ -1051,7 +1051,7 @@ class Event extends AppModel {
return null;
}
}
public function downloadProposalsFromServer($uuidList, $server, $HttpSocket = null) {
$url = $server['Server']['url'];
$authkey = $server['Server']['authkey'];
@ -1106,13 +1106,13 @@ class Event extends AppModel {
);
}
$fields = array('Event.id', 'Event.org_id', 'Event.distribution', 'Event.sharing_group_id');
if ($from) $conditions['AND'][] = array('Event.date >=' => $from);
if ($to) $conditions['AND'][] = array('Event.date <=' => $to);
if ($last) $conditions['AND'][] = array('Event.publish_timestamp >=' => $last);
if ($timestamp) $conditions['AND'][] = array('Event.timestamp >=' => $timestamp);
if ($publish_timestamp) $conditions['AND'][] = array('Event.publish_timestamp >=' => $publish_timestamp);
if ($list) {
$params = array(
'conditions' => $conditions,
@ -1154,7 +1154,7 @@ class Event extends AppModel {
$isSiteAdmin = $user['Role']['perm_site_admin'];
if (isset($options['disableSiteAdmin']) && $options['disableSiteAdmin']) $isSiteAdmin = false;
$conditionsAttributes = array();
// restricting to non-private or same org if the user is not a site-admin.
if (!$isSiteAdmin) {
$sgids = $this->SharingGroup->fetchAllAuthorised($user);
@ -1187,7 +1187,7 @@ class Event extends AppModel {
));
$conditions['AND']['OR']['Event.id'] = $delegatedEventIDs;
}
$conditionsAttributes['AND'][0]['OR'] = array(
array('AND' => array(
'Attribute.distribution >' => 0,
@ -1206,7 +1206,7 @@ class Event extends AppModel {
if ($options['to']) $conditions['AND'][] = array('Event.date <=' => $options['to']);
if ($options['last']) $conditions['AND'][] = array('Event.publish_timestamp >=' => $options['last']);
if ($options['event_uuid']) $conditions['AND'][] = array('Event.uuid' => $options['event_uuid']);
if (isset($options['deleted']) && $options['deleted']) {
if (!$user['Role']['perm_sync']) {
$conditionsAttributes['AND'][] = array(
@ -1217,7 +1217,7 @@ class Event extends AppModel {
);
}
} else $conditionsAttributes['AND']['Attribute.deleted'] = false;
if ($options['idList'] && !$options['tags']) {
$conditions['AND'][] = array('Event.id' => $options['idList']);
}
@ -1237,7 +1237,7 @@ class Event extends AppModel {
}
$conditions['AND'][] = $temp;
}
if ($options['to_ids']) {
$conditionsAttributes['AND'][] = array('Attribute.to_ids' => 1);
}
@ -1247,7 +1247,7 @@ class Event extends AppModel {
// Same idea for the published. Just adjust the tools to check for this
// TODO: It is important to make sure that this is documented
// $conditions['AND'][] = array('Event.published =' => 1);
// do not expose all the data ...
$fields = array('Event.id', 'Event.orgc_id', 'Event.org_id', 'Event.date', 'Event.threat_level_id', 'Event.info', 'Event.published', 'Event.uuid', 'Event.attribute_count', 'Event.analysis', 'Event.timestamp', 'Event.distribution', 'Event.proposal_email_lock', 'Event.user_id', 'Event.locked', 'Event.publish_timestamp', 'Event.sharing_group_id');
$fieldsAtt = array('Attribute.id', 'Attribute.type', 'Attribute.category', 'Attribute.value', 'Attribute.to_ids', 'Attribute.uuid', 'Attribute.event_id', 'Attribute.distribution', 'Attribute.timestamp', 'Attribute.comment', 'Attribute.sharing_group_id', 'Attribute.deleted');
@ -1269,7 +1269,7 @@ class Event extends AppModel {
);
if (!$options['includeAllTags']) $tagConditions = array('exportable' => 1);
else $tagConditions = array();
$params = array('conditions' => $conditions,
'recursive' => 0,
'fields' => $fields,
@ -1382,7 +1382,7 @@ class Event extends AppModel {
if ($last) $conditions['AND'][] = array('Event.publish_timestamp >=' => $last);
// This is for both single event downloads and for full downloads. Org has to be the same as the user's or distribution not org only - if the user is no siteadmin
if ($ignore == false) $conditions['AND'][] = array('Event.published' => 1);
// If we sent any tags along, load the associated tag names for each attribute
if ($tags) {
$tag = ClassRegistry::init('Tag');
@ -1401,13 +1401,13 @@ class Event extends AppModel {
}
// if we're downloading a single event, set it as a condition
if ($eventid) $conditions['AND'][] = array('Event.id' => $eventid);
//restricting to non-private or same org if the user is not a site-admin.
if (!$ignore) $conditions['AND'][] = array('Attribute.to_ids' => 1);
if ($type) $conditions['AND'][] = array('Attribute.type' => $type);
if ($category) $conditions['AND'][] = array('Attribute.category' => $category);
}
if ($eventid === 'search') {
foreach ($attributeIDList as $aID) $conditions['AND']['OR'][] = array('Attribute.id' => $aID);
}
@ -1416,7 +1416,7 @@ class Event extends AppModel {
'fields' => array('Attribute.event_id', 'Attribute.distribution', 'Attribute.category', 'Attribute.type', 'Attribute.value', 'Attribute.comment', 'Attribute.uuid', 'Attribute.to_ids', 'Attribute.timestamp', 'Attribute.id'),
'order' => array('Attribute.uuid ASC')
);
if ($includeContext) {
$params['contain'] = array(
'Event' => array(
@ -1458,7 +1458,7 @@ class Event extends AppModel {
}
return $attributes;
}
private function attachEventInfoToAttributes($attributes, $user) {
$TLs = $this->ThreatLevel->find('list', array(
'recursive' => -1,
@ -1476,7 +1476,7 @@ class Event extends AppModel {
$context_fields['orgc_id'] = 'event_org_id';
unset($context_fields['org_id']);
}
$events = $this->find('all', array(
'recursive' => -1,
'fields' => array_keys($context_fields),
@ -1507,7 +1507,7 @@ class Event extends AppModel {
}
return $attributes;
}
public function sendAlertEmailRouter($id, $user) {
if (Configure::read('MISP.block_old_event_alert') && Configure::read('MISP.block_old_event_alert_age') && is_numeric(Configure::read('MISP.block_old_event_alert_age'))) {
$oldest = time() - (Configure::read('MISP.block_old_event_alert_age') * 86400);
@ -1545,7 +1545,7 @@ class Event extends AppModel {
return ($this->sendAlertEmail($id, $user));
}
}
public function sendAlertEmail($id, $senderUser, $processId = null) {
$event = $this->fetchEvent($senderUser, array('eventid' => $id, 'includeAllTags' => true));
if (empty($event)) throw new MethodNotFoundException('Invalid Event.');
@ -1571,7 +1571,7 @@ class Event extends AppModel {
$subject = '';
}
$subject = "[" . Configure::read('MISP.org') . " MISP] Event " . $id . " - " . $subject . $event[0]['ThreatLevel']['name'] . " - TLP Amber";
// Initialise the Job class if we have a background process ID
// This will keep updating the process's progress bar
if ($processId) {
@ -1596,7 +1596,7 @@ class Event extends AppModel {
}
return true;
}
private function __buildAlertEmailBody($event, $user, $sgModel) {
$owner = false;
if ($user['org_id'] == $event['Event']['orgc_id'] || $user['org_id'] == $event['Event']['org_id'] || $user['Role']['perm_site_admin']) $owner = true;
@ -1656,7 +1656,7 @@ class Event extends AppModel {
elseif ('hostname' == $attribute['type'] or 'domain' == $attribute['type'] or 'ip-src' == $attribute['type'] or 'ip-dst' == $attribute['type']) {
$line = str_replace(".","[.]", $line);
}
if ('other' == $attribute['type']) // append the 'other' attribute types to the bottom.
$bodyTempOther .= $line;
else $body .= $line;
@ -1669,7 +1669,7 @@ class Event extends AppModel {
$body .= '==============================================' . "\n";
return $body;
}
public function sendContactEmail($id, $message, $creator_only, $user, $isSiteAdmin) {
// fetch the event
$event = $this->read(null, $id);
@ -1721,7 +1721,7 @@ class Event extends AppModel {
$body .= "\n";
$body .= "\n";
$body .= "The event is the following: \n";
// print the event in mail-format
// LATER place event-to-email-layout in a function
$appendlen = 20;
@ -1734,17 +1734,17 @@ class Event extends AppModel {
}
$bodyevent .= 'Risk : ' . $event['ThreatLevel']['name'] . "\n";
$bodyevent .= 'Analysis : ' . $event['Event']['analysis'] . "\n";
$userModel = ClassRegistry::init('User');
$targetUser = $userModel->getAuthUser($orgMembers[0]['User']['id']);
$sgModel = ClassRegistry::init('SharingGroup');
$sgs = $sgModel->fetchAllAuthorised($targetUser, false);
$relatedEvents = $this->getRelatedEvents($targetUser, $id, $sgs);
if (!empty($relatedEvents)) {
foreach ($relatedEvents as &$relatedEvent) {
$bodyevent .= 'Related to : ' . Configure::read('MISP.baseurl') . '/events/view/' . $relatedEvent['Event']['id'] . ' (' . $relatedEvent['Event']['date'] . ')' . "\n";
}
}
$bodyevent .= 'Info : ' . "\n";
@ -1769,7 +1769,7 @@ class Event extends AppModel {
}
return $result;
}
// When we receive an event via REST, we might end up with organisations, sharing groups, tags that we do not know
// or which we need to update. All of that is controller in this method.
private function __captureObjects($data, $user) {
@ -1784,7 +1784,7 @@ class Event extends AppModel {
if (isset($attribute['distribution']) && $attribute['distribution'] == 4 && !isset($sgs[$attribute['SharingGroup']['uuid']])) $sgs[$attribute['SharingGroup']['uuid']] = $attribute['SharingGroup'];
}
}
if ($data['Event']['distribution'] == 4) {
$sg = $this->SharingGroup->captureSG($data['Event']['SharingGroup'], $user);
if ($sg===false){
@ -1838,7 +1838,7 @@ class Event extends AppModel {
}
return $data;
}
/**
* Low level function to add an Event based on an Event $data array
*
@ -1946,7 +1946,7 @@ class Event extends AppModel {
}
}
}
if ($fromXml) $created_id = $this->id;
if (!empty($data['Event']['published']) && 1 == $data['Event']['published']) {
// do the necessary actions to publish the event (email, upload,...)
@ -1961,12 +1961,12 @@ class Event extends AppModel {
return json_encode($this->validationErrors);
}
}
public function _edit(&$data, $user, $id, $jobId = null) {
$data = $this->cleanupEventArrayFromXML($data);
unset($this->Attribute->validate['event_id']);
unset($this->Attribute->validate['value']['unique']); // otherwise gives bugs because event_id is not set
// reposition to get the event.id with given uuid
if (isset($data['Event']['uuid'])) $existingEvent = $this->findByUuid($data['Event']['uuid']);
else $existingEvent = $this->findById($id);
@ -2126,7 +2126,7 @@ class Event extends AppModel {
return true;
} return $this->validationErrors;
}
// format has to be:
// array('Event' => array(), 'Attribute' => array('ShadowAttribute' => array()), 'EventTag' => array(), 'ShadowAttribute' => array());
public function savePreparedEvent($event) {
@ -2143,7 +2143,7 @@ class Event extends AppModel {
}
return $event['Event']['id'];
}
private function __savePreparedAttribute(&$attribute, &$event) {
unset($attribute['id']);
$attribute['event_id'] = $event['Event']['id'];
@ -2153,7 +2153,7 @@ class Event extends AppModel {
$this->__savePreparedShadowAttribute($sa, $event, $this->Attribute->id);
}
}
private function __savePreparedShadowAttribute($shadow_attribute, &$event, $old_id = 0) {
unset($shadow_attribute['id']);
$shadow_attribute['event_id'] = $event['Event']['id'];
@ -2161,21 +2161,21 @@ class Event extends AppModel {
$this->ShadowAttribute->create();
$this->ShadowAttribute->save($shadow_attribute);
}
private function __savePreparedEventTag($event_tag, &$event) {
unset($event_tag['id']);
$event_tag['event_id'] = $event['Event']['id'];
$this->EventTag->create();
$this->EventTag->save($event_tag);
}
private function __searchUuidInAttributeArray($uuid, &$attr_array) {
foreach ($attr_array['Attribute'] as &$attr) {
if ($attr['uuid'] == $uuid) return array('Attribute' => $attr);
}
return false;
}
// pass an event or an attribute together with the server id.
// If the distribution of the object outright allows for it to be shared, return true
// If the distribution is org only / comm only, return false
@ -2192,7 +2192,7 @@ class Event extends AppModel {
}
return true;
}
/**
* Uploads this specific event to all remote servers
* TODO move this to a component
@ -2255,7 +2255,7 @@ class Event extends AppModel {
// iterate over the servers and upload the event
if(empty($servers))
return true;
$uploaded = true;
$failedServers = array();
App::uses('SyncTool', 'Tools');
@ -2309,7 +2309,7 @@ class Event extends AppModel {
return $result;
}
}
/**
* Performs all the actions required to publish an event
*
@ -2346,7 +2346,7 @@ class Event extends AppModel {
}
return $uploaded;
}
/**
*
@ -2391,7 +2391,7 @@ class Event extends AppModel {
return $result;
}
}
public function generateLocked() {
$this->User = ClassRegistry::init('User');
$this->User->recursive = -1;
@ -2430,7 +2430,7 @@ class Event extends AppModel {
);
return $toBeUpdated;
}
public function reportValidationIssuesEvents() {
$this->Behaviors->detach('Regexp');
// get all events..
@ -2452,7 +2452,7 @@ class Event extends AppModel {
}
return array($result, $k);
}
public function generateThreatLevelFromRisk() {
$risk = array('Undefined' => 4, 'Low' => 3, 'Medium' => 2, 'High' => 1);
$events = $this->find('all', array('recursive' => -1));
@ -2464,12 +2464,12 @@ class Event extends AppModel {
}
return $k;
}
// check two version strings. If version 1 is older than 2, return -1, if they are the same return 0, if version 2 is older return 1
public function compareVersions($version1, $version2) {
$version1Array = explode('.', $version1);
$version2Array = explode('.', $version2);
if ($version1Array[0] != $version2Array[0]) {
if ($version1Array[0] > $version2Array[0]) return 1;
else return -1;
@ -2483,14 +2483,14 @@ class Event extends AppModel {
else return -1;
}
}
// main dispatch method for updating an incoming xmlArray - pass xmlArray to all of the appropriate transformation methods to make all the changes necessary to save the imported event
public function updateXMLArray($xmlArray, $response = true) {
if (isset($xmlArray['xml_version']) && $response) {
$xmlArray['response']['xml_version'] = $xmlArray['xml_version'];
unset($xmlArray['xml_version']);
}
if (!$response) {
$xmlArray = array('response' => $xmlArray);
}
@ -2502,11 +2502,11 @@ class Event extends AppModel {
if ($version != 0) {
// The xml is from an instance that is newer than the local instance, let the user know that the admin needs to upgrade before it could be imported
if ($version == 1) throw new Exception('This XML file is from a MISP instance that is newer than the current instance. Please contact your administrator about upgrading this instance.');
// if the xml contains an event or events from an older MISP instance, let's try to upgrade it!
// Let's manually set the version to something below 2.2.0 if there is no version set in the xml
if (!isset($xmlArray['response']['xml_version'])) $xmlArray['response']['xml_version'] = '2.1.0';
// Upgrade from versions below 2.2.0 will need to replace the risk field with threat level id
if ($this->compareVersions($xmlArray['response']['xml_version'], '2.2.0') < 0) {
if ($response) $xmlArray['response'] = $this->__updateXMLArray220($xmlArray['response']);
@ -2534,13 +2534,13 @@ class Event extends AppModel {
}
return $xmlArray;
}
public function checkIfNewer($incomingEvent) {
$localEvent = $this->find('first', array('conditions' => array('uuid' => $incomingEvent['uuid']), 'recursive' => -1, 'fields' => array('Event.uuid', 'Event.timestamp')));
if (empty($localEvent) || $incomingEvent['timestamp'] > $localEvent['Event']['timestamp']) return true;
return false;
}
public function removeOlder(&$eventArray) {
$uuidsToCheck = array();
foreach ($eventArray as $k => &$event) {
@ -2579,7 +2579,7 @@ class Event extends AppModel {
// generate a randomised filename for the temporary file that will be passed to the python script
$randomFileName = $this->generateRandomFileName();
$tempFile = new File(APP . "files" . DS . "scripts" . DS . "tmp" . DS . $randomFileName, true, 0644);
// save the json_encoded event(s) to the temporary file
$result = $tempFile->write(json_encode($events));
$scriptFile = APP . "files" . DS . "scripts" . DS . "misp2stix.py";
@ -2593,7 +2593,7 @@ class Event extends AppModel {
$result = array();
$result['success'] = $decoded->success;
$result['message'] = $decoded->message;
if ($result['success'] == 1) {
$file = new File(APP . "files" . DS . "scripts" . DS . "tmp" . DS . $randomFileName . ".out");
$result['data'] = $file->read();
@ -2603,10 +2603,10 @@ class Event extends AppModel {
$file->delete();
return $result;
}
public function getAccessibleEventIds($include, $exclude, $includedTags, $excludedTags) {
$conditions = array();
// get all of the event IDs based on include / exclude
if (!empty($include)) $conditions['OR'] = array('id' => $include);
if (!empty($exclude)) $conditions['NOT'] = array('id' => $exclude);
@ -2627,7 +2627,7 @@ class Event extends AppModel {
}
return $ids;
}
public function generateRandomFileName() {
$length = 12;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
@ -2638,7 +2638,7 @@ class Event extends AppModel {
}
return $fn;
}
public function sharingGroupRequired($field) {
if ($this->data[$this->alias]['distribution'] == 4) {
@ -2646,7 +2646,7 @@ class Event extends AppModel {
}
return true;
}
// convenience method to check whther a user can see an event
public function checkIfAuthorised($user, $id) {
if (!isset($user['id'])) throw new MethodNotAllowedException('Invalid user.');
@ -2670,7 +2670,7 @@ class Event extends AppModel {
// regex check for from / to field by stevengoossensB
return (preg_match('/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])$/', $date)) ? $date : false;
}
public function resolveTimeDelta($delta) {
$multiplierArray = array('d' => 86400, 'h' => 3600, 'm' => 60);
$multiplier = $multiplierArray['d'];
@ -2682,7 +2682,7 @@ class Event extends AppModel {
if (!is_numeric($delta)) return false;
return time() - ($delta * $multiplier);
}
public function rearrangeEventForView(&$event, $passedArgs = array(), $all = false) {
$fTool = new FinancialTool();
foreach ($event['Event'] as $k => $v) {
@ -2726,7 +2726,7 @@ class Event extends AppModel {
$customPagination = new CustomPaginationTool();
if ($all) $passedArgs['page'] = 0;
$eventArrayWithProposals = array();
foreach ($eventArray as $k => &$object) {
if ($object['category'] === 'Financial fraud') {
if (!$fTool->validateRouter($object['type'], $object['value'])) {
@ -2763,7 +2763,7 @@ class Event extends AppModel {
$params = $customPagination->applyRulesOnArray($event['objects'], $passedArgs, 'events', 'category');
return $params;
}
// pass along a json from the server filter rules
// returns a conditions set to be merged into pagination / event fetch / etc
public function filterRulesToConditions($rules) {

View File

@ -4,7 +4,7 @@ App::uses('AppModel', 'Model');
class EventDelegation extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
'event_id' => array(
'valueNotEmpty' => array(
@ -17,7 +17,7 @@ class EventDelegation extends AppModel {
),
)
);
public $belongsTo = array(
'Event' => array(
'className' => 'Event',
@ -47,7 +47,7 @@ class EventDelegation extends AppModel {
}
return true;
}
public function transferEvent($delegation, $user) {
$this->Event->Attribute->bindModel(
array(
@ -82,7 +82,7 @@ class EventDelegation extends AppModel {
$event_id = $this->Event->savePreparedEvent($event);
return $event_id;
}
private function __prepareEvent(&$event) {
$objects = array('Attribute', 'ShadowAttribute', 'EventTag');
$objects = array(
@ -102,7 +102,7 @@ class EventDelegation extends AppModel {
$object['data'] = $encodedFile;
}
}
// unset ID fields and relations
foreach ($fields as $field) {
unset($object[$field]);

View File

@ -4,7 +4,7 @@ App::uses('AppModel', 'Model');
class EventTag extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
'event_id' => array(
'valueNotEmpty' => array(
@ -17,7 +17,7 @@ class EventTag extends AppModel {
),
),
);
public $belongsTo = array(
'Event' => array(
'className' => 'Event',
@ -26,7 +26,7 @@ class EventTag extends AppModel {
'className' => 'Tag',
),
);
// take an array of tag names to be included and an array with tagnames to be excluded and find all event IDs that fit the criteria
public function getEventIDsFromTags($includedTags, $excludedTags) {
$conditions = array();
@ -52,7 +52,7 @@ class EventTag extends AppModel {
$eventIDs = array_unique($eventIDs);
return $eventIDs;
}
public function attachTagToEvent($event_id, $tag_id) {
$existingAssociation = $this->find('first', array(
'recursive' => -1,

View File

@ -4,7 +4,7 @@ App::uses('AppModel', 'Model');
class FavouriteTag extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
'user_id' => array(
'valueNotEmpty' => array(
@ -17,6 +17,6 @@ class FavouriteTag extends AppModel {
),
),
);
public $belongsTo = array('Tag', 'User');
}

View File

@ -9,7 +9,7 @@ class Feed extends AppModel {
'Trim',
'Containable'
);
public $belongsTo = array(
'SharingGroup' => array(
'className' => 'SharingGroup',
@ -20,7 +20,7 @@ class Feed extends AppModel {
'foreignKey' => 'tag_id',
)
);
/**
* Validation rules
*
@ -42,7 +42,7 @@ class Feed extends AppModel {
),
),
);
// gets the event UUIDs from the feed by ID
// returns an array with the UUIDs of events that are new or that need updating
public function getNewEventUuids($feed, $HttpSocket) {
@ -68,8 +68,8 @@ class Feed extends AppModel {
$result['add'] = array_keys($manifest);
return $result;
}
public function getManifest($feed, $HttpSocket) {
$result = array();
$request = $this->__createFeedRequest();
@ -83,7 +83,7 @@ class Feed extends AppModel {
$events = $this->__filterEventsIndex($events, $feed);
return $events;
}
public function downloadFromFeed($actions, $feed, $HttpSocket, $user, $jobId = false) {
if ($jobId) {
$job = ClassRegistry::init('Job');
@ -134,7 +134,7 @@ class Feed extends AppModel {
}
return $results;
}
private function __createFeedRequest() {
$version = $this->checkMISPVersion();
$version = implode('.', $version);
@ -146,7 +146,7 @@ class Feed extends AppModel {
)
);
}
private function __checkIfEventBlockedByFilter($event, $filterRules) {
$fields = array('tags' => 'Tag', 'orgs' => 'Orgc');
$prefixes = array('OR', 'NOT');
@ -170,7 +170,7 @@ class Feed extends AppModel {
if (!$filterRules) return true;
return true;
}
private function __filterEventsIndex($events, $feed) {
$filterRules = array();
if (isset($feed['Feed']['rules']) && !empty($feed['Feed']['rules'])) {
@ -212,13 +212,13 @@ class Feed extends AppModel {
}
return $events;
}
public function downloadAndSaveEventFromFeed($feed, $uuid, $user) {
$event = $this->downloadEventFromFeed($feed, $uuid, $user);
if (!is_array($event) || isset($event['code'])) return false;
return $this->__saveEvent($event, $user);
}
public function downloadEventFromFeed($feed, $uuid, $user) {
$HttpSocket = $this->__setupHttpSocket($feed);
$request = $this->__createFeedRequest();
@ -230,7 +230,7 @@ class Feed extends AppModel {
return $this->__prepareEvent($response->body, $feed);
}
}
private function __saveEvent($event, $user) {
$this->Event = ClassRegistry::init('Event');
$existingEvent = $this->Event->find('first', array(
@ -250,7 +250,7 @@ class Feed extends AppModel {
}
return $result;
}
private function __prepareEvent($body, $feed) {
$filterRules = $this->__prepareFilterRules($feed);
$event = json_decode($body, true);
@ -289,19 +289,19 @@ class Feed extends AppModel {
if (!$this->__checkIfEventBlockedByFilter($event, $filterRules)) return 'blocked';
return $event;
}
private function __prepareFilterRules($feed) {
$filterRules = false;
if (isset($feed['Feed']['rules']) && !empty($feed['Feed']['rules'])) $filterRules = json_decode($feed['Feed']['rules'], true);
return $filterRules;
}
private function __setupHttpSocket($feed) {
App::uses('SyncTool', 'Tools');
$syncTool = new SyncTool();
return ($syncTool->setupHttpSocketFeed($feed));
}
private function __addEventFromFeed($HttpSocket, $feed, $uuid, $user, $filterRules) {
$request = $this->__createFeedRequest();
$uri = $feed['Feed']['url'] . '/' . $uuid . '.json';
@ -316,7 +316,7 @@ class Feed extends AppModel {
} else return $event;
}
}
private function __updateEventFromFeed($HttpSocket, $feed, $uuid, $eventId, $user, $filterRules) {
$request = $this->__createFeedRequest();
$uri = $feed['Feed']['url'] . '/' . $uuid . '.json';
@ -329,7 +329,7 @@ class Feed extends AppModel {
return $this->Event->_edit($event, $user, $uuid, $jobId = null);
}
}
public function addDefaultFeeds($newFeeds) {
foreach ($newFeeds as $newFeed) {
$existingFeed = $this->find('list', array('conditions' => array('Feed.url' => $newFeed['url'])));
@ -351,7 +351,7 @@ class Feed extends AppModel {
}
return $success;
}
public function downloadFromFeedInitiator($feedId, $user, $jobId = false) {
$this->id = $feedId;
App::uses('SyncTool', 'Tools');

View File

@ -6,7 +6,7 @@ App::uses('AppModel', 'Model');
* @property Job $Job
*/
class Job extends AppModel {
public $belongsTo = array(
'Org' => array(
'className' => 'Organisation',
@ -15,7 +15,7 @@ class Job extends AppModel {
'fields' => array('id', 'name', 'uuid')
),
);
public function beforeValidate($options = array()) {
parent::beforeValidate();
$date = date('Y-m-d H:i:s');
@ -26,7 +26,7 @@ class Job extends AppModel {
$this->data['Job']['date_modified'] = $date;
}
}
public function cache($type, $user, $target, $jobOrg = null) {
$extra = null;
$extra2 = null;

View File

@ -60,19 +60,19 @@ class Log extends AppModel {
'delete' => array('desc' => 'Delete action', 'formdesc' => "Delete action"),
'publish' => array('desc' => "Publish action", 'formdesc' => "Publish action")
);
public $logMeta = array(
'email' => array('values' => array('email'), 'name' => 'Emails'),
'auth_issues' => array('values' => array('login_fail', 'auth_fail'), 'name' => 'Authentication issues')
);
public $logMetaAdmin = array(
'update' => array('values' => array('update_database'), 'name' => 'MISP Update results'),
'settings' => array('values' => array('serverSettingsEdit', 'remove_dead_workers'), 'name' => 'Setting changes'),
'errors' => array('values' => array('warning', 'errors', 'version_warning'), 'name' => 'Warnings and errors'),
'email' => array('values' => array('admin_email'))
);
public function beforeSave($options = array()) {
if (Configure::read('MISP.log_client_ip') && isset($_SERVER['REMOTE_ADDR'])) $this->data['Log']['ip'] = $_SERVER['REMOTE_ADDR'];
$setEmpty = array('title' => '', 'model' => '', 'model_id' => 0, 'action' => '', 'user_id' => 0, 'change' => '', 'email' => '', 'org' => '', 'description' => '');
@ -82,7 +82,7 @@ class Log extends AppModel {
if (!isset($this->data['Log']['created'])) $this->data['Log']['created'] = time();
return true;
}
public function returnDates($org = 'all') {
$conditions = array();
$this->Organisation = ClassRegistry::init('Organisation');
@ -104,7 +104,7 @@ class Log extends AppModel {
}
return $data;
}
public function createLogEntry($user = array('Organisation' => array('name' => 'SYSTEM'), 'email' => 'SYSTEM', 'id' => 0), $action, $model, $model_id = 0, $title = '', $change = '') {
$this->create();
$this->save(array(

View File

@ -3,7 +3,7 @@ App::uses('AppModel', 'Model');
class Module extends AppModel {
public $useTable = false;
public function getEnrichmentModules() {
if (!Configure::read('Plugin.Enrichment_services_enable')) return 'Enrichment service not enabled.';
@ -28,7 +28,7 @@ class Module extends AppModel {
return $result;
} else return 'The enrichment service reports that it found no enrichment modules.';
}
public function getEnabledModules() {
$modules = $this->getEnrichmentModules();
if (is_array($modules)) {
@ -53,16 +53,16 @@ class Module extends AppModel {
$modules['hover_type'] = $hover_types;
return $modules;
}
public function sendRequest() {
}
public function queryModule() {
}
private function queryModule() {
}
}

View File

@ -4,7 +4,7 @@ App::uses('AppModel', 'Model');
class News extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
'message' => array(
'valueNotEmpty' => array(
@ -17,7 +17,7 @@ class News extends AppModel {
),
)
);
public $belongsTo = array(
'User' => array(
'className' => 'User',

View File

@ -57,9 +57,9 @@ class Organisation extends AppModel{
'foreignKey' => 'org_id',
),
);
public $countries = array('Not specified', 'International', 'Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua & Deps', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Bosnia Herzegovina', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina', 'Burundi', 'Cambodia', 'Cameroon', 'Canada', 'Cape Verde', 'Central African Rep', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Congo {Democratic Rep}', 'Costa Rica', 'Croatia', 'Cuba', 'Cyprus', 'Czech Republic', 'Denmark', 'Djibouti', 'Dominica', 'Dominican Republic', 'East Timor', 'Ecuador', 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Eritrea', 'Estonia', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon', 'Gambia', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guinea-Bissau', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland {Republic}', 'Israel', 'Italy', 'Ivory Coast', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Korea North', 'Korea South', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Macedonia', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Marshall Islands', 'Mauritania', 'Mauritius', 'Mexico', 'Micronesia', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Myanmar, {Burma}', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'New Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Papua New Guinea', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russian Federation', 'Rwanda', 'St Kitts & Nevis', 'St Lucia', 'Saint Vincent & the Grenadines', 'Samoa', 'San Marino', 'Sao Tome & Principe', 'Saudi Arabia', 'Senegal', 'Serbia', 'Seychelles', 'Sierra Leone', 'Singapore', 'Slovakia', 'Slovenia', 'Solomon Islands', 'Somalia', 'South Africa', 'South Sudan', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Swaziland', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tonga', 'Trinidad & Tobago', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'United Arab Emirates', 'United Kingdom', 'United States', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican City', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe');
public $organisationAssociations = array(
'Correlation' => array('table' => 'correlations', 'fields' => array('org_id')),
'Event' => array('table' => 'events', 'fields' => array('org_id', 'orgc_id')),
@ -71,7 +71,7 @@ class Organisation extends AppModel{
'Thread' => array('table' => 'threads', 'fields' => array('org_id')),
'User' => array('table' => 'users', 'fields' => array('org_id'))
);
/*
public $hasAndBelongsToMany = array(
'SharingGroup' => array(
@ -82,7 +82,7 @@ class Organisation extends AppModel{
)
);
*/
public function beforeValidate($options = array()) {
parent::beforeValidate();
if (empty($this->data['Organisation']['uuid']) && (isset($this->data['Organisation']['local']) && $this->data['Organisation']['local'])) {
@ -94,13 +94,13 @@ class Organisation extends AppModel{
if (!isset($this->data['Organisation']['nationality']) || empty($this->data['Organisation']['nationality'])) $this->data['Organisation']['nationality'] = 'Not specified';
return true;
}
public function beforeDelete($cascade = false){
if ($this->User->find('count', array('conditions' => array('User.org_id' => $this->id))) != 0) return false;
if ($this->Event->find('count', array('conditions' => array('OR' => array('Event.org_id' => $this->id, 'Event.orgc_id' => $this->id)))) != 0) return false;
return true;
}
public function captureOrg($org, $user, $force = false) {
if (is_array($org)) {
if (isset($org['uuid']) && !empty($org['uuid'])) {
@ -115,7 +115,7 @@ class Organisation extends AppModel{
$conditions = array('name' => $org);
$name = $org;
}
$existingOrg = $this->find('first', array(
'recursive' => -1,
'conditions' => $conditions,
@ -151,7 +151,7 @@ class Organisation extends AppModel{
}
return $existingOrg[$this->alias]['id'];
}
public function createOrgFromName($name, $user_id, $local) {
$existingOrg = $this->find('first', array(
'recursive' => -1,
@ -170,7 +170,7 @@ class Organisation extends AppModel{
}
return $existingOrg[$this->alias]['id'];
}
public function orgMerge($id, $request, $user) {
$currentOrg = $this->find('first', array('recursive' => -1, 'conditions' => array('Organisation.id' => $id)));
$targetOrgId = $request['Organisation']['targetType'] == 0 ? $request['Organisation']['orgsLocal'] : $request['Organisation']['orgsExternal'];

View File

@ -16,7 +16,7 @@ class Post extends AppModel {
'change' => 'full'
),
);
public $belongsTo = array(
'Thread',
'User'
@ -116,7 +116,7 @@ class Post extends AppModel {
$this->User->sendEmail($recipient, $bodyDetail, $body, $subject);
}
}
public function findPageNr($id, $context = 'thread', &$post_id = false) {
// find the current post and its position in the thread
if ($context == 'event') $conditions = array('Thread.event_id' => $id);

View File

@ -33,7 +33,7 @@ class Regexp extends AppModel {
public function beforeValidate($options = array()) {
$this->sanitizeModifiers($this->data['Regexp']['regexp']);
}
public function sanitizeModifiers(&$regex) {
preg_match('/[a-zA-Z]*$/i', $regex, $modifiers);
if (!empty($modifiers[0])) {
@ -43,7 +43,7 @@ class Regexp extends AppModel {
$regex .= $modifiers[0];
}
}
public function checkRegexp() {
if (@preg_replace($this->data['Regexp']['regexp'], 'success', $this->data['Regexp']['regexp']) != null) return true;
return false;

View File

@ -75,7 +75,7 @@ class Role extends AppModel {
'perm_template' => array('id' => 'RolePermTemplate', 'text' => 'Template Editor'),
'perm_sharing_group' => array('id' => 'RolePermSharingGroup', 'text' => 'Sharing Group Editor'),
);
public $premissionLevelName = array('Read Only', 'Manage Own Events', 'Manage Organisation Events', 'Manage and Publish Organisation Events');
public function beforeSave($options = array()) {

View File

@ -16,7 +16,7 @@ class Server extends AppModel {
'Trim',
'Containable'
);
public $belongsTo = array(
'Organisation' => array(
'className' => 'Organisation',
@ -27,7 +27,7 @@ class Server extends AppModel {
'foreignKey' => 'remote_org_id',
)
);
public $hasMany = array(
'SharingGroupServer' => array(
'className' => 'SharingGroupServer',
@ -124,7 +124,7 @@ class Server extends AppModel {
),
),
);
public $serverSettings = array(
'MISP' => array(
'branch' => 1,
@ -571,7 +571,7 @@ class Server extends AppModel {
'test' => 'testBool',
'type' => 'boolean',
'null' => false,
),
'block_old_event_alert' => array(
'level' => 1,
@ -1089,7 +1089,7 @@ class Server extends AppModel {
'type' => 'boolean',
),
);
private $__settingTabMergeRules = array(
'GnuPG' => 'Encryption',
'SMIME' => 'Encryption',
@ -1098,16 +1098,16 @@ class Server extends AppModel {
);
public $validEventIndexFilters = array('searchall', 'searchpublished', 'searchorg', 'searchtag', 'searcheventid', 'searchdate', 'searcheventinfo', 'searchthreatlevel', 'searchdistribution', 'searchanalysis', 'searchattribute');
public function isOwnedByOrg($serverid, $org) {
return $this->field('id', array('id' => $serverid, 'org' => $org)) === $serverid;
}
public function beforeSave($options = array()) {
$this->data['Server']['url'] = rtrim($this->data['Server']['url'], '/');
return true;
}
public function pull($user, $id = null, $technique=false, $server, $jobId = false, $percent = 100, $current = 0) {
if ($jobId) {
$job = ClassRegistry::init('Job');
@ -1129,7 +1129,7 @@ class Server extends AppModel {
} else if (is_string($eventIds)) {
return array(2, $eventIds);
}
// reverse array of events, to first get the old ones, and then the new ones
if (!empty($eventIds)) {
$eventIds = array_reverse($eventIds);
@ -1339,7 +1339,7 @@ class Server extends AppModel {
if (!isset($proposal['deleted']) || !$proposal['deleted']) {
if ($shadowAttribute->save($proposal)) $shadowAttribute->sendProposalAlertEmail($eid);
}
}
}
}
@ -1373,7 +1373,7 @@ class Server extends AppModel {
if (!isset($lastpulledid)) $lastpulledid = 0;
return array($successes, $fails, $pulledProposals, $lastpulledid);
}
public function filterRuleToParameter($filter_rules) {
$final = array();
if (empty($filter_rules)) return $final;
@ -1393,7 +1393,7 @@ class Server extends AppModel {
}
return $final;
}
/**
* Get an array of event_ids that are present on the remote server
@ -1464,7 +1464,7 @@ class Server extends AppModel {
// error, so return error message, since that is handled and everything is expecting an array
return "Error: got response code " . $response->code;
}
public function push($id = null, $technique=false, $jobId = false, $HttpSocket, $user) {
if ($jobId) {
$job = ClassRegistry::init('Job');
@ -1495,7 +1495,7 @@ class Server extends AppModel {
} else {
$this->redirect(array('action' => 'index'));
}
if ($push !== 'mangle') {
$sgs = $this->Event->SharingGroup->find('all', array(
'recursive' => -1,
@ -1577,9 +1577,9 @@ class Server extends AppModel {
$this->save($this->data);
}
}
$this->syncProposals($HttpSocket, $this->data, null, null, $this->Event);
if (!isset($successes)) $successes = null;
if (!isset($fails)) $fails = null;
$this->Log = ClassRegistry::init('Log');
@ -1604,7 +1604,7 @@ class Server extends AppModel {
return array($successes, $fails);
}
}
public function getEventIdsForPush($id, $HttpSocket, $eventIds, $user) {
$server = $this->read(null, $id);
$this->Event = ClassRegistry::init('Event');
@ -1638,7 +1638,7 @@ class Server extends AppModel {
}
return $uuidList;
}
public function syncProposals($HttpSocket, $server, $sa_id = null, $event_id = null, $eventModel) {
$saModel = ClassRegistry::init('ShadowAttribute');
if (null == $HttpSocket) {
@ -1675,7 +1675,7 @@ class Server extends AppModel {
unset($sa['value1']);
unset($sa['value2']);
}
$data = json_encode($event['ShadowAttribute']);
$request = array(
'header' => array(
@ -1717,7 +1717,7 @@ class Server extends AppModel {
}
return true;
}
private function __getEnrichmentSettings() {
$modules = $this->getEnrichmentModules();
$result = array();
@ -1733,7 +1733,7 @@ class Server extends AppModel {
}
return $result;
}
public function getCurrentServerSettings() {
$serverSettings = $this->serverSettings;
$results = array();
@ -1760,7 +1760,7 @@ class Server extends AppModel {
}
return $serverSettings;
}
public function serverSettingsRead($unsorted = false) {
$serverSettings = $this->getCurrentServerSettings();
$results = array();
@ -1824,14 +1824,14 @@ class Server extends AppModel {
}
return $finalSettings;
}
public function serverSettingReadSingle($settingObject, $settingName, $leafKey) {
$setting = Configure::read($settingName);
$result = $this->__evaluateLeaf($settingObject, $leafKey, $setting);
$result['setting'] = $settingName;
return $result;
}
private function __evaluateLeaf($leafValue, $leafKey, $setting) {
if (isset($setting)) {
$result = $this->{$leafValue['test']}($setting);
@ -1848,112 +1848,112 @@ class Server extends AppModel {
}
return $leafValue;
}
public function testForNumeric($value) {
if (!is_numeric($value)) return 'This setting has to be a number.';
return true;
}
public function testForEmpty($value) {
if ($value === '') return 'Value not set.';
return true;
}
public function testForPath($value) {
if ($value === '') return true;
if (preg_match('/^[a-z0-9\-\_\:\/]+$/i', $value)) return true;
return 'Invalid characters in the path.';
}
public function testDebug($value) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
if ($this->testForNumeric($value) !== true) return 'This setting has to be a number between 0 and 2, with 0 disabling debug mode.';
if ($value === 0) return true;
return 'This setting has to be set to 0 on production systems. Ignore this warning if this is not the case.';
}
public function testDebugAdmin($value) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
if ($this->testBool($value) !== true) return 'This setting has to be either true or false.';
if (!$value) return true;
return 'Enabling debug is not recommended. Turn this on temporarily if you need to see a stack trace to debug an issue, but make sure this is not left on.';
}
public function testDate($date) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
if (!strtotime($date)) return 'The date that you have entered is invalid. Expected: yyyy-mm-dd';
return true;
}
public function testBaseURL($value) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) === true ? 'HTTPS' : 'HTTP';
if ($value != strtolower($protocol) . '://' . $_SERVER['HTTP_HOST']) return false;
return true;
}
public function testMangle($value) {
if ($this->testBool($value) !== true) return $this->testBool($value);
if ($value) return 'Enabled, expect issues.';
return true;
}
public function testDisableEmail($value) {
if (isset($value) && $value) return 'E-mailing is blocked.';
return true;
}
public function testLive($value) {
if ($this->testBool($value) !== true) return $this->testBool($value);
if (!$value) return 'MISP disabled.';
return true;
}
public function testBool($value) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
if ($value !== true && $value !== false) return 'Value is not a boolean, make sure that you convert \'true\' to true for example.';
return true;
}
public function testSalt($value) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
if (strlen($value) < 32) return 'The salt has to be an at least 32 byte long string.';
if ($value == "Rooraenietu8Eeyo<Qu2eeNfterd-dd+") return 'This is the default salt shipped with the application and is therefore unsecure.';
return true;
}
public function testForTermsFile($value) {
return $this->__testForFile($value, APP . 'files' . DS . 'terms');
}
public function testForCustomImage($value) {
return $this->__testForFile($value, APP . 'webroot' . DS . 'img' . DS . 'custom');
}
public function testPasswordLength($value) {
$numeric = $this->testForNumeric($value);
if ($numeric !== true) return $numeric;
if ($value < 0) return 'Length cannot be negative, set a positive integer or 0 (to choose the default option).';
return true;
}
public function testForPortNumber($value) {
$numeric = $this->testForNumeric($value);
if ($numeric !== true) return $numeric;
if ($value < 49152 || $value > 65535) return 'It is recommended that you pick a port number in the dynamic range (49152-65535). However, if you have a valid reason to use a different port, ignore this message.';
return true;
}
public function testPasswordRegex($value) {
if (!empty($value) && @preg_match($value, 'test') === false) return 'Invalid regex.';
return true;
}
public function testPasswordResetText($value) {
if (strpos($value, '$password') === false || strpos($value, '$username') === false || strpos($value, '$misp') === false) return 'The text served to the users must include the following replacement strings: "$username", "$password", "$misp"';
return true;
}
public function testForGPGBinary($value) {
if (empty($value)) $value = $this->serverSettings['GnuPG']['binary']['value'];
if (file_exists($value)) return true;
@ -1967,40 +1967,40 @@ class Server extends AppModel {
return 'Negative seconds found. The following formats are accepted: seconds (positive integer), or duration (positive integer) followed by a letter denoting scale (such as m, h, d, w for minutes, hours, days, weeks)';
}
}
public function testForRPZBehaviour($value) {
$numeric = $this->testforNumeric($value);
if ($numeric !== true) return $numeric;
if ($value < 0 || $value > 3) return 'Invalid setting, valid range is 0-3 (0 = DROP, 1 = NXDOMAIN, 2 = NODATA, 3 = walled garden.';
return true;
}
public function testForSightingVisibility($value) {
$numeric = $this->testforNumeric($value);
if ($numeric !== true) return $numeric;
if ($value < 0 || $value > 2) return 'Invalid setting, valid range is 0-2 (0 = Event owner, 1 = Sighting reporters, 2 = Everyone.';
return true;
}
public function sightingsBeforeHook($setting, $value) {
if ($value == true) {
$this->updateDatabase('addSightings');
}
return true;
}
public function testForRPZSerial($value) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
if (!preg_match('/^((\$date(\d*)|\d*))$/', $value)) return 'Invalid format.';
return true;
}
public function testForRPZNS($value) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
if (!preg_match('/^\w+(\.\w+)*(\.?) \w+(\.\w+)*$/', $value)) return 'Invalid format.';
return true;
}
public function zmqAfterHook($setting, $value) {
App::uses('PubSubTool', 'Tools');
$pubSubTool = new PubSubTool();
@ -2017,7 +2017,7 @@ class Server extends AppModel {
$pubSubTool->reloadServer();
return true;
}
public function ipLogBeforeHook($setting, $value) {
if ($setting == 'MISP.log_client_ip') {
if ($value == true) {
@ -2026,7 +2026,7 @@ class Server extends AppModel {
}
return true;
}
public function eventBlacklistingBeforeHook($setting, $value) {
$this->cleanCacheFiles();
if ($value) {
@ -2046,7 +2046,7 @@ class Server extends AppModel {
$this->cleanCacheFiles();
return true;
}
public function orgBlacklistingBeforeHook($setting, $value) {
$this->cleanCacheFiles();
if ($value) {
@ -2059,8 +2059,8 @@ class Server extends AppModel {
}
return true;
}
// never come here directly, always go through a secondary check like testForTermsFile in order to also pass along the expected file path
private function __testForFile($value, $path) {
if ($this->testForEmpty($value) !== true) return $this->testForEmpty($value);
@ -2069,12 +2069,12 @@ class Server extends AppModel {
if (!file_exists($file)) return 'Could not find the specified file. Make sure that it is uploaded into the following directory: ' . $path;
return true;
}
public function serverSettingsSaveValue($setting, $value) {
Configure::write($setting, $value);
Configure::dump('config.php', 'default', array('MISP', 'GnuPG', 'SMIME', 'Proxy', 'SecureAuth', 'Security', 'debug', 'site_admin_debug', 'Plugin'));
}
public function checkVersion($newest) {
$version_array = $this->checkMISPVersion();
$current = 'v' . $version_array['major'] . '.' . $version_array['minor'] . '.' . $version_array['hotfix'];
@ -2082,12 +2082,12 @@ class Server extends AppModel {
$upToDate = $this->__compareVersions(array($version_array['major'], $version_array['minor'], $version_array['hotfix']), $newest_array, 0);
return array ('current' => $current, 'newest' => $newest, 'upToDate' => $upToDate);
}
private function __dissectVersion($version) {
$version = substr($version, 1);
return explode('.', $version);
}
private function __compareVersions($current, $newest, $i) {
if ($current[$i] == $newest[$i]) {
if ($i < 2) {
@ -2101,7 +2101,7 @@ class Server extends AppModel {
return 'newer';
}
}
public function getFileRules() {
$validItems = array(
'orgs' => array(
@ -2132,7 +2132,7 @@ class Server extends AppModel {
);
return $validItems;
}
public function grabFiles() {
$validItems = $this->getFileRules();
App::uses('Folder', 'Utility');
@ -2147,7 +2147,7 @@ class Server extends AppModel {
}
return $validItems;
}
public function runConnectionTest($id) {
$server = $this->find('first', array('conditions' => array('Server.id' => $id)));
App::uses('SyncTool', 'Tools');
@ -2193,7 +2193,7 @@ class Server extends AppModel {
return array('status' => 3);
}
}
public function checkVersionCompatibility($id, $user = array(), $HttpSocket = false) {
// for event publishing when we don't have a user.
if (empty($user)) $user = array('Organisation' => array('name' => 'SYSTEM'), 'email' => 'SYSTEM', 'id' => 0);
@ -2201,7 +2201,7 @@ class Server extends AppModel {
$file = new File(ROOT . DS . 'VERSION.json', true);
$localVersion = json_decode($file->read(), true);
$file->close();
$server = $this->find('first', array('conditions' => array('Server.id' => $id)));
if (!$HttpSocket) {
App::uses('SyncTool', 'Tools');
@ -2262,7 +2262,7 @@ class Server extends AppModel {
$response = "Sync to Server ('" . $id . "') aborted. The remote instance is at least a full minor version ahead - make sure you update your MISP instance!";
$canPush = true;
}
// if we haven't set a message yet, we're good to go. We are only behind by a hotfix version
if ($response === false) {
$success = true;
@ -2271,12 +2271,12 @@ class Server extends AppModel {
else $issueLevel = "error";
if ($response === false && $localVersion['hotfix'] > $remoteVersion[2]) $response = "Sync to Server ('" . $id . "') initiated, but the remote instance is a few hotfixes behind.";
if ($response === false && $localVersion['hotfix'] < $remoteVersion[2]) $response = "Sync to Server ('" . $id . "') initiated, but the remote instance is a few hotfixes ahead. Make sure you keep your instance up to date!";
if (Configure::read('MISP.ManglePushTo23') && !$canPush) {
$canPush = 'mangle';
$response = "Sync to Server ('" . $id . "') should have been blocked, but mangle sync override is enabled. A downgraded synchronisation is highly advised again, please upgrade your instance as soon as possible.";
}
if ($response !== false) {
$this->Log = ClassRegistry::init('Log');
$this->Log->create();
@ -2292,11 +2292,11 @@ class Server extends AppModel {
}
return array('success' => $success, 'response' => $response, 'canPush' => $canPush, 'version' => $remoteVersion);
}
public function isJson($string) {
return (json_last_error() == JSON_ERROR_NONE);
}
public function captureServer($server, $user) {
if (isset($server[0])) $server = $server[0];
if ($server['url'] == Configure::read('MISP.baseurl')) return 0;
@ -2342,7 +2342,7 @@ class Server extends AppModel {
}
return $writeableDirs;
}
public function writeableFilesDiagnostics(&$diagnostic_errors) {
$writeableFiles = array(
'Config' . DS . 'config.php' => 0,
@ -2359,7 +2359,7 @@ class Server extends AppModel {
}
return $writeableFiles;
}
public function stixDiagnostics(&$diagnostic_errors, &$stixVersion, &$cyboxVersion) {
$result = array();
$expected = array('stix' => '1.1.1.4', 'cybox' => '2.1.0.12');
@ -2386,7 +2386,7 @@ class Server extends AppModel {
}
return $result;
}
public function gpgDiagnostics(&$diagnostic_errors) {
$gpgStatus = 0;
if (Configure::read('GnuPG.email') && Configure::read('GnuPG.homedir')) {
@ -2420,7 +2420,7 @@ class Server extends AppModel {
if ($gpgStatus != 0) $diagnostic_errors++;
return $gpgStatus;
}
public function zmqDiagnostics(&$diagnostic_errors) {
if (!Configure::read('Plugin.ZeroMQ_enable')) return 1;
App::uses('PubSubTool', 'Tools');
@ -2433,7 +2433,7 @@ class Server extends AppModel {
$diagnostic_errors++;
return 3;
}
public function proxyDiagnostics(&$diagnostic_errors) {
$proxyStatus = 0;
$proxy = Configure::read('Proxy');
@ -2455,7 +2455,7 @@ class Server extends AppModel {
if ($proxyStatus > 1) $diagnostic_errors++;
return $proxyStatus;
}
public function sessionDiagnostics(&$diagnostic_errors, &$sessionCount) {
if (Configure::read('Session.defaults') !== 'database') {
$sessionCount = 'N/A';
@ -2475,7 +2475,7 @@ class Server extends AppModel {
}
return $sessionStatus;
}
public function workerDiagnostics(&$workerIssueCount) {
$this->ResqueStatus = new ResqueStatus\ResqueStatus(Resque::redis());
$workers = $this->ResqueStatus->getWorkers();
@ -2519,7 +2519,7 @@ class Server extends AppModel {
$worker_array['proc_accessible'] = $procAccessible;
return $worker_array;
}
public function retrieveCurrentSettings($branch, $subString) {
$settings = array();
foreach ($this->serverSettings[$branch] as $settingName => $setting) {
@ -2531,7 +2531,7 @@ class Server extends AppModel {
}
return $settings;
}
public function killWorker($pid, $user) {
if (!is_numeric($pid)) throw new MethodNotAllowedException('Non numeric PID found!');
$this->ResqueStatus = new ResqueStatus\ResqueStatus(Resque::redis());
@ -2569,7 +2569,7 @@ class Server extends AppModel {
$this->ResqueStatus->removeWorker($pid);
}
}
public function workerRemoveDead($user) {
$this->ResqueStatus = new ResqueStatus\ResqueStatus(Resque::redis());
$workers = $this->ResqueStatus->getWorkers();
@ -2597,7 +2597,7 @@ class Server extends AppModel {
}
}
}
private function __dropIndex($table, $field) {
$this->Log = ClassRegistry::init('Log');
$indexCheck = "SELECT INDEX_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema=DATABASE() AND table_name='" . $table . "' AND index_name LIKE '" . $field . "%'";
@ -2623,7 +2623,7 @@ class Server extends AppModel {
));
}
}
public function upgrade2324($user_id, $jobId = false) {
$this->cleanCacheFiles();
if (Configure::read('MISP.background_jobs') && $jobId) {
@ -2769,8 +2769,8 @@ class Server extends AppModel {
$this->Job->saveField('message', 'Upgrade complete.');
}
}
/* returns an array with the events
* error codes:
* 1: received non json response
@ -2815,7 +2815,7 @@ class Server extends AppModel {
}
return 2;
}
/* returns an array with the events
* error codes:
* 1: received non-json response
@ -2853,7 +2853,7 @@ class Server extends AppModel {
}
return 2;
}
// Loops through all servers and checks which servers' push rules don't conflict with the given event.
// returns the server objects that would allow the event to be pushed
public function eventFilterPushableServers($event, $servers) {
@ -2880,7 +2880,7 @@ class Server extends AppModel {
}
return $validServers;
}
public function getEnrichmentModules() {
if (!Configure::read('Plugin.Enrichment_services_enable')) return 'Enrichment service not enabled.';
$url = Configure::read('Plugin.Enrichment_services_url') ? Configure::read('Plugin.Enrichment_services_url') : $this->serverSettings['Plugin']['Enrichment_services_url']['value'];
@ -2904,7 +2904,7 @@ class Server extends AppModel {
return $result;
} else return 'The enrichment service reports that it found no enrichment modules.';
}
public function getEnabledModules() {
$modules = $this->getEnrichmentModules();
if (is_array($modules)) {

View File

@ -167,7 +167,7 @@ class ShadowAttribute extends AppModel {
}
// The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* beforeSave
*
@ -204,7 +204,7 @@ class ShadowAttribute extends AppModel {
$this->ShadowAttributeCorrelation = ClassRegistry::init('ShadowAttributeCorrelation');
$this->ShadowAttributeCorrelation->deleteAll(array('ShadowAttributeCorrelation.1_shadow_attribute_id' => $temp['id']));
}
private function __afterSaveCorrelation(&$sa) {
$temp = $sa;
if (isset($temp['ShadowAttribute'])) $temp = $temp['ShadowAttribute'];
@ -255,7 +255,7 @@ class ShadowAttribute extends AppModel {
}
if (!empty($shadow_attribute_correlations)) $this->ShadowAttributeCorrelation->saveMany($shadow_attribute_correlations);
}
public function afterSave($created, $options = array()) {
$result = true;
// if the 'data' field is set on the $this->data then save the data to the correct file
@ -311,7 +311,7 @@ class ShadowAttribute extends AppModel {
if (!isset($this->data['ShadowAttribute']['type'])) {
return false;
}
if (empty($this->data['ShadowAttribute']['timestamp'])) {
$date = new DateTime();
$this->data['ShadowAttribute']['timestamp'] = $date->getTimestamp();
@ -336,7 +336,7 @@ class ShadowAttribute extends AppModel {
}
return false;
}
public function validCategory($fields) {
return $this->Event->Attribute->validCategory($fields);
}
@ -477,7 +477,7 @@ class ShadowAttribute extends AppModel {
}
return $fails;
}
public function setDeleted($id) {
$this->Behaviors->detach('SysLogLogable.SysLogLogable');
$sa = $this->find('first', array('conditions' => array('ShadowAttribute.id' => $id), 'recusive' => -1));
@ -488,7 +488,7 @@ class ShadowAttribute extends AppModel {
$this->save($sa);
return true;
}
public function findOldProposal($sa) {
$oldsa = $this->find('first', array(
'conditions' => array(
@ -503,7 +503,7 @@ class ShadowAttribute extends AppModel {
if (empty($oldsa)) return false;
else return $oldsa['ShadowAttribute'];
}
public function getEventContributors($id) {
$orgs = $this->find('all', array('fields' => array('DISTINCT(org_id)'), 'conditions' => array('event_id' => $id), 'order' => false));
$org_ids = array();
@ -512,12 +512,12 @@ class ShadowAttribute extends AppModel {
}
return $org_ids;
}
public function sendProposalAlertEmail($id) {
$this->Event->recursive = -1;
$event = $this->Event->read(null, $id);
// If the event has an e-mail lock, return
if ($event['Event']['proposal_email_lock'] == 1) {
return;
@ -534,7 +534,7 @@ class ShadowAttribute extends AppModel {
),
'fields' => array('email', 'gpgkey', 'certif_public', 'contactalert', 'id')
));
$body = "Hello, \n\n";
$body .= "A user of another organisation has proposed a change to an event created by you or your organisation. \n\n";
$body .= 'To view the event in question, follow this link: ' . Configure::read('MISP.baseurl') . '/events/view/' . $id . "\n";
@ -545,7 +545,7 @@ class ShadowAttribute extends AppModel {
}
return $result;
}
public function setProposalLock($id, $lock = true) {
$this->Event->recursive = -1;
@ -558,7 +558,7 @@ class ShadowAttribute extends AppModel {
$fieldList = array('proposal_email_lock', 'id', 'info');
$this->Event->save($event, array('fieldList' => $fieldList));
}
public function generateCorrelation($jobId = false) {
$this->ShadowAttributeCorrelation = ClassRegistry::init('ShadowAttributeCorrelation');
$this->ShadowAttributeCorrelation->deleteAll(array('id !=' => 0), false);
@ -584,7 +584,7 @@ class ShadowAttribute extends AppModel {
}
return $proposalCount;
}
public function upgradeToProposalCorrelation() {
$this->Log = ClassRegistry::init('Log');
if (!Configure::read('MISP.background_jobs')) {

View File

@ -2,7 +2,7 @@
App::uses('AppModel', 'Model');
class SharingGroup extends AppModel {
public $actsAs = array(
'Containable',
'SysLogLogable.SysLogLogable' => array( // TODO Audit, logable
@ -43,7 +43,7 @@ class SharingGroup extends AppModel {
'Attribute',
'Thread'
);
public $belongsTo = array(
'Organisation' => array(
'className' => 'Organisation',
@ -62,7 +62,7 @@ class SharingGroup extends AppModel {
$this->data['SharingGroup']['date_created'] = $date;
}
$this->data['SharingGroup']['date_modified'] = $date;
$sameNameSG = $this->find('first', array(
'conditions' => array('SharingGroup.name' => $this->data['SharingGroup']['name']),
'recursive' => -1,
@ -73,7 +73,7 @@ class SharingGroup extends AppModel {
}
return true;
}
public function beforeDelete($cascade = false){
$countEvent = $this->Event->find('count', array(
'recursive' => -1,
@ -90,7 +90,7 @@ class SharingGroup extends AppModel {
if (($countEvent + $countThread + $countAttribute) == 0) return true;
return false;
}
public function fetchAllAuthorisedForServer($server) {
$conditions = array();
$ids = array();
@ -98,7 +98,7 @@ class SharingGroup extends AppModel {
$sgs = array_merge($sgs, $this->SharingGroupServer->fetchAllSGsForServer($server['Server']['id']));
return $sgs;
}
// returns a list of all sharing groups that the user is allowed to see
// scope can be:
// full: Entire SG object with all organisations and servers attached
@ -145,7 +145,7 @@ class SharingGroup extends AppModel {
return $ids;
}
}
// Who can create a new sharing group with the elements pre-defined (via REST for example)?
// 1. site admins
// 2. Sharing group enabled users
@ -153,7 +153,7 @@ class SharingGroup extends AppModel {
// 3. Sync users
// a. as long as they are at least users of the SG (they can circumvent the extend rule to
// avoid situations where no one can create / edit an SG on an instance after a push)
public function checkIfAuthorisedToSave($user, $sg) {
if (isset($sg[0])) $sg = $sg[0];
if ($user['Role']['perm_site_admin']) return true;
@ -190,7 +190,7 @@ class SharingGroup extends AppModel {
}
return false;
}
// Who is authorised to extend a sharing group?
// 1. Site admins
// 2. Sharing group permission enabled users that:
@ -226,7 +226,7 @@ class SharingGroup extends AppModel {
if (empty($sgo)) return false;
else return true;
}
// returns true if the SG exists and the user is allowed to see it
public function checkIfAuthorised($user, $id) {
if (!isset($user['id'])) throw new MethodNotAllowedException('Invalid user.');
@ -235,7 +235,7 @@ class SharingGroup extends AppModel {
if ($user['Role']['perm_site_admin'] || $this->SharingGroupServer->checkIfAuthorised($id) || $this->SharingGroupOrg->checkIfAuthorised($id, $user['org_id'])) return true;
return false;
}
public function checkIfOwner($user, $id) {
if (!isset($user['id'])) throw new MethodNotAllowedException('Invalid user.');
$this->id = $id;
@ -248,7 +248,7 @@ class SharingGroup extends AppModel {
));
return ($sg['SharingGroup']['org_id'] == $user['org_id']);
}
// Get all organisation ids that can see a SG
public function getOrgsWithAccess($id) {
$sg = $this->find('first', array(
@ -274,7 +274,7 @@ class SharingGroup extends AppModel {
}
return $orgs;
}
public function checkIfServerInSG($sg, $server) {
$results = array(
'rule' => false,
@ -292,7 +292,7 @@ class SharingGroup extends AppModel {
foreach ($sg['SharingGroupOrg'] as $org) if (isset($org['Organisation']) && $org['Organisation']['uuid'] === $server['RemoteOrg']['uuid']) return true;
return false;
}
public function getSGSyncRules($sg) {
$results = array(
'conditional' => array(),
@ -316,7 +316,7 @@ class SharingGroup extends AppModel {
}
return $results;
}
public function captureSG($sg, $user) {
$existingSG = !isset($sg['uuid']) ? null : $this->find('first', array(
'recursive' => -1,
@ -372,7 +372,7 @@ class SharingGroup extends AppModel {
}
}
unset ($sg['Organisation']);
if (isset($sg['SharingGroupOrg']['id'])) {
$temp = $sg['SharingGroupOrg'];
unset($sg['SharingGroupOrg']);
@ -405,7 +405,7 @@ class SharingGroup extends AppModel {
$this->SharingGroupOrg->save(array('sharing_group_id' => $sgids, 'org_id' => $sg['SharingGroupOrg'][$k]['org_id'], 'extend' => $org['extend']));
}
}
if (isset($sg['SharingGroupServer']['id'])) {
$temp = $sg['SharingGroupServer'];
unset($sg['SharingGroupServer']);

View File

@ -3,9 +3,9 @@ App::uses('AppModel', 'Model');
class SharingGroupElement extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
);
public $belongsTo = array(
'SharingGroup' => array(
'className' => 'SharingGroup',

View File

@ -3,9 +3,9 @@ App::uses('AppModel', 'Model');
class SharingGroupOrg extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
);
public $belongsTo = array(
'SharingGroup' => array(
'className' => 'SharingGroup',
@ -21,7 +21,7 @@ class SharingGroupOrg extends AppModel {
public function beforeValidate($options = array()) {
parent::beforeValidate();
}
public function updateOrgsForSG($id, $new_orgs, $old_orgs, $user) {
$log = ClassRegistry::init('Log');
// Loop through all of the organisations we want to add.
@ -64,7 +64,7 @@ class SharingGroupOrg extends AppModel {
}
}
}
public function fetchAllAuthorised($org_id) {
$sgs = $this->find('all', array(
'conditions' => array('org_id' => $org_id),
@ -75,7 +75,7 @@ class SharingGroupOrg extends AppModel {
foreach ($sgs as $sg) $ids[] = $sg['SharingGroupOrg']['sharing_group_id'];
return $ids;
}
// pass a sharing group ID and an organisation ID, returns true if it has a matching attached organisation object
public function checkIfAuthorised($id, $org_id) {
$sg = $this->find('first', array(

View File

@ -3,9 +3,9 @@ App::uses('AppModel', 'Model');
class SharingGroupServer extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
);
public $belongsTo = array(
'SharingGroup' => array(
'className' => 'SharingGroup',
@ -21,7 +21,7 @@ class SharingGroupServer extends AppModel {
public function beforeValidate($options = array()) {
parent::beforeValidate();
}
public function updateServersForSG($id, $new_servers, $old_servers, $limitServers, $user) {
$log = ClassRegistry::init('Log');
@ -35,7 +35,7 @@ class SharingGroupServer extends AppModel {
);
$server_name = 'server (' . $server['id'] . ')';
if ($server['id'] == 0) $server_name = 'the local server';
$found = false;
// If there is a match between a new server and an old server, keep the server in $found and unset it in the old server array.
foreach ($old_servers as $k => $old_server) {
@ -45,7 +45,7 @@ class SharingGroupServer extends AppModel {
break;
}
}
// If we have not found the server previously, create a new sharing group server object.
// Otherwise, if we have found it check whether the extended field has been altered, if not just continue without saving
if (!$found) {
@ -74,7 +74,7 @@ class SharingGroupServer extends AppModel {
$this->deleteAll(array('sharing_group_id' => $id), false);
}
}
// returns all sharing group IDs that have the local server (server_id = 0) as a server object with all orgs turned to 1
// This basically lists all SGs that allow everyone on the instance to see events tagged with it
public function fetchAllAuthorised() {
@ -87,7 +87,7 @@ class SharingGroupServer extends AppModel {
foreach ($sgs as $sg) $ids[] = $sg['SharingGroupServer']['sharing_group_id'];
return $ids;
}
// pass a sharing group ID, returns true if it has an attached server object with "all_orgs" ticked
public function checkIfAuthorised($id) {
$sg = $this->find('first', array(
@ -98,7 +98,7 @@ class SharingGroupServer extends AppModel {
if (!empty($sg)) return true;
return false;
}
public function fetchAllSGsForServer($server_id) {
$sgs = $this->find('all', array(
'recursive' => -1,

View File

@ -13,7 +13,7 @@ class Sighting extends AppModel{
'org_id' => 'numeric',
'date_sighting' => 'numeric'
);
public $belongsTo = array(
'Attribute' => array(
'className' => 'Attribute',
@ -35,7 +35,7 @@ class Sighting extends AppModel{
}
return true;
}
public function attachToEvent(&$event, &$user, $eventOnly = false) {
$ownEvent = false;
if ($user['Role']['perm_site_admin'] || $event['Event']['org_id'] == $user['org_id']) $ownEvent = true;
@ -47,7 +47,7 @@ class Sighting extends AppModel{
if (Configure::read('MISP.showorg')) {
$contain['Organisation'] = array('fields' => array('Organisation.id', 'Organisation.uuid', 'Organisation.name'));
}
// Sighting reporters setting
// If the event has any sightings for the user's org, then the user is a sighting reporter for the event too.
// This means that he /she has access to the sightings data contained within
@ -55,7 +55,7 @@ class Sighting extends AppModel{
$temp = $this->find('first', array('recursive' => -1, 'conditions' => array('Sighting.event_id' => $event['Event']['id'], 'Sighting.org_id' => $user['org_id'])));
if (empty($temp)) return array();
}
$sightings = $this->find('all', array(
'conditions' => $conditions,
'recursive' => -1,
@ -79,7 +79,7 @@ class Sighting extends AppModel{
}
return $sightings;
}
public function saveSightings($id, $values, $timestamp, $user) {
$conditions = array();
if ($id && $id !== 'stix') {
@ -110,11 +110,11 @@ class Sighting extends AppModel{
}
return $sightingsAdded;
}
public function handleStixSighting($data) {
$randomFileName = $this->generateRandomFileName();
$tempFile = new File(APP . "files" . DS . "scripts" . DS . "tmp" . DS . $randomFileName, true, 0644);
// save the json_encoded event(s) to the temporary file
if (!$tempFile->write($data)) return array('success' => 0, 'message' => 'Could not write the Sightings file to disk.');
$tempFile->close();
@ -134,7 +134,7 @@ class Sighting extends AppModel{
$tempFile->delete();
return $result;
}
public function generateRandomFileName() {
$length = 12;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

View File

@ -29,7 +29,7 @@ class Tag extends AppModel {
),
'Containable'
);
public $validate = array(
'name' => array(
'valueNotEmpty' => array(
@ -50,7 +50,7 @@ class Tag extends AppModel {
),
),
);
public $hasMany = array(
'EventTag' => array(
'className' => 'EventTag',
@ -60,17 +60,17 @@ class Tag extends AppModel {
'dependent' => true
)
);
public function beforeDelete($cascade = true) {
$this->EventTag->deleteAll(array('EventTag.tag_id' => $this->id));
}
public function validateColour($fields) {
if (!preg_match('/^#[0-9a-f]{6}$/i', $fields['colour'])) return false;
return true;
}
// find all of the event Ids that belong to the accepted tags and the rejected tags
public function fetchEventTagIds($accept=array(), $reject=array()) {
$acceptIds = array();
@ -84,7 +84,7 @@ class Tag extends AppModel {
}
return array($acceptIds, $rejectIds);
}
// find all of the event Ids that belong to tags with certain names
public function findTags($array) {
$ids = array();
@ -105,7 +105,7 @@ class Tag extends AppModel {
}
return $ids;
}
public function captureTag($tag, $user) {
$existingTag = $this->find('first', array(
'recursive' => -1,
@ -143,13 +143,13 @@ class Tag extends AppModel {
}
return $tags;
}
public function random_color() {
$colour = '#';
for ($i = 0; $i < 3; $i++) $colour .= str_pad(dechex(mt_rand(0,255)), 2, '0', STR_PAD_LEFT);
return $colour;
}
public function quickAdd($name, $colour = false) {
$this->create();
if ($colour === false) $colour = $this->random_color();
@ -160,7 +160,7 @@ class Tag extends AppModel {
);
return ($this->save($data));
}
public function quickEdit($tag, $name, $colour) {
if ($tag['Tag']['colour'] !== $colour || $tag['Tag']['name'] !== $name) {
$tag['Tag']['name'] = $name;
@ -169,7 +169,7 @@ class Tag extends AppModel {
}
return true;
}
public function getTagsForNamespace($namespace) {
$tags_temp = $this->find('all', array(
'recursive' => -1,

View File

@ -15,7 +15,7 @@ class Task extends AppModel {
'description' => 'Generates export caches for every export type and for every organisation. This process is heavy, schedule so it might be a good idea to schedule this outside of working hours and before your daily automatic imports on connected services are scheduled.',
'next_execution_time' => 1391601600,
'message' => 'Not scheduled yet.'
),
'pull_all' => array(
'type' => 'pull_all',
@ -37,7 +37,7 @@ class Task extends AppModel {
'message' => 'Not scheduled yet.'
)
);
// takes a time in the 24h format (13:49) and an integer representing the number of hours
// by which it needs to be incremeneted. Returns a string in the first parameters format
public function breakTime($time, $timeToAdd) {
@ -47,7 +47,7 @@ class Task extends AppModel {
if ($temp[0] > 23) $temp[0] = $temp[0] - 24;
return $temp[0] . ':' . $temp[1];
}
public function reQueue($task, $worker, $shell, $action, $userId, $taskId) {
$time = time();
// Keep adding the timer's time interval until we get a date that is in the future! We don't want to keep queuing tasks in the past since they will execute until it catches up.
@ -56,7 +56,7 @@ class Task extends AppModel {
}
$task['Task']['scheduled_time'] = $this->breakTime($task['Task']['scheduled_time'], $task['Task']['timer']);
$task['Task']['scheduled_time'] = date('H:i', $task['Task']['next_execution_time']);
// Now that we have figured out when the next execution should happen, it's time to enqueue it.
$process_id = CakeResque::enqueueAt(
$task['Task']['next_execution_time'],

View File

@ -18,7 +18,7 @@ class Taxonomy extends AppModel{
'rule' => array('numeric'),
)
);
public $hasMany = array(
'TaxonomyPredicate' => array(
'dependent' => true
@ -29,7 +29,7 @@ class Taxonomy extends AppModel{
parent::beforeValidate();
return true;
}
public function update() {
$directories = glob(APP . 'files' . DS . 'taxonomies' . DS . '*', GLOB_ONLYDIR);
foreach ($directories as $k => &$dir) {
@ -59,7 +59,7 @@ class Taxonomy extends AppModel{
}
return $updated;
}
private function __updateVocab(&$vocab, &$current, $skipUpdateFields = array()) {
$enabled = false;
$taxonomy = array();
@ -87,7 +87,7 @@ class Taxonomy extends AppModel{
}
return $this->validationErrors;
}
private function __getTaxonomy($id, $options = array('full' => false, 'filter' => false)) {
$recursive = -1;
if ($options['full']) $recursive = 2;
@ -122,7 +122,7 @@ class Taxonomy extends AppModel{
$taxonomy['entries'] = $entries;
return $taxonomy;
}
// returns all tags associated to a taxonomy
// returns all tags not associated to a taxonomy if $inverse is true
public function getAllTaxonomyTags($inverse = false) {
@ -140,7 +140,7 @@ class Taxonomy extends AppModel{
}
return $allTags;
}
public function getTaxonomyTags($id, $uc = false, $existingOnly = false) {
$taxonomy = $this->__getTaxonomy($id, array('full' => true, 'filter' => false));
if ($existingOnly) {
@ -163,7 +163,7 @@ class Taxonomy extends AppModel{
}
return $entries;
}
public function getTaxonomy($id, $options = array('full' => true)) {
$this->Tag = ClassRegistry::init('Tag');
$taxonomy = $this->__getTaxonomy($id, $options);
@ -178,7 +178,7 @@ class Taxonomy extends AppModel{
}
return $taxonomy;
}
private function __updateTags($id, $skipUpdateFields = array()) {
$this->Tag = ClassRegistry::init('Tag');
App::uses('ColourPaletteTool', 'Tools');
@ -198,7 +198,7 @@ class Taxonomy extends AppModel{
}
}
}
public function addTags($id, $tagList = false) {
if ($tagList && !is_array($tagList)) $tagList = array($tagList);
$this->Tag = ClassRegistry::init('Tag');

View File

@ -15,11 +15,11 @@ class TaxonomyEntry extends AppModel{
'rule' => array('stringNotEmpty'),
),
);
public $belongsTo = array(
'TaxonomyPredicate'
);
public function beforeValidate($options = array()) {
parent::beforeValidate();
return true;

View File

@ -21,7 +21,7 @@ class TaxonomyPredicate extends AppModel{
'dependent' => true
)
);
public function beforeValidate($options = array()) {
parent::beforeValidate();
return true;

View File

@ -17,14 +17,14 @@ class Template extends AppModel {
'dependent' => true,
)
);
public function trimElementPositions($id) {
// permissions
$this->id = $id;
if (!$this->exists()) {
throw new NotFoundException(__('Invalid template.'));
}
$template = $this->find('first', array(
'conditions' => array('id' => $id),
'recursive' => -1,
@ -38,32 +38,32 @@ class Template extends AppModel {
}
$this->saveAll($template);
}
public function checkAuthorisation($id, $user, $write) {
// fetch the bare template
$template = $this->find('first', array(
'conditions' => array('id' => $id),
'recursive' => -1,
));
// if not found return false
if (empty($template)) return false;
//if the user is a site admin, return the template withoug question
if ($user['Role']['perm_site_admin']) return $template;
if ($write) {
// if write access is requested, check if template belongs to user's org and whether the user is authorised to edit templates
if ($user['Organisation']['name'] == $template['Template']['org'] && $user['Role']['perm_template']) return $template;
return false;
} else {
// if read access is requested, check if the template belongs to the user's org or alternatively whether the template is shareable
if ($user['Organisation']['name'] == $template['Template']['org'] || $template['Template']['share']) return $template;
return false;
}
}
public function generateRandomFileName() {
$length = 12;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

View File

@ -20,7 +20,7 @@ class TemplateElement extends AppModel {
)
);
public $belongsTo = array('Template');
public function lastPosition($template_id) {
$result = $this->find('first', array(
'fields' => array('MAX(position) AS pos', 'id', 'template_id'),

View File

@ -9,7 +9,7 @@ App::uses('AppModel', 'Model');
class TemplateElementAttribute extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('TemplateElement');
public $validate = array(
'name' => array(
'valueNotEmpty' => array(

View File

@ -9,7 +9,7 @@ App::uses('AppModel', 'Model');
class TemplateElementFile extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('TemplateElement');
public $validate = array(
'name' => array(
'rule' => array('valueNotEmpty'),

View File

@ -9,7 +9,7 @@ App::uses('AppModel', 'Model');
class TemplateElementText extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('TemplateElement');
public $validate = array(
'name' => array(
'rule' => array('valueNotEmpty'),

View File

@ -24,7 +24,7 @@ class Thread extends AppModel {
),
'SharingGroup'
);
public function updateAfterPostChange($thread, $add = false) {
$count = count($thread['Post']);
// If we have 0 posts left, delete the thread!

View File

@ -16,10 +16,10 @@ class User extends AppModel {
* @var string
*/
public $displayField = 'email';
public $orgField = array('Organisation', 'name'); // TODO Audit, LogableBehaviour + org
/**
* Validation rules
*
@ -242,7 +242,7 @@ class User extends AppModel {
'Trim',
'Containable'
);
private function __generatePassword() {
$groups = array(
'0123456789',
@ -261,7 +261,7 @@ class User extends AppModel {
}
return $pw;
}
public function beforeValidate($options = array()) {
if (!isset($this->data['User']['id'])) {
if (isset($this->data['User']['enable_password']) && (!$this->data['User']['enable_password'] || (empty($this->data['User']['password']) && empty($this->data['User']['confirm_password'])))) {
@ -328,9 +328,9 @@ class User extends AppModel {
if (empty($check['certif_public'])) {
return true;
}
// certif_public is entered
// Check if $check is a x509 certificate
if (openssl_x509_read($check['certif_public'])){
try {
@ -383,7 +383,7 @@ class User extends AppModel {
if (strlen($value) < $length) return false;
return true;
}
public function complexPassword($check) {
/*
default password:
@ -451,7 +451,7 @@ class User extends AppModel {
}
return $fails;
}
public function getOrgs() {
$orgs = $this->Organisation->find('list', array(
'recursive' => -1,
@ -459,14 +459,14 @@ class User extends AppModel {
));
return $orgs;
}
public function getOrgMemberCount($org) {
return $this->find('count', array(
'conditions' => array(
'org =' => $org,
)));
}
public function verifyGPG($id = false) {
require_once 'Crypt/GPG.php';
$this->Behaviors->detach('Trim');
@ -597,7 +597,7 @@ class User extends AppModel {
unset($user['Organisation'], $user['Role'], $user['Server']);
return $user['User'];
}
// get the current user and rearrange it to be in the same format as in the auth component
public function getAuthUserByUuid($id) {
$conditions = array('User.authkey' => $id);
@ -610,7 +610,7 @@ class User extends AppModel {
unset($user['Organisation'], $user['Role'], $user['Server']);
return $user['User'];
}
public function getAuthUserByExternalAuth($id) {
$conditions = array('User.external_auth_key' => $id, 'User.external_auth_required' => true);
$user = $this->find('first', array('conditions' => $conditions, 'recursive' => -1,'contain' => array('Organisation', 'Role', 'Server')));
@ -622,7 +622,7 @@ class User extends AppModel {
unset($user['Organisation'], $user['Role'], $user['Server']);
return $user['User'];
}
// Fetch all users that have access to an event / discussion for e-mailing (or maybe something else in the future.
// parameters are an array of org IDs that are owners (for an event this would be orgc and org)
public function getUsersWithAccess($owners = array(), $distribution, $sharing_group_id = 0, $userConditions = array()) {
@ -636,7 +636,7 @@ class User extends AppModel {
$all = false;
$validOrgs = $owners;
}
// add all orgs to the conditions that can see the SG
if ($distribution == 4) {
$sgOrgs = $sgModel->getOrgsWithAccess($sharing_group_id);
@ -699,7 +699,7 @@ class User extends AppModel {
if (isset($user['User']['gpgkey']) && !empty($user['User']['gpgkey'])) $canEncryptGPG = true;
$canEncryptSMIME = false;
if (isset($user['User']['certif_public']) && !empty($user['User']['certif_public']) && Configure::read('SMIME.enabled')) $canEncryptSMIME = true;
// If bodyonlencrypted is enabled and the user has no encryption key, use the alternate body (if it exists)
if (Configure::read('GnuPG.bodyonlyencrypted') && !$canEncryptSMIME && !$canEncryptGPG && $bodyNoEnc) {
$body = $bodyNoEnc;
@ -863,7 +863,7 @@ class User extends AppModel {
}
return false;
}
public function adminMessageResolve($message) {
$resolveVars = array('$contact' => 'MISP.contact', '$org' => 'MISP.org', '$misp' => 'MISP.baseurl');
foreach ($resolveVars as $k => $v) {
@ -872,7 +872,7 @@ class User extends AppModel {
}
return $message;
}
public function fetchPGPKey($email) {
App::uses('SyncTool', 'Tools');
$syncTool = new SyncTool();
@ -884,7 +884,7 @@ class User extends AppModel {
$results = $this->__extractPGPInfo($matches[1]);
return $results;
}
private function __extractPGPInfo($lines) {
$extractionRules = array(
'key_id' => array('regex' => '/\">(.*?)<\/a>/', 'all' => false, 'alternate' => false),
@ -910,7 +910,7 @@ class User extends AppModel {
}
return $final;
}
public function describeAuthFields() {
$fields = array();
$fields = array_merge($fields, array_keys($this->getColumnTypes()));

View File

@ -18,7 +18,7 @@ class Warninglist extends AppModel{
'rule' => array('numeric'),
),
);
public $hasMany = array(
'WarninglistEntry' => array(
'dependent' => true
@ -32,11 +32,11 @@ class Warninglist extends AppModel{
parent::beforeValidate();
return true;
}
public function checkValidTypeJSON($check) {
return true;
}
public function update() {
$directories = glob(APP . 'files' . DS . 'warninglists' . DS . 'lists' . DS . '*', GLOB_ONLYDIR);
$updated = array();
@ -67,7 +67,7 @@ class Warninglist extends AppModel{
}
return $updated;
}
private function __updateList($list, $current) {
$list['enabled'] = false;
$warninglist = array();
@ -86,7 +86,7 @@ class Warninglist extends AppModel{
$data[] = array('value' => $value, 'warninglist_id' => $this->id);
}
$this->WarninglistEntry->saveMany($data);
if (!empty($list['matching_attributes'])) {
$data = array();
foreach ($list['matching_attributes'] as $type) {
@ -102,7 +102,7 @@ class Warninglist extends AppModel{
return $this->validationErrors;
}
}
public function fetchForEventView() {
$warninglists = $this->find('all', array('contain' => array('WarninglistType'), 'conditions' => array('enabled' => true)));
if (empty($warninglists)) return array();
@ -120,7 +120,7 @@ class Warninglist extends AppModel{
}
return $warninglists;
}
public function setWarnings(&$event, &$warninglists) {
if (empty($event['objects'])) return $event;
$eventWarnings = array();
@ -142,7 +142,7 @@ class Warninglist extends AppModel{
$event['Event']['warnings'] = $eventWarnings;
return $event;
}
private function __checkValue(&$listValues, $value, $type, $listType) {
if (strpos($type, '|')) $value = explode('|', $value);
else $value = array($value);
@ -158,7 +158,7 @@ class Warninglist extends AppModel{
}
return false;
}
// This requires an IP type attribute in a non CIDR notation format
// For the future we can expand this to look for CIDR overlaps?
private function __evalCIDRList(&$listValues, $value) {
@ -182,7 +182,7 @@ class Warninglist extends AppModel{
return false;
}
private function __evalCIDR($value, &$listValues, $function) {
$found = false;
foreach ($listValues as $lv) {
@ -191,7 +191,7 @@ class Warninglist extends AppModel{
if ($found) return true;
return false;
}
// using Alnitak's solution from http://stackoverflow.com/questions/594112/matching-an-ip-to-a-cidr-mask-in-php5
private function __ipv4InCidr($ip, $cidr) {
list ($subnet, $bits) = explode('/', $cidr);
@ -201,7 +201,7 @@ class Warninglist extends AppModel{
$subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
return ($ip & $mask) == $subnet;
}
// using Snifff's solution from http://stackoverflow.com/questions/7951061/matching-ipv6-address-to-a-cidr-subnet
private function __ipv6InCidr($ip, $cidr) {
$ip = inet_pton($ip);
@ -213,7 +213,7 @@ class Warninglist extends AppModel{
$net_bits = substr($binarynet, 0, $maskbits);
return ($ip_net_bits === $net_bits);
}
// converts inet_pton output to string with bits
private function __inet_to_bits($inet) {
$unpacked = unpack('A16', $inet);
@ -224,7 +224,7 @@ class Warninglist extends AppModel{
}
return $binaryip;
}
private function __evalString(&$listValues, $value) {
if (in_array($value, $listValues)) return true;
return false;

View File

@ -12,7 +12,7 @@ class WarninglistEntry extends AppModel{
'rule' => array('valueNotEmpty'),
)
);
public $belongsTo = array(
'Warninglist' => array(
'className' => 'Warninglist',
@ -20,7 +20,7 @@ class WarninglistEntry extends AppModel{
'counterCache' => true
)
);
public function beforeValidate($options = array()) {
parent::beforeValidate();
return true;

View File

@ -12,11 +12,11 @@ class WarninglistType extends AppModel{
'rule' => array('valueNotEmpty'),
)
);
public $belongsTo = array(
'Warninglist'
);
public function beforeValidate($options = array()) {
parent::beforeValidate();
return true;

View File

@ -121,7 +121,7 @@ class Whitelist extends AppModel {
}
return $data;
}
// A simplified whitelist removal, for when we just want to throw values against the list instead of attributes / events
public function removeWhitelistedValuesFromArray($data) {
$whitelists = $this->getBlockedValues();

View File

@ -138,7 +138,7 @@ class SysLogLogableBehavior extends LogableBehavior {
$logData['Log']['version_id'] = $Model->version_id;
unset($Model->version_id);
}
if (isset($this->schema[$this->settings[$Model->alias]['userKey']]) && $this->user) {
$logData['Log'][$this->settings[$Model->alias]['userKey']] = $this->user[$this->UserModel->alias][$this->UserModel->primaryKey];
}
@ -248,7 +248,7 @@ class SysLogLogableBehavior extends LogableBehavior {
$this->Log->create($logData);
$this->Log->save(null, array(
'validate' => false));
// write to syslogd as well
$syslog = new SysLog();
if (isset($logData['Log']['change'])) {
@ -257,15 +257,15 @@ class SysLogLogableBehavior extends LogableBehavior {
$syslog->write('notice', $logData['Log']['description']);
}
}
function setup(Model $Model, $config = array()) {
if (!is_array($config)) {
$config = array();
}
$this->settings[$Model->alias] = array_merge($this->defaults, $config);
$this->settings[$Model->alias]['ignore'][] = $Model->primaryKey;
$this->Log = ClassRegistry::init('Log');
if ($this->settings[$Model->alias]['userModel'] != $Model->alias) {
$this->UserModel = ClassRegistry::init($this->settings[$Model->alias]['userModel']);

View File

@ -12,40 +12,40 @@
* 2012-02-13 ms
*/
class UrlCacheManager {
/**
* Holds all generated urls so far by the application indexed by a custom hash
*
*/
public static $cache = array();
/**
* Holds all generated urls so far by the application indexed by a custom hash
*
*/
public static $cachePage = array();
/**
* Holds all generated urls so far by the application indexed by a custom hash
*
*/
public static $extras = array();
/**
* type for the current set (triggered by last get)
*/
public static $type = 'cache';
/**
* key for current get/set
*/
public static $key = null;
/**
* cache key for pageFiles
*/
public static $cacheKey = 'url_map';
/**
* cache key for pageFiles
*/
@ -80,7 +80,7 @@ class UrlCacheManager {
self::$cachePage = Cache::read(self::$cachePageKey, '_cake_core_');
}
self::$cache = Cache::read(self::$cacheKey, '_cake_core_');
# still old "prefix true/false" syntax?
if (Configure::read('UrlCache.verbosePrefixes')) {
unset(self::$paramFields[3]);
@ -93,7 +93,7 @@ class UrlCacheManager {
}
self::$extras = array_merge($defaults, self::$extras);
}
/**
* should be called in afterLayout()
*
@ -154,5 +154,5 @@ class UrlCacheManager {
self::$cache[self::$key] = $data;
}
}
}

View File

@ -23,11 +23,11 @@
$initialDistribution = Configure::read('MISP.default_attribute_distribution');
}
}
?>
<div class="input clear"></div>
<?php
echo $this->Form->input('distribution', array(
'options' => array($distributionLevels),
'label' => 'Distribution',
@ -195,7 +195,7 @@ $(document).ready(function() {
}).popover('show');
// $('#'+e.currentTarget.id).on('mouseleave', $('#'+e.currentTarget.id).popover('destroy');
//$('#'+e.currentTarget.id).on('mouseout', $('#'+e.currentTarget.id).popover('destroy'));
});
// workaround for browsers like IE and Chrome that do now have an onmouseover on the 'options' of a select.

View File

@ -129,7 +129,7 @@ $(document).ready(function() {
if ($('#AttributeDistribution').val() == 4) $('#SGContainer').show();
else $('#SGContainer').hide();
});
$("#AttributeCategory, #AttributeDistribution").on('mouseover', function(e) {
var $e = $(e.target);
if ($e.is('option')) {
@ -141,11 +141,11 @@ $(document).ready(function() {
}).popover('show');
}
});
$("input, label").on('mouseleave', function(e) {
$('#'+e.currentTarget.id).popover('destroy');
});
$("input, label").on('mouseover', function(e) {
var $e = $(e.target);
$('#'+e.currentTarget.id).popover('destroy');
@ -154,7 +154,7 @@ $(document).ready(function() {
placement: 'right',
}).popover('show');
});
// workaround for browsers like IE and Chrome that do now have an onmouseover on the 'options' of a select.
// disadvangate is that user needs to click on the item to see the tooltip.
// no solutions exist, except to generate the select completely using html.
@ -168,7 +168,7 @@ $(document).ready(function() {
}).popover('show');
});
});
function malwareCheckboxSetter(id) {
idDiv = id+'Div';
var value = $(id).val(); // get the selected value

View File

@ -85,9 +85,9 @@ $(document).ready(function() {
if ($('#AttributeDistribution').val() == 4) $('#SGContainer').show();
else $('#SGContainer').hide();
});
$('#AttributeAttributeIds').attr('value', getSelected());
$("#Attribute, #AttributeDistribution").on('mouseover', function(e) {
var $e = $(e.target);
if ($e.is('option')) {

View File

@ -12,7 +12,7 @@
<th>Attribute Count</th>
</tr>
<?php
foreach ($events as $event) {
?>

View File

@ -94,7 +94,7 @@ foreach ($categoryDefinitions as $category => $def) {
echo "formInfoValues['" . addslashes($category) . "'] = \"" . addslashes($info) . "\";\n"; // as we output JS code we need to add slashes
}
?>
$(document).ready(function() {
$("#AttributeType, #AttributeCategory").on('mouseover', function(e) {
var $e = $(e.target);
@ -144,7 +144,7 @@ $(document).ready(function() {
content: formInfoValues[$e.val()],
}).popover('show');
});
$('#cancel_attribute_add').click(function() {
cancelPopoverForm();
});

View File

@ -10,11 +10,11 @@
echo $this->Form->input('type', array(
'empty' => '(first choose category)'
));
?>
<div class="input clear"></div>
<?php
echo $this->Form->input('distribution', array(
'options' => array($distributionLevels),
'label' => 'Distribution',
@ -121,12 +121,12 @@ foreach ($distributionDescriptions as $type => $def) {
?>
$(document).ready(function() {
$('#AttributeDistribution').change(function() {
if ($('#AttributeDistribution').val() == 4) $('#SGContainer').show();
else $('#SGContainer').hide();
});
$("#AttributeType, #AttributeCategory, #Attribute, #AttributeDistribution").on('mouseover', function(e) {
var $e = $(e.target);
if ($e.is('option')) {

Some files were not shown because too many files have changed in this diff Show More