This repository has been archived by the owner on Feb 1, 2022. It is now read-only.
forked from wireshark/wireshark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dumpcap.c
5798 lines (5262 loc) · 218 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 <gerald@wireshark.org>
* 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 <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 <ui/cmdarg_err.h>
#include <wsutil/strtoi.h>
#include <cli_main.h>
#include <ui/version_info.h>
#include <wsutil/socket.h>
#include <wsutil/wslog.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 <ui/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/ws_assert.h>
#include "capture/ws80211_utils.h"
#include "extcap.h"
/*
* Get information about libpcap format from "wiretap/libpcap.h".
* Get information about pcapng format from "wiretap/pcapng_module.h".
* XXX - can we just use pcap_open_offline() to read the pipe?
*/
#include "wiretap/libpcap.h"
#include "wiretap/pcapng_module.h"
#include "wiretap/pcapng.h"
/**#define DEBUG_DUMPCAP**/
/**#define DEBUG_CHILD_DUMPCAP**/
#ifdef _WIN32
#include "wsutil/win32-utils.h"
#ifdef DEBUG_DUMPCAP
#include <conio.h> /* _getch() */
#endif
#endif
#ifdef DEBUG_CHILD_DUMPCAP
FILE *debug_log; /* for logging debug messages to */
/* a file if DEBUG_CHILD_DUMPCAP */
/* is defined */
#endif
static GAsyncQueue *pcap_queue;
static gint64 pcap_queue_bytes;
static gint64 pcap_queue_packets;
static gint64 pcap_queue_byte_limit = 0;
static gint64 pcap_queue_packet_limit = 0;
static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
static const char *report_capture_filename = NULL; /* capture child file name */
#ifdef _WIN32
static gchar *sig_pipe_name = NULL;
static HANDLE sig_pipe_handle = NULL;
static gboolean signal_pipe_check_running(void);
#endif
#ifdef SIGINFO
static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
#endif /* SIGINFO */
/** Stop a low-level capture (stops the capture child). */
static void capture_loop_stop(void);
/** Close a pipe, or socket if \a from_socket is TRUE */
static void cap_pipe_close(int pipe_fd, gboolean from_socket);
#if defined (__linux__)
/* whatever the deal with pcap_breakloop, linux doesn't support timeouts
* in pcap_dispatch(); on the other hand, select() works just fine there.
* Hence we use a select for that come what may.
*
* XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
* internally, and, with TPACKET_V3, once that's supported, it'll
* support timeouts, at least as I understand the way the code works.
*/
#define MUST_DO_SELECT
#endif
/** init the capture filter */
typedef enum {
INITFILTER_NO_ERROR,
INITFILTER_BAD_FILTER,
INITFILTER_OTHER_ERROR
} initfilter_status_t;
typedef enum {
STATE_EXPECT_REC_HDR,
STATE_READ_REC_HDR,
STATE_EXPECT_DATA,
STATE_READ_DATA
} cap_pipe_state_t;
typedef enum {
PIPOK,
PIPEOF,
PIPERR,
PIPNEXIST
} cap_pipe_err_t;
typedef struct _pcap_pipe_info {
gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
} pcap_pipe_info_t;
typedef struct _pcapng_pipe_info {
pcapng_block_header_t bh; /**< Pcapng general block header when capturing from a pipe */
GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
} pcapng_pipe_info_t;
struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
/*
* A source of packets from which we're capturing.
*/
typedef struct _capture_src {
guint32 received;
guint32 dropped;
guint32 flushed;
pcap_t *pcap_h;
#ifdef MUST_DO_SELECT
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 */
gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
union {
pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
} cap_pipe_info;
#ifdef _WIN32
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 */
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
int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
cap_pipe_state_t cap_pipe_state;
cap_pipe_err_t cap_pipe_err;
#if defined(_WIN32)
GMutex *cap_pipe_read_mtx;
GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
#endif
} capture_src;
typedef struct _saved_idb {
gboolean deleted;
guint interface_id; /* capture_src->interface_id for the associated SHB */
guint8 *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
guint idb_len;
} saved_idb_t;
/*
* Global capture loop state.
*/
typedef struct _loop_data {
/* common */
gboolean go; /**< TRUE as long as we're supposed to keep capturing */
int err; /**< if non-zero, error seen while capturing */
gint packets_captured; /**< Number of packets we have already captured */
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 */
gboolean pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
guint8 *saved_shb; /**< SHB to write when we have one pcapng input */
GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
/* output file(s) */
FILE *pdh;
int save_file_fd;
char *io_buffer; /**< Our IO buffer if we increase the size from the standard size */
guint64 bytes_written; /**< Bytes written for the current file. */
/* autostop conditions */
int packets_written; /**< Packets written for the current file. */
int file_count;
/* ring buffer conditions */
GTimer *file_duration_timer;
time_t next_interval_time;
int interval_s;
} loop_data;
typedef struct _pcap_queue_element {
capture_src *pcap_src;
union {
struct pcap_pkthdr phdr;
pcapng_block_header_t bh;
} u;
u_char *pd;
} pcap_queue_element;
/*
* This needs to be static, so that the SIGINT handler can clear the "go"
* flag and for saved_shb_idb_lock.
*/
static loop_data global_ld;
/*
* Timeout, in milliseconds, for reads from the stream of captured packets
* from a capture device.
*
* A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
* 64-bit applications, with sub-second timeouts not to work. The bug is
* fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
*/
#if defined(__APPLE__) && defined(__LP64__)
static gboolean need_timeout_workaround;
#define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
#else
#define CAP_READ_TIMEOUT 250
#endif
/*
* Timeout, in microseconds, for reads from the stream of captured packets
* from a pipe. Pipes don't have the same problem that BPF devices do
* in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
* of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
* of the offending versions of Snow Leopard.
*
* On Windows this value is converted to milliseconds and passed to
* WaitForSingleObject. If it's less than 1000 WaitForSingleObject
* will return immediately.
*/
#if defined(_WIN32)
#define PIPE_READ_TIMEOUT 100000
#else
#define PIPE_READ_TIMEOUT 250000
#endif
#define WRITER_THREAD_TIMEOUT 100000 /* usecs */
static void
dumpcap_log_writer(const char *domain, enum ws_log_level level,
ws_log_time_t timestamp,
const char *file, int line, const char *func,
const char *user_format, va_list user_ap,
void *user_data);
/* capture related options */
static capture_options global_capture_opts;
static GPtrArray *capture_comments = NULL;
static gboolean quiet = FALSE;
static gboolean use_threads = FALSE;
static guint64 start_time;
static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
const u_char *pd);
static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
const u_char *pd);
static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
char *secondary_errmsg,
size_t secondary_errmsglen,
const char *fname, int err,
gboolean is_close);
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
static void
print_usage(FILE *output)
{
fprintf(output, "\nUsage: dumpcap [options] ...\n");
fprintf(output, "\n");
fprintf(output, "Capture interface:\n");
fprintf(output, " -i <interface>, --interface <interface>\n");
fprintf(output, " name or idx of interface (def: first non-loopback),\n"
" or for remote capturing, use one of these formats:\n"
" rpcap://<host>/<interface>\n"
" TCP@<host>:<port>\n");
fprintf(output, " --ifname <name> name to use in the capture file for a pipe from which\n");
fprintf(output, " we're capturing\n");
fprintf(output, " --ifdescr <description>\n");
fprintf(output, " description to use in the capture file for a pipe\n");
fprintf(output, " from which we're capturing\n");
fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
#else
fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
#endif
fprintf(output, " -p, --no-promiscuous-mode\n");
fprintf(output, " don't capture in promiscuous mode\n");
#ifdef HAVE_PCAP_CREATE
fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
#endif
#ifdef CAN_SET_CAPTURE_BUFFER_SIZE
fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
#endif
fprintf(output, " -y <link type>, --linktype <link type>\n");
fprintf(output, " link layer type (def: first appropriate)\n");
fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
fprintf(output, " -L, --list-data-link-types\n");
fprintf(output, " print list of link-layer types of iface and exit\n");
fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
fprintf(output, " -d print generated BPF code for capture filter\n");
fprintf(output, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
fprintf(output, " set channel on wifi interface\n");
fprintf(output, " -S print statistics for each interface once per second\n");
fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
fprintf(output, "\n");
#ifdef HAVE_PCAP_REMOTE
fprintf(output, "RPCAP options:\n");
fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
fprintf(output, " -u use UDP for RPCAP data transfer\n");
fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
#ifdef HAVE_PCAP_SETSAMPLING
fprintf(output, " -m <sampling type> use packet sampling\n");
fprintf(output, " count:NUM - capture one packet of every NUM\n");
fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
#endif
#endif
fprintf(output, "Stop conditions:\n");
fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
fprintf(output, " duration:NUM - stop after NUM seconds\n");
fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
fprintf(output, " files:NUM - stop after NUM files\n");
fprintf(output, " packets:NUM - stop after NUM packets\n");
/*fprintf(output, "\n");*/
fprintf(output, "Output (files):\n");
fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
fprintf(output, " -g enable group read access on the output file(s)\n");
fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
fprintf(output, " interval:NUM - switch to next file when the time is\n");
fprintf(output, " an exact multiple of NUM secs\n");
fprintf(output, " printname:FILE - print filename to FILE when written\n");
fprintf(output, " (can use 'stdout' or 'stderr')\n");
fprintf(output, " -n use pcapng format instead of pcap (default)\n");
fprintf(output, " -P use libpcap format instead of pcapng\n");
fprintf(output, " --capture-comment <comment>\n");
fprintf(output, " add a capture comment to the output file\n");
fprintf(output, " (only for pcapng)\n");
fprintf(output, "\n");
ws_log_print_usage(output);
fprintf(output, "Miscellaneous:\n");
fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
fprintf(output, " within dumpcap\n");
fprintf(output, " -t use a separate thread per interface\n");
fprintf(output, " -q don't report packet capture counts\n");
fprintf(output, " -v, --version print version information and exit\n");
fprintf(output, " -h, --help display this help and exit\n");
fprintf(output, "\n");
#ifdef __linux__
fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
fprintf(output, "You might want to enable it by executing:\n");
fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
fprintf(output, "Note that this can make your system less secure!\n");
fprintf(output, "\n");
#endif
fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
fprintf(output, "\n");
fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
}
/*
* Report an error in command-line arguments.
* If we're a capture child, send a message back to the parent, otherwise
* just print it.
*/
static void
dumpcap_cmdarg_err(const char *fmt, va_list ap)
{
if (capture_child) {
gchar *msg;
/* Generate a 'special format' message back to parent */
msg = 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();
ws_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
/*
* Platform-dependent suggestions for fixing permissions.
*/
#if defined(__linux__)
#define PLATFORM_PERMISSIONS_SUGGESTION \
"\n\n" \
"On Debian and Debian derivatives such as Ubuntu, if you have " \
"installed Wireshark from a package, try running" \
"\n\n" \
" sudo dpkg-reconfigure wireshark-common" \
"\n\n" \
"selecting \"<Yes>\" in response to the question" \
"\n\n" \
" Should non-superusers be able to capture packets?" \
"\n\n" \
"adding yourself to the \"wireshark\" group by running" \
"\n\n" \
" sudo usermod -a -G wireshark {your username}" \
"\n\n" \
"and then logging out and logging back in again."
#elif defined(__APPLE__)
#define PLATFORM_PERMISSIONS_SUGGESTION \
"\n\n" \
"If you installed Wireshark using the package from wireshark.org, " \
"close this dialog and click on the \"installing ChmodBPF\" link in " \
"\"You can fix this by installing ChmodBPF.\" on the main screen, " \
"and then complete the installation procedure."
#else
#define PLATFORM_PERMISSIONS_SUGGESTION
#endif
static const char *
get_pcap_failure_secondary_error_message(cap_device_open_status open_status,
const char *open_status_str)
{
#ifdef _WIN32
/*
* On Windows, first make sure they *have* Npcap installed.
*/
if (!has_wpcap) {
return
"In order to capture packets, Npcap or WinPcap must be installed. See\n"
"\n"
" https://nmap.org/npcap/\n"
"\n"
"for a downloadable version of Npcap and for instructions on how to\n"
"install it.";
}
#endif
/*
* OK, now just return a largely platform-independent error that might
* have platform-specific suggestions at the end (for example, suggestions
* for how to get permission to capture).
*/
if (open_status == CAP_DEVICE_OPEN_ERR_GENERIC) {
/*
* We don't know what kind of error it is. See if there's a hint
* in the error string; if not, throw all generic suggestions at
* the user.
*/
static const char promisc_failed[] =
"failed to set hardware filter to promiscuous mode";
/*
* Does the error string begin with the error produced by WinPcap
* and Npcap if attempting to set promiscuous mode fails?
* (Note that this string could have a specific error message
* from an NDIS error after the initial part, so we do a prefix
* check rather than an exact match check.)
*/
if (strncmp(open_status_str, promisc_failed, sizeof promisc_failed - 1) == 0) {
/*
* Yes. Suggest that the user turn off promiscuous mode on that
* device.
*/
return
"Please turn off promiscuous mode for this device";
} else {
return
"Please check to make sure you have sufficient permissions, and that you have "
"the proper interface or pipe specified."
PLATFORM_PERMISSIONS_SUGGESTION;
}
} else if (open_status == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
/*
* This is a permissions error, so no need to specify any other
* warnings.
*/
return
"Please check to make sure you have sufficient permissions."
PLATFORM_PERMISSIONS_SUGGESTION;
} else {
/*
* This is not a permissons error, so no need to suggest
* checking permissions.
*/
return
"Please check that you have the proper interface or pipe specified.";
}
}
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)
{
g_snprintf(errmsg, (gulong) errmsg_len,
"The capture session could not be initiated on capture device \"%s\" (%s).",
iface, open_status_str);
g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
get_pcap_failure_secondary_error_message(open_status, open_status_str));
}
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;
}
static gboolean
show_filter_code(capture_options *capture_opts)
{
interface_options *interface_opts;
pcap_t *pcap_h;
cap_device_open_status open_status;
gchar 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;
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_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)) {
g_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. */
pipe_write_block(2, SP_SUCCESS, NULL);
}
return TRUE;
}
/*
* 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);
}
/*
* 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[WS_INET6_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:
printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
break;
case IF_AT_IPv6:
printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
break;
default:
printf("<type unknown %i>", if_addr->ifat_type);
}
}
if (if_info->loopback)
printf("\tloopback");
else
printf("\tnetwork");
printf("\t%s", if_info->extcap);
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, int queries)
{
GList *lt_entry, *ts_entry;
const gchar *desc_str;
if (capture_child) {
/* Let our parent know we succeeded. */
pipe_write_block(2, SP_SUCCESS, NULL);
}
if (queries & CAPS_QUERY_LINK_TYPES) {
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_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)";
printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
desc_str);
}
}
printf("\n");
if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
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)";
printf("%s\t%s\n", timestamp->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)) {
ws_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 = g_new(if_stat_t, 1);
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);
}
if (!machine_readable) {
printf("%-15s %10s %10s\n", "Interface", "Received",
"Dropped");
}
global_ld.go = TRUE;
while (global_ld.go) {
for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
if_stat = (if_stat_t *)stat_entry->data;
pcap_stats(if_stat->pch, &ps);
if (!machine_readable) {
printf("%-15s %10u %10u\n", if_stat->name,
ps.ps_recv, ps.ps_drop);
} else {
printf("%s\t%u\t%u\n", if_stat->name,
ps.ps_recv, ps.ps_drop);
fflush(stdout);
}
}
#ifdef _WIN32
/* If we have a dummy signal pipe check it */
if (!signal_pipe_check_running()) {
global_ld.go = FALSE;
}
Sleep(1 * 1000);
#else
sleep(1);
#endif
}
/* XXX - Not reached. Should we look for 'q' in stdin? */
for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
if_stat = (if_stat_t *)stat_entry->data;
pcap_close(if_stat->pch);
g_free(if_stat->name);
g_free(if_stat);
}
g_list_free(stat_list);
free_interface_list(if_list);