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