-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathCortexXDRIR.py
1524 lines (1233 loc) · 64.8 KB
/
CortexXDRIR.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 demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import hashlib
import secrets
import string
from itertools import zip_longest
from CoreIRApiModule import *
# Disable insecure warnings
urllib3.disable_warnings()
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
NONCE_LENGTH = 64
API_KEY_LENGTH = 128
INTEGRATION_CONTEXT_BRAND = 'PaloAltoNetworksXDR'
XDR_INCIDENT_TYPE_NAME = 'Cortex XDR Incident Schema'
INTEGRATION_NAME = 'Cortex XDR - IR'
ALERTS_LIMIT_PER_INCIDENTS = -1
XDR_INCIDENT_FIELDS = {
"status": {"description": "Current status of the incident: \"new\",\"under_"
"investigation\",\"resolved_known_issue\","
"\"resolved_duplicate\",\"resolved_false_positive\","
"\"resolved_true_positive\",\"resolved_security_testing\",\"resolved_other\"",
"xsoar_field_name": 'xdrstatusv2'},
"assigned_user_mail": {"description": "Email address of the assigned user.",
'xsoar_field_name': "xdrassigneduseremail"},
"assigned_user_pretty_name": {"description": "Full name of the user assigned to the incident.",
"xsoar_field_name": "xdrassigneduserprettyname"},
"resolve_comment": {"description": "Comments entered by the user when the incident was resolved.",
"xsoar_field_name": "xdrresolvecomment"},
"manual_severity": {"description": "Incident severity assigned by the user. "
"This does not affect the calculated severity low medium high",
"xsoar_field_name": "severity"},
"close_reason": {"description": "The close reason of the XSOAR incident",
"xsoar_field_name": "closeReason"}
}
MIRROR_DIRECTION = {
'None': None,
'Incoming': 'In',
'Outgoing': 'Out',
'Both': 'Both'
}
def convert_epoch_to_milli(timestamp):
if timestamp is None:
return None
if 9 < len(str(timestamp)) < 13:
timestamp = int(timestamp) * 1000
return int(timestamp)
def convert_datetime_to_epoch(the_time=0):
if the_time is None:
return None
try:
if isinstance(the_time, datetime):
return int(the_time.strftime('%s'))
except Exception as err:
demisto.debug(err)
return 0
def convert_datetime_to_epoch_millis(the_time=0):
return convert_epoch_to_milli(convert_datetime_to_epoch(the_time=the_time))
def generate_current_epoch_utc():
return convert_datetime_to_epoch_millis(datetime.now(timezone.utc))
def generate_key():
return "".join([secrets.choice(string.ascii_letters + string.digits) for _ in range(API_KEY_LENGTH)])
def create_auth(api_key):
nonce = "".join([secrets.choice(string.ascii_letters + string.digits) for _ in range(NONCE_LENGTH)])
timestamp = str(generate_current_epoch_utc()) # Get epoch time utc millis
hash_ = hashlib.sha256()
hash_.update((api_key + nonce + timestamp).encode("utf-8"))
return nonce, timestamp, hash_.hexdigest()
def clear_trailing_whitespace(res):
if res:
index = 0
while index < len(res):
for key, value in res[index].items():
if value and isinstance(value, str):
res[index][key] = value.rstrip()
index += 1
return res
def filter_and_save_unseen_incident(incidents: List, limit: int, number_of_already_filtered_incidents: int) -> List:
"""
Filters incidents that were seen already and saves the unseen incidents to LastRun object.
:param incidents: List of incident - must be list
:param limit: the maximum number of incident per fetch
:param number_of_already_filtered_incidents: number of incidents that were fetched already
:return: the filtered incidents.
"""
last_run_obj = demisto.getLastRun()
fetched_starred_incidents = last_run_obj.pop('fetched_starred_incidents', {})
filtered_incidents = []
for incident in incidents:
incident_id = incident.get('incident_id')
if incident_id in fetched_starred_incidents:
demisto.debug(f'incident (ID {incident_id}) was already fetched in the past.')
continue
fetched_starred_incidents[incident_id] = True
filtered_incidents.append(incident)
number_of_already_filtered_incidents += 1
if number_of_already_filtered_incidents >= limit:
break
last_run_obj['fetched_starred_incidents'] = fetched_starred_incidents
demisto.setLastRun(last_run_obj)
return filtered_incidents
class Client(CoreClient):
def __init__(self, base_url, proxy, verify, timeout, params=None):
if not params:
params = {}
self._params = params
super().__init__(base_url=base_url, proxy=proxy, verify=verify, headers=self.headers, timeout=timeout)
@property
def headers(self):
return get_headers(self._params)
def test_module(self, first_fetch_time):
"""
Performs basic get request to get item samples
"""
last_one_day, _ = parse_date_range(first_fetch_time, TIME_FORMAT)
try:
self.get_incidents(lte_creation_time=last_one_day, limit=1)
except Exception as err:
if 'API request Unauthorized' in str(err):
# this error is received from the XDR server when the client clock is not in sync to the server
raise DemistoException(f'{str(err)} please validate that your both '
f'XSOAR and XDR server clocks are in sync')
else:
raise
def handle_fetch_starred_incidents(self, limit: int, page_number: int, request_data: dict) -> List:
"""
handles pagination and filter of starred incidents that were fetched.
:param limit: the maximum number of incident per fetch
:param page_number: page number
:param request_data: the api call request data
:return: the filtered starred incidents.
"""
res = self._http_request(
method='POST',
url_suffix='/incidents/get_incidents/',
json_data={'request_data': request_data},
headers=self.headers,
timeout=self.timeout
)
raw_incidents = res.get('reply', {}).get('incidents', [])
# we want to avoid duplications of starred incidents in the fetch-incident command (we fetch all incidents
# in the fetch window).
filtered_incidents = filter_and_save_unseen_incident(raw_incidents, limit, 0)
# we want to support pagination on starred incidents.
while len(filtered_incidents) < limit:
page_number += 1
search_from = page_number * limit
search_to = search_from + limit
request_data['search_from'] = search_from
request_data['search_to'] = search_to
res = self._http_request(
method='POST',
url_suffix='/incidents/get_incidents/',
json_data={'request_data': request_data},
headers=self.headers,
timeout=self.timeout
)
raw_incidents = res.get('reply', {}).get('incidents', [])
if not raw_incidents:
break
filtered_incidents += filter_and_save_unseen_incident(raw_incidents, limit, len(filtered_incidents))
return filtered_incidents
def update_incident(self, incident_id, status=None, assigned_user_mail=None, assigned_user_pretty_name=None, severity=None,
resolve_comment=None, unassign_user=None, add_comment=None):
update_data: dict[str, Any] = {}
if unassign_user and (assigned_user_mail or assigned_user_pretty_name):
raise ValueError("Can't provide both assignee_email/assignee_name and unassign_user")
if unassign_user:
update_data['assigned_user_mail'] = 'none'
if assigned_user_mail:
update_data['assigned_user_mail'] = assigned_user_mail
if assigned_user_pretty_name:
update_data['assigned_user_pretty_name'] = assigned_user_pretty_name
if status:
update_data['status'] = status
if severity:
update_data['manual_severity'] = severity
if resolve_comment:
update_data['resolve_comment'] = resolve_comment
if add_comment:
update_data['comment'] = {'comment_action': 'add', 'value': add_comment}
request_data = {
'incident_id': incident_id,
'update_data': update_data,
}
self._http_request(
method='POST',
url_suffix='/incidents/update_incident/',
json_data={'request_data': request_data},
headers=self.headers,
timeout=self.timeout
)
def get_incident_extra_data(self, incident_id, alerts_limit=1000):
"""
Returns incident by id
:param incident_id: The id of incident
:param alerts_limit: Maximum number alerts to get
:return:
"""
request_data = {
'incident_id': incident_id,
'alerts_limit': alerts_limit,
}
reply = self._http_request(
method='POST',
url_suffix='/incidents/get_incident_extra_data/',
json_data={'request_data': request_data},
headers=self.headers,
timeout=self.timeout
)
incident = reply.get('reply')
return incident
def save_modified_incidents_to_integration_context(self):
last_modified_incidents = self.get_incidents(limit=100, sort_by_modification_time='desc')
modified_incidents_context = {}
for incident in last_modified_incidents:
incident_id = incident.get('incident_id')
modified_incidents_context[incident_id] = incident.get('modification_time')
set_integration_context({'modified_incidents': modified_incidents_context})
def get_contributing_event_by_alert_id(self, alert_id: int) -> dict:
request_data = {
"request_data": {
"alert_id": alert_id,
}
}
reply = self._http_request(
method='POST',
url_suffix='/alerts/get_correlation_alert_data/',
json_data=request_data,
headers=self.headers,
timeout=self.timeout,
)
return reply.get('reply', {})
def replace_featured_field(self, field_type: str, fields: list[dict]) -> dict:
request_data = {
'request_data': {
'fields': fields
}
}
reply = self._http_request(
method='POST',
url_suffix=f'/featured_fields/replace_{field_type}',
json_data=request_data,
timeout=self.timeout,
headers=self.headers,
raise_on_status=True
)
return reply.get('reply')
def get_tenant_info(self):
reply = self._http_request(
method='POST',
url_suffix='/system/get_tenant_info/',
json_data={'request_data': {}},
headers=self.headers,
timeout=self.timeout
)
return reply.get('reply', {})
def get_multiple_incidents_extra_data(self, incident_id_list=[], fields_to_exclude=[], gte_creation_time_milliseconds=0,
status=None, starred=None, starred_incidents_fetch_window=None, page_number=0, limit=100):
"""
Returns incident by id
:param incident_id_list: The list ids of incidents
:return:
Maximum number alerts to get in Maximum number alerts to get in "get_multiple_incidents_extra_data" is 50, not sorted
"""
global ALERTS_LIMIT_PER_INCIDENTS
request_data = {}
filters = []
if incident_id_list:
filters.append({"field": "incident_id_list", "operator": "in", "value": incident_id_list})
if gte_creation_time_milliseconds > 0:
filters.append({
'field': 'creation_time',
'operator': 'gte',
'value': gte_creation_time_milliseconds
})
if status:
filters.append({
'field': 'status',
'operator': 'eq',
'value': status
})
if starred and starred_incidents_fetch_window:
filters.append({
'field': 'starred',
'operator': 'eq',
'value': True
})
filters.append({
'field': 'creation_time',
'operator': 'gte',
'value': starred_incidents_fetch_window
})
if demisto.command() == 'fetch-incidents':
if len(filters) > 0:
request_data['filters'] = filters
incidents = self.handle_fetch_starred_incidents(limit, page_number, request_data)
return incidents
if len(filters) > 0:
request_data['filters'] = filters
if fields_to_exclude:
request_data['fields_to_exclude'] = fields_to_exclude
reply = self._http_request(
method='POST',
url_suffix='/incidents/get_multiple_incidents_extra_data/',
json_data={'request_data': request_data},
headers=self.headers,
timeout=self.timeout,
)
if ALERTS_LIMIT_PER_INCIDENTS < 0:
ALERTS_LIMIT_PER_INCIDENTS = arg_to_number(reply.get('reply', {}).get('alerts_limit_per_incident')) or 50
demisto.debug(f'Setting alerts limit per incident to {ALERTS_LIMIT_PER_INCIDENTS}')
incidents = reply.get('reply', {}).get('incidents', [])
return incidents
def get_headers(params: dict) -> dict:
api_key = params.get('apikey') or params.get('apikey_creds', {}).get('password', '')
api_key_id = params.get('apikey_id') or params.get('apikey_id_creds', {}).get('password', '')
nonce: str = "".join([secrets.choice(string.ascii_letters + string.digits) for _ in range(64)])
timestamp: str = str(int(datetime.now(timezone.utc).timestamp()) * 1000)
auth_key = f"{api_key}{nonce}{timestamp}"
auth_key = auth_key.encode("utf-8")
api_key_hash: str = hashlib.sha256(auth_key).hexdigest()
if argToBoolean(params.get("prevent_only", False)):
api_key_hash = api_key
headers: dict = {
"x-xdr-timestamp": timestamp,
"x-xdr-nonce": nonce,
"x-xdr-auth-id": str(api_key_id),
"Authorization": api_key_hash,
}
return headers
def get_tenant_info_command(client: Client):
tenant_info = client.get_tenant_info()
readable_output = tableToMarkdown(
'Tenant Information', tenant_info, headerTransform=pascalToSpace, removeNull=True, is_auto_json_transform=True
)
return CommandResults(
readable_output=readable_output,
outputs_prefix=f'{INTEGRATION_CONTEXT_BRAND}.TenantInformation',
outputs=tenant_info,
raw_response=tenant_info
)
def update_incident_command(client, args):
incident_id = args.get('incident_id')
assigned_user_mail = args.get('assigned_user_mail')
assigned_user_pretty_name = args.get('assigned_user_pretty_name')
status = args.get('status')
severity = args.get('manual_severity')
unassign_user = args.get('unassign_user') == 'true'
resolve_comment = args.get('resolve_comment')
add_comment = args.get('add_comment')
client.update_incident(
incident_id=incident_id,
assigned_user_mail=assigned_user_mail,
assigned_user_pretty_name=assigned_user_pretty_name,
unassign_user=unassign_user,
status=status,
severity=severity,
resolve_comment=resolve_comment,
add_comment=add_comment,
)
return f'Incident {incident_id} has been updated', None, None
def check_if_incident_was_modified_in_xdr(incident_id, last_mirrored_in_time_timestamp, last_modified_incidents_dict):
if incident_id in last_modified_incidents_dict: # search the incident in the dict of modified incidents
incident_modification_time_in_xdr = int(str(last_modified_incidents_dict[incident_id]))
demisto.debug(f"XDR incident {incident_id}\n"
f"modified time: {incident_modification_time_in_xdr}\n"
f"last mirrored in time: {last_mirrored_in_time_timestamp}")
if incident_modification_time_in_xdr > last_mirrored_in_time_timestamp: # need to update this incident
demisto.info(f"Incident '{incident_id}' was modified. performing extra-data request.")
return True
# the incident was not modified
return False
def get_last_mirrored_in_time(args):
demisto_incidents = demisto.get_incidents() # type: ignore
if demisto_incidents: # handling 5.5 version
demisto_incident = demisto_incidents[0]
last_mirrored_in_time = demisto_incident.get('CustomFields', {}).get('lastmirroredintime')
if not last_mirrored_in_time: # this is an old incident, update anyway
return 0
last_mirrored_in_timestamp = arg_to_timestamp(last_mirrored_in_time, 'last_mirrored_in_time')
else: # handling 6.0 version
last_mirrored_in_time = arg_to_timestamp(args.get('last_update'), 'last_update')
last_mirrored_in_timestamp = (last_mirrored_in_time - (120 * 1000))
return last_mirrored_in_timestamp
def get_incident_extra_data_command(client, args):
global ALERTS_LIMIT_PER_INCIDENTS
incident_id = args.get('incident_id')
alerts_limit = int(args.get('alerts_limit', 1000))
return_only_updated_incident = argToBoolean(args.get('return_only_updated_incident', 'False'))
fields_to_exclude = argToList(args.get('fields_to_exclude'))
if return_only_updated_incident:
last_mirrored_in_time = get_last_mirrored_in_time(args)
last_modified_incidents_dict = get_integration_context().get('modified_incidents', {})
if check_if_incident_was_modified_in_xdr(incident_id, last_mirrored_in_time, last_modified_incidents_dict):
pass # the incident was modified. continue to perform extra-data request
else: # the incident was not modified
return "The incident was not modified in XDR since the last mirror in.", {}, {}
raw_incident: Dict[str, Any] = client.get_multiple_incidents_extra_data(incident_id_list=[incident_id],
fields_to_exclude=fields_to_exclude)[0]
if raw_incident.get('incident', {}).get('alert_count') > ALERTS_LIMIT_PER_INCIDENTS:
raw_incident = client.get_incident_extra_data(incident_id, alerts_limit)
incident = raw_incident.get('incident', {})
incident_id = incident.get('incident_id')
raw_alerts = raw_incident.get('alerts', {}).get('data', None)
readable_output = [tableToMarkdown(f'Incident {incident_id}', incident, removeNull=True)]
file_artifacts = raw_incident.get('file_artifacts', {}).get('data')
network_artifacts = raw_incident.get('network_artifacts', {}).get('data')
context_alerts = clear_trailing_whitespace(raw_alerts)
if context_alerts:
for alert in context_alerts:
alert['host_ip_list'] = alert.get('host_ip').split(',') if alert.get('host_ip') else []
if len(context_alerts) > 0:
readable_output.append(tableToMarkdown('Alerts', context_alerts,
headers=[key for key in context_alerts[0] if key != 'host_ip'], removeNull=True))
else:
readable_output.append(tableToMarkdown('Alerts', raw_alerts, removeNull=True))
if raw_alerts and len(raw_alerts) > 0:
readable_output.append(tableToMarkdown('Alerts', raw_alerts, removeNull=True))
if network_artifacts and len(network_artifacts) > 0:
readable_output.append(tableToMarkdown('Network Artifacts', network_artifacts, removeNull=True))
else:
readable_output.append(tableToMarkdown('Network Artifacts', [], removeNull=True))
if file_artifacts and len(file_artifacts) > 0:
readable_output.append(tableToMarkdown('File Artifacts', file_artifacts, removeNull=True))
else:
readable_output.append(tableToMarkdown('File Artifacts', [], removeNull=True))
incident.update({
'alerts': raw_alerts,
'file_artifacts': file_artifacts,
'network_artifacts': network_artifacts
})
account_context_output = assign_params(
Username=incident.get('users', '')
)
endpoint_context_output = []
for alert in incident.get('alerts') or []:
alert_context = {}
if hostname := alert.get('host_name'):
alert_context['Hostname'] = hostname
if endpoint_id := alert.get('endpoint_id'):
alert_context['ID'] = endpoint_id
if alert_context:
endpoint_context_output.append(alert_context)
context_output = {f'{INTEGRATION_CONTEXT_BRAND}.Incident(val.incident_id==obj.incident_id)': incident}
if account_context_output:
context_output['Account(val.Username==obj.Username)'] = account_context_output
if endpoint_context_output:
context_output['Endpoint(val.Hostname==obj.Hostname)'] = endpoint_context_output
file_context, process_context, domain_context, ip_context = get_indicators_context(incident)
if file_context:
context_output[Common.File.CONTEXT_PATH] = file_context
if domain_context:
context_output[Common.Domain.CONTEXT_PATH] = domain_context
if ip_context:
context_output[Common.IP.CONTEXT_PATH] = ip_context
if process_context:
context_output['Process(val.Name && val.Name == obj.Name)'] = process_context
return (
'\n'.join(readable_output),
context_output,
raw_incident
)
def create_parsed_alert(product, vendor, local_ip, local_port, remote_ip, remote_port, event_timestamp, severity,
alert_name, alert_description):
alert = {
"product": product,
"vendor": vendor,
"local_ip": local_ip,
"local_port": local_port,
"remote_ip": remote_ip,
"remote_port": remote_port,
"event_timestamp": event_timestamp,
"severity": severity,
"alert_name": alert_name,
"alert_description": alert_description
}
return alert
def insert_parsed_alert_command(client, args):
product = args.get('product')
vendor = args.get('vendor')
local_ip = args.get('local_ip')
local_port = arg_to_int(
arg=args.get('local_port'),
arg_name='local_port'
)
remote_ip = args.get('remote_ip')
remote_port = arg_to_int(
arg=args.get('remote_port'),
arg_name='remote_port'
)
severity = args.get('severity')
alert_name = args.get('alert_name')
alert_description = args.get('alert_description', '')
event_timestamp = int(round(time.time() * 1000)) if args.get("event_timestamp") is None else int(args.get("event_timestamp"))
alert = create_parsed_alert(
product=product,
vendor=vendor,
local_ip=local_ip,
local_port=local_port,
remote_ip=remote_ip,
remote_port=remote_port,
event_timestamp=event_timestamp,
severity=severity,
alert_name=alert_name,
alert_description=alert_description
)
client.insert_alerts([alert])
return (
'Alert inserted successfully',
None,
None
)
def insert_cef_alerts_command(client, args):
# parsing alerts list. the reason we don't use argToList is because cef_alerts could contain comma (,) so
# we shouldn't split them by comma
alerts = args.get('cef_alerts')
if isinstance(alerts, list):
pass
elif isinstance(alerts, str):
alerts = json.loads(alerts) if alerts[0] == "[" and alerts[-1] == "]" else [alerts]
else:
raise ValueError('Invalid argument "cef_alerts". It should be either list of strings (cef alerts), '
'or single string')
client.insert_cef_alerts(alerts)
return (
'Alerts inserted successfully',
None,
None
)
def sort_all_list_incident_fields(incident_data):
"""Sorting all lists fields in an incident - without this, elements may shift which results in false
identification of changed fields"""
if incident_data.get('hosts', []):
incident_data['hosts'] = sorted(incident_data.get('hosts', []))
incident_data['hosts'] = [host.upper() for host in incident_data.get('hosts', [])]
if incident_data.get('users', []):
incident_data['users'] = sorted(incident_data.get('users', []))
incident_data['users'] = [user.upper() for user in incident_data.get('users', [])]
if incident_data.get('incident_sources', []):
incident_data['incident_sources'] = sorted(incident_data.get('incident_sources', []))
format_sublists = not argToBoolean(demisto.params().get('dont_format_sublists', False))
if incident_data.get('alerts', []):
incident_data['alerts'] = sort_by_key(incident_data.get('alerts', []), main_key='alert_id', fallback_key='name')
if format_sublists:
reformat_sublist_fields(incident_data['alerts'])
if incident_data.get('file_artifacts', []):
incident_data['file_artifacts'] = sort_by_key(incident_data.get('file_artifacts', []), main_key='file_name',
fallback_key='file_sha256')
if format_sublists:
reformat_sublist_fields(incident_data['file_artifacts'])
if incident_data.get('network_artifacts', []):
incident_data['network_artifacts'] = sort_by_key(incident_data.get('network_artifacts', []),
main_key='network_domain', fallback_key='network_remote_ip')
if format_sublists:
reformat_sublist_fields(incident_data['network_artifacts'])
def sync_incoming_incident_owners(incident_data):
if incident_data.get('assigned_user_mail') and demisto.params().get('sync_owners'):
user_info = demisto.findUser(email=incident_data.get('assigned_user_mail'))
if user_info:
demisto.debug(f"Syncing incident owners: XDR incident {incident_data.get('incident_id')}, "
f"owner {user_info.get('username')}")
incident_data['owner'] = user_info.get('username')
else:
demisto.debug(f"The user assigned to XDR incident {incident_data.get('incident_id')} "
f"is not registered on XSOAR")
def handle_incoming_user_unassignment(incident_data):
incident_data['assigned_user_mail'] = ''
incident_data['assigned_user_pretty_name'] = ''
if demisto.params().get('sync_owners'):
demisto.debug(f'Unassigning owner from XDR incident {incident_data.get("incident_id")}')
incident_data['owner'] = ''
def handle_incoming_closing_incident(incident_data):
incident_id = incident_data.get('incident_id')
demisto.debug(f'handle_incoming_closing_incident {incident_data=} {incident_id=}')
closing_entry = {} # type: Dict
if incident_data.get('status') in XDR_RESOLVED_STATUS_TO_XSOAR:
demisto.debug(f"handle_incoming_closing_incident {incident_data.get('status')=} {incident_id=}")
demisto.debug(f"Closing XDR issue {incident_id=}")
closing_entry = {
'Type': EntryType.NOTE,
'Contents': {
'dbotIncidentClose': True,
'closeReason': XDR_RESOLVED_STATUS_TO_XSOAR.get(incident_data.get("status")),
'closeNotes': incident_data.get('resolve_comment', '')
},
'ContentsFormat': EntryFormat.JSON
}
incident_data['closeReason'] = closing_entry['Contents']['closeReason']
incident_data['closeNotes'] = closing_entry['Contents']['closeNotes']
demisto.debug(f"handle_incoming_closing_incident {incident_id=} {incident_data['closeReason']=} "
f"{incident_data['closeNotes']=}")
if incident_data.get('status') == 'resolved_known_issue':
close_notes = f'Known Issue.\n{incident_data.get("closeNotes", "")}'
closing_entry['Contents']['closeNotes'] = close_notes
incident_data['closeNotes'] = close_notes
demisto.debug(f"handle_incoming_closing_incident {incident_id=} {close_notes=}")
return closing_entry
def get_mapping_fields_command():
xdr_incident_type_scheme = SchemeTypeMapping(type_name=XDR_INCIDENT_TYPE_NAME)
for field in XDR_INCIDENT_FIELDS:
xdr_incident_type_scheme.add_field(name=field, description=XDR_INCIDENT_FIELDS[field].get('description'))
mapping_response = GetMappingFieldsResponse()
mapping_response.add_scheme_type(xdr_incident_type_scheme)
return mapping_response
def get_modified_remote_data_command(client, args):
remote_args = GetModifiedRemoteDataArgs(args)
last_update = remote_args.last_update # In the first run, this value will be set to 1 minute earlier
demisto.debug(f'Performing get-modified-remote-data command. Last update is: {last_update}')
last_update_utc = dateparser.parse(last_update, settings={'TIMEZONE': 'UTC'}) # convert to utc format
if last_update_utc:
last_update_without_ms = last_update_utc.isoformat().split('.')[0]
raw_incidents = client.get_incidents(gte_modification_time=last_update_without_ms, limit=100)
modified_incident_ids = []
for raw_incident in raw_incidents:
incident_id = raw_incident.get('incident_id')
modified_incident_ids.append(incident_id)
return GetModifiedRemoteDataResponse(modified_incident_ids)
def get_remote_data_command(client, args):
remote_args = GetRemoteDataArgs(args)
demisto.debug(f'Performing get-remote-data command with incident id: {remote_args.remote_incident_id}')
incident_data = {}
try:
# when Demisto version is 6.1.0 and above, this command will only be automatically executed on incidents
# returned from get_modified_remote_data_command so we want to perform extra-data request on those incidents.
return_only_updated_incident = not is_demisto_version_ge('6.1.0') # True if version is below 6.1 else False
incident_data = get_incident_extra_data_command(client, {"incident_id": remote_args.remote_incident_id,
"alerts_limit": 1000,
"return_only_updated_incident": return_only_updated_incident,
"last_update": remote_args.last_update})
if 'The incident was not modified' not in incident_data[0]:
demisto.debug(f"Updating XDR incident {remote_args.remote_incident_id}")
incident_data = incident_data[2].get('incident')
incident_data['id'] = incident_data.get('incident_id')
sort_all_list_incident_fields(incident_data)
# deleting creation time as it keeps updating in the system
del incident_data['creation_time']
# handle unasignment
if incident_data.get('assigned_user_mail') is None:
handle_incoming_user_unassignment(incident_data)
else:
# handle owner sync
sync_incoming_incident_owners(incident_data)
# handle closed issue in XDR and handle outgoing error entry
entries = [handle_incoming_closing_incident(incident_data)]
reformatted_entries = []
for entry in entries:
if entry:
reformatted_entries.append(entry)
incident_data['in_mirror_error'] = ''
return GetRemoteDataResponse(
mirrored_object=incident_data,
entries=reformatted_entries
)
else: # no need to update this incident
incident_data = {
'id': remote_args.remote_incident_id,
'in_mirror_error': ""
}
return GetRemoteDataResponse(
mirrored_object=incident_data,
entries=[]
)
except Exception as e:
demisto.debug(f"Error in XDR incoming mirror for incident {remote_args.remote_incident_id} \n"
f"Error message: {str(e)}")
if "Rate limit exceeded" in str(e):
return_error("API rate limit")
if incident_data:
incident_data['in_mirror_error'] = str(e)
sort_all_list_incident_fields(incident_data)
# deleting creation time as it keeps updating in the system
del incident_data['creation_time']
else:
incident_data = {
'id': remote_args.remote_incident_id,
'in_mirror_error': str(e)
}
return GetRemoteDataResponse(
mirrored_object=incident_data,
entries=[]
)
def update_remote_system_command(client, args):
remote_args = UpdateRemoteSystemArgs(args)
incident_id = remote_args.remote_incident_id
demisto.debug(f"update_remote_system_command {incident_id=} {remote_args=}")
if remote_args.delta:
demisto.debug(f'Got the following delta keys {str(list(remote_args.delta.keys()))} to update'
f'incident {remote_args.remote_incident_id}')
demisto.debug(f'{remote_args.delta=}')
try:
if remote_args.incident_changed:
demisto.debug(f"update_remote_system_command {incident_id=} {remote_args.incident_changed=}")
update_args = get_update_args(remote_args)
update_args['incident_id'] = remote_args.remote_incident_id
demisto.debug(f'Sending incident with remote ID [{remote_args.remote_incident_id}]\n')
update_incident_command(client, update_args)
else:
demisto.debug(f'Skipping updating remote incident fields [{remote_args.remote_incident_id}] '
f'as it is not new nor changed')
return remote_args.remote_incident_id
except Exception as e:
demisto.debug(f"Error in outgoing mirror for incident {remote_args.remote_incident_id} \n"
f"Error message: {str(e)}")
return remote_args.remote_incident_id
def create_incidents_dictionary(incidents_data: List[Dict[str, Any]]) -> Dict[str, Any]:
"""creating a dictionary of incidents data according to the old extra data api format
fields in a dictionary format for easy access later
Args:
incidents_data (dict): incidents multiple extra data retrieved by the upgraded api
Returns:
dict: dictionary of incidents data
"""
result = {}
for incident_data in incidents_data:
incident_id = incident_data.get('incident', {}).get('incident_id')
hosts = incident_data.get('incident', {}).get('hosts')
users = incident_data.get('incident', {}).get('users')
incident_sources = incident_data.get('incident', {}).get('incident_sources')
alerts = incident_data.get('alerts', {}).get('data')
file_artifacts = incident_data.get('file_artifacts', {}).get('data')
network_artifacts = incident_data.get('network_artifacts', {}).get('data')
result[incident_id] = {
'incident': incident_data.get('incident', {}),
'hosts': hosts,
'users': users,
'incident_sources': incident_sources,
'alerts': alerts,
'file_artifacts': file_artifacts,
'network_artifacts': network_artifacts
}
return result
def fetch_incidents(client, first_fetch_time, integration_instance, last_run: dict = None, max_fetch: int = 10,
statuses: List = [], starred: Optional[bool] = None, starred_incidents_fetch_window: str = None,
fields_to_exclude: List = []):
global ALERTS_LIMIT_PER_INCIDENTS
# Get the last fetch time, if exists
last_fetch = last_run.get('time') if isinstance(last_run, dict) else None
incidents_from_previous_run = last_run.get('incidents_from_previous_run', []) if isinstance(last_run,
dict) else []
# Handle first time fetch, fetch incidents retroactively
if last_fetch is None:
last_fetch, _ = parse_date_range(first_fetch_time, to_timestamp=True)
if starred:
starred_incidents_fetch_window, _ = parse_date_range(starred_incidents_fetch_window, to_timestamp=True)
incidents = []
if incidents_from_previous_run:
raw_incidents = incidents_from_previous_run
else:
if statuses:
raw_incidents = []
for status in statuses:
raw_incidents += client.get_multiple_incidents_extra_data(gte_creation_time_milliseconds=last_fetch, status=status,
limit=max_fetch, starred=starred,
starred_incidents_fetch_window=starred_incidents_fetch_window)
raw_incidents = sorted(raw_incidents, key=lambda inc: inc['creation_time'])
else:
raw_incidents = client.get_multiple_incidents_extra_data(gte_creation_time_milliseconds=last_fetch, limit=max_fetch,
starred=starred,
starred_incidents_fetch_window=starred_incidents_fetch_window)
# save the last 100 modified incidents to the integration context - for mirroring purposes
client.save_modified_incidents_to_integration_context()
# maintain a list of non created incidents in a case of a rate limit exception
non_created_incidents: list = raw_incidents.copy()
next_run = {}
try:
count_incidents = 0
for raw_incident in raw_incidents:
incident_id = raw_incident.get('incident_id')
incident_data: dict[str, Any] = raw_incident.get('incident', {})
alert_count = arg_to_number(raw_incident.get('incident', {}).get('alert_count')) or 0
if alert_count > ALERTS_LIMIT_PER_INCIDENTS:
incident_data = get_incident_extra_data_command(client, {"incident_id": incident_id,
"alerts_limit": 1000})[2].get('incident') or {}
sort_all_list_incident_fields(incident_data)
incident_data['mirror_direction'] = MIRROR_DIRECTION.get(demisto.params().get('mirror_direction', 'None'),
None)
incident_data['mirror_instance'] = integration_instance
incident_data['last_mirrored_in'] = int(datetime.now().timestamp() * 1000)
demisto.debug(f'incident_data{incident_data}')
description = raw_incident.get('description')
occurred = timestamp_to_datestring(incident_data['creation_time'], TIME_FORMAT + 'Z')
incident: Dict[str, Any] = {
'name': f'XDR Incident {incident_id} - {description}',
'occurred': occurred,
'rawJSON': json.dumps(incident_data),
}
if demisto.params().get('sync_owners') and incident_data.get('assigned_user_mail'):
incident['owner'] = demisto.findUser(email=incident_data.get('assigned_user_mail')).get('username')
# Update last run and add incident if the incident is newer than last fetch
if incident_data['creation_time'] > last_fetch:
last_fetch = incident_data['creation_time']
incidents.append(incident)
non_created_incidents.remove(raw_incident)
count_incidents += 1
if count_incidents == max_fetch:
break
except Exception as e:
if "Rate limit exceeded" in str(e):
demisto.info(f"Cortex XDR - rate limit exceeded, number of non created incidents is: "
f"'{len(non_created_incidents)}'.\n The incidents will be created in the next fetch")
else:
raise
if non_created_incidents:
next_run['incidents_from_previous_run'] = non_created_incidents
else:
next_run['incidents_from_previous_run'] = []
next_run['time'] = last_fetch + 1
return next_run, incidents
def get_endpoints_by_status_command(client: Client, args: Dict) -> CommandResults:
status = args.get('status')
status = argToList(status)
last_seen_gte = arg_to_timestamp(
arg=args.get('last_seen_gte'),
arg_name='last_seen_gte'
)