xref: /dragonfly/sys/net/pf/pf_norm.c (revision 82730a9c)
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			 tag = -1;
817 
818 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
819 	while (r != NULL) {
820 		r->evaluations++;
821 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
822 			r = r->skip[PF_SKIP_IFP].ptr;
823 		else if (r->direction && r->direction != dir)
824 			r = r->skip[PF_SKIP_DIR].ptr;
825 		else if (r->af && r->af != AF_INET)
826 			r = r->skip[PF_SKIP_AF].ptr;
827 		else if (r->proto && r->proto != h->ip_p)
828 			r = r->skip[PF_SKIP_PROTO].ptr;
829 		else if (PF_MISMATCHAW(&r->src.addr,
830 		    (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
831 		    r->src.neg, kif))
832 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
833 		else if (PF_MISMATCHAW(&r->dst.addr,
834 		    (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
835 		    r->dst.neg, NULL))
836 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
837 		else if (r->match_tag && !pf_match_tag(m, r, &tag))
838 			r = TAILQ_NEXT(r, entries);
839 		else
840 			break;
841 	}
842 
843 	if (r == NULL || r->action == PF_NOSCRUB)
844 		return (PF_PASS);
845 	else {
846 		r->packets[dir == PF_OUT]++;
847 		r->bytes[dir == PF_OUT] += pd->tot_len;
848 	}
849 
850 	/* Check for illegal packets */
851 	if (hlen < (int)sizeof(struct ip))
852 		goto drop;
853 
854 	if (hlen > h->ip_len)
855 		goto drop;
856 
857 	/* Clear IP_DF if the rule uses the no-df option */
858 	if (r->rule_flag & PFRULE_NODF && h->ip_off & IP_DF) {
859 		u_int16_t ip_off = h->ip_off;
860 
861 		h->ip_off &= ~IP_DF;
862 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
863 	}
864 
865 	/* We will need other tests here */
866 	if (!fragoff && !mff)
867 		goto no_fragment;
868 
869 	/* We're dealing with a fragment now. Don't allow fragments
870 	 * with IP_DF to enter the cache. If the flag was cleared by
871 	 * no-df above, fine. Otherwise drop it.
872 	 */
873 	if (h->ip_off & IP_DF) {
874 		DPFPRINTF(("IP_DF\n"));
875 		goto bad;
876 	}
877 
878 	ip_len = h->ip_len - hlen;
879 
880 	/* All fragments are 8 byte aligned */
881 	if (mff && (ip_len & 0x7)) {
882 		DPFPRINTF(("mff and %d\n", ip_len));
883 		goto bad;
884 	}
885 
886 	/* Respect maximum length */
887 	if (fragoff + ip_len > IP_MAXPACKET) {
888 		DPFPRINTF(("max packet %d\n", fragoff + ip_len));
889 		goto bad;
890 	}
891 	max = fragoff + ip_len;
892 
893 	if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
894 		/* Fully buffer all of the fragments */
895 
896 		frag = pf_find_fragment(h, &pf_frag_tree);
897 
898 		/* Check if we saw the last fragment already */
899 		if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
900 		    max > frag->fr_max)
901 			goto bad;
902 
903 		/* Get an entry for the fragment queue */
904 		frent = kmalloc(sizeof(struct pf_frent), M_PFFRENTPL, M_NOWAIT);
905 		if (frent == NULL) {
906 			REASON_SET(reason, PFRES_MEMORY);
907 			return (PF_DROP);
908 		}
909 		pf_nfrents++;
910 		frent->fr_ip = h;
911 		frent->fr_m = m;
912 
913 		/* Might return a completely reassembled mbuf, or NULL */
914 		DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
915 		*m0 = m = pf_reassemble(m0, &frag, frent, mff);
916 
917 		if (m == NULL)
918 			return (PF_DROP);
919 
920 		if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
921 			goto drop;
922 
923 		h = mtod(m, struct ip *);
924 	} else {
925 		/* non-buffering fragment cache (drops or masks overlaps) */
926 		int	nomem = 0;
927 
928 		if (dir == PF_OUT && m->m_pkthdr.pf.flags & PF_TAG_FRAGCACHE) {
929 			/*
930 			 * Already passed the fragment cache in the
931 			 * input direction.  If we continued, it would
932 			 * appear to be a dup and would be dropped.
933 			 */
934 			goto fragment_pass;
935 		}
936 
937 		frag = pf_find_fragment(h, &pf_cache_tree);
938 
939 		/* Check if we saw the last fragment already */
940 		if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
941 		    max > frag->fr_max) {
942 			if (r->rule_flag & PFRULE_FRAGDROP)
943 				frag->fr_flags |= PFFRAG_DROP;
944 			goto bad;
945 		}
946 
947 		*m0 = m = pf_fragcache(m0, h, &frag, mff,
948 		    (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
949 		if (m == NULL) {
950 			if (nomem)
951 				goto no_mem;
952 			goto drop;
953 		}
954 
955 		if (dir == PF_IN)
956 			m->m_pkthdr.pf.flags |= PF_TAG_FRAGCACHE;
957 
958 		if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
959 			goto drop;
960 		goto fragment_pass;
961 	}
962 
963  no_fragment:
964 	/* At this point, only IP_DF is allowed in ip_off */
965 	if (h->ip_off & ~IP_DF) {
966 		u_int16_t ip_off = h->ip_off;
967 
968 		h->ip_off &= IP_DF;
969 		h->ip_sum = pf_cksum_fixup(h->ip_sum, htons(ip_off), htons(h->ip_off), 0);
970 	}
971 
972 	/* Enforce a minimum ttl, may cause endless packet loops */
973 	if (r->min_ttl && h->ip_ttl < r->min_ttl) {
974 		u_int16_t ip_ttl = h->ip_ttl;
975 
976 		h->ip_ttl = r->min_ttl;
977 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
978 	}
979 
980 	/* Enforce tos */
981 	if (r->rule_flag & PFRULE_SET_TOS) {
982 		u_int16_t	ov, nv;
983 
984 		ov = *(u_int16_t *)h;
985 		h->ip_tos = r->set_tos;
986 		nv = *(u_int16_t *)h;
987 
988 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
989 	}
990 
991 	if (r->rule_flag & PFRULE_RANDOMID) {
992 		u_int16_t ip_id = h->ip_id;
993 
994 		h->ip_id = ip_randomid();
995 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
996 	}
997 	if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
998 		pd->flags |= PFDESC_IP_REAS;
999 
1000 	return (PF_PASS);
1001 
1002  fragment_pass:
1003 	/* Enforce a minimum ttl, may cause endless packet loops */
1004 	if (r->min_ttl && h->ip_ttl < r->min_ttl) {
1005 		u_int16_t ip_ttl = h->ip_ttl;
1006 
1007 		h->ip_ttl = r->min_ttl;
1008 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1009 	}
1010 	/* Enforce tos */
1011 	if (r->rule_flag & PFRULE_SET_TOS) {
1012 		u_int16_t	ov, nv;
1013 
1014 		ov = *(u_int16_t *)h;
1015 		h->ip_tos = r->set_tos;
1016 		nv = *(u_int16_t *)h;
1017 
1018 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1019 	}
1020 	if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1021 		pd->flags |= PFDESC_IP_REAS;
1022 	return (PF_PASS);
1023 
1024  no_mem:
1025 	REASON_SET(reason, PFRES_MEMORY);
1026 	if (r != NULL && r->log)
1027 		PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1028 	return (PF_DROP);
1029 
1030  drop:
1031 	REASON_SET(reason, PFRES_NORM);
1032 	if (r != NULL && r->log)
1033 		PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1034 	return (PF_DROP);
1035 
1036  bad:
1037 	DPFPRINTF(("dropping bad fragment\n"));
1038 
1039 	/* Free associated fragments */
1040 	if (frag != NULL)
1041 		pf_free_fragment(frag);
1042 
1043 	REASON_SET(reason, PFRES_FRAG);
1044 	if (r != NULL && r->log)
1045 		PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1046 
1047 	return (PF_DROP);
1048 }
1049 
1050 #ifdef INET6
1051 int
1052 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1053     u_short *reason, struct pf_pdesc *pd)
1054 {
1055 	struct mbuf		*m = *m0;
1056 	struct pf_rule		*r;
1057 	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
1058 	int			 off;
1059 	struct ip6_ext		 ext;
1060 	struct ip6_opt		 opt;
1061 	struct ip6_opt_jumbo	 jumbo;
1062 	struct ip6_frag		 frag;
1063 	u_int32_t		 jumbolen = 0, plen;
1064 	u_int16_t		 fragoff = 0;
1065 	int			 optend;
1066 	int			 ooff;
1067 	u_int8_t		 proto;
1068 	int			 terminal;
1069 
1070 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1071 	while (r != NULL) {
1072 		r->evaluations++;
1073 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
1074 			r = r->skip[PF_SKIP_IFP].ptr;
1075 		else if (r->direction && r->direction != dir)
1076 			r = r->skip[PF_SKIP_DIR].ptr;
1077 		else if (r->af && r->af != AF_INET6)
1078 			r = r->skip[PF_SKIP_AF].ptr;
1079 #if 0 /* header chain! */
1080 		else if (r->proto && r->proto != h->ip6_nxt)
1081 			r = r->skip[PF_SKIP_PROTO].ptr;
1082 #endif
1083 		else if (PF_MISMATCHAW(&r->src.addr,
1084 		    (struct pf_addr *)&h->ip6_src, AF_INET6,
1085 		    r->src.neg, kif))
1086 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1087 		else if (PF_MISMATCHAW(&r->dst.addr,
1088 		    (struct pf_addr *)&h->ip6_dst, AF_INET6,
1089 		    r->dst.neg, NULL))
1090 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1091 		else
1092 			break;
1093 	}
1094 
1095 	if (r == NULL || r->action == PF_NOSCRUB)
1096 		return (PF_PASS);
1097 	else {
1098 		r->packets[dir == PF_OUT]++;
1099 		r->bytes[dir == PF_OUT] += pd->tot_len;
1100 	}
1101 
1102 	/* Check for illegal packets */
1103 	if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1104 		goto drop;
1105 
1106 	off = sizeof(struct ip6_hdr);
1107 	proto = h->ip6_nxt;
1108 	terminal = 0;
1109 	do {
1110 		switch (proto) {
1111 		case IPPROTO_FRAGMENT:
1112 			goto fragment;
1113 			break;
1114 		case IPPROTO_AH:
1115 		case IPPROTO_ROUTING:
1116 		case IPPROTO_DSTOPTS:
1117 			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1118 			    NULL, AF_INET6))
1119 				goto shortpkt;
1120 			if (proto == IPPROTO_AH)
1121 				off += (ext.ip6e_len + 2) * 4;
1122 			else
1123 				off += (ext.ip6e_len + 1) * 8;
1124 			proto = ext.ip6e_nxt;
1125 			break;
1126 		case IPPROTO_HOPOPTS:
1127 			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1128 			    NULL, AF_INET6))
1129 				goto shortpkt;
1130 			optend = off + (ext.ip6e_len + 1) * 8;
1131 			ooff = off + sizeof(ext);
1132 			do {
1133 				if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1134 				    sizeof(opt.ip6o_type), NULL, NULL,
1135 				    AF_INET6))
1136 					goto shortpkt;
1137 				if (opt.ip6o_type == IP6OPT_PAD1) {
1138 					ooff++;
1139 					continue;
1140 				}
1141 				if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1142 				    NULL, NULL, AF_INET6))
1143 					goto shortpkt;
1144 				if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1145 					goto drop;
1146 				switch (opt.ip6o_type) {
1147 				case IP6OPT_JUMBO:
1148 					if (h->ip6_plen != 0)
1149 						goto drop;
1150 					if (!pf_pull_hdr(m, ooff, &jumbo,
1151 					    sizeof(jumbo), NULL, NULL,
1152 					    AF_INET6))
1153 						goto shortpkt;
1154 					memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1155 					    sizeof(jumbolen));
1156 					jumbolen = ntohl(jumbolen);
1157 					if (jumbolen <= IPV6_MAXPACKET)
1158 						goto drop;
1159 					if (sizeof(struct ip6_hdr) + jumbolen !=
1160 					    m->m_pkthdr.len)
1161 						goto drop;
1162 					break;
1163 				default:
1164 					break;
1165 				}
1166 				ooff += sizeof(opt) + opt.ip6o_len;
1167 			} while (ooff < optend);
1168 
1169 			off = optend;
1170 			proto = ext.ip6e_nxt;
1171 			break;
1172 		default:
1173 			terminal = 1;
1174 			break;
1175 		}
1176 	} while (!terminal);
1177 
1178 	/* jumbo payload option must be present, or plen > 0 */
1179 	if (ntohs(h->ip6_plen) == 0)
1180 		plen = jumbolen;
1181 	else
1182 		plen = ntohs(h->ip6_plen);
1183 	if (plen == 0)
1184 		goto drop;
1185 	if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1186 		goto shortpkt;
1187 
1188 	/* Enforce a minimum ttl, may cause endless packet loops */
1189 	if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1190 		h->ip6_hlim = r->min_ttl;
1191 
1192 	return (PF_PASS);
1193 
1194  fragment:
1195 	if (ntohs(h->ip6_plen) == 0 || jumbolen)
1196 		goto drop;
1197 	plen = ntohs(h->ip6_plen);
1198 
1199 	if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1200 		goto shortpkt;
1201 	fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1202 	if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1203 		goto badfrag;
1204 
1205 	/* do something about it */
1206 	/* remember to set pd->flags |= PFDESC_IP_REAS */
1207 	return (PF_PASS);
1208 
1209  shortpkt:
1210 	REASON_SET(reason, PFRES_SHORT);
1211 	if (r != NULL && r->log)
1212 		PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1213 	return (PF_DROP);
1214 
1215  drop:
1216 	REASON_SET(reason, PFRES_NORM);
1217 	if (r != NULL && r->log)
1218 		PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1219 	return (PF_DROP);
1220 
1221  badfrag:
1222 	REASON_SET(reason, PFRES_FRAG);
1223 	if (r != NULL && r->log)
1224 		PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1225 	return (PF_DROP);
1226 }
1227 #endif /* INET6 */
1228 
1229 int
1230 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1231     int off, void *h, struct pf_pdesc *pd)
1232 {
1233 	struct pf_rule	*r, *rm = NULL;
1234 	struct tcphdr	*th = pd->hdr.tcp;
1235 	int		 rewrite = 0;
1236 	u_short		 reason;
1237 	u_int8_t	 flags;
1238 	sa_family_t	 af = pd->af;
1239 
1240 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1241 	while (r != NULL) {
1242 		r->evaluations++;
1243 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
1244 			r = r->skip[PF_SKIP_IFP].ptr;
1245 		else if (r->direction && r->direction != dir)
1246 			r = r->skip[PF_SKIP_DIR].ptr;
1247 		else if (r->af && r->af != af)
1248 			r = r->skip[PF_SKIP_AF].ptr;
1249 		else if (r->proto && r->proto != pd->proto)
1250 			r = r->skip[PF_SKIP_PROTO].ptr;
1251 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1252 		    r->src.neg, kif))
1253 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1254 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
1255 			    r->src.port[0], r->src.port[1], th->th_sport))
1256 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
1257 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1258 		    r->dst.neg, NULL))
1259 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1260 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1261 			    r->dst.port[0], r->dst.port[1], th->th_dport))
1262 			r = r->skip[PF_SKIP_DST_PORT].ptr;
1263 		else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1264 			    pf_osfp_fingerprint(pd, m, off, th),
1265 			    r->os_fingerprint))
1266 			r = TAILQ_NEXT(r, entries);
1267 		else {
1268 			rm = r;
1269 			break;
1270 		}
1271 	}
1272 
1273 	if (rm == NULL || rm->action == PF_NOSCRUB)
1274 		return (PF_PASS);
1275 	else {
1276 		r->packets[dir == PF_OUT]++;
1277 		r->bytes[dir == PF_OUT] += pd->tot_len;
1278 	}
1279 
1280 	if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1281 		pd->flags |= PFDESC_TCP_NORM;
1282 
1283 	flags = th->th_flags;
1284 	if (flags & TH_SYN) {
1285 		/* Illegal packet */
1286 		if (flags & TH_RST)
1287 			goto tcp_drop;
1288 
1289 		if (flags & TH_FIN)
1290 			flags &= ~TH_FIN;
1291 	} else {
1292 		/* Illegal packet */
1293 		if (!(flags & (TH_ACK|TH_RST)))
1294 			goto tcp_drop;
1295 	}
1296 
1297 	if (!(flags & TH_ACK)) {
1298 		/* These flags are only valid if ACK is set */
1299 		if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1300 			goto tcp_drop;
1301 	}
1302 
1303 	/* Check for illegal header length */
1304 	if (th->th_off < (sizeof(struct tcphdr) >> 2))
1305 		goto tcp_drop;
1306 
1307 	/* If flags changed, or reserved data set, then adjust */
1308 	if (flags != th->th_flags || th->th_x2 != 0) {
1309 		u_int16_t	ov, nv;
1310 
1311 		ov = *(u_int16_t *)(&th->th_ack + 1);
1312 		th->th_flags = flags;
1313 		th->th_x2 = 0;
1314 		nv = *(u_int16_t *)(&th->th_ack + 1);
1315 
1316 		th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1317 		rewrite = 1;
1318 	}
1319 
1320 	/* Remove urgent pointer, if TH_URG is not set */
1321 	if (!(flags & TH_URG) && th->th_urp) {
1322 		th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1323 		th->th_urp = 0;
1324 		rewrite = 1;
1325 	}
1326 
1327 	/* Process options */
1328 	if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1329 		rewrite = 1;
1330 
1331 	/* copy back packet headers if we sanitized */
1332 	if (rewrite)
1333 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
1334 
1335 	return (PF_PASS);
1336 
1337  tcp_drop:
1338 	REASON_SET(&reason, PFRES_NORM);
1339 	if (rm != NULL && r->log)
1340 		PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL, pd);
1341 	return (PF_DROP);
1342 }
1343 
1344 int
1345 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1346     struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1347 {
1348 	u_int32_t tsval, tsecr;
1349 	u_int8_t hdr[60];
1350 	u_int8_t *opt;
1351 
1352 	KASSERT((src->scrub == NULL),
1353 	    ("pf_normalize_tcp_init: src->scrub != NULL"));
1354 
1355 	src->scrub = kmalloc(sizeof(struct pf_state_scrub), M_PFSTATESCRUBPL,
1356 	    M_NOWAIT | M_ZERO);
1357 	if (src->scrub == NULL)
1358 		return (1);
1359 
1360 	switch (pd->af) {
1361 #ifdef INET
1362 	case AF_INET: {
1363 		struct ip *h = mtod(m, struct ip *);
1364 		src->scrub->pfss_ttl = h->ip_ttl;
1365 		break;
1366 	}
1367 #endif /* INET */
1368 #ifdef INET6
1369 	case AF_INET6: {
1370 		struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1371 		src->scrub->pfss_ttl = h->ip6_hlim;
1372 		break;
1373 	}
1374 #endif /* INET6 */
1375 	}
1376 
1377 
1378 	/*
1379 	 * All normalizations below are only begun if we see the start of
1380 	 * the connections.  They must all set an enabled bit in pfss_flags
1381 	 */
1382 	if ((th->th_flags & TH_SYN) == 0)
1383 		return (0);
1384 
1385 
1386 	if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1387 	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1388 		/* Diddle with TCP options */
1389 		int hlen;
1390 		opt = hdr + sizeof(struct tcphdr);
1391 		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1392 		while (hlen >= TCPOLEN_TIMESTAMP) {
1393 			switch (*opt) {
1394 			case TCPOPT_EOL:	/* FALLTHROUGH */
1395 			case TCPOPT_NOP:
1396 				opt++;
1397 				hlen--;
1398 				break;
1399 			case TCPOPT_TIMESTAMP:
1400 				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1401 					src->scrub->pfss_flags |=
1402 					    PFSS_TIMESTAMP;
1403 					src->scrub->pfss_ts_mod = karc4random();
1404 
1405 					/* note PFSS_PAWS not set yet */
1406 					memcpy(&tsval, &opt[2],
1407 					    sizeof(u_int32_t));
1408 					memcpy(&tsecr, &opt[6],
1409 					    sizeof(u_int32_t));
1410 					src->scrub->pfss_tsval0 = ntohl(tsval);
1411 					src->scrub->pfss_tsval = ntohl(tsval);
1412 					src->scrub->pfss_tsecr = ntohl(tsecr);
1413 					getmicrouptime(&src->scrub->pfss_last);
1414 				}
1415 				/* FALLTHROUGH */
1416 			default:
1417 				hlen -= MAX(opt[1], 2);
1418 				opt += MAX(opt[1], 2);
1419 				break;
1420 			}
1421 		}
1422 	}
1423 
1424 	return (0);
1425 }
1426 
1427 void
1428 pf_normalize_tcp_cleanup(struct pf_state *state)
1429 {
1430 	if (state->src.scrub)
1431 		kfree(state->src.scrub, M_PFSTATESCRUBPL);
1432 	if (state->dst.scrub)
1433 		kfree(state->dst.scrub, M_PFSTATESCRUBPL);
1434 
1435 	/* Someday... flush the TCP segment reassembly descriptors. */
1436 }
1437 
1438 int
1439 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1440     u_short *reason, struct tcphdr *th, struct pf_state *state,
1441     struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1442 {
1443 	struct timeval uptime;
1444 	u_int32_t tsval, tsecr;
1445 	u_int tsval_from_last;
1446 	u_int8_t hdr[60];
1447 	u_int8_t *opt;
1448 	int copyback = 0;
1449 	int got_ts = 0;
1450 
1451 	KASSERT((src->scrub || dst->scrub),
1452 	    ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1453 
1454 	/*
1455 	 * Enforce the minimum TTL seen for this connection.  Negate a common
1456 	 * technique to evade an intrusion detection system and confuse
1457 	 * firewall state code.
1458 	 */
1459 	switch (pd->af) {
1460 #ifdef INET
1461 	case AF_INET: {
1462 		if (src->scrub) {
1463 			struct ip *h = mtod(m, struct ip *);
1464 			if (h->ip_ttl > src->scrub->pfss_ttl)
1465 				src->scrub->pfss_ttl = h->ip_ttl;
1466 			h->ip_ttl = src->scrub->pfss_ttl;
1467 		}
1468 		break;
1469 	}
1470 #endif /* INET */
1471 #ifdef INET6
1472 	case AF_INET6: {
1473 		if (src->scrub) {
1474 			struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1475 			if (h->ip6_hlim > src->scrub->pfss_ttl)
1476 				src->scrub->pfss_ttl = h->ip6_hlim;
1477 			h->ip6_hlim = src->scrub->pfss_ttl;
1478 		}
1479 		break;
1480 	}
1481 #endif /* INET6 */
1482 	}
1483 
1484 	if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1485 	    ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1486 	    (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1487 	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1488 		/* Diddle with TCP options */
1489 		int hlen;
1490 		opt = hdr + sizeof(struct tcphdr);
1491 		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1492 		while (hlen >= TCPOLEN_TIMESTAMP) {
1493 			switch (*opt) {
1494 			case TCPOPT_EOL:	/* FALLTHROUGH */
1495 			case TCPOPT_NOP:
1496 				opt++;
1497 				hlen--;
1498 				break;
1499 			case TCPOPT_TIMESTAMP:
1500 				/* Modulate the timestamps.  Can be used for
1501 				 * NAT detection, OS uptime determination or
1502 				 * reboot detection.
1503 				 */
1504 
1505 				if (got_ts) {
1506 					/* Huh?  Multiple timestamps!? */
1507 					if (pf_status.debug >= PF_DEBUG_MISC) {
1508 						DPFPRINTF(("multiple TS??"));
1509 						pf_print_state(state);
1510 						kprintf("\n");
1511 					}
1512 					REASON_SET(reason, PFRES_TS);
1513 					return (PF_DROP);
1514 				}
1515 				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1516 					memcpy(&tsval, &opt[2],
1517 					    sizeof(u_int32_t));
1518 					if (tsval && src->scrub &&
1519 					    (src->scrub->pfss_flags &
1520 					    PFSS_TIMESTAMP)) {
1521 						tsval = ntohl(tsval);
1522 						pf_change_a(&opt[2],
1523 						    &th->th_sum,
1524 						    htonl(tsval +
1525 						    src->scrub->pfss_ts_mod),
1526 						    0);
1527 						copyback = 1;
1528 					}
1529 
1530 					/* Modulate TS reply iff valid (!0) */
1531 					memcpy(&tsecr, &opt[6],
1532 					    sizeof(u_int32_t));
1533 					if (tsecr && dst->scrub &&
1534 					    (dst->scrub->pfss_flags &
1535 					    PFSS_TIMESTAMP)) {
1536 						tsecr = ntohl(tsecr)
1537 						    - dst->scrub->pfss_ts_mod;
1538 						pf_change_a(&opt[6],
1539 						    &th->th_sum, htonl(tsecr),
1540 						    0);
1541 						copyback = 1;
1542 					}
1543 					got_ts = 1;
1544 				}
1545 				/* FALLTHROUGH */
1546 			default:
1547 				hlen -= MAX(opt[1], 2);
1548 				opt += MAX(opt[1], 2);
1549 				break;
1550 			}
1551 		}
1552 		if (copyback) {
1553 			/* Copyback the options, caller copys back header */
1554 			*writeback = 1;
1555 			m_copyback(m, off + sizeof(struct tcphdr),
1556 			    (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1557 			    sizeof(struct tcphdr));
1558 		}
1559 	}
1560 
1561 
1562 	/*
1563 	 * Must invalidate PAWS checks on connections idle for too long.
1564 	 * The fastest allowed timestamp clock is 1ms.  That turns out to
1565 	 * be about 24 days before it wraps.  XXX Right now our lowerbound
1566 	 * TS echo check only works for the first 12 days of a connection
1567 	 * when the TS has exhausted half its 32bit space
1568 	 */
1569 #define TS_MAX_IDLE	(24*24*60*60)
1570 #define TS_MAX_CONN	(12*24*60*60)	/* XXX remove when better tsecr check */
1571 
1572 	getmicrouptime(&uptime);
1573 	if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1574 	    (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1575 	    time_second - state->creation > TS_MAX_CONN))  {
1576 		if (pf_status.debug >= PF_DEBUG_MISC) {
1577 			DPFPRINTF(("src idled out of PAWS\n"));
1578 			pf_print_state(state);
1579 			kprintf("\n");
1580 		}
1581 		src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1582 		    | PFSS_PAWS_IDLED;
1583 	}
1584 	if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1585 	    uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1586 		if (pf_status.debug >= PF_DEBUG_MISC) {
1587 			DPFPRINTF(("dst idled out of PAWS\n"));
1588 			pf_print_state(state);
1589 			kprintf("\n");
1590 		}
1591 		dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1592 		    | PFSS_PAWS_IDLED;
1593 	}
1594 
1595 	if (got_ts && src->scrub && dst->scrub &&
1596 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1597 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1598 		/* Validate that the timestamps are "in-window".
1599 		 * RFC1323 describes TCP Timestamp options that allow
1600 		 * measurement of RTT (round trip time) and PAWS
1601 		 * (protection against wrapped sequence numbers).  PAWS
1602 		 * gives us a set of rules for rejecting packets on
1603 		 * long fat pipes (packets that were somehow delayed
1604 		 * in transit longer than the time it took to send the
1605 		 * full TCP sequence space of 4Gb).  We can use these
1606 		 * rules and infer a few others that will let us treat
1607 		 * the 32bit timestamp and the 32bit echoed timestamp
1608 		 * as sequence numbers to prevent a blind attacker from
1609 		 * inserting packets into a connection.
1610 		 *
1611 		 * RFC1323 tells us:
1612 		 *  - The timestamp on this packet must be greater than
1613 		 *    or equal to the last value echoed by the other
1614 		 *    endpoint.  The RFC says those will be discarded
1615 		 *    since it is a dup that has already been acked.
1616 		 *    This gives us a lowerbound on the timestamp.
1617 		 *        timestamp >= other last echoed timestamp
1618 		 *  - The timestamp will be less than or equal to
1619 		 *    the last timestamp plus the time between the
1620 		 *    last packet and now.  The RFC defines the max
1621 		 *    clock rate as 1ms.  We will allow clocks to be
1622 		 *    up to 10% fast and will allow a total difference
1623 		 *    or 30 seconds due to a route change.  And this
1624 		 *    gives us an upperbound on the timestamp.
1625 		 *        timestamp <= last timestamp + max ticks
1626 		 *    We have to be careful here.  Windows will send an
1627 		 *    initial timestamp of zero and then initialize it
1628 		 *    to a random value after the 3whs; presumably to
1629 		 *    avoid a DoS by having to call an expensive RNG
1630 		 *    during a SYN flood.  Proof MS has at least one
1631 		 *    good security geek.
1632 		 *
1633 		 *  - The TCP timestamp option must also echo the other
1634 		 *    endpoints timestamp.  The timestamp echoed is the
1635 		 *    one carried on the earliest unacknowledged segment
1636 		 *    on the left edge of the sequence window.  The RFC
1637 		 *    states that the host will reject any echoed
1638 		 *    timestamps that were larger than any ever sent.
1639 		 *    This gives us an upperbound on the TS echo.
1640 		 *        tescr <= largest_tsval
1641 		 *  - The lowerbound on the TS echo is a little more
1642 		 *    tricky to determine.  The other endpoint's echoed
1643 		 *    values will not decrease.  But there may be
1644 		 *    network conditions that re-order packets and
1645 		 *    cause our view of them to decrease.  For now the
1646 		 *    only lowerbound we can safely determine is that
1647 		 *    the TS echo will never be less than the original
1648 		 *    TS.  XXX There is probably a better lowerbound.
1649 		 *    Remove TS_MAX_CONN with better lowerbound check.
1650 		 *        tescr >= other original TS
1651 		 *
1652 		 * It is also important to note that the fastest
1653 		 * timestamp clock of 1ms will wrap its 32bit space in
1654 		 * 24 days.  So we just disable TS checking after 24
1655 		 * days of idle time.  We actually must use a 12d
1656 		 * connection limit until we can come up with a better
1657 		 * lowerbound to the TS echo check.
1658 		 */
1659 		struct timeval delta_ts;
1660 		int ts_fudge;
1661 
1662 
1663 		/*
1664 		 * PFTM_TS_DIFF is how many seconds of leeway to allow
1665 		 * a host's timestamp.  This can happen if the previous
1666 		 * packet got delayed in transit for much longer than
1667 		 * this packet.
1668 		 */
1669 		if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1670 			ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1671 
1672 
1673 		/* Calculate max ticks since the last timestamp */
1674 #define TS_MAXFREQ	1100		/* RFC max TS freq of 1Khz + 10% skew */
1675 #define TS_MICROSECS	1000000		/* microseconds per second */
1676 #ifndef timersub
1677 #define timersub(tvp, uvp, vvp)						\
1678 	do {								\
1679 		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
1680 		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
1681 		if ((vvp)->tv_usec < 0) {				\
1682 			(vvp)->tv_sec--;				\
1683 			(vvp)->tv_usec += 1000000;			\
1684 		}							\
1685 	} while (0)
1686 #endif
1687 
1688 		timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1689 		tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1690 		tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1691 
1692 
1693 		if ((src->state >= TCPS_ESTABLISHED &&
1694 		    dst->state >= TCPS_ESTABLISHED) &&
1695 		    (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1696 		    SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1697 		    (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1698 		    SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1699 			/* Bad RFC1323 implementation or an insertion attack.
1700 			 *
1701 			 * - Solaris 2.6 and 2.7 are known to send another ACK
1702 			 *   after the FIN,FIN|ACK,ACK closing that carries
1703 			 *   an old timestamp.
1704 			 */
1705 
1706 			DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1707 			    SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1708 			    SEQ_GT(tsval, src->scrub->pfss_tsval +
1709 			    tsval_from_last) ? '1' : ' ',
1710 			    SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1711 			    SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1712 			DPFPRINTF((" tsval: %u  tsecr: %u  +ticks: %u  "
1713 			    "idle: %lus %lums\n",
1714 			    tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
1715 			    delta_ts.tv_usec / 1000));
1716 			DPFPRINTF((" src->tsval: %u  tsecr: %u\n",
1717 			    src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1718 			DPFPRINTF((" dst->tsval: %u  tsecr: %u  tsval0: %u"
1719 			    "\n", dst->scrub->pfss_tsval,
1720 			    dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1721 			if (pf_status.debug >= PF_DEBUG_MISC) {
1722 				pf_print_state(state);
1723 				pf_print_flags(th->th_flags);
1724 				kprintf("\n");
1725 			}
1726 			REASON_SET(reason, PFRES_TS);
1727 			return (PF_DROP);
1728 		}
1729 
1730 		/* XXX I'd really like to require tsecr but it's optional */
1731 
1732 	} else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1733 	    ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1734 	    || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1735 	    src->scrub && dst->scrub &&
1736 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1737 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1738 		/* Didn't send a timestamp.  Timestamps aren't really useful
1739 		 * when:
1740 		 *  - connection opening or closing (often not even sent).
1741 		 *    but we must not let an attacker to put a FIN on a
1742 		 *    data packet to sneak it through our ESTABLISHED check.
1743 		 *  - on a TCP reset.  RFC suggests not even looking at TS.
1744 		 *  - on an empty ACK.  The TS will not be echoed so it will
1745 		 *    probably not help keep the RTT calculation in sync and
1746 		 *    there isn't as much danger when the sequence numbers
1747 		 *    got wrapped.  So some stacks don't include TS on empty
1748 		 *    ACKs :-(
1749 		 *
1750 		 * To minimize the disruption to mostly RFC1323 conformant
1751 		 * stacks, we will only require timestamps on data packets.
1752 		 *
1753 		 * And what do ya know, we cannot require timestamps on data
1754 		 * packets.  There appear to be devices that do legitimate
1755 		 * TCP connection hijacking.  There are HTTP devices that allow
1756 		 * a 3whs (with timestamps) and then buffer the HTTP request.
1757 		 * If the intermediate device has the HTTP response cache, it
1758 		 * will spoof the response but not bother timestamping its
1759 		 * packets.  So we can look for the presence of a timestamp in
1760 		 * the first data packet and if there, require it in all future
1761 		 * packets.
1762 		 */
1763 
1764 		if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1765 			/*
1766 			 * Hey!  Someone tried to sneak a packet in.  Or the
1767 			 * stack changed its RFC1323 behavior?!?!
1768 			 */
1769 			if (pf_status.debug >= PF_DEBUG_MISC) {
1770 				DPFPRINTF(("Did not receive expected RFC1323 "
1771 				    "timestamp\n"));
1772 				pf_print_state(state);
1773 				pf_print_flags(th->th_flags);
1774 				kprintf("\n");
1775 			}
1776 			REASON_SET(reason, PFRES_TS);
1777 			return (PF_DROP);
1778 		}
1779 	}
1780 
1781 
1782 	/*
1783 	 * We will note if a host sends his data packets with or without
1784 	 * timestamps.  And require all data packets to contain a timestamp
1785 	 * if the first does.  PAWS implicitly requires that all data packets be
1786 	 * timestamped.  But I think there are middle-man devices that hijack
1787 	 * TCP streams immediately after the 3whs and don't timestamp their
1788 	 * packets (seen in a WWW accelerator or cache).
1789 	 */
1790 	if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1791 	    (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1792 		if (got_ts)
1793 			src->scrub->pfss_flags |= PFSS_DATA_TS;
1794 		else {
1795 			src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1796 			if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1797 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1798 				/* Don't warn if other host rejected RFC1323 */
1799 				DPFPRINTF(("Broken RFC1323 stack did not "
1800 				    "timestamp data packet. Disabled PAWS "
1801 				    "security.\n"));
1802 				pf_print_state(state);
1803 				pf_print_flags(th->th_flags);
1804 				kprintf("\n");
1805 			}
1806 		}
1807 	}
1808 
1809 
1810 	/*
1811 	 * Update PAWS values
1812 	 */
1813 	if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1814 	    (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1815 		getmicrouptime(&src->scrub->pfss_last);
1816 		if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1817 		    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1818 			src->scrub->pfss_tsval = tsval;
1819 
1820 		if (tsecr) {
1821 			if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1822 			    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1823 				src->scrub->pfss_tsecr = tsecr;
1824 
1825 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1826 			    (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1827 			    src->scrub->pfss_tsval0 == 0)) {
1828 				/* tsval0 MUST be the lowest timestamp */
1829 				src->scrub->pfss_tsval0 = tsval;
1830 			}
1831 
1832 			/* Only fully initialized after a TS gets echoed */
1833 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1834 				src->scrub->pfss_flags |= PFSS_PAWS;
1835 		}
1836 	}
1837 
1838 	/* I have a dream....  TCP segment reassembly.... */
1839 	return (0);
1840 }
1841 
1842 int
1843 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1844     int off, sa_family_t af)
1845 {
1846 	u_int16_t	*mss;
1847 	int		 thoff;
1848 	int		 opt, cnt, optlen = 0;
1849 	int		 rewrite = 0;
1850 	u_char		 opts[TCP_MAXOLEN];
1851 	u_char		*optp = opts;
1852 
1853 	thoff = th->th_off << 2;
1854 	cnt = thoff - sizeof(struct tcphdr);
1855 
1856 	if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1857 	    NULL, NULL, af))
1858 		return (rewrite);
1859 
1860 	for (; cnt > 0; cnt -= optlen, optp += optlen) {
1861 		opt = optp[0];
1862 		if (opt == TCPOPT_EOL)
1863 			break;
1864 		if (opt == TCPOPT_NOP)
1865 			optlen = 1;
1866 		else {
1867 			if (cnt < 2)
1868 				break;
1869 			optlen = optp[1];
1870 			if (optlen < 2 || optlen > cnt)
1871 				break;
1872 		}
1873 		switch (opt) {
1874 		case TCPOPT_MAXSEG:
1875 			mss = (u_int16_t *)(optp + 2);
1876 			if ((ntohs(*mss)) > r->max_mss) {
1877 				th->th_sum = pf_cksum_fixup(th->th_sum,
1878 				    *mss, htons(r->max_mss), 0);
1879 				*mss = htons(r->max_mss);
1880 				rewrite = 1;
1881 			}
1882 			break;
1883 		default:
1884 			break;
1885 		}
1886 	}
1887 
1888 	if (rewrite)
1889 		m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1890 
1891 	return (rewrite);
1892 }
1893