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