/
Cylance_Protect_v2.py
1638 lines (1341 loc) · 56.8 KB
/
Cylance_Protect_v2.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
from CommonServerPython import *
import jwt
import uuid
import requests
import urllib3
import json
import re
import zipfile
from io import BytesIO
from datetime import datetime, timedelta
# disable insecure warnings
urllib3.disable_warnings()
# CONSTANTS
TOKEN_TIMEOUT = 300 # 5 minutes
URI_AUTH = 'auth/v2/token'
URI_DEVICES = 'devices/v2'
URI_POLICIES = 'policies/v2'
URI_ZONES = 'zones/v2'
URI_THREATS = 'threats/v2'
URI_LISTS = 'globallists/v2'
URI_HOSTNAME = 'devices/v2/hostname'
URI_OPTICS = 'instaqueries/v2' # Optics InstaQuery API Endpoint
SCOPE_DEVICE_LIST = 'device:list'
SCOPE_DEVICE_READ = 'device:read'
SCOPE_DEVICE_UPDATE = 'device:update'
SCOPE_DEVICE_THREAT_LIST = 'device:threatlist'
SCOPE_POLICY_LIST = 'policy:list'
SCOPE_POLICY_READ = 'policy:read'
SCOPE_ZONE_CREATE = 'zone:create'
SCOPE_ZONE_LIST = 'zone:list'
SCOPE_ZONE_READ = 'zone:read'
SCOPE_ZONE_UPDATE = 'zone:update'
SCOPE_THREAT_READ = 'threat:read'
SCOPE_THREAT_DEVICE_LIST = 'threat:devicelist'
SCOPE_THREAT_UPDATE = 'threat:update'
SCOPE_GLOBAL_LIST = 'globallist:list'
SCOPE_THREAT_LIST = 'threat:list'
SCOPE_GLOBAL_LIST_CREATE = 'globallist:create'
SCOPE_GLOBAL_LIST_DELETE = 'globallist:delete'
SCOPE_OPTICS_LIST = 'opticssurvey:list' # Get InstaQueries
SCOPE_OPTICS_CREATE = 'opticssurvey:create' # Create InstaQuery
SCOPE_OPTICS_GET = 'opticssurvey:read' # Read a InstaQuery
# PREREQUISITES
def load_server_url(): # pragma: no cover
""" Cleans and loads the server url from the configuration """
url = demisto.params()['server']
url = re.sub(r'/[\/]+$/', '', url)
url = re.sub(r'\/$', '', url)
return url
# GLOBALS
APP_ID = ''
APP_SECRET = ''
TID = ''
SERVER_URL = ''
FILE_THRESHOLD = ''
USE_SSL = False
# HELPERS
def generate_jwt_times(): # pragma: no cover
"""
Generates the epoch time window in which the token will be valid
Returns the current timestamp and the timeout timestamp (in that order)
"""
now = datetime.utcnow()
timeout_datetime = now + timedelta(seconds=TOKEN_TIMEOUT)
epoch_time = int((now - datetime(1970, 1, 1)).total_seconds())
epoch_timeout = int((timeout_datetime - datetime(1970, 1, 1)).total_seconds())
return epoch_time, epoch_timeout
def api_call(uri, method='post', headers={}, body={}, params={}, accept_404=False, access_token=''): # pragma: no cover
"""
Makes an API call to the server URL with the supplied uri, method, headers, body and params
"""
if not headers:
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_token
}
url = '{}/{}'.format(SERVER_URL, uri)
res = requests.request(method, url, headers=headers, data=json.dumps(body), params=params, verify=USE_SSL)
if res.status_code < 200 or res.status_code >= 300:
if res.status_code == 409 and str(res.content).find('already an entry for this threat') != -1:
raise Warning(res.content)
if not res.status_code == 404 and not accept_404:
return_error(
'Got status code ' + str(res.status_code) + ' with body ' + str(res.content) + ' with headers ' + str(
res.headers))
return json.loads(res.text) if res.text else res.ok
def get_authentication_token(scope=None):
"""
Generates a JWT authorization token with an optional scope and queries the API for an access token
Returns the received API access token
"""
# Generate token ID
token_id = str(uuid.uuid4())
# Generate current time & token timeout
epoch_time, epoch_timeout = generate_jwt_times()
# Token claims
claims = {
'exp': epoch_timeout,
'iat': epoch_time,
'iss': 'http://cylance.com',
'sub': APP_ID,
'tid': TID,
'jti': token_id
}
if scope:
claims['scp'] = scope
# Encode the token
encoded = jwt.encode(claims, APP_SECRET, algorithm='HS256')
payload = {'auth_token': encoded}
headers = {'Content-Type': 'application/json; charset=utf-8'}
res = api_call(method='post', uri=URI_AUTH, body=payload, headers=headers)
return res['access_token']
def threat_to_incident(threat):
incident = {
'name': 'Cylance Protect v2 threat ' + threat['name'],
'occurred': threat['last_found'] + 'Z',
'rawJSON': json.dumps(threat)
}
host_name = None
devices = get_threat_devices_request(threat['sha256'], None, None)['page_items']
for device in devices:
if device['date_found'] == threat['last_found']:
host_name = device['name']
labels = [{'type': 'Classification', 'value': threat['classification']}, {'type': 'MD5', 'value': threat['md5']},
{'type': 'SHA256', 'value': threat['sha256']}, {'type': 'ThreatLastFound', 'value': threat['last_found']},
{'type': 'HostName', 'value': host_name}]
incident['labels'] = labels
return incident
def normalize_score(score): # pragma: no cover
"""
Translates API raw float (-1 to 1) score to UI score (-100 to 100)
"""
return score * 100
def translate_score(score, threshold): # pragma: no cover
if score > 0:
dbot_score = 1
elif threshold <= score:
dbot_score = 2
else:
dbot_score = 3
return dbot_score
# FUNCTIONS
def test(): # pragma: no cover
access_token = get_authentication_token()
if not access_token:
raise Exception('Unable to get access token')
demisto.results('ok')
def get_devices():
page = demisto.args()['pageNumber'] if 'pageNumber' in demisto.args() else None
page_size = demisto.args()['pageSize'] if 'pageSize' in demisto.args() else None
result = get_devices_request(page, page_size)
devices = result['page_items']
hr = []
devices_context = []
endpoint_context = []
for device in devices:
current_device_context = {
'AgentVersion': device['agent_version'],
'DateFirstRegistered': device['date_first_registered'],
'ID': device['id'],
'IPAddress': device['ip_addresses'],
'MACAdress': device['mac_addresses'],
'Hostname': device['name'],
'State': device['state']
}
if device['policy']:
policy = {}
if device['policy']['id']:
policy['ID'] = device['policy']['id']
if device['policy']['name']:
policy['Name'] = device['policy']['name']
if policy:
current_device_context['Policy'] = policy
devices_context.append(current_device_context)
endpoint_context.append({
'IPAddress': device['ip_addresses'],
'MACAdress': device['mac_addresses'],
'Hostname': device['name']
})
current_device = dict(device)
current_device['ip_addresses'] = ', '.join(current_device['ip_addresses'])
current_device['mac_addresses'] = ', '.join(current_device['mac_addresses'])
current_device['policy'] = current_device['policy']['name']
hr.append(current_device)
ec = {
'CylanceProtect.Device(val.ID && val.ID === obj.ID)': devices_context,
'Endpoint(val.Hostname && val.Hostname === obj.Hostname)': endpoint_context
}
entry = {
'Type': entryTypes['note'],
'Contents': devices,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown('Cylance Protect Devices', hr, headerTransform=underscoreToCamelCase,
removeNull=True),
'EntryContext': ec
}
demisto.results(entry)
def get_devices_request(page=None, page_size=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_DEVICE_LIST)
params = {}
if page:
params['page'] = page
if page_size:
params['page_size'] = page_size
res = api_call(uri=URI_DEVICES, method='get', params=params, access_token=access_token)
return res
def get_device():
device_id = demisto.args()['id']
device = get_device_request(device_id)
hr = []
if device:
device_context = {
'IPAddress': device['ip_addresses'],
'MACAdress': device['mac_addresses'],
'Hostname': device['host_name'],
'OSVersion': device['os_version'],
'UpdateAvailable': device['update_available'],
'BackgroundDetection': device['background_detection'],
'DateFirstRegistered': device['date_first_registered'],
'DateLastModified': device['date_last_modified'],
'DateOffline': device['date_offline'],
'IsSafe': device['is_safe'],
'LastLoggedInUser': device['last_logged_in_user'],
'State': device['state'],
'ID': device['id'],
'Name': device['name']
}
if device['update_type']:
device_context['UpdateType'] = device['update_type']
if device['policy']:
policy = {}
if device['policy']['id']:
policy['ID'] = device['policy']['id']
if device['policy']['name']:
policy['Name'] = device['policy']['name']
if policy:
device_context['Policy'] = policy
endpoint_context = {
'IPAddress': device['ip_addresses'],
'MACAdress': device['mac_addresses'],
'Hostname': device['host_name'],
'OSVersion': device['os_version']
}
ec = {
'Endpoint(val.Hostname && val.Hostname === obj.Hostname)': endpoint_context,
'CylanceProtect.Device(val.ID && val.ID === obj.ID)': device_context
}
current_device = dict(device)
current_device['ip_addresses'] = ', '.join(current_device['ip_addresses'])
current_device['mac_addresses'] = ', '.join(current_device['mac_addresses'])
current_device['policy'] = current_device['policy']['name']
hr.append(current_device)
else:
ec = {}
title = 'Cylance Protect Device ' + device_id
entry = {
'Type': entryTypes['note'],
'Contents': device,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, hr, headerTransform=underscoreToCamelCase, removeNull=True),
'EntryContext': ec
}
demisto.results(entry)
def get_device_request(device_id): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_DEVICE_READ)
uri = '{}/{}'.format(URI_DEVICES, device_id)
res = api_call(uri=uri, method='get', access_token=access_token)
return res
def get_device_by_hostname():
hostname_id = demisto.args()['hostname']
device = get_hostname_request(hostname_id)
title = 'Cylance Protect Device ' + hostname_id
if device:
device_context = {
'AgentVersion': device['agent_version'],
'IPAddress': device['ip_addresses'],
'MACAdress': device['mac_addresses'],
'Hostname': device['host_name'],
'OSVersion': device['os_version'],
'UpdateAvailable': device['update_available'],
'BackgroundDetection': device['background_detection'],
'DateFirstRegistered': device['date_first_registered'],
'DateLastModified': device['date_last_modified'],
'DateOffline': device['date_offline'],
'IsSafe': device['is_safe'],
'LastLoggedInUser': device['last_logged_in_user'],
'State': device['state'],
'ID': device['id'],
'Name': device['name']
}
if device['update_type']:
device_context['UpdateType'] = device['update_type']
if device['policy']:
policy = {}
if device['policy']['id']:
policy['ID'] = device['policy']['id']
if device['policy']['name']:
policy['Name'] = device['policy']['name']
if policy:
device_context['Policy'] = policy
endpoint_context = {
'IPAddress': device['ip_addresses'],
'MACAdress': device['mac_addresses'],
'Hostname': device['host_name'],
'OSVersion': device['os_version']
}
ec = {
'Endpoint(val.Hostname && val.Hostname === obj.Hostname)': endpoint_context,
'CylanceProtect.Device(val.ID && val.ID === obj.ID)': device_context
}
current_device = dict(device)
current_device['ip_addresses'] = ', '.join(current_device['ip_addresses'])
current_device['mac_addresses'] = ', '.join(current_device['mac_addresses'])
current_device['policy'] = current_device['policy']['name']
hr = tableToMarkdown(title, [current_device], headerTransform=underscoreToCamelCase, removeNull=True)
else:
ec = {}
hr = '### Device For Hostname ' + hostname_id + ' Was Not Found'
entry = {
'Type': entryTypes['note'],
'Contents': device,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': hr,
'EntryContext': ec
}
demisto.results(entry)
def get_hostname_request(hostname): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_DEVICE_READ)
uri = '{}/{}'.format(URI_HOSTNAME, hostname)
res = api_call(uri=uri, method='get', access_token=access_token)
if not res:
return None
return res[0]
def update_device():
device_id = demisto.args()['id']
name = demisto.args()['name'] if 'name' in demisto.args() else None
policy_id = demisto.args()['policyId'] if 'policyId' in demisto.args() else None
add_zones = demisto.args()['addZones'] if 'addZones' in demisto.args() else None
remove_zones = demisto.args()['removeZones'] if 'removeZones' in demisto.args() else None
update_device_request(device_id, name, policy_id, add_zones, remove_zones)
hr = {}
if name:
hr['Name'] = name
if policy_id:
hr['PolicyID'] = policy_id
if add_zones:
hr['AddedZones'] = add_zones
if remove_zones:
hr['RemovedZones'] = remove_zones
device = hr.copy()
device['id'] = device_id
title = 'Device ' + device_id + ' was updated successfully.'
entry = {
'Type': entryTypes['note'],
'Contents': device,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, [hr])
}
demisto.results(entry)
def update_device_request(device_id, name=None, policy_id=None, add_zones=None, remove_zones=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_DEVICE_UPDATE)
body = {}
if name:
body['name'] = name
if policy_id:
body['policy_id'] = policy_id
if add_zones:
body['add_zone_ids'] = [add_zones]
if remove_zones:
body['remove_zone_ids'] = [remove_zones]
# Do we have anything to update?
if not body:
raise Exception('No changes detected')
uri = '{}/{}'.format(URI_DEVICES, device_id)
res = api_call(uri=uri, method='put', access_token=access_token, body=body)
return res
def get_device_threats():
device_id = demisto.args()['id']
page = demisto.args()['pageNumber'] if 'pageNumber' in demisto.args() else None
page_size = demisto.args()['pageSize'] if 'pageSize' in demisto.args() else None
device_threats = get_device_threats_request(device_id, page, page_size)['page_items']
dbot_score_array = []
for threat in device_threats:
dbot_score = 0
score = threat.get('cylance_score', None)
if score:
threat['cylance_score'] = normalize_score(threat['cylance_score'])
threshold = demisto.args().get('threshold', FILE_THRESHOLD)
dbot_score = translate_score(threat['cylance_score'], int(threshold))
dbot_score_array.append(create_dbot_score_entry(threat, dbot_score).to_context())
if device_threats:
dbot_score_dict = {Common.DBotScore.get_context_path(): []} # type: Dict[str, List[Dict[str, str]]]
for dbot_score_entry in dbot_score_array:
for key, value in list(dbot_score_entry.items()):
dbot_score_dict[Common.DBotScore.get_context_path()].append(value)
threats_context = createContext(data=device_threats, keyTransform=underscoreToCamelCase)
threats_context = add_capitalized_hash_to_context(threats_context)
ec = {'File': threats_context}
ec.update(dbot_score_dict)
title = 'Cylance Protect Device Threat ' + device_id
demisto.results({
'Type': entryTypes['note'],
'Contents': device_threats,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, device_threats, headerTransform=underscoreToCamelCase),
'EntryContext': ec
})
else:
demisto.results('No threats found.')
def get_device_threats_request(device_id, page=None, page_size=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_DEVICE_THREAT_LIST)
params = {}
if page:
params['page'] = page
if page_size:
params['page_size'] = page_size
uri = '{}/{}/threats'.format(URI_DEVICES, device_id)
res = api_call(uri=uri, method='get', access_token=access_token, params=params)
return res
def get_policies():
page = demisto.args()['pageNumber'] if 'pageNumber' in demisto.args() else None
page_size = demisto.args()['pageSize'] if 'pageSize' in demisto.args() else None
policies = get_policies_request(page, page_size)['page_items']
context_policies = createContext(data=policies, keyTransform=underscoreToCamelCase)
ec = {
'CylanceProtect.Policies(val.id && val.id === obj.id)': context_policies
}
title = 'Cylance Protect Policies'
entry = {
'Type': entryTypes['note'],
'Contents': policies,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, policies, headerTransform=underscoreToCamelCase),
'EntryContext': ec
}
demisto.results(entry)
def get_policies_request(page=None, page_size=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_POLICY_LIST)
params = {}
if page:
params['page'] = page
if page_size:
params['page_size'] = page_size
res = api_call(uri=URI_POLICIES, method='get', access_token=access_token, params=params)
return res
def create_zone():
name = demisto.args()['name']
policy_id = demisto.args()['policy_id']
criticality = demisto.args()['criticality']
zone = create_zone_request(name, policy_id, criticality)
title = 'Zone ' + name + ' was created successfully.'
demisto.results({
'Type': entryTypes['note'],
'Contents': zone,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, [zone], headerTransform=underscoreToCamelCase)
})
def create_zone_request(name, policy_id, criticality): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_ZONE_CREATE)
body = {
'name': name,
'policy_id': policy_id,
'criticality': criticality
}
res = api_call(uri=URI_ZONES, method='post', access_token=access_token, body=body)
return res
def get_zones():
page = demisto.args()['pageNumber'] if 'pageNumber' in demisto.args() else None
page_size = demisto.args()['pageSize'] if 'pageSize' in demisto.args() else None
zones = get_zones_request(page, page_size)['page_items']
context_zones = createContext(data=zones, keyTransform=underscoreToCamelCase, removeNull=True)
ec = {
'CylanceProtect.Zones(val.Id && val.Id === obj.Id)': context_zones
}
title = 'Cylance Protect Zones'
demisto.results({
'Type': entryTypes['note'],
'Contents': zones,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, zones, headerTransform=underscoreToCamelCase, removeNull=True),
'EntryContext': ec
})
def get_zones_request(page=None, page_size=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_ZONE_LIST)
params = {}
if page:
params['page'] = page
if page_size:
params['page_size'] = page_size
res = api_call(uri=URI_ZONES, method='get', access_token=access_token, params=params)
return res
def get_zone():
zone_id = demisto.args()['id']
zone = get_zone_request(zone_id)
context_zone = createContext(data=zone, keyTransform=underscoreToCamelCase, removeNull=True)
ec = {
'CylanceProtect.Zones(val.Id && val.Id === obj.Id)': context_zone
}
title = 'Cylance Protect Zone ' + zone_id
demisto.results({
'Type': entryTypes['note'],
'Contents': zone,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, zone, headerTransform=underscoreToCamelCase, removeNull=True),
'EntryContext': ec
})
def get_zone_request(zone_id): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_ZONE_READ)
uri = '{}/{}'.format(URI_ZONES, zone_id)
res = api_call(uri=uri, method='get', access_token=access_token)
return res
def update_zone():
zone_id = demisto.args()['id']
# Get current zone and fill in requires missing arguments
current_zone = get_zone_request(zone_id)
# Details to update
name = demisto.args()['name'] if 'name' in demisto.args() else current_zone['name']
policy_id = demisto.args()['policy_id'] if 'policy_id' in demisto.args() else current_zone['policy_id']
criticality = demisto.args()['criticality'] if 'criticality' in demisto.args() else current_zone['criticality']
zone = update_zone_request(zone_id, name, policy_id, criticality)
hr = {}
if name:
hr['Name'] = name
if policy_id:
hr['PolicyID'] = policy_id
if criticality:
hr['Criticality'] = criticality
title = 'Zone was updated successfully.'
demisto.results({
'Type': entryTypes['note'],
'Contents': zone,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, [hr])
})
def update_zone_request(zone_id, name, policy_id, criticality): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_ZONE_UPDATE)
body = {}
if name:
body['name'] = name
if policy_id:
body['policy_id'] = policy_id
if criticality:
body['criticality'] = criticality
# Do we have anything to update?
if not body:
raise Exception('No changes detected')
uri = '{}/{}'.format(URI_ZONES, zone_id)
res = api_call(uri=uri, method='put', access_token=access_token, body=body)
return res
def get_threat():
sha256 = demisto.args().get('sha256')
threat = get_threat_request(sha256)
if threat:
dbot_score = 0
score = threat.get('cylance_score', None)
if score:
threat['cylance_score'] = normalize_score(threat['cylance_score'])
threshold = demisto.args().get('threshold', FILE_THRESHOLD)
dbot_score = translate_score(threat['cylance_score'], int(threshold))
context_threat = createContext(data=threat, keyTransform=underscoreToCamelCase, removeNull=True)
context_threat = add_capitalized_hash_to_context(context_threat)
ec = {'File': context_threat}
ec.update(create_dbot_score_entry(threat, dbot_score).to_context())
title = 'Cylance Protect Threat ' + sha256
demisto.results({
'Type': entryTypes['note'],
'Contents': threat,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, threat, headerTransform=underscoreToCamelCase, removeNull=True),
'EntryContext': ec
})
else:
demisto.results('Threat was not found.')
def get_threat_request(sha256): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_THREAT_READ)
uri = '{}/{}'.format(URI_THREATS, sha256)
res = api_call(uri=uri, method='get', access_token=access_token, body={}, params={}, accept_404=False)
return res
def create_dbot_score_entry(threat, dbot_score):
dbot_score_entry = Common.DBotScore(
threat.get('sha256'),
DBotScoreType.FILE,
integration_name='Cylance Protect',
score=dbot_score)
return dbot_score_entry
def get_threats():
page = demisto.args().get('pageNumber')
page_size = demisto.args().get('pageSize')
threats = get_threats_request(page, page_size)['page_items']
dbot_score_array = []
for threat in threats:
dbot_score = 0
score = threat.get('cylance_score', None)
if score:
threat['cylance_score'] = normalize_score(threat['cylance_score'])
threshold = demisto.args().get('threshold', FILE_THRESHOLD)
dbot_score = translate_score(threat['cylance_score'], int(threshold))
dbot_score_array.append(create_dbot_score_entry(threat, dbot_score).to_context())
dbot_score_dict = {Common.DBotScore.get_context_path(): []} # type: Dict[str, List[Dict[str, str]]]
for dbot_score_entry in dbot_score_array:
for key, value in list(dbot_score_entry.items()):
dbot_score_dict[Common.DBotScore.get_context_path()].append(value)
context_threat = createContext(data=threats, keyTransform=underscoreToCamelCase, removeNull=True)
context_threat = add_capitalized_hash_to_context(context_threat)
ec = {'File': context_threat}
ec.update(dbot_score_dict)
title = 'Cylance Protect Threats'
demisto.results({
'Type': entryTypes['note'],
'Contents': threats,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, threats, headerTransform=underscoreToCamelCase, removeNull=True),
'EntryContext': ec
})
def get_threats_request(page=None, page_size=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_THREAT_LIST)
params = {}
if page in demisto.args():
params['page'] = demisto.args()['page']
if page_size in demisto.args():
params['page_size'] = demisto.args()['pageSize']
res = api_call(uri=URI_THREATS, method='get', access_token=access_token, params=params)
return res
def get_threat_devices():
threat_hash = demisto.args()['sha256']
page = demisto.args()['pageNumber'] if 'pageNumber' in demisto.args() else None
page_size = demisto.args()['pageSize'] if 'pageSize' in demisto.args() else None
threats = get_threat_devices_request(threat_hash, page, page_size)['page_items']
if threats:
threats_context = threats[:]
for threat in threats:
threat['ip_addresses'] = ', '.join(threat['ip_addresses'])
threat['mac_addresses'] = ', '.join(threat['mac_addresses'])
file_paths = []
endpoint_context = []
devices_context = []
for threat in threats_context:
endpoint_context.append({
'Hostname': threat['name'],
'IPAddress': threat['ip_addresses'],
'MACAddress': threat['mac_addresses']
})
current_device = {
'Hostname': threat['name'],
'IPAddress': threat['ip_addresses'],
'MACAddress': threat['mac_addresses'],
'AgentVersion': threat['agent_version'],
'DateFound': threat['date_found'],
'FilePath': threat['file_path'],
'ID': threat['id'],
'State': threat['state'],
'FileStatus': threat['file_status']
}
if threat['policy_id']:
current_device['PolicyID'] = threat['policy_id']
devices_context.append(current_device)
file_path = threat.pop('file_path')
file_paths.append({
'FilePath': file_path
})
file_context = {
'SHA256': threat_hash,
'Path': file_paths
}
ec = {
'File': file_context,
'Endpoint(val.Hostname && val.Hostname === obj.Hostname)': endpoint_context,
'CylanceProtect.Threat(val.SHA256 && val.SHA256 === obj.SHA256)': {
'SHA256': threat_hash,
'Devices': devices_context
}
}
title = 'Cylance Protect Threat ' + threat_hash + ' Devices'
demisto.results({
'Type': entryTypes['note'],
'Contents': threats,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, threats, headerTransform=underscoreToCamelCase, removeNull=True),
'EntryContext': ec
})
else:
demisto.results('No devices found on given threat.')
def get_threat_devices_request(threat_hash, page=None, page_size=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_THREAT_DEVICE_LIST)
params = {}
if page:
params['page'] = page
if page_size:
params['page_size'] = page_size
uri = '{}/{}/devices'.format(URI_THREATS, threat_hash)
res = api_call(uri=uri, method='get', access_token=access_token, params=params)
return res
def get_list():
page = demisto.args()['pageNumber'] if 'pageNumber' in demisto.args() else None
page_size = demisto.args()['pageSize'] if 'pageSize' in demisto.args() else None
lst = get_list_request(demisto.args()['listTypeId'], page, page_size)['page_items']
dbot_score_array = []
for threat in lst:
dbot_score = 0
score = threat.get('cylance_score', None)
if score:
threat['cylance_score'] = normalize_score(threat['cylance_score'])
threshold = demisto.args().get('threshold', FILE_THRESHOLD)
dbot_score = translate_score(threat['cylance_score'], int(threshold))
dbot_score_array.append(create_dbot_score_entry(threat, dbot_score).to_context())
if lst:
dbot_score_dict = {Common.DBotScore.get_context_path(): []} # type: Dict[str, List[Dict[str, str]]]
for dbot_score_entry in dbot_score_array:
for key, value in list(dbot_score_entry.items()):
dbot_score_dict[Common.DBotScore.get_context_path()].append(value)
context_list = createContext(data=lst, keyTransform=underscoreToCamelCase, removeNull=True)
context_list = add_capitalized_hash_to_context(context_list)
ec = {'File': context_list}
ec.update(dbot_score_dict)
title = 'Cylance Protect Global List'
demisto.results({
'Type': entryTypes['note'],
'Contents': lst,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, lst, headerTransform=underscoreToCamelCase, removeNull=True),
'EntryContext': ec
})
else:
demisto.results('No list of this type was found.')
def get_list_request(list_type_id, page=None, page_size=None): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_GLOBAL_LIST)
params = {}
if list_type_id == 'GlobalQuarantine':
params['listTypeId'] = 0
else: # List Type ID is GlobalSafe
params['listTypeId'] = 1
if page:
params['page'] = page
if page_size:
params['page_size'] = page_size
res = api_call(uri=URI_LISTS, method='get', access_token=access_token, params=params)
return res
def get_list_entry_by_hash(sha256=None, list_type_id=None):
if not sha256:
sha256 = demisto.args()['sha256']
if not list_type_id:
list_type_id = demisto.args()['listTypeId']
total_pages = 0
current_page = 0
found_hash = None
while not found_hash and total_pages >= current_page:
if not current_page:
current_page = 1
lst = get_list_request(list_type_id, current_page, 200)
if not total_pages:
total_pages = lst['total_pages']
for i in lst['page_items']:
if i['sha256'] == sha256:
found_hash = i
break
current_page += 1
if demisto.command() == 'cylance-protect-get-list-entry':
if found_hash:
context_list = createContext(data=found_hash, keyTransform=underscoreToCamelCase, removeNull=True)
ec = {
'CylanceListSearch': context_list
}
title = 'Cylance Protect Global List Entry'
demisto.results({
'Type': entryTypes['note'],
'Contents': found_hash,
'ContentsFormat': formats['json'],
'ReadableContentsFormat': formats['markdown'],
'HumanReadable': tableToMarkdown(title, found_hash, headerTransform=underscoreToCamelCase,
removeNull=True),
'EntryContext': ec
})
else:
demisto.results("Hash not found")
else:
return found_hash
def get_indicators_report(): # pragma: no cover
url = 'https://protect.cylance.com/Reports/ThreatDataReportV1/indicators/' + demisto.args()['token']
res = requests.request('GET', url, verify=USE_SSL)
filename = 'Indicators_Report.csv'
demisto.results(fileResult(filename, res.content))
def update_device_threats(): # pragma: no cover
device_id = demisto.args()['device_id']
threat_id = demisto.args()['threat_id']
event = demisto.args()['event']
update_device_threats_request(device_id, threat_id, event)
demisto.results('Device threat was updated successfully.')
def update_device_threats_request(device_id, threat_id, event): # pragma: no cover
access_token = get_authentication_token(scope=SCOPE_THREAT_UPDATE)
body = {
'threat_id': threat_id,
'event': event
}
uri = '{}/{}/threats'.format(URI_DEVICES, device_id)
res = api_call(uri=uri, method='post', access_token=access_token, body=body)
return res
def download_threat():
contents = {}
context = {}
dbot_score = 0
sha256 = demisto.args()['sha256']
threat_url = download_threat_request(sha256)
threat_file = requests.get(threat_url, allow_redirects=True, verify=USE_SSL)
if threat_file.status_code == 200:
if demisto.args()['unzip'] == "yes":
file_archive = BytesIO(threat_file.content)