[PATCH 1/2] net: dns: fix packet buffer overflow from long hostnames
Sascha Hauer
s.hauer at pengutronix.de
Thu Apr 2 01:25:09 PDT 2026
dns_send() uses strcpy() to copy the DNS-encoded hostname into the
packet buffer with no length check. The packet buffer has ~1482 bytes
available for the query name (PKTSIZE minus ethernet/IP/UDP headers,
DNS header, and query trailer). A hostname+domain combination longer
than this overflows the packet buffer.
The hostname comes from resolv() callers (TFTP server names, NFS
paths, user commands, etc.) and the domain from the user-configurable
global.net.domainname variable.
Fix by validating the encoded name length against the available packet
space before copying, and replace strcpy with memcpy using the known
length. Return -ENAMETOOLONG if the name doesn't fit.
Note the final component of the hostname is a dot ('.') which gets
replaced with a 0 in the "replace dots in fullname with chunk len" loop.
As we now calculate the strlen before that loop it will include that
final 0 already, so we must drop the "Mark end of host name" part.
Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply at anthropic.com>
---
net/dns.c | 17 ++++++++++++++---
1 file changed, 14 insertions(+), 3 deletions(-)
diff --git a/net/dns.c b/net/dns.c
index 8fbd13cdc3..fde1439469 100644
--- a/net/dns.c
+++ b/net/dns.c
@@ -70,6 +70,10 @@ static int dns_send(const char *name)
unsigned char *packet = net_udp_get_payload(dns_con);
unsigned char *p, *s, *fullname, *dotptr;
const unsigned char *domain;
+ int namelen;
+ /* max UDP payload minus header and query trailer (5 bytes) */
+ const int maxlen = PKTSIZE - ETHER_HDR_SIZE - sizeof(struct iphdr) -
+ sizeof(struct udphdr) - offsetof(struct header, data) - 5;
/* generate "difficult" to predict transaction id */
dns_req_id = dns_timer_start + (dns_timer_start >> 16);
@@ -90,6 +94,14 @@ static int dns_send(const char *name)
else
fullname = basprintf(".%s.", name);
+ namelen = strlen(fullname);
+ if (namelen > maxlen) {
+ pr_err("hostname too long for DNS query (%d > %d)\n",
+ namelen, maxlen);
+ free(fullname);
+ return -ENAMETOOLONG;
+ }
+
/* replace dots in fullname with chunk len */
dotptr = fullname;
do {
@@ -104,11 +116,10 @@ static int dns_send(const char *name)
} while (*(dotptr + 1));
*dotptr = 0;
- strcpy(header->data, fullname);
+ memcpy(header->data, fullname, namelen);
- p = header->data + strlen(fullname);
+ p = header->data + namelen;
- *p++ = 0; /* Mark end of host name */
*p++ = 0; /* Some servers require double null */
*p++ = (unsigned char)qtype; /* Query Type */
--
2.47.3
More information about the barebox
mailing list