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 * $FreeBSD$ 21 */ 22 23 #include <sys/param.h> 24 #include <sys/mbuf.h> 25 #include <sys/socket.h> 26 #include <sys/sockio.h> 27 #include <sys/sysctl.h> 28 #include <sys/time.h> 29 #include <sys/wait.h> 30 #include <sys/queue.h> 31 32 #include <ctype.h> 33 #include <err.h> 34 #include <errno.h> 35 #include <grp.h> 36 #include <limits.h> 37 #include <netdb.h> 38 #include <pwd.h> 39 #include <signal.h> 40 #include <stdio.h> 41 #include <stdlib.h> 42 #include <stdarg.h> 43 #include <string.h> 44 #include <timeconv.h> /* XXX do we need this ? */ 45 #include <unistd.h> 46 #include <sysexits.h> 47 #include <unistd.h> 48 #include <fcntl.h> 49 50 #define IPFW_INTERNAL /* Access to protected structures in ip_fw.h. */ 51 52 #include <net/ethernet.h> 53 #include <net/if.h> 54 #include <net/if_dl.h> 55 #include <net/pfvar.h> 56 #include <net/route.h> /* def. of struct route */ 57 #include <netinet/in.h> 58 #include <netinet/in_systm.h> 59 #include <netinet/ip.h> 60 #include <netinet/ip_icmp.h> 61 #include <netinet/icmp6.h> 62 #include <netinet/ip_fw.h> 63 #include <netinet/ip_dummynet.h> 64 #include <netinet/tcp.h> 65 #include <arpa/inet.h> 66 #include <alias.h> 67 68 int 69 do_value_as_ip, /* show table value as IP */ 70 do_resolv, /* Would try to resolve all */ 71 do_time, /* Show time stamps */ 72 do_quiet, /* Be quiet in add and flush */ 73 do_pipe, /* this cmd refers to a pipe */ 74 do_nat, /* Nat configuration. */ 75 do_sort, /* field to sort results (0 = no) */ 76 do_dynamic, /* display dynamic rules */ 77 do_expired, /* display expired dynamic rules */ 78 do_compact, /* show rules in compact mode */ 79 do_force, /* do not ask for confirmation */ 80 use_set, /* work with specified set number */ 81 show_sets, /* display rule sets */ 82 test_only, /* only check syntax */ 83 comment_only, /* only print action and comment */ 84 verbose; 85 86 #define IP_MASK_ALL 0xffffffff 87 /* 88 * the following macro returns an error message if we run out of 89 * arguments. 90 */ 91 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);} 92 93 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \ 94 if (!ac) \ 95 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \ 96 if (_substrcmp(*av, "tablearg") == 0) { \ 97 arg = IP_FW_TABLEARG; \ 98 break; \ 99 } \ 100 \ 101 { \ 102 long val; \ 103 char *end; \ 104 \ 105 val = strtol(*av, &end, 10); \ 106 \ 107 if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \ 108 errx(EX_DATAERR, "%s: invalid argument: %s", \ 109 match_value(s_x, tok), *av); \ 110 \ 111 if (errno == ERANGE || val < min || val > 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 (val == IP_FW_TABLEARG) \ 116 errx(EX_DATAERR, "%s: illegal argument value: %s", \ 117 match_value(s_x, tok), *av); \ 118 arg = val; \ 119 } \ 120 } while (0) 121 122 #define PRINT_UINT_ARG(str, arg) do { \ 123 if (str != NULL) \ 124 printf("%s",str); \ 125 if (arg == IP_FW_TABLEARG) \ 126 printf("tablearg"); \ 127 else \ 128 printf("%u", (uint32_t)arg); \ 129 } while (0) 130 131 /* 132 * _s_x is a structure that stores a string <-> token pairs, used in 133 * various places in the parser. Entries are stored in arrays, 134 * with an entry with s=NULL as terminator. 135 * The search routines are match_token() and match_value(). 136 * Often, an element with x=0 contains an error string. 137 * 138 */ 139 struct _s_x { 140 char const *s; 141 int x; 142 }; 143 144 static struct _s_x f_tcpflags[] = { 145 { "syn", TH_SYN }, 146 { "fin", TH_FIN }, 147 { "ack", TH_ACK }, 148 { "psh", TH_PUSH }, 149 { "rst", TH_RST }, 150 { "urg", TH_URG }, 151 { "tcp flag", 0 }, 152 { NULL, 0 } 153 }; 154 155 static struct _s_x f_tcpopts[] = { 156 { "mss", IP_FW_TCPOPT_MSS }, 157 { "maxseg", IP_FW_TCPOPT_MSS }, 158 { "window", IP_FW_TCPOPT_WINDOW }, 159 { "sack", IP_FW_TCPOPT_SACK }, 160 { "ts", IP_FW_TCPOPT_TS }, 161 { "timestamp", IP_FW_TCPOPT_TS }, 162 { "cc", IP_FW_TCPOPT_CC }, 163 { "tcp option", 0 }, 164 { NULL, 0 } 165 }; 166 167 /* 168 * IP options span the range 0 to 255 so we need to remap them 169 * (though in fact only the low 5 bits are significant). 170 */ 171 static struct _s_x f_ipopts[] = { 172 { "ssrr", IP_FW_IPOPT_SSRR}, 173 { "lsrr", IP_FW_IPOPT_LSRR}, 174 { "rr", IP_FW_IPOPT_RR}, 175 { "ts", IP_FW_IPOPT_TS}, 176 { "ip option", 0 }, 177 { NULL, 0 } 178 }; 179 180 static struct _s_x f_iptos[] = { 181 { "lowdelay", IPTOS_LOWDELAY}, 182 { "throughput", IPTOS_THROUGHPUT}, 183 { "reliability", IPTOS_RELIABILITY}, 184 { "mincost", IPTOS_MINCOST}, 185 { "congestion", IPTOS_ECN_CE}, 186 { "ecntransport", IPTOS_ECN_ECT0}, 187 { "ip tos option", 0}, 188 { NULL, 0 } 189 }; 190 191 static struct _s_x limit_masks[] = { 192 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT}, 193 {"src-addr", DYN_SRC_ADDR}, 194 {"src-port", DYN_SRC_PORT}, 195 {"dst-addr", DYN_DST_ADDR}, 196 {"dst-port", DYN_DST_PORT}, 197 {NULL, 0} 198 }; 199 200 /* 201 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines 202 * This is only used in this code. 203 */ 204 #define IPPROTO_ETHERTYPE 0x1000 205 static struct _s_x ether_types[] = { 206 /* 207 * Note, we cannot use "-:&/" in the names because they are field 208 * separators in the type specifications. Also, we use s = NULL as 209 * end-delimiter, because a type of 0 can be legal. 210 */ 211 { "ip", 0x0800 }, 212 { "ipv4", 0x0800 }, 213 { "ipv6", 0x86dd }, 214 { "arp", 0x0806 }, 215 { "rarp", 0x8035 }, 216 { "vlan", 0x8100 }, 217 { "loop", 0x9000 }, 218 { "trail", 0x1000 }, 219 { "at", 0x809b }, 220 { "atalk", 0x809b }, 221 { "aarp", 0x80f3 }, 222 { "pppoe_disc", 0x8863 }, 223 { "pppoe_sess", 0x8864 }, 224 { "ipx_8022", 0x00E0 }, 225 { "ipx_8023", 0x0000 }, 226 { "ipx_ii", 0x8137 }, 227 { "ipx_snap", 0x8137 }, 228 { "ipx", 0x8137 }, 229 { "ns", 0x0600 }, 230 { NULL, 0 } 231 }; 232 233 static void show_usage(void); 234 235 enum tokens { 236 TOK_NULL=0, 237 238 TOK_OR, 239 TOK_NOT, 240 TOK_STARTBRACE, 241 TOK_ENDBRACE, 242 243 TOK_ACCEPT, 244 TOK_COUNT, 245 TOK_PIPE, 246 TOK_QUEUE, 247 TOK_DIVERT, 248 TOK_TEE, 249 TOK_NETGRAPH, 250 TOK_NGTEE, 251 TOK_FORWARD, 252 TOK_SKIPTO, 253 TOK_DENY, 254 TOK_REJECT, 255 TOK_RESET, 256 TOK_UNREACH, 257 TOK_CHECKSTATE, 258 TOK_NAT, 259 260 TOK_ALTQ, 261 TOK_LOG, 262 TOK_TAG, 263 TOK_UNTAG, 264 265 TOK_TAGGED, 266 TOK_UID, 267 TOK_GID, 268 TOK_JAIL, 269 TOK_IN, 270 TOK_LIMIT, 271 TOK_KEEPSTATE, 272 TOK_LAYER2, 273 TOK_OUT, 274 TOK_DIVERTED, 275 TOK_DIVERTEDLOOPBACK, 276 TOK_DIVERTEDOUTPUT, 277 TOK_XMIT, 278 TOK_RECV, 279 TOK_VIA, 280 TOK_FRAG, 281 TOK_IPOPTS, 282 TOK_IPLEN, 283 TOK_IPID, 284 TOK_IPPRECEDENCE, 285 TOK_IPTOS, 286 TOK_IPTTL, 287 TOK_IPVER, 288 TOK_ESTAB, 289 TOK_SETUP, 290 TOK_TCPDATALEN, 291 TOK_TCPFLAGS, 292 TOK_TCPOPTS, 293 TOK_TCPSEQ, 294 TOK_TCPACK, 295 TOK_TCPWIN, 296 TOK_ICMPTYPES, 297 TOK_MAC, 298 TOK_MACTYPE, 299 TOK_VERREVPATH, 300 TOK_VERSRCREACH, 301 TOK_ANTISPOOF, 302 TOK_IPSEC, 303 TOK_COMMENT, 304 305 TOK_PLR, 306 TOK_NOERROR, 307 TOK_BUCKETS, 308 TOK_DSTIP, 309 TOK_SRCIP, 310 TOK_DSTPORT, 311 TOK_SRCPORT, 312 TOK_ALL, 313 TOK_MASK, 314 TOK_BW, 315 TOK_DELAY, 316 TOK_RED, 317 TOK_GRED, 318 TOK_DROPTAIL, 319 TOK_PROTO, 320 TOK_WEIGHT, 321 TOK_IP, 322 TOK_IF, 323 TOK_ALOG, 324 TOK_DENY_INC, 325 TOK_SAME_PORTS, 326 TOK_UNREG_ONLY, 327 TOK_RESET_ADDR, 328 TOK_ALIAS_REV, 329 TOK_PROXY_ONLY, 330 TOK_REDIR_ADDR, 331 TOK_REDIR_PORT, 332 TOK_REDIR_PROTO, 333 334 TOK_IPV6, 335 TOK_FLOWID, 336 TOK_ICMP6TYPES, 337 TOK_EXT6HDR, 338 TOK_DSTIP6, 339 TOK_SRCIP6, 340 341 TOK_IPV4, 342 TOK_UNREACH6, 343 TOK_RESET6, 344 345 TOK_FIB, 346 TOK_SETFIB, 347 }; 348 349 struct _s_x dummynet_params[] = { 350 { "plr", TOK_PLR }, 351 { "noerror", TOK_NOERROR }, 352 { "buckets", TOK_BUCKETS }, 353 { "dst-ip", TOK_DSTIP }, 354 { "src-ip", TOK_SRCIP }, 355 { "dst-port", TOK_DSTPORT }, 356 { "src-port", TOK_SRCPORT }, 357 { "proto", TOK_PROTO }, 358 { "weight", TOK_WEIGHT }, 359 { "all", TOK_ALL }, 360 { "mask", TOK_MASK }, 361 { "droptail", TOK_DROPTAIL }, 362 { "red", TOK_RED }, 363 { "gred", TOK_GRED }, 364 { "bw", TOK_BW }, 365 { "bandwidth", TOK_BW }, 366 { "delay", TOK_DELAY }, 367 { "pipe", TOK_PIPE }, 368 { "queue", TOK_QUEUE }, 369 { "flow-id", TOK_FLOWID}, 370 { "dst-ipv6", TOK_DSTIP6}, 371 { "dst-ip6", TOK_DSTIP6}, 372 { "src-ipv6", TOK_SRCIP6}, 373 { "src-ip6", TOK_SRCIP6}, 374 { "dummynet-params", TOK_NULL }, 375 { NULL, 0 } /* terminator */ 376 }; 377 378 struct _s_x nat_params[] = { 379 { "ip", TOK_IP }, 380 { "if", TOK_IF }, 381 { "log", TOK_ALOG }, 382 { "deny_in", TOK_DENY_INC }, 383 { "same_ports", TOK_SAME_PORTS }, 384 { "unreg_only", TOK_UNREG_ONLY }, 385 { "reset", TOK_RESET_ADDR }, 386 { "reverse", TOK_ALIAS_REV }, 387 { "proxy_only", TOK_PROXY_ONLY }, 388 { "redirect_addr", TOK_REDIR_ADDR }, 389 { "redirect_port", TOK_REDIR_PORT }, 390 { "redirect_proto", TOK_REDIR_PROTO }, 391 { NULL, 0 } /* terminator */ 392 }; 393 394 struct _s_x rule_actions[] = { 395 { "accept", TOK_ACCEPT }, 396 { "pass", TOK_ACCEPT }, 397 { "allow", TOK_ACCEPT }, 398 { "permit", TOK_ACCEPT }, 399 { "count", TOK_COUNT }, 400 { "pipe", TOK_PIPE }, 401 { "queue", TOK_QUEUE }, 402 { "divert", TOK_DIVERT }, 403 { "tee", TOK_TEE }, 404 { "netgraph", TOK_NETGRAPH }, 405 { "ngtee", TOK_NGTEE }, 406 { "fwd", TOK_FORWARD }, 407 { "forward", TOK_FORWARD }, 408 { "skipto", TOK_SKIPTO }, 409 { "deny", TOK_DENY }, 410 { "drop", TOK_DENY }, 411 { "reject", TOK_REJECT }, 412 { "reset6", TOK_RESET6 }, 413 { "reset", TOK_RESET }, 414 { "unreach6", TOK_UNREACH6 }, 415 { "unreach", TOK_UNREACH }, 416 { "check-state", TOK_CHECKSTATE }, 417 { "//", TOK_COMMENT }, 418 { "nat", TOK_NAT }, 419 { "setfib", TOK_SETFIB }, 420 { NULL, 0 } /* terminator */ 421 }; 422 423 struct _s_x rule_action_params[] = { 424 { "altq", TOK_ALTQ }, 425 { "log", TOK_LOG }, 426 { "tag", TOK_TAG }, 427 { "untag", TOK_UNTAG }, 428 { NULL, 0 } /* terminator */ 429 }; 430 431 struct _s_x rule_options[] = { 432 { "tagged", TOK_TAGGED }, 433 { "uid", TOK_UID }, 434 { "gid", TOK_GID }, 435 { "jail", TOK_JAIL }, 436 { "in", TOK_IN }, 437 { "limit", TOK_LIMIT }, 438 { "keep-state", TOK_KEEPSTATE }, 439 { "bridged", TOK_LAYER2 }, 440 { "layer2", TOK_LAYER2 }, 441 { "out", TOK_OUT }, 442 { "diverted", TOK_DIVERTED }, 443 { "diverted-loopback", TOK_DIVERTEDLOOPBACK }, 444 { "diverted-output", TOK_DIVERTEDOUTPUT }, 445 { "xmit", TOK_XMIT }, 446 { "recv", TOK_RECV }, 447 { "via", TOK_VIA }, 448 { "fragment", TOK_FRAG }, 449 { "frag", TOK_FRAG }, 450 { "fib", TOK_FIB }, 451 { "ipoptions", TOK_IPOPTS }, 452 { "ipopts", TOK_IPOPTS }, 453 { "iplen", TOK_IPLEN }, 454 { "ipid", TOK_IPID }, 455 { "ipprecedence", TOK_IPPRECEDENCE }, 456 { "iptos", TOK_IPTOS }, 457 { "ipttl", TOK_IPTTL }, 458 { "ipversion", TOK_IPVER }, 459 { "ipver", TOK_IPVER }, 460 { "estab", TOK_ESTAB }, 461 { "established", TOK_ESTAB }, 462 { "setup", TOK_SETUP }, 463 { "tcpdatalen", TOK_TCPDATALEN }, 464 { "tcpflags", TOK_TCPFLAGS }, 465 { "tcpflgs", TOK_TCPFLAGS }, 466 { "tcpoptions", TOK_TCPOPTS }, 467 { "tcpopts", TOK_TCPOPTS }, 468 { "tcpseq", TOK_TCPSEQ }, 469 { "tcpack", TOK_TCPACK }, 470 { "tcpwin", TOK_TCPWIN }, 471 { "icmptype", TOK_ICMPTYPES }, 472 { "icmptypes", TOK_ICMPTYPES }, 473 { "dst-ip", TOK_DSTIP }, 474 { "src-ip", TOK_SRCIP }, 475 { "dst-port", TOK_DSTPORT }, 476 { "src-port", TOK_SRCPORT }, 477 { "proto", TOK_PROTO }, 478 { "MAC", TOK_MAC }, 479 { "mac", TOK_MAC }, 480 { "mac-type", TOK_MACTYPE }, 481 { "verrevpath", TOK_VERREVPATH }, 482 { "versrcreach", TOK_VERSRCREACH }, 483 { "antispoof", TOK_ANTISPOOF }, 484 { "ipsec", TOK_IPSEC }, 485 { "icmp6type", TOK_ICMP6TYPES }, 486 { "icmp6types", TOK_ICMP6TYPES }, 487 { "ext6hdr", TOK_EXT6HDR}, 488 { "flow-id", TOK_FLOWID}, 489 { "ipv6", TOK_IPV6}, 490 { "ip6", TOK_IPV6}, 491 { "ipv4", TOK_IPV4}, 492 { "ip4", TOK_IPV4}, 493 { "dst-ipv6", TOK_DSTIP6}, 494 { "dst-ip6", TOK_DSTIP6}, 495 { "src-ipv6", TOK_SRCIP6}, 496 { "src-ip6", TOK_SRCIP6}, 497 { "//", TOK_COMMENT }, 498 499 { "not", TOK_NOT }, /* pseudo option */ 500 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */ 501 { "or", TOK_OR }, /* pseudo option */ 502 { "|", /* escape */ TOK_OR }, /* pseudo option */ 503 { "{", TOK_STARTBRACE }, /* pseudo option */ 504 { "(", TOK_STARTBRACE }, /* pseudo option */ 505 { "}", TOK_ENDBRACE }, /* pseudo option */ 506 { ")", TOK_ENDBRACE }, /* pseudo option */ 507 { NULL, 0 } /* terminator */ 508 }; 509 510 #define TABLEARG "tablearg" 511 512 static __inline uint64_t 513 align_uint64(uint64_t *pll) { 514 uint64_t ret; 515 516 bcopy (pll, &ret, sizeof(ret)); 517 return ret; 518 } 519 520 /* 521 * conditionally runs the command. 522 */ 523 static int 524 do_cmd(int optname, void *optval, uintptr_t optlen) 525 { 526 static int s = -1; /* the socket */ 527 int i; 528 529 if (test_only) 530 return 0; 531 532 if (s == -1) 533 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 534 if (s < 0) 535 err(EX_UNAVAILABLE, "socket"); 536 537 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET || 538 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST || 539 optname == IP_FW_TABLE_GETSIZE || 540 optname == IP_FW_NAT_GET_CONFIG || 541 optname == IP_FW_NAT_GET_LOG) 542 i = getsockopt(s, IPPROTO_IP, optname, optval, 543 (socklen_t *)optlen); 544 else 545 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen); 546 return i; 547 } 548 549 /** 550 * match_token takes a table and a string, returns the value associated 551 * with the string (-1 in case of failure). 552 */ 553 static int 554 match_token(struct _s_x *table, char *string) 555 { 556 struct _s_x *pt; 557 uint i = strlen(string); 558 559 for (pt = table ; i && pt->s != NULL ; pt++) 560 if (strlen(pt->s) == i && !bcmp(string, pt->s, i)) 561 return pt->x; 562 return -1; 563 } 564 565 /** 566 * match_value takes a table and a value, returns the string associated 567 * with the value (NULL in case of failure). 568 */ 569 static char const * 570 match_value(struct _s_x *p, int value) 571 { 572 for (; p->s != NULL; p++) 573 if (p->x == value) 574 return p->s; 575 return NULL; 576 } 577 578 /* 579 * _substrcmp takes two strings and returns 1 if they do not match, 580 * and 0 if they match exactly or the first string is a sub-string 581 * of the second. A warning is printed to stderr in the case that the 582 * first string is a sub-string of the second. 583 * 584 * This function will be removed in the future through the usual 585 * deprecation process. 586 */ 587 static int 588 _substrcmp(const char *str1, const char* str2) 589 { 590 591 if (strncmp(str1, str2, strlen(str1)) != 0) 592 return 1; 593 594 if (strlen(str1) != strlen(str2)) 595 warnx("DEPRECATED: '%s' matched '%s' as a sub-string", 596 str1, str2); 597 return 0; 598 } 599 600 /* 601 * _substrcmp2 takes three strings and returns 1 if the first two do not match, 602 * and 0 if they match exactly or the second string is a sub-string 603 * of the first. A warning is printed to stderr in the case that the 604 * first string does not match the third. 605 * 606 * This function exists to warn about the bizzare construction 607 * strncmp(str, "by", 2) which is used to allow people to use a shotcut 608 * for "bytes". The problem is that in addition to accepting "by", 609 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any 610 * other string beginning with "by". 611 * 612 * This function will be removed in the future through the usual 613 * deprecation process. 614 */ 615 static int 616 _substrcmp2(const char *str1, const char* str2, const char* str3) 617 { 618 619 if (strncmp(str1, str2, strlen(str2)) != 0) 620 return 1; 621 622 if (strcmp(str1, str3) != 0) 623 warnx("DEPRECATED: '%s' matched '%s'", 624 str1, str3); 625 return 0; 626 } 627 628 /* 629 * prints one port, symbolic or numeric 630 */ 631 static void 632 print_port(int proto, uint16_t port) 633 { 634 635 if (proto == IPPROTO_ETHERTYPE) { 636 char const *s; 637 638 if (do_resolv && (s = match_value(ether_types, port)) ) 639 printf("%s", s); 640 else 641 printf("0x%04x", port); 642 } else { 643 struct servent *se = NULL; 644 if (do_resolv) { 645 struct protoent *pe = getprotobynumber(proto); 646 647 se = getservbyport(htons(port), pe ? pe->p_name : NULL); 648 } 649 if (se) 650 printf("%s", se->s_name); 651 else 652 printf("%d", port); 653 } 654 } 655 656 struct _s_x _port_name[] = { 657 {"dst-port", O_IP_DSTPORT}, 658 {"src-port", O_IP_SRCPORT}, 659 {"ipid", O_IPID}, 660 {"iplen", O_IPLEN}, 661 {"ipttl", O_IPTTL}, 662 {"mac-type", O_MAC_TYPE}, 663 {"tcpdatalen", O_TCPDATALEN}, 664 {"tagged", O_TAGGED}, 665 {NULL, 0} 666 }; 667 668 /* 669 * Print the values in a list 16-bit items of the types above. 670 * XXX todo: add support for mask. 671 */ 672 static void 673 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode) 674 { 675 uint16_t *p = cmd->ports; 676 int i; 677 char const *sep; 678 679 if (opcode != 0) { 680 sep = match_value(_port_name, opcode); 681 if (sep == NULL) 682 sep = "???"; 683 printf (" %s", sep); 684 } 685 sep = " "; 686 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) { 687 printf(sep); 688 print_port(proto, p[0]); 689 if (p[0] != p[1]) { 690 printf("-"); 691 print_port(proto, p[1]); 692 } 693 sep = ","; 694 } 695 } 696 697 /* 698 * Like strtol, but also translates service names into port numbers 699 * for some protocols. 700 * In particular: 701 * proto == -1 disables the protocol check; 702 * proto == IPPROTO_ETHERTYPE looks up an internal table 703 * proto == <some value in /etc/protocols> matches the values there. 704 * Returns *end == s in case the parameter is not found. 705 */ 706 static int 707 strtoport(char *s, char **end, int base, int proto) 708 { 709 char *p, *buf; 710 char *s1; 711 int i; 712 713 *end = s; /* default - not found */ 714 if (*s == '\0') 715 return 0; /* not found */ 716 717 if (isdigit(*s)) 718 return strtol(s, end, base); 719 720 /* 721 * find separator. '\\' escapes the next char. 722 */ 723 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++) 724 if (*s1 == '\\' && s1[1] != '\0') 725 s1++; 726 727 buf = malloc(s1 - s + 1); 728 if (buf == NULL) 729 return 0; 730 731 /* 732 * copy into a buffer skipping backslashes 733 */ 734 for (p = s, i = 0; p != s1 ; p++) 735 if (*p != '\\') 736 buf[i++] = *p; 737 buf[i++] = '\0'; 738 739 if (proto == IPPROTO_ETHERTYPE) { 740 i = match_token(ether_types, buf); 741 free(buf); 742 if (i != -1) { /* found */ 743 *end = s1; 744 return i; 745 } 746 } else { 747 struct protoent *pe = NULL; 748 struct servent *se; 749 750 if (proto != 0) 751 pe = getprotobynumber(proto); 752 setservent(1); 753 se = getservbyname(buf, pe ? pe->p_name : NULL); 754 free(buf); 755 if (se != NULL) { 756 *end = s1; 757 return ntohs(se->s_port); 758 } 759 } 760 return 0; /* not found */ 761 } 762 763 /* 764 * Map between current altq queue id numbers and names. 765 */ 766 static int altq_fetched = 0; 767 static TAILQ_HEAD(, pf_altq) altq_entries = 768 TAILQ_HEAD_INITIALIZER(altq_entries); 769 770 static void 771 altq_set_enabled(int enabled) 772 { 773 int pffd; 774 775 pffd = open("/dev/pf", O_RDWR); 776 if (pffd == -1) 777 err(EX_UNAVAILABLE, 778 "altq support opening pf(4) control device"); 779 if (enabled) { 780 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST) 781 err(EX_UNAVAILABLE, "enabling altq"); 782 } else { 783 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT) 784 err(EX_UNAVAILABLE, "disabling altq"); 785 } 786 close(pffd); 787 } 788 789 static void 790 altq_fetch() 791 { 792 struct pfioc_altq pfioc; 793 struct pf_altq *altq; 794 int pffd, mnr; 795 796 if (altq_fetched) 797 return; 798 altq_fetched = 1; 799 pffd = open("/dev/pf", O_RDONLY); 800 if (pffd == -1) { 801 warn("altq support opening pf(4) control device"); 802 return; 803 } 804 bzero(&pfioc, sizeof(pfioc)); 805 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) { 806 warn("altq support getting queue list"); 807 close(pffd); 808 return; 809 } 810 mnr = pfioc.nr; 811 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) { 812 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) { 813 if (errno == EBUSY) 814 break; 815 warn("altq support getting queue list"); 816 close(pffd); 817 return; 818 } 819 if (pfioc.altq.qid == 0) 820 continue; 821 altq = malloc(sizeof(*altq)); 822 if (altq == NULL) 823 err(EX_OSERR, "malloc"); 824 *altq = pfioc.altq; 825 TAILQ_INSERT_TAIL(&altq_entries, altq, entries); 826 } 827 close(pffd); 828 } 829 830 static u_int32_t 831 altq_name_to_qid(const char *name) 832 { 833 struct pf_altq *altq; 834 835 altq_fetch(); 836 TAILQ_FOREACH(altq, &altq_entries, entries) 837 if (strcmp(name, altq->qname) == 0) 838 break; 839 if (altq == NULL) 840 errx(EX_DATAERR, "altq has no queue named `%s'", name); 841 return altq->qid; 842 } 843 844 static const char * 845 altq_qid_to_name(u_int32_t qid) 846 { 847 struct pf_altq *altq; 848 849 altq_fetch(); 850 TAILQ_FOREACH(altq, &altq_entries, entries) 851 if (qid == altq->qid) 852 break; 853 if (altq == NULL) 854 return NULL; 855 return altq->qname; 856 } 857 858 static void 859 fill_altq_qid(u_int32_t *qid, const char *av) 860 { 861 *qid = altq_name_to_qid(av); 862 } 863 864 /* 865 * Fill the body of the command with the list of port ranges. 866 */ 867 static int 868 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto) 869 { 870 uint16_t a, b, *p = cmd->ports; 871 int i = 0; 872 char *s = av; 873 874 while (*s) { 875 a = strtoport(av, &s, 0, proto); 876 if (s == av) /* empty or invalid argument */ 877 return (0); 878 879 switch (*s) { 880 case '-': /* a range */ 881 av = s + 1; 882 b = strtoport(av, &s, 0, proto); 883 /* Reject expressions like '1-abc' or '1-2-3'. */ 884 if (s == av || (*s != ',' && *s != '\0')) 885 return (0); 886 p[0] = a; 887 p[1] = b; 888 break; 889 case ',': /* comma separated list */ 890 case '\0': 891 p[0] = p[1] = a; 892 break; 893 default: 894 warnx("port list: invalid separator <%c> in <%s>", 895 *s, av); 896 return (0); 897 } 898 899 i++; 900 p += 2; 901 av = s + 1; 902 } 903 if (i > 0) { 904 if (i + 1 > F_LEN_MASK) 905 errx(EX_DATAERR, "too many ports/ranges\n"); 906 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */ 907 } 908 return (i); 909 } 910 911 static struct _s_x icmpcodes[] = { 912 { "net", ICMP_UNREACH_NET }, 913 { "host", ICMP_UNREACH_HOST }, 914 { "protocol", ICMP_UNREACH_PROTOCOL }, 915 { "port", ICMP_UNREACH_PORT }, 916 { "needfrag", ICMP_UNREACH_NEEDFRAG }, 917 { "srcfail", ICMP_UNREACH_SRCFAIL }, 918 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN }, 919 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN }, 920 { "isolated", ICMP_UNREACH_ISOLATED }, 921 { "net-prohib", ICMP_UNREACH_NET_PROHIB }, 922 { "host-prohib", ICMP_UNREACH_HOST_PROHIB }, 923 { "tosnet", ICMP_UNREACH_TOSNET }, 924 { "toshost", ICMP_UNREACH_TOSHOST }, 925 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB }, 926 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE }, 927 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF }, 928 { NULL, 0 } 929 }; 930 931 static void 932 fill_reject_code(u_short *codep, char *str) 933 { 934 int val; 935 char *s; 936 937 val = strtoul(str, &s, 0); 938 if (s == str || *s != '\0' || val >= 0x100) 939 val = match_token(icmpcodes, str); 940 if (val < 0) 941 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str); 942 *codep = val; 943 return; 944 } 945 946 static void 947 print_reject_code(uint16_t code) 948 { 949 char const *s = match_value(icmpcodes, code); 950 951 if (s != NULL) 952 printf("unreach %s", s); 953 else 954 printf("unreach %u", code); 955 } 956 957 static struct _s_x icmp6codes[] = { 958 { "no-route", ICMP6_DST_UNREACH_NOROUTE }, 959 { "admin-prohib", ICMP6_DST_UNREACH_ADMIN }, 960 { "address", ICMP6_DST_UNREACH_ADDR }, 961 { "port", ICMP6_DST_UNREACH_NOPORT }, 962 { NULL, 0 } 963 }; 964 965 static void 966 fill_unreach6_code(u_short *codep, char *str) 967 { 968 int val; 969 char *s; 970 971 val = strtoul(str, &s, 0); 972 if (s == str || *s != '\0' || val >= 0x100) 973 val = match_token(icmp6codes, str); 974 if (val < 0) 975 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str); 976 *codep = val; 977 return; 978 } 979 980 static void 981 print_unreach6_code(uint16_t code) 982 { 983 char const *s = match_value(icmp6codes, code); 984 985 if (s != NULL) 986 printf("unreach6 %s", s); 987 else 988 printf("unreach6 %u", code); 989 } 990 991 /* 992 * Returns the number of bits set (from left) in a contiguous bitmask, 993 * or -1 if the mask is not contiguous. 994 * XXX this needs a proper fix. 995 * This effectively works on masks in big-endian (network) format. 996 * when compiled on little endian architectures. 997 * 998 * First bit is bit 7 of the first byte -- note, for MAC addresses, 999 * the first bit on the wire is bit 0 of the first byte. 1000 * len is the max length in bits. 1001 */ 1002 static int 1003 contigmask(uint8_t *p, int len) 1004 { 1005 int i, n; 1006 1007 for (i=0; i<len ; i++) 1008 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */ 1009 break; 1010 for (n=i+1; n < len; n++) 1011 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0) 1012 return -1; /* mask not contiguous */ 1013 return i; 1014 } 1015 1016 /* 1017 * print flags set/clear in the two bitmasks passed as parameters. 1018 * There is a specialized check for f_tcpflags. 1019 */ 1020 static void 1021 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list) 1022 { 1023 char const *comma = ""; 1024 int i; 1025 uint8_t set = cmd->arg1 & 0xff; 1026 uint8_t clear = (cmd->arg1 >> 8) & 0xff; 1027 1028 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) { 1029 printf(" setup"); 1030 return; 1031 } 1032 1033 printf(" %s ", name); 1034 for (i=0; list[i].x != 0; i++) { 1035 if (set & list[i].x) { 1036 set &= ~list[i].x; 1037 printf("%s%s", comma, list[i].s); 1038 comma = ","; 1039 } 1040 if (clear & list[i].x) { 1041 clear &= ~list[i].x; 1042 printf("%s!%s", comma, list[i].s); 1043 comma = ","; 1044 } 1045 } 1046 } 1047 1048 /* 1049 * Print the ip address contained in a command. 1050 */ 1051 static void 1052 print_ip(ipfw_insn_ip *cmd, char const *s) 1053 { 1054 struct hostent *he = NULL; 1055 int len = F_LEN((ipfw_insn *)cmd); 1056 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d; 1057 1058 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 1059 1060 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) { 1061 printf("me"); 1062 return; 1063 } 1064 if (cmd->o.opcode == O_IP_SRC_LOOKUP || 1065 cmd->o.opcode == O_IP_DST_LOOKUP) { 1066 printf("table(%u", ((ipfw_insn *)cmd)->arg1); 1067 if (len == F_INSN_SIZE(ipfw_insn_u32)) 1068 printf(",%u", *a); 1069 printf(")"); 1070 return; 1071 } 1072 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) { 1073 uint32_t x, *map = (uint32_t *)&(cmd->mask); 1074 int i, j; 1075 char comma = '{'; 1076 1077 x = cmd->o.arg1 - 1; 1078 x = htonl( ~x ); 1079 cmd->addr.s_addr = htonl(cmd->addr.s_addr); 1080 printf("%s/%d", inet_ntoa(cmd->addr), 1081 contigmask((uint8_t *)&x, 32)); 1082 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr); 1083 x &= 0xff; /* base */ 1084 /* 1085 * Print bits and ranges. 1086 * Locate first bit set (i), then locate first bit unset (j). 1087 * If we have 3+ consecutive bits set, then print them as a 1088 * range, otherwise only print the initial bit and rescan. 1089 */ 1090 for (i=0; i < cmd->o.arg1; i++) 1091 if (map[i/32] & (1<<(i & 31))) { 1092 for (j=i+1; j < cmd->o.arg1; j++) 1093 if (!(map[ j/32] & (1<<(j & 31)))) 1094 break; 1095 printf("%c%d", comma, i+x); 1096 if (j>i+2) { /* range has at least 3 elements */ 1097 printf("-%d", j-1+x); 1098 i = j-1; 1099 } 1100 comma = ','; 1101 } 1102 printf("}"); 1103 return; 1104 } 1105 /* 1106 * len == 2 indicates a single IP, whereas lists of 1 or more 1107 * addr/mask pairs have len = (2n+1). We convert len to n so we 1108 * use that to count the number of entries. 1109 */ 1110 for (len = len / 2; len > 0; len--, a += 2) { 1111 int mb = /* mask length */ 1112 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ? 1113 32 : contigmask((uint8_t *)&(a[1]), 32); 1114 if (mb == 32 && do_resolv) 1115 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET); 1116 if (he != NULL) /* resolved to name */ 1117 printf("%s", he->h_name); 1118 else if (mb == 0) /* any */ 1119 printf("any"); 1120 else { /* numeric IP followed by some kind of mask */ 1121 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) ); 1122 if (mb < 0) 1123 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) ); 1124 else if (mb < 32) 1125 printf("/%d", mb); 1126 } 1127 if (len > 1) 1128 printf(","); 1129 } 1130 } 1131 1132 /* 1133 * prints a MAC address/mask pair 1134 */ 1135 static void 1136 print_mac(uint8_t *addr, uint8_t *mask) 1137 { 1138 int l = contigmask(mask, 48); 1139 1140 if (l == 0) 1141 printf(" any"); 1142 else { 1143 printf(" %02x:%02x:%02x:%02x:%02x:%02x", 1144 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); 1145 if (l == -1) 1146 printf("&%02x:%02x:%02x:%02x:%02x:%02x", 1147 mask[0], mask[1], mask[2], 1148 mask[3], mask[4], mask[5]); 1149 else if (l < 48) 1150 printf("/%d", l); 1151 } 1152 } 1153 1154 static void 1155 fill_icmptypes(ipfw_insn_u32 *cmd, char *av) 1156 { 1157 uint8_t type; 1158 1159 cmd->d[0] = 0; 1160 while (*av) { 1161 if (*av == ',') 1162 av++; 1163 1164 type = strtoul(av, &av, 0); 1165 1166 if (*av != ',' && *av != '\0') 1167 errx(EX_DATAERR, "invalid ICMP type"); 1168 1169 if (type > 31) 1170 errx(EX_DATAERR, "ICMP type out of range"); 1171 1172 cmd->d[0] |= 1 << type; 1173 } 1174 cmd->o.opcode = O_ICMPTYPE; 1175 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 1176 } 1177 1178 static void 1179 print_icmptypes(ipfw_insn_u32 *cmd) 1180 { 1181 int i; 1182 char sep= ' '; 1183 1184 printf(" icmptypes"); 1185 for (i = 0; i < 32; i++) { 1186 if ( (cmd->d[0] & (1 << (i))) == 0) 1187 continue; 1188 printf("%c%d", sep, i); 1189 sep = ','; 1190 } 1191 } 1192 1193 /* 1194 * Print the ip address contained in a command. 1195 */ 1196 static void 1197 print_ip6(ipfw_insn_ip6 *cmd, char const *s) 1198 { 1199 struct hostent *he = NULL; 1200 int len = F_LEN((ipfw_insn *) cmd) - 1; 1201 struct in6_addr *a = &(cmd->addr6); 1202 char trad[255]; 1203 1204 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 1205 1206 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) { 1207 printf("me6"); 1208 return; 1209 } 1210 if (cmd->o.opcode == O_IP6) { 1211 printf(" ip6"); 1212 return; 1213 } 1214 1215 /* 1216 * len == 4 indicates a single IP, whereas lists of 1 or more 1217 * addr/mask pairs have len = (2n+1). We convert len to n so we 1218 * use that to count the number of entries. 1219 */ 1220 1221 for (len = len / 4; len > 0; len -= 2, a += 2) { 1222 int mb = /* mask length */ 1223 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ? 1224 128 : contigmask((uint8_t *)&(a[1]), 128); 1225 1226 if (mb == 128 && do_resolv) 1227 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6); 1228 if (he != NULL) /* resolved to name */ 1229 printf("%s", he->h_name); 1230 else if (mb == 0) /* any */ 1231 printf("any"); 1232 else { /* numeric IP followed by some kind of mask */ 1233 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL) 1234 printf("Error ntop in print_ip6\n"); 1235 printf("%s", trad ); 1236 if (mb < 0) /* XXX not really legal... */ 1237 printf(":%s", 1238 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad))); 1239 else if (mb < 128) 1240 printf("/%d", mb); 1241 } 1242 if (len > 2) 1243 printf(","); 1244 } 1245 } 1246 1247 static void 1248 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av) 1249 { 1250 uint8_t type; 1251 1252 bzero(cmd, sizeof(*cmd)); 1253 while (*av) { 1254 if (*av == ',') 1255 av++; 1256 type = strtoul(av, &av, 0); 1257 if (*av != ',' && *av != '\0') 1258 errx(EX_DATAERR, "invalid ICMP6 type"); 1259 /* 1260 * XXX: shouldn't this be 0xFF? I can't see any reason why 1261 * we shouldn't be able to filter all possiable values 1262 * regardless of the ability of the rest of the kernel to do 1263 * anything useful with them. 1264 */ 1265 if (type > ICMP6_MAXTYPE) 1266 errx(EX_DATAERR, "ICMP6 type out of range"); 1267 cmd->d[type / 32] |= ( 1 << (type % 32)); 1268 } 1269 cmd->o.opcode = O_ICMP6TYPE; 1270 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6); 1271 } 1272 1273 1274 static void 1275 print_icmp6types(ipfw_insn_u32 *cmd) 1276 { 1277 int i, j; 1278 char sep= ' '; 1279 1280 printf(" ip6 icmp6types"); 1281 for (i = 0; i < 7; i++) 1282 for (j=0; j < 32; ++j) { 1283 if ( (cmd->d[i] & (1 << (j))) == 0) 1284 continue; 1285 printf("%c%d", sep, (i*32 + j)); 1286 sep = ','; 1287 } 1288 } 1289 1290 static void 1291 print_flow6id( ipfw_insn_u32 *cmd) 1292 { 1293 uint16_t i, limit = cmd->o.arg1; 1294 char sep = ','; 1295 1296 printf(" flow-id "); 1297 for( i=0; i < limit; ++i) { 1298 if (i == limit - 1) 1299 sep = ' '; 1300 printf("%d%c", cmd->d[i], sep); 1301 } 1302 } 1303 1304 /* structure and define for the extension header in ipv6 */ 1305 static struct _s_x ext6hdrcodes[] = { 1306 { "frag", EXT_FRAGMENT }, 1307 { "hopopt", EXT_HOPOPTS }, 1308 { "route", EXT_ROUTING }, 1309 { "dstopt", EXT_DSTOPTS }, 1310 { "ah", EXT_AH }, 1311 { "esp", EXT_ESP }, 1312 { "rthdr0", EXT_RTHDR0 }, 1313 { "rthdr2", EXT_RTHDR2 }, 1314 { NULL, 0 } 1315 }; 1316 1317 /* fills command for the extension header filtering */ 1318 int 1319 fill_ext6hdr( ipfw_insn *cmd, char *av) 1320 { 1321 int tok; 1322 char *s = av; 1323 1324 cmd->arg1 = 0; 1325 1326 while(s) { 1327 av = strsep( &s, ",") ; 1328 tok = match_token(ext6hdrcodes, av); 1329 switch (tok) { 1330 case EXT_FRAGMENT: 1331 cmd->arg1 |= EXT_FRAGMENT; 1332 break; 1333 1334 case EXT_HOPOPTS: 1335 cmd->arg1 |= EXT_HOPOPTS; 1336 break; 1337 1338 case EXT_ROUTING: 1339 cmd->arg1 |= EXT_ROUTING; 1340 break; 1341 1342 case EXT_DSTOPTS: 1343 cmd->arg1 |= EXT_DSTOPTS; 1344 break; 1345 1346 case EXT_AH: 1347 cmd->arg1 |= EXT_AH; 1348 break; 1349 1350 case EXT_ESP: 1351 cmd->arg1 |= EXT_ESP; 1352 break; 1353 1354 case EXT_RTHDR0: 1355 cmd->arg1 |= EXT_RTHDR0; 1356 break; 1357 1358 case EXT_RTHDR2: 1359 cmd->arg1 |= EXT_RTHDR2; 1360 break; 1361 1362 default: 1363 errx( EX_DATAERR, "invalid option for ipv6 exten header" ); 1364 break; 1365 } 1366 } 1367 if (cmd->arg1 == 0 ) 1368 return 0; 1369 cmd->opcode = O_EXT_HDR; 1370 cmd->len |= F_INSN_SIZE( ipfw_insn ); 1371 return 1; 1372 } 1373 1374 void 1375 print_ext6hdr( ipfw_insn *cmd ) 1376 { 1377 char sep = ' '; 1378 1379 printf(" extension header:"); 1380 if (cmd->arg1 & EXT_FRAGMENT ) { 1381 printf("%cfragmentation", sep); 1382 sep = ','; 1383 } 1384 if (cmd->arg1 & EXT_HOPOPTS ) { 1385 printf("%chop options", sep); 1386 sep = ','; 1387 } 1388 if (cmd->arg1 & EXT_ROUTING ) { 1389 printf("%crouting options", sep); 1390 sep = ','; 1391 } 1392 if (cmd->arg1 & EXT_RTHDR0 ) { 1393 printf("%crthdr0", sep); 1394 sep = ','; 1395 } 1396 if (cmd->arg1 & EXT_RTHDR2 ) { 1397 printf("%crthdr2", sep); 1398 sep = ','; 1399 } 1400 if (cmd->arg1 & EXT_DSTOPTS ) { 1401 printf("%cdestination options", sep); 1402 sep = ','; 1403 } 1404 if (cmd->arg1 & EXT_AH ) { 1405 printf("%cauthentication header", sep); 1406 sep = ','; 1407 } 1408 if (cmd->arg1 & EXT_ESP ) { 1409 printf("%cencapsulated security payload", sep); 1410 } 1411 } 1412 1413 /* 1414 * show_ipfw() prints the body of an ipfw rule. 1415 * Because the standard rule has at least proto src_ip dst_ip, we use 1416 * a helper function to produce these entries if not provided explicitly. 1417 * The first argument is the list of fields we have, the second is 1418 * the list of fields we want to be printed. 1419 * 1420 * Special cases if we have provided a MAC header: 1421 * + if the rule does not contain IP addresses/ports, do not print them; 1422 * + if the rule does not contain an IP proto, print "all" instead of "ip"; 1423 * 1424 * Once we have 'have_options', IP header fields are printed as options. 1425 */ 1426 #define HAVE_PROTO 0x0001 1427 #define HAVE_SRCIP 0x0002 1428 #define HAVE_DSTIP 0x0004 1429 #define HAVE_PROTO4 0x0008 1430 #define HAVE_PROTO6 0x0010 1431 #define HAVE_OPTIONS 0x8000 1432 1433 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP) 1434 static void 1435 show_prerequisites(int *flags, int want, int cmd) 1436 { 1437 if (comment_only) 1438 return; 1439 if ( (*flags & HAVE_IP) == HAVE_IP) 1440 *flags |= HAVE_OPTIONS; 1441 1442 if ( !(*flags & HAVE_OPTIONS)) { 1443 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) 1444 if ( (*flags & HAVE_PROTO4)) 1445 printf(" ip4"); 1446 else if ( (*flags & HAVE_PROTO6)) 1447 printf(" ip6"); 1448 else 1449 printf(" ip"); 1450 1451 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP)) 1452 printf(" from any"); 1453 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP)) 1454 printf(" to any"); 1455 } 1456 *flags |= want; 1457 } 1458 1459 static void 1460 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth) 1461 { 1462 static int twidth = 0; 1463 int l; 1464 ipfw_insn *cmd, *tagptr = NULL; 1465 char *comment = NULL; /* ptr to comment if we have one */ 1466 int proto = 0; /* default */ 1467 int flags = 0; /* prerequisites */ 1468 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */ 1469 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */ 1470 int or_block = 0; /* we are in an or block */ 1471 uint32_t set_disable; 1472 1473 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable)); 1474 1475 if (set_disable & (1 << rule->set)) { /* disabled */ 1476 if (!show_sets) 1477 return; 1478 else 1479 printf("# DISABLED "); 1480 } 1481 printf("%05u ", rule->rulenum); 1482 1483 if (pcwidth>0 || bcwidth>0) 1484 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt), 1485 bcwidth, align_uint64(&rule->bcnt)); 1486 1487 if (do_time == 2) 1488 printf("%10u ", rule->timestamp); 1489 else if (do_time == 1) { 1490 char timestr[30]; 1491 time_t t = (time_t)0; 1492 1493 if (twidth == 0) { 1494 strcpy(timestr, ctime(&t)); 1495 *strchr(timestr, '\n') = '\0'; 1496 twidth = strlen(timestr); 1497 } 1498 if (rule->timestamp) { 1499 t = _long_to_time(rule->timestamp); 1500 1501 strcpy(timestr, ctime(&t)); 1502 *strchr(timestr, '\n') = '\0'; 1503 printf("%s ", timestr); 1504 } else { 1505 printf("%*s", twidth, " "); 1506 } 1507 } 1508 1509 if (show_sets) 1510 printf("set %d ", rule->set); 1511 1512 /* 1513 * print the optional "match probability" 1514 */ 1515 if (rule->cmd_len > 0) { 1516 cmd = rule->cmd ; 1517 if (cmd->opcode == O_PROB) { 1518 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd; 1519 double d = 1.0 * p->d[0]; 1520 1521 d = (d / 0x7fffffff); 1522 printf("prob %f ", d); 1523 } 1524 } 1525 1526 /* 1527 * first print actions 1528 */ 1529 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule); 1530 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) { 1531 switch(cmd->opcode) { 1532 case O_CHECK_STATE: 1533 printf("check-state"); 1534 flags = HAVE_IP; /* avoid printing anything else */ 1535 break; 1536 1537 case O_ACCEPT: 1538 printf("allow"); 1539 break; 1540 1541 case O_COUNT: 1542 printf("count"); 1543 break; 1544 1545 case O_DENY: 1546 printf("deny"); 1547 break; 1548 1549 case O_REJECT: 1550 if (cmd->arg1 == ICMP_REJECT_RST) 1551 printf("reset"); 1552 else if (cmd->arg1 == ICMP_UNREACH_HOST) 1553 printf("reject"); 1554 else 1555 print_reject_code(cmd->arg1); 1556 break; 1557 1558 case O_UNREACH6: 1559 if (cmd->arg1 == ICMP6_UNREACH_RST) 1560 printf("reset6"); 1561 else 1562 print_unreach6_code(cmd->arg1); 1563 break; 1564 1565 case O_SKIPTO: 1566 PRINT_UINT_ARG("skipto ", cmd->arg1); 1567 break; 1568 1569 case O_PIPE: 1570 PRINT_UINT_ARG("pipe ", cmd->arg1); 1571 break; 1572 1573 case O_QUEUE: 1574 PRINT_UINT_ARG("queue ", cmd->arg1); 1575 break; 1576 1577 case O_DIVERT: 1578 PRINT_UINT_ARG("divert ", cmd->arg1); 1579 break; 1580 1581 case O_TEE: 1582 PRINT_UINT_ARG("tee ", cmd->arg1); 1583 break; 1584 1585 case O_NETGRAPH: 1586 PRINT_UINT_ARG("netgraph ", cmd->arg1); 1587 break; 1588 1589 case O_NGTEE: 1590 PRINT_UINT_ARG("ngtee ", cmd->arg1); 1591 break; 1592 1593 case O_FORWARD_IP: 1594 { 1595 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd; 1596 1597 if (s->sa.sin_addr.s_addr == INADDR_ANY) { 1598 printf("fwd tablearg"); 1599 } else { 1600 printf("fwd %s", inet_ntoa(s->sa.sin_addr)); 1601 } 1602 if (s->sa.sin_port) 1603 printf(",%d", s->sa.sin_port); 1604 } 1605 break; 1606 1607 case O_LOG: /* O_LOG is printed last */ 1608 logptr = (ipfw_insn_log *)cmd; 1609 break; 1610 1611 case O_ALTQ: /* O_ALTQ is printed after O_LOG */ 1612 altqptr = (ipfw_insn_altq *)cmd; 1613 break; 1614 1615 case O_TAG: 1616 tagptr = cmd; 1617 break; 1618 1619 case O_NAT: 1620 PRINT_UINT_ARG("nat ", cmd->arg1); 1621 break; 1622 1623 case O_SETFIB: 1624 PRINT_UINT_ARG("setfib ", cmd->arg1); 1625 break; 1626 1627 default: 1628 printf("** unrecognized action %d len %d ", 1629 cmd->opcode, cmd->len); 1630 } 1631 } 1632 if (logptr) { 1633 if (logptr->max_log > 0) 1634 printf(" log logamount %d", logptr->max_log); 1635 else 1636 printf(" log"); 1637 } 1638 if (altqptr) { 1639 const char *qname; 1640 1641 qname = altq_qid_to_name(altqptr->qid); 1642 if (qname == NULL) 1643 printf(" altq ?<%u>", altqptr->qid); 1644 else 1645 printf(" altq %s", qname); 1646 } 1647 if (tagptr) { 1648 if (tagptr->len & F_NOT) 1649 PRINT_UINT_ARG(" untag ", tagptr->arg1); 1650 else 1651 PRINT_UINT_ARG(" tag ", tagptr->arg1); 1652 } 1653 1654 /* 1655 * then print the body. 1656 */ 1657 for (l = rule->act_ofs, cmd = rule->cmd ; 1658 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1659 if ((cmd->len & F_OR) || (cmd->len & F_NOT)) 1660 continue; 1661 if (cmd->opcode == O_IP4) { 1662 flags |= HAVE_PROTO4; 1663 break; 1664 } else if (cmd->opcode == O_IP6) { 1665 flags |= HAVE_PROTO6; 1666 break; 1667 } 1668 } 1669 if (rule->_pad & 1) { /* empty rules before options */ 1670 if (!do_compact) { 1671 show_prerequisites(&flags, HAVE_PROTO, 0); 1672 printf(" from any to any"); 1673 } 1674 flags |= HAVE_IP | HAVE_OPTIONS; 1675 } 1676 1677 if (comment_only) 1678 comment = "..."; 1679 1680 for (l = rule->act_ofs, cmd = rule->cmd ; 1681 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1682 /* useful alias */ 1683 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; 1684 1685 if (comment_only) { 1686 if (cmd->opcode != O_NOP) 1687 continue; 1688 printf(" // %s\n", (char *)(cmd + 1)); 1689 return; 1690 } 1691 1692 show_prerequisites(&flags, 0, cmd->opcode); 1693 1694 switch(cmd->opcode) { 1695 case O_PROB: 1696 break; /* done already */ 1697 1698 case O_PROBE_STATE: 1699 break; /* no need to print anything here */ 1700 1701 case O_IP_SRC: 1702 case O_IP_SRC_LOOKUP: 1703 case O_IP_SRC_MASK: 1704 case O_IP_SRC_ME: 1705 case O_IP_SRC_SET: 1706 show_prerequisites(&flags, HAVE_PROTO, 0); 1707 if (!(flags & HAVE_SRCIP)) 1708 printf(" from"); 1709 if ((cmd->len & F_OR) && !or_block) 1710 printf(" {"); 1711 print_ip((ipfw_insn_ip *)cmd, 1712 (flags & HAVE_OPTIONS) ? " src-ip" : ""); 1713 flags |= HAVE_SRCIP; 1714 break; 1715 1716 case O_IP_DST: 1717 case O_IP_DST_LOOKUP: 1718 case O_IP_DST_MASK: 1719 case O_IP_DST_ME: 1720 case O_IP_DST_SET: 1721 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1722 if (!(flags & HAVE_DSTIP)) 1723 printf(" to"); 1724 if ((cmd->len & F_OR) && !or_block) 1725 printf(" {"); 1726 print_ip((ipfw_insn_ip *)cmd, 1727 (flags & HAVE_OPTIONS) ? " dst-ip" : ""); 1728 flags |= HAVE_DSTIP; 1729 break; 1730 1731 case O_IP6_SRC: 1732 case O_IP6_SRC_MASK: 1733 case O_IP6_SRC_ME: 1734 show_prerequisites(&flags, HAVE_PROTO, 0); 1735 if (!(flags & HAVE_SRCIP)) 1736 printf(" from"); 1737 if ((cmd->len & F_OR) && !or_block) 1738 printf(" {"); 1739 print_ip6((ipfw_insn_ip6 *)cmd, 1740 (flags & HAVE_OPTIONS) ? " src-ip6" : ""); 1741 flags |= HAVE_SRCIP | HAVE_PROTO; 1742 break; 1743 1744 case O_IP6_DST: 1745 case O_IP6_DST_MASK: 1746 case O_IP6_DST_ME: 1747 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1748 if (!(flags & HAVE_DSTIP)) 1749 printf(" to"); 1750 if ((cmd->len & F_OR) && !or_block) 1751 printf(" {"); 1752 print_ip6((ipfw_insn_ip6 *)cmd, 1753 (flags & HAVE_OPTIONS) ? " dst-ip6" : ""); 1754 flags |= HAVE_DSTIP; 1755 break; 1756 1757 case O_FLOW6ID: 1758 print_flow6id( (ipfw_insn_u32 *) cmd ); 1759 flags |= HAVE_OPTIONS; 1760 break; 1761 1762 case O_IP_DSTPORT: 1763 show_prerequisites(&flags, HAVE_IP, 0); 1764 case O_IP_SRCPORT: 1765 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1766 if ((cmd->len & F_OR) && !or_block) 1767 printf(" {"); 1768 if (cmd->len & F_NOT) 1769 printf(" not"); 1770 print_newports((ipfw_insn_u16 *)cmd, proto, 1771 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1772 break; 1773 1774 case O_PROTO: { 1775 struct protoent *pe = NULL; 1776 1777 if ((cmd->len & F_OR) && !or_block) 1778 printf(" {"); 1779 if (cmd->len & F_NOT) 1780 printf(" not"); 1781 proto = cmd->arg1; 1782 pe = getprotobynumber(cmd->arg1); 1783 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) && 1784 !(flags & HAVE_PROTO)) 1785 show_prerequisites(&flags, 1786 HAVE_IP | HAVE_OPTIONS, 0); 1787 if (flags & HAVE_OPTIONS) 1788 printf(" proto"); 1789 if (pe) 1790 printf(" %s", pe->p_name); 1791 else 1792 printf(" %u", cmd->arg1); 1793 } 1794 flags |= HAVE_PROTO; 1795 break; 1796 1797 default: /*options ... */ 1798 if (!(cmd->len & (F_OR|F_NOT))) 1799 if (((cmd->opcode == O_IP6) && 1800 (flags & HAVE_PROTO6)) || 1801 ((cmd->opcode == O_IP4) && 1802 (flags & HAVE_PROTO4))) 1803 break; 1804 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0); 1805 if ((cmd->len & F_OR) && !or_block) 1806 printf(" {"); 1807 if (cmd->len & F_NOT && cmd->opcode != O_IN) 1808 printf(" not"); 1809 switch(cmd->opcode) { 1810 case O_MACADDR2: { 1811 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd; 1812 1813 printf(" MAC"); 1814 print_mac(m->addr, m->mask); 1815 print_mac(m->addr + 6, m->mask + 6); 1816 } 1817 break; 1818 1819 case O_MAC_TYPE: 1820 print_newports((ipfw_insn_u16 *)cmd, 1821 IPPROTO_ETHERTYPE, cmd->opcode); 1822 break; 1823 1824 1825 case O_FRAG: 1826 printf(" frag"); 1827 break; 1828 1829 case O_FIB: 1830 printf(" fib %u", cmd->arg1 ); 1831 break; 1832 1833 case O_IN: 1834 printf(cmd->len & F_NOT ? " out" : " in"); 1835 break; 1836 1837 case O_DIVERTED: 1838 switch (cmd->arg1) { 1839 case 3: 1840 printf(" diverted"); 1841 break; 1842 case 1: 1843 printf(" diverted-loopback"); 1844 break; 1845 case 2: 1846 printf(" diverted-output"); 1847 break; 1848 default: 1849 printf(" diverted-?<%u>", cmd->arg1); 1850 break; 1851 } 1852 break; 1853 1854 case O_LAYER2: 1855 printf(" layer2"); 1856 break; 1857 case O_XMIT: 1858 case O_RECV: 1859 case O_VIA: 1860 { 1861 char const *s; 1862 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd; 1863 1864 if (cmd->opcode == O_XMIT) 1865 s = "xmit"; 1866 else if (cmd->opcode == O_RECV) 1867 s = "recv"; 1868 else /* if (cmd->opcode == O_VIA) */ 1869 s = "via"; 1870 if (cmdif->name[0] == '\0') 1871 printf(" %s %s", s, 1872 inet_ntoa(cmdif->p.ip)); 1873 else 1874 printf(" %s %s", s, cmdif->name); 1875 1876 break; 1877 } 1878 case O_IPID: 1879 if (F_LEN(cmd) == 1) 1880 printf(" ipid %u", cmd->arg1 ); 1881 else 1882 print_newports((ipfw_insn_u16 *)cmd, 0, 1883 O_IPID); 1884 break; 1885 1886 case O_IPTTL: 1887 if (F_LEN(cmd) == 1) 1888 printf(" ipttl %u", cmd->arg1 ); 1889 else 1890 print_newports((ipfw_insn_u16 *)cmd, 0, 1891 O_IPTTL); 1892 break; 1893 1894 case O_IPVER: 1895 printf(" ipver %u", cmd->arg1 ); 1896 break; 1897 1898 case O_IPPRECEDENCE: 1899 printf(" ipprecedence %u", (cmd->arg1) >> 5 ); 1900 break; 1901 1902 case O_IPLEN: 1903 if (F_LEN(cmd) == 1) 1904 printf(" iplen %u", cmd->arg1 ); 1905 else 1906 print_newports((ipfw_insn_u16 *)cmd, 0, 1907 O_IPLEN); 1908 break; 1909 1910 case O_IPOPT: 1911 print_flags("ipoptions", cmd, f_ipopts); 1912 break; 1913 1914 case O_IPTOS: 1915 print_flags("iptos", cmd, f_iptos); 1916 break; 1917 1918 case O_ICMPTYPE: 1919 print_icmptypes((ipfw_insn_u32 *)cmd); 1920 break; 1921 1922 case O_ESTAB: 1923 printf(" established"); 1924 break; 1925 1926 case O_TCPDATALEN: 1927 if (F_LEN(cmd) == 1) 1928 printf(" tcpdatalen %u", cmd->arg1 ); 1929 else 1930 print_newports((ipfw_insn_u16 *)cmd, 0, 1931 O_TCPDATALEN); 1932 break; 1933 1934 case O_TCPFLAGS: 1935 print_flags("tcpflags", cmd, f_tcpflags); 1936 break; 1937 1938 case O_TCPOPTS: 1939 print_flags("tcpoptions", cmd, f_tcpopts); 1940 break; 1941 1942 case O_TCPWIN: 1943 printf(" tcpwin %d", ntohs(cmd->arg1)); 1944 break; 1945 1946 case O_TCPACK: 1947 printf(" tcpack %d", ntohl(cmd32->d[0])); 1948 break; 1949 1950 case O_TCPSEQ: 1951 printf(" tcpseq %d", ntohl(cmd32->d[0])); 1952 break; 1953 1954 case O_UID: 1955 { 1956 struct passwd *pwd = getpwuid(cmd32->d[0]); 1957 1958 if (pwd) 1959 printf(" uid %s", pwd->pw_name); 1960 else 1961 printf(" uid %u", cmd32->d[0]); 1962 } 1963 break; 1964 1965 case O_GID: 1966 { 1967 struct group *grp = getgrgid(cmd32->d[0]); 1968 1969 if (grp) 1970 printf(" gid %s", grp->gr_name); 1971 else 1972 printf(" gid %u", cmd32->d[0]); 1973 } 1974 break; 1975 1976 case O_JAIL: 1977 printf(" jail %d", cmd32->d[0]); 1978 break; 1979 1980 case O_VERREVPATH: 1981 printf(" verrevpath"); 1982 break; 1983 1984 case O_VERSRCREACH: 1985 printf(" versrcreach"); 1986 break; 1987 1988 case O_ANTISPOOF: 1989 printf(" antispoof"); 1990 break; 1991 1992 case O_IPSEC: 1993 printf(" ipsec"); 1994 break; 1995 1996 case O_NOP: 1997 comment = (char *)(cmd + 1); 1998 break; 1999 2000 case O_KEEP_STATE: 2001 printf(" keep-state"); 2002 break; 2003 2004 case O_LIMIT: { 2005 struct _s_x *p = limit_masks; 2006 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 2007 uint8_t x = c->limit_mask; 2008 char const *comma = " "; 2009 2010 printf(" limit"); 2011 for (; p->x != 0 ; p++) 2012 if ((x & p->x) == p->x) { 2013 x &= ~p->x; 2014 printf("%s%s", comma, p->s); 2015 comma = ","; 2016 } 2017 PRINT_UINT_ARG(" ", c->conn_limit); 2018 break; 2019 } 2020 2021 case O_IP6: 2022 printf(" ip6"); 2023 break; 2024 2025 case O_IP4: 2026 printf(" ip4"); 2027 break; 2028 2029 case O_ICMP6TYPE: 2030 print_icmp6types((ipfw_insn_u32 *)cmd); 2031 break; 2032 2033 case O_EXT_HDR: 2034 print_ext6hdr( (ipfw_insn *) cmd ); 2035 break; 2036 2037 case O_TAGGED: 2038 if (F_LEN(cmd) == 1) 2039 PRINT_UINT_ARG(" tagged ", cmd->arg1); 2040 else 2041 print_newports((ipfw_insn_u16 *)cmd, 0, 2042 O_TAGGED); 2043 break; 2044 2045 default: 2046 printf(" [opcode %d len %d]", 2047 cmd->opcode, cmd->len); 2048 } 2049 } 2050 if (cmd->len & F_OR) { 2051 printf(" or"); 2052 or_block = 1; 2053 } else if (or_block) { 2054 printf(" }"); 2055 or_block = 0; 2056 } 2057 } 2058 show_prerequisites(&flags, HAVE_IP, 0); 2059 if (comment) 2060 printf(" // %s", comment); 2061 printf("\n"); 2062 } 2063 2064 static void 2065 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth) 2066 { 2067 struct protoent *pe; 2068 struct in_addr a; 2069 uint16_t rulenum; 2070 char buf[INET6_ADDRSTRLEN]; 2071 2072 if (!do_expired) { 2073 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT)) 2074 return; 2075 } 2076 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 2077 printf("%05d", rulenum); 2078 if (pcwidth>0 || bcwidth>0) 2079 printf(" %*llu %*llu (%ds)", pcwidth, 2080 align_uint64(&d->pcnt), bcwidth, 2081 align_uint64(&d->bcnt), d->expire); 2082 switch (d->dyn_type) { 2083 case O_LIMIT_PARENT: 2084 printf(" PARENT %d", d->count); 2085 break; 2086 case O_LIMIT: 2087 printf(" LIMIT"); 2088 break; 2089 case O_KEEP_STATE: /* bidir, no mask */ 2090 printf(" STATE"); 2091 break; 2092 } 2093 2094 if ((pe = getprotobynumber(d->id.proto)) != NULL) 2095 printf(" %s", pe->p_name); 2096 else 2097 printf(" proto %u", d->id.proto); 2098 2099 if (d->id.addr_type == 4) { 2100 a.s_addr = htonl(d->id.src_ip); 2101 printf(" %s %d", inet_ntoa(a), d->id.src_port); 2102 2103 a.s_addr = htonl(d->id.dst_ip); 2104 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port); 2105 } else if (d->id.addr_type == 6) { 2106 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf, 2107 sizeof(buf)), d->id.src_port); 2108 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf, 2109 sizeof(buf)), d->id.dst_port); 2110 } else 2111 printf(" UNKNOWN <-> UNKNOWN\n"); 2112 2113 printf("\n"); 2114 } 2115 2116 static int 2117 sort_q(const void *pa, const void *pb) 2118 { 2119 int rev = (do_sort < 0); 2120 int field = rev ? -do_sort : do_sort; 2121 long long res = 0; 2122 const struct dn_flow_queue *a = pa; 2123 const struct dn_flow_queue *b = pb; 2124 2125 switch (field) { 2126 case 1: /* pkts */ 2127 res = a->len - b->len; 2128 break; 2129 case 2: /* bytes */ 2130 res = a->len_bytes - b->len_bytes; 2131 break; 2132 2133 case 3: /* tot pkts */ 2134 res = a->tot_pkts - b->tot_pkts; 2135 break; 2136 2137 case 4: /* tot bytes */ 2138 res = a->tot_bytes - b->tot_bytes; 2139 break; 2140 } 2141 if (res < 0) 2142 res = -1; 2143 if (res > 0) 2144 res = 1; 2145 return (int)(rev ? res : -res); 2146 } 2147 2148 static void 2149 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q) 2150 { 2151 int l; 2152 int index_printed, indexes = 0; 2153 char buff[255]; 2154 struct protoent *pe; 2155 2156 if (fs->rq_elements == 0) 2157 return; 2158 2159 if (do_sort != 0) 2160 heapsort(q, fs->rq_elements, sizeof *q, sort_q); 2161 2162 /* Print IPv4 flows */ 2163 index_printed = 0; 2164 for (l = 0; l < fs->rq_elements; l++) { 2165 struct in_addr ina; 2166 2167 /* XXX: Should check for IPv4 flows */ 2168 if (IS_IP6_FLOW_ID(&(q[l].id))) 2169 continue; 2170 2171 if (!index_printed) { 2172 index_printed = 1; 2173 if (indexes > 0) /* currently a no-op */ 2174 printf("\n"); 2175 indexes++; 2176 printf(" " 2177 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n", 2178 fs->flow_mask.proto, 2179 fs->flow_mask.src_ip, fs->flow_mask.src_port, 2180 fs->flow_mask.dst_ip, fs->flow_mask.dst_port); 2181 2182 printf("BKT Prot ___Source IP/port____ " 2183 "____Dest. IP/port____ " 2184 "Tot_pkt/bytes Pkt/Byte Drp\n"); 2185 } 2186 2187 printf("%3d ", q[l].hash_slot); 2188 pe = getprotobynumber(q[l].id.proto); 2189 if (pe) 2190 printf("%-4s ", pe->p_name); 2191 else 2192 printf("%4u ", q[l].id.proto); 2193 ina.s_addr = htonl(q[l].id.src_ip); 2194 printf("%15s/%-5d ", 2195 inet_ntoa(ina), q[l].id.src_port); 2196 ina.s_addr = htonl(q[l].id.dst_ip); 2197 printf("%15s/%-5d ", 2198 inet_ntoa(ina), q[l].id.dst_port); 2199 printf("%4qu %8qu %2u %4u %3u\n", 2200 q[l].tot_pkts, q[l].tot_bytes, 2201 q[l].len, q[l].len_bytes, q[l].drops); 2202 if (verbose) 2203 printf(" S %20qd F %20qd\n", 2204 q[l].S, q[l].F); 2205 } 2206 2207 /* Print IPv6 flows */ 2208 index_printed = 0; 2209 for (l = 0; l < fs->rq_elements; l++) { 2210 if (!IS_IP6_FLOW_ID(&(q[l].id))) 2211 continue; 2212 2213 if (!index_printed) { 2214 index_printed = 1; 2215 if (indexes > 0) 2216 printf("\n"); 2217 indexes++; 2218 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ", 2219 fs->flow_mask.proto, fs->flow_mask.flow_id6); 2220 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6), 2221 buff, sizeof(buff)); 2222 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port); 2223 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6), 2224 buff, sizeof(buff) ); 2225 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port); 2226 2227 printf("BKT ___Prot___ _flow-id_ " 2228 "______________Source IPv6/port_______________ " 2229 "_______________Dest. IPv6/port_______________ " 2230 "Tot_pkt/bytes Pkt/Byte Drp\n"); 2231 } 2232 printf("%3d ", q[l].hash_slot); 2233 pe = getprotobynumber(q[l].id.proto); 2234 if (pe != NULL) 2235 printf("%9s ", pe->p_name); 2236 else 2237 printf("%9u ", q[l].id.proto); 2238 printf("%7d %39s/%-5d ", q[l].id.flow_id6, 2239 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)), 2240 q[l].id.src_port); 2241 printf(" %39s/%-5d ", 2242 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)), 2243 q[l].id.dst_port); 2244 printf(" %4qu %8qu %2u %4u %3u\n", 2245 q[l].tot_pkts, q[l].tot_bytes, 2246 q[l].len, q[l].len_bytes, q[l].drops); 2247 if (verbose) 2248 printf(" S %20qd F %20qd\n", q[l].S, q[l].F); 2249 } 2250 } 2251 2252 static void 2253 print_flowset_parms(struct dn_flow_set *fs, char *prefix) 2254 { 2255 int l; 2256 char qs[30]; 2257 char plr[30]; 2258 char red[90]; /* Display RED parameters */ 2259 2260 l = fs->qsize; 2261 if (fs->flags_fs & DN_QSIZE_IS_BYTES) { 2262 if (l >= 8192) 2263 sprintf(qs, "%d KB", l / 1024); 2264 else 2265 sprintf(qs, "%d B", l); 2266 } else 2267 sprintf(qs, "%3d sl.", l); 2268 if (fs->plr) 2269 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff)); 2270 else 2271 plr[0] = '\0'; 2272 if (fs->flags_fs & DN_IS_RED) /* RED parameters */ 2273 sprintf(red, 2274 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f", 2275 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ', 2276 1.0 * fs->w_q / (double)(1 << SCALE_RED), 2277 SCALE_VAL(fs->min_th), 2278 SCALE_VAL(fs->max_th), 2279 1.0 * fs->max_p / (double)(1 << SCALE_RED)); 2280 else 2281 sprintf(red, "droptail"); 2282 2283 printf("%s %s%s %d queues (%d buckets) %s\n", 2284 prefix, qs, plr, fs->rq_elements, fs->rq_size, red); 2285 } 2286 2287 static void 2288 list_pipes(void *data, uint nbytes, int ac, char *av[]) 2289 { 2290 int rulenum; 2291 void *next = data; 2292 struct dn_pipe *p = (struct dn_pipe *) data; 2293 struct dn_flow_set *fs; 2294 struct dn_flow_queue *q; 2295 int l; 2296 2297 if (ac > 0) 2298 rulenum = strtoul(*av++, NULL, 10); 2299 else 2300 rulenum = 0; 2301 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) { 2302 double b = p->bandwidth; 2303 char buf[30]; 2304 char prefix[80]; 2305 2306 if (SLIST_NEXT(p, next) != (struct dn_pipe *)DN_IS_PIPE) 2307 break; /* done with pipes, now queues */ 2308 2309 /* 2310 * compute length, as pipe have variable size 2311 */ 2312 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q); 2313 next = (char *)p + l; 2314 nbytes -= l; 2315 2316 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2) 2317 continue; 2318 2319 /* 2320 * Print rate (or clocking interface) 2321 */ 2322 if (p->if_name[0] != '\0') 2323 sprintf(buf, "%s", p->if_name); 2324 else if (b == 0) 2325 sprintf(buf, "unlimited"); 2326 else if (b >= 1000000) 2327 sprintf(buf, "%7.3f Mbit/s", b/1000000); 2328 else if (b >= 1000) 2329 sprintf(buf, "%7.3f Kbit/s", b/1000); 2330 else 2331 sprintf(buf, "%7.3f bit/s ", b); 2332 2333 sprintf(prefix, "%05d: %s %4d ms ", 2334 p->pipe_nr, buf, p->delay); 2335 print_flowset_parms(&(p->fs), prefix); 2336 if (verbose) 2337 printf(" V %20qd\n", p->V >> MY_M); 2338 2339 q = (struct dn_flow_queue *)(p+1); 2340 list_queues(&(p->fs), q); 2341 } 2342 for (fs = next; nbytes >= sizeof *fs; fs = next) { 2343 char prefix[80]; 2344 2345 if (SLIST_NEXT(fs, next) != (struct dn_flow_set *)DN_IS_QUEUE) 2346 break; 2347 l = sizeof(*fs) + fs->rq_elements * sizeof(*q); 2348 next = (char *)fs + l; 2349 nbytes -= l; 2350 2351 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) || 2352 (rulenum != fs->parent_nr && do_pipe == 1))) { 2353 continue; 2354 } 2355 2356 q = (struct dn_flow_queue *)(fs+1); 2357 sprintf(prefix, "q%05d: weight %d pipe %d ", 2358 fs->fs_nr, fs->weight, fs->parent_nr); 2359 print_flowset_parms(fs, prefix); 2360 list_queues(fs, q); 2361 } 2362 } 2363 2364 /* 2365 * This one handles all set-related commands 2366 * ipfw set { show | enable | disable } 2367 * ipfw set swap X Y 2368 * ipfw set move X to Y 2369 * ipfw set move rule X to Y 2370 */ 2371 static void 2372 sets_handler(int ac, char *av[]) 2373 { 2374 uint32_t set_disable, masks[2]; 2375 int i, nbytes; 2376 uint16_t rulenum; 2377 uint8_t cmd, new_set; 2378 2379 ac--; 2380 av++; 2381 2382 if (!ac) 2383 errx(EX_USAGE, "set needs command"); 2384 if (_substrcmp(*av, "show") == 0) { 2385 void *data; 2386 char const *msg; 2387 2388 nbytes = sizeof(struct ip_fw); 2389 if ((data = calloc(1, nbytes)) == NULL) 2390 err(EX_OSERR, "calloc"); 2391 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0) 2392 err(EX_OSERR, "getsockopt(IP_FW_GET)"); 2393 bcopy(&((struct ip_fw *)data)->next_rule, 2394 &set_disable, sizeof(set_disable)); 2395 2396 for (i = 0, msg = "disable" ; i < RESVD_SET; i++) 2397 if ((set_disable & (1<<i))) { 2398 printf("%s %d", msg, i); 2399 msg = ""; 2400 } 2401 msg = (set_disable) ? " enable" : "enable"; 2402 for (i = 0; i < RESVD_SET; i++) 2403 if (!(set_disable & (1<<i))) { 2404 printf("%s %d", msg, i); 2405 msg = ""; 2406 } 2407 printf("\n"); 2408 } else if (_substrcmp(*av, "swap") == 0) { 2409 ac--; av++; 2410 if (ac != 2) 2411 errx(EX_USAGE, "set swap needs 2 set numbers\n"); 2412 rulenum = atoi(av[0]); 2413 new_set = atoi(av[1]); 2414 if (!isdigit(*(av[0])) || rulenum > RESVD_SET) 2415 errx(EX_DATAERR, "invalid set number %s\n", av[0]); 2416 if (!isdigit(*(av[1])) || new_set > RESVD_SET) 2417 errx(EX_DATAERR, "invalid set number %s\n", av[1]); 2418 masks[0] = (4 << 24) | (new_set << 16) | (rulenum); 2419 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 2420 } else if (_substrcmp(*av, "move") == 0) { 2421 ac--; av++; 2422 if (ac && _substrcmp(*av, "rule") == 0) { 2423 cmd = 2; 2424 ac--; av++; 2425 } else 2426 cmd = 3; 2427 if (ac != 3 || _substrcmp(av[1], "to") != 0) 2428 errx(EX_USAGE, "syntax: set move [rule] X to Y\n"); 2429 rulenum = atoi(av[0]); 2430 new_set = atoi(av[2]); 2431 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) || 2432 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) ) 2433 errx(EX_DATAERR, "invalid source number %s\n", av[0]); 2434 if (!isdigit(*(av[2])) || new_set > RESVD_SET) 2435 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]); 2436 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum); 2437 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 2438 } else if (_substrcmp(*av, "disable") == 0 || 2439 _substrcmp(*av, "enable") == 0 ) { 2440 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0; 2441 2442 ac--; av++; 2443 masks[0] = masks[1] = 0; 2444 2445 while (ac) { 2446 if (isdigit(**av)) { 2447 i = atoi(*av); 2448 if (i < 0 || i > RESVD_SET) 2449 errx(EX_DATAERR, 2450 "invalid set number %d\n", i); 2451 masks[which] |= (1<<i); 2452 } else if (_substrcmp(*av, "disable") == 0) 2453 which = 0; 2454 else if (_substrcmp(*av, "enable") == 0) 2455 which = 1; 2456 else 2457 errx(EX_DATAERR, 2458 "invalid set command %s\n", *av); 2459 av++; ac--; 2460 } 2461 if ( (masks[0] & masks[1]) != 0 ) 2462 errx(EX_DATAERR, 2463 "cannot enable and disable the same set\n"); 2464 2465 i = do_cmd(IP_FW_DEL, masks, sizeof(masks)); 2466 if (i) 2467 warn("set enable/disable: setsockopt(IP_FW_DEL)"); 2468 } else 2469 errx(EX_USAGE, "invalid set command %s\n", *av); 2470 } 2471 2472 static void 2473 sysctl_handler(int ac, char *av[], int which) 2474 { 2475 ac--; 2476 av++; 2477 2478 if (ac == 0) { 2479 warnx("missing keyword to enable/disable\n"); 2480 } else if (_substrcmp(*av, "firewall") == 0) { 2481 sysctlbyname("net.inet.ip.fw.enable", NULL, 0, 2482 &which, sizeof(which)); 2483 } else if (_substrcmp(*av, "one_pass") == 0) { 2484 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0, 2485 &which, sizeof(which)); 2486 } else if (_substrcmp(*av, "debug") == 0) { 2487 sysctlbyname("net.inet.ip.fw.debug", NULL, 0, 2488 &which, sizeof(which)); 2489 } else if (_substrcmp(*av, "verbose") == 0) { 2490 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0, 2491 &which, sizeof(which)); 2492 } else if (_substrcmp(*av, "dyn_keepalive") == 0) { 2493 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0, 2494 &which, sizeof(which)); 2495 } else if (_substrcmp(*av, "altq") == 0) { 2496 altq_set_enabled(which); 2497 } else { 2498 warnx("unrecognize enable/disable keyword: %s\n", *av); 2499 } 2500 } 2501 2502 static void 2503 list(int ac, char *av[], int show_counters) 2504 { 2505 struct ip_fw *r; 2506 ipfw_dyn_rule *dynrules, *d; 2507 2508 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r))) 2509 char *lim; 2510 void *data = NULL; 2511 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width; 2512 int exitval = EX_OK; 2513 int lac; 2514 char **lav; 2515 u_long rnum, last; 2516 char *endptr; 2517 int seen = 0; 2518 uint8_t set; 2519 2520 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET; 2521 int nalloc = 1024; /* start somewhere... */ 2522 2523 last = 0; 2524 2525 if (test_only) { 2526 fprintf(stderr, "Testing only, list disabled\n"); 2527 return; 2528 } 2529 2530 ac--; 2531 av++; 2532 2533 /* get rules or pipes from kernel, resizing array as necessary */ 2534 nbytes = nalloc; 2535 2536 while (nbytes >= nalloc) { 2537 nalloc = nalloc * 2 + 200; 2538 nbytes = nalloc; 2539 if ((data = realloc(data, nbytes)) == NULL) 2540 err(EX_OSERR, "realloc"); 2541 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0) 2542 err(EX_OSERR, "getsockopt(IP_%s_GET)", 2543 do_pipe ? "DUMMYNET" : "FW"); 2544 } 2545 2546 if (do_pipe) { 2547 list_pipes(data, nbytes, ac, av); 2548 goto done; 2549 } 2550 2551 /* 2552 * Count static rules. They have variable size so we 2553 * need to scan the list to count them. 2554 */ 2555 for (nstat = 1, r = data, lim = (char *)data + nbytes; 2556 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim; 2557 ++nstat, r = NEXT(r) ) 2558 ; /* nothing */ 2559 2560 /* 2561 * Count dynamic rules. This is easier as they have 2562 * fixed size. 2563 */ 2564 r = NEXT(r); 2565 dynrules = (ipfw_dyn_rule *)r ; 2566 n = (char *)r - (char *)data; 2567 ndyn = (nbytes - n) / sizeof *dynrules; 2568 2569 /* if showing stats, figure out column widths ahead of time */ 2570 bcwidth = pcwidth = 0; 2571 if (show_counters) { 2572 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) { 2573 /* skip rules from another set */ 2574 if (use_set && r->set != use_set - 1) 2575 continue; 2576 2577 /* packet counter */ 2578 width = snprintf(NULL, 0, "%llu", 2579 align_uint64(&r->pcnt)); 2580 if (width > pcwidth) 2581 pcwidth = width; 2582 2583 /* byte counter */ 2584 width = snprintf(NULL, 0, "%llu", 2585 align_uint64(&r->bcnt)); 2586 if (width > bcwidth) 2587 bcwidth = width; 2588 } 2589 } 2590 if (do_dynamic && ndyn) { 2591 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 2592 if (use_set) { 2593 /* skip rules from another set */ 2594 bcopy((char *)&d->rule + sizeof(uint16_t), 2595 &set, sizeof(uint8_t)); 2596 if (set != use_set - 1) 2597 continue; 2598 } 2599 width = snprintf(NULL, 0, "%llu", 2600 align_uint64(&d->pcnt)); 2601 if (width > pcwidth) 2602 pcwidth = width; 2603 2604 width = snprintf(NULL, 0, "%llu", 2605 align_uint64(&d->bcnt)); 2606 if (width > bcwidth) 2607 bcwidth = width; 2608 } 2609 } 2610 /* if no rule numbers were specified, list all rules */ 2611 if (ac == 0) { 2612 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) { 2613 if (use_set && r->set != use_set - 1) 2614 continue; 2615 show_ipfw(r, pcwidth, bcwidth); 2616 } 2617 2618 if (do_dynamic && ndyn) { 2619 printf("## Dynamic rules (%d):\n", ndyn); 2620 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 2621 if (use_set) { 2622 bcopy((char *)&d->rule + sizeof(uint16_t), 2623 &set, sizeof(uint8_t)); 2624 if (set != use_set - 1) 2625 continue; 2626 } 2627 show_dyn_ipfw(d, pcwidth, bcwidth); 2628 } 2629 } 2630 goto done; 2631 } 2632 2633 /* display specific rules requested on command line */ 2634 2635 for (lac = ac, lav = av; lac != 0; lac--) { 2636 /* convert command line rule # */ 2637 last = rnum = strtoul(*lav++, &endptr, 10); 2638 if (*endptr == '-') 2639 last = strtoul(endptr+1, &endptr, 10); 2640 if (*endptr) { 2641 exitval = EX_USAGE; 2642 warnx("invalid rule number: %s", *(lav - 1)); 2643 continue; 2644 } 2645 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) { 2646 if (r->rulenum > last) 2647 break; 2648 if (use_set && r->set != use_set - 1) 2649 continue; 2650 if (r->rulenum >= rnum && r->rulenum <= last) { 2651 show_ipfw(r, pcwidth, bcwidth); 2652 seen = 1; 2653 } 2654 } 2655 if (!seen) { 2656 /* give precedence to other error(s) */ 2657 if (exitval == EX_OK) 2658 exitval = EX_UNAVAILABLE; 2659 warnx("rule %lu does not exist", rnum); 2660 } 2661 } 2662 2663 if (do_dynamic && ndyn) { 2664 printf("## Dynamic rules:\n"); 2665 for (lac = ac, lav = av; lac != 0; lac--) { 2666 last = rnum = strtoul(*lav++, &endptr, 10); 2667 if (*endptr == '-') 2668 last = strtoul(endptr+1, &endptr, 10); 2669 if (*endptr) 2670 /* already warned */ 2671 continue; 2672 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 2673 uint16_t rulenum; 2674 2675 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 2676 if (rulenum > rnum) 2677 break; 2678 if (use_set) { 2679 bcopy((char *)&d->rule + sizeof(uint16_t), 2680 &set, sizeof(uint8_t)); 2681 if (set != use_set - 1) 2682 continue; 2683 } 2684 if (r->rulenum >= rnum && r->rulenum <= last) 2685 show_dyn_ipfw(d, pcwidth, bcwidth); 2686 } 2687 } 2688 } 2689 2690 ac = 0; 2691 2692 done: 2693 free(data); 2694 2695 if (exitval != EX_OK) 2696 exit(exitval); 2697 #undef NEXT 2698 } 2699 2700 static void 2701 show_usage(void) 2702 { 2703 fprintf(stderr, "usage: ipfw [options]\n" 2704 "do \"ipfw -h\" or see ipfw manpage for details\n" 2705 ); 2706 exit(EX_USAGE); 2707 } 2708 2709 static void 2710 help(void) 2711 { 2712 fprintf(stderr, 2713 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n" 2714 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n" 2715 "add [num] [set N] [prob x] RULE-BODY\n" 2716 "{pipe|queue} N config PIPE-BODY\n" 2717 "[pipe|queue] {zero|delete|show} [N{,N}]\n" 2718 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|reset|\n" 2719 " reverse|proxy_only|redirect_addr linkspec|\n" 2720 " redirect_port linkspec|redirect_proto linkspec}\n" 2721 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n" 2722 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n" 2723 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n" 2724 "table all {flush | list}\n" 2725 "\n" 2726 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n" 2727 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n" 2728 " skipto N | {divert|tee} PORT | forward ADDR |\n" 2729 " pipe N | queue N | nat N | setfib FIB\n" 2730 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n" 2731 "ADDR: [ MAC dst src ether_type ] \n" 2732 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n" 2733 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n" 2734 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n" 2735 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n" 2736 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n" 2737 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n" 2738 "OPTION_LIST: OPTION [OPTION_LIST]\n" 2739 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n" 2740 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n" 2741 " {dst-port|src-port} LIST |\n" 2742 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n" 2743 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n" 2744 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n" 2745 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n" 2746 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n" 2747 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n" 2748 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n" 2749 ); 2750 exit(0); 2751 } 2752 2753 2754 static int 2755 lookup_host (char *host, struct in_addr *ipaddr) 2756 { 2757 struct hostent *he; 2758 2759 if (!inet_aton(host, ipaddr)) { 2760 if ((he = gethostbyname(host)) == NULL) 2761 return(-1); 2762 *ipaddr = *(struct in_addr *)he->h_addr_list[0]; 2763 } 2764 return(0); 2765 } 2766 2767 /* 2768 * fills the addr and mask fields in the instruction as appropriate from av. 2769 * Update length as appropriate. 2770 * The following formats are allowed: 2771 * me returns O_IP_*_ME 2772 * 1.2.3.4 single IP address 2773 * 1.2.3.4:5.6.7.8 address:mask 2774 * 1.2.3.4/24 address/mask 2775 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet 2776 * We can have multiple comma-separated address/mask entries. 2777 */ 2778 static void 2779 fill_ip(ipfw_insn_ip *cmd, char *av) 2780 { 2781 int len = 0; 2782 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d; 2783 2784 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 2785 2786 if (_substrcmp(av, "any") == 0) 2787 return; 2788 2789 if (_substrcmp(av, "me") == 0) { 2790 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2791 return; 2792 } 2793 2794 if (strncmp(av, "table(", 6) == 0) { 2795 char *p = strchr(av + 6, ','); 2796 2797 if (p) 2798 *p++ = '\0'; 2799 cmd->o.opcode = O_IP_DST_LOOKUP; 2800 cmd->o.arg1 = strtoul(av + 6, NULL, 0); 2801 if (p) { 2802 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2803 d[0] = strtoul(p, NULL, 0); 2804 } else 2805 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2806 return; 2807 } 2808 2809 while (av) { 2810 /* 2811 * After the address we can have '/' or ':' indicating a mask, 2812 * ',' indicating another address follows, '{' indicating a 2813 * set of addresses of unspecified size. 2814 */ 2815 char *t = NULL, *p = strpbrk(av, "/:,{"); 2816 int masklen; 2817 char md, nd; 2818 2819 if (p) { 2820 md = *p; 2821 *p++ = '\0'; 2822 if ((t = strpbrk(p, ",{")) != NULL) { 2823 nd = *t; 2824 *t = '\0'; 2825 } 2826 } else 2827 md = '\0'; 2828 2829 if (lookup_host(av, (struct in_addr *)&d[0]) != 0) 2830 errx(EX_NOHOST, "hostname ``%s'' unknown", av); 2831 switch (md) { 2832 case ':': 2833 if (!inet_aton(p, (struct in_addr *)&d[1])) 2834 errx(EX_DATAERR, "bad netmask ``%s''", p); 2835 break; 2836 case '/': 2837 masklen = atoi(p); 2838 if (masklen == 0) 2839 d[1] = htonl(0); /* mask */ 2840 else if (masklen > 32) 2841 errx(EX_DATAERR, "bad width ``%s''", p); 2842 else 2843 d[1] = htonl(~0 << (32 - masklen)); 2844 break; 2845 case '{': /* no mask, assume /24 and put back the '{' */ 2846 d[1] = htonl(~0 << (32 - 24)); 2847 *(--p) = md; 2848 break; 2849 2850 case ',': /* single address plus continuation */ 2851 *(--p) = md; 2852 /* FALLTHROUGH */ 2853 case 0: /* initialization value */ 2854 default: 2855 d[1] = htonl(~0); /* force /32 */ 2856 break; 2857 } 2858 d[0] &= d[1]; /* mask base address with mask */ 2859 if (t) 2860 *t = nd; 2861 /* find next separator */ 2862 if (p) 2863 p = strpbrk(p, ",{"); 2864 if (p && *p == '{') { 2865 /* 2866 * We have a set of addresses. They are stored as follows: 2867 * arg1 is the set size (powers of 2, 2..256) 2868 * addr is the base address IN HOST FORMAT 2869 * mask.. is an array of arg1 bits (rounded up to 2870 * the next multiple of 32) with bits set 2871 * for each host in the map. 2872 */ 2873 uint32_t *map = (uint32_t *)&cmd->mask; 2874 int low, high; 2875 int i = contigmask((uint8_t *)&(d[1]), 32); 2876 2877 if (len > 0) 2878 errx(EX_DATAERR, "address set cannot be in a list"); 2879 if (i < 24 || i > 31) 2880 errx(EX_DATAERR, "invalid set with mask %d\n", i); 2881 cmd->o.arg1 = 1<<(32-i); /* map length */ 2882 d[0] = ntohl(d[0]); /* base addr in host format */ 2883 cmd->o.opcode = O_IP_DST_SET; /* default */ 2884 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32; 2885 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++) 2886 map[i] = 0; /* clear map */ 2887 2888 av = p + 1; 2889 low = d[0] & 0xff; 2890 high = low + cmd->o.arg1 - 1; 2891 /* 2892 * Here, i stores the previous value when we specify a range 2893 * of addresses within a mask, e.g. 45-63. i = -1 means we 2894 * have no previous value. 2895 */ 2896 i = -1; /* previous value in a range */ 2897 while (isdigit(*av)) { 2898 char *s; 2899 int a = strtol(av, &s, 0); 2900 2901 if (s == av) { /* no parameter */ 2902 if (*av != '}') 2903 errx(EX_DATAERR, "set not closed\n"); 2904 if (i != -1) 2905 errx(EX_DATAERR, "incomplete range %d-", i); 2906 break; 2907 } 2908 if (a < low || a > high) 2909 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n", 2910 a, low, high); 2911 a -= low; 2912 if (i == -1) /* no previous in range */ 2913 i = a; 2914 else { /* check that range is valid */ 2915 if (i > a) 2916 errx(EX_DATAERR, "invalid range %d-%d", 2917 i+low, a+low); 2918 if (*s == '-') 2919 errx(EX_DATAERR, "double '-' in range"); 2920 } 2921 for (; i <= a; i++) 2922 map[i/32] |= 1<<(i & 31); 2923 i = -1; 2924 if (*s == '-') 2925 i = a; 2926 else if (*s == '}') 2927 break; 2928 av = s+1; 2929 } 2930 return; 2931 } 2932 av = p; 2933 if (av) /* then *av must be a ',' */ 2934 av++; 2935 2936 /* Check this entry */ 2937 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */ 2938 /* 2939 * 'any' turns the entire list into a NOP. 2940 * 'not any' never matches, so it is removed from the 2941 * list unless it is the only item, in which case we 2942 * report an error. 2943 */ 2944 if (cmd->o.len & F_NOT) { /* "not any" never matches */ 2945 if (av == NULL && len == 0) /* only this entry */ 2946 errx(EX_DATAERR, "not any never matches"); 2947 } 2948 /* else do nothing and skip this entry */ 2949 return; 2950 } 2951 /* A single IP can be stored in an optimized format */ 2952 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) { 2953 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2954 return; 2955 } 2956 len += 2; /* two words... */ 2957 d += 2; 2958 } /* end while */ 2959 if (len + 1 > F_LEN_MASK) 2960 errx(EX_DATAERR, "address list too long"); 2961 cmd->o.len |= len+1; 2962 } 2963 2964 2965 /* Try to find ipv6 address by hostname */ 2966 static int 2967 lookup_host6 (char *host, struct in6_addr *ip6addr) 2968 { 2969 struct hostent *he; 2970 2971 if (!inet_pton(AF_INET6, host, ip6addr)) { 2972 if ((he = gethostbyname2(host, AF_INET6)) == NULL) 2973 return(-1); 2974 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr)); 2975 } 2976 return(0); 2977 } 2978 2979 2980 /* n2mask sets n bits of the mask */ 2981 static void 2982 n2mask(struct in6_addr *mask, int n) 2983 { 2984 static int minimask[9] = 2985 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff }; 2986 u_char *p; 2987 2988 memset(mask, 0, sizeof(struct in6_addr)); 2989 p = (u_char *) mask; 2990 for (; n > 0; p++, n -= 8) { 2991 if (n >= 8) 2992 *p = 0xff; 2993 else 2994 *p = minimask[n]; 2995 } 2996 return; 2997 } 2998 2999 3000 /* 3001 * fill the addr and mask fields in the instruction as appropriate from av. 3002 * Update length as appropriate. 3003 * The following formats are allowed: 3004 * any matches any IP6. Actually returns an empty instruction. 3005 * me returns O_IP6_*_ME 3006 * 3007 * 03f1::234:123:0342 single IP6 addres 3008 * 03f1::234:123:0342/24 address/mask 3009 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address 3010 * 3011 * Set of address (as in ipv6) not supported because ipv6 address 3012 * are typically random past the initial prefix. 3013 * Return 1 on success, 0 on failure. 3014 */ 3015 static int 3016 fill_ip6(ipfw_insn_ip6 *cmd, char *av) 3017 { 3018 int len = 0; 3019 struct in6_addr *d = &(cmd->addr6); 3020 /* 3021 * Needed for multiple address. 3022 * Note d[1] points to struct in6_add r mask6 of cmd 3023 */ 3024 3025 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 3026 3027 if (strcmp(av, "any") == 0) 3028 return (1); 3029 3030 3031 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/ 3032 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 3033 return (1); 3034 } 3035 3036 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/ 3037 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 3038 return (1); 3039 } 3040 3041 av = strdup(av); 3042 while (av) { 3043 /* 3044 * After the address we can have '/' indicating a mask, 3045 * or ',' indicating another address follows. 3046 */ 3047 3048 char *p; 3049 int masklen; 3050 char md = '\0'; 3051 3052 if ((p = strpbrk(av, "/,")) ) { 3053 md = *p; /* save the separator */ 3054 *p = '\0'; /* terminate address string */ 3055 p++; /* and skip past it */ 3056 } 3057 /* now p points to NULL, mask or next entry */ 3058 3059 /* lookup stores address in *d as a side effect */ 3060 if (lookup_host6(av, d) != 0) { 3061 /* XXX: failed. Free memory and go */ 3062 errx(EX_DATAERR, "bad address \"%s\"", av); 3063 } 3064 /* next, look at the mask, if any */ 3065 masklen = (md == '/') ? atoi(p) : 128; 3066 if (masklen > 128 || masklen < 0) 3067 errx(EX_DATAERR, "bad width \"%s\''", p); 3068 else 3069 n2mask(&d[1], masklen); 3070 3071 APPLY_MASK(d, &d[1]) /* mask base address with mask */ 3072 3073 /* find next separator */ 3074 3075 if (md == '/') { /* find separator past the mask */ 3076 p = strpbrk(p, ","); 3077 if (p != NULL) 3078 p++; 3079 } 3080 av = p; 3081 3082 /* Check this entry */ 3083 if (masklen == 0) { 3084 /* 3085 * 'any' turns the entire list into a NOP. 3086 * 'not any' never matches, so it is removed from the 3087 * list unless it is the only item, in which case we 3088 * report an error. 3089 */ 3090 if (cmd->o.len & F_NOT && av == NULL && len == 0) 3091 errx(EX_DATAERR, "not any never matches"); 3092 continue; 3093 } 3094 3095 /* 3096 * A single IP can be stored alone 3097 */ 3098 if (masklen == 128 && av == NULL && len == 0) { 3099 len = F_INSN_SIZE(struct in6_addr); 3100 break; 3101 } 3102 3103 /* Update length and pointer to arguments */ 3104 len += F_INSN_SIZE(struct in6_addr)*2; 3105 d += 2; 3106 } /* end while */ 3107 3108 /* 3109 * Total length of the command, remember that 1 is the size of 3110 * the base command. 3111 */ 3112 if (len + 1 > F_LEN_MASK) 3113 errx(EX_DATAERR, "address list too long"); 3114 cmd->o.len |= len+1; 3115 free(av); 3116 return (1); 3117 } 3118 3119 /* 3120 * fills command for ipv6 flow-id filtering 3121 * note that the 20 bit flow number is stored in a array of u_int32_t 3122 * it's supported lists of flow-id, so in the o.arg1 we store how many 3123 * additional flow-id we want to filter, the basic is 1 3124 */ 3125 void 3126 fill_flow6( ipfw_insn_u32 *cmd, char *av ) 3127 { 3128 u_int32_t type; /* Current flow number */ 3129 u_int16_t nflow = 0; /* Current flow index */ 3130 char *s = av; 3131 cmd->d[0] = 0; /* Initializing the base number*/ 3132 3133 while (s) { 3134 av = strsep( &s, ",") ; 3135 type = strtoul(av, &av, 0); 3136 if (*av != ',' && *av != '\0') 3137 errx(EX_DATAERR, "invalid ipv6 flow number %s", av); 3138 if (type > 0xfffff) 3139 errx(EX_DATAERR, "flow number out of range %s", av); 3140 cmd->d[nflow] |= type; 3141 nflow++; 3142 } 3143 if( nflow > 0 ) { 3144 cmd->o.opcode = O_FLOW6ID; 3145 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow; 3146 cmd->o.arg1 = nflow; 3147 } 3148 else { 3149 errx(EX_DATAERR, "invalid ipv6 flow number %s", av); 3150 } 3151 } 3152 3153 static ipfw_insn * 3154 add_srcip6(ipfw_insn *cmd, char *av) 3155 { 3156 3157 fill_ip6((ipfw_insn_ip6 *)cmd, av); 3158 if (F_LEN(cmd) == 0) /* any */ 3159 ; 3160 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */ 3161 cmd->opcode = O_IP6_SRC_ME; 3162 } else if (F_LEN(cmd) == 3163 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) { 3164 /* single IP, no mask*/ 3165 cmd->opcode = O_IP6_SRC; 3166 } else { /* addr/mask opt */ 3167 cmd->opcode = O_IP6_SRC_MASK; 3168 } 3169 return cmd; 3170 } 3171 3172 static ipfw_insn * 3173 add_dstip6(ipfw_insn *cmd, char *av) 3174 { 3175 3176 fill_ip6((ipfw_insn_ip6 *)cmd, av); 3177 if (F_LEN(cmd) == 0) /* any */ 3178 ; 3179 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */ 3180 cmd->opcode = O_IP6_DST_ME; 3181 } else if (F_LEN(cmd) == 3182 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) { 3183 /* single IP, no mask*/ 3184 cmd->opcode = O_IP6_DST; 3185 } else { /* addr/mask opt */ 3186 cmd->opcode = O_IP6_DST_MASK; 3187 } 3188 return cmd; 3189 } 3190 3191 3192 /* 3193 * helper function to process a set of flags and set bits in the 3194 * appropriate masks. 3195 */ 3196 static void 3197 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode, 3198 struct _s_x *flags, char *p) 3199 { 3200 uint8_t set=0, clear=0; 3201 3202 while (p && *p) { 3203 char *q; /* points to the separator */ 3204 int val; 3205 uint8_t *which; /* mask we are working on */ 3206 3207 if (*p == '!') { 3208 p++; 3209 which = &clear; 3210 } else 3211 which = &set; 3212 q = strchr(p, ','); 3213 if (q) 3214 *q++ = '\0'; 3215 val = match_token(flags, p); 3216 if (val <= 0) 3217 errx(EX_DATAERR, "invalid flag %s", p); 3218 *which |= (uint8_t)val; 3219 p = q; 3220 } 3221 cmd->opcode = opcode; 3222 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1; 3223 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8); 3224 } 3225 3226 3227 static void 3228 delete(int ac, char *av[]) 3229 { 3230 uint32_t rulenum; 3231 struct dn_pipe p; 3232 int i; 3233 int exitval = EX_OK; 3234 int do_set = 0; 3235 3236 memset(&p, 0, sizeof p); 3237 3238 av++; ac--; 3239 NEED1("missing rule specification"); 3240 if (ac > 0 && _substrcmp(*av, "set") == 0) { 3241 /* Do not allow using the following syntax: 3242 * ipfw set N delete set M 3243 */ 3244 if (use_set) 3245 errx(EX_DATAERR, "invalid syntax"); 3246 do_set = 1; /* delete set */ 3247 ac--; av++; 3248 } 3249 3250 /* Rule number */ 3251 while (ac && isdigit(**av)) { 3252 i = atoi(*av); av++; ac--; 3253 if (do_nat) { 3254 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i); 3255 if (exitval) { 3256 exitval = EX_UNAVAILABLE; 3257 warn("rule %u not available", i); 3258 } 3259 } else if (do_pipe) { 3260 if (do_pipe == 1) 3261 p.pipe_nr = i; 3262 else 3263 p.fs.fs_nr = i; 3264 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p); 3265 if (i) { 3266 exitval = 1; 3267 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", 3268 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr); 3269 } 3270 } else { 3271 if (use_set) 3272 rulenum = (i & 0xffff) | (5 << 24) | 3273 ((use_set - 1) << 16); 3274 else 3275 rulenum = (i & 0xffff) | (do_set << 24); 3276 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum); 3277 if (i) { 3278 exitval = EX_UNAVAILABLE; 3279 warn("rule %u: setsockopt(IP_FW_DEL)", 3280 rulenum); 3281 } 3282 } 3283 } 3284 if (exitval != EX_OK) 3285 exit(exitval); 3286 } 3287 3288 3289 /* 3290 * fill the interface structure. We do not check the name as we can 3291 * create interfaces dynamically, so checking them at insert time 3292 * makes relatively little sense. 3293 * Interface names containing '*', '?', or '[' are assumed to be shell 3294 * patterns which match interfaces. 3295 */ 3296 static void 3297 fill_iface(ipfw_insn_if *cmd, char *arg) 3298 { 3299 cmd->name[0] = '\0'; 3300 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if); 3301 3302 /* Parse the interface or address */ 3303 if (strcmp(arg, "any") == 0) 3304 cmd->o.len = 0; /* effectively ignore this command */ 3305 else if (!isdigit(*arg)) { 3306 strlcpy(cmd->name, arg, sizeof(cmd->name)); 3307 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0; 3308 } else if (!inet_aton(arg, &cmd->p.ip)) 3309 errx(EX_DATAERR, "bad ip address ``%s''", arg); 3310 } 3311 3312 /* 3313 * Search for interface with name "ifn", and fill n accordingly: 3314 * 3315 * n->ip ip address of interface "ifn" 3316 * n->if_name copy of interface name "ifn" 3317 */ 3318 static void 3319 set_addr_dynamic(const char *ifn, struct cfg_nat *n) 3320 { 3321 size_t needed; 3322 int mib[6]; 3323 char *buf, *lim, *next; 3324 struct if_msghdr *ifm; 3325 struct ifa_msghdr *ifam; 3326 struct sockaddr_dl *sdl; 3327 struct sockaddr_in *sin; 3328 int ifIndex, ifMTU; 3329 3330 mib[0] = CTL_NET; 3331 mib[1] = PF_ROUTE; 3332 mib[2] = 0; 3333 mib[3] = AF_INET; 3334 mib[4] = NET_RT_IFLIST; 3335 mib[5] = 0; 3336 /* 3337 * Get interface data. 3338 */ 3339 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1) 3340 err(1, "iflist-sysctl-estimate"); 3341 if ((buf = malloc(needed)) == NULL) 3342 errx(1, "malloc failed"); 3343 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1) 3344 err(1, "iflist-sysctl-get"); 3345 lim = buf + needed; 3346 /* 3347 * Loop through interfaces until one with 3348 * given name is found. This is done to 3349 * find correct interface index for routing 3350 * message processing. 3351 */ 3352 ifIndex = 0; 3353 next = buf; 3354 while (next < lim) { 3355 ifm = (struct if_msghdr *)next; 3356 next += ifm->ifm_msglen; 3357 if (ifm->ifm_version != RTM_VERSION) { 3358 if (verbose) 3359 warnx("routing message version %d " 3360 "not understood", ifm->ifm_version); 3361 continue; 3362 } 3363 if (ifm->ifm_type == RTM_IFINFO) { 3364 sdl = (struct sockaddr_dl *)(ifm + 1); 3365 if (strlen(ifn) == sdl->sdl_nlen && 3366 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) { 3367 ifIndex = ifm->ifm_index; 3368 ifMTU = ifm->ifm_data.ifi_mtu; 3369 break; 3370 } 3371 } 3372 } 3373 if (!ifIndex) 3374 errx(1, "unknown interface name %s", ifn); 3375 /* 3376 * Get interface address. 3377 */ 3378 sin = NULL; 3379 while (next < lim) { 3380 ifam = (struct ifa_msghdr *)next; 3381 next += ifam->ifam_msglen; 3382 if (ifam->ifam_version != RTM_VERSION) { 3383 if (verbose) 3384 warnx("routing message version %d " 3385 "not understood", ifam->ifam_version); 3386 continue; 3387 } 3388 if (ifam->ifam_type != RTM_NEWADDR) 3389 break; 3390 if (ifam->ifam_addrs & RTA_IFA) { 3391 int i; 3392 char *cp = (char *)(ifam + 1); 3393 3394 for (i = 1; i < RTA_IFA; i <<= 1) { 3395 if (ifam->ifam_addrs & i) 3396 cp += SA_SIZE((struct sockaddr *)cp); 3397 } 3398 if (((struct sockaddr *)cp)->sa_family == AF_INET) { 3399 sin = (struct sockaddr_in *)cp; 3400 break; 3401 } 3402 } 3403 } 3404 if (sin == NULL) 3405 errx(1, "%s: cannot get interface address", ifn); 3406 3407 n->ip = sin->sin_addr; 3408 strncpy(n->if_name, ifn, IF_NAMESIZE); 3409 3410 free(buf); 3411 } 3412 3413 /* 3414 * XXX - The following functions, macros and definitions come from natd.c: 3415 * it would be better to move them outside natd.c, in a file 3416 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live 3417 * with it. 3418 */ 3419 3420 /* 3421 * Definition of a port range, and macros to deal with values. 3422 * FORMAT: HI 16-bits == first port in range, 0 == all ports. 3423 * LO 16-bits == number of ports in range 3424 * NOTES: - Port values are not stored in network byte order. 3425 */ 3426 3427 #define port_range u_long 3428 3429 #define GETLOPORT(x) ((x) >> 0x10) 3430 #define GETNUMPORTS(x) ((x) & 0x0000ffff) 3431 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x))) 3432 3433 /* Set y to be the low-port value in port_range variable x. */ 3434 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10)) 3435 3436 /* Set y to be the number of ports in port_range variable x. */ 3437 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y)) 3438 3439 static void 3440 StrToAddr (const char* str, struct in_addr* addr) 3441 { 3442 struct hostent* hp; 3443 3444 if (inet_aton (str, addr)) 3445 return; 3446 3447 hp = gethostbyname (str); 3448 if (!hp) 3449 errx (1, "unknown host %s", str); 3450 3451 memcpy (addr, hp->h_addr, sizeof (struct in_addr)); 3452 } 3453 3454 static int 3455 StrToPortRange (const char* str, const char* proto, port_range *portRange) 3456 { 3457 char* sep; 3458 struct servent* sp; 3459 char* end; 3460 u_short loPort; 3461 u_short hiPort; 3462 3463 /* First see if this is a service, return corresponding port if so. */ 3464 sp = getservbyname (str,proto); 3465 if (sp) { 3466 SETLOPORT(*portRange, ntohs(sp->s_port)); 3467 SETNUMPORTS(*portRange, 1); 3468 return 0; 3469 } 3470 3471 /* Not a service, see if it's a single port or port range. */ 3472 sep = strchr (str, '-'); 3473 if (sep == NULL) { 3474 SETLOPORT(*portRange, strtol(str, &end, 10)); 3475 if (end != str) { 3476 /* Single port. */ 3477 SETNUMPORTS(*portRange, 1); 3478 return 0; 3479 } 3480 3481 /* Error in port range field. */ 3482 errx (EX_DATAERR, "%s/%s: unknown service", str, proto); 3483 } 3484 3485 /* Port range, get the values and sanity check. */ 3486 sscanf (str, "%hu-%hu", &loPort, &hiPort); 3487 SETLOPORT(*portRange, loPort); 3488 SETNUMPORTS(*portRange, 0); /* Error by default */ 3489 if (loPort <= hiPort) 3490 SETNUMPORTS(*portRange, hiPort - loPort + 1); 3491 3492 if (GETNUMPORTS(*portRange) == 0) 3493 errx (EX_DATAERR, "invalid port range %s", str); 3494 3495 return 0; 3496 } 3497 3498 static int 3499 StrToProto (const char* str) 3500 { 3501 if (!strcmp (str, "tcp")) 3502 return IPPROTO_TCP; 3503 3504 if (!strcmp (str, "udp")) 3505 return IPPROTO_UDP; 3506 3507 errx (EX_DATAERR, "unknown protocol %s. Expected tcp or udp", str); 3508 } 3509 3510 static int 3511 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto, 3512 port_range *portRange) 3513 { 3514 char* ptr; 3515 3516 ptr = strchr (str, ':'); 3517 if (!ptr) 3518 errx (EX_DATAERR, "%s is missing port number", str); 3519 3520 *ptr = '\0'; 3521 ++ptr; 3522 3523 StrToAddr (str, addr); 3524 return StrToPortRange (ptr, proto, portRange); 3525 } 3526 3527 /* End of stuff taken from natd.c. */ 3528 3529 #define INC_ARGCV() do { \ 3530 (*_av)++; \ 3531 (*_ac)--; \ 3532 av = *_av; \ 3533 ac = *_ac; \ 3534 } while(0) 3535 3536 /* 3537 * The next 3 functions add support for the addr, port and proto redirect and 3538 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect() 3539 * and SetupProtoRedirect() from natd.c. 3540 * 3541 * Every setup_* function fills at least one redirect entry 3542 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool) 3543 * in buf. 3544 * 3545 * The format of data in buf is: 3546 * 3547 * 3548 * cfg_nat cfg_redir cfg_spool ...... cfg_spool 3549 * 3550 * ------------------------------------- ------------ 3551 * | | .....X ... | | | | ..... 3552 * ------------------------------------- ...... ------------ 3553 * ^ 3554 * spool_cnt n=0 ...... n=(X-1) 3555 * 3556 * len points to the amount of available space in buf 3557 * space counts the memory consumed by every function 3558 * 3559 * XXX - Every function get all the argv params so it 3560 * has to check, in optional parameters, that the next 3561 * args is a valid option for the redir entry and not 3562 * another token. Only redir_port and redir_proto are 3563 * affected by this. 3564 */ 3565 3566 static int 3567 setup_redir_addr(char *spool_buf, int len, 3568 int *_ac, char ***_av) 3569 { 3570 char **av, *sep; /* Token separator. */ 3571 /* Temporary buffer used to hold server pool ip's. */ 3572 char tmp_spool_buf[NAT_BUF_LEN]; 3573 int ac, space, lsnat; 3574 struct cfg_redir *r; 3575 struct cfg_spool *tmp; 3576 3577 av = *_av; 3578 ac = *_ac; 3579 space = 0; 3580 lsnat = 0; 3581 if (len >= SOF_REDIR) { 3582 r = (struct cfg_redir *)spool_buf; 3583 /* Skip cfg_redir at beginning of buf. */ 3584 spool_buf = &spool_buf[SOF_REDIR]; 3585 space = SOF_REDIR; 3586 len -= SOF_REDIR; 3587 } else 3588 goto nospace; 3589 r->mode = REDIR_ADDR; 3590 /* Extract local address. */ 3591 if (ac == 0) 3592 errx(EX_DATAERR, "redirect_addr: missing local address"); 3593 sep = strchr(*av, ','); 3594 if (sep) { /* LSNAT redirection syntax. */ 3595 r->laddr.s_addr = INADDR_NONE; 3596 /* Preserve av, copy spool servers to tmp_spool_buf. */ 3597 strncpy(tmp_spool_buf, *av, strlen(*av)+1); 3598 lsnat = 1; 3599 } else 3600 StrToAddr(*av, &r->laddr); 3601 INC_ARGCV(); 3602 3603 /* Extract public address. */ 3604 if (ac == 0) 3605 errx(EX_DATAERR, "redirect_addr: missing public address"); 3606 StrToAddr(*av, &r->paddr); 3607 INC_ARGCV(); 3608 3609 /* Setup LSNAT server pool. */ 3610 if (sep) { 3611 sep = strtok(tmp_spool_buf, ","); 3612 while (sep != NULL) { 3613 tmp = (struct cfg_spool *)spool_buf; 3614 if (len < SOF_SPOOL) 3615 goto nospace; 3616 len -= SOF_SPOOL; 3617 space += SOF_SPOOL; 3618 StrToAddr(sep, &tmp->addr); 3619 tmp->port = ~0; 3620 r->spool_cnt++; 3621 /* Point to the next possible cfg_spool. */ 3622 spool_buf = &spool_buf[SOF_SPOOL]; 3623 sep = strtok(NULL, ","); 3624 } 3625 } 3626 return(space); 3627 nospace: 3628 errx(EX_DATAERR, "redirect_addr: buf is too small\n"); 3629 } 3630 3631 static int 3632 setup_redir_port(char *spool_buf, int len, 3633 int *_ac, char ***_av) 3634 { 3635 char **av, *sep, *protoName; 3636 char tmp_spool_buf[NAT_BUF_LEN]; 3637 int ac, space, lsnat; 3638 struct cfg_redir *r; 3639 struct cfg_spool *tmp; 3640 u_short numLocalPorts; 3641 port_range portRange; 3642 3643 av = *_av; 3644 ac = *_ac; 3645 space = 0; 3646 lsnat = 0; 3647 numLocalPorts = 0; 3648 3649 if (len >= SOF_REDIR) { 3650 r = (struct cfg_redir *)spool_buf; 3651 /* Skip cfg_redir at beginning of buf. */ 3652 spool_buf = &spool_buf[SOF_REDIR]; 3653 space = SOF_REDIR; 3654 len -= SOF_REDIR; 3655 } else 3656 goto nospace; 3657 r->mode = REDIR_PORT; 3658 /* 3659 * Extract protocol. 3660 */ 3661 if (ac == 0) 3662 errx (EX_DATAERR, "redirect_port: missing protocol"); 3663 r->proto = StrToProto(*av); 3664 protoName = *av; 3665 INC_ARGCV(); 3666 3667 /* 3668 * Extract local address. 3669 */ 3670 if (ac == 0) 3671 errx (EX_DATAERR, "redirect_port: missing local address"); 3672 3673 sep = strchr(*av, ','); 3674 /* LSNAT redirection syntax. */ 3675 if (sep) { 3676 r->laddr.s_addr = INADDR_NONE; 3677 r->lport = ~0; 3678 numLocalPorts = 1; 3679 /* Preserve av, copy spool servers to tmp_spool_buf. */ 3680 strncpy(tmp_spool_buf, *av, strlen(*av)+1); 3681 lsnat = 1; 3682 } else { 3683 if (StrToAddrAndPortRange (*av, &r->laddr, protoName, 3684 &portRange) != 0) 3685 errx(EX_DATAERR, "redirect_port:" 3686 "invalid local port range"); 3687 3688 r->lport = GETLOPORT(portRange); 3689 numLocalPorts = GETNUMPORTS(portRange); 3690 } 3691 INC_ARGCV(); 3692 3693 /* 3694 * Extract public port and optionally address. 3695 */ 3696 if (ac == 0) 3697 errx (EX_DATAERR, "redirect_port: missing public port"); 3698 3699 sep = strchr (*av, ':'); 3700 if (sep) { 3701 if (StrToAddrAndPortRange (*av, &r->paddr, protoName, 3702 &portRange) != 0) 3703 errx(EX_DATAERR, "redirect_port:" 3704 "invalid public port range"); 3705 } else { 3706 r->paddr.s_addr = INADDR_ANY; 3707 if (StrToPortRange (*av, protoName, &portRange) != 0) 3708 errx(EX_DATAERR, "redirect_port:" 3709 "invalid public port range"); 3710 } 3711 3712 r->pport = GETLOPORT(portRange); 3713 r->pport_cnt = GETNUMPORTS(portRange); 3714 INC_ARGCV(); 3715 3716 /* 3717 * Extract remote address and optionally port. 3718 */ 3719 /* 3720 * NB: isalpha(**av) => we've to check that next parameter is really an 3721 * option for this redirect entry, else stop here processing arg[cv]. 3722 */ 3723 if (ac != 0 && !isalpha(**av)) { 3724 sep = strchr (*av, ':'); 3725 if (sep) { 3726 if (StrToAddrAndPortRange (*av, &r->raddr, protoName, 3727 &portRange) != 0) 3728 errx(EX_DATAERR, "redirect_port:" 3729 "invalid remote port range"); 3730 } else { 3731 SETLOPORT(portRange, 0); 3732 SETNUMPORTS(portRange, 1); 3733 StrToAddr (*av, &r->raddr); 3734 } 3735 INC_ARGCV(); 3736 } else { 3737 SETLOPORT(portRange, 0); 3738 SETNUMPORTS(portRange, 1); 3739 r->raddr.s_addr = INADDR_ANY; 3740 } 3741 r->rport = GETLOPORT(portRange); 3742 r->rport_cnt = GETNUMPORTS(portRange); 3743 3744 /* 3745 * Make sure port ranges match up, then add the redirect ports. 3746 */ 3747 if (numLocalPorts != r->pport_cnt) 3748 errx(EX_DATAERR, "redirect_port:" 3749 "port ranges must be equal in size"); 3750 3751 /* Remote port range is allowed to be '0' which means all ports. */ 3752 if (r->rport_cnt != numLocalPorts && 3753 (r->rport_cnt != 1 || r->rport != 0)) 3754 errx(EX_DATAERR, "redirect_port: remote port must" 3755 "be 0 or equal to local port range in size"); 3756 3757 /* 3758 * Setup LSNAT server pool. 3759 */ 3760 if (lsnat) { 3761 sep = strtok(tmp_spool_buf, ","); 3762 while (sep != NULL) { 3763 tmp = (struct cfg_spool *)spool_buf; 3764 if (len < SOF_SPOOL) 3765 goto nospace; 3766 len -= SOF_SPOOL; 3767 space += SOF_SPOOL; 3768 if (StrToAddrAndPortRange(sep, &tmp->addr, protoName, 3769 &portRange) != 0) 3770 errx(EX_DATAERR, "redirect_port:" 3771 "invalid local port range"); 3772 if (GETNUMPORTS(portRange) != 1) 3773 errx(EX_DATAERR, "redirect_port: local port" 3774 "must be single in this context"); 3775 tmp->port = GETLOPORT(portRange); 3776 r->spool_cnt++; 3777 /* Point to the next possible cfg_spool. */ 3778 spool_buf = &spool_buf[SOF_SPOOL]; 3779 sep = strtok(NULL, ","); 3780 } 3781 } 3782 return (space); 3783 nospace: 3784 errx(EX_DATAERR, "redirect_port: buf is too small\n"); 3785 } 3786 3787 static int 3788 setup_redir_proto(char *spool_buf, int len, 3789 int *_ac, char ***_av) 3790 { 3791 char **av; 3792 int ac, space; 3793 struct protoent *protoent; 3794 struct cfg_redir *r; 3795 3796 av = *_av; 3797 ac = *_ac; 3798 if (len >= SOF_REDIR) { 3799 r = (struct cfg_redir *)spool_buf; 3800 /* Skip cfg_redir at beginning of buf. */ 3801 spool_buf = &spool_buf[SOF_REDIR]; 3802 space = SOF_REDIR; 3803 len -= SOF_REDIR; 3804 } else 3805 goto nospace; 3806 r->mode = REDIR_PROTO; 3807 /* 3808 * Extract protocol. 3809 */ 3810 if (ac == 0) 3811 errx(EX_DATAERR, "redirect_proto: missing protocol"); 3812 3813 protoent = getprotobyname(*av); 3814 if (protoent == NULL) 3815 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av); 3816 else 3817 r->proto = protoent->p_proto; 3818 3819 INC_ARGCV(); 3820 3821 /* 3822 * Extract local address. 3823 */ 3824 if (ac == 0) 3825 errx(EX_DATAERR, "redirect_proto: missing local address"); 3826 else 3827 StrToAddr(*av, &r->laddr); 3828 3829 INC_ARGCV(); 3830 3831 /* 3832 * Extract optional public address. 3833 */ 3834 if (ac == 0) { 3835 r->paddr.s_addr = INADDR_ANY; 3836 r->raddr.s_addr = INADDR_ANY; 3837 } else { 3838 /* see above in setup_redir_port() */ 3839 if (!isalpha(**av)) { 3840 StrToAddr(*av, &r->paddr); 3841 INC_ARGCV(); 3842 3843 /* 3844 * Extract optional remote address. 3845 */ 3846 /* see above in setup_redir_port() */ 3847 if (ac!=0 && !isalpha(**av)) { 3848 StrToAddr(*av, &r->raddr); 3849 INC_ARGCV(); 3850 } 3851 } 3852 } 3853 return (space); 3854 nospace: 3855 errx(EX_DATAERR, "redirect_proto: buf is too small\n"); 3856 } 3857 3858 static void 3859 show_nat(int ac, char **av); 3860 3861 static void 3862 print_nat_config(char *buf) { 3863 struct cfg_nat *n; 3864 int i, cnt, flag, off; 3865 struct cfg_redir *t; 3866 struct cfg_spool *s; 3867 struct protoent *p; 3868 3869 n = (struct cfg_nat *)buf; 3870 flag = 1; 3871 off = sizeof(*n); 3872 printf("ipfw nat %u config", n->id); 3873 if (strlen(n->if_name) != 0) 3874 printf(" if %s", n->if_name); 3875 else if (n->ip.s_addr != 0) 3876 printf(" ip %s", inet_ntoa(n->ip)); 3877 while (n->mode != 0) { 3878 if (n->mode & PKT_ALIAS_LOG) { 3879 printf(" log"); 3880 n->mode &= ~PKT_ALIAS_LOG; 3881 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) { 3882 printf(" deny_in"); 3883 n->mode &= ~PKT_ALIAS_DENY_INCOMING; 3884 } else if (n->mode & PKT_ALIAS_SAME_PORTS) { 3885 printf(" same_ports"); 3886 n->mode &= ~PKT_ALIAS_SAME_PORTS; 3887 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) { 3888 printf(" unreg_only"); 3889 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY; 3890 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) { 3891 printf(" reset"); 3892 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE; 3893 } else if (n->mode & PKT_ALIAS_REVERSE) { 3894 printf(" reverse"); 3895 n->mode &= ~PKT_ALIAS_REVERSE; 3896 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) { 3897 printf(" proxy_only"); 3898 n->mode &= ~PKT_ALIAS_PROXY_ONLY; 3899 } 3900 } 3901 /* Print all the redirect's data configuration. */ 3902 for (cnt = 0; cnt < n->redir_cnt; cnt++) { 3903 t = (struct cfg_redir *)&buf[off]; 3904 off += SOF_REDIR; 3905 switch (t->mode) { 3906 case REDIR_ADDR: 3907 printf(" redirect_addr"); 3908 if (t->spool_cnt == 0) 3909 printf(" %s", inet_ntoa(t->laddr)); 3910 else 3911 for (i = 0; i < t->spool_cnt; i++) { 3912 s = (struct cfg_spool *)&buf[off]; 3913 if (i) 3914 printf(","); 3915 else 3916 printf(" "); 3917 printf("%s", inet_ntoa(s->addr)); 3918 off += SOF_SPOOL; 3919 } 3920 printf(" %s", inet_ntoa(t->paddr)); 3921 break; 3922 case REDIR_PORT: 3923 p = getprotobynumber(t->proto); 3924 printf(" redirect_port %s ", p->p_name); 3925 if (!t->spool_cnt) { 3926 printf("%s:%u", inet_ntoa(t->laddr), t->lport); 3927 if (t->pport_cnt > 1) 3928 printf("-%u", t->lport + 3929 t->pport_cnt - 1); 3930 } else 3931 for (i=0; i < t->spool_cnt; i++) { 3932 s = (struct cfg_spool *)&buf[off]; 3933 if (i) 3934 printf(","); 3935 printf("%s:%u", inet_ntoa(s->addr), 3936 s->port); 3937 off += SOF_SPOOL; 3938 } 3939 3940 printf(" "); 3941 if (t->paddr.s_addr) 3942 printf("%s:", inet_ntoa(t->paddr)); 3943 printf("%u", t->pport); 3944 if (!t->spool_cnt && t->pport_cnt > 1) 3945 printf("-%u", t->pport + t->pport_cnt - 1); 3946 3947 if (t->raddr.s_addr) { 3948 printf(" %s", inet_ntoa(t->raddr)); 3949 if (t->rport) { 3950 printf(":%u", t->rport); 3951 if (!t->spool_cnt && t->rport_cnt > 1) 3952 printf("-%u", t->rport + 3953 t->rport_cnt - 1); 3954 } 3955 } 3956 break; 3957 case REDIR_PROTO: 3958 p = getprotobynumber(t->proto); 3959 printf(" redirect_proto %s %s", p->p_name, 3960 inet_ntoa(t->laddr)); 3961 if (t->paddr.s_addr != 0) { 3962 printf(" %s", inet_ntoa(t->paddr)); 3963 if (t->raddr.s_addr) 3964 printf(" %s", inet_ntoa(t->raddr)); 3965 } 3966 break; 3967 default: 3968 errx(EX_DATAERR, "unknown redir mode"); 3969 break; 3970 } 3971 } 3972 printf("\n"); 3973 } 3974 3975 static void 3976 config_nat(int ac, char **av) 3977 { 3978 struct cfg_nat *n; /* Nat instance configuration. */ 3979 int i, len, off, tok; 3980 char *id, buf[NAT_BUF_LEN]; /* Buffer for serialized data. */ 3981 3982 len = NAT_BUF_LEN; 3983 /* Offset in buf: save space for n at the beginning. */ 3984 off = sizeof(*n); 3985 memset(buf, 0, sizeof(buf)); 3986 n = (struct cfg_nat *)buf; 3987 3988 av++; ac--; 3989 /* Nat id. */ 3990 if (ac && isdigit(**av)) { 3991 id = *av; 3992 i = atoi(*av); 3993 ac--; av++; 3994 n->id = i; 3995 } else 3996 errx(EX_DATAERR, "missing nat id"); 3997 if (ac == 0) 3998 errx(EX_DATAERR, "missing option"); 3999 4000 while (ac > 0) { 4001 tok = match_token(nat_params, *av); 4002 ac--; av++; 4003 switch (tok) { 4004 case TOK_IP: 4005 if (ac == 0) 4006 errx(EX_DATAERR, "missing option"); 4007 if (!inet_aton(av[0], &(n->ip))) 4008 errx(EX_DATAERR, "bad ip address ``%s''", 4009 av[0]); 4010 ac--; av++; 4011 break; 4012 case TOK_IF: 4013 if (ac == 0) 4014 errx(EX_DATAERR, "missing option"); 4015 set_addr_dynamic(av[0], n); 4016 ac--; av++; 4017 break; 4018 case TOK_ALOG: 4019 n->mode |= PKT_ALIAS_LOG; 4020 break; 4021 case TOK_DENY_INC: 4022 n->mode |= PKT_ALIAS_DENY_INCOMING; 4023 break; 4024 case TOK_SAME_PORTS: 4025 n->mode |= PKT_ALIAS_SAME_PORTS; 4026 break; 4027 case TOK_UNREG_ONLY: 4028 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY; 4029 break; 4030 case TOK_RESET_ADDR: 4031 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE; 4032 break; 4033 case TOK_ALIAS_REV: 4034 n->mode |= PKT_ALIAS_REVERSE; 4035 break; 4036 case TOK_PROXY_ONLY: 4037 n->mode |= PKT_ALIAS_PROXY_ONLY; 4038 break; 4039 /* 4040 * All the setup_redir_* functions work directly in the final 4041 * buffer, see above for details. 4042 */ 4043 case TOK_REDIR_ADDR: 4044 case TOK_REDIR_PORT: 4045 case TOK_REDIR_PROTO: 4046 switch (tok) { 4047 case TOK_REDIR_ADDR: 4048 i = setup_redir_addr(&buf[off], len, &ac, &av); 4049 break; 4050 case TOK_REDIR_PORT: 4051 i = setup_redir_port(&buf[off], len, &ac, &av); 4052 break; 4053 case TOK_REDIR_PROTO: 4054 i = setup_redir_proto(&buf[off], len, &ac, &av); 4055 break; 4056 } 4057 n->redir_cnt++; 4058 off += i; 4059 len -= i; 4060 break; 4061 default: 4062 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]); 4063 } 4064 } 4065 4066 i = do_cmd(IP_FW_NAT_CFG, buf, off); 4067 if (i) 4068 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG"); 4069 4070 /* After every modification, we show the resultant rule. */ 4071 int _ac = 3; 4072 char *_av[] = {"show", "config", id}; 4073 show_nat(_ac, _av); 4074 } 4075 4076 static void 4077 config_pipe(int ac, char **av) 4078 { 4079 struct dn_pipe p; 4080 int i; 4081 char *end; 4082 void *par = NULL; 4083 4084 memset(&p, 0, sizeof p); 4085 4086 av++; ac--; 4087 /* Pipe number */ 4088 if (ac && isdigit(**av)) { 4089 i = atoi(*av); av++; ac--; 4090 if (do_pipe == 1) 4091 p.pipe_nr = i; 4092 else 4093 p.fs.fs_nr = i; 4094 } 4095 while (ac > 0) { 4096 double d; 4097 int tok = match_token(dummynet_params, *av); 4098 ac--; av++; 4099 4100 switch(tok) { 4101 case TOK_NOERROR: 4102 p.fs.flags_fs |= DN_NOERROR; 4103 break; 4104 4105 case TOK_PLR: 4106 NEED1("plr needs argument 0..1\n"); 4107 d = strtod(av[0], NULL); 4108 if (d > 1) 4109 d = 1; 4110 else if (d < 0) 4111 d = 0; 4112 p.fs.plr = (int)(d*0x7fffffff); 4113 ac--; av++; 4114 break; 4115 4116 case TOK_QUEUE: 4117 NEED1("queue needs queue size\n"); 4118 end = NULL; 4119 p.fs.qsize = strtoul(av[0], &end, 0); 4120 if (*end == 'K' || *end == 'k') { 4121 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 4122 p.fs.qsize *= 1024; 4123 } else if (*end == 'B' || 4124 _substrcmp2(end, "by", "bytes") == 0) { 4125 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 4126 } 4127 ac--; av++; 4128 break; 4129 4130 case TOK_BUCKETS: 4131 NEED1("buckets needs argument\n"); 4132 p.fs.rq_size = strtoul(av[0], NULL, 0); 4133 ac--; av++; 4134 break; 4135 4136 case TOK_MASK: 4137 NEED1("mask needs mask specifier\n"); 4138 /* 4139 * per-flow queue, mask is dst_ip, dst_port, 4140 * src_ip, src_port, proto measured in bits 4141 */ 4142 par = NULL; 4143 4144 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask)); 4145 end = NULL; 4146 4147 while (ac >= 1) { 4148 uint32_t *p32 = NULL; 4149 uint16_t *p16 = NULL; 4150 uint32_t *p20 = NULL; 4151 struct in6_addr *pa6 = NULL; 4152 uint32_t a; 4153 4154 tok = match_token(dummynet_params, *av); 4155 ac--; av++; 4156 switch(tok) { 4157 case TOK_ALL: 4158 /* 4159 * special case, all bits significant 4160 */ 4161 p.fs.flow_mask.dst_ip = ~0; 4162 p.fs.flow_mask.src_ip = ~0; 4163 p.fs.flow_mask.dst_port = ~0; 4164 p.fs.flow_mask.src_port = ~0; 4165 p.fs.flow_mask.proto = ~0; 4166 n2mask(&(p.fs.flow_mask.dst_ip6), 128); 4167 n2mask(&(p.fs.flow_mask.src_ip6), 128); 4168 p.fs.flow_mask.flow_id6 = ~0; 4169 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 4170 goto end_mask; 4171 4172 case TOK_DSTIP: 4173 p32 = &p.fs.flow_mask.dst_ip; 4174 break; 4175 4176 case TOK_SRCIP: 4177 p32 = &p.fs.flow_mask.src_ip; 4178 break; 4179 4180 case TOK_DSTIP6: 4181 pa6 = &(p.fs.flow_mask.dst_ip6); 4182 break; 4183 4184 case TOK_SRCIP6: 4185 pa6 = &(p.fs.flow_mask.src_ip6); 4186 break; 4187 4188 case TOK_FLOWID: 4189 p20 = &p.fs.flow_mask.flow_id6; 4190 break; 4191 4192 case TOK_DSTPORT: 4193 p16 = &p.fs.flow_mask.dst_port; 4194 break; 4195 4196 case TOK_SRCPORT: 4197 p16 = &p.fs.flow_mask.src_port; 4198 break; 4199 4200 case TOK_PROTO: 4201 break; 4202 4203 default: 4204 ac++; av--; /* backtrack */ 4205 goto end_mask; 4206 } 4207 if (ac < 1) 4208 errx(EX_USAGE, "mask: value missing"); 4209 if (*av[0] == '/') { 4210 a = strtoul(av[0]+1, &end, 0); 4211 if (pa6 == NULL) 4212 a = (a == 32) ? ~0 : (1 << a) - 1; 4213 } else 4214 a = strtoul(av[0], &end, 0); 4215 if (p32 != NULL) 4216 *p32 = a; 4217 else if (p16 != NULL) { 4218 if (a > 0xFFFF) 4219 errx(EX_DATAERR, 4220 "port mask must be 16 bit"); 4221 *p16 = (uint16_t)a; 4222 } else if (p20 != NULL) { 4223 if (a > 0xfffff) 4224 errx(EX_DATAERR, 4225 "flow_id mask must be 20 bit"); 4226 *p20 = (uint32_t)a; 4227 } else if (pa6 != NULL) { 4228 if (a < 0 || a > 128) 4229 errx(EX_DATAERR, 4230 "in6addr invalid mask len"); 4231 else 4232 n2mask(pa6, a); 4233 } else { 4234 if (a > 0xFF) 4235 errx(EX_DATAERR, 4236 "proto mask must be 8 bit"); 4237 p.fs.flow_mask.proto = (uint8_t)a; 4238 } 4239 if (a != 0) 4240 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 4241 ac--; av++; 4242 } /* end while, config masks */ 4243 end_mask: 4244 break; 4245 4246 case TOK_RED: 4247 case TOK_GRED: 4248 NEED1("red/gred needs w_q/min_th/max_th/max_p\n"); 4249 p.fs.flags_fs |= DN_IS_RED; 4250 if (tok == TOK_GRED) 4251 p.fs.flags_fs |= DN_IS_GENTLE_RED; 4252 /* 4253 * the format for parameters is w_q/min_th/max_th/max_p 4254 */ 4255 if ((end = strsep(&av[0], "/"))) { 4256 double w_q = strtod(end, NULL); 4257 if (w_q > 1 || w_q <= 0) 4258 errx(EX_DATAERR, "0 < w_q <= 1"); 4259 p.fs.w_q = (int) (w_q * (1 << SCALE_RED)); 4260 } 4261 if ((end = strsep(&av[0], "/"))) { 4262 p.fs.min_th = strtoul(end, &end, 0); 4263 if (*end == 'K' || *end == 'k') 4264 p.fs.min_th *= 1024; 4265 } 4266 if ((end = strsep(&av[0], "/"))) { 4267 p.fs.max_th = strtoul(end, &end, 0); 4268 if (*end == 'K' || *end == 'k') 4269 p.fs.max_th *= 1024; 4270 } 4271 if ((end = strsep(&av[0], "/"))) { 4272 double max_p = strtod(end, NULL); 4273 if (max_p > 1 || max_p <= 0) 4274 errx(EX_DATAERR, "0 < max_p <= 1"); 4275 p.fs.max_p = (int)(max_p * (1 << SCALE_RED)); 4276 } 4277 ac--; av++; 4278 break; 4279 4280 case TOK_DROPTAIL: 4281 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED); 4282 break; 4283 4284 case TOK_BW: 4285 NEED1("bw needs bandwidth or interface\n"); 4286 if (do_pipe != 1) 4287 errx(EX_DATAERR, "bandwidth only valid for pipes"); 4288 /* 4289 * set clocking interface or bandwidth value 4290 */ 4291 if (av[0][0] >= 'a' && av[0][0] <= 'z') { 4292 int l = sizeof(p.if_name)-1; 4293 /* interface name */ 4294 strncpy(p.if_name, av[0], l); 4295 p.if_name[l] = '\0'; 4296 p.bandwidth = 0; 4297 } else { 4298 p.if_name[0] = '\0'; 4299 p.bandwidth = strtoul(av[0], &end, 0); 4300 if (*end == 'K' || *end == 'k') { 4301 end++; 4302 p.bandwidth *= 1000; 4303 } else if (*end == 'M') { 4304 end++; 4305 p.bandwidth *= 1000000; 4306 } 4307 if ((*end == 'B' && 4308 _substrcmp2(end, "Bi", "Bit/s") != 0) || 4309 _substrcmp2(end, "by", "bytes") == 0) 4310 p.bandwidth *= 8; 4311 if (p.bandwidth < 0) 4312 errx(EX_DATAERR, "bandwidth too large"); 4313 } 4314 ac--; av++; 4315 break; 4316 4317 case TOK_DELAY: 4318 if (do_pipe != 1) 4319 errx(EX_DATAERR, "delay only valid for pipes"); 4320 NEED1("delay needs argument 0..10000ms\n"); 4321 p.delay = strtoul(av[0], NULL, 0); 4322 ac--; av++; 4323 break; 4324 4325 case TOK_WEIGHT: 4326 if (do_pipe == 1) 4327 errx(EX_DATAERR,"weight only valid for queues"); 4328 NEED1("weight needs argument 0..100\n"); 4329 p.fs.weight = strtoul(av[0], &end, 0); 4330 ac--; av++; 4331 break; 4332 4333 case TOK_PIPE: 4334 if (do_pipe == 1) 4335 errx(EX_DATAERR,"pipe only valid for queues"); 4336 NEED1("pipe needs pipe_number\n"); 4337 p.fs.parent_nr = strtoul(av[0], &end, 0); 4338 ac--; av++; 4339 break; 4340 4341 default: 4342 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]); 4343 } 4344 } 4345 if (do_pipe == 1) { 4346 if (p.pipe_nr == 0) 4347 errx(EX_DATAERR, "pipe_nr must be > 0"); 4348 if (p.delay > 10000) 4349 errx(EX_DATAERR, "delay must be < 10000"); 4350 } else { /* do_pipe == 2, queue */ 4351 if (p.fs.parent_nr == 0) 4352 errx(EX_DATAERR, "pipe must be > 0"); 4353 if (p.fs.weight >100) 4354 errx(EX_DATAERR, "weight must be <= 100"); 4355 } 4356 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) { 4357 size_t len; 4358 long limit; 4359 4360 len = sizeof(limit); 4361 if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit", 4362 &limit, &len, NULL, 0) == -1) 4363 limit = 1024*1024; 4364 if (p.fs.qsize > limit) 4365 errx(EX_DATAERR, "queue size must be < %ldB", limit); 4366 } else { 4367 size_t len; 4368 long limit; 4369 4370 len = sizeof(limit); 4371 if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit", 4372 &limit, &len, NULL, 0) == -1) 4373 limit = 100; 4374 if (p.fs.qsize > limit) 4375 errx(EX_DATAERR, "2 <= queue size <= %ld", limit); 4376 } 4377 if (p.fs.flags_fs & DN_IS_RED) { 4378 size_t len; 4379 int lookup_depth, avg_pkt_size; 4380 double s, idle, weight, w_q; 4381 struct clockinfo ck; 4382 int t; 4383 4384 if (p.fs.min_th >= p.fs.max_th) 4385 errx(EX_DATAERR, "min_th %d must be < than max_th %d", 4386 p.fs.min_th, p.fs.max_th); 4387 if (p.fs.max_th == 0) 4388 errx(EX_DATAERR, "max_th must be > 0"); 4389 4390 len = sizeof(int); 4391 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth", 4392 &lookup_depth, &len, NULL, 0) == -1) 4393 errx(1, "sysctlbyname(\"%s\")", 4394 "net.inet.ip.dummynet.red_lookup_depth"); 4395 if (lookup_depth == 0) 4396 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth" 4397 " must be greater than zero"); 4398 4399 len = sizeof(int); 4400 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size", 4401 &avg_pkt_size, &len, NULL, 0) == -1) 4402 4403 errx(1, "sysctlbyname(\"%s\")", 4404 "net.inet.ip.dummynet.red_avg_pkt_size"); 4405 if (avg_pkt_size == 0) 4406 errx(EX_DATAERR, 4407 "net.inet.ip.dummynet.red_avg_pkt_size must" 4408 " be greater than zero"); 4409 4410 len = sizeof(struct clockinfo); 4411 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1) 4412 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate"); 4413 4414 /* 4415 * Ticks needed for sending a medium-sized packet. 4416 * Unfortunately, when we are configuring a WF2Q+ queue, we 4417 * do not have bandwidth information, because that is stored 4418 * in the parent pipe, and also we have multiple queues 4419 * competing for it. So we set s=0, which is not very 4420 * correct. But on the other hand, why do we want RED with 4421 * WF2Q+ ? 4422 */ 4423 if (p.bandwidth==0) /* this is a WF2Q+ queue */ 4424 s = 0; 4425 else 4426 s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth; 4427 4428 /* 4429 * max idle time (in ticks) before avg queue size becomes 0. 4430 * NOTA: (3/w_q) is approx the value x so that 4431 * (1-w_q)^x < 10^-3. 4432 */ 4433 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED); 4434 idle = s * 3. / w_q; 4435 p.fs.lookup_step = (int)idle / lookup_depth; 4436 if (!p.fs.lookup_step) 4437 p.fs.lookup_step = 1; 4438 weight = 1 - w_q; 4439 for (t = p.fs.lookup_step; t > 1; --t) 4440 weight *= 1 - w_q; 4441 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED)); 4442 } 4443 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p); 4444 if (i) 4445 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE"); 4446 } 4447 4448 static void 4449 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask) 4450 { 4451 int i, l; 4452 char *ap, *ptr, *optr; 4453 struct ether_addr *mac; 4454 const char *macset = "0123456789abcdefABCDEF:"; 4455 4456 if (strcmp(p, "any") == 0) { 4457 for (i = 0; i < ETHER_ADDR_LEN; i++) 4458 addr[i] = mask[i] = 0; 4459 return; 4460 } 4461 4462 optr = ptr = strdup(p); 4463 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) { 4464 l = strlen(ap); 4465 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL) 4466 errx(EX_DATAERR, "Incorrect MAC address"); 4467 bcopy(mac, addr, ETHER_ADDR_LEN); 4468 } else 4469 errx(EX_DATAERR, "Incorrect MAC address"); 4470 4471 if (ptr != NULL) { /* we have mask? */ 4472 if (p[ptr - optr - 1] == '/') { /* mask len */ 4473 l = strtol(ptr, &ap, 10); 4474 if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0) 4475 errx(EX_DATAERR, "Incorrect mask length"); 4476 for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++) 4477 mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l); 4478 } else { /* mask */ 4479 l = strlen(ptr); 4480 if (strspn(ptr, macset) != l || 4481 (mac = ether_aton(ptr)) == NULL) 4482 errx(EX_DATAERR, "Incorrect mask"); 4483 bcopy(mac, mask, ETHER_ADDR_LEN); 4484 } 4485 } else { /* default mask: ff:ff:ff:ff:ff:ff */ 4486 for (i = 0; i < ETHER_ADDR_LEN; i++) 4487 mask[i] = 0xff; 4488 } 4489 for (i = 0; i < ETHER_ADDR_LEN; i++) 4490 addr[i] &= mask[i]; 4491 4492 free(optr); 4493 } 4494 4495 /* 4496 * helper function, updates the pointer to cmd with the length 4497 * of the current command, and also cleans up the first word of 4498 * the new command in case it has been clobbered before. 4499 */ 4500 static ipfw_insn * 4501 next_cmd(ipfw_insn *cmd) 4502 { 4503 cmd += F_LEN(cmd); 4504 bzero(cmd, sizeof(*cmd)); 4505 return cmd; 4506 } 4507 4508 /* 4509 * Takes arguments and copies them into a comment 4510 */ 4511 static void 4512 fill_comment(ipfw_insn *cmd, int ac, char **av) 4513 { 4514 int i, l; 4515 char *p = (char *)(cmd + 1); 4516 4517 cmd->opcode = O_NOP; 4518 cmd->len = (cmd->len & (F_NOT | F_OR)); 4519 4520 /* Compute length of comment string. */ 4521 for (i = 0, l = 0; i < ac; i++) 4522 l += strlen(av[i]) + 1; 4523 if (l == 0) 4524 return; 4525 if (l > 84) 4526 errx(EX_DATAERR, 4527 "comment too long (max 80 chars)"); 4528 l = 1 + (l+3)/4; 4529 cmd->len = (cmd->len & (F_NOT | F_OR)) | l; 4530 for (i = 0; i < ac; i++) { 4531 strcpy(p, av[i]); 4532 p += strlen(av[i]); 4533 *p++ = ' '; 4534 } 4535 *(--p) = '\0'; 4536 } 4537 4538 /* 4539 * A function to fill simple commands of size 1. 4540 * Existing flags are preserved. 4541 */ 4542 static void 4543 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg) 4544 { 4545 cmd->opcode = opcode; 4546 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1; 4547 cmd->arg1 = arg; 4548 } 4549 4550 /* 4551 * Fetch and add the MAC address and type, with masks. This generates one or 4552 * two microinstructions, and returns the pointer to the last one. 4553 */ 4554 static ipfw_insn * 4555 add_mac(ipfw_insn *cmd, int ac, char *av[]) 4556 { 4557 ipfw_insn_mac *mac; 4558 4559 if (ac < 2) 4560 errx(EX_DATAERR, "MAC dst src"); 4561 4562 cmd->opcode = O_MACADDR2; 4563 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac); 4564 4565 mac = (ipfw_insn_mac *)cmd; 4566 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */ 4567 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]), 4568 &(mac->mask[ETHER_ADDR_LEN])); /* src */ 4569 return cmd; 4570 } 4571 4572 static ipfw_insn * 4573 add_mactype(ipfw_insn *cmd, int ac, char *av) 4574 { 4575 if (ac < 1) 4576 errx(EX_DATAERR, "missing MAC type"); 4577 if (strcmp(av, "any") != 0) { /* we have a non-null type */ 4578 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE); 4579 cmd->opcode = O_MAC_TYPE; 4580 return cmd; 4581 } else 4582 return NULL; 4583 } 4584 4585 static ipfw_insn * 4586 add_proto0(ipfw_insn *cmd, char *av, u_char *protop) 4587 { 4588 struct protoent *pe; 4589 char *ep; 4590 int proto; 4591 4592 proto = strtol(av, &ep, 10); 4593 if (*ep != '\0' || proto <= 0) { 4594 if ((pe = getprotobyname(av)) == NULL) 4595 return NULL; 4596 proto = pe->p_proto; 4597 } 4598 4599 fill_cmd(cmd, O_PROTO, 0, proto); 4600 *protop = proto; 4601 return cmd; 4602 } 4603 4604 static ipfw_insn * 4605 add_proto(ipfw_insn *cmd, char *av, u_char *protop) 4606 { 4607 u_char proto = IPPROTO_IP; 4608 4609 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4610 ; /* do not set O_IP4 nor O_IP6 */ 4611 else if (strcmp(av, "ip4") == 0) 4612 /* explicit "just IPv4" rule */ 4613 fill_cmd(cmd, O_IP4, 0, 0); 4614 else if (strcmp(av, "ip6") == 0) { 4615 /* explicit "just IPv6" rule */ 4616 proto = IPPROTO_IPV6; 4617 fill_cmd(cmd, O_IP6, 0, 0); 4618 } else 4619 return add_proto0(cmd, av, protop); 4620 4621 *protop = proto; 4622 return cmd; 4623 } 4624 4625 static ipfw_insn * 4626 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop) 4627 { 4628 u_char proto = IPPROTO_IP; 4629 4630 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4631 ; /* do not set O_IP4 nor O_IP6 */ 4632 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0) 4633 /* explicit "just IPv4" rule */ 4634 fill_cmd(cmd, O_IP4, 0, 0); 4635 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) { 4636 /* explicit "just IPv6" rule */ 4637 proto = IPPROTO_IPV6; 4638 fill_cmd(cmd, O_IP6, 0, 0); 4639 } else 4640 return add_proto0(cmd, av, protop); 4641 4642 *protop = proto; 4643 return cmd; 4644 } 4645 4646 static ipfw_insn * 4647 add_srcip(ipfw_insn *cmd, char *av) 4648 { 4649 fill_ip((ipfw_insn_ip *)cmd, av); 4650 if (cmd->opcode == O_IP_DST_SET) /* set */ 4651 cmd->opcode = O_IP_SRC_SET; 4652 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4653 cmd->opcode = O_IP_SRC_LOOKUP; 4654 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4655 cmd->opcode = O_IP_SRC_ME; 4656 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4657 cmd->opcode = O_IP_SRC; 4658 else /* addr/mask */ 4659 cmd->opcode = O_IP_SRC_MASK; 4660 return cmd; 4661 } 4662 4663 static ipfw_insn * 4664 add_dstip(ipfw_insn *cmd, char *av) 4665 { 4666 fill_ip((ipfw_insn_ip *)cmd, av); 4667 if (cmd->opcode == O_IP_DST_SET) /* set */ 4668 ; 4669 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4670 ; 4671 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4672 cmd->opcode = O_IP_DST_ME; 4673 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4674 cmd->opcode = O_IP_DST; 4675 else /* addr/mask */ 4676 cmd->opcode = O_IP_DST_MASK; 4677 return cmd; 4678 } 4679 4680 static ipfw_insn * 4681 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode) 4682 { 4683 if (_substrcmp(av, "any") == 0) { 4684 return NULL; 4685 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) { 4686 /* XXX todo: check that we have a protocol with ports */ 4687 cmd->opcode = opcode; 4688 return cmd; 4689 } 4690 return NULL; 4691 } 4692 4693 static ipfw_insn * 4694 add_src(ipfw_insn *cmd, char *av, u_char proto) 4695 { 4696 struct in6_addr a; 4697 char *host, *ch; 4698 ipfw_insn *ret = NULL; 4699 4700 if ((host = strdup(av)) == NULL) 4701 return NULL; 4702 if ((ch = strrchr(host, '/')) != NULL) 4703 *ch = '\0'; 4704 4705 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4706 inet_pton(AF_INET6, host, &a)) 4707 ret = add_srcip6(cmd, av); 4708 /* XXX: should check for IPv4, not !IPv6 */ 4709 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4710 !inet_pton(AF_INET6, host, &a))) 4711 ret = add_srcip(cmd, av); 4712 if (ret == NULL && strcmp(av, "any") != 0) 4713 ret = cmd; 4714 4715 free(host); 4716 return ret; 4717 } 4718 4719 static ipfw_insn * 4720 add_dst(ipfw_insn *cmd, char *av, u_char proto) 4721 { 4722 struct in6_addr a; 4723 char *host, *ch; 4724 ipfw_insn *ret = NULL; 4725 4726 if ((host = strdup(av)) == NULL) 4727 return NULL; 4728 if ((ch = strrchr(host, '/')) != NULL) 4729 *ch = '\0'; 4730 4731 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4732 inet_pton(AF_INET6, host, &a)) 4733 ret = add_dstip6(cmd, av); 4734 /* XXX: should check for IPv4, not !IPv6 */ 4735 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4736 !inet_pton(AF_INET6, host, &a))) 4737 ret = add_dstip(cmd, av); 4738 if (ret == NULL && strcmp(av, "any") != 0) 4739 ret = cmd; 4740 4741 free(host); 4742 return ret; 4743 } 4744 4745 /* 4746 * Parse arguments and assemble the microinstructions which make up a rule. 4747 * Rules are added into the 'rulebuf' and then copied in the correct order 4748 * into the actual rule. 4749 * 4750 * The syntax for a rule starts with the action, followed by 4751 * optional action parameters, and the various match patterns. 4752 * In the assembled microcode, the first opcode must be an O_PROBE_STATE 4753 * (generated if the rule includes a keep-state option), then the 4754 * various match patterns, log/altq actions, and the actual action. 4755 * 4756 */ 4757 static void 4758 add(int ac, char *av[]) 4759 { 4760 /* 4761 * rules are added into the 'rulebuf' and then copied in 4762 * the correct order into the actual rule. 4763 * Some things that need to go out of order (prob, action etc.) 4764 * go into actbuf[]. 4765 */ 4766 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255]; 4767 4768 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL; 4769 ipfw_insn *first_cmd; /* first match pattern */ 4770 4771 struct ip_fw *rule; 4772 4773 /* 4774 * various flags used to record that we entered some fields. 4775 */ 4776 ipfw_insn *have_state = NULL; /* check-state or keep-state */ 4777 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL; 4778 size_t len; 4779 4780 int i; 4781 4782 int open_par = 0; /* open parenthesis ( */ 4783 4784 /* proto is here because it is used to fetch ports */ 4785 u_char proto = IPPROTO_IP; /* default protocol */ 4786 4787 double match_prob = 1; /* match probability, default is always match */ 4788 4789 bzero(actbuf, sizeof(actbuf)); /* actions go here */ 4790 bzero(cmdbuf, sizeof(cmdbuf)); 4791 bzero(rulebuf, sizeof(rulebuf)); 4792 4793 rule = (struct ip_fw *)rulebuf; 4794 cmd = (ipfw_insn *)cmdbuf; 4795 action = (ipfw_insn *)actbuf; 4796 4797 av++; ac--; 4798 4799 /* [rule N] -- Rule number optional */ 4800 if (ac && isdigit(**av)) { 4801 rule->rulenum = atoi(*av); 4802 av++; 4803 ac--; 4804 } 4805 4806 /* [set N] -- set number (0..RESVD_SET), optional */ 4807 if (ac > 1 && _substrcmp(*av, "set") == 0) { 4808 int set = strtoul(av[1], NULL, 10); 4809 if (set < 0 || set > RESVD_SET) 4810 errx(EX_DATAERR, "illegal set %s", av[1]); 4811 rule->set = set; 4812 av += 2; ac -= 2; 4813 } 4814 4815 /* [prob D] -- match probability, optional */ 4816 if (ac > 1 && _substrcmp(*av, "prob") == 0) { 4817 match_prob = strtod(av[1], NULL); 4818 4819 if (match_prob <= 0 || match_prob > 1) 4820 errx(EX_DATAERR, "illegal match prob. %s", av[1]); 4821 av += 2; ac -= 2; 4822 } 4823 4824 /* action -- mandatory */ 4825 NEED1("missing action"); 4826 i = match_token(rule_actions, *av); 4827 ac--; av++; 4828 action->len = 1; /* default */ 4829 switch(i) { 4830 case TOK_CHECKSTATE: 4831 have_state = action; 4832 action->opcode = O_CHECK_STATE; 4833 break; 4834 4835 case TOK_ACCEPT: 4836 action->opcode = O_ACCEPT; 4837 break; 4838 4839 case TOK_DENY: 4840 action->opcode = O_DENY; 4841 action->arg1 = 0; 4842 break; 4843 4844 case TOK_REJECT: 4845 action->opcode = O_REJECT; 4846 action->arg1 = ICMP_UNREACH_HOST; 4847 break; 4848 4849 case TOK_RESET: 4850 action->opcode = O_REJECT; 4851 action->arg1 = ICMP_REJECT_RST; 4852 break; 4853 4854 case TOK_RESET6: 4855 action->opcode = O_UNREACH6; 4856 action->arg1 = ICMP6_UNREACH_RST; 4857 break; 4858 4859 case TOK_UNREACH: 4860 action->opcode = O_REJECT; 4861 NEED1("missing reject code"); 4862 fill_reject_code(&action->arg1, *av); 4863 ac--; av++; 4864 break; 4865 4866 case TOK_UNREACH6: 4867 action->opcode = O_UNREACH6; 4868 NEED1("missing unreach code"); 4869 fill_unreach6_code(&action->arg1, *av); 4870 ac--; av++; 4871 break; 4872 4873 case TOK_COUNT: 4874 action->opcode = O_COUNT; 4875 break; 4876 4877 case TOK_NAT: 4878 action->opcode = O_NAT; 4879 action->len = F_INSN_SIZE(ipfw_insn_nat); 4880 goto chkarg; 4881 4882 case TOK_QUEUE: 4883 action->opcode = O_QUEUE; 4884 goto chkarg; 4885 case TOK_PIPE: 4886 action->opcode = O_PIPE; 4887 goto chkarg; 4888 case TOK_SKIPTO: 4889 action->opcode = O_SKIPTO; 4890 goto chkarg; 4891 case TOK_NETGRAPH: 4892 action->opcode = O_NETGRAPH; 4893 goto chkarg; 4894 case TOK_NGTEE: 4895 action->opcode = O_NGTEE; 4896 goto chkarg; 4897 case TOK_DIVERT: 4898 action->opcode = O_DIVERT; 4899 goto chkarg; 4900 case TOK_TEE: 4901 action->opcode = O_TEE; 4902 chkarg: 4903 if (!ac) 4904 errx(EX_USAGE, "missing argument for %s", *(av - 1)); 4905 if (isdigit(**av)) { 4906 action->arg1 = strtoul(*av, NULL, 10); 4907 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG) 4908 errx(EX_DATAERR, "illegal argument for %s", 4909 *(av - 1)); 4910 } else if (_substrcmp(*av, TABLEARG) == 0) { 4911 action->arg1 = IP_FW_TABLEARG; 4912 } else if (i == TOK_DIVERT || i == TOK_TEE) { 4913 struct servent *s; 4914 setservent(1); 4915 s = getservbyname(av[0], "divert"); 4916 if (s != NULL) 4917 action->arg1 = ntohs(s->s_port); 4918 else 4919 errx(EX_DATAERR, "illegal divert/tee port"); 4920 } else 4921 errx(EX_DATAERR, "illegal argument for %s", *(av - 1)); 4922 ac--; av++; 4923 break; 4924 4925 case TOK_FORWARD: { 4926 ipfw_insn_sa *p = (ipfw_insn_sa *)action; 4927 char *s, *end; 4928 4929 NEED1("missing forward address[:port]"); 4930 4931 action->opcode = O_FORWARD_IP; 4932 action->len = F_INSN_SIZE(ipfw_insn_sa); 4933 4934 p->sa.sin_len = sizeof(struct sockaddr_in); 4935 p->sa.sin_family = AF_INET; 4936 p->sa.sin_port = 0; 4937 /* 4938 * locate the address-port separator (':' or ',') 4939 */ 4940 s = strchr(*av, ':'); 4941 if (s == NULL) 4942 s = strchr(*av, ','); 4943 if (s != NULL) { 4944 *(s++) = '\0'; 4945 i = strtoport(s, &end, 0 /* base */, 0 /* proto */); 4946 if (s == end) 4947 errx(EX_DATAERR, 4948 "illegal forwarding port ``%s''", s); 4949 p->sa.sin_port = (u_short)i; 4950 } 4951 if (_substrcmp(*av, "tablearg") == 0) 4952 p->sa.sin_addr.s_addr = INADDR_ANY; 4953 else 4954 lookup_host(*av, &(p->sa.sin_addr)); 4955 ac--; av++; 4956 break; 4957 } 4958 case TOK_COMMENT: 4959 /* pretend it is a 'count' rule followed by the comment */ 4960 action->opcode = O_COUNT; 4961 ac++; av--; /* go back... */ 4962 break; 4963 4964 case TOK_SETFIB: 4965 { 4966 int numfibs; 4967 size_t intsize = sizeof(int); 4968 4969 action->opcode = O_SETFIB; 4970 NEED1("missing fib number"); 4971 action->arg1 = strtoul(*av, NULL, 10); 4972 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1) 4973 errx(EX_DATAERR, "fibs not suported.\n"); 4974 if (action->arg1 >= numfibs) /* Temporary */ 4975 errx(EX_DATAERR, "fib too large.\n"); 4976 ac--; av++; 4977 break; 4978 } 4979 4980 default: 4981 errx(EX_DATAERR, "invalid action %s\n", av[-1]); 4982 } 4983 action = next_cmd(action); 4984 4985 /* 4986 * [altq queuename] -- altq tag, optional 4987 * [log [logamount N]] -- log, optional 4988 * 4989 * If they exist, it go first in the cmdbuf, but then it is 4990 * skipped in the copy section to the end of the buffer. 4991 */ 4992 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) { 4993 ac--; av++; 4994 switch (i) { 4995 case TOK_LOG: 4996 { 4997 ipfw_insn_log *c = (ipfw_insn_log *)cmd; 4998 int l; 4999 5000 if (have_log) 5001 errx(EX_DATAERR, 5002 "log cannot be specified more than once"); 5003 have_log = (ipfw_insn *)c; 5004 cmd->len = F_INSN_SIZE(ipfw_insn_log); 5005 cmd->opcode = O_LOG; 5006 if (ac && _substrcmp(*av, "logamount") == 0) { 5007 ac--; av++; 5008 NEED1("logamount requires argument"); 5009 l = atoi(*av); 5010 if (l < 0) 5011 errx(EX_DATAERR, 5012 "logamount must be positive"); 5013 c->max_log = l; 5014 ac--; av++; 5015 } else { 5016 len = sizeof(c->max_log); 5017 if (sysctlbyname("net.inet.ip.fw.verbose_limit", 5018 &c->max_log, &len, NULL, 0) == -1) 5019 errx(1, "sysctlbyname(\"%s\")", 5020 "net.inet.ip.fw.verbose_limit"); 5021 } 5022 } 5023 break; 5024 5025 case TOK_ALTQ: 5026 { 5027 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd; 5028 5029 NEED1("missing altq queue name"); 5030 if (have_altq) 5031 errx(EX_DATAERR, 5032 "altq cannot be specified more than once"); 5033 have_altq = (ipfw_insn *)a; 5034 cmd->len = F_INSN_SIZE(ipfw_insn_altq); 5035 cmd->opcode = O_ALTQ; 5036 fill_altq_qid(&a->qid, *av); 5037 ac--; av++; 5038 } 5039 break; 5040 5041 case TOK_TAG: 5042 case TOK_UNTAG: { 5043 uint16_t tag; 5044 5045 if (have_tag) 5046 errx(EX_USAGE, "tag and untag cannot be " 5047 "specified more than once"); 5048 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1, i, 5049 rule_action_params); 5050 have_tag = cmd; 5051 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag); 5052 ac--; av++; 5053 break; 5054 } 5055 5056 default: 5057 abort(); 5058 } 5059 cmd = next_cmd(cmd); 5060 } 5061 5062 if (have_state) /* must be a check-state, we are done */ 5063 goto done; 5064 5065 #define OR_START(target) \ 5066 if (ac && (*av[0] == '(' || *av[0] == '{')) { \ 5067 if (open_par) \ 5068 errx(EX_USAGE, "nested \"(\" not allowed\n"); \ 5069 prev = NULL; \ 5070 open_par = 1; \ 5071 if ( (av[0])[1] == '\0') { \ 5072 ac--; av++; \ 5073 } else \ 5074 (*av)++; \ 5075 } \ 5076 target: \ 5077 5078 5079 #define CLOSE_PAR \ 5080 if (open_par) { \ 5081 if (ac && ( \ 5082 strcmp(*av, ")") == 0 || \ 5083 strcmp(*av, "}") == 0)) { \ 5084 prev = NULL; \ 5085 open_par = 0; \ 5086 ac--; av++; \ 5087 } else \ 5088 errx(EX_USAGE, "missing \")\"\n"); \ 5089 } 5090 5091 #define NOT_BLOCK \ 5092 if (ac && _substrcmp(*av, "not") == 0) { \ 5093 if (cmd->len & F_NOT) \ 5094 errx(EX_USAGE, "double \"not\" not allowed\n"); \ 5095 cmd->len |= F_NOT; \ 5096 ac--; av++; \ 5097 } 5098 5099 #define OR_BLOCK(target) \ 5100 if (ac && _substrcmp(*av, "or") == 0) { \ 5101 if (prev == NULL || open_par == 0) \ 5102 errx(EX_DATAERR, "invalid OR block"); \ 5103 prev->len |= F_OR; \ 5104 ac--; av++; \ 5105 goto target; \ 5106 } \ 5107 CLOSE_PAR; 5108 5109 first_cmd = cmd; 5110 5111 #if 0 5112 /* 5113 * MAC addresses, optional. 5114 * If we have this, we skip the part "proto from src to dst" 5115 * and jump straight to the option parsing. 5116 */ 5117 NOT_BLOCK; 5118 NEED1("missing protocol"); 5119 if (_substrcmp(*av, "MAC") == 0 || 5120 _substrcmp(*av, "mac") == 0) { 5121 ac--; av++; /* the "MAC" keyword */ 5122 add_mac(cmd, ac, av); /* exits in case of errors */ 5123 cmd = next_cmd(cmd); 5124 ac -= 2; av += 2; /* dst-mac and src-mac */ 5125 NOT_BLOCK; 5126 NEED1("missing mac type"); 5127 if (add_mactype(cmd, ac, av[0])) 5128 cmd = next_cmd(cmd); 5129 ac--; av++; /* any or mac-type */ 5130 goto read_options; 5131 } 5132 #endif 5133 5134 /* 5135 * protocol, mandatory 5136 */ 5137 OR_START(get_proto); 5138 NOT_BLOCK; 5139 NEED1("missing protocol"); 5140 if (add_proto_compat(cmd, *av, &proto)) { 5141 av++; ac--; 5142 if (F_LEN(cmd) != 0) { 5143 prev = cmd; 5144 cmd = next_cmd(cmd); 5145 } 5146 } else if (first_cmd != cmd) { 5147 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 5148 } else 5149 goto read_options; 5150 OR_BLOCK(get_proto); 5151 5152 /* 5153 * "from", mandatory 5154 */ 5155 if (!ac || _substrcmp(*av, "from") != 0) 5156 errx(EX_USAGE, "missing ``from''"); 5157 ac--; av++; 5158 5159 /* 5160 * source IP, mandatory 5161 */ 5162 OR_START(source_ip); 5163 NOT_BLOCK; /* optional "not" */ 5164 NEED1("missing source address"); 5165 if (add_src(cmd, *av, proto)) { 5166 ac--; av++; 5167 if (F_LEN(cmd) != 0) { /* ! any */ 5168 prev = cmd; 5169 cmd = next_cmd(cmd); 5170 } 5171 } else 5172 errx(EX_USAGE, "bad source address %s", *av); 5173 OR_BLOCK(source_ip); 5174 5175 /* 5176 * source ports, optional 5177 */ 5178 NOT_BLOCK; /* optional "not" */ 5179 if (ac) { 5180 if (_substrcmp(*av, "any") == 0 || 5181 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5182 ac--; av++; 5183 if (F_LEN(cmd) != 0) 5184 cmd = next_cmd(cmd); 5185 } 5186 } 5187 5188 /* 5189 * "to", mandatory 5190 */ 5191 if (!ac || _substrcmp(*av, "to") != 0) 5192 errx(EX_USAGE, "missing ``to''"); 5193 av++; ac--; 5194 5195 /* 5196 * destination, mandatory 5197 */ 5198 OR_START(dest_ip); 5199 NOT_BLOCK; /* optional "not" */ 5200 NEED1("missing dst address"); 5201 if (add_dst(cmd, *av, proto)) { 5202 ac--; av++; 5203 if (F_LEN(cmd) != 0) { /* ! any */ 5204 prev = cmd; 5205 cmd = next_cmd(cmd); 5206 } 5207 } else 5208 errx( EX_USAGE, "bad destination address %s", *av); 5209 OR_BLOCK(dest_ip); 5210 5211 /* 5212 * dest. ports, optional 5213 */ 5214 NOT_BLOCK; /* optional "not" */ 5215 if (ac) { 5216 if (_substrcmp(*av, "any") == 0 || 5217 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5218 ac--; av++; 5219 if (F_LEN(cmd) != 0) 5220 cmd = next_cmd(cmd); 5221 } 5222 } 5223 5224 read_options: 5225 if (ac && first_cmd == cmd) { 5226 /* 5227 * nothing specified so far, store in the rule to ease 5228 * printout later. 5229 */ 5230 rule->_pad = 1; 5231 } 5232 prev = NULL; 5233 while (ac) { 5234 char *s; 5235 ipfw_insn_u32 *cmd32; /* alias for cmd */ 5236 5237 s = *av; 5238 cmd32 = (ipfw_insn_u32 *)cmd; 5239 5240 if (*s == '!') { /* alternate syntax for NOT */ 5241 if (cmd->len & F_NOT) 5242 errx(EX_USAGE, "double \"not\" not allowed\n"); 5243 cmd->len = F_NOT; 5244 s++; 5245 } 5246 i = match_token(rule_options, s); 5247 ac--; av++; 5248 switch(i) { 5249 case TOK_NOT: 5250 if (cmd->len & F_NOT) 5251 errx(EX_USAGE, "double \"not\" not allowed\n"); 5252 cmd->len = F_NOT; 5253 break; 5254 5255 case TOK_OR: 5256 if (open_par == 0 || prev == NULL) 5257 errx(EX_USAGE, "invalid \"or\" block\n"); 5258 prev->len |= F_OR; 5259 break; 5260 5261 case TOK_STARTBRACE: 5262 if (open_par) 5263 errx(EX_USAGE, "+nested \"(\" not allowed\n"); 5264 open_par = 1; 5265 break; 5266 5267 case TOK_ENDBRACE: 5268 if (!open_par) 5269 errx(EX_USAGE, "+missing \")\"\n"); 5270 open_par = 0; 5271 prev = NULL; 5272 break; 5273 5274 case TOK_IN: 5275 fill_cmd(cmd, O_IN, 0, 0); 5276 break; 5277 5278 case TOK_OUT: 5279 cmd->len ^= F_NOT; /* toggle F_NOT */ 5280 fill_cmd(cmd, O_IN, 0, 0); 5281 break; 5282 5283 case TOK_DIVERTED: 5284 fill_cmd(cmd, O_DIVERTED, 0, 3); 5285 break; 5286 5287 case TOK_DIVERTEDLOOPBACK: 5288 fill_cmd(cmd, O_DIVERTED, 0, 1); 5289 break; 5290 5291 case TOK_DIVERTEDOUTPUT: 5292 fill_cmd(cmd, O_DIVERTED, 0, 2); 5293 break; 5294 5295 case TOK_FRAG: 5296 fill_cmd(cmd, O_FRAG, 0, 0); 5297 break; 5298 5299 case TOK_LAYER2: 5300 fill_cmd(cmd, O_LAYER2, 0, 0); 5301 break; 5302 5303 case TOK_XMIT: 5304 case TOK_RECV: 5305 case TOK_VIA: 5306 NEED1("recv, xmit, via require interface name" 5307 " or address"); 5308 fill_iface((ipfw_insn_if *)cmd, av[0]); 5309 ac--; av++; 5310 if (F_LEN(cmd) == 0) /* not a valid address */ 5311 break; 5312 if (i == TOK_XMIT) 5313 cmd->opcode = O_XMIT; 5314 else if (i == TOK_RECV) 5315 cmd->opcode = O_RECV; 5316 else if (i == TOK_VIA) 5317 cmd->opcode = O_VIA; 5318 break; 5319 5320 case TOK_ICMPTYPES: 5321 NEED1("icmptypes requires list of types"); 5322 fill_icmptypes((ipfw_insn_u32 *)cmd, *av); 5323 av++; ac--; 5324 break; 5325 5326 case TOK_ICMP6TYPES: 5327 NEED1("icmptypes requires list of types"); 5328 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av); 5329 av++; ac--; 5330 break; 5331 5332 case TOK_IPTTL: 5333 NEED1("ipttl requires TTL"); 5334 if (strpbrk(*av, "-,")) { 5335 if (!add_ports(cmd, *av, 0, O_IPTTL)) 5336 errx(EX_DATAERR, "invalid ipttl %s", *av); 5337 } else 5338 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0)); 5339 ac--; av++; 5340 break; 5341 5342 case TOK_IPID: 5343 NEED1("ipid requires id"); 5344 if (strpbrk(*av, "-,")) { 5345 if (!add_ports(cmd, *av, 0, O_IPID)) 5346 errx(EX_DATAERR, "invalid ipid %s", *av); 5347 } else 5348 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0)); 5349 ac--; av++; 5350 break; 5351 5352 case TOK_IPLEN: 5353 NEED1("iplen requires length"); 5354 if (strpbrk(*av, "-,")) { 5355 if (!add_ports(cmd, *av, 0, O_IPLEN)) 5356 errx(EX_DATAERR, "invalid ip len %s", *av); 5357 } else 5358 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0)); 5359 ac--; av++; 5360 break; 5361 5362 case TOK_IPVER: 5363 NEED1("ipver requires version"); 5364 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0)); 5365 ac--; av++; 5366 break; 5367 5368 case TOK_IPPRECEDENCE: 5369 NEED1("ipprecedence requires value"); 5370 fill_cmd(cmd, O_IPPRECEDENCE, 0, 5371 (strtoul(*av, NULL, 0) & 7) << 5); 5372 ac--; av++; 5373 break; 5374 5375 case TOK_IPOPTS: 5376 NEED1("missing argument for ipoptions"); 5377 fill_flags(cmd, O_IPOPT, f_ipopts, *av); 5378 ac--; av++; 5379 break; 5380 5381 case TOK_IPTOS: 5382 NEED1("missing argument for iptos"); 5383 fill_flags(cmd, O_IPTOS, f_iptos, *av); 5384 ac--; av++; 5385 break; 5386 5387 case TOK_UID: 5388 NEED1("uid requires argument"); 5389 { 5390 char *end; 5391 uid_t uid; 5392 struct passwd *pwd; 5393 5394 cmd->opcode = O_UID; 5395 uid = strtoul(*av, &end, 0); 5396 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av); 5397 if (pwd == NULL) 5398 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av); 5399 cmd32->d[0] = pwd->pw_uid; 5400 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5401 ac--; av++; 5402 } 5403 break; 5404 5405 case TOK_GID: 5406 NEED1("gid requires argument"); 5407 { 5408 char *end; 5409 gid_t gid; 5410 struct group *grp; 5411 5412 cmd->opcode = O_GID; 5413 gid = strtoul(*av, &end, 0); 5414 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av); 5415 if (grp == NULL) 5416 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av); 5417 cmd32->d[0] = grp->gr_gid; 5418 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5419 ac--; av++; 5420 } 5421 break; 5422 5423 case TOK_JAIL: 5424 NEED1("jail requires argument"); 5425 { 5426 char *end; 5427 int jid; 5428 5429 cmd->opcode = O_JAIL; 5430 jid = (int)strtol(*av, &end, 0); 5431 if (jid < 0 || *end != '\0') 5432 errx(EX_DATAERR, "jail requires prison ID"); 5433 cmd32->d[0] = (uint32_t)jid; 5434 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5435 ac--; av++; 5436 } 5437 break; 5438 5439 case TOK_ESTAB: 5440 fill_cmd(cmd, O_ESTAB, 0, 0); 5441 break; 5442 5443 case TOK_SETUP: 5444 fill_cmd(cmd, O_TCPFLAGS, 0, 5445 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 ); 5446 break; 5447 5448 case TOK_TCPDATALEN: 5449 NEED1("tcpdatalen requires length"); 5450 if (strpbrk(*av, "-,")) { 5451 if (!add_ports(cmd, *av, 0, O_TCPDATALEN)) 5452 errx(EX_DATAERR, "invalid tcpdata len %s", *av); 5453 } else 5454 fill_cmd(cmd, O_TCPDATALEN, 0, 5455 strtoul(*av, NULL, 0)); 5456 ac--; av++; 5457 break; 5458 5459 case TOK_TCPOPTS: 5460 NEED1("missing argument for tcpoptions"); 5461 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av); 5462 ac--; av++; 5463 break; 5464 5465 case TOK_TCPSEQ: 5466 case TOK_TCPACK: 5467 NEED1("tcpseq/tcpack requires argument"); 5468 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 5469 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK; 5470 cmd32->d[0] = htonl(strtoul(*av, NULL, 0)); 5471 ac--; av++; 5472 break; 5473 5474 case TOK_TCPWIN: 5475 NEED1("tcpwin requires length"); 5476 fill_cmd(cmd, O_TCPWIN, 0, 5477 htons(strtoul(*av, NULL, 0))); 5478 ac--; av++; 5479 break; 5480 5481 case TOK_TCPFLAGS: 5482 NEED1("missing argument for tcpflags"); 5483 cmd->opcode = O_TCPFLAGS; 5484 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av); 5485 ac--; av++; 5486 break; 5487 5488 case TOK_KEEPSTATE: 5489 if (open_par) 5490 errx(EX_USAGE, "keep-state cannot be part " 5491 "of an or block"); 5492 if (have_state) 5493 errx(EX_USAGE, "only one of keep-state " 5494 "and limit is allowed"); 5495 have_state = cmd; 5496 fill_cmd(cmd, O_KEEP_STATE, 0, 0); 5497 break; 5498 5499 case TOK_LIMIT: { 5500 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 5501 int val; 5502 5503 if (open_par) 5504 errx(EX_USAGE, 5505 "limit cannot be part of an or block"); 5506 if (have_state) 5507 errx(EX_USAGE, "only one of keep-state and " 5508 "limit is allowed"); 5509 have_state = cmd; 5510 5511 cmd->len = F_INSN_SIZE(ipfw_insn_limit); 5512 cmd->opcode = O_LIMIT; 5513 c->limit_mask = c->conn_limit = 0; 5514 5515 while (ac > 0) { 5516 if ((val = match_token(limit_masks, *av)) <= 0) 5517 break; 5518 c->limit_mask |= val; 5519 ac--; av++; 5520 } 5521 5522 if (c->limit_mask == 0) 5523 errx(EX_USAGE, "limit: missing limit mask"); 5524 5525 GET_UINT_ARG(c->conn_limit, 1, IPFW_DEFAULT_RULE - 1, 5526 TOK_LIMIT, rule_options); 5527 5528 ac--; av++; 5529 break; 5530 } 5531 5532 case TOK_PROTO: 5533 NEED1("missing protocol"); 5534 if (add_proto(cmd, *av, &proto)) { 5535 ac--; av++; 5536 } else 5537 errx(EX_DATAERR, "invalid protocol ``%s''", 5538 *av); 5539 break; 5540 5541 case TOK_SRCIP: 5542 NEED1("missing source IP"); 5543 if (add_srcip(cmd, *av)) { 5544 ac--; av++; 5545 } 5546 break; 5547 5548 case TOK_DSTIP: 5549 NEED1("missing destination IP"); 5550 if (add_dstip(cmd, *av)) { 5551 ac--; av++; 5552 } 5553 break; 5554 5555 case TOK_SRCIP6: 5556 NEED1("missing source IP6"); 5557 if (add_srcip6(cmd, *av)) { 5558 ac--; av++; 5559 } 5560 break; 5561 5562 case TOK_DSTIP6: 5563 NEED1("missing destination IP6"); 5564 if (add_dstip6(cmd, *av)) { 5565 ac--; av++; 5566 } 5567 break; 5568 5569 case TOK_SRCPORT: 5570 NEED1("missing source port"); 5571 if (_substrcmp(*av, "any") == 0 || 5572 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5573 ac--; av++; 5574 } else 5575 errx(EX_DATAERR, "invalid source port %s", *av); 5576 break; 5577 5578 case TOK_DSTPORT: 5579 NEED1("missing destination port"); 5580 if (_substrcmp(*av, "any") == 0 || 5581 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5582 ac--; av++; 5583 } else 5584 errx(EX_DATAERR, "invalid destination port %s", 5585 *av); 5586 break; 5587 5588 case TOK_MAC: 5589 if (add_mac(cmd, ac, av)) { 5590 ac -= 2; av += 2; 5591 } 5592 break; 5593 5594 case TOK_MACTYPE: 5595 NEED1("missing mac type"); 5596 if (!add_mactype(cmd, ac, *av)) 5597 errx(EX_DATAERR, "invalid mac type %s", *av); 5598 ac--; av++; 5599 break; 5600 5601 case TOK_VERREVPATH: 5602 fill_cmd(cmd, O_VERREVPATH, 0, 0); 5603 break; 5604 5605 case TOK_VERSRCREACH: 5606 fill_cmd(cmd, O_VERSRCREACH, 0, 0); 5607 break; 5608 5609 case TOK_ANTISPOOF: 5610 fill_cmd(cmd, O_ANTISPOOF, 0, 0); 5611 break; 5612 5613 case TOK_IPSEC: 5614 fill_cmd(cmd, O_IPSEC, 0, 0); 5615 break; 5616 5617 case TOK_IPV6: 5618 fill_cmd(cmd, O_IP6, 0, 0); 5619 break; 5620 5621 case TOK_IPV4: 5622 fill_cmd(cmd, O_IP4, 0, 0); 5623 break; 5624 5625 case TOK_EXT6HDR: 5626 fill_ext6hdr( cmd, *av ); 5627 ac--; av++; 5628 break; 5629 5630 case TOK_FLOWID: 5631 if (proto != IPPROTO_IPV6 ) 5632 errx( EX_USAGE, "flow-id filter is active " 5633 "only for ipv6 protocol\n"); 5634 fill_flow6( (ipfw_insn_u32 *) cmd, *av ); 5635 ac--; av++; 5636 break; 5637 5638 case TOK_COMMENT: 5639 fill_comment(cmd, ac, av); 5640 av += ac; 5641 ac = 0; 5642 break; 5643 5644 case TOK_TAGGED: 5645 if (ac > 0 && strpbrk(*av, "-,")) { 5646 if (!add_ports(cmd, *av, 0, O_TAGGED)) 5647 errx(EX_DATAERR, "tagged: invalid tag" 5648 " list: %s", *av); 5649 } 5650 else { 5651 uint16_t tag; 5652 5653 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1, 5654 TOK_TAGGED, rule_options); 5655 fill_cmd(cmd, O_TAGGED, 0, tag); 5656 } 5657 ac--; av++; 5658 break; 5659 5660 case TOK_FIB: 5661 NEED1("fib requires fib number"); 5662 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0)); 5663 ac--; av++; 5664 break; 5665 5666 default: 5667 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s); 5668 } 5669 if (F_LEN(cmd) > 0) { /* prepare to advance */ 5670 prev = cmd; 5671 cmd = next_cmd(cmd); 5672 } 5673 } 5674 5675 done: 5676 /* 5677 * Now copy stuff into the rule. 5678 * If we have a keep-state option, the first instruction 5679 * must be a PROBE_STATE (which is generated here). 5680 * If we have a LOG option, it was stored as the first command, 5681 * and now must be moved to the top of the action part. 5682 */ 5683 dst = (ipfw_insn *)rule->cmd; 5684 5685 /* 5686 * First thing to write into the command stream is the match probability. 5687 */ 5688 if (match_prob != 1) { /* 1 means always match */ 5689 dst->opcode = O_PROB; 5690 dst->len = 2; 5691 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff); 5692 dst += dst->len; 5693 } 5694 5695 /* 5696 * generate O_PROBE_STATE if necessary 5697 */ 5698 if (have_state && have_state->opcode != O_CHECK_STATE) { 5699 fill_cmd(dst, O_PROBE_STATE, 0, 0); 5700 dst = next_cmd(dst); 5701 } 5702 5703 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */ 5704 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) { 5705 i = F_LEN(src); 5706 5707 switch (src->opcode) { 5708 case O_LOG: 5709 case O_KEEP_STATE: 5710 case O_LIMIT: 5711 case O_ALTQ: 5712 case O_TAG: 5713 break; 5714 default: 5715 bcopy(src, dst, i * sizeof(uint32_t)); 5716 dst += i; 5717 } 5718 } 5719 5720 /* 5721 * put back the have_state command as last opcode 5722 */ 5723 if (have_state && have_state->opcode != O_CHECK_STATE) { 5724 i = F_LEN(have_state); 5725 bcopy(have_state, dst, i * sizeof(uint32_t)); 5726 dst += i; 5727 } 5728 /* 5729 * start action section 5730 */ 5731 rule->act_ofs = dst - rule->cmd; 5732 5733 /* put back O_LOG, O_ALTQ, O_TAG if necessary */ 5734 if (have_log) { 5735 i = F_LEN(have_log); 5736 bcopy(have_log, dst, i * sizeof(uint32_t)); 5737 dst += i; 5738 } 5739 if (have_altq) { 5740 i = F_LEN(have_altq); 5741 bcopy(have_altq, dst, i * sizeof(uint32_t)); 5742 dst += i; 5743 } 5744 if (have_tag) { 5745 i = F_LEN(have_tag); 5746 bcopy(have_tag, dst, i * sizeof(uint32_t)); 5747 dst += i; 5748 } 5749 /* 5750 * copy all other actions 5751 */ 5752 for (src = (ipfw_insn *)actbuf; src != action; src += i) { 5753 i = F_LEN(src); 5754 bcopy(src, dst, i * sizeof(uint32_t)); 5755 dst += i; 5756 } 5757 5758 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd); 5759 i = (char *)dst - (char *)rule; 5760 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1) 5761 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD"); 5762 if (!do_quiet) 5763 show_ipfw(rule, 0, 0); 5764 } 5765 5766 static void 5767 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */) 5768 { 5769 uint32_t arg, saved_arg; 5770 int failed = EX_OK; 5771 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG"; 5772 char const *errstr; 5773 5774 av++; ac--; 5775 5776 if (!ac) { 5777 /* clear all entries */ 5778 if (do_cmd(optname, NULL, 0) < 0) 5779 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name); 5780 if (!do_quiet) 5781 printf("%s.\n", optname == IP_FW_ZERO ? 5782 "Accounting cleared":"Logging counts reset"); 5783 5784 return; 5785 } 5786 5787 while (ac) { 5788 /* Rule number */ 5789 if (isdigit(**av)) { 5790 arg = strtonum(*av, 0, 0xffff, &errstr); 5791 if (errstr) 5792 errx(EX_DATAERR, 5793 "invalid rule number %s\n", *av); 5794 saved_arg = arg; 5795 if (use_set) 5796 arg |= (1 << 24) | ((use_set - 1) << 16); 5797 av++; 5798 ac--; 5799 if (do_cmd(optname, &arg, sizeof(arg))) { 5800 warn("rule %u: setsockopt(IP_FW_%s)", 5801 saved_arg, name); 5802 failed = EX_UNAVAILABLE; 5803 } else if (!do_quiet) 5804 printf("Entry %d %s.\n", saved_arg, 5805 optname == IP_FW_ZERO ? 5806 "cleared" : "logging count reset"); 5807 } else { 5808 errx(EX_USAGE, "invalid rule number ``%s''", *av); 5809 } 5810 } 5811 if (failed != EX_OK) 5812 exit(failed); 5813 } 5814 5815 static void 5816 flush(int force) 5817 { 5818 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH; 5819 5820 if (!force && !do_quiet) { /* need to ask user */ 5821 int c; 5822 5823 printf("Are you sure? [yn] "); 5824 fflush(stdout); 5825 do { 5826 c = toupper(getc(stdin)); 5827 while (c != '\n' && getc(stdin) != '\n') 5828 if (feof(stdin)) 5829 return; /* and do not flush */ 5830 } while (c != 'Y' && c != 'N'); 5831 printf("\n"); 5832 if (c == 'N') /* user said no */ 5833 return; 5834 } 5835 /* `ipfw set N flush` - is the same that `ipfw delete set N` */ 5836 if (use_set) { 5837 uint32_t arg = ((use_set - 1) & 0xffff) | (1 << 24); 5838 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0) 5839 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)"); 5840 } else if (do_cmd(cmd, NULL, 0) < 0) 5841 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)", 5842 do_pipe ? "DUMMYNET" : "FW"); 5843 if (!do_quiet) 5844 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules"); 5845 } 5846 5847 /* 5848 * Free a the (locally allocated) copy of command line arguments. 5849 */ 5850 static void 5851 free_args(int ac, char **av) 5852 { 5853 int i; 5854 5855 for (i=0; i < ac; i++) 5856 free(av[i]); 5857 free(av); 5858 } 5859 5860 static void table_list(ipfw_table_entry ent, int need_header); 5861 5862 /* 5863 * This one handles all table-related commands 5864 * ipfw table N add addr[/masklen] [value] 5865 * ipfw table N delete addr[/masklen] 5866 * ipfw table {N | all} flush 5867 * ipfw table {N | all} list 5868 */ 5869 static void 5870 table_handler(int ac, char *av[]) 5871 { 5872 ipfw_table_entry ent; 5873 int do_add; 5874 int is_all; 5875 size_t len; 5876 char *p; 5877 uint32_t a; 5878 uint32_t tables_max; 5879 5880 len = sizeof(tables_max); 5881 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len, 5882 NULL, 0) == -1) { 5883 #ifdef IPFW_TABLES_MAX 5884 warn("Warn: Failed to get the max tables number via sysctl. " 5885 "Using the compiled in defaults. \nThe reason was"); 5886 tables_max = IPFW_TABLES_MAX; 5887 #else 5888 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")"); 5889 #endif 5890 } 5891 5892 ac--; av++; 5893 if (ac && isdigit(**av)) { 5894 ent.tbl = atoi(*av); 5895 is_all = 0; 5896 ac--; av++; 5897 } else if (ac && _substrcmp(*av, "all") == 0) { 5898 ent.tbl = 0; 5899 is_all = 1; 5900 ac--; av++; 5901 } else 5902 errx(EX_USAGE, "table number or 'all' keyword required"); 5903 if (ent.tbl >= tables_max) 5904 errx(EX_USAGE, "The table number exceeds the maximum allowed " 5905 "value (%d)", tables_max - 1); 5906 NEED1("table needs command"); 5907 if (is_all && _substrcmp(*av, "list") != 0 5908 && _substrcmp(*av, "flush") != 0) 5909 errx(EX_USAGE, "table number required"); 5910 5911 if (_substrcmp(*av, "add") == 0 || 5912 _substrcmp(*av, "delete") == 0) { 5913 do_add = **av == 'a'; 5914 ac--; av++; 5915 if (!ac) 5916 errx(EX_USAGE, "IP address required"); 5917 p = strchr(*av, '/'); 5918 if (p) { 5919 *p++ = '\0'; 5920 ent.masklen = atoi(p); 5921 if (ent.masklen > 32) 5922 errx(EX_DATAERR, "bad width ``%s''", p); 5923 } else 5924 ent.masklen = 32; 5925 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0) 5926 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5927 ac--; av++; 5928 if (do_add && ac) { 5929 unsigned int tval; 5930 /* isdigit is a bit of a hack here.. */ 5931 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) { 5932 ent.value = strtoul(*av, NULL, 0); 5933 } else { 5934 if (lookup_host(*av, (struct in_addr *)&tval) == 0) { 5935 /* The value must be stored in host order * 5936 * so that the values < 65k can be distinguished */ 5937 ent.value = ntohl(tval); 5938 } else { 5939 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5940 } 5941 } 5942 } else 5943 ent.value = 0; 5944 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL, 5945 &ent, sizeof(ent)) < 0) { 5946 /* If running silent, don't bomb out on these errors. */ 5947 if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH)))) 5948 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)", 5949 do_add ? "ADD" : "DEL"); 5950 /* In silent mode, react to a failed add by deleting */ 5951 if (do_add) { 5952 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent)); 5953 if (do_cmd(IP_FW_TABLE_ADD, 5954 &ent, sizeof(ent)) < 0) 5955 err(EX_OSERR, 5956 "setsockopt(IP_FW_TABLE_ADD)"); 5957 } 5958 } 5959 } else if (_substrcmp(*av, "flush") == 0) { 5960 a = is_all ? tables_max : (ent.tbl + 1); 5961 do { 5962 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, 5963 sizeof(ent.tbl)) < 0) 5964 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)"); 5965 } while (++ent.tbl < a); 5966 } else if (_substrcmp(*av, "list") == 0) { 5967 a = is_all ? tables_max : (ent.tbl + 1); 5968 do { 5969 table_list(ent, is_all); 5970 } while (++ent.tbl < a); 5971 } else 5972 errx(EX_USAGE, "invalid table command %s", *av); 5973 } 5974 5975 static void 5976 table_list(ipfw_table_entry ent, int need_header) 5977 { 5978 ipfw_table *tbl; 5979 socklen_t l; 5980 uint32_t a; 5981 5982 a = ent.tbl; 5983 l = sizeof(a); 5984 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0) 5985 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)"); 5986 5987 /* If a is zero we have nothing to do, the table is empty. */ 5988 if (a == 0) 5989 return; 5990 5991 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry); 5992 tbl = malloc(l); 5993 if (tbl == NULL) 5994 err(EX_OSERR, "malloc"); 5995 tbl->tbl = ent.tbl; 5996 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0) 5997 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)"); 5998 if (tbl->cnt && need_header) 5999 printf("---table(%d)---\n", tbl->tbl); 6000 for (a = 0; a < tbl->cnt; a++) { 6001 unsigned int tval; 6002 tval = tbl->ent[a].value; 6003 if (do_value_as_ip) { 6004 char tbuf[128]; 6005 strncpy(tbuf, inet_ntoa(*(struct in_addr *) 6006 &tbl->ent[a].addr), 127); 6007 /* inet_ntoa expects network order */ 6008 tval = htonl(tval); 6009 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen, 6010 inet_ntoa(*(struct in_addr *)&tval)); 6011 } else { 6012 printf("%s/%u %u\n", 6013 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr), 6014 tbl->ent[a].masklen, tval); 6015 } 6016 } 6017 free(tbl); 6018 } 6019 6020 static void 6021 show_nat(int ac, char **av) 6022 { 6023 struct cfg_nat *n; 6024 struct cfg_redir *e; 6025 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size; 6026 int nat_cnt, redir_cnt, r; 6027 uint8_t *data, *p; 6028 char *endptr; 6029 6030 do_rule = 0; 6031 nalloc = 1024; 6032 size = 0; 6033 data = NULL; 6034 frule = 0; 6035 lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */ 6036 ac--; av++; 6037 6038 if (test_only) 6039 return; 6040 6041 /* Parse parameters. */ 6042 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) { 6043 if (!strncmp(av[0], "config", strlen(av[0]))) { 6044 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1; 6045 continue; 6046 } 6047 /* Convert command line rule #. */ 6048 frule = lrule = strtoul(av[0], &endptr, 10); 6049 if (*endptr == '-') 6050 lrule = strtoul(endptr+1, &endptr, 10); 6051 if (lrule == 0) 6052 err(EX_USAGE, "invalid rule number: %s", av[0]); 6053 do_rule = 1; 6054 } 6055 6056 nbytes = nalloc; 6057 while (nbytes >= nalloc) { 6058 nalloc = nalloc * 2; 6059 nbytes = nalloc; 6060 if ((data = realloc(data, nbytes)) == NULL) 6061 err(EX_OSERR, "realloc"); 6062 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0) 6063 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)", 6064 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG"); 6065 } 6066 if (nbytes == 0) 6067 exit(0); 6068 if (do_cfg) { 6069 nat_cnt = *((int *)data); 6070 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) { 6071 n = (struct cfg_nat *)&data[i]; 6072 if (frule <= n->id && lrule >= n->id) 6073 print_nat_config(&data[i]); 6074 i += sizeof(struct cfg_nat); 6075 for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) { 6076 e = (struct cfg_redir *)&data[i]; 6077 i += sizeof(struct cfg_redir) + e->spool_cnt * 6078 sizeof(struct cfg_spool); 6079 } 6080 } 6081 } else { 6082 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) { 6083 p = &data[i]; 6084 if (p == data + nbytes) 6085 break; 6086 bcopy(p, &r, sizeof(int)); 6087 if (do_rule) { 6088 if (!(frule <= r && lrule >= r)) 6089 continue; 6090 } 6091 printf("nat %u: %s\n", r, p+sizeof(int)); 6092 } 6093 } 6094 } 6095 6096 /* 6097 * Called with the arguments (excluding program name). 6098 * Returns 0 if successful, 1 if empty command, errx() in case of errors. 6099 */ 6100 static int 6101 ipfw_main(int oldac, char **oldav) 6102 { 6103 int ch, ac, save_ac; 6104 const char *errstr; 6105 char **av, **save_av; 6106 int do_acct = 0; /* Show packet/byte count */ 6107 6108 #define WHITESP " \t\f\v\n\r" 6109 if (oldac == 0) 6110 return 1; 6111 else if (oldac == 1) { 6112 /* 6113 * If we are called with a single string, try to split it into 6114 * arguments for subsequent parsing. 6115 * But first, remove spaces after a ',', by copying the string 6116 * in-place. 6117 */ 6118 char *arg = oldav[0]; /* The string... */ 6119 int l = strlen(arg); 6120 int copy = 0; /* 1 if we need to copy, 0 otherwise */ 6121 int i, j; 6122 for (i = j = 0; i < l; i++) { 6123 if (arg[i] == '#') /* comment marker */ 6124 break; 6125 if (copy) { 6126 arg[j++] = arg[i]; 6127 copy = !index("," WHITESP, arg[i]); 6128 } else { 6129 copy = !index(WHITESP, arg[i]); 6130 if (copy) 6131 arg[j++] = arg[i]; 6132 } 6133 } 6134 if (!copy && j > 0) /* last char was a 'blank', remove it */ 6135 j--; 6136 l = j; /* the new argument length */ 6137 arg[j++] = '\0'; 6138 if (l == 0) /* empty string! */ 6139 return 1; 6140 6141 /* 6142 * First, count number of arguments. Because of the previous 6143 * processing, this is just the number of blanks plus 1. 6144 */ 6145 for (i = 0, ac = 1; i < l; i++) 6146 if (index(WHITESP, arg[i]) != NULL) 6147 ac++; 6148 6149 av = calloc(ac, sizeof(char *)); 6150 6151 /* 6152 * Second, copy arguments from cmd[] to av[]. For each one, 6153 * j is the initial character, i is the one past the end. 6154 */ 6155 for (ac = 0, i = j = 0; i < l; i++) 6156 if (index(WHITESP, arg[i]) != NULL || i == l-1) { 6157 if (i == l-1) 6158 i++; 6159 av[ac] = calloc(i-j+1, 1); 6160 bcopy(arg+j, av[ac], i-j); 6161 ac++; 6162 j = i + 1; 6163 } 6164 } else { 6165 /* 6166 * If an argument ends with ',' join with the next one. 6167 */ 6168 int first, i, l; 6169 6170 av = calloc(oldac, sizeof(char *)); 6171 for (first = i = ac = 0, l = 0; i < oldac; i++) { 6172 char *arg = oldav[i]; 6173 int k = strlen(arg); 6174 6175 l += k; 6176 if (arg[k-1] != ',' || i == oldac-1) { 6177 /* Time to copy. */ 6178 av[ac] = calloc(l+1, 1); 6179 for (l=0; first <= i; first++) { 6180 strcat(av[ac]+l, oldav[first]); 6181 l += strlen(oldav[first]); 6182 } 6183 ac++; 6184 l = 0; 6185 first = i+1; 6186 } 6187 } 6188 } 6189 6190 /* Set the force flag for non-interactive processes */ 6191 if (!do_force) 6192 do_force = !isatty(STDIN_FILENO); 6193 6194 /* Save arguments for final freeing of memory. */ 6195 save_ac = ac; 6196 save_av = av; 6197 6198 optind = optreset = 0; 6199 while ((ch = getopt(ac, av, "abcdefhinNqs:STtv")) != -1) 6200 switch (ch) { 6201 case 'a': 6202 do_acct = 1; 6203 break; 6204 6205 case 'b': 6206 comment_only = 1; 6207 do_compact = 1; 6208 break; 6209 6210 case 'c': 6211 do_compact = 1; 6212 break; 6213 6214 case 'd': 6215 do_dynamic = 1; 6216 break; 6217 6218 case 'e': 6219 do_expired = 1; 6220 break; 6221 6222 case 'f': 6223 do_force = 1; 6224 break; 6225 6226 case 'h': /* help */ 6227 free_args(save_ac, save_av); 6228 help(); 6229 break; /* NOTREACHED */ 6230 6231 case 'i': 6232 do_value_as_ip = 1; 6233 break; 6234 6235 case 'n': 6236 test_only = 1; 6237 break; 6238 6239 case 'N': 6240 do_resolv = 1; 6241 break; 6242 6243 case 'q': 6244 do_quiet = 1; 6245 break; 6246 6247 case 's': /* sort */ 6248 do_sort = atoi(optarg); 6249 break; 6250 6251 case 'S': 6252 show_sets = 1; 6253 break; 6254 6255 case 't': 6256 do_time = 1; 6257 break; 6258 6259 case 'T': 6260 do_time = 2; /* numeric timestamp */ 6261 break; 6262 6263 case 'v': /* verbose */ 6264 verbose = 1; 6265 break; 6266 6267 default: 6268 free_args(save_ac, save_av); 6269 return 1; 6270 } 6271 6272 ac -= optind; 6273 av += optind; 6274 NEED1("bad arguments, for usage summary ``ipfw''"); 6275 6276 /* 6277 * An undocumented behaviour of ipfw1 was to allow rule numbers first, 6278 * e.g. "100 add allow ..." instead of "add 100 allow ...". 6279 * In case, swap first and second argument to get the normal form. 6280 */ 6281 if (ac > 1 && isdigit(*av[0])) { 6282 char *p = av[0]; 6283 6284 av[0] = av[1]; 6285 av[1] = p; 6286 } 6287 6288 /* 6289 * Optional: pipe, queue or nat. 6290 */ 6291 do_nat = 0; 6292 do_pipe = 0; 6293 if (!strncmp(*av, "nat", strlen(*av))) 6294 do_nat = 1; 6295 else if (!strncmp(*av, "pipe", strlen(*av))) 6296 do_pipe = 1; 6297 else if (_substrcmp(*av, "queue") == 0) 6298 do_pipe = 2; 6299 else if (!strncmp(*av, "set", strlen(*av))) { 6300 if (ac > 1 && isdigit(av[1][0])) { 6301 use_set = strtonum(av[1], 0, RESVD_SET, &errstr); 6302 if (errstr) 6303 errx(EX_DATAERR, 6304 "invalid set number %s\n", av[1]); 6305 ac -= 2; av += 2; use_set++; 6306 } 6307 } 6308 6309 if (do_pipe || do_nat) { 6310 ac--; 6311 av++; 6312 } 6313 NEED1("missing command"); 6314 6315 /* 6316 * For pipes, queues and nats we normally say 'nat|pipe NN config' 6317 * but the code is easier to parse as 'nat|pipe config NN' 6318 * so we swap the two arguments. 6319 */ 6320 if ((do_pipe || do_nat) && ac > 1 && isdigit(*av[0])) { 6321 char *p = av[0]; 6322 6323 av[0] = av[1]; 6324 av[1] = p; 6325 } 6326 6327 int try_next = 0; 6328 if (use_set == 0) { 6329 if (_substrcmp(*av, "add") == 0) 6330 add(ac, av); 6331 else if (do_nat && _substrcmp(*av, "show") == 0) 6332 show_nat(ac, av); 6333 else if (do_pipe && _substrcmp(*av, "config") == 0) 6334 config_pipe(ac, av); 6335 else if (do_nat && _substrcmp(*av, "config") == 0) 6336 config_nat(ac, av); 6337 else if (_substrcmp(*av, "set") == 0) 6338 sets_handler(ac, av); 6339 else if (_substrcmp(*av, "table") == 0) 6340 table_handler(ac, av); 6341 else if (_substrcmp(*av, "enable") == 0) 6342 sysctl_handler(ac, av, 1); 6343 else if (_substrcmp(*av, "disable") == 0) 6344 sysctl_handler(ac, av, 0); 6345 else 6346 try_next = 1; 6347 } 6348 6349 if (use_set || try_next) { 6350 if (_substrcmp(*av, "delete") == 0) 6351 delete(ac, av); 6352 else if (_substrcmp(*av, "flush") == 0) 6353 flush(do_force); 6354 else if (_substrcmp(*av, "zero") == 0) 6355 zero(ac, av, IP_FW_ZERO); 6356 else if (_substrcmp(*av, "resetlog") == 0) 6357 zero(ac, av, IP_FW_RESETLOG); 6358 else if (_substrcmp(*av, "print") == 0 || 6359 _substrcmp(*av, "list") == 0) 6360 list(ac, av, do_acct); 6361 else if (_substrcmp(*av, "show") == 0) 6362 list(ac, av, 1 /* show counters */); 6363 else 6364 errx(EX_USAGE, "bad command `%s'", *av); 6365 } 6366 6367 /* Free memory allocated in the argument parsing. */ 6368 free_args(save_ac, save_av); 6369 return 0; 6370 } 6371 6372 6373 static void 6374 ipfw_readfile(int ac, char *av[]) 6375 { 6376 #define MAX_ARGS 32 6377 char buf[BUFSIZ]; 6378 char *cmd = NULL, *filename = av[ac-1]; 6379 int c, lineno=0; 6380 FILE *f = NULL; 6381 pid_t preproc = 0; 6382 6383 filename = av[ac-1]; 6384 6385 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) { 6386 switch(c) { 6387 case 'c': 6388 do_compact = 1; 6389 break; 6390 6391 case 'f': 6392 do_force = 1; 6393 break; 6394 6395 case 'N': 6396 do_resolv = 1; 6397 break; 6398 6399 case 'n': 6400 test_only = 1; 6401 break; 6402 6403 case 'p': 6404 cmd = optarg; 6405 /* 6406 * Skip previous args and delete last one, so we 6407 * pass all but the last argument to the preprocessor 6408 * via av[optind-1] 6409 */ 6410 av += optind - 1; 6411 ac -= optind - 1; 6412 if (ac < 2) 6413 errx(EX_USAGE, "no filename argument"); 6414 av[ac-1] = NULL; 6415 fprintf(stderr, "command is %s\n", av[0]); 6416 break; 6417 6418 case 'q': 6419 do_quiet = 1; 6420 break; 6421 6422 case 'S': 6423 show_sets = 1; 6424 break; 6425 6426 default: 6427 errx(EX_USAGE, "bad arguments, for usage" 6428 " summary ``ipfw''"); 6429 } 6430 6431 if (cmd != NULL) 6432 break; 6433 } 6434 6435 if (cmd == NULL && ac != optind + 1) { 6436 fprintf(stderr, "ac %d, optind %d\n", ac, optind); 6437 errx(EX_USAGE, "extraneous filename arguments"); 6438 } 6439 6440 if ((f = fopen(filename, "r")) == NULL) 6441 err(EX_UNAVAILABLE, "fopen: %s", filename); 6442 6443 if (cmd != NULL) { /* pipe through preprocessor */ 6444 int pipedes[2]; 6445 6446 if (pipe(pipedes) == -1) 6447 err(EX_OSERR, "cannot create pipe"); 6448 6449 preproc = fork(); 6450 if (preproc == -1) 6451 err(EX_OSERR, "cannot fork"); 6452 6453 if (preproc == 0) { 6454 /* 6455 * Child, will run the preprocessor with the 6456 * file on stdin and the pipe on stdout. 6457 */ 6458 if (dup2(fileno(f), 0) == -1 6459 || dup2(pipedes[1], 1) == -1) 6460 err(EX_OSERR, "dup2()"); 6461 fclose(f); 6462 close(pipedes[1]); 6463 close(pipedes[0]); 6464 execvp(cmd, av); 6465 err(EX_OSERR, "execvp(%s) failed", cmd); 6466 } else { /* parent, will reopen f as the pipe */ 6467 fclose(f); 6468 close(pipedes[1]); 6469 if ((f = fdopen(pipedes[0], "r")) == NULL) { 6470 int savederrno = errno; 6471 6472 (void)kill(preproc, SIGTERM); 6473 errno = savederrno; 6474 err(EX_OSERR, "fdopen()"); 6475 } 6476 } 6477 } 6478 6479 while (fgets(buf, BUFSIZ, f)) { /* read commands */ 6480 char linename[10]; 6481 char *args[1]; 6482 6483 lineno++; 6484 sprintf(linename, "Line %d", lineno); 6485 setprogname(linename); /* XXX */ 6486 args[0] = buf; 6487 ipfw_main(1, args); 6488 } 6489 fclose(f); 6490 if (cmd != NULL) { 6491 int status; 6492 6493 if (waitpid(preproc, &status, 0) == -1) 6494 errx(EX_OSERR, "waitpid()"); 6495 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 6496 errx(EX_UNAVAILABLE, 6497 "preprocessor exited with status %d", 6498 WEXITSTATUS(status)); 6499 else if (WIFSIGNALED(status)) 6500 errx(EX_UNAVAILABLE, 6501 "preprocessor exited with signal %d", 6502 WTERMSIG(status)); 6503 } 6504 } 6505 6506 int 6507 main(int ac, char *av[]) 6508 { 6509 /* 6510 * If the last argument is an absolute pathname, interpret it 6511 * as a file to be preprocessed. 6512 */ 6513 6514 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) 6515 ipfw_readfile(ac, av); 6516 else { 6517 if (ipfw_main(ac-1, av+1)) 6518 show_usage(); 6519 } 6520 return EX_OK; 6521 } 6522