1 /*
2  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6  /*
7   * This module implements a simple access control language that is based on
8   * host (or domain) names, NIS (host) netgroup names, IP addresses (or
9   * network numbers) and daemon process names. When a match is found the
10   * search is terminated, and depending on whether PROCESS_OPTIONS is defined,
11   * a list of options is executed or an optional shell command is executed.
12   *
13   * Host and user names are looked up on demand, provided that suitable endpoint
14   * information is available as sockaddr_in structures or TLI netbufs. As a
15   * side effect, the pattern matching process may change the contents of
16   * request structure fields.
17   *
18   * Diagnostics are reported through syslog(3).
19   *
20   * Compile with -DNETGROUP if your library provides support for netgroups.
21   *
22   * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands.
23   */
24 
25 #ifndef lint
26 static char sccsid[] = "@(#) hosts_access.c 1.21 97/02/12 02:13:22";
27 #endif
28 
29 /* System libraries. */
30 
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35 #include <rpcsvc/ypclnt.h>
36 #include <netdb.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <unistd.h>
40 #include <syslog.h>
41 #include <ctype.h>
42 #include <errno.h>
43 #include <setjmp.h>
44 #include <string.h>
45 
46 extern char *fgets();
47 extern int errno;
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 
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 char   *hosts_allow_table = HOSTS_ALLOW;
76 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();
88 static int list_match();
89 static int server_match();
90 static int client_match();
91 static int host_match();
92 static int string_match();
93 static int masked_match();
94 #ifdef HAVE_IPV6
95 static void ipv6_mask();
96 #endif
97 
98 /* Size of logical line buffer. */
99 
100 #define	BUFLEN 2048
101 
102 /* hosts_access - host access control facility */
103 
hosts_access(request)104 int     hosts_access(request)
105 struct request_info *request;
106 {
107     int     verdict;
108 
109     /*
110      * If the (daemon, client) pair is matched by an entry in the file
111      * /etc/hosts.allow, access is granted. Otherwise, if the (daemon,
112      * client) pair is matched by an entry in the file /etc/hosts.deny,
113      * access is denied. Otherwise, access is granted. A non-existent
114      * access-control file is treated as an empty file.
115      *
116      * After a rule has been matched, the optional language extensions may
117      * decide to grant or refuse service anyway. Or, while a rule is being
118      * processed, a serious error is found, and it seems better to play safe
119      * and deny service. All this is done by jumping back into the
120      * hosts_access() routine, bypassing the regular return from the
121      * table_match() function calls below.
122      */
123 
124     if (resident <= 0)
125 	resident++;
126     verdict = setjmp(tcpd_buf);
127     if (verdict != 0)
128 	return (verdict == AC_PERMIT);
129     if (table_match(hosts_allow_table, request))
130 	return (YES);
131     if (table_match(hosts_deny_table, request))
132 	return (NO);
133     return (YES);
134 }
135 
136 /* table_match - match table entries with (daemon, client) pair */
137 
table_match(table,request)138 static int table_match(table, request)
139 char   *table;
140 struct request_info *request;
141 {
142     FILE   *fp;
143     char    sv_list[BUFLEN];		/* becomes list of daemons */
144     char   *cl_list;			/* becomes list of clients */
145     char   *sh_cmd;			/* becomes optional shell command */
146     int     match = NO;
147     struct tcpd_context saved_context;
148 
149     saved_context = tcpd_context;		/* stupid compilers */
150 
151     /*
152      * Between the fopen() and fclose() calls, avoid jumps that may cause
153      * file descriptor leaks.
154      */
155 
156     if ((fp = fopen(table, "r")) != 0) {
157 	tcpd_context.file = table;
158 	tcpd_context.line = 0;
159 	while (match == NO && xgets(sv_list, sizeof(sv_list), fp) != 0) {
160 	    if (sv_list[strlen(sv_list) - 1] != '\n') {
161 		tcpd_warn("missing newline or line too long");
162 		continue;
163 	    }
164 	    if (sv_list[0] == '#' || sv_list[strspn(sv_list, " \t\r\n")] == 0)
165 		continue;
166 	    if ((cl_list = split_at(skip_ipv6_addrs(sv_list), ':')) == 0) {
167 		tcpd_warn("missing \":\" separator");
168 		continue;
169 	    }
170 	    sh_cmd = split_at(skip_ipv6_addrs(cl_list), ':');
171 	    match = list_match(sv_list, request, server_match)
172 		&& list_match(cl_list, request, client_match);
173 	}
174 	(void) fclose(fp);
175     } else if (errno != ENOENT) {
176 	tcpd_warn("cannot open %s: %m", table);
177     }
178     if (match) {
179 	if (hosts_access_verbose > 1)
180 	    syslog(LOG_DEBUG, "matched:  %s line %d",
181 		   tcpd_context.file, tcpd_context.line);
182 	if (sh_cmd) {
183 #ifdef PROCESS_OPTIONS
184 	    process_options(sh_cmd, request);
185 #else
186 	    char    cmd[BUFSIZ];
187 	    shell_cmd(percent_x(cmd, sizeof(cmd), sh_cmd, request));
188 #endif
189 	}
190     }
191     tcpd_context = saved_context;
192     return (match);
193 }
194 
195 /* list_match - match a request against a list of patterns with exceptions */
196 
list_match(list,request,match_fn)197 static int list_match(list, request, match_fn)
198 char   *list;
199 struct request_info *request;
200 int   (*match_fn) ();
201 {
202     char   *tok;
203 
204     /*
205      * Process tokens one at a time. We have exhausted all possible matches
206      * when we reach an "EXCEPT" token or the end of the list. If we do find
207      * a match, look for an "EXCEPT" list and recurse to determine whether
208      * the match is affected by any exceptions.
209      */
210 
211     for (tok = strtok(list, sep); tok != 0; tok = strtok((char *) 0, sep)) {
212 	if (STR_EQ(tok, "EXCEPT"))		/* EXCEPT: give up */
213 	    return (NO);
214 	if (match_fn(tok, request)) {		/* YES: look for exceptions */
215 	    while ((tok = strtok((char *) 0, sep)) && STR_NE(tok, "EXCEPT"))
216 		 /* VOID */ ;
217 	    return (tok == 0 || list_match((char *) 0, request, match_fn) == 0);
218 	}
219     }
220     return (NO);
221 }
222 
223 /* server_match - match server information */
224 
server_match(tok,request)225 static int server_match(tok, request)
226 char   *tok;
227 struct request_info *request;
228 {
229     char   *host;
230 
231     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain daemon */
232 	return (string_match(tok, eval_daemon(request)));
233     } else {					/* daemon@host */
234 	return (string_match(tok, eval_daemon(request))
235 		&& host_match(host, request->server));
236     }
237 }
238 
239 /* client_match - match client information */
240 
client_match(tok,request)241 static int client_match(tok, request)
242 char   *tok;
243 struct request_info *request;
244 {
245     char   *host;
246 
247     if ((host = split_at(tok + 1, '@')) == 0) {	/* plain host */
248 	return (host_match(tok, request->client));
249     } else {					/* user@host */
250 	return (host_match(host, request->client)
251 		&& string_match(tok, eval_user(request)));
252     }
253 }
254 
255 /* host_match - match host name and/or address against pattern */
256 
host_match(tok,host)257 static int host_match(tok, host)
258 char   *tok;
259 struct host_info *host;
260 {
261     char   *mask;
262 
263     /*
264      * This code looks a little hairy because we want to avoid unnecessary
265      * hostname lookups.
266      *
267      * The KNOWN pattern requires that both address AND name be known; some
268      * patterns are specific to host names or to host addresses; all other
269      * patterns are satisfied when either the address OR the name match.
270      */
271 
272     if (tok[0] == '@') {			/* netgroup: look it up */
273 #ifdef  NETGROUP
274 	static char *mydomain = 0;
275 	if (mydomain == 0)
276 	    yp_get_default_domain(&mydomain);
277 	return (innetgr(tok + 1, eval_hostname(host), (char *) 0, mydomain));
278 #else
279 	tcpd_warn("netgroup support is disabled");	/* not tcpd_jump() */
280 	return (NO);
281 #endif
282     } else if (STR_EQ(tok, "KNOWN")) {		/* check address and name */
283 	char   *name = eval_hostname(host);
284 	return (STR_NE(eval_hostaddr(host), unknown) && HOSTNAME_KNOWN(name));
285     } else if (STR_EQ(tok, "LOCAL")) {		/* local: no dots in name */
286 	char   *name = eval_hostname(host);
287 	return (strchr(name, '.') == 0 && HOSTNAME_KNOWN(name));
288 #ifdef HAVE_IPV6
289     } else if (tok[0] == '[') {			/* IPv6 address */
290 	    struct in6_addr in6, hostin6, *hip;
291 	    char *cbr;
292 	    char *slash;
293 	    int mask = IPV6_ABITS;
294 
295 	    /*
296 	     * In some cases we don't get the sockaddr, only the addr.
297 	     * We use inet_pton to convert it to its binary representation
298 	     * and match against that.
299 	     */
300 	    if (host->sin == NULL) {
301 		if (host->addr == NULL ||
302 		    inet_pton(AF_INET6, host->addr, &hostin6) != 1) {
303 		    return (NO);
304 		}
305 		hip = &hostin6;
306 	    } else {
307 		if (SGFAM(host->sin) != AF_INET6)
308 		    return (NO);
309 		hip = &host->sin->sg_sin6.sin6_addr;
310 	    }
311 
312 	    if (cbr = strchr(tok, ']'))
313 		*cbr = '\0';
314 
315 	    /*
316 	     * A /nnn prefix specifies how many bits of the address we
317 	     * need to check.
318 	     */
319 	    if (slash = strchr(tok, '/')) {
320 		*slash = '\0';
321 		mask = atoi(slash+1);
322 		if (mask < 0 || mask > IPV6_ABITS) {
323 		    tcpd_warn("bad IP6 prefix specification");
324 		    return (NO);
325 		}
326 		/* Copy, because we need to modify it below */
327 		if (host->sin != NULL) {
328 		    hostin6 = host->sin->sg_sin6.sin6_addr;
329 		    hip = &hostin6;
330 		}
331 	    }
332 
333 	    if (cbr == NULL || inet_pton(AF_INET6, tok+1, &in6) != 1) {
334 		tcpd_warn("bad IP6 address specification");
335 		return (NO);
336 	    }
337 	    /*
338 	     * Zero the bits we're not interested in in both addresses
339 	     * then compare.  Note that we take a copy of the host info
340 	     * in that case.
341 	     */
342 	    if (mask != IPV6_ABITS) {
343 		ipv6_mask(&in6, mask);
344 		ipv6_mask(hip, mask);
345 	    }
346 	    if (memcmp(&in6, hip, sizeof(in6)) == 0)
347 		return (YES);
348 	    return (NO);
349 #endif
350     } else if ((mask = split_at(tok, '/')) != 0) {	/* net/mask */
351 	return (masked_match(tok, mask, eval_hostaddr(host)));
352     } else {					/* anything else */
353 	return (string_match(tok, eval_hostaddr(host))
354 	    || (NOT_INADDR(tok) && string_match(tok, eval_hostname(host))));
355     }
356 }
357 
358 /* string_match - match string against pattern */
359 
string_match(tok,string)360 static int string_match(tok, string)
361 char   *tok;
362 char   *string;
363 {
364     int     n;
365 
366     if (tok[0] == '.') {			/* suffix */
367 	n = strlen(string) - strlen(tok);
368 	return (n > 0 && STR_EQ(tok, string + n));
369     } else if (STR_EQ(tok, "ALL")) {		/* all: match any */
370 	return (YES);
371     } else if (STR_EQ(tok, "KNOWN")) {		/* not unknown */
372 	return (STR_NE(string, unknown));
373     } else if (tok[(n = strlen(tok)) - 1] == '.') {	/* prefix */
374 	return (STRN_EQ(tok, string, n));
375     } else {					/* exact match */
376 	return (STR_EQ(tok, string));
377     }
378 }
379 
380 /* masked_match - match address against netnumber/netmask */
381 
masked_match(net_tok,mask_tok,string)382 static int masked_match(net_tok, mask_tok, string)
383 char   *net_tok;
384 char   *mask_tok;
385 char   *string;
386 {
387     unsigned long net;
388     unsigned long mask;
389     unsigned long addr;
390 
391     /*
392      * Disallow forms other than dotted quad: the treatment that inet_addr()
393      * gives to forms with less than four components is inconsistent with the
394      * access control language. John P. Rouillard <rouilj@cs.umb.edu>.
395      */
396 
397     if ((addr = dot_quad_addr(string)) == INADDR_NONE)
398 	return (NO);
399     if ((net = dot_quad_addr(net_tok)) == INADDR_NONE
400 	|| (mask = dot_quad_addr(mask_tok)) == INADDR_NONE) {
401 	tcpd_warn("bad net/mask expression: %s/%s", net_tok, mask_tok);
402 	return (NO);				/* not tcpd_jump() */
403     }
404     return ((addr & mask) == net);
405 }
406 
407 #ifdef HAVE_IPV6
408 /*
409  * Function that zeros all but the first "maskbits" bits of the IPV6 address
410  * This function can be made generic by specifying an address length as
411  * extra parameter. (So Wietse can implement 1.2.3.4/16)
412  */
ipv6_mask(in6p,maskbits)413 static void ipv6_mask(in6p, maskbits)
414 struct in6_addr *in6p;
415 int maskbits;
416 {
417     uchar_t *p = (uchar_t*) in6p;
418 
419     if (maskbits < 0 || maskbits >= IPV6_ABITS)
420 	return;
421 
422     p += maskbits / 8;
423     maskbits %= 8;
424 
425     if (maskbits != 0)
426 	*p++ &= 0xff << (8 - maskbits);
427 
428     while (p < (((uchar_t*) in6p)) + sizeof(*in6p))
429 	*p++ = 0;
430 }
431 #endif
432