-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhashstat.py
More file actions
executable file
·1190 lines (1099 loc) · 57.2 KB
/
Copy pathhashstat.py
File metadata and controls
executable file
·1190 lines (1099 loc) · 57.2 KB
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/env python3
"""
hashstat -- NTDS / pwdump password-hygiene analyzer
by Leon Johnson
Parses an NTDS.dit / pwdump file (domain\\user:rid:lm:nt:::) and reports:
* overview counts (accounts, blanks, unique, domains)
* password reuse (shared-password clusters, top offenders)
* the "security story" (admin/service/tier-crossing reuse -- the WHY)
* weak + shared overlap (clusters whose password was also cracked)
* cracked-password stats (via `john --show` or a --potfile)
* hygiene / positives (username==password, LM hashes, blanks)
Every section prints a plain-English "what this means" line so a single
screenshot reads clearly on its own. Machine accounts ($) are excluded.
"""
import os
import re
import csv
import sys
import time
import json
import glob
import shutil
import argparse
import subprocess
from collections import defaultdict, Counter
BLANK_NT = "31d6cfe0d16ae931b73c59d7e0c089c0" # NT hash of an empty password
BLANK_LM = "aad3b435b51404eeaad3b435b51404ee" # LM hash of an empty password
BLANK_LM_HALF = "aad3b435b51404ee" # LM hash of an empty 7-byte half
# ---------------------------------------------------------------- colors
class C:
NONE = '\033[0m'
RED = '\033[0;31m'
GREEN = '\033[0;32m'
ORANGE = '\033[0;33m'
BLUE = '\033[0;34m'
PURPLE = '\033[0;35m'
CYAN = '\033[0;36m'
GRAY = '\033[0;37m' # light gray -- visible on black terminals (was 1;30 "bright black")
LRED = '\033[1;31m'
LGREEN = '\033[1;32m'
YELLOW = '\033[1;33m'
LBLUE = '\033[1;34m'
LPURP = '\033[1;35m'
LCYAN = '\033[1;36m'
WHITE = '\033[1;37m'
def disable_colors():
for name in dir(C):
if name.isupper():
setattr(C, name, '')
build_tag() # rebuild the category->color map with colors cleared
BANNER = r"""
_ _ _ _
| |__ __ _ ___| |__ ___| |_ __ _| |_
| '_ \ / _` / __| '_ \/ __| __/ _` | __|
| | | | (_| \__ \ | | \__ \ || (_| | |_
|_| |_|\__,_|___/_| |_|___/\__\__,_|\__|
NTDS reuse / weak-password analyzer
"""
# ---------------------------------------------------------------- helpers
ADMIN_RE = re.compile(r'^(a_|adm_|adm-|admin)', re.I)
SERVICE_RE = re.compile(r'^(svc[_-]|s_|srv[_-])', re.I)
TEST_RE = re.compile(r'(^t_|^test|test$|_test)', re.I)
SYNC_RE = re.compile(r'^msol_', re.I)
# anchor on the tail (:rid:lm:nt:::) so a NetExec "SMB <ip> 445 <HOST> " banner
# prefix -- or any leading junk -- in front of domain\user is tolerated.
NT_TAIL = re.compile(r':(\d+):([0-9a-fA-F]{32}):([0-9a-fA-F]{32}):::\s*$', re.I)
DOM_USER = re.compile(r'(\S+)\\(.*)$') # domain (no spaces) \ user (may have spaces)
TAG = {}
def build_tag(): # category -> (label, color); rebuilt if colors get disabled
TAG.update({
'admin': ('ADMIN', C.LRED),
'service': ('SERVICE', C.ORANGE),
'test': ('TEST', C.PURPLE),
'sync': ('SYNC', C.BLUE),
'user': ('user', C.GRAY),
})
build_tag()
def clean_login(acct_str):
"""Normalize a pwdump/john login to 'domain\\user' (domain lowercased),
stripping any NetExec 'SMB <ip> 445 <HOST>' banner prefix."""
dm = DOM_USER.search(acct_str)
if dm:
return f"{dm.group(1).lower()}\\{dm.group(2)}"
toks = acct_str.split()
return toks[-1] if toks else acct_str
def classify(user):
base = user.split('\\')[-1].lower()
if ADMIN_RE.search(base): return 'admin'
if SERVICE_RE.search(base): return 'service'
if SYNC_RE.search(base): return 'sync'
if TEST_RE.search(base): return 'test'
return 'user'
def name_key(user):
"""Identity key: strip admin/service prefix, order-insensitive name parts.
Lets a_dragan.mlikota, a_mlikota.dragan, and dragan.mlikota collapse to one
person so we can spot the same human reusing across privileged/standard IDs."""
base = user.split('\\')[-1].lower()
base = ADMIN_RE.sub('', base)
base = SERVICE_RE.sub('', base)
parts = [p for p in re.split(r'[._-]+', base) if p]
return frozenset(parts)
# ---- redaction (screenshot mode) -----------------------------------------
REDACT = False
_ALIAS = {}
def build_alias(d):
"""Assign a stable label to each distinct cracked password (most common = pw-01)
so a redacted screenshot still shows which accounts share a secret."""
for i, (pw, _) in enumerate(Counter(d.cracked.values()).most_common(), 1):
_ALIAS[pw] = f"pw-{i:02d}"
def pwdisp(pw, quote=True):
if REDACT:
return f"<{_ALIAS.get(pw, 'pw-??')}·{len(pw)}ch>"
return repr(pw) if quote else pw
def hashdisp(h):
return (h[:6] + '…') if REDACT else h
def section(title, subtitle=''):
line = f"{C.CYAN}══ {C.WHITE}{title}{C.NONE}"
if subtitle:
line += f" {C.GRAY}{subtitle}{C.NONE}"
print("\n" + line)
print(f"{C.CYAN}{'─'*66}{C.NONE}")
def meaning(text):
print(f"{C.GRAY} ↳ what this means: {text}{C.NONE}")
def kv(label, value, color=None, width=30):
color = C.ORANGE if color is None else color
print(f" {label:<{width}}{color}{value}{C.NONE}")
def tagged(user, cat=None):
cat = cat or classify(user)
label, color = TAG[cat]
return f"{color}{user.split(chr(92))[-1]}{C.NONE}"
# ---------------------------------------------------------------- parsing
class Dump:
def __init__(self):
self.accounts = [] # list of dict(user, domain, rid, lm, nt)
self.machine = 0
self.malformed = 0
self.by_nt = defaultdict(list) # nt -> [account,...]
self.cracked = {} # nt(lower) -> plaintext
self.lm_cracked = set() # nt of accounts recovered via LM (plaintext uppercase)
self.enriched = False # set once BloodHound data is joined
self.matched = 0 # accounts matched to BloodHound
self.disabled_pool = [] # disabled accounts, kept aside for -D
self.filtered = False # True once disabled accounts are excluded
self.has_groups = False # set once a BloodHound groups file is joined
self.priv = {} # group name -> set of member SIDs
def parse(self, path):
try:
fh = open(path, encoding='latin-1')
except IOError:
print(f"{C.RED}[!] cannot open {path}{C.NONE}")
sys.exit(1)
for raw in fh:
line = raw.rstrip('\r\n')
m = NT_TAIL.search(line)
if not m:
if line.strip() and ':::' in line:
self.malformed += 1
continue
rid, lm, nt = m.group(1), m.group(2).lower(), m.group(3).lower()
acct_str = line[:m.start()] # strips any banner prefix later
dm = DOM_USER.search(acct_str)
if dm:
domain, user = dm.group(1).lower(), dm.group(2)
else: # no domain\ -- take last token
toks = acct_str.split()
domain, user = '', (toks[-1] if toks else acct_str)
if user.endswith('$'): # machine account
self.machine += 1
continue
full = f"{domain}\\{user}" if domain else user
acct = {'user': full, 'domain': domain, 'rid': rid, 'lm': lm, 'nt': nt}
self.accounts.append(acct)
self.by_nt[nt].append(acct)
fh.close()
# ---- derived views -------------------------------------------------
@property
def non_blank(self):
return [a for a in self.accounts if a['nt'] != BLANK_NT]
@property
def blanks(self):
return [a for a in self.accounts if a['nt'] == BLANK_NT]
@property
def clusters(self):
"""reused non-blank hashes -> member accounts, largest first"""
cl = [(nt, accts) for nt, accts in self.by_nt.items()
if nt != BLANK_NT and len(accts) > 1]
return sorted(cl, key=lambda x: len(x[1]), reverse=True)
@property
def lm_present(self):
return [a for a in self.accounts if a['lm'] and a['lm'] != BLANK_LM]
def _john_show(self, path, fmt):
"""{cleaned-login: plaintext} from `john --show --format=<fmt>` (None if john/format absent)."""
try:
out = subprocess.check_output(['john', '--show', f'--format={fmt}', path],
stderr=subprocess.DEVNULL).decode('utf-8', 'ignore')
except (subprocess.CalledProcessError, FileNotFoundError):
return None
user_pw = {}
for line in out.splitlines():
if not line or 'password hashes cracked' in line: # john's summary line
continue
# login may contain colons only inside a banner; password is the field
# right before the trailing :rid:lm:nt::: -- recover login+password robustly
tail = NT_TAIL.search(line)
body = line[:tail.start()] if tail else line
if ':' not in body:
continue
login, pw = body.rsplit(':', 1)
if pw != '':
user_pw[clean_login(login).lower()] = pw
return user_pw
def load_cracked_from_john(self, path):
nt = self._john_show(path, 'nt')
lm = self._john_show(path, 'lm') # uppercase; '?' marks an uncracked half
if nt is None and lm is None:
return False
nt, lm = nt or {}, lm or {}
for a in self.accounts:
login = a['user'].lower()
pw = nt.get(login)
if pw: # prefer the true-case NT crack
self.cracked[a['nt']] = pw
continue
lpw = lm.get(login) # else fall back to a full LM recovery
if lpw and '?' not in lpw:
self.cracked[a['nt']] = lpw
self.lm_cracked.add(a['nt'])
return True
def load_cracked_from_potfile(self, path):
"""Read a john or hashcat potfile. Handles NT (`$NT$<hash>:pw` or `<32hex>:pw`,
i.e. hashcat mode 1000) and LM half cracks (`$LM$<hash>:pw` or `<16hex>:pw`,
i.e. hashcat mode 3000), combining an account's two LM halves into its password."""
try:
fh = open(path, encoding='latin-1')
except IOError:
return False
lm_half = {}
for line in fh:
line = line.rstrip('\r\n')
if not line or ':' not in line:
continue
m = re.match(r'^\$NT\$([0-9a-fA-F]{32}):(.*)$', line)
if m:
self.cracked[m.group(1).lower()] = m.group(2); continue
m = re.match(r'^\$LM\$([0-9a-fA-F]{16}):(.*)$', line)
if m:
lm_half[m.group(1).lower()] = m.group(2); continue
h, pw = line.split(':', 1)
h = h.lower()
if re.fullmatch(r'[0-9a-fA-F]{32}', h): # NT hash (hashcat -m 1000)
self.cracked[h] = pw
elif re.fullmatch(r'[0-9a-fA-F]{16}', h): # LM half (hashcat -m 3000)
lm_half[h] = pw
fh.close()
if lm_half: # combine halves per account
for a in self.accounts:
if a['nt'] in self.cracked or len(a['lm']) != 32:
continue
h1, h2 = a['lm'][:16], a['lm'][16:]
p1 = '' if h1 == BLANK_LM_HALF else lm_half.get(h1)
p2 = '' if h2 == BLANK_LM_HALF else lm_half.get(h2)
if p1 is not None and p2 is not None and (p1 + p2):
self.cracked[a['nt']] = p1 + p2
self.lm_cracked.add(a['nt'])
return True
def enrich(self, bh):
"""Join BloodHound user records onto accounts (by sAMAccountName, then RID)."""
self.enriched = True; self.matched = 0
for a in self.accounts:
sam = a['user'].split('\\')[-1].lower()
try: rid = int(a['rid'])
except ValueError: rid = None
rec = bh.lookup(sam, rid)
if rec:
self.matched += 1
a['sid'] = rec['sid']
a['enabled'] = rec['enabled']
a['admincount'] = rec['admincount']
a['hasspn'] = rec['hasspn']
a['passwordnotreqd'] = rec['passwordnotreqd']
a['pwdneverexpires'] = rec['pwdneverexpires']
a['pwdlastset'] = rec['pwdlastset']
a['lastlogon'] = rec['lastlogon']
else:
a['enabled'] = None
def load_groups(self, members):
"""Resolve privileged-group membership (nested) from a BloodHound groups file."""
self.has_groups = True
self.priv = {
'Domain Admin': _resolve_group_users(members, lambda s: s.endswith('-512')),
'Enterprise Admin': _resolve_group_users(members, lambda s: s.endswith('-519')),
'Administrators': _resolve_group_users(members, lambda s: s.endswith('S-1-5-32-544')),
}
def apply_enabled_filter(self, include_disabled):
"""Set aside disabled accounts (always, for -D). Unless include_disabled,
also exclude them from the analysis set. Returns #excluded."""
if not self.enriched:
return 0
self.disabled_pool = [a for a in self.accounts if a.get('enabled') is False]
if include_disabled:
return 0
self.filtered = True
self.accounts = [a for a in self.accounts if a.get('enabled') is not False]
self.by_nt = defaultdict(list)
for a in self.accounts:
self.by_nt[a['nt']].append(a)
return len(self.disabled_pool)
@property
def disabled(self):
return self.disabled_pool if self.enriched else []
@property
def excluded(self):
"""Disabled accounts actually removed from analysis; empty under --include-disabled."""
return self.disabled_pool if self.filtered else []
# ---------------------------------------------------------------- bloodhound
class BH:
"""Index of BloodHound user records for enrichment lookups."""
def __init__(self):
self.by_sam = defaultdict(list); self.count = 0; self.domains = set()
def add(self, rec):
self.count += 1
if rec['sam']:
self.by_sam[rec['sam']].append(rec)
def lookup(self, sam, rid):
# Match on sAMAccountName only. RID is used ONLY to disambiguate the same
# name across domains -- never as a fallback, since RIDs (1000+) collide
# across every domain and would spuriously match unrelated datasets.
c = self.by_sam.get(sam)
if not c:
return None
if len(c) == 1:
return c[0]
for r in c:
if r['rid'] == rid:
return r
return c[0]
def _find_json(dirpath, pat):
hits = sorted(glob.glob(os.path.join(dirpath, pat)))
return hits[0] if hits else None
def _load_json(path):
try:
with open(path, encoding='utf-8') as f:
return json.load(f)
except (IOError, ValueError) as e:
print(f"{C.RED}[!] cannot read {path}: {e}{C.NONE}"); sys.exit(1)
def load_bh_groups(path):
"""group SID -> [(member SID, member type)] from a BloodHound groups JSON."""
doc = _load_json(path)
data = (doc.get('data') or []) if isinstance(doc, dict) else (doc or [])
members = {}
for g in data:
sid = str(g.get('ObjectIdentifier') or '')
members[sid] = [(str(m.get('ObjectIdentifier') or ''), m.get('ObjectType') or '')
for m in (g.get('Members') or [])]
return members
def _resolve_group_users(members, is_target):
"""Transitively collect user SIDs of every group matching is_target (handles nesting)."""
users, seen, stack = set(), set(), [s for s in members if is_target(s)]
while stack:
g = stack.pop()
if g in seen:
continue
seen.add(g)
for msid, mtype in members.get(g, []):
if not msid:
continue
(stack.append(msid) if mtype == 'Group' else users.add(msid))
return users
def load_bloodhound(path):
"""Load BloodHound users (v3-v5 or raw list) + optional groups. Accepts a file or a dir;
when given the users file, a sibling *groups*.json is auto-discovered."""
if os.path.isdir(path):
users_path = _find_json(path, '*[uU]sers*.json')
groups_path = _find_json(path, '*[gG]roups*.json')
if not users_path:
print(f"{C.RED}[!] no *users*.json under {path}{C.NONE}"); sys.exit(1)
else:
users_path = path
groups_path = _find_json(os.path.dirname(path) or '.', '*[gG]roups*.json')
doc = _load_json(users_path)
data = (doc.get('data') or doc.get('users') or []) if isinstance(doc, dict) else doc
bh = BH()
for u in data:
p = u.get('Properties') or {}
oid = str(u.get('ObjectIdentifier') or p.get('objectid') or '')
try: rid = int(oid.rsplit('-', 1)[-1])
except (ValueError, AttributeError): rid = None
sam = (p.get('samaccountname') or '').lower()
if not sam and p.get('name'):
sam = str(p['name']).split('@')[0].lower()
dom = (p.get('domain') or '').lower()
if dom:
bh.domains.add(dom)
bh.add({'sam': sam, 'rid': rid, 'sid': oid, 'enabled': p.get('enabled'),
'admincount': bool(p.get('admincount')), 'hasspn': bool(p.get('hasspn')),
'passwordnotreqd': bool(p.get('passwordnotreqd')),
'pwdneverexpires': bool(p.get('pwdneverexpires')),
'pwdlastset': p.get('pwdlastset'), 'lastlogon': p.get('lastlogontimestamp')})
groups = load_bh_groups(groups_path) if groups_path else None
return bh, users_path, groups
def en_str(a):
en = a.get('enabled')
return 'disabled' if en is False else 'enabled' if en is True else 'unknown'
def _enrich_cols(d, a):
return [en_str(a), bool(a.get('admincount')), bool(a.get('hasspn'))] if d.enriched else []
def _enrich_hdr(d):
return ['enabled', 'admincount', 'hasspn'] if d.enriched else []
# ---------------------------------------------------------------- reports
def _ov_plain(d, M):
section("OVERVIEW", d.accounts[0]['domain'] or '(no domain in file)' if d.accounts else '')
B = M['base']; LW = 32
def row(label, val, color=C.ORANGE, ind=0, pct=None):
s = f" {' '*ind + label:<{LW}}{color}{val:>9}{C.NONE}"
if pct is not None:
s += f" {C.GRAY}{'('+pct+')':>6}{C.NONE}"
print(s)
def stat(label, n, color=C.ORANGE):
row(label, f"{n:,}", color, ind=2, pct=pctstr(n, B))
row("Records parsed", f"{M['records']:,}", C.WHITE)
row("Machine accounts removed", f"{M['machine']:,}", C.GRAY)
row("User accounts", f"{M['users']:,}", C.WHITE)
if d.filtered:
row("analyzed (enabled)", f"{M['analyzed']:,}", C.GREEN, ind=2)
row("excluded (disabled)", f"{M['excluded']:,}", C.RED, ind=2)
row("with a password", f"{M['nonblank']:,}", C.ORANGE, ind=2)
row("with a BLANK password", f"{M['blanks']:,}", C.RED if M['blanks'] else C.GREEN, ind=2)
row("Unique passwords", f"{M['unique']:,}", C.ORANGE)
dom_counts = Counter(a['domain'] for a in d.accounts if a['domain'])
row("Domains in file", f"{len(dom_counts)}", C.CYAN)
for dom, n in dom_counts.most_common(6):
print(f" {C.CYAN}{dom:<26}{C.NONE}{C.GRAY}{n:>9,}{C.NONE}")
if len(dom_counts) > 6:
print(f" {C.GRAY}+ {len(dom_counts)-6} more{C.NONE}")
if d.enriched:
print()
print(f" {'BloodHound matched':<{LW}}{C.CYAN}{d.matched:,} / {M['users']:,}{C.NONE}")
row("disabled accounts", f"{len(d.disabled):,}", C.RED if d.disabled else C.GREEN, ind=2)
stat("no password required", M['nopass'], C.RED)
stat("non-expiring password", M['nonexp'])
stat("password age > 90 days", M['pw90'])
stat("password age > 1 year", M['pw1y'])
stat("unused > 90 days", M['un90'])
stat("unused > 1 year", M['un1y'])
stat("adminCount (privileged)", M['priv'], C.LRED)
if d.has_groups:
stat("Domain Admin rights", M['da'], C.LRED)
stat("Enterprise Admin rights", M['ea'], C.LRED)
stat("Administrators rights", M['admins'], C.LRED)
stat("SPN (kerberoastable)", M['spn'])
row("using LM hash", f"{M['lm']:,}", C.RED if M['lm'] else C.GREEN, pct=pctstr(M['lm'], B))
print()
row("Reusing a password", f"{M['reuse']:,}", C.ORANGE)
if d.cracked:
row("Cracked (weak)", f"{M['cracked']:,}", C.RED)
row("AFFECTED (reuse or weak)", f"{M['affected']:,}", C.LRED, pct=pctstr(M['affected'], B))
else:
print(f" {C.GRAY}(run with -c / --potfile for cracked + affected totals){C.NONE}")
if d.malformed:
row("Lines skipped (malformed)", f"{d.malformed:,}", C.GRAY)
meaning("scope of the audit: real users, hygiene, and how many share or reuse a password.")
def pctstr(n, base):
p = n / (base or 1) * 100
return "<1%" if 0 < p < 1 else f"{p:.0f}%"
def _ov_metrics(d):
now = time.time(); YEAR = 365*86400; D90 = 90*86400
acc = d.accounts; base = len(acc) or 1; exc = d.excluded
reuse = {nt for nt, a in d.by_nt.items() if nt != BLANK_NT and len(a) > 1}
aged = lambda fld, thr: sum(1 for a in acc
if isinstance(a.get(fld), (int, float)) and a[fld] > 0 and now-a[fld] > thr)
da, ea = d.priv.get('Domain Admin', set()), d.priv.get('Enterprise Admin', set())
return dict(
base=base, records=len(acc)+len(exc)+d.machine, machine=d.machine,
users=len(acc)+len(exc), analyzed=len(acc), excluded=len(exc),
unique=len({a['nt'] for a in acc if a['nt'] != BLANK_NT}),
nonexp=sum(1 for a in acc if a.get('pwdneverexpires')),
pw90=aged('pwdlastset', D90), pw1y=aged('pwdlastset', YEAR),
un90=aged('lastlogon', D90), un1y=aged('lastlogon', YEAR),
reuse=sum(1 for a in acc if a['nt'] in reuse),
cracked=sum(1 for a in acc if a['nt'] in d.cracked),
affected=sum(1 for a in acc if a['nt'] in reuse or a['nt'] in d.cracked),
priv=sum(1 for a in acc if a.get('admincount')),
da=sum(1 for a in acc if a.get('sid') in da), ea=sum(1 for a in acc if a.get('sid') in ea),
admins=sum(1 for a in acc if a.get('sid') in d.priv.get('Administrators', set())),
spn=sum(1 for a in acc if a.get('hasspn')), lm=sum(1 for a in acc if a['lm'] != BLANK_LM),
nopass=sum(1 for a in acc if a.get('passwordnotreqd')),
nonblank=len(d.non_blank), blanks=len(d.blanks),
ndomains=len({a['domain'] for a in acc if a['domain']}))
def _render_nodes(nodes, prefix=""):
n = len(nodes)
for i, nd in enumerate(nodes):
conn = "└─" if i == n-1 else "├─"
if nd.get('header'):
print(f" {C.GRAY}{prefix}{conn}{C.NONE} {C.CYAN}{nd['label']}{C.NONE}")
else:
pad = prefix + conn + " "
dots = "." * max(3, 46 - (len(pad) + len(nd['label']) + 1))
print(f" {C.GRAY}{pad}{C.NONE}{nd['label']} {C.GRAY}{dots}{C.NONE} "
f"{nd['color']}{nd['val']}{C.NONE}")
if nd.get('children'):
_render_nodes(nd['children'], prefix + (" " if i == n-1 else "│ "))
def _ov_tree(d, M):
B = M['base']
def leaf(label, n, color, showpct=False):
val = f"{n:,} ({pctstr(n, B)})" if showpct else (f"{n:,}" if isinstance(n, int) else n)
return {'label': label, 'val': val, 'color': color}
ua = [leaf("analyzed (enabled)", M['analyzed'], C.GREEN),
leaf("excluded (disabled)", M['excluded'], C.RED)] if d.filtered else []
scope = [leaf("Records parsed", M['records'], C.WHITE),
leaf("Machine removed", M['machine'], C.GRAY),
{**leaf("User accounts", M['users'], C.WHITE), 'children': ua},
leaf("with a password", M['nonblank'], C.ORANGE),
leaf("with a BLANK password", M['blanks'], C.RED if M['blanks'] else C.GREEN),
leaf("Domains in file", M['ndomains'], C.CYAN)]
if d.enriched:
scope.append(leaf("BloodHound matched", f"{d.matched:,} / {M['users']:,}", C.CYAN))
if d.malformed:
scope.append(leaf("Lines skipped (malformed)", d.malformed, C.GRAY))
cred = [leaf("Unique passwords", M['unique'], C.ORANGE)]
if d.enriched:
cred += [leaf("no password required", M['nopass'], C.RED, True),
leaf("non-expiring password", M['nonexp'], C.ORANGE, True),
leaf("password age > 90 days", M['pw90'], C.ORANGE, True),
leaf("password age > 1 year", M['pw1y'], C.ORANGE, True),
leaf("unused > 90 days", M['un90'], C.ORANGE, True),
leaf("unused > 1 year", M['un1y'], C.ORANGE, True)]
cred += [leaf("using LM hash", M['lm'], C.RED, True),
leaf("Reusing a password", M['reuse'], C.RED),
leaf("Cracked (weak)", M['cracked'], C.RED)]
risk = [leaf("Privileged (adminCount)", M['priv'], C.LRED)]
if d.has_groups:
risk += [leaf("Domain Admins", M['da'], C.LRED),
leaf("Enterprise Admins", M['ea'], C.LRED),
leaf("Administrators", M['admins'], C.LRED)]
risk.append(leaf("SPN (kerberoastable)", M['spn'], C.LRED))
print(f"{C.WHITE}Audit Summary{C.NONE}")
_render_nodes([{'label': 'Scope', 'header': True, 'children': scope},
{'label': 'Credentials', 'header': True, 'children': cred},
{'label': 'Risk / Attack Surface', 'header': True, 'children': risk}])
print(f" {C.LRED}{'Affected (reuse or weak)'}{C.NONE} "
f"{C.GRAY}{'.'*10}{C.NONE} {C.LRED}{M['affected']:,} ({pctstr(M['affected'], B)}){C.NONE}")
meaning("grouped rollup — Scope / Credentials / Risk (full detail).")
def _barchart(rows, W=34):
mx = max((v for _, v, _ in rows), default=1) or 1
for label, v, color in rows:
bar = "█" * max(1 if v else 0, round(v/mx*W))
print(f" {color}{label:<22}{C.NONE} {color}{v:>7,}{C.NONE} {color}{bar}{C.NONE}")
def _ov_bars(d, M):
print(f"{C.CYAN}Population{C.NONE}")
_barchart([("Records parsed", M['records'], C.CYAN), ("User accounts", M['users'], C.CYAN),
("Analyzed (enabled)", M['analyzed'], C.GREEN),
("Excluded (disabled)", M['excluded'], C.RED), ("Unique passwords", M['unique'], C.ORANGE)])
hygiene = [("using LM hash", M['lm'], C.RED)] # LM needs no enrichment
if d.enriched:
hygiene += [("Non-expiring", M['nonexp'], C.ORANGE), ("Pwd age > 90 days", M['pw90'], C.ORANGE),
("Pwd age > 1 year", M['pw1y'], C.ORANGE), ("Unused > 90 days", M['un90'], C.ORANGE),
("Unused > 1 year", M['un1y'], C.ORANGE)]
print(f"\n{C.CYAN}Password hygiene{C.NONE}")
_barchart(hygiene)
print(f"\n{C.CYAN}Risk / attack surface{C.NONE}")
risk = [("Reusing a password", M['reuse'], C.RED), ("Cracked (weak)", M['cracked'], C.RED),
("Affected (reuse/weak)", M['affected'], C.LRED), ("adminCount", M['priv'], C.LRED)]
if d.has_groups:
risk += [("Domain Admins", M['da'], C.LRED), ("Enterprise Admins", M['ea'], C.LRED)]
risk += [("SPN", M['spn'], C.LRED)]
_barchart(risk)
meaning("each group scaled to its own max, so small risk counts stay visible.")
def _ov_barspct(d, M):
B = M['base']
print(f"{C.WHITE}As % of analyzed ({M['analyzed']:,}){C.NONE}")
rows = [("Non-expiring", M['nonexp'], C.ORANGE), ("Pwd age > 90 days", M['pw90'], C.ORANGE),
("Pwd age > 1 year", M['pw1y'], C.ORANGE), ("Unused > 90 days", M['un90'], C.ORANGE),
("Unused > 1 year", M['un1y'], C.ORANGE), ("Reusing a password", M['reuse'], C.RED),
("Cracked (weak)", M['cracked'], C.RED), ("Affected (reuse/weak)", M['affected'], C.LRED),
("adminCount", M['priv'], C.LRED)]
if d.has_groups:
rows.append(("Domain Admins", M['da'], C.LRED))
W = 38
for label, v, color in rows:
p = v/B; fill = round(p*W)
bar = color + "█"*fill + C.NONE + C.GRAY + "·"*(W-fill) + C.NONE
print(f" {color}{label:<22}{C.NONE} {bar} {color}{p*100:>5.1f}%{C.NONE} {C.GRAY}({v:,}){C.NONE}")
meaning("every metric as a share of analyzed accounts.")
def _ov_domains(d, M=None):
doms = Counter(a['domain'] for a in (d.accounts + d.excluded) if a.get('domain'))
total = sum(doms.values()) or 1
print(f" {C.WHITE}{'Domain':<28}{'Accounts':>10} {'':<22}{'%':>6}{C.NONE}")
print(f" {C.GRAY}{'─'*72}{C.NONE}")
W = 22
for dom, n in doms.most_common(6):
p = n/total; fill = round(p*W)
bar = C.LCYAN + "█"*fill + C.NONE + C.GRAY + "-"*(W-fill) + C.NONE
print(f" {C.CYAN}{dom:<28}{C.NONE}{n:>10,} |{bar}| {p*100:>5.1f}%")
rest = len(doms) - 6
if rest > 0:
n = sum(v for _, v in doms.most_common()[6:])
print(f" {C.GRAY}+ {rest} more{'':<19}{n:>10,} |{'-'*W}| {n/total*100:>5.1f}%{C.NONE}")
print(f" {C.GRAY}{'─'*72}{C.NONE}")
print(f" {C.WHITE}TOTAL DOMAINS: {len(doms):<13}{total:>10,}{'':<24}100%{C.NONE}")
meaning("account distribution across domains (full population).")
class _Canvas:
def __init__(self, h, w):
self.h, self.w = h, w
self.ch = [[' ']*w for _ in range(h)]; self.co = [[None]*w for _ in range(h)]
def put(self, r, c, s, col=None):
for i, x in enumerate(s):
if 0 <= r < self.h and 0 <= c+i < self.w: self.ch[r][c+i] = x; self.co[r][c+i] = col
def putc(self, r, c, ch, col=None):
if 0 <= r < self.h and 0 <= c < self.w: self.ch[r][c] = ch; self.co[r][c] = col
def hseg(self, r, c1, c2, col=None, ch='─'):
for c in range(min(c1, c2), max(c1, c2)+1): self.putc(r, c, ch, col)
def vseg(self, c, r1, r2, col=None, ch='│'):
for r in range(min(r1, r2), max(r1, r2)+1): self.putc(r, c, ch, col)
def box(self, r, c, lines, col=None):
w = max(len(l) for l in lines) + 4
self.put(r, c, '┌' + '─'*(w-2) + '┐', col)
for i, l in enumerate(lines):
self.put(r+1+i, c, '│ ' + l.ljust(w-3) + '│', col)
self.put(r+len(lines)+1, c, '└' + '─'*(w-2) + '┘', col)
h = len(lines)+2
return dict(r=r, c=c, w=w, midr=r+h//2, rightc=c+w-1, botr=r+h-1)
def render(self):
out = []
for r in range(self.h):
line, cur = '', None
for c in range(self.w):
col = self.co[r][c]
if col != cur:
line += (C.NONE if cur else '') + (col or ''); cur = col
line += self.ch[r][c]
out.append((line + (C.NONE if cur else '')).rstrip())
while out and not out[-1].strip(): out.pop()
return '\n'.join(out)
def _ov_sankey(d, M):
if shutil.get_terminal_size(fallback=(100, 30)).columns < 96:
print(f"{C.GRAY}(terminal too narrow for --view sankey; showing tree){C.NONE}\n")
return _ov_tree(d, M)
G = C.GRAY; f = lambda n: f"{n:,}"
ndoms = len(Counter(a['domain'] for a in (d.accounts + d.excluded) if a.get('domain')))
cv = _Canvas(33, 100)
A = cv.box(2, 0, [f(M['records']), "Records", "parsed"], C.WHITE)
B = cv.box(2, 14, [f(M['machine']), "Machine", "removed"], G)
Cx = cv.box(2, 28, [f(M['users']), "User", "accounts"], C.WHITE)
cv.putc(A['midr'], (A['rightc']+B['c'])//2, '→', G)
cv.putc(B['midr'], (B['rightc']+Cx['c'])//2, '→', G)
An = cv.box(0, 50, [f"{f(M['analyzed'])} Analyzed ({pctstr(M['analyzed'],M['users'])})"], C.GREEN)
Ex = cv.box(5, 50, [f"{f(M['excluded'])} Excluded ({pctstr(M['excluded'],M['users'])})"], C.RED)
sc = 44
cv.hseg(Cx['midr'], Cx['rightc'], sc, G); cv.vseg(sc, An['midr'], Ex['midr'], G)
cv.putc(An['midr'], sc, '┌', G); cv.putc(Ex['midr'], sc, '└', G); cv.putc(Cx['midr'], sc, '├', G)
cv.hseg(An['midr'], sc+1, An['c']-1, G); cv.putc(An['midr'], An['c']-1, '►', C.GREEN)
cv.hseg(Ex['midr'], sc+1, Ex['c']-1, G); cv.putc(Ex['midr'], Ex['c']-1, '►', C.RED)
U = cv.box(9, 42, [f(M['unique']), "Unique", "passwords"], C.ORANGE)
dc = 34
cv.vseg(dc, Cx['botr']+1, U['midr'], G); cv.putc(U['midr'], dc, '└', G); cv.putc(Cx['botr'], dc, '┬', G)
cv.hseg(U['midr'], dc+1, U['c']-1, G); cv.putc(U['midr'], U['c']-1, '►', C.ORANGE)
NE = cv.box(7, 76, [f"{f(M['nonexp'])} ({pctstr(M['nonexp'],M['base'])})", "Non-expiring"], C.GREEN)
N9 = cv.box(11, 76, [f"{f(M['pw90'])} ({pctstr(M['pw90'],M['base'])})", "> 90 days"], C.ORANGE)
NY = cv.box(15, 76, [f"{f(M['pw1y'])} ({pctstr(M['pw1y'],M['base'])})", "> 1 year"], C.ORANGE)
ac = 70
cv.hseg(U['midr'], U['rightc'], ac, G); cv.vseg(ac, NE['midr'], NY['midr'], G)
cv.putc(NE['midr'], ac, '┌', G); cv.putc(NY['midr'], ac, '└', G)
cv.putc(N9['midr'], ac, '├', G); cv.putc(U['midr'], ac, '├', G)
for bx, col in ((NE, C.GREEN), (N9, C.ORANGE), (NY, C.ORANGE)):
cv.hseg(bx['midr'], ac+1, bx['c']-1, G); cv.putc(bx['midr'], bx['c']-1, '►', col)
RC = cv.box(18, 50, [f"{f(M['reuse'])} Reusing", f"{f(M['cracked'])} Cracked"], C.RED)
AF = cv.box(22, 50, [f"{f(M['affected'])} Affected", f"({M['affected']/M['base']*100:.2f}%)"], C.RED)
LM = cv.box(26, 50, [f"{f(M['lm'])} using LM hash"], C.RED)
xc = 40
cv.vseg(xc, U['botr']+1, LM['midr'], G, ch='┊')
for rr in (RC['r']+1, RC['r']+2, AF['midr'], LM['midr']):
cv.hseg(rr, xc+1, 49, C.RED, ch='╌'); cv.putc(rr, xc, '├', G); cv.putc(rr, 49, '►', C.RED)
DM = cv.box(30, 20, [f"{ndoms} Domains in file"], G)
cv.vseg(18, B['botr']+1, DM['midr'], G, ch='┊'); cv.putc(B['botr'], 18, '┬', G)
cv.putc(DM['midr'], 18, '└', G); cv.hseg(DM['midr'], 19, DM['c']-1, G); cv.putc(DM['midr'], DM['c']-1, '►', G)
print(cv.render())
meaning("flow from records parsed down to the affected accounts.")
_VIEWS = {'plain': _ov_plain, 'tree': _ov_tree, 'bars': _ov_bars,
'bars-pct': _ov_barspct, 'domains': _ov_domains, 'sankey': _ov_sankey}
_VIEW_ORDER = ['plain', 'tree', 'bars', 'bars-pct', 'domains', 'sankey']
def parse_views(spec):
if not spec:
return ['plain']
parts = [p.strip().lower() for p in spec.replace(',', ' ').split()]
if 'all' in parts:
return list(_VIEW_ORDER)
return [p for p in parts if p in _VIEWS] or ['plain']
def report_overview(d, views=('plain',)):
M = _ov_metrics(d)
for i, v in enumerate(views):
if i:
print()
_VIEWS.get(v, _ov_plain)(d, M)
def report_reuse(d, top):
cl = d.clusters
accts_sharing = sum(len(a) for _, a in cl)
section("PASSWORD REUSE", f"{len(cl)} shared passwords across {accts_sharing} accounts")
kv("Accounts sharing a password", f"{accts_sharing}", C.RED)
kv("Distinct shared passwords", f"{len(cl)}", C.ORANGE)
kv("Largest shared password", f"{len(cl[0][1]) if cl else 0} accounts", C.RED)
print()
total = len(d.non_blank) or 1
print(f" {C.WHITE}{'ACCOUNTS':>8} {'PASSWORD (or hash if uncracked)':<40}{'% OF USERS':>10}{C.NONE}")
print(f" {C.CYAN}{'─'*8} {'─'*40}{'─'*10}{C.NONE}")
for nt, accts in cl[:top]:
pw = d.cracked.get(nt)
if pw is not None:
vis = f"{pwdisp(pw)} (CRACKED)"
colored = f"{C.LRED}{pwdisp(pw)}{C.NONE} {C.GRAY}(CRACKED){C.NONE}"
else:
vis = hashdisp(nt)
colored = f"{C.GRAY}{hashdisp(nt)}{C.NONE}"
pad = ' ' * max(0, 40 - len(vis)) # pad by visible width, not ANSI bytes
pct = f"{len(accts)/total:.2%}"
print(f" {C.YELLOW}{len(accts):>8}{C.NONE} {colored}{pad}{C.ORANGE}{pct:>10}{C.NONE}")
meaning("each row = one password; ACCOUNTS is how many accounts share it.")
def report_privileged(d):
"""The security story: same human across IDs, admin/service reuse."""
section("SECURITY STORY", "privileged & tier-crossing reuse")
cross, multi_admin, svc_reuse = [], [], []
for nt, accts in d.clusters:
cats = {a['user']: classify(a['user']) for a in accts}
# same-person collapse inside the cluster
people = defaultdict(list)
for a in accts:
people[name_key(a['user'])].append(a['user'])
for key, members in people.items():
if len(members) > 1:
mcats = {classify(m) for m in members}
if 'admin' in mcats and mcats != {'admin'}:
cross.append((nt, members)) # admin + own standard acct
elif mcats == {'admin'}:
multi_admin.append((nt, members)) # duplicate admin identities
admins = [u for u, c in cats.items() if c == 'admin']
services = [u for u, c in cats.items() if c == 'service']
if len(admins) > 1 and not any(nt == x for x, _ in multi_admin):
multi_admin.append((nt, admins)) # different admins, one pw
if services:
svc_reuse.append((nt, accts, services))
def block(title, color, items, renderer):
if not items:
return
print(f"\n {color}▸ {title}{C.NONE}")
for it in items:
renderer(it)
block("Admin reusing their OWN password on a standard account", C.LRED, cross,
lambda it: print(" " + f"{C.GRAY}·{C.NONE} " +
" ↔ ".join(tagged(m) for m in sorted(it[1], key=len, reverse=True)) +
_crack_note(d, it[0])))
block("Same person holding multiple privileged accounts / different admins sharing one password",
C.ORANGE, multi_admin,
lambda it: print(" " + f"{C.GRAY}·{C.NONE} " +
" ↔ ".join(tagged(m) for m in sorted(set(it[1]))) +
_crack_note(d, it[0])))
block("Service accounts sharing a password", C.ORANGE, svc_reuse,
lambda it: print(" " + f"{C.GRAY}·{C.NONE} " +
f"{C.ORANGE}{', '.join(s.split(chr(92))[-1] for s in it[2])}{C.NONE}"
f" {C.GRAY}shares with {len(it[1])-len(it[2])} other acct(s){C.NONE}" +
_crack_note(d, it[0])))
if not (cross or multi_admin or svc_reuse):
print(f" {C.GREEN}none detected{C.NONE}")
meaning("this is the real risk: reuse that crosses the admin boundary or hits automation identities.")
def _crack_note(d, nt):
pw = d.cracked.get(nt)
return f" {C.LRED}[pw: {pwdisp(pw)}]{C.NONE}" if pw else f" {C.GRAY}[hash uncracked]{C.NONE}"
def report_weak_overlap(d):
section("WEAK + SHARED OVERLAP", "clusters whose shared password was also cracked")
hits = [(nt, accts) for nt, accts in d.clusters if nt in d.cracked]
if not hits:
print(f" {C.GRAY}no cracked passwords among the reuse clusters"
f" (run with -c/--cracked and john first){C.NONE}")
return
for nt, accts in hits:
print(f" {C.LRED}{pwdisp(d.cracked[nt])}{C.NONE} "
f"{C.GRAY}used by{C.NONE} {C.YELLOW}{len(accts)}{C.NONE} {C.GRAY}accounts{C.NONE}")
meaning("worst of both worlds -- a guessable password AND shared across many accounts.")
def report_cracked(d, top):
section("CRACKED PASSWORDS", "weak-password view")
if not d.cracked:
print(f" {C.GRAY}no cracks loaded -- ensure john has a potfile, or pass --potfile{C.NONE}")
return
# accounts cracked = accounts whose nt is in cracked map
cracked_accts = [a for a in d.non_blank if a['nt'] in d.cracked]
total = len(d.non_blank) or 1
uniq = {d.cracked[a['nt']] for a in cracked_accts}
kv("Accounts cracked", f"{len(cracked_accts)} ({len(cracked_accts)/total:.2%})", C.RED)
kv("Distinct cracked passwords", f"{len(uniq)}", C.ORANGE)
lm_pws = {d.cracked[a['nt']] for a in cracked_accts if a['nt'] in d.lm_cracked}
if d.lm_cracked:
n_lm = sum(1 for a in cracked_accts if a['nt'] in d.lm_cracked)
kv(" via NT (true case)", f"{len(cracked_accts)-n_lm}", C.ORANGE)
kv(" via LM (uppercase)", f"{n_lm}", C.RED)
print()
freq = Counter(d.cracked[a['nt']] for a in cracked_accts)
print(f" {C.WHITE}{'USED BY':>7} PASSWORD{C.NONE}")
print(f" {C.CYAN}{'─'*7} {'─'*30}{C.NONE}")
for pw, n in freq.most_common(top):
tag = f" {C.ORANGE}(LM, uppercase){C.NONE}" if pw in lm_pws else ""
print(f" {C.YELLOW}{n:>7}{C.NONE} {C.LRED}{pwdisp(pw)}{C.NONE}{tag}")
lm_note = " LM-recovered passwords are uppercase." if d.lm_cracked else ""
meaning(f"these fell to a wordlist -- seasonal/company/keyboard-walk patterns dominate.{lm_note}")
def report_cracked_users(d):
"""One line per cracked account -- a hand-off list for password resets."""
section("CRACKED ACCOUNTS", "per-user list (account first, copy/awk friendly)")
rows = cracked_rows(d)
if not rows:
print(f" {C.GRAY}no cracked accounts -- run with john/potfile available{C.NONE}")
return
width = min(max(len(a['user']) for a in rows) + 2, 48)
print(f" {C.WHITE}{'ACCOUNT':<{width}}{'PASSWORD':<26}NOTES{C.NONE}")
print(f" {C.CYAN}{'─'*(width-1)} {'─'*25} {'─'*14}{C.NONE}")
for a in rows:
cat = classify(a['user'])
pw = d.cracked[a['nt']]
shared = len(d.by_nt[a['nt']])
notes = []
if cat in ('admin', 'service', 'test'):
notes.append(f"{TAG[cat][1]}{TAG[cat][0]}{C.NONE}")
if shared > 1:
notes.append(f"{C.RED}shared×{shared}{C.NONE}")
if a['nt'] in d.lm_cracked:
notes.append(f"{C.ORANGE}LM (uppercase){C.NONE}")
if d.enriched:
if a.get('enabled') is False: notes.append(f"{C.RED}DISABLED{C.NONE}")
if a.get('admincount'): notes.append(f"{C.LRED}adminCount{C.NONE}")
if a.get('hasspn'): notes.append(f"{C.ORANGE}SPN{C.NONE}")
acct_color = TAG[cat][1] if cat in ('admin', 'service') else C.NONE
print(f" {acct_color}{a['user']:<{width}}{C.NONE}"
f"{C.LRED}{pwdisp(pw, quote=False):<26}{C.NONE}{' '.join(notes)}")
meaning(f"{len(rows)} accounts to force-reset; ADMIN/SERVICE first, then reused-password "
f"clusters (largest first), unique passwords last.")
def cracked_rows(d):
"""cracked accounts: admins/services first (by category), then within each
category the reused-password clusters (largest first, grouped), then uniques."""
rank = {'admin': 0, 'service': 1, 'test': 2, 'sync': 3, 'user': 4}
rows = [a for a in d.non_blank if a['nt'] in d.cracked]
rows.sort(key=lambda a: (rank[classify(a['user'])], # admins/services first
-len(d.by_nt[a['nt']]), # then bigger shared clusters
d.cracked[a['nt']], # keep identical passwords together
a['user'].lower()))
return rows
def write_cracked_csv(d):
"""Emit cracked accounts as CSV to stdout (no banner/color) for spreadsheet/tracker.
In screenshot mode the password column becomes a stable alias + length."""
w = csv.writer(sys.stdout)
if REDACT:
w.writerow(['account', 'samaccountname', 'domain', 'password_alias',
'password_length', 'category', 'shared_count'] + _enrich_hdr(d))
for a in cracked_rows(d):
pw = d.cracked[a['nt']]
w.writerow([a['user'], a['user'].split('\\')[-1], a['domain'],
_ALIAS.get(pw, 'pw-??'), len(pw), classify(a['user']),
len(d.by_nt[a['nt']])] + _enrich_cols(d, a))
else:
w.writerow(['account', 'samaccountname', 'domain', 'password',
'category', 'shared_count'] + _enrich_hdr(d))
for a in cracked_rows(d):
w.writerow([a['user'], a['user'].split('\\')[-1], a['domain'],
d.cracked[a['nt']], classify(a['user']),
len(d.by_nt[a['nt']])] + _enrich_cols(d, a))
def _by_priv(rows):
rank = {'admin': 0, 'service': 1, 'test': 2, 'sync': 3, 'user': 4}
return sorted(rows, key=lambda a: (rank[classify(a['user'])], a['user'].lower()))
def _account_table(rows):
width = min(max(len(a['user']) for a in rows) + 2, 48)
print(f" {C.WHITE}{'ACCOUNT':<{width}}{'RID':<8}TYPE{C.NONE}")
print(f" {C.CYAN}{'─'*(width-1)} {'─'*7} {'─'*8}{C.NONE}")
for a in rows:
cat = classify(a['user']); label, color = TAG[cat]
acol = color if cat in ('admin', 'service') else C.NONE
print(f" {acol}{a['user']:<{width}}{C.NONE}"
f"{C.GRAY}{a['rid']:<8}{C.NONE}{color}{label}{C.NONE}")
def report_lm_users(d):
section("LM-ENABLED ACCOUNTS", "disable LM (NoLMHash GPO) + force password reset")
rows = _by_priv(d.lm_present)
if not rows:
print(f" {C.GREEN}none -- no accounts store an LM hash{C.NONE}")
return
kv("Accounts storing an LM hash", f"{len(rows)}", C.RED)
print()
_account_table(rows)
meaning(f"{len(rows)} accounts keep a weak LM hash; enable 'Network security: Do not store "
f"LAN Manager hash value on next password change', then force a reset on each.")
def report_blank_users(d):
section("BLANK-PASSWORD ACCOUNTS", "NT hash = empty -- account has no password")
rows = _by_priv(d.blanks)
if not rows:
print(f" {C.GREEN}none -- no accounts have an empty password{C.NONE}")
return
kv("Accounts with NO password", f"{len(rows)}", C.RED)
print()
_account_table(rows)
meaning(f"{len(rows)} accounts authenticate with no password; disable them or set a password now.")
def write_lm_csv(d):
w = csv.writer(sys.stdout)
w.writerow(['account', 'samaccountname', 'domain', 'rid', 'category', 'lm_hash'] + _enrich_hdr(d))
for a in _by_priv(d.lm_present):
w.writerow([a['user'], a['user'].split('\\')[-1], a['domain'], a['rid'],
classify(a['user']), hashdisp(a['lm'])] + _enrich_cols(d, a))
def write_blank_csv(d):
w = csv.writer(sys.stdout)
w.writerow(['account', 'samaccountname', 'domain', 'rid', 'category'] + _enrich_hdr(d))
for a in _by_priv(d.blanks):
w.writerow([a['user'], a['user'].split('\\')[-1], a['domain'], a['rid'],
classify(a['user'])] + _enrich_cols(d, a))
def report_disabled_users(d):
section("DISABLED ACCOUNTS", "BloodHound-enriched -- review for removal, not reset")
if not d.enriched:
print(f" {C.GRAY}no enrichment -- pass --bloodhound <users.json>{C.NONE}")
return
rows = _by_priv(d.disabled)
if not rows:
print(f" {C.GREEN}none disabled among matched accounts{C.NONE}")
return
kv("Disabled accounts", f"{len(rows)}", C.RED)
print()
_account_table(rows)
meaning(f"{len(rows)} disabled accounts still carry crackable hashes; delete/verify, don't reset.")
def write_disabled_csv(d):
w = csv.writer(sys.stdout)
w.writerow(['account', 'samaccountname', 'domain', 'rid', 'category'])
for a in _by_priv(d.disabled):
w.writerow([a['user'], a['user'].split('\\')[-1], a['domain'], a['rid'], classify(a['user'])])
def report_hygiene(d):
section("HYGIENE & POSITIVES", "quick pass/fail signals")
# username == password (needs cracked map)