-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
CommvaultSecurityIQ.py
1496 lines (1377 loc) · 54.3 KB
/
CommvaultSecurityIQ.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 json
import os
import re
import time
from copy import copy
from dataclasses import dataclass
from datetime import datetime
from tempfile import NamedTemporaryFile
from traceback import format_exc
from typing import Any
import logging
import dateparser
import requests
import syslogmp
import urllib3
import uvicorn
from fastapi import Depends, FastAPI, Request
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.security.api_key import APIKey, APIKeyHeader
from gevent.server import StreamServer
from pydantic import BaseModel # pylint: disable=no-name-in-module
from uvicorn.logging import AccessFormatter
from urllib.parse import urlparse
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa
# Disable insecure warnings
urllib3.disable_warnings() # pylint: disable=no-member
# CONSTANTS
MAX_SAMPLES = 20
BUF_SIZE = 1024
MAX_PORT: int = 65535
HTTP_ERRORS = {
400: "400 Bad Request - Incorrect or invalid parameters",
401: "401 Authentication error - Incorrect or invalid username or password",
403: "403 Forbidden - please provide valid username and password.",
404: "404 Resource not found - invalid endpoint was called.",
408: "408 Timeout - Check Server URl/Port",
410: "410 Gone - Access to the target resource is no longer available at the origin server",
500: "500 Internal Server Error - please try again after some time.",
502: "502 Bad Gateway - Could not connect to the origin server",
503: "503 Service Unavailable",
}
class Incident(BaseModel): # pylint: disable=R0903,C0115
name: str | None = None
type: str | None = None
occurred: str | None = None
raw_json: dict | None = None
client = None
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
basic_auth = HTTPBasic(auto_error=False)
token_auth = APIKeyHeader(auto_error=False, name="Authorization")
class GenericWebhookAccessFormatter(AccessFormatter):
def get_user_agent(self, scope: dict) -> str:
headers = scope.get("headers", [])
user_agent_header = list(
filter(lambda header: header[0].decode() == "user-agent", headers)
)
user_agent = ""
if len(user_agent_header) == 1:
user_agent = user_agent_header[0][1].decode()
return user_agent
def formatMessage(self, record: logging.LogRecord) -> str:
recordcopy = copy(record)
user_agent = self.get_user_agent(recordcopy.__dict__["scope"])
recordcopy.__dict__.update({"user_agent": user_agent})
return super().formatMessage(recordcopy)
@app.post("/")
async def handle_post(
incident: dict,
request: Request,
credentials: HTTPBasicCredentials = Depends(basic_auth),
token: APIKey = Depends(token_auth),
):
del credentials, token
global client
incident_type: str | None = demisto.params().get(
"incidentType", "Commvault Suspicious File Activity"
)
incident_body = handle_post_helper(client, incident, request)
if client:
client.create_incident(
incident_body, # type: ignore
datetime.fromtimestamp((datetime.utcnow() - datetime(1970, 1, 1)).total_seconds()), # type: ignore
incident_type,
False,
) # type: ignore
return "OK"
def handle_post_helper(client, incident, request):
try:
current_date = datetime.utcnow()
epoch = datetime(1970, 1, 1)
seconds_since_epoch = (current_date - epoch).total_seconds()
event_id = incident[field_mapper(Constants.event_id, Constants.source_webhook)]
event_time = incident[
field_mapper(Constants.event_time, Constants.source_webhook)
]
hostname = (
""
if (request is None) # type: ignore
or (request.client is None)
or (request.client.host is None) # type: ignore
else request.client.host # type: ignore
)
incident_body = {
"facility": Constants.facility,
"msg": None,
"msg_id": None,
"process_id": None,
"sd": {},
"timestamp": datetime.fromtimestamp(seconds_since_epoch).strftime(
"%Y-%m-%d %H:%M:%S"
),
"occurred": None,
"originating_program": incident[
field_mapper(Constants.originating_program, Constants.source_webhook)
],
"event_id": event_id,
"event_time": event_time,
"host_name": hostname,
}
inc = client.get_incident_details(incident.get("Description")) # type: ignore
if inc.get(Constants.anomaly_sub_type, "Undefined") != "File Type": # type: ignore
return {}
incident_body.update(inc) # type: ignore
return incident_body
except Exception as err:
logging.error(f"could not print REQUEST: {err}")
return {}
def get_backup_anomaly(anomaly_id: int) -> str:
"""
Get Anomaly type from anomaly id
"""
anomaly_dict = {
0: "Undefined",
1: "File Activity",
2: "File Type",
3: "Threat Analysis",
}
return anomaly_dict.get(anomaly_id, "Undefined")
def parse_no_length_limit(data: bytes) -> syslogmp.parser.Message:
"""
Get syslog parser message
"""
parser = syslogmp.parser._Parser(b"")
parser.stream = syslogmp.parser.Stream(data)
priority_value = parser._parse_pri_part()
timestamp, hostname = parser._parse_header_part()
message = parser._parse_msg_part()
return syslogmp.parser.Message(
facility=priority_value.facility,
severity=priority_value.severity,
timestamp=timestamp,
hostname=hostname,
message=message,
)
def if_zero_set_none(value: str | None | int) -> str | None | int:
"""
If the value is zero, return None
"""
if value and int(value) > 0:
return value
return None
def extract_from_regex(
message: str, default_value: str | None, *regex_string_args: str
) -> str | None:
"""
From the message, extract the strings matching the given patterns
"""
for pattern in regex_string_args:
matches = re.search(pattern, message, re.IGNORECASE)
if matches and len(matches.groups()) > 0:
return matches.group(1).strip()
return default_value
def format_alert_description(msg: str) -> str:
"""
Format alert description
"""
default_value = msg
if msg.find("<html>") != -1 and msg.find("</html>") != -1:
resp = msg[msg.find("<html>") + 6: msg.find("</html>")]
msg = resp.strip()
if msg.find("Detected ") != -1 and msg.find(" Please click ") != -1:
msg = msg[msg.find("Detected "): msg.find(" Please click ")]
return msg
return default_value
" MAIN FUNCTION "
@dataclass(frozen=True)
class Constants:
event_id: str = "event_id"
event_time: str = "event_time"
anomaly_sub_type: str = "anomaly_sub_type"
originating_client: str = "originating_client"
originating_program: str = "originating_program"
job_id: str = "job_id"
affected_files_count: str = "affected_files_count"
modified_files_count: str = "modified_files_count"
deleted_files_count: str = "deleted_files_count"
renamed_files_count: str = "renamed_files_count"
created_files_count: str = "created_files_count"
severity_high: str = "High"
facility: str = "Commvault"
severity_info: str = "Informational"
path_key: str = "path"
source_syslog: str = "syslog"
source_webhook: str = "webhook"
source_fetch_incidents: str = "fetch"
description: str = "description"
def field_mapper(field_name: str, source: str = Constants.source_syslog) -> str:
"""
Map incoming fields
:param field_name: Query by field name
:return: Return incoming field by field name
"""
field_map = {}
if source == Constants.source_syslog:
field_map[Constants.event_id] = "Event ID"
field_map[Constants.event_time] = "Event Date"
field_map[Constants.originating_program] = "Program"
if source == Constants.source_fetch_incidents:
field_map[Constants.event_id] = "id"
field_map[Constants.event_time] = "timeSource"
field_map[Constants.originating_program] = "subsystem"
if source == Constants.source_webhook:
field_map[Constants.event_id] = "Event ID"
field_map[Constants.event_time] = "Event Date"
field_map[Constants.originating_program] = "Program"
field_map[Constants.anomaly_sub_type] = "AnomalyType"
field_map[Constants.job_id] = "job"
field_map[Constants.originating_client] = "client"
field_map[Constants.affected_files_count] = "SuspiciousFileCount"
field_map[Constants.modified_files_count] = "Modified"
field_map[Constants.renamed_files_count] = "Renamed"
field_map[Constants.created_files_count] = "Created"
field_map[Constants.deleted_files_count] = "Deleted"
return field_map[field_name]
class Client(BaseClient):
"""
Client wrapper for Commvault Client
"""
job_details_body = {
"opType": 1,
"entity": {"_type_": 0},
"options": {"restoreIndex": True},
"queries": [
{
"type": 0,
"queryId": "MimeFileList",
"whereClause": [
{
"criteria": {
"field": 38,
"dataOperator": 9,
"values": ["file"],
}
},
{
"criteria": {
"field": 147,
"dataOperator": 0,
"values": ["2"],
}
},
],
"dataParam": {
"sortParam": {"ascending": True, "sortBy": [0]},
"paging": {"firstNode": 0, "pageSize": -1, "skipNode": 0},
},
},
{
"type": 1,
"queryId": "MimeFileCount",
"whereClause": [
{
"criteria": {
"field": 38,
"dataOperator": 9,
"values": ["file"],
}
},
{
"criteria": {
"field": 147,
"dataOperator": 0,
"values": ["2"],
}
},
],
"dataParam": {
"sortParam": {"ascending": True, "sortBy": [0]},
"paging": {"firstNode": 0, "pageSize": -1, "skipNode": 0},
},
},
],
"paths": [{"path": "/**/*"}],
}
access_token_expiry_in_days = 7
access_token = None
access_token_last_generation = None
current_api_token: str = ""
qsdk_token = None
keyvault_tenant_id = None
keyvault_client_id = None
keyvault_client_secret = None
keyvault_url = None
key_secret_name = "access-token-for-xsoar"
ws_url = None
def __init__(self, base_url: str, verify: bool, proxy: bool):
"""
Constructor to initialize the Commvault client object
"""
super().__init__(base_url=base_url, verify=verify, proxy=proxy)
self.qsdk_token = None
if not base_url.endswith("/"):
self.ws_url = base_url + "/"
else:
self.ws_url = base_url
def set_props(self, params):
self.keyvault_url = params.get("AzureKeyVaultUrl", {}).get("password")
self.keyvault_tenant_id = params.get("AzureKeyVaultTenantId", {}).get(
"password"
)
self.keyvault_client_id = params.get("AzureKeyVaultClientId")
self.keyvault_client_secret = params.get("AzureKeyVaultClientSecret", {}).get(
"password"
)
def get_host(self):
if self.ws_url:
domain = urlparse(self.ws_url)
if domain.netloc:
return domain.netloc.split(":")[0]
return None
@property
def headers(self) -> dict:
"""
Client headers method
Returns:
self.headers
"""
if (
not hasattr(self, "qsdk_token") or self.qsdk_token is None
): # for logging in, before self.access_token is set
return {
"Content-Type": "application/json",
"Accept": "application/json",
}
return {
"authtoken": self.qsdk_token,
"Content-Type": "application/json",
"Accept": "application/json",
}
def http_request(
self,
method: str,
endpoint: str,
params: dict | None = None,
json_data: dict[str, Any] | None = None,
ignore_empty_response: bool = False,
headers: dict | None = None,
) -> dict:
"""
Function to make http calls
"""
try:
response = self._http_request(
method=method.upper(),
url_suffix=endpoint,
headers=self.headers if (not headers) else headers,
json_data=json_data,
params=params,
resp_type="response",
return_empty_response=ignore_empty_response,
)
response.raise_for_status()
except requests.exceptions.HTTPError as exc:
error_msg = HTTP_ERRORS.get(exc.response.status_code)
if error_msg:
raise DemistoException(f"{error_msg}", res=exc.response) from exc
retval = response.json()
return retval
def validate_session_or_generate_token(self, api_token: str) -> bool:
"""
Check for last token generation and generate new token
"""
context_info = demisto.getIntegrationContext()
if "tokenDetails" in context_info:
self.access_token = context_info.get("tokenDetails", {}).get("accessToken")
self.access_token_last_generation = context_info.get(
"tokenDetails", {}
).get("accessTokenGenerationTime")
if self.access_token_last_generation is None:
demisto.debug("Token is not present, we will create new token.")
return self.generate_access_token(api_token)
else:
current_epoch = int(datetime.now().timestamp())
token_expiry_from_last_generation = int(
(
self.access_token_last_generation
+ str(self.access_token_expiry_in_days * 7 * 24 * 60 * 60)
)
)
if current_epoch > token_expiry_from_last_generation:
demisto.debug("Token is expired, re-generating")
return self.generate_access_token(api_token)
else:
self.qsdk_token = f"QSDK {self.access_token}"
return True
def generate_access_token(self, api_token: str) -> bool:
"""
Generate access token from API token
"""
new_access_token = None
auth_token = "QSDK " + api_token
self.qsdk_token = auth_token
current_epoch = int(datetime.now().timestamp())
token_expiry_epoch = (
current_epoch + self.access_token_expiry_in_days * 24 * 60 * 60
)
token_name = f"soar-crt{current_epoch}-exp{token_expiry_epoch}"
request_body = {
"tokenExpires": {"time": token_expiry_epoch},
"scope": 2,
"tokenName": token_name,
}
try:
response = self.http_request("POST", "/ApiToken/User", None, request_body)
new_access_token = response.get("token")
current_epoch = int(datetime.now().timestamp())
self.current_api_token = str(new_access_token)
self.access_token = str(new_access_token)
self.qsdk_token = f"QSDK {str(new_access_token)}"
self.access_token_last_generation = current_epoch
current_token_dict = demisto.getIntegrationContext()
current_token_dict.update(
{
"tokenDetails": {
"accessToken": str(new_access_token),
"accessTokenGenerationTime": str(current_epoch),
}
}
)
demisto.setIntegrationContext(current_token_dict)
except Exception as error:
demisto.debug(f"Could not generate access token [{error}]")
return False
return True
def prepare_globals_and_create_server(
self,
port: int,
certificate_path: str | None,
private_key_path: str | None,
) -> StreamServer:
"""
Prepares global environments of LOG_FORMAT and creates the server to listen
to Syslog messages.
Args:
port (int): Port
certificate_path (Optional[str]): Certificate path. For SSL connection.
private_key_path (Optional[str]): Private key path. For SSL connection.
Returns:
(StreamServer): Server to listen to Syslog messages.
"""
if certificate_path and private_key_path:
server = StreamServer(
("0.0.0.0", port), # disable-secrets-detection
self.perform_long_running_execution,
keyfile=private_key_path,
certfile=certificate_path,
)
else:
server = StreamServer(
("0.0.0.0", port), # disable-secrets-detection
self.perform_long_running_execution,
)
return server
def perform_long_running_execution(self, sock: Any, address: tuple) -> None:
"""
The long running execution loop. Gets input, and performs a while True loop
and logs any error that happens.
Stops when there is no more data to read.
Args:
sock: Socket.
address(tuple): Address. Not used inside loop so marked as underscore.
Returns:
(None): Reads data, calls that creates incidents from inputted data.
"""
file_obj = sock.makefile(mode="rb")
try:
while True:
try:
line = file_obj.readline()
if not line:
demisto.info(f"Disconnected from {address}")
break
self.perform_long_running_loop(line.strip())
except Exception as error:
demisto.error(traceback.format_exc()) # print the traceback
demisto.error(
f"Error occurred during long running loop. Error was: {error}"
)
finally:
file_obj.close()
def perform_long_running_loop(self, socket_data: bytes) -> None:
"""
Function to start long running loop
"""
incident_type: str = demisto.params().get(
"incidentType", "Commvault Suspicious File Activity"
)
extracted_message = self.parse_incoming_message(socket_data)
if extracted_message:
demisto.debug("Succeeded in parsing the message ")
else:
demisto.debug("Failed in parsing the message ")
if extracted_message:
dts = datetime.fromisoformat(str(extracted_message.get("timestamp")))
self.create_incident(extracted_message, dts, incident_type, False)
def create_incident(
self,
extracted_message: Union[list, dict[str, Any]],
date_obj: datetime,
incident_type: str,
is_fetch: bool,
) -> None:
"""
Function to start create incidents
"""
date_str = date_obj.strftime("%d %B, %Y, %H:%M:%S")
incidents = []
if type(extracted_message) != list:
extracted_message = [extracted_message]
for message_ in extracted_message:
incident = {
"name": f"Suspicious File Activity Detected at [{date_str}]",
"rawJSON": json.dumps(message_),
"occurred": message_.get("occurred"),
"type": incident_type,
"details": "\n".join([f"{k}: {v}" for k, v in message_.items() if v]),
}
if message_.get(Constants.anomaly_sub_type, "Undefined") == "File Type":
incidents.append(incident)
if is_fetch:
demisto.incidents(incidents)
# self.define_indicator(extracted_message.get("originating_client"))
else:
demisto.createIncidents(incidents)
# self.define_indicator(extracted_message.get("originating_client"))
def get_events_list(self, last_run, first_fetch_time, max_fetch) -> Optional[Any]:
"""
Function to get events
"""
self.validate_session_or_generate_token(self.current_api_token)
current_date = datetime.utcnow()
epoch = datetime(1970, 1, 1)
seconds_since_epoch = int((current_date - epoch).total_seconds())
fromtime = last_run
if fromtime is None:
fromtime = str(dateparser.parse(first_fetch_time))
fromtime = int(time.mktime(datetime.fromisoformat(fromtime).timetuple()))
ustring = (
"/events?level=10&showInfo=false&showMinor=false&"
"showMajor=true&showCritical=false&"
"showAnomalous=true"
)
event_endpoint = f"{ustring}&fromTime={fromtime}&toTime={seconds_since_epoch}" # disable-secrets-detection
headers = self.headers
if max_fetch is None:
max_fetch = 50
headers["pagingInfo"] = f"0,{max_fetch}"
resp = self.http_request("GET", event_endpoint, None, headers=headers)
if resp and resp.get("commservEvents"):
return resp.get("commservEvents")
return None
def get_subclient_content_list(self, subclient_id: Union[int, str]) -> dict:
"""
Get content from subclient
:param subclient_id: subclient Id
:return: string
"""
self.validate_session_or_generate_token(self.current_api_token)
resp = self.http_request("GET", "/Subclient/" + str(subclient_id), None)
resp = resp.get("subClientProperties", [{}])[0].get("content")
return resp
def define_severity(self, anomaly_sub_type: str) -> str | None:
"""
Function to get severity from anomaly sub type
"""
severity = None
if anomaly_sub_type in ("File Type", "Threat Analysis"):
severity = Constants.severity_high
elif anomaly_sub_type == "File Activity":
severity = Constants.severity_info
return severity
def fetch_file_details(
self, job_id: Union[int, str] | None, subclient_id: Union[int, str]
) -> tuple[list, list]:
"""
Function to fetch the scanned folders list during the backup job
"""
folders_list = []
if job_id is None:
return [], []
files_list = self.get_files_list(job_id)
folder_response = self.get_subclient_content_list(subclient_id)
for resp in folder_response:
folders_list.append(resp[Constants.path_key])
return files_list, folders_list
"""def define_indicator(self, originating_client: str) -> None:
Define an indicator
:param originating_client: client which has generated the event
indicator_list = []
indicator_list.append(
{
"value": f"client [{originating_client}]",
"type": "Client",
"score": 2,
"rawJSON": {
"value": f"client [{originating_client}]",
"type": "Client",
"verdict": "suspicious",
"score": 2,
},
}
)
demisto.createIndicators(indicator_list)"""
def parse_incoming_message(self, log_message: bytes) -> dict | None:
"""
Function to parse incoming message from syslog
"""
try:
syslog_message: syslogmp.Message = parse_no_length_limit(log_message)
self.validate_session_or_generate_token(self.current_api_token)
message = syslog_message.message.decode("utf-8")
event_time = extract_from_regex(
message,
"",
"#011 {}: (.*?)#011".format(
field_mapper(Constants.event_time, Constants.source_syslog)
),
)
event_id = extract_from_regex(
message,
"",
"#011 {}: (.*?)#011".format(
field_mapper(Constants.event_id, Constants.source_syslog)
),
)
incident = {
"facility": Constants.facility,
"host_name": syslog_message.hostname,
"msg": None,
"msg_id": None,
"process_id": None,
"sd": {},
"timestamp": syslog_message.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
"occurred": None,
"event_time": event_time,
"event_id": event_id,
"originating_program": extract_from_regex(
message,
"",
r"{}: ([\w]+)+:?".format(
field_mapper(
Constants.originating_program, Constants.source_syslog
)
),
),
}
inc = self.get_incident_details(message) # type: ignore
if inc.get(Constants.anomaly_sub_type, "Undefined") != "File Type": # type: ignore
return None
incident.update(inc) # type: ignore
return incident
except syslogmp.parser.MessageFormatError as error:
demisto.debug(
f"Could not parse the log message, got MessageFormatError. Error was: {error}"
)
return None
def get_incident_details(self, message: str) -> dict | None:
"""
Function to get incident details from the alert description
"""
anomaly_sub_type = extract_from_regex(
message,
"0",
rf"{field_mapper(Constants.anomaly_sub_type)}:\[(.*?)\]",
)
if anomaly_sub_type is None or anomaly_sub_type == "0":
return None
anomaly_sub_type = get_backup_anomaly(int(anomaly_sub_type))
job_id = extract_from_regex(
message,
"0",
rf"{field_mapper(Constants.job_id)} \[(.*?)\]",
)
description = format_alert_description(message)
job_details = self.get_job_details(job_id)
if job_details is None:
demisto.info(f"Invalid job [{job_id}]")
return None
job_start_time = int(
job_details.get("jobs", [{}])[0].get("jobSummary", {}).get("jobStartTime")
)
job_end_time = int(
job_details.get("jobs", [{}])[0].get("jobSummary", {}).get("jobEndTime")
)
subclient_id = (
job_details.get("jobs", [{}])[0]
.get("jobSummary", {})
.get("subclient", {})
.get("subclientId")
)
files_list, scanned_folder_list = self.fetch_file_details(job_id, subclient_id)
details = {
"subclient_id": subclient_id,
"files_list": files_list,
"scanned_folder_list": scanned_folder_list,
"anomaly_sub_type": anomaly_sub_type,
"severity": self.define_severity(anomaly_sub_type),
"originating_client": extract_from_regex(
message,
"",
r"{} \[(.*?)\]".format(field_mapper(Constants.originating_client)),
),
"affected_files_count": if_zero_set_none(
extract_from_regex(
message,
None,
r"{}:\[(.*?)\]".format(
field_mapper(Constants.affected_files_count)
),
)
),
"modified_files_count": if_zero_set_none(
extract_from_regex(
message,
None,
r"{}FileCount:\[(.*?)\]".format(
field_mapper(Constants.modified_files_count)
),
)
),
"deleted_files_count": if_zero_set_none(
extract_from_regex(
message,
None,
r"{}FileCount:\[(.*?)\]".format(
field_mapper(Constants.deleted_files_count)
),
)
),
"renamed_files_count": if_zero_set_none(
extract_from_regex(
message,
None,
r"{}FileCount:\[(.*?)\]".format(
field_mapper(Constants.renamed_files_count)
),
)
),
"created_files_count": if_zero_set_none(
extract_from_regex(
message,
None,
r"{}FileCount:\[(.*?)\]".format(
field_mapper(Constants.created_files_count)
),
)
),
"job_start_time": datetime.utcfromtimestamp(job_start_time).strftime(
"%Y-%m-%d %H:%M:%S"
),
"job_end_time": datetime.utcfromtimestamp(job_end_time).strftime(
"%Y-%m-%d %H:%M:%S"
),
"job_id": job_id,
"external_link": extract_from_regex(
message, "", "href='(.*?)'", 'href="(.*?)"'
),
"description": description,
}
return details
def get_job_details(self, job_id: Union[int, str] | None) -> dict | None:
"""
Get job details by job Id
:param job_id: Job Id
:return: string
"""
out = None
self.validate_session_or_generate_token(self.current_api_token)
response = self.http_request("GET", "/Job/" + str(job_id), None)
if ("totalRecordsWithoutPaging" in response) and (
int(response["totalRecordsWithoutPaging"]) > 0
):
out = response
return out
def get_files_list(self, job_id: Union[int, str]) -> list:
"""
Get file list from analysis job
:param job_id: Job Id
:return: list
"""
self.job_details_body["advOptions"] = {
"advConfig": {"browseAdvancedConfigBrowseByJob": {"jobId": int(job_id)}}
}
self.validate_session_or_generate_token(self.current_api_token)
resp = self.http_request("POST", "/DoBrowse", None, self.job_details_body)
browse_responses = resp.get("browseResponses", [])
file_list = []
for browse_resp in browse_responses:
if browse_resp.get("respType") == 0:
browse_result = browse_resp.get("browseResult")
if "dataResultSet" in browse_result:
for data_result_set in browse_result.get("dataResultSet"):
file = {}
filepath = data_result_set.get("path")
file["sizeinkb"] = data_result_set.get("size")
file["folder"] = "\\".join(filepath.split("\\")[:-1])
file["filename"] = data_result_set.get("displayName")
file_list.append(file)
return file_list
def get_key_vault_access_token(self) -> str | None:
"""
Get access token to get/set secret in azure keyvault
:return:
"""
access_token = None
try:
url = f"https://login.microsoftonline.com/{self.keyvault_tenant_id}/oauth2/token" # disable-secrets-detection
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = {
"grant_type": "client_credentials",
"client_id": self.keyvault_client_id,
"client_secret": self.keyvault_client_secret,
"resource": "https://vault.azure.net", # disable-secrets-detection
}
demisto.debug("Trying to login to keyvault...")
response = requests.post(url, headers=headers, data=data)
access_token = response.json().get("access_token")
except Exception as error:
demisto.debug(
f"Failed to generate the access token to connect to Azure Keyvault due to [{error}]"
)
return access_token
def get_secret_from_key_vault(self) -> str | None:
"""
Read secret from key vault
:return:
"""
secret = None
keyvault_access_token = self.get_key_vault_access_token()
url = f"{self.keyvault_url}/secrets/{self.key_secret_name}?api-version=7.2"
headers = {"Authorization": f"Bearer {keyvault_access_token}"}
response = requests.get(url, headers=headers)
response_json = response.json()
if "error" in response_json:
if "was not found in this key vault" in response_json.get("error", {}).get(
"message", ""
):
secret = None
else:
secret = response_json.get("value")
return secret
def set_secret_in_key_vault(self, secret_key_value: str) -> bytes:
"""
Set secret in azure key vault
:return:
"""
keyvault_access_token = self.get_key_vault_access_token()
endpoint = f"{self.keyvault_url}/secrets/{self.key_secret_name}?api-version=7.2"
headers = {
"Authorization": f"Bearer {keyvault_access_token}",
"Content-Type": "application/json",
}
body = {"value": secret_key_value}
response = requests.put(endpoint, headers=headers, json=body)
return response.content
def disable_providers(self, identity_server_name: str) -> bool:
"""
:param identity_server_name: Identity Server to disable
:return: True/False
"""
not_enable = False
try:
self.validate_session_or_generate_token(self.current_api_token)
response = self.http_request("GET", f"/V4/SAML/{identity_server_name}")
if "error" in response:
demisto.debug(
f"Error [{response.get('error',{}).get('errorString','')}]"
)
return False
if response.get("enabled"):
demisto.debug(
f"SAML is enabled for identity server [{identity_server_name}]. Going to disable it"
)
body = {"enabled": not_enable, "type": "SAML"}
response = self.http_request(
"PUT",
f"/V4/SAML/{identity_server_name}",
json_data=body,
)
if response.get("errorCode", 0) > 0:
demisto.debug(
f"Could not disable as [{response.get('errMessage')}]"
)
return False
except Exception as error:
demisto.debug(f"Could not disable identity provider due to [{error}]")
return False
return True
def fetch_and_disable_saml_identity_provider(self) -> bool:
"""
Fetch SAML Providers and disable them
"""
self.validate_session_or_generate_token(self.current_api_token)
response = self.http_request("GET", "/IdentityServers")
if "errorMessage" in response:
return False
identity_servers = []
if "identityServers" in response:
identity_servers = response["identityServers"]
saml_identity_servers = [s for s in identity_servers if s.get("type") == 1]
for identity_server_info in saml_identity_servers:
identity_server_name = identity_server_info.get("IdentityServerName")