1 /* $OpenBSD: authpf.c,v 1.75 2004/01/29 01:55:10 deraadt Exp $ */
2 /* $DragonFly: src/usr.sbin/authpf/authpf.c,v 1.1 2004/09/21 21:25:28 joerg Exp $ */
5 * Copyright (C) 1998 - 2002 Bob Beck (beck@openbsd.org).
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/param.h>
30 #include <sys/types.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
37 #include <net/pf/pfvar.h>
38 #include <arpa/inet.h>
50 #include "pfctl_parser.h"
53 #include "pathnames.h"
55 #define __dead __dead2
57 extern int symset(const char *, const char *, int);
59 static int read_config(FILE *);
60 static void print_message(const char *);
61 static int allowed_luser(const char *);
62 static int check_luser(const char *, const char *);
63 static int remove_stale_rulesets(void);
64 static int change_filter(int, const char *, const char *);
65 static void authpf_kill_states(void);
67 int dev_fd; /* pf device */
68 char anchorname[PF_ANCHOR_NAME_SIZE] = "authpf";
69 char rulesetname[PF_RULESET_NAME_SIZE];
72 char *infile; /* file name printed by yyerror() in parse.y */
73 char luser[MAXLOGNAME]; /* username */
74 char ipsrc[256]; /* ip as a string */
75 char pidfile[MAXPATHLEN]; /* we save pid in this file. */
77 struct timeval Tstart, Tend; /* start and end times of session */
79 volatile sig_atomic_t want_death;
80 static void need_death(int signo);
81 static __dead void do_death(int);
84 * User shell for authenticating gateways. Sole purpose is to allow
85 * a user to ssh to a gateway, and have the gateway modify packet
86 * filters to allow access, then remove access when the user finishes
87 * up. Meant to be used only from ssh(1) connections.
90 main(int argc __unused, char **argv __unused)
92 int lockcnt = 0, n, pidfd;
99 config = fopen(PATH_CONFFILE, "r");
101 if ((cp = getenv("SSH_TTY")) == NULL) {
102 syslog(LOG_ERR, "non-interactive session connection for authpf");
106 if ((cp = getenv("SSH_CLIENT")) == NULL) {
107 syslog(LOG_ERR, "cannot determine connection source");
111 if (strlcpy(ipsrc, cp, sizeof(ipsrc)) >= sizeof(ipsrc)) {
112 syslog(LOG_ERR, "SSH_CLIENT variable too long");
115 cp = strchr(ipsrc, ' ');
117 syslog(LOG_ERR, "corrupt SSH_CLIENT variable %s", ipsrc);
121 if (inet_pton(AF_INET, ipsrc, &ina) != 1) {
123 "cannot determine IP from SSH_CLIENT %s", ipsrc);
126 /* open the pf device */
127 dev_fd = open(PATH_DEVFILE, O_RDWR);
129 syslog(LOG_ERR, "cannot open packet filter device (%m)");
136 syslog(LOG_ERR, "cannot find user for uid %u", uid);
139 if (strcmp(pw->pw_shell, PATH_AUTHPF_SHELL)) {
140 syslog(LOG_ERR, "wrong shell for user %s, uid %u",
141 pw->pw_name, pw->pw_uid);
146 * Paranoia, but this data _does_ come from outside authpf, and
147 * truncation would be bad.
149 if (strlcpy(luser, pw->pw_name, sizeof(luser)) >= sizeof(luser)) {
150 syslog(LOG_ERR, "username too long: %s", pw->pw_name);
154 if ((n = snprintf(rulesetname, sizeof(rulesetname), "%s(%ld)",
155 luser, (long)getpid())) < 0 || n >= (int)sizeof(rulesetname)) {
156 syslog(LOG_INFO, "%s(%ld) too large, ruleset name will be %ld",
157 luser, (long)getpid(), (long)getpid());
158 if ((n = snprintf(rulesetname, sizeof(rulesetname), "%ld",
159 (long)getpid())) < 0 || n >= (int)sizeof(rulesetname)) {
160 syslog(LOG_ERR, "pid too large for ruleset name");
166 /* Make our entry in /var/authpf as /var/authpf/ipaddr */
167 n = snprintf(pidfile, sizeof(pidfile), "%s/%s", PATH_PIDFILE, ipsrc);
168 if (n < 0 || (u_int)n >= sizeof(pidfile)) {
169 syslog(LOG_ERR, "path to pidfile too long");
174 * If someone else is already using this ip, then this person
175 * wants to switch users - so kill the old process and exit
178 * Note, we could print a message and tell them to log out, but the
179 * usual case of this is that someone has left themselves logged in,
180 * with the authenticated connection iconized and someone else walks
181 * up to use and automatically logs in before using. If this just
182 * gets rid of the old one silently, the new user never knows they
183 * could have used someone else's old authentication. If we
184 * tell them to log out before switching users it is an invitation
189 int save_errno, otherpid = -1;
190 char otherluser[MAXLOGNAME];
192 if ((pidfd = open(pidfile, O_RDWR|O_CREAT, 0644)) == -1 ||
193 (pidfp = fdopen(pidfd, "r+")) == NULL) {
196 syslog(LOG_ERR, "cannot open or create %s: %s", pidfile,
201 if (flock(fileno(pidfp), LOCK_EX|LOCK_NB) == 0)
205 /* Mark our pid, and username to our file. */
208 /* 31 == MAXLOGNAME - 1 */
209 if (fscanf(pidfp, "%d\n%31s\n", &otherpid, otherluser) != 2)
211 syslog(LOG_DEBUG, "tried to lock %s, in use by pid %d: %s",
212 pidfile, otherpid, strerror(save_errno));
216 "killing prior auth (pid %d) of %s by user %s",
217 otherpid, ipsrc, otherluser);
218 if (kill((pid_t) otherpid, SIGTERM) == -1) {
220 "could not kill process %d: (%m)",
226 * we try to kill the previous process and acquire the lock
227 * for 10 seconds, trying once a second. if we can't after
228 * 10 attempts we log an error and give up
230 if (++lockcnt > 10) {
231 syslog(LOG_ERR, "cannot kill previous authpf (pid %d)",
237 /* re-open, and try again. The previous authpf process
238 * we killed above should unlink the file and release
239 * it's lock, giving us a chance to get it now
248 openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);
250 if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(luser)) {
251 syslog(LOG_INFO, "user %s prohibited", luser);
255 if (config == NULL || read_config(config)) {
256 syslog(LOG_INFO, "bad or nonexistent %s", PATH_CONFFILE);
260 if (remove_stale_rulesets()) {
261 syslog(LOG_INFO, "error removing stale rulesets");
265 /* We appear to be making headway, so actually mark our pid */
267 fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
269 (void) ftruncate(fileno(pidfp), ftell(pidfp));
271 if (change_filter(1, luser, ipsrc) == -1) {
272 printf("Unable to modify filters\r\n");
276 signal(SIGTERM, need_death);
277 signal(SIGINT, need_death);
278 signal(SIGALRM, need_death);
279 signal(SIGPIPE, need_death);
280 signal(SIGHUP, need_death);
281 signal(SIGSTOP, need_death);
282 signal(SIGTSTP, need_death);
284 printf("\r\nHello %s, ", luser);
285 printf("You are authenticated from host \"%s\"\r\n", ipsrc);
286 setproctitle("%s@%s", luser, ipsrc);
287 print_message(PATH_MESSAGE);
297 printf("\r\n\r\nSorry, this service is currently unavailable due to ");
298 printf("technical difficulties\r\n\r\n");
299 print_message(PATH_PROBLEM);
300 printf("\r\nYour authentication process (pid %ld) was unable to run\n",
302 sleep(180); /* them lusers read reaaaaal slow */
308 * reads config file in PATH_CONFFILE to set optional behaviours up
318 char *pair[4], *cp, *tp;
321 if (fgets(buf, sizeof(buf), f) == NULL) {
327 if (buf[len - 1] != '\n' && !feof(f)) {
328 syslog(LOG_ERR, "line %d too long in %s", i,
334 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
337 if (!*cp || *cp == '#' || *cp == '\n')
340 for (ap = pair; ap < &pair[3] &&
341 (*ap = strsep(&cp, "=")) != NULL; ) {
348 tp = pair[1] + strlen(pair[1]);
349 while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
352 if (strcasecmp(pair[0], "anchor") == 0) {
353 if (!pair[1][0] || strlcpy(anchorname, pair[1],
354 sizeof(anchorname)) >= sizeof(anchorname))
357 } while (!feof(f) && !ferror(f));
363 syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
369 * splatter a file to stdout - max line length of 1024,
370 * used for spitting message files at users to tell them
371 * they've been bad or we're unavailable.
374 print_message(const char *filename)
379 if ((f = fopen(filename, "r")) == NULL)
380 return; /* fail silently, we don't care if it isn't there */
383 if (fgets(buf, sizeof(buf), f) == NULL) {
388 } while (fputs(buf, stdout) != EOF && !feof(f));
394 * allowed_luser checks to see if user "luser" is allowed to
395 * use this gateway by virtue of being listed in an allowed
396 * users file, namely /etc/authpf/authpf.allow .
398 * If /etc/authpf/authpf.allow does not exist, then we assume that
399 * all users who are allowed in by sshd(8) are permitted to
400 * use this gateway. If /etc/authpf/authpf.allow does exist, then a
401 * user must be listed if the connection is to continue, else
402 * the session terminates in the same manner as being banned.
405 allowed_luser(const char *user)
412 if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
413 if (errno == ENOENT) {
415 * allowfile doesn't exist, thus this gateway
416 * isn't restricted to certain users...
422 * user may in fact be allowed, but we can't open
423 * the file even though it's there. probably a config
426 syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
427 PATH_ALLOWFILE, strerror(errno));
431 * /etc/authpf/authpf.allow exists, thus we do a linear
432 * search to see if they are allowed.
433 * also, if username "*" exists, then this is a
434 * "public" gateway, such as it is, so let
438 while ((buf = fgetln(f, &len))) {
439 if (buf[len - 1] == '\n')
442 if ((lbuf = (char *)malloc(len + 1)) == NULL)
444 memcpy(lbuf, buf, len);
449 matched = strcmp(user, buf) == 0 || strcmp("*", buf) == 0;
457 return (1); /* matched an allowed username */
459 syslog(LOG_INFO, "denied access to %s: not listed in %s",
460 user, PATH_ALLOWFILE);
462 fputs("\n\nSorry, you are not allowed to use this facility!\n",
470 * check_luser checks to see if user "luser" has been banned
471 * from using us by virtue of having an file of the same name
472 * in the "luserdir" directory.
474 * If the user has been banned, we copy the contents of the file
475 * to the user's screen. (useful for telling the user what to
476 * do to get un-banned, or just to tell them they aren't
477 * going to be un-banned.)
480 check_luser(const char *userdir, const char *user)
484 char tmp[MAXPATHLEN];
486 n = snprintf(tmp, sizeof(tmp), "%s/%s", userdir, user);
487 if (n < 0 || (u_int)n >= sizeof(tmp)) {
488 syslog(LOG_ERR, "provided banned directory line too long (%s)",
492 if ((f = fopen(tmp, "r")) == NULL) {
493 if (errno == ENOENT) {
495 * file or dir doesn't exist, so therefore
496 * this luser isn't banned.. all is well
501 * user may in fact be banned, but we can't open the
502 * file even though it's there. probably a config
505 syslog(LOG_ERR, "cannot open banned file %s (%s)",
506 tmp, strerror(errno));
511 * user is banned - spit the file at them to
512 * tell what they can do and where they can go.
514 syslog(LOG_INFO, "denied access to %s: %s exists",
518 strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
520 while (fputs(tmp, stdout) != EOF && !feof(f)) {
521 if (fgets(tmp, sizeof(tmp), f) == NULL) {
532 * Search for rulesets left by other authpf processes (either because they
533 * died ungracefully or were terminated) and remove them.
536 remove_stale_rulesets(void)
538 struct pfioc_ruleset prs;
539 const int action[PF_RULESET_MAX] = { PF_SCRUB,
540 PF_PASS, PF_NAT, PF_BINAT, PF_RDR };
543 memset(&prs, 0, sizeof(prs));
544 strlcpy(prs.anchor, anchorname, sizeof(prs.anchor));
545 if (ioctl(dev_fd, DIOCGETRULESETS, &prs)) {
559 if (ioctl(dev_fd, DIOCGETRULESET, &prs))
562 if ((t = strchr(prs.name, '(')) == NULL)
566 pid = strtoul(t, &s, 10);
567 if (!prs.name[0] || errno ||
568 (*s && (t == prs.name || *s != ')')))
570 if (kill(pid, 0) && errno != EPERM) {
573 for (i = 0; i < PF_RULESET_MAX; ++i) {
574 struct pfioc_rule pr;
576 memset(&pr, 0, sizeof(pr));
577 memcpy(pr.anchor, prs.anchor, sizeof(pr.anchor));
578 memcpy(pr.ruleset, prs.name, sizeof(pr.ruleset));
579 pr.rule.action = action[i];
580 if ((ioctl(dev_fd, DIOCBEGINRULES, &pr) ||
581 ioctl(dev_fd, DIOCCOMMITRULES, &pr)) &&
593 * Add/remove filter entries for user "luser" from ip "ipsrc"
596 change_filter(int add, const char *user, const char *his_ipsrc)
604 if (user == NULL || !user[0] || his_ipsrc == NULL || !his_ipsrc[0]) {
605 syslog(LOG_ERR, "invalid luser/ipsrc");
610 if ((i = snprintf(fn, sizeof(fn), "%s/%s/authpf.rules",
611 PATH_USER_DIR, user)) < 0 || i >= (int)sizeof(fn)) {
612 syslog(LOG_ERR, "user rule path too long");
615 if ((f = fopen(fn, "r")) == NULL && errno != ENOENT) {
616 syslog(LOG_ERR, "cannot open %s (%m)", fn);
620 if (strlcpy(fn, PATH_PFRULES, sizeof(fn)) >=
622 syslog(LOG_ERR, "rule path too long");
625 if ((f = fopen(fn, "r")) == NULL) {
626 syslog(LOG_ERR, "cannot open %s (%m)", fn);
632 if (pfctl_load_fingerprints(dev_fd, 0)) {
633 syslog(LOG_ERR, "unable to load kernel's OS fingerprints");
636 bzero(&t, sizeof(t));
637 t.pfrb_type = PFRB_TRANS;
638 memset(&pf, 0, sizeof(pf));
639 for (i = 0; i < PF_RULESET_MAX; ++i) {
640 if (pfctl_add_trans(&t, i, anchorname, rulesetname)) {
641 syslog(LOG_ERR, "pfctl_add_trans %m");
645 if (pfctl_trans(dev_fd, &t, DIOCXBEGIN, 0)) {
646 syslog(LOG_ERR, "DIOCXBEGIN (%s) %m", add?"add":"remove");
651 if (symset("user_ip", his_ipsrc, 0) ||
652 symset("user_id", user, 0)) {
653 syslog(LOG_ERR, "symset");
659 pf.anchor = anchorname;
660 pf.ruleset = rulesetname;
663 if (parse_rules(f, &pf) < 0) {
664 syslog(LOG_ERR, "syntax error in rule file: "
665 "authpf rules not loaded");
674 if (pfctl_trans(dev_fd, &t, DIOCXCOMMIT, 0)) {
675 syslog(LOG_ERR, "DIOCXCOMMIT (%s) %m", add?"add":"remove");
680 gettimeofday(&Tstart, NULL);
681 syslog(LOG_INFO, "allowing %s, user %s", his_ipsrc, user);
683 gettimeofday(&Tend, NULL);
684 syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
685 his_ipsrc, user, Tend.tv_sec - Tstart.tv_sec);
692 if (pfctl_trans(dev_fd, &t, DIOCXROLLBACK, 0))
693 syslog(LOG_ERR, "DIOCXROLLBACK (%s) %m", add?"add":"remove");
700 * This is to kill off states that would otherwise be left behind stateful
701 * rules. This means we don't need to allow in more traffic than we really
702 * want to, since we don't have to worry about any luser sessions lasting
703 * longer than their ssh session. This function is based on
704 * pfctl_kill_states from pfctl.
707 authpf_kill_states(void)
709 struct pfioc_state_kill psk;
710 struct in_addr target;
712 memset(&psk, 0, sizeof(psk));
713 psk.psk_af = AF_INET;
715 inet_pton(AF_INET, ipsrc, &target);
717 /* Kill all states from ipsrc */
718 psk.psk_src.addr.v.a.addr.v4 = target;
719 memset(&psk.psk_src.addr.v.a.mask, 0xff,
720 sizeof(psk.psk_src.addr.v.a.mask));
721 if (ioctl(dev_fd, DIOCKILLSTATES, &psk))
722 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
724 /* Kill all states to ipsrc */
725 psk.psk_af = AF_INET;
726 memset(&psk.psk_src, 0, sizeof(psk.psk_src));
727 psk.psk_dst.addr.v.a.addr.v4 = target;
728 memset(&psk.psk_dst.addr.v.a.mask, 0xff,
729 sizeof(psk.psk_dst.addr.v.a.mask));
730 if (ioctl(dev_fd, DIOCKILLSTATES, &psk))
731 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
734 /* signal handler that makes us go away properly */
736 need_death(int signo __unused)
742 * function that removes our stuff when we go away.
750 change_filter(0, luser, ipsrc);
751 authpf_kill_states();
752 remove_stale_rulesets();
755 ftruncate(fileno(pidfp), 0);
757 if (unlink(pidfile) == -1)
758 syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);
763 * callbacks for parse_rules(void)
767 pfctl_add_rule(struct pfctl *pf, struct pf_rule *r)
770 struct pfioc_rule pr;
775 rs_num = PF_RULESET_FILTER;
778 rs_num = PF_RULESET_SCRUB;
782 rs_num = PF_RULESET_NAT;
786 rs_num = PF_RULESET_RDR;
790 rs_num = PF_RULESET_BINAT;
793 syslog(LOG_ERR, "invalid rule action %d", r->action);
797 bzero(&pr, sizeof(pr));
798 strlcpy(pr.anchor, pf->anchor, sizeof(pr.anchor));
799 strlcpy(pr.ruleset, pf->ruleset, sizeof(pr.ruleset));
800 if (pfctl_add_pool(pf, &r->rpool, r->af))
802 pr.ticket = pfctl_get_ticket(pf->trans, rs_num, pf->anchor,
804 pr.pool_ticket = pf->paddr.ticket;
805 memcpy(&pr.rule, r, sizeof(pr.rule));
806 if (ioctl(pf->dev, DIOCADDRULE, &pr)) {
807 syslog(LOG_ERR, "DIOCADDRULE %m");
810 pfctl_clear_pool(&r->rpool);
815 pfctl_add_pool(struct pfctl *pf, struct pf_pool *p, sa_family_t af)
817 struct pf_pooladdr *pa;
819 if (ioctl(pf->dev, DIOCBEGINADDRS, &pf->paddr)) {
820 syslog(LOG_ERR, "DIOCBEGINADDRS %m");
824 TAILQ_FOREACH(pa, &p->list, entries) {
825 memcpy(&pf->paddr.addr, pa, sizeof(struct pf_pooladdr));
826 if (ioctl(pf->dev, DIOCADDADDR, &pf->paddr)) {
827 syslog(LOG_ERR, "DIOCADDADDR %m");
835 pfctl_clear_pool(struct pf_pool *pool)
837 struct pf_pooladdr *pa;
839 while ((pa = TAILQ_FIRST(&pool->list)) != NULL) {
840 TAILQ_REMOVE(&pool->list, pa, entries);
846 pfctl_add_altq(struct pfctl *pf __unused, struct pf_altq *a __unused)
848 fprintf(stderr, "altq rules not supported in authpf\n");
853 pfctl_set_optimization(struct pfctl *pf __unused, const char *opt __unused)
855 fprintf(stderr, "set optimization not supported in authpf\n");
860 pfctl_set_logif(struct pfctl *pf __unused, char *ifname __unused)
862 fprintf(stderr, "set loginterface not supported in authpf\n");
867 pfctl_set_hostid(struct pfctl *pf __unused, u_int32_t hostid __unused)
869 fprintf(stderr, "set hostid not supported in authpf\n");
874 pfctl_set_timeout(struct pfctl *pf __unused, const char *opt __unused,
875 int seconds __unused, int quiet __unused)
877 fprintf(stderr, "set timeout not supported in authpf\n");
882 pfctl_set_limit(struct pfctl *pf __unused, const char *opt __unused,
883 unsigned int limit __unused)
885 fprintf(stderr, "set limit not supported in authpf\n");
890 pfctl_set_debug(struct pfctl *pf __unused, char *d __unused)
892 fprintf(stderr, "set debug not supported in authpf\n");
897 pfctl_define_table(char *name __unused, int flags __unused, int addrs __unused,
898 const char *anchor __unused, const char *ruleset __unused,
899 struct pfr_buffer *ab __unused, u_int32_t ticket __unused)
901 fprintf(stderr, "table definitions not yet supported in authpf\n");
906 pfctl_rules(int dev __unused, char *filename __unused, int opts __unused,
907 char *my_anchorname __unused, char *my_rulesetname __unused,
908 struct pfr_buffer *t __unused)
910 /* never called, no anchors inside anchors, but we need the stub */
911 fprintf(stderr, "load anchor not supported from authpf\n");
916 pfctl_print_title(const char *title __unused)