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