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