-
Notifications
You must be signed in to change notification settings - Fork 0
/
dumpcap.c
4857 lines (4376 loc) · 179 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
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h> /* for exit() */
#include <glib.h>
#include <string.h>
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#if defined(__APPLE__) && defined(__LP64__)
#include <sys/utsname.h>
#endif
#include <signal.h>
#include <errno.h>
#include <wsutil/cmdarg_err.h>
#include <wsutil/crash_info.h>
#include <wsutil/strtoi.h>
#include <ws_version_info.h>
#ifndef HAVE_GETOPT_LONG
#include "wsutil/wsgetopt.h"
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_LIBCAP
# include <sys/prctl.h>
# include <sys/capability.h>
#endif
#include "ringbuffer.h"
#include "caputils/capture_ifinfo.h"
#include "caputils/capture-pcap-util.h"
#include "caputils/capture-pcap-util-int.h"
#ifdef _WIN32
#include "caputils/capture-wpcap.h"
#endif /* _WIN32 */
#include "writecap/pcapio.h"
#ifdef _WIN32
#include <wsutil/unicode-utils.h>
#endif
#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 <capchild/capture_session.h>
#include <capchild/capture_sync.h>
#include "conditions.h"
#include "capture_stop_conditions.h"
#include "wsutil/tempfile.h"
#include "log.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 "caputils/ws80211_utils.h"
#ifdef HAVE_EXTCAP
#include "extcap.h"
#endif
/*
* 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"
/**#define DEBUG_DUMPCAP**/
/**#define DEBUG_CHILD_DUMPCAP**/
#ifdef _WIN32
#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 */
#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 _U_);
#ifdef __linux__
/*
* Enable kernel BPF JIT compiler if available.
* If any calls fail, just drive on - the JIT compiler might not be
* enabled, but filtering will still work, and it's not clear what
* we could do if the calls fail; should we just report the error
* and not continue to capture, should we report it as a warning, or
* what?
*/
static void
enable_kernel_bpf_jit_compiler(void)
{
int fd;
ssize_t written _U_;
static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
fd = ws_open(file, O_WRONLY);
if (fd < 0)
return;
written = ws_write(fd, "1", strlen("1"));
ws_close(fd);
}
#endif
#if !defined (__linux__)
#ifndef HAVE_PCAP_BREAKLOOP
/*
* We don't have pcap_breakloop(), which is the only way to ensure that
* pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
* won't, if the call to read the next packet or batch of packets is
* is interrupted by a signal on UN*X, just go back and try again to
* read again.
*
* On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
* the signal handler, set a flag to stop capturing; however, without
* a guarantee of that sort, we can't guarantee that we'll stop capturing
* if the read will be retried and won't time out if no packets arrive.
*
* Therefore, on at least some platforms, we work around the lack of
* pcap_breakloop() by doing a select() on the pcap_t's file descriptor
* to wait for packets to arrive, so that we're probably going to be
* blocked in the select() when the signal arrives, and can just bail
* out of the loop at that point.
*
* However, we don't want to do that on BSD (because "select()" doesn't work
* correctly on BPF devices on at least some releases of some flavors of
* BSD), and we don't want to do it on Windows (because "select()" is
* something for sockets, not for arbitrary handles). (Note that "Windows"
* here includes Cygwin; even in its pretend-it's-UNIX environment, we're
* using WinPcap, not a UNIX libpcap.)
*
* Fortunately, we don't need to do it on BSD, because the libpcap timeout
* on BSD times out even if no packets have arrived, so we'll eventually
* exit pcap_dispatch() with an indication that no packets have arrived,
* and will break out of the capture loop at that point.
*
* On Windows, we can't send a SIGINT to stop capturing, so none of this
* applies in any case.
*
* XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
* want to include it if it's not present on this platform, however.
*/
# if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
!defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
!defined(__CYGWIN__)
# define MUST_DO_SELECT
# endif /* avoid select */
#endif /* HAVE_PCAP_BREAKLOOP */
#else /* 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;
/*
* 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
int pcap_fd; /**< pcap file descriptor */
#endif
gboolean pcap_err;
guint interface_id;
GThread *tid;
int snaplen;
int linktype;
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 */
struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
#ifdef _WIN32
HANDLE cap_pipe_h; /**< The handle of the capture pipe */
#endif
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 */
gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
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 */
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
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;
/*
* 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 packet_count; /**< Number of packets we have already captured */
gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
#ifdef SIGINFO
gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
#endif
GArray *pcaps; /**< Array of capture_src's on which we're capturing */
/* output file(s) */
FILE *pdh;
int save_file_fd;
guint64 bytes_written;
guint32 autostop_files;
} loop_data;
typedef struct _pcap_queue_element {
capture_src *pcap_src;
struct pcap_pkthdr phdr;
u_char *pd;
} pcap_queue_element;
/*
* Standard secondary message for unexpected errors.
*/
static const char please_report[] =
"Please report this to the Wireshark developers.\n"
"https://bugs.wireshark.org/\n"
"(This is not a crash; please do not report it as such.)";
/*
* This needs to be static, so that the SIGINT handler can clear the "go"
* flag.
*/
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
console_log_handler(const char *log_domain, GLogLevelFlags log_level,
const char *message, gpointer user_data _U_);
/* capture related options */
static capture_options global_capture_opts;
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_get_errmsg(char *errmsg, int errmsglen, const char *fname,
int err, gboolean is_close);
static void WS_NORETURN 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
/* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
static guint64
create_timestamp(void) {
guint64 timestamp;
#ifdef _WIN32
FILETIME now;
#else
struct timeval now;
#endif
#ifdef _WIN32
/*
* Current time, represented as 100-nanosecond intervals since
* January 1, 1601, 00:00:00 UTC.
*
* I think DWORD might be signed, so cast both parts of "now"
* to guint32 so that the sign bit doesn't get treated specially.
*
* Windows 8 provides GetSystemTimePreciseAsFileTime which we
* might want to use instead.
*/
GetSystemTimeAsFileTime(&now);
timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
(guint32)now.dwLowDateTime;
/*
* Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
* intervals.
*/
timestamp /= 10;
/*
* Subtract difference, in microseconds, between January 1, 1601
* 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
*/
timestamp -= G_GUINT64_CONSTANT(11644473600000000);
#else
/*
* Current time, represented as seconds and microseconds since
* January 1, 1970, 00:00:00 UTC.
*/
gettimeofday(&now, NULL);
/*
* Convert to delta in microseconds.
*/
timestamp = (guint64)(now.tv_sec) * 1000000 +
(guint64)(now.tv_usec);
#endif
return timestamp;
}
static void
print_usage(FILE *output)
{
fprintf(output, "\nUsage: dumpcap [options] ...\n");
fprintf(output, "\n");
fprintf(output, "Capture interface:\n");
fprintf(output, " -i <interface> 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, " -f <capture filter> packet filter in libpcap filter syntax\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
#else
fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
#endif
fprintf(output, " -p don't capture in promiscuous mode\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " -I capture in monitor mode, if available\n");
#endif
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
#endif
fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
fprintf(output, " -D print list of interfaces and exit\n");
fprintf(output, " -L print list of link-layer types of iface and exit\n");
#ifdef HAVE_BPF_IMAGE
fprintf(output, " -d print generated BPF code for capture filter\n");
#endif
fprintf(output, " -k set channel on wifi interface:\n"
" <freq>,[<type>],[<center_freq1>],[<center_freq2>]\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.> ... 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, "\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.> ... 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, " -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, "\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 print version information and exit\n");
fprintf(output, " -h display this help and exit\n");
fprintf(output, "\n");
#ifdef __linux__
fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
fprintf(output, "You might want to reset it\n");
fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\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 = g_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 = g_strdup_vprintf(fmt, ap);
sync_pipe_errmsg_to_parent(2, msg, "");
g_free(msg);
} else {
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
}
}
#ifdef HAVE_LIBCAP
static void
#if 0 /* Set to enable capability debugging */
/* 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) {
cap_t caps = cap_get_proc();
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"%s: EUID: %d Capabilities: %s", pfx,
geteuid(), cap_to_text(caps, NULL));
cap_free(caps);
#else
print_caps(const char *pfx _U_) {
#endif
}
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(const char *open_err_str,
const char *iface,
char *errmsg, size_t errmsg_len,
char *secondary_errmsg,
size_t secondary_errmsg_len)
{
#ifndef _WIN32
const char *libpcap_warn;
static const char ppamsg[] = "can't find PPA for ";
#endif
g_snprintf(errmsg, (gulong) errmsg_len,
"The capture session could not be initiated on interface '%s' (%s).",
iface, open_err_str);
#ifdef _WIN32
if (!has_wpcap) {
g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
"\n"
"In order to capture packets, WinPcap must be installed; see\n"
"\n"
" https://www.winpcap.org/\n"
"\n"
"for a downloadable version of WinPcap and for instructions on how to install\n"
"WinPcap.");
} else {
g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
"\n"
"Please check that \"%s\" is the proper interface.\n"
"\n"
"\n"
"Help can be found on the following pages:\n"
"\n"
" https://wiki.wireshark.org/WinPcap\n"
" https://wiki.wireshark.org/CaptureSetup\n",
iface);
}
#else
/* If we got a "can't find PPA for X" message, warn the user (who
is running dumpcap on HP-UX) that they don't have a version of
libpcap that properly handles HP-UX (libpcap 0.6.x and later
versions, which properly handle HP-UX, say "can't find /dev/dlpi
PPA for X" rather than "can't find PPA for X"). */
if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
libpcap_warn =
"\n\n"
"You are running (T)Wireshark with a version of the libpcap library\n"
"that doesn't handle HP-UX network devices well; this means that\n"
"(T)Wireshark may not be able to capture packets.\n"
"\n"
"To fix this, you should install libpcap 0.6.2, or a later version\n"
"of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
"packaged binary form from the Software Porting And Archive Centre\n"
"for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
"at the URL lists a number of mirror sites.";
else
libpcap_warn = "";
g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
"Please check to make sure you have sufficient permissions, and that you have "
"the proper interface or pipe specified.%s", libpcap_warn);
#endif /* _WIN32 */
}
static gboolean
compile_capture_filter(const char *iface, pcap_t *pcap_h,
struct bpf_program *fcode, const char *cfilter)
{
bpf_u_int32 netnum, netmask;
gchar 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;
}
#ifdef HAVE_BPF_IMAGE
static gboolean
show_filter_code(capture_options *capture_opts)
{
interface_options interface_opts;
pcap_t *pcap_h;
gchar open_err_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;
guint 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_err_str);
if (pcap_h == NULL) {
/* Open failed; get messages */
get_capture_device_open_failure_messages(open_err_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)) {
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. */
pipe_write_block(2, SP_SUCCESS, NULL);
}
return TRUE;
}
#endif
/*
* capture_interface_list() is expected to do the right thing to get
* a list of interfaces.
*
* In most of the programs in the Wireshark suite, "the right thing"
* is to run dumpcap and ask it for the list, because dumpcap may
* be the only program in the suite with enough privileges to get
* the list.
*
* In dumpcap itself, however, we obviously can't run dumpcap to
* ask for the list. Therefore, our capture_interface_list() should
* just call get_interface_list().
*/
GList *
capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
{
return get_interface_list(err, err_str);
}
#define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
/*
* 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 void
print_machine_readable_interfaces(GList *if_list)
{
int i;
GList *if_entry;
if_info_t *if_info;
GSList *addr;
if_addr_t *if_addr;
char addr_str[ADDRSTRLEN];
if (capture_child) {
/* Let our parent know we succeeded. */
pipe_write_block(2, SP_SUCCESS, NULL);
}
i = 1; /* Interface id number */
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;
printf("%d. %s\t", i++, if_info->name);
/*
* Print the contents of the if_entry struct in a parseable format.
* Each if_entry element is tab-separated. Addresses are comma-
* separated.
*/
/* XXX - Make sure our description doesn't contain a tab */
if (if_info->vendor_description != NULL)
printf("%s\t", if_info->vendor_description);
else
printf("\t");
/* XXX - Make sure our friendly name doesn't contain a tab */
if (if_info->friendly_name != NULL)
printf("%s\t", if_info->friendly_name);
else
printf("\t");
printf("%i\t", if_info->type);
for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
addr = g_slist_next(addr)) {
if (addr != g_slist_nth(if_info->addrs, 0))
printf(",");
if_addr = (if_addr_t *)addr->data;
switch(if_addr->ifat_type) {
case IF_AT_IPv4:
if (ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str,
ADDRSTRLEN)) {
printf("%s", addr_str);
} else {
printf("<unknown IPv4>");
}
break;
case IF_AT_IPv6:
if (ws_inet_ntop6(&if_addr->addr.ip6_addr,
addr_str, ADDRSTRLEN)) {
printf("%s", addr_str);
} else {
printf("<unknown IPv6>");
}
break;
default:
printf("<type unknown %i>", if_addr->ifat_type);
}
}
if (if_info->loopback)
printf("\tloopback");
else
printf("\tnetwork");
#ifdef HAVE_EXTCAP
printf("\t%s", if_info->extcap);
#endif
printf("\n");
}
}
/*
* 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(if_capabilities_t *caps)
{
GList *lt_entry;
data_link_info_t *data_link_info;
const gchar *desc_str;
if (capture_child) {
/* Let our parent know we succeeded. */
pipe_write_block(2, SP_SUCCESS, NULL);
}
if (caps->can_set_rfmon)
printf("1\n");
else
printf("0\n");
for (lt_entry = caps->data_link_types; lt_entry != NULL;
lt_entry = g_list_next(lt_entry)) {
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)";
printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
desc_str);
}
}
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(gboolean machine_readable)
{
GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
if_info_t *if_info;
if_stat_t *if_stat;
int err;
gchar *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");
else {
cmdarg_err("%s", err_str);
g_free(err_str);
}
return err;
}
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;
#ifdef __linux__
/* On Linux nf* interfaces don't collect stats properly and don't allows multiple
* connections. We avoid collecting stats on them.
*/
if (!strncmp(if_info->name, "nf", 2)) {
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
if_info->name);
continue;
}
#endif
#ifdef HAVE_PCAP_OPEN
pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
#else
pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
#endif
if (pch) {
if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
if_stat->name = g_strdup(if_info->name);
if_stat->pch = pch;
stat_list = g_list_append(stat_list, if_stat);
}
}
if (!stat_list) {
cmdarg_err("There are no interfaces on which a capture can be done");
return 2;
}
if (capture_child) {
/* Let our parent know we succeeded. */
pipe_write_block(2, SP_SUCCESS, NULL);
}