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