-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathparser.py
More file actions
307 lines (242 loc) · 9.16 KB
/
parser.py
File metadata and controls
307 lines (242 loc) · 9.16 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
# coding: utf-8
from base64 import b64decode
import binascii
import codecs
from io import BytesIO
import struct
import re
import json
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Util import number
from Crypto.PublicKey import RSA
from .account import Account
from .chunk import Chunk
from .authenticator import Authenticator
# Secure note types that contain account-like information
ALLOWED_SECURE_NOTE_TYPES = [
b"Server",
b"Email Account",
b"Database",
b"Instant Messenger",
]
def extract_chunks(blob):
"""Splits the blob into chucks grouped by kind."""
chunks = []
stream = BytesIO(blob.bytes)
current_pos = stream.tell()
stream.seek(0, 2)
length = stream.tell()
stream.seek(current_pos, 0)
while stream.tell() < length:
chunks.append(read_chunk(stream))
return chunks
def parse_Authenticator(chunk, encryption_key):
json_result = decode_aes256_base64_auto(chunk.bytes, encryption_key)
print(json_result)
decoded_json_result = json.loads(json_result)
accounts = []
for account in decoded_json_result['accounts']:
accounts.append(Authenticator(
accountID=account['accountID'],
digits=account['digits'],
issuerName=account['issuerName'],
lmiUserId=account['lmiUserId'],
originalIssuerName=account['originalIssuerName'],
originalUserName=account['originalUserName'],
pushNotification=account['pushNotification'],
secret=account['secret'],
timeStep=account['timeStep'],
userName=account['userName'],
))
return accounts
def parse_ACCT(chunk, encryption_key):
"""
Parses an account chunk, decrypts and creates an Account object.
May return nil when the chunk does not represent an account.
All secure notes are ACCTs but not all of them strore account
information.
"""
# TODO: Make a test case that covers secure note account
io = BytesIO(chunk.payload)
id = read_item(io)
name = decode_aes256_plain_auto(read_item(io), encryption_key)
group = decode_aes256_plain_auto(read_item(io), encryption_key)
url = decode_hex(read_item(io))
notes = decode_aes256_plain_auto(read_item(io), encryption_key)
skip_item(io, 2)
username = decode_aes256_plain_auto(read_item(io), encryption_key)
password = decode_aes256_plain_auto(read_item(io), encryption_key)
skip_item(io, 2)
secure_note = read_item(io)
# Parse secure note
if secure_note == b'1':
parsed = parse_secure_note_server(notes)
if parsed.get('type') in ALLOWED_SECURE_NOTE_TYPES:
url = parsed.get('url', url)
username = parsed.get('username', username)
password = parsed.get('password', password)
return Account(id, name, username, password, url, group, notes)
def parse_PRIK(chunk, encryption_key):
"""Parse PRIK chunk which contains private RSA key"""
decrypted = decode_aes256('cbc',
encryption_key[:16],
decode_hex(chunk.payload),
encryption_key)
hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decrypted).group('hex_key')
rsa_key = RSA.importKey(decode_hex(hex_key))
rsa_key.dmp1 = rsa_key.d % (rsa_key.p - 1)
rsa_key.dmq1 = rsa_key.d % (rsa_key.q - 1)
rsa_key.iqmp = number.inverse(rsa_key.q, rsa_key.p)
return rsa_key
def parse_SHAR(chunk, encryption_key, rsa_key):
# TODO: Fake some data and make a test
io = BytesIO(chunk.payload)
id = read_item(io)
encrypted_key = decode_hex(read_item(io))
encrypted_name = read_item(io)
skip_item(io, 2)
key = read_item(io)
# Shared folder encryption key might come already in pre-decrypted form,
# where it's only AES encrypted with the regular encryption key.
# When the key is blank, then there's a RSA encrypted key, which has to
# be decrypted first before use.
if not key:
key = decode_hex(PKCS1_OAEP.new(rsa_key).decrypt(encrypted_key))
else:
key = decode_hex(decode_aes256_plain_auto(key, encryption_key))
name = decode_aes256_base64_auto(encrypted_name, key)
# TODO: Return an object, not a dict
return {'id': id, 'name': name, 'encryption_key': key}
def parse_secure_note_server(notes):
info = {}
for i in notes.split(b'\n'):
if not i: # blank line
continue
if b':' not in i: # there is no `:` if generic note
continue
# Split only once so that strings like "Hostname:host.example.com:80"
# get interpreted correctly
key, value = i.split(b':', 1)
if key == b'NoteType':
info['type'] = value
elif key == b'Hostname':
info['url'] = value
elif key == b'Username':
info['username'] = value
elif key == b'Password':
info['password'] = value
return info
def read_chunk(stream):
"""Reads one chunk from a stream and creates a Chunk object with the data read."""
# LastPass blob chunk is made up of 4-byte ID,
# big endian 4-byte size and payload of that size.
#
# Example:
# 0000: "IDID"
# 0004: 4
# 0008: 0xDE 0xAD 0xBE 0xEF
# 000C: --- Next chunk ---
return Chunk(read_id(stream), read_payload(stream, read_size(stream)))
def read_item(stream):
"""Reads an item from a stream and returns it as a string of bytes."""
# An item in an itemized chunk is made up of the
# big endian size and the payload of that size.
#
# Example:
# 0000: 4
# 0004: 0xDE 0xAD 0xBE 0xEF
# 0008: --- Next item ---
return read_payload(stream, read_size(stream))
def skip_item(stream, times=1):
"""Skips an item in a stream."""
for i in range(times):
read_item(stream)
def read_id(stream):
"""Reads a chunk ID from a stream."""
return stream.read(4)
def read_size(stream):
"""Reads a chunk or an item ID."""
return read_uint32(stream)
def read_payload(stream, size):
"""Reads a payload of a given size from a stream."""
return stream.read(size)
def read_uint32(stream):
"""Reads an unsigned 32 bit integer from a stream."""
return struct.unpack('>I', stream.read(4))[0]
def decode_hex(data):
"""Decodes a hex encoded string into raw bytes."""
try:
return codecs.decode(data, 'hex_codec')
except binascii.Error:
raise TypeError()
def decode_base64(data):
"""Decodes a base64 encoded string into raw bytes."""
return b64decode(data)
def decode_aes256_plain_auto(data, encryption_key):
"""Guesses AES cipher (EBC or CBD) from the length of the plain data."""
assert isinstance(data, bytes)
length = len(data)
if length == 0:
return b''
elif data[0] == b'!'[0] and length % 16 == 1 and length > 32:
return decode_aes256_cbc_plain(data, encryption_key)
else:
return decode_aes256_ecb_plain(data, encryption_key)
def decode_aes256_base64_auto(data, encryption_key):
"""Guesses AES cipher (EBC or CBD) from the length of the base64 encoded data."""
assert isinstance(data, bytes)
length = len(data)
if length == 0:
return b''
elif data[0] == b'!'[0]:
return decode_aes256_cbc_base64(data, encryption_key)
else:
return decode_aes256_ecb_base64(data, encryption_key)
def decode_aes256_ecb_plain(data, encryption_key):
"""Decrypts AES-256 ECB bytes."""
if not data:
return b''
else:
return decode_aes256('ecb', '', data, encryption_key)
def decode_aes256_ecb_base64(data, encryption_key):
"""Decrypts base64 encoded AES-256 ECB bytes."""
return decode_aes256_ecb_plain(decode_base64(data), encryption_key)
def decode_aes256_cbc_plain(data, encryption_key):
"""Decrypts AES-256 CBC bytes."""
if not data:
return b''
else:
# LastPass AES-256/CBC encryted string starts with an "!".
# Next 16 bytes are the IV for the cipher.
# And the rest is the encrypted payload.
return decode_aes256('cbc', data[1:17], data[17:], encryption_key)
def decode_aes256_cbc_base64(data, encryption_key):
"""Decrypts base64 encoded AES-256 CBC bytes."""
if not data:
return b''
else:
# LastPass AES-256/CBC/base64 encryted string starts with an "!".
# Next 24 bytes are the base64 encoded IV for the cipher.
# Then comes the "|".
# And the rest is the base64 encoded encrypted payload.
return decode_aes256(
'cbc',
decode_base64(data[1:25]),
decode_base64(data[26:]),
encryption_key)
def decode_aes256(cipher, iv, data, encryption_key):
"""
Decrypt AES-256 bytes.
Allowed ciphers are: :ecb, :cbc.
If for :ecb iv is not used and should be set to "".
"""
if cipher == 'cbc':
aes = AES.new(encryption_key, AES.MODE_CBC, iv)
elif cipher == 'ecb':
aes = AES.new(encryption_key, AES.MODE_ECB)
else:
raise ValueError('Unknown AES mode')
d = aes.decrypt(data)
# http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/
unpad = lambda s: s[0:-ord(d[-1:])]
return unpad(d)