-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathmax.py
1679 lines (1443 loc) · 75.7 KB
/
max.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
#!/usr/bin/python3
import requests
from requests.auth import HTTPBasicAuth
import argparse
import json
import random
import csv
import binascii
import math
import os
import multiprocessing
import webbrowser
import getpass
import datetime
try:
import html as htmllib
except ImportError:
import cgi as htmllib
from itertools import zip_longest
# option to hardcode URL & URI or put them in environment variables, these will be used for neo4j database "default" location
global_url = "http://127.0.0.1:7474" if (not os.environ.get('NEO4J_URL', False)) else os.environ['NEO4J_URL']
global_uri = "/db/neo4j/tx/commit" if (not os.environ.get('NEO4J_URI', False)) else os.environ['NEO4J_URI']
# option to hardcode creds or put them in environment variables, these will be used as the username and password "defaults"
global_username = 'neo4j' if (not os.environ.get('NEO4J_USERNAME', False)) else os.environ['NEO4J_USERNAME']
global_password = 'bloodhound' if (not os.environ.get('NEO4J_PASSWORD', False)) else os.environ['NEO4J_PASSWORD']
def do_test(args):
try:
requests.get(args.url + global_uri)
return True
except:
return False
def do_query(args, query, data_format=None):
data_format = [data_format, "row"][data_format == None]
data = {
"statements" : [
{
"statement" : query,
"resultDataContents" : [ data_format ]
}
]
}
headers = {'Content-type': 'application/json', 'Accept': 'application/json; charset=UTF-8'}
auth = HTTPBasicAuth(args.username, args.password)
r = requests.post(args.url + global_uri, auth=auth, headers=headers, json=data)
if r.status_code == 401:
print("Authentication error: the supplied credentials are incorrect for the Neo4j database, specify new credentials with -u & -p or hardcode your credentials at the top of the script")
exit()
elif r.status_code >= 300:
print("Failed to retrieve data. Server returned status code: {}".format(r.status_code))
exit()
else:
return r
def get_query_output(entry,delimeter,cols_len=None,path=False):
if path:
try:
nodes = entry['graph']['nodes']
edges = entry['graph']['relationships']
node_end_list = []
node_dict = {}
edge_dict = {}
for node in nodes:
try:
node_dict[node['id']] = node['properties']['name']
except:
node_dict[node['id']] = node['properties']['objectid']
for edge in edges:
edge_dict[node_dict[edge['startNode']]] = ["-", edge['type'], "->", node_dict[edge['endNode']]]
node_end_list.append(node_dict[edge['endNode']])
for key in edge_dict.keys():
if key not in node_end_list:
first_node = key
path = [first_node]
key = first_node
while key in edge_dict:
for item in edge_dict[key]:
path.append(item)
key = path[len(path)-1]
return " ".join(path)
except:
return "Path not found :("
else:
try:
return " {} ".format(delimeter).join(entry["row"])
except:
if cols_len == 1:
pass
else:
return " {} ".format(delimeter).join(map(str,entry["row"]))
def get_info(args):
# key : {query: "", columns: []}
queries = {
"users" : {
"query" : "MATCH (u:User) {enabled} RETURN u.name",
"columns" : ["UserName"]
},
"comps" : {
"query" : "MATCH (n:Computer) RETURN n.name",
"columns" : ["ComputerName"]
},
"groups" : {
"query" : "MATCH (n:Group) RETURN n.name",
"columns" : ["GroupName"]
},
"group-members" : {
"query" : "MATCH (g:Group {{name:\"{gname}\"}}) MATCH (n)-[r:MemberOf*1..]->(g) RETURN DISTINCT n.name",
"columns" : ["ObjectName"]
},
"group-list" : {
"query" : "MATCH (u {{name:\"{uname}\"}}) MATCH (u)-[r:MemberOf*1..]->(g:Group) RETURN DISTINCT g.name",
"columns" : ["GroupName"]
},
"groups-full" : {
"query" : "MATCH (n),(g:Group) MATCH (n)-[r:MemberOf]->(g) RETURN DISTINCT g.name,n.name",
"columns" : ["GroupName","MemberName"]
},
"das" : {
"query" : "MATCH (n:User)-[r:MemberOf*1..]->(g:Group) WHERE g.objectid ENDS WITH '-512' RETURN DISTINCT n.name",
"columns" : ["UserName"]
},
"dasess" : {
"query" : "MATCH (u:User)-[r:MemberOf*1..]->(g:Group) WHERE g.objectid ENDS WITH '-512' WITH COLLECT(u) AS das MATCH (u2:User)<-[r2:HasSession]-(c:Computer) WHERE u2 IN das RETURN DISTINCT u2.name,c.name ORDER BY u2.name",
"columns" : ["UserName","ComputerName"]
},
"dcs" : {
"query" : "MATCH (n:Computer)-[r:MemberOf*1..]->(g:Group) WHERE g.objectid ENDS WITH '-516' RETURN DISTINCT n.name",
"columns" : ["ComputerName"]
},
"unconstrained" : {
"query" : "MATCH (g:Group) WHERE g.objectid ENDS WITH '-516' MATCH (c:Computer)-[MemberOf]->(g) WITH COLLECT(c) AS dcs MATCH (n {unconstraineddelegation:true}) WHERE NOT n IN dcs RETURN n.name",
"columns" : ["ObjectName"]
},
"nopreauth" : {
"query" : "MATCH (n:User) WHERE n.dontreqpreauth=TRUE RETURN n.name",
"columns" : ["UserName"]
},
"kerberoastable" : {
"query" : "MATCH (n:User {hasspn:true}) RETURN n.name",
"columns" : ["UserName"]
},
"kerberoastableLA" : {
"query" : "MATCH (n:User {hasspn:true}) MATCH p=shortestPath((n)-[r:AdminTo|MemberOf*1..4]->(c:Computer)) RETURN DISTINCT n.name",
"columns" : ["UserName"]
},
"sessions" : {
"query" : "MATCH (m {{name:'{uname}'}})<-[r:HasSession]-(n:Computer) RETURN DISTINCT n.name",
"columns" : ["ComputerName"]
},
"localadmin" : {
"query" : "MATCH (m {{name:'{uname}'}})-[r:AdminTo|MemberOf*1..4]->(n:Computer) RETURN DISTINCT n.name",
"columns" : ["ComputerName"]
},
"adminsof" : {
"query" : "MATCH p=shortestPath((m:Computer {{name:'{comp}'}})<-[r:AdminTo|MemberOf*1..]-(n)) RETURN DISTINCT n.name",
"columns" : ["UserName"]
},
"owned" : {
"query" : "MATCH (n) WHERE n.owned=true RETURN n.name",
"columns" : ["ObjectName"]
},
"owned-groups" : {
"query" : "MATCH (n {owned:true}) MATCH (n)-[r:MemberOf*1..]->(g:Group) RETURN DISTINCT n.name,g.name",
"columns" : ["ObjectName","GroupName"]
},
"hvt" : {
"query" : "MATCH (n) WHERE n.highvalue=true RETURN n.name",
"columns" : ["ObjectName"]
},
"desc" : {
"query" : "MATCH (n) WHERE n.description IS NOT NULL RETURN n.name,n.description",
"columns" : ["ObjectName","Description"]
},
"admincomps" : {
"query" : "MATCH (n:Computer),(m:Computer) MATCH (n)-[r:MemberOf|AdminTo*1..]->(m) RETURN DISTINCT n.name,m.name ORDER BY n.name",
"columns" : ["AdminComputerName","VictimCompterName"]
},
"nolaps" : {
"query" : "MATCH (c:Computer {haslaps:false}) RETURN c.name",
"columns" : ["ComputerName"]
},
"passnotreq" : {
"query" : "MATCH (u:User {{passwordnotreqd:true}}) {enabled} RETURN u.name",
"columns" : ["UserName"]
},
"passlastset" : {
"query" : "MATCH (u:User) WHERE u.pwdlastset < (datetime().epochseconds - ({days} * 86400)) AND NOT u.pwdlastset IN [-1.0,0.0] RETURN u.name,date(datetime({{epochSeconds:toInteger(u.pwdlastset)}})) AS changedate ORDER BY changedate DESC",
"columns" : ["UserName", "DateChanged"]
},
"sidhist" : {
"query" : "MATCH (n) WHERE n.sidhistory<>[] UNWIND n.sidhistory AS x OPTIONAL MATCH (d:Domain) WHERE x CONTAINS d.objectid OPTIONAL MATCH (m {objectid:x}) RETURN n.name,x,d.name,m.name ORDER BY n.name",
"columns" : ["ObjectName","SID","DomainName","ForeignObjectName"]
},
"unsupos" : {
"query" : "MATCH (c:Computer) WHERE toLower(c.operatingsystem) =~ '.*(2000|2003|2008|xp|vista| 7 |me).*' RETURN c.name,c.operatingsystem",
"columns" : ["ComputerName","OperatingSystem"]
},
"foreignprivs" : {
"query" : "MATCH p=(n1)-[r]->(n2) WHERE NOT n1.domain=n2.domain RETURN DISTINCT n1.name,TYPE(r),n2.name ORDER BY TYPE(r)",
"columns" : ["ObjectName","EdgeName","VictimObjectName"]
},
"owned-to-hvts" : {
"query" : "MATCH shortestPath((n {owned:True})-[*1..]->(m {highvalue:True})) RETURN DISTINCT n.name",
"columns" : ["UserName"]
},
"path" : {
"query" : "MATCH p=shortestPath((n1 {{name:'{start}'}})-[rels*1..]->(n2 {{name:'{end}'}})) RETURN p",
"columns" : ["Path"]
},
"paths-all" : {
"query" : "MATCH p=allShortestPaths((n1 {{name:'{start}'}})-[rels*1..]->(n2 {{name:'{end}'}})) RETURN p",
"columns" : ["Path"]
},
"hvtpaths" : {
"query" : "MATCH p=allShortestPaths((n1 {{name:'{start}'}})-[rels*1..]->(n2 {{highvalue:true}})) RETURN p",
"columns" : ["Path"]
},
"ownedpaths" : {
"query" : "MATCH p=allShortestPaths((n1 {owned:true})-[rels*1..]->(n2 {highvalue:true})) RETURN p",
"columns" : ["Path"]
},
"ownedadmins" : {
"query": "match (u:User {owned: True})-[r:AdminTo|MemberOf*1..]->(c:Computer) return c.name, \"AdministratedBy\", u.name order by c, u",
"columns": ["ComputerName", "HasAdmin", "UserName"]
}
}
query = ""
cols = []
data_format = "row"
if (args.users):
query = queries["users"]["query"]
cols = queries["users"]["columns"]
elif (args.comps):
query = queries["comps"]["query"]
cols = queries["comps"]["columns"]
elif (args.groups):
query = queries["groups"]["query"]
cols = queries["groups"]["columns"]
elif (args.groupsfull):
query = queries["groups-full"]["query"]
cols = queries["groups-full"]["columns"]
elif (args.das):
query = queries["das"]["query"]
cols = queries["das"]["columns"]
elif (args.dasess):
query = queries["dasess"]["query"]
cols = queries["dasess"]["columns"]
elif (args.dcs):
query = queries["dcs"]["query"]
cols = queries["dcs"]["columns"]
elif (args.unconstrained):
query = queries["unconstrained"]["query"]
cols = queries["unconstrained"]["columns"]
elif (args.nopreauth):
query = queries["nopreauth"]["query"]
cols = queries["nopreauth"]["columns"]
elif (args.kerberoastable):
query = queries["kerberoastable"]["query"]
cols = queries["kerberoastable"]["columns"]
elif (args.kerberoastableLA):
query = queries["kerberoastableLA"]["query"]
cols = queries["kerberoastableLA"]["columns"]
elif (args.passnotreq):
query = queries["passnotreq"]["query"]
cols = queries["passnotreq"]["columns"]
elif (args.passlastset != ""):
query = queries["passlastset"]["query"].format(days=args.passlastset.strip())
cols = queries["passlastset"]["columns"]
elif (args.sidhist):
query = queries["sidhist"]["query"]
cols = queries["sidhist"]["columns"]
elif (args.unsupos):
query = queries["unsupos"]["query"]
cols = queries["unsupos"]["columns"]
elif (args.owned):
query = queries["owned"]["query"]
cols = queries["owned"]["columns"]
elif (args.ownedgroups):
query = queries["owned-groups"]["query"]
cols = queries["owned-groups"]["columns"]
elif (args.hvt):
query = queries["hvt"]["query"]
cols = queries["hvt"]["columns"]
elif (args.desc):
query = queries["desc"]["query"]
cols = queries["desc"]["columns"]
elif (args.admincomps):
query = queries["admincomps"]["query"]
cols = queries["admincomps"]["columns"]
elif (args.nolaps):
query = queries["nolaps"]["query"]
cols = queries["nolaps"]["columns"]
elif (args.foreignprivs):
query = queries["foreignprivs"]["query"]
cols = queries["foreignprivs"]["columns"]
elif (args.ownedtohvts):
query = queries["owned-to-hvts"]["query"]
cols = queries["owned-to-hvts"]["query"]
elif (args.unamesess != ""):
query = queries["sessions"]["query"].format(uname=args.unamesess.upper().strip())
cols = queries["sessions"]["columns"]
elif (args.unameadminto != ""):
query = queries["localadmin"]["query"].format(uname=args.unameadminto.upper().strip())
cols = queries["localadmin"]["columns"]
elif (args.comp != ""):
query = queries["adminsof"]["query"].format(comp=args.comp.upper().strip())
cols = queries["adminsof"]["columns"]
elif (args.grouplist != ""):
query = queries["group-list"]["query"].format(uname=args.grouplist.upper().strip())
cols = queries["group-list"]["columns"]
elif (args.groupmems != ""):
query = queries["group-members"]["query"].format(gname=args.groupmems.upper().strip())
cols = queries["group-members"]["columns"]
elif (args.ownedadmins):
query = queries["ownedadmins"]["query"]
cols = queries["ownedadmins"]["columns"]
elif (args.path != ""):
start = args.path.split(',')[0].strip().upper()
end = args.path.split(',')[1].strip().upper()
query = queries["path"]["query"].format(start=start,end=end)
cols = queries["path"]["columns"]
data_format = "graph"
elif (args.pathsall != ""):
start = args.pathsall.split(',')[0].strip().upper()
end = args.pathsall.split(',')[1].strip().upper()
query = queries["paths-all"]["query"].format(start=start,end=end)
cols = queries["paths-all"]["columns"]
data_format = "graph"
elif (args.hvtpaths != ""):
start = args.hvtpaths.split(',')[0].strip().upper()
query = queries["hvtpaths"]["query"].format(start=start)
cols = queries["hvtpaths"]["columns"]
data_format = "graph"
elif (args.ownedpaths != ""):
query = queries["ownedpaths"]["query"]
cols = queries["ownedpaths"]["columns"]
data_format = "graph"
if args.getnote:
query = query + ",n.notes"
cols.append("Notes")
if args.enabled and "{enabled}" in query:
query = query.format(enabled="WHERE u.enabled=true")
elif "{enabled}" in query:
query = query.format(enabled="")
else:
pass
r = do_query(args, query, data_format=data_format)
x = json.loads(r.text)
# print(r.text)
entry_list = x["results"][0]["data"]
# print(entry_list)
if cols[0] == "Path":
for entry in entry_list:
print(get_query_output(entry,args.delimeter,path=True))
else:
if args.label:
print(" - ".join(cols))
for entry in entry_list:
print(get_query_output(entry,args.delimeter,cols_len=len(cols)))
def mark_owned(args):
if (args.clear):
query = 'MATCH (n) WHERE n.owned=true SET n.owned=false'
r = do_query(args,query)
print("[+] 'Owned' attribute removed from all objects.")
else:
note_string = ""
if args.notes != "":
note_string = "SET n.notes=\"" + args.notes + "\""
f = open(args.filename).readlines()
for line in f:
if args.userpass is True or args.store:
uname, passwd = line.strip().split(':')
uname = uname.upper()
if args.store:
passwd_query = "SET n.password=\"" + passwd + "\""
else:
passwd_query = ""
else:
uname = line.upper().strip()
query = 'MATCH (n) WHERE n.name="{uname}" SET n.owned=true {notes} {passwd} RETURN n'.format(uname=uname,passwd=passwd_query,notes=note_string)
r = do_query(args, query)
fail_resp = '{"results":[{"columns":["n"],"data":[]}],"errors":[]}'
if r.text == fail_resp:
print("[-] AD Object: " + uname + " could not be marked as owned")
else:
print("[+] AD Object: " + uname + " marked as owned successfully")
def mark_hvt(args):
if (args.clear):
query = 'MATCH (n) WHERE n.highvalue=true SET n.highvalue=false'
r = do_query(args,query)
print("[+] 'High Value' attribute removed from all objects.")
else:
note_string = ""
if args.notes != "":
note_string = "SET n.notes=\"" + args.notes + "\""
f = open(args.filename).readlines()
for line in f:
query = 'MATCH (n) WHERE n.name="{uname}" SET n.highvalue=true {notes} RETURN n'.format(uname=line.upper().strip(),notes=note_string)
r = do_query(args, query)
fail_resp = '{"results":[{"columns":["n"],"data":[]}],"errors":[]}'
if r.text == fail_resp:
print("[-] AD Object: " + line.upper().strip() + " could not be marked as HVT")
else:
print("[+] AD Object: " + line.upper().strip() + " marked as HVT successfully")
def query_func(args):
data_format = ["row", "graph"][args.path]
queries = []
if args.file == None and args.query == None:
print("Error: query requires -q/--query or -f/--file input")
return
elif args.query:
queries.append(args.query)
elif args.file != None:
queries = open(args.file,'r').readlines()
for i in range(0,len(queries)):
r = do_query(args, queries[i], data_format=data_format)
x = json.loads(r.text)
try:
entry_list = x["results"][0]["data"]
cols_len = 0
for entry in entry_list:
if not args.path:
cols_len = len(entry['row'])
output = get_query_output(entry, args.delimeter, cols_len=cols_len, path=args.path)
if output != None and args.file == None:
print(output)
if args.file != None:
print("Query {} executed".format(i+1))
except:
if x['errors'][0]['code'] == "Neo.ClientError.Statement.SyntaxError":
print("Neo4j syntax error")
print(x['errors'][0]['message'])
else:
print("Uncaught error, sry")
def export_func(args):
edges = [
"MemberOf",
"HasSession",
"AdminTo",
"AllExtendedRights",
"AddMember",
"ForceChangePassword",
"GenericAll",
"GenericWrite",
"Owns",
"WriteDacl",
"WriteOwner",
"ReadLAPSPassword",
"ReadGMSAPassword",
"Contains",
"GpLink",
"CanRDP",
"CanPSRemote",
"ExecuteDCOM",
"AllowedToDelegate",
"AddAllowedToAct",
"AllowedToAct",
"SQLAdmin",
"HasSIDHistory",
"HasSPNConfigured",
"SharesPasswordWith"
]
node_name = args.NODENAME.upper().strip()
query = "MATCH (n1 {{name:'{node_name}'}}) MATCH (n1)-[r:{edge}]->(n2) RETURN DISTINCT n2.name"
data = []
for edge in edges:
print("[*] Running " + edge + " collection...")
statement = query.format(node_name=node_name, edge=edge)
r = do_query(args, statement)
x = json.loads(r.text)
try:
entry_list = x["results"][0]["data"]
list = [edge]
for value in entry_list:
try:
list.append(value["row"][0])
except:
if len(value["row"]) == 1:
pass
else:
pass
if len(list) == 1:
pass
else:
data.append(list)
print("[+] Completed " + edge + " collection: " + str(len(entry_list)) + " relationships found")
except:
if x['errors'][0]['code'] == "Neo.ClientError.Statement.SyntaxError":
print("Neo4j syntax error")
print(x['errors'][0]['message'])
else:
print("Uncaught error, sry")
export_data = zip_longest(*data, fillvalue='')
filename = node_name.replace(" ","_") + ".csv"
with open(filename,'w', encoding='utf-8', newline='') as file:
wr = csv.writer(file)
wr.writerows(export_data)
file.close()
def delete_edge(args):
if args.STARTINGNODE:
query = 'MATCH ({{name:"{startingnode}"}})-[r:{edge}]->() DELETE r RETURN COUNT (DISTINCT("{startingnode}"))'.format(edge=args.EDGENAME,startingnode=args.STARTINGNODE)
filters = 'with \'{startingnode}\' starting node'.format(startingnode=args.STARTINGNODE)
else:
query = 'MATCH p=()-[r:{edge}]->() DELETE r RETURN COUNT(DISTINCT(p))'.format(edge=args.EDGENAME)
filters = ''
r = do_query(args,query)
number = int(json.loads(r.text)['results'][0]['data'][0]['row'][0] / 2)
print("[+] '{edge}' edge removed from {number} object relationships {filters}".format(edge=args.EDGENAME,number=number,filters=filters))
def add_spns(args):
statement = "MATCH (n:User {{name:\"{uname}\"}}) MATCH (m:Computer {{name:\"{comp}\"}}) MERGE (m)-[r:HasSPNConfigured {{isacl: false}}]->(n) return n,m"
# [ [computer, user], ... ]
objects = []
if args.filename != "":
lines = open(args.filename).readlines()
for line in lines:
try:
objects.append([line.split(',')[0].strip().upper(), line.split(',')[1].strip().upper()])
except:
print("[?] Failed parse for: " + line)
elif args.ifilename != "":
lines = open(args.ifilename).readlines()
lines = lines[4:] # trim first 4 output lines
spns = []
i = 0
while (i != len(lines) and lines[i].strip() != ''):
spns.append(list(filter(('').__ne__,lines[i].strip().split(" ")))) # impacket uses a 2 space value between items, use this split hack to get around spaces in values
i += 1
for line in spns:
try:
spn = line[0].split('/')[1].split(':')[0].strip().upper()
uname = line[1].strip().upper()
domain = '.'.join(line[2].strip().split("DC=")[1:]).replace(',','').upper()
if domain not in spn:
spn = spn + '.' + domain
uname = uname + '@' + domain
if [spn,uname] not in objects:
objects.append([spn,uname])
except:
print("[?] Failed parse for: " + line[0].strip() + " and " + line[1].strip())
elif args.blood:
statement1 = "MATCH (n:User {hasspn:true}) RETURN n.name,n.serviceprincipalnames"
r = do_query(args,statement1)
try:
spns = json.loads(r.text)['results'][0]['data']
print("[*] BloodHound data queried successfully")
for user in spns:
uname = user['row'][0]
domain = uname.split("@")[1]
for fullspn in user['row'][1]:
try:
spn = fullspn.split('/')[1].split(':')[0].strip().upper()
if domain not in spn:
spn = spn + "." + domain
if [spn,uname] not in objects:
objects.append([spn,uname])
except:
print("[?] Failed parse for user " + uname + " and SPN " + fullspn)
except:
print("[-] Error querying database")
else:
print("Invalid Option")
count = 0
for set in objects:
query = statement.format(uname=set[1],comp=set[0])
r = do_query(args, query)
fail_resp = '{"results":[{"columns":["n","m"],"data":[]}],"errors":[]}'
if r.text == fail_resp:
print("[-] Relationship " + set[0] + " -- HasSPNConfigured -> " + set[1] + " could not be added")
else:
print("[+] Relationship " + set[0] + " -- HasSPNConfigured -> " + set[1] + " added")
count = count + 1
print('[+] HasSPNConfigured relationships created: ' + str(count))
def add_spw(args):
statement = "MATCH (n {{name:\"{name1}\"}}),(m {{name:\"{name2}\"}}) MERGE (n)-[r1:SharesPasswordWith]->(m) MERGE (m)-[r2:SharesPasswordWith]->(n) return n,m"
objs = open(args.filename,'r').readlines()
count = 0
for i in range(0,len(objs)):
name1 = objs[i].strip().upper()
print("[+] Creating relationships for " + name1)
for j in range(i + 1,len(objs)):
name2 = objs[j].strip().upper()
#print("query: " + str(i) + ' ' + str(j))
query = statement.format(name1=name1,name2=name2)
r = do_query(args,query)
fail_resp = '{"results":[{"columns":["n","m"],"data":[]}],"errors":[]}'
if r.text != fail_resp:
count = count + 1
print("[+] SharesPasswordWith relationships created: " + str(count))
# code from https://github.com/clr2of8/DPAT/blob/master/dpat.py#L64
def dpat_sanitize(args, pass_or_hash):
if not args.sanitize:
return pass_or_hash
else:
sanitized_string = pass_or_hash
lenp = len(pass_or_hash)
if lenp == 32:
sanitized_string = pass_or_hash[0:4] + \
"*"*(lenp-8) + pass_or_hash[lenp-5:lenp-1]
elif lenp > 2:
sanitized_string = pass_or_hash[0] + \
"*"*(lenp-2) + pass_or_hash[lenp-1]
return sanitized_string
def dpat_parse_ntds(lines, ntds_parsed):
for line in lines:
if ":::" not in line or '$' in line: #filters out other lines in ntds/computer obj
continue
line = line.replace("\r", "").replace("\n", "")
if (line == ""):
continue
else:
line = line.split(":")
# [ username, domain, rid, LM, NT, plaintext||None]
to_append = []
if (line[0].split("\\")[0] == line[0]):
# no domain found, local account
to_append.append(line[0])
to_append.append("")
else:
to_append.append(line[0].split("\\")[1])
to_append.append(line[0].split("\\")[0])
to_append.append(line[1])
to_append.append(line[2])
to_append.append(line[3])
ntds_parsed.append(to_append)
def dpat_map_users(args, users, potfile):
count = 0
for user in users:
try:
nt_hash = user[4]
lm_hash = user[3]
ntds_uname = '/'.join(filter(None, [user[1], user[0]])).replace("\\","\\\\").replace("'","\\'")
username = str(user[0].upper().strip() + "@" + user[1].upper().strip()).replace("\\","\\\\").replace("'","\\'")
cracked_bool = 'false'
password = None
password_query = ''
if nt_hash in potfile:
cracked_bool = 'true'
password = potfile[nt_hash]
elif lm_hash != "aad3b435b51404eeaad3b435b51404ee" and lm_hash in potfile:
cracked_bool = 'true'
password = potfile[lm_hash]
if password != None:
if "$HEX[" in password:
print("[!] found $HEX[], stripping and unpacking")
password = binascii.unhexlify( str( password.split("[")[1].replace("]", "") ) ).decode("utf-8")
password = password.replace("\\","\\\\").replace("'","\\'")
password_query = "SET u.password='{pwd}'".format(pwd=password)
cracked_query = "SET u.cracked={cracked_bool} SET u.nt_hash='{nt_hash}' SET u.lm_hash='{lm_hash}' SET u.ntds_uname='{ntds_uname}' {password}".format(cracked_bool=cracked_bool,nt_hash=nt_hash,lm_hash=lm_hash,ntds_uname=ntds_uname,password=password_query)
query1 = "MATCH (u:User) WHERE u.name='{username1}' OR (u.name STARTS WITH '{username2}@' AND u.objectid ENDS WITH '-{rid}') {cracked_query} RETURN u.name,u.objectid".format(username1=username, username2=user[0].replace("\\","\\\\").replace("'","\\'").upper(), rid=user[2].upper(), cracked_query=cracked_query)
r1 = do_query(args,query1)
bh_users = json.loads(r1.text)['results'][0]['data']
# if bh_users == [] then the user was not found in BH
if bh_users != []:
count = count + 1
except Exception as g:
print("[-] Mapping ERROR: {} FOR USER {}".format(g, user[0]))
# print('{}'.format(g))
# print(query1)
pass
return count
def dpat_func(args):
query_counts = {}
if args.clear:
print("[+] Clearing attributes from all users: cracked, password, nt_hash, lm_hash, ntds_uname")
clear_query = "MATCH (u:User) REMOVE u.cracked REMOVE u.nt_hash REMOVE u.lm_hash REMOVE u.ntds_uname REMOVE u.password"
do_query(args,clear_query)
return
if ((args.output) and (not args.csv and not args.html)):
print("[-] Error, --output requires --csv and/or --html type output flags")
return
if not args.noparse:
if args.ntdsfile != None:
ntds = open(args.ntdsfile, 'r').readlines()
else:
print("[-] Error, Need NTDS file")
return
if args.crackfile == None:
print("[-] Error, Need crackfile")
return
try:
print("[+] Processing NTDS")
num_lines = len(ntds)
# create threads to parse file
procs = []
manager = multiprocessing.Manager()
ntds_parsed = manager.list()
num_threads = int(args.num_threads)
for t in range(0, num_threads):
start = math.ceil((num_lines / num_threads) * t)
end = math.ceil((num_lines / num_threads) * (t + 1))
p = multiprocessing.Process(target=dpat_parse_ntds, args=(ntds[ start : end ], ntds_parsed, ))
p.start()
procs.append(p)
for p_ in procs:
p_.join()
# destroy managed list
"""
ntds_parsed = {
[uname, domain, rid, lm hash, nt hash, password] ....
}
"""
ntds_parsed = list(ntds_parsed)
# done parsing
print("[+] Processing Potfile")
# password stats like counting reused cracked passwords
potfile = {}
with open(args.crackfile,'r') as pot:
for line in pot.readlines():
try:
line = line.strip().replace("$NT$", "").replace("$LM$", "")
if (line == ""):
continue
line = line.split(":")
if len(line[0]) != 32:
continue
potfile[line[0]] = line[1]
except:
pass
print('[+] Mapping NTDS users to BloodHound data')
num_lines = len(ntds_parsed)
# create threads to parse file
procs = []
num_threads = int(args.num_threads)
for t in range(0, num_threads):
start = math.ceil((num_lines / num_threads) * t)
end = math.ceil((num_lines / num_threads) * (t + 1))
p = multiprocessing.Process(target=dpat_map_users, args=(args, ntds_parsed[ start : end ], potfile, ))
p.start()
procs.append(p)
for p_ in procs:
p_.join()
count_query = "MATCH (u:User) WHERE u.cracked IS NOT NULL RETURN COUNT(u.name)"
r = do_query(args,count_query)
resp = json.loads(r.text)['results'][0]['data']
count = resp[0]['row'][0]
print("[+] BloodHound data queried successfully, {} NTDS users mapped to BH data".format(count))
if count < 10:
print("[-] Warning: Less than 10 users mapped to BloodHound entries, verify the NTDS data matches the Neo4j data, continuing...")
except Exception as e:
print("[-] Error, {}".format(e))
return
###
### Searching for specific user/password
###
# TODO: do this stuff pre-processing for the love
# TODO: Output other info like hashes, full names, etc
if args.passwd:
print("[+] Searching for users with password '{}'".format(args.passwd))
query = "MATCH (u:User {{cracked:true}}) WHERE u.password='{pwd}' RETURN u.name".format(pwd=args.passwd.replace("\\","\\\\").replace("'","\\'"))
r = do_query(args,query)
resp = json.loads(r.text)['results'][0]['data']
print("[+] Users: {}\n".format(len(resp)))
for entry in resp:
print(entry['row'][0])
return
if args.usern:
print("[+] Searching for password for user {}".format(args.usern))
query = "MATCH (u:User) WHERE toUpper(u.name)='{uname}' OR toUpper(u.ntds_uname)='{uname}' RETURN u.name,u.password".format(uname=args.usern.upper().replace("\\","\\\\").replace("'","\\'"))
r = do_query(args,query)
resp = json.loads(r.text)['results'][0]['data']
if resp == []:
print("[-] User {uname} not found".format(uname=args.usern))
elif resp[0]['row'][1] == None:
print("[-] User {uname} not cracked, no password found".format(uname=args.usern))
else:
print("[+] Password for user {uname}: {pwd}".format(uname=args.usern,pwd=dpat_sanitize(args, resp[0]['row'][1])))
return
###
### Automated Cypher Queries for standard stuff, outputting users
###
queries = [
{
'query' : "MATCH (u:User) RETURN DISTINCT u.enabled,u.ntds_uname,u.nt_hash,u.password",
'label' : "All User Accounts"
},
{
'query' : "MATCH (u:User {cracked:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "All User Accounts Cracked"
},
{
"query" : "MATCH p=(u:User {cracked:true}) WHERE u.enabled = TRUE RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Enabled User Accounts Cracked"
},
{
'query' : "match p = (k:Group)<-[:MemberOf*1..]-(m) where k.highvalue = true WITH [ n in nodes(p) WHERE n:User] as ulist UNWIND (ulist) as u RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "High Value User Accounts Cracked"
},
{
'query' : "match p = (n:Group)<-[:MemberOf*1..]-(m) where n.objectid =~ '(?i)S-1-5-.*-512' with [ n IN nodes(p) WHERE n:User] as dalist unwind (dalist) as u RETURN DISTINCT u.enabled,u.ntds_uname,u.nt_hash,u.password",
'label' : "Domain Admin Members"
},
{
'query' : "match p = (n:Group)<-[:MemberOf*1..]-(m) where n.objectid =~ '(?i)S-1-5-.*-512' with [ n IN nodes(p) WHERE n:User] as dalist unwind (dalist) as u MATCH (u {cracked:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "Domain Admin Members Cracked"
},
{
'query' : "match p = (n:Group)<-[:MemberOf*1..]-(m) where n.objectid =~ '(?i)S-1-5-.*-519' with [ n IN nodes(p) WHERE n:User] as dalist unwind (dalist) as u RETURN DISTINCT u.enabled,u.ntds_uname,u.nt_hash,u.password",
'label' : "Enterprise Admin Members"
},
{
'query' : "match p = (n:Group)<-[:MemberOf*1..]-(m) where n.objectid =~ '(?i)S-1-5-.*-519' with [ n IN nodes(p) WHERE n:User] as dalist unwind (dalist) as u MATCH (u {cracked:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "Enterprise Admin Accounts Cracked"
},
{
'query' : "match p = (n:Group)<-[:MemberOf*1..]-(m) where n.objectid =~ '(?i)S-1-5-.*-544' with [ n IN nodes(p) WHERE n:User] as dalist unwind (dalist) as u RETURN DISTINCT u.enabled,u.ntds_uname,u.nt_hash,u.password",
'label' : "Administrator Group Members"
},
{
'query' : "match p = (n:Group)<-[:MemberOf*1..]-(m) where n.objectid =~ '(?i)S-1-5-.*-544' with [ n IN nodes(p) WHERE n:User] as dalist unwind (dalist) as u MATCH (u {cracked:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "Administrator Group Member Accounts Cracked"
},
{
'query' : "MATCH (u:User {cracked:true,hasspn:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "Kerberoastable Users Cracked"
},
{
'query' : "MATCH (u:User {cracked:true,dontreqpreauth:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "Accounts Not Requiring Kerberos Pre-Authentication Cracked"
},
{
'query' : "MATCH (u:User {cracked:true,unconstraineddelegation:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
'label' : "Unconstrained Delegation Accounts Cracked"
},
{
"query" : "MATCH (u:User {cracked:true}) WHERE u.lastlogon < (datetime().epochseconds - (182 * 86400)) AND NOT u.lastlogon IN [-1.0, 0.0] RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Inactive Accounts (Last Used Over 6mos Ago) Cracked"
},
{
"query" : "MATCH (u:User {cracked:true}) WHERE u.pwdlastset < (datetime().epochseconds - (365 * 86400)) AND NOT u.pwdlastset IN [-1.0, 0.0] RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Passwords Set Over 1yr Ago Cracked"
},
{
"query" : "MATCH (u:User {cracked:true,pwdneverexpires:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Passwords That Never Expire Cracked"
},
]
intense_queries = [
{
"query" : "match k = (n:Group)<-[:MemberOf*1..]-(m) where n.objectid ENDS WITH '-516' AND NOT (n = m) with [c in nodes(k) WHERE c:Computer] as dcs match p = shortestPath((n)-[:HasSession|AdminTo|Contains|AZLogicAppContributor*1..]->(m {unconstraineddelegation: true})) where not (n = m) AND NOT ( m IN dcs ) with [ n IN nodes(p) WHERE n:User] as ulist UNWIND ulist as u MATCH (u {cracked:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Paths To Unconstrained Delegation Objects Cracked (Excluding DCs)"
},
{
"query" : "match p = shortestPath((u)-[*1..]->(n)) where n.highvalue = true AND u <> n WITH [n in nodes(p) WHERE n:User] as ulist UNWIND(ulist) as u MATCH (u {cracked:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Paths To High Value Targets Cracked"
},
{
"query" : "MATCH p1=(u:User {cracked:true})-[r:AdminTo]->(n1) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Explicit Admin Rights Cracked"
},
{
"query" : "MATCH p2=(u:User {cracked:true})-[r1:MemberOf*1..]->(g:Group)-[r2:AdmintTo]->(n2) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Group Delegated Admin Rights Cracked"
},
{
"query" : "MATCH p1=(u:User {cracked:true})-[r:AllExtendedRights|AddMember|ForceChangePassword|GenericAll|GenericWrite|Owns|WriteDacl|WriteOwner|ReadLAPSPassword|ReadGMSAPassword|CanRDP|CanPSRemote|ExecuteDCOM|AllowedToDelegate|AddAllowedToAct|AllowedToAct|SQLAdmin|HasSIDHistory]->(n1) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Explicit Controlling Privileges Cracked"
},
{
"query" : "MATCH p2=(n)-[r1:MemberOf*1..]->(g:Group)-[r2:AllExtendedRights|AddMember|ForceChangePassword|GenericAll|GenericWrite|Owns|WriteDacl|WriteOwner|ReadLAPSPassword|ReadGMSAPassword|CanRDP|CanPSRemote|ExecuteDCOM|AllowedToDelegate|AddAllowedToAct|AllowedToAct|SQLAdmin|HasSIDHistory]->(n2) WITH [u in nodes(p2) WHERE u:User] AS ulist UNWIND(ulist) AS u MATCH (u {cracked:true}) RETURN DISTINCT u.enabled,u.ntds_uname,u.password,u.nt_hash",
"label" : "Accounts With Group Delegated Controlling Privileges Cracked"
}
]
if not args.less:
queries = queries + intense_queries
else:
print("[*] Less flag enabled, omitting high-intensity queries")