Comment 19 for bug 386791

Revision history for this message
In , agl (agl) wrote :

The following program will blow its stack and crash if I have an /etc/hosts line longer than 4Kish.

---
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main() {
  struct addrinfo hints, *res;

  memset(&hints, 0, sizeof(hints));
  hints.ai_family = PF_INET;
  getaddrinfo("www.google.com", "http", &hints, &res);

  return 0;
}
---

Setting the ai_family in the hints is required in order to reproduce the crash.

(File and line references in the following are relative to git 16c2895feabae0962e0eba2b9164c6a83014bfe4)

In sysdeps/posix/getaddrinfo.c:531 we have a loop in gaih_inet which allocas a buffer and doubles the size of that buffer each time __gethostbyname2_r returns with ERANGE.

The __gethostbyname2_r ends up in nss/nss_files/files-hosts.c:128:

      if (status == NSS_STATUS_SUCCESS»·»·······»·······»·······»······· \
»······· && _res_hconf.flags & HCONF_FLAG_MULTI)»······»·······»······· \
»·······{»······»·······»·······»·······»·······»·······»·······»······· \
»······· /* We have to get all host entries from the file. */»»······· \
»······· const size_t tmp_buflen = MIN (buflen, 4096);»»·······»······· \
»······· char tmp_buffer[tmp_buflen]»··»·······»·······»·······»······· \
»······· __attribute__ ((__aligned__ (__alignof__ (struct hostent_data))));\

Here, if HCONF_FLAG_MULTI is set then a secondary buffer is created on the stack for the use of internal_getent. This buffer is limited to 4K in size.

internal_getent will try to read lines from /etc/hosts and it will return ERANGE if the line (plus an internal structure) doesn't fit into |tmp_buffer|. When this happens the loop in getaddrinfo.c will try doubling the size of its buffer. However, |tmp_buffer| was limited to 4K so __gethostbyname2_r repeatedly returns ERANGE and gaih_inet uselessly expands the buffer on the stack until the program crashes.

I believe that the best solution is to replace:
  const size_t tmp_buflen = MIN (buflen, 4096);
with:
  const size_t tmp_buflen = buflen;

I can confirm that this fixes the crash for me.