-
Notifications
You must be signed in to change notification settings - Fork 4
/
CommonServerPython.py
11292 lines (8957 loc) · 414 KB
/
CommonServerPython.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
"""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
"""
# If you change this section, make sure you update the line offset magic number
from __future__ import print_function
import base64
import gc
import json
import logging
import os
import re
import socket
import sys
import time
import traceback
import types
import urllib
import gzip
import ssl
from random import randint
import xml.etree.cElementTree as ET
from collections import OrderedDict
from datetime import datetime, timedelta
from abc import abstractmethod
from distutils.version import LooseVersion
from threading import Lock
from inspect import currentframe
import demistomock as demisto
import warnings
def __line__():
cf = currentframe()
return cf.f_back.f_lineno # type: ignore[union-attr]
# 43 - The line offset from the beginning of the file.
_MODULES_LINE_MAPPING = {
'CommonServerPython': {'start': __line__() - 43, 'end': float('inf')},
}
XSIAM_EVENT_CHUNK_SIZE = 2 ** 20 # 1 Mib
def register_module_line(module_name, start_end, line, wrapper=0):
"""
Register a module in the line mapping for the traceback line correction algorithm.
:type module_name: ``str``
:param module_name: The name of the module. (required)
:type start_end: ``str``
:param start_end: Whether to register the line as the start or the end of the module.
Possible values: start, end. (required)
:type line: ``int``
:param line: the line number to record. (required)
:type wrapper: ``int``
:param wrapper: Wrapper size (used for inline replacements with headers such as ApiModules). (optional)
:return: None
:rtype: ``None``
"""
global _MODULES_LINE_MAPPING
default_module_info = {'start': 0, 'start_wrapper': 0, 'end': float('inf'), 'end_wrapper': float('inf')}
try:
if start_end not in ('start', 'end'):
raise ValueError('Invalid start_end argument. Acceptable values are: start, end.')
if not isinstance(line, int) or line < 0:
raise ValueError('Invalid line argument. Expected non-negative integer, '
'got {}({})'.format(type(line), line))
_MODULES_LINE_MAPPING.setdefault(module_name, default_module_info).update(
{start_end: line, '{}_wrapper'.format(start_end): line + wrapper}
)
except Exception as exc:
demisto.info(
'failed to register module line. '
'module: "{}" start_end: "{}" line: "{}".\nError: {}'.format(module_name, start_end, line, exc))
def _find_relevant_module(line):
"""
Find which module contains the given line number.
:type line: ``int``
:param trace_str: Line number to search. (required)
:return: The name of the module.
:rtype: ``str``
"""
global _MODULES_LINE_MAPPING
relevant_module = ''
for module, info in _MODULES_LINE_MAPPING.items():
if info['start'] <= line <= info['end']:
if not relevant_module:
relevant_module = module
elif info['start'] > _MODULES_LINE_MAPPING[relevant_module]['start']:
relevant_module = module
return relevant_module
def fix_traceback_line_numbers(trace_str):
"""
Fixes the given traceback line numbers.
:type trace_str: ``str``
:param trace_str: The traceback string to edit. (required)
:return: The new formated traceback.
:rtype: ``str``
"""
def is_adjusted_block(start, end, adjusted_lines):
return any(
block_start < start < end < block_end
for block_start, block_end in adjusted_lines.items()
)
for number in re.findall(r'line (\d+)', trace_str):
line_num = int(number)
module = _find_relevant_module(line_num)
if module:
module_start_line = _MODULES_LINE_MAPPING.get(module, {'start': 0})['start']
actual_number = line_num - module_start_line
# in case of ApiModule injections, adjust the line numbers of the code after the injection
# should avoid adjust ApiModule twice in case of ApiModuleA -> import ApiModuleB
adjusted_lines = {} # type: ignore[var-annotated]
modules_info = list(_MODULES_LINE_MAPPING.values())
modules_info.sort(key=lambda obj: int(obj.get('start_wrapper', obj['start'])))
for module_info in modules_info:
block_start = module_info.get('start_wrapper', module_info['start'])
block_end = module_info.get('end_wrapper', module_info['end'])
if block_start > module_start_line and block_end < line_num \
and not is_adjusted_block(block_start, block_end, adjusted_lines):
actual_number -= block_end - block_start
adjusted_lines[block_start] = block_end
# a traceback line is of the form: File "<string>", line 8853, in func5
trace_str = trace_str.replace(
'File "<string>", line {},'.format(number),
'File "<{}>", line {},'.format(module, actual_number)
)
return trace_str
OS_LINUX = False
OS_MAC = False
OS_WINDOWS = False
if sys.platform.startswith('linux'):
OS_LINUX = True
elif sys.platform.startswith('darwin'):
OS_MAC = True
elif sys.platform.startswith('win32'):
OS_WINDOWS = True
class WarningsHandler(object):
# Wrapper to handle warnings. We use a class to cleanup after execution
@staticmethod
def handle_warning(message, category, filename, lineno, file=None, line=None):
try:
msg = warnings.formatwarning(message, category, filename, lineno, line)
demisto.info("python warning: " + msg)
except Exception:
# ignore the warning if it can't be handled for some reason
pass
def __init__(self):
self.org_handler = warnings.showwarning
warnings.showwarning = WarningsHandler.handle_warning
def __del__(self):
warnings.showwarning = self.org_handler
_warnings_handler = WarningsHandler()
# ignore warnings from logging as a result of not being setup
logging.raiseExceptions = False
# imports something that can be missed from docker image
try:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from typing import Optional, Dict, List, Any, Union, Set
from urllib3 import disable_warnings
disable_warnings()
import dateparser # type: ignore
from datetime import timezone # type: ignore
except Exception:
if sys.version_info[0] < 3:
# in python 2 an exception in the imports might still be raised even though it is caught.
# for more info see https://cosmicpercolator.com/2016/01/13/exception-leaks-in-python-2-and-3/
sys.exc_clear()
CONTENT_RELEASE_VERSION = '0.0.0'
CONTENT_BRANCH_NAME = 'master'
IS_PY3 = sys.version_info[0] == 3
PY_VER_MINOR = sys.version_info[1]
STIX_PREFIX = "STIX "
# pylint: disable=undefined-variable
ZERO = timedelta(0)
HOUR = timedelta(hours=1)
# The max number of profiling related rows to print to the log on memory dump
PROFILING_DUMP_ROWS_LIMIT = 20
if IS_PY3:
STRING_TYPES = (str, bytes) # type: ignore
STRING_OBJ_TYPES = (str,)
else:
STRING_TYPES = (str, unicode) # type: ignore # noqa: F821
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
}
ENDPOINT_STATUS_OPTIONS = [
'Online',
'Offline',
'Unknown'
]
ENDPOINT_ISISOLATED_OPTIONS = [
'Yes',
'No',
'Pending isolation',
'Pending unisolation'
]
class EntryType(object):
"""
Enum: contains all the entry types (e.g. NOTE, ERROR, WARNING, FILE, etc.)
:return: None
:rtype: ``None``
"""
NOTE = 1
DOWNLOAD_AGENT = 2
FILE = 3
ERROR = 4
PINNED = 5
USER_MANAGEMENT = 6
IMAGE = 7
PLAYGROUND_ERROR = 8
ENTRY_INFO_FILE = 9
VIDEO_FILE = 10
WARNING = 11
STATIC_VIDEO_FILE = 12
MAP_ENTRY_TYPE = 15
WIDGET = 17
EXECUTION_METRICS = 19
class IncidentStatus(object):
"""
Enum: contains all the incidents status types (e.g. pending, active, done, archive)
:return: None
:rtype: ``None``
"""
PENDING = 0
ACTIVE = 1
DONE = 2
ARCHIVE = 3
class IncidentSeverity(object):
"""
Enum: contains all the incident severity types
:return: None
:rtype: ``None``
"""
UNKNOWN = 0
INFO = 0.5
LOW = 1
MEDIUM = 2
HIGH = 3
CRITICAL = 4
# 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
DBotScoreType.CVE
DBotScoreType.ACCOUNT
DBotScoreType.CRYPTOCURRENCY
DBotScoreType.EMAIL
DBotScoreType.ATTACKPATTERN
DBotScoreType.CUSTOM
:return: None
:rtype: ``None``
"""
IP = 'ip'
FILE = 'file'
DOMAIN = 'domain'
URL = 'url'
CVE = 'cve'
ACCOUNT = 'account'
CIDR = 'cidr',
DOMAINGLOB = 'domainglob'
CERTIFICATE = 'certificate'
CRYPTOCURRENCY = 'cryptocurrency'
EMAIL = 'email'
ATTACKPATTERN = 'attackpattern'
CUSTOM = 'custom'
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,
DBotScoreType.CVE,
DBotScoreType.ACCOUNT,
DBotScoreType.CIDR,
DBotScoreType.DOMAINGLOB,
DBotScoreType.CERTIFICATE,
DBotScoreType.CRYPTOCURRENCY,
DBotScoreType.EMAIL,
DBotScoreType.ATTACKPATTERN,
DBotScoreType.CUSTOM,
)
class DBotScoreReliability(object):
"""
Enum: Source reliability levels
Values are case sensitive
:return: None
:rtype: ``None``
"""
A_PLUS = 'A+ - 3rd party enrichment'
A = 'A - Completely reliable'
B = 'B - Usually reliable'
C = 'C - Fairly reliable'
D = 'D - Not usually reliable'
E = 'E - Unreliable'
F = 'F - Reliability cannot be judged'
def __init__(self):
# required to create __init__ for create_server_docs.py purpose
pass
@staticmethod
def is_valid_type(_type):
# type: (str) -> bool
return _type in (
DBotScoreReliability.A_PLUS,
DBotScoreReliability.A,
DBotScoreReliability.B,
DBotScoreReliability.C,
DBotScoreReliability.D,
DBotScoreReliability.E,
DBotScoreReliability.F,
)
@staticmethod
def get_dbot_score_reliability_from_str(reliability_str):
if reliability_str == DBotScoreReliability.A_PLUS:
return DBotScoreReliability.A_PLUS
elif reliability_str == DBotScoreReliability.A:
return DBotScoreReliability.A
elif reliability_str == DBotScoreReliability.B:
return DBotScoreReliability.B
elif reliability_str == DBotScoreReliability.C:
return DBotScoreReliability.C
elif reliability_str == DBotScoreReliability.D:
return DBotScoreReliability.D
elif reliability_str == DBotScoreReliability.E:
return DBotScoreReliability.E
elif reliability_str == DBotScoreReliability.F:
return DBotScoreReliability.F
raise Exception("Please use supported reliability only.")
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 ErrorTypes(object):
"""
Enum: contains all the available error types
:return: None
:rtype: ``None``
"""
SUCCESS = 'Successful'
QUOTA_ERROR = 'QuotaError'
GENERAL_ERROR = 'GeneralError'
AUTH_ERROR = 'AuthError'
SERVICE_ERROR = 'ServiceError'
CONNECTION_ERROR = 'ConnectionError'
PROXY_ERROR = 'ProxyError'
SSL_ERROR = 'SSLError'
TIMEOUT_ERROR = 'TimeoutError'
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"
AS = "ASN"
MUTEX = "Mutex"
Malware = "Malware"
Identity = "Identity"
Location = "Location"
Software = "Software"
@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,
FeedIndicatorType.AS,
FeedIndicatorType.MUTEX,
FeedIndicatorType.Malware,
FeedIndicatorType.Identity,
FeedIndicatorType.Location,
FeedIndicatorType.Software
)
@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.
:return:: Indicator type from FeedIndicatorType, or None if invalid IP address.
:rtype: ``str``
"""
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
@staticmethod
def indicator_type_by_server_version(indicator_type):
"""Returns the indicator type of the input by the server version.
If the server version is 6.2 and greater, remove the STIX prefix of the type
:type indicator_type: ``str``
:param indicator_type: Type of an indicator.
:return:: Indicator type .
:rtype: ``str``
"""
if is_demisto_version_ge("6.2.0") and indicator_type.startswith(STIX_PREFIX):
return indicator_type[len(STIX_PREFIX):]
return indicator_type
# -------------------------------- Threat Intel Objects ----------------------------------- #
class ThreatIntel:
"""
XSOAR Threat Intel Objects
:return: None
:rtype: ``None``
"""
class ObjectsNames(object):
"""
Enum: Threat Intel Objects names.
:return: None
:rtype: ``None``
"""
CAMPAIGN = 'Campaign'
ATTACK_PATTERN = 'Attack Pattern'
REPORT = 'Report'
MALWARE = 'Malware'
COURSE_OF_ACTION = 'Course of Action'
INTRUSION_SET = 'Intrusion Set'
TOOL = 'Tool'
THREAT_ACTOR = 'Threat Actor'
INFRASTRUCTURE = 'Infrastructure'
class ObjectsScore(object):
"""
Enum: Threat Intel Objects Score.
:return: None
:rtype: ``None``
"""
CAMPAIGN = 3
ATTACK_PATTERN = 2
REPORT = 3
MALWARE = 3
COURSE_OF_ACTION = 0
INTRUSION_SET = 3
TOOL = 2
THREAT_ACTOR = 3
INFRASTRUCTURE = 2
class KillChainPhases(object):
"""
Enum: Kill Chain Phases names.
:return: None
:rtype: ``None``
"""
BUILD_CAPABILITIES = "Build Capabilities"
PRIVILEGE_ESCALATION = "Privilege Escalation"
ADVERSARY_OPSEC = "Adversary Opsec"
CREDENTIAL_ACCESS = "Credential Access"
EXFILTRATION = "Exfiltration"
LATERAL_MOVEMENT = "Lateral Movement"
DEFENSE_EVASION = "Defense Evasion"
PERSISTENCE = "Persistence"
COLLECTION = "Collection"
IMPACT = "Impact"
INITIAL_ACCESS = "Initial Access"
DISCOVERY = "Discovery"
EXECUTION = "Execution"
INSTALLATION = "Installation"
DELIVERY = "Delivery"
WEAPONIZATION = "Weaponization"
ACT_ON_OBJECTIVES = "Actions on Objectives"
COMMAND_AND_CONTROL = "Command \u0026 Control"
def is_debug_mode():
"""Return if this script/command was passed debug-mode=true option
:return: true if debug-mode is enabled
:rtype: ``bool``
"""
# use `hasattr(demisto, 'is_debug')` to ensure compatibility with server version <= 4.5
return hasattr(demisto, 'is_debug') and demisto.is_debug
def get_schedule_metadata(context):
"""
Get the entry schedule metadata if available
:type context: ``dict``
:param context: Context in which the command was executed.
:return: Dict with metadata of scheduled entry
:rtype: ``dict``
"""
schedule_metadata = {}
parent_entry = context.get('ParentEntry', {})
if parent_entry:
schedule_metadata = assign_params(
is_polling=True if parent_entry.get('polling') else False,
polling_command=parent_entry.get('pollingCommand'),
polling_args=parent_entry.get('pollingArgs'),
times_ran=int(parent_entry.get('timesRan', 0)) + 1,
start_date=parent_entry.get('startDate'),
end_date=parent_entry.get('endingDate')
)
return schedule_metadata
def auto_detect_indicator_type(indicator_value):
"""
Infer the type of the indicator.
:type indicator_value: ``str``
:param indicator_value: The indicator whose type we want to check. (required)
:return: The type of the indicator.
:rtype: ``str``
"""
try:
import tldextract
except Exception:
raise Exception("Missing tldextract module, In order to use the auto detect function please use a docker"
" image with it installed such as: demisto/jmespath")
indicator_value = indicator_value.replace('[.]', '.').replace('[@]', '@') # Refang indicator prior to checking
if re.match(ipv4cidrRegex, indicator_value):
return FeedIndicatorType.CIDR
if re.match(ipv6cidrRegex, indicator_value):
return FeedIndicatorType.IPv6CIDR
if re.match(ipv4Regex, indicator_value):
return FeedIndicatorType.IP
if re.match(ipv6Regex, indicator_value):
return FeedIndicatorType.IPv6
if re.match(cveRegex, indicator_value):
return FeedIndicatorType.CVE
if re.match(md5Regex, indicator_value):
return FeedIndicatorType.File
if re.match(sha1Regex, indicator_value):
return FeedIndicatorType.File
if re.match(sha256Regex, indicator_value):
return FeedIndicatorType.File
if re.match(sha512Regex, indicator_value):
return FeedIndicatorType.File
if re.match(emailRegex, indicator_value):
return FeedIndicatorType.Email
if re.match(urlRegex, indicator_value):
return FeedIndicatorType.URL
try:
tldextract_version = tldextract.__version__
if LooseVersion(tldextract_version) < '3.0.0':
no_cache_extract = tldextract.TLDExtract(cache_file=False, suffix_list_urls=None)
else:
no_cache_extract = tldextract.TLDExtract(cache_dir=False, suffix_list_urls=None)
if no_cache_extract(indicator_value).suffix:
if '*' in indicator_value:
return FeedIndicatorType.DomainGlob
return FeedIndicatorType.Domain
except Exception:
demisto.debug('tldextract failed to detect indicator type. indicator value: {}'.format(indicator_value))
demisto.debug('Failed to detect indicator type. Indicator value: {}'.format(indicator_value))
return None
def add_http_prefix_if_missing(address=''):
"""
This function adds `http://` prefix to the proxy address in case it is missing.
:type address: ``string``
:param address: Proxy address.
:return: proxy address after the 'http://' prefix was added, if needed.
:rtype: ``string``
"""
PROXY_PREFIXES = ['http://', 'https://', 'socks5://', 'socks5h://', 'socks4://', 'socks4a://']
if not address:
return ''
for prefix in PROXY_PREFIXES:
if address.startswith(prefix):
return address
return 'http://' + address
def handle_proxy(proxy_param_name='proxy', checkbox_default_value=False, handle_insecure=True,
insecure_param_name=None):
"""
Handle logic for routing traffic through the system proxy.
Should usually be called at the beginning of the integration, depending on proxy checkbox state.
Additionally will unset env variables REQUESTS_CA_BUNDLE and CURL_CA_BUNDLE if handle_insecure is speficied (default).
This is needed as when these variables are set and a requests.Session object is used, requests will ignore the
Sesssion.verify setting. See: https://github.com/psf/requests/blob/master/requests/sessions.py#L703
: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
:type handle_insecure: ``bool``
:param handle_insecure: Whether to check the insecure param and unset env variables
:type insecure_param_name: ``string``
:param insecure_param_name: Name of insecure param. If None will search insecure and unsecure
:return: proxies dict for the 'proxies' parameter of 'requests' functions
:rtype: ``dict``
"""
proxies = {} # type: dict
if demisto.params().get(proxy_param_name, checkbox_default_value):
ensure_proxy_has_http_prefix()
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:
skip_proxy()
if handle_insecure:
if insecure_param_name is None:
param_names = ('insecure', 'unsecure')
else:
param_names = (insecure_param_name,) # type: ignore[assignment]
for p in param_names:
if demisto.params().get(p, False):
skip_cert_verification()
return proxies
def skip_proxy():
"""
The function deletes the proxy environment vars in order to http requests to skip routing through proxy
:return: None
:rtype: ``None``
"""
for k in ('HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'):
if k in os.environ:
del os.environ[k]
def ensure_proxy_has_http_prefix():
"""
The function checks if proxy environment vars are missing http/https prefixes, and adds http if so.
:return: None
:rtype: ``None``
"""
for k in ('HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'):
if k in os.environ:
proxy_env_var = os.getenv(k)
if proxy_env_var:
os.environ[k] = add_http_prefix_if_missing(os.environ[k])
def skip_cert_verification():
"""
The function deletes the self signed certificate env vars in order to http requests to skip certificate validation.
:return: None
:rtype: ``None``
"""
for k in ('REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE'):
if k in os.environ:
del os.environ[k]
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
:return: Full joined url
:rtype: ``string``
"""
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]