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