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