1/*-
2 * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from the Stanford/CMU enet packet filter,
6 * (net/enet.c) distributed as part of 4.3BSD, and code contributed
7 * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
8 * Berkeley Laboratory.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the University of
21 *	California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 *	@(#)bpf.c	7.5 (Berkeley) 7/15/91
39 */
40
41#ifdef HAVE_CONFIG_H
42#include "config.h"
43#endif
44
45#ifdef _WIN32
46
47#include <pcap-stdinc.h>
48
49#else /* _WIN32 */
50
51#if HAVE_INTTYPES_H
52#include <inttypes.h>
53#elif HAVE_STDINT_H
54#include <stdint.h>
55#endif
56#ifdef HAVE_SYS_BITYPES_H
57#include <sys/bitypes.h>
58#endif
59
60#include <sys/param.h>
61#include <sys/types.h>
62#include <sys/time.h>
63
64#define	SOLARIS	(defined(sun) && (defined(__SVR4) || defined(__svr4__)))
65#if defined(__hpux) || SOLARIS
66# include <sys/sysmacros.h>
67# include <sys/stream.h>
68# define	mbuf	msgb
69# define	m_next	b_cont
70# define	MLEN(m)	((m)->b_wptr - (m)->b_rptr)
71# define	mtod(m,t)	((t)(m)->b_rptr)
72#else /* defined(__hpux) || SOLARIS */
73# define	MLEN(m)	((m)->m_len)
74#endif /* defined(__hpux) || SOLARIS */
75
76#endif /* _WIN32 */
77
78#include <pcap/bpf.h>
79
80#if !defined(KERNEL) && !defined(_KERNEL)
81#include <stdlib.h>
82#endif
83
84#define int32 bpf_int32
85#define u_int32 bpf_u_int32
86
87#ifndef LBL_ALIGN
88/*
89 * XXX - IA-64?  If not, this probably won't work on Win64 IA-64
90 * systems, unless LBL_ALIGN is defined elsewhere for them.
91 * XXX - SuperH?  If not, this probably won't work on WinCE SuperH
92 * systems, unless LBL_ALIGN is defined elsewhere for them.
93 */
94#if defined(sparc) || defined(__sparc__) || defined(mips) || \
95    defined(ibm032) || defined(__alpha) || defined(__hpux) || \
96    defined(__arm__)
97#define LBL_ALIGN
98#endif
99#endif
100
101#ifndef LBL_ALIGN
102#ifndef _WIN32
103#include <netinet/in.h>
104#endif
105
106#define EXTRACT_SHORT(p)	((u_short)ntohs(*(u_short *)p))
107#define EXTRACT_LONG(p)		(ntohl(*(u_int32 *)p))
108#else
109#define EXTRACT_SHORT(p)\
110	((u_short)\
111		((u_short)*((u_char *)p+0)<<8|\
112		 (u_short)*((u_char *)p+1)<<0))
113#define EXTRACT_LONG(p)\
114		((u_int32)*((u_char *)p+0)<<24|\
115		 (u_int32)*((u_char *)p+1)<<16|\
116		 (u_int32)*((u_char *)p+2)<<8|\
117		 (u_int32)*((u_char *)p+3)<<0)
118#endif
119
120#if defined(KERNEL) || defined(_KERNEL)
121# if !defined(__hpux) && !SOLARIS
122#include <sys/mbuf.h>
123# endif
124#define MINDEX(len, _m, _k) \
125{ \
126	len = MLEN(m); \
127	while ((_k) >= len) { \
128		(_k) -= len; \
129		(_m) = (_m)->m_next; \
130		if ((_m) == 0) \
131			return 0; \
132		len = MLEN(m); \
133	} \
134}
135
136static int
137m_xword(m, k, err)
138	register struct mbuf *m;
139	register int k, *err;
140{
141	register int len;
142	register u_char *cp, *np;
143	register struct mbuf *m0;
144
145	MINDEX(len, m, k);
146	cp = mtod(m, u_char *) + k;
147	if (len - k >= 4) {
148		*err = 0;
149		return EXTRACT_LONG(cp);
150	}
151	m0 = m->m_next;
152	if (m0 == 0 || MLEN(m0) + len - k < 4)
153		goto bad;
154	*err = 0;
155	np = mtod(m0, u_char *);
156	switch (len - k) {
157
158	case 1:
159		return (cp[0] << 24) | (np[0] << 16) | (np[1] << 8) | np[2];
160
161	case 2:
162		return (cp[0] << 24) | (cp[1] << 16) | (np[0] << 8) | np[1];
163
164	default:
165		return (cp[0] << 24) | (cp[1] << 16) | (cp[2] << 8) | np[0];
166	}
167    bad:
168	*err = 1;
169	return 0;
170}
171
172static int
173m_xhalf(m, k, err)
174	register struct mbuf *m;
175	register int k, *err;
176{
177	register int len;
178	register u_char *cp;
179	register struct mbuf *m0;
180
181	MINDEX(len, m, k);
182	cp = mtod(m, u_char *) + k;
183	if (len - k >= 2) {
184		*err = 0;
185		return EXTRACT_SHORT(cp);
186	}
187	m0 = m->m_next;
188	if (m0 == 0)
189		goto bad;
190	*err = 0;
191	return (cp[0] << 8) | mtod(m0, u_char *)[0];
192 bad:
193	*err = 1;
194	return 0;
195}
196#endif
197
198#ifdef __linux__
199#include <linux/types.h>
200#include <linux/if_packet.h>
201#include <linux/filter.h>
202#endif
203
204enum {
205        BPF_S_ANC_NONE,
206        BPF_S_ANC_VLAN_TAG,
207        BPF_S_ANC_VLAN_TAG_PRESENT,
208};
209
210/*
211 * Execute the filter program starting at pc on the packet p
212 * wirelen is the length of the original packet
213 * buflen is the amount of data present
214 * aux_data is auxiliary data, currently used only when interpreting
215 * filters intended for the Linux kernel in cases where the kernel
216 * rejects the filter; it contains VLAN tag information
217 * For the kernel, p is assumed to be a pointer to an mbuf if buflen is 0,
218 * in all other cases, p is a pointer to a buffer and buflen is its size.
219 *
220 * Thanks to Ani Sinha <ani@arista.com> for providing initial implementation
221 */
222u_int
223bpf_filter_with_aux_data(pc, p, wirelen, buflen, aux_data)
224	register const struct bpf_insn *pc;
225	register const u_char *p;
226	u_int wirelen;
227	register u_int buflen;
228	register const struct bpf_aux_data *aux_data;
229{
230	register u_int32 A, X;
231	register bpf_u_int32 k;
232	u_int32 mem[BPF_MEMWORDS];
233#if defined(KERNEL) || defined(_KERNEL)
234	struct mbuf *m, *n;
235	int merr, len;
236
237	if (buflen == 0) {
238		m = (struct mbuf *)p;
239		p = mtod(m, u_char *);
240		buflen = MLEN(m);
241	} else
242		m = NULL;
243#endif
244
245	if (pc == 0)
246		/*
247		 * No filter means accept all.
248		 */
249		return (u_int)-1;
250	A = 0;
251	X = 0;
252	--pc;
253	while (1) {
254		++pc;
255		switch (pc->code) {
256
257		default:
258#if defined(KERNEL) || defined(_KERNEL)
259			return 0;
260#else
261			abort();
262#endif
263		case BPF_RET|BPF_K:
264			return (u_int)pc->k;
265
266		case BPF_RET|BPF_A:
267			return (u_int)A;
268
269		case BPF_LD|BPF_W|BPF_ABS:
270			k = pc->k;
271			if (k > buflen || sizeof(int32_t) > buflen - k) {
272#if defined(KERNEL) || defined(_KERNEL)
273				if (m == NULL)
274					return 0;
275				A = m_xword(m, k, &merr);
276				if (merr != 0)
277					return 0;
278				continue;
279#else
280				return 0;
281#endif
282			}
283			A = EXTRACT_LONG(&p[k]);
284			continue;
285
286		case BPF_LD|BPF_H|BPF_ABS:
287			k = pc->k;
288			if (k > buflen || sizeof(int16_t) > buflen - k) {
289#if defined(KERNEL) || defined(_KERNEL)
290				if (m == NULL)
291					return 0;
292				A = m_xhalf(m, k, &merr);
293				if (merr != 0)
294					return 0;
295				continue;
296#else
297				return 0;
298#endif
299			}
300			A = EXTRACT_SHORT(&p[k]);
301			continue;
302
303		case BPF_LD|BPF_B|BPF_ABS:
304			{
305#if defined(SKF_AD_VLAN_TAG) && defined(SKF_AD_VLAN_TAG_PRESENT)
306				int code = BPF_S_ANC_NONE;
307#define ANCILLARY(CODE) case SKF_AD_OFF + SKF_AD_##CODE:		\
308				code = BPF_S_ANC_##CODE;		\
309                                        if (!aux_data)                  \
310                                                return 0;               \
311                                        break;
312
313				switch (pc->k) {
314					ANCILLARY(VLAN_TAG);
315					ANCILLARY(VLAN_TAG_PRESENT);
316				default :
317#endif
318					k = pc->k;
319					if (k >= buflen) {
320#if defined(KERNEL) || defined(_KERNEL)
321						if (m == NULL)
322							return 0;
323						n = m;
324						MINDEX(len, n, k);
325						A = mtod(n, u_char *)[k];
326						continue;
327#else
328						return 0;
329#endif
330					}
331					A = p[k];
332#if defined(SKF_AD_VLAN_TAG) && defined(SKF_AD_VLAN_TAG_PRESENT)
333				}
334				switch (code) {
335				case BPF_S_ANC_VLAN_TAG:
336					if (aux_data)
337						A = aux_data->vlan_tag;
338					break;
339
340				case BPF_S_ANC_VLAN_TAG_PRESENT:
341					if (aux_data)
342						A = aux_data->vlan_tag_present;
343					break;
344				}
345#endif
346				continue;
347			}
348		case BPF_LD|BPF_W|BPF_LEN:
349			A = wirelen;
350			continue;
351
352		case BPF_LDX|BPF_W|BPF_LEN:
353			X = wirelen;
354			continue;
355
356		case BPF_LD|BPF_W|BPF_IND:
357			k = X + pc->k;
358			if (pc->k > buflen || X > buflen - pc->k ||
359			    sizeof(int32_t) > buflen - k) {
360#if defined(KERNEL) || defined(_KERNEL)
361				if (m == NULL)
362					return 0;
363				A = m_xword(m, k, &merr);
364				if (merr != 0)
365					return 0;
366				continue;
367#else
368				return 0;
369#endif
370			}
371			A = EXTRACT_LONG(&p[k]);
372			continue;
373
374		case BPF_LD|BPF_H|BPF_IND:
375			k = X + pc->k;
376			if (X > buflen || pc->k > buflen - X ||
377			    sizeof(int16_t) > buflen - k) {
378#if defined(KERNEL) || defined(_KERNEL)
379				if (m == NULL)
380					return 0;
381				A = m_xhalf(m, k, &merr);
382				if (merr != 0)
383					return 0;
384				continue;
385#else
386				return 0;
387#endif
388			}
389			A = EXTRACT_SHORT(&p[k]);
390			continue;
391
392		case BPF_LD|BPF_B|BPF_IND:
393			k = X + pc->k;
394			if (pc->k >= buflen || X >= buflen - pc->k) {
395#if defined(KERNEL) || defined(_KERNEL)
396				if (m == NULL)
397					return 0;
398				n = m;
399				MINDEX(len, n, k);
400				A = mtod(n, u_char *)[k];
401				continue;
402#else
403				return 0;
404#endif
405			}
406			A = p[k];
407			continue;
408
409		case BPF_LDX|BPF_MSH|BPF_B:
410			k = pc->k;
411			if (k >= buflen) {
412#if defined(KERNEL) || defined(_KERNEL)
413				if (m == NULL)
414					return 0;
415				n = m;
416				MINDEX(len, n, k);
417				X = (mtod(n, char *)[k] & 0xf) << 2;
418				continue;
419#else
420				return 0;
421#endif
422			}
423			X = (p[pc->k] & 0xf) << 2;
424			continue;
425
426		case BPF_LD|BPF_IMM:
427			A = pc->k;
428			continue;
429
430		case BPF_LDX|BPF_IMM:
431			X = pc->k;
432			continue;
433
434		case BPF_LD|BPF_MEM:
435			A = mem[pc->k];
436			continue;
437
438		case BPF_LDX|BPF_MEM:
439			X = mem[pc->k];
440			continue;
441
442		case BPF_ST:
443			mem[pc->k] = A;
444			continue;
445
446		case BPF_STX:
447			mem[pc->k] = X;
448			continue;
449
450		case BPF_JMP|BPF_JA:
451#if defined(KERNEL) || defined(_KERNEL)
452			/*
453			 * No backward jumps allowed.
454			 */
455			pc += pc->k;
456#else
457			/*
458			 * XXX - we currently implement "ip6 protochain"
459			 * with backward jumps, so sign-extend pc->k.
460			 */
461			pc += (bpf_int32)pc->k;
462#endif
463			continue;
464
465		case BPF_JMP|BPF_JGT|BPF_K:
466			pc += (A > pc->k) ? pc->jt : pc->jf;
467			continue;
468
469		case BPF_JMP|BPF_JGE|BPF_K:
470			pc += (A >= pc->k) ? pc->jt : pc->jf;
471			continue;
472
473		case BPF_JMP|BPF_JEQ|BPF_K:
474			pc += (A == pc->k) ? pc->jt : pc->jf;
475			continue;
476
477		case BPF_JMP|BPF_JSET|BPF_K:
478			pc += (A & pc->k) ? pc->jt : pc->jf;
479			continue;
480
481		case BPF_JMP|BPF_JGT|BPF_X:
482			pc += (A > X) ? pc->jt : pc->jf;
483			continue;
484
485		case BPF_JMP|BPF_JGE|BPF_X:
486			pc += (A >= X) ? pc->jt : pc->jf;
487			continue;
488
489		case BPF_JMP|BPF_JEQ|BPF_X:
490			pc += (A == X) ? pc->jt : pc->jf;
491			continue;
492
493		case BPF_JMP|BPF_JSET|BPF_X:
494			pc += (A & X) ? pc->jt : pc->jf;
495			continue;
496
497		case BPF_ALU|BPF_ADD|BPF_X:
498			A += X;
499			continue;
500
501		case BPF_ALU|BPF_SUB|BPF_X:
502			A -= X;
503			continue;
504
505		case BPF_ALU|BPF_MUL|BPF_X:
506			A *= X;
507			continue;
508
509		case BPF_ALU|BPF_DIV|BPF_X:
510			if (X == 0)
511				return 0;
512			A /= X;
513			continue;
514
515		case BPF_ALU|BPF_MOD|BPF_X:
516			if (X == 0)
517				return 0;
518			A %= X;
519			continue;
520
521		case BPF_ALU|BPF_AND|BPF_X:
522			A &= X;
523			continue;
524
525		case BPF_ALU|BPF_OR|BPF_X:
526			A |= X;
527			continue;
528
529		case BPF_ALU|BPF_XOR|BPF_X:
530			A ^= X;
531			continue;
532
533		case BPF_ALU|BPF_LSH|BPF_X:
534			A <<= X;
535			continue;
536
537		case BPF_ALU|BPF_RSH|BPF_X:
538			A >>= X;
539			continue;
540
541		case BPF_ALU|BPF_ADD|BPF_K:
542			A += pc->k;
543			continue;
544
545		case BPF_ALU|BPF_SUB|BPF_K:
546			A -= pc->k;
547			continue;
548
549		case BPF_ALU|BPF_MUL|BPF_K:
550			A *= pc->k;
551			continue;
552
553		case BPF_ALU|BPF_DIV|BPF_K:
554			A /= pc->k;
555			continue;
556
557		case BPF_ALU|BPF_MOD|BPF_K:
558			A %= pc->k;
559			continue;
560
561		case BPF_ALU|BPF_AND|BPF_K:
562			A &= pc->k;
563			continue;
564
565		case BPF_ALU|BPF_OR|BPF_K:
566			A |= pc->k;
567			continue;
568
569		case BPF_ALU|BPF_XOR|BPF_K:
570			A ^= pc->k;
571			continue;
572
573		case BPF_ALU|BPF_LSH|BPF_K:
574			A <<= pc->k;
575			continue;
576
577		case BPF_ALU|BPF_RSH|BPF_K:
578			A >>= pc->k;
579			continue;
580
581		case BPF_ALU|BPF_NEG:
582			/*
583			 * Most BPF arithmetic is unsigned, but negation
584			 * can't be unsigned; throw some casts to
585			 * specify what we're trying to do.
586			 */
587			A = (u_int32)(-(int32)A);
588			continue;
589
590		case BPF_MISC|BPF_TAX:
591			X = A;
592			continue;
593
594		case BPF_MISC|BPF_TXA:
595			A = X;
596			continue;
597		}
598	}
599}
600
601u_int
602bpf_filter(pc, p, wirelen, buflen)
603	register const struct bpf_insn *pc;
604	register const u_char *p;
605	u_int wirelen;
606	register u_int buflen;
607{
608	return bpf_filter_with_aux_data(pc, p, wirelen, buflen, NULL);
609}
610
611
612/*
613 * Return true if the 'fcode' is a valid filter program.
614 * The constraints are that each jump be forward and to a valid
615 * code, that memory accesses are within valid ranges (to the
616 * extent that this can be checked statically; loads of packet
617 * data have to be, and are, also checked at run time), and that
618 * the code terminates with either an accept or reject.
619 *
620 * The kernel needs to be able to verify an application's filter code.
621 * Otherwise, a bogus program could easily crash the system.
622 */
623int
624bpf_validate(f, len)
625	const struct bpf_insn *f;
626	int len;
627{
628	u_int i, from;
629	const struct bpf_insn *p;
630
631	if (len < 1)
632		return 0;
633	/*
634	 * There's no maximum program length in userland.
635	 */
636#if defined(KERNEL) || defined(_KERNEL)
637	if (len > BPF_MAXINSNS)
638		return 0;
639#endif
640
641	for (i = 0; i < (u_int)len; ++i) {
642		p = &f[i];
643		switch (BPF_CLASS(p->code)) {
644		/*
645		 * Check that memory operations use valid addresses.
646		 */
647		case BPF_LD:
648		case BPF_LDX:
649			switch (BPF_MODE(p->code)) {
650			case BPF_IMM:
651				break;
652			case BPF_ABS:
653			case BPF_IND:
654			case BPF_MSH:
655				/*
656				 * There's no maximum packet data size
657				 * in userland.  The runtime packet length
658				 * check suffices.
659				 */
660#if defined(KERNEL) || defined(_KERNEL)
661				/*
662				 * More strict check with actual packet length
663				 * is done runtime.
664				 */
665				if (p->k >= bpf_maxbufsize)
666					return 0;
667#endif
668				break;
669			case BPF_MEM:
670				if (p->k >= BPF_MEMWORDS)
671					return 0;
672				break;
673			case BPF_LEN:
674				break;
675			default:
676				return 0;
677			}
678			break;
679		case BPF_ST:
680		case BPF_STX:
681			if (p->k >= BPF_MEMWORDS)
682				return 0;
683			break;
684		case BPF_ALU:
685			switch (BPF_OP(p->code)) {
686			case BPF_ADD:
687			case BPF_SUB:
688			case BPF_MUL:
689			case BPF_OR:
690			case BPF_AND:
691			case BPF_XOR:
692			case BPF_LSH:
693			case BPF_RSH:
694			case BPF_NEG:
695				break;
696			case BPF_DIV:
697			case BPF_MOD:
698				/*
699				 * Check for constant division or modulus
700				 * by 0.
701				 */
702				if (BPF_SRC(p->code) == BPF_K && p->k == 0)
703					return 0;
704				break;
705			default:
706				return 0;
707			}
708			break;
709		case BPF_JMP:
710			/*
711			 * Check that jumps are within the code block,
712			 * and that unconditional branches don't go
713			 * backwards as a result of an overflow.
714			 * Unconditional branches have a 32-bit offset,
715			 * so they could overflow; we check to make
716			 * sure they don't.  Conditional branches have
717			 * an 8-bit offset, and the from address is <=
718			 * BPF_MAXINSNS, and we assume that BPF_MAXINSNS
719			 * is sufficiently small that adding 255 to it
720			 * won't overflow.
721			 *
722			 * We know that len is <= BPF_MAXINSNS, and we
723			 * assume that BPF_MAXINSNS is < the maximum size
724			 * of a u_int, so that i + 1 doesn't overflow.
725			 *
726			 * For userland, we don't know that the from
727			 * or len are <= BPF_MAXINSNS, but we know that
728			 * from <= len, and, except on a 64-bit system,
729			 * it's unlikely that len, if it truly reflects
730			 * the size of the program we've been handed,
731			 * will be anywhere near the maximum size of
732			 * a u_int.  We also don't check for backward
733			 * branches, as we currently support them in
734			 * userland for the protochain operation.
735			 */
736			from = i + 1;
737			switch (BPF_OP(p->code)) {
738			case BPF_JA:
739#if defined(KERNEL) || defined(_KERNEL)
740				if (from + p->k < from || from + p->k >= len)
741#else
742				if (from + p->k >= (u_int)len)
743#endif
744					return 0;
745				break;
746			case BPF_JEQ:
747			case BPF_JGT:
748			case BPF_JGE:
749			case BPF_JSET:
750				if (from + p->jt >= (u_int)len || from + p->jf >= (u_int)len)
751					return 0;
752				break;
753			default:
754				return 0;
755			}
756			break;
757		case BPF_RET:
758			break;
759		case BPF_MISC:
760			break;
761		default:
762			return 0;
763		}
764	}
765	return BPF_CLASS(f[len - 1].code) == BPF_RET;
766}
767