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