-
Notifications
You must be signed in to change notification settings - Fork 0
/
dumpcap.c
5229 lines (4724 loc) · 192 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_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.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>
#ifdef HAVE_LIBZ
#include <zlib.h> /* to get the libz version number */
#endif
#include <wsutil/cmdarg_err.h>
#include <wsutil/crash_info.h>
#include <wsutil/copyright_info.h>
#include <wsutil/ws_version_info.h>
#ifndef HAVE_GETOPT
#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 "version_info.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 "pcapio.h"
#ifdef _WIN32
#include "caputils/capture-wpcap.h"
#include <wsutil/unicode-utils.h>
#endif
#ifndef _WIN32
#include <sys/un.h>
#endif
#ifdef NEED_INET_V6DEFS_H
# include "wsutil/inet_v6defs.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/os_version_info.h"
#include "caputils/ws80211_utils.h"
/*
* Get information about libpcap format from "wiretap/libpcap.h".
* XXX - can we just use pcap_open_offline() to read the pipe?
*/
#include "wiretap/libpcap.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 = write(fd, "1", strlen("1"));
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;
typedef struct _pcap_options {
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 */
#if defined(_WIN32)
char * cap_pipe_buf; /**< Pointer to the data 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
} pcap_options;
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;
/* output file(s) */
FILE *pdh;
int save_file_fd;
guint64 bytes_written;
guint32 autostop_files;
} loop_data;
typedef struct _pcap_queue_element {
pcap_options *pcap_opts;
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"
"http://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 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_opts_p, const struct pcap_pkthdr *phdr,
const u_char *pd);
static void capture_loop_queue_packet_cb(u_char *pcap_opts_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_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
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");
fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
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
#if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
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 <freq>,[<type>]\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");
}
static void
show_version(GString *comp_info_str, GString *runtime_info_str)
{
printf("Dumpcap (Wireshark) %s\n"
"\n"
"%s"
"\n"
"%s"
"\n"
"%s",
get_ws_vcs_version_info(), get_copyright_info(), comp_info_str->str, runtime_info_str->str);
}
/*
* 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 pcap_t *
open_capture_device(capture_options *capture_opts
#ifndef HAVE_PCAP_SET_TSTAMP_PRECISION
_U_
#endif
,
interface_options *interface_opts,
char (*open_err_str)[PCAP_ERRBUF_SIZE])
{
pcap_t *pcap_h;
#ifdef HAVE_PCAP_CREATE
int err;
#endif
#if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
struct pcap_rmtauth auth;
#endif
/* Open the network interface to capture from it.
Some versions of libpcap may put warnings into the error buffer
if they succeed; to tell if that's happened, we have to clear
the error buffer, and check if it's still a null string. */
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
(*open_err_str)[0] = '\0';
#if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
/*
* If we're opening a remote device, use pcap_open(); that's currently
* the only open routine that supports remote devices.
*/
if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
auth.username = interface_opts->auth_username;
auth.password = interface_opts->auth_password;
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
interface_opts->datatx_udp, interface_opts->nocap_rpcap);
pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
/* flags */
(interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
(interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
(interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
CAP_READ_TIMEOUT, &auth, *open_err_str);
if (pcap_h == NULL) {
/* Error - did pcap actually supply an error message? */
if ((*open_err_str)[0] == '\0') {
/* Work around known WinPcap bug wherein no error message is
filled in on a failure to open an rpcap: URL. */
g_strlcpy(*open_err_str,
"Unknown error (pcap bug; actual error cause not reported)",
sizeof *open_err_str);
}
}
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"pcap_open() returned %p.", (void *)pcap_h);
} else
#endif
{
/*
* If we're not opening a remote device, use pcap_create() and
* pcap_activate() if we have them, so that we can set the buffer
* size, otherwise use pcap_open_live().
*/
#ifdef HAVE_PCAP_CREATE
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"Calling pcap_create() using %s.", interface_opts->name);
pcap_h = pcap_create(interface_opts->name, *open_err_str);
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"pcap_create() returned %p.", (void *)pcap_h);
if (pcap_h != NULL) {
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
pcap_set_snaplen(pcap_h, interface_opts->snaplen);
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
/*
* If we're writing pcap-ng files, try to enable
* nanosecond-resolution capture; any code that
* can read pcap-ng files must be able to handle
* nanosecond-resolution time stamps.
*
* If we're writing pcap files, don't try to enable
* nanosecond-resolution capture, as not all code
* that reads pcap files recognizes the nanosecond-
* resolution pcap file magic number.
*/
if (capture_opts->use_pcapng) {
/*
* The only errors this is documenting as returning
* are PCAP_ERROR_TSTAMP_PRECISION_NOTSUP, which just
* means we can't do nanosecond precision on this adapter,
* in which case we just live with whatever resolution
* we get by default, and PCAP_ERROR_ACTIVATED, which
* can't happen as we haven't activated the pcap_t yet.
*/
pcap_set_tstamp_precision(pcap_h, PCAP_TSTAMP_PRECISION_NANO);
}
#endif
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"buffersize %d.", interface_opts->buffer_size);
if (interface_opts->buffer_size != 0) {
pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
}
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"monitor_mode %d.", interface_opts->monitor_mode);
if (interface_opts->monitor_mode)
pcap_set_rfmon(pcap_h, 1);
err = pcap_activate(pcap_h);
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"pcap_activate() returned %d.", err);
if (err < 0) {
/* Failed to activate, set to NULL */
if (err == PCAP_ERROR)
g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
else
g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
pcap_close(pcap_h);
pcap_h = NULL;
}
}
#else
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
interface_opts->promisc_mode, CAP_READ_TIMEOUT,
*open_err_str);
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
"pcap_open_live() returned %p.", (void *)pcap_h);
#endif
}
g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
return pcap_h;
}
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"
" http://www.winpcap.org/\n"
"\n"
"or the mirror at\n"
"\n"
" http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
"\n"
"or the mirror at\n"
"\n"
" http://winpcap.cs.pu.edu.tw/\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 at:\n"
"\n"
" http://wiki.wireshark.org/WinPcap\n"
" http://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 */
}
/* Set the data link type on a pcap. */
static gboolean
set_pcap_linktype(pcap_t *pcap_h, int linktype, char *name,
char *errmsg, size_t errmsg_len,
char *secondary_errmsg, size_t secondary_errmsg_len)
{
char *set_linktype_err_str;
if (linktype == -1)
return TRUE; /* just use the default */
#ifdef HAVE_PCAP_SET_DATALINK
if (pcap_set_datalink(pcap_h, linktype) == 0)
return TRUE; /* no error */
set_linktype_err_str = pcap_geterr(pcap_h);
#else
/* Let them set it to the type it is; reject any other request. */
if (get_pcap_linktype(pcap_h, name) == linktype)
return TRUE; /* no error */
set_linktype_err_str =
"That DLT isn't one of the DLTs supported by this device";
#endif
g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type on interface '%s' (%s).",
name, set_linktype_err_str);
/*
* If the error isn't "XXX is not one of the DLTs supported by this device",
* tell the user to tell the Wireshark developers about it.
*/
if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
else
secondary_errmsg[0] = '\0';
return FALSE;
}
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.
*/
if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
return FALSE;
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, &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_linktype(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.
*