xref: /openbsd-src/usr.sbin/tcpdump/tcpdump.c (revision c020cf82e0cc147236f01a8dca7052034cf9d30d)
1 /*	$OpenBSD: tcpdump.c,v 1.93 2020/06/21 05:00:18 dlg Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that: (1) source code distributions
9  * retain the above copyright notice and this paragraph in its entirety, (2)
10  * distributions including binary code include the above copyright notice and
11  * this paragraph in its entirety in the documentation or other materials
12  * provided with the distribution, and (3) all advertising materials mentioning
13  * features or use of this software display the following acknowledgement:
14  * ``This product includes software developed by the University of California,
15  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16  * the University nor the names of its contributors may be used to endorse
17  * or promote products derived from this software without specific prior
18  * written permission.
19  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
22  */
23 
24 /*
25  * tcpdump - monitor tcp/ip traffic on an ethernet.
26  *
27  * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
28  * Mercilessly hacked and occasionally improved since then via the
29  * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
30  */
31 
32 #include <sys/types.h>
33 #include <sys/time.h>
34 #include <sys/ioctl.h>
35 #include <sys/wait.h>
36 
37 #include <netinet/in.h>
38 
39 #include <pcap.h>
40 #include <signal.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <limits.h>
46 #include <ctype.h>
47 #include <err.h>
48 #include <errno.h>
49 
50 #include "interface.h"
51 #include "addrtoname.h"
52 #include "setsignal.h"
53 #include "gmt2local.h"
54 
55 #include <sys/socket.h>
56 #include <net/if.h>
57 #include <net/pfvar.h>
58 #include "pfctl.h"
59 #include "pfctl_parser.h"
60 #include "privsep.h"
61 
62 int Aflag;			/* dump ascii */
63 int aflag;			/* translate network and broadcast addresses */
64 int Bflag;			/* BPF fildrop setting */
65 int dflag;			/* print filter code */
66 int eflag;			/* print ethernet header */
67 int fflag;			/* don't translate "foreign" IP address */
68 int Iflag;			/* include interface in output */
69 int Lflag;			/* List available link types */
70 int nflag;			/* leave addresses as numbers */
71 int Nflag;			/* remove domains from printed host names */
72 int Oflag = 1;			/* run filter code optimizer */
73 int oflag;			/* print passive OS fingerprints */
74 int pflag;			/* don't go promiscuous */
75 int qflag;			/* quick (shorter) output */
76 int Sflag;			/* print raw TCP sequence numbers */
77 int tflag = 1;			/* print packet arrival time */
78 int vflag;			/* verbose */
79 int xflag;			/* print packet in hex */
80 int Xflag;			/* print packet in emacs-hexl style */
81 
82 int packettype;
83 
84 char *program_name;
85 char *device = NULL;
86 
87 int32_t thiszone;		/* seconds offset from gmt to local time */
88 
89 extern volatile pid_t child_pid;
90 
91 /* Externs */
92 extern void bpf_dump(struct bpf_program *, int);
93 extern int esp_init(char *);
94 
95 /* Forwards */
96 void	cleanup(int);
97 void	gotchld(int);
98 extern __dead void usage(void);
99 
100 /* Length of saved portion of packet. */
101 int snaplen = 0;
102 
103 struct printer {
104 	pcap_handler f;
105 	int type;
106 };
107 
108 /* XXX needed if using old bpf.h */
109 #ifndef DLT_ATM_RFC1483
110 #define DLT_ATM_RFC1483 11
111 #endif
112 
113 static struct printer printers[] = {
114 	{ ether_if_print,		DLT_EN10MB },
115 	{ ether_if_print,		DLT_IEEE802 },
116 	{ sl_if_print,			DLT_SLIP },
117 	{ sl_bsdos_if_print,		DLT_SLIP_BSDOS },
118 	{ ppp_if_print,			DLT_PPP },
119 	{ ppp_hdlc_if_print,		DLT_PPP_SERIAL },
120 	{ fddi_if_print,		DLT_FDDI },
121 	{ null_if_print,		DLT_NULL },
122 	{ raw_if_print,			DLT_RAW },
123 	{ atm_if_print,			DLT_ATM_RFC1483 },
124 	{ loop_if_print,		DLT_LOOP },
125 	{ enc_if_print,			DLT_ENC },
126 	{ pflog_if_print,		DLT_PFLOG },
127 	{ pfsync_if_print,		DLT_PFSYNC },
128 	{ ppp_ether_if_print,		DLT_PPP_ETHER },
129 	{ ieee802_11_if_print,		DLT_IEEE802_11 },
130 	{ ieee802_11_radio_if_print,	DLT_IEEE802_11_RADIO },
131 	{ ofp_if_print,			DLT_OPENFLOW },
132 	{ usbpcap_if_print,		DLT_USBPCAP },
133 	{ NULL,				0 },
134 };
135 
136 static pcap_handler
137 lookup_printer(int type)
138 {
139 	struct printer *p;
140 
141 	for (p = printers; p->f; ++p) {
142 		if (type == p->type)
143 			return p->f;
144 	}
145 
146 	error("unknown data link type 0x%x", type);
147 	/* NOTREACHED */
148 }
149 
150 static int
151 init_pfosfp(void)
152 {
153 	pf_osfp_initialize();
154 	if (pfctl_file_fingerprints(-1,
155 	    PF_OPT_QUIET|PF_OPT_NOACTION, PF_OSFP_FILE) == 0)
156 		return 1;
157 	return 0;
158 }
159 
160 static pcap_t *pd;
161 
162 /* Multiple DLT support */
163 void		 pcap_list_linktypes(pcap_t *);
164 void		 pcap_print_linktype(u_int);
165 
166 void
167 pcap_print_linktype(u_int dlt)
168 {
169 	const char *name;
170 
171 	if ((name = pcap_datalink_val_to_name(dlt)) != NULL)
172 		fprintf(stderr, "%s\n", name);
173 	else
174 		fprintf(stderr, "<unknown: %u>\n", dlt);
175 }
176 
177 void
178 pcap_list_linktypes(pcap_t *p)
179 {
180 	int fd = p->fd;
181 	u_int n;
182 
183 #define MAXDLT	100
184 
185 	u_int dltlist[MAXDLT];
186 	struct bpf_dltlist dl = {MAXDLT, dltlist};
187 
188 	if (fd < 0)
189 		error("Invalid bpf descriptor");
190 
191 	if (ioctl(fd, BIOCGDLTLIST, &dl) == -1)
192 		err(1, "BIOCGDLTLIST");
193 
194 	if (dl.bfl_len > MAXDLT)
195 		error("Invalid number of linktypes: %u", dl.bfl_len);
196 
197 	fprintf(stderr, "%d link type%s supported:\n", dl.bfl_len,
198 	    dl.bfl_len == 1 ? "" : "s");
199 
200 	for (n = 0; n < dl.bfl_len; n++) {
201 		fprintf(stderr, "\t");
202 		pcap_print_linktype(dltlist[n]);
203 	}
204 }
205 
206 int
207 main(int argc, char **argv)
208 {
209 	int cnt = -1, op, i;
210 	bpf_u_int32 localnet, netmask;
211 	char *cp, *infile = NULL, *RFileName = NULL;
212 	char ebuf[PCAP_ERRBUF_SIZE], *WFileName = NULL;
213 	pcap_handler printer;
214 	struct bpf_program *fcode;
215 	u_char *pcap_userdata;
216 	u_int dirfilt = 0, dlt = (u_int) -1;
217 	const char *errstr;
218 
219 	if ((cp = strrchr(argv[0], '/')) != NULL)
220 		program_name = cp + 1;
221 	else
222 		program_name = argv[0];
223 
224 	/* '-P' used internally, exec privileged portion */
225 	if (argc >= 2 && strcmp("-P", argv[1]) == 0)
226 		priv_exec(argc, argv);
227 
228 	if (priv_init(argc, argv))
229 		error("Failed to setup privsep");
230 
231 	/* state: STATE_INIT */
232 
233 	opterr = 0;
234 	while ((op = getopt(argc, argv,
235 	    "AaB:c:D:deE:fF:i:IlLnNOopqr:s:StT:vw:xXy:Y")) != -1)
236 		switch (op) {
237 
238 		case 'A':
239 			xflag = 1;
240 			Aflag = 1;
241 			break;
242 
243 		case 'a':
244 			aflag = 1;
245 			break;
246 
247 		case 'B':
248 			if (strcasecmp(optarg, "pass") == 0)
249 				Bflag = BPF_FILDROP_PASS;
250 			else if (strcasecmp(optarg, "capture") == 0)
251 				Bflag = BPF_FILDROP_CAPTURE;
252 			else if (strcasecmp(optarg, "drop") == 0)
253 				Bflag = BPF_FILDROP_DROP;
254 			else {
255 				error("invalid BPF fildrop option: %s",
256 				    optarg);
257 			}
258 			break;
259 
260 		case 'c':
261 			cnt = strtonum(optarg, 1, INT_MAX, &errstr);
262 			if (errstr)
263 				error("invalid packet count %s: %s",
264 				    optarg, errstr);
265 			break;
266 
267 		case 'D':
268 			if (strcasecmp(optarg, "in") == 0)
269 				dirfilt = BPF_DIRECTION_OUT;
270 			else if (strcasecmp(optarg, "out") == 0)
271 				dirfilt = BPF_DIRECTION_IN;
272 			else
273 				error("invalid traffic direction %s", optarg);
274 			break;
275 
276 		case 'd':
277 			++dflag;
278 			break;
279 		case 'e':
280 			eflag = 1;
281 			break;
282 
283 		case 'f':
284 			fflag = 1;
285 			break;
286 
287 		case 'F':
288 			infile = optarg;
289 			break;
290 
291 		case 'i':
292 			device = optarg;
293 			break;
294 
295 		case 'I':
296 			Iflag = 1;
297 			break;
298 
299 		case 'l':
300 			setvbuf(stdout, NULL, _IOLBF, 0);
301 			break;
302 		case 'L':
303 			Lflag = 1;
304 			break;
305 		case 'n':
306 			nflag = 1;
307 			break;
308 
309 		case 'N':
310 			Nflag = 1;
311 			break;
312 
313 		case 'O':
314 			Oflag = 0;
315 			break;
316 
317 		case 'o':
318 			oflag = 1;
319 			break;
320 
321 		case 'p':
322 			pflag = 1;
323 			break;
324 
325 		case 'q':
326 			qflag = 1;
327 			break;
328 
329 		case 'r':
330 			RFileName = optarg;
331 			break;
332 
333 		case 's':
334 			snaplen = strtonum(optarg, 1, INT_MAX, &errstr);
335 			if (errstr)
336 				error("invalid snaplen %s: %s", optarg, errstr);
337 			break;
338 
339 		case 'S':
340 			Sflag = 1;
341 			break;
342 
343 		case 't':
344 			--tflag;
345 			break;
346 
347 		case 'T':
348 			if (strcasecmp(optarg, "vat") == 0)
349 				packettype = PT_VAT;
350 			else if (strcasecmp(optarg, "wb") == 0)
351 				packettype = PT_WB;
352 			else if (strcasecmp(optarg, "rpc") == 0)
353 				packettype = PT_RPC;
354 			else if (strcasecmp(optarg, "rtp") == 0)
355 				packettype = PT_RTP;
356 			else if (strcasecmp(optarg, "rtcp") == 0)
357 				packettype = PT_RTCP;
358 			else if (strcasecmp(optarg, "cnfp") == 0)
359 				packettype = PT_CNFP;
360 			else if (strcasecmp(optarg, "vrrp") == 0)
361 				packettype = PT_VRRP;
362 			else if (strcasecmp(optarg, "tcp") == 0)
363 				packettype = PT_TCP;
364 			else if (strcasecmp(optarg, "gre") == 0)
365 				packettype = PT_GRE;
366 			else if (strcasecmp(optarg, "vxlan") == 0)
367 				packettype = PT_VXLAN;
368 			else if (strcasecmp(optarg, "erspan") == 0)
369 				packettype = PT_ERSPAN;
370 			else if (strcasecmp(optarg, "mpls") == 0)
371 				packettype = PT_MPLS;
372 			else if (strcasecmp(optarg, "tftp") == 0)
373 				packettype = PT_TFTP;
374 			else if (strcasecmp(optarg, "wg") == 0)
375 				packettype = PT_WIREGUARD;
376 			else if (strcasecmp(optarg, "sack") == 0)
377 				/*
378 				 * kept for compatibility; DEFAULT_SNAPLEN
379 				 * used to be too short to capture SACK.
380 				 */
381 				;
382 			else
383 				error("unknown packet type `%s'", optarg);
384 			break;
385 
386 		case 'v':
387 			++vflag;
388 			break;
389 
390 		case 'w':
391 			WFileName = optarg;
392 			break;
393 #ifdef YYDEBUG
394 		case 'Y':
395 			{
396 			/* Undocumented flag */
397 			extern int yydebug;
398 			yydebug = 1;
399 			}
400 			break;
401 #endif
402 		case 'y':
403 			i = pcap_datalink_name_to_val(optarg);
404 			if (i < 0)
405 				error("invalid data link type: %s", optarg);
406 			dlt = (u_int)i;
407 			break;
408 
409 		case 'x':
410 			xflag = 1;
411 			break;
412 
413 		case 'X':
414 			Xflag = 1;
415 			xflag = 1;
416 			break;
417 
418 		case 'E':
419 			if (esp_init(optarg) < 0)
420 				error("bad esp specification `%s'", optarg);
421 			break;
422 
423 		default:
424 			usage();
425 			/* NOTREACHED */
426 		}
427 
428 	if (snaplen == 0) {
429 		switch (dlt) {
430 		case DLT_IEEE802_11:
431 			snaplen = IEEE802_11_SNAPLEN;
432 			break;
433 		case DLT_IEEE802_11_RADIO:
434 			snaplen = IEEE802_11_RADIO_SNAPLEN;
435 			break;
436 		default:
437 			snaplen = DEFAULT_SNAPLEN;
438 			break;
439 		}
440 	}
441 
442 	if (aflag && nflag)
443 		error("-a and -n options are incompatible");
444 
445 	if (RFileName != NULL) {
446 		pd = priv_pcap_offline(RFileName, ebuf);
447 		if (pd == NULL)
448 			error("%s", ebuf);
449 		/* state: STATE_BPF */
450 		localnet = 0;
451 		netmask = 0;
452 		if (fflag != 0)
453 			error("-f and -r options are incompatible");
454 	} else {
455 		if (device == NULL) {
456 			device = pcap_lookupdev(ebuf);
457 			if (device == NULL)
458 				error("%s", ebuf);
459 		}
460 		pd = priv_pcap_live(device, snaplen, !pflag, 1000, ebuf,
461 		    dlt, dirfilt, Bflag);
462 		if (pd == NULL)
463 			error("%s", ebuf);
464 
465 		/* state: STATE_BPF */
466 		if (pcap_lookupnet(device, &localnet, &netmask, ebuf)) {
467 			if (fflag)
468 				warning("%s", ebuf);
469 			localnet = 0;
470 			netmask = 0;
471 		}
472 	}
473 	i = pcap_snapshot(pd);
474 	if (snaplen < i) {
475 		warning("snaplen raised from %d to %d", snaplen, i);
476 		snaplen = i;
477 	}
478 
479 	if (Lflag) {
480 		pcap_list_linktypes(pd);
481 		exit(0);
482 	}
483 
484 	fcode = priv_pcap_setfilter(pd, Oflag, netmask);
485 	/* state: STATE_FILTER */
486 	if (fcode == NULL)
487 		error("%s", pcap_geterr(pd));
488 	if (dflag) {
489 		bpf_dump(fcode, dflag);
490 		exit(0);
491 	}
492 	if (oflag)
493 		oflag = init_pfosfp();
494 	init_addrtoname(localnet, netmask);
495 
496 	if (WFileName) {
497 		pcap_dumper_t *p;
498 
499 		p = priv_pcap_dump_open(pd, WFileName);
500 		/* state: STATE_RUN */
501 		if (p == NULL)
502 			error("%s", pcap_geterr(pd));
503 		{
504 			FILE *fp = (FILE *)p;	/* XXX touching pcap guts! */
505 			fflush(fp);
506 			setvbuf(fp, NULL, _IONBF, 0);
507 		}
508 		printer = pcap_dump;
509 		pcap_userdata = (u_char *)p;
510 	} else {
511 		printer = lookup_printer(pcap_datalink(pd));
512 		pcap_userdata = NULL;
513 		priv_init_done();
514 		/* state: STATE_RUN */
515 	}
516 	if (RFileName == NULL) {
517 		(void)fprintf(stderr, "%s: listening on %s, link-type ",
518 		    program_name, device);
519 		pcap_print_linktype(pd->linktype);
520 		(void)fflush(stderr);
521 	}
522 
523 	if (tflag > 0)
524 		thiszone = gmt2local(0);
525 
526 	if (pledge("stdio", NULL) == -1)
527 		err(1, "pledge");
528 
529 	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
530 		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
531 		    program_name, pcap_geterr(pd));
532 		exit(1);
533 	}
534 	pcap_close(pd);
535 	exit(0);
536 }
537 
538 /* make a clean exit on interrupts */
539 void
540 cleanup(int signo)
541 {
542 	struct pcap_stat stat;
543 	sigset_t allsigs;
544 
545 	sigfillset(&allsigs);
546 	sigprocmask(SIG_BLOCK, &allsigs, NULL);
547 
548 	/* Can't print the summary if reading from a savefile */
549 	dprintf(STDERR_FILENO, "\n");
550 	if (pd != NULL && pcap_file(pd) == NULL) {
551 		if (priv_pcap_stats(&stat) < 0) {
552 			dprintf(STDERR_FILENO,
553 			    "pcap_stats: %s\n", pcap_geterr(pd));
554 		} else {
555 			dprintf(STDERR_FILENO,
556 			    "%u packets received by filter\n", stat.ps_recv);
557 			dprintf(STDERR_FILENO,
558 			    "%u packets dropped by kernel\n", stat.ps_drop);
559 		}
560 	}
561 	_exit(0);
562 }
563 
564 void
565 gotchld(int signo)
566 {
567 	pid_t pid;
568 	int status;
569 	int save_err = errno;
570 
571 	do {
572 		pid = waitpid(child_pid, &status, WNOHANG);
573 		if (pid > 0 && (WIFEXITED(status) || WIFSIGNALED(status)))
574 			cleanup(0);
575 	} while (pid == -1 && errno == EINTR);
576 
577 	if (pid == -1)
578 		_exit(1);
579 
580 	errno = save_err;
581 }
582 
583 /* dump the buffer in `emacs-hexl' style */
584 void
585 default_print_hexl(const u_char *cp, unsigned int length)
586 {
587 	unsigned int i, j, jm;
588 	int c;
589 	char ln[128], buf[128];
590 
591 	printf("\n");
592 	for (i = 0; i < length; i += 0x10) {
593 		snprintf(ln, sizeof(ln), "  %04x: ", (unsigned int)i);
594 		jm = length - i;
595 		jm = jm > 16 ? 16 : jm;
596 
597 		for (j = 0; j < jm; j++) {
598 			if ((j % 2) == 1)
599 				snprintf(buf, sizeof(buf), "%02x ",
600 				    (unsigned int)cp[i+j]);
601 			else
602 				snprintf(buf, sizeof(buf), "%02x",
603 				    (unsigned int)cp[i+j]);
604 			strlcat(ln, buf, sizeof ln);
605 		}
606 		for (; j < 16; j++) {
607 			if ((j % 2) == 1)
608 				snprintf(buf, sizeof buf, "   ");
609 			else
610 				snprintf(buf, sizeof buf, "  ");
611 			strlcat(ln, buf, sizeof ln);
612 		}
613 
614 		strlcat(ln, " ", sizeof ln);
615 		for (j = 0; j < jm; j++) {
616 			c = cp[i+j];
617 			c = isprint(c) ? c : '.';
618 			buf[0] = c;
619 			buf[1] = '\0';
620 			strlcat(ln, buf, sizeof ln);
621 		}
622 		printf("%s\n", ln);
623 	}
624 }
625 
626 /* dump the text from the buffer */
627 void
628 default_print_ascii(const u_char *cp, unsigned int length)
629 {
630 	int c, i;
631 
632 	printf("\n");
633 	for (i = 0; i < length; i++) {
634 		c = cp[i];
635 		if (isprint(c) || c == '\t' || c == '\n' || c == '\r')
636 			putchar(c);
637 		else
638 			putchar('.');
639 	}
640 }
641 
642 /* Like default_print() but data need not be aligned */
643 void
644 default_print_unaligned(const u_char *cp, u_int length)
645 {
646 	u_int i, s;
647 	int nshorts;
648 
649 	if (Xflag) {
650 		/* dump the buffer in `emacs-hexl' style */
651 		default_print_hexl(cp, length);
652 	} else if (Aflag) {
653 		/* dump the text in the buffer */
654 		default_print_ascii(cp, length);
655 	} else {
656 		/* dump the buffer in old tcpdump style */
657 		nshorts = (u_int) length / sizeof(u_short);
658 		i = 0;
659 		while (--nshorts >= 0) {
660 			if ((i++ % 8) == 0)
661 				printf("\n\t\t\t");
662 			s = *cp++;
663 			printf(" %02x%02x", s, *cp++);
664 		}
665 		if (length & 1) {
666 			if ((i % 8) == 0)
667 				printf("\n\t\t\t");
668 			printf(" %02x", *cp);
669 		}
670 	}
671 }
672 
673 void
674 default_print(const u_char *bp, u_int length)
675 {
676 	const u_short *sp;
677 	u_int i;
678 	int nshorts;
679 
680 	if (Xflag) {
681 		/* dump the buffer in `emacs-hexl' style */
682 		default_print_hexl(bp, length);
683 	} else if (Aflag) {
684 		/* dump the text in the buffer */
685 		default_print_ascii(bp, length);
686 	} else {
687 		/* dump the buffer in old tcpdump style */
688 		if ((long)bp & 1) {
689 			default_print_unaligned(bp, length);
690 			return;
691 		}
692 		sp = (u_short *)bp;
693 		nshorts = (u_int) length / sizeof(u_short);
694 		i = 0;
695 		while (--nshorts >= 0) {
696 			if ((i++ % 8) == 0)
697 				printf("\n\t\t\t");
698 			printf(" %04x", ntohs(*sp++));
699 		}
700 		if (length & 1) {
701 			if ((i % 8) == 0)
702 				printf("\n\t\t\t");
703 			printf(" %02x", *(u_char *)sp);
704 		}
705 	}
706 }
707 
708 void
709 set_slave_signals(void)
710 {
711 	setsignal(SIGTERM, cleanup);
712 	setsignal(SIGINT, cleanup);
713 	setsignal(SIGCHLD, gotchld);
714 	setsignal(SIGHUP, cleanup);
715 }
716 
717 __dead void
718 usage(void)
719 {
720 	(void)fprintf(stderr,
721 "Usage: %s [-AadefILlNnOopqStvXx] [-B fildrop] [-c count] [-D direction]\n",
722 	    program_name);
723 	(void)fprintf(stderr,
724 "\t       [-E [espalg:]espkey] [-F file] [-i interface] [-r file]\n");
725 	(void)fprintf(stderr,
726 "\t       [-s snaplen] [-T type] [-w file] [-y datalinktype] [expression]\n");
727 	exit(1);
728 }
729