Debian Codegraph @

contrib/store-pw-with-gpg/gpg-pw.py

raw
1 #!/usr/bin/python
2 # Originally taken from: http://stevelosh.com/blog/2012/10/the-homely-mutt/
3 # by Steve Losh
4 # Modified by Lorenzo Grespan on Jan, 2014
5
6 import re
7 import subprocess
8 from sys import argv
9 import logging
10 from os.path import expanduser
11 import unittest
12 import os
13 import sys
14
15 logging.basicConfig(level=logging.INFO)
16
17
18 DEFAULT_PASSWORDS_FILE = os.path.join(
19 os.path.expanduser('~/Mail'),
20 'passwords.gpg')
21
22
23 def get_keychain_pass(account=None, server=None):
24 '''Mac OSX keychain password extraction'''
25 params = {
26 'security': '/usr/bin/security',
27 'command': 'find-internet-password',
28 'account': account,
29 'server': server,
30 'keychain': expanduser('~') + '/Library/Keychains/login.keychain',
31 }
32 command = ("%(security)s -v %(command)s"
33 " -g -a %(account)s -s %(server)s %(keychain)s" % params)
34 output = subprocess.check_output(
35 command, shell=True, stderr=subprocess.STDOUT)
36 outtext = [l for l in output.splitlines()
37 if l.startswith('password: ')][0]
38 return find_password(outtext)
39
40
41 def find_password(text):
42 '''Helper method for osx password extraction'''
43 # a non-capturing group
44 r = re.match(r'password: (?:0x[A-F0-9]+ )?"(.*)"', text)
45 if r:
46 return r.group(1)
47 else:
48 logging.warn("Not found")
49 return None
50
51
52 def get_gpg_pass(account, storage):
53 '''GPG method'''
54 command = ("gpg", "-d", storage)
55 # get attention
56 print('\a') # BEL
57 output = subprocess.check_output(command)
58 # p = subprocess.Popen(command, stdout=subprocess.PIPE)
59 # output, err = p.communicate()
60 for line in output.split('\n'):
61 r = re.match(r'{} ([a-zA-Z0-9]+)'.format(account), line)
62 if r:
63 return r.group(1)
64 return None
65
66
67 def get_pass(account=None, server=None, passwd_file=None):
68 '''Main method'''
69 if not passwd_file:
70 storage = DEFAULT_PASSWORDS_FILE
71 else:
72 storage = os.path.join(
73 os.path.expanduser('~/Mail'),
74 passwd_file)
75 if os.path.exists('/usr/bin/security'):
76 return get_keychain_pass(account, server)
77 if os.path.exists(storage):
78 logging.info("Using {}".format(storage))
79 return get_gpg_pass(account, storage)
80 else:
81 logging.warn("No password file found")
82 sys.exit(1)
83 return None
84
85
86 # test with: python -m unittest <this module name>
87 # really basic tests.. nothing to see. move along
88 class Tester(unittest.TestCase):
89 def testMatchSimple(self):
90 text = 'password: "exampleonetimepass "'
91 self.assertTrue(find_password(text))
92
93 def testMatchComplex(self):
94 text = r'password: 0x74676D62646D736B646970766C66696B0A "anotherexamplepass\012"'
95 self.assertTrue(find_password(text))
96
97
98 if __name__ == "__main__":
99 print(get_pass(argv[1], argv[2], argv[3]))