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