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