4 ### Key management and distribution
6 ### (c) 2006 Straylight/Edgeware
9 ###----- Licensing notice ---------------------------------------------------
11 ### This file is part of Trivial IP Encryption (TrIPE).
13 ### TrIPE is free software: you can redistribute it and/or modify it under
14 ### the terms of the GNU General Public License as published by the Free
15 ### Software Foundation; either version 3 of the License, or (at your
16 ### option) any later version.
18 ### TrIPE is distributed in the hope that it will be useful, but WITHOUT
19 ### ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20 ### FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
23 ### You should have received a copy of the GNU General Public License
24 ### along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
26 ###--------------------------------------------------------------------------
27 ### External dependencies.
37 from cStringIO import StringIO
41 ###--------------------------------------------------------------------------
42 ### Useful regular expressions
44 ## Match a comment or blank line.
45 rx_comment = RX.compile(r'^\s*(#|$)')
47 ## Match a KEY = VALUE assignment.
48 rx_keyval = RX.compile(r'^\s*([-\w]+)(?:\s+(?!=)|\s*=\s*)(|\S|\S.*\S)\s*$')
50 ## Match a ${KEY} substitution.
51 rx_dollarsubst = RX.compile(r'\$\{([-\w]+)\}')
53 ## Match a @TAG@ substitution.
54 rx_atsubst = RX.compile(r'@([-\w]+)@')
56 ## Match a single non-alphanumeric character.
57 rx_nonalpha = RX.compile(r'\W')
59 ## Match the literal string "<SEQ>".
60 rx_seq = RX.compile(r'\<SEQ\>')
62 ## Match a shell metacharacter.
63 rx_shmeta = RX.compile('[\\s`!"#$&*()\\[\\];\'|<>?\\\\]')
65 ## Match a character which needs escaping in a shell double-quoted string.
66 rx_shquote = RX.compile(r'["`$\\]')
68 ###--------------------------------------------------------------------------
69 ### Utility functions.
72 class SubprocessError (Exception): pass
73 class VerifyError (Exception): pass
75 ## Program name and identification.
76 quis = OS.path.basename(SYS.argv[0])
81 """Report MSG to standard error."""
82 SYS.stderr.write('%s: %s\n' % (quis, msg))
85 """Report MSG to standard error, and exit with code RC."""
89 def subst(s, rx, map):
91 Substitute values into a string.
93 Repeatedly match RX (a compiled regular expression) against the string S.
94 For each match, extract group 1, and use it as a key to index the MAP;
95 replace the match by the result. Finally, return the fully-substituted
100 for m in rx.finditer(s):
101 out.write(s[i:m.start()] + map[m.group(1)])
104 return out.getvalue()
106 def shell_quotify(arg):
108 Quotify ARG to keep the shell happy.
110 This isn't actually used for invoking commands, just for presentation
111 purposes; but correctness is still nice.
113 if not rx_shmeta.search(arg):
115 elif arg.find("'") == -1:
118 return '"%s"' % rx_shquote.sub(lambda m: '\\' + m.group(0), arg)
121 """Delete the directory tree given by PATH."""
125 if err.errno == ENOENT:
128 if not S_ISDIR(st.st_mode):
134 for i in OS.listdir('.'):
141 """Delete the named FILE if it exists; otherwise do nothing."""
145 if err.errno == ENOENT: return
150 Run a subprocess whose arguments are given by the string ARGS.
152 The ARGS are split at word boundaries, and then subjected to configuration
153 variable substitution (see conf_subst). Individual argument elements
154 beginning with `!' are split again into multiple arguments at word
157 args = map(conf_subst, args.split())
160 if len(a) > 0 and a[0] != '!':
163 nargs += a[1:].split()
165 print '+ %s' % ' '.join([shell_quotify(arg) for arg in args])
167 rc = OS.spawnvp(OS.P_WAIT, args[0], args)
169 raise SubprocessError(rc)
171 def hexhyphens(bytes):
173 Convert a byte string BYTES into hex, with hyphens at each 4-byte boundary.
176 for i in xrange(0, len(bytes)):
177 if i > 0 and i % 4 == 0: out.write('-')
178 out.write('%02x' % ord(bytes[i]))
179 return out.getvalue()
181 def fingerprint(kf, ktag):
183 Compute the fingerprint of a key, using the user's selected hash.
185 KF is the name of a keyfile; KTAG is the tag of the key.
187 h = C.gchashes[conf['fingerprint-hash']]()
188 k = C.KeyFile(kf)[ktag].fingerprint(h, '-secret')
191 ###--------------------------------------------------------------------------
192 ### The configuration file.
195 class ConfigFileError (Exception): pass
197 ## The configuration dictionary.
202 Apply configuration substitutions to S.
204 That is, for each ${KEY} in S, replace it with the current value of the
205 configuration variable KEY.
207 return subst(s, rx_dollarsubst, conf)
211 Read the file F and insert assignments into the configuration dictionary.
216 if rx_comment.match(line): continue
217 if line[-1] == '\n': line = line[:-1]
218 match = rx_keyval.match(line)
220 raise ConfigFileError("%s:%d: bad line `%s'" % (f, lno, line))
221 k, v = match.groups()
222 conf[k] = conf_subst(v)
226 Apply defaults to the configuration dictionary.
228 Fill in all the interesting configuration variables based on the existing
229 contents, as described in the manual.
231 for k, v in [('repos-base', 'tripe-keys.tar.gz'),
232 ('sig-base', 'tripe-keys.sig-<SEQ>'),
233 ('repos-url', '${base-url}${repos-base}'),
234 ('sig-url', '${base-url}${sig-base}'),
235 ('sig-file', '${base-dir}${sig-base}'),
236 ('repos-file', '${base-dir}${repos-base}'),
237 ('conf-file', '${base-dir}tripe-keys.conf'),
238 ('upload-hook', ': run upload hook'),
240 ('kx-genalg', lambda: {'dh': 'dh',
243 'x448': 'x448'}[conf['kx']]),
244 ('kx-param-genalg', lambda: {'dh': 'dh-param',
247 'x448': 'empty'}[conf['kx']]),
248 ('kx-param', lambda: {'dh': '-LS -b3072 -B256',
251 'x448': ''}[conf['kx']]),
252 ('kx-attrs', lambda: {'dh': 'serialization=constlen',
253 'ec': 'serialization=constlen',
255 'x448': ''}[conf['kx']]),
256 ('kx-expire', 'now + 1 year'),
257 ('kx-warn-days', '28'),
259 ('cipher', lambda: conf['bulk'] == 'naclbox'
260 and 'salsa20' or 'rijndael-cbc'),
262 ('master-keygen-flags', '-l'),
263 ('master-attrs', ''),
264 ('mgf', '${hash}-mgf'),
265 ('mac', lambda: conf['bulk'] == 'naclbox'
269 C.gchashes[conf['hash']].hashsz * 4)),
270 ('sig', lambda: {'dh': 'dsa',
273 'x448': 'ed448'}[conf['kx']]),
274 ('sig-fresh', 'always'),
275 ('sig-genalg', lambda: {'kcdsa': 'dh',
281 'ed25519': 'ed25519',
282 'ed448': 'ed448'}[conf['sig']]),
283 ('sig-param', lambda: {'dh': '-LS -b3072 -B256',
284 'dsa': '-b3072 -B256',
288 'ed448': ''}[conf['sig-genalg']]),
289 ('sig-hash', '${hash}'),
290 ('sig-expire', 'forever'),
291 ('fingerprint-hash', '${hash}')]:
293 if k in conf: continue
295 conf[k] = conf_subst(v)
298 except KeyError, exc:
299 if len(exc.args) == 0: raise
300 conf[k] = '<missing-var %s>' % exc.args[0]
302 ###--------------------------------------------------------------------------
303 ### Key-management utilities.
307 Iterate over the master keys.
309 if not OS.path.exists('master'):
311 for k in C.KeyFile('master').itervalues():
312 if (k.type != 'tripe-keys-master' or
314 not k.tag.startswith('master-')):
318 def master_sequence(k):
320 Return the sequence number of the given master key as an integer.
322 No checking is done that K is really a master key.
324 return int(k.tag[7:])
326 def max_master_sequence():
328 Find the master key with the highest sequence number and return this
332 for k in master_keys():
333 q = master_sequence(k)
339 Return the value of the configuration variable X, with <SEQ> replaced by
342 return rx_seq.sub(str(q), conf[x])
344 ###--------------------------------------------------------------------------
345 ### Commands: help [COMMAND...]
347 def version(fp = SYS.stdout):
348 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
351 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
359 Key management utility for TrIPE.
363 -h, --help Show this help message.
364 -v, --version Show the version number.
365 -u, --usage Show pointlessly short usage string.
367 Subcommands available:
369 args = commands.keys()
372 try: func, min, max, help = commands[c]
373 except KeyError: die("unknown command `%s'" % c)
374 print '%s%s%s' % (c, help and ' ', help)
376 ###--------------------------------------------------------------------------
377 ### Commands: newmaster
379 def cmd_newmaster(args):
380 seq = max_master_sequence() + 1
381 run('''key -kmaster add
382 -a${sig-genalg} !${sig-param}
383 -e${sig-expire} !${master-keygen-flags} -tmaster-%d tripe-keys-master
384 sig=${sig} hash=${sig-hash} !${master-attrs}''' % seq)
385 run('key -kmaster extract -f-secret repos/master.pub')
387 ###--------------------------------------------------------------------------
392 run('''key -krepos/param add
393 -a${kx-param-genalg} !${kx-param}
394 -eforever -tparam tripe-param
395 kx-group=${kx} mgf=${mgf} mac=${mac}
396 bulk=${bulk} cipher=${cipher} hash=${hash} ${kx-attrs}''')
399 ###--------------------------------------------------------------------------
402 def cmd_upload(args):
404 ## Sanitize the repository directory
405 umask = OS.umask(0); OS.umask(umask)
407 for f in OS.listdir('repos'):
408 ff = OS.path.join('repos', f)
409 if (f.startswith('master') or f.startswith('peer-')) \
410 and f.endswith('.old'):
417 OS.symlink('../repos', 'tmp/repos')
421 ## Build the configuration file
422 seq = max_master_sequence()
423 v = {'MASTER-SEQUENCE': str(seq),
424 'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
426 fin = file('tripe-keys.master')
427 fout = file('tmp/tripe-keys.conf', 'w')
429 fout.write(subst(line, rx_atsubst, v))
430 fin.close(); fout.close()
431 SH.copyfile('tmp/tripe-keys.conf', conf_subst('${conf-file}.new'))
432 commit = [conf['repos-file'], conf['conf-file']]
434 ## Make and sign the repository archive
436 run('tar chozf ${repos-file}.new .')
438 for k in master_keys():
439 seq = master_sequence(k)
440 sigfile = seqsubst('sig-file', seq)
441 run('''catsign -kmaster sign -abdC -kmaster-%d
442 -o%s.new ${repos-file}.new''' % (seq, sigfile))
443 commit.append(sigfile)
445 ## Commit the changes
447 new = '%s.new' % base
450 ## Remove files in the base-dir which don't correspond to ones we just
453 basedir = conf['base-dir']
456 if base.startswith(basedir): allow[base[bdl:]] = 1
457 for found in OS.listdir(basedir):
458 if found not in allow: OS.remove(OS.path.join(basedir, found))
462 run('sh -c ${upload-hook}')
464 ###--------------------------------------------------------------------------
465 ### Commands: rebuild
467 def cmd_rebuild(args):
469 for i in OS.listdir('repos'):
470 if i.startswith('peer-') and i.endswith('.pub'):
471 run('key -kkeyring.pub merge %s' % OS.path.join('repos', i))
473 ###--------------------------------------------------------------------------
476 def cmd_update(args):
481 ## Fetch a new distribution
484 seq = int(conf['master-sequence'])
485 run('curl -sL -o tripe-keys.tar.gz ${repos-url}')
486 run('curl -sL -o tripe-keys.sig %s' % seqsubst('sig-url', seq))
487 run('tar xfz tripe-keys.tar.gz')
489 ## Verify the signature
490 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
491 got = fingerprint('repos/master.pub', 'master-%d' % seq)
492 if want != got: raise VerifyError()
493 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
494 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
496 ## OK: update our copy
498 if OS.path.exists('repos'): OS.rename('repos', 'repos.old')
499 OS.rename('tmp/repos', 'repos')
500 if not FC.cmp('tmp/tripe-keys.conf', 'tripe-keys.conf', False):
501 moan('configuration file changed: recommend running another update')
502 OS.rename('tmp/tripe-keys.conf', 'tripe-keys.conf')
510 ###--------------------------------------------------------------------------
511 ### Commands: generate TAG
513 def cmd_generate(args):
515 keyring_pub = 'peer-%s.pub' % tag
516 zap('keyring'); zap(keyring_pub)
517 run('key -kkeyring merge repos/param')
518 run('key -kkeyring add -a${kx-genalg} -pparam -e${kx-expire} -t%s tripe' %
520 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
522 ###--------------------------------------------------------------------------
528 for i in OS.listdir('.'):
530 if r.endswith('.old'): r = r[:-4]
531 if (r == 'master' or r == 'param' or
532 r == 'keyring' or r == 'keyring.pub' or r.startswith('peer-')):
535 ###--------------------------------------------------------------------------
540 thresh = int(conf['kx-warn-days']) * 86400
541 if k.exptime == C.KEXP_FOREVER: return None
542 elif k.exptime == C.KEXP_EXPIRE: left = -1
543 else: left = k.exptime - now
545 return "key `%s' HAS EXPIRED" % k.tag
547 if left >= 86400: n, u, uu = left // 86400, 'day', 'days'
548 else: n, u, uu = left // 3600, 'hour', 'hours'
549 return "key `%s' EXPIRES in %d %s" % (k.tag, n, n == 1 and u or uu)
554 if OS.path.exists('keyring.pub'):
555 for k in C.KeyFile('keyring.pub').itervalues():
556 whinge = check_key(k)
557 if whinge is not None: print whinge
558 if OS.path.exists('master'):
560 for k in C.KeyFile('master').itervalues():
561 whinge = check_key(k)
562 if whinge is None: break
563 whinges.append(whinge)
565 for whinge in whinges: print whinge
567 ###--------------------------------------------------------------------------
571 macname = conf['mac']
572 index = macname.rindex('/')
573 if index == -1: tagsz = C.gcmacs[macname].tagsz
574 else: tagsz = int(macname[index + 1:])/8
578 mtu, = (lambda mtu = '1500': (mtu,))(*args)
581 mtu -= 20 # Minimum IP header
582 mtu -= 8 # UDP header
583 mtu -= 1 # TrIPE packet type octet
588 blksz = C.gcciphers[conf['cipher']].blksz
589 mtu -= mac_tagsz() # MAC tag
590 mtu -= 4 # Sequence number
591 mtu -= blksz # Initialization vector
594 mtu -= mac_tagsz() # MAC tag
595 mtu -= 4 # Sequence number
597 elif bulk == 'naclbox':
599 mtu -= 4 # Sequence number
602 die("Unknown bulk transform `%s'" % bulk)
606 ###--------------------------------------------------------------------------
609 commands = {'help': (cmd_help, 0, 1, ''),
610 'newmaster': (cmd_newmaster, 0, 0, ''),
611 'setup': (cmd_setup, 0, 0, ''),
612 'upload': (cmd_upload, 0, 0, ''),
613 'update': (cmd_update, 0, 0, ''),
614 'clean': (cmd_clean, 0, 0, ''),
615 'mtu': (cmd_mtu, 0, 1, '[PATH-MTU]'),
616 'check': (cmd_check, 0, 0, ''),
617 'generate': (cmd_generate, 1, 1, 'TAG'),
618 'rebuild': (cmd_rebuild, 0, 0, '')}
622 Load the appropriate configuration file and set up the configuration
625 for f in ['tripe-keys.master', 'tripe-keys.conf']:
626 if OS.path.exists(f):
633 Main program: parse options and dispatch to appropriate command handler.
636 opts, args = O.getopt(argv[1:], 'hvu',
637 ['help', 'version', 'usage'])
638 except O.GetoptError, exc:
643 if o in ('-h', '--help'):
646 elif o in ('-v', '--version'):
649 elif o in ('-u', '--usage'):
656 try: func, min, max, help = commands[c]
657 except KeyError: die("unknown command `%s'" % c)
659 if len(args) < min or (max is not None and len(args) > max):
660 SYS.stderr.write('Usage: %s %s%s%s\n' % (quis, c, help and ' ', help))
664 ###----- That's all, folks --------------------------------------------------
666 if __name__ == '__main__':