4 ### External dependencies
13 from cStringIO import StringIO
17 ### Useful regular expressions
19 rx_comment = RX.compile(r'^\s*(#|$)')
20 rx_keyval = RX.compile(r'^\s*([-\w]+)(?:\s+(?!=)|\s*=\s*)(|\S|\S.*\S)\s*$')
21 rx_dollarsubst = RX.compile(r'\$\{([-\w]+)\}')
22 rx_atsubst = RX.compile(r'@([-\w]+)@')
23 rx_nonalpha = RX.compile(r'\W')
24 rx_seq = RX.compile(r'\<SEQ\>')
28 class SubprocessError (Exception): pass
29 class VerifyError (Exception): pass
31 quis = OS.path.basename(SYS.argv[0])
36 SYS.stderr.write('%s: %s\n' % (quis, msg))
42 def subst(s, rx, map):
45 for m in rx.finditer(s):
46 out.write(s[i:m.start()] + map[m.group(1)])
55 if err.errno == ENOENT:
58 if not S_ISDIR(st.st_mode):
64 for i in OS.listdir('.'):
74 if err.errno == ENOENT: return
78 args = map(conf_subst, args.split())
81 if len(a) > 0 and a[0] != '!':
84 nargs += a[1:].split()
86 print '+ %s' % ' '.join(args)
87 rc = OS.spawnvp(OS.P_WAIT, args[0], args)
89 raise SubprocessError, rc
91 def hexhyphens(bytes):
93 for i in xrange(0, len(bytes)):
94 if i > 0 and i % 4 == 0: out.write('-')
95 out.write('%02x' % ord(bytes[i]))
98 def fingerprint(kf, ktag):
99 h = C.gchashes[conf['fingerprint-hash']]()
100 k = C.KeyFile(kf)[ktag].fingerprint(h, '-secret')
103 ### Read configuration
105 class ConfigFileError (Exception): pass
108 def conf_subst(s): return subst(s, rx_dollarsubst, conf)
115 if rx_comment.match(line): continue
116 if line[-1] == '\n': line = line[:-1]
117 match = rx_keyval.match(line)
119 raise ConfigFileError, "%s:%d: bad line `%s'" % (f, lno, line)
120 k, v = match.groups()
121 conf[k] = conf_subst(v)
125 for k, v in [('repos-base', 'tripe-keys.tar.gz'),
126 ('sig-base', 'tripe-keys.sig-<SEQ>'),
127 ('repos-url', '${base-url}${repos-base}'),
128 ('sig-url', '${base-url}${sig-base}'),
129 ('sig-file', '${base-dir}${sig-base}'),
130 ('repos-file', '${base-dir}${repos-base}'),
131 ('conf-file', '${base-dir}tripe-keys.conf'),
132 ('upload-hook', ': run upload hook'),
134 ('kx-param', lambda: {'dh': '-LS -b2048 -B256',
135 'ec': '-Cnist-p256'}[conf['kx']]),
136 ('kx-expire', 'now + 1 year'),
137 ('cipher', 'blowfish-cbc'),
139 ('mgf', '${hash}-mgf'),
140 ('mac', lambda: '%s-hmac/%d' %
142 C.gchashes[conf['hash']].hashsz * 4)),
143 ('sig', lambda: {'dh': 'dsa', 'ec': 'ecdsa'}[conf['kx']]),
144 ('sig-fresh', 'always'),
145 ('sig-genalg', lambda: {'kcdsa': 'dh',
150 'eckcdsa': 'ec'}[conf['sig']]),
151 ('sig-param', lambda: {'dh': '-LS -b2048 -B256',
152 'dsa': '-b2048 -B256',
154 'rsa': '-b2048'}[conf['sig-genalg']]),
155 ('sig-hash', '${hash}'),
156 ('sig-expire', 'forever'),
157 ('fingerprint-hash', '${hash}')]:
159 if k in conf: continue
161 conf[k] = conf_subst(v)
164 except KeyError, exc:
165 if len(exc.args) == 0: raise
166 conf[k] = '<missing-var %s>' % exc.args[0]
170 def version(fp = SYS.stdout):
171 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
174 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
182 Key management utility for TrIPE.
186 -h, --help Show this help message.
187 -v, --version Show the version number.
188 -u, --usage Show pointlessly short usage string.
190 Subcommands available:
192 args = commands.keys()
195 func, min, max, help = commands[c]
196 print '%s %s' % (c, help)
199 if not OS.path.exists('master'):
201 for k in C.KeyFile('master').itervalues():
202 if (k.type != 'tripe-keys-master' or
204 not k.tag.startswith('master-')):
207 def master_sequence(k):
208 return int(k.tag[7:])
209 def max_master_sequence():
211 for k in master_keys():
212 q = master_sequence(k)
216 return rx_seq.sub(str(q), conf[x])
218 def cmd_newmaster(args):
219 seq = max_master_sequence() + 1
220 run('''key -kmaster add
221 -a${sig-genalg} !${sig-param}
222 -e${sig-expire} -l -tmaster-%d tripe-keys-master
223 sig=${sig} hash=${sig-hash}''' % seq)
224 run('key -kmaster extract -f-secret repos/master.pub')
228 run('''key -krepos/param add
229 -a${kx}-param !${kx-param}
230 -eforever -tparam tripe-${kx}-param
231 cipher=${cipher} hash=${hash} mac=${mac} mgf=${mgf}''')
234 def cmd_upload(args):
236 ## Sanitize the repository directory
237 umask = OS.umask(0); OS.umask(umask)
239 for f in OS.listdir('repos'):
240 ff = OS.path.join('repos', f)
241 if (f.startswith('master') or f.startswith('peer-')) \
242 and f.endswith('.old'):
249 OS.symlink('../repos', 'tmp/repos')
253 ## Build the configuration file
254 seq = max_master_sequence()
255 v = {'MASTER-SEQUENCE': str(seq),
256 'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
258 fin = file('tripe-keys.master')
259 fout = file('tmp/tripe-keys.conf', 'w')
261 fout.write(subst(line, rx_atsubst, v))
262 fin.close(); fout.close()
263 SH.copyfile('tmp/tripe-keys.conf', conf_subst('${conf-file}.new'))
264 commit = [conf['repos-file'], conf['conf-file']]
266 ## Make and sign the repository archive
268 run('tar chozf ${repos-file}.new .')
270 for k in master_keys():
271 seq = master_sequence(k)
272 sigfile = seqsubst('sig-file', seq)
273 run('''catsign -kmaster sign -abdC -kmaster-%d
274 -o%s.new ${repos-file}.new''' % (seq, sigfile))
275 commit.append(sigfile)
277 ## Commit the changes
279 new = '%s.new' % base
284 run('sh -c ${upload-hook}')
286 def cmd_update(args):
291 ## Fetch a new distribution
294 seq = int(conf['master-sequence'])
295 run('curl -s -o tripe-keys.tar.gz ${repos-url}')
296 run('curl -s -o tripe-keys.sig %s' % seqsubst('sig-url', seq))
297 run('tar xfz tripe-keys.tar.gz')
299 ## Verify the signature
300 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
301 got = fingerprint('repos/master.pub', 'master-%d' % seq)
302 if want != got: raise VerifyError
303 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
304 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
306 ## OK: update our copy
308 if OS.path.exists('repos'): OS.rename('repos', 'repos.old')
309 OS.rename('tmp/repos', 'repos')
310 if not FC.cmp('tmp/tripe-keys.conf', 'tripe-keys.conf'):
311 moan('configuration file changed: recommend running another update')
312 OS.rename('tmp/tripe-keys.conf', 'tripe-keys.conf')
320 def cmd_rebuild(args):
322 for i in OS.listdir('repos'):
323 if i.startswith('peer-') and i.endswith('.pub'):
324 run('key -kkeyring.pub merge %s' % OS.path.join('repos', i))
326 def cmd_generate(args):
328 keyring_pub = 'peer-%s.pub' % tag
329 zap('keyring'); zap(keyring_pub)
330 run('key -kkeyring merge repos/param')
331 run('key -kkeyring add -a${kx} -pparam -e${kx-expire} -t%s tripe-${kx}' %
333 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
338 for i in OS.listdir('.'):
340 if r.endswith('.old'): r = r[:-4]
341 if (r == 'master' or r == 'param' or
342 r == 'keyring' or r == 'keyring.pub' or r.startswith('peer-')):
347 class UsageError (Exception): pass
349 commands = {'help': (cmd_help, 0, 1, ''),
350 'newmaster': (cmd_newmaster, 0, 0, ''),
351 'setup': (cmd_setup, 0, 0, ''),
352 'upload': (cmd_upload, 0, 0, ''),
353 'update': (cmd_update, 0, 0, ''),
354 'clean': (cmd_clean, 0, 0, ''),
355 'generate': (cmd_generate, 1, 1, 'TAG'),
356 'rebuild': (cmd_rebuild, 0, 0, '')}
359 for f in ['tripe-keys.master', 'tripe-keys.conf']:
360 if OS.path.exists(f):
366 opts, args = O.getopt(argv[1:], 'hvu',
367 ['help', 'version', 'usage'])
368 except O.GetoptError, exc:
373 if o in ('-h', '--help'):
376 elif o in ('-v', '--version'):
379 elif o in ('-u', '--usage'):
386 func, min, max, help = commands[c]
388 if len(args) < min or (max > 0 and len(args) > max):
389 raise UsageError, (c, help)