xref: /freebsd/contrib/tcp_wrappers/hosts_access.c (revision 46bcf11d508f4330b988cf010650e84f9ed5a0b2)
1  /*
2   * This module implements a simple access control language that is based on
3   * host (or domain) names, NIS (host) netgroup names, IP addresses (or
4   * network numbers) and daemon process names. When a match is found the
5   * search is terminated, and depending on whether PROCESS_OPTIONS is defined,
6   * a list of options is executed or an optional shell command is executed.
7   *
8   * Host and user names are looked up on demand, provided that suitable endpoint
9   * information is available as sockaddr_in structures or TLI netbufs. As a
10   * side effect, the pattern matching process may change the contents of
11   * request structure fields.
12   *
13   * Diagnostics are reported through syslog(3).
14   *
15   * Compile with -DNETGROUP if your library provides support for netgroups.
16   *
17   * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
18   *
19   * $FreeBSD$
20   */
21 
22 #ifndef lint
23 static char sccsid[] = "@(#) hosts_access.c 1.21 97/02/12 02:13:22";
24 #endif
25 
26 /* System libraries. */
27 
28 #include <sys/types.h>
29 #ifdef INT32_T
30     typedef uint32_t u_int32_t;
31 #endif
32 #include <sys/param.h>
33 #ifdef INET6
34 #include <sys/socket.h>
35 #endif
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #include <stdio.h>
39 #include <syslog.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <setjmp.h>
43 #include <string.h>
44 #ifdef INET6
45 #include <netdb.h>
46 #endif
47 #include <stdlib.h>
48 
49 extern char *fgets();
50 extern int errno;
51 
52 #ifndef	INADDR_NONE
53 #define	INADDR_NONE	(-1)		/* XXX should be 0xffffffff */
54 #endif
55 
56 /* Local stuff. */
57 
58 #include "tcpd.h"
59 
60 /* Error handling. */
61 
62 extern jmp_buf tcpd_buf;
63 
64 /* Delimiters for lists of daemons or clients. */
65 
66 static char sep[] = ", \t\r\n";
67 
68 /* Constants to be used in assignments only, not in comparisons... */
69 
70 #define	YES		1
71 #define	NO		0
72 
73  /*
74   * These variables are globally visible so that they can be redirected in
75   * verification mode.
76   */
77 
78 char   *hosts_allow_table = HOSTS_ALLOW;
79 char   *hosts_deny_table = HOSTS_DENY;
80 int     hosts_access_verbose = 0;
81 
82  /*
83   * In a long-running process, we are not at liberty to just go away.
84   */
85 
86 int     resident = (-1);		/* -1, 0: unknown; +1: yes */
87 
88 /* Forward declarations. */
89 
90 static int table_match();
91 static int list_match();
92 static int server_match();
93 static int client_match();
94 static int host_match();
95 static int string_match();
96 static int masked_match();
97 #ifdef INET6
98 static int masked_match4();
99 static int masked_match6();
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     hosts_access(request)
109 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 table_match(table, request)
143 char   *table;
144 struct request_info *request;
145 {
146     FILE   *fp;
147     char    sv_list[BUFLEN];		/* becomes list of daemons */
148     char   *cl_list;			/* becomes list of clients */
149     char   *sh_cmd;			/* becomes optional shell command */
150     int     match = NO;
151     struct tcpd_context saved_context;
152     char   *cp;
153 
154     saved_context = tcpd_context;		/* stupid compilers */
155 
156     /*
157      * Between the fopen() and fclose() calls, avoid jumps that may cause
158      * file descriptor leaks.
159      */
160 
161     if ((fp = fopen(table, "r")) != 0) {
162 	tcpd_context.file = table;
163 	tcpd_context.line = 0;
164 	while (match == NO && xgets(sv_list, sizeof(sv_list), fp) != 0) {
165 	    if (sv_list[strlen(sv_list) - 1] != '\n') {
166 		tcpd_warn("missing newline or line too long");
167 		continue;
168 	    }
169 	    /* Ignore anything after unescaped # character */
170 	    for (cp = strchr(sv_list, '#'); cp != NULL;) {
171 		if (cp > sv_list && cp[-1] == '\\') {
172 		    cp = strchr(cp + 1, '#');
173 		    continue;
174 		}
175 		*cp = '\0';
176 		break;
177 	    }
178 	    if (sv_list[strspn(sv_list, " \t\r\n")] == 0)
179 		continue;
180 	    if ((cl_list = split_at(sv_list, ':')) == 0) {
181 		tcpd_warn("missing \":\" separator");
182 		continue;
183 	    }
184 	    sh_cmd = split_at(cl_list, ':');
185 	    match = list_match(sv_list, request, server_match)
186 		&& list_match(cl_list, request, client_match);
187 	}
188 	(void) fclose(fp);
189     } else if (errno != ENOENT) {
190 	tcpd_warn("cannot open %s: %m", table);
191     }
192     if (match) {
193 	if (hosts_access_verbose > 1)
194 	    syslog(LOG_DEBUG, "matched:  %s line %d",
195 		   tcpd_context.file, tcpd_context.line);
196 	if (sh_cmd) {
197 #ifdef PROCESS_OPTIONS
198 	    process_options(sh_cmd, request);
199 #else
200 	    char    cmd[BUFSIZ];
201 	    shell_cmd(percent_x(cmd, sizeof(cmd), sh_cmd, request));
202 #endif
203 	}
204     }
205     tcpd_context = saved_context;
206     return (match);
207 }
208 
209 /* list_match - match a request against a list of patterns with exceptions */
210 
211 static int list_match(list, request, match_fn)
212 char   *list;
213 struct request_info *request;
214 int   (*match_fn) ();
215 {
216     char   *tok;
217 
218     /*
219      * Process tokens one at a time. We have exhausted all possible matches
220      * when we reach an "EXCEPT" token or the end of the list. If we do find
221      * a match, look for an "EXCEPT" list and recurse to determine whether
222      * the match is affected by any exceptions.
223      */
224 
225     for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) {
226 	if (STR_EQ(tok, "EXCEPT"))		/* EXCEPT: give up */
227 	    return (NO);
228 	if (match_fn(tok, request)) {		/* YES: look for exceptions */
229 	    while ((tok = strtok((char *) 0, sep)) && STR_NE(tok, "EXCEPT"))
230 		 /* VOID */ ;
231 	    return (tok == 0 || list_match((char *) 0, request, match_fn) == 0);
232 	}
233     }
234     return (NO);
235 }
236 
237 /* server_match - match server information */
238 
239 static int server_match(tok, request)
240 char   *tok;
241 struct request_info *request;
242 {
243     char   *host;
244 
245     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain daemon */
246 	return (string_match(tok, eval_daemon(request)));
247     } else {					/* daemon@host */
248 	return (string_match(tok, eval_daemon(request))
249 		&& host_match(host, request->server));
250     }
251 }
252 
253 /* client_match - match client information */
254 
255 static int client_match(tok, request)
256 char   *tok;
257 struct request_info *request;
258 {
259     char   *host;
260 
261     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain host */
262 	return (host_match(tok, request->client));
263     } else {					/* user@host */
264 	return (host_match(host, request->client)
265 		&& string_match(tok, eval_user(request)));
266     }
267 }
268 
269 /* hostfile_match - look up host patterns from file */
270 
271 static int hostfile_match(path, host)
272 char   *path;
273 struct hosts_info *host;
274 {
275     char    tok[BUFSIZ];
276     int     match = NO;
277     FILE   *fp;
278 
279     if ((fp = fopen(path, "r")) != 0) {
280 	while (fscanf(fp, "%s", tok) == 1 && !(match = host_match(tok, host)))
281 	     /* void */ ;
282 	fclose(fp);
283     } else if (errno != ENOENT) {
284 	tcpd_warn("open %s: %m", path);
285     }
286     return (match);
287 }
288 
289 /* host_match - match host name and/or address against pattern */
290 
291 static int host_match(tok, host)
292 char   *tok;
293 struct host_info *host;
294 {
295     char   *mask;
296 
297     /*
298      * This code looks a little hairy because we want to avoid unnecessary
299      * hostname lookups.
300      *
301      * The KNOWN pattern requires that both address AND name be known; some
302      * patterns are specific to host names or to host addresses; all other
303      * patterns are satisfied when either the address OR the name match.
304      */
305 
306     if (tok[0] == '@') {			/* netgroup: look it up */
307 #ifdef  NETGROUP
308 	static char *mydomain = 0;
309 	if (mydomain == 0)
310 	    yp_get_default_domain(&mydomain);
311 	return (innetgr(tok + 1, eval_hostname(host), (char *) 0, mydomain));
312 #else
313 	tcpd_warn("netgroup support is disabled");	/* not tcpd_jump() */
314 	return (NO);
315 #endif
316     } else if (tok[0] == '/') {			/* /file hack */
317 	return (hostfile_match(tok, host));
318     } else if (STR_EQ(tok, "KNOWN")) {		/* check address and name */
319 	char   *name = eval_hostname(host);
320 	return (STR_NE(eval_hostaddr(host), unknown) && HOSTNAME_KNOWN(name));
321     } else if (STR_EQ(tok, "LOCAL")) {		/* local: no dots in name */
322 	char   *name = eval_hostname(host);
323 	return (strchr(name, '.') == 0 && HOSTNAME_KNOWN(name));
324     } else if ((mask = split_at(tok, '/')) != 0) {	/* net/mask */
325 	return (masked_match(tok, mask, eval_hostaddr(host)));
326     } else {					/* anything else */
327 	return (string_match(tok, eval_hostaddr(host))
328 	    || (NOT_INADDR(tok) && string_match(tok, eval_hostname(host))));
329     }
330 }
331 
332 /* string_match - match string against pattern */
333 
334 static int string_match(tok, string)
335 char   *tok;
336 char   *string;
337 {
338     int     n;
339 
340 #ifdef INET6
341     /* convert IPv4 mapped IPv6 address to IPv4 address */
342     if (STRN_EQ(string, "::ffff:", 7)
343 	&& dot_quad_addr(string + 7) != INADDR_NONE) {
344 	string += 7;
345     }
346 #endif
347     if (tok[0] == '.') {			/* suffix */
348 	n = strlen(string) - strlen(tok);
349 	return (n > 0 && STR_EQ(tok, string + n));
350     } else if (STR_EQ(tok, "ALL")) {		/* all: match any */
351 	return (YES);
352     } else if (STR_EQ(tok, "KNOWN")) {		/* not unknown */
353 	return (STR_NE(string, unknown));
354     } else if (tok[(n = strlen(tok)) - 1] == '.') {	/* prefix */
355 	return (STRN_EQ(tok, string, n));
356     } else {					/* exact match */
357 #ifdef INET6
358 	struct addrinfo hints, *res;
359 	struct sockaddr_in6 pat, addr;
360 	int len, ret;
361 	char ch;
362 
363 	len = strlen(tok);
364 	if (*tok == '[' && tok[len - 1] == ']') {
365 	    ch = tok[len - 1];
366 	    tok[len - 1] = '\0';
367 	    memset(&hints, 0, sizeof(hints));
368 	    hints.ai_family = AF_INET6;
369 	    hints.ai_socktype = SOCK_STREAM;
370 	    hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
371 	    if ((ret = getaddrinfo(tok + 1, NULL, &hints, &res)) == 0) {
372 		memcpy(&pat, res->ai_addr, sizeof(pat));
373 		freeaddrinfo(res);
374 	    }
375 	    tok[len - 1] = ch;
376 	    if (ret != 0 || getaddrinfo(string, NULL, &hints, &res) != 0)
377 		return NO;
378 	    memcpy(&addr, res->ai_addr, sizeof(addr));
379 	    freeaddrinfo(res);
380 	    if (pat.sin6_scope_id != 0 &&
381 		addr.sin6_scope_id != pat.sin6_scope_id)
382 		return NO;
383 	    return (!memcmp(&pat.sin6_addr, &addr.sin6_addr,
384 			    sizeof(struct in6_addr)));
385 	    return (ret);
386 	}
387 #endif
388 	return (STR_EQ(tok, string));
389     }
390 }
391 
392 /* masked_match - match address against netnumber/netmask */
393 
394 #ifdef INET6
395 static int masked_match(net_tok, mask_tok, string)
396 char   *net_tok;
397 char   *mask_tok;
398 char   *string;
399 {
400     return (masked_match4(net_tok, mask_tok, string) ||
401 	    masked_match6(net_tok, mask_tok, string));
402 }
403 
404 static int masked_match4(net_tok, mask_tok, string)
405 #else
406 static int masked_match(net_tok, mask_tok, string)
407 #endif
408 char   *net_tok;
409 char   *mask_tok;
410 char   *string;
411 {
412 #ifdef INET6
413     u_int32_t net;
414     u_int32_t mask;
415     u_int32_t addr;
416 #else
417     unsigned long net;
418     unsigned long mask;
419     unsigned long addr;
420 #endif
421 
422     /*
423      * Disallow forms other than dotted quad: the treatment that inet_addr()
424      * gives to forms with less than four components is inconsistent with the
425      * access control language. John P. Rouillard <rouilj@cs.umb.edu>.
426      */
427 
428     if ((addr = dot_quad_addr(string)) == INADDR_NONE)
429 	return (NO);
430     if ((net = dot_quad_addr(net_tok)) == INADDR_NONE
431 	|| (mask = dot_quad_addr(mask_tok)) == INADDR_NONE) {
432 #ifndef INET6
433 	tcpd_warn("bad net/mask expression: %s/%s", net_tok, mask_tok);
434 #endif
435 	return (NO);				/* not tcpd_jump() */
436     }
437     return ((addr & mask) == net);
438 }
439 
440 #ifdef INET6
441 static int masked_match6(net_tok, mask_tok, string)
442 char   *net_tok;
443 char   *mask_tok;
444 char   *string;
445 {
446     struct addrinfo hints, *res;
447     struct sockaddr_in6 net, addr;
448     u_int32_t mask;
449     int len, mask_len, i = 0;
450     char ch;
451 
452     memset(&hints, 0, sizeof(hints));
453     hints.ai_family = AF_INET6;
454     hints.ai_socktype = SOCK_STREAM;
455     hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
456     if (getaddrinfo(string, NULL, &hints, &res) != 0)
457 	return NO;
458     memcpy(&addr, res->ai_addr, sizeof(addr));
459     freeaddrinfo(res);
460 
461     if (IN6_IS_ADDR_V4MAPPED(&addr.sin6_addr)) {
462 	if ((*(u_int32_t *)&net.sin6_addr.s6_addr[12] = dot_quad_addr(net_tok)) == INADDR_NONE
463 	 || (mask = dot_quad_addr(mask_tok)) == INADDR_NONE)
464 	    return (NO);
465 	return ((*(u_int32_t *)&addr.sin6_addr.s6_addr[12] & mask) == *(u_int32_t *)&net.sin6_addr.s6_addr[12]);
466     }
467 
468     /* match IPv6 address against netnumber/prefixlen */
469     len = strlen(net_tok);
470     if (*net_tok != '[' || net_tok[len - 1] != ']')
471 	return NO;
472     ch = net_tok[len - 1];
473     net_tok[len - 1] = '\0';
474     if (getaddrinfo(net_tok + 1, NULL, &hints, &res) != 0) {
475 	net_tok[len - 1] = ch;
476 	return NO;
477     }
478     memcpy(&net, res->ai_addr, sizeof(net));
479     freeaddrinfo(res);
480     net_tok[len - 1] = ch;
481     if ((mask_len = atoi(mask_tok)) < 0 || mask_len > 128)
482 	return NO;
483 
484     if (net.sin6_scope_id != 0 && addr.sin6_scope_id != net.sin6_scope_id)
485 	return NO;
486     while (mask_len > 0) {
487 	if (mask_len < 32) {
488 	    mask = htonl(~(0xffffffff >> mask_len));
489 	    if ((*(u_int32_t *)&addr.sin6_addr.s6_addr[i] & mask) != (*(u_int32_t *)&net.sin6_addr.s6_addr[i] & mask))
490 		return NO;
491 	    break;
492 	}
493 	if (*(u_int32_t *)&addr.sin6_addr.s6_addr[i] != *(u_int32_t *)&net.sin6_addr.s6_addr[i])
494 	    return NO;
495 	i += 4;
496 	mask_len -= 32;
497     }
498     return YES;
499 }
500 #endif /* INET6 */
501