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