1 /* $OpenBSD: authpf.c,v 1.112 2009/01/10 19:08:53 miod 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.
18 * $FreeBSD: head/contrib/pf/authpf/authpf.c 223637 2011-06-28 11:57:25Z bz $
21 #include <sys/param.h>
22 #include <sys/types.h>
24 #include <sys/ioctl.h>
25 #include <sys/socket.h>
31 #include <net/pf/pfvar.h>
32 #include <arpa/inet.h>
36 #include <login_cap.h>
45 #include "pathnames.h"
47 #define __dead __dead2
49 static int read_config(FILE *);
50 static void print_message(const char *);
51 static int allowed_luser(const char *);
52 static int check_luser(const char *, const char *);
53 static int remove_stale_rulesets(void);
54 static int change_filter(int, const char *, const char *);
55 static int change_table(int, const char *);
56 static void authpf_kill_states(void);
58 int dev_fd; /* pf device */
59 char anchorname[PF_ANCHOR_NAME_SIZE] = "authpf";
60 char rulesetname[MAXPATHLEN - PF_ANCHOR_NAME_SIZE - 2];
61 char tablename[PF_TABLE_NAME_SIZE] = "authpf_users";
64 char luser[MAXLOGNAME]; /* username */
65 char ipsrc[256]; /* ip as a string */
66 char pidfile[MAXPATHLEN]; /* we save pid in this file. */
68 struct timeval Tstart, Tend; /* start and end times of session */
70 volatile sig_atomic_t want_death;
71 static void need_death(int signo);
72 static __dead void do_death(int);
75 * User shell for authenticating gateways. Sole purpose is to allow
76 * a user to ssh to a gateway, and have the gateway modify packet
77 * filters to allow access, then remove access when the user finishes
78 * up. Meant to be used only from ssh(1) connections.
81 main(int argc __unused, char **argv __unused)
83 int lockcnt = 0, n, pidfd;
93 config = fopen(PATH_CONFFILE, "r");
95 syslog(LOG_ERR, "cannot open %s (%m)", PATH_CONFFILE);
99 if ((cp = getenv("SSH_TTY")) == NULL) {
100 syslog(LOG_ERR, "non-interactive session connection for authpf");
104 if ((cp = getenv("SSH_CLIENT")) == NULL) {
105 syslog(LOG_ERR, "cannot determine connection source");
109 if (strlcpy(ipsrc, cp, sizeof(ipsrc)) >= sizeof(ipsrc)) {
110 syslog(LOG_ERR, "SSH_CLIENT variable too long");
113 cp = strchr(ipsrc, ' ');
115 syslog(LOG_ERR, "corrupt SSH_CLIENT variable %s", ipsrc);
119 if (inet_pton(AF_INET, ipsrc, &ina) != 1 &&
120 inet_pton(AF_INET6, ipsrc, &ina) != 1) {
122 "cannot determine IP from SSH_CLIENT %s", ipsrc);
125 /* open the pf device */
126 dev_fd = open(PATH_DEVFILE, O_RDWR);
128 syslog(LOG_ERR, "cannot open packet filter device (%m)");
135 syslog(LOG_ERR, "cannot find user for uid %u", uid);
139 if ((lc = login_getclass(pw->pw_class)) != NULL)
140 shell = login_getcapstr(lc, "shell", pw->pw_shell,
143 shell = pw->pw_shell;
147 if (strcmp(shell, PATH_AUTHPF_SHELL)) {
148 syslog(LOG_ERR, "wrong shell for user %s, uid %u",
149 pw->pw_name, pw->pw_uid);
157 * Paranoia, but this data _does_ come from outside authpf, and
158 * truncation would be bad.
160 if (strlcpy(luser, pw->pw_name, sizeof(luser)) >= sizeof(luser)) {
161 syslog(LOG_ERR, "username too long: %s", pw->pw_name);
165 if ((n = snprintf(rulesetname, sizeof(rulesetname), "%s(%ld)",
166 luser, (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
167 syslog(LOG_INFO, "%s(%ld) too large, ruleset name will be %ld",
168 luser, (long)getpid(), (long)getpid());
169 if ((n = snprintf(rulesetname, sizeof(rulesetname), "%ld",
170 (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
171 syslog(LOG_ERR, "pid too large for ruleset name");
177 /* Make our entry in /var/authpf as /var/authpf/ipaddr */
178 n = snprintf(pidfile, sizeof(pidfile), "%s/%s", PATH_PIDFILE, ipsrc);
179 if (n < 0 || (u_int)n >= sizeof(pidfile)) {
180 syslog(LOG_ERR, "path to pidfile too long");
185 * If someone else is already using this ip, then this person
186 * wants to switch users - so kill the old process and exit
189 * Note, we could print a message and tell them to log out, but the
190 * usual case of this is that someone has left themselves logged in,
191 * with the authenticated connection iconized and someone else walks
192 * up to use and automatically logs in before using. If this just
193 * gets rid of the old one silently, the new user never knows they
194 * could have used someone else's old authentication. If we
195 * tell them to log out before switching users it is an invitation
200 int save_errno, otherpid = -1;
201 char otherluser[MAXLOGNAME];
203 if ((pidfd = open(pidfile, O_RDWR|O_CREAT, 0644)) == -1 ||
204 (pidfp = fdopen(pidfd, "r+")) == NULL) {
207 syslog(LOG_ERR, "cannot open or create %s: %s", pidfile,
212 if (flock(fileno(pidfp), LOCK_EX|LOCK_NB) == 0)
216 /* Mark our pid, and username to our file. */
219 /* 31 == MAXLOGNAME - 1 */
220 if (fscanf(pidfp, "%d\n%31s\n", &otherpid, otherluser) != 2)
222 syslog(LOG_DEBUG, "tried to lock %s, in use by pid %d: %s",
223 pidfile, otherpid, strerror(save_errno));
227 "killing prior auth (pid %d) of %s by user %s",
228 otherpid, ipsrc, otherluser);
229 if (kill((pid_t) otherpid, SIGTERM) == -1) {
231 "could not kill process %d: (%m)",
237 * We try to kill the previous process and acquire the lock
238 * for 10 seconds, trying once a second. if we can't after
239 * 10 attempts we log an error and give up.
241 if (++lockcnt > 10) {
242 syslog(LOG_ERR, "cannot kill previous authpf (pid %d)",
250 /* re-open, and try again. The previous authpf process
251 * we killed above should unlink the file and release
252 * it's lock, giving us a chance to get it now
258 /* whack the group list */
260 if (setgroups(1, &gid) == -1) {
261 syslog(LOG_INFO, "setgroups: %s", strerror(errno));
267 if (setresuid(uid, uid, uid) == -1) {
268 syslog(LOG_INFO, "setresuid: %s", strerror(errno));
271 openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);
273 if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(luser)) {
274 syslog(LOG_INFO, "user %s prohibited", luser);
278 if (read_config(config)) {
279 syslog(LOG_ERR, "invalid config file %s", PATH_CONFFILE);
283 if (remove_stale_rulesets()) {
284 syslog(LOG_INFO, "error removing stale rulesets");
288 /* We appear to be making headway, so actually mark our pid */
290 fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
292 ftruncate(fileno(pidfp), ftell(pidfp));
294 if (change_filter(1, luser, ipsrc) == -1) {
295 printf("Unable to modify filters\r\n");
298 if (change_table(1, ipsrc) == -1) {
299 printf("Unable to modify table\r\n");
300 change_filter(0, luser, ipsrc);
304 signal(SIGTERM, need_death);
305 signal(SIGINT, need_death);
306 signal(SIGALRM, need_death);
307 signal(SIGPIPE, need_death);
308 signal(SIGHUP, need_death);
309 signal(SIGQUIT, need_death);
310 signal(SIGTSTP, need_death);
312 printf("\r\nHello %s. ", luser);
313 printf("You are authenticated from host \"%s\"\r\n", ipsrc);
314 setproctitle("%s@%s", luser, ipsrc);
315 print_message(PATH_MESSAGE);
325 printf("\r\n\r\nSorry, this service is currently unavailable due to ");
326 printf("technical difficulties\r\n\r\n");
327 print_message(PATH_PROBLEM);
328 printf("\r\nYour authentication process (pid %ld) was unable to run\n",
330 sleep(180); /* them lusers read reaaaaal slow */
336 * reads config file in PATH_CONFFILE to set optional behaviours up
346 char *pair[4], *cp, *tp;
349 if (fgets(buf, sizeof(buf), f) == NULL) {
357 if (buf[len - 1] != '\n' && !feof(f)) {
358 syslog(LOG_ERR, "line %d too long in %s", i,
364 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
367 if (!*cp || *cp == '#' || *cp == '\n')
370 for (ap = pair; ap < &pair[3] &&
371 (*ap = strsep(&cp, "=")) != NULL; ) {
378 tp = pair[1] + strlen(pair[1]);
379 while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
382 if (strcasecmp(pair[0], "anchor") == 0) {
383 if (!pair[1][0] || strlcpy(anchorname, pair[1],
384 sizeof(anchorname)) >= sizeof(anchorname))
387 if (strcasecmp(pair[0], "table") == 0) {
388 if (!pair[1][0] || strlcpy(tablename, pair[1],
389 sizeof(tablename)) >= sizeof(tablename))
392 } while (!feof(f) && !ferror(f));
398 syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
404 * splatter a file to stdout - max line length of 1024,
405 * used for spitting message files at users to tell them
406 * they've been bad or we're unavailable.
409 print_message(const char *filename)
414 if ((f = fopen(filename, "r")) == NULL)
415 return; /* fail silently, we don't care if it isn't there */
418 if (fgets(buf, sizeof(buf), f) == NULL) {
423 } while (fputs(buf, stdout) != EOF && !feof(f));
429 * allowed_luser checks to see if user "luser" is allowed to
430 * use this gateway by virtue of being listed in an allowed
431 * users file, namely /etc/authpf/authpf.allow .
433 * If /etc/authpf/authpf.allow does not exist, then we assume that
434 * all users who are allowed in by sshd(8) are permitted to
435 * use this gateway. If /etc/authpf/authpf.allow does exist, then a
436 * user must be listed if the connection is to continue, else
437 * the session terminates in the same manner as being banned.
440 allowed_luser(const char *user)
447 if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
448 if (errno == ENOENT) {
450 * allowfile doesn't exist, thus this gateway
451 * isn't restricted to certain users...
457 * user may in fact be allowed, but we can't open
458 * the file even though it's there. probably a config
461 syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
462 PATH_ALLOWFILE, strerror(errno));
466 * /etc/authpf/authpf.allow exists, thus we do a linear
467 * search to see if they are allowed.
468 * also, if username "*" exists, then this is a
469 * "public" gateway, such as it is, so let
473 while ((buf = fgetln(f, &len))) {
474 if (buf[len - 1] == '\n')
477 if ((lbuf = (char *)malloc(len + 1)) == NULL)
479 memcpy(lbuf, buf, len);
484 matched = strcmp(user, buf) == 0 || strcmp("*", buf) == 0;
492 return (1); /* matched an allowed username */
494 syslog(LOG_INFO, "denied access to %s: not listed in %s",
495 user, PATH_ALLOWFILE);
497 fputs("\n\nSorry, you are not allowed to use this facility!\n",
505 * check_luser checks to see if user "luser" has been banned
506 * from using us by virtue of having an file of the same name
507 * in the "luserdir" directory.
509 * If the user has been banned, we copy the contents of the file
510 * to the user's screen. (useful for telling the user what to
511 * do to get un-banned, or just to tell them they aren't
512 * going to be un-banned.)
515 check_luser(const char *userdir, const char *user)
519 char tmp[MAXPATHLEN];
521 n = snprintf(tmp, sizeof(tmp), "%s/%s", userdir, user);
522 if (n < 0 || (u_int)n >= sizeof(tmp)) {
523 syslog(LOG_ERR, "provided banned directory line too long (%s)",
527 if ((f = fopen(tmp, "r")) == NULL) {
528 if (errno == ENOENT) {
530 * file or dir doesn't exist, so therefore
531 * this luser isn't banned.. all is well
536 * user may in fact be banned, but we can't open the
537 * file even though it's there. probably a config
540 syslog(LOG_ERR, "cannot open banned file %s (%s)",
541 tmp, strerror(errno));
546 * user is banned - spit the file at them to
547 * tell what they can do and where they can go.
549 syslog(LOG_INFO, "denied access to %s: %s exists",
553 strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
555 while (fputs(tmp, stdout) != EOF && !feof(f)) {
556 if (fgets(tmp, sizeof(tmp), f) == NULL) {
569 * Search for rulesets left by other authpf processes (either because they
570 * died ungracefully or were terminated) and remove them.
573 remove_stale_rulesets(void)
575 struct pfioc_ruleset prs;
578 memset(&prs, 0, sizeof(prs));
579 strlcpy(prs.path, anchorname, sizeof(prs.path));
580 if (ioctl(dev_fd, DIOCGETRULESETS, &prs)) {
594 if (ioctl(dev_fd, DIOCGETRULESET, &prs))
597 if ((t = strchr(prs.name, '(')) == NULL)
601 pid = strtoul(t, &s, 10);
602 if (!prs.name[0] || errno ||
603 (*s && (t == prs.name || *s != ')')))
605 if (kill(pid, 0) && errno != EPERM) {
607 struct pfioc_trans_e t_e[PF_RULESET_MAX+1];
608 struct pfioc_trans t_local;
610 bzero(&t_local, sizeof(t_local));
611 bzero(t_e, sizeof(t_e));
612 t_local.size = PF_RULESET_MAX+1;
613 t_local.esize = sizeof(t_e[0]);
615 for (i = 0; i < PF_RULESET_MAX+1; ++i) {
617 snprintf(t_e[i].anchor, sizeof(t_e[i].anchor),
618 "%s/%s", anchorname, prs.name);
628 * Add/remove filter entries for user "luser" from ip "ipsrc"
631 change_filter(int add, const char *user, const char *his_ipsrc)
633 const char *pargv[13] = {
634 "pfctl", "-p", "/dev/pf", "-q", "-a", "anchor/ruleset",
635 "-D", "user_ip=X", "-D", "user_id=X", "-f",
638 char *fdpath = NULL, *userstr = NULL, *ipstr = NULL;
639 char *rsn = NULL, *fn = NULL;
644 if (user == NULL || !user[0] || his_ipsrc == NULL || !his_ipsrc[0]) {
645 syslog(LOG_ERR, "invalid user/ipsrc");
649 if (asprintf(&rsn, "%s/%s", anchorname, rulesetname) == -1)
651 if (asprintf(&fdpath, "/dev/fd/%d", dev_fd) == -1)
653 if (asprintf(&ipstr, "user_ip=%s", his_ipsrc) == -1)
655 if (asprintf(&userstr, "user_id=%s", user) == -1)
661 if (asprintf(&fn, "%s/%s/authpf.rules", PATH_USER_DIR, user)
664 if (stat(fn, &sb) == -1) {
666 if ((fn = strdup(PATH_PFRULES)) == NULL)
675 pargv[11] = "/dev/null";
679 switch (pid = fork()) {
681 syslog(LOG_ERR, "fork failed");
684 /* revoke group privs before exec */
686 if (setregid(gid, gid) == -1) {
689 execvp(PATH_PFCTL, __DECONST(char *const *, pargv));
690 warn("exec of %s failed", PATH_PFCTL);
697 syslog(LOG_ERR, "pfctl exited abnormally");
702 gettimeofday(&Tstart, NULL);
703 syslog(LOG_INFO, "allowing %s, user %s", his_ipsrc, user);
705 gettimeofday(&Tend, NULL);
706 syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
707 his_ipsrc, user, Tend.tv_sec - Tstart.tv_sec);
711 syslog(LOG_ERR, "malloc failed");
722 * Add/remove this IP from the "authpf_users" table.
725 change_table(int add, const char *his_ipsrc)
727 struct pfioc_table io;
728 struct pfr_addr addr;
730 bzero(&io, sizeof(io));
731 strlcpy(io.pfrio_table.pfrt_name, tablename,
732 sizeof(io.pfrio_table.pfrt_name));
733 io.pfrio_buffer = &addr;
734 io.pfrio_esize = sizeof(addr);
737 bzero(&addr, sizeof(addr));
738 if (his_ipsrc == NULL || !his_ipsrc[0])
740 if (inet_pton(AF_INET, his_ipsrc, &addr.pfra_ip4addr) == 1) {
741 addr.pfra_af = AF_INET;
743 } else if (inet_pton(AF_INET6, his_ipsrc, &addr.pfra_ip6addr) == 1) {
744 addr.pfra_af = AF_INET6;
747 syslog(LOG_ERR, "invalid his_ipsrc");
751 if (ioctl(dev_fd, add ? DIOCRADDADDRS : DIOCRDELADDRS, &io) &&
753 syslog(LOG_ERR, "cannot %s %s from table %s: %s",
754 add ? "add" : "remove", his_ipsrc, tablename,
762 * This is to kill off states that would otherwise be left behind stateful
763 * rules. This means we don't need to allow in more traffic than we really
764 * want to, since we don't have to worry about any luser sessions lasting
765 * longer than their ssh session. This function is based on
766 * pfctl_kill_states from pfctl.
769 authpf_kill_states(void)
771 struct pfioc_state_kill psk;
772 struct pf_addr target;
774 memset(&psk, 0, sizeof(psk));
775 memset(&target, 0, sizeof(target));
777 if (inet_pton(AF_INET, ipsrc, &target.v4) == 1)
778 psk.psk_af = AF_INET;
779 else if (inet_pton(AF_INET6, ipsrc, &target.v6) == 1)
780 psk.psk_af = AF_INET6;
782 syslog(LOG_ERR, "inet_pton(%s) failed", ipsrc);
786 /* Kill all states from ipsrc */
787 memcpy(&psk.psk_src.addr.v.a.addr, &target,
788 sizeof(psk.psk_src.addr.v.a.addr));
789 memset(&psk.psk_src.addr.v.a.mask, 0xff,
790 sizeof(psk.psk_src.addr.v.a.mask));
791 if (ioctl(dev_fd, DIOCKILLSTATES, &psk))
792 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
794 /* Kill all states to ipsrc */
795 memset(&psk.psk_src, 0, sizeof(psk.psk_src));
796 memcpy(&psk.psk_dst.addr.v.a.addr, &target,
797 sizeof(psk.psk_dst.addr.v.a.addr));
798 memset(&psk.psk_dst.addr.v.a.mask, 0xff,
799 sizeof(psk.psk_dst.addr.v.a.mask));
800 if (ioctl(dev_fd, DIOCKILLSTATES, &psk))
801 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
804 /* signal handler that makes us go away properly */
806 need_death(int signo __unused)
812 * function that removes our stuff when we go away.
820 change_filter(0, luser, ipsrc);
821 change_table(0, ipsrc);
822 authpf_kill_states();
823 remove_stale_rulesets();
825 if (pidfile[0] && (pidfp != NULL))
826 if (unlink(pidfile) == -1)
827 syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);