forked from wireshark/wireshark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dumpcap.c
6293 lines (5716 loc) · 238 KB
/
dumpcap.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* dumpcap.c
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include <config.h>
#define WS_LOG_DOMAIN LOG_DOMAIN_CAPCHILD
#include <stdio.h>
#include <stdlib.h> /* for exit() */
#include <glib.h>
#include <string.h>
#include <ws_exit_codes.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>
#include <wsutil/array.h>
#include <wsutil/cmdarg_err.h>
#include <wsutil/strtoi.h>
#include <cli_main.h>
#include <wsutil/version_info.h>
#include <wsutil/socket.h>
#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
#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"
#include <wsutil/json_dumper.h>
#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 these for extra logging. Note that when dumpcap is spawned as
* a child process, logs are sent to the parent via the sync pipe.
* The parent will pass along the Capchild domain log level settings,
* so "--log-debug Capchild" or "--log-level debug" can be used to get
* debugging from dumpcap sent to the parent.
*/
//#define DEBUG_DUMPCAP /* Waits for keypress on quitting on Windows */
//#define DEBUG_CHILD_DUMPCAP /* Writes logs to file */
#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 */
#include <stdarg.h> /* va_copy */
#endif
static GAsyncQueue *pcap_queue;
static int64_t pcap_queue_bytes;
static int64_t pcap_queue_packets;
static int64_t pcap_queue_byte_limit;
static int64_t pcap_queue_packet_limit;
static bool capture_child; /* false: standalone call, true: this is an Wireshark capture child */
static const char *report_capture_filename; /* capture child file name */
#ifdef _WIN32
static char *sig_pipe_name;
static HANDLE sig_pipe_handle;
static bool signal_pipe_check_running(void);
#endif
static int sync_pipe_fd = 2;
#ifdef ENABLE_ASAN
/* This has public visibility so that if compiled with shared libasan (the
* gcc default) function interposition occurs.
*/
WS_DLL_PUBLIC int
__lsan_is_turned_off(void)
{
/* If we're in capture child mode, don't run a LSan report and
* send it to stderr, because it isn't properly formatted for
* the sync pipe.
* We could, if debugging variables are set, send the reports
* elsewhere instead, by calling __sanitizer_set_report_path()
* or __sanitizer_set_report_fd()
*/
if (capture_child) {
return 1;
}
#ifdef HAVE_LIBCAP
/* LSan dies with a fatal error without explanation if it can't ptrace.
* Normally, the "dumpable" attribute (which also controls ptracing)
* is set to 1 (SUID_DUMP_USER, process is dumpable.) However, it is
* reset to the current value in /proc/sys/fs/suid_dumpable in the
* following circumstances: euid/egid changes, fsuid/fsgid changes,
* execve of a setuid or setgid program that changes the euid or egid,
* execve of a program with capabilities exceeding those already
* permitted for the process.
*
* Unless we're running as root, one of those applies to dumpcap.
*
* The default value of /proc/sys/fs/suid_dumpable is 0, SUID_DUMP_DISABLE.
* In such a case, LeakSanitizer temporarily sets the value to 1 to
* allow ptracing, and then sets it back to 0.
*
* Another possible value, used by Ubuntu, Fedora, etc., is 2,
* which creates dumps readable by root only. For security reasons,
* unprivileged programs are not allowed to change the value to 2.
* (See https://nvd.nist.gov/vuln/detail/CVE-2006-2451 )
*
* LSan does not check for the value 2 and change dumpable to 1 in that
* case, possibly because if it did it could not change it back to 2
* and would have to either leave the process dumpable or change it to 0.
*
* The usual way to control the family of sanitizers is through environment
* variables. However, complicating things, changing the dumpable attribute
* to 0 or 2 changes the ownership of files in /proc/[pid] (including
* /proc/self ) to root:root, in particular /proc/[pid]/environ, and so
* ASAN_OPTIONS=detect_leaks=0 has no effect. (Unless the process has
* CAP_SYS_PTRACE, which allows tracing of any process, but that's also
* a security risk and we'll have dropped that with other privileges.)
*
* So if prctl(PR_GET_DUMPABLE) returns 2, we know that the process will
* die with a fatal error if it attempts to run LSan, so don't.
*
* See proc(5), prctl(2), ptrace(2), and
* https://github.com/google/sanitizers/issues/1306
* https://github.com/llvm/llvm-project/issues/55944
*/
if (prctl(PR_GET_DUMPABLE) == 2) {
ws_debug("Not running LeakSanitizer because /proc/sys/fs/suid_dumpable is 2");
return 1;
}
#endif
return 0;
}
WS_DLL_PUBLIC const char*
__asan_default_options(void)
{
/* By default don't override our exit code if there's a leak or error.
* We particularly don't want to do this if running as a capture child,
* because capture/capture_sync doesn't expect the ASan exit codes.
*/
return "exitcode=0";
}
#endif
#ifdef SIGINFO
static bool infodelay; /* if true, don't print capture info in SIGINFO handler */
static bool 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, bool 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 {
bool 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 {
uint32_t received;
uint32_t dropped;
uint32_t flushed;
pcap_t *pcap_h;
#ifdef MUST_DO_SELECT
int pcap_fd; /**< pcap file descriptor */
#endif
bool pcap_err;
unsigned interface_id;
unsigned idb_id; /**< If from_pcapng is false, the output IDB interface ID. Otherwise the mapping in src_iface_to_global is used. */
GThread *tid;
int snaplen;
int linktype;
bool ts_nsec; /**< true if we're using nanosecond precision. */
/**< capture pipe (unix only "input file") */
bool from_cap_pipe; /**< true if we are capturing data from a capture pipe */
bool from_cap_socket; /**< true if we're capturing from socket */
bool 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
HANDLE cap_pipe_h; /**< The handle of the capture pipe */
#endif
int cap_pipe_fd; /**< the file descriptor of the capture pipe */
bool 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 */
unsigned cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
#if defined(_WIN32)
char * cap_pipe_buf; /**< Pointer to the buffer we read into */
DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
#else
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 {
bool deleted;
unsigned interface_id; /* capture_src->interface_id for the associated SHB */
uint8_t *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
unsigned idb_len;
} saved_idb_t;
/*
* Global capture loop state.
*/
typedef struct _loop_data {
/* common */
bool go; /**< true as long as we're supposed to keep capturing */
int err; /**< if non-zero, error seen while capturing */
int packets_captured; /**< Number of packets we have already captured */
unsigned inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
#ifdef SIGINFO
bool report_packet_count; /**< Set by SIGINFO handler; print packet count */
#endif
GArray *pcaps; /**< Array of capture_src's on which we're capturing */
bool pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
uint8_t *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 */
uint64_t 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;
uint8_t *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 bool 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,
const char *file, long line, const char *func,
const char *fatal_msg, ws_log_manifest_t *mft,
const char *user_format, va_list user_ap,
void *user_data);
/* capture related options */
static capture_options global_capture_opts;
static GPtrArray *capture_comments;
static bool quiet;
static bool really_quiet;
static bool use_threads;
static uint64_t start_time;
static void capture_loop_write_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
const uint8_t *pd);
static void capture_loop_queue_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
const uint8_t *pd);
static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd);
static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd);
static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
char *secondary_errmsg,
size_t secondary_errmsglen,
const char *fname, int err,
bool 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(uint32_t received, uint32_t pcap_drops, uint32_t drops, uint32_t flushed, uint32_t ps_ifdrop, char *name);
static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
static void report_cfilter_error(capture_options *capture_opts, unsigned 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"
#ifdef HAVE_PCAP_REMOTE
" or for remote capturing, use one of these formats:\n"
" rpcap://<host>/<interface>\n"
#else
" or for remote capturing, use this format:\n"
#endif
" 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, " --update-interval interval between updates with new packets (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
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");
ws_log_print_usage(output);
fprintf(output, "\n");
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) {
char *msg;
/* Generate a 'special format' message back to parent */
msg = ws_strdup_vprintf(fmt, ap);
sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, 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) {
char *msg;
msg = ws_strdup_vprintf(fmt, ap);
sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
g_free(msg);
} else {
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
}
}
#ifdef HAVE_LIBCAP
static void
/* see 'man cap_to_text()' for explanation of output */
/* '=' means 'all= ' ie: no capabilities */
/* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
/* .... */
print_caps(const char *pfx) {
if (ws_log_msg_is_active(WS_LOG_DOMAIN, LOG_LEVEL_NOISY)) {
cap_t caps = cap_get_proc();
char *caps_text = cap_to_text(caps, NULL);
ws_noisy("%s: EUID: %d Capabilities: %s", pfx, geteuid(), caps_text);
cap_free(caps_text);
cap_free(caps);
}
}
static void
relinquish_all_capabilities(void)
{
/* Drop any and all capabilities this process may have. */
/* Allowed whether or not process has any privileges. */
cap_t caps = cap_init(); /* all capabilities initialized to off */
print_caps("Pre-clear");
if (cap_set_proc(caps)) {
cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
}
print_caps("Post-clear");
cap_free(caps);
}
#endif
static void
get_capture_device_open_failure_messages(cap_device_open_status open_status,
const char *open_status_str,
const char *iface,
char *errmsg, size_t errmsg_len,
char *secondary_errmsg,
size_t secondary_errmsg_len)
{
switch (open_status) {
case CAP_DEVICE_OPEN_ERROR_NO_SUCH_DEVICE:
snprintf(errmsg, errmsg_len,
"There is no device named \"%s\".\n(%s)",
iface, open_status_str);
break;
case CAP_DEVICE_OPEN_ERROR_RFMON_NOTSUP:
snprintf(errmsg, errmsg_len,
"Capturing in monitor mode is not supported on device \"%s\".\n(%s)",
iface, open_status_str);
break;
case CAP_DEVICE_OPEN_ERROR_PERM_DENIED:
snprintf(errmsg, errmsg_len,
"You do not have permission to capture on device \"%s\".\n(%s)",
iface, open_status_str);
break;
case CAP_DEVICE_OPEN_ERROR_IFACE_NOT_UP:
snprintf(errmsg, errmsg_len,
"Device \"%s\" is not up.\n(%s)",
iface, open_status_str);
break;
case CAP_DEVICE_OPEN_ERROR_PROMISC_PERM_DENIED:
snprintf(errmsg, errmsg_len,
"You do not have permission to capture in promiscuous mode on device \"%s\".\n(%s)",
iface, open_status_str);
break;
case CAP_DEVICE_OPEN_ERROR_OTHER:
default:
snprintf(errmsg, errmsg_len,
"The capture session could not be initiated on capture device \"%s\".\n(%s)",
iface, open_status_str);
break;
}
snprintf(secondary_errmsg, secondary_errmsg_len, "%s",
get_pcap_failure_secondary_error_message(open_status, open_status_str));
}
static bool
compile_capture_filter(const char *iface, pcap_t *pcap_h,
struct bpf_program *fcode, const char *cfilter)
{
bpf_u_int32 netnum, netmask;
char lookup_net_err_str[PCAP_ERRBUF_SIZE];
if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
/*
* Well, we can't get the netmask for this interface; it's used
* only for filters that check for broadcast IP addresses, so
* we just punt and use 0. It might be nice to warn the user,
* but that's a pain in a GUI application, as it'd involve popping
* up a message box, and it's not clear how often this would make
* a difference (only filters that check for IP broadcast addresses
* use the netmask).
*/
/*cmdarg_err(
"Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
netmask = 0;
}
/*
* Sigh. Older versions of libpcap don't properly declare the
* third argument to pcap_compile() as a const pointer. Cast
* away the warning.
*/
DIAG_OFF(cast-qual)
if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
return false;
DIAG_ON(cast-qual)
return true;
}
static bool
show_filter_code(capture_options *capture_opts)
{
interface_options *interface_opts;
pcap_t *pcap_h;
cap_device_open_status open_status;
char open_status_str[PCAP_ERRBUF_SIZE];
char errmsg[MSG_MAX_LENGTH+1];
char secondary_errmsg[MSG_MAX_LENGTH+1];
struct bpf_program fcode;
struct bpf_insn *insn;
u_int i;
unsigned j;
for (j = 0; j < capture_opts->ifaces->len; j++) {
interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
pcap_h = open_capture_device(capture_opts, interface_opts,
CAP_READ_TIMEOUT, &open_status, &open_status_str);
if (pcap_h == NULL) {
/* Open failed; get messages */
get_capture_device_open_failure_messages(open_status, open_status_str,
interface_opts->name,
errmsg, sizeof errmsg,
secondary_errmsg,
sizeof secondary_errmsg);
/* And report them */
report_capture_error(errmsg, secondary_errmsg);
return false;
}
/* Set the link-layer type. */
if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
errmsg, sizeof errmsg,
secondary_errmsg, sizeof secondary_errmsg)) {
pcap_close(pcap_h);
report_capture_error(errmsg, secondary_errmsg);
return false;
}
/* OK, try to compile the capture filter. */
if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
interface_opts->cfilter)) {
snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_h));
pcap_close(pcap_h);
report_cfilter_error(capture_opts, j, errmsg);
return false;
}
pcap_close(pcap_h);
/* Now print the filter code. */
insn = fcode.bf_insns;
for (i = 0; i < fcode.bf_len; insn++, i++)
printf("%s\n", bpf_image(insn, i));
}
/* If not using libcap: we now can now set euid/egid to ruid/rgid */
/* to remove any suid privileges. */
/* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
/* (euid/egid have already previously been set to ruid/rgid. */
/* (See comment in main() for details) */
#ifndef HAVE_LIBCAP
relinquish_special_privs_perm();
#else
relinquish_all_capabilities();
#endif
if (capture_child) {
/* Let our parent know we succeeded. */
sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
}
return true;
}
static void
print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries);
/*
* Output a machine readable list of the interfaces
* This list is retrieved by the sync_interface_list_open() function
* The actual output of this function can be viewed with the command "dumpcap -D -Z none"
*/
static int
print_machine_readable_interfaces(GList *if_list, int caps_queries, bool print_statistics)
{
GList *if_entry;
if_info_t *if_info;
GSList *addr;
if_addr_t *if_addr;
char addr_str[WS_INET6_ADDRSTRLEN];
int status;
json_dumper dumper = {
.output_string = g_string_new(NULL),
.flags = JSON_DUMPER_FLAGS_NO_DEBUG,
// Don't abort on failure
};
json_dumper_begin_array(&dumper);
/*
* Print the contents of the if_entry struct in a parseable format (JSON)
*/
for (if_entry = g_list_first(if_list); if_entry != NULL;
if_entry = g_list_next(if_entry)) {
if_info = (if_info_t *)if_entry->data;
json_dumper_begin_object(&dumper);
json_dumper_set_member_name(&dumper, if_info->name);
json_dumper_begin_object(&dumper);
json_dumper_set_member_name(&dumper, "friendly_name");
json_dumper_value_string(&dumper, if_info->friendly_name);
json_dumper_set_member_name(&dumper, "vendor_description");
json_dumper_value_string(&dumper, if_info->vendor_description);
json_dumper_set_member_name(&dumper, "type");
json_dumper_value_anyf(&dumper, "%i", if_info->type);
json_dumper_set_member_name(&dumper, "addrs");
json_dumper_begin_array(&dumper);
for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
addr = g_slist_next(addr)) {
if_addr = (if_addr_t *)addr->data;
switch(if_addr->ifat_type) {
case IF_AT_IPv4:
json_dumper_value_string(&dumper, ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
break;
case IF_AT_IPv6:
json_dumper_value_string(&dumper, ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
break;
default:
json_dumper_value_anyf(&dumper, "<type unknown %i>", if_addr->ifat_type);
}
}
json_dumper_end_array(&dumper);
json_dumper_set_member_name(&dumper, "loopback");
json_dumper_value_anyf(&dumper, "%s", if_info->loopback ? "true" : "false");
json_dumper_set_member_name(&dumper, "extcap");
json_dumper_value_string(&dumper, if_info->extcap);
if (if_info->caps && caps_queries) {
json_dumper_set_member_name(&dumper, "caps");
json_dumper_begin_object(&dumper);
print_machine_readable_if_capabilities(&dumper, if_info->caps, caps_queries);
json_dumper_end_object(&dumper);
}
json_dumper_end_object(&dumper);
json_dumper_end_object(&dumper);
}
json_dumper_end_array(&dumper);
if (json_dumper_finish(&dumper)) {
status = 0;
if (capture_child) {
if (print_statistics) {
sync_pipe_write_string_msg(sync_pipe_fd, SP_IFACE_LIST, dumper.output_string->str);
} else {
/* Let our parent know we succeeded. */
sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
printf("%s", dumper.output_string->str);
}
} else {
printf("%s", dumper.output_string->str);
}
} else {
status = 2;
if (capture_child) {
sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
} else {
cmdarg_err("Unexpected JSON error");
}
}
g_string_free(dumper.output_string, TRUE);
return status;
}
/*
* If you change the machine-readable output format of this function,
* you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
*/
static void
print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries)
{
GList *lt_entry, *ts_entry;
const char *desc_str;
json_dumper_set_member_name(dumper, "status");
json_dumper_value_anyf(dumper, "%i", caps->status);
if (caps->primary_msg) {
json_dumper_set_member_name(dumper, "primary_msg");
json_dumper_value_string(dumper, caps->primary_msg);
}
if (queries & CAPS_QUERY_LINK_TYPES) {
json_dumper_set_member_name(dumper, "rfmon");
json_dumper_value_anyf(dumper, "%s", caps->can_set_rfmon ? "true" : "false");
json_dumper_set_member_name(dumper, "data_link_types");
json_dumper_begin_array(dumper);
for (lt_entry = caps->data_link_types; lt_entry != NULL;
lt_entry = g_list_next(lt_entry)) {
data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
if (data_link_info->description != NULL)
desc_str = data_link_info->description;
else
desc_str = "(not supported)";
json_dumper_begin_object(dumper);
json_dumper_set_member_name(dumper, "dlt");
json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
json_dumper_set_member_name(dumper, "name");
json_dumper_value_string(dumper, data_link_info->name);
json_dumper_set_member_name(dumper, "description");
json_dumper_value_string(dumper, desc_str);
json_dumper_end_object(dumper);
}
json_dumper_end_array(dumper);
json_dumper_set_member_name(dumper, "data_link_types_rfmon");
json_dumper_begin_array(dumper);
for (lt_entry = caps->data_link_types_rfmon; lt_entry != NULL;
lt_entry = g_list_next(lt_entry)) {
data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
if (data_link_info->description != NULL)
desc_str = data_link_info->description;
else
desc_str = "(not supported)";
json_dumper_begin_object(dumper);
json_dumper_set_member_name(dumper, "dlt");
json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
json_dumper_set_member_name(dumper, "name");
json_dumper_value_string(dumper, data_link_info->name);
json_dumper_set_member_name(dumper, "description");
json_dumper_value_string(dumper, desc_str);
json_dumper_end_object(dumper);
}
json_dumper_end_array(dumper);
}
if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
json_dumper_set_member_name(dumper, "timestamp_types");
json_dumper_begin_array(dumper);
for (ts_entry = caps->timestamp_types; ts_entry != NULL;
ts_entry = g_list_next(ts_entry)) {
timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
if (timestamp->description != NULL)
desc_str = timestamp->description;
else
desc_str = "(none)";
json_dumper_begin_object(dumper);
json_dumper_set_member_name(dumper, "name");
json_dumper_value_string(dumper, timestamp->name);
json_dumper_set_member_name(dumper, "description");
json_dumper_value_string(dumper, desc_str);
json_dumper_end_object(dumper);
}
json_dumper_end_array(dumper);
}
}
typedef struct {
char *name;
pcap_t *pch;
} if_stat_t;
/* Print the number of packets captured for each interface until we're killed. */
static int
print_statistics_loop(bool machine_readable)
{
GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
if_info_t *if_info;
if_stat_t *if_stat;
int err;
char *err_str;
pcap_t *pch;
char errbuf[PCAP_ERRBUF_SIZE];
struct pcap_stat ps;
if_list = get_interface_list(&err, &err_str);
if (if_list == NULL) {
if (err == 0) {
cmdarg_err("There are no interfaces on which a capture can be done");