-
Notifications
You must be signed in to change notification settings - Fork 861
/
Copy pathtcpdump.c
3178 lines (2882 loc) · 82 KB
/
tcpdump.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
/*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Support for splitting captures into multiple files with a maximum
* file size:
*
* Copyright (c) 2001
* Seth Webster <swebster@sst.ll.mit.edu>
*/
/*
* tcpdump - dump traffic on a network
*
* First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
* Mercilessly hacked and occasionally improved since then via the
* combined efforts of Van, Steve McCanne and Craig Leres of LBL.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/*
* Some older versions of Mac OS X may ship pcap.h from libpcap 0.6 with a
* libpcap based on 0.8. That means it has pcap_findalldevs() but the
* header doesn't define pcap_if_t, meaning that we can't actually *use*
* pcap_findalldevs().
*/
#ifdef HAVE_PCAP_FINDALLDEVS
#ifndef HAVE_PCAP_IF_T
#undef HAVE_PCAP_FINDALLDEVS
#endif
#endif
#include "netdissect-stdinc.h"
/*
* This must appear after including netdissect-stdinc.h, so that _U_ is
* defined.
*/
#ifndef lint
static const char copyright[] _U_ =
"@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
The Regents of the University of California. All rights reserved.\n";
#endif
#include <sys/stat.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_LIBCRYPTO
#include <openssl/crypto.h>
#endif
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
#include "missing/getopt_long.h"
#endif
/* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
* to compile if <pcap.h> has already been included; including the headers
* in the opposite order works fine.
*/
#ifdef HAVE_CAPSICUM
#include <sys/capsicum.h>
#include <sys/ioccom.h>
#include <net/bpf.h>
#include <libgen.h>
#ifdef HAVE_CASPER
#include <libcasper.h>
#include <casper/cap_dns.h>
#include <sys/nv.h>
#endif /* HAVE_CASPER */
#endif /* HAVE_CAPSICUM */
#ifdef HAVE_PCAP_OPEN
/*
* We found pcap_open() in the capture library, so we'll be using
* the remote capture APIs; define PCAP_REMOTE before we include pcap.h,
* so we get those APIs declared, and the types and #defines that they
* use defined.
*
* WinPcap's headers require that PCAP_REMOTE be defined in order to get
* remote-capture APIs declared and types and #defines that they use
* defined.
*
* (Versions of libpcap with those APIs, and thus Npcap, which is based on
* those versions of libpcap, don't require it.)
*/
#define HAVE_REMOTE
#endif
#include <pcap.h>
#include <signal.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <pwd.h>
#include <grp.h>
#endif /* _WIN32 */
/* capabilities convenience library */
/* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
* If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
* Thus, the later tests are done only on HAVE_LIBCAP_NG.
*/
#ifdef HAVE_LIBCAP_NG
#ifdef HAVE_CAP_NG_H
#include <cap-ng.h>
#else
#undef HAVE_LIBCAP_NG
#endif /* HAVE_CAP_NG_H */
#endif /* HAVE_LIBCAP_NG */
#ifdef __FreeBSD__
#include <sys/sysctl.h>
#endif /* __FreeBSD__ */
#include "netdissect.h"
#include "interface.h"
#include "addrtoname.h"
#include "machdep.h"
#include "pcap-missing.h"
#include "ascii_strcasecmp.h"
#include "print.h"
#include "fptype.h"
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#if defined(SIGINFO)
#define SIGNAL_REQ_INFO SIGINFO
#elif defined(SIGUSR1)
#define SIGNAL_REQ_INFO SIGUSR1
#endif
#if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2)
#define SIGNAL_FLUSH_PCAP SIGUSR2
#endif
#if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
static int Bflag; /* buffer size */
#endif
#ifdef HAVE_PCAP_DUMP_FTELL64
static int64_t Cflag; /* rotate dump files after this many bytes */
#else
static long Cflag; /* rotate dump files after this many bytes */
#endif
static int Cflag_count; /* Keep track of which file number we're writing */
#ifdef HAVE_PCAP_FINDALLDEVS
static int Dflag; /* list available devices and exit */
#endif
#ifdef HAVE_PCAP_FINDALLDEVS_EX
static char *remote_interfaces_source; /* list available devices from this source and exit */
#endif
/*
* This is exported because, in some versions of libpcap, if libpcap
* is built with optimizer debugging code (which is *NOT* the default
* configuration!), the library *imports*(!) a variable named dflag,
* under the expectation that tcpdump is exporting it, to govern
* how much debugging information to print when optimizing
* the generated BPF code.
*
* This is a horrible hack; newer versions of libpcap don't import
* dflag but, instead, *if* built with optimizer debugging code,
* *export* a routine to set that flag.
*/
extern int dflag;
int dflag; /* print filter code */
static int Gflag; /* rotate dump files after this many seconds */
static int Gflag_count; /* number of files created with Gflag rotation */
static time_t Gflag_time; /* The last time_t the dump file was rotated. */
static int Lflag; /* list available data link types and exit */
static int Iflag; /* rfmon (monitor) mode */
#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
static int Jflag; /* list available time stamp types */
static int jflag = -1; /* packet time stamp source */
#endif
static int lflag; /* line-buffered output */
static int pflag; /* don't go promiscuous */
#ifdef HAVE_PCAP_SETDIRECTION
static int Qflag = -1; /* restrict captured packet by send/receive direction */
#endif
#ifdef HAVE_PCAP_DUMP_FLUSH
static int Uflag; /* "unbuffered" output of dump files */
#endif
static int Wflag; /* recycle output files after this number of files */
static int WflagChars;
static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
static int timeout = 1000; /* default timeout = 1000 ms = 1 s */
#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
static int immediate_mode;
#endif
static int count_mode;
static int infodelay;
static int infoprint;
char *program_name;
#ifdef HAVE_CASPER
cap_channel_t *capdns;
#endif
/* Forwards */
static NORETURN void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
static NORETURN void exit_tcpdump(int);
static void (*setsignal (int sig, void (*func)(int)))(int);
static void cleanup(int);
static void child_cleanup(int);
static void print_version(void);
static void print_usage(void);
#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
static NORETURN void show_tstamp_types_and_exit(pcap_t *, const char *device);
#endif
static NORETURN void show_dlts_and_exit(pcap_t *, const char *device);
#ifdef HAVE_PCAP_FINDALLDEVS
static NORETURN void show_devices_and_exit(void);
#endif
#ifdef HAVE_PCAP_FINDALLDEVS_EX
static NORETURN void show_remote_devices_and_exit(void);
#endif
static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
static void droproot(const char *, const char *);
#ifdef SIGNAL_REQ_INFO
static void requestinfo(int);
#endif
#ifdef SIGNAL_FLUSH_PCAP
static void flushpcap(int);
#endif
#ifdef _WIN32
static HANDLE timer_handle = INVALID_HANDLE_VALUE;
static void CALLBACK verbose_stats_dump(PVOID param, BOOLEAN timer_fired);
#else /* _WIN32 */
static void verbose_stats_dump(int sig);
#endif /* _WIN32 */
static void info(int);
static u_int packets_captured;
#ifdef HAVE_PCAP_FINDALLDEVS
static const struct tok status_flags[] = {
#ifdef PCAP_IF_UP
{ PCAP_IF_UP, "Up" },
#endif
#ifdef PCAP_IF_RUNNING
{ PCAP_IF_RUNNING, "Running" },
#endif
{ PCAP_IF_LOOPBACK, "Loopback" },
#ifdef PCAP_IF_WIRELESS
{ PCAP_IF_WIRELESS, "Wireless" },
#endif
{ 0, NULL }
};
#endif
static pcap_t *pd;
static pcap_dumper_t *pdd = NULL;
static int supports_monitor_mode;
extern int optind;
extern int opterr;
extern char *optarg;
struct dump_info {
char *WFileName;
char *CurrentFileName;
pcap_t *pd;
pcap_dumper_t *pdd;
netdissect_options *ndo;
#ifdef HAVE_CAPSICUM
int dirfd;
#endif
};
#if defined(HAVE_PCAP_SET_PARSER_DEBUG)
/*
* We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
* by any libpcap header, because it's a special hack, only available if
* libpcap was configured to include it, and only intended for use by
* libpcap developers trying to debug the parser for filter expressions).
*/
#ifdef _WIN32
__declspec(dllimport)
#else /* _WIN32 */
extern
#endif /* _WIN32 */
void pcap_set_parser_debug(int);
#elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
/*
* We don't have pcap_set_parser_debug() in libpcap, but we do have
* pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
* to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
*/
static void
pcap_set_parser_debug(int value)
{
#ifdef HAVE_PCAP_DEBUG
extern int pcap_debug;
pcap_debug = value;
#else /* HAVE_PCAP_DEBUG */
extern int yydebug;
yydebug = value;
#endif /* HAVE_PCAP_DEBUG */
}
#define HAVE_PCAP_SET_PARSER_DEBUG
#endif
#if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
/*
* We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
* by any libpcap header, because it's a special hack, only available if
* libpcap was configured to include it, and only intended for use by
* libpcap developers trying to debug the optimizer for filter expressions).
*/
#ifdef _WIN32
__declspec(dllimport)
#else /* _WIN32 */
extern
#endif /* _WIN32 */
void pcap_set_optimizer_debug(int);
#endif
/* VARARGS */
static void
error(const char *fmt, ...)
{
va_list ap;
(void)fprintf(stderr, "%s: ", program_name);
va_start(ap, fmt);
(void)vfprintf(stderr, fmt, ap);
va_end(ap);
if (*fmt) {
fmt += strlen(fmt);
if (fmt[-1] != '\n')
(void)fputc('\n', stderr);
}
exit_tcpdump(S_ERR_HOST_PROGRAM);
/* NOTREACHED */
}
/* VARARGS */
static void
warning(const char *fmt, ...)
{
va_list ap;
(void)fprintf(stderr, "%s: WARNING: ", program_name);
va_start(ap, fmt);
(void)vfprintf(stderr, fmt, ap);
va_end(ap);
if (*fmt) {
fmt += strlen(fmt);
if (fmt[-1] != '\n')
(void)fputc('\n', stderr);
}
}
static void
exit_tcpdump(int status)
{
nd_cleanup();
exit(status);
}
#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
static void
show_tstamp_types_and_exit(pcap_t *pc, const char *device)
{
int n_tstamp_types;
int *tstamp_types = 0;
const char *tstamp_type_name;
int i;
n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types);
if (n_tstamp_types < 0)
error("%s", pcap_geterr(pc));
if (n_tstamp_types == 0) {
fprintf(stderr, "Time stamp type cannot be set for %s\n",
device);
exit_tcpdump(S_SUCCESS);
}
fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
device);
for (i = 0; i < n_tstamp_types; i++) {
tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
if (tstamp_type_name != NULL) {
(void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
pcap_tstamp_type_val_to_description(tstamp_types[i]));
} else {
(void) fprintf(stderr, " %d\n", tstamp_types[i]);
}
}
pcap_free_tstamp_types(tstamp_types);
exit_tcpdump(S_SUCCESS);
}
#endif
static void
show_dlts_and_exit(pcap_t *pc, const char *device)
{
int n_dlts, i;
int *dlts = 0;
const char *dlt_name;
n_dlts = pcap_list_datalinks(pc, &dlts);
if (n_dlts < 0)
error("%s", pcap_geterr(pc));
else if (n_dlts == 0 || !dlts)
error("No data link types.");
/*
* If the interface is known to support monitor mode, indicate
* whether these are the data link types available when not in
* monitor mode, if -I wasn't specified, or when in monitor mode,
* when -I was specified (the link-layer types available in
* monitor mode might be different from the ones available when
* not in monitor mode).
*/
if (supports_monitor_mode)
(void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
device,
Iflag ? "when in monitor mode" : "when not in monitor mode");
else
(void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
device);
for (i = 0; i < n_dlts; i++) {
dlt_name = pcap_datalink_val_to_name(dlts[i]);
if (dlt_name != NULL) {
(void) fprintf(stderr, " %s (%s)", dlt_name,
pcap_datalink_val_to_description(dlts[i]));
/*
* OK, does tcpdump handle that type?
*/
if (!has_printer(dlts[i]))
(void) fprintf(stderr, " (printing not supported)");
fprintf(stderr, "\n");
} else {
(void) fprintf(stderr, " DLT %d (printing not supported)\n",
dlts[i]);
}
}
#ifdef HAVE_PCAP_FREE_DATALINKS
pcap_free_datalinks(dlts);
#endif
exit_tcpdump(S_SUCCESS);
}
#ifdef HAVE_PCAP_FINDALLDEVS
static void
show_devices_and_exit(void)
{
pcap_if_t *dev, *devlist;
char ebuf[PCAP_ERRBUF_SIZE];
int i;
if (pcap_findalldevs(&devlist, ebuf) < 0)
error("%s", ebuf);
for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
printf("%d.%s", i+1, dev->name);
if (dev->description != NULL)
printf(" (%s)", dev->description);
if (dev->flags != 0) {
printf(" [");
printf("%s", bittok2str(status_flags, "none", dev->flags));
#ifdef PCAP_IF_WIRELESS
if (dev->flags & PCAP_IF_WIRELESS) {
switch (dev->flags & PCAP_IF_CONNECTION_STATUS) {
case PCAP_IF_CONNECTION_STATUS_UNKNOWN:
printf(", Association status unknown");
break;
case PCAP_IF_CONNECTION_STATUS_CONNECTED:
printf(", Associated");
break;
case PCAP_IF_CONNECTION_STATUS_DISCONNECTED:
printf(", Not associated");
break;
case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE:
break;
}
} else {
switch (dev->flags & PCAP_IF_CONNECTION_STATUS) {
case PCAP_IF_CONNECTION_STATUS_UNKNOWN:
printf(", Connection status unknown");
break;
case PCAP_IF_CONNECTION_STATUS_CONNECTED:
printf(", Connected");
break;
case PCAP_IF_CONNECTION_STATUS_DISCONNECTED:
printf(", Disconnected");
break;
case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE:
break;
}
}
#endif
printf("]");
}
printf("\n");
}
pcap_freealldevs(devlist);
exit_tcpdump(S_SUCCESS);
}
#endif /* HAVE_PCAP_FINDALLDEVS */
#ifdef HAVE_PCAP_FINDALLDEVS_EX
static void
show_remote_devices_and_exit(void)
{
pcap_if_t *dev, *devlist;
char ebuf[PCAP_ERRBUF_SIZE];
int i;
if (pcap_findalldevs_ex(remote_interfaces_source, NULL, &devlist,
ebuf) < 0)
error("%s", ebuf);
for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
printf("%d.%s", i+1, dev->name);
if (dev->description != NULL)
printf(" (%s)", dev->description);
if (dev->flags != 0)
printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
printf("\n");
}
pcap_freealldevs(devlist);
exit_tcpdump(S_SUCCESS);
}
#endif /* HAVE_PCAP_FINDALLDEVS */
/*
* Short options.
*
* Note that there we use all letters for short options except for g, k,
* o, and P, and those are used by other versions of tcpdump, and we should
* only use them for the same purposes that the other versions of tcpdump
* use them:
*
* macOS tcpdump uses -g to force non--v output for IP to be on one
* line, making it more "g"repable;
*
* macOS tcpdump uses -k to specify that packet comments in pcapng files
* should be printed;
*
* OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
* for hosts sending TCP SYN packets;
*
* macOS tcpdump uses -P to indicate that -w should write pcapng rather
* than pcap files.
*
* macOS tcpdump also uses -Q to specify expressions that match packet
* metadata, including but not limited to the packet direction.
* The expression syntax is different from a simple "in|out|inout",
* and those expressions aren't accepted by macOS tcpdump, but the
* equivalents would be "in" = "dir=in", "out" = "dir=out", and
* "inout" = "dir=in or dir=out", and the parser could conceivably
* special-case "in", "out", and "inout" as expressions for backwards
* compatibility, so all is not (yet) lost.
*/
/*
* Set up flags that might or might not be supported depending on the
* version of libpcap we're using.
*/
#if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
#define B_FLAG "B:"
#define B_FLAG_USAGE " [ -B size ]"
#else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
#define B_FLAG
#define B_FLAG_USAGE
#endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
#ifdef HAVE_PCAP_FINDALLDEVS
#define D_FLAG "D"
#else
#define D_FLAG
#endif
#ifdef HAVE_PCAP_CREATE
#define I_FLAG "I"
#else /* HAVE_PCAP_CREATE */
#define I_FLAG
#endif /* HAVE_PCAP_CREATE */
#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
#define j_FLAG "j:"
#define j_FLAG_USAGE " [ -j tstamptype ]"
#define J_FLAG "J"
#else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
#define j_FLAG
#define j_FLAG_USAGE
#define J_FLAG
#endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
#ifdef USE_LIBSMI
#define m_FLAG_USAGE "[ -m module ] ..."
#endif
#ifdef HAVE_PCAP_SETDIRECTION
#define Q_FLAG "Q:"
#define Q_FLAG_USAGE " [ -Q in|out|inout ]"
#else
#define Q_FLAG
#define Q_FLAG_USAGE
#endif
#ifdef HAVE_PCAP_DUMP_FLUSH
#define U_FLAG "U"
#else
#define U_FLAG
#endif
#define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#"
/*
* Long options.
*
* We do not currently have long options corresponding to all short
* options; we should probably pick appropriate option names for them.
*
* However, the short options where the number of times the option is
* specified matters, such as -v and -d and -t, should probably not
* just map to a long option, as saying
*
* tcpdump --verbose --verbose
*
* doesn't make sense; it should be --verbosity={N} or something such
* as that.
*
* For long options with no corresponding short options, we define values
* outside the range of ASCII graphic characters, make that the last
* component of the entry for the long option, and have a case for that
* option in the switch statement.
*/
#define OPTION_VERSION 128
#define OPTION_TSTAMP_PRECISION 129
#define OPTION_IMMEDIATE_MODE 130
#define OPTION_PRINT 131
#define OPTION_LIST_REMOTE_INTERFACES 132
#define OPTION_TSTAMP_MICRO 133
#define OPTION_TSTAMP_NANO 134
#define OPTION_FP_TYPE 135
#define OPTION_COUNT 136
static const struct option longopts[] = {
#if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
{ "buffer-size", required_argument, NULL, 'B' },
#endif
{ "list-interfaces", no_argument, NULL, 'D' },
#ifdef HAVE_PCAP_FINDALLDEVS_EX
{ "list-remote-interfaces", required_argument, NULL, OPTION_LIST_REMOTE_INTERFACES },
#endif
{ "help", no_argument, NULL, 'h' },
{ "interface", required_argument, NULL, 'i' },
#ifdef HAVE_PCAP_CREATE
{ "monitor-mode", no_argument, NULL, 'I' },
#endif
#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
{ "time-stamp-type", required_argument, NULL, 'j' },
{ "list-time-stamp-types", no_argument, NULL, 'J' },
#endif
#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
{ "micro", no_argument, NULL, OPTION_TSTAMP_MICRO},
{ "nano", no_argument, NULL, OPTION_TSTAMP_NANO},
{ "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
#endif
{ "dont-verify-checksums", no_argument, NULL, 'K' },
{ "list-data-link-types", no_argument, NULL, 'L' },
{ "no-optimize", no_argument, NULL, 'O' },
{ "no-promiscuous-mode", no_argument, NULL, 'p' },
#ifdef HAVE_PCAP_SETDIRECTION
{ "direction", required_argument, NULL, 'Q' },
#endif
{ "snapshot-length", required_argument, NULL, 's' },
{ "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
#ifdef HAVE_PCAP_DUMP_FLUSH
{ "packet-buffered", no_argument, NULL, 'U' },
#endif
{ "linktype", required_argument, NULL, 'y' },
#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
{ "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
#endif
#ifdef HAVE_PCAP_SET_PARSER_DEBUG
{ "debug-filter-parser", no_argument, NULL, 'Y' },
#endif
{ "relinquish-privileges", required_argument, NULL, 'Z' },
{ "count", no_argument, NULL, OPTION_COUNT },
{ "fp-type", no_argument, NULL, OPTION_FP_TYPE },
{ "number", no_argument, NULL, '#' },
{ "print", no_argument, NULL, OPTION_PRINT },
{ "version", no_argument, NULL, OPTION_VERSION },
{ NULL, 0, NULL, 0 }
};
#ifdef HAVE_PCAP_FINDALLDEVS_EX
#define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
#else
#define LIST_REMOTE_INTERFACES_USAGE
#endif
#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
#define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
#else
#define IMMEDIATE_MODE_USAGE ""
#endif
#ifndef _WIN32
/* Drop root privileges and chroot if necessary */
static void
droproot(const char *username, const char *chroot_dir)
{
struct passwd *pw = NULL;
if (chroot_dir && !username)
error("Chroot without dropping root is insecure");
pw = getpwnam(username);
if (pw) {
if (chroot_dir) {
if (chroot(chroot_dir) != 0 || chdir ("/") != 0)
error("Couldn't chroot/chdir to '%.64s': %s",
chroot_dir, pcap_strerror(errno));
}
#ifdef HAVE_LIBCAP_NG
{
int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
if (ret < 0)
error("capng_change_id(): return %d\n", ret);
else
fprintf(stderr, "dropped privs to %s\n", username);
}
#else
if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0)
error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
username,
(unsigned long)pw->pw_uid,
(unsigned long)pw->pw_gid,
pcap_strerror(errno));
else {
fprintf(stderr, "dropped privs to %s\n", username);
}
#endif /* HAVE_LIBCAP_NG */
} else
error("Couldn't find user '%.32s'", username);
#ifdef HAVE_LIBCAP_NG
/* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
DIAG_OFF_CLANG(assign-enum)
capng_updatev(
CAPNG_DROP,
CAPNG_EFFECTIVE | CAPNG_PERMITTED,
CAP_SETUID,
CAP_SETGID,
CAP_SYS_CHROOT,
-1);
DIAG_ON_CLANG(assign-enum)
capng_apply(CAPNG_SELECT_BOTH);
#endif /* HAVE_LIBCAP_NG */
}
#endif /* _WIN32 */
static int
getWflagChars(int x)
{
int c = 0;
x -= 1;
while (x > 0) {
c += 1;
x /= 10;
}
return c;
}
static void
MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
{
char *filename = malloc(PATH_MAX + 1);
if (filename == NULL)
error("Makefilename: malloc");
/* Process with strftime if Gflag is set. */
if (Gflag != 0) {
struct tm *local_tm;
/* Convert Gflag_time to a usable format */
if ((local_tm = localtime(&Gflag_time)) == NULL) {
error("MakeTimedFilename: localtime");
}
/* There's no good way to detect an error in strftime since a return
* value of 0 isn't necessarily failure.
*/
strftime(filename, PATH_MAX, orig_name, local_tm);
} else {
strncpy(filename, orig_name, PATH_MAX);
}
if (cnt == 0 && max_chars == 0)
strncpy(buffer, filename, PATH_MAX + 1);
else
if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
/* Report an error if the filename is too large */
error("too many output files or filename is too long (> %d)", PATH_MAX);
free(filename);
}
static char *
get_next_file(FILE *VFile, char *ptr)
{
char *ret;
size_t len;
ret = fgets(ptr, PATH_MAX, VFile);
if (!ret)
return NULL;
len = strlen (ptr);
if (len > 0 && ptr[len - 1] == '\n')
ptr[len - 1] = '\0';
return ret;
}
#ifdef HAVE_CASPER
static cap_channel_t *
capdns_setup(void)
{
cap_channel_t *capcas, *capdnsloc;
const char *types[1];
int families[2];
capcas = cap_init();
if (capcas == NULL)
error("unable to create casper process");
capdnsloc = cap_service_open(capcas, "system.dns");
/* Casper capability no longer needed. */
cap_close(capcas);
if (capdnsloc == NULL)
error("unable to open system.dns service");
/* Limit system.dns to reverse DNS lookups. */
types[0] = "ADDR";
if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
error("unable to limit access to system.dns service");
families[0] = AF_INET;
families[1] = AF_INET6;
if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
error("unable to limit access to system.dns service");
return (capdnsloc);
}
#endif /* HAVE_CASPER */
#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
static int
tstamp_precision_from_string(const char *precision)
{
if (strncmp(precision, "nano", strlen("nano")) == 0)
return PCAP_TSTAMP_PRECISION_NANO;
if (strncmp(precision, "micro", strlen("micro")) == 0)
return PCAP_TSTAMP_PRECISION_MICRO;
return -EINVAL;
}
static const char *
tstamp_precision_to_string(int precision)
{
switch (precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
return "micro";
case PCAP_TSTAMP_PRECISION_NANO:
return "nano";
default:
return "unknown";
}
}
#endif
#ifdef HAVE_CAPSICUM
/*
* Ensure that, on a dump file's descriptor, we have all the rights
* necessary to make the standard I/O library work with an fdopen()ed
* FILE * from that descriptor.
*
* A long time ago in a galaxy far, far away, AT&T decided that, instead
* of providing separate APIs for getting and setting the FD_ flags on a
* descriptor, getting and setting the O_ flags on a descriptor, and
* locking files, they'd throw them all into a kitchen-sink fcntl() call
* along the lines of ioctl(), the fact that ioctl() operations are
* largely specific to particular character devices but fcntl() operations
* are either generic to all descriptors or generic to all descriptors for
* regular files nonwithstanding.
*
* The Capsicum people decided that fine-grained control of descriptor
* operations was required, so that you need to grant permission for
* reading, writing, seeking, and fcntl-ing. The latter, courtesy of
* AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
* collection of things, so there are *individual* fcntls for which
* permission needs to be granted.
*
* The FreeBSD standard I/O people implemented some optimizations that
* requires that the standard I/O routines be able to determine whether
* the descriptor for the FILE * is open append-only or not; as that
* descriptor could have come from an open() rather than an fopen(),
* that requires that it be able to do an F_GETFL fcntl() to read
* the O_ flags.
*
* Tcpdump uses ftell() to determine how much data has been written
* to a file in order to, when used with -C, determine when it's time
* to rotate capture files. ftell() therefore needs to do an lseek()
* to find out the file offset and must, thanks to the aforementioned
* optimization, also know whether the descriptor is open append-only
* or not.
*
* The net result of all the above is that we need to grant CAP_SEEK,
* CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
*
* Perhaps this is the universe's way of saying that either
*
* 1) there needs to be an fopenat() call and a pcap_dump_openat() call
* using it, so that Capsicum-capable tcpdump wouldn't need to do
* an fdopen()
*
* or
*
* 2) there needs to be a cap_fdopen() call in the FreeBSD standard
* I/O library that knows what rights are needed by the standard
* I/O library, based on the open mode, and assigns them, perhaps
* with an additional argument indicating, for example, whether
* seeking should be allowed, so that tcpdump doesn't need to know
* what the standard I/O library happens to require this week.
*/
static void
set_dumper_capsicum_rights(pcap_dumper_t *p)
{
int fd = fileno(pcap_dump_file(p));
cap_rights_t rights;
cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
error("unable to limit dump descriptor");