xref: /freebsd/usr.sbin/ipfwpcap/ipfwpcap.c (revision f0a75d274af375d15b97b830966b99a02b7db911)
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 <unistd.h>
33 #include <sys/types.h>
34 #include <sys/time.h>
35 #include <sys/param.h>		/* for MAXPATHLEN */
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 
39 #include <netinet/in_systm.h>	/* for IP_MAXPACKET */
40 #include <netinet/ip.h>		/* for IP_MAXPACKET */
41 
42 /* XXX normally defined in config.h */
43 #define HAVE_STRLCPY 1
44 #define HAVE_SNPRINTF 1
45 #define HAVE_VSNPRINTF 1
46 #include <pcap-int.h>	/* see pcap(3) and /usr/src/contrib/libpcap/. */
47 
48 #ifdef IP_MAXPACKET
49 #define BUFMAX	IP_MAXPACKET
50 #else
51 #define BUFMAX	65535
52 #endif
53 
54 #ifndef MAXPATHLEN
55 #define MAXPATHLEN	1024
56 #endif
57 
58 static int debug = 0;
59 static int reflect = 0;		/* 1 == write packet back to socket. */
60 
61 static ssize_t totbytes = 0, maxbytes = 0;
62 static ssize_t totpkts = 0, maxpkts = 0;
63 
64 char *prog = NULL;
65 char pidfile[MAXPATHLEN] = { '\0' };
66 
67 /*
68  * tidy up.
69  */
70 void
71 quit(sig)
72 int sig;
73 {
74 	(void) unlink(pidfile);
75 	exit(sig);
76 }
77 
78 /*
79  * do the "paper work"
80  *	- save my own pid in /var/run/$0.{port#}.pid
81  */
82 okay(pn)
83 int pn;
84 {
85 	FILE *fp;
86 	int fd, numlen, n;
87 	char *p, numbuf[80];
88 
89 	numlen = sizeof(numbuf);
90 	bzero(numbuf, numlen);
91 	snprintf(numbuf, numlen-1, "%ld\n", getpid());
92 	numlen = strlen(numbuf);
93 
94 	if (pidfile[0] == '\0') {
95 		p = (char *)rindex(prog, '/');
96 		p = (p == NULL) ? prog : p+1 ;
97 
98 		snprintf(pidfile, sizeof(pidfile)-1,
99 			"%s%s.%d.pid", _PATH_VARRUN, p, pn);
100 	}
101 
102 	fd = open(pidfile, O_WRONLY|O_CREAT|O_EXCL, 0644);
103 	if (fd < 0) { perror(pidfile); exit(21); }
104 
105         siginterrupt(SIGTERM, 1);
106         siginterrupt(SIGHUP, 1);
107         signal (SIGTERM, quit);
108         signal (SIGHUP, quit);
109 
110 	n = write(fd, numbuf, numlen);
111 	if (n < 0) { perror(pidfile); quit(23); }
112 	(void) close(fd);
113 }
114 
115 usage()
116 {
117 	fprintf(stderr, "\
118 \n\
119 usage:\n\
120     %s [-dr] [-b maxbytes] [-p maxpkts] [-P pidfile] portnum dumpfile\n\
121 \n\
122 where:\n\
123 	'-d'  = enable debugging messages.\n\
124 	'-r'  = reflect. write packets back to the divert socket.\n\
125 		(ie. simulate the original intent of \"ipfw tee\").\n\
126 	'-rr' = indicate that it is okay to quit if packet-count or\n\
127 		byte-count limits are reached (see the NOTE below\n\
128 		about what this implies).\n\
129 	'-b bytcnt'   = stop dumping after {bytcnt} bytes.\n\
130 	'-p pktcnt'   = stop dumping after {pktcnt} packets.\n\
131 	'-P pidfile'  = alternate file to store the PID\n\
132 			(default: /var/run/%s.{portnum}.pid).\n\
133 \n\
134 	portnum  = divert(4) socket port number.\n\
135 	dumpfile = file to write captured packets (tcpdump format).\n\
136 		   (specify '-' to write packets to stdout).\n\
137 \n\
138 ", prog, prog);
139 
140 	fprintf(stderr, "\
141 The '-r' option should not be necessary, but because \"ipfw tee\" is broken\n\
142 (see BUGS in ipfw(8) for details) this feature can be used along with\n\
143 an \"ipfw divert\" rule to simulate the original intent of \"ipfw tee\".\n\
144 \n\
145 NOTE: With an \"ipfw divert\" rule, diverted packets will silently\n\
146       disappear if there is nothing listening to the divert socket.\n\
147 \n\
148 ");
149 	exit(-1);
150 }
151 
152 main(ac, av)
153 int ac;
154 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) = %d (%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