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