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