xref: /freebsd/contrib/pf/authpf/authpf.c (revision aa0a1e58)
1 /*	$OpenBSD: authpf.c,v 1.104 2007/02/24 17:35:08 beck Exp $	*/
2 
3 /*
4  * Copyright (C) 1998 - 2007 Bob Beck (beck@openbsd.org).
5  *
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.
9  *
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.
17  */
18 
19 #include <sys/cdefs.h>
20 __FBSDID("$FreeBSD$");
21 
22 #include <sys/param.h>
23 #include <sys/file.h>
24 #include <sys/ioctl.h>
25 #include <sys/socket.h>
26 #include <sys/stat.h>
27 #include <sys/time.h>
28 #include <sys/wait.h>
29 
30 #include <net/if.h>
31 #include <net/pfvar.h>
32 #include <arpa/inet.h>
33 
34 #include <err.h>
35 #include <errno.h>
36 #ifdef __FreeBSD__
37 #include <inttypes.h>
38 #endif
39 #include <login_cap.h>
40 #include <pwd.h>
41 #include <signal.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <syslog.h>
46 #include <unistd.h>
47 
48 #include "pathnames.h"
49 
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);
58 
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";
63 
64 FILE	*pidfp;
65 char	 luser[MAXLOGNAME];	/* username */
66 char	 ipsrc[256];		/* ip as a string */
67 char	 pidfile[MAXPATHLEN];	/* we save pid in this file. */
68 
69 struct timeval	Tstart, Tend;	/* start and end times of session */
70 
71 volatile sig_atomic_t	want_death;
72 static void		need_death(int signo);
73 #ifdef __FreeBSD__
74 static __dead2 void	do_death(int);
75 #else
76 static __dead void	do_death(int);
77 #endif
78 
79 /*
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.
84  */
85 int
86 main(int argc, char *argv[])
87 {
88 	int		 lockcnt = 0, n, pidfd;
89 	FILE		*config;
90 	struct in6_addr	 ina;
91 	struct passwd	*pw;
92 	char		*cp;
93 	gid_t		 gid;
94 	uid_t		 uid;
95 	char		*shell;
96 	login_cap_t	*lc;
97 
98 	config = fopen(PATH_CONFFILE, "r");
99 	if (config == NULL) {
100 		syslog(LOG_ERR, "can not open %s (%m)", PATH_CONFFILE);
101 		exit(1);
102 	}
103 
104 	if ((cp = getenv("SSH_TTY")) == NULL) {
105 		syslog(LOG_ERR, "non-interactive session connection for authpf");
106 		exit(1);
107 	}
108 
109 	if ((cp = getenv("SSH_CLIENT")) == NULL) {
110 		syslog(LOG_ERR, "cannot determine connection source");
111 		exit(1);
112 	}
113 
114 	if (strlcpy(ipsrc, cp, sizeof(ipsrc)) >= sizeof(ipsrc)) {
115 		syslog(LOG_ERR, "SSH_CLIENT variable too long");
116 		exit(1);
117 	}
118 	cp = strchr(ipsrc, ' ');
119 	if (!cp) {
120 		syslog(LOG_ERR, "corrupt SSH_CLIENT variable %s", ipsrc);
121 		exit(1);
122 	}
123 	*cp = '\0';
124 	if (inet_pton(AF_INET, ipsrc, &ina) != 1 &&
125 	    inet_pton(AF_INET6, ipsrc, &ina) != 1) {
126 		syslog(LOG_ERR,
127 		    "cannot determine IP from SSH_CLIENT %s", ipsrc);
128 		exit(1);
129 	}
130 	/* open the pf device */
131 	dev = open(PATH_DEVFILE, O_RDWR);
132 	if (dev == -1) {
133 		syslog(LOG_ERR, "cannot open packet filter device (%m)");
134 		goto die;
135 	}
136 
137 	uid = getuid();
138 	pw = getpwuid(uid);
139 	if (pw == NULL) {
140 		syslog(LOG_ERR, "cannot find user for uid %u", uid);
141 		goto die;
142 	}
143 
144 	if ((lc = login_getclass(pw->pw_class)) != NULL)
145 		shell = (char *)login_getcapstr(lc, "shell", pw->pw_shell,
146 		    pw->pw_shell);
147 	else
148 		shell = pw->pw_shell;
149 
150 	login_close(lc);
151 
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)
156 			free(shell);
157 		goto die;
158 	}
159 
160 	if (shell != pw->pw_shell)
161 		free(shell);
162 
163 	/*
164 	 * Paranoia, but this data _does_ come from outside authpf, and
165 	 * truncation would be bad.
166 	 */
167 	if (strlcpy(luser, pw->pw_name, sizeof(luser)) >= sizeof(luser)) {
168 		syslog(LOG_ERR, "username too long: %s", pw->pw_name);
169 		goto die;
170 	}
171 
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");
179 			goto die;
180 		}
181 	}
182 
183 
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");
188 		goto die;
189 	}
190 
191 	/*
192 	 * If someone else is already using this ip, then this person
193 	 * wants to switch users - so kill the old process and exit
194 	 * as well.
195 	 *
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
203 	 * for abuse.
204 	 */
205 
206 	do {
207 		int	save_errno, otherpid = -1;
208 		char	otherluser[MAXLOGNAME];
209 
210 		if ((pidfd = open(pidfile, O_RDWR|O_CREAT, 0644)) == -1 ||
211 		    (pidfp = fdopen(pidfd, "r+")) == NULL) {
212 			if (pidfd != -1)
213 				close(pidfd);
214 			syslog(LOG_ERR, "cannot open or create %s: %s", pidfile,
215 			    strerror(errno));
216 			goto die;
217 		}
218 
219 		if (flock(fileno(pidfp), LOCK_EX|LOCK_NB) == 0)
220 			break;
221 		save_errno = errno;
222 
223 		/* Mark our pid, and username to our file. */
224 
225 		rewind(pidfp);
226 		/* 31 == MAXLOGNAME - 1 */
227 		if (fscanf(pidfp, "%d\n%31s\n", &otherpid, otherluser) != 2)
228 			otherpid = -1;
229 		syslog(LOG_DEBUG, "tried to lock %s, in use by pid %d: %s",
230 		    pidfile, otherpid, strerror(save_errno));
231 
232 		if (otherpid > 0) {
233 			syslog(LOG_INFO,
234 			    "killing prior auth (pid %d) of %s by user %s",
235 			    otherpid, ipsrc, otherluser);
236 			if (kill((pid_t) otherpid, SIGTERM) == -1) {
237 				syslog(LOG_INFO,
238 				    "could not kill process %d: (%m)",
239 				    otherpid);
240 			}
241 		}
242 
243 		/*
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
247 		 */
248 		if (++lockcnt > 10) {
249 			syslog(LOG_ERR, "cannot kill previous authpf (pid %d)",
250 			    otherpid);
251 			fclose(pidfp);
252 			pidfp = NULL;
253 			goto dogdeath;
254 		}
255 		sleep(1);
256 
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
260 		 */
261 		fclose(pidfp);
262 		pidfp = NULL;
263 	} while (1);
264 
265 	/* whack the group list */
266 	gid = getegid();
267 	if (setgroups(1, &gid) == -1) {
268 		syslog(LOG_INFO, "setgroups: %s", strerror(errno));
269 		do_death(0);
270 	}
271 
272 	/* revoke privs */
273 	uid = getuid();
274 	if (setresuid(uid, uid, uid) == -1) {
275 		syslog(LOG_INFO, "setresuid: %s", strerror(errno));
276 		do_death(0);
277 	}
278 	openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);
279 
280 	if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(luser)) {
281 		syslog(LOG_INFO, "user %s prohibited", luser);
282 		do_death(0);
283 	}
284 
285 	if (read_config(config)) {
286 		syslog(LOG_ERR, "invalid config file %s", PATH_CONFFILE);
287 		do_death(0);
288 	}
289 
290 	if (remove_stale_rulesets()) {
291 		syslog(LOG_INFO, "error removing stale rulesets");
292 		do_death(0);
293 	}
294 
295 	/* We appear to be making headway, so actually mark our pid */
296 	rewind(pidfp);
297 	fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
298 	fflush(pidfp);
299 	(void) ftruncate(fileno(pidfp), ftello(pidfp));
300 
301 	if (change_filter(1, luser, ipsrc) == -1) {
302 		printf("Unable to modify filters\r\n");
303 		do_death(0);
304 	}
305 	if (change_table(1, ipsrc) == -1) {
306 		printf("Unable to modify table\r\n");
307 		change_filter(0, luser, ipsrc);
308 		do_death(0);
309 	}
310 
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);
318 	while (1) {
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);
323 		while (1) {
324 			sleep(10);
325 			if (want_death)
326 				do_death(1);
327 		}
328 	}
329 
330 	/* NOTREACHED */
331 dogdeath:
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",
336 	    (long)getpid());
337 	sleep(180); /* them lusers read reaaaaal slow */
338 die:
339 	do_death(0);
340 
341 	/* NOTREACHED */
342 }
343 
344 /*
345  * reads config file in PATH_CONFFILE to set optional behaviours up
346  */
347 static int
348 read_config(FILE *f)
349 {
350 	char	buf[1024];
351 	int	i = 0;
352 
353 	do {
354 		char	**ap;
355 		char	 *pair[4], *cp, *tp;
356 		int	  len;
357 
358 		if (fgets(buf, sizeof(buf), f) == NULL) {
359 			fclose(f);
360 			return (0);
361 		}
362 		i++;
363 		len = strlen(buf);
364 		if (buf[len - 1] != '\n' && !feof(f)) {
365 			syslog(LOG_ERR, "line %d too long in %s", i,
366 			    PATH_CONFFILE);
367 			return (1);
368 		}
369 		buf[len - 1] = '\0';
370 
371 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
372 			; /* nothing */
373 
374 		if (!*cp || *cp == '#' || *cp == '\n')
375 			continue;
376 
377 		for (ap = pair; ap < &pair[3] &&
378 		    (*ap = strsep(&cp, "=")) != NULL; ) {
379 			if (**ap != '\0')
380 				ap++;
381 		}
382 		if (ap != &pair[2])
383 			goto parse_error;
384 
385 		tp = pair[1] + strlen(pair[1]);
386 		while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
387 			*tp-- = '\0';
388 
389 		if (strcasecmp(pair[0], "anchor") == 0) {
390 			if (!pair[1][0] || strlcpy(anchorname, pair[1],
391 			    sizeof(anchorname)) >= sizeof(anchorname))
392 				goto parse_error;
393 		}
394 		if (strcasecmp(pair[0], "table") == 0) {
395 			if (!pair[1][0] || strlcpy(tablename, pair[1],
396 			    sizeof(tablename)) >= sizeof(tablename))
397 				goto parse_error;
398 		}
399 	} while (!feof(f) && !ferror(f));
400 	fclose(f);
401 	return (0);
402 
403 parse_error:
404 	fclose(f);
405 	syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
406 	return (1);
407 }
408 
409 
410 /*
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.
414  */
415 static void
416 print_message(char *filename)
417 {
418 	char	 buf[1024];
419 	FILE	*f;
420 
421 	if ((f = fopen(filename, "r")) == NULL)
422 		return; /* fail silently, we don't care if it isn't there */
423 
424 	do {
425 		if (fgets(buf, sizeof(buf), f) == NULL) {
426 			fflush(stdout);
427 			fclose(f);
428 			return;
429 		}
430 	} while (fputs(buf, stdout) != EOF && !feof(f));
431 	fflush(stdout);
432 	fclose(f);
433 }
434 
435 /*
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 .
439  *
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.
445  */
446 static int
447 allowed_luser(char *luser)
448 {
449 	char	*buf, *lbuf;
450 	int	 matched;
451 	size_t	 len;
452 	FILE	*f;
453 
454 	if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
455 		if (errno == ENOENT) {
456 			/*
457 			 * allowfile doesn't exist, thus this gateway
458 			 * isn't restricted to certain users...
459 			 */
460 			return (1);
461 		}
462 
463 		/*
464 		 * luser may in fact be allowed, but we can't open
465 		 * the file even though it's there. probably a config
466 		 * problem.
467 		 */
468 		syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
469 		    PATH_ALLOWFILE, strerror(errno));
470 		return (0);
471 	} else {
472 		/*
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
477 		 * everyone use it.
478 		 */
479 		lbuf = NULL;
480 		while ((buf = fgetln(f, &len))) {
481 			if (buf[len - 1] == '\n')
482 				buf[len - 1] = '\0';
483 			else {
484 				if ((lbuf = (char *)malloc(len + 1)) == NULL)
485 					err(1, NULL);
486 				memcpy(lbuf, buf, len);
487 				lbuf[len] = '\0';
488 				buf = lbuf;
489 			}
490 
491 			matched = strcmp(luser, buf) == 0 || strcmp("*", buf) == 0;
492 
493 			if (lbuf != NULL) {
494 				free(lbuf);
495 				lbuf = NULL;
496 			}
497 
498 			if (matched)
499 				return (1); /* matched an allowed username */
500 		}
501 		syslog(LOG_INFO, "denied access to %s: not listed in %s",
502 		    luser, PATH_ALLOWFILE);
503 
504 		/* reuse buf */
505 		buf = "\n\nSorry, you are not allowed to use this facility!\n";
506 		fputs(buf, stdout);
507 	}
508 	fflush(stdout);
509 	return (0);
510 }
511 
512 /*
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.
516  *
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.)
521  */
522 static int
523 check_luser(char *luserdir, char *luser)
524 {
525 	FILE	*f;
526 	int	 n;
527 	char	 tmp[MAXPATHLEN];
528 
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)",
532 		    luserdir);
533 		return (0);
534 	}
535 	if ((f = fopen(tmp, "r")) == NULL) {
536 		if (errno == ENOENT) {
537 			/*
538 			 * file or dir doesn't exist, so therefore
539 			 * this luser isn't banned..  all is well
540 			 */
541 			return (1);
542 		} else {
543 			/*
544 			 * luser may in fact be banned, but we can't open the
545 			 * file even though it's there. probably a config
546 			 * problem.
547 			 */
548 			syslog(LOG_ERR, "cannot open banned file %s (%s)",
549 			    tmp, strerror(errno));
550 			return (0);
551 		}
552 	} else {
553 		/*
554 		 * luser is banned - spit the file at them to
555 		 * tell what they can do and where they can go.
556 		 */
557 		syslog(LOG_INFO, "denied access to %s: %s exists",
558 		    luser, tmp);
559 
560 		/* reuse tmp */
561 		strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
562 		    sizeof(tmp));
563 		while (fputs(tmp, stdout) != EOF && !feof(f)) {
564 			if (fgets(tmp, sizeof(tmp), f) == NULL) {
565 				fflush(stdout);
566 				fclose(f);
567 				return (0);
568 			}
569 		}
570 		fclose(f);
571 	}
572 	fflush(stdout);
573 	return (0);
574 }
575 
576 /*
577  * Search for rulesets left by other authpf processes (either because they
578  * died ungracefully or were terminated) and remove them.
579  */
580 static int
581 remove_stale_rulesets(void)
582 {
583 	struct pfioc_ruleset	 prs;
584 	u_int32_t		 nr, mnr;
585 
586 	memset(&prs, 0, sizeof(prs));
587 	strlcpy(prs.path, anchorname, sizeof(prs.path));
588 	if (ioctl(dev, DIOCGETRULESETS, &prs)) {
589 		if (errno == EINVAL)
590 			return (0);
591 		else
592 			return (1);
593 	}
594 
595 	mnr = prs.nr;
596 	nr = 0;
597 	while (nr < mnr) {
598 		char	*s, *t;
599 		pid_t	 pid;
600 
601 		prs.nr = nr;
602 		if (ioctl(dev, DIOCGETRULESET, &prs))
603 			return (1);
604 		errno = 0;
605 		if ((t = strchr(prs.name, '(')) == NULL)
606 			t = prs.name;
607 		else
608 			t++;
609 		pid = strtoul(t, &s, 10);
610 		if (!prs.name[0] || errno ||
611 		    (*s && (t == prs.name || *s != ')')))
612 			return (1);
613 		if (kill(pid, 0) && errno != EPERM) {
614 			int			i;
615 			struct pfioc_trans_e	t_e[PF_RULESET_MAX+1];
616 			struct pfioc_trans	t;
617 
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]);
622 			t.array = t_e;
623 			for (i = 0; i < PF_RULESET_MAX+1; ++i) {
624 				t_e[i].rs_num = i;
625 				snprintf(t_e[i].anchor, sizeof(t_e[i].anchor),
626 				    "%s/%s", anchorname, prs.name);
627 			}
628 			t_e[PF_RULESET_MAX].rs_num = PF_RULESET_TABLE;
629 			if ((ioctl(dev, DIOCXBEGIN, &t) ||
630 			    ioctl(dev, DIOCXCOMMIT, &t)) &&
631 			    errno != EINVAL)
632 				return (1);
633 			mnr--;
634 		} else
635 			nr++;
636 	}
637 	return (0);
638 }
639 
640 /*
641  * Add/remove filter entries for user "luser" from ip "ipsrc"
642  */
643 static int
644 change_filter(int add, const char *luser, const char *ipsrc)
645 {
646 	char	*pargv[13] = {
647 		"pfctl", "-p", "/dev/pf", "-q", "-a", "anchor/ruleset",
648 		"-D", "user_ip=X", "-D", "user_id=X", "-f",
649 		"file", NULL
650 	};
651 	char	*fdpath = NULL, *userstr = NULL, *ipstr = NULL;
652 	char	*rsn = NULL, *fn = NULL;
653 	pid_t	pid;
654 	gid_t   gid;
655 	int	s;
656 
657 	if (luser == NULL || !luser[0] || ipsrc == NULL || !ipsrc[0]) {
658 		syslog(LOG_ERR, "invalid luser/ipsrc");
659 		goto error;
660 	}
661 
662 	if (asprintf(&rsn, "%s/%s", anchorname, rulesetname) == -1)
663 		goto no_mem;
664 	if (asprintf(&fdpath, "/dev/fd/%d", dev) == -1)
665 		goto no_mem;
666 	if (asprintf(&ipstr, "user_ip=%s", ipsrc) == -1)
667 		goto no_mem;
668 	if (asprintf(&userstr, "user_id=%s", luser) == -1)
669 		goto no_mem;
670 
671 	if (add) {
672 		struct stat sb;
673 
674 		if (asprintf(&fn, "%s/%s/authpf.rules", PATH_USER_DIR, luser)
675 		    == -1)
676 			goto no_mem;
677 		if (stat(fn, &sb) == -1) {
678 			free(fn);
679 			if ((fn = strdup(PATH_PFRULES)) == NULL)
680 				goto no_mem;
681 		}
682 	}
683 	pargv[2] = fdpath;
684 	pargv[5] = rsn;
685 	pargv[7] = userstr;
686 	pargv[9] = ipstr;
687 	if (!add)
688 		pargv[11] = "/dev/null";
689 	else
690 		pargv[11] = fn;
691 
692 	switch (pid = fork()) {
693 	case -1:
694 		syslog(LOG_ERR, "fork failed");
695 		goto error;
696 	case 0:
697 		/* revoke group privs before exec */
698 		gid = getgid();
699 		if (setregid(gid, gid) == -1) {
700 			err(1, "setregid");
701 		}
702 		execvp(PATH_PFCTL, pargv);
703 		warn("exec of %s failed", PATH_PFCTL);
704 		_exit(1);
705 	}
706 
707 	/* parent */
708 	waitpid(pid, &s, 0);
709 	if (s != 0) {
710 		syslog(LOG_ERR, "pfctl exited abnormally");
711 		goto error;
712 	}
713 
714 	if (add) {
715 		gettimeofday(&Tstart, NULL);
716 		syslog(LOG_INFO, "allowing %s, user %s", ipsrc, luser);
717 	} else {
718 		gettimeofday(&Tend, NULL);
719 #ifdef __FreeBSD__
720 		syslog(LOG_INFO, "removed %s, user %s - duration %jd seconds",
721 		    ipsrc, luser, (intmax_t)(Tend.tv_sec - Tstart.tv_sec));
722 #else
723 		syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
724 		    ipsrc, luser, Tend.tv_sec - Tstart.tv_sec);
725 #endif
726 	}
727 	return (0);
728 no_mem:
729 	syslog(LOG_ERR, "malloc failed");
730 error:
731 	free(fdpath);
732 	free(rsn);
733 	free(userstr);
734 	free(ipstr);
735 	free(fn);
736 	return (-1);
737 }
738 
739 /*
740  * Add/remove this IP from the "authpf_users" table.
741  */
742 static int
743 change_table(int add, const char *ipsrc)
744 {
745 	struct pfioc_table	io;
746 	struct pfr_addr		addr;
747 
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);
753 	io.pfrio_size = 1;
754 
755 	bzero(&addr, sizeof(addr));
756 	if (ipsrc == NULL || !ipsrc[0])
757 		return (-1);
758 	if (inet_pton(AF_INET, ipsrc, &addr.pfra_ip4addr) == 1) {
759 		addr.pfra_af = AF_INET;
760 		addr.pfra_net = 32;
761 	} else if (inet_pton(AF_INET6, ipsrc, &addr.pfra_ip6addr) == 1) {
762 		addr.pfra_af = AF_INET6;
763 		addr.pfra_net = 128;
764 	} else {
765 		syslog(LOG_ERR, "invalid ipsrc");
766 		return (-1);
767 	}
768 
769 	if (ioctl(dev, add ? DIOCRADDADDRS : DIOCRDELADDRS, &io) &&
770 	    errno != ESRCH) {
771 		syslog(LOG_ERR, "cannot %s %s from table %s: %s",
772 		    add ? "add" : "remove", ipsrc, tablename,
773 		    strerror(errno));
774 		return (-1);
775 	}
776 	return (0);
777 }
778 
779 /*
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.
785  */
786 static void
787 authpf_kill_states(void)
788 {
789 	struct pfioc_state_kill	psk;
790 	struct pf_addr target;
791 
792 	memset(&psk, 0, sizeof(psk));
793 	memset(&target, 0, sizeof(target));
794 
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;
799 	else {
800 		syslog(LOG_ERR, "inet_pton(%s) failed", ipsrc);
801 		return;
802 	}
803 
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)");
811 
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)");
820 }
821 
822 /* signal handler that makes us go away properly */
823 static void
824 need_death(int signo)
825 {
826 	want_death = 1;
827 }
828 
829 /*
830  * function that removes our stuff when we go away.
831  */
832 #ifdef __FreeBSD__
833 static __dead2 void
834 #else
835 static __dead void
836 #endif
837 do_death(int active)
838 {
839 	int	ret = 0;
840 
841 	if (active) {
842 		change_filter(0, luser, ipsrc);
843 		change_table(0, ipsrc);
844 		authpf_kill_states();
845 		remove_stale_rulesets();
846 	}
847 	if (pidfile[0] && (pidfp != NULL))
848 		if (unlink(pidfile) == -1)
849 			syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);
850 	exit(ret);
851 }
852