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