fix stack-based oob memory clobber in resolver's result sorting
[musl] / src / network / lookup_name.c
1 #include <sys/socket.h>
2 #include <netinet/in.h>
3 #include <netdb.h>
4 #include <net/if.h>
5 #include <arpa/inet.h>
6 #include <ctype.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <pthread.h>
12 #include <errno.h>
13 #include "lookup.h"
14 #include "stdio_impl.h"
15 #include "syscall.h"
16
17 static int is_valid_hostname(const char *host)
18 {
19         const unsigned char *s;
20         if (strnlen(host, 255)-1 >= 254 || mbstowcs(0, host, 0) == -1) return 0;
21         for (s=(void *)host; *s>=0x80 || *s=='.' || *s=='-' || isalnum(*s); s++);
22         return !*s;
23 }
24
25 static int name_from_null(struct address buf[static 2], const char *name, int family, int flags)
26 {
27         int cnt = 0;
28         if (name) return 0;
29         if (flags & AI_PASSIVE) {
30                 if (family != AF_INET6)
31                         buf[cnt++] = (struct address){ .family = AF_INET };
32                 if (family != AF_INET)
33                         buf[cnt++] = (struct address){ .family = AF_INET6 };
34         } else {
35                 if (family != AF_INET6)
36                         buf[cnt++] = (struct address){ .family = AF_INET, .addr = { 127,0,0,1 } };
37                 if (family != AF_INET)
38                         buf[cnt++] = (struct address){ .family = AF_INET6, .addr = { [15] = 1 } };
39         }
40         return cnt;
41 }
42
43 static int name_from_numeric(struct address buf[static 1], const char *name, int family)
44 {
45         return __lookup_ipliteral(buf, name, family);
46 }
47
48 static int name_from_hosts(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
49 {
50         char line[512];
51         size_t l = strlen(name);
52         int cnt = 0, badfam = 0;
53         unsigned char _buf[1032];
54         FILE _f, *f = __fopen_rb_ca("/etc/hosts", &_f, _buf, sizeof _buf);
55         if (!f) switch (errno) {
56         case ENOENT:
57         case ENOTDIR:
58         case EACCES:
59                 return 0;
60         default:
61                 return EAI_SYSTEM;
62         }
63         while (fgets(line, sizeof line, f) && cnt < MAXADDRS) {
64                 char *p, *z;
65
66                 if ((p=strchr(line, '#'))) *p++='\n', *p=0;
67                 for(p=line+1; (p=strstr(p, name)) &&
68                         (!isspace(p[-1]) || !isspace(p[l])); p++);
69                 if (!p) continue;
70
71                 /* Isolate IP address to parse */
72                 for (p=line; *p && !isspace(*p); p++);
73                 *p++ = 0;
74                 switch (name_from_numeric(buf+cnt, line, family)) {
75                 case 1:
76                         cnt++;
77                         break;
78                 case 0:
79                         continue;
80                 default:
81                         badfam = EAI_NONAME;
82                         continue;
83                 }
84
85                 /* Extract first name as canonical name */
86                 for (; *p && isspace(*p); p++);
87                 for (z=p; *z && !isspace(*z); z++);
88                 *z = 0;
89                 if (is_valid_hostname(p)) memcpy(canon, p, z-p+1);
90         }
91         __fclose_ca(f);
92         return cnt ? cnt : badfam;
93 }
94
95 struct dpc_ctx {
96         struct address *addrs;
97         char *canon;
98         int cnt;
99 };
100
101 int __dns_parse(const unsigned char *, int, int (*)(void *, int, const void *, int, const void *), void *);
102 int __dn_expand(const unsigned char *, const unsigned char *, const unsigned char *, char *, int);
103 int __res_mkquery(int, const char *, int, int, const unsigned char *, int, const unsigned char*, unsigned char *, int);
104 int __res_msend_rc(int, const unsigned char *const *, const int *, unsigned char *const *, int *, int, const struct resolvconf *);
105
106 #define RR_A 1
107 #define RR_CNAME 5
108 #define RR_AAAA 28
109
110 static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet)
111 {
112         char tmp[256];
113         struct dpc_ctx *ctx = c;
114         if (ctx->cnt >= MAXADDRS) return -1;
115         switch (rr) {
116         case RR_A:
117                 if (len != 4) return -1;
118                 ctx->addrs[ctx->cnt].family = AF_INET;
119                 ctx->addrs[ctx->cnt].scopeid = 0;
120                 memcpy(ctx->addrs[ctx->cnt++].addr, data, 4);
121                 break;
122         case RR_AAAA:
123                 if (len != 16) return -1;
124                 ctx->addrs[ctx->cnt].family = AF_INET6;
125                 ctx->addrs[ctx->cnt].scopeid = 0;
126                 memcpy(ctx->addrs[ctx->cnt++].addr, data, 16);
127                 break;
128         case RR_CNAME:
129                 if (__dn_expand(packet, (const unsigned char *)packet + 512,
130                     data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp))
131                         strcpy(ctx->canon, tmp);
132                 break;
133         }
134         return 0;
135 }
136
137 static int name_from_dns(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family, const struct resolvconf *conf)
138 {
139         unsigned char qbuf[2][280], abuf[2][512];
140         const unsigned char *qp[2] = { qbuf[0], qbuf[1] };
141         unsigned char *ap[2] = { abuf[0], abuf[1] };
142         int qlens[2], alens[2];
143         int i, nq = 0;
144         struct dpc_ctx ctx = { .addrs = buf, .canon = canon };
145         static const struct { int af; int rr; } afrr[2] = {
146                 { .af = AF_INET6, .rr = RR_A },
147                 { .af = AF_INET, .rr = RR_AAAA },
148         };
149
150         for (i=0; i<2; i++) {
151                 if (family != afrr[i].af) {
152                         qlens[nq] = __res_mkquery(0, name, 1, afrr[i].rr,
153                                 0, 0, 0, qbuf[nq], sizeof *qbuf);
154                         if (qlens[nq] == -1)
155                                 return EAI_NONAME;
156                         nq++;
157                 }
158         }
159
160         if (__res_msend_rc(nq, qp, qlens, ap, alens, sizeof *abuf, conf) < 0)
161                 return EAI_SYSTEM;
162
163         for (i=0; i<nq; i++)
164                 __dns_parse(abuf[i], alens[i], dns_parse_callback, &ctx);
165
166         if (ctx.cnt) return ctx.cnt;
167         if (alens[0] < 4 || (abuf[0][3] & 15) == 2) return EAI_AGAIN;
168         if ((abuf[0][3] & 15) == 0) return EAI_NONAME;
169         if ((abuf[0][3] & 15) == 3) return 0;
170         return EAI_FAIL;
171 }
172
173 static int name_from_dns_search(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family)
174 {
175         char search[256];
176         struct resolvconf conf;
177         size_t l, dots;
178         char *p, *z;
179
180         if (__get_resolv_conf(&conf, search, sizeof search) < 0) return -1;
181
182         /* Count dots, suppress search when >=ndots or name ends in
183          * a dot, which is an explicit request for global scope. */
184         for (dots=l=0; name[l]; l++) if (name[l]=='.') dots++;
185         if (dots >= conf.ndots || name[l-1]=='.') *search = 0;
186
187         /* Strip final dot for canon, fail if multiple trailing dots. */
188         if (name[l-1]=='.') l--;
189         if (!l || name[l-1]=='.') return EAI_NONAME;
190
191         /* This can never happen; the caller already checked length. */
192         if (l >= 256) return EAI_NONAME;
193
194         /* Name with search domain appended is setup in canon[]. This both
195          * provides the desired default canonical name (if the requested
196          * name is not a CNAME record) and serves as a buffer for passing
197          * the full requested name to name_from_dns. */
198         memcpy(canon, name, l);
199         canon[l] = '.';
200
201         for (p=search; *p; p=z) {
202                 for (; isspace(*p); p++);
203                 for (z=p; *z && !isspace(*z); z++);
204                 if (z==p) break;
205                 if (z-p < 256 - l - 1) {
206                         memcpy(canon+l+1, p, z-p);
207                         canon[z-p+1+l] = 0;
208                         int cnt = name_from_dns(buf, canon, canon, family, &conf);
209                         if (cnt) return cnt;
210                 }
211         }
212
213         canon[l] = 0;
214         return name_from_dns(buf, canon, name, family, &conf);
215 }
216
217 static const struct policy {
218         unsigned char addr[16];
219         unsigned char len, mask;
220         unsigned char prec, label;
221 } defpolicy[] = {
222         { "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1", 15, 0xff, 50, 0 },
223         { "\0\0\0\0\0\0\0\0\0\0\xff\xff", 11, 0xff, 35, 4 },
224         { "\x20\2", 1, 0xff, 30, 2 },
225         { "\x20\1", 3, 0xff, 5, 5 },
226         { "\xfc", 0, 0xfe, 3, 13 },
227 #if 0
228         /* These are deprecated and/or returned to the address
229          * pool, so despite the RFC, treating them as special
230          * is probably wrong. */
231         { "", 11, 0xff, 1, 3 },
232         { "\xfe\xc0", 1, 0xc0, 1, 11 },
233         { "\x3f\xfe", 1, 0xff, 1, 12 },
234 #endif
235         /* Last rule must match all addresses to stop loop. */
236         { "", 0, 0, 40, 1 },
237 };
238
239 static const struct policy *policyof(const struct in6_addr *a)
240 {
241         int i;
242         for (i=0; ; i++) {
243                 if (memcmp(a->s6_addr, defpolicy[i].addr, defpolicy[i].len))
244                         continue;
245                 if ((a->s6_addr[defpolicy[i].len] & defpolicy[i].mask)
246                     != defpolicy[i].addr[defpolicy[i].len])
247                         continue;
248                 return defpolicy+i;
249         }
250 }
251
252 static int labelof(const struct in6_addr *a)
253 {
254         return policyof(a)->label;
255 }
256
257 static int scopeof(const struct in6_addr *a)
258 {
259         if (IN6_IS_ADDR_MULTICAST(a)) return a->s6_addr[1] & 15;
260         if (IN6_IS_ADDR_LINKLOCAL(a)) return 2;
261         if (IN6_IS_ADDR_LOOPBACK(a)) return 2;
262         if (IN6_IS_ADDR_SITELOCAL(a)) return 5;
263         return 14;
264 }
265
266 static int prefixmatch(const struct in6_addr *s, const struct in6_addr *d)
267 {
268         /* FIXME: The common prefix length should be limited to no greater
269          * than the nominal length of the prefix portion of the source
270          * address. However the definition of the source prefix length is
271          * not clear and thus this limiting is not yet implemented. */
272         unsigned i;
273         for (i=0; i<128 && !((s->s6_addr[i/8]^d->s6_addr[i/8])&(128>>(i%8))); i++);
274         return i;
275 }
276
277 #define DAS_USABLE              0x40000000
278 #define DAS_MATCHINGSCOPE       0x20000000
279 #define DAS_MATCHINGLABEL       0x10000000
280 #define DAS_PREC_SHIFT          20
281 #define DAS_SCOPE_SHIFT         16
282 #define DAS_PREFIX_SHIFT        8
283 #define DAS_ORDER_SHIFT         0
284
285 static int addrcmp(const void *_a, const void *_b)
286 {
287         const struct address *a = _a, *b = _b;
288         return b->sortkey - a->sortkey;
289 }
290
291 int __lookup_name(struct address buf[static MAXADDRS], char canon[static 256], const char *name, int family, int flags)
292 {
293         int cnt = 0, i, j;
294
295         *canon = 0;
296         if (name) {
297                 /* reject empty name and check len so it fits into temp bufs */
298                 size_t l = strnlen(name, 255);
299                 if (l-1 >= 254)
300                         return EAI_NONAME;
301                 memcpy(canon, name, l+1);
302         }
303
304         /* Procedurally, a request for v6 addresses with the v4-mapped
305          * flag set is like a request for unspecified family, followed
306          * by filtering of the results. */
307         if (flags & AI_V4MAPPED) {
308                 if (family == AF_INET6) family = AF_UNSPEC;
309                 else flags -= AI_V4MAPPED;
310         }
311
312         /* Try each backend until there's at least one result. */
313         cnt = name_from_null(buf, name, family, flags);
314         if (!cnt) cnt = name_from_numeric(buf, name, family);
315         if (!cnt && !(flags & AI_NUMERICHOST)) {
316                 cnt = name_from_hosts(buf, canon, name, family);
317                 if (!cnt) cnt = name_from_dns_search(buf, canon, name, family);
318         }
319         if (cnt<=0) return cnt ? cnt : EAI_NONAME;
320
321         /* Filter/transform results for v4-mapped lookup, if requested. */
322         if (flags & AI_V4MAPPED) {
323                 if (!(flags & AI_ALL)) {
324                         /* If any v6 results exist, remove v4 results. */
325                         for (i=0; i<cnt && buf[i].family != AF_INET6; i++);
326                         if (i<cnt) {
327                                 for (j=0; i<cnt; i++) {
328                                         if (buf[i].family == AF_INET6)
329                                                 buf[j++] = buf[i];
330                                 }
331                                 cnt = i = j;
332                         }
333                 }
334                 /* Translate any remaining v4 results to v6 */
335                 for (i=0; i<cnt; i++) {
336                         if (buf[i].family != AF_INET) continue;
337                         memcpy(buf[i].addr+12, buf[i].addr, 4);
338                         memcpy(buf[i].addr, "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
339                         buf[i].family = AF_INET6;
340                 }
341         }
342
343         /* No further processing is needed if there are fewer than 2
344          * results or if there are only IPv4 results. */
345         if (cnt<2 || family==AF_INET) return cnt;
346         for (i=0; i<cnt; i++) if (buf[i].family != AF_INET) break;
347         if (i==cnt) return cnt;
348
349         int cs;
350         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
351
352         /* The following implements a subset of RFC 3484/6724 destination
353          * address selection by generating a single 31-bit sort key for
354          * each address. Rules 3, 4, and 7 are omitted for having
355          * excessive runtime and code size cost and dubious benefit.
356          * So far the label/precedence table cannot be customized. */
357         for (i=0; i<cnt; i++) {
358                 int family = buf[i].family;
359                 int key = 0;
360                 struct sockaddr_in6 sa6 = { 0 }, da6 = {
361                         .sin6_family = AF_INET6,
362                         .sin6_scope_id = buf[i].scopeid,
363                         .sin6_port = 65535
364                 };
365                 struct sockaddr_in sa4 = { 0 }, da4 = {
366                         .sin_family = AF_INET,
367                         .sin_port = 65535
368                 };
369                 void *sa, *da;
370                 socklen_t salen, dalen;
371                 if (family == AF_INET6) {
372                         memcpy(da6.sin6_addr.s6_addr, buf[i].addr, 16);
373                         da = &da6; dalen = sizeof da6;
374                         sa = &sa6; salen = sizeof sa6;
375                 } else {
376                         memcpy(sa6.sin6_addr.s6_addr,
377                                 "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
378                         memcpy(da6.sin6_addr.s6_addr+12, buf[i].addr, 4);
379                         memcpy(da6.sin6_addr.s6_addr,
380                                 "\0\0\0\0\0\0\0\0\0\0\xff\xff", 12);
381                         memcpy(da6.sin6_addr.s6_addr+12, buf[i].addr, 4);
382                         memcpy(&da4.sin_addr, buf[i].addr, 4);
383                         da = &da4; dalen = sizeof da4;
384                         sa = &sa4; salen = sizeof sa4;
385                 }
386                 const struct policy *dpolicy = policyof(&da6.sin6_addr);
387                 int dscope = scopeof(&da6.sin6_addr);
388                 int dlabel = dpolicy->label;
389                 int dprec = dpolicy->prec;
390                 int prefixlen = 0;
391                 int fd = socket(family, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_UDP);
392                 if (fd >= 0) {
393                         if (!connect(fd, da, dalen)) {
394                                 key |= DAS_USABLE;
395                                 if (!getsockname(fd, sa, &salen)) {
396                                         if (family == AF_INET) memcpy(
397                                                 sa6.sin6_addr.s6_addr+12,
398                                                 &sa4.sin_addr, 4);
399                                         if (dscope == scopeof(&sa6.sin6_addr))
400                                                 key |= DAS_MATCHINGSCOPE;
401                                         if (dlabel == labelof(&sa6.sin6_addr))
402                                                 key |= DAS_MATCHINGLABEL;
403                                         prefixlen = prefixmatch(&sa6.sin6_addr,
404                                                 &da6.sin6_addr);
405                                 }
406                         }
407                         close(fd);
408                 }
409                 key |= dprec << DAS_PREC_SHIFT;
410                 key |= (15-dscope) << DAS_SCOPE_SHIFT;
411                 key |= prefixlen << DAS_PREFIX_SHIFT;
412                 key |= (MAXADDRS-i) << DAS_ORDER_SHIFT;
413                 buf[i].sortkey = key;
414         }
415         qsort(buf, cnt, sizeof *buf, addrcmp);
416
417         pthread_setcancelstate(cs, 0);
418
419         return cnt;
420 }