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