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/ethernet.h> 51 #include <net/if.h> 52 #include <net/if_dl.h> 53 #include <net/pfvar.h> 54 #include <net/route.h> /* def. of struct route */ 55 #include <netinet/in.h> 56 #include <netinet/in_systm.h> 57 #include <netinet/ip.h> 58 #include <netinet/ip_icmp.h> 59 #include <netinet/icmp6.h> 60 #include <netinet/ip_fw.h> 61 #include <netinet/ip_dummynet.h> 62 #include <netinet/tcp.h> 63 #include <arpa/inet.h> 64 #include <alias.h> 65 66 int 67 do_resolv, /* Would try to resolve all */ 68 do_time, /* Show time stamps */ 69 do_quiet, /* Be quiet in add and flush */ 70 do_pipe, /* this cmd refers to a pipe */ 71 do_nat, /* Nat configuration. */ 72 do_sort, /* field to sort results (0 = no) */ 73 do_dynamic, /* display dynamic rules */ 74 do_expired, /* display expired dynamic rules */ 75 do_compact, /* show rules in compact mode */ 76 do_force, /* do not ask for confirmation */ 77 show_sets, /* display rule sets */ 78 test_only, /* only check syntax */ 79 comment_only, /* only print action and comment */ 80 verbose; 81 82 #define IP_MASK_ALL 0xffffffff 83 /* 84 * the following macro returns an error message if we run out of 85 * arguments. 86 */ 87 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);} 88 89 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \ 90 if (!ac) \ 91 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \ 92 if (_substrcmp(*av, "tablearg") == 0) { \ 93 arg = IP_FW_TABLEARG; \ 94 break; \ 95 } \ 96 \ 97 { \ 98 long val; \ 99 char *end; \ 100 \ 101 val = strtol(*av, &end, 10); \ 102 \ 103 if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \ 104 errx(EX_DATAERR, "%s: invalid argument: %s", \ 105 match_value(s_x, tok), *av); \ 106 \ 107 if (errno == ERANGE || val < min || val > max) \ 108 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \ 109 match_value(s_x, tok), min, max, *av); \ 110 \ 111 if (val == IP_FW_TABLEARG) \ 112 errx(EX_DATAERR, "%s: illegal argument value: %s", \ 113 match_value(s_x, tok), *av); \ 114 arg = val; \ 115 } \ 116 } while (0) 117 118 #define PRINT_UINT_ARG(str, arg) do { \ 119 if (str != NULL) \ 120 printf("%s",str); \ 121 if (arg == IP_FW_TABLEARG) \ 122 printf("tablearg"); \ 123 else \ 124 printf("%u", (uint32_t)arg); \ 125 } while (0) 126 127 /* 128 * _s_x is a structure that stores a string <-> token pairs, used in 129 * various places in the parser. Entries are stored in arrays, 130 * with an entry with s=NULL as terminator. 131 * The search routines are match_token() and match_value(). 132 * Often, an element with x=0 contains an error string. 133 * 134 */ 135 struct _s_x { 136 char const *s; 137 int x; 138 }; 139 140 static struct _s_x f_tcpflags[] = { 141 { "syn", TH_SYN }, 142 { "fin", TH_FIN }, 143 { "ack", TH_ACK }, 144 { "psh", TH_PUSH }, 145 { "rst", TH_RST }, 146 { "urg", TH_URG }, 147 { "tcp flag", 0 }, 148 { NULL, 0 } 149 }; 150 151 static struct _s_x f_tcpopts[] = { 152 { "mss", IP_FW_TCPOPT_MSS }, 153 { "maxseg", IP_FW_TCPOPT_MSS }, 154 { "window", IP_FW_TCPOPT_WINDOW }, 155 { "sack", IP_FW_TCPOPT_SACK }, 156 { "ts", IP_FW_TCPOPT_TS }, 157 { "timestamp", IP_FW_TCPOPT_TS }, 158 { "cc", IP_FW_TCPOPT_CC }, 159 { "tcp option", 0 }, 160 { NULL, 0 } 161 }; 162 163 /* 164 * IP options span the range 0 to 255 so we need to remap them 165 * (though in fact only the low 5 bits are significant). 166 */ 167 static struct _s_x f_ipopts[] = { 168 { "ssrr", IP_FW_IPOPT_SSRR}, 169 { "lsrr", IP_FW_IPOPT_LSRR}, 170 { "rr", IP_FW_IPOPT_RR}, 171 { "ts", IP_FW_IPOPT_TS}, 172 { "ip option", 0 }, 173 { NULL, 0 } 174 }; 175 176 static struct _s_x f_iptos[] = { 177 { "lowdelay", IPTOS_LOWDELAY}, 178 { "throughput", IPTOS_THROUGHPUT}, 179 { "reliability", IPTOS_RELIABILITY}, 180 { "mincost", IPTOS_MINCOST}, 181 { "congestion", IPTOS_CE}, 182 { "ecntransport", IPTOS_ECT}, 183 { "ip tos option", 0}, 184 { NULL, 0 } 185 }; 186 187 static struct _s_x limit_masks[] = { 188 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT}, 189 {"src-addr", DYN_SRC_ADDR}, 190 {"src-port", DYN_SRC_PORT}, 191 {"dst-addr", DYN_DST_ADDR}, 192 {"dst-port", DYN_DST_PORT}, 193 {NULL, 0} 194 }; 195 196 /* 197 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines 198 * This is only used in this code. 199 */ 200 #define IPPROTO_ETHERTYPE 0x1000 201 static struct _s_x ether_types[] = { 202 /* 203 * Note, we cannot use "-:&/" in the names because they are field 204 * separators in the type specifications. Also, we use s = NULL as 205 * end-delimiter, because a type of 0 can be legal. 206 */ 207 { "ip", 0x0800 }, 208 { "ipv4", 0x0800 }, 209 { "ipv6", 0x86dd }, 210 { "arp", 0x0806 }, 211 { "rarp", 0x8035 }, 212 { "vlan", 0x8100 }, 213 { "loop", 0x9000 }, 214 { "trail", 0x1000 }, 215 { "at", 0x809b }, 216 { "atalk", 0x809b }, 217 { "aarp", 0x80f3 }, 218 { "pppoe_disc", 0x8863 }, 219 { "pppoe_sess", 0x8864 }, 220 { "ipx_8022", 0x00E0 }, 221 { "ipx_8023", 0x0000 }, 222 { "ipx_ii", 0x8137 }, 223 { "ipx_snap", 0x8137 }, 224 { "ipx", 0x8137 }, 225 { "ns", 0x0600 }, 226 { NULL, 0 } 227 }; 228 229 static void show_usage(void); 230 231 enum tokens { 232 TOK_NULL=0, 233 234 TOK_OR, 235 TOK_NOT, 236 TOK_STARTBRACE, 237 TOK_ENDBRACE, 238 239 TOK_ACCEPT, 240 TOK_COUNT, 241 TOK_PIPE, 242 TOK_QUEUE, 243 TOK_DIVERT, 244 TOK_TEE, 245 TOK_NETGRAPH, 246 TOK_NGTEE, 247 TOK_FORWARD, 248 TOK_SKIPTO, 249 TOK_DENY, 250 TOK_REJECT, 251 TOK_RESET, 252 TOK_UNREACH, 253 TOK_CHECKSTATE, 254 TOK_NAT, 255 256 TOK_ALTQ, 257 TOK_LOG, 258 TOK_TAG, 259 TOK_UNTAG, 260 261 TOK_TAGGED, 262 TOK_UID, 263 TOK_GID, 264 TOK_JAIL, 265 TOK_IN, 266 TOK_LIMIT, 267 TOK_KEEPSTATE, 268 TOK_LAYER2, 269 TOK_OUT, 270 TOK_DIVERTED, 271 TOK_DIVERTEDLOOPBACK, 272 TOK_DIVERTEDOUTPUT, 273 TOK_XMIT, 274 TOK_RECV, 275 TOK_VIA, 276 TOK_FRAG, 277 TOK_IPOPTS, 278 TOK_IPLEN, 279 TOK_IPID, 280 TOK_IPPRECEDENCE, 281 TOK_IPTOS, 282 TOK_IPTTL, 283 TOK_IPVER, 284 TOK_ESTAB, 285 TOK_SETUP, 286 TOK_TCPDATALEN, 287 TOK_TCPFLAGS, 288 TOK_TCPOPTS, 289 TOK_TCPSEQ, 290 TOK_TCPACK, 291 TOK_TCPWIN, 292 TOK_ICMPTYPES, 293 TOK_MAC, 294 TOK_MACTYPE, 295 TOK_VERREVPATH, 296 TOK_VERSRCREACH, 297 TOK_ANTISPOOF, 298 TOK_IPSEC, 299 TOK_COMMENT, 300 301 TOK_PLR, 302 TOK_NOERROR, 303 TOK_BUCKETS, 304 TOK_DSTIP, 305 TOK_SRCIP, 306 TOK_DSTPORT, 307 TOK_SRCPORT, 308 TOK_ALL, 309 TOK_MASK, 310 TOK_BW, 311 TOK_DELAY, 312 TOK_RED, 313 TOK_GRED, 314 TOK_DROPTAIL, 315 TOK_PROTO, 316 TOK_WEIGHT, 317 TOK_IP, 318 TOK_IF, 319 TOK_ALOG, 320 TOK_DENY_INC, 321 TOK_SAME_PORTS, 322 TOK_UNREG_ONLY, 323 TOK_RESET_ADDR, 324 TOK_ALIAS_REV, 325 TOK_PROXY_ONLY, 326 TOK_REDIR_ADDR, 327 TOK_REDIR_PORT, 328 TOK_REDIR_PROTO, 329 330 TOK_IPV6, 331 TOK_FLOWID, 332 TOK_ICMP6TYPES, 333 TOK_EXT6HDR, 334 TOK_DSTIP6, 335 TOK_SRCIP6, 336 337 TOK_IPV4, 338 TOK_UNREACH6, 339 TOK_RESET6, 340 }; 341 342 struct _s_x dummynet_params[] = { 343 { "plr", TOK_PLR }, 344 { "noerror", TOK_NOERROR }, 345 { "buckets", TOK_BUCKETS }, 346 { "dst-ip", TOK_DSTIP }, 347 { "src-ip", TOK_SRCIP }, 348 { "dst-port", TOK_DSTPORT }, 349 { "src-port", TOK_SRCPORT }, 350 { "proto", TOK_PROTO }, 351 { "weight", TOK_WEIGHT }, 352 { "all", TOK_ALL }, 353 { "mask", TOK_MASK }, 354 { "droptail", TOK_DROPTAIL }, 355 { "red", TOK_RED }, 356 { "gred", TOK_GRED }, 357 { "bw", TOK_BW }, 358 { "bandwidth", TOK_BW }, 359 { "delay", TOK_DELAY }, 360 { "pipe", TOK_PIPE }, 361 { "queue", TOK_QUEUE }, 362 { "flow-id", TOK_FLOWID}, 363 { "dst-ipv6", TOK_DSTIP6}, 364 { "dst-ip6", TOK_DSTIP6}, 365 { "src-ipv6", TOK_SRCIP6}, 366 { "src-ip6", TOK_SRCIP6}, 367 { "dummynet-params", TOK_NULL }, 368 { NULL, 0 } /* terminator */ 369 }; 370 371 struct _s_x nat_params[] = { 372 { "ip", TOK_IP }, 373 { "if", TOK_IF }, 374 { "log", TOK_ALOG }, 375 { "deny_in", TOK_DENY_INC }, 376 { "same_ports", TOK_SAME_PORTS }, 377 { "unreg_only", TOK_UNREG_ONLY }, 378 { "reset", TOK_RESET_ADDR }, 379 { "reverse", TOK_ALIAS_REV }, 380 { "proxy_only", TOK_PROXY_ONLY }, 381 { "redirect_addr", TOK_REDIR_ADDR }, 382 { "redirect_port", TOK_REDIR_PORT }, 383 { "redirect_proto", TOK_REDIR_PROTO }, 384 { NULL, 0 } /* terminator */ 385 }; 386 387 struct _s_x rule_actions[] = { 388 { "accept", TOK_ACCEPT }, 389 { "pass", TOK_ACCEPT }, 390 { "allow", TOK_ACCEPT }, 391 { "permit", TOK_ACCEPT }, 392 { "count", TOK_COUNT }, 393 { "pipe", TOK_PIPE }, 394 { "queue", TOK_QUEUE }, 395 { "divert", TOK_DIVERT }, 396 { "tee", TOK_TEE }, 397 { "netgraph", TOK_NETGRAPH }, 398 { "ngtee", TOK_NGTEE }, 399 { "fwd", TOK_FORWARD }, 400 { "forward", TOK_FORWARD }, 401 { "skipto", TOK_SKIPTO }, 402 { "deny", TOK_DENY }, 403 { "drop", TOK_DENY }, 404 { "reject", TOK_REJECT }, 405 { "reset6", TOK_RESET6 }, 406 { "reset", TOK_RESET }, 407 { "unreach6", TOK_UNREACH6 }, 408 { "unreach", TOK_UNREACH }, 409 { "check-state", TOK_CHECKSTATE }, 410 { "//", TOK_COMMENT }, 411 { "nat", TOK_NAT }, 412 { NULL, 0 } /* terminator */ 413 }; 414 415 struct _s_x rule_action_params[] = { 416 { "altq", TOK_ALTQ }, 417 { "log", TOK_LOG }, 418 { "tag", TOK_TAG }, 419 { "untag", TOK_UNTAG }, 420 { NULL, 0 } /* terminator */ 421 }; 422 423 struct _s_x rule_options[] = { 424 { "tagged", TOK_TAGGED }, 425 { "uid", TOK_UID }, 426 { "gid", TOK_GID }, 427 { "jail", TOK_JAIL }, 428 { "in", TOK_IN }, 429 { "limit", TOK_LIMIT }, 430 { "keep-state", TOK_KEEPSTATE }, 431 { "bridged", TOK_LAYER2 }, 432 { "layer2", TOK_LAYER2 }, 433 { "out", TOK_OUT }, 434 { "diverted", TOK_DIVERTED }, 435 { "diverted-loopback", TOK_DIVERTEDLOOPBACK }, 436 { "diverted-output", TOK_DIVERTEDOUTPUT }, 437 { "xmit", TOK_XMIT }, 438 { "recv", TOK_RECV }, 439 { "via", TOK_VIA }, 440 { "fragment", TOK_FRAG }, 441 { "frag", TOK_FRAG }, 442 { "ipoptions", TOK_IPOPTS }, 443 { "ipopts", TOK_IPOPTS }, 444 { "iplen", TOK_IPLEN }, 445 { "ipid", TOK_IPID }, 446 { "ipprecedence", TOK_IPPRECEDENCE }, 447 { "iptos", TOK_IPTOS }, 448 { "ipttl", TOK_IPTTL }, 449 { "ipversion", TOK_IPVER }, 450 { "ipver", TOK_IPVER }, 451 { "estab", TOK_ESTAB }, 452 { "established", TOK_ESTAB }, 453 { "setup", TOK_SETUP }, 454 { "tcpdatalen", TOK_TCPDATALEN }, 455 { "tcpflags", TOK_TCPFLAGS }, 456 { "tcpflgs", TOK_TCPFLAGS }, 457 { "tcpoptions", TOK_TCPOPTS }, 458 { "tcpopts", TOK_TCPOPTS }, 459 { "tcpseq", TOK_TCPSEQ }, 460 { "tcpack", TOK_TCPACK }, 461 { "tcpwin", TOK_TCPWIN }, 462 { "icmptype", TOK_ICMPTYPES }, 463 { "icmptypes", TOK_ICMPTYPES }, 464 { "dst-ip", TOK_DSTIP }, 465 { "src-ip", TOK_SRCIP }, 466 { "dst-port", TOK_DSTPORT }, 467 { "src-port", TOK_SRCPORT }, 468 { "proto", TOK_PROTO }, 469 { "MAC", TOK_MAC }, 470 { "mac", TOK_MAC }, 471 { "mac-type", TOK_MACTYPE }, 472 { "verrevpath", TOK_VERREVPATH }, 473 { "versrcreach", TOK_VERSRCREACH }, 474 { "antispoof", TOK_ANTISPOOF }, 475 { "ipsec", TOK_IPSEC }, 476 { "icmp6type", TOK_ICMP6TYPES }, 477 { "icmp6types", TOK_ICMP6TYPES }, 478 { "ext6hdr", TOK_EXT6HDR}, 479 { "flow-id", TOK_FLOWID}, 480 { "ipv6", TOK_IPV6}, 481 { "ip6", TOK_IPV6}, 482 { "ipv4", TOK_IPV4}, 483 { "ip4", TOK_IPV4}, 484 { "dst-ipv6", TOK_DSTIP6}, 485 { "dst-ip6", TOK_DSTIP6}, 486 { "src-ipv6", TOK_SRCIP6}, 487 { "src-ip6", TOK_SRCIP6}, 488 { "//", TOK_COMMENT }, 489 490 { "not", TOK_NOT }, /* pseudo option */ 491 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */ 492 { "or", TOK_OR }, /* pseudo option */ 493 { "|", /* escape */ TOK_OR }, /* pseudo option */ 494 { "{", TOK_STARTBRACE }, /* pseudo option */ 495 { "(", TOK_STARTBRACE }, /* pseudo option */ 496 { "}", TOK_ENDBRACE }, /* pseudo option */ 497 { ")", TOK_ENDBRACE }, /* pseudo option */ 498 { NULL, 0 } /* terminator */ 499 }; 500 501 #define TABLEARG "tablearg" 502 503 static __inline uint64_t 504 align_uint64(uint64_t *pll) { 505 uint64_t ret; 506 507 bcopy (pll, &ret, sizeof(ret)); 508 return ret; 509 } 510 511 /* 512 * conditionally runs the command. 513 */ 514 static int 515 do_cmd(int optname, void *optval, uintptr_t optlen) 516 { 517 static int s = -1; /* the socket */ 518 int i; 519 520 if (test_only) 521 return 0; 522 523 if (s == -1) 524 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 525 if (s < 0) 526 err(EX_UNAVAILABLE, "socket"); 527 528 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET || 529 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST || 530 optname == IP_FW_TABLE_GETSIZE || 531 optname == IP_FW_NAT_GET_CONFIG || 532 optname == IP_FW_NAT_GET_LOG) 533 i = getsockopt(s, IPPROTO_IP, optname, optval, 534 (socklen_t *)optlen); 535 else 536 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen); 537 return i; 538 } 539 540 /** 541 * match_token takes a table and a string, returns the value associated 542 * with the string (-1 in case of failure). 543 */ 544 static int 545 match_token(struct _s_x *table, char *string) 546 { 547 struct _s_x *pt; 548 uint i = strlen(string); 549 550 for (pt = table ; i && pt->s != NULL ; pt++) 551 if (strlen(pt->s) == i && !bcmp(string, pt->s, i)) 552 return pt->x; 553 return -1; 554 } 555 556 /** 557 * match_value takes a table and a value, returns the string associated 558 * with the value (NULL in case of failure). 559 */ 560 static char const * 561 match_value(struct _s_x *p, int value) 562 { 563 for (; p->s != NULL; p++) 564 if (p->x == value) 565 return p->s; 566 return NULL; 567 } 568 569 /* 570 * _substrcmp takes two strings and returns 1 if they do not match, 571 * and 0 if they match exactly or the first string is a sub-string 572 * of the second. A warning is printed to stderr in the case that the 573 * first string is a sub-string of the second. 574 * 575 * This function will be removed in the future through the usual 576 * deprecation process. 577 */ 578 static int 579 _substrcmp(const char *str1, const char* str2) 580 { 581 582 if (strncmp(str1, str2, strlen(str1)) != 0) 583 return 1; 584 585 if (strlen(str1) != strlen(str2)) 586 warnx("DEPRECATED: '%s' matched '%s' as a sub-string", 587 str1, str2); 588 return 0; 589 } 590 591 /* 592 * _substrcmp2 takes three strings and returns 1 if the first two do not match, 593 * and 0 if they match exactly or the second string is a sub-string 594 * of the first. A warning is printed to stderr in the case that the 595 * first string does not match the third. 596 * 597 * This function exists to warn about the bizzare construction 598 * strncmp(str, "by", 2) which is used to allow people to use a shotcut 599 * for "bytes". The problem is that in addition to accepting "by", 600 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any 601 * other string beginning with "by". 602 * 603 * This function will be removed in the future through the usual 604 * deprecation process. 605 */ 606 static int 607 _substrcmp2(const char *str1, const char* str2, const char* str3) 608 { 609 610 if (strncmp(str1, str2, strlen(str2)) != 0) 611 return 1; 612 613 if (strcmp(str1, str3) != 0) 614 warnx("DEPRECATED: '%s' matched '%s'", 615 str1, str3); 616 return 0; 617 } 618 619 /* 620 * prints one port, symbolic or numeric 621 */ 622 static void 623 print_port(int proto, uint16_t port) 624 { 625 626 if (proto == IPPROTO_ETHERTYPE) { 627 char const *s; 628 629 if (do_resolv && (s = match_value(ether_types, port)) ) 630 printf("%s", s); 631 else 632 printf("0x%04x", port); 633 } else { 634 struct servent *se = NULL; 635 if (do_resolv) { 636 struct protoent *pe = getprotobynumber(proto); 637 638 se = getservbyport(htons(port), pe ? pe->p_name : NULL); 639 } 640 if (se) 641 printf("%s", se->s_name); 642 else 643 printf("%d", port); 644 } 645 } 646 647 struct _s_x _port_name[] = { 648 {"dst-port", O_IP_DSTPORT}, 649 {"src-port", O_IP_SRCPORT}, 650 {"ipid", O_IPID}, 651 {"iplen", O_IPLEN}, 652 {"ipttl", O_IPTTL}, 653 {"mac-type", O_MAC_TYPE}, 654 {"tcpdatalen", O_TCPDATALEN}, 655 {"tagged", O_TAGGED}, 656 {NULL, 0} 657 }; 658 659 /* 660 * Print the values in a list 16-bit items of the types above. 661 * XXX todo: add support for mask. 662 */ 663 static void 664 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode) 665 { 666 uint16_t *p = cmd->ports; 667 int i; 668 char const *sep; 669 670 if (cmd->o.len & F_NOT) 671 printf(" not"); 672 if (opcode != 0) { 673 sep = match_value(_port_name, opcode); 674 if (sep == NULL) 675 sep = "???"; 676 printf (" %s", sep); 677 } 678 sep = " "; 679 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) { 680 printf(sep); 681 print_port(proto, p[0]); 682 if (p[0] != p[1]) { 683 printf("-"); 684 print_port(proto, p[1]); 685 } 686 sep = ","; 687 } 688 } 689 690 /* 691 * Like strtol, but also translates service names into port numbers 692 * for some protocols. 693 * In particular: 694 * proto == -1 disables the protocol check; 695 * proto == IPPROTO_ETHERTYPE looks up an internal table 696 * proto == <some value in /etc/protocols> matches the values there. 697 * Returns *end == s in case the parameter is not found. 698 */ 699 static int 700 strtoport(char *s, char **end, int base, int proto) 701 { 702 char *p, *buf; 703 char *s1; 704 int i; 705 706 *end = s; /* default - not found */ 707 if (*s == '\0') 708 return 0; /* not found */ 709 710 if (isdigit(*s)) 711 return strtol(s, end, base); 712 713 /* 714 * find separator. '\\' escapes the next char. 715 */ 716 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++) 717 if (*s1 == '\\' && s1[1] != '\0') 718 s1++; 719 720 buf = malloc(s1 - s + 1); 721 if (buf == NULL) 722 return 0; 723 724 /* 725 * copy into a buffer skipping backslashes 726 */ 727 for (p = s, i = 0; p != s1 ; p++) 728 if (*p != '\\') 729 buf[i++] = *p; 730 buf[i++] = '\0'; 731 732 if (proto == IPPROTO_ETHERTYPE) { 733 i = match_token(ether_types, buf); 734 free(buf); 735 if (i != -1) { /* found */ 736 *end = s1; 737 return i; 738 } 739 } else { 740 struct protoent *pe = NULL; 741 struct servent *se; 742 743 if (proto != 0) 744 pe = getprotobynumber(proto); 745 setservent(1); 746 se = getservbyname(buf, pe ? pe->p_name : NULL); 747 free(buf); 748 if (se != NULL) { 749 *end = s1; 750 return ntohs(se->s_port); 751 } 752 } 753 return 0; /* not found */ 754 } 755 756 /* 757 * Map between current altq queue id numbers and names. 758 */ 759 static int altq_fetched = 0; 760 static TAILQ_HEAD(, pf_altq) altq_entries = 761 TAILQ_HEAD_INITIALIZER(altq_entries); 762 763 static void 764 altq_set_enabled(int enabled) 765 { 766 int pffd; 767 768 pffd = open("/dev/pf", O_RDWR); 769 if (pffd == -1) 770 err(EX_UNAVAILABLE, 771 "altq support opening pf(4) control device"); 772 if (enabled) { 773 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST) 774 err(EX_UNAVAILABLE, "enabling altq"); 775 } else { 776 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT) 777 err(EX_UNAVAILABLE, "disabling altq"); 778 } 779 close(pffd); 780 } 781 782 static void 783 altq_fetch() 784 { 785 struct pfioc_altq pfioc; 786 struct pf_altq *altq; 787 int pffd, mnr; 788 789 if (altq_fetched) 790 return; 791 altq_fetched = 1; 792 pffd = open("/dev/pf", O_RDONLY); 793 if (pffd == -1) { 794 warn("altq support opening pf(4) control device"); 795 return; 796 } 797 bzero(&pfioc, sizeof(pfioc)); 798 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) { 799 warn("altq support getting queue list"); 800 close(pffd); 801 return; 802 } 803 mnr = pfioc.nr; 804 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) { 805 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) { 806 if (errno == EBUSY) 807 break; 808 warn("altq support getting queue list"); 809 close(pffd); 810 return; 811 } 812 if (pfioc.altq.qid == 0) 813 continue; 814 altq = malloc(sizeof(*altq)); 815 if (altq == NULL) 816 err(EX_OSERR, "malloc"); 817 *altq = pfioc.altq; 818 TAILQ_INSERT_TAIL(&altq_entries, altq, entries); 819 } 820 close(pffd); 821 } 822 823 static u_int32_t 824 altq_name_to_qid(const char *name) 825 { 826 struct pf_altq *altq; 827 828 altq_fetch(); 829 TAILQ_FOREACH(altq, &altq_entries, entries) 830 if (strcmp(name, altq->qname) == 0) 831 break; 832 if (altq == NULL) 833 errx(EX_DATAERR, "altq has no queue named `%s'", name); 834 return altq->qid; 835 } 836 837 static const char * 838 altq_qid_to_name(u_int32_t qid) 839 { 840 struct pf_altq *altq; 841 842 altq_fetch(); 843 TAILQ_FOREACH(altq, &altq_entries, entries) 844 if (qid == altq->qid) 845 break; 846 if (altq == NULL) 847 return NULL; 848 return altq->qname; 849 } 850 851 static void 852 fill_altq_qid(u_int32_t *qid, const char *av) 853 { 854 *qid = altq_name_to_qid(av); 855 } 856 857 /* 858 * Fill the body of the command with the list of port ranges. 859 */ 860 static int 861 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto) 862 { 863 uint16_t a, b, *p = cmd->ports; 864 int i = 0; 865 char *s = av; 866 867 while (*s) { 868 a = strtoport(av, &s, 0, proto); 869 if (s == av) /* empty or invalid argument */ 870 return (0); 871 872 switch (*s) { 873 case '-': /* a range */ 874 av = s + 1; 875 b = strtoport(av, &s, 0, proto); 876 /* Reject expressions like '1-abc' or '1-2-3'. */ 877 if (s == av || (*s != ',' && *s != '\0')) 878 return (0); 879 p[0] = a; 880 p[1] = b; 881 break; 882 case ',': /* comma separated list */ 883 case '\0': 884 p[0] = p[1] = a; 885 break; 886 default: 887 warnx("port list: invalid separator <%c> in <%s>", 888 *s, av); 889 return (0); 890 } 891 892 i++; 893 p += 2; 894 av = s + 1; 895 } 896 if (i > 0) { 897 if (i + 1 > F_LEN_MASK) 898 errx(EX_DATAERR, "too many ports/ranges\n"); 899 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */ 900 } 901 return (i); 902 } 903 904 static struct _s_x icmpcodes[] = { 905 { "net", ICMP_UNREACH_NET }, 906 { "host", ICMP_UNREACH_HOST }, 907 { "protocol", ICMP_UNREACH_PROTOCOL }, 908 { "port", ICMP_UNREACH_PORT }, 909 { "needfrag", ICMP_UNREACH_NEEDFRAG }, 910 { "srcfail", ICMP_UNREACH_SRCFAIL }, 911 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN }, 912 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN }, 913 { "isolated", ICMP_UNREACH_ISOLATED }, 914 { "net-prohib", ICMP_UNREACH_NET_PROHIB }, 915 { "host-prohib", ICMP_UNREACH_HOST_PROHIB }, 916 { "tosnet", ICMP_UNREACH_TOSNET }, 917 { "toshost", ICMP_UNREACH_TOSHOST }, 918 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB }, 919 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE }, 920 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF }, 921 { NULL, 0 } 922 }; 923 924 static void 925 fill_reject_code(u_short *codep, char *str) 926 { 927 int val; 928 char *s; 929 930 val = strtoul(str, &s, 0); 931 if (s == str || *s != '\0' || val >= 0x100) 932 val = match_token(icmpcodes, str); 933 if (val < 0) 934 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str); 935 *codep = val; 936 return; 937 } 938 939 static void 940 print_reject_code(uint16_t code) 941 { 942 char const *s = match_value(icmpcodes, code); 943 944 if (s != NULL) 945 printf("unreach %s", s); 946 else 947 printf("unreach %u", code); 948 } 949 950 static struct _s_x icmp6codes[] = { 951 { "no-route", ICMP6_DST_UNREACH_NOROUTE }, 952 { "admin-prohib", ICMP6_DST_UNREACH_ADMIN }, 953 { "address", ICMP6_DST_UNREACH_ADDR }, 954 { "port", ICMP6_DST_UNREACH_NOPORT }, 955 { NULL, 0 } 956 }; 957 958 static void 959 fill_unreach6_code(u_short *codep, char *str) 960 { 961 int val; 962 char *s; 963 964 val = strtoul(str, &s, 0); 965 if (s == str || *s != '\0' || val >= 0x100) 966 val = match_token(icmp6codes, str); 967 if (val < 0) 968 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str); 969 *codep = val; 970 return; 971 } 972 973 static void 974 print_unreach6_code(uint16_t code) 975 { 976 char const *s = match_value(icmp6codes, code); 977 978 if (s != NULL) 979 printf("unreach6 %s", s); 980 else 981 printf("unreach6 %u", code); 982 } 983 984 /* 985 * Returns the number of bits set (from left) in a contiguous bitmask, 986 * or -1 if the mask is not contiguous. 987 * XXX this needs a proper fix. 988 * This effectively works on masks in big-endian (network) format. 989 * when compiled on little endian architectures. 990 * 991 * First bit is bit 7 of the first byte -- note, for MAC addresses, 992 * the first bit on the wire is bit 0 of the first byte. 993 * len is the max length in bits. 994 */ 995 static int 996 contigmask(uint8_t *p, int len) 997 { 998 int i, n; 999 1000 for (i=0; i<len ; i++) 1001 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */ 1002 break; 1003 for (n=i+1; n < len; n++) 1004 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0) 1005 return -1; /* mask not contiguous */ 1006 return i; 1007 } 1008 1009 /* 1010 * print flags set/clear in the two bitmasks passed as parameters. 1011 * There is a specialized check for f_tcpflags. 1012 */ 1013 static void 1014 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list) 1015 { 1016 char const *comma = ""; 1017 int i; 1018 uint8_t set = cmd->arg1 & 0xff; 1019 uint8_t clear = (cmd->arg1 >> 8) & 0xff; 1020 1021 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) { 1022 printf(" setup"); 1023 return; 1024 } 1025 1026 printf(" %s ", name); 1027 for (i=0; list[i].x != 0; i++) { 1028 if (set & list[i].x) { 1029 set &= ~list[i].x; 1030 printf("%s%s", comma, list[i].s); 1031 comma = ","; 1032 } 1033 if (clear & list[i].x) { 1034 clear &= ~list[i].x; 1035 printf("%s!%s", comma, list[i].s); 1036 comma = ","; 1037 } 1038 } 1039 } 1040 1041 /* 1042 * Print the ip address contained in a command. 1043 */ 1044 static void 1045 print_ip(ipfw_insn_ip *cmd, char const *s) 1046 { 1047 struct hostent *he = NULL; 1048 int len = F_LEN((ipfw_insn *)cmd); 1049 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d; 1050 1051 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 1052 1053 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) { 1054 printf("me"); 1055 return; 1056 } 1057 if (cmd->o.opcode == O_IP_SRC_LOOKUP || 1058 cmd->o.opcode == O_IP_DST_LOOKUP) { 1059 printf("table(%u", ((ipfw_insn *)cmd)->arg1); 1060 if (len == F_INSN_SIZE(ipfw_insn_u32)) 1061 printf(",%u", *a); 1062 printf(")"); 1063 return; 1064 } 1065 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) { 1066 uint32_t x, *map = (uint32_t *)&(cmd->mask); 1067 int i, j; 1068 char comma = '{'; 1069 1070 x = cmd->o.arg1 - 1; 1071 x = htonl( ~x ); 1072 cmd->addr.s_addr = htonl(cmd->addr.s_addr); 1073 printf("%s/%d", inet_ntoa(cmd->addr), 1074 contigmask((uint8_t *)&x, 32)); 1075 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr); 1076 x &= 0xff; /* base */ 1077 /* 1078 * Print bits and ranges. 1079 * Locate first bit set (i), then locate first bit unset (j). 1080 * If we have 3+ consecutive bits set, then print them as a 1081 * range, otherwise only print the initial bit and rescan. 1082 */ 1083 for (i=0; i < cmd->o.arg1; i++) 1084 if (map[i/32] & (1<<(i & 31))) { 1085 for (j=i+1; j < cmd->o.arg1; j++) 1086 if (!(map[ j/32] & (1<<(j & 31)))) 1087 break; 1088 printf("%c%d", comma, i+x); 1089 if (j>i+2) { /* range has at least 3 elements */ 1090 printf("-%d", j-1+x); 1091 i = j-1; 1092 } 1093 comma = ','; 1094 } 1095 printf("}"); 1096 return; 1097 } 1098 /* 1099 * len == 2 indicates a single IP, whereas lists of 1 or more 1100 * addr/mask pairs have len = (2n+1). We convert len to n so we 1101 * use that to count the number of entries. 1102 */ 1103 for (len = len / 2; len > 0; len--, a += 2) { 1104 int mb = /* mask length */ 1105 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ? 1106 32 : contigmask((uint8_t *)&(a[1]), 32); 1107 if (mb == 32 && do_resolv) 1108 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET); 1109 if (he != NULL) /* resolved to name */ 1110 printf("%s", he->h_name); 1111 else if (mb == 0) /* any */ 1112 printf("any"); 1113 else { /* numeric IP followed by some kind of mask */ 1114 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) ); 1115 if (mb < 0) 1116 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) ); 1117 else if (mb < 32) 1118 printf("/%d", mb); 1119 } 1120 if (len > 1) 1121 printf(","); 1122 } 1123 } 1124 1125 /* 1126 * prints a MAC address/mask pair 1127 */ 1128 static void 1129 print_mac(uint8_t *addr, uint8_t *mask) 1130 { 1131 int l = contigmask(mask, 48); 1132 1133 if (l == 0) 1134 printf(" any"); 1135 else { 1136 printf(" %02x:%02x:%02x:%02x:%02x:%02x", 1137 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); 1138 if (l == -1) 1139 printf("&%02x:%02x:%02x:%02x:%02x:%02x", 1140 mask[0], mask[1], mask[2], 1141 mask[3], mask[4], mask[5]); 1142 else if (l < 48) 1143 printf("/%d", l); 1144 } 1145 } 1146 1147 static void 1148 fill_icmptypes(ipfw_insn_u32 *cmd, char *av) 1149 { 1150 uint8_t type; 1151 1152 cmd->d[0] = 0; 1153 while (*av) { 1154 if (*av == ',') 1155 av++; 1156 1157 type = strtoul(av, &av, 0); 1158 1159 if (*av != ',' && *av != '\0') 1160 errx(EX_DATAERR, "invalid ICMP type"); 1161 1162 if (type > 31) 1163 errx(EX_DATAERR, "ICMP type out of range"); 1164 1165 cmd->d[0] |= 1 << type; 1166 } 1167 cmd->o.opcode = O_ICMPTYPE; 1168 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 1169 } 1170 1171 static void 1172 print_icmptypes(ipfw_insn_u32 *cmd) 1173 { 1174 int i; 1175 char sep= ' '; 1176 1177 printf(" icmptypes"); 1178 for (i = 0; i < 32; i++) { 1179 if ( (cmd->d[0] & (1 << (i))) == 0) 1180 continue; 1181 printf("%c%d", sep, i); 1182 sep = ','; 1183 } 1184 } 1185 1186 /* 1187 * Print the ip address contained in a command. 1188 */ 1189 static void 1190 print_ip6(ipfw_insn_ip6 *cmd, char const *s) 1191 { 1192 struct hostent *he = NULL; 1193 int len = F_LEN((ipfw_insn *) cmd) - 1; 1194 struct in6_addr *a = &(cmd->addr6); 1195 char trad[255]; 1196 1197 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 1198 1199 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) { 1200 printf("me6"); 1201 return; 1202 } 1203 if (cmd->o.opcode == O_IP6) { 1204 printf(" ip6"); 1205 return; 1206 } 1207 1208 /* 1209 * len == 4 indicates a single IP, whereas lists of 1 or more 1210 * addr/mask pairs have len = (2n+1). We convert len to n so we 1211 * use that to count the number of entries. 1212 */ 1213 1214 for (len = len / 4; len > 0; len -= 2, a += 2) { 1215 int mb = /* mask length */ 1216 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ? 1217 128 : contigmask((uint8_t *)&(a[1]), 128); 1218 1219 if (mb == 128 && do_resolv) 1220 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6); 1221 if (he != NULL) /* resolved to name */ 1222 printf("%s", he->h_name); 1223 else if (mb == 0) /* any */ 1224 printf("any"); 1225 else { /* numeric IP followed by some kind of mask */ 1226 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL) 1227 printf("Error ntop in print_ip6\n"); 1228 printf("%s", trad ); 1229 if (mb < 0) /* XXX not really legal... */ 1230 printf(":%s", 1231 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad))); 1232 else if (mb < 128) 1233 printf("/%d", mb); 1234 } 1235 if (len > 2) 1236 printf(","); 1237 } 1238 } 1239 1240 static void 1241 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av) 1242 { 1243 uint8_t type; 1244 1245 bzero(cmd, sizeof(*cmd)); 1246 while (*av) { 1247 if (*av == ',') 1248 av++; 1249 type = strtoul(av, &av, 0); 1250 if (*av != ',' && *av != '\0') 1251 errx(EX_DATAERR, "invalid ICMP6 type"); 1252 /* 1253 * XXX: shouldn't this be 0xFF? I can't see any reason why 1254 * we shouldn't be able to filter all possiable values 1255 * regardless of the ability of the rest of the kernel to do 1256 * anything useful with them. 1257 */ 1258 if (type > ICMP6_MAXTYPE) 1259 errx(EX_DATAERR, "ICMP6 type out of range"); 1260 cmd->d[type / 32] |= ( 1 << (type % 32)); 1261 } 1262 cmd->o.opcode = O_ICMP6TYPE; 1263 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6); 1264 } 1265 1266 1267 static void 1268 print_icmp6types(ipfw_insn_u32 *cmd) 1269 { 1270 int i, j; 1271 char sep= ' '; 1272 1273 printf(" ip6 icmp6types"); 1274 for (i = 0; i < 7; i++) 1275 for (j=0; j < 32; ++j) { 1276 if ( (cmd->d[i] & (1 << (j))) == 0) 1277 continue; 1278 printf("%c%d", sep, (i*32 + j)); 1279 sep = ','; 1280 } 1281 } 1282 1283 static void 1284 print_flow6id( ipfw_insn_u32 *cmd) 1285 { 1286 uint16_t i, limit = cmd->o.arg1; 1287 char sep = ','; 1288 1289 printf(" flow-id "); 1290 for( i=0; i < limit; ++i) { 1291 if (i == limit - 1) 1292 sep = ' '; 1293 printf("%d%c", cmd->d[i], sep); 1294 } 1295 } 1296 1297 /* structure and define for the extension header in ipv6 */ 1298 static struct _s_x ext6hdrcodes[] = { 1299 { "frag", EXT_FRAGMENT }, 1300 { "hopopt", EXT_HOPOPTS }, 1301 { "route", EXT_ROUTING }, 1302 { "dstopt", EXT_DSTOPTS }, 1303 { "ah", EXT_AH }, 1304 { "esp", EXT_ESP }, 1305 { "rthdr0", EXT_RTHDR0 }, 1306 { "rthdr2", EXT_RTHDR2 }, 1307 { NULL, 0 } 1308 }; 1309 1310 /* fills command for the extension header filtering */ 1311 int 1312 fill_ext6hdr( ipfw_insn *cmd, char *av) 1313 { 1314 int tok; 1315 char *s = av; 1316 1317 cmd->arg1 = 0; 1318 1319 while(s) { 1320 av = strsep( &s, ",") ; 1321 tok = match_token(ext6hdrcodes, av); 1322 switch (tok) { 1323 case EXT_FRAGMENT: 1324 cmd->arg1 |= EXT_FRAGMENT; 1325 break; 1326 1327 case EXT_HOPOPTS: 1328 cmd->arg1 |= EXT_HOPOPTS; 1329 break; 1330 1331 case EXT_ROUTING: 1332 cmd->arg1 |= EXT_ROUTING; 1333 break; 1334 1335 case EXT_DSTOPTS: 1336 cmd->arg1 |= EXT_DSTOPTS; 1337 break; 1338 1339 case EXT_AH: 1340 cmd->arg1 |= EXT_AH; 1341 break; 1342 1343 case EXT_ESP: 1344 cmd->arg1 |= EXT_ESP; 1345 break; 1346 1347 case EXT_RTHDR0: 1348 cmd->arg1 |= EXT_RTHDR0; 1349 break; 1350 1351 case EXT_RTHDR2: 1352 cmd->arg1 |= EXT_RTHDR2; 1353 break; 1354 1355 default: 1356 errx( EX_DATAERR, "invalid option for ipv6 exten header" ); 1357 break; 1358 } 1359 } 1360 if (cmd->arg1 == 0 ) 1361 return 0; 1362 cmd->opcode = O_EXT_HDR; 1363 cmd->len |= F_INSN_SIZE( ipfw_insn ); 1364 return 1; 1365 } 1366 1367 void 1368 print_ext6hdr( ipfw_insn *cmd ) 1369 { 1370 char sep = ' '; 1371 1372 printf(" extension header:"); 1373 if (cmd->arg1 & EXT_FRAGMENT ) { 1374 printf("%cfragmentation", sep); 1375 sep = ','; 1376 } 1377 if (cmd->arg1 & EXT_HOPOPTS ) { 1378 printf("%chop options", sep); 1379 sep = ','; 1380 } 1381 if (cmd->arg1 & EXT_ROUTING ) { 1382 printf("%crouting options", sep); 1383 sep = ','; 1384 } 1385 if (cmd->arg1 & EXT_RTHDR0 ) { 1386 printf("%crthdr0", sep); 1387 sep = ','; 1388 } 1389 if (cmd->arg1 & EXT_RTHDR2 ) { 1390 printf("%crthdr2", sep); 1391 sep = ','; 1392 } 1393 if (cmd->arg1 & EXT_DSTOPTS ) { 1394 printf("%cdestination options", sep); 1395 sep = ','; 1396 } 1397 if (cmd->arg1 & EXT_AH ) { 1398 printf("%cauthentication header", sep); 1399 sep = ','; 1400 } 1401 if (cmd->arg1 & EXT_ESP ) { 1402 printf("%cencapsulated security payload", sep); 1403 } 1404 } 1405 1406 /* 1407 * show_ipfw() prints the body of an ipfw rule. 1408 * Because the standard rule has at least proto src_ip dst_ip, we use 1409 * a helper function to produce these entries if not provided explicitly. 1410 * The first argument is the list of fields we have, the second is 1411 * the list of fields we want to be printed. 1412 * 1413 * Special cases if we have provided a MAC header: 1414 * + if the rule does not contain IP addresses/ports, do not print them; 1415 * + if the rule does not contain an IP proto, print "all" instead of "ip"; 1416 * 1417 * Once we have 'have_options', IP header fields are printed as options. 1418 */ 1419 #define HAVE_PROTO 0x0001 1420 #define HAVE_SRCIP 0x0002 1421 #define HAVE_DSTIP 0x0004 1422 #define HAVE_PROTO4 0x0008 1423 #define HAVE_PROTO6 0x0010 1424 #define HAVE_OPTIONS 0x8000 1425 1426 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP) 1427 static void 1428 show_prerequisites(int *flags, int want, int cmd) 1429 { 1430 if (comment_only) 1431 return; 1432 if ( (*flags & HAVE_IP) == HAVE_IP) 1433 *flags |= HAVE_OPTIONS; 1434 1435 if ( !(*flags & HAVE_OPTIONS)) { 1436 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) 1437 if ( (*flags & HAVE_PROTO4)) 1438 printf(" ip4"); 1439 else if ( (*flags & HAVE_PROTO6)) 1440 printf(" ip6"); 1441 else 1442 printf(" ip"); 1443 1444 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP)) 1445 printf(" from any"); 1446 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP)) 1447 printf(" to any"); 1448 } 1449 *flags |= want; 1450 } 1451 1452 static void 1453 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth) 1454 { 1455 static int twidth = 0; 1456 int l; 1457 ipfw_insn *cmd, *tagptr = NULL; 1458 char *comment = NULL; /* ptr to comment if we have one */ 1459 int proto = 0; /* default */ 1460 int flags = 0; /* prerequisites */ 1461 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */ 1462 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */ 1463 int or_block = 0; /* we are in an or block */ 1464 uint32_t set_disable; 1465 1466 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable)); 1467 1468 if (set_disable & (1 << rule->set)) { /* disabled */ 1469 if (!show_sets) 1470 return; 1471 else 1472 printf("# DISABLED "); 1473 } 1474 printf("%05u ", rule->rulenum); 1475 1476 if (pcwidth>0 || bcwidth>0) 1477 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt), 1478 bcwidth, align_uint64(&rule->bcnt)); 1479 1480 if (do_time == 2) 1481 printf("%10u ", rule->timestamp); 1482 else if (do_time == 1) { 1483 char timestr[30]; 1484 time_t t = (time_t)0; 1485 1486 if (twidth == 0) { 1487 strcpy(timestr, ctime(&t)); 1488 *strchr(timestr, '\n') = '\0'; 1489 twidth = strlen(timestr); 1490 } 1491 if (rule->timestamp) { 1492 t = _long_to_time(rule->timestamp); 1493 1494 strcpy(timestr, ctime(&t)); 1495 *strchr(timestr, '\n') = '\0'; 1496 printf("%s ", timestr); 1497 } else { 1498 printf("%*s", twidth, " "); 1499 } 1500 } 1501 1502 if (show_sets) 1503 printf("set %d ", rule->set); 1504 1505 /* 1506 * print the optional "match probability" 1507 */ 1508 if (rule->cmd_len > 0) { 1509 cmd = rule->cmd ; 1510 if (cmd->opcode == O_PROB) { 1511 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd; 1512 double d = 1.0 * p->d[0]; 1513 1514 d = (d / 0x7fffffff); 1515 printf("prob %f ", d); 1516 } 1517 } 1518 1519 /* 1520 * first print actions 1521 */ 1522 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule); 1523 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) { 1524 switch(cmd->opcode) { 1525 case O_CHECK_STATE: 1526 printf("check-state"); 1527 flags = HAVE_IP; /* avoid printing anything else */ 1528 break; 1529 1530 case O_ACCEPT: 1531 printf("allow"); 1532 break; 1533 1534 case O_COUNT: 1535 printf("count"); 1536 break; 1537 1538 case O_DENY: 1539 printf("deny"); 1540 break; 1541 1542 case O_REJECT: 1543 if (cmd->arg1 == ICMP_REJECT_RST) 1544 printf("reset"); 1545 else if (cmd->arg1 == ICMP_UNREACH_HOST) 1546 printf("reject"); 1547 else 1548 print_reject_code(cmd->arg1); 1549 break; 1550 1551 case O_UNREACH6: 1552 if (cmd->arg1 == ICMP6_UNREACH_RST) 1553 printf("reset6"); 1554 else 1555 print_unreach6_code(cmd->arg1); 1556 break; 1557 1558 case O_SKIPTO: 1559 PRINT_UINT_ARG("skipto ", cmd->arg1); 1560 break; 1561 1562 case O_PIPE: 1563 PRINT_UINT_ARG("pipe ", cmd->arg1); 1564 break; 1565 1566 case O_QUEUE: 1567 PRINT_UINT_ARG("queue ", cmd->arg1); 1568 break; 1569 1570 case O_DIVERT: 1571 PRINT_UINT_ARG("divert ", cmd->arg1); 1572 break; 1573 1574 case O_TEE: 1575 PRINT_UINT_ARG("tee ", cmd->arg1); 1576 break; 1577 1578 case O_NETGRAPH: 1579 PRINT_UINT_ARG("netgraph ", cmd->arg1); 1580 break; 1581 1582 case O_NGTEE: 1583 PRINT_UINT_ARG("ngtee ", cmd->arg1); 1584 break; 1585 1586 case O_FORWARD_IP: 1587 { 1588 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd; 1589 1590 if (s->sa.sin_addr.s_addr == INADDR_ANY) { 1591 printf("fwd tablearg"); 1592 } else { 1593 printf("fwd %s", inet_ntoa(s->sa.sin_addr)); 1594 } 1595 if (s->sa.sin_port) 1596 printf(",%d", s->sa.sin_port); 1597 } 1598 break; 1599 1600 case O_LOG: /* O_LOG is printed last */ 1601 logptr = (ipfw_insn_log *)cmd; 1602 break; 1603 1604 case O_ALTQ: /* O_ALTQ is printed after O_LOG */ 1605 altqptr = (ipfw_insn_altq *)cmd; 1606 break; 1607 1608 case O_TAG: 1609 tagptr = cmd; 1610 break; 1611 1612 case O_NAT: 1613 printf("nat %u", cmd->arg1); 1614 break; 1615 1616 default: 1617 printf("** unrecognized action %d len %d ", 1618 cmd->opcode, cmd->len); 1619 } 1620 } 1621 if (logptr) { 1622 if (logptr->max_log > 0) 1623 printf(" log logamount %d", logptr->max_log); 1624 else 1625 printf(" log"); 1626 } 1627 if (altqptr) { 1628 const char *qname; 1629 1630 qname = altq_qid_to_name(altqptr->qid); 1631 if (qname == NULL) 1632 printf(" altq ?<%u>", altqptr->qid); 1633 else 1634 printf(" altq %s", qname); 1635 } 1636 if (tagptr) { 1637 if (tagptr->len & F_NOT) 1638 PRINT_UINT_ARG(" untag ", tagptr->arg1); 1639 else 1640 PRINT_UINT_ARG(" tag ", tagptr->arg1); 1641 } 1642 1643 /* 1644 * then print the body. 1645 */ 1646 for (l = rule->act_ofs, cmd = rule->cmd ; 1647 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1648 if ((cmd->len & F_OR) || (cmd->len & F_NOT)) 1649 continue; 1650 if (cmd->opcode == O_IP4) { 1651 flags |= HAVE_PROTO4; 1652 break; 1653 } else if (cmd->opcode == O_IP6) { 1654 flags |= HAVE_PROTO6; 1655 break; 1656 } 1657 } 1658 if (rule->_pad & 1) { /* empty rules before options */ 1659 if (!do_compact) { 1660 show_prerequisites(&flags, HAVE_PROTO, 0); 1661 printf(" from any to any"); 1662 } 1663 flags |= HAVE_IP | HAVE_OPTIONS; 1664 } 1665 1666 if (comment_only) 1667 comment = "..."; 1668 1669 for (l = rule->act_ofs, cmd = rule->cmd ; 1670 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1671 /* useful alias */ 1672 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; 1673 1674 if (comment_only) { 1675 if (cmd->opcode != O_NOP) 1676 continue; 1677 printf(" // %s\n", (char *)(cmd + 1)); 1678 return; 1679 } 1680 1681 show_prerequisites(&flags, 0, cmd->opcode); 1682 1683 switch(cmd->opcode) { 1684 case O_PROB: 1685 break; /* done already */ 1686 1687 case O_PROBE_STATE: 1688 break; /* no need to print anything here */ 1689 1690 case O_IP_SRC: 1691 case O_IP_SRC_LOOKUP: 1692 case O_IP_SRC_MASK: 1693 case O_IP_SRC_ME: 1694 case O_IP_SRC_SET: 1695 show_prerequisites(&flags, HAVE_PROTO, 0); 1696 if (!(flags & HAVE_SRCIP)) 1697 printf(" from"); 1698 if ((cmd->len & F_OR) && !or_block) 1699 printf(" {"); 1700 print_ip((ipfw_insn_ip *)cmd, 1701 (flags & HAVE_OPTIONS) ? " src-ip" : ""); 1702 flags |= HAVE_SRCIP; 1703 break; 1704 1705 case O_IP_DST: 1706 case O_IP_DST_LOOKUP: 1707 case O_IP_DST_MASK: 1708 case O_IP_DST_ME: 1709 case O_IP_DST_SET: 1710 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1711 if (!(flags & HAVE_DSTIP)) 1712 printf(" to"); 1713 if ((cmd->len & F_OR) && !or_block) 1714 printf(" {"); 1715 print_ip((ipfw_insn_ip *)cmd, 1716 (flags & HAVE_OPTIONS) ? " dst-ip" : ""); 1717 flags |= HAVE_DSTIP; 1718 break; 1719 1720 case O_IP6_SRC: 1721 case O_IP6_SRC_MASK: 1722 case O_IP6_SRC_ME: 1723 show_prerequisites(&flags, HAVE_PROTO, 0); 1724 if (!(flags & HAVE_SRCIP)) 1725 printf(" from"); 1726 if ((cmd->len & F_OR) && !or_block) 1727 printf(" {"); 1728 print_ip6((ipfw_insn_ip6 *)cmd, 1729 (flags & HAVE_OPTIONS) ? " src-ip6" : ""); 1730 flags |= HAVE_SRCIP | HAVE_PROTO; 1731 break; 1732 1733 case O_IP6_DST: 1734 case O_IP6_DST_MASK: 1735 case O_IP6_DST_ME: 1736 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1737 if (!(flags & HAVE_DSTIP)) 1738 printf(" to"); 1739 if ((cmd->len & F_OR) && !or_block) 1740 printf(" {"); 1741 print_ip6((ipfw_insn_ip6 *)cmd, 1742 (flags & HAVE_OPTIONS) ? " dst-ip6" : ""); 1743 flags |= HAVE_DSTIP; 1744 break; 1745 1746 case O_FLOW6ID: 1747 print_flow6id( (ipfw_insn_u32 *) cmd ); 1748 flags |= HAVE_OPTIONS; 1749 break; 1750 1751 case O_IP_DSTPORT: 1752 show_prerequisites(&flags, HAVE_IP, 0); 1753 case O_IP_SRCPORT: 1754 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1755 if ((cmd->len & F_OR) && !or_block) 1756 printf(" {"); 1757 print_newports((ipfw_insn_u16 *)cmd, proto, 1758 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1759 break; 1760 1761 case O_PROTO: { 1762 struct protoent *pe = NULL; 1763 1764 if ((cmd->len & F_OR) && !or_block) 1765 printf(" {"); 1766 if (cmd->len & F_NOT) 1767 printf(" not"); 1768 proto = cmd->arg1; 1769 pe = getprotobynumber(cmd->arg1); 1770 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) && 1771 !(flags & HAVE_PROTO)) 1772 show_prerequisites(&flags, 1773 HAVE_IP | HAVE_OPTIONS, 0); 1774 if (flags & HAVE_OPTIONS) 1775 printf(" proto"); 1776 if (pe) 1777 printf(" %s", pe->p_name); 1778 else 1779 printf(" %u", cmd->arg1); 1780 } 1781 flags |= HAVE_PROTO; 1782 break; 1783 1784 default: /*options ... */ 1785 if (!(cmd->len & (F_OR|F_NOT))) 1786 if (((cmd->opcode == O_IP6) && 1787 (flags & HAVE_PROTO6)) || 1788 ((cmd->opcode == O_IP4) && 1789 (flags & HAVE_PROTO4))) 1790 break; 1791 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0); 1792 if ((cmd->len & F_OR) && !or_block) 1793 printf(" {"); 1794 if (cmd->len & F_NOT && cmd->opcode != O_IN) 1795 printf(" not"); 1796 switch(cmd->opcode) { 1797 case O_MACADDR2: { 1798 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd; 1799 1800 printf(" MAC"); 1801 print_mac(m->addr, m->mask); 1802 print_mac(m->addr + 6, m->mask + 6); 1803 } 1804 break; 1805 1806 case O_MAC_TYPE: 1807 print_newports((ipfw_insn_u16 *)cmd, 1808 IPPROTO_ETHERTYPE, cmd->opcode); 1809 break; 1810 1811 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(const char *p, uint8_t *addr, uint8_t *mask) 4378 { 4379 int i, l; 4380 char *ap, *ptr, *optr; 4381 struct ether_addr *mac; 4382 const char *macset = "0123456789abcdefABCDEF:"; 4383 4384 if (strcmp(p, "any") == 0) { 4385 for (i = 0; i < ETHER_ADDR_LEN; i++) 4386 addr[i] = mask[i] = 0; 4387 return; 4388 } 4389 4390 optr = ptr = strdup(p); 4391 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) { 4392 l = strlen(ap); 4393 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL) 4394 errx(EX_DATAERR, "Incorrect MAC address"); 4395 bcopy(mac, addr, ETHER_ADDR_LEN); 4396 } else 4397 errx(EX_DATAERR, "Incorrect MAC address"); 4398 4399 if (ptr != NULL) { /* we have mask? */ 4400 if (p[ptr - optr - 1] == '/') { /* mask len */ 4401 l = strtol(ptr, &ap, 10); 4402 if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0) 4403 errx(EX_DATAERR, "Incorrect mask length"); 4404 for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++) 4405 mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l); 4406 } else { /* mask */ 4407 l = strlen(ptr); 4408 if (strspn(ptr, macset) != l || 4409 (mac = ether_aton(ptr)) == NULL) 4410 errx(EX_DATAERR, "Incorrect mask"); 4411 bcopy(mac, mask, ETHER_ADDR_LEN); 4412 } 4413 } else { /* default mask: ff:ff:ff:ff:ff:ff */ 4414 for (i = 0; i < ETHER_ADDR_LEN; i++) 4415 mask[i] = 0xff; 4416 } 4417 for (i = 0; i < ETHER_ADDR_LEN; i++) 4418 addr[i] &= mask[i]; 4419 4420 free(optr); 4421 } 4422 4423 /* 4424 * helper function, updates the pointer to cmd with the length 4425 * of the current command, and also cleans up the first word of 4426 * the new command in case it has been clobbered before. 4427 */ 4428 static ipfw_insn * 4429 next_cmd(ipfw_insn *cmd) 4430 { 4431 cmd += F_LEN(cmd); 4432 bzero(cmd, sizeof(*cmd)); 4433 return cmd; 4434 } 4435 4436 /* 4437 * Takes arguments and copies them into a comment 4438 */ 4439 static void 4440 fill_comment(ipfw_insn *cmd, int ac, char **av) 4441 { 4442 int i, l; 4443 char *p = (char *)(cmd + 1); 4444 4445 cmd->opcode = O_NOP; 4446 cmd->len = (cmd->len & (F_NOT | F_OR)); 4447 4448 /* Compute length of comment string. */ 4449 for (i = 0, l = 0; i < ac; i++) 4450 l += strlen(av[i]) + 1; 4451 if (l == 0) 4452 return; 4453 if (l > 84) 4454 errx(EX_DATAERR, 4455 "comment too long (max 80 chars)"); 4456 l = 1 + (l+3)/4; 4457 cmd->len = (cmd->len & (F_NOT | F_OR)) | l; 4458 for (i = 0; i < ac; i++) { 4459 strcpy(p, av[i]); 4460 p += strlen(av[i]); 4461 *p++ = ' '; 4462 } 4463 *(--p) = '\0'; 4464 } 4465 4466 /* 4467 * A function to fill simple commands of size 1. 4468 * Existing flags are preserved. 4469 */ 4470 static void 4471 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg) 4472 { 4473 cmd->opcode = opcode; 4474 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1; 4475 cmd->arg1 = arg; 4476 } 4477 4478 /* 4479 * Fetch and add the MAC address and type, with masks. This generates one or 4480 * two microinstructions, and returns the pointer to the last one. 4481 */ 4482 static ipfw_insn * 4483 add_mac(ipfw_insn *cmd, int ac, char *av[]) 4484 { 4485 ipfw_insn_mac *mac; 4486 4487 if (ac < 2) 4488 errx(EX_DATAERR, "MAC dst src"); 4489 4490 cmd->opcode = O_MACADDR2; 4491 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac); 4492 4493 mac = (ipfw_insn_mac *)cmd; 4494 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */ 4495 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]), 4496 &(mac->mask[ETHER_ADDR_LEN])); /* src */ 4497 return cmd; 4498 } 4499 4500 static ipfw_insn * 4501 add_mactype(ipfw_insn *cmd, int ac, char *av) 4502 { 4503 if (ac < 1) 4504 errx(EX_DATAERR, "missing MAC type"); 4505 if (strcmp(av, "any") != 0) { /* we have a non-null type */ 4506 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE); 4507 cmd->opcode = O_MAC_TYPE; 4508 return cmd; 4509 } else 4510 return NULL; 4511 } 4512 4513 static ipfw_insn * 4514 add_proto0(ipfw_insn *cmd, char *av, u_char *protop) 4515 { 4516 struct protoent *pe; 4517 char *ep; 4518 int proto; 4519 4520 proto = strtol(av, &ep, 10); 4521 if (*ep != '\0' || proto <= 0) { 4522 if ((pe = getprotobyname(av)) == NULL) 4523 return NULL; 4524 proto = pe->p_proto; 4525 } 4526 4527 fill_cmd(cmd, O_PROTO, 0, proto); 4528 *protop = proto; 4529 return cmd; 4530 } 4531 4532 static ipfw_insn * 4533 add_proto(ipfw_insn *cmd, char *av, u_char *protop) 4534 { 4535 u_char proto = IPPROTO_IP; 4536 4537 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4538 ; /* do not set O_IP4 nor O_IP6 */ 4539 else if (strcmp(av, "ip4") == 0) 4540 /* explicit "just IPv4" rule */ 4541 fill_cmd(cmd, O_IP4, 0, 0); 4542 else if (strcmp(av, "ip6") == 0) { 4543 /* explicit "just IPv6" rule */ 4544 proto = IPPROTO_IPV6; 4545 fill_cmd(cmd, O_IP6, 0, 0); 4546 } else 4547 return add_proto0(cmd, av, protop); 4548 4549 *protop = proto; 4550 return cmd; 4551 } 4552 4553 static ipfw_insn * 4554 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop) 4555 { 4556 u_char proto = IPPROTO_IP; 4557 4558 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4559 ; /* do not set O_IP4 nor O_IP6 */ 4560 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0) 4561 /* explicit "just IPv4" rule */ 4562 fill_cmd(cmd, O_IP4, 0, 0); 4563 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) { 4564 /* explicit "just IPv6" rule */ 4565 proto = IPPROTO_IPV6; 4566 fill_cmd(cmd, O_IP6, 0, 0); 4567 } else 4568 return add_proto0(cmd, av, protop); 4569 4570 *protop = proto; 4571 return cmd; 4572 } 4573 4574 static ipfw_insn * 4575 add_srcip(ipfw_insn *cmd, char *av) 4576 { 4577 fill_ip((ipfw_insn_ip *)cmd, av); 4578 if (cmd->opcode == O_IP_DST_SET) /* set */ 4579 cmd->opcode = O_IP_SRC_SET; 4580 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4581 cmd->opcode = O_IP_SRC_LOOKUP; 4582 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4583 cmd->opcode = O_IP_SRC_ME; 4584 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4585 cmd->opcode = O_IP_SRC; 4586 else /* addr/mask */ 4587 cmd->opcode = O_IP_SRC_MASK; 4588 return cmd; 4589 } 4590 4591 static ipfw_insn * 4592 add_dstip(ipfw_insn *cmd, char *av) 4593 { 4594 fill_ip((ipfw_insn_ip *)cmd, av); 4595 if (cmd->opcode == O_IP_DST_SET) /* set */ 4596 ; 4597 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4598 ; 4599 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4600 cmd->opcode = O_IP_DST_ME; 4601 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4602 cmd->opcode = O_IP_DST; 4603 else /* addr/mask */ 4604 cmd->opcode = O_IP_DST_MASK; 4605 return cmd; 4606 } 4607 4608 static ipfw_insn * 4609 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode) 4610 { 4611 if (_substrcmp(av, "any") == 0) { 4612 return NULL; 4613 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) { 4614 /* XXX todo: check that we have a protocol with ports */ 4615 cmd->opcode = opcode; 4616 return cmd; 4617 } 4618 return NULL; 4619 } 4620 4621 static ipfw_insn * 4622 add_src(ipfw_insn *cmd, char *av, u_char proto) 4623 { 4624 struct in6_addr a; 4625 char *host, *ch; 4626 ipfw_insn *ret = NULL; 4627 4628 if ((host = strdup(av)) == NULL) 4629 return NULL; 4630 if ((ch = strrchr(host, '/')) != NULL) 4631 *ch = '\0'; 4632 4633 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4634 inet_pton(AF_INET6, host, &a)) 4635 ret = add_srcip6(cmd, av); 4636 /* XXX: should check for IPv4, not !IPv6 */ 4637 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4638 !inet_pton(AF_INET6, host, &a))) 4639 ret = add_srcip(cmd, av); 4640 if (ret == NULL && strcmp(av, "any") != 0) 4641 ret = cmd; 4642 4643 free(host); 4644 return ret; 4645 } 4646 4647 static ipfw_insn * 4648 add_dst(ipfw_insn *cmd, char *av, u_char proto) 4649 { 4650 struct in6_addr a; 4651 char *host, *ch; 4652 ipfw_insn *ret = NULL; 4653 4654 if ((host = strdup(av)) == NULL) 4655 return NULL; 4656 if ((ch = strrchr(host, '/')) != NULL) 4657 *ch = '\0'; 4658 4659 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4660 inet_pton(AF_INET6, host, &a)) 4661 ret = add_dstip6(cmd, av); 4662 /* XXX: should check for IPv4, not !IPv6 */ 4663 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4664 !inet_pton(AF_INET6, host, &a))) 4665 ret = add_dstip(cmd, av); 4666 if (ret == NULL && strcmp(av, "any") != 0) 4667 ret = cmd; 4668 4669 free(host); 4670 return ret; 4671 } 4672 4673 /* 4674 * Parse arguments and assemble the microinstructions which make up a rule. 4675 * Rules are added into the 'rulebuf' and then copied in the correct order 4676 * into the actual rule. 4677 * 4678 * The syntax for a rule starts with the action, followed by 4679 * optional action parameters, and the various match patterns. 4680 * In the assembled microcode, the first opcode must be an O_PROBE_STATE 4681 * (generated if the rule includes a keep-state option), then the 4682 * various match patterns, log/altq actions, and the actual action. 4683 * 4684 */ 4685 static void 4686 add(int ac, char *av[]) 4687 { 4688 /* 4689 * rules are added into the 'rulebuf' and then copied in 4690 * the correct order into the actual rule. 4691 * Some things that need to go out of order (prob, action etc.) 4692 * go into actbuf[]. 4693 */ 4694 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255]; 4695 4696 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL; 4697 ipfw_insn *first_cmd; /* first match pattern */ 4698 4699 struct ip_fw *rule; 4700 4701 /* 4702 * various flags used to record that we entered some fields. 4703 */ 4704 ipfw_insn *have_state = NULL; /* check-state or keep-state */ 4705 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL; 4706 size_t len; 4707 4708 int i; 4709 4710 int open_par = 0; /* open parenthesis ( */ 4711 4712 /* proto is here because it is used to fetch ports */ 4713 u_char proto = IPPROTO_IP; /* default protocol */ 4714 4715 double match_prob = 1; /* match probability, default is always match */ 4716 4717 bzero(actbuf, sizeof(actbuf)); /* actions go here */ 4718 bzero(cmdbuf, sizeof(cmdbuf)); 4719 bzero(rulebuf, sizeof(rulebuf)); 4720 4721 rule = (struct ip_fw *)rulebuf; 4722 cmd = (ipfw_insn *)cmdbuf; 4723 action = (ipfw_insn *)actbuf; 4724 4725 av++; ac--; 4726 4727 /* [rule N] -- Rule number optional */ 4728 if (ac && isdigit(**av)) { 4729 rule->rulenum = atoi(*av); 4730 av++; 4731 ac--; 4732 } 4733 4734 /* [set N] -- set number (0..RESVD_SET), optional */ 4735 if (ac > 1 && _substrcmp(*av, "set") == 0) { 4736 int set = strtoul(av[1], NULL, 10); 4737 if (set < 0 || set > RESVD_SET) 4738 errx(EX_DATAERR, "illegal set %s", av[1]); 4739 rule->set = set; 4740 av += 2; ac -= 2; 4741 } 4742 4743 /* [prob D] -- match probability, optional */ 4744 if (ac > 1 && _substrcmp(*av, "prob") == 0) { 4745 match_prob = strtod(av[1], NULL); 4746 4747 if (match_prob <= 0 || match_prob > 1) 4748 errx(EX_DATAERR, "illegal match prob. %s", av[1]); 4749 av += 2; ac -= 2; 4750 } 4751 4752 /* action -- mandatory */ 4753 NEED1("missing action"); 4754 i = match_token(rule_actions, *av); 4755 ac--; av++; 4756 action->len = 1; /* default */ 4757 switch(i) { 4758 case TOK_CHECKSTATE: 4759 have_state = action; 4760 action->opcode = O_CHECK_STATE; 4761 break; 4762 4763 case TOK_ACCEPT: 4764 action->opcode = O_ACCEPT; 4765 break; 4766 4767 case TOK_DENY: 4768 action->opcode = O_DENY; 4769 action->arg1 = 0; 4770 break; 4771 4772 case TOK_REJECT: 4773 action->opcode = O_REJECT; 4774 action->arg1 = ICMP_UNREACH_HOST; 4775 break; 4776 4777 case TOK_RESET: 4778 action->opcode = O_REJECT; 4779 action->arg1 = ICMP_REJECT_RST; 4780 break; 4781 4782 case TOK_RESET6: 4783 action->opcode = O_UNREACH6; 4784 action->arg1 = ICMP6_UNREACH_RST; 4785 break; 4786 4787 case TOK_UNREACH: 4788 action->opcode = O_REJECT; 4789 NEED1("missing reject code"); 4790 fill_reject_code(&action->arg1, *av); 4791 ac--; av++; 4792 break; 4793 4794 case TOK_UNREACH6: 4795 action->opcode = O_UNREACH6; 4796 NEED1("missing unreach code"); 4797 fill_unreach6_code(&action->arg1, *av); 4798 ac--; av++; 4799 break; 4800 4801 case TOK_COUNT: 4802 action->opcode = O_COUNT; 4803 break; 4804 4805 case TOK_QUEUE: 4806 action->opcode = O_QUEUE; 4807 goto chkarg; 4808 case TOK_PIPE: 4809 action->opcode = O_PIPE; 4810 goto chkarg; 4811 case TOK_SKIPTO: 4812 action->opcode = O_SKIPTO; 4813 goto chkarg; 4814 case TOK_NETGRAPH: 4815 action->opcode = O_NETGRAPH; 4816 goto chkarg; 4817 case TOK_NGTEE: 4818 action->opcode = O_NGTEE; 4819 goto chkarg; 4820 case TOK_DIVERT: 4821 action->opcode = O_DIVERT; 4822 goto chkarg; 4823 case TOK_TEE: 4824 action->opcode = O_TEE; 4825 chkarg: 4826 if (!ac) 4827 errx(EX_USAGE, "missing argument for %s", *(av - 1)); 4828 if (isdigit(**av)) { 4829 action->arg1 = strtoul(*av, NULL, 10); 4830 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG) 4831 errx(EX_DATAERR, "illegal argument for %s", 4832 *(av - 1)); 4833 } else if (_substrcmp(*av, TABLEARG) == 0) { 4834 action->arg1 = IP_FW_TABLEARG; 4835 } else if (i == TOK_DIVERT || i == TOK_TEE) { 4836 struct servent *s; 4837 setservent(1); 4838 s = getservbyname(av[0], "divert"); 4839 if (s != NULL) 4840 action->arg1 = ntohs(s->s_port); 4841 else 4842 errx(EX_DATAERR, "illegal divert/tee port"); 4843 } else 4844 errx(EX_DATAERR, "illegal argument for %s", *(av - 1)); 4845 ac--; av++; 4846 break; 4847 4848 case TOK_FORWARD: { 4849 ipfw_insn_sa *p = (ipfw_insn_sa *)action; 4850 char *s, *end; 4851 4852 NEED1("missing forward address[:port]"); 4853 4854 action->opcode = O_FORWARD_IP; 4855 action->len = F_INSN_SIZE(ipfw_insn_sa); 4856 4857 p->sa.sin_len = sizeof(struct sockaddr_in); 4858 p->sa.sin_family = AF_INET; 4859 p->sa.sin_port = 0; 4860 /* 4861 * locate the address-port separator (':' or ',') 4862 */ 4863 s = strchr(*av, ':'); 4864 if (s == NULL) 4865 s = strchr(*av, ','); 4866 if (s != NULL) { 4867 *(s++) = '\0'; 4868 i = strtoport(s, &end, 0 /* base */, 0 /* proto */); 4869 if (s == end) 4870 errx(EX_DATAERR, 4871 "illegal forwarding port ``%s''", s); 4872 p->sa.sin_port = (u_short)i; 4873 } 4874 if (_substrcmp(*av, "tablearg") == 0) 4875 p->sa.sin_addr.s_addr = INADDR_ANY; 4876 else 4877 lookup_host(*av, &(p->sa.sin_addr)); 4878 ac--; av++; 4879 break; 4880 } 4881 case TOK_COMMENT: 4882 /* pretend it is a 'count' rule followed by the comment */ 4883 action->opcode = O_COUNT; 4884 ac++; av--; /* go back... */ 4885 break; 4886 4887 case TOK_NAT: 4888 action->opcode = O_NAT; 4889 action->len = F_INSN_SIZE(ipfw_insn_nat); 4890 NEED1("missing nat number"); 4891 action->arg1 = strtoul(*av, NULL, 10); 4892 ac--; av++; 4893 break; 4894 4895 default: 4896 errx(EX_DATAERR, "invalid action %s\n", av[-1]); 4897 } 4898 action = next_cmd(action); 4899 4900 /* 4901 * [altq queuename] -- altq tag, optional 4902 * [log [logamount N]] -- log, optional 4903 * 4904 * If they exist, it go first in the cmdbuf, but then it is 4905 * skipped in the copy section to the end of the buffer. 4906 */ 4907 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) { 4908 ac--; av++; 4909 switch (i) { 4910 case TOK_LOG: 4911 { 4912 ipfw_insn_log *c = (ipfw_insn_log *)cmd; 4913 int l; 4914 4915 if (have_log) 4916 errx(EX_DATAERR, 4917 "log cannot be specified more than once"); 4918 have_log = (ipfw_insn *)c; 4919 cmd->len = F_INSN_SIZE(ipfw_insn_log); 4920 cmd->opcode = O_LOG; 4921 if (ac && _substrcmp(*av, "logamount") == 0) { 4922 ac--; av++; 4923 NEED1("logamount requires argument"); 4924 l = atoi(*av); 4925 if (l < 0) 4926 errx(EX_DATAERR, 4927 "logamount must be positive"); 4928 c->max_log = l; 4929 ac--; av++; 4930 } else { 4931 len = sizeof(c->max_log); 4932 if (sysctlbyname("net.inet.ip.fw.verbose_limit", 4933 &c->max_log, &len, NULL, 0) == -1) 4934 errx(1, "sysctlbyname(\"%s\")", 4935 "net.inet.ip.fw.verbose_limit"); 4936 } 4937 } 4938 break; 4939 4940 case TOK_ALTQ: 4941 { 4942 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd; 4943 4944 NEED1("missing altq queue name"); 4945 if (have_altq) 4946 errx(EX_DATAERR, 4947 "altq cannot be specified more than once"); 4948 have_altq = (ipfw_insn *)a; 4949 cmd->len = F_INSN_SIZE(ipfw_insn_altq); 4950 cmd->opcode = O_ALTQ; 4951 fill_altq_qid(&a->qid, *av); 4952 ac--; av++; 4953 } 4954 break; 4955 4956 case TOK_TAG: 4957 case TOK_UNTAG: { 4958 uint16_t tag; 4959 4960 if (have_tag) 4961 errx(EX_USAGE, "tag and untag cannot be " 4962 "specified more than once"); 4963 GET_UINT_ARG(tag, 1, 65534, i, rule_action_params); 4964 have_tag = cmd; 4965 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag); 4966 ac--; av++; 4967 break; 4968 } 4969 4970 default: 4971 abort(); 4972 } 4973 cmd = next_cmd(cmd); 4974 } 4975 4976 if (have_state) /* must be a check-state, we are done */ 4977 goto done; 4978 4979 #define OR_START(target) \ 4980 if (ac && (*av[0] == '(' || *av[0] == '{')) { \ 4981 if (open_par) \ 4982 errx(EX_USAGE, "nested \"(\" not allowed\n"); \ 4983 prev = NULL; \ 4984 open_par = 1; \ 4985 if ( (av[0])[1] == '\0') { \ 4986 ac--; av++; \ 4987 } else \ 4988 (*av)++; \ 4989 } \ 4990 target: \ 4991 4992 4993 #define CLOSE_PAR \ 4994 if (open_par) { \ 4995 if (ac && ( \ 4996 strcmp(*av, ")") == 0 || \ 4997 strcmp(*av, "}") == 0)) { \ 4998 prev = NULL; \ 4999 open_par = 0; \ 5000 ac--; av++; \ 5001 } else \ 5002 errx(EX_USAGE, "missing \")\"\n"); \ 5003 } 5004 5005 #define NOT_BLOCK \ 5006 if (ac && _substrcmp(*av, "not") == 0) { \ 5007 if (cmd->len & F_NOT) \ 5008 errx(EX_USAGE, "double \"not\" not allowed\n"); \ 5009 cmd->len |= F_NOT; \ 5010 ac--; av++; \ 5011 } 5012 5013 #define OR_BLOCK(target) \ 5014 if (ac && _substrcmp(*av, "or") == 0) { \ 5015 if (prev == NULL || open_par == 0) \ 5016 errx(EX_DATAERR, "invalid OR block"); \ 5017 prev->len |= F_OR; \ 5018 ac--; av++; \ 5019 goto target; \ 5020 } \ 5021 CLOSE_PAR; 5022 5023 first_cmd = cmd; 5024 5025 #if 0 5026 /* 5027 * MAC addresses, optional. 5028 * If we have this, we skip the part "proto from src to dst" 5029 * and jump straight to the option parsing. 5030 */ 5031 NOT_BLOCK; 5032 NEED1("missing protocol"); 5033 if (_substrcmp(*av, "MAC") == 0 || 5034 _substrcmp(*av, "mac") == 0) { 5035 ac--; av++; /* the "MAC" keyword */ 5036 add_mac(cmd, ac, av); /* exits in case of errors */ 5037 cmd = next_cmd(cmd); 5038 ac -= 2; av += 2; /* dst-mac and src-mac */ 5039 NOT_BLOCK; 5040 NEED1("missing mac type"); 5041 if (add_mactype(cmd, ac, av[0])) 5042 cmd = next_cmd(cmd); 5043 ac--; av++; /* any or mac-type */ 5044 goto read_options; 5045 } 5046 #endif 5047 5048 /* 5049 * protocol, mandatory 5050 */ 5051 OR_START(get_proto); 5052 NOT_BLOCK; 5053 NEED1("missing protocol"); 5054 if (add_proto_compat(cmd, *av, &proto)) { 5055 av++; ac--; 5056 if (F_LEN(cmd) != 0) { 5057 prev = cmd; 5058 cmd = next_cmd(cmd); 5059 } 5060 } else if (first_cmd != cmd) { 5061 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 5062 } else 5063 goto read_options; 5064 OR_BLOCK(get_proto); 5065 5066 /* 5067 * "from", mandatory 5068 */ 5069 if (!ac || _substrcmp(*av, "from") != 0) 5070 errx(EX_USAGE, "missing ``from''"); 5071 ac--; av++; 5072 5073 /* 5074 * source IP, mandatory 5075 */ 5076 OR_START(source_ip); 5077 NOT_BLOCK; /* optional "not" */ 5078 NEED1("missing source address"); 5079 if (add_src(cmd, *av, proto)) { 5080 ac--; av++; 5081 if (F_LEN(cmd) != 0) { /* ! any */ 5082 prev = cmd; 5083 cmd = next_cmd(cmd); 5084 } 5085 } else 5086 errx(EX_USAGE, "bad source address %s", *av); 5087 OR_BLOCK(source_ip); 5088 5089 /* 5090 * source ports, optional 5091 */ 5092 NOT_BLOCK; /* optional "not" */ 5093 if (ac) { 5094 if (_substrcmp(*av, "any") == 0 || 5095 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5096 ac--; av++; 5097 if (F_LEN(cmd) != 0) 5098 cmd = next_cmd(cmd); 5099 } 5100 } 5101 5102 /* 5103 * "to", mandatory 5104 */ 5105 if (!ac || _substrcmp(*av, "to") != 0) 5106 errx(EX_USAGE, "missing ``to''"); 5107 av++; ac--; 5108 5109 /* 5110 * destination, mandatory 5111 */ 5112 OR_START(dest_ip); 5113 NOT_BLOCK; /* optional "not" */ 5114 NEED1("missing dst address"); 5115 if (add_dst(cmd, *av, proto)) { 5116 ac--; av++; 5117 if (F_LEN(cmd) != 0) { /* ! any */ 5118 prev = cmd; 5119 cmd = next_cmd(cmd); 5120 } 5121 } else 5122 errx( EX_USAGE, "bad destination address %s", *av); 5123 OR_BLOCK(dest_ip); 5124 5125 /* 5126 * dest. ports, optional 5127 */ 5128 NOT_BLOCK; /* optional "not" */ 5129 if (ac) { 5130 if (_substrcmp(*av, "any") == 0 || 5131 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5132 ac--; av++; 5133 if (F_LEN(cmd) != 0) 5134 cmd = next_cmd(cmd); 5135 } 5136 } 5137 5138 read_options: 5139 if (ac && first_cmd == cmd) { 5140 /* 5141 * nothing specified so far, store in the rule to ease 5142 * printout later. 5143 */ 5144 rule->_pad = 1; 5145 } 5146 prev = NULL; 5147 while (ac) { 5148 char *s; 5149 ipfw_insn_u32 *cmd32; /* alias for cmd */ 5150 5151 s = *av; 5152 cmd32 = (ipfw_insn_u32 *)cmd; 5153 5154 if (*s == '!') { /* alternate syntax for NOT */ 5155 if (cmd->len & F_NOT) 5156 errx(EX_USAGE, "double \"not\" not allowed\n"); 5157 cmd->len = F_NOT; 5158 s++; 5159 } 5160 i = match_token(rule_options, s); 5161 ac--; av++; 5162 switch(i) { 5163 case TOK_NOT: 5164 if (cmd->len & F_NOT) 5165 errx(EX_USAGE, "double \"not\" not allowed\n"); 5166 cmd->len = F_NOT; 5167 break; 5168 5169 case TOK_OR: 5170 if (open_par == 0 || prev == NULL) 5171 errx(EX_USAGE, "invalid \"or\" block\n"); 5172 prev->len |= F_OR; 5173 break; 5174 5175 case TOK_STARTBRACE: 5176 if (open_par) 5177 errx(EX_USAGE, "+nested \"(\" not allowed\n"); 5178 open_par = 1; 5179 break; 5180 5181 case TOK_ENDBRACE: 5182 if (!open_par) 5183 errx(EX_USAGE, "+missing \")\"\n"); 5184 open_par = 0; 5185 prev = NULL; 5186 break; 5187 5188 case TOK_IN: 5189 fill_cmd(cmd, O_IN, 0, 0); 5190 break; 5191 5192 case TOK_OUT: 5193 cmd->len ^= F_NOT; /* toggle F_NOT */ 5194 fill_cmd(cmd, O_IN, 0, 0); 5195 break; 5196 5197 case TOK_DIVERTED: 5198 fill_cmd(cmd, O_DIVERTED, 0, 3); 5199 break; 5200 5201 case TOK_DIVERTEDLOOPBACK: 5202 fill_cmd(cmd, O_DIVERTED, 0, 1); 5203 break; 5204 5205 case TOK_DIVERTEDOUTPUT: 5206 fill_cmd(cmd, O_DIVERTED, 0, 2); 5207 break; 5208 5209 case TOK_FRAG: 5210 fill_cmd(cmd, O_FRAG, 0, 0); 5211 break; 5212 5213 case TOK_LAYER2: 5214 fill_cmd(cmd, O_LAYER2, 0, 0); 5215 break; 5216 5217 case TOK_XMIT: 5218 case TOK_RECV: 5219 case TOK_VIA: 5220 NEED1("recv, xmit, via require interface name" 5221 " or address"); 5222 fill_iface((ipfw_insn_if *)cmd, av[0]); 5223 ac--; av++; 5224 if (F_LEN(cmd) == 0) /* not a valid address */ 5225 break; 5226 if (i == TOK_XMIT) 5227 cmd->opcode = O_XMIT; 5228 else if (i == TOK_RECV) 5229 cmd->opcode = O_RECV; 5230 else if (i == TOK_VIA) 5231 cmd->opcode = O_VIA; 5232 break; 5233 5234 case TOK_ICMPTYPES: 5235 NEED1("icmptypes requires list of types"); 5236 fill_icmptypes((ipfw_insn_u32 *)cmd, *av); 5237 av++; ac--; 5238 break; 5239 5240 case TOK_ICMP6TYPES: 5241 NEED1("icmptypes requires list of types"); 5242 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av); 5243 av++; ac--; 5244 break; 5245 5246 case TOK_IPTTL: 5247 NEED1("ipttl requires TTL"); 5248 if (strpbrk(*av, "-,")) { 5249 if (!add_ports(cmd, *av, 0, O_IPTTL)) 5250 errx(EX_DATAERR, "invalid ipttl %s", *av); 5251 } else 5252 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0)); 5253 ac--; av++; 5254 break; 5255 5256 case TOK_IPID: 5257 NEED1("ipid requires id"); 5258 if (strpbrk(*av, "-,")) { 5259 if (!add_ports(cmd, *av, 0, O_IPID)) 5260 errx(EX_DATAERR, "invalid ipid %s", *av); 5261 } else 5262 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0)); 5263 ac--; av++; 5264 break; 5265 5266 case TOK_IPLEN: 5267 NEED1("iplen requires length"); 5268 if (strpbrk(*av, "-,")) { 5269 if (!add_ports(cmd, *av, 0, O_IPLEN)) 5270 errx(EX_DATAERR, "invalid ip len %s", *av); 5271 } else 5272 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0)); 5273 ac--; av++; 5274 break; 5275 5276 case TOK_IPVER: 5277 NEED1("ipver requires version"); 5278 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0)); 5279 ac--; av++; 5280 break; 5281 5282 case TOK_IPPRECEDENCE: 5283 NEED1("ipprecedence requires value"); 5284 fill_cmd(cmd, O_IPPRECEDENCE, 0, 5285 (strtoul(*av, NULL, 0) & 7) << 5); 5286 ac--; av++; 5287 break; 5288 5289 case TOK_IPOPTS: 5290 NEED1("missing argument for ipoptions"); 5291 fill_flags(cmd, O_IPOPT, f_ipopts, *av); 5292 ac--; av++; 5293 break; 5294 5295 case TOK_IPTOS: 5296 NEED1("missing argument for iptos"); 5297 fill_flags(cmd, O_IPTOS, f_iptos, *av); 5298 ac--; av++; 5299 break; 5300 5301 case TOK_UID: 5302 NEED1("uid requires argument"); 5303 { 5304 char *end; 5305 uid_t uid; 5306 struct passwd *pwd; 5307 5308 cmd->opcode = O_UID; 5309 uid = strtoul(*av, &end, 0); 5310 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av); 5311 if (pwd == NULL) 5312 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av); 5313 cmd32->d[0] = pwd->pw_uid; 5314 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5315 ac--; av++; 5316 } 5317 break; 5318 5319 case TOK_GID: 5320 NEED1("gid requires argument"); 5321 { 5322 char *end; 5323 gid_t gid; 5324 struct group *grp; 5325 5326 cmd->opcode = O_GID; 5327 gid = strtoul(*av, &end, 0); 5328 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av); 5329 if (grp == NULL) 5330 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av); 5331 cmd32->d[0] = grp->gr_gid; 5332 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5333 ac--; av++; 5334 } 5335 break; 5336 5337 case TOK_JAIL: 5338 NEED1("jail requires argument"); 5339 { 5340 char *end; 5341 int jid; 5342 5343 cmd->opcode = O_JAIL; 5344 jid = (int)strtol(*av, &end, 0); 5345 if (jid < 0 || *end != '\0') 5346 errx(EX_DATAERR, "jail requires prison ID"); 5347 cmd32->d[0] = (uint32_t)jid; 5348 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5349 ac--; av++; 5350 } 5351 break; 5352 5353 case TOK_ESTAB: 5354 fill_cmd(cmd, O_ESTAB, 0, 0); 5355 break; 5356 5357 case TOK_SETUP: 5358 fill_cmd(cmd, O_TCPFLAGS, 0, 5359 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 ); 5360 break; 5361 5362 case TOK_TCPDATALEN: 5363 NEED1("tcpdatalen requires length"); 5364 if (strpbrk(*av, "-,")) { 5365 if (!add_ports(cmd, *av, 0, O_TCPDATALEN)) 5366 errx(EX_DATAERR, "invalid tcpdata len %s", *av); 5367 } else 5368 fill_cmd(cmd, O_TCPDATALEN, 0, 5369 strtoul(*av, NULL, 0)); 5370 ac--; av++; 5371 break; 5372 5373 case TOK_TCPOPTS: 5374 NEED1("missing argument for tcpoptions"); 5375 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av); 5376 ac--; av++; 5377 break; 5378 5379 case TOK_TCPSEQ: 5380 case TOK_TCPACK: 5381 NEED1("tcpseq/tcpack requires argument"); 5382 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 5383 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK; 5384 cmd32->d[0] = htonl(strtoul(*av, NULL, 0)); 5385 ac--; av++; 5386 break; 5387 5388 case TOK_TCPWIN: 5389 NEED1("tcpwin requires length"); 5390 fill_cmd(cmd, O_TCPWIN, 0, 5391 htons(strtoul(*av, NULL, 0))); 5392 ac--; av++; 5393 break; 5394 5395 case TOK_TCPFLAGS: 5396 NEED1("missing argument for tcpflags"); 5397 cmd->opcode = O_TCPFLAGS; 5398 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av); 5399 ac--; av++; 5400 break; 5401 5402 case TOK_KEEPSTATE: 5403 if (open_par) 5404 errx(EX_USAGE, "keep-state cannot be part " 5405 "of an or block"); 5406 if (have_state) 5407 errx(EX_USAGE, "only one of keep-state " 5408 "and limit is allowed"); 5409 have_state = cmd; 5410 fill_cmd(cmd, O_KEEP_STATE, 0, 0); 5411 break; 5412 5413 case TOK_LIMIT: { 5414 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 5415 int val; 5416 5417 if (open_par) 5418 errx(EX_USAGE, 5419 "limit cannot be part of an or block"); 5420 if (have_state) 5421 errx(EX_USAGE, "only one of keep-state and " 5422 "limit is allowed"); 5423 have_state = cmd; 5424 5425 cmd->len = F_INSN_SIZE(ipfw_insn_limit); 5426 cmd->opcode = O_LIMIT; 5427 c->limit_mask = c->conn_limit = 0; 5428 5429 while (ac > 0) { 5430 if ((val = match_token(limit_masks, *av)) <= 0) 5431 break; 5432 c->limit_mask |= val; 5433 ac--; av++; 5434 } 5435 5436 if (c->limit_mask == 0) 5437 errx(EX_USAGE, "limit: missing limit mask"); 5438 5439 GET_UINT_ARG(c->conn_limit, 1, 65534, TOK_LIMIT, 5440 rule_options); 5441 5442 ac--; av++; 5443 break; 5444 } 5445 5446 case TOK_PROTO: 5447 NEED1("missing protocol"); 5448 if (add_proto(cmd, *av, &proto)) { 5449 ac--; av++; 5450 } else 5451 errx(EX_DATAERR, "invalid protocol ``%s''", 5452 *av); 5453 break; 5454 5455 case TOK_SRCIP: 5456 NEED1("missing source IP"); 5457 if (add_srcip(cmd, *av)) { 5458 ac--; av++; 5459 } 5460 break; 5461 5462 case TOK_DSTIP: 5463 NEED1("missing destination IP"); 5464 if (add_dstip(cmd, *av)) { 5465 ac--; av++; 5466 } 5467 break; 5468 5469 case TOK_SRCIP6: 5470 NEED1("missing source IP6"); 5471 if (add_srcip6(cmd, *av)) { 5472 ac--; av++; 5473 } 5474 break; 5475 5476 case TOK_DSTIP6: 5477 NEED1("missing destination IP6"); 5478 if (add_dstip6(cmd, *av)) { 5479 ac--; av++; 5480 } 5481 break; 5482 5483 case TOK_SRCPORT: 5484 NEED1("missing source port"); 5485 if (_substrcmp(*av, "any") == 0 || 5486 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5487 ac--; av++; 5488 } else 5489 errx(EX_DATAERR, "invalid source port %s", *av); 5490 break; 5491 5492 case TOK_DSTPORT: 5493 NEED1("missing destination port"); 5494 if (_substrcmp(*av, "any") == 0 || 5495 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5496 ac--; av++; 5497 } else 5498 errx(EX_DATAERR, "invalid destination port %s", 5499 *av); 5500 break; 5501 5502 case TOK_MAC: 5503 if (add_mac(cmd, ac, av)) { 5504 ac -= 2; av += 2; 5505 } 5506 break; 5507 5508 case TOK_MACTYPE: 5509 NEED1("missing mac type"); 5510 if (!add_mactype(cmd, ac, *av)) 5511 errx(EX_DATAERR, "invalid mac type %s", *av); 5512 ac--; av++; 5513 break; 5514 5515 case TOK_VERREVPATH: 5516 fill_cmd(cmd, O_VERREVPATH, 0, 0); 5517 break; 5518 5519 case TOK_VERSRCREACH: 5520 fill_cmd(cmd, O_VERSRCREACH, 0, 0); 5521 break; 5522 5523 case TOK_ANTISPOOF: 5524 fill_cmd(cmd, O_ANTISPOOF, 0, 0); 5525 break; 5526 5527 case TOK_IPSEC: 5528 fill_cmd(cmd, O_IPSEC, 0, 0); 5529 break; 5530 5531 case TOK_IPV6: 5532 fill_cmd(cmd, O_IP6, 0, 0); 5533 break; 5534 5535 case TOK_IPV4: 5536 fill_cmd(cmd, O_IP4, 0, 0); 5537 break; 5538 5539 case TOK_EXT6HDR: 5540 fill_ext6hdr( cmd, *av ); 5541 ac--; av++; 5542 break; 5543 5544 case TOK_FLOWID: 5545 if (proto != IPPROTO_IPV6 ) 5546 errx( EX_USAGE, "flow-id filter is active " 5547 "only for ipv6 protocol\n"); 5548 fill_flow6( (ipfw_insn_u32 *) cmd, *av ); 5549 ac--; av++; 5550 break; 5551 5552 case TOK_COMMENT: 5553 fill_comment(cmd, ac, av); 5554 av += ac; 5555 ac = 0; 5556 break; 5557 5558 case TOK_TAGGED: 5559 if (ac > 0 && strpbrk(*av, "-,")) { 5560 if (!add_ports(cmd, *av, 0, O_TAGGED)) 5561 errx(EX_DATAERR, "tagged: invalid tag" 5562 " list: %s", *av); 5563 } 5564 else { 5565 uint16_t tag; 5566 5567 GET_UINT_ARG(tag, 1, 65534, TOK_TAGGED, 5568 rule_options); 5569 fill_cmd(cmd, O_TAGGED, 0, tag); 5570 } 5571 ac--; av++; 5572 break; 5573 5574 default: 5575 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s); 5576 } 5577 if (F_LEN(cmd) > 0) { /* prepare to advance */ 5578 prev = cmd; 5579 cmd = next_cmd(cmd); 5580 } 5581 } 5582 5583 done: 5584 /* 5585 * Now copy stuff into the rule. 5586 * If we have a keep-state option, the first instruction 5587 * must be a PROBE_STATE (which is generated here). 5588 * If we have a LOG option, it was stored as the first command, 5589 * and now must be moved to the top of the action part. 5590 */ 5591 dst = (ipfw_insn *)rule->cmd; 5592 5593 /* 5594 * First thing to write into the command stream is the match probability. 5595 */ 5596 if (match_prob != 1) { /* 1 means always match */ 5597 dst->opcode = O_PROB; 5598 dst->len = 2; 5599 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff); 5600 dst += dst->len; 5601 } 5602 5603 /* 5604 * generate O_PROBE_STATE if necessary 5605 */ 5606 if (have_state && have_state->opcode != O_CHECK_STATE) { 5607 fill_cmd(dst, O_PROBE_STATE, 0, 0); 5608 dst = next_cmd(dst); 5609 } 5610 5611 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */ 5612 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) { 5613 i = F_LEN(src); 5614 5615 switch (src->opcode) { 5616 case O_LOG: 5617 case O_KEEP_STATE: 5618 case O_LIMIT: 5619 case O_ALTQ: 5620 case O_TAG: 5621 break; 5622 default: 5623 bcopy(src, dst, i * sizeof(uint32_t)); 5624 dst += i; 5625 } 5626 } 5627 5628 /* 5629 * put back the have_state command as last opcode 5630 */ 5631 if (have_state && have_state->opcode != O_CHECK_STATE) { 5632 i = F_LEN(have_state); 5633 bcopy(have_state, dst, i * sizeof(uint32_t)); 5634 dst += i; 5635 } 5636 /* 5637 * start action section 5638 */ 5639 rule->act_ofs = dst - rule->cmd; 5640 5641 /* put back O_LOG, O_ALTQ, O_TAG if necessary */ 5642 if (have_log) { 5643 i = F_LEN(have_log); 5644 bcopy(have_log, dst, i * sizeof(uint32_t)); 5645 dst += i; 5646 } 5647 if (have_altq) { 5648 i = F_LEN(have_altq); 5649 bcopy(have_altq, dst, i * sizeof(uint32_t)); 5650 dst += i; 5651 } 5652 if (have_tag) { 5653 i = F_LEN(have_tag); 5654 bcopy(have_tag, dst, i * sizeof(uint32_t)); 5655 dst += i; 5656 } 5657 /* 5658 * copy all other actions 5659 */ 5660 for (src = (ipfw_insn *)actbuf; src != action; src += i) { 5661 i = F_LEN(src); 5662 bcopy(src, dst, i * sizeof(uint32_t)); 5663 dst += i; 5664 } 5665 5666 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd); 5667 i = (char *)dst - (char *)rule; 5668 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1) 5669 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD"); 5670 if (!do_quiet) 5671 show_ipfw(rule, 0, 0); 5672 } 5673 5674 static void 5675 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */) 5676 { 5677 int rulenum; 5678 int failed = EX_OK; 5679 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG"; 5680 5681 av++; ac--; 5682 5683 if (!ac) { 5684 /* clear all entries */ 5685 if (do_cmd(optname, NULL, 0) < 0) 5686 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name); 5687 if (!do_quiet) 5688 printf("%s.\n", optname == IP_FW_ZERO ? 5689 "Accounting cleared":"Logging counts reset"); 5690 5691 return; 5692 } 5693 5694 while (ac) { 5695 /* Rule number */ 5696 if (isdigit(**av)) { 5697 rulenum = atoi(*av); 5698 av++; 5699 ac--; 5700 if (do_cmd(optname, &rulenum, sizeof rulenum)) { 5701 warn("rule %u: setsockopt(IP_FW_%s)", 5702 rulenum, name); 5703 failed = EX_UNAVAILABLE; 5704 } else if (!do_quiet) 5705 printf("Entry %d %s.\n", rulenum, 5706 optname == IP_FW_ZERO ? 5707 "cleared" : "logging count reset"); 5708 } else { 5709 errx(EX_USAGE, "invalid rule number ``%s''", *av); 5710 } 5711 } 5712 if (failed != EX_OK) 5713 exit(failed); 5714 } 5715 5716 static void 5717 flush(int force) 5718 { 5719 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH; 5720 5721 if (!force && !do_quiet) { /* need to ask user */ 5722 int c; 5723 5724 printf("Are you sure? [yn] "); 5725 fflush(stdout); 5726 do { 5727 c = toupper(getc(stdin)); 5728 while (c != '\n' && getc(stdin) != '\n') 5729 if (feof(stdin)) 5730 return; /* and do not flush */ 5731 } while (c != 'Y' && c != 'N'); 5732 printf("\n"); 5733 if (c == 'N') /* user said no */ 5734 return; 5735 } 5736 if (do_cmd(cmd, NULL, 0) < 0) 5737 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)", 5738 do_pipe ? "DUMMYNET" : "FW"); 5739 if (!do_quiet) 5740 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules"); 5741 } 5742 5743 /* 5744 * Free a the (locally allocated) copy of command line arguments. 5745 */ 5746 static void 5747 free_args(int ac, char **av) 5748 { 5749 int i; 5750 5751 for (i=0; i < ac; i++) 5752 free(av[i]); 5753 free(av); 5754 } 5755 5756 /* 5757 * This one handles all table-related commands 5758 * ipfw table N add addr[/masklen] [value] 5759 * ipfw table N delete addr[/masklen] 5760 * ipfw table N flush 5761 * ipfw table N list 5762 */ 5763 static void 5764 table_handler(int ac, char *av[]) 5765 { 5766 ipfw_table_entry ent; 5767 ipfw_table *tbl; 5768 int do_add; 5769 char *p; 5770 socklen_t l; 5771 uint32_t a; 5772 5773 ac--; av++; 5774 if (ac && isdigit(**av)) { 5775 ent.tbl = atoi(*av); 5776 ac--; av++; 5777 } else 5778 errx(EX_USAGE, "table number required"); 5779 NEED1("table needs command"); 5780 if (_substrcmp(*av, "add") == 0 || 5781 _substrcmp(*av, "delete") == 0) { 5782 do_add = **av == 'a'; 5783 ac--; av++; 5784 if (!ac) 5785 errx(EX_USAGE, "IP address required"); 5786 p = strchr(*av, '/'); 5787 if (p) { 5788 *p++ = '\0'; 5789 ent.masklen = atoi(p); 5790 if (ent.masklen > 32) 5791 errx(EX_DATAERR, "bad width ``%s''", p); 5792 } else 5793 ent.masklen = 32; 5794 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0) 5795 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5796 ac--; av++; 5797 if (do_add && ac) { 5798 unsigned int tval; 5799 /* isdigit is a bit of a hack here.. */ 5800 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) { 5801 ent.value = strtoul(*av, NULL, 0); 5802 } else { 5803 if (lookup_host(*av, (struct in_addr *)&tval) == 0) { 5804 /* The value must be stored in host order * 5805 * so that the values < 65k can be distinguished */ 5806 ent.value = ntohl(tval); 5807 } else { 5808 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5809 } 5810 } 5811 } else 5812 ent.value = 0; 5813 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL, 5814 &ent, sizeof(ent)) < 0) { 5815 /* If running silent, don't bomb out on these errors. */ 5816 if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH)))) 5817 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)", 5818 do_add ? "ADD" : "DEL"); 5819 /* In silent mode, react to a failed add by deleting */ 5820 if (do_add) { 5821 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent)); 5822 if (do_cmd(IP_FW_TABLE_ADD, 5823 &ent, sizeof(ent)) < 0) 5824 err(EX_OSERR, 5825 "setsockopt(IP_FW_TABLE_ADD)"); 5826 } 5827 } 5828 } else if (_substrcmp(*av, "flush") == 0) { 5829 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0) 5830 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)"); 5831 } else if (_substrcmp(*av, "list") == 0) { 5832 a = ent.tbl; 5833 l = sizeof(a); 5834 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0) 5835 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)"); 5836 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry); 5837 tbl = malloc(l); 5838 if (tbl == NULL) 5839 err(EX_OSERR, "malloc"); 5840 tbl->tbl = ent.tbl; 5841 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0) 5842 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)"); 5843 for (a = 0; a < tbl->cnt; a++) { 5844 /* Heuristic to print it the right way */ 5845 /* values < 64k are printed as numbers */ 5846 unsigned int tval; 5847 tval = tbl->ent[a].value; 5848 if (tval > 0xffff) { 5849 char tbuf[128]; 5850 strncpy(tbuf, inet_ntoa(*(struct in_addr *) 5851 &tbl->ent[a].addr), 127); 5852 /* inet_ntoa expects host order */ 5853 tval = htonl(tval); 5854 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen, 5855 inet_ntoa(*(struct in_addr *)&tval)); 5856 } else { 5857 printf("%s/%u %u\n", 5858 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr), 5859 tbl->ent[a].masklen, tbl->ent[a].value); 5860 } 5861 } 5862 } else 5863 errx(EX_USAGE, "invalid table command %s", *av); 5864 } 5865 5866 static void 5867 show_nat(int ac, char **av) { 5868 struct cfg_nat *n; 5869 struct cfg_redir *e; 5870 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size; 5871 int nat_cnt, r; 5872 uint8_t *data, *p; 5873 char **lav, *endptr; 5874 5875 do_rule = 0; 5876 nalloc = 1024; 5877 size = 0; 5878 data = NULL; 5879 ac--; av++; 5880 5881 /* Parse parameters. */ 5882 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) { 5883 if (!strncmp(av[0], "config", strlen(av[0]))) { 5884 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1; 5885 continue; 5886 } 5887 /* Convert command line rule #. */ 5888 frule = lrule = strtoul(av[0], &endptr, 10); 5889 if (*endptr == '-') 5890 lrule = strtoul(endptr+1, &endptr, 10); 5891 if (lrule == 0) 5892 err(EX_USAGE, "invalid rule number: %s", av[0]); 5893 do_rule = 1; 5894 } 5895 5896 nbytes = nalloc; 5897 while (nbytes >= nalloc) { 5898 nalloc = nalloc * 2; 5899 nbytes = nalloc; 5900 if ((data = realloc(data, nbytes)) == NULL) 5901 err(EX_OSERR, "realloc"); 5902 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0) 5903 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)", 5904 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG"); 5905 } 5906 if (nbytes == 0) 5907 exit(0); 5908 if (do_cfg) { 5909 nat_cnt = *((int *)data); 5910 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) { 5911 n = (struct cfg_nat *)&data[i]; 5912 if (do_rule) { 5913 if (!(frule <= n->id && lrule >= n->id)) 5914 continue; 5915 } 5916 print_nat_config(&data[i]); 5917 i += sizeof(struct cfg_nat); 5918 e = (struct cfg_redir *)&data[i]; 5919 if (e->mode == REDIR_ADDR || e->mode == REDIR_PORT || 5920 e->mode == REDIR_PROTO) 5921 i += sizeof(struct cfg_redir) + e->spool_cnt * 5922 sizeof(struct cfg_spool); 5923 } 5924 } else { 5925 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) { 5926 p = &data[i]; 5927 if (p == data + nbytes) 5928 break; 5929 bcopy(p, &r, sizeof(int)); 5930 if (do_rule) { 5931 if (!(frule <= r && lrule >= r)) 5932 continue; 5933 } 5934 printf("nat %u: %s\n", r, p+sizeof(int)); 5935 } 5936 } 5937 } 5938 5939 /* 5940 * Called with the arguments (excluding program name). 5941 * Returns 0 if successful, 1 if empty command, errx() in case of errors. 5942 */ 5943 static int 5944 ipfw_main(int oldac, char **oldav) 5945 { 5946 int ch, ac, save_ac; 5947 char **av, **save_av; 5948 int do_acct = 0; /* Show packet/byte count */ 5949 5950 #define WHITESP " \t\f\v\n\r" 5951 if (oldac == 0) 5952 return 1; 5953 else if (oldac == 1) { 5954 /* 5955 * If we are called with a single string, try to split it into 5956 * arguments for subsequent parsing. 5957 * But first, remove spaces after a ',', by copying the string 5958 * in-place. 5959 */ 5960 char *arg = oldav[0]; /* The string... */ 5961 int l = strlen(arg); 5962 int copy = 0; /* 1 if we need to copy, 0 otherwise */ 5963 int i, j; 5964 for (i = j = 0; i < l; i++) { 5965 if (arg[i] == '#') /* comment marker */ 5966 break; 5967 if (copy) { 5968 arg[j++] = arg[i]; 5969 copy = !index("," WHITESP, arg[i]); 5970 } else { 5971 copy = !index(WHITESP, arg[i]); 5972 if (copy) 5973 arg[j++] = arg[i]; 5974 } 5975 } 5976 if (!copy && j > 0) /* last char was a 'blank', remove it */ 5977 j--; 5978 l = j; /* the new argument length */ 5979 arg[j++] = '\0'; 5980 if (l == 0) /* empty string! */ 5981 return 1; 5982 5983 /* 5984 * First, count number of arguments. Because of the previous 5985 * processing, this is just the number of blanks plus 1. 5986 */ 5987 for (i = 0, ac = 1; i < l; i++) 5988 if (index(WHITESP, arg[i]) != NULL) 5989 ac++; 5990 5991 av = calloc(ac, sizeof(char *)); 5992 5993 /* 5994 * Second, copy arguments from cmd[] to av[]. For each one, 5995 * j is the initial character, i is the one past the end. 5996 */ 5997 for (ac = 0, i = j = 0; i < l; i++) 5998 if (index(WHITESP, arg[i]) != NULL || i == l-1) { 5999 if (i == l-1) 6000 i++; 6001 av[ac] = calloc(i-j+1, 1); 6002 bcopy(arg+j, av[ac], i-j); 6003 ac++; 6004 j = i + 1; 6005 } 6006 } else { 6007 /* 6008 * If an argument ends with ',' join with the next one. 6009 */ 6010 int first, i, l; 6011 6012 av = calloc(oldac, sizeof(char *)); 6013 for (first = i = ac = 0, l = 0; i < oldac; i++) { 6014 char *arg = oldav[i]; 6015 int k = strlen(arg); 6016 6017 l += k; 6018 if (arg[k-1] != ',' || i == oldac-1) { 6019 /* Time to copy. */ 6020 av[ac] = calloc(l+1, 1); 6021 for (l=0; first <= i; first++) { 6022 strcat(av[ac]+l, oldav[first]); 6023 l += strlen(oldav[first]); 6024 } 6025 ac++; 6026 l = 0; 6027 first = i+1; 6028 } 6029 } 6030 } 6031 6032 /* Set the force flag for non-interactive processes */ 6033 if (!do_force) 6034 do_force = !isatty(STDIN_FILENO); 6035 6036 /* Save arguments for final freeing of memory. */ 6037 save_ac = ac; 6038 save_av = av; 6039 6040 optind = optreset = 0; 6041 while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1) 6042 switch (ch) { 6043 case 'a': 6044 do_acct = 1; 6045 break; 6046 6047 case 'b': 6048 comment_only = 1; 6049 do_compact = 1; 6050 break; 6051 6052 case 'c': 6053 do_compact = 1; 6054 break; 6055 6056 case 'd': 6057 do_dynamic = 1; 6058 break; 6059 6060 case 'e': 6061 do_expired = 1; 6062 break; 6063 6064 case 'f': 6065 do_force = 1; 6066 break; 6067 6068 case 'h': /* help */ 6069 free_args(save_ac, save_av); 6070 help(); 6071 break; /* NOTREACHED */ 6072 6073 case 'n': 6074 test_only = 1; 6075 break; 6076 6077 case 'N': 6078 do_resolv = 1; 6079 break; 6080 6081 case 'q': 6082 do_quiet = 1; 6083 break; 6084 6085 case 's': /* sort */ 6086 do_sort = atoi(optarg); 6087 break; 6088 6089 case 'S': 6090 show_sets = 1; 6091 break; 6092 6093 case 't': 6094 do_time = 1; 6095 break; 6096 6097 case 'T': 6098 do_time = 2; /* numeric timestamp */ 6099 break; 6100 6101 case 'v': /* verbose */ 6102 verbose = 1; 6103 break; 6104 6105 default: 6106 free_args(save_ac, save_av); 6107 return 1; 6108 } 6109 6110 ac -= optind; 6111 av += optind; 6112 NEED1("bad arguments, for usage summary ``ipfw''"); 6113 6114 /* 6115 * An undocumented behaviour of ipfw1 was to allow rule numbers first, 6116 * e.g. "100 add allow ..." instead of "add 100 allow ...". 6117 * In case, swap first and second argument to get the normal form. 6118 */ 6119 if (ac > 1 && isdigit(*av[0])) { 6120 char *p = av[0]; 6121 6122 av[0] = av[1]; 6123 av[1] = p; 6124 } 6125 6126 /* 6127 * Optional: pipe, queue or nat. 6128 */ 6129 do_nat = 0; 6130 do_pipe = 0; 6131 if (!strncmp(*av, "nat", strlen(*av))) 6132 do_nat = 1; 6133 else if (!strncmp(*av, "pipe", strlen(*av))) 6134 do_pipe = 1; 6135 else if (_substrcmp(*av, "queue") == 0) 6136 do_pipe = 2; 6137 if (do_pipe || do_nat) { 6138 ac--; 6139 av++; 6140 } 6141 NEED1("missing command"); 6142 6143 /* 6144 * For pipes, queues and nats we normally say 'nat|pipe NN config' 6145 * but the code is easier to parse as 'nat|pipe config NN' 6146 * so we swap the two arguments. 6147 */ 6148 if ((do_pipe || do_nat) && ac > 1 && isdigit(*av[0])) { 6149 char *p = av[0]; 6150 6151 av[0] = av[1]; 6152 av[1] = p; 6153 } 6154 6155 if (_substrcmp(*av, "add") == 0) 6156 add(ac, av); 6157 else if (do_nat && _substrcmp(*av, "show") == 0) 6158 show_nat(ac, av); 6159 else if (do_pipe && _substrcmp(*av, "config") == 0) 6160 config_pipe(ac, av); 6161 else if (do_nat && _substrcmp(*av, "config") == 0) 6162 config_nat(ac, av); 6163 else if (_substrcmp(*av, "delete") == 0) 6164 delete(ac, av); 6165 else if (_substrcmp(*av, "flush") == 0) 6166 flush(do_force); 6167 else if (_substrcmp(*av, "zero") == 0) 6168 zero(ac, av, IP_FW_ZERO); 6169 else if (_substrcmp(*av, "resetlog") == 0) 6170 zero(ac, av, IP_FW_RESETLOG); 6171 else if (_substrcmp(*av, "print") == 0 || 6172 _substrcmp(*av, "list") == 0) 6173 list(ac, av, do_acct); 6174 else if (_substrcmp(*av, "set") == 0) 6175 sets_handler(ac, av); 6176 else if (_substrcmp(*av, "table") == 0) 6177 table_handler(ac, av); 6178 else if (_substrcmp(*av, "enable") == 0) 6179 sysctl_handler(ac, av, 1); 6180 else if (_substrcmp(*av, "disable") == 0) 6181 sysctl_handler(ac, av, 0); 6182 else if (_substrcmp(*av, "show") == 0) 6183 list(ac, av, 1 /* show counters */); 6184 else 6185 errx(EX_USAGE, "bad command `%s'", *av); 6186 6187 /* Free memory allocated in the argument parsing. */ 6188 free_args(save_ac, save_av); 6189 return 0; 6190 } 6191 6192 6193 static void 6194 ipfw_readfile(int ac, char *av[]) 6195 { 6196 #define MAX_ARGS 32 6197 char buf[BUFSIZ]; 6198 char *cmd = NULL, *filename = av[ac-1]; 6199 int c, lineno=0; 6200 FILE *f = NULL; 6201 pid_t preproc = 0; 6202 6203 filename = av[ac-1]; 6204 6205 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) { 6206 switch(c) { 6207 case 'c': 6208 do_compact = 1; 6209 break; 6210 6211 case 'f': 6212 do_force = 1; 6213 break; 6214 6215 case 'N': 6216 do_resolv = 1; 6217 break; 6218 6219 case 'n': 6220 test_only = 1; 6221 break; 6222 6223 case 'p': 6224 cmd = optarg; 6225 /* 6226 * Skip previous args and delete last one, so we 6227 * pass all but the last argument to the preprocessor 6228 * via av[optind-1] 6229 */ 6230 av += optind - 1; 6231 ac -= optind - 1; 6232 if (ac < 2) 6233 errx(EX_USAGE, "no filename argument"); 6234 av[ac-1] = NULL; 6235 fprintf(stderr, "command is %s\n", av[0]); 6236 break; 6237 6238 case 'q': 6239 do_quiet = 1; 6240 break; 6241 6242 case 'S': 6243 show_sets = 1; 6244 break; 6245 6246 default: 6247 errx(EX_USAGE, "bad arguments, for usage" 6248 " summary ``ipfw''"); 6249 } 6250 6251 if (cmd != NULL) 6252 break; 6253 } 6254 6255 if (cmd == NULL && ac != optind + 1) { 6256 fprintf(stderr, "ac %d, optind %d\n", ac, optind); 6257 errx(EX_USAGE, "extraneous filename arguments"); 6258 } 6259 6260 if ((f = fopen(filename, "r")) == NULL) 6261 err(EX_UNAVAILABLE, "fopen: %s", filename); 6262 6263 if (cmd != NULL) { /* pipe through preprocessor */ 6264 int pipedes[2]; 6265 6266 if (pipe(pipedes) == -1) 6267 err(EX_OSERR, "cannot create pipe"); 6268 6269 preproc = fork(); 6270 if (preproc == -1) 6271 err(EX_OSERR, "cannot fork"); 6272 6273 if (preproc == 0) { 6274 /* 6275 * Child, will run the preprocessor with the 6276 * file on stdin and the pipe on stdout. 6277 */ 6278 if (dup2(fileno(f), 0) == -1 6279 || dup2(pipedes[1], 1) == -1) 6280 err(EX_OSERR, "dup2()"); 6281 fclose(f); 6282 close(pipedes[1]); 6283 close(pipedes[0]); 6284 execvp(cmd, av); 6285 err(EX_OSERR, "execvp(%s) failed", cmd); 6286 } else { /* parent, will reopen f as the pipe */ 6287 fclose(f); 6288 close(pipedes[1]); 6289 if ((f = fdopen(pipedes[0], "r")) == NULL) { 6290 int savederrno = errno; 6291 6292 (void)kill(preproc, SIGTERM); 6293 errno = savederrno; 6294 err(EX_OSERR, "fdopen()"); 6295 } 6296 } 6297 } 6298 6299 while (fgets(buf, BUFSIZ, f)) { /* read commands */ 6300 char linename[10]; 6301 char *args[1]; 6302 6303 lineno++; 6304 sprintf(linename, "Line %d", lineno); 6305 setprogname(linename); /* XXX */ 6306 args[0] = buf; 6307 ipfw_main(1, args); 6308 } 6309 fclose(f); 6310 if (cmd != NULL) { 6311 int status; 6312 6313 if (waitpid(preproc, &status, 0) == -1) 6314 errx(EX_OSERR, "waitpid()"); 6315 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 6316 errx(EX_UNAVAILABLE, 6317 "preprocessor exited with status %d", 6318 WEXITSTATUS(status)); 6319 else if (WIFSIGNALED(status)) 6320 errx(EX_UNAVAILABLE, 6321 "preprocessor exited with signal %d", 6322 WTERMSIG(status)); 6323 } 6324 } 6325 6326 int 6327 main(int ac, char *av[]) 6328 { 6329 /* 6330 * If the last argument is an absolute pathname, interpret it 6331 * as a file to be preprocessed. 6332 */ 6333 6334 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) 6335 ipfw_readfile(ac, av); 6336 else { 6337 if (ipfw_main(ac-1, av+1)) 6338 show_usage(); 6339 } 6340 return EX_OK; 6341 } 6342