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