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