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