xref: /freebsd/contrib/tcp_wrappers/hosts_access.c (revision 6be3386466ab79a84b48429ae66244f21526d3df)
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(char *table, struct request_info *request);
91 static int list_match(char *list, struct request_info *request,
92     int (*match_fn)(char *, struct request_info *));
93 static int server_match(char *tok, struct request_info *request);
94 static int client_match(char *tok, struct request_info *request);
95 static int host_match(char *tok, struct host_info *host);
96 static int string_match(char *tok, char *string);
97 static int masked_match(char *net_tok, char *mask_tok, char *string);
98 #ifdef INET6
99 static int masked_match4(char *net_tok, char *mask_tok, char *string);
100 static int masked_match6(char *net_tok, char *mask_tok, char *string);
101 #endif
102 
103 /* Size of logical line buffer. */
104 
105 #define	BUFLEN 2048
106 
107 /* definition to be used from workarounds.c */
108 #ifdef NETGROUP
109 int     yp_get_default_domain(char  **);
110 #endif
111 
112 /* hosts_access - host access control facility */
113 
114 int     hosts_access(request)
115 struct request_info *request;
116 {
117     int     verdict;
118 
119     /*
120      * If the (daemon, client) pair is matched by an entry in the file
121      * /etc/hosts.allow, access is granted. Otherwise, if the (daemon,
122      * client) pair is matched by an entry in the file /etc/hosts.deny,
123      * access is denied. Otherwise, access is granted. A non-existent
124      * access-control file is treated as an empty file.
125      *
126      * After a rule has been matched, the optional language extensions may
127      * decide to grant or refuse service anyway. Or, while a rule is being
128      * processed, a serious error is found, and it seems better to play safe
129      * and deny service. All this is done by jumping back into the
130      * hosts_access() routine, bypassing the regular return from the
131      * table_match() function calls below.
132      */
133 
134     if (resident <= 0)
135 	resident++;
136     verdict = setjmp(tcpd_buf);
137     if (verdict != 0)
138 	return (verdict == AC_PERMIT);
139     if (table_match(hosts_allow_table, request))
140 	return (YES);
141     if (table_match(hosts_deny_table, request))
142 	return (NO);
143     return (YES);
144 }
145 
146 /* table_match - match table entries with (daemon, client) pair */
147 
148 static int table_match(table, request)
149 char   *table;
150 struct request_info *request;
151 {
152     FILE   *fp;
153     char    sv_list[BUFLEN];		/* becomes list of daemons */
154     char   *cl_list;			/* becomes list of clients */
155     char   *sh_cmd;			/* becomes optional shell command */
156     int     match = NO;
157     struct tcpd_context saved_context;
158     char   *cp;
159 
160     saved_context = tcpd_context;		/* stupid compilers */
161 
162     /*
163      * Between the fopen() and fclose() calls, avoid jumps that may cause
164      * file descriptor leaks.
165      */
166 
167     if ((fp = fopen(table, "r")) != 0) {
168 	tcpd_context.file = table;
169 	tcpd_context.line = 0;
170 	while (match == NO && xgets(sv_list, sizeof(sv_list), fp) != 0) {
171 	    if (sv_list[strlen(sv_list) - 1] != '\n') {
172 		tcpd_warn("missing newline or line too long");
173 		continue;
174 	    }
175 	    /* Ignore anything after unescaped # character */
176 	    for (cp = strchr(sv_list, '#'); cp != NULL;) {
177 		if (cp > sv_list && cp[-1] == '\\') {
178 		    cp = strchr(cp + 1, '#');
179 		    continue;
180 		}
181 		*cp = '\0';
182 		break;
183 	    }
184 	    if (sv_list[strspn(sv_list, " \t\r\n")] == 0)
185 		continue;
186 	    if ((cl_list = split_at(sv_list, ':')) == 0) {
187 		tcpd_warn("missing \":\" separator");
188 		continue;
189 	    }
190 	    sh_cmd = split_at(cl_list, ':');
191 	    match = list_match(sv_list, request, server_match)
192 		&& list_match(cl_list, request, client_match);
193 	}
194 	(void) fclose(fp);
195     } else if (errno != ENOENT) {
196 	tcpd_warn("cannot open %s: %m", table);
197     }
198     if (match) {
199 	if (hosts_access_verbose > 1)
200 	    syslog(LOG_DEBUG, "matched:  %s line %d",
201 		   tcpd_context.file, tcpd_context.line);
202 	if (sh_cmd) {
203 #ifdef PROCESS_OPTIONS
204 	    process_options(sh_cmd, request);
205 #else
206 	    char    cmd[BUFSIZ];
207 	    shell_cmd(percent_x(cmd, sizeof(cmd), sh_cmd, request));
208 #endif
209 	}
210     }
211     tcpd_context = saved_context;
212     return (match);
213 }
214 
215 /* list_match - match a request against a list of patterns with exceptions */
216 
217 static int list_match(char *list, struct request_info *request,
218     int (*match_fn)(char *, struct request_info *))
219 {
220     char   *tok;
221 
222     /*
223      * Process tokens one at a time. We have exhausted all possible matches
224      * when we reach an "EXCEPT" token or the end of the list. If we do find
225      * a match, look for an "EXCEPT" list and recurse to determine whether
226      * the match is affected by any exceptions.
227      */
228 
229     for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) {
230 	if (STR_EQ(tok, "EXCEPT"))		/* EXCEPT: give up */
231 	    return (NO);
232 	if (match_fn(tok, request)) {		/* YES: look for exceptions */
233 	    while ((tok = strtok((char *) 0, sep)) && STR_NE(tok, "EXCEPT"))
234 		 /* VOID */ ;
235 	    return (tok == 0 || list_match((char *) 0, request, match_fn) == 0);
236 	}
237     }
238     return (NO);
239 }
240 
241 /* server_match - match server information */
242 
243 static int server_match(tok, request)
244 char   *tok;
245 struct request_info *request;
246 {
247     char   *host;
248 
249     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain daemon */
250 	return (string_match(tok, eval_daemon(request)));
251     } else {					/* daemon@host */
252 	return (string_match(tok, eval_daemon(request))
253 		&& host_match(host, request->server));
254     }
255 }
256 
257 /* client_match - match client information */
258 
259 static int client_match(tok, request)
260 char   *tok;
261 struct request_info *request;
262 {
263     char   *host;
264 
265     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain host */
266 	return (host_match(tok, request->client));
267     } else {					/* user@host */
268 	return (host_match(host, request->client)
269 		&& string_match(tok, eval_user(request)));
270     }
271 }
272 
273 /* hostfile_match - look up host patterns from file */
274 
275 static int hostfile_match(path, host)
276 char   *path;
277 struct host_info *host;
278 {
279     char    tok[BUFSIZ];
280     int     match = NO;
281     FILE   *fp;
282 
283     if ((fp = fopen(path, "r")) != 0) {
284 	while (fscanf(fp, "%s", tok) == 1 && !(match = host_match(tok, host)))
285 	     /* void */ ;
286 	fclose(fp);
287     } else if (errno != ENOENT) {
288 	tcpd_warn("open %s: %m", path);
289     }
290     return (match);
291 }
292 
293 /* host_match - match host name and/or address against pattern */
294 
295 static int host_match(tok, host)
296 char   *tok;
297 struct host_info *host;
298 {
299     char   *mask;
300 
301     /*
302      * This code looks a little hairy because we want to avoid unnecessary
303      * hostname lookups.
304      *
305      * The KNOWN pattern requires that both address AND name be known; some
306      * patterns are specific to host names or to host addresses; all other
307      * patterns are satisfied when either the address OR the name match.
308      */
309 
310     if (tok[0] == '@') {			/* netgroup: look it up */
311 #ifdef  NETGROUP
312 	static char *mydomain = 0;
313 	if (mydomain == 0)
314 	    yp_get_default_domain(&mydomain);
315 	return (innetgr(tok + 1, eval_hostname(host), (char *) 0, mydomain));
316 #else
317 	tcpd_warn("netgroup support is disabled");	/* not tcpd_jump() */
318 	return (NO);
319 #endif
320     } else if (tok[0] == '/') {			/* /file hack */
321 	return (hostfile_match(tok, host));
322     } else if (STR_EQ(tok, "KNOWN")) {		/* check address and name */
323 	char   *name = eval_hostname(host);
324 	return (STR_NE(eval_hostaddr(host), unknown) && HOSTNAME_KNOWN(name));
325     } else if (STR_EQ(tok, "LOCAL")) {		/* local: no dots in name */
326 	char   *name = eval_hostname(host);
327 	return (strchr(name, '.') == 0 && HOSTNAME_KNOWN(name));
328     } else if ((mask = split_at(tok, '/')) != 0) {	/* net/mask */
329 	return (masked_match(tok, mask, eval_hostaddr(host)));
330     } else {					/* anything else */
331 	return (string_match(tok, eval_hostaddr(host))
332 	    || (NOT_INADDR(tok) && string_match(tok, eval_hostname(host))));
333     }
334 }
335 
336 /* string_match - match string against pattern */
337 
338 static int string_match(tok, string)
339 char   *tok;
340 char   *string;
341 {
342     int     n;
343 
344 #ifdef INET6
345     /* convert IPv4 mapped IPv6 address to IPv4 address */
346     if (STRN_EQ(string, "::ffff:", 7)
347 	&& dot_quad_addr(string + 7) != INADDR_NONE) {
348 	string += 7;
349     }
350 #endif
351     if (tok[0] == '.') {			/* suffix */
352 	n = strlen(string) - strlen(tok);
353 	return (n > 0 && STR_EQ(tok, string + n));
354     } else if (STR_EQ(tok, "ALL")) {		/* all: match any */
355 	return (YES);
356     } else if (STR_EQ(tok, "KNOWN")) {		/* not unknown */
357 	return (STR_NE(string, unknown));
358     } else if (tok[(n = strlen(tok)) - 1] == '.') {	/* prefix */
359 	return (STRN_EQ(tok, string, n));
360     } else {					/* exact match */
361 #ifdef INET6
362 	struct addrinfo hints, *res;
363 	struct sockaddr_in6 pat, addr;
364 	int len, ret;
365 	char ch;
366 
367 	len = strlen(tok);
368 	if (*tok == '[' && tok[len - 1] == ']') {
369 	    ch = tok[len - 1];
370 	    tok[len - 1] = '\0';
371 	    memset(&hints, 0, sizeof(hints));
372 	    hints.ai_family = AF_INET6;
373 	    hints.ai_socktype = SOCK_STREAM;
374 	    hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
375 	    if ((ret = getaddrinfo(tok + 1, NULL, &hints, &res)) == 0) {
376 		memcpy(&pat, res->ai_addr, sizeof(pat));
377 		freeaddrinfo(res);
378 	    }
379 	    tok[len - 1] = ch;
380 	    if (ret != 0 || getaddrinfo(string, NULL, &hints, &res) != 0)
381 		return NO;
382 	    memcpy(&addr, res->ai_addr, sizeof(addr));
383 	    freeaddrinfo(res);
384 	    if (pat.sin6_scope_id != 0 &&
385 		addr.sin6_scope_id != pat.sin6_scope_id)
386 		return NO;
387 	    return (!memcmp(&pat.sin6_addr, &addr.sin6_addr,
388 			    sizeof(struct in6_addr)));
389 	    return (ret);
390 	}
391 #endif
392 	return (STR_EQ(tok, string));
393     }
394 }
395 
396 /* masked_match - match address against netnumber/netmask */
397 
398 #ifdef INET6
399 static int masked_match(net_tok, mask_tok, string)
400 char   *net_tok;
401 char   *mask_tok;
402 char   *string;
403 {
404     return (masked_match4(net_tok, mask_tok, string) ||
405 	    masked_match6(net_tok, mask_tok, string));
406 }
407 
408 static int masked_match4(net_tok, mask_tok, string)
409 #else
410 static int masked_match(net_tok, mask_tok, string)
411 #endif
412 char   *net_tok;
413 char   *mask_tok;
414 char   *string;
415 {
416 #ifdef INET6
417     u_int32_t net;
418     u_int32_t mask;
419     u_int32_t addr;
420 #else
421     unsigned long net;
422     unsigned long mask;
423     unsigned long addr;
424 #endif
425 
426     /*
427      * Disallow forms other than dotted quad: the treatment that inet_addr()
428      * gives to forms with less than four components is inconsistent with the
429      * access control language. John P. Rouillard <rouilj@cs.umb.edu>.
430      */
431 
432     if ((addr = dot_quad_addr(string)) == INADDR_NONE)
433 	return (NO);
434     if ((net = dot_quad_addr(net_tok)) == INADDR_NONE
435 	|| (mask = dot_quad_addr(mask_tok)) == INADDR_NONE) {
436 #ifndef INET6
437 	tcpd_warn("bad net/mask expression: %s/%s", net_tok, mask_tok);
438 #endif
439 	return (NO);				/* not tcpd_jump() */
440     }
441     return ((addr & mask) == net);
442 }
443 
444 #ifdef INET6
445 static int masked_match6(net_tok, mask_tok, string)
446 char   *net_tok;
447 char   *mask_tok;
448 char   *string;
449 {
450     struct addrinfo hints, *res;
451     struct sockaddr_in6 net, addr;
452     u_int32_t mask;
453     int len, mask_len, i = 0;
454     char ch;
455 
456     memset(&hints, 0, sizeof(hints));
457     hints.ai_family = AF_INET6;
458     hints.ai_socktype = SOCK_STREAM;
459     hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
460     if (getaddrinfo(string, NULL, &hints, &res) != 0)
461 	return NO;
462     memcpy(&addr, res->ai_addr, sizeof(addr));
463     freeaddrinfo(res);
464 
465     if (IN6_IS_ADDR_V4MAPPED(&addr.sin6_addr)) {
466 	if ((*(u_int32_t *)&net.sin6_addr.s6_addr[12] = dot_quad_addr(net_tok)) == INADDR_NONE
467 	 || (mask = dot_quad_addr(mask_tok)) == INADDR_NONE)
468 	    return (NO);
469 	return ((*(u_int32_t *)&addr.sin6_addr.s6_addr[12] & mask) == *(u_int32_t *)&net.sin6_addr.s6_addr[12]);
470     }
471 
472     /* match IPv6 address against netnumber/prefixlen */
473     len = strlen(net_tok);
474     if (*net_tok != '[' || net_tok[len - 1] != ']')
475 	return NO;
476     ch = net_tok[len - 1];
477     net_tok[len - 1] = '\0';
478     if (getaddrinfo(net_tok + 1, NULL, &hints, &res) != 0) {
479 	net_tok[len - 1] = ch;
480 	return NO;
481     }
482     memcpy(&net, res->ai_addr, sizeof(net));
483     freeaddrinfo(res);
484     net_tok[len - 1] = ch;
485     if ((mask_len = atoi(mask_tok)) < 0 || mask_len > 128)
486 	return NO;
487 
488     if (net.sin6_scope_id != 0 && addr.sin6_scope_id != net.sin6_scope_id)
489 	return NO;
490     while (mask_len > 0) {
491 	if (mask_len < 32) {
492 	    mask = htonl(~(0xffffffff >> mask_len));
493 	    if ((*(u_int32_t *)&addr.sin6_addr.s6_addr[i] & mask) != (*(u_int32_t *)&net.sin6_addr.s6_addr[i] & mask))
494 		return NO;
495 	    break;
496 	}
497 	if (*(u_int32_t *)&addr.sin6_addr.s6_addr[i] != *(u_int32_t *)&net.sin6_addr.s6_addr[i])
498 	    return NO;
499 	i += 4;
500 	mask_len -= 32;
501     }
502     return YES;
503 }
504 #endif /* INET6 */
505