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