chiark / gitweb /
tripe-keys: Provide upload-hook for more complicated publishing.
[tripe] / keys / tripe-keys.in
CommitLineData
060ca767 1#! @PYTHON@
2# -*-python-*-
3
4### External dependencies
5
6import catacomb as C
7import os as OS
8import sys as SYS
9import sre as RX
10import getopt as O
c77687d5 11import shutil as SH
12import filecmp as FC
060ca767 13from cStringIO import StringIO
14from errno import *
15from stat import *
16
17### Useful regular expressions
18
c77687d5 19rx_comment = RX.compile(r'^\s*(#|$)')
20rx_keyval = RX.compile(r'^\s*([-\w]+)(?:\s+(?!=)|\s*=\s*)(|\S|\S.*\S)\s*$')
21rx_dollarsubst = RX.compile(r'\$\{([-\w]+)\}')
22rx_atsubst = RX.compile(r'@([-\w]+)@')
23rx_nonalpha = RX.compile(r'\W')
24rx_seq = RX.compile(r'\<SEQ\>')
060ca767 25
26### Utility functions
27
28class SubprocessError (Exception): pass
29class VerifyError (Exception): pass
30
31quis = OS.path.basename(SYS.argv[0])
32PACKAGE = "@PACKAGE@"
33VERSION = "@VERSION@"
34
35def moan(msg):
36 SYS.stderr.write('%s: %s\n' % (quis, msg))
37
38def die(msg, rc = 1):
39 moan(msg)
40 SYS.exit(rc)
41
42def 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
51def rmtree(path):
52 try:
c77687d5 53 st = OS.lstat(path)
060ca767 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
70def zap(file):
71 try:
72 OS.unlink(file)
73 except OSError, err:
74 if err.errno == ENOENT: return
75 raise
76
77def 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
91def 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
98def 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
105class ConfigFileError (Exception): pass
106conf = {}
107
c77687d5 108def conf_subst(s): return subst(s, rx_dollarsubst, conf)
060ca767 109
110## Read the file
111def conf_read(f):
112 lno = 0
113 for line in file(f):
114 lno += 1
c77687d5 115 if rx_comment.match(line): continue
060ca767 116 if line[-1] == '\n': line = line[:-1]
c77687d5 117 match = rx_keyval.match(line)
060ca767 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
124def conf_defaults():
c77687d5 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}'),
060ca767 131 ('conf-file', '${base-dir}tripe-keys.conf'),
b14ccd2f 132 ('upload-hook', ': run upload hook'),
060ca767 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
170def version(fp = SYS.stdout):
171 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
172
173def usage(fp):
174 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
175
176def cmd_help(args):
177 if len(args) == 0:
178 version(SYS.stdout)
179 print
180 usage(SYS.stdout)
181 print """
182Key management utility for TrIPE.
183
184Options supported:
185
e04c2d50
MW
186-h, --help Show this help message.
187-v, --version Show the version number.
188-u, --usage Show pointlessly short usage string.
060ca767 189
190Subcommands 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
c77687d5 198def master_keys():
199 if not OS.path.exists('master'):
200 return
b42d45c0 201 for k in C.KeyFile('master').itervalues():
c77687d5 202 if (k.type != 'tripe-keys-master' or
203 k.expiredp or
204 not k.tag.startswith('master-')):
205 continue #??
206 yield k
207def master_sequence(k):
208 return int(k.tag[7:])
209def 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
215def seqsubst(x, q):
216 return rx_seq.sub(str(q), conf[x])
217
218def cmd_newmaster(args):
219 seq = max_master_sequence() + 1
060ca767 220 run('''key -kmaster add
221 -a${sig-genalg} !${sig-param}
c77687d5 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')
060ca767 225
c77687d5 226def cmd_setup(args):
227 OS.mkdir('repos')
060ca767 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}''')
c77687d5 232 cmd_newmaster(args)
060ca767 233
234def 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)
c77687d5 241 if (f.startswith('master') or f.startswith('peer-')) \
242 and f.endswith('.old'):
060ca767 243 OS.unlink(ff)
244 continue
c77687d5 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)
e04c2d50 283 rmtree('tmp')
b14ccd2f 284 run('sh -c ${upload-hook}')
060ca767 285
286def 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')
c77687d5 294 seq = int(conf['master-sequence'])
162fcf48
MW
295 run('curl -s -o tripe-keys.tar.gz ${repos-url}')
296 run('curl -s -o tripe-keys.sig %s' % seqsubst('sig-url', seq))
060ca767 297 run('tar xfz tripe-keys.tar.gz')
298
299 ## Verify the signature
c77687d5 300 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
301 got = fingerprint('repos/master.pub', 'master-%d' % seq)
060ca767 302 if want != got: raise VerifyError
c77687d5 303 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
304 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
060ca767 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')
c77687d5 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')
060ca767 313 rmtree('repos.old')
314
315 finally:
316 OS.chdir(cwd)
317 rmtree('tmp')
318 cmd_rebuild(args)
319
320def 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
326def 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}' %
c77687d5 332 tag)
ca6eb20c 333 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
060ca767 334
335def cmd_clean(args):
336 rmtree('repos')
337 rmtree('tmp')
c77687d5 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)
060ca767 344
345### Main driver
346
347class UsageError (Exception): pass
e04c2d50 348
060ca767 349commands = {'help': (cmd_help, 0, 1, ''),
c77687d5 350 'newmaster': (cmd_newmaster, 0, 0, ''),
060ca767 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
358def 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()
364def 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
392init()
393main(SYS.argv)