From bb8f5bb0a80e207c06e1aa9da97a4de1a6873a13 Mon Sep 17 00:00:00 2001 From: Chilledheart Date: Thu, 2 Feb 2023 20:05:40 +0800 Subject: [PATCH] Windows: Invalid stack variable out of scope for HOSTS file path (#502) In some conditions Windows might try to use a stack address that has gone out of scope when determining where to read the hosts data from for file lookups. Fix By: @Chilledheart --- src/lib/ares_getaddrinfo.c | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/lib/ares_getaddrinfo.c b/src/lib/ares_getaddrinfo.c index bc9f19bf..1c414987 100644 --- a/src/lib/ares_getaddrinfo.c +++ b/src/lib/ares_getaddrinfo.c @@ -430,16 +430,20 @@ static int file_lookup(struct host_query *hquery) FILE *fp; int error; int status; - const char *path_hosts = NULL; + char *path_hosts = NULL; if (hquery->hints.ai_flags & ARES_AI_ENVHOSTS) { - path_hosts = getenv("CARES_HOSTS"); + path_hosts = ares_strdup(getenv("CARES_HOSTS")); + if (!path_hosts) + return ARES_ENOMEM; } if (hquery->channel->hosts_path) { - path_hosts = hquery->channel->hosts_path; + path_hosts = ares_strdup(hquery->channel->hosts_path); + if (!path_hosts) + return ARES_ENOMEM; } if (!path_hosts) @@ -473,15 +477,15 @@ static int file_lookup(struct host_query *hquery) return ARES_ENOTFOUND; strcat(PATH_HOSTS, WIN_PATH_HOSTS); - path_hosts = PATH_HOSTS; - #elif defined(WATT32) const char *PATH_HOSTS = _w32_GetHostsFile(); if (!PATH_HOSTS) return ARES_ENOTFOUND; #endif - path_hosts = PATH_HOSTS; + path_hosts = ares_strdup(PATH_HOSTS); + if (!path_hosts) + return ARES_ENOMEM; } fp = fopen(path_hosts, "r"); @@ -507,6 +511,7 @@ static int file_lookup(struct host_query *hquery) status = ares__readaddrinfo(fp, hquery->name, hquery->port, &hquery->hints, hquery->ai); fclose(fp); } + ares_free(path_hosts); /* RFC6761 section 6.3 #3 states that "Name resolution APIs and libraries * SHOULD recognize localhost names as special and SHOULD always return the