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