xref: /freebsd/sys/netpfil/pf/pf_norm.c (revision 28f42739a547ffe0b5dfaaf9f49fb4c4813aa232)
1 /*-
2  * Copyright 2001 Niels Provos <provos@citi.umich.edu>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  *
25  *	$OpenBSD: pf_norm.c,v 1.114 2009/01/29 14:11:45 henning Exp $
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_pf.h"
34 
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.h>
38 #include <sys/mbuf.h>
39 #include <sys/mutex.h>
40 #include <sys/refcount.h>
41 #include <sys/rwlock.h>
42 #include <sys/socket.h>
43 
44 #include <net/if.h>
45 #include <net/vnet.h>
46 #include <net/pfvar.h>
47 #include <net/if_pflog.h>
48 
49 #include <netinet/in.h>
50 #include <netinet/ip.h>
51 #include <netinet/ip_var.h>
52 #include <netinet/tcp.h>
53 #include <netinet/tcp_fsm.h>
54 #include <netinet/tcp_seq.h>
55 
56 #ifdef INET6
57 #include <netinet/ip6.h>
58 #endif /* INET6 */
59 
60 struct pf_frent {
61 	LIST_ENTRY(pf_frent) fr_next;
62 	union {
63 		struct {
64 			struct ip *_fr_ip;
65 			struct mbuf *_fr_m;
66 		} _frag;
67 		struct {
68 			uint16_t _fr_off;
69 			uint16_t _fr_end;
70 		} _cache;
71 	} _u;
72 };
73 #define	fr_ip	_u._frag._fr_ip
74 #define	fr_m	_u._frag._fr_m
75 #define	fr_off	_u._cache._fr_off
76 #define	fr_end	_u._cache._fr_end
77 
78 struct pf_fragment {
79 	RB_ENTRY(pf_fragment) fr_entry;
80 	TAILQ_ENTRY(pf_fragment) frag_next;
81 	struct in_addr	fr_src;
82 	struct in_addr	fr_dst;
83 	u_int8_t	fr_p;		/* protocol of this fragment */
84 	u_int8_t	fr_flags;	/* status flags */
85 #define PFFRAG_SEENLAST	0x0001		/* Seen the last fragment for this */
86 #define PFFRAG_NOBUFFER	0x0002		/* Non-buffering fragment cache */
87 #define PFFRAG_DROP	0x0004		/* Drop all fragments */
88 #define BUFFER_FRAGMENTS(fr)	(!((fr)->fr_flags & PFFRAG_NOBUFFER))
89 	u_int16_t	fr_id;		/* fragment id for reassemble */
90 	u_int16_t	fr_max;		/* fragment data max */
91 	u_int32_t	fr_timeout;
92 	LIST_HEAD(, pf_frent) fr_queue;
93 };
94 
95 static struct mtx pf_frag_mtx;
96 MTX_SYSINIT(pf_frag_mtx, &pf_frag_mtx, "pf fragments", MTX_DEF);
97 #define PF_FRAG_LOCK()		mtx_lock(&pf_frag_mtx)
98 #define PF_FRAG_UNLOCK()	mtx_unlock(&pf_frag_mtx)
99 #define PF_FRAG_ASSERT()	mtx_assert(&pf_frag_mtx, MA_OWNED)
100 
101 VNET_DEFINE(uma_zone_t, pf_state_scrub_z);	/* XXX: shared with pfsync */
102 
103 static VNET_DEFINE(uma_zone_t, pf_frent_z);
104 #define	V_pf_frent_z	VNET(pf_frent_z)
105 static VNET_DEFINE(uma_zone_t, pf_frag_z);
106 #define	V_pf_frag_z	VNET(pf_frag_z)
107 
108 TAILQ_HEAD(pf_fragqueue, pf_fragment);
109 TAILQ_HEAD(pf_cachequeue, pf_fragment);
110 static VNET_DEFINE(struct pf_fragqueue,	pf_fragqueue);
111 #define	V_pf_fragqueue			VNET(pf_fragqueue)
112 static VNET_DEFINE(struct pf_cachequeue,	pf_cachequeue);
113 #define	V_pf_cachequeue			VNET(pf_cachequeue)
114 RB_HEAD(pf_frag_tree, pf_fragment);
115 static VNET_DEFINE(struct pf_frag_tree,	pf_frag_tree);
116 #define	V_pf_frag_tree			VNET(pf_frag_tree)
117 static VNET_DEFINE(struct pf_frag_tree,	pf_cache_tree);
118 #define	V_pf_cache_tree			VNET(pf_cache_tree)
119 static int		 pf_frag_compare(struct pf_fragment *,
120 			    struct pf_fragment *);
121 static RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
122 static RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
123 
124 /* Private prototypes */
125 static void		 pf_free_fragment(struct pf_fragment *);
126 static void		 pf_remove_fragment(struct pf_fragment *);
127 static int		 pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
128 			    struct tcphdr *, int, sa_family_t);
129 #ifdef INET
130 static void		 pf_ip2key(struct pf_fragment *, struct ip *);
131 static void		 pf_scrub_ip(struct mbuf **, u_int32_t, u_int8_t,
132 			    u_int8_t);
133 static void		 pf_flush_fragments(void);
134 static struct pf_fragment *pf_find_fragment(struct ip *, struct pf_frag_tree *);
135 static struct mbuf	*pf_reassemble(struct mbuf **, struct pf_fragment **,
136 			    struct pf_frent *, int);
137 static struct mbuf	*pf_fragcache(struct mbuf **, struct ip*,
138 			    struct pf_fragment **, int, int, int *);
139 #endif /* INET */
140 #ifdef INET6
141 static void		 pf_scrub_ip6(struct mbuf **, u_int8_t);
142 #endif
143 #define	DPFPRINTF(x) do {				\
144 	if (V_pf_status.debug >= PF_DEBUG_MISC) {	\
145 		printf("%s: ", __func__);		\
146 		printf x ;				\
147 	}						\
148 } while(0)
149 
150 void
151 pf_vnet_normalize_init(void)
152 {
153 
154 	V_pf_frag_z = uma_zcreate("pf frags", sizeof(struct pf_fragment),
155 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
156 	V_pf_frent_z = uma_zcreate("pf frag entries", sizeof(struct pf_frent),
157 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
158 	V_pf_state_scrub_z = uma_zcreate("pf state scrubs",
159 	    sizeof(struct pf_state_scrub),  NULL, NULL, NULL, NULL,
160 	    UMA_ALIGN_PTR, 0);
161 
162 	V_pf_limits[PF_LIMIT_FRAGS].zone = V_pf_frent_z;
163 	V_pf_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT;
164 	uma_zone_set_max(V_pf_frent_z, PFFRAG_FRENT_HIWAT);
165 	uma_zone_set_warning(V_pf_frent_z, "PF frag entries limit reached");
166 	TAILQ_INIT(&V_pf_fragqueue);
167 	TAILQ_INIT(&V_pf_cachequeue);
168 }
169 
170 void
171 pf_normalize_cleanup(void)
172 {
173 
174 	uma_zdestroy(V_pf_state_scrub_z);
175 	uma_zdestroy(V_pf_frent_z);
176 	uma_zdestroy(V_pf_frag_z);
177 }
178 
179 static int
180 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
181 {
182 	int	diff;
183 
184 	if ((diff = a->fr_id - b->fr_id))
185 		return (diff);
186 	else if ((diff = a->fr_p - b->fr_p))
187 		return (diff);
188 	else if (a->fr_src.s_addr < b->fr_src.s_addr)
189 		return (-1);
190 	else if (a->fr_src.s_addr > b->fr_src.s_addr)
191 		return (1);
192 	else if (a->fr_dst.s_addr < b->fr_dst.s_addr)
193 		return (-1);
194 	else if (a->fr_dst.s_addr > b->fr_dst.s_addr)
195 		return (1);
196 	return (0);
197 }
198 
199 void
200 pf_purge_expired_fragments(void)
201 {
202 	struct pf_fragment	*frag;
203 	u_int32_t		 expire = time_uptime -
204 				    V_pf_default_rule.timeout[PFTM_FRAG];
205 
206 	PF_FRAG_LOCK();
207 	while ((frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue)) != NULL) {
208 		KASSERT((BUFFER_FRAGMENTS(frag)),
209 		    ("BUFFER_FRAGMENTS(frag) == 0: %s", __FUNCTION__));
210 		if (frag->fr_timeout > expire)
211 			break;
212 
213 		DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
214 		pf_free_fragment(frag);
215 	}
216 
217 	while ((frag = TAILQ_LAST(&V_pf_cachequeue, pf_cachequeue)) != NULL) {
218 		KASSERT((!BUFFER_FRAGMENTS(frag)),
219 		    ("BUFFER_FRAGMENTS(frag) != 0: %s", __FUNCTION__));
220 		if (frag->fr_timeout > expire)
221 			break;
222 
223 		DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
224 		pf_free_fragment(frag);
225 		KASSERT((TAILQ_EMPTY(&V_pf_cachequeue) ||
226 		    TAILQ_LAST(&V_pf_cachequeue, pf_cachequeue) != frag),
227 		    ("!(TAILQ_EMPTY() || TAILQ_LAST() == farg): %s",
228 		    __FUNCTION__));
229 	}
230 	PF_FRAG_UNLOCK();
231 }
232 
233 #ifdef INET
234 /*
235  * Try to flush old fragments to make space for new ones
236  */
237 static void
238 pf_flush_fragments(void)
239 {
240 	struct pf_fragment	*frag, *cache;
241 	int			 goal;
242 
243 	PF_FRAG_ASSERT();
244 
245 	goal = uma_zone_get_cur(V_pf_frent_z) * 9 / 10;
246 	DPFPRINTF(("trying to free %d frag entriess\n", goal));
247 	while (goal < uma_zone_get_cur(V_pf_frent_z)) {
248 		frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue);
249 		if (frag)
250 			pf_free_fragment(frag);
251 		cache = TAILQ_LAST(&V_pf_cachequeue, pf_cachequeue);
252 		if (cache)
253 			pf_free_fragment(cache);
254 		if (frag == NULL && cache == NULL)
255 			break;
256 	}
257 }
258 #endif /* INET */
259 
260 /* Frees the fragments and all associated entries */
261 static void
262 pf_free_fragment(struct pf_fragment *frag)
263 {
264 	struct pf_frent		*frent;
265 
266 	PF_FRAG_ASSERT();
267 
268 	/* Free all fragments */
269 	if (BUFFER_FRAGMENTS(frag)) {
270 		for (frent = LIST_FIRST(&frag->fr_queue); frent;
271 		    frent = LIST_FIRST(&frag->fr_queue)) {
272 			LIST_REMOVE(frent, fr_next);
273 
274 			m_freem(frent->fr_m);
275 			uma_zfree(V_pf_frent_z, frent);
276 		}
277 	} else {
278 		for (frent = LIST_FIRST(&frag->fr_queue); frent;
279 		    frent = LIST_FIRST(&frag->fr_queue)) {
280 			LIST_REMOVE(frent, fr_next);
281 
282 			KASSERT((LIST_EMPTY(&frag->fr_queue) ||
283 			    LIST_FIRST(&frag->fr_queue)->fr_off >
284 			    frent->fr_end),
285 			    ("! (LIST_EMPTY() || LIST_FIRST()->fr_off >"
286 			    " frent->fr_end): %s", __func__));
287 
288 			uma_zfree(V_pf_frent_z, frent);
289 		}
290 	}
291 
292 	pf_remove_fragment(frag);
293 }
294 
295 #ifdef INET
296 static void
297 pf_ip2key(struct pf_fragment *key, struct ip *ip)
298 {
299 	key->fr_p = ip->ip_p;
300 	key->fr_id = ip->ip_id;
301 	key->fr_src.s_addr = ip->ip_src.s_addr;
302 	key->fr_dst.s_addr = ip->ip_dst.s_addr;
303 }
304 
305 static struct pf_fragment *
306 pf_find_fragment(struct ip *ip, struct pf_frag_tree *tree)
307 {
308 	struct pf_fragment	 key;
309 	struct pf_fragment	*frag;
310 
311 	PF_FRAG_ASSERT();
312 
313 	pf_ip2key(&key, ip);
314 
315 	frag = RB_FIND(pf_frag_tree, tree, &key);
316 	if (frag != NULL) {
317 		/* XXX Are we sure we want to update the timeout? */
318 		frag->fr_timeout = time_uptime;
319 		if (BUFFER_FRAGMENTS(frag)) {
320 			TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
321 			TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
322 		} else {
323 			TAILQ_REMOVE(&V_pf_cachequeue, frag, frag_next);
324 			TAILQ_INSERT_HEAD(&V_pf_cachequeue, frag, frag_next);
325 		}
326 	}
327 
328 	return (frag);
329 }
330 #endif /* INET */
331 
332 /* Removes a fragment from the fragment queue and frees the fragment */
333 
334 static void
335 pf_remove_fragment(struct pf_fragment *frag)
336 {
337 
338 	PF_FRAG_ASSERT();
339 
340 	if (BUFFER_FRAGMENTS(frag)) {
341 		RB_REMOVE(pf_frag_tree, &V_pf_frag_tree, frag);
342 		TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
343 		uma_zfree(V_pf_frag_z, frag);
344 	} else {
345 		RB_REMOVE(pf_frag_tree, &V_pf_cache_tree, frag);
346 		TAILQ_REMOVE(&V_pf_cachequeue, frag, frag_next);
347 		uma_zfree(V_pf_frag_z, frag);
348 	}
349 }
350 
351 #ifdef INET
352 #define FR_IP_OFF(fr)	((ntohs((fr)->fr_ip->ip_off) & IP_OFFMASK) << 3)
353 static struct mbuf *
354 pf_reassemble(struct mbuf **m0, struct pf_fragment **frag,
355     struct pf_frent *frent, int mff)
356 {
357 	struct mbuf	*m = *m0, *m2;
358 	struct pf_frent	*frea, *next;
359 	struct pf_frent	*frep = NULL;
360 	struct ip	*ip = frent->fr_ip;
361 	int		 hlen = ip->ip_hl << 2;
362 	u_int16_t	 off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
363 	u_int16_t	 ip_len = ntohs(ip->ip_len) - ip->ip_hl * 4;
364 	u_int16_t	 max = ip_len + off;
365 
366 	PF_FRAG_ASSERT();
367 	KASSERT((*frag == NULL || BUFFER_FRAGMENTS(*frag)),
368 	    ("! (*frag == NULL || BUFFER_FRAGMENTS(*frag)): %s", __FUNCTION__));
369 
370 	/* Strip off ip header */
371 	m->m_data += hlen;
372 	m->m_len -= hlen;
373 
374 	/* Create a new reassembly queue for this packet */
375 	if (*frag == NULL) {
376 		*frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
377 		if (*frag == NULL) {
378 			pf_flush_fragments();
379 			*frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
380 			if (*frag == NULL)
381 				goto drop_fragment;
382 		}
383 
384 		(*frag)->fr_flags = 0;
385 		(*frag)->fr_max = 0;
386 		(*frag)->fr_src = frent->fr_ip->ip_src;
387 		(*frag)->fr_dst = frent->fr_ip->ip_dst;
388 		(*frag)->fr_p = frent->fr_ip->ip_p;
389 		(*frag)->fr_id = frent->fr_ip->ip_id;
390 		(*frag)->fr_timeout = time_uptime;
391 		LIST_INIT(&(*frag)->fr_queue);
392 
393 		RB_INSERT(pf_frag_tree, &V_pf_frag_tree, *frag);
394 		TAILQ_INSERT_HEAD(&V_pf_fragqueue, *frag, frag_next);
395 
396 		/* We do not have a previous fragment */
397 		frep = NULL;
398 		goto insert;
399 	}
400 
401 	/*
402 	 * Find a fragment after the current one:
403 	 *  - off contains the real shifted offset.
404 	 */
405 	LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
406 		if (FR_IP_OFF(frea) > off)
407 			break;
408 		frep = frea;
409 	}
410 
411 	KASSERT((frep != NULL || frea != NULL),
412 	    ("!(frep != NULL || frea != NULL): %s", __FUNCTION__));;
413 
414 	if (frep != NULL &&
415 	    FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl *
416 	    4 > off)
417 	{
418 		u_int16_t	precut;
419 
420 		precut = FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) -
421 		    frep->fr_ip->ip_hl * 4 - off;
422 		if (precut >= ip_len)
423 			goto drop_fragment;
424 		m_adj(frent->fr_m, precut);
425 		DPFPRINTF(("overlap -%d\n", precut));
426 		/* Enforce 8 byte boundaries */
427 		ip->ip_off = htons(ntohs(ip->ip_off) + (precut >> 3));
428 		off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
429 		ip_len -= precut;
430 		ip->ip_len = htons(ip_len);
431 	}
432 
433 	for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
434 	    frea = next)
435 	{
436 		u_int16_t	aftercut;
437 
438 		aftercut = ip_len + off - FR_IP_OFF(frea);
439 		DPFPRINTF(("adjust overlap %d\n", aftercut));
440 		if (aftercut < ntohs(frea->fr_ip->ip_len) - frea->fr_ip->ip_hl
441 		    * 4)
442 		{
443 			frea->fr_ip->ip_len =
444 			    htons(ntohs(frea->fr_ip->ip_len) - aftercut);
445 			frea->fr_ip->ip_off = htons(ntohs(frea->fr_ip->ip_off) +
446 			    (aftercut >> 3));
447 			m_adj(frea->fr_m, aftercut);
448 			break;
449 		}
450 
451 		/* This fragment is completely overlapped, lose it */
452 		next = LIST_NEXT(frea, fr_next);
453 		m_freem(frea->fr_m);
454 		LIST_REMOVE(frea, fr_next);
455 		uma_zfree(V_pf_frent_z, frea);
456 	}
457 
458  insert:
459 	/* Update maximum data size */
460 	if ((*frag)->fr_max < max)
461 		(*frag)->fr_max = max;
462 	/* This is the last segment */
463 	if (!mff)
464 		(*frag)->fr_flags |= PFFRAG_SEENLAST;
465 
466 	if (frep == NULL)
467 		LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
468 	else
469 		LIST_INSERT_AFTER(frep, frent, fr_next);
470 
471 	/* Check if we are completely reassembled */
472 	if (!((*frag)->fr_flags & PFFRAG_SEENLAST))
473 		return (NULL);
474 
475 	/* Check if we have all the data */
476 	off = 0;
477 	for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
478 		next = LIST_NEXT(frep, fr_next);
479 
480 		off += ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl * 4;
481 		if (off < (*frag)->fr_max &&
482 		    (next == NULL || FR_IP_OFF(next) != off))
483 		{
484 			DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
485 			    off, next == NULL ? -1 : FR_IP_OFF(next),
486 			    (*frag)->fr_max));
487 			return (NULL);
488 		}
489 	}
490 	DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
491 	if (off < (*frag)->fr_max)
492 		return (NULL);
493 
494 	/* We have all the data */
495 	frent = LIST_FIRST(&(*frag)->fr_queue);
496 	KASSERT((frent != NULL), ("frent == NULL: %s", __FUNCTION__));
497 	if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
498 		DPFPRINTF(("drop: too big: %d\n", off));
499 		pf_free_fragment(*frag);
500 		*frag = NULL;
501 		return (NULL);
502 	}
503 	next = LIST_NEXT(frent, fr_next);
504 
505 	/* Magic from ip_input */
506 	ip = frent->fr_ip;
507 	m = frent->fr_m;
508 	m2 = m->m_next;
509 	m->m_next = NULL;
510 	m_cat(m, m2);
511 	uma_zfree(V_pf_frent_z, frent);
512 	for (frent = next; frent != NULL; frent = next) {
513 		next = LIST_NEXT(frent, fr_next);
514 
515 		m2 = frent->fr_m;
516 		uma_zfree(V_pf_frent_z, frent);
517 		m->m_pkthdr.csum_flags &= m2->m_pkthdr.csum_flags;
518 		m->m_pkthdr.csum_data += m2->m_pkthdr.csum_data;
519 		m_cat(m, m2);
520 	}
521 
522 	while (m->m_pkthdr.csum_data & 0xffff0000)
523 		m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
524 		    (m->m_pkthdr.csum_data >> 16);
525 	ip->ip_src = (*frag)->fr_src;
526 	ip->ip_dst = (*frag)->fr_dst;
527 
528 	/* Remove from fragment queue */
529 	pf_remove_fragment(*frag);
530 	*frag = NULL;
531 
532 	hlen = ip->ip_hl << 2;
533 	ip->ip_len = htons(off + hlen);
534 	m->m_len += hlen;
535 	m->m_data -= hlen;
536 
537 	/* some debugging cruft by sklower, below, will go away soon */
538 	/* XXX this should be done elsewhere */
539 	if (m->m_flags & M_PKTHDR) {
540 		int plen = 0;
541 		for (m2 = m; m2; m2 = m2->m_next)
542 			plen += m2->m_len;
543 		m->m_pkthdr.len = plen;
544 	}
545 
546 	DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip->ip_len)));
547 	return (m);
548 
549  drop_fragment:
550 	/* Oops - fail safe - drop packet */
551 	uma_zfree(V_pf_frent_z, frent);
552 	m_freem(m);
553 	return (NULL);
554 }
555 
556 static struct mbuf *
557 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
558     int drop, int *nomem)
559 {
560 	struct mbuf		*m = *m0;
561 	struct pf_frent		*frp, *fra, *cur = NULL;
562 	int			 ip_len = ntohs(h->ip_len) - (h->ip_hl << 2);
563 	u_int16_t		 off = ntohs(h->ip_off) << 3;
564 	u_int16_t		 max = ip_len + off;
565 	int			 hosed = 0;
566 
567 	PF_FRAG_ASSERT();
568 	KASSERT((*frag == NULL || !BUFFER_FRAGMENTS(*frag)),
569 	    ("!(*frag == NULL || !BUFFER_FRAGMENTS(*frag)): %s", __FUNCTION__));
570 
571 	/* Create a new range queue for this packet */
572 	if (*frag == NULL) {
573 		*frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
574 		if (*frag == NULL) {
575 			pf_flush_fragments();
576 			*frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
577 			if (*frag == NULL)
578 				goto no_mem;
579 		}
580 
581 		/* Get an entry for the queue */
582 		cur = uma_zalloc(V_pf_frent_z, M_NOWAIT);
583 		if (cur == NULL) {
584 			uma_zfree(V_pf_frag_z, *frag);
585 			*frag = NULL;
586 			goto no_mem;
587 		}
588 
589 		(*frag)->fr_flags = PFFRAG_NOBUFFER;
590 		(*frag)->fr_max = 0;
591 		(*frag)->fr_src = h->ip_src;
592 		(*frag)->fr_dst = h->ip_dst;
593 		(*frag)->fr_p = h->ip_p;
594 		(*frag)->fr_id = h->ip_id;
595 		(*frag)->fr_timeout = time_uptime;
596 
597 		cur->fr_off = off;
598 		cur->fr_end = max;
599 		LIST_INIT(&(*frag)->fr_queue);
600 		LIST_INSERT_HEAD(&(*frag)->fr_queue, cur, fr_next);
601 
602 		RB_INSERT(pf_frag_tree, &V_pf_cache_tree, *frag);
603 		TAILQ_INSERT_HEAD(&V_pf_cachequeue, *frag, frag_next);
604 
605 		DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off, max));
606 
607 		goto pass;
608 	}
609 
610 	/*
611 	 * Find a fragment after the current one:
612 	 *  - off contains the real shifted offset.
613 	 */
614 	frp = NULL;
615 	LIST_FOREACH(fra, &(*frag)->fr_queue, fr_next) {
616 		if (fra->fr_off > off)
617 			break;
618 		frp = fra;
619 	}
620 
621 	KASSERT((frp != NULL || fra != NULL),
622 	    ("!(frp != NULL || fra != NULL): %s", __FUNCTION__));
623 
624 	if (frp != NULL) {
625 		int	precut;
626 
627 		precut = frp->fr_end - off;
628 		if (precut >= ip_len) {
629 			/* Fragment is entirely a duplicate */
630 			DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
631 			    h->ip_id, frp->fr_off, frp->fr_end, off, max));
632 			goto drop_fragment;
633 		}
634 		if (precut == 0) {
635 			/* They are adjacent.  Fixup cache entry */
636 			DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
637 			    h->ip_id, frp->fr_off, frp->fr_end, off, max));
638 			frp->fr_end = max;
639 		} else if (precut > 0) {
640 			/* The first part of this payload overlaps with a
641 			 * fragment that has already been passed.
642 			 * Need to trim off the first part of the payload.
643 			 * But to do so easily, we need to create another
644 			 * mbuf to throw the original header into.
645 			 */
646 
647 			DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
648 			    h->ip_id, precut, frp->fr_off, frp->fr_end, off,
649 			    max));
650 
651 			off += precut;
652 			max -= precut;
653 			/* Update the previous frag to encompass this one */
654 			frp->fr_end = max;
655 
656 			if (!drop) {
657 				/* XXX Optimization opportunity
658 				 * This is a very heavy way to trim the payload.
659 				 * we could do it much faster by diddling mbuf
660 				 * internals but that would be even less legible
661 				 * than this mbuf magic.  For my next trick,
662 				 * I'll pull a rabbit out of my laptop.
663 				 */
664 				*m0 = m_dup(m, M_NOWAIT);
665 				if (*m0 == NULL)
666 					goto no_mem;
667 				/* From KAME Project : We have missed this! */
668 				m_adj(*m0, (h->ip_hl << 2) -
669 				    (*m0)->m_pkthdr.len);
670 
671 				KASSERT(((*m0)->m_next == NULL),
672 				    ("(*m0)->m_next != NULL: %s",
673 				    __FUNCTION__));
674 				m_adj(m, precut + (h->ip_hl << 2));
675 				m_cat(*m0, m);
676 				m = *m0;
677 				if (m->m_flags & M_PKTHDR) {
678 					int plen = 0;
679 					struct mbuf *t;
680 					for (t = m; t; t = t->m_next)
681 						plen += t->m_len;
682 					m->m_pkthdr.len = plen;
683 				}
684 
685 
686 				h = mtod(m, struct ip *);
687 
688 				KASSERT(((int)m->m_len ==
689 				    ntohs(h->ip_len) - precut),
690 				    ("m->m_len != ntohs(h->ip_len) - precut: %s",
691 				    __FUNCTION__));
692 				h->ip_off = htons(ntohs(h->ip_off) +
693 				    (precut >> 3));
694 				h->ip_len = htons(ntohs(h->ip_len) - precut);
695 			} else {
696 				hosed++;
697 			}
698 		} else {
699 			/* There is a gap between fragments */
700 
701 			DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
702 			    h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
703 			    max));
704 
705 			cur = uma_zalloc(V_pf_frent_z, M_NOWAIT);
706 			if (cur == NULL)
707 				goto no_mem;
708 
709 			cur->fr_off = off;
710 			cur->fr_end = max;
711 			LIST_INSERT_AFTER(frp, cur, fr_next);
712 		}
713 	}
714 
715 	if (fra != NULL) {
716 		int	aftercut;
717 		int	merge = 0;
718 
719 		aftercut = max - fra->fr_off;
720 		if (aftercut == 0) {
721 			/* Adjacent fragments */
722 			DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
723 			    h->ip_id, off, max, fra->fr_off, fra->fr_end));
724 			fra->fr_off = off;
725 			merge = 1;
726 		} else if (aftercut > 0) {
727 			/* Need to chop off the tail of this fragment */
728 			DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
729 			    h->ip_id, aftercut, off, max, fra->fr_off,
730 			    fra->fr_end));
731 			fra->fr_off = off;
732 			max -= aftercut;
733 
734 			merge = 1;
735 
736 			if (!drop) {
737 				m_adj(m, -aftercut);
738 				if (m->m_flags & M_PKTHDR) {
739 					int plen = 0;
740 					struct mbuf *t;
741 					for (t = m; t; t = t->m_next)
742 						plen += t->m_len;
743 					m->m_pkthdr.len = plen;
744 				}
745 				h = mtod(m, struct ip *);
746 				KASSERT(((int)m->m_len == ntohs(h->ip_len) - aftercut),
747 				    ("m->m_len != ntohs(h->ip_len) - aftercut: %s",
748 				    __FUNCTION__));
749 				h->ip_len = htons(ntohs(h->ip_len) - aftercut);
750 			} else {
751 				hosed++;
752 			}
753 		} else if (frp == NULL) {
754 			/* There is a gap between fragments */
755 			DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
756 			    h->ip_id, -aftercut, off, max, fra->fr_off,
757 			    fra->fr_end));
758 
759 			cur = uma_zalloc(V_pf_frent_z, M_NOWAIT);
760 			if (cur == NULL)
761 				goto no_mem;
762 
763 			cur->fr_off = off;
764 			cur->fr_end = max;
765 			LIST_INSERT_BEFORE(fra, cur, fr_next);
766 		}
767 
768 
769 		/* Need to glue together two separate fragment descriptors */
770 		if (merge) {
771 			if (cur && fra->fr_off <= cur->fr_end) {
772 				/* Need to merge in a previous 'cur' */
773 				DPFPRINTF(("fragcache[%d]: adjacent(merge "
774 				    "%d-%d) %d-%d (%d-%d)\n",
775 				    h->ip_id, cur->fr_off, cur->fr_end, off,
776 				    max, fra->fr_off, fra->fr_end));
777 				fra->fr_off = cur->fr_off;
778 				LIST_REMOVE(cur, fr_next);
779 				uma_zfree(V_pf_frent_z, cur);
780 				cur = NULL;
781 
782 			} else if (frp && fra->fr_off <= frp->fr_end) {
783 				/* Need to merge in a modified 'frp' */
784 				KASSERT((cur == NULL), ("cur != NULL: %s",
785 				    __FUNCTION__));
786 				DPFPRINTF(("fragcache[%d]: adjacent(merge "
787 				    "%d-%d) %d-%d (%d-%d)\n",
788 				    h->ip_id, frp->fr_off, frp->fr_end, off,
789 				    max, fra->fr_off, fra->fr_end));
790 				fra->fr_off = frp->fr_off;
791 				LIST_REMOVE(frp, fr_next);
792 				uma_zfree(V_pf_frent_z, frp);
793 				frp = NULL;
794 
795 			}
796 		}
797 	}
798 
799 	if (hosed) {
800 		/*
801 		 * We must keep tracking the overall fragment even when
802 		 * we're going to drop it anyway so that we know when to
803 		 * free the overall descriptor.  Thus we drop the frag late.
804 		 */
805 		goto drop_fragment;
806 	}
807 
808 
809  pass:
810 	/* Update maximum data size */
811 	if ((*frag)->fr_max < max)
812 		(*frag)->fr_max = max;
813 
814 	/* This is the last segment */
815 	if (!mff)
816 		(*frag)->fr_flags |= PFFRAG_SEENLAST;
817 
818 	/* Check if we are completely reassembled */
819 	if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
820 	    LIST_FIRST(&(*frag)->fr_queue)->fr_off == 0 &&
821 	    LIST_FIRST(&(*frag)->fr_queue)->fr_end == (*frag)->fr_max) {
822 		/* Remove from fragment queue */
823 		DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
824 		    (*frag)->fr_max));
825 		pf_free_fragment(*frag);
826 		*frag = NULL;
827 	}
828 
829 	return (m);
830 
831  no_mem:
832 	*nomem = 1;
833 
834 	/* Still need to pay attention to !IP_MF */
835 	if (!mff && *frag != NULL)
836 		(*frag)->fr_flags |= PFFRAG_SEENLAST;
837 
838 	m_freem(m);
839 	return (NULL);
840 
841  drop_fragment:
842 
843 	/* Still need to pay attention to !IP_MF */
844 	if (!mff && *frag != NULL)
845 		(*frag)->fr_flags |= PFFRAG_SEENLAST;
846 
847 	if (drop) {
848 		/* This fragment has been deemed bad.  Don't reass */
849 		if (((*frag)->fr_flags & PFFRAG_DROP) == 0)
850 			DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
851 			    h->ip_id));
852 		(*frag)->fr_flags |= PFFRAG_DROP;
853 	}
854 
855 	m_freem(m);
856 	return (NULL);
857 }
858 
859 int
860 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
861     struct pf_pdesc *pd)
862 {
863 	struct mbuf		*m = *m0;
864 	struct pf_rule		*r;
865 	struct pf_frent		*frent;
866 	struct pf_fragment	*frag = NULL;
867 	struct ip		*h = mtod(m, struct ip *);
868 	int			 mff = (ntohs(h->ip_off) & IP_MF);
869 	int			 hlen = h->ip_hl << 2;
870 	u_int16_t		 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
871 	u_int16_t		 max;
872 	int			 ip_len;
873 	int			 ip_off;
874 	int			 tag = -1;
875 
876 	PF_RULES_RASSERT();
877 
878 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
879 	while (r != NULL) {
880 		r->evaluations++;
881 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
882 			r = r->skip[PF_SKIP_IFP].ptr;
883 		else if (r->direction && r->direction != dir)
884 			r = r->skip[PF_SKIP_DIR].ptr;
885 		else if (r->af && r->af != AF_INET)
886 			r = r->skip[PF_SKIP_AF].ptr;
887 		else if (r->proto && r->proto != h->ip_p)
888 			r = r->skip[PF_SKIP_PROTO].ptr;
889 		else if (PF_MISMATCHAW(&r->src.addr,
890 		    (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
891 		    r->src.neg, kif, M_GETFIB(m)))
892 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
893 		else if (PF_MISMATCHAW(&r->dst.addr,
894 		    (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
895 		    r->dst.neg, NULL, M_GETFIB(m)))
896 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
897 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
898 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
899 			r = TAILQ_NEXT(r, entries);
900 		else
901 			break;
902 	}
903 
904 	if (r == NULL || r->action == PF_NOSCRUB)
905 		return (PF_PASS);
906 	else {
907 		r->packets[dir == PF_OUT]++;
908 		r->bytes[dir == PF_OUT] += pd->tot_len;
909 	}
910 
911 	/* Check for illegal packets */
912 	if (hlen < (int)sizeof(struct ip))
913 		goto drop;
914 
915 	if (hlen > ntohs(h->ip_len))
916 		goto drop;
917 
918 	/* Clear IP_DF if the rule uses the no-df option */
919 	if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
920 		u_int16_t ip_off = h->ip_off;
921 
922 		h->ip_off &= htons(~IP_DF);
923 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
924 	}
925 
926 	/* We will need other tests here */
927 	if (!fragoff && !mff)
928 		goto no_fragment;
929 
930 	/* We're dealing with a fragment now. Don't allow fragments
931 	 * with IP_DF to enter the cache. If the flag was cleared by
932 	 * no-df above, fine. Otherwise drop it.
933 	 */
934 	if (h->ip_off & htons(IP_DF)) {
935 		DPFPRINTF(("IP_DF\n"));
936 		goto bad;
937 	}
938 
939 	ip_len = ntohs(h->ip_len) - hlen;
940 	ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
941 
942 	/* All fragments are 8 byte aligned */
943 	if (mff && (ip_len & 0x7)) {
944 		DPFPRINTF(("mff and %d\n", ip_len));
945 		goto bad;
946 	}
947 
948 	/* Respect maximum length */
949 	if (fragoff + ip_len > IP_MAXPACKET) {
950 		DPFPRINTF(("max packet %d\n", fragoff + ip_len));
951 		goto bad;
952 	}
953 	max = fragoff + ip_len;
954 
955 	if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
956 
957 		/* Fully buffer all of the fragments */
958 		PF_FRAG_LOCK();
959 		frag = pf_find_fragment(h, &V_pf_frag_tree);
960 
961 		/* Check if we saw the last fragment already */
962 		if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
963 		    max > frag->fr_max)
964 			goto bad;
965 
966 		/* Get an entry for the fragment queue */
967 		frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
968 		if (frent == NULL) {
969 			PF_FRAG_UNLOCK();
970 			REASON_SET(reason, PFRES_MEMORY);
971 			return (PF_DROP);
972 		}
973 		frent->fr_ip = h;
974 		frent->fr_m = m;
975 
976 		/* Might return a completely reassembled mbuf, or NULL */
977 		DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
978 		*m0 = m = pf_reassemble(m0, &frag, frent, mff);
979 		PF_FRAG_UNLOCK();
980 
981 		if (m == NULL)
982 			return (PF_DROP);
983 
984 		if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
985 			goto drop;
986 
987 		h = mtod(m, struct ip *);
988 	} else {
989 		/* non-buffering fragment cache (drops or masks overlaps) */
990 		int	nomem = 0;
991 
992 		if (dir == PF_OUT && pd->pf_mtag &&
993 		    pd->pf_mtag->flags & PF_TAG_FRAGCACHE) {
994 			/*
995 			 * Already passed the fragment cache in the
996 			 * input direction.  If we continued, it would
997 			 * appear to be a dup and would be dropped.
998 			 */
999 			goto fragment_pass;
1000 		}
1001 
1002 		PF_FRAG_LOCK();
1003 		frag = pf_find_fragment(h, &V_pf_cache_tree);
1004 
1005 		/* Check if we saw the last fragment already */
1006 		if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
1007 		    max > frag->fr_max) {
1008 			if (r->rule_flag & PFRULE_FRAGDROP)
1009 				frag->fr_flags |= PFFRAG_DROP;
1010 			goto bad;
1011 		}
1012 
1013 		*m0 = m = pf_fragcache(m0, h, &frag, mff,
1014 		    (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
1015 		PF_FRAG_UNLOCK();
1016 		if (m == NULL) {
1017 			if (nomem)
1018 				goto no_mem;
1019 			goto drop;
1020 		}
1021 
1022 		if (dir == PF_IN) {
1023 			/* Use mtag from copied and trimmed mbuf chain. */
1024 			pd->pf_mtag = pf_get_mtag(m);
1025 			if (pd->pf_mtag == NULL) {
1026 				m_freem(m);
1027 				*m0 = NULL;
1028 				goto no_mem;
1029 			}
1030 			pd->pf_mtag->flags |= PF_TAG_FRAGCACHE;
1031 		}
1032 
1033 		if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
1034 			goto drop;
1035 		goto fragment_pass;
1036 	}
1037 
1038  no_fragment:
1039 	/* At this point, only IP_DF is allowed in ip_off */
1040 	if (h->ip_off & ~htons(IP_DF)) {
1041 		u_int16_t ip_off = h->ip_off;
1042 
1043 		h->ip_off &= htons(IP_DF);
1044 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1045 	}
1046 
1047 	/* not missing a return here */
1048 
1049  fragment_pass:
1050 	pf_scrub_ip(&m, r->rule_flag, r->min_ttl, r->set_tos);
1051 
1052 	if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1053 		pd->flags |= PFDESC_IP_REAS;
1054 	return (PF_PASS);
1055 
1056  no_mem:
1057 	REASON_SET(reason, PFRES_MEMORY);
1058 	if (r != NULL && r->log)
1059 		PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
1060 		    1);
1061 	return (PF_DROP);
1062 
1063  drop:
1064 	REASON_SET(reason, PFRES_NORM);
1065 	if (r != NULL && r->log)
1066 		PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
1067 		    1);
1068 	return (PF_DROP);
1069 
1070  bad:
1071 	DPFPRINTF(("dropping bad fragment\n"));
1072 
1073 	/* Free associated fragments */
1074 	if (frag != NULL) {
1075 		pf_free_fragment(frag);
1076 		PF_FRAG_UNLOCK();
1077 	}
1078 
1079 	REASON_SET(reason, PFRES_FRAG);
1080 	if (r != NULL && r->log)
1081 		PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
1082 		    1);
1083 
1084 	return (PF_DROP);
1085 }
1086 #endif
1087 
1088 #ifdef INET6
1089 int
1090 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1091     u_short *reason, struct pf_pdesc *pd)
1092 {
1093 	struct mbuf		*m = *m0;
1094 	struct pf_rule		*r;
1095 	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
1096 	int			 off;
1097 	struct ip6_ext		 ext;
1098 	struct ip6_opt		 opt;
1099 	struct ip6_opt_jumbo	 jumbo;
1100 	struct ip6_frag		 frag;
1101 	u_int32_t		 jumbolen = 0, plen;
1102 	u_int16_t		 fragoff = 0;
1103 	int			 optend;
1104 	int			 ooff;
1105 	u_int8_t		 proto;
1106 	int			 terminal;
1107 
1108 	PF_RULES_RASSERT();
1109 
1110 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1111 	while (r != NULL) {
1112 		r->evaluations++;
1113 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
1114 			r = r->skip[PF_SKIP_IFP].ptr;
1115 		else if (r->direction && r->direction != dir)
1116 			r = r->skip[PF_SKIP_DIR].ptr;
1117 		else if (r->af && r->af != AF_INET6)
1118 			r = r->skip[PF_SKIP_AF].ptr;
1119 #if 0 /* header chain! */
1120 		else if (r->proto && r->proto != h->ip6_nxt)
1121 			r = r->skip[PF_SKIP_PROTO].ptr;
1122 #endif
1123 		else if (PF_MISMATCHAW(&r->src.addr,
1124 		    (struct pf_addr *)&h->ip6_src, AF_INET6,
1125 		    r->src.neg, kif, M_GETFIB(m)))
1126 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1127 		else if (PF_MISMATCHAW(&r->dst.addr,
1128 		    (struct pf_addr *)&h->ip6_dst, AF_INET6,
1129 		    r->dst.neg, NULL, M_GETFIB(m)))
1130 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1131 		else
1132 			break;
1133 	}
1134 
1135 	if (r == NULL || r->action == PF_NOSCRUB)
1136 		return (PF_PASS);
1137 	else {
1138 		r->packets[dir == PF_OUT]++;
1139 		r->bytes[dir == PF_OUT] += pd->tot_len;
1140 	}
1141 
1142 	/* Check for illegal packets */
1143 	if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1144 		goto drop;
1145 
1146 	off = sizeof(struct ip6_hdr);
1147 	proto = h->ip6_nxt;
1148 	terminal = 0;
1149 	do {
1150 		switch (proto) {
1151 		case IPPROTO_FRAGMENT:
1152 			goto fragment;
1153 			break;
1154 		case IPPROTO_AH:
1155 		case IPPROTO_ROUTING:
1156 		case IPPROTO_DSTOPTS:
1157 			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1158 			    NULL, AF_INET6))
1159 				goto shortpkt;
1160 			if (proto == IPPROTO_AH)
1161 				off += (ext.ip6e_len + 2) * 4;
1162 			else
1163 				off += (ext.ip6e_len + 1) * 8;
1164 			proto = ext.ip6e_nxt;
1165 			break;
1166 		case IPPROTO_HOPOPTS:
1167 			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1168 			    NULL, AF_INET6))
1169 				goto shortpkt;
1170 			optend = off + (ext.ip6e_len + 1) * 8;
1171 			ooff = off + sizeof(ext);
1172 			do {
1173 				if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1174 				    sizeof(opt.ip6o_type), NULL, NULL,
1175 				    AF_INET6))
1176 					goto shortpkt;
1177 				if (opt.ip6o_type == IP6OPT_PAD1) {
1178 					ooff++;
1179 					continue;
1180 				}
1181 				if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1182 				    NULL, NULL, AF_INET6))
1183 					goto shortpkt;
1184 				if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1185 					goto drop;
1186 				switch (opt.ip6o_type) {
1187 				case IP6OPT_JUMBO:
1188 					if (h->ip6_plen != 0)
1189 						goto drop;
1190 					if (!pf_pull_hdr(m, ooff, &jumbo,
1191 					    sizeof(jumbo), NULL, NULL,
1192 					    AF_INET6))
1193 						goto shortpkt;
1194 					memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1195 					    sizeof(jumbolen));
1196 					jumbolen = ntohl(jumbolen);
1197 					if (jumbolen <= IPV6_MAXPACKET)
1198 						goto drop;
1199 					if (sizeof(struct ip6_hdr) + jumbolen !=
1200 					    m->m_pkthdr.len)
1201 						goto drop;
1202 					break;
1203 				default:
1204 					break;
1205 				}
1206 				ooff += sizeof(opt) + opt.ip6o_len;
1207 			} while (ooff < optend);
1208 
1209 			off = optend;
1210 			proto = ext.ip6e_nxt;
1211 			break;
1212 		default:
1213 			terminal = 1;
1214 			break;
1215 		}
1216 	} while (!terminal);
1217 
1218 	/* jumbo payload option must be present, or plen > 0 */
1219 	if (ntohs(h->ip6_plen) == 0)
1220 		plen = jumbolen;
1221 	else
1222 		plen = ntohs(h->ip6_plen);
1223 	if (plen == 0)
1224 		goto drop;
1225 	if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1226 		goto shortpkt;
1227 
1228 	pf_scrub_ip6(&m, r->min_ttl);
1229 
1230 	return (PF_PASS);
1231 
1232  fragment:
1233 	if (ntohs(h->ip6_plen) == 0 || jumbolen)
1234 		goto drop;
1235 	plen = ntohs(h->ip6_plen);
1236 
1237 	if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1238 		goto shortpkt;
1239 	fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1240 	if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1241 		goto badfrag;
1242 
1243 	/* do something about it */
1244 	/* remember to set pd->flags |= PFDESC_IP_REAS */
1245 	return (PF_PASS);
1246 
1247  shortpkt:
1248 	REASON_SET(reason, PFRES_SHORT);
1249 	if (r != NULL && r->log)
1250 		PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1251 		    1);
1252 	return (PF_DROP);
1253 
1254  drop:
1255 	REASON_SET(reason, PFRES_NORM);
1256 	if (r != NULL && r->log)
1257 		PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1258 		    1);
1259 	return (PF_DROP);
1260 
1261  badfrag:
1262 	REASON_SET(reason, PFRES_FRAG);
1263 	if (r != NULL && r->log)
1264 		PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1265 		    1);
1266 	return (PF_DROP);
1267 }
1268 #endif /* INET6 */
1269 
1270 int
1271 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1272     int off, void *h, struct pf_pdesc *pd)
1273 {
1274 	struct pf_rule	*r, *rm = NULL;
1275 	struct tcphdr	*th = pd->hdr.tcp;
1276 	int		 rewrite = 0;
1277 	u_short		 reason;
1278 	u_int8_t	 flags;
1279 	sa_family_t	 af = pd->af;
1280 
1281 	PF_RULES_RASSERT();
1282 
1283 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1284 	while (r != NULL) {
1285 		r->evaluations++;
1286 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
1287 			r = r->skip[PF_SKIP_IFP].ptr;
1288 		else if (r->direction && r->direction != dir)
1289 			r = r->skip[PF_SKIP_DIR].ptr;
1290 		else if (r->af && r->af != af)
1291 			r = r->skip[PF_SKIP_AF].ptr;
1292 		else if (r->proto && r->proto != pd->proto)
1293 			r = r->skip[PF_SKIP_PROTO].ptr;
1294 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1295 		    r->src.neg, kif, M_GETFIB(m)))
1296 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1297 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
1298 			    r->src.port[0], r->src.port[1], th->th_sport))
1299 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
1300 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1301 		    r->dst.neg, NULL, M_GETFIB(m)))
1302 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1303 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1304 			    r->dst.port[0], r->dst.port[1], th->th_dport))
1305 			r = r->skip[PF_SKIP_DST_PORT].ptr;
1306 		else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1307 			    pf_osfp_fingerprint(pd, m, off, th),
1308 			    r->os_fingerprint))
1309 			r = TAILQ_NEXT(r, entries);
1310 		else {
1311 			rm = r;
1312 			break;
1313 		}
1314 	}
1315 
1316 	if (rm == NULL || rm->action == PF_NOSCRUB)
1317 		return (PF_PASS);
1318 	else {
1319 		r->packets[dir == PF_OUT]++;
1320 		r->bytes[dir == PF_OUT] += pd->tot_len;
1321 	}
1322 
1323 	if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1324 		pd->flags |= PFDESC_TCP_NORM;
1325 
1326 	flags = th->th_flags;
1327 	if (flags & TH_SYN) {
1328 		/* Illegal packet */
1329 		if (flags & TH_RST)
1330 			goto tcp_drop;
1331 
1332 		if (flags & TH_FIN)
1333 			flags &= ~TH_FIN;
1334 	} else {
1335 		/* Illegal packet */
1336 		if (!(flags & (TH_ACK|TH_RST)))
1337 			goto tcp_drop;
1338 	}
1339 
1340 	if (!(flags & TH_ACK)) {
1341 		/* These flags are only valid if ACK is set */
1342 		if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1343 			goto tcp_drop;
1344 	}
1345 
1346 	/* Check for illegal header length */
1347 	if (th->th_off < (sizeof(struct tcphdr) >> 2))
1348 		goto tcp_drop;
1349 
1350 	/* If flags changed, or reserved data set, then adjust */
1351 	if (flags != th->th_flags || th->th_x2 != 0) {
1352 		u_int16_t	ov, nv;
1353 
1354 		ov = *(u_int16_t *)(&th->th_ack + 1);
1355 		th->th_flags = flags;
1356 		th->th_x2 = 0;
1357 		nv = *(u_int16_t *)(&th->th_ack + 1);
1358 
1359 		th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1360 		rewrite = 1;
1361 	}
1362 
1363 	/* Remove urgent pointer, if TH_URG is not set */
1364 	if (!(flags & TH_URG) && th->th_urp) {
1365 		th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1366 		th->th_urp = 0;
1367 		rewrite = 1;
1368 	}
1369 
1370 	/* Process options */
1371 	if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1372 		rewrite = 1;
1373 
1374 	/* copy back packet headers if we sanitized */
1375 	if (rewrite)
1376 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
1377 
1378 	return (PF_PASS);
1379 
1380  tcp_drop:
1381 	REASON_SET(&reason, PFRES_NORM);
1382 	if (rm != NULL && r->log)
1383 		PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1384 		    1);
1385 	return (PF_DROP);
1386 }
1387 
1388 int
1389 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1390     struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1391 {
1392 	u_int32_t tsval, tsecr;
1393 	u_int8_t hdr[60];
1394 	u_int8_t *opt;
1395 
1396 	KASSERT((src->scrub == NULL),
1397 	    ("pf_normalize_tcp_init: src->scrub != NULL"));
1398 
1399 	src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1400 	if (src->scrub == NULL)
1401 		return (1);
1402 
1403 	switch (pd->af) {
1404 #ifdef INET
1405 	case AF_INET: {
1406 		struct ip *h = mtod(m, struct ip *);
1407 		src->scrub->pfss_ttl = h->ip_ttl;
1408 		break;
1409 	}
1410 #endif /* INET */
1411 #ifdef INET6
1412 	case AF_INET6: {
1413 		struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1414 		src->scrub->pfss_ttl = h->ip6_hlim;
1415 		break;
1416 	}
1417 #endif /* INET6 */
1418 	}
1419 
1420 
1421 	/*
1422 	 * All normalizations below are only begun if we see the start of
1423 	 * the connections.  They must all set an enabled bit in pfss_flags
1424 	 */
1425 	if ((th->th_flags & TH_SYN) == 0)
1426 		return (0);
1427 
1428 
1429 	if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1430 	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1431 		/* Diddle with TCP options */
1432 		int hlen;
1433 		opt = hdr + sizeof(struct tcphdr);
1434 		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1435 		while (hlen >= TCPOLEN_TIMESTAMP) {
1436 			switch (*opt) {
1437 			case TCPOPT_EOL:	/* FALLTHROUGH */
1438 			case TCPOPT_NOP:
1439 				opt++;
1440 				hlen--;
1441 				break;
1442 			case TCPOPT_TIMESTAMP:
1443 				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1444 					src->scrub->pfss_flags |=
1445 					    PFSS_TIMESTAMP;
1446 					src->scrub->pfss_ts_mod =
1447 					    htonl(arc4random());
1448 
1449 					/* note PFSS_PAWS not set yet */
1450 					memcpy(&tsval, &opt[2],
1451 					    sizeof(u_int32_t));
1452 					memcpy(&tsecr, &opt[6],
1453 					    sizeof(u_int32_t));
1454 					src->scrub->pfss_tsval0 = ntohl(tsval);
1455 					src->scrub->pfss_tsval = ntohl(tsval);
1456 					src->scrub->pfss_tsecr = ntohl(tsecr);
1457 					getmicrouptime(&src->scrub->pfss_last);
1458 				}
1459 				/* FALLTHROUGH */
1460 			default:
1461 				hlen -= MAX(opt[1], 2);
1462 				opt += MAX(opt[1], 2);
1463 				break;
1464 			}
1465 		}
1466 	}
1467 
1468 	return (0);
1469 }
1470 
1471 void
1472 pf_normalize_tcp_cleanup(struct pf_state *state)
1473 {
1474 	if (state->src.scrub)
1475 		uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1476 	if (state->dst.scrub)
1477 		uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1478 
1479 	/* Someday... flush the TCP segment reassembly descriptors. */
1480 }
1481 
1482 int
1483 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1484     u_short *reason, struct tcphdr *th, struct pf_state *state,
1485     struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1486 {
1487 	struct timeval uptime;
1488 	u_int32_t tsval, tsecr;
1489 	u_int tsval_from_last;
1490 	u_int8_t hdr[60];
1491 	u_int8_t *opt;
1492 	int copyback = 0;
1493 	int got_ts = 0;
1494 
1495 	KASSERT((src->scrub || dst->scrub),
1496 	    ("%s: src->scrub && dst->scrub!", __func__));
1497 
1498 	/*
1499 	 * Enforce the minimum TTL seen for this connection.  Negate a common
1500 	 * technique to evade an intrusion detection system and confuse
1501 	 * firewall state code.
1502 	 */
1503 	switch (pd->af) {
1504 #ifdef INET
1505 	case AF_INET: {
1506 		if (src->scrub) {
1507 			struct ip *h = mtod(m, struct ip *);
1508 			if (h->ip_ttl > src->scrub->pfss_ttl)
1509 				src->scrub->pfss_ttl = h->ip_ttl;
1510 			h->ip_ttl = src->scrub->pfss_ttl;
1511 		}
1512 		break;
1513 	}
1514 #endif /* INET */
1515 #ifdef INET6
1516 	case AF_INET6: {
1517 		if (src->scrub) {
1518 			struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1519 			if (h->ip6_hlim > src->scrub->pfss_ttl)
1520 				src->scrub->pfss_ttl = h->ip6_hlim;
1521 			h->ip6_hlim = src->scrub->pfss_ttl;
1522 		}
1523 		break;
1524 	}
1525 #endif /* INET6 */
1526 	}
1527 
1528 	if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1529 	    ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1530 	    (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1531 	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1532 		/* Diddle with TCP options */
1533 		int hlen;
1534 		opt = hdr + sizeof(struct tcphdr);
1535 		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1536 		while (hlen >= TCPOLEN_TIMESTAMP) {
1537 			switch (*opt) {
1538 			case TCPOPT_EOL:	/* FALLTHROUGH */
1539 			case TCPOPT_NOP:
1540 				opt++;
1541 				hlen--;
1542 				break;
1543 			case TCPOPT_TIMESTAMP:
1544 				/* Modulate the timestamps.  Can be used for
1545 				 * NAT detection, OS uptime determination or
1546 				 * reboot detection.
1547 				 */
1548 
1549 				if (got_ts) {
1550 					/* Huh?  Multiple timestamps!? */
1551 					if (V_pf_status.debug >= PF_DEBUG_MISC) {
1552 						DPFPRINTF(("multiple TS??"));
1553 						pf_print_state(state);
1554 						printf("\n");
1555 					}
1556 					REASON_SET(reason, PFRES_TS);
1557 					return (PF_DROP);
1558 				}
1559 				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1560 					memcpy(&tsval, &opt[2],
1561 					    sizeof(u_int32_t));
1562 					if (tsval && src->scrub &&
1563 					    (src->scrub->pfss_flags &
1564 					    PFSS_TIMESTAMP)) {
1565 						tsval = ntohl(tsval);
1566 						pf_change_a(&opt[2],
1567 						    &th->th_sum,
1568 						    htonl(tsval +
1569 						    src->scrub->pfss_ts_mod),
1570 						    0);
1571 						copyback = 1;
1572 					}
1573 
1574 					/* Modulate TS reply iff valid (!0) */
1575 					memcpy(&tsecr, &opt[6],
1576 					    sizeof(u_int32_t));
1577 					if (tsecr && dst->scrub &&
1578 					    (dst->scrub->pfss_flags &
1579 					    PFSS_TIMESTAMP)) {
1580 						tsecr = ntohl(tsecr)
1581 						    - dst->scrub->pfss_ts_mod;
1582 						pf_change_a(&opt[6],
1583 						    &th->th_sum, htonl(tsecr),
1584 						    0);
1585 						copyback = 1;
1586 					}
1587 					got_ts = 1;
1588 				}
1589 				/* FALLTHROUGH */
1590 			default:
1591 				hlen -= MAX(opt[1], 2);
1592 				opt += MAX(opt[1], 2);
1593 				break;
1594 			}
1595 		}
1596 		if (copyback) {
1597 			/* Copyback the options, caller copys back header */
1598 			*writeback = 1;
1599 			m_copyback(m, off + sizeof(struct tcphdr),
1600 			    (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1601 			    sizeof(struct tcphdr));
1602 		}
1603 	}
1604 
1605 
1606 	/*
1607 	 * Must invalidate PAWS checks on connections idle for too long.
1608 	 * The fastest allowed timestamp clock is 1ms.  That turns out to
1609 	 * be about 24 days before it wraps.  XXX Right now our lowerbound
1610 	 * TS echo check only works for the first 12 days of a connection
1611 	 * when the TS has exhausted half its 32bit space
1612 	 */
1613 #define TS_MAX_IDLE	(24*24*60*60)
1614 #define TS_MAX_CONN	(12*24*60*60)	/* XXX remove when better tsecr check */
1615 
1616 	getmicrouptime(&uptime);
1617 	if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1618 	    (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1619 	    time_uptime - state->creation > TS_MAX_CONN))  {
1620 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1621 			DPFPRINTF(("src idled out of PAWS\n"));
1622 			pf_print_state(state);
1623 			printf("\n");
1624 		}
1625 		src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1626 		    | PFSS_PAWS_IDLED;
1627 	}
1628 	if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1629 	    uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1630 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1631 			DPFPRINTF(("dst idled out of PAWS\n"));
1632 			pf_print_state(state);
1633 			printf("\n");
1634 		}
1635 		dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1636 		    | PFSS_PAWS_IDLED;
1637 	}
1638 
1639 	if (got_ts && src->scrub && dst->scrub &&
1640 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1641 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1642 		/* Validate that the timestamps are "in-window".
1643 		 * RFC1323 describes TCP Timestamp options that allow
1644 		 * measurement of RTT (round trip time) and PAWS
1645 		 * (protection against wrapped sequence numbers).  PAWS
1646 		 * gives us a set of rules for rejecting packets on
1647 		 * long fat pipes (packets that were somehow delayed
1648 		 * in transit longer than the time it took to send the
1649 		 * full TCP sequence space of 4Gb).  We can use these
1650 		 * rules and infer a few others that will let us treat
1651 		 * the 32bit timestamp and the 32bit echoed timestamp
1652 		 * as sequence numbers to prevent a blind attacker from
1653 		 * inserting packets into a connection.
1654 		 *
1655 		 * RFC1323 tells us:
1656 		 *  - The timestamp on this packet must be greater than
1657 		 *    or equal to the last value echoed by the other
1658 		 *    endpoint.  The RFC says those will be discarded
1659 		 *    since it is a dup that has already been acked.
1660 		 *    This gives us a lowerbound on the timestamp.
1661 		 *        timestamp >= other last echoed timestamp
1662 		 *  - The timestamp will be less than or equal to
1663 		 *    the last timestamp plus the time between the
1664 		 *    last packet and now.  The RFC defines the max
1665 		 *    clock rate as 1ms.  We will allow clocks to be
1666 		 *    up to 10% fast and will allow a total difference
1667 		 *    or 30 seconds due to a route change.  And this
1668 		 *    gives us an upperbound on the timestamp.
1669 		 *        timestamp <= last timestamp + max ticks
1670 		 *    We have to be careful here.  Windows will send an
1671 		 *    initial timestamp of zero and then initialize it
1672 		 *    to a random value after the 3whs; presumably to
1673 		 *    avoid a DoS by having to call an expensive RNG
1674 		 *    during a SYN flood.  Proof MS has at least one
1675 		 *    good security geek.
1676 		 *
1677 		 *  - The TCP timestamp option must also echo the other
1678 		 *    endpoints timestamp.  The timestamp echoed is the
1679 		 *    one carried on the earliest unacknowledged segment
1680 		 *    on the left edge of the sequence window.  The RFC
1681 		 *    states that the host will reject any echoed
1682 		 *    timestamps that were larger than any ever sent.
1683 		 *    This gives us an upperbound on the TS echo.
1684 		 *        tescr <= largest_tsval
1685 		 *  - The lowerbound on the TS echo is a little more
1686 		 *    tricky to determine.  The other endpoint's echoed
1687 		 *    values will not decrease.  But there may be
1688 		 *    network conditions that re-order packets and
1689 		 *    cause our view of them to decrease.  For now the
1690 		 *    only lowerbound we can safely determine is that
1691 		 *    the TS echo will never be less than the original
1692 		 *    TS.  XXX There is probably a better lowerbound.
1693 		 *    Remove TS_MAX_CONN with better lowerbound check.
1694 		 *        tescr >= other original TS
1695 		 *
1696 		 * It is also important to note that the fastest
1697 		 * timestamp clock of 1ms will wrap its 32bit space in
1698 		 * 24 days.  So we just disable TS checking after 24
1699 		 * days of idle time.  We actually must use a 12d
1700 		 * connection limit until we can come up with a better
1701 		 * lowerbound to the TS echo check.
1702 		 */
1703 		struct timeval delta_ts;
1704 		int ts_fudge;
1705 
1706 
1707 		/*
1708 		 * PFTM_TS_DIFF is how many seconds of leeway to allow
1709 		 * a host's timestamp.  This can happen if the previous
1710 		 * packet got delayed in transit for much longer than
1711 		 * this packet.
1712 		 */
1713 		if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1714 			ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1715 
1716 		/* Calculate max ticks since the last timestamp */
1717 #define TS_MAXFREQ	1100		/* RFC max TS freq of 1Khz + 10% skew */
1718 #define TS_MICROSECS	1000000		/* microseconds per second */
1719 		delta_ts = uptime;
1720 		timevalsub(&delta_ts, &src->scrub->pfss_last);
1721 		tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1722 		tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1723 
1724 		if ((src->state >= TCPS_ESTABLISHED &&
1725 		    dst->state >= TCPS_ESTABLISHED) &&
1726 		    (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1727 		    SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1728 		    (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1729 		    SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1730 			/* Bad RFC1323 implementation or an insertion attack.
1731 			 *
1732 			 * - Solaris 2.6 and 2.7 are known to send another ACK
1733 			 *   after the FIN,FIN|ACK,ACK closing that carries
1734 			 *   an old timestamp.
1735 			 */
1736 
1737 			DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1738 			    SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1739 			    SEQ_GT(tsval, src->scrub->pfss_tsval +
1740 			    tsval_from_last) ? '1' : ' ',
1741 			    SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1742 			    SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1743 			DPFPRINTF((" tsval: %u  tsecr: %u  +ticks: %u  "
1744 			    "idle: %jus %lums\n",
1745 			    tsval, tsecr, tsval_from_last,
1746 			    (uintmax_t)delta_ts.tv_sec,
1747 			    delta_ts.tv_usec / 1000));
1748 			DPFPRINTF((" src->tsval: %u  tsecr: %u\n",
1749 			    src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1750 			DPFPRINTF((" dst->tsval: %u  tsecr: %u  tsval0: %u"
1751 			    "\n", dst->scrub->pfss_tsval,
1752 			    dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1753 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1754 				pf_print_state(state);
1755 				pf_print_flags(th->th_flags);
1756 				printf("\n");
1757 			}
1758 			REASON_SET(reason, PFRES_TS);
1759 			return (PF_DROP);
1760 		}
1761 
1762 		/* XXX I'd really like to require tsecr but it's optional */
1763 
1764 	} else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1765 	    ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1766 	    || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1767 	    src->scrub && dst->scrub &&
1768 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1769 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1770 		/* Didn't send a timestamp.  Timestamps aren't really useful
1771 		 * when:
1772 		 *  - connection opening or closing (often not even sent).
1773 		 *    but we must not let an attacker to put a FIN on a
1774 		 *    data packet to sneak it through our ESTABLISHED check.
1775 		 *  - on a TCP reset.  RFC suggests not even looking at TS.
1776 		 *  - on an empty ACK.  The TS will not be echoed so it will
1777 		 *    probably not help keep the RTT calculation in sync and
1778 		 *    there isn't as much danger when the sequence numbers
1779 		 *    got wrapped.  So some stacks don't include TS on empty
1780 		 *    ACKs :-(
1781 		 *
1782 		 * To minimize the disruption to mostly RFC1323 conformant
1783 		 * stacks, we will only require timestamps on data packets.
1784 		 *
1785 		 * And what do ya know, we cannot require timestamps on data
1786 		 * packets.  There appear to be devices that do legitimate
1787 		 * TCP connection hijacking.  There are HTTP devices that allow
1788 		 * a 3whs (with timestamps) and then buffer the HTTP request.
1789 		 * If the intermediate device has the HTTP response cache, it
1790 		 * will spoof the response but not bother timestamping its
1791 		 * packets.  So we can look for the presence of a timestamp in
1792 		 * the first data packet and if there, require it in all future
1793 		 * packets.
1794 		 */
1795 
1796 		if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1797 			/*
1798 			 * Hey!  Someone tried to sneak a packet in.  Or the
1799 			 * stack changed its RFC1323 behavior?!?!
1800 			 */
1801 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1802 				DPFPRINTF(("Did not receive expected RFC1323 "
1803 				    "timestamp\n"));
1804 				pf_print_state(state);
1805 				pf_print_flags(th->th_flags);
1806 				printf("\n");
1807 			}
1808 			REASON_SET(reason, PFRES_TS);
1809 			return (PF_DROP);
1810 		}
1811 	}
1812 
1813 
1814 	/*
1815 	 * We will note if a host sends his data packets with or without
1816 	 * timestamps.  And require all data packets to contain a timestamp
1817 	 * if the first does.  PAWS implicitly requires that all data packets be
1818 	 * timestamped.  But I think there are middle-man devices that hijack
1819 	 * TCP streams immediately after the 3whs and don't timestamp their
1820 	 * packets (seen in a WWW accelerator or cache).
1821 	 */
1822 	if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1823 	    (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1824 		if (got_ts)
1825 			src->scrub->pfss_flags |= PFSS_DATA_TS;
1826 		else {
1827 			src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1828 			if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1829 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1830 				/* Don't warn if other host rejected RFC1323 */
1831 				DPFPRINTF(("Broken RFC1323 stack did not "
1832 				    "timestamp data packet. Disabled PAWS "
1833 				    "security.\n"));
1834 				pf_print_state(state);
1835 				pf_print_flags(th->th_flags);
1836 				printf("\n");
1837 			}
1838 		}
1839 	}
1840 
1841 
1842 	/*
1843 	 * Update PAWS values
1844 	 */
1845 	if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1846 	    (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1847 		getmicrouptime(&src->scrub->pfss_last);
1848 		if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1849 		    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1850 			src->scrub->pfss_tsval = tsval;
1851 
1852 		if (tsecr) {
1853 			if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1854 			    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1855 				src->scrub->pfss_tsecr = tsecr;
1856 
1857 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1858 			    (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1859 			    src->scrub->pfss_tsval0 == 0)) {
1860 				/* tsval0 MUST be the lowest timestamp */
1861 				src->scrub->pfss_tsval0 = tsval;
1862 			}
1863 
1864 			/* Only fully initialized after a TS gets echoed */
1865 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1866 				src->scrub->pfss_flags |= PFSS_PAWS;
1867 		}
1868 	}
1869 
1870 	/* I have a dream....  TCP segment reassembly.... */
1871 	return (0);
1872 }
1873 
1874 static int
1875 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1876     int off, sa_family_t af)
1877 {
1878 	u_int16_t	*mss;
1879 	int		 thoff;
1880 	int		 opt, cnt, optlen = 0;
1881 	int		 rewrite = 0;
1882 	u_char		 opts[TCP_MAXOLEN];
1883 	u_char		*optp = opts;
1884 
1885 	thoff = th->th_off << 2;
1886 	cnt = thoff - sizeof(struct tcphdr);
1887 
1888 	if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1889 	    NULL, NULL, af))
1890 		return (rewrite);
1891 
1892 	for (; cnt > 0; cnt -= optlen, optp += optlen) {
1893 		opt = optp[0];
1894 		if (opt == TCPOPT_EOL)
1895 			break;
1896 		if (opt == TCPOPT_NOP)
1897 			optlen = 1;
1898 		else {
1899 			if (cnt < 2)
1900 				break;
1901 			optlen = optp[1];
1902 			if (optlen < 2 || optlen > cnt)
1903 				break;
1904 		}
1905 		switch (opt) {
1906 		case TCPOPT_MAXSEG:
1907 			mss = (u_int16_t *)(optp + 2);
1908 			if ((ntohs(*mss)) > r->max_mss) {
1909 				th->th_sum = pf_cksum_fixup(th->th_sum,
1910 				    *mss, htons(r->max_mss), 0);
1911 				*mss = htons(r->max_mss);
1912 				rewrite = 1;
1913 			}
1914 			break;
1915 		default:
1916 			break;
1917 		}
1918 	}
1919 
1920 	if (rewrite)
1921 		m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1922 
1923 	return (rewrite);
1924 }
1925 
1926 #ifdef INET
1927 static void
1928 pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
1929 {
1930 	struct mbuf		*m = *m0;
1931 	struct ip		*h = mtod(m, struct ip *);
1932 
1933 	/* Clear IP_DF if no-df was requested */
1934 	if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1935 		u_int16_t ip_off = h->ip_off;
1936 
1937 		h->ip_off &= htons(~IP_DF);
1938 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1939 	}
1940 
1941 	/* Enforce a minimum ttl, may cause endless packet loops */
1942 	if (min_ttl && h->ip_ttl < min_ttl) {
1943 		u_int16_t ip_ttl = h->ip_ttl;
1944 
1945 		h->ip_ttl = min_ttl;
1946 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1947 	}
1948 
1949 	/* Enforce tos */
1950 	if (flags & PFRULE_SET_TOS) {
1951 		u_int16_t	ov, nv;
1952 
1953 		ov = *(u_int16_t *)h;
1954 		h->ip_tos = tos;
1955 		nv = *(u_int16_t *)h;
1956 
1957 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1958 	}
1959 
1960 	/* random-id, but not for fragments */
1961 	if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
1962 		u_int16_t ip_id = h->ip_id;
1963 
1964 		h->ip_id = ip_randomid();
1965 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1966 	}
1967 }
1968 #endif /* INET */
1969 
1970 #ifdef INET6
1971 static void
1972 pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
1973 {
1974 	struct mbuf		*m = *m0;
1975 	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
1976 
1977 	/* Enforce a minimum ttl, may cause endless packet loops */
1978 	if (min_ttl && h->ip6_hlim < min_ttl)
1979 		h->ip6_hlim = min_ttl;
1980 }
1981 #endif
1982