-
Notifications
You must be signed in to change notification settings - Fork 95
/
zircolite.py
executable file
·2713 lines (2497 loc) · 102 KB
/
zircolite.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
#!python3
# Standard libs
import argparse
import asyncio
import base64
import chardet
import csv
import functools
import hashlib
import logging
import multiprocessing as mp
import os
import random
import re
import shutil
import signal
import socket
import sqlite3
import string
import subprocess
import sys
import time
from pathlib import Path
from sqlite3 import Error
from sys import platform as _platform
# External libs (Mandatory)
import orjson as json
import xxhash
from colorama import Fore
from tqdm import tqdm
from tqdm.asyncio import tqdm as tqdmAsync
from RestrictedPython import compile_restricted
from RestrictedPython import safe_builtins
from RestrictedPython import limited_builtins
from RestrictedPython import utility_builtins
from RestrictedPython.Eval import default_guarded_getiter
from RestrictedPython.Guards import guarded_iter_unpack_sequence
# External libs (Optional)
forwardingDisabled = False
try:
import aiohttp
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except ImportError:
forwardingDisabled = True
elasticForwardingDisabled = False
try:
from elasticsearch import AsyncElasticsearch
except ImportError:
elasticForwardingDisabled = True
updateDisabled = False
try:
import requests
except ImportError:
forwardingDisabled = True
updateDisabled = True
sigmaConversionDisabled = False
try:
from sigma.collection import SigmaCollection
from sigma.backends.sqlite import sqlite
from sigma.processing.resolver import ProcessingPipelineResolver
from sigma.plugins import InstalledSigmaPlugins
import yaml
except ImportError:
sigmaConversionDisabled = True
pyevtxDisabled = False
try:
from evtx import PyEvtxParser
except ImportError:
pyevtxDisabled = True
jinja2Disabled = False
try:
from jinja2 import Template
except ImportError:
jinja2Disabled = True
xmlImportDisabled = False
try:
from lxml import etree
except ImportError:
xmlImportDisabled = True
def signal_handler(sig, frame):
print("[-] Execution interrupted !")
sys.exit(0)
def quitOnError(message, logger=None):
logger.error(message)
sys.exit(1)
def checkIfExists(path, errorMessage, logger=None):
"""Test if path provided is a file"""
if not (Path(path).is_file()):
quitOnError(errorMessage, logger)
def initLogger(debugMode, logFile=None):
fileLogLevel = logging.INFO
fileLogFormat = "%(asctime)s %(levelname)-8s %(message)s"
if debugMode:
fileLogLevel = logging.DEBUG
fileLogFormat = (
"%(asctime)s %(levelname)-8s %(module)s:%(lineno)s %(funcName)s %(message)s"
)
if logFile is not None:
logging.basicConfig(
format=fileLogFormat,
filename=logFile,
level=fileLogLevel,
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.StreamHandler()
formatter = logging.Formatter("%(message)s")
logger.setFormatter(formatter)
logger.setLevel(logging.INFO)
logging.getLogger().addHandler(logger)
else:
logging.basicConfig(
format="%(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S"
)
return logging.getLogger()
class templateEngine:
def __init__(self, logger=None, template=[], templateOutput=[], timeField=""):
self.logger = logger or logging.getLogger(__name__)
self.template = template
self.templateOutput = templateOutput
self.timeField = timeField
def generateFromTemplate(self, templateFile, outputFilename, data):
"""Use Jinja2 to output data in a specific format"""
try:
tmpl = open(templateFile, "r", encoding="utf-8")
template = Template(tmpl.read())
with open(outputFilename, "a", encoding="utf-8") as tpl:
tpl.write(template.render(data=data, timeField=self.timeField))
except Exception as e:
self.logger.error(
f"{Fore.RED} [-] Template error, activate debug mode to check for errors{Fore.RESET}"
)
self.logger.debug(f" [-] {e}")
def run(self, data):
for template, templateOutput in zip(self.template, self.templateOutput):
self.logger.info(
f'[+] Applying template "{template[0]}", outputting to : {templateOutput[0]}'
)
self.generateFromTemplate(template[0], templateOutput[0], data)
class eventForwarder:
"""Class for handling event forwarding"""
def __init__(
self,
remote,
timeField,
token,
logger=None,
index=None,
login="",
password="",
pipeline="",
):
self.logger = logger or logging.getLogger(__name__)
self.remoteHost = remote
self.token = token
self.localHostname = socket.gethostname()
self.userAgent = "zircolite/2.x"
self.index = index
self.login = login
self.password = password
self.pipeline = pipeline
self.queueSize = 20
self.connectionFailed = False
self.timeField = timeField
def send(self, payloads, forwardAll=False):
if payloads:
if self.remoteHost:
try:
# Change EventLoopPolicy on Windows https://stackoverflow.com/questions/45600579/asyncio-event-loop-is-closed-when-getting-loop
if _platform == "win32":
asyncio.set_event_loop_policy(
asyncio.WindowsSelectorEventLoopPolicy()
)
# Splunk HEC
if self.token:
asyncio.run(
self.sendAllAsyncQueue(
payloads,
timeField=self.timeField,
sigmaEvents=(not forwardAll),
mode="HEC",
)
)
# ElasticSearch
elif self.index:
self.disableESDefaultLogging()
asyncio.run(
self.sendAllAsyncQueue(
payloads,
timeField=self.timeField,
sigmaEvents=(not forwardAll),
mode="ES",
)
)
# HTTP
else:
asyncio.run(
self.sendAllAsyncQueue(
payloads,
timeField=self.timeField,
sigmaEvents=(not forwardAll),
mode="HTTP",
)
)
except Exception as e:
self.logger.debug(f"{Fore.RED} [-] {e}")
def networkCheck(self):
"""Check remote connectivity"""
self.logger.info(f"[+] Check connectivity to {self.remoteHost}")
try:
requests.get(
self.remoteHost,
headers={"user-agent": self.userAgent},
timeout=10,
verify=False,
)
except (requests.ConnectionError, requests.Timeout):
return False
return True
def formatToEpoch(self, timestamp):
try:
return (
str(time.mktime(time.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f%z")))
+ timestamp.split(".")[1][:-1]
)
except ValueError:
try:
return (
str(time.mktime(time.strptime(timestamp, "%Y-%m-%dT%H:%M:%S%z")))
+ timestamp.split(".")[1][:-1]
)
except Exception:
self.logger.debug(
f"{Fore.RED} [-] Timestamp error: {timestamp}{Fore.RESET}"
)
def disableESDefaultLogging(self):
"""By Default Elastic client has a logger set to INFO level"""
es_log = logging.getLogger("elasticsearch")
es_log.setLevel(logging.ERROR)
es_log = logging.getLogger("elastic_transport")
es_log.setLevel(logging.ERROR)
async def HECWorker(self, session, queue, sigmaEvents):
while True:
if self.index:
providedIndex = f"?index={self.index}"
else:
providedIndex = ""
data = await queue.get() # Pop data from Queue
resp = await session.post(
f"{self.remoteHost}/services/collector/event{providedIndex}",
headers={"Authorization": f"Splunk {self.token}"},
json=data,
) # Exec action from Queue
queue.task_done() # Notify Queue action ended
if str(resp.status)[0] in ["4", "5"]:
self.logger.error(
f"{Fore.RED} [-] Forwarding failed for event {Fore.RESET}"
)
async def ESWorker(self, session, queue, sigmaEvents):
while True:
data = await queue.get() # Pop data from Queue
index = self.index
if sigmaEvents:
index = f"{self.index}-sigma"
else:
if "OriginalLogfile" in data["payload"]:
index = f'{index}-{("".join([char for char in data["payload"]["OriginalLogfile"].split(".")[0] if (char.isalpha() or char == "-")])).lower()}'
try:
await session.index(
index=index, document=data["payload"], id=data["hash"]
) # Exec action from Queue
except Exception as e:
if "error" in e.body:
if e.body["error"]["type"] == "mapper_parsing_exception":
errField = e.body["error"]["reason"].split("[")[1].split("]")[0]
errType = e.body["error"]["reason"].split("[")[2].split("]")[0]
errValue = (
e.body["error"]["reason"].split("value: '")[1].split("'")[0]
)
canInsert = False
if errType == "long" and errValue.startswith(
"0x"
): # Hex value in long field
data["payload"][errField] = int(
data["payload"][errField], 16
)
canInsert = True
elif errType == "boolean" and errValue.startswith(
"0"
): # 0 value in bool field
data["payload"][errField] = "false"
canInsert = True
elif errType == "boolean" and errValue.startswith(
"1"
): # 1 value in bool field
data["payload"][errField] = "true"
canInsert = True
elif (
errType == "long"
and isinstance((data["payload"][errField]), int)
and data["payload"][errField] > (2**63 - 1)
): # ES limit
data["payload"][errField] = 2**63 - 1
canInsert = True
elif (
errType == "long"
and isinstance((data["payload"][errField]), int)
and data["payload"][errField] < -(2**63)
): # ES limit
data["payload"][errField] = -(2**63)
canInsert = True
elif errType == "long" and isinstance(
data["payload"][errField], argparse.BooleanOptionalAction
):
if type(data["payload"][errField]):
data["payload"][errField] = 1
else:
data["payload"][errField] = 0
canInsert = True
else:
self.logger.debug(
f"{Fore.RED} [-] ES Mapping parser error : {e}{Fore.RESET}"
)
if canInsert:
try:
await session.index(
index=index,
document=data["payload"],
id=data["hash"],
)
except Exception as e:
self.logger.debug(
f"{Fore.RED} [-] ES error : {e}{Fore.RESET}"
)
elif e.body["error"]["type"] == "illegal_argument_exception":
errField = e.body["error"]["reason"].split("[")[1].split("]")[0]
data["payload"].pop(errField, None) # remove value from payload
try:
await session.index(
index=index, document=data["payload"], id=data["hash"]
)
except Exception as e:
self.logger.debug(
f"{Fore.RED} [-] ES error : {e}{Fore.RESET}"
)
else:
self.logger.debug(
f"{Fore.RED} [-] ES error : {e}{Fore.RESET}"
)
queue.task_done() # Notify Queue action ended
async def HTTPWorker(self, session, queue, sigmaEvents):
while True:
data = await queue.get() # Pop data from Queue
resp = await session.post(
self.remoteHost, headers={"user-agent": self.userAgent}, json=data
) # Exec action from Queue
queue.task_done() # Notify Queue action ended
if str(resp.status)[0] in ["4", "5"]:
self.logger.error(
f"{Fore.RED} [-] Forwarding failed for event {Fore.RESET}"
)
def formatEventForES(self, payload, match={}, timeField="", sigmaEvents=False):
if self.pipeline != "":
payload["pipeline"] = self.pipeline
if sigmaEvents:
payload = {
"title": payload["title"],
"id": payload["id"],
"sigmafile": payload["sigmafile"],
"description": payload["description"],
"sigma": payload["sigma"],
"rule_level": payload["rule_level"],
"tags": payload["tags"],
"host": self.localHostname,
}
[
(
payload.update({key: eval(value)})
if value in ["False", "True"]
else payload.update({key: value})
)
for key, value in match.items()
] # In detected events boolean are stored as strings
return {"payload": payload, "hash": xxhash.xxh64_hexdigest(str(payload))}
def formatEventForSplunk(self, payload, match={}, timeField="", sigmaEvents=False):
if sigmaEvents:
payload = {
"title": payload["title"],
"id": payload["id"],
"sigmafile": payload["sigmafile"],
"description": payload["description"],
"sigma": payload["sigma"],
"rule_level": payload["rule_level"],
"tags": payload["tags"],
}
[payload.update({key: value}) for key, value in match.items()]
if timeField == "":
return {"sourcetype": "_json", "event": payload, "host": self.localHostname}
elif timeField not in payload:
self.logger.error(
f"{Fore.RED} [-] Provided time field was not found {Fore.RESET}"
)
return {"sourcetype": "_json", "event": payload, "host": self.localHostname}
else:
return {
"sourcetype": "_json",
"event": payload,
"host": self.localHostname,
"time": self.formatToEpoch(payload[timeField]),
}
def formatEventForHTTTP(self, payload, match={}, timeField="", sigmaEvents=False):
payload.update({"host": self.localHostname})
return payload
def initESSession(self):
if self.login == "":
session = AsyncElasticsearch(hosts=[self.remoteHost], verify_certs=False)
else:
session = AsyncElasticsearch(
hosts=[self.remoteHost],
verify_certs=False,
basic_auth=(self.login, self.password),
)
return session
async def testESSession(self, session):
try:
await session.info()
except Exception:
self.logger.error(f"{Fore.RED} [-] Connection to ES failed {Fore.RESET}")
await session.close()
self.connectionFailed = True
async def testSplunkSession(self, session):
data = {"sourcetype": "_json", "event": {}, "host": self.localHostname}
resp = await session.post(
f"{self.remoteHost}/services/collector/event",
headers={"Authorization": f"Splunk {self.token}"},
json=data,
)
if str(resp.status)[0] in ["4", "5"]:
await session.close()
self.logger.error(
f"{Fore.RED} [-] Connection to Splunk HEC failed - Forwarding disabled {Fore.RESET}"
)
self.connectionFailed = True
async def testHTTPSession(self, session):
resp = await session.post(
self.remoteHost, headers={"user-agent": self.userAgent}, json={}
)
if str(resp.status)[0] in ["4", "5"]:
await session.close()
self.logger.error(
f"{Fore.RED} [-] Connection to HTTP Server failed - Forwarding disabled {Fore.RESET}"
)
self.connectionFailed = True
async def sendAllAsyncQueue(
self, payloads, timeField="", sigmaEvents=False, mode=""
):
if self.connectionFailed:
return
if mode == "ES":
session = self.initESSession()
await self.testESSession(session)
if self.connectionFailed:
return
fnformatEvent = self.formatEventForES
fnWorker = self.ESWorker
elif mode == "HEC":
session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False))
await self.testSplunkSession(session)
if self.connectionFailed:
return
fnformatEvent = self.formatEventForSplunk
fnWorker = self.HECWorker
elif mode == "HTTP":
session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False))
await self.testHTTPSession(session)
if self.connectionFailed:
return
fnformatEvent = self.formatEventForHTTTP
fnWorker = self.HTTPWorker
else:
return
# Init queue
queue = asyncio.Queue()
tasks = []
if not sigmaEvents:
self.logger.info("[+] Gathering events to forward")
payloads = tqdmAsync(payloads, colour="yellow")
for payload in payloads:
if sigmaEvents:
for match in payload["matches"]:
queue.put_nowait(
fnformatEvent(
payload=payload,
match=match,
timeField=timeField,
sigmaEvents=sigmaEvents,
)
)
else:
queue.put_nowait(
fnformatEvent(
payload=payload, timeField=timeField, sigmaEvents=sigmaEvents
)
)
# Create workers to process Queue
for i in range(20):
task = asyncio.create_task(
fnWorker(session, queue, sigmaEvents=sigmaEvents)
)
tasks.append(task)
if not sigmaEvents:
self.logger.info(
f"[+] Forwarding {queue.qsize()} events to {self.remoteHost} {Fore.CYAN}(Don't panic if nothing change for a long time){Fore.RESET}"
)
await queue.join()
# Cancel our worker tasks.
for task in tasks:
task.cancel()
# Wait until all worker tasks are cancelled.
await asyncio.gather(*tasks, return_exceptions=True)
await session.close()
class JSONFlattener:
"""Perform JSON Flattening"""
def __init__(
self,
configFile,
logger=None,
timeAfter="1970-01-01T00:00:00",
timeBefore="9999-12-12T23:59:59",
timeField=None,
hashes=False,
args_config=None,
):
self.logger = logger or logging.getLogger(__name__)
self.keyDict = {}
self.fieldStmt = ""
self.valuesStmt = []
self.timeAfter = timeAfter
self.timeBefore = timeBefore
self.timeField = timeField
self.hashes = hashes
self.args_config = args_config
self.JSONArray = args_config.json_array_input
# Initialize the cache for compiled code
self.compiled_code_cache = {}
# Convert the argparse.Namespace to a dictionary
args_dict = vars(args_config)
# Find the chosen input format
self.chosen_input = next(
(key for key, value in args_dict.items() if "_input" in key and value), None
)
if self.chosen_input is None:
self.chosen_input = "evtx_input" # Since evtx is the default input, we force it no chosen input has been found
with open(configFile, "r", encoding="UTF-8") as fieldMappingsFile:
self.fieldMappingsDict = json.loads(fieldMappingsFile.read())
self.fieldExclusions = self.fieldMappingsDict["exclusions"]
self.fieldMappings = self.fieldMappingsDict["mappings"]
self.uselessValues = self.fieldMappingsDict["useless"]
self.aliases = self.fieldMappingsDict["alias"]
self.fieldSplitList = self.fieldMappingsDict["split"]
self.transforms = self.fieldMappingsDict["transforms"]
self.transforms_enabled = self.fieldMappingsDict["transforms_enabled"]
# Define the authorized BUILTINS for Resticted Python
def default_guarded_getitem(ob, index):
return ob[index]
default_guarded_getattr = getattr
self.RestrictedPython_BUILTINS = {
"__name__": "script",
"_getiter_": default_guarded_getiter,
"_getattr_": default_guarded_getattr,
"_getitem_": default_guarded_getitem,
"base64": base64,
"re": re,
"chardet": chardet,
"_iter_unpack_sequence_": guarded_iter_unpack_sequence,
}
self.RestrictedPython_BUILTINS.update(safe_builtins)
self.RestrictedPython_BUILTINS.update(limited_builtins)
self.RestrictedPython_BUILTINS.update(utility_builtins)
def run(self, file):
"""
Flatten json object with nested keys into a single level.
Returns the flattened json object
"""
self.logger.debug(f"FLATTENING : {file}")
JSONLine = {}
JSONOutput = []
fieldStmt = ""
def transformValue(code, param):
try:
# Check if the code has already been compiled
if code in self.compiled_code_cache:
byte_code = self.compiled_code_cache[code]
else:
# Compile the code and store it in the cache
byte_code = compile_restricted(
code, filename="<inline code>", mode="exec"
)
self.compiled_code_cache[code] = byte_code
# Prepare the execution environment
TransformFunction = {}
exec(byte_code, self.RestrictedPython_BUILTINS, TransformFunction)
return TransformFunction["transform"](param)
except Exception as e:
self.logger.debug(f"ERROR: Couldn't apply transform: {e}")
return param # Return the original parameter if transform fails
def flatten(x, name=""):
nonlocal fieldStmt
# If it is a Dict go deeper
if isinstance(x, dict):
for a in x:
flatten(x[a], name + a + ".")
else:
# Applying exclusions. Be careful, the key/value pair is discarded if there is a partial match
if not any(
exclusion in name[:-1] for exclusion in self.fieldExclusions
):
# Arrays are not expanded
if isinstance(x, list):
value = "".join(str(x))
else:
value = x
# Excluding useless values (e.g. "null"). The value must be an exact match.
if value not in self.uselessValues:
# Applying field mappings
rawFieldName = name[:-1]
if rawFieldName in self.fieldMappings:
key = self.fieldMappings[rawFieldName]
else:
# Removing all annoying character from field name
key = "".join(
e for e in rawFieldName.split(".")[-1] if e.isalnum()
)
# Preparing aliases (work on original field name and Mapped field name)
keys = [key]
for fieldName in [key, rawFieldName]:
if fieldName in self.aliases:
keys.append(self.aliases[key])
# Applying field transforms (work on original field name and Mapped field name)
keysThatNeedTransformedValues = []
transformedValuesByKeys = {}
if self.transforms_enabled:
for fieldName in [key, rawFieldName]:
if fieldName in self.transforms:
for transform in self.transforms[fieldName]:
if (
transform["enabled"]
and self.chosen_input
in transform["source_condition"]
):
transformCode = transform["code"]
# If the transform rule ask for a dedicated alias
if transform["alias"]:
keys.append(transform["alias_name"])
keysThatNeedTransformedValues.append(
transform["alias_name"]
)
transformedValuesByKeys[
transform["alias_name"]
] = transformValue(transformCode, value)
else:
value = transformValue(
transformCode, value
)
# Applying field splitting
fieldsToSplit = []
if rawFieldName in self.fieldSplitList:
fieldsToSplit.append(rawFieldName)
if key in self.fieldSplitList:
fieldsToSplit.append(key)
if len(fieldsToSplit) > 0:
for field in fieldsToSplit:
try:
splittedFields = value.split(
self.fieldSplitList[field]["separator"]
)
for splittedField in splittedFields:
k, v = splittedField.split(
self.fieldSplitList[field]["equal"]
)
keyLower = k.lower()
JSONLine[k] = v
if keyLower not in self.keyDict:
self.keyDict[keyLower] = k
fieldStmt += f"'{k}' TEXT COLLATE NOCASE,\n"
except Exception as e:
self.logger.debug(
f"ERROR : Couldn't apply field splitting, value(s) {str(splittedFields)} : {e}"
)
# Applying aliases
for key in keys:
if key in keysThatNeedTransformedValues:
JSONLine[key] = transformedValuesByKeys[key]
else:
JSONLine[key] = value
# Creating the CREATE TABLE SQL statement
keyLower = key.lower()
if keyLower not in self.keyDict:
self.keyDict[keyLower] = key
if isinstance(value, int):
fieldStmt += f"'{key}' INTEGER,\n"
else:
fieldStmt += f"'{key}' TEXT COLLATE NOCASE,\n"
# If filesize is not zero
if os.stat(file).st_size != 0:
with open(str(file), "r", encoding="utf-8") as JSONFile:
filename = os.path.basename(file)
logs = JSONFile
# If the file is a json array
if self.JSONArray:
try:
logs = json.loads(JSONFile.read())
except Exception as e:
self.logger.debug(f"JSON ARRAY ERROR : {e}")
logs = []
for line in logs:
try:
if self.JSONArray:
dictToFlatten = line
else:
dictToFlatten = json.loads(line)
dictToFlatten.update({"OriginalLogfile": filename})
if self.hashes:
dictToFlatten.update(
{
"OriginalLogLinexxHash": xxhash.xxh64_hexdigest(
line[:-1]
)
}
)
flatten(dictToFlatten)
except Exception as e:
self.logger.debug(f"JSON ERROR : {e}")
# Handle timestamp filters
if (
self.timeAfter != "1970-01-01T00:00:00"
or self.timeBefore != "9999-12-12T23:59:59"
) and (self.timeField in JSONLine):
try:
timestamp = time.strptime(
JSONLine[self.timeField].split(".")[0].replace("Z", ""),
"%Y-%m-%dT%H:%M:%S",
)
if (
timestamp > self.timeAfter
and timestamp < self.timeBefore
):
JSONOutput.append(JSONLine)
except Exception:
JSONOutput.append(JSONLine)
else:
JSONOutput.append(JSONLine)
JSONLine = {}
return {"dbFields": fieldStmt, "dbValues": JSONOutput}
def runAll(self, EVTXJSONList):
for evtxJSON in tqdm(EVTXJSONList, colour="yellow"):
if os.stat(evtxJSON).st_size != 0:
results = self.run(evtxJSON)
self.fieldStmt += results["dbFields"]
self.valuesStmt += results["dbValues"]
class zirCore:
"""Load data into database and apply detection rules"""
def __init__(
self,
config,
logger=None,
noOutput=False,
timeAfter="1970-01-01T00:00:00",
timeBefore="9999-12-12T23:59:59",
limit=-1,
csvMode=False,
timeField=None,
hashes=False,
dbLocation=":memory:",
delimiter=";",
):
self.logger = logger or logging.getLogger(__name__)
self.dbConnection = self.createConnection(dbLocation)
self.fullResults = []
self.ruleset = {}
self.noOutput = noOutput
self.timeAfter = timeAfter
self.timeBefore = timeBefore
self.config = config
self.limit = limit
self.csvMode = csvMode
self.timeField = timeField
self.hashes = hashes
self.delimiter = delimiter
def close(self):
self.dbConnection.close()
def createConnection(self, db):
"""create a database connection to a SQLite database"""
conn = None
self.logger.debug(f"CONNECTING TO : {db}")
try:
if db == ":memory:":
conn = sqlite3.connect(db, isolation_level=None)
conn.execute("PRAGMA journal_mode = MEMORY;")
conn.execute("PRAGMA synchronous = OFF;")
conn.execute("PRAGMA temp_store = MEMORY;")
else:
conn = sqlite3.connect(db)
conn.row_factory = sqlite3.Row # Allows to get a dict
def udf_regex(x, y):
if y is None:
return 0
if re.search(x, y):
return 1
else:
return 0
conn.create_function(
"regexp", 2, udf_regex
) # Allows to use regex in SQlite
except Error as e:
self.logger.error(f"{Fore.RED} [-] {e}")
return conn
def createDb(self, fieldStmt):
createTableStmt = f"CREATE TABLE logs ( row_id INTEGER, {fieldStmt} PRIMARY KEY(row_id AUTOINCREMENT) );"
self.logger.debug(f" CREATE : {createTableStmt}")
if not self.executeQuery(createTableStmt):
self.logger.error(f"{Fore.RED} [-] Unable to create table{Fore.RESET}")
sys.exit(1)
def createIndex(self):
self.executeQuery('CREATE INDEX "idx_eventid" ON "logs" ("eventid");')
def executeQuery(self, query):
"""Perform a SQL Query with the provided connection"""
if self.dbConnection is not None:
dbHandle = self.dbConnection.cursor()
self.logger.debug(f"EXECUTING : {query}")
try:
dbHandle.execute(query)
self.dbConnection.commit()
return True
except Error as e:
self.logger.debug(f" [-] {e}")
return False
else:
self.logger.error(f"{Fore.RED} [-] No connection to Db{Fore.RESET}")
return False
def executeSelectQuery(self, query):
"""
Execute a SELECT SQL query and return the results as a list of dictionaries.
"""
if self.dbConnection is None:
self.logger.error(f"{Fore.RED} [-] No connection to Db{Fore.RESET}")
return []
try:
cursor = self.dbConnection.cursor()
self.logger.debug(f"Executing SELECT query: {query}")
cursor.execute(query)
rows = cursor.fetchall()
# Convert rows to list of dictionaries
result = [dict(row) for row in rows]
return result
except sqlite3.Error as e:
self.logger.debug(f" [-] SQL query error: {e}")
return []
def loadDbInMemory(self, db):
"""In db only mode it is possible to restore an on disk Db to avoid EVTX extraction and flattening"""
dbfileConnection = self.createConnection(db)
dbfileConnection.backup(self.dbConnection)
dbfileConnection.close()
def escape_identifier(self, identifier):
"""Escape SQL identifiers like table or column names."""
return identifier.replace('"', '""')
def insertData2Db(self, JSONLine):
"""Build a parameterized INSERT INTO query and insert data into the database."""
columns = JSONLine.keys()
columnsEscaped = ", ".join([self.escape_identifier(col) for col in columns])
placeholders = ", ".join(["?"] * len(columns))
values = []
for col in columns:
value = JSONLine[col]
if isinstance(value, int):
# Check if value exceeds SQLite INTEGER limits
if abs(value) > 9223372036854775807:
value = str(value) # Convert to string
values.append(value)
insertStmt = f"INSERT INTO logs ({columnsEscaped}) VALUES ({placeholders})"
try:
self.dbConnection.execute(insertStmt, values)
return True
except Exception as e:
self.logger.debug(f" [-] {e}")
return False
def insertFlattenedJSON2Db(self, flattenedJSON, forwarder=None):
if forwarder:
forwarder.send(flattenedJSON, forwardAll=True)
for JSONLine in tqdm(flattenedJSON, colour="yellow"):
self.insertData2Db(JSONLine)
self.createIndex()
def saveFlattenedJSON2File(self, flattenedJSON, outputFile):
with open(outputFile, "w", encoding="utf-8") as file:
for JSONLine in tqdm(flattenedJSON, colour="yellow"):
file.write(f'{json.dumps(JSONLine).decode("utf-8")}\n')
def saveDbToDisk(self, dbFilename):
self.logger.info("[+] Saving working data to disk as a SQLite DB")
onDiskDb = sqlite3.connect(dbFilename)
self.dbConnection.backup(onDiskDb)
onDiskDb.close()
def executeRule(self, rule):
"""
Execute a single Sigma rule against the database and return the results.
"""
if "rule" not in rule:
self.logger.debug("RULE FORMAT ERROR: 'rule' key missing")
return {}
# Set default values for missing rule keys