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