-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Sighting.php
1706 lines (1559 loc) · 65.5 KB
/
Sighting.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('TmpFileTool', 'Tools');
App::uses('ServerSyncTool', 'Tools');
App::uses('ProcessTool', 'Tools');
/**
* @property Attribute $Attribute
* @property Event $Event
* @property Organisation $Organisation
*/
class Sighting extends AppModel
{
const ONE_DAY = 86400; // in seconds
// Possible values of `Plugin.Sightings_policy` setting
const SIGHTING_POLICY_EVENT_OWNER = 0,
SIGHTING_POLICY_SIGHTING_REPORTER = 1,
SIGHTING_POLICY_EVERYONE = 2,
SIGHTING_POLICY_HOST_ORG = 3; // the same as SIGHTING_POLICY_EVENT_OWNER, but also sightings from host org are visible
private $orgCache = [];
public $useTable = 'sightings';
public $recursive = -1;
public $actsAs = array(
'Containable',
);
public $validate = array(
'event_id' => 'numeric',
'attribute_id' => 'numeric',
'org_id' => 'numeric',
'date_sighting' => 'numeric',
'uuid' => 'uuid',
'type' => array(
'rule' => array('inList', array(0, 1, 2)),
'message' => 'Invalid type. Valid options are: 0 (Sighting), 1 (False-positive), 2 (Expiration).'
)
);
public $belongsTo = array(
'Attribute',
'Event',
'Organisation' => array(
'className' => 'Organisation',
'foreignKey' => 'org_id'
),
);
const TYPE = array(
0 => 'sighting',
1 => 'false-positive',
2 => 'expiration'
);
public $validFormats = array(
'json' => array('json', 'JsonExport', 'json'),
'xml' => array('xml', 'XmlExport', 'xml'),
'csv' => array('csv', 'CsvExport', 'csv')
);
public function beforeValidate($options = array())
{
if (empty($this->data['Sighting']['id']) && empty($this->data['Sighting']['date_sighting'])) {
$this->data['Sighting']['date_sighting'] = date('Y-m-d H:i:s');
}
if (empty($this->data['Sighting']['uuid'])) {
$this->data['Sighting']['uuid'] = CakeText::uuid();
} else {
$this->data['Sighting']['uuid'] = strtolower($this->data['Sighting']['uuid']);
}
return true;
}
public function afterSave($created, $options = array())
{
$pubToZmq = $this->pubToZmq('sighting');
$kafkaTopic = $this->kafkaTopic('sighting');
$isTriggerCallable = $this->isTriggerCallable('sighting-after-save');
if ($pubToZmq || $kafkaTopic || $isTriggerCallable) {
$sighting = $this->getSighting($this->id);
if ($pubToZmq) {
$pubSubTool = $this->getPubSubTool();
$pubSubTool->sighting_save($sighting, 'add');
}
if ($kafkaTopic) {
$kafkaPubTool = $this->getKafkaPubTool();
$kafkaPubTool->publishJson($kafkaTopic, $sighting, 'add');
}
if($isTriggerCallable) {
$workflowErrors = [];
$logging = [
'model' => 'Sighting',
'action' => $created ? 'add' : 'edit',
'id' => $sighting['Sighting']['id'],
];
$triggerData = $sighting;
$this->executeTrigger('sighting-after-save', $triggerData, $workflowErrors, $logging);
}
}
return true;
}
public function beforeDelete($cascade = true)
{
$pubToZmq = $this->pubToZmq('sighting');
$kafkaTopic = $this->kafkaTopic('sighting');
if ($pubToZmq || $kafkaTopic) {
$sighting = $this->getSighting($this->id);
if ($pubToZmq) {
$pubSubTool = $this->getPubSubTool();
$pubSubTool->sighting_save($sighting, 'delete');
}
if ($kafkaTopic) {
$kafkaPubTool = $this->getKafkaPubTool();
$kafkaPubTool->publishJson($kafkaTopic, $sighting, 'delete');
}
}
}
/**
* @param array $sightings
* @param int|null $attributeId
* @param int $eventId
* @param array $user
* @return bool
*/
public function captureSightings(array $sightings, $attributeId, $eventId, array $user)
{
// Since sightings are immutable (it is not possible to change it from web interface), we can check
// if sighting with given uuid already exists and skip them
$existingSighting = $this->existing($sightings);
// Fetch existing organisations in bulk
$existingOrganisations = $this->existingOrganisations($sightings);
if ($attributeId === null) {
// If attribute ID is not set, check real ID and also check if user can access that attribute
$attributes = $this->Attribute->fetchAttributesSimple($user, [
'conditions' => [
'Attribute.uuid' => array_column($sightings, 'attribute_uuid'),
'Attribute.event_id' => $eventId,
],
'fields' => ['Attribute.id', 'Attribute.uuid'],
]);
$attributes = array_column(array_column($attributes, 'Attribute'), 'id', 'uuid');
}
$toSave = [];
foreach ($sightings as $sighting) {
if (!empty($sighting['uuid']) && isset($existingSighting[$sighting['uuid']])) {
continue; // already exists, skip
}
if ($attributeId === null) {
if (isset($attributes[$sighting['attribute_uuid']])) {
$sighting['attribute_id'] = $attributes[$sighting['attribute_uuid']];
} else {
continue; // attribute not exists ar user don't have permission to access it
}
} else {
$sighting['attribute_id'] = $attributeId;
}
$orgId = 0;
if (isset($sighting['Organisation'])) {
if (isset($existingOrganisations[$sighting['Organisation']['uuid']])) {
$orgId = $existingOrganisations[$sighting['Organisation']['uuid']];
} else {
$orgId = $this->Organisation->captureOrg($sighting['Organisation'], $user);
}
} else if (isset($user['org_id'])) {
$orgId = $user['org_id'];
}
unset($sighting['id']);
$sighting['org_id'] = $orgId;
$sighting['event_id'] = $eventId;
$toSave[] = $sighting;
}
return $this->saveMany($toSave);
}
/**
* Fetch sightings with proper ACL checks
*
* @param array $user
* @param array $ids Sightings IDs
* @param bool $includeEvent
* @param bool $includeAttribute
* @param bool $includeUuid Add attribute and event UUID to sighting
* @return array
*/
private function getSightings(array $user, array $ids, $includeEvent = true, $includeAttribute = false, $includeUuid = false)
{
$eventFields = $includeEvent ? ['Event.id', 'Event.uuid', 'Event.orgc_id', 'Event.org_id', 'Event.info'] : ['Event.org_id'];
if ($includeUuid && !$includeEvent) {
$eventFields[] = 'Event.uuid';
}
$attributeFields = $includeAttribute ? ['Attribute.id', 'Attribute.value','Attribute.uuid', 'Attribute.type', 'Attribute.category', 'Attribute.to_ids'] : ['Attribute.id', 'Attribute.value'];
if ($includeUuid && !$includeAttribute) {
$attributeFields[] = 'Attribute.uuid';
}
// Fetch all attributes that are connected to sightings and user can see them
$attributeConditions = $this->Attribute->buildConditions($user);
$subQueryOptions = [
'fields' => ['DISTINCT Sighting.attribute_id'],
'conditions' => ['Sighting.id' => $ids],
];
$attributeConditions[] = $this->subQueryGenerator($this, $subQueryOptions, 'Attribute.id');
$attributes = $this->Attribute->find('all', [
'recursive' => -1,
'conditions' => $attributeConditions,
'contain' => [
'Event' => [
'fields' => $eventFields,
],
'Object',
],
'fields' => $attributeFields,
'order' => [],
]);
if (empty($attributes)) {
return [];
}
$sightings = $this->filterSightingsByAttributeACL($user, $attributes, $ids);
if (empty($sightings)) {
return [];
}
$attributesById = [];
foreach ($attributes as $attribute) {
$attributesById[$attribute['Attribute']['id']] = $attribute;
}
$anonymise = Configure::read('Plugin.Sightings_anonymise');
$results = [];
foreach ($sightings as $sighting) {
$sightingAttribute = $attributesById[$sighting['Sighting']['attribute_id']];
if ($anonymise && $sighting['Sighting']['org_id'] != $user['org_id']) {
unset($sighting['Sighting']['org_id']);
}
// rearrange it to match the event format of fetchevent
$result = $sighting['Sighting'];
$result['value'] = $sightingAttribute['Attribute']['value'];
if ($includeUuid) {
$result['attribute_uuid'] = $sightingAttribute['Attribute']['uuid'];
$result['event_uuid'] = $sightingAttribute['Event']['uuid'];
}
if ($includeAttribute) {
$result['Attribute'] = $sightingAttribute['Attribute'];
}
if ($includeEvent) {
$sightingAttribute['Event']['Orgc']['name'] = $this->getOrganisationById($sightingAttribute['Event']['orgc_id'])['name'];
$result['Event'] = $sightingAttribute['Event'];
}
if (isset($result['org_id']) && $result['org_id'] != 0) {
$result['Organisation'] = $this->getOrganisationById($result['org_id']);
}
$results[] = ['Sighting' => $result];
}
return $results;
}
/**
* Return sighting without ACL checks
*
* @param int $id
* @return array
*/
public function getSighting($id)
{
$sighting = $this->find('first', array(
'recursive' => -1,
'contain' => array(
'Attribute' => array(
'fields' => array('Attribute.value', 'Attribute.id', 'Attribute.uuid', 'Attribute.type', 'Attribute.category', 'Attribute.to_ids')
),
'Event' => array(
'fields' => ['Event.id', 'Event.uuid', 'Event.orgc_id', 'Event.org_id', 'Event.info'],
)
),
'conditions' => array('Sighting.id' => $id)
));
if (empty($sighting)) {
return array();
}
// Put event organisation name from cache
$sighting['Event']['Orgc']['name'] = $this->getOrganisationById($sighting['Event']['orgc_id'])['name'];
// rearrange it to match the event format of fetchevent
$result = array(
'Sighting' => $sighting['Sighting']
);
$result['Sighting']['Event'] = $sighting['Event'];
$result['Sighting']['Attribute'] = $sighting['Attribute'];
return $result;
}
/**
* @param array $tagIds
* @param array $user
* @param null|string $type
* @return array
*/
public function tagsSparkline(array $tagIds, array $user, $type = null)
{
if (empty($tagIds)) {
return [];
}
$conditions = ['Sighting.date_sighting >' => $this->getMaximumRange()];
if ($type !== null) {
$conditions['Sighting.type'] = $type;
}
$sightingsPolicy = $this->sightingsPolicy();
if ($sightingsPolicy === self::SIGHTING_POLICY_EVENT_OWNER) {
$conditions['Sighting.org_id'] = $user['org_id'];
} else if ($sightingsPolicy === self::SIGHTING_POLICY_HOST_ORG) {
$conditions['Sighting.org_id'] = [$user['org_id'], Configure::read('MISP.host_org_id')];
}
// TODO: Currently, we dont support `SIGHTING_POLICY_SIGHTING_REPORTER` for tags
$sparklineData = [];
foreach (['event', 'attribute'] as $context) {
$sightings = $this->fetchGroupedSightingsForTags($tagIds, $conditions, $context);
$objectElement = ucfirst($context) . 'Tag';
foreach ($sightings as $sighting) {
$tagId = $sighting[$objectElement]['tag_id'];
$date = $sighting['Sighting']['date'];
$count = (int)$sighting['Sighting']['sighting_count'];
if (isset($sparklineData[$tagId][$date]['sighting'])) {
$sparklineData[$tagId][$date]['sighting'] += $count;
} else {
$sparklineData[$tagId][$date]['sighting'] = $count;
}
}
}
return $this->generateSparkline($sparklineData, false);
}
/**
* @param array $attributes Attribute must contain Event
* @param array $user
* @param bool $csvWithFalsePositive
* @return array[]
*/
public function attributesStatistics(array $attributes, array $user, $csvWithFalsePositive = false)
{
if (empty($attributes)) {
return ['data' => [], 'csv' => []];
}
$conditions = $this->createConditionsByAttributes($user, $attributes);
$groupedSightings = $this->fetchGroupedSightings($conditions, $user);
return $this->generateStatistics($groupedSightings, $csvWithFalsePositive);
}
/**
* @param array $user
* @param array $attributes Attributes with `Attribute.id`, `Event.id` and `Event.org_id` fields
* @param array $ids
* @return array
*/
private function filterSightingsByAttributeACL(array $user, array $attributes, array $ids)
{
$sightingsPolicy = $this->sightingsPolicy();
$attributesKeyed = [];
$hostOrgId = Configure::read('MISP.host_org_id');
$userOrgId = $user['org_id'];
foreach ($attributes as $attribute) {
$attributesKeyed[$attribute['Attribute']['id']] = $attribute;
}
unset($attributes);
$sightings = $this->find('all', [
'recursive' => -1,
'conditions' => [
'Sighting.id' => $ids
],
'order' => 'Sighting.id'
]);
foreach ($sightings as $k => $sighting) {
$attribute = $attributesKeyed[$sighting['Sighting']['attribute_id']];
$ownEvent = $attribute['Event']['org_id'] == $userOrgId;
if (!$ownEvent) {
if ($sightingsPolicy === self::SIGHTING_POLICY_EVENT_OWNER) {
if ($sighting['Sighting']['org_id'] != $userOrgId) {
unset($sightings[$k]);
}
} else if ($sightingsPolicy === self::SIGHTING_POLICY_SIGHTING_REPORTER) {
if (!$this->isreporter($attribute['Event']['id'], $userOrgId)) {
unset($sightings[$k]);
}
} else if ($sightingsPolicy === self::SIGHTING_POLICY_HOST_ORG) {
if (!in_array($sighting['Sighting']['org_id'], [$userOrgId, $hostOrgId])) {
unset($sightings[$k]);
}
}
}
}
return array_values($sightings);
}
/**
* @param array $user
* @param array $attributes Attributes with `Attribute.id`, `Event.id` and `Event.org_id` fields
* @return array
*/
private function createConditionsByAttributes(array $user, array $attributes)
{
$sightingsPolicy = $this->sightingsPolicy();
if ($sightingsPolicy === self::SIGHTING_POLICY_EVERYONE || $user['Role']['perm_site_admin']) {
return ['Sighting.attribute_id' => array_column(array_column($attributes, 'Attribute'), 'id')];
}
$hostOrgId = Configure::read('MISP.host_org_id');
$userOrgId = $user['org_id'];
$conditions = [];
foreach ($attributes as $attribute) {
$attributeConditions = ['Sighting.attribute_id' => $attribute['Attribute']['id']];
$ownEvent = $attribute['Event']['org_id'] == $userOrgId;
if (!$ownEvent) {
if ($sightingsPolicy === self::SIGHTING_POLICY_EVENT_OWNER) {
$attributeConditions['Sighting.org_id'] = $userOrgId;
} else if ($sightingsPolicy === self::SIGHTING_POLICY_SIGHTING_REPORTER) {
if (!$this->isReporter($attribute['Event']['id'], $userOrgId)) {
continue; // skip attribute
}
} else if ($sightingsPolicy === self::SIGHTING_POLICY_HOST_ORG) {
$attributeConditions['Sighting.org_id'] = [$userOrgId, $hostOrgId];
}
}
$conditions['OR'][] = $attributeConditions;
}
return $conditions;
}
/**
* @param array $events
* @param array $user
* @param bool $csvWithFalsePositive
* @return array
*/
public function eventsStatistic(array $events, array $user, $csvWithFalsePositive = false)
{
if (empty($events)) {
return ['data' => [], 'csv' => []];
}
$sightingsPolicy = $this->sightingsPolicy();
$conditions = [];
foreach ($events as $event) {
$eventCondition = ['Sighting.event_id' => $event['Event']['id']];
$ownEvent = $user['Role']['perm_site_admin'] || $event['Event']['org_id'] == $user['org_id'];
if (!$ownEvent) {
if ($sightingsPolicy === self::SIGHTING_POLICY_EVENT_OWNER) {
$eventCondition['Sighting.org_id'] = $user['org_id'];
} else if ($sightingsPolicy === self::SIGHTING_POLICY_SIGHTING_REPORTER) {
if (!$this->isReporter($event['Event']['id'], $user['org_id'])) {
continue;
}
} else if ($sightingsPolicy === self::SIGHTING_POLICY_HOST_ORG) {
$eventCondition['Sighting.org_id'] = [$user['org_id'], Configure::read('MISP.host_org_id')];
}
}
$conditions['OR'][] = $eventCondition;
}
$groupedSightings = $this->fetchGroupedSightings($conditions, $user);
return $this->generateStatistics($groupedSightings, $csvWithFalsePositive);
}
/**
* @param array $conditions
* @param array $user
* @return array
*/
private function fetchGroupedSightings(array $conditions, array $user)
{
if (empty($conditions)) {
return [];
}
// Returns date in `Y-m-d` format
$this->virtualFields['date'] = $this->dateVirtualColumn();
$this->virtualFields['sighting_count'] = 'COUNT(id)';
$this->virtualFields['last_timestamp'] = 'MAX(date_sighting)';
$groupedSightings = $this->find('all', array(
'conditions' => $conditions,
'fields' => ['org_id', 'attribute_id', 'type', 'date', 'last_timestamp', 'sighting_count'],
'recursive' => -1,
'group' => ['org_id', 'attribute_id', 'type', 'date'],
'order' => ['date'], // from oldest
));
unset(
$this->virtualFields['date'],
$this->virtualFields['sighting_count'],
$this->virtualFields['last_timestamp']
);
return $this->attachOrgToSightings($groupedSightings, $user, false);
}
/**
* @param array $tagIds
* @param array $conditions
* @param string $context
* @return array
*/
private function fetchGroupedSightingsForTags(array $tagIds, array $conditions, $context)
{
$conditions[ucfirst($context) . 'Tag.tag_id'] = $tagIds;
// Temporary bind EventTag or AttributeTag model
$this->bindModel([
'hasOne' => [
ucfirst($context) . 'Tag' => [
'foreignKey' => false,
'conditions' => ucfirst($context) . 'Tag.' . $context . '_id = Sighting.' . $context . '_id',
]
]
]);
// Returns date in `Y-m-d` format
$this->virtualFields['date'] = $this->dateVirtualColumn();
$this->virtualFields['sighting_count'] = 'COUNT(Sighting.id)';
$sightings = $this->find('all', [
'recursive' => -1,
'contain' => [ucfirst($context) . 'Tag'],
'conditions' => $conditions,
'fields' => [ucfirst($context) . 'Tag.tag_id', 'date', 'sighting_count'],
'group' => [ucfirst($context) . 'Tag.tag_id', 'date'],
'order' => ['date'], // from oldest
]);
unset($this->virtualFields['date'], $this->virtualFields['sighting_count']);
return $sightings;
}
/**
* @param array $groupedSightings
* @param bool $csvWithFalsePositive
* @return array[]
*/
private function generateStatistics(array $groupedSightings, $csvWithFalsePositive = false)
{
$sightingsData = [];
$sparklineData = [];
$range = $this->getMaximumRange();
foreach ($groupedSightings as $sighting) {
$type = self::TYPE[$sighting['type']];
$orgName = isset($sighting['Organisation']['name']) ? $sighting['Organisation']['name'] : __('Others');
$count = (int)$sighting['sighting_count'];
$inRange = strtotime($sighting['date']) >= $range;
foreach ([$sighting['attribute_id'], 'all'] as $needle) {
if (!isset($sightingsData[$needle][$type])) {
$sightingsData[$needle][$type] = ['count' => 0, 'orgs' => []];
}
$ref = &$sightingsData[$needle][$type];
$ref['count'] += $count;
if (!isset($ref['orgs'][$orgName])) {
$ref['orgs'][$orgName] = ['count' => $count, 'date' => $sighting['last_timestamp']];
} else {
$ref['orgs'][$orgName]['count'] += $count;
$ref['orgs'][$orgName]['date'] = $sighting['last_timestamp'];
}
if ($inRange) {
if (isset($sparklineData[$needle][$sighting['date']][$type])) {
$sparklineData[$needle][$sighting['date']][$type] += $count;
} else {
$sparklineData[$needle][$sighting['date']][$type] = $count;
}
}
}
}
return ['data' => $sightingsData, 'csv' => $this->generateSparkline($sparklineData, $csvWithFalsePositive)];
}
/**
* @param array $sparklineData
* @param bool $csvWithFalsePositive
* @return array
*/
private function generateSparkline(array $sparklineData, $csvWithFalsePositive)
{
$todayString = date('Y-m-d');
$today = strtotime($todayString);
// If nothing found, generate default "empty" CSV for 'all'
if (!isset($sparklineData['all'])) {
$sparklineData['all'][$todayString] = null;
}
$csv = [];
foreach ($sparklineData as $object => $data) {
$startDate = key($data); // oldest date for sparkline
$startDate = strtotime($startDate) - (self::ONE_DAY * 3);
$csvForObject = $csvWithFalsePositive ? 'Date,Sighting,False-positive\n' : 'Date,Close\n';
for ($date = $startDate; $date <= $today; $date += self::ONE_DAY) {
$dateAsString = date('Y-m-d', $date);
$csvForObject .= $dateAsString . ',' . (isset($data[$dateAsString]['sighting']) ? $data[$dateAsString]['sighting'] : '0');
if ($csvWithFalsePositive) {
$csvForObject .= ',' . (isset($data[$dateAsString]['false-positive']) ? $data[$dateAsString]['false-positive'] : '0');
}
$csvForObject .= '\n';
}
$csv[$object] = $csvForObject;
}
return $csv;
}
/**
* @param array $sightings
* @param array $user
* @param false $forSync
* @return array
*/
private function attachOrgToSightings(array $sightings, array $user, $forSync = false)
{
$showOrg = Configure::read('MISP.showorg');
$anonymise = Configure::read('Plugin.Sightings_anonymise');
$anonymiseAs = Configure::read('Plugin.Sightings_anonymise_as');
$anonOrg = null;
if ($forSync && !empty($anonymiseAs)) {
$anonOrg = $this->getOrganisationById($anonymiseAs);
}
foreach ($sightings as $k => $sighting) {
$sighting = $sighting['Sighting'];
if ($showOrg && $sighting['org_id']) {
$sighting['Organisation'] = $this->getOrganisationById($sighting['org_id']);
}
if ($sighting['org_id'] != $user['org_id'] && $anonymise) {
if (empty($anonOrg)) {
unset($sighting['org_id']);
unset($sighting['Organisation']);
} else {
$sighting['org_id'] = $anonOrg['id'];
$sighting['Organisation'] = $anonOrg;
}
}
$sightings[$k] = $sighting;
}
$this->orgCache = []; // clear org cache
return $sightings;
}
/**
* @param array $event
* @param array $user
* @param array $sightingsUuidsToPush
* @return Generator<array>
*/
public function fetchUuidsForEventToPush(array $event, array $user, array $sightingsUuidsToPush = [])
{
$conditions = $this->createConditions($user, $event);
if ($conditions === false) {
return null;
}
$conditions['Sighting.event_id'] = $event['Event']['id'];
if (!empty($sightingsUuidsToPush)) {
$conditions['Sighting.uuid'] = $sightingsUuidsToPush;
}
while (true) {
$uuids = $this->find('column', [
'conditions' => $conditions,
'fields' => ['Sighting.uuid'],
'limit' => 250000,
'order' => ['Sighting.uuid'],
]);
$count = count($uuids);
if ($count === 0) {
return null;
}
yield $uuids;
if ($count !== 250000) {
return;
}
$conditions['Sighting.uuid >'] = $uuids[$count - 1];
}
}
/**
* @param array $event Just 'Event' object is enough
* @param array $user
* @param array|int|null $attribute Attribute model or attribute ID
* @param array|bool $extraConditions
* @param bool $forSync
* @return array|int
*/
public function attachToEvent(array $event, array $user, $attribute = null, $extraConditions = false, $forSync = false)
{
$conditions = $this->createConditions($user, $event);
if ($conditions === false) {
return [];
}
$conditions['Sighting.event_id'] = $event['Event']['id'];
if (isset($attribute['Attribute']['id'])) {
$conditions['Sighting.attribute_id'] = $attribute['Attribute']['id'];
} elseif (is_numeric($attribute)) {
$conditions['Sighting.attribute_id'] = $attribute;
$attribute = $this->Attribute->find('first', [
'recursive' => -1,
'conditions' => ['Attribute.id' => $attribute],
'fields' => ['Attribute.uuid']
]);
}
if ($extraConditions !== false) {
$conditions['AND'] = $extraConditions;
}
$sightings = $this->find('all', array(
'conditions' => $conditions,
'recursive' => -1,
));
if (empty($sightings)) {
return [];
}
if ($attribute === null) {
// Do not add attribute uuid in contain query, joining is slow and takes more memory
$attributeUuids = $this->Attribute->find('all', [
'conditions' => ['Attribute.event_id' => $event['Event']['id']],
'fields' => ['Attribute.id', 'Attribute.uuid'],
'recursive' => -1,
]);
// `array_column` is much faster than find('list')
$attributeUuids = array_column(array_column($attributeUuids, 'Attribute'), 'uuid', 'id');
foreach ($sightings as $k => $sighting) {
$sighting['Sighting']['attribute_uuid'] = $attributeUuids[$sighting['Sighting']['attribute_id']];
$sightings[$k] = $sighting;
}
unset($attributeUuids);
} else {
foreach ($sightings as $k => $sighting) {
$sighting['Sighting']['attribute_uuid'] = $attribute['Attribute']['uuid'];
$sightings[$k] = $sighting;
}
}
return $this->attachOrgToSightings($sightings, $user, $forSync);
}
public function saveSightings($id, $values, $timestamp, $user, $type = false, $source = false, $sighting_uuid = false, $publish = false, $saveOnBehalfOf = false, $filters=[])
{
if (!in_array($type, array(0, 1, 2))) {
return 'Invalid type, please change it before you POST 1000000 sightings.';
}
if ($sighting_uuid) {
// Since sightings are immutable (it is not possible to change it from web interface), we can check
// if sighting with given uuid already exists and quit early
$existing_sighting = $this->find('count', array(
'recursive' => -1,
'conditions' => array('uuid' => $sighting_uuid),
'callbacks' => false,
));
if ($existing_sighting) {
return 0;
}
}
$conditions = array();
if ($id && $id !== 'stix') {
$id = $this->explodeIdList($id);
if (!is_array($id) && strlen($id) == 36) {
$conditions = array('Attribute.uuid' => $id);
} else {
$conditions = array('Attribute.id' => $id);
}
} else {
if (!$values) {
return 'No valid attributes found.';
}
if (!is_array($values)) {
$values = array($values);
}
if (empty($filters)) {
foreach ($values as $value) {
foreach (array('value1', 'value2') as $field) {
$conditions['OR'][] = array(
'Attribute.' . $field => $value
);
}
}
}
}
$attributes = [];
if (empty($filters)) {
$attributes = $this->Attribute->fetchAttributesSimple($user, [
'conditions' => $conditions,
'fields' => ['Attribute.id', 'Attribute.event_id'],
]);
} else {
$filters['value'] = $values;
$params = $this->Attribute->restSearch($user, 'json', $filters, true);
$attributes = $this->Attribute->fetchAttributes($user, $params);
}
if (empty($attributes)) {
return 'No valid attributes found that match the criteria.';
}
$sightingsAdded = 0;
foreach ($attributes as $attribute) {
if ($type === '2') {
// remove existing expiration by the same org if it exists
$this->deleteAll(array(
'Sighting.org_id' => $user['org_id'],
'Sighting.type' => $type,
'Sighting.attribute_id' => $attribute['Attribute']['id'],
));
}
$this->create();
$sighting = array(
'attribute_id' => $attribute['Attribute']['id'],
'event_id' => $attribute['Attribute']['event_id'],
'org_id' => ($saveOnBehalfOf === false) ? $user['org_id'] : $saveOnBehalfOf,
'date_sighting' => $timestamp,
'type' => $type,
'source' => $source,
);
// zeroq: allow setting a specific uuid
if ($sighting_uuid) {
$sighting['uuid'] = $sighting_uuid;
}
$result = $this->save($sighting);
if ($result === false) {
return json_encode($this->validationErrors);
}
++$sightingsAdded;
if ($publish) {
$this->Event->publishSightingsRouter($sighting['event_id'], $user);
}
}
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();
$scriptFile = APP . "files" . DS . "scripts" . DS . "stixsighting2misp.py";
// Execute the python script and point it to the temporary filename
$result = ProcessTool::execute([ProcessTool::pythonBin(), $scriptFile, $randomFileName]);
// The result of the script will be a returned JSON object with 2 variables: success (boolean) and message
// If success = 1 then the temporary output file was successfully written, otherwise an error message is passed along
$result = json_decode($result, true);
if ($result['success'] == 1) {
$file = new File(APP . "files" . DS . "scripts" . DS . "tmp" . DS . $randomFileName . ".out");
$result['data'] = $file->read();
$file->close();
$file->delete();
}
$tempFile->delete();
return $result;
}
/**
* @return bool
* @deprecated
*/
public function addUuids()
{
$sightings = $this->find('all', array(
'recursive' => -1,
'conditions' => array('uuid' => '')
));
$this->saveMany($sightings);
return true;
}
public function explodeIdList($id)
{
if (strpos($id, '|')) {
$id = explode('|', $id);
foreach ($id as $k => $v) {
if (!is_numeric($v)) {
unset($id[$k]);
}
}
$id = array_values($id);
}
return $id;
}
/**
* @param array $user
* @param $ids
* @param string $context
* @param int|false $orgId
* @param int|false $sightingsType
* @param bool $orderDesc
* @return array|int|null
* @throws Exception
*/
public function listSightings(array $user, $ids, $context, $orgId = false, $sightingsType = false, $orderDesc = true)
{
$ids = is_array($ids) ? $ids : $this->explodeIdList($ids);
$objectIds = [];
$eventOwnerOrgIdList = [];
if ($context === 'attribute') {
$objects = $this->Event->Attribute->fetchAttributes($user, ['conditions' => ['Attribute.id' => $ids, 'Attribute.deleted' => 0], 'flatten' => 1]);
foreach ($objects as $object) {
$objectIds[] = $object['Attribute']['id'];
$eventOwnerOrgIdList[$object['Event']['id']] = $object['Event']['orgc_id'];
}
} elseif ($context === 'event') {
// let's set the context to event here, since we reuse the variable later on for some additional lookups.
// Passing $context = 'org' could have interesting results otherwise...
$objects = $this->Event->fetchSimpleEvents($user, ['conditions' => ['Event.id' => $ids]]);
foreach ($objects as $object) {
$objectIds[] = $object['Event']['id'];
$eventOwnerOrgIdList[$object['Event']['id']] = $object['Event']['orgc_id'];
}
} else {
throw new InvalidArgumentException("Invalid context '$context'.");
}
unset($objects);
if (empty($objectIds)) {
throw new MethodNotAllowedException('Invalid object.');
}
$conditions = array(
'Sighting.' . $context . '_id' => $objectIds
);
if ($orgId) {
$conditions[] = array('Sighting.org_id' => $orgId);
}
if ($sightingsType !== false) {
$conditions[] = array('Sighting.type' => $sightingsType);
}
$sightings = $this->find('all', array(
'conditions' => $conditions,
'recursive' => -1,
'contain' => array('Organisation.name'),
'order' => array(sprintf('Sighting.date_sighting %s', $orderDesc ? 'DESC' : ''))
));
if (empty($sightings)) {
return [];
}
if ($user['Role']['perm_site_admin']) {
return $sightings; // site admin can see all sightings, do not limit him
}
$sightingsPolicy = $this->sightingsPolicy();
if ($sightingsPolicy === self::SIGHTING_POLICY_EVENT_OWNER || $sightingsPolicy === self::SIGHTING_POLICY_HOST_ORG) {
$userOrgId = $user['org_id'];
$allowedOrgs = [$userOrgId];
if ($sightingsPolicy === self::SIGHTING_POLICY_HOST_ORG) {
$allowedOrgs[] = Configure::read('MISP.host_org_id');
}
foreach ($sightings as $k => $sighting) {
if ($eventOwnerOrgIdList[$sighting['Sighting']['event_id']] !== $userOrgId && !in_array($sighting['Sighting']['org_id'], $allowedOrgs)) {
unset($sightings[$k]);
}
}
$sightings = array_values($sightings);
} else if ($sightingsPolicy === self::SIGHTING_POLICY_SIGHTING_REPORTER) {
$eventsWithOwnSightings = array();
foreach ($sightings as $k => $sighting) {
$eventId = $sighting['Sighting']['event_id'];
if (!isset($eventsWithOwnSightings[$eventId])) {
$isReporter = $this->isReporter($eventId, $user['org_id']);
if ($isReporter) {
$eventsWithOwnSightings[$eventId] = true;
} else {
$ownEvent = $eventOwnerOrgIdList[$eventId] == $user['org_id'];
$eventsWithOwnSightings[$eventId] = $ownEvent;
}
}
if (!$eventsWithOwnSightings[$eventId]) {
unset($sightings[$k]);
}
}
$sightings = array_values($sightings);