xref: /netbsd-src/dist/pf/usr.sbin/authpf/authpf.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: authpf.c,v 1.4 2005/07/01 12:43:50 peter Exp $	*/
2 /*	$OpenBSD: authpf.c,v 1.89 2005/02/10 04:24:15 joel Exp $	*/
3 
4 /*
5  * Copyright (C) 1998 - 2002 Bob Beck (beck@openbsd.org).
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/types.h>
30 #include <sys/file.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <sys/wait.h>
36 
37 #include <net/if.h>
38 #include <netinet/in.h>
39 #include <net/pfvar.h>
40 #include <arpa/inet.h>
41 
42 #include <err.h>
43 #include <errno.h>
44 #include <login_cap.h>
45 #include <pwd.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <syslog.h>
51 #include <unistd.h>
52 
53 #include "pathnames.h"
54 
55 extern int	symset(const char *, const char *, int);
56 
57 static int	read_config(FILE *);
58 static void	print_message(char *);
59 static int	allowed_luser(char *);
60 static int	check_luser(char *, char *);
61 static int	remove_stale_rulesets(void);
62 static int	change_filter(int, const char *, const char *);
63 static int	change_table(int, const char *, const char *);
64 static void	authpf_kill_states(void);
65 
66 int	dev;			/* pf device */
67 char	anchorname[PF_ANCHOR_NAME_SIZE] = "authpf";
68 char	rulesetname[MAXPATHLEN - PF_ANCHOR_NAME_SIZE - 2];
69 char	tablename[PF_TABLE_NAME_SIZE] = "authpf_users";
70 
71 FILE	*pidfp;
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. */
76 
77 struct timeval	Tstart, Tend;	/* start and end times of session */
78 
79 volatile sig_atomic_t	want_death;
80 static void		need_death(int signo);
81 static __dead void	do_death(int);
82 
83 /*
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.
88  */
89 int
90 main(int argc, char *argv[])
91 {
92 	int		 lockcnt = 0, n, pidfd;
93 	FILE		*config;
94 	struct in6_addr	 ina;
95 	struct passwd	*pw;
96 	char		*cp;
97 	uid_t		 uid;
98 	char		*shell;
99 	login_cap_t	*lc;
100 
101 	config = fopen(PATH_CONFFILE, "r");
102 
103 	if ((cp = getenv("SSH_TTY")) == NULL) {
104 		syslog(LOG_ERR, "non-interactive session connection for authpf");
105 		exit(1);
106 	}
107 
108 	if ((cp = getenv("SSH_CLIENT")) == NULL) {
109 		syslog(LOG_ERR, "cannot determine connection source");
110 		exit(1);
111 	}
112 
113 	if (strlcpy(ipsrc, cp, sizeof(ipsrc)) >= sizeof(ipsrc)) {
114 		syslog(LOG_ERR, "SSH_CLIENT variable too long");
115 		exit(1);
116 	}
117 	cp = strchr(ipsrc, ' ');
118 	if (!cp) {
119 		syslog(LOG_ERR, "corrupt SSH_CLIENT variable %s", ipsrc);
120 		exit(1);
121 	}
122 	*cp = '\0';
123 	if (inet_pton(AF_INET, ipsrc, &ina) != 1 &&
124 	    inet_pton(AF_INET6, ipsrc, &ina) != 1) {
125 		syslog(LOG_ERR,
126 		    "cannot determine IP from SSH_CLIENT %s", ipsrc);
127 		exit(1);
128 	}
129 	/* open the pf device */
130 	dev = open(PATH_DEVFILE, O_RDWR);
131 	if (dev == -1) {
132 		syslog(LOG_ERR, "cannot open packet filter device (%m)");
133 		goto die;
134 	}
135 
136 	uid = getuid();
137 	pw = getpwuid(uid);
138 	endpwent();
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 = 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 			goto dogdeath;
252 		}
253 		sleep(1);
254 
255 		/* re-open, and try again. The previous authpf process
256 		 * we killed above should unlink the file and release
257 		 * it's lock, giving us a chance to get it now
258 		 */
259 		fclose(pidfp);
260 	} while (1);
261 
262 	/* revoke privs */
263 	seteuid(getuid());
264 	setuid(getuid());
265 
266 	openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);
267 
268 	if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(luser)) {
269 		syslog(LOG_INFO, "user %s prohibited", luser);
270 		do_death(0);
271 	}
272 
273 	if (config == NULL || read_config(config)) {
274 		syslog(LOG_INFO, "bad or nonexistent %s", PATH_CONFFILE);
275 		do_death(0);
276 	}
277 
278 	if (remove_stale_rulesets()) {
279 		syslog(LOG_INFO, "error removing stale rulesets");
280 		do_death(0);
281 	}
282 
283 	/* We appear to be making headway, so actually mark our pid */
284 	rewind(pidfp);
285 	fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
286 	fflush(pidfp);
287 	(void) ftruncate(fileno(pidfp), ftello(pidfp));
288 
289 	if (change_filter(1, luser, ipsrc) == -1) {
290 		printf("Unable to modify filters\r\n");
291 		do_death(0);
292 	}
293 	if (change_table(1, luser, ipsrc) == -1) {
294 		printf("Unable to modify table\r\n");
295 		change_filter(0, luser, ipsrc);
296 		do_death(0);
297 	}
298 
299 	signal(SIGTERM, need_death);
300 	signal(SIGINT, need_death);
301 	signal(SIGALRM, need_death);
302 	signal(SIGPIPE, need_death);
303 	signal(SIGHUP, need_death);
304 	signal(SIGSTOP, need_death);
305 	signal(SIGTSTP, need_death);
306 	while (1) {
307 		printf("\r\nHello %s. ", luser);
308 		printf("You are authenticated from host \"%s\"\r\n", ipsrc);
309 		setproctitle("%s@%s", luser, ipsrc);
310 		print_message(PATH_MESSAGE);
311 		while (1) {
312 			sleep(10);
313 			if (want_death)
314 				do_death(1);
315 		}
316 	}
317 
318 	/* NOTREACHED */
319 dogdeath:
320 	printf("\r\n\r\nSorry, this service is currently unavailable due to ");
321 	printf("technical difficulties\r\n\r\n");
322 	print_message(PATH_PROBLEM);
323 	printf("\r\nYour authentication process (pid %ld) was unable to run\n",
324 	    (long)getpid());
325 	sleep(180); /* them lusers read reaaaaal slow */
326 die:
327 	do_death(0);
328 	return (0);
329 }
330 
331 /*
332  * reads config file in PATH_CONFFILE to set optional behaviours up
333  */
334 static int
335 read_config(FILE *f)
336 {
337 	char	buf[1024];
338 	int	i = 0;
339 
340 	do {
341 		char	**ap;
342 		char	 *pair[4], *cp, *tp;
343 		int	  len;
344 
345 		if (fgets(buf, sizeof(buf), f) == NULL) {
346 			fclose(f);
347 			return (0);
348 		}
349 		i++;
350 		len = strlen(buf);
351 		if (buf[len - 1] != '\n' && !feof(f)) {
352 			syslog(LOG_ERR, "line %d too long in %s", i,
353 			    PATH_CONFFILE);
354 			return (1);
355 		}
356 		buf[len - 1] = '\0';
357 
358 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
359 			; /* nothing */
360 
361 		if (!*cp || *cp == '#' || *cp == '\n')
362 			continue;
363 
364 		for (ap = pair; ap < &pair[3] &&
365 		    (*ap = strsep(&cp, "=")) != NULL; ) {
366 			if (**ap != '\0')
367 				ap++;
368 		}
369 		if (ap != &pair[2])
370 			goto parse_error;
371 
372 		tp = pair[1] + strlen(pair[1]);
373 		while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
374 			*tp-- = '\0';
375 
376 		if (strcasecmp(pair[0], "anchor") == 0) {
377 			if (!pair[1][0] || strlcpy(anchorname, pair[1],
378 			    sizeof(anchorname)) >= sizeof(anchorname))
379 				goto parse_error;
380 		}
381 		if (strcasecmp(pair[0], "table") == 0) {
382 			if (!pair[1][0] || strlcpy(tablename, pair[1],
383 			    sizeof(tablename)) >= sizeof(tablename))
384 				goto parse_error;
385 		}
386 	} while (!feof(f) && !ferror(f));
387 	fclose(f);
388 	return (0);
389 
390 parse_error:
391 	fclose(f);
392 	syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
393 	return (1);
394 }
395 
396 
397 /*
398  * splatter a file to stdout - max line length of 1024,
399  * used for spitting message files at users to tell them
400  * they've been bad or we're unavailable.
401  */
402 static void
403 print_message(char *filename)
404 {
405 	char	 buf[1024];
406 	FILE	*f;
407 
408 	if ((f = fopen(filename, "r")) == NULL)
409 		return; /* fail silently, we don't care if it isn't there */
410 
411 	do {
412 		if (fgets(buf, sizeof(buf), f) == NULL) {
413 			fflush(stdout);
414 			fclose(f);
415 			return;
416 		}
417 	} while (fputs(buf, stdout) != EOF && !feof(f));
418 	fflush(stdout);
419 	fclose(f);
420 }
421 
422 /*
423  * allowed_luser checks to see if user "luser" is allowed to
424  * use this gateway by virtue of being listed in an allowed
425  * users file, namely /etc/authpf/authpf.allow .
426  *
427  * If /etc/authpf/authpf.allow does not exist, then we assume that
428  * all users who are allowed in by sshd(8) are permitted to
429  * use this gateway. If /etc/authpf/authpf.allow does exist, then a
430  * user must be listed if the connection is to continue, else
431  * the session terminates in the same manner as being banned.
432  */
433 static int
434 allowed_luser(char *luser)
435 {
436 	char	*buf, *lbuf;
437 	int	 matched;
438 	size_t	 len;
439 	FILE	*f;
440 
441 	if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
442 		if (errno == ENOENT) {
443 			/*
444 			 * allowfile doesn't exist, thus this gateway
445 			 * isn't restricted to certain users...
446 			 */
447 			return (1);
448 		}
449 
450 		/*
451 		 * luser may in fact be allowed, but we can't open
452 		 * the file even though it's there. probably a config
453 		 * problem.
454 		 */
455 		syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
456 		    PATH_ALLOWFILE, strerror(errno));
457 		return (0);
458 	} else {
459 		/*
460 		 * /etc/authpf/authpf.allow exists, thus we do a linear
461 		 * search to see if they are allowed.
462 		 * also, if username "*" exists, then this is a
463 		 * "public" gateway, such as it is, so let
464 		 * everyone use it.
465 		 */
466 		lbuf = NULL;
467 		while ((buf = fgetln(f, &len))) {
468 			if (buf[len - 1] == '\n')
469 				buf[len - 1] = '\0';
470 			else {
471 				if ((lbuf = (char *)malloc(len + 1)) == NULL)
472 					err(1, NULL);
473 				memcpy(lbuf, buf, len);
474 				lbuf[len] = '\0';
475 				buf = lbuf;
476 			}
477 
478 			matched = strcmp(luser, buf) == 0 || strcmp("*", buf) == 0;
479 
480 			if (lbuf != NULL) {
481 				free(lbuf);
482 				lbuf = NULL;
483 			}
484 
485 			if (matched)
486 				return (1); /* matched an allowed username */
487 		}
488 		syslog(LOG_INFO, "denied access to %s: not listed in %s",
489 		    luser, PATH_ALLOWFILE);
490 
491 		/* reuse buf */
492 		buf = "\n\nSorry, you are not allowed to use this facility!\n";
493 		fputs(buf, stdout);
494 	}
495 	fflush(stdout);
496 	return (0);
497 }
498 
499 /*
500  * check_luser checks to see if user "luser" has been banned
501  * from using us by virtue of having an file of the same name
502  * in the "luserdir" directory.
503  *
504  * If the user has been banned, we copy the contents of the file
505  * to the user's screen. (useful for telling the user what to
506  * do to get un-banned, or just to tell them they aren't
507  * going to be un-banned.)
508  */
509 static int
510 check_luser(char *luserdir, char *luser)
511 {
512 	FILE	*f;
513 	int	 n;
514 	char	 tmp[MAXPATHLEN];
515 
516 	n = snprintf(tmp, sizeof(tmp), "%s/%s", luserdir, luser);
517 	if (n < 0 || (u_int)n >= sizeof(tmp)) {
518 		syslog(LOG_ERR, "provided banned directory line too long (%s)",
519 		    luserdir);
520 		return (0);
521 	}
522 	if ((f = fopen(tmp, "r")) == NULL) {
523 		if (errno == ENOENT) {
524 			/*
525 			 * file or dir doesn't exist, so therefore
526 			 * this luser isn't banned..  all is well
527 			 */
528 			return (1);
529 		} else {
530 			/*
531 			 * luser may in fact be banned, but we can't open the
532 			 * file even though it's there. probably a config
533 			 * problem.
534 			 */
535 			syslog(LOG_ERR, "cannot open banned file %s (%s)",
536 			    tmp, strerror(errno));
537 			return (0);
538 		}
539 	} else {
540 		/*
541 		 * luser is banned - spit the file at them to
542 		 * tell what they can do and where they can go.
543 		 */
544 		syslog(LOG_INFO, "denied access to %s: %s exists",
545 		    luser, tmp);
546 
547 		/* reuse tmp */
548 		strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
549 		    sizeof(tmp));
550 		while (fputs(tmp, stdout) != EOF && !feof(f)) {
551 			if (fgets(tmp, sizeof(tmp), f) == NULL) {
552 				fflush(stdout);
553 				return (0);
554 			}
555 		}
556 	}
557 	fflush(stdout);
558 	return (0);
559 }
560 
561 /*
562  * Search for rulesets left by other authpf processes (either because they
563  * died ungracefully or were terminated) and remove them.
564  */
565 static int
566 remove_stale_rulesets(void)
567 {
568 	struct pfioc_ruleset	 prs;
569 	u_int32_t		 nr, mnr;
570 
571 	memset(&prs, 0, sizeof(prs));
572 	strlcpy(prs.path, anchorname, sizeof(prs.path));
573 	if (ioctl(dev, DIOCGETRULESETS, &prs)) {
574 		if (errno == EINVAL)
575 			return (0);
576 		else
577 			return (1);
578 	}
579 
580 	mnr = prs.nr;
581 	nr = 0;
582 	while (nr < mnr) {
583 		char	*s, *t;
584 		pid_t	 pid;
585 
586 		prs.nr = nr;
587 		if (ioctl(dev, DIOCGETRULESET, &prs))
588 			return (1);
589 		errno = 0;
590 		if ((t = strchr(prs.name, '(')) == NULL)
591 			t = prs.name;
592 		else
593 			t++;
594 		pid = strtoul(t, &s, 10);
595 		if (!prs.name[0] || errno ||
596 		    (*s && (t == prs.name || *s != ')')))
597 			return (1);
598 		if (kill(pid, 0) && errno != EPERM) {
599 			int			i;
600 			struct pfioc_trans_e	t_e[PF_RULESET_MAX+1];
601 			struct pfioc_trans	t;
602 
603 			bzero(&t, sizeof(t));
604 			bzero(t_e, sizeof(t_e));
605 			t.size = PF_RULESET_MAX+1;
606 			t.esize = sizeof(t_e[0]);
607 			t.array = t_e;
608 			for (i = 0; i < PF_RULESET_MAX+1; ++i) {
609 				t_e[i].rs_num = i;
610 				snprintf(t_e[i].anchor, sizeof(t_e[i].anchor),
611 				    "%s/%s", anchorname, prs.name);
612 			}
613 			t_e[PF_RULESET_MAX].rs_num = PF_RULESET_TABLE;
614 			if ((ioctl(dev, DIOCXBEGIN, &t) ||
615 			    ioctl(dev, DIOCXCOMMIT, &t)) &&
616 			    errno != EINVAL)
617 				return (1);
618 			mnr--;
619 		} else
620 			nr++;
621 	}
622 	return (0);
623 }
624 
625 /*
626  * Add/remove filter entries for user "luser" from ip "ipsrc"
627  */
628 static int
629 change_filter(int add, const char *luser, const char *ipsrc)
630 {
631 	char	*pargv[13] = {
632 		"pfctl", "-p", "/dev/pf", "-q", "-a", "anchor/ruleset",
633 		"-D", "user_ip=X", "-D", "user_id=X", "-f",
634 		"file", NULL
635 	};
636 	char	*fdpath = NULL, *userstr = NULL, *ipstr = NULL;
637 	char	*rsn = NULL, *fn = NULL;
638 	pid_t	pid;
639 	int	s;
640 
641 	if (luser == NULL || !luser[0] || ipsrc == NULL || !ipsrc[0]) {
642 		syslog(LOG_ERR, "invalid luser/ipsrc");
643 		goto error;
644 	}
645 
646 	if (asprintf(&rsn, "%s/%s", anchorname, rulesetname) == -1)
647 		goto no_mem;
648 	if (asprintf(&fdpath, "/dev/fd/%d", dev) == -1)
649 		goto no_mem;
650 	if (asprintf(&ipstr, "user_ip=%s", ipsrc) == -1)
651 		goto no_mem;
652 	if (asprintf(&userstr, "user_id=%s", luser) == -1)
653 		goto no_mem;
654 
655 	if (add) {
656 		struct stat sb;
657 
658 		if (asprintf(&fn, "%s/%s/authpf.rules", PATH_USER_DIR, luser)
659 		    == -1)
660 			goto no_mem;
661 		if (stat(fn, &sb) == -1) {
662 			free(fn);
663 			if ((fn = strdup(PATH_PFRULES)) == NULL)
664 				goto no_mem;
665 		}
666 	}
667 	pargv[2] = fdpath;
668 	pargv[5] = rsn;
669 	pargv[7] = userstr;
670 	pargv[9] = ipstr;
671 	if (!add)
672 		pargv[11] = "/dev/null";
673 	else
674 		pargv[11] = fn;
675 
676 	switch (pid = fork()) {
677 	case -1:
678 		err(1, "fork failed");
679 	case 0:
680 		execvp(PATH_PFCTL, pargv);
681 		warn("exec of %s failed", PATH_PFCTL);
682 		_exit(1);
683 	}
684 
685 	/* parent */
686 	waitpid(pid, &s, 0);
687 	if (s != 0) {
688 		if (WIFEXITED(s)) {
689 			syslog(LOG_ERR, "pfctl exited abnormally");
690 			goto error;
691 		}
692 	}
693 
694 	if (add) {
695 		gettimeofday(&Tstart, NULL);
696 		syslog(LOG_INFO, "allowing %s, user %s", ipsrc, luser);
697 	} else {
698 		gettimeofday(&Tend, NULL);
699 		syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
700 		    ipsrc, luser, Tend.tv_sec - Tstart.tv_sec);
701 	}
702 	return (0);
703 no_mem:
704 	syslog(LOG_ERR, "malloc failed");
705 error:
706 	free(fdpath);
707 	fdpath = NULL;
708 	free(rsn);
709 	rsn = NULL;
710 	free(userstr);
711 	userstr = NULL;
712 	free(ipstr);
713 	ipstr = NULL;
714 	free(fn);
715 	fn = NULL;
716 	infile = NULL;
717 	return (-1);
718 }
719 
720 /*
721  * Add/remove this IP from the "authpf_users" table.
722  */
723 static int
724 change_table(int add, const char *luser, const char *ipsrc)
725 {
726 	struct pfioc_table	io;
727 	struct pfr_addr		addr;
728 
729 	bzero(&io, sizeof(io));
730 	strlcpy(io.pfrio_table.pfrt_name, tablename, sizeof(io.pfrio_table));
731 	io.pfrio_buffer = &addr;
732 	io.pfrio_esize = sizeof(addr);
733 	io.pfrio_size = 1;
734 
735 	bzero(&addr, sizeof(addr));
736 	if (ipsrc == NULL || !ipsrc[0])
737 		return (-1);
738 	if (inet_pton(AF_INET, ipsrc, &addr.pfra_ip4addr) == 1) {
739 		addr.pfra_af = AF_INET;
740 		addr.pfra_net = 32;
741 	} else if (inet_pton(AF_INET6, ipsrc, &addr.pfra_ip6addr) == 1) {
742 		addr.pfra_af = AF_INET6;
743 		addr.pfra_net = 128;
744 	} else {
745 		syslog(LOG_ERR, "invalid ipsrc");
746 		return (-1);
747 	}
748 
749 	if (ioctl(dev, add ? DIOCRADDADDRS : DIOCRDELADDRS, &io) &&
750 	    errno != ESRCH) {
751 		syslog(LOG_ERR, "cannot %s %s from table %s: %s",
752 		    add ? "add" : "remove", ipsrc, tablename,
753 		    strerror(errno));
754 		return (-1);
755 	}
756 	return (0);
757 }
758 
759 /*
760  * This is to kill off states that would otherwise be left behind stateful
761  * rules. This means we don't need to allow in more traffic than we really
762  * want to, since we don't have to worry about any luser sessions lasting
763  * longer than their ssh session. This function is based on
764  * pfctl_kill_states from pfctl.
765  */
766 static void
767 authpf_kill_states(void)
768 {
769 	struct pfioc_state_kill	psk;
770 	struct pf_addr target;
771 
772 	memset(&psk, 0, sizeof(psk));
773 	memset(&target, 0, sizeof(target));
774 
775 	if (inet_pton(AF_INET, ipsrc, &target.v4) == 1)
776 		psk.psk_af = AF_INET;
777 	else if (inet_pton(AF_INET6, ipsrc, &target.v6) == 1)
778 		psk.psk_af = AF_INET6;
779 	else {
780 		syslog(LOG_ERR, "inet_pton(%s) failed", ipsrc);
781 		return;
782 	}
783 
784 	/* Kill all states from ipsrc */
785 	memcpy(&psk.psk_src.addr.v.a.addr, &target,
786 	    sizeof(psk.psk_src.addr.v.a.addr));
787 	memset(&psk.psk_src.addr.v.a.mask, 0xff,
788 	    sizeof(psk.psk_src.addr.v.a.mask));
789 	if (ioctl(dev, DIOCKILLSTATES, &psk))
790 		syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
791 
792 	/* Kill all states to ipsrc */
793 	memset(&psk.psk_src, 0, sizeof(psk.psk_src));
794 	memcpy(&psk.psk_dst.addr.v.a.addr, &target,
795 	    sizeof(psk.psk_dst.addr.v.a.addr));
796 	memset(&psk.psk_dst.addr.v.a.mask, 0xff,
797 	    sizeof(psk.psk_dst.addr.v.a.mask));
798 	if (ioctl(dev, DIOCKILLSTATES, &psk))
799 		syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
800 }
801 
802 /* signal handler that makes us go away properly */
803 static void
804 need_death(int signo)
805 {
806 	want_death = 1;
807 }
808 
809 /*
810  * function that removes our stuff when we go away.
811  */
812 static __dead void
813 do_death(int active)
814 {
815 	int	ret = 0;
816 
817 	if (active) {
818 		change_filter(0, luser, ipsrc);
819 		change_table(0, luser, ipsrc);
820 		authpf_kill_states();
821 		remove_stale_rulesets();
822 	}
823 	if (pidfp)
824 		ftruncate(fileno(pidfp), 0);
825 	if (pidfile[0])
826 		if (unlink(pidfile) == -1)
827 			syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);
828 	exit(ret);
829 }
830