30c8a3
From 087df702931f32eeb3a29957a8fe3fa31749d642 Mon Sep 17 00:00:00 2001
30c8a3
From: Simo Sorce <simo@redhat.com>
30c8a3
Date: Tue, 28 Apr 2020 10:08:02 +0200
30c8a3
Subject: [PATCH] Switch to python cryptography
30c8a3
30c8a3
Original patch: https://github.com/simo5/dnspython/commit/bfe84d523bd4fde7b2655857d78bba85ed05f43c
30c8a3
The same change in master: https://github.com/rthalley/dnspython/pull/449
30c8a3
---
30c8a3
 dns/dnssec.py        | 168 ++++++++++++++++++++-----------------------
30c8a3
 setup.py             |   2 +-
30c8a3
 tests/test_dnssec.py |  12 +---
30c8a3
 3 files changed, 79 insertions(+), 103 deletions(-)
30c8a3
30c8a3
diff --git a/dns/dnssec.py b/dns/dnssec.py
30c8a3
index 35da6b5..73e92da 100644
30c8a3
--- a/dns/dnssec.py
30c8a3
+++ b/dns/dnssec.py
30c8a3
@@ -17,6 +17,7 @@
30c8a3
30c8a3
 """Common DNSSEC-related functions and constants."""
30c8a3
30c8a3
+import hashlib  # used in make_ds() to avoid pycrypto dependency
30c8a3
 from io import BytesIO
30c8a3
 import struct
30c8a3
 import time
30c8a3
@@ -165,10 +166,10 @@ def make_ds(name, key, algorithm, origin=None):
30c8a3
30c8a3
     if algorithm.upper() == 'SHA1':
30c8a3
         dsalg = 1
30c8a3
-        hash = SHA1.new()
30c8a3
+        hash = hashlib.sha1()
30c8a3
     elif algorithm.upper() == 'SHA256':
30c8a3
         dsalg = 2
30c8a3
-        hash = SHA256.new()
30c8a3
+        hash = hashlib.sha256()
30c8a3
     else:
30c8a3
         raise UnsupportedAlgorithm('unsupported algorithm "%s"' % algorithm)
30c8a3
30c8a3
@@ -214,7 +215,7 @@ def _is_dsa(algorithm):
30c8a3
30c8a3
30c8a3
 def _is_ecdsa(algorithm):
30c8a3
-    return _have_ecdsa and (algorithm in (ECDSAP256SHA256, ECDSAP384SHA384))
30c8a3
+    return (algorithm in (ECDSAP256SHA256, ECDSAP384SHA384))
30c8a3
30c8a3
30c8a3
 def _is_md5(algorithm):
30c8a3
@@ -240,18 +241,26 @@ def _is_sha512(algorithm):
30c8a3
30c8a3
 def _make_hash(algorithm):
30c8a3
     if _is_md5(algorithm):
30c8a3
-        return MD5.new()
30c8a3
+        return hashes.MD5()
30c8a3
     if _is_sha1(algorithm):
30c8a3
-        return SHA1.new()
30c8a3
+        return hashes.SHA1()
30c8a3
     if _is_sha256(algorithm):
30c8a3
-        return SHA256.new()
30c8a3
+        return hashes.SHA256()
30c8a3
     if _is_sha384(algorithm):
30c8a3
-        return SHA384.new()
30c8a3
+        return hashes.SHA384()
30c8a3
     if _is_sha512(algorithm):
30c8a3
-        return SHA512.new()
30c8a3
+        return hashes.SHA512()
30c8a3
+    if algorithm == ED25519:
30c8a3
+        return hashes.SHA512()
30c8a3
+    if algorithm == ED448:
30c8a3
+        return hashes.SHAKE256(114)
30c8a3
     raise ValidationFailure('unknown hash for algorithm %u' % algorithm)
30c8a3
30c8a3
30c8a3
+def _bytes_to_long(b):
30c8a3
+    return int.from_bytes(b, 'big')
30c8a3
+
30c8a3
+
30c8a3
 def _make_algorithm_id(algorithm):
