/
SplunkPy.py
2728 lines (2240 loc) · 117 KB
/
SplunkPy.py
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
import hashlib
import io
import json
import re
from datetime import datetime, timedelta
import dateparser
import demistomock as demisto
import pytz
import requests
import splunklib.client as client
import splunklib.results as results
from splunklib.data import Record
import urllib3
from CommonServerPython import * # noqa: F401
from splunklib.binding import AuthenticationError, HTTPError, namespace
urllib3.disable_warnings()
# Define utf8 as default encoding
params = demisto.params()
SPLUNK_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
VERIFY_CERTIFICATE = not bool(params.get('unsecure'))
FETCH_LIMIT = int(params.get('fetch_limit')) if params.get('fetch_limit') else 50
FETCH_LIMIT = max(min(200, FETCH_LIMIT), 1)
MIRROR_LIMIT = 1000
PROBLEMATIC_CHARACTERS = ['.', '(', ')', '[', ']']
REPLACE_WITH = '_'
REPLACE_FLAG = params.get('replaceKeys', False)
FETCH_TIME = demisto.params().get('fetch_time')
PROXIES = handle_proxy()
TIME_UNIT_TO_MINUTES = {'minute': 1, 'hour': 60, 'day': 24 * 60, 'week': 7 * 24 * 60, 'month': 30 * 24 * 60,
'year': 365 * 24 * 60}
DEFAULT_DISPOSITIONS = {
'True Positive - Suspicious Activity': 'disposition:1',
'Benign Positive - Suspicious But Expected': 'disposition:2',
'False Positive - Incorrect Analytic Logic': 'disposition:3',
'False Positive - Inaccurate Data': 'disposition:4',
'Other': 'disposition:5',
'Undetermined': 'disposition:6'
}
# =========== Mirroring Mechanism Globals ===========
MIRROR_DIRECTION = {
'None': None,
'Incoming': 'In',
'Outgoing': 'Out',
'Incoming And Outgoing': 'Both'
}
OUTGOING_MIRRORED_FIELDS = ['comment', 'status', 'owner', 'urgency', 'reviewer', 'disposition']
# =========== Enrichment Mechanism Globals ===========
ENABLED_ENRICHMENTS = params.get('enabled_enrichments', [])
DRILLDOWN_ENRICHMENT = 'Drilldown'
ASSET_ENRICHMENT = 'Asset'
IDENTITY_ENRICHMENT = 'Identity'
SUBMITTED_NOTABLES = 'submitted_notables'
EVENT_ID = 'event_id'
JOB_CREATION_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
NOT_YET_SUBMITTED_NOTABLES = 'not_yet_submitted_notables'
INFO_MIN_TIME = "info_min_time"
INFO_MAX_TIME = "info_max_time"
INCIDENTS = 'incidents'
DUMMY = 'dummy'
NOTABLE = 'notable'
ENRICHMENTS = 'enrichments'
MAX_HANDLE_NOTABLES = 20
MAX_SUBMIT_NOTABLES = 30
CACHE = 'cache'
STATUS = 'status'
DATA = 'data'
TYPE = 'type'
ID = 'id'
CREATION_TIME = 'creation_time'
INCIDENT_CREATED = 'incident_created'
DRILLDOWN_REGEX = r'([^\s\$]+)=(\$[^\$]+\$)|(\$[^\$]+\$)'
ENRICHMENT_TYPE_TO_ENRICHMENT_STATUS = {
DRILLDOWN_ENRICHMENT: 'successful_drilldown_enrichment',
ASSET_ENRICHMENT: 'successful_asset_enrichment',
IDENTITY_ENRICHMENT: 'successful_identity_enrichment'
}
# =========== Not Missing Events Mechanism Globals ===========
CUSTOM_ID = 'custom_id'
OCCURRED = 'occurred'
INDEX_TIME = 'index_time'
TIME_IS_MISSING = 'time_is_missing'
# =========== Enrich User Mechanism ============
class UserMappingObject:
def __init__(
self, service: client.Service,
should_map_user: bool,
table_name: str = 'splunk_xsoar_users',
xsoar_user_column_name: str = 'xsoar_user',
splunk_user_column_name: str = 'splunk_user'
):
self.service = service
self.should_map = should_map_user
self.table_name = table_name
self.xsoar_user_column_name = xsoar_user_column_name
self.splunk_user_column_name = splunk_user_column_name
def _get_record(self, col: str, value_to_search: str):
""" Gets the records with the value found in the relevant column. """
kvstore: client.KVStoreCollection = self.service.kvstore[self.table_name]
return kvstore.data.query(query=json.dumps({col: value_to_search}))
def get_xsoar_user_by_splunk(self, splunk_user):
record = list(self._get_record(self.splunk_user_column_name, splunk_user))
if not record:
demisto.error(
"Could not find xsoar user matching splunk's {splunk_user}. "
"Consider adding it to the {table_name} lookup.".format(
splunk_user=splunk_user, table_name=self.table_name))
return ''
# assuming username is unique, so only one record is returned.
xsoar_user = record[0].get(self.xsoar_user_column_name)
if not xsoar_user:
demisto.error(
"Xsoar user matching splunk's {splunk_user} is empty. Fix the record in {table_name} lookup.".format(
splunk_user=splunk_user, table_name=self.table_name))
return ''
return xsoar_user
def get_splunk_user_by_xsoar(self, xsoar_user, map_missing=True):
record = list(self._get_record(self.xsoar_user_column_name, xsoar_user))
if not record:
demisto.error(
"Could not find splunk user matching xsoar's {xsoar_user}. "
"Consider adding it to the {table_name} lookup.".format(
xsoar_user=xsoar_user, table_name=self.table_name))
return 'unassigned' if map_missing else None
# assuming username is unique, so only one record is returned.
splunk_user = record[0].get(self.splunk_user_column_name)
if not splunk_user:
demisto.error(
"Splunk user matching Xsoar's {xsoar_user} is empty. Fix the record in {table_name} lookup.".format(
xsoar_user=xsoar_user, table_name=self.table_name))
return 'unassigned' if map_missing else None
return splunk_user
def get_splunk_user_by_xsoar_command(self, args):
xsoar_users = argToList(args.get('xsoar_username'))
map_missing = argToBoolean(args.get('map_missing', True))
outputs = []
for user in xsoar_users:
splunk_user = self.get_splunk_user_by_xsoar(user, map_missing=map_missing) if user else None
outputs.append(
{'XsoarUser': user,
'SplunkUser': splunk_user if splunk_user else 'Could not map splunk user, Check logs for more info.'})
return CommandResults(
outputs=outputs,
outputs_prefix='Splunk.UserMapping',
readable_output=tableToMarkdown('Xsoar-Splunk Username Mapping', outputs,
headers=['XsoarUser', 'SplunkUser'])
)
# =========== Regular Fetch Mechanism ===========
def splunk_time_to_datetime(incident_ocurred_time):
incident_time_without_timezone = incident_ocurred_time.split('.')[0]
incident_time_datetime = datetime.strptime(incident_time_without_timezone, SPLUNK_TIME_FORMAT)
return incident_time_datetime
def get_latest_incident_time(incidents):
def get_incident_time_datetime(incident):
incident_time = incident["occurred"]
incident_time_datetime = splunk_time_to_datetime(incident_time)
return incident_time_datetime
latest_incident = max(incidents, key=get_incident_time_datetime)
return latest_incident["occurred"]
def get_next_start_time(latests_incident_fetched_time, latest_time, were_new_incidents_found=True):
if were_new_incidents_found:
latest_incident_datetime = splunk_time_to_datetime(latests_incident_fetched_time)
next_run_without_miliseconds_and_tz = latest_incident_datetime.strftime(SPLUNK_TIME_FORMAT)
next_run = next_run_without_miliseconds_and_tz
return next_run
else:
return latest_time
def create_incident_custom_id(incident):
incident_raw_data = json.loads(incident["rawJSON"])
fields_to_add = ['_cd', 'index', '_time', '_indextime', '_raw']
fields_supplied_by_user = demisto.params().get('unique_id_fields', '')
fields_supplied_by_user = '' if not fields_supplied_by_user else fields_supplied_by_user
fields_to_add.extend(fields_supplied_by_user.split(','))
incident_custom_id = '___'
for field_name in fields_to_add:
if field_name in incident_raw_data:
incident_custom_id += '{}___{}'.format(field_name, incident_raw_data[field_name])
elif field_name in incident:
incident_custom_id += '{}___{}'.format(field_name, incident[field_name])
extensive_log('[SplunkPy] ID after all fields were added: {}'.format(incident_custom_id))
unique_id = hashlib.md5(incident_custom_id.encode('utf-8')).hexdigest() # nosec # guardrails-disable-line
extensive_log('[SplunkPy] Found incident ID is: {}'.format(unique_id))
return unique_id
def extensive_log(message):
if demisto.params().get('extensive_logs', False):
demisto.debug(message)
def remove_old_incident_ids(last_run_fetched_ids, current_epoch_time, occurred_look_behind):
"""Remove all the IDs of all the incidents that were found more than twice the look behind time frame,
to stop our IDs dict from becoming too large.
Args:
last_run_fetched_ids (list): All the event IDs that weren't out of date in the last run + all the new event IDs
from newly fetched events in this run.
current_epoch_time (int): The current time in epoch.
occurred_look_behind (int): The max look behind time (parameter, as defined by the user).
Returns:
new_last_run_fetched_ids (list): The updated list of IDs, without old IDs.
"""
new_last_run_fetched_ids = {}
for inc_id, addition_time in list(last_run_fetched_ids.items()):
max_look_behind_in_seconds = occurred_look_behind * 60
deletion_threshold_in_seconds = max_look_behind_in_seconds * 2
if current_epoch_time - addition_time < deletion_threshold_in_seconds:
new_last_run_fetched_ids[inc_id] = addition_time
return new_last_run_fetched_ids
def enforce_look_behind_time(last_run_time, now, look_behind_time):
""" Verifies that the start time of the fetch is at X minutes before
the end time, X being the number of minutes specified in the look_behind parameter.
The reason this is needed is to ensure that events that have a significant difference
between their index time and occurrence time in Splunk are still fetched and are not missed.
Args:
last_run_time (str): The current start time of the fetch.
now (str): The current end time of the fetch.
look_behind_time (int): The minimal difference (in minutes) that should be enforced between
the start time and end time.
Returns:
last_run (str): The new start time for the fetch.
"""
last_run_datetime = datetime.strptime(last_run_time, SPLUNK_TIME_FORMAT)
now_datetime = datetime.strptime(now, SPLUNK_TIME_FORMAT)
if now_datetime - last_run_datetime < timedelta(minutes=look_behind_time):
time_before_given_look_behind_datetime = now_datetime - timedelta(minutes=look_behind_time)
time_before_given_look_behind = datetime.strftime(time_before_given_look_behind_datetime, SPLUNK_TIME_FORMAT)
return time_before_given_look_behind
return last_run_time
def get_fetch_start_times(dem_params, service, last_run_earliest_time, occurence_time_look_behind):
current_time_for_fetch = datetime.utcnow()
if demisto.get(dem_params, 'timezone'):
timezone = dem_params['timezone']
current_time_for_fetch = current_time_for_fetch + timedelta(minutes=int(timezone))
now = current_time_for_fetch.strftime(SPLUNK_TIME_FORMAT)
if demisto.get(dem_params, 'useSplunkTime'):
now = get_current_splunk_time(service)
current_time_in_splunk = datetime.strptime(now, SPLUNK_TIME_FORMAT)
current_time_for_fetch = current_time_in_splunk
if not last_run_earliest_time:
fetch_time_in_minutes = parse_time_to_minutes()
start_time_for_fetch = current_time_for_fetch - timedelta(minutes=fetch_time_in_minutes)
last_run_earliest_time = start_time_for_fetch.strftime(SPLUNK_TIME_FORMAT)
extensive_log('[SplunkPy] SplunkPy last run is None. Last run earliest time is: {}'.format(last_run_earliest_time))
occured_start_time = enforce_look_behind_time(last_run_earliest_time, now, occurence_time_look_behind)
return occured_start_time, now
def build_fetch_kwargs(dem_params, occured_start_time, latest_time, search_offset):
occurred_start_time_fieldname = dem_params.get("earliest_occurrence_time_fieldname", "earliest_time")
occurred_end_time_fieldname = dem_params.get("latest_occurrence_time_fieldname", "latest_time")
extensive_log('[SplunkPy] occurred_start_time_fieldname: {}'.format(occurred_start_time_fieldname))
extensive_log('[SplunkPy] occured_start_time: {}'.format(occured_start_time))
kwargs_oneshot = {
occurred_start_time_fieldname: occured_start_time,
occurred_end_time_fieldname: latest_time,
"count": FETCH_LIMIT,
'offset': search_offset
}
return kwargs_oneshot
def build_fetch_query(dem_params):
fetch_query = dem_params['fetchQuery']
if demisto.get(dem_params, 'extractFields'):
extractFields = dem_params['extractFields']
extra_raw_arr = extractFields.split(',')
for field in extra_raw_arr:
field_trimmed = field.strip()
fetch_query = fetch_query + ' | eval ' + field_trimmed + '=' + field_trimmed
return fetch_query
def fetch_notables(service: client.Service, mapper: UserMappingObject, cache_object: "Cache" = None, enrich_notables=False):
last_run_data = demisto.getLastRun()
if not last_run_data:
extensive_log('[SplunkPy] SplunkPy first run')
last_run_earliest_time = last_run_data and last_run_data.get('time')
last_run_latest_time = last_run_data and last_run_data.get('latest_time')
extensive_log(f'[SplunkPy] SplunkPy last run is:\n {last_run_data}')
search_offset = last_run_data.get('offset', 0)
dem_params = demisto.params()
occurred_look_behind = int(dem_params.get('occurrence_look_behind', 15) or 15)
extensive_log(f'[SplunkPy] occurrence look behind is: {occurred_look_behind}')
occured_start_time, now = get_fetch_start_times(dem_params, service, last_run_earliest_time, occurred_look_behind)
# if last_run_latest_time is not None it's mean we are in a batch fetch iteration with offset
latest_time = last_run_latest_time or now
kwargs_oneshot = build_fetch_kwargs(dem_params, occured_start_time, latest_time, search_offset)
fetch_query = build_fetch_query(dem_params)
demisto.debug(f'[SplunkPy] fetch query = {fetch_query}')
demisto.debug(f'[SplunkPy] oneshot query args = {kwargs_oneshot}')
oneshotsearch_results = service.jobs.oneshot(fetch_query, **kwargs_oneshot) # type: ignore
reader = results.ResultsReader(oneshotsearch_results)
last_run_fetched_ids = last_run_data.get('found_incidents_ids', {})
incidents = []
notables = []
incident_ids_to_add = []
num_of_dropped = 0
for item in reader:
extensive_log(f'[SplunkPy] Incident data before parsing to notable: {item}')
notable_incident = Notable(data=item)
inc = notable_incident.to_incident(mapper)
extensive_log(f'[SplunkPy] Incident data after parsing to notable: {inc}')
incident_id = create_incident_custom_id(inc)
if incident_id not in last_run_fetched_ids:
incident_ids_to_add.append(incident_id)
incidents.append(inc)
notables.append(notable_incident)
extensive_log(f'[SplunkPy] - Fetched incident {item.get("event_id", incident_id)} to be created.')
else:
num_of_dropped += 1
extensive_log(f'[SplunkPy] - Dropped incident {item.get("event_id", incident_id)} due to duplication.')
current_epoch_time = int(time.time())
extensive_log(f'[SplunkPy] Size of last_run_fetched_ids before adding new IDs: {len(last_run_fetched_ids)}')
for incident_id in incident_ids_to_add:
last_run_fetched_ids[incident_id] = current_epoch_time
extensive_log(f'[SplunkPy] Size of last_run_fetched_ids after adding new IDs: {len(last_run_fetched_ids)}')
last_run_fetched_ids = remove_old_incident_ids(last_run_fetched_ids, current_epoch_time, occurred_look_behind)
extensive_log('[SplunkPy] Size of last_run_fetched_ids after '
f'removing old IDs: {len(last_run_fetched_ids)}')
extensive_log(f'[SplunkPy] SplunkPy - incidents fetched on last run = {last_run_fetched_ids}')
demisto.debug(f'SplunkPy - total number of new incidents found is: {len(incidents)}')
demisto.debug(f'SplunkPy - total number of dropped incidents is: {num_of_dropped}')
if not enrich_notables or not cache_object:
demisto.incidents(incidents)
else:
cache_object.not_yet_submitted_notables += notables
if DUMMY not in last_run_data:
# we add dummy data to the last run to differentiate between the fetch-incidents triggered to the
# fetch-incidents running as part of "Pull from instance" in Classification & Mapping, as we don't
# want to add data to the integration context (which will ruin the logic of the cache object)
last_run_data.update({DUMMY: DUMMY})
# we didn't get any new incident or get less then limit
# so the next run earliest time will be the latest_time from this iteration
# should also set when num_of_dropped == FETCH_LIMIT
if not incidents or (len(incidents) + num_of_dropped) < FETCH_LIMIT:
next_run_earliest_time = latest_time
new_last_run = {
'time': next_run_earliest_time,
'latest_time': None,
'offset': 0,
'found_incidents_ids': last_run_fetched_ids
}
# we get limit notables from splunk
# we should fetch the entire queue with offset - so set the offset, time and latest_time for the next run
else:
new_last_run = {
'time': occured_start_time,
'latest_time': latest_time,
'offset': search_offset + FETCH_LIMIT,
'found_incidents_ids': last_run_fetched_ids
}
demisto.debug(f'SplunkPy - {new_last_run["time"]=}, {new_last_run["latest_time"]=}, {new_last_run["offset"]=}')
last_run_data.update(new_last_run)
demisto.setLastRun(last_run_data)
def fetch_incidents(service: client.Service, mapper: UserMappingObject):
if ENABLED_ENRICHMENTS:
integration_context = get_integration_context()
if not demisto.getLastRun() and integration_context:
# In "Pull from instance" in Classification & Mapping the last run object is empty, integration context
# will not be empty because of the enrichment mechanism. In regular enriched fetch, we use dummy data
# in the last run object to avoid entering this case
fetch_incidents_for_mapping(integration_context)
else:
run_enrichment_mechanism(service, integration_context, mapper)
else:
fetch_notables(service=service, enrich_notables=False, mapper=mapper)
# =========== Regular Fetch Mechanism ===========
# =========== Enriching Fetch Mechanism ===========
class Enrichment:
""" A class to represent an Enrichment. Each notable has 3 possible enrichments: Drilldown, Asset & Identity
Attributes:
type (str): The enrichment type. Possible values are: Drilldown, Asset & Identity.
id (str): The enrichment's job id in Splunk server.
data (list): The enrichment's data list (events retrieved from the job's search).
creation_time (str): The enrichment's creation time in ISO format.
status (str): The enrichment's status.
"""
FAILED = 'Enrichment failed'
EXCEEDED_TIMEOUT = 'Enrichment exceed the given timeout'
IN_PROGRESS = 'Enrichment is in progress'
SUCCESSFUL = 'Enrichment successfully handled'
HANDLED = (EXCEEDED_TIMEOUT, FAILED, SUCCESSFUL)
def __init__(self, enrichment_type, status=None, enrichment_id=None, data=None, creation_time=None):
self.type = enrichment_type
self.id = enrichment_id
self.data = data if data else []
self.creation_time = creation_time if creation_time else datetime.utcnow().isoformat()
self.status = status if status else Enrichment.IN_PROGRESS
@classmethod
def from_job(cls, enrichment_type, job: client.Job):
""" Creates an Enrichment object from Splunk Job object
Args:
enrichment_type (str): The enrichment type
job (splunklib.client.Job): The corresponding Splunk Job
Returns:
The created enrichment (Enrichment)
"""
if job:
return cls(enrichment_type=enrichment_type, enrichment_id=job["sid"])
else:
return cls(enrichment_type=enrichment_type, status=Enrichment.FAILED)
@classmethod
def from_json(cls, enrichment_dict):
""" Deserialization method.
Args:
enrichment_dict (dict): The enrichment dict in JSON format.
Returns:
An instance of the Enrichment class constructed from JSON representation.
"""
return cls(
enrichment_type=enrichment_dict.get(TYPE),
data=enrichment_dict.get(DATA),
status=enrichment_dict.get(STATUS),
enrichment_id=enrichment_dict.get(ID),
creation_time=enrichment_dict.get(CREATION_TIME)
)
class Notable:
""" A class to represent a notable.
Attributes:
data (dict): The notable data.
id (str): The notable's id.
enrichments (list): The list of all enrichments that needs to handle.
incident_created (bool): Whether an incident created or not.
occurred (str): The occurred time of the notable.
custom_id (str): The custom ID of the notable (used in the fetch function).
time_is_missing (bool): Whether the `_time` field has an empty value or not.
index_time (str): The time the notable have been indexed.
"""
def __init__(self, data, enrichments=None, notable_id=None, occurred=None, custom_id=None, index_time=None,
time_is_missing=None, incident_created=None):
self.data = data
self.id = notable_id if notable_id else self.get_id()
self.enrichments = enrichments if enrichments else []
self.incident_created = incident_created if incident_created else False
self.time_is_missing = time_is_missing if time_is_missing else False
self.index_time = index_time if index_time else self.data.get('_indextime')
self.occurred = occurred if occurred else self.get_occurred()
self.custom_id = custom_id if custom_id else self.create_custom_id()
def get_id(self):
if EVENT_ID in self.data:
return self.data[EVENT_ID]
else:
if ENABLED_ENRICHMENTS:
raise Exception('When using the enrichment mechanism, an event_id field is needed, and thus, '
'one must use a fetch query of the following format: search `notable` .......\n'
'Please re-edit the fetchQuery parameter in the integration configuration, reset '
'the fetch mechanism using the splunk-reset-enriching-fetch-mechanism command and '
'run the fetch again.')
else:
return None
@staticmethod
def create_incident(notable_data, occurred, mapper: UserMappingObject):
incident = {} # type: Dict[str,Any]
rule_title, rule_name = '', ''
if demisto.get(notable_data, 'rule_title'):
rule_title = notable_data['rule_title']
if demisto.get(notable_data, 'rule_name'):
rule_name = notable_data['rule_name']
incident["name"] = "{} : {}".format(rule_title, rule_name)
if demisto.get(notable_data, 'urgency'):
incident["severity"] = severity_to_level(notable_data['urgency'])
if demisto.get(notable_data, 'rule_description'):
incident["details"] = notable_data["rule_description"]
if demisto.get(notable_data, "owner") and mapper.should_map:
owner = mapper.get_xsoar_user_by_splunk(notable_data["owner"])
if owner:
incident["owner"] = owner
incident["occurred"] = occurred
notable_data = parse_notable(notable_data)
notable_data.update({
'mirror_instance': demisto.integrationInstance(),
'mirror_direction': MIRROR_DIRECTION.get(demisto.params().get('mirror_direction'))
})
incident["rawJSON"] = json.dumps(notable_data)
labels = []
if demisto.get(demisto.params(), 'parseNotableEventsRaw'):
isParseNotableEventsRaw = demisto.params()['parseNotableEventsRaw']
if isParseNotableEventsRaw:
rawDict = rawToDict(notable_data['_raw'])
for rawKey in rawDict:
val = rawDict[rawKey] if isinstance(rawDict[rawKey], str) else convert_to_str(rawDict[rawKey])
labels.append({'type': rawKey, 'value': val})
if demisto.get(notable_data, 'security_domain'):
labels.append({'type': 'security_domain', 'value': notable_data["security_domain"]})
incident['labels'] = labels
incident['dbotMirrorId'] = notable_data.get(EVENT_ID)
return incident
def to_incident(self, mapper: UserMappingObject):
""" Gathers all data from all notable's enrichments and return an incident """
self.incident_created = True
for e in self.enrichments:
self.data[e.type] = e.data
self.data[ENRICHMENT_TYPE_TO_ENRICHMENT_STATUS[e.type]] = e.status == Enrichment.SUCCESSFUL
return self.create_incident(self.data, self.occurred, mapper=mapper)
def submitted(self):
""" Returns an indicator on whether any of the notable's enrichments was submitted or not """
return any(enrichment.status == Enrichment.IN_PROGRESS for enrichment in self.enrichments) and len(
self.enrichments) == len(ENABLED_ENRICHMENTS)
def failed_to_submit(self):
""" Returns an indicator on whether all notable's enrichments were failed to submit or not """
return all(enrichment.status == Enrichment.FAILED for enrichment in self.enrichments) and len(
self.enrichments) == len(ENABLED_ENRICHMENTS)
def handled(self):
""" Returns an indicator on whether all notable's enrichments were handled or not """
return all(enrichment.status in Enrichment.HANDLED for enrichment in self.enrichments) or any(
enrichment.status == Enrichment.EXCEEDED_TIMEOUT for enrichment in self.enrichments)
def get_submitted_enrichments(self):
""" Returns indicators on whether each enrichment was submitted/failed or not initiated """
submitted_drilldown, submitted_asset, submitted_identity = False, False, False
for enrichment in self.enrichments:
if enrichment.type == DRILLDOWN_ENRICHMENT:
submitted_drilldown = True
elif enrichment.type == ASSET_ENRICHMENT:
submitted_asset = True
elif enrichment.type == IDENTITY_ENRICHMENT:
submitted_identity = True
return submitted_drilldown, submitted_asset, submitted_identity
def get_occurred(self):
""" Returns the occurred time, if not exists in data, returns the current fetch time """
if '_time' in self.data:
notable_occurred = self.data['_time']
else:
# Use-cases where fetching non-notables from Splunk
notable_occurred = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.0+00:00')
self.time_is_missing = True
demisto.debug('\n\n occurred time in else: {} \n\n'.format(notable_occurred))
return notable_occurred
def create_custom_id(self):
""" Generates a custom ID for a given notable """
if self.id:
return self.id
notable_raw_data = self.data.get('_raw', '')
raw_hash = hashlib.md5(notable_raw_data.encode('utf-8')).hexdigest() # nosec # guardrails-disable-line
if self.time_is_missing and self.index_time:
notable_custom_id = '{}_{}'.format(self.index_time, raw_hash) # index_time stays in epoch to differentiate
demisto.debug('Creating notable custom id using the index time')
else:
notable_custom_id = '{}_{}'.format(self.occurred, raw_hash)
return notable_custom_id
def is_enrichment_process_exceeding_timeout(self, enrichment_timeout):
""" Checks whether an enrichment process has exceeded timeout or not
Args:
enrichment_timeout (int): The timeout for the enrichment process
Returns (bool): True if the enrichment process exceeded the given timeout, False otherwise
"""
now = datetime.utcnow()
exceeding_timeout = False
for enrichment in self.enrichments:
if enrichment.status == Enrichment.IN_PROGRESS:
creation_time_datetime = datetime.strptime(enrichment.creation_time, JOB_CREATION_TIME_FORMAT)
if now - creation_time_datetime > timedelta(minutes=enrichment_timeout):
exceeding_timeout = True
enrichment.status = Enrichment.EXCEEDED_TIMEOUT
return exceeding_timeout
@classmethod
def from_json(cls, notable_dict):
""" Deserialization method.
Args:
notable_dict: The notable dict in JSON format.
Returns:
An instance of the Enrichment class constructed from JSON representation.
"""
return cls(
data=notable_dict.get(DATA),
enrichments=list(map(Enrichment.from_json, notable_dict.get(ENRICHMENTS))),
notable_id=notable_dict.get(ID),
custom_id=notable_dict.get(CUSTOM_ID),
occurred=notable_dict.get(OCCURRED),
time_is_missing=notable_dict.get(TIME_IS_MISSING),
index_time=notable_dict.get(INDEX_TIME),
incident_created=notable_dict.get(INCIDENT_CREATED)
)
class Cache:
""" A class to represent the cache for the enriching fetch mechanism.
Attributes:
not_yet_submitted_notables (list): The list of all notables that were fetched but not yet submitted.
submitted_notables (list): The list of all submitted notables that needs to be handled.
"""
def __init__(self, not_yet_submitted_notables=None, submitted_notables=None):
self.not_yet_submitted_notables = not_yet_submitted_notables if not_yet_submitted_notables else []
self.submitted_notables = submitted_notables if submitted_notables else []
def done_submitting(self):
return not self.not_yet_submitted_notables
def done_handling(self):
return not self.submitted_notables
def organize(self):
""" This function is designated to handle unexpected behaviors in the enrichment mechanism.
E.g. Connection error, instance disabling, etc...
It re-organizes the cache object to the correct state of the mechanism when the exception was caught.
If there are notables that were handled but the mechanism didn't create an incident for them, it returns them.
This function is called in each "end" of execution of the enrichment mechanism.
Returns:
handled_not_created_incident (list): The list of all notables that have been handled but not created an
incident.
"""
not_yet_submitted, submitted, handled_not_created_incident = [], [], []
for notable in self.not_yet_submitted_notables:
if notable.submitted():
if notable not in self.submitted_notables:
submitted.append(notable)
elif notable.failed_to_submit():
if not notable.incident_created:
handled_not_created_incident.append(notable)
else:
not_yet_submitted.append(notable)
for notable in self.submitted_notables:
if notable.handled():
if not notable.incident_created:
handled_not_created_incident.append(notable)
else:
submitted.append(notable)
self.not_yet_submitted_notables = not_yet_submitted
self.submitted_notables = submitted
return handled_not_created_incident
@classmethod
def from_json(cls, cache_dict):
""" Deserialization method.
Args:
cache_dict: The cache dict in JSON format.
Returns:
An instance of the Cache class constructed from JSON representation.
"""
return cls(
not_yet_submitted_notables=list(map(Notable.from_json, cache_dict.get(NOT_YET_SUBMITTED_NOTABLES, []))),
submitted_notables=list(map(Notable.from_json, cache_dict.get(SUBMITTED_NOTABLES, [])))
)
@classmethod
def load_from_integration_context(cls, integration_context):
return Cache.from_json(json.loads(integration_context.get(CACHE, "{}")))
def dump_to_integration_context(self, integration_context):
integration_context[CACHE] = json.dumps(self, default=lambda obj: obj.__dict__)
set_integration_context(integration_context)
def get_fields_query_part(notable_data, prefix, fields, raw_dict=None, add_backslash=False):
""" Given the fields to search for in the notables and the prefix, creates the query part for splunk search.
For example: if fields are ["user"], and the value of the "user" fields in the notable is ["u1", "u2"], and the
prefix is "identity", the function returns: (identity="u1" OR identity="u2")
Args:
notable_data (dict): The notable.
prefix (str): The prefix to attach to each value returned in the query.
fields (list): The fields to search in the notable for.
raw_dict (dict): The raw dict
add_backslash (bool): For users that contains single backslash, we add one more
Returns: The query part
"""
if not raw_dict:
raw_dict = rawToDict(notable_data.get('_raw', ''))
raw_list = [] # type: list
for field in fields:
raw_list += argToList(notable_data.get(field, "")) + argToList(raw_dict.get(field, ""))
if add_backslash:
raw_list = [item.replace('\\', '\\\\') for item in raw_list]
raw_list = ['{}="{}"'.format(prefix, item.strip('"')) for item in raw_list]
if not raw_list:
return ""
elif len(raw_list) == 1:
return raw_list[0]
else:
return "({})".format(" OR ".join(raw_list))
def get_notable_field_and_value(raw_field, notable_data, raw=None):
""" Gets the value by the name of the raw_field. We don't search for equivalence because raw field
can be "threat_match_field|s" while the field is "threat_match_field".
Args:
raw_field (str): The raw field
notable_data (dict): The notable data
raw (dict): The raw dict
Returns: The value in the notable which is associated with raw_field
"""
if not raw:
raw = rawToDict(notable_data.get('_raw', ''))
for field in notable_data:
if field in raw_field:
return field, notable_data[field]
for field in raw:
if field in raw_field:
return field, raw[field]
demisto.error('Failed building drilldown search query. field {} was not found in the notable.'.format(raw_field))
return "", ""
def build_drilldown_search(notable_data, search, raw_dict):
""" Replaces all needed fields in a drilldown search query
Args:
notable_data (dict): The notable data
search (str): The drilldown search query
raw_dict (dict): The raw dict
Returns (str): A searchable drilldown search query
"""
searchable_search = []
start = 0
for match in re.finditer(DRILLDOWN_REGEX, search):
groups = match.groups()
prefix = groups[0]
raw_field = (groups[1] or groups[2]).strip('$')
field, replacement = get_notable_field_and_value(raw_field, notable_data, raw_dict)
if not field and not replacement:
return ""
if prefix:
replacement = get_fields_query_part(notable_data, prefix, [field], raw_dict)
end = match.start()
searchable_search.append(search[start:end])
searchable_search.append(str(replacement))
start = match.end()
searchable_search.append(search[start:]) # Handling the tail of the query
return ''.join(searchable_search)
def get_drilldown_timeframe(notable_data, raw):
""" Sets the drilldown search timeframe data.
Args:
notable_data (dict): The notable
raw (dict): The raw dict
Returns:
task_status: True if the timeframe was retrieved successfully, False otherwise.
earliest_offset: The earliest time to query from.
latest_offset: The latest time to query to.
"""
task_status = True
earliest_offset = notable_data.get("drilldown_earliest", "")
latest_offset = notable_data.get("drilldown_latest", "")
info_min_time = raw.get(INFO_MIN_TIME, "")
info_max_time = raw.get(INFO_MAX_TIME, "")
if not earliest_offset or earliest_offset == "${}$".format(INFO_MIN_TIME):
if info_min_time:
earliest_offset = info_min_time
else:
demisto.debug("Failed retrieving info min time")
task_status = False
if not latest_offset or latest_offset == "${}$".format(INFO_MAX_TIME):
if info_max_time:
latest_offset = info_max_time
else:
demisto.debug("Failed retrieving info max time")
task_status = False
return task_status, earliest_offset, latest_offset
def drilldown_enrichment(service: client.Service, notable_data, num_enrichment_events):
""" Performs a drilldown enrichment.
Args:
service (splunklib.client.Service): Splunk service object.
notable_data (dict): The notable data
num_enrichment_events (int): The maximal number of events to return per enrichment type.
Returns: The Splunk Job
"""
job = None
search = notable_data.get("drilldown_search", "")
if search:
raw_dict = rawToDict(notable_data.get("_raw", ""))
searchable_query = build_drilldown_search(notable_data, search, raw_dict)
if searchable_query:
status, earliest_offset, latest_offset = get_drilldown_timeframe(notable_data, raw_dict)
if status:
kwargs = {"count": num_enrichment_events, "exec_mode": "normal"}
if latest_offset:
kwargs['latest_time'] = latest_offset
if earliest_offset:
kwargs['earliest_time'] = earliest_offset
query = build_search_query({"query": searchable_query})
demisto.debug("Drilldown query for notable {}: {}".format(notable_data[EVENT_ID], query))
try:
job = service.jobs.create(query, **kwargs)
except Exception as e:
demisto.error("Caught an exception in drilldown_enrichment function: {}".format(str(e)))
else:
demisto.debug('Failed getting the drilldown timeframe for notable {}'.format(notable_data[EVENT_ID]))
else:
demisto.debug("Couldn't build search query for notable {} with the following drilldown "
"search {}".format(notable_data[EVENT_ID], search))
else:
demisto.debug("drill-down was not configured for notable {}".format(notable_data[EVENT_ID]))
return job
def identity_enrichment(service: client.Service, notable_data, num_enrichment_events) -> client.Job:
""" Performs an identity enrichment.
Args:
service (splunklib.client.Service): Splunk service object
notable_data (dict): The notable data
num_enrichment_events (int): The maximal number of events to return per enrichment type.
Returns: The Splunk Job
"""
job = None
error_msg = "Failed submitting identity enrichment request to Splunk for notable {}".format(notable_data[EVENT_ID])
users = get_fields_query_part(
notable_data=notable_data, prefix="identity", fields=["user", "src_user"], add_backslash=True
)
if users:
kwargs = {"count": num_enrichment_events, "exec_mode": "normal"}
query = '| inputlookup identity_lookup_expanded where {}'.format(users)
demisto.debug("Identity query for notable {}: {}".format(notable_data[EVENT_ID], query))
try:
job = service.jobs.create(query, **kwargs)
except Exception as e:
demisto.error("Caught an exception in drilldown_enrichment function: {}".format(str(e)))
else:
demisto.debug('No users were found in notable. {}'.format(error_msg))
return job
def asset_enrichment(service: client.Service, notable_data, num_enrichment_events) -> client.Job:
""" Performs an asset enrichment.
Args:
service (splunklib.client.Service): Splunk service object
notable_data (dict): The notable data
num_enrichment_events (int): The maximal number of events to return per enrichment type.
Returns: The Splunk Job
"""
job = None
error_msg = "Failed submitting asset enrichment request to Splunk for notable {}".format(notable_data[EVENT_ID])
assets = get_fields_query_part(
notable_data=notable_data, prefix="asset", fields=["src", "dest", "src_ip", "dst_ip"]
)
if assets:
kwargs = {"count": num_enrichment_events, "exec_mode": "normal"}
query = '| inputlookup append=T asset_lookup_by_str where {} | inputlookup append=t asset_lookup_by_cidr ' \
'where {} | rename _key as asset_id | stats values(*) as * by asset_id'.format(assets, assets)
demisto.debug("Asset query for notable {}: {}".format(notable_data[EVENT_ID], query))
try:
job = service.jobs.create(query, **kwargs)
except Exception as e:
demisto.error("Caught an exception in asset_enrichment function: {}".format(str(e)))
else:
demisto.debug('No assets were found in notable. {}'.format(error_msg))
return job
def handle_submitted_notables(service: client.Service, incidents, cache_object: Cache, mapper: UserMappingObject):
""" Handles submitted notables. For each submitted notable, tries to retrieve its results, if results aren't ready,
it moves to the next submitted notable.
Args:
service (splunklib.client.Service): Splunk service object.