ipfw2.c revision 117577
1252867Sdelphij/* 2252867Sdelphij * Copyright (c) 2002-2003 Luigi Rizzo 3252867Sdelphij * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp 4252867Sdelphij * Copyright (c) 1994 Ugen J.S.Antsilevich 5252867Sdelphij * 6252867Sdelphij * Idea and grammar partially left from: 7252867Sdelphij * Copyright (c) 1993 Daniel Boulet 8252867Sdelphij * 9252867Sdelphij * Redistribution and use in source forms, with and without modification, 10252867Sdelphij * are permitted provided that this entire comment appears intact. 11252867Sdelphij * 12252867Sdelphij * Redistribution in binary form may occur without any restrictions. 13252867Sdelphij * Obviously, it would be nice if you gave credit where credit is due 14252867Sdelphij * but requiring it would be too onerous. 15252867Sdelphij * 16252867Sdelphij * This software is provided ``AS IS'' without any warranties of any kind. 17252867Sdelphij * 18252867Sdelphij * NEW command line interface for IP firewall facility 19252867Sdelphij * 20252867Sdelphij * $FreeBSD: head/sbin/ipfw/ipfw2.c 117577 2003-07-14 18:57:41Z luigi $ 21252867Sdelphij */ 22252867Sdelphij 23252867Sdelphij#include <sys/param.h> 24252867Sdelphij#include <sys/mbuf.h> 25252867Sdelphij#include <sys/socket.h> 26252867Sdelphij#include <sys/sockio.h> 27252867Sdelphij#include <sys/sysctl.h> 28252867Sdelphij#include <sys/time.h> 29252867Sdelphij#include <sys/wait.h> 30252867Sdelphij 31252867Sdelphij#include <ctype.h> 32252867Sdelphij#include <err.h> 33252867Sdelphij#include <errno.h> 34252867Sdelphij#include <grp.h> 35252867Sdelphij#include <limits.h> 36252867Sdelphij#include <netdb.h> 37252867Sdelphij#include <pwd.h> 38252867Sdelphij#include <signal.h> 39252867Sdelphij#include <stdio.h> 40252867Sdelphij#include <stdlib.h> 41252867Sdelphij#include <stdarg.h> 42252867Sdelphij#include <string.h> 43252867Sdelphij#include <timeconv.h> /* XXX do we need this ? */ 44252867Sdelphij#include <unistd.h> 45252867Sdelphij#include <sysexits.h> 46252867Sdelphij 47252867Sdelphij#include <net/if.h> 48252867Sdelphij#include <netinet/in.h> 49252867Sdelphij#include <netinet/in_systm.h> 50252867Sdelphij#include <netinet/ip.h> 51252867Sdelphij#include <netinet/ip_icmp.h> 52252867Sdelphij#include <netinet/ip_fw.h> 53252867Sdelphij#include <net/route.h> /* def. of struct route */ 54252867Sdelphij#include <netinet/ip_dummynet.h> 55252867Sdelphij#include <netinet/tcp.h> 56252867Sdelphij#include <arpa/inet.h> 57252867Sdelphij 58252867Sdelphijint 59252867Sdelphij do_resolv, /* Would try to resolve all */ 60252867Sdelphij do_time, /* Show time stamps */ 61252867Sdelphij do_quiet, /* Be quiet in add and flush */ 62252867Sdelphij do_pipe, /* this cmd refers to a pipe */ 63252867Sdelphij do_sort, /* field to sort results (0 = no) */ 64252867Sdelphij do_dynamic, /* display dynamic rules */ 65252867Sdelphij do_expired, /* display expired dynamic rules */ 66252867Sdelphij do_compact, /* show rules in compact mode */ 67252867Sdelphij show_sets, /* display rule sets */ 68252867Sdelphij test_only, /* only check syntax */ 69252867Sdelphij verbose; 70252867Sdelphij 71252867Sdelphij#define IP_MASK_ALL 0xffffffff 72252867Sdelphij 73252867Sdelphij/* 74252867Sdelphij * _s_x is a structure that stores a string <-> token pairs, used in 75252867Sdelphij * various places in the parser. Entries are stored in arrays, 76252867Sdelphij * with an entry with s=NULL as terminator. 77252867Sdelphij * The search routines are match_token() and match_value(). 78252867Sdelphij * Often, an element with x=0 contains an error string. 79252867Sdelphij * 80252867Sdelphij */ 81252867Sdelphijstruct _s_x { 82252867Sdelphij char const *s; 83252867Sdelphij int x; 84252867Sdelphij}; 85252867Sdelphij 86252867Sdelphijstatic struct _s_x f_tcpflags[] = { 87252867Sdelphij { "syn", TH_SYN }, 88252867Sdelphij { "fin", TH_FIN }, 89252867Sdelphij { "ack", TH_ACK }, 90252867Sdelphij { "psh", TH_PUSH }, 91252867Sdelphij { "rst", TH_RST }, 92252867Sdelphij { "urg", TH_URG }, 93252867Sdelphij { "tcp flag", 0 }, 94252867Sdelphij { NULL, 0 } 95252867Sdelphij}; 96252867Sdelphij 97252867Sdelphijstatic struct _s_x f_tcpopts[] = { 98252867Sdelphij { "mss", IP_FW_TCPOPT_MSS }, 99252867Sdelphij { "maxseg", IP_FW_TCPOPT_MSS }, 100252867Sdelphij { "window", IP_FW_TCPOPT_WINDOW }, 101252867Sdelphij { "sack", IP_FW_TCPOPT_SACK }, 102252867Sdelphij { "ts", IP_FW_TCPOPT_TS }, 103252867Sdelphij { "timestamp", IP_FW_TCPOPT_TS }, 104252867Sdelphij { "cc", IP_FW_TCPOPT_CC }, 105252867Sdelphij { "tcp option", 0 }, 106252867Sdelphij { NULL, 0 } 107252867Sdelphij}; 108252867Sdelphij 109252867Sdelphij/* 110252867Sdelphij * IP options span the range 0 to 255 so we need to remap them 111252867Sdelphij * (though in fact only the low 5 bits are significant). 112252867Sdelphij */ 113252867Sdelphijstatic struct _s_x f_ipopts[] = { 114252867Sdelphij { "ssrr", IP_FW_IPOPT_SSRR}, 115252867Sdelphij { "lsrr", IP_FW_IPOPT_LSRR}, 116252867Sdelphij { "rr", IP_FW_IPOPT_RR}, 117252867Sdelphij { "ts", IP_FW_IPOPT_TS}, 118252867Sdelphij { "ip option", 0 }, 119252867Sdelphij { NULL, 0 } 120252867Sdelphij}; 121252867Sdelphij 122252867Sdelphijstatic struct _s_x f_iptos[] = { 123252867Sdelphij { "lowdelay", IPTOS_LOWDELAY}, 124252867Sdelphij { "throughput", IPTOS_THROUGHPUT}, 125252867Sdelphij { "reliability", IPTOS_RELIABILITY}, 126252867Sdelphij { "mincost", IPTOS_MINCOST}, 127252867Sdelphij { "congestion", IPTOS_CE}, 128252867Sdelphij { "ecntransport", IPTOS_ECT}, 129252867Sdelphij { "ip tos option", 0}, 130252867Sdelphij { NULL, 0 } 131252867Sdelphij}; 132252867Sdelphij 133252867Sdelphijstatic struct _s_x limit_masks[] = { 134252867Sdelphij {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT}, 135252867Sdelphij {"src-addr", DYN_SRC_ADDR}, 136252867Sdelphij {"src-port", DYN_SRC_PORT}, 137252867Sdelphij {"dst-addr", DYN_DST_ADDR}, 138252867Sdelphij {"dst-port", DYN_DST_PORT}, 139252867Sdelphij {NULL, 0} 140252867Sdelphij}; 141252867Sdelphij 142252867Sdelphij/* 143252867Sdelphij * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines 144252867Sdelphij * This is only used in this code. 145252867Sdelphij */ 146252867Sdelphij#define IPPROTO_ETHERTYPE 0x1000 147252867Sdelphijstatic struct _s_x ether_types[] = { 148252867Sdelphij /* 149252867Sdelphij * Note, we cannot use "-:&/" in the names because they are field 150252867Sdelphij * separators in the type specifications. Also, we use s = NULL as 151252867Sdelphij * end-delimiter, because a type of 0 can be legal. 152252867Sdelphij */ 153252867Sdelphij { "ip", 0x0800 }, 154252867Sdelphij { "ipv4", 0x0800 }, 155252867Sdelphij { "ipv6", 0x86dd }, 156252867Sdelphij { "arp", 0x0806 }, 157252867Sdelphij { "rarp", 0x8035 }, 158252867Sdelphij { "vlan", 0x8100 }, 159252867Sdelphij { "loop", 0x9000 }, 160252867Sdelphij { "trail", 0x1000 }, 161252867Sdelphij { "at", 0x809b }, 162252867Sdelphij { "atalk", 0x809b }, 163252867Sdelphij { "aarp", 0x80f3 }, 164252867Sdelphij { "pppoe_disc", 0x8863 }, 165252867Sdelphij { "pppoe_sess", 0x8864 }, 166252867Sdelphij { "ipx_8022", 0x00E0 }, 167252867Sdelphij { "ipx_8023", 0x0000 }, 168252867Sdelphij { "ipx_ii", 0x8137 }, 169252867Sdelphij { "ipx_snap", 0x8137 }, 170252867Sdelphij { "ipx", 0x8137 }, 171252867Sdelphij { "ns", 0x0600 }, 172252867Sdelphij { NULL, 0 } 173252867Sdelphij}; 174252867Sdelphij 175252867Sdelphijstatic void show_usage(void); 176252867Sdelphij 177252867Sdelphijenum tokens { 178252867Sdelphij TOK_NULL=0, 179252867Sdelphij 180252867Sdelphij TOK_OR, 181252867Sdelphij TOK_NOT, 182252867Sdelphij TOK_STARTBRACE, 183252867Sdelphij TOK_ENDBRACE, 184252867Sdelphij 185252867Sdelphij TOK_ACCEPT, 186252867Sdelphij TOK_COUNT, 187 TOK_PIPE, 188 TOK_QUEUE, 189 TOK_DIVERT, 190 TOK_TEE, 191 TOK_FORWARD, 192 TOK_SKIPTO, 193 TOK_DENY, 194 TOK_REJECT, 195 TOK_RESET, 196 TOK_UNREACH, 197 TOK_CHECKSTATE, 198 199 TOK_UID, 200 TOK_GID, 201 TOK_IN, 202 TOK_LIMIT, 203 TOK_KEEPSTATE, 204 TOK_LAYER2, 205 TOK_OUT, 206 TOK_XMIT, 207 TOK_RECV, 208 TOK_VIA, 209 TOK_FRAG, 210 TOK_IPOPTS, 211 TOK_IPLEN, 212 TOK_IPID, 213 TOK_IPPRECEDENCE, 214 TOK_IPTOS, 215 TOK_IPTTL, 216 TOK_IPVER, 217 TOK_ESTAB, 218 TOK_SETUP, 219 TOK_TCPFLAGS, 220 TOK_TCPOPTS, 221 TOK_TCPSEQ, 222 TOK_TCPACK, 223 TOK_TCPWIN, 224 TOK_ICMPTYPES, 225 TOK_MAC, 226 TOK_MACTYPE, 227 TOK_VERREVPATH, 228 TOK_IPSEC, 229 TOK_COMMENT, 230 231 TOK_PLR, 232 TOK_NOERROR, 233 TOK_BUCKETS, 234 TOK_DSTIP, 235 TOK_SRCIP, 236 TOK_DSTPORT, 237 TOK_SRCPORT, 238 TOK_ALL, 239 TOK_MASK, 240 TOK_BW, 241 TOK_DELAY, 242 TOK_RED, 243 TOK_GRED, 244 TOK_DROPTAIL, 245 TOK_PROTO, 246 TOK_WEIGHT, 247}; 248 249struct _s_x dummynet_params[] = { 250 { "plr", TOK_PLR }, 251 { "noerror", TOK_NOERROR }, 252 { "buckets", TOK_BUCKETS }, 253 { "dst-ip", TOK_DSTIP }, 254 { "src-ip", TOK_SRCIP }, 255 { "dst-port", TOK_DSTPORT }, 256 { "src-port", TOK_SRCPORT }, 257 { "proto", TOK_PROTO }, 258 { "weight", TOK_WEIGHT }, 259 { "all", TOK_ALL }, 260 { "mask", TOK_MASK }, 261 { "droptail", TOK_DROPTAIL }, 262 { "red", TOK_RED }, 263 { "gred", TOK_GRED }, 264 { "bw", TOK_BW }, 265 { "bandwidth", TOK_BW }, 266 { "delay", TOK_DELAY }, 267 { "pipe", TOK_PIPE }, 268 { "queue", TOK_QUEUE }, 269 { "dummynet-params", TOK_NULL }, 270 { NULL, 0 } /* terminator */ 271}; 272 273struct _s_x rule_actions[] = { 274 { "accept", TOK_ACCEPT }, 275 { "pass", TOK_ACCEPT }, 276 { "allow", TOK_ACCEPT }, 277 { "permit", TOK_ACCEPT }, 278 { "count", TOK_COUNT }, 279 { "pipe", TOK_PIPE }, 280 { "queue", TOK_QUEUE }, 281 { "divert", TOK_DIVERT }, 282 { "tee", TOK_TEE }, 283 { "fwd", TOK_FORWARD }, 284 { "forward", TOK_FORWARD }, 285 { "skipto", TOK_SKIPTO }, 286 { "deny", TOK_DENY }, 287 { "drop", TOK_DENY }, 288 { "reject", TOK_REJECT }, 289 { "reset", TOK_RESET }, 290 { "unreach", TOK_UNREACH }, 291 { "check-state", TOK_CHECKSTATE }, 292 { "//", TOK_COMMENT }, 293 { NULL, 0 } /* terminator */ 294}; 295 296struct _s_x rule_options[] = { 297 { "uid", TOK_UID }, 298 { "gid", TOK_GID }, 299 { "in", TOK_IN }, 300 { "limit", TOK_LIMIT }, 301 { "keep-state", TOK_KEEPSTATE }, 302 { "bridged", TOK_LAYER2 }, 303 { "layer2", TOK_LAYER2 }, 304 { "out", TOK_OUT }, 305 { "xmit", TOK_XMIT }, 306 { "recv", TOK_RECV }, 307 { "via", TOK_VIA }, 308 { "fragment", TOK_FRAG }, 309 { "frag", TOK_FRAG }, 310 { "ipoptions", TOK_IPOPTS }, 311 { "ipopts", TOK_IPOPTS }, 312 { "iplen", TOK_IPLEN }, 313 { "ipid", TOK_IPID }, 314 { "ipprecedence", TOK_IPPRECEDENCE }, 315 { "iptos", TOK_IPTOS }, 316 { "ipttl", TOK_IPTTL }, 317 { "ipversion", TOK_IPVER }, 318 { "ipver", TOK_IPVER }, 319 { "estab", TOK_ESTAB }, 320 { "established", TOK_ESTAB }, 321 { "setup", TOK_SETUP }, 322 { "tcpflags", TOK_TCPFLAGS }, 323 { "tcpflgs", TOK_TCPFLAGS }, 324 { "tcpoptions", TOK_TCPOPTS }, 325 { "tcpopts", TOK_TCPOPTS }, 326 { "tcpseq", TOK_TCPSEQ }, 327 { "tcpack", TOK_TCPACK }, 328 { "tcpwin", TOK_TCPWIN }, 329 { "icmptype", TOK_ICMPTYPES }, 330 { "icmptypes", TOK_ICMPTYPES }, 331 { "dst-ip", TOK_DSTIP }, 332 { "src-ip", TOK_SRCIP }, 333 { "dst-port", TOK_DSTPORT }, 334 { "src-port", TOK_SRCPORT }, 335 { "proto", TOK_PROTO }, 336 { "MAC", TOK_MAC }, 337 { "mac", TOK_MAC }, 338 { "mac-type", TOK_MACTYPE }, 339 { "verrevpath", TOK_VERREVPATH }, 340 { "ipsec", TOK_IPSEC }, 341 { "//", TOK_COMMENT }, 342 343 { "not", TOK_NOT }, /* pseudo option */ 344 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */ 345 { "or", TOK_OR }, /* pseudo option */ 346 { "|", /* escape */ TOK_OR }, /* pseudo option */ 347 { "{", TOK_STARTBRACE }, /* pseudo option */ 348 { "(", TOK_STARTBRACE }, /* pseudo option */ 349 { "}", TOK_ENDBRACE }, /* pseudo option */ 350 { ")", TOK_ENDBRACE }, /* pseudo option */ 351 { NULL, 0 } /* terminator */ 352}; 353 354static __inline uint64_t 355align_uint64(uint64_t *pll) { 356 uint64_t ret; 357 358 bcopy (pll, &ret, sizeof(ret)); 359 return ret; 360}; 361 362/* 363 * conditionally runs the command. 364 */ 365static int 366do_cmd(int optname, void *optval, socklen_t optlen) 367{ 368 static int s = -1; /* the socket */ 369 int i; 370 371 if (test_only) 372 return 0; 373 374 if (s == -1) 375 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); 376 if (s < 0) 377 err(EX_UNAVAILABLE, "socket"); 378 379 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET || 380 optname == IP_FW_ADD) 381 i = getsockopt(s, IPPROTO_IP, optname, optval, 382 (socklen_t *)optlen); 383 else 384 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen); 385 return i; 386} 387 388/** 389 * match_token takes a table and a string, returns the value associated 390 * with the string (-1 in case of failure). 391 */ 392static int 393match_token(struct _s_x *table, char *string) 394{ 395 struct _s_x *pt; 396 uint i = strlen(string); 397 398 for (pt = table ; i && pt->s != NULL ; pt++) 399 if (strlen(pt->s) == i && !bcmp(string, pt->s, i)) 400 return pt->x; 401 return -1; 402}; 403 404/** 405 * match_value takes a table and a value, returns the string associated 406 * with the value (NULL in case of failure). 407 */ 408static char const * 409match_value(struct _s_x *p, int value) 410{ 411 for (; p->s != NULL; p++) 412 if (p->x == value) 413 return p->s; 414 return NULL; 415} 416 417/* 418 * prints one port, symbolic or numeric 419 */ 420static void 421print_port(int proto, uint16_t port) 422{ 423 424 if (proto == IPPROTO_ETHERTYPE) { 425 char const *s; 426 427 if (do_resolv && (s = match_value(ether_types, port)) ) 428 printf("%s", s); 429 else 430 printf("0x%04x", port); 431 } else { 432 struct servent *se = NULL; 433 if (do_resolv) { 434 struct protoent *pe = getprotobynumber(proto); 435 436 se = getservbyport(htons(port), pe ? pe->p_name : NULL); 437 } 438 if (se) 439 printf("%s", se->s_name); 440 else 441 printf("%d", port); 442 } 443} 444 445struct _s_x _port_name[] = { 446 {"dst-port", O_IP_DSTPORT}, 447 {"src-port", O_IP_SRCPORT}, 448 {"ipid", O_IPID}, 449 {"iplen", O_IPLEN}, 450 {"ipttl", O_IPTTL}, 451 {"mac-type", O_MAC_TYPE}, 452 {NULL, 0} 453}; 454 455/* 456 * Print the values in a list 16-bit items of the types above. 457 * XXX todo: add support for mask. 458 */ 459static void 460print_newports(ipfw_insn_u16 *cmd, int proto, int opcode) 461{ 462 uint16_t *p = cmd->ports; 463 int i; 464 char const *sep; 465 466 if (cmd->o.len & F_NOT) 467 printf(" not"); 468 if (opcode != 0) { 469 sep = match_value(_port_name, opcode); 470 if (sep == NULL) 471 sep = "???"; 472 printf (" %s", sep); 473 } 474 sep = " "; 475 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) { 476 printf(sep); 477 print_port(proto, p[0]); 478 if (p[0] != p[1]) { 479 printf("-"); 480 print_port(proto, p[1]); 481 } 482 sep = ","; 483 } 484} 485 486/* 487 * Like strtol, but also translates service names into port numbers 488 * for some protocols. 489 * In particular: 490 * proto == -1 disables the protocol check; 491 * proto == IPPROTO_ETHERTYPE looks up an internal table 492 * proto == <some value in /etc/protocols> matches the values there. 493 * Returns *end == s in case the parameter is not found. 494 */ 495static int 496strtoport(char *s, char **end, int base, int proto) 497{ 498 char *p, *buf; 499 char *s1; 500 int i; 501 502 *end = s; /* default - not found */ 503 if (*s == '\0') 504 return 0; /* not found */ 505 506 if (isdigit(*s)) 507 return strtol(s, end, base); 508 509 /* 510 * find separator. '\\' escapes the next char. 511 */ 512 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++) 513 if (*s1 == '\\' && s1[1] != '\0') 514 s1++; 515 516 buf = malloc(s1 - s + 1); 517 if (buf == NULL) 518 return 0; 519 520 /* 521 * copy into a buffer skipping backslashes 522 */ 523 for (p = s, i = 0; p != s1 ; p++) 524 if (*p != '\\') 525 buf[i++] = *p; 526 buf[i++] = '\0'; 527 528 if (proto == IPPROTO_ETHERTYPE) { 529 i = match_token(ether_types, buf); 530 free(buf); 531 if (i != -1) { /* found */ 532 *end = s1; 533 return i; 534 } 535 } else { 536 struct protoent *pe = NULL; 537 struct servent *se; 538 539 if (proto != 0) 540 pe = getprotobynumber(proto); 541 setservent(1); 542 se = getservbyname(buf, pe ? pe->p_name : NULL); 543 free(buf); 544 if (se != NULL) { 545 *end = s1; 546 return ntohs(se->s_port); 547 } 548 } 549 return 0; /* not found */ 550} 551 552/* 553 * Fill the body of the command with the list of port ranges. 554 */ 555static int 556fill_newports(ipfw_insn_u16 *cmd, char *av, int proto) 557{ 558 uint16_t a, b, *p = cmd->ports; 559 int i = 0; 560 char *s = av; 561 562 while (*s) { 563 a = strtoport(av, &s, 0, proto); 564 if (s == av) /* no parameter */ 565 break; 566 if (*s == '-') { /* a range */ 567 av = s+1; 568 b = strtoport(av, &s, 0, proto); 569 if (s == av) /* no parameter */ 570 break; 571 p[0] = a; 572 p[1] = b; 573 } else if (*s == ',' || *s == '\0' ) 574 p[0] = p[1] = a; 575 else /* invalid separator */ 576 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n", 577 *s, av); 578 i++; 579 p += 2; 580 av = s+1; 581 } 582 if (i > 0) { 583 if (i+1 > F_LEN_MASK) 584 errx(EX_DATAERR, "too many ports/ranges\n"); 585 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */ 586 } 587 return i; 588} 589 590static struct _s_x icmpcodes[] = { 591 { "net", ICMP_UNREACH_NET }, 592 { "host", ICMP_UNREACH_HOST }, 593 { "protocol", ICMP_UNREACH_PROTOCOL }, 594 { "port", ICMP_UNREACH_PORT }, 595 { "needfrag", ICMP_UNREACH_NEEDFRAG }, 596 { "srcfail", ICMP_UNREACH_SRCFAIL }, 597 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN }, 598 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN }, 599 { "isolated", ICMP_UNREACH_ISOLATED }, 600 { "net-prohib", ICMP_UNREACH_NET_PROHIB }, 601 { "host-prohib", ICMP_UNREACH_HOST_PROHIB }, 602 { "tosnet", ICMP_UNREACH_TOSNET }, 603 { "toshost", ICMP_UNREACH_TOSHOST }, 604 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB }, 605 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE }, 606 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF }, 607 { NULL, 0 } 608}; 609 610static void 611fill_reject_code(u_short *codep, char *str) 612{ 613 int val; 614 char *s; 615 616 val = strtoul(str, &s, 0); 617 if (s == str || *s != '\0' || val >= 0x100) 618 val = match_token(icmpcodes, str); 619 if (val < 0) 620 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str); 621 *codep = val; 622 return; 623} 624 625static void 626print_reject_code(uint16_t code) 627{ 628 char const *s = match_value(icmpcodes, code); 629 630 if (s != NULL) 631 printf("unreach %s", s); 632 else 633 printf("unreach %u", code); 634} 635 636/* 637 * Returns the number of bits set (from left) in a contiguous bitmask, 638 * or -1 if the mask is not contiguous. 639 * XXX this needs a proper fix. 640 * This effectively works on masks in big-endian (network) format. 641 * when compiled on little endian architectures. 642 * 643 * First bit is bit 7 of the first byte -- note, for MAC addresses, 644 * the first bit on the wire is bit 0 of the first byte. 645 * len is the max length in bits. 646 */ 647static int 648contigmask(uint8_t *p, int len) 649{ 650 int i, n; 651 652 for (i=0; i<len ; i++) 653 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */ 654 break; 655 for (n=i+1; n < len; n++) 656 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0) 657 return -1; /* mask not contiguous */ 658 return i; 659} 660 661/* 662 * print flags set/clear in the two bitmasks passed as parameters. 663 * There is a specialized check for f_tcpflags. 664 */ 665static void 666print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list) 667{ 668 char const *comma = ""; 669 int i; 670 uint8_t set = cmd->arg1 & 0xff; 671 uint8_t clear = (cmd->arg1 >> 8) & 0xff; 672 673 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) { 674 printf(" setup"); 675 return; 676 } 677 678 printf(" %s ", name); 679 for (i=0; list[i].x != 0; i++) { 680 if (set & list[i].x) { 681 set &= ~list[i].x; 682 printf("%s%s", comma, list[i].s); 683 comma = ","; 684 } 685 if (clear & list[i].x) { 686 clear &= ~list[i].x; 687 printf("%s!%s", comma, list[i].s); 688 comma = ","; 689 } 690 } 691} 692 693/* 694 * Print the ip address contained in a command. 695 */ 696static void 697print_ip(ipfw_insn_ip *cmd, char const *s) 698{ 699 struct hostent *he = NULL; 700 int len = F_LEN((ipfw_insn *)cmd); 701 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d; 702 703 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s); 704 705 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) { 706 printf("me"); 707 return; 708 } 709 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) { 710 uint32_t x, *map = (uint32_t *)&(cmd->mask); 711 int i, j; 712 char comma = '{'; 713 714 x = cmd->o.arg1 - 1; 715 x = htonl( ~x ); 716 cmd->addr.s_addr = htonl(cmd->addr.s_addr); 717 printf("%s/%d", inet_ntoa(cmd->addr), 718 contigmask((uint8_t *)&x, 32)); 719 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr); 720 x &= 0xff; /* base */ 721 /* 722 * Print bits and ranges. 723 * Locate first bit set (i), then locate first bit unset (j). 724 * If we have 3+ consecutive bits set, then print them as a 725 * range, otherwise only print the initial bit and rescan. 726 */ 727 for (i=0; i < cmd->o.arg1; i++) 728 if (map[i/32] & (1<<(i & 31))) { 729 for (j=i+1; j < cmd->o.arg1; j++) 730 if (!(map[ j/32] & (1<<(j & 31)))) 731 break; 732 printf("%c%d", comma, i+x); 733 if (j>i+2) { /* range has at least 3 elements */ 734 printf("-%d", j-1+x); 735 i = j-1; 736 } 737 comma = ','; 738 } 739 printf("}"); 740 return; 741 } 742 /* 743 * len == 2 indicates a single IP, whereas lists of 1 or more 744 * addr/mask pairs have len = (2n+1). We convert len to n so we 745 * use that to count the number of entries. 746 */ 747 for (len = len / 2; len > 0; len--, a += 2) { 748 int mb = /* mask length */ 749 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ? 750 32 : contigmask((uint8_t *)&(a[1]), 32); 751 if (mb == 32 && do_resolv) 752 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET); 753 if (he != NULL) /* resolved to name */ 754 printf("%s", he->h_name); 755 else if (mb == 0) /* any */ 756 printf("any"); 757 else { /* numeric IP followed by some kind of mask */ 758 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) ); 759 if (mb < 0) 760 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) ); 761 else if (mb < 32) 762 printf("/%d", mb); 763 } 764 if (len > 1) 765 printf(","); 766 } 767} 768 769/* 770 * prints a MAC address/mask pair 771 */ 772static void 773print_mac(uint8_t *addr, uint8_t *mask) 774{ 775 int l = contigmask(mask, 48); 776 777 if (l == 0) 778 printf(" any"); 779 else { 780 printf(" %02x:%02x:%02x:%02x:%02x:%02x", 781 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); 782 if (l == -1) 783 printf("&%02x:%02x:%02x:%02x:%02x:%02x", 784 mask[0], mask[1], mask[2], 785 mask[3], mask[4], mask[5]); 786 else if (l < 48) 787 printf("/%d", l); 788 } 789} 790 791static void 792fill_icmptypes(ipfw_insn_u32 *cmd, char *av) 793{ 794 uint8_t type; 795 796 cmd->d[0] = 0; 797 while (*av) { 798 if (*av == ',') 799 av++; 800 801 type = strtoul(av, &av, 0); 802 803 if (*av != ',' && *av != '\0') 804 errx(EX_DATAERR, "invalid ICMP type"); 805 806 if (type > 31) 807 errx(EX_DATAERR, "ICMP type out of range"); 808 809 cmd->d[0] |= 1 << type; 810 } 811 cmd->o.opcode = O_ICMPTYPE; 812 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 813} 814 815static void 816print_icmptypes(ipfw_insn_u32 *cmd) 817{ 818 int i; 819 char sep= ' '; 820 821 printf(" icmptypes"); 822 for (i = 0; i < 32; i++) { 823 if ( (cmd->d[0] & (1 << (i))) == 0) 824 continue; 825 printf("%c%d", sep, i); 826 sep = ','; 827 } 828} 829 830/* 831 * show_ipfw() prints the body of an ipfw rule. 832 * Because the standard rule has at least proto src_ip dst_ip, we use 833 * a helper function to produce these entries if not provided explicitly. 834 * The first argument is the list of fields we have, the second is 835 * the list of fields we want to be printed. 836 * 837 * Special cases if we have provided a MAC header: 838 * + if the rule does not contain IP addresses/ports, do not print them; 839 * + if the rule does not contain an IP proto, print "all" instead of "ip"; 840 * 841 * Once we have 'have_options', IP header fields are printed as options. 842 */ 843#define HAVE_PROTO 0x0001 844#define HAVE_SRCIP 0x0002 845#define HAVE_DSTIP 0x0004 846#define HAVE_MAC 0x0008 847#define HAVE_MACTYPE 0x0010 848#define HAVE_OPTIONS 0x8000 849 850#define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP) 851static void 852show_prerequisites(int *flags, int want, int cmd) 853{ 854 if ( (*flags & HAVE_IP) == HAVE_IP) 855 *flags |= HAVE_OPTIONS; 856 857 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC && 858 cmd != O_MAC_TYPE) { 859 /* 860 * mac-type was optimized out by the compiler, 861 * restore it 862 */ 863 printf(" any"); 864 *flags |= HAVE_MACTYPE | HAVE_OPTIONS; 865 return; 866 } 867 if ( !(*flags & HAVE_OPTIONS)) { 868 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) 869 printf(" ip"); 870 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP)) 871 printf(" from any"); 872 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP)) 873 printf(" to any"); 874 } 875 *flags |= want; 876} 877 878static void 879show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth) 880{ 881 static int twidth = 0; 882 int l; 883 ipfw_insn *cmd; 884 int proto = 0; /* default */ 885 int flags = 0; /* prerequisites */ 886 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */ 887 int or_block = 0; /* we are in an or block */ 888 uint32_t set_disable; 889 890 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable)); 891 892 if (set_disable & (1 << rule->set)) { /* disabled */ 893 if (!show_sets) 894 return; 895 else 896 printf("# DISABLED "); 897 } 898 printf("%05u ", rule->rulenum); 899 900 if (pcwidth>0 || bcwidth>0) 901 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt), 902 bcwidth, align_uint64(&rule->bcnt)); 903 904 if (do_time == 2) 905 printf("%10u ", rule->timestamp); 906 else if (do_time == 1) { 907 char timestr[30]; 908 time_t t = (time_t)0; 909 910 if (twidth == 0) { 911 strcpy(timestr, ctime(&t)); 912 *strchr(timestr, '\n') = '\0'; 913 twidth = strlen(timestr); 914 } 915 if (rule->timestamp) { 916#if _FreeBSD_version < 500000 /* XXX check */ 917#define _long_to_time(x) (time_t)(x) 918#endif 919 t = _long_to_time(rule->timestamp); 920 921 strcpy(timestr, ctime(&t)); 922 *strchr(timestr, '\n') = '\0'; 923 printf("%s ", timestr); 924 } else { 925 printf("%*s", twidth, " "); 926 } 927 } 928 929 if (show_sets) 930 printf("set %d ", rule->set); 931 932 /* 933 * print the optional "match probability" 934 */ 935 if (rule->cmd_len > 0) { 936 cmd = rule->cmd ; 937 if (cmd->opcode == O_PROB) { 938 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd; 939 double d = 1.0 * p->d[0]; 940 941 d = (d / 0x7fffffff); 942 printf("prob %f ", d); 943 } 944 } 945 946 /* 947 * first print actions 948 */ 949 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule); 950 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) { 951 switch(cmd->opcode) { 952 case O_CHECK_STATE: 953 printf("check-state"); 954 flags = HAVE_IP; /* avoid printing anything else */ 955 break; 956 957 case O_ACCEPT: 958 printf("allow"); 959 break; 960 961 case O_COUNT: 962 printf("count"); 963 break; 964 965 case O_DENY: 966 printf("deny"); 967 break; 968 969 case O_REJECT: 970 if (cmd->arg1 == ICMP_REJECT_RST) 971 printf("reset"); 972 else if (cmd->arg1 == ICMP_UNREACH_HOST) 973 printf("reject"); 974 else 975 print_reject_code(cmd->arg1); 976 break; 977 978 case O_SKIPTO: 979 printf("skipto %u", cmd->arg1); 980 break; 981 982 case O_PIPE: 983 printf("pipe %u", cmd->arg1); 984 break; 985 986 case O_QUEUE: 987 printf("queue %u", cmd->arg1); 988 break; 989 990 case O_DIVERT: 991 printf("divert %u", cmd->arg1); 992 break; 993 994 case O_TEE: 995 printf("tee %u", cmd->arg1); 996 break; 997 998 case O_FORWARD_IP: 999 { 1000 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd; 1001 1002 printf("fwd %s", inet_ntoa(s->sa.sin_addr)); 1003 if (s->sa.sin_port) 1004 printf(",%d", s->sa.sin_port); 1005 } 1006 break; 1007 1008 case O_LOG: /* O_LOG is printed last */ 1009 logptr = (ipfw_insn_log *)cmd; 1010 break; 1011 1012 default: 1013 printf("** unrecognized action %d len %d", 1014 cmd->opcode, cmd->len); 1015 } 1016 } 1017 if (logptr) { 1018 if (logptr->max_log > 0) 1019 printf(" log logamount %d", logptr->max_log); 1020 else 1021 printf(" log"); 1022 } 1023 1024 /* 1025 * then print the body. 1026 */ 1027 if (rule->_pad & 1) { /* empty rules before options */ 1028 if (!do_compact) 1029 printf(" ip from any to any"); 1030 flags |= HAVE_IP | HAVE_OPTIONS; 1031 } 1032 1033 for (l = rule->act_ofs, cmd = rule->cmd ; 1034 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) { 1035 /* useful alias */ 1036 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd; 1037 1038 show_prerequisites(&flags, 0, cmd->opcode); 1039 1040 switch(cmd->opcode) { 1041 case O_PROB: 1042 break; /* done already */ 1043 1044 case O_PROBE_STATE: 1045 break; /* no need to print anything here */ 1046 1047 case O_MACADDR2: { 1048 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd; 1049 1050 if ((cmd->len & F_OR) && !or_block) 1051 printf(" {"); 1052 if (cmd->len & F_NOT) 1053 printf(" not"); 1054 printf(" MAC"); 1055 flags |= HAVE_MAC; 1056 print_mac(m->addr, m->mask); 1057 print_mac(m->addr + 6, m->mask + 6); 1058 } 1059 break; 1060 1061 case O_MAC_TYPE: 1062 if ((cmd->len & F_OR) && !or_block) 1063 printf(" {"); 1064 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE, 1065 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1066 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS; 1067 break; 1068 1069 case O_IP_SRC: 1070 case O_IP_SRC_MASK: 1071 case O_IP_SRC_ME: 1072 case O_IP_SRC_SET: 1073 show_prerequisites(&flags, HAVE_PROTO, 0); 1074 if (!(flags & HAVE_SRCIP)) 1075 printf(" from"); 1076 if ((cmd->len & F_OR) && !or_block) 1077 printf(" {"); 1078 print_ip((ipfw_insn_ip *)cmd, 1079 (flags & HAVE_OPTIONS) ? " src-ip" : ""); 1080 flags |= HAVE_SRCIP; 1081 break; 1082 1083 case O_IP_DST: 1084 case O_IP_DST_MASK: 1085 case O_IP_DST_ME: 1086 case O_IP_DST_SET: 1087 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1088 if (!(flags & HAVE_DSTIP)) 1089 printf(" to"); 1090 if ((cmd->len & F_OR) && !or_block) 1091 printf(" {"); 1092 print_ip((ipfw_insn_ip *)cmd, 1093 (flags & HAVE_OPTIONS) ? " dst-ip" : ""); 1094 flags |= HAVE_DSTIP; 1095 break; 1096 1097 case O_IP_DSTPORT: 1098 show_prerequisites(&flags, HAVE_IP, 0); 1099 case O_IP_SRCPORT: 1100 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0); 1101 if ((cmd->len & F_OR) && !or_block) 1102 printf(" {"); 1103 print_newports((ipfw_insn_u16 *)cmd, proto, 1104 (flags & HAVE_OPTIONS) ? cmd->opcode : 0); 1105 break; 1106 1107 case O_PROTO: { 1108 struct protoent *pe; 1109 1110 if ((cmd->len & F_OR) && !or_block) 1111 printf(" {"); 1112 if (cmd->len & F_NOT) 1113 printf(" not"); 1114 proto = cmd->arg1; 1115 pe = getprotobynumber(cmd->arg1); 1116 if (flags & HAVE_OPTIONS) 1117 printf(" proto"); 1118 if (pe) 1119 printf(" %s", pe->p_name); 1120 else 1121 printf(" %u", cmd->arg1); 1122 } 1123 flags |= HAVE_PROTO; 1124 break; 1125 1126 default: /*options ... */ 1127 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0); 1128 if ((cmd->len & F_OR) && !or_block) 1129 printf(" {"); 1130 if (cmd->len & F_NOT && cmd->opcode != O_IN) 1131 printf(" not"); 1132 switch(cmd->opcode) { 1133 case O_FRAG: 1134 printf(" frag"); 1135 break; 1136 1137 case O_IN: 1138 printf(cmd->len & F_NOT ? " out" : " in"); 1139 break; 1140 1141 case O_LAYER2: 1142 printf(" layer2"); 1143 break; 1144 case O_XMIT: 1145 case O_RECV: 1146 case O_VIA: { 1147 char const *s; 1148 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd; 1149 1150 if (cmd->opcode == O_XMIT) 1151 s = "xmit"; 1152 else if (cmd->opcode == O_RECV) 1153 s = "recv"; 1154 else /* if (cmd->opcode == O_VIA) */ 1155 s = "via"; 1156 if (cmdif->name[0] == '\0') 1157 printf(" %s %s", s, 1158 inet_ntoa(cmdif->p.ip)); 1159 else if (cmdif->p.unit == -1) 1160 printf(" %s %s*", s, cmdif->name); 1161 else 1162 printf(" %s %s%d", s, cmdif->name, 1163 cmdif->p.unit); 1164 } 1165 break; 1166 1167 case O_IPID: 1168 if (F_LEN(cmd) == 1) 1169 printf(" ipid %u", cmd->arg1 ); 1170 else 1171 print_newports((ipfw_insn_u16 *)cmd, 0, 1172 O_IPID); 1173 break; 1174 1175 case O_IPTTL: 1176 if (F_LEN(cmd) == 1) 1177 printf(" ipttl %u", cmd->arg1 ); 1178 else 1179 print_newports((ipfw_insn_u16 *)cmd, 0, 1180 O_IPTTL); 1181 break; 1182 1183 case O_IPVER: 1184 printf(" ipver %u", cmd->arg1 ); 1185 break; 1186 1187 case O_IPPRECEDENCE: 1188 printf(" ipprecedence %u", (cmd->arg1) >> 5 ); 1189 break; 1190 1191 case O_IPLEN: 1192 if (F_LEN(cmd) == 1) 1193 printf(" iplen %u", cmd->arg1 ); 1194 else 1195 print_newports((ipfw_insn_u16 *)cmd, 0, 1196 O_IPLEN); 1197 break; 1198 1199 case O_IPOPT: 1200 print_flags("ipoptions", cmd, f_ipopts); 1201 break; 1202 1203 case O_IPTOS: 1204 print_flags("iptos", cmd, f_iptos); 1205 break; 1206 1207 case O_ICMPTYPE: 1208 print_icmptypes((ipfw_insn_u32 *)cmd); 1209 break; 1210 1211 case O_ESTAB: 1212 printf(" established"); 1213 break; 1214 1215 case O_TCPFLAGS: 1216 print_flags("tcpflags", cmd, f_tcpflags); 1217 break; 1218 1219 case O_TCPOPTS: 1220 print_flags("tcpoptions", cmd, f_tcpopts); 1221 break; 1222 1223 case O_TCPWIN: 1224 printf(" tcpwin %d", ntohs(cmd->arg1)); 1225 break; 1226 1227 case O_TCPACK: 1228 printf(" tcpack %d", ntohl(cmd32->d[0])); 1229 break; 1230 1231 case O_TCPSEQ: 1232 printf(" tcpseq %d", ntohl(cmd32->d[0])); 1233 break; 1234 1235 case O_UID: 1236 { 1237 struct passwd *pwd = getpwuid(cmd32->d[0]); 1238 1239 if (pwd) 1240 printf(" uid %s", pwd->pw_name); 1241 else 1242 printf(" uid %u", cmd32->d[0]); 1243 } 1244 break; 1245 1246 case O_GID: 1247 { 1248 struct group *grp = getgrgid(cmd32->d[0]); 1249 1250 if (grp) 1251 printf(" gid %s", grp->gr_name); 1252 else 1253 printf(" gid %u", cmd32->d[0]); 1254 } 1255 break; 1256 1257 case O_VERREVPATH: 1258 printf(" verrevpath"); 1259 break; 1260 1261 case O_IPSEC: 1262 printf(" ipsec"); 1263 break; 1264 1265 case O_NOP: 1266 printf(" // %s", (char *)(cmd + 1)); 1267 break; 1268 1269 case O_KEEP_STATE: 1270 printf(" keep-state"); 1271 break; 1272 1273 case O_LIMIT: 1274 { 1275 struct _s_x *p = limit_masks; 1276 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 1277 uint8_t x = c->limit_mask; 1278 char const *comma = " "; 1279 1280 printf(" limit"); 1281 for (; p->x != 0 ; p++) 1282 if ((x & p->x) == p->x) { 1283 x &= ~p->x; 1284 printf("%s%s", comma, p->s); 1285 comma = ","; 1286 } 1287 printf(" %d", c->conn_limit); 1288 } 1289 break; 1290 1291 default: 1292 printf(" [opcode %d len %d]", 1293 cmd->opcode, cmd->len); 1294 } 1295 } 1296 if (cmd->len & F_OR) { 1297 printf(" or"); 1298 or_block = 1; 1299 } else if (or_block) { 1300 printf(" }"); 1301 or_block = 0; 1302 } 1303 } 1304 show_prerequisites(&flags, HAVE_IP, 0); 1305 1306 printf("\n"); 1307} 1308 1309static void 1310show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth) 1311{ 1312 struct protoent *pe; 1313 struct in_addr a; 1314 uint16_t rulenum; 1315 1316 if (!do_expired) { 1317 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT)) 1318 return; 1319 } 1320 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 1321 printf("%05d", rulenum); 1322 if (pcwidth>0 || bcwidth>0) 1323 printf(" %*llu %*llu (%ds)", pcwidth, 1324 align_uint64(&d->pcnt), bcwidth, 1325 align_uint64(&d->bcnt), d->expire); 1326 switch (d->dyn_type) { 1327 case O_LIMIT_PARENT: 1328 printf(" PARENT %d", d->count); 1329 break; 1330 case O_LIMIT: 1331 printf(" LIMIT"); 1332 break; 1333 case O_KEEP_STATE: /* bidir, no mask */ 1334 printf(" STATE"); 1335 break; 1336 } 1337 1338 if ((pe = getprotobynumber(d->id.proto)) != NULL) 1339 printf(" %s", pe->p_name); 1340 else 1341 printf(" proto %u", d->id.proto); 1342 1343 a.s_addr = htonl(d->id.src_ip); 1344 printf(" %s %d", inet_ntoa(a), d->id.src_port); 1345 1346 a.s_addr = htonl(d->id.dst_ip); 1347 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port); 1348 printf("\n"); 1349} 1350 1351static int 1352sort_q(const void *pa, const void *pb) 1353{ 1354 int rev = (do_sort < 0); 1355 int field = rev ? -do_sort : do_sort; 1356 long long res = 0; 1357 const struct dn_flow_queue *a = pa; 1358 const struct dn_flow_queue *b = pb; 1359 1360 switch (field) { 1361 case 1: /* pkts */ 1362 res = a->len - b->len; 1363 break; 1364 case 2: /* bytes */ 1365 res = a->len_bytes - b->len_bytes; 1366 break; 1367 1368 case 3: /* tot pkts */ 1369 res = a->tot_pkts - b->tot_pkts; 1370 break; 1371 1372 case 4: /* tot bytes */ 1373 res = a->tot_bytes - b->tot_bytes; 1374 break; 1375 } 1376 if (res < 0) 1377 res = -1; 1378 if (res > 0) 1379 res = 1; 1380 return (int)(rev ? res : -res); 1381} 1382 1383static void 1384list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q) 1385{ 1386 int l; 1387 1388 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n", 1389 fs->flow_mask.proto, 1390 fs->flow_mask.src_ip, fs->flow_mask.src_port, 1391 fs->flow_mask.dst_ip, fs->flow_mask.dst_port); 1392 if (fs->rq_elements == 0) 1393 return; 1394 1395 printf("BKT Prot ___Source IP/port____ " 1396 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n"); 1397 if (do_sort != 0) 1398 heapsort(q, fs->rq_elements, sizeof *q, sort_q); 1399 for (l = 0; l < fs->rq_elements; l++) { 1400 struct in_addr ina; 1401 struct protoent *pe; 1402 1403 ina.s_addr = htonl(q[l].id.src_ip); 1404 printf("%3d ", q[l].hash_slot); 1405 pe = getprotobynumber(q[l].id.proto); 1406 if (pe) 1407 printf("%-4s ", pe->p_name); 1408 else 1409 printf("%4u ", q[l].id.proto); 1410 printf("%15s/%-5d ", 1411 inet_ntoa(ina), q[l].id.src_port); 1412 ina.s_addr = htonl(q[l].id.dst_ip); 1413 printf("%15s/%-5d ", 1414 inet_ntoa(ina), q[l].id.dst_port); 1415 printf("%4qu %8qu %2u %4u %3u\n", 1416 q[l].tot_pkts, q[l].tot_bytes, 1417 q[l].len, q[l].len_bytes, q[l].drops); 1418 if (verbose) 1419 printf(" S %20qd F %20qd\n", 1420 q[l].S, q[l].F); 1421 } 1422} 1423 1424static void 1425print_flowset_parms(struct dn_flow_set *fs, char *prefix) 1426{ 1427 int l; 1428 char qs[30]; 1429 char plr[30]; 1430 char red[90]; /* Display RED parameters */ 1431 1432 l = fs->qsize; 1433 if (fs->flags_fs & DN_QSIZE_IS_BYTES) { 1434 if (l >= 8192) 1435 sprintf(qs, "%d KB", l / 1024); 1436 else 1437 sprintf(qs, "%d B", l); 1438 } else 1439 sprintf(qs, "%3d sl.", l); 1440 if (fs->plr) 1441 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff)); 1442 else 1443 plr[0] = '\0'; 1444 if (fs->flags_fs & DN_IS_RED) /* RED parameters */ 1445 sprintf(red, 1446 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f", 1447 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ', 1448 1.0 * fs->w_q / (double)(1 << SCALE_RED), 1449 SCALE_VAL(fs->min_th), 1450 SCALE_VAL(fs->max_th), 1451 1.0 * fs->max_p / (double)(1 << SCALE_RED)); 1452 else 1453 sprintf(red, "droptail"); 1454 1455 printf("%s %s%s %d queues (%d buckets) %s\n", 1456 prefix, qs, plr, fs->rq_elements, fs->rq_size, red); 1457} 1458 1459static void 1460list_pipes(void *data, uint nbytes, int ac, char *av[]) 1461{ 1462 int rulenum; 1463 void *next = data; 1464 struct dn_pipe *p = (struct dn_pipe *) data; 1465 struct dn_flow_set *fs; 1466 struct dn_flow_queue *q; 1467 int l; 1468 1469 if (ac > 0) 1470 rulenum = strtoul(*av++, NULL, 10); 1471 else 1472 rulenum = 0; 1473 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) { 1474 double b = p->bandwidth; 1475 char buf[30]; 1476 char prefix[80]; 1477 1478 if (p->next != (struct dn_pipe *)DN_IS_PIPE) 1479 break; /* done with pipes, now queues */ 1480 1481 /* 1482 * compute length, as pipe have variable size 1483 */ 1484 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q); 1485 next = (char *)p + l; 1486 nbytes -= l; 1487 1488 if (rulenum != 0 && rulenum != p->pipe_nr) 1489 continue; 1490 1491 /* 1492 * Print rate (or clocking interface) 1493 */ 1494 if (p->if_name[0] != '\0') 1495 sprintf(buf, "%s", p->if_name); 1496 else if (b == 0) 1497 sprintf(buf, "unlimited"); 1498 else if (b >= 1000000) 1499 sprintf(buf, "%7.3f Mbit/s", b/1000000); 1500 else if (b >= 1000) 1501 sprintf(buf, "%7.3f Kbit/s", b/1000); 1502 else 1503 sprintf(buf, "%7.3f bit/s ", b); 1504 1505 sprintf(prefix, "%05d: %s %4d ms ", 1506 p->pipe_nr, buf, p->delay); 1507 print_flowset_parms(&(p->fs), prefix); 1508 if (verbose) 1509 printf(" V %20qd\n", p->V >> MY_M); 1510 1511 q = (struct dn_flow_queue *)(p+1); 1512 list_queues(&(p->fs), q); 1513 } 1514 for (fs = next; nbytes >= sizeof *fs; fs = next) { 1515 char prefix[80]; 1516 1517 if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE) 1518 break; 1519 l = sizeof(*fs) + fs->rq_elements * sizeof(*q); 1520 next = (char *)fs + l; 1521 nbytes -= l; 1522 q = (struct dn_flow_queue *)(fs+1); 1523 sprintf(prefix, "q%05d: weight %d pipe %d ", 1524 fs->fs_nr, fs->weight, fs->parent_nr); 1525 print_flowset_parms(fs, prefix); 1526 list_queues(fs, q); 1527 } 1528} 1529 1530/* 1531 * This one handles all set-related commands 1532 * ipfw set { show | enable | disable } 1533 * ipfw set swap X Y 1534 * ipfw set move X to Y 1535 * ipfw set move rule X to Y 1536 */ 1537static void 1538sets_handler(int ac, char *av[]) 1539{ 1540 uint32_t set_disable, masks[2]; 1541 int i, nbytes; 1542 uint16_t rulenum; 1543 uint8_t cmd, new_set; 1544 1545 ac--; 1546 av++; 1547 1548 if (!ac) 1549 errx(EX_USAGE, "set needs command"); 1550 if (!strncmp(*av, "show", strlen(*av)) ) { 1551 void *data; 1552 char const *msg; 1553 1554 nbytes = sizeof(struct ip_fw); 1555 if ((data = calloc(1, nbytes)) == NULL) 1556 err(EX_OSERR, "calloc"); 1557 if (do_cmd(IP_FW_GET, data, (socklen_t)&nbytes) < 0) 1558 err(EX_OSERR, "getsockopt(IP_FW_GET)"); 1559 bcopy(&((struct ip_fw *)data)->next_rule, 1560 &set_disable, sizeof(set_disable)); 1561 1562 for (i = 0, msg = "disable" ; i < 31; i++) 1563 if ((set_disable & (1<<i))) { 1564 printf("%s %d", msg, i); 1565 msg = ""; 1566 } 1567 msg = (set_disable) ? " enable" : "enable"; 1568 for (i = 0; i < 31; i++) 1569 if (!(set_disable & (1<<i))) { 1570 printf("%s %d", msg, i); 1571 msg = ""; 1572 } 1573 printf("\n"); 1574 } else if (!strncmp(*av, "swap", strlen(*av))) { 1575 ac--; av++; 1576 if (ac != 2) 1577 errx(EX_USAGE, "set swap needs 2 set numbers\n"); 1578 rulenum = atoi(av[0]); 1579 new_set = atoi(av[1]); 1580 if (!isdigit(*(av[0])) || rulenum > 30) 1581 errx(EX_DATAERR, "invalid set number %s\n", av[0]); 1582 if (!isdigit(*(av[1])) || new_set > 30) 1583 errx(EX_DATAERR, "invalid set number %s\n", av[1]); 1584 masks[0] = (4 << 24) | (new_set << 16) | (rulenum); 1585 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 1586 } else if (!strncmp(*av, "move", strlen(*av))) { 1587 ac--; av++; 1588 if (ac && !strncmp(*av, "rule", strlen(*av))) { 1589 cmd = 2; 1590 ac--; av++; 1591 } else 1592 cmd = 3; 1593 if (ac != 3 || strncmp(av[1], "to", strlen(*av))) 1594 errx(EX_USAGE, "syntax: set move [rule] X to Y\n"); 1595 rulenum = atoi(av[0]); 1596 new_set = atoi(av[2]); 1597 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > 30) || 1598 (cmd == 2 && rulenum == 65535) ) 1599 errx(EX_DATAERR, "invalid source number %s\n", av[0]); 1600 if (!isdigit(*(av[2])) || new_set > 30) 1601 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]); 1602 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum); 1603 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t)); 1604 } else if (!strncmp(*av, "disable", strlen(*av)) || 1605 !strncmp(*av, "enable", strlen(*av)) ) { 1606 int which = !strncmp(*av, "enable", strlen(*av)) ? 1 : 0; 1607 1608 ac--; av++; 1609 masks[0] = masks[1] = 0; 1610 1611 while (ac) { 1612 if (isdigit(**av)) { 1613 i = atoi(*av); 1614 if (i < 0 || i > 30) 1615 errx(EX_DATAERR, 1616 "invalid set number %d\n", i); 1617 masks[which] |= (1<<i); 1618 } else if (!strncmp(*av, "disable", strlen(*av))) 1619 which = 0; 1620 else if (!strncmp(*av, "enable", strlen(*av))) 1621 which = 1; 1622 else 1623 errx(EX_DATAERR, 1624 "invalid set command %s\n", *av); 1625 av++; ac--; 1626 } 1627 if ( (masks[0] & masks[1]) != 0 ) 1628 errx(EX_DATAERR, 1629 "cannot enable and disable the same set\n"); 1630 1631 i = do_cmd(IP_FW_DEL, masks, sizeof(masks)); 1632 if (i) 1633 warn("set enable/disable: setsockopt(IP_FW_DEL)"); 1634 } else 1635 errx(EX_USAGE, "invalid set command %s\n", *av); 1636} 1637 1638static void 1639sysctl_handler(int ac, char *av[], int which) 1640{ 1641 ac--; 1642 av++; 1643 1644 if (*av == NULL) { 1645 warnx("missing keyword to enable/disable\n"); 1646 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) { 1647 sysctlbyname("net.inet.ip.fw.enable", NULL, 0, 1648 &which, sizeof(which)); 1649 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) { 1650 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0, 1651 &which, sizeof(which)); 1652 } else if (strncmp(*av, "debug", strlen(*av)) == 0) { 1653 sysctlbyname("net.inet.ip.fw.debug", NULL, 0, 1654 &which, sizeof(which)); 1655 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) { 1656 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0, 1657 &which, sizeof(which)); 1658 } else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) { 1659 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0, 1660 &which, sizeof(which)); 1661 } else { 1662 warnx("unrecognize enable/disable keyword: %s\n", *av); 1663 } 1664} 1665 1666static void 1667list(int ac, char *av[], int show_counters) 1668{ 1669 struct ip_fw *r; 1670 ipfw_dyn_rule *dynrules, *d; 1671 1672#define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r))) 1673 char *lim; 1674 void *data = NULL; 1675 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width; 1676 int exitval = EX_OK; 1677 int lac; 1678 char **lav; 1679 u_long rnum, last; 1680 char *endptr; 1681 int seen = 0; 1682 1683 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET; 1684 int nalloc = 1024; /* start somewhere... */ 1685 1686 if (test_only) { 1687 fprintf(stderr, "Testing only, list disabled\n"); 1688 return; 1689 } 1690 1691 ac--; 1692 av++; 1693 1694 /* get rules or pipes from kernel, resizing array as necessary */ 1695 nbytes = nalloc; 1696 1697 while (nbytes >= nalloc) { 1698 nalloc = nalloc * 2 + 200; 1699 nbytes = nalloc; 1700 if ((data = realloc(data, nbytes)) == NULL) 1701 err(EX_OSERR, "realloc"); 1702 if (do_cmd(ocmd, data, (socklen_t)&nbytes) < 0) 1703 err(EX_OSERR, "getsockopt(IP_%s_GET)", 1704 do_pipe ? "DUMMYNET" : "FW"); 1705 } 1706 1707 if (do_pipe) { 1708 list_pipes(data, nbytes, ac, av); 1709 goto done; 1710 } 1711 1712 /* 1713 * Count static rules. They have variable size so we 1714 * need to scan the list to count them. 1715 */ 1716 for (nstat = 1, r = data, lim = (char *)data + nbytes; 1717 r->rulenum < 65535 && (char *)r < lim; 1718 ++nstat, r = NEXT(r) ) 1719 ; /* nothing */ 1720 1721 /* 1722 * Count dynamic rules. This is easier as they have 1723 * fixed size. 1724 */ 1725 r = NEXT(r); 1726 dynrules = (ipfw_dyn_rule *)r ; 1727 n = (char *)r - (char *)data; 1728 ndyn = (nbytes - n) / sizeof *dynrules; 1729 1730 /* if showing stats, figure out column widths ahead of time */ 1731 bcwidth = pcwidth = 0; 1732 if (show_counters) { 1733 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) { 1734 /* packet counter */ 1735 width = snprintf(NULL, 0, "%llu", 1736 align_uint64(&r->pcnt)); 1737 if (width > pcwidth) 1738 pcwidth = width; 1739 1740 /* byte counter */ 1741 width = snprintf(NULL, 0, "%llu", 1742 align_uint64(&r->bcnt)); 1743 if (width > bcwidth) 1744 bcwidth = width; 1745 } 1746 } 1747 if (do_dynamic && ndyn) { 1748 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 1749 width = snprintf(NULL, 0, "%llu", 1750 align_uint64(&d->pcnt)); 1751 if (width > pcwidth) 1752 pcwidth = width; 1753 1754 width = snprintf(NULL, 0, "%llu", 1755 align_uint64(&d->bcnt)); 1756 if (width > bcwidth) 1757 bcwidth = width; 1758 } 1759 } 1760 /* if no rule numbers were specified, list all rules */ 1761 if (ac == 0) { 1762 for (n = 0, r = data; n < nstat; n++, r = NEXT(r) ) 1763 show_ipfw(r, pcwidth, bcwidth); 1764 1765 if (do_dynamic && ndyn) { 1766 printf("## Dynamic rules (%d):\n", ndyn); 1767 for (n = 0, d = dynrules; n < ndyn; n++, d++) 1768 show_dyn_ipfw(d, pcwidth, bcwidth); 1769 } 1770 goto done; 1771 } 1772 1773 /* display specific rules requested on command line */ 1774 1775 for (lac = ac, lav = av; lac != 0; lac--) { 1776 /* convert command line rule # */ 1777 last = rnum = strtoul(*lav++, &endptr, 10); 1778 if (*endptr == '-') 1779 last = strtoul(endptr+1, &endptr, 10); 1780 if (*endptr) { 1781 exitval = EX_USAGE; 1782 warnx("invalid rule number: %s", *(lav - 1)); 1783 continue; 1784 } 1785 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) { 1786 if (r->rulenum > last) 1787 break; 1788 if (r->rulenum >= rnum && r->rulenum <= last) { 1789 show_ipfw(r, pcwidth, bcwidth); 1790 seen = 1; 1791 } 1792 } 1793 if (!seen) { 1794 /* give precedence to other error(s) */ 1795 if (exitval == EX_OK) 1796 exitval = EX_UNAVAILABLE; 1797 warnx("rule %lu does not exist", rnum); 1798 } 1799 } 1800 1801 if (do_dynamic && ndyn) { 1802 printf("## Dynamic rules:\n"); 1803 for (lac = ac, lav = av; lac != 0; lac--) { 1804 rnum = strtoul(*lav++, &endptr, 10); 1805 if (*endptr == '-') 1806 last = strtoul(endptr+1, &endptr, 10); 1807 if (*endptr) 1808 /* already warned */ 1809 continue; 1810 for (n = 0, d = dynrules; n < ndyn; n++, d++) { 1811 uint16_t rulenum; 1812 1813 bcopy(&d->rule, &rulenum, sizeof(rulenum)); 1814 if (rulenum > rnum) 1815 break; 1816 if (r->rulenum >= rnum && r->rulenum <= last) 1817 show_dyn_ipfw(d, pcwidth, bcwidth); 1818 } 1819 } 1820 } 1821 1822 ac = 0; 1823 1824done: 1825 free(data); 1826 1827 if (exitval != EX_OK) 1828 exit(exitval); 1829#undef NEXT 1830} 1831 1832static void 1833show_usage(void) 1834{ 1835 fprintf(stderr, "usage: ipfw [options]\n" 1836"do \"ipfw -h\" or see ipfw manpage for details\n" 1837); 1838 exit(EX_USAGE); 1839} 1840 1841static void 1842help(void) 1843{ 1844 fprintf(stderr, 1845"ipfw syntax summary (but please do read the ipfw(8) manpage):\n" 1846"ipfw [-acdeftTnNpqS] <command> where <command> is one of:\n" 1847"add [num] [set N] [prob x] RULE-BODY\n" 1848"{pipe|queue} N config PIPE-BODY\n" 1849"[pipe|queue] {zero|delete|show} [N{,N}]\n" 1850"set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n" 1851"\n" 1852"RULE-BODY: check-state [LOG] | ACTION [LOG] ADDR [OPTION_LIST]\n" 1853"ACTION: check-state | allow | count | deny | reject | skipto N |\n" 1854" {divert|tee} PORT | forward ADDR | pipe N | queue N\n" 1855"ADDR: [ MAC dst src ether_type ] \n" 1856" [ from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n" 1857"IPADDR: [not] { any | me | ip/bits{x,y,z} | IPLIST }\n" 1858"IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n" 1859"OPTION_LIST: OPTION [OPTION_LIST]\n" 1860"OPTION: bridged | {dst-ip|src-ip} ADDR | {dst-port|src-port} LIST |\n" 1861" estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n" 1862" iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n" 1863" ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n" 1864" mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n" 1865" setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n" 1866" verrevpath\n" 1867); 1868exit(0); 1869} 1870 1871 1872static int 1873lookup_host (char *host, struct in_addr *ipaddr) 1874{ 1875 struct hostent *he; 1876 1877 if (!inet_aton(host, ipaddr)) { 1878 if ((he = gethostbyname(host)) == NULL) 1879 return(-1); 1880 *ipaddr = *(struct in_addr *)he->h_addr_list[0]; 1881 } 1882 return(0); 1883} 1884 1885/* 1886 * fills the addr and mask fields in the instruction as appropriate from av. 1887 * Update length as appropriate. 1888 * The following formats are allowed: 1889 * any matches any IP. Actually returns an empty instruction. 1890 * me returns O_IP_*_ME 1891 * 1.2.3.4 single IP address 1892 * 1.2.3.4:5.6.7.8 address:mask 1893 * 1.2.3.4/24 address/mask 1894 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet 1895 * We can have multiple comma-separated address/mask entries. 1896 */ 1897static void 1898fill_ip(ipfw_insn_ip *cmd, char *av) 1899{ 1900 int len = 0; 1901 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d; 1902 1903 cmd->o.len &= ~F_LEN_MASK; /* zero len */ 1904 1905 if (!strncmp(av, "any", strlen(av))) 1906 return; 1907 1908 if (!strncmp(av, "me", strlen(av))) { 1909 cmd->o.len |= F_INSN_SIZE(ipfw_insn); 1910 return; 1911 } 1912 1913 while (av) { 1914 /* 1915 * After the address we can have '/' or ':' indicating a mask, 1916 * ',' indicating another address follows, '{' indicating a 1917 * set of addresses of unspecified size. 1918 */ 1919 char *p = strpbrk(av, "/:,{"); 1920 int masklen; 1921 char md; 1922 1923 if (p) { 1924 md = *p; 1925 *p++ = '\0'; 1926 } else 1927 md = '\0'; 1928 1929 if (lookup_host(av, (struct in_addr *)&d[0]) != 0) 1930 errx(EX_NOHOST, "hostname ``%s'' unknown", av); 1931 switch (md) { 1932 case ':': 1933 if (!inet_aton(p, (struct in_addr *)&d[1])) 1934 errx(EX_DATAERR, "bad netmask ``%s''", p); 1935 break; 1936 case '/': 1937 masklen = atoi(p); 1938 if (masklen == 0) 1939 d[1] = htonl(0); /* mask */ 1940 else if (masklen > 32) 1941 errx(EX_DATAERR, "bad width ``%s''", p); 1942 else 1943 d[1] = htonl(~0 << (32 - masklen)); 1944 break; 1945 case '{': /* no mask, assume /24 and put back the '{' */ 1946 d[1] = htonl(~0 << (32 - 24)); 1947 *(--p) = md; 1948 break; 1949 1950 case ',': /* single address plus continuation */ 1951 *(--p) = md; 1952 /* FALLTHROUGH */ 1953 case 0: /* initialization value */ 1954 default: 1955 d[1] = htonl(~0); /* force /32 */ 1956 break; 1957 } 1958 d[0] &= d[1]; /* mask base address with mask */ 1959 /* find next separator */ 1960 if (p) 1961 p = strpbrk(p, ",{"); 1962 if (p && *p == '{') { 1963 /* 1964 * We have a set of addresses. They are stored as follows: 1965 * arg1 is the set size (powers of 2, 2..256) 1966 * addr is the base address IN HOST FORMAT 1967 * mask.. is an array of arg1 bits (rounded up to 1968 * the next multiple of 32) with bits set 1969 * for each host in the map. 1970 */ 1971 uint32_t *map = (uint32_t *)&cmd->mask; 1972 int low, high; 1973 int i = contigmask((uint8_t *)&(d[1]), 32); 1974 1975 if (len > 0) 1976 errx(EX_DATAERR, "address set cannot be in a list"); 1977 if (i < 24 || i > 31) 1978 errx(EX_DATAERR, "invalid set with mask %d\n", i); 1979 cmd->o.arg1 = 1<<(32-i); /* map length */ 1980 d[0] = ntohl(d[0]); /* base addr in host format */ 1981 cmd->o.opcode = O_IP_DST_SET; /* default */ 1982 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32; 1983 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++) 1984 map[i] = 0; /* clear map */ 1985 1986 av = p + 1; 1987 low = d[0] & 0xff; 1988 high = low + cmd->o.arg1 - 1; 1989 /* 1990 * Here, i stores the previous value when we specify a range 1991 * of addresses within a mask, e.g. 45-63. i = -1 means we 1992 * have no previous value. 1993 */ 1994 i = -1; /* previous value in a range */ 1995 while (isdigit(*av)) { 1996 char *s; 1997 int a = strtol(av, &s, 0); 1998 1999 if (s == av) { /* no parameter */ 2000 if (*av != '}') 2001 errx(EX_DATAERR, "set not closed\n"); 2002 if (i != -1) 2003 errx(EX_DATAERR, "incomplete range %d-", i); 2004 break; 2005 } 2006 if (a < low || a > high) 2007 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n", 2008 a, low, high); 2009 a -= low; 2010 if (i == -1) /* no previous in range */ 2011 i = a; 2012 else { /* check that range is valid */ 2013 if (i > a) 2014 errx(EX_DATAERR, "invalid range %d-%d", 2015 i+low, a+low); 2016 if (*s == '-') 2017 errx(EX_DATAERR, "double '-' in range"); 2018 } 2019 for (; i <= a; i++) 2020 map[i/32] |= 1<<(i & 31); 2021 i = -1; 2022 if (*s == '-') 2023 i = a; 2024 else if (*s == '}') 2025 break; 2026 av = s+1; 2027 } 2028 return; 2029 } 2030 av = p; 2031 if (av) /* then *av must be a ',' */ 2032 av++; 2033 2034 /* Check this entry */ 2035 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */ 2036 /* 2037 * 'any' turns the entire list into a NOP. 2038 * 'not any' never matches, so it is removed from the 2039 * list unless it is the only item, in which case we 2040 * report an error. 2041 */ 2042 if (cmd->o.len & F_NOT) { /* "not any" never matches */ 2043 if (av == NULL && len == 0) /* only this entry */ 2044 errx(EX_DATAERR, "not any never matches"); 2045 } 2046 /* else do nothing and skip this entry */ 2047 continue; 2048 } 2049 /* A single IP can be stored in an optimized format */ 2050 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) { 2051 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32); 2052 return; 2053 } 2054 len += 2; /* two words... */ 2055 d += 2; 2056 } /* end while */ 2057 cmd->o.len |= len+1; 2058} 2059 2060 2061/* 2062 * helper function to process a set of flags and set bits in the 2063 * appropriate masks. 2064 */ 2065static void 2066fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode, 2067 struct _s_x *flags, char *p) 2068{ 2069 uint8_t set=0, clear=0; 2070 2071 while (p && *p) { 2072 char *q; /* points to the separator */ 2073 int val; 2074 uint8_t *which; /* mask we are working on */ 2075 2076 if (*p == '!') { 2077 p++; 2078 which = &clear; 2079 } else 2080 which = &set; 2081 q = strchr(p, ','); 2082 if (q) 2083 *q++ = '\0'; 2084 val = match_token(flags, p); 2085 if (val <= 0) 2086 errx(EX_DATAERR, "invalid flag %s", p); 2087 *which |= (uint8_t)val; 2088 p = q; 2089 } 2090 cmd->opcode = opcode; 2091 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1; 2092 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8); 2093} 2094 2095 2096static void 2097delete(int ac, char *av[]) 2098{ 2099 uint32_t rulenum; 2100 struct dn_pipe p; 2101 int i; 2102 int exitval = EX_OK; 2103 int do_set = 0; 2104 2105 memset(&p, 0, sizeof p); 2106 2107 av++; ac--; 2108 if (ac > 0 && !strncmp(*av, "set", strlen(*av))) { 2109 do_set = 1; /* delete set */ 2110 ac--; av++; 2111 } 2112 2113 /* Rule number */ 2114 while (ac && isdigit(**av)) { 2115 i = atoi(*av); av++; ac--; 2116 if (do_pipe) { 2117 if (do_pipe == 1) 2118 p.pipe_nr = i; 2119 else 2120 p.fs.fs_nr = i; 2121 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p); 2122 if (i) { 2123 exitval = 1; 2124 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)", 2125 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr); 2126 } 2127 } else { 2128 rulenum = (i & 0xffff) | (do_set << 24); 2129 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum); 2130 if (i) { 2131 exitval = EX_UNAVAILABLE; 2132 warn("rule %u: setsockopt(IP_FW_DEL)", 2133 rulenum); 2134 } 2135 } 2136 } 2137 if (exitval != EX_OK) 2138 exit(exitval); 2139} 2140 2141 2142/* 2143 * fill the interface structure. We do not check the name as we can 2144 * create interfaces dynamically, so checking them at insert time 2145 * makes relatively little sense. 2146 * A '*' following the name means any unit. 2147 */ 2148static void 2149fill_iface(ipfw_insn_if *cmd, char *arg) 2150{ 2151 cmd->name[0] = '\0'; 2152 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if); 2153 2154 /* Parse the interface or address */ 2155 if (!strcmp(arg, "any")) 2156 cmd->o.len = 0; /* effectively ignore this command */ 2157 else if (!isdigit(*arg)) { 2158 char *q; 2159 2160 strncpy(cmd->name, arg, sizeof(cmd->name)); 2161 cmd->name[sizeof(cmd->name) - 1] = '\0'; 2162 /* find first digit or wildcard */ 2163 for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++) 2164 continue; 2165 cmd->p.unit = (*q == '*') ? -1 : atoi(q); 2166 *q = '\0'; 2167 } else if (!inet_aton(arg, &cmd->p.ip)) 2168 errx(EX_DATAERR, "bad ip address ``%s''", arg); 2169} 2170 2171/* 2172 * the following macro returns an error message if we run out of 2173 * arguments. 2174 */ 2175#define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);} 2176 2177static void 2178config_pipe(int ac, char **av) 2179{ 2180 struct dn_pipe p; 2181 int i; 2182 char *end; 2183 uint32_t a; 2184 void *par = NULL; 2185 2186 memset(&p, 0, sizeof p); 2187 2188 av++; ac--; 2189 /* Pipe number */ 2190 if (ac && isdigit(**av)) { 2191 i = atoi(*av); av++; ac--; 2192 if (do_pipe == 1) 2193 p.pipe_nr = i; 2194 else 2195 p.fs.fs_nr = i; 2196 } 2197 while (ac > 0) { 2198 double d; 2199 int tok = match_token(dummynet_params, *av); 2200 ac--; av++; 2201 2202 switch(tok) { 2203 case TOK_NOERROR: 2204 p.fs.flags_fs |= DN_NOERROR; 2205 break; 2206 2207 case TOK_PLR: 2208 NEED1("plr needs argument 0..1\n"); 2209 d = strtod(av[0], NULL); 2210 if (d > 1) 2211 d = 1; 2212 else if (d < 0) 2213 d = 0; 2214 p.fs.plr = (int)(d*0x7fffffff); 2215 ac--; av++; 2216 break; 2217 2218 case TOK_QUEUE: 2219 NEED1("queue needs queue size\n"); 2220 end = NULL; 2221 p.fs.qsize = strtoul(av[0], &end, 0); 2222 if (*end == 'K' || *end == 'k') { 2223 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 2224 p.fs.qsize *= 1024; 2225 } else if (*end == 'B' || !strncmp(end, "by", 2)) { 2226 p.fs.flags_fs |= DN_QSIZE_IS_BYTES; 2227 } 2228 ac--; av++; 2229 break; 2230 2231 case TOK_BUCKETS: 2232 NEED1("buckets needs argument\n"); 2233 p.fs.rq_size = strtoul(av[0], NULL, 0); 2234 ac--; av++; 2235 break; 2236 2237 case TOK_MASK: 2238 NEED1("mask needs mask specifier\n"); 2239 /* 2240 * per-flow queue, mask is dst_ip, dst_port, 2241 * src_ip, src_port, proto measured in bits 2242 */ 2243 par = NULL; 2244 2245 p.fs.flow_mask.dst_ip = 0; 2246 p.fs.flow_mask.src_ip = 0; 2247 p.fs.flow_mask.dst_port = 0; 2248 p.fs.flow_mask.src_port = 0; 2249 p.fs.flow_mask.proto = 0; 2250 end = NULL; 2251 2252 while (ac >= 1) { 2253 uint32_t *p32 = NULL; 2254 uint16_t *p16 = NULL; 2255 2256 tok = match_token(dummynet_params, *av); 2257 ac--; av++; 2258 switch(tok) { 2259 case TOK_ALL: 2260 /* 2261 * special case, all bits significant 2262 */ 2263 p.fs.flow_mask.dst_ip = ~0; 2264 p.fs.flow_mask.src_ip = ~0; 2265 p.fs.flow_mask.dst_port = ~0; 2266 p.fs.flow_mask.src_port = ~0; 2267 p.fs.flow_mask.proto = ~0; 2268 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 2269 goto end_mask; 2270 2271 case TOK_DSTIP: 2272 p32 = &p.fs.flow_mask.dst_ip; 2273 break; 2274 2275 case TOK_SRCIP: 2276 p32 = &p.fs.flow_mask.src_ip; 2277 break; 2278 2279 case TOK_DSTPORT: 2280 p16 = &p.fs.flow_mask.dst_port; 2281 break; 2282 2283 case TOK_SRCPORT: 2284 p16 = &p.fs.flow_mask.src_port; 2285 break; 2286 2287 case TOK_PROTO: 2288 break; 2289 2290 default: 2291 ac++; av--; /* backtrack */ 2292 goto end_mask; 2293 } 2294 if (ac < 1) 2295 errx(EX_USAGE, "mask: value missing"); 2296 if (*av[0] == '/') { 2297 a = strtoul(av[0]+1, &end, 0); 2298 a = (a == 32) ? ~0 : (1 << a) - 1; 2299 } else 2300 a = strtoul(av[0], &end, 0); 2301 if (p32 != NULL) 2302 *p32 = a; 2303 else if (p16 != NULL) { 2304 if (a > 65535) 2305 errx(EX_DATAERR, 2306 "mask: must be 16 bit"); 2307 *p16 = (uint16_t)a; 2308 } else { 2309 if (a > 255) 2310 errx(EX_DATAERR, 2311 "mask: must be 8 bit"); 2312 p.fs.flow_mask.proto = (uint8_t)a; 2313 } 2314 if (a != 0) 2315 p.fs.flags_fs |= DN_HAVE_FLOW_MASK; 2316 ac--; av++; 2317 } /* end while, config masks */ 2318end_mask: 2319 break; 2320 2321 case TOK_RED: 2322 case TOK_GRED: 2323 NEED1("red/gred needs w_q/min_th/max_th/max_p\n"); 2324 p.fs.flags_fs |= DN_IS_RED; 2325 if (tok == TOK_GRED) 2326 p.fs.flags_fs |= DN_IS_GENTLE_RED; 2327 /* 2328 * the format for parameters is w_q/min_th/max_th/max_p 2329 */ 2330 if ((end = strsep(&av[0], "/"))) { 2331 double w_q = strtod(end, NULL); 2332 if (w_q > 1 || w_q <= 0) 2333 errx(EX_DATAERR, "0 < w_q <= 1"); 2334 p.fs.w_q = (int) (w_q * (1 << SCALE_RED)); 2335 } 2336 if ((end = strsep(&av[0], "/"))) { 2337 p.fs.min_th = strtoul(end, &end, 0); 2338 if (*end == 'K' || *end == 'k') 2339 p.fs.min_th *= 1024; 2340 } 2341 if ((end = strsep(&av[0], "/"))) { 2342 p.fs.max_th = strtoul(end, &end, 0); 2343 if (*end == 'K' || *end == 'k') 2344 p.fs.max_th *= 1024; 2345 } 2346 if ((end = strsep(&av[0], "/"))) { 2347 double max_p = strtod(end, NULL); 2348 if (max_p > 1 || max_p <= 0) 2349 errx(EX_DATAERR, "0 < max_p <= 1"); 2350 p.fs.max_p = (int)(max_p * (1 << SCALE_RED)); 2351 } 2352 ac--; av++; 2353 break; 2354 2355 case TOK_DROPTAIL: 2356 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED); 2357 break; 2358 2359 case TOK_BW: 2360 NEED1("bw needs bandwidth or interface\n"); 2361 if (do_pipe != 1) 2362 errx(EX_DATAERR, "bandwidth only valid for pipes"); 2363 /* 2364 * set clocking interface or bandwidth value 2365 */ 2366 if (av[0][0] >= 'a' && av[0][0] <= 'z') { 2367 int l = sizeof(p.if_name)-1; 2368 /* interface name */ 2369 strncpy(p.if_name, av[0], l); 2370 p.if_name[l] = '\0'; 2371 p.bandwidth = 0; 2372 } else { 2373 p.if_name[0] = '\0'; 2374 p.bandwidth = strtoul(av[0], &end, 0); 2375 if (*end == 'K' || *end == 'k') { 2376 end++; 2377 p.bandwidth *= 1000; 2378 } else if (*end == 'M') { 2379 end++; 2380 p.bandwidth *= 1000000; 2381 } 2382 if (*end == 'B' || !strncmp(end, "by", 2)) 2383 p.bandwidth *= 8; 2384 if (p.bandwidth < 0) 2385 errx(EX_DATAERR, "bandwidth too large"); 2386 } 2387 ac--; av++; 2388 break; 2389 2390 case TOK_DELAY: 2391 if (do_pipe != 1) 2392 errx(EX_DATAERR, "delay only valid for pipes"); 2393 NEED1("delay needs argument 0..10000ms\n"); 2394 p.delay = strtoul(av[0], NULL, 0); 2395 ac--; av++; 2396 break; 2397 2398 case TOK_WEIGHT: 2399 if (do_pipe == 1) 2400 errx(EX_DATAERR,"weight only valid for queues"); 2401 NEED1("weight needs argument 0..100\n"); 2402 p.fs.weight = strtoul(av[0], &end, 0); 2403 ac--; av++; 2404 break; 2405 2406 case TOK_PIPE: 2407 if (do_pipe == 1) 2408 errx(EX_DATAERR,"pipe only valid for queues"); 2409 NEED1("pipe needs pipe_number\n"); 2410 p.fs.parent_nr = strtoul(av[0], &end, 0); 2411 ac--; av++; 2412 break; 2413 2414 default: 2415 errx(EX_DATAERR, "unrecognised option ``%s''", *av); 2416 } 2417 } 2418 if (do_pipe == 1) { 2419 if (p.pipe_nr == 0) 2420 errx(EX_DATAERR, "pipe_nr must be > 0"); 2421 if (p.delay > 10000) 2422 errx(EX_DATAERR, "delay must be < 10000"); 2423 } else { /* do_pipe == 2, queue */ 2424 if (p.fs.parent_nr == 0) 2425 errx(EX_DATAERR, "pipe must be > 0"); 2426 if (p.fs.weight >100) 2427 errx(EX_DATAERR, "weight must be <= 100"); 2428 } 2429 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) { 2430 if (p.fs.qsize > 1024*1024) 2431 errx(EX_DATAERR, "queue size must be < 1MB"); 2432 } else { 2433 if (p.fs.qsize > 100) 2434 errx(EX_DATAERR, "2 <= queue size <= 100"); 2435 } 2436 if (p.fs.flags_fs & DN_IS_RED) { 2437 size_t len; 2438 int lookup_depth, avg_pkt_size; 2439 double s, idle, weight, w_q; 2440 struct clockinfo ck; 2441 int t; 2442 2443 if (p.fs.min_th >= p.fs.max_th) 2444 errx(EX_DATAERR, "min_th %d must be < than max_th %d", 2445 p.fs.min_th, p.fs.max_th); 2446 if (p.fs.max_th == 0) 2447 errx(EX_DATAERR, "max_th must be > 0"); 2448 2449 len = sizeof(int); 2450 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth", 2451 &lookup_depth, &len, NULL, 0) == -1) 2452 2453 errx(1, "sysctlbyname(\"%s\")", 2454 "net.inet.ip.dummynet.red_lookup_depth"); 2455 if (lookup_depth == 0) 2456 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth" 2457 " must be greater than zero"); 2458 2459 len = sizeof(int); 2460 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size", 2461 &avg_pkt_size, &len, NULL, 0) == -1) 2462 2463 errx(1, "sysctlbyname(\"%s\")", 2464 "net.inet.ip.dummynet.red_avg_pkt_size"); 2465 if (avg_pkt_size == 0) 2466 errx(EX_DATAERR, 2467 "net.inet.ip.dummynet.red_avg_pkt_size must" 2468 " be greater than zero"); 2469 2470 len = sizeof(struct clockinfo); 2471 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1) 2472 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate"); 2473 2474 /* 2475 * Ticks needed for sending a medium-sized packet. 2476 * Unfortunately, when we are configuring a WF2Q+ queue, we 2477 * do not have bandwidth information, because that is stored 2478 * in the parent pipe, and also we have multiple queues 2479 * competing for it. So we set s=0, which is not very 2480 * correct. But on the other hand, why do we want RED with 2481 * WF2Q+ ? 2482 */ 2483 if (p.bandwidth==0) /* this is a WF2Q+ queue */ 2484 s = 0; 2485 else 2486 s = ck.hz * avg_pkt_size * 8 / p.bandwidth; 2487 2488 /* 2489 * max idle time (in ticks) before avg queue size becomes 0. 2490 * NOTA: (3/w_q) is approx the value x so that 2491 * (1-w_q)^x < 10^-3. 2492 */ 2493 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED); 2494 idle = s * 3. / w_q; 2495 p.fs.lookup_step = (int)idle / lookup_depth; 2496 if (!p.fs.lookup_step) 2497 p.fs.lookup_step = 1; 2498 weight = 1 - w_q; 2499 for (t = p.fs.lookup_step; t > 0; --t) 2500 weight *= weight; 2501 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED)); 2502 } 2503 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p); 2504 if (i) 2505 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE"); 2506} 2507 2508static void 2509get_mac_addr_mask(char *p, uint8_t *addr, uint8_t *mask) 2510{ 2511 int i, l; 2512 2513 for (i=0; i<6; i++) 2514 addr[i] = mask[i] = 0; 2515 if (!strcmp(p, "any")) 2516 return; 2517 2518 for (i=0; *p && i<6;i++, p++) { 2519 addr[i] = strtol(p, &p, 16); 2520 if (*p != ':') /* we start with the mask */ 2521 break; 2522 } 2523 if (*p == '/') { /* mask len */ 2524 l = strtol(p+1, &p, 0); 2525 for (i=0; l>0; l -=8, i++) 2526 mask[i] = (l >=8) ? 0xff : (~0) << (8-l); 2527 } else if (*p == '&') { /* mask */ 2528 for (i=0, p++; *p && i<6;i++, p++) { 2529 mask[i] = strtol(p, &p, 16); 2530 if (*p != ':') 2531 break; 2532 } 2533 } else if (*p == '\0') { 2534 for (i=0; i<6; i++) 2535 mask[i] = 0xff; 2536 } 2537 for (i=0; i<6; i++) 2538 addr[i] &= mask[i]; 2539} 2540 2541/* 2542 * helper function, updates the pointer to cmd with the length 2543 * of the current command, and also cleans up the first word of 2544 * the new command in case it has been clobbered before. 2545 */ 2546static ipfw_insn * 2547next_cmd(ipfw_insn *cmd) 2548{ 2549 cmd += F_LEN(cmd); 2550 bzero(cmd, sizeof(*cmd)); 2551 return cmd; 2552} 2553 2554/* 2555 * Takes arguments and copies them into a comment 2556 */ 2557static void 2558fill_comment(ipfw_insn *cmd, int ac, char **av) 2559{ 2560 int i, l; 2561 char *p = (char *)(cmd + 1); 2562 2563 cmd->opcode = O_NOP; 2564 cmd->len = (cmd->len & (F_NOT | F_OR)); 2565 2566 /* Compute length of comment string. */ 2567 for (i = 0, l = 0; i < ac; i++) 2568 l += strlen(av[i]) + 1; 2569 if (l == 0) 2570 return; 2571 if (l > 84) 2572 errx(EX_DATAERR, 2573 "comment too long (max 80 chars)"); 2574 l = 1 + (l+3)/4; 2575 cmd->len = (cmd->len & (F_NOT | F_OR)) | l; 2576 for (i = 0; i < ac; i++) { 2577 strcpy(p, av[i]); 2578 p += strlen(av[i]); 2579 *p++ = ' '; 2580 } 2581 *(--p) = '\0'; 2582} 2583 2584/* 2585 * A function to fill simple commands of size 1. 2586 * Existing flags are preserved. 2587 */ 2588static void 2589fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg) 2590{ 2591 cmd->opcode = opcode; 2592 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1; 2593 cmd->arg1 = arg; 2594} 2595 2596/* 2597 * Fetch and add the MAC address and type, with masks. This generates one or 2598 * two microinstructions, and returns the pointer to the last one. 2599 */ 2600static ipfw_insn * 2601add_mac(ipfw_insn *cmd, int ac, char *av[]) 2602{ 2603 ipfw_insn_mac *mac; 2604 2605 if (ac < 2) 2606 errx(EX_DATAERR, "MAC dst src"); 2607 2608 cmd->opcode = O_MACADDR2; 2609 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac); 2610 2611 mac = (ipfw_insn_mac *)cmd; 2612 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */ 2613 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */ 2614 return cmd; 2615} 2616 2617static ipfw_insn * 2618add_mactype(ipfw_insn *cmd, int ac, char *av) 2619{ 2620 if (ac < 1) 2621 errx(EX_DATAERR, "missing MAC type"); 2622 if (strcmp(av, "any") != 0) { /* we have a non-null type */ 2623 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE); 2624 cmd->opcode = O_MAC_TYPE; 2625 return cmd; 2626 } else 2627 return NULL; 2628} 2629 2630static ipfw_insn * 2631add_proto(ipfw_insn *cmd, char *av) 2632{ 2633 struct protoent *pe; 2634 u_char proto = 0; 2635 2636 if (!strncmp(av, "all", strlen(av))) 2637 ; /* same as "ip" */ 2638 else if ((proto = atoi(av)) > 0) 2639 ; /* all done! */ 2640 else if ((pe = getprotobyname(av)) != NULL) 2641 proto = pe->p_proto; 2642 else 2643 return NULL; 2644 if (proto != IPPROTO_IP) 2645 fill_cmd(cmd, O_PROTO, 0, proto); 2646 return cmd; 2647} 2648 2649static ipfw_insn * 2650add_srcip(ipfw_insn *cmd, char *av) 2651{ 2652 fill_ip((ipfw_insn_ip *)cmd, av); 2653 if (cmd->opcode == O_IP_DST_SET) /* set */ 2654 cmd->opcode = O_IP_SRC_SET; 2655 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 2656 cmd->opcode = O_IP_SRC_ME; 2657 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 2658 cmd->opcode = O_IP_SRC; 2659 else /* addr/mask */ 2660 cmd->opcode = O_IP_SRC_MASK; 2661 return cmd; 2662} 2663 2664static ipfw_insn * 2665add_dstip(ipfw_insn *cmd, char *av) 2666{ 2667 fill_ip((ipfw_insn_ip *)cmd, av); 2668 if (cmd->opcode == O_IP_DST_SET) /* set */ 2669 ; 2670 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */ 2671 cmd->opcode = O_IP_DST_ME; 2672 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */ 2673 cmd->opcode = O_IP_DST; 2674 else /* addr/mask */ 2675 cmd->opcode = O_IP_DST_MASK; 2676 return cmd; 2677} 2678 2679static ipfw_insn * 2680add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode) 2681{ 2682 if (!strncmp(av, "any", strlen(av))) { 2683 return NULL; 2684 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) { 2685 /* XXX todo: check that we have a protocol with ports */ 2686 cmd->opcode = opcode; 2687 return cmd; 2688 } 2689 return NULL; 2690} 2691 2692/* 2693 * Parse arguments and assemble the microinstructions which make up a rule. 2694 * Rules are added into the 'rulebuf' and then copied in the correct order 2695 * into the actual rule. 2696 * 2697 * The syntax for a rule starts with the action, followed by an 2698 * optional log action, and the various match patterns. 2699 * In the assembled microcode, the first opcode must be an O_PROBE_STATE 2700 * (generated if the rule includes a keep-state option), then the 2701 * various match patterns, the "log" action, and the actual action. 2702 * 2703 */ 2704static void 2705add(int ac, char *av[]) 2706{ 2707 /* 2708 * rules are added into the 'rulebuf' and then copied in 2709 * the correct order into the actual rule. 2710 * Some things that need to go out of order (prob, action etc.) 2711 * go into actbuf[]. 2712 */ 2713 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255]; 2714 2715 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL; 2716 ipfw_insn *first_cmd; /* first match pattern */ 2717 2718 struct ip_fw *rule; 2719 2720 /* 2721 * various flags used to record that we entered some fields. 2722 */ 2723 ipfw_insn *have_state = NULL; /* check-state or keep-state */ 2724 2725 int i; 2726 2727 int open_par = 0; /* open parenthesis ( */ 2728 2729 /* proto is here because it is used to fetch ports */ 2730 u_char proto = IPPROTO_IP; /* default protocol */ 2731 2732 double match_prob = 1; /* match probability, default is always match */ 2733 2734 bzero(actbuf, sizeof(actbuf)); /* actions go here */ 2735 bzero(cmdbuf, sizeof(cmdbuf)); 2736 bzero(rulebuf, sizeof(rulebuf)); 2737 2738 rule = (struct ip_fw *)rulebuf; 2739 cmd = (ipfw_insn *)cmdbuf; 2740 action = (ipfw_insn *)actbuf; 2741 2742 av++; ac--; 2743 2744 /* [rule N] -- Rule number optional */ 2745 if (ac && isdigit(**av)) { 2746 rule->rulenum = atoi(*av); 2747 av++; 2748 ac--; 2749 } 2750 2751 /* [set N] -- set number (0..30), optional */ 2752 if (ac > 1 && !strncmp(*av, "set", strlen(*av))) { 2753 int set = strtoul(av[1], NULL, 10); 2754 if (set < 0 || set > 30) 2755 errx(EX_DATAERR, "illegal set %s", av[1]); 2756 rule->set = set; 2757 av += 2; ac -= 2; 2758 } 2759 2760 /* [prob D] -- match probability, optional */ 2761 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) { 2762 match_prob = strtod(av[1], NULL); 2763 2764 if (match_prob <= 0 || match_prob > 1) 2765 errx(EX_DATAERR, "illegal match prob. %s", av[1]); 2766 av += 2; ac -= 2; 2767 } 2768 2769 /* action -- mandatory */ 2770 NEED1("missing action"); 2771 i = match_token(rule_actions, *av); 2772 ac--; av++; 2773 action->len = 1; /* default */ 2774 switch(i) { 2775 case TOK_CHECKSTATE: 2776 have_state = action; 2777 action->opcode = O_CHECK_STATE; 2778 break; 2779 2780 case TOK_ACCEPT: 2781 action->opcode = O_ACCEPT; 2782 break; 2783 2784 case TOK_DENY: 2785 action->opcode = O_DENY; 2786 action->arg1 = 0; 2787 break; 2788 2789 case TOK_REJECT: 2790 action->opcode = O_REJECT; 2791 action->arg1 = ICMP_UNREACH_HOST; 2792 break; 2793 2794 case TOK_RESET: 2795 action->opcode = O_REJECT; 2796 action->arg1 = ICMP_REJECT_RST; 2797 break; 2798 2799 case TOK_UNREACH: 2800 action->opcode = O_REJECT; 2801 NEED1("missing reject code"); 2802 fill_reject_code(&action->arg1, *av); 2803 ac--; av++; 2804 break; 2805 2806 case TOK_COUNT: 2807 action->opcode = O_COUNT; 2808 break; 2809 2810 case TOK_QUEUE: 2811 case TOK_PIPE: 2812 action->len = F_INSN_SIZE(ipfw_insn_pipe); 2813 case TOK_SKIPTO: 2814 if (i == TOK_QUEUE) 2815 action->opcode = O_QUEUE; 2816 else if (i == TOK_PIPE) 2817 action->opcode = O_PIPE; 2818 else if (i == TOK_SKIPTO) 2819 action->opcode = O_SKIPTO; 2820 NEED1("missing skipto/pipe/queue number"); 2821 action->arg1 = strtoul(*av, NULL, 10); 2822 av++; ac--; 2823 break; 2824 2825 case TOK_DIVERT: 2826 case TOK_TEE: 2827 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE; 2828 NEED1("missing divert/tee port"); 2829 action->arg1 = strtoul(*av, NULL, 0); 2830 if (action->arg1 == 0) { 2831 struct servent *s; 2832 setservent(1); 2833 s = getservbyname(av[0], "divert"); 2834 if (s != NULL) 2835 action->arg1 = ntohs(s->s_port); 2836 else 2837 errx(EX_DATAERR, "illegal divert/tee port"); 2838 } 2839 ac--; av++; 2840 break; 2841 2842 case TOK_FORWARD: { 2843 ipfw_insn_sa *p = (ipfw_insn_sa *)action; 2844 char *s, *end; 2845 2846 NEED1("missing forward address[:port]"); 2847 2848 action->opcode = O_FORWARD_IP; 2849 action->len = F_INSN_SIZE(ipfw_insn_sa); 2850 2851 p->sa.sin_len = sizeof(struct sockaddr_in); 2852 p->sa.sin_family = AF_INET; 2853 p->sa.sin_port = 0; 2854 /* 2855 * locate the address-port separator (':' or ',') 2856 */ 2857 s = strchr(*av, ':'); 2858 if (s == NULL) 2859 s = strchr(*av, ','); 2860 if (s != NULL) { 2861 *(s++) = '\0'; 2862 i = strtoport(s, &end, 0 /* base */, 0 /* proto */); 2863 if (s == end) 2864 errx(EX_DATAERR, 2865 "illegal forwarding port ``%s''", s); 2866 p->sa.sin_port = (u_short)i; 2867 } 2868 lookup_host(*av, &(p->sa.sin_addr)); 2869 } 2870 ac--; av++; 2871 break; 2872 2873 case TOK_COMMENT: 2874 /* pretend it is a 'count' rule followed by the comment */ 2875 action->opcode = O_COUNT; 2876 ac++; av--; /* go back... */ 2877 break; 2878 2879 default: 2880 errx(EX_DATAERR, "invalid action %s\n", av[-1]); 2881 } 2882 action = next_cmd(action); 2883 2884 /* 2885 * [log [logamount N]] -- log, optional 2886 * 2887 * If exists, it goes first in the cmdbuf, but then it is 2888 * skipped in the copy section to the end of the buffer. 2889 */ 2890 if (ac && !strncmp(*av, "log", strlen(*av))) { 2891 ipfw_insn_log *c = (ipfw_insn_log *)cmd; 2892 int l; 2893 2894 cmd->len = F_INSN_SIZE(ipfw_insn_log); 2895 cmd->opcode = O_LOG; 2896 av++; ac--; 2897 if (ac && !strncmp(*av, "logamount", strlen(*av))) { 2898 ac--; av++; 2899 NEED1("logamount requires argument"); 2900 l = atoi(*av); 2901 if (l < 0) 2902 errx(EX_DATAERR, "logamount must be positive"); 2903 c->max_log = l; 2904 ac--; av++; 2905 } 2906 cmd = next_cmd(cmd); 2907 } 2908 2909 if (have_state) /* must be a check-state, we are done */ 2910 goto done; 2911 2912#define OR_START(target) \ 2913 if (ac && (*av[0] == '(' || *av[0] == '{')) { \ 2914 if (open_par) \ 2915 errx(EX_USAGE, "nested \"(\" not allowed\n"); \ 2916 prev = NULL; \ 2917 open_par = 1; \ 2918 if ( (av[0])[1] == '\0') { \ 2919 ac--; av++; \ 2920 } else \ 2921 (*av)++; \ 2922 } \ 2923 target: \ 2924 2925 2926#define CLOSE_PAR \ 2927 if (open_par) { \ 2928 if (ac && ( \ 2929 !strncmp(*av, ")", strlen(*av)) || \ 2930 !strncmp(*av, "}", strlen(*av)) )) { \ 2931 prev = NULL; \ 2932 open_par = 0; \ 2933 ac--; av++; \ 2934 } else \ 2935 errx(EX_USAGE, "missing \")\"\n"); \ 2936 } 2937 2938#define NOT_BLOCK \ 2939 if (ac && !strncmp(*av, "not", strlen(*av))) { \ 2940 if (cmd->len & F_NOT) \ 2941 errx(EX_USAGE, "double \"not\" not allowed\n"); \ 2942 cmd->len |= F_NOT; \ 2943 ac--; av++; \ 2944 } 2945 2946#define OR_BLOCK(target) \ 2947 if (ac && !strncmp(*av, "or", strlen(*av))) { \ 2948 if (prev == NULL || open_par == 0) \ 2949 errx(EX_DATAERR, "invalid OR block"); \ 2950 prev->len |= F_OR; \ 2951 ac--; av++; \ 2952 goto target; \ 2953 } \ 2954 CLOSE_PAR; 2955 2956 first_cmd = cmd; 2957 2958#if 0 2959 /* 2960 * MAC addresses, optional. 2961 * If we have this, we skip the part "proto from src to dst" 2962 * and jump straight to the option parsing. 2963 */ 2964 NOT_BLOCK; 2965 NEED1("missing protocol"); 2966 if (!strncmp(*av, "MAC", strlen(*av)) || 2967 !strncmp(*av, "mac", strlen(*av))) { 2968 ac--; av++; /* the "MAC" keyword */ 2969 add_mac(cmd, ac, av); /* exits in case of errors */ 2970 cmd = next_cmd(cmd); 2971 ac -= 2; av += 2; /* dst-mac and src-mac */ 2972 NOT_BLOCK; 2973 NEED1("missing mac type"); 2974 if (add_mactype(cmd, ac, av[0])) 2975 cmd = next_cmd(cmd); 2976 ac--; av++; /* any or mac-type */ 2977 goto read_options; 2978 } 2979#endif 2980 2981 /* 2982 * protocol, mandatory 2983 */ 2984 OR_START(get_proto); 2985 NOT_BLOCK; 2986 NEED1("missing protocol"); 2987 if (add_proto(cmd, *av)) { 2988 av++; ac--; 2989 if (F_LEN(cmd) == 0) /* plain IP */ 2990 proto = 0; 2991 else { 2992 proto = cmd->arg1; 2993 prev = cmd; 2994 cmd = next_cmd(cmd); 2995 } 2996 } else if (first_cmd != cmd) { 2997 errx(EX_DATAERR, "invalid protocol ``%s''", *av); 2998 } else 2999 goto read_options; 3000 OR_BLOCK(get_proto); 3001 3002 /* 3003 * "from", mandatory 3004 */ 3005 if (!ac || strncmp(*av, "from", strlen(*av))) 3006 errx(EX_USAGE, "missing ``from''"); 3007 ac--; av++; 3008 3009 /* 3010 * source IP, mandatory 3011 */ 3012 OR_START(source_ip); 3013 NOT_BLOCK; /* optional "not" */ 3014 NEED1("missing source address"); 3015 if (add_srcip(cmd, *av)) { 3016 ac--; av++; 3017 if (F_LEN(cmd) != 0) { /* ! any */ 3018 prev = cmd; 3019 cmd = next_cmd(cmd); 3020 } 3021 } 3022 OR_BLOCK(source_ip); 3023 3024 /* 3025 * source ports, optional 3026 */ 3027 NOT_BLOCK; /* optional "not" */ 3028 if (ac) { 3029 if (!strncmp(*av, "any", strlen(*av)) || 3030 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 3031 ac--; av++; 3032 if (F_LEN(cmd) != 0) 3033 cmd = next_cmd(cmd); 3034 } 3035 } 3036 3037 /* 3038 * "to", mandatory 3039 */ 3040 if (!ac || strncmp(*av, "to", strlen(*av))) 3041 errx(EX_USAGE, "missing ``to''"); 3042 av++; ac--; 3043 3044 /* 3045 * destination, mandatory 3046 */ 3047 OR_START(dest_ip); 3048 NOT_BLOCK; /* optional "not" */ 3049 NEED1("missing dst address"); 3050 if (add_dstip(cmd, *av)) { 3051 ac--; av++; 3052 if (F_LEN(cmd) != 0) { /* ! any */ 3053 prev = cmd; 3054 cmd = next_cmd(cmd); 3055 } 3056 } 3057 OR_BLOCK(dest_ip); 3058 3059 /* 3060 * dest. ports, optional 3061 */ 3062 NOT_BLOCK; /* optional "not" */ 3063 if (ac) { 3064 if (!strncmp(*av, "any", strlen(*av)) || 3065 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 3066 ac--; av++; 3067 if (F_LEN(cmd) != 0) 3068 cmd = next_cmd(cmd); 3069 } 3070 } 3071 3072read_options: 3073 if (ac && first_cmd == cmd) { 3074 /* 3075 * nothing specified so far, store in the rule to ease 3076 * printout later. 3077 */ 3078 rule->_pad = 1; 3079 } 3080 prev = NULL; 3081 while (ac) { 3082 char *s; 3083 ipfw_insn_u32 *cmd32; /* alias for cmd */ 3084 3085 s = *av; 3086 cmd32 = (ipfw_insn_u32 *)cmd; 3087 3088 if (*s == '!') { /* alternate syntax for NOT */ 3089 if (cmd->len & F_NOT) 3090 errx(EX_USAGE, "double \"not\" not allowed\n"); 3091 cmd->len = F_NOT; 3092 s++; 3093 } 3094 i = match_token(rule_options, s); 3095 ac--; av++; 3096 switch(i) { 3097 case TOK_NOT: 3098 if (cmd->len & F_NOT) 3099 errx(EX_USAGE, "double \"not\" not allowed\n"); 3100 cmd->len = F_NOT; 3101 break; 3102 3103 case TOK_OR: 3104 if (open_par == 0 || prev == NULL) 3105 errx(EX_USAGE, "invalid \"or\" block\n"); 3106 prev->len |= F_OR; 3107 break; 3108 3109 case TOK_STARTBRACE: 3110 if (open_par) 3111 errx(EX_USAGE, "+nested \"(\" not allowed\n"); 3112 open_par = 1; 3113 break; 3114 3115 case TOK_ENDBRACE: 3116 if (!open_par) 3117 errx(EX_USAGE, "+missing \")\"\n"); 3118 open_par = 0; 3119 prev = NULL; 3120 break; 3121 3122 case TOK_IN: 3123 fill_cmd(cmd, O_IN, 0, 0); 3124 break; 3125 3126 case TOK_OUT: 3127 cmd->len ^= F_NOT; /* toggle F_NOT */ 3128 fill_cmd(cmd, O_IN, 0, 0); 3129 break; 3130 3131 case TOK_FRAG: 3132 fill_cmd(cmd, O_FRAG, 0, 0); 3133 break; 3134 3135 case TOK_LAYER2: 3136 fill_cmd(cmd, O_LAYER2, 0, 0); 3137 break; 3138 3139 case TOK_XMIT: 3140 case TOK_RECV: 3141 case TOK_VIA: 3142 NEED1("recv, xmit, via require interface name" 3143 " or address"); 3144 fill_iface((ipfw_insn_if *)cmd, av[0]); 3145 ac--; av++; 3146 if (F_LEN(cmd) == 0) /* not a valid address */ 3147 break; 3148 if (i == TOK_XMIT) 3149 cmd->opcode = O_XMIT; 3150 else if (i == TOK_RECV) 3151 cmd->opcode = O_RECV; 3152 else if (i == TOK_VIA) 3153 cmd->opcode = O_VIA; 3154 break; 3155 3156 case TOK_ICMPTYPES: 3157 NEED1("icmptypes requires list of types"); 3158 fill_icmptypes((ipfw_insn_u32 *)cmd, *av); 3159 av++; ac--; 3160 break; 3161 3162 case TOK_IPTTL: 3163 NEED1("ipttl requires TTL"); 3164 if (strpbrk(*av, "-,")) { 3165 if (!add_ports(cmd, *av, 0, O_IPTTL)) 3166 errx(EX_DATAERR, "invalid ipttl %s", *av); 3167 } else 3168 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0)); 3169 ac--; av++; 3170 break; 3171 3172 case TOK_IPID: 3173 NEED1("ipid requires id"); 3174 if (strpbrk(*av, "-,")) { 3175 if (!add_ports(cmd, *av, 0, O_IPID)) 3176 errx(EX_DATAERR, "invalid ipid %s", *av); 3177 } else 3178 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0)); 3179 ac--; av++; 3180 break; 3181 3182 case TOK_IPLEN: 3183 NEED1("iplen requires length"); 3184 if (strpbrk(*av, "-,")) { 3185 if (!add_ports(cmd, *av, 0, O_IPLEN)) 3186 errx(EX_DATAERR, "invalid ip len %s", *av); 3187 } else 3188 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0)); 3189 ac--; av++; 3190 break; 3191 3192 case TOK_IPVER: 3193 NEED1("ipver requires version"); 3194 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0)); 3195 ac--; av++; 3196 break; 3197 3198 case TOK_IPPRECEDENCE: 3199 NEED1("ipprecedence requires value"); 3200 fill_cmd(cmd, O_IPPRECEDENCE, 0, 3201 (strtoul(*av, NULL, 0) & 7) << 5); 3202 ac--; av++; 3203 break; 3204 3205 case TOK_IPOPTS: 3206 NEED1("missing argument for ipoptions"); 3207 fill_flags(cmd, O_IPOPT, f_ipopts, *av); 3208 ac--; av++; 3209 break; 3210 3211 case TOK_IPTOS: 3212 NEED1("missing argument for iptos"); 3213 fill_flags(cmd, O_IPTOS, f_iptos, *av); 3214 ac--; av++; 3215 break; 3216 3217 case TOK_UID: 3218 NEED1("uid requires argument"); 3219 { 3220 char *end; 3221 uid_t uid; 3222 struct passwd *pwd; 3223 3224 cmd->opcode = O_UID; 3225 uid = strtoul(*av, &end, 0); 3226 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av); 3227 if (pwd == NULL) 3228 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av); 3229 cmd32->d[0] = pwd->pw_uid; 3230 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 3231 ac--; av++; 3232 } 3233 break; 3234 3235 case TOK_GID: 3236 NEED1("gid requires argument"); 3237 { 3238 char *end; 3239 gid_t gid; 3240 struct group *grp; 3241 3242 cmd->opcode = O_GID; 3243 gid = strtoul(*av, &end, 0); 3244 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av); 3245 if (grp == NULL) 3246 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av); 3247 cmd32->d[0] = grp->gr_gid; 3248 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 3249 ac--; av++; 3250 } 3251 break; 3252 3253 case TOK_ESTAB: 3254 fill_cmd(cmd, O_ESTAB, 0, 0); 3255 break; 3256 3257 case TOK_SETUP: 3258 fill_cmd(cmd, O_TCPFLAGS, 0, 3259 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 ); 3260 break; 3261 3262 case TOK_TCPOPTS: 3263 NEED1("missing argument for tcpoptions"); 3264 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av); 3265 ac--; av++; 3266 break; 3267 3268 case TOK_TCPSEQ: 3269 case TOK_TCPACK: 3270 NEED1("tcpseq/tcpack requires argument"); 3271 cmd->len = F_INSN_SIZE(ipfw_insn_u32); 3272 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK; 3273 cmd32->d[0] = htonl(strtoul(*av, NULL, 0)); 3274 ac--; av++; 3275 break; 3276 3277 case TOK_TCPWIN: 3278 NEED1("tcpwin requires length"); 3279 fill_cmd(cmd, O_TCPWIN, 0, 3280 htons(strtoul(*av, NULL, 0))); 3281 ac--; av++; 3282 break; 3283 3284 case TOK_TCPFLAGS: 3285 NEED1("missing argument for tcpflags"); 3286 cmd->opcode = O_TCPFLAGS; 3287 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av); 3288 ac--; av++; 3289 break; 3290 3291 case TOK_KEEPSTATE: 3292 if (open_par) 3293 errx(EX_USAGE, "keep-state cannot be part " 3294 "of an or block"); 3295 if (have_state) 3296 errx(EX_USAGE, "only one of keep-state " 3297 "and limit is allowed"); 3298 have_state = cmd; 3299 fill_cmd(cmd, O_KEEP_STATE, 0, 0); 3300 break; 3301 3302 case TOK_LIMIT: 3303 if (open_par) 3304 errx(EX_USAGE, "limit cannot be part " 3305 "of an or block"); 3306 if (have_state) 3307 errx(EX_USAGE, "only one of keep-state " 3308 "and limit is allowed"); 3309 NEED1("limit needs mask and # of connections"); 3310 have_state = cmd; 3311 { 3312 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd; 3313 3314 cmd->len = F_INSN_SIZE(ipfw_insn_limit); 3315 cmd->opcode = O_LIMIT; 3316 c->limit_mask = 0; 3317 c->conn_limit = 0; 3318 for (; ac >1 ;) { 3319 int val; 3320 3321 val = match_token(limit_masks, *av); 3322 if (val <= 0) 3323 break; 3324 c->limit_mask |= val; 3325 ac--; av++; 3326 } 3327 c->conn_limit = atoi(*av); 3328 if (c->conn_limit == 0) 3329 errx(EX_USAGE, "limit: limit must be >0"); 3330 if (c->limit_mask == 0) 3331 errx(EX_USAGE, "missing limit mask"); 3332 ac--; av++; 3333 } 3334 break; 3335 3336 case TOK_PROTO: 3337 NEED1("missing protocol"); 3338 if (add_proto(cmd, *av)) { 3339 proto = cmd->arg1; 3340 ac--; av++; 3341 } else 3342 errx(EX_DATAERR, "invalid protocol ``%s''", 3343 *av); 3344 break; 3345 3346 case TOK_SRCIP: 3347 NEED1("missing source IP"); 3348 if (add_srcip(cmd, *av)) { 3349 ac--; av++; 3350 } 3351 break; 3352 3353 case TOK_DSTIP: 3354 NEED1("missing destination IP"); 3355 if (add_dstip(cmd, *av)) { 3356 ac--; av++; 3357 } 3358 break; 3359 3360 case TOK_SRCPORT: 3361 NEED1("missing source port"); 3362 if (!strncmp(*av, "any", strlen(*av)) || 3363 add_ports(cmd, *av, proto, O_IP_SRCPORT)) { 3364 ac--; av++; 3365 } else 3366 errx(EX_DATAERR, "invalid source port %s", *av); 3367 break; 3368 3369 case TOK_DSTPORT: 3370 NEED1("missing destination port"); 3371 if (!strncmp(*av, "any", strlen(*av)) || 3372 add_ports(cmd, *av, proto, O_IP_DSTPORT)) { 3373 ac--; av++; 3374 } else 3375 errx(EX_DATAERR, "invalid destination port %s", 3376 *av); 3377 break; 3378 3379 case TOK_MAC: 3380 if (ac < 2) 3381 errx(EX_USAGE, "MAC dst-mac src-mac"); 3382 if (add_mac(cmd, ac, av)) { 3383 ac -= 2; av += 2; 3384 } 3385 break; 3386 3387 case TOK_MACTYPE: 3388 NEED1("missing mac type"); 3389 if (!add_mactype(cmd, ac, *av)) 3390 errx(EX_DATAERR, "invalid mac type %s", *av); 3391 ac--; av++; 3392 break; 3393 3394 case TOK_VERREVPATH: 3395 fill_cmd(cmd, O_VERREVPATH, 0, 0); 3396 break; 3397 3398 case TOK_IPSEC: 3399 fill_cmd(cmd, O_IPSEC, 0, 0); 3400 break; 3401 3402 case TOK_COMMENT: 3403 fill_comment(cmd, ac, av); 3404 av += ac; 3405 ac = 0; 3406 break; 3407 3408 default: 3409 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s); 3410 } 3411 if (F_LEN(cmd) > 0) { /* prepare to advance */ 3412 prev = cmd; 3413 cmd = next_cmd(cmd); 3414 } 3415 } 3416 3417done: 3418 /* 3419 * Now copy stuff into the rule. 3420 * If we have a keep-state option, the first instruction 3421 * must be a PROBE_STATE (which is generated here). 3422 * If we have a LOG option, it was stored as the first command, 3423 * and now must be moved to the top of the action part. 3424 */ 3425 dst = (ipfw_insn *)rule->cmd; 3426 3427 /* 3428 * First thing to write into the command stream is the match probability. 3429 */ 3430 if (match_prob != 1) { /* 1 means always match */ 3431 dst->opcode = O_PROB; 3432 dst->len = 2; 3433 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff); 3434 dst += dst->len; 3435 } 3436 3437 /* 3438 * generate O_PROBE_STATE if necessary 3439 */ 3440 if (have_state && have_state->opcode != O_CHECK_STATE) { 3441 fill_cmd(dst, O_PROBE_STATE, 0, 0); 3442 dst = next_cmd(dst); 3443 } 3444 /* 3445 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT 3446 */ 3447 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) { 3448 i = F_LEN(src); 3449 3450 switch (src->opcode) { 3451 case O_LOG: 3452 case O_KEEP_STATE: 3453 case O_LIMIT: 3454 break; 3455 default: 3456 bcopy(src, dst, i * sizeof(uint32_t)); 3457 dst += i; 3458 } 3459 } 3460 3461 /* 3462 * put back the have_state command as last opcode 3463 */ 3464 if (have_state && have_state->opcode != O_CHECK_STATE) { 3465 i = F_LEN(have_state); 3466 bcopy(have_state, dst, i * sizeof(uint32_t)); 3467 dst += i; 3468 } 3469 /* 3470 * start action section 3471 */ 3472 rule->act_ofs = dst - rule->cmd; 3473 3474 /* 3475 * put back O_LOG if necessary 3476 */ 3477 src = (ipfw_insn *)cmdbuf; 3478 if (src->opcode == O_LOG) { 3479 i = F_LEN(src); 3480 bcopy(src, dst, i * sizeof(uint32_t)); 3481 dst += i; 3482 } 3483 /* 3484 * copy all other actions 3485 */ 3486 for (src = (ipfw_insn *)actbuf; src != action; src += i) { 3487 i = F_LEN(src); 3488 bcopy(src, dst, i * sizeof(uint32_t)); 3489 dst += i; 3490 } 3491 3492 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd); 3493 i = (char *)dst - (char *)rule; 3494 if (do_cmd(IP_FW_ADD, rule, (socklen_t)&i) == -1) 3495 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD"); 3496 if (!do_quiet) 3497 show_ipfw(rule, 0, 0); 3498} 3499 3500static void 3501zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */) 3502{ 3503 int rulenum; 3504 int failed = EX_OK; 3505 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG"; 3506 3507 av++; ac--; 3508 3509 if (!ac) { 3510 /* clear all entries */ 3511 if (do_cmd(optname, NULL, 0) < 0) 3512 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name); 3513 if (!do_quiet) 3514 printf("%s.\n", optname == IP_FW_ZERO ? 3515 "Accounting cleared":"Logging counts reset"); 3516 3517 return; 3518 } 3519 3520 while (ac) { 3521 /* Rule number */ 3522 if (isdigit(**av)) { 3523 rulenum = atoi(*av); 3524 av++; 3525 ac--; 3526 if (do_cmd(optname, &rulenum, sizeof rulenum)) { 3527 warn("rule %u: setsockopt(IP_FW_%s)", 3528 rulenum, name); 3529 failed = EX_UNAVAILABLE; 3530 } else if (!do_quiet) 3531 printf("Entry %d %s.\n", rulenum, 3532 optname == IP_FW_ZERO ? 3533 "cleared" : "logging count reset"); 3534 } else { 3535 errx(EX_USAGE, "invalid rule number ``%s''", *av); 3536 } 3537 } 3538 if (failed != EX_OK) 3539 exit(failed); 3540} 3541 3542static void 3543flush(int force) 3544{ 3545 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH; 3546 3547 if (!force && !do_quiet) { /* need to ask user */ 3548 int c; 3549 3550 printf("Are you sure? [yn] "); 3551 fflush(stdout); 3552 do { 3553 c = toupper(getc(stdin)); 3554 while (c != '\n' && getc(stdin) != '\n') 3555 if (feof(stdin)) 3556 return; /* and do not flush */ 3557 } while (c != 'Y' && c != 'N'); 3558 printf("\n"); 3559 if (c == 'N') /* user said no */ 3560 return; 3561 } 3562 if (do_cmd(cmd, NULL, 0) < 0) 3563 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)", 3564 do_pipe ? "DUMMYNET" : "FW"); 3565 if (!do_quiet) 3566 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules"); 3567} 3568 3569/* 3570 * Free a the (locally allocated) copy of command line arguments. 3571 */ 3572static void 3573free_args(int ac, char **av) 3574{ 3575 int i; 3576 3577 for (i=0; i < ac; i++) 3578 free(av[i]); 3579 free(av); 3580} 3581 3582/* 3583 * Called with the arguments (excluding program name). 3584 * Returns 0 if successful, 1 if empty command, errx() in case of errors. 3585 */ 3586static int 3587ipfw_main(int oldac, char **oldav) 3588{ 3589 int ch, ac, save_ac; 3590 char **av, **save_av; 3591 int do_acct = 0; /* Show packet/byte count */ 3592 int do_force = 0; /* Don't ask for confirmation */ 3593 3594#define WHITESP " \t\f\v\n\r" 3595 if (oldac == 0) 3596 return 1; 3597 else if (oldac == 1) { 3598 /* 3599 * If we are called with a single string, try to split it into 3600 * arguments for subsequent parsing. 3601 * But first, remove spaces after a ',', by copying the string 3602 * in-place. 3603 */ 3604 char *arg = oldav[0]; /* The string... */ 3605 int l = strlen(arg); 3606 int copy = 0; /* 1 if we need to copy, 0 otherwise */ 3607 int i, j; 3608 for (i = j = 0; i < l; i++) { 3609 if (arg[i] == '#') /* comment marker */ 3610 break; 3611 if (copy) { 3612 arg[j++] = arg[i]; 3613 copy = !index("," WHITESP, arg[i]); 3614 } else { 3615 copy = !index(WHITESP, arg[i]); 3616 if (copy) 3617 arg[j++] = arg[i]; 3618 } 3619 } 3620 if (!copy && j > 0) /* last char was a 'blank', remove it */ 3621 j--; 3622 l = j; /* the new argument length */ 3623 arg[j++] = '\0'; 3624 if (l == 0) /* empty string! */ 3625 return 1; 3626 3627 /* 3628 * First, count number of arguments. Because of the previous 3629 * processing, this is just the number of blanks plus 1. 3630 */ 3631 for (i = 0, ac = 1; i < l; i++) 3632 if (index(WHITESP, arg[i]) != NULL) 3633 ac++; 3634 3635 av = calloc(ac, sizeof(char *)); 3636 3637 /* 3638 * Second, copy arguments from cmd[] to av[]. For each one, 3639 * j is the initial character, i is the one past the end. 3640 */ 3641 for (ac = 0, i = j = 0; i < l; i++) 3642 if (index(WHITESP, arg[i]) != NULL || i == l-1) { 3643 if (i == l-1) 3644 i++; 3645 av[ac] = calloc(i-j+1, 1); 3646 bcopy(arg+j, av[ac], i-j); 3647 ac++; 3648 j = i + 1; 3649 } 3650 } else { 3651 /* 3652 * If an argument ends with ',' join with the next one. 3653 */ 3654 int first, i, l; 3655 3656 av = calloc(oldac, sizeof(char *)); 3657 for (first = i = ac = 0, l = 0; i < oldac; i++) { 3658 char *arg = oldav[i]; 3659 int k = strlen(arg); 3660 3661 l += k; 3662 if (arg[k-1] != ',' || i == oldac-1) { 3663 /* Time to copy. */ 3664 av[ac] = calloc(l+1, 1); 3665 for (l=0; first <= i; first++) { 3666 strcat(av[ac]+l, oldav[first]); 3667 l += strlen(oldav[first]); 3668 } 3669 ac++; 3670 l = 0; 3671 first = i+1; 3672 } 3673 } 3674 } 3675 3676 /* Set the force flag for non-interactive processes */ 3677 do_force = !isatty(STDIN_FILENO); 3678 3679 /* Save arguments for final freeing of memory. */ 3680 save_ac = ac; 3681 save_av = av; 3682 3683 optind = optreset = 0; 3684 while ((ch = getopt(ac, av, "acdefhnNqs:STtv")) != -1) 3685 switch (ch) { 3686 case 'a': 3687 do_acct = 1; 3688 break; 3689 3690 case 'c': 3691 do_compact = 1; 3692 break; 3693 3694 case 'd': 3695 do_dynamic = 1; 3696 break; 3697 3698 case 'e': 3699 do_expired = 1; 3700 break; 3701 3702 case 'f': 3703 do_force = 1; 3704 break; 3705 3706 case 'h': /* help */ 3707 free_args(save_ac, save_av); 3708 help(); 3709 break; /* NOTREACHED */ 3710 3711 case 'n': 3712 test_only = 1; 3713 break; 3714 3715 case 'N': 3716 do_resolv = 1; 3717 break; 3718 3719 case 'q': 3720 do_quiet = 1; 3721 break; 3722 3723 case 's': /* sort */ 3724 do_sort = atoi(optarg); 3725 break; 3726 3727 case 'S': 3728 show_sets = 1; 3729 break; 3730 3731 case 't': 3732 do_time = 1; 3733 break; 3734 3735 case 'T': 3736 do_time = 2; /* numeric timestamp */ 3737 break; 3738 3739 case 'v': /* verbose */ 3740 verbose = 1; 3741 break; 3742 3743 default: 3744 free_args(save_ac, save_av); 3745 return 1; 3746 } 3747 3748 ac -= optind; 3749 av += optind; 3750 NEED1("bad arguments, for usage summary ``ipfw''"); 3751 3752 /* 3753 * An undocumented behaviour of ipfw1 was to allow rule numbers first, 3754 * e.g. "100 add allow ..." instead of "add 100 allow ...". 3755 * In case, swap first and second argument to get the normal form. 3756 */ 3757 if (ac > 1 && isdigit(*av[0])) { 3758 char *p = av[0]; 3759 3760 av[0] = av[1]; 3761 av[1] = p; 3762 } 3763 3764 /* 3765 * optional: pipe or queue 3766 */ 3767 if (!strncmp(*av, "pipe", strlen(*av))) 3768 do_pipe = 1; 3769 else if (!strncmp(*av, "queue", strlen(*av))) 3770 do_pipe = 2; 3771 if (do_pipe) { 3772 ac--; 3773 av++; 3774 } 3775 NEED1("missing command"); 3776 3777 /* 3778 * For pipes and queues we normally say 'pipe NN config' 3779 * but the code is easier to parse as 'pipe config NN' 3780 * so we swap the two arguments. 3781 */ 3782 if (do_pipe > 0 && ac > 1 && isdigit(*av[0])) { 3783 char *p = av[0]; 3784 3785 av[0] = av[1]; 3786 av[1] = p; 3787 } 3788 3789 if (!strncmp(*av, "add", strlen(*av))) 3790 add(ac, av); 3791 else if (do_pipe && !strncmp(*av, "config", strlen(*av))) 3792 config_pipe(ac, av); 3793 else if (!strncmp(*av, "delete", strlen(*av))) 3794 delete(ac, av); 3795 else if (!strncmp(*av, "flush", strlen(*av))) 3796 flush(do_force); 3797 else if (!strncmp(*av, "zero", strlen(*av))) 3798 zero(ac, av, IP_FW_ZERO); 3799 else if (!strncmp(*av, "resetlog", strlen(*av))) 3800 zero(ac, av, IP_FW_RESETLOG); 3801 else if (!strncmp(*av, "print", strlen(*av)) || 3802 !strncmp(*av, "list", strlen(*av))) 3803 list(ac, av, do_acct); 3804 else if (!strncmp(*av, "set", strlen(*av))) 3805 sets_handler(ac, av); 3806 else if (!strncmp(*av, "enable", strlen(*av))) 3807 sysctl_handler(ac, av, 1); 3808 else if (!strncmp(*av, "disable", strlen(*av))) 3809 sysctl_handler(ac, av, 0); 3810 else if (!strncmp(*av, "show", strlen(*av))) 3811 list(ac, av, 1 /* show counters */); 3812 else 3813 errx(EX_USAGE, "bad command `%s'", *av); 3814 3815 /* Free memory allocated in the argument parsing. */ 3816 free_args(save_ac, save_av); 3817 return 0; 3818} 3819 3820 3821static void 3822ipfw_readfile(int ac, char *av[]) 3823{ 3824#define MAX_ARGS 32 3825 char buf[BUFSIZ]; 3826 char *cmd = NULL, *filename = av[ac-1]; 3827 int c, lineno=0; 3828 FILE *f = NULL; 3829 pid_t preproc = 0; 3830 3831 filename = av[ac-1]; 3832 3833 while ((c = getopt(ac, av, "cNnp:qS")) != -1) { 3834 switch(c) { 3835 case 'c': 3836 do_compact = 1; 3837 break; 3838 3839 case 'N': 3840 do_resolv = 1; 3841 break; 3842 3843 case 'n': 3844 test_only = 1; 3845 break; 3846 3847 case 'p': 3848 cmd = optarg; 3849 /* 3850 * Skip previous args and delete last one, so we 3851 * pass all but the last argument to the preprocessor 3852 * via av[optind-1] 3853 */ 3854 av += optind - 1; 3855 ac -= optind - 1; 3856 av[ac-1] = NULL; 3857 fprintf(stderr, "command is %s\n", av[0]); 3858 break; 3859 3860 case 'q': 3861 do_quiet = 1; 3862 break; 3863 3864 case 'S': 3865 show_sets = 1; 3866 break; 3867 3868 default: 3869 errx(EX_USAGE, "bad arguments, for usage" 3870 " summary ``ipfw''"); 3871 } 3872 3873 if (cmd != NULL) 3874 break; 3875 } 3876 3877 if (cmd == NULL && ac != optind + 1) { 3878 fprintf(stderr, "ac %d, optind %d\n", ac, optind); 3879 errx(EX_USAGE, "extraneous filename arguments"); 3880 } 3881 3882 if ((f = fopen(filename, "r")) == NULL) 3883 err(EX_UNAVAILABLE, "fopen: %s", filename); 3884 3885 if (cmd != NULL) { /* pipe through preprocessor */ 3886 int pipedes[2]; 3887 3888 if (pipe(pipedes) == -1) 3889 err(EX_OSERR, "cannot create pipe"); 3890 3891 preproc = fork(); 3892 if (preproc == -1) 3893 err(EX_OSERR, "cannot fork"); 3894 3895 if (preproc == 0) { 3896 /* 3897 * Child, will run the preprocessor with the 3898 * file on stdin and the pipe on stdout. 3899 */ 3900 if (dup2(fileno(f), 0) == -1 3901 || dup2(pipedes[1], 1) == -1) 3902 err(EX_OSERR, "dup2()"); 3903 fclose(f); 3904 close(pipedes[1]); 3905 close(pipedes[0]); 3906 execvp(cmd, av); 3907 err(EX_OSERR, "execvp(%s) failed", cmd); 3908 } else { /* parent, will reopen f as the pipe */ 3909 fclose(f); 3910 close(pipedes[1]); 3911 if ((f = fdopen(pipedes[0], "r")) == NULL) { 3912 int savederrno = errno; 3913 3914 (void)kill(preproc, SIGTERM); 3915 errno = savederrno; 3916 err(EX_OSERR, "fdopen()"); 3917 } 3918 } 3919 } 3920 3921 while (fgets(buf, BUFSIZ, f)) { /* read commands */ 3922 char linename[10]; 3923 char *args[1]; 3924 3925 lineno++; 3926 sprintf(linename, "Line %d", lineno); 3927 setprogname(linename); /* XXX */ 3928 args[0] = buf; 3929 ipfw_main(1, args); 3930 } 3931 fclose(f); 3932 if (cmd != NULL) { 3933 int status; 3934 3935 if (waitpid(preproc, &status, 0) == -1) 3936 errx(EX_OSERR, "waitpid()"); 3937 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 3938 errx(EX_UNAVAILABLE, 3939 "preprocessor exited with status %d", 3940 WEXITSTATUS(status)); 3941 else if (WIFSIGNALED(status)) 3942 errx(EX_UNAVAILABLE, 3943 "preprocessor exited with signal %d", 3944 WTERMSIG(status)); 3945 } 3946} 3947 3948int 3949main(int ac, char *av[]) 3950{ 3951 /* 3952 * If the last argument is an absolute pathname, interpret it 3953 * as a file to be preprocessed. 3954 */ 3955 3956 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) 3957 ipfw_readfile(ac, av); 3958 else { 3959 if (ipfw_main(ac-1, av+1)) 3960 show_usage(); 3961 } 3962 return EX_OK; 3963} 3964