-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Server.php
8084 lines (7732 loc) · 368 KB
/
Server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
App::uses('AppModel', 'Model');
App::uses('GpgTool', 'Tools');
App::uses('ServerSyncTool', 'Tools');
App::uses('SystemSetting', 'Model');
App::uses('EncryptedValue', 'Tools');
App::uses('GitTool', 'Tools');
App::uses('ProcessTool', 'Tools');
/**
* @property-read array $serverSettings
* @property-read array $command_line_functions
* @property Organisation $Organisation
* @property User $User
*/
class Server extends AppModel
{
const SETTING_CRITICAL = 0,
SETTING_RECOMMENDED = 1,
SETTING_OPTIONAL = 2;
public $name = 'Server';
public $actsAs = array(
'AuditLog',
'SysLogLogable.SysLogLogable' => array(
'userModel' => 'User',
'userKey' => 'user_id',
'change' => 'full'
),
'Trim',
'Containable'
);
public $belongsTo = array(
'Organisation' => array(
'className' => 'Organisation',
'foreignKey' => 'org_id',
),
'RemoteOrg' => array(
'className' => 'Organisation',
'foreignKey' => 'remote_org_id',
)
);
public $hasMany = array(
'SharingGroupServer' => array(
'className' => 'SharingGroupServer',
'foreignKey' => 'server_id',
'dependent'=> true,
),
'User' => array(
'className' => 'User',
'foreignKey' => 'server_id',
),
);
public $displayField = 'url';
public $validate = array(
'url' => array(
'url' => array(
'rule' => array('validateURL'),
'message' => 'Please enter a valid base-url.'
)
),
'authkey' => array(
'rule' => array('validateAuthkey')
),
'name' => array(
'rule' => array('notBlank'),
'allowEmpty' => false,
'required' => true
),
'org_id' => array(
'numeric' => array(
'rule' => array('valueIsID'),
'allowEmpty' => false,
'required' => true,
),
),
'push' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
'allowEmpty' => true,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'pull' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
'allowEmpty' => true,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'push_sightings' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
'allowEmpty' => true,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'lastpushedid' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
'allowEmpty' => true,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'lastpulledid' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
'allowEmpty' => true,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
public $syncTestErrorCodes = array();
const MYSQL_RECOMMENDED_SETTINGS = [
'innodb_buffer_pool_size' => [
'default' => '134217728',
'recommended' => '2147483648',
'explanation' => 'The InnoDB buffer pool is the memory area where caches table and index data reside. It is the most important MySQL setting, in a dedicated server it should be around 3/4 of all the available RAM. In a shared server it should be around 1/2 of the available RAM.',
],
'innodb_dedicated_server' => [
'default' => '0',
'recommended' => '',
'explanation' => 'Set to `1` if the database is running in a dedicated server. The database engine will examine the available memory and dynamically set `innodb_buffer_pool_size`, `innodb_log_file_size`, `innodb_log_files_in_group` and `innodb_flush_method`. It is particularly useful in cloud enviroments that can be auto-scaled.',
],
'innodb_log_file_size' => [
'default' => '100663296',
'recommended' => '629145600',
'explanation' => 'This parameter determines the fixed size for MySQLs redo logs. Tuning this value affects the crash recovery time and also overall system performance.',
],
'innodb_log_files_in_group' => [
'default' => '2',
'recommended' => '2',
'explanation' => 'Defines the number of log files in the log group.',
],
'innodb_change_buffering' => [
'default' => 'none',
'recommended' => 'none',
'explanation' => 'Whether InnoDB performs change buffering, an optimization that delays write operations to secondary indexes so that the I/O operations can be performed sequentially, enabling it causes extremely long shutdown times for upgrades.',
],
'innodb_io_capacity' => [
'default' => '200',
'recommended' => '1000',
'explanation' => 'Defines the number of I/O operations per second (IOPS) available to InnoDB background tasks, such as flushing pages from the buffer pool and merging data from the change buffer.',
],
'innodb_io_capacity_max' => [
'default' => '2000',
'recommended' => '2000',
'explanation' => 'If flushing activity falls behind, InnoDB can flush more aggressively, at a higher rate of I/O operations per second (IOPS) than defined by the `innodb_io_capacity variable`.',
],
'innodb_stats_persistent' => [
'default' => 'ON',
'recommended' => 'ON',
'explanation' => 'Specifies whether InnoDB index statistics are persisted to disk. Otherwise, statistics may be recalculated frequently which can lead to variations in query execution plans.',
],
'innodb_read_io_threads' => [
'default' => '4',
'recommended' => '16',
'explanation' => 'The number of I/O threads for read operations in InnoDB.',
],
'innodb_write_io_threads' => [
'default' => '4',
'recommended' => '4',
'explanation' => 'The number of I/O threads for write operations in InnoDB.',
],
];
public function __construct($id = false, $table = null, $ds = null)
{
parent::__construct($id, $table, $ds);
$this->syncTestErrorCodes = array(
2 => __('Server unreachable'),
3 => __('Unexpected error'),
4 => __('Authentication failed'),
5 => __('Password change required'),
6 => __('Terms not accepted')
);
}
public $actions_description = array(
'verifyGnuPGkeys' => array(
'title' => 'Verify GnuPG keys',
'description' => "Run a full validation of all GnuPG keys within this instance's userbase. The script will try to identify possible issues with each key and report back on the results.",
'url' => '/users/verifyGPG/'
),
'databaseCleanupScripts' => array(
'title' => 'Database Cleanup Scripts',
'description' => 'If you run into an issue with an infinite upgrade loop (when upgrading from version ~2.4.50) that ends up filling your database with upgrade script log messages, run the following script.',
'url' => '/logs/pruneUpdateLogs/'
),
'releaseUpdateLock' => array(
'title' => 'Release update lock',
'description' => 'If your your database is locked and is not updating, unlock it here.',
'ignore_disabled' => true,
'url' => '/servers/releaseUpdateLock/'
),
'normalizeCustomTagsToTaxonomyFormat' => array(
'title' => 'Normalize custom tags to taxonomy format',
'description' => 'Transform all custom tags existing in a taxonomy into the taxonomy version',
'url' => '/taxonomies/normalizeCustomTagsToTaxonomyFormat/'
),
);
public $validEventIndexFilters = array('searchall', 'searchpublished', 'searchorg', 'searchtag', 'searcheventid', 'searchdate', 'searcheventinfo', 'searchthreatlevel', 'searchdistribution', 'searchanalysis', 'searchattribute');
public function beforeSave($options = array())
{
$server = &$this->data['Server'];
if (!empty($server['url'])) {
$server['url'] = rtrim($server['url'], '/');
}
if (empty($server['id'])) {
$max_prio = $this->find('first', array(
'recursive' => -1,
'order' => array('Server.priority' => 'DESC'),
'fields' => array('Server.priority')
));
if (empty($max_prio)) {
$max_prio = 0;
} else {
$max_prio = $max_prio['Server']['priority'];
}
$server['priority'] = $max_prio + 1;
}
// Encrypt authkey if plain key provided and encryption is enabled
if (!empty($server['authkey']) && strlen($server['authkey']) === 40) {
$server['authkey'] = EncryptedValue::encryptIfEnabled($server['authkey']);
}
try {
// Clean caches when remote server setting changed
$cacheKeys = [
"misp:event_index:{$this->id}",
"misp:fetched_sightings:{$this->id}",
"misp:empty_events:{$this->id}",
];
RedisTool::unlink(RedisTool::init(), $cacheKeys);
} catch (Exception $e) {
// ignore
}
return true;
}
/**
* @param int|string $technique 'full', 'update', remote event ID or remote event UUID
* @param ServerSyncTool $serverSync
* @param bool $force
* @return array Event UUIDSs or IDs
* @throws HttpSocketHttpException
* @throws HttpSocketJsonException
*/
private function __getEventIdListBasedOnPullTechnique($technique, ServerSyncTool $serverSync, $force = false)
{
if ("full" === $technique) {
// get a list of the event_ids on the server
$eventIds = $this->getEventIdsFromServer($serverSync, false, false, $force);
// reverse array of events, to first get the old ones, and then the new ones
return array_reverse($eventIds);
} elseif ("update" === $technique) {
$eventIds = $this->getEventIdsFromServer($serverSync, false, true, $force);
$eventModel = ClassRegistry::init('Event');
$localEventUuids = $eventModel->find('column', array(
'fields' => array('Event.uuid'),
));
return array_intersect($eventIds, $localEventUuids);
} elseif (is_numeric($technique)) {
return array(intval($technique));
} elseif (Validation::uuid($technique)) {
return array($technique);
}
throw new InvalidArgumentException("Invalid pull technique `$technique`.");
}
/**
* @param array $event
* @param array $server
* @param array $user
* @param array $pullRules
* @return bool Return true if event was emptied by pull rules
*/
private function __updatePulledEventBeforeInsert(array &$event, array $server, array $user, array $pullRules)
{
$pullRulesEmptiedEvent = false;
// we have an Event array
// The event came from a pull, so it should be locked.
$event['Event']['locked'] = true;
if (!isset($event['Event']['distribution'])) { // version 1
$event['Event']['distribution'] = '1';
}
// Distribution
if (empty(Configure::read('MISP.host_org_id')) || !$server['Server']['internal'] || Configure::read('MISP.host_org_id') != $server['Server']['org_id']) {
switch ($event['Event']['distribution']) {
case 1:
// if community only, downgrade to org only after pull
$event['Event']['distribution'] = '0';
break;
case 2:
// if connected communities downgrade to community only
$event['Event']['distribution'] = '1';
break;
}
// We remove local tags obtained via pull
if (isset($event['Event']['Tag'])) {
foreach ($event['Event']['Tag'] as $key => $a) {
if ($a['local']) {
unset($event['Event']['Tag'][$key]);
}
}
}
$filterOnTypeEnabled = !empty(Configure::read('MISP.enable_synchronisation_filtering_on_type'));
$attributeTypeFilteringEnabled = $filterOnTypeEnabled && !empty($pullRules['type_attributes']['NOT']);
if (isset($event['Event']['Attribute'])) {
$originalCount = count($event['Event']['Attribute']);
foreach ($event['Event']['Attribute'] as $key => $attribute) {
if ($attributeTypeFilteringEnabled && in_array($attribute['type'], $pullRules['type_attributes']['NOT'], true)) {
unset($event['Event']['Attribute'][$key]);
continue;
}
switch ($attribute['distribution']) {
case '1':
$event['Event']['Attribute'][$key]['distribution'] = '0';
break;
case '2':
$event['Event']['Attribute'][$key]['distribution'] = '1';
break;
}
// We remove local tags obtained via pull
if (isset($attribute['Tag'])) {
foreach ($attribute['Tag'] as $k => $v) {
if ($v['local']) {
unset($event['Event']['Attribute'][$key]['Tag'][$k]);
}
}
}
}
if ($attributeTypeFilteringEnabled && $originalCount > 0 && empty($event['Event']['Attribute'])) {
$pullRulesEmptiedEvent = true;
}
}
if (isset($event['Event']['Object'])) {
$originalObjectCount = count($event['Event']['Object']);
foreach ($event['Event']['Object'] as $i => $object) {
if (
$filterOnTypeEnabled &&
!empty($pullRules['type_objects']['NOT']) &&
in_array($object['template_uuid'], $pullRules['type_objects']['NOT'], true)
) {
unset($event['Event']['Object'][$i]);
continue;
}
switch ($object['distribution']) {
case '1':
$event['Event']['Object'][$i]['distribution'] = '0';
break;
case '2':
$event['Event']['Object'][$i]['distribution'] = '1';
break;
}
if (isset($object['Attribute'])) {
$originalAttributeCount = count($object['Attribute']);
foreach ($object['Attribute'] as $j => $a) {
if ($attributeTypeFilteringEnabled && in_array($a['type'], $pullRules['type_attributes']['NOT'], true)) {
unset($event['Event']['Object'][$i]['Attribute'][$j]);
continue;
}
switch ($a['distribution']) {
case '1':
$event['Event']['Object'][$i]['Attribute'][$j]['distribution'] = '0';
break;
case '2':
$event['Event']['Object'][$i]['Attribute'][$j]['distribution'] = '1';
break;
}
// We remove local tags obtained via pull
if (isset($a['Tag'])) {
foreach ($a['Tag'] as $k => $v) {
if ($v['local']) {
unset($event['Event']['Object'][$i]['Attribute'][$j]['Tag'][$k]);
}
}
}
}
if ($attributeTypeFilteringEnabled && $originalAttributeCount > 0 && empty($event['Event']['Object'][$i]['Attribute'])) {
unset($event['Event']['Object'][$i]); // Object is empty, get rid of it
}
}
}
if ($filterOnTypeEnabled && $originalObjectCount > 0 && empty($event['Event']['Object'])) {
$pullRulesEmptiedEvent = true;
}
}
if (isset($event['Event']['EventReport'])) {
foreach ($event['Event']['EventReport'] as $key => $r) {
switch ($r['distribution']) {
case '1':
$event['Event']['EventReport'][$key]['distribution'] = '0';
break;
case '2':
$event['Event']['EventReport'][$key]['distribution'] = '1';
break;
}
}
}
}
// Distribution, set reporter of the event, being the admin that initiated the pull
$event['Event']['user_id'] = $user['id'];
return $pullRulesEmptiedEvent;
}
/**
* @param array $event
* @return bool True if event is not empty
*/
private function __checkIfEventSaveAble(array $event)
{
if (!empty($event['Event']['Attribute'])) {
foreach ($event['Event']['Attribute'] as $attribute) {
if (empty($attribute['deleted'])) {
return true;
}
}
}
if (!empty($event['Event']['Object'])) {
foreach ($event['Event']['Object'] as $object) {
if (!empty($object['deleted'])) {
continue;
}
if (!empty($object['Attribute'])) {
foreach ($object['Attribute'] as $attribute) {
if (empty($attribute['deleted'])) {
return true;
}
}
}
}
}
if (!empty($event['Event']['EventReport'])) {
foreach ($event['Event']['EventReport'] as $report) {
if (empty($report['deleted'])) {
return true;
}
}
}
return false;
}
/**
* @param array $event
* @param int|string $eventId
* @param array $successes
* @param array $fails
* @param Event $eventModel
* @param array $server
* @param array $user
* @param int $jobId
* @param bool $force
* @param HttpSocketResponseExtended $response
* @return false|void
* @throws Exception
*/
private function __checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, &$successes, &$fails, Event $eventModel, $server, $user, $jobId, $force = false, $response)
{
// check if the event already exist (using the uuid)
$existingEvent = $eventModel->find('first', [
'conditions' => ['Event.uuid' => $event['Event']['uuid']],
'recursive' => -1,
'fields' => ['id', 'locked', 'protected'],
'contain' => ['CryptographicKey']
]);
$passAlong = $server['Server']['id'];
if (!$existingEvent) {
// add data for newly imported events
if (isset($event['Event']['protected']) && $event['Event']['protected']) {
if (!$eventModel->CryptographicKey->validateProtectedEvent($response->body, $user, $response->getHeader('x-pgp-signature'), $event)) {
$fails[$eventId] = __('Event failed the validation checks. The remote instance claims that the event can be signed with a valid key which is sus.');
return false;
}
}
$result = $eventModel->_add($event, true, $user, $server['Server']['org_id'], $passAlong, true, $jobId);
if ($result) {
$successes[] = $eventId;
if ($this->pubToZmq('event')) {
$pubSubTool = $this->getPubSubTool();
$pubSubTool->event_save(array('Event' => $eventId, 'Server' => $server['Server']['id']), 'add_from_connected_server');
}
} else {
$fails[$eventId] = __('Failed (partially?) because of validation errors: ') . json_encode($eventModel->validationErrors);
}
} else {
if (!$existingEvent['Event']['locked'] && !$server['Server']['internal']) {
$fails[$eventId] = __('Blocked an edit to an event that was created locally. This can happen if a synchronised event that was created on this instance was modified by an administrator on the remote side.');
} else {
if ($existingEvent['Event']['protected']) {
if (!$eventModel->CryptographicKey->validateProtectedEvent($response->body, $user, $response->getHeader('x-pgp-signature'), $existingEvent)) {
$fails[$eventId] = __('Event failed the validation checks. The remote instance claims that the event can be signed with a valid key which is sus.');
}
}
$result = $eventModel->_edit($event, $user, $existingEvent['Event']['id'], $jobId, $passAlong, $force);
if ($result === true) {
$successes[] = $eventId;
if ($this->pubToZmq('event')) {
$pubSubTool = $this->getPubSubTool();
$pubSubTool->event_save(array('Event' => $eventId, 'Server' => $server['Server']['id']), 'edit_from_connected_server');
}
} elseif (isset($result['error'])) {
$fails[$eventId] = $result['error'];
} else {
$fails[$eventId] = json_encode($result);
}
}
}
}
/**
* @param int|string $eventId Event ID or UUID
* @param array $successes
* @param array $fails
* @param Event $eventModel
* @param ServerSyncTool $serverSync
* @param array $user
* @param int $jobId
* @param bool $force
* @return bool
*/
private function __pullEvent($eventId, array &$successes, array &$fails, Event $eventModel, ServerSyncTool $serverSync, $user, $jobId, $force = false)
{
$params = [
'deleted' => [0, 1],
'excludeGalaxy' => 1,
'includeEventCorrelations' => 0, // we don't need remote correlations
'includeFeedCorrelations' => 0,
'includeWarninglistHits' => 0, // we don't need remote warninglist hits
];
if (empty($serverSync->server()['Server']['internal'])) {
$params['excludeLocalTags'] = 1;
}
try {
$response = $serverSync->fetchEvent($eventId, $params);
$event = $response->json();
} catch (Exception $e) {
$this->logException("Failed to download the event $eventId from remote server {$serverSync->serverId()} '{$serverSync->serverName()}'", $e);
$fails[$eventId] = __('failed downloading the event');
return false;
}
$pullRulesEmptiedEvent = $this->__updatePulledEventBeforeInsert($event, $serverSync->server(), $user, $serverSync->pullRules());
if (!$this->__checkIfEventSaveAble($event)) {
if (!$pullRulesEmptiedEvent) { // The event is empty because of the filtering rule. This is not considered a failure
$fails[$eventId] = __('Empty event detected.');
$this->addEmptyEvent($serverSync->serverId(), $event);
}
return false;
}
try {
$this->__checkIfPulledEventExistsAndAddOrUpdate($event, $eventId, $successes, $fails, $eventModel, $serverSync->server(), $user, $jobId, $force, $response);
} catch (Exception $e) {
$title = __('Pulling an event (#%s) from Server #%s has failed. The sync process was not interrupted.', $eventId, $serverSync->serverId());
$this->loadLog()->createLogEntry(
$user,
'error',
'Server',
$serverSync->serverId(),
$title, $e->getMessage());
}
return true;
}
/**
* @param array $user
* @param string $technique
* @param array $server
* @param int|false $jobId
* @param bool $force
* @return array|string
* @throws HttpSocketHttpException
* @throws HttpSocketJsonException
* @throws JsonException
*/
public function pull(array $user, $technique, array $server, $jobId = false, $force = false)
{
if ($jobId) {
Configure::write('CurrentUserId', $user['id']);
$job = ClassRegistry::init('Job');
$email = "Scheduled job";
} else {
$email = $user['email'];
}
$serverSync = new ServerSyncTool($server, $this->setupSyncRequest($server));
try {
$server['Server']['version'] = $serverSync->info()['version'];
} catch (Exception $e) {
$this->logException("Could not get remote server `{$server['Server']['name']}` version.", $e);
if ($e instanceof HttpSocketHttpException && $e->getCode() === 403) {
$message = __('Not authorised. This is either due to an invalid auth key, or due to the sync user not having authentication permissions enabled on the remote server. Another reason could be an incorrect sync server setting.');
} else {
$message = $e->getMessage();
}
$title = 'Failed pull from ' . $server['Server']['url'] . ' initiated by ' . $email;
$this->loadLog()->createLogEntry($user, 'error', 'Server', $server['Server']['id'], $title, $message);
return $message;
}
$pulledClusters = 0;
if (!empty($server['Server']['pull_galaxy_clusters'])) {
$this->GalaxyCluster = ClassRegistry::init('GalaxyCluster');
if ($jobId) {
$job->saveProgress($jobId, $technique === 'pull_relevant_clusters' ? __('Pulling relevant galaxy clusters.') : __('Pulling galaxy clusters.'));
}
$pulledClusters = $this->GalaxyCluster->pullGalaxyClusters($user, $serverSync, $technique);
if ($technique === 'pull_relevant_clusters') {
if ($jobId) {
$job->saveStatus($jobId, true, 'Pulling complete.');
}
return array(array(), array(), 0, 0, $pulledClusters);
}
if ($jobId) {
$job->saveProgress($jobId, 'Pulling events.', 10);
}
}
try {
$eventIds = $this->__getEventIdListBasedOnPullTechnique($technique, $serverSync, $force);
} catch (Exception $e) {
$this->logException("Could not fetch event IDs from server `{$server['Server']['name']}`.", $e);
if ($e instanceof HttpSocketHttpException && $e->getCode() === 403) {
$message = __('Not authorised. This is either due to an invalid auth key, or due to the sync user not having authentication permissions enabled on the remote server. Another reason could be an incorrect sync server setting.');
} else {
$message = $e->getMessage();
}
$title = 'Failed pull from ' . $server['Server']['url'] . ' initiated by ' . $email;
$this->loadLog()->createLogEntry($user, 'error', 'Server', $server['Server']['id'], $title, $message);
return $message;
}
/** @var Event $eventModel */
$eventModel = ClassRegistry::init('Event');
$successes = [];
$fails = [];
// now process the $eventIds to pull each of the events sequentially
if (!empty($eventIds)) {
// download each event
if ($jobId) {
$job->saveProgress($jobId, __n('Pulling %s event.', 'Pulling %s events.', count($eventIds), count($eventIds)));
}
foreach ($eventIds as $k => $eventId) {
$this->__pullEvent($eventId, $successes, $fails, $eventModel, $serverSync, $user, $jobId, $force);
if ($jobId && $k % 10 === 0) {
$job->saveProgress($jobId, null, 10 + 40 * (($k + 1) / count($eventIds)));
}
}
foreach ($fails as $eventid => $message) {
$this->loadLog()->createLogEntry($user, 'pull', 'Server', $server['Server']['id'], "Failed to pull event #$eventid.", 'Reason: ' . $message);
}
}
if ($jobId) {
$job->saveProgress($jobId, 'Pulling proposals.', 50);
}
$pulledProposals = $pulledSightings = 0;
if ($technique === 'full' || $technique === 'update') {
$pulledProposals = $eventModel->ShadowAttribute->pullProposals($user, $serverSync);
if ($jobId) {
$job->saveProgress($jobId, 'Pulling sightings.', 75);
}
$pulledSightings = $eventModel->Sighting->pullSightings($user, $serverSync);
$this->AnalystData = ClassRegistry::init('AnalystData');
$pulledAnalystData = $this->AnalystData->pull($user, $serverSync);
}
if ($jobId) {
$job->saveStatus($jobId, true, 'Pull completed.');
}
$change = sprintf(
'%s events, %s proposals, %s sightings, %s galaxy clusters and %s analyst data pulled or updated. %s events failed or didn\'t need an update.',
count($successes),
$pulledProposals,
$pulledSightings,
$pulledClusters,
$pulledAnalystData,
count($fails)
);
$this->loadLog()->createLogEntry($user, 'pull', 'Server', $server['Server']['id'], 'Pull from ' . $server['Server']['url'] . ' initiated by ' . $email, $change);
return [$successes, $fails, $pulledProposals, $pulledSightings, $pulledClusters, $pulledAnalystData];
}
public function filterRuleToParameter($filter_rules)
{
$final = array();
if (empty($filter_rules)) {
return $final;
}
$filter_rules = $this->jsonDecode($filter_rules);
$url_params = array();
foreach ($filter_rules as $field => $rules) {
$temp = array();
if ($field === 'url_params') {
$url_params = empty($rules) ? [] : $this->jsonDecode($rules);
} else {
foreach ($rules as $operator => $elements) {
foreach ($elements as $k => $element) {
if ($operator === 'NOT') {
$element = '!' . $element;
}
if (!empty($element)) {
$temp[] = $element;
}
}
}
if (!empty($temp)) {
$final[substr($field, 0, strlen($field) -1)] = $temp;
}
}
}
if (!empty($url_params)) {
$final = array_merge_recursive($final, $url_params);
}
return $final;
}
/**
* fetchCustomClusterIdsFromServer Fetch custom-published remote clusters' UUIDs and versions
*
* @param ServerSyncTool $serverSync
* @param array $conditions
* @return array The list of clusters
* @throws JsonException|HttpSocketHttpException|HttpSocketJsonException
*/
private function fetchCustomClusterIdsFromServer(ServerSyncTool $serverSync, array $conditions = [])
{
$filterRules = [
'published' => 1,
'minimal' => 1,
'custom' => 1,
];
$filterRules = array_merge($filterRules, $conditions);
$clusterArray = $serverSync->galaxyClusterSearch($filterRules)->json();
if (isset($clusterArray['response'])) {
$clusterArray = $clusterArray['response'];
}
return $clusterArray;
}
/**
* fetchUUIDsFromServer Fetch remote analyst datas' UUIDs and timestamp
*
* @param ServerSyncTool $serverSync
* @param array $conditions
* @return array The list of analyst data
* @throws JsonException|HttpSocketHttpException|HttpSocketJsonException
*/
public function fetchUUIDsFromServer(ServerSyncTool $serverSync, array $conditions = [])
{
$filterRules = $conditions;
$dataArray = $serverSync->fetchIndexMinimal($filterRules)->json();
if (isset($dataArray['response'])) {
$dataArray = $dataArray['response'];
}
return $dataArray;
}
/**
* filterAnalystDataForPush Send a candidate data to be pushed and returns the list of accepted entries
*
* @param ServerSyncTool $serverSync
* @param array $conditions
* @return array The list of analyst data
* @throws JsonException|HttpSocketHttpException|HttpSocketJsonException
*/
public function filterAnalystDataForPush(ServerSyncTool $serverSync, array $candidates = [])
{
$dataArray = $serverSync->filterAnalystDataForPush($candidates)->json();
if (isset($dataArray['response'])) {
$dataArray = $dataArray['response'];
}
return $dataArray;
}
/**
* Get a list of cluster IDs that are present on the remote server and returns clusters that should be pulled
*
* @param ServerSyncTool $serverSync
* @param bool $onlyUpdateLocalCluster If set to true, only cluster present locally will be returned
* @param array $eligibleClusters Array of cluster present locally that could potentially be updated. Linked to $onlyUpdateLocalCluster
* @param array $conditions Conditions to be sent to the remote server while fetching accessible clusters IDs
* @return array List of cluster UUIDs to be pulled
* @throws HttpSocketHttpException
* @throws HttpSocketJsonException
* @throws JsonException
*/
public function getElligibleClusterIdsFromServerForPull(ServerSyncTool $serverSync, $onlyUpdateLocalCluster=true, array $eligibleClusters=array(), array $conditions=array())
{
$this->log("Fetching eligible clusters from server #{$serverSync->serverId()} for pull: " . JsonTool::encode($conditions), LOG_INFO);
if ($onlyUpdateLocalCluster && empty($eligibleClusters)) {
return []; // no clusters for update
}
$clusterArray = $this->fetchCustomClusterIdsFromServer($serverSync, $conditions=$conditions);
if (empty($clusterArray)) {
return []; // empty remote clusters
}
/** @var GalaxyClusterBlocklist $GalaxyClusterBlocklist */
$GalaxyClusterBlocklist = ClassRegistry::init('GalaxyClusterBlocklist');
if (!$onlyUpdateLocalCluster) {
/** @var GalaxyCluster $GalaxyCluster */
$GalaxyCluster = ClassRegistry::init('GalaxyCluster');
// Do not fetch clusters with the same or newer version that already exists on local instance
$eligibleClusters = $GalaxyCluster->find('list', [
'conditions' => ['GalaxyCluster.uuid' => array_column(array_column($clusterArray, 'GalaxyCluster'), 'uuid')],
'fields' => ['GalaxyCluster.uuid', 'GalaxyCluster.version'],
]);
}
$clustersForPull = [];
foreach ($clusterArray as $cluster) {
$clusterUuid = $cluster['GalaxyCluster']['uuid'];
if ($GalaxyClusterBlocklist->checkIfBlocked($clusterUuid)) {
continue; // skip blocked clusters
}
if (isset($eligibleClusters[$clusterUuid])) {
$localVersion = $eligibleClusters[$clusterUuid];
if ($localVersion < $cluster['GalaxyCluster']['version']) {
$clustersForPull[] = $clusterUuid;
}
} elseif (!$onlyUpdateLocalCluster) {
$clustersForPull[] = $clusterUuid;
}
}
return $clustersForPull;
}
/**
* Get an array of cluster_ids that are present on the remote server and returns clusters that should be pushed.
* @param ServerSyncTool $serverSync
* @param array $localClusters
* @param array $conditions
* @return array
* @throws HttpSocketHttpException
* @throws HttpSocketJsonException
* @throws JsonException
*/
private function getElligibleClusterIdsFromServerForPush(ServerSyncTool $serverSync, array $localClusters=array(), array $conditions=array())
{
$this->log("Fetching eligible clusters from server #{$serverSync->serverId()} for push: " . JsonTool::encode($conditions), LOG_INFO);
$clusterArray = $this->fetchCustomClusterIdsFromServer($serverSync, $conditions=$conditions);
$keyedClusterArray = Hash::combine($clusterArray, '{n}.GalaxyCluster.uuid', '{n}.GalaxyCluster.version');
if (!empty($localClusters)) {
foreach ($localClusters as $k => $localCluster) {
if (isset($keyedClusterArray[$localCluster['GalaxyCluster']['uuid']])) {
$remoteVersion = $keyedClusterArray[$localCluster['GalaxyCluster']['uuid']];
if ($localCluster['GalaxyCluster']['version'] <= $remoteVersion) {
unset($localClusters[$k]);
}
}
}
}
return $localClusters;
}
/**
* @param ServerSyncTool $serverSync
* @param bool $ignoreFilterRules Ignore defined server pull rules
* @return array
* @throws HttpSocketHttpException
* @throws HttpSocketJsonException
* @throws JsonException
* @throws RedisException
*/
public function getEventIndexFromServer(ServerSyncTool $serverSync, $ignoreFilterRules = false)
{
if (!$ignoreFilterRules) {
$filterRules = $this->filterRuleToParameter($serverSync->server()['Server']['pull_rules']);
if (!empty($filterRules['org']) && !$serverSync->isSupported(ServerSyncTool::FEATURE_ORG_RULE)) {
$filterRules['org'] = implode('|', $filterRules['org']);
}
} else {
$filterRules = [];
}
$filterRules['minimal'] = 1;
$filterRules['published'] = 1;
// Fetch event index from cache if exists and is not modified
$redis = RedisTool::init();
$indexFromCache = $redis->get("misp:event_index:{$serverSync->serverId()}");
if ($indexFromCache) {
list($etag, $eventIndex) = RedisTool::deserialize(RedisTool::decompress($indexFromCache));
} else {
$etag = '""'; // Provide empty ETag, so MISP will compute ETag for returned data
}
$response = $serverSync->eventIndex($filterRules, $etag);
if ($response->isNotModified() && $indexFromCache) {
return $eventIndex;
}
$eventIndex = $response->json();
// correct $eventArray if just one event, probably this response returns old MISP
if (isset($eventIndex['id'])) {
$eventIndex = [$eventIndex];
}
// Save to cache for 24 hours if ETag provided
$etag = $response->getHeader('etag');
if ($etag) {
$data = RedisTool::compress(RedisTool::serialize([$etag, $eventIndex]));
$redis->setex("misp:event_index:{$serverSync->serverId()}", 3600 * 24, $data);
} elseif ($indexFromCache) {
RedisTool::unlink($redis, "misp:event_index:{$serverSync->serverId()}");
}
return $eventIndex;
}
/**
* @param array $events
* @return void
*/
private function removeOlderEvents(array &$events)
{
$conditions = (count($events) > 10000) ? [] : ['Event.uuid' => array_column($events, 'uuid')];
$this->Event = ClassRegistry::init('Event');
$localEvents = $this->Event->find('all', [
'recursive' => -1,
'conditions' => $conditions,
'fields' => ['Event.uuid', 'Event.timestamp', 'Event.locked'],
]);
$localEvents = array_column(array_column($localEvents, 'Event'), null, 'uuid');
foreach ($events as $k => $event) {
$uuid = $event['uuid'];
if (isset($localEvents[$uuid]) && ($localEvents[$uuid]['timestamp'] >= $event['timestamp'] || !$localEvents[$uuid]['locked'])) {
unset($events[$k]);
}
}
}
/**
* @param int $serverId
* @param array $event
* @return void
* @throws RedisException
*/
private function addEmptyEvent($serverId, array $event)
{
$emptyEventKey = "{$event['Event']['uuid']}:{$event['Event']['timestamp']}";
$redis = RedisTool::init();
$redis->sAdd("misp:empty_events:$serverId", $emptyEventKey);
$redis->expire("misp:empty_events:$serverId", 24 * 3600);
}
/**
* Remove from $events array events, that was already fetched before and was empty.
* @param int $serverId
* @param array $events
* @return void
*/
private function removeEmptyEvents($serverId, array &$events)
{
try {
$emptyEvents = RedisTool::init()->sMembers("misp:empty_events:$serverId");
} catch (Exception $e) {
return;
}
if (empty($emptyEvents)) {
return;