[c573278] | 1 | #!/usr/local/bin/python |
---|
| 2 | |
---|
| 3 | import sys, os |
---|
| 4 | import subprocess, tempfile |
---|
| 5 | |
---|
| 6 | from string import join |
---|
| 7 | from optparse import OptionParser |
---|
| 8 | from federation.util import abac_pem_type, abac_split_cert |
---|
| 9 | |
---|
| 10 | class Parser(OptionParser): |
---|
| 11 | def __init__(self): |
---|
| 12 | OptionParser.__init__(self, usage='%prog [options]') |
---|
| 13 | self.add_option('--out', dest='out', help='destination file', |
---|
| 14 | default='./cert.pem') |
---|
| 15 | self.add_option('--debug', dest='debug', action='store_true', |
---|
| 16 | default=False, help='Just print command') |
---|
| 17 | self.add_option('--openssl', dest='openssl', |
---|
| 18 | help='Path to openssl command', default='/usr/bin/openssl') |
---|
| 19 | |
---|
| 20 | parser = Parser() |
---|
| 21 | opts, args = parser.parse_args() |
---|
| 22 | delete_key = False |
---|
| 23 | |
---|
| 24 | if args: |
---|
| 25 | key = args[0] |
---|
| 26 | |
---|
| 27 | ktype = abac_pem_type(key) |
---|
| 28 | if ktype == 'both': |
---|
| 29 | key, cert = abac_split_cert(key) |
---|
| 30 | os.unlink(cert) |
---|
| 31 | delete_key = True |
---|
| 32 | elif ktype != 'key': |
---|
| 33 | sys.exit('Cannot use %s as identity. It is a %s ' % ktype + |
---|
| 34 | 'and we were expecting a key') |
---|
| 35 | |
---|
| 36 | |
---|
| 37 | try: |
---|
| 38 | tf, tn = tempfile.mkstemp(suffix=".pem") |
---|
| 39 | cmd = [opts.openssl, 'req', '-new', '-nodes', '-subj', |
---|
| 40 | '/CN=users.isi.deterlab.net', '-x509', '-days', '3650', |
---|
| 41 | '-key', key, '-out', tn] |
---|
| 42 | if opts.debug: |
---|
| 43 | print join(cmd) |
---|
| 44 | sys.exit(0) |
---|
| 45 | else: |
---|
| 46 | rv = subprocess.call(cmd) |
---|
| 47 | if rv == 0: |
---|
| 48 | try: |
---|
| 49 | of = os.fdopen(os.open(opts.out, |
---|
| 50 | os.O_WRONLY | os.O_CREAT, 0600), 'w') |
---|
| 51 | for inf in (tn, key): |
---|
| 52 | f = open(inf, 'r') |
---|
| 53 | for line in f: |
---|
| 54 | print >>of, line, |
---|
| 55 | f.close() |
---|
| 56 | of.close() |
---|
| 57 | except EnvironmentError, e: |
---|
| 58 | sys.exit("Cannot open %s: %s" % (efilename, e.strerror)) |
---|
| 59 | else: |
---|
| 60 | sys.exit("%s failed: %d" % (opts.openssl, rv)) |
---|
| 61 | finally: |
---|
| 62 | if delete_key and key: os.unlink(key) |
---|