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 ('master-keygen-flags', '-l'),
140 ('mgf', '${hash}-mgf'),
141 ('mac', lambda: '%s-hmac/%d' %
143 C.gchashes[conf['hash']].hashsz * 4)),
144 ('sig', lambda: {'dh': 'dsa', 'ec': 'ecdsa'}[conf['kx']]),
145 ('sig-fresh', 'always'),
146 ('sig-genalg', lambda: {'kcdsa': 'dh',
151 'eckcdsa': 'ec'}[conf['sig']]),
152 ('sig-param', lambda: {'dh': '-LS -b2048 -B256',
153 'dsa': '-b2048 -B256',
155 'rsa': '-b2048'}[conf['sig-genalg']]),
156 ('sig-hash', '${hash}'),
157 ('sig-expire', 'forever'),
158 ('fingerprint-hash', '${hash}')]:
160 if k in conf: continue
162 conf[k] = conf_subst(v)
165 except KeyError, exc:
166 if len(exc.args) == 0: raise
167 conf[k] = '<missing-var %s>' % exc.args[0]
171 def version(fp = SYS.stdout):
172 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
175 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
183 Key management utility for TrIPE.
187 -h, --help Show this help message.
188 -v, --version Show the version number.
189 -u, --usage Show pointlessly short usage string.
191 Subcommands available:
193 args = commands.keys()
196 func, min, max, help = commands[c]
197 print '%s %s' % (c, help)
200 if not OS.path.exists('master'):
202 for k in C.KeyFile('master').itervalues():
203 if (k.type != 'tripe-keys-master' or
205 not k.tag.startswith('master-')):
208 def master_sequence(k):
209 return int(k.tag[7:])
210 def max_master_sequence():
212 for k in master_keys():
213 q = master_sequence(k)
217 return rx_seq.sub(str(q), conf[x])
219 def cmd_newmaster(args):
220 seq = max_master_sequence() + 1
221 run('''key -kmaster add
222 -a${sig-genalg} !${sig-param}
223 -e${sig-expire} !${master-keygen-flags} -tmaster-%d tripe-keys-master
224 sig=${sig} hash=${sig-hash}''' % seq)
225 run('key -kmaster extract -f-secret repos/master.pub')
229 run('''key -krepos/param add
230 -a${kx}-param !${kx-param}
231 -eforever -tparam tripe-${kx}-param
232 cipher=${cipher} hash=${hash} mac=${mac} mgf=${mgf}''')
235 def cmd_upload(args):
237 ## Sanitize the repository directory
238 umask = OS.umask(0); OS.umask(umask)
240 for f in OS.listdir('repos'):
241 ff = OS.path.join('repos', f)
242 if (f.startswith('master') or f.startswith('peer-')) \
243 and f.endswith('.old'):
250 OS.symlink('../repos', 'tmp/repos')
254 ## Build the configuration file
255 seq = max_master_sequence()
256 v = {'MASTER-SEQUENCE': str(seq),
257 'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
259 fin = file('tripe-keys.master')
260 fout = file('tmp/tripe-keys.conf', 'w')
262 fout.write(subst(line, rx_atsubst, v))
263 fin.close(); fout.close()
264 SH.copyfile('tmp/tripe-keys.conf', conf_subst('${conf-file}.new'))
265 commit = [conf['repos-file'], conf['conf-file']]
267 ## Make and sign the repository archive
269 run('tar chozf ${repos-file}.new .')
271 for k in master_keys():
272 seq = master_sequence(k)
273 sigfile = seqsubst('sig-file', seq)
274 run('''catsign -kmaster sign -abdC -kmaster-%d
275 -o%s.new ${repos-file}.new''' % (seq, sigfile))
276 commit.append(sigfile)
278 ## Commit the changes
280 new = '%s.new' % base
285 run('sh -c ${upload-hook}')
287 def cmd_update(args):
292 ## Fetch a new distribution
295 seq = int(conf['master-sequence'])
296 run('curl -s -o tripe-keys.tar.gz ${repos-url}')
297 run('curl -s -o tripe-keys.sig %s' % seqsubst('sig-url', seq))
298 run('tar xfz tripe-keys.tar.gz')
300 ## Verify the signature
301 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
302 got = fingerprint('repos/master.pub', 'master-%d' % seq)
303 if want != got: raise VerifyError
304 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
305 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
307 ## OK: update our copy
309 if OS.path.exists('repos'): OS.rename('repos', 'repos.old')
310 OS.rename('tmp/repos', 'repos')
311 if not FC.cmp('tmp/tripe-keys.conf', 'tripe-keys.conf'):
312 moan('configuration file changed: recommend running another update')
313 OS.rename('tmp/tripe-keys.conf', 'tripe-keys.conf')
321 def cmd_rebuild(args):
323 for i in OS.listdir('repos'):
324 if i.startswith('peer-') and i.endswith('.pub'):
325 run('key -kkeyring.pub merge %s' % OS.path.join('repos', i))
327 def cmd_generate(args):
329 keyring_pub = 'peer-%s.pub' % tag
330 zap('keyring'); zap(keyring_pub)
331 run('key -kkeyring merge repos/param')
332 run('key -kkeyring add -a${kx} -pparam -e${kx-expire} -t%s tripe-${kx}' %
334 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
339 for i in OS.listdir('.'):
341 if r.endswith('.old'): r = r[:-4]
342 if (r == 'master' or r == 'param' or
343 r == 'keyring' or r == 'keyring.pub' or r.startswith('peer-')):
348 class UsageError (Exception): pass
350 commands = {'help': (cmd_help, 0, 1, ''),
351 'newmaster': (cmd_newmaster, 0, 0, ''),
352 'setup': (cmd_setup, 0, 0, ''),
353 'upload': (cmd_upload, 0, 0, ''),
354 'update': (cmd_update, 0, 0, ''),
355 'clean': (cmd_clean, 0, 0, ''),
356 'generate': (cmd_generate, 1, 1, 'TAG'),
357 'rebuild': (cmd_rebuild, 0, 0, '')}
360 for f in ['tripe-keys.master', 'tripe-keys.conf']:
361 if OS.path.exists(f):
367 opts, args = O.getopt(argv[1:], 'hvu',
368 ['help', 'version', 'usage'])
369 except O.GetoptError, exc:
374 if o in ('-h', '--help'):
377 elif o in ('-v', '--version'):
380 elif o in ('-u', '--usage'):
387 func, min, max, help = commands[c]
389 if len(args) < min or (max > 0 and len(args) > max):
390 raise UsageError, (c, help)