xref: /openbsd/usr.sbin/authpf/authpf.c (revision 3d8817e4)
1 /*	$OpenBSD: authpf.c,v 1.115 2010/09/02 14:01:04 sobrado 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/types.h>
20 #include <sys/file.h>
21 #include <sys/ioctl.h>
22 #include <sys/socket.h>
23 #include <sys/stat.h>
24 #include <sys/time.h>
25 #include <sys/wait.h>
26 
27 #include <net/if.h>
28 #include <net/pfvar.h>
29 #include <arpa/inet.h>
30 
31 #include <err.h>
32 #include <errno.h>
33 #include <login_cap.h>
34 #include <pwd.h>
35 #include <grp.h>
36 #include <signal.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <syslog.h>
41 #include <unistd.h>
42 
43 #include "pathnames.h"
44 
45 static int	read_config(FILE *);
46 static void	print_message(char *);
47 static int	allowed_luser(struct passwd *);
48 static int	check_luser(char *, char *);
49 static int	remove_stale_rulesets(void);
50 static int	recursive_ruleset_purge(char *, char *);
51 static int	change_filter(int, const char *, const char *);
52 static int	change_table(int, const char *);
53 static void	authpf_kill_states(void);
54 
55 int	dev;			/* pf device */
56 char	anchorname[PF_ANCHOR_NAME_SIZE] = "authpf";
57 char	rulesetname[MAXPATHLEN - PF_ANCHOR_NAME_SIZE - 2];
58 char	tablename[PF_TABLE_NAME_SIZE] = "authpf_users";
59 int	user_ip = 1;	/* controls whether $user_ip is set */
60 
61 FILE	*pidfp;
62 int	pidfd = -1;
63 char	 luser[MAXLOGNAME];	/* username */
64 char	 ipsrc[256];		/* ip as a string */
65 char	 pidfile[MAXPATHLEN];	/* we save pid in this file. */
66 
67 struct timeval	Tstart, Tend;	/* start and end times of session */
68 
69 volatile sig_atomic_t	want_death;
70 static void		need_death(int signo);
71 static __dead void	do_death(int);
72 extern char *__progname;	/* program name */
73 
74 /*
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.
79  */
80 int
81 main(int argc, char *argv[])
82 {
83 	int		 lockcnt = 0, n;
84 	FILE		*config;
85 	struct in6_addr	 ina;
86 	struct passwd	*pw;
87 	char		*cp;
88 	gid_t		 gid;
89 	uid_t		 uid;
90 	char		*shell;
91 	login_cap_t	*lc;
92 
93 	if (strcmp(__progname, "-authpf-noip") == 0)
94                 user_ip = 0;
95 
96 	config = fopen(PATH_CONFFILE, "r");
97 	if (config == NULL) {
98 		syslog(LOG_ERR, "cannot open %s (%m)", PATH_CONFFILE);
99 		exit(1);
100 	}
101 
102 	if ((cp = getenv("SSH_TTY")) == NULL) {
103 		syslog(LOG_ERR, "non-interactive session connection for authpf");
104 		exit(1);
105 	}
106 
107 	if ((cp = getenv("SSH_CLIENT")) == NULL) {
108 		syslog(LOG_ERR, "cannot determine connection source");
109 		exit(1);
110 	}
111 
112 	if (strlcpy(ipsrc, cp, sizeof(ipsrc)) >= sizeof(ipsrc)) {
113 		syslog(LOG_ERR, "SSH_CLIENT variable too long");
114 		exit(1);
115 	}
116 	cp = strchr(ipsrc, ' ');
117 	if (!cp) {
118 		syslog(LOG_ERR, "corrupt SSH_CLIENT variable %s", ipsrc);
119 		exit(1);
120 	}
121 	*cp = '\0';
122 	if (inet_pton(AF_INET, ipsrc, &ina) != 1 &&
123 	    inet_pton(AF_INET6, ipsrc, &ina) != 1) {
124 		syslog(LOG_ERR,
125 		    "cannot determine IP from SSH_CLIENT %s", ipsrc);
126 		exit(1);
127 	}
128 	/* open the pf device */
129 	dev = open(PATH_DEVFILE, O_RDWR);
130 	if (dev == -1) {
131 		syslog(LOG_ERR, "cannot open packet filter device (%m)");
132 		goto die;
133 	}
134 
135 	uid = getuid();
136 	pw = getpwuid(uid);
137 	if (pw == NULL) {
138 		syslog(LOG_ERR, "cannot find user for uid %u", uid);
139 		goto die;
140 	}
141 
142 	if ((lc = login_getclass(pw->pw_class)) != NULL)
143 		shell = login_getcapstr(lc, "shell", pw->pw_shell,
144 		    pw->pw_shell);
145 	else
146 		shell = pw->pw_shell;
147 
148 	login_close(lc);
149 
150 	if (strcmp(shell, PATH_AUTHPF_SHELL) &&
151 	    strcmp(shell, PATH_AUTHPF_SHELL_NOIP)) {
152 		syslog(LOG_ERR, "wrong shell for user %s, uid %u",
153 		    pw->pw_name, pw->pw_uid);
154 		if (shell != pw->pw_shell)
155 			free(shell);
156 		goto die;
157 	}
158 
159 	if (shell != pw->pw_shell)
160 		free(shell);
161 
162 	/*
163 	 * Paranoia, but this data _does_ come from outside authpf, and
164 	 * truncation would be bad.
165 	 */
166 	if (strlcpy(luser, pw->pw_name, sizeof(luser)) >= sizeof(luser)) {
167 		syslog(LOG_ERR, "username too long: %s", pw->pw_name);
168 		goto die;
169 	}
170 
171 	if ((n = snprintf(rulesetname, sizeof(rulesetname), "%s(%ld)",
172 	    luser, (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
173 		syslog(LOG_INFO, "%s(%ld) too large, ruleset name will be %ld",
174 		    luser, (long)getpid(), (long)getpid());
175 		if ((n = snprintf(rulesetname, sizeof(rulesetname), "%ld",
176 		    (long)getpid())) < 0 || (u_int)n >= sizeof(rulesetname)) {
177 			syslog(LOG_ERR, "pid too large for ruleset name");
178 			goto die;
179 		}
180 	}
181 
182 
183 	/* Make our entry in /var/authpf as ipaddr or username */
184 	n = snprintf(pidfile, sizeof(pidfile), "%s/%s",
185 	    PATH_PIDFILE, user_ip ? ipsrc : luser);
186 	if (n < 0 || (u_int)n >= sizeof(pidfile)) {
187 		syslog(LOG_ERR, "path to pidfile too long");
188 		goto die;
189 	}
190 
191 	signal(SIGTERM, need_death);
192 	signal(SIGINT, need_death);
193 	signal(SIGALRM, need_death);
194 	signal(SIGPIPE, need_death);
195 	signal(SIGHUP, need_death);
196 	signal(SIGQUIT, need_death);
197 	signal(SIGTSTP, need_death);
198 
199 	/*
200 	 * If someone else is already using this ip, then this person
201 	 * wants to switch users - so kill the old process and exit
202 	 * as well.
203 	 *
204 	 * Note, we could print a message and tell them to log out, but the
205 	 * usual case of this is that someone has left themselves logged in,
206 	 * with the authenticated connection iconized and someone else walks
207 	 * up to use and automatically logs in before using. If this just
208 	 * gets rid of the old one silently, the new user never knows they
209 	 * could have used someone else's old authentication. If we
210 	 * tell them to log out before switching users it is an invitation
211 	 * for abuse.
212 	 */
213 
214 	do {
215 		int	save_errno, otherpid = -1;
216 		char	otherluser[MAXLOGNAME];
217 
218 		if ((pidfd = open(pidfile, O_RDWR|O_CREAT, 0644)) == -1 ||
219 		    (pidfp = fdopen(pidfd, "r+")) == NULL) {
220 			if (pidfd != -1)
221 				close(pidfd);
222 			syslog(LOG_ERR, "cannot open or create %s: %s", pidfile,
223 			    strerror(errno));
224 			goto die;
225 		}
226 
227 		if (flock(fileno(pidfp), LOCK_EX|LOCK_NB) == 0)
228 			break;
229 		save_errno = errno;
230 
231 		/* Mark our pid, and username to our file. */
232 
233 		rewind(pidfp);
234 		/* 31 == MAXLOGNAME - 1 */
235 		if (fscanf(pidfp, "%d\n%31s\n", &otherpid, otherluser) != 2)
236 			otherpid = -1;
237 		syslog(LOG_DEBUG, "tried to lock %s, in use by pid %d: %s",
238 		    pidfile, otherpid, strerror(save_errno));
239 
240 		if (otherpid > 0) {
241 			syslog(LOG_INFO,
242 			    "killing prior auth (pid %d) of %s by user %s",
243 			    otherpid, ipsrc, otherluser);
244 			if (kill((pid_t) otherpid, SIGTERM) == -1) {
245 				syslog(LOG_INFO,
246 				    "could not kill process %d: (%m)",
247 				    otherpid);
248 			}
249 		}
250 
251 		/*
252 		 * We try to kill the previous process and acquire the lock
253 		 * for 10 seconds, trying once a second. if we can't after
254 		 * 10 attempts we log an error and give up.
255 		 */
256 		if (want_death || ++lockcnt > 10) {
257 			if (!want_death)
258 				syslog(LOG_ERR, "cannot kill previous authpf (pid %d)",
259 				    otherpid);
260 			fclose(pidfp);
261 			pidfp = NULL;
262 			pidfd = -1;
263 			goto dogdeath;
264 		}
265 		sleep(1);
266 
267 		/* re-open, and try again. The previous authpf process
268 		 * we killed above should unlink the file and release
269 		 * it's lock, giving us a chance to get it now
270 		 */
271 		fclose(pidfp);
272 		pidfp = NULL;
273 		pidfd = -1;
274 	} while (1);
275 
276 	/* whack the group list */
277 	gid = getegid();
278 	if (setgroups(1, &gid) == -1) {
279 		syslog(LOG_INFO, "setgroups: %s", strerror(errno));
280 		do_death(0);
281 	}
282 
283 	/* revoke privs */
284 	uid = getuid();
285 	if (setresuid(uid, uid, uid) == -1) {
286 		syslog(LOG_INFO, "setresuid: %s", strerror(errno));
287 		do_death(0);
288 	}
289 	openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);
290 
291 	if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(pw)) {
292 		syslog(LOG_INFO, "user %s prohibited", luser);
293 		do_death(0);
294 	}
295 
296 	if (read_config(config)) {
297 		syslog(LOG_ERR, "invalid config file %s", PATH_CONFFILE);
298 		do_death(0);
299 	}
300 
301 	if (remove_stale_rulesets()) {
302 		syslog(LOG_INFO, "error removing stale rulesets");
303 		do_death(0);
304 	}
305 
306 	/* We appear to be making headway, so actually mark our pid */
307 	rewind(pidfp);
308 	fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
309 	fflush(pidfp);
310 	(void) ftruncate(fileno(pidfp), ftello(pidfp));
311 
312 	if (change_filter(1, luser, ipsrc) == -1) {
313 		printf("Unable to modify filters\r\n");
314 		do_death(0);
315 	}
316 	if (user_ip && change_table(1, ipsrc) == -1) {
317 		printf("Unable to modify table\r\n");
318 		change_filter(0, luser, ipsrc);
319 		do_death(0);
320 	}
321 
322 	while (1) {
323 		struct stat sb;
324 		char *path_message;
325 		printf("\r\nHello %s. ", luser);
326 		printf("You are authenticated from host \"%s\"\r\n", ipsrc);
327 		setproctitle("%s@%s", luser, ipsrc);
328 		if (asprintf(&path_message, "%s/%s/authpf.message",
329 		    PATH_USER_DIR, luser) == -1)
330 			do_death(1);
331 		if (stat(path_message, &sb) == -1 || ! S_ISREG(sb.st_mode)) {
332 			free(path_message);
333 			if ((path_message = strdup(PATH_MESSAGE)) == NULL)
334 				do_death(1);
335 		}
336 		print_message(path_message);
337 		while (1) {
338 			sleep(10);
339 			if (want_death)
340 				do_death(1);
341 		}
342 	}
343 
344 	/* NOTREACHED */
345 dogdeath:
346 	printf("\r\n\r\nSorry, this service is currently unavailable due to ");
347 	printf("technical difficulties\r\n\r\n");
348 	print_message(PATH_PROBLEM);
349 	printf("\r\nYour authentication process (pid %ld) was unable to run\n",
350 	    (long)getpid());
351 	sleep(180); /* them lusers read reaaaaal slow */
352 die:
353 	do_death(0);
354 }
355 
356 /*
357  * reads config file in PATH_CONFFILE to set optional behaviours up
358  */
359 static int
360 read_config(FILE *f)
361 {
362 	char	buf[1024];
363 	int	i = 0;
364 
365 	do {
366 		char	**ap;
367 		char	 *pair[4], *cp, *tp;
368 		int	  len;
369 
370 		if (fgets(buf, sizeof(buf), f) == NULL) {
371 			fclose(f);
372 			return (0);
373 		}
374 		i++;
375 		len = strlen(buf);
376 		if (len == 0)
377 			continue;
378 		if (buf[len - 1] != '\n' && !feof(f)) {
379 			syslog(LOG_ERR, "line %d too long in %s", i,
380 			    PATH_CONFFILE);
381 			return (1);
382 		}
383 		buf[len - 1] = '\0';
384 
385 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
386 			; /* nothing */
387 
388 		if (!*cp || *cp == '#' || *cp == '\n')
389 			continue;
390 
391 		for (ap = pair; ap < &pair[3] &&
392 		    (*ap = strsep(&cp, "=")) != NULL; ) {
393 			if (**ap != '\0')
394 				ap++;
395 		}
396 		if (ap != &pair[2])
397 			goto parse_error;
398 
399 		tp = pair[1] + strlen(pair[1]);
400 		while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
401 			*tp-- = '\0';
402 
403 		if (strcasecmp(pair[0], "anchor") == 0) {
404 			if (!pair[1][0] || strlcpy(anchorname, pair[1],
405 			    sizeof(anchorname)) >= sizeof(anchorname))
406 				goto parse_error;
407 		}
408 		if (strcasecmp(pair[0], "table") == 0) {
409 			if (!pair[1][0] || strlcpy(tablename, pair[1],
410 			    sizeof(tablename)) >= sizeof(tablename))
411 				goto parse_error;
412 		}
413 	} while (!feof(f) && !ferror(f));
414 	fclose(f);
415 	return (0);
416 
417 parse_error:
418 	fclose(f);
419 	syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
420 	return (1);
421 }
422 
423 
424 /*
425  * splatter a file to stdout - max line length of 1024,
426  * used for spitting message files at users to tell them
427  * they've been bad or we're unavailable.
428  */
429 static void
430 print_message(char *filename)
431 {
432 	char	 buf[1024];
433 	FILE	*f;
434 
435 	if ((f = fopen(filename, "r")) == NULL)
436 		return; /* fail silently, we don't care if it isn't there */
437 
438 	do {
439 		if (fgets(buf, sizeof(buf), f) == NULL) {
440 			fflush(stdout);
441 			fclose(f);
442 			return;
443 		}
444 	} while (fputs(buf, stdout) != EOF && !feof(f));
445 	fflush(stdout);
446 	fclose(f);
447 }
448 
449 /*
450  * allowed_luser checks to see if user "luser" is allowed to
451  * use this gateway by virtue of being listed in an allowed
452  * users file, namely /etc/authpf/authpf.allow .
453  * Users may be listed by <username>, %<group>, or @<login_class>.
454  *
455  * If /etc/authpf/authpf.allow does not exist, then we assume that
456  * all users who are allowed in by sshd(8) are permitted to
457  * use this gateway. If /etc/authpf/authpf.allow does exist, then a
458  * user must be listed if the connection is to continue, else
459  * the session terminates in the same manner as being banned.
460  */
461 static int
462 allowed_luser(struct passwd *pw)
463 {
464 	char	*buf, *lbuf;
465 	int	 matched;
466 	size_t	 len;
467 	FILE	*f;
468 
469 	if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
470 		if (errno == ENOENT) {
471 			/*
472 			 * allowfile doesn't exist, thus this gateway
473 			 * isn't restricted to certain users...
474 			 */
475 			return (1);
476 		}
477 
478 		/*
479 		 * luser may in fact be allowed, but we can't open
480 		 * the file even though it's there. probably a config
481 		 * problem.
482 		 */
483 		syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
484 		    PATH_ALLOWFILE, strerror(errno));
485 		return (0);
486 	} else {
487 		/*
488 		 * /etc/authpf/authpf.allow exists, thus we do a linear
489 		 * search to see if they are allowed.
490 		 * also, if username "*" exists, then this is a
491 		 * "public" gateway, such as it is, so let
492 		 * everyone use it.
493 		 */
494 		int gl_init = 0, ngroups = NGROUPS + 1;
495 		gid_t groups[NGROUPS + 1];
496 
497 		lbuf = NULL;
498 		matched = 0;
499 
500 		while ((buf = fgetln(f, &len))) {
501 
502 			if (buf[len - 1] == '\n')
503 				buf[len - 1] = '\0';
504 			else {
505 				if ((lbuf = (char *)malloc(len + 1)) == NULL)
506 					err(1, NULL);
507 				memcpy(lbuf, buf, len);
508 				lbuf[len] = '\0';
509 				buf = lbuf;
510 			}
511 
512 			if (buf[0] == '@') {
513 				/* check login class */
514 				if (strcmp(pw->pw_class, buf + 1) == 0)
515 					matched++;
516 			} else if (buf[0] == '%') {
517 				/* check group membership */
518 				int cnt;
519 				struct group *group;
520 
521 				if ((group = getgrnam(buf + 1)) == NULL) {
522 					syslog(LOG_ERR,
523 					    "invalid group '%s' in %s (%s)",
524 					    buf + 1, PATH_ALLOWFILE,
525 				 	    strerror(errno));
526 					return (0);
527 				}
528 
529 				if (!gl_init) {
530 					(void) getgrouplist(pw->pw_name,
531 					    pw->pw_gid, groups, &ngroups);
532 					gl_init++;
533 				}
534 
535 				for ( cnt = 0; cnt < ngroups; cnt++) {
536 					if (group->gr_gid == groups[cnt]) {
537 						matched++;
538 						break;
539 					}
540 				}
541 			} else {
542 				/* check username and wildcard */
543 				matched = strcmp(pw->pw_name, buf) == 0 ||
544 				    strcmp("*", buf) == 0;
545 			}
546 
547 			if (lbuf != NULL) {
548 				free(lbuf);
549 				lbuf = NULL;
550 			}
551 
552 			if (matched)
553 				return (1); /* matched an allowed user/group */
554 		}
555 		syslog(LOG_INFO, "denied access to %s: not listed in %s",
556 		    pw->pw_name, PATH_ALLOWFILE);
557 
558 		/* reuse buf */
559 		buf = "\n\nSorry, you are not allowed to use this facility!\n";
560 		fputs(buf, stdout);
561 	}
562 	fflush(stdout);
563 	return (0);
564 }
565 
566 /*
567  * check_luser checks to see if user "luser" has been banned
568  * from using us by virtue of having an file of the same name
569  * in the "luserdir" directory.
570  *
571  * If the user has been banned, we copy the contents of the file
572  * to the user's screen. (useful for telling the user what to
573  * do to get un-banned, or just to tell them they aren't
574  * going to be un-banned.)
575  */
576 static int
577 check_luser(char *luserdir, char *luser)
578 {
579 	FILE	*f;
580 	int	 n;
581 	char	 tmp[MAXPATHLEN];
582 
583 	n = snprintf(tmp, sizeof(tmp), "%s/%s", luserdir, luser);
584 	if (n < 0 || (u_int)n >= sizeof(tmp)) {
585 		syslog(LOG_ERR, "provided banned directory line too long (%s)",
586 		    luserdir);
587 		return (0);
588 	}
589 	if ((f = fopen(tmp, "r")) == NULL) {
590 		if (errno == ENOENT) {
591 			/*
592 			 * file or dir doesn't exist, so therefore
593 			 * this luser isn't banned..  all is well
594 			 */
595 			return (1);
596 		} else {
597 			/*
598 			 * luser may in fact be banned, but we can't open the
599 			 * file even though it's there. probably a config
600 			 * problem.
601 			 */
602 			syslog(LOG_ERR, "cannot open banned file %s (%s)",
603 			    tmp, strerror(errno));
604 			return (0);
605 		}
606 	} else {
607 		/*
608 		 * luser is banned - spit the file at them to
609 		 * tell what they can do and where they can go.
610 		 */
611 		syslog(LOG_INFO, "denied access to %s: %s exists",
612 		    luser, tmp);
613 
614 		/* reuse tmp */
615 		strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
616 		    sizeof(tmp));
617 		while (fputs(tmp, stdout) != EOF && !feof(f)) {
618 			if (fgets(tmp, sizeof(tmp), f) == NULL) {
619 				fflush(stdout);
620 				fclose(f);
621 				return (0);
622 			}
623 		}
624 		fclose(f);
625 	}
626 	fflush(stdout);
627 	return (0);
628 }
629 
630 /*
631  * Search for rulesets left by other authpf processes (either because they
632  * died ungracefully or were terminated) and remove them.
633  */
634 static int
635 remove_stale_rulesets(void)
636 {
637 	struct pfioc_ruleset	 prs;
638 	u_int32_t		 nr;
639 
640 	memset(&prs, 0, sizeof(prs));
641 	strlcpy(prs.path, anchorname, sizeof(prs.path));
642 	if (ioctl(dev, DIOCGETRULESETS, &prs)) {
643 		if (errno == EINVAL)
644 			return (0);
645 		else
646 			return (1);
647 	}
648 
649 	nr = prs.nr;
650 	while (nr) {
651 		char	*s, *t;
652 		pid_t	 pid;
653 
654 		prs.nr = nr - 1;
655 		if (ioctl(dev, DIOCGETRULESET, &prs))
656 			return (1);
657 		errno = 0;
658 		if ((t = strchr(prs.name, '(')) == NULL)
659 			t = prs.name;
660 		else
661 			t++;
662 		pid = strtoul(t, &s, 10);
663 		if (!prs.name[0] || errno ||
664 		    (*s && (t == prs.name || *s != ')')))
665 			return (1);
666 		if ((kill(pid, 0) && errno != EPERM) || pid == getpid()) {
667 			if (recursive_ruleset_purge(anchorname, prs.name))
668 				return (1);
669 		}
670 		nr--;
671 	}
672 	return (0);
673 }
674 
675 static int
676 recursive_ruleset_purge(char *an, char *rs)
677 {
678 	struct pfioc_trans_e     *t_e = NULL;
679 	struct pfioc_trans	 *t = NULL;
680 	struct pfioc_ruleset	 *prs = NULL;
681 
682 	/* purge rules */
683 	errno = 0;
684 	if ((t = calloc(1, sizeof(struct pfioc_trans))) == NULL)
685 		goto no_mem;
686 	if ((t_e = calloc(2, sizeof(struct pfioc_trans_e))) == NULL)
687 		goto no_mem;
688 	t->size = 2;
689 	t->esize = sizeof(struct pfioc_trans_e);
690 	t->array = t_e;
691 	t_e[0].type = PF_TRANS_RULESET;
692 	snprintf(t_e[0].anchor, sizeof(t_e[0].anchor), "%s/%s", an, rs);
693 	t_e[1].type = PF_TRANS_TABLE;
694 
695 	if ((ioctl(dev, DIOCXBEGIN, t) ||
696 	    ioctl(dev, DIOCXCOMMIT, t)) &&
697 	    errno != EINVAL)
698 		goto cleanup;
699 
700 	/* purge any children */
701 	if ((prs = calloc(1, sizeof(struct pfioc_ruleset))) == NULL)
702 		goto no_mem;
703 	snprintf(prs->path, sizeof(prs->path), "%s/%s", an, rs);
704 	if (ioctl(dev, DIOCGETRULESETS, prs)) {
705 		if (errno != EINVAL)
706 			goto cleanup;
707 		errno = 0;
708 	} else {
709 		int nr = prs->nr;
710 
711 		while (nr) {
712 			prs->nr = 0;
713 			if (ioctl(dev, DIOCGETRULESET, prs))
714 				goto cleanup;
715 
716 			if (recursive_ruleset_purge(prs->path, prs->name))
717 				goto cleanup;
718 			nr--;
719 		}
720 	}
721 
722 no_mem:
723 	if (errno == ENOMEM)
724 		syslog(LOG_ERR, "calloc failed");
725 
726 cleanup:
727 	free(t);
728 	free(t_e);
729 	free(prs);
730 	return (errno);
731 }
732 
733 /*
734  * Add/remove filter entries for user "luser" from ip "ipsrc"
735  */
736 static int
737 change_filter(int add, const char *luser, const char *ipsrc)
738 {
739 	char	*fdpath = NULL, *userstr = NULL, *ipstr = NULL;
740 	char	*rsn = NULL, *fn = NULL;
741 	pid_t	pid;
742 	gid_t   gid;
743 	int	s;
744 
745 	if (add) {
746 		struct stat sb;
747 		char	*pargv[13] = {
748 			"pfctl", "-p", "/dev/pf", "-q", "-a", "anchor/ruleset",
749 			"-D", "user_id=X", "-D", "user_ip=X", "-f", "file", NULL
750 		};
751 
752 		if (luser == NULL || !luser[0] || ipsrc == NULL || !ipsrc[0]) {
753 			syslog(LOG_ERR, "invalid luser/ipsrc");
754 			goto error;
755 		}
756 
757 		if (asprintf(&rsn, "%s/%s", anchorname, rulesetname) == -1)
758 			goto no_mem;
759 		if (asprintf(&fdpath, "/dev/fd/%d", dev) == -1)
760 			goto no_mem;
761 		if (asprintf(&ipstr, "user_ip=%s", ipsrc) == -1)
762 			goto no_mem;
763 		if (asprintf(&userstr, "user_id=%s", luser) == -1)
764 			goto no_mem;
765 		if (asprintf(&fn, "%s/%s/authpf.rules",
766 		    PATH_USER_DIR, luser) == -1)
767 			goto no_mem;
768 		if (stat(fn, &sb) == -1) {
769 			free(fn);
770 			if ((fn = strdup(PATH_PFRULES)) == NULL)
771 				goto no_mem;
772 		}
773 		pargv[2] = fdpath;
774 		pargv[5] = rsn;
775 		pargv[7] = userstr;
776 		if (user_ip) {
777 			pargv[9] = ipstr;
778 			pargv[11] = fn;
779 		} else {
780 			pargv[8] = "-f";
781 			pargv[9] = fn;
782 			pargv[10] = NULL;
783 		}
784 
785 		switch (pid = fork()) {
786 		case -1:
787 			syslog(LOG_ERR, "fork failed");
788 			goto error;
789 		case 0:
790 			/* revoke group privs before exec */
791 			gid = getgid();
792 			if (setregid(gid, gid) == -1) {
793 				err(1, "setregid");
794 			}
795 			execvp(PATH_PFCTL, pargv);
796 			warn("exec of %s failed", PATH_PFCTL);
797 			_exit(1);
798 		}
799 
800 		/* parent */
801 		waitpid(pid, &s, 0);
802 		if (s != 0) {
803 			syslog(LOG_ERR, "pfctl exited abnormally");
804 			goto error;
805 		}
806 
807 		gettimeofday(&Tstart, NULL);
808 		syslog(LOG_INFO, "allowing %s, user %s", ipsrc, luser);
809 	} else {
810 		remove_stale_rulesets();
811 
812 		gettimeofday(&Tend, NULL);
813 		syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
814 		    ipsrc, luser, Tend.tv_sec - Tstart.tv_sec);
815 	}
816 	return (0);
817 no_mem:
818 	syslog(LOG_ERR, "malloc failed");
819 error:
820 	free(fdpath);
821 	free(rsn);
822 	free(userstr);
823 	free(ipstr);
824 	free(fn);
825 	return (-1);
826 }
827 
828 /*
829  * Add/remove this IP from the "authpf_users" table.
830  */
831 static int
832 change_table(int add, const char *ipsrc)
833 {
834 	struct pfioc_table	io;
835 	struct pfr_addr		addr;
836 
837 	bzero(&io, sizeof(io));
838 	strlcpy(io.pfrio_table.pfrt_name, tablename,
839 	    sizeof(io.pfrio_table.pfrt_name));
840 	io.pfrio_buffer = &addr;
841 	io.pfrio_esize = sizeof(addr);
842 	io.pfrio_size = 1;
843 
844 	bzero(&addr, sizeof(addr));
845 	if (ipsrc == NULL || !ipsrc[0])
846 		return (-1);
847 	if (inet_pton(AF_INET, ipsrc, &addr.pfra_ip4addr) == 1) {
848 		addr.pfra_af = AF_INET;
849 		addr.pfra_net = 32;
850 	} else if (inet_pton(AF_INET6, ipsrc, &addr.pfra_ip6addr) == 1) {
851 		addr.pfra_af = AF_INET6;
852 		addr.pfra_net = 128;
853 	} else {
854 		syslog(LOG_ERR, "invalid ipsrc");
855 		return (-1);
856 	}
857 
858 	if (ioctl(dev, add ? DIOCRADDADDRS : DIOCRDELADDRS, &io) &&
859 	    errno != ESRCH) {
860 		syslog(LOG_ERR, "cannot %s %s from table %s: %s",
861 		    add ? "add" : "remove", ipsrc, tablename,
862 		    strerror(errno));
863 		return (-1);
864 	}
865 	return (0);
866 }
867 
868 /*
869  * This is to kill off states that would otherwise be left behind stateful
870  * rules. This means we don't need to allow in more traffic than we really
871  * want to, since we don't have to worry about any luser sessions lasting
872  * longer than their ssh session. This function is based on
873  * pfctl_kill_states from pfctl.
874  */
875 static void
876 authpf_kill_states(void)
877 {
878 	struct pfioc_state_kill	psk;
879 	struct pf_addr target;
880 
881 	memset(&psk, 0, sizeof(psk));
882 	memset(&target, 0, sizeof(target));
883 
884 	if (inet_pton(AF_INET, ipsrc, &target.v4) == 1)
885 		psk.psk_af = AF_INET;
886 	else if (inet_pton(AF_INET6, ipsrc, &target.v6) == 1)
887 		psk.psk_af = AF_INET6;
888 	else {
889 		syslog(LOG_ERR, "inet_pton(%s) failed", ipsrc);
890 		return;
891 	}
892 
893 	/* Kill all states from ipsrc */
894 	memcpy(&psk.psk_src.addr.v.a.addr, &target,
895 	    sizeof(psk.psk_src.addr.v.a.addr));
896 	memset(&psk.psk_src.addr.v.a.mask, 0xff,
897 	    sizeof(psk.psk_src.addr.v.a.mask));
898 	if (ioctl(dev, DIOCKILLSTATES, &psk))
899 		syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
900 
901 	/* Kill all states to ipsrc */
902 	memset(&psk.psk_src, 0, sizeof(psk.psk_src));
903 	memcpy(&psk.psk_dst.addr.v.a.addr, &target,
904 	    sizeof(psk.psk_dst.addr.v.a.addr));
905 	memset(&psk.psk_dst.addr.v.a.mask, 0xff,
906 	    sizeof(psk.psk_dst.addr.v.a.mask));
907 	if (ioctl(dev, DIOCKILLSTATES, &psk))
908 		syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
909 }
910 
911 /* signal handler that makes us go away properly */
912 static void
913 need_death(int signo)
914 {
915 	want_death = 1;
916 }
917 
918 /*
919  * function that removes our stuff when we go away.
920  */
921 static __dead void
922 do_death(int active)
923 {
924 	int	ret = 0;
925 
926 	if (active) {
927 		change_filter(0, luser, ipsrc);
928 		if (user_ip) {
929 			change_table(0, ipsrc);
930 			authpf_kill_states();
931 		}
932 	}
933 	if (pidfile[0] && pidfd != -1)
934 		if (unlink(pidfile) == -1)
935 			syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);
936 	exit(ret);
937 }
938