Skip to content

Instantly share code, notes, and snippets.

@zoni
Last active December 30, 2015 14:09
Show Gist options
  • Save zoni/7840162 to your computer and use it in GitHub Desktop.
Save zoni/7840162 to your computer and use it in GitHub Desktop.
Invoke script to ease dealing with (StartSSL) TLS certificate generation.
Certificates may be created with the help of invoke. This is geared towards
use of StartSSL certificates, but does not enforce this (--no-startssl).
See `invoke --help` for general help on invoke, including useage of how
to list all tasks and their corresponding help and option flags.
To create a new key:
invoke createkey foo.domain.tld.key
And create a CSR for it:
invoke createcsr foo.domain.tld.key
To install the certificate once obtained from StartSSL (this wil copy
the cert to current dir if it was located elsewhere, concatenate the
certificate itself, StartSSL intermediate certificate and StartSSL root
certificate together to form a correct certificate chain, and create
a version of this with the private key embedded, as well):
invoke install foo.domain.tld.crt
import sys
from invoke import task, run
def strip_extension(filename):
"""Return filename with extension removed"""
if not "." in filename:
return filename
else:
return ".".join(filename.rsplit(".")[:-1])
@task
def createkey(name, size="4096"):
"""Create a new RSA key"""
if not name.endswith(".key"):
name += ".key"
run("openssl genrsa -out {name} {size}".format(**locals()))
@task
def createcsr(key):
"""Create a certificate signing request for the given key"""
out = "{}.csr".format(strip_extension(key))
run("openssl req -new -key {key} -out {out}".format(**locals()))
@task
def install(certificate, startssl=True):
"""Install the signed certificate (including chained versions)"""
if not (certificate.endswith(".pem") or certificate.endswith(".crt")):
sys.stderr.write("This doesn't look like a certificate (not ending in .pem or .crt), aborting!\n")
sys.exit(1)
basename = strip_extension(certificate)
crt = "{}.crt".format(basename)
key = "{}.key".format(basename)
if crt != certificate:
run("cp {certificate} {crt}".format(**locals()))
run("cat {key} {crt} > {basename}.withkey.crt".format(**locals()))
if startssl:
run("cat {crt} startssl/{{sub.class1.server.ca.pem,ca.pem}} > {basename}.chained.crt".format(**locals()), pty=True)
run("cat {key} {crt} startssl/{{sub.class1.server.ca.pem,ca.pem}} > {basename}.chained.withkey.crt".format(**locals()), pty=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment