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