Skip to content

dns_get_record(): A record with short RDATA publishes a wrong IP address (bytes taken from the next record) #25968

In review

Description

@kid-lxy

Description

The following code (requires the crafted UDP server below on 127.0.0.1:53 and nameserver 127.0.0.1 as the resolver, in an isolated test container):

<?php
var_dump(@dns_get_record('bug.test', DNS_A));

The fixture returns two A answers. The FIRST one declares RDLENGTH = 1 but the dotted-quad read needs 4 bytes; the second is a valid 5.6.7.8:

import socket, struct
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("127.0.0.1", 53))
while True:
    data, addr = s.recvfrom(65535)
    if len(data) < 12: continue
    idx = 12
    while idx < len(data) and data[idx] != 0: idx += 1 + data[idx]
    q = data[12:idx + 5]
    hdr = data[:2] + struct.pack(">HHHHH", 0x8580, 1, 2, 0, 0)
    r1 = b"\xc0\x0c" + struct.pack(">HHIH", 1, 1, 0, 1) + b"\x09"          # A, RDLENGTH=1, only byte 9
    r2 = b"\xc0\x0c" + struct.pack(">HHIH", 1, 1, 0, 4) + b"\x05\x06\x07\x08"  # valid A 5.6.7.8
    s.sendto(hdr + q + r1 + r2, addr)

Resulted in this output:

array(2) {
  [0]=> array(5) { ... ["type"]=> string(1) "A" ["ip"]=> string(10) "9.192.12.0" }
  [1]=> array(5) { ... ["type"]=> string(1) "A" ["ip"]=> string(7) "5.6.7.8" }
}

But I expected this output instead:

The first record must be rejected as malformed (RDLENGTH=1 cannot hold an IPv4 address),
i.e. only the second record should be returned (or the call should fail).

Root cause in php_parserr() (ext/standard/dns.c, master):

case DNS_T_A:
    CHECKCP(4);                       /* only guards the message end, not this record's RDATA */
    add_assoc_string(subarray, "type", "A");
    snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]);
    add_assoc_string(subarray, "ip", name);

CHECKCP(4) ensures the 4 bytes lie inside the received message, but nothing enforces dlen >= 4 for the record. With RDLENGTH = 1 the three missing bytes are read from the NEXT record's owner pointer / type field (c0 0c 00 → 192.12.0), producing the bogus address 9.192.12.0 returned to userland.

PHP Version

PHP 8.7.0-dev (cli) (built: Nov 29 2026 03:42:09) (NTS)
Copyright © The PHP Group and Contributors
Zend Engine v4.7.0-dev, Copyright © Zend by Perforce
    with Zend OPcache v8.7.0-dev, Copyright ©, by Zend by Perforce

Operating System

Ubuntu 24.04.5 LTS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions