1 /* 2 * Copyright (c) 2002-2003 Luigi Rizzo 3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp 4 * Copyright (c) 1994 Ugen J.S.Antsilevich 5 * 6 * Idea and grammar partially left from: 7 * Copyright (c) 1993 Daniel Boulet 8 * 9 * Redistribution and use in source forms, with and without modification, 10 * are permitted provided that this entire comment appears intact. 11 * 12 * Redistribution in binary form may occur without any restrictions. 13 * Obviously, it would be nice if you gave credit where credit is due 14 * but requiring it would be too onerous. 15 * 16 * This software is provided ``AS IS'' without any warranties of any kind. 17 * 18 * NEW command line interface for IP firewall facility 19 * 20 * $FreeBSD$ 21 */ 22 23 #include <sys/param.h> 24 #include <sys/mbuf.h> 25 #include <sys/socket.h> 26 #include <sys/sockio.h> 27 #include <sys/sysctl.h> 28 #include <sys/time.h> 29 #include <sys/wait.h> 30 #include <sys/queue.h> 31 32 #include <ctype.h> 33 #include <err.h> 34 #include <errno.h> 35 #include <grp.h> 36 #include <limits.h> 37 #include <netdb.h> 38 #include <pwd.h> 39 #include <signal.h> 40 #include <stdio.h> 41 #include <stdlib.h> 42 #include <stdarg.h> 43 #include <string.h> 44 #include <timeconv.h> /* XXX do we need this ? */ 45 #include <unistd.h> 46 #include <sysexits.h> 47 #include <unistd.h> 48 #include <fcntl.h> 49 50 #include <net/if.h> 51 #include <net/pfvar.h> 52 #include <netinet/in.h> 53 #include <netinet/in_systm.h> 54 #include <netinet/ip.h> 55 #include <netinet/ip_icmp.h> 56 #include <netinet/ip_fw.h> 57 #include <netinet/ip_dummynet.h> 58 #include <netinet/tcp.h> 59 #include <arpa/inet.h> 60 61 int 62 do_resolv, /* Would try to resolve all */ 63 do_time, /* Show time stamps */ 64 do_quiet, /* Be quiet in add and flush */ 65 do_pipe, /* this cmd refers to a pipe */ 66 do_sort, /* field to sort results (0 = no) */ 67 do_dynamic, /* display dynamic rules */ 68 do_expired, /* display expired dynamic rules */ 69 do_compact, /* show rules in compact mode */ 70 do_force, /* do not ask for confirmation */ 71 show_sets, /* display rule sets */ 72 test_only, /* only check syntax */ 73 comment_only, /* only print action and comment */ 74 verbose; 75 76 #define IP_MASK_ALL 0xffffffff 77 /* 78 * the following macro returns an error message if we run out of 79 * arguments. 80 */ 81 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);} 82 83 /* 84 * _s_x is a structure that stores a string <-> token pairs, used in 85 * various places in the parser. Entries are stored in arrays, 86 * with an entry with s=NULL as terminator. 87 * The search routines are match_token() and match_value(). 88 * Often, an element with x=0 contains an error string. 89 * 90 */ 91 struct _s_x { 92 char const *s; 93 int x; 94 }; 95 96 static struct _s_x f_tcpflags[] = { 97 { "syn", TH_SYN }, 98 { "fin", TH_FIN }, 99 { "ack", TH_ACK }, 100 { "psh", TH_PUSH }, 101 { "rst", TH_RST }, 102 { "urg", TH_URG }, 103 { "tcp flag", 0 }, 104 { NULL, 0 } 105 }; 106 107 static struct _s_x f_tcpopts[] = { 108 { "mss", IP_FW_TCPOPT_MSS }, 109 { "maxseg", IP_FW_TCPOPT_MSS }, 110 { "window", IP_FW_TCPOPT_WINDOW }, 111 { "sack", IP_FW_TCPOPT_SACK }, 112 { "ts", IP_FW_TCPOPT_TS }, 113 { "timestamp", IP_FW_TCPOPT_TS }, 114 { "cc", IP_FW_TCPOPT_CC }, 115 { "tcp option", 0 }, 116 { NULL, 0 } 117 }; 118 119 /* 120 * IP options span the range 0 to 255 so we need to remap them 121 * (though in fact only the low 5 bits are significant). 122 */ 123 static struct _s_x f_ipopts[] = { 124 { "ssrr", IP_FW_IPOPT_SSRR}, 125 { "lsrr", IP_FW_IPOPT_LSRR}, 126 { "rr", IP_FW_IPOPT_RR}, 127 { "ts", IP_FW_IPOPT_TS}, 128 { "ip option", 0 }, 129 { NULL, 0 } 130 }; 131 132 static struct _s_x f_iptos[] = { 133 { "lowdelay", IPTOS_LOWDELAY}, 134 { "throughput", IPTOS_THROUGHPUT}, 135 { "reliability", IPTOS_RELIABILITY}, 136 { "mincost", IPTOS_MINCOST}, 137 { "congestion", IPTOS_CE}, 138 { "ecntransport", IPTOS_ECT}, 139 { "ip tos option", 0}, 140 { NULL, 0 } 141 }; 142 143 static struct _s_x limit_masks[] = { 144 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT}, 145 {"src-addr", DYN_SRC_ADDR}, 146 {"src-port", DYN_SRC_PORT}, 147 {"dst-addr", DYN_DST_ADDR}, 148 {"dst-port", DYN_DST_PORT}, 149 {NULL, 0} 150 }; 151 152 /* 153 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines 154 * This is only used in this code. 155 */ 156 #define IPPROTO_ETHERTYPE 0x1000 157 static struct _s_x ether_types[] = { 158 /* 159 * Note, we cannot use "-:&/" in the names because they are field 160 * separators in the type specifications. Also, we use s = NULL as 161 * end-delimiter, because a type of 0 can be legal. 162 */ 163 { "ip", 0x0800 }, 164 { "ipv4", 0x0800 }, 165 { "ipv6", 0x86dd }, 166 { "arp", 0x0806 }, 167 { "rarp", 0x8035 }, 168 { "vlan", 0x8100 }, 169 { "loop", 0x9000 }, 170 { "trail", 0x1000 }, 171 { "at", 0x809b }, 172 { "atalk", 0x809b }, 173 { "aarp", 0x80f3 }, 174 { "pppoe_disc", 0x8863 }, 175 { "pppoe_sess", 0x8864 }, 176 { "ipx_8022", 0x00E0 }, 177 { "ipx_8023", 0x0000 }, 178 { "ipx_ii", 0x8137 }, 179 { "ipx_snap", 0x8137 }, 180 { "ipx", 0x8137 }, 181 { "ns", 0x0600 }, 182 { NULL, 0 } 183 }; 184 185 static void show_usage(void); 186 187 enum tokens { 188 TOK_NULL=0, 189 190 TOK_OR, 191 TOK_NOT, 192 TOK_STARTBRACE, 193 TOK_ENDBRACE, 194 195 TOK_ACCEPT, 196 TOK_COUNT, 197 TOK_PIPE, 198 TOK_QUEUE, 199 TOK_DIVERT, 200 TOK_TEE, 201 TOK_FORWARD, 202 TOK_SKIPTO, 203 TOK_DENY, 204 TOK_REJECT, 205 TOK_RESET, 206 TOK_UNREACH, 207 TOK_CHECKSTATE, 208 209 TOK_ALTQ, 210 TOK_LOG, 211 212 TOK_UID, 213 TOK_GID, 214 TOK_JAIL, 215 TOK_IN, 216 TOK_LIMIT, 217 TOK_KEEPSTATE, 218 TOK_LAYER2, 219 TOK_OUT, 220 TOK_DIVERTED, 221 TOK_DIVERTEDLOOPBACK, 222 TOK_DIVERTEDOUTPUT, 223 TOK_XMIT, 224 TOK_RECV, 225 TOK_VIA, 226 TOK_FRAG, 227 TOK_IPOPTS, 228 TOK_IPLEN, 229 TOK_IPID, 230 TOK_IPPRECEDENCE, 231 TOK_IPTOS, 232 TOK_IPTTL, 233 TOK_IPVER, 234 TOK_ESTAB, 235 TOK_SETUP, 236 TOK_TCPDATALEN, 237 TOK_TCPFLAGS, 238 TOK_TCPOPTS, 239 TOK_TCPSEQ, 240 TOK_TCPACK, 241 TOK_TCPWIN, 242 TOK_ICMPTYPES, 243 TOK_MAC, 244 TOK_MACTYPE, 245 TOK_VERREVPATH, 246 TOK_VERSRCREACH, 247 TOK_ANTISPOOF, 248 TOK_IPSEC, 249 TOK_COMMENT, 250 251 TOK_PLR, 252 TOK_NOERROR, 253 TOK_BUCKETS, 254 TOK_DSTIP, 255 TOK_SRCIP, 256 TOK_DSTPORT, 257 TOK_SRCPORT, 258 TOK_ALL, 259 TOK_MASK, 260 TOK_BW, 261 TOK_DELAY, 262 TOK_RED, 263 TOK_GRED, 264 TOK_DROPTAIL, 265 TOK_PROTO, 266 TOK_WEIGHT, 267 }; 268 269 struct _s_x dummynet_params[] = { 270 { "plr", TOK_PLR }, 271 { "noerror", TOK_NOERROR }, 272 { "buckets", TOK_BUCKETS }, 273 { "dst-ip", TOK_DSTIP }, 274 { "src-ip", TOK_SRCIP }, 275 { "dst-port", TOK_DSTPORT }, 276 { "src-port", TOK_SRCPORT }, 277 { "proto", TOK_PROTO }, 278 { "weight", TOK_WEIGHT }, 279 { "all", TOK_ALL }, 280 { "mask", TOK_MASK }, 281 { "droptail", TOK_DROPTAIL }, 282 { "red", TOK_RED }, 283 { "gred", TOK_GRED }, 284 { "bw", TOK_BW }, 285 { "bandwidth", TOK_BW }, 286 { "delay", TOK_DELAY }, 287 { "pipe", TOK_PIPE }, 288 { "queue", TOK_QUEUE }, 289 { "dummynet-params", TOK_NULL }, 290 { NULL, 0 } /* terminator */ 291 }; 292 293 struct _s_x rule_actions[] = { 294 { "accept", TOK_ACCEPT }, 295 { "pass", TOK_ACCEPT }, 296 { "allow", TOK_ACCEPT }, 297 { "permit", TOK_ACCEPT }, 298 { "count", TOK_COUNT }, 299 { "pipe", TOK_PIPE }, 300 { "queue", TOK_QUEUE }, 301 { "divert", TOK_DIVERT }, 302 { "tee", TOK_TEE }, 303 { "fwd", TOK_FORWARD }, 304 { "forward", TOK_FORWARD }, 305 { "skipto", TOK_SKIPTO }, 306 { "deny", TOK_DENY }, 307 { "drop", TOK_DENY }, 308 { "reject", TOK_REJECT }, 309 { "reset", TOK_RESET }, 310 { "unreach", TOK_UNREACH }, 311 { "check-state", TOK_CHECKSTATE }, 312 { "//", TOK_COMMENT }, 313 { NULL, 0 } /* terminator */ 314 }; 315 316 struct _s_x rule_action_params[] = { 317 { "altq", TOK_ALTQ }, 318 { "log", TOK_LOG }, 319 { NULL, 0 } /* terminator */ 320 }; 321 322 struct _s_x rule_options[] = { 323 { "uid", TOK_UID }, 324 { "gid", TOK_GID }, 325 { "jail", TOK_JAIL }, 326 { "in", TOK_IN }, 327 { "limit", TOK_LIMIT }, 328 { "keep-state", TOK_KEEPSTATE }, 329 { "bridged", TOK_LAYER2 }, 330 { "layer2", TOK_LAYER2 }, 331 { "out", TOK_OUT }, 332 { "diverted", TOK_DIVERTED }, 333 { "diverted-loopback", TOK_DIVERTEDLOOPBACK }, 334 { "diverted-output", TOK_DIVERTEDOUTPUT }, 335 { "xmit", TOK_XMIT }, 336 { "recv", TOK_RECV }, 337 { "via", TOK_VIA }, 338 { "fragment", TOK_FRAG }, 339 { "frag", TOK_FRAG }, 340 { "ipoptions", TOK_IPOPTS }, 341 { "ipopts", TOK_IPOPTS }, 342 { "iplen", TOK_IPLEN }, 343 { "ipid", TOK_IPID }, 344 { "ipprecedence", TOK_IPPRECEDENCE }, 345 { "iptos", TOK_IPTOS }, 346 { "ipttl", TOK_IPTTL }, 347 { "ipversion", TOK_IPVER }, 348 { "ipver", TOK_IPVER }, 349 { "estab", TOK_ESTAB }, 350 { "established", TOK_ESTAB }, 351 { "setup", TOK_SETUP }, 352 { "tcpdatalen", TOK_TCPDATALEN }, 353 { "tcpflags", TOK_TCPFLAGS }, 354 { "tcpflgs", TOK_TCPFLAGS }, 355 { "tcpoptions", TOK_TCPOPTS }, 356 { "tcpopts", TOK_TCPOPTS }, 357 { "tcpseq", TOK_TCPSEQ }, 358 { "tcpack", TOK_TCPACK }, 359 { "tcpwin", TOK_TCPWIN }, 360 { "icmptype", TOK_ICMPTYPES }, 361 { "icmptypes", TOK_ICMPTYPES }, 362 { "dst-ip", TOK_DSTIP }, 363 { "src-ip", TOK_SRCIP }, 364 { "dst-port", TOK_DSTPORT }, 365 { "src-port", TOK_SRCPORT }, 366 { "proto", TOK_PROTO }, 367 { "MAC", TOK_MAC }, 368 { "mac", TOK_MAC }, 369 { "mac-type", TOK_MACTYPE }, 370 { "verrevpath", TOK_VERREVPATH }, 371 { "versrcreach", TOK_VERSRCREACH }, 372 { "antispoof", TOK_ANTISPOOF }, 373 { "ipsec", TOK_IPSEC }, 374 { "//", TOK_COMMENT }, 375 376 { "not", TOK_NOT }, /* pseudo option */ 377 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */ 378 { "or", TOK_OR }, /* pseudo option */ 379 { "|", /* escape */ TOK_OR }, /* pseudo option */ 380 { "{", TOK_STARTBRACE }, /* pseudo option */ 381 { "(", TOK_STARTBRACE }, /* pseudo option */ 382 { "}", TOK_ENDBRACE }, /* pseudo option */ 383 { ")", TOK_ENDBRACE }, /* pseudo option */ 384 { NULL, 0 } /* terminator */ 385 }; 386 387 static __inline uint64_t 388 align_uint64(uint64_t *pll) { 389 uint64_t ret; 390 391 bcopy (pll, &ret, sizeof(ret)); 392 return ret; 393 } 394 395 /* 396 * conditionally runs the command. 397 */ 398 static int 399 do_cmd(int optname, void *optval, uintptr_t optlen) 400 { 401 static int s = -1; /* the socket */ 402 int i; 403 404 if (test_only) 405 return 0; 406 407 if (s == -1) 408 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 409 if (s < 0) 410 err(EX_UNAVAILABLE, "socket"); 411 412 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET || 413 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST || 414 optname == IP_FW_TABLE_GETSIZE) 415 i = getsockopt(s, IPPROTO_IP, optname, optval, 416 (socklen_t *)optlen); 417 else 418 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen); 419 return i; 420 } 421 422 /** 423 * match_token takes a table and a string, returns the value associated 424 * with the string (-1 in case of failure). 425 */ 426 static int 427 match_token(struct _s_x *table, char *string) 428 { 429 struct _s_x *pt; 430 uint i = strlen(string); 431 432 for (pt = table ; i && pt->s != NULL ; pt++) 433 if (strlen(pt->s) == i && !bcmp(string, pt->s, i)) 434 return pt->x; 435 return -1; 436 } 437 438 /** 439 * match_value takes a table and a value, returns the string associated 440 * with the value (NULL in case of failure). 441 */ 442 static char const * 443 match_value(struct _s_x *p, int value) 444 { 445 for (; p->s != NULL; p++) 446 if (p->x == value) 447 return p->s; 448 return NULL; 449 } 450 451 /* 452 * prints one port, symbolic or numeric 453 */ 454 static void 455 print_port(int proto, uint16_t port) 456 { 457 458 if (proto == IPPROTO_ETHERTYPE) { 459 char const *s; 460 461 if (do_resolv && (s = match_value(ether_types, port)) ) 462 printf("%s", s); 463 else 464 printf("0x%04x", port); 465 } else { 466 struct servent *se = NULL; 467 if (do_resolv) { 468 struct protoent *pe = getprotobynumber(proto); 469 470 se = getservbyport(htons(port), pe ? pe->p_name : NULL); 471 } 472 if (se) 473 printf("%s", se->s_name); 474 else 475 printf("%d", port); 476 } 477 } 478 479 struct _s_x _port_name[] = { 480 {"dst-port", O_IP_DSTPORT}, 481 {"src-port", O_IP_SRCPORT}, 482 {"ipid", O_IPID}, 483 {"iplen", O_IPLEN}, 484 {"ipttl", O_IPTTL}, 485 {"mac-type", O_MAC_TYPE}, 486 {"tcpdatalen", O_TCPDATALEN}, 487 {NULL, 0} 488 }; 489 490 /* 491 * Print the values in a list 16-bit items of the types above. 492 * XXX todo: add support for mask. 493 */ 494 static void 495 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode) 496 { 497 uint16_t *p = cmd->ports; 498 int i; 499 char const *sep; 500 501 if (cmd->o.len & F_NOT) 502 printf(" not"); 503 if (opcode != 0) { 504 sep = match_value(_port_name, opcode); 505 if (sep == NULL) 506 sep = "???"; 507 printf (" %s", sep); 508 } 509 sep = " "; 510 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) { 511 printf(sep); 512 print_port(proto, p[0]); 513 if (p[0] != p[1]) { 514 printf("-"); 515 print_port(proto, p[1]); 516 } 517 sep = ","; 518 } 519 } 520 521 /* 522 * Like strtol, but also translates service names into port numbers 523 * for some protocols. 524 * In particular: 525 * proto == -1 disables the protocol check; 526 * proto == IPPROTO_ETHERTYPE looks up an internal table 527 * proto == <some value in /etc/protocols> matches the values there. 528 * Returns *end == s in case the parameter is not found. 529 */ 530 static int 531 strtoport(char *s, char **end, int base, int proto) 532 { 533 char *p, *buf; 534 char *s1; 535 int i; 536 537 *end = s; /* default - not found */ 538 if (*s == '\0') 539 return 0; /* not found */ 540 541 if (isdigit(*s)) 542 return strtol(s, end, base); 543 544 /* 545 * find separator. '\\' escapes the next char. 546 */ 547 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++) 548 if (*s1 == '\\' && s1[1] != '\0') 549 s1++; 550 551 buf = malloc(s1 - s + 1); 552 if (buf == NULL) 553 return 0; 554 555 /* 556 * copy into a buffer skipping backslashes 557 */ 558 for (p = s, i = 0; p != s1 ; p++) 559 if (*p != '\\') 560 buf[i++] = *p; 561 buf[i++] = '\0'; 562 563 if (proto == IPPROTO_ETHERTYPE) { 564 i = match_token(ether_types, buf); 565 free(buf); 566 if (i != -1) { /* found */ 567 *end = s1; 568 return i; 569 } 570 } else { 571 struct protoent *pe = NULL; 572 struct servent *se; 573 574 if (proto != 0) 575 pe = getprotobynumber(proto); 576 setservent(1); 577 se = getservbyname(buf, pe ? pe->p_name : NULL); 578 free(buf); 579 if (se != NULL) { 580 *end = s1; 581 return ntohs(se->s_port); 582 } 583 } 584 return 0; /* not found */ 585 } 586 587 /* 588 * Map between current altq queue id numbers and names. 589 */ 590 static int altq_fetched = 0; 591 static TAILQ_HEAD(, pf_altq) altq_entries = 592 TAILQ_HEAD_INITIALIZER(altq_entries); 593 594 static void 595 altq_set_enabled(int enabled) 596 { 597 int pffd; 598 599 pffd = open("/dev/pf", O_RDWR); 600 if (pffd == -1) 601 err(EX_UNAVAILABLE, 602 "altq support opening pf(4) control device"); 603 if (enabled) { 604 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST) 605 err(EX_UNAVAILABLE, "enabling altq"); 606 } else { 607 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT) 608 err(EX_UNAVAILABLE, "disabling altq"); 609 } 610 close(pffd); 611 } 612 613 static void 614 altq_fetch() 615 { 616 struct pfioc_altq pfioc; 617 struct pf_altq *altq; 618 int pffd, mnr; 619 620 if (altq_fetched) 621 return; 622 altq_fetched = 1; 623 pffd = open("/dev/pf", O_RDONLY); 624 if (pffd == -1) { 625 warn("altq support opening pf(4) control device"); 626 return; 627 } 628 bzero(&pfioc, sizeof(pfioc)); 629 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) { 630 warn("altq support getting queue list"); 631 close(pffd); 632 return; 633 } 634 mnr = pfioc.nr; 635 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) { 636 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) { 637 if (errno == EBUSY) 638 break; 639 warn("altq support getting queue list"); 640 close(pffd); 641 return; 642 } 643 if (pfioc.altq.qid == 0) 644 continue; 645 altq = malloc(sizeof(*altq)); 646 if (altq == NULL) 647 err(EX_OSERR, "malloc"); 648 *altq = pfioc.altq; 649 TAILQ_INSERT_TAIL(&altq_entries, altq, entries); 650 } 651 close(pffd); 652 } 653 654 static u_int32_t 655 altq_name_to_qid(const char *name) 656 { 657 struct pf_altq *altq; 658 659 altq_fetch(); 660 TAILQ_FOREACH(altq, &altq_entries, entries) 661 if (strcmp(name, altq->qname) == 0) 662 break; 663 if (altq == NULL) 664 errx(EX_DATAERR, "altq has no queue named `%s'", name); 665 return altq->qid; 666 } 667 668 static const char * 669 altq_qid_to_name(u_int32_t qid) 670 { 671 struct pf_altq *altq; 672 673 altq_fetch(); 674 TAILQ_FOREACH(altq, &altq_entries, entries) 675 if (qid == altq->qid) 676 break; 677 if (altq == NULL) 678 return NULL; 679 return altq->qname; 680 } 681 682 static void 683 fill_altq_qid(u_int32_t *qid, const char *av) 684 { 685 *qid = altq_name_to_qid(av); 686 } 687 688 /* 689 * Fill the body of the command with the list of port ranges. 690 */ 691 static int 692 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto) 693 { 694 uint16_t a, b, *p = cmd->ports; 695 int i = 0; 696 char *s = av; 697 698 while (*s) { 699 a = strtoport(av, &s, 0, proto); 700 if (s == av) /* no parameter */ 701 break; 702 if (*s == '-') { /* a range */ 703 av = s+1; 704 b = strtoport(av, &s, 0, proto); 705 if (s == av) /* no parameter */ 706 break; 707 p[0] = a; 708 p[1] = b; 709 } else if (*s == ',' || *s == '\0' ) 710 p[0] = p[1] = a; 711 else /* invalid separator */ 712 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n", 713 *s, av); 714 i++; 715 p += 2; 716 av = s+1; 717 } 718 if (i > 0) { 719 if (i+1 > F_LEN_MASK) 720 errx(EX_DATAERR, "too many ports/ranges\n"); 721 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */ 722 } 723 return i; 724 } 725 726 static struct _s_x icmpcodes[] = { 727 { "net", ICMP_UNREACH_NET }, 728 { "host", ICMP_UNREACH_HOST }, 729 { "protocol", ICMP_UNREACH_PROTOCOL }, 730 { "port", ICMP_UNREACH_PORT }, 731 { "needfrag", ICMP_UNREACH_NEEDFRAG }, 732 { "srcfail", ICMP_UNREACH_SRCFAIL }, 733 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN }, 734 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN }, 735 { "isolated", ICMP_UNREACH_ISOLATED }, 736 { "net-prohib", ICMP_UNREACH_NET_PROHIB }, 737 { "host-prohib", ICMP_UNREACH_HOST_PROHIB }, 738 { "tosnet", ICMP_UNREACH_TOSNET }, 739 { "toshost", ICMP_UNREACH_TOSHOST }, 740 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB }, 741 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE }, 742 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF }, 743 { NULL, 0 } 744 }; 745 746 static void 747 fill_reject_code(u_short *codep, char *str) 748 { 749 int val; 750 char *s; 751 752 val = strtoul(str, &s, 0); 753 if (s == str || *s != '\0' || val >= 0x100) 754 val = match_token(icmpcodes, str); 755 if (val < 0) 756 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str); 757 *codep = val; 758 return; 759 } 760 761 static void 762 print_reject_code(uint16_t code) 763 { 764 char const *s = match_value(icmpcodes, code); 765 766 if (s != NULL) 767 printf("unreach %s", s); 768 else 769 printf("unreach %u", code); 770 } 771 772 /* 773 * Returns the number of bits set (from left) in a contiguous bitmask, 774 * or -1 if the mask is not contiguous. 775 * XXX this needs a proper fix. 776 * This effectively works on masks in big-endian (network) format. 777 * when compiled on little endian architectures. 778 * 779 * First bit is bit 7 of the first byte -- note, for MAC addresses, 780 * the first bit on the wire is bit 0 of the first byte. 781 * len is the max length in bits. 782 */ 783 static int 784 contigmask(uint8_t *p, int len) 785 { 786 int i, n; 787 788 for (i=0; i<len ; i++) 789 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */ 790 break; 791 for (n=i+1; n < len; n++) 792 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0) 793 return -1; /* mask not contiguous */ 794 return i; 795 } 796 797 /* 798 * print flags set/clear in the two bitmasks passed as parameters. 799 * There is a specialized check for f_tcpflags. 800 */ 801 static void 802 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list) 803 { 804 char const *comma = ""; 805 int i; 806 uint8_t set = cmd->arg1 & 0xff; 807 uint8_t clear = (cmd->arg1 >> 8) & 0xff; 808 809 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) { 810 printf(" setup"); 811 return; 812 } 813 814 printf(" %s ", name); 815 for (i=0; list[i].x != 0; i++) { 816 if (set & list[i].x) { 817 set &= ~list[i].x; 818 printf("%s%s", comma, list[i].s); 819 comma = ","; 820 } 821 if (clear & list[i].x) { 822 clear &= ~list[i].x; 823 printf("%s!%s", comma, list[i].s); 824 comma = ","; 825 } 826 } 827 } 828 829 /* 830 * Print the ip address contained in a command. 831 */ 832 static void 833 print_ip(ipfw_insn_ip *cmd, char const *s) 834 { 835 struct hostent *he = NULL; 836 int len = F_LEN((ipfw_insn *)cmd); 837 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d; 838 839 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 840 841 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) { 842 printf("me"); 843 return; 844 } 845 if (cmd->o.opcode == O_IP_SRC_LOOKUP || 846 cmd->o.opcode == O_IP_DST_LOOKUP) { 847 printf("table(%u", ((ipfw_insn *)cmd)->arg1); 848 if (len == F_INSN_SIZE(ipfw_insn_u32)) 849 printf(",%u", *a); 850 printf(")"); 851 return; 852 } 853 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) { 854 uint32_t x, *map = (uint32_t *)&(cmd->mask); 855 int i, j; 856 char comma = '{'; 857 858 x = cmd->o.arg1 - 1; 859 x = htonl( ~x ); 860 cmd->addr.s_addr = htonl(cmd->addr.s_addr); 861 printf("%s/%d", inet_ntoa(cmd->addr), 862 contigmask((uint8_t *)&x, 32)); 863 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr); 864 x &= 0xff; /* base */ 865 /* 866 * Print bits and ranges. 867 * Locate first bit set (i), then locate first bit unset (j). 868 * If we have 3+ consecutive bits set, then print them as a 869 * range, otherwise only print the initial bit and rescan. 870 */ 871 for (i=0; i < cmd->o.arg1; i++) 872 if (map[i/32] & (1<<(i & 31))) { 873 for (j=i+1; j < cmd->o.arg1; j++) 874 if (!(map[ j/32] & (1<<(j & 31)))) 875 break; 876 printf("%c%d", comma, i+x); 877 if (j>i+2) { /* range has at least 3 elements */ 878 printf("-%d", j-1+x); 879 i = j-1; 880 } 881 comma = ','; 882 } 883 printf("}"); 884 return; 885 } 886 /* 887 * len == 2 indicates a single IP, whereas lists of 1 or more 888 * addr/mask pairs have len = (2n+1). We convert len to n so we 889 * use that to count the number of entries. 890 */ 891 for (len = len / 2; len > 0; len--, a += 2) { 892 int mb = /* mask length */ 893 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ? 894 32 : contigmask((uint8_t *)&(a[1]), 32); 895 if (mb == 32 && do_resolv) 896 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET); 897 if (he != NULL) /* resolved to name */ 898 printf("%s", he->h_name); 899 else if (mb == 0) /* any */ 900 printf("any"); 901 else { /* numeric IP followed by some kind of mask */ 902 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) ); 903 if (mb < 0) 904 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) ); 905 else if (mb < 32) 906 printf("/%d", mb); 907 } 908 if (len > 1) 909 printf(","); 910 } 911 } 912 913 /* 914 * prints a MAC address/mask pair 915 */ 916 static void 917 print_mac(uint8_t *addr, uint8_t *mask) 918 { 919 int l = contigmask(mask, 48); 920 921 if (l == 0) 922 printf(" any"); 923 else { 924 printf(" %02x:%02x:%02x:%02x:%02x:%02x", 925 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); 926 if (l == -1) 927 printf("&%02x:%02x:%02x:%02x:%02x:%02x", 928 mask[0], mask[1], mask[2], 929 mask[3], mask[4], mask[5]); 930 else if (l < 48) 931 printf("/%d", l); 932 } 933 } 934 935 static void 936 fill_icmptypes(ipfw_insn_u32 *cmd, char *av) 937 { 938 uint8_t type; 939 940 cmd->d[0] = 0; 941 while (*av) { 942 if (*av == ',') 943 av++; 944 945 type = strtoul(av, &av, 0); 946 947 if (*av != ',' && *av != '\0') 948 errx(EX_DATAERR, "invalid ICMP type"); 949 950 if (type > 31) 951 errx(EX_DATAERR, "ICMP type out of range"); 952 953 cmd->d[0] |= 1 << type; 954 } 955 cmd->o.opcode = O_ICMPTYPE; 956 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 957 } 958 959 static void 960 print_icmptypes(ipfw_insn_u32 *cmd) 961 { 962 int i; 963 char sep= ' '; 964 965 printf(" icmptypes"); 966 for (i = 0; i < 32; i++) { 967 if ( (cmd->d[0] & (1 << (i))) == 0) 968 continue; 969 printf("%c%d", sep, i); 970 sep = ','; 971 } 972 } 973 974 /* 975 * show_ipfw() prints the body of an ipfw rule. 976 * Because the standard rule has at least proto src_ip dst_ip, we use 977 * a helper function to produce these entries if not provided explicitly. 978 * The first argument is the list of fields we have, the second is 979 * the list of fields we want to be printed. 980 * 981 * Special cases if we have provided a MAC header: 982 * + if the rule does not contain IP addresses/ports, do not print them; 983 * + if the rule does not contain an IP proto, print "all" instead of "ip"; 984 * 985 * Once we have 'have_options', IP header fields are printed as options. 986 */ 987 #define HAVE_PROTO 0x0001 988 #define HAVE_SRCIP 0x0002 989 #define HAVE_DSTIP 0x0004 990 #define HAVE_MAC 0x0008 991 #define HAVE_MACTYPE 0x0010 992 #define HAVE_OPTIONS 0x8000 993 994 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP) 995 static void 996 show_prerequisites(int *flags, int want, int cmd) 997 { 998 if (comment_only) 999 return; 1000 if ( (*flags & HAVE_IP) == HAVE_IP) 1001 *flags |= HAVE_OPTIONS; 1002 1003 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC && 1004 cmd != O_MAC_TYPE) { 1005 /* 1006 * mac-type was optimized out by the compiler, 1007 * restore it 1008 */ 1009 printf(" any"); 1010 *flags |= HAVE_MACTYPE | HAVE_OPTIONS; 1011 return; 1012 } 1013 if ( !(*flags & HAVE_OPTIONS)) { 1014 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) 1015 printf(" ip"); 1016 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP)) 1017 printf(" from any"); 1018 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP)) 1019 printf(" to any"); 1020 } 1021 *flags |= want; 1022 } 1023 1024 static void 1025 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth) 1026 { 1027 static int twidth = 0; 1028 int l; 1029 ipfw_insn *cmd; 1030 char *comment = NULL; /* ptr to comment if we have one */ 1031 int proto = 0; /* default */ 1032 int flags = 0; /* prerequisites */ 1033 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */ 1034 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */ 1035 int or_block = 0; /* we are in an or block */ 1036 uint32_t set_disable; 1037 1038 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable)); 1039 1040 if (set_disable & (1 << rule->set)) { /* disabled */ 1041 if (!show_sets) 1042 return; 1043 else 1044 printf("# DISABLED "); 1045 } 1046 printf("%05u ", rule->rulenum); 1047 1048 if (pcwidth>0 || bcwidth>0) 1049 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt), 1050 bcwidth, align_uint64(&rule->bcnt)); 1051 1052 if (do_time == 2) 1053 printf("%10u ", rule->timestamp); 1054 else if (do_time == 1) { 1055 char timestr[30]; 1056 time_t t = (time_t)0; 1057 1058 if (twidth == 0) { 1059 strcpy(timestr, ctime(&t)); 1060 *strchr(timestr, '\n') = '\0'; 1061 twidth = strlen(timestr); 1062 } 1063 if (rule->timestamp) { 1064 #if _FreeBSD_version < 500000 /* XXX check */ 1065 #define _long_to_time(x) (time_t)(x) 1066 #endif 1067 t = _long_to_time(rule->timestamp); 1068 1069 strcpy(timestr, ctime(&t)); 1070 *strchr(timestr, '\n') = '\0'; 1071 printf("%s ", timestr); 1072 } else { 1073 printf("%*s", twidth, " "); 1074 } 1075 } 1076 1077 if (show_sets) 1078 printf("set %d ", rule->set); 1079 1080 /* 1081 * print the optional "match probability" 1082 */ 1083 if (rule->cmd_len > 0) { 1084 cmd = rule->cmd ; 1085 if (cmd->opcode == O_PROB) { 1086 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd; 1087 double d = 1.0 * p->d[0]; 1088 1089 d = (d / 0x7fffffff); 1090 printf("prob %f ", d); 1091 } 1092 } 1093 1094 /* 1095 * first print actions 1096 */ 1097 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule); 1098 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) { 1099 switch(cmd->opcode) { 1100 case O_CHECK_STATE: 1101 printf("check-state"); 1102 flags = HAVE_IP; /* avoid printing anything else */ 1103 break; 1104 1105 case O_ACCEPT: 1106 printf("allow"); 1107 break; 1108 1109 case O_COUNT: 1110 printf("count"); 1111 break; 1112 1113 case O_DENY: 1114 printf("deny"); 1115 break; 1116 1117 case O_REJECT: 1118 if (cmd->arg1 == ICMP_REJECT_RST) 1119 printf("reset"); 1120 else if (cmd->arg1 == ICMP_UNREACH_HOST) 1121 printf("reject"); 1122 else 1123 print_reject_code(cmd->arg1); 1124 break; 1125 1126 case O_SKIPTO: 1127 printf("skipto %u", cmd->arg1); 1128 break; 1129 1130 case O_PIPE: 1131 printf("pipe %u", cmd->arg1); 1132 break; 1133 1134 case O_QUEUE: 1135 printf("queue %u", cmd->arg1); 1136 break; 1137 1138 case O_DIVERT: 1139 printf("divert %u", cmd->arg1); 1140 break; 1141 1142 case O_TEE: 1143 printf("tee %u", cmd->arg1); 1144 break; 1145 1146 case O_FORWARD_IP: 1147 { 1148 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd; 1149 1150 printf("fwd %s", inet_ntoa(s->sa.sin_addr)); 1151 if (s->sa.sin_port) 1152 printf(",%d", s->sa.sin_port); 1153 } 1154 break; 1155 1156 case O_LOG: /* O_LOG is printed last */ 1157 logptr = (ipfw_insn_log *)cmd; 1158 break; 1159 1160 case O_ALTQ: /* O_ALTQ is printed after O_LOG */ 1161 altqptr = (ipfw_insn_altq *)cmd; 1162 break; 1163 1164 default: 1165 printf("** unrecognized action %d len %d ", 1166 cmd->opcode, cmd->len); 1167 } 1168 } 1169 if (logptr) { 1170 if (logptr->max_log > 0) 1171 printf(" log logamount %d", logptr->max_log); 1172 else 1173 printf(" log"); 1174 } 1175 if (altqptr) { 1176 const char *qname; 1177 1178 qname = altq_qid_to_name(altqptr->qid); 1179 if (qname == NULL) 1180 printf(" altq ?<%u>", altqptr->qid); 1181 else 1182 printf(" altq %s", qname); 1183 } 1184 1185 /* 1186 * then print the body. 1187 */ 1188 if (rule->_pad & 1) { /* empty rules before options */ 1189 if (!do_compact) 1190 printf(" ip from any to any"); 1191 flags |= HAVE_IP | HAVE_OPTIONS; 1192 } 1193 1194 if (comment_only) 1195 comment = "..."; 1196 1197 for (l = rule->act_ofs, cmd = rule->cmd ; 1198 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1199 /* useful alias */ 1200 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; 1201 1202 if (comment_only) { 1203 if (cmd->opcode != O_NOP) 1204 continue; 1205 printf(" // %s\n", (char *)(cmd + 1)); 1206 return; 1207 } 1208 1209 show_prerequisites(&flags, 0, cmd->opcode); 1210 1211 switch(cmd->opcode) { 1212 case O_PROB: 1213 break; /* done already */ 1214 1215 case O_PROBE_STATE: 1216 break; /* no need to print anything here */ 1217 1218 case O_MACADDR2: { 1219 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd; 1220 1221 if ((cmd->len & F_OR) && !or_block) 1222 printf(" {"); 1223 if (cmd->len & F_NOT) 1224 printf(" not"); 1225 printf(" MAC"); 1226 flags |= HAVE_MAC; 1227 print_mac(m->addr, m->mask); 1228 print_mac(m->addr + 6, m->mask + 6); 1229 } 1230 break; 1231 1232 case O_MAC_TYPE: 1233 if ((cmd->len & F_OR) && !or_block) 1234 printf(" {"); 1235 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE, 1236 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1237 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS; 1238 break; 1239 1240 case O_IP_SRC: 1241 case O_IP_SRC_LOOKUP: 1242 case O_IP_SRC_MASK: 1243 case O_IP_SRC_ME: 1244 case O_IP_SRC_SET: 1245 show_prerequisites(&flags, HAVE_PROTO, 0); 1246 if (!(flags & HAVE_SRCIP)) 1247 printf(" from"); 1248 if ((cmd->len & F_OR) && !or_block) 1249 printf(" {"); 1250 print_ip((ipfw_insn_ip *)cmd, 1251 (flags & HAVE_OPTIONS) ? " src-ip" : ""); 1252 flags |= HAVE_SRCIP; 1253 break; 1254 1255 case O_IP_DST: 1256 case O_IP_DST_LOOKUP: 1257 case O_IP_DST_MASK: 1258 case O_IP_DST_ME: 1259 case O_IP_DST_SET: 1260 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1261 if (!(flags & HAVE_DSTIP)) 1262 printf(" to"); 1263 if ((cmd->len & F_OR) && !or_block) 1264 printf(" {"); 1265 print_ip((ipfw_insn_ip *)cmd, 1266 (flags & HAVE_OPTIONS) ? " dst-ip" : ""); 1267 flags |= HAVE_DSTIP; 1268 break; 1269 1270 case O_IP_DSTPORT: 1271 show_prerequisites(&flags, HAVE_IP, 0); 1272 case O_IP_SRCPORT: 1273 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1274 if ((cmd->len & F_OR) && !or_block) 1275 printf(" {"); 1276 print_newports((ipfw_insn_u16 *)cmd, proto, 1277 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1278 break; 1279 1280 case O_PROTO: { 1281 struct protoent *pe; 1282 1283 if ((cmd->len & F_OR) && !or_block) 1284 printf(" {"); 1285 if (cmd->len & F_NOT) 1286 printf(" not"); 1287 proto = cmd->arg1; 1288 pe = getprotobynumber(cmd->arg1); 1289 if (flags & HAVE_OPTIONS) 1290 printf(" proto"); 1291 if (pe) 1292 printf(" %s", pe->p_name); 1293 else 1294 printf(" %u", cmd->arg1); 1295 } 1296 flags |= HAVE_PROTO; 1297 break; 1298 1299 default: /*options ... */ 1300 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0); 1301 if ((cmd->len & F_OR) && !or_block) 1302 printf(" {"); 1303 if (cmd->len & F_NOT && cmd->opcode != O_IN) 1304 printf(" not"); 1305 switch(cmd->opcode) { 1306 case O_FRAG: 1307 printf(" frag"); 1308 break; 1309 1310 case O_IN: 1311 printf(cmd->len & F_NOT ? " out" : " in"); 1312 break; 1313 1314 case O_DIVERTED: 1315 switch (cmd->arg1) { 1316 case 3: 1317 printf(" diverted"); 1318 break; 1319 case 1: 1320 printf(" diverted-loopback"); 1321 break; 1322 case 2: 1323 printf(" diverted-output"); 1324 break; 1325 default: 1326 printf(" diverted-?<%u>", cmd->arg1); 1327 break; 1328 } 1329 break; 1330 1331 case O_LAYER2: 1332 printf(" layer2"); 1333 break; 1334 case O_XMIT: 1335 case O_RECV: 1336 case O_VIA: { 1337 char const *s; 1338 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd; 1339 1340 if (cmd->opcode == O_XMIT) 1341 s = "xmit"; 1342 else if (cmd->opcode == O_RECV) 1343 s = "recv"; 1344 else /* if (cmd->opcode == O_VIA) */ 1345 s = "via"; 1346 if (cmdif->name[0] == '\0') 1347 printf(" %s %s", s, 1348 inet_ntoa(cmdif->p.ip)); 1349 printf(" %s %s", s, cmdif->name); 1350 } 1351 break; 1352 1353 case O_IPID: 1354 if (F_LEN(cmd) == 1) 1355 printf(" ipid %u", cmd->arg1 ); 1356 else 1357 print_newports((ipfw_insn_u16 *)cmd, 0, 1358 O_IPID); 1359 break; 1360 1361 case O_IPTTL: 1362 if (F_LEN(cmd) == 1) 1363 printf(" ipttl %u", cmd->arg1 ); 1364 else 1365 print_newports((ipfw_insn_u16 *)cmd, 0, 1366 O_IPTTL); 1367 break; 1368 1369 case O_IPVER: 1370 printf(" ipver %u", cmd->arg1 ); 1371 break; 1372 1373 case O_IPPRECEDENCE: 1374 printf(" ipprecedence %u", (cmd->arg1) >> 5 ); 1375 break; 1376 1377 case O_IPLEN: 1378 if (F_LEN(cmd) == 1) 1379 printf(" iplen %u", cmd->arg1 ); 1380 else 1381 print_newports((ipfw_insn_u16 *)cmd, 0, 1382 O_IPLEN); 1383 break; 1384 1385 case O_IPOPT: 1386 print_flags("ipoptions", cmd, f_ipopts); 1387 break; 1388 1389 case O_IPTOS: 1390 print_flags("iptos", cmd, f_iptos); 1391 break; 1392 1393 case O_ICMPTYPE: 1394 print_icmptypes((ipfw_insn_u32 *)cmd); 1395 break; 1396 1397 case O_ESTAB: 1398 printf(" established"); 1399 break; 1400 1401 case O_TCPDATALEN: 1402 if (F_LEN(cmd) == 1) 1403 printf(" tcpdatalen %u", cmd->arg1 ); 1404 else 1405 print_newports((ipfw_insn_u16 *)cmd, 0, 1406 O_TCPDATALEN); 1407 break; 1408 1409 case O_TCPFLAGS: 1410 print_flags("tcpflags", cmd, f_tcpflags); 1411 break; 1412 1413 case O_TCPOPTS: 1414 print_flags("tcpoptions", cmd, f_tcpopts); 1415 break; 1416 1417 case O_TCPWIN: 1418 printf(" tcpwin %d", ntohs(cmd->arg1)); 1419 break; 1420 1421 case O_TCPACK: 1422 printf(" tcpack %d", ntohl(cmd32->d[0])); 1423 break; 1424 1425 case O_TCPSEQ: 1426 printf(" tcpseq %d", ntohl(cmd32->d[0])); 1427 break; 1428 1429 case O_UID: 1430 { 1431 struct passwd *pwd = getpwuid(cmd32->d[0]); 1432 1433 if (pwd) 1434 printf(" uid %s", pwd->pw_name); 1435 else 1436 printf(" uid %u", cmd32->d[0]); 1437 } 1438 break; 1439 1440 case O_GID: 1441 { 1442 struct group *grp = getgrgid(cmd32->d[0]); 1443 1444 if (grp) 1445 printf(" gid %s", grp->gr_name); 1446 else 1447 printf(" gid %u", cmd32->d[0]); 1448 } 1449 break; 1450 1451 case O_JAIL: 1452 printf(" jail %d", cmd32->d[0]); 1453 break; 1454 1455 case O_VERREVPATH: 1456 printf(" verrevpath"); 1457 break; 1458 1459 case O_VERSRCREACH: 1460 printf(" versrcreach"); 1461 break; 1462 1463 case O_ANTISPOOF: 1464 printf(" antispoof"); 1465 break; 1466 1467 case O_IPSEC: 1468 printf(" ipsec"); 1469 break; 1470 1471 case O_NOP: 1472 comment = (char *)(cmd + 1); 1473 break; 1474 1475 case O_KEEP_STATE: 1476 printf(" keep-state"); 1477 break; 1478 1479 case O_LIMIT: 1480 { 1481 struct _s_x *p = limit_masks; 1482 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 1483 uint8_t x = c->limit_mask; 1484 char const *comma = " "; 1485 1486 printf(" limit"); 1487 for (; p->x != 0 ; p++) 1488 if ((x & p->x) == p->x) { 1489 x &= ~p->x; 1490 printf("%s%s", comma, p->s); 1491 comma = ","; 1492 } 1493 printf(" %d", c->conn_limit); 1494 } 1495 break; 1496 1497 default: 1498 printf(" [opcode %d len %d]", 1499 cmd->opcode, cmd->len); 1500 } 1501 } 1502 if (cmd->len & F_OR) { 1503 printf(" or"); 1504 or_block = 1; 1505 } else if (or_block) { 1506 printf(" }"); 1507 or_block = 0; 1508 } 1509 } 1510 show_prerequisites(&flags, HAVE_IP, 0); 1511 if (comment) 1512 printf(" // %s", comment); 1513 printf("\n"); 1514 } 1515 1516 static void 1517 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth) 1518 { 1519 struct protoent *pe; 1520 struct in_addr a; 1521 uint16_t rulenum; 1522 1523 if (!do_expired) { 1524 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT)) 1525 return; 1526 } 1527 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 1528 printf("%05d", rulenum); 1529 if (pcwidth>0 || bcwidth>0) 1530 printf(" %*llu %*llu (%ds)", pcwidth, 1531 align_uint64(&d->pcnt), bcwidth, 1532 align_uint64(&d->bcnt), d->expire); 1533 switch (d->dyn_type) { 1534 case O_LIMIT_PARENT: 1535 printf(" PARENT %d", d->count); 1536 break; 1537 case O_LIMIT: 1538 printf(" LIMIT"); 1539 break; 1540 case O_KEEP_STATE: /* bidir, no mask */ 1541 printf(" STATE"); 1542 break; 1543 } 1544 1545 if ((pe = getprotobynumber(d->id.proto)) != NULL) 1546 printf(" %s", pe->p_name); 1547 else 1548 printf(" proto %u", d->id.proto); 1549 1550 a.s_addr = htonl(d->id.src_ip); 1551 printf(" %s %d", inet_ntoa(a), d->id.src_port); 1552 1553 a.s_addr = htonl(d->id.dst_ip); 1554 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port); 1555 printf("\n"); 1556 } 1557 1558 static int 1559 sort_q(const void *pa, const void *pb) 1560 { 1561 int rev = (do_sort < 0); 1562 int field = rev ? -do_sort : do_sort; 1563 long long res = 0; 1564 const struct dn_flow_queue *a = pa; 1565 const struct dn_flow_queue *b = pb; 1566 1567 switch (field) { 1568 case 1: /* pkts */ 1569 res = a->len - b->len; 1570 break; 1571 case 2: /* bytes */ 1572 res = a->len_bytes - b->len_bytes; 1573 break; 1574 1575 case 3: /* tot pkts */ 1576 res = a->tot_pkts - b->tot_pkts; 1577 break; 1578 1579 case 4: /* tot bytes */ 1580 res = a->tot_bytes - b->tot_bytes; 1581 break; 1582 } 1583 if (res < 0) 1584 res = -1; 1585 if (res > 0) 1586 res = 1; 1587 return (int)(rev ? res : -res); 1588 } 1589 1590 static void 1591 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q) 1592 { 1593 int l; 1594 1595 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n", 1596 fs->flow_mask.proto, 1597 fs->flow_mask.src_ip, fs->flow_mask.src_port, 1598 fs->flow_mask.dst_ip, fs->flow_mask.dst_port); 1599 if (fs->rq_elements == 0) 1600 return; 1601 1602 printf("BKT Prot ___Source IP/port____ " 1603 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n"); 1604 if (do_sort != 0) 1605 heapsort(q, fs->rq_elements, sizeof *q, sort_q); 1606 for (l = 0; l < fs->rq_elements; l++) { 1607 struct in_addr ina; 1608 struct protoent *pe; 1609 1610 ina.s_addr = htonl(q[l].id.src_ip); 1611 printf("%3d ", q[l].hash_slot); 1612 pe = getprotobynumber(q[l].id.proto); 1613 if (pe) 1614 printf("%-4s ", pe->p_name); 1615 else 1616 printf("%4u ", q[l].id.proto); 1617 printf("%15s/%-5d ", 1618 inet_ntoa(ina), q[l].id.src_port); 1619 ina.s_addr = htonl(q[l].id.dst_ip); 1620 printf("%15s/%-5d ", 1621 inet_ntoa(ina), q[l].id.dst_port); 1622 printf("%4qu %8qu %2u %4u %3u\n", 1623 q[l].tot_pkts, q[l].tot_bytes, 1624 q[l].len, q[l].len_bytes, q[l].drops); 1625 if (verbose) 1626 printf(" S %20qd F %20qd\n", 1627 q[l].S, q[l].F); 1628 } 1629 } 1630 1631 static void 1632 print_flowset_parms(struct dn_flow_set *fs, char *prefix) 1633 { 1634 int l; 1635 char qs[30]; 1636 char plr[30]; 1637 char red[90]; /* Display RED parameters */ 1638 1639 l = fs->qsize; 1640 if (fs->flags_fs & DN_QSIZE_IS_BYTES) { 1641 if (l >= 8192) 1642 sprintf(qs, "%d KB", l / 1024); 1643 else 1644 sprintf(qs, "%d B", l); 1645 } else 1646 sprintf(qs, "%3d sl.", l); 1647 if (fs->plr) 1648 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff)); 1649 else 1650 plr[0] = '\0'; 1651 if (fs->flags_fs & DN_IS_RED) /* RED parameters */ 1652 sprintf(red, 1653 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f", 1654 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ', 1655 1.0 * fs->w_q / (double)(1 << SCALE_RED), 1656 SCALE_VAL(fs->min_th), 1657 SCALE_VAL(fs->max_th), 1658 1.0 * fs->max_p / (double)(1 << SCALE_RED)); 1659 else 1660 sprintf(red, "droptail"); 1661 1662 printf("%s %s%s %d queues (%d buckets) %s\n", 1663 prefix, qs, plr, fs->rq_elements, fs->rq_size, red); 1664 } 1665 1666 static void 1667 list_pipes(void *data, uint nbytes, int ac, char *av[]) 1668 { 1669 int rulenum; 1670 void *next = data; 1671 struct dn_pipe *p = (struct dn_pipe *) data; 1672 struct dn_flow_set *fs; 1673 struct dn_flow_queue *q; 1674 int l; 1675 1676 if (ac > 0) 1677 rulenum = strtoul(*av++, NULL, 10); 1678 else 1679 rulenum = 0; 1680 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) { 1681 double b = p->bandwidth; 1682 char buf[30]; 1683 char prefix[80]; 1684 1685 if (p->next != (struct dn_pipe *)DN_IS_PIPE) 1686 break; /* done with pipes, now queues */ 1687 1688 /* 1689 * compute length, as pipe have variable size 1690 */ 1691 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q); 1692 next = (char *)p + l; 1693 nbytes -= l; 1694 1695 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2) 1696 continue; 1697 1698 /* 1699 * Print rate (or clocking interface) 1700 */ 1701 if (p->if_name[0] != '\0') 1702 sprintf(buf, "%s", p->if_name); 1703 else if (b == 0) 1704 sprintf(buf, "unlimited"); 1705 else if (b >= 1000000) 1706 sprintf(buf, "%7.3f Mbit/s", b/1000000); 1707 else if (b >= 1000) 1708 sprintf(buf, "%7.3f Kbit/s", b/1000); 1709 else 1710 sprintf(buf, "%7.3f bit/s ", b); 1711 1712 sprintf(prefix, "%05d: %s %4d ms ", 1713 p->pipe_nr, buf, p->delay); 1714 print_flowset_parms(&(p->fs), prefix); 1715 if (verbose) 1716 printf(" V %20qd\n", p->V >> MY_M); 1717 1718 q = (struct dn_flow_queue *)(p+1); 1719 list_queues(&(p->fs), q); 1720 } 1721 for (fs = next; nbytes >= sizeof *fs; fs = next) { 1722 char prefix[80]; 1723 1724 if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE) 1725 break; 1726 l = sizeof(*fs) + fs->rq_elements * sizeof(*q); 1727 next = (char *)fs + l; 1728 nbytes -= l; 1729 1730 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) || 1731 (rulenum != fs->parent_nr && do_pipe == 1))) { 1732 continue; 1733 } 1734 1735 q = (struct dn_flow_queue *)(fs+1); 1736 sprintf(prefix, "q%05d: weight %d pipe %d ", 1737 fs->fs_nr, fs->weight, fs->parent_nr); 1738 print_flowset_parms(fs, prefix); 1739 list_queues(fs, q); 1740 } 1741 } 1742 1743 /* 1744 * This one handles all set-related commands 1745 * ipfw set { show | enable | disable } 1746 * ipfw set swap X Y 1747 * ipfw set move X to Y 1748 * ipfw set move rule X to Y 1749 */ 1750 static void 1751 sets_handler(int ac, char *av[]) 1752 { 1753 uint32_t set_disable, masks[2]; 1754 int i, nbytes; 1755 uint16_t rulenum; 1756 uint8_t cmd, new_set; 1757 1758 ac--; 1759 av++; 1760 1761 if (!ac) 1762 errx(EX_USAGE, "set needs command"); 1763 if (!strncmp(*av, "show", strlen(*av)) ) { 1764 void *data; 1765 char const *msg; 1766 1767 nbytes = sizeof(struct ip_fw); 1768 if ((data = calloc(1, nbytes)) == NULL) 1769 err(EX_OSERR, "calloc"); 1770 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0) 1771 err(EX_OSERR, "getsockopt(IP_FW_GET)"); 1772 bcopy(&((struct ip_fw *)data)->next_rule, 1773 &set_disable, sizeof(set_disable)); 1774 1775 for (i = 0, msg = "disable" ; i < RESVD_SET; i++) 1776 if ((set_disable & (1<<i))) { 1777 printf("%s %d", msg, i); 1778 msg = ""; 1779 } 1780 msg = (set_disable) ? " enable" : "enable"; 1781 for (i = 0; i < RESVD_SET; i++) 1782 if (!(set_disable & (1<<i))) { 1783 printf("%s %d", msg, i); 1784 msg = ""; 1785 } 1786 printf("\n"); 1787 } else if (!strncmp(*av, "swap", strlen(*av))) { 1788 ac--; av++; 1789 if (ac != 2) 1790 errx(EX_USAGE, "set swap needs 2 set numbers\n"); 1791 rulenum = atoi(av[0]); 1792 new_set = atoi(av[1]); 1793 if (!isdigit(*(av[0])) || rulenum > RESVD_SET) 1794 errx(EX_DATAERR, "invalid set number %s\n", av[0]); 1795 if (!isdigit(*(av[1])) || new_set > RESVD_SET) 1796 errx(EX_DATAERR, "invalid set number %s\n", av[1]); 1797 masks[0] = (4 << 24) | (new_set << 16) | (rulenum); 1798 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 1799 } else if (!strncmp(*av, "move", strlen(*av))) { 1800 ac--; av++; 1801 if (ac && !strncmp(*av, "rule", strlen(*av))) { 1802 cmd = 2; 1803 ac--; av++; 1804 } else 1805 cmd = 3; 1806 if (ac != 3 || strncmp(av[1], "to", strlen(*av))) 1807 errx(EX_USAGE, "syntax: set move [rule] X to Y\n"); 1808 rulenum = atoi(av[0]); 1809 new_set = atoi(av[2]); 1810 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) || 1811 (cmd == 2 && rulenum == 65535) ) 1812 errx(EX_DATAERR, "invalid source number %s\n", av[0]); 1813 if (!isdigit(*(av[2])) || new_set > RESVD_SET) 1814 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]); 1815 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum); 1816 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 1817 } else if (!strncmp(*av, "disable", strlen(*av)) || 1818 !strncmp(*av, "enable", strlen(*av)) ) { 1819 int which = !strncmp(*av, "enable", strlen(*av)) ? 1 : 0; 1820 1821 ac--; av++; 1822 masks[0] = masks[1] = 0; 1823 1824 while (ac) { 1825 if (isdigit(**av)) { 1826 i = atoi(*av); 1827 if (i < 0 || i > RESVD_SET) 1828 errx(EX_DATAERR, 1829 "invalid set number %d\n", i); 1830 masks[which] |= (1<<i); 1831 } else if (!strncmp(*av, "disable", strlen(*av))) 1832 which = 0; 1833 else if (!strncmp(*av, "enable", strlen(*av))) 1834 which = 1; 1835 else 1836 errx(EX_DATAERR, 1837 "invalid set command %s\n", *av); 1838 av++; ac--; 1839 } 1840 if ( (masks[0] & masks[1]) != 0 ) 1841 errx(EX_DATAERR, 1842 "cannot enable and disable the same set\n"); 1843 1844 i = do_cmd(IP_FW_DEL, masks, sizeof(masks)); 1845 if (i) 1846 warn("set enable/disable: setsockopt(IP_FW_DEL)"); 1847 } else 1848 errx(EX_USAGE, "invalid set command %s\n", *av); 1849 } 1850 1851 static void 1852 sysctl_handler(int ac, char *av[], int which) 1853 { 1854 ac--; 1855 av++; 1856 1857 if (ac == 0) { 1858 warnx("missing keyword to enable/disable\n"); 1859 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) { 1860 sysctlbyname("net.inet.ip.fw.enable", NULL, 0, 1861 &which, sizeof(which)); 1862 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) { 1863 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0, 1864 &which, sizeof(which)); 1865 } else if (strncmp(*av, "debug", strlen(*av)) == 0) { 1866 sysctlbyname("net.inet.ip.fw.debug", NULL, 0, 1867 &which, sizeof(which)); 1868 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) { 1869 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0, 1870 &which, sizeof(which)); 1871 } else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) { 1872 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0, 1873 &which, sizeof(which)); 1874 } else if (strncmp(*av, "altq", strlen(*av)) == 0) { 1875 altq_set_enabled(which); 1876 } else { 1877 warnx("unrecognize enable/disable keyword: %s\n", *av); 1878 } 1879 } 1880 1881 static void 1882 list(int ac, char *av[], int show_counters) 1883 { 1884 struct ip_fw *r; 1885 ipfw_dyn_rule *dynrules, *d; 1886 1887 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r))) 1888 char *lim; 1889 void *data = NULL; 1890 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width; 1891 int exitval = EX_OK; 1892 int lac; 1893 char **lav; 1894 u_long rnum, last; 1895 char *endptr; 1896 int seen = 0; 1897 1898 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET; 1899 int nalloc = 1024; /* start somewhere... */ 1900 1901 last = 0; 1902 1903 if (test_only) { 1904 fprintf(stderr, "Testing only, list disabled\n"); 1905 return; 1906 } 1907 1908 ac--; 1909 av++; 1910 1911 /* get rules or pipes from kernel, resizing array as necessary */ 1912 nbytes = nalloc; 1913 1914 while (nbytes >= nalloc) { 1915 nalloc = nalloc * 2 + 200; 1916 nbytes = nalloc; 1917 if ((data = realloc(data, nbytes)) == NULL) 1918 err(EX_OSERR, "realloc"); 1919 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0) 1920 err(EX_OSERR, "getsockopt(IP_%s_GET)", 1921 do_pipe ? "DUMMYNET" : "FW"); 1922 } 1923 1924 if (do_pipe) { 1925 list_pipes(data, nbytes, ac, av); 1926 goto done; 1927 } 1928 1929 /* 1930 * Count static rules. They have variable size so we 1931 * need to scan the list to count them. 1932 */ 1933 for (nstat = 1, r = data, lim = (char *)data + nbytes; 1934 r->rulenum < 65535 && (char *)r < lim; 1935 ++nstat, r = NEXT(r) ) 1936 ; /* nothing */ 1937 1938 /* 1939 * Count dynamic rules. This is easier as they have 1940 * fixed size. 1941 */ 1942 r = NEXT(r); 1943 dynrules = (ipfw_dyn_rule *)r ; 1944 n = (char *)r - (char *)data; 1945 ndyn = (nbytes - n) / sizeof *dynrules; 1946 1947 /* if showing stats, figure out column widths ahead of time */ 1948 bcwidth = pcwidth = 0; 1949 if (show_counters) { 1950 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) { 1951 /* packet counter */ 1952 width = snprintf(NULL, 0, "%llu", 1953 align_uint64(&r->pcnt)); 1954 if (width > pcwidth) 1955 pcwidth = width; 1956 1957 /* byte counter */ 1958 width = snprintf(NULL, 0, "%llu", 1959 align_uint64(&r->bcnt)); 1960 if (width > bcwidth) 1961 bcwidth = width; 1962 } 1963 } 1964 if (do_dynamic && ndyn) { 1965 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 1966 width = snprintf(NULL, 0, "%llu", 1967 align_uint64(&d->pcnt)); 1968 if (width > pcwidth) 1969 pcwidth = width; 1970 1971 width = snprintf(NULL, 0, "%llu", 1972 align_uint64(&d->bcnt)); 1973 if (width > bcwidth) 1974 bcwidth = width; 1975 } 1976 } 1977 /* if no rule numbers were specified, list all rules */ 1978 if (ac == 0) { 1979 for (n = 0, r = data; n < nstat; n++, r = NEXT(r) ) 1980 show_ipfw(r, pcwidth, bcwidth); 1981 1982 if (do_dynamic && ndyn) { 1983 printf("## Dynamic rules (%d):\n", ndyn); 1984 for (n = 0, d = dynrules; n < ndyn; n++, d++) 1985 show_dyn_ipfw(d, pcwidth, bcwidth); 1986 } 1987 goto done; 1988 } 1989 1990 /* display specific rules requested on command line */ 1991 1992 for (lac = ac, lav = av; lac != 0; lac--) { 1993 /* convert command line rule # */ 1994 last = rnum = strtoul(*lav++, &endptr, 10); 1995 if (*endptr == '-') 1996 last = strtoul(endptr+1, &endptr, 10); 1997 if (*endptr) { 1998 exitval = EX_USAGE; 1999 warnx("invalid rule number: %s", *(lav - 1)); 2000 continue; 2001 } 2002 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) { 2003 if (r->rulenum > last) 2004 break; 2005 if (r->rulenum >= rnum && r->rulenum <= last) { 2006 show_ipfw(r, pcwidth, bcwidth); 2007 seen = 1; 2008 } 2009 } 2010 if (!seen) { 2011 /* give precedence to other error(s) */ 2012 if (exitval == EX_OK) 2013 exitval = EX_UNAVAILABLE; 2014 warnx("rule %lu does not exist", rnum); 2015 } 2016 } 2017 2018 if (do_dynamic && ndyn) { 2019 printf("## Dynamic rules:\n"); 2020 for (lac = ac, lav = av; lac != 0; lac--) { 2021 rnum = strtoul(*lav++, &endptr, 10); 2022 if (*endptr == '-') 2023 last = strtoul(endptr+1, &endptr, 10); 2024 if (*endptr) 2025 /* already warned */ 2026 continue; 2027 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 2028 uint16_t rulenum; 2029 2030 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 2031 if (rulenum > rnum) 2032 break; 2033 if (r->rulenum >= rnum && r->rulenum <= last) 2034 show_dyn_ipfw(d, pcwidth, bcwidth); 2035 } 2036 } 2037 } 2038 2039 ac = 0; 2040 2041 done: 2042 free(data); 2043 2044 if (exitval != EX_OK) 2045 exit(exitval); 2046 #undef NEXT 2047 } 2048 2049 static void 2050 show_usage(void) 2051 { 2052 fprintf(stderr, "usage: ipfw [options]\n" 2053 "do \"ipfw -h\" or see ipfw manpage for details\n" 2054 ); 2055 exit(EX_USAGE); 2056 } 2057 2058 static void 2059 help(void) 2060 { 2061 fprintf(stderr, 2062 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n" 2063 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n" 2064 "add [num] [set N] [prob x] RULE-BODY\n" 2065 "{pipe|queue} N config PIPE-BODY\n" 2066 "[pipe|queue] {zero|delete|show} [N{,N}]\n" 2067 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n" 2068 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n" 2069 "\n" 2070 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n" 2071 "ACTION: check-state | allow | count | deny | reject | skipto N |\n" 2072 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n" 2073 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n" 2074 "ADDR: [ MAC dst src ether_type ] \n" 2075 " [ from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n" 2076 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n" 2077 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n" 2078 "OPTION_LIST: OPTION [OPTION_LIST]\n" 2079 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n" 2080 " {dst-ip|src-ip} ADDR | {dst-port|src-port} LIST |\n" 2081 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n" 2082 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n" 2083 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n" 2084 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n" 2085 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n" 2086 " verrevpath | versrcreach | antispoof\n" 2087 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n" 2088 ); 2089 exit(0); 2090 } 2091 2092 2093 static int 2094 lookup_host (char *host, struct in_addr *ipaddr) 2095 { 2096 struct hostent *he; 2097 2098 if (!inet_aton(host, ipaddr)) { 2099 if ((he = gethostbyname(host)) == NULL) 2100 return(-1); 2101 *ipaddr = *(struct in_addr *)he->h_addr_list[0]; 2102 } 2103 return(0); 2104 } 2105 2106 /* 2107 * fills the addr and mask fields in the instruction as appropriate from av. 2108 * Update length as appropriate. 2109 * The following formats are allowed: 2110 * any matches any IP. Actually returns an empty instruction. 2111 * me returns O_IP_*_ME 2112 * 1.2.3.4 single IP address 2113 * 1.2.3.4:5.6.7.8 address:mask 2114 * 1.2.3.4/24 address/mask 2115 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet 2116 * We can have multiple comma-separated address/mask entries. 2117 */ 2118 static void 2119 fill_ip(ipfw_insn_ip *cmd, char *av) 2120 { 2121 int len = 0; 2122 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d; 2123 2124 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 2125 2126 if (!strncmp(av, "any", strlen(av))) 2127 return; 2128 2129 if (!strncmp(av, "me", strlen(av))) { 2130 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2131 return; 2132 } 2133 2134 if (!strncmp(av, "table(", 6)) { 2135 char *p = strchr(av + 6, ','); 2136 2137 if (p) 2138 *p++ = '\0'; 2139 cmd->o.opcode = O_IP_DST_LOOKUP; 2140 cmd->o.arg1 = strtoul(av + 6, NULL, 0); 2141 if (p) { 2142 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2143 d[0] = strtoul(p, NULL, 0); 2144 } else 2145 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2146 return; 2147 } 2148 2149 while (av) { 2150 /* 2151 * After the address we can have '/' or ':' indicating a mask, 2152 * ',' indicating another address follows, '{' indicating a 2153 * set of addresses of unspecified size. 2154 */ 2155 char *p = strpbrk(av, "/:,{"); 2156 int masklen; 2157 char md; 2158 2159 if (p) { 2160 md = *p; 2161 *p++ = '\0'; 2162 } else 2163 md = '\0'; 2164 2165 if (lookup_host(av, (struct in_addr *)&d[0]) != 0) 2166 errx(EX_NOHOST, "hostname ``%s'' unknown", av); 2167 switch (md) { 2168 case ':': 2169 if (!inet_aton(p, (struct in_addr *)&d[1])) 2170 errx(EX_DATAERR, "bad netmask ``%s''", p); 2171 break; 2172 case '/': 2173 masklen = atoi(p); 2174 if (masklen == 0) 2175 d[1] = htonl(0); /* mask */ 2176 else if (masklen > 32) 2177 errx(EX_DATAERR, "bad width ``%s''", p); 2178 else 2179 d[1] = htonl(~0 << (32 - masklen)); 2180 break; 2181 case '{': /* no mask, assume /24 and put back the '{' */ 2182 d[1] = htonl(~0 << (32 - 24)); 2183 *(--p) = md; 2184 break; 2185 2186 case ',': /* single address plus continuation */ 2187 *(--p) = md; 2188 /* FALLTHROUGH */ 2189 case 0: /* initialization value */ 2190 default: 2191 d[1] = htonl(~0); /* force /32 */ 2192 break; 2193 } 2194 d[0] &= d[1]; /* mask base address with mask */ 2195 /* find next separator */ 2196 if (p) 2197 p = strpbrk(p, ",{"); 2198 if (p && *p == '{') { 2199 /* 2200 * We have a set of addresses. They are stored as follows: 2201 * arg1 is the set size (powers of 2, 2..256) 2202 * addr is the base address IN HOST FORMAT 2203 * mask.. is an array of arg1 bits (rounded up to 2204 * the next multiple of 32) with bits set 2205 * for each host in the map. 2206 */ 2207 uint32_t *map = (uint32_t *)&cmd->mask; 2208 int low, high; 2209 int i = contigmask((uint8_t *)&(d[1]), 32); 2210 2211 if (len > 0) 2212 errx(EX_DATAERR, "address set cannot be in a list"); 2213 if (i < 24 || i > 31) 2214 errx(EX_DATAERR, "invalid set with mask %d\n", i); 2215 cmd->o.arg1 = 1<<(32-i); /* map length */ 2216 d[0] = ntohl(d[0]); /* base addr in host format */ 2217 cmd->o.opcode = O_IP_DST_SET; /* default */ 2218 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32; 2219 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++) 2220 map[i] = 0; /* clear map */ 2221 2222 av = p + 1; 2223 low = d[0] & 0xff; 2224 high = low + cmd->o.arg1 - 1; 2225 /* 2226 * Here, i stores the previous value when we specify a range 2227 * of addresses within a mask, e.g. 45-63. i = -1 means we 2228 * have no previous value. 2229 */ 2230 i = -1; /* previous value in a range */ 2231 while (isdigit(*av)) { 2232 char *s; 2233 int a = strtol(av, &s, 0); 2234 2235 if (s == av) { /* no parameter */ 2236 if (*av != '}') 2237 errx(EX_DATAERR, "set not closed\n"); 2238 if (i != -1) 2239 errx(EX_DATAERR, "incomplete range %d-", i); 2240 break; 2241 } 2242 if (a < low || a > high) 2243 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n", 2244 a, low, high); 2245 a -= low; 2246 if (i == -1) /* no previous in range */ 2247 i = a; 2248 else { /* check that range is valid */ 2249 if (i > a) 2250 errx(EX_DATAERR, "invalid range %d-%d", 2251 i+low, a+low); 2252 if (*s == '-') 2253 errx(EX_DATAERR, "double '-' in range"); 2254 } 2255 for (; i <= a; i++) 2256 map[i/32] |= 1<<(i & 31); 2257 i = -1; 2258 if (*s == '-') 2259 i = a; 2260 else if (*s == '}') 2261 break; 2262 av = s+1; 2263 } 2264 return; 2265 } 2266 av = p; 2267 if (av) /* then *av must be a ',' */ 2268 av++; 2269 2270 /* Check this entry */ 2271 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */ 2272 /* 2273 * 'any' turns the entire list into a NOP. 2274 * 'not any' never matches, so it is removed from the 2275 * list unless it is the only item, in which case we 2276 * report an error. 2277 */ 2278 if (cmd->o.len & F_NOT) { /* "not any" never matches */ 2279 if (av == NULL && len == 0) /* only this entry */ 2280 errx(EX_DATAERR, "not any never matches"); 2281 } 2282 /* else do nothing and skip this entry */ 2283 return; 2284 } 2285 /* A single IP can be stored in an optimized format */ 2286 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) { 2287 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2288 return; 2289 } 2290 len += 2; /* two words... */ 2291 d += 2; 2292 } /* end while */ 2293 cmd->o.len |= len+1; 2294 } 2295 2296 2297 /* 2298 * helper function to process a set of flags and set bits in the 2299 * appropriate masks. 2300 */ 2301 static void 2302 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode, 2303 struct _s_x *flags, char *p) 2304 { 2305 uint8_t set=0, clear=0; 2306 2307 while (p && *p) { 2308 char *q; /* points to the separator */ 2309 int val; 2310 uint8_t *which; /* mask we are working on */ 2311 2312 if (*p == '!') { 2313 p++; 2314 which = &clear; 2315 } else 2316 which = &set; 2317 q = strchr(p, ','); 2318 if (q) 2319 *q++ = '\0'; 2320 val = match_token(flags, p); 2321 if (val <= 0) 2322 errx(EX_DATAERR, "invalid flag %s", p); 2323 *which |= (uint8_t)val; 2324 p = q; 2325 } 2326 cmd->opcode = opcode; 2327 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1; 2328 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8); 2329 } 2330 2331 2332 static void 2333 delete(int ac, char *av[]) 2334 { 2335 uint32_t rulenum; 2336 struct dn_pipe p; 2337 int i; 2338 int exitval = EX_OK; 2339 int do_set = 0; 2340 2341 memset(&p, 0, sizeof p); 2342 2343 av++; ac--; 2344 NEED1("missing rule specification"); 2345 if (ac > 0 && !strncmp(*av, "set", strlen(*av))) { 2346 do_set = 1; /* delete set */ 2347 ac--; av++; 2348 } 2349 2350 /* Rule number */ 2351 while (ac && isdigit(**av)) { 2352 i = atoi(*av); av++; ac--; 2353 if (do_pipe) { 2354 if (do_pipe == 1) 2355 p.pipe_nr = i; 2356 else 2357 p.fs.fs_nr = i; 2358 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p); 2359 if (i) { 2360 exitval = 1; 2361 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", 2362 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr); 2363 } 2364 } else { 2365 rulenum = (i & 0xffff) | (do_set << 24); 2366 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum); 2367 if (i) { 2368 exitval = EX_UNAVAILABLE; 2369 warn("rule %u: setsockopt(IP_FW_DEL)", 2370 rulenum); 2371 } 2372 } 2373 } 2374 if (exitval != EX_OK) 2375 exit(exitval); 2376 } 2377 2378 2379 /* 2380 * fill the interface structure. We do not check the name as we can 2381 * create interfaces dynamically, so checking them at insert time 2382 * makes relatively little sense. 2383 * Interface names containing '*', '?', or '[' are assumed to be shell 2384 * patterns which match interfaces. 2385 */ 2386 static void 2387 fill_iface(ipfw_insn_if *cmd, char *arg) 2388 { 2389 cmd->name[0] = '\0'; 2390 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if); 2391 2392 /* Parse the interface or address */ 2393 if (!strcmp(arg, "any")) 2394 cmd->o.len = 0; /* effectively ignore this command */ 2395 else if (!isdigit(*arg)) { 2396 strlcpy(cmd->name, arg, sizeof(cmd->name)); 2397 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0; 2398 } else if (!inet_aton(arg, &cmd->p.ip)) 2399 errx(EX_DATAERR, "bad ip address ``%s''", arg); 2400 } 2401 2402 static void 2403 config_pipe(int ac, char **av) 2404 { 2405 struct dn_pipe p; 2406 int i; 2407 char *end; 2408 uint32_t a; 2409 void *par = NULL; 2410 2411 memset(&p, 0, sizeof p); 2412 2413 av++; ac--; 2414 /* Pipe number */ 2415 if (ac && isdigit(**av)) { 2416 i = atoi(*av); av++; ac--; 2417 if (do_pipe == 1) 2418 p.pipe_nr = i; 2419 else 2420 p.fs.fs_nr = i; 2421 } 2422 while (ac > 0) { 2423 double d; 2424 int tok = match_token(dummynet_params, *av); 2425 ac--; av++; 2426 2427 switch(tok) { 2428 case TOK_NOERROR: 2429 p.fs.flags_fs |= DN_NOERROR; 2430 break; 2431 2432 case TOK_PLR: 2433 NEED1("plr needs argument 0..1\n"); 2434 d = strtod(av[0], NULL); 2435 if (d > 1) 2436 d = 1; 2437 else if (d < 0) 2438 d = 0; 2439 p.fs.plr = (int)(d*0x7fffffff); 2440 ac--; av++; 2441 break; 2442 2443 case TOK_QUEUE: 2444 NEED1("queue needs queue size\n"); 2445 end = NULL; 2446 p.fs.qsize = strtoul(av[0], &end, 0); 2447 if (*end == 'K' || *end == 'k') { 2448 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 2449 p.fs.qsize *= 1024; 2450 } else if (*end == 'B' || !strncmp(end, "by", 2)) { 2451 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 2452 } 2453 ac--; av++; 2454 break; 2455 2456 case TOK_BUCKETS: 2457 NEED1("buckets needs argument\n"); 2458 p.fs.rq_size = strtoul(av[0], NULL, 0); 2459 ac--; av++; 2460 break; 2461 2462 case TOK_MASK: 2463 NEED1("mask needs mask specifier\n"); 2464 /* 2465 * per-flow queue, mask is dst_ip, dst_port, 2466 * src_ip, src_port, proto measured in bits 2467 */ 2468 par = NULL; 2469 2470 p.fs.flow_mask.dst_ip = 0; 2471 p.fs.flow_mask.src_ip = 0; 2472 p.fs.flow_mask.dst_port = 0; 2473 p.fs.flow_mask.src_port = 0; 2474 p.fs.flow_mask.proto = 0; 2475 end = NULL; 2476 2477 while (ac >= 1) { 2478 uint32_t *p32 = NULL; 2479 uint16_t *p16 = NULL; 2480 2481 tok = match_token(dummynet_params, *av); 2482 ac--; av++; 2483 switch(tok) { 2484 case TOK_ALL: 2485 /* 2486 * special case, all bits significant 2487 */ 2488 p.fs.flow_mask.dst_ip = ~0; 2489 p.fs.flow_mask.src_ip = ~0; 2490 p.fs.flow_mask.dst_port = ~0; 2491 p.fs.flow_mask.src_port = ~0; 2492 p.fs.flow_mask.proto = ~0; 2493 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 2494 goto end_mask; 2495 2496 case TOK_DSTIP: 2497 p32 = &p.fs.flow_mask.dst_ip; 2498 break; 2499 2500 case TOK_SRCIP: 2501 p32 = &p.fs.flow_mask.src_ip; 2502 break; 2503 2504 case TOK_DSTPORT: 2505 p16 = &p.fs.flow_mask.dst_port; 2506 break; 2507 2508 case TOK_SRCPORT: 2509 p16 = &p.fs.flow_mask.src_port; 2510 break; 2511 2512 case TOK_PROTO: 2513 break; 2514 2515 default: 2516 ac++; av--; /* backtrack */ 2517 goto end_mask; 2518 } 2519 if (ac < 1) 2520 errx(EX_USAGE, "mask: value missing"); 2521 if (*av[0] == '/') { 2522 a = strtoul(av[0]+1, &end, 0); 2523 a = (a == 32) ? ~0 : (1 << a) - 1; 2524 } else 2525 a = strtoul(av[0], &end, 0); 2526 if (p32 != NULL) 2527 *p32 = a; 2528 else if (p16 != NULL) { 2529 if (a > 65535) 2530 errx(EX_DATAERR, 2531 "mask: must be 16 bit"); 2532 *p16 = (uint16_t)a; 2533 } else { 2534 if (a > 255) 2535 errx(EX_DATAERR, 2536 "mask: must be 8 bit"); 2537 p.fs.flow_mask.proto = (uint8_t)a; 2538 } 2539 if (a != 0) 2540 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 2541 ac--; av++; 2542 } /* end while, config masks */ 2543 end_mask: 2544 break; 2545 2546 case TOK_RED: 2547 case TOK_GRED: 2548 NEED1("red/gred needs w_q/min_th/max_th/max_p\n"); 2549 p.fs.flags_fs |= DN_IS_RED; 2550 if (tok == TOK_GRED) 2551 p.fs.flags_fs |= DN_IS_GENTLE_RED; 2552 /* 2553 * the format for parameters is w_q/min_th/max_th/max_p 2554 */ 2555 if ((end = strsep(&av[0], "/"))) { 2556 double w_q = strtod(end, NULL); 2557 if (w_q > 1 || w_q <= 0) 2558 errx(EX_DATAERR, "0 < w_q <= 1"); 2559 p.fs.w_q = (int) (w_q * (1 << SCALE_RED)); 2560 } 2561 if ((end = strsep(&av[0], "/"))) { 2562 p.fs.min_th = strtoul(end, &end, 0); 2563 if (*end == 'K' || *end == 'k') 2564 p.fs.min_th *= 1024; 2565 } 2566 if ((end = strsep(&av[0], "/"))) { 2567 p.fs.max_th = strtoul(end, &end, 0); 2568 if (*end == 'K' || *end == 'k') 2569 p.fs.max_th *= 1024; 2570 } 2571 if ((end = strsep(&av[0], "/"))) { 2572 double max_p = strtod(end, NULL); 2573 if (max_p > 1 || max_p <= 0) 2574 errx(EX_DATAERR, "0 < max_p <= 1"); 2575 p.fs.max_p = (int)(max_p * (1 << SCALE_RED)); 2576 } 2577 ac--; av++; 2578 break; 2579 2580 case TOK_DROPTAIL: 2581 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED); 2582 break; 2583 2584 case TOK_BW: 2585 NEED1("bw needs bandwidth or interface\n"); 2586 if (do_pipe != 1) 2587 errx(EX_DATAERR, "bandwidth only valid for pipes"); 2588 /* 2589 * set clocking interface or bandwidth value 2590 */ 2591 if (av[0][0] >= 'a' && av[0][0] <= 'z') { 2592 int l = sizeof(p.if_name)-1; 2593 /* interface name */ 2594 strncpy(p.if_name, av[0], l); 2595 p.if_name[l] = '\0'; 2596 p.bandwidth = 0; 2597 } else { 2598 p.if_name[0] = '\0'; 2599 p.bandwidth = strtoul(av[0], &end, 0); 2600 if (*end == 'K' || *end == 'k') { 2601 end++; 2602 p.bandwidth *= 1000; 2603 } else if (*end == 'M') { 2604 end++; 2605 p.bandwidth *= 1000000; 2606 } 2607 if (*end == 'B' || !strncmp(end, "by", 2)) 2608 p.bandwidth *= 8; 2609 if (p.bandwidth < 0) 2610 errx(EX_DATAERR, "bandwidth too large"); 2611 } 2612 ac--; av++; 2613 break; 2614 2615 case TOK_DELAY: 2616 if (do_pipe != 1) 2617 errx(EX_DATAERR, "delay only valid for pipes"); 2618 NEED1("delay needs argument 0..10000ms\n"); 2619 p.delay = strtoul(av[0], NULL, 0); 2620 ac--; av++; 2621 break; 2622 2623 case TOK_WEIGHT: 2624 if (do_pipe == 1) 2625 errx(EX_DATAERR,"weight only valid for queues"); 2626 NEED1("weight needs argument 0..100\n"); 2627 p.fs.weight = strtoul(av[0], &end, 0); 2628 ac--; av++; 2629 break; 2630 2631 case TOK_PIPE: 2632 if (do_pipe == 1) 2633 errx(EX_DATAERR,"pipe only valid for queues"); 2634 NEED1("pipe needs pipe_number\n"); 2635 p.fs.parent_nr = strtoul(av[0], &end, 0); 2636 ac--; av++; 2637 break; 2638 2639 default: 2640 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]); 2641 } 2642 } 2643 if (do_pipe == 1) { 2644 if (p.pipe_nr == 0) 2645 errx(EX_DATAERR, "pipe_nr must be > 0"); 2646 if (p.delay > 10000) 2647 errx(EX_DATAERR, "delay must be < 10000"); 2648 } else { /* do_pipe == 2, queue */ 2649 if (p.fs.parent_nr == 0) 2650 errx(EX_DATAERR, "pipe must be > 0"); 2651 if (p.fs.weight >100) 2652 errx(EX_DATAERR, "weight must be <= 100"); 2653 } 2654 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) { 2655 if (p.fs.qsize > 1024*1024) 2656 errx(EX_DATAERR, "queue size must be < 1MB"); 2657 } else { 2658 if (p.fs.qsize > 100) 2659 errx(EX_DATAERR, "2 <= queue size <= 100"); 2660 } 2661 if (p.fs.flags_fs & DN_IS_RED) { 2662 size_t len; 2663 int lookup_depth, avg_pkt_size; 2664 double s, idle, weight, w_q; 2665 struct clockinfo ck; 2666 int t; 2667 2668 if (p.fs.min_th >= p.fs.max_th) 2669 errx(EX_DATAERR, "min_th %d must be < than max_th %d", 2670 p.fs.min_th, p.fs.max_th); 2671 if (p.fs.max_th == 0) 2672 errx(EX_DATAERR, "max_th must be > 0"); 2673 2674 len = sizeof(int); 2675 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth", 2676 &lookup_depth, &len, NULL, 0) == -1) 2677 2678 errx(1, "sysctlbyname(\"%s\")", 2679 "net.inet.ip.dummynet.red_lookup_depth"); 2680 if (lookup_depth == 0) 2681 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth" 2682 " must be greater than zero"); 2683 2684 len = sizeof(int); 2685 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size", 2686 &avg_pkt_size, &len, NULL, 0) == -1) 2687 2688 errx(1, "sysctlbyname(\"%s\")", 2689 "net.inet.ip.dummynet.red_avg_pkt_size"); 2690 if (avg_pkt_size == 0) 2691 errx(EX_DATAERR, 2692 "net.inet.ip.dummynet.red_avg_pkt_size must" 2693 " be greater than zero"); 2694 2695 len = sizeof(struct clockinfo); 2696 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1) 2697 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate"); 2698 2699 /* 2700 * Ticks needed for sending a medium-sized packet. 2701 * Unfortunately, when we are configuring a WF2Q+ queue, we 2702 * do not have bandwidth information, because that is stored 2703 * in the parent pipe, and also we have multiple queues 2704 * competing for it. So we set s=0, which is not very 2705 * correct. But on the other hand, why do we want RED with 2706 * WF2Q+ ? 2707 */ 2708 if (p.bandwidth==0) /* this is a WF2Q+ queue */ 2709 s = 0; 2710 else 2711 s = ck.hz * avg_pkt_size * 8 / p.bandwidth; 2712 2713 /* 2714 * max idle time (in ticks) before avg queue size becomes 0. 2715 * NOTA: (3/w_q) is approx the value x so that 2716 * (1-w_q)^x < 10^-3. 2717 */ 2718 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED); 2719 idle = s * 3. / w_q; 2720 p.fs.lookup_step = (int)idle / lookup_depth; 2721 if (!p.fs.lookup_step) 2722 p.fs.lookup_step = 1; 2723 weight = 1 - w_q; 2724 for (t = p.fs.lookup_step; t > 0; --t) 2725 weight *= weight; 2726 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED)); 2727 } 2728 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p); 2729 if (i) 2730 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE"); 2731 } 2732 2733 static void 2734 get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask) 2735 { 2736 int i, l; 2737 2738 for (i=0; i<6; i++) 2739 addr[i] = mask[i] = 0; 2740 if (!strcmp(p, "any")) 2741 return; 2742 2743 for (i=0; *p && i<6;i++, p++) { 2744 addr[i] = strtol(p, &p, 16); 2745 if (*p != ':') /* we start with the mask */ 2746 break; 2747 } 2748 if (*p == '/') { /* mask len */ 2749 l = strtol(p+1, &p, 0); 2750 for (i=0; l>0; l -=8, i++) 2751 mask[i] = (l >=8) ? 0xff : (~0) << (8-l); 2752 } else if (*p == '&') { /* mask */ 2753 for (i=0, p++; *p && i<6;i++, p++) { 2754 mask[i] = strtol(p, &p, 16); 2755 if (*p != ':') 2756 break; 2757 } 2758 } else if (*p == '\0') { 2759 for (i=0; i<6; i++) 2760 mask[i] = 0xff; 2761 } 2762 for (i=0; i<6; i++) 2763 addr[i] &= mask[i]; 2764 } 2765 2766 /* 2767 * helper function, updates the pointer to cmd with the length 2768 * of the current command, and also cleans up the first word of 2769 * the new command in case it has been clobbered before. 2770 */ 2771 static ipfw_insn * 2772 next_cmd(ipfw_insn *cmd) 2773 { 2774 cmd += F_LEN(cmd); 2775 bzero(cmd, sizeof(*cmd)); 2776 return cmd; 2777 } 2778 2779 /* 2780 * Takes arguments and copies them into a comment 2781 */ 2782 static void 2783 fill_comment(ipfw_insn *cmd, int ac, char **av) 2784 { 2785 int i, l; 2786 char *p = (char *)(cmd + 1); 2787 2788 cmd->opcode = O_NOP; 2789 cmd->len = (cmd->len & (F_NOT | F_OR)); 2790 2791 /* Compute length of comment string. */ 2792 for (i = 0, l = 0; i < ac; i++) 2793 l += strlen(av[i]) + 1; 2794 if (l == 0) 2795 return; 2796 if (l > 84) 2797 errx(EX_DATAERR, 2798 "comment too long (max 80 chars)"); 2799 l = 1 + (l+3)/4; 2800 cmd->len = (cmd->len & (F_NOT | F_OR)) | l; 2801 for (i = 0; i < ac; i++) { 2802 strcpy(p, av[i]); 2803 p += strlen(av[i]); 2804 *p++ = ' '; 2805 } 2806 *(--p) = '\0'; 2807 } 2808 2809 /* 2810 * A function to fill simple commands of size 1. 2811 * Existing flags are preserved. 2812 */ 2813 static void 2814 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg) 2815 { 2816 cmd->opcode = opcode; 2817 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1; 2818 cmd->arg1 = arg; 2819 } 2820 2821 /* 2822 * Fetch and add the MAC address and type, with masks. This generates one or 2823 * two microinstructions, and returns the pointer to the last one. 2824 */ 2825 static ipfw_insn * 2826 add_mac(ipfw_insn *cmd, int ac, char *av[]) 2827 { 2828 ipfw_insn_mac *mac; 2829 2830 if (ac < 2) 2831 errx(EX_DATAERR, "MAC dst src"); 2832 2833 cmd->opcode = O_MACADDR2; 2834 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac); 2835 2836 mac = (ipfw_insn_mac *)cmd; 2837 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */ 2838 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */ 2839 return cmd; 2840 } 2841 2842 static ipfw_insn * 2843 add_mactype(ipfw_insn *cmd, int ac, char *av) 2844 { 2845 if (ac < 1) 2846 errx(EX_DATAERR, "missing MAC type"); 2847 if (strcmp(av, "any") != 0) { /* we have a non-null type */ 2848 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE); 2849 cmd->opcode = O_MAC_TYPE; 2850 return cmd; 2851 } else 2852 return NULL; 2853 } 2854 2855 static ipfw_insn * 2856 add_proto(ipfw_insn *cmd, char *av) 2857 { 2858 struct protoent *pe; 2859 u_char proto = 0; 2860 2861 if (!strncmp(av, "all", strlen(av))) 2862 ; /* same as "ip" */ 2863 else if ((proto = atoi(av)) > 0) 2864 ; /* all done! */ 2865 else if ((pe = getprotobyname(av)) != NULL) 2866 proto = pe->p_proto; 2867 else 2868 return NULL; 2869 if (proto != IPPROTO_IP) 2870 fill_cmd(cmd, O_PROTO, 0, proto); 2871 return cmd; 2872 } 2873 2874 static ipfw_insn * 2875 add_srcip(ipfw_insn *cmd, char *av) 2876 { 2877 fill_ip((ipfw_insn_ip *)cmd, av); 2878 if (cmd->opcode == O_IP_DST_SET) /* set */ 2879 cmd->opcode = O_IP_SRC_SET; 2880 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 2881 cmd->opcode = O_IP_SRC_LOOKUP; 2882 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 2883 cmd->opcode = O_IP_SRC_ME; 2884 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 2885 cmd->opcode = O_IP_SRC; 2886 else /* addr/mask */ 2887 cmd->opcode = O_IP_SRC_MASK; 2888 return cmd; 2889 } 2890 2891 static ipfw_insn * 2892 add_dstip(ipfw_insn *cmd, char *av) 2893 { 2894 fill_ip((ipfw_insn_ip *)cmd, av); 2895 if (cmd->opcode == O_IP_DST_SET) /* set */ 2896 ; 2897 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 2898 ; 2899 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 2900 cmd->opcode = O_IP_DST_ME; 2901 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 2902 cmd->opcode = O_IP_DST; 2903 else /* addr/mask */ 2904 cmd->opcode = O_IP_DST_MASK; 2905 return cmd; 2906 } 2907 2908 static ipfw_insn * 2909 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode) 2910 { 2911 if (!strncmp(av, "any", strlen(av))) { 2912 return NULL; 2913 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) { 2914 /* XXX todo: check that we have a protocol with ports */ 2915 cmd->opcode = opcode; 2916 return cmd; 2917 } 2918 return NULL; 2919 } 2920 2921 /* 2922 * Parse arguments and assemble the microinstructions which make up a rule. 2923 * Rules are added into the 'rulebuf' and then copied in the correct order 2924 * into the actual rule. 2925 * 2926 * The syntax for a rule starts with the action, followed by 2927 * optional action parameters, and the various match patterns. 2928 * In the assembled microcode, the first opcode must be an O_PROBE_STATE 2929 * (generated if the rule includes a keep-state option), then the 2930 * various match patterns, log/altq actions, and the actual action. 2931 * 2932 */ 2933 static void 2934 add(int ac, char *av[]) 2935 { 2936 /* 2937 * rules are added into the 'rulebuf' and then copied in 2938 * the correct order into the actual rule. 2939 * Some things that need to go out of order (prob, action etc.) 2940 * go into actbuf[]. 2941 */ 2942 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255]; 2943 2944 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL; 2945 ipfw_insn *first_cmd; /* first match pattern */ 2946 2947 struct ip_fw *rule; 2948 2949 /* 2950 * various flags used to record that we entered some fields. 2951 */ 2952 ipfw_insn *have_state = NULL; /* check-state or keep-state */ 2953 ipfw_insn *have_log = NULL, *have_altq = NULL; 2954 size_t len; 2955 2956 int i; 2957 2958 int open_par = 0; /* open parenthesis ( */ 2959 2960 /* proto is here because it is used to fetch ports */ 2961 u_char proto = IPPROTO_IP; /* default protocol */ 2962 2963 double match_prob = 1; /* match probability, default is always match */ 2964 2965 bzero(actbuf, sizeof(actbuf)); /* actions go here */ 2966 bzero(cmdbuf, sizeof(cmdbuf)); 2967 bzero(rulebuf, sizeof(rulebuf)); 2968 2969 rule = (struct ip_fw *)rulebuf; 2970 cmd = (ipfw_insn *)cmdbuf; 2971 action = (ipfw_insn *)actbuf; 2972 2973 av++; ac--; 2974 2975 /* [rule N] -- Rule number optional */ 2976 if (ac && isdigit(**av)) { 2977 rule->rulenum = atoi(*av); 2978 av++; 2979 ac--; 2980 } 2981 2982 /* [set N] -- set number (0..RESVD_SET), optional */ 2983 if (ac > 1 && !strncmp(*av, "set", strlen(*av))) { 2984 int set = strtoul(av[1], NULL, 10); 2985 if (set < 0 || set > RESVD_SET) 2986 errx(EX_DATAERR, "illegal set %s", av[1]); 2987 rule->set = set; 2988 av += 2; ac -= 2; 2989 } 2990 2991 /* [prob D] -- match probability, optional */ 2992 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) { 2993 match_prob = strtod(av[1], NULL); 2994 2995 if (match_prob <= 0 || match_prob > 1) 2996 errx(EX_DATAERR, "illegal match prob. %s", av[1]); 2997 av += 2; ac -= 2; 2998 } 2999 3000 /* action -- mandatory */ 3001 NEED1("missing action"); 3002 i = match_token(rule_actions, *av); 3003 ac--; av++; 3004 action->len = 1; /* default */ 3005 switch(i) { 3006 case TOK_CHECKSTATE: 3007 have_state = action; 3008 action->opcode = O_CHECK_STATE; 3009 break; 3010 3011 case TOK_ACCEPT: 3012 action->opcode = O_ACCEPT; 3013 break; 3014 3015 case TOK_DENY: 3016 action->opcode = O_DENY; 3017 action->arg1 = 0; 3018 break; 3019 3020 case TOK_REJECT: 3021 action->opcode = O_REJECT; 3022 action->arg1 = ICMP_UNREACH_HOST; 3023 break; 3024 3025 case TOK_RESET: 3026 action->opcode = O_REJECT; 3027 action->arg1 = ICMP_REJECT_RST; 3028 break; 3029 3030 case TOK_UNREACH: 3031 action->opcode = O_REJECT; 3032 NEED1("missing reject code"); 3033 fill_reject_code(&action->arg1, *av); 3034 ac--; av++; 3035 break; 3036 3037 case TOK_COUNT: 3038 action->opcode = O_COUNT; 3039 break; 3040 3041 case TOK_QUEUE: 3042 case TOK_PIPE: 3043 action->len = F_INSN_SIZE(ipfw_insn_pipe); 3044 case TOK_SKIPTO: 3045 if (i == TOK_QUEUE) 3046 action->opcode = O_QUEUE; 3047 else if (i == TOK_PIPE) 3048 action->opcode = O_PIPE; 3049 else if (i == TOK_SKIPTO) 3050 action->opcode = O_SKIPTO; 3051 NEED1("missing skipto/pipe/queue number"); 3052 action->arg1 = strtoul(*av, NULL, 10); 3053 av++; ac--; 3054 break; 3055 3056 case TOK_DIVERT: 3057 case TOK_TEE: 3058 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE; 3059 NEED1("missing divert/tee port"); 3060 action->arg1 = strtoul(*av, NULL, 0); 3061 if (action->arg1 == 0) { 3062 struct servent *s; 3063 setservent(1); 3064 s = getservbyname(av[0], "divert"); 3065 if (s != NULL) 3066 action->arg1 = ntohs(s->s_port); 3067 else 3068 errx(EX_DATAERR, "illegal divert/tee port"); 3069 } 3070 ac--; av++; 3071 break; 3072 3073 case TOK_FORWARD: { 3074 ipfw_insn_sa *p = (ipfw_insn_sa *)action; 3075 char *s, *end; 3076 3077 NEED1("missing forward address[:port]"); 3078 3079 action->opcode = O_FORWARD_IP; 3080 action->len = F_INSN_SIZE(ipfw_insn_sa); 3081 3082 p->sa.sin_len = sizeof(struct sockaddr_in); 3083 p->sa.sin_family = AF_INET; 3084 p->sa.sin_port = 0; 3085 /* 3086 * locate the address-port separator (':' or ',') 3087 */ 3088 s = strchr(*av, ':'); 3089 if (s == NULL) 3090 s = strchr(*av, ','); 3091 if (s != NULL) { 3092 *(s++) = '\0'; 3093 i = strtoport(s, &end, 0 /* base */, 0 /* proto */); 3094 if (s == end) 3095 errx(EX_DATAERR, 3096 "illegal forwarding port ``%s''", s); 3097 p->sa.sin_port = (u_short)i; 3098 } 3099 lookup_host(*av, &(p->sa.sin_addr)); 3100 } 3101 ac--; av++; 3102 break; 3103 3104 case TOK_COMMENT: 3105 /* pretend it is a 'count' rule followed by the comment */ 3106 action->opcode = O_COUNT; 3107 ac++; av--; /* go back... */ 3108 break; 3109 3110 default: 3111 errx(EX_DATAERR, "invalid action %s\n", av[-1]); 3112 } 3113 action = next_cmd(action); 3114 3115 /* 3116 * [altq queuename] -- altq tag, optional 3117 * [log [logamount N]] -- log, optional 3118 * 3119 * If they exist, it go first in the cmdbuf, but then it is 3120 * skipped in the copy section to the end of the buffer. 3121 */ 3122 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) { 3123 ac--; av++; 3124 switch (i) { 3125 case TOK_LOG: 3126 { 3127 ipfw_insn_log *c = (ipfw_insn_log *)cmd; 3128 int l; 3129 3130 if (have_log) 3131 errx(EX_DATAERR, 3132 "log cannot be specified more than once"); 3133 have_log = (ipfw_insn *)c; 3134 cmd->len = F_INSN_SIZE(ipfw_insn_log); 3135 cmd->opcode = O_LOG; 3136 if (ac && !strncmp(*av, "logamount", strlen(*av))) { 3137 ac--; av++; 3138 NEED1("logamount requires argument"); 3139 l = atoi(*av); 3140 if (l < 0) 3141 errx(EX_DATAERR, 3142 "logamount must be positive"); 3143 c->max_log = l; 3144 ac--; av++; 3145 } else { 3146 len = sizeof(c->max_log); 3147 if (sysctlbyname("net.inet.ip.fw.verbose_limit", 3148 &c->max_log, &len, NULL, 0) == -1) 3149 errx(1, "sysctlbyname(\"%s\")", 3150 "net.inet.ip.fw.verbose_limit"); 3151 } 3152 } 3153 break; 3154 3155 case TOK_ALTQ: 3156 { 3157 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd; 3158 3159 NEED1("missing altq queue name"); 3160 if (have_altq) 3161 errx(EX_DATAERR, 3162 "altq cannot be specified more than once"); 3163 have_altq = (ipfw_insn *)a; 3164 cmd->len = F_INSN_SIZE(ipfw_insn_altq); 3165 cmd->opcode = O_ALTQ; 3166 fill_altq_qid(&a->qid, *av); 3167 ac--; av++; 3168 } 3169 break; 3170 3171 default: 3172 abort(); 3173 } 3174 cmd = next_cmd(cmd); 3175 } 3176 3177 if (have_state) /* must be a check-state, we are done */ 3178 goto done; 3179 3180 #define OR_START(target) \ 3181 if (ac && (*av[0] == '(' || *av[0] == '{')) { \ 3182 if (open_par) \ 3183 errx(EX_USAGE, "nested \"(\" not allowed\n"); \ 3184 prev = NULL; \ 3185 open_par = 1; \ 3186 if ( (av[0])[1] == '\0') { \ 3187 ac--; av++; \ 3188 } else \ 3189 (*av)++; \ 3190 } \ 3191 target: \ 3192 3193 3194 #define CLOSE_PAR \ 3195 if (open_par) { \ 3196 if (ac && ( \ 3197 !strncmp(*av, ")", strlen(*av)) || \ 3198 !strncmp(*av, "}", strlen(*av)) )) { \ 3199 prev = NULL; \ 3200 open_par = 0; \ 3201 ac--; av++; \ 3202 } else \ 3203 errx(EX_USAGE, "missing \")\"\n"); \ 3204 } 3205 3206 #define NOT_BLOCK \ 3207 if (ac && !strncmp(*av, "not", strlen(*av))) { \ 3208 if (cmd->len & F_NOT) \ 3209 errx(EX_USAGE, "double \"not\" not allowed\n"); \ 3210 cmd->len |= F_NOT; \ 3211 ac--; av++; \ 3212 } 3213 3214 #define OR_BLOCK(target) \ 3215 if (ac && !strncmp(*av, "or", strlen(*av))) { \ 3216 if (prev == NULL || open_par == 0) \ 3217 errx(EX_DATAERR, "invalid OR block"); \ 3218 prev->len |= F_OR; \ 3219 ac--; av++; \ 3220 goto target; \ 3221 } \ 3222 CLOSE_PAR; 3223 3224 first_cmd = cmd; 3225 3226 #if 0 3227 /* 3228 * MAC addresses, optional. 3229 * If we have this, we skip the part "proto from src to dst" 3230 * and jump straight to the option parsing. 3231 */ 3232 NOT_BLOCK; 3233 NEED1("missing protocol"); 3234 if (!strncmp(*av, "MAC", strlen(*av)) || 3235 !strncmp(*av, "mac", strlen(*av))) { 3236 ac--; av++; /* the "MAC" keyword */ 3237 add_mac(cmd, ac, av); /* exits in case of errors */ 3238 cmd = next_cmd(cmd); 3239 ac -= 2; av += 2; /* dst-mac and src-mac */ 3240 NOT_BLOCK; 3241 NEED1("missing mac type"); 3242 if (add_mactype(cmd, ac, av[0])) 3243 cmd = next_cmd(cmd); 3244 ac--; av++; /* any or mac-type */ 3245 goto read_options; 3246 } 3247 #endif 3248 3249 /* 3250 * protocol, mandatory 3251 */ 3252 OR_START(get_proto); 3253 NOT_BLOCK; 3254 NEED1("missing protocol"); 3255 if (add_proto(cmd, *av)) { 3256 av++; ac--; 3257 if (F_LEN(cmd) == 0) /* plain IP */ 3258 proto = 0; 3259 else { 3260 proto = cmd->arg1; 3261 prev = cmd; 3262 cmd = next_cmd(cmd); 3263 } 3264 } else if (first_cmd != cmd) { 3265 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 3266 } else 3267 goto read_options; 3268 OR_BLOCK(get_proto); 3269 3270 /* 3271 * "from", mandatory 3272 */ 3273 if (!ac || strncmp(*av, "from", strlen(*av))) 3274 errx(EX_USAGE, "missing ``from''"); 3275 ac--; av++; 3276 3277 /* 3278 * source IP, mandatory 3279 */ 3280 OR_START(source_ip); 3281 NOT_BLOCK; /* optional "not" */ 3282 NEED1("missing source address"); 3283 if (add_srcip(cmd, *av)) { 3284 ac--; av++; 3285 if (F_LEN(cmd) != 0) { /* ! any */ 3286 prev = cmd; 3287 cmd = next_cmd(cmd); 3288 } 3289 } 3290 OR_BLOCK(source_ip); 3291 3292 /* 3293 * source ports, optional 3294 */ 3295 NOT_BLOCK; /* optional "not" */ 3296 if (ac) { 3297 if (!strncmp(*av, "any", strlen(*av)) || 3298 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 3299 ac--; av++; 3300 if (F_LEN(cmd) != 0) 3301 cmd = next_cmd(cmd); 3302 } 3303 } 3304 3305 /* 3306 * "to", mandatory 3307 */ 3308 if (!ac || strncmp(*av, "to", strlen(*av))) 3309 errx(EX_USAGE, "missing ``to''"); 3310 av++; ac--; 3311 3312 /* 3313 * destination, mandatory 3314 */ 3315 OR_START(dest_ip); 3316 NOT_BLOCK; /* optional "not" */ 3317 NEED1("missing dst address"); 3318 if (add_dstip(cmd, *av)) { 3319 ac--; av++; 3320 if (F_LEN(cmd) != 0) { /* ! any */ 3321 prev = cmd; 3322 cmd = next_cmd(cmd); 3323 } 3324 } 3325 OR_BLOCK(dest_ip); 3326 3327 /* 3328 * dest. ports, optional 3329 */ 3330 NOT_BLOCK; /* optional "not" */ 3331 if (ac) { 3332 if (!strncmp(*av, "any", strlen(*av)) || 3333 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 3334 ac--; av++; 3335 if (F_LEN(cmd) != 0) 3336 cmd = next_cmd(cmd); 3337 } 3338 } 3339 3340 read_options: 3341 if (ac && first_cmd == cmd) { 3342 /* 3343 * nothing specified so far, store in the rule to ease 3344 * printout later. 3345 */ 3346 rule->_pad = 1; 3347 } 3348 prev = NULL; 3349 while (ac) { 3350 char *s; 3351 ipfw_insn_u32 *cmd32; /* alias for cmd */ 3352 3353 s = *av; 3354 cmd32 = (ipfw_insn_u32 *)cmd; 3355 3356 if (*s == '!') { /* alternate syntax for NOT */ 3357 if (cmd->len & F_NOT) 3358 errx(EX_USAGE, "double \"not\" not allowed\n"); 3359 cmd->len = F_NOT; 3360 s++; 3361 } 3362 i = match_token(rule_options, s); 3363 ac--; av++; 3364 switch(i) { 3365 case TOK_NOT: 3366 if (cmd->len & F_NOT) 3367 errx(EX_USAGE, "double \"not\" not allowed\n"); 3368 cmd->len = F_NOT; 3369 break; 3370 3371 case TOK_OR: 3372 if (open_par == 0 || prev == NULL) 3373 errx(EX_USAGE, "invalid \"or\" block\n"); 3374 prev->len |= F_OR; 3375 break; 3376 3377 case TOK_STARTBRACE: 3378 if (open_par) 3379 errx(EX_USAGE, "+nested \"(\" not allowed\n"); 3380 open_par = 1; 3381 break; 3382 3383 case TOK_ENDBRACE: 3384 if (!open_par) 3385 errx(EX_USAGE, "+missing \")\"\n"); 3386 open_par = 0; 3387 prev = NULL; 3388 break; 3389 3390 case TOK_IN: 3391 fill_cmd(cmd, O_IN, 0, 0); 3392 break; 3393 3394 case TOK_OUT: 3395 cmd->len ^= F_NOT; /* toggle F_NOT */ 3396 fill_cmd(cmd, O_IN, 0, 0); 3397 break; 3398 3399 case TOK_DIVERTED: 3400 fill_cmd(cmd, O_DIVERTED, 0, 3); 3401 break; 3402 3403 case TOK_DIVERTEDLOOPBACK: 3404 fill_cmd(cmd, O_DIVERTED, 0, 1); 3405 break; 3406 3407 case TOK_DIVERTEDOUTPUT: 3408 fill_cmd(cmd, O_DIVERTED, 0, 2); 3409 break; 3410 3411 case TOK_FRAG: 3412 fill_cmd(cmd, O_FRAG, 0, 0); 3413 break; 3414 3415 case TOK_LAYER2: 3416 fill_cmd(cmd, O_LAYER2, 0, 0); 3417 break; 3418 3419 case TOK_XMIT: 3420 case TOK_RECV: 3421 case TOK_VIA: 3422 NEED1("recv, xmit, via require interface name" 3423 " or address"); 3424 fill_iface((ipfw_insn_if *)cmd, av[0]); 3425 ac--; av++; 3426 if (F_LEN(cmd) == 0) /* not a valid address */ 3427 break; 3428 if (i == TOK_XMIT) 3429 cmd->opcode = O_XMIT; 3430 else if (i == TOK_RECV) 3431 cmd->opcode = O_RECV; 3432 else if (i == TOK_VIA) 3433 cmd->opcode = O_VIA; 3434 break; 3435 3436 case TOK_ICMPTYPES: 3437 NEED1("icmptypes requires list of types"); 3438 fill_icmptypes((ipfw_insn_u32 *)cmd, *av); 3439 av++; ac--; 3440 break; 3441 3442 case TOK_IPTTL: 3443 NEED1("ipttl requires TTL"); 3444 if (strpbrk(*av, "-,")) { 3445 if (!add_ports(cmd, *av, 0, O_IPTTL)) 3446 errx(EX_DATAERR, "invalid ipttl %s", *av); 3447 } else 3448 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0)); 3449 ac--; av++; 3450 break; 3451 3452 case TOK_IPID: 3453 NEED1("ipid requires id"); 3454 if (strpbrk(*av, "-,")) { 3455 if (!add_ports(cmd, *av, 0, O_IPID)) 3456 errx(EX_DATAERR, "invalid ipid %s", *av); 3457 } else 3458 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0)); 3459 ac--; av++; 3460 break; 3461 3462 case TOK_IPLEN: 3463 NEED1("iplen requires length"); 3464 if (strpbrk(*av, "-,")) { 3465 if (!add_ports(cmd, *av, 0, O_IPLEN)) 3466 errx(EX_DATAERR, "invalid ip len %s", *av); 3467 } else 3468 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0)); 3469 ac--; av++; 3470 break; 3471 3472 case TOK_IPVER: 3473 NEED1("ipver requires version"); 3474 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0)); 3475 ac--; av++; 3476 break; 3477 3478 case TOK_IPPRECEDENCE: 3479 NEED1("ipprecedence requires value"); 3480 fill_cmd(cmd, O_IPPRECEDENCE, 0, 3481 (strtoul(*av, NULL, 0) & 7) << 5); 3482 ac--; av++; 3483 break; 3484 3485 case TOK_IPOPTS: 3486 NEED1("missing argument for ipoptions"); 3487 fill_flags(cmd, O_IPOPT, f_ipopts, *av); 3488 ac--; av++; 3489 break; 3490 3491 case TOK_IPTOS: 3492 NEED1("missing argument for iptos"); 3493 fill_flags(cmd, O_IPTOS, f_iptos, *av); 3494 ac--; av++; 3495 break; 3496 3497 case TOK_UID: 3498 NEED1("uid requires argument"); 3499 { 3500 char *end; 3501 uid_t uid; 3502 struct passwd *pwd; 3503 3504 cmd->opcode = O_UID; 3505 uid = strtoul(*av, &end, 0); 3506 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av); 3507 if (pwd == NULL) 3508 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av); 3509 cmd32->d[0] = pwd->pw_uid; 3510 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 3511 ac--; av++; 3512 } 3513 break; 3514 3515 case TOK_GID: 3516 NEED1("gid requires argument"); 3517 { 3518 char *end; 3519 gid_t gid; 3520 struct group *grp; 3521 3522 cmd->opcode = O_GID; 3523 gid = strtoul(*av, &end, 0); 3524 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av); 3525 if (grp == NULL) 3526 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av); 3527 cmd32->d[0] = grp->gr_gid; 3528 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 3529 ac--; av++; 3530 } 3531 break; 3532 3533 case TOK_JAIL: 3534 NEED1("jail requires argument"); 3535 { 3536 char *end; 3537 int jid; 3538 3539 cmd->opcode = O_JAIL; 3540 jid = (int)strtol(*av, &end, 0); 3541 if (jid < 0 || *end != '\0') 3542 errx(EX_DATAERR, "jail requires prison ID"); 3543 cmd32->d[0] = (uint32_t)jid; 3544 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 3545 ac--; av++; 3546 } 3547 break; 3548 3549 case TOK_ESTAB: 3550 fill_cmd(cmd, O_ESTAB, 0, 0); 3551 break; 3552 3553 case TOK_SETUP: 3554 fill_cmd(cmd, O_TCPFLAGS, 0, 3555 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 ); 3556 break; 3557 3558 case TOK_TCPDATALEN: 3559 NEED1("tcpdatalen requires length"); 3560 if (strpbrk(*av, "-,")) { 3561 if (!add_ports(cmd, *av, 0, O_TCPDATALEN)) 3562 errx(EX_DATAERR, "invalid tcpdata len %s", *av); 3563 } else 3564 fill_cmd(cmd, O_TCPDATALEN, 0, 3565 strtoul(*av, NULL, 0)); 3566 ac--; av++; 3567 break; 3568 3569 case TOK_TCPOPTS: 3570 NEED1("missing argument for tcpoptions"); 3571 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av); 3572 ac--; av++; 3573 break; 3574 3575 case TOK_TCPSEQ: 3576 case TOK_TCPACK: 3577 NEED1("tcpseq/tcpack requires argument"); 3578 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 3579 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK; 3580 cmd32->d[0] = htonl(strtoul(*av, NULL, 0)); 3581 ac--; av++; 3582 break; 3583 3584 case TOK_TCPWIN: 3585 NEED1("tcpwin requires length"); 3586 fill_cmd(cmd, O_TCPWIN, 0, 3587 htons(strtoul(*av, NULL, 0))); 3588 ac--; av++; 3589 break; 3590 3591 case TOK_TCPFLAGS: 3592 NEED1("missing argument for tcpflags"); 3593 cmd->opcode = O_TCPFLAGS; 3594 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av); 3595 ac--; av++; 3596 break; 3597 3598 case TOK_KEEPSTATE: 3599 if (open_par) 3600 errx(EX_USAGE, "keep-state cannot be part " 3601 "of an or block"); 3602 if (have_state) 3603 errx(EX_USAGE, "only one of keep-state " 3604 "and limit is allowed"); 3605 have_state = cmd; 3606 fill_cmd(cmd, O_KEEP_STATE, 0, 0); 3607 break; 3608 3609 case TOK_LIMIT: 3610 if (open_par) 3611 errx(EX_USAGE, "limit cannot be part " 3612 "of an or block"); 3613 if (have_state) 3614 errx(EX_USAGE, "only one of keep-state " 3615 "and limit is allowed"); 3616 NEED1("limit needs mask and # of connections"); 3617 have_state = cmd; 3618 { 3619 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 3620 3621 cmd->len = F_INSN_SIZE(ipfw_insn_limit); 3622 cmd->opcode = O_LIMIT; 3623 c->limit_mask = 0; 3624 c->conn_limit = 0; 3625 for (; ac >1 ;) { 3626 int val; 3627 3628 val = match_token(limit_masks, *av); 3629 if (val <= 0) 3630 break; 3631 c->limit_mask |= val; 3632 ac--; av++; 3633 } 3634 c->conn_limit = atoi(*av); 3635 if (c->conn_limit == 0) 3636 errx(EX_USAGE, "limit: limit must be >0"); 3637 if (c->limit_mask == 0) 3638 errx(EX_USAGE, "missing limit mask"); 3639 ac--; av++; 3640 } 3641 break; 3642 3643 case TOK_PROTO: 3644 NEED1("missing protocol"); 3645 if (add_proto(cmd, *av)) { 3646 proto = cmd->arg1; 3647 ac--; av++; 3648 } else 3649 errx(EX_DATAERR, "invalid protocol ``%s''", 3650 *av); 3651 break; 3652 3653 case TOK_SRCIP: 3654 NEED1("missing source IP"); 3655 if (add_srcip(cmd, *av)) { 3656 ac--; av++; 3657 } 3658 break; 3659 3660 case TOK_DSTIP: 3661 NEED1("missing destination IP"); 3662 if (add_dstip(cmd, *av)) { 3663 ac--; av++; 3664 } 3665 break; 3666 3667 case TOK_SRCPORT: 3668 NEED1("missing source port"); 3669 if (!strncmp(*av, "any", strlen(*av)) || 3670 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 3671 ac--; av++; 3672 } else 3673 errx(EX_DATAERR, "invalid source port %s", *av); 3674 break; 3675 3676 case TOK_DSTPORT: 3677 NEED1("missing destination port"); 3678 if (!strncmp(*av, "any", strlen(*av)) || 3679 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 3680 ac--; av++; 3681 } else 3682 errx(EX_DATAERR, "invalid destination port %s", 3683 *av); 3684 break; 3685 3686 case TOK_MAC: 3687 if (add_mac(cmd, ac, av)) { 3688 ac -= 2; av += 2; 3689 } 3690 break; 3691 3692 case TOK_MACTYPE: 3693 NEED1("missing mac type"); 3694 if (!add_mactype(cmd, ac, *av)) 3695 errx(EX_DATAERR, "invalid mac type %s", *av); 3696 ac--; av++; 3697 break; 3698 3699 case TOK_VERREVPATH: 3700 fill_cmd(cmd, O_VERREVPATH, 0, 0); 3701 break; 3702 3703 case TOK_VERSRCREACH: 3704 fill_cmd(cmd, O_VERSRCREACH, 0, 0); 3705 break; 3706 3707 case TOK_ANTISPOOF: 3708 fill_cmd(cmd, O_ANTISPOOF, 0, 0); 3709 break; 3710 3711 case TOK_IPSEC: 3712 fill_cmd(cmd, O_IPSEC, 0, 0); 3713 break; 3714 3715 case TOK_COMMENT: 3716 fill_comment(cmd, ac, av); 3717 av += ac; 3718 ac = 0; 3719 break; 3720 3721 default: 3722 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s); 3723 } 3724 if (F_LEN(cmd) > 0) { /* prepare to advance */ 3725 prev = cmd; 3726 cmd = next_cmd(cmd); 3727 } 3728 } 3729 3730 done: 3731 /* 3732 * Now copy stuff into the rule. 3733 * If we have a keep-state option, the first instruction 3734 * must be a PROBE_STATE (which is generated here). 3735 * If we have a LOG option, it was stored as the first command, 3736 * and now must be moved to the top of the action part. 3737 */ 3738 dst = (ipfw_insn *)rule->cmd; 3739 3740 /* 3741 * First thing to write into the command stream is the match probability. 3742 */ 3743 if (match_prob != 1) { /* 1 means always match */ 3744 dst->opcode = O_PROB; 3745 dst->len = 2; 3746 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff); 3747 dst += dst->len; 3748 } 3749 3750 /* 3751 * generate O_PROBE_STATE if necessary 3752 */ 3753 if (have_state && have_state->opcode != O_CHECK_STATE) { 3754 fill_cmd(dst, O_PROBE_STATE, 0, 0); 3755 dst = next_cmd(dst); 3756 } 3757 /* 3758 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ 3759 */ 3760 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) { 3761 i = F_LEN(src); 3762 3763 switch (src->opcode) { 3764 case O_LOG: 3765 case O_KEEP_STATE: 3766 case O_LIMIT: 3767 case O_ALTQ: 3768 break; 3769 default: 3770 bcopy(src, dst, i * sizeof(uint32_t)); 3771 dst += i; 3772 } 3773 } 3774 3775 /* 3776 * put back the have_state command as last opcode 3777 */ 3778 if (have_state && have_state->opcode != O_CHECK_STATE) { 3779 i = F_LEN(have_state); 3780 bcopy(have_state, dst, i * sizeof(uint32_t)); 3781 dst += i; 3782 } 3783 /* 3784 * start action section 3785 */ 3786 rule->act_ofs = dst - rule->cmd; 3787 3788 /* 3789 * put back O_LOG, O_ALTQ if necessary 3790 */ 3791 if (have_log) { 3792 i = F_LEN(have_log); 3793 bcopy(have_log, dst, i * sizeof(uint32_t)); 3794 dst += i; 3795 } 3796 if (have_altq) { 3797 i = F_LEN(have_altq); 3798 bcopy(have_altq, dst, i * sizeof(uint32_t)); 3799 dst += i; 3800 } 3801 /* 3802 * copy all other actions 3803 */ 3804 for (src = (ipfw_insn *)actbuf; src != action; src += i) { 3805 i = F_LEN(src); 3806 bcopy(src, dst, i * sizeof(uint32_t)); 3807 dst += i; 3808 } 3809 3810 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd); 3811 i = (char *)dst - (char *)rule; 3812 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1) 3813 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD"); 3814 if (!do_quiet) 3815 show_ipfw(rule, 0, 0); 3816 } 3817 3818 static void 3819 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */) 3820 { 3821 int rulenum; 3822 int failed = EX_OK; 3823 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG"; 3824 3825 av++; ac--; 3826 3827 if (!ac) { 3828 /* clear all entries */ 3829 if (do_cmd(optname, NULL, 0) < 0) 3830 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name); 3831 if (!do_quiet) 3832 printf("%s.\n", optname == IP_FW_ZERO ? 3833 "Accounting cleared":"Logging counts reset"); 3834 3835 return; 3836 } 3837 3838 while (ac) { 3839 /* Rule number */ 3840 if (isdigit(**av)) { 3841 rulenum = atoi(*av); 3842 av++; 3843 ac--; 3844 if (do_cmd(optname, &rulenum, sizeof rulenum)) { 3845 warn("rule %u: setsockopt(IP_FW_%s)", 3846 rulenum, name); 3847 failed = EX_UNAVAILABLE; 3848 } else if (!do_quiet) 3849 printf("Entry %d %s.\n", rulenum, 3850 optname == IP_FW_ZERO ? 3851 "cleared" : "logging count reset"); 3852 } else { 3853 errx(EX_USAGE, "invalid rule number ``%s''", *av); 3854 } 3855 } 3856 if (failed != EX_OK) 3857 exit(failed); 3858 } 3859 3860 static void 3861 flush(int force) 3862 { 3863 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH; 3864 3865 if (!force && !do_quiet) { /* need to ask user */ 3866 int c; 3867 3868 printf("Are you sure? [yn] "); 3869 fflush(stdout); 3870 do { 3871 c = toupper(getc(stdin)); 3872 while (c != '\n' && getc(stdin) != '\n') 3873 if (feof(stdin)) 3874 return; /* and do not flush */ 3875 } while (c != 'Y' && c != 'N'); 3876 printf("\n"); 3877 if (c == 'N') /* user said no */ 3878 return; 3879 } 3880 if (do_cmd(cmd, NULL, 0) < 0) 3881 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)", 3882 do_pipe ? "DUMMYNET" : "FW"); 3883 if (!do_quiet) 3884 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules"); 3885 } 3886 3887 /* 3888 * Free a the (locally allocated) copy of command line arguments. 3889 */ 3890 static void 3891 free_args(int ac, char **av) 3892 { 3893 int i; 3894 3895 for (i=0; i < ac; i++) 3896 free(av[i]); 3897 free(av); 3898 } 3899 3900 /* 3901 * This one handles all table-related commands 3902 * ipfw table N add addr[/masklen] [value] 3903 * ipfw table N delete addr[/masklen] 3904 * ipfw table N flush 3905 * ipfw table N list 3906 */ 3907 static void 3908 table_handler(int ac, char *av[]) 3909 { 3910 ipfw_table_entry ent; 3911 ipfw_table *tbl; 3912 int do_add; 3913 char *p; 3914 socklen_t l; 3915 uint32_t a; 3916 3917 ac--; av++; 3918 if (ac && isdigit(**av)) { 3919 ent.tbl = atoi(*av); 3920 ac--; av++; 3921 } else 3922 errx(EX_USAGE, "table number required"); 3923 NEED1("table needs command"); 3924 if (strncmp(*av, "add", strlen(*av)) == 0 || 3925 strncmp(*av, "delete", strlen(*av)) == 0) { 3926 do_add = **av == 'a'; 3927 ac--; av++; 3928 if (!ac) 3929 errx(EX_USAGE, "IP address required"); 3930 p = strchr(*av, '/'); 3931 if (p) { 3932 *p++ = '\0'; 3933 ent.masklen = atoi(p); 3934 if (ent.masklen > 32) 3935 errx(EX_DATAERR, "bad width ``%s''", p); 3936 } else 3937 ent.masklen = 32; 3938 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0) 3939 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 3940 ac--; av++; 3941 if (do_add && ac) 3942 ent.value = strtoul(*av, NULL, 0); 3943 else 3944 ent.value = 0; 3945 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL, 3946 &ent, sizeof(ent)) < 0) 3947 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)", 3948 do_add ? "ADD" : "DEL"); 3949 } else if (strncmp(*av, "flush", strlen(*av)) == 0) { 3950 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0) 3951 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)"); 3952 } else if (strncmp(*av, "list", strlen(*av)) == 0) { 3953 a = ent.tbl; 3954 l = sizeof(a); 3955 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0) 3956 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)"); 3957 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry); 3958 tbl = malloc(l); 3959 if (tbl == NULL) 3960 err(EX_OSERR, "malloc"); 3961 tbl->tbl = ent.tbl; 3962 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0) 3963 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)"); 3964 for (a = 0; a < tbl->cnt; a++) { 3965 printf("%s/%u %u\n", 3966 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr), 3967 tbl->ent[a].masklen, tbl->ent[a].value); 3968 } 3969 } else 3970 errx(EX_USAGE, "invalid table command %s", *av); 3971 } 3972 3973 /* 3974 * Called with the arguments (excluding program name). 3975 * Returns 0 if successful, 1 if empty command, errx() in case of errors. 3976 */ 3977 static int 3978 ipfw_main(int oldac, char **oldav) 3979 { 3980 int ch, ac, save_ac; 3981 char **av, **save_av; 3982 int do_acct = 0; /* Show packet/byte count */ 3983 3984 #define WHITESP " \t\f\v\n\r" 3985 if (oldac == 0) 3986 return 1; 3987 else if (oldac == 1) { 3988 /* 3989 * If we are called with a single string, try to split it into 3990 * arguments for subsequent parsing. 3991 * But first, remove spaces after a ',', by copying the string 3992 * in-place. 3993 */ 3994 char *arg = oldav[0]; /* The string... */ 3995 int l = strlen(arg); 3996 int copy = 0; /* 1 if we need to copy, 0 otherwise */ 3997 int i, j; 3998 for (i = j = 0; i < l; i++) { 3999 if (arg[i] == '#') /* comment marker */ 4000 break; 4001 if (copy) { 4002 arg[j++] = arg[i]; 4003 copy = !index("," WHITESP, arg[i]); 4004 } else { 4005 copy = !index(WHITESP, arg[i]); 4006 if (copy) 4007 arg[j++] = arg[i]; 4008 } 4009 } 4010 if (!copy && j > 0) /* last char was a 'blank', remove it */ 4011 j--; 4012 l = j; /* the new argument length */ 4013 arg[j++] = '\0'; 4014 if (l == 0) /* empty string! */ 4015 return 1; 4016 4017 /* 4018 * First, count number of arguments. Because of the previous 4019 * processing, this is just the number of blanks plus 1. 4020 */ 4021 for (i = 0, ac = 1; i < l; i++) 4022 if (index(WHITESP, arg[i]) != NULL) 4023 ac++; 4024 4025 av = calloc(ac, sizeof(char *)); 4026 4027 /* 4028 * Second, copy arguments from cmd[] to av[]. For each one, 4029 * j is the initial character, i is the one past the end. 4030 */ 4031 for (ac = 0, i = j = 0; i < l; i++) 4032 if (index(WHITESP, arg[i]) != NULL || i == l-1) { 4033 if (i == l-1) 4034 i++; 4035 av[ac] = calloc(i-j+1, 1); 4036 bcopy(arg+j, av[ac], i-j); 4037 ac++; 4038 j = i + 1; 4039 } 4040 } else { 4041 /* 4042 * If an argument ends with ',' join with the next one. 4043 */ 4044 int first, i, l; 4045 4046 av = calloc(oldac, sizeof(char *)); 4047 for (first = i = ac = 0, l = 0; i < oldac; i++) { 4048 char *arg = oldav[i]; 4049 int k = strlen(arg); 4050 4051 l += k; 4052 if (arg[k-1] != ',' || i == oldac-1) { 4053 /* Time to copy. */ 4054 av[ac] = calloc(l+1, 1); 4055 for (l=0; first <= i; first++) { 4056 strcat(av[ac]+l, oldav[first]); 4057 l += strlen(oldav[first]); 4058 } 4059 ac++; 4060 l = 0; 4061 first = i+1; 4062 } 4063 } 4064 } 4065 4066 /* Set the force flag for non-interactive processes */ 4067 if (!do_force) 4068 do_force = !isatty(STDIN_FILENO); 4069 4070 /* Save arguments for final freeing of memory. */ 4071 save_ac = ac; 4072 save_av = av; 4073 4074 optind = optreset = 0; 4075 while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1) 4076 switch (ch) { 4077 case 'a': 4078 do_acct = 1; 4079 break; 4080 4081 case 'b': 4082 comment_only = 1; 4083 do_compact = 1; 4084 break; 4085 4086 case 'c': 4087 do_compact = 1; 4088 break; 4089 4090 case 'd': 4091 do_dynamic = 1; 4092 break; 4093 4094 case 'e': 4095 do_expired = 1; 4096 break; 4097 4098 case 'f': 4099 do_force = 1; 4100 break; 4101 4102 case 'h': /* help */ 4103 free_args(save_ac, save_av); 4104 help(); 4105 break; /* NOTREACHED */ 4106 4107 case 'n': 4108 test_only = 1; 4109 break; 4110 4111 case 'N': 4112 do_resolv = 1; 4113 break; 4114 4115 case 'q': 4116 do_quiet = 1; 4117 break; 4118 4119 case 's': /* sort */ 4120 do_sort = atoi(optarg); 4121 break; 4122 4123 case 'S': 4124 show_sets = 1; 4125 break; 4126 4127 case 't': 4128 do_time = 1; 4129 break; 4130 4131 case 'T': 4132 do_time = 2; /* numeric timestamp */ 4133 break; 4134 4135 case 'v': /* verbose */ 4136 verbose = 1; 4137 break; 4138 4139 default: 4140 free_args(save_ac, save_av); 4141 return 1; 4142 } 4143 4144 ac -= optind; 4145 av += optind; 4146 NEED1("bad arguments, for usage summary ``ipfw''"); 4147 4148 /* 4149 * An undocumented behaviour of ipfw1 was to allow rule numbers first, 4150 * e.g. "100 add allow ..." instead of "add 100 allow ...". 4151 * In case, swap first and second argument to get the normal form. 4152 */ 4153 if (ac > 1 && isdigit(*av[0])) { 4154 char *p = av[0]; 4155 4156 av[0] = av[1]; 4157 av[1] = p; 4158 } 4159 4160 /* 4161 * optional: pipe or queue 4162 */ 4163 do_pipe = 0; 4164 if (!strncmp(*av, "pipe", strlen(*av))) 4165 do_pipe = 1; 4166 else if (!strncmp(*av, "queue", strlen(*av))) 4167 do_pipe = 2; 4168 if (do_pipe) { 4169 ac--; 4170 av++; 4171 } 4172 NEED1("missing command"); 4173 4174 /* 4175 * For pipes and queues we normally say 'pipe NN config' 4176 * but the code is easier to parse as 'pipe config NN' 4177 * so we swap the two arguments. 4178 */ 4179 if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) { 4180 char *p = av[0]; 4181 4182 av[0] = av[1]; 4183 av[1] = p; 4184 } 4185 4186 if (!strncmp(*av, "add", strlen(*av))) 4187 add(ac, av); 4188 else if (do_pipe && !strncmp(*av, "config", strlen(*av))) 4189 config_pipe(ac, av); 4190 else if (!strncmp(*av, "delete", strlen(*av))) 4191 delete(ac, av); 4192 else if (!strncmp(*av, "flush", strlen(*av))) 4193 flush(do_force); 4194 else if (!strncmp(*av, "zero", strlen(*av))) 4195 zero(ac, av, IP_FW_ZERO); 4196 else if (!strncmp(*av, "resetlog", strlen(*av))) 4197 zero(ac, av, IP_FW_RESETLOG); 4198 else if (!strncmp(*av, "print", strlen(*av)) || 4199 !strncmp(*av, "list", strlen(*av))) 4200 list(ac, av, do_acct); 4201 else if (!strncmp(*av, "set", strlen(*av))) 4202 sets_handler(ac, av); 4203 else if (!strncmp(*av, "table", strlen(*av))) 4204 table_handler(ac, av); 4205 else if (!strncmp(*av, "enable", strlen(*av))) 4206 sysctl_handler(ac, av, 1); 4207 else if (!strncmp(*av, "disable", strlen(*av))) 4208 sysctl_handler(ac, av, 0); 4209 else if (!strncmp(*av, "show", strlen(*av))) 4210 list(ac, av, 1 /* show counters */); 4211 else 4212 errx(EX_USAGE, "bad command `%s'", *av); 4213 4214 /* Free memory allocated in the argument parsing. */ 4215 free_args(save_ac, save_av); 4216 return 0; 4217 } 4218 4219 4220 static void 4221 ipfw_readfile(int ac, char *av[]) 4222 { 4223 #define MAX_ARGS 32 4224 char buf[BUFSIZ]; 4225 char *cmd = NULL, *filename = av[ac-1]; 4226 int c, lineno=0; 4227 FILE *f = NULL; 4228 pid_t preproc = 0; 4229 4230 filename = av[ac-1]; 4231 4232 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) { 4233 switch(c) { 4234 case 'c': 4235 do_compact = 1; 4236 break; 4237 4238 case 'f': 4239 do_force = 1; 4240 break; 4241 4242 case 'N': 4243 do_resolv = 1; 4244 break; 4245 4246 case 'n': 4247 test_only = 1; 4248 break; 4249 4250 case 'p': 4251 cmd = optarg; 4252 /* 4253 * Skip previous args and delete last one, so we 4254 * pass all but the last argument to the preprocessor 4255 * via av[optind-1] 4256 */ 4257 av += optind - 1; 4258 ac -= optind - 1; 4259 av[ac-1] = NULL; 4260 fprintf(stderr, "command is %s\n", av[0]); 4261 break; 4262 4263 case 'q': 4264 do_quiet = 1; 4265 break; 4266 4267 case 'S': 4268 show_sets = 1; 4269 break; 4270 4271 default: 4272 errx(EX_USAGE, "bad arguments, for usage" 4273 " summary ``ipfw''"); 4274 } 4275 4276 if (cmd != NULL) 4277 break; 4278 } 4279 4280 if (cmd == NULL && ac != optind + 1) { 4281 fprintf(stderr, "ac %d, optind %d\n", ac, optind); 4282 errx(EX_USAGE, "extraneous filename arguments"); 4283 } 4284 4285 if ((f = fopen(filename, "r")) == NULL) 4286 err(EX_UNAVAILABLE, "fopen: %s", filename); 4287 4288 if (cmd != NULL) { /* pipe through preprocessor */ 4289 int pipedes[2]; 4290 4291 if (pipe(pipedes) == -1) 4292 err(EX_OSERR, "cannot create pipe"); 4293 4294 preproc = fork(); 4295 if (preproc == -1) 4296 err(EX_OSERR, "cannot fork"); 4297 4298 if (preproc == 0) { 4299 /* 4300 * Child, will run the preprocessor with the 4301 * file on stdin and the pipe on stdout. 4302 */ 4303 if (dup2(fileno(f), 0) == -1 4304 || dup2(pipedes[1], 1) == -1) 4305 err(EX_OSERR, "dup2()"); 4306 fclose(f); 4307 close(pipedes[1]); 4308 close(pipedes[0]); 4309 execvp(cmd, av); 4310 err(EX_OSERR, "execvp(%s) failed", cmd); 4311 } else { /* parent, will reopen f as the pipe */ 4312 fclose(f); 4313 close(pipedes[1]); 4314 if ((f = fdopen(pipedes[0], "r")) == NULL) { 4315 int savederrno = errno; 4316 4317 (void)kill(preproc, SIGTERM); 4318 errno = savederrno; 4319 err(EX_OSERR, "fdopen()"); 4320 } 4321 } 4322 } 4323 4324 while (fgets(buf, BUFSIZ, f)) { /* read commands */ 4325 char linename[10]; 4326 char *args[1]; 4327 4328 lineno++; 4329 sprintf(linename, "Line %d", lineno); 4330 setprogname(linename); /* XXX */ 4331 args[0] = buf; 4332 ipfw_main(1, args); 4333 } 4334 fclose(f); 4335 if (cmd != NULL) { 4336 int status; 4337 4338 if (waitpid(preproc, &status, 0) == -1) 4339 errx(EX_OSERR, "waitpid()"); 4340 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 4341 errx(EX_UNAVAILABLE, 4342 "preprocessor exited with status %d", 4343 WEXITSTATUS(status)); 4344 else if (WIFSIGNALED(status)) 4345 errx(EX_UNAVAILABLE, 4346 "preprocessor exited with signal %d", 4347 WTERMSIG(status)); 4348 } 4349 } 4350 4351 int 4352 main(int ac, char *av[]) 4353 { 4354 /* 4355 * If the last argument is an absolute pathname, interpret it 4356 * as a file to be preprocessed. 4357 */ 4358 4359 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) 4360 ipfw_readfile(ac, av); 4361 else { 4362 if (ipfw_main(ac-1, av+1)) 4363 show_usage(); 4364 } 4365 return EX_OK; 4366 } 4367