forked from pradeep1288/ffpasscracker
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfirefox_passwd.py
executable file
·349 lines (271 loc) · 11.3 KB
/
firefox_passwd.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
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python
"""
Recovers your Firefox or Thunderbird passwords
Author : Tobias Mueller
"""
import sys
import os
try:
# try to use the python-nss lib from mozilla
# import nss
#except ImportError:
# fall back to dlopen of libnss3.so
from ctypes import (
CDLL, Structure,
c_void_p, c_uint, c_ubyte, c_char_p,
byref, cast, string_at,
)
#### libnss definitions
class SECItem(Structure):
_fields_ = [('type',c_uint),('data',c_void_p),('len',c_uint)]
class secuPWData(Structure):
_fields_ = [('source',c_ubyte),('data',c_char_p)]
(PW_NONE, PW_FROMFILE, PW_PLAINTEXT, PW_EXTERNAL) = (0, 1, 2, 3)
# SECStatus
(SECWouldBlock, SECFailure, SECSuccess) = (-2, -1, 0)
#### end of libnss definitions
#except ImportError as e:
# print 'Failed to find either nss or ctypes library.'
# raise
except ImportError: pass
try:
from sqlite3 import dbapi2 as sqlite
except ImportError:
from pysqlite2 import dbapi2 as sqlite
import base64
from getpass import getpass
import logging
from optparse import OptionParser
from collections import namedtuple
from ConfigParser import RawConfigParser, NoOptionError
from subprocess import Popen, CalledProcessError, PIPE
LOGLEVEL_DEFAULT = 'warn'
log = logging.getLogger()
#PWDECRYPT = 'pwdecrypt'
PWDECRYPT = '/usr/bin/pwdecrypt' # from libnss3-tools
SITEFIELDS = ['id', 'hostname', 'httpRealm', 'formSubmitURL', 'usernameField', 'passwordField', 'encryptedUsername', 'encryptedPassword', 'guid', 'encType', 'plain_username', 'plain_password' ]
Site = namedtuple('FirefoxSite', SITEFIELDS)
'''The format of the SQLite database is (2011):
(id INTEGER PRIMARY KEY,
hostname TEXT NOT NULL,
httpRealm TEXT,
formSubmitURL TEXT,
usernameField TEXT NOT NULL,
passwordField TEXT NOT NULL,
encryptedUsername TEXT NOT NULL,
encryptedPassword TEXT NOT NULL,
guid TEXT,
encType INTEGER);
'''
def get_default_firefox_profile_directory(profiledir='~/.mozilla/firefox'):
"""Returns the directory name of the default profile
If you changed the default dir to something like ~/.thunderbird,
you would get the Thunderbird default profile directory.
"""
profiles_dir = os.path.expanduser(profiledir)
profile_path = None
cp = RawConfigParser()
cp.read(os.path.join(profiles_dir, "profiles.ini"))
for section in cp.sections():
if not cp.has_option(section, "Path"):
continue
if (not profile_path or
(cp.has_option(section, "Default") and cp.get(section, "Default").strip() == "1")):
profile_path = os.path.join(profiles_dir, cp.get(section, "Path").strip())
if not profile_path:
raise RuntimeError("Cannot find default Firefox profile")
return profile_path
def get_encrypted_sites(firefox_profile_dir=None):
"""Opens signons.sqlite and yields encryped password data"""
if firefox_profile_dir is None:
firefox_profile_dir = get_default_firefox_profile_directory()
signons_db = os.path.join(firefox_profile_dir, "signons.sqlite")
query = '''SELECT id, hostname, httpRealm, formSubmitURL,
usernameField, passwordField, encryptedUsername,
encryptedPassword, guid, encType, 'noplainuser', 'noplainpasswd' FROM moz_logins;'''
# We don't want to type out all the column from the DB as we have
## stored them in the SITEFIELDS already. However, we have two
## components extra, the plain usename and password. So we remove
## that from the list, because the table doesn't have that column.
## And we add two literal SQL strings to make our "Site" data
## structure happy
#queryfields = SITEFIELDS[:-2] + ["'noplainuser'", "'noplainpassword'"]
#query = '''SELECT %s
# FROM moz_logins;''' % ', '.join(queryfields)
conn = sqlite.connect(signons_db)
try:
cursor = conn.cursor()
cursor.execute(query)
for site in map(Site._make, cursor.fetchall()):
yield site
finally:
conn.close()
def decrypt(encrypted_string, firefox_profile_directory, password = None):
"""Opens an external tool to decrypt strings
This is mostly for historical reasons or if the API changes. It is
very slow because it needs to call out a lot. It uses the
"pwdecrypt" tool which you might have packaged. Otherwise, you
need to build it yourself.
"""
log = logging.getLogger('firefoxpasswd.decrypt')
execute = [PWDECRYPT, '-d', firefox_profile_directory]
if password:
execute.extend(['-p', password])
process = Popen(execute, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, error = process.communicate(encrypted_string)
log.debug('Sent: %s', encrypted_string)
log.debug('Got: %s', output)
NEEDLE = 'Decrypted: "' # This string is prepended to the decrypted password if found
output = output.strip()
if output == encrypted_string:
log.error('Password was not correct. Please try again without a '
'password or with the correct one')
index = output.index(NEEDLE) + len(NEEDLE)
password = output[index:-1] # And we strip the final quotation mark
return password
class NativeDecryptor(object):
"""Calls the NSS API to decrypt strings"""
def __init__(self, directory, password = ''):
"""You need to give the profile directory and optionally a
password. If you don't give a password but one is needed, you
will be prompted by getpass to provide one.
"""
self.directory = directory
self.log = logging.getLogger('NativeDecryptor')
self.log.debug('Trying to work on %s', directory)
self.libnss = CDLL('libnss3.so')
if self.libnss.NSS_Init(directory) != 0:
self.log.error('Could not initialize NSS')
# Initialize to the empty string, not None, because the password
# function expects rather an empty string
self.password = password = password or ''
slot = self.libnss.PK11_GetInternalKeySlot()
pw_good = self.libnss.PK11_CheckUserPassword(slot, c_char_p(password))
while pw_good != SECSuccess:
msg = 'Password is not good (%d)!' % pw_good
print >>sys.stderr, msg
password = getpass('Please enter password: ')
pw_good = self.libnss.PK11_CheckUserPassword(slot, c_char_p(password))
#raise RuntimeError(msg)
# That's it, we're done with passwords, but we leave the old
# code below in, for nostalgic reasons.
if password is None:
pwdata = secuPWData()
pwdata.source = PW_NONE
pwdata.data = 0
else:
# It's not clear whether this actually works
pwdata = secuPWData()
pwdata.source = PW_PLAINTEXT
pwdata.data = c_char_p (password)
# It doesn't actually work :-(
# Now follow some attempts that were not succesful!
def setpwfunc():
# One attempt was to use PK11PassworFunc. Didn't work.
def password_cb(slot, retry, arg):
#s = self.libnss.PL_strdup(password)
s = self.libnss.PL_strdup("foo")
return s
PK11PasswordFunc = CFUNCTYPE(c_void_p, PRBool, c_void_p)
c_password_cb = PK11PasswordFunc(password_cb)
#self.libnss.PK11_SetPasswordFunc(c_password_cb)
# To be ignored
def changepw():
# Another attempt was to use ChangePW. Again, no effect.
#ret = self.libnss.PK11_ChangePW(slot, pwdata.data, 0);
ret = self.libnss.PK11_ChangePW(slot, password, 0)
if ret == SECFailure:
raise RuntimeError('Setting password failed! %s' % ret)
#self.pwdata = pwdata
def __del__(self):
self.libnss.NSS_Shutdown()
def decrypt(self, string, *args):
"""Decrypts a given string"""
libnss = self.libnss
uname = SECItem()
dectext = SECItem()
#pwdata = self.pwdata
cstring = SECItem()
cstring.data = cast( c_char_p( base64.b64decode(string)), c_void_p)
cstring.len = len(base64.b64decode(string))
#if libnss.PK11SDR_Decrypt (byref (cstring), byref (dectext), byref (pwdata)) == -1:
self.log.debug('Trying to decrypt %s (error: %s)', string, libnss.PORT_GetError())
if libnss.PK11SDR_Decrypt (byref (cstring), byref (dectext)) == -1:
error = libnss.PORT_GetError()
libnss.PR_ErrorToString.restype = c_char_p
error_str = libnss.PR_ErrorToString(error)
raise Exception ("%d: %s" % (error, error_str))
decrypted_data = string_at(dectext.data, dectext.len)
return decrypted_data
def encrypted_sites(self):
"""Yields the encryped passwords from the profile"""
sites = get_encrypted_sites(self.directory)
return sites
def decrypted_sites(self):
"""Decrypts the encrypted_sites and yields the results"""
sites = self.encrypted_sites()
for site in sites:
plain_user = self.decrypt(site.encryptedUsername)
plain_password = self.decrypt(site.encryptedPassword)
site = site._replace(plain_username=plain_user,
plain_password=plain_password)
yield site
def get_firefox_sites_with_decrypted_passwords(firefox_profile_directory = None, password = None):
"""decryption of passwords using the external pwdecrypt program"""
if not firefox_profile_directory:
firefox_profile_directory = get_default_firefox_profile_directory()
#decrypt = NativeDecryptor(firefox_profile_directory).decrypt
for site in get_encrypted_sites(firefox_profile_directory):
plain_user = decrypt(site.encryptedUsername, firefox_profile_directory, password)
plain_password = decrypt(site.encryptedPassword, firefox_profile_directory, password)
site = site._replace(plain_username=plain_user, plain_password=plain_password)
log.debug("Dealing with Site: %r", site)
log.info("user: %s, passwd: %s", plain_user, plain_password)
yield site
def main_decryptor(firefox_profile_directory, password, thunderbird=False):
"""Main function to get Firefox and Thunderbird passwords"""
if not firefox_profile_directory:
if thunderbird:
dir = '~/.thunderbird/'
else:
dir = '~/.mozilla/firefox'
firefox_profile_directory = get_default_firefox_profile_directory(dir)
decryptor = NativeDecryptor(firefox_profile_directory, password)
for site in decryptor.decrypted_sites():
print site
def main():
parser = OptionParser()
parser.add_option("-d", "--directory", default=None,
help="the Firefox profile directory to use")
parser.add_option("-p", "--password", default=None,
help="the master password for the Firefox profile")
parser.add_option("-l", "--loglevel", default=LOGLEVEL_DEFAULT,
help="the level of logging detail [debug, info, warn, critical, error]")
parser.add_option("-t", "--thunderbird", default=False, action='store_true',
help="by default we try to find the Firefox default profile."
" But you can as well ask for Thunderbird's default profile."
" For a more reliable way, give the directory with -d.")
parser.add_option("-n", "--native", default=True, action='store_true',
help="use the native decryptor, i.e. make Python use "
"libnss directly instead of invoking the helper program"
"DEFUNCT! this option will not be checked.")
parser.add_option("-e", "--external", default=False, action='store_true',
help="use an external program `pwdecrypt' to actually "
"decrypt the passwords. This calls out a lot and is dead "
"slow. "
"You need to use this method if you have a password "
"protected database though.")
options, args = parser.parse_args()
loglevel = {'debug': logging.DEBUG, 'info': logging.INFO,
'warn': logging.WARN, 'critical':logging.CRITICAL,
'error': logging.ERROR}.get(options.loglevel, LOGLEVEL_DEFAULT)
logging.basicConfig(level=loglevel)
log = logging.getLogger()
password = options.password
if not options.external:
sys.exit (main_decryptor(options.directory, password, thunderbird=options.thunderbird))
else:
for site in get_firefox_sites_with_decrypted_passwords(options.directory, password):
print site
if __name__ == '__main__':
main()