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