1/* 2 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000 3 * The Regents of the University of California. All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that: (1) source code distributions 7 * retain the above copyright notice and this paragraph in its entirety, (2) 8 * distributions including binary code include the above copyright notice and 9 * this paragraph in its entirety in the documentation or other materials 10 * provided with the distribution, and (3) all advertising materials mentioning 11 * features or use of this software display the following acknowledgement: 12 * ``This product includes software developed by the University of California, 13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of 14 * the University nor the names of its contributors may be used to endorse 15 * or promote products derived from this software without specific prior 16 * written permission. 17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED 18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF 19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 20 * 21 * Support for splitting captures into multiple files with a maximum 22 * file size: 23 * 24 * Copyright (c) 2001 25 * Seth Webster <swebster@sst.ll.mit.edu> 26 */ 27 28#include <sys/cdefs.h> 29#ifndef lint 30__RCSID("$NetBSD: tcpdump.c,v 1.19 2023/08/17 20:19:40 christos Exp $"); 31#endif 32 33/* 34 * tcpdump - dump traffic on a network 35 * 36 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory. 37 * Mercilessly hacked and occasionally improved since then via the 38 * combined efforts of Van, Steve McCanne and Craig Leres of LBL. 39 */ 40 41#ifdef HAVE_CONFIG_H 42#include <config.h> 43#endif 44 45/* 46 * Some older versions of Mac OS X may ship pcap.h from libpcap 0.6 with a 47 * libpcap based on 0.8. That means it has pcap_findalldevs() but the 48 * header doesn't define pcap_if_t, meaning that we can't actually *use* 49 * pcap_findalldevs(). 50 */ 51#ifdef HAVE_PCAP_FINDALLDEVS 52#ifndef HAVE_PCAP_IF_T 53#undef HAVE_PCAP_FINDALLDEVS 54#endif 55#endif 56 57#include "netdissect-stdinc.h" 58 59/* 60 * This must appear after including netdissect-stdinc.h, so that _U_ is 61 * defined. 62 */ 63#ifndef lint 64static const char copyright[] _U_ = 65 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\ 66The Regents of the University of California. All rights reserved.\n"; 67#endif 68 69#include <sys/stat.h> 70 71#ifdef HAVE_FCNTL_H 72#include <fcntl.h> 73#endif 74 75#ifdef HAVE_LIBCRYPTO 76#include <openssl/crypto.h> 77#endif 78 79#ifdef HAVE_GETOPT_LONG 80#include <getopt.h> 81#else 82#include "missing/getopt_long.h" 83#endif 84/* Capsicum-specific code requires macros from <net/bpf.h>, which will fail 85 * to compile if <pcap.h> has already been included; including the headers 86 * in the opposite order works fine. For the most part anyway, because in 87 * FreeBSD <pcap/pcap.h> declares bpf_dump() instead of <net/bpf.h>. Thus 88 * interface.h takes care of it later to avoid a compiler warning. 89 */ 90#ifdef HAVE_CAPSICUM 91#include <sys/capsicum.h> 92#include <sys/ioccom.h> 93#include <net/bpf.h> 94#include <libgen.h> 95#ifdef HAVE_CASPER 96#include <libcasper.h> 97#include <casper/cap_dns.h> 98#include <sys/nv.h> 99#endif /* HAVE_CASPER */ 100#endif /* HAVE_CAPSICUM */ 101#ifdef HAVE_PCAP_OPEN 102/* 103 * We found pcap_open() in the capture library, so we'll be using 104 * the remote capture APIs; define PCAP_REMOTE before we include pcap.h, 105 * so we get those APIs declared, and the types and #defines that they 106 * use defined. 107 * 108 * WinPcap's headers require that PCAP_REMOTE be defined in order to get 109 * remote-capture APIs declared and types and #defines that they use 110 * defined. 111 * 112 * (Versions of libpcap with those APIs, and thus Npcap, which is based on 113 * those versions of libpcap, don't require it.) 114 */ 115#define HAVE_REMOTE 116#endif 117#include <pcap.h> 118#include <signal.h> 119#include <stdio.h> 120#include <stdarg.h> 121#include <stdlib.h> 122#include <string.h> 123#include <limits.h> 124#include <resolv.h> 125#ifdef _WIN32 126#include <windows.h> 127#else 128#include <sys/time.h> 129#include <sys/wait.h> 130#include <sys/resource.h> 131#include <pwd.h> 132#include <grp.h> 133#endif /* _WIN32 */ 134 135/* 136 * Pathname separator. 137 * Use this in pathnames, but do *not* use it in URLs. 138 */ 139#ifdef _WIN32 140#define PATH_SEPARATOR '\\' 141#else 142#define PATH_SEPARATOR '/' 143#endif 144 145/* capabilities convenience library */ 146/* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H. 147 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG. 148 * Thus, the later tests are done only on HAVE_LIBCAP_NG. 149 */ 150#ifdef HAVE_LIBCAP_NG 151#ifdef HAVE_CAP_NG_H 152#include <cap-ng.h> 153#else 154#undef HAVE_LIBCAP_NG 155#endif /* HAVE_CAP_NG_H */ 156#endif /* HAVE_LIBCAP_NG */ 157 158#ifdef __FreeBSD__ 159#include <sys/sysctl.h> 160#endif /* __FreeBSD__ */ 161 162#include "netdissect-stdinc.h" 163#include "netdissect.h" 164#include "interface.h" 165#include "addrtoname.h" 166#include "machdep.h" 167#include "pcap-missing.h" 168#include "ascii_strcasecmp.h" 169 170#include "print.h" 171 172#include "diag-control.h" 173 174#include "fptype.h" 175 176#ifndef PATH_MAX 177#define PATH_MAX 1024 178#endif 179 180#if defined(SIGINFO) 181#define SIGNAL_REQ_INFO SIGINFO 182#elif defined(SIGUSR1) 183#define SIGNAL_REQ_INFO SIGUSR1 184#endif 185 186#if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2) 187#define SIGNAL_FLUSH_PCAP SIGUSR2 188#endif 189 190#if defined(HAVE_PCAP_CREATE) || defined(_WIN32) 191static int Bflag; /* buffer size */ 192#endif 193#ifdef HAVE_PCAP_DUMP_FTELL64 194static int64_t Cflag; /* rotate dump files after this many bytes */ 195#else 196static long Cflag; /* rotate dump files after this many bytes */ 197#endif 198static int Cflag_count; /* Keep track of which file number we're writing */ 199#ifdef HAVE_PCAP_FINDALLDEVS 200static int Dflag; /* list available devices and exit */ 201#endif 202#ifdef HAVE_PCAP_FINDALLDEVS_EX 203static char *remote_interfaces_source; /* list available devices from this source and exit */ 204#endif 205 206/* 207 * This is exported because, in some versions of libpcap, if libpcap 208 * is built with optimizer debugging code (which is *NOT* the default 209 * configuration!), the library *imports*(!) a variable named dflag, 210 * under the expectation that tcpdump is exporting it, to govern 211 * how much debugging information to print when optimizing 212 * the generated BPF code. 213 * 214 * This is a horrible hack; newer versions of libpcap don't import 215 * dflag but, instead, *if* built with optimizer debugging code, 216 * *export* a routine to set that flag. 217 */ 218extern int dflag; 219int dflag; /* print filter code */ 220static int Gflag; /* rotate dump files after this many seconds */ 221static int Gflag_count; /* number of files created with Gflag rotation */ 222static time_t Gflag_time; /* The last time_t the dump file was rotated. */ 223static int Lflag; /* list available data link types and exit */ 224static int Iflag; /* rfmon (monitor) mode */ 225#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 226static int Jflag; /* list available time stamp types */ 227static int jflag = -1; /* packet time stamp source */ 228#endif 229static int lflag; /* line-buffered output */ 230static int pflag; /* don't go promiscuous */ 231#ifdef HAVE_PCAP_SETDIRECTION 232static int Qflag = -1; /* restrict captured packet by send/receive direction */ 233#endif 234#ifdef HAVE_PCAP_DUMP_FLUSH 235static int Uflag; /* "unbuffered" output of dump files */ 236#endif 237static int Wflag; /* recycle output files after this number of files */ 238static int WflagChars; 239static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */ 240static int timeout = 1000; /* default timeout = 1000 ms = 1 s */ 241#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE 242static int immediate_mode; 243#endif 244static int count_mode; 245 246static int infodelay; 247static int infoprint; 248 249char *program_name; 250 251/* Forwards */ 252static NORETURN void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2); 253static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2); 254static NORETURN void exit_tcpdump(int); 255static void (*setsignal (int sig, void (*func)(int)))(int); 256static void cleanup(int); 257static void child_cleanup(int); 258static void print_version(FILE *); 259static void print_usage(FILE *); 260#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 261static NORETURN void show_tstamp_types_and_exit(pcap_t *, const char *device); 262#endif 263static NORETURN void show_dlts_and_exit(pcap_t *, const char *device); 264#ifdef HAVE_PCAP_FINDALLDEVS 265static NORETURN void show_devices_and_exit(void); 266#endif 267#ifdef HAVE_PCAP_FINDALLDEVS_EX 268static NORETURN void show_remote_devices_and_exit(void); 269#endif 270 271static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *); 272static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *); 273static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *); 274static void droproot(const char *, const char *); 275 276#ifdef SIGNAL_REQ_INFO 277static void requestinfo(int); 278#endif 279 280#ifdef SIGNAL_FLUSH_PCAP 281static void flushpcap(int); 282#endif 283 284#ifdef _WIN32 285 static HANDLE timer_handle = INVALID_HANDLE_VALUE; 286 static void CALLBACK verbose_stats_dump(PVOID param, BOOLEAN timer_fired); 287#else /* _WIN32 */ 288 static void verbose_stats_dump(int sig); 289#endif /* _WIN32 */ 290 291static void info(int); 292static u_int packets_captured; 293 294#ifdef HAVE_PCAP_FINDALLDEVS 295static const struct tok status_flags[] = { 296#ifdef PCAP_IF_UP 297 { PCAP_IF_UP, "Up" }, 298#endif 299#ifdef PCAP_IF_RUNNING 300 { PCAP_IF_RUNNING, "Running" }, 301#endif 302 { PCAP_IF_LOOPBACK, "Loopback" }, 303#ifdef PCAP_IF_WIRELESS 304 { PCAP_IF_WIRELESS, "Wireless" }, 305#endif 306 { 0, NULL } 307}; 308#endif 309 310static pcap_t *pd; 311static pcap_dumper_t *pdd = NULL; 312 313static int supports_monitor_mode; 314 315extern int optind; 316extern int opterr; 317extern char *optarg; 318 319struct dump_info { 320 char *WFileName; 321 char *CurrentFileName; 322 pcap_t *pd; 323 pcap_dumper_t *pdd; 324 netdissect_options *ndo; 325#ifdef HAVE_CAPSICUM 326 int dirfd; 327#endif 328}; 329 330#if defined(HAVE_PCAP_SET_PARSER_DEBUG) 331/* 332 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared 333 * by any libpcap header, because it's a special hack, only available if 334 * libpcap was configured to include it, and only intended for use by 335 * libpcap developers trying to debug the parser for filter expressions). 336 */ 337#ifdef _WIN32 338__declspec(dllimport) 339#else /* _WIN32 */ 340extern 341#endif /* _WIN32 */ 342void pcap_set_parser_debug(int); 343#elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG) 344/* 345 * We don't have pcap_set_parser_debug() in libpcap, but we do have 346 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug() 347 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG. 348 */ 349static void 350pcap_set_parser_debug(int value) 351{ 352#ifdef HAVE_PCAP_DEBUG 353 extern int pcap_debug __weak; 354 355 if (&pcap_debug) 356 pcap_debug = value; 357#else /* HAVE_PCAP_DEBUG */ 358 extern int yydebug; 359 360 yydebug = value; 361#endif /* HAVE_PCAP_DEBUG */ 362} 363 364#define HAVE_PCAP_SET_PARSER_DEBUG 365#endif 366 367#if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG) 368/* 369 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared 370 * by any libpcap header, because it's a special hack, only available if 371 * libpcap was configured to include it, and only intended for use by 372 * libpcap developers trying to debug the optimizer for filter expressions). 373 */ 374#ifdef _WIN32 375__declspec(dllimport) 376#else /* _WIN32 */ 377extern 378#endif /* _WIN32 */ 379void pcap_set_optimizer_debug(int); 380#endif 381 382/* VARARGS */ 383static void 384error(const char *fmt, ...) 385{ 386 va_list ap; 387 388 (void)fprintf(stderr, "%s: ", program_name); 389 va_start(ap, fmt); 390 (void)vfprintf(stderr, fmt, ap); 391 va_end(ap); 392 if (*fmt) { 393 fmt += strlen(fmt); 394 if (fmt[-1] != '\n') 395 (void)fputc('\n', stderr); 396 } 397 exit_tcpdump(S_ERR_HOST_PROGRAM); 398 /* NOTREACHED */ 399} 400 401/* VARARGS */ 402static void 403warning(const char *fmt, ...) 404{ 405 va_list ap; 406 407 (void)fprintf(stderr, "%s: WARNING: ", program_name); 408 va_start(ap, fmt); 409 (void)vfprintf(stderr, fmt, ap); 410 va_end(ap); 411 if (*fmt) { 412 fmt += strlen(fmt); 413 if (fmt[-1] != '\n') 414 (void)fputc('\n', stderr); 415 } 416} 417 418static void 419exit_tcpdump(int status) 420{ 421 nd_cleanup(); 422 exit(status); 423} 424 425#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 426static void 427show_tstamp_types_and_exit(pcap_t *pc, const char *device) 428{ 429 int n_tstamp_types; 430 int *tstamp_types = 0; 431 const char *tstamp_type_name; 432 int i; 433 434 n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types); 435 if (n_tstamp_types < 0) 436 error("%s", pcap_geterr(pc)); 437 438 if (n_tstamp_types == 0) { 439 fprintf(stderr, "Time stamp type cannot be set for %s\n", 440 device); 441 exit_tcpdump(S_SUCCESS); 442 } 443 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n", 444 device); 445 for (i = 0; i < n_tstamp_types; i++) { 446 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]); 447 if (tstamp_type_name != NULL) { 448 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name, 449 pcap_tstamp_type_val_to_description(tstamp_types[i])); 450 } else { 451 (void) fprintf(stderr, " %d\n", tstamp_types[i]); 452 } 453 } 454 pcap_free_tstamp_types(tstamp_types); 455 exit_tcpdump(S_SUCCESS); 456} 457#endif 458 459static void 460show_dlts_and_exit(pcap_t *pc, const char *device) 461{ 462 int n_dlts, i; 463 int *dlts = 0; 464 const char *dlt_name; 465 466 n_dlts = pcap_list_datalinks(pc, &dlts); 467 if (n_dlts < 0) 468 error("%s", pcap_geterr(pc)); 469 else if (n_dlts == 0 || !dlts) 470 error("No data link types."); 471 472 /* 473 * If the interface is known to support monitor mode, indicate 474 * whether these are the data link types available when not in 475 * monitor mode, if -I wasn't specified, or when in monitor mode, 476 * when -I was specified (the link-layer types available in 477 * monitor mode might be different from the ones available when 478 * not in monitor mode). 479 */ 480 if (supports_monitor_mode) 481 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n", 482 device, 483 Iflag ? "when in monitor mode" : "when not in monitor mode"); 484 else 485 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n", 486 device); 487 488 for (i = 0; i < n_dlts; i++) { 489 dlt_name = pcap_datalink_val_to_name(dlts[i]); 490 if (dlt_name != NULL) { 491 (void) fprintf(stderr, " %s (%s)", dlt_name, 492 pcap_datalink_val_to_description(dlts[i])); 493 494 /* 495 * OK, does tcpdump handle that type? 496 */ 497 if (!has_printer(dlts[i])) 498 (void) fprintf(stderr, " (printing not supported)"); 499 fprintf(stderr, "\n"); 500 } else { 501 (void) fprintf(stderr, " DLT %d (printing not supported)\n", 502 dlts[i]); 503 } 504 } 505#ifdef HAVE_PCAP_FREE_DATALINKS 506 pcap_free_datalinks(dlts); 507#endif 508 exit_tcpdump(S_SUCCESS); 509} 510 511#ifdef HAVE_PCAP_FINDALLDEVS 512static void 513show_devices_and_exit(void) 514{ 515 pcap_if_t *dev, *devlist; 516 char ebuf[PCAP_ERRBUF_SIZE]; 517 int i; 518 519 if (pcap_findalldevs(&devlist, ebuf) < 0) 520 error("%s", ebuf); 521 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) { 522 printf("%d.%s", i+1, dev->name); 523 if (dev->description != NULL) 524 printf(" (%s)", dev->description); 525 if (dev->flags != 0) { 526 printf(" ["); 527 printf("%s", bittok2str(status_flags, "none", dev->flags)); 528#ifdef PCAP_IF_WIRELESS 529 if (dev->flags & PCAP_IF_WIRELESS) { 530 switch (dev->flags & PCAP_IF_CONNECTION_STATUS) { 531 532 case PCAP_IF_CONNECTION_STATUS_UNKNOWN: 533 printf(", Association status unknown"); 534 break; 535 536 case PCAP_IF_CONNECTION_STATUS_CONNECTED: 537 printf(", Associated"); 538 break; 539 540 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED: 541 printf(", Not associated"); 542 break; 543 544 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE: 545 break; 546 } 547 } else { 548 switch (dev->flags & PCAP_IF_CONNECTION_STATUS) { 549 550 case PCAP_IF_CONNECTION_STATUS_UNKNOWN: 551 printf(", Connection status unknown"); 552 break; 553 554 case PCAP_IF_CONNECTION_STATUS_CONNECTED: 555 printf(", Connected"); 556 break; 557 558 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED: 559 printf(", Disconnected"); 560 break; 561 562 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE: 563 break; 564 } 565 } 566#endif 567 printf("]"); 568 } 569 printf("\n"); 570 } 571 pcap_freealldevs(devlist); 572 exit_tcpdump(S_SUCCESS); 573} 574#endif /* HAVE_PCAP_FINDALLDEVS */ 575 576#ifdef HAVE_PCAP_FINDALLDEVS_EX 577static void 578show_remote_devices_and_exit(void) 579{ 580 pcap_if_t *dev, *devlist; 581 char ebuf[PCAP_ERRBUF_SIZE]; 582 int i; 583 584 if (pcap_findalldevs_ex(remote_interfaces_source, NULL, &devlist, 585 ebuf) < 0) 586 error("%s", ebuf); 587 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) { 588 printf("%d.%s", i+1, dev->name); 589 if (dev->description != NULL) 590 printf(" (%s)", dev->description); 591 if (dev->flags != 0) 592 printf(" [%s]", bittok2str(status_flags, "none", dev->flags)); 593 printf("\n"); 594 } 595 pcap_freealldevs(devlist); 596 exit_tcpdump(S_SUCCESS); 597} 598#endif /* HAVE_PCAP_FINDALLDEVS */ 599 600/* 601 * Short options. 602 * 603 * Note that there we use all letters for short options except for g, k, 604 * o, and P, and those are used by other versions of tcpdump, and we should 605 * only use them for the same purposes that the other versions of tcpdump 606 * use them: 607 * 608 * macOS tcpdump uses -g to force non--v output for IP to be on one 609 * line, making it more "g"repable; 610 * 611 * macOS tcpdump uses -k to specify that packet comments in pcapng files 612 * should be printed; 613 * 614 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done 615 * for hosts sending TCP SYN packets; 616 * 617 * macOS tcpdump uses -P to indicate that -w should write pcapng rather 618 * than pcap files. 619 * 620 * macOS tcpdump also uses -Q to specify expressions that match packet 621 * metadata, including but not limited to the packet direction. 622 * The expression syntax is different from a simple "in|out|inout", 623 * and those expressions aren't accepted by macOS tcpdump, but the 624 * equivalents would be "in" = "dir=in", "out" = "dir=out", and 625 * "inout" = "dir=in or dir=out", and the parser could conceivably 626 * special-case "in", "out", and "inout" as expressions for backwards 627 * compatibility, so all is not (yet) lost. 628 */ 629 630/* 631 * Set up flags that might or might not be supported depending on the 632 * version of libpcap we're using. 633 */ 634#if defined(HAVE_PCAP_CREATE) || defined(_WIN32) 635#define B_FLAG "B:" 636#define B_FLAG_USAGE " [ -B size ]" 637#else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ 638#define B_FLAG 639#define B_FLAG_USAGE 640#endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ 641 642#ifdef HAVE_PCAP_FINDALLDEVS 643#define D_FLAG "D" 644#else 645#define D_FLAG 646#endif 647 648#ifdef HAVE_PCAP_CREATE 649#define I_FLAG "I" 650#else /* HAVE_PCAP_CREATE */ 651#define I_FLAG 652#endif /* HAVE_PCAP_CREATE */ 653 654#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 655#define j_FLAG "j:" 656#define j_FLAG_USAGE " [ -j tstamptype ]" 657#define J_FLAG "J" 658#else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */ 659#define j_FLAG 660#define j_FLAG_USAGE 661#define J_FLAG 662#endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */ 663 664#ifdef USE_LIBSMI 665#define m_FLAG_USAGE "[ -m module ] ..." 666#endif 667 668#ifdef HAVE_PCAP_SETDIRECTION 669#define Q_FLAG "Q:" 670#define Q_FLAG_USAGE " [ -Q in|out|inout ]" 671#else 672#define Q_FLAG 673#define Q_FLAG_USAGE 674#endif 675 676#ifdef HAVE_PCAP_DUMP_FLUSH 677#define U_FLAG "U" 678#else 679#define U_FLAG 680#endif 681 682#define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#" 683 684/* 685 * Long options. 686 * 687 * We do not currently have long options corresponding to all short 688 * options; we should probably pick appropriate option names for them. 689 * 690 * However, the short options where the number of times the option is 691 * specified matters, such as -v and -d and -t, should probably not 692 * just map to a long option, as saying 693 * 694 * tcpdump --verbose --verbose 695 * 696 * doesn't make sense; it should be --verbosity={N} or something such 697 * as that. 698 * 699 * For long options with no corresponding short options, we define values 700 * outside the range of ASCII graphic characters, make that the last 701 * component of the entry for the long option, and have a case for that 702 * option in the switch statement. 703 */ 704#define OPTION_VERSION 128 705#define OPTION_TSTAMP_PRECISION 129 706#define OPTION_IMMEDIATE_MODE 130 707#define OPTION_PRINT 131 708#define OPTION_LIST_REMOTE_INTERFACES 132 709#define OPTION_TSTAMP_MICRO 133 710#define OPTION_TSTAMP_NANO 134 711#define OPTION_FP_TYPE 135 712#define OPTION_COUNT 136 713 714static const struct option longopts[] = { 715#if defined(HAVE_PCAP_CREATE) || defined(_WIN32) 716 { "buffer-size", required_argument, NULL, 'B' }, 717#endif 718 { "list-interfaces", no_argument, NULL, 'D' }, 719#ifdef HAVE_PCAP_FINDALLDEVS_EX 720 { "list-remote-interfaces", required_argument, NULL, OPTION_LIST_REMOTE_INTERFACES }, 721#endif 722 { "help", no_argument, NULL, 'h' }, 723 { "interface", required_argument, NULL, 'i' }, 724#ifdef HAVE_PCAP_CREATE 725 { "monitor-mode", no_argument, NULL, 'I' }, 726#endif 727#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 728 { "time-stamp-type", required_argument, NULL, 'j' }, 729 { "list-time-stamp-types", no_argument, NULL, 'J' }, 730#endif 731#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION 732 { "micro", no_argument, NULL, OPTION_TSTAMP_MICRO}, 733 { "nano", no_argument, NULL, OPTION_TSTAMP_NANO}, 734 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION}, 735#endif 736 { "dont-verify-checksums", no_argument, NULL, 'K' }, 737 { "list-data-link-types", no_argument, NULL, 'L' }, 738 { "no-optimize", no_argument, NULL, 'O' }, 739 { "no-promiscuous-mode", no_argument, NULL, 'p' }, 740#ifdef HAVE_PCAP_SETDIRECTION 741 { "direction", required_argument, NULL, 'Q' }, 742#endif 743 { "snapshot-length", required_argument, NULL, 's' }, 744 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' }, 745#ifdef HAVE_PCAP_DUMP_FLUSH 746 { "packet-buffered", no_argument, NULL, 'U' }, 747#endif 748 { "linktype", required_argument, NULL, 'y' }, 749#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE 750 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE }, 751#endif 752#ifdef HAVE_PCAP_SET_PARSER_DEBUG 753 { "debug-filter-parser", no_argument, NULL, 'Y' }, 754#endif 755 { "relinquish-privileges", required_argument, NULL, 'Z' }, 756 { "count", no_argument, NULL, OPTION_COUNT }, 757 { "fp-type", no_argument, NULL, OPTION_FP_TYPE }, 758 { "number", no_argument, NULL, '#' }, 759 { "print", no_argument, NULL, OPTION_PRINT }, 760 { "version", no_argument, NULL, OPTION_VERSION }, 761 { NULL, 0, NULL, 0 } 762}; 763 764#ifdef HAVE_PCAP_FINDALLDEVS_EX 765#define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]" 766#else 767#define LIST_REMOTE_INTERFACES_USAGE 768#endif 769 770#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE 771#define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]" 772#else 773#define IMMEDIATE_MODE_USAGE "" 774#endif 775 776#ifndef _WIN32 777/* Drop root privileges and chroot if necessary */ 778static void 779droproot(const char *username, const char *chroot_dir) 780{ 781 struct passwd *pw = NULL; 782 783 if (chroot_dir && !username) 784 error("Chroot without dropping root is insecure"); 785 786 pw = getpwnam(username); 787 if (pw) { 788 if (initgroups(pw->pw_name, pw->pw_gid) != 0) { 789 fprintf(stderr, "tcpdump: Couldn't initgroups to " 790 "'%.32s' gid=%lu: %s\n", pw->pw_name, 791 (unsigned long)pw->pw_gid, 792 pcap_strerror(errno)); 793 exit(1); 794 } 795 if (chroot_dir) { 796 setprotoent(1); 797 res_init(); 798 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) 799 error("Couldn't chroot/chdir to '%.64s': %s", 800 chroot_dir, pcap_strerror(errno)); 801 } 802#ifdef HAVE_LIBCAP_NG 803 { 804 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG); 805 if (ret < 0) 806 error("capng_change_id(): return %d\n", ret); 807 else 808 fprintf(stderr, "dropped privs to %s\n", username); 809 } 810#else 811 if (initgroups(pw->pw_name, pw->pw_gid) != 0 || 812 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) 813 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s", 814 username, 815 (unsigned long)pw->pw_uid, 816 (unsigned long)pw->pw_gid, 817 pcap_strerror(errno)); 818 else { 819// fprintf(stderr, "dropped privs to %s\n", username); 820 } 821#endif /* HAVE_LIBCAP_NG */ 822 } else 823 error("Couldn't find user '%.32s'", username); 824#ifdef HAVE_LIBCAP_NG 825 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */ 826DIAG_OFF_ASSIGN_ENUM 827 capng_updatev( 828 CAPNG_DROP, 829 CAPNG_EFFECTIVE | CAPNG_PERMITTED, 830 CAP_SETUID, 831 CAP_SETGID, 832 CAP_SYS_CHROOT, 833 -1); 834DIAG_ON_ASSIGN_ENUM 835 capng_apply(CAPNG_SELECT_BOTH); 836#endif /* HAVE_LIBCAP_NG */ 837 838} 839#endif /* _WIN32 */ 840 841static int 842getWflagChars(int x) 843{ 844 int c = 0; 845 846 x -= 1; 847 while (x > 0) { 848 c += 1; 849 x /= 10; 850 } 851 852 return c; 853} 854 855 856static void 857MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars) 858{ 859 char *filename = malloc(PATH_MAX + 1); 860 if (filename == NULL) 861 error("%s: malloc", __func__); 862 if (strlen(orig_name) == 0) 863 error("an empty string is not a valid file name"); 864 865 /* Process with strftime if Gflag is set. */ 866 if (Gflag != 0) { 867 struct tm *local_tm; 868 869 /* Convert Gflag_time to a usable format */ 870 if ((local_tm = localtime(&Gflag_time)) == NULL) { 871 error("%s: localtime", __func__); 872 } 873 874 /* There's no good way to detect an error in strftime since a return 875 * value of 0 isn't necessarily failure; if orig_name is an empty 876 * string, the formatted string will be empty. 877 * 878 * However, the C90 standard says that, if there *is* a 879 * buffer overflow, the content of the buffer is undefined, 880 * so we must check for a buffer overflow. 881 * 882 * So we check above for an empty orig_name, and only call 883 * strftime() if it's non-empty, in which case the return 884 * value will only be 0 if the formatted date doesn't fit 885 * in the buffer. 886 * 887 * (We check above because, even if we don't use -G, we 888 * want a better error message than "tcpdump: : No such 889 * file or directory" for this case.) 890 */ 891 if (strftime(filename, PATH_MAX, orig_name, local_tm) == 0) { 892 error("%s: strftime", __func__); 893 } 894 } else { 895 strncpy(filename, orig_name, PATH_MAX); 896 } 897 898 if (cnt == 0 && max_chars == 0) 899 strncpy(buffer, filename, PATH_MAX + 1); 900 else 901 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX) 902 /* Report an error if the filename is too large */ 903 error("too many output files or filename is too long (> %d)", PATH_MAX); 904 free(filename); 905} 906 907static char * 908get_next_file(FILE *VFile, char *ptr) 909{ 910 char *ret; 911 size_t len; 912 913 ret = fgets(ptr, PATH_MAX, VFile); 914 if (!ret) 915 return NULL; 916 917 len = strlen (ptr); 918 if (len > 0 && ptr[len - 1] == '\n') 919 ptr[len - 1] = '\0'; 920 921 return ret; 922} 923 924#ifdef HAVE_CASPER 925static cap_channel_t * 926capdns_setup(void) 927{ 928 cap_channel_t *capcas, *capdnsloc; 929 const char *types[1]; 930 int families[2]; 931 932 capcas = cap_init(); 933 if (capcas == NULL) 934 error("unable to create casper process"); 935 capdnsloc = cap_service_open(capcas, "system.dns"); 936 /* Casper capability no longer needed. */ 937 cap_close(capcas); 938 if (capdnsloc == NULL) 939 error("unable to open system.dns service"); 940 /* Limit system.dns to reverse DNS lookups. */ 941 types[0] = "ADDR"; 942 if (cap_dns_type_limit(capdnsloc, types, 1) < 0) 943 error("unable to limit access to system.dns service"); 944 families[0] = AF_INET; 945 families[1] = AF_INET6; 946 if (cap_dns_family_limit(capdnsloc, families, 2) < 0) 947 error("unable to limit access to system.dns service"); 948 949 return (capdnsloc); 950} 951#endif /* HAVE_CASPER */ 952 953#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION 954static int 955tstamp_precision_from_string(const char *precision) 956{ 957 if (strncmp(precision, "nano", strlen("nano")) == 0) 958 return PCAP_TSTAMP_PRECISION_NANO; 959 960 if (strncmp(precision, "micro", strlen("micro")) == 0) 961 return PCAP_TSTAMP_PRECISION_MICRO; 962 963 return -EINVAL; 964} 965 966static const char * 967tstamp_precision_to_string(int precision) 968{ 969 switch (precision) { 970 971 case PCAP_TSTAMP_PRECISION_MICRO: 972 return "micro"; 973 974 case PCAP_TSTAMP_PRECISION_NANO: 975 return "nano"; 976 977 default: 978 return "unknown"; 979 } 980} 981#endif 982 983#ifdef HAVE_CAPSICUM 984/* 985 * Ensure that, on a dump file's descriptor, we have all the rights 986 * necessary to make the standard I/O library work with an fdopen()ed 987 * FILE * from that descriptor. 988 * 989 * A long time ago in a galaxy far, far away, AT&T decided that, instead 990 * of providing separate APIs for getting and setting the FD_ flags on a 991 * descriptor, getting and setting the O_ flags on a descriptor, and 992 * locking files, they'd throw them all into a kitchen-sink fcntl() call 993 * along the lines of ioctl(), the fact that ioctl() operations are 994 * largely specific to particular character devices but fcntl() operations 995 * are either generic to all descriptors or generic to all descriptors for 996 * regular files nonwithstanding. 997 * 998 * The Capsicum people decided that fine-grained control of descriptor 999 * operations was required, so that you need to grant permission for 1000 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of 1001 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley 1002 * collection of things, so there are *individual* fcntls for which 1003 * permission needs to be granted. 1004 * 1005 * The FreeBSD standard I/O people implemented some optimizations that 1006 * requires that the standard I/O routines be able to determine whether 1007 * the descriptor for the FILE * is open append-only or not; as that 1008 * descriptor could have come from an open() rather than an fopen(), 1009 * that requires that it be able to do an F_GETFL fcntl() to read 1010 * the O_ flags. 1011 * 1012 * Tcpdump uses ftell() to determine how much data has been written 1013 * to a file in order to, when used with -C, determine when it's time 1014 * to rotate capture files. ftell() therefore needs to do an lseek() 1015 * to find out the file offset and must, thanks to the aforementioned 1016 * optimization, also know whether the descriptor is open append-only 1017 * or not. 1018 * 1019 * The net result of all the above is that we need to grant CAP_SEEK, 1020 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability. 1021 * 1022 * Perhaps this is the universe's way of saying that either 1023 * 1024 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call 1025 * using it, so that Capsicum-capable tcpdump wouldn't need to do 1026 * an fdopen() 1027 * 1028 * or 1029 * 1030 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard 1031 * I/O library that knows what rights are needed by the standard 1032 * I/O library, based on the open mode, and assigns them, perhaps 1033 * with an additional argument indicating, for example, whether 1034 * seeking should be allowed, so that tcpdump doesn't need to know 1035 * what the standard I/O library happens to require this week. 1036 */ 1037static void 1038set_dumper_capsicum_rights(pcap_dumper_t *p) 1039{ 1040 int fd = fileno(pcap_dump_file(p)); 1041 cap_rights_t rights; 1042 1043 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL); 1044 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) { 1045 error("unable to limit dump descriptor"); 1046 } 1047 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) { 1048 error("unable to limit dump descriptor fcntls"); 1049 } 1050} 1051#endif 1052 1053/* 1054 * Copy arg vector into a new buffer, concatenating arguments with spaces. 1055 */ 1056static char * 1057copy_argv(char **argv) 1058{ 1059 char **p; 1060 size_t len = 0; 1061 char *buf; 1062 char *src, *dst; 1063 1064 p = argv; 1065 if (*p == NULL) 1066 return 0; 1067 1068 while (*p) 1069 len += strlen(*p++) + 1; 1070 1071 buf = (char *)malloc(len); 1072 if (buf == NULL) 1073 error("%s: malloc", __func__); 1074 1075 p = argv; 1076 dst = buf; 1077 while ((src = *p++) != NULL) { 1078 while ((*dst++ = *src++) != '\0') 1079 ; 1080 dst[-1] = ' '; 1081 } 1082 dst[-1] = '\0'; 1083 1084 return buf; 1085} 1086 1087/* 1088 * On Windows, we need to open the file in binary mode, so that 1089 * we get all the bytes specified by the size we get from "fstat()". 1090 * On UNIX, that's not necessary. O_BINARY is defined on Windows; 1091 * we define it as 0 if it's not defined, so it does nothing. 1092 */ 1093#ifndef O_BINARY 1094#define O_BINARY 0 1095#endif 1096 1097static char * 1098read_infile(char *fname) 1099{ 1100 int i, fd; 1101 ssize_t cc; 1102 char *cp; 1103 our_statb buf; 1104 1105 fd = open(fname, O_RDONLY|O_BINARY); 1106 if (fd < 0) 1107 error("can't open %s: %s", fname, pcap_strerror(errno)); 1108 1109 if (our_fstat(fd, &buf) < 0) 1110 error("can't stat %s: %s", fname, pcap_strerror(errno)); 1111 1112 /* 1113 * Reject files whose size doesn't fit into an int; a filter 1114 * *that* large will probably be too big. 1115 */ 1116 if (buf.st_size > INT_MAX) 1117 error("%s is too large", fname); 1118 1119 cp = malloc((u_int)buf.st_size + 1); 1120 if (cp == NULL) 1121 error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1, 1122 fname, pcap_strerror(errno)); 1123 cc = read(fd, cp, (u_int)buf.st_size); 1124 if (cc < 0) 1125 error("read %s: %s", fname, pcap_strerror(errno)); 1126 if (cc != buf.st_size) 1127 error("short read %s (%d != %d)", fname, (int) cc, 1128 (int)buf.st_size); 1129 1130 close(fd); 1131 /* replace "# comment" with spaces */ 1132 for (i = 0; i < cc; i++) { 1133 if (cp[i] == '#') 1134 while (i < cc && cp[i] != '\n') 1135 cp[i++] = ' '; 1136 } 1137 cp[cc] = '\0'; 1138 return (cp); 1139} 1140 1141#ifdef HAVE_PCAP_FINDALLDEVS 1142static long 1143parse_interface_number(const char *device) 1144{ 1145 const char *p; 1146 long devnum; 1147 char *end; 1148 1149 /* 1150 * Search for a colon, terminating any scheme at the beginning 1151 * of the device. 1152 */ 1153 p = strchr(device, ':'); 1154 if (p != NULL) { 1155 /* 1156 * We found it. Is it followed by "//"? 1157 */ 1158 p++; /* skip the : */ 1159 if (strncmp(p, "//", 2) == 0) { 1160 /* 1161 * Yes. Search for the next /, at the end of the 1162 * authority part of the URL. 1163 */ 1164 p += 2; /* skip the // */ 1165 p = strchr(p, '/'); 1166 if (p != NULL) { 1167 /* 1168 * OK, past the / is the path. 1169 */ 1170 device = p + 1; 1171 } 1172 } 1173 } 1174 devnum = strtol(device, &end, 10); 1175 if (device != end && *end == '\0') { 1176 /* 1177 * It's all-numeric, but is it a valid number? 1178 */ 1179 if (devnum <= 0) { 1180 /* 1181 * No, it's not an ordinal. 1182 */ 1183 error("Invalid adapter index"); 1184 } 1185 return (devnum); 1186 } else { 1187 /* 1188 * It's not all-numeric; return -1, so our caller 1189 * knows that. 1190 */ 1191 return (-1); 1192 } 1193} 1194 1195static char * 1196find_interface_by_number(const char *url 1197#ifndef HAVE_PCAP_FINDALLDEVS_EX 1198_U_ 1199#endif 1200, long devnum) 1201{ 1202 pcap_if_t *dev, *devlist; 1203 long i; 1204 char ebuf[PCAP_ERRBUF_SIZE]; 1205 char *device; 1206#ifdef HAVE_PCAP_FINDALLDEVS_EX 1207 const char *endp; 1208 char *host_url; 1209#endif 1210 int status; 1211 1212#ifdef HAVE_PCAP_FINDALLDEVS_EX 1213 /* 1214 * Search for a colon, terminating any scheme at the beginning 1215 * of the URL. 1216 */ 1217 endp = strchr(url, ':'); 1218 if (endp != NULL) { 1219 /* 1220 * We found it. Is it followed by "//"? 1221 */ 1222 endp++; /* skip the : */ 1223 if (strncmp(endp, "//", 2) == 0) { 1224 /* 1225 * Yes. Search for the next /, at the end of the 1226 * authority part of the URL. 1227 */ 1228 endp += 2; /* skip the // */ 1229 endp = strchr(endp, '/'); 1230 } else 1231 endp = NULL; 1232 } 1233 if (endp != NULL) { 1234 /* 1235 * OK, everything from device to endp is a URL to hand 1236 * to pcap_findalldevs_ex(). 1237 */ 1238 endp++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */ 1239 host_url = malloc(endp - url + 1); 1240 if (host_url == NULL && (endp - url + 1) > 0) 1241 error("Invalid allocation for host"); 1242 1243 memcpy(host_url, url, endp - url); 1244 host_url[endp - url] = '\0'; 1245 status = pcap_findalldevs_ex(host_url, NULL, &devlist, ebuf); 1246 free(host_url); 1247 } else 1248#endif 1249 status = pcap_findalldevs(&devlist, ebuf); 1250 if (status < 0) 1251 error("%s", ebuf); 1252 /* 1253 * Look for the devnum-th entry in the list of devices (1-based). 1254 */ 1255 for (i = 0, dev = devlist; i < devnum-1 && dev != NULL; 1256 i++, dev = dev->next) 1257 ; 1258 if (dev == NULL) 1259 error("Invalid adapter index"); 1260 device = strdup(dev->name); 1261 pcap_freealldevs(devlist); 1262 return (device); 1263} 1264#endif 1265 1266#ifdef HAVE_PCAP_OPEN 1267/* 1268 * Prefixes for rpcap URLs. 1269 */ 1270static char rpcap_prefix[] = "rpcap://"; 1271static char rpcap_ssl_prefix[] = "rpcaps://"; 1272#endif 1273 1274static pcap_t * 1275open_interface(const char *device, netdissect_options *ndo, char *ebuf) 1276{ 1277 pcap_t *pc; 1278#ifdef HAVE_PCAP_CREATE 1279 int status; 1280 char *cp; 1281#endif 1282 1283#ifdef HAVE_PCAP_OPEN 1284 /* 1285 * Is this an rpcap URL? 1286 */ 1287 if (strncmp(device, rpcap_prefix, sizeof(rpcap_prefix) - 1) == 0 || 1288 strncmp(device, rpcap_ssl_prefix, sizeof(rpcap_ssl_prefix) - 1) == 0) { 1289 /* 1290 * Yes. Open it with pcap_open(). 1291 */ 1292 *ebuf = '\0'; 1293 pc = pcap_open(device, ndo->ndo_snaplen, 1294 pflag ? 0 : PCAP_OPENFLAG_PROMISCUOUS, timeout, NULL, 1295 ebuf); 1296 if (pc == NULL) { 1297 /* 1298 * If this failed with "No such device" or "The system 1299 * cannot find the device specified", that means 1300 * the interface doesn't exist; return NULL, so that 1301 * the caller can see whether the device name is 1302 * actually an interface index. 1303 */ 1304 if (strstr(ebuf, "No such device") != NULL || 1305 strstr(ebuf, "The system cannot find the device specified") != NULL) 1306 return (NULL); 1307 error("%s", ebuf); 1308 } 1309 if (*ebuf) 1310 warning("%s", ebuf); 1311 return (pc); 1312 } 1313#endif /* HAVE_PCAP_OPEN */ 1314 1315#ifdef HAVE_PCAP_CREATE 1316 pc = pcap_create(device, ebuf); 1317 if (pc == NULL) { 1318 /* 1319 * If this failed with "No such device", that means 1320 * the interface doesn't exist; return NULL, so that 1321 * the caller can see whether the device name is 1322 * actually an interface index. 1323 */ 1324 if (strstr(ebuf, "No such device") != NULL) 1325 return (NULL); 1326 error("%s", ebuf); 1327 } 1328#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 1329 if (Jflag) 1330 show_tstamp_types_and_exit(pc, device); 1331#endif 1332#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION 1333 status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision); 1334 if (status != 0) 1335 error("%s: Can't set %ssecond time stamp precision: %s", 1336 device, 1337 tstamp_precision_to_string(ndo->ndo_tstamp_precision), 1338 pcap_statustostr(status)); 1339#endif 1340 1341#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE 1342 if (immediate_mode) { 1343 status = pcap_set_immediate_mode(pc, 1); 1344 if (status != 0) 1345 error("%s: Can't set immediate mode: %s", 1346 device, pcap_statustostr(status)); 1347 } 1348#endif 1349 /* 1350 * Is this an interface that supports monitor mode? 1351 */ 1352 if (pcap_can_set_rfmon(pc) == 1) 1353 supports_monitor_mode = 1; 1354 else 1355 supports_monitor_mode = 0; 1356 if (ndo->ndo_snaplen != 0) { 1357 /* 1358 * A snapshot length was explicitly specified; 1359 * use it. 1360 */ 1361 status = pcap_set_snaplen(pc, ndo->ndo_snaplen); 1362 if (status != 0) 1363 error("%s: Can't set snapshot length: %s", 1364 device, pcap_statustostr(status)); 1365 } 1366 status = pcap_set_promisc(pc, !pflag); 1367 if (status != 0) 1368 error("%s: Can't set promiscuous mode: %s", 1369 device, pcap_statustostr(status)); 1370 if (Iflag) { 1371 status = pcap_set_rfmon(pc, 1); 1372 if (status != 0) 1373 error("%s: Can't set monitor mode: %s", 1374 device, pcap_statustostr(status)); 1375 } 1376 status = pcap_set_timeout(pc, timeout); 1377 if (status != 0) 1378 error("%s: pcap_set_timeout failed: %s", 1379 device, pcap_statustostr(status)); 1380 if (Bflag != 0) { 1381 status = pcap_set_buffer_size(pc, Bflag); 1382 if (status != 0) 1383 error("%s: Can't set buffer size: %s", 1384 device, pcap_statustostr(status)); 1385 } 1386#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 1387 if (jflag != -1) { 1388 status = pcap_set_tstamp_type(pc, jflag); 1389 if (status < 0) 1390 error("%s: Can't set time stamp type: %s", 1391 device, pcap_statustostr(status)); 1392 else if (status > 0) 1393 warning("When trying to set timestamp type '%s' on %s: %s", 1394 pcap_tstamp_type_val_to_name(jflag), device, 1395 pcap_statustostr(status)); 1396 } 1397#endif 1398 status = pcap_activate(pc); 1399 if (status < 0) { 1400 /* 1401 * pcap_activate() failed. 1402 */ 1403 cp = pcap_geterr(pc); 1404 if (status == PCAP_ERROR) 1405 error("%s", cp); 1406 else if (status == PCAP_ERROR_NO_SUCH_DEVICE) { 1407 /* 1408 * Return an error for our caller to handle. 1409 */ 1410 snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)", 1411 device, pcap_statustostr(status), cp); 1412 } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0') 1413 error("%s: %s\n(%s)", device, 1414 pcap_statustostr(status), cp); 1415#ifdef __FreeBSD__ 1416 else if (status == PCAP_ERROR_RFMON_NOTSUP && 1417 strncmp(device, "wlan", 4) == 0) { 1418 char parent[8], newdev[8]; 1419 char sysctl[32]; 1420 size_t s = sizeof(parent); 1421 1422 snprintf(sysctl, sizeof(sysctl), 1423 "net.wlan.%d.%%parent", atoi(device + 4)); 1424 sysctlbyname(sysctl, parent, &s, NULL, 0); 1425 strlcpy(newdev, device, sizeof(newdev)); 1426 /* Suggest a new wlan device. */ 1427 /* FIXME: incrementing the index this way is not going to work well 1428 * when the index is 9 or greater but the only consequence in this 1429 * specific case would be an error message that looks a bit odd. 1430 */ 1431 newdev[strlen(newdev)-1]++; 1432 error("%s is not a monitor mode VAP\n" 1433 "To create a new monitor mode VAP use:\n" 1434 " ifconfig %s create wlandev %s wlanmode monitor\n" 1435 "and use %s as the tcpdump interface", 1436 device, newdev, parent, newdev); 1437 } 1438#endif 1439 else 1440 error("%s: %s", device, 1441 pcap_statustostr(status)); 1442 pcap_close(pc); 1443 return (NULL); 1444 } else if (status > 0) { 1445 /* 1446 * pcap_activate() succeeded, but it's warning us 1447 * of a problem it had. 1448 */ 1449 cp = pcap_geterr(pc); 1450 if (status == PCAP_WARNING) 1451 warning("%s", cp); 1452 else if (status == PCAP_WARNING_PROMISC_NOTSUP && 1453 *cp != '\0') 1454 warning("%s: %s\n(%s)", device, 1455 pcap_statustostr(status), cp); 1456 else 1457 warning("%s: %s", device, 1458 pcap_statustostr(status)); 1459 } 1460#ifdef HAVE_PCAP_SETDIRECTION 1461 if (Qflag != -1) { 1462 status = pcap_setdirection(pc, Qflag); 1463 if (status != 0) 1464 error("%s: pcap_setdirection() failed: %s", 1465 device, pcap_geterr(pc)); 1466 } 1467#endif /* HAVE_PCAP_SETDIRECTION */ 1468#else /* HAVE_PCAP_CREATE */ 1469 *ebuf = '\0'; 1470 /* 1471 * If no snapshot length was specified, or a length of 0 was 1472 * specified, default to 256KB. 1473 */ 1474 if (ndo->ndo_snaplen == 0) 1475 ndo->ndo_snaplen = MAXIMUM_SNAPLEN; 1476 pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, timeout, ebuf); 1477 if (pc == NULL) { 1478 /* 1479 * If this failed with "No such device", that means 1480 * the interface doesn't exist; return NULL, so that 1481 * the caller can see whether the device name is 1482 * actually an interface index. 1483 */ 1484 if (strstr(ebuf, "No such device") != NULL) 1485 return (NULL); 1486 error("%s", ebuf); 1487 } 1488 if (*ebuf) 1489 warning("%s", ebuf); 1490#endif /* HAVE_PCAP_CREATE */ 1491 1492 return (pc); 1493} 1494 1495int 1496main(int argc, char **argv) 1497{ 1498 int cnt, op, i; 1499 bpf_u_int32 localnet = 0, netmask = 0; 1500 char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName; 1501 char *endp; 1502 pcap_handler callback; 1503 int dlt; 1504 const char *dlt_name; 1505 struct bpf_program fcode; 1506#ifndef _WIN32 1507 void (*oldhandler)(int); 1508#endif 1509 struct dump_info dumpinfo; 1510 u_char *pcap_userdata; 1511 char ebuf[PCAP_ERRBUF_SIZE]; 1512 char VFileLine[PATH_MAX + 1]; 1513 const char *username = NULL; 1514#ifndef _WIN32 1515 const char *chroot_dir = NULL; 1516#endif 1517 char *ret = NULL; 1518 char *end; 1519#ifdef HAVE_PCAP_FINDALLDEVS 1520 pcap_if_t *devlist; 1521 long devnum; 1522#endif 1523 int status; 1524 FILE *VFile; 1525#ifdef HAVE_CAPSICUM 1526 cap_rights_t rights; 1527 int cansandbox; 1528#endif /* HAVE_CAPSICUM */ 1529 int Oflag = 1; /* run filter code optimizer */ 1530 int yflag_dlt = -1; 1531 const char *yflag_dlt_name = NULL; 1532 int print = 0; 1533 1534 netdissect_options Ndo; 1535 netdissect_options *ndo = &Ndo; 1536 1537 /* 1538 * Initialize the netdissect code. 1539 */ 1540 if (nd_init(ebuf, sizeof(ebuf)) == -1) 1541 error("%s", ebuf); 1542 1543 memset(ndo, 0, sizeof(*ndo)); 1544 ndo_set_function_pointers(ndo); 1545 1546 cnt = -1; 1547 device = NULL; 1548 infile = NULL; 1549 RFileName = NULL; 1550 VFileName = NULL; 1551 VFile = NULL; 1552 WFileName = NULL; 1553 dlt = -1; 1554 if ((cp = strrchr(argv[0], PATH_SEPARATOR)) != NULL) 1555 ndo->program_name = program_name = cp + 1; 1556 else 1557 ndo->program_name = program_name = argv[0]; 1558 1559#if defined(HAVE_PCAP_WSOCKINIT) 1560 if (pcap_wsockinit() != 0) 1561 error("Attempting to initialize Winsock failed"); 1562#elif defined(HAVE_WSOCKINIT) 1563 if (wsockinit() != 0) 1564 error("Attempting to initialize Winsock failed"); 1565#endif 1566 1567 /* 1568 * On platforms where the CPU doesn't support unaligned loads, 1569 * force unaligned accesses to abort with SIGBUS, rather than 1570 * being fixed up (slowly) by the OS kernel; on those platforms, 1571 * misaligned accesses are bugs, and we want tcpdump to crash so 1572 * that the bugs are reported. 1573 */ 1574 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0) 1575 error("%s", ebuf); 1576 1577 while ( 1578 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1) 1579 switch (op) { 1580 1581 case 'a': 1582 /* compatibility for old -a */ 1583 break; 1584 1585 case 'A': 1586 ++ndo->ndo_Aflag; 1587 break; 1588 1589 case 'b': 1590 ++ndo->ndo_bflag; 1591 break; 1592 1593#if defined(HAVE_PCAP_CREATE) || defined(_WIN32) 1594 case 'B': 1595 Bflag = atoi(optarg)*1024; 1596 if (Bflag <= 0) 1597 error("invalid packet buffer size %s", optarg); 1598 break; 1599#endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ 1600 1601 case 'c': 1602 cnt = atoi(optarg); 1603 if (cnt <= 0) 1604 error("invalid packet count %s", optarg); 1605 break; 1606 1607 case 'C': 1608 errno = 0; 1609#ifdef HAVE_PCAP_DUMP_FTELL64 1610 Cflag = strtoint64_t(optarg, &endp, 10); 1611#else 1612 Cflag = strtol(optarg, &endp, 10); 1613#endif 1614 if (endp == optarg || *endp != '\0' || errno != 0 1615 || Cflag <= 0) 1616 error("invalid file size %s", optarg); 1617 /* 1618 * Will multiplying it by 1000000 overflow? 1619 */ 1620#ifdef HAVE_PCAP_DUMP_FTELL64 1621 if (Cflag > INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000) 1622#else 1623 if (Cflag > LONG_MAX / 1000000) 1624#endif 1625 error("file size %s is too large", optarg); 1626 Cflag *= 1000000; 1627 break; 1628 1629 case 'd': 1630 ++dflag; 1631 break; 1632 1633#ifdef HAVE_PCAP_FINDALLDEVS 1634 case 'D': 1635 Dflag++; 1636 break; 1637#endif 1638 1639#ifdef HAVE_PCAP_FINDALLDEVS_EX 1640 case OPTION_LIST_REMOTE_INTERFACES: 1641 remote_interfaces_source = optarg; 1642 break; 1643#endif 1644 1645 case 'L': 1646 Lflag++; 1647 break; 1648 1649 case 'e': 1650 ++ndo->ndo_eflag; 1651 break; 1652 1653 case 'E': 1654#ifndef HAVE_LIBCRYPTO 1655 warning("crypto code not compiled in"); 1656#endif 1657 ndo->ndo_espsecret = optarg; 1658 break; 1659 1660 case 'f': 1661 ++ndo->ndo_fflag; 1662 break; 1663 1664 case 'F': 1665 infile = optarg; 1666 break; 1667 1668 case 'G': 1669 Gflag = atoi(optarg); 1670 if (Gflag < 0) 1671 error("invalid number of seconds %s", optarg); 1672 1673 /* We will create one file initially. */ 1674 Gflag_count = 0; 1675 1676 /* Grab the current time for rotation use. */ 1677 if ((Gflag_time = time(NULL)) == (time_t)-1) { 1678 error("%s: can't get current time: %s", 1679 __func__, pcap_strerror(errno)); 1680 } 1681 break; 1682 1683 case 'h': 1684 print_usage(stdout); 1685 exit_tcpdump(S_SUCCESS); 1686 break; 1687 1688 case 'H': 1689 ++ndo->ndo_Hflag; 1690 break; 1691 1692 case 'i': 1693 device = optarg; 1694 break; 1695 1696#ifdef HAVE_PCAP_CREATE 1697 case 'I': 1698 ++Iflag; 1699 break; 1700#endif /* HAVE_PCAP_CREATE */ 1701 1702#ifdef HAVE_PCAP_SET_TSTAMP_TYPE 1703 case 'j': 1704 jflag = pcap_tstamp_type_name_to_val(optarg); 1705 if (jflag < 0) 1706 error("invalid time stamp type %s", optarg); 1707 break; 1708 1709 case 'J': 1710 Jflag++; 1711 break; 1712#endif 1713 1714 case 'l': 1715#ifdef _WIN32 1716 /* 1717 * _IOLBF is the same as _IOFBF in Microsoft's C 1718 * libraries; the only alternative they offer 1719 * is _IONBF. 1720 * 1721 * XXX - this should really be checking for MSVC++, 1722 * not _WIN32, if, for example, MinGW has its own 1723 * C library that is more UNIX-compatible. 1724 */ 1725 setvbuf(stdout, NULL, _IONBF, 0); 1726#else /* _WIN32 */ 1727#ifdef HAVE_SETLINEBUF 1728 setlinebuf(stdout); 1729#else 1730 setvbuf(stdout, NULL, _IOLBF, 0); 1731#endif 1732#endif /* _WIN32 */ 1733 lflag = 1; 1734 break; 1735 1736 case 'K': 1737 ++ndo->ndo_Kflag; 1738 break; 1739 1740 case 'm': 1741 if (nd_have_smi_support()) { 1742 if (nd_load_smi_module(optarg, ebuf, sizeof(ebuf)) == -1) 1743 error("%s", ebuf); 1744 } else { 1745 (void)fprintf(stderr, "%s: ignoring option `-m %s' ", 1746 program_name, optarg); 1747 (void)fprintf(stderr, "(no libsmi support)\n"); 1748 } 1749 break; 1750 1751 case 'M': 1752 /* TCP-MD5 shared secret */ 1753#ifndef HAVE_LIBCRYPTO 1754 warning("crypto code not compiled in"); 1755#endif 1756 ndo->ndo_sigsecret = optarg; 1757 break; 1758 1759 case 'n': 1760 ++ndo->ndo_nflag; 1761 break; 1762 1763 case 'N': 1764 ++ndo->ndo_Nflag; 1765 break; 1766 1767 case 'O': 1768 Oflag = 0; 1769 break; 1770 1771 case 'p': 1772 ++pflag; 1773 break; 1774 1775 case 'q': 1776 ++ndo->ndo_qflag; 1777 ++ndo->ndo_suppress_default_print; 1778 break; 1779 1780#ifdef HAVE_PCAP_SETDIRECTION 1781 case 'Q': 1782 if (ascii_strcasecmp(optarg, "in") == 0) 1783 Qflag = PCAP_D_IN; 1784 else if (ascii_strcasecmp(optarg, "out") == 0) 1785 Qflag = PCAP_D_OUT; 1786 else if (ascii_strcasecmp(optarg, "inout") == 0) 1787 Qflag = PCAP_D_INOUT; 1788 else 1789 error("unknown capture direction `%s'", optarg); 1790 break; 1791#endif /* HAVE_PCAP_SETDIRECTION */ 1792 1793 case 'r': 1794 RFileName = optarg; 1795 break; 1796 1797 case 's': 1798 ndo->ndo_snaplen = (int)strtol(optarg, &end, 0); 1799 if (optarg == end || *end != '\0' 1800 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN) 1801 error("invalid snaplen %s (must be >= 0 and <= %d)", 1802 optarg, MAXIMUM_SNAPLEN); 1803 break; 1804 1805 case 'S': 1806 ++ndo->ndo_Sflag; 1807 break; 1808 1809 case 't': 1810 ++ndo->ndo_tflag; 1811 break; 1812 1813 case 'T': 1814 if (ascii_strcasecmp(optarg, "vat") == 0) 1815 ndo->ndo_packettype = PT_VAT; 1816 else if (ascii_strcasecmp(optarg, "wb") == 0) 1817 ndo->ndo_packettype = PT_WB; 1818 else if (ascii_strcasecmp(optarg, "rpc") == 0) 1819 ndo->ndo_packettype = PT_RPC; 1820 else if (ascii_strcasecmp(optarg, "rtp") == 0) 1821 ndo->ndo_packettype = PT_RTP; 1822 else if (ascii_strcasecmp(optarg, "rtcp") == 0) 1823 ndo->ndo_packettype = PT_RTCP; 1824 else if (ascii_strcasecmp(optarg, "snmp") == 0) 1825 ndo->ndo_packettype = PT_SNMP; 1826 else if (ascii_strcasecmp(optarg, "cnfp") == 0) 1827 ndo->ndo_packettype = PT_CNFP; 1828 else if (ascii_strcasecmp(optarg, "tftp") == 0) 1829 ndo->ndo_packettype = PT_TFTP; 1830 else if (ascii_strcasecmp(optarg, "aodv") == 0) 1831 ndo->ndo_packettype = PT_AODV; 1832 else if (ascii_strcasecmp(optarg, "carp") == 0) 1833 ndo->ndo_packettype = PT_CARP; 1834 else if (ascii_strcasecmp(optarg, "radius") == 0) 1835 ndo->ndo_packettype = PT_RADIUS; 1836 else if (ascii_strcasecmp(optarg, "zmtp1") == 0) 1837 ndo->ndo_packettype = PT_ZMTP1; 1838 else if (ascii_strcasecmp(optarg, "vxlan") == 0) 1839 ndo->ndo_packettype = PT_VXLAN; 1840 else if (ascii_strcasecmp(optarg, "pgm") == 0) 1841 ndo->ndo_packettype = PT_PGM; 1842 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0) 1843 ndo->ndo_packettype = PT_PGM_ZMTP1; 1844 else if (ascii_strcasecmp(optarg, "lmp") == 0) 1845 ndo->ndo_packettype = PT_LMP; 1846 else if (ascii_strcasecmp(optarg, "resp") == 0) 1847 ndo->ndo_packettype = PT_RESP; 1848 else if (ascii_strcasecmp(optarg, "ptp") == 0) 1849 ndo->ndo_packettype = PT_PTP; 1850 else if (ascii_strcasecmp(optarg, "someip") == 0) 1851 ndo->ndo_packettype = PT_SOMEIP; 1852 else if (ascii_strcasecmp(optarg, "domain") == 0) 1853 ndo->ndo_packettype = PT_DOMAIN; 1854 else 1855 error("unknown packet type `%s'", optarg); 1856 break; 1857 1858 case 'u': 1859 ++ndo->ndo_uflag; 1860 break; 1861 1862#ifdef HAVE_PCAP_DUMP_FLUSH 1863 case 'U': 1864 ++Uflag; 1865 break; 1866#endif 1867 1868 case 'v': 1869 ++ndo->ndo_vflag; 1870 break; 1871 1872 case 'V': 1873 VFileName = optarg; 1874 break; 1875 1876 case 'w': 1877 WFileName = optarg; 1878 break; 1879 1880 case 'W': 1881 Wflag = atoi(optarg); 1882 if (Wflag <= 0) 1883 error("invalid number of output files %s", optarg); 1884 WflagChars = getWflagChars(Wflag); 1885 break; 1886 1887 case 'x': 1888 ++ndo->ndo_xflag; 1889 ++ndo->ndo_suppress_default_print; 1890 break; 1891 1892 case 'X': 1893 ++ndo->ndo_Xflag; 1894 ++ndo->ndo_suppress_default_print; 1895 break; 1896 1897 case 'y': 1898 yflag_dlt_name = optarg; 1899 yflag_dlt = 1900 pcap_datalink_name_to_val(yflag_dlt_name); 1901 if (yflag_dlt < 0) 1902 error("invalid data link type %s", yflag_dlt_name); 1903 break; 1904 1905#ifdef HAVE_PCAP_SET_PARSER_DEBUG 1906 case 'Y': 1907 { 1908 /* Undocumented flag */ 1909 pcap_set_parser_debug(1); 1910 } 1911 break; 1912#endif 1913 case 'z': 1914 zflag = optarg; 1915 break; 1916 1917 case 'Z': 1918 username = optarg; 1919 break; 1920 1921 case '#': 1922 ndo->ndo_packet_number = 1; 1923 break; 1924 1925 case OPTION_VERSION: 1926 print_version(stdout); 1927 exit_tcpdump(S_SUCCESS); 1928 break; 1929 1930#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION 1931 case OPTION_TSTAMP_PRECISION: 1932 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg); 1933 if (ndo->ndo_tstamp_precision < 0) 1934 error("unsupported time stamp precision"); 1935 break; 1936#endif 1937 1938#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE 1939 case OPTION_IMMEDIATE_MODE: 1940 immediate_mode = 1; 1941 break; 1942#endif 1943 1944 case OPTION_PRINT: 1945 print = 1; 1946 break; 1947 1948#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION 1949 case OPTION_TSTAMP_MICRO: 1950 ndo->ndo_tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO; 1951 break; 1952 1953 case OPTION_TSTAMP_NANO: 1954 ndo->ndo_tstamp_precision = PCAP_TSTAMP_PRECISION_NANO; 1955 break; 1956#endif 1957 1958 case OPTION_FP_TYPE: 1959 /* 1960 * Print out the type of floating-point arithmetic 1961 * we're doing; it's probably IEEE, unless somebody 1962 * tries to run this on a VAX, but the precision 1963 * may differ (e.g., it might be 32-bit, 64-bit, 1964 * or 80-bit). 1965 */ 1966 float_type_check(0x4e93312d); 1967 return 0; 1968 1969 case OPTION_COUNT: 1970 count_mode = 1; 1971 break; 1972 1973 default: 1974 print_usage(stderr); 1975 exit_tcpdump(S_ERR_HOST_PROGRAM); 1976 /* NOTREACHED */ 1977 } 1978 1979#ifdef HAVE_PCAP_FINDALLDEVS 1980 if (Dflag) 1981 show_devices_and_exit(); 1982#endif 1983#ifdef HAVE_PCAP_FINDALLDEVS_EX 1984 if (remote_interfaces_source != NULL) 1985 show_remote_devices_and_exit(); 1986#endif 1987 1988#if defined(DLT_LINUX_SLL2) && defined(HAVE_PCAP_SET_DATALINK) 1989/* Set default linktype DLT_LINUX_SLL2 when capturing on the "any" device */ 1990 if (device != NULL && 1991 strncmp (device, "any", strlen("any")) == 0 1992 && yflag_dlt == -1) 1993 yflag_dlt = DLT_LINUX_SLL2; 1994#endif 1995 1996 switch (ndo->ndo_tflag) { 1997 1998 case 0: /* Default */ 1999 case 1: /* No time stamp */ 2000 case 2: /* Unix timeval style */ 2001 case 3: /* Microseconds/nanoseconds since previous packet */ 2002 case 4: /* Date + Default */ 2003 case 5: /* Microseconds/nanoseconds since first packet */ 2004 break; 2005 2006 default: /* Not supported */ 2007 error("only -t, -tt, -ttt, -tttt and -ttttt are supported"); 2008 break; 2009 } 2010 2011 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL)) 2012 error("-f can not be used with -V or -r"); 2013 2014 if (VFileName != NULL && RFileName != NULL) 2015 error("-V and -r are mutually exclusive."); 2016 2017 /* 2018 * If we're printing dissected packets to the standard output, 2019 * and either the standard output is a terminal or we're doing 2020 * "line" buffering, set the capture timeout to .1 second rather 2021 * than 1 second, as the user's probably expecting to see packets 2022 * pop up immediately shortly after they arrive. 2023 * 2024 * XXX - would there be some value appropriate for all cases, 2025 * based on, say, the buffer size and packet input rate? 2026 */ 2027 if ((WFileName == NULL || print) && (isatty(1) || lflag)) 2028 timeout = 100; 2029 2030#ifdef WITH_CHROOT 2031 /* if run as root, prepare for chrooting */ 2032 if (getuid() == 0 || geteuid() == 0) { 2033 /* future extensibility for cmd-line arguments */ 2034 if (!chroot_dir) 2035 chroot_dir = WITH_CHROOT; 2036 } 2037#endif 2038 2039#ifdef WITH_USER 2040 /* if run as root, prepare for dropping root privileges */ 2041 if (getuid() == 0 || geteuid() == 0) { 2042 /* Run with '-Z root' to restore old behaviour */ 2043 if (!username) 2044 username = WITH_USER; 2045 } 2046#endif 2047 2048 if (RFileName != NULL || VFileName != NULL) { 2049 /* 2050 * If RFileName is non-null, it's the pathname of a 2051 * savefile to read. If VFileName is non-null, it's 2052 * the pathname of a file containing a list of pathnames 2053 * (one per line) of savefiles to read. 2054 * 2055 * In either case, we're reading a savefile, not doing 2056 * a live capture. 2057 */ 2058#ifndef _WIN32 2059 /* 2060 * We don't need network access, so relinquish any set-UID 2061 * or set-GID privileges we have (if any). 2062 * 2063 * We do *not* want set-UID privileges when opening a 2064 * trace file, as that might let the user read other 2065 * people's trace files (especially if we're set-UID 2066 * root). 2067 */ 2068 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 ) 2069 fprintf(stderr, "Warning: setgid/setuid failed !\n"); 2070#endif /* _WIN32 */ 2071 if (VFileName != NULL) { 2072 if (VFileName[0] == '-' && VFileName[1] == '\0') 2073 VFile = stdin; 2074 else 2075 VFile = fopen(VFileName, "r"); 2076 2077 if (VFile == NULL) 2078 error("Unable to open file: %s\n", pcap_strerror(errno)); 2079 2080 ret = get_next_file(VFile, VFileLine); 2081 if (!ret) 2082 error("Nothing in %s\n", VFileName); 2083 RFileName = VFileLine; 2084 } 2085 2086#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION 2087 pd = pcap_open_offline_with_tstamp_precision(RFileName, 2088 ndo->ndo_tstamp_precision, ebuf); 2089#else 2090 pd = pcap_open_offline(RFileName, ebuf); 2091#endif 2092 2093 if (pd == NULL) 2094 error("%s", ebuf); 2095#ifdef HAVE_CAPSICUM 2096 cap_rights_init(&rights, CAP_READ); 2097 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 && 2098 errno != ENOSYS) { 2099 error("unable to limit pcap descriptor"); 2100 } 2101#endif 2102 dlt = pcap_datalink(pd); 2103 dlt_name = pcap_datalink_val_to_name(dlt); 2104 fprintf(stderr, "reading from file %s", RFileName); 2105 if (dlt_name == NULL) { 2106 fprintf(stderr, ", link-type %u", dlt); 2107 } else { 2108 fprintf(stderr, ", link-type %s (%s)", dlt_name, 2109 pcap_datalink_val_to_description(dlt)); 2110 } 2111 fprintf(stderr, ", snapshot length %d\n", pcap_snapshot(pd)); 2112#ifdef DLT_LINUX_SLL2 2113 if (dlt == DLT_LINUX_SLL2) 2114 fprintf(stderr, "Warning: interface names might be incorrect\n"); 2115#endif 2116 } else if (dflag && !device) { 2117 int dump_dlt = DLT_EN10MB; 2118 /* 2119 * We're dumping the compiled code without an explicit 2120 * device specification. (If a device is specified, we 2121 * definitely want to open it to use the DLT of that device.) 2122 * Either default to DLT_EN10MB with a warning, or use 2123 * the user-specified value if supplied. 2124 */ 2125 /* 2126 * If no snapshot length was specified, or a length of 0 was 2127 * specified, default to 256KB. 2128 */ 2129 if (ndo->ndo_snaplen == 0) 2130 ndo->ndo_snaplen = MAXIMUM_SNAPLEN; 2131 /* 2132 * If a DLT was specified with the -y flag, use that instead. 2133 */ 2134 if (yflag_dlt != -1) 2135 dump_dlt = yflag_dlt; 2136 else 2137 fprintf(stderr, "Warning: assuming Ethernet\n"); 2138 pd = pcap_open_dead(dump_dlt, ndo->ndo_snaplen); 2139 } else { 2140 /* 2141 * We're doing a live capture. 2142 */ 2143 if (device == NULL) { 2144 /* 2145 * No interface was specified. Pick one. 2146 */ 2147#ifdef HAVE_PCAP_FINDALLDEVS 2148 /* 2149 * Find the list of interfaces, and pick 2150 * the first interface. 2151 */ 2152 if (pcap_findalldevs(&devlist, ebuf) == -1) 2153 error("%s", ebuf); 2154 if (devlist == NULL) 2155 error("no interfaces available for capture"); 2156 device = strdup(devlist->name); 2157 pcap_freealldevs(devlist); 2158#else /* HAVE_PCAP_FINDALLDEVS */ 2159 /* 2160 * Use whatever interface pcap_lookupdev() 2161 * chooses. 2162 */ 2163 device = pcap_lookupdev(ebuf); 2164 if (device == NULL) 2165 error("%s", ebuf); 2166#endif 2167 } 2168 2169 /* 2170 * Try to open the interface with the specified name. 2171 */ 2172 pd = open_interface(device, ndo, ebuf); 2173 if (pd == NULL) { 2174 /* 2175 * That failed. If we can get a list of 2176 * interfaces, and the interface name 2177 * is purely numeric, try to use it as 2178 * a 1-based index in the list of 2179 * interfaces. 2180 */ 2181#ifdef HAVE_PCAP_FINDALLDEVS 2182 devnum = parse_interface_number(device); 2183 if (devnum == -1) { 2184 /* 2185 * It's not a number; just report 2186 * the open error and fail. 2187 */ 2188 error("%s", ebuf); 2189 } 2190 2191 /* 2192 * OK, it's a number; try to find the 2193 * interface with that index, and try 2194 * to open it. 2195 * 2196 * find_interface_by_number() exits if it 2197 * couldn't be found. 2198 */ 2199 device = find_interface_by_number(device, devnum); 2200 pd = open_interface(device, ndo, ebuf); 2201 if (pd == NULL) 2202 error("%s", ebuf); 2203#else /* HAVE_PCAP_FINDALLDEVS */ 2204 /* 2205 * We can't get a list of interfaces; just 2206 * fail. 2207 */ 2208 error("%s", ebuf); 2209#endif /* HAVE_PCAP_FINDALLDEVS */ 2210 } 2211 2212 /* 2213 * Let user own process after capture device has 2214 * been opened. 2215 */ 2216#ifndef _WIN32 2217 if (setgid(getgid()) != 0 || setuid(getuid()) != 0) 2218 fprintf(stderr, "Warning: setgid/setuid failed !\n"); 2219#endif /* _WIN32 */ 2220#if !defined(HAVE_PCAP_CREATE) && defined(_WIN32) 2221 if(Bflag != 0) 2222 if(pcap_setbuff(pd, Bflag)==-1){ 2223 error("%s", pcap_geterr(pd)); 2224 } 2225#endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */ 2226 if (Lflag) 2227 show_dlts_and_exit(pd, device); 2228 if (yflag_dlt >= 0) { 2229#ifdef HAVE_PCAP_SET_DATALINK 2230 if (pcap_set_datalink(pd, yflag_dlt) < 0) 2231 error("%s", pcap_geterr(pd)); 2232#else 2233 /* 2234 * We don't actually support changing the 2235 * data link type, so we only let them 2236 * set it to what it already is. 2237 */ 2238 if (yflag_dlt != pcap_datalink(pd)) { 2239 error("%s is not one of the DLTs supported by this device\n", 2240 yflag_dlt_name); 2241 } 2242#endif 2243 (void)fprintf(stderr, "%s: data link type %s\n", 2244 program_name, 2245 pcap_datalink_val_to_name(yflag_dlt)); 2246 (void)fflush(stderr); 2247 } 2248 i = pcap_snapshot(pd); 2249 if (ndo->ndo_snaplen < i) { 2250 if (ndo->ndo_snaplen != 0) 2251 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i); 2252 ndo->ndo_snaplen = i; 2253 } else if (ndo->ndo_snaplen > i) { 2254 warning("snaplen lowered from %d to %d", ndo->ndo_snaplen, i); 2255 ndo->ndo_snaplen = i; 2256 } 2257 if(ndo->ndo_fflag != 0) { 2258 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) { 2259 warning("foreign (-f) flag used but: %s", ebuf); 2260 } 2261 } 2262 2263 } 2264 if (infile) 2265 cmdbuf = read_infile(infile); 2266 else 2267 cmdbuf = copy_argv(&argv[optind]); 2268 2269#ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG 2270 pcap_set_optimizer_debug(dflag); 2271#endif 2272 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) 2273 error("%s", pcap_geterr(pd)); 2274 if (dflag) { 2275 bpf_dump(&fcode, dflag); 2276 pcap_close(pd); 2277 free(cmdbuf); 2278 pcap_freecode(&fcode); 2279 exit_tcpdump(S_SUCCESS); 2280 } 2281 2282#ifdef HAVE_CASPER 2283 if (!ndo->ndo_nflag) 2284 capdns = capdns_setup(); 2285#endif /* HAVE_CASPER */ 2286 2287 init_print(ndo, localnet, netmask); 2288 2289#ifndef _WIN32 2290 (void)setsignal(SIGPIPE, cleanup); 2291 (void)setsignal(SIGTERM, cleanup); 2292#endif /* _WIN32 */ 2293 (void)setsignal(SIGINT, cleanup); 2294#if defined(HAVE_FORK) || defined(HAVE_VFORK) 2295 (void)setsignal(SIGCHLD, child_cleanup); 2296#endif 2297 /* Cooperate with nohup(1) */ 2298#ifndef _WIN32 2299 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL) 2300 (void)setsignal(SIGHUP, oldhandler); 2301#endif /* _WIN32 */ 2302 2303#ifndef _WIN32 2304 /* 2305 * If a user name was specified with "-Z", attempt to switch to 2306 * that user's UID. This would probably be used with sudo, 2307 * to allow tcpdump to be run in a special restricted 2308 * account (if you just want to allow users to open capture 2309 * devices, and can't just give users that permission, 2310 * you'd make tcpdump set-UID or set-GID). 2311 * 2312 * Tcpdump doesn't necessarily write only to one savefile; 2313 * the general only way to allow a -Z instance to write to 2314 * savefiles as the user under whose UID it's run, rather 2315 * than as the user specified with -Z, would thus be to switch 2316 * to the original user ID before opening a capture file and 2317 * then switch back to the -Z user ID after opening the savefile. 2318 * Switching to the -Z user ID only after opening the first 2319 * savefile doesn't handle the general case. 2320 */ 2321 2322 if (getuid() == 0 || geteuid() == 0) { 2323#ifdef HAVE_LIBCAP_NG 2324 /* Initialize capng */ 2325 capng_clear(CAPNG_SELECT_BOTH); 2326 if (username) { 2327DIAG_OFF_ASSIGN_ENUM 2328 capng_updatev( 2329 CAPNG_ADD, 2330 CAPNG_PERMITTED | CAPNG_EFFECTIVE, 2331 CAP_SETUID, 2332 CAP_SETGID, 2333 -1); 2334DIAG_ON_ASSIGN_ENUM 2335 } 2336 if (chroot_dir) { 2337DIAG_OFF_ASSIGN_ENUM 2338 capng_update( 2339 CAPNG_ADD, 2340 CAPNG_PERMITTED | CAPNG_EFFECTIVE, 2341 CAP_SYS_CHROOT 2342 ); 2343DIAG_ON_ASSIGN_ENUM 2344 } 2345 2346 if (WFileName) { 2347DIAG_OFF_ASSIGN_ENUM 2348 capng_update( 2349 CAPNG_ADD, 2350 CAPNG_PERMITTED | CAPNG_EFFECTIVE, 2351 CAP_DAC_OVERRIDE 2352 ); 2353DIAG_ON_ASSIGN_ENUM 2354 } 2355 capng_apply(CAPNG_SELECT_BOTH); 2356#endif /* HAVE_LIBCAP_NG */ 2357 if (username || chroot_dir) { 2358#ifndef HAVE_LIBCAP_NG 2359 if (!WFileName) 2360#endif 2361 droproot(username, chroot_dir); 2362 } 2363 } 2364#endif /* _WIN32 */ 2365 2366 if (pcap_setfilter(pd, &fcode) < 0) 2367 error("%s", pcap_geterr(pd)); 2368#ifdef HAVE_CAPSICUM 2369 if (RFileName == NULL && VFileName == NULL && pcap_fileno(pd) != -1) { 2370 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF }; 2371 2372 /* 2373 * The various libpcap devices use a combination of 2374 * read (bpf), ioctl (bpf, netmap), poll (netmap) 2375 * so we add the relevant access rights. 2376 */ 2377 cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT); 2378 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 && 2379 errno != ENOSYS) { 2380 error("unable to limit pcap descriptor"); 2381 } 2382 if (cap_ioctls_limit(pcap_fileno(pd), cmds, 2383 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) { 2384 error("unable to limit ioctls on pcap descriptor"); 2385 } 2386 } 2387#endif 2388 if (WFileName) { 2389 /* Do not exceed the default PATH_MAX for files. */ 2390 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1); 2391 2392 if (dumpinfo.CurrentFileName == NULL) 2393 error("malloc of dumpinfo.CurrentFileName"); 2394 2395 /* We do not need numbering for dumpfiles if Cflag isn't set. */ 2396 if (Cflag != 0) 2397 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars); 2398 else 2399 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0); 2400 2401 pdd = pcap_dump_open(pd, dumpinfo.CurrentFileName); 2402#ifdef HAVE_LIBCAP_NG 2403 /* Give up CAP_DAC_OVERRIDE capability. 2404 * Only allow it to be restored if the -C or -G flag have been 2405 * set since we may need to create more files later on. 2406 */ 2407 capng_update( 2408 CAPNG_DROP, 2409 (Cflag || Gflag ? 0 : CAPNG_PERMITTED) 2410 | CAPNG_EFFECTIVE, 2411 CAP_DAC_OVERRIDE 2412 ); 2413 capng_apply(CAPNG_SELECT_BOTH); 2414#endif /* HAVE_LIBCAP_NG */ 2415 if (pdd == NULL) 2416 error("%s", pcap_geterr(pd)); 2417#ifdef HAVE_CAPSICUM 2418 set_dumper_capsicum_rights(pdd); 2419#endif 2420 if (Cflag != 0 || Gflag != 0) { 2421#ifdef HAVE_CAPSICUM 2422 /* 2423 * basename() and dirname() may modify their input buffer 2424 * and they do since FreeBSD 12.0, but they didn't before. 2425 * Hence use the return value only, but always assume the 2426 * input buffer has been modified and would need to be 2427 * reset before the next use. 2428 */ 2429 char *WFileName_copy; 2430 2431 if ((WFileName_copy = strdup(WFileName)) == NULL) { 2432 error("Unable to allocate memory for file %s", 2433 WFileName); 2434 } 2435 DIAG_OFF_C11_EXTENSIONS 2436 dumpinfo.WFileName = strdup(basename(WFileName_copy)); 2437 DIAG_ON_C11_EXTENSIONS 2438 if (dumpinfo.WFileName == NULL) { 2439 error("Unable to allocate memory for file %s", 2440 WFileName); 2441 } 2442 free(WFileName_copy); 2443 2444 if ((WFileName_copy = strdup(WFileName)) == NULL) { 2445 error("Unable to allocate memory for file %s", 2446 WFileName); 2447 } 2448 DIAG_OFF_C11_EXTENSIONS 2449 char *WFileName_dirname = dirname(WFileName_copy); 2450 DIAG_ON_C11_EXTENSIONS 2451 dumpinfo.dirfd = open(WFileName_dirname, 2452 O_DIRECTORY | O_RDONLY); 2453 if (dumpinfo.dirfd < 0) { 2454 error("unable to open directory %s", 2455 WFileName_dirname); 2456 } 2457 free(WFileName_dirname); 2458 free(WFileName_copy); 2459 2460 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL, 2461 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE); 2462 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 && 2463 errno != ENOSYS) { 2464 error("unable to limit directory rights"); 2465 } 2466 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 && 2467 errno != ENOSYS) { 2468 error("unable to limit dump descriptor fcntls"); 2469 } 2470#else /* !HAVE_CAPSICUM */ 2471 dumpinfo.WFileName = WFileName; 2472#endif 2473 callback = dump_packet_and_trunc; 2474 dumpinfo.pd = pd; 2475 dumpinfo.pdd = pdd; 2476 pcap_userdata = (u_char *)&dumpinfo; 2477 } else { 2478 callback = dump_packet; 2479 dumpinfo.WFileName = WFileName; 2480 dumpinfo.pd = pd; 2481 dumpinfo.pdd = pdd; 2482 pcap_userdata = (u_char *)&dumpinfo; 2483 } 2484 if (print) { 2485 dlt = pcap_datalink(pd); 2486 ndo->ndo_if_printer = get_if_printer(dlt); 2487 dumpinfo.ndo = ndo; 2488 } else 2489 dumpinfo.ndo = NULL; 2490 2491#ifdef HAVE_PCAP_DUMP_FLUSH 2492 if (Uflag) 2493 pcap_dump_flush(pdd); 2494#endif 2495 } else { 2496 dlt = pcap_datalink(pd); 2497 ndo->ndo_if_printer = get_if_printer(dlt); 2498 callback = print_packet; 2499 pcap_userdata = (u_char *)ndo; 2500 } 2501 2502#ifdef SIGNAL_REQ_INFO 2503 /* 2504 * We can't get statistics when reading from a file rather 2505 * than capturing from a device. 2506 */ 2507 if (RFileName == NULL) 2508 (void)setsignal(SIGNAL_REQ_INFO, requestinfo); 2509#endif 2510#ifdef SIGNAL_FLUSH_PCAP 2511 (void)setsignal(SIGNAL_FLUSH_PCAP, flushpcap); 2512#endif 2513 2514 if (ndo->ndo_vflag > 0 && WFileName && RFileName == NULL && !print) { 2515 /* 2516 * When capturing to a file, if "--print" wasn't specified, 2517 *"-v" means tcpdump should, once per second, 2518 * "v"erbosely report the number of packets captured. 2519 * Except when reading from a file, because -r, -w and -v 2520 * together used to make a corner case, in which pcap_loop() 2521 * errored due to EINTR (see GH #155 for details). 2522 */ 2523#ifdef _WIN32 2524 /* 2525 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741 2526 * 2527 * suggests that this dates back to W2K. 2528 * 2529 * I don't know what a "long wait" is, but we'll assume 2530 * that printing the stats could be a "long wait". 2531 */ 2532 CreateTimerQueueTimer(&timer_handle, NULL, 2533 verbose_stats_dump, NULL, 1000, 1000, 2534 WT_EXECUTEDEFAULT|WT_EXECUTELONGFUNCTION); 2535 setvbuf(stderr, NULL, _IONBF, 0); 2536#else /* _WIN32 */ 2537 /* 2538 * Assume this is UN*X, and that it has setitimer(); that 2539 * dates back to UNIX 95. 2540 */ 2541 struct itimerval timer; 2542 (void)setsignal(SIGALRM, verbose_stats_dump); 2543 timer.it_interval.tv_sec = 1; 2544 timer.it_interval.tv_usec = 0; 2545 timer.it_value.tv_sec = 1; 2546 timer.it_value.tv_usec = 1; 2547 setitimer(ITIMER_REAL, &timer, NULL); 2548#endif /* _WIN32 */ 2549 } 2550 2551 if (RFileName == NULL) { 2552 /* 2553 * Live capture (if -V was specified, we set RFileName 2554 * to a file from the -V file). Print a message to 2555 * the standard error on UN*X. 2556 */ 2557 if (!ndo->ndo_vflag && !WFileName) { 2558 (void)fprintf(stderr, 2559 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n", 2560 program_name); 2561 } else 2562 (void)fprintf(stderr, "%s: ", program_name); 2563 dlt = pcap_datalink(pd); 2564 dlt_name = pcap_datalink_val_to_name(dlt); 2565 (void)fprintf(stderr, "listening on %s", device); 2566 if (dlt_name == NULL) { 2567 (void)fprintf(stderr, ", link-type %u", dlt); 2568 } else { 2569 (void)fprintf(stderr, ", link-type %s (%s)", dlt_name, 2570 pcap_datalink_val_to_description(dlt)); 2571 } 2572 (void)fprintf(stderr, ", snapshot length %d bytes\n", ndo->ndo_snaplen); 2573 (void)fflush(stderr); 2574 } 2575 2576 /* 2577 * If a user name was specified with "-Z", attempt to switch to 2578 * that user's UID. This would probably be used with sudo, 2579 * to allow tcpdump to be run in a special restricted 2580 * account (if you just want to allow users to open capture 2581 * devices, and can't just give users that permission, 2582 * you'd make tcpdump set-UID or set-GID). 2583 * 2584 * Tcpdump doesn't necessarily write only to one savefile; 2585 * the general only way to allow a -Z instance to write to 2586 * savefiles as the user under whose UID it's run, rather 2587 * than as the user specified with -Z, would thus be to switch 2588 * to the original user ID before opening a capture file and 2589 * then switch back to the -Z user ID after opening the savefile. 2590 * Switching to the -Z user ID only after opening the first 2591 * savefile doesn't handle the general case. 2592 */ 2593 if (getuid() == 0 || geteuid() == 0) { 2594 if (username || chroot_dir) 2595 droproot(username, chroot_dir); 2596 } 2597 2598#ifdef HAVE_CAPSICUM 2599 cansandbox = (VFileName == NULL && zflag == NULL); 2600#ifdef HAVE_CASPER 2601 cansandbox = (cansandbox && (ndo->ndo_nflag || capdns != NULL)); 2602#else 2603 cansandbox = (cansandbox && ndo->ndo_nflag); 2604#endif /* HAVE_CASPER */ 2605 if (cansandbox && cap_enter() < 0 && errno != ENOSYS) 2606 error("unable to enter the capability mode"); 2607#endif /* HAVE_CAPSICUM */ 2608 2609 do { 2610 status = pcap_loop(pd, cnt, callback, pcap_userdata); 2611 if (WFileName == NULL) { 2612 /* 2613 * We're printing packets. Flush the printed output, 2614 * so it doesn't get intermingled with error output. 2615 */ 2616 if (status == -2) { 2617 /* 2618 * We got interrupted, so perhaps we didn't 2619 * manage to finish a line we were printing. 2620 * Print an extra newline, just in case. 2621 */ 2622 putchar('\n'); 2623 } 2624 (void)fflush(stdout); 2625 } 2626 if (status == -2) { 2627 /* 2628 * We got interrupted. If we are reading multiple 2629 * files (via -V) set these so that we stop. 2630 */ 2631 VFileName = NULL; 2632 ret = NULL; 2633 } 2634 if (status == -1) { 2635 /* 2636 * Error. Report it. 2637 */ 2638 (void)fprintf(stderr, "%s: pcap_loop: %s\n", 2639 program_name, pcap_geterr(pd)); 2640 } 2641 if (RFileName == NULL) { 2642 /* 2643 * We're doing a live capture. Report the capture 2644 * statistics. 2645 */ 2646 info(1); 2647 } 2648 pcap_close(pd); 2649 if (VFileName != NULL) { 2650 ret = get_next_file(VFile, VFileLine); 2651 if (ret) { 2652 int new_dlt; 2653 2654 RFileName = VFileLine; 2655 pd = pcap_open_offline(RFileName, ebuf); 2656 if (pd == NULL) 2657 error("%s", ebuf); 2658#ifdef HAVE_CAPSICUM 2659 cap_rights_init(&rights, CAP_READ); 2660 if (cap_rights_limit(fileno(pcap_file(pd)), 2661 &rights) < 0 && errno != ENOSYS) { 2662 error("unable to limit pcap descriptor"); 2663 } 2664#endif 2665 new_dlt = pcap_datalink(pd); 2666 if (new_dlt != dlt) { 2667 /* 2668 * The new file has a different 2669 * link-layer header type from the 2670 * previous one. 2671 */ 2672 if (WFileName != NULL) { 2673 /* 2674 * We're writing raw packets 2675 * that match the filter to 2676 * a pcap file. pcap files 2677 * don't support multiple 2678 * different link-layer 2679 * header types, so we fail 2680 * here. 2681 */ 2682 error("%s: new dlt does not match original", RFileName); 2683 } 2684 2685 /* 2686 * We're printing the decoded packets; 2687 * switch to the new DLT. 2688 * 2689 * To do that, we need to change 2690 * the printer, change the DLT name, 2691 * and recompile the filter with 2692 * the new DLT. 2693 */ 2694 dlt = new_dlt; 2695 ndo->ndo_if_printer = get_if_printer(dlt); 2696 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) 2697 error("%s", pcap_geterr(pd)); 2698 } 2699 2700 /* 2701 * Set the filter on the new file. 2702 */ 2703 if (pcap_setfilter(pd, &fcode) < 0) 2704 error("%s", pcap_geterr(pd)); 2705 2706 /* 2707 * Report the new file. 2708 */ 2709 dlt_name = pcap_datalink_val_to_name(dlt); 2710 fprintf(stderr, "reading from file %s", RFileName); 2711 if (dlt_name == NULL) { 2712 fprintf(stderr, ", link-type %u", dlt); 2713 } else { 2714 fprintf(stderr, ", link-type %s (%s)", 2715 dlt_name, 2716 pcap_datalink_val_to_description(dlt)); 2717 } 2718 fprintf(stderr, ", snapshot length %d\n", pcap_snapshot(pd)); 2719 } 2720 } 2721 } 2722 while (ret != NULL); 2723 2724 if (count_mode && RFileName != NULL) 2725 fprintf(stdout, "%u packet%s\n", packets_captured, 2726 PLURAL_SUFFIX(packets_captured)); 2727 2728 free(cmdbuf); 2729 pcap_freecode(&fcode); 2730 exit_tcpdump(status == -1 ? S_ERR_HOST_PROGRAM : S_SUCCESS); 2731} 2732 2733/* 2734 * Catch a signal. 2735 */ 2736static void 2737(*setsignal (int sig, void (*func)(int)))(int) 2738{ 2739#ifdef _WIN32 2740 return (signal(sig, func)); 2741#else 2742 struct sigaction old, new; 2743 2744 memset(&new, 0, sizeof(new)); 2745 new.sa_handler = func; 2746 if ((sig == SIGCHLD) 2747# ifdef SIGNAL_REQ_INFO 2748 || (sig == SIGNAL_REQ_INFO) 2749# endif 2750# ifdef SIGNAL_FLUSH_PCAP 2751 || (sig == SIGNAL_FLUSH_PCAP) 2752# endif 2753 ) 2754 new.sa_flags = SA_RESTART; 2755 if (sigaction(sig, &new, &old) < 0) 2756 return (SIG_ERR); 2757 return (old.sa_handler); 2758#endif 2759} 2760 2761/* make a clean exit on interrupts */ 2762static void 2763cleanup(int signo _U_) 2764{ 2765#ifdef _WIN32 2766 if (timer_handle != INVALID_HANDLE_VALUE) { 2767 DeleteTimerQueueTimer(NULL, timer_handle, NULL); 2768 CloseHandle(timer_handle); 2769 timer_handle = INVALID_HANDLE_VALUE; 2770 } 2771#else /* _WIN32 */ 2772 struct itimerval timer; 2773 2774 timer.it_interval.tv_sec = 0; 2775 timer.it_interval.tv_usec = 0; 2776 timer.it_value.tv_sec = 0; 2777 timer.it_value.tv_usec = 0; 2778 setitimer(ITIMER_REAL, &timer, NULL); 2779#endif /* _WIN32 */ 2780 2781#ifdef HAVE_PCAP_BREAKLOOP 2782 /* 2783 * We have "pcap_breakloop()"; use it, so that we do as little 2784 * as possible in the signal handler (it's probably not safe 2785 * to do anything with standard I/O streams in a signal handler - 2786 * the ANSI C standard doesn't say it is). 2787 */ 2788 pcap_breakloop(pd); 2789#else 2790 /* 2791 * We don't have "pcap_breakloop()"; this isn't safe, but 2792 * it's the best we can do. Print the summary if we're 2793 * not reading from a savefile - i.e., if we're doing a 2794 * live capture - and exit. 2795 */ 2796 if (pd != NULL && pcap_file(pd) == NULL) { 2797 /* 2798 * We got interrupted, so perhaps we didn't 2799 * manage to finish a line we were printing. 2800 * Print an extra newline, just in case. 2801 */ 2802 putchar('\n'); 2803 (void)fflush(stdout); 2804 info(1); 2805 } 2806 exit_tcpdump(S_SUCCESS); 2807#endif 2808} 2809 2810/* 2811 On windows, we do not use a fork, so we do not care less about 2812 waiting a child processes to die 2813 */ 2814#if defined(HAVE_FORK) || defined(HAVE_VFORK) 2815static void 2816child_cleanup(int signo _U_) 2817{ 2818 wait(NULL); 2819} 2820#endif /* HAVE_FORK && HAVE_VFORK */ 2821 2822static void 2823info(int verbose) 2824{ 2825 struct pcap_stat stats; 2826 2827 /* 2828 * Older versions of libpcap didn't set ps_ifdrop on some 2829 * platforms; initialize it to 0 to handle that. 2830 */ 2831 stats.ps_ifdrop = 0; 2832 if (pcap_stats(pd, &stats) < 0) { 2833 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd)); 2834 infoprint = 0; 2835 return; 2836 } 2837 2838 if (!verbose) 2839 fprintf(stderr, "%s: ", program_name); 2840 2841 (void)fprintf(stderr, "%u packet%s captured", packets_captured, 2842 PLURAL_SUFFIX(packets_captured)); 2843 if (!verbose) 2844 fputs(", ", stderr); 2845 else 2846 putc('\n', stderr); 2847 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv, 2848 PLURAL_SUFFIX(stats.ps_recv)); 2849 if (!verbose) 2850 fputs(", ", stderr); 2851 else 2852 putc('\n', stderr); 2853 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop, 2854 PLURAL_SUFFIX(stats.ps_drop)); 2855 if (stats.ps_ifdrop != 0) { 2856 if (!verbose) 2857 fputs(", ", stderr); 2858 else 2859 putc('\n', stderr); 2860 (void)fprintf(stderr, "%u packet%s dropped by interface\n", 2861 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop)); 2862 } else 2863 putc('\n', stderr); 2864 infoprint = 0; 2865} 2866 2867#if defined(HAVE_FORK) || defined(HAVE_VFORK) 2868#ifdef HAVE_FORK 2869#define fork_subprocess() fork() 2870#else 2871#define fork_subprocess() vfork() 2872#endif 2873static void 2874compress_savefile(const char *filename) 2875{ 2876 pid_t child; 2877 2878 child = fork_subprocess(); 2879 if (child == -1) { 2880 fprintf(stderr, 2881 "compress_savefile: fork failed: %s\n", 2882 pcap_strerror(errno)); 2883 return; 2884 } 2885 if (child != 0) { 2886 /* Parent process. */ 2887 return; 2888 } 2889 2890 /* 2891 * Child process. 2892 * Set to lowest priority so that this doesn't disturb the capture. 2893 */ 2894#ifdef NZERO 2895 setpriority(PRIO_PROCESS, 0, NZERO - 1); 2896#else 2897 setpriority(PRIO_PROCESS, 0, 19); 2898#endif 2899 if (execlp(zflag, zflag, filename, (char *)NULL) == -1) 2900 fprintf(stderr, 2901 "compress_savefile: execlp(%s, %s) failed: %s\n", 2902 zflag, 2903 filename, 2904 pcap_strerror(errno)); 2905#ifdef HAVE_FORK 2906 exit(S_ERR_HOST_PROGRAM); 2907#else 2908 _exit(S_ERR_HOST_PROGRAM); 2909#endif 2910} 2911#else /* HAVE_FORK && HAVE_VFORK */ 2912static void 2913compress_savefile(const char *filename) 2914{ 2915 fprintf(stderr, 2916 "compress_savefile failed. Functionality not implemented under your system\n"); 2917} 2918#endif /* HAVE_FORK && HAVE_VFORK */ 2919 2920static void 2921dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 2922{ 2923 struct dump_info *dump_info; 2924 2925 ++packets_captured; 2926 2927 ++infodelay; 2928 2929 dump_info = (struct dump_info *)user; 2930 2931 /* 2932 * XXX - this won't force the file to rotate on the specified time 2933 * boundary, but it will rotate on the first packet received after the 2934 * specified Gflag number of seconds. Note: if a Gflag time boundary 2935 * and a Cflag size boundary coincide, the time rotation will occur 2936 * first thereby cancelling the Cflag boundary (since the file should 2937 * be 0). 2938 */ 2939 if (Gflag != 0) { 2940 /* Check if it is time to rotate */ 2941 time_t t; 2942 2943 /* Get the current time */ 2944 if ((t = time(NULL)) == (time_t)-1) { 2945 error("%s: can't get current_time: %s", 2946 __func__, pcap_strerror(errno)); 2947 } 2948 2949 2950 /* If the time is greater than the specified window, rotate */ 2951 if (t - Gflag_time >= Gflag) { 2952#ifdef HAVE_CAPSICUM 2953 FILE *fp; 2954 int fd; 2955#endif 2956 2957 /* Update the Gflag_time */ 2958 Gflag_time = t; 2959 /* Update Gflag_count */ 2960 Gflag_count++; 2961 /* 2962 * Close the current file and open a new one. 2963 */ 2964 pcap_dump_close(dump_info->pdd); 2965 2966 /* 2967 * Compress the file we just closed, if the user asked for it 2968 */ 2969 if (zflag != NULL) 2970 compress_savefile(dump_info->CurrentFileName); 2971 2972 /* 2973 * Check to see if we've exceeded the Wflag (when 2974 * not using Cflag). 2975 */ 2976 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) { 2977 (void)fprintf(stderr, "Maximum file limit reached: %d\n", 2978 Wflag); 2979 info(1); 2980 exit_tcpdump(S_SUCCESS); 2981 /* NOTREACHED */ 2982 } 2983 if (dump_info->CurrentFileName != NULL) 2984 free(dump_info->CurrentFileName); 2985 /* Allocate space for max filename + \0. */ 2986 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1); 2987 if (dump_info->CurrentFileName == NULL) 2988 error("dump_packet_and_trunc: malloc"); 2989 /* 2990 * Gflag was set otherwise we wouldn't be here. Reset the count 2991 * so multiple files would end with 1,2,3 in the filename. 2992 * The counting is handled with the -C flow after this. 2993 */ 2994 Cflag_count = 0; 2995 2996 /* 2997 * This is always the first file in the Cflag 2998 * rotation: e.g. 0 2999 * We also don't need numbering if Cflag is not set. 3000 */ 3001 if (Cflag != 0) 3002 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 3003 WflagChars); 3004 else 3005 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0); 3006 3007#ifdef HAVE_LIBCAP_NG 3008 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); 3009 capng_apply(CAPNG_SELECT_BOTH); 3010#endif /* HAVE_LIBCAP_NG */ 3011#ifdef HAVE_CAPSICUM 3012 fd = openat(dump_info->dirfd, 3013 dump_info->CurrentFileName, 3014 O_CREAT | O_WRONLY | O_TRUNC, 0644); 3015 if (fd < 0) { 3016 error("unable to open file %s", 3017 dump_info->CurrentFileName); 3018 } 3019 fp = fdopen(fd, "w"); 3020 if (fp == NULL) { 3021 error("unable to fdopen file %s", 3022 dump_info->CurrentFileName); 3023 } 3024 dump_info->pdd = pcap_dump_fopen(dump_info->pd, fp); 3025#else /* !HAVE_CAPSICUM */ 3026 dump_info->pdd = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName); 3027#endif 3028#ifdef HAVE_LIBCAP_NG 3029 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); 3030 capng_apply(CAPNG_SELECT_BOTH); 3031#endif /* HAVE_LIBCAP_NG */ 3032 if (dump_info->pdd == NULL) 3033 error("%s", pcap_geterr(pd)); 3034#ifdef HAVE_CAPSICUM 3035 set_dumper_capsicum_rights(dump_info->pdd); 3036#endif 3037 } 3038 } 3039 3040 /* 3041 * XXX - this won't prevent capture files from getting 3042 * larger than Cflag - the last packet written to the 3043 * file could put it over Cflag. 3044 */ 3045 if (Cflag != 0) { 3046#ifdef HAVE_PCAP_DUMP_FTELL64 3047 int64_t size = pcap_dump_ftell64(dump_info->pdd); 3048#else 3049 /* 3050 * XXX - this only handles a Cflag value > 2^31-1 on 3051 * LP64 platforms; to handle ILP32 (32-bit UN*X and 3052 * Windows) or LLP64 (64-bit Windows) would require 3053 * a version of libpcap with pcap_dump_ftell64(). 3054 */ 3055 long size = pcap_dump_ftell(dump_info->pdd); 3056#endif 3057 3058 if (size == -1) 3059 error("ftell fails on output file"); 3060 if (size > Cflag) { 3061#ifdef HAVE_CAPSICUM 3062 FILE *fp; 3063 int fd; 3064#endif 3065 3066 /* 3067 * Close the current file and open a new one. 3068 */ 3069 pcap_dump_close(dump_info->pdd); 3070 3071 /* 3072 * Compress the file we just closed, if the user 3073 * asked for it. 3074 */ 3075 if (zflag != NULL) 3076 compress_savefile(dump_info->CurrentFileName); 3077 3078 Cflag_count++; 3079 if (Wflag > 0) { 3080 if (Cflag_count >= Wflag) 3081 Cflag_count = 0; 3082 } 3083 if (dump_info->CurrentFileName != NULL) 3084 free(dump_info->CurrentFileName); 3085 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1); 3086 if (dump_info->CurrentFileName == NULL) 3087 error("%s: malloc", __func__); 3088 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars); 3089#ifdef HAVE_LIBCAP_NG 3090 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); 3091 capng_apply(CAPNG_SELECT_BOTH); 3092#endif /* HAVE_LIBCAP_NG */ 3093#ifdef HAVE_CAPSICUM 3094 fd = openat(dump_info->dirfd, dump_info->CurrentFileName, 3095 O_CREAT | O_WRONLY | O_TRUNC, 0644); 3096 if (fd < 0) { 3097 error("unable to open file %s", 3098 dump_info->CurrentFileName); 3099 } 3100 fp = fdopen(fd, "w"); 3101 if (fp == NULL) { 3102 error("unable to fdopen file %s", 3103 dump_info->CurrentFileName); 3104 } 3105 dump_info->pdd = pcap_dump_fopen(dump_info->pd, fp); 3106#else /* !HAVE_CAPSICUM */ 3107 dump_info->pdd = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName); 3108#endif 3109#ifdef HAVE_LIBCAP_NG 3110 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE); 3111 capng_apply(CAPNG_SELECT_BOTH); 3112#endif /* HAVE_LIBCAP_NG */ 3113 if (dump_info->pdd == NULL) 3114 error("%s", pcap_geterr(pd)); 3115#ifdef HAVE_CAPSICUM 3116 set_dumper_capsicum_rights(dump_info->pdd); 3117#endif 3118 } 3119 } 3120 3121 pcap_dump((u_char *)dump_info->pdd, h, sp); 3122#ifdef HAVE_PCAP_DUMP_FLUSH 3123 if (Uflag) 3124 pcap_dump_flush(dump_info->pdd); 3125#endif 3126 3127 if (dump_info->ndo != NULL) 3128 pretty_print_packet(dump_info->ndo, h, sp, packets_captured); 3129 3130 --infodelay; 3131 if (infoprint) 3132 info(0); 3133} 3134 3135static void 3136dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 3137{ 3138 struct dump_info *dump_info; 3139 3140 ++packets_captured; 3141 3142 ++infodelay; 3143 3144 dump_info = (struct dump_info *)user; 3145 3146 pcap_dump((u_char *)dump_info->pdd, h, sp); 3147#ifdef HAVE_PCAP_DUMP_FLUSH 3148 if (Uflag) 3149 pcap_dump_flush(dump_info->pdd); 3150#endif 3151 3152 if (dump_info->ndo != NULL) 3153 pretty_print_packet(dump_info->ndo, h, sp, packets_captured); 3154 3155 --infodelay; 3156 if (infoprint) 3157 info(0); 3158} 3159 3160static void 3161print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp) 3162{ 3163 ++packets_captured; 3164 3165 ++infodelay; 3166 3167 if (!count_mode) 3168 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured); 3169 3170 --infodelay; 3171 if (infoprint) 3172 info(0); 3173} 3174 3175#ifdef SIGNAL_REQ_INFO 3176static void 3177requestinfo(int signo _U_) 3178{ 3179 if (infodelay) 3180 ++infoprint; 3181 else 3182 info(0); 3183} 3184#endif 3185 3186#ifdef SIGNAL_FLUSH_PCAP 3187static void 3188flushpcap(int signo _U_) 3189{ 3190 if (pdd != NULL) 3191 pcap_dump_flush(pdd); 3192} 3193#endif 3194 3195static void 3196print_packets_captured (void) 3197{ 3198 static u_int prev_packets_captured, first = 1; 3199 3200 if (infodelay == 0 && (first || packets_captured != prev_packets_captured)) { 3201 fprintf(stderr, "Got %u\r", packets_captured); 3202 first = 0; 3203 prev_packets_captured = packets_captured; 3204 } 3205} 3206 3207/* 3208 * Called once each second in verbose mode while dumping to file 3209 */ 3210#ifdef _WIN32 3211static void CALLBACK verbose_stats_dump(PVOID param _U_, 3212 BOOLEAN timer_fired _U_) 3213{ 3214 print_packets_captured(); 3215} 3216#else /* _WIN32 */ 3217static void verbose_stats_dump(int sig _U_) 3218{ 3219 print_packets_captured(); 3220} 3221#endif /* _WIN32 */ 3222 3223DIAG_OFF_DEPRECATION 3224static void 3225print_version(FILE *f) 3226{ 3227#ifndef HAVE_PCAP_LIB_VERSION 3228 #ifdef HAVE_PCAP_VERSION 3229 extern char pcap_version[]; 3230 #else /* HAVE_PCAP_VERSION */ 3231 static char pcap_version[] = "unknown"; 3232 #endif /* HAVE_PCAP_VERSION */ 3233#endif /* HAVE_PCAP_LIB_VERSION */ 3234 const char *smi_version_string; 3235 3236 (void)fprintf(f, "%s version " PACKAGE_VERSION "\n", program_name); 3237#ifdef HAVE_PCAP_LIB_VERSION 3238 (void)fprintf(f, "%s\n", pcap_lib_version()); 3239#else /* HAVE_PCAP_LIB_VERSION */ 3240 (void)fprintf(f, "libpcap version %s\n", pcap_version); 3241#endif /* HAVE_PCAP_LIB_VERSION */ 3242 3243#if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION) 3244 (void)fprintf (f, "%s\n", SSLeay_version(SSLEAY_VERSION)); 3245#endif 3246 3247 smi_version_string = nd_smi_version_string(); 3248 if (smi_version_string != NULL) 3249 (void)fprintf (f, "SMI-library: %s\n", smi_version_string); 3250 3251#if defined(__SANITIZE_ADDRESS__) 3252 (void)fprintf (f, "Compiled with AddressSanitizer/GCC.\n"); 3253#elif defined(__has_feature) 3254# if __has_feature(address_sanitizer) 3255 (void)fprintf (f, "Compiled with AddressSanitizer/Clang.\n"); 3256# elif __has_feature(memory_sanitizer) 3257 (void)fprintf (f, "Compiled with MemorySanitizer/Clang.\n"); 3258# endif 3259#endif /* __SANITIZE_ADDRESS__ or __has_feature */ 3260} 3261DIAG_ON_DEPRECATION 3262 3263static void 3264print_usage(FILE *f) 3265{ 3266 print_version(f); 3267 (void)fprintf(f, 3268"Usage: %s [-Abd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ] [--count]\n", program_name); 3269 (void)fprintf(f, 3270"\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n"); 3271 (void)fprintf(f, 3272"\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE "\n"); 3273#ifdef HAVE_PCAP_FINDALLDEVS_EX 3274 (void)fprintf(f, 3275"\t\t" LIST_REMOTE_INTERFACES_USAGE "\n"); 3276#endif 3277#ifdef USE_LIBSMI 3278 (void)fprintf(f, 3279"\t\t" m_FLAG_USAGE "\n"); 3280#endif 3281 (void)fprintf(f, 3282"\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE "\n"); 3283 (void)fprintf(f, 3284"\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ --version ]\n"); 3285 (void)fprintf(f, 3286"\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n"); 3287#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION 3288 (void)fprintf(f, 3289"\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n"); 3290#endif 3291 (void)fprintf(f, 3292"\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n"); 3293} 3294