ca_tool.py 2.29 KB
Newer Older
1
import optparse
2
import os
3
4
5
6
import logging
import sys
from OpenSSL import crypto
from autoca import ca_stub
7
from autoca import certutil
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33


def writeout(output, data):
    if output:
        outfd = open(output, 'w')
    else:
        outfd = sys.stdout
    outfd.write(data)
    if output:
        outfd.close()


def main():
    parser = optparse.OptionParser()
    parser.add_option('--url', dest='url',
                      help='autoca API endpoint')
    parser.add_option('--output', dest='output', metavar='FILE',
                      help='write output to this file')
    parser.add_option('--outkey', dest='outkey', metavar='FILE',
                      help='write private key to this file (only '
                      'useful with the "sign" command)')
    parser.add_option('--server', dest='server', action='store_true',
                      help='create a server certificate (for "sign")')
    parser.add_option('--subject', dest='subject',
                      help='specify the X.509 subject as a set of '
                      'comma-separated ATTR=VALUE assignments')
34
35
    parser.add_option('--secret', dest='secret',
                      help='shared secret for authentication')
36
37
38
39
40
41
    opts, args = parser.parse_args()
    if len(args) < 1:
        parser.error('No command specified')
    if not opts.url:
        parser.error('Must specify --url')

42
43
44
45
46
47
48
    secret = opts.secret
    if not secret:
        if os.getenv('AUTOCA_SECRET'):
            with open(os.getenv('AUTOCA_SECRET'), 'r') as fd:
                secret = fd.read().strip()

    ca = ca_stub.CaStub(opts.url, secret)
49
50
51

    cmd, args = args[0], args[1:]
    if cmd == 'get-ca':
ale's avatar
fixes    
ale committed
52
        writeout(opts.output, ca.get_ca())
53
    elif cmd == 'get-crl':
ale's avatar
fixes    
ale committed
54
        writeout(opts.output, ca.get_crl(format='pem'))
55
56
57
    elif cmd == 'sign':
        if not opts.subject:
            parser.error('Must specify --subject')
58
        subject = certutil.parse_subject(opts.subject)
ale's avatar
fixes    
ale committed
59
        pkey, cert = ca.make_certificate(subject, days=7,
60
                                         server=opts.server)
61
62
63
64
65
66
67
68
69
70
        writeout(opts.output, crypto.dump_certificate(
                crypto.FILETYPE_PEM, cert))
        writeout(opts.outkey, crypto.dump_privatekey(
                crypto.FILETYPE_PEM, pkey))
    else:
        parser.error('Unknown command')


if __name__ == '__main__':
    main()