xref: /openbsd-src/usr.sbin/tcpdump/tcpdump.c (revision d874cce4b1d9fe6b41c9e4f2117a77d8a4a37b92)
1 /*	$OpenBSD: tcpdump.c,v 1.60 2008/04/18 21:35:11 djm 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.60 2008/04/18 21:35:11 djm 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 				snaplen = SACK_SNAPLEN;
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;
385 			break;
386 
387 		case 'X':
388 			++Xflag;
389 			if (xflag == 0) ++xflag;
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 = 0;
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 
501 	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
502 		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
503 		    program_name, pcap_geterr(pd));
504 		exit(1);
505 	}
506 	pcap_close(pd);
507 	exit(0);
508 }
509 
510 /* make a clean exit on interrupts */
511 /* ARGSUSED */
512 RETSIGTYPE
513 cleanup(int signo)
514 {
515 	struct pcap_stat stat;
516 	sigset_t allsigs;
517 	char buf[1024];
518 
519 	sigfillset(&allsigs);
520 	sigprocmask(SIG_BLOCK, &allsigs, NULL);
521 
522 	/* Can't print the summary if reading from a savefile */
523 	(void)write(STDERR_FILENO, "\n", 1);
524 	if (pd != NULL && pcap_file(pd) == NULL) {
525 		if (pcap_stats(pd, &stat) < 0) {
526 			(void)snprintf(buf, sizeof buf,
527 			    "pcap_stats: %s\n", pcap_geterr(pd));
528 			write(STDERR_FILENO, buf, strlen(buf));
529 		} else {
530 			(void)snprintf(buf, sizeof buf,
531 			    "%d packets received by filter\n", stat.ps_recv);
532 			write(STDERR_FILENO, buf, strlen(buf));
533 			(void)snprintf(buf, sizeof buf,
534 			    "%d packets dropped by kernel\n", stat.ps_drop);
535 			write(STDERR_FILENO, buf, strlen(buf));
536 		}
537 	}
538 	_exit(0);
539 }
540 
541 /* ARGSUSED */
542 RETSIGTYPE
543 gotchld(int signo)
544 {
545 	pid_t pid;
546 	int status;
547 	int save_err = errno;
548 
549 	do {
550 		pid = waitpid(child_pid, &status, WNOHANG);
551 		if (pid > 0 && (WIFEXITED(status) || WIFSIGNALED(status)))
552 			cleanup(0);
553 	} while (pid == -1 && errno == EINTR);
554 
555 	if (pid == -1)
556 		_exit(1);
557 
558 	errno = save_err;
559 }
560 
561 /* dump the buffer in `emacs-hexl' style */
562 void
563 default_print_hexl(const u_char *cp, unsigned int length, unsigned int offset)
564 {
565 	unsigned int i, j, jm;
566 	int c;
567 	char ln[128], buf[128];
568 
569 	printf("\n");
570 	for (i = 0; i < length; i += 0x10) {
571 		snprintf(ln, sizeof(ln), "  %04x: ",
572 		    (unsigned int)(i + offset));
573 		jm = length - i;
574 		jm = jm > 16 ? 16 : jm;
575 
576 		for (j = 0; j < jm; j++) {
577 			if ((j % 2) == 1)
578 				snprintf(buf, sizeof(buf), "%02x ",
579 				    (unsigned int)cp[i+j]);
580 			else
581 				snprintf(buf, sizeof(buf), "%02x",
582 				    (unsigned int)cp[i+j]);
583 			strlcat(ln, buf, sizeof ln);
584 		}
585 		for (; j < 16; j++) {
586 			if ((j % 2) == 1)
587 				snprintf(buf, sizeof buf, "   ");
588 			else
589 				snprintf(buf, sizeof buf, "  ");
590 			strlcat(ln, buf, sizeof ln);
591 		}
592 
593 		strlcat(ln, " ", sizeof ln);
594 		for (j = 0; j < jm; j++) {
595 			c = cp[i+j];
596 			c = isprint(c) ? c : '.';
597 			buf[0] = c;
598 			buf[1] = '\0';
599 			strlcat(ln, buf, sizeof ln);
600 		}
601 		printf("%s\n", ln);
602 	}
603 }
604 
605 /* Like default_print() but data need not be aligned */
606 void
607 default_print_unaligned(register const u_char *cp, register u_int length)
608 {
609 	register u_int i, s;
610 	register int nshorts;
611 
612 	if (Xflag) {
613 		/* dump the buffer in `emacs-hexl' style */
614 		default_print_hexl(cp, length, 0);
615 	} else {
616 		/* dump the buffer in old tcpdump style */
617 		nshorts = (u_int) length / sizeof(u_short);
618 		i = 0;
619 		while (--nshorts >= 0) {
620 			if ((i++ % 8) == 0)
621 				(void)printf("\n\t\t\t");
622 			s = *cp++;
623 			(void)printf(" %02x%02x", s, *cp++);
624 		}
625 		if (length & 1) {
626 			if ((i % 8) == 0)
627 				(void)printf("\n\t\t\t");
628 			(void)printf(" %02x", *cp);
629 		}
630 	}
631 }
632 
633 void
634 default_print(register const u_char *bp, register u_int length)
635 {
636 	register const u_short *sp;
637 	register u_int i;
638 	register int nshorts;
639 
640 	if (Xflag) {
641 		/* dump the buffer in `emacs-hexl' style */
642 		default_print_hexl(bp, length, 0);
643 	} else {
644 		/* dump the buffer in old tcpdump style */
645 		if ((long)bp & 1) {
646 			default_print_unaligned(bp, length);
647 			return;
648 		}
649 		sp = (u_short *)bp;
650 		nshorts = (u_int) length / sizeof(u_short);
651 		i = 0;
652 		while (--nshorts >= 0) {
653 			if ((i++ % 8) == 0)
654 				(void)printf("\n\t\t\t");
655 			(void)printf(" %04x", ntohs(*sp++));
656 		}
657 		if (length & 1) {
658 			if ((i % 8) == 0)
659 				(void)printf("\n\t\t\t");
660 			(void)printf(" %02x", *(u_char *)sp);
661 		}
662 	}
663 }
664 
665 void
666 set_slave_signals(void)
667 {
668 	RETSIGTYPE (*oldhandler)(int);
669 
670 	setsignal(SIGTERM, cleanup);
671 	setsignal(SIGINT, cleanup);
672 	setsignal(SIGCHLD, gotchld);
673 	/* Cooperate with nohup(1) XXX is this still necessary/working? */
674 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
675 		(void)setsignal(SIGHUP, oldhandler);
676 }
677 
678 __dead void
679 usage(void)
680 {
681 	(void)fprintf(stderr,
682 "Usage: %s [-adefILlNnOopqStvXx] [-c count] [-D direction]\n",
683 	    program_name);
684 	(void)fprintf(stderr,
685 "\t       [-E [espalg:]espkey] [-F file] [-i interface] [-r file]\n");
686 	(void)fprintf(stderr,
687 "\t       [-s snaplen] [-T type] [-w file] [-y datalinktype] [expression]\n");
688 	exit(1);
689 }
690