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