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