xref: /minix/lib/libwrap/hosts_access.c (revision 90b80121)
1 /*	$NetBSD: hosts_access.c,v 1.20 2012/03/21 10:10:37 matt Exp $	*/
2 
3  /*
4   * This module implements a simple access control language that is based on
5   * host (or domain) names, NIS (host) netgroup names, IP addresses (or
6   * network numbers) and daemon process names. When a match is found the
7   * search is terminated, and depending on whether PROCESS_OPTIONS is defined,
8   * a list of options is executed or an optional shell command is executed.
9   *
10   * Host and user names are looked up on demand, provided that suitable endpoint
11   * information is available as sockaddr_in structures or TLI netbufs. As a
12   * side effect, the pattern matching process may change the contents of
13   * request structure fields.
14   *
15   * Diagnostics are reported through syslog(3).
16   *
17   * Compile with -DNETGROUP if your library provides support for netgroups.
18   *
19   * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
20   */
21 
22 #include <sys/cdefs.h>
23 #ifndef lint
24 #if 0
25 static char sccsid[] = "@(#) hosts_access.c 1.21 97/02/12 02:13:22";
26 #else
27 __RCSID("$NetBSD: hosts_access.c,v 1.20 2012/03/21 10:10:37 matt Exp $");
28 #endif
29 #endif
30 
31 /* System libraries. */
32 
33 #include <sys/types.h>
34 #include <sys/param.h>
35 #ifdef INET6
36 #include <sys/socket.h>
37 #endif
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <syslog.h>
43 #include <ctype.h>
44 #include <errno.h>
45 #include <setjmp.h>
46 #include <string.h>
47 #include <netdb.h>
48 #ifdef  NETGROUP
49 #include <netgroup.h>
50 #include <rpcsvc/ypclnt.h>
51 #endif
52 
53 /* Local stuff. */
54 
55 #include "tcpd.h"
56 
57 /* Error handling. */
58 
59 extern jmp_buf tcpd_buf;
60 
61 /* Delimiters for lists of daemons or clients. */
62 
63 static char sep[] = ", \t\r\n";
64 
65 /* Constants to be used in assignments only, not in comparisons... */
66 
67 #define	YES		1
68 #define	NO		0
69 
70  /*
71   * These variables are globally visible so that they can be redirected in
72   * verification mode.
73   */
74 
75 const char   *hosts_allow_table = HOSTS_ALLOW;
76 const char   *hosts_deny_table = HOSTS_DENY;
77 int     hosts_access_verbose = 0;
78 
79  /*
80   * In a long-running process, we are not at liberty to just go away.
81   */
82 
83 int     resident = (-1);		/* -1, 0: unknown; +1: yes */
84 
85 /* Forward declarations. */
86 
87 static int table_match(const char *, struct request_info *);
88 static int list_match(char *, struct request_info *,
89     int (*)(char *, struct request_info *));
90 static int server_match(char *, struct request_info *);
91 static int client_match(char *, struct request_info *);
92 static int host_match(char *, struct host_info *);
93 static int hostfile_match(char *, struct host_info *);
94 static int rbl_match(char *, char *);
95 static int string_match(char *, char *);
96 static int masked_match(char *, char *, char *);
97 static int masked_match4(char *, char *, char *);
98 #ifdef INET6
99 static int masked_match6(char *, char *, char *);
100 #endif
101 
102 /* Size of logical line buffer. */
103 
104 #define	BUFLEN 2048
105 
106 /* hosts_access - host access control facility */
107 
108 int
109 hosts_access(struct request_info *request)
110 {
111     int     verdict;
112 
113     /*
114      * If the (daemon, client) pair is matched by an entry in the file
115      * /etc/hosts.allow, access is granted. Otherwise, if the (daemon,
116      * client) pair is matched by an entry in the file /etc/hosts.deny,
117      * access is denied. Otherwise, access is granted. A non-existent
118      * access-control file is treated as an empty file.
119      *
120      * After a rule has been matched, the optional language extensions may
121      * decide to grant or refuse service anyway. Or, while a rule is being
122      * processed, a serious error is found, and it seems better to play safe
123      * and deny service. All this is done by jumping back into the
124      * hosts_access() routine, bypassing the regular return from the
125      * table_match() function calls below.
126      */
127 
128     if (resident <= 0)
129 	resident++;
130     verdict = setjmp(tcpd_buf);
131     if (verdict != 0)
132 	return (verdict == AC_PERMIT);
133     if (table_match(hosts_allow_table, request))
134 	return (YES);
135     if (table_match(hosts_deny_table, request))
136 	return (NO);
137     return (YES);
138 }
139 
140 /* table_match - match table entries with (daemon, client) pair */
141 
142 static int
143 table_match(const char *table, struct request_info *request)
144 {
145     FILE   *fp;
146     char    sv_list[BUFLEN];		/* becomes list of daemons */
147     char   *cl_list;			/* becomes list of clients */
148     char   *sh_cmd = NULL;		/* becomes optional shell command */
149     int     match = NO;
150     struct tcpd_context saved_context;
151 
152     saved_context = tcpd_context;		/* stupid compilers */
153 
154     /*
155      * Between the fopen() and fclose() calls, avoid jumps that may cause
156      * file descriptor leaks.
157      */
158 
159     if ((fp = fopen(table, "r")) != 0) {
160 	tcpd_context.file = table;
161 	tcpd_context.line = 0;
162 	while (match == NO && xgets(sv_list, sizeof(sv_list), fp) != 0) {
163 	    if (sv_list[strlen(sv_list) - 1] != '\n') {
164 		tcpd_warn("missing newline or line too long");
165 		continue;
166 	    }
167 	    if (sv_list[0] == '#' || sv_list[strspn(sv_list, " \t\r\n")] == 0)
168 		continue;
169 	    if ((cl_list = split_at(sv_list, ':')) == 0) {
170 		tcpd_warn("missing \":\" separator");
171 		continue;
172 	    }
173 	    sh_cmd = split_at(cl_list, ':');
174 	    match = list_match(sv_list, request, server_match)
175 		&& list_match(cl_list, request, client_match);
176 	}
177 	(void) fclose(fp);
178     } else if (errno != ENOENT) {
179 	tcpd_warn("cannot open %s: %m", table);
180     }
181     if (match) {
182 	if (hosts_access_verbose > 1)
183 	    syslog(LOG_DEBUG, "matched:  %s line %d",
184 		   tcpd_context.file, tcpd_context.line);
185 	if (sh_cmd) {
186 #ifdef PROCESS_OPTIONS
187 	    process_options(sh_cmd, request);
188 #else
189 	    char    cmd[BUFSIZ];
190 	    shell_cmd(percent_x(cmd, sizeof(cmd), sh_cmd, request));
191 #endif
192 	}
193     }
194     tcpd_context = saved_context;
195     return (match);
196 }
197 
198 /* list_match - match a request against a list of patterns with exceptions */
199 
200 static int
201 list_match(char *list, struct request_info *request,
202     int (*match_fn)(char *, struct request_info *))
203 {
204     char   *tok;
205     static char *last;
206     int l;
207 
208     /*
209      * Process tokens one at a time. We have exhausted all possible matches
210      * when we reach an "EXCEPT" token or the end of the list. If we do find
211      * a match, look for an "EXCEPT" list and recurse to determine whether
212      * the match is affected by any exceptions.
213      */
214 
215     for (tok = strtok_r(list, sep, &last); tok != 0;
216       tok = strtok_r(NULL, sep, &last)) {
217 	if (STR_EQ(tok, "EXCEPT"))		/* EXCEPT: give up */
218 	    return (NO);
219 	l = strlen(tok);
220 	if (*tok == '[' && tok[l - 1] == ']') {
221 	    tok[l - 1] = '\0';
222 	    tok++;
223 	}
224 	if (match_fn(tok, request)) {		/* YES: look for exceptions */
225 	    while ((tok = strtok_r(NULL, sep, &last)) && STR_NE(tok, "EXCEPT"))
226 		 /* VOID */ ;
227 	    return (tok == 0 || list_match(NULL, request, match_fn) == 0);
228 	}
229     }
230     return (NO);
231 }
232 
233 /* server_match - match server information */
234 
235 static int
236 server_match(char *tok, struct request_info *request)
237 {
238     char   *host;
239 
240     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain daemon */
241 	return (string_match(tok, eval_daemon(request)));
242     } else {					/* daemon@host */
243 	return (string_match(tok, eval_daemon(request))
244 		&& host_match(host, request->server));
245     }
246 }
247 
248 /* client_match - match client information */
249 
250 static int
251 client_match(char *tok, struct request_info *request)
252 {
253     char   *host;
254 
255     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain host */
256 	return (host_match(tok, request->client));
257     } else {					/* user@host */
258 	return (host_match(host, request->client)
259 		&& string_match(tok, eval_user(request)));
260     }
261 }
262 
263 /* host_match - match host name and/or address against pattern */
264 
265 static int
266 host_match(char *tok, struct host_info *host)
267 {
268     char   *mask;
269 
270     /*
271      * This code looks a little hairy because we want to avoid unnecessary
272      * hostname lookups.
273      *
274      * The KNOWN pattern requires that both address AND name be known; some
275      * patterns are specific to host names or to host addresses; all other
276      * patterns are satisfied when either the address OR the name match.
277      */
278 
279     if (tok[0] == '@') {			/* netgroup: look it up */
280 #ifdef  NETGROUP
281 	static char *mydomain = 0;
282 	if (mydomain == 0)
283 	    yp_get_default_domain(&mydomain);
284 	return (innetgr(tok + 1, eval_hostname(host), NULL, mydomain));
285 #else
286 	tcpd_warn("netgroup support is disabled");	/* not tcpd_jump() */
287 	return (NO);
288 #endif
289     } else if (tok[0] == '/') {			/* /file hack */
290 	return (hostfile_match(tok, host));
291     } else if (STR_EQ(tok, "KNOWN")) {		/* check address and name */
292 	char   *name = eval_hostname(host);
293 	return (STR_NE(eval_hostaddr(host), unknown) && HOSTNAME_KNOWN(name));
294     } else if (STR_EQ(tok, "LOCAL")) {		/* local: no dots in name */
295 	char   *name = eval_hostname(host);
296 	return (strchr(name, '.') == 0 && HOSTNAME_KNOWN(name));
297     } else if (strncmp(tok, "{RBL}.", 6) == 0) { /* RBL lookup in domain */
298 	return rbl_match(tok+6, eval_hostaddr(host));
299     } else if ((mask = split_at(tok, '/')) != 0) {	/* net/mask */
300 	return (masked_match(tok, mask, eval_hostaddr(host)));
301     } else {					/* anything else */
302 	return (string_match(tok, eval_hostaddr(host))
303 	    || (NOT_INADDR(tok) && string_match(tok, eval_hostname(host))));
304     }
305 }
306 
307 /* hostfile_match - look up host patterns from file */
308 
309 static int
310 hostfile_match(char *path, struct host_info *host)
311 {
312     char    tok[BUFSIZ];
313     int     match = NO;
314     FILE   *fp;
315 
316     if ((fp = fopen(path, "r")) != 0) {
317 	while (fscanf(fp, "%s", tok) == 1 && !(match = host_match(tok, host)))
318 	     /* void */ ;
319 	fclose(fp);
320     } else if (errno != ENOENT) {
321 	tcpd_warn("open %s: %m", path);
322     }
323     return (match);
324 }
325 
326 /* rbl_match() - match host by looking up in RBL domain */
327 
328 static int
329 rbl_match(
330     char   *rbl_domain,			/* RBL domain */
331     char   *rbl_hostaddr)		/* hostaddr */
332 {
333     char *rbl_name;
334     unsigned long host_address;
335     int ret = NO;
336     size_t len = strlen(rbl_domain) + (4 * 4) + 2;
337 
338     if (dot_quad_addr(rbl_hostaddr, &host_address) != 0) {
339 	tcpd_warn("unable to convert %s to address", rbl_hostaddr);
340 	return (NO);
341     }
342     host_address = ntohl(host_address);
343     /*  construct the rbl name to look up */
344     if ((rbl_name = malloc(len)) == NULL) {
345 	tcpd_jump("not enough memory to build RBL name for %s in %s", rbl_hostaddr, rbl_domain);
346 	/* NOTREACHED */
347     }
348     snprintf(rbl_name, len, "%u.%u.%u.%u.%s",
349 	    (unsigned int) ((host_address) & 0xff),
350 	    (unsigned int) ((host_address >> 8) & 0xff),
351 	    (unsigned int) ((host_address >> 16) & 0xff),
352 	    (unsigned int) ((host_address >> 24) & 0xff),
353 	    rbl_domain);
354     /* look it up */
355     if (gethostbyname(rbl_name) != NULL) {
356 	/* successful lookup - they're on the RBL list */
357 	ret = YES;
358     }
359     free(rbl_name);
360 
361     return ret;
362 }
363 
364 /* string_match - match string against pattern */
365 
366 static int
367 string_match(char *tok, char *string)
368 {
369     int     n;
370 
371     if (tok[0] == '.') {			/* suffix */
372 	n = strlen(string) - strlen(tok);
373 	return (n > 0 && STR_EQ(tok, string + n));
374     } else if (STR_EQ(tok, "ALL")) {		/* all: match any */
375 	return (YES);
376     } else if (STR_EQ(tok, "KNOWN")) {		/* not unknown */
377 	return (STR_NE(string, unknown));
378     } else if (tok[(n = strlen(tok)) - 1] == '.') {	/* prefix */
379 	return (STRN_EQ(tok, string, n));
380     } else {					/* exact match */
381 	return (STR_EQ(tok, string));
382     }
383 }
384 
385 /* masked_match - match address against netnumber/netmask */
386 
387 static int
388 masked_match(char *net_tok, char *mask_tok, char *string)
389 {
390 #ifndef INET6
391     return masked_match4(net_tok, mask_tok, string);
392 #else
393     /*
394      * masked_match4() is kept just for supporting shortened IPv4 address form.
395      * If we could get rid of shortened IPv4 form, we could just always use
396      * masked_match6().
397      */
398     if (dot_quad_addr(net_tok, NULL) != -1 &&
399         dot_quad_addr(mask_tok, NULL) != -1 &&
400         dot_quad_addr(string, NULL) != -1) {
401 	return masked_match4(net_tok, mask_tok, string);
402     } else
403 	return masked_match6(net_tok, mask_tok, string);
404 #endif
405 }
406 
407 static int
408 masked_match4(char *net_tok, char *mask_tok, char *string)
409 {
410     unsigned long net;
411     unsigned long mask;
412     unsigned long addr;
413 
414     /*
415      * Disallow forms other than dotted quad: the treatment that inet_addr()
416      * gives to forms with less than four components is inconsistent with the
417      * access control language. John P. Rouillard <rouilj@cs.umb.edu>.
418      */
419 
420     if (dot_quad_addr(string, &addr) != 0)
421 	return (NO);
422     if (dot_quad_addr(net_tok, &net) != 0 ||
423         dot_quad_addr(mask_tok, &mask) != 0) {
424 	tcpd_warn("bad net/mask expression: %s/%s", net_tok, mask_tok);
425 	return (NO);				/* not tcpd_jump() */
426     }
427 
428     if ((net & ~mask) != 0)
429 	tcpd_warn("host bits not all zero in %s/%s", net_tok, mask_tok);
430 
431     return ((addr & mask) == net);
432 }
433 
434 #ifdef INET6
435 static int
436 masked_match6(char *net_tok, char *mask_tok, char *string)
437 {
438     union {
439 	struct sockaddr sa;
440 	struct sockaddr_in sin;
441 	struct sockaddr_in6 sin6;
442     } net, mask, addr;
443     struct addrinfo hints, *res;
444     unsigned long masklen;
445     char *ep;
446     size_t i;
447     char *np, *mp, *ap;
448     size_t alen;
449 
450     memset(&hints, 0, sizeof(hints));
451     hints.ai_family = PF_UNSPEC;
452     hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
453     hints.ai_flags = AI_NUMERICHOST;
454     if (getaddrinfo(net_tok, "0", &hints, &res) == 0) {
455 	if (res->ai_addrlen > sizeof(net) || res->ai_next) {
456 	    freeaddrinfo(res);
457 	    return NO;
458 	}
459 	memcpy(&net, res->ai_addr, res->ai_addrlen);
460 	freeaddrinfo(res);
461     } else
462 	return NO;
463 
464     memset(&hints, 0, sizeof(hints));
465     hints.ai_family = net.sa.sa_family;
466     hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
467     hints.ai_flags = AI_NUMERICHOST;
468     ep = NULL;
469     if (getaddrinfo(mask_tok, "0", &hints, &res) == 0) {
470 	if (res->ai_family == AF_INET6 &&
471 	    ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id) {
472 	    freeaddrinfo(res);
473 	    return NO;
474 	}
475 	if (res->ai_addrlen > sizeof(mask) || res->ai_next) {
476 	    freeaddrinfo(res);
477 	    return NO;
478 	}
479 	memcpy(&mask, res->ai_addr, res->ai_addrlen);
480 	freeaddrinfo(res);
481     } else {
482 	ep = NULL;
483 	masklen = strtoul(mask_tok, &ep, 10);
484 	if (ep && !*ep) {
485 	    memset(&mask, 0, sizeof(mask));
486 	    mask.sa.sa_family = net.sa.sa_family;
487 	    mask.sa.sa_len = net.sa.sa_len;
488 	    switch (mask.sa.sa_family) {
489 	    case AF_INET:
490 		mp = (char *)&mask.sin.sin_addr;
491 		alen = sizeof(mask.sin.sin_addr);
492 		break;
493 	    case AF_INET6:
494 		mp = (char *)&mask.sin6.sin6_addr;
495 		alen = sizeof(mask.sin6.sin6_addr);
496 		break;
497 	    default:
498 		return NO;
499 	    }
500 	    if (masklen / 8 > alen)
501 		return NO;
502 	    memset(mp, 0xff, masklen / 8);
503 	    if (masklen % 8)
504 		mp[masklen / 8] = 0xff00 >> (masklen % 8);
505 	} else
506 	    return NO;
507     }
508 
509     memset(&hints, 0, sizeof(hints));
510     hints.ai_family = PF_UNSPEC;
511     hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
512     hints.ai_flags = AI_NUMERICHOST;
513     if (getaddrinfo(string, "0", &hints, &res) == 0) {
514 	if (res->ai_addrlen > sizeof(addr) || res->ai_next) {
515 	    freeaddrinfo(res);
516 	    return NO;
517 	}
518 	/* special case - IPv4 mapped address */
519 	if (net.sa.sa_family == AF_INET && res->ai_family == AF_INET6 &&
520 	    IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res->ai_addr)->sin6_addr)) {
521 	    memset(&addr, 0, sizeof(addr));
522 	    addr.sa.sa_family = net.sa.sa_family;
523 	    addr.sa.sa_len = net.sa.sa_len;
524 	    memcpy(&addr.sin.sin_addr,
525 	        &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr.s6_addr[12],
526 		sizeof(addr.sin.sin_addr));
527 	} else
528 	    memcpy(&addr, res->ai_addr, res->ai_addrlen);
529 	freeaddrinfo(res);
530     } else
531 	return NO;
532 
533     if (net.sa.sa_family != mask.sa.sa_family ||
534         net.sa.sa_family != addr.sa.sa_family) {
535 	return NO;
536     }
537 
538     switch (net.sa.sa_family) {
539     case AF_INET:
540 	np = (char *)&net.sin.sin_addr;
541 	mp = (char *)&mask.sin.sin_addr;
542 	ap = (char *)&addr.sin.sin_addr;
543 	alen = sizeof(net.sin.sin_addr);
544 	break;
545     case AF_INET6:
546 	np = (char *)&net.sin6.sin6_addr;
547 	mp = (char *)&mask.sin6.sin6_addr;
548 	ap = (char *)&addr.sin6.sin6_addr;
549 	alen = sizeof(net.sin6.sin6_addr);
550 	break;
551     default:
552 	return NO;
553     }
554 
555     for (i = 0; i < alen; i++)
556 	if (np[i] & ~mp[i]) {
557 	    tcpd_warn("host bits not all zero in %s/%s", net_tok, mask_tok);
558 	    break;
559 	}
560 
561     for (i = 0; i < alen; i++)
562 	ap[i] &= mp[i];
563 
564     if (addr.sa.sa_family == AF_INET6 && addr.sin6.sin6_scope_id &&
565         addr.sin6.sin6_scope_id != net.sin6.sin6_scope_id)
566 	return NO;
567     return (memcmp(ap, np, alen) == 0);
568 }
569 #endif
570