mitmproxy/netlib/certutils.py

482 lines
14 KiB
Python
Raw Normal View History

import os
import ssl
import time
import datetime
import ipaddress
2015-09-20 16:12:55 +00:00
import sys
2012-06-27 04:42:00 +00:00
from pyasn1.type import univ, constraint, char, namedtype, tag
from pyasn1.codec.der.decoder import decode
from pyasn1.error import PyAsn1Error
2012-06-27 04:42:00 +00:00
import OpenSSL
from mitmproxy.types import serializable
2016-02-08 03:28:49 +00:00
# Default expiry must not be too long: https://github.com/mitmproxy/mitmproxy/issues/815
2016-02-08 03:16:58 +00:00
DEFAULT_EXP = 94608000 # = 24 * 60 * 60 * 365 * 3
2014-03-04 01:12:58 +00:00
# Generated with "openssl dhparam". It's too slow to generate this on startup.
2015-09-18 13:38:31 +00:00
DEFAULT_DHPARAM = b"""
-----BEGIN DH PARAMETERS-----
MIICCAKCAgEAyT6LzpwVFS3gryIo29J5icvgxCnCebcdSe/NHMkD8dKJf8suFCg3
O2+dguLakSVif/t6dhImxInJk230HmfC8q93hdcg/j8rLGJYDKu3ik6H//BAHKIv
j5O9yjU3rXCfmVJQic2Nne39sg3CreAepEts2TvYHhVv3TEAzEqCtOuTjgDv0ntJ
Gwpj+BJBRQGG9NvprX1YGJ7WOFBP/hWU7d6tgvE6Xa7T/u9QIKpYHMIkcN/l3ZFB
chZEqVlyrcngtSXCROTPcDOQ6Q8QzhaBJS+Z6rcsd7X+haiQqvoFcmaJ08Ks6LQC
ZIL2EtYJw8V8z7C0igVEBIADZBI6OTbuuhDwRw//zU1uq52Oc48CIZlGxTYG/Evq
o9EWAXUYVzWkDSTeBH1r4z/qLPE2cnhtMxbFxuvK53jGB0emy2y1Ei6IhKshJ5qX
IB/aE7SSHyQ3MDHHkCmQJCsOd4Mo26YX61NZ+n501XjqpCBQ2+DfZCBh8Va2wDyv
A2Ryg9SUz8j0AXViRNMJgJrr446yro/FuJZwnQcO3WQnXeqSBnURqKjmqkeFP+d8
6mk2tqJaY507lRNqtGlLnj7f5RNoBFJDCLBNurVgfvq9TCVWKDIFD4vZRjCrnl6I
rD693XKIHUCWOjMh1if6omGXKHH40QuME2gNa50+YPn1iYDl88uDbbMCAQI=
-----END DH PARAMETERS-----
"""
2014-03-04 01:12:58 +00:00
2014-03-04 01:12:58 +00:00
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, 2048)
2014-03-04 01:12:58 +00:00
cert = OpenSSL.crypto.X509()
cert.set_serial_number(int(time.time() * 10000))
2014-03-04 01:12:58 +00:00
cert.set_version(2)
cert.get_subject().CN = cn
cert.get_subject().O = o
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([
2015-05-28 00:12:37 +00:00
OpenSSL.crypto.X509Extension(
2015-09-18 13:38:31 +00:00
b"basicConstraints",
2015-05-28 00:12:37 +00:00
True,
2015-09-18 13:38:31 +00:00
b"CA:TRUE"
2015-05-28 00:12:37 +00:00
),
OpenSSL.crypto.X509Extension(
2015-09-18 13:38:31 +00:00
b"nsCertType",
2015-05-28 00:12:37 +00:00
False,
2015-09-18 13:38:31 +00:00
b"sslCA"
2015-05-28 00:12:37 +00:00
),
OpenSSL.crypto.X509Extension(
2015-09-18 13:38:31 +00:00
b"extendedKeyUsage",
2015-05-28 00:12:37 +00:00
False,
2015-09-18 13:38:31 +00:00
b"serverAuth,clientAuth,emailProtection,timeStamping,msCodeInd,msCodeCom,msCTLSign,msSGC,msEFS,nsSGC"
2015-05-28 00:12:37 +00:00
),
OpenSSL.crypto.X509Extension(
2015-09-18 13:38:31 +00:00
b"keyUsage",
2015-05-28 00:12:37 +00:00
True,
2015-09-18 13:38:31 +00:00
b"keyCertSign, cRLSign"
2015-05-28 00:12:37 +00:00
),
OpenSSL.crypto.X509Extension(
2015-09-18 13:38:31 +00:00
b"subjectKeyIdentifier",
2015-05-28 00:12:37 +00:00
False,
2015-09-18 13:38:31 +00:00
b"hash",
2015-05-28 00:12:37 +00:00
subject=cert
),
])
cert.sign(key, "sha256")
2014-03-04 01:12:58 +00:00
return key, cert
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.
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.
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:
try:
ipaddress.ip_address(i.decode("ascii"))
except ValueError:
ss.append(b"DNS: %s" % i)
else:
ss.append(b"IP: %s" % i)
ss = b", ".join(ss)
2012-06-27 04:42:00 +00:00
cert = OpenSSL.crypto.X509()
cert.gmtime_adj_notBefore(-3600 * 48)
2015-02-16 23:10:10 +00:00
cert.gmtime_adj_notAfter(DEFAULT_EXP)
2014-03-04 01:12:58 +00:00
cert.set_issuer(cacert.get_subject())
2016-02-02 17:15:55 +00:00
if commonname is not None:
cert.get_subject().CN = commonname
cert.set_serial_number(int(time.time() * 10000))
2012-06-27 04:42:00 +00:00
if ss:
cert.set_version(2)
2015-05-30 00:02:58 +00:00
cert.add_extensions(
2015-09-18 13:38:31 +00:00
[OpenSSL.crypto.X509Extension(b"subjectAltName", False, ss)])
2014-03-04 01:12:58 +00:00
cert.set_pubkey(cacert.get_pubkey())
cert.sign(privkey, "sha256")
return SSLCert(cert)
2012-06-27 04:42:00 +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
2016-10-17 04:29:45 +00:00
class CertStoreEntry:
2014-10-08 22:15:39 +00:00
def __init__(self, cert, privatekey, chain_file):
2014-10-08 18:46:30 +00:00
self.cert = cert
2014-10-08 22:15:39 +00:00
self.privatekey = privatekey
2014-10-08 18:46:30 +00:00
self.chain_file = chain_file
2014-03-10 04:29:27 +00:00
2016-10-17 04:29:45 +00:00
class CertStore:
"""
Implements an in-memory certificate store.
"""
STORE_CAP = 100
2015-05-28 00:18:56 +00:00
2015-05-30 00:02:58 +00:00
def __init__(
self,
default_privatekey,
default_ca,
default_chain_file,
dhparams):
2014-10-08 22:15:39 +00:00
self.default_privatekey = default_privatekey
2014-10-08 18:46:30 +00:00
self.default_ca = default_ca
self.default_chain_file = default_chain_file
2014-03-07 03:38:50 +00:00
self.dhparams = dhparams
self.certs = dict()
self.expire_queue = []
def expire(self, entry):
self.expire_queue.append(entry)
if len(self.expire_queue) > self.STORE_CAP:
d = self.expire_queue.pop(0)
for k, v in list(self.certs.items()):
if v == d:
del self.certs[k]
2014-03-04 01:12:58 +00:00
2014-10-08 22:15:39 +00:00
@staticmethod
def load_dhparam(path):
# 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)
2015-09-20 16:12:55 +00:00
bio = OpenSSL.SSL._lib.BIO_new_file(path.encode(sys.getfilesystemencoding()), b"r")
2014-03-07 03:38:50 +00:00
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(
2015-05-30 00:02:58 +00:00
bio,
OpenSSL.SSL._ffi.NULL,
OpenSSL.SSL._ffi.NULL,
OpenSSL.SSL._ffi.NULL)
2014-03-07 03:38:50 +00:00
dh = OpenSSL.SSL._ffi.gc(dh, OpenSSL.SSL._lib.DH_free)
return dh
2014-03-04 01:12:58 +00:00
@classmethod
2014-10-08 18:46:30 +00:00
def from_store(cls, path, basename):
ca_path = os.path.join(path, basename + "-ca.pem")
if not os.path.exists(ca_path):
key, ca = cls.create_store(path, basename)
2014-03-04 01:12:58 +00:00
else:
2014-10-08 18:46:30 +00:00
with open(ca_path, "rb") as f:
raw = f.read()
2015-05-30 00:02:58 +00:00
ca = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
raw)
key = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
raw)
2014-10-08 18:46:30 +00:00
dh_path = os.path.join(path, basename + "-dhparam.pem")
dh = cls.load_dhparam(dh_path)
return cls(key, ca, ca_path, dh)
2014-03-04 01:12:58 +00:00
2014-10-08 22:15:39 +00:00
@staticmethod
def create_store(path, basename, o=None, cn=None, expiry=DEFAULT_EXP):
2014-03-04 01:12:58 +00:00
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
2014-10-08 22:15:39 +00:00
with open(os.path.join(path, basename + "-ca.pem"), "wb") as f:
2015-05-30 00:02:58 +00:00
f.write(
OpenSSL.crypto.dump_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
key))
f.write(
OpenSSL.crypto.dump_certificate(
OpenSSL.crypto.FILETYPE_PEM,
ca))
2014-03-04 01:12:58 +00:00
# Dump the certificate in PEM format
2014-10-08 22:15:39 +00:00
with open(os.path.join(path, basename + "-ca-cert.pem"), "wb") as f:
2015-05-30 00:02:58 +00:00
f.write(
OpenSSL.crypto.dump_certificate(
OpenSSL.crypto.FILETYPE_PEM,
ca))
2014-03-04 01:12:58 +00:00
# Create a .cer file with the same contents for Android
2014-10-08 22:15:39 +00:00
with open(os.path.join(path, basename + "-ca-cert.cer"), "wb") as f:
2015-05-30 00:02:58 +00:00
f.write(
OpenSSL.crypto.dump_certificate(
OpenSSL.crypto.FILETYPE_PEM,
ca))
2014-03-04 01:12:58 +00:00
# Dump the certificate in PKCS12 format for Windows devices
2014-10-08 22:15:39 +00:00
with open(os.path.join(path, basename + "-ca-cert.p12"), "wb") as f:
p12 = OpenSSL.crypto.PKCS12()
p12.set_certificate(ca)
p12.set_privatekey(key)
f.write(p12.export())
with open(os.path.join(path, basename + "-dhparam.pem"), "wb") as f:
f.write(DEFAULT_DHPARAM)
2014-03-04 01:12:58 +00:00
return key, ca
def add_cert_file(self, spec, path):
2014-10-08 18:46:30 +00:00
with open(path, "rb") as f:
raw = f.read()
2015-05-30 00:02:58 +00:00
cert = SSLCert(
OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM,
raw))
try:
2015-05-30 00:02:58 +00:00
privatekey = OpenSSL.crypto.load_privatekey(
OpenSSL.crypto.FILETYPE_PEM,
raw)
except Exception:
2014-10-08 22:15:39 +00:00
privatekey = self.default_privatekey
2014-10-08 18:46:30 +00:00
self.add_cert(
2014-10-08 22:15:39 +00:00
CertStoreEntry(cert, privatekey, path),
2014-10-08 18:46:30 +00:00
spec
)
2014-10-08 18:46:30 +00:00
def add_cert(self, entry, *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-10-08 18:46:30 +00:00
if entry.cert.cn:
self.certs[entry.cert.cn] = entry
for i in entry.cert.altnames:
self.certs[i] = entry
for i in names:
2014-10-08 18:46:30 +00:00
self.certs[i] = entry
@staticmethod
def asterisk_forms(dn):
2016-02-02 17:15:55 +00:00
if dn is None:
return []
2015-09-18 13:38:31 +00:00
parts = dn.split(b".")
parts.reverse()
2015-09-18 13:38:31 +00:00
curr_dn = b""
dn_forms = [b"*"]
for part in parts[:-1]:
2015-09-18 13:38:31 +00:00
curr_dn = b"." + part + curr_dn # .example.com
dn_forms.append(b"*" + curr_dn) # *.example.com
if parts[-1] != b"*":
dn_forms.append(parts[-1] + curr_dn)
return dn_forms
def get_cert(self, commonname, sans):
"""
2014-10-08 22:15:39 +00:00
Returns an (cert, privkey, cert_chain) tuple.
commonname: Common name for the generated certificate. Must be a
valid, plain-ASCII, IDNA-encoded domain name.
sans: A list of Subject Alternate Names.
"""
potential_keys = self.asterisk_forms(commonname)
for s in sans:
potential_keys.extend(self.asterisk_forms(s))
potential_keys.append((commonname, tuple(sans)))
2015-05-30 00:02:58 +00:00
name = next(
2015-09-20 16:12:55 +00:00
filter(lambda key: key in self.certs, potential_keys),
None
)
if name:
2014-10-08 18:46:30 +00:00
entry = self.certs[name]
else:
2014-10-08 22:15:39 +00:00
entry = CertStoreEntry(
2015-05-30 00:02:58 +00:00
cert=dummy_cert(
self.default_privatekey,
self.default_ca,
commonname,
sans),
2014-10-08 22:15:39 +00:00
privatekey=self.default_privatekey,
2015-05-30 00:02:58 +00:00
chain_file=self.default_chain_file)
2014-10-08 18:46:30 +00:00
self.certs[(commonname, tuple(sans))] = entry
self.expire(entry)
2014-10-08 22:15:39 +00:00
return entry.cert, entry.privatekey, entry.chain_file
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.
# TODO: We should also handle iPAddresses.
2012-06-27 04:42:00 +00:00
componentType = namedtype.NamedTypes(
namedtype.NamedType('dNSName', char.IA5String().subtype(
implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2)
)
2012-06-27 04:42:00 +00:00
),
)
class _GeneralNames(univ.SequenceOf):
componentType = _GeneralName()
2015-05-30 00:02:58 +00:00
sizeSpec = univ.SequenceOf.sizeSpec + \
constraint.ValueSizeConstraint(1, 1024)
2012-06-27 04:42:00 +00:00
class SSLCert(serializable.Serializable):
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
def __eq__(self, other):
return self.digest("sha256") == other.digest("sha256")
2014-09-04 17:18:43 +00:00
def __ne__(self, other):
return not self.__eq__(other)
2016-02-08 03:16:58 +00:00
def get_state(self):
return self.to_pem()
def set_state(self, state):
self.x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, state)
@classmethod
def from_state(cls, state):
2016-04-02 18:20:28 +00:00
return cls.from_pem(state)
2016-02-08 03:16:58 +00:00
2012-06-27 10:11:58 +00:00
@classmethod
2016-02-08 03:16:58 +00:00
def from_pem(cls, txt):
2012-06-27 10:11:58 +00:00
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, txt)
2016-02-08 03:16:58 +00:00
return cls(x509)
2012-06-27 04:42:00 +00:00
@classmethod
2016-02-08 03:16:58 +00:00
def from_der(cls, der):
2012-06-27 04:42:00 +00:00
pem = ssl.DER_cert_to_PEM_cert(der)
2016-02-08 03:16:58 +00:00
return cls.from_pem(pem)
2012-06-27 04:42:00 +00:00
def to_pem(self):
2015-05-30 00:02:58 +00:00
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()
2015-09-20 17:40:09 +00:00
return datetime.datetime.strptime(t.decode("ascii"), "%Y%m%d%H%M%SZ")
2012-06-27 04:42:00 +00:00
@property
def notafter(self):
2012-06-27 10:11:58 +00:00
t = self.x509.get_notAfter()
2015-09-20 17:40:09 +00:00
return datetime.datetime.strptime(t.decode("ascii"), "%Y%m%d%H%M%SZ")
2012-06-27 04:42:00 +00:00
@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):
c = None
2012-06-27 04:42:00 +00:00
for i in self.subject:
2015-09-18 13:38:31 +00:00
if i[0] == b"CN":
c = i[1]
return c
2012-06-27 04:42:00 +00:00
@property
def altnames(self):
"""
Returns:
All DNS altnames.
"""
# tcp.TCPClient.convert_to_ssl assumes that this property only contains DNS altnames for hostname verification.
2012-06-27 04:42:00 +00:00
altnames = []
2012-06-27 10:11:58 +00:00
for i in range(self.x509.get_extension_count()):
ext = self.x509.get_extension(i)
2015-09-18 13:38:31 +00:00
if ext.get_short_name() == b"subjectAltName":
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())
return altnames