-
Notifications
You must be signed in to change notification settings - Fork 1
/
tracer.py
2876 lines (2461 loc) · 120 KB
/
tracer.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 os
import re
import sys
import csv
import glob
import pickle
import shutil
import argparse
import datetime
import subprocess
from functools import wraps
from logging import getLogger
from logging.config import dictConfig
from ssl import create_default_context
try:
from lxml import etree
has_lxml = True
except ImportError:
has_lxml = False
try:
from evtx import PyEvtxParser
has_evtx = True
except ImportError:
has_evtx = False
try:
from py2neo import Graph, GraphService, ClientError
has_py2neo = True
except ImportError:
has_py2neo = False
try:
import numpy as np
has_numpy = True
except ImportError:
has_numpy = False
try:
import changefinder
has_changefinder = True
except ImportError:
has_changefinder = False
try:
from flask import Flask, render_template, request, redirect, session
has_flask = True
except ImportError:
has_flask = False
try:
import pandas as pd
has_pandas = True
except ImportError:
has_pandas = False
try:
from hmmlearn import hmm
has_hmmlearn = True
except ImportError:
has_hmmlearn = False
try:
import joblib
has_sklearn = True
except ImportError:
has_sklearn = False
try:
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search, Q
has_es = True
except ImportError:
has_es = False
try:
import yaml
has_pyyaml = True
except ImportError:
has_pyyaml = False
try:
from flask_login import UserMixin, LoginManager, login_user, logout_user, current_user
has_flask_login = True
except ImportError:
has_flask_login = False
try:
from flask_sqlalchemy import SQLAlchemy
has_flask_sqlalchemy = True
except ImportError:
has_flask_sqlalchemy = False
try:
from flask_wtf import FlaskForm
has_flask_wtf = True
except ImportError:
has_flask_wtf = False
try:
from wtforms import StringField, PasswordField
from wtforms.validators import ValidationError, DataRequired, EqualTo, Length
has_wtforms = True
except ImportError:
has_wtforms = False
try:
import git
has_git = True
except ImportError:
has_git = False
try:
from sigma.parser.rule import SigmaParser
from sigma.configuration import SigmaConfiguration
from sigma.parser.condition import ConditionAND, ConditionOR, ConditionNOT, NodeSubexpression
has_sigma = True
except ImportError:
has_sigma = False
# Check Event Id
EVENT_ID = [4624, 4625, 4662, 4768, 4769, 4776, 4672, 4720, 4726, 4728, 4729, 4732, 4733, 4756, 4757, 4719, 5137, 5141]
# EVTX Header
EVTX_HEADER = b"\x45\x6C\x66\x46\x69\x6C\x65\x00"
# String Check list
UCHECK = r"[%*+=\[\]\\/|;:\"<>?,&]"
HCHECK = r"[*\\/|:\"<>?&]"
# IPv4 regex
IPv4_PATTERN = re.compile(r"\A\d+\.\d+\.\d+\.\d+\Z", re.DOTALL)
# IPv6 regex
IPv6_PATTERN = re.compile(r"\A(::(([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})){0,5})?|([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(::(([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})){0,4})?|:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(::(([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})){0,3})?|:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(::(([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})){0,2})?|:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(::(([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(:([0-9a-f]|[1-9a-f][0-9a-f]{1,3}))?)?|:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})(::([0-9a-f]|[1-9a-f][0-9a-f]{1,3})?|(:([0-9a-f]|[1-9a-f][0-9a-f]{1,3})){3}))))))\Z", re.DOTALL)
# LogonTracer folder path
FPATH = os.path.dirname(os.path.abspath(__file__))
# CategoryId
CATEGORY_IDs = {
"%%8280": "Account_Logon",
"%%8270": "Account_Management",
"%%8276": "Detailed_Tracking",
"%%8279": "DS_Access",
"%%8273": "Logon/Logoff",
"%%8274": "Object_Access",
"%%8277": "Policy_Change",
"%%8275": "Privilege_Use",
"%%8272": "System"}
# Auditing Constants
AUDITING_CONSTANTS = {
"{0cce9210-69ae-11d9-bed3-505054503030}": "SecurityStateChange",
"{0cce9211-69ae-11d9-bed3-505054503030}": "SecuritySubsystemExtension",
"{0cce9212-69ae-11d9-bed3-505054503030}": "Integrity",
"{0cce9213-69ae-11d9-bed3-505054503030}": "IPSecDriverEvents",
"{0cce9214-69ae-11d9-bed3-505054503030}": "Others",
"{0cce9215-69ae-11d9-bed3-505054503030}": "Logon",
"{0cce9216-69ae-11d9-bed3-505054503030}": "Logoff",
"{0cce9217-69ae-11d9-bed3-505054503030}": "AccountLockout",
"{0cce9218-69ae-11d9-bed3-505054503030}": "IPSecMainMode",
"{0cce9219-69ae-11d9-bed3-505054503030}": "IPSecQuickMode",
"{0cce921a-69ae-11d9-bed3-505054503030}": "IPSecUserMode",
"{0cce921b-69ae-11d9-bed3-505054503030}": "SpecialLogon",
"{0cce921c-69ae-11d9-bed3-505054503030}": "Others",
"{0cce921d-69ae-11d9-bed3-505054503030}": "FileSystem",
"{0cce921e-69ae-11d9-bed3-505054503030}": "Registry",
"{0cce921f-69ae-11d9-bed3-505054503030}": "Kernel",
"{0cce9220-69ae-11d9-bed3-505054503030}": "Sam",
"{0cce9221-69ae-11d9-bed3-505054503030}": "CertificationServices",
"{0cce9222-69ae-11d9-bed3-505054503030}": "ApplicationGenerated",
"{0cce9223-69ae-11d9-bed3-505054503030}": "Handle",
"{0cce9224-69ae-11d9-bed3-505054503030}": "Share",
"{0cce9225-69ae-11d9-bed3-505054503030}": "FirewallPacketDrops",
"{0cce9226-69ae-11d9-bed3-505054503030}": "FirewallConnection",
"{0cce9227-69ae-11d9-bed3-505054503030}": "Other",
"{0cce9228-69ae-11d9-bed3-505054503030}": "Sensitive",
"{0cce9229-69ae-11d9-bed3-505054503030}": "NonSensitive",
"{0cce922a-69ae-11d9-bed3-505054503030}": "Others",
"{0cce922b-69ae-11d9-bed3-505054503030}": "ProcessCreation",
"{0cce922c-69ae-11d9-bed3-505054503030}": "ProcessTermination",
"{0cce922d-69ae-11d9-bed3-505054503030}": "DpapiActivity",
"{0cce922e-69ae-11d9-bed3-505054503030}": "RpcCall",
"{0cce922f-69ae-11d9-bed3-505054503030}": "AuditPolicy",
"{0cce9230-69ae-11d9-bed3-505054503030}": "AuthenticationPolicy",
"{0cce9231-69ae-11d9-bed3-505054503030}": "AuthorizationPolicy",
"{0cce9232-69ae-11d9-bed3-505054503030}": "MpsscvRulePolicy",
"{0cce9233-69ae-11d9-bed3-505054503030}": "WfpIPSecPolicy",
"{0cce9234-69ae-11d9-bed3-505054503030}": "Others",
"{0cce9235-69ae-11d9-bed3-505054503030}": "UserAccount",
"{0cce9236-69ae-11d9-bed3-505054503030}": "ComputerAccount",
"{0cce9237-69ae-11d9-bed3-505054503030}": "SecurityGroup",
"{0cce9238-69ae-11d9-bed3-505054503030}": "DistributionGroup",
"{0cce9239-69ae-11d9-bed3-505054503030}": "ApplicationGroup",
"{0cce923a-69ae-11d9-bed3-505054503030}": "Others",
"{0cce923b-69ae-11d9-bed3-505054503030}": "DSAccess",
"{0cce923c-69ae-11d9-bed3-505054503030}": "AdAuditChanges",
"{0cce923d-69ae-11d9-bed3-505054503030}": "Replication",
"{0cce923e-69ae-11d9-bed3-505054503030}": "DetailedReplication",
"{0cce923f-69ae-11d9-bed3-505054503030}": "CredentialValidation",
"{0cce9240-69ae-11d9-bed3-505054503030}": "Kerberos",
"{0cce9241-69ae-11d9-bed3-505054503030}": "Others",
"{0cce9242-69ae-11d9-bed3-505054503030}": "KerbCredentialValidation",
"{0cce9243-69ae-11d9-bed3-505054503030}": "NPS"}
# Load logging config
with open(FPATH + "/config/logging.yml", 'r') as logging_open:
logging_data = yaml.safe_load(logging_open)
dictConfig(logging_data)
logger = getLogger("agent_logger")
# Flask instance
if not has_flask:
logger.error("[!] Flask must be installed for this script.")
sys.exit(1)
else:
app = Flask(__name__)
parser = argparse.ArgumentParser(description="Visualizing and analyzing active directory Windows logon event logs.")
parser.add_argument("-r", "--run", action="store_true", default=False,
help="Start web application.")
parser.add_argument("-o", "--port", dest="port", action="store", type=int, metavar="PORT",
help="Port number to be started web application. (default: 8080).")
parser.add_argument("--host", dest="host", action="store", type=str, metavar="HOST",
help="Host address to bind the web application. (default: 0.0.0.0).")
parser.add_argument("-e", "--evtx", dest="evtx", nargs="*", action="store", type=str, metavar="EVTX",
help="Import to the AD EVTX file. (multiple files OK)")
parser.add_argument("-x", "--xml", dest="xmls", nargs="*", action="store", type=str, metavar="XML",
help="Import to the XML file for event log. (multiple files OK)")
parser.add_argument("-s", "--server", dest="server", action="store", type=str, metavar="SERVER",
help="Neo4j server. (default: localhost)")
parser.add_argument("-u", "--user", dest="user", action="store", type=str, metavar="USERNAME",
help="Neo4j account name. (default: neo4j)")
parser.add_argument("-p", "--password", dest="password", action="store", type=str, metavar="PASSWORD",
help="Neo4j password. (default: password).")
parser.add_argument("--wsport", dest="wsport", action="store", type=str, metavar="PORT",
help="Neo4j websocket port number. (default: 7687).")
parser.add_argument("-l", "--learn", action="store_true", default=False,
help="Machine learning event logs using Hidden Markov Model.")
parser.add_argument("--sigma", action="store_true", default=False,
help="Scan using Sigma rule. (default: False)")
parser.add_argument("--es-server", dest="esserver", action="store", type=str, metavar="ESSERVER",
help="Elastic Search server address. (default: localhost:9200)")
parser.add_argument("--es-index", dest="esindex", action="store", type=str, metavar="ESINDEX",
help="Elastic Search index to search. (default: winlogbeat-*)")
parser.add_argument("--es-prefix", dest="esprefix", action="store", type=str, metavar="ESPREFIX",
help="Elastic Search event object prefix. (default: winlog)")
parser.add_argument("--es-user", dest="esuser", action="store", type=str, metavar="ESUSER",
help="Elastic Search ssl authentication user. (default: elastic)")
parser.add_argument("--es-pass", dest="espassword", action="store", type=str, metavar="ESPASSWORD",
help="Elastic Search ssl authentication password.")
parser.add_argument("--es-cafile", dest="escafile", action="store", type=str, metavar="ESCAFILE",
help="Elastic Search ssl cert file.")
parser.add_argument("--es", action="store_true", default=False,
help="Import data from Elastic Search. (default: False)")
parser.add_argument("--postes", action="store_true", default=False,
help="Post data to Elastic Search. (default: False)")
parser.add_argument("-z", "--timezone", dest="timezone", action="store", type=int, metavar="UTC",
help="Event log time zone. (for example: +9) (default: GMT)")
parser.add_argument("-f", "--from", dest="fromdate", action="store", type=str, metavar="DATE",
help="Parse Security Event log from this time. (for example: 2017-01-01T00:00:00)")
parser.add_argument("-t", "--to", dest="todate", action="store", type=str, metavar="DATE",
help="Parse Security Event log to this time. (for example: 2017-02-28T23:59:59)")
parser.add_argument("-c", "--config", dest="config", action="store", type=str, metavar="FILE",
help="Configuration file path. (default: config/config.yml)")
parser.add_argument("--case", dest="case", action="store", type=str, metavar="CASE_NAME",
help="[for Neo4j Enterprise] Case management option. If you want to manage each EVTX files in case. (default: neo4j)")
parser.add_argument("--create_user", dest="create_user", action="store", type=str, metavar="USER",
help="Create a new Neo4j user.")
parser.add_argument("--create_password", dest="create_password", action="store", type=str, metavar="PASSWORD",
help="Create a new Neo4j password.")
parser.add_argument("--role", dest="role", action="store", type=str, metavar="ROLE",
help="[for Neo4j Enterprise] User role option [admin, architect, reader]. (default: reader)")
parser.add_argument("--delete_user", dest="delete_user", action="store", type=str, metavar="USER",
help="Delete a Neo4j user.")
parser.add_argument("--add", action="store_true", default=False,
help="Add additional data to Neo4j database. (default: False)")
parser.add_argument("--delete", action="store_true", default=False,
help="Delete all nodes and relationships from this Neo4j database. (default: False)")
args = parser.parse_args()
statement_user = """
MERGE (user:Username{{ user:'{user}' }}) set user.rights='{rights}', user.sid='{sid}', user.rank={rank}, user.status='{status}', user.counts='{counts}', user.counts4624='{counts4624}', user.counts4625='{counts4625}', user.counts4768='{counts4768}', user.counts4769='{counts4769}', user.counts4776='{counts4776}', user.detect='{detect}'
RETURN user
"""
statement_ip = """
MERGE (ip:IPAddress{{ IP:'{IP}' }}) set ip.rank={rank}, ip.hostname='{hostname}'
RETURN ip
"""
statement_r = """
MATCH (user:Username{{ user:'{user}' }})
MATCH (ip:IPAddress{{ IP:'{IP}' }})
CREATE (ip)-[event:Event]->(user) set event.id={id}, event.logintype={logintype}, event.status='{status}', event.count={count}, event.authname='{authname}', event.date={date}
RETURN user, ip
"""
statement_date = """
MERGE (date:Date{{ date:'{Daterange}' }}) set date.start='{start}', date.end='{end}'
RETURN date
"""
statement_domain = """
MERGE (domain:Domain{{ domain:'{domain}' }})
RETURN domain
"""
statement_dr = """
MATCH (domain:Domain{{ domain:'{domain}' }})
MATCH (user:Username{{ user:'{user}' }})
CREATE (user)-[group:Group]->(domain)
RETURN user, domain
"""
statement_del = """
MERGE (date:Deletetime{{ date:'{deletetime}' }}) set date.user='{user}', date.domain='{domain}'
RETURN date
"""
statement_pl = """
MERGE (id:ID{{ id:{id} }}) set id.changetime='{changetime}', id.category='{category}', id.sub='{sub}'
RETURN id
"""
statement_pr = """
MATCH (id:ID{{ id:{id} }})
MATCH (user:Username{{ user:'{user}' }})
CREATE (user)-[group:Policy]->(id) set group.date='{date}'
RETURN user, id
"""
statement_cd = """
CREATE DATABASE {case};
"""
statement_dd = """
DROP DATABASE {case};
"""
statement_cu = """
CREATE USER {username} SET PASSWORD '{password}' CHANGE NOT REQUIRED;
"""
# for Neo4j enterprise edition
#statement_cu = """
# CREATE USER {username} SET PASSWORD '{password}' CHANGE NOT REQUIRED SET STATUS ACTIVE;
# """
statement_au = """
ALTER CURRENT USER SET PASSWORD FROM '{oldPassword}' TO '{newPassword}';
"""
statement_du = """
DROP USER {username};
"""
statement_su = """
ALTER USER {username} SET STATUS {action};
"""
statement_role_add = """
CREATE OR REPLACE ROLE {username}_role AS COPY OF {role};
"""
statement_role_revole = """
REVOKE GRANT ACCESS ON DATABASES {database} FROM {username}_role;
"""
statement_role_set = """
GRANT ROLE {username}_role TO {username};
"""
statement_role_set_admin = """
GRANT ROLE admin TO {username};
"""
statement_default_db_access = """
GRANT ACCESS ON DATABASE neo4j TO {username}_role;
"""
statement_db_access = """
GRANT ACCESS ON DATABASE {database} TO {username}_role;
"""
es_doc_user = """
{{"@timestamp":"{datetime}", "user":"{user}", "rights":"{rights}", "sid":"{sid}", "status":"{status}", "rank":{rank}}}
"""
es_doc_ip = """
{{"@timestamp":"{datetime}", "IP":"{IP}", "hostname":"{hostname}", "rank":{rank}}}
"""
if not has_flask_login:
logger.error("[!] flask-login must be installed for this script.")
sys.exit(1)
if not has_flask_sqlalchemy:
logger.error("[!] flask-sqlalchemy must be installed for this script.")
sys.exit(1)
if not has_pyyaml:
logger.error("[!] pyyaml must be installed for this script.")
sys.exit(1)
if not has_flask_wtf:
logger.error("[!] flask_wtf must be installed for this script.")
sys.exit(1)
if not has_wtforms:
logger.error("[!] wtforms must be installed for this script.")
sys.exit(1)
if args.config:
config_path = args.config
else:
config_path = FPATH + "/config/config.yml"
with open(config_path, 'r') as config_open:
config_data = yaml.safe_load(config_open)["settings"]
# neo4j password
NEO4J_PASSWORD = config_data["neo4j"]["NEO4J_PASSWORD"]
# neo4j user name
NEO4J_USER = config_data["neo4j"]["NEO4J_USER"]
# neo4j server
NEO4J_SERVER = config_data["neo4j"]["NEO4J_SERVER"]
# neo4j listen port
NEO4J_PORT = config_data["neo4j"]["NEO4J_PORT"]
# Web application port
WEB_PORT = config_data["logontracer"]["WEB_PORT"]
# Web application address
WEB_HOST = config_data["logontracer"]["WEB_HOST"]
# Flag for SESSION_COOKIE_SECURE
USE_HTTPS = config_data["logontracer"]["SESSION_COOKIE_SECURE"]
# Websocket port
WS_PORT = config_data["neo4j"]["WS_PORT"]
# Elastic Search server
ES_SERVER = config_data["elastic"]["ES_SERVER"]
# Elastic index
ES_INDEX = config_data["elastic"]["ES_INDEX"]
# Elastic prefix
ES_PREFIX = config_data["elastic"]["ES_PREFIX"]
# Elastic auth user
ES_USER = config_data["elastic"]["ES_USER"]
# logontracer default user
default_user = config_data["logontracer"]["default_user"]
# logontracer default password
default_password = config_data["logontracer"]["default_password"]
# logontracer user info database
database_name = config_data["logontracer"]["database_name"]
# Default neo4j database name
CASE_NAME = config_data["logontracer"]["default_case"]
# Sigma rules url
SIGMA_URL = config_data["sigma"]["git_url"]
# Sigma scan result file
SIGMA_RESULTS_FILE = config_data["sigma"]["results"]
if args.user:
NEO4J_USER = args.user
if args.password:
NEO4J_PASSWORD = args.password
if args.server:
NEO4J_SERVER = args.server
if args.port:
WEB_PORT = args.port
if args.host:
WEB_HOST = args.host
if args.wsport:
WS_PORT = args.wsport
if args.esserver:
ES_SERVER = args.esserver
if args.esindex:
ES_INDEX = args.esindex
if args.esprefix:
ES_PREFIX = args.esprefix
if args.esuser:
ES_USER = args.esuser
if args.espassword:
ES_PASSWORD = args.espassword
if args.escafile:
ES_CAFILE = args.escafile
if args.case:
CASE_NAME = args.case
# Setup login user
app.config["SESSION_COOKIE_SECURE"] = USE_HTTPS
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + database_name
app.config["SECRET_KEY"] = os.urandom(24)
app.permanent_session_lifetime = datetime.timedelta(minutes=60)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), nullable=False, unique=True)
urole = db.Column(db.String(20))
def __init__(self, username, urole):
self.username = username
self.urole = urole
def get_id(self):
return self.id
def get_username(self):
return self.username
def get_urole(self):
return self.urole
class SettingForm(FlaskForm):
password1 = PasswordField('Password', validators=[DataRequired(), EqualTo('password2', message='Passwords must match.'), Length(min=3, max=20)])
password2 = PasswordField('Password (again)', validators=[DataRequired(), Length(min=3, max=20)])
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=3, max=50)])
password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=20)])
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=3, max=50)])
password1 = PasswordField('Password', validators=[DataRequired(), EqualTo('password2', message='Passwords must match.'), Length(min=3, max=20)])
password2 = PasswordField('Password (again)', validators=[DataRequired(), Length(min=3, max=20)])
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('This username is already registered.')
class CaseForm(FlaskForm):
case = StringField('Case', validators=[DataRequired()])
with app.app_context():
db.create_all()
user_query = User.query.filter_by(username=default_user).first()
if user_query is None:
create_user = User(username=default_user, urole="ADMIN")
db.session.add(create_user)
db.session.commit()
@login_manager.user_loader
def load_user(user_id):
return db.session.get(User, int(user_id))
@login_manager.unauthorized_handler
def unauthorized():
return redirect('/login')
# Web application logging decorater
def http_request_logging(f):
@wraps(f)
def decorated_function(*args, **kwargs):
try:
app.logger.info('%s - %s - %s - %s', request.remote_addr, request.method, request.url, request.query_string)
except Exception as e:
app.logger.exception(e)
pass
return f(*args, **kwargs)
return decorated_function
# Costom login_required with role
def login_required(role="ANY"):
def wrapper(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated:
return login_manager.unauthorized()
urole = current_user.get_urole()
if ((urole != role) and (role != "ANY")):
return login_manager.unauthorized()
return fn(*args, **kwargs)
return decorated_view
return wrapper
# Web application login page
@app.route('/login', methods=['GET', 'POST'])
@http_request_logging
def login():
if current_user.is_authenticated:
return redirect('/')
session.permanent = True
session["case"] = CASE_NAME
form = LoginForm(request.form)
if form.validate_on_submit():
username = form.username.data
password = form.password.data
remember = True if request.form.get("remember") else False
session["username"] = username
session["password"] = password
try:
GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
user = User.query.filter_by(username=username).first()
logger.info("[+] login user {0}.".format(username))
login_user(user, remember=remember)
return redirect('/')
except:
logger.error("[!] login failed user {0}.".format(username))
return render_template('login.html', form=form, messages='<div class="alert alert-danger" role="alert">Invalid username or password.</div>')
return render_template('login.html', form=form, messages="")
# Web application signup page
@app.route('/signup', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ADMIN")
def signup():
form = RegistrationForm(request.form)
if form.validate_on_submit():
username = form.username.data
password = form.password1.data
admin = True if request.form.get("admin") else False
if admin:
role = "ADMIN"
role_neo4j = "admin"
else:
role = "USER"
role_neo4j = "architect"
with app.app_context():
user = User(username=username, urole=role)
db.session.add(user)
db.session.commit()
try:
service = GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
except:
logger.error("[!] Can't connect Neo4j Database GraphService.")
sys.exit(1)
create_neo4j_user(service, username, password, role_neo4j)
return redirect('/')
else:
return render_template('signup.html', form=form)
# Web application change password page
@app.route('/setting', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ANY")
def setting():
form = SettingForm(request.form)
if form.validate_on_submit():
username = current_user.username
password = form.password1.data
with app.app_context():
user_query = User.query.filter_by(username=username).first()
db.session.delete(user_query)
db.session.commit()
user = User(username=username, urole=user_query.urole)
db.session.add(user)
db.session.commit()
try:
service = GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
except:
logger.error("[!] Can't connect Neo4j Database GraphService.")
sys.exit(1)
try:
system = service.system_graph
system.run(statement_au.format(**{"oldPassword": session["password"], "newPassword": password}))
logger.info("[+] Change user {0} password for neo4j.".format(username))
except ClientError as e:
if "User does not exist" in str(e):
logger.error("[!] User does not exist {0}.".format(username))
elif "Unsupported administration command" in str(e):
logger.error("[!] Can't change password.")
else:
logger.error(str(e))
session["password"] = password
return redirect('/')
else:
return render_template('setting.html', form=form)
# Web application logout
@app.route('/logout')
@http_request_logging
@login_required(role="ANY")
def logout():
logout_user()
return redirect('/login')
# Web application create case
@app.route('/addcase', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ADMIN")
def addcase():
form = CaseForm(request.form)
if form.validate_on_submit():
try:
service = GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
except:
logger.error("[!] Can't connect Neo4j Database GraphService.")
sys.exit(1)
if "Enterprise" in service.product:
case = form.case.data
if not re.search(r"\A[0-9a-zA-Z]{2,20}\Z", case):
return render_template('addcase.html', form=form, messages='<div class="alert alert-danger" role="alert">You can use letters upper/lowercase and numbers.</div>')
session["case"] = case
create_database(service, case)
return render_template("index.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=case)
else:
return render_template("index.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=CASE_NAME)
else:
return render_template('addcase.html', form=form, messages='<div class="alert alert-info" role="alert">This feature is in Neo4j Enterprise.</div>')
# Web application delete case
@app.route('/delcase', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ADMIN")
def delcase():
if request.method == "POST":
case_name = request.form.get('caseName')
try:
service = GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
except:
logger.error("[!] Can't connect Neo4j Database GraphService.")
sys.exit(1)
if "Enterprise" in service.product:
if re.search(r"\A[0-9a-zA-Z]{2,20}\Z", case_name):
delete_database(service, case_name)
return render_template("delcase.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='<div><div class="alert alert-success" role="alert">Deleted case ' + case_name + '</div></div>')
else:
return render_template("delcase.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='<div><div class="alert alert-danger" role="alert">This feature is in Neo4j Enterprise.</div></div>')
else:
return render_template("delcase.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='')
# Web application change case
@app.route('/changecase', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ANY")
def changecase():
if request.method == "POST":
case_name = request.form.get('caseName')
if not re.search(r"\A[0-9a-zA-Z]{2,20}\Z", case_name):
return redirect('/')
session["case"] = case_name
return render_template("index.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=case_name)
else:
return render_template("changecase.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"])
@app.route('/changecase_t', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ANY")
def changecase_t():
if request.method == "POST":
case_name = request.form.get('caseName')
if not re.search(r"\A[0-9a-zA-Z]{2,20}\Z", case_name):
return redirect('/')
session["case"] = case_name
return render_template("timeline.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=case_name)
else:
return render_template("changecase.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"])
# Web application add case management
@app.route('/casemng', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ADMIN")
def case_management():
if request.method == "POST":
user = request.form.get("userSelect")
case_name = request.form.get('caseName')
try:
service = GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
except:
logger.error("[!] Can't connect Neo4j Database GraphService.")
sys.exit(1)
if "Enterprise" in service.product:
if not re.search(UCHECK, user) and re.search(r"\A[0-9a-zA-Z]{2,20}\Z", case_name):
add_db_access_role(service, user, case_name)
return render_template("casemng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='<div><div class="alert alert-success" role="alert">Added access role for case ' + case_name + ' of user ' + user + '</div></div>')
else:
return render_template("casemng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='<div><div class="alert alert-danger" role="alert">This feature is in Neo4j Enterprise.</div></div>')
else:
return render_template("casemng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='')
# Web application delete case management
@app.route('/delcasemng', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ADMIN")
def case_management_del():
if request.method == "POST":
user_db = [userlist.split("_") for userlist in request.form.getlist("userlist")]
try:
service = GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
except:
logger.error("[!] Can't connect Neo4j Database GraphService.")
sys.exit(1)
if "Enterprise" in service.product:
for user, case_name in user_db:
if not re.search(UCHECK, user) and re.search(r"\A[0-9a-zA-Z]{2,20}\Z", case_name):
delete_db_access_role(service, user, case_name)
return render_template("delcasemng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='<div><div class="alert alert-success" role="alert">Deleted access role to case ' + case_name + ' for user ' + user + '</div></div>')
else:
return render_template("delcasemng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='<div><div class="alert alert-danger" role="alert">This feature is in Neo4j Enterprise.</div></div>')
else:
return render_template("delcasemng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"], messages='')
# Web application user management
@app.route('/usermng', methods=['GET', 'POST'])
@http_request_logging
@login_required(role="ADMIN")
def user_management():
if request.method == "POST":
users = [userlist.strip("Check_") for userlist in request.form.getlist("userlist")]
action = request.form.get("action")
try:
service = GraphService(host=NEO4J_SERVER, user=session["username"], password=session["password"])
except:
logger.error("[!] Can't connect Neo4j Database GraphService.")
sys.exit(1)
if "delete" in action:
for user in users:
if not re.search(UCHECK, user):
delete_neo4j_user(service, user)
with app.app_context():
user_query = User.query.filter_by(username=user).first()
db.session.delete(user_query)
db.session.commit()
elif ("suspended" in action or "active" in action) and "Enterprise" in service.product:
for user in users:
if not re.search(UCHECK, user):
change_status_neo4j_user(service, user, action)
return render_template("usermng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"])
else:
return render_template("usermng.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"])
# Web application index.html
@app.route('/')
@http_request_logging
@login_required(role="ANY")
def index():
return render_template("index.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"])
# Timeline view
@app.route('/timeline')
@login_required(role="ANY")
@http_request_logging
def timeline():
return render_template("timeline.html", server_ip=NEO4J_SERVER, ws_port=WS_PORT, neo4j_password=session["password"], neo4j_user=session["username"], case_name=session["case"])
# Web application logs
@app.route('/log')
@login_required(role="ANY")
def logs():
with open(FPATH + "/static/logontracer.log", "r") as lf:
logdata = lf.read()
return logdata
# Sigma rule scan results
@app.route('/sigma')
@login_required(role="ANY")
def sigma():
with open(FPATH + "/static/sigma_results.csv", "r") as sf:
sigma_logs = sf.read()
return sigma_logs
# Web application upload
@app.route("/upload", methods=["POST"])
@login_required(role="ANY")
@http_request_logging
def do_upload():
UPLOAD_DIR = os.path.join(FPATH, 'upload')
filelist = ""
if os.path.exists(UPLOAD_DIR) is False:
os.makedirs(UPLOAD_DIR)
logger.info("[+] make upload folder {0}.".format(UPLOAD_DIR))
try:
timezone = request.form["timezone"]
logtype = request.form["logtype"]
addlog = request.form["addlog"]
sigmascan = request.form["sigmascan"]
casename = request.form["casename"]
for i in range(0, len(request.files)):
loadfile = "file" + str(i)
file = request.files[loadfile]
if file and file.filename:
if "EVTX" in logtype:
filename = os.path.join(UPLOAD_DIR, str(i) + ".evtx")
elif "XML" in logtype:
filename = os.path.join(UPLOAD_DIR, str(i) + ".xml")
else:
continue
file.save(filename)
filelist += filename + " "
if "EVTX" in logtype:
logoption = " -e "
elif "XML" in logtype:
logoption = " -x "
else:
return "FAIL"
if not re.search(r"\A-{0,1}[0-9]{1,2}\Z", timezone):
return "FAIL"
if addlog in "true":
add_option = "--add"
else:
add_option = "--delete"
if sigmascan in "true":
add_option += " --sigma"
if not re.search(r"\A[0-9a-zA-Z]{2,20}\Z", casename):
return "FAIL"
parse_command = "nohup python3 " + FPATH + "/logontracer.py " + add_option + " --case " + casename + " -z " + timezone + logoption + filelist + " -s " + NEO4J_SERVER + " -u " + session["username"] + " -p " + session["password"] + " > " + FPATH + "/static/logontracer.log 2>&1 &"
subprocess.call("rm -f " + FPATH + "/static/logontracer.log > /dev/null", shell=True)
subprocess.call(parse_command, shell=True)
# parse_evtx(filename)
return "SUCCESS"
except:
return "FAIL"
# Load from Elasticsearch
@app.route("/esload", methods=["POST"])
@login_required(role="ANY")
@http_request_logging
def es_load():
try:
fromdatetime = request.form["fromdatetime"]
todatetime = request.form["todatetime"]
timezone = request.form["timezone"]
es_server = request.form["es_server"]
addlog = request.form["addlog"]
casename = request.form["casename"]
addes = request.form["addes"]
if fromdatetime not in "false":
try:
datetime.datetime.strptime(fromdatetime, "%Y-%m-%dT%H:%M:%S")
fromdatetime = " -f " + fromdatetime
except:
return "FAIL"
else: