1 /* $OpenBSD: authpf.c,v 1.104 2007/02/24 17:35:08 beck Exp $ */
4 * Copyright (C) 1998 - 2007 Bob Beck (beck@openbsd.org).
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 #include <sys/cdefs.h>
20 __FBSDID("$FreeBSD$");
22 #include <sys/param.h>
24 #include <sys/ioctl.h>
25 #include <sys/socket.h>
31 #include <net/pfvar.h>
32 #include <arpa/inet.h>
39 #include <login_cap.h>
48 #include "pathnames.h"
50 static int read_config(FILE *);
51 static void print_message(char *);
52 static int allowed_luser(char *);
53 static int check_luser(char *, char *);
54 static int remove_stale_rulesets(void);
55 static int change_filter(int, const char *, const char *);
56 static int change_table(int, const char *);
57 static void authpf_kill_states(void);
59 int dev; /* pf device */
60 char anchorname[PF_ANCHOR_NAME_SIZE] = "authpf";
61 char rulesetname[MAXPATHLEN - PF_ANCHOR_NAME_SIZE - 2];
62 char tablename[PF_TABLE_NAME_SIZE] = "authpf_users";
65 char luser[MAXLOGNAME]; /* username */
66 char ipsrc[256]; /* ip as a string */
67 char pidfile[MAXPATHLEN]; /* we save pid in this file. */
69 struct timeval Tstart, Tend; /* start and end times of session */
71 volatile sig_atomic_t want_death;
72 static void need_death(int signo);
74 static __dead2 void do_death(int);
76 static __dead void do_death(int);
80 * User shell for authenticating gateways. Sole purpose is to allow
81 * a user to ssh to a gateway, and have the gateway modify packet
82 * filters to allow access, then remove access when the user finishes
83 * up. Meant to be used only from ssh(1) connections.
86 main(int argc, char *argv[])
88 int lockcnt = 0, n, pidfd;
98 config = fopen(PATH_CONFFILE, "r");
100 syslog(LOG_ERR, "can not open %s (%m)", PATH_CONFFILE);
104 if ((cp = getenv("SSH_TTY")) == NULL) {
105 syslog(LOG_ERR, "non-interactive session connection for authpf");
109 if ((cp = getenv("SSH_CLIENT")) == NULL) {
110 syslog(LOG_ERR, "cannot determine connection source");
114 if (strlcpy(ipsrc, cp, sizeof(ipsrc)) >= sizeof(ipsrc)) {
115 syslog(LOG_ERR, "SSH_CLIENT variable too long");
118 cp = strchr(ipsrc, ' ');
120 syslog(LOG_ERR, "corrupt SSH_CLIENT variable %s", ipsrc);
124 if (inet_pton(AF_INET, ipsrc, &ina) != 1 &&
125 inet_pton(AF_INET6, ipsrc, &ina) != 1) {
127 "cannot determine IP from SSH_CLIENT %s", ipsrc);
130 /* open the pf device */
131 dev = open(PATH_DEVFILE, O_RDWR);
133 syslog(LOG_ERR, "cannot open packet filter device (%m)");
140 syslog(LOG_ERR, "cannot find user for uid %u", uid);
144 if ((lc = login_getclass(pw->pw_class)) != NULL)
145 shell = (char *)login_getcapstr(lc, "shell", pw->pw_shell,
148 shell = pw->pw_shell;
152 if (strcmp(shell, PATH_AUTHPF_SHELL)) {
153 syslog(LOG_ERR, "wrong shell for user %s, uid %u",
154 pw->pw_name, pw->pw_uid);
155 if (shell != pw->pw_shell)
160 if (shell != pw->pw_shell)
164 * Paranoia, but this data _does_ come from outside authpf, and
165 * truncation would be bad.
167 if (strlcpy(luser, pw->pw_name, sizeof(luser)) >= sizeof(luser)) {
168 syslog(LOG_ERR, "username too long: %s", pw->pw_name);
172 if ((n = snprintf(rulesetname, sizeof(rulesetname), "%s(%ld)",
173 luser, (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
174 syslog(LOG_INFO, "%s(%ld) too large, ruleset name will be %ld",
175 luser, (long)getpid(), (long)getpid());
176 if ((n = snprintf(rulesetname, sizeof(rulesetname), "%ld",
177 (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
178 syslog(LOG_ERR, "pid too large for ruleset name");
184 /* Make our entry in /var/authpf as /var/authpf/ipaddr */
185 n = snprintf(pidfile, sizeof(pidfile), "%s/%s", PATH_PIDFILE, ipsrc);
186 if (n < 0 || (u_int)n >= sizeof(pidfile)) {
187 syslog(LOG_ERR, "path to pidfile too long");
192 * If someone else is already using this ip, then this person
193 * wants to switch users - so kill the old process and exit
196 * Note, we could print a message and tell them to log out, but the
197 * usual case of this is that someone has left themselves logged in,
198 * with the authenticated connection iconized and someone else walks
199 * up to use and automatically logs in before using. If this just
200 * gets rid of the old one silently, the new user never knows they
201 * could have used someone else's old authentication. If we
202 * tell them to log out before switching users it is an invitation
207 int save_errno, otherpid = -1;
208 char otherluser[MAXLOGNAME];
210 if ((pidfd = open(pidfile, O_RDWR|O_CREAT, 0644)) == -1 ||
211 (pidfp = fdopen(pidfd, "r+")) == NULL) {
214 syslog(LOG_ERR, "cannot open or create %s: %s", pidfile,
219 if (flock(fileno(pidfp), LOCK_EX|LOCK_NB) == 0)
223 /* Mark our pid, and username to our file. */
226 /* 31 == MAXLOGNAME - 1 */
227 if (fscanf(pidfp, "%d\n%31s\n", &otherpid, otherluser) != 2)
229 syslog(LOG_DEBUG, "tried to lock %s, in use by pid %d: %s",
230 pidfile, otherpid, strerror(save_errno));
234 "killing prior auth (pid %d) of %s by user %s",
235 otherpid, ipsrc, otherluser);
236 if (kill((pid_t) otherpid, SIGTERM) == -1) {
238 "could not kill process %d: (%m)",
244 * we try to kill the previous process and acquire the lock
245 * for 10 seconds, trying once a second. if we can't after
246 * 10 attempts we log an error and give up
248 if (++lockcnt > 10) {
249 syslog(LOG_ERR, "cannot kill previous authpf (pid %d)",
257 /* re-open, and try again. The previous authpf process
258 * we killed above should unlink the file and release
259 * it's lock, giving us a chance to get it now
265 /* whack the group list */
267 if (setgroups(1, &gid) == -1) {
268 syslog(LOG_INFO, "setgroups: %s", strerror(errno));
274 if (setresuid(uid, uid, uid) == -1) {
275 syslog(LOG_INFO, "setresuid: %s", strerror(errno));
278 openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);
280 if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(luser)) {
281 syslog(LOG_INFO, "user %s prohibited", luser);
285 if (read_config(config)) {
286 syslog(LOG_ERR, "invalid config file %s", PATH_CONFFILE);
290 if (remove_stale_rulesets()) {
291 syslog(LOG_INFO, "error removing stale rulesets");
295 /* We appear to be making headway, so actually mark our pid */
297 fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
299 (void) ftruncate(fileno(pidfp), ftello(pidfp));
301 if (change_filter(1, luser, ipsrc) == -1) {
302 printf("Unable to modify filters\r\n");
305 if (change_table(1, ipsrc) == -1) {
306 printf("Unable to modify table\r\n");
307 change_filter(0, luser, ipsrc);
311 signal(SIGTERM, need_death);
312 signal(SIGINT, need_death);
313 signal(SIGALRM, need_death);
314 signal(SIGPIPE, need_death);
315 signal(SIGHUP, need_death);
316 signal(SIGQUIT, need_death);
317 signal(SIGTSTP, need_death);
319 printf("\r\nHello %s. ", luser);
320 printf("You are authenticated from host \"%s\"\r\n", ipsrc);
321 setproctitle("%s@%s", luser, ipsrc);
322 print_message(PATH_MESSAGE);
332 printf("\r\n\r\nSorry, this service is currently unavailable due to ");
333 printf("technical difficulties\r\n\r\n");
334 print_message(PATH_PROBLEM);
335 printf("\r\nYour authentication process (pid %ld) was unable to run\n",
337 sleep(180); /* them lusers read reaaaaal slow */
345 * reads config file in PATH_CONFFILE to set optional behaviours up
355 char *pair[4], *cp, *tp;
358 if (fgets(buf, sizeof(buf), f) == NULL) {
364 if (buf[len - 1] != '\n' && !feof(f)) {
365 syslog(LOG_ERR, "line %d too long in %s", i,
371 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
374 if (!*cp || *cp == '#' || *cp == '\n')
377 for (ap = pair; ap < &pair[3] &&
378 (*ap = strsep(&cp, "=")) != NULL; ) {
385 tp = pair[1] + strlen(pair[1]);
386 while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
389 if (strcasecmp(pair[0], "anchor") == 0) {
390 if (!pair[1][0] || strlcpy(anchorname, pair[1],
391 sizeof(anchorname)) >= sizeof(anchorname))
394 if (strcasecmp(pair[0], "table") == 0) {
395 if (!pair[1][0] || strlcpy(tablename, pair[1],
396 sizeof(tablename)) >= sizeof(tablename))
399 } while (!feof(f) && !ferror(f));
405 syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
411 * splatter a file to stdout - max line length of 1024,
412 * used for spitting message files at users to tell them
413 * they've been bad or we're unavailable.
416 print_message(char *filename)
421 if ((f = fopen(filename, "r")) == NULL)
422 return; /* fail silently, we don't care if it isn't there */
425 if (fgets(buf, sizeof(buf), f) == NULL) {
430 } while (fputs(buf, stdout) != EOF && !feof(f));
436 * allowed_luser checks to see if user "luser" is allowed to
437 * use this gateway by virtue of being listed in an allowed
438 * users file, namely /etc/authpf/authpf.allow .
440 * If /etc/authpf/authpf.allow does not exist, then we assume that
441 * all users who are allowed in by sshd(8) are permitted to
442 * use this gateway. If /etc/authpf/authpf.allow does exist, then a
443 * user must be listed if the connection is to continue, else
444 * the session terminates in the same manner as being banned.
447 allowed_luser(char *luser)
454 if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
455 if (errno == ENOENT) {
457 * allowfile doesn't exist, thus this gateway
458 * isn't restricted to certain users...
464 * luser may in fact be allowed, but we can't open
465 * the file even though it's there. probably a config
468 syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
469 PATH_ALLOWFILE, strerror(errno));
473 * /etc/authpf/authpf.allow exists, thus we do a linear
474 * search to see if they are allowed.
475 * also, if username "*" exists, then this is a
476 * "public" gateway, such as it is, so let
480 while ((buf = fgetln(f, &len))) {
481 if (buf[len - 1] == '\n')
484 if ((lbuf = (char *)malloc(len + 1)) == NULL)
486 memcpy(lbuf, buf, len);
491 matched = strcmp(luser, buf) == 0 || strcmp("*", buf) == 0;
499 return (1); /* matched an allowed username */
501 syslog(LOG_INFO, "denied access to %s: not listed in %s",
502 luser, PATH_ALLOWFILE);
505 buf = "\n\nSorry, you are not allowed to use this facility!\n";
513 * check_luser checks to see if user "luser" has been banned
514 * from using us by virtue of having an file of the same name
515 * in the "luserdir" directory.
517 * If the user has been banned, we copy the contents of the file
518 * to the user's screen. (useful for telling the user what to
519 * do to get un-banned, or just to tell them they aren't
520 * going to be un-banned.)
523 check_luser(char *luserdir, char *luser)
527 char tmp[MAXPATHLEN];
529 n = snprintf(tmp, sizeof(tmp), "%s/%s", luserdir, luser);
530 if (n < 0 || (u_int)n >= sizeof(tmp)) {
531 syslog(LOG_ERR, "provided banned directory line too long (%s)",
535 if ((f = fopen(tmp, "r")) == NULL) {
536 if (errno == ENOENT) {
538 * file or dir doesn't exist, so therefore
539 * this luser isn't banned.. all is well
544 * luser may in fact be banned, but we can't open the
545 * file even though it's there. probably a config
548 syslog(LOG_ERR, "cannot open banned file %s (%s)",
549 tmp, strerror(errno));
554 * luser is banned - spit the file at them to
555 * tell what they can do and where they can go.
557 syslog(LOG_INFO, "denied access to %s: %s exists",
561 strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
563 while (fputs(tmp, stdout) != EOF && !feof(f)) {
564 if (fgets(tmp, sizeof(tmp), f) == NULL) {
577 * Search for rulesets left by other authpf processes (either because they
578 * died ungracefully or were terminated) and remove them.
581 remove_stale_rulesets(void)
583 struct pfioc_ruleset prs;
586 memset(&prs, 0, sizeof(prs));
587 strlcpy(prs.path, anchorname, sizeof(prs.path));
588 if (ioctl(dev, DIOCGETRULESETS, &prs)) {
602 if (ioctl(dev, DIOCGETRULESET, &prs))
605 if ((t = strchr(prs.name, '(')) == NULL)
609 pid = strtoul(t, &s, 10);
610 if (!prs.name[0] || errno ||
611 (*s && (t == prs.name || *s != ')')))
613 if (kill(pid, 0) && errno != EPERM) {
615 struct pfioc_trans_e t_e[PF_RULESET_MAX+1];
616 struct pfioc_trans t;
618 bzero(&t, sizeof(t));
619 bzero(t_e, sizeof(t_e));
620 t.size = PF_RULESET_MAX+1;
621 t.esize = sizeof(t_e[0]);
623 for (i = 0; i < PF_RULESET_MAX+1; ++i) {
625 snprintf(t_e[i].anchor, sizeof(t_e[i].anchor),
626 "%s/%s", anchorname, prs.name);
628 t_e[PF_RULESET_MAX].rs_num = PF_RULESET_TABLE;
629 if ((ioctl(dev, DIOCXBEGIN, &t) ||
630 ioctl(dev, DIOCXCOMMIT, &t)) &&
641 * Add/remove filter entries for user "luser" from ip "ipsrc"
644 change_filter(int add, const char *luser, const char *ipsrc)
647 "pfctl", "-p", "/dev/pf", "-q", "-a", "anchor/ruleset",
648 "-D", "user_ip=X", "-D", "user_id=X", "-f",
651 char *fdpath = NULL, *userstr = NULL, *ipstr = NULL;
652 char *rsn = NULL, *fn = NULL;
657 if (luser == NULL || !luser[0] || ipsrc == NULL || !ipsrc[0]) {
658 syslog(LOG_ERR, "invalid luser/ipsrc");
662 if (asprintf(&rsn, "%s/%s", anchorname, rulesetname) == -1)
664 if (asprintf(&fdpath, "/dev/fd/%d", dev) == -1)
666 if (asprintf(&ipstr, "user_ip=%s", ipsrc) == -1)
668 if (asprintf(&userstr, "user_id=%s", luser) == -1)
674 if (asprintf(&fn, "%s/%s/authpf.rules", PATH_USER_DIR, luser)
677 if (stat(fn, &sb) == -1) {
679 if ((fn = strdup(PATH_PFRULES)) == NULL)
688 pargv[11] = "/dev/null";
692 switch (pid = fork()) {
694 syslog(LOG_ERR, "fork failed");
697 /* revoke group privs before exec */
699 if (setregid(gid, gid) == -1) {
702 execvp(PATH_PFCTL, pargv);
703 warn("exec of %s failed", PATH_PFCTL);
710 syslog(LOG_ERR, "pfctl exited abnormally");
715 gettimeofday(&Tstart, NULL);
716 syslog(LOG_INFO, "allowing %s, user %s", ipsrc, luser);
718 gettimeofday(&Tend, NULL);
720 syslog(LOG_INFO, "removed %s, user %s - duration %jd seconds",
721 ipsrc, luser, (intmax_t)(Tend.tv_sec - Tstart.tv_sec));
723 syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
724 ipsrc, luser, Tend.tv_sec - Tstart.tv_sec);
729 syslog(LOG_ERR, "malloc failed");
740 * Add/remove this IP from the "authpf_users" table.
743 change_table(int add, const char *ipsrc)
745 struct pfioc_table io;
746 struct pfr_addr addr;
748 bzero(&io, sizeof(io));
749 strlcpy(io.pfrio_table.pfrt_name, tablename,
750 sizeof(io.pfrio_table.pfrt_name));
751 io.pfrio_buffer = &addr;
752 io.pfrio_esize = sizeof(addr);
755 bzero(&addr, sizeof(addr));
756 if (ipsrc == NULL || !ipsrc[0])
758 if (inet_pton(AF_INET, ipsrc, &addr.pfra_ip4addr) == 1) {
759 addr.pfra_af = AF_INET;
761 } else if (inet_pton(AF_INET6, ipsrc, &addr.pfra_ip6addr) == 1) {
762 addr.pfra_af = AF_INET6;
765 syslog(LOG_ERR, "invalid ipsrc");
769 if (ioctl(dev, add ? DIOCRADDADDRS : DIOCRDELADDRS, &io) &&
771 syslog(LOG_ERR, "cannot %s %s from table %s: %s",
772 add ? "add" : "remove", ipsrc, tablename,
780 * This is to kill off states that would otherwise be left behind stateful
781 * rules. This means we don't need to allow in more traffic than we really
782 * want to, since we don't have to worry about any luser sessions lasting
783 * longer than their ssh session. This function is based on
784 * pfctl_kill_states from pfctl.
787 authpf_kill_states(void)
789 struct pfioc_state_kill psk;
790 struct pf_addr target;
792 memset(&psk, 0, sizeof(psk));
793 memset(&target, 0, sizeof(target));
795 if (inet_pton(AF_INET, ipsrc, &target.v4) == 1)
796 psk.psk_af = AF_INET;
797 else if (inet_pton(AF_INET6, ipsrc, &target.v6) == 1)
798 psk.psk_af = AF_INET6;
800 syslog(LOG_ERR, "inet_pton(%s) failed", ipsrc);
804 /* Kill all states from ipsrc */
805 memcpy(&psk.psk_src.addr.v.a.addr, &target,
806 sizeof(psk.psk_src.addr.v.a.addr));
807 memset(&psk.psk_src.addr.v.a.mask, 0xff,
808 sizeof(psk.psk_src.addr.v.a.mask));
809 if (ioctl(dev, DIOCKILLSTATES, &psk))
810 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
812 /* Kill all states to ipsrc */
813 memset(&psk.psk_src, 0, sizeof(psk.psk_src));
814 memcpy(&psk.psk_dst.addr.v.a.addr, &target,
815 sizeof(psk.psk_dst.addr.v.a.addr));
816 memset(&psk.psk_dst.addr.v.a.mask, 0xff,
817 sizeof(psk.psk_dst.addr.v.a.mask));
818 if (ioctl(dev, DIOCKILLSTATES, &psk))
819 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
822 /* signal handler that makes us go away properly */
824 need_death(int signo)
830 * function that removes our stuff when we go away.
842 change_filter(0, luser, ipsrc);
843 change_table(0, ipsrc);
844 authpf_kill_states();
845 remove_stale_rulesets();
847 if (pidfile[0] && (pidfp != NULL))
848 if (unlink(pidfile) == -1)
849 syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);