wireshark/dumpcap.c

5817 lines
219 KiB
C
Raw Permalink Normal View History

/* dumpcap.c
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <config.h>
Refactor our logging and extend the wslog API Experience has shown that: 1. The current logging methods are not very reliable or practical. A logging bitmask makes little sense as the user-facing interface (who would want debug but not crtical messages for example?); it's computer-friendly and user-unfriendly. More importantly the console log level preference is initialized too late in the startup process to be used for the logging subsystem and that fact raises a number of annoying and hard-to-fix usability issues. 2. Coding around G_MESSAGES_DEBUG to comply with our log level mask and not clobber the user's settings or not create unexpected log misses is unworkable and generally follows the principle of most surprise. The fact that G_MESSAGES_DEBUG="all" can leak to other programs using GLib is also annoying. 3. The non-structured GLib logging API is very opinionated and lacks configurability beyond replacing the log handler. 4. Windows GUI has some special code to attach to a console, but it would be nice to abstract away the rest under a single interface. 5. Using this logger seems to be noticeably faster. Deprecate the console log level preference and extend our API to implement a log handler in wsutil/wslog.h to provide easy-to-use, flexible and dependable logging during all execution phases. Log levels have a hierarchy, from most verbose to least verbose (debug to error). When a given level is set everything above that is also enabled. The log level can be set with an environment variable or a command line option (parsed as soon as possible but still later than the environment). The default log level is "message". Dissector logging is not included because it is not clear what log domain they should use. An explosion to thousands of domains is not desirable and putting everything in a single domain is probably too coarse and noisy. For now I think it makes sense to let them do their own thing using g_log_default_handler() and continue using the G_MESSAGES_DEBUG mechanism with specific domains for each individual dissector. In the future a mechanism may be added to selectively enable these domains at runtime while trying to avoid the problems introduced by G_MESSAGES_DEBUG.
2021-06-08 01:46:52 +00:00
#define WS_LOG_DOMAIN LOG_DOMAIN_CAPCHILD
#include <stdio.h>
#include <stdlib.h> /* for exit() */
#include <glib.h>
#include <string.h>
#include <sys/types.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#include <wsutil/ws_getopt.h>
#if defined(__APPLE__) && defined(__LP64__)
#include <sys/utsname.h>
#endif
#include <signal.h>
#include <errno.h>
2023-02-06 22:46:45 +00:00
#include <wsutil/cmdarg_err.h>
#include <wsutil/strtoi.h>
#include <cli_main.h>
2023-02-06 21:57:51 +00:00
#include <wsutil/version_info.h>
#include <wsutil/socket.h>
Refactor our logging and extend the wslog API Experience has shown that: 1. The current logging methods are not very reliable or practical. A logging bitmask makes little sense as the user-facing interface (who would want debug but not crtical messages for example?); it's computer-friendly and user-unfriendly. More importantly the console log level preference is initialized too late in the startup process to be used for the logging subsystem and that fact raises a number of annoying and hard-to-fix usability issues. 2. Coding around G_MESSAGES_DEBUG to comply with our log level mask and not clobber the user's settings or not create unexpected log misses is unworkable and generally follows the principle of most surprise. The fact that G_MESSAGES_DEBUG="all" can leak to other programs using GLib is also annoying. 3. The non-structured GLib logging API is very opinionated and lacks configurability beyond replacing the log handler. 4. Windows GUI has some special code to attach to a console, but it would be nice to abstract away the rest under a single interface. 5. Using this logger seems to be noticeably faster. Deprecate the console log level preference and extend our API to implement a log handler in wsutil/wslog.h to provide easy-to-use, flexible and dependable logging during all execution phases. Log levels have a hierarchy, from most verbose to least verbose (debug to error). When a given level is set everything above that is also enabled. The log level can be set with an environment variable or a command line option (parsed as soon as possible but still later than the environment). The default log level is "message". Dissector logging is not included because it is not clear what log domain they should use. An explosion to thousands of domains is not desirable and putting everything in a single domain is probably too coarse and noisy. For now I think it makes sense to let them do their own thing using g_log_default_handler() and continue using the G_MESSAGES_DEBUG mechanism with specific domains for each individual dissector. In the future a mechanism may be added to selectively enable these domains at runtime while trying to avoid the problems introduced by G_MESSAGES_DEBUG.
2021-06-08 01:46:52 +00:00
#include <wsutil/wslog.h>
#include <wsutil/file_util.h>
#ifdef HAVE_LIBCAP
# include <sys/prctl.h>
# include <sys/capability.h>
#endif
#include "ringbuffer.h"
#include "capture/capture_ifinfo.h"
#include "capture/capture-pcap-util.h"
#include "capture/capture-pcap-util-int.h"
#ifdef _WIN32
#include "capture/capture-wpcap.h"
#endif /* _WIN32 */
#include "writecap/pcapio.h"
#ifndef _WIN32
#include <sys/un.h>
#endif
2023-02-06 22:50:32 +00:00
#include <wsutil/clopts_common.h>
#include <wsutil/privileges.h>
#include "sync_pipe.h"
#include "capture_opts.h"
#include <capture/capture_session.h>
#include <capture/capture_sync.h>
#include "wsutil/tempfile.h"
#include "wsutil/file_util.h"
#include "wsutil/cpu_info.h"
#include "wsutil/os_version_info.h"
#include "wsutil/str_util.h"
#include "wsutil/inet_addr.h"
#include "wsutil/time_util.h"
#include "wsutil/please_report_bug.h"
#include "wsutil/glib-compat.h"
2021-06-18 18:21:42 +00:00
#include <wsutil/ws_assert.h>
#include "capture/ws80211_utils.h"
#include "extcap.h"
/*
* Get information about libpcap format from "wiretap/libpcap.h".
* Get information about pcapng format from "wiretap/pcapng_module.h".
* XXX - can we just use pcap_open_offline() to read the pipe?
*/
#include "wiretap/libpcap.h"
#include "wiretap/pcapng_module.h"
#include "wiretap/pcapng.h"
/**#define DEBUG_DUMPCAP**/
/**#define DEBUG_CHILD_DUMPCAP**/
#ifdef _WIN32
#include "wsutil/win32-utils.h"
#ifdef DEBUG_DUMPCAP
#include <conio.h> /* _getch() */
#endif
#endif
#ifdef DEBUG_CHILD_DUMPCAP
FILE *debug_log; /* for logging debug messages to */
/* a file if DEBUG_CHILD_DUMPCAP */
/* is defined */
#endif
static GAsyncQueue *pcap_queue;
static gint64 pcap_queue_bytes;
static gint64 pcap_queue_packets;
static gint64 pcap_queue_byte_limit = 0;
static gint64 pcap_queue_packet_limit = 0;
static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
static const char *report_capture_filename = NULL; /* capture child file name */
#ifdef _WIN32
static gchar *sig_pipe_name = NULL;
static HANDLE sig_pipe_handle = NULL;
static gboolean signal_pipe_check_running(void);
#endif
#ifdef SIGINFO
static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
#endif /* SIGINFO */
/** Stop a low-level capture (stops the capture child). */
static void capture_loop_stop(void);
/** Close a pipe, or socket if \a from_socket is TRUE */
static void cap_pipe_close(int pipe_fd, gboolean from_socket);
#if defined (__linux__)
/* whatever the deal with pcap_breakloop, linux doesn't support timeouts
* in pcap_dispatch(); on the other hand, select() works just fine there.
* Hence we use a select for that come what may.
*
* XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
* internally, and, with TPACKET_V3, once that's supported, it'll
* support timeouts, at least as I understand the way the code works.
*/
#define MUST_DO_SELECT
#endif
/** init the capture filter */
typedef enum {
INITFILTER_NO_ERROR,
INITFILTER_BAD_FILTER,
INITFILTER_OTHER_ERROR
} initfilter_status_t;
typedef enum {
STATE_EXPECT_REC_HDR,
STATE_READ_REC_HDR,
STATE_EXPECT_DATA,
STATE_READ_DATA
} cap_pipe_state_t;
typedef enum {
PIPOK,
PIPEOF,
PIPERR,
PIPNEXIST
} cap_pipe_err_t;
typedef struct _pcap_pipe_info {
gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
} pcap_pipe_info_t;
typedef struct _pcapng_pipe_info {
pcapng_block_header_t bh; /**< Pcapng general block header when capturing from a pipe */
GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
} pcapng_pipe_info_t;
struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
/*
* A source of packets from which we're capturing.
*/
typedef struct _capture_src {
guint32 received;
guint32 dropped;
guint32 flushed;
pcap_t *pcap_h;
#ifdef MUST_DO_SELECT
2013-01-22 08:28:46 +00:00
int pcap_fd; /**< pcap file descriptor */
#endif
gboolean pcap_err;
guint interface_id;
GThread *tid;
int snaplen;
int linktype;
2013-01-22 08:28:46 +00:00
gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
/**< capture pipe (unix only "input file") */
gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
union {
pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
} cap_pipe_info;
#ifdef _WIN32
2013-01-22 08:28:46 +00:00
HANDLE cap_pipe_h; /**< The handle of the capture pipe */
#endif
2013-01-22 08:28:46 +00:00
int cap_pipe_fd; /**< the file descriptor of the capture pipe */
gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
#if defined(_WIN32)
char * cap_pipe_buf; /**< Pointer to the buffer we read into */
2013-01-22 08:28:46 +00:00
DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
#else
2013-01-22 08:28:46 +00:00
size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
#endif
int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
cap_pipe_state_t cap_pipe_state;
cap_pipe_err_t cap_pipe_err;
#if defined(_WIN32)
GMutex *cap_pipe_read_mtx;
GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
#endif
} capture_src;
typedef struct _saved_idb {
gboolean deleted;
guint interface_id; /* capture_src->interface_id for the associated SHB */
guint8 *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
guint idb_len;
} saved_idb_t;
/*
* Global capture loop state.
*/
typedef struct _loop_data {
/* common */
gboolean go; /**< TRUE as long as we're supposed to keep capturing */
int err; /**< if non-zero, error seen while capturing */
gint packets_captured; /**< Number of packets we have already captured */
2013-01-22 08:28:46 +00:00
guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
#ifdef SIGINFO
2013-01-22 08:28:46 +00:00
gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
#endif
GArray *pcaps; /**< Array of capture_src's on which we're capturing */
gboolean pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
guint8 *saved_shb; /**< SHB to write when we have one pcapng input */
GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
/* output file(s) */
FILE *pdh;
int save_file_fd;
char *io_buffer; /**< Our IO buffer if we increase the size from the standard size */
guint64 bytes_written; /**< Bytes written for the current file. */
/* autostop conditions */
int packets_written; /**< Packets written for the current file. */
int file_count;
/* ring buffer conditions */
GTimer *file_duration_timer;
time_t next_interval_time;
int interval_s;
} loop_data;
typedef struct _pcap_queue_element {
capture_src *pcap_src;
union {
struct pcap_pkthdr phdr;
pcapng_block_header_t bh;
} u;
u_char *pd;
} pcap_queue_element;
/*
* This needs to be static, so that the SIGINT handler can clear the "go"
* flag and for saved_shb_idb_lock.
*/
static loop_data global_ld;
/*
* Timeout, in milliseconds, for reads from the stream of captured packets
* from a capture device.
*
* A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
* 64-bit applications, with sub-second timeouts not to work. The bug is
* fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
*/
#if defined(__APPLE__) && defined(__LP64__)
static gboolean need_timeout_workaround;
#define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
#else
#define CAP_READ_TIMEOUT 250
#endif
/*
* Timeout, in microseconds, for reads from the stream of captured packets
* from a pipe. Pipes don't have the same problem that BPF devices do
* in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
* of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
* of the offending versions of Snow Leopard.
*
* On Windows this value is converted to milliseconds and passed to
* WaitForSingleObject. If it's less than 1000 WaitForSingleObject
* will return immediately.
*/
#if defined(_WIN32)
#define PIPE_READ_TIMEOUT 100000
#else
#define PIPE_READ_TIMEOUT 250000
#endif
#define WRITER_THREAD_TIMEOUT 100000 /* usecs */
static void
dumpcap_log_writer(const char *domain, enum ws_log_level level,
struct timespec timestamp,
2022-01-04 01:23:10 +00:00
const char *file, long line, const char *func,
const char *user_format, va_list user_ap,
void *user_data);
/* capture related options */
static capture_options global_capture_opts;
static GPtrArray *capture_comments = NULL;
static gboolean quiet = FALSE;
static gboolean use_threads = FALSE;
static guint64 start_time;
static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
const u_char *pd);
static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
const u_char *pd);
static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
char *secondary_errmsg,
size_t secondary_errmsglen,
const char *fname, int err,
gboolean is_close);
WS_NORETURN static void exit_main(int err);
static void report_new_capture_file(const char *filename);
static void report_packet_count(unsigned int packet_count);
static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
#define MSG_MAX_LENGTH 4096
static void
print_usage(FILE *output)
{
fprintf(output, "\nUsage: dumpcap [options] ...\n");
fprintf(output, "\n");
fprintf(output, "Capture interface:\n");
fprintf(output, " -i <interface>, --interface <interface>\n");
fprintf(output, " name or idx of interface (def: first non-loopback),\n"
" or for remote capturing, use one of these formats:\n"
" rpcap://<host>/<interface>\n"
" TCP@<host>:<port>\n");
fprintf(output, " --ifname <name> name to use in the capture file for a pipe from which\n");
fprintf(output, " we're capturing\n");
fprintf(output, " --ifdescr <description>\n");
fprintf(output, " description to use in the capture file for a pipe\n");
fprintf(output, " from which we're capturing\n");
fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
#else
fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
#endif
fprintf(output, " -p, --no-promiscuous-mode\n");
fprintf(output, " don't capture in promiscuous mode\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
#endif
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
#endif
fprintf(output, " -y <link type>, --linktype <link type>\n");
fprintf(output, " link layer type (def: first appropriate)\n");
fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
fprintf(output, " -L, --list-data-link-types\n");
fprintf(output, " print list of link-layer types of iface and exit\n");
fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
fprintf(output, " -d print generated BPF code for capture filter\n");
fprintf(output, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
fprintf(output, " set channel on wifi interface\n");
fprintf(output, " -S print statistics for each interface once per second\n");
fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
fprintf(output, "\n");
#ifdef HAVE_PCAP_REMOTE
fprintf(output, "RPCAP options:\n");
fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
fprintf(output, " -u use UDP for RPCAP data transfer\n");
fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
#ifdef HAVE_PCAP_SETSAMPLING
fprintf(output, " -m <sampling type> use packet sampling\n");
fprintf(output, " count:NUM - capture one packet of every NUM\n");
fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
#endif
#endif
fprintf(output, "Stop conditions:\n");
fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
fprintf(output, " duration:NUM - stop after NUM seconds\n");
fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
fprintf(output, " files:NUM - stop after NUM files\n");
fprintf(output, " packets:NUM - stop after NUM packets\n");
/*fprintf(output, "\n");*/
fprintf(output, "Output (files):\n");
fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
fprintf(output, " -g enable group read access on the output file(s)\n");
fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
fprintf(output, " interval:NUM - switch to next file when the time is\n");
fprintf(output, " an exact multiple of NUM secs\n");
fprintf(output, " printname:FILE - print filename to FILE when written\n");
fprintf(output, " (can use 'stdout' or 'stderr')\n");
fprintf(output, " -n use pcapng format instead of pcap (default)\n");
fprintf(output, " -P use libpcap format instead of pcapng\n");
fprintf(output, " --capture-comment <comment>\n");
fprintf(output, " add a capture comment to the output file\n");
fprintf(output, " (only for pcapng)\n");
fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
fprintf(output, " (default: %s)\n", g_get_tmp_dir());
fprintf(output, "\n");
2021-06-15 21:50:46 +00:00
ws_log_print_usage(output);
fprintf(output, "\n");
2021-06-15 21:50:46 +00:00
fprintf(output, "Miscellaneous:\n");
fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
fprintf(output, " within dumpcap\n");
fprintf(output, " -t use a separate thread per interface\n");
fprintf(output, " -q don't report packet capture counts\n");
fprintf(output, " -v, --version print version information and exit\n");
fprintf(output, " -h, --help display this help and exit\n");
fprintf(output, "\n");
#ifdef __linux__
fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
fprintf(output, "You might want to enable it by executing:\n");
fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
fprintf(output, "Note that this can make your system less secure!\n");
fprintf(output, "\n");
#endif
fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
fprintf(output, "\n");
fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
}
/*
* Report an error in command-line arguments.
* If we're a capture child, send a message back to the parent, otherwise
* just print it.
*/
static void
dumpcap_cmdarg_err(const char *fmt, va_list ap)
{
if (capture_child) {
gchar *msg;
/* Generate a 'special format' message back to parent */
msg = ws_strdup_vprintf(fmt, ap);
sync_pipe_errmsg_to_parent(2, msg, "");
g_free(msg);
} else {
fprintf(stderr, "dumpcap: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
}
}
/*
* Report additional information for an error in command-line arguments.
* If we're a capture child, send a message back to the parent, otherwise
* just print it.
*/
static void
dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
{
if (capture_child) {
gchar *msg;
msg = ws_strdup_vprintf(fmt, ap);