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