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