xref: /freebsd/usr.sbin/ipfwpcap/ipfwpcap.c (revision 10ff414c)
1 /*
2  * copy diverted (or tee'd) packets to a file in 'tcpdump' format
3  * (ie. this uses the '-lpcap' routines).
4  *
5  * example usage:
6  *	# ipfwpcap -r 8091 divt.log &
7  *	# ipfw add 2864 divert 8091 ip from 128.432.53.82 to any
8  *	# ipfw add 2864 divert 8091 ip from any to 128.432.53.82
9  *
10  *   the resulting dump file can be read with ...
11  *	# tcpdump -nX -r divt.log
12  */
13 /*
14  * Written by P Kern { pkern [AT] cns.utoronto.ca }
15  *
16  * Copyright (c) 2004 University of Toronto. All rights reserved.
17  * Anyone may use or copy this software except that this copyright
18  * notice remain intact and that credit is given where it is due.
19  * The University of Toronto and the author make no warranty and
20  * accept no liability for this software.
21  *
22  * From: Header: /local/src/local.lib/SRC/ipfwpcap/RCS/ipfwpcap.c,v 1.4 2004/01/15 16:19:07 pkern Exp
23  *
24  * $FreeBSD$
25  */
26 
27 #include <stdio.h>
28 #include <errno.h>
29 #include <paths.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <sys/types.h>
36 #include <sys/time.h>
37 #include <sys/param.h>		/* for MAXPATHLEN */
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 
41 #include <netinet/in_systm.h>	/* for IP_MAXPACKET */
42 #include <netinet/ip.h>		/* for IP_MAXPACKET */
43 
44 #include <net/bpf.h>
45 
46 /* XXX normally defined in config.h */
47 #define HAVE_STRLCPY 1
48 #define HAVE_SNPRINTF 1
49 #define HAVE_VSNPRINTF 1
50 #include <pcap-int.h>	/* see pcap(3) and /usr/src/contrib/libpcap/. */
51 
52 #ifdef IP_MAXPACKET
53 #define BUFMAX	IP_MAXPACKET
54 #else
55 #define BUFMAX	65535
56 #endif
57 
58 #ifndef MAXPATHLEN
59 #define MAXPATHLEN	1024
60 #endif
61 
62 static int debug = 0;
63 static int reflect = 0;		/* 1 == write packet back to socket. */
64 
65 static ssize_t totbytes = 0, maxbytes = 0;
66 static ssize_t totpkts = 0, maxpkts = 0;
67 
68 static char *prog = NULL;
69 static char pidfile[MAXPATHLEN];
70 
71 /*
72  * tidy up.
73  */
74 static void
75 quit(int sig)
76 {
77 	(void) unlink(pidfile);
78 	exit(sig);
79 }
80 
81 /*
82  * do the "paper work"
83  *	- save my own pid in /var/run/$0.{port#}.pid
84  */
85 static void
86 okay(int pn)
87 {
88 	int fd;
89 	char *p, numbuf[80];
90 
91 	if (pidfile[0] == '\0') {
92 		p = strrchr(prog, '/');
93 		p = (p == NULL) ? prog : p + 1;
94 
95 		snprintf(pidfile, sizeof pidfile,
96 			"%s%s.%d.pid", _PATH_VARRUN, p, pn);
97 	}
98 
99 	fd = open(pidfile, O_WRONLY|O_CREAT|O_EXCL, 0644);
100 	if (fd < 0) {
101 		perror(pidfile);
102 		exit(21);
103 	}
104 
105 	siginterrupt(SIGTERM, 1);
106 	siginterrupt(SIGHUP, 1);
107 	signal(SIGTERM, quit);
108 	signal(SIGHUP, quit);
109 	signal(SIGINT, quit);
110 
111 	snprintf(numbuf, sizeof numbuf, "%d\n", getpid());
112 	if (write(fd, numbuf, strlen(numbuf)) < 0) {
113 		perror(pidfile);
114 		quit(23);
115 	}
116 	(void) close(fd);
117 }
118 
119 static void
120 usage(void)
121 {
122 	fprintf(stderr,
123 "\n"
124 "usage:\n"
125 "    %s [-dr] [-b maxbytes] [-p maxpkts] [-P pidfile] portnum dumpfile\n"
126 "\n"
127 "where:\n"
128 "	'-d'  = enable debugging messages.\n"
129 "	'-r'  = reflect. write packets back to the divert socket.\n"
130 "		(ie. simulate the original intent of \"ipfw tee\").\n"
131 "	'-rr' = indicate that it is okay to quit if packet-count or\n"
132 "		byte-count limits are reached (see the NOTE below\n"
133 "		about what this implies).\n"
134 "	'-b bytcnt'   = stop dumping after {bytcnt} bytes.\n"
135 "	'-p pktcnt'   = stop dumping after {pktcnt} packets.\n"
136 "	'-P pidfile'  = alternate file to store the PID\n"
137 "			(default: /var/run/%s.{portnum}.pid).\n"
138 "\n"
139 "	portnum  = divert(4) socket port number.\n"
140 "	dumpfile = file to write captured packets (tcpdump format).\n"
141 "		   (specify '-' to write packets to stdout).\n"
142 "\n"
143 "The '-r' option should not be necessary, but because \"ipfw tee\" is broken\n"
144 "(see BUGS in ipfw(8) for details) this feature can be used along with\n"
145 "an \"ipfw divert\" rule to simulate the original intent of \"ipfw tee\".\n"
146 "\n"
147 "NOTE: With an \"ipfw divert\" rule, diverted packets will silently\n"
148 "      disappear if there is nothing listening to the divert socket.\n"
149 "\n", prog, prog);
150 	exit(1);
151 }
152 
153 int
154 main(int ac, char *av[])
155 {
156 	int r, sd, portnum, l;
157         struct sockaddr_in sin;
158 	int errflg = 0;
159 
160 	int nfd;
161 	fd_set rds;
162 
163 	ssize_t nr;
164 
165 	char *dumpf, buf[BUFMAX];
166 
167 	pcap_t *p;
168 	pcap_dumper_t *dp;
169 	struct pcap_pkthdr phd;
170 
171 	prog = av[0];
172 
173 	while ((r = getopt(ac, av, "drb:p:P:")) != -1) {
174 		switch (r) {
175 		case 'd':
176 			debug++;
177 			break;
178 		case 'r':
179 			reflect++;
180 			break;
181 		case 'b':
182 			maxbytes = (ssize_t) atol(optarg);
183 			break;
184 		case 'p':
185 			maxpkts = (ssize_t) atoi(optarg);
186 			break;
187 		case 'P':
188 			strcpy(pidfile, optarg);
189 			break;
190 		case '?':
191 		default:
192 			errflg++;
193 			break;
194 		}
195 	}
196 
197 	if ((ac - optind) != 2 || errflg)
198 		usage();
199 
200 	portnum = atoi(av[optind++]);
201 	dumpf = av[optind];
202 
203 if (debug) fprintf(stderr, "bind to %d.\ndump to '%s'.\n", portnum, dumpf);
204 
205 	if ((r = socket(PF_INET, SOCK_RAW, IPPROTO_DIVERT)) == -1) {
206 		perror("socket(DIVERT)");
207 		exit(2);
208 	}
209 	sd = r;
210 
211 	sin.sin_port = htons(portnum);
212 	sin.sin_family = AF_INET;
213 	sin.sin_addr.s_addr = INADDR_ANY;
214 
215 	if (bind(sd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
216 		perror("bind(divert)");
217 		exit(3);
218 	}
219 
220 	p = pcap_open_dead(DLT_RAW, BUFMAX);
221 	dp = pcap_dump_open(p, dumpf);
222 	if (dp == NULL) {
223 		pcap_perror(p, dumpf);
224 		exit(4);
225 	}
226 
227 	okay(portnum);
228 
229 	nfd = sd + 1;
230 	for (;;) {
231 		FD_ZERO(&rds);
232 		FD_SET(sd, &rds);
233 
234 		r = select(nfd, &rds, NULL, NULL, NULL);
235 		if (r == -1) {
236 			if (errno == EINTR) continue;
237 			perror("select");
238 			quit(11);
239 		}
240 
241 		if (!FD_ISSET(sd, &rds))
242 			/* hmm. no work. */
243 			continue;
244 
245 		/*
246 		 * use recvfrom(3 and sendto(3) as in natd(8).
247 		 * see /usr/src/sbin/natd/natd.c
248 		 * see ipfw(8) about using 'divert' and 'tee'.
249 		 */
250 
251 		/*
252 		 * read packet.
253 		 */
254 		l = sizeof(sin);
255 		nr = recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr *)&sin, &l);
256 if (debug) fprintf(stderr, "recvfrom(%d) = %zd (%d)\n", sd, nr, l);
257 		if (nr < 0 && errno != EINTR) {
258 			perror("recvfrom(sd)");
259 			quit(12);
260 		}
261 		if (nr <= 0) continue;
262 
263 		if (reflect) {
264 			/*
265 			 * write packet back so it can continue
266 			 * being processed by any further IPFW rules.
267 			 */
268 			l = sizeof(sin);
269 			r = sendto(sd, buf, nr, 0, (struct sockaddr *)&sin, l);
270 if (debug) fprintf(stderr, "  sendto(%d) = %d\n", sd, r);
271 			if (r < 0) { perror("sendto(sd)"); quit(13); }
272 		}
273 
274 		/*
275 		 * check maximums, if any.
276 		 * but don't quit if must continue reflecting packets.
277 		 */
278 		if (maxpkts) {
279 			totpkts++;
280 			if (totpkts > maxpkts) {
281 				if (reflect == 1) continue;
282 				quit(0);
283 			}
284 		}
285 		if (maxbytes) {
286 			totbytes += nr;
287 			if (totbytes > maxbytes) {
288 				if (reflect == 1) continue;
289 				quit(0);
290 			}
291 		}
292 
293 		/*
294 		 * save packet in tcpdump(1) format. see pcap(3).
295 		 * divert packets are fully assembled. see ipfw(8).
296 		 */
297 		(void) gettimeofday(&(phd.ts), NULL);
298 		phd.caplen = phd.len = nr;
299 		pcap_dump((u_char *)dp, &phd, buf);
300 		if (ferror((FILE *)dp)) { perror(dumpf); quit(14); }
301 		(void) fflush((FILE *)dp);
302 	}
303 
304 	quit(0);
305 }
306