3 * $Id: fw.c,v 1.16 2003/11/29 20:36:07 mdw Exp $
5 * Port forwarding thingy
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of the `fw' port forwarder.
14 * `fw' is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * `fw' is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with `fw'; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 /*----- Revision history --------------------------------------------------*
32 * Revision 1.16 2003/11/29 20:36:07 mdw
33 * Privileged outgoing connections.
35 * Revision 1.15 2003/11/25 14:46:50 mdw
36 * Update docco for new options.
38 * Revision 1.14 2003/01/24 20:12:40 mdw
39 * Correctly cast uid and gid sentinel values.
41 * Revision 1.13 2002/02/22 23:45:20 mdw
42 * Add option to change the listen(2) parameter. Receive `fw'-specific
45 * Revision 1.12 2002/01/13 14:49:17 mdw
46 * Track @dstr_vputf@ change.
48 * Revision 1.11 2001/02/03 20:33:26 mdw
49 * Fix flags to be unsigned.
51 * Revision 1.10 2001/02/03 20:30:03 mdw
52 * Support re-reading config files on SIGHUP.
54 * Revision 1.9 2001/01/20 11:55:17 mdw
55 * Handle select errors more robustly.
57 * Revision 1.8 2000/03/23 23:19:19 mdw
58 * Fix changed options in parser table.
60 * Revision 1.7 2000/03/23 00:37:33 mdw
61 * Add option to change user and group after initialization. Naughtily
62 * reassign short equivalents of --grammar and --options.
64 * Revision 1.6 1999/12/22 15:44:10 mdw
65 * Make syslog a separate option, and do it better.
67 * Revision 1.5 1999/10/22 22:47:50 mdw
68 * Grammar changes. Also, don't enable SIGINT if it's currently ignored.
70 * Revision 1.4 1999/10/10 16:46:12 mdw
71 * New resolver to initialize. Also, include options for grammar and
74 * Revision 1.3 1999/07/26 23:30:42 mdw
75 * Major reconstruction work for new design.
77 * Revision 1.2 1999/07/03 13:55:17 mdw
78 * Various changes. Add configuration grammar to help text. Change to
79 * root directory and open syslog when forking into background.
81 * Revision 1.1.1.1 1999/07/01 08:56:23 mdw
86 /*----- Header files ------------------------------------------------------*/
106 #include <mLib/bres.h>
107 #include <mLib/dstr.h>
108 #include <mLib/mdwopt.h>
109 #include <mLib/quis.h>
110 #include <mLib/report.h>
111 #include <mLib/sel.h>
112 #include <mLib/sig.h>
113 #include <mLib/sub.h>
121 #include "privconn.h"
126 /*----- Global variables --------------------------------------------------*/
128 sel_state *sel; /* Multiplexor for nonblocking I/O */
130 /*----- Static variables --------------------------------------------------*/
132 typedef struct conffile {
133 struct conffile *next;
137 static unsigned flags = 0; /* Global state flags */
138 static unsigned active = 0; /* Number of active things */
139 static conffile *conffiles = 0; /* List of configuration files */
145 /*----- Configuration parsing ---------------------------------------------*/
149 * Arguments: @scanner *sc@ = pointer to scanner definition
153 * Use: Parses a configuration file from the scanner.
156 static source_ops *sources[] =
157 { &xsource_ops, &fsource_ops, &ssource_ops, 0 };
158 static target_ops *targets[] =
159 { &xtarget_ops, &ftarget_ops, &starget_ops, 0 };
161 void parse(scanner *sc)
166 if (sc->t == CTOK_EOF)
168 if (sc->t != CTOK_WORD)
169 error(sc, "parse error, keyword expected");
171 /* --- Handle a forwarding request --- */
173 if (strcmp(sc->d.buf, "forward") == 0 ||
174 strcmp(sc->d.buf, "fw") == 0 ||
175 strcmp(sc->d.buf, "from") == 0) {
181 /* --- Read a source description --- */
186 /* --- Try to find a source type which understands --- */
189 for (sops = sources; *sops; sops++) {
190 if ((s = (*sops)->read(sc)) != 0)
193 error(sc, "unknown source name `%s'", sc->d.buf);
195 /* --- Read any source-specific options --- */
200 while (sc->t == CTOK_WORD) {
201 if (!s->ops->option || !s->ops->option(s, sc)) {
202 error(sc, "unknown %s source option `%s'",
203 s->ops->name, sc->d.buf);
209 error(sc, "parse error, missing `}'");
214 /* --- Read a destination description --- */
216 if (sc->t == CTOK_WORD && (strcmp(sc->d.buf, "to") == 0 ||
217 strcmp(sc->d.buf, "->") == 0))
223 /* --- Try to find a target which understands --- */
226 for (tops = targets; *tops; tops++) {
227 if ((t = (*tops)->read(sc)) != 0)
230 error(sc, "unknown target name `%s'", sc->d.buf);
232 /* --- Read any target-specific options --- */
237 while (sc->t == CTOK_WORD) {
238 if (!t->ops->option || !t->ops->option(t, sc)) {
239 error(sc, "unknown %s target option `%s'",
240 t->ops->name, sc->d.buf);
246 error(sc, "parse error, `}' expected");
251 /* --- Combine the source and target --- */
253 s->ops->attach(s, sc, t);
258 /* --- Include configuration from a file --- *
260 * Slightly tricky. Scan the optional semicolon from the including
261 * stream, not the included one.
264 else if (strcmp(sc->d.buf, "include") == 0) {
269 conf_name(sc, '/', &d);
270 if ((fp = fopen(d.buf, "r")) == 0)
271 error(sc, "can't include `%s': %s", d.buf, strerror(errno));
275 scan_push(sc, scan_file(fp, d.buf, 0));
278 continue; /* Don't parse a trailing `;' */
281 /* --- Other configuration is handled elsewhere --- */
285 /* --- First try among the sources --- */
290 for (sops = sources; *sops; sops++) {
291 if ((*sops)->option && (*sops)->option(0, sc))
296 /* --- Then try among the targets --- */
301 for (tops = targets; *tops; tops++) {
302 if ((*tops)->option && (*tops)->option(0, sc))
307 /* --- Nobody wants the option --- */
309 error(sc, "unknown global option or prefix `%s'", sc->d.buf);
319 /*----- General utility functions -----------------------------------------*/
321 /* --- @fw_log@ --- *
323 * Arguments: @time_t t@ = when the connection occurred or (@-1@)
324 * @const char *fmt@ = format string to fill in
325 * @...@ = other arguments
329 * Use: Logs a connection.
332 void fw_log(time_t t, const char *fmt, ...)
338 if (flags & FW_QUIET)
345 d.len += strftime(d.buf, d.sz, "%Y-%m-%d %H:%M:%S ", tm);
347 dstr_vputf(&d, fmt, &ap);
349 if (flags & FW_SYSLOG)
350 syslog(LOG_NOTICE, "%s", d.buf);
353 dstr_write(&d, stderr);
358 /* --- @fw_inc@, @fw_dec@ --- *
364 * Use: Increments or decrements the active thing count. `fw' won't
365 * quit while there are active things.
368 void fw_inc(void) { flags |= FW_SET; active++; }
369 void fw_dec(void) { if (active) active--; }
371 /* --- @fw_exit@ --- *
377 * Use: Exits when appropriate.
380 static void fw_exit(void)
386 /* --- @fw_tidy@ --- *
388 * Arguments: @int n@ = signal number
389 * @void *p@ = an uninteresting argument
393 * Use: Handles various signals and causes a clean tidy-up.
396 static void fw_tidy(int n, void *p)
400 case SIGTERM: sn = "SIGTERM"; break;
401 case SIGINT: sn = "SIGINT"; break;
405 fw_log(-1, "closing down gracefully on %s", sn);
409 /* --- @fw_die@ --- *
411 * Arguments: @int n@ = signal number
412 * @void *p@ = an uninteresting argument
416 * Use: Handles various signals and causes an abrupt shutdown.
419 static void fw_die(int n, void *p)
423 case SIGQUIT: sn = "SIGQUIT"; break;
427 fw_log(-1, "closing down abruptly on %s", sn);
432 /* --- @fw_reload@ --- *
434 * Arguments: @int n@ = a signal number
435 * @void *p@ = an uninteresting argument
439 * Use: Handles a hangup signal by re-reading configuration files.
442 static void fw_reload(int n, void *p)
450 fw_log(-1, "no configuration files to reload: ignoring SIGHUP");
453 fw_log(-1, "reloading configuration files...");
456 for (cf = conffiles; cf; cf = cf->next) {
457 if ((fp = fopen(cf->name, "r")) == 0)
458 fw_log(-1, "error loading `%s': %s", cf->name, strerror(errno));
460 scan_add(&sc, scan_file(fp, cf->name, 0));
463 fw_log(-1, "... reload completed OK");
466 /*----- Startup and options parsing ---------------------------------------*/
468 /* --- Standard GNU help options --- */
470 static void version(FILE *fp)
472 pquis(fp, "$ version " VERSION "\n");
475 static void usage(FILE *fp)
477 pquis(fp, "Usage: $ [-dql] [-f file] [config statements...]\n");
480 static void help(FILE *fp)
486 An excessively full-featured port-forwarder, which subsumes large chunks\n\
487 of the functionality of inetd, netcat, and normal cat. Options available\n\
490 -h, --help Display this help message.\n\
491 -v, --version Display the program's version number.\n\
492 -u, --usage Display a terse usage summary.\n\
494 -G, --grammar Show a summary of the configuration language.\n\
495 -O, --options Show a summary of the source and target options.\n\
497 -f, --file=FILE Read configuration from a file.\n\
498 -q, --quiet Don't emit any logging information.\n\
499 -d, --daemon Fork into background after initializing.\n\
500 -l, --syslog Send log output to the system logger.\n\
501 -s, --setuid=USER Change uid to USER after initializing sources.\n\
502 -g, --setgid=GRP Change gid to GRP after initializing sources.\n\
504 Configuration may be supplied in one or more configuration files, or on\n\
505 the command line (or both). If no `-f' option is present, and no\n\
506 configuration is given on the command line, the standard input stream is\n\
509 Configuration is free-form. Comments begin with a `#' character and\n\
510 continue to the end of the line. Each command line argument is considered\n\
511 to be a separate line.\n\
513 The grammar is fairly complicated. For a summary, run `$ --grammar'.\n\
514 For a summary of the various options, run `$ --options'.\n\
518 /* --- Other helpful options --- */
520 static void grammar(FILE *fp)
527 FILE ::= EMPTY | FILE STMT [`;']\n\
528 STMT ::= OPTION-STMT | FW-STMT\n\
529 FW-STMT ::= `fw' SOURCE OPTIONS [`to'|`->'] TARGET OPTIONS\n\
530 OPTIONS ::= `{' OPTION-SEQ `}'\n\
531 OPTION-SEQ ::= EMPTY | OPTION-STMT [`;'] OPTION-SEQ\n\
534 OPTION-STMT ::= Q-OPTION\n\
535 Q-OPTION ::= OPTION\n\
536 | PREFIX `.' Q-OPTION\n\
537 | PREFIX `{' OPTION-SEQ `}'\n\
540 File source and target\n\
543 FILE ::= `file' [`.'] FSPEC [`,' FSPEC]\n\
544 FSPEC ::= FD-SPEC | NAME-SPEC | NULL-SPEC\n\
545 FD-SPEC ::= [[`:']`fd'[`:']] NUMBER|`stdin'|`stdout'\n\
546 NAME-SPEC ::= [[`:']`file'[`:']] FILE-NAME\n\
547 FILE-NAME ::= PATH-SEQ | [ PATH-SEQ ]\n\
548 PATH-SEQ ::= PATH-ELT | PATH-SEQ PATH-ELT\n\
549 PATH-ELT ::= `/' | WORD\n\
550 NULL-SPEC ::= [`:']`null'[`:']\n\
552 Exec source and target\n\
555 EXEC ::= `exec' [`.'] CMD-SPEC\n\
556 CMD-SPEC ::= SHELL-CMD | [PROG-NAME] `[' ARGV0 ARG-SEQ `]'\n\
557 ARG-SEQ ::= WORD | ARG-SEQ WORD\n\
558 SHELL-CMD ::= WORD\n\
561 Socket source and target\n\
562 SOURCE ::= SOCKET-SOURCE\n\
563 TARGET ::= SOCKET-TARGET\n\
564 SOCKET-SOURCE ::= [`socket'[`.']] [[`:']ADDR-TYPE[`:']] SOURCE-ADDR\n\
565 SOCKET-TARGET ::= [`socket'[`.']] [[`:']ADDR-TYPE[`:']] TARGET-ADDR\n\
567 INET-SOURCE-ADDR ::= [`port'] PORT\n\
568 INET-TARGET-ADDR ::= ADDRESS [`:'] PORT\n\
569 ADDRESS ::= ADDR-ELT | ADDRESS ADDR-ELT\n\
570 ADDR-ELT ::= `.' | WORD\n\
572 UNIX-SOURCE-ADDR ::= FILE-NAME\n\
573 UNIX-TARGET-ADDR ::= FILE-NAME\n\
577 static void options(FILE *fp)
583 File attributes (`fattr')\n\
584 prefix.FATTR.MODE [=] MODE\n\
585 prefix.FATTR.OWNER [=] USER\n\
586 prefix.FATTR.GROUP [=] GROUP\n\
589 file.create [=] yes|no\n\
590 file.open [=] no|truncate|append\n\
594 exec.logging [=] yes|no\n\
595 exec.dir [=] FILE-NAME\n\
596 exec.root [=] FILE-NAME\n\
597 exec.user [=] USER\n\
598 exec.group [=] GROUP\n\
599 exec.rlimit.LIMIT[.hard|.soft] [=] VALUE\n\
601 exec.env.unset VAR\n\
602 exec.env.[set] VAR [=] VALUE\n\
605 socket.conn [=] NUMBER|unlimited|one-shot\n\
606 socket.listen [=] NUMBER\n\
607 socket.logging [=] yes|no\n\
609 socket.inet.source.[allow|deny] [host] ADDR [/ ADDR]\n\
610 socket.inet.source.[allow|deny] priv-port\n\
611 socket.inet.source.addr [=] any|ADDR\n\
612 socket.inet.dest.addr [=] any|ADDR\n\
613 socket.inet.dest.priv-port [=] yes|no\n\
615 socket.unix.fattr.*\n\
621 * Arguments: @int argc@ = number of command line arguments
622 * @char *argv[]@ = vector of argument strings
626 * Use: Simple port-forwarding server.
629 int main(int argc, char *argv[])
633 sig s_term, s_quit, s_int, s_hup;
637 conffile *cf, **cff = &conffiles;
644 /* --- Initialize things --- */
654 fattr_init(&fattr_global);
659 /* --- Parse command line options --- */
662 static struct option opts[] = {
664 /* --- Standard GNU help options --- */
666 { "help", 0, 0, 'h' },
667 { "version", 0, 0, 'v' },
668 { "usage", 0, 0, 'u' },
670 /* --- Other help options --- */
672 { "grammar", 0, 0, 'G' },
673 { "options", 0, 0, 'O' },
675 /* --- Other useful arguments --- */
677 { "file", OPTF_ARGREQ, 0, 'f' },
678 { "fork", 0, 0, 'd' },
679 { "daemon", 0, 0, 'd' },
680 { "syslog", 0, 0, 'l' },
681 { "log", 0, 0, 'l' },
682 { "quiet", 0, 0, 'q' },
683 { "setuid", OPTF_ARGREQ, 0, 's' },
684 { "uid", OPTF_ARGREQ, 0, 's' },
685 { "setgid", OPTF_ARGREQ, 0, 'g' },
686 { "gid", OPTF_ARGREQ, 0, 'g' },
688 /* --- Magic terminator --- */
692 int i = mdwopt(argc, argv, "+hvu GO f:dls:g:", opts, 0, 0, 0);
718 if (strcmp(optarg, "-") == 0)
719 scan_add(&sc, scan_file(stdin, "<stdin>", SCF_NOCLOSE));
722 if ((fp = fopen(optarg, "r")) == 0)
723 die(1, "couldn't open file `%s': %s", optarg, strerror(errno));
724 cf = CREATE(conffile);
728 scan_add(&sc, scan_file(fp, optarg, 0));
742 if (isdigit((unsigned char )optarg[0])) {
744 drop = strtol(optarg, &q, 0);
746 die(1, "bad uid `%s'", optarg);
748 struct passwd *pw = getpwnam(optarg);
750 die(1, "unknown user `%s'", optarg);
755 if (isdigit((unsigned char )optarg[0])) {
757 dropg = strtol(optarg, &q, 0);
759 die(1, "bad gid `%s'", optarg);
761 struct group *gr = getgrnam(optarg);
763 die(1, "unknown group `%s'", optarg);
779 /* --- Deal with the remaining arguments --- */
782 scan_add(&sc, scan_argv(argv + optind));
785 else if (!isatty(STDIN_FILENO))
786 scan_add(&sc, scan_file(stdin, "<stdin>", SCF_NOCLOSE));
788 moan("no configuration given and stdin is a terminal.");
789 moan("type `%s --help' for usage information.", QUIS);
793 /* --- Parse the configuration now gathered --- */
797 /* --- Set up some signal handlers --- *
799 * Don't enable @SIGINT@ if the caller already disabled it.
805 sig_add(&s_term, SIGTERM, fw_tidy, 0);
806 sig_add(&s_quit, SIGQUIT, fw_die, 0);
807 sigaction(SIGINT, 0, &sa);
808 if (sa.sa_handler != SIG_IGN)
809 sig_add(&s_int, SIGINT, fw_tidy, 0);
810 sig_add(&s_hup, SIGHUP, fw_reload, 0);
813 /* --- Drop privileges --- */
815 if (drop != (uid_t)-1)
817 #ifdef HAVE_SETGROUPS
818 if ((dropg != (gid_t)-1 && (setgid(dropg) || setgroups(1, &dropg))) ||
819 (drop != (uid_t)-1 && setuid(drop)))
820 die(1, "couldn't drop privileges: %s", strerror(errno));
822 if ((dropg != (gid_t)-1 && setgid(dropg)) ||
823 (drop != (uid_t)-1 && setuid(drop)))
824 die(1, "couldn't drop privileges: %s", strerror(errno));
827 /* --- Fork into the background --- */
834 die(1, "couldn't fork: %s", strerror(errno));
838 close(0); close(1); close(2);
849 openlog(QUIS, 0, LOG_DAEMON);
852 /* --- Let rip --- */
854 if (!(flags & FW_SET))
855 moan("nothing to do!");
856 signal(SIGPIPE, SIG_IGN);
861 if (!sel_select(sel))
863 else if (errno != EINTR && errno != EAGAIN) {
864 fw_log(-1, "error from select: %s", strerror(errno));
867 fw_log(-1, "too many consecutive select errors: bailing out");
877 /*----- That's all, folks -------------------------------------------------*/