xref: /openbsd-src/usr.sbin/tcpdump/tcpdump.c (revision 91f110e064cd7c194e59e019b83bb7496c1c84d4)
1 /*	$OpenBSD: tcpdump.c,v 1.65 2012/07/11 10:37:38 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 /*
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 "machdep.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 RETSIGTYPE cleanup(int);
96 RETSIGTYPE 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 extern int optind;
203 extern int opterr;
204 extern char *optarg;
205 
206 int
207 main(int argc, char **argv)
208 {
209 	int cnt = -1, op, i;
210 	bpf_u_int32 localnet, netmask;
211 	char *cp, *infile = NULL, *RFileName = NULL;
212 	char ebuf[PCAP_ERRBUF_SIZE], *WFileName = NULL;
213 	pcap_handler printer;
214 	struct bpf_program *fcode;
215 	u_char *pcap_userdata;
216 	u_int dirfilt = 0, dlt = (u_int) -1;
217 
218 	if ((cp = strrchr(argv[0], '/')) != NULL)
219 		program_name = cp + 1;
220 	else
221 		program_name = argv[0];
222 
223 	if (priv_init(argc, argv))
224 		error("Failed to setup privsep");
225 
226 	/* state: STATE_INIT */
227 	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
228 		error("%s", ebuf);
229 
230 	opterr = 0;
231 	while ((op = getopt(argc, argv,
232 	    "Aac:D:deE:fF:i:IlLnNOopqr:s:StT:vw:xXy:Y")) != -1)
233 		switch (op) {
234 
235 		case 'A':
236 			if (xflag == 0) ++xflag;
237 			++Aflag;
238 			break;
239 
240 		case 'a':
241 			++aflag;
242 			break;
243 
244 		case 'c':
245 			cnt = atoi(optarg);
246 			if (cnt <= 0)
247 				error("invalid packet count %s", optarg);
248 			break;
249 
250 		case 'D':
251 			if (strcasecmp(optarg, "in") == 0)
252 				dirfilt = BPF_DIRECTION_OUT;
253 			else if (strcasecmp(optarg, "out") == 0)
254 				dirfilt = BPF_DIRECTION_IN;
255 			else
256 				error("invalid traffic direction %s", optarg);
257 			break;
258 
259 		case 'd':
260 			++dflag;
261 			break;
262 		case 'e':
263 			++eflag;
264 			break;
265 
266 		case 'f':
267 			++fflag;
268 			break;
269 
270 		case 'F':
271 			infile = optarg;
272 			break;
273 
274 		case 'i':
275 			device = optarg;
276 			break;
277 
278 		case 'I':
279 			++Iflag;
280 			break;
281 
282 		case 'l':
283 #ifdef HAVE_SETLINEBUF
284 			setlinebuf(stdout);
285 #else
286 			setvbuf(stdout, NULL, _IOLBF, 0);
287 #endif
288 			break;
289 		case 'L':
290 			++Lflag;
291 			break;
292 		case 'n':
293 			++nflag;
294 			break;
295 
296 		case 'N':
297 			++Nflag;
298 			break;
299 
300 		case 'O':
301 			Oflag = 0;
302 			break;
303 
304 		case 'o':
305 			oflag = 1;
306 			break;
307 
308 		case 'p':
309 			++pflag;
310 			break;
311 
312 		case 'q':
313 			++qflag;
314 			break;
315 
316 		case 'r':
317 			RFileName = optarg;
318 			break;
319 
320 		case 's':
321 			snaplen = atoi(optarg);
322 			if (snaplen <= 0)
323 				error("invalid snaplen %s", optarg);
324 			break;
325 
326 		case 'S':
327 			++Sflag;
328 			break;
329 
330 		case 't':
331 			--tflag;
332 			break;
333 
334 		case 'T':
335 			if (strcasecmp(optarg, "vat") == 0)
336 				packettype = PT_VAT;
337 			else if (strcasecmp(optarg, "wb") == 0)
338 				packettype = PT_WB;
339 			else if (strcasecmp(optarg, "rpc") == 0)
340 				packettype = PT_RPC;
341 			else if (strcasecmp(optarg, "rtp") == 0)
342 				packettype = PT_RTP;
343 			else if (strcasecmp(optarg, "rtcp") == 0)
344 				packettype = PT_RTCP;
345 			else if (strcasecmp(optarg, "cnfp") == 0)
346 				packettype = PT_CNFP;
347 			else if (strcasecmp(optarg, "vrrp") == 0)
348 				packettype = PT_VRRP;
349 			else if (strcasecmp(optarg, "tcp") == 0)
350 				packettype = PT_TCP;
351 			else if (strcasecmp(optarg, "sack") == 0)
352 				/*
353 				 * kept for compatibility; DEFAULT_SNAPLEN
354 				 * used to be too short to capture SACK.
355 				 */
356 				;
357 			else
358 				error("unknown packet type `%s'", optarg);
359 			break;
360 
361 		case 'v':
362 			++vflag;
363 			break;
364 
365 		case 'w':
366 			WFileName = optarg;
367 			break;
368 #ifdef YYDEBUG
369 		case 'Y':
370 			{
371 			/* Undocumented flag */
372 			extern int yydebug;
373 			yydebug = 1;
374 			}
375 			break;
376 #endif
377 		case 'y':
378 			i = pcap_datalink_name_to_val(optarg);
379 			if (i < 0)
380 				error("invalid data link type: %s", optarg);
381 			dlt = (u_int)i;
382 			break;
383 
384 		case 'x':
385 			++xflag;
386 			break;
387 
388 		case 'X':
389 			++Xflag;
390 			if (xflag == 0) ++xflag;
391 			break;
392 
393 		case 'E':
394 			if (esp_init(optarg) < 0)
395 				error("bad esp specification `%s'", optarg);
396 			break;
397 
398 		default:
399 			usage();
400 			/* NOTREACHED */
401 		}
402 
403 	if (snaplen == 0) {
404 		switch (dlt) {
405 		case DLT_IEEE802_11:
406 			snaplen = IEEE802_11_SNAPLEN;
407 			break;
408 		case DLT_IEEE802_11_RADIO:
409 			snaplen = IEEE802_11_RADIO_SNAPLEN;
410 			break;
411 		default:
412 			snaplen = DEFAULT_SNAPLEN;
413 			break;
414 		}
415 	}
416 
417 	if (aflag && nflag)
418 		error("-a and -n options are incompatible");
419 
420 	if (RFileName != NULL) {
421 		pd = priv_pcap_offline(RFileName, ebuf);
422 		if (pd == NULL)
423 			error("%s", ebuf);
424 		/* state: STATE_BPF */
425 		localnet = 0;
426 		netmask = 0;
427 		if (fflag != 0)
428 			error("-f and -r options are incompatible");
429 	} else {
430 		if (device == NULL) {
431 			device = pcap_lookupdev(ebuf);
432 			if (device == NULL)
433 				error("%s", ebuf);
434 		}
435 		pd = priv_pcap_live(device, snaplen, !pflag, 1000, ebuf,
436 		    dlt, dirfilt);
437 		if (pd == NULL)
438 			error("%s", ebuf);
439 
440 		/* state: STATE_BPF */
441 		if (pcap_lookupnet(device, &localnet, &netmask, ebuf)) {
442 			if (fflag)
443 				warning("%s", ebuf);
444 			localnet = 0;
445 			netmask = 0;
446 		}
447 	}
448 	i = pcap_snapshot(pd);
449 	if (snaplen < i) {
450 		warning("snaplen raised from %d to %d", snaplen, i);
451 		snaplen = i;
452 	}
453 
454 	if (Lflag) {
455 		pcap_list_linktypes(pd);
456 		exit(0);
457 	}
458 
459 	fcode = priv_pcap_setfilter(pd, Oflag, netmask);
460 	/* state: STATE_FILTER */
461 	if (fcode == NULL)
462 		error("%s", pcap_geterr(pd));
463 	if (dflag) {
464 		bpf_dump(fcode, dflag);
465 		exit(0);
466 	}
467 	init_addrtoname(localnet, netmask);
468 
469 	if (WFileName) {
470 		pcap_dumper_t *p;
471 
472 		p = priv_pcap_dump_open(pd, WFileName);
473 		/* state: STATE_RUN */
474 		if (p == NULL)
475 			error("%s", pcap_geterr(pd));
476 		{
477 			FILE *fp = (FILE *)p;	/* XXX touching pcap guts! */
478 			fflush(fp);
479 			setvbuf(fp, NULL, _IONBF, 0);
480 		}
481 		printer = pcap_dump;
482 		pcap_userdata = (u_char *)p;
483 	} else {
484 		printer = lookup_printer(pcap_datalink(pd));
485 		pcap_userdata = 0;
486 		priv_init_done();
487 		/* state: STATE_RUN */
488 	}
489 	if (RFileName == NULL) {
490 		(void)fprintf(stderr, "%s: listening on %s, link-type ",
491 		    program_name, device);
492 		pcap_print_linktype(pd->linktype);
493 		(void)fflush(stderr);
494 	}
495 
496 	if (oflag)
497 		oflag = init_pfosfp();
498 	if (tflag > 0)
499 		thiszone = gmt2local(0);
500 
501 
502 	if (pcap_loop(pd, cnt, printer, pcap_userdata) < 0) {
503 		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
504 		    program_name, pcap_geterr(pd));
505 		exit(1);
506 	}
507 	pcap_close(pd);
508 	exit(0);
509 }
510 
511 /* make a clean exit on interrupts */
512 /* ARGSUSED */
513 RETSIGTYPE
514 cleanup(int signo)
515 {
516 	struct pcap_stat stat;
517 	sigset_t allsigs;
518 	char buf[1024];
519 
520 	sigfillset(&allsigs);
521 	sigprocmask(SIG_BLOCK, &allsigs, NULL);
522 
523 	/* Can't print the summary if reading from a savefile */
524 	(void)write(STDERR_FILENO, "\n", 1);
525 	if (pd != NULL && pcap_file(pd) == NULL) {
526 		if (pcap_stats(pd, &stat) < 0) {
527 			(void)snprintf(buf, sizeof buf,
528 			    "pcap_stats: %s\n", pcap_geterr(pd));
529 			write(STDERR_FILENO, buf, strlen(buf));
530 		} else {
531 			(void)snprintf(buf, sizeof buf,
532 			    "%d packets received by filter\n", stat.ps_recv);
533 			write(STDERR_FILENO, buf, strlen(buf));
534 			(void)snprintf(buf, sizeof buf,
535 			    "%d packets dropped by kernel\n", stat.ps_drop);
536 			write(STDERR_FILENO, buf, strlen(buf));
537 		}
538 	}
539 	_exit(0);
540 }
541 
542 /* ARGSUSED */
543 RETSIGTYPE
544 gotchld(int signo)
545 {
546 	pid_t pid;
547 	int status;
548 	int save_err = errno;
549 
550 	do {
551 		pid = waitpid(child_pid, &status, WNOHANG);
552 		if (pid > 0 && (WIFEXITED(status) || WIFSIGNALED(status)))
553 			cleanup(0);
554 	} while (pid == -1 && errno == EINTR);
555 
556 	if (pid == -1)
557 		_exit(1);
558 
559 	errno = save_err;
560 }
561 
562 /* dump the buffer in `emacs-hexl' style */
563 void
564 default_print_hexl(const u_char *cp, unsigned int length)
565 {
566 	unsigned int i, j, jm;
567 	int c;
568 	char ln[128], buf[128];
569 
570 	printf("\n");
571 	for (i = 0; i < length; i += 0x10) {
572 		snprintf(ln, sizeof(ln), "  %04x: ", (unsigned int)i);
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 /* dump the text from the buffer */
606 void
607 default_print_ascii(const u_char *cp, unsigned int length)
608 {
609 	int c, i;
610 
611 	printf("\n");
612 	for (i = 0; i < length; i++) {
613 		c = cp[i];
614 		c = isprint(c) || isspace(c) ? c : '.';
615 		putchar(c);
616 	}
617 }
618 
619 /* Like default_print() but data need not be aligned */
620 void
621 default_print_unaligned(register const u_char *cp, register u_int length)
622 {
623 	register u_int i, s;
624 	register int nshorts;
625 
626 	if (Xflag) {
627 		/* dump the buffer in `emacs-hexl' style */
628 		default_print_hexl(cp, length);
629 	} else if (Aflag) {
630 		/* dump the text in the buffer */
631 		default_print_ascii(cp, length);
632 	} else {
633 		/* dump the buffer in old tcpdump style */
634 		nshorts = (u_int) length / sizeof(u_short);
635 		i = 0;
636 		while (--nshorts >= 0) {
637 			if ((i++ % 8) == 0)
638 				(void)printf("\n\t\t\t");
639 			s = *cp++;
640 			(void)printf(" %02x%02x", s, *cp++);
641 		}
642 		if (length & 1) {
643 			if ((i % 8) == 0)
644 				(void)printf("\n\t\t\t");
645 			(void)printf(" %02x", *cp);
646 		}
647 	}
648 }
649 
650 void
651 default_print(register const u_char *bp, register u_int length)
652 {
653 	register const u_short *sp;
654 	register u_int i;
655 	register int nshorts;
656 
657 	if (Xflag) {
658 		/* dump the buffer in `emacs-hexl' style */
659 		default_print_hexl(bp, length);
660 	} else if (Aflag) {
661 		/* dump the text in the buffer */
662 		default_print_ascii(bp, length);
663 	} else {
664 		/* dump the buffer in old tcpdump style */
665 		if ((long)bp & 1) {
666 			default_print_unaligned(bp, length);
667 			return;
668 		}
669 		sp = (u_short *)bp;
670 		nshorts = (u_int) length / sizeof(u_short);
671 		i = 0;
672 		while (--nshorts >= 0) {
673 			if ((i++ % 8) == 0)
674 				(void)printf("\n\t\t\t");
675 			(void)printf(" %04x", ntohs(*sp++));
676 		}
677 		if (length & 1) {
678 			if ((i % 8) == 0)
679 				(void)printf("\n\t\t\t");
680 			(void)printf(" %02x", *(u_char *)sp);
681 		}
682 	}
683 }
684 
685 void
686 set_slave_signals(void)
687 {
688 	RETSIGTYPE (*oldhandler)(int);
689 
690 	setsignal(SIGTERM, cleanup);
691 	setsignal(SIGINT, cleanup);
692 	setsignal(SIGCHLD, gotchld);
693 	/* Cooperate with nohup(1) XXX is this still necessary/working? */
694 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
695 		(void)setsignal(SIGHUP, oldhandler);
696 }
697 
698 __dead void
699 usage(void)
700 {
701 	(void)fprintf(stderr,
702 "Usage: %s [-AadefILlNnOopqStvXx] [-c count] [-D direction]\n",
703 	    program_name);
704 	(void)fprintf(stderr,
705 "\t       [-E [espalg:]espkey] [-F file] [-i interface] [-r file]\n");
706 	(void)fprintf(stderr,
707 "\t       [-s snaplen] [-T type] [-w file] [-y datalinktype] [expression]\n");
708 	exit(1);
709 }
710