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
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.
18 ### TrIPE 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.
23 ### You should have received a copy of the GNU General Public License
24 ### along with TrIPE; if not, write to the Free Software Foundation,
25 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 ###--------------------------------------------------------------------------
28 ### External dependencies.
38 from cStringIO import StringIO
42 ###--------------------------------------------------------------------------
43 ### Useful regular expressions
45 ## Match a comment or blank line.
46 rx_comment = RX.compile(r'^\s*(#|$)')
48 ## Match a KEY = VALUE assignment.
49 rx_keyval = RX.compile(r'^\s*([-\w]+)(?:\s+(?!=)|\s*=\s*)(|\S|\S.*\S)\s*$')
51 ## Match a ${KEY} substitution.
52 rx_dollarsubst = RX.compile(r'\$\{([-\w]+)\}')
54 ## Match a @TAG@ substitution.
55 rx_atsubst = RX.compile(r'@([-\w]+)@')
57 ## Match a single non-alphanumeric character.
58 rx_nonalpha = RX.compile(r'\W')
60 ## Match the literal string "<SEQ>".
61 rx_seq = RX.compile(r'\<SEQ\>')
63 ## Match a shell metacharacter.
64 rx_shmeta = RX.compile('[\\s`!"#$&*()\\[\\];\'|<>?\\\\]')
66 ## Match a character which needs escaping in a shell double-quoted string.
67 rx_shquote = RX.compile(r'["`$\\]')
69 ###--------------------------------------------------------------------------
70 ### Utility functions.
73 class SubprocessError (Exception): pass
74 class VerifyError (Exception): pass
76 ## Program name and identification.
77 quis = OS.path.basename(SYS.argv[0])
82 """Report MSG to standard error."""
83 SYS.stderr.write('%s: %s\n' % (quis, msg))
86 """Report MSG to standard error, and exit with code RC."""
90 def subst(s, rx, map):
92 Substitute values into a string.
94 Repeatedly match RX (a compiled regular expression) against the string S.
95 For each match, extract group 1, and use it as a key to index the MAP;
96 replace the match by the result. Finally, return the fully-substituted
101 for m in rx.finditer(s):
102 out.write(s[i:m.start()] + map[m.group(1)])
105 return out.getvalue()
107 def shell_quotify(arg):
109 Quotify ARG to keep the shell happy.
111 This isn't actually used for invoking commands, just for presentation
112 purposes; but correctness is still nice.
114 if not rx_shmeta.search(arg):
116 elif arg.find("'") == -1:
119 return '"%s"' % rx_shquote.sub(lambda m: '\\' + m.group(0), arg)
122 """Delete the directory tree given by PATH."""
126 if err.errno == ENOENT:
129 if not S_ISDIR(st.st_mode):
135 for i in OS.listdir('.'):
142 """Delete the named FILE if it exists; otherwise do nothing."""
146 if err.errno == ENOENT: return
151 Run a subprocess whose arguments are given by the string ARGS.
153 The ARGS are split at word boundaries, and then subjected to configuration
154 variable substitution (see conf_subst). Individual argument elements
155 beginning with `!' are split again into multiple arguments at word
158 args = map(conf_subst, args.split())
161 if len(a) > 0 and a[0] != '!':
164 nargs += a[1:].split()
166 print '+ %s' % ' '.join([shell_quotify(arg) for arg in args])
168 rc = OS.spawnvp(OS.P_WAIT, args[0], args)
170 raise SubprocessError, rc
172 def hexhyphens(bytes):
174 Convert a byte string BYTES into hex, with hyphens at each 4-byte boundary.
177 for i in xrange(0, len(bytes)):
178 if i > 0 and i % 4 == 0: out.write('-')
179 out.write('%02x' % ord(bytes[i]))
180 return out.getvalue()
182 def fingerprint(kf, ktag):
184 Compute the fingerprint of a key, using the user's selected hash.
186 KF is the name of a keyfile; KTAG is the tag of the key.
188 h = C.gchashes[conf['fingerprint-hash']]()
189 k = C.KeyFile(kf)[ktag].fingerprint(h, '-secret')
192 ###--------------------------------------------------------------------------
193 ### The configuration file.
196 class ConfigFileError (Exception): pass
198 ## The configuration dictionary.
203 Apply configuration substitutions to S.
205 That is, for each ${KEY} in S, replace it with the current value of the
206 configuration variable KEY.
208 return subst(s, rx_dollarsubst, conf)
212 Read the file F and insert assignments into the configuration dictionary.
217 if rx_comment.match(line): continue
218 if line[-1] == '\n': line = line[:-1]
219 match = rx_keyval.match(line)
221 raise ConfigFileError, "%s:%d: bad line `%s'" % (f, lno, line)
222 k, v = match.groups()
223 conf[k] = conf_subst(v)
227 Apply defaults to the configuration dictionary.
229 Fill in all the interesting configuration variables based on the existing
230 contents, as described in the manual.
232 for k, v in [('repos-base', 'tripe-keys.tar.gz'),
233 ('sig-base', 'tripe-keys.sig-<SEQ>'),
234 ('repos-url', '${base-url}${repos-base}'),
235 ('sig-url', '${base-url}${sig-base}'),
236 ('sig-file', '${base-dir}${sig-base}'),
237 ('repos-file', '${base-dir}${repos-base}'),
238 ('conf-file', '${base-dir}tripe-keys.conf'),
239 ('upload-hook', ': run upload hook'),
241 ('kx-genalg', lambda: {'dh': 'dh',
242 'ec': 'ec'}[conf['kx']]),
243 ('kx-param-genalg', lambda: {'dh': 'dh-param',
244 'ec': 'ec-param'}[conf['kx']]),
245 ('kx-param', lambda: {'dh': '-LS -b3072 -B256',
246 'ec': '-Cnist-p256'}[conf['kx']]),
247 ('kx-attrs', 'serialization=constlen'),
248 ('kx-expire', 'now + 1 year'),
249 ('kx-warn-days', '28'),
251 ('cipher', lambda: conf['bulk'] == 'naclbox'
252 and 'salsa20' or 'rijndael-cbc'),
254 ('master-keygen-flags', '-l'),
255 ('master-attrs', ''),
256 ('mgf', '${hash}-mgf'),
257 ('mac', lambda: conf['bulk'] == 'naclbox'
261 C.gchashes[conf['hash']].hashsz * 4)),
262 ('sig', lambda: {'dh': 'dsa', 'ec': 'ecdsa'}[conf['kx']]),
263 ('sig-fresh', 'always'),
264 ('sig-genalg', lambda: {'kcdsa': 'dh',
270 'ed25519': 'ed25519',
271 'ed448': 'ed448'}[conf['sig']]),
272 ('sig-param', lambda: {'dh': '-LS -b3072 -B256',
273 'dsa': '-b3072 -B256',
277 'ed448': ''}[conf['sig-genalg']]),
278 ('sig-hash', '${hash}'),
279 ('sig-expire', 'forever'),
280 ('fingerprint-hash', '${hash}')]:
282 if k in conf: continue
284 conf[k] = conf_subst(v)
287 except KeyError, exc:
288 if len(exc.args) == 0: raise
289 conf[k] = '<missing-var %s>' % exc.args[0]
291 ###--------------------------------------------------------------------------
292 ### Key-management utilities.
296 Iterate over the master keys.
298 if not OS.path.exists('master'):
300 for k in C.KeyFile('master').itervalues():
301 if (k.type != 'tripe-keys-master' or
303 not k.tag.startswith('master-')):
307 def master_sequence(k):
309 Return the sequence number of the given master key as an integer.
311 No checking is done that K is really a master key.
313 return int(k.tag[7:])
315 def max_master_sequence():
317 Find the master key with the highest sequence number and return this
321 for k in master_keys():
322 q = master_sequence(k)
328 Return the value of the configuration variable X, with <SEQ> replaced by
331 return rx_seq.sub(str(q), conf[x])
333 ###--------------------------------------------------------------------------
334 ### Commands: help [COMMAND...]
336 def version(fp = SYS.stdout):
337 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
340 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
348 Key management utility for TrIPE.
352 -h, --help Show this help message.
353 -v, --version Show the version number.
354 -u, --usage Show pointlessly short usage string.
356 Subcommands available:
358 args = commands.keys()
361 try: func, min, max, help = commands[c]
362 except KeyError: die("unknown command `%s'" % c)
363 print '%s%s%s' % (c, help and ' ', help)
365 ###--------------------------------------------------------------------------
366 ### Commands: newmaster
368 def cmd_newmaster(args):
369 seq = max_master_sequence() + 1
370 run('''key -kmaster add
371 -a${sig-genalg} !${sig-param}
372 -e${sig-expire} !${master-keygen-flags} -tmaster-%d tripe-keys-master
373 sig=${sig} hash=${sig-hash} !${master-attrs}''' % seq)
374 run('key -kmaster extract -f-secret repos/master.pub')
376 ###--------------------------------------------------------------------------
381 run('''key -krepos/param add
382 -a${kx-param-genalg} !${kx-param}
383 -eforever -tparam tripe-param
384 kx-group=${kx} mgf=${mgf} mac=${mac}
385 bulk=${bulk} cipher=${cipher} hash=${hash} ${kx-attrs}''')
388 ###--------------------------------------------------------------------------
391 def cmd_upload(args):
393 ## Sanitize the repository directory
394 umask = OS.umask(0); OS.umask(umask)
396 for f in OS.listdir('repos'):
397 ff = OS.path.join('repos', f)
398 if (f.startswith('master') or f.startswith('peer-')) \
399 and f.endswith('.old'):
406 OS.symlink('../repos', 'tmp/repos')
410 ## Build the configuration file
411 seq = max_master_sequence()
412 v = {'MASTER-SEQUENCE': str(seq),
413 'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
415 fin = file('tripe-keys.master')
416 fout = file('tmp/tripe-keys.conf', 'w')
418 fout.write(subst(line, rx_atsubst, v))
419 fin.close(); fout.close()
420 SH.copyfile('tmp/tripe-keys.conf', conf_subst('${conf-file}.new'))
421 commit = [conf['repos-file'], conf['conf-file']]
423 ## Make and sign the repository archive
425 run('tar chozf ${repos-file}.new .')
427 for k in master_keys():
428 seq = master_sequence(k)
429 sigfile = seqsubst('sig-file', seq)
430 run('''catsign -kmaster sign -abdC -kmaster-%d
431 -o%s.new ${repos-file}.new''' % (seq, sigfile))
432 commit.append(sigfile)
434 ## Commit the changes
436 new = '%s.new' % base
439 ## Remove files in the base-dir which don't correspond to ones we just
442 basedir = conf['base-dir']
445 if base.startswith(basedir): allow[base[bdl:]] = 1
446 for found in OS.listdir(basedir):
447 if found not in allow: OS.remove(OS.path.join(basedir, found))
451 run('sh -c ${upload-hook}')
453 ###--------------------------------------------------------------------------
454 ### Commands: rebuild
456 def cmd_rebuild(args):
458 for i in OS.listdir('repos'):
459 if i.startswith('peer-') and i.endswith('.pub'):
460 run('key -kkeyring.pub merge %s' % OS.path.join('repos', i))
462 ###--------------------------------------------------------------------------
465 def cmd_update(args):
470 ## Fetch a new distribution
473 seq = int(conf['master-sequence'])
474 run('curl -s -o tripe-keys.tar.gz ${repos-url}')
475 run('curl -s -o tripe-keys.sig %s' % seqsubst('sig-url', seq))
476 run('tar xfz tripe-keys.tar.gz')
478 ## Verify the signature
479 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
480 got = fingerprint('repos/master.pub', 'master-%d' % seq)
481 if want != got: raise VerifyError
482 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
483 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
485 ## OK: update our copy
487 if OS.path.exists('repos'): OS.rename('repos', 'repos.old')
488 OS.rename('tmp/repos', 'repos')
489 if not FC.cmp('tmp/tripe-keys.conf', 'tripe-keys.conf', False):
490 moan('configuration file changed: recommend running another update')
491 OS.rename('tmp/tripe-keys.conf', 'tripe-keys.conf')
499 ###--------------------------------------------------------------------------
500 ### Commands: generate TAG
502 def cmd_generate(args):
504 keyring_pub = 'peer-%s.pub' % tag
505 zap('keyring'); zap(keyring_pub)
506 run('key -kkeyring merge repos/param')
507 run('key -kkeyring add -a${kx-genalg} -pparam -e${kx-expire} -t%s tripe' %
509 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
511 ###--------------------------------------------------------------------------
517 for i in OS.listdir('.'):
519 if r.endswith('.old'): r = r[:-4]
520 if (r == 'master' or r == 'param' or
521 r == 'keyring' or r == 'keyring.pub' or r.startswith('peer-')):
524 ###--------------------------------------------------------------------------
529 thresh = int(conf['kx-warn-days']) * 86400
530 if k.exptime == C.KEXP_FOREVER: return None
531 elif k.exptime == C.KEXP_EXPIRE: left = -1
532 else: left = k.exptime - now
534 return "key `%s' HAS EXPIRED" % k.tag
536 if left >= 86400: n, u, uu = left // 86400, 'day', 'days'
537 else: n, u, uu = left // 3600, 'hour', 'hours'
538 return "key `%s' EXPIRES in %d %s" % (k.tag, n, n == 1 and u or uu)
543 if OS.path.exists('keyring.pub'):
544 for k in C.KeyFile('keyring.pub').itervalues():
545 whinge = check_key(k)
546 if whinge is not None: print whinge
547 if OS.path.exists('master'):
549 for k in C.KeyFile('master').itervalues():
550 whinge = check_key(k)
551 if whinge is None: break
552 whinges.append(whinge)
554 for whinge in whinges: print whinge
556 ###--------------------------------------------------------------------------
560 macname = conf['mac']
561 index = macname.rindex('/')
562 if index == -1: tagsz = C.gcmacs[macname].tagsz
563 else: tagsz = int(macname[index + 1:])/8
567 mtu, = (lambda mtu = '1500': (mtu,))(*args)
570 mtu -= 20 # Minimum IP header
571 mtu -= 8 # UDP header
572 mtu -= 1 # TrIPE packet type octet
577 blksz = C.gcciphers[conf['cipher']].blksz
578 mtu -= mac_tagsz() # MAC tag
579 mtu -= 4 # Sequence number
580 mtu -= blksz # Initialization vector
583 mtu -= mac_tagsz() # MAC tag
584 mtu -= 4 # Sequence number
586 elif bulk == 'naclbox':
588 mtu -= 4 # Sequence number
591 die("Unknown bulk transform `%s'" % bulk)
595 ###--------------------------------------------------------------------------
598 commands = {'help': (cmd_help, 0, 1, ''),
599 'newmaster': (cmd_newmaster, 0, 0, ''),
600 'setup': (cmd_setup, 0, 0, ''),
601 'upload': (cmd_upload, 0, 0, ''),
602 'update': (cmd_update, 0, 0, ''),
603 'clean': (cmd_clean, 0, 0, ''),
604 'mtu': (cmd_mtu, 0, 1, '[PATH-MTU]'),
605 'check': (cmd_check, 0, 0, ''),
606 'generate': (cmd_generate, 1, 1, 'TAG'),
607 'rebuild': (cmd_rebuild, 0, 0, '')}
611 Load the appropriate configuration file and set up the configuration
614 for f in ['tripe-keys.master', 'tripe-keys.conf']:
615 if OS.path.exists(f):
622 Main program: parse options and dispatch to appropriate command handler.
625 opts, args = O.getopt(argv[1:], 'hvu',
626 ['help', 'version', 'usage'])
627 except O.GetoptError, exc:
632 if o in ('-h', '--help'):
635 elif o in ('-v', '--version'):
638 elif o in ('-u', '--usage'):
645 try: func, min, max, help = commands[c]
646 except KeyError: die("unknown command `%s'" % c)
648 if len(args) < min or (max is not None and len(args) > max):
649 SYS.stderr.write('Usage: %s %s%s%s\n' % (quis, c, help and ' ', help))
653 ###----- That's all, folks --------------------------------------------------
655 if __name__ == '__main__':