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