2014-08-16 13:53:07 +00:00
|
|
|
from __future__ import (absolute_import, print_function, division)
|
2013-10-07 20:55:35 +00:00
|
|
|
import os, ssl, time, datetime
|
2014-07-18 20:55:25 +00:00
|
|
|
import itertools
|
2012-06-27 04:42:00 +00:00
|
|
|
from pyasn1.type import univ, constraint, char, namedtype, tag
|
|
|
|
from pyasn1.codec.der.decoder import decode
|
2012-07-24 02:55:54 +00:00
|
|
|
from pyasn1.error import PyAsn1Error
|
2012-06-27 04:42:00 +00:00
|
|
|
import OpenSSL
|
|
|
|
|
2014-03-04 01:12:58 +00:00
|
|
|
DEFAULT_EXP = 62208000 # =24 * 60 * 60 * 720
|
|
|
|
# Generated with "openssl dhparam". It's too slow to generate this on startup.
|
|
|
|
DEFAULT_DHPARAM = """-----BEGIN DH PARAMETERS-----
|
|
|
|
MIGHAoGBAOdPzMbYgoYfO3YBYauCLRlE8X1XypTiAjoeCFD0qWRx8YUsZ6Sj20W5
|
|
|
|
zsfQxlZfKovo3f2MftjkDkbI/C/tDgxoe0ZPbjy5CjdOhkzxn0oTbKTs16Rw8DyK
|
|
|
|
1LjTR65sQJkJEdgsX8TSi/cicCftJZl9CaZEaObF2bdgSgGK+PezAgEC
|
|
|
|
-----END DH PARAMETERS-----"""
|
|
|
|
|
|
|
|
def create_ca(o, cn, exp):
|
2012-06-27 04:42:00 +00:00
|
|
|
key = OpenSSL.crypto.PKey()
|
|
|
|
key.generate_key(OpenSSL.crypto.TYPE_RSA, 1024)
|
2014-03-04 01:12:58 +00:00
|
|
|
cert = OpenSSL.crypto.X509()
|
|
|
|
cert.set_serial_number(int(time.time()*10000))
|
|
|
|
cert.set_version(2)
|
|
|
|
cert.get_subject().CN = cn
|
|
|
|
cert.get_subject().O = o
|
2014-04-25 17:40:37 +00:00
|
|
|
cert.gmtime_adj_notBefore(-3600*48)
|
2014-03-04 01:12:58 +00:00
|
|
|
cert.gmtime_adj_notAfter(exp)
|
|
|
|
cert.set_issuer(cert.get_subject())
|
|
|
|
cert.set_pubkey(key)
|
|
|
|
cert.add_extensions([
|
2012-06-27 04:42:00 +00:00
|
|
|
OpenSSL.crypto.X509Extension("basicConstraints", True,
|
|
|
|
"CA:TRUE"),
|
2014-06-29 11:10:07 +00:00
|
|
|
OpenSSL.crypto.X509Extension("nsCertType", False,
|
2012-06-27 04:42:00 +00:00
|
|
|
"sslCA"),
|
|
|
|
OpenSSL.crypto.X509Extension("extendedKeyUsage", True,
|
|
|
|
"serverAuth,clientAuth,emailProtection,timeStamping,msCodeInd,msCodeCom,msCTLSign,msSGC,msEFS,nsSGC"
|
|
|
|
),
|
|
|
|
OpenSSL.crypto.X509Extension("keyUsage", False,
|
|
|
|
"keyCertSign, cRLSign"),
|
|
|
|
OpenSSL.crypto.X509Extension("subjectKeyIdentifier", False, "hash",
|
2014-03-04 01:12:58 +00:00
|
|
|
subject=cert),
|
2012-06-27 04:42:00 +00:00
|
|
|
])
|
2014-03-04 01:12:58 +00:00
|
|
|
cert.sign(key, "sha1")
|
|
|
|
return key, cert
|
|
|
|
|
|
|
|
|
2014-03-05 00:19:16 +00:00
|
|
|
def dummy_cert(privkey, cacert, commonname, sans):
|
2012-06-27 04:42:00 +00:00
|
|
|
"""
|
2014-03-04 01:12:58 +00:00
|
|
|
Generates a dummy certificate.
|
2013-01-05 12:15:53 +00:00
|
|
|
|
2014-03-05 00:19:16 +00:00
|
|
|
privkey: CA private key
|
2014-03-04 01:12:58 +00:00
|
|
|
cacert: CA certificate
|
2012-06-27 04:42:00 +00:00
|
|
|
commonname: Common name for the generated certificate.
|
2013-01-05 12:15:53 +00:00
|
|
|
sans: A list of Subject Alternate Names.
|
2012-06-27 04:42:00 +00:00
|
|
|
|
2014-03-04 01:12:58 +00:00
|
|
|
Returns cert if operation succeeded, None if not.
|
2012-06-27 04:42:00 +00:00
|
|
|
"""
|
|
|
|
ss = []
|
|
|
|
for i in sans:
|
|
|
|
ss.append("DNS: %s"%i)
|
|
|
|
ss = ", ".join(ss)
|
|
|
|
|
|
|
|
cert = OpenSSL.crypto.X509()
|
2014-01-08 01:46:55 +00:00
|
|
|
cert.gmtime_adj_notBefore(-3600*48)
|
2012-06-27 04:42:00 +00:00
|
|
|
cert.gmtime_adj_notAfter(60 * 60 * 24 * 30)
|
2014-03-04 01:12:58 +00:00
|
|
|
cert.set_issuer(cacert.get_subject())
|
2013-09-24 19:18:41 +00:00
|
|
|
cert.get_subject().CN = commonname
|
2012-06-27 04:42:00 +00:00
|
|
|
cert.set_serial_number(int(time.time()*10000))
|
|
|
|
if ss:
|
2013-04-19 13:37:14 +00:00
|
|
|
cert.set_version(2)
|
2012-06-27 04:42:00 +00:00
|
|
|
cert.add_extensions([OpenSSL.crypto.X509Extension("subjectAltName", True, ss)])
|
2014-03-04 01:12:58 +00:00
|
|
|
cert.set_pubkey(cacert.get_pubkey())
|
2014-03-05 00:19:16 +00:00
|
|
|
cert.sign(privkey, "sha1")
|
2013-08-12 04:03:29 +00:00
|
|
|
return SSLCert(cert)
|
2012-06-27 04:42:00 +00:00
|
|
|
|
2013-01-05 12:15:53 +00:00
|
|
|
|
2014-07-18 20:55:25 +00:00
|
|
|
# DNTree did not pass TestCertStore.test_sans_change and is temporarily replaced by a simple dict.
|
|
|
|
#
|
|
|
|
# class _Node(UserDict.UserDict):
|
|
|
|
# def __init__(self):
|
|
|
|
# UserDict.UserDict.__init__(self)
|
|
|
|
# self.value = None
|
|
|
|
#
|
|
|
|
#
|
|
|
|
# class DNTree:
|
|
|
|
# """
|
|
|
|
# Domain store that knows about wildcards. DNS wildcards are very
|
|
|
|
# restricted - the only valid variety is an asterisk on the left-most
|
|
|
|
# domain component, i.e.:
|
|
|
|
#
|
|
|
|
# *.foo.com
|
|
|
|
# """
|
|
|
|
# def __init__(self):
|
|
|
|
# self.d = _Node()
|
|
|
|
#
|
|
|
|
# def add(self, dn, cert):
|
|
|
|
# parts = dn.split(".")
|
|
|
|
# parts.reverse()
|
|
|
|
# current = self.d
|
|
|
|
# for i in parts:
|
|
|
|
# current = current.setdefault(i, _Node())
|
|
|
|
# current.value = cert
|
|
|
|
#
|
|
|
|
# def get(self, dn):
|
|
|
|
# parts = dn.split(".")
|
|
|
|
# current = self.d
|
|
|
|
# for i in reversed(parts):
|
|
|
|
# if i in current:
|
|
|
|
# current = current[i]
|
|
|
|
# elif "*" in current:
|
|
|
|
# return current["*"].value
|
|
|
|
# else:
|
|
|
|
# return None
|
|
|
|
# return current.value
|
2014-03-05 00:19:16 +00:00
|
|
|
|
|
|
|
|
2014-03-10 04:29:27 +00:00
|
|
|
|
2013-01-05 12:15:53 +00:00
|
|
|
class CertStore:
|
|
|
|
"""
|
2013-08-12 04:03:29 +00:00
|
|
|
Implements an in-memory certificate store.
|
2013-01-05 12:15:53 +00:00
|
|
|
"""
|
2014-03-07 03:38:50 +00:00
|
|
|
def __init__(self, privkey, cacert, dhparams=None):
|
2014-03-05 00:19:16 +00:00
|
|
|
self.privkey, self.cacert = privkey, cacert
|
2014-03-07 03:38:50 +00:00
|
|
|
self.dhparams = dhparams
|
2014-07-18 20:55:25 +00:00
|
|
|
self.certs = dict()
|
2014-03-04 01:12:58 +00:00
|
|
|
|
2014-03-07 03:38:50 +00:00
|
|
|
@classmethod
|
|
|
|
def load_dhparam(klass, path):
|
2014-03-11 19:23:27 +00:00
|
|
|
|
|
|
|
# netlib<=0.10 doesn't generate a dhparam file.
|
|
|
|
# Create it now if neccessary.
|
|
|
|
if not os.path.exists(path):
|
|
|
|
with open(path, "wb") as f:
|
|
|
|
f.write(DEFAULT_DHPARAM)
|
|
|
|
|
2014-03-07 03:38:50 +00:00
|
|
|
bio = OpenSSL.SSL._lib.BIO_new_file(path, b"r")
|
|
|
|
if bio != OpenSSL.SSL._ffi.NULL:
|
|
|
|
bio = OpenSSL.SSL._ffi.gc(bio, OpenSSL.SSL._lib.BIO_free)
|
|
|
|
dh = OpenSSL.SSL._lib.PEM_read_bio_DHparams(
|
|
|
|
bio, OpenSSL.SSL._ffi.NULL, OpenSSL.SSL._ffi.NULL, OpenSSL.SSL._ffi.NULL
|
|
|
|
)
|
|
|
|
dh = OpenSSL.SSL._ffi.gc(dh, OpenSSL.SSL._lib.DH_free)
|
|
|
|
return dh
|
|
|
|
|
2014-03-04 01:12:58 +00:00
|
|
|
@classmethod
|
|
|
|
def from_store(klass, path, basename):
|
|
|
|
p = os.path.join(path, basename + "-ca.pem")
|
|
|
|
if not os.path.exists(p):
|
|
|
|
key, ca = klass.create_store(path, basename)
|
|
|
|
else:
|
|
|
|
p = os.path.join(path, basename + "-ca.pem")
|
|
|
|
raw = file(p, "rb").read()
|
|
|
|
ca = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, raw)
|
|
|
|
key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, raw)
|
2014-03-07 03:38:50 +00:00
|
|
|
dhp = os.path.join(path, basename + "-dhparam.pem")
|
|
|
|
dh = klass.load_dhparam(dhp)
|
|
|
|
return klass(key, ca, dh)
|
2014-03-04 01:12:58 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def create_store(klass, path, basename, o=None, cn=None, expiry=DEFAULT_EXP):
|
|
|
|
if not os.path.exists(path):
|
|
|
|
os.makedirs(path)
|
|
|
|
|
|
|
|
o = o or basename
|
|
|
|
cn = cn or basename
|
|
|
|
|
|
|
|
key, ca = create_ca(o=o, cn=cn, exp=expiry)
|
|
|
|
# Dump the CA plus private key
|
|
|
|
f = open(os.path.join(path, basename + "-ca.pem"), "wb")
|
|
|
|
f.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
|
|
|
|
f.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca))
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
# Dump the certificate in PEM format
|
2014-03-07 03:38:50 +00:00
|
|
|
f = open(os.path.join(path, basename + "-ca-cert.pem"), "wb")
|
2014-03-04 01:12:58 +00:00
|
|
|
f.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca))
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
# Create a .cer file with the same contents for Android
|
2014-03-07 03:38:50 +00:00
|
|
|
f = open(os.path.join(path, basename + "-ca-cert.cer"), "wb")
|
2014-03-04 01:12:58 +00:00
|
|
|
f.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca))
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
# Dump the certificate in PKCS12 format for Windows devices
|
2014-03-07 03:38:50 +00:00
|
|
|
f = open(os.path.join(path, basename + "-ca-cert.p12"), "wb")
|
2014-03-04 01:12:58 +00:00
|
|
|
p12 = OpenSSL.crypto.PKCS12()
|
|
|
|
p12.set_certificate(ca)
|
|
|
|
p12.set_privatekey(key)
|
|
|
|
f.write(p12.export())
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
f = open(os.path.join(path, basename + "-dhparam.pem"), "wb")
|
|
|
|
f.write(DEFAULT_DHPARAM)
|
|
|
|
f.close()
|
|
|
|
return key, ca
|
2013-01-05 12:15:53 +00:00
|
|
|
|
2014-03-05 04:29:14 +00:00
|
|
|
def add_cert_file(self, spec, path):
|
2014-03-05 00:19:16 +00:00
|
|
|
raw = file(path, "rb").read()
|
|
|
|
cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, raw)
|
|
|
|
try:
|
|
|
|
privkey = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, raw)
|
|
|
|
except Exception:
|
|
|
|
privkey = None
|
2014-03-05 04:29:14 +00:00
|
|
|
self.add_cert(SSLCert(cert), privkey, spec)
|
2014-03-05 00:19:16 +00:00
|
|
|
|
|
|
|
def add_cert(self, cert, privkey, *names):
|
|
|
|
"""
|
|
|
|
Adds a cert to the certstore. We register the CN in the cert plus
|
|
|
|
any SANs, and also the list of names provided as an argument.
|
|
|
|
"""
|
2014-03-05 04:29:14 +00:00
|
|
|
if cert.cn:
|
2014-07-18 20:55:25 +00:00
|
|
|
self.certs[cert.cn] = (cert, privkey)
|
2014-03-05 00:19:16 +00:00
|
|
|
for i in cert.altnames:
|
2014-07-18 20:55:25 +00:00
|
|
|
self.certs[i] = (cert, privkey)
|
2014-03-05 00:19:16 +00:00
|
|
|
for i in names:
|
2014-07-18 20:55:25 +00:00
|
|
|
self.certs[i] = (cert, privkey)
|
2014-03-05 00:19:16 +00:00
|
|
|
|
2014-07-18 22:02:31 +00:00
|
|
|
@staticmethod
|
|
|
|
def asterisk_forms(dn):
|
|
|
|
parts = dn.split(".")
|
|
|
|
parts.reverse()
|
|
|
|
curr_dn = ""
|
|
|
|
dn_forms = ["*"]
|
|
|
|
for part in parts[:-1]:
|
|
|
|
curr_dn = "." + part + curr_dn # .example.com
|
|
|
|
dn_forms.append("*" + curr_dn) # *.example.com
|
|
|
|
if parts[-1] != "*":
|
|
|
|
dn_forms.append(parts[-1] + curr_dn)
|
|
|
|
return dn_forms
|
|
|
|
|
2014-03-02 00:50:19 +00:00
|
|
|
def get_cert(self, commonname, sans):
|
2013-01-05 12:15:53 +00:00
|
|
|
"""
|
2014-03-05 00:19:16 +00:00
|
|
|
Returns an (cert, privkey) tuple.
|
2013-01-05 12:15:53 +00:00
|
|
|
|
|
|
|
commonname: Common name for the generated certificate. Must be a
|
|
|
|
valid, plain-ASCII, IDNA-encoded domain name.
|
|
|
|
|
|
|
|
sans: A list of Subject Alternate Names.
|
|
|
|
|
2013-01-05 12:34:39 +00:00
|
|
|
Return None if the certificate could not be found or generated.
|
2013-01-05 12:15:53 +00:00
|
|
|
"""
|
2014-07-18 20:55:25 +00:00
|
|
|
|
2014-07-18 22:02:31 +00:00
|
|
|
potential_keys = self.asterisk_forms(commonname)
|
|
|
|
for s in sans:
|
|
|
|
potential_keys.extend(self.asterisk_forms(s))
|
|
|
|
potential_keys.append((commonname, tuple(sans)))
|
|
|
|
|
2014-07-18 20:55:25 +00:00
|
|
|
name = next(itertools.ifilter(lambda key: key in self.certs, potential_keys), None)
|
|
|
|
if name:
|
|
|
|
c = self.certs[name]
|
|
|
|
else:
|
|
|
|
c = dummy_cert(self.privkey, self.cacert, commonname, sans), None
|
|
|
|
self.certs[(commonname, tuple(sans))] = c
|
|
|
|
|
|
|
|
return c[0], (c[1] or self.privkey)
|
2012-06-27 04:42:00 +00:00
|
|
|
|
2014-03-10 04:29:27 +00:00
|
|
|
def gen_pkey(self, cert):
|
2014-08-16 13:53:07 +00:00
|
|
|
from . import certffi
|
2014-03-10 04:29:27 +00:00
|
|
|
certffi.set_flags(self.privkey, 1)
|
|
|
|
return self.privkey
|
|
|
|
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
class _GeneralName(univ.Choice):
|
|
|
|
# We are only interested in dNSNames. We use a default handler to ignore
|
|
|
|
# other types.
|
|
|
|
componentType = namedtype.NamedTypes(
|
|
|
|
namedtype.NamedType('dNSName', char.IA5String().subtype(
|
|
|
|
implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2)
|
|
|
|
)
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class _GeneralNames(univ.SequenceOf):
|
|
|
|
componentType = _GeneralName()
|
|
|
|
sizeSpec = univ.SequenceOf.sizeSpec + constraint.ValueSizeConstraint(1, 1024)
|
|
|
|
|
|
|
|
|
2014-01-31 00:06:53 +00:00
|
|
|
class SSLCert:
|
2012-06-27 10:11:58 +00:00
|
|
|
def __init__(self, cert):
|
2012-06-27 04:42:00 +00:00
|
|
|
"""
|
|
|
|
Returns a (common name, [subject alternative names]) tuple.
|
|
|
|
"""
|
2012-06-27 10:11:58 +00:00
|
|
|
self.x509 = cert
|
|
|
|
|
2014-03-05 00:19:16 +00:00
|
|
|
def __eq__(self, other):
|
|
|
|
return self.digest("sha1") == other.digest("sha1")
|
|
|
|
|
2012-06-27 10:11:58 +00:00
|
|
|
@classmethod
|
|
|
|
def from_pem(klass, txt):
|
|
|
|
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, txt)
|
|
|
|
return klass(x509)
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_der(klass, der):
|
|
|
|
pem = ssl.DER_cert_to_PEM_cert(der)
|
2012-06-27 10:11:58 +00:00
|
|
|
return klass.from_pem(pem)
|
2012-06-27 04:42:00 +00:00
|
|
|
|
2012-06-28 02:56:21 +00:00
|
|
|
def to_pem(self):
|
|
|
|
return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, self.x509)
|
|
|
|
|
2012-06-27 04:42:00 +00:00
|
|
|
def digest(self, name):
|
2012-06-27 10:11:58 +00:00
|
|
|
return self.x509.digest(name)
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def issuer(self):
|
2012-06-27 10:11:58 +00:00
|
|
|
return self.x509.get_issuer().get_components()
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def notbefore(self):
|
2012-06-27 10:11:58 +00:00
|
|
|
t = self.x509.get_notBefore()
|
2012-06-27 04:42:00 +00:00
|
|
|
return datetime.datetime.strptime(t, "%Y%m%d%H%M%SZ")
|
|
|
|
|
|
|
|
@property
|
|
|
|
def notafter(self):
|
2012-06-27 10:11:58 +00:00
|
|
|
t = self.x509.get_notAfter()
|
2012-06-27 04:42:00 +00:00
|
|
|
return datetime.datetime.strptime(t, "%Y%m%d%H%M%SZ")
|
|
|
|
|
|
|
|
@property
|
|
|
|
def has_expired(self):
|
2012-06-27 10:11:58 +00:00
|
|
|
return self.x509.has_expired()
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def subject(self):
|
2012-06-27 10:11:58 +00:00
|
|
|
return self.x509.get_subject().get_components()
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def serial(self):
|
2012-06-27 10:11:58 +00:00
|
|
|
return self.x509.get_serial_number()
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def keyinfo(self):
|
2012-06-27 10:11:58 +00:00
|
|
|
pk = self.x509.get_pubkey()
|
2012-06-27 04:42:00 +00:00
|
|
|
types = {
|
|
|
|
OpenSSL.crypto.TYPE_RSA: "RSA",
|
|
|
|
OpenSSL.crypto.TYPE_DSA: "DSA",
|
|
|
|
}
|
|
|
|
return (
|
|
|
|
types.get(pk.type(), "UNKNOWN"),
|
|
|
|
pk.bits()
|
|
|
|
)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def cn(self):
|
2013-01-20 09:13:38 +00:00
|
|
|
c = None
|
2012-06-27 04:42:00 +00:00
|
|
|
for i in self.subject:
|
|
|
|
if i[0] == "CN":
|
2013-01-20 09:13:38 +00:00
|
|
|
c = i[1]
|
|
|
|
return c
|
2012-06-27 04:42:00 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def altnames(self):
|
|
|
|
altnames = []
|
2012-06-27 10:11:58 +00:00
|
|
|
for i in range(self.x509.get_extension_count()):
|
|
|
|
ext = self.x509.get_extension(i)
|
2012-06-27 04:42:00 +00:00
|
|
|
if ext.get_short_name() == "subjectAltName":
|
2012-07-24 02:55:54 +00:00
|
|
|
try:
|
|
|
|
dec = decode(ext.get_data(), asn1Spec=_GeneralNames())
|
|
|
|
except PyAsn1Error:
|
|
|
|
continue
|
2012-06-27 04:42:00 +00:00
|
|
|
for i in dec[0]:
|
|
|
|
altnames.append(i[0].asOctets())
|
2014-08-16 13:53:07 +00:00
|
|
|
return altnames
|