chiark / gitweb /
Weird. tripe-keys got backdates somewhere.
[tripe] / 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                ('kx', 'dh'),
133                ('kx-param', lambda: {'dh': '-LS -b2048 -B256',
134                                      'ec': '-Cnist-p256'}[conf['kx']]),
135                ('kx-expire', 'now + 1 year'),
136                ('cipher', 'blowfish-cbc'),
137                ('hash', 'sha256'),
138                ('mgf', '${hash}-mgf'),
139                ('mac', lambda: '%s-hmac/%d' %
140                          (conf['hash'],
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',
145                                        'dsa': 'dsa',
146                                        'rsapkcs1': 'rsa',
147                                        'rsapss': 'rsa',
148                                        'ecdsa': 'ec',
149                                        'eckcdsa': 'ec'}[conf['sig']]),
150                ('sig-param', lambda: {'dh': '-LS -b2048 -B256',
151                                       'dsa': '-b2048 -B256',
152                                       'ec': '-Cnist-p256',
153                                       'rsa': '-b2048'}[conf['sig-genalg']]),
154                ('sig-hash', '${hash}'),
155                ('sig-expire', 'forever'),
156                ('fingerprint-hash', '${hash}')]:
157     try:
158       if k in conf: continue
159       if type(v) == str:
160         conf[k] = conf_subst(v)
161       else:
162         conf[k] = v()
163     except KeyError, exc:
164       if len(exc.args) == 0: raise
165       conf[k] = '<missing-var %s>' % exc.args[0]
166
167 ### Commands
168
169 def version(fp = SYS.stdout):
170   fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
171
172 def usage(fp):
173   fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
174
175 def cmd_help(args):
176   if len(args) == 0:
177     version(SYS.stdout)
178     print
179     usage(SYS.stdout)
180     print """
181 Key management utility for TrIPE.
182
183 Options supported:
184
185 -h, --help              Show this help message.
186 -v, --version           Show the version number.
187 -u, --usage             Show pointlessly short usage string.
188
189 Subcommands available:
190 """
191     args = commands.keys()
192     args.sort()
193   for c in args:
194     func, min, max, help = commands[c]
195     print '%s %s' % (c, help)
196
197 def master_keys():
198   if not OS.path.exists('master'):
199     return
200   for k in C.KeyFile('master'):
201     if (k.type != 'tripe-keys-master' or
202         k.expiredp or
203         not k.tag.startswith('master-')):
204       continue #??
205     yield k
206 def master_sequence(k):
207   return int(k.tag[7:])
208 def max_master_sequence():
209   seq = -1
210   for k in master_keys():
211     q = master_sequence(k)
212     if q > seq: seq = q
213   return seq
214 def seqsubst(x, q):
215   return rx_seq.sub(str(q), conf[x])
216
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')
224
225 def cmd_setup(args):
226   OS.mkdir('repos')
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}''')
231   cmd_newmaster(args)
232
233 def cmd_upload(args):
234
235   ## Sanitize the repository directory
236   umask = OS.umask(0); OS.umask(umask)
237   mode = 0666 & ~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'):
242       OS.unlink(ff)
243       continue
244     OS.chmod(ff, mode)
245
246   rmtree('tmp')
247   OS.mkdir('tmp')
248   OS.symlink('../repos', 'tmp/repos')
249   cwd = OS.getcwd()
250   try:
251
252     ## Build the configuration file
253     seq = max_master_sequence()
254     v = {'MASTER-SEQUENCE': str(seq),
255          'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
256                                              'master-%d' % seq))}
257     fin = file('tripe-keys.master')
258     fout = file('tmp/tripe-keys.conf', 'w')
259     for line in fin:
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']]
264
265     ## Make and sign the repository archive
266     OS.chdir('tmp')
267     run('tar chozf ${repos-file}.new .')
268     OS.chdir(cwd)
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)
275
276     ## Commit the changes
277     for base in commit:
278       new = '%s.new' % base
279       OS.rename(new, base)
280   finally:
281     OS.chdir(cwd)
282     rmtree('tmp')    
283
284 def cmd_update(args):
285   cwd = OS.getcwd()
286   rmtree('tmp')
287   try:
288
289     ## Fetch a new distribution
290     OS.mkdir('tmp')
291     OS.chdir('tmp')
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')
296
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)
303
304     ## OK: update our copy
305     OS.chdir(cwd)
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')
311     rmtree('repos.old')
312
313   finally:
314     OS.chdir(cwd)
315     rmtree('tmp')
316   cmd_rebuild(args)
317
318 def cmd_rebuild(args):
319   zap('keyring.pub')
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))
323
324 def cmd_generate(args):
325   tag, = 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}' %
330       tag)
331   run('key -kkeyring extract -f-secret %s' % keyring_pub)
332
333 def cmd_clean(args):
334   rmtree('repos')
335   rmtree('tmp')
336   for i in OS.listdir('.'):
337     r = i
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-')):
341       zap(i)
342
343 ### Main driver
344
345 class UsageError (Exception): pass
346   
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, '')}
355
356 def init():
357   for f in ['tripe-keys.master', 'tripe-keys.conf']:
358     if OS.path.exists(f):
359       conf_read(f)
360       break
361   conf_defaults()
362 def main(argv):
363   try:
364     opts, args = O.getopt(argv[1:], 'hvu',
365                           ['help', 'version', 'usage'])
366   except O.GetoptError, exc:
367     moan(exc)
368     usage(SYS.stderr)
369     SYS.exit(1)
370   for o, v in opts:
371     if o in ('-h', '--help'):
372       cmd_help([])
373       SYS.exit(0)
374     elif o in ('-v', '--version'):
375       version(SYS.stdout)
376       SYS.exit(0)
377     elif o in ('-u', '--usage'):
378       usage(SYS.stdout)
379       SYS.exit(0)
380   if len(argv) < 2:
381     cmd_help([])
382   else:
383     c = argv[1]
384     func, min, max, help = commands[c]
385     args = argv[2:]
386     if len(args) < min or (max > 0 and len(args) > max):
387       raise UsageError, (c, help)
388     func(args)
389
390 init()
391 main(SYS.argv)