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