xref: /freebsd/contrib/tcp_wrappers/options.c (revision 54e9e4e72d711fb41f88f793f6c64df1126112f9)
1  /*
2   * General skeleton for adding options to the access control language. The
3   * features offered by this module are documented in the hosts_options(5)
4   * manual page (source file: hosts_options.5, "nroff -man" format).
5   *
6   * Notes and warnings for those who want to add features:
7   *
8   * In case of errors, abort options processing and deny access. There are too
9   * many irreversible side effects to make error recovery feasible. For
10   * example, it makes no sense to continue after we have already changed the
11   * userid.
12   *
13   * In case of errors, do not terminate the process: the routines might be
14   * called from a long-running daemon that should run forever. Instead, call
15   * tcpd_jump() which does a non-local goto back into the hosts_access()
16   * routine.
17   *
18   * In case of severe errors, use clean_exit() instead of directly calling
19   * exit(), or the inetd may loop on an UDP request.
20   *
21   * In verification mode (for example, with the "tcpdmatch" command) the
22   * "dry_run" flag is set. In this mode, an option function should just "say"
23   * what it is going to do instead of really doing it.
24   *
25   * Some option functions do not return (for example, the twist option passes
26   * control to another program). In verification mode (dry_run flag is set)
27   * such options should clear the "dry_run" flag to inform the caller of this
28   * course of action.
29   *
30   * $FreeBSD$
31   */
32 
33 #ifndef lint
34 static char sccsid[] = "@(#) options.c 1.17 96/02/11 17:01:31";
35 #endif
36 
37 /* System libraries. */
38 
39 #include <sys/types.h>
40 #include <sys/param.h>
41 #include <sys/socket.h>
42 #include <sys/stat.h>
43 #include <netinet/in.h>
44 #include <netdb.h>
45 #include <stdio.h>
46 #define SYSLOG_NAMES
47 #include <syslog.h>
48 #include <pwd.h>
49 #include <grp.h>
50 #include <ctype.h>
51 #include <setjmp.h>
52 #include <string.h>
53 #include <unistd.h>
54 #include <stdlib.h>
55 
56 #ifndef MAXPATHNAMELEN
57 #define MAXPATHNAMELEN  BUFSIZ
58 #endif
59 
60 /* Local stuff. */
61 
62 #include "tcpd.h"
63 
64 /* Options runtime support. */
65 
66 int     dry_run = 0;			/* flag set in verification mode */
67 extern jmp_buf tcpd_buf;		/* tcpd_jump() support */
68 
69 /* Options parser support. */
70 
71 static char whitespace_eq[] = "= \t\r\n";
72 #define whitespace (whitespace_eq + 1)
73 
74 static char *get_field(char *string);		/* chew :-delimited field off string */
75 static char *chop_string(char *string);		/* strip leading and trailing blanks */
76 
77 /* List of functions that implement the options. Add yours here. */
78 
79 static void user_option();		/* execute "user name.group" option */
80 static void group_option();		/* execute "group name" option */
81 static void umask_option();		/* execute "umask mask" option */
82 static void linger_option();		/* execute "linger time" option */
83 static void keepalive_option();		/* execute "keepalive" option */
84 static void spawn_option();		/* execute "spawn command" option */
85 static void twist_option();		/* execute "twist command" option */
86 static void rfc931_option();		/* execute "rfc931" option */
87 static void setenv_option();		/* execute "setenv name value" */
88 static void nice_option();		/* execute "nice" option */
89 static void severity_option();		/* execute "severity value" */
90 static void allow_option();		/* execute "allow" option */
91 static void deny_option();		/* execute "deny" option */
92 static void banners_option();		/* execute "banners path" option */
93 
94 /* Structure of the options table. */
95 
96 struct option {
97     char   *name;			/* keyword name, case is ignored */
98     void  (*func) ();			/* function that does the real work */
99     int     flags;			/* see below... */
100 };
101 
102 #define NEED_ARG	(1<<1)		/* option requires argument */
103 #define USE_LAST	(1<<2)		/* option must be last */
104 #define OPT_ARG		(1<<3)		/* option has optional argument */
105 #define EXPAND_ARG	(1<<4)		/* do %x expansion on argument */
106 
107 #define need_arg(o)	((o)->flags & NEED_ARG)
108 #define opt_arg(o)	((o)->flags & OPT_ARG)
109 #define permit_arg(o)	((o)->flags & (NEED_ARG | OPT_ARG))
110 #define use_last(o)	((o)->flags & USE_LAST)
111 #define expand_arg(o)	((o)->flags & EXPAND_ARG)
112 
113 /* List of known keywords. Add yours here. */
114 
115 static struct option option_table[] = {
116     "user", user_option, NEED_ARG,
117     "group", group_option, NEED_ARG,
118     "umask", umask_option, NEED_ARG,
119     "linger", linger_option, NEED_ARG,
120     "keepalive", keepalive_option, 0,
121     "spawn", spawn_option, NEED_ARG | EXPAND_ARG,
122     "twist", twist_option, NEED_ARG | EXPAND_ARG | USE_LAST,
123     "rfc931", rfc931_option, OPT_ARG,
124     "setenv", setenv_option, NEED_ARG | EXPAND_ARG,
125     "nice", nice_option, OPT_ARG,
126     "severity", severity_option, NEED_ARG,
127     "allow", allow_option, USE_LAST,
128     "deny", deny_option, USE_LAST,
129     "banners", banners_option, NEED_ARG,
130     0,
131 };
132 
133 /* process_options - process access control options */
134 
135 void    process_options(options, request)
136 char   *options;
137 struct request_info *request;
138 {
139     char   *key;
140     char   *value;
141     char   *curr_opt;
142     char   *next_opt;
143     struct option *op;
144     char    bf[BUFSIZ];
145 
146     for (curr_opt = get_field(options); curr_opt; curr_opt = next_opt) {
147 	next_opt = get_field((char *) 0);
148 
149 	/*
150 	 * Separate the option into name and value parts. For backwards
151 	 * compatibility we ignore exactly one '=' between name and value.
152 	 */
153 	curr_opt = chop_string(curr_opt);
154 	if (*(value = curr_opt + strcspn(curr_opt, whitespace_eq))) {
155 	    if (*value != '=') {
156 		*value++ = 0;
157 		value += strspn(value, whitespace);
158 	    }
159 	    if (*value == '=') {
160 		*value++ = 0;
161 		value += strspn(value, whitespace);
162 	    }
163 	}
164 	if (*value == 0)
165 	    value = 0;
166 	key = curr_opt;
167 
168 	/*
169 	 * Disallow missing option names (and empty option fields).
170 	 */
171 	if (*key == 0)
172 	    tcpd_jump("missing option name");
173 
174 	/*
175 	 * Lookup the option-specific info and do some common error checks.
176 	 * Delegate option-specific processing to the specific functions.
177 	 */
178 
179 	for (op = option_table; op->name && STR_NE(op->name, key); op++)
180 	     /* VOID */ ;
181 	if (op->name == 0)
182 	    tcpd_jump("bad option name: \"%s\"", key);
183 	if (!value && need_arg(op))
184 	    tcpd_jump("option \"%s\" requires value", key);
185 	if (value && !permit_arg(op))
186 	    tcpd_jump("option \"%s\" requires no value", key);
187 	if (next_opt && use_last(op))
188 	    tcpd_jump("option \"%s\" must be at end", key);
189 	if (value && expand_arg(op))
190 	    value = chop_string(percent_x(bf, sizeof(bf), value, request));
191 	if (hosts_access_verbose)
192 	    syslog(LOG_DEBUG, "option:   %s %s", key, value ? value : "");
193 	(*(op->func)) (value, request);
194     }
195 }
196 
197 /* allow_option - grant access */
198 
199 /* ARGSUSED */
200 
201 static void allow_option(value, request)
202 char   *value;
203 struct request_info *request;
204 {
205     longjmp(tcpd_buf, AC_PERMIT);
206 }
207 
208 /* deny_option - deny access */
209 
210 /* ARGSUSED */
211 
212 static void deny_option(value, request)
213 char   *value;
214 struct request_info *request;
215 {
216     longjmp(tcpd_buf, AC_DENY);
217 }
218 
219 /* banners_option - expand %<char>, terminate each line with CRLF */
220 
221 static void banners_option(value, request)
222 char   *value;
223 struct request_info *request;
224 {
225     char    path[MAXPATHNAMELEN];
226     char    ibuf[BUFSIZ];
227     char    obuf[2 * BUFSIZ];
228     struct stat st;
229     int     ch;
230     FILE   *fp;
231 
232     sprintf(path, "%s/%s", value, eval_daemon(request));
233     if ((fp = fopen(path, "r")) != 0) {
234 	while ((ch = fgetc(fp)) == 0)
235 	    write(request->fd, "", 1);
236 	ungetc(ch, fp);
237 	while (fgets(ibuf, sizeof(ibuf) - 1, fp)) {
238 	    if (split_at(ibuf, '\n'))
239 		strcat(ibuf, "\r\n");
240 	    percent_x(obuf, sizeof(obuf), ibuf, request);
241 	    write(request->fd, obuf, strlen(obuf));
242 	}
243 	fclose(fp);
244     } else if (stat(value, &st) < 0) {
245 	tcpd_warn("%s: %m", value);
246     }
247 }
248 
249 /* group_option - switch group id */
250 
251 /* ARGSUSED */
252 
253 static void group_option(value, request)
254 char   *value;
255 struct request_info *request;
256 {
257     struct group *grp;
258     struct group *getgrnam();
259 
260     if ((grp = getgrnam(value)) == 0)
261 	tcpd_jump("unknown group: \"%s\"", value);
262     endgrent();
263 
264     if (dry_run == 0 && setgid(grp->gr_gid))
265 	tcpd_jump("setgid(%s): %m", value);
266 }
267 
268 /* user_option - switch user id */
269 
270 /* ARGSUSED */
271 
272 static void user_option(value, request)
273 char   *value;
274 struct request_info *request;
275 {
276     struct passwd *pwd;
277     struct passwd *getpwnam();
278     char   *group;
279 
280     if ((group = split_at(value, '.')) != 0)
281 	group_option(group, request);
282     if ((pwd = getpwnam(value)) == 0)
283 	tcpd_jump("unknown user: \"%s\"", value);
284     endpwent();
285 
286     if (dry_run == 0 && setuid(pwd->pw_uid))
287 	tcpd_jump("setuid(%s): %m", value);
288 }
289 
290 /* umask_option - set file creation mask */
291 
292 /* ARGSUSED */
293 
294 static void umask_option(value, request)
295 char   *value;
296 struct request_info *request;
297 {
298     unsigned mask;
299     char    junk;
300 
301     if (sscanf(value, "%o%c", &mask, &junk) != 1 || (mask & 0777) != mask)
302 	tcpd_jump("bad umask value: \"%s\"", value);
303     (void) umask(mask);
304 }
305 
306 /* spawn_option - spawn a shell command and wait */
307 
308 /* ARGSUSED */
309 
310 static void spawn_option(value, request)
311 char   *value;
312 struct request_info *request;
313 {
314     if (dry_run == 0)
315 	shell_cmd(value);
316 }
317 
318 /* linger_option - set the socket linger time (Marc Boucher <marc@cam.org>) */
319 
320 /* ARGSUSED */
321 
322 static void linger_option(value, request)
323 char   *value;
324 struct request_info *request;
325 {
326     struct linger linger;
327     char    junk;
328 
329     if (sscanf(value, "%d%c", &linger.l_linger, &junk) != 1
330 	|| linger.l_linger < 0)
331 	tcpd_jump("bad linger value: \"%s\"", value);
332     if (dry_run == 0) {
333 	linger.l_onoff = (linger.l_linger != 0);
334 	if (setsockopt(request->fd, SOL_SOCKET, SO_LINGER, (char *) &linger,
335 		       sizeof(linger)) < 0)
336 	    tcpd_warn("setsockopt SO_LINGER %d: %m", linger.l_linger);
337     }
338 }
339 
340 /* keepalive_option - set the socket keepalive option */
341 
342 /* ARGSUSED */
343 
344 static void keepalive_option(value, request)
345 char   *value;
346 struct request_info *request;
347 {
348     static int on = 1;
349 
350     if (dry_run == 0 && setsockopt(request->fd, SOL_SOCKET, SO_KEEPALIVE,
351 				   (char *) &on, sizeof(on)) < 0)
352 	tcpd_warn("setsockopt SO_KEEPALIVE: %m");
353 }
354 
355 /* nice_option - set nice value */
356 
357 /* ARGSUSED */
358 
359 static void nice_option(value, request)
360 char   *value;
361 struct request_info *request;
362 {
363     int     niceval = 10;
364     char    junk;
365 
366     if (value != 0 && sscanf(value, "%d%c", &niceval, &junk) != 1)
367 	tcpd_jump("bad nice value: \"%s\"", value);
368     if (dry_run == 0 && nice(niceval) < 0)
369 	tcpd_warn("nice(%d): %m", niceval);
370 }
371 
372 /* twist_option - replace process by shell command */
373 
374 static void twist_option(value, request)
375 char   *value;
376 struct request_info *request;
377 {
378     char   *error;
379 
380     if (dry_run != 0) {
381 	dry_run = 0;
382     } else {
383 	if (resident > 0)
384 	    tcpd_jump("twist option in resident process");
385 
386 	syslog(deny_severity, "twist %s to %s", eval_client(request), value);
387 
388 	/* Before switching to the shell, set up stdin, stdout and stderr. */
389 
390 #define maybe_dup2(from, to) ((from == to) ? to : (close(to), dup(from)))
391 
392 	if (maybe_dup2(request->fd, 0) != 0 ||
393 	    maybe_dup2(request->fd, 1) != 1 ||
394 	    maybe_dup2(request->fd, 2) != 2) {
395 	    error = "twist_option: dup: %m";
396 	} else {
397 	    if (request->fd > 2)
398 		close(request->fd);
399 	    (void) execl("/bin/sh", "sh", "-c", value, (char *) 0);
400 	    error = "twist_option: /bin/sh: %m";
401 	}
402 
403 	/* Something went wrong: we MUST terminate the process. */
404 
405 	tcpd_warn(error);
406 	clean_exit(request);
407     }
408 }
409 
410 /* rfc931_option - look up remote user name */
411 
412 static void rfc931_option(value, request)
413 char   *value;
414 struct request_info *request;
415 {
416     int     timeout;
417     char    junk;
418 
419     if (value != 0) {
420 	if (sscanf(value, "%d%c", &timeout, &junk) != 1 || timeout <= 0)
421 	    tcpd_jump("bad rfc931 timeout: \"%s\"", value);
422 	rfc931_timeout = timeout;
423     }
424     (void) eval_user(request);
425 }
426 
427 /* setenv_option - set environment variable */
428 
429 /* ARGSUSED */
430 
431 static void setenv_option(value, request)
432 char   *value;
433 struct request_info *request;
434 {
435     char   *var_value;
436 
437     if (*(var_value = value + strcspn(value, whitespace)))
438 	*var_value++ = 0;
439     if (setenv(chop_string(value), chop_string(var_value), 1))
440 	tcpd_jump("memory allocation failure");
441 }
442 
443 /* severity_map - lookup facility or severity value */
444 
445 static int severity_map(table, name)
446 const CODE   *table;
447 char   *name;
448 {
449     const CODE *t;
450     int ret = -1;
451 
452     for (t = table; t->c_name; t++)
453 	if (STR_EQ(t->c_name, name)) {
454 	    ret = t->c_val;
455 	    break;
456 	}
457     if (ret == -1)
458     	tcpd_jump("bad syslog facility or severity: \"%s\"", name);
459 
460     return (ret);
461 }
462 
463 /* severity_option - change logging severity for this event (Dave Mitchell) */
464 
465 /* ARGSUSED */
466 
467 static void severity_option(value, request)
468 char   *value;
469 struct request_info *request;
470 {
471     char   *level = split_at(value, '.');
472 
473     allow_severity = deny_severity = level ?
474 	severity_map(facilitynames, value) | severity_map(prioritynames, level)
475 	: severity_map(prioritynames, value);
476 }
477 
478 /* get_field - return pointer to next field in string */
479 
480 static char *get_field(string)
481 char   *string;
482 {
483     static char *last = "";
484     char   *src;
485     char   *dst;
486     char   *ret;
487     int     ch;
488 
489     /*
490      * This function returns pointers to successive fields within a given
491      * string. ":" is the field separator; warn if the rule ends in one. It
492      * replaces a "\:" sequence by ":", without treating the result of
493      * substitution as field terminator. A null argument means resume search
494      * where the previous call terminated. This function destroys its
495      * argument.
496      *
497      * Work from explicit source or from memory. While processing \: we
498      * overwrite the input. This way we do not have to maintain buffers for
499      * copies of input fields.
500      */
501 
502     src = dst = ret = (string ? string : last);
503     if (src[0] == 0)
504 	return (0);
505 
506     while (ch = *src) {
507 	if (ch == ':') {
508 	    if (*++src == 0)
509 		tcpd_warn("rule ends in \":\"");
510 	    break;
511 	}
512 	if (ch == '\\' && src[1] == ':')
513 	    src++;
514 	*dst++ = *src++;
515     }
516     last = src;
517     *dst = 0;
518     return (ret);
519 }
520 
521 /* chop_string - strip leading and trailing blanks from string */
522 
523 static char *chop_string(string)
524 register char *string;
525 {
526     char   *start = 0;
527     char   *end;
528     char   *cp;
529 
530     for (cp = string; *cp; cp++) {
531 	if (!isspace(*cp)) {
532 	    if (start == 0)
533 		start = cp;
534 	    end = cp;
535 	}
536     }
537     return (start ? (end[1] = 0, start) : cp);
538 }
539