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.
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 ###--------------------------------------------------------------------------
63 ### Utility functions.
66 class SubprocessError (Exception): pass
67 class VerifyError (Exception): pass
69 ## Program name and identification.
70 quis = OS.path.basename(SYS.argv[0])
75 """Report MSG to standard error."""
76 SYS.stderr.write('%s: %s\n' % (quis, msg))
79 """Report MSG to standard error, and exit with code RC."""
83 def subst(s, rx, map):
85 Substitute values into a string.
87 Repeatedly match RX (a compiled regular expression) against the string S.
88 For each match, extract group 1, and use it as a key to index the MAP;
89 replace the match by the result. Finally, return the fully-substituted
94 for m in rx.finditer(s):
95 out.write(s[i:m.start()] + map[m.group(1)])
101 """Delete the directory tree given by PATH."""
105 if err.errno == ENOENT:
108 if not S_ISDIR(st.st_mode):
114 for i in OS.listdir('.'):
121 """Delete the named FILE if it exists; otherwise do nothing."""
125 if err.errno == ENOENT: return
130 Run a subprocess whose arguments are given by the string ARGS.
132 The ARGS are split at word boundaries, and then subjected to configuration
133 variable substitution (see conf_subst). Individual argument elements
134 beginning with `!' are split again into multiple arguments at word
137 args = map(conf_subst, args.split())
140 if len(a) > 0 and a[0] != '!':
143 nargs += a[1:].split()
145 print '+ %s' % ' '.join(args)
147 rc = OS.spawnvp(OS.P_WAIT, args[0], args)
149 raise SubprocessError, rc
151 def hexhyphens(bytes):
153 Convert a byte string BYTES into hex, with hyphens at each 4-byte boundary.
156 for i in xrange(0, len(bytes)):
157 if i > 0 and i % 4 == 0: out.write('-')
158 out.write('%02x' % ord(bytes[i]))
159 return out.getvalue()
161 def fingerprint(kf, ktag):
163 Compute the fingerprint of a key, using the user's selected hash.
165 KF is the name of a keyfile; KTAG is the tag of the key.
167 h = C.gchashes[conf['fingerprint-hash']]()
168 k = C.KeyFile(kf)[ktag].fingerprint(h, '-secret')
171 ###--------------------------------------------------------------------------
172 ### The configuration file.
175 class ConfigFileError (Exception): pass
177 ## The configuration dictionary.
182 Apply configuration substitutions to S.
184 That is, for each ${KEY} in S, replace it with the current value of the
185 configuration variable KEY.
187 return subst(s, rx_dollarsubst, conf)
191 Read the file F and insert assignments into the configuration dictionary.
196 if rx_comment.match(line): continue
197 if line[-1] == '\n': line = line[:-1]
198 match = rx_keyval.match(line)
200 raise ConfigFileError, "%s:%d: bad line `%s'" % (f, lno, line)
201 k, v = match.groups()
202 conf[k] = conf_subst(v)
206 Apply defaults to the configuration dictionary.
208 Fill in all the interesting configuration variables based on the existing
209 contents, as described in the manual.
211 for k, v in [('repos-base', 'tripe-keys.tar.gz'),
212 ('sig-base', 'tripe-keys.sig-<SEQ>'),
213 ('repos-url', '${base-url}${repos-base}'),
214 ('sig-url', '${base-url}${sig-base}'),
215 ('sig-file', '${base-dir}${sig-base}'),
216 ('repos-file', '${base-dir}${repos-base}'),
217 ('conf-file', '${base-dir}tripe-keys.conf'),
218 ('upload-hook', ': run upload hook'),
220 ('kx-param', lambda: {'dh': '-LS -b2048 -B256',
221 'ec': '-Cnist-p256'}[conf['kx']]),
222 ('kx-expire', 'now + 1 year'),
223 ('cipher', 'blowfish-cbc'),
225 ('master-keygen-flags', '-l'),
226 ('mgf', '${hash}-mgf'),
227 ('mac', lambda: '%s-hmac/%d' %
229 C.gchashes[conf['hash']].hashsz * 4)),
230 ('sig', lambda: {'dh': 'dsa', 'ec': 'ecdsa'}[conf['kx']]),
231 ('sig-fresh', 'always'),
232 ('sig-genalg', lambda: {'kcdsa': 'dh',
237 'eckcdsa': 'ec'}[conf['sig']]),
238 ('sig-param', lambda: {'dh': '-LS -b2048 -B256',
239 'dsa': '-b2048 -B256',
241 'rsa': '-b2048'}[conf['sig-genalg']]),
242 ('sig-hash', '${hash}'),
243 ('sig-expire', 'forever'),
244 ('fingerprint-hash', '${hash}')]:
246 if k in conf: continue
248 conf[k] = conf_subst(v)
251 except KeyError, exc:
252 if len(exc.args) == 0: raise
253 conf[k] = '<missing-var %s>' % exc.args[0]
255 ###--------------------------------------------------------------------------
256 ### Key-management utilities.
260 Iterate over the master keys.
262 if not OS.path.exists('master'):
264 for k in C.KeyFile('master').itervalues():
265 if (k.type != 'tripe-keys-master' or
267 not k.tag.startswith('master-')):
271 def master_sequence(k):
273 Return the sequence number of the given master key as an integer.
275 No checking is done that K is really a master key.
277 return int(k.tag[7:])
279 def max_master_sequence():
281 Find the master key with the highest sequence number and return this
285 for k in master_keys():
286 q = master_sequence(k)
292 Return the value of the configuration variable X, with <SEQ> replaced by
295 return rx_seq.sub(str(q), conf[x])
297 ###--------------------------------------------------------------------------
298 ### Commands: help [COMMAND...]
300 def version(fp = SYS.stdout):
301 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
304 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
312 Key management utility for TrIPE.
316 -h, --help Show this help message.
317 -v, --version Show the version number.
318 -u, --usage Show pointlessly short usage string.
320 Subcommands available:
322 args = commands.keys()
325 func, min, max, help = commands[c]
326 print '%s %s' % (c, help)
328 ###--------------------------------------------------------------------------
329 ### Commands: newmaster
331 def cmd_newmaster(args):
332 seq = max_master_sequence() + 1
333 run('''key -kmaster add
334 -a${sig-genalg} !${sig-param}
335 -e${sig-expire} !${master-keygen-flags} -tmaster-%d tripe-keys-master
336 sig=${sig} hash=${sig-hash}''' % seq)
337 run('key -kmaster extract -f-secret repos/master.pub')
339 ###--------------------------------------------------------------------------
344 run('''key -krepos/param add
345 -a${kx}-param !${kx-param}
346 -eforever -tparam tripe-${kx}-param
347 cipher=${cipher} hash=${hash} mac=${mac} mgf=${mgf}''')
350 ###--------------------------------------------------------------------------
353 def cmd_upload(args):
355 ## Sanitize the repository directory
356 umask = OS.umask(0); OS.umask(umask)
358 for f in OS.listdir('repos'):
359 ff = OS.path.join('repos', f)
360 if (f.startswith('master') or f.startswith('peer-')) \
361 and f.endswith('.old'):
368 OS.symlink('../repos', 'tmp/repos')
372 ## Build the configuration file
373 seq = max_master_sequence()
374 v = {'MASTER-SEQUENCE': str(seq),
375 'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
377 fin = file('tripe-keys.master')
378 fout = file('tmp/tripe-keys.conf', 'w')
380 fout.write(subst(line, rx_atsubst, v))
381 fin.close(); fout.close()
382 SH.copyfile('tmp/tripe-keys.conf', conf_subst('${conf-file}.new'))
383 commit = [conf['repos-file'], conf['conf-file']]
385 ## Make and sign the repository archive
387 run('tar chozf ${repos-file}.new .')
389 for k in master_keys():
390 seq = master_sequence(k)
391 sigfile = seqsubst('sig-file', seq)
392 run('''catsign -kmaster sign -abdC -kmaster-%d
393 -o%s.new ${repos-file}.new''' % (seq, sigfile))
394 commit.append(sigfile)
396 ## Commit the changes
398 new = '%s.new' % base
403 run('sh -c ${upload-hook}')
405 ###--------------------------------------------------------------------------
406 ### Commands: rebuild
408 def cmd_rebuild(args):
410 for i in OS.listdir('repos'):
411 if i.startswith('peer-') and i.endswith('.pub'):
412 run('key -kkeyring.pub merge %s' % OS.path.join('repos', i))
414 ###--------------------------------------------------------------------------
417 def cmd_update(args):
422 ## Fetch a new distribution
425 seq = int(conf['master-sequence'])
426 run('curl -s -o tripe-keys.tar.gz ${repos-url}')
427 run('curl -s -o tripe-keys.sig %s' % seqsubst('sig-url', seq))
428 run('tar xfz tripe-keys.tar.gz')
430 ## Verify the signature
431 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
432 got = fingerprint('repos/master.pub', 'master-%d' % seq)
433 if want != got: raise VerifyError
434 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
435 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
437 ## OK: update our copy
439 if OS.path.exists('repos'): OS.rename('repos', 'repos.old')
440 OS.rename('tmp/repos', 'repos')
441 if not FC.cmp('tmp/tripe-keys.conf', 'tripe-keys.conf'):
442 moan('configuration file changed: recommend running another update')
443 OS.rename('tmp/tripe-keys.conf', 'tripe-keys.conf')
451 ###--------------------------------------------------------------------------
452 ### Commands: generate TAG
454 def cmd_generate(args):
456 keyring_pub = 'peer-%s.pub' % tag
457 zap('keyring'); zap(keyring_pub)
458 run('key -kkeyring merge repos/param')
459 run('key -kkeyring add -a${kx} -pparam -e${kx-expire} -t%s tripe-${kx}' %
461 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
463 ###--------------------------------------------------------------------------
469 for i in OS.listdir('.'):
471 if r.endswith('.old'): r = r[:-4]
472 if (r == 'master' or r == 'param' or
473 r == 'keyring' or r == 'keyring.pub' or r.startswith('peer-')):
476 ###--------------------------------------------------------------------------
480 mtu, = (lambda mtu = '1500': (mtu,))(*args)
483 blksz = C.gcciphers[conf['cipher']].blksz
485 index = conf['mac'].find('/')
487 tagsz = C.gcmacs[conf['mac']].tagsz
489 tagsz = int(conf['mac'][index + 1:])/8
491 mtu -= 20 # Minimum IP header
492 mtu -= 8 # UDP header
493 mtu -= 1 # TrIPE packet type octet
494 mtu -= tagsz # MAC tag
495 mtu -= 4 # Sequence number
496 mtu -= blksz # Initialization vector
500 ###--------------------------------------------------------------------------
504 class UsageError (Exception): pass
506 commands = {'help': (cmd_help, 0, 1, ''),
507 'newmaster': (cmd_newmaster, 0, 0, ''),
508 'setup': (cmd_setup, 0, 0, ''),
509 'upload': (cmd_upload, 0, 0, ''),
510 'update': (cmd_update, 0, 0, ''),
511 'clean': (cmd_clean, 0, 0, ''),
512 'mtu': (cmd_mtu, 0, 1, '[PATH-MTU]'),
513 'generate': (cmd_generate, 1, 1, 'TAG'),
514 'rebuild': (cmd_rebuild, 0, 0, '')}
518 Load the appropriate configuration file and set up the configuration
521 for f in ['tripe-keys.master', 'tripe-keys.conf']:
522 if OS.path.exists(f):
529 Main program: parse options and dispatch to appropriate command handler.
532 opts, args = O.getopt(argv[1:], 'hvu',
533 ['help', 'version', 'usage'])
534 except O.GetoptError, exc:
539 if o in ('-h', '--help'):
542 elif o in ('-v', '--version'):
545 elif o in ('-u', '--usage'):
552 func, min, max, help = commands[c]
554 if len(args) < min or (max > 0 and len(args) > max):
555 raise UsageError, (c, help)
558 ###----- That's all, folks --------------------------------------------------
560 if __name__ == '__main__':