chiark / gitweb /
tripe-keys: Provide upload-hook for more complicated publishing.
[tripe] / keys / tripe-keys.in
1 #! @PYTHON@
2 # -*-python-*-
3
4 ### External dependencies
5
6 import catacomb as C
7 import os as OS
8 import sys as SYS
9 import sre as RX
10 import getopt as O
11 import shutil as SH
12 import filecmp as FC
13 from cStringIO import StringIO
14 from errno import *
15 from stat import *
16
17 ### Useful regular expressions
18
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\>')
25
26 ### Utility functions
27
28 class SubprocessError (Exception): pass
29 class VerifyError (Exception): pass
30
31 quis = OS.path.basename(SYS.argv[0])
32 PACKAGE = "@PACKAGE@"
33 VERSION = "@VERSION@"
34
35 def moan(msg):
36   SYS.stderr.write('%s: %s\n' % (quis, msg))
37
38 def die(msg, rc = 1):
39   moan(msg)
40   SYS.exit(rc)
41
42 def subst(s, rx, map):
43   out = StringIO()
44   i = 0
45   for m in rx.finditer(s):
46     out.write(s[i:m.start()] + map[m.group(1)])
47     i = m.end()
48   out.write(s[i:])
49   return out.getvalue()
50
51 def rmtree(path):
52   try:
53     st = OS.lstat(path)
54   except OSError, err:
55     if err.errno == ENOENT:
56       return
57     raise
58   if not S_ISDIR(st.st_mode):
59     OS.unlink(path)
60   else:
61     cwd = OS.getcwd()
62     try:
63       OS.chdir(path)
64       for i in OS.listdir('.'):
65         rmtree(i)
66     finally:
67       OS.chdir(cwd)
68     OS.rmdir(path)
69
70 def zap(file):
71   try:
72     OS.unlink(file)
73   except OSError, err:
74     if err.errno == ENOENT: return
75     raise
76
77 def run(args):
78   args = map(conf_subst, args.split())
79   nargs = []
80   for a in args:
81     if len(a) > 0 and a[0] != '!':
82       nargs += [a]
83     else:
84       nargs += a[1:].split()
85   args = nargs
86   print '+ %s' % ' '.join(args)
87   rc = OS.spawnvp(OS.P_WAIT, args[0], args)
88   if rc != 0:
89     raise SubprocessError, rc
90
91 def hexhyphens(bytes):
92   out = StringIO()
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]))
96   return out.getvalue()
97
98 def fingerprint(kf, ktag):
99   h = C.gchashes[conf['fingerprint-hash']]()
100   k = C.KeyFile(kf)[ktag].fingerprint(h, '-secret')
101   return h.done()
102
103 ### Read configuration
104
105 class ConfigFileError (Exception): pass
106 conf = {}
107
108 def conf_subst(s): return subst(s, rx_dollarsubst, conf)
109
110 ## Read the file
111 def conf_read(f):
112   lno = 0
113   for line in file(f):
114     lno += 1
115     if rx_comment.match(line): continue
116     if line[-1] == '\n': line = line[:-1]
117     match = rx_keyval.match(line)
118     if not match:
119       raise ConfigFileError, "%s:%d: bad line `%s'" % (f, lno, line)
120     k, v = match.groups()
121     conf[k] = conf_subst(v)
122
123 ## Sift the wreckage
124 def conf_defaults():
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'),
133                ('kx', 'dh'),
134                ('kx-param', lambda: {'dh': '-LS -b2048 -B256',
135                                      'ec': '-Cnist-p256'}[conf['kx']]),
136                ('kx-expire', 'now + 1 year'),
137                ('cipher', 'blowfish-cbc'),
138                ('hash', 'sha256'),
139                ('mgf', '${hash}-mgf'),
140                ('mac', lambda: '%s-hmac/%d' %
141                          (conf['hash'],
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',
146                                        'dsa': 'dsa',
147                                        'rsapkcs1': 'rsa',
148                                        'rsapss': 'rsa',
149                                        'ecdsa': 'ec',
150                                        'eckcdsa': 'ec'}[conf['sig']]),
151                ('sig-param', lambda: {'dh': '-LS -b2048 -B256',
152                                       'dsa': '-b2048 -B256',
153                                       'ec': '-Cnist-p256',
154                                       'rsa': '-b2048'}[conf['sig-genalg']]),
155                ('sig-hash', '${hash}'),
156                ('sig-expire', 'forever'),
157                ('fingerprint-hash', '${hash}')]:
158     try:
159       if k in conf: continue
160       if type(v) == str:
161         conf[k] = conf_subst(v)
162       else:
163         conf[k] = v()
164     except KeyError, exc:
165       if len(exc.args) == 0: raise
166       conf[k] = '<missing-var %s>' % exc.args[0]
167
168 ### Commands
169
170 def version(fp = SYS.stdout):
171   fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
172
173 def usage(fp):
174   fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
175
176 def cmd_help(args):
177   if len(args) == 0:
178     version(SYS.stdout)
179     print
180     usage(SYS.stdout)
181     print """
182 Key management utility for TrIPE.
183
184 Options supported:
185
186 -h, --help              Show this help message.
187 -v, --version           Show the version number.
188 -u, --usage             Show pointlessly short usage string.
189
190 Subcommands available:
191 """
192     args = commands.keys()
193     args.sort()
194   for c in args:
195     func, min, max, help = commands[c]
196     print '%s %s' % (c, help)
197
198 def master_keys():
199   if not OS.path.exists('master'):
200     return
201   for k in C.KeyFile('master').itervalues():
202     if (k.type != 'tripe-keys-master' or
203         k.expiredp or
204         not k.tag.startswith('master-')):
205       continue #??
206     yield k
207 def master_sequence(k):
208   return int(k.tag[7:])
209 def max_master_sequence():
210   seq = -1
211   for k in master_keys():
212     q = master_sequence(k)
213     if q > seq: seq = q
214   return seq
215 def seqsubst(x, q):
216   return rx_seq.sub(str(q), conf[x])
217
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')
225
226 def cmd_setup(args):
227   OS.mkdir('repos')
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}''')
232   cmd_newmaster(args)
233
234 def cmd_upload(args):
235
236   ## Sanitize the repository directory
237   umask = OS.umask(0); OS.umask(umask)
238   mode = 0666 & ~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'):
243       OS.unlink(ff)
244       continue
245     OS.chmod(ff, mode)
246
247   rmtree('tmp')
248   OS.mkdir('tmp')
249   OS.symlink('../repos', 'tmp/repos')
250   cwd = OS.getcwd()
251   try:
252
253     ## Build the configuration file
254     seq = max_master_sequence()
255     v = {'MASTER-SEQUENCE': str(seq),
256          'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
257                                              'master-%d' % seq))}
258     fin = file('tripe-keys.master')
259     fout = file('tmp/tripe-keys.conf', 'w')
260     for line in fin:
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']]
265
266     ## Make and sign the repository archive
267     OS.chdir('tmp')
268     run('tar chozf ${repos-file}.new .')
269     OS.chdir(cwd)
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)
276
277     ## Commit the changes
278     for base in commit:
279       new = '%s.new' % base
280       OS.rename(new, base)
281   finally:
282     OS.chdir(cwd)
283     rmtree('tmp')
284   run('sh -c ${upload-hook}')
285
286 def cmd_update(args):
287   cwd = OS.getcwd()
288   rmtree('tmp')
289   try:
290
291     ## Fetch a new distribution
292     OS.mkdir('tmp')
293     OS.chdir('tmp')
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')
298
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)
305
306     ## OK: update our copy
307     OS.chdir(cwd)
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')
313     rmtree('repos.old')
314
315   finally:
316     OS.chdir(cwd)
317     rmtree('tmp')
318   cmd_rebuild(args)
319
320 def cmd_rebuild(args):
321   zap('keyring.pub')
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))
325
326 def cmd_generate(args):
327   tag, = 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}' %
332       tag)
333   run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
334
335 def cmd_clean(args):
336   rmtree('repos')
337   rmtree('tmp')
338   for i in OS.listdir('.'):
339     r = i
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-')):
343       zap(i)
344
345 ### Main driver
346
347 class UsageError (Exception): pass
348
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, '')}
357
358 def init():
359   for f in ['tripe-keys.master', 'tripe-keys.conf']:
360     if OS.path.exists(f):
361       conf_read(f)
362       break
363   conf_defaults()
364 def main(argv):
365   try:
366     opts, args = O.getopt(argv[1:], 'hvu',
367                           ['help', 'version', 'usage'])
368   except O.GetoptError, exc:
369     moan(exc)
370     usage(SYS.stderr)
371     SYS.exit(1)
372   for o, v in opts:
373     if o in ('-h', '--help'):
374       cmd_help([])
375       SYS.exit(0)
376     elif o in ('-v', '--version'):
377       version(SYS.stdout)
378       SYS.exit(0)
379     elif o in ('-u', '--usage'):
380       usage(SYS.stdout)
381       SYS.exit(0)
382   if len(argv) < 2:
383     cmd_help([])
384   else:
385     c = argv[1]
386     func, min, max, help = commands[c]
387     args = argv[2:]
388     if len(args) < min or (max > 0 and len(args) > max):
389       raise UsageError, (c, help)
390     func(args)
391
392 init()
393 main(SYS.argv)