1 /* 2 * Copyright (c) 2002-2003,2010 Luigi Rizzo 3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp 4 * Copyright (c) 1994 Ugen J.S.Antsilevich 5 * 6 * Idea and grammar partially left from: 7 * Copyright (c) 1993 Daniel Boulet 8 * 9 * Redistribution and use in source forms, with and without modification, 10 * are permitted provided that this entire comment appears intact. 11 * 12 * Redistribution in binary form may occur without any restrictions. 13 * Obviously, it would be nice if you gave credit where credit is due 14 * but requiring it would be too onerous. 15 * 16 * This software is provided ``AS IS'' without any warranties of any kind. 17 * 18 * Command line interface for IP firewall facility 19 * 20 * $FreeBSD$ 21 */ 22 23 #include <sys/wait.h> 24 #include <ctype.h> 25 #include <err.h> 26 #include <errno.h> 27 #include <signal.h> 28 #include <stdio.h> 29 #include <stdlib.h> 30 #include <string.h> 31 #include <sysexits.h> 32 #include <unistd.h> 33 34 #ifdef FSTACK 35 #include <stdint.h> 36 #include "ff_ipc.h" 37 #endif 38 39 #include "ipfw2.h" 40 41 static void 42 help(void) 43 { 44 fprintf(stderr, 45 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n\n" 46 #ifndef FSTACK 47 "\tipfw [-abcdefhnNqStTv] <command>\n\n" 48 #else 49 "\tipfw -P <f-stack proc_id> [-abcdefhnNqStTv] <command>\n\n" 50 #endif 51 "where <command> is one of the following:\n\n" 52 "add [num] [set N] [prob x] RULE-BODY\n" 53 "{pipe|queue} N config PIPE-BODY\n" 54 "[pipe|queue] {zero|delete|show} [N{,N}]\n" 55 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|reset|\n" 56 " reverse|proxy_only|redirect_addr linkspec|\n" 57 " redirect_port linkspec|redirect_proto linkspec}\n" 58 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n" 59 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n" 60 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n" 61 "table all {flush | list}\n" 62 "\n" 63 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n" 64 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n" 65 " skipto N | {divert|tee} PORT | forward ADDR |\n" 66 " pipe N | queue N | nat N | setfib FIB | reass\n" 67 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n" 68 "ADDR: [ MAC dst src ether_type ] \n" 69 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n" 70 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n" 71 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n" 72 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n" 73 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n" 74 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n" 75 "OPTION_LIST: OPTION [OPTION_LIST]\n" 76 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n" 77 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n" 78 " {dst-port|src-port} LIST |\n" 79 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n" 80 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n" 81 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n" 82 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n" 83 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n" 84 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n" 85 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n" 86 ); 87 88 exit(0); 89 } 90 91 /* 92 * Called with the arguments, including program name because getopt 93 * wants it to be present. 94 * Returns 0 if successful, 1 if empty command, errx() in case of errors. 95 * First thing we do is process parameters creating an argv[] array 96 * which includes the program name and a NULL entry at the end. 97 * If we are called with a single string, we split it on whitespace. 98 * Also, arguments with a trailing ',' are joined to the next one. 99 * The pointers (av[]) and data are in a single chunk of memory. 100 * av[0] points to the original program name, all other entries 101 * point into the allocated chunk. 102 */ 103 static int 104 ipfw_main(int oldac, char **oldav) 105 { 106 int ch, ac; 107 const char *errstr; 108 char **av, **save_av; 109 int do_acct = 0; /* Show packet/byte count */ 110 int try_next = 0; /* set if pipe cmd not found */ 111 int av_size; /* compute the av size */ 112 char *av_p; /* used to build the av list */ 113 114 #define WHITESP " \t\f\v\n\r" 115 if (oldac < 2) 116 return 1; /* need at least one argument */ 117 118 if (oldac == 2) { 119 /* 120 * If we are called with one argument, try to split it into 121 * words for subsequent parsing. Spaces after a ',' are 122 * removed by copying the string in-place. 123 */ 124 char *arg = oldav[1]; /* The string is the first arg. */ 125 int l = strlen(arg); 126 int copy = 0; /* 1 if we need to copy, 0 otherwise */ 127 int i, j; 128 129 for (i = j = 0; i < l; i++) { 130 if (arg[i] == '#') /* comment marker */ 131 break; 132 if (copy) { 133 arg[j++] = arg[i]; 134 copy = !strchr("," WHITESP, arg[i]); 135 } else { 136 copy = !strchr(WHITESP, arg[i]); 137 if (copy) 138 arg[j++] = arg[i]; 139 } 140 } 141 if (!copy && j > 0) /* last char was a 'blank', remove it */ 142 j--; 143 l = j; /* the new argument length */ 144 arg[j++] = '\0'; 145 if (l == 0) /* empty string! */ 146 return 1; 147 148 /* 149 * First, count number of arguments. Because of the previous 150 * processing, this is just the number of blanks plus 1. 151 */ 152 for (i = 0, ac = 1; i < l; i++) 153 if (strchr(WHITESP, arg[i]) != NULL) 154 ac++; 155 156 /* 157 * Allocate the argument list structure as a single block 158 * of memory, containing pointers and the argument 159 * strings. We include one entry for the program name 160 * because getopt expects it, and a NULL at the end 161 * to simplify further parsing. 162 */ 163 ac++; /* add 1 for the program name */ 164 av_size = (ac+1) * sizeof(char *) + l + 1; 165 av = safe_calloc(av_size, 1); 166 167 /* 168 * Init the argument pointer to the end of the array 169 * and copy arguments from arg[] to av[]. For each one, 170 * j is the initial character, i is the one past the end. 171 */ 172 av_p = (char *)&av[ac+1]; 173 for (ac = 1, i = j = 0; i < l; i++) { 174 if (strchr(WHITESP, arg[i]) != NULL || i == l-1) { 175 if (i == l-1) 176 i++; 177 bcopy(arg+j, av_p, i-j); 178 av[ac] = av_p; 179 av_p += i-j; /* the length of the string */ 180 *av_p++ = '\0'; 181 ac++; 182 j = i + 1; 183 } 184 } 185 } else { 186 /* 187 * If an argument ends with ',' join with the next one. 188 */ 189 int first, i, l=0; 190 191 /* 192 * Allocate the argument list structure as a single block 193 * of memory, containing both pointers and the argument 194 * strings. We include some space for the program name 195 * because getopt expects it. 196 * We add an extra pointer to the end of the array, 197 * to make simpler further parsing. 198 */ 199 for (i=0; i<oldac; i++) 200 l += strlen(oldav[i]); 201 202 av_size = (oldac+1) * sizeof(char *) + l + oldac; 203 av = safe_calloc(av_size, 1); 204 205 /* 206 * Init the argument pointer to the end of the array 207 * and copy arguments from arg[] to av[] 208 */ 209 av_p = (char *)&av[oldac+1]; 210 for (first = i = ac = 1, l = 0; i < oldac; i++) { 211 char *arg = oldav[i]; 212 int k = strlen(arg); 213 214 l += k; 215 if (arg[k-1] != ',' || i == oldac-1) { 216 /* Time to copy. */ 217 av[ac] = av_p; 218 for (l=0; first <= i; first++) { 219 strcat(av_p, oldav[first]); 220 av_p += strlen(oldav[first]); 221 } 222 *av_p++ = '\0'; 223 ac++; 224 l = 0; 225 first = i+1; 226 } 227 } 228 } 229 230 /* 231 * set the progname pointer to the original string 232 * and terminate the array with null 233 */ 234 av[0] = oldav[0]; 235 av[ac] = NULL; 236 237 /* Set the force flag for non-interactive processes */ 238 if (!co.do_force) 239 co.do_force = !isatty(STDIN_FILENO); 240 241 #ifdef EMULATE_SYSCTL /* sysctl emulation */ 242 if ( ac >= 2 && !strcmp(av[1], "sysctl")) { 243 char *s; 244 int i; 245 246 if (ac != 3) { 247 printf( "sysctl emulation usage:\n" 248 " ipfw sysctl name[=value]\n" 249 " ipfw sysctl -a\n"); 250 return 0; 251 } 252 s = strchr(av[2], '='); 253 if (s == NULL) { 254 s = !strcmp(av[2], "-a") ? NULL : av[2]; 255 sysctlbyname(s, NULL, NULL, NULL, 0); 256 } else { /* ipfw sysctl x.y.z=value */ 257 /* assume an INT value, will extend later */ 258 if (s[1] == '\0') { 259 printf("ipfw sysctl: missing value\n\n"); 260 return 0; 261 } 262 *s = '\0'; 263 i = strtol(s+1, NULL, 0); 264 sysctlbyname(av[2], NULL, NULL, &i, sizeof(int)); 265 } 266 return 0; 267 } 268 #endif 269 270 /* Save arguments for final freeing of memory. */ 271 save_av = av; 272 273 optind = optreset = 1; /* restart getopt() */ 274 #ifndef FSTACK 275 while ((ch = getopt(ac, av, "abcdefhinNp:qs:STtv")) != -1) 276 #else 277 while ((ch = getopt(ac, av, "abcdefhinNp:qs:STtvP:")) != -1) 278 #endif 279 switch (ch) { 280 case 'a': 281 do_acct = 1; 282 break; 283 284 case 'b': 285 co.comment_only = 1; 286 co.do_compact = 1; 287 break; 288 289 case 'c': 290 co.do_compact = 1; 291 break; 292 293 case 'd': 294 co.do_dynamic = 1; 295 break; 296 297 case 'e': 298 co.do_expired = 1; 299 break; 300 301 case 'f': 302 co.do_force = 1; 303 break; 304 305 case 'h': /* help */ 306 free(save_av); 307 help(); 308 break; /* NOTREACHED */ 309 310 case 'i': 311 co.do_value_as_ip = 1; 312 break; 313 314 case 'n': 315 co.test_only = 1; 316 break; 317 318 case 'N': 319 co.do_resolv = 1; 320 break; 321 322 case 'p': 323 errx(EX_USAGE, "An absolute pathname must be used " 324 "with -p option."); 325 /* NOTREACHED */ 326 327 case 'q': 328 co.do_quiet = 1; 329 break; 330 331 case 's': /* sort */ 332 co.do_sort = atoi(optarg); 333 break; 334 335 case 'S': 336 co.show_sets = 1; 337 break; 338 339 case 't': 340 co.do_time = 1; 341 break; 342 343 case 'T': 344 co.do_time = 2; /* numeric timestamp */ 345 break; 346 347 case 'v': /* verbose */ 348 co.verbose = 1; 349 break; 350 #ifdef FSTACK 351 case 'P': 352 ff_set_proc_id(atoi(optarg)); 353 break; 354 #endif 355 default: 356 free(save_av); 357 return 1; 358 } 359 360 ac -= optind; 361 av += optind; 362 NEED1("bad arguments, for usage summary ``ipfw''"); 363 364 /* 365 * An undocumented behaviour of ipfw1 was to allow rule numbers first, 366 * e.g. "100 add allow ..." instead of "add 100 allow ...". 367 * In case, swap first and second argument to get the normal form. 368 */ 369 if (ac > 1 && isdigit(*av[0])) { 370 char *p = av[0]; 371 372 av[0] = av[1]; 373 av[1] = p; 374 } 375 376 /* 377 * Optional: pipe, queue or nat. 378 */ 379 co.do_nat = 0; 380 co.do_pipe = 0; 381 co.use_set = 0; 382 if (!strncmp(*av, "nat", strlen(*av))) 383 co.do_nat = 1; 384 else if (!strncmp(*av, "pipe", strlen(*av))) 385 co.do_pipe = 1; 386 else if (_substrcmp(*av, "queue") == 0) 387 co.do_pipe = 2; 388 else if (_substrcmp(*av, "flowset") == 0) 389 co.do_pipe = 2; 390 else if (_substrcmp(*av, "sched") == 0) 391 co.do_pipe = 3; 392 else if (!strncmp(*av, "set", strlen(*av))) { 393 if (ac > 1 && isdigit(av[1][0])) { 394 co.use_set = strtonum(av[1], 0, resvd_set_number, 395 &errstr); 396 if (errstr) 397 errx(EX_DATAERR, 398 "invalid set number %s\n", av[1]); 399 ac -= 2; av += 2; co.use_set++; 400 } 401 } 402 403 if (co.do_pipe || co.do_nat) { 404 ac--; 405 av++; 406 } 407 NEED1("missing command"); 408 409 /* 410 * For pipes, queues and nats we normally say 'nat|pipe NN config' 411 * but the code is easier to parse as 'nat|pipe config NN' 412 * so we swap the two arguments. 413 */ 414 if ((co.do_pipe || co.do_nat) && ac > 1 && isdigit(*av[0])) { 415 char *p = av[0]; 416 417 av[0] = av[1]; 418 av[1] = p; 419 } 420 421 if (co.use_set == 0) { 422 if (_substrcmp(*av, "add") == 0) 423 ipfw_add(av); 424 else if (co.do_nat && _substrcmp(*av, "show") == 0) 425 ipfw_show_nat(ac, av); 426 else if (co.do_pipe && _substrcmp(*av, "config") == 0) 427 #ifdef DUMMYNET 428 ipfw_config_pipe(ac, av); 429 #else 430 { 431 errx(EX_UNAVAILABLE, "ipfw_config_pipe not supported"); 432 } 433 #endif 434 else if (co.do_nat && _substrcmp(*av, "config") == 0) 435 ipfw_config_nat(ac, av); 436 else if (_substrcmp(*av, "set") == 0) 437 ipfw_sets_handler(av); 438 else if (_substrcmp(*av, "table") == 0) 439 ipfw_table_handler(ac, av); 440 else if (_substrcmp(*av, "enable") == 0) 441 ipfw_sysctl_handler(av, 1); 442 else if (_substrcmp(*av, "disable") == 0) 443 ipfw_sysctl_handler(av, 0); 444 else 445 try_next = 1; 446 } 447 448 if (co.use_set || try_next) { 449 if (_substrcmp(*av, "delete") == 0) 450 ipfw_delete(av); 451 else if (_substrcmp(*av, "flush") == 0) 452 ipfw_flush(co.do_force); 453 else if (_substrcmp(*av, "zero") == 0) 454 ipfw_zero(ac, av, 0 /* IP_FW_ZERO */); 455 else if (_substrcmp(*av, "resetlog") == 0) 456 ipfw_zero(ac, av, 1 /* IP_FW_RESETLOG */); 457 else if (_substrcmp(*av, "print") == 0 || 458 _substrcmp(*av, "list") == 0) 459 ipfw_list(ac, av, do_acct); 460 else if (_substrcmp(*av, "show") == 0) 461 ipfw_list(ac, av, 1 /* show counters */); 462 else if (_substrcmp(*av, "table") == 0) 463 ipfw_table_handler(ac, av); 464 else if (_substrcmp(*av, "internal") == 0) 465 ipfw_internal_handler(ac, av); 466 else 467 errx(EX_USAGE, "bad command `%s'", *av); 468 } 469 470 /* Free memory allocated in the argument parsing. */ 471 free(save_av); 472 return 0; 473 } 474 475 476 static void 477 ipfw_readfile(int ac, char *av[]) 478 { 479 #define MAX_ARGS 32 480 char buf[4096]; 481 char *progname = av[0]; /* original program name */ 482 const char *cmd = NULL; /* preprocessor name, if any */ 483 const char *filename = av[ac-1]; /* file to read */ 484 int c, lineno=0; 485 FILE *f = NULL; 486 pid_t preproc = 0; 487 488 #ifndef FSTACK 489 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) { 490 #else 491 while ((c = getopt(ac, av, "cfNnp:qSP:")) != -1) { 492 #endif 493 switch(c) { 494 case 'c': 495 co.do_compact = 1; 496 break; 497 498 case 'f': 499 co.do_force = 1; 500 break; 501 502 case 'N': 503 co.do_resolv = 1; 504 break; 505 506 case 'n': 507 co.test_only = 1; 508 break; 509 510 case 'p': 511 /* 512 * ipfw -p cmd [args] filename 513 * 514 * We are done with getopt(). All arguments 515 * except the filename go to the preprocessor, 516 * so we need to do the following: 517 * - check that a filename is actually present; 518 * - advance av by optind-1 to skip arguments 519 * already processed; 520 * - decrease ac by optind, to remove the args 521 * already processed and the final filename; 522 * - set the last entry in av[] to NULL so 523 * popen() can detect the end of the array; 524 * - set optind=ac to let getopt() terminate. 525 */ 526 if (optind == ac) 527 errx(EX_USAGE, "no filename argument"); 528 cmd = optarg; 529 av[ac-1] = NULL; 530 av += optind - 1; 531 ac -= optind; 532 optind = ac; 533 break; 534 535 case 'q': 536 co.do_quiet = 1; 537 break; 538 539 case 'S': 540 co.show_sets = 1; 541 break; 542 543 #ifdef FSTACK 544 case 'P': 545 ff_set_proc_id(atoi(optarg)); 546 break; 547 #endif 548 549 default: 550 errx(EX_USAGE, "bad arguments, for usage" 551 " summary ``ipfw''"); 552 } 553 554 } 555 556 if (cmd == NULL && ac != optind + 1) 557 errx(EX_USAGE, "extraneous filename arguments %s", av[ac-1]); 558 559 if ((f = fopen(filename, "r")) == NULL) 560 err(EX_UNAVAILABLE, "fopen: %s", filename); 561 562 if (cmd != NULL) { /* pipe through preprocessor */ 563 int pipedes[2]; 564 565 if (pipe(pipedes) == -1) 566 err(EX_OSERR, "cannot create pipe"); 567 568 preproc = fork(); 569 if (preproc == -1) 570 err(EX_OSERR, "cannot fork"); 571 572 if (preproc == 0) { 573 /* 574 * Child, will run the preprocessor with the 575 * file on stdin and the pipe on stdout. 576 */ 577 if (dup2(fileno(f), 0) == -1 578 || dup2(pipedes[1], 1) == -1) 579 err(EX_OSERR, "dup2()"); 580 fclose(f); 581 close(pipedes[1]); 582 close(pipedes[0]); 583 execvp(cmd, av); 584 err(EX_OSERR, "execvp(%s) failed", cmd); 585 } else { /* parent, will reopen f as the pipe */ 586 fclose(f); 587 close(pipedes[1]); 588 if ((f = fdopen(pipedes[0], "r")) == NULL) { 589 int savederrno = errno; 590 591 (void)kill(preproc, SIGTERM); 592 errno = savederrno; 593 err(EX_OSERR, "fdopen()"); 594 } 595 } 596 } 597 598 while (fgets(buf, sizeof(buf), f)) { /* read commands */ 599 char linename[20]; 600 char *args[2]; 601 602 lineno++; 603 snprintf(linename, sizeof(linename), "Line %d", lineno); 604 #ifndef FSTACK 605 setprogname(linename); /* XXX */ 606 #endif 607 args[0] = progname; 608 args[1] = buf; 609 ipfw_main(2, args); 610 } 611 fclose(f); 612 if (cmd != NULL) { 613 int status; 614 615 if (waitpid(preproc, &status, 0) == -1) 616 errx(EX_OSERR, "waitpid()"); 617 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK) 618 errx(EX_UNAVAILABLE, 619 "preprocessor exited with status %d", 620 WEXITSTATUS(status)); 621 else if (WIFSIGNALED(status)) 622 errx(EX_UNAVAILABLE, 623 "preprocessor exited with signal %d", 624 WTERMSIG(status)); 625 } 626 } 627 628 int 629 main(int ac, char *av[]) 630 { 631 #if defined(_WIN32) && defined(TCC) 632 { 633 WSADATA wsaData; 634 int ret=0; 635 unsigned short wVersionRequested = MAKEWORD(2, 2); 636 ret = WSAStartup(wVersionRequested, &wsaData); 637 if (ret != 0) { 638 /* Tell the user that we could not find a usable */ 639 /* Winsock DLL. */ 640 printf("WSAStartup failed with error: %d\n", ret); 641 return 1; 642 } 643 } 644 #endif 645 /* 646 * If the last argument is an absolute pathname, interpret it 647 * as a file to be preprocessed. 648 */ 649 #ifdef FSTACK 650 ff_ipc_init(); 651 #endif 652 if (ac > 1 && av[ac - 1][0] == '/') { 653 if (access(av[ac - 1], R_OK) == 0) 654 ipfw_readfile(ac, av); 655 else 656 err(EX_USAGE, "pathname: %s", av[ac - 1]); 657 } else { 658 if (ipfw_main(ac, av)) { 659 errx(EX_USAGE, 660 "usage: ipfw [options]\n" 661 "do \"ipfw -h\" or \"man ipfw\" for details"); 662 } 663 } 664 return EX_OK; 665 } 666