forked from demisto/content-external-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommonServerPython.py
More file actions
3597 lines (2868 loc) · 127 KB
/
CommonServerPython.py
File metadata and controls
3597 lines (2868 loc) · 127 KB
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
"""Common functions script
This script will be appended to each server script before being executed.
Please notice that to add custom common code, add it to the CommonServerUserPython script.
Note that adding code to CommonServerUserPython can override functions in CommonServerPython
"""
from __future__ import print_function
import base64
import json
import logging
import os
import re
import socket
import sys
import time
import traceback
import xml.etree.cElementTree as ET
from collections import OrderedDict
from datetime import datetime, timedelta
from abc import abstractmethod
import demistomock as demisto
# imports something that can be missed from docker image
try:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
except Exception:
pass
CONTENT_RELEASE_VERSION = '0.0.0'
CONTENT_BRANCH_NAME = 'master'
IS_PY3 = sys.version_info[0] == 3
# pylint: disable=undefined-variable
if IS_PY3:
STRING_TYPES = (str, bytes) # type: ignore
STRING_OBJ_TYPES = (str,)
else:
STRING_TYPES = (str, unicode) # type: ignore
STRING_OBJ_TYPES = STRING_TYPES # type: ignore
# pylint: enable=undefined-variable
# DEPRECATED - use EntryType enum instead
entryTypes = {
'note': 1,
'downloadAgent': 2,
'file': 3,
'error': 4,
'pinned': 5,
'userManagement': 6,
'image': 7,
'playgroundError': 8,
'entryInfoFile': 9,
'warning': 11,
'map': 15,
'widget': 17
}
class EntryType(object):
"""
Enum: contains all the entry types (e.g. NOTE, ERROR, WARNING, FILE, etc.)
"""
NOTE = 1
DOWNLOAD_AGENT = 2
FILE = 3
ERROR = 4
PINNED = 5
USER_MANAGEMENT = 6
IMAGE = 7
PLAYGROUND_ERROR = 8
ENTRY_INFO_FILE = 9
WARNING = 11
MAP_ENTRY_TYPE = 15
WIDGET = 17
# DEPRECATED - use EntryFormat enum instead
formats = {
'html': 'html',
'table': 'table',
'json': 'json',
'text': 'text',
'dbotResponse': 'dbotCommandResponse',
'markdown': 'markdown'
}
class EntryFormat(object):
"""
Enum: contains all the entry formats (e.g. HTML, TABLE, JSON, etc.)
"""
HTML = 'html'
TABLE = 'table'
JSON = 'json'
TEXT = 'text'
DBOT_RESPONSE = 'dbotCommandResponse'
MARKDOWN = 'markdown'
@classmethod
def is_valid_type(cls, _type):
# type: (str) -> bool
return _type in (
EntryFormat.HTML,
EntryFormat.TABLE,
EntryFormat.JSON,
EntryFormat.TEXT,
EntryFormat.MARKDOWN,
EntryFormat.DBOT_RESPONSE
)
brands = {
'xfe': 'xfe',
'vt': 'virustotal',
'wf': 'WildFire',
'cy': 'cylance',
'cs': 'crowdstrike-intel'
}
providers = {
'xfe': 'IBM X-Force Exchange',
'vt': 'VirusTotal',
'wf': 'WildFire',
'cy': 'Cylance',
'cs': 'CrowdStrike'
}
thresholds = {
'xfeScore': 4,
'vtPositives': 10,
'vtPositiveUrlsForIP': 30
}
class DBotScoreType(object):
"""
Enum: contains all the indicator types
DBotScoreType.IP
DBotScoreType.FILE
DBotScoreType.DOMAIN
DBotScoreType.URL
:return: None
:rtype: ``None``
"""
IP = 'ip'
FILE = 'file'
DOMAIN = 'domain'
URL = 'url'
def __init__(self):
# required to create __init__ for create_server_docs.py purpose
pass
@classmethod
def is_valid_type(cls, _type):
# type: (str) -> bool
return _type in (
DBotScoreType.IP,
DBotScoreType.FILE,
DBotScoreType.DOMAIN,
DBotScoreType.URL
)
INDICATOR_TYPE_TO_CONTEXT_KEY = {
'ip': 'Address',
'email': 'Address',
'url': 'Data',
'domain': 'Name',
'cve': 'ID',
'md5': 'file',
'sha1': 'file',
'sha256': 'file',
'crc32': 'file',
'sha512': 'file',
'ctph': 'file',
'ssdeep': 'file'
}
class FeedIndicatorType(object):
"""Type of Indicator (Reputations), used in TIP integrations"""
Account = "Account"
CVE = "CVE"
Domain = "Domain"
DomainGlob = "DomainGlob"
Email = "Email"
File = "File"
FQDN = "Domain"
Host = "Host"
IP = "IP"
CIDR = "CIDR"
IPv6 = "IPv6"
IPv6CIDR = "IPv6CIDR"
Registry = "Registry Key"
SSDeep = "ssdeep"
URL = "URL"
@staticmethod
def is_valid_type(_type):
return _type in (
FeedIndicatorType.Account,
FeedIndicatorType.CVE,
FeedIndicatorType.Domain,
FeedIndicatorType.DomainGlob,
FeedIndicatorType.Email,
FeedIndicatorType.File,
FeedIndicatorType.Host,
FeedIndicatorType.IP,
FeedIndicatorType.CIDR,
FeedIndicatorType.IPv6,
FeedIndicatorType.IPv6CIDR,
FeedIndicatorType.Registry,
FeedIndicatorType.SSDeep,
FeedIndicatorType.URL
)
@staticmethod
def list_all_supported_indicators():
indicator_types = []
for key, val in vars(FeedIndicatorType).items():
if not key.startswith('__') and type(val) == str:
indicator_types.append(val)
return indicator_types
@staticmethod
def ip_to_indicator_type(ip):
"""Returns the indicator type of the input IP.
:type ip: ``str``
:param ip: IP address to get it's indicator type.
:rtype: ``str``
:return:: Indicator type from FeedIndicatorType, or None if invalid IP address.
"""
if re.match(ipv4cidrRegex, ip):
return FeedIndicatorType.CIDR
elif re.match(ipv4Regex, ip):
return FeedIndicatorType.IP
elif re.match(ipv6cidrRegex, ip):
return FeedIndicatorType.IPv6CIDR
elif re.match(ipv6Regex, ip):
return FeedIndicatorType.IPv6
else:
return None
# ===== Fix fetching credentials from vault instances =====
# ====================================================================================
try:
for k, v in demisto.params().items():
if isinstance(v, dict):
if 'credentials' in v:
vault = v['credentials'].get('vaultInstanceId')
if vault:
v['identifier'] = v['credentials'].get('user')
break
except Exception:
pass
# ====================================================================================
def handle_proxy(proxy_param_name='proxy', checkbox_default_value=False):
"""
Handle logic for routing traffic through the system proxy.
Should usually be called at the beginning of the integration, depending on proxy checkbox state.
:type proxy_param_name: ``string``
:param proxy_param_name: name of the "use system proxy" integration parameter
:type checkbox_default_value: ``bool``
:param checkbox_default_value: Default value of the proxy param checkbox
:rtype: ``dict``
:return: proxies dict for the 'proxies' parameter of 'requests' functions
"""
proxies = {} # type: dict
if demisto.params().get(proxy_param_name, checkbox_default_value):
proxies = {
'http': os.environ.get('HTTP_PROXY') or os.environ.get('http_proxy', ''),
'https': os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy', '')
}
else:
for k in ('HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'):
if k in os.environ:
del os.environ[k]
return proxies
def urljoin(url, suffix=""):
"""
Will join url and its suffix
Example:
"https://google.com/", "/" => "https://google.com/"
"https://google.com", "/" => "https://google.com/"
"https://google.com", "api" => "https://google.com/api"
"https://google.com", "/api" => "https://google.com/api"
"https://google.com/", "api" => "https://google.com/api"
"https://google.com/", "/api" => "https://google.com/api"
:type url: ``string``
:param url: URL string (required)
:type suffix: ``string``
:param suffix: the second part of the url
:rtype: ``string``
:return: Full joined url
"""
if url[-1:] != "/":
url = url + "/"
if suffix.startswith("/"):
suffix = suffix[1:]
return url + suffix
return url + suffix
def positiveUrl(entry):
"""
Checks if the given entry from a URL reputation query is positive (known bad) (deprecated)
:type entry: ``dict``
:param entry: URL entry (required)
:return: True if bad, false otherwise
:rtype: ``bool``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
if entry['Brand'] == brands['xfe']:
return demisto.get(entry, 'Contents.url.result.score') > thresholds['xfeScore']
if entry['Brand'] == brands['vt']:
return demisto.get(entry, 'Contents.positives') > thresholds['vtPositives']
if entry['Brand'] == brands['cs'] and demisto.get(entry, 'Contents'):
c = demisto.get(entry, 'Contents')[0]
return demisto.get(c, 'indicator') and demisto.get(c, 'malicious_confidence') in ['high', 'medium']
return False
def positiveFile(entry):
"""
Checks if the given entry from a file reputation query is positive (known bad) (deprecated)
:type entry: ``dict``
:param entry: File entry (required)
:return: True if bad, false otherwise
:rtype: ``bool``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
if entry['Brand'] == brands['xfe'] and (demisto.get(entry, 'Contents.malware.family')
or demisto.gets(entry, 'Contents.malware.origins.external.family')):
return True
if entry['Brand'] == brands['vt']:
return demisto.get(entry, 'Contents.positives') > thresholds['vtPositives']
if entry['Brand'] == brands['wf']:
return demisto.get(entry, 'Contents.wildfire.file_info.malware') == 'yes'
if entry['Brand'] == brands['cy'] and demisto.get(entry, 'Contents'):
contents = demisto.get(entry, 'Contents')
k = contents.keys()
if k and len(k) > 0:
v = contents[k[0]]
if v and demisto.get(v, 'generalscore'):
return v['generalscore'] < -0.5
if entry['Brand'] == brands['cs'] and demisto.get(entry, 'Contents'):
c = demisto.get(entry, 'Contents')[0]
return demisto.get(c, 'indicator') and demisto.get(c, 'malicious_confidence') in ['high', 'medium']
return False
def vtCountPositives(entry):
"""
Counts the number of detected URLs in the entry
:type entry: ``dict``
:param entry: Demisto entry (required)
:return: The number of detected URLs
:rtype: ``int``
"""
positives = 0
if demisto.get(entry, 'Contents.detected_urls'):
for detected in demisto.get(entry, 'Contents.detected_urls'):
if demisto.get(detected, 'positives') > thresholds['vtPositives']:
positives += 1
return positives
def positiveIp(entry):
"""
Checks if the given entry from a file reputation query is positive (known bad) (deprecated)
:type entry: ``dict``
:param entry: IP entry (required)
:return: True if bad, false otherwise
:rtype: ``bool``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
if entry['Brand'] == brands['xfe']:
return demisto.get(entry, 'Contents.reputation.score') > thresholds['xfeScore']
if entry['Brand'] == brands['vt'] and demisto.get(entry, 'Contents.detected_urls'):
return vtCountPositives(entry) > thresholds['vtPositiveUrlsForIP']
if entry['Brand'] == brands['cs'] and demisto.get(entry, 'Contents'):
c = demisto.get(entry, 'Contents')[0]
return demisto.get(c, 'indicator') and demisto.get(c, 'malicious_confidence') in ['high', 'medium']
return False
def formatEpochDate(t):
"""
Convert a time expressed in seconds since the epoch to a string representing local time
:type t: ``int``
:param t: Time represented in seconds (required)
:return: A string representing local time
:rtype: ``str``
"""
if t:
return time.ctime(t)
return ''
def shortCrowdStrike(entry):
"""
Display CrowdStrike Intel results in Markdown (deprecated)
:type entry: ``dict``
:param entry: CrowdStrike result entry (required)
:return: A Demisto entry containing the shortened CrowdStrike info
:rtype: ``dict``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
if entry['Brand'] == brands['cs'] and demisto.get(entry, 'Contents'):
c = demisto.get(entry, 'Contents')[0]
csRes = '## CrowdStrike Falcon Intelligence'
csRes += '\n\n### Indicator - ' + demisto.gets(c, 'indicator')
labels = demisto.get(c, 'labels')
if labels:
csRes += '\n### Labels'
csRes += '\nName|Created|Last Valid'
csRes += '\n----|-------|----------'
for label in labels:
csRes += '\n' + demisto.gets(label, 'name') + '|' + \
formatEpochDate(demisto.get(label, 'created_on')) + '|' + \
formatEpochDate(demisto.get(label, 'last_valid_on'))
relations = demisto.get(c, 'relations')
if relations:
csRes += '\n### Relations'
csRes += '\nIndicator|Type|Created|Last Valid'
csRes += '\n---------|----|-------|----------'
for r in relations:
csRes += '\n' + demisto.gets(r, 'indicator') + '|' + demisto.gets(r, 'type') + '|' + \
formatEpochDate(demisto.get(label, 'created_date')) + '|' + \
formatEpochDate(demisto.get(label, 'last_valid_date'))
return {'ContentsFormat': formats['markdown'], 'Type': entryTypes['note'], 'Contents': csRes}
return entry
def shortUrl(entry):
"""
Formats a URL reputation entry into a short table (deprecated)
:type entry: ``dict``
:param entry: URL result entry (required)
:return: A Demisto entry containing the shortened URL info
:rtype: ``dict``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
c = entry['Contents']
if entry['Brand'] == brands['xfe']:
return {'ContentsFormat': formats['table'], 'Type': entryTypes['note'], 'Contents': {
'Country': c['country'], 'MalwareCount': demisto.get(c, 'malware.count'),
'A': demisto.gets(c, 'resolution.A'), 'AAAA': demisto.gets(c, 'resolution.AAAA'),
'Score': demisto.get(c, 'url.result.score'), 'Categories': demisto.gets(c, 'url.result.cats'),
'URL': demisto.get(c, 'url.result.url'), 'Provider': providers['xfe'],
'ProviderLink': 'https://exchange.xforce.ibmcloud.com/url/' + demisto.get(c, 'url.result.url')}}
if entry['Brand'] == brands['vt']:
return {'ContentsFormat': formats['table'], 'Type': entryTypes['note'], 'Contents': {
'ScanDate': c['scan_date'], 'Positives': c['positives'], 'Total': c['total'],
'URL': c['url'], 'Provider': providers['vt'], 'ProviderLink': c['permalink']}}
if entry['Brand'] == brands['cs'] and demisto.get(entry, 'Contents'):
return shortCrowdStrike(entry)
return {'ContentsFormat': 'text', 'Type': 4, 'Contents': 'Unknown provider for result: ' + entry['Brand']}
def shortFile(entry):
"""
Formats a file reputation entry into a short table (deprecated)
:type entry: ``dict``
:param entry: File result entry (required)
:return: A Demisto entry containing the shortened file info
:rtype: ``dict``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
c = entry['Contents']
if entry['Brand'] == brands['xfe']:
cm = c['malware']
return {'ContentsFormat': formats['table'], 'Type': entryTypes['note'], 'Contents': {
'Family': cm['family'], 'MIMEType': cm['mimetype'], 'MD5': cm['md5'][2:] if 'md5' in cm else '',
'CnCServers': demisto.get(cm, 'origins.CncServers.count'),
'DownloadServers': demisto.get(cm, 'origins.downloadServers.count'),
'Emails': demisto.get(cm, 'origins.emails.count'),
'ExternalFamily': demisto.gets(cm, 'origins.external.family'),
'ExternalCoverage': demisto.get(cm, 'origins.external.detectionCoverage'),
'Provider': providers['xfe'],
'ProviderLink': 'https://exchange.xforce.ibmcloud.com/malware/' + cm['md5'].replace('0x', '')}}
if entry['Brand'] == brands['vt']:
return {'ContentsFormat': formats['table'], 'Type': entryTypes['note'], 'Contents': {
'Resource': c['resource'], 'ScanDate': c['scan_date'], 'Positives': c['positives'],
'Total': c['total'], 'SHA1': c['sha1'], 'SHA256': c['sha256'], 'Provider': providers['vt'],
'ProviderLink': c['permalink']}}
if entry['Brand'] == brands['wf']:
c = demisto.get(entry, 'Contents.wildfire.file_info')
if c:
return {'Contents': {'Type': c['filetype'], 'Malware': c['malware'], 'MD5': c['md5'],
'SHA256': c['sha256'], 'Size': c['size'], 'Provider': providers['wf']},
'ContentsFormat': formats['table'], 'Type': entryTypes['note']}
if entry['Brand'] == brands['cy'] and demisto.get(entry, 'Contents'):
contents = demisto.get(entry, 'Contents')
k = contents.keys()
if k and len(k) > 0:
v = contents[k[0]]
if v and demisto.get(v, 'generalscore'):
return {'Contents': {'Status': v['status'], 'Code': v['statuscode'], 'Score': v['generalscore'],
'Classifiers': str(v['classifiers']), 'ConfirmCode': v['confirmcode'],
'Error': v['error'], 'Provider': providers['cy']},
'ContentsFormat': formats['table'], 'Type': entryTypes['note']}
if entry['Brand'] == brands['cs'] and demisto.get(entry, 'Contents'):
return shortCrowdStrike(entry)
return {'ContentsFormat': formats['text'], 'Type': entryTypes['error'],
'Contents': 'Unknown provider for result: ' + entry['Brand']}
def shortIp(entry):
"""
Formats an ip reputation entry into a short table (deprecated)
:type entry: ``dict``
:param entry: IP result entry (required)
:return: A Demisto entry containing the shortened IP info
:rtype: ``dict``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
c = entry['Contents']
if entry['Brand'] == brands['xfe']:
cr = c['reputation']
return {'ContentsFormat': formats['table'], 'Type': entryTypes['note'], 'Contents': {
'IP': cr['ip'], 'Score': cr['score'], 'Geo': str(cr['geo']), 'Categories': str(cr['cats']),
'Provider': providers['xfe']}}
if entry['Brand'] == brands['vt']:
return {'ContentsFormat': formats['table'], 'Type': entryTypes['note'],
'Contents': {'Positive URLs': vtCountPositives(entry), 'Provider': providers['vt']}}
if entry['Brand'] == brands['cs'] and demisto.get(entry, 'Contents'):
return shortCrowdStrike(entry)
return {'ContentsFormat': formats['text'], 'Type': entryTypes['error'],
'Contents': 'Unknown provider for result: ' + entry['Brand']}
def shortDomain(entry):
"""
Formats a domain reputation entry into a short table (deprecated)
:type entry: ``dict``
:param entry: Domain result entry (required)
:return: A Demisto entry containing the shortened domain info
:rtype: ``dict``
"""
if entry['Type'] != entryTypes['error'] and entry['ContentsFormat'] == formats['json']:
if entry['Brand'] == brands['vt']:
return {'ContentsFormat': formats['table'], 'Type': entryTypes['note'],
'Contents': {'Positive URLs': vtCountPositives(entry), 'Provider': providers['vt']}}
return {'ContentsFormat': formats['text'], 'Type': entryTypes['error'],
'Contents': 'Unknown provider for result: ' + entry['Brand']}
def get_error(execute_command_result):
"""
execute_command_result must contain error entry - check the result first with is_error function
if there is no error entry in the result then it will raise an Exception
:type execute_command_result: ``dict`` or ``list``
:param execute_command_result: result of demisto.executeCommand()
:return: Error message extracted from the demisto.executeCommand() result
:rtype: ``string``
"""
if not is_error(execute_command_result):
raise ValueError("execute_command_result has no error entry. before using get_error use is_error")
if isinstance(execute_command_result, dict):
return execute_command_result['Contents']
error_messages = []
for entry in execute_command_result:
is_error_entry = type(entry) == dict and entry['Type'] == entryTypes['error']
if is_error_entry:
error_messages.append(entry['Contents'])
return '\n'.join(error_messages)
def is_error(execute_command_result):
"""
Check if the given execute_command_result has an error entry
:type execute_command_result: ``dict`` or ``list``
:param execute_command_result: Demisto entry (required) or result of demisto.executeCommand()
:return: True if the execute_command_result has an error entry, false otherwise
:rtype: ``bool``
"""
if execute_command_result is None:
return False
if isinstance(execute_command_result, list):
if len(execute_command_result) > 0:
for entry in execute_command_result:
if type(entry) == dict and entry['Type'] == entryTypes['error']:
return True
return type(execute_command_result) == dict and execute_command_result['Type'] == entryTypes['error']
isError = is_error
def FormatADTimestamp(ts):
"""
Formats an Active Directory timestamp into human readable time representation
:type ts: ``int``
:param ts: The timestamp to be formatted (required)
:return: A string represeting the time
:rtype: ``str``
"""
return (datetime(year=1601, month=1, day=1) + timedelta(seconds=int(ts) / 10 ** 7)).ctime()
def PrettifyCompactedTimestamp(x):
"""
Formats a compacted timestamp string into human readable time representation
:type x: ``str``
:param x: The timestamp to be formatted (required)
:return: A string represeting the time
:rtype: ``str``
"""
return '%s-%s-%sT%s:%s:%s' % (x[:4], x[4:6], x[6:8], x[8:10], x[10:12], x[12:])
def NormalizeRegistryPath(strRegistryPath):
"""
Normalizes a registry path string
:type strRegistryPath: ``str``
:param strRegistryPath: The registry path (required)
:return: The normalized string
:rtype: ``str``
"""
dSub = {
'HKCR': 'HKEY_CLASSES_ROOT',
'HKCU': 'HKEY_CURRENT_USER',
'HKLM': 'HKEY_LOCAL_MACHINE',
'HKU': 'HKEY_USERS',
'HKCC': 'HKEY_CURRENT_CONFIG',
'HKPD': 'HKEY_PERFORMANCE_DATA'
}
for k in dSub:
if strRegistryPath[:len(k)] == k:
return dSub[k] + strRegistryPath[len(k):]
return strRegistryPath
def scoreToReputation(score):
"""
Converts score (in number format) to human readable reputation format
:type score: ``int``
:param score: The score to be formatted (required)
:return: The formatted score
:rtype: ``str``
"""
to_str = {
4: 'Critical',
3: 'Bad',
2: 'Suspicious',
1: 'Good',
0.5: 'Informational',
0: 'Unknown'
}
return to_str.get(score, 'None')
def b64_encode(text):
"""
Base64 encode a string. Wrapper function around base64.b64encode which will accept a string
In py3 will encode the string to binary using utf-8 encoding and return a string result decoded using utf-8
:param text: string to encode
:type text: str
:return: encoded string
:rtype: str
"""
if not text:
return ''
elif isinstance(text, bytes):
to_encode = text
else:
to_encode = text.encode('utf-8', 'ignore')
res = base64.b64encode(to_encode)
if IS_PY3:
res = res.decode('utf-8') # type: ignore
return res
def encode_string_results(text):
"""
Encode string as utf-8, if any unicode character exists.
:param text: string to encode
:type text: str
:return: encoded string
:rtype: str
"""
if not isinstance(text, STRING_OBJ_TYPES):
return text
try:
return str(text)
except UnicodeEncodeError as exception:
return text.encode("utf8", "replace")
def safe_load_json(json_object):
"""
Safely loads a JSON object from an argument. Allows the argument to accept either a JSON in string form,
or an entry ID corresponding to a JSON file.
:param json_object: Entry ID or JSON string.
:type json_object: str
:return: Dictionary object from a parsed JSON file or string.
:rtype: dict
"""
safe_json = None
if isinstance(json_object, dict) or isinstance(json_object, list):
return json_object
if (json_object.startswith('{') and json_object.endswith('}')) or (json_object.startswith('[') and json_object.endswith(']')):
try:
safe_json = json.loads(json_object)
except ValueError as e:
return_error(
'Unable to parse JSON string. Please verify the JSON is valid. - ' + str(e))
else:
try:
path = demisto.getFilePath(json_object)
with open(path['path'], 'rb') as data:
try:
safe_json = json.load(data)
except Exception: # lgtm [py/catch-base-exception]
safe_json = json.loads(data.read())
except Exception as e:
return_error('Unable to parse JSON file. Please verify the JSON is valid or the Entry'
'ID is correct. - ' + str(e))
return safe_json
def datetime_to_string(datetime_obj):
"""
Converts a datetime object into a string. When used with `json.dumps()` for the `default` parameter,
e.g. `json.dumps(response, default=datetime_to_string)` datetime_to_string allows entire JSON objects
to be safely added to context without causing any datetime marshalling errors.
:param datetime_obj: Datetime object.
:type datetime_obj: datetime.datetime
:return: String representation of a datetime object.
:rtype: str
"""
if isinstance(datetime_obj, datetime): # type: ignore
return datetime_obj.__str__()
def remove_empty_elements(d):
"""
Recursively remove empty lists, empty dicts, or None elements from a dictionary.
:param d: Input dictionary.
:type d: dict
:return: Dictionary with all empty lists, and empty dictionaries removed.
:rtype: dict
"""
def empty(x):
return x is None or x == {} or x == []
if not isinstance(d, (dict, list)):
return d
elif isinstance(d, list):
return [v for v in (remove_empty_elements(v) for v in d) if not empty(v)]
else:
return {k: v for k, v in ((k, remove_empty_elements(v)) for k, v in d.items()) if not empty(v)}
def aws_table_to_markdown(response, table_header):
"""
Converts a raw response from AWS into a markdown formatted table. This function checks to see if
there is only one nested dict in the top level of the dictionary and will use the nested data.
:param response: Raw response from AWS
:type response: dict
:param table_header: The header string to use for the table.
:type table_header: str
:return: Markdown formatted table as a string.
:rtype: str
"""
if isinstance(response, dict):
if len(response) == 1:
if isinstance(response[list(response.keys())[0]], dict) or isinstance(
response[list(response.keys())[0]], list):
if isinstance(response[list(response.keys())[0]], list):
list_response = response[list(response.keys())[0]]
if isinstance(list_response[0], str):
human_readable = tableToMarkdown(
table_header, response)
else:
human_readable = tableToMarkdown(
table_header, response[list(response.keys())[0]])
else:
human_readable = tableToMarkdown(
table_header, response[list(response.keys())[0]])
else:
human_readable = tableToMarkdown(table_header, response)
else:
human_readable = tableToMarkdown(table_header, response)
else:
human_readable = tableToMarkdown(table_header, response)
return human_readable
class IntegrationLogger(object):
"""
a logger for python integrations:
use LOG(<message>) to add a record to the logger (message can be any object with __str__)
use LOG.print_log(verbose=True/False) to display all records in War-Room (if verbose) and server log.
use add_replace_strs to add sensitive strings that should be replaced before going to the log.
:type message: ``str``
:param message: The message to be logged
:return: No data returned
:rtype: ``None``
"""
def __init__(self):
self.messages = [] # type: list
self.write_buf = [] # type: list
self.replace_strs = [] # type: list
self.buffering = True
# if for some reason you don't want to auto add credentials.password to replace strings
# set the os env COMMON_SERVER_NO_AUTO_REPLACE_STRS. Either in CommonServerUserPython, or docker env
if (not os.getenv('COMMON_SERVER_NO_AUTO_REPLACE_STRS') and hasattr(demisto, 'getParam')):
# add common params
sensitive_params = ('key', 'private', 'password', 'secret', 'token', 'credentials')
if demisto.params():
for (k, v) in demisto.params().items():
k_lower = k.lower()
for p in sensitive_params:
if p in k_lower:
if isinstance(v, STRING_OBJ_TYPES):
self.add_replace_strs(v, b64_encode(v))
if isinstance(v, dict) and v.get('password'): # credentials object case
pswrd = v.get('password')
self.add_replace_strs(pswrd, b64_encode(pswrd))
def encode(self, message):
try:
res = str(message)
except UnicodeEncodeError as exception:
# could not decode the message
# if message is an Exception, try encode the exception's message
if isinstance(message, Exception) and message.args and isinstance(message.args[0], STRING_OBJ_TYPES):
res = message.args[0].encode('utf-8', 'replace') # type: ignore
elif isinstance(message, STRING_OBJ_TYPES):
# try encode the message itself
res = message.encode('utf-8', 'replace') # type: ignore
else:
res = "Failed encoding message with error: {}".format(exception)
for s in self.replace_strs:
res = res.replace(s, '<XX_REPLACED>')
return res
def __call__(self, message):
text = self.encode(message)
if self.buffering:
self.messages.append(text)
else:
demisto.info(text)
def add_replace_strs(self, *args):
'''
Add strings which will be replaced when logging.
Meant for avoiding passwords and so forth in the log.
'''
to_add = [self.encode(a) for a in args if a]
self.replace_strs.extend(to_add)
def set_buffering(self, state):
"""
set whether the logger buffers messages or writes staight to the demisto log
:param state: True/False
:type state: boolean
"""
self.buffering = state
def print_log(self, verbose=False):
if self.write_buf:
self.messages.append("".join(self.write_buf))
if self.messages:
text = 'Full Integration Log:\n' + '\n'.join(self.messages)
if verbose:
demisto.log(text)
demisto.info(text)
self.messages = []
def write(self, msg):
# same as __call__ but allows IntegrationLogger to act as a File like object.
msg = self.encode(msg)
has_newline = False
if '\n' in msg:
has_newline = True
# if new line is last char we trim it out
if msg[-1] == '\n':
msg = msg[:-1]
self.write_buf.append(msg)
if has_newline:
text = "".join(self.write_buf)
if self.buffering:
self.messages.append(text)
else:
demisto.info(text)
self.write_buf = []
def print_override(self, *args, **kwargs):
# print function that can be used to override print usage of internal modules
# will print to the log if the print target is stdout/stderr
try:
import __builtin__ # type: ignore
except ImportError:
# Python 3
import builtins as __builtin__ # type: ignore
file_ = kwargs.get('file')
if (not file_) or file_ == sys.stdout or file_ == sys.stderr:
kwargs['file'] = self
__builtin__.print(*args, **kwargs)
"""
a logger for python integrations:
use LOG(<message>) to add a record to the logger (message can be any object with __str__)
use LOG.print_log() to display all records in War-Room and server log.
"""
LOG = IntegrationLogger()
def formatAllArgs(args, kwds):
"""
makes a nice string representation of all the arguments
:type args: ``list``
:param args: function arguments (required)
:type kwds: ``dict``
:param kwds: function keyword arguments (required)
:return: string representation of all the arguments