eBPF-based security platform
kernel-obs: record a DNS label's NUL, dot or unprintable byte as '?'
Daniel Borkmann2c4db4cbbc56
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex 2bc441e3..4de799a0 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -833,7 +833,8 @@ signed config image.* - ``t9103-kernel-obs-priv``- Privilege and executable-mapping records in maps, OTLP and ClickHouse* - ``t9104-kernel-obs-dns-matrix``- - DNS over loopback in maps, OTLP and ClickHouse+ - DNS over loopback in maps, OTLP and ClickHouse, and a label's NUL,+ dot or byte outside printable ASCII recorded as ``?``* - ``t9105-delivery``- The operator package built and installed in an operator VMwithout a TPM, which publishes ``kernel-obs`` and the Java agentdiff --git a/testing/end2end/dns_obs_matrix.py b/testing/end2end/dns_obs_matrix.pyindex f5ab82ca..55a2d152 100755--- a/testing/end2end/dns_obs_matrix.py+++ b/testing/end2end/dns_obs_matrix.py@@ -28,6 +28,7 @@ COUNTERS = ("QUERY_QDCOUNT_BAD","QUERY_SCRATCH_MISS","QUERY_NAME_FAIL",+ "QUERY_NAME_REPLACED","QUERY_EMPTY_NAME","QUERY_QTYPE_READ_FAIL","QUERY_QTYPE_UNSUPPORTED",@@ -227,17 +228,21 @@ class Matrix:def pair(self, stem: str, name: str, qtype: int, answers: list[bytes],*, ipv6_transport: bool = False,- response_counters: dict[str, int] | None = None) -> int:+ response_counters: dict[str, int] | None = None,+ labels: list[bytes] | None = None,+ query_counters: dict[str, int] | None = None) -> int:txid = self.txid()- qname = wire_name(name)+ qname = wire_name(name if labels is None else labels)make_frame = frame6 if ipv6_transport else frame4family_counter = "PACKET_IPV6" if ipv6_transport else "PACKET_IPV4"+ query_expected = {family_counter: 1, "QUERY_PACKET": 1,+ "QUERY_STORED": 1}+ if query_counters:+ query_expected.update(query_counters)self.add(Case(f"{stem}: query", QUERY, txid,make_frame(query_payload(txid, qname, qtype), QUERY),- count(**{family_counter: 1, "QUERY_PACKET": 1,- "QUERY_STORED": 1}),- True, name, qtype,+ query_expected, True, name, qtype,))expected = {family_counter: 1,@@ -686,6 +691,24 @@ def build_deterministic_matrix() -> Matrix:matrix.pair("127-label maximum wire name", long_name, A,[rr(rdata=b"\xc0\x00\x02\x0b")])+ # A label byte that is a NUL, a dot or not printable ASCII is recorded+ # as '?', so that the name keeps its labels and its length.+ for stem, labels, recorded, last in (+ ("NUL in a label", [b"ww\x00w", b"evil", b"example"],+ "ww?w.evil.example", 0x0c),+ ("dot in a label", [b"www.good", b"example"],+ "www?good.example", 0x0d),+ ("bytes past ASCII in a label", [b"caf\xc3\xa9", b"example"],+ "caf??.example", 0x0e),+ ("space and control byte in a label", [b"a b\x01", b"example"],+ "a?b?.example", 0x0f),+ ("NUL alone in the first label", [b"\x00", b"evil", b"example"],+ "?.evil.example", 0x10),+ ):+ matrix.pair(stem, recorded, A, [rr(rdata=bytes((192, 0, 2, last)))],+ labels=labels,+ query_counters={"QUERY_NAME_REPLACED": 1})+# Multiple answers for one address exercise lookup and seen_count updates.matrix.pair("duplicate address answer", "duplicate.example", A,[rr(rdata=b"\xc0\x00\x02\x14"),diff --git a/testing/end2end/kernel_obs_checks.py b/testing/end2end/kernel_obs_checks.pyindex e0e8f985..2930b4f3 100644--- a/testing/end2end/kernel_obs_checks.py+++ b/testing/end2end/kernel_obs_checks.py@@ -228,6 +228,18 @@ def t9104_check(argv):assert any(item["name"] == name for item in record["names"]), record+def t9104_check_odd(argv):+ records = read_documents(argv[1])+ assert len(records) == 1 and records[0].get("map") == "dns", records+ names = {item["address"]: [name["name"] for name in item["names"]]+ for item in records[0].get("records", [])}+ for address, name in (("203.0.113.81", "ww?w.evil.example"),+ ("203.0.113.82", "www?good.example"),+ ("203.0.113.83", "caf??.example"),+ ("203.0.113.84", "?.evil.example")):+ assert names.get(address) == [name], (address, records)++def t9104_check_empty(argv):records = read_documents(argv[1])assert len(records) == 1 and records[0].get("map") == "dns", records@@ -242,6 +254,7 @@ CHECKS = {"t9101_check_exec_only": t9101_check_exec_only,"t9102_check": t9102_check,"t9104_check": t9104_check,+ "t9104_check_odd": t9104_check_odd,"t9104_check_empty": t9104_check_empty,}diff --git a/testing/end2end/kernel_obs_events.py b/testing/end2end/kernel_obs_events.pyindex d00602e8..9057f7e7 100755--- a/testing/end2end/kernel_obs_events.py+++ b/testing/end2end/kernel_obs_events.py@@ -301,8 +301,7 @@ def socket_events():print(json.dumps(expected))-def dns_name(name):- labels = [label.encode() for label in name.split(".")]+def dns_wire_name(labels):if not labels or any(not label or len(label) > 63 for label in labels):raise ValueError("DNS labels must contain between 1 and 63 bytes")wire = b"".join(bytes([len(label)]) + label for label in labels) + b"\0"@@ -311,6 +310,10 @@ def dns_name(name):return wire+def dns_name(name):+ return dns_wire_name([label.encode() for label in name.split(".")])++def dns_event():nameservers = []with open("/etc/resolv.conf", encoding="utf-8") as resolv:@@ -344,9 +347,9 @@ def dns_event():raise RuntimeError(f"DNS query failed: {last_error}")-def local_dns_exchange(name, answers):+def local_dns_exchange(wire_name, answers):transaction = random.randrange(1, 65535)- question = dns_name(name) + struct.pack("!HH", 1, 1)+ question = wire_name + struct.pack("!HH", 1, 1)query = struct.pack("!HHHHHH", transaction, 0x0100, 1, 0, 0, 0) + questionerrors = []@@ -388,14 +391,31 @@ def local_dns_exchange(name, answers):def dns_long_event():answer = b"\xc0\x0c" + struct.pack("!HHIH4s", 1, 1, 60, 4,socket.inet_aton("203.0.113.10"))- local_dns_exchange(".".join(["a"] * 127), [answer])+ local_dns_exchange(dns_name(".".join(["a"] * 127)), [answer])def dns_many_answers_event():unsupported = b"\xc0\x0c" + struct.pack("!HHIHB", 16, 1, 60, 1, 0)answer = b"\xc0\x0c" + struct.pack("!HHIH4s", 1, 1, 60, 4,socket.inet_aton("203.0.113.75"))- local_dns_exchange("many.example", [unsupported] * 74 + [answer])+ local_dns_exchange(dns_name("many.example"), [unsupported] * 74 + [answer])+++# Labels holding a NUL, a dot, UTF-8 and a NUL alone, whose bytes+# kernel-obs records as '?'.+ODD_NAMES = (+ ([b"ww\0w", b"evil", b"example"], "203.0.113.81"),+ ([b"www.good", b"example"], "203.0.113.82"),+ ([b"caf\xc3\xa9", b"example"], "203.0.113.83"),+ ([b"\0", b"evil", b"example"], "203.0.113.84"),+)+++def dns_odd_event():+ for labels, address in ODD_NAMES:+ answer = b"\xc0\x0c" + struct.pack("!HHIH4s", 1, 1, 60, 4,+ socket.inet_aton(address))+ local_dns_exchange(dns_wire_name(labels), [answer])EVENTS = {@@ -409,6 +429,7 @@ EVENTS = {"watch": watch_event,"dns-long": dns_long_event,"dns-many": dns_many_answers_event,+ "dns-odd": dns_odd_event,}ALL = ("exec", "tcp", "udp", "dns", "listen", "file")diff --git a/testing/end2end/t9104-kernel-obs-dns-matrix.sh b/testing/end2end/t9104-kernel-obs-dns-matrix.shindex 47b81624..59425879 100755--- a/testing/end2end/t9104-kernel-obs-dns-matrix.sh+++ b/testing/end2end/t9104-kernel-obs-dns-matrix.sh@@ -27,4 +27,10 @@ test_expect_success 'DNS observations use real loopback UDP traffic' 'python3 end2end/kernel_obs_checks.py t9104_check_empty "$OTEL_OUT/t9104-dns-empty.ndjson"'+test_expect_success 'a label byte that is a NUL, a dot or not printable ASCII is recorded as ?' '+ python3 end2end/kernel_obs_events.py dns-odd &&+ otel_export dns "$OTEL_OUT/t9104-dns-odd.ndjson" &&+ python3 end2end/kernel_obs_checks.py t9104_check_odd "$OTEL_OUT/t9104-dns-odd.ndjson"+'+test_donediff --git a/upatches/kernel-obs/README.md b/upatches/kernel-obs/README.mdindex db71643e..e4797535 100644--- a/upatches/kernel-obs/README.md+++ b/upatches/kernel-obs/README.md@@ -89,6 +89,15 @@ creations are not recorded. UNIX paths, message payloads and VSOCK peeridentifiers are not recorded. AF_PACKET and AF_XDP ring records cover setupand wakeup calls, not individual frames.+DNS records keep the question name of the query an answer resolved, its+labels joined by dots. A label may hold any byte; a NUL, a dot, a space+or any other byte outside printable ASCII in it is recorded as `?`, so+that the recorded name keeps the length and the labels of the name+queried. The labels `www.good` and `example` are recorded as+`www?good.example`, not as the three labels of `www.good.example`, and+`ww\0w.evil.example`, whose first label holds a NUL, as+`ww?w.evil.example` rather than `ww`.+Packet counts come from the cgroup hooks on the root cgroup and coverevery socket on the host, including sockets created before the load,which are attributed to their cgroup alone until their owner is known.@@ -210,8 +219,8 @@ namespace, addresses, ports and transaction ID. It does not yet:- [ ] reject IP fragments, check the IP and UDP lengths against the packetand hold the 1232-byte parsing budget on the packet itself;- [ ] walk IPv6 extension headers, or reject packets that carry one;-- [ ] reject an embedded NUL in a label and bound every compression- pointer it skips, against loops and out-of-packet targets;+- [ ] bound every compression pointer it skips, against loops and+ out-of-packet targets;- [ ] count a full pending table, LRU displacement, stale responses andanswers past its cap of 75, instead of dropping them silently;- [ ] cover malformed packets on the target, which needs a live packetdiff --git a/upatches/kernel-obs/obs_dns.bpf.c b/upatches/kernel-obs/obs_dns.bpf.cindex 951f7999..dd5c54db 100644--- a/upatches/kernel-obs/obs_dns.bpf.c+++ b/upatches/kernel-obs/obs_dns.bpf.c@@ -25,6 +25,8 @@#define DNS_MAX_PACKET_BYTES (DNS_MAX_UDP_BYTES + DNS_MAX_IP_HEADER_BYTES)#define DNS_REQ_MAP_ENTRIES 1024#define DNS_COMPRESSED_MASK 0xc0+/* Set in what the label and name parsers return, above any label's length. */+#define DNS_NAME_REPLACED 0x100enum dns_debug_counter {DNS_DBG_QUERY_PACKET,@@ -34,6 +36,7 @@ enum dns_debug_counter {DNS_DBG_QUERY_QDCOUNT_BAD,DNS_DBG_QUERY_SCRATCH_MISS,DNS_DBG_QUERY_NAME_FAIL,+ DNS_DBG_QUERY_NAME_REPLACED,DNS_DBG_QUERY_EMPTY_NAME,DNS_DBG_QUERY_QTYPE_READ_FAIL,DNS_DBG_QUERY_QTYPE_UNSUPPORTED,@@ -385,16 +388,35 @@ static __always_inline bool dns_read_u32_raw(struct __sk_buff *skb,return true;}+/*+ * A label may hold any byte, but the recorded name is a C string with dots+ * between its labels: a NUL in a label would end the name there and a dot+ * would split the label in two, either recording another name than the+ * one resolved. Such a byte is recorded as '?', as is any other outside+ * printable ASCII, rather than the name refused, which would leave the+ * query unrecorded.+ */+static __always_inline bool dns_label_byte_recordable(__u8 byte)+{+ return byte > ' ' && byte <= '~' && byte != '.';+}++/*+ * Copies one label into the scratch name and returns the bytes it took,+ * 0 at the root label, with DNS_NAME_REPLACED set when a byte of the label+ * was recorded as '?'.+ */__attribute__((noinline)) intobs_dns_parse_name_label(struct __sk_buff *skb, __u32 off, __u32 start){__u8 *data = (__u8 *)(long)skb->data;__u8 *data_end = (__u8 *)(long)skb->data_end;- struct dns_scratch *scratch;__u32 wire_offset, dst, i, zero = 0;+ struct dns_scratch *scratch;+ int replaced = 0;+ __u8 len, byte;__u8 *src;char *out;- __u8 len;if (off < start || off >= DNS_MAX_PACKET_BYTES)return -EINVAL;@@ -438,16 +460,25 @@ obs_dns_parse_name_label(struct __sk_buff *skb, __u32 off, __u32 start)for (i = 0; i < len; i++) {if (src + i + 1 > data_end)return -EINVAL;- out[dst + i] = src[i];+ byte = src[i];+ if (!dns_label_byte_recordable(byte)) {+ byte = '?';+ replaced = DNS_NAME_REPLACED;+ }+ out[dst + i] = byte;}- return (int)len + 1;+ return ((int)len + 1) | replaced;}+/*+ * Returns a negative errno, or 0 with DNS_NAME_REPLACED set when a byte of+ * the name was recorded as '?'.+ */static __always_inline int dns_parse_name(struct __sk_buff *skb, __u32 off,char *out, __u32 *next_off){__u32 start = off, pos = off;- int consumed, i;+ int consumed, replaced = 0, i;if (!out || !next_off)return -EINVAL;@@ -459,8 +490,10 @@ static __always_inline int dns_parse_name(struct __sk_buff *skb, __u32 off,return consumed;if (consumed == 0) {*next_off = pos + 1;- return 0;+ return replaced;}+ replaced |= consumed & DNS_NAME_REPLACED;+ consumed &= ~DNS_NAME_REPLACED;if ((__u32)consumed > DNS_MAX_PACKET_BYTES - pos)return -EINVAL;pos += (__u32)consumed;@@ -559,6 +592,7 @@ static __always_inline void dns_parse_query_payload(struct __sk_buff *skb,struct obs_ident ident = {};__u32 zero = 0, next = 0;__u16 id, flags, qdcount, qtype, qclass;+ int parsed;dns_debug_inc(DNS_DBG_QUERY_PACKET);if (!dns_query_ident(skb, &ident)) {@@ -584,11 +618,14 @@ static __always_inline void dns_parse_query_payload(struct __sk_buff *skb,dns_debug_inc(DNS_DBG_QUERY_SCRATCH_MISS);return;}- if (dns_parse_name(skb, dns_off + sizeof(struct dns_hdr),- scratch->req.name, &next)) {+ parsed = dns_parse_name(skb, dns_off + sizeof(struct dns_hdr),+ scratch->req.name, &next);+ if (parsed < 0) {dns_debug_inc(DNS_DBG_QUERY_NAME_FAIL);return;}+ if (parsed & DNS_NAME_REPLACED)+ dns_debug_inc(DNS_DBG_QUERY_NAME_REPLACED);if (!scratch->req.name[0]) {dns_debug_inc(DNS_DBG_QUERY_EMPTY_NAME);return;