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