30c8a3
     if _is_md5(algorithm):
30c8a3
         oid = [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05]
30c8a3
@@ -316,8 +325,6 @@ def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
30c8a3
         if rrsig.inception > now:
30c8a3
             raise ValidationFailure('not yet valid')
30c8a3
30c8a3
-        hash = _make_hash(rrsig.algorithm)
30c8a3
-
30c8a3
         if _is_rsa(rrsig.algorithm):
30c8a3
             keyptr = candidate_key.key
30c8a3
             (bytes_,) = struct.unpack('!B', keyptr[0:1])
30c8a3
@@ -328,9 +335,9 @@ def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
30c8a3
             rsa_e = keyptr[0:bytes_]
30c8a3
             rsa_n = keyptr[bytes_:]
30c8a3
             try:
30c8a3
-                pubkey = CryptoRSA.construct(
30c8a3
-                    (number.bytes_to_long(rsa_n),
30c8a3
-                     number.bytes_to_long(rsa_e)))
30c8a3
+                public_key = rsa.RSAPublicNumbers(
30c8a3
+                    _bytes_to_long(rsa_e),
30c8a3
+                    _bytes_to_long(rsa_n)).public_key(default_backend())
30c8a3
             except ValueError:
30c8a3
                 raise ValidationFailure('invalid public key')
30c8a3
             sig = rrsig.signature
30c8a3
@@ -346,42 +353,47 @@ def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
30c8a3
             dsa_g = keyptr[0:octets]
30c8a3
             keyptr = keyptr[octets:]
30c8a3
             dsa_y = keyptr[0:octets]
30c8a3
-            pubkey = CryptoDSA.construct(
30c8a3
-                (number.bytes_to_long(dsa_y),
30c8a3
-                 number.bytes_to_long(dsa_g),
30c8a3
-                 number.bytes_to_long(dsa_p),
30c8a3
-                 number.bytes_to_long(dsa_q)))
30c8a3
-            sig = rrsig.signature[1:]
30c8a3
+            try:
30c8a3
+                public_key = dsa.DSAPublicNumbers(
30c8a3
+                    _bytes_to_long(dsa_y),
30c8a3
+                    dsa.DSAParameterNumbers(
30c8a3
+                        _bytes_to_long(dsa_p),
30c8a3
+                        _bytes_to_long(dsa_q),
30c8a3
+                        _bytes_to_long(dsa_g))).public_key(default_backend())
30c8a3
+            except ValueError:
30c8a3
+                raise ValidationFailure('invalid public key')
30c8a3
+            sig_r = rrsig.signature[1:21]
30c8a3
+            sig_s = rrsig.signature[21:]
30c8a3
+            sig = utils.encode_dss_signature(_bytes_to_long(sig_r),
30c8a3
+                                             _bytes_to_long(sig_s))
30c8a3
         elif _is_ecdsa(rrsig.algorithm):
30c8a3
-            # use ecdsa for NIST-384p -- not currently supported by pycryptodome
30c8a3
-
30c8a3
             keyptr = candidate_key.key
30c8a3
-
30c8a3
             if rrsig.algorithm == ECDSAP256SHA256:
30c8a3
-                curve = ecdsa.curves.NIST256p
30c8a3
-                key_len = 32
30c8a3
+                curve = ec.SECP256R1()
30c8a3
+                octets = 32
30c8a3
             elif rrsig.algorithm == ECDSAP384SHA384:
