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