1 /*
2 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
16 * written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20 *
21 * Support for splitting captures into multiple files with a maximum
22 * file size:
23 *
24 * Copyright (c) 2001
25 * Seth Webster <swebster@sst.ll.mit.edu>
26 */
27
28 /*
29 * tcpdump - dump traffic on a network
30 *
31 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
32 * Mercilessly hacked and occasionally improved since then via the
33 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
34 */
35
36 #include <config.h>
37 #ifndef TCPDUMP_CONFIG_H_
38 #error "The included config.h header is not from the tcpdump build."
39 #endif
40
41 /*
42 * Some older versions of Mac OS X ship pcap.h from libpcap 0.6 with a
43 * libpcap based on 0.8. That means it has pcap_findalldevs() but the
44 * header doesn't define pcap_if_t, meaning that we can't actually *use*
45 * pcap_findalldevs().
46 */
47 #ifdef HAVE_PCAP_FINDALLDEVS
48 #ifndef HAVE_PCAP_IF_T
49 #undef HAVE_PCAP_FINDALLDEVS
50 #endif
51 #endif
52
53 #include "netdissect-stdinc.h"
54
55 /*
56 * This must appear after including netdissect-stdinc.h, so that _U_ is
57 * defined.
58 */
59 #ifndef lint
60 static const char copyright[] _U_ =
61 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
62 The Regents of the University of California. All rights reserved.\n";
63 #endif
64
65 #include <sys/stat.h>
66
67 #include <fcntl.h>
68
69 #ifdef HAVE_LIBCRYPTO
70 #include <openssl/crypto.h>
71 #endif
72
73 #ifdef HAVE_GETOPT_LONG
74 #include <getopt.h>
75 #else
76 #include "missing/getopt_long.h"
77 #endif
78 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
79 * to compile if <pcap.h> has already been included; including the headers
80 * in the opposite order works fine. For the most part anyway, because in
81 * FreeBSD <pcap/pcap.h> declares bpf_dump() instead of <net/bpf.h>. Thus
82 * interface.h takes care of it later to avoid a compiler warning.
83 */
84 #ifdef HAVE_CAPSICUM
85 #include <sys/capsicum.h>
86 #include <sys/ioccom.h>
87 #include <net/bpf.h>
88 #include <libgen.h>
89 #ifdef HAVE_CASPER
90 #include <libcasper.h>
91 #include <casper/cap_dns.h>
92 #include <sys/nv.h>
93 #endif /* HAVE_CASPER */
94 #endif /* HAVE_CAPSICUM */
95 #ifdef HAVE_PCAP_OPEN
96 /*
97 * We found pcap_open() in the capture library, so we'll be using
98 * the remote capture APIs; define PCAP_REMOTE before we include pcap.h,
99 * so we get those APIs declared, and the types and #defines that they
100 * use defined.
101 *
102 * WinPcap's headers require that PCAP_REMOTE be defined in order to get
103 * remote-capture APIs declared and types and #defines that they use
104 * defined.
105 *
106 * (Versions of libpcap with those APIs, and thus Npcap, which is based on
107 * those versions of libpcap, don't require it.)
108 */
109 #define HAVE_REMOTE
110 #endif
111 #include <pcap.h>
112 #include <signal.h>
113 #include <stdio.h>
114 #include <stdarg.h>
115 #include <stdlib.h>
116 #include <string.h>
117 #include <limits.h>
118 #ifdef _WIN32
119 #include <windows.h>
120 #else
121 #include <sys/time.h>
122 #include <sys/wait.h>
123 #include <sys/resource.h>
124 #include <pwd.h>
125 #include <grp.h>
126 #endif /* _WIN32 */
127
128 /*
129 * Pathname separator.
130 * Use this in pathnames, but do *not* use it in URLs.
131 */
132 #ifdef _WIN32
133 #define PATH_SEPARATOR '\\'
134 #else
135 #define PATH_SEPARATOR '/'
136 #endif
137
138 /* capabilities convenience library */
139 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
140 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
141 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
142 */
143 #ifdef HAVE_LIBCAP_NG
144 #ifdef HAVE_CAP_NG_H
145 #include <cap-ng.h>
146 #else
147 #undef HAVE_LIBCAP_NG
148 #endif /* HAVE_CAP_NG_H */
149 #endif /* HAVE_LIBCAP_NG */
150
151 #ifdef __FreeBSD__
152 #include <sys/sysctl.h>
153 #endif /* __FreeBSD__ */
154
155 #include "netdissect.h"
156 #include "interface.h"
157 #include "addrtoname.h"
158 #include "machdep.h"
159 #include "pcap-missing.h"
160 #include "ascii_strcasecmp.h"
161
162 #include "print.h"
163
164 #include "diag-control.h"
165
166 #include "fptype.h"
167
168 #ifndef PATH_MAX
169 #define PATH_MAX 1024
170 #endif
171
172 #if defined(SIGINFO)
173 #define SIGNAL_REQ_INFO SIGINFO
174 #elif defined(SIGUSR1)
175 #define SIGNAL_REQ_INFO SIGUSR1
176 #endif
177
178 #if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2)
179 #define SIGNAL_FLUSH_PCAP SIGUSR2
180 #endif
181
182 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
183 static int Bflag; /* buffer size */
184 #endif
185 #ifdef HAVE_PCAP_DUMP_FTELL64
186 static int64_t Cflag; /* rotate dump files after this many bytes */
187 #else
188 static long Cflag; /* rotate dump files after this many bytes */
189 #endif
190 static int Cflag_count; /* Keep track of which file number we're writing */
191 #ifdef HAVE_PCAP_FINDALLDEVS
192 static int Dflag; /* list available devices and exit */
193 #endif
194 #ifdef HAVE_PCAP_FINDALLDEVS_EX
195 static char *remote_interfaces_source; /* list available devices from this source and exit */
196 #endif
197
198 /*
199 * This is exported because, in some versions of libpcap, if libpcap
200 * is built with optimizer debugging code (which is *NOT* the default
201 * configuration!), the library *imports*(!) a variable named dflag,
202 * under the expectation that tcpdump is exporting it, to govern
203 * how much debugging information to print when optimizing
204 * the generated BPF code.
205 *
206 * This is a horrible hack; newer versions of libpcap don't import
207 * dflag but, instead, *if* built with optimizer debugging code,
208 * *export* a routine to set that flag.
209 */
210 extern int dflag;
211 int dflag; /* print filter code */
212 static int Gflag; /* rotate dump files after this many seconds */
213 static int Gflag_count; /* number of files created with Gflag rotation */
214 static time_t Gflag_time; /* The last time_t the dump file was rotated. */
215 static int Lflag; /* list available data link types and exit */
216 static int Iflag; /* rfmon (monitor) mode */
217 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
218 static int Jflag; /* list available time stamp types */
219 static int jflag = -1; /* packet time stamp source */
220 #endif
221 static int lflag; /* line-buffered output */
222 static int pflag; /* don't go promiscuous */
223 #ifdef HAVE_PCAP_SETDIRECTION
224 static int Qflag = -1; /* restrict captured packet by send/receive direction */
225 #endif
226 #ifdef HAVE_PCAP_DUMP_FLUSH
227 static int Uflag; /* "unbuffered" output of dump files */
228 #endif
229 static int Wflag; /* recycle output files after this number of files */
230 static int WflagChars;
231 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
232 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
233 #endif
234 static int timeout = 1000; /* default timeout = 1000 ms = 1 s */
235 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
236 static int immediate_mode;
237 #endif
238 static int count_mode;
239
240 static int infodelay;
241 static int infoprint;
242
243 char *program_name;
244
245 /*
246 * #ifdef HAVE_CASPER
247 * cap_channel_t *capdns;
248 * #endif
249 */
250
251 /* Forwards */
252 static NORETURN void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
253 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
254 static NORETURN void exit_tcpdump(int);
255 static void (*setsignal (int sig, void (*func)(int)))(int);
256 static void cleanup(int);
257 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
258 static void child_cleanup(int);
259 #endif
260 static void print_version(FILE *);
261 static void print_usage(FILE *);
262 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
263 static NORETURN void show_tstamp_types_and_exit(pcap_t *, const char *device);
264 #endif
265 static NORETURN void show_dlts_and_exit(pcap_t *, const char *device);
266 #ifdef HAVE_PCAP_FINDALLDEVS
267 static NORETURN void show_devices_and_exit(void);
268 #endif
269 #ifdef HAVE_PCAP_FINDALLDEVS_EX
270 static NORETURN void show_remote_devices_and_exit(void);
271 #endif
272
273 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
274 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
275 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
276 static void droproot(const char *, const char *);
277
278 #ifdef SIGNAL_REQ_INFO
279 static void requestinfo(int);
280 #endif
281
282 #ifdef SIGNAL_FLUSH_PCAP
283 static void flushpcap(int);
284 #endif
285
286 #ifdef _WIN32
287 static HANDLE timer_handle = INVALID_HANDLE_VALUE;
288 static void CALLBACK verbose_stats_dump(PVOID param, BOOLEAN timer_fired);
289 #else /* _WIN32 */
290 static void verbose_stats_dump(int sig);
291 #endif /* _WIN32 */
292
293 static void info(int);
294 static u_int packets_captured;
295
296 #ifdef HAVE_PCAP_FINDALLDEVS
297 static const struct tok status_flags[] = {
298 #ifdef PCAP_IF_UP
299 { PCAP_IF_UP, "Up" },
300 #endif
301 #ifdef PCAP_IF_RUNNING
302 { PCAP_IF_RUNNING, "Running" },
303 #endif
304 { PCAP_IF_LOOPBACK, "Loopback" },
305 #ifdef PCAP_IF_WIRELESS
306 { PCAP_IF_WIRELESS, "Wireless" },
307 #endif
308 { 0, NULL }
309 };
310 #endif
311
312 static pcap_t *pd;
313 static pcap_dumper_t *pdd = NULL;
314
315 static int supports_monitor_mode;
316
317 extern int optind;
318 extern int opterr;
319 extern char *optarg;
320
321 struct dump_info {
322 char *WFileName;
323 char *CurrentFileName;
324 pcap_t *pd;
325 pcap_dumper_t *pdd;
326 netdissect_options *ndo;
327 #ifdef HAVE_CAPSICUM
328 int dirfd;
329 #endif
330 };
331
332 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
333 /*
334 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
335 * by any libpcap header, because it's a special hack, only available if
336 * libpcap was configured to include it, and only intended for use by
337 * libpcap developers trying to debug the parser for filter expressions).
338 */
339 #ifdef _WIN32
340 __declspec(dllimport)
341 #else /* _WIN32 */
342 extern
343 #endif /* _WIN32 */
344 void pcap_set_parser_debug(int);
345 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
346 /*
347 * We don't have pcap_set_parser_debug() in libpcap, but we do have
348 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
349 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
350 */
351 static void
pcap_set_parser_debug(int value)352 pcap_set_parser_debug(int value)
353 {
354 #ifdef HAVE_PCAP_DEBUG
355 extern int pcap_debug;
356
357 pcap_debug = value;
358 #else /* HAVE_PCAP_DEBUG */
359 extern int yydebug;
360
361 yydebug = value;
362 #endif /* HAVE_PCAP_DEBUG */
363 }
364
365 #define HAVE_PCAP_SET_PARSER_DEBUG
366 #endif
367
368 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
369 /*
370 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
371 * by any libpcap header, because it's a special hack, only available if
372 * libpcap was configured to include it, and only intended for use by
373 * libpcap developers trying to debug the optimizer for filter expressions).
374 */
375 #ifdef _WIN32
376 __declspec(dllimport)
377 #else /* _WIN32 */
378 extern
379 #endif /* _WIN32 */
380 void pcap_set_optimizer_debug(int);
381 #endif
382
383 /* VARARGS */
384 static void
error(const char * fmt,...)385 error(const char *fmt, ...)
386 {
387 va_list ap;
388
389 (void)fprintf(stderr, "%s: ", program_name);
390 va_start(ap, fmt);
391 (void)vfprintf(stderr, fmt, ap);
392 va_end(ap);
393 if (*fmt) {
394 fmt += strlen(fmt);
395 if (fmt[-1] != '\n')
396 (void)fputc('\n', stderr);
397 }
398 exit_tcpdump(S_ERR_HOST_PROGRAM);
399 /* NOTREACHED */
400 }
401
402 /* VARARGS */
403 static void
warning(const char * fmt,...)404 warning(const char *fmt, ...)
405 {
406 va_list ap;
407
408 (void)fprintf(stderr, "%s: WARNING: ", program_name);
409 va_start(ap, fmt);
410 (void)vfprintf(stderr, fmt, ap);
411 va_end(ap);
412 if (*fmt) {
413 fmt += strlen(fmt);
414 if (fmt[-1] != '\n')
415 (void)fputc('\n', stderr);
416 }
417 }
418
419 static void
exit_tcpdump(int status)420 exit_tcpdump(int status)
421 {
422 nd_cleanup();
423 exit(status);
424 }
425
426 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
427 static void
show_tstamp_types_and_exit(pcap_t * pc,const char * device)428 show_tstamp_types_and_exit(pcap_t *pc, const char *device)
429 {
430 int n_tstamp_types;
431 int *tstamp_types = 0;
432 const char *tstamp_type_name;
433 int i;
434
435 n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types);
436 if (n_tstamp_types < 0)
437 error("%s", pcap_geterr(pc));
438
439 if (n_tstamp_types == 0) {
440 fprintf(stderr, "Time stamp type cannot be set for %s\n",
441 device);
442 exit_tcpdump(S_SUCCESS);
443 }
444 fprintf(stdout, "Time stamp types for %s (use option -j to set):\n",
445 device);
446 for (i = 0; i < n_tstamp_types; i++) {
447 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
448 if (tstamp_type_name != NULL) {
449 (void) fprintf(stdout, " %s (%s)\n", tstamp_type_name,
450 pcap_tstamp_type_val_to_description(tstamp_types[i]));
451 } else {
452 (void) fprintf(stdout, " %d\n", tstamp_types[i]);
453 }
454 }
455 pcap_free_tstamp_types(tstamp_types);
456 exit_tcpdump(S_SUCCESS);
457 }
458 #endif
459
460 static void
show_dlts_and_exit(pcap_t * pc,const char * device)461 show_dlts_and_exit(pcap_t *pc, const char *device)
462 {
463 int n_dlts, i;
464 int *dlts = 0;
465 const char *dlt_name;
466
467 n_dlts = pcap_list_datalinks(pc, &dlts);
468 if (n_dlts < 0)
469 error("%s", pcap_geterr(pc));
470 else if (n_dlts == 0 || !dlts)
471 error("No data link types.");
472
473 /*
474 * If the interface is known to support monitor mode, indicate
475 * whether these are the data link types available when not in
476 * monitor mode, if -I wasn't specified, or when in monitor mode,
477 * when -I was specified (the link-layer types available in
478 * monitor mode might be different from the ones available when
479 * not in monitor mode).
480 */
481 (void) fprintf(stdout, "Data link types for ");
482 if (supports_monitor_mode)
483 (void) fprintf(stdout, "%s %s",
484 device,
485 Iflag ? "when in monitor mode" : "when not in monitor mode");
486 else
487 (void) fprintf(stdout, "%s",
488 device);
489 (void) fprintf(stdout, " (use option -y to set):\n");
490
491 for (i = 0; i < n_dlts; i++) {
492 dlt_name = pcap_datalink_val_to_name(dlts[i]);
493 if (dlt_name != NULL) {
494 (void) fprintf(stdout, " %s (%s)", dlt_name,
495 pcap_datalink_val_to_description(dlts[i]));
496
497 /*
498 * OK, does tcpdump handle that type?
499 */
500 if (!has_printer(dlts[i]))
501 (void) fprintf(stdout, " (printing not supported)");
502 fprintf(stdout, "\n");
503 } else {
504 (void) fprintf(stdout, " DLT %d (printing not supported)\n",
505 dlts[i]);
506 }
507 }
508 #ifdef HAVE_PCAP_FREE_DATALINKS
509 pcap_free_datalinks(dlts);
510 #endif
511 exit_tcpdump(S_SUCCESS);
512 }
513
514 #ifdef HAVE_PCAP_FINDALLDEVS
515 static void
show_devices_and_exit(void)516 show_devices_and_exit(void)
517 {
518 pcap_if_t *dev, *devlist;
519 char ebuf[PCAP_ERRBUF_SIZE];
520 int i;
521
522 if (pcap_findalldevs(&devlist, ebuf) < 0)
523 error("%s", ebuf);
524 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
525 printf("%d.%s", i+1, dev->name);
526 if (dev->description != NULL)
527 printf(" (%s)", dev->description);
528 if (dev->flags != 0) {
529 printf(" [");
530 printf("%s", bittok2str(status_flags, "none", dev->flags));
531 #ifdef PCAP_IF_WIRELESS
532 if (dev->flags & PCAP_IF_WIRELESS) {
533 switch (dev->flags & PCAP_IF_CONNECTION_STATUS) {
534
535 case PCAP_IF_CONNECTION_STATUS_UNKNOWN:
536 printf(", Association status unknown");
537 break;
538
539 case PCAP_IF_CONNECTION_STATUS_CONNECTED:
540 printf(", Associated");
541 break;
542
543 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED:
544 printf(", Not associated");
545 break;
546
547 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE:
548 break;
549 }
550 } else {
551 switch (dev->flags & PCAP_IF_CONNECTION_STATUS) {
552
553 case PCAP_IF_CONNECTION_STATUS_UNKNOWN:
554 printf(", Connection status unknown");
555 break;
556
557 case PCAP_IF_CONNECTION_STATUS_CONNECTED:
558 printf(", Connected");
559 break;
560
561 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED:
562 printf(", Disconnected");
563 break;
564
565 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE:
566 break;
567 }
568 }
569 #endif
570 printf("]");
571 }
572 printf("\n");
573 }
574 pcap_freealldevs(devlist);
575 exit_tcpdump(S_SUCCESS);
576 }
577 #endif /* HAVE_PCAP_FINDALLDEVS */
578
579 #ifdef HAVE_PCAP_FINDALLDEVS_EX
580 static void
show_remote_devices_and_exit(void)581 show_remote_devices_and_exit(void)
582 {
583 pcap_if_t *dev, *devlist;
584 char ebuf[PCAP_ERRBUF_SIZE];
585 int i;
586
587 if (pcap_findalldevs_ex(remote_interfaces_source, NULL, &devlist,
588 ebuf) < 0)
589 error("%s", ebuf);
590 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
591 printf("%d.%s", i+1, dev->name);
592 if (dev->description != NULL)
593 printf(" (%s)", dev->description);
594 if (dev->flags != 0)
595 printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
596 printf("\n");
597 }
598 pcap_freealldevs(devlist);
599 exit_tcpdump(S_SUCCESS);
600 }
601 #endif /* HAVE_PCAP_FINDALLDEVS */
602
603 /*
604 * Short options.
605 *
606 * Note that there we use all letters for short options except for k,
607 * o, and P, and those are used by other versions of tcpdump, and we should
608 * only use them for the same purposes that the other versions of tcpdump
609 * use them:
610 *
611 * macOS tcpdump uses -k to specify that packet comments in pcapng files
612 * should be printed;
613 *
614 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
615 * for hosts sending TCP SYN packets;
616 *
617 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
618 * than pcap files.
619 *
620 * macOS tcpdump also uses -Q to specify expressions that match packet
621 * metadata, including but not limited to the packet direction.
622 * The expression syntax is different from a simple "in|out|inout",
623 * and those expressions aren't accepted by macOS tcpdump, but the
624 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
625 * "inout" = "dir=in or dir=out", and the parser could conceivably
626 * special-case "in", "out", and "inout" as expressions for backwards
627 * compatibility, so all is not (yet) lost.
628 */
629
630 /*
631 * Set up flags that might or might not be supported depending on the
632 * version of libpcap we're using.
633 */
634 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
635 #define B_FLAG "B:"
636 #define B_FLAG_USAGE " [ -B size ]"
637 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
638 #define B_FLAG
639 #define B_FLAG_USAGE
640 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
641
642 #ifdef HAVE_PCAP_FINDALLDEVS
643 #define D_FLAG "D"
644 #else
645 #define D_FLAG
646 #endif
647
648 #ifdef HAVE_PCAP_CREATE
649 #define I_FLAG "I"
650 #else /* HAVE_PCAP_CREATE */
651 #define I_FLAG
652 #endif /* HAVE_PCAP_CREATE */
653
654 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
655 #define j_FLAG "j:"
656 #define j_FLAG_USAGE " [ -j tstamptype ]"
657 #define J_FLAG "J"
658 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
659 #define j_FLAG
660 #define j_FLAG_USAGE
661 #define J_FLAG
662 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
663
664 #ifdef USE_LIBSMI
665 #define m_FLAG_USAGE "[ -m module ] ..."
666 #endif
667
668 #ifdef HAVE_PCAP_SETDIRECTION
669 #define Q_FLAG "Q:"
670 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
671 #else
672 #define Q_FLAG
673 #define Q_FLAG_USAGE
674 #endif
675
676 #ifdef HAVE_PCAP_DUMP_FLUSH
677 #define U_FLAG "U"
678 #else
679 #define U_FLAG
680 #endif
681
682 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
683 #define z_FLAG "z:"
684 #define z_FLAG_USAGE "[ -z postrotate-command ] "
685 #else
686 #define z_FLAG
687 #define z_FLAG_USAGE
688 #endif
689
690 #ifdef HAVE_LIBCRYPTO
691 #define E_FLAG "E:"
692 #define E_FLAG_USAGE "[ -E algo:secret ] "
693 #define M_FLAG "M:"
694 #define M_FLAG_USAGE "[ -M secret ] "
695 #else
696 #define E_FLAG
697 #define E_FLAG_USAGE
698 #define M_FLAG
699 #define M_FLAG_USAGE
700 #endif
701
702 #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "e" E_FLAG "fF:gG:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:" M_FLAG "nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Y" z_FLAG "Z:#"
703
704 /*
705 * Long options.
706 *
707 * We do not currently have long options corresponding to all short
708 * options; we should probably pick appropriate option names for them.
709 *
710 * However, the short options where the number of times the option is
711 * specified matters, such as -v and -d and -t, should probably not
712 * just map to a long option, as saying
713 *
714 * tcpdump --verbose --verbose
715 *
716 * doesn't make sense; it should be --verbosity={N} or something such
717 * as that.
718 *
719 * For long options with no corresponding short options, we define values
720 * outside the range of ASCII graphic characters, make that the last
721 * component of the entry for the long option, and have a case for that
722 * option in the switch statement.
723 */
724 #define OPTION_VERSION 128
725 #define OPTION_TSTAMP_PRECISION 129
726 #define OPTION_IMMEDIATE_MODE 130
727 #define OPTION_PRINT 131
728 #define OPTION_LIST_REMOTE_INTERFACES 132
729 #define OPTION_TSTAMP_MICRO 133
730 #define OPTION_TSTAMP_NANO 134
731 #define OPTION_FP_TYPE 135
732 #define OPTION_COUNT 136
733 #define OPTION_TIME_T_SIZE 139
734
735 static const struct option longopts[] = {
736 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
737 { "buffer-size", required_argument, NULL, 'B' },
738 #endif
739 { "list-interfaces", no_argument, NULL, 'D' },
740 #ifdef HAVE_PCAP_FINDALLDEVS_EX
741 { "list-remote-interfaces", required_argument, NULL, OPTION_LIST_REMOTE_INTERFACES },
742 #endif
743 { "help", no_argument, NULL, 'h' },
744 { "interface", required_argument, NULL, 'i' },
745 #ifdef HAVE_PCAP_CREATE
746 { "monitor-mode", no_argument, NULL, 'I' },
747 #endif
748 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
749 { "time-stamp-type", required_argument, NULL, 'j' },
750 { "list-time-stamp-types", no_argument, NULL, 'J' },
751 #endif
752 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
753 { "micro", no_argument, NULL, OPTION_TSTAMP_MICRO},
754 { "nano", no_argument, NULL, OPTION_TSTAMP_NANO},
755 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
756 #endif
757 { "dont-verify-checksums", no_argument, NULL, 'K' },
758 { "list-data-link-types", no_argument, NULL, 'L' },
759 { "no-optimize", no_argument, NULL, 'O' },
760 { "no-promiscuous-mode", no_argument, NULL, 'p' },
761 #ifdef HAVE_PCAP_SETDIRECTION
762 { "direction", required_argument, NULL, 'Q' },
763 #endif
764 { "snapshot-length", required_argument, NULL, 's' },
765 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
766 #ifdef HAVE_PCAP_DUMP_FLUSH
767 { "packet-buffered", no_argument, NULL, 'U' },
768 #endif
769 { "linktype", required_argument, NULL, 'y' },
770 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
771 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
772 #endif
773 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
774 { "debug-filter-parser", no_argument, NULL, 'Y' },
775 #endif
776 { "relinquish-privileges", required_argument, NULL, 'Z' },
777 { "count", no_argument, NULL, OPTION_COUNT },
778 { "fp-type", no_argument, NULL, OPTION_FP_TYPE },
779 { "number", no_argument, NULL, '#' },
780 { "print", no_argument, NULL, OPTION_PRINT },
781 { "time-t-size", no_argument, NULL, OPTION_TIME_T_SIZE },
782 { "ip-oneline", no_argument, NULL, 'g' },
783 { "version", no_argument, NULL, OPTION_VERSION },
784 { NULL, 0, NULL, 0 }
785 };
786
787 #ifdef HAVE_PCAP_FINDALLDEVS_EX
788 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
789 #else
790 #define LIST_REMOTE_INTERFACES_USAGE
791 #endif
792
793 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
794 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
795 #else
796 #define IMMEDIATE_MODE_USAGE ""
797 #endif
798
799 #ifndef _WIN32
800 /* Drop root privileges and chroot if necessary */
801 static void
droproot(const char * username,const char * chroot_dir)802 droproot(const char *username, const char *chroot_dir)
803 {
804 struct passwd *pw = NULL;
805
806 if (chroot_dir && !username)
807 error("Chroot without dropping root is insecure");
808
809 pw = getpwnam(username);
810 if (pw) {
811 if (chroot_dir) {
812 if (chroot(chroot_dir) != 0 || chdir ("/") != 0)
813 error("Couldn't chroot/chdir to '%.64s': %s",
814 chroot_dir, pcap_strerror(errno));
815 }
816 #ifdef HAVE_LIBCAP_NG
817 {
818 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
819 if (ret < 0)
820 error("capng_change_id(): return %d", ret);
821 else
822 fprintf(stderr, "dropped privs to %s\n", username);
823 }
824 #else
825 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
826 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0)
827 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
828 username,
829 (unsigned long)pw->pw_uid,
830 (unsigned long)pw->pw_gid,
831 pcap_strerror(errno));
832 else {
833 fprintf(stderr, "dropped privs to %s\n", username);
834 }
835 #endif /* HAVE_LIBCAP_NG */
836 } else
837 error("Couldn't find user '%.32s'", username);
838 #ifdef HAVE_LIBCAP_NG
839 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT anymore. */
840 DIAG_OFF_ASSIGN_ENUM
841 capng_updatev(
842 CAPNG_DROP,
843 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
844 CAP_SETUID,
845 CAP_SETGID,
846 CAP_SYS_CHROOT,
847 -1);
848 DIAG_ON_ASSIGN_ENUM
849 capng_apply(CAPNG_SELECT_BOTH);
850 #endif /* HAVE_LIBCAP_NG */
851
852 }
853 #endif /* _WIN32 */
854
855 static int
getWflagChars(int x)856 getWflagChars(int x)
857 {
858 int c = 0;
859
860 x -= 1;
861 while (x > 0) {
862 c += 1;
863 x /= 10;
864 }
865
866 return c;
867 }
868
869
870 static void
MakeFilename(char * buffer,char * orig_name,int cnt,int max_chars)871 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
872 {
873 char *filename = malloc(PATH_MAX + 1);
874 if (filename == NULL)
875 error("%s: malloc", __func__);
876 if (strlen(orig_name) == 0)
877 error("an empty string is not a valid file name");
878
879 /* Process with strftime if Gflag is set. */
880 if (Gflag != 0) {
881 struct tm *local_tm;
882
883 /* Convert Gflag_time to a usable format */
884 if ((local_tm = localtime(&Gflag_time)) == NULL) {
885 error("%s: localtime", __func__);
886 }
887
888 /* There's no good way to detect an error in strftime since a return
889 * value of 0 isn't necessarily failure; if orig_name is an empty
890 * string, the formatted string will be empty.
891 *
892 * However, the C90 standard says that, if there *is* a
893 * buffer overflow, the content of the buffer is undefined,
894 * so we must check for a buffer overflow.
895 *
896 * So we check above for an empty orig_name, and only call
897 * strftime() if it's non-empty, in which case the return
898 * value will only be 0 if the formatted date doesn't fit
899 * in the buffer.
900 *
901 * (We check above because, even if we don't use -G, we
902 * want a better error message than "tcpdump: : No such
903 * file or directory" for this case.)
904 */
905 if (strftime(filename, PATH_MAX, orig_name, local_tm) == 0) {
906 error("%s: strftime", __func__);
907 }
908 } else {
909 strncpy(filename, orig_name, PATH_MAX);
910 }
911
912 if (cnt == 0 && max_chars == 0)
913 strncpy(buffer, filename, PATH_MAX + 1);
914 else
915 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
916 /* Report an error if the filename is too large */
917 error("too many output files or filename is too long (> %d)", PATH_MAX);
918 free(filename);
919 }
920
921 static char *
get_next_file(FILE * VFile,char * ptr)922 get_next_file(FILE *VFile, char *ptr)
923 {
924 char *ret;
925 size_t len;
926
927 ret = fgets(ptr, PATH_MAX, VFile);
928 if (!ret)
929 return NULL;
930
931 len = strlen (ptr);
932 if (len > 0 && ptr[len - 1] == '\n')
933 ptr[len - 1] = '\0';
934
935 return ret;
936 }
937
938 #ifdef HAVE_CASPER
939 static cap_channel_t *
capdns_setup(void)940 capdns_setup(void)
941 {
942 cap_channel_t *capcas, *capdnsloc;
943 const char *types[1];
944 int families[2];
945
946 capcas = cap_init();
947 if (capcas == NULL)
948 error("unable to create casper process");
949 capdnsloc = cap_service_open(capcas, "system.dns");
950 /* Casper capability no longer needed. */
951 cap_close(capcas);
952 if (capdnsloc == NULL)
953 error("unable to open system.dns service");
954 /* Limit system.dns to reverse DNS lookups. */
955 types[0] = "ADDR2NAME";
956 if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
957 error("unable to limit access to system.dns service");
958 families[0] = AF_INET;
959 families[1] = AF_INET6;
960 if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
961 error("unable to limit access to system.dns service");
962
963 return (capdnsloc);
964 }
965 #endif /* HAVE_CASPER */
966
967 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
968 static int
tstamp_precision_from_string(const char * precision)969 tstamp_precision_from_string(const char *precision)
970 {
971 if (strncmp(precision, "nano", strlen("nano")) == 0)
972 return PCAP_TSTAMP_PRECISION_NANO;
973
974 if (strncmp(precision, "micro", strlen("micro")) == 0)
975 return PCAP_TSTAMP_PRECISION_MICRO;
976
977 return -EINVAL;
978 }
979
980 static const char *
tstamp_precision_to_string(int precision)981 tstamp_precision_to_string(int precision)
982 {
983 switch (precision) {
984
985 case PCAP_TSTAMP_PRECISION_MICRO:
986 return "micro";
987
988 case PCAP_TSTAMP_PRECISION_NANO:
989 return "nano";
990
991 default:
992 return "unknown";
993 }
994 }
995 #endif
996
997 #ifdef HAVE_CAPSICUM
998 /*
999 * Ensure that, on a dump file's descriptor, we have all the rights
1000 * necessary to make the standard I/O library work with an fdopen()ed
1001 * FILE * from that descriptor.
1002 *
1003 * A long time ago in a galaxy far, far away, AT&T decided that, instead
1004 * of providing separate APIs for getting and setting the FD_ flags on a
1005 * descriptor, getting and setting the O_ flags on a descriptor, and
1006 * locking files, they'd throw them all into a kitchen-sink fcntl() call
1007 * along the lines of ioctl(), the fact that ioctl() operations are
1008 * largely specific to particular character devices but fcntl() operations
1009 * are either generic to all descriptors or generic to all descriptors for
1010 * regular files notwithstanding.
1011 *
1012 * The Capsicum people decided that fine-grained control of descriptor
1013 * operations was required, so that you need to grant permission for
1014 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
1015 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
1016 * collection of things, so there are *individual* fcntls for which
1017 * permission needs to be granted.
1018 *
1019 * The FreeBSD standard I/O people implemented some optimizations that
1020 * requires that the standard I/O routines be able to determine whether
1021 * the descriptor for the FILE * is open append-only or not; as that
1022 * descriptor could have come from an open() rather than an fopen(),
1023 * that requires that it be able to do an F_GETFL fcntl() to read
1024 * the O_ flags.
1025 *
1026 * tcpdump uses ftell() to determine how much data has been written
1027 * to a file in order to, when used with -C, determine when it's time
1028 * to rotate capture files. ftell() therefore needs to do an lseek()
1029 * to find out the file offset and must, thanks to the aforementioned
1030 * optimization, also know whether the descriptor is open append-only
1031 * or not.
1032 *
1033 * The net result of all the above is that we need to grant CAP_SEEK,
1034 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
1035 *
1036 * Perhaps this is the universe's way of saying that either
1037 *
1038 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
1039 * using it, so that Capsicum-capable tcpdump wouldn't need to do
1040 * an fdopen()
1041 *
1042 * or
1043 *
1044 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
1045 * I/O library that knows what rights are needed by the standard
1046 * I/O library, based on the open mode, and assigns them, perhaps
1047 * with an additional argument indicating, for example, whether
1048 * seeking should be allowed, so that tcpdump doesn't need to know
1049 * what the standard I/O library happens to require this week.
1050 */
1051 static void
set_dumper_capsicum_rights(pcap_dumper_t * p)1052 set_dumper_capsicum_rights(pcap_dumper_t *p)
1053 {
1054 int fd = fileno(pcap_dump_file(p));
1055 cap_rights_t rights;
1056
1057 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
1058 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
1059 error("unable to limit dump descriptor");
1060 }
1061 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
1062 error("unable to limit dump descriptor fcntls");
1063 }
1064 }
1065 #endif
1066
1067 /*
1068 * Copy arg vector into a new buffer, concatenating arguments with spaces.
1069 */
1070 static char *
copy_argv(char ** argv)1071 copy_argv(char **argv)
1072 {
1073 char **p;
1074 size_t len = 0;
1075 char *buf;
1076 char *src, *dst;
1077
1078 p = argv;
1079 if (*p == NULL)
1080 return 0;
1081
1082 while (*p)
1083 len += strlen(*p++) + 1;
1084
1085 buf = (char *)malloc(len);
1086 if (buf == NULL)
1087 error("%s: malloc", __func__);
1088
1089 p = argv;
1090 dst = buf;
1091 while ((src = *p++) != NULL) {
1092 while ((*dst++ = *src++) != '\0')
1093 ;
1094 dst[-1] = ' ';
1095 }
1096 dst[-1] = '\0';
1097
1098 return buf;
1099 }
1100
1101 /*
1102 * On Windows, we need to open the file in binary mode, so that
1103 * we get all the bytes specified by the size we get from "fstat()".
1104 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1105 * we define it as 0 if it's not defined, so it does nothing.
1106 */
1107 #ifndef O_BINARY
1108 #define O_BINARY 0
1109 #endif
1110
1111 static char *
read_infile(char * fname)1112 read_infile(char *fname)
1113 {
1114 int i, fd;
1115 ssize_t cc;
1116 char *cp;
1117 our_statb buf;
1118
1119 fd = open(fname, O_RDONLY|O_BINARY);
1120 if (fd < 0)
1121 error("can't open %s: %s", fname, pcap_strerror(errno));
1122
1123 if (our_fstat(fd, &buf) < 0)
1124 error("can't stat %s: %s", fname, pcap_strerror(errno));
1125
1126 /*
1127 * Reject files whose size doesn't fit into an int; a filter
1128 * *that* large will probably be too big.
1129 */
1130 if (buf.st_size > INT_MAX)
1131 error("%s is too large", fname);
1132
1133 cp = malloc((u_int)buf.st_size + 1);
1134 if (cp == NULL)
1135 error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
1136 fname, pcap_strerror(errno));
1137 cc = read(fd, cp, (u_int)buf.st_size);
1138 if (cc < 0)
1139 error("read %s: %s", fname, pcap_strerror(errno));
1140 if (cc != buf.st_size)
1141 error("short read %s (%d != %d)", fname, (int) cc,
1142 (int)buf.st_size);
1143
1144 close(fd);
1145 /* replace "# comment" with spaces */
1146 for (i = 0; i < cc; i++) {
1147 if (cp[i] == '#')
1148 while (i < cc && cp[i] != '\n')
1149 cp[i++] = ' ';
1150 }
1151 cp[cc] = '\0';
1152 return (cp);
1153 }
1154
1155 #ifdef HAVE_PCAP_FINDALLDEVS
1156 static long
parse_interface_number(const char * device)1157 parse_interface_number(const char *device)
1158 {
1159 const char *p;
1160 long devnum;
1161 char *end;
1162
1163 /*
1164 * Search for a colon, terminating any scheme at the beginning
1165 * of the device.
1166 */
1167 p = strchr(device, ':');
1168 if (p != NULL) {
1169 /*
1170 * We found it. Is it followed by "//"?
1171 */
1172 p++; /* skip the : */
1173 if (strncmp(p, "//", 2) == 0) {
1174 /*
1175 * Yes. Search for the next /, at the end of the
1176 * authority part of the URL.
1177 */
1178 p += 2; /* skip the // */
1179 p = strchr(p, '/');
1180 if (p != NULL) {
1181 /*
1182 * OK, past the / is the path.
1183 */
1184 device = p + 1;
1185 }
1186 }
1187 }
1188 devnum = strtol(device, &end, 10);
1189 if (device != end && *end == '\0') {
1190 /*
1191 * It's all-numeric, but is it a valid number?
1192 */
1193 if (devnum <= 0) {
1194 /*
1195 * No, it's not an ordinal.
1196 */
1197 error("Invalid adapter index %s", device);
1198 }
1199 return (devnum);
1200 } else {
1201 /*
1202 * It's not all-numeric; return -1, so our caller
1203 * knows that.
1204 */
1205 return (-1);
1206 }
1207 }
1208
1209 static char *
find_interface_by_number(const char * url _U_,long devnum)1210 find_interface_by_number(const char *url
1211 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1212 _U_
1213 #endif
1214 , long devnum)
1215 {
1216 pcap_if_t *dev, *devlist;
1217 long i;
1218 char ebuf[PCAP_ERRBUF_SIZE];
1219 char *device;
1220 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1221 const char *endp;
1222 char *host_url;
1223 #endif
1224 int status;
1225
1226 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1227 /*
1228 * Search for a colon, terminating any scheme at the beginning
1229 * of the URL.
1230 */
1231 endp = strchr(url, ':');
1232 if (endp != NULL) {
1233 /*
1234 * We found it. Is it followed by "//"?
1235 */
1236 endp++; /* skip the : */
1237 if (strncmp(endp, "//", 2) == 0) {
1238 /*
1239 * Yes. Search for the next /, at the end of the
1240 * authority part of the URL.
1241 */
1242 endp += 2; /* skip the // */
1243 endp = strchr(endp, '/');
1244 } else
1245 endp = NULL;
1246 }
1247 if (endp != NULL) {
1248 /*
1249 * OK, everything from device to endp is a URL to hand
1250 * to pcap_findalldevs_ex().
1251 */
1252 endp++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1253 host_url = malloc(endp - url + 1);
1254 if (host_url == NULL && (endp - url + 1) > 0)
1255 error("Invalid allocation for host");
1256
1257 memcpy(host_url, url, endp - url);
1258 host_url[endp - url] = '\0';
1259 status = pcap_findalldevs_ex(host_url, NULL, &devlist, ebuf);
1260 free(host_url);
1261 } else
1262 #endif
1263 status = pcap_findalldevs(&devlist, ebuf);
1264 if (status < 0)
1265 error("%s", ebuf);
1266 if (devlist == NULL)
1267 error("no interfaces available for capture");
1268 /*
1269 * Look for the devnum-th entry in the list of devices (1-based).
1270 */
1271 for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
1272 i++, dev = dev->next)
1273 ;
1274 if (dev == NULL) {
1275 pcap_freealldevs(devlist);
1276 error("Invalid adapter index %ld: only %ld interface%s found",
1277 devnum, i, (i == 1) ? "" : "s");
1278 }
1279 device = strdup(dev->name);
1280 pcap_freealldevs(devlist);
1281 return (device);
1282 }
1283 #endif
1284
1285 #ifdef HAVE_PCAP_OPEN
1286 /*
1287 * Prefixes for rpcap URLs.
1288 */
1289 static char rpcap_prefix[] = "rpcap://";
1290 static char rpcap_ssl_prefix[] = "rpcaps://";
1291 #endif
1292
1293 static pcap_t *
open_interface(const char * device,netdissect_options * ndo,char * ebuf)1294 open_interface(const char *device, netdissect_options *ndo, char *ebuf)
1295 {
1296 pcap_t *pc;
1297 #ifdef HAVE_PCAP_CREATE
1298 int status;
1299 char *cp;
1300 #endif
1301
1302 #ifdef HAVE_PCAP_OPEN
1303 /*
1304 * Is this an rpcap URL?
1305 */
1306 if (strncmp(device, rpcap_prefix, sizeof(rpcap_prefix) - 1) == 0 ||
1307 strncmp(device, rpcap_ssl_prefix, sizeof(rpcap_ssl_prefix) - 1) == 0) {
1308 /*
1309 * Yes. Open it with pcap_open().
1310 */
1311 *ebuf = '\0';
1312 pc = pcap_open(device, ndo->ndo_snaplen,
1313 pflag ? 0 : PCAP_OPENFLAG_PROMISCUOUS, timeout, NULL,
1314 ebuf);
1315 if (pc == NULL) {
1316 /*
1317 * If this failed with "No such device" or "The system
1318 * cannot find the device specified", that means
1319 * the interface doesn't exist; return NULL, so that
1320 * the caller can see whether the device name is
1321 * actually an interface index.
1322 */
1323 if (strstr(ebuf, "No such device") != NULL ||
1324 strstr(ebuf, "The system cannot find the device specified") != NULL)
1325 return (NULL);
1326 error("%s", ebuf);
1327 }
1328 if (*ebuf)
1329 warning("%s", ebuf);
1330 return (pc);
1331 }
1332 #endif /* HAVE_PCAP_OPEN */
1333
1334 #ifdef HAVE_PCAP_CREATE
1335 pc = pcap_create(device, ebuf);
1336 if (pc == NULL) {
1337 /*
1338 * If this failed with "No such device", that means
1339 * the interface doesn't exist; return NULL, so that
1340 * the caller can see whether the device name is
1341 * actually an interface index.
1342 */
1343 if (strstr(ebuf, "No such device") != NULL)
1344 return (NULL);
1345 error("%s", ebuf);
1346 }
1347 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1348 if (Jflag)
1349 show_tstamp_types_and_exit(pc, device);
1350 #endif
1351 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1352 status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
1353 if (status != 0)
1354 error("%s: Can't set %ssecond time stamp precision: %s",
1355 device,
1356 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1357 pcap_statustostr(status));
1358 #endif
1359
1360 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1361 if (immediate_mode) {
1362 status = pcap_set_immediate_mode(pc, 1);
1363 if (status != 0)
1364 error("%s: Can't set immediate mode: %s",
1365 device, pcap_statustostr(status));
1366 }
1367 #endif
1368 /*
1369 * Is this an interface that supports monitor mode?
1370 */
1371 if (pcap_can_set_rfmon(pc) == 1)
1372 supports_monitor_mode = 1;
1373 else
1374 supports_monitor_mode = 0;
1375 if (ndo->ndo_snaplen != 0) {
1376 /*
1377 * A snapshot length was explicitly specified;
1378 * use it.
1379 */
1380 status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
1381 if (status != 0)
1382 error("%s: Can't set snapshot length: %s",
1383 device, pcap_statustostr(status));
1384 }
1385 status = pcap_set_promisc(pc, !pflag);
1386 if (status != 0)
1387 error("%s: Can't set promiscuous mode: %s",
1388 device, pcap_statustostr(status));
1389 if (Iflag) {
1390 status = pcap_set_rfmon(pc, 1);
1391 if (status != 0)
1392 error("%s: Can't set monitor mode: %s",
1393 device, pcap_statustostr(status));
1394 }
1395 status = pcap_set_timeout(pc, timeout);
1396 if (status != 0)
1397 error("%s: pcap_set_timeout failed: %s",
1398 device, pcap_statustostr(status));
1399 if (Bflag != 0) {
1400 status = pcap_set_buffer_size(pc, Bflag);
1401 if (status != 0)
1402 error("%s: Can't set buffer size: %s",
1403 device, pcap_statustostr(status));
1404 }
1405 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1406 if (jflag != -1) {
1407 status = pcap_set_tstamp_type(pc, jflag);
1408 if (status < 0)
1409 error("%s: Can't set time stamp type: %s",
1410 device, pcap_statustostr(status));
1411 else if (status > 0)
1412 warning("When trying to set timestamp type '%s' on %s: %s",
1413 pcap_tstamp_type_val_to_name(jflag), device,
1414 pcap_statustostr(status));
1415 }
1416 #endif
1417 status = pcap_activate(pc);
1418 if (status < 0) {
1419 /*
1420 * pcap_activate() failed.
1421 */
1422 cp = pcap_geterr(pc);
1423 if (status == PCAP_ERROR)
1424 error("%s: %s", device, cp);
1425 else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
1426 /*
1427 * Return an error for our caller to handle.
1428 */
1429 snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
1430 device, pcap_statustostr(status), cp);
1431 } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
1432 error("%s: %s\n(%s)", device,
1433 pcap_statustostr(status), cp);
1434 #ifdef PCAP_ERROR_CAPTURE_NOTSUP
1435 else if (status == PCAP_ERROR_CAPTURE_NOTSUP && *cp != '\0')
1436 error("%s: %s\n(%s)", device,
1437 pcap_statustostr(status), cp);
1438 #endif
1439 #ifdef __FreeBSD__
1440 else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1441 strncmp(device, "wlan", 4) == 0) {
1442 char parent[8], newdev[8];
1443 char sysctl[32];
1444 size_t s = sizeof(parent);
1445
1446 snprintf(sysctl, sizeof(sysctl),
1447 "net.wlan.%d.%%parent", atoi(device + 4));
1448 sysctlbyname(sysctl, parent, &s, NULL, 0);
1449 strlcpy(newdev, device, sizeof(newdev));
1450 /* Suggest a new wlan device. */
1451 /* FIXME: incrementing the index this way is not going to work well
1452 * when the index is 9 or greater but the only consequence in this
1453 * specific case would be an error message that looks a bit odd.
1454 */
1455 newdev[strlen(newdev)-1]++;
1456 error("%s is not a monitor mode VAP"
1457 "To create a new monitor mode VAP use:\n"
1458 " ifconfig %s create wlandev %s wlanmode monitor\n"
1459 "and use %s as the tcpdump interface",
1460 device, newdev, parent, newdev);
1461 }
1462 #endif
1463 else
1464 error("%s: %s", device,
1465 pcap_statustostr(status));
1466 pcap_close(pc);
1467 return (NULL);
1468 } else if (status > 0) {
1469 /*
1470 * pcap_activate() succeeded, but it's warning us
1471 * of a problem it had.
1472 */
1473 cp = pcap_geterr(pc);
1474 if (status == PCAP_WARNING)
1475 warning("%s", cp);
1476 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1477 *cp != '\0')
1478 warning("%s: %s\n(%s)", device,
1479 pcap_statustostr(status), cp);
1480 else
1481 warning("%s: %s", device,
1482 pcap_statustostr(status));
1483 }
1484 #ifdef HAVE_PCAP_SETDIRECTION
1485 if (Qflag != -1) {
1486 status = pcap_setdirection(pc, Qflag);
1487 if (status != 0)
1488 error("%s: pcap_setdirection() failed: %s",
1489 device, pcap_geterr(pc));
1490 }
1491 #endif /* HAVE_PCAP_SETDIRECTION */
1492 #else /* HAVE_PCAP_CREATE */
1493 *ebuf = '\0';
1494 /*
1495 * If no snapshot length was specified, or a length of 0 was
1496 * specified, default to 256KB.
1497 */
1498 if (ndo->ndo_snaplen == 0)
1499 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1500 pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, timeout, ebuf);
1501 if (pc == NULL) {
1502 /*
1503 * If this failed with "No such device", that means
1504 * the interface doesn't exist; return NULL, so that
1505 * the caller can see whether the device name is
1506 * actually an interface index.
1507 */
1508 if (strstr(ebuf, "No such device") != NULL)
1509 return (NULL);
1510 error("%s", ebuf);
1511 }
1512 if (*ebuf)
1513 warning("%s", ebuf);
1514 #endif /* HAVE_PCAP_CREATE */
1515
1516 return (pc);
1517 }
1518
1519 int
main(int argc,char ** argv)1520 main(int argc, char **argv)
1521 {
1522 int cnt, op, i;
1523 bpf_u_int32 localnet = 0, netmask = 0;
1524 char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1525 char *endp;
1526 pcap_handler callback;
1527 int dlt;
1528 const char *dlt_name;
1529 struct bpf_program fcode;
1530 #ifndef _WIN32
1531 void (*oldhandler)(int);
1532 #endif
1533 struct dump_info dumpinfo;
1534 u_char *pcap_userdata;
1535 char ebuf[PCAP_ERRBUF_SIZE];
1536 char VFileLine[PATH_MAX + 1];
1537 const char *username = NULL;
1538 #ifndef _WIN32
1539 const char *chroot_dir = NULL;
1540 #endif
1541 char *ret = NULL;
1542 char *end;
1543 #ifdef HAVE_PCAP_FINDALLDEVS
1544 pcap_if_t *devlist;
1545 long devnum;
1546 #endif
1547 int status;
1548 FILE *VFile;
1549 #ifdef HAVE_CAPSICUM
1550 cap_rights_t rights;
1551 int cansandbox;
1552 #endif /* HAVE_CAPSICUM */
1553 int Oflag = 1; /* run filter code optimizer */
1554 int yflag_dlt = -1;
1555 const char *yflag_dlt_name = NULL;
1556 int print = 0;
1557 long Cflagmult;
1558
1559 netdissect_options Ndo;
1560 netdissect_options *ndo = &Ndo;
1561
1562 #ifdef _WIN32
1563 /*
1564 * We need to look for wpcap.dll in \Windows\System32\Npcap first,
1565 * as either:
1566 *
1567 * 1) WinPcap isn't installed and Npcap isn't installed in "WinPcap
1568 * API-compatible Mode", so there's no wpcap.dll in
1569 * \Windows\System32, only in \Windows\System32\Npcap;
1570 *
1571 * 2) WinPcap is installed and Npcap isn't installed in "WinPcap
1572 * API-compatible Mode", so the wpcap.dll in \Windows\System32
1573 * is a WinPcap DLL, but we'd prefer an Npcap DLL (we should
1574 * work with either one if we're configured against WinPcap,
1575 * and we'll probably require Npcap if we're configured against
1576 * it), and that's in \Windows\System32\Npcap;
1577 *
1578 * 3) Npcap is installed in "WinPcap API-compatible Mode", so both
1579 * \Windows\System32 and \Windows\System32\Npcap have an Npcap
1580 * wpcap.dll.
1581 *
1582 * Unfortunately, Windows has no notion of an rpath, so we can't
1583 * set the rpath to include \Windows\System32\Npcap at link time;
1584 * what we need to do is to link wpcap as a delay-load DLL and
1585 * add \Windows\System32\Npcap to the DLL search path early in
1586 * main() with a call to SetDllDirectory().
1587 *
1588 * The same applies to packet.dll.
1589 *
1590 * We add \Windows\System32\Npcap here.
1591 *
1592 * See https://npcap.com/guide/npcap-devguide.html#npcap-feature-native-dll-implicitly
1593 */
1594 WCHAR *dll_directory = NULL;
1595 size_t dll_directory_buf_len = 0; /* units of bytes */
1596 UINT system_directory_buf_len = 0; /* units of WCHARs */
1597 UINT system_directory_len; /* units of WCHARs */
1598 static const WCHAR npcap[] = L"\\Npcap";
1599
1600 /*
1601 * Get the system directory path, in UTF-16, into a buffer that's
1602 * large enough for that directory path plus "\Npcap".
1603 *
1604 * String manipulation in C, plus fetching a variable-length
1605 * string into a buffer whose size is fixed at the time of
1606 * the call, with an oddball return value (see below), is just
1607 * a huge bag of fun.
1608 *
1609 * And it's even more fun when dealing with UTF-16, so that the
1610 * buffer sizes used in GetSystemDirectoryW() are in different
1611 * units from the buffer sizes used in realloc()! We maintain
1612 * all sizes/length in units of bytes, not WCHARs, so that our
1613 * heads don't explode.
1614 */
1615 for (;;) {
1616 /*
1617 * Try to fetch the system directory.
1618 *
1619 * GetSystemDirectoryW() expects a buffer size in units
1620 * of WCHARs, not bytes, and returns a directory path
1621 * length in units of WCHARs, not bytes.
1622 *
1623 * For extra fun, if GetSystemDirectoryW() succeeds,
1624 * the return value is the length of the directory
1625 * path in units of WCHARs, *not* including the
1626 * terminating '\0', but if it fails because the
1627 * path string wouldn't fit, the return value is
1628 * the length of the directory path in units of WCHARs,
1629 * *including* the terminating '\0'.
1630 */
1631 system_directory_len = GetSystemDirectoryW(dll_directory,
1632 system_directory_buf_len);
1633 if (system_directory_len == 0)
1634 error("GetSystemDirectoryW() failed");
1635
1636 /*
1637 * Did the directory path fit in the buffer?
1638 *
1639 * As per the above, this means that the return value
1640 * *plus 1*, so that the terminating '\0' is counted,
1641 * is <= the buffer size.
1642 *
1643 * (If the directory path, complete with the terminating
1644 * '\0', fits *exactly*, the return value would be the
1645 * size of the buffer minus 1, as it doesn't count the
1646 * terminating '\0', so the test below would succeed.
1647 *
1648 * If everything *but* the terminating '\0' fits,
1649 * the return value would be the size of the buffer + 1,
1650 * i.e., the size that the string in question would
1651 * have required.
1652 *
1653 * The astute reader will note that returning the
1654 * size of the buffer is not one of the two cases
1655 * above, and should never happen.)
1656 */
1657 if ((system_directory_len + 1) <= system_directory_buf_len) {
1658 /*
1659 * No. We have a buffer that's large enough
1660 * for our purposes.
1661 */
1662 break;
1663 }
1664
1665 /*
1666 * Yes. Grow the buffer.
1667 *
1668 * The space we'll need in the buffer for the system
1669 * directory, in units of WCHARs, is system_directory_len,
1670 * as that's the length of the system directory path
1671 * including the terminating '\0'.
1672 */
1673 system_directory_buf_len = system_directory_len;
1674
1675 /*
1676 * The size of the DLL directory buffer, in *bytes*, must
1677 * be the number of WCHARs taken by the system directory,
1678 * *minus* the terminating '\0' (as we'll overwrite that
1679 * with the "\" of the "\Npcap" string), multiplied by
1680 * sizeof(WCHAR) to convert it to the number of bytes,
1681 * plus the size of the "\Npcap" string, in bytes (which
1682 * will include the terminating '\0', as that will become
1683 * the DLL path's terminating '\0').
1684 */
1685 dll_directory_buf_len =
1686 ((system_directory_len - 1)*sizeof(WCHAR)) + sizeof npcap;
1687 dll_directory = realloc(dll_directory, dll_directory_buf_len);
1688 if (dll_directory == NULL)
1689 error("Can't allocate string for Npcap directory");
1690 }
1691
1692 /*
1693 * OK, that worked.
1694 *
1695 * Now append \Npcap. We add the length of the system directory path,
1696 * in WCHARs, *not* including the terminating '\0' (which, since
1697 * GetSystemDirectoryW() succeeded, is the return value of
1698 * GetSystemDirectoryW(), as per the above), to the pointer to the
1699 * beginning of the path, to go past the end of the system directory
1700 * to point to the terminating '\0'.
1701 */
1702 memcpy(dll_directory + system_directory_len, npcap, sizeof npcap);
1703
1704 /*
1705 * Now add that as a system DLL directory.
1706 */
1707 if (!SetDllDirectoryW(dll_directory))
1708 error("SetDllDirectory failed");
1709
1710 free(dll_directory);
1711 #endif
1712
1713 /*
1714 * Initialize the netdissect code.
1715 */
1716 if (nd_init(ebuf, sizeof(ebuf)) == -1)
1717 error("%s", ebuf);
1718
1719 memset(ndo, 0, sizeof(*ndo));
1720 ndo_set_function_pointers(ndo);
1721
1722 cnt = -1;
1723 device = NULL;
1724 infile = NULL;
1725 RFileName = NULL;
1726 VFileName = NULL;
1727 VFile = NULL;
1728 WFileName = NULL;
1729 dlt = -1;
1730 if ((cp = strrchr(argv[0], PATH_SEPARATOR)) != NULL)
1731 ndo->program_name = program_name = cp + 1;
1732 else
1733 ndo->program_name = program_name = argv[0];
1734
1735 #if defined(HAVE_PCAP_WSOCKINIT)
1736 if (pcap_wsockinit() != 0)
1737 error("Attempting to initialize Winsock failed");
1738 #elif defined(HAVE_WSOCKINIT)
1739 if (wsockinit() != 0)
1740 error("Attempting to initialize Winsock failed");
1741 #endif
1742
1743 /*
1744 * On platforms where the CPU doesn't support unaligned loads,
1745 * force unaligned accesses to abort with SIGBUS, rather than
1746 * being fixed up (slowly) by the OS kernel; on those platforms,
1747 * misaligned accesses are bugs, and we want tcpdump to crash so
1748 * that the bugs are reported.
1749 */
1750 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1751 error("%s", ebuf);
1752
1753 /*
1754 * An explicit tzset() call is usually not needed as it happens
1755 * implicitly the first time we call localtime() or mktime(),
1756 * but in some cases (sandboxing, chroot) this may be too late.
1757 */
1758 tzset();
1759
1760 while (
1761 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1762 switch (op) {
1763
1764 case 'a':
1765 /* compatibility for old -a */
1766 break;
1767
1768 case 'A':
1769 ++ndo->ndo_Aflag;
1770 break;
1771
1772 case 'b':
1773 ++ndo->ndo_bflag;
1774 break;
1775
1776 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1777 case 'B':
1778 Bflag = atoi(optarg)*1024;
1779 if (Bflag <= 0)
1780 error("invalid packet buffer size %s", optarg);
1781 break;
1782 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1783
1784 case 'c':
1785 cnt = atoi(optarg);
1786 if (cnt <= 0)
1787 error("invalid packet count %s", optarg);
1788 break;
1789
1790 case 'C':
1791 errno = 0;
1792 #ifdef HAVE_PCAP_DUMP_FTELL64
1793 Cflag = strtoint64_t(optarg, &endp, 10);
1794 #else
1795 Cflag = strtol(optarg, &endp, 10);
1796 #endif
1797 if (endp == optarg || errno != 0 || Cflag <= 0)
1798 error("invalid file size %s", optarg);
1799
1800 if (*endp == '\0') {
1801 /*
1802 * There's nothing after the file size,
1803 * so the size is in units of 1 MB
1804 * (1,000,000 bytes).
1805 */
1806 Cflagmult = 1000000;
1807 } else {
1808 /*
1809 * There's something after the file
1810 * size.
1811 *
1812 * If it's a single letter, then:
1813 *
1814 * if the letter is k or K, the size
1815 * is in units of 1 KiB (1024 bytes);
1816 *
1817 * if the letter is m or M, the size
1818 * is in units of 1 MiB (1,048,576 bytes);
1819 *
1820 * if the letter is g or G, the size
1821 * is in units of 1 GiB (1,073,741,824 bytes).
1822 *
1823 * Otherwise, it's an error.
1824 */
1825 switch (*endp) {
1826
1827 case 'k':
1828 case 'K':
1829 Cflagmult = 1024;
1830 break;
1831
1832 case 'm':
1833 case 'M':
1834 Cflagmult = 1024*1024;
1835 break;
1836
1837 case 'g':
1838 case 'G':
1839 Cflagmult = 1024*1024*1024;
1840 break;
1841
1842 default:
1843 error("invalid file size %s", optarg);
1844 }
1845
1846 /*
1847 * OK, there was a letter that we treat
1848 * as a units indication; was there
1849 * anything after it?
1850 */
1851 endp++;
1852 if (*endp != '\0') {
1853 /* Yes - error */
1854 error("invalid file size %s", optarg);
1855 }
1856 }
1857
1858 /*
1859 * Will multiplying it by multiplier overflow?
1860 */
1861 #ifdef HAVE_PCAP_DUMP_FTELL64
1862 if (Cflag > INT64_MAX / Cflagmult)
1863 #else
1864 if (Cflag > LONG_MAX / Cflagmult)
1865 #endif
1866 error("file size %s is too large", optarg);
1867 Cflag *= Cflagmult;
1868 break;
1869
1870 case 'd':
1871 ++dflag;
1872 break;
1873
1874 #ifdef HAVE_PCAP_FINDALLDEVS
1875 case 'D':
1876 Dflag++;
1877 break;
1878 #endif
1879
1880 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1881 case OPTION_LIST_REMOTE_INTERFACES:
1882 remote_interfaces_source = optarg;
1883 break;
1884 #endif
1885
1886 case 'L':
1887 Lflag++;
1888 break;
1889
1890 case 'e':
1891 ++ndo->ndo_eflag;
1892 break;
1893
1894 #ifdef HAVE_LIBCRYPTO
1895 case 'E':
1896 ndo->ndo_espsecret = optarg;
1897 break;
1898 #endif
1899
1900 case 'f':
1901 ++ndo->ndo_fflag;
1902 break;
1903
1904 case 'F':
1905 infile = optarg;
1906 break;
1907
1908 case 'g':
1909 ++ndo->ndo_gflag;
1910 break;
1911
1912 case 'G':
1913 Gflag = atoi(optarg);
1914 if (Gflag < 0)
1915 error("invalid number of seconds %s", optarg);
1916
1917 /* We will create one file initially. */
1918 Gflag_count = 0;
1919
1920 /* Grab the current time for rotation use. */
1921 if ((Gflag_time = time(NULL)) == (time_t)-1) {
1922 error("%s: can't get current time: %s",
1923 __func__, pcap_strerror(errno));
1924 }
1925 break;
1926
1927 case 'h':
1928 print_usage(stdout);
1929 exit_tcpdump(S_SUCCESS);
1930 break;
1931
1932 case 'H':
1933 ++ndo->ndo_Hflag;
1934 break;
1935
1936 case 'i':
1937 device = optarg;
1938 break;
1939
1940 #ifdef HAVE_PCAP_CREATE
1941 case 'I':
1942 ++Iflag;
1943 break;
1944 #endif /* HAVE_PCAP_CREATE */
1945
1946 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1947 case 'j':
1948 jflag = pcap_tstamp_type_name_to_val(optarg);
1949 if (jflag < 0)
1950 error("invalid time stamp type %s", optarg);
1951 break;
1952
1953 case 'J':
1954 Jflag++;
1955 break;
1956 #endif
1957
1958 case 'l':
1959 #ifdef _WIN32
1960 /*
1961 * _IOLBF is the same as _IOFBF in Microsoft's C
1962 * libraries; the only alternative they offer
1963 * is _IONBF.
1964 *
1965 * XXX - this should really be checking for MSVC++,
1966 * not _WIN32, if, for example, MinGW has its own
1967 * C library that is more UNIX-compatible.
1968 */
1969 setvbuf(stdout, NULL, _IONBF, 0);
1970 #else /* _WIN32 */
1971 #ifdef HAVE_SETLINEBUF
1972 setlinebuf(stdout);
1973 #else
1974 setvbuf(stdout, NULL, _IOLBF, 0);
1975 #endif
1976 #endif /* _WIN32 */
1977 lflag = 1;
1978 break;
1979
1980 case 'K':
1981 ++ndo->ndo_Kflag;
1982 break;
1983
1984 case 'm':
1985 if (nd_have_smi_support()) {
1986 if (nd_load_smi_module(optarg, ebuf, sizeof(ebuf)) == -1)
1987 error("%s", ebuf);
1988 } else {
1989 (void)fprintf(stderr, "%s: ignoring option '-m %s' ",
1990 program_name, optarg);
1991 (void)fprintf(stderr, "(no libsmi support)\n");
1992 }
1993 break;
1994
1995 #ifdef HAVE_LIBCRYPTO
1996 case 'M':
1997 /* TCP-MD5 shared secret */
1998 ndo->ndo_sigsecret = optarg;
1999 break;
2000 #endif
2001
2002 case 'n':
2003 ++ndo->ndo_nflag;
2004 break;
2005
2006 case 'N':
2007 ++ndo->ndo_Nflag;
2008 break;
2009
2010 case 'O':
2011 Oflag = 0;
2012 break;
2013
2014 case 'p':
2015 ++pflag;
2016 break;
2017
2018 case 'q':
2019 ++ndo->ndo_qflag;
2020 ++ndo->ndo_suppress_default_print;
2021 break;
2022
2023 #ifdef HAVE_PCAP_SETDIRECTION
2024 case 'Q':
2025 if (ascii_strcasecmp(optarg, "in") == 0)
2026 Qflag = PCAP_D_IN;
2027 else if (ascii_strcasecmp(optarg, "out") == 0)
2028 Qflag = PCAP_D_OUT;
2029 else if (ascii_strcasecmp(optarg, "inout") == 0)
2030 Qflag = PCAP_D_INOUT;
2031 else
2032 error("unknown capture direction '%s'", optarg);
2033 break;
2034 #endif /* HAVE_PCAP_SETDIRECTION */
2035
2036 case 'r':
2037 RFileName = optarg;
2038 break;
2039
2040 case 's':
2041 ndo->ndo_snaplen = (int)strtol(optarg, &end, 0);
2042 if (optarg == end || *end != '\0'
2043 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
2044 error("invalid snaplen %s (must be >= 0 and <= %d)",
2045 optarg, MAXIMUM_SNAPLEN);
2046 break;
2047
2048 case 'S':
2049 ++ndo->ndo_Sflag;
2050 break;
2051
2052 case 't':
2053 ++ndo->ndo_tflag;
2054 break;
2055
2056 case 'T':
2057 if (ascii_strcasecmp(optarg, "vat") == 0)
2058 ndo->ndo_packettype = PT_VAT;
2059 else if (ascii_strcasecmp(optarg, "wb") == 0)
2060 ndo->ndo_packettype = PT_WB;
2061 else if (ascii_strcasecmp(optarg, "rpc") == 0)
2062 ndo->ndo_packettype = PT_RPC;
2063 else if (ascii_strcasecmp(optarg, "rtp") == 0)
2064 ndo->ndo_packettype = PT_RTP;
2065 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
2066 ndo->ndo_packettype = PT_RTCP;
2067 else if (ascii_strcasecmp(optarg, "snmp") == 0)
2068 ndo->ndo_packettype = PT_SNMP;
2069 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
2070 ndo->ndo_packettype = PT_CNFP;
2071 else if (ascii_strcasecmp(optarg, "tftp") == 0)
2072 ndo->ndo_packettype = PT_TFTP;
2073 else if (ascii_strcasecmp(optarg, "aodv") == 0)
2074 ndo->ndo_packettype = PT_AODV;
2075 else if (ascii_strcasecmp(optarg, "carp") == 0)
2076 ndo->ndo_packettype = PT_CARP;
2077 else if (ascii_strcasecmp(optarg, "radius") == 0)
2078 ndo->ndo_packettype = PT_RADIUS;
2079 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
2080 ndo->ndo_packettype = PT_ZMTP1;
2081 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
2082 ndo->ndo_packettype = PT_VXLAN;
2083 else if (ascii_strcasecmp(optarg, "pgm") == 0)
2084 ndo->ndo_packettype = PT_PGM;
2085 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
2086 ndo->ndo_packettype = PT_PGM_ZMTP1;
2087 else if (ascii_strcasecmp(optarg, "lmp") == 0)
2088 ndo->ndo_packettype = PT_LMP;
2089 else if (ascii_strcasecmp(optarg, "resp") == 0)
2090 ndo->ndo_packettype = PT_RESP;
2091 else if (ascii_strcasecmp(optarg, "ptp") == 0)
2092 ndo->ndo_packettype = PT_PTP;
2093 else if (ascii_strcasecmp(optarg, "someip") == 0)
2094 ndo->ndo_packettype = PT_SOMEIP;
2095 else if (ascii_strcasecmp(optarg, "domain") == 0)
2096 ndo->ndo_packettype = PT_DOMAIN;
2097 else
2098 error("unknown packet type '%s'", optarg);
2099 break;
2100
2101 case 'u':
2102 ++ndo->ndo_uflag;
2103 break;
2104
2105 #ifdef HAVE_PCAP_DUMP_FLUSH
2106 case 'U':
2107 ++Uflag;
2108 break;
2109 #endif
2110
2111 case 'v':
2112 ++ndo->ndo_vflag;
2113 break;
2114
2115 case 'V':
2116 VFileName = optarg;
2117 break;
2118
2119 case 'w':
2120 WFileName = optarg;
2121 break;
2122
2123 case 'W':
2124 Wflag = atoi(optarg);
2125 if (Wflag <= 0)
2126 error("invalid number of output files %s", optarg);
2127 WflagChars = getWflagChars(Wflag);
2128 break;
2129
2130 case 'x':
2131 ++ndo->ndo_xflag;
2132 ++ndo->ndo_suppress_default_print;
2133 break;
2134
2135 case 'X':
2136 ++ndo->ndo_Xflag;
2137 ++ndo->ndo_suppress_default_print;
2138 break;
2139
2140 case 'y':
2141 yflag_dlt_name = optarg;
2142 yflag_dlt =
2143 pcap_datalink_name_to_val(yflag_dlt_name);
2144 if (yflag_dlt < 0)
2145 error("invalid data link type %s", yflag_dlt_name);
2146 break;
2147
2148 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
2149 case 'Y':
2150 {
2151 /* Undocumented flag */
2152 pcap_set_parser_debug(1);
2153 }
2154 break;
2155 #endif
2156
2157 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2158 case 'z':
2159 zflag = optarg;
2160 break;
2161 #endif
2162
2163 case 'Z':
2164 username = optarg;
2165 break;
2166
2167 case '#':
2168 ndo->ndo_packet_number = 1;
2169 break;
2170
2171 case OPTION_TIME_T_SIZE:
2172 printf("%zu\n", sizeof(time_t) * 8);
2173 return 0;
2174
2175 case OPTION_VERSION:
2176 print_version(stdout);
2177 exit_tcpdump(S_SUCCESS);
2178 break;
2179
2180 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2181 case OPTION_TSTAMP_PRECISION:
2182 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
2183 if (ndo->ndo_tstamp_precision < 0)
2184 error("unsupported time stamp precision");
2185 break;
2186 #endif
2187
2188 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2189 case OPTION_IMMEDIATE_MODE:
2190 immediate_mode = 1;
2191 break;
2192 #endif
2193
2194 case OPTION_PRINT:
2195 print = 1;
2196 break;
2197
2198 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2199 case OPTION_TSTAMP_MICRO:
2200 ndo->ndo_tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
2201 break;
2202
2203 case OPTION_TSTAMP_NANO:
2204 ndo->ndo_tstamp_precision = PCAP_TSTAMP_PRECISION_NANO;
2205 break;
2206 #endif
2207
2208 case OPTION_FP_TYPE:
2209 /*
2210 * Print out the type of floating-point arithmetic
2211 * we're doing; it's probably IEEE, unless somebody
2212 * tries to run this on a VAX, but the precision
2213 * may differ (e.g., it might be 32-bit, 64-bit,
2214 * or 80-bit).
2215 */
2216 float_type_check(0x4e93312d);
2217 return 0;
2218
2219 case OPTION_COUNT:
2220 count_mode = 1;
2221 break;
2222
2223 default:
2224 print_usage(stderr);
2225 exit_tcpdump(S_ERR_HOST_PROGRAM);
2226 /* NOTREACHED */
2227 }
2228
2229 if (ndo->ndo_Aflag && ndo->ndo_xflag)
2230 error("-A and -x[x] are mutually exclusive.");
2231 if (ndo->ndo_Aflag && ndo->ndo_Xflag)
2232 error("-A and -X[X] are mutually exclusive.");
2233 if (ndo->ndo_xflag && ndo->ndo_Xflag)
2234 error("-x[x] and -X[X] are mutually exclusive.");
2235 if (Cflag != 0 && WFileName == NULL)
2236 error("-C cannot be used without -w.");
2237 if (Gflag != 0 && WFileName == NULL)
2238 error("-G cannot be used without -w.");
2239 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2240 if (zflag != NULL && (WFileName == NULL || (Cflag == 0 && Gflag == 0)))
2241 error("-z cannot be used without -w and (-C or -G).");
2242 #endif
2243
2244 #ifdef HAVE_PCAP_FINDALLDEVS
2245 if (Dflag)
2246 show_devices_and_exit();
2247 #endif
2248 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2249 if (remote_interfaces_source != NULL)
2250 show_remote_devices_and_exit();
2251 #endif
2252
2253 switch (ndo->ndo_tflag) {
2254
2255 case 0: /* Default */
2256 case 1: /* No time stamp */
2257 case 2: /* Unix timeval style */
2258 case 3: /* Microseconds/nanoseconds since previous packet */
2259 case 4: /* Date + Default */
2260 case 5: /* Microseconds/nanoseconds since first packet */
2261 break;
2262
2263 default: /* Not supported */
2264 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
2265 break;
2266 }
2267
2268 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
2269 error("-f cannot be used with -V or -r.");
2270
2271 if (VFileName != NULL && RFileName != NULL)
2272 error("-V and -r are mutually exclusive.");
2273
2274 /*
2275 * If we're printing dissected packets to the standard output,
2276 * and either the standard output is a terminal or we're doing
2277 * "line" buffering, set the capture timeout to .1 second rather
2278 * than 1 second, as the user's probably expecting to see packets
2279 * pop up immediately shortly after they arrive.
2280 *
2281 * XXX - would there be some value appropriate for all cases,
2282 * based on, say, the buffer size and packet input rate?
2283 */
2284 if ((WFileName == NULL || print) && (isatty(1) || lflag))
2285 timeout = 100;
2286
2287 #ifdef WITH_CHROOT
2288 /* if run as root, prepare for chrooting */
2289 if (getuid() == 0 || geteuid() == 0) {
2290 /* future extensibility for cmd-line arguments */
2291 if (!chroot_dir)
2292 chroot_dir = WITH_CHROOT;
2293 }
2294 #endif
2295
2296 #ifdef WITH_USER
2297 /* if run as root, prepare for dropping root privileges */
2298 if (getuid() == 0 || geteuid() == 0) {
2299 /* Run with '-Z root' to restore old behaviour */
2300 if (!username)
2301 username = WITH_USER;
2302 else if (strcmp(username, "root") == 0)
2303 username = NULL;
2304 }
2305 #endif
2306
2307 if (RFileName != NULL || VFileName != NULL) {
2308 /*
2309 * If RFileName is non-null, it's the pathname of a
2310 * savefile to read. If VFileName is non-null, it's
2311 * the pathname of a file containing a list of pathnames
2312 * (one per line) of savefiles to read.
2313 *
2314 * In either case, we're reading a savefile, not doing
2315 * a live capture.
2316 */
2317 #ifndef _WIN32
2318 /*
2319 * We don't need network access, so relinquish any set-UID
2320 * or set-GID privileges we have (if any).
2321 *
2322 * We do *not* want set-UID privileges when opening a
2323 * trace file, as that might let the user read other
2324 * people's trace files (especially if we're set-UID
2325 * root).
2326 */
2327 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
2328 fprintf(stderr, "Warning: setgid/setuid failed !\n");
2329 #endif /* _WIN32 */
2330 if (VFileName != NULL) {
2331 if (VFileName[0] == '-' && VFileName[1] == '\0')
2332 VFile = stdin;
2333 else
2334 VFile = fopen(VFileName, "r");
2335
2336 if (VFile == NULL)
2337 error("Unable to open file: %s", pcap_strerror(errno));
2338
2339 ret = get_next_file(VFile, VFileLine);
2340 if (!ret)
2341 error("Nothing in %s", VFileName);
2342 RFileName = VFileLine;
2343 }
2344
2345 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2346 pd = pcap_open_offline_with_tstamp_precision(RFileName,
2347 ndo->ndo_tstamp_precision, ebuf);
2348 #else
2349 pd = pcap_open_offline(RFileName, ebuf);
2350 #endif
2351
2352 if (pd == NULL)
2353 error("%s", ebuf);
2354 #ifdef HAVE_CAPSICUM
2355 cap_rights_init(&rights, CAP_READ);
2356 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
2357 errno != ENOSYS) {
2358 error("unable to limit pcap descriptor");
2359 }
2360 #endif
2361 dlt = pcap_datalink(pd);
2362 dlt_name = pcap_datalink_val_to_name(dlt);
2363 fprintf(stderr, "reading from file %s", RFileName);
2364 if (dlt_name == NULL) {
2365 fprintf(stderr, ", link-type %u", dlt);
2366 } else {
2367 fprintf(stderr, ", link-type %s (%s)", dlt_name,
2368 pcap_datalink_val_to_description(dlt));
2369 }
2370 fprintf(stderr, ", snapshot length %d\n", pcap_snapshot(pd));
2371 #ifdef DLT_LINUX_SLL2
2372 if (dlt == DLT_LINUX_SLL2)
2373 fprintf(stderr, "Warning: interface names might be incorrect\n");
2374 #endif
2375 } else if (dflag && !device) {
2376 int dump_dlt = DLT_EN10MB;
2377 /*
2378 * We're dumping the compiled code without an explicit
2379 * device specification. (If a device is specified, we
2380 * definitely want to open it to use the DLT of that device.)
2381 * Either default to DLT_EN10MB with a warning, or use
2382 * the user-specified value if supplied.
2383 */
2384 /*
2385 * If no snapshot length was specified, or a length of 0 was
2386 * specified, default to 256KB.
2387 */
2388 if (ndo->ndo_snaplen == 0)
2389 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
2390 /*
2391 * If a DLT was specified with the -y flag, use that instead.
2392 */
2393 if (yflag_dlt != -1)
2394 dump_dlt = yflag_dlt;
2395 else
2396 fprintf(stderr, "Warning: assuming Ethernet\n");
2397 pd = pcap_open_dead(dump_dlt, ndo->ndo_snaplen);
2398 } else {
2399 /*
2400 * We're doing a live capture.
2401 */
2402 if (device == NULL) {
2403 /*
2404 * No interface was specified. Pick one.
2405 */
2406 #ifdef HAVE_PCAP_FINDALLDEVS
2407 /*
2408 * Find the list of interfaces, and pick
2409 * the first interface.
2410 */
2411 if (pcap_findalldevs(&devlist, ebuf) == -1)
2412 error("%s", ebuf);
2413 if (devlist == NULL)
2414 error("no interfaces available for capture");
2415 device = strdup(devlist->name);
2416 pcap_freealldevs(devlist);
2417 #else /* HAVE_PCAP_FINDALLDEVS */
2418 /*
2419 * Use whatever interface pcap_lookupdev()
2420 * chooses.
2421 */
2422 device = pcap_lookupdev(ebuf);
2423 if (device == NULL)
2424 error("%s", ebuf);
2425 #endif
2426 }
2427
2428 /*
2429 * Try to open the interface with the specified name.
2430 */
2431 pd = open_interface(device, ndo, ebuf);
2432 if (pd == NULL) {
2433 /*
2434 * That failed. If we can get a list of
2435 * interfaces, and the interface name
2436 * is purely numeric, try to use it as
2437 * a 1-based index in the list of
2438 * interfaces.
2439 */
2440 #ifdef HAVE_PCAP_FINDALLDEVS
2441 devnum = parse_interface_number(device);
2442 if (devnum == -1) {
2443 /*
2444 * It's not a number; just report
2445 * the open error and fail.
2446 */
2447 error("%s", ebuf);
2448 }
2449
2450 /*
2451 * OK, it's a number; try to find the
2452 * interface with that index, and try
2453 * to open it.
2454 *
2455 * find_interface_by_number() exits if it
2456 * couldn't be found.
2457 */
2458 device = find_interface_by_number(device, devnum);
2459 pd = open_interface(device, ndo, ebuf);
2460 if (pd == NULL)
2461 error("%s", ebuf);
2462 #else /* HAVE_PCAP_FINDALLDEVS */
2463 /*
2464 * We can't get a list of interfaces; just
2465 * fail.
2466 */
2467 error("%s", ebuf);
2468 #endif /* HAVE_PCAP_FINDALLDEVS */
2469 }
2470
2471 /*
2472 * Let user own process after capture device has
2473 * been opened.
2474 */
2475 #ifndef _WIN32
2476 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2477 fprintf(stderr, "Warning: setgid/setuid failed !\n");
2478 #endif /* _WIN32 */
2479 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2480 if(Bflag != 0)
2481 if(pcap_setbuff(pd, Bflag)==-1){
2482 error("%s", pcap_geterr(pd));
2483 }
2484 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2485 if (Lflag)
2486 show_dlts_and_exit(pd, device);
2487 if (yflag_dlt >= 0) {
2488 #ifdef HAVE_PCAP_SET_DATALINK
2489 if (pcap_set_datalink(pd, yflag_dlt) < 0)
2490 error("%s", pcap_geterr(pd));
2491 #else
2492 /*
2493 * We don't actually support changing the
2494 * data link type, so we only let them
2495 * set it to what it already is.
2496 */
2497 if (yflag_dlt != pcap_datalink(pd)) {
2498 error("%s is not one of the DLTs supported by this device\n",
2499 yflag_dlt_name);
2500 }
2501 #endif
2502 (void)fprintf(stderr, "%s: data link type %s\n",
2503 program_name,
2504 pcap_datalink_val_to_name(yflag_dlt));
2505 (void)fflush(stderr);
2506 }
2507 #if defined(DLT_LINUX_SLL2) && defined(HAVE_PCAP_SET_DATALINK)
2508 else {
2509 /*
2510 * Attempt to set default linktype to
2511 * DLT_LINUX_SLL2 when capturing on the
2512 * "any" device.
2513 *
2514 * If the attempt fails, just quietly drive
2515 * on; this may be a non-Linux "any" device
2516 * that doesn't support DLT_LINUX_SLL2.
2517 */
2518 if (strcmp(device, "any") == 0) {
2519 DIAG_OFF_WARN_UNUSED_RESULT
2520 (void) pcap_set_datalink(pd, DLT_LINUX_SLL2);
2521 DIAG_ON_WARN_UNUSED_RESULT
2522 }
2523 }
2524 #endif
2525 i = pcap_snapshot(pd);
2526 if (ndo->ndo_snaplen < i) {
2527 if (ndo->ndo_snaplen != 0)
2528 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
2529 ndo->ndo_snaplen = i;
2530 } else if (ndo->ndo_snaplen > i) {
2531 warning("snaplen lowered from %d to %d", ndo->ndo_snaplen, i);
2532 ndo->ndo_snaplen = i;
2533 }
2534 if(ndo->ndo_fflag != 0) {
2535 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
2536 warning("foreign (-f) flag used but: %s", ebuf);
2537 }
2538 }
2539
2540 }
2541 if (infile)
2542 cmdbuf = read_infile(infile);
2543 else
2544 cmdbuf = copy_argv(&argv[optind]);
2545
2546 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2547 pcap_set_optimizer_debug(dflag);
2548 #endif
2549 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2550 error("%s", pcap_geterr(pd));
2551 if (dflag) {
2552 bpf_dump(&fcode, dflag);
2553 pcap_close(pd);
2554 free(cmdbuf);
2555 pcap_freecode(&fcode);
2556 exit_tcpdump(S_SUCCESS);
2557 }
2558
2559 #ifdef HAVE_CASPER
2560 if (!ndo->ndo_nflag)
2561 capdns = capdns_setup();
2562 #endif /* HAVE_CASPER */
2563
2564 init_print(ndo, localnet, netmask);
2565
2566 #ifndef _WIN32
2567 (void)setsignal(SIGPIPE, cleanup);
2568 (void)setsignal(SIGTERM, cleanup);
2569 #endif /* _WIN32 */
2570 (void)setsignal(SIGINT, cleanup);
2571 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2572 (void)setsignal(SIGCHLD, child_cleanup);
2573 #endif
2574 /* Cooperate with nohup(1) */
2575 #ifndef _WIN32
2576 /*
2577 * In illumos /usr/include/sys/iso/signal_iso.h causes Clang to
2578 * generate a -Wstrict-prototypes warning here, see [1]. The
2579 * __illumos__ macro is available since at least GCC 11 and Clang 13,
2580 * see [2].
2581 * 1: https://www.illumos.org/issues/16344
2582 * 2: https://www.illumos.org/issues/13726
2583 */
2584 #ifdef __illumos__
2585 DIAG_OFF_STRICT_PROTOTYPES
2586 #endif /* __illumos__ */
2587 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
2588 #ifdef __illumos__
2589 DIAG_ON_STRICT_PROTOTYPES
2590 #endif /* __illumos__ */
2591 (void)setsignal(SIGHUP, oldhandler);
2592 #endif /* _WIN32 */
2593
2594 #ifndef _WIN32
2595 /*
2596 * If a user name was specified with "-Z", attempt to switch to
2597 * that user's UID. This would probably be used with sudo,
2598 * to allow tcpdump to be run in a special restricted
2599 * account (if you just want to allow users to open capture
2600 * devices, and can't just give users that permission,
2601 * you'd make tcpdump set-UID or set-GID).
2602 *
2603 * tcpdump doesn't necessarily write only to one savefile;
2604 * the general only way to allow a -Z instance to write to
2605 * savefiles as the user under whose UID it's run, rather
2606 * than as the user specified with -Z, would thus be to switch
2607 * to the original user ID before opening a capture file and
2608 * then switch back to the -Z user ID after opening the savefile.
2609 * Switching to the -Z user ID only after opening the first
2610 * savefile doesn't handle the general case.
2611 */
2612
2613 if (getuid() == 0 || geteuid() == 0) {
2614 #ifdef HAVE_LIBCAP_NG
2615 /* Initialize capng */
2616 capng_clear(CAPNG_SELECT_BOTH);
2617 if (username) {
2618 DIAG_OFF_ASSIGN_ENUM
2619 capng_updatev(
2620 CAPNG_ADD,
2621 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2622 CAP_SETUID,
2623 CAP_SETGID,
2624 -1);
2625 DIAG_ON_ASSIGN_ENUM
2626 }
2627 if (chroot_dir) {
2628 DIAG_OFF_ASSIGN_ENUM
2629 capng_update(
2630 CAPNG_ADD,
2631 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2632 CAP_SYS_CHROOT
2633 );
2634 DIAG_ON_ASSIGN_ENUM
2635 }
2636
2637 if (WFileName) {
2638 DIAG_OFF_ASSIGN_ENUM
2639 capng_update(
2640 CAPNG_ADD,
2641 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
2642 CAP_DAC_OVERRIDE
2643 );
2644 DIAG_ON_ASSIGN_ENUM
2645 }
2646 capng_apply(CAPNG_SELECT_BOTH);
2647 #endif /* HAVE_LIBCAP_NG */
2648 if (username || chroot_dir)
2649 droproot(username, chroot_dir);
2650
2651 }
2652 #endif /* _WIN32 */
2653
2654 if (pcap_setfilter(pd, &fcode) < 0)
2655 error("%s", pcap_geterr(pd));
2656 #ifdef HAVE_CAPSICUM
2657 if (RFileName == NULL && VFileName == NULL && pcap_fileno(pd) != -1) {
2658 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
2659
2660 /*
2661 * The various libpcap devices use a combination of
2662 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2663 * so we add the relevant access rights.
2664 */
2665 cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
2666 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
2667 errno != ENOSYS) {
2668 error("unable to limit pcap descriptor");
2669 }
2670 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
2671 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
2672 error("unable to limit ioctls on pcap descriptor");
2673 }
2674 }
2675 #endif
2676 if (WFileName) {
2677 /* Do not exceed the default PATH_MAX for files. */
2678 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
2679
2680 if (dumpinfo.CurrentFileName == NULL)
2681 error("malloc of dumpinfo.CurrentFileName");
2682
2683 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2684 if (Cflag != 0)
2685 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
2686 else
2687 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
2688
2689 pdd = pcap_dump_open(pd, dumpinfo.CurrentFileName);
2690 #ifdef HAVE_LIBCAP_NG
2691 /* Give up CAP_DAC_OVERRIDE capability.
2692 * Only allow it to be restored if the -C or -G flag have been
2693 * set since we may need to create more files later on.
2694 */
2695 capng_update(
2696 CAPNG_DROP,
2697 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
2698 | CAPNG_EFFECTIVE,
2699 CAP_DAC_OVERRIDE
2700 );
2701 capng_apply(CAPNG_SELECT_BOTH);
2702 #endif /* HAVE_LIBCAP_NG */
2703 if (pdd == NULL)
2704 error("%s", pcap_geterr(pd));
2705 #ifdef HAVE_CAPSICUM
2706 set_dumper_capsicum_rights(pdd);
2707 #endif
2708 if (Cflag != 0 || Gflag != 0) {
2709 #ifdef HAVE_CAPSICUM
2710 /*
2711 * basename() and dirname() may modify their input buffer
2712 * and they do since FreeBSD 12.0, but they didn't before.
2713 * Hence use the return value only, but always assume the
2714 * input buffer has been modified and would need to be
2715 * reset before the next use.
2716 */
2717 char *WFileName_copy;
2718
2719 if ((WFileName_copy = strdup(WFileName)) == NULL) {
2720 error("Unable to allocate memory for file %s",
2721 WFileName);
2722 }
2723 DIAG_OFF_C11_EXTENSIONS
2724 dumpinfo.WFileName = strdup(basename(WFileName_copy));
2725 DIAG_ON_C11_EXTENSIONS
2726 if (dumpinfo.WFileName == NULL) {
2727 error("Unable to allocate memory for file %s",
2728 WFileName);
2729 }
2730 free(WFileName_copy);
2731
2732 if ((WFileName_copy = strdup(WFileName)) == NULL) {
2733 error("Unable to allocate memory for file %s",
2734 WFileName);
2735 }
2736 DIAG_OFF_C11_EXTENSIONS
2737 char *WFileName_dirname = dirname(WFileName_copy);
2738 DIAG_ON_C11_EXTENSIONS
2739 dumpinfo.dirfd = open(WFileName_dirname,
2740 O_DIRECTORY | O_RDONLY);
2741 if (dumpinfo.dirfd < 0) {
2742 error("unable to open directory %s",
2743 WFileName_dirname);
2744 }
2745 free(WFileName_dirname);
2746 free(WFileName_copy);
2747
2748 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
2749 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
2750 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
2751 errno != ENOSYS) {
2752 error("unable to limit directory rights");
2753 }
2754 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
2755 errno != ENOSYS) {
2756 error("unable to limit dump descriptor fcntls");
2757 }
2758 #else /* !HAVE_CAPSICUM */
2759 dumpinfo.WFileName = WFileName;
2760 #endif
2761 callback = dump_packet_and_trunc;
2762 dumpinfo.pd = pd;
2763 dumpinfo.pdd = pdd;
2764 pcap_userdata = (u_char *)&dumpinfo;
2765 } else {
2766 callback = dump_packet;
2767 dumpinfo.WFileName = WFileName;
2768 dumpinfo.pd = pd;
2769 dumpinfo.pdd = pdd;
2770 pcap_userdata = (u_char *)&dumpinfo;
2771 }
2772 if (print) {
2773 dlt = pcap_datalink(pd);
2774 ndo->ndo_if_printer = get_if_printer(dlt);
2775 dumpinfo.ndo = ndo;
2776 } else
2777 dumpinfo.ndo = NULL;
2778
2779 #ifdef HAVE_PCAP_DUMP_FLUSH
2780 if (Uflag)
2781 pcap_dump_flush(pdd);
2782 #endif
2783 } else {
2784 dlt = pcap_datalink(pd);
2785 ndo->ndo_if_printer = get_if_printer(dlt);
2786 callback = print_packet;
2787 pcap_userdata = (u_char *)ndo;
2788 }
2789
2790 #ifdef SIGNAL_REQ_INFO
2791 /*
2792 * We can't get statistics when reading from a file rather
2793 * than capturing from a device.
2794 */
2795 if (RFileName == NULL)
2796 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
2797 #endif
2798 #ifdef SIGNAL_FLUSH_PCAP
2799 (void)setsignal(SIGNAL_FLUSH_PCAP, flushpcap);
2800 #endif
2801
2802 if (ndo->ndo_vflag > 0 && WFileName && RFileName == NULL && !print) {
2803 /*
2804 * When capturing to a file, if "--print" wasn't specified,
2805 *"-v" means tcpdump should, once per second,
2806 * "v"erbosely report the number of packets captured.
2807 * Except when reading from a file, because -r, -w and -v
2808 * together used to make a corner case, in which pcap_loop()
2809 * errored due to EINTR (see GH #155 for details).
2810 */
2811 #ifdef _WIN32
2812 /*
2813 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2814 *
2815 * suggests that this dates back to W2K.
2816 *
2817 * I don't know what a "long wait" is, but we'll assume
2818 * that printing the stats could be a "long wait".
2819 */
2820 CreateTimerQueueTimer(&timer_handle, NULL,
2821 verbose_stats_dump, NULL, 1000, 1000,
2822 WT_EXECUTEDEFAULT|WT_EXECUTELONGFUNCTION);
2823 setvbuf(stderr, NULL, _IONBF, 0);
2824 #else /* _WIN32 */
2825 /*
2826 * Assume this is UN*X, and that it has setitimer(); that
2827 * dates back to UNIX 95.
2828 */
2829 struct itimerval timer;
2830 (void)setsignal(SIGALRM, verbose_stats_dump);
2831 timer.it_interval.tv_sec = 1;
2832 timer.it_interval.tv_usec = 0;
2833 timer.it_value.tv_sec = 1;
2834 timer.it_value.tv_usec = 1;
2835 setitimer(ITIMER_REAL, &timer, NULL);
2836 #endif /* _WIN32 */
2837 }
2838
2839 if (RFileName == NULL) {
2840 /*
2841 * Live capture (if -V was specified, we set RFileName
2842 * to a file from the -V file). Print a message to
2843 * the standard error on UN*X.
2844 */
2845 if (!ndo->ndo_vflag && !WFileName) {
2846 (void)fprintf(stderr,
2847 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n",
2848 program_name);
2849 } else
2850 (void)fprintf(stderr, "%s: ", program_name);
2851 dlt = pcap_datalink(pd);
2852 dlt_name = pcap_datalink_val_to_name(dlt);
2853 (void)fprintf(stderr, "listening on %s", device);
2854 if (dlt_name == NULL) {
2855 (void)fprintf(stderr, ", link-type %u", dlt);
2856 } else {
2857 (void)fprintf(stderr, ", link-type %s (%s)", dlt_name,
2858 pcap_datalink_val_to_description(dlt));
2859 }
2860 (void)fprintf(stderr, ", snapshot length %d bytes\n", ndo->ndo_snaplen);
2861 (void)fflush(stderr);
2862 }
2863
2864 #ifdef HAVE_CAPSICUM
2865 cansandbox = (VFileName == NULL && zflag == NULL &&
2866 ndo->ndo_espsecret == NULL);
2867 #ifdef HAVE_CASPER
2868 cansandbox = (cansandbox && (ndo->ndo_nflag || capdns != NULL));
2869 #else
2870 cansandbox = (cansandbox && ndo->ndo_nflag);
2871 #endif /* HAVE_CASPER */
2872 cansandbox = (cansandbox && (pcap_fileno(pd) != -1 ||
2873 RFileName != NULL));
2874
2875 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2876 error("unable to enter the capability mode");
2877 #endif /* HAVE_CAPSICUM */
2878
2879 do {
2880 status = pcap_loop(pd, cnt, callback, pcap_userdata);
2881 if (WFileName == NULL) {
2882 /*
2883 * We're printing packets. Flush the printed output,
2884 * so it doesn't get intermingled with error output.
2885 */
2886 if (status == -2) {
2887 /*
2888 * We got interrupted, so perhaps we didn't
2889 * manage to finish a line we were printing.
2890 * Print an extra newline, just in case.
2891 */
2892 putchar('\n');
2893 }
2894 (void)fflush(stdout);
2895 }
2896 if (status == -2) {
2897 /*
2898 * We got interrupted. If we are reading multiple
2899 * files (via -V) set these so that we stop.
2900 */
2901 VFileName = NULL;
2902 ret = NULL;
2903 }
2904 if (status == -1) {
2905 /*
2906 * Error. Report it.
2907 */
2908 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
2909 program_name, pcap_geterr(pd));
2910 }
2911 if (RFileName == NULL) {
2912 /*
2913 * We're doing a live capture. Report the capture
2914 * statistics.
2915 */
2916 info(1);
2917 }
2918 pcap_close(pd);
2919 pd = NULL;
2920 if (VFileName != NULL) {
2921 ret = get_next_file(VFile, VFileLine);
2922 if (ret) {
2923 int new_dlt;
2924
2925 RFileName = VFileLine;
2926 pd = pcap_open_offline(RFileName, ebuf);
2927 if (pd == NULL)
2928 error("%s", ebuf);
2929 #ifdef HAVE_CAPSICUM
2930 cap_rights_init(&rights, CAP_READ);
2931 if (cap_rights_limit(fileno(pcap_file(pd)),
2932 &rights) < 0 && errno != ENOSYS) {
2933 error("unable to limit pcap descriptor");
2934 }
2935 #endif
2936 new_dlt = pcap_datalink(pd);
2937 if (new_dlt != dlt) {
2938 /*
2939 * The new file has a different
2940 * link-layer header type from the
2941 * previous one.
2942 */
2943 if (WFileName != NULL) {
2944 /*
2945 * We're writing raw packets
2946 * that match the filter to
2947 * a pcap file. pcap files
2948 * don't support multiple
2949 * different link-layer
2950 * header types, so we fail
2951 * here.
2952 */
2953 error("%s: new dlt does not match original", RFileName);
2954 }
2955
2956 /*
2957 * We're printing the decoded packets;
2958 * switch to the new DLT.
2959 *
2960 * To do that, we need to change
2961 * the printer, change the DLT name,
2962 * and recompile the filter with
2963 * the new DLT.
2964 */
2965 dlt = new_dlt;
2966 ndo->ndo_if_printer = get_if_printer(dlt);
2967 /* Free the old filter */
2968 pcap_freecode(&fcode);
2969 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2970 error("%s", pcap_geterr(pd));
2971 }
2972
2973 /*
2974 * Set the filter on the new file.
2975 */
2976 if (pcap_setfilter(pd, &fcode) < 0)
2977 error("%s", pcap_geterr(pd));
2978
2979 /*
2980 * Report the new file.
2981 */
2982 dlt_name = pcap_datalink_val_to_name(dlt);
2983 fprintf(stderr, "reading from file %s", RFileName);
2984 if (dlt_name == NULL) {
2985 fprintf(stderr, ", link-type %u", dlt);
2986 } else {
2987 fprintf(stderr, ", link-type %s (%s)",
2988 dlt_name,
2989 pcap_datalink_val_to_description(dlt));
2990 }
2991 fprintf(stderr, ", snapshot length %d\n", pcap_snapshot(pd));
2992 }
2993 }
2994 }
2995 while (ret != NULL);
2996
2997 if (count_mode && RFileName != NULL)
2998 fprintf(stdout, "%u packet%s\n", packets_captured,
2999 PLURAL_SUFFIX(packets_captured));
3000
3001 free(cmdbuf);
3002 pcap_freecode(&fcode);
3003 exit_tcpdump(status == -1 ? S_ERR_HOST_PROGRAM : S_SUCCESS);
3004 }
3005
3006 /*
3007 * Catch a signal.
3008 */
3009 static void
setsignal(int sig,void (* func)(int))3010 (*setsignal (int sig, void (*func)(int)))(int)
3011 {
3012 #ifdef _WIN32
3013 return (signal(sig, func));
3014 #else
3015 struct sigaction old, new;
3016
3017 memset(&new, 0, sizeof(new));
3018 new.sa_handler = func;
3019 if ((sig == SIGCHLD)
3020 # ifdef SIGNAL_REQ_INFO
3021 || (sig == SIGNAL_REQ_INFO)
3022 # endif
3023 # ifdef SIGNAL_FLUSH_PCAP
3024 || (sig == SIGNAL_FLUSH_PCAP)
3025 # endif
3026 )
3027 new.sa_flags = SA_RESTART;
3028 if (sigaction(sig, &new, &old) < 0)
3029 /* The same workaround as for SIG_DFL above. */
3030 #ifdef __illumos__
3031 DIAG_OFF_STRICT_PROTOTYPES
3032 #endif /* __illumos__ */
3033 return (SIG_ERR);
3034 #ifdef __illumos__
3035 DIAG_ON_STRICT_PROTOTYPES
3036 #endif /* __illumos__ */
3037 return (old.sa_handler);
3038 #endif
3039 }
3040
3041 /* make a clean exit on interrupts */
3042 static void
cleanup(int signo _U_)3043 cleanup(int signo _U_)
3044 {
3045 #ifdef _WIN32
3046 if (timer_handle != INVALID_HANDLE_VALUE) {
3047 DeleteTimerQueueTimer(NULL, timer_handle, NULL);
3048 CloseHandle(timer_handle);
3049 timer_handle = INVALID_HANDLE_VALUE;
3050 }
3051 #else /* _WIN32 */
3052 struct itimerval timer;
3053
3054 timer.it_interval.tv_sec = 0;
3055 timer.it_interval.tv_usec = 0;
3056 timer.it_value.tv_sec = 0;
3057 timer.it_value.tv_usec = 0;
3058 setitimer(ITIMER_REAL, &timer, NULL);
3059 #endif /* _WIN32 */
3060
3061 #ifdef HAVE_PCAP_BREAKLOOP
3062 /*
3063 * We have "pcap_breakloop()"; use it, so that we do as little
3064 * as possible in the signal handler (it's probably not safe
3065 * to do anything with standard I/O streams in a signal handler -
3066 * the ANSI C standard doesn't say it is).
3067 */
3068 if (pd)
3069 pcap_breakloop(pd);
3070 #else
3071 /*
3072 * We don't have "pcap_breakloop()"; this isn't safe, but
3073 * it's the best we can do. Print the summary if we're
3074 * not reading from a savefile - i.e., if we're doing a
3075 * live capture - and exit.
3076 */
3077 if (pd != NULL && pcap_file(pd) == NULL) {
3078 /*
3079 * We got interrupted, so perhaps we didn't
3080 * manage to finish a line we were printing.
3081 * Print an extra newline, just in case.
3082 */
3083 putchar('\n');
3084 (void)fflush(stdout);
3085 info(1);
3086 }
3087 exit_tcpdump(S_SUCCESS);
3088 #endif
3089 }
3090
3091 /*
3092 On windows, we do not use a fork, so we do not care less about
3093 waiting a child processes to die
3094 */
3095 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3096 static void
child_cleanup(int signo _U_)3097 child_cleanup(int signo _U_)
3098 {
3099 while (waitpid(-1, NULL, WNOHANG) >= 0);
3100 }
3101 #endif /* HAVE_FORK && HAVE_VFORK */
3102
3103 static void
info(int verbose)3104 info(int verbose)
3105 {
3106 struct pcap_stat stats;
3107
3108 /*
3109 * Older versions of libpcap didn't set ps_ifdrop on some
3110 * platforms; initialize it to 0 to handle that.
3111 */
3112 stats.ps_ifdrop = 0;
3113 if (pcap_stats(pd, &stats) < 0) {
3114 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
3115 infoprint = 0;
3116 return;
3117 }
3118
3119 if (!verbose)
3120 fprintf(stderr, "%s: ", program_name);
3121
3122 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
3123 PLURAL_SUFFIX(packets_captured));
3124 if (!verbose)
3125 fputs(", ", stderr);
3126 else
3127 putc('\n', stderr);
3128 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
3129 PLURAL_SUFFIX(stats.ps_recv));
3130 if (!verbose)
3131 fputs(", ", stderr);
3132 else
3133 putc('\n', stderr);
3134 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
3135 PLURAL_SUFFIX(stats.ps_drop));
3136 if (stats.ps_ifdrop != 0) {
3137 if (!verbose)
3138 fputs(", ", stderr);
3139 else
3140 putc('\n', stderr);
3141 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
3142 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
3143 } else
3144 putc('\n', stderr);
3145 infoprint = 0;
3146 }
3147
3148 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3149 #ifdef HAVE_FORK
3150 #define fork_subprocess() fork()
3151 #else
3152 #define fork_subprocess() vfork()
3153 #endif
3154 static void
compress_savefile(const char * filename)3155 compress_savefile(const char *filename)
3156 {
3157 pid_t child;
3158
3159 child = fork_subprocess();
3160 if (child == -1) {
3161 fprintf(stderr,
3162 "%s: fork failed: %s\n",
3163 __func__, pcap_strerror(errno));
3164 return;
3165 }
3166 if (child != 0) {
3167 /* Parent process. */
3168 return;
3169 }
3170
3171 /*
3172 * Child process.
3173 * Set to lowest priority so that this doesn't disturb the capture.
3174 */
3175 #ifdef NZERO
3176 setpriority(PRIO_PROCESS, 0, NZERO - 1);
3177 #else
3178 setpriority(PRIO_PROCESS, 0, 19);
3179 #endif
3180 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
3181 fprintf(stderr,
3182 "%s: execlp(%s, %s) failed: %s\n",
3183 __func__, zflag, filename, pcap_strerror(errno));
3184 #ifdef HAVE_FORK
3185 exit(S_ERR_HOST_PROGRAM);
3186 #else
3187 _exit(S_ERR_HOST_PROGRAM);
3188 #endif
3189 }
3190 #endif /* HAVE_FORK || HAVE_VFORK */
3191
3192 static void
dump_packet_and_trunc(u_char * user,const struct pcap_pkthdr * h,const u_char * sp)3193 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
3194 {
3195 struct dump_info *dump_info;
3196
3197 ++packets_captured;
3198
3199 ++infodelay;
3200
3201 dump_info = (struct dump_info *)user;
3202
3203 /*
3204 * XXX - this won't force the file to rotate on the specified time
3205 * boundary, but it will rotate on the first packet received after the
3206 * specified Gflag number of seconds. Note: if a Gflag time boundary
3207 * and a Cflag size boundary coincide, the time rotation will occur
3208 * first thereby cancelling the Cflag boundary (since the file should
3209 * be 0).
3210 */
3211 if (Gflag != 0) {
3212 /* Check if it is time to rotate */
3213 time_t t;
3214
3215 /* Get the current time */
3216 if ((t = time(NULL)) == (time_t)-1) {
3217 error("%s: can't get current_time: %s",
3218 __func__, pcap_strerror(errno));
3219 }
3220
3221
3222 /* If the time is greater than the specified window, rotate */
3223 if (t - Gflag_time >= Gflag) {
3224 #ifdef HAVE_CAPSICUM
3225 FILE *fp;
3226 int fd;
3227 #endif
3228
3229 /* Update the Gflag_time */
3230 Gflag_time = t;
3231 /* Update Gflag_count */
3232 Gflag_count++;
3233 /*
3234 * Close the current file and open a new one.
3235 */
3236 pcap_dump_close(dump_info->pdd);
3237
3238 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3239 /*
3240 * Compress the file we just closed, if the user asked for it
3241 */
3242 if (zflag != NULL)
3243 compress_savefile(dump_info->CurrentFileName);
3244 #endif
3245
3246 /*
3247 * Check to see if we've exceeded the Wflag (when
3248 * not using Cflag).
3249 */
3250 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
3251 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
3252 Wflag);
3253 info(1);
3254 exit_tcpdump(S_SUCCESS);
3255 /* NOTREACHED */
3256 }
3257 if (dump_info->CurrentFileName != NULL)
3258 free(dump_info->CurrentFileName);
3259 /* Allocate space for max filename + \0. */
3260 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
3261 if (dump_info->CurrentFileName == NULL)
3262 error("dump_packet_and_trunc: malloc");
3263 /*
3264 * Gflag was set otherwise we wouldn't be here. Reset the count
3265 * so multiple files would end with 1,2,3 in the filename.
3266 * The counting is handled with the -C flow after this.
3267 */
3268 Cflag_count = 0;
3269
3270 /*
3271 * This is always the first file in the Cflag
3272 * rotation: e.g. 0
3273 * We also don't need numbering if Cflag is not set.
3274 */
3275 if (Cflag != 0)
3276 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
3277 WflagChars);
3278 else
3279 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
3280
3281 #ifdef HAVE_LIBCAP_NG
3282 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
3283 capng_apply(CAPNG_SELECT_BOTH);
3284 #endif /* HAVE_LIBCAP_NG */
3285 #ifdef HAVE_CAPSICUM
3286 fd = openat(dump_info->dirfd,
3287 dump_info->CurrentFileName,
3288 O_CREAT | O_WRONLY | O_TRUNC, 0644);
3289 if (fd < 0) {
3290 error("unable to open file %s",
3291 dump_info->CurrentFileName);
3292 }
3293 fp = fdopen(fd, "w");
3294 if (fp == NULL) {
3295 error("unable to fdopen file %s",
3296 dump_info->CurrentFileName);
3297 }
3298 dump_info->pdd = pcap_dump_fopen(dump_info->pd, fp);
3299 #else /* !HAVE_CAPSICUM */
3300 dump_info->pdd = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
3301 #endif
3302 #ifdef HAVE_LIBCAP_NG
3303 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
3304 capng_apply(CAPNG_SELECT_BOTH);
3305 #endif /* HAVE_LIBCAP_NG */
3306 if (dump_info->pdd == NULL)
3307 error("%s", pcap_geterr(pd));
3308 #ifdef HAVE_CAPSICUM
3309 set_dumper_capsicum_rights(dump_info->pdd);
3310 #endif
3311 }
3312 }
3313
3314 /*
3315 * XXX - this won't prevent capture files from getting
3316 * larger than Cflag - the last packet written to the
3317 * file could put it over Cflag.
3318 */
3319 if (Cflag != 0) {
3320 #ifdef HAVE_PCAP_DUMP_FTELL64
3321 int64_t size = pcap_dump_ftell64(dump_info->pdd);
3322 #else
3323 /*
3324 * XXX - this only handles a Cflag value > 2^31-1 on
3325 * LP64 platforms; to handle ILP32 (32-bit UN*X and
3326 * Windows) or LLP64 (64-bit Windows) would require
3327 * a version of libpcap with pcap_dump_ftell64().
3328 */
3329 long size = pcap_dump_ftell(dump_info->pdd);
3330 #endif
3331
3332 if (size == -1)
3333 error("ftell fails on output file");
3334 if (size > Cflag) {
3335 #ifdef HAVE_CAPSICUM
3336 FILE *fp;
3337 int fd;
3338 #endif
3339
3340 /*
3341 * Close the current file and open a new one.
3342 */
3343 pcap_dump_close(dump_info->pdd);
3344
3345 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3346 /*
3347 * Compress the file we just closed, if the user
3348 * asked for it.
3349 */
3350 if (zflag != NULL)
3351 compress_savefile(dump_info->CurrentFileName);
3352 #endif
3353
3354 Cflag_count++;
3355 if (Wflag > 0) {
3356 if (Cflag_count >= Wflag)
3357 Cflag_count = 0;
3358 }
3359 if (dump_info->CurrentFileName != NULL)
3360 free(dump_info->CurrentFileName);
3361 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
3362 if (dump_info->CurrentFileName == NULL)
3363 error("%s: malloc", __func__);
3364 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
3365 #ifdef HAVE_LIBCAP_NG
3366 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
3367 capng_apply(CAPNG_SELECT_BOTH);
3368 #endif /* HAVE_LIBCAP_NG */
3369 #ifdef HAVE_CAPSICUM
3370 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
3371 O_CREAT | O_WRONLY | O_TRUNC, 0644);
3372 if (fd < 0) {
3373 error("unable to open file %s",
3374 dump_info->CurrentFileName);
3375 }
3376 fp = fdopen(fd, "w");
3377 if (fp == NULL) {
3378 error("unable to fdopen file %s",
3379 dump_info->CurrentFileName);
3380 }
3381 dump_info->pdd = pcap_dump_fopen(dump_info->pd, fp);
3382 #else /* !HAVE_CAPSICUM */
3383 dump_info->pdd = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
3384 #endif
3385 #ifdef HAVE_LIBCAP_NG
3386 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
3387 capng_apply(CAPNG_SELECT_BOTH);
3388 #endif /* HAVE_LIBCAP_NG */
3389 if (dump_info->pdd == NULL)
3390 error("%s", pcap_geterr(pd));
3391 #ifdef HAVE_CAPSICUM
3392 set_dumper_capsicum_rights(dump_info->pdd);
3393 #endif
3394 }
3395 }
3396
3397 pcap_dump((u_char *)dump_info->pdd, h, sp);
3398 #ifdef HAVE_PCAP_DUMP_FLUSH
3399 if (Uflag)
3400 pcap_dump_flush(dump_info->pdd);
3401 #endif
3402
3403 if (dump_info->ndo != NULL)
3404 pretty_print_packet(dump_info->ndo, h, sp, packets_captured);
3405
3406 --infodelay;
3407 if (infoprint)
3408 info(0);
3409 }
3410
3411 static void
dump_packet(u_char * user,const struct pcap_pkthdr * h,const u_char * sp)3412 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
3413 {
3414 struct dump_info *dump_info;
3415
3416 ++packets_captured;
3417
3418 ++infodelay;
3419
3420 dump_info = (struct dump_info *)user;
3421
3422 pcap_dump((u_char *)dump_info->pdd, h, sp);
3423 #ifdef HAVE_PCAP_DUMP_FLUSH
3424 if (Uflag)
3425 pcap_dump_flush(dump_info->pdd);
3426 #endif
3427
3428 if (dump_info->ndo != NULL)
3429 pretty_print_packet(dump_info->ndo, h, sp, packets_captured);
3430
3431 --infodelay;
3432 if (infoprint)
3433 info(0);
3434 }
3435
3436 static void
print_packet(u_char * user,const struct pcap_pkthdr * h,const u_char * sp)3437 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
3438 {
3439 ++packets_captured;
3440
3441 ++infodelay;
3442
3443 if (!count_mode)
3444 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
3445
3446 --infodelay;
3447 if (infoprint)
3448 info(0);
3449 }
3450
3451 #ifdef SIGNAL_REQ_INFO
3452 static void
requestinfo(int signo _U_)3453 requestinfo(int signo _U_)
3454 {
3455 if (infodelay)
3456 ++infoprint;
3457 else
3458 info(0);
3459 }
3460 #endif
3461
3462 #ifdef SIGNAL_FLUSH_PCAP
3463 static void
flushpcap(int signo _U_)3464 flushpcap(int signo _U_)
3465 {
3466 if (pdd != NULL)
3467 pcap_dump_flush(pdd);
3468 }
3469 #endif
3470
3471 static void
print_packets_captured(void)3472 print_packets_captured (void)
3473 {
3474 static u_int prev_packets_captured, first = 1;
3475
3476 if (infodelay == 0 && (first || packets_captured != prev_packets_captured)) {
3477 fprintf(stderr, "Got %u\r", packets_captured);
3478 first = 0;
3479 prev_packets_captured = packets_captured;
3480 }
3481 }
3482
3483 /*
3484 * Called once each second in verbose mode while dumping to file
3485 */
3486 #ifdef _WIN32
verbose_stats_dump(PVOID param _U_,BOOLEAN timer_fired _U_)3487 static void CALLBACK verbose_stats_dump(PVOID param _U_,
3488 BOOLEAN timer_fired _U_)
3489 {
3490 print_packets_captured();
3491 }
3492 #else /* _WIN32 */
verbose_stats_dump(int sig _U_)3493 static void verbose_stats_dump(int sig _U_)
3494 {
3495 print_packets_captured();
3496 }
3497 #endif /* _WIN32 */
3498
3499 DIAG_OFF_DEPRECATION
3500 static void
print_version(FILE * f)3501 print_version(FILE *f)
3502 {
3503 #ifndef HAVE_PCAP_LIB_VERSION
3504 #ifdef HAVE_PCAP_VERSION
3505 extern char pcap_version[];
3506 #else /* HAVE_PCAP_VERSION */
3507 static char pcap_version[] = "unknown";
3508 #endif /* HAVE_PCAP_VERSION */
3509 #endif /* HAVE_PCAP_LIB_VERSION */
3510 const char *smi_version_string;
3511
3512 (void)fprintf(f, "%s version " PACKAGE_VERSION "\n", program_name);
3513 #ifdef HAVE_PCAP_LIB_VERSION
3514 (void)fprintf(f, "%s\n", pcap_lib_version());
3515 #else /* HAVE_PCAP_LIB_VERSION */
3516 (void)fprintf(f, "libpcap version %s\n", pcap_version);
3517 #endif /* HAVE_PCAP_LIB_VERSION */
3518
3519 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3520 (void)fprintf (f, "%s\n", SSLeay_version(SSLEAY_VERSION));
3521 #endif
3522
3523 smi_version_string = nd_smi_version_string();
3524 if (smi_version_string != NULL)
3525 (void)fprintf (f, "SMI-library: %s\n", smi_version_string);
3526
3527 #if defined(__SANITIZE_ADDRESS__)
3528 (void)fprintf (f, "Compiled with AddressSanitizer/GCC.\n");
3529 #elif defined(__has_feature)
3530 # if __has_feature(address_sanitizer)
3531 (void)fprintf (f, "Compiled with AddressSanitizer/Clang.\n");
3532 # elif __has_feature(memory_sanitizer)
3533 (void)fprintf (f, "Compiled with MemorySanitizer/Clang.\n");
3534 # endif
3535 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3536 (void)fprintf (f, "%zu-bit build, %zu-bit time_t\n",
3537 sizeof(void *) * 8, sizeof(time_t) * 8);
3538 }
3539 DIAG_ON_DEPRECATION
3540
3541 static void
print_usage(FILE * f)3542 print_usage(FILE *f)
3543 {
3544 print_version(f);
3545 (void)fprintf(f,
3546 "Usage: %s [-Abd" D_FLAG "efghH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ] [--count]\n", program_name);
3547 (void)fprintf(f,
3548 "\t\t[ -C file_size ] " E_FLAG_USAGE "[ -F file ] [ -G seconds ]\n");
3549 (void)fprintf(f,
3550 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE "\n");
3551 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3552 (void)fprintf(f,
3553 "\t\t" LIST_REMOTE_INTERFACES_USAGE "\n");
3554 #endif
3555 #ifdef USE_LIBSMI
3556 (void)fprintf(f,
3557 "\t\t" m_FLAG_USAGE "\n");
3558 #endif
3559 (void)fprintf(f,
3560 "\t\t" M_FLAG_USAGE "[ --number ] [ --print ]" Q_FLAG_USAGE "\n");
3561 (void)fprintf(f,
3562 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ --version ]\n");
3563 (void)fprintf(f,
3564 "\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n");
3565 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3566 (void)fprintf(f,
3567 "\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n");
3568 #endif
3569 (void)fprintf(f,
3570 "\t\t" z_FLAG_USAGE "[ -Z user ] [ expression ]\n");
3571 }
3572