30c8a3
-                curve = ecdsa.curves.NIST384p
30c8a3
-                key_len = 48
30c8a3
-
30c8a3
-            x = number.bytes_to_long(keyptr[0:key_len])
30c8a3
-            y = number.bytes_to_long(keyptr[key_len:key_len * 2])
30c8a3
-            if not ecdsa.ecdsa.point_is_valid(curve.generator, x, y):
30c8a3
-                raise ValidationFailure('invalid ECDSA key')
30c8a3
-            point = ecdsa.ellipticcurve.Point(curve.curve, x, y, curve.order)
30c8a3
-            verifying_key = ecdsa.keys.VerifyingKey.from_public_point(point,
30c8a3
-                                                                      curve)
30c8a3
-            pubkey = ECKeyWrapper(verifying_key, key_len)
30c8a3
-            r = rrsig.signature[:key_len]
30c8a3
-            s = rrsig.signature[key_len:]
30c8a3
-            sig = ecdsa.ecdsa.Signature(number.bytes_to_long(r),
30c8a3
-                                        number.bytes_to_long(s))
30c8a3
+                curve = ec.SECP384R1()
30c8a3
+                octets = 48
30c8a3
+            ecdsa_x = keyptr[0:octets]
30c8a3
+            ecdsa_y = keyptr[octets:octets * 2]
30c8a3
+            try:
30c8a3
+                public_key = ec.EllipticCurvePublicNumbers(
30c8a3
+                    curve=curve,
30c8a3
+                    x=_bytes_to_long(ecdsa_x),
30c8a3
+                    y=_bytes_to_long(ecdsa_y)).public_key(default_backend())
30c8a3
+            except ValueError:
30c8a3
+                raise ValidationFailure('invalid public key')
30c8a3
+            sig_r = rrsig.signature[0:octets]
30c8a3
+            sig_s = rrsig.signature[octets:]
30c8a3
+            sig = utils.encode_dss_signature(_bytes_to_long(sig_r),
30c8a3
+                                             _bytes_to_long(sig_s))
30c8a3
30c8a3
         else:
30c8a3
             raise ValidationFailure('unknown algorithm %u' % rrsig.algorithm)
30c8a3
30c8a3
-        hash.update(_to_rdata(rrsig, origin)[:18])
30c8a3
-        hash.update(rrsig.signer.to_digestable(origin))
30c8a3
+        data = b''
30c8a3
+        data += _to_rdata(rrsig, origin)[:18]
30c8a3
+        data += rrsig.signer.to_digestable(origin)
30c8a3
30c8a3
         if rrsig.labels < len(rrname) - 1:
30c8a3
             suffix = rrname.split(rrsig.labels + 1)[1]
30c8a3
@@ -391,25 +403,21 @@ def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
30c8a3
                               rrsig.original_ttl)
30c8a3
         rrlist = sorted(rdataset)
30c8a3
         for rr in rrlist:
30c8a3
-            hash.update(rrnamebuf)
30c8a3
-            hash.update(rrfixed)
30c8a3
+            data += rrnamebuf
30c8a3
+            data += rrfixed
30c8a3
             rrdata = rr.to_digestable(origin)
30c8a3
             rrlen = struct.pack('!H', len(rrdata))
30c8a3
-            hash.update(rrlen)
30c8a3
-            hash.update(rrdata)
30c8a3
+            data += rrlen
30c8a3
+            data += rrdata
30c8a3
30c8a3
+        chosen_hash = _make_hash(rrsig.algorithm)
30c8a3
         try:
30c8a3
             if _is_rsa(rrsig.algorithm):
30c8a3
-                verifier = pkcs1_15.new(pubkey)
30c8a3
-                # will raise ValueError if verify fails:
30c8a3
-                verifier.verify(hash, sig)
30c8a3
+                public_key.verify(sig, data, padding.PKCS1v15(), chosen_hash)
30c8a3
             elif _is_dsa(rrsig.algorithm):
30c8a3
-                verifier = DSS.new(pubkey, 'fips-186-3')
30c8a3
-                verifier.verify(hash, sig)
30c8a3
+                public_key.verify(sig, data, chosen_hash)
30c8a3
             elif _is_ecdsa(rrsig.algorithm):
30c8a3
-                digest = hash.digest()
30c8a3
-                if not pubkey.verify(digest, sig):
30c8a3
-                    raise ValueError
30c8a3
+                public_key.verify(sig, data, ec.ECDSA(chosen_hash))
30c8a3
             else:
30c8a3
                 # Raise here for code clarity; this won't actually ever happen
30c8a3
                 # since if the algorithm is really unknown we'd already have
