[PATCH v2] resolv: Add test for gethostbyname_r unaligned buffer [BZ #18287]
Florian Weimer
fweimer@redhat.com
Fri Jun 19 14:37:03 GMT 2026
* Sergey Kolosov:
> +/* Test gethostbyname_r with a specified buffer size and alignment.
> + Returns true if the buffer is sufficient, false if it's too small. */
> +static bool
> +query_host (const char *host_name, size_t size, size_t align)
> +{
> + struct hostent ret;
> + struct hostent *result;
> + int err;
> +
> + /* Allocate memory for buffer, alignment padding, and a 64-byte checking area. */
I think this line is now longer than 79 characters. Please wrap.
> + size_t total_alloc = size + align + 64;
> + unsigned char *raw_buf = xmalloc (total_alloc);
> +
> + /* Fill in buffer with 0xAA to detect buffer overflow. */
Suggest: Fill the tail of the buffer with 0xAA to dewtect overflows below.
> + memset (raw_buf, 0, size + align);
> + memset (raw_buf + size + align, 0xAA, 64);
> +
> + char *ptr = (char *) raw_buf + align;
> +
> + int res = gethostbyname_r (host_name, &ret, ptr, size, &result, &err);
> +
> + /* Verify that the overflow guard region remains unchanged. */
> + bool overflow_detected = false;
> + for (int i = 0; i < 64; i++)
> + {
> + if (raw_buf[size + align + i] != 0xAA)
> + {
> + overflow_detected = true;
> + break;
> + }
> + }
> +
> + if (overflow_detected)
> + {
> + free (raw_buf);
> + FAIL_EXIT1 ("Buffer overflow was detected! (align=%zu, size=%zu)\n",
> + align, size);
> + }
The free is superfluous (we generally do not clean up memory before
FAIL_EXIT1), and I think this can move into the for loop above.
> + if (res == 0 && result != NULL)
> + {
> + /* Generate the expected response to satisfy check_hostent. */
> + char expected_response[4096];
> + strcpy (expected_response, "name: foo.site.example\n");
> + for (int i = 0; i <= 60; i++)
> + {
> + char buf[64];
> + snprintf (buf, sizeof (buf), "address: 127.126.125.%d\n", i);
> + strcat (expected_response, buf);
> + }
> +
> + check_hostent (host_name, &ret, expected_response);
> + is_sufficient = true; /* Buffer is sufficient. */
I'd use fprintf with xopen_memstream.
Thanks,
Florian
More information about the Libc-alpha
mailing list