netk-cli 0.2.0__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.
- netk/__init__.py +70 -0
- netk/__main__.py +10 -0
- netk/cli.py +229 -0
- netk/commands/__init__.py +1 -0
- netk/commands/dns.py +121 -0
- netk/commands/doctor.py +96 -0
- netk/commands/http.py +385 -0
- netk/commands/ping.py +203 -0
- netk/commands/schema.py +187 -0
- netk/commands/tcp.py +67 -0
- netk/commands/tls.py +200 -0
- netk/contract.py +132 -0
- netk/dns/__init__.py +18 -0
- netk/dns/client.py +225 -0
- netk/dns/codec.py +232 -0
- netk/dns/resolver.py +81 -0
- netk/py.typed +0 -0
- netk/render.py +221 -0
- netk/slo.py +74 -0
- netk/targets.py +196 -0
- netk_cli-0.2.0.dist-info/METADATA +238 -0
- netk_cli-0.2.0.dist-info/RECORD +26 -0
- netk_cli-0.2.0.dist-info/WHEEL +5 -0
- netk_cli-0.2.0.dist-info/entry_points.txt +2 -0
- netk_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
- netk_cli-0.2.0.dist-info/top_level.txt +1 -0
netk/dns/client.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""One DNS question over UDP, TCP, DoT or DoH, with truncation and timeout fallbacks.
|
|
2
|
+
|
|
3
|
+
Policy, in order:
|
|
4
|
+
UDP (EDNS0, 1232-byte buffer) -> TCP on timeout -> report a next step in the error.
|
|
5
|
+
A truncated UDP answer is retried over TCP instead of being returned half-empty.
|
|
6
|
+
DoH goes through an opener with proxies disabled, because netk probes the network
|
|
7
|
+
as it actually is, not as ``http_proxy`` wishes it were.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import contextlib
|
|
14
|
+
import socket
|
|
15
|
+
import ssl
|
|
16
|
+
import struct
|
|
17
|
+
import time
|
|
18
|
+
import urllib.error
|
|
19
|
+
import urllib.request
|
|
20
|
+
from urllib.parse import urlsplit
|
|
21
|
+
|
|
22
|
+
from ..contract import RC_TIMEOUT, NetkError
|
|
23
|
+
from .codec import build_query, parse_response
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def dns_query(
|
|
27
|
+
name: str,
|
|
28
|
+
qtype: int,
|
|
29
|
+
server: str,
|
|
30
|
+
port: int = 53,
|
|
31
|
+
use_tcp: bool = False,
|
|
32
|
+
timeout: float = 5.0,
|
|
33
|
+
doh: str | None = None,
|
|
34
|
+
allow_tcp_retry: bool = True,
|
|
35
|
+
*,
|
|
36
|
+
dot: bool = False,
|
|
37
|
+
doh_get: bool = False,
|
|
38
|
+
retries: int = 1,
|
|
39
|
+
) -> dict:
|
|
40
|
+
"""Ask one question and return the parsed message plus transport metadata."""
|
|
41
|
+
_, packet = build_query(name, qtype)
|
|
42
|
+
attempt = 0
|
|
43
|
+
while True:
|
|
44
|
+
try:
|
|
45
|
+
return _exchange(
|
|
46
|
+
name,
|
|
47
|
+
qtype,
|
|
48
|
+
server,
|
|
49
|
+
port,
|
|
50
|
+
use_tcp,
|
|
51
|
+
timeout,
|
|
52
|
+
doh,
|
|
53
|
+
allow_tcp_retry,
|
|
54
|
+
dot,
|
|
55
|
+
doh_get,
|
|
56
|
+
packet,
|
|
57
|
+
)
|
|
58
|
+
except NetkError as exc:
|
|
59
|
+
attempt += 1
|
|
60
|
+
if attempt >= max(1, retries) or exc.rc != RC_TIMEOUT:
|
|
61
|
+
raise
|
|
62
|
+
time.sleep(min(0.2 * attempt, 1.0))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _exchange(
|
|
66
|
+
name, qtype, server, port, use_tcp, timeout, doh, allow_tcp_retry, dot, doh_get, packet
|
|
67
|
+
) -> dict:
|
|
68
|
+
started = time.perf_counter()
|
|
69
|
+
udp_timeout = False
|
|
70
|
+
if doh:
|
|
71
|
+
endpoint = urlsplit(doh)
|
|
72
|
+
data, transport = _doh(packet, doh, timeout, doh_get), "doh"
|
|
73
|
+
server, port = endpoint.hostname or doh, endpoint.port or 443
|
|
74
|
+
elif dot:
|
|
75
|
+
data, transport = _stream(packet, server, port or 853, timeout, tls=True), "dot"
|
|
76
|
+
elif use_tcp:
|
|
77
|
+
data, transport = _stream(packet, server, port, timeout, tls=False), "tcp"
|
|
78
|
+
else:
|
|
79
|
+
try:
|
|
80
|
+
data = _udp(packet, server, port, timeout)
|
|
81
|
+
transport = "udp"
|
|
82
|
+
except socket.timeout:
|
|
83
|
+
if not allow_tcp_retry:
|
|
84
|
+
raise NetkError(
|
|
85
|
+
"timeout", f"DNS query to {server}:{port} timed out", RC_TIMEOUT
|
|
86
|
+
) from None
|
|
87
|
+
try:
|
|
88
|
+
data, transport = _stream(packet, server, port, timeout, tls=False), "tcp"
|
|
89
|
+
udp_timeout = True
|
|
90
|
+
except NetkError as exc:
|
|
91
|
+
raise NetkError(
|
|
92
|
+
"timeout",
|
|
93
|
+
f"no UDP reply from {server}:{port} in {timeout}s; TCP retry failed "
|
|
94
|
+
f"({exc.message}); if this network filters DNS, add "
|
|
95
|
+
f"--doh https://dns.alidns.com/dns-query",
|
|
96
|
+
RC_TIMEOUT,
|
|
97
|
+
) from exc
|
|
98
|
+
|
|
99
|
+
elapsed = time.perf_counter() - started
|
|
100
|
+
parsed = parse_response(data)
|
|
101
|
+
if parsed["flags"]["truncated"] and transport == "udp":
|
|
102
|
+
try:
|
|
103
|
+
parsed = parse_response(_stream(packet, server, port, timeout, tls=False))
|
|
104
|
+
transport = "tcp"
|
|
105
|
+
except NetkError as exc:
|
|
106
|
+
# A truncated answer still beats no answer; say why it is incomplete.
|
|
107
|
+
parsed["truncated_retry_error"] = exc.message
|
|
108
|
+
|
|
109
|
+
if parsed["id"] != struct.unpack("!H", packet[:2])[0]:
|
|
110
|
+
raise NetkError("dns", "response id mismatch")
|
|
111
|
+
|
|
112
|
+
parsed.update(
|
|
113
|
+
{
|
|
114
|
+
"server": server,
|
|
115
|
+
"port": port,
|
|
116
|
+
"transport": transport,
|
|
117
|
+
"query_time_ms": round(elapsed * 1000, 3),
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
if udp_timeout:
|
|
121
|
+
parsed["udp_timeout"] = True
|
|
122
|
+
return parsed
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _udp(packet: bytes, server: str, port: int, timeout: float) -> bytes:
|
|
126
|
+
family = socket.AF_INET6 if ":" in server else socket.AF_INET
|
|
127
|
+
sock = socket.socket(family, socket.SOCK_DGRAM)
|
|
128
|
+
sock.settimeout(timeout)
|
|
129
|
+
query_id = struct.unpack("!H", packet[:2])[0]
|
|
130
|
+
try:
|
|
131
|
+
sock.sendto(packet, (server, port))
|
|
132
|
+
deadline = time.perf_counter() + timeout
|
|
133
|
+
while True:
|
|
134
|
+
remaining = deadline - time.perf_counter()
|
|
135
|
+
if remaining <= 0:
|
|
136
|
+
raise socket.timeout()
|
|
137
|
+
sock.settimeout(remaining)
|
|
138
|
+
try:
|
|
139
|
+
candidate, _ = sock.recvfrom(4096)
|
|
140
|
+
except ConnectionResetError:
|
|
141
|
+
# Windows surfaces ICMP port-unreachable as WSAECONNRESET. Treat
|
|
142
|
+
# it as silence so the TCP retry (and its advice) still runs.
|
|
143
|
+
raise socket.timeout() from None
|
|
144
|
+
if len(candidate) >= 2 and struct.unpack("!H", candidate[:2])[0] == query_id:
|
|
145
|
+
return candidate
|
|
146
|
+
except ConnectionResetError:
|
|
147
|
+
raise socket.timeout() from None
|
|
148
|
+
finally:
|
|
149
|
+
sock.close()
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _stream(packet: bytes, server: str, port: int, timeout: float, tls: bool) -> bytes:
|
|
153
|
+
try:
|
|
154
|
+
raw = socket.create_connection((server, port), timeout=timeout)
|
|
155
|
+
except socket.timeout:
|
|
156
|
+
raise NetkError(
|
|
157
|
+
"timeout", f"TCP connect to {server}:{port} timed out", RC_TIMEOUT
|
|
158
|
+
) from None
|
|
159
|
+
except OSError as exc:
|
|
160
|
+
raise NetkError("connection", f"TCP connect to {server}:{port} failed: {exc}") from exc
|
|
161
|
+
sock = raw
|
|
162
|
+
try:
|
|
163
|
+
if tls:
|
|
164
|
+
context = ssl.create_default_context()
|
|
165
|
+
try:
|
|
166
|
+
sock = context.wrap_socket(raw, server_hostname=server)
|
|
167
|
+
except ssl.SSLError as exc:
|
|
168
|
+
raw.close()
|
|
169
|
+
raise NetkError("tls", f"TLS handshake with {server}:{port} failed: {exc}") from exc
|
|
170
|
+
# after wrap_socket the original socket object is detached: only touch `sock`
|
|
171
|
+
sock.settimeout(timeout)
|
|
172
|
+
sock.sendall(struct.pack("!H", len(packet)) + packet)
|
|
173
|
+
length = struct.unpack("!H", _recv_exact(sock, 2))[0]
|
|
174
|
+
if length == 0:
|
|
175
|
+
raise NetkError("dns", "empty response over TCP")
|
|
176
|
+
return _recv_exact(sock, length)
|
|
177
|
+
except socket.timeout:
|
|
178
|
+
raise NetkError("timeout", f"read from {server}:{port} timed out", RC_TIMEOUT) from None
|
|
179
|
+
except OSError as exc:
|
|
180
|
+
raise NetkError("connection", f"TCP exchange with {server}:{port} failed: {exc}") from exc
|
|
181
|
+
finally:
|
|
182
|
+
with contextlib.suppress(OSError):
|
|
183
|
+
sock.close()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _recv_exact(sock: socket.socket, size: int) -> bytes:
|
|
187
|
+
chunks = b""
|
|
188
|
+
while len(chunks) < size:
|
|
189
|
+
part = sock.recv(size - len(chunks))
|
|
190
|
+
if not part:
|
|
191
|
+
raise NetkError("dns", "connection closed mid-response")
|
|
192
|
+
chunks += part
|
|
193
|
+
return chunks
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _doh(packet: bytes, endpoint: str, timeout: float, get: bool) -> bytes:
|
|
197
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
198
|
+
if get:
|
|
199
|
+
encoded = base64.urlsafe_b64encode(packet).rstrip(b"=").decode("ascii")
|
|
200
|
+
separator = "&" if urlsplit(endpoint).query else "?"
|
|
201
|
+
url = f"{endpoint}{separator}dns={encoded}"
|
|
202
|
+
request = urllib.request.Request(
|
|
203
|
+
url, headers={"Accept": "application/dns-message"}, method="GET"
|
|
204
|
+
)
|
|
205
|
+
else:
|
|
206
|
+
request = urllib.request.Request(
|
|
207
|
+
endpoint,
|
|
208
|
+
data=packet,
|
|
209
|
+
method="POST",
|
|
210
|
+
headers={
|
|
211
|
+
"Content-Type": "application/dns-message",
|
|
212
|
+
"Accept": "application/dns-message",
|
|
213
|
+
},
|
|
214
|
+
)
|
|
215
|
+
try:
|
|
216
|
+
with opener.open(request, timeout=timeout) as response:
|
|
217
|
+
return response.read()
|
|
218
|
+
except urllib.error.HTTPError as exc:
|
|
219
|
+
raise NetkError("dns", f"DoH endpoint returned HTTP {exc.code}") from exc
|
|
220
|
+
except urllib.error.URLError as exc:
|
|
221
|
+
if isinstance(exc.reason, socket.timeout):
|
|
222
|
+
raise NetkError("timeout", f"DoH query to {endpoint} timed out", RC_TIMEOUT) from exc
|
|
223
|
+
raise NetkError("dns", f"DoH query to {endpoint} failed: {exc.reason}") from exc
|
|
224
|
+
except socket.timeout:
|
|
225
|
+
raise NetkError("timeout", f"DoH query to {endpoint} timed out", RC_TIMEOUT) from None
|
netk/dns/codec.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""DNS wire format: query builder, response parser and typed rdata decoders.
|
|
2
|
+
|
|
3
|
+
Stdlib only, no ``dig``. Compression pointers, EDNS0, and the record types an
|
|
4
|
+
agent actually asks about (A/AAAA/CNAME/MX/TXT/NS/SOA/SRV/CAA/PTR/HTTPS/DS/TLSA)
|
|
5
|
+
are decoded into plain strings so the JSON stays diffable.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import random
|
|
11
|
+
import socket
|
|
12
|
+
import struct
|
|
13
|
+
|
|
14
|
+
from ..contract import RC_USAGE, NetkError
|
|
15
|
+
|
|
16
|
+
Q_TYPES = {
|
|
17
|
+
"A": 1,
|
|
18
|
+
"NS": 2,
|
|
19
|
+
"CNAME": 5,
|
|
20
|
+
"SOA": 6,
|
|
21
|
+
"PTR": 12,
|
|
22
|
+
"MX": 15,
|
|
23
|
+
"TXT": 16,
|
|
24
|
+
"AAAA": 28,
|
|
25
|
+
"SRV": 33,
|
|
26
|
+
"NAPTR": 35,
|
|
27
|
+
"DS": 43,
|
|
28
|
+
"TLSA": 52,
|
|
29
|
+
"HTTPS": 65,
|
|
30
|
+
"CAA": 257,
|
|
31
|
+
}
|
|
32
|
+
R_TYPES = {value: key for key, value in Q_TYPES.items()}
|
|
33
|
+
RCODES = {
|
|
34
|
+
0: "NOERROR",
|
|
35
|
+
1: "FORMERR",
|
|
36
|
+
2: "SERVFAIL",
|
|
37
|
+
3: "NXDOMAIN",
|
|
38
|
+
4: "NOTIMP",
|
|
39
|
+
5: "REFUSED",
|
|
40
|
+
6: "YXDOMAIN",
|
|
41
|
+
7: "YXRRSET",
|
|
42
|
+
8: "NXRRSET",
|
|
43
|
+
9: "NOTAUTH",
|
|
44
|
+
10: "NOTZONE",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def encode_qname(name: str) -> bytes:
|
|
49
|
+
"""Encode a domain name into wire format, IDNA for non-ASCII labels."""
|
|
50
|
+
if not name or name in (".", ""):
|
|
51
|
+
raise NetkError("usage", f"invalid name {name!r}", RC_USAGE)
|
|
52
|
+
labels = name.rstrip(".").split(".")
|
|
53
|
+
out = b""
|
|
54
|
+
for label in labels:
|
|
55
|
+
if not label:
|
|
56
|
+
raise NetkError("usage", f"invalid name {name!r} (empty label)", RC_USAGE)
|
|
57
|
+
try:
|
|
58
|
+
raw = label.encode("idna") if not label.isascii() else label.encode()
|
|
59
|
+
except UnicodeError as exc:
|
|
60
|
+
raise NetkError("usage", f"invalid label {label!r}: {exc}", RC_USAGE) from exc
|
|
61
|
+
if len(raw) > 63:
|
|
62
|
+
raise NetkError("usage", f"label too long in {name!r}", RC_USAGE)
|
|
63
|
+
out += bytes([len(raw)]) + raw
|
|
64
|
+
if len(out) + 1 > 255:
|
|
65
|
+
raise NetkError("usage", f"name too long: {name!r}", RC_USAGE)
|
|
66
|
+
return out + b"\x00"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def build_query(
|
|
70
|
+
name: str, qtype: int, qid: int | None = None, edns: bool = True, edns_size: int = 1232
|
|
71
|
+
) -> tuple[int, bytes]:
|
|
72
|
+
"""Build a recursion-desired query; EDNS0 advertises a 1232-byte UDP buffer."""
|
|
73
|
+
qid = qid if qid is not None else random.randint(0, 0xFFFF)
|
|
74
|
+
flags = 0x0100 # RD
|
|
75
|
+
header = struct.pack("!HHHHHH", qid, flags, 1, 0, 0, 1 if edns else 0)
|
|
76
|
+
question = encode_qname(name) + struct.pack("!HH", qtype, 1)
|
|
77
|
+
# OPT pseudo-RR: root owner name, type 41, class = advertised UDP payload size.
|
|
78
|
+
additional = b"\x00" + struct.pack("!HHIH", 41, edns_size, 0, 0) if edns else b""
|
|
79
|
+
return qid, header + question + additional
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def read_name(msg: bytes, offset: int, depth: int = 0) -> tuple[str, int]:
|
|
83
|
+
"""Read a possibly-compressed name; returns (name, offset after the name)."""
|
|
84
|
+
labels: list[str] = []
|
|
85
|
+
jumped, end = False, offset
|
|
86
|
+
while True:
|
|
87
|
+
if offset >= len(msg) or depth > 20:
|
|
88
|
+
raise NetkError("dns", "malformed DNS name")
|
|
89
|
+
length = msg[offset]
|
|
90
|
+
if length & 0xC0 == 0xC0:
|
|
91
|
+
if offset + 1 >= len(msg):
|
|
92
|
+
raise NetkError("dns", "truncated compression pointer")
|
|
93
|
+
if not jumped:
|
|
94
|
+
end = offset + 2
|
|
95
|
+
offset = struct.unpack("!H", msg[offset : offset + 2])[0] & 0x3FFF
|
|
96
|
+
jumped, depth = True, depth + 1
|
|
97
|
+
continue
|
|
98
|
+
if length == 0:
|
|
99
|
+
offset += 1
|
|
100
|
+
return ".".join(labels), (end if jumped else offset)
|
|
101
|
+
if offset + 1 + length > len(msg):
|
|
102
|
+
raise NetkError("dns", "truncated label")
|
|
103
|
+
labels.append(msg[offset + 1 : offset + 1 + length].decode("utf-8", "replace"))
|
|
104
|
+
offset += 1 + length
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _unpack(fmt: str, data: bytes, where: str) -> tuple:
|
|
108
|
+
try:
|
|
109
|
+
return struct.unpack(fmt, data)
|
|
110
|
+
except struct.error as exc:
|
|
111
|
+
raise NetkError("dns", f"truncated {where} rdata") from exc
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _decode_txt(msg: bytes, offset: int, end: int) -> str:
|
|
115
|
+
chunks, cursor = [], offset
|
|
116
|
+
while cursor < end:
|
|
117
|
+
size = msg[cursor]
|
|
118
|
+
chunks.append(msg[cursor + 1 : cursor + 1 + size].decode("utf-8", "replace"))
|
|
119
|
+
cursor += 1 + size
|
|
120
|
+
return "".join(chunks)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def decode_rdata(msg: bytes, offset: int, rdlen: int, rtype: int) -> str:
|
|
124
|
+
"""Decode one record's rdata into the string form exposed in JSON."""
|
|
125
|
+
end = offset + rdlen
|
|
126
|
+
if end > len(msg):
|
|
127
|
+
raise NetkError("dns", "record rdata runs past the end of the message")
|
|
128
|
+
if rtype == 1:
|
|
129
|
+
return socket.inet_ntoa(msg[offset:end])
|
|
130
|
+
if rtype == 28:
|
|
131
|
+
return socket.inet_ntop(socket.AF_INET6, msg[offset:end])
|
|
132
|
+
if rtype in (2, 5, 12):
|
|
133
|
+
return read_name(msg, offset)[0] or "."
|
|
134
|
+
if rtype == 15:
|
|
135
|
+
preference = _unpack("!H", msg[offset : offset + 2], "MX")[0]
|
|
136
|
+
return f"{preference} {read_name(msg, offset + 2)[0] or '.'}"
|
|
137
|
+
if rtype == 16:
|
|
138
|
+
return _decode_txt(msg, offset, end)
|
|
139
|
+
if rtype == 6:
|
|
140
|
+
primary, cursor = read_name(msg, offset)
|
|
141
|
+
mailbox, cursor = read_name(msg, cursor)
|
|
142
|
+
serial, refresh, retry, expire, minimum = _unpack(
|
|
143
|
+
"!IIIII", msg[cursor : cursor + 20], "SOA"
|
|
144
|
+
)
|
|
145
|
+
return f"{primary} {mailbox} {serial} {refresh} {retry} {expire} {minimum}"
|
|
146
|
+
if rtype == 33:
|
|
147
|
+
priority, weight, port = _unpack("!HHH", msg[offset : offset + 6], "SRV")
|
|
148
|
+
return f"{priority} {weight} {port} {read_name(msg, offset + 6)[0] or '.'}"
|
|
149
|
+
if rtype == 35:
|
|
150
|
+
order, preference = _unpack("!HH", msg[offset : offset + 4], "NAPTR")
|
|
151
|
+
cursor = offset + 4
|
|
152
|
+
parts = []
|
|
153
|
+
for _ in range(3): # flags, service, regexp: each a quoted <character-string>
|
|
154
|
+
size = msg[cursor]
|
|
155
|
+
parts.append(msg[cursor + 1 : cursor + 1 + size].decode("utf-8", "replace"))
|
|
156
|
+
cursor += 1 + size
|
|
157
|
+
return (
|
|
158
|
+
f'{order} {preference} "{parts[0]}" "{parts[1]}" "{parts[2]}" '
|
|
159
|
+
f"{read_name(msg, cursor)[0]}"
|
|
160
|
+
)
|
|
161
|
+
if rtype == 43:
|
|
162
|
+
key_tag, algorithm, digest_type = _unpack("!HBB", msg[offset : offset + 4], "DS")
|
|
163
|
+
digest = msg[offset + 4 : end].hex().upper()
|
|
164
|
+
return f"{key_tag} {algorithm} {digest_type} {digest}"
|
|
165
|
+
if rtype == 52:
|
|
166
|
+
usage, selector, matching = _unpack("!BBB", msg[offset : offset + 3], "TLSA")
|
|
167
|
+
return f"{usage} {selector} {matching} {msg[offset + 3 : end].hex().upper()}"
|
|
168
|
+
if rtype == 257:
|
|
169
|
+
flags = msg[offset]
|
|
170
|
+
taglen = msg[offset + 1]
|
|
171
|
+
tag = msg[offset + 2 : offset + 2 + taglen].decode("utf-8", "replace")
|
|
172
|
+
value = msg[offset + 2 + taglen : end].decode("utf-8", "replace")
|
|
173
|
+
return f'{flags} {tag} "{value}"'
|
|
174
|
+
return msg[offset:end].hex()
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def parse_response(data: bytes) -> dict:
|
|
178
|
+
"""Parse a full DNS message into the JSON shape every consumer sees."""
|
|
179
|
+
if len(data) < 12:
|
|
180
|
+
raise NetkError("dns", "response shorter than a DNS header")
|
|
181
|
+
qid, flags, qdcount, ancount, nscount, arcount = struct.unpack("!HHHHHH", data[:12])
|
|
182
|
+
offset, questions = 12, []
|
|
183
|
+
for _ in range(qdcount):
|
|
184
|
+
name, offset = read_name(data, offset)
|
|
185
|
+
qtype = _unpack("!HH", data[offset : offset + 4], "question")[0]
|
|
186
|
+
offset += 4
|
|
187
|
+
questions.append({"name": name, "type": R_TYPES.get(qtype, f"TYPE{qtype}")})
|
|
188
|
+
sections: dict[str, list[dict]] = {}
|
|
189
|
+
for label, count in (("answer", ancount), ("authority", nscount), ("additional", arcount)):
|
|
190
|
+
records = []
|
|
191
|
+
for _ in range(count):
|
|
192
|
+
name, offset = read_name(data, offset)
|
|
193
|
+
rtype, _, ttl, rdlen = _unpack("!HHIH", data[offset : offset + 10], "record header")
|
|
194
|
+
offset += 10
|
|
195
|
+
if rtype == 41: # OPT pseudo-record: not data, keeps extended rcode
|
|
196
|
+
offset += rdlen
|
|
197
|
+
continue
|
|
198
|
+
records.append(
|
|
199
|
+
{
|
|
200
|
+
"name": name,
|
|
201
|
+
"type": R_TYPES.get(rtype, f"TYPE{rtype}"),
|
|
202
|
+
"ttl": ttl,
|
|
203
|
+
"value": decode_rdata(data, offset, rdlen, rtype),
|
|
204
|
+
}
|
|
205
|
+
)
|
|
206
|
+
offset += rdlen
|
|
207
|
+
sections[label] = records
|
|
208
|
+
return {
|
|
209
|
+
"id": qid,
|
|
210
|
+
"rcode": RCODES.get(flags & 0xF, str(flags & 0xF)),
|
|
211
|
+
"flags": {
|
|
212
|
+
"authoritative": bool(flags & 0x0400),
|
|
213
|
+
"truncated": bool(flags & 0x0200),
|
|
214
|
+
"recursion_desired": bool(flags & 0x0100),
|
|
215
|
+
"recursion_available": bool(flags & 0x0080),
|
|
216
|
+
"authenticated": bool(flags & 0x0020),
|
|
217
|
+
},
|
|
218
|
+
"questions": questions,
|
|
219
|
+
**sections,
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def dedupe(records: list[dict]) -> list[dict]:
|
|
224
|
+
"""Drop byte-identical records (multi-type queries can repeat them)."""
|
|
225
|
+
seen, out = set(), []
|
|
226
|
+
for record in records:
|
|
227
|
+
key = (record["name"], record["type"], record["ttl"], record["value"])
|
|
228
|
+
if key in seen:
|
|
229
|
+
continue
|
|
230
|
+
seen.add(key)
|
|
231
|
+
out.append(record)
|
|
232
|
+
return out
|
netk/dns/resolver.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Where the OS keeps its resolvers, and how netk finds them without a subprocess.
|
|
2
|
+
|
|
3
|
+
Order: ``NETK_DNS`` env -> ``/etc/resolv.conf`` -> Windows registry -> public fallback.
|
|
4
|
+
The ``source`` label is part of the contract (``env`` / ``system`` / ``fallback``)
|
|
5
|
+
because "which resolver answered" is usually the first question in a DNS incident.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
from ..targets import split_servers, unique, windows_resolvers
|
|
14
|
+
|
|
15
|
+
RESOLV_CONF = "/etc/resolv.conf"
|
|
16
|
+
STUB_RESOLVERS = {"127.0.0.53", "127.0.0.54"} # systemd-resolved stub
|
|
17
|
+
FALLBACK = ["1.1.1.1", "8.8.8.8"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def resolver_config() -> dict:
|
|
21
|
+
"""Return ``{servers, source, file?, stub}`` describing this machine's resolver."""
|
|
22
|
+
env = os.environ.get("NETK_DNS")
|
|
23
|
+
if env:
|
|
24
|
+
servers = [s.strip() for s in env.split(",") if s.strip()]
|
|
25
|
+
return {"servers": servers, "source": "env", "stub": False}
|
|
26
|
+
|
|
27
|
+
servers = _resolv_conf()
|
|
28
|
+
if servers:
|
|
29
|
+
return {
|
|
30
|
+
"servers": servers,
|
|
31
|
+
"source": "system",
|
|
32
|
+
"file": RESOLV_CONF,
|
|
33
|
+
"stub": all(s in STUB_RESOLVERS for s in servers),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if sys.platform.startswith("win"):
|
|
37
|
+
try:
|
|
38
|
+
servers = unique(windows_resolvers())
|
|
39
|
+
except ImportError:
|
|
40
|
+
servers = []
|
|
41
|
+
if servers:
|
|
42
|
+
return {"servers": servers, "source": "system", "file": "registry", "stub": False}
|
|
43
|
+
|
|
44
|
+
return {"servers": list(FALLBACK), "source": "fallback", "stub": False}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _resolv_conf() -> list[str]:
|
|
48
|
+
try:
|
|
49
|
+
with open(RESOLV_CONF, encoding="utf-8") as handle:
|
|
50
|
+
lines = handle.read().splitlines()
|
|
51
|
+
except OSError:
|
|
52
|
+
return []
|
|
53
|
+
servers = []
|
|
54
|
+
for line in lines:
|
|
55
|
+
fields = line.split()
|
|
56
|
+
if len(fields) > 1 and fields[0] == "nameserver" and not fields[1].startswith("#"):
|
|
57
|
+
servers.append(fields[1])
|
|
58
|
+
return servers
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def system_resolvers() -> tuple[list[str], str]:
|
|
62
|
+
"""Compatibility wrapper: ``(servers, source)``."""
|
|
63
|
+
config = resolver_config()
|
|
64
|
+
return config["servers"], config["source"]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def split_endpoint(value: str, default_port: int = 53) -> tuple[str, int]:
|
|
68
|
+
"""Split ``ip``, ``ip:port``, ``[v6]`` or ``[v6]:port``."""
|
|
69
|
+
value = value.strip()
|
|
70
|
+
if value.startswith("["):
|
|
71
|
+
host, _, rest = value[1:].partition("]")
|
|
72
|
+
port = rest.lstrip(":")
|
|
73
|
+
return host, int(port) if port.isdigit() else default_port
|
|
74
|
+
if value.count(":") == 1:
|
|
75
|
+
host, port = value.split(":")
|
|
76
|
+
if port.isdigit():
|
|
77
|
+
return host, int(port)
|
|
78
|
+
return value, default_port
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
__all__ = ["resolver_config", "system_resolvers", "split_endpoint", "split_servers"]
|
netk/py.typed
ADDED
|
File without changes
|