Repository: pyca/cryptography

Issue:
Add signature algorithm support to X509
Signature algorithms are OIDs that contain both the digest function (SHA1, SHA2, etc) and signature type (RSA/DSA/ECDSA). The simple way to handle this would be to return the ObjectIdentifier instance and add the OIDs. e.g.:

``` python
OID_MD5_WITH_RSA = ObjectIdentifier("1.2.840.113549.1.1.4")
OID_SHA1_WITH_RSA = ObjectIdentifier("1.2.840.113549.1.1.5")
OID_SHA224_WITH_RSA = ObjectIdentifier("1.2.840.113549.1.1.14")
OID_SHA256_WITH_RSA = ObjectIdentifier("1.2.840.113549.1.1.11")
OID_SHA384_WITH_RSA = ObjectIdentifier("1.2.840.113549.1.1.12")
OID_SHA512_WITH_RSA = ObjectIdentifier("1.2.840.113549.1.1.13")
OID_ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1")
OID_ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2")
OID_ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3")
OID_ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4")
```

The type of the signature is already known from the object type though, so we could also choose to implement a new function that just tells you what digest function was used (returning an instance of hashes.SHA256 for example).

Right now I'm leaning towards supporting the OID directly and adding a convenience function that can tell you the digest directly in a later PR.



Discussion:

Resolving patch:
diff --git a/src/cryptography/hazmat/backends/openssl/x509.py b/src/cryptography/hazmat/backends/openssl/x509.py
--- a/src/cryptography/hazmat/backends/openssl/x509.py
+++ b/src/cryptography/hazmat/backends/openssl/x509.py
@@ -16,6 +16,7 @@
 import datetime
 
 from cryptography import utils, x509
+from cryptography.exceptions import UnsupportedAlgorithm
 from cryptography.hazmat.primitives import hashes
 
 
@@ -121,14 +122,7 @@ def _build_x509_name(self, x509_name):
                 buf, lambda buf: self._backend._lib.OPENSSL_free(buf[0])
             )
             value = self._backend._ffi.buffer(buf[0], res)[:].decode('utf8')
-            # Set to 80 on the recommendation of
-            # https://www.openssl.org/docs/crypto/OBJ_nid2ln.html
-            buf_len = 80
-            buf = self._backend._ffi.new("char[]", buf_len)
-            res = self._backend._lib.OBJ_obj2txt(buf, buf_len, obj, 1)
-            assert res > 0
-            oid = self._backend._ffi.buffer(buf, res)[:].decode()
-
+            oid = self._obj2txt(obj)
             attributes.append(
                 x509.NameAttribute(
                     x509.ObjectIdentifier(oid), value
@@ -136,3 +130,22 @@ def _build_x509_name(self, x509_name):
             )
 
         return x509.Name(attributes)
+
+    def _obj2txt(self, obj):
+        # Set to 80 on the recommendation of
+        # https://www.openssl.org/docs/crypto/OBJ_nid2ln.html#return_values
+        buf_len = 80
+        buf = self._backend._ffi.new("char[]", buf_len)
+        res = self._backend._lib.OBJ_obj2txt(buf, buf_len, obj, 1)
+        assert res > 0
+        return self._backend._ffi.buffer(buf, res)[:].decode()
+
+    @property
+    def signature_hash_algorithm(self):
+        oid = self._obj2txt(self._x509.sig_alg.algorithm)
+        try:
+            return x509._SIG_OIDS_TO_HASH[oid]
+        except KeyError:
+            raise UnsupportedAlgorithm(
+                "Signature algorithm OID:{0} not recognized".format(oid)
+            )
diff --git a/src/cryptography/hazmat/bindings/openssl/x509.py b/src/cryptography/hazmat/bindings/openssl/x509.py
--- a/src/cryptography/hazmat/bindings/openssl/x509.py
+++ b/src/cryptography/hazmat/bindings/openssl/x509.py
@@ -65,6 +65,7 @@
 } X509_CRL;
 
 typedef struct {
+    X509_ALGOR *sig_alg;
     X509_CINF *cert_info;
     ...;
 } X509;
diff --git a/src/cryptography/x509.py b/src/cryptography/x509.py
--- a/src/cryptography/x509.py
+++ b/src/cryptography/x509.py
@@ -10,6 +10,7 @@
 import six
 
 from cryptography import utils
+from cryptography.hazmat.primitives import hashes
 
 
 _OID_NAMES = {
@@ -28,6 +29,19 @@
     "2.5.4.65": "pseudonym",
     "0.9.2342.19200300.100.1.25": "domainComponent",
     "1.2.840.113549.1.9.1": "emailAddress",
+    "1.2.840.113549.1.1.4": "md5WithRSAEncryption",
+    "1.2.840.113549.1.1.5": "sha1WithRSAEncryption",
+    "1.2.840.113549.1.1.14": "sha224WithRSAEncryption",
+    "1.2.840.113549.1.1.11": "sha256WithRSAEncryption",
+    "1.2.840.113549.1.1.12": "sha384WithRSAEncryption",
+    "1.2.840.113549.1.1.13": "sha512WithRSAEncryption",
+    "1.2.840.10045.4.3.1": "ecdsa-with-SHA224",
+    "1.2.840.10045.4.3.2": "ecdsa-with-SHA256",
+    "1.2.840.10045.4.3.3": "ecdsa-with-SHA384",
+    "1.2.840.10045.4.3.4": "ecdsa-with-SHA512",
+    "1.2.840.10040.4.3": "dsa-with-sha1",
+    "2.16.840.1.101.3.4.3.1": "dsa-with-sha224",
+    "2.16.840.1.101.3.4.3.2": "dsa-with-sha256",
 }
 
 
