ca_tool.py 1.99 KB
Newer Older
1 2 3 4 5 6 7 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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
import optparse
import logging
import sys
from OpenSSL import crypto
from autoca import ca_stub


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


def parse_subject(subjstr):
    return dict(x.split('=', 1) for x in subjstr.split(','))


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')
    opts, args = parser.parse_args()
    if len(args) < 1:
        parser.error('No command specified')
    if not opts.url:
        parser.error('Must specify --url')

    ca = ca_stub.CaStub(opts.url)

    cmd, args = args[0], args[1:]
    if cmd == 'get-ca':
        writeout(opts.output, ca.get_ca(parse=False))
    elif cmd == 'get-crl':
        writeout(opts.output, ca.get_crl(parse=False))
    elif cmd == 'sign':
        if not opts.subject:
            parser.error('Must specify --subject')
        subject = parse_subject(opts.subject)
        pkey, cert = ca.sign_certificate(subject['CN'], **subject)
        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()