chiark / gitweb /
cleanup: Whitespaces fixes, left right and centre.
[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'),
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
169def version(fp = SYS.stdout):
170 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
171
172def usage(fp):
173 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
174
175def cmd_help(args):
176 if len(args) == 0:
177 version(SYS.stdout)
178 print
179 usage(SYS.stdout)
180 print """
181Key management utility for TrIPE.
182
183Options supported:
184
e04c2d50
MW
185-h, --help Show this help message.
186-v, --version Show the version number.
187-u, --usage Show pointlessly short usage string.
060ca767 188
189Subcommands 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
c77687d5 197def 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
206def master_sequence(k):
207 return int(k.tag[7:])
208def 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
214def seqsubst(x, q):
215 return rx_seq.sub(str(q), conf[x])
216
217def cmd_newmaster(args):
218 seq = max_master_sequence() + 1
060ca767 219 run('''key -kmaster add
220 -a${sig-genalg} !${sig-param}
c77687d5 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')
060ca767 224
c77687d5 225def cmd_setup(args):
226 OS.mkdir('repos')
060ca767 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}''')
c77687d5 231 cmd_newmaster(args)
060ca767 232
233def 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)
c77687d5 240 if (f.startswith('master') or f.startswith('peer-')) \
241 and f.endswith('.old'):
060ca767 242 OS.unlink(ff)
243 continue
c77687d5 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)
e04c2d50 282 rmtree('tmp')
060ca767 283
284def 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')
c77687d5 292 seq = int(conf['master-sequence'])
162fcf48
MW
293 run('curl -s -o tripe-keys.tar.gz ${repos-url}')
294 run('curl -s -o tripe-keys.sig %s' % seqsubst('sig-url', seq))
060ca767 295 run('tar xfz tripe-keys.tar.gz')
296
297 ## Verify the signature
c77687d5 298 want = C.bytes(rx_nonalpha.sub('', conf['hk-master']))
299 got = fingerprint('repos/master.pub', 'master-%d' % seq)
060ca767 300 if want != got: raise VerifyError
c77687d5 301 run('''catsign -krepos/master.pub verify -avC -kmaster-%d
302 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''' % seq)
060ca767 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')
c77687d5 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')
060ca767 311 rmtree('repos.old')
312
313 finally:
314 OS.chdir(cwd)
315 rmtree('tmp')
316 cmd_rebuild(args)
317
318def 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
324def 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}' %
c77687d5 330 tag)
ca6eb20c 331 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
060ca767 332
333def cmd_clean(args):
334 rmtree('repos')
335 rmtree('tmp')
c77687d5 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)
060ca767 342
343### Main driver
344
345class UsageError (Exception): pass
e04c2d50 346
060ca767 347commands = {'help': (cmd_help, 0, 1, ''),
c77687d5 348 'newmaster': (cmd_newmaster, 0, 0, ''),
060ca767 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
356def 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()
362def 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
390init()
391main(SYS.argv)