aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/_cffi_src/openssl/asn1.py5
-rw-r--r--src/_cffi_src/openssl/ec.py2
-rw-r--r--src/_cffi_src/openssl/x509v3.py1
-rw-r--r--src/cryptography/hazmat/backends/interfaces.py4
-rw-r--r--src/cryptography/hazmat/backends/multibackend.py4
-rw-r--r--src/cryptography/hazmat/backends/openssl/backend.py119
-rw-r--r--src/cryptography/hazmat/backends/openssl/x509.py6
-rw-r--r--src/cryptography/utils.py7
-rw-r--r--src/cryptography/x509.py112
9 files changed, 247 insertions, 13 deletions
diff --git a/src/_cffi_src/openssl/asn1.py b/src/_cffi_src/openssl/asn1.py
index 44e9de17..96084721 100644
--- a/src/_cffi_src/openssl/asn1.py
+++ b/src/_cffi_src/openssl/asn1.py
@@ -43,6 +43,7 @@ typedef struct asn1_string_st ASN1_IA5STRING;
typedef ... ASN1_BIT_STRING;
typedef ... ASN1_OBJECT;
typedef struct asn1_string_st ASN1_STRING;
+typedef struct asn1_string_st ASN1_UTF8STRING;
typedef ... ASN1_TYPE;
typedef ... ASN1_GENERALIZEDTIME;
typedef ... ASN1_ENUMERATED;
@@ -125,9 +126,13 @@ int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *, int, int);
"""
MACROS = """
+ASN1_UTF8STRING *ASN1_UTF8STRING_new(void);
+void ASN1_UTF8STRING_free(ASN1_UTF8STRING *);
+
ASN1_BIT_STRING *ASN1_BIT_STRING_new(void);
void ASN1_BIT_STRING_free(ASN1_BIT_STRING *);
int i2d_ASN1_BIT_STRING(ASN1_BIT_STRING *, unsigned char **);
+int i2d_ASN1_OCTET_STRING(ASN1_OCTET_STRING *, unsigned char **);
/* This is not a macro, but is const on some versions of OpenSSL */
int ASN1_BIT_STRING_get_bit(ASN1_BIT_STRING *, int);
ASN1_TIME *M_ASN1_TIME_dup(void *);
diff --git a/src/_cffi_src/openssl/ec.py b/src/_cffi_src/openssl/ec.py
index 93ca2754..10c87c33 100644
--- a/src/_cffi_src/openssl/ec.py
+++ b/src/_cffi_src/openssl/ec.py
@@ -397,7 +397,7 @@ static const long Cryptography_HAS_EC2M = 1;
#endif
#if defined(OPENSSL_NO_EC) || OPENSSL_VERSION_NUMBER < 0x1000200f || \
- defined(LIBRESSL_VERSION_NUMBER)
+ defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20020002L
static const long Cryptography_HAS_EC_1_0_2 = 0;
const char *(*EC_curve_nid2nist)(int) = NULL;
#else
diff --git a/src/_cffi_src/openssl/x509v3.py b/src/_cffi_src/openssl/x509v3.py
index 6e35dacc..84e49640 100644
--- a/src/_cffi_src/openssl/x509v3.py
+++ b/src/_cffi_src/openssl/x509v3.py
@@ -279,6 +279,7 @@ void sk_ASN1_INTEGER_free(Cryptography_STACK_OF_ASN1_INTEGER *);
int sk_ASN1_INTEGER_num(Cryptography_STACK_OF_ASN1_INTEGER *);
ASN1_INTEGER *sk_ASN1_INTEGER_value(Cryptography_STACK_OF_ASN1_INTEGER *, int);
int sk_ASN1_INTEGER_push(Cryptography_STACK_OF_ASN1_INTEGER *, ASN1_INTEGER *);
+Cryptography_STACK_OF_ASN1_INTEGER *sk_ASN1_INTEGER_new_null(void);
X509_EXTENSION *X509V3_EXT_i2d(int, int, void *);
diff --git a/src/cryptography/hazmat/backends/interfaces.py b/src/cryptography/hazmat/backends/interfaces.py
index 49ccda18..a43621a7 100644
--- a/src/cryptography/hazmat/backends/interfaces.py
+++ b/src/cryptography/hazmat/backends/interfaces.py
@@ -281,9 +281,9 @@ class X509Backend(object):
"""
@abc.abstractmethod
- def sign_x509_certificate(self, builder, private_key, algorithm):
+ def create_x509_certificate(self, builder, private_key, algorithm):
"""
- Sign an X.509 Certificate from a CertificateBuilder object.
+ Create and sign an X.509 certificate from a CertificateBuilder object.
"""
diff --git a/src/cryptography/hazmat/backends/multibackend.py b/src/cryptography/hazmat/backends/multibackend.py
index 8008989e..9db32aa5 100644
--- a/src/cryptography/hazmat/backends/multibackend.py
+++ b/src/cryptography/hazmat/backends/multibackend.py
@@ -352,9 +352,9 @@ class MultiBackend(object):
_Reasons.UNSUPPORTED_X509
)
- def sign_x509_certificate(self, builder, private_key, algorithm):
+ def create_x509_certificate(self, builder, private_key, algorithm):
for b in self._filtered_backends(X509Backend):
- return b.sign_x509_certificate(builder, private_key, algorithm)
+ return b.create_x509_certificate(builder, private_key, algorithm)
raise UnsupportedAlgorithm(
"This backend does not support X.509.",
diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py
index cf294c01..6675f677 100644
--- a/src/cryptography/hazmat/backends/openssl/backend.py
+++ b/src/cryptography/hazmat/backends/openssl/backend.py
@@ -38,7 +38,8 @@ from cryptography.hazmat.backends.openssl.rsa import (
_RSAPrivateKey, _RSAPublicKey
)
from cryptography.hazmat.backends.openssl.x509 import (
- _Certificate, _CertificateSigningRequest
+ _Certificate, _CertificateSigningRequest, _DISTPOINT_TYPE_FULLNAME,
+ _DISTPOINT_TYPE_RELATIVENAME
)
from cryptography.hazmat.bindings.openssl.binding import Binding
from cryptography.hazmat.primitives import hashes, serialization
@@ -181,6 +182,36 @@ def _encode_key_usage(backend, key_usage):
return pp, r
+def _encode_authority_key_identifier(backend, authority_keyid):
+ akid = backend._lib.AUTHORITY_KEYID_new()
+ assert akid != backend._ffi.NULL
+ akid = backend._ffi.gc(akid, backend._lib.AUTHORITY_KEYID_free)
+ if authority_keyid.key_identifier is not None:
+ akid.keyid = _encode_asn1_str(
+ backend,
+ authority_keyid.key_identifier,
+ len(authority_keyid.key_identifier)
+ )
+
+ if authority_keyid.authority_cert_issuer is not None:
+ akid.issuer = _encode_general_names(
+ backend, authority_keyid.authority_cert_issuer
+ )
+
+ if authority_keyid.authority_cert_serial_number is not None:
+ akid.serial = _encode_asn1_int(
+ backend, authority_keyid.authority_cert_serial_number
+ )
+
+ pp = backend._ffi.new('unsigned char **')
+ r = backend._lib.i2d_AUTHORITY_KEYID(akid, pp)
+ assert r > 0
+ pp = backend._ffi.gc(
+ pp, lambda pointer: backend._lib.OPENSSL_free(pointer[0])
+ )
+ return pp, r
+
+
def _encode_basic_constraints(backend, basic_constraints):
constraints = backend._lib.BASIC_CONSTRAINTS_new()
constraints = backend._ffi.gc(
@@ -253,6 +284,17 @@ def _encode_subject_alt_name(backend, san):
return pp, r
+def _encode_subject_key_identifier(backend, ski):
+ asn1_str = _encode_asn1_str_gc(backend, ski.digest, len(ski.digest))
+ pp = backend._ffi.new("unsigned char **")
+ r = backend._lib.i2d_ASN1_OCTET_STRING(asn1_str, pp)
+ assert r > 0
+ pp = backend._ffi.gc(
+ pp, lambda pointer: backend._lib.OPENSSL_free(pointer[0])
+ )
+ return pp, r
+
+
def _encode_general_name(backend, name):
if isinstance(name, x509.DNSName):
gn = backend._lib.GENERAL_NAME_new()
@@ -359,6 +401,67 @@ def _encode_extended_key_usage(backend, extended_key_usage):
return pp, r
+_CRLREASONFLAGS = {
+ x509.ReasonFlags.key_compromise: 1,
+ x509.ReasonFlags.ca_compromise: 2,
+ x509.ReasonFlags.affiliation_changed: 3,
+ x509.ReasonFlags.superseded: 4,
+ x509.ReasonFlags.cessation_of_operation: 5,
+ x509.ReasonFlags.certificate_hold: 6,
+ x509.ReasonFlags.privilege_withdrawn: 7,
+ x509.ReasonFlags.aa_compromise: 8,
+}
+
+
+def _encode_crl_distribution_points(backend, crl_distribution_points):
+ cdp = backend._lib.sk_DIST_POINT_new_null()
+ cdp = backend._ffi.gc(cdp, backend._lib.sk_DIST_POINT_free)
+ for point in crl_distribution_points:
+ dp = backend._lib.DIST_POINT_new()
+ assert dp != backend._ffi.NULL
+
+ if point.reasons:
+ bitmask = backend._lib.ASN1_BIT_STRING_new()
+ assert bitmask != backend._ffi.NULL
+ dp.reasons = bitmask
+ for reason in point.reasons:
+ res = backend._lib.ASN1_BIT_STRING_set_bit(
+ bitmask, _CRLREASONFLAGS[reason], 1
+ )
+ assert res == 1
+
+ if point.full_name:
+ dpn = backend._lib.DIST_POINT_NAME_new()
+ assert dpn != backend._ffi.NULL
+ dpn.type = _DISTPOINT_TYPE_FULLNAME
+ dpn.name.fullname = _encode_general_names(backend, point.full_name)
+ dp.distpoint = dpn
+
+ if point.relative_name:
+ dpn = backend._lib.DIST_POINT_NAME_new()
+ assert dpn != backend._ffi.NULL
+ dpn.type = _DISTPOINT_TYPE_RELATIVENAME
+ name = _encode_name_gc(backend, point.relative_name)
+ relativename = backend._lib.sk_X509_NAME_ENTRY_dup(name.entries)
+ assert relativename != backend._ffi.NULL
+ dpn.name.relativename = relativename
+ dp.distpoint = dpn
+
+ if point.crl_issuer:
+ dp.CRLissuer = _encode_general_names(backend, point.crl_issuer)
+
+ res = backend._lib.sk_DIST_POINT_push(cdp, dp)
+ assert res >= 1
+
+ pp = backend._ffi.new('unsigned char **')
+ r = backend._lib.i2d_CRL_DIST_POINTS(cdp, pp)
+ assert r > 0
+ pp = backend._ffi.gc(
+ pp, lambda pointer: backend._lib.OPENSSL_free(pointer[0])
+ )
+ return pp, r
+
+
@utils.register_interface(CipherBackend)
@utils.register_interface(CMACBackend)
@utils.register_interface(DERSerializationBackend)
@@ -1100,7 +1203,7 @@ class Backend(object):
return _CertificateSigningRequest(self, x509_req)
- def sign_x509_certificate(self, builder, private_key, algorithm):
+ def create_x509_certificate(self, builder, private_key, algorithm):
if not isinstance(builder, x509.CertificateBuilder):
raise TypeError('Builder type mismatch.')
if not isinstance(algorithm, hashes.HashAlgorithm):
@@ -1167,26 +1270,36 @@ class Backend(object):
for i, extension in enumerate(builder._extensions):
if isinstance(extension.value, x509.BasicConstraints):
pp, r = _encode_basic_constraints(self, extension.value)
+ elif isinstance(extension.value, x509.AuthorityKeyIdentifier):
+ pp, r = _encode_authority_key_identifier(self, extension.value)
elif isinstance(extension.value, x509.KeyUsage):
pp, r = _encode_key_usage(self, extension.value)
elif isinstance(extension.value, x509.ExtendedKeyUsage):
pp, r = _encode_extended_key_usage(self, extension.value)
elif isinstance(extension.value, x509.SubjectAlternativeName):
pp, r = _encode_subject_alt_name(self, extension.value)
+ elif isinstance(extension.value, x509.SubjectKeyIdentifier):
+ pp, r = _encode_subject_key_identifier(self, extension.value)
elif isinstance(extension.value, x509.AuthorityInformationAccess):
pp, r = _encode_authority_information_access(
self, extension.value
)
+ elif isinstance(extension.value, x509.CRLDistributionPoints):
+ pp, r = _encode_crl_distribution_points(
+ self, extension.value
+ )
else:
raise NotImplementedError('Extension not yet supported.')
- obj = _txt2obj(self, extension.oid.dotted_string)
+ obj = _txt2obj_gc(self, extension.oid.dotted_string)
extension = self._lib.X509_EXTENSION_create_by_OBJ(
self._ffi.NULL,
obj,
1 if extension.critical else 0,
_encode_asn1_str_gc(self, pp[0], r)
)
+ assert extension != self._ffi.NULL
+ extension = self._ffi.gc(extension, self._lib.X509_EXTENSION_free)
res = self._lib.X509_add_ext(x509_cert, extension, i)
assert res == 1
diff --git a/src/cryptography/hazmat/backends/openssl/x509.py b/src/cryptography/hazmat/backends/openssl/x509.py
index ee9a3bbf..564b2680 100644
--- a/src/cryptography/hazmat/backends/openssl/x509.py
+++ b/src/cryptography/hazmat/backends/openssl/x509.py
@@ -592,6 +592,10 @@ def _decode_extended_key_usage(backend, sk):
return x509.ExtendedKeyUsage(ekus)
+_DISTPOINT_TYPE_FULLNAME = 0
+_DISTPOINT_TYPE_RELATIVENAME = 1
+
+
def _decode_crl_distribution_points(backend, cdps):
cdps = backend._ffi.cast("Cryptography_STACK_OF_DIST_POINT *", cdps)
cdps = backend._ffi.gc(cdps, backend._lib.sk_DIST_POINT_free)
@@ -651,7 +655,7 @@ def _decode_crl_distribution_points(backend, cdps):
# point so make sure it's not null.
if cdp.distpoint != backend._ffi.NULL:
# Type 0 is fullName, there is no #define for it in the code.
- if cdp.distpoint.type == 0:
+ if cdp.distpoint.type == _DISTPOINT_TYPE_FULLNAME:
full_name = _decode_general_names(
backend, cdp.distpoint.name.fullname
)
diff --git a/src/cryptography/utils.py b/src/cryptography/utils.py
index 24afe612..993571bd 100644
--- a/src/cryptography/utils.py
+++ b/src/cryptography/utils.py
@@ -5,6 +5,7 @@
from __future__ import absolute_import, division, print_function
import abc
+import binascii
import inspect
import struct
import sys
@@ -46,6 +47,12 @@ else:
return result
+def int_to_bytes(integer):
+ hex_string = '%x' % integer
+ n = len(hex_string)
+ return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
+
+
class InterfaceNotImplemented(Exception):
pass
diff --git a/src/cryptography/x509.py b/src/cryptography/x509.py
index 0ddff728..397274e8 100644
--- a/src/cryptography/x509.py
+++ b/src/cryptography/x509.py
@@ -6,21 +6,53 @@ from __future__ import absolute_import, division, print_function
import abc
import datetime
+import hashlib
import ipaddress
from email.utils import parseaddr
from enum import Enum
import idna
+from pyasn1.codec.der import decoder
+from pyasn1.type import namedtype, univ
+
import six
from six.moves import urllib_parse
from cryptography import utils
-from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa
+class _SubjectPublicKeyInfo(univ.Sequence):
+ componentType = namedtype.NamedTypes(
+ namedtype.NamedType('algorithm', univ.Sequence()),
+ namedtype.NamedType('subjectPublicKey', univ.BitString())
+ )
+
+
+def _key_identifier_from_public_key(public_key):
+ # This is a very slow way to do this.
+ serialized = public_key.public_bytes(
+ serialization.Encoding.DER,
+ serialization.PublicFormat.SubjectPublicKeyInfo
+ )
+ spki, remaining = decoder.decode(
+ serialized, asn1Spec=_SubjectPublicKeyInfo()
+ )
+ assert not remaining
+ # the univ.BitString object is a tuple of bits. We need bytes and
+ # pyasn1 really doesn't want to give them to us. To get it we'll
+ # build an integer and convert that to bytes.
+ bits = 0
+ for bit in spki.getComponentByName("subjectPublicKey"):
+ bits = bits << 1 | bit
+
+ data = utils.int_to_bytes(bits)
+ return hashlib.sha1(data).digest()
+
+
_OID_NAMES = {
"2.5.4.3": "commonName",
"2.5.4.6": "countryName",
@@ -313,7 +345,19 @@ class Extension(object):
return not self == other
+@six.add_metaclass(abc.ABCMeta)
+class ExtensionType(object):
+ @abc.abstractproperty
+ def oid(self):
+ """
+ Returns the oid associated with the given extension type.
+ """
+
+
+@utils.register_interface(ExtensionType)
class ExtendedKeyUsage(object):
+ oid = OID_EXTENDED_KEY_USAGE
+
def __init__(self, usages):
if not all(isinstance(x, ObjectIdentifier) for x in usages):
raise TypeError(
@@ -341,11 +385,15 @@ class ExtendedKeyUsage(object):
return not self == other
+@utils.register_interface(ExtensionType)
class OCSPNoCheck(object):
- pass
+ oid = OID_OCSP_NO_CHECK
+@utils.register_interface(ExtensionType)
class BasicConstraints(object):
+ oid = OID_BASIC_CONSTRAINTS
+
def __init__(self, ca, path_length):
if not isinstance(ca, bool):
raise TypeError("ca must be a boolean value")
@@ -381,7 +429,10 @@ class BasicConstraints(object):
return not self == other
+@utils.register_interface(ExtensionType)
class KeyUsage(object):
+ oid = OID_KEY_USAGE
+
def __init__(self, digital_signature, content_commitment, key_encipherment,
data_encipherment, key_agreement, key_cert_sign, crl_sign,
encipher_only, decipher_only):
@@ -464,7 +515,10 @@ class KeyUsage(object):
return not self == other
+@utils.register_interface(ExtensionType)
class AuthorityInformationAccess(object):
+ oid = OID_AUTHORITY_INFORMATION_ACCESS
+
def __init__(self, descriptions):
if not all(isinstance(x, AccessDescription) for x in descriptions):
raise TypeError(
@@ -528,7 +582,10 @@ class AccessDescription(object):
access_location = utils.read_only_property("_access_location")
+@utils.register_interface(ExtensionType)
class CertificatePolicies(object):
+ oid = OID_CERTIFICATE_POLICIES
+
def __init__(self, policies):
if not all(isinstance(x, PolicyInformation) for x in policies):
raise TypeError(
@@ -665,10 +722,17 @@ class NoticeReference(object):
notice_numbers = utils.read_only_property("_notice_numbers")
+@utils.register_interface(ExtensionType)
class SubjectKeyIdentifier(object):
+ oid = OID_SUBJECT_KEY_IDENTIFIER
+
def __init__(self, digest):
self._digest = digest
+ @classmethod
+ def from_public_key(cls, public_key):
+ return cls(_key_identifier_from_public_key(public_key))
+
digest = utils.read_only_property("_digest")
def __repr__(self):
@@ -686,7 +750,10 @@ class SubjectKeyIdentifier(object):
return not self == other
+@utils.register_interface(ExtensionType)
class NameConstraints(object):
+ oid = OID_NAME_CONSTRAINTS
+
def __init__(self, permitted_subtrees, excluded_subtrees):
if permitted_subtrees is not None:
if not all(
@@ -750,7 +817,10 @@ class NameConstraints(object):
excluded_subtrees = utils.read_only_property("_excluded_subtrees")
+@utils.register_interface(ExtensionType)
class CRLDistributionPoints(object):
+ oid = OID_CRL_DISTRIBUTION_POINTS
+
def __init__(self, distribution_points):
if not all(
isinstance(x, DistributionPoint) for x in distribution_points
@@ -785,7 +855,8 @@ class DistributionPoint(object):
def __init__(self, full_name, relative_name, reasons, crl_issuer):
if full_name and relative_name:
raise ValueError(
- "At least one of full_name and relative_name must be None"
+ "You cannot provide both full_name and relative_name, at "
+ "least one must be None."
)
if full_name and not all(
@@ -870,7 +941,10 @@ class ReasonFlags(Enum):
remove_from_crl = "removeFromCRL"
+@utils.register_interface(ExtensionType)
class InhibitAnyPolicy(object):
+ oid = OID_INHIBIT_ANY_POLICY
+
def __init__(self, skip_certs):
if not isinstance(skip_certs, six.integer_types):
raise TypeError("skip_certs must be an integer")
@@ -1160,7 +1234,10 @@ class GeneralNames(object):
return not self == other
+@utils.register_interface(ExtensionType)
class SubjectAlternativeName(object):
+ oid = OID_SUBJECT_ALTERNATIVE_NAME
+
def __init__(self, general_names):
self._general_names = GeneralNames(general_names)
@@ -1186,7 +1263,10 @@ class SubjectAlternativeName(object):
return not self == other
+@utils.register_interface(ExtensionType)
class IssuerAlternativeName(object):
+ oid = OID_ISSUER_ALTERNATIVE_NAME
+
def __init__(self, general_names):
self._general_names = GeneralNames(general_names)
@@ -1212,7 +1292,10 @@ class IssuerAlternativeName(object):
return not self == other
+@utils.register_interface(ExtensionType)
class AuthorityKeyIdentifier(object):
+ oid = OID_AUTHORITY_KEY_IDENTIFIER
+
def __init__(self, key_identifier, authority_cert_issuer,
authority_cert_serial_number):
if authority_cert_issuer or authority_cert_serial_number:
@@ -1239,6 +1322,15 @@ class AuthorityKeyIdentifier(object):
self._authority_cert_issuer = authority_cert_issuer
self._authority_cert_serial_number = authority_cert_serial_number
+ @classmethod
+ def from_issuer_public_key(cls, public_key):
+ digest = _key_identifier_from_public_key(public_key)
+ return cls(
+ key_identifier=digest,
+ authority_cert_issuer=None,
+ authority_cert_serial_number=None
+ )
+
def __repr__(self):
return (
"<AuthorityKeyIdentifier(key_identifier={0.key_identifier!r}, "
@@ -1720,6 +1812,10 @@ class CertificateBuilder(object):
"""
if isinstance(extension, BasicConstraints):
extension = Extension(OID_BASIC_CONSTRAINTS, critical, extension)
+ elif isinstance(extension, AuthorityKeyIdentifier):
+ extension = Extension(
+ OID_AUTHORITY_KEY_IDENTIFIER, critical, extension
+ )
elif isinstance(extension, KeyUsage):
extension = Extension(OID_KEY_USAGE, critical, extension)
elif isinstance(extension, ExtendedKeyUsage):
@@ -1732,8 +1828,16 @@ class CertificateBuilder(object):
extension = Extension(
OID_AUTHORITY_INFORMATION_ACCESS, critical, extension
)
+ elif isinstance(extension, SubjectKeyIdentifier):
+ extension = Extension(
+ OID_SUBJECT_KEY_IDENTIFIER, critical, extension
+ )
elif isinstance(extension, InhibitAnyPolicy):
extension = Extension(OID_INHIBIT_ANY_POLICY, critical, extension)
+ elif isinstance(extension, CRLDistributionPoints):
+ extension = Extension(
+ OID_CRL_DISTRIBUTION_POINTS, critical, extension
+ )
else:
raise NotImplementedError('Unsupported X.509 extension.')
@@ -1770,4 +1874,4 @@ class CertificateBuilder(object):
if self._public_key is None:
raise ValueError("A certificate must have a public key")
- return backend.sign_x509_certificate(self, private_key, algorithm)
+ return backend.create_x509_certificate(self, private_key, algorithm)