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