1323530Savg /*
2323530Savg  * This module implements a simple access control language that is based on
3323530Savg  * host (or domain) names, NIS (host) netgroup names, IP addresses (or
4323530Savg  * network numbers) and daemon process names. When a match is found the
5323530Savg  * search is terminated, and depending on whether PROCESS_OPTIONS is defined,
6323530Savg  * a list of options is executed or an optional shell command is executed.
7323530Savg  *
8323530Savg  * Host and user names are looked up on demand, provided that suitable endpoint
9323530Savg  * information is available as sockaddr_in structures or TLI netbufs. As a
10323530Savg  * side effect, the pattern matching process may change the contents of
11323530Savg  * request structure fields.
12323530Savg  *
13323530Savg  * Diagnostics are reported through syslog(3).
14323530Savg  *
15323530Savg  * Compile with -DNETGROUP if your library provides support for netgroups.
16323530Savg  *
17323530Savg  * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
18323530Savg  *
19323530Savg  * $FreeBSD$
20323530Savg  */
21323530Savg
22323530Savg#ifndef lint
23323530Savgstatic char sccsid[] = "@(#) hosts_access.c 1.21 97/02/12 02:13:22";
24323530Savg#endif
25323530Savg
26323530Savg/* System libraries. */
27323530Savg
28323530Savg#include <sys/types.h>
29323530Savg#ifdef INT32_T
30323530Savg    typedef uint32_t u_int32_t;
31323530Savg#endif
32323530Savg#include <sys/param.h>
33323530Savg#ifdef INET6
34323530Savg#include <sys/socket.h>
35323530Savg#endif
36323530Savg#include <netinet/in.h>
37323530Savg#include <arpa/inet.h>
38323530Savg#include <stdio.h>
39323530Savg#include <syslog.h>
40323530Savg#include <ctype.h>
41323530Savg#include <errno.h>
42323530Savg#include <setjmp.h>
43323530Savg#include <string.h>
44323530Savg#ifdef INET6
45323530Savg#include <netdb.h>
46323530Savg#endif
47323530Savg
48323530Savgextern char *fgets();
49323530Savgextern int errno;
50323530Savg
51323530Savg#ifndef	INADDR_NONE
52323530Savg#define	INADDR_NONE	(-1)		/* XXX should be 0xffffffff */
53323530Savg#endif
54323530Savg
55323530Savg/* Local stuff. */
56323530Savg
57323530Savg#include "tcpd.h"
58323530Savg
59323530Savg/* Error handling. */
60323530Savg
61323530Savgextern jmp_buf tcpd_buf;
62323530Savg
63323530Savg/* Delimiters for lists of daemons or clients. */
64323530Savg
65323530Savgstatic char sep[] = ", \t\r\n";
66323530Savg
67323530Savg/* Constants to be used in assignments only, not in comparisons... */
68323530Savg
69323530Savg#define	YES		1
70323530Savg#define	NO		0
71323530Savg
72323530Savg /*
73323530Savg  * These variables are globally visible so that they can be redirected in
74323530Savg  * verification mode.
75323530Savg  */
76323530Savg
77323530Savgchar   *hosts_allow_table = HOSTS_ALLOW;
78323530Savgchar   *hosts_deny_table = HOSTS_DENY;
79323530Savgint     hosts_access_verbose = 0;
80323530Savg
81323530Savg /*
82323530Savg  * In a long-running process, we are not at liberty to just go away.
83323530Savg  */
84323530Savg
85323530Savgint     resident = (-1);		/* -1, 0: unknown; +1: yes */
86323530Savg
87323530Savg/* Forward declarations. */
88323530Savg
89323530Savgstatic int table_match();
90323530Savgstatic int list_match();
91323530Savgstatic int server_match();
92323530Savgstatic int client_match();
93323530Savgstatic int host_match();
94323530Savgstatic int string_match();
95323530Savgstatic int masked_match();
96323530Savg#ifdef INET6
97323530Savgstatic int masked_match4();
98323530Savgstatic int masked_match6();
99323530Savg#endif
100323530Savg
101323530Savg/* Size of logical line buffer. */
102323530Savg
103323530Savg#define	BUFLEN 2048
104323530Savg
105323530Savg/* hosts_access - host access control facility */
106323530Savg
107323530Savgint     hosts_access(request)
108323530Savgstruct request_info *request;
109323530Savg{
110323530Savg    int     verdict;
111323530Savg
112323530Savg    /*
113323530Savg     * If the (daemon, client) pair is matched by an entry in the file
114323530Savg     * /etc/hosts.allow, access is granted. Otherwise, if the (daemon,
115323530Savg     * client) pair is matched by an entry in the file /etc/hosts.deny,
116323530Savg     * access is denied. Otherwise, access is granted. A non-existent
117323530Savg     * access-control file is treated as an empty file.
118323530Savg     *
119323530Savg     * After a rule has been matched, the optional language extensions may
120323530Savg     * decide to grant or refuse service anyway. Or, while a rule is being
121323530Savg     * processed, a serious error is found, and it seems better to play safe
122323530Savg     * and deny service. All this is done by jumping back into the
123323530Savg     * hosts_access() routine, bypassing the regular return from the
124323530Savg     * table_match() function calls below.
125323530Savg     */
126323530Savg
127323530Savg    if (resident <= 0)
128323530Savg	resident++;
129323530Savg    verdict = setjmp(tcpd_buf);
130323530Savg    if (verdict != 0)
131323530Savg	return (verdict == AC_PERMIT);
132323530Savg    if (table_match(hosts_allow_table, request))
133323530Savg	return (YES);
134323530Savg    if (table_match(hosts_deny_table, request))
135323530Savg	return (NO);
136323530Savg    return (YES);
137323530Savg}
138323530Savg
139323530Savg/* table_match - match table entries with (daemon, client) pair */
140323530Savg
141323530Savgstatic int table_match(table, request)
142323530Savgchar   *table;
143323530Savgstruct request_info *request;
144323530Savg{
145323530Savg    FILE   *fp;
146323530Savg    char    sv_list[BUFLEN];		/* becomes list of daemons */
147323530Savg    char   *cl_list;			/* becomes list of clients */
148323530Savg    char   *sh_cmd;			/* becomes optional shell command */
149323530Savg    int     match = NO;
150323530Savg    struct tcpd_context saved_context;
151323530Savg    char   *cp;
152323530Savg
153323530Savg    saved_context = tcpd_context;		/* stupid compilers */
154323530Savg
155323530Savg    /*
156323530Savg     * Between the fopen() and fclose() calls, avoid jumps that may cause
157323530Savg     * file descriptor leaks.
158323530Savg     */
159323530Savg
160323530Savg    if ((fp = fopen(table, "r")) != 0) {
161323530Savg	tcpd_context.file = table;
162323530Savg	tcpd_context.line = 0;
163323530Savg	while (match == NO && xgets(sv_list, sizeof(sv_list), fp) != 0) {
164323530Savg	    if (sv_list[strlen(sv_list) - 1] != '\n') {
165323530Savg		tcpd_warn("missing newline or line too long");
166323530Savg		continue;
167323530Savg	    }
168323530Savg	    /* Ignore anything after unescaped # character */
169323530Savg	    for (cp = strchr(sv_list, '#'); cp != NULL;) {
170323530Savg		if (cp > sv_list && cp[-1] == '\\') {
171323530Savg		    cp = strchr(cp + 1, '#');
172323530Savg		    continue;
173323530Savg		}
174323530Savg		*cp = '\0';
175323530Savg		break;
176323530Savg	    }
177	    if (sv_list[strspn(sv_list, " \t\r\n")] == 0)
178		continue;
179	    if ((cl_list = split_at(sv_list, ':')) == 0) {
180		tcpd_warn("missing \":\" separator");
181		continue;
182	    }
183	    sh_cmd = split_at(cl_list, ':');
184	    match = list_match(sv_list, request, server_match)
185		&& list_match(cl_list, request, client_match);
186	}
187	(void) fclose(fp);
188    } else if (errno != ENOENT) {
189	tcpd_warn("cannot open %s: %m", table);
190    }
191    if (match) {
192	if (hosts_access_verbose > 1)
193	    syslog(LOG_DEBUG, "matched:  %s line %d",
194		   tcpd_context.file, tcpd_context.line);
195	if (sh_cmd) {
196#ifdef PROCESS_OPTIONS
197	    process_options(sh_cmd, request);
198#else
199	    char    cmd[BUFSIZ];
200	    shell_cmd(percent_x(cmd, sizeof(cmd), sh_cmd, request));
201#endif
202	}
203    }
204    tcpd_context = saved_context;
205    return (match);
206}
207
208/* list_match - match a request against a list of patterns with exceptions */
209
210static int list_match(list, request, match_fn)
211char   *list;
212struct request_info *request;
213int   (*match_fn) ();
214{
215    char   *tok;
216
217    /*
218     * Process tokens one at a time. We have exhausted all possible matches
219     * when we reach an "EXCEPT" token or the end of the list. If we do find
220     * a match, look for an "EXCEPT" list and recurse to determine whether
221     * the match is affected by any exceptions.
222     */
223
224    for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) {
225	if (STR_EQ(tok, "EXCEPT"))		/* EXCEPT: give up */
226	    return (NO);
227	if (match_fn(tok, request)) {		/* YES: look for exceptions */
228	    while ((tok = strtok((char *) 0, sep)) && STR_NE(tok, "EXCEPT"))
229		 /* VOID */ ;
230	    return (tok == 0 || list_match((char *) 0, request, match_fn) == 0);
231	}
232    }
233    return (NO);
234}
235
236/* server_match - match server information */
237
238static int server_match(tok, request)
239char   *tok;
240struct request_info *request;
241{
242    char   *host;
243
244    if ((host = split_at(tok + 1, '@')) == 0) {	/* plain daemon */
245	return (string_match(tok, eval_daemon(request)));
246    } else {					/* daemon@host */
247	return (string_match(tok, eval_daemon(request))
248		&& host_match(host, request->server));
249    }
250}
251
252/* client_match - match client information */
253
254static int client_match(tok, request)
255char   *tok;
256struct request_info *request;
257{
258    char   *host;
259
260    if ((host = split_at(tok + 1, '@')) == 0) {	/* plain host */
261	return (host_match(tok, request->client));
262    } else {					/* user@host */
263	return (host_match(host, request->client)
264		&& string_match(tok, eval_user(request)));
265    }
266}
267
268/* hostfile_match - look up host patterns from file */
269
270static int hostfile_match(path, host)
271char   *path;
272struct hosts_info *host;
273{
274    char    tok[BUFSIZ];
275    int     match = NO;
276    FILE   *fp;
277
278    if ((fp = fopen(path, "r")) != 0) {
279	while (fscanf(fp, "%s", tok) == 1 && !(match = host_match(tok, host)))
280	     /* void */ ;
281	fclose(fp);
282    } else if (errno != ENOENT) {
283	tcpd_warn("open %s: %m", path);
284    }
285    return (match);
286}
287
288/* host_match - match host name and/or address against pattern */
289
290static int host_match(tok, host)
291char   *tok;
292struct host_info *host;
293{
294    char   *mask;
295
296    /*
297     * This code looks a little hairy because we want to avoid unnecessary
298     * hostname lookups.
299     *
300     * The KNOWN pattern requires that both address AND name be known; some
301     * patterns are specific to host names or to host addresses; all other
302     * patterns are satisfied when either the address OR the name match.
303     */
304
305    if (tok[0] == '@') {			/* netgroup: look it up */
306#ifdef  NETGROUP
307	static char *mydomain = 0;
308	if (mydomain == 0)
309	    yp_get_default_domain(&mydomain);
310	return (innetgr(tok + 1, eval_hostname(host), (char *) 0, mydomain));
311#else
312	tcpd_warn("netgroup support is disabled");	/* not tcpd_jump() */
313	return (NO);
314#endif
315    } else if (tok[0] == '/') {			/* /file hack */
316	return (hostfile_match(tok, host));
317    } else if (STR_EQ(tok, "KNOWN")) {		/* check address and name */
318	char   *name = eval_hostname(host);
319	return (STR_NE(eval_hostaddr(host), unknown) && HOSTNAME_KNOWN(name));
320    } else if (STR_EQ(tok, "LOCAL")) {		/* local: no dots in name */
321	char   *name = eval_hostname(host);
322	return (strchr(name, '.') == 0 && HOSTNAME_KNOWN(name));
323    } else if ((mask = split_at(tok, '/')) != 0) {	/* net/mask */
324	return (masked_match(tok, mask, eval_hostaddr(host)));
325    } else {					/* anything else */
326	return (string_match(tok, eval_hostaddr(host))
327	    || (NOT_INADDR(tok) && string_match(tok, eval_hostname(host))));
328    }
329}
330
331/* string_match - match string against pattern */
332
333static int string_match(tok, string)
334char   *tok;
335char   *string;
336{
337    int     n;
338
339#ifdef INET6
340    /* convert IPv4 mapped IPv6 address to IPv4 address */
341    if (STRN_EQ(string, "::ffff:", 7)
342	&& dot_quad_addr(string + 7) != INADDR_NONE) {
343	string += 7;
344    }
345#endif
346    if (tok[0] == '.') {			/* suffix */
347	n = strlen(string) - strlen(tok);
348	return (n > 0 && STR_EQ(tok, string + n));
349    } else if (STR_EQ(tok, "ALL")) {		/* all: match any */
350	return (YES);
351    } else if (STR_EQ(tok, "KNOWN")) {		/* not unknown */
352	return (STR_NE(string, unknown));
353    } else if (tok[(n = strlen(tok)) - 1] == '.') {	/* prefix */
354	return (STRN_EQ(tok, string, n));
355    } else {					/* exact match */
356#ifdef INET6
357	struct addrinfo hints, *res;
358	struct sockaddr_in6 pat, addr;
359	int len, ret;
360	char ch;
361
362	len = strlen(tok);
363	if (*tok == '[' && tok[len - 1] == ']') {
364	    ch = tok[len - 1];
365	    tok[len - 1] = '\0';
366	    memset(&hints, 0, sizeof(hints));
367	    hints.ai_family = AF_INET6;
368	    hints.ai_socktype = SOCK_STREAM;
369	    hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
370	    if ((ret = getaddrinfo(tok + 1, NULL, &hints, &res)) == 0) {
371		memcpy(&pat, res->ai_addr, sizeof(pat));
372		freeaddrinfo(res);
373	    }
374	    tok[len - 1] = ch;
375	    if (ret != 0 || getaddrinfo(string, NULL, &hints, &res) != 0)
376		return NO;
377	    memcpy(&addr, res->ai_addr, sizeof(addr));
378	    freeaddrinfo(res);
379	    if (pat.sin6_scope_id != 0 &&
380		addr.sin6_scope_id != pat.sin6_scope_id)
381		return NO;
382	    return (!memcmp(&pat.sin6_addr, &addr.sin6_addr,
383			    sizeof(struct in6_addr)));
384	    return (ret);
385	}
386#endif
387	return (STR_EQ(tok, string));
388    }
389}
390
391/* masked_match - match address against netnumber/netmask */
392
393#ifdef INET6
394static int masked_match(net_tok, mask_tok, string)
395char   *net_tok;
396char   *mask_tok;
397char   *string;
398{
399    return (masked_match4(net_tok, mask_tok, string) ||
400	    masked_match6(net_tok, mask_tok, string));
401}
402
403static int masked_match4(net_tok, mask_tok, string)
404#else
405static int masked_match(net_tok, mask_tok, string)
406#endif
407char   *net_tok;
408char   *mask_tok;
409char   *string;
410{
411#ifdef INET6
412    u_int32_t net;
413    u_int32_t mask;
414    u_int32_t addr;
415#else
416    unsigned long net;
417    unsigned long mask;
418    unsigned long addr;
419#endif
420
421    /*
422     * Disallow forms other than dotted quad: the treatment that inet_addr()
423     * gives to forms with less than four components is inconsistent with the
424     * access control language. John P. Rouillard <rouilj@cs.umb.edu>.
425     */
426
427    if ((addr = dot_quad_addr(string)) == INADDR_NONE)
428	return (NO);
429    if ((net = dot_quad_addr(net_tok)) == INADDR_NONE
430	|| (mask = dot_quad_addr(mask_tok)) == INADDR_NONE) {
431#ifndef INET6
432	tcpd_warn("bad net/mask expression: %s/%s", net_tok, mask_tok);
433#endif
434	return (NO);				/* not tcpd_jump() */
435    }
436    return ((addr & mask) == net);
437}
438
439#ifdef INET6
440static int masked_match6(net_tok, mask_tok, string)
441char   *net_tok;
442char   *mask_tok;
443char   *string;
444{
445    struct addrinfo hints, *res;
446    struct sockaddr_in6 net, addr;
447    u_int32_t mask;
448    int len, mask_len, i = 0;
449    char ch;
450
451    memset(&hints, 0, sizeof(hints));
452    hints.ai_family = AF_INET6;
453    hints.ai_socktype = SOCK_STREAM;
454    hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
455    if (getaddrinfo(string, NULL, &hints, &res) != 0)
456	return NO;
457    memcpy(&addr, res->ai_addr, sizeof(addr));
458    freeaddrinfo(res);
459
460    if (IN6_IS_ADDR_V4MAPPED(&addr.sin6_addr)) {
461	if ((*(u_int32_t *)&net.sin6_addr.s6_addr[12] = dot_quad_addr(net_tok)) == INADDR_NONE
462	 || (mask = dot_quad_addr(mask_tok)) == INADDR_NONE)
463	    return (NO);
464	return ((*(u_int32_t *)&addr.sin6_addr.s6_addr[12] & mask) == *(u_int32_t *)&net.sin6_addr.s6_addr[12]);
465    }
466
467    /* match IPv6 address against netnumber/prefixlen */
468    len = strlen(net_tok);
469    if (*net_tok != '[' || net_tok[len - 1] != ']')
470	return NO;
471    ch = net_tok[len - 1];
472    net_tok[len - 1] = '\0';
473    if (getaddrinfo(net_tok + 1, NULL, &hints, &res) != 0) {
474	net_tok[len - 1] = ch;
475	return NO;
476    }
477    memcpy(&net, res->ai_addr, sizeof(net));
478    freeaddrinfo(res);
479    net_tok[len - 1] = ch;
480    if ((mask_len = atoi(mask_tok)) < 0 || mask_len > 128)
481	return NO;
482
483    if (net.sin6_scope_id != 0 && addr.sin6_scope_id != net.sin6_scope_id)
484	return NO;
485    while (mask_len > 0) {
486	if (mask_len < 32) {
487	    mask = htonl(~(0xffffffff >> mask_len));
488	    if ((*(u_int32_t *)&addr.sin6_addr.s6_addr[i] & mask) != (*(u_int32_t *)&net.sin6_addr.s6_addr[i] & mask))
489		return NO;
490	    break;
491	}
492	if (*(u_int32_t *)&addr.sin6_addr.s6_addr[i] != *(u_int32_t *)&net.sin6_addr.s6_addr[i])
493	    return NO;
494	i += 4;
495	mask_len -= 32;
496    }
497    return YES;
498}
499#endif /* INET6 */
500