xref: /openbsd-src/usr.sbin/authpf/authpf.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: authpf.c,v 1.112 2009/01/10 19:08:53 miod 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 		printf("\r\nHello %s. ", luser);
324 		printf("You are authenticated from host \"%s\"\r\n", ipsrc);
325 		setproctitle("%s@%s", luser, ipsrc);
326 		print_message(PATH_MESSAGE);
327 		while (1) {
328 			sleep(10);
329 			if (want_death)
330 				do_death(1);
331 		}
332 	}
333 
334 	/* NOTREACHED */
335 dogdeath:
336 	printf("\r\n\r\nSorry, this service is currently unavailable due to ");
337 	printf("technical difficulties\r\n\r\n");
338 	print_message(PATH_PROBLEM);
339 	printf("\r\nYour authentication process (pid %ld) was unable to run\n",
340 	    (long)getpid());
341 	sleep(180); /* them lusers read reaaaaal slow */
342 die:
343 	do_death(0);
344 }
345 
346 /*
347  * reads config file in PATH_CONFFILE to set optional behaviours up
348  */
349 static int
350 read_config(FILE *f)
351 {
352 	char	buf[1024];
353 	int	i = 0;
354 
355 	do {
356 		char	**ap;
357 		char	 *pair[4], *cp, *tp;
358 		int	  len;
359 
360 		if (fgets(buf, sizeof(buf), f) == NULL) {
361 			fclose(f);
362 			return (0);
363 		}
364 		i++;
365 		len = strlen(buf);
366 		if (len == 0)
367 			continue;
368 		if (buf[len - 1] != '\n' && !feof(f)) {
369 			syslog(LOG_ERR, "line %d too long in %s", i,
370 			    PATH_CONFFILE);
371 			return (1);
372 		}
373 		buf[len - 1] = '\0';
374 
375 		for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
376 			; /* nothing */
377 
378 		if (!*cp || *cp == '#' || *cp == '\n')
379 			continue;
380 
381 		for (ap = pair; ap < &pair[3] &&
382 		    (*ap = strsep(&cp, "=")) != NULL; ) {
383 			if (**ap != '\0')
384 				ap++;
385 		}
386 		if (ap != &pair[2])
387 			goto parse_error;
388 
389 		tp = pair[1] + strlen(pair[1]);
390 		while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
391 			*tp-- = '\0';
392 
393 		if (strcasecmp(pair[0], "anchor") == 0) {
394 			if (!pair[1][0] || strlcpy(anchorname, pair[1],
395 			    sizeof(anchorname)) >= sizeof(anchorname))
396 				goto parse_error;
397 		}
398 		if (strcasecmp(pair[0], "table") == 0) {
399 			if (!pair[1][0] || strlcpy(tablename, pair[1],
400 			    sizeof(tablename)) >= sizeof(tablename))
401 				goto parse_error;
402 		}
403 	} while (!feof(f) && !ferror(f));
404 	fclose(f);
405 	return (0);
406 
407 parse_error:
408 	fclose(f);
409 	syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
410 	return (1);
411 }
412 
413 
414 /*
415  * splatter a file to stdout - max line length of 1024,
416  * used for spitting message files at users to tell them
417  * they've been bad or we're unavailable.
418  */
419 static void
420 print_message(char *filename)
421 {
422 	char	 buf[1024];
423 	FILE	*f;
424 
425 	if ((f = fopen(filename, "r")) == NULL)
426 		return; /* fail silently, we don't care if it isn't there */
427 
428 	do {
429 		if (fgets(buf, sizeof(buf), f) == NULL) {
430 			fflush(stdout);
431 			fclose(f);
432 			return;
433 		}
434 	} while (fputs(buf, stdout) != EOF && !feof(f));
435 	fflush(stdout);
436 	fclose(f);
437 }
438 
439 /*
440  * allowed_luser checks to see if user "luser" is allowed to
441  * use this gateway by virtue of being listed in an allowed
442  * users file, namely /etc/authpf/authpf.allow .
443  * Users may be listed by <username>, %<group>, or @<login_class>.
444  *
445  * If /etc/authpf/authpf.allow does not exist, then we assume that
446  * all users who are allowed in by sshd(8) are permitted to
447  * use this gateway. If /etc/authpf/authpf.allow does exist, then a
448  * user must be listed if the connection is to continue, else
449  * the session terminates in the same manner as being banned.
450  */
451 static int
452 allowed_luser(struct passwd *pw)
453 {
454 	char	*buf, *lbuf;
455 	int	 matched;
456 	size_t	 len;
457 	FILE	*f;
458 
459 	if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
460 		if (errno == ENOENT) {
461 			/*
462 			 * allowfile doesn't exist, thus this gateway
463 			 * isn't restricted to certain users...
464 			 */
465 			return (1);
466 		}
467 
468 		/*
469 		 * luser may in fact be allowed, but we can't open
470 		 * the file even though it's there. probably a config
471 		 * problem.
472 		 */
473 		syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
474 		    PATH_ALLOWFILE, strerror(errno));
475 		return (0);
476 	} else {
477 		/*
478 		 * /etc/authpf/authpf.allow exists, thus we do a linear
479 		 * search to see if they are allowed.
480 		 * also, if username "*" exists, then this is a
481 		 * "public" gateway, such as it is, so let
482 		 * everyone use it.
483 		 */
484 		int gl_init = 0, ngroups = NGROUPS + 1;
485 		gid_t groups[NGROUPS + 1];
486 
487 		lbuf = NULL;
488 		matched = 0;
489 
490 		while ((buf = fgetln(f, &len))) {
491 
492 			if (buf[len - 1] == '\n')
493 				buf[len - 1] = '\0';
494 			else {
495 				if ((lbuf = (char *)malloc(len + 1)) == NULL)
496 					err(1, NULL);
497 				memcpy(lbuf, buf, len);
498 				lbuf[len] = '\0';
499 				buf = lbuf;
500 			}
501 
502 			if (buf[0] == '@') {
503 				/* check login class */
504 				if (strcmp(pw->pw_class, buf + 1) == 0)
505 					matched++;
506 			} else if (buf[0] == '%') {
507 				/* check group membership */
508 				int cnt;
509 				struct group *group;
510 
511 				if ((group = getgrnam(buf + 1)) == NULL) {
512 					syslog(LOG_ERR,
513 					    "invalid group '%s' in %s (%s)",
514 					    buf + 1, PATH_ALLOWFILE,
515 				 	    strerror(errno));
516 					return (0);
517 				}
518 
519 				if (!gl_init) {
520 					(void) getgrouplist(pw->pw_name,
521 					    pw->pw_gid, groups, &ngroups);
522 					gl_init++;
523 				}
524 
525 				for ( cnt = 0; cnt < ngroups; cnt++) {
526 					if (group->gr_gid == groups[cnt]) {
527 						matched++;
528 						break;
529 					}
530 				}
531 			} else {
532 				/* check username and wildcard */
533 				matched = strcmp(pw->pw_name, buf) == 0 ||
534 				    strcmp("*", buf) == 0;
535 			}
536 
537 			if (lbuf != NULL) {
538 				free(lbuf);
539 				lbuf = NULL;
540 			}
541 
542 			if (matched)
543 				return (1); /* matched an allowed user/group */
544 		}
545 		syslog(LOG_INFO, "denied access to %s: not listed in %s",
546 		    pw->pw_name, PATH_ALLOWFILE);
547 
548 		/* reuse buf */
549 		buf = "\n\nSorry, you are not allowed to use this facility!\n";
550 		fputs(buf, stdout);
551 	}
552 	fflush(stdout);
553 	return (0);
554 }
555 
556 /*
557  * check_luser checks to see if user "luser" has been banned
558  * from using us by virtue of having an file of the same name
559  * in the "luserdir" directory.
560  *
561  * If the user has been banned, we copy the contents of the file
562  * to the user's screen. (useful for telling the user what to
563  * do to get un-banned, or just to tell them they aren't
564  * going to be un-banned.)
565  */
566 static int
567 check_luser(char *luserdir, char *luser)
568 {
569 	FILE	*f;
570 	int	 n;
571 	char	 tmp[MAXPATHLEN];
572 
573 	n = snprintf(tmp, sizeof(tmp), "%s/%s", luserdir, luser);
574 	if (n < 0 || (u_int)n >= sizeof(tmp)) {
575 		syslog(LOG_ERR, "provided banned directory line too long (%s)",
576 		    luserdir);
577 		return (0);
578 	}
579 	if ((f = fopen(tmp, "r")) == NULL) {
580 		if (errno == ENOENT) {
581 			/*
582 			 * file or dir doesn't exist, so therefore
583 			 * this luser isn't banned..  all is well
584 			 */
585 			return (1);
586 		} else {
587 			/*
588 			 * luser may in fact be banned, but we can't open the
589 			 * file even though it's there. probably a config
590 			 * problem.
591 			 */
592 			syslog(LOG_ERR, "cannot open banned file %s (%s)",
593 			    tmp, strerror(errno));
594 			return (0);
595 		}
596 	} else {
597 		/*
598 		 * luser is banned - spit the file at them to
599 		 * tell what they can do and where they can go.
600 		 */
601 		syslog(LOG_INFO, "denied access to %s: %s exists",
602 		    luser, tmp);
603 
604 		/* reuse tmp */
605 		strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
606 		    sizeof(tmp));
607 		while (fputs(tmp, stdout) != EOF && !feof(f)) {
608 			if (fgets(tmp, sizeof(tmp), f) == NULL) {
609 				fflush(stdout);
610 				fclose(f);
611 				return (0);
612 			}
613 		}
614 		fclose(f);
615 	}
616 	fflush(stdout);
617 	return (0);
618 }
619 
620 /*
621  * Search for rulesets left by other authpf processes (either because they
622  * died ungracefully or were terminated) and remove them.
623  */
624 static int
625 remove_stale_rulesets(void)
626 {
627 	struct pfioc_ruleset	 prs;
628 	u_int32_t		 nr;
629 
630 	memset(&prs, 0, sizeof(prs));
631 	strlcpy(prs.path, anchorname, sizeof(prs.path));
632 	if (ioctl(dev, DIOCGETRULESETS, &prs)) {
633 		if (errno == EINVAL)
634 			return (0);
635 		else
636 			return (1);
637 	}
638 
639 	nr = prs.nr;
640 	while (nr) {
641 		char	*s, *t;
642 		pid_t	 pid;
643 
644 		prs.nr = nr - 1;
645 		if (ioctl(dev, DIOCGETRULESET, &prs))
646 			return (1);
647 		errno = 0;
648 		if ((t = strchr(prs.name, '(')) == NULL)
649 			t = prs.name;
650 		else
651 			t++;
652 		pid = strtoul(t, &s, 10);
653 		if (!prs.name[0] || errno ||
654 		    (*s && (t == prs.name || *s != ')')))
655 			return (1);
656 		if ((kill(pid, 0) && errno != EPERM) || pid == getpid()) {
657 			if (recursive_ruleset_purge(anchorname, prs.name))
658 				return (1);
659 		}
660 		nr--;
661 	}
662 	return (0);
663 }
664 
665 static int
666 recursive_ruleset_purge(char *an, char *rs)
667 {
668 	struct pfioc_trans_e     *t_e = NULL;
669 	struct pfioc_trans	 *t = NULL;
670 	struct pfioc_ruleset	 *prs = NULL;
671 	int			  i;
672 
673 
674 	/* purge rules */
675 	errno = 0;
676 	if ((t = calloc(1, sizeof(struct pfioc_trans))) == NULL)
677 		goto no_mem;
678 	if ((t_e = calloc(PF_RULESET_MAX+1,
679 	    sizeof(struct pfioc_trans_e))) == NULL)
680 		goto no_mem;
681 	t->size = PF_RULESET_MAX+1;
682 	t->esize = sizeof(struct pfioc_trans_e);
683 	t->array = t_e;
684 	for (i = 0; i < PF_RULESET_MAX+1; ++i) {
685 		t_e[i].rs_num = i;
686 		snprintf(t_e[i].anchor, sizeof(t_e[i].anchor), "%s/%s", an, rs);
687 	}
688 	t_e[PF_RULESET_MAX].rs_num = PF_RULESET_TABLE;
689 	if ((ioctl(dev, DIOCXBEGIN, t) ||
690 	    ioctl(dev, DIOCXCOMMIT, t)) &&
691 	    errno != EINVAL)
692 		goto cleanup;
693 
694 	/* purge any children */
695 	if ((prs = calloc(1, sizeof(struct pfioc_ruleset))) == NULL)
696 		goto no_mem;
697 	snprintf(prs->path, sizeof(prs->path), "%s/%s", an, rs);
698 	if (ioctl(dev, DIOCGETRULESETS, prs)) {
699 		if (errno != EINVAL)
700 			goto cleanup;
701 		errno = 0;
702 	} else {
703 		int nr = prs->nr;
704 
705 		while (nr) {
706 			prs->nr = 0;
707 			if (ioctl(dev, DIOCGETRULESET, prs))
708 				goto cleanup;
709 
710 			if (recursive_ruleset_purge(prs->path, prs->name))
711 				goto cleanup;
712 			nr--;
713 		}
714 	}
715 
716 no_mem:
717 	if (errno == ENOMEM)
718 		syslog(LOG_ERR, "calloc failed");
719 
720 cleanup:
721 	free(t);
722 	free(t_e);
723 	free(prs);
724 	return (errno);
725 }
726 
727 /*
728  * Add/remove filter entries for user "luser" from ip "ipsrc"
729  */
730 static int
731 change_filter(int add, const char *luser, const char *ipsrc)
732 {
733 	char	*fdpath = NULL, *userstr = NULL, *ipstr = NULL;
734 	char	*rsn = NULL, *fn = NULL;
735 	pid_t	pid;
736 	gid_t   gid;
737 	int	s;
738 
739 	if (add) {
740 		struct stat sb;
741 		char	*pargv[13] = {
742 			"pfctl", "-p", "/dev/pf", "-q", "-a", "anchor/ruleset",
743 			"-D", "user_id=X", "-D", "user_ip=X", "-f", "file", NULL
744 		};
745 
746 		if (luser == NULL || !luser[0] || ipsrc == NULL || !ipsrc[0]) {
747 			syslog(LOG_ERR, "invalid luser/ipsrc");
748 			goto error;
749 		}
750 
751 		if (asprintf(&rsn, "%s/%s", anchorname, rulesetname) == -1)
752 			goto no_mem;
753 		if (asprintf(&fdpath, "/dev/fd/%d", dev) == -1)
754 			goto no_mem;
755 		if (asprintf(&ipstr, "user_ip=%s", ipsrc) == -1)
756 			goto no_mem;
757 		if (asprintf(&userstr, "user_id=%s", luser) == -1)
758 			goto no_mem;
759 		if (asprintf(&fn, "%s/%s/authpf.rules",
760 		    PATH_USER_DIR, luser) == -1)
761 			goto no_mem;
762 		if (stat(fn, &sb) == -1) {
763 			free(fn);
764 			if ((fn = strdup(PATH_PFRULES)) == NULL)
765 				goto no_mem;
766 		}
767 		pargv[2] = fdpath;
768 		pargv[5] = rsn;
769 		pargv[7] = userstr;
770 		if (user_ip) {
771 			pargv[9] = ipstr;
772 			pargv[11] = fn;
773 		} else {
774 			pargv[8] = "-f";
775 			pargv[9] = fn;
776 			pargv[10] = NULL;
777 		}
778 
779 		switch (pid = fork()) {
780 		case -1:
781 			syslog(LOG_ERR, "fork failed");
782 			goto error;
783 		case 0:
784 			/* revoke group privs before exec */
785 			gid = getgid();
786 			if (setregid(gid, gid) == -1) {
787 				err(1, "setregid");
788 			}
789 			execvp(PATH_PFCTL, pargv);
790 			warn("exec of %s failed", PATH_PFCTL);
791 			_exit(1);
792 		}
793 
794 		/* parent */
795 		waitpid(pid, &s, 0);
796 		if (s != 0) {
797 			syslog(LOG_ERR, "pfctl exited abnormally");
798 			goto error;
799 		}
800 
801 		gettimeofday(&Tstart, NULL);
802 		syslog(LOG_INFO, "allowing %s, user %s", ipsrc, luser);
803 	} else {
804 		remove_stale_rulesets();
805 
806 		gettimeofday(&Tend, NULL);
807 		syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
808 		    ipsrc, luser, Tend.tv_sec - Tstart.tv_sec);
809 	}
810 	return (0);
811 no_mem:
812 	syslog(LOG_ERR, "malloc failed");
813 error:
814 	free(fdpath);
815 	free(rsn);
816 	free(userstr);
817 	free(ipstr);
818 	free(fn);
819 	return (-1);
820 }
821 
822 /*
823  * Add/remove this IP from the "authpf_users" table.
824  */
825 static int
826 change_table(int add, const char *ipsrc)
827 {
828 	struct pfioc_table	io;
829 	struct pfr_addr		addr;
830 
831 	bzero(&io, sizeof(io));
832 	strlcpy(io.pfrio_table.pfrt_name, tablename,
833 	    sizeof(io.pfrio_table.pfrt_name));
834 	io.pfrio_buffer = &addr;
835 	io.pfrio_esize = sizeof(addr);
836 	io.pfrio_size = 1;
837 
838 	bzero(&addr, sizeof(addr));
839 	if (ipsrc == NULL || !ipsrc[0])
840 		return (-1);
841 	if (inet_pton(AF_INET, ipsrc, &addr.pfra_ip4addr) == 1) {
842 		addr.pfra_af = AF_INET;
843 		addr.pfra_net = 32;
844 	} else if (inet_pton(AF_INET6, ipsrc, &addr.pfra_ip6addr) == 1) {
845 		addr.pfra_af = AF_INET6;
846 		addr.pfra_net = 128;
847 	} else {
848 		syslog(LOG_ERR, "invalid ipsrc");
849 		return (-1);
850 	}
851 
852 	if (ioctl(dev, add ? DIOCRADDADDRS : DIOCRDELADDRS, &io) &&
853 	    errno != ESRCH) {
854 		syslog(LOG_ERR, "cannot %s %s from table %s: %s",
855 		    add ? "add" : "remove", ipsrc, tablename,
856 		    strerror(errno));
857 		return (-1);
858 	}
859 	return (0);
860 }
861 
862 /*
863  * This is to kill off states that would otherwise be left behind stateful
864  * rules. This means we don't need to allow in more traffic than we really
865  * want to, since we don't have to worry about any luser sessions lasting
866  * longer than their ssh session. This function is based on
867  * pfctl_kill_states from pfctl.
868  */
869 static void
870 authpf_kill_states(void)
871 {
872 	struct pfioc_state_kill	psk;
873 	struct pf_addr target;
874 
875 	memset(&psk, 0, sizeof(psk));
876 	memset(&target, 0, sizeof(target));
877 
878 	if (inet_pton(AF_INET, ipsrc, &target.v4) == 1)
879 		psk.psk_af = AF_INET;
880 	else if (inet_pton(AF_INET6, ipsrc, &target.v6) == 1)
881 		psk.psk_af = AF_INET6;
882 	else {
883 		syslog(LOG_ERR, "inet_pton(%s) failed", ipsrc);
884 		return;
885 	}
886 
887 	/* Kill all states from ipsrc */
888 	memcpy(&psk.psk_src.addr.v.a.addr, &target,
889 	    sizeof(psk.psk_src.addr.v.a.addr));
890 	memset(&psk.psk_src.addr.v.a.mask, 0xff,
891 	    sizeof(psk.psk_src.addr.v.a.mask));
892 	if (ioctl(dev, DIOCKILLSTATES, &psk))
893 		syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
894 
895 	/* Kill all states to ipsrc */
896 	memset(&psk.psk_src, 0, sizeof(psk.psk_src));
897 	memcpy(&psk.psk_dst.addr.v.a.addr, &target,
898 	    sizeof(psk.psk_dst.addr.v.a.addr));
899 	memset(&psk.psk_dst.addr.v.a.mask, 0xff,
900 	    sizeof(psk.psk_dst.addr.v.a.mask));
901 	if (ioctl(dev, DIOCKILLSTATES, &psk))
902 		syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
903 }
904 
905 /* signal handler that makes us go away properly */
906 static void
907 need_death(int signo)
908 {
909 	want_death = 1;
910 }
911 
912 /*
913  * function that removes our stuff when we go away.
914  */
915 static __dead void
916 do_death(int active)
917 {
918 	int	ret = 0;
919 
920 	if (active) {
921 		change_filter(0, luser, ipsrc);
922 		if (user_ip) {
923 			change_table(0, ipsrc);
924 			authpf_kill_states();
925 		}
926 	}
927 	if (pidfile[0] && pidfd != -1)
928 		if (unlink(pidfile) == -1)
929 			syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);
930 	exit(ret);
931 }
932