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