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
23static 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#ifndef	INADDR_NONE
50#define	INADDR_NONE	(-1)		/* XXX should be 0xffffffff */
51#endif
52
53/* Local stuff. */
54
55#include "tcpd.h"
56
57/* Error handling. */
58
59extern jmp_buf tcpd_buf;
60
61/* Delimiters for lists of daemons or clients. */
62
63static 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
75char   *hosts_allow_table = HOSTS_ALLOW;
76char   *hosts_deny_table = HOSTS_DENY;
77int     hosts_access_verbose = 0;
78
79 /*
80  * In a long-running process, we are not at liberty to just go away.
81  */
82
83int     resident = (-1);		/* -1, 0: unknown; +1: yes */
84
85/* Forward declarations. */
86
87static int table_match(char *table, struct request_info *request);
88static int list_match(char *list, struct request_info *request,
89    int (*match_fn)(char *, struct request_info *));
90static int server_match(char *tok, struct request_info *request);
91static int client_match(char *tok, struct request_info *request);
92static int host_match(char *tok, struct host_info *host);
93static int string_match(char *tok, char *string);
94static int masked_match(char *net_tok, char *mask_tok, char *string);
95#ifdef INET6
96static int masked_match4(char *net_tok, char *mask_tok, char *string);
97static int masked_match6(char *net_tok, char *mask_tok, char *string);
98#endif
99
100/* Size of logical line buffer. */
101
102#define	BUFLEN 2048
103
104/* definition to be used from workarounds.c */
105#ifdef NETGROUP
106int     yp_get_default_domain(char  **);
107#endif
108
109/* hosts_access - host access control facility */
110
111int     hosts_access(struct request_info *request)
112{
113    int     verdict;
114
115    /*
116     * If the (daemon, client) pair is matched by an entry in the file
117     * /etc/hosts.allow, access is granted. Otherwise, if the (daemon,
118     * client) pair is matched by an entry in the file /etc/hosts.deny,
119     * access is denied. Otherwise, access is granted. A non-existent
120     * access-control file is treated as an empty file.
121     *
122     * After a rule has been matched, the optional language extensions may
123     * decide to grant or refuse service anyway. Or, while a rule is being
124     * processed, a serious error is found, and it seems better to play safe
125     * and deny service. All this is done by jumping back into the
126     * hosts_access() routine, bypassing the regular return from the
127     * table_match() function calls below.
128     */
129
130    if (resident <= 0)
131	resident++;
132    verdict = setjmp(tcpd_buf);
133    if (verdict != 0)
134	return (verdict == AC_PERMIT);
135    if (table_match(hosts_allow_table, request))
136	return (YES);
137    if (table_match(hosts_deny_table, request))
138	return (NO);
139    return (YES);
140}
141
142/* table_match - match table entries with (daemon, client) pair */
143
144static int table_match(char *table, 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
211static int list_match(char *list, struct request_info *request,
212    int (*match_fn)(char *, struct request_info *))
213{
214    char   *tok;
215
216    /*
217     * Process tokens one at a time. We have exhausted all possible matches
218     * when we reach an "EXCEPT" token or the end of the list. If we do find
219     * a match, look for an "EXCEPT" list and recurse to determine whether
220     * the match is affected by any exceptions.
221     */
222
223    for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) {
224	if (STR_EQ(tok, "EXCEPT"))		/* EXCEPT: give up */
225	    return (NO);
226	if (match_fn(tok, request)) {		/* YES: look for exceptions */
227	    while ((tok = strtok((char *) 0, sep)) && STR_NE(tok, "EXCEPT"))
228		 /* VOID */ ;
229	    return (tok == 0 || list_match((char *) 0, request, match_fn) == 0);
230	}
231    }
232    return (NO);
233}
234
235/* server_match - match server information */
236
237static int server_match(char *tok, struct request_info *request)
238{
239    char   *host;
240
241    if ((host = split_at(tok + 1, '@')) == 0) {	/* plain daemon */
242	return (string_match(tok, eval_daemon(request)));
243    } else {					/* daemon@host */
244	return (string_match(tok, eval_daemon(request))
245		&& host_match(host, request->server));
246    }
247}
248
249/* client_match - match client information */
250
251static int 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/* hostfile_match - look up host patterns from file */
264
265static int hostfile_match(char *path, struct host_info *host)
266{
267    char    tok[BUFSIZ];
268    int     match = NO;
269    FILE   *fp;
270
271    if ((fp = fopen(path, "r")) != 0) {
272	while (fscanf(fp, "%s", tok) == 1 && !(match = host_match(tok, host)))
273	     /* void */ ;
274	fclose(fp);
275    } else if (errno != ENOENT) {
276	tcpd_warn("open %s: %m", path);
277    }
278    return (match);
279}
280
281/* host_match - match host name and/or address against pattern */
282
283static int host_match(char *tok, struct host_info *host)
284{
285    char   *mask;
286
287    /*
288     * This code looks a little hairy because we want to avoid unnecessary
289     * hostname lookups.
290     *
291     * The KNOWN pattern requires that both address AND name be known; some
292     * patterns are specific to host names or to host addresses; all other
293     * patterns are satisfied when either the address OR the name match.
294     */
295
296    if (tok[0] == '@') {			/* netgroup: look it up */
297#ifdef  NETGROUP
298	static char *mydomain = 0;
299	if (mydomain == 0)
300	    yp_get_default_domain(&mydomain);
301	return (innetgr(tok + 1, eval_hostname(host), (char *) 0, mydomain));
302#else
303	tcpd_warn("netgroup support is disabled");	/* not tcpd_jump() */
304	return (NO);
305#endif
306    } else if (tok[0] == '/') {			/* /file hack */
307	return (hostfile_match(tok, host));
308    } else if (STR_EQ(tok, "KNOWN")) {		/* check address and name */
309	char   *name = eval_hostname(host);
310	return (STR_NE(eval_hostaddr(host), unknown) && HOSTNAME_KNOWN(name));
311    } else if (STR_EQ(tok, "LOCAL")) {		/* local: no dots in name */
312	char   *name = eval_hostname(host);
313	return (strchr(name, '.') == 0 && HOSTNAME_KNOWN(name));
314    } else if ((mask = split_at(tok, '/')) != 0) {	/* net/mask */
315	return (masked_match(tok, mask, eval_hostaddr(host)));
316    } else {					/* anything else */
317	return (string_match(tok, eval_hostaddr(host))
318	    || (NOT_INADDR(tok) && NOT_INADDR6(tok)
319	     && string_match(tok, eval_hostname(host))));
320    }
321}
322
323/* string_match - match string against pattern */
324
325static int string_match(char *tok, char *string)
326{
327    int     n;
328
329#ifdef INET6
330    /* convert IPv4 mapped IPv6 address to IPv4 address */
331    if (STRN_EQ(string, "::ffff:", 7)
332	&& dot_quad_addr(string + 7) != INADDR_NONE) {
333	string += 7;
334    }
335#endif
336    if (tok[0] == '.') {			/* suffix */
337	n = strlen(string) - strlen(tok);
338	return (n > 0 && STR_EQ(tok, string + n));
339    } else if (STR_EQ(tok, "ALL")) {		/* all: match any */
340	return (YES);
341    } else if (STR_EQ(tok, "KNOWN")) {		/* not unknown */
342	return (STR_NE(string, unknown));
343    } else if (tok[(n = strlen(tok)) - 1] == '.') {	/* prefix */
344	return (STRN_EQ(tok, string, n));
345    } else {					/* exact match */
346#ifdef INET6
347	struct addrinfo hints, *res;
348	struct sockaddr_in6 pat, addr;
349	int len, ret;
350	char ch;
351
352	len = strlen(tok);
353	if (*tok == '[' && tok[len - 1] == ']') {
354	    ch = tok[len - 1];
355	    tok[len - 1] = '\0';
356	    memset(&hints, 0, sizeof(hints));
357	    hints.ai_family = AF_INET6;
358	    hints.ai_socktype = SOCK_STREAM;
359	    hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
360	    if ((ret = getaddrinfo(tok + 1, NULL, &hints, &res)) == 0) {
361		memcpy(&pat, res->ai_addr, sizeof(pat));
362		freeaddrinfo(res);
363	    }
364	    tok[len - 1] = ch;
365	    if (ret != 0 || getaddrinfo(string, NULL, &hints, &res) != 0)
366		return NO;
367	    memcpy(&addr, res->ai_addr, sizeof(addr));
368	    freeaddrinfo(res);
369	    if (pat.sin6_scope_id != 0 &&
370		addr.sin6_scope_id != pat.sin6_scope_id)
371		return NO;
372	    return (!memcmp(&pat.sin6_addr, &addr.sin6_addr,
373			    sizeof(struct in6_addr)));
374	    return (ret);
375	}
376#endif
377	return (STR_EQ(tok, string));
378    }
379}
380
381/* masked_match - match address against netnumber/netmask */
382
383#ifdef INET6
384static int masked_match(char *net_tok, char *mask_tok, char *string)
385{
386    return (masked_match4(net_tok, mask_tok, string) ||
387	    masked_match6(net_tok, mask_tok, string));
388}
389
390static int masked_match4(char *net_tok, char *mask_tok, char *string)
391#else
392static int masked_match(char *net_tok, char *mask_tok, char *string)
393#endif
394{
395#ifdef INET6
396    u_int32_t net;
397    u_int32_t mask;
398    u_int32_t addr;
399#else
400    unsigned long net;
401    unsigned long mask;
402    unsigned long addr;
403#endif
404
405    /*
406     * Disallow forms other than dotted quad: the treatment that inet_addr()
407     * gives to forms with less than four components is inconsistent with the
408     * access control language. John P. Rouillard <rouilj@cs.umb.edu>.
409     */
410
411    if ((addr = dot_quad_addr(string)) == INADDR_NONE)
412	return (NO);
413    if ((net = dot_quad_addr(net_tok)) == INADDR_NONE
414	|| (mask = dot_quad_addr(mask_tok)) == INADDR_NONE) {
415#ifndef INET6
416	tcpd_warn("bad net/mask expression: %s/%s", net_tok, mask_tok);
417#endif
418	return (NO);				/* not tcpd_jump() */
419    }
420    return ((addr & mask) == net);
421}
422
423#ifdef INET6
424static int masked_match6(char *net_tok, char *mask_tok, char *string)
425{
426    struct addrinfo hints, *res;
427    struct sockaddr_in6 net, addr;
428    u_int32_t mask;
429    int len, mask_len, i = 0;
430    char ch;
431
432    memset(&hints, 0, sizeof(hints));
433    hints.ai_family = AF_INET6;
434    hints.ai_socktype = SOCK_STREAM;
435    hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
436    if (getaddrinfo(string, NULL, &hints, &res) != 0)
437	return NO;
438    memcpy(&addr, res->ai_addr, sizeof(addr));
439    freeaddrinfo(res);
440
441    if (IN6_IS_ADDR_V4MAPPED(&addr.sin6_addr)) {
442	if ((*(u_int32_t *)&net.sin6_addr.s6_addr[12] = dot_quad_addr(net_tok)) == INADDR_NONE
443	 || (mask = dot_quad_addr(mask_tok)) == INADDR_NONE)
444	    return (NO);
445	return ((*(u_int32_t *)&addr.sin6_addr.s6_addr[12] & mask) == *(u_int32_t *)&net.sin6_addr.s6_addr[12]);
446    }
447
448    /* match IPv6 address against netnumber/prefixlen */
449    len = strlen(net_tok);
450    if (*net_tok != '[' || net_tok[len - 1] != ']')
451	return NO;
452    ch = net_tok[len - 1];
453    net_tok[len - 1] = '\0';
454    if (getaddrinfo(net_tok + 1, NULL, &hints, &res) != 0) {
455	net_tok[len - 1] = ch;
456	return NO;
457    }
458    memcpy(&net, res->ai_addr, sizeof(net));
459    freeaddrinfo(res);
460    net_tok[len - 1] = ch;
461    if ((mask_len = atoi(mask_tok)) < 0 || mask_len > 128)
462	return NO;
463
464    if (net.sin6_scope_id != 0 && addr.sin6_scope_id != net.sin6_scope_id)
465	return NO;
466    while (mask_len > 0) {
467	if (mask_len < 32) {
468	    mask = htonl(~(0xffffffff >> mask_len));
469	    if ((*(u_int32_t *)&addr.sin6_addr.s6_addr[i] & mask) != (*(u_int32_t *)&net.sin6_addr.s6_addr[i] & mask))
470		return NO;
471	    break;
472	}
473	if (*(u_int32_t *)&addr.sin6_addr.s6_addr[i] != *(u_int32_t *)&net.sin6_addr.s6_addr[i])
474	    return NO;
475	i += 4;
476	mask_len -= 32;
477    }
478    return YES;
479}
480#endif /* INET6 */
481