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