1 /*
2  * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code distributions
7  * retain the above copyright notice and this paragraph in its entirety, (2)
8  * distributions including binary code include the above copyright notice and
9  * this paragraph in its entirety in the documentation or other materials
10  * provided with the distribution, and (3) all advertising materials mentioning
11  * features or use of this software display the following acknowledgement:
12  * ``This product includes software developed by the University of California,
13  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14  * the University nor the names of its contributors may be used to endorse
15  * or promote products derived from this software without specific prior
16  * written permission.
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20  */
21 
22 #include "varattrs.h"
23 
24 /*
25  * This doesn't actually test libpcap itself; it tests whether
26  * valgrind properly handles the APIs libpcap uses.  If it doesn't,
27  * we end up getting patches submitted to "fix" references that
28  * valgrind claims are being made to uninitialized data, when, in
29  * fact, the OS isn't making any such references - or we get
30  * valgrind *not* detecting *actual* incorrect references.
31  *
32  * Both BPF and Linux socket filters aren't handled correctly
33  * by some versions of valgrind.  See valgrind bug 318203 for
34  * Linux:
35  *
36  *	https://bugs.kde.org/show_bug.cgi?id=318203
37  *
38  * and valgrind bug 312989 for macOS:
39  *
40  *	https://bugs.kde.org/show_bug.cgi?id=312989
41  *
42  * The fixes for both of those are checked into the official valgrind
43  * repository.
44  *
45  * The unofficial FreeBSD port has similar issues to the official macOS
46  * port, for similar reasons.
47  */
48 #ifndef lint
49 static const char copyright[] _U_ =
50     "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
51 The Regents of the University of California.  All rights reserved.\n";
52 #endif
53 
54 #ifdef HAVE_CONFIG_H
55 #include <config.h>
56 #endif
57 
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <stdarg.h>
62 #include <unistd.h>
63 #include <fcntl.h>
64 #include <errno.h>
65 #include <arpa/inet.h>
66 #include <sys/types.h>
67 #include <sys/stat.h>
68 
69 #include "pcap/funcattrs.h"
70 
71 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(_AIX) || defined(sun)
72 /* OS with BPF - use BPF */
73 #define USE_BPF
74 #elif defined(linux)
75 /* Linux - use socket filters */
76 #define USE_SOCKET_FILTERS
77 #else
78 #error "Unknown platform or platform that doesn't support Valgrind"
79 #endif
80 
81 #if defined(USE_BPF)
82 
83 #include <sys/ioctl.h>
84 #include <net/bpf.h>
85 
86 /*
87  * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
88  * native OS version, as we're going to be doing our own ioctls to
89  * make sure that, in the uninitialized-data tests, the filters aren't
90  * checked by libpcap before being handed to BPF.
91  */
92 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
93 
94 #elif defined(USE_SOCKET_FILTERS)
95 
96 #include <sys/socket.h>
97 #include <linux/types.h>
98 #include <linux/filter.h>
99 
100 #endif
101 
102 #include <pcap.h>
103 
104 static char *program_name;
105 
106 /* Forwards */
107 static void PCAP_NORETURN usage(void);
108 static void PCAP_NORETURN error(const char *, ...) PCAP_PRINTFLIKE(1, 2);
109 static void warning(const char *, ...) PCAP_PRINTFLIKE(1, 2);
110 
111 /*
112  * On Windows, we need to open the file in binary mode, so that
113  * we get all the bytes specified by the size we get from "fstat()".
114  * On UNIX, that's not necessary.  O_BINARY is defined on Windows;
115  * we define it as 0 if it's not defined, so it does nothing.
116  */
117 #ifndef O_BINARY
118 #define O_BINARY	0
119 #endif
120 
121 static char *
122 read_infile(char *fname)
123 {
124 	register int i, fd, cc;
125 	register char *cp;
126 	struct stat buf;
127 
128 	fd = open(fname, O_RDONLY|O_BINARY);
129 	if (fd < 0)
130 		error("can't open %s: %s", fname, pcap_strerror(errno));
131 
132 	if (fstat(fd, &buf) < 0)
133 		error("can't stat %s: %s", fname, pcap_strerror(errno));
134 
135 	cp = malloc((u_int)buf.st_size + 1);
136 	if (cp == NULL)
137 		error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
138 			fname, pcap_strerror(errno));
139 	cc = read(fd, cp, (u_int)buf.st_size);
140 	if (cc < 0)
141 		error("read %s: %s", fname, pcap_strerror(errno));
142 	if (cc != buf.st_size)
143 		error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
144 
145 	close(fd);
146 	/* replace "# comment" with spaces */
147 	for (i = 0; i < cc; i++) {
148 		if (cp[i] == '#')
149 			while (i < cc && cp[i] != '\n')
150 				cp[i++] = ' ';
151 	}
152 	cp[cc] = '\0';
153 	return (cp);
154 }
155 
156 /* VARARGS */
157 static void
158 error(const char *fmt, ...)
159 {
160 	va_list ap;
161 
162 	(void)fprintf(stderr, "%s: ", program_name);
163 	va_start(ap, fmt);
164 	(void)vfprintf(stderr, fmt, ap);
165 	va_end(ap);
166 	if (*fmt) {
167 		fmt += strlen(fmt);
168 		if (fmt[-1] != '\n')
169 			(void)fputc('\n', stderr);
170 	}
171 	exit(1);
172 	/* NOTREACHED */
173 }
174 
175 /* VARARGS */
176 static void
177 warning(const char *fmt, ...)
178 {
179 	va_list ap;
180 
181 	(void)fprintf(stderr, "%s: WARNING: ", program_name);
182 	va_start(ap, fmt);
183 	(void)vfprintf(stderr, fmt, ap);
184 	va_end(ap);
185 	if (*fmt) {
186 		fmt += strlen(fmt);
187 		if (fmt[-1] != '\n')
188 			(void)fputc('\n', stderr);
189 	}
190 }
191 
192 /*
193  * Copy arg vector into a new buffer, concatenating arguments with spaces.
194  */
195 static char *
196 copy_argv(register char **argv)
197 {
198 	register char **p;
199 	register u_int len = 0;
200 	char *buf;
201 	char *src, *dst;
202 
203 	p = argv;
204 	if (*p == 0)
205 		return 0;
206 
207 	while (*p)
208 		len += strlen(*p++) + 1;
209 
210 	buf = (char *)malloc(len);
211 	if (buf == NULL)
212 		error("copy_argv: malloc");
213 
214 	p = argv;
215 	dst = buf;
216 	while ((src = *p++) != NULL) {
217 		while ((*dst++ = *src++) != '\0')
218 			;
219 		dst[-1] = ' ';
220 	}
221 	dst[-1] = '\0';
222 
223 	return buf;
224 }
225 
226 #define INSN_COUNT	17
227 
228 int
229 main(int argc, char **argv)
230 {
231 	char *cp, *device;
232 	int op;
233 	int dorfmon, useactivate;
234 	char ebuf[PCAP_ERRBUF_SIZE];
235 	char *infile;
236 	const char *cmdbuf;
237 	pcap_if_t *devlist;
238 	pcap_t *pd;
239 	int status = 0;
240 	int pcap_fd;
241 #if defined(USE_BPF)
242 	struct bpf_program bad_fcode;
243 	struct bpf_insn uninitialized[INSN_COUNT];
244 #elif defined(USE_SOCKET_FILTERS)
245 	struct sock_fprog bad_fcode;
246 	struct sock_filter uninitialized[INSN_COUNT];
247 #endif
248 	struct bpf_program fcode;
249 
250 	device = NULL;
251 	dorfmon = 0;
252 	useactivate = 0;
253 	infile = NULL;
254 
255 	if ((cp = strrchr(argv[0], '/')) != NULL)
256 		program_name = cp + 1;
257 	else
258 		program_name = argv[0];
259 
260 	opterr = 0;
261 	while ((op = getopt(argc, argv, "aF:i:I")) != -1) {
262 		switch (op) {
263 
264 		case 'a':
265 			useactivate = 1;
266 			break;
267 
268 		case 'F':
269 			infile = optarg;
270 			break;
271 
272 		case 'i':
273 			device = optarg;
274 			break;
275 
276 		case 'I':
277 			dorfmon = 1;
278 			useactivate = 1;	/* required for rfmon */
279 			break;
280 
281 		default:
282 			usage();
283 			/* NOTREACHED */
284 		}
285 	}
286 
287 	if (device == NULL) {
288 		/*
289 		 * No interface specified; get whatever pcap_lookupdev()
290 		 * finds.
291 		 */
292 		if (pcap_findalldevs(&devlist, ebuf) == -1)
293 			error("%s", ebuf);
294 		if (devlist == NULL)
295 			error("no interfaces available for capture");
296 		device = strdup(devlist->name);
297 		pcap_freealldevs(devlist);
298 	}
299 
300 	if (infile != NULL) {
301 		/*
302 		 * Filter specified with "-F" and a file containing
303 		 * a filter.
304 		 */
305 		cmdbuf = read_infile(infile);
306 	} else {
307 		if (optind < argc) {
308 			/*
309 			 * Filter specified with arguments on the
310 			 * command line.
311 			 */
312 			cmdbuf = copy_argv(&argv[optind+1]);
313 		} else {
314 			/*
315 			 * No filter specified; use an empty string, which
316 			 * compiles to an "accept all" filter.
317 			 */
318 			cmdbuf = "";
319 		}
320 	}
321 
322 	if (useactivate) {
323 		pd = pcap_create(device, ebuf);
324 		if (pd == NULL)
325 			error("%s: pcap_create() failed: %s", device, ebuf);
326 		status = pcap_set_snaplen(pd, 65535);
327 		if (status != 0)
328 			error("%s: pcap_set_snaplen failed: %s",
329 			    device, pcap_statustostr(status));
330 		status = pcap_set_promisc(pd, 1);
331 		if (status != 0)
332 			error("%s: pcap_set_promisc failed: %s",
333 			    device, pcap_statustostr(status));
334 		if (dorfmon) {
335 			status = pcap_set_rfmon(pd, 1);
336 			if (status != 0)
337 				error("%s: pcap_set_rfmon failed: %s",
338 				    device, pcap_statustostr(status));
339 		}
340 		status = pcap_set_timeout(pd, 1000);
341 		if (status != 0)
342 			error("%s: pcap_set_timeout failed: %s",
343 			    device, pcap_statustostr(status));
344 		status = pcap_activate(pd);
345 		if (status < 0) {
346 			/*
347 			 * pcap_activate() failed.
348 			 */
349 			error("%s: %s\n(%s)", device,
350 			    pcap_statustostr(status), pcap_geterr(pd));
351 		} else if (status > 0) {
352 			/*
353 			 * pcap_activate() succeeded, but it's warning us
354 			 * of a problem it had.
355 			 */
356 			warning("%s: %s\n(%s)", device,
357 			    pcap_statustostr(status), pcap_geterr(pd));
358 		}
359 	} else {
360 		*ebuf = '\0';
361 		pd = pcap_open_live(device, 65535, 1, 1000, ebuf);
362 		if (pd == NULL)
363 			error("%s", ebuf);
364 		else if (*ebuf)
365 			warning("%s", ebuf);
366 	}
367 
368 	pcap_fd = pcap_fileno(pd);
369 
370 	/*
371 	 * Try setting a filter with an uninitialized bpf_program
372 	 * structure.  This should cause valgrind to report a
373 	 * problem.
374 	 *
375 	 * We don't check for errors, because it could get an
376 	 * error due to a bad pointer or count.
377 	 */
378 #if defined(USE_BPF)
379 	ioctl(pcap_fd, BIOCSETF, &bad_fcode);
380 #elif defined(USE_SOCKET_FILTERS)
381 	setsockopt(pcap_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bad_fcode,
382 	    sizeof(bad_fcode));
383 #endif
384 
385 	/*
386 	 * Try setting a filter with an initialized bpf_program
387 	 * structure that points to an uninitialized program.
388 	 * That should also cause valgrind to report a problem.
389 	 *
390 	 * We don't check for errors, because it could get an
391 	 * error due to a bad pointer or count.
392 	 */
393 #if defined(USE_BPF)
394 	bad_fcode.bf_len = INSN_COUNT;
395 	bad_fcode.bf_insns = uninitialized;
396 	ioctl(pcap_fd, BIOCSETF, &bad_fcode);
397 #elif defined(USE_SOCKET_FILTERS)
398 	bad_fcode.len = INSN_COUNT;
399 	bad_fcode.filter = uninitialized;
400 	setsockopt(pcap_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bad_fcode,
401 	    sizeof(bad_fcode));
402 #endif
403 
404 	/*
405 	 * Now compile a filter and set the filter with that.
406 	 * That should *not* cause valgrind to report a
407 	 * problem.
408 	 */
409 	if (pcap_compile(pd, &fcode, cmdbuf, 1, 0) < 0)
410 		error("can't compile filter: %s", pcap_geterr(pd));
411 	if (pcap_setfilter(pd, &fcode) < 0)
412 		error("can't set filter: %s", pcap_geterr(pd));
413 
414 	pcap_close(pd);
415 	exit(status < 0 ? 1 : 0);
416 }
417 
418 static void
419 usage(void)
420 {
421 	(void)fprintf(stderr, "%s, with %s\n", program_name,
422 	    pcap_lib_version());
423 	(void)fprintf(stderr,
424 	    "Usage: %s [-aI] [ -F file ] [ -I interface ] [ expression ]\n",
425 	    program_name);
426 	exit(1);
427 }
428