pf: Update packet filter to the version that comes with OpenBSD 4.1
[dragonfly.git] / usr.sbin / pfctl / pfctl_parser.c
1 /*      $OpenBSD: pfctl_parser.c,v 1.234 2006/10/31 23:46:24 mcbride Exp $ */
2
3 /*
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002,2003 Henning Brauer
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  *    - Redistributions of source code must retain the above copyright
13  *      notice, this list of conditions and the following disclaimer.
14  *    - Redistributions in binary form must reproduce the above
15  *      copyright notice, this list of conditions and the following
16  *      disclaimer in the documentation and/or other materials provided
17  *      with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <sys/socket.h>
37 #include <sys/param.h>
38 #include <sys/user.h>
39 #include <net/if.h>
40 #include <netinet/in.h>
41 #include <netinet/in_systm.h>
42 #include <netinet/ip.h>
43 #include <netinet/ip_icmp.h>
44 #include <netinet/icmp6.h>
45 #include <net/pf/pfvar.h>
46 #include <arpa/inet.h>
47
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <ctype.h>
52 #include <netdb.h>
53 #include <stdarg.h>
54 #include <errno.h>
55 #include <err.h>
56 #include <ifaddrs.h>
57 #include <unistd.h>
58
59 #include "pfctl_parser.h"
60 #include "pfctl.h"
61
62 void             print_op (u_int8_t, const char *, const char *);
63 void             print_port (u_int8_t, u_int16_t, u_int16_t, const char *);
64 void             print_ugid (u_int8_t, unsigned, unsigned, const char *, unsigned);
65 void             print_flags (u_int8_t);
66 void             print_fromto(struct pf_rule_addr *, pf_osfp_t,
67                     struct pf_rule_addr *, u_int8_t, u_int8_t, int);
68 int              ifa_skip_if(const char *filter, struct node_host *p);
69
70 struct node_host        *ifa_grouplookup(const char *, int);
71 struct node_host        *host_if(const char *, int);
72 static struct node_host *host_v4(const char *);
73 struct node_host        *host_v6(const char *, int);
74 struct node_host        *host_dns(const char *, int, int);
75
76 const char *tcpflags = "FSRPAUEW";
77
78 static const struct icmptypeent icmp_type[] = {
79         { "echoreq",    ICMP_ECHO },
80         { "echorep",    ICMP_ECHOREPLY },
81         { "unreach",    ICMP_UNREACH },
82         { "squench",    ICMP_SOURCEQUENCH },
83         { "redir",      ICMP_REDIRECT },
84         { "althost",    ICMP_ALTHOSTADDR },
85         { "routeradv",  ICMP_ROUTERADVERT },
86         { "routersol",  ICMP_ROUTERSOLICIT },
87         { "timex",      ICMP_TIMXCEED },
88         { "paramprob",  ICMP_PARAMPROB },
89         { "timereq",    ICMP_TSTAMP },
90         { "timerep",    ICMP_TSTAMPREPLY },
91         { "inforeq",    ICMP_IREQ },
92         { "inforep",    ICMP_IREQREPLY },
93         { "maskreq",    ICMP_MASKREQ },
94         { "maskrep",    ICMP_MASKREPLY },
95         { "trace",      ICMP_TRACEROUTE },
96         { "dataconv",   ICMP_DATACONVERR },
97         { "mobredir",   ICMP_MOBILE_REDIRECT },
98         { "ipv6-where", ICMP_IPV6_WHEREAREYOU },
99         { "ipv6-here",  ICMP_IPV6_IAMHERE },
100         { "mobregreq",  ICMP_MOBILE_REGREQUEST },
101         { "mobregrep",  ICMP_MOBILE_REGREPLY },
102         { "skip",       ICMP_SKIP },
103         { "photuris",   ICMP_PHOTURIS }
104 };
105
106 static const struct icmptypeent icmp6_type[] = {
107         { "unreach",    ICMP6_DST_UNREACH },
108         { "toobig",     ICMP6_PACKET_TOO_BIG },
109         { "timex",      ICMP6_TIME_EXCEEDED },
110         { "paramprob",  ICMP6_PARAM_PROB },
111         { "echoreq",    ICMP6_ECHO_REQUEST },
112         { "echorep",    ICMP6_ECHO_REPLY },
113         { "groupqry",   ICMP6_MEMBERSHIP_QUERY },
114         { "listqry",    MLD_LISTENER_QUERY },
115         { "grouprep",   ICMP6_MEMBERSHIP_REPORT },
116         { "listenrep",  MLD_LISTENER_REPORT },
117         { "groupterm",  ICMP6_MEMBERSHIP_REDUCTION },
118         { "listendone", MLD_LISTENER_DONE },
119         { "routersol",  ND_ROUTER_SOLICIT },
120         { "routeradv",  ND_ROUTER_ADVERT },
121         { "neighbrsol", ND_NEIGHBOR_SOLICIT },
122         { "neighbradv", ND_NEIGHBOR_ADVERT },
123         { "redir",      ND_REDIRECT },
124         { "routrrenum", ICMP6_ROUTER_RENUMBERING },
125         { "wrureq",     ICMP6_WRUREQUEST },
126         { "wrurep",     ICMP6_WRUREPLY },
127         { "fqdnreq",    ICMP6_FQDN_QUERY },
128         { "fqdnrep",    ICMP6_FQDN_REPLY },
129         { "niqry",      ICMP6_NI_QUERY },
130         { "nirep",      ICMP6_NI_REPLY },
131         { "mtraceresp", MLD_MTRACE_RESP },
132         { "mtrace",     MLD_MTRACE }
133 };
134
135 static const struct icmpcodeent icmp_code[] = {
136         { "net-unr",            ICMP_UNREACH,   ICMP_UNREACH_NET },
137         { "host-unr",           ICMP_UNREACH,   ICMP_UNREACH_HOST },
138         { "proto-unr",          ICMP_UNREACH,   ICMP_UNREACH_PROTOCOL },
139         { "port-unr",           ICMP_UNREACH,   ICMP_UNREACH_PORT },
140         { "needfrag",           ICMP_UNREACH,   ICMP_UNREACH_NEEDFRAG },
141         { "srcfail",            ICMP_UNREACH,   ICMP_UNREACH_SRCFAIL },
142         { "net-unk",            ICMP_UNREACH,   ICMP_UNREACH_NET_UNKNOWN },
143         { "host-unk",           ICMP_UNREACH,   ICMP_UNREACH_HOST_UNKNOWN },
144         { "isolate",            ICMP_UNREACH,   ICMP_UNREACH_ISOLATED },
145         { "net-prohib",         ICMP_UNREACH,   ICMP_UNREACH_NET_PROHIB },
146         { "host-prohib",        ICMP_UNREACH,   ICMP_UNREACH_HOST_PROHIB },
147         { "net-tos",            ICMP_UNREACH,   ICMP_UNREACH_TOSNET },
148         { "host-tos",           ICMP_UNREACH,   ICMP_UNREACH_TOSHOST },
149         { "filter-prohib",      ICMP_UNREACH,   ICMP_UNREACH_FILTER_PROHIB },
150         { "host-preced",        ICMP_UNREACH,   ICMP_UNREACH_HOST_PRECEDENCE },
151         { "cutoff-preced",      ICMP_UNREACH,   ICMP_UNREACH_PRECEDENCE_CUTOFF },
152         { "redir-net",          ICMP_REDIRECT,  ICMP_REDIRECT_NET },
153         { "redir-host",         ICMP_REDIRECT,  ICMP_REDIRECT_HOST },
154         { "redir-tos-net",      ICMP_REDIRECT,  ICMP_REDIRECT_TOSNET },
155         { "redir-tos-host",     ICMP_REDIRECT,  ICMP_REDIRECT_TOSHOST },
156         { "normal-adv",         ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NORMAL },
157         { "common-adv",         ICMP_ROUTERADVERT, ICMP_ROUTERADVERT_NOROUTE_COMMON },
158         { "transit",            ICMP_TIMXCEED,  ICMP_TIMXCEED_INTRANS },
159         { "reassemb",           ICMP_TIMXCEED,  ICMP_TIMXCEED_REASS },
160         { "badhead",            ICMP_PARAMPROB, ICMP_PARAMPROB_ERRATPTR },
161         { "optmiss",            ICMP_PARAMPROB, ICMP_PARAMPROB_OPTABSENT },
162         { "badlen",             ICMP_PARAMPROB, ICMP_PARAMPROB_LENGTH },
163         { "unknown-ind",        ICMP_PHOTURIS,  ICMP_PHOTURIS_UNKNOWN_INDEX },
164         { "auth-fail",          ICMP_PHOTURIS,  ICMP_PHOTURIS_AUTH_FAILED },
165         { "decrypt-fail",       ICMP_PHOTURIS,  ICMP_PHOTURIS_DECRYPT_FAILED }
166 };
167
168 static const struct icmpcodeent icmp6_code[] = {
169         { "admin-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN },
170         { "noroute-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE },
171         { "notnbr-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOTNEIGHBOR },
172         { "beyond-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_BEYONDSCOPE },
173         { "addr-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR },
174         { "port-unr", ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT },
175         { "transit", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_TRANSIT },
176         { "reassemb", ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_REASSEMBLY },
177         { "badhead", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER },
178         { "nxthdr", ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER },
179         { "redironlink", ND_REDIRECT, ND_REDIRECT_ONLINK },
180         { "redirrouter", ND_REDIRECT, ND_REDIRECT_ROUTER }
181 };
182
183 const struct pf_timeout pf_timeouts[] = {
184         { "tcp.first",          PFTM_TCP_FIRST_PACKET },
185         { "tcp.opening",        PFTM_TCP_OPENING },
186         { "tcp.established",    PFTM_TCP_ESTABLISHED },
187         { "tcp.closing",        PFTM_TCP_CLOSING },
188         { "tcp.finwait",        PFTM_TCP_FIN_WAIT },
189         { "tcp.closed",         PFTM_TCP_CLOSED },
190         { "tcp.tsdiff",         PFTM_TS_DIFF },
191         { "udp.first",          PFTM_UDP_FIRST_PACKET },
192         { "udp.single",         PFTM_UDP_SINGLE },
193         { "udp.multiple",       PFTM_UDP_MULTIPLE },
194         { "icmp.first",         PFTM_ICMP_FIRST_PACKET },
195         { "icmp.error",         PFTM_ICMP_ERROR_REPLY },
196         { "other.first",        PFTM_OTHER_FIRST_PACKET },
197         { "other.single",       PFTM_OTHER_SINGLE },
198         { "other.multiple",     PFTM_OTHER_MULTIPLE },
199         { "frag",               PFTM_FRAG },
200         { "interval",           PFTM_INTERVAL },
201         { "adaptive.start",     PFTM_ADAPTIVE_START },
202         { "adaptive.end",       PFTM_ADAPTIVE_END },
203         { "src.track",          PFTM_SRC_NODE },
204         { NULL,                 0 }
205 };
206
207 const struct icmptypeent *
208 geticmptypebynumber(u_int8_t type, sa_family_t af)
209 {
210         unsigned int    i;
211
212         if (af != AF_INET6) {
213                 for (i=0; i < (sizeof (icmp_type) / sizeof(icmp_type[0]));
214                     i++) {
215                         if (type == icmp_type[i].type)
216                                 return (&icmp_type[i]);
217                 }
218         } else {
219                 for (i=0; i < (sizeof (icmp6_type) /
220                     sizeof(icmp6_type[0])); i++) {
221                         if (type == icmp6_type[i].type)
222                                  return (&icmp6_type[i]);
223                 }
224         }
225         return (NULL);
226 }
227
228 const struct icmptypeent *
229 geticmptypebyname(char *w, sa_family_t af)
230 {
231         unsigned int    i;
232
233         if (af != AF_INET6) {
234                 for (i=0; i < (sizeof (icmp_type) / sizeof(icmp_type[0]));
235                     i++) {
236                         if (!strcmp(w, icmp_type[i].name))
237                                 return (&icmp_type[i]);
238                 }
239         } else {
240                 for (i=0; i < (sizeof (icmp6_type) /
241                     sizeof(icmp6_type[0])); i++) {
242                         if (!strcmp(w, icmp6_type[i].name))
243                                 return (&icmp6_type[i]);
244                 }
245         }
246         return (NULL);
247 }
248
249 const struct icmpcodeent *
250 geticmpcodebynumber(u_int8_t type, u_int8_t code, sa_family_t af)
251 {
252         unsigned int    i;
253
254         if (af != AF_INET6) {
255                 for (i=0; i < (sizeof (icmp_code) / sizeof(icmp_code[0]));
256                     i++) {
257                         if (type == icmp_code[i].type &&
258                             code == icmp_code[i].code)
259                                 return (&icmp_code[i]);
260                 }
261         } else {
262                 for (i=0; i < (sizeof (icmp6_code) /
263                     sizeof(icmp6_code[0])); i++) {
264                         if (type == icmp6_code[i].type &&
265                             code == icmp6_code[i].code)
266                                 return (&icmp6_code[i]);
267                 }
268         }
269         return (NULL);
270 }
271
272 const struct icmpcodeent *
273 geticmpcodebyname(u_long type, char *w, sa_family_t af)
274 {
275         unsigned int    i;
276
277         if (af != AF_INET6) {
278                 for (i=0; i < (sizeof (icmp_code) / sizeof(icmp_code[0]));
279                     i++) {
280                         if (type == icmp_code[i].type &&
281                             !strcmp(w, icmp_code[i].name))
282                                 return (&icmp_code[i]);
283                 }
284         } else {
285                 for (i=0; i < (sizeof (icmp6_code) /
286                     sizeof(icmp6_code[0])); i++) {
287                         if (type == icmp6_code[i].type &&
288                             !strcmp(w, icmp6_code[i].name))
289                                 return (&icmp6_code[i]);
290                 }
291         }
292         return (NULL);
293 }
294
295 void
296 print_op(u_int8_t op, const char *a1, const char *a2)
297 {
298         if (op == PF_OP_IRG)
299                 printf(" %s >< %s", a1, a2);
300         else if (op == PF_OP_XRG)
301                 printf(" %s <> %s", a1, a2);
302         else if (op == PF_OP_EQ)
303                 printf(" = %s", a1);
304         else if (op == PF_OP_NE)
305                 printf(" != %s", a1);
306         else if (op == PF_OP_LT)
307                 printf(" < %s", a1);
308         else if (op == PF_OP_LE)
309                 printf(" <= %s", a1);
310         else if (op == PF_OP_GT)
311                 printf(" > %s", a1);
312         else if (op == PF_OP_GE)
313                 printf(" >= %s", a1);
314         else if (op == PF_OP_RRG)
315                 printf(" %s:%s", a1, a2);
316 }
317
318 void
319 print_port(u_int8_t op, u_int16_t p1, u_int16_t p2, const char *proto)
320 {
321         char             a1[6], a2[6];
322         struct servent  *s;
323
324         s = getservbyport(p1, proto);
325         p1 = ntohs(p1);
326         p2 = ntohs(p2);
327         snprintf(a1, sizeof(a1), "%u", p1);
328         snprintf(a2, sizeof(a2), "%u", p2);
329         printf(" port");
330         if (s != NULL && (op == PF_OP_EQ || op == PF_OP_NE))
331                 print_op(op, s->s_name, a2);
332         else
333                 print_op(op, a1, a2);
334 }
335
336 void
337 print_ugid(u_int8_t op, unsigned u1, unsigned u2, const char *t, unsigned umax)
338 {
339         char    a1[11], a2[11];
340
341         snprintf(a1, sizeof(a1), "%u", u1);
342         snprintf(a2, sizeof(a2), "%u", u2);
343         printf(" %s", t);
344         if (u1 == umax && (op == PF_OP_EQ || op == PF_OP_NE))
345                 print_op(op, "unknown", a2);
346         else
347                 print_op(op, a1, a2);
348 }
349
350 void
351 print_flags(u_int8_t f)
352 {
353         int     i;
354
355         for (i = 0; tcpflags[i]; ++i)
356                 if (f & (1 << i))
357                         printf("%c", tcpflags[i]);
358 }
359
360 void
361 print_fromto(struct pf_rule_addr *src, pf_osfp_t osfp, struct pf_rule_addr *dst,
362     sa_family_t af, u_int8_t proto, int verbose)
363 {
364         char buf[PF_OSFP_LEN*3];
365         if (src->addr.type == PF_ADDR_ADDRMASK &&
366             dst->addr.type == PF_ADDR_ADDRMASK &&
367             PF_AZERO(&src->addr.v.a.addr, AF_INET6) &&
368             PF_AZERO(&src->addr.v.a.mask, AF_INET6) &&
369             PF_AZERO(&dst->addr.v.a.addr, AF_INET6) &&
370             PF_AZERO(&dst->addr.v.a.mask, AF_INET6) &&
371             !src->neg && !dst->neg &&
372             !src->port_op && !dst->port_op &&
373             osfp == PF_OSFP_ANY)
374                 printf(" all");
375         else {
376                 printf(" from ");
377                 if (src->neg)
378                         printf("! ");
379                 print_addr(&src->addr, af, verbose);
380                 if (src->port_op)
381                         print_port(src->port_op, src->port[0],
382                             src->port[1],
383                             proto == IPPROTO_TCP ? "tcp" : "udp");
384                 if (osfp != PF_OSFP_ANY)
385                         printf(" os \"%s\"", pfctl_lookup_fingerprint(osfp, buf,
386                             sizeof(buf)));
387
388                 printf(" to ");
389                 if (dst->neg)
390                         printf("! ");
391                 print_addr(&dst->addr, af, verbose);
392                 if (dst->port_op)
393                         print_port(dst->port_op, dst->port[0],
394                             dst->port[1],
395                             proto == IPPROTO_TCP ? "tcp" : "udp");
396         }
397 }
398
399 void
400 print_pool(struct pf_pool *pool, u_int16_t p1, u_int16_t p2,
401     sa_family_t af, int id)
402 {
403         struct pf_pooladdr      *pooladdr;
404
405         if ((TAILQ_FIRST(&pool->list) != NULL) &&
406             TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
407                 printf("{ ");
408         TAILQ_FOREACH(pooladdr, &pool->list, entries){
409                 switch (id) {
410                 case PF_NAT:
411                 case PF_RDR:
412                 case PF_BINAT:
413                         print_addr(&pooladdr->addr, af, 0);
414                         break;
415                 case PF_PASS:
416                         if (PF_AZERO(&pooladdr->addr.v.a.addr, af))
417                                 printf("%s", pooladdr->ifname);
418                         else {
419                                 printf("(%s ", pooladdr->ifname);
420                                 print_addr(&pooladdr->addr, af, 0);
421                                 printf(")");
422                         }
423                         break;
424                 default:
425                         break;
426                 }
427                 if (TAILQ_NEXT(pooladdr, entries) != NULL)
428                         printf(", ");
429                 else if (TAILQ_NEXT(TAILQ_FIRST(&pool->list), entries) != NULL)
430                         printf(" }");
431         }
432         switch (id) {
433         case PF_NAT:
434                 if ((p1 != PF_NAT_PROXY_PORT_LOW ||
435                     p2 != PF_NAT_PROXY_PORT_HIGH) && (p1 != 0 || p2 != 0)) {
436                         if (p1 == p2)
437                                 printf(" port %u", p1);
438                         else
439                                 printf(" port %u:%u", p1, p2);
440                 }
441                 break;
442         case PF_RDR:
443                 if (p1) {
444                         printf(" port %u", p1);
445                         if (p2 && (p2 != p1))
446                                 printf(":%u", p2);
447                 }
448                 break;
449         default:
450                 break;
451         }
452         switch (pool->opts & PF_POOL_TYPEMASK) {
453         case PF_POOL_NONE:
454                 break;
455         case PF_POOL_BITMASK:
456                 printf(" bitmask");
457                 break;
458         case PF_POOL_RANDOM:
459                 printf(" random");
460                 break;
461         case PF_POOL_SRCHASH:
462                 printf(" source-hash 0x%08x%08x%08x%08x",
463                     pool->key.key32[0], pool->key.key32[1],
464                     pool->key.key32[2], pool->key.key32[3]);
465                 break;
466         case PF_POOL_ROUNDROBIN:
467                 printf(" round-robin");
468                 break;
469         }
470         if (pool->opts & PF_POOL_STICKYADDR)
471                 printf(" sticky-address");
472         if (id == PF_NAT && p1 == 0 && p2 == 0)
473                 printf(" static-port");
474 }
475
476 const char      *pf_reasons[PFRES_MAX+1] = PFRES_NAMES;
477 const char      *pf_lcounters[LCNT_MAX+1] = LCNT_NAMES;
478 const char      *pf_fcounters[FCNT_MAX+1] = FCNT_NAMES;
479 const char      *pf_scounters[FCNT_MAX+1] = FCNT_NAMES;
480
481 void
482 print_status(struct pf_status *s, int opts)
483 {
484         char                    statline[80];
485         const char *running;
486         time_t                  runtime;
487         int                     i;
488         char                    buf[PF_MD5_DIGEST_LENGTH * 2 + 1];
489         static const char       hex[] = "0123456789abcdef";
490
491         runtime = time(NULL) - s->since;
492         running = s->running ? "Enabled" : "Disabled";
493
494         if (s->since) {
495                 unsigned        sec, min, hrs, day = runtime;
496
497                 sec = day % 60;
498                 day /= 60;
499                 min = day % 60;
500                 day /= 60;
501                 hrs = day % 24;
502                 day /= 24;
503                 snprintf(statline, sizeof(statline),
504                     "Status: %s for %u days %.2u:%.2u:%.2u",
505                     running, day, hrs, min, sec);
506         } else
507                 snprintf(statline, sizeof(statline), "Status: %s", running);
508         printf("%-44s", statline);
509         switch (s->debug) {
510         case PF_DEBUG_NONE:
511                 printf("%15s\n\n", "Debug: None");
512                 break;
513         case PF_DEBUG_URGENT:
514                 printf("%15s\n\n", "Debug: Urgent");
515                 break;
516         case PF_DEBUG_MISC:
517                 printf("%15s\n\n", "Debug: Misc");
518                 break;
519         case PF_DEBUG_NOISY:
520                 printf("%15s\n\n", "Debug: Loud");
521                 break;
522         }
523
524         if (opts & PF_OPT_VERBOSE) {
525                 printf("Hostid:   0x%08x\n", ntohl(s->hostid));
526
527                 for (i = 0; i < PF_MD5_DIGEST_LENGTH; i++) {
528                         buf[i + i] = hex[s->pf_chksum[i] >> 4];
529                         buf[i + i + 1] = hex[s->pf_chksum[i] & 0x0f];
530                 }
531                 buf[i + i] = '\0';
532                 printf("Checksum: 0x%s\n\n", buf);
533         }
534
535         if (s->ifname[0] != 0) {
536                 printf("Interface Stats for %-16s %5s %16s\n",
537                     s->ifname, "IPv4", "IPv6");
538                 printf("  %-25s %14llu %16llu\n", "Bytes In",
539                     (unsigned long long)s->bcounters[0][0],
540                     (unsigned long long)s->bcounters[1][0]);
541                 printf("  %-25s %14llu %16llu\n", "Bytes Out",
542                     (unsigned long long)s->bcounters[0][1],
543                     (unsigned long long)s->bcounters[1][1]);
544                 printf("  Packets In\n");
545                 printf("    %-23s %14llu %16llu\n", "Passed",
546                     (unsigned long long)s->pcounters[0][0][PF_PASS],
547                     (unsigned long long)s->pcounters[1][0][PF_PASS]);
548                 printf("    %-23s %14llu %16llu\n", "Blocked",
549                     (unsigned long long)s->pcounters[0][0][PF_DROP],
550                     (unsigned long long)s->pcounters[1][0][PF_DROP]);
551                 printf("  Packets Out\n");
552                 printf("    %-23s %14llu %16llu\n", "Passed",
553                     (unsigned long long)s->pcounters[0][1][PF_PASS],
554                     (unsigned long long)s->pcounters[1][1][PF_PASS]);
555                 printf("    %-23s %14llu %16llu\n\n", "Blocked",
556                     (unsigned long long)s->pcounters[0][1][PF_DROP],
557                     (unsigned long long)s->pcounters[1][1][PF_DROP]);
558         }
559         printf("%-27s %14s %16s\n", "State Table", "Total", "Rate");
560         printf("  %-25s %14u %14s\n", "current entries", s->states, "");
561         for (i = 0; i < FCNT_MAX; i++) {
562                 printf("  %-25s %14llu ", pf_fcounters[i],
563                             (unsigned long long)s->fcounters[i]);
564                 if (runtime > 0)
565                         printf("%14.1f/s\n",
566                             (double)s->fcounters[i] / (double)runtime);
567                 else
568                         printf("%14s\n", "");
569         }
570         if (opts & PF_OPT_VERBOSE) {
571                 printf("Source Tracking Table\n");
572                 printf("  %-25s %14u %14s\n", "current entries",
573                     s->src_nodes, "");
574                 for (i = 0; i < SCNT_MAX; i++) {
575                         printf("  %-25s %14lld ", pf_scounters[i],
576                                     (unsigned long long)s->scounters[i]);
577                         if (runtime > 0)
578                                 printf("%14.1f/s\n",
579                                     (double)s->scounters[i] / (double)runtime);
580                         else
581                                 printf("%14s\n", "");
582                 }
583         }
584         printf("Counters\n");
585         for (i = 0; i < PFRES_MAX; i++) {
586                 printf("  %-25s %14llu ", pf_reasons[i],
587                     (unsigned long long)s->counters[i]);
588                 if (runtime > 0)
589                         printf("%14.1f/s\n",
590                             (double)s->counters[i] / (double)runtime);
591                 else
592                         printf("%14s\n", "");
593         }
594         if (opts & PF_OPT_VERBOSE) {
595                 printf("Limit Counters\n");
596                 for (i = 0; i < LCNT_MAX; i++) {
597                         printf("  %-25s %14lld ", pf_lcounters[i],
598                                     s->lcounters[i]);
599                         if (runtime > 0)
600                                 printf("%14.1f/s\n",
601                                     (double)s->lcounters[i] / (double)runtime);
602                         else
603                                 printf("%14s\n", "");
604                 }
605         }
606 }
607
608 void
609 print_src_node(struct pf_src_node *sn, int opts)
610 {
611         struct pf_addr_wrap aw;
612         int min, sec;
613
614         memset(&aw, 0, sizeof(aw));
615         if (sn->af == AF_INET)
616                 aw.v.a.mask.addr32[0] = 0xffffffff;
617         else
618                 memset(&aw.v.a.mask, 0xff, sizeof(aw.v.a.mask));
619
620         aw.v.a.addr = sn->addr;
621         print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
622         printf(" -> ");
623         aw.v.a.addr = sn->raddr;
624         print_addr(&aw, sn->af, opts & PF_OPT_VERBOSE2);
625         printf(" ( states %u, connections %u, rate %u.%u/%us )\n", sn->states,
626             sn->conn, sn->conn_rate.count / 1000,
627             (sn->conn_rate.count % 1000) / 100, sn->conn_rate.seconds);
628         if (opts & PF_OPT_VERBOSE) {
629                 sec = sn->creation % 60;
630                 sn->creation /= 60;
631                 min = sn->creation % 60;
632                 sn->creation /= 60;
633                 printf("   age %.2u:%.2u:%.2u", sn->creation, min, sec);
634                 if (sn->states == 0) {
635                         sec = sn->expire % 60;
636                         sn->expire /= 60;
637                         min = sn->expire % 60;
638                         sn->expire /= 60;
639                         printf(", expires in %.2u:%.2u:%.2u",
640                             sn->expire, min, sec);
641                 }
642                 printf(", %llu pkts, %llu bytes",
643                     sn->packets[0] + sn->packets[1],
644                     sn->bytes[0] + sn->bytes[1]);
645                 switch (sn->ruletype) {
646                 case PF_NAT:
647                         if (sn->rule.nr != (uint32_t)(-1))
648                                 printf(", nat rule %u", sn->rule.nr);
649                         break;
650                 case PF_RDR:
651                         if (sn->rule.nr != (uint32_t)(-1))
652                                 printf(", rdr rule %u", sn->rule.nr);
653                         break;
654                 case PF_PASS:
655                         if (sn->rule.nr != (uint32_t)(-1))
656                                 printf(", filter rule %u", sn->rule.nr);
657                         break;
658                 }
659                 printf("\n");
660         }
661 }
662
663 void
664 print_rule(struct pf_rule *r, const char *anchor_call, int verbose)
665 {
666         static const char *actiontypes[] = { "pass", "block", "scrub",
667             "no scrub", "nat", "no nat", "binat", "no binat", "rdr", "no rdr" };
668         static const char *anchortypes[] = { "anchor", "anchor", "anchor",
669             "anchor", "nat-anchor", "nat-anchor", "binat-anchor",
670             "binat-anchor", "rdr-anchor", "rdr-anchor" };
671         int     i, opts;
672
673         if (verbose)
674                 printf("@%d ", r->nr);
675         if (r->action > PF_NORDR)
676                 printf("action(%d)", r->action);
677         else if (anchor_call[0]) {
678                 if (anchor_call[0] == '_') {
679                         printf("%s", anchortypes[r->action]);
680                 } else
681                         printf("%s \"%s\"", anchortypes[r->action],
682                             anchor_call);
683         } else {
684                 printf("%s", actiontypes[r->action]);
685                 if (r->natpass)
686                         printf(" pass");
687         }
688         if (r->action == PF_DROP) {
689                 if (r->rule_flag & PFRULE_RETURN)
690                         printf(" return");
691                 else if (r->rule_flag & PFRULE_RETURNRST) {
692                         if (!r->return_ttl)
693                                 printf(" return-rst");
694                         else
695                                 printf(" return-rst(ttl %d)", r->return_ttl);
696                 } else if (r->rule_flag & PFRULE_RETURNICMP) {
697                         const struct icmpcodeent        *ic, *ic6;
698
699                         ic = geticmpcodebynumber(r->return_icmp >> 8,
700                             r->return_icmp & 255, AF_INET);
701                         ic6 = geticmpcodebynumber(r->return_icmp6 >> 8,
702                             r->return_icmp6 & 255, AF_INET6);
703
704                         switch (r->af) {
705                         case AF_INET:
706                                 printf(" return-icmp");
707                                 if (ic == NULL)
708                                         printf("(%u)", r->return_icmp & 255);
709                                 else
710                                         printf("(%s)", ic->name);
711                                 break;
712                         case AF_INET6:
713                                 printf(" return-icmp6");
714                                 if (ic6 == NULL)
715                                         printf("(%u)", r->return_icmp6 & 255);
716                                 else
717                                         printf("(%s)", ic6->name);
718                                 break;
719                         default:
720                                 printf(" return-icmp");
721                                 if (ic == NULL)
722                                         printf("(%u, ", r->return_icmp & 255);
723                                 else
724                                         printf("(%s, ", ic->name);
725                                 if (ic6 == NULL)
726                                         printf("%u)", r->return_icmp6 & 255);
727                                 else
728                                         printf("%s)", ic6->name);
729                                 break;
730                         }
731                 } else
732                         printf(" drop");
733         }
734         if (r->direction == PF_IN)
735                 printf(" in");
736         else if (r->direction == PF_OUT)
737                 printf(" out");
738         if (r->log) {
739                 printf(" log");
740                 if (r->log & ~PF_LOG || r->logif) {
741                         int count = 0;
742
743                         printf(" (");
744                         if (r->log & PF_LOG_ALL)
745                                 printf("%sall", count++ ? ", " : "");
746                         if (r->log & PF_LOG_SOCKET_LOOKUP)
747                                 printf("%suser", count++ ? ", " : "");
748                         if (r->logif)
749                                 printf("%sto pflog%u", count++ ? ", " : "",
750                                     r->logif);
751                         printf(")");
752                 }
753         }
754         if (r->quick)
755                 printf(" quick");
756         if (r->ifname[0]) {
757                 if (r->ifnot)
758                         printf(" on ! %s", r->ifname);
759                 else
760                         printf(" on %s", r->ifname);
761         }
762         if (r->rt) {
763                 if (r->rt == PF_ROUTETO)
764                         printf(" route-to");
765                 else if (r->rt == PF_REPLYTO)
766                         printf(" reply-to");
767                 else if (r->rt == PF_DUPTO)
768                         printf(" dup-to");
769                 else if (r->rt == PF_FASTROUTE)
770                         printf(" fastroute");
771                 if (r->rt != PF_FASTROUTE) {
772                         printf(" ");
773                         print_pool(&r->rpool, 0, 0, r->af, PF_PASS);
774                 }
775         }
776         if (r->af) {
777                 if (r->af == AF_INET)
778                         printf(" inet");
779                 else
780                         printf(" inet6");
781         }
782         if (r->proto) {
783                 struct protoent *p;
784
785                 if ((p = getprotobynumber(r->proto)) != NULL)
786                         printf(" proto %s", p->p_name);
787                 else
788                         printf(" proto %u", r->proto);
789         }
790         print_fromto(&r->src, r->os_fingerprint, &r->dst, r->af, r->proto,
791             verbose);
792         if (r->uid.op)
793                 print_ugid(r->uid.op, r->uid.uid[0], r->uid.uid[1], "user",
794                     UID_MAX);
795         if (r->gid.op)
796                 print_ugid(r->gid.op, r->gid.gid[0], r->gid.gid[1], "group",
797                     GID_MAX);
798         if (r->flags || r->flagset) {
799                 printf(" flags ");
800                 print_flags(r->flags);
801                 printf("/");
802                 print_flags(r->flagset);
803         } else if (r->action == PF_PASS &&
804             (!r->proto || r->proto == IPPROTO_TCP) &&
805             !(r->rule_flag & PFRULE_FRAGMENT) &&
806             !anchor_call[0] && r->keep_state)
807                 printf(" flags any");
808         if (r->type) {
809                 const struct icmptypeent        *it;
810
811                 it = geticmptypebynumber(r->type-1, r->af);
812                 if (r->af != AF_INET6)
813                         printf(" icmp-type");
814                 else
815                         printf(" icmp6-type");
816                 if (it != NULL)
817                         printf(" %s", it->name);
818                 else
819                         printf(" %u", r->type-1);
820                 if (r->code) {
821                         const struct icmpcodeent        *ic;
822
823                         ic = geticmpcodebynumber(r->type-1, r->code-1, r->af);
824                         if (ic != NULL)
825                                 printf(" code %s", ic->name);
826                         else
827                                 printf(" code %u", r->code-1);
828                 }
829         }
830         if (r->tos)
831                 printf(" tos 0x%2.2x", r->tos);
832         if (!r->keep_state && r->action == PF_PASS && !anchor_call[0])
833                 printf(" no state");
834         else if (r->keep_state == PF_STATE_NORMAL)
835                 printf(" keep state");
836         else if (r->keep_state == PF_STATE_MODULATE)
837                 printf(" modulate state");
838         else if (r->keep_state == PF_STATE_SYNPROXY)
839                 printf(" synproxy state");
840         if (r->prob) {
841                 char    buf[20];
842
843                 snprintf(buf, sizeof(buf), "%f", r->prob*100.0/(UINT_MAX+1.0));
844                 for (i = strlen(buf)-1; i > 0; i--) {
845                         if (buf[i] == '0')
846                                 buf[i] = '\0';
847                         else {
848                                 if (buf[i] == '.')
849                                         buf[i] = '\0';
850                                 break;
851                         }
852                 }
853                 printf(" probability %s%%", buf);
854         }
855         opts = 0;
856         if (r->max_states || r->max_src_nodes || r->max_src_states)
857                 opts = 1;
858         if (r->pickup_mode)
859                 opts = 1;
860         if (r->rule_flag & PFRULE_NOSYNC)
861                 opts = 1;
862         if (r->rule_flag & PFRULE_SRCTRACK)
863                 opts = 1;
864         if (r->rule_flag & PFRULE_IFBOUND)
865                 opts = 1;
866         for (i = 0; !opts && i < PFTM_MAX; ++i)
867                 if (r->timeout[i])
868                         opts = 1;
869         if (opts) {
870                 printf(" (");
871                 switch(r->pickup_mode) {
872                 case PF_PICKUPS_UNSPECIFIED:
873                         break;
874                 case PF_PICKUPS_DISABLED:
875                         printf("no-pickups");
876                         opts = 0;
877                         break;
878                 case PF_PICKUPS_HASHONLY:
879                         printf("hash-only");
880                         opts = 0;
881                         break;
882                 case PF_PICKUPS_ENABLED:
883                         printf("pickups");
884                         opts = 0;
885                         break;
886                 default:
887                         printf("unknown-pickups-mode-%d", r->pickup_mode);
888                         break;
889                 }
890                 if (r->max_states) {
891                         if (!opts)
892                                 printf(", ");
893                         printf("max %u", r->max_states);
894                         opts = 0;
895                 }
896                 if (r->rule_flag & PFRULE_NOSYNC) {
897                         if (!opts)
898                                 printf(", ");
899                         printf("no-sync");
900                         opts = 0;
901                 }
902                 if (r->rule_flag & PFRULE_SRCTRACK) {
903                         if (!opts)
904                                 printf(", ");
905                         printf("source-track");
906                         if (r->rule_flag & PFRULE_RULESRCTRACK)
907                                 printf(" rule");
908                         else
909                                 printf(" global");
910                         opts = 0;
911                 }
912                 if (r->max_src_states) {
913                         if (!opts)
914                                 printf(", ");
915                         printf("max-src-states %u", r->max_src_states);
916                         opts = 0;
917                 }
918                 if (r->max_src_conn) {
919                         if (!opts)
920                                 printf(", ");
921                         printf("max-src-conn %u", r->max_src_conn);
922                         opts = 0;
923                 }
924                 if (r->max_src_conn_rate.limit) {
925                         if (!opts)
926                                 printf(", ");
927                         printf("max-src-conn-rate %u/%u",
928                             r->max_src_conn_rate.limit,
929                             r->max_src_conn_rate.seconds);
930                         opts = 0;
931                 }
932                 if (r->max_src_nodes) {
933                         if (!opts)
934                                 printf(", ");
935                         printf("max-src-nodes %u", r->max_src_nodes);
936                         opts = 0;
937                 }
938                 if (r->overload_tblname[0]) {
939                         if (!opts)
940                                 printf(", ");
941                         printf("overload <%s>", r->overload_tblname);
942                         if (r->flush)
943                                 printf(" flush");
944                         if (r->flush & PF_FLUSH_GLOBAL)
945                                 printf(" global");
946                 }
947                 if (r->rule_flag & PFRULE_IFBOUND) {
948                         if (!opts)
949                                 printf(", ");
950                         printf("if-bound");
951                         opts = 0;
952                 }
953                 for (i = 0; i < PFTM_MAX; ++i)
954                         if (r->timeout[i]) {
955                                 int j;
956
957                                 if (!opts)
958                                         printf(", ");
959                                 opts = 0;
960                                 for (j = 0; pf_timeouts[j].name != NULL;
961                                     ++j)
962                                         if (pf_timeouts[j].timeout == i)
963                                                 break;
964                                 printf("%s %u", pf_timeouts[j].name == NULL ?
965                                     "inv.timeout" : pf_timeouts[j].name,
966                                     r->timeout[i]);
967                         }
968                 printf(")");
969         }
970         if (r->rule_flag & PFRULE_FRAGMENT)
971                 printf(" fragment");
972         if (r->rule_flag & PFRULE_NODF)
973                 printf(" no-df");
974         if (r->rule_flag & PFRULE_RANDOMID)
975                 printf(" random-id");
976         if (r->min_ttl)
977                 printf(" min-ttl %d", r->min_ttl);
978         if (r->max_mss)
979                 printf(" max-mss %d", r->max_mss);
980         if (r->allow_opts)
981                 printf(" allow-opts");
982         if (r->action == PF_SCRUB) {
983                 if (r->rule_flag & PFRULE_REASSEMBLE_TCP)
984                         printf(" reassemble tcp");
985
986                 if (r->rule_flag & PFRULE_FRAGDROP)
987                         printf(" fragment drop-ovl");
988                 else if (r->rule_flag & PFRULE_FRAGCROP)
989                         printf(" fragment crop");
990                 else
991                         printf(" fragment reassemble");
992         }
993         if (r->label[0])
994                 printf(" label \"%s\"", r->label);
995         if (r->qname[0] && r->pqname[0])
996                 printf(" queue(%s, %s)", r->qname, r->pqname);
997         else if (r->qname[0])
998                 printf(" queue %s", r->qname);
999         if (r->tagname[0])
1000                 printf(" tag %s", r->tagname);
1001         if (r->match_tagname[0]) {
1002                 if (r->match_tag_not)
1003                         printf(" !");
1004                 printf(" tagged %s", r->match_tagname);
1005         }
1006         if (r->rtableid != -1)
1007                 printf(" rtable %u", r->rtableid);
1008         if (!anchor_call[0] && (r->action == PF_NAT ||
1009             r->action == PF_BINAT || r->action == PF_RDR)) {
1010                 printf(" -> ");
1011                 print_pool(&r->rpool, r->rpool.proxy_port[0],
1012                     r->rpool.proxy_port[1], r->af, r->action);
1013         }
1014 }
1015
1016 void
1017 print_tabledef(const char *name, int flags, int addrs,
1018     struct node_tinithead *nodes)
1019 {
1020         struct node_tinit       *ti, *nti;
1021         struct node_host        *h;
1022
1023         printf("table <%s>", name);
1024         if (flags & PFR_TFLAG_CONST)
1025                 printf(" const");
1026         if (flags & PFR_TFLAG_PERSIST)
1027                 printf(" persist");
1028         SIMPLEQ_FOREACH(ti, nodes, entries) {
1029                 if (ti->file) {
1030                         printf(" file \"%s\"", ti->file);
1031                         continue;
1032                 }
1033                 printf(" {");
1034                 for (;;) {
1035                         for (h = ti->host; h != NULL; h = h->next) {
1036                                 printf(h->not ? " !" : " ");
1037                                 print_addr(&h->addr, h->af, 0);
1038                         }
1039                         nti = SIMPLEQ_NEXT(ti, entries);
1040                         if (nti != NULL && nti->file == NULL)
1041                                 ti = nti;       /* merge lists */
1042                         else
1043                                 break;
1044                 }
1045                 printf(" }");
1046         }
1047         if (addrs && SIMPLEQ_EMPTY(nodes))
1048                 printf(" { }");
1049         printf("\n");
1050 }
1051
1052 int
1053 parse_flags(const char *s)
1054 {
1055         const char      *p, *q;
1056         u_int8_t         f = 0;
1057
1058         for (p = s; *p; p++) {
1059                 if ((q = strchr(tcpflags, *p)) == NULL)
1060                         return -1;
1061                 else
1062                         f |= 1 << (q - tcpflags);
1063         }
1064         return (f ? f : PF_TH_ALL);
1065 }
1066
1067 void
1068 set_ipmask(struct node_host *h, u_int8_t b)
1069 {
1070         struct pf_addr  *m, *n;
1071         int              i, j = 0;
1072
1073         m = &h->addr.v.a.mask;
1074         memset(m, 0, sizeof(*m));
1075
1076         while (b >= 32) {
1077                 m->addr32[j++] = 0xffffffff;
1078                 b -= 32;
1079         }
1080         for (i = 31; i > 31-b; --i)
1081                 m->addr32[j] |= (1 << i);
1082         if (b)
1083                 m->addr32[j] = htonl(m->addr32[j]);
1084
1085         /* Mask off bits of the address that will never be used. */
1086         n = &h->addr.v.a.addr;
1087         if (h->addr.type == PF_ADDR_ADDRMASK)
1088                 for (i = 0; i < 4; i++)
1089                         n->addr32[i] = n->addr32[i] & m->addr32[i];
1090 }
1091
1092 int
1093 check_netmask(struct node_host *h, sa_family_t af)
1094 {
1095         struct node_host        *n = NULL;
1096         struct pf_addr  *m;
1097
1098         for (n = h; n != NULL; n = n->next) {
1099                 if (h->addr.type == PF_ADDR_TABLE)
1100                         continue;
1101                 m = &h->addr.v.a.mask;
1102                 /* fix up netmask for dynaddr */
1103                 if (af == AF_INET && h->addr.type == PF_ADDR_DYNIFTL &&
1104                     unmask(m, AF_INET6) > 32)
1105                         set_ipmask(n, 32);
1106                 /* netmasks > 32 bit are invalid on v4 */
1107                 if (af == AF_INET &&
1108                     (m->addr32[1] || m->addr32[2] || m->addr32[3])) {
1109                         fprintf(stderr, "netmask %u invalid for IPv4 address\n",
1110                             unmask(m, AF_INET6));
1111                         return (1);
1112                 }
1113         }
1114         return (0);
1115 }
1116
1117 /* interface lookup routines */
1118
1119 struct node_host        *iftab;
1120
1121 void
1122 ifa_load(void)
1123 {
1124         struct ifaddrs          *ifap, *ifa;
1125         struct node_host        *n = NULL, *h = NULL;
1126
1127         if (getifaddrs(&ifap) < 0)
1128                 err(1, "getifaddrs");
1129
1130         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
1131                 if (!(ifa->ifa_addr->sa_family == AF_INET ||
1132                     ifa->ifa_addr->sa_family == AF_INET6 ||
1133                     ifa->ifa_addr->sa_family == AF_LINK))
1134                                 continue;
1135                 n = calloc(1, sizeof(struct node_host));
1136                 if (n == NULL)
1137                         err(1, "address: calloc");
1138                 n->af = ifa->ifa_addr->sa_family;
1139                 n->ifa_flags = ifa->ifa_flags;
1140 #ifdef __KAME__
1141                 if (n->af == AF_INET6 &&
1142                     IN6_IS_ADDR_LINKLOCAL(&((struct sockaddr_in6 *)
1143                     ifa->ifa_addr)->sin6_addr) &&
1144                     ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id ==
1145                     0) {
1146                         struct sockaddr_in6     *sin6;
1147
1148                         sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1149                         sin6->sin6_scope_id = sin6->sin6_addr.s6_addr[2] << 8 |
1150                             sin6->sin6_addr.s6_addr[3];
1151                         sin6->sin6_addr.s6_addr[2] = 0;
1152                         sin6->sin6_addr.s6_addr[3] = 0;
1153                 }
1154 #endif
1155                 n->ifindex = 0;
1156                 if (n->af == AF_INET) {
1157                         memcpy(&n->addr.v.a.addr, &((struct sockaddr_in *)
1158                             ifa->ifa_addr)->sin_addr.s_addr,
1159                             sizeof(struct in_addr));
1160                         memcpy(&n->addr.v.a.mask, &((struct sockaddr_in *)
1161                             ifa->ifa_netmask)->sin_addr.s_addr,
1162                             sizeof(struct in_addr));
1163                         if (ifa->ifa_broadaddr != NULL)
1164                                 memcpy(&n->bcast, &((struct sockaddr_in *)
1165                                     ifa->ifa_broadaddr)->sin_addr.s_addr,
1166                                     sizeof(struct in_addr));
1167                         if (ifa->ifa_dstaddr != NULL)
1168                                 memcpy(&n->peer, &((struct sockaddr_in *)
1169                                     ifa->ifa_dstaddr)->sin_addr.s_addr,
1170                                     sizeof(struct in_addr));
1171                 } else if (n->af == AF_INET6) {
1172                         memcpy(&n->addr.v.a.addr, &((struct sockaddr_in6 *)
1173                             ifa->ifa_addr)->sin6_addr.s6_addr,
1174                             sizeof(struct in6_addr));
1175                         memcpy(&n->addr.v.a.mask, &((struct sockaddr_in6 *)
1176                             ifa->ifa_netmask)->sin6_addr.s6_addr,
1177                             sizeof(struct in6_addr));
1178                         if (ifa->ifa_broadaddr != NULL)
1179                                 memcpy(&n->bcast, &((struct sockaddr_in6 *)
1180                                     ifa->ifa_broadaddr)->sin6_addr.s6_addr,
1181                                     sizeof(struct in6_addr));
1182                         if (ifa->ifa_dstaddr != NULL)
1183                                  memcpy(&n->peer, &((struct sockaddr_in6 *)
1184                                     ifa->ifa_dstaddr)->sin6_addr.s6_addr,
1185                                     sizeof(struct in6_addr));
1186                         n->ifindex = ((struct sockaddr_in6 *)
1187                             ifa->ifa_addr)->sin6_scope_id;
1188                 }
1189                 if ((n->ifname = strdup(ifa->ifa_name)) == NULL)
1190                         err(1, "ifa_load: strdup");
1191                 n->next = NULL;
1192                 n->tail = n;
1193                 if (h == NULL)
1194                         h = n;
1195                 else {
1196                         h->tail->next = n;
1197                         h->tail = n;
1198                 }
1199         }
1200
1201         iftab = h;
1202         freeifaddrs(ifap);
1203 }
1204
1205 struct node_host *
1206 ifa_exists(const char *ifa_name)
1207 {
1208         struct node_host        *n;
1209         struct ifgroupreq       ifgr;
1210         int                     s;
1211
1212         if (iftab == NULL)
1213                 ifa_load();
1214
1215         /* check wether this is a group */
1216         if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1217                 err(1, "socket");
1218         bzero(&ifgr, sizeof(ifgr));
1219         strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1220         if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == 0) {
1221                 /* fake a node_host */
1222                 if ((n = calloc(1, sizeof(*n))) == NULL)
1223                         err(1, "calloc");
1224                 if ((n->ifname = strdup(ifa_name)) == NULL)
1225                         err(1, "strdup");
1226                 close(s);
1227                 return (n);
1228         }
1229         close(s);
1230
1231         for (n = iftab; n; n = n->next) {
1232                 if (n->af == AF_LINK && !strncmp(n->ifname, ifa_name, IFNAMSIZ))
1233                         return (n);
1234         }
1235
1236         return (NULL);
1237 }
1238
1239 struct node_host *
1240 ifa_grouplookup(const char *ifa_name, int flags)
1241 {
1242         struct ifg_req          *ifg;
1243         struct ifgroupreq        ifgr;
1244         int                      s;
1245         size_t          len;
1246         struct node_host        *n, *h = NULL;
1247
1248         if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
1249                 err(1, "socket");
1250         bzero(&ifgr, sizeof(ifgr));
1251         strlcpy(ifgr.ifgr_name, ifa_name, sizeof(ifgr.ifgr_name));
1252         if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1) {
1253                 close(s);
1254                 return (NULL);
1255         }
1256
1257         len = ifgr.ifgr_len;
1258         if ((ifgr.ifgr_groups = calloc(1, len)) == NULL)
1259                 err(1, "calloc");
1260         if (ioctl(s, SIOCGIFGMEMB, (caddr_t)&ifgr) == -1)
1261                 err(1, "SIOCGIFGMEMB");
1262
1263         for (ifg = ifgr.ifgr_groups; ifg && len >= sizeof(struct ifg_req);
1264             ifg++) {
1265                 len -= sizeof(struct ifg_req);
1266                 if ((n = ifa_lookup(ifg->ifgrq_member, flags)) == NULL)
1267                         continue;
1268                 if (h == NULL)
1269                         h = n;
1270                 else {
1271                         h->tail->next = n;
1272                         h->tail = n->tail;
1273                 }
1274         }
1275         free(ifgr.ifgr_groups);
1276         close(s);
1277
1278         return (h);
1279 }
1280
1281 struct node_host *
1282 ifa_lookup(const char *ifa_name, int flags)
1283 {
1284         struct node_host        *p = NULL, *h = NULL, *n = NULL;
1285         int                      got4 = 0, got6 = 0;
1286         const char               *last_if = NULL;
1287
1288         if ((h = ifa_grouplookup(ifa_name, flags)) != NULL)
1289                 return (h);
1290
1291         if (!strncmp(ifa_name, "self", IFNAMSIZ))
1292                 ifa_name = NULL;
1293
1294         if (iftab == NULL)
1295                 ifa_load();
1296
1297         for (p = iftab; p; p = p->next) {
1298                 if (ifa_skip_if(ifa_name, p))
1299                         continue;
1300                 if ((flags & PFI_AFLAG_BROADCAST) && p->af != AF_INET)
1301                         continue;
1302                 if ((flags & PFI_AFLAG_BROADCAST) &&
1303                     !(p->ifa_flags & IFF_BROADCAST))
1304                         continue;
1305                 if ((flags & PFI_AFLAG_PEER) &&
1306                     !(p->ifa_flags & IFF_POINTOPOINT))
1307                         continue;
1308                 if ((flags & PFI_AFLAG_NETWORK) && p->ifindex > 0)
1309                         continue;
1310                 if (last_if == NULL || strcmp(last_if, p->ifname))
1311                         got4 = got6 = 0;
1312                 last_if = p->ifname;
1313                 if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET && got4)
1314                         continue;
1315                 if ((flags & PFI_AFLAG_NOALIAS) && p->af == AF_INET6 && got6)
1316                         continue;
1317                 if (p->af == AF_INET)
1318                         got4 = 1;
1319                 else
1320                         got6 = 1;
1321                 n = calloc(1, sizeof(struct node_host));
1322                 if (n == NULL)
1323                         err(1, "address: calloc");
1324                 n->af = p->af;
1325                 if (flags & PFI_AFLAG_BROADCAST)
1326                         memcpy(&n->addr.v.a.addr, &p->bcast,
1327                             sizeof(struct pf_addr));
1328                 else if (flags & PFI_AFLAG_PEER)
1329                         memcpy(&n->addr.v.a.addr, &p->peer,
1330                             sizeof(struct pf_addr));
1331                 else
1332                         memcpy(&n->addr.v.a.addr, &p->addr.v.a.addr,
1333                             sizeof(struct pf_addr));
1334                 if (flags & PFI_AFLAG_NETWORK)
1335                         set_ipmask(n, unmask(&p->addr.v.a.mask, n->af));
1336                 else {
1337                         if (n->af == AF_INET) {
1338                                 if (p->ifa_flags & IFF_LOOPBACK &&
1339                                     p->ifa_flags & IFF_LINK1)
1340                                         memcpy(&n->addr.v.a.mask,
1341                                             &p->addr.v.a.mask,
1342                                             sizeof(struct pf_addr));
1343                                 else
1344                                         set_ipmask(n, 32);
1345                         } else
1346                                 set_ipmask(n, 128);
1347                 }
1348                 n->ifindex = p->ifindex;
1349
1350                 n->next = NULL;
1351                 n->tail = n;
1352                 if (h == NULL)
1353                         h = n;
1354                 else {
1355                         h->tail->next = n;
1356                         h->tail = n;
1357                 }
1358         }
1359         return (h);
1360 }
1361
1362 int
1363 ifa_skip_if(const char *filter, struct node_host *p)
1364 {
1365         int     n;
1366
1367         if (p->af != AF_INET && p->af != AF_INET6)
1368                 return (1);
1369         if (filter == NULL || !*filter)
1370                 return (0);
1371         if (!strcmp(p->ifname, filter))
1372                 return (0);     /* exact match */
1373         n = strlen(filter);
1374         if (n < 1 || n >= IFNAMSIZ)
1375                 return (1);     /* sanity check */
1376         if (filter[n-1] >= '0' && filter[n-1] <= '9')
1377                 return (1);     /* only do exact match in that case */
1378         if (strncmp(p->ifname, filter, n))
1379                 return (1);     /* prefix doesn't match */
1380         return (p->ifname[n] < '0' || p->ifname[n] > '9');
1381 }
1382
1383
1384 struct node_host *
1385 host(const char *s)
1386 {
1387         struct node_host        *h = NULL;
1388         int                      mask, v4mask, v6mask, cont = 1;
1389         char                    *p, *q, *ps;
1390
1391         if ((p = strrchr(s, '/')) != NULL) {
1392                 mask = strtol(p+1, &q, 0);
1393                 if (!q || *q || mask > 128 || q == (p+1)) {
1394                         fprintf(stderr, "invalid netmask '%s'\n", p);
1395                         return (NULL);
1396                 }
1397                 if ((ps = malloc(strlen(s) - strlen(p) + 1)) == NULL)
1398                         err(1, "host: malloc");
1399                 strlcpy(ps, s, strlen(s) - strlen(p) + 1);
1400                 v4mask = v6mask = mask;
1401         } else {
1402                 if ((ps = strdup(s)) == NULL)
1403                         err(1, "host: strdup");
1404                 v4mask = 32;
1405                 v6mask = 128;
1406                 mask = -1;
1407         }
1408
1409         /* interface with this name exists? */
1410         if (cont && (h = host_if(ps, mask)) != NULL)
1411                 cont = 0;
1412
1413         /* IPv4 address? */
1414         if (cont && (h = host_v4(s)) != NULL)
1415                 cont = 0;
1416
1417         /* IPv6 address? */
1418         if (cont && (h = host_v6(ps, v6mask)) != NULL)
1419                 cont = 0;
1420
1421         /* dns lookup */
1422         if (cont && (h = host_dns(ps, v4mask, v6mask)) != NULL)
1423                 cont = 0;
1424         free(ps);
1425
1426         if (h == NULL || cont == 1) {
1427                 fprintf(stderr, "no IP address found for %s\n", s);
1428                 return (NULL);
1429         }
1430         return (h);
1431 }
1432
1433 struct node_host *
1434 host_if(const char *s, int mask)
1435 {
1436         struct node_host        *n, *h = NULL;
1437         char                    *p, *ps;
1438         int                      flags = 0;
1439
1440         if ((ps = strdup(s)) == NULL)
1441                 err(1, "host_if: strdup");
1442         while ((p = strrchr(ps, ':')) != NULL) {
1443                 if (!strcmp(p+1, "network"))
1444                         flags |= PFI_AFLAG_NETWORK;
1445                 else if (!strcmp(p+1, "broadcast"))
1446                         flags |= PFI_AFLAG_BROADCAST;
1447                 else if (!strcmp(p+1, "peer"))
1448                         flags |= PFI_AFLAG_PEER;
1449                 else if (!strcmp(p+1, "0"))
1450                         flags |= PFI_AFLAG_NOALIAS;
1451                 else {
1452                         free(ps);
1453                         return (NULL);
1454                 }
1455                 *p = '\0';
1456         }
1457         if (flags & (flags - 1) & PFI_AFLAG_MODEMASK) { /* Yep! */
1458                 fprintf(stderr, "illegal combination of interface modifiers\n");
1459                 free(ps);
1460                 return (NULL);
1461         }
1462         if ((flags & (PFI_AFLAG_NETWORK|PFI_AFLAG_BROADCAST)) && mask > -1) {
1463                 fprintf(stderr, "network or broadcast lookup, but "
1464                     "extra netmask given\n");
1465                 free(ps);
1466                 return (NULL);
1467         }
1468         if (ifa_exists(ps) || !strncmp(ps, "self", IFNAMSIZ)) {
1469                 /* interface with this name exists */
1470                 h = ifa_lookup(ps, flags);
1471                 for (n = h; n != NULL && mask > -1; n = n->next)
1472                         set_ipmask(n, mask);
1473         }
1474
1475         free(ps);
1476         return (h);
1477 }
1478
1479 static struct node_host *
1480 host_v4(const char *s)
1481 {
1482         struct node_host        *h = NULL;
1483         struct in_addr           ina;
1484         int                      bits = 32;
1485
1486         memset(&ina, 0, sizeof(struct in_addr));
1487         if (strrchr(s, '/') != NULL) {
1488                 if ((bits = inet_net_pton(AF_INET, s, &ina, sizeof(ina))) == -1)
1489                         return (NULL);
1490         } else {
1491                 if (inet_pton(AF_INET, s, &ina) != 1)
1492                         return (NULL);
1493         }
1494
1495         h = calloc(1, sizeof(struct node_host));
1496         if (h == NULL)
1497                 err(1, "address: calloc");
1498         h->ifname = NULL;
1499         h->af = AF_INET;
1500         h->addr.v.a.addr.addr32[0] = ina.s_addr;
1501         set_ipmask(h, bits);
1502         h->next = NULL;
1503         h->tail = h;
1504
1505         return (h);
1506 }
1507
1508 struct node_host *
1509 host_v6(const char *s, int mask)
1510 {
1511         struct addrinfo          hints, *res;
1512         struct node_host        *h = NULL;
1513
1514         memset(&hints, 0, sizeof(hints));
1515         hints.ai_family = AF_INET6;
1516         hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1517         hints.ai_flags = AI_NUMERICHOST;
1518         if (getaddrinfo(s, "0", &hints, &res) == 0) {
1519                 h = calloc(1, sizeof(struct node_host));
1520                 if (h == NULL)
1521                         err(1, "address: calloc");
1522                 h->ifname = NULL;
1523                 h->af = AF_INET6;
1524                 memcpy(&h->addr.v.a.addr,
1525                     &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1526                     sizeof(h->addr.v.a.addr));
1527                 h->ifindex =
1528                     ((struct sockaddr_in6 *)res->ai_addr)->sin6_scope_id;
1529                 set_ipmask(h, mask);
1530                 freeaddrinfo(res);
1531                 h->next = NULL;
1532                 h->tail = h;
1533         }
1534
1535         return (h);
1536 }
1537
1538 struct node_host *
1539 host_dns(const char *s, int v4mask, int v6mask)
1540 {
1541         struct addrinfo          hints, *res0, *res;
1542         struct node_host        *n, *h = NULL;
1543         int                      error, noalias = 0;
1544         int                      got4 = 0, got6 = 0;
1545         char                    *p, *ps;
1546
1547         if ((ps = strdup(s)) == NULL)
1548                 err(1, "host_dns: strdup");
1549         if ((p = strrchr(ps, ':')) != NULL && !strcmp(p, ":0")) {
1550                 noalias = 1;
1551                 *p = '\0';
1552         }
1553         memset(&hints, 0, sizeof(hints));
1554         hints.ai_family = PF_UNSPEC;
1555         hints.ai_socktype = SOCK_STREAM; /* DUMMY */
1556         error = getaddrinfo(ps, NULL, &hints, &res0);
1557         if (error) {
1558                 free(ps);
1559                 return (h);
1560         }
1561
1562         for (res = res0; res; res = res->ai_next) {
1563                 if (res->ai_family != AF_INET &&
1564                     res->ai_family != AF_INET6)
1565                         continue;
1566                 if (noalias) {
1567                         if (res->ai_family == AF_INET) {
1568                                 if (got4)
1569                                         continue;
1570                                 got4 = 1;
1571                         } else {
1572                                 if (got6)
1573                                         continue;
1574                                 got6 = 1;
1575                         }
1576                 }
1577                 n = calloc(1, sizeof(struct node_host));
1578                 if (n == NULL)
1579                         err(1, "host_dns: calloc");
1580                 n->ifname = NULL;
1581                 n->af = res->ai_family;
1582                 if (res->ai_family == AF_INET) {
1583                         memcpy(&n->addr.v.a.addr,
1584                             &((struct sockaddr_in *)
1585                             res->ai_addr)->sin_addr.s_addr,
1586                             sizeof(struct in_addr));
1587                         set_ipmask(n, v4mask);
1588                 } else {
1589                         memcpy(&n->addr.v.a.addr,
1590                             &((struct sockaddr_in6 *)
1591                             res->ai_addr)->sin6_addr.s6_addr,
1592                             sizeof(struct in6_addr));
1593                         n->ifindex =
1594                             ((struct sockaddr_in6 *)
1595                             res->ai_addr)->sin6_scope_id;
1596                         set_ipmask(n, v6mask);
1597                 }
1598                 n->next = NULL;
1599                 n->tail = n;
1600                 if (h == NULL)
1601                         h = n;
1602                 else {
1603                         h->tail->next = n;
1604                         h->tail = n;
1605                 }
1606         }
1607         freeaddrinfo(res0);
1608         free(ps);
1609
1610         return (h);
1611 }
1612
1613 /*
1614  * convert a hostname to a list of addresses and put them in the given buffer.
1615  * test:
1616  *      if set to 1, only simple addresses are accepted (no netblock, no "!").
1617  */
1618 int
1619 append_addr(struct pfr_buffer *b, char *s, int test)
1620 {
1621         char                     *r;
1622         struct node_host        *h, *n;
1623         int                      rv, not = 0;
1624
1625         for (r = s; *r == '!'; r++)
1626                 not = !not;
1627         if ((n = host(r)) == NULL) {
1628                 errno = 0;
1629                 return (-1);
1630         }
1631         rv = append_addr_host(b, n, test, not);
1632         do {
1633                 h = n;
1634                 n = n->next;
1635                 free(h);
1636         } while (n != NULL);
1637         return (rv);
1638 }
1639
1640 /*
1641  * same as previous function, but with a pre-parsed input and the ability
1642  * to "negate" the result. Does not free the node_host list.
1643  * not:
1644  *      setting it to 1 is equivalent to adding "!" in front of parameter s.
1645  */
1646 int
1647 append_addr_host(struct pfr_buffer *b, struct node_host *n, int test, int not)
1648 {
1649         int                      bits;
1650         struct pfr_addr          addr;
1651
1652         do {
1653                 bzero(&addr, sizeof(addr));
1654                 addr.pfra_not = n->not ^ not;
1655                 addr.pfra_af = n->af;
1656                 addr.pfra_net = unmask(&n->addr.v.a.mask, n->af);
1657                 switch (n->af) {
1658                 case AF_INET:
1659                         addr.pfra_ip4addr.s_addr = n->addr.v.a.addr.addr32[0];
1660                         bits = 32;
1661                         break;
1662                 case AF_INET6:
1663                         memcpy(&addr.pfra_ip6addr, &n->addr.v.a.addr.v6,
1664                             sizeof(struct in6_addr));
1665                         bits = 128;
1666                         break;
1667                 default:
1668                         errno = EINVAL;
1669                         return (-1);
1670                 }
1671                 if ((test && (not || addr.pfra_net != bits)) ||
1672                     addr.pfra_net > bits) {
1673                         errno = EINVAL;
1674                         return (-1);
1675                 }
1676                 if (pfr_buf_add(b, &addr))
1677                         return (-1);
1678         } while ((n = n->next) != NULL);
1679
1680         return (0);
1681 }
1682
1683 int
1684 pfctl_add_trans(struct pfr_buffer *buf, int rs_num, const char *anchor)
1685 {
1686         struct pfioc_trans_e trans;
1687
1688         bzero(&trans, sizeof(trans));
1689         trans.rs_num = rs_num;
1690         if (strlcpy(trans.anchor, anchor,
1691             sizeof(trans.anchor)) >= sizeof(trans.anchor))
1692                 errx(1, "pfctl_add_trans: strlcpy");
1693
1694         return pfr_buf_add(buf, &trans);
1695 }
1696
1697 u_int32_t
1698 pfctl_get_ticket(struct pfr_buffer *buf, int rs_num, const char *anchor)
1699 {
1700         const struct pfioc_trans_e *p;
1701
1702         PFRB_FOREACH(p, buf)
1703                 if (rs_num == p->rs_num && !strcmp(anchor, p->anchor))
1704                         return (p->ticket);
1705         errx(1, "pfctl_get_ticket: assertion failed");
1706 }
1707
1708 int
1709 pfctl_trans(int dev, struct pfr_buffer *buf, u_long cmd, int from)
1710 {
1711         struct pfioc_trans trans;
1712
1713         bzero(&trans, sizeof(trans));
1714         trans.size = buf->pfrb_size - from;
1715         trans.esize = sizeof(struct pfioc_trans_e);
1716         trans.array = ((struct pfioc_trans_e *)buf->pfrb_caddr) + from;
1717         return ioctl(dev, cmd, &trans);
1718 }