forked from Synacktiv-contrib/stuffz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
android-ks-decryptor.py
executable file
·337 lines (274 loc) · 9.17 KB
/
android-ks-decryptor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env python3
#
# Script to decode and decrypt Android Keystores (only software).
#
# Julien Legras - Synacktiv
# Thomas Etrillard - Synacktiv
#
#coding: utf-8
# Docs and usesful links
# https://nelenkov.blogspot.com/2015/06/keystore-redesign-in-android-m.html
# http://www.cs.ru.nl/~joeri/papers/spsm14.pdf
# http://androidxref.com/6.0.1_r10/xref/system/security/keystore/keystore.cpp#587
# https://github.com/googlesamples/android-BasicAndroidKeyStore/
# https://developer.android.com/training/articles/keystore
from passlib.crypto.digest import pbkdf2_hmac
from hashlib import md5
from Crypto.Cipher import AES
import sys
import struct
import base64
import os
from io import BytesIO
import argparse
import textwrap
KEY_BLOB_TYPE = { 1 : "generic", 2: "master_key", 3: "key_pair", 4: "keymaster_10"}
AES_BLOCK_SIZE = int(128 / 8)
SALT_SIZE = 16
MD5_DIGEST_LENGTH = 16
PBKDF2_ALGO = "sha1"
KEK_LENGTH = int(128 / 8)
KEK_ROUNDS = 8192
INT_SIZE = 4
KEYSTORE_FLAG_ENCRYPTED = 1 << 0
KEYSTORE_FLAG_SUPER_ENCRYPTED = 4 << 0
KEYSTORE_FLAG_FALLBACK = 1 << 1
HEADER_SIZE = 4
# PKEY TYPES
EVP_PKEY_RSA = 6
EVP_PKEY_DSA = 116
EVP_PKEY_EC = 408
# MAGICS
SOFT_KM_MAGIC = 0x504b2338
SOFT_KM_MAGIC_LE = 0x38234b50
# TAG TYPES
KM_INVALID = 0 << 28
KM_ENUM = 1 << 28
KM_ENUM_REP = 2 << 28
KM_INT = 3 << 28
KM_INT_REP = 4 << 28
KM_LONG = 5 << 28
KM_DATE = 6 << 28
KM_BOOL = 7 << 28
KM_BIGNUM = 8 << 28
KM_BYTES = 9 << 28
KM_LONG_REP = 10 << 28
TAG_PURPOSE = KM_ENUM_REP | 1
TAG_ALGORITHM = KM_ENUM | 2
TAG_KEY_SIZE = KM_INT | 3
TAG_BLOCK_MODE = KM_ENUM_REP | 4
TAG_DIGEST = KM_ENUM_REP | 5
TAG_PADDING = KM_ENUM_REP | 6
TAG_ROOT_OF_TRUST = KM_BYTES | 704
ALGORITHM_RSA = 1
ALGORITHM_EC = 3
ALGORITHM_AES = 32
ALGORITHM_HMAC = 128
ALGORITHM_NAME = {
1: 'RSA',
3: 'EC',
32: 'AES',
33: '3DES',
128: 'HMAC'
}
class AuthorizationSet:
def __init__(self):
self.tags = []
def get_algorithm_name(self):
for tag, ti in self.tags:
if tag == TAG_ALGORITHM:
return ALGORITHM_NAME[ti]
def parse(blob, offset):
auth_set = AuthorizationSet()
b = BytesIO(blob[offset:])
indirect_data_size, = struct.unpack("<i", b.read(INT_SIZE))
if indirect_data_size > 0:
indirect_data = b.read(indirect_data_size)
elts_cnt, elts_size = struct.unpack("<ii", b.read(2*INT_SIZE))
for i in range(elts_cnt):
tag, = struct.unpack("<i", b.read(INT_SIZE))
if tag == -1:
continue
tag_type = tag & (0XF << 28)
if tag_type == KM_INVALID:
break
elif tag_type in [KM_ENUM, KM_ENUM_REP, KM_INT, KM_INT_REP]:
ti, = struct.unpack("<i", b.read(INT_SIZE))
auth_set.tags.append((tag, ti))
elif tag_type in [KM_LONG, KM_LONG_REP, KM_DATE]:
ti, = struct.unpack("<l", b.read(INT_SIZE))
auth_set.tags.append((tag, ti))
elif tag_type == KM_BOOL:
ti = b.read(1)
auth_set.tags.append((tag, ti))
elif tag_type in [KM_BIGNUM, KM_BYTES]:
l, o = struct.unpack("<ii", b.read(2*INT_SIZE))
l.read(o) # skip
ti = b.read(l)
auth_set.tags.append((tag, ti))
else:
raise ValueError
return auth_set
class KeystorePrinters:
def show_key_pair(ks, output_filename=None, dump=False):
if dump and not output_filename:
dump = False
b = BytesIO(ks.value)
magic = b.read(INT_SIZE)
typ, = struct.unpack(">i", b.read(INT_SIZE))
if typ not in [EVP_PKEY_EC, EVP_PKEY_RSA, EVP_PKEY_DSA]:
# maybe an old format, RSA by default
typ = EVP_PKEY_RSA
pubkey_len = typ
else:
pubkey_len, = struct.unpack(">i", b.read(INT_SIZE))
if pubkey_len > 0:
pubkey_bytes = b.read(pubkey_len)
privkey_len, = struct.unpack(">i", b.read(INT_SIZE))
privkey_bytes = b.read(privkey_len)
alg_name = None
if typ == EVP_PKEY_RSA:
alg_name = "RSA"
elif typ == EVP_PKEY_DSA:
alg_name = "DSA"
elif typ == EVP_PKEY_EC:
alg_name = "EC"
else:
raise ValueError
output = sys.stdout
if dump: output = open(output_filename, 'w')
output.write("-----BEGIN %s PRIVATE KEY-----\n" % alg_name)
output.write(textwrap.fill(base64.b64encode(privkey_bytes).decode('utf-8'), 64))
output.write("\n-----END %s PRIVATE KEY-----\n" % alg_name)
if dump: output.close()
def show_keymaster_10(ks, output_filename=None, dump=False):
b = BytesIO(ks.value)
version = b.read(1)
length, = struct.unpack("<i", b.read(INT_SIZE))
privkey_bytes = b.read(length)
keymat_length, = struct.unpack("<i", b.read(INT_SIZE))
keymat = b.read(keymat_length)
tag_length, = struct.unpack("<i", b.read(INT_SIZE))
tag = b.read(tag_length)
cipher = keymat + tag
b.read(INT_SIZE)
authorizations = b.read()
auth_set = AuthorizationSet.parse(authorizations, 0)
alg_name = auth_set.get_algorithm_name()
output = sys.stdout
if dump: output = open(output_filename, 'w')
output.write("-----BEGIN %s PRIVATE KEY-----\n" % alg_name)
output.write(textwrap.fill(base64.b64encode(privkey_bytes).decode('utf-8'), 64))
output.write("\n-----END %s PRIVATE KEY-----\n" % alg_name)
if dump: output.close()
def show_master_key(ks):
print("master key: %s" % (ks.value.hex()))
def show_generic(ks, output_filename=None, dump=False):
output = sys.stdout
if dump: output = open(output_filename, 'w')
if ks.value[:2] == b'\x30\x82':
output.write("-----BEGIN CERTIFICATE-----\n")
output.write(textwrap.fill(base64.b64encode(ks.value).decode('utf-8'), 64))
output.write("\n-----END CERTIFICATE-----\n")
else:
output.write(ks.value.decode('utf-8'))
if dump: output.close()
class KeystoreBlob:
PRINTERS = [
None,
KeystorePrinters.show_generic,
KeystorePrinters.show_master_key,
KeystorePrinters.show_key_pair,
KeystorePrinters.show_keymaster_10
]
def __init__(self):
self.value = None
self.description = None
self.version = None
self.type = None
self.flags = None
self.info = None
self.blob = None
self.blob_length = None
def parse_master_key(filename, password):
ksb = KeystoreBlob()
with open(filename, "rb") as ksb.blob:
ksb.parse_header()
iv = ksb.blob.read(AES_BLOCK_SIZE)
b = ksb.blob.read()
encrypted, salt = b[:-ksb.info], b[-SALT_SIZE:]
kek = ksb.generate_kek(password, salt)
decrypted = BytesIO(ksb.decrypt(iv, encrypted, kek))
digest = decrypted.read(MD5_DIGEST_LENGTH).hex()
digest_calculated = md5(decrypted.read()).hexdigest()
assert digest == digest_calculated
decrypted.seek(MD5_DIGEST_LENGTH)
length, = struct.unpack(">i", decrypted.read(INT_SIZE))
ksb.value = decrypted.read(length)
ksb.description = decrypted.read(ksb.info)
return ksb
def parse(filename, master_key=None):
ksb = KeystoreBlob()
with open(filename, "rb") as ksb.blob:
ksb.parse_header()
iv = ksb.blob.read(AES_BLOCK_SIZE)
encrypted = ksb.blob.read()
if (ksb.is_encrypted()):
if master_key is None:
print("The masterkey is required to decrypt this keystore blob")
sys.exit(1)
decrypted = BytesIO(ksb.decrypt(iv, encrypted, master_key))
digest = decrypted.read(MD5_DIGEST_LENGTH).hex()
digest_calculated = md5(decrypted.read()).hexdigest()
assert digest == digest_calculated
else:
decrypted = BytesIO(encrypted)
decrypted.seek(MD5_DIGEST_LENGTH)
length, = struct.unpack(">i", decrypted.read(INT_SIZE))
ksb.value = decrypted.read(length)
ksb.description = decrypted.read(ksb.info)
return ksb
def parse_header(self):
self.blob.seek(0, 2)
self.blob_length = self.blob.tell()
self.blob.seek(0)
self.version, self.type, self.flags, self.info = self.blob.read(HEADER_SIZE)
def generate_kek(self, password, salt):
return pbkdf2_hmac(PBKDF2_ALGO, password, salt,
KEK_ROUNDS, keylen=KEK_LENGTH)
def decrypt(self, iv, encrypted, kek):
return AES.new(kek, mode=AES.MODE_CBC, IV=iv).decrypt(encrypted)
def is_encrypted(self):
return (self.flags & KEYSTORE_FLAG_ENCRYPTED) == KEYSTORE_FLAG_ENCRYPTED
def is_super_encrypted(self):
return (self.flags & KEYSTORE_FLAG_SUPER_ENCRYPTED) == KEYSTORE_FLAG_SUPER_ENCRYPTED
def main():
parser = argparse.ArgumentParser(description='Parse Android keystores')
parser.add_argument('keyfile', help='user_X/uid_USRPKEY_keyname or just user_X/ to parse the whole directory')
parser.add_argument('--master-key', help='user_X/.masterkey')
parser.add_argument('--password', help='The password protecting the lockscreen')
parser.add_argument('--dump-pem', action='store_true', help='Dump the decoded keys and certificates in <keyfile>.pem')
args = parser.parse_args()
if os.path.isdir(args.keyfile) and os.path.isfile(os.path.join(args.keyfile, '.masterkey')):
args.master_key = os.path.join(args.keyfile, '.masterkey')
mk_value = None
if args.master_key:
mk = KeystoreBlob.parse_master_key(args.master_key, args.password)
mk_value = mk.value
if os.path.isdir(args.keyfile):
for kf in os.listdir(args.keyfile):
if kf == '.masterkey': continue
print("[+] Parsing %s" % kf)
b = KeystoreBlob.parse(os.path.join(args.keyfile, kf), mk_value)
if b.is_super_encrypted():
print("This format is not supported.")
continue
KeystoreBlob.PRINTERS[b.type](b, os.path.join(args.keyfile, kf) + ".pem", args.dump_pem)
else:
b = KeystoreBlob.parse(args.keyfile, mk_value)
if b.is_super_encrypted():
print("This format is not supported.")
return
KeystoreBlob.PRINTERS[b.type](b, args.keyfile + ".pem", args.dump_pem)
if __name__ == '__main__':
main()