authpf.c revision 1.5.18.2 1 /* $NetBSD: authpf.c,v 1.5.18.2 2008/04/19 12:31:04 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 defined(__OpenBSD__)
267 if (setresuid(uid, uid, uid) == -1) {
268 syslog(LOG_INFO, "setresuid: %s", strerror(errno));
269 do_death(0);
270 }
271 #else /* defined(__OpenBSD__) */
272 /* NetBSD */
273 if (setuid(uid) == -1) {
274 syslog(LOG_INFO, "setresuid: %s", strerror(errno));
275 do_death(0);
276 }
277 #endif /* defined(__OpenBSD__) */
278 openlog("authpf", LOG_PID | LOG_NDELAY, LOG_DAEMON);
279
280 if (!check_luser(PATH_BAN_DIR, luser) || !allowed_luser(luser)) {
281 syslog(LOG_INFO, "user %s prohibited", luser);
282 do_death(0);
283 }
284
285 if (read_config(config)) {
286 syslog(LOG_ERR, "invalid config file %s", PATH_CONFFILE);
287 do_death(0);
288 }
289
290 if (remove_stale_rulesets()) {
291 syslog(LOG_INFO, "error removing stale rulesets");
292 do_death(0);
293 }
294
295 /* We appear to be making headway, so actually mark our pid */
296 rewind(pidfp);
297 fprintf(pidfp, "%ld\n%s\n", (long)getpid(), luser);
298 fflush(pidfp);
299 (void) ftruncate(fileno(pidfp), ftello(pidfp));
300
301 if (change_filter(1, luser, ipsrc) == -1) {
302 printf("Unable to modify filters\r\n");
303 do_death(0);
304 }
305 if (change_table(1, ipsrc) == -1) {
306 printf("Unable to modify table\r\n");
307 change_filter(0, luser, ipsrc);
308 do_death(0);
309 }
310
311 signal(SIGTERM, need_death);
312 signal(SIGINT, need_death);
313 signal(SIGALRM, need_death);
314 signal(SIGPIPE, need_death);
315 signal(SIGHUP, need_death);
316 signal(SIGQUIT, need_death);
317 signal(SIGTSTP, need_death);
318 while (1) {
319 printf("\r\nHello %s. ", luser);
320 printf("You are authenticated from host \"%s\"\r\n", ipsrc);
321 setproctitle("%s@%s", luser, ipsrc);
322 print_message(PATH_MESSAGE);
323 while (1) {
324 sleep(10);
325 if (want_death)
326 do_death(1);
327 }
328 }
329
330 /* NOTREACHED */
331 dogdeath:
332 printf("\r\n\r\nSorry, this service is currently unavailable due to ");
333 printf("technical difficulties\r\n\r\n");
334 print_message(PATH_PROBLEM);
335 printf("\r\nYour authentication process (pid %ld) was unable to run\n",
336 (long)getpid());
337 sleep(180); /* them lusers read reaaaaal slow */
338 die:
339 do_death(0);
340 return (0);
341 }
342
343 /*
344 * reads config file in PATH_CONFFILE to set optional behaviours up
345 */
346 static int
347 read_config(FILE *f)
348 {
349 char buf[1024];
350 int i = 0;
351
352 do {
353 char **ap;
354 char *pair[4], *cp, *tp;
355 int len;
356
357 if (fgets(buf, sizeof(buf), f) == NULL) {
358 fclose(f);
359 return (0);
360 }
361 i++;
362 len = strlen(buf);
363 if (buf[len - 1] != '\n' && !feof(f)) {
364 syslog(LOG_ERR, "line %d too long in %s", i,
365 PATH_CONFFILE);
366 return (1);
367 }
368 buf[len - 1] = '\0';
369
370 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
371 ; /* nothing */
372
373 if (!*cp || *cp == '#' || *cp == '\n')
374 continue;
375
376 for (ap = pair; ap < &pair[3] &&
377 (*ap = strsep(&cp, "=")) != NULL; ) {
378 if (**ap != '\0')
379 ap++;
380 }
381 if (ap != &pair[2])
382 goto parse_error;
383
384 tp = pair[1] + strlen(pair[1]);
385 while ((*tp == ' ' || *tp == '\t') && tp >= pair[1])
386 *tp-- = '\0';
387
388 if (strcasecmp(pair[0], "anchor") == 0) {
389 if (!pair[1][0] || strlcpy(anchorname, pair[1],
390 sizeof(anchorname)) >= sizeof(anchorname))
391 goto parse_error;
392 }
393 if (strcasecmp(pair[0], "table") == 0) {
394 if (!pair[1][0] || strlcpy(tablename, pair[1],
395 sizeof(tablename)) >= sizeof(tablename))
396 goto parse_error;
397 }
398 } while (!feof(f) && !ferror(f));
399 fclose(f);
400 return (0);
401
402 parse_error:
403 fclose(f);
404 syslog(LOG_ERR, "parse error, line %d of %s", i, PATH_CONFFILE);
405 return (1);
406 }
407
408
409 /*
410 * splatter a file to stdout - max line length of 1024,
411 * used for spitting message files at users to tell them
412 * they've been bad or we're unavailable.
413 */
414 static void
415 print_message(char *filename)
416 {
417 char buf[1024];
418 FILE *f;
419
420 if ((f = fopen(filename, "r")) == NULL)
421 return; /* fail silently, we don't care if it isn't there */
422
423 do {
424 if (fgets(buf, sizeof(buf), f) == NULL) {
425 fflush(stdout);
426 fclose(f);
427 return;
428 }
429 } while (fputs(buf, stdout) != EOF && !feof(f));
430 fflush(stdout);
431 fclose(f);
432 }
433
434 /*
435 * allowed_luser checks to see if user "luser" is allowed to
436 * use this gateway by virtue of being listed in an allowed
437 * users file, namely /etc/authpf/authpf.allow .
438 *
439 * If /etc/authpf/authpf.allow does not exist, then we assume that
440 * all users who are allowed in by sshd(8) are permitted to
441 * use this gateway. If /etc/authpf/authpf.allow does exist, then a
442 * user must be listed if the connection is to continue, else
443 * the session terminates in the same manner as being banned.
444 */
445 static int
446 allowed_luser(char *luser)
447 {
448 char *buf, *lbuf;
449 int matched;
450 size_t len;
451 FILE *f;
452
453 if ((f = fopen(PATH_ALLOWFILE, "r")) == NULL) {
454 if (errno == ENOENT) {
455 /*
456 * allowfile doesn't exist, thus this gateway
457 * isn't restricted to certain users...
458 */
459 return (1);
460 }
461
462 /*
463 * luser may in fact be allowed, but we can't open
464 * the file even though it's there. probably a config
465 * problem.
466 */
467 syslog(LOG_ERR, "cannot open allowed users file %s (%s)",
468 PATH_ALLOWFILE, strerror(errno));
469 return (0);
470 } else {
471 /*
472 * /etc/authpf/authpf.allow exists, thus we do a linear
473 * search to see if they are allowed.
474 * also, if username "*" exists, then this is a
475 * "public" gateway, such as it is, so let
476 * everyone use it.
477 */
478 lbuf = NULL;
479 while ((buf = fgetln(f, &len))) {
480 if (buf[len - 1] == '\n')
481 buf[len - 1] = '\0';
482 else {
483 if ((lbuf = (char *)malloc(len + 1)) == NULL)
484 err(1, NULL);
485 memcpy(lbuf, buf, len);
486 lbuf[len] = '\0';
487 buf = lbuf;
488 }
489
490 matched = strcmp(luser, buf) == 0 || strcmp("*", buf) == 0;
491
492 if (lbuf != NULL) {
493 free(lbuf);
494 lbuf = NULL;
495 }
496
497 if (matched)
498 return (1); /* matched an allowed username */
499 }
500 syslog(LOG_INFO, "denied access to %s: not listed in %s",
501 luser, PATH_ALLOWFILE);
502
503 /* reuse buf */
504 buf = "\n\nSorry, you are not allowed to use this facility!\n";
505 fputs(buf, stdout);
506 }
507 fflush(stdout);
508 return (0);
509 }
510
511 /*
512 * check_luser checks to see if user "luser" has been banned
513 * from using us by virtue of having an file of the same name
514 * in the "luserdir" directory.
515 *
516 * If the user has been banned, we copy the contents of the file
517 * to the user's screen. (useful for telling the user what to
518 * do to get un-banned, or just to tell them they aren't
519 * going to be un-banned.)
520 */
521 static int
522 check_luser(char *luserdir, char *luser)
523 {
524 FILE *f;
525 int n;
526 char tmp[MAXPATHLEN];
527
528 n = snprintf(tmp, sizeof(tmp), "%s/%s", luserdir, luser);
529 if (n < 0 || (u_int)n >= sizeof(tmp)) {
530 syslog(LOG_ERR, "provided banned directory line too long (%s)",
531 luserdir);
532 return (0);
533 }
534 if ((f = fopen(tmp, "r")) == NULL) {
535 if (errno == ENOENT) {
536 /*
537 * file or dir doesn't exist, so therefore
538 * this luser isn't banned.. all is well
539 */
540 return (1);
541 } else {
542 /*
543 * luser may in fact be banned, but we can't open the
544 * file even though it's there. probably a config
545 * problem.
546 */
547 syslog(LOG_ERR, "cannot open banned file %s (%s)",
548 tmp, strerror(errno));
549 return (0);
550 }
551 } else {
552 /*
553 * luser is banned - spit the file at them to
554 * tell what they can do and where they can go.
555 */
556 syslog(LOG_INFO, "denied access to %s: %s exists",
557 luser, tmp);
558
559 /* reuse tmp */
560 strlcpy(tmp, "\n\n-**- Sorry, you have been banned! -**-\n\n",
561 sizeof(tmp));
562 while (fputs(tmp, stdout) != EOF && !feof(f)) {
563 if (fgets(tmp, sizeof(tmp), f) == NULL) {
564 fclose(f);
565 fflush(stdout);
566 fclose(f);
567 return (0);
568 }
569 }
570 fclose(f);
571 }
572 fflush(stdout);
573 return (0);
574 }
575
576 /*
577 * Search for rulesets left by other authpf processes (either because they
578 * died ungracefully or were terminated) and remove them.
579 */
580 static int
581 remove_stale_rulesets(void)
582 {
583 struct pfioc_ruleset prs;
584 u_int32_t nr, mnr;
585
586 memset(&prs, 0, sizeof(prs));
587 strlcpy(prs.path, anchorname, sizeof(prs.path));
588 if (ioctl(dev, DIOCGETRULESETS, &prs)) {
589 if (errno == EINVAL)
590 return (0);
591 else
592 return (1);
593 }
594
595 mnr = prs.nr;
596 nr = 0;
597 while (nr < mnr) {
598 char *s, *t;
599 pid_t pid;
600
601 prs.nr = nr;
602 if (ioctl(dev, DIOCGETRULESET, &prs))
603 return (1);
604 errno = 0;
605 if ((t = strchr(prs.name, '(')) == NULL)
606 t = prs.name;
607 else
608 t++;
609 pid = strtoul(t, &s, 10);
610 if (!prs.name[0] || errno ||
611 (*s && (t == prs.name || *s != ')')))
612 return (1);
613 if (kill(pid, 0) && errno != EPERM) {
614 int i;
615 struct pfioc_trans_e t_e[PF_RULESET_MAX+1];
616 struct pfioc_trans t;
617
618 bzero(&t, sizeof(t));
619 bzero(t_e, sizeof(t_e));
620 t.size = PF_RULESET_MAX+1;
621 t.esize = sizeof(t_e[0]);
622 t.array = t_e;
623 for (i = 0; i < PF_RULESET_MAX+1; ++i) {
624 t_e[i].rs_num = i;
625 snprintf(t_e[i].anchor, sizeof(t_e[i].anchor),
626 "%s/%s", anchorname, prs.name);
627 }
628 t_e[PF_RULESET_MAX].rs_num = PF_RULESET_TABLE;
629 if ((ioctl(dev, DIOCXBEGIN, &t) ||
630 ioctl(dev, DIOCXCOMMIT, &t)) &&
631 errno != EINVAL)
632 return (1);
633 mnr--;
634 } else
635 nr++;
636 }
637 return (0);
638 }
639
640 /*
641 * Add/remove filter entries for user "luser" from ip "ipsrc"
642 */
643 static int
644 change_filter(int add, const char *luser, const char *ipsrc)
645 {
646 char *pargv[13] = {
647 "pfctl", "-p", "/dev/pf", "-q", "-a", "anchor/ruleset",
648 "-D", "user_ip=X", "-D", "user_id=X", "-f",
649 "file", NULL
650 };
651 char *fdpath = NULL, *userstr = NULL, *ipstr = NULL;
652 char *rsn = NULL, *fn = NULL;
653 pid_t pid;
654 gid_t gid;
655 int s;
656
657 if (luser == NULL || !luser[0] || ipsrc == NULL || !ipsrc[0]) {
658 syslog(LOG_ERR, "invalid luser/ipsrc");
659 goto error;
660 }
661
662 if (asprintf(&rsn, "%s/%s", anchorname, rulesetname) == -1)
663 goto no_mem;
664 if (asprintf(&fdpath, "/dev/fd/%d", dev) == -1)
665 goto no_mem;
666 if (asprintf(&ipstr, "user_ip=%s", ipsrc) == -1)
667 goto no_mem;
668 if (asprintf(&userstr, "user_id=%s", luser) == -1)
669 goto no_mem;
670
671 if (add) {
672 struct stat sb;
673
674 if (asprintf(&fn, "%s/%s/authpf.rules", PATH_USER_DIR, luser)
675 == -1)
676 goto no_mem;
677 if (stat(fn, &sb) == -1) {
678 free(fn);
679 if ((fn = strdup(PATH_PFRULES)) == NULL)
680 goto no_mem;
681 }
682 }
683 pargv[2] = fdpath;
684 pargv[5] = rsn;
685 pargv[7] = userstr;
686 pargv[9] = ipstr;
687 if (!add)
688 pargv[11] = "/dev/null";
689 else
690 pargv[11] = fn;
691
692 switch (pid = fork()) {
693 case -1:
694 syslog(LOG_ERR, "fork failed");
695 goto error;
696 case 0:
697 /* revoke group privs before exec */
698 gid = getgid();
699 if (setregid(gid, gid) == -1) {
700 err(1, "setregid");
701 }
702 execvp(PATH_PFCTL, pargv);
703 warn("exec of %s failed", PATH_PFCTL);
704 _exit(1);
705 }
706
707 /* parent */
708 waitpid(pid, &s, 0);
709 if (s != 0) {
710 syslog(LOG_ERR, "pfctl exited abnormally");
711 goto error;
712 }
713
714 if (add) {
715 gettimeofday(&Tstart, NULL);
716 syslog(LOG_INFO, "allowing %s, user %s", ipsrc, luser);
717 } else {
718 gettimeofday(&Tend, NULL);
719 syslog(LOG_INFO, "removed %s, user %s - duration %ld seconds",
720 ipsrc, luser, Tend.tv_sec - Tstart.tv_sec);
721 }
722 return (0);
723 no_mem:
724 syslog(LOG_ERR, "malloc failed");
725 error:
726 free(fdpath);
727 free(rsn);
728 free(userstr);
729 free(ipstr);
730 free(fn);
731 return (-1);
732 }
733
734 /*
735 * Add/remove this IP from the "authpf_users" table.
736 */
737 static int
738 change_table(int add, const char *ipsrc)
739 {
740 struct pfioc_table io;
741 struct pfr_addr addr;
742
743 bzero(&io, sizeof(io));
744 strlcpy(io.pfrio_table.pfrt_name, tablename,
745 sizeof(io.pfrio_table.pfrt_name));
746 io.pfrio_buffer = &addr;
747 io.pfrio_esize = sizeof(addr);
748 io.pfrio_size = 1;
749
750 bzero(&addr, sizeof(addr));
751 if (ipsrc == NULL || !ipsrc[0])
752 return (-1);
753 if (inet_pton(AF_INET, ipsrc, &addr.pfra_ip4addr) == 1) {
754 addr.pfra_af = AF_INET;
755 addr.pfra_net = 32;
756 } else if (inet_pton(AF_INET6, ipsrc, &addr.pfra_ip6addr) == 1) {
757 addr.pfra_af = AF_INET6;
758 addr.pfra_net = 128;
759 } else {
760 syslog(LOG_ERR, "invalid ipsrc");
761 return (-1);
762 }
763
764 if (ioctl(dev, add ? DIOCRADDADDRS : DIOCRDELADDRS, &io) &&
765 errno != ESRCH) {
766 syslog(LOG_ERR, "cannot %s %s from table %s: %s",
767 add ? "add" : "remove", ipsrc, tablename,
768 strerror(errno));
769 return (-1);
770 }
771 return (0);
772 }
773
774 /*
775 * This is to kill off states that would otherwise be left behind stateful
776 * rules. This means we don't need to allow in more traffic than we really
777 * want to, since we don't have to worry about any luser sessions lasting
778 * longer than their ssh session. This function is based on
779 * pfctl_kill_states from pfctl.
780 */
781 static void
782 authpf_kill_states(void)
783 {
784 struct pfioc_state_kill psk;
785 struct pf_addr target;
786
787 memset(&psk, 0, sizeof(psk));
788 memset(&target, 0, sizeof(target));
789
790 if (inet_pton(AF_INET, ipsrc, &target.v4) == 1)
791 psk.psk_af = AF_INET;
792 else if (inet_pton(AF_INET6, ipsrc, &target.v6) == 1)
793 psk.psk_af = AF_INET6;
794 else {
795 syslog(LOG_ERR, "inet_pton(%s) failed", ipsrc);
796 return;
797 }
798
799 /* Kill all states from ipsrc */
800 memcpy(&psk.psk_src.addr.v.a.addr, &target,
801 sizeof(psk.psk_src.addr.v.a.addr));
802 memset(&psk.psk_src.addr.v.a.mask, 0xff,
803 sizeof(psk.psk_src.addr.v.a.mask));
804 if (ioctl(dev, DIOCKILLSTATES, &psk))
805 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
806
807 /* Kill all states to ipsrc */
808 memset(&psk.psk_src, 0, sizeof(psk.psk_src));
809 memcpy(&psk.psk_dst.addr.v.a.addr, &target,
810 sizeof(psk.psk_dst.addr.v.a.addr));
811 memset(&psk.psk_dst.addr.v.a.mask, 0xff,
812 sizeof(psk.psk_dst.addr.v.a.mask));
813 if (ioctl(dev, DIOCKILLSTATES, &psk))
814 syslog(LOG_ERR, "DIOCKILLSTATES failed (%m)");
815 }
816
817 /* signal handler that makes us go away properly */
818 static void
819 need_death(int signo)
820 {
821 want_death = 1;
822 }
823
824 /*
825 * function that removes our stuff when we go away.
826 */
827 static __dead void
828 do_death(int active)
829 {
830 int ret = 0;
831
832 if (active) {
833 change_filter(0, luser, ipsrc);
834 change_table(0, ipsrc);
835 authpf_kill_states();
836 remove_stale_rulesets();
837 }
838 if (pidfile[0] && (pidfp != NULL))
839 if (unlink(pidfile) == -1)
840 syslog(LOG_ERR, "cannot unlink %s (%m)", pidfile);
841 exit(ret);
842 }
843