30c8a3
@@ -417,7 +425,7 @@ def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None):
30c8a3
                 raise ValidationFailure('unknown algorithm %u' % rrsig.algorithm)
30c8a3
             # If we got here, we successfully verified so we can return without error
30c8a3
             return
30c8a3
-        except ValueError:
30c8a3
+        except InvalidSignature:
30c8a3
             # this happens on an individual validation failure
30c8a3
             continue
30c8a3
     # nothing verified -- raise failure:
30c8a3
@@ -472,48 +480,24 @@ def _validate(rrset, rrsigset, keys, origin=None, now=None):
30c8a3
     raise ValidationFailure("no RRSIGs validated")
30c8a3
30c8a3
30c8a3
-def _need_pycrypto(*args, **kwargs):
30c8a3
-    raise NotImplementedError("DNSSEC validation requires pycryptodome/pycryptodomex")
30c8a3
+def _need_pyca(*args, **kwargs):
30c8a3
+    raise NotImplementedError("DNSSEC validation requires python cryptography")
30c8a3
30c8a3
30c8a3
 try:
30c8a3
-    try:
30c8a3
-        # test we're using pycryptodome, not pycrypto (which misses SHA1 for example)
30c8a3
-        from Crypto.Hash import MD5, SHA1, SHA256, SHA384, SHA512
30c8a3
-        from Crypto.PublicKey import RSA as CryptoRSA, DSA as CryptoDSA
30c8a3
-        from Crypto.Signature import pkcs1_15, DSS
30c8a3
-        from Crypto.Util import number
30c8a3
-    except ImportError:
30c8a3
-        from Cryptodome.Hash import MD5, SHA1, SHA256, SHA384, SHA512
30c8a3
-        from Cryptodome.PublicKey import RSA as CryptoRSA, DSA as CryptoDSA
30c8a3
-        from Cryptodome.Signature import pkcs1_15, DSS
30c8a3
-        from Cryptodome.Util import number
30c8a3
+    from cryptography.exceptions import InvalidSignature
30c8a3
+    from cryptography.hazmat.backends import default_backend
30c8a3
+    from cryptography.hazmat.primitives import hashes
30c8a3
+    from cryptography.hazmat.primitives.asymmetric import padding
30c8a3
+    from cryptography.hazmat.primitives.asymmetric import utils
30c8a3
+    from cryptography.hazmat.primitives.asymmetric import dsa
30c8a3
+    from cryptography.hazmat.primitives.asymmetric import ec
30c8a3
+    from cryptography.hazmat.primitives.asymmetric import rsa
30c8a3
 except ImportError:
30c8a3
-    validate = _need_pycrypto
30c8a3
-    validate_rrsig = _need_pycrypto
30c8a3
-    _have_pycrypto = False
30c8a3
-    _have_ecdsa = False
30c8a3
+    validate = _need_pyca
30c8a3
+    validate_rrsig = _need_pyca
30c8a3
+    _have_pyca = False
30c8a3
 else:
30c8a3
     validate = _validate
30c8a3
     validate_rrsig = _validate_rrsig
