tba-protocol-dns 0.4.0.dev5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tba_protocol_dns/__init__.py +1 -0
- tba_protocol_dns/ddr.py +7 -0
- tba_protocol_dns/dnssec.py +1029 -0
- tba_protocol_dns/dnssecalgs/__init__.py +65 -0
- tba_protocol_dns/dnssecalgs/_native.py +82 -0
- tba_protocol_dns/dnssecalgs/base.py +80 -0
- tba_protocol_dns/dnssecalgs/cryptography.py +56 -0
- tba_protocol_dns/dnssecalgs/dsa.py +15 -0
- tba_protocol_dns/dnssecalgs/ecdsa.py +17 -0
- tba_protocol_dns/dnssecalgs/eddsa.py +15 -0
- tba_protocol_dns/dnssecalgs/mldsa.py +14 -0
- tba_protocol_dns/dnssecalgs/rsa.py +19 -0
- tba_protocol_dns/gss_tsig.py +103 -0
- tba_protocol_dns/py.typed +0 -0
- tba_protocol_dns/update.py +198 -0
- tba_protocol_dns/xfr.py +794 -0
- tba_protocol_dns/zonemd.py +7 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/METADATA +348 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/RECORD +23 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/WHEEL +4 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/entry_points.txt +5 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/licenses/LICENSE +201 -0
- tba_protocol_dns-0.4.0.dev5.dist-info/licenses/NOTICE +10 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Registry of DNSSEC signing algorithms, including private-use algorithms."""
|
|
2
|
+
|
|
3
|
+
from tba_primitives_dns_name.name import Name, from_text, from_wire
|
|
4
|
+
|
|
5
|
+
from . import dsa, ecdsa, eddsa, mldsa, rsa
|
|
6
|
+
from .base import (
|
|
7
|
+
GenericPrivateKey as GenericPrivateKey,
|
|
8
|
+
GenericPublicKey as GenericPublicKey,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
AlgorithmPrefix = bytes | Name | None
|
|
12
|
+
algorithms: dict[tuple[int, AlgorithmPrefix], type[GenericPrivateKey]] = {
|
|
13
|
+
(cls.public_cls.algorithm, None): cls
|
|
14
|
+
for module in (rsa, dsa, ecdsa, eddsa, mldsa)
|
|
15
|
+
for name, cls in vars(module).items()
|
|
16
|
+
if name.startswith("Private")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get_algorithm_cls(algorithm, prefix=None):
|
|
21
|
+
"""Return the registered private key class for an algorithm and prefix."""
|
|
22
|
+
from ..dnssec import UnsupportedAlgorithm, algorithm_from_text
|
|
23
|
+
|
|
24
|
+
number = algorithm_from_text(algorithm)
|
|
25
|
+
try:
|
|
26
|
+
return algorithms[number, prefix]
|
|
27
|
+
except KeyError as exc:
|
|
28
|
+
raise UnsupportedAlgorithm(
|
|
29
|
+
f"unsupported DNSSEC key algorithm {algorithm}"
|
|
30
|
+
) from exc
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_algorithm_cls_from_dnskey(dnskey):
|
|
34
|
+
"""Look up the algorithm implementation identified by a DNSKEY."""
|
|
35
|
+
from ..dnssec import Algorithm, UnsupportedAlgorithm
|
|
36
|
+
|
|
37
|
+
prefix = None
|
|
38
|
+
if dnskey.algorithm == Algorithm.PRIVATEDNS:
|
|
39
|
+
prefix, _ = from_wire(dnskey.key)
|
|
40
|
+
elif dnskey.algorithm == Algorithm.PRIVATEOID:
|
|
41
|
+
if not dnskey.key or len(dnskey.key) <= dnskey.key[0]:
|
|
42
|
+
raise UnsupportedAlgorithm("invalid PRIVATEOID DNSKEY prefix")
|
|
43
|
+
prefix = dnskey.key[: dnskey.key[0] + 1]
|
|
44
|
+
return get_algorithm_cls(dnskey.algorithm, prefix)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def register_algorithm_cls(algorithm, algorithm_cls, name=None, oid=None):
|
|
48
|
+
"""Register a private key implementation and its optional private-use prefix."""
|
|
49
|
+
from ..dnssec import Algorithm, algorithm_from_text
|
|
50
|
+
|
|
51
|
+
if not issubclass(algorithm_cls, GenericPrivateKey):
|
|
52
|
+
raise TypeError("invalid DNSSEC algorithm class")
|
|
53
|
+
number = algorithm_from_text(algorithm)
|
|
54
|
+
prefix = None
|
|
55
|
+
if number == Algorithm.PRIVATEDNS:
|
|
56
|
+
if name is None:
|
|
57
|
+
raise ValueError("PRIVATEDNS requires a name")
|
|
58
|
+
prefix = from_text(name) if isinstance(name, str) else name
|
|
59
|
+
elif number == Algorithm.PRIVATEOID:
|
|
60
|
+
if oid is None:
|
|
61
|
+
raise ValueError("PRIVATEOID requires an OID")
|
|
62
|
+
prefix = bytes((len(oid),)) + oid
|
|
63
|
+
elif name or oid:
|
|
64
|
+
raise ValueError("DNS names and OIDs require a private-use algorithm")
|
|
65
|
+
algorithms[number, prefix] = algorithm_cls
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Adapters from the DNSSEC key contracts to the native implementations."""
|
|
2
|
+
|
|
3
|
+
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
|
4
|
+
|
|
5
|
+
from .cryptography import CryptographyPrivateKey, CryptographyPublicKey
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from cryptography.hazmat.primitives.asymmetric import mldsa
|
|
9
|
+
except ImportError:
|
|
10
|
+
mldsa = None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NativePublicKey(CryptographyPublicKey):
|
|
14
|
+
@classmethod
|
|
15
|
+
def from_dnskey(cls, key):
|
|
16
|
+
from ..dnssec import _public_key
|
|
17
|
+
|
|
18
|
+
cls._ensure_algorithm_key_combination(key)
|
|
19
|
+
return cls(_public_key(cls.algorithm, key.key))
|
|
20
|
+
|
|
21
|
+
def encode_key_bytes(self):
|
|
22
|
+
from ..dnssec import _native_dnskey_data
|
|
23
|
+
|
|
24
|
+
return _native_dnskey_data(self.key, self.algorithm)
|
|
25
|
+
|
|
26
|
+
def verify(self, signature, data):
|
|
27
|
+
from ..dnssec import _native_verify
|
|
28
|
+
|
|
29
|
+
_native_verify(
|
|
30
|
+
self.key, signature, data, self.algorithm, self.encode_key_bytes()
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class NativePrivateKey(CryptographyPrivateKey):
|
|
35
|
+
def sign(self, data, verify=False, deterministic=True):
|
|
36
|
+
from ..dnssec import _native_sign
|
|
37
|
+
|
|
38
|
+
public = self.public_key()
|
|
39
|
+
signature = _native_sign(
|
|
40
|
+
self.key, data, public.algorithm, public.encode_key_bytes(), deterministic
|
|
41
|
+
)
|
|
42
|
+
if verify:
|
|
43
|
+
public.verify(signature, data)
|
|
44
|
+
return signature
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def generate(cls, *args, **kwargs):
|
|
48
|
+
return cls(cls.generate_key(*args, **kwargs))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def rsa_key(key_size, public_exponent=65537):
|
|
52
|
+
return rsa.generate_private_key(public_exponent, key_size)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def ec_key(curve):
|
|
56
|
+
def generate():
|
|
57
|
+
return ec.generate_private_key(curve())
|
|
58
|
+
|
|
59
|
+
return generate
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def implementations(module, definitions, public_type, private_type, generate):
|
|
63
|
+
"""Create named public and private wrappers sharing a native key format."""
|
|
64
|
+
public = {}
|
|
65
|
+
private = {}
|
|
66
|
+
for number, name in definitions.items():
|
|
67
|
+
public["Public" + name] = type(
|
|
68
|
+
"Public" + name,
|
|
69
|
+
(NativePublicKey,),
|
|
70
|
+
{"algorithm": number, "key_cls": public_type, "__module__": module},
|
|
71
|
+
)
|
|
72
|
+
private["Private" + name] = type(
|
|
73
|
+
"Private" + name,
|
|
74
|
+
(NativePrivateKey,),
|
|
75
|
+
{
|
|
76
|
+
"public_cls": public["Public" + name],
|
|
77
|
+
"key_cls": private_type,
|
|
78
|
+
"generate_key": staticmethod(generate),
|
|
79
|
+
"__module__": module,
|
|
80
|
+
},
|
|
81
|
+
)
|
|
82
|
+
return public | private
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Public interfaces for DNSSEC key formats and signature algorithms."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
from tba_codec_dns.rdtypes.ANY.DNSKEY import DNSKEY
|
|
6
|
+
from tba_codec_dns.wire import RecordClass, RecordType
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class GenericPublicKey(ABC):
|
|
10
|
+
algorithm: int
|
|
11
|
+
|
|
12
|
+
@abstractmethod
|
|
13
|
+
def __init__(self, key):
|
|
14
|
+
"""Accept a public key in the implementation's native representation."""
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
@abstractmethod
|
|
18
|
+
def from_dnskey(cls, key):
|
|
19
|
+
"""Construct a public key from DNSKEY RDATA."""
|
|
20
|
+
|
|
21
|
+
@abstractmethod
|
|
22
|
+
def encode_key_bytes(self):
|
|
23
|
+
"""Encode the DNSKEY public key field."""
|
|
24
|
+
|
|
25
|
+
@abstractmethod
|
|
26
|
+
def verify(self, signature, data):
|
|
27
|
+
"""Verify a DNSSEC signature or raise an invalid-signature exception."""
|
|
28
|
+
|
|
29
|
+
def to_dnskey(self, flags=256, protocol=3):
|
|
30
|
+
if not 0 <= flags <= 65535 or not 0 <= protocol <= 255:
|
|
31
|
+
raise ValueError("DNSKEY flags or protocol outside its wire range")
|
|
32
|
+
return DNSKEY(
|
|
33
|
+
RecordClass.IN,
|
|
34
|
+
RecordType.DNSKEY,
|
|
35
|
+
int(flags),
|
|
36
|
+
int(protocol),
|
|
37
|
+
int(self.algorithm),
|
|
38
|
+
self.encode_key_bytes(),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def _ensure_algorithm_key_combination(cls, key):
|
|
43
|
+
from ..dnssec import AlgorithmKeyMismatch
|
|
44
|
+
|
|
45
|
+
if key.algorithm != cls.algorithm:
|
|
46
|
+
raise AlgorithmKeyMismatch("DNSKEY does not match its DNSSEC algorithm")
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
@abstractmethod
|
|
50
|
+
def from_pem(cls, public_pem):
|
|
51
|
+
"""Read a PEM SubjectPublicKeyInfo public key."""
|
|
52
|
+
|
|
53
|
+
@abstractmethod
|
|
54
|
+
def to_pem(self):
|
|
55
|
+
"""Write a PEM SubjectPublicKeyInfo public key."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class GenericPrivateKey(ABC):
|
|
59
|
+
public_cls: type[GenericPublicKey]
|
|
60
|
+
|
|
61
|
+
@abstractmethod
|
|
62
|
+
def __init__(self, key):
|
|
63
|
+
"""Accept a private key in the implementation's native representation."""
|
|
64
|
+
|
|
65
|
+
@abstractmethod
|
|
66
|
+
def sign(self, data, verify=False, deterministic=True):
|
|
67
|
+
"""Sign canonical DNSSEC data."""
|
|
68
|
+
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def public_key(self):
|
|
71
|
+
"""Return the associated DNSSEC public key."""
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
@abstractmethod
|
|
75
|
+
def from_pem(cls, private_pem, password=None):
|
|
76
|
+
"""Read a PEM PKCS#8 private key."""
|
|
77
|
+
|
|
78
|
+
@abstractmethod
|
|
79
|
+
def to_pem(self, password=None):
|
|
80
|
+
"""Write a PEM PKCS#8 private key."""
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""DNSSEC key adapters for cryptography-backed algorithms."""
|
|
2
|
+
|
|
3
|
+
from cryptography.hazmat.primitives import serialization
|
|
4
|
+
|
|
5
|
+
from .base import GenericPrivateKey, GenericPublicKey
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _check_key_type(key, expected):
|
|
9
|
+
from ..dnssec import AlgorithmKeyMismatch
|
|
10
|
+
|
|
11
|
+
if expected is None:
|
|
12
|
+
raise TypeError("DNSSEC key type must be specified")
|
|
13
|
+
if not isinstance(key, expected):
|
|
14
|
+
raise AlgorithmKeyMismatch("key does not match its DNSSEC algorithm")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CryptographyPublicKey(GenericPublicKey):
|
|
18
|
+
key_cls = None
|
|
19
|
+
|
|
20
|
+
def __init__(self, key):
|
|
21
|
+
_check_key_type(key, self.key_cls)
|
|
22
|
+
self.key = key
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def from_pem(cls, public_pem):
|
|
26
|
+
return cls(key=serialization.load_pem_public_key(public_pem))
|
|
27
|
+
|
|
28
|
+
def to_pem(self):
|
|
29
|
+
return self.key.public_bytes(
|
|
30
|
+
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class CryptographyPrivateKey(GenericPrivateKey):
|
|
35
|
+
key_cls = None
|
|
36
|
+
|
|
37
|
+
def __init__(self, key):
|
|
38
|
+
_check_key_type(key, self.key_cls)
|
|
39
|
+
self.key = key
|
|
40
|
+
|
|
41
|
+
def public_key(self):
|
|
42
|
+
return self.public_cls(key=self.key.public_key())
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_pem(cls, private_pem, password=None):
|
|
46
|
+
return cls(key=serialization.load_pem_private_key(private_pem, password))
|
|
47
|
+
|
|
48
|
+
def to_pem(self, password=None):
|
|
49
|
+
encryption = (
|
|
50
|
+
serialization.BestAvailableEncryption(password)
|
|
51
|
+
if password
|
|
52
|
+
else serialization.NoEncryption()
|
|
53
|
+
)
|
|
54
|
+
return self.key.private_bytes(
|
|
55
|
+
serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, encryption
|
|
56
|
+
)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""DNSSEC DSA key implementations."""
|
|
2
|
+
|
|
3
|
+
from cryptography.hazmat.primitives.asymmetric import dsa
|
|
4
|
+
|
|
5
|
+
from ._native import implementations
|
|
6
|
+
|
|
7
|
+
globals().update(
|
|
8
|
+
implementations(
|
|
9
|
+
__name__,
|
|
10
|
+
{3: "DSA", 6: "DSANSEC3SHA1"},
|
|
11
|
+
dsa.DSAPublicKey,
|
|
12
|
+
dsa.DSAPrivateKey,
|
|
13
|
+
dsa.generate_private_key,
|
|
14
|
+
)
|
|
15
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""DNSSEC ECDSA key implementations."""
|
|
2
|
+
|
|
3
|
+
from ._native import ec, ec_key, implementations
|
|
4
|
+
|
|
5
|
+
for _number, _name, _curve in (
|
|
6
|
+
(13, "ECDSAP256SHA256", ec.SECP256R1),
|
|
7
|
+
(14, "ECDSAP384SHA384", ec.SECP384R1),
|
|
8
|
+
):
|
|
9
|
+
globals().update(
|
|
10
|
+
implementations(
|
|
11
|
+
__name__,
|
|
12
|
+
{_number: _name},
|
|
13
|
+
ec.EllipticCurvePublicKey,
|
|
14
|
+
ec.EllipticCurvePrivateKey,
|
|
15
|
+
ec_key(_curve),
|
|
16
|
+
)
|
|
17
|
+
)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""DNSSEC EdDSA key implementations."""
|
|
2
|
+
|
|
3
|
+
from cryptography.hazmat.primitives.asymmetric import ed448, ed25519
|
|
4
|
+
|
|
5
|
+
from ._native import implementations
|
|
6
|
+
|
|
7
|
+
for _number, _name, _public, _private in (
|
|
8
|
+
(15, "ED25519", ed25519.Ed25519PublicKey, ed25519.Ed25519PrivateKey),
|
|
9
|
+
(16, "ED448", ed448.Ed448PublicKey, ed448.Ed448PrivateKey),
|
|
10
|
+
):
|
|
11
|
+
globals().update(
|
|
12
|
+
implementations(
|
|
13
|
+
__name__, {_number: _name}, _public, _private, _private.generate
|
|
14
|
+
)
|
|
15
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""DNSSEC ML-DSA key implementation."""
|
|
2
|
+
|
|
3
|
+
from ._native import implementations, mldsa
|
|
4
|
+
|
|
5
|
+
if mldsa is not None:
|
|
6
|
+
globals().update(
|
|
7
|
+
implementations(
|
|
8
|
+
__name__,
|
|
9
|
+
{18: "MLDSA44"},
|
|
10
|
+
mldsa.MLDSA44PublicKey,
|
|
11
|
+
mldsa.MLDSA44PrivateKey,
|
|
12
|
+
mldsa.MLDSA44PrivateKey.generate,
|
|
13
|
+
)
|
|
14
|
+
)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""DNSSEC RSA key implementations."""
|
|
2
|
+
|
|
3
|
+
from ._native import implementations, rsa, rsa_key
|
|
4
|
+
|
|
5
|
+
globals().update(
|
|
6
|
+
implementations(
|
|
7
|
+
__name__,
|
|
8
|
+
{
|
|
9
|
+
1: "RSAMD5",
|
|
10
|
+
5: "RSASHA1",
|
|
11
|
+
7: "RSASHA1NSEC3SHA1",
|
|
12
|
+
8: "RSASHA256",
|
|
13
|
+
10: "RSASHA512",
|
|
14
|
+
},
|
|
15
|
+
rsa.RSAPublicKey,
|
|
16
|
+
rsa.RSAPrivateKey,
|
|
17
|
+
rsa_key,
|
|
18
|
+
)
|
|
19
|
+
)
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Client-side GSS-TSIG negotiation using a caller's GSS context (RFC 3645)."""
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from tba_codec_dns.tkey import Tkey
|
|
10
|
+
from tba_codec_dns.tsig import GssContext, GssTsigKey, TsigError, verify
|
|
11
|
+
from tba_codec_dns.wire import Message, Question, RecordClass, RecordType
|
|
12
|
+
from tba_primitives_dns_name.names import parse_name
|
|
13
|
+
from tba_provider_dns_resolver.async_transport import run_blocking
|
|
14
|
+
from tba_provider_dns_resolver.transport import deadline_after, remaining, tcp_query
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class InitiatorContext(GssContext, Protocol):
|
|
18
|
+
@property
|
|
19
|
+
def complete(self) -> bool: ...
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def actual_flags(self) -> Iterable[int]: ...
|
|
23
|
+
|
|
24
|
+
def step(self, token: bytes | None) -> bytes | None: ...
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _advance(context: InitiatorContext, token: bytes | None) -> bytes | None:
|
|
28
|
+
try:
|
|
29
|
+
output = context.step(token)
|
|
30
|
+
if context.complete and not {2, 4, 32}.issubset(map(int, context.actual_flags)):
|
|
31
|
+
raise TsigError(
|
|
32
|
+
"GSS context requires mutual authentication, replay detection, and integrity"
|
|
33
|
+
)
|
|
34
|
+
return output
|
|
35
|
+
except TsigError:
|
|
36
|
+
raise
|
|
37
|
+
except Exception as exc:
|
|
38
|
+
raise TsigError("could not establish the GSS-TSIG security context") from exc
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def negotiate(
|
|
42
|
+
server: str,
|
|
43
|
+
context: InitiatorContext,
|
|
44
|
+
*,
|
|
45
|
+
port: int = 53,
|
|
46
|
+
timeout: float = 10,
|
|
47
|
+
name: str | None = None,
|
|
48
|
+
) -> GssTsigKey:
|
|
49
|
+
"""Establish a mutually authenticated GSS-TSIG key with a DNS server."""
|
|
50
|
+
owner = parse_name(
|
|
51
|
+
f"{uuid4().hex}.gss-tsig." if name is None else name, canonical=True
|
|
52
|
+
)
|
|
53
|
+
key = GssTsigKey(owner, context)
|
|
54
|
+
deadline = deadline_after(timeout)
|
|
55
|
+
question = Question(owner, RecordType.TKEY, RecordClass.ANY)
|
|
56
|
+
token = _advance(context, None)
|
|
57
|
+
for _ in range(10):
|
|
58
|
+
if not token:
|
|
59
|
+
raise TsigError("GSS context produced no TKEY negotiation token")
|
|
60
|
+
now = int(time.time())
|
|
61
|
+
record = Tkey(key.algorithm, now, now + 3600, 3, key=token).record(owner)
|
|
62
|
+
query = Message(secrets.randbits(16), 0, (question,), additional=(record,))
|
|
63
|
+
response = tcp_query(query, server, port=port, timeout=remaining(deadline))
|
|
64
|
+
if response.rcode:
|
|
65
|
+
raise TsigError(
|
|
66
|
+
f"TKEY negotiation failed with DNS response code {response.rcode}"
|
|
67
|
+
)
|
|
68
|
+
answers = [
|
|
69
|
+
rr
|
|
70
|
+
for rr in response.answers
|
|
71
|
+
if rr.type == RecordType.TKEY
|
|
72
|
+
and rr.name == owner
|
|
73
|
+
and rr.rdclass == RecordClass.ANY
|
|
74
|
+
]
|
|
75
|
+
if len(answers) != 1:
|
|
76
|
+
raise TsigError("TKEY negotiation requires one answer for its key name")
|
|
77
|
+
answer = Tkey.from_wire(answers[0].data)
|
|
78
|
+
if (
|
|
79
|
+
tuple(label.lower() for label in answer.algorithm) != key.algorithm
|
|
80
|
+
or answer.mode != 3
|
|
81
|
+
):
|
|
82
|
+
raise TsigError("unexpected GSS-TSIG negotiation algorithm or mode")
|
|
83
|
+
if answer.error:
|
|
84
|
+
raise TsigError(
|
|
85
|
+
f"GSS-TSIG negotiation failed with TKEY error {answer.error}"
|
|
86
|
+
)
|
|
87
|
+
token = None if context.complete else _advance(context, answer.key or None)
|
|
88
|
+
signed = any(rr.type == RecordType.TSIG for rr in response.additional)
|
|
89
|
+
if context.complete and signed:
|
|
90
|
+
verify(response.to_wire(), key)
|
|
91
|
+
if context.complete and not token:
|
|
92
|
+
if not signed:
|
|
93
|
+
raise TsigError(
|
|
94
|
+
"completed GSS-TSIG negotiation requires a signed TKEY response"
|
|
95
|
+
)
|
|
96
|
+
return key
|
|
97
|
+
raise TsigError("GSS-TSIG negotiation exceeded ten token exchanges")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
async def negotiate_async(
|
|
101
|
+
server: str, context: InitiatorContext, **kwargs
|
|
102
|
+
) -> GssTsigKey:
|
|
103
|
+
return await run_blocking(negotiate, server, context, **kwargs)
|
|
File without changes
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Build and send RFC 2136 DNS UPDATE requests."""
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import ssl
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
|
|
7
|
+
from tba_codec_dns.message import UpdateMessage as UpdateMessage
|
|
8
|
+
from tba_codec_dns.rdata import Rdata
|
|
9
|
+
from tba_codec_dns.rdata import from_text as parse_rdata
|
|
10
|
+
from tba_codec_dns.rdataset import Rdataset
|
|
11
|
+
from tba_codec_dns.tsig import AuthKey, sign, verify
|
|
12
|
+
from tba_codec_dns.wire import (
|
|
13
|
+
Message,
|
|
14
|
+
Question,
|
|
15
|
+
RecordClass,
|
|
16
|
+
RecordType,
|
|
17
|
+
ResourceRecord,
|
|
18
|
+
record_class,
|
|
19
|
+
record_type,
|
|
20
|
+
)
|
|
21
|
+
from tba_primitives_dns_name.name import Name as DomainName
|
|
22
|
+
from tba_primitives_dns_name.names import Name, is_subdomain, parse_name
|
|
23
|
+
from tba_provider_dns_resolver.async_transport import run_blocking
|
|
24
|
+
from tba_provider_dns_resolver.transport import (
|
|
25
|
+
check_response,
|
|
26
|
+
deadline_after,
|
|
27
|
+
exchange_udp_packet,
|
|
28
|
+
stream,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Update:
|
|
33
|
+
def __init__(self, zone: str | DomainName, *, rdclass: int | str = RecordClass.IN):
|
|
34
|
+
self.zone = parse_name(str(zone), canonical=True)
|
|
35
|
+
self.rdclass = record_class(rdclass)
|
|
36
|
+
if self.rdclass in (0, RecordClass.NONE, RecordClass.ANY):
|
|
37
|
+
raise ValueError("UPDATE requires a concrete zone class")
|
|
38
|
+
self.prerequisites: list[ResourceRecord] = []
|
|
39
|
+
self.changes: list[ResourceRecord] = []
|
|
40
|
+
|
|
41
|
+
def _owner(self, name: str | Name | DomainName) -> Name:
|
|
42
|
+
if isinstance(name, DomainName):
|
|
43
|
+
name = name.to_text()
|
|
44
|
+
owner = (
|
|
45
|
+
parse_name(name, self.zone, canonical=True)
|
|
46
|
+
if isinstance(name, str)
|
|
47
|
+
else name
|
|
48
|
+
)
|
|
49
|
+
if not is_subdomain(owner, self.zone):
|
|
50
|
+
raise ValueError("UPDATE owner is outside the zone")
|
|
51
|
+
return owner
|
|
52
|
+
|
|
53
|
+
def _placeholder(
|
|
54
|
+
self, name: str | Name, kind: int | str, rdclass: int
|
|
55
|
+
) -> ResourceRecord:
|
|
56
|
+
return ResourceRecord(self._owner(name), record_type(kind), rdclass, 0, b"")
|
|
57
|
+
|
|
58
|
+
def _record(self, record: ResourceRecord) -> ResourceRecord:
|
|
59
|
+
self._owner(record.name)
|
|
60
|
+
if record.rdclass != self.rdclass or record.type in (
|
|
61
|
+
RecordType.ANY,
|
|
62
|
+
RecordType.AXFR,
|
|
63
|
+
RecordType.IXFR,
|
|
64
|
+
RecordType.OPT,
|
|
65
|
+
RecordType.TSIG,
|
|
66
|
+
RecordType.TKEY,
|
|
67
|
+
):
|
|
68
|
+
raise ValueError("record class or type cannot be used for UPDATE")
|
|
69
|
+
return record
|
|
70
|
+
|
|
71
|
+
def _values(
|
|
72
|
+
self, name: str | Name | DomainName, values: tuple, ttl: int
|
|
73
|
+
) -> tuple[ResourceRecord, ...]:
|
|
74
|
+
owner = self._owner(name)
|
|
75
|
+
if isinstance(values[0], Rdata):
|
|
76
|
+
return tuple(self._record(value.record(owner, ttl)) for value in values)
|
|
77
|
+
kind, *text = values
|
|
78
|
+
if not text:
|
|
79
|
+
raise ValueError("DNS update requires at least one RDATA value")
|
|
80
|
+
origin = DomainName((*self.zone, b""))
|
|
81
|
+
return tuple(
|
|
82
|
+
self._record(
|
|
83
|
+
parse_rdata(self.rdclass, kind, value, origin).record(owner, ttl)
|
|
84
|
+
)
|
|
85
|
+
for value in text
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def _records(self, arguments: tuple) -> tuple[ResourceRecord, ...]:
|
|
89
|
+
if not arguments or isinstance(arguments[0], ResourceRecord):
|
|
90
|
+
return tuple(self._record(record) for record in arguments)
|
|
91
|
+
owner, *args = arguments
|
|
92
|
+
if len(args) == 1 and isinstance(args[0], Rdataset):
|
|
93
|
+
return tuple(self._record(rr) for rr in args[0].records(self._owner(owner)))
|
|
94
|
+
if len(args) < 2:
|
|
95
|
+
raise ValueError("DNS update requires records, a dataset, or TTL and RDATA")
|
|
96
|
+
return self._values(owner, tuple(args[1:]), args[0])
|
|
97
|
+
|
|
98
|
+
def present(
|
|
99
|
+
self,
|
|
100
|
+
name: str | Name | DomainName,
|
|
101
|
+
kind: int | str | Rdata | Rdataset = RecordType.ANY,
|
|
102
|
+
*values,
|
|
103
|
+
) -> None:
|
|
104
|
+
if isinstance(kind, Rdataset):
|
|
105
|
+
if values:
|
|
106
|
+
raise ValueError("unexpected RDATA after a DNS dataset")
|
|
107
|
+
self.require_values(*kind.records(self._owner(name)))
|
|
108
|
+
elif values or isinstance(kind, Rdata):
|
|
109
|
+
self.require_values(*self._values(name, (kind, *values), 0))
|
|
110
|
+
else:
|
|
111
|
+
self.prerequisites.append(self._placeholder(name, kind, RecordClass.ANY))
|
|
112
|
+
|
|
113
|
+
def absent(self, name: str | Name, kind: int | str = RecordType.ANY) -> None:
|
|
114
|
+
self.prerequisites.append(self._placeholder(name, kind, RecordClass.NONE))
|
|
115
|
+
|
|
116
|
+
def require_values(self, *records: ResourceRecord) -> None:
|
|
117
|
+
self.prerequisites.extend(
|
|
118
|
+
tuple(replace(self._record(rr), ttl=0) for rr in records)
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
def add(self, *arguments) -> None:
|
|
122
|
+
self.changes.extend(self._records(arguments))
|
|
123
|
+
|
|
124
|
+
def delete(
|
|
125
|
+
self,
|
|
126
|
+
name: str | Name | DomainName,
|
|
127
|
+
kind: int | str | Rdata | Rdataset = RecordType.ANY,
|
|
128
|
+
*values,
|
|
129
|
+
) -> None:
|
|
130
|
+
if isinstance(kind, Rdataset):
|
|
131
|
+
if values:
|
|
132
|
+
raise ValueError("unexpected RDATA after a DNS dataset")
|
|
133
|
+
self.delete_values(*kind.records(self._owner(name)))
|
|
134
|
+
elif values or isinstance(kind, Rdata):
|
|
135
|
+
self.delete_values(*self._values(name, (kind, *values), 0))
|
|
136
|
+
else:
|
|
137
|
+
self.changes.append(self._placeholder(name, kind, RecordClass.ANY))
|
|
138
|
+
|
|
139
|
+
def delete_values(self, *records: ResourceRecord) -> None:
|
|
140
|
+
self.changes.extend(
|
|
141
|
+
tuple(
|
|
142
|
+
replace(self._record(rr), ttl=0, rdclass=RecordClass.NONE)
|
|
143
|
+
for rr in records
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def replace(self, *arguments) -> None:
|
|
148
|
+
accepted = self._records(arguments)
|
|
149
|
+
for owner, kind in dict.fromkeys((rr.name, rr.type) for rr in accepted):
|
|
150
|
+
self.delete(owner, kind)
|
|
151
|
+
self.changes.extend(accepted)
|
|
152
|
+
|
|
153
|
+
def message(self, identifier: int | None = None) -> Message:
|
|
154
|
+
return Message(
|
|
155
|
+
secrets.randbits(16) if identifier is None else identifier,
|
|
156
|
+
5 << 11,
|
|
157
|
+
(Question(self.zone, RecordType.SOA, self.rdclass),),
|
|
158
|
+
tuple(self.prerequisites),
|
|
159
|
+
tuple(self.changes),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def send_update(
|
|
164
|
+
update: Update,
|
|
165
|
+
server: str,
|
|
166
|
+
*,
|
|
167
|
+
port: int = 53,
|
|
168
|
+
timeout: float = 3,
|
|
169
|
+
key: AuthKey | None = None,
|
|
170
|
+
udp: bool = False,
|
|
171
|
+
server_name: str | None = None,
|
|
172
|
+
context: ssl.SSLContext | None = None,
|
|
173
|
+
) -> Message:
|
|
174
|
+
request = update.message()
|
|
175
|
+
packet = request.to_wire()
|
|
176
|
+
request_mac = None
|
|
177
|
+
if key is not None:
|
|
178
|
+
packet, request_mac = sign(packet, key)
|
|
179
|
+
deadline = deadline_after(timeout)
|
|
180
|
+
if udp:
|
|
181
|
+
if server_name is not None or context is not None:
|
|
182
|
+
raise ValueError("DNS UDP updates cannot use a TLS context")
|
|
183
|
+
reply = exchange_udp_packet(request, packet, server, port, deadline, None)
|
|
184
|
+
else:
|
|
185
|
+
with stream(
|
|
186
|
+
server, port, deadline, server_name=server_name, context=context
|
|
187
|
+
) as connection:
|
|
188
|
+
connection.send(packet)
|
|
189
|
+
reply = connection.receive()
|
|
190
|
+
if key is not None:
|
|
191
|
+
verify(reply, key, request_mac=request_mac)
|
|
192
|
+
response = Message.from_wire(reply)
|
|
193
|
+
check_response(request, response, allow_empty_question=True)
|
|
194
|
+
return response
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def send_update_async(update: Update, server: str, **kwargs) -> Message:
|
|
198
|
+
return await run_blocking(send_update, update, server, **kwargs)
|