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