@@ -143,6 +157,36 @@ def __len__(self):
 OID_DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25")
 OID_EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1")
 
+OID_RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4")
+OID_RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5")
+OID_RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14")
+OID_RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11")
+OID_RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12")
+OID_RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13")
+OID_ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1")
+OID_ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2")
+OID_ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3")
+OID_ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4")
+OID_DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3")
+OID_DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1")
+OID_DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2")
+
+_SIG_OIDS_TO_HASH = {
+    OID_RSA_WITH_MD5.dotted_string: hashes.MD5(),
+    OID_RSA_WITH_SHA1.dotted_string: hashes.SHA1(),
+    OID_RSA_WITH_SHA224.dotted_string: hashes.SHA224(),
+    OID_RSA_WITH_SHA256.dotted_string: hashes.SHA256(),
+    OID_RSA_WITH_SHA384.dotted_string: hashes.SHA384(),
+    OID_RSA_WITH_SHA512.dotted_string: hashes.SHA512(),
+    OID_ECDSA_WITH_SHA224.dotted_string: hashes.SHA224(),
+    OID_ECDSA_WITH_SHA256.dotted_string: hashes.SHA256(),
+    OID_ECDSA_WITH_SHA384.dotted_string: hashes.SHA384(),
+    OID_ECDSA_WITH_SHA512.dotted_string: hashes.SHA512(),
+    OID_DSA_WITH_SHA1.dotted_string: hashes.SHA1(),
+    OID_DSA_WITH_SHA224.dotted_string: hashes.SHA224(),
+    OID_DSA_WITH_SHA256.dotted_string: hashes.SHA256()
+}
+
 
 @six.add_metaclass(abc.ABCMeta)
 class Certificate(object):
@@ -193,3 +237,10 @@ def subject(self):
         """
         Returns the subject name object.
         """
+
+    @abc.abstractproperty
+    def signature_hash_algorithm(self):
+        """
+        Returns a HashAlgorithm corresponding to the type of the digest signed
+        in the certificate.
+        """


Test patch:
diff --git a/tests/test_x509.py b/tests/test_x509.py
--- a/tests/test_x509.py
+++ b/tests/test_x509.py
@@ -13,6 +13,7 @@
 import six
 
 from cryptography import x509
+from cryptography.exceptions import UnsupportedAlgorithm
 from cryptography.hazmat.backends.interfaces import (
     DSABackend, EllipticCurveBackend, RSABackend, X509Backend
 )
@@ -45,6 +46,7 @@ def test_load_pem_cert(self, backend):
         assert cert.serial == 11559813051657483483
         fingerprint = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
         assert fingerprint == b"2b619ed04bfc9c3b08eb677d272192286a0947a8"
+        assert isinstance(cert.signature_hash_algorithm, hashes.SHA1)
 
     def test_load_der_cert(self, backend):
         cert = _load_cert(
@@ -56,6 +58,7 @@ def test_load_der_cert(self, backend):
         assert cert.serial == 2
         fingerprint = binascii.hexlify(cert.fingerprint(hashes.SHA1()))
         assert fingerprint == b"6f49779533d565e8b7c1062503eab41492c38e4d"
+        assert isinstance(cert.signature_hash_algorithm, hashes.SHA256)
 
     def test_issuer(self, backend):
         cert = _load_cert(
@@ -328,6 +331,15 @@ def test_invalid_der(self, backend):
         with pytest.raises(ValueError):
             x509.load_der_x509_certificate(b"notacert", backend)
 
+    def test_unsupported_signature_hash_algorithm_cert(self, backend):
+        cert = _load_cert(
+            os.path.join("x509", "verisign_md2_root.pem"),
+            x509.load_pem_x509_certificate,
+            backend
+        )
+        with pytest.raises(UnsupportedAlgorithm):
+            cert.signature_hash_algorithm
+
 
 @pytest.mark.requires_backend_interface(interface=DSABackend)
 @pytest.mark.requires_backend_interface(interface=X509Backend)
@@ -338,6 +350,7 @@ def test_load_dsa_cert(self, backend):
             x509.load_pem_x509_certificate,
             backend
         )
+        assert isinstance(cert.signature_hash_algorithm, hashes.SHA1)
         public_key = cert.public_key()
         assert isinstance(public_key, interfaces.DSAPublicKey)
         if isinstance(public_key, interfaces.DSAPublicKeyWithNumbers):
@@ -390,6 +403,7 @@ def test_load_ecdsa_cert(self, backend):
             x509.load_pem_x509_certificate,
             backend
         )
+        assert isinstance(cert.signature_hash_algorithm, hashes.SHA384)
         public_key = cert.public_key()
         assert isinstance(public_key, interfaces.EllipticCurvePublicKey)
         if isinstance(