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 *t = NULL, *p = strpbrk(av, "/:,{"); 2767 int masklen; 2768 char md, nd; 2769 2770 if (p) { 2771 md = *p; 2772 *p++ = '\0'; 2773 if ((t = strpbrk(p, ",{")) != NULL) { 2774 nd = *t; 2775 *t = '\0'; 2776 } 2777 } else 2778 md = '\0'; 2779 2780 if (lookup_host(av, (struct in_addr *)&d[0]) != 0) 2781 errx(EX_NOHOST, "hostname ``%s'' unknown", av); 2782 switch (md) { 2783 case ':': 2784 if (!inet_aton(p, (struct in_addr *)&d[1])) 2785 errx(EX_DATAERR, "bad netmask ``%s''", p); 2786 break; 2787 case '/': 2788 masklen = atoi(p); 2789 if (masklen == 0) 2790 d[1] = htonl(0); /* mask */ 2791 else if (masklen > 32) 2792 errx(EX_DATAERR, "bad width ``%s''", p); 2793 else 2794 d[1] = htonl(~0 << (32 - masklen)); 2795 break; 2796 case '{': /* no mask, assume /24 and put back the '{' */ 2797 d[1] = htonl(~0 << (32 - 24)); 2798 *(--p) = md; 2799 break; 2800 2801 case ',': /* single address plus continuation */ 2802 *(--p) = md; 2803 /* FALLTHROUGH */ 2804 case 0: /* initialization value */ 2805 default: 2806 d[1] = htonl(~0); /* force /32 */ 2807 break; 2808 } 2809 d[0] &= d[1]; /* mask base address with mask */ 2810 if (t) 2811 *t = nd; 2812 /* find next separator */ 2813 if (p) 2814 p = strpbrk(p, ",{"); 2815 if (p && *p == '{') { 2816 /* 2817 * We have a set of addresses. They are stored as follows: 2818 * arg1 is the set size (powers of 2, 2..256) 2819 * addr is the base address IN HOST FORMAT 2820 * mask.. is an array of arg1 bits (rounded up to 2821 * the next multiple of 32) with bits set 2822 * for each host in the map. 2823 */ 2824 uint32_t *map = (uint32_t *)&cmd->mask; 2825 int low, high; 2826 int i = contigmask((uint8_t *)&(d[1]), 32); 2827 2828 if (len > 0) 2829 errx(EX_DATAERR, "address set cannot be in a list"); 2830 if (i < 24 || i > 31) 2831 errx(EX_DATAERR, "invalid set with mask %d\n", i); 2832 cmd->o.arg1 = 1<<(32-i); /* map length */ 2833 d[0] = ntohl(d[0]); /* base addr in host format */ 2834 cmd->o.opcode = O_IP_DST_SET; /* default */ 2835 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32; 2836 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++) 2837 map[i] = 0; /* clear map */ 2838 2839 av = p + 1; 2840 low = d[0] & 0xff; 2841 high = low + cmd->o.arg1 - 1; 2842 /* 2843 * Here, i stores the previous value when we specify a range 2844 * of addresses within a mask, e.g. 45-63. i = -1 means we 2845 * have no previous value. 2846 */ 2847 i = -1; /* previous value in a range */ 2848 while (isdigit(*av)) { 2849 char *s; 2850 int a = strtol(av, &s, 0); 2851 2852 if (s == av) { /* no parameter */ 2853 if (*av != '}') 2854 errx(EX_DATAERR, "set not closed\n"); 2855 if (i != -1) 2856 errx(EX_DATAERR, "incomplete range %d-", i); 2857 break; 2858 } 2859 if (a < low || a > high) 2860 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n", 2861 a, low, high); 2862 a -= low; 2863 if (i == -1) /* no previous in range */ 2864 i = a; 2865 else { /* check that range is valid */ 2866 if (i > a) 2867 errx(EX_DATAERR, "invalid range %d-%d", 2868 i+low, a+low); 2869 if (*s == '-') 2870 errx(EX_DATAERR, "double '-' in range"); 2871 } 2872 for (; i <= a; i++) 2873 map[i/32] |= 1<<(i & 31); 2874 i = -1; 2875 if (*s == '-') 2876 i = a; 2877 else if (*s == '}') 2878 break; 2879 av = s+1; 2880 } 2881 return; 2882 } 2883 av = p; 2884 if (av) /* then *av must be a ',' */ 2885 av++; 2886 2887 /* Check this entry */ 2888 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */ 2889 /* 2890 * 'any' turns the entire list into a NOP. 2891 * 'not any' never matches, so it is removed from the 2892 * list unless it is the only item, in which case we 2893 * report an error. 2894 */ 2895 if (cmd->o.len & F_NOT) { /* "not any" never matches */ 2896 if (av == NULL && len == 0) /* only this entry */ 2897 errx(EX_DATAERR, "not any never matches"); 2898 } 2899 /* else do nothing and skip this entry */ 2900 return; 2901 } 2902 /* A single IP can be stored in an optimized format */ 2903 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) { 2904 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2905 return; 2906 } 2907 len += 2; /* two words... */ 2908 d += 2; 2909 } /* end while */ 2910 if (len + 1 > F_LEN_MASK) 2911 errx(EX_DATAERR, "address list too long"); 2912 cmd->o.len |= len+1; 2913 } 2914 2915 2916 /* Try to find ipv6 address by hostname */ 2917 static int 2918 lookup_host6 (char *host, struct in6_addr *ip6addr) 2919 { 2920 struct hostent *he; 2921 2922 if (!inet_pton(AF_INET6, host, ip6addr)) { 2923 if ((he = gethostbyname2(host, AF_INET6)) == NULL) 2924 return(-1); 2925 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr)); 2926 } 2927 return(0); 2928 } 2929 2930 2931 /* n2mask sets n bits of the mask */ 2932 static void 2933 n2mask(struct in6_addr *mask, int n) 2934 { 2935 static int minimask[9] = 2936 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff }; 2937 u_char *p; 2938 2939 memset(mask, 0, sizeof(struct in6_addr)); 2940 p = (u_char *) mask; 2941 for (; n > 0; p++, n -= 8) { 2942 if (n >= 8) 2943 *p = 0xff; 2944 else 2945 *p = minimask[n]; 2946 } 2947 return; 2948 } 2949 2950 2951 /* 2952 * fill the addr and mask fields in the instruction as appropriate from av. 2953 * Update length as appropriate. 2954 * The following formats are allowed: 2955 * any matches any IP6. Actually returns an empty instruction. 2956 * me returns O_IP6_*_ME 2957 * 2958 * 03f1::234:123:0342 single IP6 addres 2959 * 03f1::234:123:0342/24 address/mask 2960 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address 2961 * 2962 * Set of address (as in ipv6) not supported because ipv6 address 2963 * are typically random past the initial prefix. 2964 * Return 1 on success, 0 on failure. 2965 */ 2966 static int 2967 fill_ip6(ipfw_insn_ip6 *cmd, char *av) 2968 { 2969 int len = 0; 2970 struct in6_addr *d = &(cmd->addr6); 2971 /* 2972 * Needed for multiple address. 2973 * Note d[1] points to struct in6_add r mask6 of cmd 2974 */ 2975 2976 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 2977 2978 if (strcmp(av, "any") == 0) 2979 return (1); 2980 2981 2982 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/ 2983 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2984 return (1); 2985 } 2986 2987 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/ 2988 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2989 return (1); 2990 } 2991 2992 av = strdup(av); 2993 while (av) { 2994 /* 2995 * After the address we can have '/' indicating a mask, 2996 * or ',' indicating another address follows. 2997 */ 2998 2999 char *p; 3000 int masklen; 3001 char md = '\0'; 3002 3003 if ((p = strpbrk(av, "/,")) ) { 3004 md = *p; /* save the separator */ 3005 *p = '\0'; /* terminate address string */ 3006 p++; /* and skip past it */ 3007 } 3008 /* now p points to NULL, mask or next entry */ 3009 3010 /* lookup stores address in *d as a side effect */ 3011 if (lookup_host6(av, d) != 0) { 3012 /* XXX: failed. Free memory and go */ 3013 errx(EX_DATAERR, "bad address \"%s\"", av); 3014 } 3015 /* next, look at the mask, if any */ 3016 masklen = (md == '/') ? atoi(p) : 128; 3017 if (masklen > 128 || masklen < 0) 3018 errx(EX_DATAERR, "bad width \"%s\''", p); 3019 else 3020 n2mask(&d[1], masklen); 3021 3022 APPLY_MASK(d, &d[1]) /* mask base address with mask */ 3023 3024 /* find next separator */ 3025 3026 if (md == '/') { /* find separator past the mask */ 3027 p = strpbrk(p, ","); 3028 if (p != NULL) 3029 p++; 3030 } 3031 av = p; 3032 3033 /* Check this entry */ 3034 if (masklen == 0) { 3035 /* 3036 * 'any' turns the entire list into a NOP. 3037 * 'not any' never matches, so it is removed from the 3038 * list unless it is the only item, in which case we 3039 * report an error. 3040 */ 3041 if (cmd->o.len & F_NOT && av == NULL && len == 0) 3042 errx(EX_DATAERR, "not any never matches"); 3043 continue; 3044 } 3045 3046 /* 3047 * A single IP can be stored alone 3048 */ 3049 if (masklen == 128 && av == NULL && len == 0) { 3050 len = F_INSN_SIZE(struct in6_addr); 3051 break; 3052 } 3053 3054 /* Update length and pointer to arguments */ 3055 len += F_INSN_SIZE(struct in6_addr)*2; 3056 d += 2; 3057 } /* end while */ 3058 3059 /* 3060 * Total length of the command, remember that 1 is the size of 3061 * the base command. 3062 */ 3063 if (len + 1 > F_LEN_MASK) 3064 errx(EX_DATAERR, "address list too long"); 3065 cmd->o.len |= len+1; 3066 free(av); 3067 return (1); 3068 } 3069 3070 /* 3071 * fills command for ipv6 flow-id filtering 3072 * note that the 20 bit flow number is stored in a array of u_int32_t 3073 * it's supported lists of flow-id, so in the o.arg1 we store how many 3074 * additional flow-id we want to filter, the basic is 1 3075 */ 3076 void 3077 fill_flow6( ipfw_insn_u32 *cmd, char *av ) 3078 { 3079 u_int32_t type; /* Current flow number */ 3080 u_int16_t nflow = 0; /* Current flow index */ 3081 char *s = av; 3082 cmd->d[0] = 0; /* Initializing the base number*/ 3083 3084 while (s) { 3085 av = strsep( &s, ",") ; 3086 type = strtoul(av, &av, 0); 3087 if (*av != ',' && *av != '\0') 3088 errx(EX_DATAERR, "invalid ipv6 flow number %s", av); 3089 if (type > 0xfffff) 3090 errx(EX_DATAERR, "flow number out of range %s", av); 3091 cmd->d[nflow] |= type; 3092 nflow++; 3093 } 3094 if( nflow > 0 ) { 3095 cmd->o.opcode = O_FLOW6ID; 3096 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow; 3097 cmd->o.arg1 = nflow; 3098 } 3099 else { 3100 errx(EX_DATAERR, "invalid ipv6 flow number %s", av); 3101 } 3102 } 3103 3104 static ipfw_insn * 3105 add_srcip6(ipfw_insn *cmd, char *av) 3106 { 3107 3108 fill_ip6((ipfw_insn_ip6 *)cmd, av); 3109 if (F_LEN(cmd) == 0) /* any */ 3110 ; 3111 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */ 3112 cmd->opcode = O_IP6_SRC_ME; 3113 } else if (F_LEN(cmd) == 3114 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) { 3115 /* single IP, no mask*/ 3116 cmd->opcode = O_IP6_SRC; 3117 } else { /* addr/mask opt */ 3118 cmd->opcode = O_IP6_SRC_MASK; 3119 } 3120 return cmd; 3121 } 3122 3123 static ipfw_insn * 3124 add_dstip6(ipfw_insn *cmd, char *av) 3125 { 3126 3127 fill_ip6((ipfw_insn_ip6 *)cmd, av); 3128 if (F_LEN(cmd) == 0) /* any */ 3129 ; 3130 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */ 3131 cmd->opcode = O_IP6_DST_ME; 3132 } else if (F_LEN(cmd) == 3133 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) { 3134 /* single IP, no mask*/ 3135 cmd->opcode = O_IP6_DST; 3136 } else { /* addr/mask opt */ 3137 cmd->opcode = O_IP6_DST_MASK; 3138 } 3139 return cmd; 3140 } 3141 3142 3143 /* 3144 * helper function to process a set of flags and set bits in the 3145 * appropriate masks. 3146 */ 3147 static void 3148 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode, 3149 struct _s_x *flags, char *p) 3150 { 3151 uint8_t set=0, clear=0; 3152 3153 while (p && *p) { 3154 char *q; /* points to the separator */ 3155 int val; 3156 uint8_t *which; /* mask we are working on */ 3157 3158 if (*p == '!') { 3159 p++; 3160 which = &clear; 3161 } else 3162 which = &set; 3163 q = strchr(p, ','); 3164 if (q) 3165 *q++ = '\0'; 3166 val = match_token(flags, p); 3167 if (val <= 0) 3168 errx(EX_DATAERR, "invalid flag %s", p); 3169 *which |= (uint8_t)val; 3170 p = q; 3171 } 3172 cmd->opcode = opcode; 3173 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1; 3174 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8); 3175 } 3176 3177 3178 static void 3179 delete(int ac, char *av[]) 3180 { 3181 uint32_t rulenum; 3182 struct dn_pipe p; 3183 int i; 3184 int exitval = EX_OK; 3185 int do_set = 0; 3186 3187 memset(&p, 0, sizeof p); 3188 3189 av++; ac--; 3190 NEED1("missing rule specification"); 3191 if (ac > 0 && _substrcmp(*av, "set") == 0) { 3192 do_set = 1; /* delete set */ 3193 ac--; av++; 3194 } 3195 3196 /* Rule number */ 3197 while (ac && isdigit(**av)) { 3198 i = atoi(*av); av++; ac--; 3199 if (do_nat) { 3200 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i); 3201 if (exitval) { 3202 exitval = EX_UNAVAILABLE; 3203 warn("rule %u not available", i); 3204 } 3205 } else if (do_pipe) { 3206 if (do_pipe == 1) 3207 p.pipe_nr = i; 3208 else 3209 p.fs.fs_nr = i; 3210 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p); 3211 if (i) { 3212 exitval = 1; 3213 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", 3214 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr); 3215 } 3216 } else { 3217 rulenum = (i & 0xffff) | (do_set << 24); 3218 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum); 3219 if (i) { 3220 exitval = EX_UNAVAILABLE; 3221 warn("rule %u: setsockopt(IP_FW_DEL)", 3222 rulenum); 3223 } 3224 } 3225 } 3226 if (exitval != EX_OK) 3227 exit(exitval); 3228 } 3229 3230 3231 /* 3232 * fill the interface structure. We do not check the name as we can 3233 * create interfaces dynamically, so checking them at insert time 3234 * makes relatively little sense. 3235 * Interface names containing '*', '?', or '[' are assumed to be shell 3236 * patterns which match interfaces. 3237 */ 3238 static void 3239 fill_iface(ipfw_insn_if *cmd, char *arg) 3240 { 3241 cmd->name[0] = '\0'; 3242 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if); 3243 3244 /* Parse the interface or address */ 3245 if (strcmp(arg, "any") == 0) 3246 cmd->o.len = 0; /* effectively ignore this command */ 3247 else if (!isdigit(*arg)) { 3248 strlcpy(cmd->name, arg, sizeof(cmd->name)); 3249 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0; 3250 } else if (!inet_aton(arg, &cmd->p.ip)) 3251 errx(EX_DATAERR, "bad ip address ``%s''", arg); 3252 } 3253 3254 /* 3255 * Search for interface with name "ifn", and fill n accordingly: 3256 * 3257 * n->ip ip address of interface "ifn" 3258 * n->if_name copy of interface name "ifn" 3259 */ 3260 static void 3261 set_addr_dynamic(const char *ifn, struct cfg_nat *n) 3262 { 3263 size_t needed; 3264 int mib[6]; 3265 char *buf, *lim, *next; 3266 struct if_msghdr *ifm; 3267 struct ifa_msghdr *ifam; 3268 struct sockaddr_dl *sdl; 3269 struct sockaddr_in *sin; 3270 int ifIndex, ifMTU; 3271 3272 mib[0] = CTL_NET; 3273 mib[1] = PF_ROUTE; 3274 mib[2] = 0; 3275 mib[3] = AF_INET; 3276 mib[4] = NET_RT_IFLIST; 3277 mib[5] = 0; 3278 /* 3279 * Get interface data. 3280 */ 3281 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1) 3282 err(1, "iflist-sysctl-estimate"); 3283 if ((buf = malloc(needed)) == NULL) 3284 errx(1, "malloc failed"); 3285 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1) 3286 err(1, "iflist-sysctl-get"); 3287 lim = buf + needed; 3288 /* 3289 * Loop through interfaces until one with 3290 * given name is found. This is done to 3291 * find correct interface index for routing 3292 * message processing. 3293 */ 3294 ifIndex = 0; 3295 next = buf; 3296 while (next < lim) { 3297 ifm = (struct if_msghdr *)next; 3298 next += ifm->ifm_msglen; 3299 if (ifm->ifm_version != RTM_VERSION) { 3300 if (verbose) 3301 warnx("routing message version %d " 3302 "not understood", ifm->ifm_version); 3303 continue; 3304 } 3305 if (ifm->ifm_type == RTM_IFINFO) { 3306 sdl = (struct sockaddr_dl *)(ifm + 1); 3307 if (strlen(ifn) == sdl->sdl_nlen && 3308 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) { 3309 ifIndex = ifm->ifm_index; 3310 ifMTU = ifm->ifm_data.ifi_mtu; 3311 break; 3312 } 3313 } 3314 } 3315 if (!ifIndex) 3316 errx(1, "unknown interface name %s", ifn); 3317 /* 3318 * Get interface address. 3319 */ 3320 sin = NULL; 3321 while (next < lim) { 3322 ifam = (struct ifa_msghdr *)next; 3323 next += ifam->ifam_msglen; 3324 if (ifam->ifam_version != RTM_VERSION) { 3325 if (verbose) 3326 warnx("routing message version %d " 3327 "not understood", ifam->ifam_version); 3328 continue; 3329 } 3330 if (ifam->ifam_type != RTM_NEWADDR) 3331 break; 3332 if (ifam->ifam_addrs & RTA_IFA) { 3333 int i; 3334 char *cp = (char *)(ifam + 1); 3335 3336 for (i = 1; i < RTA_IFA; i <<= 1) { 3337 if (ifam->ifam_addrs & i) 3338 cp += SA_SIZE((struct sockaddr *)cp); 3339 } 3340 if (((struct sockaddr *)cp)->sa_family == AF_INET) { 3341 sin = (struct sockaddr_in *)cp; 3342 break; 3343 } 3344 } 3345 } 3346 if (sin == NULL) 3347 errx(1, "%s: cannot get interface address", ifn); 3348 3349 n->ip = sin->sin_addr; 3350 strncpy(n->if_name, ifn, IF_NAMESIZE); 3351 3352 free(buf); 3353 } 3354 3355 /* 3356 * XXX - The following functions, macros and definitions come from natd.c: 3357 * it would be better to move them outside natd.c, in a file 3358 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live 3359 * with it. 3360 */ 3361 3362 /* 3363 * Definition of a port range, and macros to deal with values. 3364 * FORMAT: HI 16-bits == first port in range, 0 == all ports. 3365 * LO 16-bits == number of ports in range 3366 * NOTES: - Port values are not stored in network byte order. 3367 */ 3368 3369 #define port_range u_long 3370 3371 #define GETLOPORT(x) ((x) >> 0x10) 3372 #define GETNUMPORTS(x) ((x) & 0x0000ffff) 3373 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x))) 3374 3375 /* Set y to be the low-port value in port_range variable x. */ 3376 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10)) 3377 3378 /* Set y to be the number of ports in port_range variable x. */ 3379 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y)) 3380 3381 static void 3382 StrToAddr (const char* str, struct in_addr* addr) 3383 { 3384 struct hostent* hp; 3385 3386 if (inet_aton (str, addr)) 3387 return; 3388 3389 hp = gethostbyname (str); 3390 if (!hp) 3391 errx (1, "unknown host %s", str); 3392 3393 memcpy (addr, hp->h_addr, sizeof (struct in_addr)); 3394 } 3395 3396 static int 3397 StrToPortRange (const char* str, const char* proto, port_range *portRange) 3398 { 3399 char* sep; 3400 struct servent* sp; 3401 char* end; 3402 u_short loPort; 3403 u_short hiPort; 3404 3405 /* First see if this is a service, return corresponding port if so. */ 3406 sp = getservbyname (str,proto); 3407 if (sp) { 3408 SETLOPORT(*portRange, ntohs(sp->s_port)); 3409 SETNUMPORTS(*portRange, 1); 3410 return 0; 3411 } 3412 3413 /* Not a service, see if it's a single port or port range. */ 3414 sep = strchr (str, '-'); 3415 if (sep == NULL) { 3416 SETLOPORT(*portRange, strtol(str, &end, 10)); 3417 if (end != str) { 3418 /* Single port. */ 3419 SETNUMPORTS(*portRange, 1); 3420 return 0; 3421 } 3422 3423 /* Error in port range field. */ 3424 errx (EX_DATAERR, "%s/%s: unknown service", str, proto); 3425 } 3426 3427 /* Port range, get the values and sanity check. */ 3428 sscanf (str, "%hu-%hu", &loPort, &hiPort); 3429 SETLOPORT(*portRange, loPort); 3430 SETNUMPORTS(*portRange, 0); /* Error by default */ 3431 if (loPort <= hiPort) 3432 SETNUMPORTS(*portRange, hiPort - loPort + 1); 3433 3434 if (GETNUMPORTS(*portRange) == 0) 3435 errx (EX_DATAERR, "invalid port range %s", str); 3436 3437 return 0; 3438 } 3439 3440 static int 3441 StrToProto (const char* str) 3442 { 3443 if (!strcmp (str, "tcp")) 3444 return IPPROTO_TCP; 3445 3446 if (!strcmp (str, "udp")) 3447 return IPPROTO_UDP; 3448 3449 errx (EX_DATAERR, "unknown protocol %s. Expected tcp or udp", str); 3450 } 3451 3452 static int 3453 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto, 3454 port_range *portRange) 3455 { 3456 char* ptr; 3457 3458 ptr = strchr (str, ':'); 3459 if (!ptr) 3460 errx (EX_DATAERR, "%s is missing port number", str); 3461 3462 *ptr = '\0'; 3463 ++ptr; 3464 3465 StrToAddr (str, addr); 3466 return StrToPortRange (ptr, proto, portRange); 3467 } 3468 3469 /* End of stuff taken from natd.c. */ 3470 3471 #define INC_ARGCV() do { \ 3472 (*_av)++; \ 3473 (*_ac)--; \ 3474 av = *_av; \ 3475 ac = *_ac; \ 3476 } while(0) 3477 3478 /* 3479 * The next 3 functions add support for the addr, port and proto redirect and 3480 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect() 3481 * and SetupProtoRedirect() from natd.c. 3482 * 3483 * Every setup_* function fills at least one redirect entry 3484 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool) 3485 * in buf. 3486 * 3487 * The format of data in buf is: 3488 * 3489 * 3490 * cfg_nat cfg_redir cfg_spool ...... cfg_spool 3491 * 3492 * ------------------------------------- ------------ 3493 * | | .....X ... | | | | ..... 3494 * ------------------------------------- ...... ------------ 3495 * ^ 3496 * spool_cnt n=0 ...... n=(X-1) 3497 * 3498 * len points to the amount of available space in buf 3499 * space counts the memory consumed by every function 3500 * 3501 * XXX - Every function get all the argv params so it 3502 * has to check, in optional parameters, that the next 3503 * args is a valid option for the redir entry and not 3504 * another token. Only redir_port and redir_proto are 3505 * affected by this. 3506 */ 3507 3508 static int 3509 setup_redir_addr(char *spool_buf, int len, 3510 int *_ac, char ***_av) 3511 { 3512 char **av, *sep; /* Token separator. */ 3513 /* Temporary buffer used to hold server pool ip's. */ 3514 char tmp_spool_buf[NAT_BUF_LEN]; 3515 int ac, i, space, lsnat; 3516 struct cfg_redir *r; 3517 struct cfg_spool *tmp; 3518 3519 av = *_av; 3520 ac = *_ac; 3521 space = 0; 3522 lsnat = 0; 3523 if (len >= SOF_REDIR) { 3524 r = (struct cfg_redir *)spool_buf; 3525 /* Skip cfg_redir at beginning of buf. */ 3526 spool_buf = &spool_buf[SOF_REDIR]; 3527 space = SOF_REDIR; 3528 len -= SOF_REDIR; 3529 } else 3530 goto nospace; 3531 r->mode = REDIR_ADDR; 3532 /* Extract local address. */ 3533 if (ac == 0) 3534 errx(EX_DATAERR, "redirect_addr: missing local address"); 3535 sep = strchr(*av, ','); 3536 if (sep) { /* LSNAT redirection syntax. */ 3537 r->laddr.s_addr = INADDR_NONE; 3538 /* Preserve av, copy spool servers to tmp_spool_buf. */ 3539 strncpy(tmp_spool_buf, *av, strlen(*av)+1); 3540 lsnat = 1; 3541 } else 3542 StrToAddr(*av, &r->laddr); 3543 INC_ARGCV(); 3544 3545 /* Extract public address. */ 3546 if (ac == 0) 3547 errx(EX_DATAERR, "redirect_addr: missing public address"); 3548 StrToAddr(*av, &r->paddr); 3549 INC_ARGCV(); 3550 3551 /* Setup LSNAT server pool. */ 3552 if (sep) { 3553 sep = strtok(tmp_spool_buf, ","); 3554 while (sep != NULL) { 3555 tmp = (struct cfg_spool *)spool_buf; 3556 if (len < SOF_SPOOL) 3557 goto nospace; 3558 len -= SOF_SPOOL; 3559 space += SOF_SPOOL; 3560 StrToAddr(sep, &tmp->addr); 3561 tmp->port = ~0; 3562 r->spool_cnt++; 3563 /* Point to the next possible cfg_spool. */ 3564 spool_buf = &spool_buf[SOF_SPOOL]; 3565 sep = strtok(NULL, ","); 3566 } 3567 } 3568 return(space); 3569 nospace: 3570 errx(EX_DATAERR, "redirect_addr: buf is too small\n"); 3571 } 3572 3573 static int 3574 setup_redir_port(char *spool_buf, int len, 3575 int *_ac, char ***_av) 3576 { 3577 char **av, *sep, *protoName; 3578 char tmp_spool_buf[NAT_BUF_LEN]; 3579 int ac, space, lsnat; 3580 struct cfg_redir *r; 3581 struct cfg_spool *tmp; 3582 u_short numLocalPorts; 3583 port_range portRange; 3584 3585 av = *_av; 3586 ac = *_ac; 3587 space = 0; 3588 lsnat = 0; 3589 numLocalPorts = 0; 3590 3591 if (len >= SOF_REDIR) { 3592 r = (struct cfg_redir *)spool_buf; 3593 /* Skip cfg_redir at beginning of buf. */ 3594 spool_buf = &spool_buf[SOF_REDIR]; 3595 space = SOF_REDIR; 3596 len -= SOF_REDIR; 3597 } else 3598 goto nospace; 3599 r->mode = REDIR_PORT; 3600 /* 3601 * Extract protocol. 3602 */ 3603 if (ac == 0) 3604 errx (EX_DATAERR, "redirect_port: missing protocol"); 3605 r->proto = StrToProto(*av); 3606 protoName = *av; 3607 INC_ARGCV(); 3608 3609 /* 3610 * Extract local address. 3611 */ 3612 if (ac == 0) 3613 errx (EX_DATAERR, "redirect_port: missing local address"); 3614 3615 sep = strchr(*av, ','); 3616 /* LSNAT redirection syntax. */ 3617 if (sep) { 3618 r->laddr.s_addr = INADDR_NONE; 3619 r->lport = ~0; 3620 numLocalPorts = 1; 3621 /* Preserve av, copy spool servers to tmp_spool_buf. */ 3622 strncpy(tmp_spool_buf, *av, strlen(*av)+1); 3623 lsnat = 1; 3624 } else { 3625 if (StrToAddrAndPortRange (*av, &r->laddr, protoName, 3626 &portRange) != 0) 3627 errx(EX_DATAERR, "redirect_port:" 3628 "invalid local port range"); 3629 3630 r->lport = GETLOPORT(portRange); 3631 numLocalPorts = GETNUMPORTS(portRange); 3632 } 3633 INC_ARGCV(); 3634 3635 /* 3636 * Extract public port and optionally address. 3637 */ 3638 if (ac == 0) 3639 errx (EX_DATAERR, "redirect_port: missing public port"); 3640 3641 sep = strchr (*av, ':'); 3642 if (sep) { 3643 if (StrToAddrAndPortRange (*av, &r->paddr, protoName, 3644 &portRange) != 0) 3645 errx(EX_DATAERR, "redirect_port:" 3646 "invalid public port range"); 3647 } else { 3648 r->paddr.s_addr = INADDR_ANY; 3649 if (StrToPortRange (*av, protoName, &portRange) != 0) 3650 errx(EX_DATAERR, "redirect_port:" 3651 "invalid public port range"); 3652 } 3653 3654 r->pport = GETLOPORT(portRange); 3655 r->pport_cnt = GETNUMPORTS(portRange); 3656 INC_ARGCV(); 3657 3658 /* 3659 * Extract remote address and optionally port. 3660 */ 3661 /* 3662 * NB: isalpha(**av) => we've to check that next parameter is really an 3663 * option for this redirect entry, else stop here processing arg[cv]. 3664 */ 3665 if (ac != 0 && !isalpha(**av)) { 3666 sep = strchr (*av, ':'); 3667 if (sep) { 3668 if (StrToAddrAndPortRange (*av, &r->raddr, protoName, 3669 &portRange) != 0) 3670 errx(EX_DATAERR, "redirect_port:" 3671 "invalid remote port range"); 3672 } else { 3673 SETLOPORT(portRange, 0); 3674 SETNUMPORTS(portRange, 1); 3675 StrToAddr (*av, &r->raddr); 3676 } 3677 INC_ARGCV(); 3678 } else { 3679 SETLOPORT(portRange, 0); 3680 SETNUMPORTS(portRange, 1); 3681 r->raddr.s_addr = INADDR_ANY; 3682 } 3683 r->rport = GETLOPORT(portRange); 3684 r->rport_cnt = GETNUMPORTS(portRange); 3685 3686 /* 3687 * Make sure port ranges match up, then add the redirect ports. 3688 */ 3689 if (numLocalPorts != r->pport_cnt) 3690 errx(EX_DATAERR, "redirect_port:" 3691 "port ranges must be equal in size"); 3692 3693 /* Remote port range is allowed to be '0' which means all ports. */ 3694 if (r->rport_cnt != numLocalPorts && 3695 (r->rport_cnt != 1 || r->rport != 0)) 3696 errx(EX_DATAERR, "redirect_port: remote port must" 3697 "be 0 or equal to local port range in size"); 3698 3699 /* 3700 * Setup LSNAT server pool. 3701 */ 3702 if (lsnat) { 3703 sep = strtok(tmp_spool_buf, ","); 3704 while (sep != NULL) { 3705 tmp = (struct cfg_spool *)spool_buf; 3706 if (len < SOF_SPOOL) 3707 goto nospace; 3708 len -= SOF_SPOOL; 3709 space += SOF_SPOOL; 3710 if (StrToAddrAndPortRange(sep, &tmp->addr, protoName, 3711 &portRange) != 0) 3712 errx(EX_DATAERR, "redirect_port:" 3713 "invalid local port range"); 3714 if (GETNUMPORTS(portRange) != 1) 3715 errx(EX_DATAERR, "redirect_port: local port" 3716 "must be single in this context"); 3717 tmp->port = GETLOPORT(portRange); 3718 r->spool_cnt++; 3719 /* Point to the next possible cfg_spool. */ 3720 spool_buf = &spool_buf[SOF_SPOOL]; 3721 sep = strtok(NULL, ","); 3722 } 3723 } 3724 return (space); 3725 nospace: 3726 errx(EX_DATAERR, "redirect_port: buf is too small\n"); 3727 } 3728 3729 static int 3730 setup_redir_proto(char *spool_buf, int len, 3731 int *_ac, char ***_av) 3732 { 3733 char **av; 3734 int ac, i, space; 3735 struct protoent *protoent; 3736 struct cfg_redir *r; 3737 3738 av = *_av; 3739 ac = *_ac; 3740 if (len >= SOF_REDIR) { 3741 r = (struct cfg_redir *)spool_buf; 3742 /* Skip cfg_redir at beginning of buf. */ 3743 spool_buf = &spool_buf[SOF_REDIR]; 3744 space = SOF_REDIR; 3745 len -= SOF_REDIR; 3746 } else 3747 goto nospace; 3748 r->mode = REDIR_PROTO; 3749 /* 3750 * Extract protocol. 3751 */ 3752 if (ac == 0) 3753 errx(EX_DATAERR, "redirect_proto: missing protocol"); 3754 3755 protoent = getprotobyname(*av); 3756 if (protoent == NULL) 3757 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av); 3758 else 3759 r->proto = protoent->p_proto; 3760 3761 INC_ARGCV(); 3762 3763 /* 3764 * Extract local address. 3765 */ 3766 if (ac == 0) 3767 errx(EX_DATAERR, "redirect_proto: missing local address"); 3768 else 3769 StrToAddr(*av, &r->laddr); 3770 3771 INC_ARGCV(); 3772 3773 /* 3774 * Extract optional public address. 3775 */ 3776 if (ac == 0) { 3777 r->paddr.s_addr = INADDR_ANY; 3778 r->raddr.s_addr = INADDR_ANY; 3779 } else { 3780 /* see above in setup_redir_port() */ 3781 if (!isalpha(**av)) { 3782 StrToAddr(*av, &r->paddr); 3783 INC_ARGCV(); 3784 3785 /* 3786 * Extract optional remote address. 3787 */ 3788 /* see above in setup_redir_port() */ 3789 if (ac!=0 && !isalpha(**av)) { 3790 StrToAddr(*av, &r->raddr); 3791 INC_ARGCV(); 3792 } 3793 } 3794 } 3795 return (space); 3796 nospace: 3797 errx(EX_DATAERR, "redirect_proto: buf is too small\n"); 3798 } 3799 3800 static void 3801 show_nat(int ac, char **av); 3802 3803 static void 3804 print_nat_config(char *buf) { 3805 struct cfg_nat *n; 3806 int i, cnt, flag, off; 3807 struct cfg_redir *t; 3808 struct cfg_spool *s; 3809 struct protoent *p; 3810 3811 n = (struct cfg_nat *)buf; 3812 flag = 1; 3813 off = sizeof(*n); 3814 printf("ipfw nat %u config", n->id); 3815 if (strlen(n->if_name) != 0) 3816 printf(" if %s", n->if_name); 3817 else if (n->ip.s_addr != 0) 3818 printf(" ip %s", inet_ntoa(n->ip)); 3819 while (n->mode != 0) { 3820 if (n->mode & PKT_ALIAS_LOG) { 3821 printf(" log"); 3822 n->mode &= ~PKT_ALIAS_LOG; 3823 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) { 3824 printf(" deny_in"); 3825 n->mode &= ~PKT_ALIAS_DENY_INCOMING; 3826 } else if (n->mode & PKT_ALIAS_SAME_PORTS) { 3827 printf(" same_ports"); 3828 n->mode &= ~PKT_ALIAS_SAME_PORTS; 3829 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) { 3830 printf(" unreg_only"); 3831 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY; 3832 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) { 3833 printf(" reset"); 3834 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE; 3835 } else if (n->mode & PKT_ALIAS_REVERSE) { 3836 printf(" reverse"); 3837 n->mode &= ~PKT_ALIAS_REVERSE; 3838 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) { 3839 printf(" proxy_only"); 3840 n->mode &= ~PKT_ALIAS_PROXY_ONLY; 3841 } 3842 } 3843 /* Print all the redirect's data configuration. */ 3844 for (cnt = 0; cnt < n->redir_cnt; cnt++) { 3845 t = (struct cfg_redir *)&buf[off]; 3846 off += SOF_REDIR; 3847 switch (t->mode) { 3848 case REDIR_ADDR: 3849 printf(" redirect_addr"); 3850 if (t->spool_cnt == 0) 3851 printf(" %s", inet_ntoa(t->laddr)); 3852 else 3853 for (i = 0; i < t->spool_cnt; i++) { 3854 s = (struct cfg_spool *)&buf[off]; 3855 if (i) 3856 printf(","); 3857 else 3858 printf(" "); 3859 printf("%s", inet_ntoa(s->addr)); 3860 off += SOF_SPOOL; 3861 } 3862 printf(" %s", inet_ntoa(t->paddr)); 3863 break; 3864 case REDIR_PORT: 3865 p = getprotobynumber(t->proto); 3866 printf(" redirect_port %s ", p->p_name); 3867 if (!t->spool_cnt) { 3868 printf("%s:%u", inet_ntoa(t->laddr), t->lport); 3869 if (t->pport_cnt > 1) 3870 printf("-%u", t->lport + 3871 t->pport_cnt - 1); 3872 } else 3873 for (i=0; i < t->spool_cnt; i++) { 3874 s = (struct cfg_spool *)&buf[off]; 3875 if (i) 3876 printf(","); 3877 printf("%s:%u", inet_ntoa(s->addr), 3878 s->port); 3879 off += SOF_SPOOL; 3880 } 3881 3882 printf(" "); 3883 if (t->paddr.s_addr) 3884 printf("%s:", inet_ntoa(t->paddr)); 3885 printf("%u", t->pport); 3886 if (!t->spool_cnt && t->pport_cnt > 1) 3887 printf("-%u", t->pport + t->pport_cnt - 1); 3888 3889 if (t->raddr.s_addr) { 3890 printf(" %s", inet_ntoa(t->raddr)); 3891 if (t->rport) { 3892 printf(":%u", t->rport); 3893 if (!t->spool_cnt && t->rport_cnt > 1) 3894 printf("-%u", t->rport + 3895 t->rport_cnt - 1); 3896 } 3897 } 3898 break; 3899 case REDIR_PROTO: 3900 p = getprotobynumber(t->proto); 3901 printf(" redirect_proto %s %s", p->p_name, 3902 inet_ntoa(t->laddr)); 3903 if (t->paddr.s_addr != 0) { 3904 printf(" %s", inet_ntoa(t->paddr)); 3905 if (t->raddr.s_addr) 3906 printf(" %s", inet_ntoa(t->raddr)); 3907 } 3908 break; 3909 default: 3910 errx(EX_DATAERR, "unknown redir mode"); 3911 break; 3912 } 3913 } 3914 printf("\n"); 3915 } 3916 3917 static void 3918 config_nat(int ac, char **av) 3919 { 3920 struct cfg_nat *n; /* Nat instance configuration. */ 3921 struct in_addr ip; 3922 int i, len, off, tok; 3923 char *id, buf[NAT_BUF_LEN]; /* Buffer for serialized data. */ 3924 3925 len = NAT_BUF_LEN; 3926 /* Offset in buf: save space for n at the beginning. */ 3927 off = sizeof(*n); 3928 memset(buf, 0, sizeof(buf)); 3929 n = (struct cfg_nat *)buf; 3930 3931 av++; ac--; 3932 /* Nat id. */ 3933 if (ac && isdigit(**av)) { 3934 id = *av; 3935 i = atoi(*av); 3936 ac--; av++; 3937 n->id = i; 3938 } else 3939 errx(EX_DATAERR, "missing nat id"); 3940 if (ac == 0) 3941 errx(EX_DATAERR, "missing option"); 3942 3943 while (ac > 0) { 3944 tok = match_token(nat_params, *av); 3945 ac--; av++; 3946 switch (tok) { 3947 case TOK_IP: 3948 if (ac == 0) 3949 errx(EX_DATAERR, "missing option"); 3950 if (!inet_aton(av[0], &(n->ip))) 3951 errx(EX_DATAERR, "bad ip address ``%s''", 3952 av[0]); 3953 ac--; av++; 3954 break; 3955 case TOK_IF: 3956 set_addr_dynamic(av[0], n); 3957 ac--; av++; 3958 break; 3959 case TOK_ALOG: 3960 n->mode |= PKT_ALIAS_LOG; 3961 break; 3962 case TOK_DENY_INC: 3963 n->mode |= PKT_ALIAS_DENY_INCOMING; 3964 break; 3965 case TOK_SAME_PORTS: 3966 n->mode |= PKT_ALIAS_SAME_PORTS; 3967 break; 3968 case TOK_UNREG_ONLY: 3969 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY; 3970 break; 3971 case TOK_RESET_ADDR: 3972 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE; 3973 break; 3974 case TOK_ALIAS_REV: 3975 n->mode |= PKT_ALIAS_REVERSE; 3976 break; 3977 case TOK_PROXY_ONLY: 3978 n->mode |= PKT_ALIAS_PROXY_ONLY; 3979 break; 3980 /* 3981 * All the setup_redir_* functions work directly in the final 3982 * buffer, see above for details. 3983 */ 3984 case TOK_REDIR_ADDR: 3985 case TOK_REDIR_PORT: 3986 case TOK_REDIR_PROTO: 3987 switch (tok) { 3988 case TOK_REDIR_ADDR: 3989 i = setup_redir_addr(&buf[off], len, &ac, &av); 3990 break; 3991 case TOK_REDIR_PORT: 3992 i = setup_redir_port(&buf[off], len, &ac, &av); 3993 break; 3994 case TOK_REDIR_PROTO: 3995 i = setup_redir_proto(&buf[off], len, &ac, &av); 3996 break; 3997 } 3998 n->redir_cnt++; 3999 off += i; 4000 len -= i; 4001 break; 4002 default: 4003 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]); 4004 } 4005 } 4006 4007 i = do_cmd(IP_FW_NAT_CFG, buf, off); 4008 if (i) 4009 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG"); 4010 4011 /* After every modification, we show the resultant rule. */ 4012 int _ac = 3; 4013 char *_av[] = {"show", "config", id}; 4014 show_nat(_ac, _av); 4015 } 4016 4017 static void 4018 config_pipe(int ac, char **av) 4019 { 4020 struct dn_pipe p; 4021 int i; 4022 char *end; 4023 void *par = NULL; 4024 4025 memset(&p, 0, sizeof p); 4026 4027 av++; ac--; 4028 /* Pipe number */ 4029 if (ac && isdigit(**av)) { 4030 i = atoi(*av); av++; ac--; 4031 if (do_pipe == 1) 4032 p.pipe_nr = i; 4033 else 4034 p.fs.fs_nr = i; 4035 } 4036 while (ac > 0) { 4037 double d; 4038 int tok = match_token(dummynet_params, *av); 4039 ac--; av++; 4040 4041 switch(tok) { 4042 case TOK_NOERROR: 4043 p.fs.flags_fs |= DN_NOERROR; 4044 break; 4045 4046 case TOK_PLR: 4047 NEED1("plr needs argument 0..1\n"); 4048 d = strtod(av[0], NULL); 4049 if (d > 1) 4050 d = 1; 4051 else if (d < 0) 4052 d = 0; 4053 p.fs.plr = (int)(d*0x7fffffff); 4054 ac--; av++; 4055 break; 4056 4057 case TOK_QUEUE: 4058 NEED1("queue needs queue size\n"); 4059 end = NULL; 4060 p.fs.qsize = strtoul(av[0], &end, 0); 4061 if (*end == 'K' || *end == 'k') { 4062 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 4063 p.fs.qsize *= 1024; 4064 } else if (*end == 'B' || 4065 _substrcmp2(end, "by", "bytes") == 0) { 4066 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 4067 } 4068 ac--; av++; 4069 break; 4070 4071 case TOK_BUCKETS: 4072 NEED1("buckets needs argument\n"); 4073 p.fs.rq_size = strtoul(av[0], NULL, 0); 4074 ac--; av++; 4075 break; 4076 4077 case TOK_MASK: 4078 NEED1("mask needs mask specifier\n"); 4079 /* 4080 * per-flow queue, mask is dst_ip, dst_port, 4081 * src_ip, src_port, proto measured in bits 4082 */ 4083 par = NULL; 4084 4085 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask)); 4086 end = NULL; 4087 4088 while (ac >= 1) { 4089 uint32_t *p32 = NULL; 4090 uint16_t *p16 = NULL; 4091 uint32_t *p20 = NULL; 4092 struct in6_addr *pa6 = NULL; 4093 uint32_t a; 4094 4095 tok = match_token(dummynet_params, *av); 4096 ac--; av++; 4097 switch(tok) { 4098 case TOK_ALL: 4099 /* 4100 * special case, all bits significant 4101 */ 4102 p.fs.flow_mask.dst_ip = ~0; 4103 p.fs.flow_mask.src_ip = ~0; 4104 p.fs.flow_mask.dst_port = ~0; 4105 p.fs.flow_mask.src_port = ~0; 4106 p.fs.flow_mask.proto = ~0; 4107 n2mask(&(p.fs.flow_mask.dst_ip6), 128); 4108 n2mask(&(p.fs.flow_mask.src_ip6), 128); 4109 p.fs.flow_mask.flow_id6 = ~0; 4110 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 4111 goto end_mask; 4112 4113 case TOK_DSTIP: 4114 p32 = &p.fs.flow_mask.dst_ip; 4115 break; 4116 4117 case TOK_SRCIP: 4118 p32 = &p.fs.flow_mask.src_ip; 4119 break; 4120 4121 case TOK_DSTIP6: 4122 pa6 = &(p.fs.flow_mask.dst_ip6); 4123 break; 4124 4125 case TOK_SRCIP6: 4126 pa6 = &(p.fs.flow_mask.src_ip6); 4127 break; 4128 4129 case TOK_FLOWID: 4130 p20 = &p.fs.flow_mask.flow_id6; 4131 break; 4132 4133 case TOK_DSTPORT: 4134 p16 = &p.fs.flow_mask.dst_port; 4135 break; 4136 4137 case TOK_SRCPORT: 4138 p16 = &p.fs.flow_mask.src_port; 4139 break; 4140 4141 case TOK_PROTO: 4142 break; 4143 4144 default: 4145 ac++; av--; /* backtrack */ 4146 goto end_mask; 4147 } 4148 if (ac < 1) 4149 errx(EX_USAGE, "mask: value missing"); 4150 if (*av[0] == '/') { 4151 a = strtoul(av[0]+1, &end, 0); 4152 if (pa6 == NULL) 4153 a = (a == 32) ? ~0 : (1 << a) - 1; 4154 } else 4155 a = strtoul(av[0], &end, 0); 4156 if (p32 != NULL) 4157 *p32 = a; 4158 else if (p16 != NULL) { 4159 if (a > 0xFFFF) 4160 errx(EX_DATAERR, 4161 "port mask must be 16 bit"); 4162 *p16 = (uint16_t)a; 4163 } else if (p20 != NULL) { 4164 if (a > 0xfffff) 4165 errx(EX_DATAERR, 4166 "flow_id mask must be 20 bit"); 4167 *p20 = (uint32_t)a; 4168 } else if (pa6 != NULL) { 4169 if (a < 0 || a > 128) 4170 errx(EX_DATAERR, 4171 "in6addr invalid mask len"); 4172 else 4173 n2mask(pa6, a); 4174 } else { 4175 if (a > 0xFF) 4176 errx(EX_DATAERR, 4177 "proto mask must be 8 bit"); 4178 p.fs.flow_mask.proto = (uint8_t)a; 4179 } 4180 if (a != 0) 4181 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 4182 ac--; av++; 4183 } /* end while, config masks */ 4184 end_mask: 4185 break; 4186 4187 case TOK_RED: 4188 case TOK_GRED: 4189 NEED1("red/gred needs w_q/min_th/max_th/max_p\n"); 4190 p.fs.flags_fs |= DN_IS_RED; 4191 if (tok == TOK_GRED) 4192 p.fs.flags_fs |= DN_IS_GENTLE_RED; 4193 /* 4194 * the format for parameters is w_q/min_th/max_th/max_p 4195 */ 4196 if ((end = strsep(&av[0], "/"))) { 4197 double w_q = strtod(end, NULL); 4198 if (w_q > 1 || w_q <= 0) 4199 errx(EX_DATAERR, "0 < w_q <= 1"); 4200 p.fs.w_q = (int) (w_q * (1 << SCALE_RED)); 4201 } 4202 if ((end = strsep(&av[0], "/"))) { 4203 p.fs.min_th = strtoul(end, &end, 0); 4204 if (*end == 'K' || *end == 'k') 4205 p.fs.min_th *= 1024; 4206 } 4207 if ((end = strsep(&av[0], "/"))) { 4208 p.fs.max_th = strtoul(end, &end, 0); 4209 if (*end == 'K' || *end == 'k') 4210 p.fs.max_th *= 1024; 4211 } 4212 if ((end = strsep(&av[0], "/"))) { 4213 double max_p = strtod(end, NULL); 4214 if (max_p > 1 || max_p <= 0) 4215 errx(EX_DATAERR, "0 < max_p <= 1"); 4216 p.fs.max_p = (int)(max_p * (1 << SCALE_RED)); 4217 } 4218 ac--; av++; 4219 break; 4220 4221 case TOK_DROPTAIL: 4222 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED); 4223 break; 4224 4225 case TOK_BW: 4226 NEED1("bw needs bandwidth or interface\n"); 4227 if (do_pipe != 1) 4228 errx(EX_DATAERR, "bandwidth only valid for pipes"); 4229 /* 4230 * set clocking interface or bandwidth value 4231 */ 4232 if (av[0][0] >= 'a' && av[0][0] <= 'z') { 4233 int l = sizeof(p.if_name)-1; 4234 /* interface name */ 4235 strncpy(p.if_name, av[0], l); 4236 p.if_name[l] = '\0'; 4237 p.bandwidth = 0; 4238 } else { 4239 p.if_name[0] = '\0'; 4240 p.bandwidth = strtoul(av[0], &end, 0); 4241 if (*end == 'K' || *end == 'k') { 4242 end++; 4243 p.bandwidth *= 1000; 4244 } else if (*end == 'M') { 4245 end++; 4246 p.bandwidth *= 1000000; 4247 } 4248 if ((*end == 'B' && 4249 _substrcmp2(end, "Bi", "Bit/s") != 0) || 4250 _substrcmp2(end, "by", "bytes") == 0) 4251 p.bandwidth *= 8; 4252 if (p.bandwidth < 0) 4253 errx(EX_DATAERR, "bandwidth too large"); 4254 } 4255 ac--; av++; 4256 break; 4257 4258 case TOK_DELAY: 4259 if (do_pipe != 1) 4260 errx(EX_DATAERR, "delay only valid for pipes"); 4261 NEED1("delay needs argument 0..10000ms\n"); 4262 p.delay = strtoul(av[0], NULL, 0); 4263 ac--; av++; 4264 break; 4265 4266 case TOK_WEIGHT: 4267 if (do_pipe == 1) 4268 errx(EX_DATAERR,"weight only valid for queues"); 4269 NEED1("weight needs argument 0..100\n"); 4270 p.fs.weight = strtoul(av[0], &end, 0); 4271 ac--; av++; 4272 break; 4273 4274 case TOK_PIPE: 4275 if (do_pipe == 1) 4276 errx(EX_DATAERR,"pipe only valid for queues"); 4277 NEED1("pipe needs pipe_number\n"); 4278 p.fs.parent_nr = strtoul(av[0], &end, 0); 4279 ac--; av++; 4280 break; 4281 4282 default: 4283 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]); 4284 } 4285 } 4286 if (do_pipe == 1) { 4287 if (p.pipe_nr == 0) 4288 errx(EX_DATAERR, "pipe_nr must be > 0"); 4289 if (p.delay > 10000) 4290 errx(EX_DATAERR, "delay must be < 10000"); 4291 } else { /* do_pipe == 2, queue */ 4292 if (p.fs.parent_nr == 0) 4293 errx(EX_DATAERR, "pipe must be > 0"); 4294 if (p.fs.weight >100) 4295 errx(EX_DATAERR, "weight must be <= 100"); 4296 } 4297 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) { 4298 if (p.fs.qsize > 1024*1024) 4299 errx(EX_DATAERR, "queue size must be < 1MB"); 4300 } else { 4301 if (p.fs.qsize > 100) 4302 errx(EX_DATAERR, "2 <= queue size <= 100"); 4303 } 4304 if (p.fs.flags_fs & DN_IS_RED) { 4305 size_t len; 4306 int lookup_depth, avg_pkt_size; 4307 double s, idle, weight, w_q; 4308 struct clockinfo ck; 4309 int t; 4310 4311 if (p.fs.min_th >= p.fs.max_th) 4312 errx(EX_DATAERR, "min_th %d must be < than max_th %d", 4313 p.fs.min_th, p.fs.max_th); 4314 if (p.fs.max_th == 0) 4315 errx(EX_DATAERR, "max_th must be > 0"); 4316 4317 len = sizeof(int); 4318 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth", 4319 &lookup_depth, &len, NULL, 0) == -1) 4320 4321 errx(1, "sysctlbyname(\"%s\")", 4322 "net.inet.ip.dummynet.red_lookup_depth"); 4323 if (lookup_depth == 0) 4324 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth" 4325 " must be greater than zero"); 4326 4327 len = sizeof(int); 4328 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size", 4329 &avg_pkt_size, &len, NULL, 0) == -1) 4330 4331 errx(1, "sysctlbyname(\"%s\")", 4332 "net.inet.ip.dummynet.red_avg_pkt_size"); 4333 if (avg_pkt_size == 0) 4334 errx(EX_DATAERR, 4335 "net.inet.ip.dummynet.red_avg_pkt_size must" 4336 " be greater than zero"); 4337 4338 len = sizeof(struct clockinfo); 4339 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1) 4340 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate"); 4341 4342 /* 4343 * Ticks needed for sending a medium-sized packet. 4344 * Unfortunately, when we are configuring a WF2Q+ queue, we 4345 * do not have bandwidth information, because that is stored 4346 * in the parent pipe, and also we have multiple queues 4347 * competing for it. So we set s=0, which is not very 4348 * correct. But on the other hand, why do we want RED with 4349 * WF2Q+ ? 4350 */ 4351 if (p.bandwidth==0) /* this is a WF2Q+ queue */ 4352 s = 0; 4353 else 4354 s = ck.hz * avg_pkt_size * 8 / p.bandwidth; 4355 4356 /* 4357 * max idle time (in ticks) before avg queue size becomes 0. 4358 * NOTA: (3/w_q) is approx the value x so that 4359 * (1-w_q)^x < 10^-3. 4360 */ 4361 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED); 4362 idle = s * 3. / w_q; 4363 p.fs.lookup_step = (int)idle / lookup_depth; 4364 if (!p.fs.lookup_step) 4365 p.fs.lookup_step = 1; 4366 weight = 1 - w_q; 4367 for (t = p.fs.lookup_step; t > 0; --t) 4368 weight *= weight; 4369 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED)); 4370 } 4371 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p); 4372 if (i) 4373 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE"); 4374 } 4375 4376 static void 4377 get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask) 4378 { 4379 int i, l; 4380 4381 for (i=0; i<6; i++) 4382 addr[i] = mask[i] = 0; 4383 if (strcmp(p, "any") == 0) 4384 return; 4385 4386 for (i=0; *p && i<6;i++, p++) { 4387 addr[i] = strtol(p, &p, 16); 4388 if (*p != ':') /* we start with the mask */ 4389 break; 4390 } 4391 if (*p == '/') { /* mask len */ 4392 l = strtol(p+1, &p, 0); 4393 for (i=0; l>0; l -=8, i++) 4394 mask[i] = (l >=8) ? 0xff : (~0) << (8-l); 4395 } else if (*p == '&') { /* mask */ 4396 for (i=0, p++; *p && i<6;i++, p++) { 4397 mask[i] = strtol(p, &p, 16); 4398 if (*p != ':') 4399 break; 4400 } 4401 } else if (*p == '\0') { 4402 for (i=0; i<6; i++) 4403 mask[i] = 0xff; 4404 } 4405 for (i=0; i<6; i++) 4406 addr[i] &= mask[i]; 4407 } 4408 4409 /* 4410 * helper function, updates the pointer to cmd with the length 4411 * of the current command, and also cleans up the first word of 4412 * the new command in case it has been clobbered before. 4413 */ 4414 static ipfw_insn * 4415 next_cmd(ipfw_insn *cmd) 4416 { 4417 cmd += F_LEN(cmd); 4418 bzero(cmd, sizeof(*cmd)); 4419 return cmd; 4420 } 4421 4422 /* 4423 * Takes arguments and copies them into a comment 4424 */ 4425 static void 4426 fill_comment(ipfw_insn *cmd, int ac, char **av) 4427 { 4428 int i, l; 4429 char *p = (char *)(cmd + 1); 4430 4431 cmd->opcode = O_NOP; 4432 cmd->len = (cmd->len & (F_NOT | F_OR)); 4433 4434 /* Compute length of comment string. */ 4435 for (i = 0, l = 0; i < ac; i++) 4436 l += strlen(av[i]) + 1; 4437 if (l == 0) 4438 return; 4439 if (l > 84) 4440 errx(EX_DATAERR, 4441 "comment too long (max 80 chars)"); 4442 l = 1 + (l+3)/4; 4443 cmd->len = (cmd->len & (F_NOT | F_OR)) | l; 4444 for (i = 0; i < ac; i++) { 4445 strcpy(p, av[i]); 4446 p += strlen(av[i]); 4447 *p++ = ' '; 4448 } 4449 *(--p) = '\0'; 4450 } 4451 4452 /* 4453 * A function to fill simple commands of size 1. 4454 * Existing flags are preserved. 4455 */ 4456 static void 4457 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg) 4458 { 4459 cmd->opcode = opcode; 4460 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1; 4461 cmd->arg1 = arg; 4462 } 4463 4464 /* 4465 * Fetch and add the MAC address and type, with masks. This generates one or 4466 * two microinstructions, and returns the pointer to the last one. 4467 */ 4468 static ipfw_insn * 4469 add_mac(ipfw_insn *cmd, int ac, char *av[]) 4470 { 4471 ipfw_insn_mac *mac; 4472 4473 if (ac < 2) 4474 errx(EX_DATAERR, "MAC dst src"); 4475 4476 cmd->opcode = O_MACADDR2; 4477 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac); 4478 4479 mac = (ipfw_insn_mac *)cmd; 4480 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */ 4481 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */ 4482 return cmd; 4483 } 4484 4485 static ipfw_insn * 4486 add_mactype(ipfw_insn *cmd, int ac, char *av) 4487 { 4488 if (ac < 1) 4489 errx(EX_DATAERR, "missing MAC type"); 4490 if (strcmp(av, "any") != 0) { /* we have a non-null type */ 4491 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE); 4492 cmd->opcode = O_MAC_TYPE; 4493 return cmd; 4494 } else 4495 return NULL; 4496 } 4497 4498 static ipfw_insn * 4499 add_proto0(ipfw_insn *cmd, char *av, u_char *protop) 4500 { 4501 struct protoent *pe; 4502 char *ep; 4503 int proto; 4504 4505 proto = strtol(av, &ep, 10); 4506 if (*ep != '\0' || proto <= 0) { 4507 if ((pe = getprotobyname(av)) == NULL) 4508 return NULL; 4509 proto = pe->p_proto; 4510 } 4511 4512 fill_cmd(cmd, O_PROTO, 0, proto); 4513 *protop = proto; 4514 return cmd; 4515 } 4516 4517 static ipfw_insn * 4518 add_proto(ipfw_insn *cmd, char *av, u_char *protop) 4519 { 4520 u_char proto = IPPROTO_IP; 4521 4522 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4523 ; /* do not set O_IP4 nor O_IP6 */ 4524 else if (strcmp(av, "ip4") == 0) 4525 /* explicit "just IPv4" rule */ 4526 fill_cmd(cmd, O_IP4, 0, 0); 4527 else if (strcmp(av, "ip6") == 0) { 4528 /* explicit "just IPv6" rule */ 4529 proto = IPPROTO_IPV6; 4530 fill_cmd(cmd, O_IP6, 0, 0); 4531 } else 4532 return add_proto0(cmd, av, protop); 4533 4534 *protop = proto; 4535 return cmd; 4536 } 4537 4538 static ipfw_insn * 4539 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop) 4540 { 4541 u_char proto = IPPROTO_IP; 4542 4543 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4544 ; /* do not set O_IP4 nor O_IP6 */ 4545 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0) 4546 /* explicit "just IPv4" rule */ 4547 fill_cmd(cmd, O_IP4, 0, 0); 4548 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) { 4549 /* explicit "just IPv6" rule */ 4550 proto = IPPROTO_IPV6; 4551 fill_cmd(cmd, O_IP6, 0, 0); 4552 } else 4553 return add_proto0(cmd, av, protop); 4554 4555 *protop = proto; 4556 return cmd; 4557 } 4558 4559 static ipfw_insn * 4560 add_srcip(ipfw_insn *cmd, char *av) 4561 { 4562 fill_ip((ipfw_insn_ip *)cmd, av); 4563 if (cmd->opcode == O_IP_DST_SET) /* set */ 4564 cmd->opcode = O_IP_SRC_SET; 4565 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4566 cmd->opcode = O_IP_SRC_LOOKUP; 4567 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4568 cmd->opcode = O_IP_SRC_ME; 4569 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4570 cmd->opcode = O_IP_SRC; 4571 else /* addr/mask */ 4572 cmd->opcode = O_IP_SRC_MASK; 4573 return cmd; 4574 } 4575 4576 static ipfw_insn * 4577 add_dstip(ipfw_insn *cmd, char *av) 4578 { 4579 fill_ip((ipfw_insn_ip *)cmd, av); 4580 if (cmd->opcode == O_IP_DST_SET) /* set */ 4581 ; 4582 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4583 ; 4584 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4585 cmd->opcode = O_IP_DST_ME; 4586 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4587 cmd->opcode = O_IP_DST; 4588 else /* addr/mask */ 4589 cmd->opcode = O_IP_DST_MASK; 4590 return cmd; 4591 } 4592 4593 static ipfw_insn * 4594 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode) 4595 { 4596 if (_substrcmp(av, "any") == 0) { 4597 return NULL; 4598 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) { 4599 /* XXX todo: check that we have a protocol with ports */ 4600 cmd->opcode = opcode; 4601 return cmd; 4602 } 4603 return NULL; 4604 } 4605 4606 static ipfw_insn * 4607 add_src(ipfw_insn *cmd, char *av, u_char proto) 4608 { 4609 struct in6_addr a; 4610 char *host, *ch; 4611 ipfw_insn *ret = NULL; 4612 4613 if ((host = strdup(av)) == NULL) 4614 return NULL; 4615 if ((ch = strrchr(host, '/')) != NULL) 4616 *ch = '\0'; 4617 4618 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4619 inet_pton(AF_INET6, host, &a)) 4620 ret = add_srcip6(cmd, av); 4621 /* XXX: should check for IPv4, not !IPv6 */ 4622 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4623 !inet_pton(AF_INET6, host, &a))) 4624 ret = add_srcip(cmd, av); 4625 if (ret == NULL && strcmp(av, "any") != 0) 4626 ret = cmd; 4627 4628 free(host); 4629 return ret; 4630 } 4631 4632 static ipfw_insn * 4633 add_dst(ipfw_insn *cmd, char *av, u_char proto) 4634 { 4635 struct in6_addr a; 4636 char *host, *ch; 4637 ipfw_insn *ret = NULL; 4638 4639 if ((host = strdup(av)) == NULL) 4640 return NULL; 4641 if ((ch = strrchr(host, '/')) != NULL) 4642 *ch = '\0'; 4643 4644 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4645 inet_pton(AF_INET6, host, &a)) 4646 ret = add_dstip6(cmd, av); 4647 /* XXX: should check for IPv4, not !IPv6 */ 4648 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4649 !inet_pton(AF_INET6, host, &a))) 4650 ret = add_dstip(cmd, av); 4651 if (ret == NULL && strcmp(av, "any") != 0) 4652 ret = cmd; 4653 4654 free(host); 4655 return ret; 4656 } 4657 4658 /* 4659 * Parse arguments and assemble the microinstructions which make up a rule. 4660 * Rules are added into the 'rulebuf' and then copied in the correct order 4661 * into the actual rule. 4662 * 4663 * The syntax for a rule starts with the action, followed by 4664 * optional action parameters, and the various match patterns. 4665 * In the assembled microcode, the first opcode must be an O_PROBE_STATE 4666 * (generated if the rule includes a keep-state option), then the 4667 * various match patterns, log/altq actions, and the actual action. 4668 * 4669 */ 4670 static void 4671 add(int ac, char *av[]) 4672 { 4673 /* 4674 * rules are added into the 'rulebuf' and then copied in 4675 * the correct order into the actual rule. 4676 * Some things that need to go out of order (prob, action etc.) 4677 * go into actbuf[]. 4678 */ 4679 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255]; 4680 4681 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL; 4682 ipfw_insn *first_cmd; /* first match pattern */ 4683 4684 struct ip_fw *rule; 4685 4686 /* 4687 * various flags used to record that we entered some fields. 4688 */ 4689 ipfw_insn *have_state = NULL; /* check-state or keep-state */ 4690 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL; 4691 size_t len; 4692 4693 int i; 4694 4695 int open_par = 0; /* open parenthesis ( */ 4696 4697 /* proto is here because it is used to fetch ports */ 4698 u_char proto = IPPROTO_IP; /* default protocol */ 4699 4700 double match_prob = 1; /* match probability, default is always match */ 4701 4702 bzero(actbuf, sizeof(actbuf)); /* actions go here */ 4703 bzero(cmdbuf, sizeof(cmdbuf)); 4704 bzero(rulebuf, sizeof(rulebuf)); 4705 4706 rule = (struct ip_fw *)rulebuf; 4707 cmd = (ipfw_insn *)cmdbuf; 4708 action = (ipfw_insn *)actbuf; 4709 4710 av++; ac--; 4711 4712 /* [rule N] -- Rule number optional */ 4713 if (ac && isdigit(**av)) { 4714 rule->rulenum = atoi(*av); 4715 av++; 4716 ac--; 4717 } 4718 4719 /* [set N] -- set number (0..RESVD_SET), optional */ 4720 if (ac > 1 && _substrcmp(*av, "set") == 0) { 4721 int set = strtoul(av[1], NULL, 10); 4722 if (set < 0 || set > RESVD_SET) 4723 errx(EX_DATAERR, "illegal set %s", av[1]); 4724 rule->set = set; 4725 av += 2; ac -= 2; 4726 } 4727 4728 /* [prob D] -- match probability, optional */ 4729 if (ac > 1 && _substrcmp(*av, "prob") == 0) { 4730 match_prob = strtod(av[1], NULL); 4731 4732 if (match_prob <= 0 || match_prob > 1) 4733 errx(EX_DATAERR, "illegal match prob. %s", av[1]); 4734 av += 2; ac -= 2; 4735 } 4736 4737 /* action -- mandatory */ 4738 NEED1("missing action"); 4739 i = match_token(rule_actions, *av); 4740 ac--; av++; 4741 action->len = 1; /* default */ 4742 switch(i) { 4743 case TOK_CHECKSTATE: 4744 have_state = action; 4745 action->opcode = O_CHECK_STATE; 4746 break; 4747 4748 case TOK_ACCEPT: 4749 action->opcode = O_ACCEPT; 4750 break; 4751 4752 case TOK_DENY: 4753 action->opcode = O_DENY; 4754 action->arg1 = 0; 4755 break; 4756 4757 case TOK_REJECT: 4758 action->opcode = O_REJECT; 4759 action->arg1 = ICMP_UNREACH_HOST; 4760 break; 4761 4762 case TOK_RESET: 4763 action->opcode = O_REJECT; 4764 action->arg1 = ICMP_REJECT_RST; 4765 break; 4766 4767 case TOK_RESET6: 4768 action->opcode = O_UNREACH6; 4769 action->arg1 = ICMP6_UNREACH_RST; 4770 break; 4771 4772 case TOK_UNREACH: 4773 action->opcode = O_REJECT; 4774 NEED1("missing reject code"); 4775 fill_reject_code(&action->arg1, *av); 4776 ac--; av++; 4777 break; 4778 4779 case TOK_UNREACH6: 4780 action->opcode = O_UNREACH6; 4781 NEED1("missing unreach code"); 4782 fill_unreach6_code(&action->arg1, *av); 4783 ac--; av++; 4784 break; 4785 4786 case TOK_COUNT: 4787 action->opcode = O_COUNT; 4788 break; 4789 4790 case TOK_QUEUE: 4791 action->opcode = O_QUEUE; 4792 goto chkarg; 4793 case TOK_PIPE: 4794 action->opcode = O_PIPE; 4795 goto chkarg; 4796 case TOK_SKIPTO: 4797 action->opcode = O_SKIPTO; 4798 goto chkarg; 4799 case TOK_NETGRAPH: 4800 action->opcode = O_NETGRAPH; 4801 goto chkarg; 4802 case TOK_NGTEE: 4803 action->opcode = O_NGTEE; 4804 goto chkarg; 4805 case TOK_DIVERT: 4806 action->opcode = O_DIVERT; 4807 goto chkarg; 4808 case TOK_TEE: 4809 action->opcode = O_TEE; 4810 chkarg: 4811 if (!ac) 4812 errx(EX_USAGE, "missing argument for %s", *(av - 1)); 4813 if (isdigit(**av)) { 4814 action->arg1 = strtoul(*av, NULL, 10); 4815 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG) 4816 errx(EX_DATAERR, "illegal argument for %s", 4817 *(av - 1)); 4818 } else if (_substrcmp(*av, TABLEARG) == 0) { 4819 action->arg1 = IP_FW_TABLEARG; 4820 } else if (i == TOK_DIVERT || i == TOK_TEE) { 4821 struct servent *s; 4822 setservent(1); 4823 s = getservbyname(av[0], "divert"); 4824 if (s != NULL) 4825 action->arg1 = ntohs(s->s_port); 4826 else 4827 errx(EX_DATAERR, "illegal divert/tee port"); 4828 } else 4829 errx(EX_DATAERR, "illegal argument for %s", *(av - 1)); 4830 ac--; av++; 4831 break; 4832 4833 case TOK_FORWARD: { 4834 ipfw_insn_sa *p = (ipfw_insn_sa *)action; 4835 char *s, *end; 4836 4837 NEED1("missing forward address[:port]"); 4838 4839 action->opcode = O_FORWARD_IP; 4840 action->len = F_INSN_SIZE(ipfw_insn_sa); 4841 4842 p->sa.sin_len = sizeof(struct sockaddr_in); 4843 p->sa.sin_family = AF_INET; 4844 p->sa.sin_port = 0; 4845 /* 4846 * locate the address-port separator (':' or ',') 4847 */ 4848 s = strchr(*av, ':'); 4849 if (s == NULL) 4850 s = strchr(*av, ','); 4851 if (s != NULL) { 4852 *(s++) = '\0'; 4853 i = strtoport(s, &end, 0 /* base */, 0 /* proto */); 4854 if (s == end) 4855 errx(EX_DATAERR, 4856 "illegal forwarding port ``%s''", s); 4857 p->sa.sin_port = (u_short)i; 4858 } 4859 if (_substrcmp(*av, "tablearg") == 0) 4860 p->sa.sin_addr.s_addr = INADDR_ANY; 4861 else 4862 lookup_host(*av, &(p->sa.sin_addr)); 4863 ac--; av++; 4864 break; 4865 } 4866 case TOK_COMMENT: 4867 /* pretend it is a 'count' rule followed by the comment */ 4868 action->opcode = O_COUNT; 4869 ac++; av--; /* go back... */ 4870 break; 4871 4872 case TOK_NAT: 4873 action->opcode = O_NAT; 4874 action->len = F_INSN_SIZE(ipfw_insn_nat); 4875 NEED1("missing nat number"); 4876 action->arg1 = strtoul(*av, NULL, 10); 4877 ac--; av++; 4878 break; 4879 4880 default: 4881 errx(EX_DATAERR, "invalid action %s\n", av[-1]); 4882 } 4883 action = next_cmd(action); 4884 4885 /* 4886 * [altq queuename] -- altq tag, optional 4887 * [log [logamount N]] -- log, optional 4888 * 4889 * If they exist, it go first in the cmdbuf, but then it is 4890 * skipped in the copy section to the end of the buffer. 4891 */ 4892 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) { 4893 ac--; av++; 4894 switch (i) { 4895 case TOK_LOG: 4896 { 4897 ipfw_insn_log *c = (ipfw_insn_log *)cmd; 4898 int l; 4899 4900 if (have_log) 4901 errx(EX_DATAERR, 4902 "log cannot be specified more than once"); 4903 have_log = (ipfw_insn *)c; 4904 cmd->len = F_INSN_SIZE(ipfw_insn_log); 4905 cmd->opcode = O_LOG; 4906 if (ac && _substrcmp(*av, "logamount") == 0) { 4907 ac--; av++; 4908 NEED1("logamount requires argument"); 4909 l = atoi(*av); 4910 if (l < 0) 4911 errx(EX_DATAERR, 4912 "logamount must be positive"); 4913 c->max_log = l; 4914 ac--; av++; 4915 } else { 4916 len = sizeof(c->max_log); 4917 if (sysctlbyname("net.inet.ip.fw.verbose_limit", 4918 &c->max_log, &len, NULL, 0) == -1) 4919 errx(1, "sysctlbyname(\"%s\")", 4920 "net.inet.ip.fw.verbose_limit"); 4921 } 4922 } 4923 break; 4924 4925 case TOK_ALTQ: 4926 { 4927 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd; 4928 4929 NEED1("missing altq queue name"); 4930 if (have_altq) 4931 errx(EX_DATAERR, 4932 "altq cannot be specified more than once"); 4933 have_altq = (ipfw_insn *)a; 4934 cmd->len = F_INSN_SIZE(ipfw_insn_altq); 4935 cmd->opcode = O_ALTQ; 4936 fill_altq_qid(&a->qid, *av); 4937 ac--; av++; 4938 } 4939 break; 4940 4941 case TOK_TAG: 4942 case TOK_UNTAG: { 4943 uint16_t tag; 4944 4945 if (have_tag) 4946 errx(EX_USAGE, "tag and untag cannot be " 4947 "specified more than once"); 4948 GET_UINT_ARG(tag, 1, 65534, i, rule_action_params); 4949 have_tag = cmd; 4950 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag); 4951 ac--; av++; 4952 break; 4953 } 4954 4955 default: 4956 abort(); 4957 } 4958 cmd = next_cmd(cmd); 4959 } 4960 4961 if (have_state) /* must be a check-state, we are done */ 4962 goto done; 4963 4964 #define OR_START(target) \ 4965 if (ac && (*av[0] == '(' || *av[0] == '{')) { \ 4966 if (open_par) \ 4967 errx(EX_USAGE, "nested \"(\" not allowed\n"); \ 4968 prev = NULL; \ 4969 open_par = 1; \ 4970 if ( (av[0])[1] == '\0') { \ 4971 ac--; av++; \ 4972 } else \ 4973 (*av)++; \ 4974 } \ 4975 target: \ 4976 4977 4978 #define CLOSE_PAR \ 4979 if (open_par) { \ 4980 if (ac && ( \ 4981 strcmp(*av, ")") == 0 || \ 4982 strcmp(*av, "}") == 0)) { \ 4983 prev = NULL; \ 4984 open_par = 0; \ 4985 ac--; av++; \ 4986 } else \ 4987 errx(EX_USAGE, "missing \")\"\n"); \ 4988 } 4989 4990 #define NOT_BLOCK \ 4991 if (ac && _substrcmp(*av, "not") == 0) { \ 4992 if (cmd->len & F_NOT) \ 4993 errx(EX_USAGE, "double \"not\" not allowed\n"); \ 4994 cmd->len |= F_NOT; \ 4995 ac--; av++; \ 4996 } 4997 4998 #define OR_BLOCK(target) \ 4999 if (ac && _substrcmp(*av, "or") == 0) { \ 5000 if (prev == NULL || open_par == 0) \ 5001 errx(EX_DATAERR, "invalid OR block"); \ 5002 prev->len |= F_OR; \ 5003 ac--; av++; \ 5004 goto target; \ 5005 } \ 5006 CLOSE_PAR; 5007 5008 first_cmd = cmd; 5009 5010 #if 0 5011 /* 5012 * MAC addresses, optional. 5013 * If we have this, we skip the part "proto from src to dst" 5014 * and jump straight to the option parsing. 5015 */ 5016 NOT_BLOCK; 5017 NEED1("missing protocol"); 5018 if (_substrcmp(*av, "MAC") == 0 || 5019 _substrcmp(*av, "mac") == 0) { 5020 ac--; av++; /* the "MAC" keyword */ 5021 add_mac(cmd, ac, av); /* exits in case of errors */ 5022 cmd = next_cmd(cmd); 5023 ac -= 2; av += 2; /* dst-mac and src-mac */ 5024 NOT_BLOCK; 5025 NEED1("missing mac type"); 5026 if (add_mactype(cmd, ac, av[0])) 5027 cmd = next_cmd(cmd); 5028 ac--; av++; /* any or mac-type */ 5029 goto read_options; 5030 } 5031 #endif 5032 5033 /* 5034 * protocol, mandatory 5035 */ 5036 OR_START(get_proto); 5037 NOT_BLOCK; 5038 NEED1("missing protocol"); 5039 if (add_proto_compat(cmd, *av, &proto)) { 5040 av++; ac--; 5041 if (F_LEN(cmd) != 0) { 5042 prev = cmd; 5043 cmd = next_cmd(cmd); 5044 } 5045 } else if (first_cmd != cmd) { 5046 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 5047 } else 5048 goto read_options; 5049 OR_BLOCK(get_proto); 5050 5051 /* 5052 * "from", mandatory 5053 */ 5054 if (!ac || _substrcmp(*av, "from") != 0) 5055 errx(EX_USAGE, "missing ``from''"); 5056 ac--; av++; 5057 5058 /* 5059 * source IP, mandatory 5060 */ 5061 OR_START(source_ip); 5062 NOT_BLOCK; /* optional "not" */ 5063 NEED1("missing source address"); 5064 if (add_src(cmd, *av, proto)) { 5065 ac--; av++; 5066 if (F_LEN(cmd) != 0) { /* ! any */ 5067 prev = cmd; 5068 cmd = next_cmd(cmd); 5069 } 5070 } else 5071 errx(EX_USAGE, "bad source address %s", *av); 5072 OR_BLOCK(source_ip); 5073 5074 /* 5075 * source ports, optional 5076 */ 5077 NOT_BLOCK; /* optional "not" */ 5078 if (ac) { 5079 if (_substrcmp(*av, "any") == 0 || 5080 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5081 ac--; av++; 5082 if (F_LEN(cmd) != 0) 5083 cmd = next_cmd(cmd); 5084 } 5085 } 5086 5087 /* 5088 * "to", mandatory 5089 */ 5090 if (!ac || _substrcmp(*av, "to") != 0) 5091 errx(EX_USAGE, "missing ``to''"); 5092 av++; ac--; 5093 5094 /* 5095 * destination, mandatory 5096 */ 5097 OR_START(dest_ip); 5098 NOT_BLOCK; /* optional "not" */ 5099 NEED1("missing dst address"); 5100 if (add_dst(cmd, *av, proto)) { 5101 ac--; av++; 5102 if (F_LEN(cmd) != 0) { /* ! any */ 5103 prev = cmd; 5104 cmd = next_cmd(cmd); 5105 } 5106 } else 5107 errx( EX_USAGE, "bad destination address %s", *av); 5108 OR_BLOCK(dest_ip); 5109 5110 /* 5111 * dest. ports, optional 5112 */ 5113 NOT_BLOCK; /* optional "not" */ 5114 if (ac) { 5115 if (_substrcmp(*av, "any") == 0 || 5116 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5117 ac--; av++; 5118 if (F_LEN(cmd) != 0) 5119 cmd = next_cmd(cmd); 5120 } 5121 } 5122 5123 read_options: 5124 if (ac && first_cmd == cmd) { 5125 /* 5126 * nothing specified so far, store in the rule to ease 5127 * printout later. 5128 */ 5129 rule->_pad = 1; 5130 } 5131 prev = NULL; 5132 while (ac) { 5133 char *s; 5134 ipfw_insn_u32 *cmd32; /* alias for cmd */ 5135 5136 s = *av; 5137 cmd32 = (ipfw_insn_u32 *)cmd; 5138 5139 if (*s == '!') { /* alternate syntax for NOT */ 5140 if (cmd->len & F_NOT) 5141 errx(EX_USAGE, "double \"not\" not allowed\n"); 5142 cmd->len = F_NOT; 5143 s++; 5144 } 5145 i = match_token(rule_options, s); 5146 ac--; av++; 5147 switch(i) { 5148 case TOK_NOT: 5149 if (cmd->len & F_NOT) 5150 errx(EX_USAGE, "double \"not\" not allowed\n"); 5151 cmd->len = F_NOT; 5152 break; 5153 5154 case TOK_OR: 5155 if (open_par == 0 || prev == NULL) 5156 errx(EX_USAGE, "invalid \"or\" block\n"); 5157 prev->len |= F_OR; 5158 break; 5159 5160 case TOK_STARTBRACE: 5161 if (open_par) 5162 errx(EX_USAGE, "+nested \"(\" not allowed\n"); 5163 open_par = 1; 5164 break; 5165 5166 case TOK_ENDBRACE: 5167 if (!open_par) 5168 errx(EX_USAGE, "+missing \")\"\n"); 5169 open_par = 0; 5170 prev = NULL; 5171 break; 5172 5173 case TOK_IN: 5174 fill_cmd(cmd, O_IN, 0, 0); 5175 break; 5176 5177 case TOK_OUT: 5178 cmd->len ^= F_NOT; /* toggle F_NOT */ 5179 fill_cmd(cmd, O_IN, 0, 0); 5180 break; 5181 5182 case TOK_DIVERTED: 5183 fill_cmd(cmd, O_DIVERTED, 0, 3); 5184 break; 5185 5186 case TOK_DIVERTEDLOOPBACK: 5187 fill_cmd(cmd, O_DIVERTED, 0, 1); 5188 break; 5189 5190 case TOK_DIVERTEDOUTPUT: 5191 fill_cmd(cmd, O_DIVERTED, 0, 2); 5192 break; 5193 5194 case TOK_FRAG: 5195 fill_cmd(cmd, O_FRAG, 0, 0); 5196 break; 5197 5198 case TOK_LAYER2: 5199 fill_cmd(cmd, O_LAYER2, 0, 0); 5200 break; 5201 5202 case TOK_XMIT: 5203 case TOK_RECV: 5204 case TOK_VIA: 5205 NEED1("recv, xmit, via require interface name" 5206 " or address"); 5207 fill_iface((ipfw_insn_if *)cmd, av[0]); 5208 ac--; av++; 5209 if (F_LEN(cmd) == 0) /* not a valid address */ 5210 break; 5211 if (i == TOK_XMIT) 5212 cmd->opcode = O_XMIT; 5213 else if (i == TOK_RECV) 5214 cmd->opcode = O_RECV; 5215 else if (i == TOK_VIA) 5216 cmd->opcode = O_VIA; 5217 break; 5218 5219 case TOK_ICMPTYPES: 5220 NEED1("icmptypes requires list of types"); 5221 fill_icmptypes((ipfw_insn_u32 *)cmd, *av); 5222 av++; ac--; 5223 break; 5224 5225 case TOK_ICMP6TYPES: 5226 NEED1("icmptypes requires list of types"); 5227 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av); 5228 av++; ac--; 5229 break; 5230 5231 case TOK_IPTTL: 5232 NEED1("ipttl requires TTL"); 5233 if (strpbrk(*av, "-,")) { 5234 if (!add_ports(cmd, *av, 0, O_IPTTL)) 5235 errx(EX_DATAERR, "invalid ipttl %s", *av); 5236 } else 5237 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0)); 5238 ac--; av++; 5239 break; 5240 5241 case TOK_IPID: 5242 NEED1("ipid requires id"); 5243 if (strpbrk(*av, "-,")) { 5244 if (!add_ports(cmd, *av, 0, O_IPID)) 5245 errx(EX_DATAERR, "invalid ipid %s", *av); 5246 } else 5247 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0)); 5248 ac--; av++; 5249 break; 5250 5251 case TOK_IPLEN: 5252 NEED1("iplen requires length"); 5253 if (strpbrk(*av, "-,")) { 5254 if (!add_ports(cmd, *av, 0, O_IPLEN)) 5255 errx(EX_DATAERR, "invalid ip len %s", *av); 5256 } else 5257 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0)); 5258 ac--; av++; 5259 break; 5260 5261 case TOK_IPVER: 5262 NEED1("ipver requires version"); 5263 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0)); 5264 ac--; av++; 5265 break; 5266 5267 case TOK_IPPRECEDENCE: 5268 NEED1("ipprecedence requires value"); 5269 fill_cmd(cmd, O_IPPRECEDENCE, 0, 5270 (strtoul(*av, NULL, 0) & 7) << 5); 5271 ac--; av++; 5272 break; 5273 5274 case TOK_IPOPTS: 5275 NEED1("missing argument for ipoptions"); 5276 fill_flags(cmd, O_IPOPT, f_ipopts, *av); 5277 ac--; av++; 5278 break; 5279 5280 case TOK_IPTOS: 5281 NEED1("missing argument for iptos"); 5282 fill_flags(cmd, O_IPTOS, f_iptos, *av); 5283 ac--; av++; 5284 break; 5285 5286 case TOK_UID: 5287 NEED1("uid requires argument"); 5288 { 5289 char *end; 5290 uid_t uid; 5291 struct passwd *pwd; 5292 5293 cmd->opcode = O_UID; 5294 uid = strtoul(*av, &end, 0); 5295 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av); 5296 if (pwd == NULL) 5297 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av); 5298 cmd32->d[0] = pwd->pw_uid; 5299 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5300 ac--; av++; 5301 } 5302 break; 5303 5304 case TOK_GID: 5305 NEED1("gid requires argument"); 5306 { 5307 char *end; 5308 gid_t gid; 5309 struct group *grp; 5310 5311 cmd->opcode = O_GID; 5312 gid = strtoul(*av, &end, 0); 5313 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av); 5314 if (grp == NULL) 5315 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av); 5316 cmd32->d[0] = grp->gr_gid; 5317 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5318 ac--; av++; 5319 } 5320 break; 5321 5322 case TOK_JAIL: 5323 NEED1("jail requires argument"); 5324 { 5325 char *end; 5326 int jid; 5327 5328 cmd->opcode = O_JAIL; 5329 jid = (int)strtol(*av, &end, 0); 5330 if (jid < 0 || *end != '\0') 5331 errx(EX_DATAERR, "jail requires prison ID"); 5332 cmd32->d[0] = (uint32_t)jid; 5333 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5334 ac--; av++; 5335 } 5336 break; 5337 5338 case TOK_ESTAB: 5339 fill_cmd(cmd, O_ESTAB, 0, 0); 5340 break; 5341 5342 case TOK_SETUP: 5343 fill_cmd(cmd, O_TCPFLAGS, 0, 5344 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 ); 5345 break; 5346 5347 case TOK_TCPDATALEN: 5348 NEED1("tcpdatalen requires length"); 5349 if (strpbrk(*av, "-,")) { 5350 if (!add_ports(cmd, *av, 0, O_TCPDATALEN)) 5351 errx(EX_DATAERR, "invalid tcpdata len %s", *av); 5352 } else 5353 fill_cmd(cmd, O_TCPDATALEN, 0, 5354 strtoul(*av, NULL, 0)); 5355 ac--; av++; 5356 break; 5357 5358 case TOK_TCPOPTS: 5359 NEED1("missing argument for tcpoptions"); 5360 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av); 5361 ac--; av++; 5362 break; 5363 5364 case TOK_TCPSEQ: 5365 case TOK_TCPACK: 5366 NEED1("tcpseq/tcpack requires argument"); 5367 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 5368 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK; 5369 cmd32->d[0] = htonl(strtoul(*av, NULL, 0)); 5370 ac--; av++; 5371 break; 5372 5373 case TOK_TCPWIN: 5374 NEED1("tcpwin requires length"); 5375 fill_cmd(cmd, O_TCPWIN, 0, 5376 htons(strtoul(*av, NULL, 0))); 5377 ac--; av++; 5378 break; 5379 5380 case TOK_TCPFLAGS: 5381 NEED1("missing argument for tcpflags"); 5382 cmd->opcode = O_TCPFLAGS; 5383 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av); 5384 ac--; av++; 5385 break; 5386 5387 case TOK_KEEPSTATE: 5388 if (open_par) 5389 errx(EX_USAGE, "keep-state cannot be part " 5390 "of an or block"); 5391 if (have_state) 5392 errx(EX_USAGE, "only one of keep-state " 5393 "and limit is allowed"); 5394 have_state = cmd; 5395 fill_cmd(cmd, O_KEEP_STATE, 0, 0); 5396 break; 5397 5398 case TOK_LIMIT: { 5399 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 5400 int val; 5401 5402 if (open_par) 5403 errx(EX_USAGE, 5404 "limit cannot be part of an or block"); 5405 if (have_state) 5406 errx(EX_USAGE, "only one of keep-state and" 5407 "limit is allowed"); 5408 have_state = cmd; 5409 5410 cmd->len = F_INSN_SIZE(ipfw_insn_limit); 5411 cmd->opcode = O_LIMIT; 5412 c->limit_mask = c->conn_limit = 0; 5413 5414 while (ac > 0) { 5415 if ((val = match_token(limit_masks, *av)) <= 0) 5416 break; 5417 c->limit_mask |= val; 5418 ac--; av++; 5419 } 5420 5421 if (c->limit_mask == 0) 5422 errx(EX_USAGE, "limit: missing limit mask"); 5423 5424 GET_UINT_ARG(c->conn_limit, 1, 65534, TOK_LIMIT, 5425 rule_options); 5426 5427 ac--; av++; 5428 break; 5429 } 5430 5431 case TOK_PROTO: 5432 NEED1("missing protocol"); 5433 if (add_proto(cmd, *av, &proto)) { 5434 ac--; av++; 5435 } else 5436 errx(EX_DATAERR, "invalid protocol ``%s''", 5437 *av); 5438 break; 5439 5440 case TOK_SRCIP: 5441 NEED1("missing source IP"); 5442 if (add_srcip(cmd, *av)) { 5443 ac--; av++; 5444 } 5445 break; 5446 5447 case TOK_DSTIP: 5448 NEED1("missing destination IP"); 5449 if (add_dstip(cmd, *av)) { 5450 ac--; av++; 5451 } 5452 break; 5453 5454 case TOK_SRCIP6: 5455 NEED1("missing source IP6"); 5456 if (add_srcip6(cmd, *av)) { 5457 ac--; av++; 5458 } 5459 break; 5460 5461 case TOK_DSTIP6: 5462 NEED1("missing destination IP6"); 5463 if (add_dstip6(cmd, *av)) { 5464 ac--; av++; 5465 } 5466 break; 5467 5468 case TOK_SRCPORT: 5469 NEED1("missing source port"); 5470 if (_substrcmp(*av, "any") == 0 || 5471 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5472 ac--; av++; 5473 } else 5474 errx(EX_DATAERR, "invalid source port %s", *av); 5475 break; 5476 5477 case TOK_DSTPORT: 5478 NEED1("missing destination port"); 5479 if (_substrcmp(*av, "any") == 0 || 5480 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5481 ac--; av++; 5482 } else 5483 errx(EX_DATAERR, "invalid destination port %s", 5484 *av); 5485 break; 5486 5487 case TOK_MAC: 5488 if (add_mac(cmd, ac, av)) { 5489 ac -= 2; av += 2; 5490 } 5491 break; 5492 5493 case TOK_MACTYPE: 5494 NEED1("missing mac type"); 5495 if (!add_mactype(cmd, ac, *av)) 5496 errx(EX_DATAERR, "invalid mac type %s", *av); 5497 ac--; av++; 5498 break; 5499 5500 case TOK_VERREVPATH: 5501 fill_cmd(cmd, O_VERREVPATH, 0, 0); 5502 break; 5503 5504 case TOK_VERSRCREACH: 5505 fill_cmd(cmd, O_VERSRCREACH, 0, 0); 5506 break; 5507 5508 case TOK_ANTISPOOF: 5509 fill_cmd(cmd, O_ANTISPOOF, 0, 0); 5510 break; 5511 5512 case TOK_IPSEC: 5513 fill_cmd(cmd, O_IPSEC, 0, 0); 5514 break; 5515 5516 case TOK_IPV6: 5517 fill_cmd(cmd, O_IP6, 0, 0); 5518 break; 5519 5520 case TOK_IPV4: 5521 fill_cmd(cmd, O_IP4, 0, 0); 5522 break; 5523 5524 case TOK_EXT6HDR: 5525 fill_ext6hdr( cmd, *av ); 5526 ac--; av++; 5527 break; 5528 5529 case TOK_FLOWID: 5530 if (proto != IPPROTO_IPV6 ) 5531 errx( EX_USAGE, "flow-id filter is active " 5532 "only for ipv6 protocol\n"); 5533 fill_flow6( (ipfw_insn_u32 *) cmd, *av ); 5534 ac--; av++; 5535 break; 5536 5537 case TOK_COMMENT: 5538 fill_comment(cmd, ac, av); 5539 av += ac; 5540 ac = 0; 5541 break; 5542 5543 case TOK_TAGGED: 5544 if (ac > 0 && strpbrk(*av, "-,")) { 5545 if (!add_ports(cmd, *av, 0, O_TAGGED)) 5546 errx(EX_DATAERR, "tagged: invalid tag" 5547 " list: %s", *av); 5548 } 5549 else { 5550 uint16_t tag; 5551 5552 GET_UINT_ARG(tag, 1, 65534, TOK_TAGGED, 5553 rule_options); 5554 fill_cmd(cmd, O_TAGGED, 0, tag); 5555 } 5556 ac--; av++; 5557 break; 5558 5559 default: 5560 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s); 5561 } 5562 if (F_LEN(cmd) > 0) { /* prepare to advance */ 5563 prev = cmd; 5564 cmd = next_cmd(cmd); 5565 } 5566 } 5567 5568 done: 5569 /* 5570 * Now copy stuff into the rule. 5571 * If we have a keep-state option, the first instruction 5572 * must be a PROBE_STATE (which is generated here). 5573 * If we have a LOG option, it was stored as the first command, 5574 * and now must be moved to the top of the action part. 5575 */ 5576 dst = (ipfw_insn *)rule->cmd; 5577 5578 /* 5579 * First thing to write into the command stream is the match probability. 5580 */ 5581 if (match_prob != 1) { /* 1 means always match */ 5582 dst->opcode = O_PROB; 5583 dst->len = 2; 5584 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff); 5585 dst += dst->len; 5586 } 5587 5588 /* 5589 * generate O_PROBE_STATE if necessary 5590 */ 5591 if (have_state && have_state->opcode != O_CHECK_STATE) { 5592 fill_cmd(dst, O_PROBE_STATE, 0, 0); 5593 dst = next_cmd(dst); 5594 } 5595 5596 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */ 5597 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) { 5598 i = F_LEN(src); 5599 5600 switch (src->opcode) { 5601 case O_LOG: 5602 case O_KEEP_STATE: 5603 case O_LIMIT: 5604 case O_ALTQ: 5605 case O_TAG: 5606 break; 5607 default: 5608 bcopy(src, dst, i * sizeof(uint32_t)); 5609 dst += i; 5610 } 5611 } 5612 5613 /* 5614 * put back the have_state command as last opcode 5615 */ 5616 if (have_state && have_state->opcode != O_CHECK_STATE) { 5617 i = F_LEN(have_state); 5618 bcopy(have_state, dst, i * sizeof(uint32_t)); 5619 dst += i; 5620 } 5621 /* 5622 * start action section 5623 */ 5624 rule->act_ofs = dst - rule->cmd; 5625 5626 /* put back O_LOG, O_ALTQ, O_TAG if necessary */ 5627 if (have_log) { 5628 i = F_LEN(have_log); 5629 bcopy(have_log, dst, i * sizeof(uint32_t)); 5630 dst += i; 5631 } 5632 if (have_altq) { 5633 i = F_LEN(have_altq); 5634 bcopy(have_altq, dst, i * sizeof(uint32_t)); 5635 dst += i; 5636 } 5637 if (have_tag) { 5638 i = F_LEN(have_tag); 5639 bcopy(have_tag, dst, i * sizeof(uint32_t)); 5640 dst += i; 5641 } 5642 /* 5643 * copy all other actions 5644 */ 5645 for (src = (ipfw_insn *)actbuf; src != action; src += i) { 5646 i = F_LEN(src); 5647 bcopy(src, dst, i * sizeof(uint32_t)); 5648 dst += i; 5649 } 5650 5651 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd); 5652 i = (char *)dst - (char *)rule; 5653 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1) 5654 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD"); 5655 if (!do_quiet) 5656 show_ipfw(rule, 0, 0); 5657 } 5658 5659 static void 5660 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */) 5661 { 5662 int rulenum; 5663 int failed = EX_OK; 5664 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG"; 5665 5666 av++; ac--; 5667 5668 if (!ac) { 5669 /* clear all entries */ 5670 if (do_cmd(optname, NULL, 0) < 0) 5671 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name); 5672 if (!do_quiet) 5673 printf("%s.\n", optname == IP_FW_ZERO ? 5674 "Accounting cleared":"Logging counts reset"); 5675 5676 return; 5677 } 5678 5679 while (ac) { 5680 /* Rule number */ 5681 if (isdigit(**av)) { 5682 rulenum = atoi(*av); 5683 av++; 5684 ac--; 5685 if (do_cmd(optname, &rulenum, sizeof rulenum)) { 5686 warn("rule %u: setsockopt(IP_FW_%s)", 5687 rulenum, name); 5688 failed = EX_UNAVAILABLE; 5689 } else if (!do_quiet) 5690 printf("Entry %d %s.\n", rulenum, 5691 optname == IP_FW_ZERO ? 5692 "cleared" : "logging count reset"); 5693 } else { 5694 errx(EX_USAGE, "invalid rule number ``%s''", *av); 5695 } 5696 } 5697 if (failed != EX_OK) 5698 exit(failed); 5699 } 5700 5701 static void 5702 flush(int force) 5703 { 5704 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH; 5705 5706 if (!force && !do_quiet) { /* need to ask user */ 5707 int c; 5708 5709 printf("Are you sure? [yn] "); 5710 fflush(stdout); 5711 do { 5712 c = toupper(getc(stdin)); 5713 while (c != '\n' && getc(stdin) != '\n') 5714 if (feof(stdin)) 5715 return; /* and do not flush */ 5716 } while (c != 'Y' && c != 'N'); 5717 printf("\n"); 5718 if (c == 'N') /* user said no */ 5719 return; 5720 } 5721 if (do_cmd(cmd, NULL, 0) < 0) 5722 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)", 5723 do_pipe ? "DUMMYNET" : "FW"); 5724 if (!do_quiet) 5725 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules"); 5726 } 5727 5728 /* 5729 * Free a the (locally allocated) copy of command line arguments. 5730 */ 5731 static void 5732 free_args(int ac, char **av) 5733 { 5734 int i; 5735 5736 for (i=0; i < ac; i++) 5737 free(av[i]); 5738 free(av); 5739 } 5740 5741 /* 5742 * This one handles all table-related commands 5743 * ipfw table N add addr[/masklen] [value] 5744 * ipfw table N delete addr[/masklen] 5745 * ipfw table N flush 5746 * ipfw table N list 5747 */ 5748 static void 5749 table_handler(int ac, char *av[]) 5750 { 5751 ipfw_table_entry ent; 5752 ipfw_table *tbl; 5753 int do_add; 5754 char *p; 5755 socklen_t l; 5756 uint32_t a; 5757 5758 ac--; av++; 5759 if (ac && isdigit(**av)) { 5760 ent.tbl = atoi(*av); 5761 ac--; av++; 5762 } else 5763 errx(EX_USAGE, "table number required"); 5764 NEED1("table needs command"); 5765 if (_substrcmp(*av, "add") == 0 || 5766 _substrcmp(*av, "delete") == 0) { 5767 do_add = **av == 'a'; 5768 ac--; av++; 5769 if (!ac) 5770 errx(EX_USAGE, "IP address required"); 5771 p = strchr(*av, '/'); 5772 if (p) { 5773 *p++ = '\0'; 5774 ent.masklen = atoi(p); 5775 if (ent.masklen > 32) 5776 errx(EX_DATAERR, "bad width ``%s''", p); 5777 } else 5778 ent.masklen = 32; 5779 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0) 5780 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5781 ac--; av++; 5782 if (do_add && ac) { 5783 unsigned int tval; 5784 /* isdigit is a bit of a hack here.. */ 5785 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) { 5786 ent.value = strtoul(*av, NULL, 0); 5787 } else { 5788 if (lookup_host(*av, (struct in_addr *)&tval) == 0) { 5789 /* The value must be stored in host order * 5790 * so that the values < 65k can be distinguished */ 5791 ent.value = ntohl(tval); 5792 } else { 5793 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5794 } 5795 } 5796 } else 5797 ent.value = 0; 5798 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL, 5799 &ent, sizeof(ent)) < 0) { 5800 /* If running silent, don't bomb out on these errors. */ 5801 if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH)))) 5802 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)", 5803 do_add ? "ADD" : "DEL"); 5804 /* In silent mode, react to a failed add by deleting */ 5805 if (do_add) { 5806 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent)); 5807 if (do_cmd(IP_FW_TABLE_ADD, 5808 &ent, sizeof(ent)) < 0) 5809 err(EX_OSERR, 5810 "setsockopt(IP_FW_TABLE_ADD)"); 5811 } 5812 } 5813 } else if (_substrcmp(*av, "flush") == 0) { 5814 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0) 5815 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)"); 5816 } else if (_substrcmp(*av, "list") == 0) { 5817 a = ent.tbl; 5818 l = sizeof(a); 5819 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0) 5820 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)"); 5821 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry); 5822 tbl = malloc(l); 5823 if (tbl == NULL) 5824 err(EX_OSERR, "malloc"); 5825 tbl->tbl = ent.tbl; 5826 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0) 5827 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)"); 5828 for (a = 0; a < tbl->cnt; a++) { 5829 /* Heuristic to print it the right way */ 5830 /* values < 64k are printed as numbers */ 5831 unsigned int tval; 5832 tval = tbl->ent[a].value; 5833 if (tval > 0xffff) { 5834 char tbuf[128]; 5835 strncpy(tbuf, inet_ntoa(*(struct in_addr *) 5836 &tbl->ent[a].addr), 127); 5837 /* inet_ntoa expects host order */ 5838 tval = htonl(tval); 5839 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen, 5840 inet_ntoa(*(struct in_addr *)&tval)); 5841 } else { 5842 printf("%s/%u %u\n", 5843 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr), 5844 tbl->ent[a].masklen, tbl->ent[a].value); 5845 } 5846 } 5847 } else 5848 errx(EX_USAGE, "invalid table command %s", *av); 5849 } 5850 5851 static void 5852 show_nat(int ac, char **av) { 5853 struct cfg_nat *n; 5854 struct cfg_redir *e; 5855 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size; 5856 int nat_cnt, r; 5857 uint8_t *data, *p; 5858 char **lav, *endptr; 5859 5860 do_rule = 0; 5861 nalloc = 1024; 5862 size = 0; 5863 data = NULL; 5864 ac--; av++; 5865 5866 /* Parse parameters. */ 5867 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) { 5868 if (!strncmp(av[0], "config", strlen(av[0]))) { 5869 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1; 5870 continue; 5871 } 5872 /* Convert command line rule #. */ 5873 frule = lrule = strtoul(av[0], &endptr, 10); 5874 if (*endptr == '-') 5875 lrule = strtoul(endptr+1, &endptr, 10); 5876 if (lrule == 0) 5877 err(EX_USAGE, "invalid rule number: %s", av[0]); 5878 do_rule = 1; 5879 } 5880 5881 nbytes = nalloc; 5882 while (nbytes >= nalloc) { 5883 nalloc = nalloc * 2; 5884 nbytes = nalloc; 5885 if ((data = realloc(data, nbytes)) == NULL) 5886 err(EX_OSERR, "realloc"); 5887 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0) 5888 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)", 5889 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG"); 5890 } 5891 if (nbytes == 0) 5892 exit(0); 5893 if (do_cfg) { 5894 nat_cnt = *((int *)data); 5895 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) { 5896 n = (struct cfg_nat *)&data[i]; 5897 if (do_rule) { 5898 if (!(frule <= n->id && lrule >= n->id)) 5899 continue; 5900 } 5901 print_nat_config(&data[i]); 5902 i += sizeof(struct cfg_nat); 5903 e = (struct cfg_redir *)&data[i]; 5904 if (e->mode == REDIR_ADDR || e->mode == REDIR_PORT || 5905 e->mode == REDIR_PROTO) 5906 i += sizeof(struct cfg_redir) + e->spool_cnt * 5907 sizeof(struct cfg_spool); 5908 } 5909 } else { 5910 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) { 5911 p = &data[i]; 5912 if (p == data + nbytes) 5913 break; 5914 bcopy(p, &r, sizeof(int)); 5915 if (do_rule) { 5916 if (!(frule <= r && lrule >= r)) 5917 continue; 5918 } 5919 printf("nat %u: %s\n", r, p+sizeof(int)); 5920 } 5921 } 5922 } 5923 5924 /* 5925 * Called with the arguments (excluding program name). 5926 * Returns 0 if successful, 1 if empty command, errx() in case of errors. 5927 */ 5928 static int 5929 ipfw_main(int oldac, char **oldav) 5930 { 5931 int ch, ac, save_ac; 5932 char **av, **save_av; 5933 int do_acct = 0; /* Show packet/byte count */ 5934 5935 #define WHITESP " \t\f\v\n\r" 5936 if (oldac == 0) 5937 return 1; 5938 else if (oldac == 1) { 5939 /* 5940 * If we are called with a single string, try to split it into 5941 * arguments for subsequent parsing. 5942 * But first, remove spaces after a ',', by copying the string 5943 * in-place. 5944 */ 5945 char *arg = oldav[0]; /* The string... */ 5946 int l = strlen(arg); 5947 int copy = 0; /* 1 if we need to copy, 0 otherwise */ 5948 int i, j; 5949 for (i = j = 0; i < l; i++) { 5950 if (arg[i] == '#') /* comment marker */ 5951 break; 5952 if (copy) { 5953 arg[j++] = arg[i]; 5954 copy = !index("," WHITESP, arg[i]); 5955 } else { 5956 copy = !index(WHITESP, arg[i]); 5957 if (copy) 5958 arg[j++] = arg[i]; 5959 } 5960 } 5961 if (!copy && j > 0) /* last char was a 'blank', remove it */ 5962 j--; 5963 l = j; /* the new argument length */ 5964 arg[j++] = '\0'; 5965 if (l == 0) /* empty string! */ 5966 return 1; 5967 5968 /* 5969 * First, count number of arguments. Because of the previous 5970 * processing, this is just the number of blanks plus 1. 5971 */ 5972 for (i = 0, ac = 1; i < l; i++) 5973 if (index(WHITESP, arg[i]) != NULL) 5974 ac++; 5975 5976 av = calloc(ac, sizeof(char *)); 5977 5978 /* 5979 * Second, copy arguments from cmd[] to av[]. For each one, 5980 * j is the initial character, i is the one past the end. 5981 */ 5982 for (ac = 0, i = j = 0; i < l; i++) 5983 if (index(WHITESP, arg[i]) != NULL || i == l-1) { 5984 if (i == l-1) 5985 i++; 5986 av[ac] = calloc(i-j+1, 1); 5987 bcopy(arg+j, av[ac], i-j); 5988 ac++; 5989 j = i + 1; 5990 } 5991 } else { 5992 /* 5993 * If an argument ends with ',' join with the next one. 5994 */ 5995 int first, i, l; 5996 5997 av = calloc(oldac, sizeof(char *)); 5998 for (first = i = ac = 0, l = 0; i < oldac; i++) { 5999 char *arg = oldav[i]; 6000 int k = strlen(arg); 6001 6002 l += k; 6003 if (arg[k-1] != ',' || i == oldac-1) { 6004 /* Time to copy. */ 6005 av[ac] = calloc(l+1, 1); 6006 for (l=0; first <= i; first++) { 6007 strcat(av[ac]+l, oldav[first]); 6008 l += strlen(oldav[first]); 6009 } 6010 ac++; 6011 l = 0; 6012 first = i+1; 6013 } 6014 } 6015 } 6016 6017 /* Set the force flag for non-interactive processes */ 6018 if (!do_force) 6019 do_force = !isatty(STDIN_FILENO); 6020 6021 /* Save arguments for final freeing of memory. */ 6022 save_ac = ac; 6023 save_av = av; 6024 6025 optind = optreset = 0; 6026 while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1) 6027 switch (ch) { 6028 case 'a': 6029 do_acct = 1; 6030 break; 6031 6032 case 'b': 6033 comment_only = 1; 6034 do_compact = 1; 6035 break; 6036 6037 case 'c': 6038 do_compact = 1; 6039 break; 6040 6041 case 'd': 6042 do_dynamic = 1; 6043 break; 6044 6045 case 'e': 6046 do_expired = 1; 6047 break; 6048 6049 case 'f': 6050 do_force = 1; 6051 break; 6052 6053 case 'h': /* help */ 6054 free_args(save_ac, save_av); 6055 help(); 6056 break; /* NOTREACHED */ 6057 6058 case 'n': 6059 test_only = 1; 6060 break; 6061 6062 case 'N': 6063 do_resolv = 1; 6064 break; 6065 6066 case 'q': 6067 do_quiet = 1; 6068 break; 6069 6070 case 's': /* sort */ 6071 do_sort = atoi(optarg); 6072 break; 6073 6074 case 'S': 6075 show_sets = 1; 6076 break; 6077 6078 case 't': 6079 do_time = 1; 6080 break; 6081 6082 case 'T': 6083 do_time = 2; /* numeric timestamp */ 6084 break; 6085 6086 case 'v': /* verbose */ 6087 verbose = 1; 6088 break; 6089 6090 default: 6091 free_args(save_ac, save_av); 6092 return 1; 6093 } 6094 6095 ac -= optind; 6096 av += optind; 6097 NEED1("bad arguments, for usage summary ``ipfw''"); 6098 6099 /* 6100 * An undocumented behaviour of ipfw1 was to allow rule numbers first, 6101 * e.g. "100 add allow ..." instead of "add 100 allow ...". 6102 * In case, swap first and second argument to get the normal form. 6103 */ 6104 if (ac > 1 && isdigit(*av[0])) { 6105 char *p = av[0]; 6106 6107 av[0] = av[1]; 6108 av[1] = p; 6109 } 6110 6111 /* 6112 * Optional: pipe, queue or nat. 6113 */ 6114 do_nat = 0; 6115 do_pipe = 0; 6116 if (!strncmp(*av, "nat", strlen(*av))) 6117 do_nat = 1; 6118 else if (!strncmp(*av, "pipe", strlen(*av))) 6119 do_pipe = 1; 6120 else if (_substrcmp(*av, "queue") == 0) 6121 do_pipe = 2; 6122 if (do_pipe || do_nat) { 6123 ac--; 6124 av++; 6125 } 6126 NEED1("missing command"); 6127 6128 /* 6129 * For pipes, queues and nats we normally say 'nat|pipe NN config' 6130 * but the code is easier to parse as 'nat|pipe config NN' 6131 * so we swap the two arguments. 6132 */ 6133 if ((do_pipe || do_nat) && ac > 1 && isdigit(*av[0])) { 6134 char *p = av[0]; 6135 6136 av[0] = av[1]; 6137 av[1] = p; 6138 } 6139 6140 if (_substrcmp(*av, "add") == 0) 6141 add(ac, av); 6142 else if (do_nat && _substrcmp(*av, "show") == 0) 6143 show_nat(ac, av); 6144 else if (do_pipe && _substrcmp(*av, "config") == 0) 6145 config_pipe(ac, av); 6146 else if (do_nat && _substrcmp(*av, "config") == 0) 6147 config_nat(ac, av); 6148 else if (_substrcmp(*av, "delete") == 0) 6149 delete(ac, av); 6150 else if (_substrcmp(*av, "flush") == 0) 6151 flush(do_force); 6152 else if (_substrcmp(*av, "zero") == 0) 6153 zero(ac, av, IP_FW_ZERO); 6154 else if (_substrcmp(*av, "resetlog") == 0) 6155 zero(ac, av, IP_FW_RESETLOG); 6156 else if (_substrcmp(*av, "print") == 0 || 6157 _substrcmp(*av, "list") == 0) 6158 list(ac, av, do_acct); 6159 else if (_substrcmp(*av, "set") == 0) 6160 sets_handler(ac, av); 6161 else if (_substrcmp(*av, "table") == 0) 6162 table_handler(ac, av); 6163 else if (_substrcmp(*av, "enable") == 0) 6164 sysctl_handler(ac, av, 1); 6165 else if (_substrcmp(*av, "disable") == 0) 6166 sysctl_handler(ac, av, 0); 6167 else if (_substrcmp(*av, "show") == 0) 6168 list(ac, av, 1 /* show counters */); 6169 else 6170 errx(EX_USAGE, "bad command `%s'", *av); 6171 6172 /* Free memory allocated in the argument parsing. */ 6173 free_args(save_ac, save_av); 6174 return 0; 6175 } 6176 6177 6178 static void 6179 ipfw_readfile(int ac, char *av[]) 6180 { 6181 #define MAX_ARGS 32 6182 char buf[BUFSIZ]; 6183 char *cmd = NULL, *filename = av[ac-1]; 6184 int c, lineno=0; 6185 FILE *f = NULL; 6186 pid_t preproc = 0; 6187 6188 filename = av[ac-1]; 6189 6190 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) { 6191 switch(c) { 6192 case 'c': 6193 do_compact = 1; 6194 break; 6195 6196 case 'f': 6197 do_force = 1; 6198 break; 6199 6200 case 'N': 6201 do_resolv = 1; 6202 break; 6203 6204 case 'n': 6205 test_only = 1; 6206 break; 6207 6208 case 'p': 6209 cmd = optarg; 6210 /* 6211 * Skip previous args and delete last one, so we 6212 * pass all but the last argument to the preprocessor 6213 * via av[optind-1] 6214 */ 6215 av += optind - 1; 6216 ac -= optind - 1; 6217 if (ac < 2) 6218 errx(EX_USAGE, "no filename argument"); 6219 av[ac-1] = NULL; 6220 fprintf(stderr, "command is %s\n", av[0]); 6221 break; 6222 6223 case 'q': 6224 do_quiet = 1; 6225 break; 6226 6227 case 'S': 6228 show_sets = 1; 6229 break; 6230 6231 default: 6232 errx(EX_USAGE, "bad arguments, for usage" 6233 " summary ``ipfw''"); 6234 } 6235 6236 if (cmd != NULL) 6237 break; 6238 } 6239 6240 if (cmd == NULL && ac != optind + 1) { 6241 fprintf(stderr, "ac %d, optind %d\n", ac, optind); 6242 errx(EX_USAGE, "extraneous filename arguments"); 6243 } 6244 6245 if ((f = fopen(filename, "r")) == NULL) 6246 err(EX_UNAVAILABLE, "fopen: %s", filename); 6247 6248 if (cmd != NULL) { /* pipe through preprocessor */ 6249 int pipedes[2]; 6250 6251 if (pipe(pipedes) == -1) 6252 err(EX_OSERR, "cannot create pipe"); 6253 6254 preproc = fork(); 6255 if (preproc == -1) 6256 err(EX_OSERR, "cannot fork"); 6257 6258 if (preproc == 0) { 6259 /* 6260 * Child, will run the preprocessor with the 6261 * file on stdin and the pipe on stdout. 6262 */ 6263 if (dup2(fileno(f), 0) == -1 6264 || dup2(pipedes[1], 1) == -1) 6265 err(EX_OSERR, "dup2()"); 6266 fclose(f); 6267 close(pipedes[1]); 6268 close(pipedes[0]); 6269 execvp(cmd, av); 6270 err(EX_OSERR, "execvp(%s) failed", cmd); 6271 } else { /* parent, will reopen f as the pipe */ 6272 fclose(f); 6273 close(pipedes[1]); 6274 if ((f = fdopen(pipedes[0], "r")) == NULL) { 6275 int savederrno = errno; 6276 6277 (void)kill(preproc, SIGTERM); 6278 errno = savederrno; 6279 err(EX_OSERR, "fdopen()"); 6280 } 6281 } 6282 } 6283 6284 while (fgets(buf, BUFSIZ, f)) { /* read commands */ 6285 char linename[10]; 6286 char *args[1]; 6287 6288 lineno++; 6289 sprintf(linename, "Line %d", lineno); 6290 setprogname(linename); /* XXX */ 6291 args[0] = buf; 6292 ipfw_main(1, args); 6293 } 6294 fclose(f); 6295 if (cmd != NULL) { 6296 int status; 6297 6298 if (waitpid(preproc, &status, 0) == -1) 6299 errx(EX_OSERR, "waitpid()"); 6300 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 6301 errx(EX_UNAVAILABLE, 6302 "preprocessor exited with status %d", 6303 WEXITSTATUS(status)); 6304 else if (WIFSIGNALED(status)) 6305 errx(EX_UNAVAILABLE, 6306 "preprocessor exited with signal %d", 6307 WTERMSIG(status)); 6308 } 6309 } 6310 6311 int 6312 main(int ac, char *av[]) 6313 { 6314 /* 6315 * If the last argument is an absolute pathname, interpret it 6316 * as a file to be preprocessed. 6317 */ 6318 6319 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) 6320 ipfw_readfile(ac, av); 6321 else { 6322 if (ipfw_main(ac-1, av+1)) 6323 show_usage(); 6324 } 6325 return EX_OK; 6326 } 6327