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