xref: /openbsd/sys/net/pf_norm.c (revision e5dd7070)
1 /*	$OpenBSD: pf_norm.c,v 1.219 2020/06/24 22:03:43 cheloha Exp $ */
2 
3 /*
4  * Copyright 2001 Niels Provos <provos@citi.umich.edu>
5  * Copyright 2009 Henning Brauer <henning@openbsd.org>
6  * Copyright 2011-2018 Alexander Bluhm <bluhm@openbsd.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "pflog.h"
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/mbuf.h>
35 #include <sys/filio.h>
36 #include <sys/fcntl.h>
37 #include <sys/socket.h>
38 #include <sys/kernel.h>
39 #include <sys/time.h>
40 #include <sys/pool.h>
41 #include <sys/syslog.h>
42 #include <sys/mutex.h>
43 
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_pflog.h>
47 
48 #include <netinet/in.h>
49 #include <netinet/ip.h>
50 #include <netinet/ip_var.h>
51 #include <netinet/ip_icmp.h>
52 #include <netinet/tcp.h>
53 #include <netinet/tcp_seq.h>
54 #include <netinet/tcp_fsm.h>
55 #include <netinet/udp.h>
56 
57 #ifdef INET6
58 #include <netinet6/in6_var.h>
59 #include <netinet/ip6.h>
60 #include <netinet6/ip6_var.h>
61 #include <netinet/icmp6.h>
62 #include <netinet6/nd6.h>
63 #endif /* INET6 */
64 
65 #include <net/pfvar.h>
66 #include <net/pfvar_priv.h>
67 
68 struct pf_frent {
69 	TAILQ_ENTRY(pf_frent) fr_next;
70 	struct mbuf	*fe_m;
71 	u_int16_t	 fe_hdrlen;	/* ipv4 header length with ip options
72 					   ipv6, extension, fragment header */
73 	u_int16_t	 fe_extoff;	/* last extension header offset or 0 */
74 	u_int16_t	 fe_len;	/* fragment length */
75 	u_int16_t	 fe_off;	/* fragment offset */
76 	u_int16_t	 fe_mff;	/* more fragment flag */
77 };
78 
79 RB_HEAD(pf_frag_tree, pf_fragment);
80 struct pf_frnode {
81 	struct pf_addr	fn_src;		/* ip source address */
82 	struct pf_addr	fn_dst;		/* ip destination address */
83 	sa_family_t	fn_af;		/* address family */
84 	u_int8_t	fn_proto;	/* protocol for fragments in fn_tree */
85 	u_int8_t	fn_direction;	/* pf packet direction */
86 	u_int32_t	fn_fragments;	/* number of entries in fn_tree */
87 	u_int32_t	fn_gen;		/* fr_gen of newest entry in fn_tree */
88 
89 	RB_ENTRY(pf_frnode) fn_entry;
90 	struct pf_frag_tree fn_tree;	/* matching fragments, lookup by id */
91 };
92 
93 struct pf_fragment {
94 	struct pf_frent	*fr_firstoff[PF_FRAG_ENTRY_POINTS];
95 					/* pointers to queue element */
96 	u_int8_t	fr_entries[PF_FRAG_ENTRY_POINTS];
97 					/* count entries between pointers */
98 	RB_ENTRY(pf_fragment) fr_entry;
99 	TAILQ_ENTRY(pf_fragment) frag_next;
100 	TAILQ_HEAD(pf_fragq, pf_frent) fr_queue;
101 	u_int32_t	fr_id;		/* fragment id for reassemble */
102 	int32_t		fr_timeout;
103 	u_int32_t	fr_gen;		/* generation number (per pf_frnode) */
104 	u_int16_t	fr_maxlen;	/* maximum length of single fragment */
105 	u_int16_t	fr_holes;	/* number of holes in the queue */
106 	struct pf_frnode *fr_node;	/* ip src/dst/proto/af for fragments */
107 };
108 
109 struct pf_fragment_tag {
110 	u_int16_t	 ft_hdrlen;	/* header length of reassembled pkt */
111 	u_int16_t	 ft_extoff;	/* last extension header offset or 0 */
112 	u_int16_t	 ft_maxlen;	/* maximum fragment payload length */
113 };
114 
115 TAILQ_HEAD(pf_fragqueue, pf_fragment)	pf_fragqueue;
116 
117 static __inline int	 pf_frnode_compare(struct pf_frnode *,
118 			    struct pf_frnode *);
119 RB_HEAD(pf_frnode_tree, pf_frnode)	pf_frnode_tree;
120 RB_PROTOTYPE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
121 RB_GENERATE(pf_frnode_tree, pf_frnode, fn_entry, pf_frnode_compare);
122 
123 static __inline int	 pf_frag_compare(struct pf_fragment *,
124 			    struct pf_fragment *);
125 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
126 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
127 
128 /* Private prototypes */
129 void			 pf_flush_fragments(void);
130 void			 pf_free_fragment(struct pf_fragment *);
131 struct pf_fragment	*pf_find_fragment(struct pf_frnode *, u_int32_t);
132 struct pf_frent		*pf_create_fragment(u_short *);
133 int			 pf_frent_holes(struct pf_frent *);
134 static inline int	 pf_frent_index(struct pf_frent *);
135 int			 pf_frent_insert(struct pf_fragment *,
136 			    struct pf_frent *, struct pf_frent *);
137 void			 pf_frent_remove(struct pf_fragment *,
138 			    struct pf_frent *);
139 struct pf_frent		*pf_frent_previous(struct pf_fragment *,
140 			    struct pf_frent *);
141 struct pf_fragment	*pf_fillup_fragment(struct pf_frnode *, u_int32_t,
142 			    struct pf_frent *, u_short *);
143 struct mbuf		*pf_join_fragment(struct pf_fragment *);
144 int			 pf_reassemble(struct mbuf **, int, u_short *);
145 #ifdef INET6
146 int			 pf_reassemble6(struct mbuf **, struct ip6_frag *,
147 			    u_int16_t, u_int16_t, int, u_short *);
148 #endif /* INET6 */
149 
150 /* Globals */
151 struct pool		 pf_frent_pl, pf_frag_pl, pf_frnode_pl;
152 struct pool		 pf_state_scrub_pl;
153 int			 pf_nfrents;
154 
155 #ifdef WITH_PF_LOCK
156 struct mutex		 pf_frag_mtx;
157 
158 #define PF_FRAG_LOCK_INIT()	mtx_init(&pf_frag_mtx, IPL_SOFTNET)
159 #define PF_FRAG_LOCK()		mtx_enter(&pf_frag_mtx)
160 #define PF_FRAG_UNLOCK()	mtx_leave(&pf_frag_mtx)
161 #else /* !WITH_PF_LOCK */
162 #define PF_FRAG_LOCK_INIT()	(void)(0)
163 #define PF_FRAG_LOCK()		(void)(0)
164 #define PF_FRAG_UNLOCK()	(void)(0)
165 #endif /* WITH_PF_LOCK */
166 
167 void
168 pf_normalize_init(void)
169 {
170 	pool_init(&pf_frent_pl, sizeof(struct pf_frent), 0,
171 	    IPL_SOFTNET, 0, "pffrent", NULL);
172 	pool_init(&pf_frnode_pl, sizeof(struct pf_frnode), 0,
173 	    IPL_SOFTNET, 0, "pffrnode", NULL);
174 	pool_init(&pf_frag_pl, sizeof(struct pf_fragment), 0,
175 	    IPL_SOFTNET, 0, "pffrag", NULL);
176 	pool_init(&pf_state_scrub_pl, sizeof(struct pf_state_scrub), 0,
177 	    IPL_SOFTNET, 0, "pfstscr", NULL);
178 
179 	pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
180 	pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
181 
182 	TAILQ_INIT(&pf_fragqueue);
183 
184 	PF_FRAG_LOCK_INIT();
185 }
186 
187 static __inline int
188 pf_frnode_compare(struct pf_frnode *a, struct pf_frnode *b)
189 {
190 	int	diff;
191 
192 	if ((diff = a->fn_proto - b->fn_proto) != 0)
193 		return (diff);
194 	if ((diff = a->fn_af - b->fn_af) != 0)
195 		return (diff);
196 	if ((diff = pf_addr_compare(&a->fn_src, &b->fn_src, a->fn_af)) != 0)
197 		return (diff);
198 	if ((diff = pf_addr_compare(&a->fn_dst, &b->fn_dst, a->fn_af)) != 0)
199 		return (diff);
200 
201 	return (0);
202 }
203 
204 static __inline int
205 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
206 {
207 	int	diff;
208 
209 	if ((diff = a->fr_id - b->fr_id) != 0)
210 		return (diff);
211 
212 	return (0);
213 }
214 
215 void
216 pf_purge_expired_fragments(void)
217 {
218 	struct pf_fragment	*frag;
219 	int32_t			 expire;
220 
221 	PF_ASSERT_UNLOCKED();
222 
223 	expire = getuptime() - pf_default_rule.timeout[PFTM_FRAG];
224 
225 	PF_FRAG_LOCK();
226 	while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
227 		if (frag->fr_timeout > expire)
228 			break;
229 		DPFPRINTF(LOG_NOTICE, "expiring %d(%p)", frag->fr_id, frag);
230 		pf_free_fragment(frag);
231 	}
232 	PF_FRAG_UNLOCK();
233 }
234 
235 /*
236  * Try to flush old fragments to make space for new ones
237  */
238 void
239 pf_flush_fragments(void)
240 {
241 	struct pf_fragment	*frag;
242 	int			 goal;
243 
244 	goal = pf_nfrents * 9 / 10;
245 	DPFPRINTF(LOG_NOTICE, "trying to free > %d frents", pf_nfrents - goal);
246 	while (goal < pf_nfrents) {
247 		if ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) == NULL)
248 			break;
249 		pf_free_fragment(frag);
250 	}
251 }
252 
253 /*
254  * Remove a fragment from the fragment queue, free its fragment entries,
255  * and free the fragment itself.
256  */
257 void
258 pf_free_fragment(struct pf_fragment *frag)
259 {
260 	struct pf_frent		*frent;
261 	struct pf_frnode	*frnode;
262 
263 	frnode = frag->fr_node;
264 	RB_REMOVE(pf_frag_tree, &frnode->fn_tree, frag);
265 	KASSERT(frnode->fn_fragments >= 1);
266 	frnode->fn_fragments--;
267 	if (frnode->fn_fragments == 0) {
268 		KASSERT(RB_EMPTY(&frnode->fn_tree));
269 		RB_REMOVE(pf_frnode_tree, &pf_frnode_tree, frnode);
270 		pool_put(&pf_frnode_pl, frnode);
271 	}
272 	TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
273 
274 	/* Free all fragment entries */
275 	while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
276 		TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
277 		m_freem(frent->fe_m);
278 		pool_put(&pf_frent_pl, frent);
279 		pf_nfrents--;
280 	}
281 	pool_put(&pf_frag_pl, frag);
282 }
283 
284 struct pf_fragment *
285 pf_find_fragment(struct pf_frnode *key, u_int32_t id)
286 {
287 	struct pf_fragment	*frag, idkey;
288 	struct pf_frnode	*frnode;
289 	u_int32_t		 stale;
290 
291 	frnode = RB_FIND(pf_frnode_tree, &pf_frnode_tree, key);
292 	if (frnode == NULL)
293 		return (NULL);
294 	KASSERT(frnode->fn_fragments >= 1);
295 	idkey.fr_id = id;
296 	frag = RB_FIND(pf_frag_tree, &frnode->fn_tree, &idkey);
297 	if (frag == NULL)
298 		return (NULL);
299 	/*
300 	 * Limit the number of fragments we accept for each (proto,src,dst,af)
301 	 * combination (aka pf_frnode), so we can deal better with a high rate
302 	 * of fragments.  Problem analysis is in RFC 4963.
303 	 * Store the current generation for each pf_frnode in fn_gen and on
304 	 * lookup discard 'stale' fragments (pf_fragment, based on the fr_gen
305 	 * member).  Instead of adding another button interpret the pf fragment
306 	 * timeout in multiples of 200 fragments.  This way the default of 60s
307 	 * means: pf_fragment objects older than 60*200 = 12,000 generations
308 	 * are considered stale.
309 	 */
310 	stale = pf_default_rule.timeout[PFTM_FRAG] * PF_FRAG_STALE;
311 	if ((frnode->fn_gen - frag->fr_gen) >= stale) {
312 		DPFPRINTF(LOG_NOTICE, "stale fragment %d(%p), gen %u, num %u",
313 		    frag->fr_id, frag, frag->fr_gen, frnode->fn_fragments);
314 		pf_free_fragment(frag);
315 		return (NULL);
316 	}
317 	TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
318 	TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
319 
320 	return (frag);
321 }
322 
323 struct pf_frent *
324 pf_create_fragment(u_short *reason)
325 {
326 	struct pf_frent	*frent;
327 
328 	frent = pool_get(&pf_frent_pl, PR_NOWAIT);
329 	if (frent == NULL) {
330 		pf_flush_fragments();
331 		frent = pool_get(&pf_frent_pl, PR_NOWAIT);
332 		if (frent == NULL) {
333 			REASON_SET(reason, PFRES_MEMORY);
334 			return (NULL);
335 		}
336 	}
337 	pf_nfrents++;
338 
339 	return (frent);
340 }
341 
342 /*
343  * Calculate the additional holes that were created in the fragment
344  * queue by inserting this fragment.  A fragment in the middle
345  * creates one more hole by splitting.  For each connected side,
346  * it loses one hole.
347  * Fragment entry must be in the queue when calling this function.
348  */
349 int
350 pf_frent_holes(struct pf_frent *frent)
351 {
352 	struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
353 	struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
354 	int holes = 1;
355 
356 	if (prev == NULL) {
357 		if (frent->fe_off == 0)
358 			holes--;
359 	} else {
360 		KASSERT(frent->fe_off != 0);
361 		if (frent->fe_off == prev->fe_off + prev->fe_len)
362 			holes--;
363 	}
364 	if (next == NULL) {
365 		if (!frent->fe_mff)
366 			holes--;
367 	} else {
368 		KASSERT(frent->fe_mff);
369 		if (next->fe_off == frent->fe_off + frent->fe_len)
370 			holes--;
371 	}
372 	return holes;
373 }
374 
375 static inline int
376 pf_frent_index(struct pf_frent *frent)
377 {
378 	/*
379 	 * We have an array of 16 entry points to the queue.  A full size
380 	 * 65535 octet IP packet can have 8192 fragments.  So the queue
381 	 * traversal length is at most 512 and at most 16 entry points are
382 	 * checked.  We need 128 additional bytes on a 64 bit architecture.
383 	 */
384 	CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) ==
385 	    16 - 1);
386 	CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1);
387 
388 	return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS);
389 }
390 
391 int
392 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent,
393     struct pf_frent *prev)
394 {
395 	CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff);
396 	int index;
397 
398 	/*
399 	 * A packet has at most 65536 octets.  With 16 entry points, each one
400 	 * spawns 4096 octets.  We limit these to 64 fragments each, which
401 	 * means on average every fragment must have at least 64 octets.
402 	 */
403 	index = pf_frent_index(frent);
404 	if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT)
405 		return ENOBUFS;
406 	frag->fr_entries[index]++;
407 
408 	if (prev == NULL) {
409 		TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
410 	} else {
411 		KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off);
412 		TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next);
413 	}
414 
415 	if (frag->fr_firstoff[index] == NULL) {
416 		KASSERT(prev == NULL || pf_frent_index(prev) < index);
417 		frag->fr_firstoff[index] = frent;
418 	} else {
419 		if (frent->fe_off < frag->fr_firstoff[index]->fe_off) {
420 			KASSERT(prev == NULL || pf_frent_index(prev) < index);
421 			frag->fr_firstoff[index] = frent;
422 		} else {
423 			KASSERT(prev != NULL);
424 			KASSERT(pf_frent_index(prev) == index);
425 		}
426 	}
427 
428 	frag->fr_holes += pf_frent_holes(frent);
429 
430 	return 0;
431 }
432 
433 void
434 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent)
435 {
436 #ifdef DIAGNOSTIC
437 	struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
438 #endif
439 	struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
440 	int index;
441 
442 	frag->fr_holes -= pf_frent_holes(frent);
443 
444 	index = pf_frent_index(frent);
445 	KASSERT(frag->fr_firstoff[index] != NULL);
446 	if (frag->fr_firstoff[index]->fe_off == frent->fe_off) {
447 		if (next == NULL) {
448 			frag->fr_firstoff[index] = NULL;
449 		} else {
450 			KASSERT(frent->fe_off + frent->fe_len <= next->fe_off);
451 			if (pf_frent_index(next) == index) {
452 				frag->fr_firstoff[index] = next;
453 			} else {
454 				frag->fr_firstoff[index] = NULL;
455 			}
456 		}
457 	} else {
458 		KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off);
459 		KASSERT(prev != NULL);
460 		KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off);
461 		KASSERT(pf_frent_index(prev) == index);
462 	}
463 
464 	TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
465 
466 	KASSERT(frag->fr_entries[index] > 0);
467 	frag->fr_entries[index]--;
468 }
469 
470 struct pf_frent *
471 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent)
472 {
473 	struct pf_frent *prev, *next;
474 	int index;
475 
476 	/*
477 	 * If there are no fragments after frag, take the final one.  Assume
478 	 * that the global queue is not empty.
479 	 */
480 	prev = TAILQ_LAST(&frag->fr_queue, pf_fragq);
481 	KASSERT(prev != NULL);
482 	if (prev->fe_off <= frent->fe_off)
483 		return prev;
484 	/*
485 	 * We want to find a fragment entry that is before frag, but still
486 	 * close to it.  Find the first fragment entry that is in the same
487 	 * entry point or in the first entry point after that.  As we have
488 	 * already checked that there are entries behind frag, this will
489 	 * succeed.
490 	 */
491 	for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS;
492 	    index++) {
493 		prev = frag->fr_firstoff[index];
494 		if (prev != NULL)
495 			break;
496 	}
497 	KASSERT(prev != NULL);
498 	/*
499 	 * In prev we may have a fragment from the same entry point that is
500 	 * before frent, or one that is just one position behind frent.
501 	 * In the latter case, we go back one step and have the predecessor.
502 	 * There may be none if the new fragment will be the first one.
503 	 */
504 	if (prev->fe_off > frent->fe_off) {
505 		prev = TAILQ_PREV(prev, pf_fragq, fr_next);
506 		if (prev == NULL)
507 			return NULL;
508 		KASSERT(prev->fe_off <= frent->fe_off);
509 		return prev;
510 	}
511 	/*
512 	 * In prev is the first fragment of the entry point.  The offset
513 	 * of frag is behind it.  Find the closest previous fragment.
514 	 */
515 	for (next = TAILQ_NEXT(prev, fr_next); next != NULL;
516 	    next = TAILQ_NEXT(next, fr_next)) {
517 		if (next->fe_off > frent->fe_off)
518 			break;
519 		prev = next;
520 	}
521 	return prev;
522 }
523 
524 struct pf_fragment *
525 pf_fillup_fragment(struct pf_frnode *key, u_int32_t id,
526     struct pf_frent *frent, u_short *reason)
527 {
528 	struct pf_frent		*after, *next, *prev;
529 	struct pf_fragment	*frag;
530 	struct pf_frnode	*frnode;
531 	u_int16_t		 total;
532 
533 	/* No empty fragments */
534 	if (frent->fe_len == 0) {
535 		DPFPRINTF(LOG_NOTICE, "bad fragment: len 0");
536 		goto bad_fragment;
537 	}
538 
539 	/* All fragments are 8 byte aligned */
540 	if (frent->fe_mff && (frent->fe_len & 0x7)) {
541 		DPFPRINTF(LOG_NOTICE, "bad fragment: mff and len %d",
542 		    frent->fe_len);
543 		goto bad_fragment;
544 	}
545 
546 	/* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET */
547 	if (frent->fe_off + frent->fe_len > IP_MAXPACKET) {
548 		DPFPRINTF(LOG_NOTICE, "bad fragment: max packet %d",
549 		    frent->fe_off + frent->fe_len);
550 		goto bad_fragment;
551 	}
552 
553 	DPFPRINTF(LOG_INFO, key->fn_af == AF_INET ?
554 	    "reass frag %d @ %d-%d" : "reass frag %#08x @ %d-%d",
555 	    id, frent->fe_off, frent->fe_off + frent->fe_len);
556 
557 	/* Fully buffer all of the fragments in this fragment queue */
558 	frag = pf_find_fragment(key, id);
559 
560 	/* Create a new reassembly queue for this packet */
561 	if (frag == NULL) {
562 		frag = pool_get(&pf_frag_pl, PR_NOWAIT);
563 		if (frag == NULL) {
564 			pf_flush_fragments();
565 			frag = pool_get(&pf_frag_pl, PR_NOWAIT);
566 			if (frag == NULL) {
567 				REASON_SET(reason, PFRES_MEMORY);
568 				goto drop_fragment;
569 			}
570 		}
571 		frnode = RB_FIND(pf_frnode_tree, &pf_frnode_tree, key);
572 		if (frnode == NULL) {
573 			frnode = pool_get(&pf_frnode_pl, PR_NOWAIT);
574 			if (frnode == NULL) {
575 				pf_flush_fragments();
576 				frnode = pool_get(&pf_frnode_pl, PR_NOWAIT);
577 				if (frnode == NULL) {
578 					REASON_SET(reason, PFRES_MEMORY);
579 					pool_put(&pf_frag_pl, frag);
580 					goto drop_fragment;
581 				}
582 			}
583 			*frnode = *key;
584 			RB_INIT(&frnode->fn_tree);
585 			frnode->fn_fragments = 0;
586 			frnode->fn_gen = 0;
587 		}
588 		memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff));
589 		memset(frag->fr_entries, 0, sizeof(frag->fr_entries));
590 		TAILQ_INIT(&frag->fr_queue);
591 		frag->fr_id = id;
592 		frag->fr_timeout = getuptime();
593 		frag->fr_gen = frnode->fn_gen++;
594 		frag->fr_maxlen = frent->fe_len;
595 		frag->fr_holes = 1;
596 		frag->fr_node = frnode;
597 		/* RB_INSERT cannot fail as pf_find_fragment() found nothing */
598 		RB_INSERT(pf_frag_tree, &frnode->fn_tree, frag);
599 		frnode->fn_fragments++;
600 		if (frnode->fn_fragments == 1)
601 			RB_INSERT(pf_frnode_tree, &pf_frnode_tree, frnode);
602 		TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
603 
604 		/* We do not have a previous fragment, cannot fail. */
605 		pf_frent_insert(frag, frent, NULL);
606 
607 		return (frag);
608 	}
609 
610 	KASSERT(!TAILQ_EMPTY(&frag->fr_queue));
611 	KASSERT(frag->fr_node);
612 
613 	/* Remember maximum fragment len for refragmentation */
614 	if (frent->fe_len > frag->fr_maxlen)
615 		frag->fr_maxlen = frent->fe_len;
616 
617 	/* Maximum data we have seen already */
618 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
619 	    TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
620 
621 	/* Non terminal fragments must have more fragments flag */
622 	if (frent->fe_off + frent->fe_len < total && !frent->fe_mff)
623 		goto free_ipv6_fragment;
624 
625 	/* Check if we saw the last fragment already */
626 	if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) {
627 		if (frent->fe_off + frent->fe_len > total ||
628 		    (frent->fe_off + frent->fe_len == total && frent->fe_mff))
629 			goto free_ipv6_fragment;
630 	} else {
631 		if (frent->fe_off + frent->fe_len == total && !frent->fe_mff)
632 			goto free_ipv6_fragment;
633 	}
634 
635 	/* Find neighbors for newly inserted fragment */
636 	prev = pf_frent_previous(frag, frent);
637 	if (prev == NULL) {
638 		after = TAILQ_FIRST(&frag->fr_queue);
639 		KASSERT(after != NULL);
640 	} else {
641 		after = TAILQ_NEXT(prev, fr_next);
642 	}
643 
644 	if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) {
645 		u_int16_t	precut;
646 
647 #ifdef INET6
648 		if (frag->fr_node->fn_af == AF_INET6)
649 			goto free_ipv6_fragment;
650 #endif /* INET6 */
651 
652 		precut = prev->fe_off + prev->fe_len - frent->fe_off;
653 		if (precut >= frent->fe_len) {
654 			DPFPRINTF(LOG_NOTICE, "new frag overlapped");
655 			goto drop_fragment;
656 		}
657 		DPFPRINTF(LOG_NOTICE, "frag head overlap %d", precut);
658 		m_adj(frent->fe_m, precut);
659 		frent->fe_off += precut;
660 		frent->fe_len -= precut;
661 	}
662 
663 	for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off;
664 	    after = next) {
665 		u_int16_t	aftercut;
666 
667 #ifdef INET6
668 		if (frag->fr_node->fn_af == AF_INET6)
669 			goto free_ipv6_fragment;
670 #endif /* INET6 */
671 
672 		aftercut = frent->fe_off + frent->fe_len - after->fe_off;
673 		if (aftercut < after->fe_len) {
674 			DPFPRINTF(LOG_NOTICE, "frag tail overlap %d", aftercut);
675 			m_adj(after->fe_m, aftercut);
676 			after->fe_off += aftercut;
677 			after->fe_len -= aftercut;
678 			break;
679 		}
680 
681 		/* This fragment is completely overlapped, lose it */
682 		DPFPRINTF(LOG_NOTICE, "old frag overlapped");
683 		next = TAILQ_NEXT(after, fr_next);
684 		pf_frent_remove(frag, after);
685 		m_freem(after->fe_m);
686 		pool_put(&pf_frent_pl, after);
687 		pf_nfrents--;
688 	}
689 
690 	/* If part of the queue gets too long, there is not way to recover. */
691 	if (pf_frent_insert(frag, frent, prev)) {
692 		DPFPRINTF(LOG_WARNING, "fragment queue limit exceeded");
693 		goto free_fragment;
694 	}
695 
696 	return (frag);
697 
698 free_ipv6_fragment:
699 	if (frag->fr_node->fn_af == AF_INET)
700 		goto bad_fragment;
701 	/*
702 	 * RFC 5722, Errata 3089:  When reassembling an IPv6 datagram, if one
703 	 * or more its constituent fragments is determined to be an overlapping
704 	 * fragment, the entire datagram (and any constituent fragments) MUST
705 	 * be silently discarded.
706 	 */
707 	DPFPRINTF(LOG_NOTICE, "flush overlapping fragments");
708 free_fragment:
709 	pf_free_fragment(frag);
710 bad_fragment:
711 	REASON_SET(reason, PFRES_FRAG);
712 drop_fragment:
713 	pool_put(&pf_frent_pl, frent);
714 	pf_nfrents--;
715 	return (NULL);
716 }
717 
718 struct mbuf *
719 pf_join_fragment(struct pf_fragment *frag)
720 {
721 	struct mbuf		*m, *m2;
722 	struct pf_frent		*frent;
723 
724 	frent = TAILQ_FIRST(&frag->fr_queue);
725 	TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
726 
727 	m = frent->fe_m;
728 	/* Strip off any trailing bytes */
729 	if ((frent->fe_hdrlen + frent->fe_len) < m->m_pkthdr.len)
730 		m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len);
731 	/* Magic from ip_input */
732 	m2 = m->m_next;
733 	m->m_next = NULL;
734 	m_cat(m, m2);
735 	pool_put(&pf_frent_pl, frent);
736 	pf_nfrents--;
737 
738 	while ((frent = TAILQ_FIRST(&frag->fr_queue)) != NULL) {
739 		TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
740 		m2 = frent->fe_m;
741 		/* Strip off ip header */
742 		m_adj(m2, frent->fe_hdrlen);
743 		/* Strip off any trailing bytes */
744 		if (frent->fe_len < m2->m_pkthdr.len)
745 			m_adj(m2, frent->fe_len - m2->m_pkthdr.len);
746 		pool_put(&pf_frent_pl, frent);
747 		pf_nfrents--;
748 		m_removehdr(m2);
749 		m_cat(m, m2);
750 	}
751 
752 	/* Remove from fragment queue */
753 	pf_free_fragment(frag);
754 
755 	return (m);
756 }
757 
758 int
759 pf_reassemble(struct mbuf **m0, int dir, u_short *reason)
760 {
761 	struct mbuf		*m = *m0;
762 	struct ip		*ip = mtod(m, struct ip *);
763 	struct pf_frent		*frent;
764 	struct pf_fragment	*frag;
765 	struct pf_frnode	 key;
766 	u_int16_t		 total, hdrlen;
767 
768 	/* Get an entry for the fragment queue */
769 	if ((frent = pf_create_fragment(reason)) == NULL)
770 		return (PF_DROP);
771 
772 	frent->fe_m = m;
773 	frent->fe_hdrlen = ip->ip_hl << 2;
774 	frent->fe_extoff = 0;
775 	frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
776 	frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
777 	frent->fe_mff = ntohs(ip->ip_off) & IP_MF;
778 
779 	key.fn_src.v4 = ip->ip_src;
780 	key.fn_dst.v4 = ip->ip_dst;
781 	key.fn_af = AF_INET;
782 	key.fn_proto = ip->ip_p;
783 	key.fn_direction = dir;
784 
785 	PF_FRAG_LOCK();
786 	if ((frag = pf_fillup_fragment(&key, ip->ip_id, frent, reason))
787 	    == NULL) {
788 		PF_FRAG_UNLOCK();
789 		return (PF_DROP);
790 	}
791 
792 	/* The mbuf is part of the fragment entry, no direct free or access */
793 	m = *m0 = NULL;
794 
795 	if (frag->fr_holes) {
796 		DPFPRINTF(LOG_DEBUG, "frag %d, holes %d",
797 		    frag->fr_id, frag->fr_holes);
798 		PF_FRAG_UNLOCK();
799 		return (PF_PASS);  /* drop because *m0 is NULL, no error */
800 	}
801 
802 	/* We have all the data */
803 	frent = TAILQ_FIRST(&frag->fr_queue);
804 	KASSERT(frent != NULL);
805 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
806 	    TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
807 	hdrlen = frent->fe_hdrlen;
808 	m = *m0 = pf_join_fragment(frag);
809 	frag = NULL;
810 	m_calchdrlen(m);
811 
812 	ip = mtod(m, struct ip *);
813 	ip->ip_len = htons(hdrlen + total);
814 	ip->ip_off &= ~(IP_MF|IP_OFFMASK);
815 
816 	if (hdrlen + total > IP_MAXPACKET) {
817 		PF_FRAG_UNLOCK();
818 		DPFPRINTF(LOG_NOTICE, "drop: too big: %d", total);
819 		ip->ip_len = 0;
820 		REASON_SET(reason, PFRES_SHORT);
821 		/* PF_DROP requires a valid mbuf *m0 in pf_test() */
822 		return (PF_DROP);
823 	}
824 
825 	PF_FRAG_UNLOCK();
826 	DPFPRINTF(LOG_INFO, "complete: %p(%d)", m, ntohs(ip->ip_len));
827 	return (PF_PASS);
828 }
829 
830 #ifdef INET6
831 int
832 pf_reassemble6(struct mbuf **m0, struct ip6_frag *fraghdr,
833     u_int16_t hdrlen, u_int16_t extoff, int dir, u_short *reason)
834 {
835 	struct mbuf		*m = *m0;
836 	struct ip6_hdr		*ip6 = mtod(m, struct ip6_hdr *);
837 	struct m_tag		*mtag;
838 	struct pf_fragment_tag	*ftag;
839 	struct pf_frent		*frent;
840 	struct pf_fragment	*frag;
841 	struct pf_frnode	 key;
842 	int			 off;
843 	u_int16_t		 total, maxlen;
844 	u_int8_t		 proto;
845 
846 	/* Get an entry for the fragment queue */
847 	if ((frent = pf_create_fragment(reason)) == NULL)
848 		return (PF_DROP);
849 
850 	frent->fe_m = m;
851 	frent->fe_hdrlen = hdrlen;
852 	frent->fe_extoff = extoff;
853 	frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen;
854 	frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK);
855 	frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG;
856 
857 	key.fn_src.v6 = ip6->ip6_src;
858 	key.fn_dst.v6 = ip6->ip6_dst;
859 	key.fn_af = AF_INET6;
860 	/* Only the first fragment's protocol is relevant */
861 	key.fn_proto = 0;
862 	key.fn_direction = dir;
863 
864 	PF_FRAG_LOCK();
865 	if ((frag = pf_fillup_fragment(&key, fraghdr->ip6f_ident, frent,
866 	    reason)) == NULL) {
867 		PF_FRAG_UNLOCK();
868 		return (PF_DROP);
869 	}
870 
871 	/* The mbuf is part of the fragment entry, no direct free or access */
872 	m = *m0 = NULL;
873 
874 	if (frag->fr_holes) {
875 		DPFPRINTF(LOG_DEBUG, "frag %#08x, holes %d",
876 		    frag->fr_id, frag->fr_holes);
877 		PF_FRAG_UNLOCK();
878 		return (PF_PASS);  /* drop because *m0 is NULL, no error */
879 	}
880 
881 	/* We have all the data */
882 	frent = TAILQ_FIRST(&frag->fr_queue);
883 	KASSERT(frent != NULL);
884 	extoff = frent->fe_extoff;
885 	maxlen = frag->fr_maxlen;
886 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
887 	    TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
888 	hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
889 	m = *m0 = pf_join_fragment(frag);
890 	frag = NULL;
891 
892 	/* Take protocol from first fragment header */
893 	if ((m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt),
894 	    &off)) == NULL)
895 		panic("%s: short frag mbuf chain", __func__);
896 	proto = *(mtod(m, caddr_t) + off);
897 	m = *m0;
898 
899 	/* Delete frag6 header */
900 	if (frag6_deletefraghdr(m, hdrlen) != 0)
901 		goto fail;
902 
903 	m_calchdrlen(m);
904 
905 	if ((mtag = m_tag_get(PACKET_TAG_PF_REASSEMBLED, sizeof(struct
906 	    pf_fragment_tag), M_NOWAIT)) == NULL)
907 		goto fail;
908 	ftag = (struct pf_fragment_tag *)(mtag + 1);
909 	ftag->ft_hdrlen = hdrlen;
910 	ftag->ft_extoff = extoff;
911 	ftag->ft_maxlen = maxlen;
912 	m_tag_prepend(m, mtag);
913 
914 	ip6 = mtod(m, struct ip6_hdr *);
915 	ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
916 	if (extoff) {
917 		/* Write protocol into next field of last extension header */
918 		if ((m = m_getptr(m, extoff + offsetof(struct ip6_ext,
919 		    ip6e_nxt), &off)) == NULL)
920 			panic("%s: short ext mbuf chain", __func__);
921 		*(mtod(m, caddr_t) + off) = proto;
922 		m = *m0;
923 	} else
924 		ip6->ip6_nxt = proto;
925 
926 	if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
927 		PF_FRAG_UNLOCK();
928 		DPFPRINTF(LOG_NOTICE, "drop: too big: %d", total);
929 		ip6->ip6_plen = 0;
930 		REASON_SET(reason, PFRES_SHORT);
931 		/* PF_DROP requires a valid mbuf *m0 in pf_test6() */
932 		return (PF_DROP);
933 	}
934 	PF_FRAG_UNLOCK();
935 
936 	DPFPRINTF(LOG_INFO, "complete: %p(%d)", m, ntohs(ip6->ip6_plen));
937 	return (PF_PASS);
938 
939 fail:
940 	PF_FRAG_UNLOCK();
941 	REASON_SET(reason, PFRES_MEMORY);
942 	/* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later */
943 	return (PF_DROP);
944 }
945 
946 int
947 pf_refragment6(struct mbuf **m0, struct m_tag *mtag, struct sockaddr_in6 *dst,
948     struct ifnet *ifp, struct rtentry *rt)
949 {
950 	struct mbuf		*m = *m0, *t;
951 	struct pf_fragment_tag	*ftag = (struct pf_fragment_tag *)(mtag + 1);
952 	u_int32_t		 mtu;
953 	u_int16_t		 hdrlen, extoff, maxlen;
954 	u_int8_t		 proto;
955 	int			 error, action;
956 
957 	hdrlen = ftag->ft_hdrlen;
958 	extoff = ftag->ft_extoff;
959 	maxlen = ftag->ft_maxlen;
960 	m_tag_delete(m, mtag);
961 	mtag = NULL;
962 	ftag = NULL;
963 
964 	/* Checksum must be calculated for the whole packet */
965 	in6_proto_cksum_out(m, NULL);
966 
967 	if (extoff) {
968 		int off;
969 
970 		/* Use protocol from next field of last extension header */
971 		if ((m = m_getptr(m, extoff + offsetof(struct ip6_ext,
972 		    ip6e_nxt), &off)) == NULL)
973 			panic("%s: short ext mbuf chain", __func__);
974 		proto = *(mtod(m, caddr_t) + off);
975 		*(mtod(m, caddr_t) + off) = IPPROTO_FRAGMENT;
976 		m = *m0;
977 	} else {
978 		struct ip6_hdr *hdr;
979 
980 		hdr = mtod(m, struct ip6_hdr *);
981 		proto = hdr->ip6_nxt;
982 		hdr->ip6_nxt = IPPROTO_FRAGMENT;
983 	}
984 
985 	/*
986 	 * Maxlen may be less than 8 iff there was only a single
987 	 * fragment.  As it was fragmented before, add a fragment
988 	 * header also for a single fragment.  If total or maxlen
989 	 * is less than 8, ip6_fragment() will return EMSGSIZE and
990 	 * we drop the packet.
991 	 */
992 	mtu = hdrlen + sizeof(struct ip6_frag) + maxlen;
993 	error = ip6_fragment(m, hdrlen, proto, mtu);
994 
995 	m = (*m0)->m_nextpkt;
996 	(*m0)->m_nextpkt = NULL;
997 	if (error == 0) {
998 		/* The first mbuf contains the unfragmented packet */
999 		m_freemp(m0);
1000 		action = PF_PASS;
1001 	} else {
1002 		/* Drop expects an mbuf to free */
1003 		DPFPRINTF(LOG_NOTICE, "refragment error %d", error);
1004 		action = PF_DROP;
1005 	}
1006 
1007 	for (t = m; m; m = t) {
1008 		t = m->m_nextpkt;
1009 		m->m_nextpkt = NULL;
1010 		m->m_pkthdr.pf.flags |= PF_TAG_REFRAGMENTED;
1011 		if (error == 0) {
1012 			if (ifp == NULL) {
1013 				ip6_forward(m, NULL, 0);
1014 			} else if ((u_long)m->m_pkthdr.len <= ifp->if_mtu) {
1015 				ifp->if_output(ifp, m, sin6tosa(dst), rt);
1016 			} else {
1017 				icmp6_error(m, ICMP6_PACKET_TOO_BIG, 0,
1018 				    ifp->if_mtu);
1019 			}
1020 		} else {
1021 			m_freem(m);
1022 		}
1023 	}
1024 
1025 	return (action);
1026 }
1027 #endif /* INET6 */
1028 
1029 int
1030 pf_normalize_ip(struct pf_pdesc *pd, u_short *reason)
1031 {
1032 	struct ip	*h = mtod(pd->m, struct ip *);
1033 	u_int16_t	 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1034 	u_int16_t	 mff = (ntohs(h->ip_off) & IP_MF);
1035 
1036 	if (!fragoff && !mff)
1037 		goto no_fragment;
1038 
1039 	/* Clear IP_DF if we're in no-df mode */
1040 	if (pf_status.reass & PF_REASS_NODF && h->ip_off & htons(IP_DF))
1041 		h->ip_off &= htons(~IP_DF);
1042 
1043 	/* We're dealing with a fragment now. Don't allow fragments
1044 	 * with IP_DF to enter the cache. If the flag was cleared by
1045 	 * no-df above, fine. Otherwise drop it.
1046 	 */
1047 	if (h->ip_off & htons(IP_DF)) {
1048 		DPFPRINTF(LOG_NOTICE, "bad fragment: IP_DF");
1049 		REASON_SET(reason, PFRES_FRAG);
1050 		return (PF_DROP);
1051 	}
1052 
1053 	if (!pf_status.reass)
1054 		return (PF_PASS);	/* no reassembly */
1055 
1056 	/* Returns PF_DROP or m is NULL or completely reassembled mbuf */
1057 	if (pf_reassemble(&pd->m, pd->dir, reason) != PF_PASS)
1058 		return (PF_DROP);
1059 	if (pd->m == NULL)
1060 		return (PF_PASS);  /* packet has been reassembled, no error */
1061 
1062 	h = mtod(pd->m, struct ip *);
1063 
1064 no_fragment:
1065 	/* At this point, only IP_DF is allowed in ip_off */
1066 	if (h->ip_off & ~htons(IP_DF))
1067 		h->ip_off &= htons(IP_DF);
1068 
1069 	return (PF_PASS);
1070 }
1071 
1072 #ifdef INET6
1073 int
1074 pf_normalize_ip6(struct pf_pdesc *pd, u_short *reason)
1075 {
1076 	struct ip6_frag		 frag;
1077 
1078 	if (pd->fragoff == 0)
1079 		goto no_fragment;
1080 
1081 	if (!pf_pull_hdr(pd->m, pd->fragoff, &frag, sizeof(frag), NULL, reason,
1082 	    AF_INET6))
1083 		return (PF_DROP);
1084 
1085 	if (!pf_status.reass)
1086 		return (PF_PASS);	/* no reassembly */
1087 
1088 	/* Returns PF_DROP or m is NULL or completely reassembled mbuf */
1089 	if (pf_reassemble6(&pd->m, &frag, pd->fragoff + sizeof(frag),
1090 	    pd->extoff, pd->dir, reason) != PF_PASS)
1091 		return (PF_DROP);
1092 	if (pd->m == NULL)
1093 		return (PF_PASS);  /* packet has been reassembled, no error */
1094 
1095 no_fragment:
1096 	return (PF_PASS);
1097 }
1098 #endif /* INET6 */
1099 
1100 int
1101 pf_normalize_tcp(struct pf_pdesc *pd)
1102 {
1103 	struct tcphdr	*th = &pd->hdr.tcp;
1104 	u_short		 reason;
1105 	u_int8_t	 flags;
1106 	u_int		 rewrite = 0;
1107 
1108 	flags = th->th_flags;
1109 	if (flags & TH_SYN) {
1110 		/* Illegal packet */
1111 		if (flags & TH_RST)
1112 			goto tcp_drop;
1113 
1114 		if (flags & TH_FIN)	/* XXX why clear instead of drop? */
1115 			flags &= ~TH_FIN;
1116 	} else {
1117 		/* Illegal packet */
1118 		if (!(flags & (TH_ACK|TH_RST)))
1119 			goto tcp_drop;
1120 	}
1121 
1122 	if (!(flags & TH_ACK)) {
1123 		/* These flags are only valid if ACK is set */
1124 		if (flags & (TH_FIN|TH_PUSH|TH_URG))
1125 			goto tcp_drop;
1126 	}
1127 
1128 	/* If flags changed, or reserved data set, then adjust */
1129 	if (flags != th->th_flags || th->th_x2 != 0) {
1130 		/* hack: set 4-bit th_x2 = 0 */
1131 		u_int8_t *th_off = (u_int8_t*)(&th->th_ack+1);
1132 		pf_patch_8(pd, th_off, th->th_off << 4, PF_HI);
1133 
1134 		pf_patch_8(pd, &th->th_flags, flags, PF_LO);
1135 		rewrite = 1;
1136 	}
1137 
1138 	/* Remove urgent pointer, if TH_URG is not set */
1139 	if (!(flags & TH_URG) && th->th_urp) {
1140 		pf_patch_16(pd, &th->th_urp, 0);
1141 		rewrite = 1;
1142 	}
1143 
1144 	/* copy back packet headers if we sanitized */
1145 	if (rewrite) {
1146 		m_copyback(pd->m, pd->off, sizeof(*th), th, M_NOWAIT);
1147 	}
1148 
1149 	return (PF_PASS);
1150 
1151 tcp_drop:
1152 	REASON_SET(&reason, PFRES_NORM);
1153 	return (PF_DROP);
1154 }
1155 
1156 int
1157 pf_normalize_tcp_init(struct pf_pdesc *pd, struct pf_state_peer *src)
1158 {
1159 	struct tcphdr	*th = &pd->hdr.tcp;
1160 	u_int32_t	 tsval, tsecr;
1161 	int		 olen;
1162 	u_int8_t	 opts[MAX_TCPOPTLEN], *opt;
1163 
1164 
1165 	KASSERT(src->scrub == NULL);
1166 
1167 	src->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
1168 	if (src->scrub == NULL)
1169 		return (1);
1170 	memset(src->scrub, 0, sizeof(*src->scrub));
1171 
1172 	switch (pd->af) {
1173 	case AF_INET: {
1174 		struct ip *h = mtod(pd->m, struct ip *);
1175 		src->scrub->pfss_ttl = h->ip_ttl;
1176 		break;
1177 	}
1178 #ifdef INET6
1179 	case AF_INET6: {
1180 		struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1181 		src->scrub->pfss_ttl = h->ip6_hlim;
1182 		break;
1183 	}
1184 #endif /* INET6 */
1185 	default:
1186 		unhandled_af(pd->af);
1187 	}
1188 
1189 	/*
1190 	 * All normalizations below are only begun if we see the start of
1191 	 * the connections.  They must all set an enabled bit in pfss_flags
1192 	 */
1193 	if ((th->th_flags & TH_SYN) == 0)
1194 		return (0);
1195 
1196 	olen = (th->th_off << 2) - sizeof(*th);
1197 	if (olen < TCPOLEN_TIMESTAMP || !pf_pull_hdr(pd->m,
1198 	    pd->off + sizeof(*th), opts, olen, NULL, NULL, pd->af))
1199 		return (0);
1200 
1201 	opt = opts;
1202 	while ((opt = pf_find_tcpopt(opt, opts, olen,
1203 		    TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1204 
1205 		src->scrub->pfss_flags |= PFSS_TIMESTAMP;
1206 		src->scrub->pfss_ts_mod = arc4random();
1207 		/* note PFSS_PAWS not set yet */
1208 		memcpy(&tsval, &opt[2], sizeof(u_int32_t));
1209 		memcpy(&tsecr, &opt[6], sizeof(u_int32_t));
1210 		src->scrub->pfss_tsval0 = ntohl(tsval);
1211 		src->scrub->pfss_tsval = ntohl(tsval);
1212 		src->scrub->pfss_tsecr = ntohl(tsecr);
1213 		getmicrouptime(&src->scrub->pfss_last);
1214 
1215 		opt += opt[1];
1216 	}
1217 
1218 	return (0);
1219 }
1220 
1221 void
1222 pf_normalize_tcp_cleanup(struct pf_state *state)
1223 {
1224 	if (state->src.scrub)
1225 		pool_put(&pf_state_scrub_pl, state->src.scrub);
1226 	if (state->dst.scrub)
1227 		pool_put(&pf_state_scrub_pl, state->dst.scrub);
1228 
1229 	/* Someday... flush the TCP segment reassembly descriptors. */
1230 }
1231 
1232 int
1233 pf_normalize_tcp_stateful(struct pf_pdesc *pd, u_short *reason,
1234     struct pf_state *state, struct pf_state_peer *src,
1235     struct pf_state_peer *dst, int *writeback)
1236 {
1237 	struct tcphdr	*th = &pd->hdr.tcp;
1238 	struct timeval	 uptime;
1239 	u_int		 tsval_from_last;
1240 	u_int32_t	 tsval, tsecr;
1241 	int		 copyback = 0;
1242 	int		 got_ts = 0;
1243 	int		 olen;
1244 	u_int8_t	 opts[MAX_TCPOPTLEN], *opt;
1245 
1246 	KASSERT(src->scrub || dst->scrub);
1247 
1248 	/*
1249 	 * Enforce the minimum TTL seen for this connection.  Negate a common
1250 	 * technique to evade an intrusion detection system and confuse
1251 	 * firewall state code.
1252 	 */
1253 	switch (pd->af) {
1254 	case AF_INET:
1255 		if (src->scrub) {
1256 			struct ip *h = mtod(pd->m, struct ip *);
1257 			if (h->ip_ttl > src->scrub->pfss_ttl)
1258 				src->scrub->pfss_ttl = h->ip_ttl;
1259 			h->ip_ttl = src->scrub->pfss_ttl;
1260 		}
1261 		break;
1262 #ifdef INET6
1263 	case AF_INET6:
1264 		if (src->scrub) {
1265 			struct ip6_hdr *h = mtod(pd->m, struct ip6_hdr *);
1266 			if (h->ip6_hlim > src->scrub->pfss_ttl)
1267 				src->scrub->pfss_ttl = h->ip6_hlim;
1268 			h->ip6_hlim = src->scrub->pfss_ttl;
1269 		}
1270 		break;
1271 #endif /* INET6 */
1272 	default:
1273 		unhandled_af(pd->af);
1274 	}
1275 
1276 	olen = (th->th_off << 2) - sizeof(*th);
1277 
1278 	if (olen >= TCPOLEN_TIMESTAMP &&
1279 	    ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1280 	    (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1281 	    pf_pull_hdr(pd->m, pd->off + sizeof(*th), opts, olen, NULL, NULL,
1282 	    pd->af)) {
1283 
1284 		/* Modulate the timestamps.  Can be used for NAT detection, OS
1285 		 * uptime determination or reboot detection.
1286 		 */
1287 		opt = opts;
1288 		while ((opt = pf_find_tcpopt(opt, opts, olen,
1289 			    TCPOPT_TIMESTAMP, TCPOLEN_TIMESTAMP)) != NULL) {
1290 
1291 			u_int8_t *ts = opt + 2;
1292 			u_int8_t *tsr = opt + 6;
1293 
1294 			if (got_ts) {
1295 				/* Huh?  Multiple timestamps!? */
1296 				if (pf_status.debug >= LOG_NOTICE) {
1297 					log(LOG_NOTICE,
1298 					    "pf: %s: multiple TS??", __func__);
1299 					pf_print_state(state);
1300 					addlog("\n");
1301 				}
1302 				REASON_SET(reason, PFRES_TS);
1303 				return (PF_DROP);
1304 			}
1305 
1306 			memcpy(&tsval, ts, sizeof(u_int32_t));
1307 			memcpy(&tsecr, tsr, sizeof(u_int32_t));
1308 
1309 			/* modulate TS */
1310 			if (tsval && src->scrub &&
1311 			    (src->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1312 				/* tsval used further on */
1313 				tsval = ntohl(tsval);
1314 				pf_patch_32_unaligned(pd,
1315 				    ts, htonl(tsval + src->scrub->pfss_ts_mod),
1316 				    PF_ALGNMNT(ts - opts));
1317 				copyback = 1;
1318 			}
1319 
1320 			/* modulate TS reply if any (!0) */
1321 			if (tsecr && dst->scrub &&
1322 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1323 				/* tsecr used further on */
1324 				tsecr = ntohl(tsecr) - dst->scrub->pfss_ts_mod;
1325 				pf_patch_32_unaligned(pd,
1326 				    tsr, htonl(tsecr), PF_ALGNMNT(tsr - opts));
1327 				copyback = 1;
1328 			}
1329 
1330 			got_ts = 1;
1331 			opt += opt[1];
1332 		}
1333 
1334 		if (copyback) {
1335 			/* Copyback the options, caller copys back header */
1336 			*writeback = 1;
1337 			m_copyback(pd->m, pd->off + sizeof(*th), olen, opts, M_NOWAIT);
1338 		}
1339 	}
1340 
1341 
1342 	/*
1343 	 * Must invalidate PAWS checks on connections idle for too long.
1344 	 * The fastest allowed timestamp clock is 1ms.  That turns out to
1345 	 * be about 24 days before it wraps.  XXX Right now our lowerbound
1346 	 * TS echo check only works for the first 12 days of a connection
1347 	 * when the TS has exhausted half its 32bit space
1348 	 */
1349 #define TS_MAX_IDLE	(24*24*60*60)
1350 #define TS_MAX_CONN	(12*24*60*60)	/* XXX remove when better tsecr check */
1351 
1352 	getmicrouptime(&uptime);
1353 	if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1354 	    (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1355 	    getuptime() - state->creation > TS_MAX_CONN))  {
1356 		if (pf_status.debug >= LOG_NOTICE) {
1357 			log(LOG_NOTICE, "pf: src idled out of PAWS ");
1358 			pf_print_state(state);
1359 			addlog("\n");
1360 		}
1361 		src->scrub->pfss_flags =
1362 		    (src->scrub->pfss_flags & ~PFSS_PAWS) | PFSS_PAWS_IDLED;
1363 	}
1364 	if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1365 	    uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1366 		if (pf_status.debug >= LOG_NOTICE) {
1367 			log(LOG_NOTICE, "pf: dst idled out of PAWS ");
1368 			pf_print_state(state);
1369 			addlog("\n");
1370 		}
1371 		dst->scrub->pfss_flags =
1372 		    (dst->scrub->pfss_flags & ~PFSS_PAWS) | PFSS_PAWS_IDLED;
1373 	}
1374 
1375 	if (got_ts && src->scrub && dst->scrub &&
1376 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1377 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1378 		/* Validate that the timestamps are "in-window".
1379 		 * RFC1323 describes TCP Timestamp options that allow
1380 		 * measurement of RTT (round trip time) and PAWS
1381 		 * (protection against wrapped sequence numbers).  PAWS
1382 		 * gives us a set of rules for rejecting packets on
1383 		 * long fat pipes (packets that were somehow delayed
1384 		 * in transit longer than the time it took to send the
1385 		 * full TCP sequence space of 4Gb).  We can use these
1386 		 * rules and infer a few others that will let us treat
1387 		 * the 32bit timestamp and the 32bit echoed timestamp
1388 		 * as sequence numbers to prevent a blind attacker from
1389 		 * inserting packets into a connection.
1390 		 *
1391 		 * RFC1323 tells us:
1392 		 *  - The timestamp on this packet must be greater than
1393 		 *    or equal to the last value echoed by the other
1394 		 *    endpoint.  The RFC says those will be discarded
1395 		 *    since it is a dup that has already been acked.
1396 		 *    This gives us a lowerbound on the timestamp.
1397 		 *        timestamp >= other last echoed timestamp
1398 		 *  - The timestamp will be less than or equal to
1399 		 *    the last timestamp plus the time between the
1400 		 *    last packet and now.  The RFC defines the max
1401 		 *    clock rate as 1ms.  We will allow clocks to be
1402 		 *    up to 10% fast and will allow a total difference
1403 		 *    or 30 seconds due to a route change.  And this
1404 		 *    gives us an upperbound on the timestamp.
1405 		 *        timestamp <= last timestamp + max ticks
1406 		 *    We have to be careful here.  Windows will send an
1407 		 *    initial timestamp of zero and then initialize it
1408 		 *    to a random value after the 3whs; presumably to
1409 		 *    avoid a DoS by having to call an expensive RNG
1410 		 *    during a SYN flood.  Proof MS has at least one
1411 		 *    good security geek.
1412 		 *
1413 		 *  - The TCP timestamp option must also echo the other
1414 		 *    endpoints timestamp.  The timestamp echoed is the
1415 		 *    one carried on the earliest unacknowledged segment
1416 		 *    on the left edge of the sequence window.  The RFC
1417 		 *    states that the host will reject any echoed
1418 		 *    timestamps that were larger than any ever sent.
1419 		 *    This gives us an upperbound on the TS echo.
1420 		 *        tescr <= largest_tsval
1421 		 *  - The lowerbound on the TS echo is a little more
1422 		 *    tricky to determine.  The other endpoint's echoed
1423 		 *    values will not decrease.  But there may be
1424 		 *    network conditions that re-order packets and
1425 		 *    cause our view of them to decrease.  For now the
1426 		 *    only lowerbound we can safely determine is that
1427 		 *    the TS echo will never be less than the original
1428 		 *    TS.  XXX There is probably a better lowerbound.
1429 		 *    Remove TS_MAX_CONN with better lowerbound check.
1430 		 *        tescr >= other original TS
1431 		 *
1432 		 * It is also important to note that the fastest
1433 		 * timestamp clock of 1ms will wrap its 32bit space in
1434 		 * 24 days.  So we just disable TS checking after 24
1435 		 * days of idle time.  We actually must use a 12d
1436 		 * connection limit until we can come up with a better
1437 		 * lowerbound to the TS echo check.
1438 		 */
1439 		struct timeval	delta_ts;
1440 		int		ts_fudge;
1441 
1442 		/*
1443 		 * PFTM_TS_DIFF is how many seconds of leeway to allow
1444 		 * a host's timestamp.  This can happen if the previous
1445 		 * packet got delayed in transit for much longer than
1446 		 * this packet.
1447 		 */
1448 		if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1449 			ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1450 
1451 		/* Calculate max ticks since the last timestamp */
1452 #define TS_MAXFREQ	1100		/* RFC max TS freq of 1Khz + 10% skew */
1453 #define TS_MICROSECS	1000000		/* microseconds per second */
1454 		timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1455 		tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1456 		tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1457 
1458 		if ((src->state >= TCPS_ESTABLISHED &&
1459 		    dst->state >= TCPS_ESTABLISHED) &&
1460 		    (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1461 		    SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1462 		    (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1463 		    SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1464 			/* Bad RFC1323 implementation or an insertion attack.
1465 			 *
1466 			 * - Solaris 2.6 and 2.7 are known to send another ACK
1467 			 *   after the FIN,FIN|ACK,ACK closing that carries
1468 			 *   an old timestamp.
1469 			 */
1470 
1471 			DPFPRINTF(LOG_NOTICE, "Timestamp failed %c%c%c%c",
1472 			    SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1473 			    SEQ_GT(tsval, src->scrub->pfss_tsval +
1474 			    tsval_from_last) ? '1' : ' ',
1475 			    SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1476 			    SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' ');
1477 			DPFPRINTF(LOG_NOTICE, " tsval: %u  tsecr: %u  "
1478 			    "+ticks: %u  idle: %llu.%06lus", tsval, tsecr,
1479 			    tsval_from_last, (long long)delta_ts.tv_sec,
1480 			    delta_ts.tv_usec);
1481 			DPFPRINTF(LOG_NOTICE, " src->tsval: %u  tsecr: %u",
1482 			    src->scrub->pfss_tsval, src->scrub->pfss_tsecr);
1483 			DPFPRINTF(LOG_NOTICE, " dst->tsval: %u  tsecr: %u  "
1484 			    "tsval0: %u", dst->scrub->pfss_tsval,
1485 			    dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0);
1486 			if (pf_status.debug >= LOG_NOTICE) {
1487 				log(LOG_NOTICE, "pf: ");
1488 				pf_print_state(state);
1489 				pf_print_flags(th->th_flags);
1490 				addlog("\n");
1491 			}
1492 			REASON_SET(reason, PFRES_TS);
1493 			return (PF_DROP);
1494 		}
1495 		/* XXX I'd really like to require tsecr but it's optional */
1496 	} else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1497 	    ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1498 	    || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1499 	    src->scrub && dst->scrub &&
1500 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1501 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1502 		/* Didn't send a timestamp.  Timestamps aren't really useful
1503 		 * when:
1504 		 *  - connection opening or closing (often not even sent).
1505 		 *    but we must not let an attacker to put a FIN on a
1506 		 *    data packet to sneak it through our ESTABLISHED check.
1507 		 *  - on a TCP reset.  RFC suggests not even looking at TS.
1508 		 *  - on an empty ACK.  The TS will not be echoed so it will
1509 		 *    probably not help keep the RTT calculation in sync and
1510 		 *    there isn't as much danger when the sequence numbers
1511 		 *    got wrapped.  So some stacks don't include TS on empty
1512 		 *    ACKs :-(
1513 		 *
1514 		 * To minimize the disruption to mostly RFC1323 conformant
1515 		 * stacks, we will only require timestamps on data packets.
1516 		 *
1517 		 * And what do ya know, we cannot require timestamps on data
1518 		 * packets.  There appear to be devices that do legitimate
1519 		 * TCP connection hijacking.  There are HTTP devices that allow
1520 		 * a 3whs (with timestamps) and then buffer the HTTP request.
1521 		 * If the intermediate device has the HTTP response cache, it
1522 		 * will spoof the response but not bother timestamping its
1523 		 * packets.  So we can look for the presence of a timestamp in
1524 		 * the first data packet and if there, require it in all future
1525 		 * packets.
1526 		 */
1527 
1528 		if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1529 			/*
1530 			 * Hey!  Someone tried to sneak a packet in.  Or the
1531 			 * stack changed its RFC1323 behavior?!?!
1532 			 */
1533 			if (pf_status.debug >= LOG_NOTICE) {
1534 				log(LOG_NOTICE,
1535 				    "pf: did not receive expected RFC1323 "
1536 				    "timestamp");
1537 				pf_print_state(state);
1538 				pf_print_flags(th->th_flags);
1539 				addlog("\n");
1540 			}
1541 			REASON_SET(reason, PFRES_TS);
1542 			return (PF_DROP);
1543 		}
1544 	}
1545 
1546 	/*
1547 	 * We will note if a host sends his data packets with or without
1548 	 * timestamps.  And require all data packets to contain a timestamp
1549 	 * if the first does.  PAWS implicitly requires that all data packets be
1550 	 * timestamped.  But I think there are middle-man devices that hijack
1551 	 * TCP streams immediately after the 3whs and don't timestamp their
1552 	 * packets (seen in a WWW accelerator or cache).
1553 	 */
1554 	if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1555 	    (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1556 		if (got_ts)
1557 			src->scrub->pfss_flags |= PFSS_DATA_TS;
1558 		else {
1559 			src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1560 			if (pf_status.debug >= LOG_NOTICE && dst->scrub &&
1561 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1562 				/* Don't warn if other host rejected RFC1323 */
1563 				log(LOG_NOTICE,
1564 				    "pf: broken RFC1323 stack did not "
1565 				    "timestamp data packet. Disabled PAWS "
1566 				    "security.");
1567 				pf_print_state(state);
1568 				pf_print_flags(th->th_flags);
1569 				addlog("\n");
1570 			}
1571 		}
1572 	}
1573 
1574 	/*
1575 	 * Update PAWS values
1576 	 */
1577 	if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1578 	    (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1579 		getmicrouptime(&src->scrub->pfss_last);
1580 		if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1581 		    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1582 			src->scrub->pfss_tsval = tsval;
1583 
1584 		if (tsecr) {
1585 			if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1586 			    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1587 				src->scrub->pfss_tsecr = tsecr;
1588 
1589 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1590 			    (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1591 			    src->scrub->pfss_tsval0 == 0)) {
1592 				/* tsval0 MUST be the lowest timestamp */
1593 				src->scrub->pfss_tsval0 = tsval;
1594 			}
1595 
1596 			/* Only fully initialized after a TS gets echoed */
1597 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1598 				src->scrub->pfss_flags |= PFSS_PAWS;
1599 		}
1600 	}
1601 
1602 	/* I have a dream....  TCP segment reassembly.... */
1603 	return (0);
1604 }
1605 
1606 int
1607 pf_normalize_mss(struct pf_pdesc *pd, u_int16_t maxmss)
1608 {
1609 	int		 olen, optsoff;
1610 	u_int8_t	 opts[MAX_TCPOPTLEN], *opt;
1611 
1612 	olen = (pd->hdr.tcp.th_off << 2) - sizeof(struct tcphdr);
1613 	optsoff = pd->off + sizeof(struct tcphdr);
1614 	if (olen < TCPOLEN_MAXSEG ||
1615 	    !pf_pull_hdr(pd->m, optsoff, opts, olen, NULL, NULL, pd->af))
1616 		return (0);
1617 
1618 	opt = opts;
1619 	while ((opt = pf_find_tcpopt(opt, opts, olen,
1620 		    TCPOPT_MAXSEG, TCPOLEN_MAXSEG)) != NULL) {
1621 		u_int16_t	mss;
1622 		u_int8_t       *mssp = opt + 2;
1623 		memcpy(&mss, mssp, sizeof(mss));
1624 		if (ntohs(mss) > maxmss) {
1625 			size_t mssoffopts = mssp - opts;
1626 			pf_patch_16_unaligned(pd, &mss,
1627 			    htons(maxmss), PF_ALGNMNT(mssoffopts));
1628 			m_copyback(pd->m, optsoff + mssoffopts,
1629 			    sizeof(mss), &mss, M_NOWAIT);
1630 			m_copyback(pd->m, pd->off,
1631 			    sizeof(struct tcphdr), &pd->hdr.tcp, M_NOWAIT);
1632 		}
1633 
1634 		opt += opt[1];
1635 	}
1636 
1637 	return (0);
1638 }
1639 
1640 void
1641 pf_scrub(struct mbuf *m, u_int16_t flags, sa_family_t af, u_int8_t min_ttl,
1642     u_int8_t tos)
1643 {
1644 	struct ip		*h = mtod(m, struct ip *);
1645 #ifdef INET6
1646 	struct ip6_hdr		*h6 = mtod(m, struct ip6_hdr *);
1647 #endif	/* INET6 */
1648 
1649 	/* Clear IP_DF if no-df was requested */
1650 	if (flags & PFSTATE_NODF && af == AF_INET && h->ip_off & htons(IP_DF))
1651 		h->ip_off &= htons(~IP_DF);
1652 
1653 	/* Enforce a minimum ttl, may cause endless packet loops */
1654 	if (min_ttl && af == AF_INET && h->ip_ttl < min_ttl)
1655 		h->ip_ttl = min_ttl;
1656 #ifdef INET6
1657 	if (min_ttl && af == AF_INET6 && h6->ip6_hlim < min_ttl)
1658 		h6->ip6_hlim = min_ttl;
1659 #endif	/* INET6 */
1660 
1661 	/* Enforce tos */
1662 	if (flags & PFSTATE_SETTOS) {
1663 		if (af == AF_INET)
1664 			h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK);
1665 #ifdef INET6
1666 		if (af == AF_INET6) {
1667 			/* drugs are unable to explain such idiocy */
1668 			h6->ip6_flow &= ~htonl(0x0fc00000);
1669 			h6->ip6_flow |= htonl(((u_int32_t)tos) << 20);
1670 		}
1671 #endif	/* INET6 */
1672 	}
1673 
1674 	/* random-id, but not for fragments */
1675 	if (flags & PFSTATE_RANDOMID && af == AF_INET &&
1676 	    !(h->ip_off & ~htons(IP_DF)))
1677 		h->ip_id = htons(ip_randomid());
1678 }
1679