| 1 | #! /usr/bin/python |
| 2 | ### -*-python-*- |
| 3 | ### |
| 4 | ### Tool for maintaining a secure-ish password database |
| 5 | ### |
| 6 | ### (c) 2005 Straylight/Edgeware |
| 7 | ### |
| 8 | |
| 9 | ###----- Licensing notice --------------------------------------------------- |
| 10 | ### |
| 11 | ### This file is part of the Python interface to Catacomb. |
| 12 | ### |
| 13 | ### Catacomb/Python is free software; you can redistribute it and/or modify |
| 14 | ### it under the terms of the GNU General Public License as published by |
| 15 | ### the Free Software Foundation; either version 2 of the License, or |
| 16 | ### (at your option) any later version. |
| 17 | ### |
| 18 | ### Catacomb/Python is distributed in the hope that it will be useful, |
| 19 | ### but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 20 | ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 21 | ### GNU General Public License for more details. |
| 22 | ### |
| 23 | ### You should have received a copy of the GNU General Public License |
| 24 | ### along with Catacomb/Python; if not, write to the Free Software Foundation, |
| 25 | ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 26 | |
| 27 | ###-------------------------------------------------------------------------- |
| 28 | ### Imported modules. |
| 29 | |
| 30 | from __future__ import with_statement |
| 31 | |
| 32 | from os import environ |
| 33 | import sys as SYS; from sys import argv, exit, stdin, stdout, stderr |
| 34 | from getopt import getopt, GetoptError |
| 35 | from fnmatch import fnmatch |
| 36 | import re |
| 37 | |
| 38 | import catacomb as C |
| 39 | from catacomb.pwsafe import * |
| 40 | |
| 41 | ###-------------------------------------------------------------------------- |
| 42 | ### Python version portability. |
| 43 | |
| 44 | if SYS.version_info >= (3,): |
| 45 | import io as IO |
| 46 | def hack_stream(stream): |
| 47 | _enc = stream.encoding |
| 48 | _lbuf = stream.line_buffering |
| 49 | _nl = stream.newlines |
| 50 | return IO.TextIOWrapper(stream.detach(), |
| 51 | encoding = _enc, |
| 52 | line_buffering = _lbuf, |
| 53 | newline = _nl, |
| 54 | errors = "surrogateescape") |
| 55 | SYS.stdout = stdout = hack_stream(stdout) |
| 56 | def _text(bin): return bin.decode(errors = "surrogateescape") |
| 57 | def _bin(text): return text.encode(errors = "surrogateescape") |
| 58 | else: |
| 59 | def _text(bin): return bin |
| 60 | def _bin(text): return text |
| 61 | |
| 62 | def _excval(): return SYS.exc_info()[1] |
| 63 | |
| 64 | ###-------------------------------------------------------------------------- |
| 65 | ### Utilities. |
| 66 | |
| 67 | ## The program name. |
| 68 | prog = re.sub(r'^.*[/\\]', '', argv[0]) |
| 69 | |
| 70 | def moan(msg): |
| 71 | """Issue a warning message MSG.""" |
| 72 | stderr.write('%s: %s\n' % (prog, msg)) |
| 73 | |
| 74 | def die(msg): |
| 75 | """Report MSG as a fatal error, and exit.""" |
| 76 | moan(msg) |
| 77 | exit(1) |
| 78 | |
| 79 | ###-------------------------------------------------------------------------- |
| 80 | ### Subcommand implementations. |
| 81 | |
| 82 | def cmd_create(av): |
| 83 | |
| 84 | ## Default crypto-primitive selections. |
| 85 | cipher = 'rijndael-cbc' |
| 86 | hash = 'sha256' |
| 87 | mac = None |
| 88 | |
| 89 | ## Parse the options. |
| 90 | try: |
| 91 | opts, args = getopt(av, 'c:d:h:m:', |
| 92 | ['cipher=', 'database=', 'mac=', 'hash=']) |
| 93 | except GetoptError: |
| 94 | return 1 |
| 95 | dbty = 'flat' |
| 96 | for o, a in opts: |
| 97 | if o in ('-c', '--cipher'): cipher = a |
| 98 | elif o in ('-m', '--mac'): mac = a |
| 99 | elif o in ('-h', '--hash'): hash = a |
| 100 | elif o in ('-d', '--database'): dbty = a |
| 101 | else: raise Exception("barf") |
| 102 | if len(args) > 2: return 1 |
| 103 | if len(args) >= 1: tag = args[0] |
| 104 | else: tag = 'pwsafe' |
| 105 | |
| 106 | ## Set up the database. |
| 107 | if mac is None: mac = hash + '-hmac' |
| 108 | try: dbcls = StorageBackend.byname(dbty) |
| 109 | except KeyError: die("Unknown database backend `%s'" % dbty) |
| 110 | PW.create(dbcls, file, tag, |
| 111 | C.gcciphers[cipher], C.gchashes[hash], C.gcmacs[mac]) |
| 112 | |
| 113 | def cmd_changepp(av): |
| 114 | if len(av) != 0: return 1 |
| 115 | with PW(file, writep = True) as pw: pw.changepp() |
| 116 | |
| 117 | def cmd_find(av): |
| 118 | if len(av) != 1: return 1 |
| 119 | with PW(file) as pw: |
| 120 | try: print(_text(pw[_bin(av[0])])) |
| 121 | except KeyError: die("Password `%s' not found" % _excval().args[0]) |
| 122 | |
| 123 | def cmd_store(av): |
| 124 | if len(av) < 1 or len(av) > 2: return 1 |
| 125 | tag = av[0] |
| 126 | with PW(file, writep = True) as pw: |
| 127 | if len(av) < 2: |
| 128 | pp = C.getpass("Enter passphrase `%s': " % tag) |
| 129 | vpp = C.getpass("Confirm passphrase `%s': " % tag) |
| 130 | if pp != vpp: die("passphrases don't match") |
| 131 | elif av[1] == '-': |
| 132 | pp = _bin(stdin.readline().rstrip('\n')) |
| 133 | else: |
| 134 | pp = _bin(av[1]) |
| 135 | pw[_bin(av[0])] = pp |
| 136 | |
| 137 | def cmd_copy(av): |
| 138 | if len(av) < 1 or len(av) > 2: return 1 |
| 139 | with PW(file) as pw_in: |
| 140 | with PW(av[0], writep = True) as pw_out: |
| 141 | if len(av) >= 3: pat = av[1] |
| 142 | else: pat = None |
| 143 | for k in pw_in: |
| 144 | ktext = _text(k) |
| 145 | if pat is None or fnmatch(ktext, pat): pw_out[k] = pw_in[k] |
| 146 | |
| 147 | def cmd_list(av): |
| 148 | if len(av) > 1: return 1 |
| 149 | with PW(file) as pw: |
| 150 | if len(av) >= 1: pat = av[0] |
| 151 | else: pat = None |
| 152 | for k in pw: |
| 153 | ktext = _text(k) |
| 154 | if pat is None or fnmatch(ktext, pat): print(ktext) |
| 155 | |
| 156 | def cmd_topixie(av): |
| 157 | if len(av) > 2: return 1 |
| 158 | with PW(file) as pw: |
| 159 | pix = C.Pixie() |
| 160 | if len(av) == 0: |
| 161 | for tag in pw: pix.set(tag, pw[_bin(tag)]) |
| 162 | else: |
| 163 | tag = _bin(av[0]) |
| 164 | if len(av) >= 2: pptag = av[1] |
| 165 | else: pptag = av[0] |
| 166 | pix.set(pptag, pw[tag]) |
| 167 | |
| 168 | def cmd_del(av): |
| 169 | if len(av) != 1: return 1 |
| 170 | with PW(file, writep = True) as pw: |
| 171 | tag = _bin(av[0]) |
| 172 | try: del pw[tag] |
| 173 | except KeyError: die("Password `%s' not found" % _excval().args[0]) |
| 174 | |
| 175 | def cmd_xfer(av): |
| 176 | |
| 177 | ## Parse the command line. |
| 178 | try: opts, args = getopt(av, 'd:', ['database=']) |
| 179 | except GetoptError: return 1 |
| 180 | dbty = 'flat' |
| 181 | for o, a in opts: |
| 182 | if o in ('-d', '--database'): dbty = a |
| 183 | else: raise Exception("barf") |
| 184 | if len(args) != 1: return 1 |
| 185 | try: dbcls = StorageBackend.byname(dbty) |
| 186 | except KeyError: die("Unknown database backend `%s'" % dbty) |
| 187 | |
| 188 | ## Create the target database. |
| 189 | with StorageBackend.open(file) as db_in: |
| 190 | with dbcls.create(args[0]) as db_out: |
| 191 | for k, v in db_in.iter_meta(): db_out.put_meta(k, v) |
| 192 | for k, v in db_in.iter_passwds(): db_out.put_passwd(k, v) |
| 193 | |
| 194 | commands = { 'create': [cmd_create, |
| 195 | '[-c CIPHER] [-d DBTYPE] [-h HASH] [-m MAC] [PP-TAG]'], |
| 196 | 'find' : [cmd_find, 'LABEL'], |
| 197 | 'store' : [cmd_store, 'LABEL [VALUE]'], |
| 198 | 'list' : [cmd_list, '[GLOB-PATTERN]'], |
| 199 | 'changepp' : [cmd_changepp, ''], |
| 200 | 'copy' : [cmd_copy, 'DEST-FILE [GLOB-PATTERN]'], |
| 201 | 'to-pixie' : [cmd_topixie, '[TAG [PIXIE-TAG]]'], |
| 202 | 'delete' : [cmd_del, 'TAG'], |
| 203 | 'xfer': [cmd_xfer, '[-d DBTYPE] DEST-FILE'] } |
| 204 | |
| 205 | ###-------------------------------------------------------------------------- |
| 206 | ### Command-line handling and dispatch. |
| 207 | |
| 208 | def version(): |
| 209 | print('%s 1.0.0' % prog) |
| 210 | print('Backend types: %s' % |
| 211 | ' '.join([c.NAME for c in StorageBackend.classes()])) |
| 212 | |
| 213 | def usage(fp): |
| 214 | fp.write('Usage: %s COMMAND [ARGS...]\n' % prog) |
| 215 | |
| 216 | def help(): |
| 217 | version() |
| 218 | print('') |
| 219 | usage(stdout) |
| 220 | print(''' |
| 221 | Maintains passwords or other short secrets securely. |
| 222 | |
| 223 | Options: |
| 224 | |
| 225 | -h, --help Show this help text. |
| 226 | -v, --version Show program version number. |
| 227 | -u, --usage Show short usage message. |
| 228 | |
| 229 | -f, --file=FILE Where to find the password-safe file. |
| 230 | |
| 231 | Commands provided: |
| 232 | ''') |
| 233 | for c in sorted(commands): |
| 234 | print('%s %s' % (c, commands[c][1])) |
| 235 | |
| 236 | ## Choose a default database file. |
| 237 | if 'PWSAFE' in environ: |
| 238 | file = environ['PWSAFE'] |
| 239 | else: |
| 240 | file = '%s/.pwsafe' % environ['HOME'] |
| 241 | |
| 242 | ## Parse the command-line options. |
| 243 | try: |
| 244 | opts, argv = getopt(argv[1:], 'hvuf:', |
| 245 | ['help', 'version', 'usage', 'file=']) |
| 246 | except GetoptError: |
| 247 | usage(stderr) |
| 248 | exit(1) |
| 249 | for o, a in opts: |
| 250 | if o in ('-h', '--help'): |
| 251 | help() |
| 252 | exit(0) |
| 253 | elif o in ('-v', '--version'): |
| 254 | version() |
| 255 | exit(0) |
| 256 | elif o in ('-u', '--usage'): |
| 257 | usage(stdout) |
| 258 | exit(0) |
| 259 | elif o in ('-f', '--file'): |
| 260 | file = a |
| 261 | else: |
| 262 | raise Exception("barf") |
| 263 | if len(argv) < 1: |
| 264 | usage(stderr) |
| 265 | exit(1) |
| 266 | |
| 267 | ## Dispatch to a command handler. |
| 268 | if argv[0] in commands: |
| 269 | c = argv[0] |
| 270 | argv = argv[1:] |
| 271 | else: |
| 272 | c = 'find' |
| 273 | try: |
| 274 | if commands[c][0](argv): |
| 275 | stderr.write('Usage: %s %s %s\n' % (prog, c, commands[c][1])) |
| 276 | exit(1) |
| 277 | except DecryptError: |
| 278 | die("decryption failure") |
| 279 | |
| 280 | ###----- That's all, folks -------------------------------------------------- |