30c8a3
-    _have_pycrypto = True
30c8a3
-
30c8a3
-    try:
30c8a3
-        import ecdsa
30c8a3
-        import ecdsa.ecdsa
30c8a3
-        import ecdsa.ellipticcurve
30c8a3
-        import ecdsa.keys
30c8a3
-    except ImportError:
30c8a3
-        _have_ecdsa = False
30c8a3
-    else:
30c8a3
-        _have_ecdsa = True
30c8a3
-
30c8a3
-        class ECKeyWrapper(object):
30c8a3
-
30c8a3
-            def __init__(self, key, key_len):
30c8a3
-                self.key = key
30c8a3
-                self.key_len = key_len
30c8a3
-
30c8a3
-            def verify(self, digest, sig):
30c8a3
-                diglong = number.bytes_to_long(digest)
30c8a3
-                return self.key.pubkey.verifies(diglong, sig)
30c8a3
+    _have_pyca = True
30c8a3
diff --git a/setup.py b/setup.py
30c8a3
index 743d43c..2ee38a7 100755
30c8a3
--- a/setup.py
30c8a3
+++ b/setup.py
30c8a3
@@ -75,7 +75,7 @@ direct manipulation of DNS zones, messages, names, and records.""",
30c8a3
     'provides': ['dns'],
30c8a3
     'extras_require': {
30c8a3
         'IDNA': ['idna>=2.1'],
30c8a3
-        'DNSSEC': ['pycryptodome', 'ecdsa>=0.13'],
30c8a3
+        'DNSSEC': ['cryptography>=2.3'],
30c8a3
         },
30c8a3
     'ext_modules': ext_modules if compile_cython else None,
30c8a3
     'zip_safe': False if compile_cython else None,
30c8a3
diff --git a/tests/test_dnssec.py b/tests/test_dnssec.py
30c8a3
index c87862a..20b52b2 100644
30c8a3
--- a/tests/test_dnssec.py
30c8a3
+++ b/tests/test_dnssec.py
30c8a3
@@ -151,8 +151,8 @@ abs_ecdsa384_soa_rrsig = dns.rrset.from_text('example.', 86400, 'IN', 'RRSIG',
30c8a3
30c8a3
30c8a3
30c8a3
-@unittest.skipUnless(dns.dnssec._have_pycrypto,
30c8a3
-                     "Pycryptodome cannot be imported")
30c8a3
+@unittest.skipUnless(dns.dnssec._have_pyca,
30c8a3
+                     "Python Cryptography cannot be imported")
30c8a3
 class DNSSECValidatorTestCase(unittest.TestCase):
30c8a3
30c8a3
     def testAbsoluteRSAGood(self): # type: () -> None
30c8a3
@@ -199,28 +199,20 @@ class DNSSECValidatorTestCase(unittest.TestCase):
30c8a3
         ds = dns.dnssec.make_ds(abs_example, example_sep_key, 'SHA256')
30c8a3
         self.failUnless(ds == example_ds_sha256)
30c8a3
30c8a3
-    @unittest.skipUnless(dns.dnssec._have_ecdsa,
30c8a3
-                         "python ECDSA cannot be imported")
30c8a3
     def testAbsoluteECDSA256Good(self): # type: () -> None
30c8a3
         dns.dnssec.validate(abs_ecdsa256_soa, abs_ecdsa256_soa_rrsig,
30c8a3
                             abs_ecdsa256_keys, None, when3)
30c8a3
30c8a3
-    @unittest.skipUnless(dns.dnssec._have_ecdsa,
30c8a3
-                         "python ECDSA cannot be imported")
30c8a3
     def testAbsoluteECDSA256Bad(self): # type: () -> None
30c8a3
         def bad(): # type: () -> None
30c8a3
             dns.dnssec.validate(abs_other_ecdsa256_soa, abs_ecdsa256_soa_rrsig,
30c8a3
                                 abs_ecdsa256_keys, None, when3)
30c8a3
         self.failUnlessRaises(dns.dnssec.ValidationFailure, bad)
30c8a3
30c8a3
-    @unittest.skipUnless(dns.dnssec._have_ecdsa,
30c8a3
-                         "python ECDSA cannot be imported")
30c8a3
     def testAbsoluteECDSA384Good(self): # type: () -> None
30c8a3
         dns.dnssec.validate(abs_ecdsa384_soa, abs_ecdsa384_soa_rrsig,
30c8a3
                             abs_ecdsa384_keys, None, when4)
30c8a3
30c8a3
-    @unittest.skipUnless(dns.dnssec._have_ecdsa,
30c8a3
-                         "python ECDSA cannot be imported")
30c8a3
     def testAbsoluteECDSA384Bad(self): # type: () -> None
30c8a3
         def bad(): # type: () -> None
30c8a3
             dns.dnssec.validate(abs_other_ecdsa384_soa, abs_ecdsa384_soa_rrsig,
30c8a3
--
30c8a3
2.26.2
30c8a3