1 /* 2 * Copyright (c) 2002-2003 Luigi Rizzo 3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp 4 * Copyright (c) 1994 Ugen J.S.Antsilevich 5 * 6 * Idea and grammar partially left from: 7 * Copyright (c) 1993 Daniel Boulet 8 * 9 * Redistribution and use in source forms, with and without modification, 10 * are permitted provided that this entire comment appears intact. 11 * 12 * Redistribution in binary form may occur without any restrictions. 13 * Obviously, it would be nice if you gave credit where credit is due 14 * but requiring it would be too onerous. 15 * 16 * This software is provided ``AS IS'' without any warranties of any kind. 17 * 18 * NEW command line interface for IP firewall facility 19 * 20 * $FreeBSD$ 21 */ 22 23 #include <sys/param.h> 24 #include <sys/mbuf.h> 25 #include <sys/socket.h> 26 #include <sys/sockio.h> 27 #include <sys/sysctl.h> 28 #include <sys/time.h> 29 #include <sys/wait.h> 30 #include <sys/queue.h> 31 32 #include <ctype.h> 33 #include <err.h> 34 #include <errno.h> 35 #include <grp.h> 36 #include <limits.h> 37 #include <netdb.h> 38 #include <pwd.h> 39 #include <signal.h> 40 #include <stdio.h> 41 #include <stdlib.h> 42 #include <stdarg.h> 43 #include <string.h> 44 #include <timeconv.h> /* XXX do we need this ? */ 45 #include <unistd.h> 46 #include <sysexits.h> 47 #include <unistd.h> 48 #include <fcntl.h> 49 50 #include <net/ethernet.h> 51 #include <net/if.h> 52 #include <net/if_dl.h> 53 #include <net/pfvar.h> 54 #include <net/route.h> /* def. of struct route */ 55 #include <netinet/in.h> 56 #include <netinet/in_systm.h> 57 #include <netinet/ip.h> 58 #include <netinet/ip_icmp.h> 59 #include <netinet/icmp6.h> 60 #include <netinet/ip_fw.h> 61 #include <netinet/ip_dummynet.h> 62 #include <netinet/tcp.h> 63 #include <arpa/inet.h> 64 #include <alias.h> 65 66 int 67 do_resolv, /* Would try to resolve all */ 68 do_time, /* Show time stamps */ 69 do_quiet, /* Be quiet in add and flush */ 70 do_pipe, /* this cmd refers to a pipe */ 71 do_nat, /* Nat configuration. */ 72 do_sort, /* field to sort results (0 = no) */ 73 do_dynamic, /* display dynamic rules */ 74 do_expired, /* display expired dynamic rules */ 75 do_compact, /* show rules in compact mode */ 76 do_force, /* do not ask for confirmation */ 77 use_set, /* work with specified set number */ 78 show_sets, /* display rule sets */ 79 test_only, /* only check syntax */ 80 comment_only, /* only print action and comment */ 81 verbose; 82 83 #define IP_MASK_ALL 0xffffffff 84 /* 85 * the following macro returns an error message if we run out of 86 * arguments. 87 */ 88 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);} 89 90 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \ 91 if (!ac) \ 92 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \ 93 if (_substrcmp(*av, "tablearg") == 0) { \ 94 arg = IP_FW_TABLEARG; \ 95 break; \ 96 } \ 97 \ 98 { \ 99 long val; \ 100 char *end; \ 101 \ 102 val = strtol(*av, &end, 10); \ 103 \ 104 if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \ 105 errx(EX_DATAERR, "%s: invalid argument: %s", \ 106 match_value(s_x, tok), *av); \ 107 \ 108 if (errno == ERANGE || val < min || val > max) \ 109 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \ 110 match_value(s_x, tok), min, max, *av); \ 111 \ 112 if (val == IP_FW_TABLEARG) \ 113 errx(EX_DATAERR, "%s: illegal argument value: %s", \ 114 match_value(s_x, tok), *av); \ 115 arg = val; \ 116 } \ 117 } while (0) 118 119 #define PRINT_UINT_ARG(str, arg) do { \ 120 if (str != NULL) \ 121 printf("%s",str); \ 122 if (arg == IP_FW_TABLEARG) \ 123 printf("tablearg"); \ 124 else \ 125 printf("%u", (uint32_t)arg); \ 126 } while (0) 127 128 /* 129 * _s_x is a structure that stores a string <-> token pairs, used in 130 * various places in the parser. Entries are stored in arrays, 131 * with an entry with s=NULL as terminator. 132 * The search routines are match_token() and match_value(). 133 * Often, an element with x=0 contains an error string. 134 * 135 */ 136 struct _s_x { 137 char const *s; 138 int x; 139 }; 140 141 static struct _s_x f_tcpflags[] = { 142 { "syn", TH_SYN }, 143 { "fin", TH_FIN }, 144 { "ack", TH_ACK }, 145 { "psh", TH_PUSH }, 146 { "rst", TH_RST }, 147 { "urg", TH_URG }, 148 { "tcp flag", 0 }, 149 { NULL, 0 } 150 }; 151 152 static struct _s_x f_tcpopts[] = { 153 { "mss", IP_FW_TCPOPT_MSS }, 154 { "maxseg", IP_FW_TCPOPT_MSS }, 155 { "window", IP_FW_TCPOPT_WINDOW }, 156 { "sack", IP_FW_TCPOPT_SACK }, 157 { "ts", IP_FW_TCPOPT_TS }, 158 { "timestamp", IP_FW_TCPOPT_TS }, 159 { "cc", IP_FW_TCPOPT_CC }, 160 { "tcp option", 0 }, 161 { NULL, 0 } 162 }; 163 164 /* 165 * IP options span the range 0 to 255 so we need to remap them 166 * (though in fact only the low 5 bits are significant). 167 */ 168 static struct _s_x f_ipopts[] = { 169 { "ssrr", IP_FW_IPOPT_SSRR}, 170 { "lsrr", IP_FW_IPOPT_LSRR}, 171 { "rr", IP_FW_IPOPT_RR}, 172 { "ts", IP_FW_IPOPT_TS}, 173 { "ip option", 0 }, 174 { NULL, 0 } 175 }; 176 177 static struct _s_x f_iptos[] = { 178 { "lowdelay", IPTOS_LOWDELAY}, 179 { "throughput", IPTOS_THROUGHPUT}, 180 { "reliability", IPTOS_RELIABILITY}, 181 { "mincost", IPTOS_MINCOST}, 182 { "congestion", IPTOS_ECN_CE}, 183 { "ecntransport", IPTOS_ECN_ECT0}, 184 { "ip tos option", 0}, 185 { NULL, 0 } 186 }; 187 188 static struct _s_x limit_masks[] = { 189 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT}, 190 {"src-addr", DYN_SRC_ADDR}, 191 {"src-port", DYN_SRC_PORT}, 192 {"dst-addr", DYN_DST_ADDR}, 193 {"dst-port", DYN_DST_PORT}, 194 {NULL, 0} 195 }; 196 197 /* 198 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines 199 * This is only used in this code. 200 */ 201 #define IPPROTO_ETHERTYPE 0x1000 202 static struct _s_x ether_types[] = { 203 /* 204 * Note, we cannot use "-:&/" in the names because they are field 205 * separators in the type specifications. Also, we use s = NULL as 206 * end-delimiter, because a type of 0 can be legal. 207 */ 208 { "ip", 0x0800 }, 209 { "ipv4", 0x0800 }, 210 { "ipv6", 0x86dd }, 211 { "arp", 0x0806 }, 212 { "rarp", 0x8035 }, 213 { "vlan", 0x8100 }, 214 { "loop", 0x9000 }, 215 { "trail", 0x1000 }, 216 { "at", 0x809b }, 217 { "atalk", 0x809b }, 218 { "aarp", 0x80f3 }, 219 { "pppoe_disc", 0x8863 }, 220 { "pppoe_sess", 0x8864 }, 221 { "ipx_8022", 0x00E0 }, 222 { "ipx_8023", 0x0000 }, 223 { "ipx_ii", 0x8137 }, 224 { "ipx_snap", 0x8137 }, 225 { "ipx", 0x8137 }, 226 { "ns", 0x0600 }, 227 { NULL, 0 } 228 }; 229 230 static void show_usage(void); 231 232 enum tokens { 233 TOK_NULL=0, 234 235 TOK_OR, 236 TOK_NOT, 237 TOK_STARTBRACE, 238 TOK_ENDBRACE, 239 240 TOK_ACCEPT, 241 TOK_COUNT, 242 TOK_PIPE, 243 TOK_QUEUE, 244 TOK_DIVERT, 245 TOK_TEE, 246 TOK_NETGRAPH, 247 TOK_NGTEE, 248 TOK_FORWARD, 249 TOK_SKIPTO, 250 TOK_DENY, 251 TOK_REJECT, 252 TOK_RESET, 253 TOK_UNREACH, 254 TOK_CHECKSTATE, 255 TOK_NAT, 256 257 TOK_ALTQ, 258 TOK_LOG, 259 TOK_TAG, 260 TOK_UNTAG, 261 262 TOK_TAGGED, 263 TOK_UID, 264 TOK_GID, 265 TOK_JAIL, 266 TOK_IN, 267 TOK_LIMIT, 268 TOK_KEEPSTATE, 269 TOK_LAYER2, 270 TOK_OUT, 271 TOK_DIVERTED, 272 TOK_DIVERTEDLOOPBACK, 273 TOK_DIVERTEDOUTPUT, 274 TOK_XMIT, 275 TOK_RECV, 276 TOK_VIA, 277 TOK_FRAG, 278 TOK_IPOPTS, 279 TOK_IPLEN, 280 TOK_IPID, 281 TOK_IPPRECEDENCE, 282 TOK_IPTOS, 283 TOK_IPTTL, 284 TOK_IPVER, 285 TOK_ESTAB, 286 TOK_SETUP, 287 TOK_TCPDATALEN, 288 TOK_TCPFLAGS, 289 TOK_TCPOPTS, 290 TOK_TCPSEQ, 291 TOK_TCPACK, 292 TOK_TCPWIN, 293 TOK_ICMPTYPES, 294 TOK_MAC, 295 TOK_MACTYPE, 296 TOK_VERREVPATH, 297 TOK_VERSRCREACH, 298 TOK_ANTISPOOF, 299 TOK_IPSEC, 300 TOK_COMMENT, 301 302 TOK_PLR, 303 TOK_NOERROR, 304 TOK_BUCKETS, 305 TOK_DSTIP, 306 TOK_SRCIP, 307 TOK_DSTPORT, 308 TOK_SRCPORT, 309 TOK_ALL, 310 TOK_MASK, 311 TOK_BW, 312 TOK_DELAY, 313 TOK_RED, 314 TOK_GRED, 315 TOK_DROPTAIL, 316 TOK_PROTO, 317 TOK_WEIGHT, 318 TOK_IP, 319 TOK_IF, 320 TOK_ALOG, 321 TOK_DENY_INC, 322 TOK_SAME_PORTS, 323 TOK_UNREG_ONLY, 324 TOK_RESET_ADDR, 325 TOK_ALIAS_REV, 326 TOK_PROXY_ONLY, 327 TOK_REDIR_ADDR, 328 TOK_REDIR_PORT, 329 TOK_REDIR_PROTO, 330 331 TOK_IPV6, 332 TOK_FLOWID, 333 TOK_ICMP6TYPES, 334 TOK_EXT6HDR, 335 TOK_DSTIP6, 336 TOK_SRCIP6, 337 338 TOK_IPV4, 339 TOK_UNREACH6, 340 TOK_RESET6, 341 }; 342 343 struct _s_x dummynet_params[] = { 344 { "plr", TOK_PLR }, 345 { "noerror", TOK_NOERROR }, 346 { "buckets", TOK_BUCKETS }, 347 { "dst-ip", TOK_DSTIP }, 348 { "src-ip", TOK_SRCIP }, 349 { "dst-port", TOK_DSTPORT }, 350 { "src-port", TOK_SRCPORT }, 351 { "proto", TOK_PROTO }, 352 { "weight", TOK_WEIGHT }, 353 { "all", TOK_ALL }, 354 { "mask", TOK_MASK }, 355 { "droptail", TOK_DROPTAIL }, 356 { "red", TOK_RED }, 357 { "gred", TOK_GRED }, 358 { "bw", TOK_BW }, 359 { "bandwidth", TOK_BW }, 360 { "delay", TOK_DELAY }, 361 { "pipe", TOK_PIPE }, 362 { "queue", TOK_QUEUE }, 363 { "flow-id", TOK_FLOWID}, 364 { "dst-ipv6", TOK_DSTIP6}, 365 { "dst-ip6", TOK_DSTIP6}, 366 { "src-ipv6", TOK_SRCIP6}, 367 { "src-ip6", TOK_SRCIP6}, 368 { "dummynet-params", TOK_NULL }, 369 { NULL, 0 } /* terminator */ 370 }; 371 372 struct _s_x nat_params[] = { 373 { "ip", TOK_IP }, 374 { "if", TOK_IF }, 375 { "log", TOK_ALOG }, 376 { "deny_in", TOK_DENY_INC }, 377 { "same_ports", TOK_SAME_PORTS }, 378 { "unreg_only", TOK_UNREG_ONLY }, 379 { "reset", TOK_RESET_ADDR }, 380 { "reverse", TOK_ALIAS_REV }, 381 { "proxy_only", TOK_PROXY_ONLY }, 382 { "redirect_addr", TOK_REDIR_ADDR }, 383 { "redirect_port", TOK_REDIR_PORT }, 384 { "redirect_proto", TOK_REDIR_PROTO }, 385 { NULL, 0 } /* terminator */ 386 }; 387 388 struct _s_x rule_actions[] = { 389 { "accept", TOK_ACCEPT }, 390 { "pass", TOK_ACCEPT }, 391 { "allow", TOK_ACCEPT }, 392 { "permit", TOK_ACCEPT }, 393 { "count", TOK_COUNT }, 394 { "pipe", TOK_PIPE }, 395 { "queue", TOK_QUEUE }, 396 { "divert", TOK_DIVERT }, 397 { "tee", TOK_TEE }, 398 { "netgraph", TOK_NETGRAPH }, 399 { "ngtee", TOK_NGTEE }, 400 { "fwd", TOK_FORWARD }, 401 { "forward", TOK_FORWARD }, 402 { "skipto", TOK_SKIPTO }, 403 { "deny", TOK_DENY }, 404 { "drop", TOK_DENY }, 405 { "reject", TOK_REJECT }, 406 { "reset6", TOK_RESET6 }, 407 { "reset", TOK_RESET }, 408 { "unreach6", TOK_UNREACH6 }, 409 { "unreach", TOK_UNREACH }, 410 { "check-state", TOK_CHECKSTATE }, 411 { "//", TOK_COMMENT }, 412 { "nat", TOK_NAT }, 413 { NULL, 0 } /* terminator */ 414 }; 415 416 struct _s_x rule_action_params[] = { 417 { "altq", TOK_ALTQ }, 418 { "log", TOK_LOG }, 419 { "tag", TOK_TAG }, 420 { "untag", TOK_UNTAG }, 421 { NULL, 0 } /* terminator */ 422 }; 423 424 struct _s_x rule_options[] = { 425 { "tagged", TOK_TAGGED }, 426 { "uid", TOK_UID }, 427 { "gid", TOK_GID }, 428 { "jail", TOK_JAIL }, 429 { "in", TOK_IN }, 430 { "limit", TOK_LIMIT }, 431 { "keep-state", TOK_KEEPSTATE }, 432 { "bridged", TOK_LAYER2 }, 433 { "layer2", TOK_LAYER2 }, 434 { "out", TOK_OUT }, 435 { "diverted", TOK_DIVERTED }, 436 { "diverted-loopback", TOK_DIVERTEDLOOPBACK }, 437 { "diverted-output", TOK_DIVERTEDOUTPUT }, 438 { "xmit", TOK_XMIT }, 439 { "recv", TOK_RECV }, 440 { "via", TOK_VIA }, 441 { "fragment", TOK_FRAG }, 442 { "frag", TOK_FRAG }, 443 { "ipoptions", TOK_IPOPTS }, 444 { "ipopts", TOK_IPOPTS }, 445 { "iplen", TOK_IPLEN }, 446 { "ipid", TOK_IPID }, 447 { "ipprecedence", TOK_IPPRECEDENCE }, 448 { "iptos", TOK_IPTOS }, 449 { "ipttl", TOK_IPTTL }, 450 { "ipversion", TOK_IPVER }, 451 { "ipver", TOK_IPVER }, 452 { "estab", TOK_ESTAB }, 453 { "established", TOK_ESTAB }, 454 { "setup", TOK_SETUP }, 455 { "tcpdatalen", TOK_TCPDATALEN }, 456 { "tcpflags", TOK_TCPFLAGS }, 457 { "tcpflgs", TOK_TCPFLAGS }, 458 { "tcpoptions", TOK_TCPOPTS }, 459 { "tcpopts", TOK_TCPOPTS }, 460 { "tcpseq", TOK_TCPSEQ }, 461 { "tcpack", TOK_TCPACK }, 462 { "tcpwin", TOK_TCPWIN }, 463 { "icmptype", TOK_ICMPTYPES }, 464 { "icmptypes", TOK_ICMPTYPES }, 465 { "dst-ip", TOK_DSTIP }, 466 { "src-ip", TOK_SRCIP }, 467 { "dst-port", TOK_DSTPORT }, 468 { "src-port", TOK_SRCPORT }, 469 { "proto", TOK_PROTO }, 470 { "MAC", TOK_MAC }, 471 { "mac", TOK_MAC }, 472 { "mac-type", TOK_MACTYPE }, 473 { "verrevpath", TOK_VERREVPATH }, 474 { "versrcreach", TOK_VERSRCREACH }, 475 { "antispoof", TOK_ANTISPOOF }, 476 { "ipsec", TOK_IPSEC }, 477 { "icmp6type", TOK_ICMP6TYPES }, 478 { "icmp6types", TOK_ICMP6TYPES }, 479 { "ext6hdr", TOK_EXT6HDR}, 480 { "flow-id", TOK_FLOWID}, 481 { "ipv6", TOK_IPV6}, 482 { "ip6", TOK_IPV6}, 483 { "ipv4", TOK_IPV4}, 484 { "ip4", TOK_IPV4}, 485 { "dst-ipv6", TOK_DSTIP6}, 486 { "dst-ip6", TOK_DSTIP6}, 487 { "src-ipv6", TOK_SRCIP6}, 488 { "src-ip6", TOK_SRCIP6}, 489 { "//", TOK_COMMENT }, 490 491 { "not", TOK_NOT }, /* pseudo option */ 492 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */ 493 { "or", TOK_OR }, /* pseudo option */ 494 { "|", /* escape */ TOK_OR }, /* pseudo option */ 495 { "{", TOK_STARTBRACE }, /* pseudo option */ 496 { "(", TOK_STARTBRACE }, /* pseudo option */ 497 { "}", TOK_ENDBRACE }, /* pseudo option */ 498 { ")", TOK_ENDBRACE }, /* pseudo option */ 499 { NULL, 0 } /* terminator */ 500 }; 501 502 #define TABLEARG "tablearg" 503 504 static __inline uint64_t 505 align_uint64(uint64_t *pll) { 506 uint64_t ret; 507 508 bcopy (pll, &ret, sizeof(ret)); 509 return ret; 510 } 511 512 /* 513 * conditionally runs the command. 514 */ 515 static int 516 do_cmd(int optname, void *optval, uintptr_t optlen) 517 { 518 static int s = -1; /* the socket */ 519 int i; 520 521 if (test_only) 522 return 0; 523 524 if (s == -1) 525 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 526 if (s < 0) 527 err(EX_UNAVAILABLE, "socket"); 528 529 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET || 530 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST || 531 optname == IP_FW_TABLE_GETSIZE || 532 optname == IP_FW_NAT_GET_CONFIG || 533 optname == IP_FW_NAT_GET_LOG) 534 i = getsockopt(s, IPPROTO_IP, optname, optval, 535 (socklen_t *)optlen); 536 else 537 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen); 538 return i; 539 } 540 541 /** 542 * match_token takes a table and a string, returns the value associated 543 * with the string (-1 in case of failure). 544 */ 545 static int 546 match_token(struct _s_x *table, char *string) 547 { 548 struct _s_x *pt; 549 uint i = strlen(string); 550 551 for (pt = table ; i && pt->s != NULL ; pt++) 552 if (strlen(pt->s) == i && !bcmp(string, pt->s, i)) 553 return pt->x; 554 return -1; 555 } 556 557 /** 558 * match_value takes a table and a value, returns the string associated 559 * with the value (NULL in case of failure). 560 */ 561 static char const * 562 match_value(struct _s_x *p, int value) 563 { 564 for (; p->s != NULL; p++) 565 if (p->x == value) 566 return p->s; 567 return NULL; 568 } 569 570 /* 571 * _substrcmp takes two strings and returns 1 if they do not match, 572 * and 0 if they match exactly or the first string is a sub-string 573 * of the second. A warning is printed to stderr in the case that the 574 * first string is a sub-string of the second. 575 * 576 * This function will be removed in the future through the usual 577 * deprecation process. 578 */ 579 static int 580 _substrcmp(const char *str1, const char* str2) 581 { 582 583 if (strncmp(str1, str2, strlen(str1)) != 0) 584 return 1; 585 586 if (strlen(str1) != strlen(str2)) 587 warnx("DEPRECATED: '%s' matched '%s' as a sub-string", 588 str1, str2); 589 return 0; 590 } 591 592 /* 593 * _substrcmp2 takes three strings and returns 1 if the first two do not match, 594 * and 0 if they match exactly or the second string is a sub-string 595 * of the first. A warning is printed to stderr in the case that the 596 * first string does not match the third. 597 * 598 * This function exists to warn about the bizzare construction 599 * strncmp(str, "by", 2) which is used to allow people to use a shotcut 600 * for "bytes". The problem is that in addition to accepting "by", 601 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any 602 * other string beginning with "by". 603 * 604 * This function will be removed in the future through the usual 605 * deprecation process. 606 */ 607 static int 608 _substrcmp2(const char *str1, const char* str2, const char* str3) 609 { 610 611 if (strncmp(str1, str2, strlen(str2)) != 0) 612 return 1; 613 614 if (strcmp(str1, str3) != 0) 615 warnx("DEPRECATED: '%s' matched '%s'", 616 str1, str3); 617 return 0; 618 } 619 620 /* 621 * prints one port, symbolic or numeric 622 */ 623 static void 624 print_port(int proto, uint16_t port) 625 { 626 627 if (proto == IPPROTO_ETHERTYPE) { 628 char const *s; 629 630 if (do_resolv && (s = match_value(ether_types, port)) ) 631 printf("%s", s); 632 else 633 printf("0x%04x", port); 634 } else { 635 struct servent *se = NULL; 636 if (do_resolv) { 637 struct protoent *pe = getprotobynumber(proto); 638 639 se = getservbyport(htons(port), pe ? pe->p_name : NULL); 640 } 641 if (se) 642 printf("%s", se->s_name); 643 else 644 printf("%d", port); 645 } 646 } 647 648 struct _s_x _port_name[] = { 649 {"dst-port", O_IP_DSTPORT}, 650 {"src-port", O_IP_SRCPORT}, 651 {"ipid", O_IPID}, 652 {"iplen", O_IPLEN}, 653 {"ipttl", O_IPTTL}, 654 {"mac-type", O_MAC_TYPE}, 655 {"tcpdatalen", O_TCPDATALEN}, 656 {"tagged", O_TAGGED}, 657 {NULL, 0} 658 }; 659 660 /* 661 * Print the values in a list 16-bit items of the types above. 662 * XXX todo: add support for mask. 663 */ 664 static void 665 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode) 666 { 667 uint16_t *p = cmd->ports; 668 int i; 669 char const *sep; 670 671 if (opcode != 0) { 672 sep = match_value(_port_name, opcode); 673 if (sep == NULL) 674 sep = "???"; 675 printf (" %s", sep); 676 } 677 sep = " "; 678 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) { 679 printf(sep); 680 print_port(proto, p[0]); 681 if (p[0] != p[1]) { 682 printf("-"); 683 print_port(proto, p[1]); 684 } 685 sep = ","; 686 } 687 } 688 689 /* 690 * Like strtol, but also translates service names into port numbers 691 * for some protocols. 692 * In particular: 693 * proto == -1 disables the protocol check; 694 * proto == IPPROTO_ETHERTYPE looks up an internal table 695 * proto == <some value in /etc/protocols> matches the values there. 696 * Returns *end == s in case the parameter is not found. 697 */ 698 static int 699 strtoport(char *s, char **end, int base, int proto) 700 { 701 char *p, *buf; 702 char *s1; 703 int i; 704 705 *end = s; /* default - not found */ 706 if (*s == '\0') 707 return 0; /* not found */ 708 709 if (isdigit(*s)) 710 return strtol(s, end, base); 711 712 /* 713 * find separator. '\\' escapes the next char. 714 */ 715 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++) 716 if (*s1 == '\\' && s1[1] != '\0') 717 s1++; 718 719 buf = malloc(s1 - s + 1); 720 if (buf == NULL) 721 return 0; 722 723 /* 724 * copy into a buffer skipping backslashes 725 */ 726 for (p = s, i = 0; p != s1 ; p++) 727 if (*p != '\\') 728 buf[i++] = *p; 729 buf[i++] = '\0'; 730 731 if (proto == IPPROTO_ETHERTYPE) { 732 i = match_token(ether_types, buf); 733 free(buf); 734 if (i != -1) { /* found */ 735 *end = s1; 736 return i; 737 } 738 } else { 739 struct protoent *pe = NULL; 740 struct servent *se; 741 742 if (proto != 0) 743 pe = getprotobynumber(proto); 744 setservent(1); 745 se = getservbyname(buf, pe ? pe->p_name : NULL); 746 free(buf); 747 if (se != NULL) { 748 *end = s1; 749 return ntohs(se->s_port); 750 } 751 } 752 return 0; /* not found */ 753 } 754 755 /* 756 * Map between current altq queue id numbers and names. 757 */ 758 static int altq_fetched = 0; 759 static TAILQ_HEAD(, pf_altq) altq_entries = 760 TAILQ_HEAD_INITIALIZER(altq_entries); 761 762 static void 763 altq_set_enabled(int enabled) 764 { 765 int pffd; 766 767 pffd = open("/dev/pf", O_RDWR); 768 if (pffd == -1) 769 err(EX_UNAVAILABLE, 770 "altq support opening pf(4) control device"); 771 if (enabled) { 772 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST) 773 err(EX_UNAVAILABLE, "enabling altq"); 774 } else { 775 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT) 776 err(EX_UNAVAILABLE, "disabling altq"); 777 } 778 close(pffd); 779 } 780 781 static void 782 altq_fetch() 783 { 784 struct pfioc_altq pfioc; 785 struct pf_altq *altq; 786 int pffd, mnr; 787 788 if (altq_fetched) 789 return; 790 altq_fetched = 1; 791 pffd = open("/dev/pf", O_RDONLY); 792 if (pffd == -1) { 793 warn("altq support opening pf(4) control device"); 794 return; 795 } 796 bzero(&pfioc, sizeof(pfioc)); 797 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) { 798 warn("altq support getting queue list"); 799 close(pffd); 800 return; 801 } 802 mnr = pfioc.nr; 803 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) { 804 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) { 805 if (errno == EBUSY) 806 break; 807 warn("altq support getting queue list"); 808 close(pffd); 809 return; 810 } 811 if (pfioc.altq.qid == 0) 812 continue; 813 altq = malloc(sizeof(*altq)); 814 if (altq == NULL) 815 err(EX_OSERR, "malloc"); 816 *altq = pfioc.altq; 817 TAILQ_INSERT_TAIL(&altq_entries, altq, entries); 818 } 819 close(pffd); 820 } 821 822 static u_int32_t 823 altq_name_to_qid(const char *name) 824 { 825 struct pf_altq *altq; 826 827 altq_fetch(); 828 TAILQ_FOREACH(altq, &altq_entries, entries) 829 if (strcmp(name, altq->qname) == 0) 830 break; 831 if (altq == NULL) 832 errx(EX_DATAERR, "altq has no queue named `%s'", name); 833 return altq->qid; 834 } 835 836 static const char * 837 altq_qid_to_name(u_int32_t qid) 838 { 839 struct pf_altq *altq; 840 841 altq_fetch(); 842 TAILQ_FOREACH(altq, &altq_entries, entries) 843 if (qid == altq->qid) 844 break; 845 if (altq == NULL) 846 return NULL; 847 return altq->qname; 848 } 849 850 static void 851 fill_altq_qid(u_int32_t *qid, const char *av) 852 { 853 *qid = altq_name_to_qid(av); 854 } 855 856 /* 857 * Fill the body of the command with the list of port ranges. 858 */ 859 static int 860 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto) 861 { 862 uint16_t a, b, *p = cmd->ports; 863 int i = 0; 864 char *s = av; 865 866 while (*s) { 867 a = strtoport(av, &s, 0, proto); 868 if (s == av) /* empty or invalid argument */ 869 return (0); 870 871 switch (*s) { 872 case '-': /* a range */ 873 av = s + 1; 874 b = strtoport(av, &s, 0, proto); 875 /* Reject expressions like '1-abc' or '1-2-3'. */ 876 if (s == av || (*s != ',' && *s != '\0')) 877 return (0); 878 p[0] = a; 879 p[1] = b; 880 break; 881 case ',': /* comma separated list */ 882 case '\0': 883 p[0] = p[1] = a; 884 break; 885 default: 886 warnx("port list: invalid separator <%c> in <%s>", 887 *s, av); 888 return (0); 889 } 890 891 i++; 892 p += 2; 893 av = s + 1; 894 } 895 if (i > 0) { 896 if (i + 1 > F_LEN_MASK) 897 errx(EX_DATAERR, "too many ports/ranges\n"); 898 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */ 899 } 900 return (i); 901 } 902 903 static struct _s_x icmpcodes[] = { 904 { "net", ICMP_UNREACH_NET }, 905 { "host", ICMP_UNREACH_HOST }, 906 { "protocol", ICMP_UNREACH_PROTOCOL }, 907 { "port", ICMP_UNREACH_PORT }, 908 { "needfrag", ICMP_UNREACH_NEEDFRAG }, 909 { "srcfail", ICMP_UNREACH_SRCFAIL }, 910 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN }, 911 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN }, 912 { "isolated", ICMP_UNREACH_ISOLATED }, 913 { "net-prohib", ICMP_UNREACH_NET_PROHIB }, 914 { "host-prohib", ICMP_UNREACH_HOST_PROHIB }, 915 { "tosnet", ICMP_UNREACH_TOSNET }, 916 { "toshost", ICMP_UNREACH_TOSHOST }, 917 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB }, 918 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE }, 919 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF }, 920 { NULL, 0 } 921 }; 922 923 static void 924 fill_reject_code(u_short *codep, char *str) 925 { 926 int val; 927 char *s; 928 929 val = strtoul(str, &s, 0); 930 if (s == str || *s != '\0' || val >= 0x100) 931 val = match_token(icmpcodes, str); 932 if (val < 0) 933 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str); 934 *codep = val; 935 return; 936 } 937 938 static void 939 print_reject_code(uint16_t code) 940 { 941 char const *s = match_value(icmpcodes, code); 942 943 if (s != NULL) 944 printf("unreach %s", s); 945 else 946 printf("unreach %u", code); 947 } 948 949 static struct _s_x icmp6codes[] = { 950 { "no-route", ICMP6_DST_UNREACH_NOROUTE }, 951 { "admin-prohib", ICMP6_DST_UNREACH_ADMIN }, 952 { "address", ICMP6_DST_UNREACH_ADDR }, 953 { "port", ICMP6_DST_UNREACH_NOPORT }, 954 { NULL, 0 } 955 }; 956 957 static void 958 fill_unreach6_code(u_short *codep, char *str) 959 { 960 int val; 961 char *s; 962 963 val = strtoul(str, &s, 0); 964 if (s == str || *s != '\0' || val >= 0x100) 965 val = match_token(icmp6codes, str); 966 if (val < 0) 967 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str); 968 *codep = val; 969 return; 970 } 971 972 static void 973 print_unreach6_code(uint16_t code) 974 { 975 char const *s = match_value(icmp6codes, code); 976 977 if (s != NULL) 978 printf("unreach6 %s", s); 979 else 980 printf("unreach6 %u", code); 981 } 982 983 /* 984 * Returns the number of bits set (from left) in a contiguous bitmask, 985 * or -1 if the mask is not contiguous. 986 * XXX this needs a proper fix. 987 * This effectively works on masks in big-endian (network) format. 988 * when compiled on little endian architectures. 989 * 990 * First bit is bit 7 of the first byte -- note, for MAC addresses, 991 * the first bit on the wire is bit 0 of the first byte. 992 * len is the max length in bits. 993 */ 994 static int 995 contigmask(uint8_t *p, int len) 996 { 997 int i, n; 998 999 for (i=0; i<len ; i++) 1000 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */ 1001 break; 1002 for (n=i+1; n < len; n++) 1003 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0) 1004 return -1; /* mask not contiguous */ 1005 return i; 1006 } 1007 1008 /* 1009 * print flags set/clear in the two bitmasks passed as parameters. 1010 * There is a specialized check for f_tcpflags. 1011 */ 1012 static void 1013 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list) 1014 { 1015 char const *comma = ""; 1016 int i; 1017 uint8_t set = cmd->arg1 & 0xff; 1018 uint8_t clear = (cmd->arg1 >> 8) & 0xff; 1019 1020 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) { 1021 printf(" setup"); 1022 return; 1023 } 1024 1025 printf(" %s ", name); 1026 for (i=0; list[i].x != 0; i++) { 1027 if (set & list[i].x) { 1028 set &= ~list[i].x; 1029 printf("%s%s", comma, list[i].s); 1030 comma = ","; 1031 } 1032 if (clear & list[i].x) { 1033 clear &= ~list[i].x; 1034 printf("%s!%s", comma, list[i].s); 1035 comma = ","; 1036 } 1037 } 1038 } 1039 1040 /* 1041 * Print the ip address contained in a command. 1042 */ 1043 static void 1044 print_ip(ipfw_insn_ip *cmd, char const *s) 1045 { 1046 struct hostent *he = NULL; 1047 int len = F_LEN((ipfw_insn *)cmd); 1048 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d; 1049 1050 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 1051 1052 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) { 1053 printf("me"); 1054 return; 1055 } 1056 if (cmd->o.opcode == O_IP_SRC_LOOKUP || 1057 cmd->o.opcode == O_IP_DST_LOOKUP) { 1058 printf("table(%u", ((ipfw_insn *)cmd)->arg1); 1059 if (len == F_INSN_SIZE(ipfw_insn_u32)) 1060 printf(",%u", *a); 1061 printf(")"); 1062 return; 1063 } 1064 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) { 1065 uint32_t x, *map = (uint32_t *)&(cmd->mask); 1066 int i, j; 1067 char comma = '{'; 1068 1069 x = cmd->o.arg1 - 1; 1070 x = htonl( ~x ); 1071 cmd->addr.s_addr = htonl(cmd->addr.s_addr); 1072 printf("%s/%d", inet_ntoa(cmd->addr), 1073 contigmask((uint8_t *)&x, 32)); 1074 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr); 1075 x &= 0xff; /* base */ 1076 /* 1077 * Print bits and ranges. 1078 * Locate first bit set (i), then locate first bit unset (j). 1079 * If we have 3+ consecutive bits set, then print them as a 1080 * range, otherwise only print the initial bit and rescan. 1081 */ 1082 for (i=0; i < cmd->o.arg1; i++) 1083 if (map[i/32] & (1<<(i & 31))) { 1084 for (j=i+1; j < cmd->o.arg1; j++) 1085 if (!(map[ j/32] & (1<<(j & 31)))) 1086 break; 1087 printf("%c%d", comma, i+x); 1088 if (j>i+2) { /* range has at least 3 elements */ 1089 printf("-%d", j-1+x); 1090 i = j-1; 1091 } 1092 comma = ','; 1093 } 1094 printf("}"); 1095 return; 1096 } 1097 /* 1098 * len == 2 indicates a single IP, whereas lists of 1 or more 1099 * addr/mask pairs have len = (2n+1). We convert len to n so we 1100 * use that to count the number of entries. 1101 */ 1102 for (len = len / 2; len > 0; len--, a += 2) { 1103 int mb = /* mask length */ 1104 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ? 1105 32 : contigmask((uint8_t *)&(a[1]), 32); 1106 if (mb == 32 && do_resolv) 1107 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET); 1108 if (he != NULL) /* resolved to name */ 1109 printf("%s", he->h_name); 1110 else if (mb == 0) /* any */ 1111 printf("any"); 1112 else { /* numeric IP followed by some kind of mask */ 1113 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) ); 1114 if (mb < 0) 1115 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) ); 1116 else if (mb < 32) 1117 printf("/%d", mb); 1118 } 1119 if (len > 1) 1120 printf(","); 1121 } 1122 } 1123 1124 /* 1125 * prints a MAC address/mask pair 1126 */ 1127 static void 1128 print_mac(uint8_t *addr, uint8_t *mask) 1129 { 1130 int l = contigmask(mask, 48); 1131 1132 if (l == 0) 1133 printf(" any"); 1134 else { 1135 printf(" %02x:%02x:%02x:%02x:%02x:%02x", 1136 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); 1137 if (l == -1) 1138 printf("&%02x:%02x:%02x:%02x:%02x:%02x", 1139 mask[0], mask[1], mask[2], 1140 mask[3], mask[4], mask[5]); 1141 else if (l < 48) 1142 printf("/%d", l); 1143 } 1144 } 1145 1146 static void 1147 fill_icmptypes(ipfw_insn_u32 *cmd, char *av) 1148 { 1149 uint8_t type; 1150 1151 cmd->d[0] = 0; 1152 while (*av) { 1153 if (*av == ',') 1154 av++; 1155 1156 type = strtoul(av, &av, 0); 1157 1158 if (*av != ',' && *av != '\0') 1159 errx(EX_DATAERR, "invalid ICMP type"); 1160 1161 if (type > 31) 1162 errx(EX_DATAERR, "ICMP type out of range"); 1163 1164 cmd->d[0] |= 1 << type; 1165 } 1166 cmd->o.opcode = O_ICMPTYPE; 1167 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 1168 } 1169 1170 static void 1171 print_icmptypes(ipfw_insn_u32 *cmd) 1172 { 1173 int i; 1174 char sep= ' '; 1175 1176 printf(" icmptypes"); 1177 for (i = 0; i < 32; i++) { 1178 if ( (cmd->d[0] & (1 << (i))) == 0) 1179 continue; 1180 printf("%c%d", sep, i); 1181 sep = ','; 1182 } 1183 } 1184 1185 /* 1186 * Print the ip address contained in a command. 1187 */ 1188 static void 1189 print_ip6(ipfw_insn_ip6 *cmd, char const *s) 1190 { 1191 struct hostent *he = NULL; 1192 int len = F_LEN((ipfw_insn *) cmd) - 1; 1193 struct in6_addr *a = &(cmd->addr6); 1194 char trad[255]; 1195 1196 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 1197 1198 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) { 1199 printf("me6"); 1200 return; 1201 } 1202 if (cmd->o.opcode == O_IP6) { 1203 printf(" ip6"); 1204 return; 1205 } 1206 1207 /* 1208 * len == 4 indicates a single IP, whereas lists of 1 or more 1209 * addr/mask pairs have len = (2n+1). We convert len to n so we 1210 * use that to count the number of entries. 1211 */ 1212 1213 for (len = len / 4; len > 0; len -= 2, a += 2) { 1214 int mb = /* mask length */ 1215 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ? 1216 128 : contigmask((uint8_t *)&(a[1]), 128); 1217 1218 if (mb == 128 && do_resolv) 1219 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6); 1220 if (he != NULL) /* resolved to name */ 1221 printf("%s", he->h_name); 1222 else if (mb == 0) /* any */ 1223 printf("any"); 1224 else { /* numeric IP followed by some kind of mask */ 1225 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL) 1226 printf("Error ntop in print_ip6\n"); 1227 printf("%s", trad ); 1228 if (mb < 0) /* XXX not really legal... */ 1229 printf(":%s", 1230 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad))); 1231 else if (mb < 128) 1232 printf("/%d", mb); 1233 } 1234 if (len > 2) 1235 printf(","); 1236 } 1237 } 1238 1239 static void 1240 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av) 1241 { 1242 uint8_t type; 1243 1244 bzero(cmd, sizeof(*cmd)); 1245 while (*av) { 1246 if (*av == ',') 1247 av++; 1248 type = strtoul(av, &av, 0); 1249 if (*av != ',' && *av != '\0') 1250 errx(EX_DATAERR, "invalid ICMP6 type"); 1251 /* 1252 * XXX: shouldn't this be 0xFF? I can't see any reason why 1253 * we shouldn't be able to filter all possiable values 1254 * regardless of the ability of the rest of the kernel to do 1255 * anything useful with them. 1256 */ 1257 if (type > ICMP6_MAXTYPE) 1258 errx(EX_DATAERR, "ICMP6 type out of range"); 1259 cmd->d[type / 32] |= ( 1 << (type % 32)); 1260 } 1261 cmd->o.opcode = O_ICMP6TYPE; 1262 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6); 1263 } 1264 1265 1266 static void 1267 print_icmp6types(ipfw_insn_u32 *cmd) 1268 { 1269 int i, j; 1270 char sep= ' '; 1271 1272 printf(" ip6 icmp6types"); 1273 for (i = 0; i < 7; i++) 1274 for (j=0; j < 32; ++j) { 1275 if ( (cmd->d[i] & (1 << (j))) == 0) 1276 continue; 1277 printf("%c%d", sep, (i*32 + j)); 1278 sep = ','; 1279 } 1280 } 1281 1282 static void 1283 print_flow6id( ipfw_insn_u32 *cmd) 1284 { 1285 uint16_t i, limit = cmd->o.arg1; 1286 char sep = ','; 1287 1288 printf(" flow-id "); 1289 for( i=0; i < limit; ++i) { 1290 if (i == limit - 1) 1291 sep = ' '; 1292 printf("%d%c", cmd->d[i], sep); 1293 } 1294 } 1295 1296 /* structure and define for the extension header in ipv6 */ 1297 static struct _s_x ext6hdrcodes[] = { 1298 { "frag", EXT_FRAGMENT }, 1299 { "hopopt", EXT_HOPOPTS }, 1300 { "route", EXT_ROUTING }, 1301 { "dstopt", EXT_DSTOPTS }, 1302 { "ah", EXT_AH }, 1303 { "esp", EXT_ESP }, 1304 { "rthdr0", EXT_RTHDR0 }, 1305 { "rthdr2", EXT_RTHDR2 }, 1306 { NULL, 0 } 1307 }; 1308 1309 /* fills command for the extension header filtering */ 1310 int 1311 fill_ext6hdr( ipfw_insn *cmd, char *av) 1312 { 1313 int tok; 1314 char *s = av; 1315 1316 cmd->arg1 = 0; 1317 1318 while(s) { 1319 av = strsep( &s, ",") ; 1320 tok = match_token(ext6hdrcodes, av); 1321 switch (tok) { 1322 case EXT_FRAGMENT: 1323 cmd->arg1 |= EXT_FRAGMENT; 1324 break; 1325 1326 case EXT_HOPOPTS: 1327 cmd->arg1 |= EXT_HOPOPTS; 1328 break; 1329 1330 case EXT_ROUTING: 1331 cmd->arg1 |= EXT_ROUTING; 1332 break; 1333 1334 case EXT_DSTOPTS: 1335 cmd->arg1 |= EXT_DSTOPTS; 1336 break; 1337 1338 case EXT_AH: 1339 cmd->arg1 |= EXT_AH; 1340 break; 1341 1342 case EXT_ESP: 1343 cmd->arg1 |= EXT_ESP; 1344 break; 1345 1346 case EXT_RTHDR0: 1347 cmd->arg1 |= EXT_RTHDR0; 1348 break; 1349 1350 case EXT_RTHDR2: 1351 cmd->arg1 |= EXT_RTHDR2; 1352 break; 1353 1354 default: 1355 errx( EX_DATAERR, "invalid option for ipv6 exten header" ); 1356 break; 1357 } 1358 } 1359 if (cmd->arg1 == 0 ) 1360 return 0; 1361 cmd->opcode = O_EXT_HDR; 1362 cmd->len |= F_INSN_SIZE( ipfw_insn ); 1363 return 1; 1364 } 1365 1366 void 1367 print_ext6hdr( ipfw_insn *cmd ) 1368 { 1369 char sep = ' '; 1370 1371 printf(" extension header:"); 1372 if (cmd->arg1 & EXT_FRAGMENT ) { 1373 printf("%cfragmentation", sep); 1374 sep = ','; 1375 } 1376 if (cmd->arg1 & EXT_HOPOPTS ) { 1377 printf("%chop options", sep); 1378 sep = ','; 1379 } 1380 if (cmd->arg1 & EXT_ROUTING ) { 1381 printf("%crouting options", sep); 1382 sep = ','; 1383 } 1384 if (cmd->arg1 & EXT_RTHDR0 ) { 1385 printf("%crthdr0", sep); 1386 sep = ','; 1387 } 1388 if (cmd->arg1 & EXT_RTHDR2 ) { 1389 printf("%crthdr2", sep); 1390 sep = ','; 1391 } 1392 if (cmd->arg1 & EXT_DSTOPTS ) { 1393 printf("%cdestination options", sep); 1394 sep = ','; 1395 } 1396 if (cmd->arg1 & EXT_AH ) { 1397 printf("%cauthentication header", sep); 1398 sep = ','; 1399 } 1400 if (cmd->arg1 & EXT_ESP ) { 1401 printf("%cencapsulated security payload", sep); 1402 } 1403 } 1404 1405 /* 1406 * show_ipfw() prints the body of an ipfw rule. 1407 * Because the standard rule has at least proto src_ip dst_ip, we use 1408 * a helper function to produce these entries if not provided explicitly. 1409 * The first argument is the list of fields we have, the second is 1410 * the list of fields we want to be printed. 1411 * 1412 * Special cases if we have provided a MAC header: 1413 * + if the rule does not contain IP addresses/ports, do not print them; 1414 * + if the rule does not contain an IP proto, print "all" instead of "ip"; 1415 * 1416 * Once we have 'have_options', IP header fields are printed as options. 1417 */ 1418 #define HAVE_PROTO 0x0001 1419 #define HAVE_SRCIP 0x0002 1420 #define HAVE_DSTIP 0x0004 1421 #define HAVE_PROTO4 0x0008 1422 #define HAVE_PROTO6 0x0010 1423 #define HAVE_OPTIONS 0x8000 1424 1425 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP) 1426 static void 1427 show_prerequisites(int *flags, int want, int cmd) 1428 { 1429 if (comment_only) 1430 return; 1431 if ( (*flags & HAVE_IP) == HAVE_IP) 1432 *flags |= HAVE_OPTIONS; 1433 1434 if ( !(*flags & HAVE_OPTIONS)) { 1435 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) 1436 if ( (*flags & HAVE_PROTO4)) 1437 printf(" ip4"); 1438 else if ( (*flags & HAVE_PROTO6)) 1439 printf(" ip6"); 1440 else 1441 printf(" ip"); 1442 1443 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP)) 1444 printf(" from any"); 1445 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP)) 1446 printf(" to any"); 1447 } 1448 *flags |= want; 1449 } 1450 1451 static void 1452 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth) 1453 { 1454 static int twidth = 0; 1455 int l; 1456 ipfw_insn *cmd, *tagptr = NULL; 1457 char *comment = NULL; /* ptr to comment if we have one */ 1458 int proto = 0; /* default */ 1459 int flags = 0; /* prerequisites */ 1460 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */ 1461 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */ 1462 int or_block = 0; /* we are in an or block */ 1463 uint32_t set_disable; 1464 1465 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable)); 1466 1467 if (set_disable & (1 << rule->set)) { /* disabled */ 1468 if (!show_sets) 1469 return; 1470 else 1471 printf("# DISABLED "); 1472 } 1473 printf("%05u ", rule->rulenum); 1474 1475 if (pcwidth>0 || bcwidth>0) 1476 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt), 1477 bcwidth, align_uint64(&rule->bcnt)); 1478 1479 if (do_time == 2) 1480 printf("%10u ", rule->timestamp); 1481 else if (do_time == 1) { 1482 char timestr[30]; 1483 time_t t = (time_t)0; 1484 1485 if (twidth == 0) { 1486 strcpy(timestr, ctime(&t)); 1487 *strchr(timestr, '\n') = '\0'; 1488 twidth = strlen(timestr); 1489 } 1490 if (rule->timestamp) { 1491 t = _long_to_time(rule->timestamp); 1492 1493 strcpy(timestr, ctime(&t)); 1494 *strchr(timestr, '\n') = '\0'; 1495 printf("%s ", timestr); 1496 } else { 1497 printf("%*s", twidth, " "); 1498 } 1499 } 1500 1501 if (show_sets) 1502 printf("set %d ", rule->set); 1503 1504 /* 1505 * print the optional "match probability" 1506 */ 1507 if (rule->cmd_len > 0) { 1508 cmd = rule->cmd ; 1509 if (cmd->opcode == O_PROB) { 1510 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd; 1511 double d = 1.0 * p->d[0]; 1512 1513 d = (d / 0x7fffffff); 1514 printf("prob %f ", d); 1515 } 1516 } 1517 1518 /* 1519 * first print actions 1520 */ 1521 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule); 1522 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) { 1523 switch(cmd->opcode) { 1524 case O_CHECK_STATE: 1525 printf("check-state"); 1526 flags = HAVE_IP; /* avoid printing anything else */ 1527 break; 1528 1529 case O_ACCEPT: 1530 printf("allow"); 1531 break; 1532 1533 case O_COUNT: 1534 printf("count"); 1535 break; 1536 1537 case O_DENY: 1538 printf("deny"); 1539 break; 1540 1541 case O_REJECT: 1542 if (cmd->arg1 == ICMP_REJECT_RST) 1543 printf("reset"); 1544 else if (cmd->arg1 == ICMP_UNREACH_HOST) 1545 printf("reject"); 1546 else 1547 print_reject_code(cmd->arg1); 1548 break; 1549 1550 case O_UNREACH6: 1551 if (cmd->arg1 == ICMP6_UNREACH_RST) 1552 printf("reset6"); 1553 else 1554 print_unreach6_code(cmd->arg1); 1555 break; 1556 1557 case O_SKIPTO: 1558 PRINT_UINT_ARG("skipto ", cmd->arg1); 1559 break; 1560 1561 case O_PIPE: 1562 PRINT_UINT_ARG("pipe ", cmd->arg1); 1563 break; 1564 1565 case O_QUEUE: 1566 PRINT_UINT_ARG("queue ", cmd->arg1); 1567 break; 1568 1569 case O_DIVERT: 1570 PRINT_UINT_ARG("divert ", cmd->arg1); 1571 break; 1572 1573 case O_TEE: 1574 PRINT_UINT_ARG("tee ", cmd->arg1); 1575 break; 1576 1577 case O_NETGRAPH: 1578 PRINT_UINT_ARG("netgraph ", cmd->arg1); 1579 break; 1580 1581 case O_NGTEE: 1582 PRINT_UINT_ARG("ngtee ", cmd->arg1); 1583 break; 1584 1585 case O_FORWARD_IP: 1586 { 1587 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd; 1588 1589 if (s->sa.sin_addr.s_addr == INADDR_ANY) { 1590 printf("fwd tablearg"); 1591 } else { 1592 printf("fwd %s", inet_ntoa(s->sa.sin_addr)); 1593 } 1594 if (s->sa.sin_port) 1595 printf(",%d", s->sa.sin_port); 1596 } 1597 break; 1598 1599 case O_LOG: /* O_LOG is printed last */ 1600 logptr = (ipfw_insn_log *)cmd; 1601 break; 1602 1603 case O_ALTQ: /* O_ALTQ is printed after O_LOG */ 1604 altqptr = (ipfw_insn_altq *)cmd; 1605 break; 1606 1607 case O_TAG: 1608 tagptr = cmd; 1609 break; 1610 1611 case O_NAT: 1612 printf("nat %u", cmd->arg1); 1613 break; 1614 1615 default: 1616 printf("** unrecognized action %d len %d ", 1617 cmd->opcode, cmd->len); 1618 } 1619 } 1620 if (logptr) { 1621 if (logptr->max_log > 0) 1622 printf(" log logamount %d", logptr->max_log); 1623 else 1624 printf(" log"); 1625 } 1626 if (altqptr) { 1627 const char *qname; 1628 1629 qname = altq_qid_to_name(altqptr->qid); 1630 if (qname == NULL) 1631 printf(" altq ?<%u>", altqptr->qid); 1632 else 1633 printf(" altq %s", qname); 1634 } 1635 if (tagptr) { 1636 if (tagptr->len & F_NOT) 1637 PRINT_UINT_ARG(" untag ", tagptr->arg1); 1638 else 1639 PRINT_UINT_ARG(" tag ", tagptr->arg1); 1640 } 1641 1642 /* 1643 * then print the body. 1644 */ 1645 for (l = rule->act_ofs, cmd = rule->cmd ; 1646 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1647 if ((cmd->len & F_OR) || (cmd->len & F_NOT)) 1648 continue; 1649 if (cmd->opcode == O_IP4) { 1650 flags |= HAVE_PROTO4; 1651 break; 1652 } else if (cmd->opcode == O_IP6) { 1653 flags |= HAVE_PROTO6; 1654 break; 1655 } 1656 } 1657 if (rule->_pad & 1) { /* empty rules before options */ 1658 if (!do_compact) { 1659 show_prerequisites(&flags, HAVE_PROTO, 0); 1660 printf(" from any to any"); 1661 } 1662 flags |= HAVE_IP | HAVE_OPTIONS; 1663 } 1664 1665 if (comment_only) 1666 comment = "..."; 1667 1668 for (l = rule->act_ofs, cmd = rule->cmd ; 1669 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1670 /* useful alias */ 1671 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; 1672 1673 if (comment_only) { 1674 if (cmd->opcode != O_NOP) 1675 continue; 1676 printf(" // %s\n", (char *)(cmd + 1)); 1677 return; 1678 } 1679 1680 show_prerequisites(&flags, 0, cmd->opcode); 1681 1682 switch(cmd->opcode) { 1683 case O_PROB: 1684 break; /* done already */ 1685 1686 case O_PROBE_STATE: 1687 break; /* no need to print anything here */ 1688 1689 case O_IP_SRC: 1690 case O_IP_SRC_LOOKUP: 1691 case O_IP_SRC_MASK: 1692 case O_IP_SRC_ME: 1693 case O_IP_SRC_SET: 1694 show_prerequisites(&flags, HAVE_PROTO, 0); 1695 if (!(flags & HAVE_SRCIP)) 1696 printf(" from"); 1697 if ((cmd->len & F_OR) && !or_block) 1698 printf(" {"); 1699 print_ip((ipfw_insn_ip *)cmd, 1700 (flags & HAVE_OPTIONS) ? " src-ip" : ""); 1701 flags |= HAVE_SRCIP; 1702 break; 1703 1704 case O_IP_DST: 1705 case O_IP_DST_LOOKUP: 1706 case O_IP_DST_MASK: 1707 case O_IP_DST_ME: 1708 case O_IP_DST_SET: 1709 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1710 if (!(flags & HAVE_DSTIP)) 1711 printf(" to"); 1712 if ((cmd->len & F_OR) && !or_block) 1713 printf(" {"); 1714 print_ip((ipfw_insn_ip *)cmd, 1715 (flags & HAVE_OPTIONS) ? " dst-ip" : ""); 1716 flags |= HAVE_DSTIP; 1717 break; 1718 1719 case O_IP6_SRC: 1720 case O_IP6_SRC_MASK: 1721 case O_IP6_SRC_ME: 1722 show_prerequisites(&flags, HAVE_PROTO, 0); 1723 if (!(flags & HAVE_SRCIP)) 1724 printf(" from"); 1725 if ((cmd->len & F_OR) && !or_block) 1726 printf(" {"); 1727 print_ip6((ipfw_insn_ip6 *)cmd, 1728 (flags & HAVE_OPTIONS) ? " src-ip6" : ""); 1729 flags |= HAVE_SRCIP | HAVE_PROTO; 1730 break; 1731 1732 case O_IP6_DST: 1733 case O_IP6_DST_MASK: 1734 case O_IP6_DST_ME: 1735 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1736 if (!(flags & HAVE_DSTIP)) 1737 printf(" to"); 1738 if ((cmd->len & F_OR) && !or_block) 1739 printf(" {"); 1740 print_ip6((ipfw_insn_ip6 *)cmd, 1741 (flags & HAVE_OPTIONS) ? " dst-ip6" : ""); 1742 flags |= HAVE_DSTIP; 1743 break; 1744 1745 case O_FLOW6ID: 1746 print_flow6id( (ipfw_insn_u32 *) cmd ); 1747 flags |= HAVE_OPTIONS; 1748 break; 1749 1750 case O_IP_DSTPORT: 1751 show_prerequisites(&flags, HAVE_IP, 0); 1752 case O_IP_SRCPORT: 1753 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1754 if ((cmd->len & F_OR) && !or_block) 1755 printf(" {"); 1756 if (cmd->len & F_NOT) 1757 printf(" not"); 1758 print_newports((ipfw_insn_u16 *)cmd, proto, 1759 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1760 break; 1761 1762 case O_PROTO: { 1763 struct protoent *pe = NULL; 1764 1765 if ((cmd->len & F_OR) && !or_block) 1766 printf(" {"); 1767 if (cmd->len & F_NOT) 1768 printf(" not"); 1769 proto = cmd->arg1; 1770 pe = getprotobynumber(cmd->arg1); 1771 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) && 1772 !(flags & HAVE_PROTO)) 1773 show_prerequisites(&flags, 1774 HAVE_IP | HAVE_OPTIONS, 0); 1775 if (flags & HAVE_OPTIONS) 1776 printf(" proto"); 1777 if (pe) 1778 printf(" %s", pe->p_name); 1779 else 1780 printf(" %u", cmd->arg1); 1781 } 1782 flags |= HAVE_PROTO; 1783 break; 1784 1785 default: /*options ... */ 1786 if (!(cmd->len & (F_OR|F_NOT))) 1787 if (((cmd->opcode == O_IP6) && 1788 (flags & HAVE_PROTO6)) || 1789 ((cmd->opcode == O_IP4) && 1790 (flags & HAVE_PROTO4))) 1791 break; 1792 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0); 1793 if ((cmd->len & F_OR) && !or_block) 1794 printf(" {"); 1795 if (cmd->len & F_NOT && cmd->opcode != O_IN) 1796 printf(" not"); 1797 switch(cmd->opcode) { 1798 case O_MACADDR2: { 1799 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd; 1800 1801 printf(" MAC"); 1802 print_mac(m->addr, m->mask); 1803 print_mac(m->addr + 6, m->mask + 6); 1804 } 1805 break; 1806 1807 case O_MAC_TYPE: 1808 print_newports((ipfw_insn_u16 *)cmd, 1809 IPPROTO_ETHERTYPE, cmd->opcode); 1810 break; 1811 1812 1813 case O_FRAG: 1814 printf(" frag"); 1815 break; 1816 1817 case O_IN: 1818 printf(cmd->len & F_NOT ? " out" : " in"); 1819 break; 1820 1821 case O_DIVERTED: 1822 switch (cmd->arg1) { 1823 case 3: 1824 printf(" diverted"); 1825 break; 1826 case 1: 1827 printf(" diverted-loopback"); 1828 break; 1829 case 2: 1830 printf(" diverted-output"); 1831 break; 1832 default: 1833 printf(" diverted-?<%u>", cmd->arg1); 1834 break; 1835 } 1836 break; 1837 1838 case O_LAYER2: 1839 printf(" layer2"); 1840 break; 1841 case O_XMIT: 1842 case O_RECV: 1843 case O_VIA: 1844 { 1845 char const *s; 1846 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd; 1847 1848 if (cmd->opcode == O_XMIT) 1849 s = "xmit"; 1850 else if (cmd->opcode == O_RECV) 1851 s = "recv"; 1852 else /* if (cmd->opcode == O_VIA) */ 1853 s = "via"; 1854 if (cmdif->name[0] == '\0') 1855 printf(" %s %s", s, 1856 inet_ntoa(cmdif->p.ip)); 1857 else 1858 printf(" %s %s", s, cmdif->name); 1859 1860 break; 1861 } 1862 case O_IPID: 1863 if (F_LEN(cmd) == 1) 1864 printf(" ipid %u", cmd->arg1 ); 1865 else 1866 print_newports((ipfw_insn_u16 *)cmd, 0, 1867 O_IPID); 1868 break; 1869 1870 case O_IPTTL: 1871 if (F_LEN(cmd) == 1) 1872 printf(" ipttl %u", cmd->arg1 ); 1873 else 1874 print_newports((ipfw_insn_u16 *)cmd, 0, 1875 O_IPTTL); 1876 break; 1877 1878 case O_IPVER: 1879 printf(" ipver %u", cmd->arg1 ); 1880 break; 1881 1882 case O_IPPRECEDENCE: 1883 printf(" ipprecedence %u", (cmd->arg1) >> 5 ); 1884 break; 1885 1886 case O_IPLEN: 1887 if (F_LEN(cmd) == 1) 1888 printf(" iplen %u", cmd->arg1 ); 1889 else 1890 print_newports((ipfw_insn_u16 *)cmd, 0, 1891 O_IPLEN); 1892 break; 1893 1894 case O_IPOPT: 1895 print_flags("ipoptions", cmd, f_ipopts); 1896 break; 1897 1898 case O_IPTOS: 1899 print_flags("iptos", cmd, f_iptos); 1900 break; 1901 1902 case O_ICMPTYPE: 1903 print_icmptypes((ipfw_insn_u32 *)cmd); 1904 break; 1905 1906 case O_ESTAB: 1907 printf(" established"); 1908 break; 1909 1910 case O_TCPDATALEN: 1911 if (F_LEN(cmd) == 1) 1912 printf(" tcpdatalen %u", cmd->arg1 ); 1913 else 1914 print_newports((ipfw_insn_u16 *)cmd, 0, 1915 O_TCPDATALEN); 1916 break; 1917 1918 case O_TCPFLAGS: 1919 print_flags("tcpflags", cmd, f_tcpflags); 1920 break; 1921 1922 case O_TCPOPTS: 1923 print_flags("tcpoptions", cmd, f_tcpopts); 1924 break; 1925 1926 case O_TCPWIN: 1927 printf(" tcpwin %d", ntohs(cmd->arg1)); 1928 break; 1929 1930 case O_TCPACK: 1931 printf(" tcpack %d", ntohl(cmd32->d[0])); 1932 break; 1933 1934 case O_TCPSEQ: 1935 printf(" tcpseq %d", ntohl(cmd32->d[0])); 1936 break; 1937 1938 case O_UID: 1939 { 1940 struct passwd *pwd = getpwuid(cmd32->d[0]); 1941 1942 if (pwd) 1943 printf(" uid %s", pwd->pw_name); 1944 else 1945 printf(" uid %u", cmd32->d[0]); 1946 } 1947 break; 1948 1949 case O_GID: 1950 { 1951 struct group *grp = getgrgid(cmd32->d[0]); 1952 1953 if (grp) 1954 printf(" gid %s", grp->gr_name); 1955 else 1956 printf(" gid %u", cmd32->d[0]); 1957 } 1958 break; 1959 1960 case O_JAIL: 1961 printf(" jail %d", cmd32->d[0]); 1962 break; 1963 1964 case O_VERREVPATH: 1965 printf(" verrevpath"); 1966 break; 1967 1968 case O_VERSRCREACH: 1969 printf(" versrcreach"); 1970 break; 1971 1972 case O_ANTISPOOF: 1973 printf(" antispoof"); 1974 break; 1975 1976 case O_IPSEC: 1977 printf(" ipsec"); 1978 break; 1979 1980 case O_NOP: 1981 comment = (char *)(cmd + 1); 1982 break; 1983 1984 case O_KEEP_STATE: 1985 printf(" keep-state"); 1986 break; 1987 1988 case O_LIMIT: { 1989 struct _s_x *p = limit_masks; 1990 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 1991 uint8_t x = c->limit_mask; 1992 char const *comma = " "; 1993 1994 printf(" limit"); 1995 for (; p->x != 0 ; p++) 1996 if ((x & p->x) == p->x) { 1997 x &= ~p->x; 1998 printf("%s%s", comma, p->s); 1999 comma = ","; 2000 } 2001 PRINT_UINT_ARG(" ", c->conn_limit); 2002 break; 2003 } 2004 2005 case O_IP6: 2006 printf(" ip6"); 2007 break; 2008 2009 case O_IP4: 2010 printf(" ip4"); 2011 break; 2012 2013 case O_ICMP6TYPE: 2014 print_icmp6types((ipfw_insn_u32 *)cmd); 2015 break; 2016 2017 case O_EXT_HDR: 2018 print_ext6hdr( (ipfw_insn *) cmd ); 2019 break; 2020 2021 case O_TAGGED: 2022 if (F_LEN(cmd) == 1) 2023 PRINT_UINT_ARG(" tagged ", cmd->arg1); 2024 else 2025 print_newports((ipfw_insn_u16 *)cmd, 0, 2026 O_TAGGED); 2027 break; 2028 2029 default: 2030 printf(" [opcode %d len %d]", 2031 cmd->opcode, cmd->len); 2032 } 2033 } 2034 if (cmd->len & F_OR) { 2035 printf(" or"); 2036 or_block = 1; 2037 } else if (or_block) { 2038 printf(" }"); 2039 or_block = 0; 2040 } 2041 } 2042 show_prerequisites(&flags, HAVE_IP, 0); 2043 if (comment) 2044 printf(" // %s", comment); 2045 printf("\n"); 2046 } 2047 2048 static void 2049 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth) 2050 { 2051 struct protoent *pe; 2052 struct in_addr a; 2053 uint16_t rulenum; 2054 char buf[INET6_ADDRSTRLEN]; 2055 2056 if (!do_expired) { 2057 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT)) 2058 return; 2059 } 2060 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 2061 printf("%05d", rulenum); 2062 if (pcwidth>0 || bcwidth>0) 2063 printf(" %*llu %*llu (%ds)", pcwidth, 2064 align_uint64(&d->pcnt), bcwidth, 2065 align_uint64(&d->bcnt), d->expire); 2066 switch (d->dyn_type) { 2067 case O_LIMIT_PARENT: 2068 printf(" PARENT %d", d->count); 2069 break; 2070 case O_LIMIT: 2071 printf(" LIMIT"); 2072 break; 2073 case O_KEEP_STATE: /* bidir, no mask */ 2074 printf(" STATE"); 2075 break; 2076 } 2077 2078 if ((pe = getprotobynumber(d->id.proto)) != NULL) 2079 printf(" %s", pe->p_name); 2080 else 2081 printf(" proto %u", d->id.proto); 2082 2083 if (d->id.addr_type == 4) { 2084 a.s_addr = htonl(d->id.src_ip); 2085 printf(" %s %d", inet_ntoa(a), d->id.src_port); 2086 2087 a.s_addr = htonl(d->id.dst_ip); 2088 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port); 2089 } else if (d->id.addr_type == 6) { 2090 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf, 2091 sizeof(buf)), d->id.src_port); 2092 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf, 2093 sizeof(buf)), d->id.dst_port); 2094 } else 2095 printf(" UNKNOWN <-> UNKNOWN\n"); 2096 2097 printf("\n"); 2098 } 2099 2100 static int 2101 sort_q(const void *pa, const void *pb) 2102 { 2103 int rev = (do_sort < 0); 2104 int field = rev ? -do_sort : do_sort; 2105 long long res = 0; 2106 const struct dn_flow_queue *a = pa; 2107 const struct dn_flow_queue *b = pb; 2108 2109 switch (field) { 2110 case 1: /* pkts */ 2111 res = a->len - b->len; 2112 break; 2113 case 2: /* bytes */ 2114 res = a->len_bytes - b->len_bytes; 2115 break; 2116 2117 case 3: /* tot pkts */ 2118 res = a->tot_pkts - b->tot_pkts; 2119 break; 2120 2121 case 4: /* tot bytes */ 2122 res = a->tot_bytes - b->tot_bytes; 2123 break; 2124 } 2125 if (res < 0) 2126 res = -1; 2127 if (res > 0) 2128 res = 1; 2129 return (int)(rev ? res : -res); 2130 } 2131 2132 static void 2133 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q) 2134 { 2135 int l; 2136 int index_printed, indexes = 0; 2137 char buff[255]; 2138 struct protoent *pe; 2139 2140 if (fs->rq_elements == 0) 2141 return; 2142 2143 if (do_sort != 0) 2144 heapsort(q, fs->rq_elements, sizeof *q, sort_q); 2145 2146 /* Print IPv4 flows */ 2147 index_printed = 0; 2148 for (l = 0; l < fs->rq_elements; l++) { 2149 struct in_addr ina; 2150 2151 /* XXX: Should check for IPv4 flows */ 2152 if (IS_IP6_FLOW_ID(&(q[l].id))) 2153 continue; 2154 2155 if (!index_printed) { 2156 index_printed = 1; 2157 if (indexes > 0) /* currently a no-op */ 2158 printf("\n"); 2159 indexes++; 2160 printf(" " 2161 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n", 2162 fs->flow_mask.proto, 2163 fs->flow_mask.src_ip, fs->flow_mask.src_port, 2164 fs->flow_mask.dst_ip, fs->flow_mask.dst_port); 2165 2166 printf("BKT Prot ___Source IP/port____ " 2167 "____Dest. IP/port____ " 2168 "Tot_pkt/bytes Pkt/Byte Drp\n"); 2169 } 2170 2171 printf("%3d ", q[l].hash_slot); 2172 pe = getprotobynumber(q[l].id.proto); 2173 if (pe) 2174 printf("%-4s ", pe->p_name); 2175 else 2176 printf("%4u ", q[l].id.proto); 2177 ina.s_addr = htonl(q[l].id.src_ip); 2178 printf("%15s/%-5d ", 2179 inet_ntoa(ina), q[l].id.src_port); 2180 ina.s_addr = htonl(q[l].id.dst_ip); 2181 printf("%15s/%-5d ", 2182 inet_ntoa(ina), q[l].id.dst_port); 2183 printf("%4qu %8qu %2u %4u %3u\n", 2184 q[l].tot_pkts, q[l].tot_bytes, 2185 q[l].len, q[l].len_bytes, q[l].drops); 2186 if (verbose) 2187 printf(" S %20qd F %20qd\n", 2188 q[l].S, q[l].F); 2189 } 2190 2191 /* Print IPv6 flows */ 2192 index_printed = 0; 2193 for (l = 0; l < fs->rq_elements; l++) { 2194 if (!IS_IP6_FLOW_ID(&(q[l].id))) 2195 continue; 2196 2197 if (!index_printed) { 2198 index_printed = 1; 2199 if (indexes > 0) 2200 printf("\n"); 2201 indexes++; 2202 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ", 2203 fs->flow_mask.proto, fs->flow_mask.flow_id6); 2204 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6), 2205 buff, sizeof(buff)); 2206 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port); 2207 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6), 2208 buff, sizeof(buff) ); 2209 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port); 2210 2211 printf("BKT ___Prot___ _flow-id_ " 2212 "______________Source IPv6/port_______________ " 2213 "_______________Dest. IPv6/port_______________ " 2214 "Tot_pkt/bytes Pkt/Byte Drp\n"); 2215 } 2216 printf("%3d ", q[l].hash_slot); 2217 pe = getprotobynumber(q[l].id.proto); 2218 if (pe != NULL) 2219 printf("%9s ", pe->p_name); 2220 else 2221 printf("%9u ", q[l].id.proto); 2222 printf("%7d %39s/%-5d ", q[l].id.flow_id6, 2223 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)), 2224 q[l].id.src_port); 2225 printf(" %39s/%-5d ", 2226 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)), 2227 q[l].id.dst_port); 2228 printf(" %4qu %8qu %2u %4u %3u\n", 2229 q[l].tot_pkts, q[l].tot_bytes, 2230 q[l].len, q[l].len_bytes, q[l].drops); 2231 if (verbose) 2232 printf(" S %20qd F %20qd\n", q[l].S, q[l].F); 2233 } 2234 } 2235 2236 static void 2237 print_flowset_parms(struct dn_flow_set *fs, char *prefix) 2238 { 2239 int l; 2240 char qs[30]; 2241 char plr[30]; 2242 char red[90]; /* Display RED parameters */ 2243 2244 l = fs->qsize; 2245 if (fs->flags_fs & DN_QSIZE_IS_BYTES) { 2246 if (l >= 8192) 2247 sprintf(qs, "%d KB", l / 1024); 2248 else 2249 sprintf(qs, "%d B", l); 2250 } else 2251 sprintf(qs, "%3d sl.", l); 2252 if (fs->plr) 2253 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff)); 2254 else 2255 plr[0] = '\0'; 2256 if (fs->flags_fs & DN_IS_RED) /* RED parameters */ 2257 sprintf(red, 2258 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f", 2259 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ', 2260 1.0 * fs->w_q / (double)(1 << SCALE_RED), 2261 SCALE_VAL(fs->min_th), 2262 SCALE_VAL(fs->max_th), 2263 1.0 * fs->max_p / (double)(1 << SCALE_RED)); 2264 else 2265 sprintf(red, "droptail"); 2266 2267 printf("%s %s%s %d queues (%d buckets) %s\n", 2268 prefix, qs, plr, fs->rq_elements, fs->rq_size, red); 2269 } 2270 2271 static void 2272 list_pipes(void *data, uint nbytes, int ac, char *av[]) 2273 { 2274 int rulenum; 2275 void *next = data; 2276 struct dn_pipe *p = (struct dn_pipe *) data; 2277 struct dn_flow_set *fs; 2278 struct dn_flow_queue *q; 2279 int l; 2280 2281 if (ac > 0) 2282 rulenum = strtoul(*av++, NULL, 10); 2283 else 2284 rulenum = 0; 2285 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) { 2286 double b = p->bandwidth; 2287 char buf[30]; 2288 char prefix[80]; 2289 2290 if (SLIST_NEXT(p, next) != (struct dn_pipe *)DN_IS_PIPE) 2291 break; /* done with pipes, now queues */ 2292 2293 /* 2294 * compute length, as pipe have variable size 2295 */ 2296 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q); 2297 next = (char *)p + l; 2298 nbytes -= l; 2299 2300 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2) 2301 continue; 2302 2303 /* 2304 * Print rate (or clocking interface) 2305 */ 2306 if (p->if_name[0] != '\0') 2307 sprintf(buf, "%s", p->if_name); 2308 else if (b == 0) 2309 sprintf(buf, "unlimited"); 2310 else if (b >= 1000000) 2311 sprintf(buf, "%7.3f Mbit/s", b/1000000); 2312 else if (b >= 1000) 2313 sprintf(buf, "%7.3f Kbit/s", b/1000); 2314 else 2315 sprintf(buf, "%7.3f bit/s ", b); 2316 2317 sprintf(prefix, "%05d: %s %4d ms ", 2318 p->pipe_nr, buf, p->delay); 2319 print_flowset_parms(&(p->fs), prefix); 2320 if (verbose) 2321 printf(" V %20qd\n", p->V >> MY_M); 2322 2323 q = (struct dn_flow_queue *)(p+1); 2324 list_queues(&(p->fs), q); 2325 } 2326 for (fs = next; nbytes >= sizeof *fs; fs = next) { 2327 char prefix[80]; 2328 2329 if (SLIST_NEXT(fs, next) != (struct dn_flow_set *)DN_IS_QUEUE) 2330 break; 2331 l = sizeof(*fs) + fs->rq_elements * sizeof(*q); 2332 next = (char *)fs + l; 2333 nbytes -= l; 2334 2335 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) || 2336 (rulenum != fs->parent_nr && do_pipe == 1))) { 2337 continue; 2338 } 2339 2340 q = (struct dn_flow_queue *)(fs+1); 2341 sprintf(prefix, "q%05d: weight %d pipe %d ", 2342 fs->fs_nr, fs->weight, fs->parent_nr); 2343 print_flowset_parms(fs, prefix); 2344 list_queues(fs, q); 2345 } 2346 } 2347 2348 /* 2349 * This one handles all set-related commands 2350 * ipfw set { show | enable | disable } 2351 * ipfw set swap X Y 2352 * ipfw set move X to Y 2353 * ipfw set move rule X to Y 2354 */ 2355 static void 2356 sets_handler(int ac, char *av[]) 2357 { 2358 uint32_t set_disable, masks[2]; 2359 int i, nbytes; 2360 uint16_t rulenum; 2361 uint8_t cmd, new_set; 2362 2363 ac--; 2364 av++; 2365 2366 if (!ac) 2367 errx(EX_USAGE, "set needs command"); 2368 if (_substrcmp(*av, "show") == 0) { 2369 void *data; 2370 char const *msg; 2371 2372 nbytes = sizeof(struct ip_fw); 2373 if ((data = calloc(1, nbytes)) == NULL) 2374 err(EX_OSERR, "calloc"); 2375 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0) 2376 err(EX_OSERR, "getsockopt(IP_FW_GET)"); 2377 bcopy(&((struct ip_fw *)data)->next_rule, 2378 &set_disable, sizeof(set_disable)); 2379 2380 for (i = 0, msg = "disable" ; i < RESVD_SET; i++) 2381 if ((set_disable & (1<<i))) { 2382 printf("%s %d", msg, i); 2383 msg = ""; 2384 } 2385 msg = (set_disable) ? " enable" : "enable"; 2386 for (i = 0; i < RESVD_SET; i++) 2387 if (!(set_disable & (1<<i))) { 2388 printf("%s %d", msg, i); 2389 msg = ""; 2390 } 2391 printf("\n"); 2392 } else if (_substrcmp(*av, "swap") == 0) { 2393 ac--; av++; 2394 if (ac != 2) 2395 errx(EX_USAGE, "set swap needs 2 set numbers\n"); 2396 rulenum = atoi(av[0]); 2397 new_set = atoi(av[1]); 2398 if (!isdigit(*(av[0])) || rulenum > RESVD_SET) 2399 errx(EX_DATAERR, "invalid set number %s\n", av[0]); 2400 if (!isdigit(*(av[1])) || new_set > RESVD_SET) 2401 errx(EX_DATAERR, "invalid set number %s\n", av[1]); 2402 masks[0] = (4 << 24) | (new_set << 16) | (rulenum); 2403 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 2404 } else if (_substrcmp(*av, "move") == 0) { 2405 ac--; av++; 2406 if (ac && _substrcmp(*av, "rule") == 0) { 2407 cmd = 2; 2408 ac--; av++; 2409 } else 2410 cmd = 3; 2411 if (ac != 3 || _substrcmp(av[1], "to") != 0) 2412 errx(EX_USAGE, "syntax: set move [rule] X to Y\n"); 2413 rulenum = atoi(av[0]); 2414 new_set = atoi(av[2]); 2415 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) || 2416 (cmd == 2 && rulenum == 65535) ) 2417 errx(EX_DATAERR, "invalid source number %s\n", av[0]); 2418 if (!isdigit(*(av[2])) || new_set > RESVD_SET) 2419 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]); 2420 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum); 2421 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 2422 } else if (_substrcmp(*av, "disable") == 0 || 2423 _substrcmp(*av, "enable") == 0 ) { 2424 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0; 2425 2426 ac--; av++; 2427 masks[0] = masks[1] = 0; 2428 2429 while (ac) { 2430 if (isdigit(**av)) { 2431 i = atoi(*av); 2432 if (i < 0 || i > RESVD_SET) 2433 errx(EX_DATAERR, 2434 "invalid set number %d\n", i); 2435 masks[which] |= (1<<i); 2436 } else if (_substrcmp(*av, "disable") == 0) 2437 which = 0; 2438 else if (_substrcmp(*av, "enable") == 0) 2439 which = 1; 2440 else 2441 errx(EX_DATAERR, 2442 "invalid set command %s\n", *av); 2443 av++; ac--; 2444 } 2445 if ( (masks[0] & masks[1]) != 0 ) 2446 errx(EX_DATAERR, 2447 "cannot enable and disable the same set\n"); 2448 2449 i = do_cmd(IP_FW_DEL, masks, sizeof(masks)); 2450 if (i) 2451 warn("set enable/disable: setsockopt(IP_FW_DEL)"); 2452 } else 2453 errx(EX_USAGE, "invalid set command %s\n", *av); 2454 } 2455 2456 static void 2457 sysctl_handler(int ac, char *av[], int which) 2458 { 2459 ac--; 2460 av++; 2461 2462 if (ac == 0) { 2463 warnx("missing keyword to enable/disable\n"); 2464 } else if (_substrcmp(*av, "firewall") == 0) { 2465 sysctlbyname("net.inet.ip.fw.enable", NULL, 0, 2466 &which, sizeof(which)); 2467 } else if (_substrcmp(*av, "one_pass") == 0) { 2468 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0, 2469 &which, sizeof(which)); 2470 } else if (_substrcmp(*av, "debug") == 0) { 2471 sysctlbyname("net.inet.ip.fw.debug", NULL, 0, 2472 &which, sizeof(which)); 2473 } else if (_substrcmp(*av, "verbose") == 0) { 2474 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0, 2475 &which, sizeof(which)); 2476 } else if (_substrcmp(*av, "dyn_keepalive") == 0) { 2477 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0, 2478 &which, sizeof(which)); 2479 } else if (_substrcmp(*av, "altq") == 0) { 2480 altq_set_enabled(which); 2481 } else { 2482 warnx("unrecognize enable/disable keyword: %s\n", *av); 2483 } 2484 } 2485 2486 static void 2487 list(int ac, char *av[], int show_counters) 2488 { 2489 struct ip_fw *r; 2490 ipfw_dyn_rule *dynrules, *d; 2491 2492 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r))) 2493 char *lim; 2494 void *data = NULL; 2495 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width; 2496 int exitval = EX_OK; 2497 int lac; 2498 char **lav; 2499 u_long rnum, last; 2500 char *endptr; 2501 int seen = 0; 2502 uint8_t set; 2503 2504 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET; 2505 int nalloc = 1024; /* start somewhere... */ 2506 2507 last = 0; 2508 2509 if (test_only) { 2510 fprintf(stderr, "Testing only, list disabled\n"); 2511 return; 2512 } 2513 2514 ac--; 2515 av++; 2516 2517 /* get rules or pipes from kernel, resizing array as necessary */ 2518 nbytes = nalloc; 2519 2520 while (nbytes >= nalloc) { 2521 nalloc = nalloc * 2 + 200; 2522 nbytes = nalloc; 2523 if ((data = realloc(data, nbytes)) == NULL) 2524 err(EX_OSERR, "realloc"); 2525 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0) 2526 err(EX_OSERR, "getsockopt(IP_%s_GET)", 2527 do_pipe ? "DUMMYNET" : "FW"); 2528 } 2529 2530 if (do_pipe) { 2531 list_pipes(data, nbytes, ac, av); 2532 goto done; 2533 } 2534 2535 /* 2536 * Count static rules. They have variable size so we 2537 * need to scan the list to count them. 2538 */ 2539 for (nstat = 1, r = data, lim = (char *)data + nbytes; 2540 r->rulenum < 65535 && (char *)r < lim; 2541 ++nstat, r = NEXT(r) ) 2542 ; /* nothing */ 2543 2544 /* 2545 * Count dynamic rules. This is easier as they have 2546 * fixed size. 2547 */ 2548 r = NEXT(r); 2549 dynrules = (ipfw_dyn_rule *)r ; 2550 n = (char *)r - (char *)data; 2551 ndyn = (nbytes - n) / sizeof *dynrules; 2552 2553 /* if showing stats, figure out column widths ahead of time */ 2554 bcwidth = pcwidth = 0; 2555 if (show_counters) { 2556 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) { 2557 /* skip rules from another set */ 2558 if (use_set && r->set != use_set - 1) 2559 continue; 2560 2561 /* packet counter */ 2562 width = snprintf(NULL, 0, "%llu", 2563 align_uint64(&r->pcnt)); 2564 if (width > pcwidth) 2565 pcwidth = width; 2566 2567 /* byte counter */ 2568 width = snprintf(NULL, 0, "%llu", 2569 align_uint64(&r->bcnt)); 2570 if (width > bcwidth) 2571 bcwidth = width; 2572 } 2573 } 2574 if (do_dynamic && ndyn) { 2575 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 2576 if (use_set) { 2577 /* skip rules from another set */ 2578 bcopy((char *)&d->rule + sizeof(uint16_t), 2579 &set, sizeof(uint8_t)); 2580 if (set != use_set - 1) 2581 continue; 2582 } 2583 width = snprintf(NULL, 0, "%llu", 2584 align_uint64(&d->pcnt)); 2585 if (width > pcwidth) 2586 pcwidth = width; 2587 2588 width = snprintf(NULL, 0, "%llu", 2589 align_uint64(&d->bcnt)); 2590 if (width > bcwidth) 2591 bcwidth = width; 2592 } 2593 } 2594 /* if no rule numbers were specified, list all rules */ 2595 if (ac == 0) { 2596 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) { 2597 if (use_set && r->set != use_set - 1) 2598 continue; 2599 show_ipfw(r, pcwidth, bcwidth); 2600 } 2601 2602 if (do_dynamic && ndyn) { 2603 printf("## Dynamic rules (%d):\n", ndyn); 2604 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 2605 if (use_set) { 2606 bcopy((char *)&d->rule + sizeof(uint16_t), 2607 &set, sizeof(uint8_t)); 2608 if (set != use_set - 1) 2609 continue; 2610 } 2611 show_dyn_ipfw(d, pcwidth, bcwidth); 2612 } 2613 } 2614 goto done; 2615 } 2616 2617 /* display specific rules requested on command line */ 2618 2619 for (lac = ac, lav = av; lac != 0; lac--) { 2620 /* convert command line rule # */ 2621 last = rnum = strtoul(*lav++, &endptr, 10); 2622 if (*endptr == '-') 2623 last = strtoul(endptr+1, &endptr, 10); 2624 if (*endptr) { 2625 exitval = EX_USAGE; 2626 warnx("invalid rule number: %s", *(lav - 1)); 2627 continue; 2628 } 2629 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) { 2630 if (r->rulenum > last) 2631 break; 2632 if (use_set && r->set != use_set - 1) 2633 continue; 2634 if (r->rulenum >= rnum && r->rulenum <= last) { 2635 show_ipfw(r, pcwidth, bcwidth); 2636 seen = 1; 2637 } 2638 } 2639 if (!seen) { 2640 /* give precedence to other error(s) */ 2641 if (exitval == EX_OK) 2642 exitval = EX_UNAVAILABLE; 2643 warnx("rule %lu does not exist", rnum); 2644 } 2645 } 2646 2647 if (do_dynamic && ndyn) { 2648 printf("## Dynamic rules:\n"); 2649 for (lac = ac, lav = av; lac != 0; lac--) { 2650 last = rnum = strtoul(*lav++, &endptr, 10); 2651 if (*endptr == '-') 2652 last = strtoul(endptr+1, &endptr, 10); 2653 if (*endptr) 2654 /* already warned */ 2655 continue; 2656 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 2657 uint16_t rulenum; 2658 2659 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 2660 if (rulenum > rnum) 2661 break; 2662 if (use_set) { 2663 bcopy((char *)&d->rule + sizeof(uint16_t), 2664 &set, sizeof(uint8_t)); 2665 if (set != use_set - 1) 2666 continue; 2667 } 2668 if (r->rulenum >= rnum && r->rulenum <= last) 2669 show_dyn_ipfw(d, pcwidth, bcwidth); 2670 } 2671 } 2672 } 2673 2674 ac = 0; 2675 2676 done: 2677 free(data); 2678 2679 if (exitval != EX_OK) 2680 exit(exitval); 2681 #undef NEXT 2682 } 2683 2684 static void 2685 show_usage(void) 2686 { 2687 fprintf(stderr, "usage: ipfw [options]\n" 2688 "do \"ipfw -h\" or see ipfw manpage for details\n" 2689 ); 2690 exit(EX_USAGE); 2691 } 2692 2693 static void 2694 help(void) 2695 { 2696 fprintf(stderr, 2697 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n" 2698 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n" 2699 "add [num] [set N] [prob x] RULE-BODY\n" 2700 "{pipe|queue} N config PIPE-BODY\n" 2701 "[pipe|queue] {zero|delete|show} [N{,N}]\n" 2702 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|reset|\n" 2703 " reverse|proxy_only|redirect_addr linkspec|\n" 2704 " redirect_port linkspec|redirect_proto linkspec}\n" 2705 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n" 2706 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n" 2707 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n" 2708 "\n" 2709 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n" 2710 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n" 2711 " skipto N | {divert|tee} PORT | forward ADDR |\n" 2712 " pipe N | queue N | nat N\n" 2713 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n" 2714 "ADDR: [ MAC dst src ether_type ] \n" 2715 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n" 2716 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n" 2717 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n" 2718 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n" 2719 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n" 2720 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n" 2721 "OPTION_LIST: OPTION [OPTION_LIST]\n" 2722 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n" 2723 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n" 2724 " {dst-port|src-port} LIST |\n" 2725 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n" 2726 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n" 2727 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n" 2728 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] |\n" 2729 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n" 2730 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n" 2731 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n" 2732 ); 2733 exit(0); 2734 } 2735 2736 2737 static int 2738 lookup_host (char *host, struct in_addr *ipaddr) 2739 { 2740 struct hostent *he; 2741 2742 if (!inet_aton(host, ipaddr)) { 2743 if ((he = gethostbyname(host)) == NULL) 2744 return(-1); 2745 *ipaddr = *(struct in_addr *)he->h_addr_list[0]; 2746 } 2747 return(0); 2748 } 2749 2750 /* 2751 * fills the addr and mask fields in the instruction as appropriate from av. 2752 * Update length as appropriate. 2753 * The following formats are allowed: 2754 * me returns O_IP_*_ME 2755 * 1.2.3.4 single IP address 2756 * 1.2.3.4:5.6.7.8 address:mask 2757 * 1.2.3.4/24 address/mask 2758 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet 2759 * We can have multiple comma-separated address/mask entries. 2760 */ 2761 static void 2762 fill_ip(ipfw_insn_ip *cmd, char *av) 2763 { 2764 int len = 0; 2765 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d; 2766 2767 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 2768 2769 if (_substrcmp(av, "any") == 0) 2770 return; 2771 2772 if (_substrcmp(av, "me") == 0) { 2773 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2774 return; 2775 } 2776 2777 if (strncmp(av, "table(", 6) == 0) { 2778 char *p = strchr(av + 6, ','); 2779 2780 if (p) 2781 *p++ = '\0'; 2782 cmd->o.opcode = O_IP_DST_LOOKUP; 2783 cmd->o.arg1 = strtoul(av + 6, NULL, 0); 2784 if (p) { 2785 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2786 d[0] = strtoul(p, NULL, 0); 2787 } else 2788 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 2789 return; 2790 } 2791 2792 while (av) { 2793 /* 2794 * After the address we can have '/' or ':' indicating a mask, 2795 * ',' indicating another address follows, '{' indicating a 2796 * set of addresses of unspecified size. 2797 */ 2798 char *t = NULL, *p = strpbrk(av, "/:,{"); 2799 int masklen; 2800 char md, nd; 2801 2802 if (p) { 2803 md = *p; 2804 *p++ = '\0'; 2805 if ((t = strpbrk(p, ",{")) != NULL) { 2806 nd = *t; 2807 *t = '\0'; 2808 } 2809 } else 2810 md = '\0'; 2811 2812 if (lookup_host(av, (struct in_addr *)&d[0]) != 0) 2813 errx(EX_NOHOST, "hostname ``%s'' unknown", av); 2814 switch (md) { 2815 case ':': 2816 if (!inet_aton(p, (struct in_addr *)&d[1])) 2817 errx(EX_DATAERR, "bad netmask ``%s''", p); 2818 break; 2819 case '/': 2820 masklen = atoi(p); 2821 if (masklen == 0) 2822 d[1] = htonl(0); /* mask */ 2823 else if (masklen > 32) 2824 errx(EX_DATAERR, "bad width ``%s''", p); 2825 else 2826 d[1] = htonl(~0 << (32 - masklen)); 2827 break; 2828 case '{': /* no mask, assume /24 and put back the '{' */ 2829 d[1] = htonl(~0 << (32 - 24)); 2830 *(--p) = md; 2831 break; 2832 2833 case ',': /* single address plus continuation */ 2834 *(--p) = md; 2835 /* FALLTHROUGH */ 2836 case 0: /* initialization value */ 2837 default: 2838 d[1] = htonl(~0); /* force /32 */ 2839 break; 2840 } 2841 d[0] &= d[1]; /* mask base address with mask */ 2842 if (t) 2843 *t = nd; 2844 /* find next separator */ 2845 if (p) 2846 p = strpbrk(p, ",{"); 2847 if (p && *p == '{') { 2848 /* 2849 * We have a set of addresses. They are stored as follows: 2850 * arg1 is the set size (powers of 2, 2..256) 2851 * addr is the base address IN HOST FORMAT 2852 * mask.. is an array of arg1 bits (rounded up to 2853 * the next multiple of 32) with bits set 2854 * for each host in the map. 2855 */ 2856 uint32_t *map = (uint32_t *)&cmd->mask; 2857 int low, high; 2858 int i = contigmask((uint8_t *)&(d[1]), 32); 2859 2860 if (len > 0) 2861 errx(EX_DATAERR, "address set cannot be in a list"); 2862 if (i < 24 || i > 31) 2863 errx(EX_DATAERR, "invalid set with mask %d\n", i); 2864 cmd->o.arg1 = 1<<(32-i); /* map length */ 2865 d[0] = ntohl(d[0]); /* base addr in host format */ 2866 cmd->o.opcode = O_IP_DST_SET; /* default */ 2867 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32; 2868 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++) 2869 map[i] = 0; /* clear map */ 2870 2871 av = p + 1; 2872 low = d[0] & 0xff; 2873 high = low + cmd->o.arg1 - 1; 2874 /* 2875 * Here, i stores the previous value when we specify a range 2876 * of addresses within a mask, e.g. 45-63. i = -1 means we 2877 * have no previous value. 2878 */ 2879 i = -1; /* previous value in a range */ 2880 while (isdigit(*av)) { 2881 char *s; 2882 int a = strtol(av, &s, 0); 2883 2884 if (s == av) { /* no parameter */ 2885 if (*av != '}') 2886 errx(EX_DATAERR, "set not closed\n"); 2887 if (i != -1) 2888 errx(EX_DATAERR, "incomplete range %d-", i); 2889 break; 2890 } 2891 if (a < low || a > high) 2892 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n", 2893 a, low, high); 2894 a -= low; 2895 if (i == -1) /* no previous in range */ 2896 i = a; 2897 else { /* check that range is valid */ 2898 if (i > a) 2899 errx(EX_DATAERR, "invalid range %d-%d", 2900 i+low, a+low); 2901 if (*s == '-') 2902 errx(EX_DATAERR, "double '-' in range"); 2903 } 2904 for (; i <= a; i++) 2905 map[i/32] |= 1<<(i & 31); 2906 i = -1; 2907 if (*s == '-') 2908 i = a; 2909 else if (*s == '}') 2910 break; 2911 av = s+1; 2912 } 2913 return; 2914 } 2915 av = p; 2916 if (av) /* then *av must be a ',' */ 2917 av++; 2918 2919 /* Check this entry */ 2920 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */ 2921 /* 2922 * 'any' turns the entire list into a NOP. 2923 * 'not any' never matches, so it is removed from the 2924 * list unless it is the only item, in which case we 2925 * report an error. 2926 */ 2927 if (cmd->o.len & F_NOT) { /* "not any" never matches */ 2928 if (av == NULL && len == 0) /* only this entry */ 2929 errx(EX_DATAERR, "not any never matches"); 2930 } 2931 /* else do nothing and skip this entry */ 2932 return; 2933 } 2934 /* A single IP can be stored in an optimized format */ 2935 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) { 2936 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2937 return; 2938 } 2939 len += 2; /* two words... */ 2940 d += 2; 2941 } /* end while */ 2942 if (len + 1 > F_LEN_MASK) 2943 errx(EX_DATAERR, "address list too long"); 2944 cmd->o.len |= len+1; 2945 } 2946 2947 2948 /* Try to find ipv6 address by hostname */ 2949 static int 2950 lookup_host6 (char *host, struct in6_addr *ip6addr) 2951 { 2952 struct hostent *he; 2953 2954 if (!inet_pton(AF_INET6, host, ip6addr)) { 2955 if ((he = gethostbyname2(host, AF_INET6)) == NULL) 2956 return(-1); 2957 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr)); 2958 } 2959 return(0); 2960 } 2961 2962 2963 /* n2mask sets n bits of the mask */ 2964 static void 2965 n2mask(struct in6_addr *mask, int n) 2966 { 2967 static int minimask[9] = 2968 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff }; 2969 u_char *p; 2970 2971 memset(mask, 0, sizeof(struct in6_addr)); 2972 p = (u_char *) mask; 2973 for (; n > 0; p++, n -= 8) { 2974 if (n >= 8) 2975 *p = 0xff; 2976 else 2977 *p = minimask[n]; 2978 } 2979 return; 2980 } 2981 2982 2983 /* 2984 * fill the addr and mask fields in the instruction as appropriate from av. 2985 * Update length as appropriate. 2986 * The following formats are allowed: 2987 * any matches any IP6. Actually returns an empty instruction. 2988 * me returns O_IP6_*_ME 2989 * 2990 * 03f1::234:123:0342 single IP6 addres 2991 * 03f1::234:123:0342/24 address/mask 2992 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address 2993 * 2994 * Set of address (as in ipv6) not supported because ipv6 address 2995 * are typically random past the initial prefix. 2996 * Return 1 on success, 0 on failure. 2997 */ 2998 static int 2999 fill_ip6(ipfw_insn_ip6 *cmd, char *av) 3000 { 3001 int len = 0; 3002 struct in6_addr *d = &(cmd->addr6); 3003 /* 3004 * Needed for multiple address. 3005 * Note d[1] points to struct in6_add r mask6 of cmd 3006 */ 3007 3008 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 3009 3010 if (strcmp(av, "any") == 0) 3011 return (1); 3012 3013 3014 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/ 3015 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 3016 return (1); 3017 } 3018 3019 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/ 3020 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 3021 return (1); 3022 } 3023 3024 av = strdup(av); 3025 while (av) { 3026 /* 3027 * After the address we can have '/' indicating a mask, 3028 * or ',' indicating another address follows. 3029 */ 3030 3031 char *p; 3032 int masklen; 3033 char md = '\0'; 3034 3035 if ((p = strpbrk(av, "/,")) ) { 3036 md = *p; /* save the separator */ 3037 *p = '\0'; /* terminate address string */ 3038 p++; /* and skip past it */ 3039 } 3040 /* now p points to NULL, mask or next entry */ 3041 3042 /* lookup stores address in *d as a side effect */ 3043 if (lookup_host6(av, d) != 0) { 3044 /* XXX: failed. Free memory and go */ 3045 errx(EX_DATAERR, "bad address \"%s\"", av); 3046 } 3047 /* next, look at the mask, if any */ 3048 masklen = (md == '/') ? atoi(p) : 128; 3049 if (masklen > 128 || masklen < 0) 3050 errx(EX_DATAERR, "bad width \"%s\''", p); 3051 else 3052 n2mask(&d[1], masklen); 3053 3054 APPLY_MASK(d, &d[1]) /* mask base address with mask */ 3055 3056 /* find next separator */ 3057 3058 if (md == '/') { /* find separator past the mask */ 3059 p = strpbrk(p, ","); 3060 if (p != NULL) 3061 p++; 3062 } 3063 av = p; 3064 3065 /* Check this entry */ 3066 if (masklen == 0) { 3067 /* 3068 * 'any' turns the entire list into a NOP. 3069 * 'not any' never matches, so it is removed from the 3070 * list unless it is the only item, in which case we 3071 * report an error. 3072 */ 3073 if (cmd->o.len & F_NOT && av == NULL && len == 0) 3074 errx(EX_DATAERR, "not any never matches"); 3075 continue; 3076 } 3077 3078 /* 3079 * A single IP can be stored alone 3080 */ 3081 if (masklen == 128 && av == NULL && len == 0) { 3082 len = F_INSN_SIZE(struct in6_addr); 3083 break; 3084 } 3085 3086 /* Update length and pointer to arguments */ 3087 len += F_INSN_SIZE(struct in6_addr)*2; 3088 d += 2; 3089 } /* end while */ 3090 3091 /* 3092 * Total length of the command, remember that 1 is the size of 3093 * the base command. 3094 */ 3095 if (len + 1 > F_LEN_MASK) 3096 errx(EX_DATAERR, "address list too long"); 3097 cmd->o.len |= len+1; 3098 free(av); 3099 return (1); 3100 } 3101 3102 /* 3103 * fills command for ipv6 flow-id filtering 3104 * note that the 20 bit flow number is stored in a array of u_int32_t 3105 * it's supported lists of flow-id, so in the o.arg1 we store how many 3106 * additional flow-id we want to filter, the basic is 1 3107 */ 3108 void 3109 fill_flow6( ipfw_insn_u32 *cmd, char *av ) 3110 { 3111 u_int32_t type; /* Current flow number */ 3112 u_int16_t nflow = 0; /* Current flow index */ 3113 char *s = av; 3114 cmd->d[0] = 0; /* Initializing the base number*/ 3115 3116 while (s) { 3117 av = strsep( &s, ",") ; 3118 type = strtoul(av, &av, 0); 3119 if (*av != ',' && *av != '\0') 3120 errx(EX_DATAERR, "invalid ipv6 flow number %s", av); 3121 if (type > 0xfffff) 3122 errx(EX_DATAERR, "flow number out of range %s", av); 3123 cmd->d[nflow] |= type; 3124 nflow++; 3125 } 3126 if( nflow > 0 ) { 3127 cmd->o.opcode = O_FLOW6ID; 3128 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow; 3129 cmd->o.arg1 = nflow; 3130 } 3131 else { 3132 errx(EX_DATAERR, "invalid ipv6 flow number %s", av); 3133 } 3134 } 3135 3136 static ipfw_insn * 3137 add_srcip6(ipfw_insn *cmd, char *av) 3138 { 3139 3140 fill_ip6((ipfw_insn_ip6 *)cmd, av); 3141 if (F_LEN(cmd) == 0) /* any */ 3142 ; 3143 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */ 3144 cmd->opcode = O_IP6_SRC_ME; 3145 } else if (F_LEN(cmd) == 3146 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) { 3147 /* single IP, no mask*/ 3148 cmd->opcode = O_IP6_SRC; 3149 } else { /* addr/mask opt */ 3150 cmd->opcode = O_IP6_SRC_MASK; 3151 } 3152 return cmd; 3153 } 3154 3155 static ipfw_insn * 3156 add_dstip6(ipfw_insn *cmd, char *av) 3157 { 3158 3159 fill_ip6((ipfw_insn_ip6 *)cmd, av); 3160 if (F_LEN(cmd) == 0) /* any */ 3161 ; 3162 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */ 3163 cmd->opcode = O_IP6_DST_ME; 3164 } else if (F_LEN(cmd) == 3165 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) { 3166 /* single IP, no mask*/ 3167 cmd->opcode = O_IP6_DST; 3168 } else { /* addr/mask opt */ 3169 cmd->opcode = O_IP6_DST_MASK; 3170 } 3171 return cmd; 3172 } 3173 3174 3175 /* 3176 * helper function to process a set of flags and set bits in the 3177 * appropriate masks. 3178 */ 3179 static void 3180 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode, 3181 struct _s_x *flags, char *p) 3182 { 3183 uint8_t set=0, clear=0; 3184 3185 while (p && *p) { 3186 char *q; /* points to the separator */ 3187 int val; 3188 uint8_t *which; /* mask we are working on */ 3189 3190 if (*p == '!') { 3191 p++; 3192 which = &clear; 3193 } else 3194 which = &set; 3195 q = strchr(p, ','); 3196 if (q) 3197 *q++ = '\0'; 3198 val = match_token(flags, p); 3199 if (val <= 0) 3200 errx(EX_DATAERR, "invalid flag %s", p); 3201 *which |= (uint8_t)val; 3202 p = q; 3203 } 3204 cmd->opcode = opcode; 3205 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1; 3206 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8); 3207 } 3208 3209 3210 static void 3211 delete(int ac, char *av[]) 3212 { 3213 uint32_t rulenum; 3214 struct dn_pipe p; 3215 int i; 3216 int exitval = EX_OK; 3217 int do_set = 0; 3218 3219 memset(&p, 0, sizeof p); 3220 3221 av++; ac--; 3222 NEED1("missing rule specification"); 3223 if (ac > 0 && _substrcmp(*av, "set") == 0) { 3224 /* Do not allow using the following syntax: 3225 * ipfw set N delete set M 3226 */ 3227 if (use_set) 3228 errx(EX_DATAERR, "invalid syntax"); 3229 do_set = 1; /* delete set */ 3230 ac--; av++; 3231 } 3232 3233 /* Rule number */ 3234 while (ac && isdigit(**av)) { 3235 i = atoi(*av); av++; ac--; 3236 if (do_nat) { 3237 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i); 3238 if (exitval) { 3239 exitval = EX_UNAVAILABLE; 3240 warn("rule %u not available", i); 3241 } 3242 } else if (do_pipe) { 3243 if (do_pipe == 1) 3244 p.pipe_nr = i; 3245 else 3246 p.fs.fs_nr = i; 3247 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p); 3248 if (i) { 3249 exitval = 1; 3250 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", 3251 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr); 3252 } 3253 } else { 3254 if (use_set) 3255 rulenum = (i & 0xffff) | (5 << 24) | 3256 ((use_set - 1) << 16); 3257 else 3258 rulenum = (i & 0xffff) | (do_set << 24); 3259 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum); 3260 if (i) { 3261 exitval = EX_UNAVAILABLE; 3262 warn("rule %u: setsockopt(IP_FW_DEL)", 3263 rulenum); 3264 } 3265 } 3266 } 3267 if (exitval != EX_OK) 3268 exit(exitval); 3269 } 3270 3271 3272 /* 3273 * fill the interface structure. We do not check the name as we can 3274 * create interfaces dynamically, so checking them at insert time 3275 * makes relatively little sense. 3276 * Interface names containing '*', '?', or '[' are assumed to be shell 3277 * patterns which match interfaces. 3278 */ 3279 static void 3280 fill_iface(ipfw_insn_if *cmd, char *arg) 3281 { 3282 cmd->name[0] = '\0'; 3283 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if); 3284 3285 /* Parse the interface or address */ 3286 if (strcmp(arg, "any") == 0) 3287 cmd->o.len = 0; /* effectively ignore this command */ 3288 else if (!isdigit(*arg)) { 3289 strlcpy(cmd->name, arg, sizeof(cmd->name)); 3290 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0; 3291 } else if (!inet_aton(arg, &cmd->p.ip)) 3292 errx(EX_DATAERR, "bad ip address ``%s''", arg); 3293 } 3294 3295 /* 3296 * Search for interface with name "ifn", and fill n accordingly: 3297 * 3298 * n->ip ip address of interface "ifn" 3299 * n->if_name copy of interface name "ifn" 3300 */ 3301 static void 3302 set_addr_dynamic(const char *ifn, struct cfg_nat *n) 3303 { 3304 size_t needed; 3305 int mib[6]; 3306 char *buf, *lim, *next; 3307 struct if_msghdr *ifm; 3308 struct ifa_msghdr *ifam; 3309 struct sockaddr_dl *sdl; 3310 struct sockaddr_in *sin; 3311 int ifIndex, ifMTU; 3312 3313 mib[0] = CTL_NET; 3314 mib[1] = PF_ROUTE; 3315 mib[2] = 0; 3316 mib[3] = AF_INET; 3317 mib[4] = NET_RT_IFLIST; 3318 mib[5] = 0; 3319 /* 3320 * Get interface data. 3321 */ 3322 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1) 3323 err(1, "iflist-sysctl-estimate"); 3324 if ((buf = malloc(needed)) == NULL) 3325 errx(1, "malloc failed"); 3326 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1) 3327 err(1, "iflist-sysctl-get"); 3328 lim = buf + needed; 3329 /* 3330 * Loop through interfaces until one with 3331 * given name is found. This is done to 3332 * find correct interface index for routing 3333 * message processing. 3334 */ 3335 ifIndex = 0; 3336 next = buf; 3337 while (next < lim) { 3338 ifm = (struct if_msghdr *)next; 3339 next += ifm->ifm_msglen; 3340 if (ifm->ifm_version != RTM_VERSION) { 3341 if (verbose) 3342 warnx("routing message version %d " 3343 "not understood", ifm->ifm_version); 3344 continue; 3345 } 3346 if (ifm->ifm_type == RTM_IFINFO) { 3347 sdl = (struct sockaddr_dl *)(ifm + 1); 3348 if (strlen(ifn) == sdl->sdl_nlen && 3349 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) { 3350 ifIndex = ifm->ifm_index; 3351 ifMTU = ifm->ifm_data.ifi_mtu; 3352 break; 3353 } 3354 } 3355 } 3356 if (!ifIndex) 3357 errx(1, "unknown interface name %s", ifn); 3358 /* 3359 * Get interface address. 3360 */ 3361 sin = NULL; 3362 while (next < lim) { 3363 ifam = (struct ifa_msghdr *)next; 3364 next += ifam->ifam_msglen; 3365 if (ifam->ifam_version != RTM_VERSION) { 3366 if (verbose) 3367 warnx("routing message version %d " 3368 "not understood", ifam->ifam_version); 3369 continue; 3370 } 3371 if (ifam->ifam_type != RTM_NEWADDR) 3372 break; 3373 if (ifam->ifam_addrs & RTA_IFA) { 3374 int i; 3375 char *cp = (char *)(ifam + 1); 3376 3377 for (i = 1; i < RTA_IFA; i <<= 1) { 3378 if (ifam->ifam_addrs & i) 3379 cp += SA_SIZE((struct sockaddr *)cp); 3380 } 3381 if (((struct sockaddr *)cp)->sa_family == AF_INET) { 3382 sin = (struct sockaddr_in *)cp; 3383 break; 3384 } 3385 } 3386 } 3387 if (sin == NULL) 3388 errx(1, "%s: cannot get interface address", ifn); 3389 3390 n->ip = sin->sin_addr; 3391 strncpy(n->if_name, ifn, IF_NAMESIZE); 3392 3393 free(buf); 3394 } 3395 3396 /* 3397 * XXX - The following functions, macros and definitions come from natd.c: 3398 * it would be better to move them outside natd.c, in a file 3399 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live 3400 * with it. 3401 */ 3402 3403 /* 3404 * Definition of a port range, and macros to deal with values. 3405 * FORMAT: HI 16-bits == first port in range, 0 == all ports. 3406 * LO 16-bits == number of ports in range 3407 * NOTES: - Port values are not stored in network byte order. 3408 */ 3409 3410 #define port_range u_long 3411 3412 #define GETLOPORT(x) ((x) >> 0x10) 3413 #define GETNUMPORTS(x) ((x) & 0x0000ffff) 3414 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x))) 3415 3416 /* Set y to be the low-port value in port_range variable x. */ 3417 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10)) 3418 3419 /* Set y to be the number of ports in port_range variable x. */ 3420 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y)) 3421 3422 static void 3423 StrToAddr (const char* str, struct in_addr* addr) 3424 { 3425 struct hostent* hp; 3426 3427 if (inet_aton (str, addr)) 3428 return; 3429 3430 hp = gethostbyname (str); 3431 if (!hp) 3432 errx (1, "unknown host %s", str); 3433 3434 memcpy (addr, hp->h_addr, sizeof (struct in_addr)); 3435 } 3436 3437 static int 3438 StrToPortRange (const char* str, const char* proto, port_range *portRange) 3439 { 3440 char* sep; 3441 struct servent* sp; 3442 char* end; 3443 u_short loPort; 3444 u_short hiPort; 3445 3446 /* First see if this is a service, return corresponding port if so. */ 3447 sp = getservbyname (str,proto); 3448 if (sp) { 3449 SETLOPORT(*portRange, ntohs(sp->s_port)); 3450 SETNUMPORTS(*portRange, 1); 3451 return 0; 3452 } 3453 3454 /* Not a service, see if it's a single port or port range. */ 3455 sep = strchr (str, '-'); 3456 if (sep == NULL) { 3457 SETLOPORT(*portRange, strtol(str, &end, 10)); 3458 if (end != str) { 3459 /* Single port. */ 3460 SETNUMPORTS(*portRange, 1); 3461 return 0; 3462 } 3463 3464 /* Error in port range field. */ 3465 errx (EX_DATAERR, "%s/%s: unknown service", str, proto); 3466 } 3467 3468 /* Port range, get the values and sanity check. */ 3469 sscanf (str, "%hu-%hu", &loPort, &hiPort); 3470 SETLOPORT(*portRange, loPort); 3471 SETNUMPORTS(*portRange, 0); /* Error by default */ 3472 if (loPort <= hiPort) 3473 SETNUMPORTS(*portRange, hiPort - loPort + 1); 3474 3475 if (GETNUMPORTS(*portRange) == 0) 3476 errx (EX_DATAERR, "invalid port range %s", str); 3477 3478 return 0; 3479 } 3480 3481 static int 3482 StrToProto (const char* str) 3483 { 3484 if (!strcmp (str, "tcp")) 3485 return IPPROTO_TCP; 3486 3487 if (!strcmp (str, "udp")) 3488 return IPPROTO_UDP; 3489 3490 errx (EX_DATAERR, "unknown protocol %s. Expected tcp or udp", str); 3491 } 3492 3493 static int 3494 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto, 3495 port_range *portRange) 3496 { 3497 char* ptr; 3498 3499 ptr = strchr (str, ':'); 3500 if (!ptr) 3501 errx (EX_DATAERR, "%s is missing port number", str); 3502 3503 *ptr = '\0'; 3504 ++ptr; 3505 3506 StrToAddr (str, addr); 3507 return StrToPortRange (ptr, proto, portRange); 3508 } 3509 3510 /* End of stuff taken from natd.c. */ 3511 3512 #define INC_ARGCV() do { \ 3513 (*_av)++; \ 3514 (*_ac)--; \ 3515 av = *_av; \ 3516 ac = *_ac; \ 3517 } while(0) 3518 3519 /* 3520 * The next 3 functions add support for the addr, port and proto redirect and 3521 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect() 3522 * and SetupProtoRedirect() from natd.c. 3523 * 3524 * Every setup_* function fills at least one redirect entry 3525 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool) 3526 * in buf. 3527 * 3528 * The format of data in buf is: 3529 * 3530 * 3531 * cfg_nat cfg_redir cfg_spool ...... cfg_spool 3532 * 3533 * ------------------------------------- ------------ 3534 * | | .....X ... | | | | ..... 3535 * ------------------------------------- ...... ------------ 3536 * ^ 3537 * spool_cnt n=0 ...... n=(X-1) 3538 * 3539 * len points to the amount of available space in buf 3540 * space counts the memory consumed by every function 3541 * 3542 * XXX - Every function get all the argv params so it 3543 * has to check, in optional parameters, that the next 3544 * args is a valid option for the redir entry and not 3545 * another token. Only redir_port and redir_proto are 3546 * affected by this. 3547 */ 3548 3549 static int 3550 setup_redir_addr(char *spool_buf, int len, 3551 int *_ac, char ***_av) 3552 { 3553 char **av, *sep; /* Token separator. */ 3554 /* Temporary buffer used to hold server pool ip's. */ 3555 char tmp_spool_buf[NAT_BUF_LEN]; 3556 int ac, i, space, lsnat; 3557 struct cfg_redir *r; 3558 struct cfg_spool *tmp; 3559 3560 av = *_av; 3561 ac = *_ac; 3562 space = 0; 3563 lsnat = 0; 3564 if (len >= SOF_REDIR) { 3565 r = (struct cfg_redir *)spool_buf; 3566 /* Skip cfg_redir at beginning of buf. */ 3567 spool_buf = &spool_buf[SOF_REDIR]; 3568 space = SOF_REDIR; 3569 len -= SOF_REDIR; 3570 } else 3571 goto nospace; 3572 r->mode = REDIR_ADDR; 3573 /* Extract local address. */ 3574 if (ac == 0) 3575 errx(EX_DATAERR, "redirect_addr: missing local address"); 3576 sep = strchr(*av, ','); 3577 if (sep) { /* LSNAT redirection syntax. */ 3578 r->laddr.s_addr = INADDR_NONE; 3579 /* Preserve av, copy spool servers to tmp_spool_buf. */ 3580 strncpy(tmp_spool_buf, *av, strlen(*av)+1); 3581 lsnat = 1; 3582 } else 3583 StrToAddr(*av, &r->laddr); 3584 INC_ARGCV(); 3585 3586 /* Extract public address. */ 3587 if (ac == 0) 3588 errx(EX_DATAERR, "redirect_addr: missing public address"); 3589 StrToAddr(*av, &r->paddr); 3590 INC_ARGCV(); 3591 3592 /* Setup LSNAT server pool. */ 3593 if (sep) { 3594 sep = strtok(tmp_spool_buf, ","); 3595 while (sep != NULL) { 3596 tmp = (struct cfg_spool *)spool_buf; 3597 if (len < SOF_SPOOL) 3598 goto nospace; 3599 len -= SOF_SPOOL; 3600 space += SOF_SPOOL; 3601 StrToAddr(sep, &tmp->addr); 3602 tmp->port = ~0; 3603 r->spool_cnt++; 3604 /* Point to the next possible cfg_spool. */ 3605 spool_buf = &spool_buf[SOF_SPOOL]; 3606 sep = strtok(NULL, ","); 3607 } 3608 } 3609 return(space); 3610 nospace: 3611 errx(EX_DATAERR, "redirect_addr: buf is too small\n"); 3612 } 3613 3614 static int 3615 setup_redir_port(char *spool_buf, int len, 3616 int *_ac, char ***_av) 3617 { 3618 char **av, *sep, *protoName; 3619 char tmp_spool_buf[NAT_BUF_LEN]; 3620 int ac, space, lsnat; 3621 struct cfg_redir *r; 3622 struct cfg_spool *tmp; 3623 u_short numLocalPorts; 3624 port_range portRange; 3625 3626 av = *_av; 3627 ac = *_ac; 3628 space = 0; 3629 lsnat = 0; 3630 numLocalPorts = 0; 3631 3632 if (len >= SOF_REDIR) { 3633 r = (struct cfg_redir *)spool_buf; 3634 /* Skip cfg_redir at beginning of buf. */ 3635 spool_buf = &spool_buf[SOF_REDIR]; 3636 space = SOF_REDIR; 3637 len -= SOF_REDIR; 3638 } else 3639 goto nospace; 3640 r->mode = REDIR_PORT; 3641 /* 3642 * Extract protocol. 3643 */ 3644 if (ac == 0) 3645 errx (EX_DATAERR, "redirect_port: missing protocol"); 3646 r->proto = StrToProto(*av); 3647 protoName = *av; 3648 INC_ARGCV(); 3649 3650 /* 3651 * Extract local address. 3652 */ 3653 if (ac == 0) 3654 errx (EX_DATAERR, "redirect_port: missing local address"); 3655 3656 sep = strchr(*av, ','); 3657 /* LSNAT redirection syntax. */ 3658 if (sep) { 3659 r->laddr.s_addr = INADDR_NONE; 3660 r->lport = ~0; 3661 numLocalPorts = 1; 3662 /* Preserve av, copy spool servers to tmp_spool_buf. */ 3663 strncpy(tmp_spool_buf, *av, strlen(*av)+1); 3664 lsnat = 1; 3665 } else { 3666 if (StrToAddrAndPortRange (*av, &r->laddr, protoName, 3667 &portRange) != 0) 3668 errx(EX_DATAERR, "redirect_port:" 3669 "invalid local port range"); 3670 3671 r->lport = GETLOPORT(portRange); 3672 numLocalPorts = GETNUMPORTS(portRange); 3673 } 3674 INC_ARGCV(); 3675 3676 /* 3677 * Extract public port and optionally address. 3678 */ 3679 if (ac == 0) 3680 errx (EX_DATAERR, "redirect_port: missing public port"); 3681 3682 sep = strchr (*av, ':'); 3683 if (sep) { 3684 if (StrToAddrAndPortRange (*av, &r->paddr, protoName, 3685 &portRange) != 0) 3686 errx(EX_DATAERR, "redirect_port:" 3687 "invalid public port range"); 3688 } else { 3689 r->paddr.s_addr = INADDR_ANY; 3690 if (StrToPortRange (*av, protoName, &portRange) != 0) 3691 errx(EX_DATAERR, "redirect_port:" 3692 "invalid public port range"); 3693 } 3694 3695 r->pport = GETLOPORT(portRange); 3696 r->pport_cnt = GETNUMPORTS(portRange); 3697 INC_ARGCV(); 3698 3699 /* 3700 * Extract remote address and optionally port. 3701 */ 3702 /* 3703 * NB: isalpha(**av) => we've to check that next parameter is really an 3704 * option for this redirect entry, else stop here processing arg[cv]. 3705 */ 3706 if (ac != 0 && !isalpha(**av)) { 3707 sep = strchr (*av, ':'); 3708 if (sep) { 3709 if (StrToAddrAndPortRange (*av, &r->raddr, protoName, 3710 &portRange) != 0) 3711 errx(EX_DATAERR, "redirect_port:" 3712 "invalid remote port range"); 3713 } else { 3714 SETLOPORT(portRange, 0); 3715 SETNUMPORTS(portRange, 1); 3716 StrToAddr (*av, &r->raddr); 3717 } 3718 INC_ARGCV(); 3719 } else { 3720 SETLOPORT(portRange, 0); 3721 SETNUMPORTS(portRange, 1); 3722 r->raddr.s_addr = INADDR_ANY; 3723 } 3724 r->rport = GETLOPORT(portRange); 3725 r->rport_cnt = GETNUMPORTS(portRange); 3726 3727 /* 3728 * Make sure port ranges match up, then add the redirect ports. 3729 */ 3730 if (numLocalPorts != r->pport_cnt) 3731 errx(EX_DATAERR, "redirect_port:" 3732 "port ranges must be equal in size"); 3733 3734 /* Remote port range is allowed to be '0' which means all ports. */ 3735 if (r->rport_cnt != numLocalPorts && 3736 (r->rport_cnt != 1 || r->rport != 0)) 3737 errx(EX_DATAERR, "redirect_port: remote port must" 3738 "be 0 or equal to local port range in size"); 3739 3740 /* 3741 * Setup LSNAT server pool. 3742 */ 3743 if (lsnat) { 3744 sep = strtok(tmp_spool_buf, ","); 3745 while (sep != NULL) { 3746 tmp = (struct cfg_spool *)spool_buf; 3747 if (len < SOF_SPOOL) 3748 goto nospace; 3749 len -= SOF_SPOOL; 3750 space += SOF_SPOOL; 3751 if (StrToAddrAndPortRange(sep, &tmp->addr, protoName, 3752 &portRange) != 0) 3753 errx(EX_DATAERR, "redirect_port:" 3754 "invalid local port range"); 3755 if (GETNUMPORTS(portRange) != 1) 3756 errx(EX_DATAERR, "redirect_port: local port" 3757 "must be single in this context"); 3758 tmp->port = GETLOPORT(portRange); 3759 r->spool_cnt++; 3760 /* Point to the next possible cfg_spool. */ 3761 spool_buf = &spool_buf[SOF_SPOOL]; 3762 sep = strtok(NULL, ","); 3763 } 3764 } 3765 return (space); 3766 nospace: 3767 errx(EX_DATAERR, "redirect_port: buf is too small\n"); 3768 } 3769 3770 static int 3771 setup_redir_proto(char *spool_buf, int len, 3772 int *_ac, char ***_av) 3773 { 3774 char **av; 3775 int ac, i, space; 3776 struct protoent *protoent; 3777 struct cfg_redir *r; 3778 3779 av = *_av; 3780 ac = *_ac; 3781 if (len >= SOF_REDIR) { 3782 r = (struct cfg_redir *)spool_buf; 3783 /* Skip cfg_redir at beginning of buf. */ 3784 spool_buf = &spool_buf[SOF_REDIR]; 3785 space = SOF_REDIR; 3786 len -= SOF_REDIR; 3787 } else 3788 goto nospace; 3789 r->mode = REDIR_PROTO; 3790 /* 3791 * Extract protocol. 3792 */ 3793 if (ac == 0) 3794 errx(EX_DATAERR, "redirect_proto: missing protocol"); 3795 3796 protoent = getprotobyname(*av); 3797 if (protoent == NULL) 3798 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av); 3799 else 3800 r->proto = protoent->p_proto; 3801 3802 INC_ARGCV(); 3803 3804 /* 3805 * Extract local address. 3806 */ 3807 if (ac == 0) 3808 errx(EX_DATAERR, "redirect_proto: missing local address"); 3809 else 3810 StrToAddr(*av, &r->laddr); 3811 3812 INC_ARGCV(); 3813 3814 /* 3815 * Extract optional public address. 3816 */ 3817 if (ac == 0) { 3818 r->paddr.s_addr = INADDR_ANY; 3819 r->raddr.s_addr = INADDR_ANY; 3820 } else { 3821 /* see above in setup_redir_port() */ 3822 if (!isalpha(**av)) { 3823 StrToAddr(*av, &r->paddr); 3824 INC_ARGCV(); 3825 3826 /* 3827 * Extract optional remote address. 3828 */ 3829 /* see above in setup_redir_port() */ 3830 if (ac!=0 && !isalpha(**av)) { 3831 StrToAddr(*av, &r->raddr); 3832 INC_ARGCV(); 3833 } 3834 } 3835 } 3836 return (space); 3837 nospace: 3838 errx(EX_DATAERR, "redirect_proto: buf is too small\n"); 3839 } 3840 3841 static void 3842 show_nat(int ac, char **av); 3843 3844 static void 3845 print_nat_config(char *buf) { 3846 struct cfg_nat *n; 3847 int i, cnt, flag, off; 3848 struct cfg_redir *t; 3849 struct cfg_spool *s; 3850 struct protoent *p; 3851 3852 n = (struct cfg_nat *)buf; 3853 flag = 1; 3854 off = sizeof(*n); 3855 printf("ipfw nat %u config", n->id); 3856 if (strlen(n->if_name) != 0) 3857 printf(" if %s", n->if_name); 3858 else if (n->ip.s_addr != 0) 3859 printf(" ip %s", inet_ntoa(n->ip)); 3860 while (n->mode != 0) { 3861 if (n->mode & PKT_ALIAS_LOG) { 3862 printf(" log"); 3863 n->mode &= ~PKT_ALIAS_LOG; 3864 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) { 3865 printf(" deny_in"); 3866 n->mode &= ~PKT_ALIAS_DENY_INCOMING; 3867 } else if (n->mode & PKT_ALIAS_SAME_PORTS) { 3868 printf(" same_ports"); 3869 n->mode &= ~PKT_ALIAS_SAME_PORTS; 3870 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) { 3871 printf(" unreg_only"); 3872 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY; 3873 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) { 3874 printf(" reset"); 3875 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE; 3876 } else if (n->mode & PKT_ALIAS_REVERSE) { 3877 printf(" reverse"); 3878 n->mode &= ~PKT_ALIAS_REVERSE; 3879 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) { 3880 printf(" proxy_only"); 3881 n->mode &= ~PKT_ALIAS_PROXY_ONLY; 3882 } 3883 } 3884 /* Print all the redirect's data configuration. */ 3885 for (cnt = 0; cnt < n->redir_cnt; cnt++) { 3886 t = (struct cfg_redir *)&buf[off]; 3887 off += SOF_REDIR; 3888 switch (t->mode) { 3889 case REDIR_ADDR: 3890 printf(" redirect_addr"); 3891 if (t->spool_cnt == 0) 3892 printf(" %s", inet_ntoa(t->laddr)); 3893 else 3894 for (i = 0; i < t->spool_cnt; i++) { 3895 s = (struct cfg_spool *)&buf[off]; 3896 if (i) 3897 printf(","); 3898 else 3899 printf(" "); 3900 printf("%s", inet_ntoa(s->addr)); 3901 off += SOF_SPOOL; 3902 } 3903 printf(" %s", inet_ntoa(t->paddr)); 3904 break; 3905 case REDIR_PORT: 3906 p = getprotobynumber(t->proto); 3907 printf(" redirect_port %s ", p->p_name); 3908 if (!t->spool_cnt) { 3909 printf("%s:%u", inet_ntoa(t->laddr), t->lport); 3910 if (t->pport_cnt > 1) 3911 printf("-%u", t->lport + 3912 t->pport_cnt - 1); 3913 } else 3914 for (i=0; i < t->spool_cnt; i++) { 3915 s = (struct cfg_spool *)&buf[off]; 3916 if (i) 3917 printf(","); 3918 printf("%s:%u", inet_ntoa(s->addr), 3919 s->port); 3920 off += SOF_SPOOL; 3921 } 3922 3923 printf(" "); 3924 if (t->paddr.s_addr) 3925 printf("%s:", inet_ntoa(t->paddr)); 3926 printf("%u", t->pport); 3927 if (!t->spool_cnt && t->pport_cnt > 1) 3928 printf("-%u", t->pport + t->pport_cnt - 1); 3929 3930 if (t->raddr.s_addr) { 3931 printf(" %s", inet_ntoa(t->raddr)); 3932 if (t->rport) { 3933 printf(":%u", t->rport); 3934 if (!t->spool_cnt && t->rport_cnt > 1) 3935 printf("-%u", t->rport + 3936 t->rport_cnt - 1); 3937 } 3938 } 3939 break; 3940 case REDIR_PROTO: 3941 p = getprotobynumber(t->proto); 3942 printf(" redirect_proto %s %s", p->p_name, 3943 inet_ntoa(t->laddr)); 3944 if (t->paddr.s_addr != 0) { 3945 printf(" %s", inet_ntoa(t->paddr)); 3946 if (t->raddr.s_addr) 3947 printf(" %s", inet_ntoa(t->raddr)); 3948 } 3949 break; 3950 default: 3951 errx(EX_DATAERR, "unknown redir mode"); 3952 break; 3953 } 3954 } 3955 printf("\n"); 3956 } 3957 3958 static void 3959 config_nat(int ac, char **av) 3960 { 3961 struct cfg_nat *n; /* Nat instance configuration. */ 3962 struct in_addr ip; 3963 int i, len, off, tok; 3964 char *id, buf[NAT_BUF_LEN]; /* Buffer for serialized data. */ 3965 3966 len = NAT_BUF_LEN; 3967 /* Offset in buf: save space for n at the beginning. */ 3968 off = sizeof(*n); 3969 memset(buf, 0, sizeof(buf)); 3970 n = (struct cfg_nat *)buf; 3971 3972 av++; ac--; 3973 /* Nat id. */ 3974 if (ac && isdigit(**av)) { 3975 id = *av; 3976 i = atoi(*av); 3977 ac--; av++; 3978 n->id = i; 3979 } else 3980 errx(EX_DATAERR, "missing nat id"); 3981 if (ac == 0) 3982 errx(EX_DATAERR, "missing option"); 3983 3984 while (ac > 0) { 3985 tok = match_token(nat_params, *av); 3986 ac--; av++; 3987 switch (tok) { 3988 case TOK_IP: 3989 if (ac == 0) 3990 errx(EX_DATAERR, "missing option"); 3991 if (!inet_aton(av[0], &(n->ip))) 3992 errx(EX_DATAERR, "bad ip address ``%s''", 3993 av[0]); 3994 ac--; av++; 3995 break; 3996 case TOK_IF: 3997 set_addr_dynamic(av[0], n); 3998 ac--; av++; 3999 break; 4000 case TOK_ALOG: 4001 n->mode |= PKT_ALIAS_LOG; 4002 break; 4003 case TOK_DENY_INC: 4004 n->mode |= PKT_ALIAS_DENY_INCOMING; 4005 break; 4006 case TOK_SAME_PORTS: 4007 n->mode |= PKT_ALIAS_SAME_PORTS; 4008 break; 4009 case TOK_UNREG_ONLY: 4010 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY; 4011 break; 4012 case TOK_RESET_ADDR: 4013 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE; 4014 break; 4015 case TOK_ALIAS_REV: 4016 n->mode |= PKT_ALIAS_REVERSE; 4017 break; 4018 case TOK_PROXY_ONLY: 4019 n->mode |= PKT_ALIAS_PROXY_ONLY; 4020 break; 4021 /* 4022 * All the setup_redir_* functions work directly in the final 4023 * buffer, see above for details. 4024 */ 4025 case TOK_REDIR_ADDR: 4026 case TOK_REDIR_PORT: 4027 case TOK_REDIR_PROTO: 4028 switch (tok) { 4029 case TOK_REDIR_ADDR: 4030 i = setup_redir_addr(&buf[off], len, &ac, &av); 4031 break; 4032 case TOK_REDIR_PORT: 4033 i = setup_redir_port(&buf[off], len, &ac, &av); 4034 break; 4035 case TOK_REDIR_PROTO: 4036 i = setup_redir_proto(&buf[off], len, &ac, &av); 4037 break; 4038 } 4039 n->redir_cnt++; 4040 off += i; 4041 len -= i; 4042 break; 4043 default: 4044 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]); 4045 } 4046 } 4047 4048 i = do_cmd(IP_FW_NAT_CFG, buf, off); 4049 if (i) 4050 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG"); 4051 4052 /* After every modification, we show the resultant rule. */ 4053 int _ac = 3; 4054 char *_av[] = {"show", "config", id}; 4055 show_nat(_ac, _av); 4056 } 4057 4058 static void 4059 config_pipe(int ac, char **av) 4060 { 4061 struct dn_pipe p; 4062 int i; 4063 char *end; 4064 void *par = NULL; 4065 4066 memset(&p, 0, sizeof p); 4067 4068 av++; ac--; 4069 /* Pipe number */ 4070 if (ac && isdigit(**av)) { 4071 i = atoi(*av); av++; ac--; 4072 if (do_pipe == 1) 4073 p.pipe_nr = i; 4074 else 4075 p.fs.fs_nr = i; 4076 } 4077 while (ac > 0) { 4078 double d; 4079 int tok = match_token(dummynet_params, *av); 4080 ac--; av++; 4081 4082 switch(tok) { 4083 case TOK_NOERROR: 4084 p.fs.flags_fs |= DN_NOERROR; 4085 break; 4086 4087 case TOK_PLR: 4088 NEED1("plr needs argument 0..1\n"); 4089 d = strtod(av[0], NULL); 4090 if (d > 1) 4091 d = 1; 4092 else if (d < 0) 4093 d = 0; 4094 p.fs.plr = (int)(d*0x7fffffff); 4095 ac--; av++; 4096 break; 4097 4098 case TOK_QUEUE: 4099 NEED1("queue needs queue size\n"); 4100 end = NULL; 4101 p.fs.qsize = strtoul(av[0], &end, 0); 4102 if (*end == 'K' || *end == 'k') { 4103 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 4104 p.fs.qsize *= 1024; 4105 } else if (*end == 'B' || 4106 _substrcmp2(end, "by", "bytes") == 0) { 4107 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 4108 } 4109 ac--; av++; 4110 break; 4111 4112 case TOK_BUCKETS: 4113 NEED1("buckets needs argument\n"); 4114 p.fs.rq_size = strtoul(av[0], NULL, 0); 4115 ac--; av++; 4116 break; 4117 4118 case TOK_MASK: 4119 NEED1("mask needs mask specifier\n"); 4120 /* 4121 * per-flow queue, mask is dst_ip, dst_port, 4122 * src_ip, src_port, proto measured in bits 4123 */ 4124 par = NULL; 4125 4126 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask)); 4127 end = NULL; 4128 4129 while (ac >= 1) { 4130 uint32_t *p32 = NULL; 4131 uint16_t *p16 = NULL; 4132 uint32_t *p20 = NULL; 4133 struct in6_addr *pa6 = NULL; 4134 uint32_t a; 4135 4136 tok = match_token(dummynet_params, *av); 4137 ac--; av++; 4138 switch(tok) { 4139 case TOK_ALL: 4140 /* 4141 * special case, all bits significant 4142 */ 4143 p.fs.flow_mask.dst_ip = ~0; 4144 p.fs.flow_mask.src_ip = ~0; 4145 p.fs.flow_mask.dst_port = ~0; 4146 p.fs.flow_mask.src_port = ~0; 4147 p.fs.flow_mask.proto = ~0; 4148 n2mask(&(p.fs.flow_mask.dst_ip6), 128); 4149 n2mask(&(p.fs.flow_mask.src_ip6), 128); 4150 p.fs.flow_mask.flow_id6 = ~0; 4151 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 4152 goto end_mask; 4153 4154 case TOK_DSTIP: 4155 p32 = &p.fs.flow_mask.dst_ip; 4156 break; 4157 4158 case TOK_SRCIP: 4159 p32 = &p.fs.flow_mask.src_ip; 4160 break; 4161 4162 case TOK_DSTIP6: 4163 pa6 = &(p.fs.flow_mask.dst_ip6); 4164 break; 4165 4166 case TOK_SRCIP6: 4167 pa6 = &(p.fs.flow_mask.src_ip6); 4168 break; 4169 4170 case TOK_FLOWID: 4171 p20 = &p.fs.flow_mask.flow_id6; 4172 break; 4173 4174 case TOK_DSTPORT: 4175 p16 = &p.fs.flow_mask.dst_port; 4176 break; 4177 4178 case TOK_SRCPORT: 4179 p16 = &p.fs.flow_mask.src_port; 4180 break; 4181 4182 case TOK_PROTO: 4183 break; 4184 4185 default: 4186 ac++; av--; /* backtrack */ 4187 goto end_mask; 4188 } 4189 if (ac < 1) 4190 errx(EX_USAGE, "mask: value missing"); 4191 if (*av[0] == '/') { 4192 a = strtoul(av[0]+1, &end, 0); 4193 if (pa6 == NULL) 4194 a = (a == 32) ? ~0 : (1 << a) - 1; 4195 } else 4196 a = strtoul(av[0], &end, 0); 4197 if (p32 != NULL) 4198 *p32 = a; 4199 else if (p16 != NULL) { 4200 if (a > 0xFFFF) 4201 errx(EX_DATAERR, 4202 "port mask must be 16 bit"); 4203 *p16 = (uint16_t)a; 4204 } else if (p20 != NULL) { 4205 if (a > 0xfffff) 4206 errx(EX_DATAERR, 4207 "flow_id mask must be 20 bit"); 4208 *p20 = (uint32_t)a; 4209 } else if (pa6 != NULL) { 4210 if (a < 0 || a > 128) 4211 errx(EX_DATAERR, 4212 "in6addr invalid mask len"); 4213 else 4214 n2mask(pa6, a); 4215 } else { 4216 if (a > 0xFF) 4217 errx(EX_DATAERR, 4218 "proto mask must be 8 bit"); 4219 p.fs.flow_mask.proto = (uint8_t)a; 4220 } 4221 if (a != 0) 4222 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 4223 ac--; av++; 4224 } /* end while, config masks */ 4225 end_mask: 4226 break; 4227 4228 case TOK_RED: 4229 case TOK_GRED: 4230 NEED1("red/gred needs w_q/min_th/max_th/max_p\n"); 4231 p.fs.flags_fs |= DN_IS_RED; 4232 if (tok == TOK_GRED) 4233 p.fs.flags_fs |= DN_IS_GENTLE_RED; 4234 /* 4235 * the format for parameters is w_q/min_th/max_th/max_p 4236 */ 4237 if ((end = strsep(&av[0], "/"))) { 4238 double w_q = strtod(end, NULL); 4239 if (w_q > 1 || w_q <= 0) 4240 errx(EX_DATAERR, "0 < w_q <= 1"); 4241 p.fs.w_q = (int) (w_q * (1 << SCALE_RED)); 4242 } 4243 if ((end = strsep(&av[0], "/"))) { 4244 p.fs.min_th = strtoul(end, &end, 0); 4245 if (*end == 'K' || *end == 'k') 4246 p.fs.min_th *= 1024; 4247 } 4248 if ((end = strsep(&av[0], "/"))) { 4249 p.fs.max_th = strtoul(end, &end, 0); 4250 if (*end == 'K' || *end == 'k') 4251 p.fs.max_th *= 1024; 4252 } 4253 if ((end = strsep(&av[0], "/"))) { 4254 double max_p = strtod(end, NULL); 4255 if (max_p > 1 || max_p <= 0) 4256 errx(EX_DATAERR, "0 < max_p <= 1"); 4257 p.fs.max_p = (int)(max_p * (1 << SCALE_RED)); 4258 } 4259 ac--; av++; 4260 break; 4261 4262 case TOK_DROPTAIL: 4263 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED); 4264 break; 4265 4266 case TOK_BW: 4267 NEED1("bw needs bandwidth or interface\n"); 4268 if (do_pipe != 1) 4269 errx(EX_DATAERR, "bandwidth only valid for pipes"); 4270 /* 4271 * set clocking interface or bandwidth value 4272 */ 4273 if (av[0][0] >= 'a' && av[0][0] <= 'z') { 4274 int l = sizeof(p.if_name)-1; 4275 /* interface name */ 4276 strncpy(p.if_name, av[0], l); 4277 p.if_name[l] = '\0'; 4278 p.bandwidth = 0; 4279 } else { 4280 p.if_name[0] = '\0'; 4281 p.bandwidth = strtoul(av[0], &end, 0); 4282 if (*end == 'K' || *end == 'k') { 4283 end++; 4284 p.bandwidth *= 1000; 4285 } else if (*end == 'M') { 4286 end++; 4287 p.bandwidth *= 1000000; 4288 } 4289 if ((*end == 'B' && 4290 _substrcmp2(end, "Bi", "Bit/s") != 0) || 4291 _substrcmp2(end, "by", "bytes") == 0) 4292 p.bandwidth *= 8; 4293 if (p.bandwidth < 0) 4294 errx(EX_DATAERR, "bandwidth too large"); 4295 } 4296 ac--; av++; 4297 break; 4298 4299 case TOK_DELAY: 4300 if (do_pipe != 1) 4301 errx(EX_DATAERR, "delay only valid for pipes"); 4302 NEED1("delay needs argument 0..10000ms\n"); 4303 p.delay = strtoul(av[0], NULL, 0); 4304 ac--; av++; 4305 break; 4306 4307 case TOK_WEIGHT: 4308 if (do_pipe == 1) 4309 errx(EX_DATAERR,"weight only valid for queues"); 4310 NEED1("weight needs argument 0..100\n"); 4311 p.fs.weight = strtoul(av[0], &end, 0); 4312 ac--; av++; 4313 break; 4314 4315 case TOK_PIPE: 4316 if (do_pipe == 1) 4317 errx(EX_DATAERR,"pipe only valid for queues"); 4318 NEED1("pipe needs pipe_number\n"); 4319 p.fs.parent_nr = strtoul(av[0], &end, 0); 4320 ac--; av++; 4321 break; 4322 4323 default: 4324 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]); 4325 } 4326 } 4327 if (do_pipe == 1) { 4328 if (p.pipe_nr == 0) 4329 errx(EX_DATAERR, "pipe_nr must be > 0"); 4330 if (p.delay > 10000) 4331 errx(EX_DATAERR, "delay must be < 10000"); 4332 } else { /* do_pipe == 2, queue */ 4333 if (p.fs.parent_nr == 0) 4334 errx(EX_DATAERR, "pipe must be > 0"); 4335 if (p.fs.weight >100) 4336 errx(EX_DATAERR, "weight must be <= 100"); 4337 } 4338 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) { 4339 if (p.fs.qsize > 1024*1024) 4340 errx(EX_DATAERR, "queue size must be < 1MB"); 4341 } else { 4342 if (p.fs.qsize > 100) 4343 errx(EX_DATAERR, "2 <= queue size <= 100"); 4344 } 4345 if (p.fs.flags_fs & DN_IS_RED) { 4346 size_t len; 4347 int lookup_depth, avg_pkt_size; 4348 double s, idle, weight, w_q; 4349 struct clockinfo ck; 4350 int t; 4351 4352 if (p.fs.min_th >= p.fs.max_th) 4353 errx(EX_DATAERR, "min_th %d must be < than max_th %d", 4354 p.fs.min_th, p.fs.max_th); 4355 if (p.fs.max_th == 0) 4356 errx(EX_DATAERR, "max_th must be > 0"); 4357 4358 len = sizeof(int); 4359 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth", 4360 &lookup_depth, &len, NULL, 0) == -1) 4361 4362 errx(1, "sysctlbyname(\"%s\")", 4363 "net.inet.ip.dummynet.red_lookup_depth"); 4364 if (lookup_depth == 0) 4365 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth" 4366 " must be greater than zero"); 4367 4368 len = sizeof(int); 4369 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size", 4370 &avg_pkt_size, &len, NULL, 0) == -1) 4371 4372 errx(1, "sysctlbyname(\"%s\")", 4373 "net.inet.ip.dummynet.red_avg_pkt_size"); 4374 if (avg_pkt_size == 0) 4375 errx(EX_DATAERR, 4376 "net.inet.ip.dummynet.red_avg_pkt_size must" 4377 " be greater than zero"); 4378 4379 len = sizeof(struct clockinfo); 4380 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1) 4381 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate"); 4382 4383 /* 4384 * Ticks needed for sending a medium-sized packet. 4385 * Unfortunately, when we are configuring a WF2Q+ queue, we 4386 * do not have bandwidth information, because that is stored 4387 * in the parent pipe, and also we have multiple queues 4388 * competing for it. So we set s=0, which is not very 4389 * correct. But on the other hand, why do we want RED with 4390 * WF2Q+ ? 4391 */ 4392 if (p.bandwidth==0) /* this is a WF2Q+ queue */ 4393 s = 0; 4394 else 4395 s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth; 4396 4397 /* 4398 * max idle time (in ticks) before avg queue size becomes 0. 4399 * NOTA: (3/w_q) is approx the value x so that 4400 * (1-w_q)^x < 10^-3. 4401 */ 4402 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED); 4403 idle = s * 3. / w_q; 4404 p.fs.lookup_step = (int)idle / lookup_depth; 4405 if (!p.fs.lookup_step) 4406 p.fs.lookup_step = 1; 4407 weight = 1 - w_q; 4408 for (t = p.fs.lookup_step; t > 1; --t) 4409 weight *= 1 - w_q; 4410 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED)); 4411 } 4412 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p); 4413 if (i) 4414 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE"); 4415 } 4416 4417 static void 4418 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask) 4419 { 4420 int i, l; 4421 char *ap, *ptr, *optr; 4422 struct ether_addr *mac; 4423 const char *macset = "0123456789abcdefABCDEF:"; 4424 4425 if (strcmp(p, "any") == 0) { 4426 for (i = 0; i < ETHER_ADDR_LEN; i++) 4427 addr[i] = mask[i] = 0; 4428 return; 4429 } 4430 4431 optr = ptr = strdup(p); 4432 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) { 4433 l = strlen(ap); 4434 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL) 4435 errx(EX_DATAERR, "Incorrect MAC address"); 4436 bcopy(mac, addr, ETHER_ADDR_LEN); 4437 } else 4438 errx(EX_DATAERR, "Incorrect MAC address"); 4439 4440 if (ptr != NULL) { /* we have mask? */ 4441 if (p[ptr - optr - 1] == '/') { /* mask len */ 4442 l = strtol(ptr, &ap, 10); 4443 if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0) 4444 errx(EX_DATAERR, "Incorrect mask length"); 4445 for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++) 4446 mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l); 4447 } else { /* mask */ 4448 l = strlen(ptr); 4449 if (strspn(ptr, macset) != l || 4450 (mac = ether_aton(ptr)) == NULL) 4451 errx(EX_DATAERR, "Incorrect mask"); 4452 bcopy(mac, mask, ETHER_ADDR_LEN); 4453 } 4454 } else { /* default mask: ff:ff:ff:ff:ff:ff */ 4455 for (i = 0; i < ETHER_ADDR_LEN; i++) 4456 mask[i] = 0xff; 4457 } 4458 for (i = 0; i < ETHER_ADDR_LEN; i++) 4459 addr[i] &= mask[i]; 4460 4461 free(optr); 4462 } 4463 4464 /* 4465 * helper function, updates the pointer to cmd with the length 4466 * of the current command, and also cleans up the first word of 4467 * the new command in case it has been clobbered before. 4468 */ 4469 static ipfw_insn * 4470 next_cmd(ipfw_insn *cmd) 4471 { 4472 cmd += F_LEN(cmd); 4473 bzero(cmd, sizeof(*cmd)); 4474 return cmd; 4475 } 4476 4477 /* 4478 * Takes arguments and copies them into a comment 4479 */ 4480 static void 4481 fill_comment(ipfw_insn *cmd, int ac, char **av) 4482 { 4483 int i, l; 4484 char *p = (char *)(cmd + 1); 4485 4486 cmd->opcode = O_NOP; 4487 cmd->len = (cmd->len & (F_NOT | F_OR)); 4488 4489 /* Compute length of comment string. */ 4490 for (i = 0, l = 0; i < ac; i++) 4491 l += strlen(av[i]) + 1; 4492 if (l == 0) 4493 return; 4494 if (l > 84) 4495 errx(EX_DATAERR, 4496 "comment too long (max 80 chars)"); 4497 l = 1 + (l+3)/4; 4498 cmd->len = (cmd->len & (F_NOT | F_OR)) | l; 4499 for (i = 0; i < ac; i++) { 4500 strcpy(p, av[i]); 4501 p += strlen(av[i]); 4502 *p++ = ' '; 4503 } 4504 *(--p) = '\0'; 4505 } 4506 4507 /* 4508 * A function to fill simple commands of size 1. 4509 * Existing flags are preserved. 4510 */ 4511 static void 4512 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg) 4513 { 4514 cmd->opcode = opcode; 4515 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1; 4516 cmd->arg1 = arg; 4517 } 4518 4519 /* 4520 * Fetch and add the MAC address and type, with masks. This generates one or 4521 * two microinstructions, and returns the pointer to the last one. 4522 */ 4523 static ipfw_insn * 4524 add_mac(ipfw_insn *cmd, int ac, char *av[]) 4525 { 4526 ipfw_insn_mac *mac; 4527 4528 if (ac < 2) 4529 errx(EX_DATAERR, "MAC dst src"); 4530 4531 cmd->opcode = O_MACADDR2; 4532 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac); 4533 4534 mac = (ipfw_insn_mac *)cmd; 4535 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */ 4536 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]), 4537 &(mac->mask[ETHER_ADDR_LEN])); /* src */ 4538 return cmd; 4539 } 4540 4541 static ipfw_insn * 4542 add_mactype(ipfw_insn *cmd, int ac, char *av) 4543 { 4544 if (ac < 1) 4545 errx(EX_DATAERR, "missing MAC type"); 4546 if (strcmp(av, "any") != 0) { /* we have a non-null type */ 4547 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE); 4548 cmd->opcode = O_MAC_TYPE; 4549 return cmd; 4550 } else 4551 return NULL; 4552 } 4553 4554 static ipfw_insn * 4555 add_proto0(ipfw_insn *cmd, char *av, u_char *protop) 4556 { 4557 struct protoent *pe; 4558 char *ep; 4559 int proto; 4560 4561 proto = strtol(av, &ep, 10); 4562 if (*ep != '\0' || proto <= 0) { 4563 if ((pe = getprotobyname(av)) == NULL) 4564 return NULL; 4565 proto = pe->p_proto; 4566 } 4567 4568 fill_cmd(cmd, O_PROTO, 0, proto); 4569 *protop = proto; 4570 return cmd; 4571 } 4572 4573 static ipfw_insn * 4574 add_proto(ipfw_insn *cmd, char *av, u_char *protop) 4575 { 4576 u_char proto = IPPROTO_IP; 4577 4578 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4579 ; /* do not set O_IP4 nor O_IP6 */ 4580 else if (strcmp(av, "ip4") == 0) 4581 /* explicit "just IPv4" rule */ 4582 fill_cmd(cmd, O_IP4, 0, 0); 4583 else if (strcmp(av, "ip6") == 0) { 4584 /* explicit "just IPv6" rule */ 4585 proto = IPPROTO_IPV6; 4586 fill_cmd(cmd, O_IP6, 0, 0); 4587 } else 4588 return add_proto0(cmd, av, protop); 4589 4590 *protop = proto; 4591 return cmd; 4592 } 4593 4594 static ipfw_insn * 4595 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop) 4596 { 4597 u_char proto = IPPROTO_IP; 4598 4599 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0) 4600 ; /* do not set O_IP4 nor O_IP6 */ 4601 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0) 4602 /* explicit "just IPv4" rule */ 4603 fill_cmd(cmd, O_IP4, 0, 0); 4604 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) { 4605 /* explicit "just IPv6" rule */ 4606 proto = IPPROTO_IPV6; 4607 fill_cmd(cmd, O_IP6, 0, 0); 4608 } else 4609 return add_proto0(cmd, av, protop); 4610 4611 *protop = proto; 4612 return cmd; 4613 } 4614 4615 static ipfw_insn * 4616 add_srcip(ipfw_insn *cmd, char *av) 4617 { 4618 fill_ip((ipfw_insn_ip *)cmd, av); 4619 if (cmd->opcode == O_IP_DST_SET) /* set */ 4620 cmd->opcode = O_IP_SRC_SET; 4621 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4622 cmd->opcode = O_IP_SRC_LOOKUP; 4623 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4624 cmd->opcode = O_IP_SRC_ME; 4625 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4626 cmd->opcode = O_IP_SRC; 4627 else /* addr/mask */ 4628 cmd->opcode = O_IP_SRC_MASK; 4629 return cmd; 4630 } 4631 4632 static ipfw_insn * 4633 add_dstip(ipfw_insn *cmd, char *av) 4634 { 4635 fill_ip((ipfw_insn_ip *)cmd, av); 4636 if (cmd->opcode == O_IP_DST_SET) /* set */ 4637 ; 4638 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */ 4639 ; 4640 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 4641 cmd->opcode = O_IP_DST_ME; 4642 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 4643 cmd->opcode = O_IP_DST; 4644 else /* addr/mask */ 4645 cmd->opcode = O_IP_DST_MASK; 4646 return cmd; 4647 } 4648 4649 static ipfw_insn * 4650 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode) 4651 { 4652 if (_substrcmp(av, "any") == 0) { 4653 return NULL; 4654 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) { 4655 /* XXX todo: check that we have a protocol with ports */ 4656 cmd->opcode = opcode; 4657 return cmd; 4658 } 4659 return NULL; 4660 } 4661 4662 static ipfw_insn * 4663 add_src(ipfw_insn *cmd, char *av, u_char proto) 4664 { 4665 struct in6_addr a; 4666 char *host, *ch; 4667 ipfw_insn *ret = NULL; 4668 4669 if ((host = strdup(av)) == NULL) 4670 return NULL; 4671 if ((ch = strrchr(host, '/')) != NULL) 4672 *ch = '\0'; 4673 4674 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4675 inet_pton(AF_INET6, host, &a)) 4676 ret = add_srcip6(cmd, av); 4677 /* XXX: should check for IPv4, not !IPv6 */ 4678 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4679 !inet_pton(AF_INET6, host, &a))) 4680 ret = add_srcip(cmd, av); 4681 if (ret == NULL && strcmp(av, "any") != 0) 4682 ret = cmd; 4683 4684 free(host); 4685 return ret; 4686 } 4687 4688 static ipfw_insn * 4689 add_dst(ipfw_insn *cmd, char *av, u_char proto) 4690 { 4691 struct in6_addr a; 4692 char *host, *ch; 4693 ipfw_insn *ret = NULL; 4694 4695 if ((host = strdup(av)) == NULL) 4696 return NULL; 4697 if ((ch = strrchr(host, '/')) != NULL) 4698 *ch = '\0'; 4699 4700 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 || 4701 inet_pton(AF_INET6, host, &a)) 4702 ret = add_dstip6(cmd, av); 4703 /* XXX: should check for IPv4, not !IPv6 */ 4704 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 || 4705 !inet_pton(AF_INET6, host, &a))) 4706 ret = add_dstip(cmd, av); 4707 if (ret == NULL && strcmp(av, "any") != 0) 4708 ret = cmd; 4709 4710 free(host); 4711 return ret; 4712 } 4713 4714 /* 4715 * Parse arguments and assemble the microinstructions which make up a rule. 4716 * Rules are added into the 'rulebuf' and then copied in the correct order 4717 * into the actual rule. 4718 * 4719 * The syntax for a rule starts with the action, followed by 4720 * optional action parameters, and the various match patterns. 4721 * In the assembled microcode, the first opcode must be an O_PROBE_STATE 4722 * (generated if the rule includes a keep-state option), then the 4723 * various match patterns, log/altq actions, and the actual action. 4724 * 4725 */ 4726 static void 4727 add(int ac, char *av[]) 4728 { 4729 /* 4730 * rules are added into the 'rulebuf' and then copied in 4731 * the correct order into the actual rule. 4732 * Some things that need to go out of order (prob, action etc.) 4733 * go into actbuf[]. 4734 */ 4735 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255]; 4736 4737 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL; 4738 ipfw_insn *first_cmd; /* first match pattern */ 4739 4740 struct ip_fw *rule; 4741 4742 /* 4743 * various flags used to record that we entered some fields. 4744 */ 4745 ipfw_insn *have_state = NULL; /* check-state or keep-state */ 4746 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL; 4747 size_t len; 4748 4749 int i; 4750 4751 int open_par = 0; /* open parenthesis ( */ 4752 4753 /* proto is here because it is used to fetch ports */ 4754 u_char proto = IPPROTO_IP; /* default protocol */ 4755 4756 double match_prob = 1; /* match probability, default is always match */ 4757 4758 bzero(actbuf, sizeof(actbuf)); /* actions go here */ 4759 bzero(cmdbuf, sizeof(cmdbuf)); 4760 bzero(rulebuf, sizeof(rulebuf)); 4761 4762 rule = (struct ip_fw *)rulebuf; 4763 cmd = (ipfw_insn *)cmdbuf; 4764 action = (ipfw_insn *)actbuf; 4765 4766 av++; ac--; 4767 4768 /* [rule N] -- Rule number optional */ 4769 if (ac && isdigit(**av)) { 4770 rule->rulenum = atoi(*av); 4771 av++; 4772 ac--; 4773 } 4774 4775 /* [set N] -- set number (0..RESVD_SET), optional */ 4776 if (ac > 1 && _substrcmp(*av, "set") == 0) { 4777 int set = strtoul(av[1], NULL, 10); 4778 if (set < 0 || set > RESVD_SET) 4779 errx(EX_DATAERR, "illegal set %s", av[1]); 4780 rule->set = set; 4781 av += 2; ac -= 2; 4782 } 4783 4784 /* [prob D] -- match probability, optional */ 4785 if (ac > 1 && _substrcmp(*av, "prob") == 0) { 4786 match_prob = strtod(av[1], NULL); 4787 4788 if (match_prob <= 0 || match_prob > 1) 4789 errx(EX_DATAERR, "illegal match prob. %s", av[1]); 4790 av += 2; ac -= 2; 4791 } 4792 4793 /* action -- mandatory */ 4794 NEED1("missing action"); 4795 i = match_token(rule_actions, *av); 4796 ac--; av++; 4797 action->len = 1; /* default */ 4798 switch(i) { 4799 case TOK_CHECKSTATE: 4800 have_state = action; 4801 action->opcode = O_CHECK_STATE; 4802 break; 4803 4804 case TOK_ACCEPT: 4805 action->opcode = O_ACCEPT; 4806 break; 4807 4808 case TOK_DENY: 4809 action->opcode = O_DENY; 4810 action->arg1 = 0; 4811 break; 4812 4813 case TOK_REJECT: 4814 action->opcode = O_REJECT; 4815 action->arg1 = ICMP_UNREACH_HOST; 4816 break; 4817 4818 case TOK_RESET: 4819 action->opcode = O_REJECT; 4820 action->arg1 = ICMP_REJECT_RST; 4821 break; 4822 4823 case TOK_RESET6: 4824 action->opcode = O_UNREACH6; 4825 action->arg1 = ICMP6_UNREACH_RST; 4826 break; 4827 4828 case TOK_UNREACH: 4829 action->opcode = O_REJECT; 4830 NEED1("missing reject code"); 4831 fill_reject_code(&action->arg1, *av); 4832 ac--; av++; 4833 break; 4834 4835 case TOK_UNREACH6: 4836 action->opcode = O_UNREACH6; 4837 NEED1("missing unreach code"); 4838 fill_unreach6_code(&action->arg1, *av); 4839 ac--; av++; 4840 break; 4841 4842 case TOK_COUNT: 4843 action->opcode = O_COUNT; 4844 break; 4845 4846 case TOK_QUEUE: 4847 action->opcode = O_QUEUE; 4848 goto chkarg; 4849 case TOK_PIPE: 4850 action->opcode = O_PIPE; 4851 goto chkarg; 4852 case TOK_SKIPTO: 4853 action->opcode = O_SKIPTO; 4854 goto chkarg; 4855 case TOK_NETGRAPH: 4856 action->opcode = O_NETGRAPH; 4857 goto chkarg; 4858 case TOK_NGTEE: 4859 action->opcode = O_NGTEE; 4860 goto chkarg; 4861 case TOK_DIVERT: 4862 action->opcode = O_DIVERT; 4863 goto chkarg; 4864 case TOK_TEE: 4865 action->opcode = O_TEE; 4866 chkarg: 4867 if (!ac) 4868 errx(EX_USAGE, "missing argument for %s", *(av - 1)); 4869 if (isdigit(**av)) { 4870 action->arg1 = strtoul(*av, NULL, 10); 4871 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG) 4872 errx(EX_DATAERR, "illegal argument for %s", 4873 *(av - 1)); 4874 } else if (_substrcmp(*av, TABLEARG) == 0) { 4875 action->arg1 = IP_FW_TABLEARG; 4876 } else if (i == TOK_DIVERT || i == TOK_TEE) { 4877 struct servent *s; 4878 setservent(1); 4879 s = getservbyname(av[0], "divert"); 4880 if (s != NULL) 4881 action->arg1 = ntohs(s->s_port); 4882 else 4883 errx(EX_DATAERR, "illegal divert/tee port"); 4884 } else 4885 errx(EX_DATAERR, "illegal argument for %s", *(av - 1)); 4886 ac--; av++; 4887 break; 4888 4889 case TOK_FORWARD: { 4890 ipfw_insn_sa *p = (ipfw_insn_sa *)action; 4891 char *s, *end; 4892 4893 NEED1("missing forward address[:port]"); 4894 4895 action->opcode = O_FORWARD_IP; 4896 action->len = F_INSN_SIZE(ipfw_insn_sa); 4897 4898 p->sa.sin_len = sizeof(struct sockaddr_in); 4899 p->sa.sin_family = AF_INET; 4900 p->sa.sin_port = 0; 4901 /* 4902 * locate the address-port separator (':' or ',') 4903 */ 4904 s = strchr(*av, ':'); 4905 if (s == NULL) 4906 s = strchr(*av, ','); 4907 if (s != NULL) { 4908 *(s++) = '\0'; 4909 i = strtoport(s, &end, 0 /* base */, 0 /* proto */); 4910 if (s == end) 4911 errx(EX_DATAERR, 4912 "illegal forwarding port ``%s''", s); 4913 p->sa.sin_port = (u_short)i; 4914 } 4915 if (_substrcmp(*av, "tablearg") == 0) 4916 p->sa.sin_addr.s_addr = INADDR_ANY; 4917 else 4918 lookup_host(*av, &(p->sa.sin_addr)); 4919 ac--; av++; 4920 break; 4921 } 4922 case TOK_COMMENT: 4923 /* pretend it is a 'count' rule followed by the comment */ 4924 action->opcode = O_COUNT; 4925 ac++; av--; /* go back... */ 4926 break; 4927 4928 case TOK_NAT: 4929 action->opcode = O_NAT; 4930 action->len = F_INSN_SIZE(ipfw_insn_nat); 4931 NEED1("missing nat number"); 4932 action->arg1 = strtoul(*av, NULL, 10); 4933 ac--; av++; 4934 break; 4935 4936 default: 4937 errx(EX_DATAERR, "invalid action %s\n", av[-1]); 4938 } 4939 action = next_cmd(action); 4940 4941 /* 4942 * [altq queuename] -- altq tag, optional 4943 * [log [logamount N]] -- log, optional 4944 * 4945 * If they exist, it go first in the cmdbuf, but then it is 4946 * skipped in the copy section to the end of the buffer. 4947 */ 4948 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) { 4949 ac--; av++; 4950 switch (i) { 4951 case TOK_LOG: 4952 { 4953 ipfw_insn_log *c = (ipfw_insn_log *)cmd; 4954 int l; 4955 4956 if (have_log) 4957 errx(EX_DATAERR, 4958 "log cannot be specified more than once"); 4959 have_log = (ipfw_insn *)c; 4960 cmd->len = F_INSN_SIZE(ipfw_insn_log); 4961 cmd->opcode = O_LOG; 4962 if (ac && _substrcmp(*av, "logamount") == 0) { 4963 ac--; av++; 4964 NEED1("logamount requires argument"); 4965 l = atoi(*av); 4966 if (l < 0) 4967 errx(EX_DATAERR, 4968 "logamount must be positive"); 4969 c->max_log = l; 4970 ac--; av++; 4971 } else { 4972 len = sizeof(c->max_log); 4973 if (sysctlbyname("net.inet.ip.fw.verbose_limit", 4974 &c->max_log, &len, NULL, 0) == -1) 4975 errx(1, "sysctlbyname(\"%s\")", 4976 "net.inet.ip.fw.verbose_limit"); 4977 } 4978 } 4979 break; 4980 4981 case TOK_ALTQ: 4982 { 4983 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd; 4984 4985 NEED1("missing altq queue name"); 4986 if (have_altq) 4987 errx(EX_DATAERR, 4988 "altq cannot be specified more than once"); 4989 have_altq = (ipfw_insn *)a; 4990 cmd->len = F_INSN_SIZE(ipfw_insn_altq); 4991 cmd->opcode = O_ALTQ; 4992 fill_altq_qid(&a->qid, *av); 4993 ac--; av++; 4994 } 4995 break; 4996 4997 case TOK_TAG: 4998 case TOK_UNTAG: { 4999 uint16_t tag; 5000 5001 if (have_tag) 5002 errx(EX_USAGE, "tag and untag cannot be " 5003 "specified more than once"); 5004 GET_UINT_ARG(tag, 1, 65534, i, rule_action_params); 5005 have_tag = cmd; 5006 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag); 5007 ac--; av++; 5008 break; 5009 } 5010 5011 default: 5012 abort(); 5013 } 5014 cmd = next_cmd(cmd); 5015 } 5016 5017 if (have_state) /* must be a check-state, we are done */ 5018 goto done; 5019 5020 #define OR_START(target) \ 5021 if (ac && (*av[0] == '(' || *av[0] == '{')) { \ 5022 if (open_par) \ 5023 errx(EX_USAGE, "nested \"(\" not allowed\n"); \ 5024 prev = NULL; \ 5025 open_par = 1; \ 5026 if ( (av[0])[1] == '\0') { \ 5027 ac--; av++; \ 5028 } else \ 5029 (*av)++; \ 5030 } \ 5031 target: \ 5032 5033 5034 #define CLOSE_PAR \ 5035 if (open_par) { \ 5036 if (ac && ( \ 5037 strcmp(*av, ")") == 0 || \ 5038 strcmp(*av, "}") == 0)) { \ 5039 prev = NULL; \ 5040 open_par = 0; \ 5041 ac--; av++; \ 5042 } else \ 5043 errx(EX_USAGE, "missing \")\"\n"); \ 5044 } 5045 5046 #define NOT_BLOCK \ 5047 if (ac && _substrcmp(*av, "not") == 0) { \ 5048 if (cmd->len & F_NOT) \ 5049 errx(EX_USAGE, "double \"not\" not allowed\n"); \ 5050 cmd->len |= F_NOT; \ 5051 ac--; av++; \ 5052 } 5053 5054 #define OR_BLOCK(target) \ 5055 if (ac && _substrcmp(*av, "or") == 0) { \ 5056 if (prev == NULL || open_par == 0) \ 5057 errx(EX_DATAERR, "invalid OR block"); \ 5058 prev->len |= F_OR; \ 5059 ac--; av++; \ 5060 goto target; \ 5061 } \ 5062 CLOSE_PAR; 5063 5064 first_cmd = cmd; 5065 5066 #if 0 5067 /* 5068 * MAC addresses, optional. 5069 * If we have this, we skip the part "proto from src to dst" 5070 * and jump straight to the option parsing. 5071 */ 5072 NOT_BLOCK; 5073 NEED1("missing protocol"); 5074 if (_substrcmp(*av, "MAC") == 0 || 5075 _substrcmp(*av, "mac") == 0) { 5076 ac--; av++; /* the "MAC" keyword */ 5077 add_mac(cmd, ac, av); /* exits in case of errors */ 5078 cmd = next_cmd(cmd); 5079 ac -= 2; av += 2; /* dst-mac and src-mac */ 5080 NOT_BLOCK; 5081 NEED1("missing mac type"); 5082 if (add_mactype(cmd, ac, av[0])) 5083 cmd = next_cmd(cmd); 5084 ac--; av++; /* any or mac-type */ 5085 goto read_options; 5086 } 5087 #endif 5088 5089 /* 5090 * protocol, mandatory 5091 */ 5092 OR_START(get_proto); 5093 NOT_BLOCK; 5094 NEED1("missing protocol"); 5095 if (add_proto_compat(cmd, *av, &proto)) { 5096 av++; ac--; 5097 if (F_LEN(cmd) != 0) { 5098 prev = cmd; 5099 cmd = next_cmd(cmd); 5100 } 5101 } else if (first_cmd != cmd) { 5102 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 5103 } else 5104 goto read_options; 5105 OR_BLOCK(get_proto); 5106 5107 /* 5108 * "from", mandatory 5109 */ 5110 if (!ac || _substrcmp(*av, "from") != 0) 5111 errx(EX_USAGE, "missing ``from''"); 5112 ac--; av++; 5113 5114 /* 5115 * source IP, mandatory 5116 */ 5117 OR_START(source_ip); 5118 NOT_BLOCK; /* optional "not" */ 5119 NEED1("missing source address"); 5120 if (add_src(cmd, *av, proto)) { 5121 ac--; av++; 5122 if (F_LEN(cmd) != 0) { /* ! any */ 5123 prev = cmd; 5124 cmd = next_cmd(cmd); 5125 } 5126 } else 5127 errx(EX_USAGE, "bad source address %s", *av); 5128 OR_BLOCK(source_ip); 5129 5130 /* 5131 * source ports, optional 5132 */ 5133 NOT_BLOCK; /* optional "not" */ 5134 if (ac) { 5135 if (_substrcmp(*av, "any") == 0 || 5136 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5137 ac--; av++; 5138 if (F_LEN(cmd) != 0) 5139 cmd = next_cmd(cmd); 5140 } 5141 } 5142 5143 /* 5144 * "to", mandatory 5145 */ 5146 if (!ac || _substrcmp(*av, "to") != 0) 5147 errx(EX_USAGE, "missing ``to''"); 5148 av++; ac--; 5149 5150 /* 5151 * destination, mandatory 5152 */ 5153 OR_START(dest_ip); 5154 NOT_BLOCK; /* optional "not" */ 5155 NEED1("missing dst address"); 5156 if (add_dst(cmd, *av, proto)) { 5157 ac--; av++; 5158 if (F_LEN(cmd) != 0) { /* ! any */ 5159 prev = cmd; 5160 cmd = next_cmd(cmd); 5161 } 5162 } else 5163 errx( EX_USAGE, "bad destination address %s", *av); 5164 OR_BLOCK(dest_ip); 5165 5166 /* 5167 * dest. ports, optional 5168 */ 5169 NOT_BLOCK; /* optional "not" */ 5170 if (ac) { 5171 if (_substrcmp(*av, "any") == 0 || 5172 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5173 ac--; av++; 5174 if (F_LEN(cmd) != 0) 5175 cmd = next_cmd(cmd); 5176 } 5177 } 5178 5179 read_options: 5180 if (ac && first_cmd == cmd) { 5181 /* 5182 * nothing specified so far, store in the rule to ease 5183 * printout later. 5184 */ 5185 rule->_pad = 1; 5186 } 5187 prev = NULL; 5188 while (ac) { 5189 char *s; 5190 ipfw_insn_u32 *cmd32; /* alias for cmd */ 5191 5192 s = *av; 5193 cmd32 = (ipfw_insn_u32 *)cmd; 5194 5195 if (*s == '!') { /* alternate syntax for NOT */ 5196 if (cmd->len & F_NOT) 5197 errx(EX_USAGE, "double \"not\" not allowed\n"); 5198 cmd->len = F_NOT; 5199 s++; 5200 } 5201 i = match_token(rule_options, s); 5202 ac--; av++; 5203 switch(i) { 5204 case TOK_NOT: 5205 if (cmd->len & F_NOT) 5206 errx(EX_USAGE, "double \"not\" not allowed\n"); 5207 cmd->len = F_NOT; 5208 break; 5209 5210 case TOK_OR: 5211 if (open_par == 0 || prev == NULL) 5212 errx(EX_USAGE, "invalid \"or\" block\n"); 5213 prev->len |= F_OR; 5214 break; 5215 5216 case TOK_STARTBRACE: 5217 if (open_par) 5218 errx(EX_USAGE, "+nested \"(\" not allowed\n"); 5219 open_par = 1; 5220 break; 5221 5222 case TOK_ENDBRACE: 5223 if (!open_par) 5224 errx(EX_USAGE, "+missing \")\"\n"); 5225 open_par = 0; 5226 prev = NULL; 5227 break; 5228 5229 case TOK_IN: 5230 fill_cmd(cmd, O_IN, 0, 0); 5231 break; 5232 5233 case TOK_OUT: 5234 cmd->len ^= F_NOT; /* toggle F_NOT */ 5235 fill_cmd(cmd, O_IN, 0, 0); 5236 break; 5237 5238 case TOK_DIVERTED: 5239 fill_cmd(cmd, O_DIVERTED, 0, 3); 5240 break; 5241 5242 case TOK_DIVERTEDLOOPBACK: 5243 fill_cmd(cmd, O_DIVERTED, 0, 1); 5244 break; 5245 5246 case TOK_DIVERTEDOUTPUT: 5247 fill_cmd(cmd, O_DIVERTED, 0, 2); 5248 break; 5249 5250 case TOK_FRAG: 5251 fill_cmd(cmd, O_FRAG, 0, 0); 5252 break; 5253 5254 case TOK_LAYER2: 5255 fill_cmd(cmd, O_LAYER2, 0, 0); 5256 break; 5257 5258 case TOK_XMIT: 5259 case TOK_RECV: 5260 case TOK_VIA: 5261 NEED1("recv, xmit, via require interface name" 5262 " or address"); 5263 fill_iface((ipfw_insn_if *)cmd, av[0]); 5264 ac--; av++; 5265 if (F_LEN(cmd) == 0) /* not a valid address */ 5266 break; 5267 if (i == TOK_XMIT) 5268 cmd->opcode = O_XMIT; 5269 else if (i == TOK_RECV) 5270 cmd->opcode = O_RECV; 5271 else if (i == TOK_VIA) 5272 cmd->opcode = O_VIA; 5273 break; 5274 5275 case TOK_ICMPTYPES: 5276 NEED1("icmptypes requires list of types"); 5277 fill_icmptypes((ipfw_insn_u32 *)cmd, *av); 5278 av++; ac--; 5279 break; 5280 5281 case TOK_ICMP6TYPES: 5282 NEED1("icmptypes requires list of types"); 5283 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av); 5284 av++; ac--; 5285 break; 5286 5287 case TOK_IPTTL: 5288 NEED1("ipttl requires TTL"); 5289 if (strpbrk(*av, "-,")) { 5290 if (!add_ports(cmd, *av, 0, O_IPTTL)) 5291 errx(EX_DATAERR, "invalid ipttl %s", *av); 5292 } else 5293 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0)); 5294 ac--; av++; 5295 break; 5296 5297 case TOK_IPID: 5298 NEED1("ipid requires id"); 5299 if (strpbrk(*av, "-,")) { 5300 if (!add_ports(cmd, *av, 0, O_IPID)) 5301 errx(EX_DATAERR, "invalid ipid %s", *av); 5302 } else 5303 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0)); 5304 ac--; av++; 5305 break; 5306 5307 case TOK_IPLEN: 5308 NEED1("iplen requires length"); 5309 if (strpbrk(*av, "-,")) { 5310 if (!add_ports(cmd, *av, 0, O_IPLEN)) 5311 errx(EX_DATAERR, "invalid ip len %s", *av); 5312 } else 5313 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0)); 5314 ac--; av++; 5315 break; 5316 5317 case TOK_IPVER: 5318 NEED1("ipver requires version"); 5319 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0)); 5320 ac--; av++; 5321 break; 5322 5323 case TOK_IPPRECEDENCE: 5324 NEED1("ipprecedence requires value"); 5325 fill_cmd(cmd, O_IPPRECEDENCE, 0, 5326 (strtoul(*av, NULL, 0) & 7) << 5); 5327 ac--; av++; 5328 break; 5329 5330 case TOK_IPOPTS: 5331 NEED1("missing argument for ipoptions"); 5332 fill_flags(cmd, O_IPOPT, f_ipopts, *av); 5333 ac--; av++; 5334 break; 5335 5336 case TOK_IPTOS: 5337 NEED1("missing argument for iptos"); 5338 fill_flags(cmd, O_IPTOS, f_iptos, *av); 5339 ac--; av++; 5340 break; 5341 5342 case TOK_UID: 5343 NEED1("uid requires argument"); 5344 { 5345 char *end; 5346 uid_t uid; 5347 struct passwd *pwd; 5348 5349 cmd->opcode = O_UID; 5350 uid = strtoul(*av, &end, 0); 5351 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av); 5352 if (pwd == NULL) 5353 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av); 5354 cmd32->d[0] = pwd->pw_uid; 5355 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5356 ac--; av++; 5357 } 5358 break; 5359 5360 case TOK_GID: 5361 NEED1("gid requires argument"); 5362 { 5363 char *end; 5364 gid_t gid; 5365 struct group *grp; 5366 5367 cmd->opcode = O_GID; 5368 gid = strtoul(*av, &end, 0); 5369 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av); 5370 if (grp == NULL) 5371 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av); 5372 cmd32->d[0] = grp->gr_gid; 5373 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5374 ac--; av++; 5375 } 5376 break; 5377 5378 case TOK_JAIL: 5379 NEED1("jail requires argument"); 5380 { 5381 char *end; 5382 int jid; 5383 5384 cmd->opcode = O_JAIL; 5385 jid = (int)strtol(*av, &end, 0); 5386 if (jid < 0 || *end != '\0') 5387 errx(EX_DATAERR, "jail requires prison ID"); 5388 cmd32->d[0] = (uint32_t)jid; 5389 cmd->len |= F_INSN_SIZE(ipfw_insn_u32); 5390 ac--; av++; 5391 } 5392 break; 5393 5394 case TOK_ESTAB: 5395 fill_cmd(cmd, O_ESTAB, 0, 0); 5396 break; 5397 5398 case TOK_SETUP: 5399 fill_cmd(cmd, O_TCPFLAGS, 0, 5400 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 ); 5401 break; 5402 5403 case TOK_TCPDATALEN: 5404 NEED1("tcpdatalen requires length"); 5405 if (strpbrk(*av, "-,")) { 5406 if (!add_ports(cmd, *av, 0, O_TCPDATALEN)) 5407 errx(EX_DATAERR, "invalid tcpdata len %s", *av); 5408 } else 5409 fill_cmd(cmd, O_TCPDATALEN, 0, 5410 strtoul(*av, NULL, 0)); 5411 ac--; av++; 5412 break; 5413 5414 case TOK_TCPOPTS: 5415 NEED1("missing argument for tcpoptions"); 5416 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av); 5417 ac--; av++; 5418 break; 5419 5420 case TOK_TCPSEQ: 5421 case TOK_TCPACK: 5422 NEED1("tcpseq/tcpack requires argument"); 5423 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 5424 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK; 5425 cmd32->d[0] = htonl(strtoul(*av, NULL, 0)); 5426 ac--; av++; 5427 break; 5428 5429 case TOK_TCPWIN: 5430 NEED1("tcpwin requires length"); 5431 fill_cmd(cmd, O_TCPWIN, 0, 5432 htons(strtoul(*av, NULL, 0))); 5433 ac--; av++; 5434 break; 5435 5436 case TOK_TCPFLAGS: 5437 NEED1("missing argument for tcpflags"); 5438 cmd->opcode = O_TCPFLAGS; 5439 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av); 5440 ac--; av++; 5441 break; 5442 5443 case TOK_KEEPSTATE: 5444 if (open_par) 5445 errx(EX_USAGE, "keep-state cannot be part " 5446 "of an or block"); 5447 if (have_state) 5448 errx(EX_USAGE, "only one of keep-state " 5449 "and limit is allowed"); 5450 have_state = cmd; 5451 fill_cmd(cmd, O_KEEP_STATE, 0, 0); 5452 break; 5453 5454 case TOK_LIMIT: { 5455 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 5456 int val; 5457 5458 if (open_par) 5459 errx(EX_USAGE, 5460 "limit cannot be part of an or block"); 5461 if (have_state) 5462 errx(EX_USAGE, "only one of keep-state and " 5463 "limit is allowed"); 5464 have_state = cmd; 5465 5466 cmd->len = F_INSN_SIZE(ipfw_insn_limit); 5467 cmd->opcode = O_LIMIT; 5468 c->limit_mask = c->conn_limit = 0; 5469 5470 while (ac > 0) { 5471 if ((val = match_token(limit_masks, *av)) <= 0) 5472 break; 5473 c->limit_mask |= val; 5474 ac--; av++; 5475 } 5476 5477 if (c->limit_mask == 0) 5478 errx(EX_USAGE, "limit: missing limit mask"); 5479 5480 GET_UINT_ARG(c->conn_limit, 1, 65534, TOK_LIMIT, 5481 rule_options); 5482 5483 ac--; av++; 5484 break; 5485 } 5486 5487 case TOK_PROTO: 5488 NEED1("missing protocol"); 5489 if (add_proto(cmd, *av, &proto)) { 5490 ac--; av++; 5491 } else 5492 errx(EX_DATAERR, "invalid protocol ``%s''", 5493 *av); 5494 break; 5495 5496 case TOK_SRCIP: 5497 NEED1("missing source IP"); 5498 if (add_srcip(cmd, *av)) { 5499 ac--; av++; 5500 } 5501 break; 5502 5503 case TOK_DSTIP: 5504 NEED1("missing destination IP"); 5505 if (add_dstip(cmd, *av)) { 5506 ac--; av++; 5507 } 5508 break; 5509 5510 case TOK_SRCIP6: 5511 NEED1("missing source IP6"); 5512 if (add_srcip6(cmd, *av)) { 5513 ac--; av++; 5514 } 5515 break; 5516 5517 case TOK_DSTIP6: 5518 NEED1("missing destination IP6"); 5519 if (add_dstip6(cmd, *av)) { 5520 ac--; av++; 5521 } 5522 break; 5523 5524 case TOK_SRCPORT: 5525 NEED1("missing source port"); 5526 if (_substrcmp(*av, "any") == 0 || 5527 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 5528 ac--; av++; 5529 } else 5530 errx(EX_DATAERR, "invalid source port %s", *av); 5531 break; 5532 5533 case TOK_DSTPORT: 5534 NEED1("missing destination port"); 5535 if (_substrcmp(*av, "any") == 0 || 5536 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 5537 ac--; av++; 5538 } else 5539 errx(EX_DATAERR, "invalid destination port %s", 5540 *av); 5541 break; 5542 5543 case TOK_MAC: 5544 if (add_mac(cmd, ac, av)) { 5545 ac -= 2; av += 2; 5546 } 5547 break; 5548 5549 case TOK_MACTYPE: 5550 NEED1("missing mac type"); 5551 if (!add_mactype(cmd, ac, *av)) 5552 errx(EX_DATAERR, "invalid mac type %s", *av); 5553 ac--; av++; 5554 break; 5555 5556 case TOK_VERREVPATH: 5557 fill_cmd(cmd, O_VERREVPATH, 0, 0); 5558 break; 5559 5560 case TOK_VERSRCREACH: 5561 fill_cmd(cmd, O_VERSRCREACH, 0, 0); 5562 break; 5563 5564 case TOK_ANTISPOOF: 5565 fill_cmd(cmd, O_ANTISPOOF, 0, 0); 5566 break; 5567 5568 case TOK_IPSEC: 5569 fill_cmd(cmd, O_IPSEC, 0, 0); 5570 break; 5571 5572 case TOK_IPV6: 5573 fill_cmd(cmd, O_IP6, 0, 0); 5574 break; 5575 5576 case TOK_IPV4: 5577 fill_cmd(cmd, O_IP4, 0, 0); 5578 break; 5579 5580 case TOK_EXT6HDR: 5581 fill_ext6hdr( cmd, *av ); 5582 ac--; av++; 5583 break; 5584 5585 case TOK_FLOWID: 5586 if (proto != IPPROTO_IPV6 ) 5587 errx( EX_USAGE, "flow-id filter is active " 5588 "only for ipv6 protocol\n"); 5589 fill_flow6( (ipfw_insn_u32 *) cmd, *av ); 5590 ac--; av++; 5591 break; 5592 5593 case TOK_COMMENT: 5594 fill_comment(cmd, ac, av); 5595 av += ac; 5596 ac = 0; 5597 break; 5598 5599 case TOK_TAGGED: 5600 if (ac > 0 && strpbrk(*av, "-,")) { 5601 if (!add_ports(cmd, *av, 0, O_TAGGED)) 5602 errx(EX_DATAERR, "tagged: invalid tag" 5603 " list: %s", *av); 5604 } 5605 else { 5606 uint16_t tag; 5607 5608 GET_UINT_ARG(tag, 1, 65534, TOK_TAGGED, 5609 rule_options); 5610 fill_cmd(cmd, O_TAGGED, 0, tag); 5611 } 5612 ac--; av++; 5613 break; 5614 5615 default: 5616 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s); 5617 } 5618 if (F_LEN(cmd) > 0) { /* prepare to advance */ 5619 prev = cmd; 5620 cmd = next_cmd(cmd); 5621 } 5622 } 5623 5624 done: 5625 /* 5626 * Now copy stuff into the rule. 5627 * If we have a keep-state option, the first instruction 5628 * must be a PROBE_STATE (which is generated here). 5629 * If we have a LOG option, it was stored as the first command, 5630 * and now must be moved to the top of the action part. 5631 */ 5632 dst = (ipfw_insn *)rule->cmd; 5633 5634 /* 5635 * First thing to write into the command stream is the match probability. 5636 */ 5637 if (match_prob != 1) { /* 1 means always match */ 5638 dst->opcode = O_PROB; 5639 dst->len = 2; 5640 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff); 5641 dst += dst->len; 5642 } 5643 5644 /* 5645 * generate O_PROBE_STATE if necessary 5646 */ 5647 if (have_state && have_state->opcode != O_CHECK_STATE) { 5648 fill_cmd(dst, O_PROBE_STATE, 0, 0); 5649 dst = next_cmd(dst); 5650 } 5651 5652 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */ 5653 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) { 5654 i = F_LEN(src); 5655 5656 switch (src->opcode) { 5657 case O_LOG: 5658 case O_KEEP_STATE: 5659 case O_LIMIT: 5660 case O_ALTQ: 5661 case O_TAG: 5662 break; 5663 default: 5664 bcopy(src, dst, i * sizeof(uint32_t)); 5665 dst += i; 5666 } 5667 } 5668 5669 /* 5670 * put back the have_state command as last opcode 5671 */ 5672 if (have_state && have_state->opcode != O_CHECK_STATE) { 5673 i = F_LEN(have_state); 5674 bcopy(have_state, dst, i * sizeof(uint32_t)); 5675 dst += i; 5676 } 5677 /* 5678 * start action section 5679 */ 5680 rule->act_ofs = dst - rule->cmd; 5681 5682 /* put back O_LOG, O_ALTQ, O_TAG if necessary */ 5683 if (have_log) { 5684 i = F_LEN(have_log); 5685 bcopy(have_log, dst, i * sizeof(uint32_t)); 5686 dst += i; 5687 } 5688 if (have_altq) { 5689 i = F_LEN(have_altq); 5690 bcopy(have_altq, dst, i * sizeof(uint32_t)); 5691 dst += i; 5692 } 5693 if (have_tag) { 5694 i = F_LEN(have_tag); 5695 bcopy(have_tag, dst, i * sizeof(uint32_t)); 5696 dst += i; 5697 } 5698 /* 5699 * copy all other actions 5700 */ 5701 for (src = (ipfw_insn *)actbuf; src != action; src += i) { 5702 i = F_LEN(src); 5703 bcopy(src, dst, i * sizeof(uint32_t)); 5704 dst += i; 5705 } 5706 5707 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd); 5708 i = (char *)dst - (char *)rule; 5709 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1) 5710 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD"); 5711 if (!do_quiet) 5712 show_ipfw(rule, 0, 0); 5713 } 5714 5715 static void 5716 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */) 5717 { 5718 uint32_t arg, saved_arg; 5719 int failed = EX_OK; 5720 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG"; 5721 char const *errstr; 5722 5723 av++; ac--; 5724 5725 if (!ac) { 5726 /* clear all entries */ 5727 if (do_cmd(optname, NULL, 0) < 0) 5728 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name); 5729 if (!do_quiet) 5730 printf("%s.\n", optname == IP_FW_ZERO ? 5731 "Accounting cleared":"Logging counts reset"); 5732 5733 return; 5734 } 5735 5736 while (ac) { 5737 /* Rule number */ 5738 if (isdigit(**av)) { 5739 arg = strtonum(*av, 0, 0xffff, &errstr); 5740 if (errstr) 5741 errx(EX_DATAERR, 5742 "invalid rule number %s\n", *av); 5743 saved_arg = arg; 5744 if (use_set) 5745 arg |= (1 << 24) | ((use_set - 1) << 16); 5746 av++; 5747 ac--; 5748 if (do_cmd(optname, &arg, sizeof(arg))) { 5749 warn("rule %u: setsockopt(IP_FW_%s)", 5750 saved_arg, name); 5751 failed = EX_UNAVAILABLE; 5752 } else if (!do_quiet) 5753 printf("Entry %d %s.\n", saved_arg, 5754 optname == IP_FW_ZERO ? 5755 "cleared" : "logging count reset"); 5756 } else { 5757 errx(EX_USAGE, "invalid rule number ``%s''", *av); 5758 } 5759 } 5760 if (failed != EX_OK) 5761 exit(failed); 5762 } 5763 5764 static void 5765 flush(int force) 5766 { 5767 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH; 5768 5769 if (!force && !do_quiet) { /* need to ask user */ 5770 int c; 5771 5772 printf("Are you sure? [yn] "); 5773 fflush(stdout); 5774 do { 5775 c = toupper(getc(stdin)); 5776 while (c != '\n' && getc(stdin) != '\n') 5777 if (feof(stdin)) 5778 return; /* and do not flush */ 5779 } while (c != 'Y' && c != 'N'); 5780 printf("\n"); 5781 if (c == 'N') /* user said no */ 5782 return; 5783 } 5784 /* `ipfw set N flush` - is the same that `ipfw delete set N` */ 5785 if (use_set) { 5786 uint32_t arg = ((use_set - 1) & 0xffff) | (1 << 24); 5787 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0) 5788 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)"); 5789 } else if (do_cmd(cmd, NULL, 0) < 0) 5790 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)", 5791 do_pipe ? "DUMMYNET" : "FW"); 5792 if (!do_quiet) 5793 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules"); 5794 } 5795 5796 /* 5797 * Free a the (locally allocated) copy of command line arguments. 5798 */ 5799 static void 5800 free_args(int ac, char **av) 5801 { 5802 int i; 5803 5804 for (i=0; i < ac; i++) 5805 free(av[i]); 5806 free(av); 5807 } 5808 5809 /* 5810 * This one handles all table-related commands 5811 * ipfw table N add addr[/masklen] [value] 5812 * ipfw table N delete addr[/masklen] 5813 * ipfw table N flush 5814 * ipfw table N list 5815 */ 5816 static void 5817 table_handler(int ac, char *av[]) 5818 { 5819 ipfw_table_entry ent; 5820 ipfw_table *tbl; 5821 int do_add; 5822 char *p; 5823 socklen_t l; 5824 uint32_t a; 5825 5826 ac--; av++; 5827 if (ac && isdigit(**av)) { 5828 ent.tbl = atoi(*av); 5829 ac--; av++; 5830 } else 5831 errx(EX_USAGE, "table number required"); 5832 NEED1("table needs command"); 5833 if (_substrcmp(*av, "add") == 0 || 5834 _substrcmp(*av, "delete") == 0) { 5835 do_add = **av == 'a'; 5836 ac--; av++; 5837 if (!ac) 5838 errx(EX_USAGE, "IP address required"); 5839 p = strchr(*av, '/'); 5840 if (p) { 5841 *p++ = '\0'; 5842 ent.masklen = atoi(p); 5843 if (ent.masklen > 32) 5844 errx(EX_DATAERR, "bad width ``%s''", p); 5845 } else 5846 ent.masklen = 32; 5847 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0) 5848 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5849 ac--; av++; 5850 if (do_add && ac) { 5851 unsigned int tval; 5852 /* isdigit is a bit of a hack here.. */ 5853 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) { 5854 ent.value = strtoul(*av, NULL, 0); 5855 } else { 5856 if (lookup_host(*av, (struct in_addr *)&tval) == 0) { 5857 /* The value must be stored in host order * 5858 * so that the values < 65k can be distinguished */ 5859 ent.value = ntohl(tval); 5860 } else { 5861 errx(EX_NOHOST, "hostname ``%s'' unknown", *av); 5862 } 5863 } 5864 } else 5865 ent.value = 0; 5866 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL, 5867 &ent, sizeof(ent)) < 0) { 5868 /* If running silent, don't bomb out on these errors. */ 5869 if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH)))) 5870 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)", 5871 do_add ? "ADD" : "DEL"); 5872 /* In silent mode, react to a failed add by deleting */ 5873 if (do_add) { 5874 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent)); 5875 if (do_cmd(IP_FW_TABLE_ADD, 5876 &ent, sizeof(ent)) < 0) 5877 err(EX_OSERR, 5878 "setsockopt(IP_FW_TABLE_ADD)"); 5879 } 5880 } 5881 } else if (_substrcmp(*av, "flush") == 0) { 5882 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl, sizeof(ent.tbl)) < 0) 5883 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)"); 5884 } else if (_substrcmp(*av, "list") == 0) { 5885 a = ent.tbl; 5886 l = sizeof(a); 5887 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0) 5888 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)"); 5889 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry); 5890 tbl = malloc(l); 5891 if (tbl == NULL) 5892 err(EX_OSERR, "malloc"); 5893 tbl->tbl = ent.tbl; 5894 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0) 5895 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)"); 5896 for (a = 0; a < tbl->cnt; a++) { 5897 /* Heuristic to print it the right way */ 5898 /* values < 64k are printed as numbers */ 5899 unsigned int tval; 5900 tval = tbl->ent[a].value; 5901 if (tval > 0xffff) { 5902 char tbuf[128]; 5903 strncpy(tbuf, inet_ntoa(*(struct in_addr *) 5904 &tbl->ent[a].addr), 127); 5905 /* inet_ntoa expects host order */ 5906 tval = htonl(tval); 5907 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen, 5908 inet_ntoa(*(struct in_addr *)&tval)); 5909 } else { 5910 printf("%s/%u %u\n", 5911 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr), 5912 tbl->ent[a].masklen, tbl->ent[a].value); 5913 } 5914 } 5915 } else 5916 errx(EX_USAGE, "invalid table command %s", *av); 5917 } 5918 5919 static void 5920 show_nat(int ac, char **av) { 5921 struct cfg_nat *n; 5922 struct cfg_redir *e; 5923 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size; 5924 int nat_cnt, r; 5925 uint8_t *data, *p; 5926 char **lav, *endptr; 5927 5928 do_rule = 0; 5929 nalloc = 1024; 5930 size = 0; 5931 data = NULL; 5932 ac--; av++; 5933 5934 /* Parse parameters. */ 5935 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) { 5936 if (!strncmp(av[0], "config", strlen(av[0]))) { 5937 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1; 5938 continue; 5939 } 5940 /* Convert command line rule #. */ 5941 frule = lrule = strtoul(av[0], &endptr, 10); 5942 if (*endptr == '-') 5943 lrule = strtoul(endptr+1, &endptr, 10); 5944 if (lrule == 0) 5945 err(EX_USAGE, "invalid rule number: %s", av[0]); 5946 do_rule = 1; 5947 } 5948 5949 nbytes = nalloc; 5950 while (nbytes >= nalloc) { 5951 nalloc = nalloc * 2; 5952 nbytes = nalloc; 5953 if ((data = realloc(data, nbytes)) == NULL) 5954 err(EX_OSERR, "realloc"); 5955 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0) 5956 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)", 5957 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG"); 5958 } 5959 if (nbytes == 0) 5960 exit(0); 5961 if (do_cfg) { 5962 nat_cnt = *((int *)data); 5963 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) { 5964 n = (struct cfg_nat *)&data[i]; 5965 if (do_rule) { 5966 if (!(frule <= n->id && lrule >= n->id)) 5967 continue; 5968 } 5969 print_nat_config(&data[i]); 5970 i += sizeof(struct cfg_nat); 5971 e = (struct cfg_redir *)&data[i]; 5972 if (e->mode == REDIR_ADDR || e->mode == REDIR_PORT || 5973 e->mode == REDIR_PROTO) 5974 i += sizeof(struct cfg_redir) + e->spool_cnt * 5975 sizeof(struct cfg_spool); 5976 } 5977 } else { 5978 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) { 5979 p = &data[i]; 5980 if (p == data + nbytes) 5981 break; 5982 bcopy(p, &r, sizeof(int)); 5983 if (do_rule) { 5984 if (!(frule <= r && lrule >= r)) 5985 continue; 5986 } 5987 printf("nat %u: %s\n", r, p+sizeof(int)); 5988 } 5989 } 5990 } 5991 5992 /* 5993 * Called with the arguments (excluding program name). 5994 * Returns 0 if successful, 1 if empty command, errx() in case of errors. 5995 */ 5996 static int 5997 ipfw_main(int oldac, char **oldav) 5998 { 5999 int ch, ac, save_ac; 6000 const char *errstr; 6001 char **av, **save_av; 6002 int do_acct = 0; /* Show packet/byte count */ 6003 6004 #define WHITESP " \t\f\v\n\r" 6005 if (oldac == 0) 6006 return 1; 6007 else if (oldac == 1) { 6008 /* 6009 * If we are called with a single string, try to split it into 6010 * arguments for subsequent parsing. 6011 * But first, remove spaces after a ',', by copying the string 6012 * in-place. 6013 */ 6014 char *arg = oldav[0]; /* The string... */ 6015 int l = strlen(arg); 6016 int copy = 0; /* 1 if we need to copy, 0 otherwise */ 6017 int i, j; 6018 for (i = j = 0; i < l; i++) { 6019 if (arg[i] == '#') /* comment marker */ 6020 break; 6021 if (copy) { 6022 arg[j++] = arg[i]; 6023 copy = !index("," WHITESP, arg[i]); 6024 } else { 6025 copy = !index(WHITESP, arg[i]); 6026 if (copy) 6027 arg[j++] = arg[i]; 6028 } 6029 } 6030 if (!copy && j > 0) /* last char was a 'blank', remove it */ 6031 j--; 6032 l = j; /* the new argument length */ 6033 arg[j++] = '\0'; 6034 if (l == 0) /* empty string! */ 6035 return 1; 6036 6037 /* 6038 * First, count number of arguments. Because of the previous 6039 * processing, this is just the number of blanks plus 1. 6040 */ 6041 for (i = 0, ac = 1; i < l; i++) 6042 if (index(WHITESP, arg[i]) != NULL) 6043 ac++; 6044 6045 av = calloc(ac, sizeof(char *)); 6046 6047 /* 6048 * Second, copy arguments from cmd[] to av[]. For each one, 6049 * j is the initial character, i is the one past the end. 6050 */ 6051 for (ac = 0, i = j = 0; i < l; i++) 6052 if (index(WHITESP, arg[i]) != NULL || i == l-1) { 6053 if (i == l-1) 6054 i++; 6055 av[ac] = calloc(i-j+1, 1); 6056 bcopy(arg+j, av[ac], i-j); 6057 ac++; 6058 j = i + 1; 6059 } 6060 } else { 6061 /* 6062 * If an argument ends with ',' join with the next one. 6063 */ 6064 int first, i, l; 6065 6066 av = calloc(oldac, sizeof(char *)); 6067 for (first = i = ac = 0, l = 0; i < oldac; i++) { 6068 char *arg = oldav[i]; 6069 int k = strlen(arg); 6070 6071 l += k; 6072 if (arg[k-1] != ',' || i == oldac-1) { 6073 /* Time to copy. */ 6074 av[ac] = calloc(l+1, 1); 6075 for (l=0; first <= i; first++) { 6076 strcat(av[ac]+l, oldav[first]); 6077 l += strlen(oldav[first]); 6078 } 6079 ac++; 6080 l = 0; 6081 first = i+1; 6082 } 6083 } 6084 } 6085 6086 /* Set the force flag for non-interactive processes */ 6087 if (!do_force) 6088 do_force = !isatty(STDIN_FILENO); 6089 6090 /* Save arguments for final freeing of memory. */ 6091 save_ac = ac; 6092 save_av = av; 6093 6094 optind = optreset = 0; 6095 while ((ch = getopt(ac, av, "abcdefhnNqs:STtv")) != -1) 6096 switch (ch) { 6097 case 'a': 6098 do_acct = 1; 6099 break; 6100 6101 case 'b': 6102 comment_only = 1; 6103 do_compact = 1; 6104 break; 6105 6106 case 'c': 6107 do_compact = 1; 6108 break; 6109 6110 case 'd': 6111 do_dynamic = 1; 6112 break; 6113 6114 case 'e': 6115 do_expired = 1; 6116 break; 6117 6118 case 'f': 6119 do_force = 1; 6120 break; 6121 6122 case 'h': /* help */ 6123 free_args(save_ac, save_av); 6124 help(); 6125 break; /* NOTREACHED */ 6126 6127 case 'n': 6128 test_only = 1; 6129 break; 6130 6131 case 'N': 6132 do_resolv = 1; 6133 break; 6134 6135 case 'q': 6136 do_quiet = 1; 6137 break; 6138 6139 case 's': /* sort */ 6140 do_sort = atoi(optarg); 6141 break; 6142 6143 case 'S': 6144 show_sets = 1; 6145 break; 6146 6147 case 't': 6148 do_time = 1; 6149 break; 6150 6151 case 'T': 6152 do_time = 2; /* numeric timestamp */ 6153 break; 6154 6155 case 'v': /* verbose */ 6156 verbose = 1; 6157 break; 6158 6159 default: 6160 free_args(save_ac, save_av); 6161 return 1; 6162 } 6163 6164 ac -= optind; 6165 av += optind; 6166 NEED1("bad arguments, for usage summary ``ipfw''"); 6167 6168 /* 6169 * An undocumented behaviour of ipfw1 was to allow rule numbers first, 6170 * e.g. "100 add allow ..." instead of "add 100 allow ...". 6171 * In case, swap first and second argument to get the normal form. 6172 */ 6173 if (ac > 1 && isdigit(*av[0])) { 6174 char *p = av[0]; 6175 6176 av[0] = av[1]; 6177 av[1] = p; 6178 } 6179 6180 /* 6181 * Optional: pipe, queue or nat. 6182 */ 6183 do_nat = 0; 6184 do_pipe = 0; 6185 if (!strncmp(*av, "nat", strlen(*av))) 6186 do_nat = 1; 6187 else if (!strncmp(*av, "pipe", strlen(*av))) 6188 do_pipe = 1; 6189 else if (_substrcmp(*av, "queue") == 0) 6190 do_pipe = 2; 6191 else if (!strncmp(*av, "set", strlen(*av))) { 6192 if (ac > 1 && isdigit(av[1][0])) { 6193 use_set = strtonum(av[1], 0, RESVD_SET, &errstr); 6194 if (errstr) 6195 errx(EX_DATAERR, 6196 "invalid set number %s\n", av[1]); 6197 ac -= 2; av += 2; use_set++; 6198 } 6199 } 6200 6201 if (do_pipe || do_nat) { 6202 ac--; 6203 av++; 6204 } 6205 NEED1("missing command"); 6206 6207 /* 6208 * For pipes, queues and nats we normally say 'nat|pipe NN config' 6209 * but the code is easier to parse as 'nat|pipe config NN' 6210 * so we swap the two arguments. 6211 */ 6212 if ((do_pipe || do_nat) && ac > 1 && isdigit(*av[0])) { 6213 char *p = av[0]; 6214 6215 av[0] = av[1]; 6216 av[1] = p; 6217 } 6218 6219 int try_next = 0; 6220 if (use_set == 0) { 6221 if (_substrcmp(*av, "add") == 0) 6222 add(ac, av); 6223 else if (do_nat && _substrcmp(*av, "show") == 0) 6224 show_nat(ac, av); 6225 else if (do_pipe && _substrcmp(*av, "config") == 0) 6226 config_pipe(ac, av); 6227 else if (do_nat && _substrcmp(*av, "config") == 0) 6228 config_nat(ac, av); 6229 else if (_substrcmp(*av, "set") == 0) 6230 sets_handler(ac, av); 6231 else if (_substrcmp(*av, "table") == 0) 6232 table_handler(ac, av); 6233 else if (_substrcmp(*av, "enable") == 0) 6234 sysctl_handler(ac, av, 1); 6235 else if (_substrcmp(*av, "disable") == 0) 6236 sysctl_handler(ac, av, 0); 6237 else 6238 try_next = 1; 6239 } 6240 6241 if (use_set || try_next) { 6242 if (_substrcmp(*av, "delete") == 0) 6243 delete(ac, av); 6244 else if (_substrcmp(*av, "flush") == 0) 6245 flush(do_force); 6246 else if (_substrcmp(*av, "zero") == 0) 6247 zero(ac, av, IP_FW_ZERO); 6248 else if (_substrcmp(*av, "resetlog") == 0) 6249 zero(ac, av, IP_FW_RESETLOG); 6250 else if (_substrcmp(*av, "print") == 0 || 6251 _substrcmp(*av, "list") == 0) 6252 list(ac, av, do_acct); 6253 else if (_substrcmp(*av, "show") == 0) 6254 list(ac, av, 1 /* show counters */); 6255 else 6256 errx(EX_USAGE, "bad command `%s'", *av); 6257 } 6258 6259 /* Free memory allocated in the argument parsing. */ 6260 free_args(save_ac, save_av); 6261 return 0; 6262 } 6263 6264 6265 static void 6266 ipfw_readfile(int ac, char *av[]) 6267 { 6268 #define MAX_ARGS 32 6269 char buf[BUFSIZ]; 6270 char *cmd = NULL, *filename = av[ac-1]; 6271 int c, lineno=0; 6272 FILE *f = NULL; 6273 pid_t preproc = 0; 6274 6275 filename = av[ac-1]; 6276 6277 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) { 6278 switch(c) { 6279 case 'c': 6280 do_compact = 1; 6281 break; 6282 6283 case 'f': 6284 do_force = 1; 6285 break; 6286 6287 case 'N': 6288 do_resolv = 1; 6289 break; 6290 6291 case 'n': 6292 test_only = 1; 6293 break; 6294 6295 case 'p': 6296 cmd = optarg; 6297 /* 6298 * Skip previous args and delete last one, so we 6299 * pass all but the last argument to the preprocessor 6300 * via av[optind-1] 6301 */ 6302 av += optind - 1; 6303 ac -= optind - 1; 6304 if (ac < 2) 6305 errx(EX_USAGE, "no filename argument"); 6306 av[ac-1] = NULL; 6307 fprintf(stderr, "command is %s\n", av[0]); 6308 break; 6309 6310 case 'q': 6311 do_quiet = 1; 6312 break; 6313 6314 case 'S': 6315 show_sets = 1; 6316 break; 6317 6318 default: 6319 errx(EX_USAGE, "bad arguments, for usage" 6320 " summary ``ipfw''"); 6321 } 6322 6323 if (cmd != NULL) 6324 break; 6325 } 6326 6327 if (cmd == NULL && ac != optind + 1) { 6328 fprintf(stderr, "ac %d, optind %d\n", ac, optind); 6329 errx(EX_USAGE, "extraneous filename arguments"); 6330 } 6331 6332 if ((f = fopen(filename, "r")) == NULL) 6333 err(EX_UNAVAILABLE, "fopen: %s", filename); 6334 6335 if (cmd != NULL) { /* pipe through preprocessor */ 6336 int pipedes[2]; 6337 6338 if (pipe(pipedes) == -1) 6339 err(EX_OSERR, "cannot create pipe"); 6340 6341 preproc = fork(); 6342 if (preproc == -1) 6343 err(EX_OSERR, "cannot fork"); 6344 6345 if (preproc == 0) { 6346 /* 6347 * Child, will run the preprocessor with the 6348 * file on stdin and the pipe on stdout. 6349 */ 6350 if (dup2(fileno(f), 0) == -1 6351 || dup2(pipedes[1], 1) == -1) 6352 err(EX_OSERR, "dup2()"); 6353 fclose(f); 6354 close(pipedes[1]); 6355 close(pipedes[0]); 6356 execvp(cmd, av); 6357 err(EX_OSERR, "execvp(%s) failed", cmd); 6358 } else { /* parent, will reopen f as the pipe */ 6359 fclose(f); 6360 close(pipedes[1]); 6361 if ((f = fdopen(pipedes[0], "r")) == NULL) { 6362 int savederrno = errno; 6363 6364 (void)kill(preproc, SIGTERM); 6365 errno = savederrno; 6366 err(EX_OSERR, "fdopen()"); 6367 } 6368 } 6369 } 6370 6371 while (fgets(buf, BUFSIZ, f)) { /* read commands */ 6372 char linename[10]; 6373 char *args[1]; 6374 6375 lineno++; 6376 sprintf(linename, "Line %d", lineno); 6377 setprogname(linename); /* XXX */ 6378 args[0] = buf; 6379 ipfw_main(1, args); 6380 } 6381 fclose(f); 6382 if (cmd != NULL) { 6383 int status; 6384 6385 if (waitpid(preproc, &status, 0) == -1) 6386 errx(EX_OSERR, "waitpid()"); 6387 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 6388 errx(EX_UNAVAILABLE, 6389 "preprocessor exited with status %d", 6390 WEXITSTATUS(status)); 6391 else if (WIFSIGNALED(status)) 6392 errx(EX_UNAVAILABLE, 6393 "preprocessor exited with signal %d", 6394 WTERMSIG(status)); 6395 } 6396 } 6397 6398 int 6399 main(int ac, char *av[]) 6400 { 6401 /* 6402 * If the last argument is an absolute pathname, interpret it 6403 * as a file to be preprocessed. 6404 */ 6405 6406 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) 6407 ipfw_readfile(ac, av); 6408 else { 6409 if (ipfw_main(ac-1, av+1)) 6410 show_usage(); 6411 } 6412 return EX_OK; 6413 } 6414