]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/tcp_wrappers/options.c
Merge bmake-20230622
[FreeBSD/FreeBSD.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   * $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) (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(value, request)
201 char   *value;
202 struct request_info *request;
203 {
204     longjmp(tcpd_buf, AC_PERMIT);
205 }
206
207 /* deny_option - deny access */
208
209 /* ARGSUSED */
210
211 static void deny_option(value, request)
212 char   *value;
213 struct request_info *request;
214 {
215     longjmp(tcpd_buf, AC_DENY);
216 }
217
218 /* banners_option - expand %<char>, terminate each line with CRLF */
219
220 static void banners_option(char *value, 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(char *value, struct request_info *request)
251 {
252     struct group *grp;
253     struct group *getgrnam();
254
255     if ((grp = getgrnam(value)) == 0)
256         tcpd_jump("unknown group: \"%s\"", value);
257     endgrent();
258
259     if (dry_run == 0 && setgid(grp->gr_gid))
260         tcpd_jump("setgid(%s): %m", value);
261 }
262
263 /* user_option - switch user id */
264
265 /* ARGSUSED */
266
267 static void user_option(char *value, struct request_info *request)
268 {
269     struct passwd *pwd;
270     struct passwd *getpwnam();
271     char   *group;
272
273     if ((group = split_at(value, '.')) != 0)
274         group_option(group, request);
275     if ((pwd = getpwnam(value)) == 0)
276         tcpd_jump("unknown user: \"%s\"", value);
277     endpwent();
278
279     if (dry_run == 0 && setuid(pwd->pw_uid))
280         tcpd_jump("setuid(%s): %m", value);
281 }
282
283 /* umask_option - set file creation mask */
284
285 /* ARGSUSED */
286
287 static void umask_option(char *value, struct request_info *request)
288 {
289     unsigned mask;
290     char    junk;
291
292     if (sscanf(value, "%o%c", &mask, &junk) != 1 || (mask & 0777) != mask)
293         tcpd_jump("bad umask value: \"%s\"", value);
294     (void) umask(mask);
295 }
296
297 /* spawn_option - spawn a shell command and wait */
298
299 /* ARGSUSED */
300
301 static void spawn_option(char *value, struct request_info *request)
302 {
303     if (dry_run == 0)
304         shell_cmd(value);
305 }
306
307 /* linger_option - set the socket linger time (Marc Boucher <marc@cam.org>) */
308
309 /* ARGSUSED */
310
311 static void linger_option(char *value, struct request_info *request)
312 {
313     struct linger linger;
314     char    junk;
315
316     if (sscanf(value, "%d%c", &linger.l_linger, &junk) != 1
317         || linger.l_linger < 0)
318         tcpd_jump("bad linger value: \"%s\"", value);
319     if (dry_run == 0) {
320         linger.l_onoff = (linger.l_linger != 0);
321         if (setsockopt(request->fd, SOL_SOCKET, SO_LINGER, (char *) &linger,
322                        sizeof(linger)) < 0)
323             tcpd_warn("setsockopt SO_LINGER %d: %m", linger.l_linger);
324     }
325 }
326
327 /* keepalive_option - set the socket keepalive option */
328
329 /* ARGSUSED */
330
331 static void keepalive_option(char *value, struct request_info *request)
332 {
333     static int on = 1;
334
335     if (dry_run == 0 && setsockopt(request->fd, SOL_SOCKET, SO_KEEPALIVE,
336                                    (char *) &on, sizeof(on)) < 0)
337         tcpd_warn("setsockopt SO_KEEPALIVE: %m");
338 }
339
340 /* nice_option - set nice value */
341
342 /* ARGSUSED */
343
344 static void nice_option(char *value, struct request_info *request)
345 {
346     int     niceval = 10;
347     char    junk;
348
349     if (value != 0 && sscanf(value, "%d%c", &niceval, &junk) != 1)
350         tcpd_jump("bad nice value: \"%s\"", value);
351     if (dry_run == 0 && nice(niceval) < 0)
352         tcpd_warn("nice(%d): %m", niceval);
353 }
354
355 /* twist_option - replace process by shell command */
356
357 static void twist_option(char *value, struct request_info *request)
358 {
359     char   *error;
360
361     if (dry_run != 0) {
362         dry_run = 0;
363     } else {
364         if (resident > 0)
365             tcpd_jump("twist option in resident process");
366
367         syslog(deny_severity, "twist %s to %s", eval_client(request), value);
368
369         /* Before switching to the shell, set up stdin, stdout and stderr. */
370
371 #define maybe_dup2(from, to) ((from == to) ? to : (close(to), dup(from)))
372
373         if (maybe_dup2(request->fd, 0) != 0 ||
374             maybe_dup2(request->fd, 1) != 1 ||
375             maybe_dup2(request->fd, 2) != 2) {
376             error = "twist_option: dup: %m";
377         } else {
378             if (request->fd > 2)
379                 close(request->fd);
380             (void) execl("/bin/sh", "sh", "-c", value, (char *) 0);
381             error = "twist_option: /bin/sh: %m";
382         }
383
384         /* Something went wrong: we MUST terminate the process. */
385
386         tcpd_warn(error);
387         clean_exit(request);
388     }
389 }
390
391 /* rfc931_option - look up remote user name */
392
393 static void rfc931_option(char *value, struct request_info *request)
394 {
395     int     timeout;
396     char    junk;
397
398     if (value != 0) {
399         if (sscanf(value, "%d%c", &timeout, &junk) != 1 || timeout <= 0)
400             tcpd_jump("bad rfc931 timeout: \"%s\"", value);
401         rfc931_timeout = timeout;
402     }
403     (void) eval_user(request);
404 }
405
406 /* setenv_option - set environment variable */
407
408 /* ARGSUSED */
409
410 static void setenv_option(char *value, struct request_info *request)
411 {
412     char   *var_value;
413
414     if (*(var_value = value + strcspn(value, whitespace)))
415         *var_value++ = 0;
416     if (setenv(chop_string(value), chop_string(var_value), 1))
417         tcpd_jump("memory allocation failure");
418 }
419
420 /* severity_map - lookup facility or severity value */
421
422 static int severity_map(const CODE *table, char *name)
423 {
424     const CODE *t;
425     int ret = -1;
426
427     for (t = table; t->c_name; t++)
428         if (STR_EQ(t->c_name, name)) {
429             ret = t->c_val;
430             break;
431         }
432     if (ret == -1)
433         tcpd_jump("bad syslog facility or severity: \"%s\"", name);
434
435     return (ret);
436 }
437
438 /* severity_option - change logging severity for this event (Dave Mitchell) */
439
440 /* ARGSUSED */
441
442 static void severity_option(char *value, struct request_info *request)
443 {
444     char   *level = split_at(value, '.');
445
446     allow_severity = deny_severity = level ?
447         severity_map(facilitynames, value) | severity_map(prioritynames, level)
448         : severity_map(prioritynames, value);
449 }
450
451 /* get_field - return pointer to next field in string */
452
453 static char *get_field(char *string)
454 {
455     static char *last = "";
456     char   *src;
457     char   *dst;
458     char   *ret;
459     int     ch;
460
461     /*
462      * This function returns pointers to successive fields within a given
463      * string. ":" is the field separator; warn if the rule ends in one. It
464      * replaces a "\:" sequence by ":", without treating the result of
465      * substitution as field terminator. A null argument means resume search
466      * where the previous call terminated. This function destroys its
467      * argument.
468      * 
469      * Work from explicit source or from memory. While processing \: we
470      * overwrite the input. This way we do not have to maintain buffers for
471      * copies of input fields.
472      */
473
474     src = dst = ret = (string ? string : last);
475     if (src[0] == 0)
476         return (0);
477
478     while (ch = *src) {
479         if (ch == ':') {
480             if (*++src == 0)
481                 tcpd_warn("rule ends in \":\"");
482             break;
483         }
484         if (ch == '\\' && src[1] == ':')
485             src++;
486         *dst++ = *src++;
487     }
488     last = src;
489     *dst = 0;
490     return (ret);
491 }
492
493 /* chop_string - strip leading and trailing blanks from string */
494
495 static char *chop_string(register char *string)
496 {
497     char   *start = 0;
498     char   *end;
499     char   *cp;
500
501     for (cp = string; *cp; cp++) {
502         if (!isspace(*cp)) {
503             if (start == 0)
504                 start = cp;
505             end = cp;
506         }
507     }
508     return (start ? (end[1] = 0, start) : cp);
509 }