-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
executable file
·237 lines (213 loc) · 7.96 KB
/
main.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
#!/usr/bin/python3
import sys
import logging
import argparse
from shutil import which
from struct import unpack
from hashlib import sha256
from zlib import decompress
from getpass import getpass
from base64 import b64decode
import xml.etree.ElementTree as ET
from subprocess import run, DEVNULL
from Cryptodome.Cipher import AES, Salsa20
web = which('firefox') or (
logging.error('please specify a working browser'),
sys.exit(1))
clip = which('xclip') or (
logging.error('please specify the clipboard command'),
sys.exit(1))
clip = [clip, '-sel', 'c']
class clr:
PURPLE = '\033[95m'
OCEAN = '\033[96m'
ENDC = '\033[0m'
#BOLD = '\033[1m'
#UNDERLINE = '\033[4m'
#RED = '\033[91m'
#GREEN = '\033[92m'
#YELLOW = '\033[93m'
#BLUE = '\033[94m'
head_map = (None, 'comment', 'cipher', 'gzip', 'main_seed', 'roll_seed',
'rounds', 'IV', 'inner_key', 'head_chk', 'inner_cipher')
goodsig = b'\x03\xD9\xA2\x9A\x67\xFB\x4B\xB5'
cipher_AES = b'\x31\xC1\xF2\xE6\xBF\x71\x43\x50\xBE\x58\x05\x21\x6A\xFC\x5A\xFF'
inner_Salsa20 = b'\x02\x00\x00\x00'
sal20_nounce = b'\xE8\x30\x09\x4B\x97\x20\x5D\x2A'
attribs = ('Notes', 'Title', 'URL', 'UserName')
def composite_key(password: bytes, keyfile:str) -> bytes:
p = sha256(password).digest() if password else b''
k = b''
if keyfile:
with open(keyfile, 'rb') as f:
k = sha256(f.read()).digest()
return sha256(p + k).digest()
def final_key(rollkey: bytes, rounds: int, rollseed: bytes, mainseed: bytes) -> bytes:
logging.info(f'rounds: {rounds}')
aes = AES.new(rollseed, AES.MODE_ECB)
for i in range(rounds):
rollkey = aes.encrypt(rollkey)
rollkey = sha256(rollkey).digest()
return sha256(mainseed + rollkey).digest()
def head2dict(f) -> dict:
'''Parse kdbx header part '''
sig, ver = unpack('<8sI', f.read(12))
if sig != goodsig:
logging.error('kdbx not supported')
sys.exit(1)
logging.info(f'ver {hex(ver)}')
head = {}
while True:
index, size = unpack('<BH', f.read(3))
data = f.read(size)
if index == 0:
break
head[index] = data
if head[2] != cipher_AES:
logging.error('cipher not AES')
sys.exit(1)
if head[10] != inner_Salsa20:
logging.error('stream cipher not Salsa20')
sys.exit(1)
logging.info('\n'.join(f'{head_map[i]} {head[i]}' for i in head))
return head
def decbody(hd:dict, f, secpsw, secfile) -> bytes:
'''Parse kdbx body '''
aes = AES.new(
final_key(
composite_key(secpsw, secfile),
unpack('<Q', hd[6])[0],
hd[5],
hd[4]),
AES.MODE_CBC,
hd[7])
if aes.decrypt(f.read(len(hd[9]))) != hd[9]:
logging.error('decryption error')
sys.exit(1)
return aes.decrypt(f.read())
def body2xml(body: bytes, is_compressed, to_save: str) -> ET.Element:
'''Parse AES-decrypted body to xml,
where inner psw still Salsa20-encrypted.
'''
offset = 0 # in Bytes
ret = b''
blk_sz = 40
# read data block by block
while True:
_, chk, size = unpack('<4s32sI', body[offset:offset+blk_sz])
# last block flags
if chk == b'\x00'*32 and size == 0:
break
offset += blk_sz
data = body[offset:offset+size]
if sha256(data).digest() != chk:
logging.error('body corrupted')
sys.exit(1)
offset += size
ret += data
if is_compressed:
ret = decompress(ret, 31)
if to_save:
try:
with open(to_save, 'wb') as fbout:
fbout.write(ret)
logging.warning('[unsafe] xml saved to %s', to_save)
except Exception as e:
logging.error('err when saving xml: %s', e)
return ET.fromstring(ret.decode())[1]
def xml2lst(xml: ET.Element, key) -> list:
'''Restruct the root xml of kdbx to key-val pairs,
and prepare plaintext password for clipboard.
Return a list, each of whose element is a tuple:
({key: val,
key: val,
...},
plainpsw)
'''
ss = Salsa20.new(sha256(key).digest(), sal20_nounce)
ret = []
for entry in (xml.findall('./Group/Entry') + xml.findall('./Group/Group/Entry')):
kv = {} # as ret[*][0]
pln = None # plaintext-psw as ret[*][1]
# get the "most recent" k-v pairs of this entry,
# i.e., note, psw, title, URL, username, etc.
for pair in entry.findall('./String'):
if pair[0].text == 'Password':
# psw found: only the 1st is currently in use;
# other old ones need to involve in salsa20.
for psw in entry.findall(".//Value[@Protected='True']"):
# psw may be empty
t = psw.text and ss.decrypt(b64decode(psw.text))
pln = pln or psw.text==pair[1].text and t
elif not pair[1].attrib.get('Protected', False):
kv[pair[0].text] = pair[1].text
ret.append((kv, pln,))
return ret
def must_input(prompt: str) -> str:
i = None
while not i:
i = input(f'{prompt}{"" if i is None else " <must input>"}: ')
return i
def yn(q:str, y=True) -> bool:
'''Ask a yes-no 'q?' with a default answer, so that
a lazy user can just hit ENTER to indicate the default.
Anyway, return True if user input is 'y', False if 'n'.
'''
q = clr.OCEAN + q + '? ' + clr.ENDC
return (input(q+'[y]/n ')!='n') if y else (input(q+'y/[n] ')=='y')
def clrkv(dct:dict, dlm: str):
print(dlm.join((clr.PURPLE+k+clr.ENDC+': '+v) for k,v in dct.items() if v))
def sl(l: list):
cho = ''
while cho != 'e':
cho = must_input('s(earch)? l(ist)? e(xit)?')[0]
if cho == 's':
kw = must_input('keyword').lower()
nomatch = True
for d, p in l:
if any((d[a] and kw in d[a].lower()) for a in attribs):
clrkv(d, '\n')
if yn('thats it', False):
nomatch = False
if d[attribs[2]] and yn('open URL'):
run([web, d[attribs[2]]])
if p and yn('psw to clipb', False):
run(clip, input=p)
if d[attribs[3]] and yn('username to clipb', False):
run(clip, input=d[attribs[3]].encode())
if yn('clear clipb'):
run(clip, stdin=DEVNULL)
break
if nomatch:
logging.warning('no match')
elif cho == 'l':
exhausted = True
for ct, entry in enumerate(l):
clrkv(entry[0], '; ')
if 9 == ct%10:
if not yn('more'):
exhausted = False
break
if exhausted:
logging.warning('all entries exhausted')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('db', help='the kdbx database')
parser.add_argument('-k', '--keyfile', help='the key file')
parser.add_argument('-s', '--save', help='save xml (unsafe)')
parser.add_argument('-x', '--xml', help='recover from an (unsafe) xml file')
parser.add_argument('-o', '--header', action='store_true', help='only show header and quit')
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
logging.basicConfig(level=(logging.INFO if args.header or args.verbose else logging.WARNING),
format='[%(levelname)s] %(message)s')
with open(args.db, 'rb') as f:
hd = head2dict(f)
if not args.header:
# TODO safesave(args.save)
sl(xml2lst(
ET.parse(args.xml).getroot()[1] if args.xml else body2xml(
decbody(hd, f, getpass().encode(), args.keyfile),
unpack('<I', hd[3]),
args.save),
hd[8]))