/
CrowdStrikeFalcon.py
5765 lines (4787 loc) · 229 KB
/
CrowdStrikeFalcon.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
''' IMPORTS '''
import base64
import email
import hashlib
import json
from enum import Enum
from threading import Timer
from collections.abc import Callable
from typing import Any
import requests
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport
# Disable insecure warnings
import urllib3
urllib3.disable_warnings()
''' GLOBALS/PARAMS '''
INTEGRATION_NAME = 'CrowdStrike Falcon'
IDP_DETECTION = "IDP detection"
CLIENT_ID = demisto.params().get('credentials', {}).get('identifier') or demisto.params().get('client_id')
SECRET = demisto.params().get('credentials', {}).get('password') or demisto.params().get('secret')
# Remove trailing slash to prevent wrong URL path to service
SERVER = demisto.params()['url'][:-1] if (demisto.params()['url'] and demisto.params()['url'].endswith('/')) else \
demisto.params()['url']
# Should we use SSL
USE_SSL = not demisto.params().get('insecure', False)
# How many time before the first fetch to retrieve incidents
FETCH_TIME = demisto.params().get('fetch_time', '3 days')
BYTE_CREDS = f'{CLIENT_ID}:{SECRET}'.encode()
# Headers to be sent in requests
HEADERS = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'Basic {base64.b64encode(BYTE_CREDS).decode()}'
}
# Note: True life time of token is actually 30 mins
TOKEN_LIFE_TIME = 28
INCIDENTS_PER_FETCH = int(demisto.params().get('incidents_per_fetch', 15))
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
IDP_DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
DEFAULT_TIMEOUT = 30
# Remove proxy if not set to true in params
handle_proxy()
''' KEY DICTIONARY '''
DETECTIONS_BASE_KEY_MAP = {
'device.hostname': 'System',
'device.cid': 'CustomerID',
'hostinfo.domain': 'MachineDomain',
'detection_id': 'ID',
'created_timestamp': 'ProcessStartTime',
'max_severity': 'MaxSeverity',
'show_in_ui': 'ShowInUi',
'status': 'Status',
'first_behavior': 'FirstBehavior',
'last_behavior': 'LastBehavior',
'max_confidence': 'MaxConfidence',
}
DETECTIONS_BEHAVIORS_KEY_MAP = {
'filename': 'FileName',
'scenario': 'Scenario',
'md5': 'MD5',
'sha256': 'SHA256',
'ioc_type': 'IOCType',
'ioc_value': 'IOCValue',
'cmdline': 'CommandLine',
'user_name': 'UserName',
'behavior_id': 'ID',
'alleged_filetype': 'AllegedFiletype',
'confidence': 'Confidence',
'description': 'Description',
'display_name': 'DisplayName',
'filepath': 'Filepath',
'parent_md5': 'ParentMD5',
'parent_sha256': 'ParentSHA256',
'pattern_disposition': 'PatternDisposition',
'pattern_disposition_details': 'PatternDispositionDetails',
'tactic': 'Tactic',
'tactic_id': 'TacticID',
'technique': 'Technique',
'technique_id': 'TechniqueId',
}
IOC_KEY_MAP = {
'type': 'Type',
'value': 'Value',
'policy': 'Policy',
'source': 'Source',
'share_level': 'ShareLevel',
'expiration': 'Expiration',
'description': 'Description',
'created_on': 'CreatedTime',
'created_by': 'CreatedBy',
'modified_on': 'ModifiedTime',
'modified_by': 'ModifiedBy',
'id': 'ID',
'platforms': 'Platforms',
'action': 'Action',
'severity': 'Severity',
'tags': 'Tags',
}
IOC_HEADERS = ['ID', 'Action', 'Severity', 'Type', 'Value', 'Expiration', 'CreatedBy', 'CreatedTime', 'Description',
'ModifiedBy', 'ModifiedTime', 'Platforms', 'Policy', 'ShareLevel', 'Source', 'Tags']
IOC_DEVICE_COUNT_MAP = {
'id': 'ID',
'type': 'Type',
'value': 'Value',
'device_count': 'DeviceCount'
}
SEARCH_DEVICE_KEY_MAP = {
'device_id': 'ID',
'external_ip': 'ExternalIP',
'local_ip': 'LocalIP',
'hostname': 'Hostname',
'os_version': 'OS',
'mac_address': 'MacAddress',
'first_seen': 'FirstSeen',
'last_seen': 'LastSeen',
'status': 'Status',
}
SEARCH_DEVICE_VERBOSE_KEY_MAP = {
'agent_load_flags': 'AgentLoadFlags',
'agent_local_time': 'AgentLocalTime',
'agent_version': 'AgentVersion',
'bios_manufacturer': 'BiosManufacturer',
'bios_version': 'BiosVersion',
'cid': 'CID',
'config_id_base': 'ConfigIdBase',
'config_id_build': 'ConfigIdBuild',
'config_id_platform': 'ConfigIdPlatform',
'connection_ip': 'ConnectionIp',
'connection_mac_address': 'ConnectionMacAddress',
'cpu_signature': 'CpuSignature',
'default_gateway_ip': 'DefaultGatewayIP',
'device_id': 'ID',
'device_policies': 'DevicePolicies',
'external_ip': 'ExternalIP',
'first_seen': 'FirstSeen',
'group_hash': 'GroupHash',
'group_name': 'GroupName',
'group_names': 'GroupNames',
'groups': 'Groups',
'hostname': 'Hostname',
'kernel_version': 'KernelVersion',
'last_seen': 'LastSeen',
'local_ip': 'LocalIP',
'mac_address': 'MacAddress',
'major_version': 'MajorVersion',
'meta': 'Meta',
'minor_version': 'MinorVersion',
'modified_timestamp': 'ModifiedTimestamp',
'os_version': 'OS',
'platform_id': 'PlatformID',
'platform_name': 'PlatformName',
'policies': 'Policies',
'product_type_desc': 'ProductTypeDesc',
'provision_status': 'ProvisionStatus',
'reduced_functionality_mode': 'ReducedFunctionalityMode',
'serial_number': 'SerialNumber',
'status': 'Status',
'system_manufacturer': 'SystemManufacturer',
'system_product_name': 'SystemProductName',
'tags': 'Tags'
}
ENDPOINT_KEY_MAP = {
'device_id': 'ID',
'local_ip': 'IPAddress',
'os_version': 'OS',
'hostname': 'Hostname',
'status': 'Status',
}
''' SPLIT KEY DICTIONARY '''
"""
Pattern:
{
'Path': 'Path to item',
'NewKey': 'Value of output key',
'Delim': 'Delimiter char',
'Index': Split Array Index
}
"""
DETECTIONS_BEHAVIORS_SPLIT_KEY_MAP = [
{
'Path': 'parent_details.parent_process_graph_id',
'NewKey': 'SensorID',
'Delim': ':',
'Index': 1
},
{
'Path': 'parent_details.parent_process_graph_id',
'NewKey': 'ParentProcessID',
'Delim': ':',
'Index': 2
},
{
'Path': 'triggering_process_graph_id',
'NewKey': 'ProcessID',
'Delim': ':',
'Index': 2
},
]
HOST_GROUP_HEADERS = ['id', 'name', 'group_type', 'description', 'assignment_rule',
'created_by', 'created_timestamp',
'modified_by', 'modified_timestamp']
STATUS_TEXT_TO_NUM = {'New': "20",
'Reopened': "25",
'In Progress': "30",
'Closed': "40"}
STATUS_NUM_TO_TEXT = {20: 'New',
25: 'Reopened',
30: 'In Progress',
40: 'Closed'}
''' MIRRORING DICTIONARIES & PARAMS '''
DETECTION_STATUS = {'new', 'in_progress', 'true_positive', 'false_positive', 'ignored', 'closed', 'reopened'}
IDP_DETECTION_STATUS = {'new', 'in_progress', 'closed', 'reopened'}
CS_FALCON_DETECTION_OUTGOING_ARGS = {'status': f'Updated detection status, one of {"/".join(DETECTION_STATUS)}'}
CS_FALCON_INCIDENT_OUTGOING_ARGS = {'tag': 'A tag that have been added or removed from the incident',
'status': f'Updated incident status, one of {"/".join(STATUS_TEXT_TO_NUM.keys())}'}
CS_FALCON_DETECTION_INCOMING_ARGS = ['status', 'severity', 'behaviors.tactic', 'behaviors.scenario', 'behaviors.objective',
'behaviors.technique', 'device.hostname']
CS_FALCON_INCIDENT_INCOMING_ARGS = ['state', 'status', 'tactics', 'techniques', 'objectives', 'tags', 'hosts.hostname']
MIRROR_DIRECTION_DICT = {
'None': None,
'Incoming': 'In',
'Outgoing': 'Out',
'Incoming And Outgoing': 'Both'
}
HOST_STATUS_DICT = {
'online': 'Online',
'offline': 'Offline',
'unknown': 'Unknown'
}
CPU_UTILITY_INT_TO_STR_KEY_MAP = {
1: 'Lowest',
2: 'Low',
3: 'Medium',
4: 'High',
5: 'Highest',
}
CPU_UTILITY_STR_TO_INT_KEY_MAP = {
value: key for key, value in CPU_UTILITY_INT_TO_STR_KEY_MAP.items()}
SCHEDULE_INTERVAL_STR_TO_INT = {
'never': 0,
'daily': 1,
'weekly': 7,
'every other week': 14,
'every four weeks': 28,
'monthly': 30,
}
class IncidentType(Enum):
INCIDENT = 'inc'
DETECTION = 'ldt'
IDP_DETECTION = ':ind:'
MIRROR_DIRECTION = MIRROR_DIRECTION_DICT.get(demisto.params().get('mirror_direction'))
INTEGRATION_INSTANCE = demisto.integrationInstance()
''' HELPER FUNCTIONS '''
def http_request(method, url_suffix, params=None, data=None, files=None, headers=HEADERS, safe=False,
get_token_flag=True, no_json=False, json=None, status_code=None, timeout=None):
"""
A wrapper for requests lib to send our requests and handle requests and responses better.
:param json: JSON body
:type json ``dict`` or ``list``
:type method: ``str``
:param method: HTTP method for the request.
:type url_suffix: ``str``
:param url_suffix: The suffix of the URL (endpoint)
:type params: ``dict``
:param params: The URL params to be passed.
:type data: ``str``
:param data: The body data of the request.
:type headers: ``dict``
:param headers: Request headers
:type safe: ``bool``
:param safe: If set to true will return None in case of http error
:type get_token_flag: ``bool``
:param get_token_flag: If set to True will call get_token()
:type no_json: ``bool``
:param no_json: If set to true will not parse the content and will return the raw response object for successful
response
:type status_code: ``int``
:param: status_code: The request codes to accept as OK.
:type timeout: ``float``
:param: timeout: The timeout for the request.
:return: Returns the http request response json
:rtype: ``dict``
"""
if get_token_flag:
token = get_token()
headers['Authorization'] = f'Bearer {token}'
url = SERVER + url_suffix
headers['User-Agent'] = 'PANW-XSOAR'
try:
res = requests.request(
method,
url,
verify=USE_SSL,
params=params,
data=data,
headers=headers,
files=files,
json=json,
timeout=timeout,
)
except requests.exceptions.RequestException as e:
return_error(f'Error in connection to the server. Please make sure you entered the URL correctly.'
f' Exception is {str(e)}.')
try:
valid_status_codes = {200, 201, 202, 204}
# Handling a case when we want to return an entry for 404 status code.
if status_code:
valid_status_codes.add(status_code)
if res.status_code not in valid_status_codes:
res_json = res.json()
reason = res.reason
resources = res_json.get('resources', {})
if resources:
if isinstance(resources, list):
reason += f'\n{str(resources)}'
else:
for host_id, resource in resources.items():
errors = resource.get('errors', [])
if errors:
error_message = errors[0].get('message')
reason += f'\nHost ID {host_id} - {error_message}'
elif res_json.get('errors'):
errors = res_json.get('errors', [])
for error in errors:
reason += f"\n{error.get('message')}"
err_msg = 'Error in API call to CrowdStrike Falcon: code: {code} - reason: {reason}'.format(
code=res.status_code,
reason=reason
)
# try to create a new token
if res.status_code in (401, 403) and get_token_flag:
LOG(err_msg)
token = get_token(new_token=True)
headers['Authorization'] = f'Bearer {token}'
return http_request(
method=method,
url_suffix=url_suffix,
params=params,
data=data,
headers=headers,
files=files,
json=json,
safe=safe,
get_token_flag=False,
status_code=status_code,
no_json=no_json,
timeout=timeout,
)
elif safe:
return None
raise DemistoException(err_msg)
return res if no_json else res.json()
except ValueError as exception:
raise ValueError(
f'Failed to parse json object from response: {exception} - {res.content}') # type: ignore[str-bytes-safe]
def create_relationships(cve: dict) -> list:
"""
creates relationships between the cve and each actor from 'actors' field
: args: cve contains the cve id and the actors field if it is exists.
: return: a list of relationships by type THREAT_ACTOR.
"""
list_with_actors_field = []
if not cve.get('actors'):
return []
for actor in cve.get('actors', {}):
list_with_actors_field.append(actor)
relationships_list: list[EntityRelationship] = []
# need to create entity
for entity_b in list_with_actors_field:
relationships_list.append(EntityRelationship(entity_a=cve.get('id'),
entity_a_type=FeedIndicatorType.CVE,
name=EntityRelationship.Relationships.TARGETED_BY,
entity_b=entity_b,
entity_b_type=ThreatIntel.ObjectsNames.THREAT_ACTOR,
brand=INTEGRATION_NAME,
reverse_name=EntityRelationship.Relationships.TARGETS))
return relationships_list
def create_dbot_Score(cve: dict, reliability: str) -> Common.DBotScore:
"""
Creates DBotScore CVE indicator, for get_cve_command.
"""
return Common.DBotScore(indicator=cve.get('id'),
indicator_type=DBotScoreType.CVE,
integration_name=INTEGRATION_NAME,
score=Common.DBotScore.NONE,
reliability=reliability)
def create_publications(cve: dict) -> list:
"""
Creates publications list from CVE, while using get_cve_command.
"""
publications = []
if cve.get('references'):
for reference in cve.get('references', {}):
publications.append(Common.Publications(title='references', link=reference))
if cve.get('vendor_advisory'):
for vendor_advisory in cve.get('vendor_advisory', {}):
publications.append(Common.Publications(title='vendor_advisory', link=vendor_advisory))
return publications
def build_query_params(query_params: dict) -> str:
"""
Gets a dict of {property: value} and return a string to use as a query param in the requests of exclusion entities.
For example: {'name': 'test', 'os_name': 'WINDOWS'} => '?name=test+os_name=WINDOWS'
Args:
query_params: dict of exclusion property: value.
Returns:
String to use as a query param in the requests of exclusion.
"""
query = ''
for key, value in query_params.items():
if query:
query += '+'
query += f"{key}:'{value}'"
return query
''' API FUNCTIONS '''
def create_entry_object(contents: list[Any] | dict[str, Any] = {}, ec: list[Any] | dict[str, Any] | None = None,
hr: str = ''):
"""
Creates an entry object
:type contents: ``dict``
:param contents: Raw response to output
:type ec: ``dict``
:param ec: Entry context of the entry object
:type hr: ``str``
:param hr: Human readable
:return: Entry object
:rtype: ``dict``
"""
return {
'Type': entryTypes['note'],
'Contents': contents,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': hr,
'EntryContext': ec
}
def add_mirroring_fields(incident: dict):
"""
Updates the given incident to hold the needed mirroring fields.
"""
incident['mirror_direction'] = MIRROR_DIRECTION
incident['mirror_instance'] = INTEGRATION_INSTANCE
def detection_to_incident(detection):
"""
Creates an incident of a detection.
:type detection: ``dict``
:param detection: Single detection object
:return: Incident representation of a detection
:rtype ``dict``
"""
add_mirroring_fields(detection)
incident = {
'name': 'Detection ID: ' + str(detection.get('detection_id')),
'occurred': str(detection.get('first_behavior')),
'rawJSON': json.dumps(detection),
'severity': severity_string_to_int(detection.get('max_severity_displayname'))
}
return incident
def incident_to_incident_context(incident):
"""
Creates an incident context of a incident.
:type incident: ``dict``
:param incident: Single detection object
:return: Incident context representation of a incident
:rtype ``dict``
"""
add_mirroring_fields(incident)
if incident.get('status'):
incident['status'] = STATUS_NUM_TO_TEXT.get(incident.get('status'))
incident_id = str(incident.get('incident_id'))
incident_context = {
'name': f'Incident ID: {incident_id}',
'occurred': str(incident.get('start')),
'rawJSON': json.dumps(incident)
}
return incident_context
def idp_detection_to_incident_context(idp_detection):
"""
Creates an incident context of an IDP detection.
:type idp_detection: ``dict``
:param idp_detection: Single IDP detection object
:return: Incident context representation of an IDP detection.
:rtype ``dict``
"""
add_mirroring_fields(idp_detection)
if status := idp_detection.get('status'):
idp_detection['status'] = status
incident_context = {
'name': f'IDP Detection ID: {idp_detection.get("composite_id")}',
'occurred': idp_detection.get('start_time'),
'last_updated': idp_detection.get('updated_timestamp'),
'rawJSON': json.dumps(idp_detection)
}
return incident_context
def severity_string_to_int(severity):
"""
Converts a severity string to DBot score representation
:type severity: ``str``
:param severity: String representation of a severity
:return: DBot score representation of the severity
:rtype ``int``
"""
if severity in ('Critical', 'High'):
return 3
elif severity in ('Medium', 'Low'):
return 2
return 0
def get_trasnformed_dict(old_dict, transformation_dict):
"""
Returns a dictionary with the same values as old_dict, with the correlating key:value in transformation_dict
:type old_dict: ``dict``
:param old_dict: Old dictionary to pull values from
:type transformation_dict: ``dict``
:param transformation_dict: Transformation dictionary that contains oldkeys:newkeys
:return Transformed dictionart (according to transformation_dict values)
:rtype ``dict``
"""
new_dict = {}
for k in list(old_dict.keys()):
if k in transformation_dict:
new_dict[transformation_dict[k]] = old_dict[k]
return new_dict
def extract_transformed_dict_with_split(old_dict, transformation_dict_arr):
"""
Extracts new values out of old_dict using a json structure of:
{'Path': 'Path to item', 'NewKey': 'Value of output key', 'Delim': 'Delimiter char', 'Index': Split Array Index}
"""
new_dict = {}
for trans_dict in transformation_dict_arr:
try:
val = demisto.get(old_dict, trans_dict['Path'])
if 'split' in dir(val):
i = trans_dict['Index']
new_dict[trans_dict['NewKey']] = val.split(trans_dict['Delim'])[i]
except Exception as ex:
LOG(f'Error {ex} with: {trans_dict}')
return new_dict
def get_passed_mins(start_time, end_time_str):
"""
Returns the time passed in mins
:param start_time: Start time in datetime
:param end_time_str: End time in str
:return: The passed mins in int
"""
time_delta = start_time - datetime.fromtimestamp(end_time_str)
return time_delta.seconds / 60
def handle_response_errors(raw_res: dict, err_msg: str | None = None):
"""
Raise exception if raw_res is empty or contains errors
"""
if not err_msg:
err_msg = "The server was unable to return a result, please run the command again."
if not raw_res:
raise DemistoException(err_msg)
if raw_res.get('errors'):
raise DemistoException(raw_res.get('errors'))
def create_json_iocs_list(
ioc_type: str,
iocs_value: list[str],
action: str,
platforms: list[str],
severity: str | None = None,
source: str | None = None,
description: str | None = None,
expiration: str | None = None,
applied_globally: bool | None = None,
host_groups: list[str] | None = None,
tags: list[str] | None = None) -> list[dict]:
"""
Get a list of iocs values and create a list of Json objects with the iocs data.
This function is used for uploading multiple indicator with same arguments with different values.
:param ioc_type: The type of the indicator.
:param iocs_value: List of the indicator.
:param action: Action to take when a host observes the custom IOC.
:param platforms: The platforms that the indicator applies to.
:param severity: The severity level to apply to this indicator.
:param source: The source where this indicator originated.
:param description: A meaningful description of the indicator.
:param expiration: The date on which the indicator will become inactive.
:param applied_globally: Whether the indicator is applied globally.
:param host_groups: List of host group IDs that the indicator applies to.
:param tags: List of tags to apply to the indicator.
"""
iocs_list = []
for ioc_value in iocs_value:
iocs_list.append(assign_params(
type=ioc_type,
value=ioc_value,
action=action,
platforms=platforms,
severity=severity,
source=source,
description=description,
expiration=expiration,
applied_globally=applied_globally,
host_groups=host_groups,
tags=tags,
))
return iocs_list
''' COMMAND SPECIFIC FUNCTIONS '''
def init_rtr_single_session(host_id: str, queue_offline: bool = False) -> str:
"""
Start a session with single host.
:param host_id: Host agent ID to initialize a RTR session on.
:return: The session ID to execute the command on
"""
endpoint_url = '/real-time-response/entities/sessions/v1'
body = json.dumps({
'device_id': host_id,
'queue_offline': queue_offline
})
response = http_request('POST', endpoint_url, data=body)
resources = response.get('resources')
if resources and isinstance(resources, list) and isinstance(resources[0], dict):
session_id = resources[0].get('session_id')
if isinstance(session_id, str):
return session_id
raise ValueError('No session id found in the response')
def init_rtr_batch_session(host_ids: list, offline=False) -> str:
"""
Start a session with one or more hosts
:param host_ids: List of host agent ID’s to initialize a RTR session on.
:return: The session batch ID to execute the command on
"""
endpoint_url = '/real-time-response/combined/batch-init-session/v1'
body = json.dumps({
'host_ids': host_ids,
'queue_offline': offline
})
response = http_request('POST', endpoint_url, data=body)
return response.get('batch_id')
def refresh_session(host_id: str) -> dict:
"""
Refresh a session timeout on a single host.
:param host_id: Host agent ID to run RTR command on.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/entities/refresh-session/v1'
body = json.dumps({
'device_id': host_id
})
response = http_request('POST', endpoint_url, data=body)
return response
def batch_refresh_session(batch_id: str) -> None:
"""
Batch refresh a RTR session on multiple hosts.
:param batch_id: Batch ID to execute the command on.
"""
demisto.debug('Starting session refresh')
endpoint_url = '/real-time-response/combined/batch-refresh-session/v1'
body = json.dumps({
'batch_id': batch_id
})
response = http_request('POST', endpoint_url, data=body)
demisto.debug(f'Refresh session response: {response}')
demisto.debug('Finished session refresh')
def run_batch_read_cmd(batch_id: str, command_type: str, full_command: str, timeout: int = 30) -> dict:
"""
Sends RTR command scope with read access
:param batch_id: Batch ID to execute the command on.
:param command_type: Read-only command type we are going to execute, for example: ls or cd.
:param full_command: Full command string for the command.
:param timeout: The timeout for the request.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/combined/batch-command/v1'
body = json.dumps({
'base_command': command_type,
'batch_id': batch_id,
'command_string': full_command
})
params = {
'timeout': timeout
}
response = http_request('POST', endpoint_url, data=body, params=params, timeout=timeout)
return response
def run_batch_write_cmd(batch_id: str, command_type: str, full_command: str, optional_hosts: list | None = None,
timeout: int = DEFAULT_TIMEOUT) -> dict:
"""
Sends RTR command scope with write access
:param batch_id: Batch ID to execute the command on.
:param command_type: Read-only command type we are going to execute, for example: ls or cd.
:param full_command: Full command string for the command.
:param optional_hosts: The hosts ids to run the command on.
:param timeout: The timeout for the request.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/combined/batch-active-responder-command/v1'
default_body = {
'base_command': command_type,
'batch_id': batch_id,
'command_string': full_command
}
params = {
'timeout': timeout if timeout else DEFAULT_TIMEOUT
}
if optional_hosts:
default_body['optional_hosts'] = optional_hosts # type:ignore
body = json.dumps(default_body)
response = http_request('POST', endpoint_url, data=body, timeout=timeout, params=params)
return response
def run_batch_admin_cmd(batch_id: str, command_type: str, full_command: str, timeout: int = 30,
optional_hosts: list | None = None) -> dict:
"""
Sends RTR command scope with write access
:param batch_id: Batch ID to execute the command on.
:param command_type: Read-only command type we are going to execute, for example: ls or cd.
:param full_command: Full command string for the command.
:param timeout: Timeout for how long to wait for the request in seconds.
:param optional_hosts: The hosts ids to run the command on.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/combined/batch-admin-command/v1'
params = {
'timeout': timeout
}
default_body = {
'base_command': command_type,
'batch_id': batch_id,
'command_string': full_command
}
if optional_hosts:
default_body['optional_hosts'] = optional_hosts # type:ignore
body = json.dumps(default_body)
response = http_request('POST', endpoint_url, data=body, params=params, timeout=timeout)
return response
def run_batch_get_cmd(host_ids: list, file_path: str, optional_hosts: list | None = None, timeout: int | None = None,
timeout_duration: str | None = None, offline: bool = False) -> dict:
"""
Batch executes `get` command across hosts to retrieve files.
After this call is made `/real-time-response/combined/batch-get-command/v1` is used to query for the results.
:param host_ids: List of host agent ID’s to run RTR command on.
:param file_path: Full path to the file that is to be retrieved from each host in the batch.
:param optional_hosts: List of a subset of hosts we want to run the command on.
If this list is supplied, only these hosts will receive the command.
:param timeout: Timeout for how long to wait for the request in seconds
:param timeout_duration: Timeout duration for for how long to wait for the request in duration syntax
:param offline: Whether the command will run against an offline-queued session for execution when the host comes online.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/combined/batch-get-command/v1'
batch_id = init_rtr_batch_session(host_ids, offline)
body = assign_params(batch_id=batch_id, file_path=f'"{file_path}"', optional_hosts=optional_hosts)
params = assign_params(timeout=timeout, timeout_duration=timeout_duration)
response = http_request('POST', endpoint_url, data=json.dumps(body), params=params)
return response
def status_get_cmd(request_id: str, timeout: int | None = None, timeout_duration: str | None = None) -> dict:
"""
Retrieves the status of the specified batch get command. Will return successful files when they are finished processing.
:param request_id: ID to the request of `get` command.
:param timeout: Timeout for how long to wait for the request in seconds
:param timeout_duration: Timeout duration for how long to wait for the request in duration syntax
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/combined/batch-get-command/v1'
params = assign_params(timeout=timeout, timeout_duration=timeout_duration, batch_get_cmd_req_id=request_id)
response = http_request('GET', endpoint_url, params=params)
return response
def run_single_read_cmd(host_id: str, command_type: str, full_command: str, queue_offline: bool,
timeout: int = 30) -> dict:
"""
Sends RTR command scope with read access
:param host_id: Host agent ID to run RTR command on.
:param command_type: Active-Responder command type we are going to execute, for example: get or cp.
:param full_command: Full command string for the command.
:param queue_offline: Whether the command will run against an offline-queued session and be queued for execution
when the host comes online. # noqa: E501
:param timeout: The timeout for the request.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/entities/command/v1'
session_id = init_rtr_single_session(host_id, queue_offline)
body = json.dumps({
'base_command': command_type,
'command_string': full_command,
'session_id': session_id
})
params = {
'timeout': timeout
}
response = http_request('POST', endpoint_url, data=body, timeout=timeout, params=params)
return response
def run_single_write_cmd(host_id: str, command_type: str, full_command: str, queue_offline: bool,
timeout: int = 30) -> dict:
"""
Sends RTR command scope with write access
:param host_id: Host agent ID to run RTR command on.
:param command_type: Active-Responder command type we are going to execute, for example: get or cp.
:param full_command: Full command string for the command.
:param queue_offline: Whether the command will run against an offline-queued session and be queued for execution
when the host comes online. # noqa: E501
:param timeout: The timeout for the request.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/entities/active-responder-command/v1'
session_id = init_rtr_single_session(host_id, queue_offline)
body = json.dumps({
'base_command': command_type,
'command_string': full_command,
'session_id': session_id
})
params = {
'timeout': timeout
}
response = http_request('POST', endpoint_url, data=body, timeout=timeout, params=params)
return response
def run_single_admin_cmd(host_id: str, command_type: str, full_command: str, queue_offline: bool,
timeout: int = 30) -> dict:
"""
Sends RTR command scope with admin access
:param host_id: Host agent ID to run RTR command on.
:param command_type: Active-Responder command type we are going to execute, for example: get or cp.
:param full_command: Full command string for the command.
:param queue_offline: Whether the command will run against an offline-queued session and be queued for execution
when the host comes online. # noqa: E501
:param timeout: The timeout for the request.
:return: Response JSON which contains errors (if exist) and retrieved resources
"""
endpoint_url = '/real-time-response/entities/admin-command/v1'
session_id = init_rtr_single_session(host_id, queue_offline)
body = json.dumps({
'base_command': command_type,
'command_string': full_command,
'session_id': session_id
})
params = {
'timeout': timeout
}
response = http_request('POST', endpoint_url, data=body, timeout=timeout, params=params)
return response
def status_read_cmd(request_id: str, sequence_id: int | None) -> dict:
"""
Get status of an executed command with read access on a single host.
:param request_id: Cloud Request ID of the executed command to query
:param sequence_id: Sequence ID that we want to retrieve. Command responses are chunked across sequences
"""
endpoint_url = '/real-time-response/entities/command/v1'
params = {
'cloud_request_id': request_id,
'sequence_id': sequence_id or 0
}
response = http_request('GET', endpoint_url, params=params)
return response
def status_write_cmd(request_id: str, sequence_id: int | None) -> dict:
"""
Get status of an executed command with write access on a single host.