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'),
133 ('kx-param', lambda: {'dh': '-LS -b2048 -B256',
134 'ec': '-Cnist-p256'}[conf['kx']]),
135 ('kx-expire', 'now + 1 year'),
136 ('cipher', 'blowfish-cbc'),
138 ('mgf', '${hash}-mgf'),
139 ('mac', lambda: '%s-hmac/%d' %
141 C.gchashes[conf['hash']].hashsz * 4)),
142 ('sig', lambda: {'dh': 'dsa', 'ec': 'ecdsa'}[conf['kx']]),
143 ('sig-fresh', 'always'),
144 ('sig-genalg', lambda: {'kcdsa': 'dh',
149 'eckcdsa': 'ec'}[conf['sig']]),
150 ('sig-param', lambda: {'dh': '-LS -b2048 -B256',
151 'dsa': '-b2048 -B256',
153 'rsa': '-b2048'}[conf['sig-genalg']]),
154 ('sig-hash', '${hash}'),
155 ('sig-expire', 'forever'),
156 ('fingerprint-hash', '${hash}')]:
158 if k in conf: continue
160 conf[k] = conf_subst(v)
163 except KeyError, exc:
164 if len(exc.args) == 0: raise
165 conf[k] = '<missing-var %s>' % exc.args[0]
169 def version(fp = SYS.stdout):
170 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
173 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
181 Key management utility for TrIPE.
185 -h, --help Show this help message.
186 -v, --version Show the version number.
187 -u, --usage Show pointlessly short usage string.
189 Subcommands available:
191 args = commands.keys()
194 func, min, max, help = commands[c]
195 print '%s %s' % (c, help)
198 if not OS.path.exists('master'):
200 for k in C.KeyFile('master'):
201 if (k.type != 'tripe-keys-master' or
203 not k.tag.startswith('master-')):
206 def master_sequence(k):
207 return int(k.tag[7:])
208 def max_master_sequence():
210 for k in master_keys():
211 q = master_sequence(k)
215 return rx_seq.sub(str(q), conf[x])
217 def cmd_newmaster(args):
218 seq = max_master_sequence() + 1
219 run('''key -kmaster add
220 -a${sig-genalg} !${sig-param}
221 -e${sig-expire} -l -tmaster-%d tripe-keys-master
222 sig=${sig} hash=${sig-hash}''' % seq)
223 run('key -kmaster extract -f-secret repos/master.pub')
227 run('''key -krepos/param add
228 -a${kx}-param !${kx-param}
229 -eforever -tparam tripe-${kx}-param
230 cipher=${cipher} hash=${hash} mac=${mac} mgf=${mgf}''')
233 def cmd_upload(args):
235 ## Sanitize the repository directory
236 umask = OS.umask(0); OS.umask(umask)
238 for f in OS.listdir('repos'):
239 ff = OS.path.join('repos', f)
240 if (f.startswith('master') or f.startswith('peer-')) \
241 and f.endswith('.old'):
248 OS.symlink('../repos', 'tmp/repos')
252 ## Build the configuration file
253 seq = max_master_sequence()
254 v = {'MASTER-SEQUENCE': str(seq),
255 'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
257 fin = file('tripe-keys.master')
258 fout = file('tmp/tripe-keys.conf', 'w')
260 fout.write(subst(line, rx_atsubst, v))
261 fin.close(); fout.close()
262 SH.copyfile('tmp/tripe-keys.conf', conf_subst('${conf-file}.new'))
263 commit = [conf['repos-file'], conf['conf-file']]
265 ## Make and sign the repository archive
267 run('tar chozf ${repos-file}.new .')
269 for k in master_keys():
270 seq = master_sequence(k)
271 sigfile = seqsubst('sig-file', seq)
272 run('''catsign -kmaster sign -abdC -kmaster-%d
273 -o%s.new ${repos-file}.new''' % (seq, sigfile))
274 commit.append(sigfile)
276 ## Commit the changes
278 new = '%s.new' % base
284 def cmd_update(args):
289 ## Fetch a new distribution
292 seq = int(conf['master-sequence'])
293 run('wget -q -O tripe-keys.tar.gz ${repos-url}')
294 run('wget -q -O tripe-keys.sig %s' % seqsubst('sig-url', seq))
295 run('tar xfz tripe-keys.tar.gz')
297 ## Verify the signature
298 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
299 got = fingerprint('repos/master.pub', 'master-%d' % seq)
300 if want != got: raise VerifyError
301 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
302 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
304 ## OK: update our copy
306 if OS.path.exists('repos'): OS.rename('repos', 'repos.old')
307 OS.rename('tmp/repos', 'repos')
308 if not FC.cmp('tmp/tripe-keys.conf', 'tripe-keys.conf'):
309 moan('configuration file changed: recommend running another update')
310 OS.rename('tmp/tripe-keys.conf', 'tripe-keys.conf')
318 def cmd_rebuild(args):
320 for i in OS.listdir('repos'):
321 if i.startswith('peer-') and i.endswith('.pub'):
322 run('key -kkeyring.pub merge %s' % OS.path.join('repos', i))
324 def cmd_generate(args):
326 keyring_pub = 'peer-%s.pub' % tag
327 zap('keyring'); zap(keyring_pub)
328 run('key -kkeyring merge repos/param')
329 run('key -kkeyring add -a${kx} -pparam -e${kx-expire} -t%s tripe-${kx}' %
331 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
336 for i in OS.listdir('.'):
338 if r.endswith('.old'): r = r[:-4]
339 if (r == 'master' or r == 'param' or
340 r == 'keyring' or r == 'keyring.pub' or r.startswith('peer-')):
345 class UsageError (Exception): pass
347 commands = {'help': (cmd_help, 0, 1, ''),
348 'newmaster': (cmd_newmaster, 0, 0, ''),
349 'setup': (cmd_setup, 0, 0, ''),
350 'upload': (cmd_upload, 0, 0, ''),
351 'update': (cmd_update, 0, 0, ''),
352 'clean': (cmd_clean, 0, 0, ''),
353 'generate': (cmd_generate, 1, 1, 'TAG'),
354 'rebuild': (cmd_rebuild, 0, 0, '')}
357 for f in ['tripe-keys.master', 'tripe-keys.conf']:
358 if OS.path.exists(f):
364 opts, args = O.getopt(argv[1:], 'hvu',
365 ['help', 'version', 'usage'])
366 except O.GetoptError, exc:
371 if o in ('-h', '--help'):
374 elif o in ('-v', '--version'):
377 elif o in ('-u', '--usage'):
384 func, min, max, help = commands[c]
386 if len(args) < min or (max > 0 and len(args) > max):
387 raise UsageError, (c, help)