#!/usr/bin/env python import os, sys import MySQLdb import tempfile import stat from optparse import OptionParser from deter import fedid class opt_parser(OptionParser): def __init__(self): OptionParser.__init__(self, usage="%prog [opts] (--help for details)", version="0.1") self.add_option('-u', '--user', dest='users', action='append', default=[], help="Users to extract from DB") self.add_option('-p', '--project', dest='projects', action='append', default=[], help="Projects to extract from DB") self.add_option('-d', '--cert-dir', dest='cert_dir', default=None, help='Directory to store copies of certificates') def cert_to_fid(cstr): fd, path = tempfile.mkstemp('.pem') try: try: f = os.fdopen(fd, "w") print >>f, cstr f.close() except IOError, e: print >>sys.stderr, "Error creating user %s" % u return fedid(file=path) finally: os.remove(path) def add_list(l, field): str = "" for x in l: if str: str += " OR " else: str = " AND (" str += "%s='%s'" % (field, x) if str: str += ")" return str fids = { } q_start = """ SELECT g.uid, CASE g.gid WHEN g.pid THEN g.pid ELSE CONCAT(g.pid, '/', g.gid) END, CONCAT('-----BEGIN PRIVATE KEY-----\\n', s.privkey, '-----END PRIVATE KEY-----\\n', '-----BEGIN CERTIFICATE-----\\n', s.cert, '-----END CERTIFICATE-----\\n'), encrypted FROM group_membership g INNER JOIN user_sslcerts s ON g.uid = s.uid WHERE revoked is NULL AND encrypted = 0 """ q_end =""" ORDER BY s.uid """ opts, args = opt_parser().parse_args() if opts.cert_dir: if not os.path.isdir(opts.cert_dir): sys.exit('Not a directory: %s' % opts.cert_dir) elif not os.access(opts.cert_dir, os.W_OK): sys.exit('Cannot write %s' % opts.cert_dir) else: os.chmod(opts.cert_dir, stat.S_IRWXU) user_clause= add_list(opts.users, 'g.uid') project_clause= add_list(opts.projects, 'g.pid') query = q_start + user_clause + project_clause + q_end db = MySQLdb.connect(db='tbdb') c = db.cursor() c.execute(query) for u, p, c, e in c.fetchall(): fid = fids.get(c, None) if not fid: fid = cert_to_fid(c) fids[c] = fid if opts.cert_dir: cf =os.path.join(opts.cert_dir, '%s.pem' % u) if not os.access(cf, os.F_OK) or os.access(cf, os.W_OK): try: f = open(cf, 'w') f.write(c) f.close() os.chmod(cf, stat.S_IREAD) except EnvironmentError, e: print >>sys.stderr, 'Cannot write %s: %s' % \ (e.filename, e.strerror)