4 ### External dependencies
11 from cStringIO import StringIO
15 ### Useful regular expressions
17 r_comment = RX.compile(r'^\s*(#|$)')
18 r_keyval = RX.compile(r'^\s*([-\w]+)(?:\s+(?!=)|\s*=\s*)(|\S|\S.*\S)\s*$')
19 r_dollarsubst = RX.compile(r'\$\{([-\w]+)\}')
20 r_atsubst = RX.compile(r'@([-\w]+)@')
21 r_nonalpha = RX.compile(r'\W')
25 class SubprocessError (Exception): pass
26 class VerifyError (Exception): pass
28 quis = OS.path.basename(SYS.argv[0])
33 SYS.stderr.write('%s: %s\n' % (quis, msg))
39 def subst(s, rx, map):
42 for m in rx.finditer(s):
43 out.write(s[i:m.start()] + map[m.group(1)])
52 if err.errno == ENOENT:
55 if not S_ISDIR(st.st_mode):
61 for i in OS.listdir('.'):
71 if err.errno == ENOENT: return
75 args = map(conf_subst, args.split())
78 if len(a) > 0 and a[0] != '!':
81 nargs += a[1:].split()
83 print '+ %s' % ' '.join(args)
84 rc = OS.spawnvp(OS.P_WAIT, args[0], args)
86 raise SubprocessError, rc
88 def hexhyphens(bytes):
90 for i in xrange(0, len(bytes)):
91 if i > 0 and i % 4 == 0: out.write('-')
92 out.write('%02x' % ord(bytes[i]))
95 def fingerprint(kf, ktag):
96 h = C.gchashes[conf['fingerprint-hash']]()
97 k = C.KeyFile(kf)[ktag].fingerprint(h, '-secret')
100 ### Read configuration
102 class ConfigFileError (Exception): pass
105 def conf_subst(s): return subst(s, r_dollarsubst, conf)
112 if r_comment.match(line): continue
113 if line[-1] == '\n': line = line[:-1]
114 match = r_keyval.match(line)
116 raise ConfigFileError, "%s:%d: bad line `%s'" % (f, lno, line)
117 k, v = match.groups()
118 conf[k] = conf_subst(v)
122 for k, v in [('sig-url', '${base-url}tripe-keys.sig'),
123 ('repos-url', '${base-url}tripe-keys.tar.gz'),
124 ('sig-file', '${base-dir}tripe-keys.sig'),
125 ('repos-file', '${base-dir}tripe-keys.tar.gz'),
126 ('conf-file', '${base-dir}tripe-keys.conf'),
128 ('kx-param', lambda: {'dh': '-LS -b2048 -B256',
129 'ec': '-Cnist-p256'}[conf['kx']]),
130 ('kx-expire', 'now + 1 year'),
131 ('cipher', 'blowfish-cbc'),
133 ('mgf', '${hash}-mgf'),
134 ('mac', lambda: '%s-hmac/%d' %
136 C.gchashes[conf['hash']].hashsz * 4)),
137 ('sig', lambda: {'dh': 'dsa', 'ec': 'ecdsa'}[conf['kx']]),
138 ('sig-fresh', 'always'),
139 ('sig-genalg', lambda: {'kcdsa': 'dh',
144 'eckcdsa': 'ec'}[conf['sig']]),
145 ('sig-param', lambda: {'dh': '-LS -b2048 -B256',
146 'dsa': '-b2048 -B256',
148 'rsa': '-b2048'}[conf['sig-genalg']]),
149 ('sig-hash', '${hash}'),
150 ('sig-expire', 'forever'),
151 ('fingerprint-hash', '${hash}')]:
153 if k in conf: continue
155 conf[k] = conf_subst(v)
158 except KeyError, exc:
159 if len(exc.args) == 0: raise
160 conf[k] = '<missing-var %s>' % exc.args[0]
164 def version(fp = SYS.stdout):
165 fp.write('%s, %s version %s\n' % (quis, PACKAGE, VERSION))
168 fp.write('Usage: %s SUBCOMMAND [ARGS...]\n' % quis)
176 Key management utility for TrIPE.
180 -h, --help Show this help message.
181 -v, --version Show the version number.
182 -u, --usage Show pointlessly short usage string.
184 Subcommands available:
186 args = commands.keys()
189 func, min, max, help = commands[c]
190 print '%s %s' % (c, help)
195 ## Generate the master key
196 run('''key -kmaster add
197 -a${sig-genalg} !${sig-param}
198 -e${sig-expire} -l -ttripe-keys-master ccsig
199 sig=${sig} hash=${sig-hash}''')
200 run('key -kmaster extract -f-secret repos/master.pub tripe-keys-master')
202 ## Generate the parameters key
203 run('''key -krepos/param add
204 -a${kx}-param !${kx-param}
205 -eforever -tparam tripe-${kx}-param
206 cipher=${cipher} hash=${hash} mac=${mac} mgf=${mgf}''')
209 print 'Setup OK: master key = %s' % \
210 hexhyphens(fingerprint('repos/master.pub', 'tripe-keys-master'))
212 def cmd_upload(args):
214 ## Sanitize the repository directory
215 umask = OS.umask(0); OS.umask(umask)
217 for f in OS.listdir('repos'):
218 ff = OS.path.join('repos', f)
219 if f.endswith('.old'):
222 OS.chmod(OS.path.join('repos', f), mode)
224 ## Build the configuration file
225 v = {'HK-MASTER': hexhyphens(fingerprint('repos/master.pub',
226 'tripe-keys-master'))}
227 fin = file('tripe-keys.master')
228 fout = file(conf_subst('${conf-file}.new'), 'w')
230 fout.write(subst(line, r_atsubst, v))
231 fin.close(); fout.close()
233 ## Make and sign the repository archive
234 run('tar chozf ${repos-file}.new repos')
235 run('''catsign -kmaster sign -abdC -ktripe-keys-master
236 -o${sig-file}.new ${repos-file}.new''')
238 ## Commit the changes
239 for i in ['conf-file', 'repos-file', 'sig-file']:
241 new = '%s.new' % base
244 def cmd_update(args):
249 ## Fetch a new distribution
252 run('wget -q -O tripe-keys.tar.gz ${repos-url}')
253 run('wget -q -O tripe-keys.sig ${sig-url}')
254 run('tar xfz tripe-keys.tar.gz')
256 ## Verify the signature
257 want = C.bytes(r_nonalpha.sub('', conf['hk-master']))
258 got = fingerprint('repos/master.pub', 'tripe-keys-master')
259 if want != got: raise VerifyError
260 run('''catsign -krepos/master.pub verify -avC -ktripe-keys-master
261 -t${sig-fresh} tripe-keys.sig tripe-keys.tar.gz''')
263 ## OK: update our copy
265 if OS.path.exists('repos'): OS.rename('repos', 'repos.old')
266 OS.rename('tmp/repos', 'repos')
274 def cmd_rebuild(args):
276 for i in OS.listdir('repos'):
277 if i.startswith('peer-') and i.endswith('.pub'):
278 run('key -kkeyring.pub merge %s' % OS.path.join('repos', i))
280 def cmd_generate(args):
282 keyring_pub = 'peer-%s.pub' % tag
283 zap('keyring'); zap(keyring_pub)
284 run('key -kkeyring merge repos/param')
285 run('key -kkeyring add -a${kx} -pparam -e${kx-expire} -t%s tripe-${kx}' %
287 run('key -kkeyring extract -f-secret %s %s' % (keyring_pub, tag))
288 print 'Generated %s key = %s' % \
290 hexhyphens(fingerprint('repos/master.pub', 'tripe-keys-master')))
296 for i in 'master', 'keyring.pub':
302 class UsageError (Exception): pass
304 commands = {'help': (cmd_help, 0, 1, ''),
305 'setup': (cmd_setup, 0, 0, ''),
306 'upload': (cmd_upload, 0, 0, ''),
307 'update': (cmd_update, 0, 0, ''),
308 'clean': (cmd_clean, 0, 0, ''),
309 'generate': (cmd_generate, 1, 1, 'TAG'),
310 'rebuild': (cmd_rebuild, 0, 0, '')}
313 for f in ['tripe-keys.master', 'tripe-keys.conf']:
314 if OS.path.exists(f):
320 opts, args = O.getopt(argv[1:], 'hvu',
321 ['help', 'version', 'usage'])
322 except O.GetoptError, exc:
327 if o in ('-h', '--help'):
330 elif o in ('-v', '--version'):
333 elif o in ('-u', '--usage'):
340 func, min, max, help = commands[c]
342 if len(args) < min or (max > 0 and len(args) > max):
343 raise UsageError, (c, help)