xref: /openbsd-src/usr.sbin/tcpdump/tcpdump.c (revision aa997e528a848ca5596493c2a801bdd6fb26ae61)
1 /*	$OpenBSD: tcpdump.c,v 1.83 2018/02/06 03:07:51 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 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, "sack") == 0)
351 				/*
352 				 * kept for compatibility; DEFAULT_SNAPLEN
353 				 * used to be too short to capture SACK.
354 				 */
355 				;
356 			else
357 				error("unknown packet type `%s'", optarg);
358 			break;
359 
360 		case 'v':
361 			++vflag;
362 			break;
363 
364 		case 'w':
365 			WFileName = optarg;
366 			break;
367 #ifdef YYDEBUG
368 		case 'Y':
369 			{
370 			/* Undocumented flag */
371 			extern int yydebug;
372 			yydebug = 1;
373 			}
374 			break;
375 #endif
376 		case 'y':
377 			i = pcap_datalink_name_to_val(optarg);
378 			if (i < 0)
379 				error("invalid data link type: %s", optarg);
380 			dlt = (u_int)i;
381 			break;
382 
383 		case 'x':
384 			xflag = 1;
385 			break;
386 
387 		case 'X':
388 			Xflag = 1;
389 			xflag = 1;
390 			break;
391 
392 		case 'E':
393 			if (esp_init(optarg) < 0)
394 				error("bad esp specification `%s'", optarg);
395 			break;
396 
397 		default:
398 			usage();
399 			/* NOTREACHED */
400 		}
401 
402 	if (snaplen == 0) {
403 		switch (dlt) {
404 		case DLT_IEEE802_11:
405 			snaplen = IEEE802_11_SNAPLEN;
406 			break;
407 		case DLT_IEEE802_11_RADIO:
408 			snaplen = IEEE802_11_RADIO_SNAPLEN;
409 			break;
410 		default:
411 			snaplen = DEFAULT_SNAPLEN;
412 			break;
413 		}
414 	}
415 
416 	if (aflag && nflag)
417 		error("-a and -n options are incompatible");
418 
419 	if (RFileName != NULL) {
420 		pd = priv_pcap_offline(RFileName, ebuf);
421 		if (pd == NULL)
422 			error("%s", ebuf);
423 		/* state: STATE_BPF */
424 		localnet = 0;
425 		netmask = 0;
426 		if (fflag != 0)
427 			error("-f and -r options are incompatible");
428 	} else {
429 		if (device == NULL) {
430 			device = pcap_lookupdev(ebuf);
431 			if (device == NULL)
432 				error("%s", ebuf);
433 		}
434 		pd = priv_pcap_live(device, snaplen, !pflag, 1000, ebuf,
435 		    dlt, dirfilt);
436 		if (pd == NULL)
437 			error("%s", ebuf);
438 
439 		/* state: STATE_BPF */
440 		if (pcap_lookupnet(device, &localnet, &netmask, ebuf)) {
441 			if (fflag)
442 				warning("%s", ebuf);
443 			localnet = 0;
444 			netmask = 0;
445 		}
446 	}
447 	i = pcap_snapshot(pd);
448 	if (snaplen < i) {
449 		warning("snaplen raised from %d to %d", snaplen, i);
450 		snaplen = i;
451 	}
452 
453 	if (Lflag) {
454 		pcap_list_linktypes(pd);
455 		exit(0);
456 	}
457 
458 	fcode = priv_pcap_setfilter(pd, Oflag, netmask);
459 	/* state: STATE_FILTER */
460 	if (fcode == NULL)
461 		error("%s", pcap_geterr(pd));
462 	if (dflag) {
463 		bpf_dump(fcode, dflag);
464 		exit(0);
465 	}
466 	init_addrtoname(localnet, netmask);
467 
468 	if (WFileName) {
469 		pcap_dumper_t *p;
470 
471 		p = priv_pcap_dump_open(pd, WFileName);
472 		/* state: STATE_RUN */
473 		if (p == NULL)
474 			error("%s", pcap_geterr(pd));
475 		{
476 			FILE *fp = (FILE *)p;	/* XXX touching pcap guts! */
477 			fflush(fp);
478 			setvbuf(fp, NULL, _IONBF, 0);
479 		}
480 		printer = pcap_dump;
481 		pcap_userdata = (u_char *)p;
482 	} else {
483 		printer = lookup_printer(pcap_datalink(pd));
484 		pcap_userdata = NULL;
485 		priv_init_done();
486 		/* state: STATE_RUN */
487 	}
488 	if (RFileName == NULL) {
489 		(void)fprintf(stderr, "%s: listening on %s, link-type ",
490 		    program_name, device);
491 		pcap_print_linktype(pd->linktype);
492 		(void)fflush(stderr);
493 	}
494 
495 	if (oflag)
496 		oflag = init_pfosfp();
497 	if (tflag > 0)
498 		thiszone = gmt2local(0);
499 
500 	if (pledge("stdio", NULL) == -1)
501 		err(1, "pledge");
502 
503 	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
504 		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
505 		    program_name, pcap_geterr(pd));
506 		exit(1);
507 	}
508 	pcap_close(pd);
509 	exit(0);
510 }
511 
512 /* make a clean exit on interrupts */
513 void
514 cleanup(int signo)
515 {
516 	struct pcap_stat stat;
517 	sigset_t allsigs;
518 
519 	sigfillset(&allsigs);
520 	sigprocmask(SIG_BLOCK, &allsigs, NULL);
521 
522 	/* Can't print the summary if reading from a savefile */
523 	dprintf(STDERR_FILENO, "\n");
524 	if (pd != NULL && pcap_file(pd) == NULL) {
525 		if (priv_pcap_stats(&stat) < 0) {
526 			dprintf(STDERR_FILENO,
527 			    "pcap_stats: %s\n", pcap_geterr(pd));
528 		} else {
529 			dprintf(STDERR_FILENO,
530 			    "%u packets received by filter\n", stat.ps_recv);
531 			dprintf(STDERR_FILENO,
532 			    "%u packets dropped by kernel\n", stat.ps_drop);
533 		}
534 	}
535 	_exit(0);
536 }
537 
538 void
539 gotchld(int signo)
540 {
541 	pid_t pid;
542 	int status;
543 	int save_err = errno;
544 
545 	do {
546 		pid = waitpid(child_pid, &status, WNOHANG);
547 		if (pid > 0 && (WIFEXITED(status) || WIFSIGNALED(status)))
548 			cleanup(0);
549 	} while (pid == -1 && errno == EINTR);
550 
551 	if (pid == -1)
552 		_exit(1);
553 
554 	errno = save_err;
555 }
556 
557 /* dump the buffer in `emacs-hexl' style */
558 void
559 default_print_hexl(const u_char *cp, unsigned int length)
560 {
561 	unsigned int i, j, jm;
562 	int c;
563 	char ln[128], buf[128];
564 
565 	printf("\n");
566 	for (i = 0; i < length; i += 0x10) {
567 		snprintf(ln, sizeof(ln), "  %04x: ", (unsigned int)i);
568 		jm = length - i;
569 		jm = jm > 16 ? 16 : jm;
570 
571 		for (j = 0; j < jm; j++) {
572 			if ((j % 2) == 1)
573 				snprintf(buf, sizeof(buf), "%02x ",
574 				    (unsigned int)cp[i+j]);
575 			else
576 				snprintf(buf, sizeof(buf), "%02x",
577 				    (unsigned int)cp[i+j]);
578 			strlcat(ln, buf, sizeof ln);
579 		}
580 		for (; j < 16; j++) {
581 			if ((j % 2) == 1)
582 				snprintf(buf, sizeof buf, "   ");
583 			else
584 				snprintf(buf, sizeof buf, "  ");
585 			strlcat(ln, buf, sizeof ln);
586 		}
587 
588 		strlcat(ln, " ", sizeof ln);
589 		for (j = 0; j < jm; j++) {
590 			c = cp[i+j];
591 			c = isprint(c) ? c : '.';
592 			buf[0] = c;
593 			buf[1] = '\0';
594 			strlcat(ln, buf, sizeof ln);
595 		}
596 		printf("%s\n", ln);
597 	}
598 }
599 
600 /* dump the text from the buffer */
601 void
602 default_print_ascii(const u_char *cp, unsigned int length)
603 {
604 	int c, i;
605 
606 	printf("\n");
607 	for (i = 0; i < length; i++) {
608 		c = cp[i];
609 		if (isprint(c) || c == '\t' || c == '\n' || c == '\r')
610 			putchar(c);
611 		else
612 			putchar('.');
613 	}
614 }
615 
616 /* Like default_print() but data need not be aligned */
617 void
618 default_print_unaligned(const u_char *cp, u_int length)
619 {
620 	u_int i, s;
621 	int nshorts;
622 
623 	if (Xflag) {
624 		/* dump the buffer in `emacs-hexl' style */
625 		default_print_hexl(cp, length);
626 	} else if (Aflag) {
627 		/* dump the text in the buffer */
628 		default_print_ascii(cp, length);
629 	} else {
630 		/* dump the buffer in old tcpdump style */
631 		nshorts = (u_int) length / sizeof(u_short);
632 		i = 0;
633 		while (--nshorts >= 0) {
634 			if ((i++ % 8) == 0)
635 				(void)printf("\n\t\t\t");
636 			s = *cp++;
637 			(void)printf(" %02x%02x", s, *cp++);
638 		}
639 		if (length & 1) {
640 			if ((i % 8) == 0)
641 				(void)printf("\n\t\t\t");
642 			(void)printf(" %02x", *cp);
643 		}
644 	}
645 }
646 
647 void
648 default_print(const u_char *bp, u_int length)
649 {
650 	const u_short *sp;
651 	u_int i;
652 	int nshorts;
653 
654 	if (Xflag) {
655 		/* dump the buffer in `emacs-hexl' style */
656 		default_print_hexl(bp, length);
657 	} else if (Aflag) {
658 		/* dump the text in the buffer */
659 		default_print_ascii(bp, length);
660 	} else {
661 		/* dump the buffer in old tcpdump style */
662 		if ((long)bp & 1) {
663 			default_print_unaligned(bp, length);
664 			return;
665 		}
666 		sp = (u_short *)bp;
667 		nshorts = (u_int) length / sizeof(u_short);
668 		i = 0;
669 		while (--nshorts >= 0) {
670 			if ((i++ % 8) == 0)
671 				(void)printf("\n\t\t\t");
672 			(void)printf(" %04x", ntohs(*sp++));
673 		}
674 		if (length & 1) {
675 			if ((i % 8) == 0)
676 				(void)printf("\n\t\t\t");
677 			(void)printf(" %02x", *(u_char *)sp);
678 		}
679 	}
680 }
681 
682 void
683 set_slave_signals(void)
684 {
685 	setsignal(SIGTERM, cleanup);
686 	setsignal(SIGINT, cleanup);
687 	setsignal(SIGCHLD, gotchld);
688 	setsignal(SIGHUP, cleanup);
689 }
690 
691 __dead void
692 usage(void)
693 {
694 	(void)fprintf(stderr,
695 "Usage: %s [-AadefILlNnOopqStvXx] [-c count] [-D direction]\n",
696 	    program_name);
697 	(void)fprintf(stderr,
698 "\t       [-E [espalg:]espkey] [-F file] [-i interface] [-r file]\n");
699 	(void)fprintf(stderr,
700 "\t       [-s snaplen] [-T type] [-w file] [-y datalinktype] [expression]\n");
701 	exit(1);
702 }
703