xref: /freebsd/contrib/tcp_wrappers/options.c (revision 1719886f6d08408b834d270c59ffcfd821c8f63a)
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(char *, struct request_info *);		/* user name.group */
80 static void group_option(char *, struct request_info *);	/* group name */
81 static void umask_option(char *, struct request_info *);	/* umask mask */
82 static void linger_option(char *, struct request_info *);	/* linger time */
83 static void keepalive_option(char *, struct request_info *);	/* keepalive */
84 static void spawn_option(char *, struct request_info *);	/* spawn command */
85 static void twist_option(char *, struct request_info *);	/* twist command */
86 static void rfc931_option(char *, struct request_info *);	/* rfc931 */
87 static void setenv_option(char *, struct request_info *);	/* setenv name value */
88 static void nice_option(char *, struct request_info *);		/* nice */
89 static void severity_option(char *, struct request_info *);	/* severity value */
90 static void allow_option(char *, struct request_info *);	/* allow */
91 static void deny_option(char *, struct request_info *);		/* deny */
92 static void banners_option(char *, struct request_info *);	/* banners path */
93 
94 /* Structure of the options table. */
95 
96 struct option {
97     char   *name;			/* keyword name, case is ignored */
98     void  (*func) (char *value, struct request_info *request);
99 					/* function that does the real work */
100     int     flags;			/* see below... */
101 };
102 
103 #define NEED_ARG	(1<<1)		/* option requires argument */
104 #define USE_LAST	(1<<2)		/* option must be last */
105 #define OPT_ARG		(1<<3)		/* option has optional argument */
106 #define EXPAND_ARG	(1<<4)		/* do %x expansion on argument */
107 
108 #define need_arg(o)	((o)->flags & NEED_ARG)
109 #define opt_arg(o)	((o)->flags & OPT_ARG)
110 #define permit_arg(o)	((o)->flags & (NEED_ARG | OPT_ARG))
111 #define use_last(o)	((o)->flags & USE_LAST)
112 #define expand_arg(o)	((o)->flags & EXPAND_ARG)
113 
114 /* List of known keywords. Add yours here. */
115 
116 static struct option option_table[] = {
117     "user", user_option, NEED_ARG,
118     "group", group_option, NEED_ARG,
119     "umask", umask_option, NEED_ARG,
120     "linger", linger_option, NEED_ARG,
121     "keepalive", keepalive_option, 0,
122     "spawn", spawn_option, NEED_ARG | EXPAND_ARG,
123     "twist", twist_option, NEED_ARG | EXPAND_ARG | USE_LAST,
124     "rfc931", rfc931_option, OPT_ARG,
125     "setenv", setenv_option, NEED_ARG | EXPAND_ARG,
126     "nice", nice_option, OPT_ARG,
127     "severity", severity_option, NEED_ARG,
128     "allow", allow_option, USE_LAST,
129     "deny", deny_option, USE_LAST,
130     "banners", banners_option, NEED_ARG,
131     0,
132 };
133 
134 /* process_options - process access control options */
135 
136 void    process_options(char *options, struct request_info *request)
137 {
138     char   *key;
139     char   *value;
140     char   *curr_opt;
141     char   *next_opt;
142     struct option *op;
143     char    bf[BUFSIZ];
144 
145     for (curr_opt = get_field(options); curr_opt; curr_opt = next_opt) {
146 	next_opt = get_field((char *) 0);
147 
148 	/*
149 	 * Separate the option into name and value parts. For backwards
150 	 * compatibility we ignore exactly one '=' between name and value.
151 	 */
152 	curr_opt = chop_string(curr_opt);
153 	if (*(value = curr_opt + strcspn(curr_opt, whitespace_eq))) {
154 	    if (*value != '=') {
155 		*value++ = 0;
156 		value += strspn(value, whitespace);
157 	    }
158 	    if (*value == '=') {
159 		*value++ = 0;
160 		value += strspn(value, whitespace);
161 	    }
162 	}
163 	if (*value == 0)
164 	    value = 0;
165 	key = curr_opt;
166 
167 	/*
168 	 * Disallow missing option names (and empty option fields).
169 	 */
170 	if (*key == 0)
171 	    tcpd_jump("missing option name");
172 
173 	/*
174 	 * Lookup the option-specific info and do some common error checks.
175 	 * Delegate option-specific processing to the specific functions.
176 	 */
177 
178 	for (op = option_table; op->name && STR_NE(op->name, key); op++)
179 	     /* VOID */ ;
180 	if (op->name == 0)
181 	    tcpd_jump("bad option name: \"%s\"", key);
182 	if (!value && need_arg(op))
183 	    tcpd_jump("option \"%s\" requires value", key);
184 	if (value && !permit_arg(op))
185 	    tcpd_jump("option \"%s\" requires no value", key);
186 	if (next_opt && use_last(op))
187 	    tcpd_jump("option \"%s\" must be at end", key);
188 	if (value && expand_arg(op))
189 	    value = chop_string(percent_x(bf, sizeof(bf), value, request));
190 	if (hosts_access_verbose)
191 	    syslog(LOG_DEBUG, "option:   %s %s", key, value ? value : "");
192 	(*(op->func)) (value, request);
193     }
194 }
195 
196 /* allow_option - grant access */
197 
198 /* ARGSUSED */
199 
200 static void allow_option(char *value, struct request_info *request)
201 {
202     longjmp(tcpd_buf, AC_PERMIT);
203 }
204 
205 /* deny_option - deny access */
206 
207 /* ARGSUSED */
208 
209 static void deny_option(char *value, struct request_info *request)
210 {
211     longjmp(tcpd_buf, AC_DENY);
212 }
213 
214 /* banners_option - expand %<char>, terminate each line with CRLF */
215 
216 static void banners_option(char *value, struct request_info *request)
217 {
218     char    path[MAXPATHNAMELEN];
219     char    ibuf[BUFSIZ];
220     char    obuf[2 * BUFSIZ];
221     struct stat st;
222     int     ch;
223     FILE   *fp;
224 
225     sprintf(path, "%s/%s", value, eval_daemon(request));
226     if ((fp = fopen(path, "r")) != 0) {
227 	while ((ch = fgetc(fp)) == 0)
228 	    write(request->fd, "", 1);
229 	ungetc(ch, fp);
230 	while (fgets(ibuf, sizeof(ibuf) - 1, fp)) {
231 	    if (split_at(ibuf, '\n'))
232 		strcat(ibuf, "\r\n");
233 	    percent_x(obuf, sizeof(obuf), ibuf, request);
234 	    write(request->fd, obuf, strlen(obuf));
235 	}
236 	fclose(fp);
237     } else if (stat(value, &st) < 0) {
238 	tcpd_warn("%s: %m", value);
239     }
240 }
241 
242 /* group_option - switch group id */
243 
244 /* ARGSUSED */
245 
246 static void group_option(char *value, struct request_info *request)
247 {
248     struct group *grp;
249 
250     if ((grp = getgrnam(value)) == 0)
251 	tcpd_jump("unknown group: \"%s\"", value);
252     endgrent();
253 
254     if (dry_run == 0 && setgid(grp->gr_gid))
255 	tcpd_jump("setgid(%s): %m", value);
256 }
257 
258 /* user_option - switch user id */
259 
260 /* ARGSUSED */
261 
262 static void user_option(char *value, struct request_info *request)
263 {
264     struct passwd *pwd;
265     char   *group;
266 
267     if ((group = split_at(value, '.')) != 0)
268 	group_option(group, request);
269     if ((pwd = getpwnam(value)) == 0)
270 	tcpd_jump("unknown user: \"%s\"", value);
271     endpwent();
272 
273     if (dry_run == 0 && setuid(pwd->pw_uid))
274 	tcpd_jump("setuid(%s): %m", value);
275 }
276 
277 /* umask_option - set file creation mask */
278 
279 /* ARGSUSED */
280 
281 static void umask_option(char *value, struct request_info *request)
282 {
283     unsigned mask;
284     char    junk;
285 
286     if (sscanf(value, "%o%c", &mask, &junk) != 1 || (mask & 0777) != mask)
287 	tcpd_jump("bad umask value: \"%s\"", value);
288     (void) umask(mask);
289 }
290 
291 /* spawn_option - spawn a shell command and wait */
292 
293 /* ARGSUSED */
294 
295 static void spawn_option(char *value, struct request_info *request)
296 {
297     if (dry_run == 0)
298 	shell_cmd(value);
299 }
300 
301 /* linger_option - set the socket linger time (Marc Boucher <marc@cam.org>) */
302 
303 /* ARGSUSED */
304 
305 static void linger_option(char *value, struct request_info *request)
306 {
307     struct linger linger;
308     char    junk;
309 
310     if (sscanf(value, "%d%c", &linger.l_linger, &junk) != 1
311 	|| linger.l_linger < 0)
312 	tcpd_jump("bad linger value: \"%s\"", value);
313     if (dry_run == 0) {
314 	linger.l_onoff = (linger.l_linger != 0);
315 	if (setsockopt(request->fd, SOL_SOCKET, SO_LINGER, (char *) &linger,
316 		       sizeof(linger)) < 0)
317 	    tcpd_warn("setsockopt SO_LINGER %d: %m", linger.l_linger);
318     }
319 }
320 
321 /* keepalive_option - set the socket keepalive option */
322 
323 /* ARGSUSED */
324 
325 static void keepalive_option(char *value, struct request_info *request)
326 {
327     static int on = 1;
328 
329     if (dry_run == 0 && setsockopt(request->fd, SOL_SOCKET, SO_KEEPALIVE,
330 				   (char *) &on, sizeof(on)) < 0)
331 	tcpd_warn("setsockopt SO_KEEPALIVE: %m");
332 }
333 
334 /* nice_option - set nice value */
335 
336 /* ARGSUSED */
337 
338 static void nice_option(char *value, struct request_info *request)
339 {
340     int     niceval = 10;
341     char    junk;
342 
343     if (value != 0 && sscanf(value, "%d%c", &niceval, &junk) != 1)
344 	tcpd_jump("bad nice value: \"%s\"", value);
345     if (dry_run == 0 && nice(niceval) < 0)
346 	tcpd_warn("nice(%d): %m", niceval);
347 }
348 
349 /* twist_option - replace process by shell command */
350 
351 static void twist_option(char *value, struct request_info *request)
352 {
353     char   *error;
354 
355     if (dry_run != 0) {
356 	dry_run = 0;
357     } else {
358 	if (resident > 0)
359 	    tcpd_jump("twist option in resident process");
360 
361 	syslog(deny_severity, "twist %s to %s", eval_client(request), value);
362 
363 	/* Before switching to the shell, set up stdin, stdout and stderr. */
364 
365 #define maybe_dup2(from, to) ((from == to) ? to : (close(to), dup(from)))
366 
367 	if (maybe_dup2(request->fd, 0) != 0 ||
368 	    maybe_dup2(request->fd, 1) != 1 ||
369 	    maybe_dup2(request->fd, 2) != 2) {
370 	    error = "twist_option: dup: %m";
371 	} else {
372 	    if (request->fd > 2)
373 		close(request->fd);
374 	    (void) execl("/bin/sh", "sh", "-c", value, (char *) 0);
375 	    error = "twist_option: /bin/sh: %m";
376 	}
377 
378 	/* Something went wrong: we MUST terminate the process. */
379 
380 	tcpd_warn(error);
381 	clean_exit(request);
382     }
383 }
384 
385 /* rfc931_option - look up remote user name */
386 
387 static void rfc931_option(char *value, struct request_info *request)
388 {
389     int     timeout;
390     char    junk;
391 
392     if (value != 0) {
393 	if (sscanf(value, "%d%c", &timeout, &junk) != 1 || timeout <= 0)
394 	    tcpd_jump("bad rfc931 timeout: \"%s\"", value);
395 	rfc931_timeout = timeout;
396     }
397     (void) eval_user(request);
398 }
399 
400 /* setenv_option - set environment variable */
401 
402 /* ARGSUSED */
403 
404 static void setenv_option(char *value, struct request_info *request)
405 {
406     char   *var_value;
407 
408     if (*(var_value = value + strcspn(value, whitespace)))
409 	*var_value++ = 0;
410     if (setenv(chop_string(value), chop_string(var_value), 1))
411 	tcpd_jump("memory allocation failure");
412 }
413 
414 /* severity_map - lookup facility or severity value */
415 
416 static int severity_map(const CODE *table, char *name)
417 {
418     const CODE *t;
419     int ret = -1;
420 
421     for (t = table; t->c_name; t++)
422 	if (STR_EQ(t->c_name, name)) {
423 	    ret = t->c_val;
424 	    break;
425 	}
426     if (ret == -1)
427     	tcpd_jump("bad syslog facility or severity: \"%s\"", name);
428 
429     return (ret);
430 }
431 
432 /* severity_option - change logging severity for this event (Dave Mitchell) */
433 
434 /* ARGSUSED */
435 
436 static void severity_option(char *value, struct request_info *request)
437 {
438     char   *level = split_at(value, '.');
439 
440     allow_severity = deny_severity = level ?
441 	severity_map(facilitynames, value) | severity_map(prioritynames, level)
442 	: severity_map(prioritynames, value);
443 }
444 
445 /* get_field - return pointer to next field in string */
446 
447 static char *get_field(char *string)
448 {
449     static char *last = "";
450     char   *src;
451     char   *dst;
452     char   *ret;
453     int     ch;
454 
455     /*
456      * This function returns pointers to successive fields within a given
457      * string. ":" is the field separator; warn if the rule ends in one. It
458      * replaces a "\:" sequence by ":", without treating the result of
459      * substitution as field terminator. A null argument means resume search
460      * where the previous call terminated. This function destroys its
461      * argument.
462      *
463      * Work from explicit source or from memory. While processing \: we
464      * overwrite the input. This way we do not have to maintain buffers for
465      * copies of input fields.
466      */
467 
468     src = dst = ret = (string ? string : last);
469     if (src[0] == 0)
470 	return (0);
471 
472     while (ch = *src) {
473 	if (ch == ':') {
474 	    if (*++src == 0)
475 		tcpd_warn("rule ends in \":\"");
476 	    break;
477 	}
478 	if (ch == '\\' && src[1] == ':')
479 	    src++;
480 	*dst++ = *src++;
481     }
482     last = src;
483     *dst = 0;
484     return (ret);
485 }
486 
487 /* chop_string - strip leading and trailing blanks from string */
488 
489 static char *chop_string(register char *string)
490 {
491     char   *start = 0;
492     char   *end;
493     char   *cp;
494 
495     for (cp = string; *cp; cp++) {
496 	if (!isspace(*cp)) {
497 	    if (start == 0)
498 		start = cp;
499 	    end = cp;
500 	}
501     }
502     return (start ? (end[1] = 0, start) : cp);
503 }
504