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