-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtokeepass.py
112 lines (100 loc) · 2.95 KB
/
tokeepass.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
import subprocess
from StringIO import StringIO
import cgi
class EndOfFile(Exception):
pass
class Entry(object):
_started = False
_count = 0
def __init__(self, name, account, password):
self.name = name
self.account = account
self.password = password
@staticmethod
def roll(fi):
"""
roll to next record
"""
while True:
Entry._count += 1
line = fi.readline().strip()
if line == '' and fi.tell() == fi.len:
raise EndOfFile()
if line.startswith('keychain: "'):
break
@staticmethod
def parse(fi):
if not Entry._started:
Entry._started = True
Entry.roll(fi)
Entry._count += 1
rtype = fi.readline().strip()
if rtype not in ('class: "inet"', 'class: "genp"'):
Entry.roll(fi)
return Entry.parse(fi) # try next
lines = []
while True:
Entry._count += 1
line = fi.readline().strip()
if line.startswith('keychain: "'):
break
lines.append(line)
return lines
@staticmethod
def create(fi):
lines = Entry.parse(fi)
name = account = password = ''
nextpassword = False
for line in lines:
if line.startswith('"srvr"<blob>="') or line.startswith('"svce"<blob>="'):
name = line.replace('"srvr"<blob>="', '').replace(
'"svce"<blob>="', '').strip('"')
elif line.startswith('"acct"<blob>="'):
account = line.replace('"acct"<blob>="', '').strip('"')
elif line.startswith('data:'):
nextpassword = True
elif nextpassword:
password = line[1:-1]
return Entry(name, account, password)
if __name__ == '__main__':
# security dump-keychain -d login.keychain
call = subprocess.Popen([
'security',
'dump-keychain',
'-d',
'login.keychain'
],
stderr = subprocess.PIPE,
stdout = subprocess.PIPE,
)
stdoutdata, stderrdata = call.communicate()
entries = []
data = StringIO(stdoutdata)
while True:
try:
entries.append(Entry.create(data))
except EndOfFile:
break
fi = open('output.xml', 'w')
fi.write("""<!DOCTYPE KEEPASSX_DATABASE>
<database>
<group>
<title>Imported</title>
<icon>1</icon>
""")
for entry in entries:
fi.write("""<entry>
<title>%s</title>
<username>%s</username>
<password>%s</password>
<url></url>
<comment></comment>
<icon>1</icon>
<creation>2012-12-02T01:30:20</creation>
<lastaccess>2012-12-02T01:30:39</lastaccess>
<lastmod>2012-12-02T01:30:39</lastmod>
<expire>Never</expire>
</entry>
""" % (cgi.escape(entry.name), cgi.escape(entry.account), cgi.escape(entry.password)))
fi.write("""</group></database>""")
fi.close()