1 /*-
2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
5 *
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
8 *
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
11 *
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
15 *
16 * This software is provided ``AS IS'' without any warranties of any kind.
17 *
18 * NEW command line interface for IP firewall facility
19 */
20
21 #include <sys/types.h>
22 #include <sys/param.h>
23 #include <sys/socket.h>
24 #include <sys/sockio.h>
25 #include <sys/sysctl.h>
26
27 #include "ipfw2.h"
28
29 #include <ctype.h>
30 #include <err.h>
31 #include <errno.h>
32 #include <grp.h>
33 #include <jail.h>
34 #include <netdb.h>
35 #include <pwd.h>
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdint.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sysexits.h>
42 #include <time.h> /* ctime */
43 #include <timeconv.h> /* _long_to_time */
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <stddef.h> /* offsetof */
47
48 #include <net/ethernet.h>
49 #include <net/if.h> /* only IFNAMSIZ */
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h> /* only n_short, n_long */
52 #include <netinet/ip.h>
53 #include <netinet/ip_icmp.h>
54 #include <netinet/ip_fw.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
57
58 struct cmdline_opts g_co; /* global options */
59
60 struct format_opts {
61 int bcwidth;
62 int pcwidth;
63 int show_counters;
64 int show_time; /* show timestamp */
65 uint32_t set_mask; /* enabled sets mask */
66 uint32_t flags; /* request flags */
67 uint32_t first; /* first rule to request */
68 uint32_t last; /* last rule to request */
69 uint32_t dcnt; /* number of dynamic states */
70 ipfw_obj_ctlv *tstate; /* table state data */
71 };
72
73 int resvd_set_number = RESVD_SET;
74
75 static int ipfw_socket = -1;
76
77 #define CHECK_LENGTH(v, len) do { \
78 if ((v) < (len)) \
79 errx(EX_DATAERR, "Rule too long"); \
80 } while (0)
81 /*
82 * Check if we have enough space in cmd buffer. Note that since
83 * first 8? u32 words are reserved by reserved header, full cmd
84 * buffer can't be used, so we need to protect from buffer overrun
85 * only. At the beginning, cblen is less than actual buffer size by
86 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
87 * for checking small instructions fitting in given range.
88 * We also (ab)use the fact that ipfw_insn is always the first field
89 * for any custom instruction.
90 */
91 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
92
93 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
94 if (!av[0]) \
95 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
96 if (_substrcmp(*av, "tablearg") == 0) { \
97 arg = IP_FW_TARG; \
98 break; \
99 } \
100 \
101 { \
102 long _xval; \
103 char *end; \
104 \
105 _xval = strtol(*av, &end, 10); \
106 \
107 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
108 errx(EX_DATAERR, "%s: invalid argument: %s", \
109 match_value(s_x, tok), *av); \
110 \
111 if (errno == ERANGE || _xval < min || _xval > max) \
112 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
113 match_value(s_x, tok), min, max, *av); \
114 \
115 if (_xval == IP_FW_TARG) \
116 errx(EX_DATAERR, "%s: illegal argument value: %s", \
117 match_value(s_x, tok), *av); \
118 arg = _xval; \
119 } \
120 } while (0)
121
122 static struct _s_x f_tcpflags[] = {
123 { "syn", TH_SYN },
124 { "fin", TH_FIN },
125 { "ack", TH_ACK },
126 { "psh", TH_PUSH },
127 { "rst", TH_RST },
128 { "urg", TH_URG },
129 { "tcp flag", 0 },
130 { NULL, 0 }
131 };
132
133 static struct _s_x f_tcpopts[] = {
134 { "mss", IP_FW_TCPOPT_MSS },
135 { "maxseg", IP_FW_TCPOPT_MSS },
136 { "window", IP_FW_TCPOPT_WINDOW },
137 { "sack", IP_FW_TCPOPT_SACK },
138 { "ts", IP_FW_TCPOPT_TS },
139 { "timestamp", IP_FW_TCPOPT_TS },
140 { "cc", IP_FW_TCPOPT_CC },
141 { "tcp option", 0 },
142 { NULL, 0 }
143 };
144
145 /*
146 * IP options span the range 0 to 255 so we need to remap them
147 * (though in fact only the low 5 bits are significant).
148 */
149 static struct _s_x f_ipopts[] = {
150 { "ssrr", IP_FW_IPOPT_SSRR},
151 { "lsrr", IP_FW_IPOPT_LSRR},
152 { "rr", IP_FW_IPOPT_RR},
153 { "ts", IP_FW_IPOPT_TS},
154 { "ip option", 0 },
155 { NULL, 0 }
156 };
157
158 static struct _s_x f_iptos[] = {
159 { "lowdelay", IPTOS_LOWDELAY},
160 { "throughput", IPTOS_THROUGHPUT},
161 { "reliability", IPTOS_RELIABILITY},
162 { "mincost", IPTOS_MINCOST},
163 { "congestion", IPTOS_ECN_CE},
164 { "ecntransport", IPTOS_ECN_ECT0},
165 { "ip tos option", 0},
166 { NULL, 0 }
167 };
168
169 static struct _s_x f_ipoff[] = {
170 { "rf", IP_RF >> 8 },
171 { "df", IP_DF >> 8 },
172 { "mf", IP_MF >> 8 },
173 { "offset", 0x1 },
174 { NULL, 0}
175 };
176
177 struct _s_x f_ipdscp[] = {
178 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
179 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
180 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
181 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
182 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
183 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
184 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
185 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
186 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
187 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
188 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
189 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
190 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
191 { "va", IPTOS_DSCP_VA >> 2 }, /* 101100 */
192 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
193 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
194 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
195 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
196 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
197 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
198 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
199 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
200 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
201 { NULL, 0 }
202 };
203
204 static struct _s_x limit_masks[] = {
205 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
206 {"src-addr", DYN_SRC_ADDR},
207 {"src-port", DYN_SRC_PORT},
208 {"dst-addr", DYN_DST_ADDR},
209 {"dst-port", DYN_DST_PORT},
210 {NULL, 0}
211 };
212
213 /*
214 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
215 * This is only used in this code.
216 */
217 #define IPPROTO_ETHERTYPE 0x1000
218 static struct _s_x ether_types[] = {
219 /*
220 * Note, we cannot use "-:&/" in the names because they are field
221 * separators in the type specifications. Also, we use s = NULL as
222 * end-delimiter, because a type of 0 can be legal.
223 */
224 { "ip", 0x0800 },
225 { "ipv4", 0x0800 },
226 { "ipv6", 0x86dd },
227 { "arp", 0x0806 },
228 { "rarp", 0x8035 },
229 { "vlan", 0x8100 },
230 { "loop", 0x9000 },
231 { "trail", 0x1000 },
232 { "at", 0x809b },
233 { "atalk", 0x809b },
234 { "aarp", 0x80f3 },
235 { "pppoe_disc", 0x8863 },
236 { "pppoe_sess", 0x8864 },
237 { "ipx_8022", 0x00E0 },
238 { "ipx_8023", 0x0000 },
239 { "ipx_ii", 0x8137 },
240 { "ipx_snap", 0x8137 },
241 { "ipx", 0x8137 },
242 { "ns", 0x0600 },
243 { NULL, 0 }
244 };
245
246 static struct _s_x rule_eactions[] = {
247 { "nat64clat", TOK_NAT64CLAT },
248 { "nat64lsn", TOK_NAT64LSN },
249 { "nat64stl", TOK_NAT64STL },
250 { "nptv6", TOK_NPTV6 },
251 { "tcp-setmss", TOK_TCPSETMSS },
252 { NULL, 0 } /* terminator */
253 };
254
255 static struct _s_x rule_actions[] = {
256 { "abort6", TOK_ABORT6 },
257 { "abort", TOK_ABORT },
258 { "accept", TOK_ACCEPT },
259 { "pass", TOK_ACCEPT },
260 { "allow", TOK_ACCEPT },
261 { "permit", TOK_ACCEPT },
262 { "count", TOK_COUNT },
263 { "pipe", TOK_PIPE },
264 { "queue", TOK_QUEUE },
265 { "divert", TOK_DIVERT },
266 { "tee", TOK_TEE },
267 { "netgraph", TOK_NETGRAPH },
268 { "ngtee", TOK_NGTEE },
269 { "fwd", TOK_FORWARD },
270 { "forward", TOK_FORWARD },
271 { "skipto", TOK_SKIPTO },
272 { "deny", TOK_DENY },
273 { "drop", TOK_DENY },
274 { "reject", TOK_REJECT },
275 { "reset6", TOK_RESET6 },
276 { "reset", TOK_RESET },
277 { "unreach6", TOK_UNREACH6 },
278 { "unreach", TOK_UNREACH },
279 { "check-state", TOK_CHECKSTATE },
280 { "//", TOK_COMMENT },
281 { "nat", TOK_NAT },
282 { "reass", TOK_REASS },
283 { "setfib", TOK_SETFIB },
284 { "setdscp", TOK_SETDSCP },
285 { "call", TOK_CALL },
286 { "return", TOK_RETURN },
287 { "eaction", TOK_EACTION },
288 { "tcp-setmss", TOK_TCPSETMSS },
289 { NULL, 0 } /* terminator */
290 };
291
292 static struct _s_x rule_action_params[] = {
293 { "altq", TOK_ALTQ },
294 { "log", TOK_LOG },
295 { "tag", TOK_TAG },
296 { "untag", TOK_UNTAG },
297 { NULL, 0 } /* terminator */
298 };
299
300 /*
301 * The 'lookup' instruction accepts one of the following arguments.
302 * Arguments are passed as v[1] in O_DST_LOOKUP options.
303 */
304 static struct _s_x lookup_keys[] = {
305 { "dst-ip", LOOKUP_DST_IP },
306 { "src-ip", LOOKUP_SRC_IP },
307 { "dst-port", LOOKUP_DST_PORT },
308 { "src-port", LOOKUP_SRC_PORT },
309 { "dst-mac", LOOKUP_DST_MAC },
310 { "src-mac", LOOKUP_SRC_MAC },
311 { "uid", LOOKUP_UID },
312 { "jail", LOOKUP_JAIL },
313 { "dscp", LOOKUP_DSCP },
314 { NULL, 0 },
315 };
316
317 static struct _s_x rule_options[] = {
318 { "tagged", TOK_TAGGED },
319 { "uid", TOK_UID },
320 { "gid", TOK_GID },
321 { "jail", TOK_JAIL },
322 { "in", TOK_IN },
323 { "limit", TOK_LIMIT },
324 { "set-limit", TOK_SETLIMIT },
325 { "keep-state", TOK_KEEPSTATE },
326 { "record-state", TOK_RECORDSTATE },
327 { "bridged", TOK_LAYER2 },
328 { "layer2", TOK_LAYER2 },
329 { "out", TOK_OUT },
330 { "diverted", TOK_DIVERTED },
331 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
332 { "diverted-output", TOK_DIVERTEDOUTPUT },
333 { "xmit", TOK_XMIT },
334 { "recv", TOK_RECV },
335 { "via", TOK_VIA },
336 { "fragment", TOK_FRAG },
337 { "frag", TOK_FRAG },
338 { "fib", TOK_FIB },
339 { "ipoptions", TOK_IPOPTS },
340 { "ipopts", TOK_IPOPTS },
341 { "iplen", TOK_IPLEN },
342 { "ipid", TOK_IPID },
343 { "ipprecedence", TOK_IPPRECEDENCE },
344 { "dscp", TOK_DSCP },
345 { "iptos", TOK_IPTOS },
346 { "ipttl", TOK_IPTTL },
347 { "ipversion", TOK_IPVER },
348 { "ipver", TOK_IPVER },
349 { "estab", TOK_ESTAB },
350 { "established", TOK_ESTAB },
351 { "setup", TOK_SETUP },
352 { "sockarg", TOK_SOCKARG },
353 { "tcpdatalen", TOK_TCPDATALEN },
354 { "tcpflags", TOK_TCPFLAGS },
355 { "tcpflgs", TOK_TCPFLAGS },
356 { "tcpmss", TOK_TCPMSS },
357 { "tcpoptions", TOK_TCPOPTS },
358 { "tcpopts", TOK_TCPOPTS },
359 { "tcpseq", TOK_TCPSEQ },
360 { "tcpack", TOK_TCPACK },
361 { "tcpwin", TOK_TCPWIN },
362 { "icmptype", TOK_ICMPTYPES },
363 { "icmptypes", TOK_ICMPTYPES },
364 { "dst-ip", TOK_DSTIP },
365 { "src-ip", TOK_SRCIP },
366 { "dst-port", TOK_DSTPORT },
367 { "src-port", TOK_SRCPORT },
368 { "dst-mac", TOK_DSTMAC },
369 { "src-mac", TOK_SRCMAC },
370 { "proto", TOK_PROTO },
371 { "MAC", TOK_MAC },
372 { "mac", TOK_MAC },
373 { "mac-type", TOK_MACTYPE },
374 { "verrevpath", TOK_VERREVPATH },
375 { "versrcreach", TOK_VERSRCREACH },
376 { "antispoof", TOK_ANTISPOOF },
377 { "ipsec", TOK_IPSEC },
378 { "icmp6type", TOK_ICMP6TYPES },
379 { "icmp6types", TOK_ICMP6TYPES },
380 { "ext6hdr", TOK_EXT6HDR },
381 { "flow-id", TOK_FLOWID },
382 { "ipv6", TOK_IPV6 },
383 { "ip6", TOK_IPV6 },
384 { "ipv4", TOK_IPV4 },
385 { "ip4", TOK_IPV4 },
386 { "dst-ipv6", TOK_DSTIP6 },
387 { "dst-ip6", TOK_DSTIP6 },
388 { "src-ipv6", TOK_SRCIP6 },
389 { "src-ip6", TOK_SRCIP6 },
390 { "lookup", TOK_LOOKUP },
391 { "flow", TOK_FLOW },
392 { "defer-action", TOK_SKIPACTION },
393 { "defer-immediate-action", TOK_SKIPACTION },
394 { "//", TOK_COMMENT },
395
396 { "not", TOK_NOT }, /* pseudo option */
397 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
398 { "or", TOK_OR }, /* pseudo option */
399 { "|", /* escape */ TOK_OR }, /* pseudo option */
400 { "{", TOK_STARTBRACE }, /* pseudo option */
401 { "(", TOK_STARTBRACE }, /* pseudo option */
402 { "}", TOK_ENDBRACE }, /* pseudo option */
403 { ")", TOK_ENDBRACE }, /* pseudo option */
404 { NULL, 0 } /* terminator */
405 };
406
407 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
408 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
409 ipfw_cfg_lheader **pcfg, size_t *psize);
410 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
411 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
412 static void ipfw_list_tifaces(void);
413
414 struct tidx;
415 static uint16_t pack_object(struct tidx *tstate, const char *name, int otype);
416 static uint16_t pack_table(struct tidx *tstate, const char *name);
417
418 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
419 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
420 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
421 uint16_t type);
422
423 int
is_ipfw(void)424 is_ipfw(void)
425 {
426 return (g_co.prog == cmdline_prog_ipfw);
427 }
428
429 /*
430 * Simple string buffer API.
431 * Used to simplify buffer passing between function and for
432 * transparent overrun handling.
433 */
434
435 /*
436 * Allocates new buffer of given size @sz.
437 *
438 * Returns 0 on success.
439 */
440 int
bp_alloc(struct buf_pr * b,size_t size)441 bp_alloc(struct buf_pr *b, size_t size)
442 {
443 memset(b, 0, sizeof(struct buf_pr));
444
445 if ((b->buf = calloc(1, size)) == NULL)
446 return (ENOMEM);
447
448 b->ptr = b->buf;
449 b->size = size;
450 b->avail = b->size;
451
452 return (0);
453 }
454
455 void
bp_free(struct buf_pr * b)456 bp_free(struct buf_pr *b)
457 {
458
459 free(b->buf);
460 }
461
462 /*
463 * Flushes buffer so new writer start from beginning.
464 */
465 void
bp_flush(struct buf_pr * b)466 bp_flush(struct buf_pr *b)
467 {
468
469 b->ptr = b->buf;
470 b->avail = b->size;
471 b->buf[0] = '\0';
472 }
473
474 /*
475 * Print message specified by @format and args.
476 * Automatically manage buffer space and transparently handle
477 * buffer overruns.
478 *
479 * Returns number of bytes that should have been printed.
480 */
481 int
bprintf(struct buf_pr * b,const char * format,...)482 bprintf(struct buf_pr *b, const char *format, ...)
483 {
484 va_list args;
485 int i;
486
487 va_start(args, format);
488
489 i = vsnprintf(b->ptr, b->avail, format, args);
490 va_end(args);
491
492 if (i < 0 || (size_t)i > b->avail) {
493 /* Overflow or print error */
494 b->avail = 0;
495 } else {
496 b->ptr += i;
497 b->avail -= i;
498 }
499
500 b->needed += i;
501
502 return (i);
503 }
504
505 /*
506 * Special values printer for tablearg-aware opcodes.
507 */
508 void
bprint_uint_arg(struct buf_pr * bp,const char * str,uint32_t arg)509 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
510 {
511
512 if (str != NULL)
513 bprintf(bp, "%s", str);
514 if (arg == IP_FW_TARG)
515 bprintf(bp, "tablearg");
516 else
517 bprintf(bp, "%u", arg);
518 }
519
520 /*
521 * Helper routine to print a possibly unaligned uint64_t on
522 * various platform. If width > 0, print the value with
523 * the desired width, followed by a space;
524 * otherwise, return the required width.
525 */
526 int
pr_u64(struct buf_pr * b,void * pd,int width)527 pr_u64(struct buf_pr *b, void *pd, int width)
528 {
529 #ifdef TCC
530 #define U64_FMT "I64"
531 #else
532 #define U64_FMT "llu"
533 #endif
534 uint64_t u;
535 unsigned long long d;
536
537 bcopy (pd, &u, sizeof(u));
538 d = u;
539 return (width > 0) ?
540 bprintf(b, "%*" U64_FMT " ", width, d) :
541 snprintf(NULL, 0, "%" U64_FMT, d) ;
542 #undef U64_FMT
543 }
544
545
546 void *
safe_calloc(size_t number,size_t size)547 safe_calloc(size_t number, size_t size)
548 {
549 void *ret = calloc(number, size);
550
551 if (ret == NULL)
552 err(EX_OSERR, "calloc");
553 return ret;
554 }
555
556 void *
safe_realloc(void * ptr,size_t size)557 safe_realloc(void *ptr, size_t size)
558 {
559 void *ret = realloc(ptr, size);
560
561 if (ret == NULL)
562 err(EX_OSERR, "realloc");
563 return ret;
564 }
565
566 /*
567 * Compare things like interface or table names.
568 */
569 int
stringnum_cmp(const char * a,const char * b)570 stringnum_cmp(const char *a, const char *b)
571 {
572 int la, lb;
573
574 la = strlen(a);
575 lb = strlen(b);
576
577 if (la > lb)
578 return (1);
579 else if (la < lb)
580 return (-01);
581
582 return (strcmp(a, b));
583 }
584
585
586 /*
587 * conditionally runs the command.
588 * Selected options or negative -> getsockopt
589 */
590 int
do_cmd(int optname,void * optval,uintptr_t optlen)591 do_cmd(int optname, void *optval, uintptr_t optlen)
592 {
593 int i;
594
595 if (g_co.test_only)
596 return 0;
597
598 if (ipfw_socket == -1)
599 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
600 if (ipfw_socket < 0)
601 err(EX_UNAVAILABLE, "socket");
602
603 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
604 optname == IP_FW_ADD || optname == IP_FW3 ||
605 optname == IP_FW_NAT_GET_CONFIG ||
606 optname < 0 ||
607 optname == IP_FW_NAT_GET_LOG) {
608 if (optname < 0)
609 optname = -optname;
610 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
611 (socklen_t *)optlen);
612 } else {
613 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
614 }
615 return i;
616 }
617
618 /*
619 * do_set3 - pass ipfw control cmd to kernel
620 * @optname: option name
621 * @optval: pointer to option data
622 * @optlen: option length
623 *
624 * Assumes op3 header is already embedded.
625 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
626 * Returns 0 on success or errno otherwise.
627 */
628 int
do_set3(int optname,ip_fw3_opheader * op3,size_t optlen)629 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
630 {
631
632 if (g_co.test_only)
633 return (0);
634
635 if (ipfw_socket == -1)
636 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
637 if (ipfw_socket < 0)
638 err(EX_UNAVAILABLE, "socket");
639
640 op3->opcode = optname;
641
642 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
643 }
644
645 /*
646 * do_get3 - pass ipfw control cmd to kernel
647 * @optname: option name
648 * @optval: pointer to option data
649 * @optlen: pointer to option length
650 *
651 * Assumes op3 header is already embedded.
652 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
653 * Returns 0 on success or errno otherwise.
654 */
655 int
do_get3(int optname,ip_fw3_opheader * op3,size_t * optlen)656 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
657 {
658 int error;
659 socklen_t len;
660
661 if (g_co.test_only)
662 return (0);
663
664 if (ipfw_socket == -1)
665 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
666 if (ipfw_socket < 0)
667 err(EX_UNAVAILABLE, "socket");
668
669 op3->opcode = optname;
670
671 len = *optlen;
672 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
673 *optlen = len;
674
675 return (error);
676 }
677
678 /**
679 * match_token takes a table and a string, returns the value associated
680 * with the string (-1 in case of failure).
681 */
682 int
match_token(struct _s_x * table,const char * string)683 match_token(struct _s_x *table, const char *string)
684 {
685 struct _s_x *pt;
686 uint i = strlen(string);
687
688 for (pt = table ; i && pt->s != NULL ; pt++)
689 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
690 return pt->x;
691 return (-1);
692 }
693
694 /**
695 * match_token_relaxed takes a table and a string, returns the value associated
696 * with the string for the best match.
697 *
698 * Returns:
699 * value from @table for matched records
700 * -1 for non-matched records
701 * -2 if more than one records match @string.
702 */
703 int
match_token_relaxed(struct _s_x * table,const char * string)704 match_token_relaxed(struct _s_x *table, const char *string)
705 {
706 struct _s_x *pt, *m;
707 int i, c;
708
709 i = strlen(string);
710 c = 0;
711
712 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
713 if (strncmp(pt->s, string, i) != 0)
714 continue;
715 m = pt;
716 c++;
717 }
718
719 if (c == 1)
720 return (m->x);
721
722 return (c > 0 ? -2: -1);
723 }
724
725 int
get_token(struct _s_x * table,const char * string,const char * errbase)726 get_token(struct _s_x *table, const char *string, const char *errbase)
727 {
728 int tcmd;
729
730 if ((tcmd = match_token_relaxed(table, string)) < 0)
731 errx(EX_USAGE, "%s %s %s",
732 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
733
734 return (tcmd);
735 }
736
737 /**
738 * match_value takes a table and a value, returns the string associated
739 * with the value (NULL in case of failure).
740 */
741 char const *
match_value(struct _s_x * p,int value)742 match_value(struct _s_x *p, int value)
743 {
744 for (; p->s != NULL; p++)
745 if (p->x == value)
746 return p->s;
747 return NULL;
748 }
749
750 size_t
concat_tokens(char * buf,size_t bufsize,struct _s_x * table,const char * delimiter)751 concat_tokens(char *buf, size_t bufsize, struct _s_x *table,
752 const char *delimiter)
753 {
754 struct _s_x *pt;
755 int l;
756 size_t sz;
757
758 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
759 l = snprintf(buf + sz, bufsize - sz, "%s%s",
760 (sz == 0) ? "" : delimiter, pt->s);
761 sz += l;
762 bufsize += l;
763 if (sz > bufsize)
764 return (bufsize);
765 }
766
767 return (sz);
768 }
769
770 /*
771 * helper function to process a set of flags and set bits in the
772 * appropriate masks.
773 */
774 int
fill_flags(struct _s_x * flags,char * p,char ** e,uint32_t * set,uint32_t * clear)775 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
776 uint32_t *clear)
777 {
778 char *q; /* points to the separator */
779 int val;
780 uint32_t *which; /* mask we are working on */
781
782 while (p && *p) {
783 if (*p == '!') {
784 p++;
785 which = clear;
786 } else
787 which = set;
788 q = strchr(p, ',');
789 if (q)
790 *q++ = '\0';
791 val = match_token(flags, p);
792 if (val <= 0) {
793 if (e != NULL)
794 *e = p;
795 return (-1);
796 }
797 *which |= (uint32_t)val;
798 p = q;
799 }
800 return (0);
801 }
802
803 void
print_flags_buffer(char * buf,size_t sz,struct _s_x * list,uint32_t set)804 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
805 {
806 char const *comma = "";
807 int i, l;
808
809 for (i = 0; list[i].x != 0; i++) {
810 if ((set & list[i].x) == 0)
811 continue;
812
813 set &= ~list[i].x;
814 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
815 if (l < 0 || (size_t)l >= sz)
816 return;
817 comma = ",";
818 buf += l;
819 sz -=l;
820 }
821 }
822
823 /*
824 * _substrcmp takes two strings and returns 1 if they do not match,
825 * and 0 if they match exactly or the first string is a sub-string
826 * of the second. A warning is printed to stderr in the case that the
827 * first string is a sub-string of the second.
828 *
829 * This function will be removed in the future through the usual
830 * deprecation process.
831 */
832 int
_substrcmp(const char * str1,const char * str2)833 _substrcmp(const char *str1, const char* str2)
834 {
835
836 if (strncmp(str1, str2, strlen(str1)) != 0)
837 return 1;
838
839 if (strlen(str1) != strlen(str2))
840 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
841 str1, str2);
842 return 0;
843 }
844
845 /*
846 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
847 * and 0 if they match exactly or the second string is a sub-string
848 * of the first. A warning is printed to stderr in the case that the
849 * first string does not match the third.
850 *
851 * This function exists to warn about the bizarre construction
852 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
853 * for "bytes". The problem is that in addition to accepting "by",
854 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
855 * other string beginning with "by".
856 *
857 * This function will be removed in the future through the usual
858 * deprecation process.
859 */
860 int
_substrcmp2(const char * str1,const char * str2,const char * str3)861 _substrcmp2(const char *str1, const char* str2, const char* str3)
862 {
863
864 if (strncmp(str1, str2, strlen(str2)) != 0)
865 return 1;
866
867 if (strcmp(str1, str3) != 0)
868 warnx("DEPRECATED: '%s' matched '%s'",
869 str1, str3);
870 return 0;
871 }
872
873 /*
874 * prints one port, symbolic or numeric
875 */
876 static void
print_port(struct buf_pr * bp,int proto,uint16_t port)877 print_port(struct buf_pr *bp, int proto, uint16_t port)
878 {
879
880 if (proto == IPPROTO_ETHERTYPE) {
881 char const *s;
882
883 if (g_co.do_resolv && (s = match_value(ether_types, port)) )
884 bprintf(bp, "%s", s);
885 else
886 bprintf(bp, "0x%04x", port);
887 } else {
888 struct servent *se = NULL;
889 if (g_co.do_resolv) {
890 struct protoent *pe = getprotobynumber(proto);
891
892 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
893 }
894 if (se)
895 bprintf(bp, "%s", se->s_name);
896 else
897 bprintf(bp, "%d", port);
898 }
899 }
900
901 static struct _s_x _port_name[] = {
902 {"dst-port", O_IP_DSTPORT},
903 {"src-port", O_IP_SRCPORT},
904 {"ipid", O_IPID},
905 {"iplen", O_IPLEN},
906 {"ipttl", O_IPTTL},
907 {"mac-type", O_MAC_TYPE},
908 {"tcpdatalen", O_TCPDATALEN},
909 {"tcpmss", O_TCPMSS},
910 {"tcpwin", O_TCPWIN},
911 {"tagged", O_TAGGED},
912 {NULL, 0}
913 };
914
915 /*
916 * Print the values in a list 16-bit items of the types above.
917 * XXX todo: add support for mask.
918 */
919 static void
print_newports(struct buf_pr * bp,const ipfw_insn_u16 * cmd,int proto,int opcode)920 print_newports(struct buf_pr *bp, const ipfw_insn_u16 *cmd, int proto, int opcode)
921 {
922 const uint16_t *p = cmd->ports;
923 int i;
924 char const *sep;
925
926 if (opcode != 0) {
927 sep = match_value(_port_name, opcode);
928 if (sep == NULL)
929 sep = "???";
930 bprintf(bp, " %s", sep);
931 }
932 sep = " ";
933 for (i = F_LEN((const ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
934 bprintf(bp, "%s", sep);
935 print_port(bp, proto, p[0]);
936 if (p[0] != p[1]) {
937 bprintf(bp, "-");
938 print_port(bp, proto, p[1]);
939 }
940 sep = ",";
941 }
942 }
943
944 /*
945 * Like strtol, but also translates service names into port numbers
946 * for some protocols.
947 * In particular:
948 * proto == -1 disables the protocol check;
949 * proto == IPPROTO_ETHERTYPE looks up an internal table
950 * proto == <some value in /etc/protocols> matches the values there.
951 * Returns *end == s in case the parameter is not found.
952 */
953 static int
strtoport(char * s,char ** end,int base,int proto)954 strtoport(char *s, char **end, int base, int proto)
955 {
956 char *p, *buf;
957 char *s1;
958 int i;
959
960 *end = s; /* default - not found */
961 if (*s == '\0')
962 return 0; /* not found */
963
964 if (isdigit(*s))
965 return strtol(s, end, base);
966
967 /*
968 * find separator. '\\' escapes the next char.
969 */
970 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
971 *s1 == '_' || *s1 == '.') ; s1++)
972 if (*s1 == '\\' && s1[1] != '\0')
973 s1++;
974
975 buf = safe_calloc(s1 - s + 1, 1);
976
977 /*
978 * copy into a buffer skipping backslashes
979 */
980 for (p = s, i = 0; p != s1 ; p++)
981 if (*p != '\\')
982 buf[i++] = *p;
983 buf[i++] = '\0';
984
985 if (proto == IPPROTO_ETHERTYPE) {
986 i = match_token(ether_types, buf);
987 free(buf);
988 if (i != -1) { /* found */
989 *end = s1;
990 return i;
991 }
992 } else {
993 struct protoent *pe = NULL;
994 struct servent *se;
995
996 if (proto != 0)
997 pe = getprotobynumber(proto);
998 setservent(1);
999 se = getservbyname(buf, pe ? pe->p_name : NULL);
1000 free(buf);
1001 if (se != NULL) {
1002 *end = s1;
1003 return ntohs(se->s_port);
1004 }
1005 }
1006 return 0; /* not found */
1007 }
1008
1009 /*
1010 * Fill the body of the command with the list of port ranges.
1011 */
1012 static int
fill_newports(ipfw_insn_u16 * cmd,char * av,int proto,int cblen)1013 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
1014 {
1015 uint16_t a, b, *p = cmd->ports;
1016 int i = 0;
1017 char *s = av;
1018
1019 while (*s) {
1020 a = strtoport(av, &s, 0, proto);
1021 if (s == av) /* empty or invalid argument */
1022 return (0);
1023
1024 CHECK_LENGTH(cblen, i + 2);
1025
1026 switch (*s) {
1027 case '-': /* a range */
1028 av = s + 1;
1029 b = strtoport(av, &s, 0, proto);
1030 /* Reject expressions like '1-abc' or '1-2-3'. */
1031 if (s == av || (*s != ',' && *s != '\0'))
1032 return (0);
1033 p[0] = a;
1034 p[1] = b;
1035 break;
1036 case ',': /* comma separated list */
1037 case '\0':
1038 p[0] = p[1] = a;
1039 break;
1040 default:
1041 warnx("port list: invalid separator <%c> in <%s>",
1042 *s, av);
1043 return (0);
1044 }
1045
1046 i++;
1047 p += 2;
1048 av = s + 1;
1049 }
1050 if (i > 0) {
1051 if (i + 1 > F_LEN_MASK)
1052 errx(EX_DATAERR, "too many ports/ranges\n");
1053 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1054 }
1055 return (i);
1056 }
1057
1058 /*
1059 * Fill the body of the command with the list of DiffServ codepoints.
1060 */
1061 static void
fill_dscp(ipfw_insn * cmd,char * av,int cblen)1062 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1063 {
1064 uint32_t *low, *high;
1065 char *s = av, *a;
1066 int code;
1067
1068 cmd->opcode = O_DSCP;
1069 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1070
1071 CHECK_CMDLEN;
1072
1073 low = (uint32_t *)(cmd + 1);
1074 high = low + 1;
1075
1076 *low = 0;
1077 *high = 0;
1078
1079 while (s != NULL) {
1080 a = strchr(s, ',');
1081
1082 if (a != NULL)
1083 *a++ = '\0';
1084
1085 if (isalpha(*s)) {
1086 if ((code = match_token(f_ipdscp, s)) == -1)
1087 errx(EX_DATAERR, "Unknown DSCP code");
1088 } else {
1089 code = strtoul(s, NULL, 10);
1090 if (code < 0 || code > 63)
1091 errx(EX_DATAERR, "Invalid DSCP value");
1092 }
1093
1094 if (code >= 32)
1095 *high |= 1 << (code - 32);
1096 else
1097 *low |= 1 << code;
1098
1099 s = a;
1100 }
1101 }
1102
1103 static struct _s_x icmpcodes[] = {
1104 { "net", ICMP_UNREACH_NET },
1105 { "host", ICMP_UNREACH_HOST },
1106 { "protocol", ICMP_UNREACH_PROTOCOL },
1107 { "port", ICMP_UNREACH_PORT },
1108 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1109 { "srcfail", ICMP_UNREACH_SRCFAIL },
1110 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1111 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1112 { "isolated", ICMP_UNREACH_ISOLATED },
1113 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1114 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1115 { "tosnet", ICMP_UNREACH_TOSNET },
1116 { "toshost", ICMP_UNREACH_TOSHOST },
1117 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1118 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1119 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1120 { NULL, 0 }
1121 };
1122
1123 static void
fill_reject_code(u_short * codep,char * str)1124 fill_reject_code(u_short *codep, char *str)
1125 {
1126 int val;
1127 char *s;
1128
1129 val = strtoul(str, &s, 0);
1130 if (s == str || *s != '\0' || val >= 0x100)
1131 val = match_token(icmpcodes, str);
1132 if (val < 0)
1133 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1134 *codep = val;
1135 return;
1136 }
1137
1138 static void
print_reject_code(struct buf_pr * bp,uint16_t code)1139 print_reject_code(struct buf_pr *bp, uint16_t code)
1140 {
1141 char const *s;
1142
1143 if ((s = match_value(icmpcodes, code)) != NULL)
1144 bprintf(bp, "unreach %s", s);
1145 else
1146 bprintf(bp, "unreach %u", code);
1147 }
1148
1149 /*
1150 * Returns the number of bits set (from left) in a contiguous bitmask,
1151 * or -1 if the mask is not contiguous.
1152 * XXX this needs a proper fix.
1153 * This effectively works on masks in big-endian (network) format.
1154 * when compiled on little endian architectures.
1155 *
1156 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1157 * the first bit on the wire is bit 0 of the first byte.
1158 * len is the max length in bits.
1159 */
1160 int
contigmask(const uint8_t * p,int len)1161 contigmask(const uint8_t *p, int len)
1162 {
1163 int i, n;
1164
1165 for (i=0; i<len ; i++)
1166 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1167 break;
1168 for (n=i+1; n < len; n++)
1169 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1170 return -1; /* mask not contiguous */
1171 return i;
1172 }
1173
1174 /*
1175 * print flags set/clear in the two bitmasks passed as parameters.
1176 * There is a specialized check for f_tcpflags.
1177 */
1178 static void
print_flags(struct buf_pr * bp,char const * name,const ipfw_insn * cmd,struct _s_x * list)1179 print_flags(struct buf_pr *bp, char const *name, const ipfw_insn *cmd,
1180 struct _s_x *list)
1181 {
1182 char const *comma = "";
1183 int i;
1184 uint8_t set = cmd->arg1 & 0xff;
1185 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1186
1187 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1188 bprintf(bp, " setup");
1189 return;
1190 }
1191
1192 bprintf(bp, " %s ", name);
1193 for (i=0; list[i].x != 0; i++) {
1194 if (set & list[i].x) {
1195 set &= ~list[i].x;
1196 bprintf(bp, "%s%s", comma, list[i].s);
1197 comma = ",";
1198 }
1199 if (clear & list[i].x) {
1200 clear &= ~list[i].x;
1201 bprintf(bp, "%s!%s", comma, list[i].s);
1202 comma = ",";
1203 }
1204 }
1205 }
1206
1207
1208 /*
1209 * Print the ip address contained in a command.
1210 */
1211 static void
print_ip(struct buf_pr * bp,const struct format_opts * fo,const ipfw_insn_ip * cmd)1212 print_ip(struct buf_pr *bp, const struct format_opts *fo,
1213 const ipfw_insn_ip *cmd)
1214 {
1215 struct hostent *he = NULL;
1216 const struct in_addr *ia;
1217 const uint32_t *a = ((const ipfw_insn_u32 *)cmd)->d;
1218 uint32_t len = F_LEN((const ipfw_insn *)cmd);
1219 char *t;
1220
1221 bprintf(bp, " ");
1222 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1223 const char *arg;
1224
1225 arg = match_value(lookup_keys, a[1]);
1226 t = table_search_ctlv(fo->tstate,
1227 ((const ipfw_insn *)cmd)->arg1);
1228 bprintf(bp, "lookup %s %s", arg, t);
1229 return;
1230 }
1231 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1232 bprintf(bp, "me");
1233 return;
1234 }
1235 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1236 cmd->o.opcode == O_IP_DST_LOOKUP) {
1237 t = table_search_ctlv(fo->tstate,
1238 ((const ipfw_insn *)cmd)->arg1);
1239 bprintf(bp, "table(%s", t);
1240 if (len == F_INSN_SIZE(ipfw_insn_u32))
1241 bprintf(bp, ",%u", *a);
1242 bprintf(bp, ")");
1243 return;
1244 }
1245 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1246 const uint32_t *map = (const uint32_t *)&cmd->mask;
1247 struct in_addr addr;
1248 uint32_t x;
1249 int i, j;
1250 char comma = '{';
1251
1252 x = cmd->o.arg1 - 1;
1253 x = htonl(~x);
1254 addr.s_addr = htonl(cmd->addr.s_addr);
1255 bprintf(bp, "%s/%d", inet_ntoa(addr),
1256 contigmask((uint8_t *)&x, 32));
1257 x = cmd->addr.s_addr;
1258 x &= 0xff; /* base */
1259 /*
1260 * Print bits and ranges.
1261 * Locate first bit set (i), then locate first bit unset (j).
1262 * If we have 3+ consecutive bits set, then print them as a
1263 * range, otherwise only print the initial bit and rescan.
1264 */
1265 for (i=0; i < cmd->o.arg1; i++)
1266 if (map[i/32] & (1<<(i & 31))) {
1267 for (j=i+1; j < cmd->o.arg1; j++)
1268 if (!(map[ j/32] & (1<<(j & 31))))
1269 break;
1270 bprintf(bp, "%c%d", comma, i+x);
1271 if (j>i+2) { /* range has at least 3 elements */
1272 bprintf(bp, "-%d", j-1+x);
1273 i = j-1;
1274 }
1275 comma = ',';
1276 }
1277 bprintf(bp, "}");
1278 return;
1279 }
1280 /*
1281 * len == 2 indicates a single IP, whereas lists of 1 or more
1282 * addr/mask pairs have len = (2n+1). We convert len to n so we
1283 * use that to count the number of entries.
1284 */
1285 for (len = len / 2; len > 0; len--, a += 2) {
1286 int mb = /* mask length */
1287 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1288 32 : contigmask((const uint8_t *)&(a[1]), 32);
1289 if (mb == 32 && g_co.do_resolv)
1290 he = gethostbyaddr((const char *)&(a[0]), sizeof(in_addr_t),
1291 AF_INET);
1292 if (he != NULL) /* resolved to name */
1293 bprintf(bp, "%s", he->h_name);
1294 else if (mb == 0) /* any */
1295 bprintf(bp, "any");
1296 else { /* numeric IP followed by some kind of mask */
1297 ia = (const struct in_addr *)&a[0];
1298 bprintf(bp, "%s", inet_ntoa(*ia));
1299 if (mb < 0) {
1300 ia = (const struct in_addr *)&a[1];
1301 bprintf(bp, ":%s", inet_ntoa(*ia));
1302 } else if (mb < 32)
1303 bprintf(bp, "/%d", mb);
1304 }
1305 if (len > 1)
1306 bprintf(bp, ",");
1307 }
1308 }
1309
1310 /*
1311 * prints a MAC address/mask pair
1312 */
1313 static void
format_mac(struct buf_pr * bp,const uint8_t * addr,const uint8_t * mask)1314 format_mac(struct buf_pr *bp, const uint8_t *addr, const uint8_t *mask)
1315 {
1316 int l = contigmask(mask, 48);
1317
1318 if (l == 0)
1319 bprintf(bp, " any");
1320 else {
1321 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1322 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1323 if (l == -1)
1324 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1325 mask[0], mask[1], mask[2],
1326 mask[3], mask[4], mask[5]);
1327 else if (l < 48)
1328 bprintf(bp, "/%d", l);
1329 }
1330 }
1331
1332 static void
print_mac(struct buf_pr * bp,const ipfw_insn_mac * mac)1333 print_mac(struct buf_pr *bp, const ipfw_insn_mac *mac)
1334 {
1335
1336 bprintf(bp, " MAC");
1337 format_mac(bp, mac->addr, mac->mask);
1338 format_mac(bp, mac->addr + 6, mac->mask + 6);
1339 }
1340
1341 static void
print_mac_lookup(struct buf_pr * bp,const struct format_opts * fo,const ipfw_insn * cmd)1342 print_mac_lookup(struct buf_pr *bp, const struct format_opts *fo,
1343 const ipfw_insn *cmd)
1344 {
1345 uint32_t len = F_LEN(cmd);
1346 char *t;
1347
1348 bprintf(bp, " ");
1349
1350 t = table_search_ctlv(fo->tstate, cmd->arg1);
1351 bprintf(bp, "table(%s", t);
1352 if (len == F_INSN_SIZE(ipfw_insn_u32))
1353 bprintf(bp, ",%u", ((const ipfw_insn_u32 *)cmd)->d[0]);
1354 bprintf(bp, ")");
1355 }
1356
1357 static void
fill_icmptypes(ipfw_insn_u32 * cmd,char * av)1358 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1359 {
1360 uint8_t type;
1361
1362 cmd->d[0] = 0;
1363 while (*av) {
1364 if (*av == ',')
1365 av++;
1366
1367 type = strtoul(av, &av, 0);
1368
1369 if (*av != ',' && *av != '\0')
1370 errx(EX_DATAERR, "invalid ICMP type");
1371
1372 if (type > 31)
1373 errx(EX_DATAERR, "ICMP type out of range");
1374
1375 cmd->d[0] |= 1 << type;
1376 }
1377 cmd->o.opcode = O_ICMPTYPE;
1378 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1379 }
1380
1381 static void
print_icmptypes(struct buf_pr * bp,const ipfw_insn_u32 * cmd)1382 print_icmptypes(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1383 {
1384 int i;
1385 char sep= ' ';
1386
1387 bprintf(bp, " icmptypes");
1388 for (i = 0; i < 32; i++) {
1389 if ( (cmd->d[0] & (1 << (i))) == 0)
1390 continue;
1391 bprintf(bp, "%c%d", sep, i);
1392 sep = ',';
1393 }
1394 }
1395
1396 static void
print_dscp(struct buf_pr * bp,const ipfw_insn_u32 * cmd)1397 print_dscp(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1398 {
1399 const uint32_t *v;
1400 const char *code;
1401 int i = 0;
1402 char sep= ' ';
1403
1404 bprintf(bp, " dscp");
1405 v = cmd->d;
1406 while (i < 64) {
1407 if (*v & (1 << i)) {
1408 if ((code = match_value(f_ipdscp, i)) != NULL)
1409 bprintf(bp, "%c%s", sep, code);
1410 else
1411 bprintf(bp, "%c%d", sep, i);
1412 sep = ',';
1413 }
1414
1415 if ((++i % 32) == 0)
1416 v++;
1417 }
1418 }
1419
1420 #define insntod(cmd, type) ((const ipfw_insn_ ## type *)(cmd))
1421 struct show_state {
1422 struct ip_fw_rule *rule;
1423 const ipfw_insn *eaction;
1424 uint8_t *printed;
1425 int flags;
1426 #define HAVE_PROTO 0x0001
1427 #define HAVE_SRCIP 0x0002
1428 #define HAVE_DSTIP 0x0004
1429 #define HAVE_PROBE_STATE 0x0008
1430 int proto;
1431 int or_block;
1432 };
1433
1434 static int
init_show_state(struct show_state * state,struct ip_fw_rule * rule)1435 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1436 {
1437
1438 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1439 if (state->printed == NULL)
1440 return (ENOMEM);
1441 state->rule = rule;
1442 state->eaction = NULL;
1443 state->flags = 0;
1444 state->proto = 0;
1445 state->or_block = 0;
1446 return (0);
1447 }
1448
1449 static void
free_show_state(struct show_state * state)1450 free_show_state(struct show_state *state)
1451 {
1452
1453 free(state->printed);
1454 }
1455
1456 static uint8_t
is_printed_opcode(struct show_state * state,const ipfw_insn * cmd)1457 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1458 {
1459
1460 return (state->printed[cmd - state->rule->cmd]);
1461 }
1462
1463 static void
mark_printed(struct show_state * state,const ipfw_insn * cmd)1464 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1465 {
1466
1467 state->printed[cmd - state->rule->cmd] = 1;
1468 }
1469
1470 static void
print_limit_mask(struct buf_pr * bp,const ipfw_insn_limit * limit)1471 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1472 {
1473 struct _s_x *p = limit_masks;
1474 char const *comma = " ";
1475 uint8_t x;
1476
1477 for (x = limit->limit_mask; p->x != 0; p++) {
1478 if ((x & p->x) == p->x) {
1479 x &= ~p->x;
1480 bprintf(bp, "%s%s", comma, p->s);
1481 comma = ",";
1482 }
1483 }
1484 bprint_uint_arg(bp, " ", limit->conn_limit);
1485 }
1486
1487 static int
print_instruction(struct buf_pr * bp,const struct format_opts * fo,struct show_state * state,const ipfw_insn * cmd)1488 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1489 struct show_state *state, const ipfw_insn *cmd)
1490 {
1491 struct protoent *pe;
1492 struct passwd *pwd;
1493 struct group *grp;
1494 const char *s;
1495 double d;
1496
1497 if (is_printed_opcode(state, cmd))
1498 return (0);
1499 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1500 bprintf(bp, " {");
1501 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1502 bprintf(bp, " not");
1503
1504 switch (cmd->opcode) {
1505 case O_PROB:
1506 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1507 bprintf(bp, "prob %f ", d);
1508 break;
1509 case O_PROBE_STATE: /* no need to print anything here */
1510 state->flags |= HAVE_PROBE_STATE;
1511 break;
1512 case O_IP_SRC:
1513 case O_IP_SRC_LOOKUP:
1514 case O_IP_SRC_MASK:
1515 case O_IP_SRC_ME:
1516 case O_IP_SRC_SET:
1517 if (state->flags & HAVE_SRCIP)
1518 bprintf(bp, " src-ip");
1519 print_ip(bp, fo, insntod(cmd, ip));
1520 break;
1521 case O_IP_DST:
1522 case O_IP_DST_LOOKUP:
1523 case O_IP_DST_MASK:
1524 case O_IP_DST_ME:
1525 case O_IP_DST_SET:
1526 if (state->flags & HAVE_DSTIP)
1527 bprintf(bp, " dst-ip");
1528 print_ip(bp, fo, insntod(cmd, ip));
1529 break;
1530 case O_IP6_SRC:
1531 case O_IP6_SRC_MASK:
1532 case O_IP6_SRC_ME:
1533 if (state->flags & HAVE_SRCIP)
1534 bprintf(bp, " src-ip6");
1535 print_ip6(bp, insntod(cmd, ip6));
1536 break;
1537 case O_IP6_DST:
1538 case O_IP6_DST_MASK:
1539 case O_IP6_DST_ME:
1540 if (state->flags & HAVE_DSTIP)
1541 bprintf(bp, " dst-ip6");
1542 print_ip6(bp, insntod(cmd, ip6));
1543 break;
1544 case O_MAC_SRC_LOOKUP:
1545 bprintf(bp, " src-mac");
1546 print_mac_lookup(bp, fo, cmd);
1547 break;
1548 case O_MAC_DST_LOOKUP:
1549 bprintf(bp, " dst-mac");
1550 print_mac_lookup(bp, fo, cmd);
1551 break;
1552 case O_FLOW6ID:
1553 print_flow6id(bp, insntod(cmd, u32));
1554 break;
1555 case O_IP_DSTPORT:
1556 case O_IP_SRCPORT:
1557 print_newports(bp, insntod(cmd, u16), state->proto,
1558 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1559 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1560 break;
1561 case O_PROTO:
1562 pe = getprotobynumber(cmd->arg1);
1563 if (state->flags & HAVE_PROTO)
1564 bprintf(bp, " proto");
1565 if (pe != NULL)
1566 bprintf(bp, " %s", pe->p_name);
1567 else
1568 bprintf(bp, " %u", cmd->arg1);
1569 state->proto = cmd->arg1;
1570 break;
1571 case O_MACADDR2:
1572 print_mac(bp, insntod(cmd, mac));
1573 break;
1574 case O_MAC_TYPE:
1575 print_newports(bp, insntod(cmd, u16),
1576 IPPROTO_ETHERTYPE, cmd->opcode);
1577 break;
1578 case O_FRAG:
1579 print_flags(bp, "frag", cmd, f_ipoff);
1580 break;
1581 case O_FIB:
1582 bprintf(bp, " fib %u", cmd->arg1);
1583 break;
1584 case O_SOCKARG:
1585 bprintf(bp, " sockarg");
1586 break;
1587 case O_IN:
1588 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1589 break;
1590 case O_DIVERTED:
1591 switch (cmd->arg1) {
1592 case 3:
1593 bprintf(bp, " diverted");
1594 break;
1595 case 2:
1596 bprintf(bp, " diverted-output");
1597 break;
1598 case 1:
1599 bprintf(bp, " diverted-loopback");
1600 break;
1601 default:
1602 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1603 break;
1604 }
1605 break;
1606 case O_LAYER2:
1607 bprintf(bp, " layer2");
1608 break;
1609 case O_XMIT:
1610 case O_RECV:
1611 case O_VIA:
1612 if (cmd->opcode == O_XMIT)
1613 s = "xmit";
1614 else if (cmd->opcode == O_RECV)
1615 s = "recv";
1616 else /* if (cmd->opcode == O_VIA) */
1617 s = "via";
1618 switch (insntod(cmd, if)->name[0]) {
1619 case '\0':
1620 bprintf(bp, " %s %s", s,
1621 inet_ntoa(insntod(cmd, if)->p.ip));
1622 break;
1623 case '\1':
1624 bprintf(bp, " %s table(%s)", s,
1625 table_search_ctlv(fo->tstate,
1626 insntod(cmd, if)->p.kidx));
1627 break;
1628 default:
1629 bprintf(bp, " %s %s", s,
1630 insntod(cmd, if)->name);
1631 }
1632 break;
1633 case O_IP_FLOW_LOOKUP:
1634 s = table_search_ctlv(fo->tstate, cmd->arg1);
1635 bprintf(bp, " flow table(%s", s);
1636 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1637 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1638 bprintf(bp, ")");
1639 break;
1640 case O_IPID:
1641 case O_IPTTL:
1642 case O_IPLEN:
1643 case O_TCPDATALEN:
1644 case O_TCPMSS:
1645 case O_TCPWIN:
1646 if (F_LEN(cmd) == 1) {
1647 switch (cmd->opcode) {
1648 case O_IPID:
1649 s = "ipid";
1650 break;
1651 case O_IPTTL:
1652 s = "ipttl";
1653 break;
1654 case O_IPLEN:
1655 s = "iplen";
1656 break;
1657 case O_TCPDATALEN:
1658 s = "tcpdatalen";
1659 break;
1660 case O_TCPMSS:
1661 s = "tcpmss";
1662 break;
1663 case O_TCPWIN:
1664 s = "tcpwin";
1665 break;
1666 default:
1667 s = "<unknown>";
1668 break;
1669 }
1670 bprintf(bp, " %s %u", s, cmd->arg1);
1671 } else
1672 print_newports(bp, insntod(cmd, u16), 0,
1673 cmd->opcode);
1674 break;
1675 case O_IPVER:
1676 bprintf(bp, " ipver %u", cmd->arg1);
1677 break;
1678 case O_IPPRECEDENCE:
1679 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1680 break;
1681 case O_DSCP:
1682 print_dscp(bp, insntod(cmd, u32));
1683 break;
1684 case O_IPOPT:
1685 print_flags(bp, "ipoptions", cmd, f_ipopts);
1686 break;
1687 case O_IPTOS:
1688 print_flags(bp, "iptos", cmd, f_iptos);
1689 break;
1690 case O_ICMPTYPE:
1691 print_icmptypes(bp, insntod(cmd, u32));
1692 break;
1693 case O_ESTAB:
1694 bprintf(bp, " established");
1695 break;
1696 case O_TCPFLAGS:
1697 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1698 break;
1699 case O_TCPOPTS:
1700 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1701 break;
1702 case O_TCPACK:
1703 bprintf(bp, " tcpack %d",
1704 ntohl(insntod(cmd, u32)->d[0]));
1705 break;
1706 case O_TCPSEQ:
1707 bprintf(bp, " tcpseq %d",
1708 ntohl(insntod(cmd, u32)->d[0]));
1709 break;
1710 case O_UID:
1711 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1712 if (pwd != NULL)
1713 bprintf(bp, " uid %s", pwd->pw_name);
1714 else
1715 bprintf(bp, " uid %u",
1716 insntod(cmd, u32)->d[0]);
1717 break;
1718 case O_GID:
1719 grp = getgrgid(insntod(cmd, u32)->d[0]);
1720 if (grp != NULL)
1721 bprintf(bp, " gid %s", grp->gr_name);
1722 else
1723 bprintf(bp, " gid %u",
1724 insntod(cmd, u32)->d[0]);
1725 break;
1726 case O_JAIL:
1727 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1728 break;
1729 case O_VERREVPATH:
1730 bprintf(bp, " verrevpath");
1731 break;
1732 case O_VERSRCREACH:
1733 bprintf(bp, " versrcreach");
1734 break;
1735 case O_ANTISPOOF:
1736 bprintf(bp, " antispoof");
1737 break;
1738 case O_IPSEC:
1739 bprintf(bp, " ipsec");
1740 break;
1741 case O_NOP:
1742 bprintf(bp, " // %s", (const char *)(cmd + 1));
1743 break;
1744 case O_KEEP_STATE:
1745 if (state->flags & HAVE_PROBE_STATE)
1746 bprintf(bp, " keep-state");
1747 else
1748 bprintf(bp, " record-state");
1749 bprintf(bp, " :%s",
1750 object_search_ctlv(fo->tstate, cmd->arg1,
1751 IPFW_TLV_STATE_NAME));
1752 break;
1753 case O_LIMIT:
1754 if (state->flags & HAVE_PROBE_STATE)
1755 bprintf(bp, " limit");
1756 else
1757 bprintf(bp, " set-limit");
1758 print_limit_mask(bp, insntod(cmd, limit));
1759 bprintf(bp, " :%s",
1760 object_search_ctlv(fo->tstate, cmd->arg1,
1761 IPFW_TLV_STATE_NAME));
1762 break;
1763 case O_IP6:
1764 if (state->flags & HAVE_PROTO)
1765 bprintf(bp, " proto");
1766 bprintf(bp, " ip6");
1767 break;
1768 case O_IP4:
1769 if (state->flags & HAVE_PROTO)
1770 bprintf(bp, " proto");
1771 bprintf(bp, " ip4");
1772 break;
1773 case O_ICMP6TYPE:
1774 print_icmp6types(bp, insntod(cmd, u32));
1775 break;
1776 case O_EXT_HDR:
1777 print_ext6hdr(bp, cmd);
1778 break;
1779 case O_TAGGED:
1780 if (F_LEN(cmd) == 1)
1781 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1782 else
1783 print_newports(bp, insntod(cmd, u16),
1784 0, O_TAGGED);
1785 break;
1786 case O_SKIP_ACTION:
1787 bprintf(bp, " defer-immediate-action");
1788 break;
1789 default:
1790 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1791 cmd->len);
1792 }
1793 if (cmd->len & F_OR) {
1794 bprintf(bp, " or");
1795 state->or_block = 1;
1796 } else if (state->or_block != 0) {
1797 bprintf(bp, " }");
1798 state->or_block = 0;
1799 }
1800 mark_printed(state, cmd);
1801
1802 return (1);
1803 }
1804
1805 static ipfw_insn *
print_opcode(struct buf_pr * bp,struct format_opts * fo,struct show_state * state,int opcode)1806 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1807 struct show_state *state, int opcode)
1808 {
1809 ipfw_insn *cmd;
1810 int l;
1811
1812 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1813 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1814 /* We use zero opcode to print the rest of options */
1815 if (opcode >= 0 && cmd->opcode != opcode)
1816 continue;
1817 /*
1818 * Skip O_NOP, when we printing the rest
1819 * of options, it will be handled separately.
1820 */
1821 if (cmd->opcode == O_NOP && opcode != O_NOP)
1822 continue;
1823 if (!print_instruction(bp, fo, state, cmd))
1824 continue;
1825 return (cmd);
1826 }
1827 return (NULL);
1828 }
1829
1830 static void
print_fwd(struct buf_pr * bp,const ipfw_insn * cmd)1831 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1832 {
1833 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1834 const ipfw_insn_sa6 *sa6;
1835 const ipfw_insn_sa *sa;
1836 uint16_t port;
1837
1838 if (cmd->opcode == O_FORWARD_IP) {
1839 sa = insntod(cmd, sa);
1840 port = sa->sa.sin_port;
1841 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1842 bprintf(bp, "fwd tablearg");
1843 else
1844 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1845 } else {
1846 sa6 = insntod(cmd, sa6);
1847 port = sa6->sa.sin6_port;
1848 bprintf(bp, "fwd ");
1849 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1850 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1851 NI_NUMERICHOST) == 0)
1852 bprintf(bp, "%s", buf);
1853 }
1854 if (port != 0)
1855 bprintf(bp, ",%u", port);
1856 }
1857
1858 static int
print_action_instruction(struct buf_pr * bp,const struct format_opts * fo,struct show_state * state,const ipfw_insn * cmd)1859 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1860 struct show_state *state, const ipfw_insn *cmd)
1861 {
1862 const char *s;
1863
1864 if (is_printed_opcode(state, cmd))
1865 return (0);
1866 switch (cmd->opcode) {
1867 case O_CHECK_STATE:
1868 bprintf(bp, "check-state");
1869 if (cmd->arg1 != 0)
1870 s = object_search_ctlv(fo->tstate, cmd->arg1,
1871 IPFW_TLV_STATE_NAME);
1872 else
1873 s = NULL;
1874 bprintf(bp, " :%s", s ? s: "any");
1875 break;
1876 case O_ACCEPT:
1877 bprintf(bp, "allow");
1878 break;
1879 case O_COUNT:
1880 bprintf(bp, "count");
1881 break;
1882 case O_DENY:
1883 bprintf(bp, "deny");
1884 break;
1885 case O_REJECT:
1886 if (cmd->arg1 == ICMP_REJECT_RST)
1887 bprintf(bp, "reset");
1888 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1889 bprintf(bp, "abort");
1890 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1891 bprintf(bp, "reject");
1892 else
1893 print_reject_code(bp, cmd->arg1);
1894 break;
1895 case O_UNREACH6:
1896 if (cmd->arg1 == ICMP6_UNREACH_RST)
1897 bprintf(bp, "reset6");
1898 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1899 bprintf(bp, "abort6");
1900 else
1901 print_unreach6_code(bp, cmd->arg1);
1902 break;
1903 case O_SKIPTO:
1904 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1905 break;
1906 case O_PIPE:
1907 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1908 break;
1909 case O_QUEUE:
1910 bprint_uint_arg(bp, "queue ", cmd->arg1);
1911 break;
1912 case O_DIVERT:
1913 bprint_uint_arg(bp, "divert ", cmd->arg1);
1914 break;
1915 case O_TEE:
1916 bprint_uint_arg(bp, "tee ", cmd->arg1);
1917 break;
1918 case O_NETGRAPH:
1919 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1920 break;
1921 case O_NGTEE:
1922 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1923 break;
1924 case O_FORWARD_IP:
1925 case O_FORWARD_IP6:
1926 print_fwd(bp, cmd);
1927 break;
1928 case O_LOG:
1929 if (insntod(cmd, log)->max_log > 0)
1930 bprintf(bp, " log logamount %d",
1931 insntod(cmd, log)->max_log);
1932 else
1933 bprintf(bp, " log");
1934 break;
1935 case O_ALTQ:
1936 #ifndef NO_ALTQ
1937 print_altq_cmd(bp, insntod(cmd, altq));
1938 #endif
1939 break;
1940 case O_TAG:
1941 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
1942 " tag ", cmd->arg1);
1943 break;
1944 case O_NAT:
1945 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1946 bprint_uint_arg(bp, "nat ", cmd->arg1);
1947 else
1948 bprintf(bp, "nat global");
1949 break;
1950 case O_SETFIB:
1951 if (cmd->arg1 == IP_FW_TARG)
1952 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1953 else
1954 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1955 break;
1956 case O_EXTERNAL_ACTION:
1957 /*
1958 * The external action can consists of two following
1959 * each other opcodes - O_EXTERNAL_ACTION and
1960 * O_EXTERNAL_INSTANCE. The first contains the ID of
1961 * name of external action. The second contains the ID
1962 * of name of external action instance.
1963 * NOTE: in case when external action has no named
1964 * instances support, the second opcode isn't needed.
1965 */
1966 state->eaction = cmd;
1967 s = object_search_ctlv(fo->tstate, cmd->arg1,
1968 IPFW_TLV_EACTION);
1969 if (match_token(rule_eactions, s) != -1)
1970 bprintf(bp, "%s", s);
1971 else
1972 bprintf(bp, "eaction %s", s);
1973 break;
1974 case O_EXTERNAL_INSTANCE:
1975 if (state->eaction == NULL)
1976 break;
1977 /*
1978 * XXX: we need to teach ipfw(9) to rewrite opcodes
1979 * in the user buffer on rule addition. When we add
1980 * the rule, we specify zero TLV type for
1981 * O_EXTERNAL_INSTANCE object. To show correct
1982 * rule after `ipfw add` we need to search instance
1983 * name with zero type. But when we do `ipfw show`
1984 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1985 * macro.
1986 */
1987 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1988 if (s == NULL)
1989 s = object_search_ctlv(fo->tstate,
1990 cmd->arg1, IPFW_TLV_EACTION_NAME(
1991 state->eaction->arg1));
1992 bprintf(bp, " %s", s);
1993 break;
1994 case O_EXTERNAL_DATA:
1995 if (state->eaction == NULL)
1996 break;
1997 /*
1998 * Currently we support data formatting only for
1999 * external data with datalen u16. For unknown data
2000 * print its size in bytes.
2001 */
2002 if (cmd->len == F_INSN_SIZE(ipfw_insn))
2003 bprintf(bp, " %u", cmd->arg1);
2004 else
2005 bprintf(bp, " %ubytes",
2006 cmd->len * sizeof(uint32_t));
2007 break;
2008 case O_SETDSCP:
2009 if (cmd->arg1 == IP_FW_TARG) {
2010 bprintf(bp, "setdscp tablearg");
2011 break;
2012 }
2013 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
2014 if (s != NULL)
2015 bprintf(bp, "setdscp %s", s);
2016 else
2017 bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
2018 break;
2019 case O_REASS:
2020 bprintf(bp, "reass");
2021 break;
2022 case O_CALLRETURN:
2023 if (cmd->len & F_NOT)
2024 bprintf(bp, "return");
2025 else
2026 bprint_uint_arg(bp, "call ", cmd->arg1);
2027 break;
2028 default:
2029 bprintf(bp, "** unrecognized action %d len %d ",
2030 cmd->opcode, cmd->len);
2031 }
2032 mark_printed(state, cmd);
2033
2034 return (1);
2035 }
2036
2037
2038 static ipfw_insn *
print_action(struct buf_pr * bp,struct format_opts * fo,struct show_state * state,uint8_t opcode)2039 print_action(struct buf_pr *bp, struct format_opts *fo,
2040 struct show_state *state, uint8_t opcode)
2041 {
2042 ipfw_insn *cmd;
2043 int l;
2044
2045 for (l = state->rule->cmd_len - state->rule->act_ofs,
2046 cmd = ACTION_PTR(state->rule); l > 0;
2047 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2048 if (cmd->opcode != opcode)
2049 continue;
2050 if (!print_action_instruction(bp, fo, state, cmd))
2051 continue;
2052 return (cmd);
2053 }
2054 return (NULL);
2055 }
2056
2057 static void
print_proto(struct buf_pr * bp,struct format_opts * fo,struct show_state * state)2058 print_proto(struct buf_pr *bp, struct format_opts *fo,
2059 struct show_state *state)
2060 {
2061 ipfw_insn *cmd;
2062 int l, proto, ip4, ip6;
2063
2064 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2065 proto = ip4 = ip6 = 0;
2066 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2067 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2068 switch (cmd->opcode) {
2069 case O_PROTO:
2070 proto++;
2071 break;
2072 case O_IP4:
2073 ip4 = 1;
2074 if (cmd->len & F_OR)
2075 ip4++;
2076 break;
2077 case O_IP6:
2078 ip6 = 1;
2079 if (cmd->len & F_OR)
2080 ip6++;
2081 break;
2082 default:
2083 continue;
2084 }
2085 }
2086 if (proto == 0 && ip4 == 0 && ip6 == 0) {
2087 state->proto = IPPROTO_IP;
2088 state->flags |= HAVE_PROTO;
2089 bprintf(bp, " ip");
2090 return;
2091 }
2092 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2093 cmd = NULL;
2094 if (ip4 || ip6)
2095 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2096 if (cmd != NULL && (cmd->len & F_OR))
2097 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2098 if (cmd == NULL || (cmd->len & F_OR))
2099 for (l = proto; l > 0; l--) {
2100 cmd = print_opcode(bp, fo, state, O_PROTO);
2101 if (cmd == NULL || (cmd->len & F_OR) == 0)
2102 break;
2103 }
2104 /* Initialize proto, it is used by print_newports() */
2105 state->flags |= HAVE_PROTO;
2106 if (state->proto == 0 && ip6 != 0)
2107 state->proto = IPPROTO_IPV6;
2108 }
2109
2110 static int
match_opcode(int opcode,const int opcodes[],size_t nops)2111 match_opcode(int opcode, const int opcodes[], size_t nops)
2112 {
2113 size_t i;
2114
2115 for (i = 0; i < nops; i++)
2116 if (opcode == opcodes[i])
2117 return (1);
2118 return (0);
2119 }
2120
2121 static void
print_address(struct buf_pr * bp,struct format_opts * fo,struct show_state * state,const int opcodes[],size_t nops,int portop,int flag)2122 print_address(struct buf_pr *bp, struct format_opts *fo,
2123 struct show_state *state, const int opcodes[], size_t nops, int portop,
2124 int flag)
2125 {
2126 ipfw_insn *cmd;
2127 int count, l, portcnt, pf;
2128
2129 count = portcnt = 0;
2130 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2131 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2132 if (match_opcode(cmd->opcode, opcodes, nops))
2133 count++;
2134 else if (cmd->opcode == portop)
2135 portcnt++;
2136 }
2137 if (count == 0)
2138 bprintf(bp, " any");
2139 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2140 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2141 if (!match_opcode(cmd->opcode, opcodes, nops))
2142 continue;
2143 print_instruction(bp, fo, state, cmd);
2144 if ((cmd->len & F_OR) == 0)
2145 break;
2146 count--;
2147 }
2148 /*
2149 * If several O_IP_?PORT opcodes specified, leave them to the
2150 * options section.
2151 */
2152 if (portcnt == 1) {
2153 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2154 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2155 if (cmd->opcode != portop) {
2156 pf = (cmd->len & F_OR);
2157 continue;
2158 }
2159 /* Print opcode iff it is not in OR block. */
2160 if (pf == 0 && (cmd->len & F_OR) == 0)
2161 print_instruction(bp, fo, state, cmd);
2162 break;
2163 }
2164 }
2165 state->flags |= flag;
2166 }
2167
2168 static const int action_opcodes[] = {
2169 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2170 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2171 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2172 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN,
2173 /* keep the following opcodes at the end of the list */
2174 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2175 };
2176
2177 static const int modifier_opcodes[] = {
2178 O_LOG, O_ALTQ, O_TAG
2179 };
2180
2181 static const int src_opcodes[] = {
2182 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2183 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2184 };
2185
2186 static const int dst_opcodes[] = {
2187 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2188 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2189 };
2190
2191 static void
show_static_rule(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,struct ip_fw_rule * rule,struct ip_fw_bcounter * cntr)2192 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2193 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2194 {
2195 static int twidth = 0;
2196 struct show_state state;
2197 ipfw_insn *cmd;
2198 size_t i;
2199
2200 /* Print # DISABLED or skip the rule */
2201 if ((fo->set_mask & (1 << rule->set)) == 0) {
2202 /* disabled mask */
2203 if (!co->show_sets)
2204 return;
2205 else
2206 bprintf(bp, "# DISABLED ");
2207 }
2208 if (init_show_state(&state, rule) != 0) {
2209 warn("init_show_state() failed");
2210 return;
2211 }
2212 bprintf(bp, "%05u ", rule->rulenum);
2213
2214 /* only if counters are available */
2215 if (cntr != NULL) {
2216 /* Print counters if enabled */
2217 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2218 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2219 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2220 }
2221
2222 /* Print timestamp */
2223 if (co->do_time == TIMESTAMP_NUMERIC)
2224 bprintf(bp, "%10u ", cntr->timestamp);
2225 else if (co->do_time == TIMESTAMP_STRING) {
2226 char timestr[30];
2227 time_t t = (time_t)0;
2228
2229 if (twidth == 0) {
2230 strcpy(timestr, ctime(&t));
2231 *strchr(timestr, '\n') = '\0';
2232 twidth = strlen(timestr);
2233 }
2234 if (cntr->timestamp > 0) {
2235 t = _long_to_time(cntr->timestamp);
2236
2237 strcpy(timestr, ctime(&t));
2238 *strchr(timestr, '\n') = '\0';
2239 bprintf(bp, "%s ", timestr);
2240 } else {
2241 bprintf(bp, "%*s ", twidth, "");
2242 }
2243 }
2244 }
2245
2246 /* Print set number */
2247 if (co->show_sets)
2248 bprintf(bp, "set %d ", rule->set);
2249
2250 /* Print the optional "match probability" */
2251 cmd = print_opcode(bp, fo, &state, O_PROB);
2252 /* Print rule action */
2253 for (i = 0; i < nitems(action_opcodes); i++) {
2254 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2255 if (cmd == NULL)
2256 continue;
2257 /* Handle special cases */
2258 switch (cmd->opcode) {
2259 case O_CHECK_STATE:
2260 goto end;
2261 case O_EXTERNAL_ACTION:
2262 case O_EXTERNAL_INSTANCE:
2263 /* External action can have several instructions */
2264 continue;
2265 }
2266 break;
2267 }
2268 /* Print rule modifiers */
2269 for (i = 0; i < nitems(modifier_opcodes); i++)
2270 print_action(bp, fo, &state, modifier_opcodes[i]);
2271 /*
2272 * Print rule body
2273 */
2274 if (co->comment_only != 0)
2275 goto end;
2276
2277 if (rule->flags & IPFW_RULE_JUSTOPTS) {
2278 state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2279 /*
2280 * Print `proto ip` if all opcodes has been already printed.
2281 */
2282 if (memchr(state.printed, 0, rule->act_ofs) == NULL) {
2283 bprintf(bp, " proto ip");
2284 goto end;
2285 }
2286 goto justopts;
2287 }
2288
2289 print_proto(bp, fo, &state);
2290 if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2291 goto justopts;
2292
2293 /* Print source */
2294 bprintf(bp, " from");
2295 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2296 O_IP_SRCPORT, HAVE_SRCIP);
2297
2298 /* Print destination */
2299 bprintf(bp, " to");
2300 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2301 O_IP_DSTPORT, HAVE_DSTIP);
2302
2303 justopts:
2304 /* Print the rest of options */
2305 while (print_opcode(bp, fo, &state, -1))
2306 ;
2307 end:
2308 /* Print comment at the end */
2309 cmd = print_opcode(bp, fo, &state, O_NOP);
2310 if (co->comment_only != 0 && cmd == NULL)
2311 bprintf(bp, " // ...");
2312 bprintf(bp, "\n");
2313 free_show_state(&state);
2314 }
2315
2316 static void
show_dyn_state(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,ipfw_dyn_rule * d)2317 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2318 struct buf_pr *bp, ipfw_dyn_rule *d)
2319 {
2320 struct protoent *pe;
2321 struct in_addr a;
2322 uint16_t rulenum;
2323 char buf[INET6_ADDRSTRLEN];
2324
2325 if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2326 return;
2327
2328 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2329 bprintf(bp, "%05d", rulenum);
2330 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2331 bprintf(bp, " ");
2332 pr_u64(bp, &d->pcnt, fo->pcwidth);
2333 pr_u64(bp, &d->bcnt, fo->bcwidth);
2334 bprintf(bp, "(%ds)", d->expire);
2335 }
2336 switch (d->dyn_type) {
2337 case O_LIMIT_PARENT:
2338 bprintf(bp, " PARENT %d", d->count);
2339 break;
2340 case O_LIMIT:
2341 bprintf(bp, " LIMIT");
2342 break;
2343 case O_KEEP_STATE: /* bidir, no mask */
2344 bprintf(bp, " STATE");
2345 break;
2346 }
2347
2348 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2349 bprintf(bp, " %s", pe->p_name);
2350 else
2351 bprintf(bp, " proto %u", d->id.proto);
2352
2353 if (d->id.addr_type == 4) {
2354 a.s_addr = htonl(d->id.src_ip);
2355 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2356
2357 a.s_addr = htonl(d->id.dst_ip);
2358 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2359 } else if (d->id.addr_type == 6) {
2360 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2361 sizeof(buf)), d->id.src_port);
2362 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2363 buf, sizeof(buf)), d->id.dst_port);
2364 } else
2365 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2366 if (d->kidx != 0)
2367 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2368 d->kidx, IPFW_TLV_STATE_NAME));
2369
2370 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2371 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2372 if (co->verbose) {
2373 bprintf(bp, " state 0x%08x%s", d->state,
2374 d->state ? " ": ",");
2375 if (d->state & IPFW_DYN_ORPHANED)
2376 bprintf(bp, "ORPHANED,");
2377 if ((d->state & BOTH_SYN) == BOTH_SYN)
2378 bprintf(bp, "BOTH_SYN,");
2379 else {
2380 if (d->state & TH_SYN)
2381 bprintf(bp, "F_SYN,");
2382 if (d->state & (TH_SYN << 8))
2383 bprintf(bp, "R_SYN,");
2384 }
2385 if ((d->state & BOTH_FIN) == BOTH_FIN)
2386 bprintf(bp, "BOTH_FIN,");
2387 else {
2388 if (d->state & TH_FIN)
2389 bprintf(bp, "F_FIN,");
2390 if (d->state & (TH_FIN << 8))
2391 bprintf(bp, "R_FIN,");
2392 }
2393 bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2394 d->ack_rev);
2395 }
2396 }
2397
2398 static int
do_range_cmd(int cmd,ipfw_range_tlv * rt)2399 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2400 {
2401 ipfw_range_header rh;
2402 size_t sz;
2403
2404 memset(&rh, 0, sizeof(rh));
2405 memcpy(&rh.range, rt, sizeof(*rt));
2406 rh.range.head.length = sizeof(*rt);
2407 rh.range.head.type = IPFW_TLV_RANGE;
2408 sz = sizeof(rh);
2409
2410 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2411 return (-1);
2412 /* Save number of matched objects */
2413 rt->new_set = rh.range.new_set;
2414 return (0);
2415 }
2416
2417 /*
2418 * This one handles all set-related commands
2419 * ipfw set { show | enable | disable }
2420 * ipfw set swap X Y
2421 * ipfw set move X to Y
2422 * ipfw set move rule X to Y
2423 */
2424 void
ipfw_sets_handler(char * av[])2425 ipfw_sets_handler(char *av[])
2426 {
2427 ipfw_range_tlv rt;
2428 const char *msg;
2429 size_t size;
2430 uint32_t masks[2];
2431 int i;
2432 uint16_t rulenum;
2433 uint8_t cmd;
2434
2435 av++;
2436 memset(&rt, 0, sizeof(rt));
2437
2438 if (av[0] == NULL)
2439 errx(EX_USAGE, "set needs command");
2440 if (_substrcmp(*av, "show") == 0) {
2441 struct format_opts fo;
2442 ipfw_cfg_lheader *cfg;
2443
2444 memset(&fo, 0, sizeof(fo));
2445 if (ipfw_get_config(&g_co, &fo, &cfg, &size) != 0)
2446 err(EX_OSERR, "requesting config failed");
2447
2448 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2449 if ((cfg->set_mask & (1<<i)) == 0) {
2450 printf("%s %d", msg, i);
2451 msg = "";
2452 }
2453 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2454 for (i = 0; i < RESVD_SET; i++)
2455 if ((cfg->set_mask & (1<<i)) != 0) {
2456 printf("%s %d", msg, i);
2457 msg = "";
2458 }
2459 printf("\n");
2460 free(cfg);
2461 } else if (_substrcmp(*av, "swap") == 0) {
2462 av++;
2463 if ( av[0] == NULL || av[1] == NULL )
2464 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2465 rt.set = atoi(av[0]);
2466 rt.new_set = atoi(av[1]);
2467 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2468 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2469 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2470 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2471 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2472 } else if (_substrcmp(*av, "move") == 0) {
2473 av++;
2474 if (av[0] && _substrcmp(*av, "rule") == 0) {
2475 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2476 cmd = IP_FW_XMOVE;
2477 av++;
2478 } else
2479 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2480 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2481 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2482 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2483 rulenum = atoi(av[0]);
2484 rt.new_set = atoi(av[2]);
2485 if (cmd == IP_FW_XMOVE) {
2486 rt.start_rule = rulenum;
2487 rt.end_rule = rulenum;
2488 } else
2489 rt.set = rulenum;
2490 rt.new_set = atoi(av[2]);
2491 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2492 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2493 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2494 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2495 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2496 i = do_range_cmd(cmd, &rt);
2497 if (i < 0)
2498 err(EX_OSERR, "failed to move %s",
2499 cmd == IP_FW_SET_MOVE ? "set": "rule");
2500 } else if (_substrcmp(*av, "disable") == 0 ||
2501 _substrcmp(*av, "enable") == 0 ) {
2502 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2503
2504 av++;
2505 masks[0] = masks[1] = 0;
2506
2507 while (av[0]) {
2508 if (isdigit(**av)) {
2509 i = atoi(*av);
2510 if (i < 0 || i > RESVD_SET)
2511 errx(EX_DATAERR,
2512 "invalid set number %d\n", i);
2513 masks[which] |= (1<<i);
2514 } else if (_substrcmp(*av, "disable") == 0)
2515 which = 0;
2516 else if (_substrcmp(*av, "enable") == 0)
2517 which = 1;
2518 else
2519 errx(EX_DATAERR,
2520 "invalid set command %s\n", *av);
2521 av++;
2522 }
2523 if ( (masks[0] & masks[1]) != 0 )
2524 errx(EX_DATAERR,
2525 "cannot enable and disable the same set\n");
2526
2527 rt.set = masks[0];
2528 rt.new_set = masks[1];
2529 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2530 if (i)
2531 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2532 } else
2533 errx(EX_USAGE, "invalid set command %s\n", *av);
2534 }
2535
2536 void
ipfw_sysctl_handler(char * av[],int which)2537 ipfw_sysctl_handler(char *av[], int which)
2538 {
2539 av++;
2540
2541 if (av[0] == NULL) {
2542 warnx("missing keyword to enable/disable\n");
2543 } else if (_substrcmp(*av, "firewall") == 0) {
2544 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2545 &which, sizeof(which));
2546 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2547 &which, sizeof(which));
2548 } else if (_substrcmp(*av, "one_pass") == 0) {
2549 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2550 &which, sizeof(which));
2551 } else if (_substrcmp(*av, "debug") == 0) {
2552 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2553 &which, sizeof(which));
2554 } else if (_substrcmp(*av, "verbose") == 0) {
2555 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2556 &which, sizeof(which));
2557 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2558 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2559 &which, sizeof(which));
2560 #ifndef NO_ALTQ
2561 } else if (_substrcmp(*av, "altq") == 0) {
2562 altq_set_enabled(which);
2563 #endif
2564 } else {
2565 warnx("unrecognize enable/disable keyword: %s\n", *av);
2566 }
2567 }
2568
2569 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2570 void *arg, void *state);
2571
2572 static void
prepare_format_dyn(struct cmdline_opts * co,struct format_opts * fo,void * arg __unused,void * _state)2573 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2574 void *arg __unused, void *_state)
2575 {
2576 ipfw_dyn_rule *d;
2577 int width;
2578 uint8_t set;
2579
2580 d = (ipfw_dyn_rule *)_state;
2581 /* Count _ALL_ states */
2582 fo->dcnt++;
2583
2584 if (fo->show_counters == 0)
2585 return;
2586
2587 if (co->use_set) {
2588 /* skip states from another set */
2589 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2590 sizeof(uint8_t));
2591 if (set != co->use_set - 1)
2592 return;
2593 }
2594
2595 width = pr_u64(NULL, &d->pcnt, 0);
2596 if (width > fo->pcwidth)
2597 fo->pcwidth = width;
2598
2599 width = pr_u64(NULL, &d->bcnt, 0);
2600 if (width > fo->bcwidth)
2601 fo->bcwidth = width;
2602 }
2603
2604 static int
foreach_state(struct cmdline_opts * co,struct format_opts * fo,caddr_t base,size_t sz,state_cb dyn_bc,void * dyn_arg)2605 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2606 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2607 {
2608 int ttype;
2609 state_cb *fptr;
2610 void *farg;
2611 ipfw_obj_tlv *tlv;
2612 ipfw_obj_ctlv *ctlv;
2613
2614 fptr = NULL;
2615 ttype = 0;
2616
2617 while (sz > 0) {
2618 ctlv = (ipfw_obj_ctlv *)base;
2619 switch (ctlv->head.type) {
2620 case IPFW_TLV_DYNSTATE_LIST:
2621 base += sizeof(*ctlv);
2622 sz -= sizeof(*ctlv);
2623 ttype = IPFW_TLV_DYN_ENT;
2624 fptr = dyn_bc;
2625 farg = dyn_arg;
2626 break;
2627 default:
2628 return (sz);
2629 }
2630
2631 while (sz > 0) {
2632 tlv = (ipfw_obj_tlv *)base;
2633 if (tlv->type != ttype)
2634 break;
2635
2636 fptr(co, fo, farg, tlv + 1);
2637 sz -= tlv->length;
2638 base += tlv->length;
2639 }
2640 }
2641
2642 return (sz);
2643 }
2644
2645 static void
prepare_format_opts(struct cmdline_opts * co,struct format_opts * fo,ipfw_obj_tlv * rtlv,int rcnt,caddr_t dynbase,size_t dynsz)2646 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2647 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2648 {
2649 int bcwidth, pcwidth, width;
2650 int n;
2651 struct ip_fw_bcounter *cntr;
2652 struct ip_fw_rule *r;
2653
2654 bcwidth = 0;
2655 pcwidth = 0;
2656 if (fo->show_counters != 0) {
2657 for (n = 0; n < rcnt; n++,
2658 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2659 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2660 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2661 /* skip rules from another set */
2662 if (co->use_set && r->set != co->use_set - 1)
2663 continue;
2664
2665 /* packet counter */
2666 width = pr_u64(NULL, &cntr->pcnt, 0);
2667 if (width > pcwidth)
2668 pcwidth = width;
2669
2670 /* byte counter */
2671 width = pr_u64(NULL, &cntr->bcnt, 0);
2672 if (width > bcwidth)
2673 bcwidth = width;
2674 }
2675 }
2676 fo->bcwidth = bcwidth;
2677 fo->pcwidth = pcwidth;
2678
2679 fo->dcnt = 0;
2680 if (co->do_dynamic && dynsz > 0)
2681 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2682 }
2683
2684 static int
list_static_range(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,ipfw_obj_tlv * rtlv,int rcnt)2685 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2686 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2687 {
2688 int n, seen;
2689 struct ip_fw_rule *r;
2690 struct ip_fw_bcounter *cntr;
2691
2692 for (n = seen = 0; n < rcnt; n++,
2693 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2694
2695 if ((fo->show_counters | fo->show_time) != 0) {
2696 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2697 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2698 } else {
2699 cntr = NULL;
2700 r = (struct ip_fw_rule *)(rtlv + 1);
2701 }
2702 if (r->rulenum > fo->last)
2703 break;
2704 if (co->use_set && r->set != co->use_set - 1)
2705 continue;
2706 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2707 show_static_rule(co, fo, bp, r, cntr);
2708 printf("%s", bp->buf);
2709 bp_flush(bp);
2710 seen++;
2711 }
2712 }
2713
2714 return (seen);
2715 }
2716
2717 static void
list_dyn_state(struct cmdline_opts * co,struct format_opts * fo,void * _arg,void * _state)2718 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2719 void *_arg, void *_state)
2720 {
2721 uint16_t rulenum;
2722 uint8_t set;
2723 ipfw_dyn_rule *d;
2724 struct buf_pr *bp;
2725
2726 d = (ipfw_dyn_rule *)_state;
2727 bp = (struct buf_pr *)_arg;
2728
2729 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2730 if (rulenum > fo->last)
2731 return;
2732 if (co->use_set) {
2733 bcopy((char *)&d->rule + sizeof(uint16_t),
2734 &set, sizeof(uint8_t));
2735 if (set != co->use_set - 1)
2736 return;
2737 }
2738 if (rulenum >= fo->first) {
2739 show_dyn_state(co, fo, bp, d);
2740 printf("%s\n", bp->buf);
2741 bp_flush(bp);
2742 }
2743 }
2744
2745 static int
list_dyn_range(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,caddr_t base,size_t sz)2746 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2747 struct buf_pr *bp, caddr_t base, size_t sz)
2748 {
2749
2750 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2751 return (sz);
2752 }
2753
2754 void
ipfw_list(int ac,char * av[],int show_counters)2755 ipfw_list(int ac, char *av[], int show_counters)
2756 {
2757 ipfw_cfg_lheader *cfg;
2758 struct format_opts sfo;
2759 size_t sz;
2760 int error;
2761 int lac;
2762 char **lav;
2763 uint32_t rnum;
2764 char *endptr;
2765
2766 if (g_co.test_only) {
2767 fprintf(stderr, "Testing only, list disabled\n");
2768 return;
2769 }
2770 if (g_co.do_pipe) {
2771 dummynet_list(ac, av, show_counters);
2772 return;
2773 }
2774
2775 ac--;
2776 av++;
2777 memset(&sfo, 0, sizeof(sfo));
2778
2779 /* Determine rule range to request */
2780 if (ac > 0) {
2781 for (lac = ac, lav = av; lac != 0; lac--) {
2782 rnum = strtoul(*lav++, &endptr, 10);
2783 if (sfo.first == 0 || rnum < sfo.first)
2784 sfo.first = rnum;
2785
2786 if (*endptr == '-')
2787 rnum = strtoul(endptr + 1, &endptr, 10);
2788 if (sfo.last == 0 || rnum > sfo.last)
2789 sfo.last = rnum;
2790 }
2791 }
2792
2793 /* get configuraion from kernel */
2794 cfg = NULL;
2795 sfo.show_counters = show_counters;
2796 sfo.show_time = g_co.do_time;
2797 if (g_co.do_dynamic != 2)
2798 sfo.flags |= IPFW_CFG_GET_STATIC;
2799 if (g_co.do_dynamic != 0)
2800 sfo.flags |= IPFW_CFG_GET_STATES;
2801 if ((sfo.show_counters | sfo.show_time) != 0)
2802 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2803 if (ipfw_get_config(&g_co, &sfo, &cfg, &sz) != 0)
2804 err(EX_OSERR, "retrieving config failed");
2805
2806 error = ipfw_show_config(&g_co, &sfo, cfg, sz, ac, av);
2807
2808 free(cfg);
2809
2810 if (error != EX_OK)
2811 exit(error);
2812 }
2813
2814 static int
ipfw_show_config(struct cmdline_opts * co,struct format_opts * fo,ipfw_cfg_lheader * cfg,size_t sz,int ac,char * av[])2815 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2816 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2817 {
2818 caddr_t dynbase;
2819 size_t dynsz;
2820 int rcnt;
2821 int exitval = EX_OK;
2822 int lac;
2823 char **lav;
2824 char *endptr;
2825 size_t readsz;
2826 struct buf_pr bp;
2827 ipfw_obj_ctlv *ctlv;
2828 ipfw_obj_tlv *rbase;
2829
2830 /*
2831 * Handle tablenames TLV first, if any
2832 */
2833 rbase = NULL;
2834 dynbase = NULL;
2835 dynsz = 0;
2836 readsz = sizeof(*cfg);
2837 rcnt = 0;
2838
2839 fo->set_mask = cfg->set_mask;
2840
2841 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2842 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2843 object_sort_ctlv(ctlv);
2844 fo->tstate = ctlv;
2845 readsz += ctlv->head.length;
2846 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2847 }
2848
2849 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2850 /* We've requested static rules */
2851 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2852 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2853 rcnt = ctlv->count;
2854 readsz += ctlv->head.length;
2855 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2856 ctlv->head.length);
2857 }
2858 }
2859
2860 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2861 /* We may have some dynamic states */
2862 dynsz = sz - readsz;
2863 /* Skip empty header */
2864 if (dynsz != sizeof(ipfw_obj_ctlv))
2865 dynbase = (caddr_t)ctlv;
2866 else
2867 dynsz = 0;
2868 }
2869
2870 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2871 bp_alloc(&bp, 4096);
2872
2873 /* if no rule numbers were specified, list all rules */
2874 if (ac == 0) {
2875 fo->first = 0;
2876 fo->last = IPFW_DEFAULT_RULE;
2877 if (cfg->flags & IPFW_CFG_GET_STATIC)
2878 list_static_range(co, fo, &bp, rbase, rcnt);
2879
2880 if (co->do_dynamic && dynsz > 0) {
2881 printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2882 dynsz);
2883 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2884 }
2885
2886 bp_free(&bp);
2887 return (EX_OK);
2888 }
2889
2890 /* display specific rules requested on command line */
2891 for (lac = ac, lav = av; lac != 0; lac--) {
2892 /* convert command line rule # */
2893 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2894 if (*endptr == '-')
2895 fo->last = strtoul(endptr + 1, &endptr, 10);
2896 if (*endptr) {
2897 exitval = EX_USAGE;
2898 warnx("invalid rule number: %s", *(lav - 1));
2899 continue;
2900 }
2901
2902 if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
2903 continue;
2904
2905 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2906 /* give precedence to other error(s) */
2907 if (exitval == EX_OK)
2908 exitval = EX_UNAVAILABLE;
2909 if (fo->first == fo->last)
2910 warnx("rule %u does not exist", fo->first);
2911 else
2912 warnx("no rules in range %u-%u",
2913 fo->first, fo->last);
2914 }
2915 }
2916
2917 if (co->do_dynamic && dynsz > 0) {
2918 printf("## Dynamic rules:\n");
2919 for (lac = ac, lav = av; lac != 0; lac--) {
2920 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2921 if (*endptr == '-')
2922 fo->last = strtoul(endptr+1, &endptr, 10);
2923 if (*endptr)
2924 /* already warned */
2925 continue;
2926 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2927 }
2928 }
2929
2930 bp_free(&bp);
2931 return (exitval);
2932 }
2933
2934
2935 /*
2936 * Retrieves current ipfw configuration of given type
2937 * and stores its pointer to @pcfg.
2938 *
2939 * Caller is responsible for freeing @pcfg.
2940 *
2941 * Returns 0 on success.
2942 */
2943
2944 static int
ipfw_get_config(struct cmdline_opts * co,struct format_opts * fo,ipfw_cfg_lheader ** pcfg,size_t * psize)2945 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2946 ipfw_cfg_lheader **pcfg, size_t *psize)
2947 {
2948 ipfw_cfg_lheader *cfg;
2949 size_t sz;
2950 int i;
2951
2952
2953 if (co->test_only != 0) {
2954 fprintf(stderr, "Testing only, list disabled\n");
2955 return (0);
2956 }
2957
2958 /* Start with some data size */
2959 sz = 4096;
2960 cfg = NULL;
2961
2962 for (i = 0; i < 16; i++) {
2963 if (cfg != NULL)
2964 free(cfg);
2965 if ((cfg = calloc(1, sz)) == NULL)
2966 return (ENOMEM);
2967
2968 cfg->flags = fo->flags;
2969 cfg->start_rule = fo->first;
2970 cfg->end_rule = fo->last;
2971
2972 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2973 if (errno != ENOMEM) {
2974 free(cfg);
2975 return (errno);
2976 }
2977
2978 /* Buffer size is not enough. Try to increase */
2979 sz = sz * 2;
2980 if (sz < cfg->size)
2981 sz = cfg->size;
2982 continue;
2983 }
2984
2985 *pcfg = cfg;
2986 *psize = sz;
2987 return (0);
2988 }
2989
2990 free(cfg);
2991 return (ENOMEM);
2992 }
2993
2994 static int
lookup_host(char * host,struct in_addr * ipaddr)2995 lookup_host (char *host, struct in_addr *ipaddr)
2996 {
2997 struct hostent *he;
2998
2999 if (!inet_aton(host, ipaddr)) {
3000 if ((he = gethostbyname(host)) == NULL)
3001 return(-1);
3002 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
3003 }
3004 return(0);
3005 }
3006
3007 struct tidx {
3008 ipfw_obj_ntlv *idx;
3009 uint32_t count;
3010 uint32_t size;
3011 uint16_t counter;
3012 uint8_t set;
3013 };
3014
3015 int
ipfw_check_object_name(const char * name)3016 ipfw_check_object_name(const char *name)
3017 {
3018 int c, i, l;
3019
3020 /*
3021 * Check that name is null-terminated and contains
3022 * valid symbols only. Valid mask is:
3023 * [a-zA-Z0-9\-_\.]{1,63}
3024 */
3025 l = strlen(name);
3026 if (l == 0 || l >= 64)
3027 return (EINVAL);
3028 for (i = 0; i < l; i++) {
3029 c = name[i];
3030 if (isalpha(c) || isdigit(c) || c == '_' ||
3031 c == '-' || c == '.')
3032 continue;
3033 return (EINVAL);
3034 }
3035 return (0);
3036 }
3037
3038 static const char *default_state_name = "default";
3039
3040 static int
state_check_name(const char * name)3041 state_check_name(const char *name)
3042 {
3043
3044 if (ipfw_check_object_name(name) != 0)
3045 return (EINVAL);
3046 if (strcmp(name, "any") == 0)
3047 return (EINVAL);
3048 return (0);
3049 }
3050
3051 static int
eaction_check_name(const char * name)3052 eaction_check_name(const char *name)
3053 {
3054
3055 if (ipfw_check_object_name(name) != 0)
3056 return (EINVAL);
3057 /* Restrict some 'special' names */
3058 if (match_token(rule_actions, name) != -1 &&
3059 match_token(rule_action_params, name) != -1)
3060 return (EINVAL);
3061 return (0);
3062 }
3063
3064 static uint16_t
pack_object(struct tidx * tstate,const char * name,int otype)3065 pack_object(struct tidx *tstate, const char *name, int otype)
3066 {
3067 ipfw_obj_ntlv *ntlv;
3068 uint32_t i;
3069
3070 for (i = 0; i < tstate->count; i++) {
3071 if (strcmp(tstate->idx[i].name, name) != 0)
3072 continue;
3073 if (tstate->idx[i].set != tstate->set)
3074 continue;
3075 if (tstate->idx[i].head.type != otype)
3076 continue;
3077
3078 return (tstate->idx[i].idx);
3079 }
3080
3081 if (tstate->count + 1 > tstate->size) {
3082 tstate->size += 4;
3083 tstate->idx = realloc(tstate->idx, tstate->size *
3084 sizeof(ipfw_obj_ntlv));
3085 if (tstate->idx == NULL)
3086 return (0);
3087 }
3088
3089 ntlv = &tstate->idx[i];
3090 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3091 strlcpy(ntlv->name, name, sizeof(ntlv->name));
3092 ntlv->head.type = otype;
3093 ntlv->head.length = sizeof(ipfw_obj_ntlv);
3094 ntlv->set = tstate->set;
3095 ntlv->idx = ++tstate->counter;
3096 tstate->count++;
3097
3098 return (ntlv->idx);
3099 }
3100
3101 static uint16_t
pack_table(struct tidx * tstate,const char * name)3102 pack_table(struct tidx *tstate, const char *name)
3103 {
3104
3105 if (table_check_name(name) != 0)
3106 return (0);
3107
3108 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3109 }
3110
3111 void
fill_table(struct _ipfw_insn * cmd,char * av,uint8_t opcode,struct tidx * tstate)3112 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3113 struct tidx *tstate)
3114 {
3115 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3116 uint16_t uidx;
3117 char *p;
3118
3119 if ((p = strchr(av + 6, ')')) == NULL)
3120 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3121 *p = '\0';
3122 p = strchr(av + 6, ',');
3123 if (p)
3124 *p++ = '\0';
3125
3126 if ((uidx = pack_table(tstate, av + 6)) == 0)
3127 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3128
3129 cmd->opcode = opcode;
3130 cmd->arg1 = uidx;
3131 if (p) {
3132 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3133 d[0] = strtoul(p, NULL, 0);
3134 } else
3135 cmd->len |= F_INSN_SIZE(ipfw_insn);
3136 }
3137
3138
3139 /*
3140 * fills the addr and mask fields in the instruction as appropriate from av.
3141 * Update length as appropriate.
3142 * The following formats are allowed:
3143 * me returns O_IP_*_ME
3144 * 1.2.3.4 single IP address
3145 * 1.2.3.4:5.6.7.8 address:mask
3146 * 1.2.3.4/24 address/mask
3147 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3148 * We can have multiple comma-separated address/mask entries.
3149 */
3150 static void
fill_ip(ipfw_insn_ip * cmd,char * av,int cblen,struct tidx * tstate)3151 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3152 {
3153 int len = 0;
3154 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3155
3156 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3157
3158 if (_substrcmp(av, "any") == 0)
3159 return;
3160
3161 if (_substrcmp(av, "me") == 0) {
3162 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3163 return;
3164 }
3165
3166 if (strncmp(av, "table(", 6) == 0) {
3167 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3168 return;
3169 }
3170
3171 while (av) {
3172 /*
3173 * After the address we can have '/' or ':' indicating a mask,
3174 * ',' indicating another address follows, '{' indicating a
3175 * set of addresses of unspecified size.
3176 */
3177 char *t = NULL, *p = strpbrk(av, "/:,{");
3178 int masklen;
3179 char md, nd = '\0';
3180
3181 CHECK_LENGTH(cblen, (int)F_INSN_SIZE(ipfw_insn) + 2 + len);
3182
3183 if (p) {
3184 md = *p;
3185 *p++ = '\0';
3186 if ((t = strpbrk(p, ",{")) != NULL) {
3187 nd = *t;
3188 *t = '\0';
3189 }
3190 } else
3191 md = '\0';
3192
3193 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3194 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3195 switch (md) {
3196 case ':':
3197 if (!inet_aton(p, (struct in_addr *)&d[1]))
3198 errx(EX_DATAERR, "bad netmask ``%s''", p);
3199 break;
3200 case '/':
3201 masklen = atoi(p);
3202 if (masklen == 0)
3203 d[1] = htonl(0U); /* mask */
3204 else if (masklen > 32)
3205 errx(EX_DATAERR, "bad width ``%s''", p);
3206 else
3207 d[1] = htonl(~0U << (32 - masklen));
3208 break;
3209 case '{': /* no mask, assume /24 and put back the '{' */
3210 d[1] = htonl(~0U << (32 - 24));
3211 *(--p) = md;
3212 break;
3213
3214 case ',': /* single address plus continuation */
3215 *(--p) = md;
3216 /* FALLTHROUGH */
3217 case 0: /* initialization value */
3218 default:
3219 d[1] = htonl(~0U); /* force /32 */
3220 break;
3221 }
3222 d[0] &= d[1]; /* mask base address with mask */
3223 if (t)
3224 *t = nd;
3225 /* find next separator */
3226 if (p)
3227 p = strpbrk(p, ",{");
3228 if (p && *p == '{') {
3229 /*
3230 * We have a set of addresses. They are stored as follows:
3231 * arg1 is the set size (powers of 2, 2..256)
3232 * addr is the base address IN HOST FORMAT
3233 * mask.. is an array of arg1 bits (rounded up to
3234 * the next multiple of 32) with bits set
3235 * for each host in the map.
3236 */
3237 uint32_t *map = (uint32_t *)&cmd->mask;
3238 int low, high;
3239 int i = contigmask((uint8_t *)&(d[1]), 32);
3240
3241 if (len > 0)
3242 errx(EX_DATAERR, "address set cannot be in a list");
3243 if (i < 24 || i > 31)
3244 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3245 cmd->o.arg1 = 1<<(32-i); /* map length */
3246 d[0] = ntohl(d[0]); /* base addr in host format */
3247 cmd->o.opcode = O_IP_DST_SET; /* default */
3248 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3249 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3250 map[i] = 0; /* clear map */
3251
3252 av = p + 1;
3253 low = d[0] & 0xff;
3254 high = low + cmd->o.arg1 - 1;
3255 /*
3256 * Here, i stores the previous value when we specify a range
3257 * of addresses within a mask, e.g. 45-63. i = -1 means we
3258 * have no previous value.
3259 */
3260 i = -1; /* previous value in a range */
3261 while (isdigit(*av)) {
3262 char *s;
3263 int a = strtol(av, &s, 0);
3264
3265 if (s == av) { /* no parameter */
3266 if (*av != '}')
3267 errx(EX_DATAERR, "set not closed\n");
3268 if (i != -1)
3269 errx(EX_DATAERR, "incomplete range %d-", i);
3270 break;
3271 }
3272 if (a < low || a > high)
3273 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3274 a, low, high);
3275 a -= low;
3276 if (i == -1) /* no previous in range */
3277 i = a;
3278 else { /* check that range is valid */
3279 if (i > a)
3280 errx(EX_DATAERR, "invalid range %d-%d",
3281 i+low, a+low);
3282 if (*s == '-')
3283 errx(EX_DATAERR, "double '-' in range");
3284 }
3285 for (; i <= a; i++)
3286 map[i/32] |= 1<<(i & 31);
3287 i = -1;
3288 if (*s == '-')
3289 i = a;
3290 else if (*s == '}')
3291 break;
3292 av = s+1;
3293 }
3294 return;
3295 }
3296 av = p;
3297 if (av) /* then *av must be a ',' */
3298 av++;
3299
3300 /* Check this entry */
3301 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3302 /*
3303 * 'any' turns the entire list into a NOP.
3304 * 'not any' never matches, so it is removed from the
3305 * list unless it is the only item, in which case we
3306 * report an error.
3307 */
3308 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3309 if (av == NULL && len == 0) /* only this entry */
3310 errx(EX_DATAERR, "not any never matches");
3311 }
3312 /* else do nothing and skip this entry */
3313 return;
3314 }
3315 /* A single IP can be stored in an optimized format */
3316 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3317 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3318 return;
3319 }
3320 len += 2; /* two words... */
3321 d += 2;
3322 } /* end while */
3323 if (len + 1 > F_LEN_MASK)
3324 errx(EX_DATAERR, "address list too long");
3325 cmd->o.len |= len+1;
3326 }
3327
3328
3329 /* n2mask sets n bits of the mask */
3330 void
n2mask(struct in6_addr * mask,int n)3331 n2mask(struct in6_addr *mask, int n)
3332 {
3333 static int minimask[9] =
3334 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3335 u_char *p;
3336
3337 memset(mask, 0, sizeof(struct in6_addr));
3338 p = (u_char *) mask;
3339 for (; n > 0; p++, n -= 8) {
3340 if (n >= 8)
3341 *p = 0xff;
3342 else
3343 *p = minimask[n];
3344 }
3345 return;
3346 }
3347
3348 static void
fill_flags_cmd(ipfw_insn * cmd,enum ipfw_opcodes opcode,struct _s_x * flags,char * p)3349 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3350 struct _s_x *flags, char *p)
3351 {
3352 char *e;
3353 uint32_t set = 0, clear = 0;
3354
3355 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3356 errx(EX_DATAERR, "invalid flag %s", e);
3357
3358 cmd->opcode = opcode;
3359 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3360 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3361 }
3362
3363
3364 void
ipfw_delete(char * av[])3365 ipfw_delete(char *av[])
3366 {
3367 ipfw_range_tlv rt;
3368 char *sep;
3369 int i, j;
3370 int exitval = EX_OK;
3371 int do_set = 0;
3372
3373 av++;
3374 NEED1("missing rule specification");
3375 if ( *av && _substrcmp(*av, "set") == 0) {
3376 /* Do not allow using the following syntax:
3377 * ipfw set N delete set M
3378 */
3379 if (g_co.use_set)
3380 errx(EX_DATAERR, "invalid syntax");
3381 do_set = 1; /* delete set */
3382 av++;
3383 }
3384
3385 /* Rule number */
3386 while (*av && isdigit(**av)) {
3387 i = strtol(*av, &sep, 10);
3388 j = i;
3389 if (*sep== '-')
3390 j = strtol(sep + 1, NULL, 10);
3391 av++;
3392 if (g_co.do_nat) {
3393 exitval = ipfw_delete_nat(i);
3394 } else if (g_co.do_pipe) {
3395 exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3396 } else {
3397 memset(&rt, 0, sizeof(rt));
3398 if (do_set != 0) {
3399 rt.set = i & 31;
3400 rt.flags = IPFW_RCFLAG_SET;
3401 } else {
3402 rt.start_rule = i & 0xffff;
3403 rt.end_rule = j & 0xffff;
3404 if (rt.start_rule == 0 && rt.end_rule == 0)
3405 rt.flags |= IPFW_RCFLAG_ALL;
3406 else
3407 rt.flags |= IPFW_RCFLAG_RANGE;
3408 if (g_co.use_set != 0) {
3409 rt.set = g_co.use_set - 1;
3410 rt.flags |= IPFW_RCFLAG_SET;
3411 }
3412 }
3413 if (g_co.do_dynamic == 2)
3414 rt.flags |= IPFW_RCFLAG_DYNAMIC;
3415 i = do_range_cmd(IP_FW_XDEL, &rt);
3416 if (i != 0) {
3417 exitval = EX_UNAVAILABLE;
3418 if (g_co.do_quiet)
3419 continue;
3420 warn("rule %u: setsockopt(IP_FW_XDEL)",
3421 rt.start_rule);
3422 } else if (rt.new_set == 0 && do_set == 0 &&
3423 g_co.do_dynamic != 2) {
3424 exitval = EX_UNAVAILABLE;
3425 if (g_co.do_quiet)
3426 continue;
3427 if (rt.start_rule != rt.end_rule)
3428 warnx("no rules rules in %u-%u range",
3429 rt.start_rule, rt.end_rule);
3430 else
3431 warnx("rule %u not found",
3432 rt.start_rule);
3433 }
3434 }
3435 }
3436 if (exitval != EX_OK && g_co.do_force == 0)
3437 exit(exitval);
3438 }
3439
3440
3441 /*
3442 * fill the interface structure. We do not check the name as we can
3443 * create interfaces dynamically, so checking them at insert time
3444 * makes relatively little sense.
3445 * Interface names containing '*', '?', or '[' are assumed to be shell
3446 * patterns which match interfaces.
3447 */
3448 static void
fill_iface(ipfw_insn_if * cmd,char * arg,int cblen,struct tidx * tstate)3449 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3450 {
3451 char *p;
3452 uint16_t uidx;
3453
3454 cmd->name[0] = '\0';
3455 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3456
3457 CHECK_CMDLEN;
3458
3459 /* Parse the interface or address */
3460 if (strcmp(arg, "any") == 0)
3461 cmd->o.len = 0; /* effectively ignore this command */
3462 else if (strncmp(arg, "table(", 6) == 0) {
3463 if ((p = strchr(arg + 6, ')')) == NULL)
3464 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3465 *p = '\0';
3466 p = strchr(arg + 6, ',');
3467 if (p)
3468 *p++ = '\0';
3469 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3470 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3471
3472 cmd->name[0] = '\1'; /* Special value indicating table */
3473 cmd->p.kidx = uidx;
3474 } else if (!isdigit(*arg)) {
3475 strlcpy(cmd->name, arg, sizeof(cmd->name));
3476 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3477 } else if (!inet_aton(arg, &cmd->p.ip))
3478 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3479 }
3480
3481 static void
get_mac_addr_mask(const char * p,uint8_t * addr,uint8_t * mask)3482 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3483 {
3484 int i;
3485 size_t l;
3486 char *ap, *ptr, *optr;
3487 struct ether_addr *mac;
3488 const char *macset = "0123456789abcdefABCDEF:";
3489
3490 if (strcmp(p, "any") == 0) {
3491 for (i = 0; i < ETHER_ADDR_LEN; i++)
3492 addr[i] = mask[i] = 0;
3493 return;
3494 }
3495
3496 optr = ptr = strdup(p);
3497 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3498 l = strlen(ap);
3499 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3500 errx(EX_DATAERR, "Incorrect MAC address");
3501 bcopy(mac, addr, ETHER_ADDR_LEN);
3502 } else
3503 errx(EX_DATAERR, "Incorrect MAC address");
3504
3505 if (ptr != NULL) { /* we have mask? */
3506 if (p[ptr - optr - 1] == '/') { /* mask len */
3507 long ml = strtol(ptr, &ap, 10);
3508 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3509 errx(EX_DATAERR, "Incorrect mask length");
3510 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3511 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3512 } else { /* mask */
3513 l = strlen(ptr);
3514 if (strspn(ptr, macset) != l ||
3515 (mac = ether_aton(ptr)) == NULL)
3516 errx(EX_DATAERR, "Incorrect mask");
3517 bcopy(mac, mask, ETHER_ADDR_LEN);
3518 }
3519 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3520 for (i = 0; i < ETHER_ADDR_LEN; i++)
3521 mask[i] = 0xff;
3522 }
3523 for (i = 0; i < ETHER_ADDR_LEN; i++)
3524 addr[i] &= mask[i];
3525
3526 free(optr);
3527 }
3528
3529 /*
3530 * helper function, updates the pointer to cmd with the length
3531 * of the current command, and also cleans up the first word of
3532 * the new command in case it has been clobbered before.
3533 */
3534 static ipfw_insn *
next_cmd(ipfw_insn * cmd,int * len)3535 next_cmd(ipfw_insn *cmd, int *len)
3536 {
3537 *len -= F_LEN(cmd);
3538 CHECK_LENGTH(*len, 0);
3539 cmd += F_LEN(cmd);
3540 bzero(cmd, sizeof(*cmd));
3541 return cmd;
3542 }
3543
3544 /*
3545 * Takes arguments and copies them into a comment
3546 */
3547 static void
fill_comment(ipfw_insn * cmd,char ** av,int cblen)3548 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3549 {
3550 int i, l;
3551 char *p = (char *)(cmd + 1);
3552
3553 cmd->opcode = O_NOP;
3554 cmd->len = (cmd->len & (F_NOT | F_OR));
3555
3556 /* Compute length of comment string. */
3557 for (i = 0, l = 0; av[i] != NULL; i++)
3558 l += strlen(av[i]) + 1;
3559 if (l == 0)
3560 return;
3561 if (l > 84)
3562 errx(EX_DATAERR,
3563 "comment too long (max 80 chars)");
3564 l = 1 + (l+3)/4;
3565 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3566 CHECK_CMDLEN;
3567
3568 for (i = 0; av[i] != NULL; i++) {
3569 strcpy(p, av[i]);
3570 p += strlen(av[i]);
3571 *p++ = ' ';
3572 }
3573 *(--p) = '\0';
3574 }
3575
3576 /*
3577 * A function to fill simple commands of size 1.
3578 * Existing flags are preserved.
3579 */
3580 static void
fill_cmd(ipfw_insn * cmd,enum ipfw_opcodes opcode,int flags,uint16_t arg)3581 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3582 {
3583 cmd->opcode = opcode;
3584 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3585 cmd->arg1 = arg;
3586 }
3587
3588 /*
3589 * Fetch and add the MAC address and type, with masks. This generates one or
3590 * two microinstructions, and returns the pointer to the last one.
3591 */
3592 static ipfw_insn *
add_mac(ipfw_insn * cmd,char * av[],int cblen)3593 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3594 {
3595 ipfw_insn_mac *mac;
3596
3597 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3598 errx(EX_DATAERR, "MAC dst src");
3599
3600 cmd->opcode = O_MACADDR2;
3601 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3602 CHECK_CMDLEN;
3603
3604 mac = (ipfw_insn_mac *)cmd;
3605 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3606 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3607 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3608 return cmd;
3609 }
3610
3611 static ipfw_insn *
add_mactype(ipfw_insn * cmd,char * av,int cblen)3612 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3613 {
3614 if (!av)
3615 errx(EX_DATAERR, "missing MAC type");
3616 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3617 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3618 cblen);
3619 cmd->opcode = O_MAC_TYPE;
3620 return cmd;
3621 } else
3622 return NULL;
3623 }
3624
3625 static ipfw_insn *
add_proto0(ipfw_insn * cmd,char * av,u_char * protop)3626 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3627 {
3628 struct protoent *pe;
3629 char *ep;
3630 int proto;
3631
3632 proto = strtol(av, &ep, 10);
3633 if (*ep != '\0' || proto <= 0) {
3634 if ((pe = getprotobyname(av)) == NULL)
3635 return NULL;
3636 proto = pe->p_proto;
3637 }
3638
3639 fill_cmd(cmd, O_PROTO, 0, proto);
3640 *protop = proto;
3641 return cmd;
3642 }
3643
3644 static ipfw_insn *
add_proto(ipfw_insn * cmd,char * av,u_char * protop)3645 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3646 {
3647 u_char proto = IPPROTO_IP;
3648
3649 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3650 ; /* do not set O_IP4 nor O_IP6 */
3651 else if (strcmp(av, "ip4") == 0)
3652 /* explicit "just IPv4" rule */
3653 fill_cmd(cmd, O_IP4, 0, 0);
3654 else if (strcmp(av, "ip6") == 0) {
3655 /* explicit "just IPv6" rule */
3656 proto = IPPROTO_IPV6;
3657 fill_cmd(cmd, O_IP6, 0, 0);
3658 } else
3659 return add_proto0(cmd, av, protop);
3660
3661 *protop = proto;
3662 return cmd;
3663 }
3664
3665 static ipfw_insn *
add_proto_compat(ipfw_insn * cmd,char * av,u_char * protop)3666 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3667 {
3668 u_char proto = IPPROTO_IP;
3669
3670 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3671 ; /* do not set O_IP4 nor O_IP6 */
3672 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3673 /* explicit "just IPv4" rule */
3674 fill_cmd(cmd, O_IP4, 0, 0);
3675 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3676 /* explicit "just IPv6" rule */
3677 proto = IPPROTO_IPV6;
3678 fill_cmd(cmd, O_IP6, 0, 0);
3679 } else
3680 return add_proto0(cmd, av, protop);
3681
3682 *protop = proto;
3683 return cmd;
3684 }
3685
3686 static ipfw_insn *
add_srcip(ipfw_insn * cmd,char * av,int cblen,struct tidx * tstate)3687 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3688 {
3689 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3690 if (cmd->opcode == O_IP_DST_SET) /* set */
3691 cmd->opcode = O_IP_SRC_SET;
3692 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3693 cmd->opcode = O_IP_SRC_LOOKUP;
3694 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3695 cmd->opcode = O_IP_SRC_ME;
3696 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3697 cmd->opcode = O_IP_SRC;
3698 else /* addr/mask */
3699 cmd->opcode = O_IP_SRC_MASK;
3700 return cmd;
3701 }
3702
3703 static ipfw_insn *
add_dstip(ipfw_insn * cmd,char * av,int cblen,struct tidx * tstate)3704 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3705 {
3706 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3707 if (cmd->opcode == O_IP_DST_SET) /* set */
3708 ;
3709 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3710 ;
3711 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3712 cmd->opcode = O_IP_DST_ME;
3713 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3714 cmd->opcode = O_IP_DST;
3715 else /* addr/mask */
3716 cmd->opcode = O_IP_DST_MASK;
3717 return cmd;
3718 }
3719
3720 static ipfw_insn *
add_srcmac(ipfw_insn * cmd,char * av,struct tidx * tstate)3721 add_srcmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3722 {
3723
3724 if (strncmp(av, "table(", 6) == 0)
3725 fill_table(cmd, av, O_MAC_SRC_LOOKUP, tstate);
3726 else
3727 errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3728 return cmd;
3729 }
3730
3731 static ipfw_insn *
add_dstmac(ipfw_insn * cmd,char * av,struct tidx * tstate)3732 add_dstmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3733 {
3734
3735 if (strncmp(av, "table(", 6) == 0)
3736 fill_table(cmd, av, O_MAC_DST_LOOKUP, tstate);
3737 else
3738 errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3739 return cmd;
3740 }
3741
3742
3743 static struct _s_x f_reserved_keywords[] = {
3744 { "altq", TOK_OR },
3745 { "//", TOK_OR },
3746 { "diverted", TOK_OR },
3747 { "dst-port", TOK_OR },
3748 { "src-port", TOK_OR },
3749 { "established", TOK_OR },
3750 { "keep-state", TOK_OR },
3751 { "frag", TOK_OR },
3752 { "icmptypes", TOK_OR },
3753 { "in", TOK_OR },
3754 { "out", TOK_OR },
3755 { "ip6", TOK_OR },
3756 { "any", TOK_OR },
3757 { "to", TOK_OR },
3758 { "via", TOK_OR },
3759 { "{", TOK_OR },
3760 { NULL, 0 } /* terminator */
3761 };
3762
3763 static ipfw_insn *
add_ports(ipfw_insn * cmd,char * av,u_char proto,int opcode,int cblen)3764 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3765 {
3766
3767 if (match_token(f_reserved_keywords, av) != -1)
3768 return (NULL);
3769
3770 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3771 /* XXX todo: check that we have a protocol with ports */
3772 cmd->opcode = opcode;
3773 return cmd;
3774 }
3775 return NULL;
3776 }
3777
3778 static ipfw_insn *
add_src(ipfw_insn * cmd,char * av,u_char proto,int cblen,struct tidx * tstate)3779 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3780 {
3781 struct in6_addr a;
3782 char *host, *ch, buf[INET6_ADDRSTRLEN];
3783 ipfw_insn *ret = NULL;
3784 size_t len;
3785
3786 /* Copy first address in set if needed */
3787 if ((ch = strpbrk(av, "/,")) != NULL) {
3788 len = ch - av;
3789 strlcpy(buf, av, sizeof(buf));
3790 if (len < sizeof(buf))
3791 buf[len] = '\0';
3792 host = buf;
3793 } else
3794 host = av;
3795
3796 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3797 inet_pton(AF_INET6, host, &a) == 1)
3798 ret = add_srcip6(cmd, av, cblen, tstate);
3799 /* XXX: should check for IPv4, not !IPv6 */
3800 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3801 inet_pton(AF_INET6, host, &a) != 1))
3802 ret = add_srcip(cmd, av, cblen, tstate);
3803 if (ret == NULL && strcmp(av, "any") != 0)
3804 ret = cmd;
3805
3806 return ret;
3807 }
3808
3809 static ipfw_insn *
add_dst(ipfw_insn * cmd,char * av,u_char proto,int cblen,struct tidx * tstate)3810 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3811 {
3812 struct in6_addr a;
3813 char *host, *ch, buf[INET6_ADDRSTRLEN];
3814 ipfw_insn *ret = NULL;
3815 size_t len;
3816
3817 /* Copy first address in set if needed */
3818 if ((ch = strpbrk(av, "/,")) != NULL) {
3819 len = ch - av;
3820 strlcpy(buf, av, sizeof(buf));
3821 if (len < sizeof(buf))
3822 buf[len] = '\0';
3823 host = buf;
3824 } else
3825 host = av;
3826
3827 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3828 inet_pton(AF_INET6, host, &a) == 1)
3829 ret = add_dstip6(cmd, av, cblen, tstate);
3830 /* XXX: should check for IPv4, not !IPv6 */
3831 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3832 inet_pton(AF_INET6, host, &a) != 1))
3833 ret = add_dstip(cmd, av, cblen, tstate);
3834 if (ret == NULL && strcmp(av, "any") != 0)
3835 ret = cmd;
3836
3837 return ret;
3838 }
3839
3840 /*
3841 * Parse arguments and assemble the microinstructions which make up a rule.
3842 * Rules are added into the 'rulebuf' and then copied in the correct order
3843 * into the actual rule.
3844 *
3845 * The syntax for a rule starts with the action, followed by
3846 * optional action parameters, and the various match patterns.
3847 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3848 * (generated if the rule includes a keep-state option), then the
3849 * various match patterns, log/altq actions, and the actual action.
3850 *
3851 */
3852 static void
compile_rule(char * av[],uint32_t * rbuf,int * rbufsize,struct tidx * tstate)3853 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3854 {
3855 /*
3856 * rules are added into the 'rulebuf' and then copied in
3857 * the correct order into the actual rule.
3858 * Some things that need to go out of order (prob, action etc.)
3859 * go into actbuf[].
3860 */
3861 static uint32_t actbuf[255], cmdbuf[255];
3862 int rblen, ablen, cblen;
3863
3864 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3865 ipfw_insn *first_cmd; /* first match pattern */
3866
3867 struct ip_fw_rule *rule;
3868
3869 /*
3870 * various flags used to record that we entered some fields.
3871 */
3872 ipfw_insn *have_state = NULL; /* any state-related option */
3873 int have_rstate = 0;
3874 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3875 ipfw_insn *have_skipcmd = NULL;
3876 size_t len;
3877
3878 int i;
3879
3880 int open_par = 0; /* open parenthesis ( */
3881
3882 /* proto is here because it is used to fetch ports */
3883 u_char proto = IPPROTO_IP; /* default protocol */
3884
3885 double match_prob = 1; /* match probability, default is always match */
3886
3887 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3888 bzero(cmdbuf, sizeof(cmdbuf));
3889 bzero(rbuf, *rbufsize);
3890
3891 rule = (struct ip_fw_rule *)rbuf;
3892 cmd = (ipfw_insn *)cmdbuf;
3893 action = (ipfw_insn *)actbuf;
3894
3895 rblen = *rbufsize / sizeof(uint32_t);
3896 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3897 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3898 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3899 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3900
3901 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3902 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3903
3904 av++;
3905
3906 /* [rule N] -- Rule number optional */
3907 if (av[0] && isdigit(**av)) {
3908 rule->rulenum = atoi(*av);
3909 av++;
3910 }
3911
3912 /* [set N] -- set number (0..RESVD_SET), optional */
3913 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3914 int set = strtoul(av[1], NULL, 10);
3915 if (set < 0 || set > RESVD_SET)
3916 errx(EX_DATAERR, "illegal set %s", av[1]);
3917 rule->set = set;
3918 tstate->set = set;
3919 av += 2;
3920 }
3921
3922 /* [prob D] -- match probability, optional */
3923 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3924 match_prob = strtod(av[1], NULL);
3925
3926 if (match_prob <= 0 || match_prob > 1)
3927 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3928 av += 2;
3929 }
3930
3931 /* action -- mandatory */
3932 NEED1("missing action");
3933 i = match_token(rule_actions, *av);
3934 av++;
3935 action->len = 1; /* default */
3936 CHECK_ACTLEN;
3937 switch(i) {
3938 case TOK_CHECKSTATE:
3939 have_state = action;
3940 action->opcode = O_CHECK_STATE;
3941 if (*av == NULL ||
3942 match_token(rule_options, *av) == TOK_COMMENT) {
3943 action->arg1 = pack_object(tstate,
3944 default_state_name, IPFW_TLV_STATE_NAME);
3945 break;
3946 }
3947 if (*av[0] == ':') {
3948 if (strcmp(*av + 1, "any") == 0)
3949 action->arg1 = 0;
3950 else if (state_check_name(*av + 1) == 0)
3951 action->arg1 = pack_object(tstate, *av + 1,
3952 IPFW_TLV_STATE_NAME);
3953 else
3954 errx(EX_DATAERR, "Invalid state name %s",
3955 *av);
3956 av++;
3957 break;
3958 }
3959 errx(EX_DATAERR, "Invalid state name %s", *av);
3960 break;
3961
3962 case TOK_ABORT:
3963 action->opcode = O_REJECT;
3964 action->arg1 = ICMP_REJECT_ABORT;
3965 break;
3966
3967 case TOK_ABORT6:
3968 action->opcode = O_UNREACH6;
3969 action->arg1 = ICMP6_UNREACH_ABORT;
3970 break;
3971
3972 case TOK_ACCEPT:
3973 action->opcode = O_ACCEPT;
3974 break;
3975
3976 case TOK_DENY:
3977 action->opcode = O_DENY;
3978 action->arg1 = 0;
3979 break;
3980
3981 case TOK_REJECT:
3982 action->opcode = O_REJECT;
3983 action->arg1 = ICMP_UNREACH_HOST;
3984 break;
3985
3986 case TOK_RESET:
3987 action->opcode = O_REJECT;
3988 action->arg1 = ICMP_REJECT_RST;
3989 break;
3990
3991 case TOK_RESET6:
3992 action->opcode = O_UNREACH6;
3993 action->arg1 = ICMP6_UNREACH_RST;
3994 break;
3995
3996 case TOK_UNREACH:
3997 action->opcode = O_REJECT;
3998 NEED1("missing reject code");
3999 fill_reject_code(&action->arg1, *av);
4000 av++;
4001 break;
4002
4003 case TOK_UNREACH6:
4004 action->opcode = O_UNREACH6;
4005 NEED1("missing unreach code");
4006 fill_unreach6_code(&action->arg1, *av);
4007 av++;
4008 break;
4009
4010 case TOK_COUNT:
4011 action->opcode = O_COUNT;
4012 break;
4013
4014 case TOK_NAT:
4015 action->opcode = O_NAT;
4016 action->len = F_INSN_SIZE(ipfw_insn_nat);
4017 CHECK_ACTLEN;
4018 if (*av != NULL && _substrcmp(*av, "global") == 0) {
4019 action->arg1 = IP_FW_NAT44_GLOBAL;
4020 av++;
4021 break;
4022 } else
4023 goto chkarg;
4024 case TOK_QUEUE:
4025 action->opcode = O_QUEUE;
4026 goto chkarg;
4027 case TOK_PIPE:
4028 action->opcode = O_PIPE;
4029 goto chkarg;
4030 case TOK_SKIPTO:
4031 action->opcode = O_SKIPTO;
4032 goto chkarg;
4033 case TOK_NETGRAPH:
4034 action->opcode = O_NETGRAPH;
4035 goto chkarg;
4036 case TOK_NGTEE:
4037 action->opcode = O_NGTEE;
4038 goto chkarg;
4039 case TOK_DIVERT:
4040 action->opcode = O_DIVERT;
4041 goto chkarg;
4042 case TOK_TEE:
4043 action->opcode = O_TEE;
4044 goto chkarg;
4045 case TOK_CALL:
4046 action->opcode = O_CALLRETURN;
4047 chkarg:
4048 if (!av[0])
4049 errx(EX_USAGE, "missing argument for %s", *(av - 1));
4050 if (isdigit(**av)) {
4051 action->arg1 = strtoul(*av, NULL, 10);
4052 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
4053 errx(EX_DATAERR, "illegal argument for %s",
4054 *(av - 1));
4055 } else if (_substrcmp(*av, "tablearg") == 0) {
4056 action->arg1 = IP_FW_TARG;
4057 } else if (i == TOK_DIVERT || i == TOK_TEE) {
4058 struct servent *s;
4059 setservent(1);
4060 s = getservbyname(av[0], "divert");
4061 if (s != NULL)
4062 action->arg1 = ntohs(s->s_port);
4063 else
4064 errx(EX_DATAERR, "illegal divert/tee port");
4065 } else
4066 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
4067 av++;
4068 break;
4069
4070 case TOK_FORWARD: {
4071 /*
4072 * Locate the address-port separator (':' or ',').
4073 * Could be one of the following:
4074 * hostname:port
4075 * IPv4 a.b.c.d,port
4076 * IPv4 a.b.c.d:port
4077 * IPv6 w:x:y::z,port
4078 * IPv6 [w:x:y::z]:port
4079 */
4080 struct sockaddr_storage result;
4081 struct addrinfo *res;
4082 char *s, *end;
4083 int family;
4084 u_short port_number = 0;
4085
4086 NEED1("missing forward address[:port]");
4087
4088 if (strncmp(*av, "tablearg", 8) == 0 &&
4089 ((*av)[8] == '\0' || (*av)[8] == ',' || (*av)[8] == ':'))
4090 memcpy(++(*av), "0.0.0.0", 7);
4091
4092 /*
4093 * Are we an bracket-enclosed IPv6 address?
4094 */
4095 if (strchr(*av, '['))
4096 (*av)++;
4097
4098 /*
4099 * locate the address-port separator (':' or ',')
4100 */
4101 s = strchr(*av, ',');
4102 if (s == NULL) {
4103 s = strchr(*av, ']');
4104 /* Prevent erroneous parsing on brackets. */
4105 if (s != NULL)
4106 *(s++) = '\0';
4107 else
4108 s = *av;
4109
4110 /* Distinguish between IPv4:port and IPv6 cases. */
4111 s = strchr(s, ':');
4112 if (s && strchr(s+1, ':'))
4113 s = NULL; /* no port */
4114 }
4115
4116 if (s != NULL) {
4117 /* Terminate host portion and set s to start of port. */
4118 *(s++) = '\0';
4119 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4120 if (s == end)
4121 errx(EX_DATAERR,
4122 "illegal forwarding port ``%s''", s);
4123 port_number = (u_short)i;
4124 }
4125
4126 /*
4127 * Resolve the host name or address to a family and a
4128 * network representation of the address.
4129 */
4130 if (getaddrinfo(*av, NULL, NULL, &res))
4131 errx(EX_DATAERR, NULL);
4132 /* Just use the first host in the answer. */
4133 family = res->ai_family;
4134 memcpy(&result, res->ai_addr, res->ai_addrlen);
4135 freeaddrinfo(res);
4136
4137 if (family == PF_INET) {
4138 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4139
4140 action->opcode = O_FORWARD_IP;
4141 action->len = F_INSN_SIZE(ipfw_insn_sa);
4142 CHECK_ACTLEN;
4143
4144 /*
4145 * In the kernel we assume AF_INET and use only
4146 * sin_port and sin_addr. Remember to set sin_len as
4147 * the routing code seems to use it too.
4148 */
4149 p->sa.sin_len = sizeof(struct sockaddr_in);
4150 p->sa.sin_family = AF_INET;
4151 p->sa.sin_port = port_number;
4152 p->sa.sin_addr.s_addr =
4153 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4154 } else if (family == PF_INET6) {
4155 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4156
4157 action->opcode = O_FORWARD_IP6;
4158 action->len = F_INSN_SIZE(ipfw_insn_sa6);
4159 CHECK_ACTLEN;
4160
4161 p->sa.sin6_len = sizeof(struct sockaddr_in6);
4162 p->sa.sin6_family = AF_INET6;
4163 p->sa.sin6_port = port_number;
4164 p->sa.sin6_flowinfo = 0;
4165 p->sa.sin6_scope_id =
4166 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4167 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4168 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4169 } else {
4170 errx(EX_DATAERR, "Invalid address family in forward action");
4171 }
4172 av++;
4173 break;
4174 }
4175 case TOK_COMMENT:
4176 /* pretend it is a 'count' rule followed by the comment */
4177 action->opcode = O_COUNT;
4178 av--; /* go back... */
4179 break;
4180
4181 case TOK_SETFIB:
4182 {
4183 int numfibs;
4184 size_t intsize = sizeof(int);
4185
4186 action->opcode = O_SETFIB;
4187 NEED1("missing fib number");
4188 if (_substrcmp(*av, "tablearg") == 0) {
4189 action->arg1 = IP_FW_TARG;
4190 } else {
4191 action->arg1 = strtoul(*av, NULL, 10);
4192 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4193 NULL, 0) == -1)
4194 errx(EX_DATAERR, "fibs not supported.\n");
4195 if (action->arg1 >= numfibs) /* Temporary */
4196 errx(EX_DATAERR, "fib too large.\n");
4197 /* Add high-order bit to fib to make room for tablearg*/
4198 action->arg1 |= 0x8000;
4199 }
4200 av++;
4201 break;
4202 }
4203
4204 case TOK_SETDSCP:
4205 {
4206 int code;
4207
4208 action->opcode = O_SETDSCP;
4209 NEED1("missing DSCP code");
4210 if (_substrcmp(*av, "tablearg") == 0) {
4211 action->arg1 = IP_FW_TARG;
4212 } else {
4213 if (isalpha(*av[0])) {
4214 if ((code = match_token(f_ipdscp, *av)) == -1)
4215 errx(EX_DATAERR, "Unknown DSCP code");
4216 action->arg1 = code;
4217 } else
4218 action->arg1 = strtoul(*av, NULL, 10);
4219 /*
4220 * Add high-order bit to DSCP to make room
4221 * for tablearg
4222 */
4223 action->arg1 |= 0x8000;
4224 }
4225 av++;
4226 break;
4227 }
4228
4229 case TOK_REASS:
4230 action->opcode = O_REASS;
4231 break;
4232
4233 case TOK_RETURN:
4234 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4235 break;
4236
4237 case TOK_TCPSETMSS: {
4238 u_long mss;
4239 uint16_t idx;
4240
4241 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4242 if (idx == 0)
4243 errx(EX_DATAERR, "pack_object failed");
4244 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4245 NEED1("Missing MSS value");
4246 action = next_cmd(action, &ablen);
4247 action->len = 1;
4248 CHECK_ACTLEN;
4249 mss = strtoul(*av, NULL, 10);
4250 if (mss == 0 || mss > UINT16_MAX)
4251 errx(EX_USAGE, "invalid MSS value %s", *av);
4252 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4253 av++;
4254 break;
4255 }
4256
4257 default:
4258 av--;
4259 if (match_token(rule_eactions, *av) == -1)
4260 errx(EX_DATAERR, "invalid action %s\n", *av);
4261 /*
4262 * External actions support.
4263 * XXX: we support only syntax with instance name.
4264 * For known external actions (from rule_eactions list)
4265 * we can handle syntax directly. But with `eaction'
4266 * keyword we can use only `eaction <name> <instance>'
4267 * syntax.
4268 */
4269 case TOK_EACTION: {
4270 uint16_t idx;
4271
4272 NEED1("Missing eaction name");
4273 if (eaction_check_name(*av) != 0)
4274 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4275 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4276 if (idx == 0)
4277 errx(EX_DATAERR, "pack_object failed");
4278 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4279 av++;
4280 NEED1("Missing eaction instance name");
4281 action = next_cmd(action, &ablen);
4282 action->len = 1;
4283 CHECK_ACTLEN;
4284 if (eaction_check_name(*av) != 0)
4285 errx(EX_DATAERR, "Invalid eaction instance name %s",
4286 *av);
4287 /*
4288 * External action instance object has TLV type depended
4289 * from the external action name object index. Since we
4290 * currently don't know this index, use zero as TLV type.
4291 */
4292 idx = pack_object(tstate, *av, 0);
4293 if (idx == 0)
4294 errx(EX_DATAERR, "pack_object failed");
4295 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4296 av++;
4297 }
4298 }
4299 action = next_cmd(action, &ablen);
4300
4301 /*
4302 * [altq queuename] -- altq tag, optional
4303 * [log [logamount N]] -- log, optional
4304 *
4305 * If they exist, it go first in the cmdbuf, but then it is
4306 * skipped in the copy section to the end of the buffer.
4307 */
4308 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4309 av++;
4310 switch (i) {
4311 case TOK_LOG:
4312 {
4313 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4314 int l;
4315
4316 if (have_log)
4317 errx(EX_DATAERR,
4318 "log cannot be specified more than once");
4319 have_log = (ipfw_insn *)c;
4320 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4321 CHECK_CMDLEN;
4322 cmd->opcode = O_LOG;
4323 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4324 av++;
4325 NEED1("logamount requires argument");
4326 l = atoi(*av);
4327 if (l < 0)
4328 errx(EX_DATAERR,
4329 "logamount must be positive");
4330 c->max_log = l;
4331 av++;
4332 } else {
4333 len = sizeof(c->max_log);
4334 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4335 &c->max_log, &len, NULL, 0) == -1) {
4336 if (g_co.test_only) {
4337 c->max_log = 0;
4338 break;
4339 }
4340 errx(1, "sysctlbyname(\"%s\")",
4341 "net.inet.ip.fw.verbose_limit");
4342 }
4343 }
4344 }
4345 break;
4346
4347 #ifndef NO_ALTQ
4348 case TOK_ALTQ:
4349 {
4350 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4351
4352 NEED1("missing altq queue name");
4353 if (have_altq)
4354 errx(EX_DATAERR,
4355 "altq cannot be specified more than once");
4356 have_altq = (ipfw_insn *)a;
4357 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4358 CHECK_CMDLEN;
4359 cmd->opcode = O_ALTQ;
4360 a->qid = altq_name_to_qid(*av);
4361 av++;
4362 }
4363 break;
4364 #endif
4365
4366 case TOK_TAG:
4367 case TOK_UNTAG: {
4368 uint16_t tag;
4369
4370 if (have_tag)
4371 errx(EX_USAGE, "tag and untag cannot be "
4372 "specified more than once");
4373 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4374 rule_action_params);
4375 have_tag = cmd;
4376 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4377 av++;
4378 break;
4379 }
4380
4381 default:
4382 abort();
4383 }
4384 cmd = next_cmd(cmd, &cblen);
4385 }
4386
4387 if (have_state) { /* must be a check-state, we are done */
4388 if (*av != NULL &&
4389 match_token(rule_options, *av) == TOK_COMMENT) {
4390 /* check-state has a comment */
4391 av++;
4392 fill_comment(cmd, av, cblen);
4393 cmd = next_cmd(cmd, &cblen);
4394 av[0] = NULL;
4395 }
4396 goto done;
4397 }
4398
4399 #define OR_START(target) \
4400 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4401 if (open_par) \
4402 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4403 prev = NULL; \
4404 open_par = 1; \
4405 if ( (av[0])[1] == '\0') { \
4406 av++; \
4407 } else \
4408 (*av)++; \
4409 } \
4410 target: \
4411
4412
4413 #define CLOSE_PAR \
4414 if (open_par) { \
4415 if (av[0] && ( \
4416 strcmp(*av, ")") == 0 || \
4417 strcmp(*av, "}") == 0)) { \
4418 prev = NULL; \
4419 open_par = 0; \
4420 av++; \
4421 } else \
4422 errx(EX_USAGE, "missing \")\"\n"); \
4423 }
4424
4425 #define NOT_BLOCK \
4426 if (av[0] && _substrcmp(*av, "not") == 0) { \
4427 if (cmd->len & F_NOT) \
4428 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4429 cmd->len |= F_NOT; \
4430 av++; \
4431 }
4432
4433 #define OR_BLOCK(target) \
4434 if (av[0] && _substrcmp(*av, "or") == 0) { \
4435 if (prev == NULL || open_par == 0) \
4436 errx(EX_DATAERR, "invalid OR block"); \
4437 prev->len |= F_OR; \
4438 av++; \
4439 goto target; \
4440 } \
4441 CLOSE_PAR;
4442
4443 first_cmd = cmd;
4444
4445 #if 0
4446 /*
4447 * MAC addresses, optional.
4448 * If we have this, we skip the part "proto from src to dst"
4449 * and jump straight to the option parsing.
4450 */
4451 NOT_BLOCK;
4452 NEED1("missing protocol");
4453 if (_substrcmp(*av, "MAC") == 0 ||
4454 _substrcmp(*av, "mac") == 0) {
4455 av++; /* the "MAC" keyword */
4456 add_mac(cmd, av); /* exits in case of errors */
4457 cmd = next_cmd(cmd);
4458 av += 2; /* dst-mac and src-mac */
4459 NOT_BLOCK;
4460 NEED1("missing mac type");
4461 if (add_mactype(cmd, av[0]))
4462 cmd = next_cmd(cmd);
4463 av++; /* any or mac-type */
4464 goto read_options;
4465 }
4466 #endif
4467
4468 /*
4469 * protocol, mandatory
4470 */
4471 OR_START(get_proto);
4472 NOT_BLOCK;
4473 NEED1("missing protocol");
4474 if (add_proto_compat(cmd, *av, &proto)) {
4475 av++;
4476 if (F_LEN(cmd) != 0) {
4477 prev = cmd;
4478 cmd = next_cmd(cmd, &cblen);
4479 }
4480 } else if (first_cmd != cmd) {
4481 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4482 } else {
4483 rule->flags |= IPFW_RULE_JUSTOPTS;
4484 goto read_options;
4485 }
4486 OR_BLOCK(get_proto);
4487
4488 first_cmd = cmd; /* update pointer to use in compact form */
4489
4490 /*
4491 * "from", mandatory
4492 */
4493 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4494 errx(EX_USAGE, "missing ``from''");
4495 av++;
4496
4497 /*
4498 * source IP, mandatory
4499 */
4500 OR_START(source_ip);
4501 NOT_BLOCK; /* optional "not" */
4502 NEED1("missing source address");
4503 if (add_src(cmd, *av, proto, cblen, tstate)) {
4504 av++;
4505 if (F_LEN(cmd) != 0) { /* ! any */
4506 prev = cmd;
4507 cmd = next_cmd(cmd, &cblen);
4508 }
4509 } else
4510 errx(EX_USAGE, "bad source address %s", *av);
4511 OR_BLOCK(source_ip);
4512
4513 /*
4514 * source ports, optional
4515 */
4516 NOT_BLOCK; /* optional "not" */
4517 if ( av[0] != NULL ) {
4518 if (_substrcmp(*av, "any") == 0 ||
4519 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4520 av++;
4521 if (F_LEN(cmd) != 0)
4522 cmd = next_cmd(cmd, &cblen);
4523 }
4524 }
4525
4526 /*
4527 * "to", mandatory
4528 */
4529 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4530 errx(EX_USAGE, "missing ``to''");
4531 av++;
4532
4533 /*
4534 * destination, mandatory
4535 */
4536 OR_START(dest_ip);
4537 NOT_BLOCK; /* optional "not" */
4538 NEED1("missing dst address");
4539 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4540 av++;
4541 if (F_LEN(cmd) != 0) { /* ! any */
4542 prev = cmd;
4543 cmd = next_cmd(cmd, &cblen);
4544 }
4545 } else
4546 errx( EX_USAGE, "bad destination address %s", *av);
4547 OR_BLOCK(dest_ip);
4548
4549 /*
4550 * dest. ports, optional
4551 */
4552 NOT_BLOCK; /* optional "not" */
4553 if (av[0]) {
4554 if (_substrcmp(*av, "any") == 0 ||
4555 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4556 av++;
4557 if (F_LEN(cmd) != 0)
4558 cmd = next_cmd(cmd, &cblen);
4559 }
4560 }
4561 if (first_cmd == cmd)
4562 rule->flags |= IPFW_RULE_NOOPT;
4563
4564 read_options:
4565 prev = NULL;
4566 while ( av[0] != NULL ) {
4567 char *s;
4568 ipfw_insn_u32 *cmd32; /* alias for cmd */
4569
4570 s = *av;
4571 cmd32 = (ipfw_insn_u32 *)cmd;
4572
4573 if (*s == '!') { /* alternate syntax for NOT */
4574 if (cmd->len & F_NOT)
4575 errx(EX_USAGE, "double \"not\" not allowed\n");
4576 cmd->len = F_NOT;
4577 s++;
4578 }
4579 i = match_token(rule_options, s);
4580 av++;
4581 switch(i) {
4582 case TOK_NOT:
4583 if (cmd->len & F_NOT)
4584 errx(EX_USAGE, "double \"not\" not allowed\n");
4585 cmd->len = F_NOT;
4586 break;
4587
4588 case TOK_OR:
4589 if (open_par == 0 || prev == NULL)
4590 errx(EX_USAGE, "invalid \"or\" block\n");
4591 prev->len |= F_OR;
4592 break;
4593
4594 case TOK_STARTBRACE:
4595 if (open_par)
4596 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4597 open_par = 1;
4598 break;
4599
4600 case TOK_ENDBRACE:
4601 if (!open_par)
4602 errx(EX_USAGE, "+missing \")\"\n");
4603 open_par = 0;
4604 prev = NULL;
4605 break;
4606
4607 case TOK_IN:
4608 fill_cmd(cmd, O_IN, 0, 0);
4609 break;
4610
4611 case TOK_OUT:
4612 cmd->len ^= F_NOT; /* toggle F_NOT */
4613 fill_cmd(cmd, O_IN, 0, 0);
4614 break;
4615
4616 case TOK_DIVERTED:
4617 fill_cmd(cmd, O_DIVERTED, 0, 3);
4618 break;
4619
4620 case TOK_DIVERTEDLOOPBACK:
4621 fill_cmd(cmd, O_DIVERTED, 0, 1);
4622 break;
4623
4624 case TOK_DIVERTEDOUTPUT:
4625 fill_cmd(cmd, O_DIVERTED, 0, 2);
4626 break;
4627
4628 case TOK_FRAG: {
4629 uint32_t set = 0, clear = 0;
4630
4631 if (*av != NULL && fill_flags(f_ipoff, *av, NULL,
4632 &set, &clear) == 0)
4633 av++;
4634 else {
4635 /*
4636 * Compatibility: no argument after "frag"
4637 * keyword equals to "frag offset".
4638 */
4639 set = 0x01;
4640 clear = 0;
4641 }
4642 fill_cmd(cmd, O_FRAG, 0,
4643 (set & 0xff) | ( (clear & 0xff) << 8));
4644 break;
4645 }
4646
4647 case TOK_LAYER2:
4648 fill_cmd(cmd, O_LAYER2, 0, 0);
4649 break;
4650
4651 case TOK_XMIT:
4652 case TOK_RECV:
4653 case TOK_VIA:
4654 NEED1("recv, xmit, via require interface name"
4655 " or address");
4656 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4657 av++;
4658 if (F_LEN(cmd) == 0) /* not a valid address */
4659 break;
4660 if (i == TOK_XMIT)
4661 cmd->opcode = O_XMIT;
4662 else if (i == TOK_RECV)
4663 cmd->opcode = O_RECV;
4664 else if (i == TOK_VIA)
4665 cmd->opcode = O_VIA;
4666 break;
4667
4668 case TOK_ICMPTYPES:
4669 NEED1("icmptypes requires list of types");
4670 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4671 av++;
4672 break;
4673
4674 case TOK_ICMP6TYPES:
4675 NEED1("icmptypes requires list of types");
4676 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4677 av++;
4678 break;
4679
4680 case TOK_IPTTL:
4681 NEED1("ipttl requires TTL");
4682 if (strpbrk(*av, "-,")) {
4683 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4684 errx(EX_DATAERR, "invalid ipttl %s", *av);
4685 } else
4686 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4687 av++;
4688 break;
4689
4690 case TOK_IPID:
4691 NEED1("ipid requires id");
4692 if (strpbrk(*av, "-,")) {
4693 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4694 errx(EX_DATAERR, "invalid ipid %s", *av);
4695 } else
4696 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4697 av++;
4698 break;
4699
4700 case TOK_IPLEN:
4701 NEED1("iplen requires length");
4702 if (strpbrk(*av, "-,")) {
4703 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4704 errx(EX_DATAERR, "invalid ip len %s", *av);
4705 } else
4706 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4707 av++;
4708 break;
4709
4710 case TOK_IPVER:
4711 NEED1("ipver requires version");
4712 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4713 av++;
4714 break;
4715
4716 case TOK_IPPRECEDENCE:
4717 NEED1("ipprecedence requires value");
4718 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4719 (strtoul(*av, NULL, 0) & 7) << 5);
4720 av++;
4721 break;
4722
4723 case TOK_DSCP:
4724 NEED1("missing DSCP code");
4725 fill_dscp(cmd, *av, cblen);
4726 av++;
4727 break;
4728
4729 case TOK_IPOPTS:
4730 NEED1("missing argument for ipoptions");
4731 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4732 av++;
4733 break;
4734
4735 case TOK_IPTOS:
4736 NEED1("missing argument for iptos");
4737 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4738 av++;
4739 break;
4740
4741 case TOK_UID:
4742 NEED1("uid requires argument");
4743 {
4744 char *end;
4745 uid_t uid;
4746 struct passwd *pwd;
4747
4748 cmd->opcode = O_UID;
4749 uid = strtoul(*av, &end, 0);
4750 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4751 if (pwd == NULL)
4752 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4753 cmd32->d[0] = pwd->pw_uid;
4754 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4755 av++;
4756 }
4757 break;
4758
4759 case TOK_GID:
4760 NEED1("gid requires argument");
4761 {
4762 char *end;
4763 gid_t gid;
4764 struct group *grp;
4765
4766 cmd->opcode = O_GID;
4767 gid = strtoul(*av, &end, 0);
4768 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4769 if (grp == NULL)
4770 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4771 cmd32->d[0] = grp->gr_gid;
4772 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4773 av++;
4774 }
4775 break;
4776
4777 case TOK_JAIL:
4778 NEED1("jail requires argument");
4779 {
4780 char *end;
4781 int jid;
4782
4783 cmd->opcode = O_JAIL;
4784 /*
4785 * If av is a number, then we'll just pass it as-is. If
4786 * it's a name, try to resolve that to a jid.
4787 *
4788 * We save the jail_getid(3) call for a fallback because
4789 * it entails an unconditional trip to the kernel to
4790 * either validate a jid or resolve a name to a jid.
4791 * This specific token doesn't currently require a
4792 * jid to be an active jail, so we save a transition
4793 * by simply using a number that we're given.
4794 */
4795 jid = strtoul(*av, &end, 10);
4796 if (*end != '\0') {
4797 jid = jail_getid(*av);
4798 if (jid < 0)
4799 errx(EX_DATAERR, "%s", jail_errmsg);
4800 }
4801 cmd32->d[0] = (uint32_t)jid;
4802 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4803 av++;
4804 }
4805 break;
4806
4807 case TOK_ESTAB:
4808 fill_cmd(cmd, O_ESTAB, 0, 0);
4809 break;
4810
4811 case TOK_SETUP:
4812 fill_cmd(cmd, O_TCPFLAGS, 0,
4813 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4814 break;
4815
4816 case TOK_TCPDATALEN:
4817 NEED1("tcpdatalen requires length");
4818 if (strpbrk(*av, "-,")) {
4819 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4820 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4821 } else
4822 fill_cmd(cmd, O_TCPDATALEN, 0,
4823 strtoul(*av, NULL, 0));
4824 av++;
4825 break;
4826
4827 case TOK_TCPOPTS:
4828 NEED1("missing argument for tcpoptions");
4829 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4830 av++;
4831 break;
4832
4833 case TOK_TCPSEQ:
4834 case TOK_TCPACK:
4835 NEED1("tcpseq/tcpack requires argument");
4836 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4837 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4838 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4839 av++;
4840 break;
4841
4842 case TOK_TCPMSS:
4843 case TOK_TCPWIN:
4844 NEED1("tcpmss/tcpwin requires size");
4845 if (strpbrk(*av, "-,")) {
4846 if (add_ports(cmd, *av, 0,
4847 i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
4848 cblen) == NULL)
4849 errx(EX_DATAERR, "invalid %s size %s",
4850 s, *av);
4851 } else
4852 fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
4853 O_TCPMSS, 0, strtoul(*av, NULL, 0));
4854 av++;
4855 break;
4856
4857 case TOK_TCPFLAGS:
4858 NEED1("missing argument for tcpflags");
4859 cmd->opcode = O_TCPFLAGS;
4860 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4861 av++;
4862 break;
4863
4864 case TOK_KEEPSTATE:
4865 case TOK_RECORDSTATE: {
4866 uint16_t uidx;
4867
4868 if (open_par)
4869 errx(EX_USAGE, "keep-state or record-state cannot be part "
4870 "of an or block");
4871 if (have_state)
4872 errx(EX_USAGE, "only one of keep-state, record-state, "
4873 " limit and set-limit is allowed");
4874 if (*av != NULL && *av[0] == ':') {
4875 if (state_check_name(*av + 1) != 0)
4876 errx(EX_DATAERR,
4877 "Invalid state name %s", *av);
4878 uidx = pack_object(tstate, *av + 1,
4879 IPFW_TLV_STATE_NAME);
4880 av++;
4881 } else
4882 uidx = pack_object(tstate, default_state_name,
4883 IPFW_TLV_STATE_NAME);
4884 have_state = cmd;
4885 have_rstate = i == TOK_RECORDSTATE;
4886 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4887 break;
4888 }
4889
4890 case TOK_LIMIT:
4891 case TOK_SETLIMIT: {
4892 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4893 int val;
4894
4895 if (open_par)
4896 errx(EX_USAGE,
4897 "limit or set-limit cannot be part of an or block");
4898 if (have_state)
4899 errx(EX_USAGE, "only one of keep-state, record-state, "
4900 " limit and set-limit is allowed");
4901 have_state = cmd;
4902 have_rstate = i == TOK_SETLIMIT;
4903
4904 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4905 CHECK_CMDLEN;
4906 cmd->opcode = O_LIMIT;
4907 c->limit_mask = c->conn_limit = 0;
4908
4909 while ( av[0] != NULL ) {
4910 if ((val = match_token(limit_masks, *av)) <= 0)
4911 break;
4912 c->limit_mask |= val;
4913 av++;
4914 }
4915
4916 if (c->limit_mask == 0)
4917 errx(EX_USAGE, "limit: missing limit mask");
4918
4919 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4920 TOK_LIMIT, rule_options);
4921 av++;
4922
4923 if (*av != NULL && *av[0] == ':') {
4924 if (state_check_name(*av + 1) != 0)
4925 errx(EX_DATAERR,
4926 "Invalid state name %s", *av);
4927 cmd->arg1 = pack_object(tstate, *av + 1,
4928 IPFW_TLV_STATE_NAME);
4929 av++;
4930 } else
4931 cmd->arg1 = pack_object(tstate,
4932 default_state_name, IPFW_TLV_STATE_NAME);
4933 break;
4934 }
4935
4936 case TOK_PROTO:
4937 NEED1("missing protocol");
4938 if (add_proto(cmd, *av, &proto)) {
4939 av++;
4940 } else
4941 errx(EX_DATAERR, "invalid protocol ``%s''",
4942 *av);
4943 break;
4944
4945 case TOK_SRCIP:
4946 NEED1("missing source IP");
4947 if (add_srcip(cmd, *av, cblen, tstate)) {
4948 av++;
4949 }
4950 break;
4951
4952 case TOK_DSTIP:
4953 NEED1("missing destination IP");
4954 if (add_dstip(cmd, *av, cblen, tstate)) {
4955 av++;
4956 }
4957 break;
4958
4959 case TOK_SRCIP6:
4960 NEED1("missing source IP6");
4961 if (add_srcip6(cmd, *av, cblen, tstate)) {
4962 av++;
4963 }
4964 break;
4965
4966 case TOK_DSTIP6:
4967 NEED1("missing destination IP6");
4968 if (add_dstip6(cmd, *av, cblen, tstate)) {
4969 av++;
4970 }
4971 break;
4972
4973
4974 case TOK_SRCMAC:
4975 NEED1("missing source MAC");
4976 if (add_srcmac(cmd, *av, tstate)) {
4977 av++;
4978 }
4979 break;
4980
4981 case TOK_DSTMAC:
4982 NEED1("missing destination MAC");
4983 if (add_dstmac(cmd, *av, tstate)) {
4984 av++;
4985 }
4986 break;
4987
4988 case TOK_SRCPORT:
4989 NEED1("missing source port");
4990 if (_substrcmp(*av, "any") == 0 ||
4991 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4992 av++;
4993 } else
4994 errx(EX_DATAERR, "invalid source port %s", *av);
4995 break;
4996
4997 case TOK_DSTPORT:
4998 NEED1("missing destination port");
4999 if (_substrcmp(*av, "any") == 0 ||
5000 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5001 av++;
5002 } else
5003 errx(EX_DATAERR, "invalid destination port %s",
5004 *av);
5005 break;
5006
5007 case TOK_MAC:
5008 if (add_mac(cmd, av, cblen))
5009 av += 2;
5010 break;
5011
5012 case TOK_MACTYPE:
5013 NEED1("missing mac type");
5014 if (!add_mactype(cmd, *av, cblen))
5015 errx(EX_DATAERR, "invalid mac type %s", *av);
5016 av++;
5017 break;
5018
5019 case TOK_VERREVPATH:
5020 fill_cmd(cmd, O_VERREVPATH, 0, 0);
5021 break;
5022
5023 case TOK_VERSRCREACH:
5024 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5025 break;
5026
5027 case TOK_ANTISPOOF:
5028 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5029 break;
5030
5031 case TOK_IPSEC:
5032 fill_cmd(cmd, O_IPSEC, 0, 0);
5033 break;
5034
5035 case TOK_IPV6:
5036 fill_cmd(cmd, O_IP6, 0, 0);
5037 break;
5038
5039 case TOK_IPV4:
5040 fill_cmd(cmd, O_IP4, 0, 0);
5041 break;
5042
5043 case TOK_EXT6HDR:
5044 NEED1("missing extension header");
5045 fill_ext6hdr( cmd, *av );
5046 av++;
5047 break;
5048
5049 case TOK_FLOWID:
5050 if (proto != IPPROTO_IPV6 )
5051 errx( EX_USAGE, "flow-id filter is active "
5052 "only for ipv6 protocol\n");
5053 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
5054 av++;
5055 break;
5056
5057 case TOK_COMMENT:
5058 fill_comment(cmd, av, cblen);
5059 av[0]=NULL;
5060 break;
5061
5062 case TOK_TAGGED:
5063 if (av[0] && strpbrk(*av, "-,")) {
5064 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
5065 errx(EX_DATAERR, "tagged: invalid tag"
5066 " list: %s", *av);
5067 }
5068 else {
5069 uint16_t tag;
5070
5071 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
5072 TOK_TAGGED, rule_options);
5073 fill_cmd(cmd, O_TAGGED, 0, tag);
5074 }
5075 av++;
5076 break;
5077
5078 case TOK_FIB:
5079 NEED1("fib requires fib number");
5080 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5081 av++;
5082 break;
5083 case TOK_SOCKARG:
5084 fill_cmd(cmd, O_SOCKARG, 0, 0);
5085 break;
5086
5087 case TOK_LOOKUP: {
5088 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
5089
5090 if (!av[0] || !av[1])
5091 errx(EX_USAGE, "format: lookup argument tablenum");
5092 cmd->opcode = O_IP_DST_LOOKUP;
5093 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
5094 i = match_token(lookup_keys, *av);
5095 if (i == -1)
5096 errx(EX_USAGE, "format: cannot lookup on %s", *av);
5097 __PAST_END(c->d, 1) = i;
5098 av++;
5099
5100 if ((i = pack_table(tstate, *av)) == 0)
5101 errx(EX_DATAERR, "Invalid table name: %s", *av);
5102
5103 cmd->arg1 = i;
5104 av++;
5105 }
5106 break;
5107 case TOK_FLOW:
5108 NEED1("missing table name");
5109 if (strncmp(*av, "table(", 6) != 0)
5110 errx(EX_DATAERR,
5111 "enclose table name into \"table()\"");
5112 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5113 av++;
5114 break;
5115
5116 case TOK_SKIPACTION:
5117 if (have_skipcmd)
5118 errx(EX_USAGE, "only one defer-action "
5119 "is allowed");
5120 have_skipcmd = cmd;
5121 fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5122 break;
5123
5124 default:
5125 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5126 }
5127 if (F_LEN(cmd) > 0) { /* prepare to advance */
5128 prev = cmd;
5129 cmd = next_cmd(cmd, &cblen);
5130 }
5131 }
5132
5133 done:
5134
5135 if (!have_state && have_skipcmd)
5136 warnx("Rule contains \"defer-immediate-action\" "
5137 "and doesn't contain any state-related options.");
5138
5139 /*
5140 * Now copy stuff into the rule.
5141 * If we have a keep-state option, the first instruction
5142 * must be a PROBE_STATE (which is generated here).
5143 * If we have a LOG option, it was stored as the first command,
5144 * and now must be moved to the top of the action part.
5145 */
5146 dst = (ipfw_insn *)rule->cmd;
5147
5148 /*
5149 * First thing to write into the command stream is the match probability.
5150 */
5151 if (match_prob != 1) { /* 1 means always match */
5152 dst->opcode = O_PROB;
5153 dst->len = 2;
5154 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5155 dst += dst->len;
5156 }
5157
5158 /*
5159 * generate O_PROBE_STATE if necessary
5160 */
5161 if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5162 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5163 dst = next_cmd(dst, &rblen);
5164 }
5165
5166 /*
5167 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5168 * O_SKIP_ACTION
5169 */
5170 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5171 i = F_LEN(src);
5172 CHECK_RBUFLEN(i);
5173
5174 switch (src->opcode) {
5175 case O_LOG:
5176 case O_KEEP_STATE:
5177 case O_LIMIT:
5178 case O_ALTQ:
5179 case O_TAG:
5180 case O_SKIP_ACTION:
5181 break;
5182 default:
5183 bcopy(src, dst, i * sizeof(uint32_t));
5184 dst += i;
5185 }
5186 }
5187
5188 /*
5189 * put back the have_state command as last opcode
5190 */
5191 if (have_state && have_state->opcode != O_CHECK_STATE) {
5192 i = F_LEN(have_state);
5193 CHECK_RBUFLEN(i);
5194 bcopy(have_state, dst, i * sizeof(uint32_t));
5195 dst += i;
5196 }
5197
5198 /*
5199 * put back the have_skipcmd command as very last opcode
5200 */
5201 if (have_skipcmd) {
5202 i = F_LEN(have_skipcmd);
5203 CHECK_RBUFLEN(i);
5204 bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5205 dst += i;
5206 }
5207
5208 /*
5209 * start action section
5210 */
5211 rule->act_ofs = dst - rule->cmd;
5212
5213 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5214 if (have_log) {
5215 i = F_LEN(have_log);
5216 CHECK_RBUFLEN(i);
5217 bcopy(have_log, dst, i * sizeof(uint32_t));
5218 dst += i;
5219 }
5220 if (have_altq) {
5221 i = F_LEN(have_altq);
5222 CHECK_RBUFLEN(i);
5223 bcopy(have_altq, dst, i * sizeof(uint32_t));
5224 dst += i;
5225 }
5226 if (have_tag) {
5227 i = F_LEN(have_tag);
5228 CHECK_RBUFLEN(i);
5229 bcopy(have_tag, dst, i * sizeof(uint32_t));
5230 dst += i;
5231 }
5232
5233 /*
5234 * copy all other actions
5235 */
5236 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5237 i = F_LEN(src);
5238 CHECK_RBUFLEN(i);
5239 bcopy(src, dst, i * sizeof(uint32_t));
5240 dst += i;
5241 }
5242
5243 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5244 *rbufsize = (char *)dst - (char *)rule;
5245 }
5246
5247 static int
compare_ntlv(const void * _a,const void * _b)5248 compare_ntlv(const void *_a, const void *_b)
5249 {
5250 const ipfw_obj_ntlv *a, *b;
5251
5252 a = (const ipfw_obj_ntlv *)_a;
5253 b = (const ipfw_obj_ntlv *)_b;
5254
5255 if (a->set < b->set)
5256 return (-1);
5257 else if (a->set > b->set)
5258 return (1);
5259
5260 if (a->idx < b->idx)
5261 return (-1);
5262 else if (a->idx > b->idx)
5263 return (1);
5264
5265 if (a->head.type < b->head.type)
5266 return (-1);
5267 else if (a->head.type > b->head.type)
5268 return (1);
5269
5270 return (0);
5271 }
5272
5273 /*
5274 * Provide kernel with sorted list of referenced objects
5275 */
5276 static void
object_sort_ctlv(ipfw_obj_ctlv * ctlv)5277 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5278 {
5279
5280 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5281 }
5282
5283 struct object_kt {
5284 uint16_t uidx;
5285 uint16_t type;
5286 };
5287 static int
compare_object_kntlv(const void * k,const void * v)5288 compare_object_kntlv(const void *k, const void *v)
5289 {
5290 const ipfw_obj_ntlv *ntlv;
5291 struct object_kt key;
5292
5293 key = *((const struct object_kt *)k);
5294 ntlv = (const ipfw_obj_ntlv *)v;
5295
5296 if (key.uidx < ntlv->idx)
5297 return (-1);
5298 else if (key.uidx > ntlv->idx)
5299 return (1);
5300
5301 if (key.type < ntlv->head.type)
5302 return (-1);
5303 else if (key.type > ntlv->head.type)
5304 return (1);
5305
5306 return (0);
5307 }
5308
5309 /*
5310 * Finds object name in @ctlv by @idx and @type.
5311 * Uses the following facts:
5312 * 1) All TLVs are the same size
5313 * 2) Kernel implementation provides already sorted list.
5314 *
5315 * Returns table name or NULL.
5316 */
5317 static char *
object_search_ctlv(ipfw_obj_ctlv * ctlv,uint16_t idx,uint16_t type)5318 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5319 {
5320 ipfw_obj_ntlv *ntlv;
5321 struct object_kt key;
5322
5323 key.uidx = idx;
5324 key.type = type;
5325
5326 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5327 compare_object_kntlv);
5328
5329 if (ntlv != NULL)
5330 return (ntlv->name);
5331
5332 return (NULL);
5333 }
5334
5335 static char *
table_search_ctlv(ipfw_obj_ctlv * ctlv,uint16_t idx)5336 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5337 {
5338
5339 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5340 }
5341
5342 /*
5343 * Adds one or more rules to ipfw chain.
5344 * Data layout:
5345 * Request:
5346 * [
5347 * ip_fw3_opheader
5348 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5349 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5350 * ]
5351 * Reply:
5352 * [
5353 * ip_fw3_opheader
5354 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5355 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5356 * ]
5357 *
5358 * Rules in reply are modified to store their actual ruleset number.
5359 *
5360 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5361 * according to their idx field and there has to be no duplicates.
5362 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5363 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5364 */
5365 void
ipfw_add(char * av[])5366 ipfw_add(char *av[])
5367 {
5368 uint32_t rulebuf[1024];
5369 int rbufsize, default_off, tlen, rlen;
5370 size_t sz;
5371 struct tidx ts;
5372 struct ip_fw_rule *rule;
5373 caddr_t tbuf;
5374 ip_fw3_opheader *op3;
5375 ipfw_obj_ctlv *ctlv, *tstate;
5376
5377 rbufsize = sizeof(rulebuf);
5378 memset(rulebuf, 0, rbufsize);
5379 memset(&ts, 0, sizeof(ts));
5380
5381 /* Optimize case with no tables */
5382 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5383 op3 = (ip_fw3_opheader *)rulebuf;
5384 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5385 rule = (struct ip_fw_rule *)(ctlv + 1);
5386 rbufsize -= default_off;
5387
5388 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5389 /* Align rule size to u64 boundary */
5390 rlen = roundup2(rbufsize, sizeof(uint64_t));
5391
5392 tbuf = NULL;
5393 sz = 0;
5394 tstate = NULL;
5395 if (ts.count != 0) {
5396 /* Some tables. We have to alloc more data */
5397 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5398 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5399
5400 if ((tbuf = calloc(1, sz)) == NULL)
5401 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5402 op3 = (ip_fw3_opheader *)tbuf;
5403 /* Tables first */
5404 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5405 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5406 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5407 ctlv->count = ts.count;
5408 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5409 memcpy(ctlv + 1, ts.idx, tlen);
5410 object_sort_ctlv(ctlv);
5411 tstate = ctlv;
5412 /* Rule next */
5413 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5414 ctlv->head.type = IPFW_TLV_RULE_LIST;
5415 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5416 ctlv->count = 1;
5417 memcpy(ctlv + 1, rule, rbufsize);
5418 } else {
5419 /* Simply add header */
5420 sz = rlen + default_off;
5421 memset(ctlv, 0, sizeof(*ctlv));
5422 ctlv->head.type = IPFW_TLV_RULE_LIST;
5423 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5424 ctlv->count = 1;
5425 }
5426
5427 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5428 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5429
5430 if (!g_co.do_quiet) {
5431 struct format_opts sfo;
5432 struct buf_pr bp;
5433 memset(&sfo, 0, sizeof(sfo));
5434 sfo.tstate = tstate;
5435 sfo.set_mask = (uint32_t)(-1);
5436 bp_alloc(&bp, 4096);
5437 show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5438 printf("%s", bp.buf);
5439 bp_free(&bp);
5440 }
5441
5442 if (tbuf != NULL)
5443 free(tbuf);
5444
5445 if (ts.idx != NULL)
5446 free(ts.idx);
5447 }
5448
5449 /*
5450 * clear the counters or the log counters.
5451 * optname has the following values:
5452 * 0 (zero both counters and logging)
5453 * 1 (zero logging only)
5454 */
5455 void
ipfw_zero(int ac,char * av[],int optname)5456 ipfw_zero(int ac, char *av[], int optname)
5457 {
5458 ipfw_range_tlv rt;
5459 char const *errstr;
5460 char const *name = optname ? "RESETLOG" : "ZERO";
5461 uint32_t arg;
5462 int failed = EX_OK;
5463
5464 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5465 av++; ac--;
5466
5467 if (ac == 0) {
5468 /* clear all entries */
5469 memset(&rt, 0, sizeof(rt));
5470 rt.flags = IPFW_RCFLAG_ALL;
5471 if (do_range_cmd(optname, &rt) < 0)
5472 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5473 if (!g_co.do_quiet)
5474 printf("%s.\n", optname == IP_FW_XZERO ?
5475 "Accounting cleared":"Logging counts reset");
5476
5477 return;
5478 }
5479
5480 while (ac) {
5481 /* Rule number */
5482 if (isdigit(**av)) {
5483 arg = strtonum(*av, 0, 0xffff, &errstr);
5484 if (errstr)
5485 errx(EX_DATAERR,
5486 "invalid rule number %s\n", *av);
5487 memset(&rt, 0, sizeof(rt));
5488 rt.start_rule = arg;
5489 rt.end_rule = arg;
5490 rt.flags |= IPFW_RCFLAG_RANGE;
5491 if (g_co.use_set != 0) {
5492 rt.set = g_co.use_set - 1;
5493 rt.flags |= IPFW_RCFLAG_SET;
5494 }
5495 if (do_range_cmd(optname, &rt) != 0) {
5496 warn("rule %u: setsockopt(IP_FW_X%s)",
5497 arg, name);
5498 failed = EX_UNAVAILABLE;
5499 } else if (rt.new_set == 0) {
5500 printf("Entry %d not found\n", arg);
5501 failed = EX_UNAVAILABLE;
5502 } else if (!g_co.do_quiet)
5503 printf("Entry %d %s.\n", arg,
5504 optname == IP_FW_XZERO ?
5505 "cleared" : "logging count reset");
5506 } else {
5507 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5508 }
5509 av++; ac--;
5510 }
5511 if (failed != EX_OK)
5512 exit(failed);
5513 }
5514
5515 void
ipfw_flush(int force)5516 ipfw_flush(int force)
5517 {
5518 ipfw_range_tlv rt;
5519
5520 if (!force && !g_co.do_quiet) { /* need to ask user */
5521 int c;
5522
5523 printf("Are you sure? [yn] ");
5524 fflush(stdout);
5525 do {
5526 c = toupper(getc(stdin));
5527 while (c != '\n' && getc(stdin) != '\n')
5528 if (feof(stdin))
5529 return; /* and do not flush */
5530 } while (c != 'Y' && c != 'N');
5531 printf("\n");
5532 if (c == 'N') /* user said no */
5533 return;
5534 }
5535 if (g_co.do_pipe) {
5536 dummynet_flush();
5537 return;
5538 }
5539 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5540 memset(&rt, 0, sizeof(rt));
5541 if (g_co.use_set != 0) {
5542 rt.set = g_co.use_set - 1;
5543 rt.flags = IPFW_RCFLAG_SET;
5544 } else
5545 rt.flags = IPFW_RCFLAG_ALL;
5546 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5547 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5548 if (!g_co.do_quiet)
5549 printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
5550 }
5551
5552 static struct _s_x intcmds[] = {
5553 { "talist", TOK_TALIST },
5554 { "iflist", TOK_IFLIST },
5555 { "olist", TOK_OLIST },
5556 { "vlist", TOK_VLIST },
5557 { NULL, 0 }
5558 };
5559
5560 static struct _s_x otypes[] = {
5561 { "EACTION", IPFW_TLV_EACTION },
5562 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5563 { NULL, 0 }
5564 };
5565
5566 static const char*
lookup_eaction_name(ipfw_obj_ntlv * ntlv,int cnt,uint16_t type)5567 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5568 {
5569 const char *name;
5570 int i;
5571
5572 name = NULL;
5573 for (i = 0; i < cnt; i++) {
5574 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5575 continue;
5576 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5577 continue;
5578 name = ntlv[i].name;
5579 break;
5580 }
5581 return (name);
5582 }
5583
5584 static void
ipfw_list_objects(int ac __unused,char * av[]__unused)5585 ipfw_list_objects(int ac __unused, char *av[] __unused)
5586 {
5587 ipfw_obj_lheader req, *olh;
5588 ipfw_obj_ntlv *ntlv;
5589 const char *name;
5590 size_t sz;
5591 uint32_t i;
5592
5593 memset(&req, 0, sizeof(req));
5594 sz = sizeof(req);
5595 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5596 if (errno != ENOMEM)
5597 return;
5598
5599 sz = req.size;
5600 if ((olh = calloc(1, sz)) == NULL)
5601 return;
5602
5603 olh->size = sz;
5604 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5605 free(olh);
5606 return;
5607 }
5608
5609 if (olh->count > 0)
5610 printf("Objects list:\n");
5611 else
5612 printf("There are no objects\n");
5613 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5614 for (i = 0; i < olh->count; i++) {
5615 name = match_value(otypes, ntlv->head.type);
5616 if (name == NULL)
5617 name = lookup_eaction_name(
5618 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5619 ntlv->head.type);
5620 if (name == NULL)
5621 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5622 ntlv->idx, ntlv->head.type, ntlv->name);
5623 else
5624 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5625 ntlv->idx, name, ntlv->name);
5626 ntlv++;
5627 }
5628 free(olh);
5629 }
5630
5631 void
ipfw_internal_handler(int ac,char * av[])5632 ipfw_internal_handler(int ac, char *av[])
5633 {
5634 int tcmd;
5635
5636 ac--; av++;
5637 NEED1("internal cmd required");
5638
5639 if ((tcmd = match_token(intcmds, *av)) == -1)
5640 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5641
5642 switch (tcmd) {
5643 case TOK_IFLIST:
5644 ipfw_list_tifaces();
5645 break;
5646 case TOK_TALIST:
5647 ipfw_list_ta(ac, av);
5648 break;
5649 case TOK_OLIST:
5650 ipfw_list_objects(ac, av);
5651 break;
5652 case TOK_VLIST:
5653 ipfw_list_values(ac, av);
5654 break;
5655 }
5656 }
5657
5658 static int
ipfw_get_tracked_ifaces(ipfw_obj_lheader ** polh)5659 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5660 {
5661 ipfw_obj_lheader req, *olh;
5662 size_t sz;
5663
5664 memset(&req, 0, sizeof(req));
5665 sz = sizeof(req);
5666
5667 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5668 if (errno != ENOMEM)
5669 return (errno);
5670 }
5671
5672 sz = req.size;
5673 if ((olh = calloc(1, sz)) == NULL)
5674 return (ENOMEM);
5675
5676 olh->size = sz;
5677 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5678 free(olh);
5679 return (errno);
5680 }
5681
5682 *polh = olh;
5683 return (0);
5684 }
5685
5686 static int
ifinfo_cmp(const void * a,const void * b)5687 ifinfo_cmp(const void *a, const void *b)
5688 {
5689 const ipfw_iface_info *ia, *ib;
5690
5691 ia = (const ipfw_iface_info *)a;
5692 ib = (const ipfw_iface_info *)b;
5693
5694 return (stringnum_cmp(ia->ifname, ib->ifname));
5695 }
5696
5697 /*
5698 * Retrieves table list from kernel,
5699 * optionally sorts it and calls requested function for each table.
5700 * Returns 0 on success.
5701 */
5702 static void
ipfw_list_tifaces(void)5703 ipfw_list_tifaces(void)
5704 {
5705 ipfw_obj_lheader *olh = NULL;
5706 ipfw_iface_info *info;
5707 uint32_t i;
5708 int error;
5709
5710 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5711 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5712
5713 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5714
5715 info = (ipfw_iface_info *)(olh + 1);
5716 for (i = 0; i < olh->count; i++) {
5717 if (info->flags & IPFW_IFFLAG_RESOLVED)
5718 printf("%s ifindex: %d refcount: %u changes: %u\n",
5719 info->ifname, info->ifindex, info->refcnt,
5720 info->gencnt);
5721 else
5722 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5723 info->ifname, info->refcnt, info->gencnt);
5724 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
5725 }
5726
5727 free(olh);
5728 }
5729