xref: /freebsd/sys/netpfil/pf/pf_norm.c (revision 42249ef2)
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"));
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", 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",
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" : "reass frag %#08x @ %d-%d",
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", 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", 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"));
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", 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", 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", frag->fr_id, frag->fr_holes));
834 		PF_FRAG_UNLOCK();
835 		return (PF_PASS);  /* Drop because *m0 is NULL, no error. */
836 	}
837 
838 	/* We have all the data. */
839 	frent = TAILQ_FIRST(&frag->fr_queue);
840 	KASSERT(frent != NULL, ("frent != NULL"));
841 	extoff = frent->fe_extoff;
842 	maxlen = frag->fr_maxlen;
843 	frag_id = frag->fr_id;
844 	total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
845 		TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
846 	hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
847 
848 	m = *m0 = pf_join_fragment(frag);
849 	frag = NULL;
850 
851 	PF_FRAG_UNLOCK();
852 
853 	/* Take protocol from first fragment header. */
854 	m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off);
855 	KASSERT(m, ("%s: short mbuf chain", __func__));
856 	proto = *(mtod(m, caddr_t) + off);
857 	m = *m0;
858 
859 	/* Delete frag6 header */
860 	if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0)
861 		goto fail;
862 
863 	if (m->m_flags & M_PKTHDR) {
864 		int plen = 0;
865 		for (m = *m0; m; m = m->m_next)
866 			plen += m->m_len;
867 		m = *m0;
868 		m->m_pkthdr.len = plen;
869 	}
870 
871 	if ((mtag = m_tag_get(PF_REASSEMBLED, sizeof(struct pf_fragment_tag),
872 	    M_NOWAIT)) == NULL)
873 		goto fail;
874 	ftag = (struct pf_fragment_tag *)(mtag + 1);
875 	ftag->ft_hdrlen = hdrlen;
876 	ftag->ft_extoff = extoff;
877 	ftag->ft_maxlen = maxlen;
878 	ftag->ft_id = frag_id;
879 	m_tag_prepend(m, mtag);
880 
881 	ip6 = mtod(m, struct ip6_hdr *);
882 	ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
883 	if (extoff) {
884 		/* Write protocol into next field of last extension header. */
885 		m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
886 		    &off);
887 		KASSERT(m, ("%s: short mbuf chain", __func__));
888 		*(mtod(m, char *) + off) = proto;
889 		m = *m0;
890 	} else
891 		ip6->ip6_nxt = proto;
892 
893 	if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
894 		DPFPRINTF(("drop: too big: %d", total));
895 		ip6->ip6_plen = 0;
896 		REASON_SET(reason, PFRES_SHORT);
897 		/* PF_DROP requires a valid mbuf *m0 in pf_test6(). */
898 		return (PF_DROP);
899 	}
900 
901 	DPFPRINTF(("complete: %p(%d)", m, ntohs(ip6->ip6_plen)));
902 	return (PF_PASS);
903 
904 fail:
905 	REASON_SET(reason, PFRES_MEMORY);
906 	/* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */
907 	return (PF_DROP);
908 }
909 #endif	/* INET6 */
910 
911 #ifdef INET6
912 int
913 pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag)
914 {
915 	struct mbuf		*m = *m0, *t;
916 	struct pf_fragment_tag	*ftag = (struct pf_fragment_tag *)(mtag + 1);
917 	struct pf_pdesc		 pd;
918 	uint32_t		 frag_id;
919 	uint16_t		 hdrlen, extoff, maxlen;
920 	uint8_t			 proto;
921 	int			 error, action;
922 
923 	hdrlen = ftag->ft_hdrlen;
924 	extoff = ftag->ft_extoff;
925 	maxlen = ftag->ft_maxlen;
926 	frag_id = ftag->ft_id;
927 	m_tag_delete(m, mtag);
928 	mtag = NULL;
929 	ftag = NULL;
930 
931 	if (extoff) {
932 		int off;
933 
934 		/* Use protocol from next field of last extension header */
935 		m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
936 		    &off);
937 		KASSERT((m != NULL), ("pf_refragment6: short mbuf chain"));
938 		proto = *(mtod(m, caddr_t) + off);
939 		*(mtod(m, char *) + off) = IPPROTO_FRAGMENT;
940 		m = *m0;
941 	} else {
942 		struct ip6_hdr *hdr;
943 
944 		hdr = mtod(m, struct ip6_hdr *);
945 		proto = hdr->ip6_nxt;
946 		hdr->ip6_nxt = IPPROTO_FRAGMENT;
947 	}
948 
949 	/* The MTU must be a multiple of 8 bytes, or we risk doing the
950 	 * fragmentation wrong. */
951 	maxlen = maxlen & ~7;
952 
953 	/*
954 	 * Maxlen may be less than 8 if there was only a single
955 	 * fragment.  As it was fragmented before, add a fragment
956 	 * header also for a single fragment.  If total or maxlen
957 	 * is less than 8, ip6_fragment() will return EMSGSIZE and
958 	 * we drop the packet.
959 	 */
960 	error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
961 	m = (*m0)->m_nextpkt;
962 	(*m0)->m_nextpkt = NULL;
963 	if (error == 0) {
964 		/* The first mbuf contains the unfragmented packet. */
965 		m_freem(*m0);
966 		*m0 = NULL;
967 		action = PF_PASS;
968 	} else {
969 		/* Drop expects an mbuf to free. */
970 		DPFPRINTF(("refragment error %d", error));
971 		action = PF_DROP;
972 	}
973 	for (t = m; m; m = t) {
974 		t = m->m_nextpkt;
975 		m->m_nextpkt = NULL;
976 		m->m_flags |= M_SKIP_FIREWALL;
977 		memset(&pd, 0, sizeof(pd));
978 		pd.pf_mtag = pf_find_mtag(m);
979 		if (error == 0)
980 			ip6_forward(m, 0);
981 		else
982 			m_freem(m);
983 	}
984 
985 	return (action);
986 }
987 #endif /* INET6 */
988 
989 #ifdef INET
990 int
991 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
992     struct pf_pdesc *pd)
993 {
994 	struct mbuf		*m = *m0;
995 	struct pf_rule		*r;
996 	struct ip		*h = mtod(m, struct ip *);
997 	int			 mff = (ntohs(h->ip_off) & IP_MF);
998 	int			 hlen = h->ip_hl << 2;
999 	u_int16_t		 fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1000 	u_int16_t		 max;
1001 	int			 ip_len;
1002 	int			 ip_off;
1003 	int			 tag = -1;
1004 	int			 verdict;
1005 
1006 	PF_RULES_RASSERT();
1007 
1008 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1009 	while (r != NULL) {
1010 		r->evaluations++;
1011 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
1012 			r = r->skip[PF_SKIP_IFP].ptr;
1013 		else if (r->direction && r->direction != dir)
1014 			r = r->skip[PF_SKIP_DIR].ptr;
1015 		else if (r->af && r->af != AF_INET)
1016 			r = r->skip[PF_SKIP_AF].ptr;
1017 		else if (r->proto && r->proto != h->ip_p)
1018 			r = r->skip[PF_SKIP_PROTO].ptr;
1019 		else if (PF_MISMATCHAW(&r->src.addr,
1020 		    (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
1021 		    r->src.neg, kif, M_GETFIB(m)))
1022 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1023 		else if (PF_MISMATCHAW(&r->dst.addr,
1024 		    (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
1025 		    r->dst.neg, NULL, M_GETFIB(m)))
1026 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1027 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
1028 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
1029 			r = TAILQ_NEXT(r, entries);
1030 		else
1031 			break;
1032 	}
1033 
1034 	if (r == NULL || r->action == PF_NOSCRUB)
1035 		return (PF_PASS);
1036 	else {
1037 		r->packets[dir == PF_OUT]++;
1038 		r->bytes[dir == PF_OUT] += pd->tot_len;
1039 	}
1040 
1041 	/* Check for illegal packets */
1042 	if (hlen < (int)sizeof(struct ip)) {
1043 		REASON_SET(reason, PFRES_NORM);
1044 		goto drop;
1045 	}
1046 
1047 	if (hlen > ntohs(h->ip_len)) {
1048 		REASON_SET(reason, PFRES_NORM);
1049 		goto drop;
1050 	}
1051 
1052 	/* Clear IP_DF if the rule uses the no-df option */
1053 	if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1054 		u_int16_t ip_off = h->ip_off;
1055 
1056 		h->ip_off &= htons(~IP_DF);
1057 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1058 	}
1059 
1060 	/* We will need other tests here */
1061 	if (!fragoff && !mff)
1062 		goto no_fragment;
1063 
1064 	/* We're dealing with a fragment now. Don't allow fragments
1065 	 * with IP_DF to enter the cache. If the flag was cleared by
1066 	 * no-df above, fine. Otherwise drop it.
1067 	 */
1068 	if (h->ip_off & htons(IP_DF)) {
1069 		DPFPRINTF(("IP_DF\n"));
1070 		goto bad;
1071 	}
1072 
1073 	ip_len = ntohs(h->ip_len) - hlen;
1074 	ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1075 
1076 	/* All fragments are 8 byte aligned */
1077 	if (mff && (ip_len & 0x7)) {
1078 		DPFPRINTF(("mff and %d\n", ip_len));
1079 		goto bad;
1080 	}
1081 
1082 	/* Respect maximum length */
1083 	if (fragoff + ip_len > IP_MAXPACKET) {
1084 		DPFPRINTF(("max packet %d\n", fragoff + ip_len));
1085 		goto bad;
1086 	}
1087 	max = fragoff + ip_len;
1088 
1089 	/* Fully buffer all of the fragments
1090 	 * Might return a completely reassembled mbuf, or NULL */
1091 	PF_FRAG_LOCK();
1092 	DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
1093 	verdict = pf_reassemble(m0, h, dir, reason);
1094 	PF_FRAG_UNLOCK();
1095 
1096 	if (verdict != PF_PASS)
1097 		return (PF_DROP);
1098 
1099 	m = *m0;
1100 	if (m == NULL)
1101 		return (PF_DROP);
1102 
1103 	h = mtod(m, struct ip *);
1104 
1105  no_fragment:
1106 	/* At this point, only IP_DF is allowed in ip_off */
1107 	if (h->ip_off & ~htons(IP_DF)) {
1108 		u_int16_t ip_off = h->ip_off;
1109 
1110 		h->ip_off &= htons(IP_DF);
1111 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1112 	}
1113 
1114 	pf_scrub_ip(&m, r->rule_flag, r->min_ttl, r->set_tos);
1115 
1116 	return (PF_PASS);
1117 
1118  bad:
1119 	DPFPRINTF(("dropping bad fragment\n"));
1120 	REASON_SET(reason, PFRES_FRAG);
1121  drop:
1122 	if (r != NULL && r->log)
1123 		PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
1124 		    1);
1125 
1126 	return (PF_DROP);
1127 }
1128 #endif
1129 
1130 #ifdef INET6
1131 int
1132 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1133     u_short *reason, struct pf_pdesc *pd)
1134 {
1135 	struct mbuf		*m = *m0;
1136 	struct pf_rule		*r;
1137 	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
1138 	int			 extoff;
1139 	int			 off;
1140 	struct ip6_ext		 ext;
1141 	struct ip6_opt		 opt;
1142 	struct ip6_frag		 frag;
1143 	u_int32_t		 plen;
1144 	int			 optend;
1145 	int			 ooff;
1146 	u_int8_t		 proto;
1147 	int			 terminal;
1148 
1149 	PF_RULES_RASSERT();
1150 
1151 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1152 	while (r != NULL) {
1153 		r->evaluations++;
1154 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
1155 			r = r->skip[PF_SKIP_IFP].ptr;
1156 		else if (r->direction && r->direction != dir)
1157 			r = r->skip[PF_SKIP_DIR].ptr;
1158 		else if (r->af && r->af != AF_INET6)
1159 			r = r->skip[PF_SKIP_AF].ptr;
1160 #if 0 /* header chain! */
1161 		else if (r->proto && r->proto != h->ip6_nxt)
1162 			r = r->skip[PF_SKIP_PROTO].ptr;
1163 #endif
1164 		else if (PF_MISMATCHAW(&r->src.addr,
1165 		    (struct pf_addr *)&h->ip6_src, AF_INET6,
1166 		    r->src.neg, kif, M_GETFIB(m)))
1167 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1168 		else if (PF_MISMATCHAW(&r->dst.addr,
1169 		    (struct pf_addr *)&h->ip6_dst, AF_INET6,
1170 		    r->dst.neg, NULL, M_GETFIB(m)))
1171 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1172 		else
1173 			break;
1174 	}
1175 
1176 	if (r == NULL || r->action == PF_NOSCRUB)
1177 		return (PF_PASS);
1178 	else {
1179 		r->packets[dir == PF_OUT]++;
1180 		r->bytes[dir == PF_OUT] += pd->tot_len;
1181 	}
1182 
1183 	/* Check for illegal packets */
1184 	if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1185 		goto drop;
1186 
1187 	plen = ntohs(h->ip6_plen);
1188 	/* jumbo payload option not supported */
1189 	if (plen == 0)
1190 		goto drop;
1191 
1192 	extoff = 0;
1193 	off = sizeof(struct ip6_hdr);
1194 	proto = h->ip6_nxt;
1195 	terminal = 0;
1196 	do {
1197 		switch (proto) {
1198 		case IPPROTO_FRAGMENT:
1199 			goto fragment;
1200 			break;
1201 		case IPPROTO_AH:
1202 		case IPPROTO_ROUTING:
1203 		case IPPROTO_DSTOPTS:
1204 			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1205 			    NULL, AF_INET6))
1206 				goto shortpkt;
1207 			extoff = off;
1208 			if (proto == IPPROTO_AH)
1209 				off += (ext.ip6e_len + 2) * 4;
1210 			else
1211 				off += (ext.ip6e_len + 1) * 8;
1212 			proto = ext.ip6e_nxt;
1213 			break;
1214 		case IPPROTO_HOPOPTS:
1215 			if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1216 			    NULL, AF_INET6))
1217 				goto shortpkt;
1218 			extoff = off;
1219 			optend = off + (ext.ip6e_len + 1) * 8;
1220 			ooff = off + sizeof(ext);
1221 			do {
1222 				if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1223 				    sizeof(opt.ip6o_type), NULL, NULL,
1224 				    AF_INET6))
1225 					goto shortpkt;
1226 				if (opt.ip6o_type == IP6OPT_PAD1) {
1227 					ooff++;
1228 					continue;
1229 				}
1230 				if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1231 				    NULL, NULL, AF_INET6))
1232 					goto shortpkt;
1233 				if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1234 					goto drop;
1235 				if (opt.ip6o_type == IP6OPT_JUMBO)
1236 					goto drop;
1237 				ooff += sizeof(opt) + opt.ip6o_len;
1238 			} while (ooff < optend);
1239 
1240 			off = optend;
1241 			proto = ext.ip6e_nxt;
1242 			break;
1243 		default:
1244 			terminal = 1;
1245 			break;
1246 		}
1247 	} while (!terminal);
1248 
1249 	if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1250 		goto shortpkt;
1251 
1252 	pf_scrub_ip6(&m, r->min_ttl);
1253 
1254 	return (PF_PASS);
1255 
1256  fragment:
1257 	if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1258 		goto shortpkt;
1259 
1260 	if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1261 		goto shortpkt;
1262 
1263 	/* Offset now points to data portion. */
1264 	off += sizeof(frag);
1265 
1266 	/* Returns PF_DROP or *m0 is NULL or completely reassembled mbuf. */
1267 	if (pf_reassemble6(m0, h, &frag, off, extoff, reason) != PF_PASS)
1268 		return (PF_DROP);
1269 	m = *m0;
1270 	if (m == NULL)
1271 		return (PF_DROP);
1272 
1273 	pd->flags |= PFDESC_IP_REAS;
1274 	return (PF_PASS);
1275 
1276  shortpkt:
1277 	REASON_SET(reason, PFRES_SHORT);
1278 	if (r != NULL && r->log)
1279 		PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1280 		    1);
1281 	return (PF_DROP);
1282 
1283  drop:
1284 	REASON_SET(reason, PFRES_NORM);
1285 	if (r != NULL && r->log)
1286 		PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1287 		    1);
1288 	return (PF_DROP);
1289 }
1290 #endif /* INET6 */
1291 
1292 int
1293 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1294     int off, void *h, struct pf_pdesc *pd)
1295 {
1296 	struct pf_rule	*r, *rm = NULL;
1297 	struct tcphdr	*th = pd->hdr.tcp;
1298 	int		 rewrite = 0;
1299 	u_short		 reason;
1300 	u_int8_t	 flags;
1301 	sa_family_t	 af = pd->af;
1302 
1303 	PF_RULES_RASSERT();
1304 
1305 	r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1306 	while (r != NULL) {
1307 		r->evaluations++;
1308 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
1309 			r = r->skip[PF_SKIP_IFP].ptr;
1310 		else if (r->direction && r->direction != dir)
1311 			r = r->skip[PF_SKIP_DIR].ptr;
1312 		else if (r->af && r->af != af)
1313 			r = r->skip[PF_SKIP_AF].ptr;
1314 		else if (r->proto && r->proto != pd->proto)
1315 			r = r->skip[PF_SKIP_PROTO].ptr;
1316 		else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1317 		    r->src.neg, kif, M_GETFIB(m)))
1318 			r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1319 		else if (r->src.port_op && !pf_match_port(r->src.port_op,
1320 			    r->src.port[0], r->src.port[1], th->th_sport))
1321 			r = r->skip[PF_SKIP_SRC_PORT].ptr;
1322 		else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1323 		    r->dst.neg, NULL, M_GETFIB(m)))
1324 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
1325 		else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1326 			    r->dst.port[0], r->dst.port[1], th->th_dport))
1327 			r = r->skip[PF_SKIP_DST_PORT].ptr;
1328 		else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1329 			    pf_osfp_fingerprint(pd, m, off, th),
1330 			    r->os_fingerprint))
1331 			r = TAILQ_NEXT(r, entries);
1332 		else {
1333 			rm = r;
1334 			break;
1335 		}
1336 	}
1337 
1338 	if (rm == NULL || rm->action == PF_NOSCRUB)
1339 		return (PF_PASS);
1340 	else {
1341 		r->packets[dir == PF_OUT]++;
1342 		r->bytes[dir == PF_OUT] += pd->tot_len;
1343 	}
1344 
1345 	if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1346 		pd->flags |= PFDESC_TCP_NORM;
1347 
1348 	flags = th->th_flags;
1349 	if (flags & TH_SYN) {
1350 		/* Illegal packet */
1351 		if (flags & TH_RST)
1352 			goto tcp_drop;
1353 
1354 		if (flags & TH_FIN)
1355 			goto tcp_drop;
1356 	} else {
1357 		/* Illegal packet */
1358 		if (!(flags & (TH_ACK|TH_RST)))
1359 			goto tcp_drop;
1360 	}
1361 
1362 	if (!(flags & TH_ACK)) {
1363 		/* These flags are only valid if ACK is set */
1364 		if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1365 			goto tcp_drop;
1366 	}
1367 
1368 	/* Check for illegal header length */
1369 	if (th->th_off < (sizeof(struct tcphdr) >> 2))
1370 		goto tcp_drop;
1371 
1372 	/* If flags changed, or reserved data set, then adjust */
1373 	if (flags != th->th_flags || th->th_x2 != 0) {
1374 		u_int16_t	ov, nv;
1375 
1376 		ov = *(u_int16_t *)(&th->th_ack + 1);
1377 		th->th_flags = flags;
1378 		th->th_x2 = 0;
1379 		nv = *(u_int16_t *)(&th->th_ack + 1);
1380 
1381 		th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, ov, nv, 0);
1382 		rewrite = 1;
1383 	}
1384 
1385 	/* Remove urgent pointer, if TH_URG is not set */
1386 	if (!(flags & TH_URG) && th->th_urp) {
1387 		th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, th->th_urp,
1388 		    0, 0);
1389 		th->th_urp = 0;
1390 		rewrite = 1;
1391 	}
1392 
1393 	/* Process options */
1394 	if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1395 		rewrite = 1;
1396 
1397 	/* copy back packet headers if we sanitized */
1398 	if (rewrite)
1399 		m_copyback(m, off, sizeof(*th), (caddr_t)th);
1400 
1401 	return (PF_PASS);
1402 
1403  tcp_drop:
1404 	REASON_SET(&reason, PFRES_NORM);
1405 	if (rm != NULL && r->log)
1406 		PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1407 		    1);
1408 	return (PF_DROP);
1409 }
1410 
1411 int
1412 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1413     struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1414 {
1415 	u_int32_t tsval, tsecr;
1416 	u_int8_t hdr[60];
1417 	u_int8_t *opt;
1418 
1419 	KASSERT((src->scrub == NULL),
1420 	    ("pf_normalize_tcp_init: src->scrub != NULL"));
1421 
1422 	src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1423 	if (src->scrub == NULL)
1424 		return (1);
1425 
1426 	switch (pd->af) {
1427 #ifdef INET
1428 	case AF_INET: {
1429 		struct ip *h = mtod(m, struct ip *);
1430 		src->scrub->pfss_ttl = h->ip_ttl;
1431 		break;
1432 	}
1433 #endif /* INET */
1434 #ifdef INET6
1435 	case AF_INET6: {
1436 		struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1437 		src->scrub->pfss_ttl = h->ip6_hlim;
1438 		break;
1439 	}
1440 #endif /* INET6 */
1441 	}
1442 
1443 
1444 	/*
1445 	 * All normalizations below are only begun if we see the start of
1446 	 * the connections.  They must all set an enabled bit in pfss_flags
1447 	 */
1448 	if ((th->th_flags & TH_SYN) == 0)
1449 		return (0);
1450 
1451 
1452 	if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1453 	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1454 		/* Diddle with TCP options */
1455 		int hlen;
1456 		opt = hdr + sizeof(struct tcphdr);
1457 		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1458 		while (hlen >= TCPOLEN_TIMESTAMP) {
1459 			switch (*opt) {
1460 			case TCPOPT_EOL:	/* FALLTHROUGH */
1461 			case TCPOPT_NOP:
1462 				opt++;
1463 				hlen--;
1464 				break;
1465 			case TCPOPT_TIMESTAMP:
1466 				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1467 					src->scrub->pfss_flags |=
1468 					    PFSS_TIMESTAMP;
1469 					src->scrub->pfss_ts_mod =
1470 					    htonl(arc4random());
1471 
1472 					/* note PFSS_PAWS not set yet */
1473 					memcpy(&tsval, &opt[2],
1474 					    sizeof(u_int32_t));
1475 					memcpy(&tsecr, &opt[6],
1476 					    sizeof(u_int32_t));
1477 					src->scrub->pfss_tsval0 = ntohl(tsval);
1478 					src->scrub->pfss_tsval = ntohl(tsval);
1479 					src->scrub->pfss_tsecr = ntohl(tsecr);
1480 					getmicrouptime(&src->scrub->pfss_last);
1481 				}
1482 				/* FALLTHROUGH */
1483 			default:
1484 				hlen -= MAX(opt[1], 2);
1485 				opt += MAX(opt[1], 2);
1486 				break;
1487 			}
1488 		}
1489 	}
1490 
1491 	return (0);
1492 }
1493 
1494 void
1495 pf_normalize_tcp_cleanup(struct pf_state *state)
1496 {
1497 	if (state->src.scrub)
1498 		uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1499 	if (state->dst.scrub)
1500 		uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1501 
1502 	/* Someday... flush the TCP segment reassembly descriptors. */
1503 }
1504 
1505 int
1506 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1507     u_short *reason, struct tcphdr *th, struct pf_state *state,
1508     struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1509 {
1510 	struct timeval uptime;
1511 	u_int32_t tsval, tsecr;
1512 	u_int tsval_from_last;
1513 	u_int8_t hdr[60];
1514 	u_int8_t *opt;
1515 	int copyback = 0;
1516 	int got_ts = 0;
1517 
1518 	KASSERT((src->scrub || dst->scrub),
1519 	    ("%s: src->scrub && dst->scrub!", __func__));
1520 
1521 	/*
1522 	 * Enforce the minimum TTL seen for this connection.  Negate a common
1523 	 * technique to evade an intrusion detection system and confuse
1524 	 * firewall state code.
1525 	 */
1526 	switch (pd->af) {
1527 #ifdef INET
1528 	case AF_INET: {
1529 		if (src->scrub) {
1530 			struct ip *h = mtod(m, struct ip *);
1531 			if (h->ip_ttl > src->scrub->pfss_ttl)
1532 				src->scrub->pfss_ttl = h->ip_ttl;
1533 			h->ip_ttl = src->scrub->pfss_ttl;
1534 		}
1535 		break;
1536 	}
1537 #endif /* INET */
1538 #ifdef INET6
1539 	case AF_INET6: {
1540 		if (src->scrub) {
1541 			struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1542 			if (h->ip6_hlim > src->scrub->pfss_ttl)
1543 				src->scrub->pfss_ttl = h->ip6_hlim;
1544 			h->ip6_hlim = src->scrub->pfss_ttl;
1545 		}
1546 		break;
1547 	}
1548 #endif /* INET6 */
1549 	}
1550 
1551 	if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1552 	    ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1553 	    (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1554 	    pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1555 		/* Diddle with TCP options */
1556 		int hlen;
1557 		opt = hdr + sizeof(struct tcphdr);
1558 		hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1559 		while (hlen >= TCPOLEN_TIMESTAMP) {
1560 			switch (*opt) {
1561 			case TCPOPT_EOL:	/* FALLTHROUGH */
1562 			case TCPOPT_NOP:
1563 				opt++;
1564 				hlen--;
1565 				break;
1566 			case TCPOPT_TIMESTAMP:
1567 				/* Modulate the timestamps.  Can be used for
1568 				 * NAT detection, OS uptime determination or
1569 				 * reboot detection.
1570 				 */
1571 
1572 				if (got_ts) {
1573 					/* Huh?  Multiple timestamps!? */
1574 					if (V_pf_status.debug >= PF_DEBUG_MISC) {
1575 						DPFPRINTF(("multiple TS??"));
1576 						pf_print_state(state);
1577 						printf("\n");
1578 					}
1579 					REASON_SET(reason, PFRES_TS);
1580 					return (PF_DROP);
1581 				}
1582 				if (opt[1] >= TCPOLEN_TIMESTAMP) {
1583 					memcpy(&tsval, &opt[2],
1584 					    sizeof(u_int32_t));
1585 					if (tsval && src->scrub &&
1586 					    (src->scrub->pfss_flags &
1587 					    PFSS_TIMESTAMP)) {
1588 						tsval = ntohl(tsval);
1589 						pf_change_proto_a(m, &opt[2],
1590 						    &th->th_sum,
1591 						    htonl(tsval +
1592 						    src->scrub->pfss_ts_mod),
1593 						    0);
1594 						copyback = 1;
1595 					}
1596 
1597 					/* Modulate TS reply iff valid (!0) */
1598 					memcpy(&tsecr, &opt[6],
1599 					    sizeof(u_int32_t));
1600 					if (tsecr && dst->scrub &&
1601 					    (dst->scrub->pfss_flags &
1602 					    PFSS_TIMESTAMP)) {
1603 						tsecr = ntohl(tsecr)
1604 						    - dst->scrub->pfss_ts_mod;
1605 						pf_change_proto_a(m, &opt[6],
1606 						    &th->th_sum, htonl(tsecr),
1607 						    0);
1608 						copyback = 1;
1609 					}
1610 					got_ts = 1;
1611 				}
1612 				/* FALLTHROUGH */
1613 			default:
1614 				hlen -= MAX(opt[1], 2);
1615 				opt += MAX(opt[1], 2);
1616 				break;
1617 			}
1618 		}
1619 		if (copyback) {
1620 			/* Copyback the options, caller copys back header */
1621 			*writeback = 1;
1622 			m_copyback(m, off + sizeof(struct tcphdr),
1623 			    (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1624 			    sizeof(struct tcphdr));
1625 		}
1626 	}
1627 
1628 
1629 	/*
1630 	 * Must invalidate PAWS checks on connections idle for too long.
1631 	 * The fastest allowed timestamp clock is 1ms.  That turns out to
1632 	 * be about 24 days before it wraps.  XXX Right now our lowerbound
1633 	 * TS echo check only works for the first 12 days of a connection
1634 	 * when the TS has exhausted half its 32bit space
1635 	 */
1636 #define TS_MAX_IDLE	(24*24*60*60)
1637 #define TS_MAX_CONN	(12*24*60*60)	/* XXX remove when better tsecr check */
1638 
1639 	getmicrouptime(&uptime);
1640 	if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1641 	    (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1642 	    time_uptime - state->creation > TS_MAX_CONN))  {
1643 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1644 			DPFPRINTF(("src idled out of PAWS\n"));
1645 			pf_print_state(state);
1646 			printf("\n");
1647 		}
1648 		src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1649 		    | PFSS_PAWS_IDLED;
1650 	}
1651 	if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1652 	    uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1653 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
1654 			DPFPRINTF(("dst idled out of PAWS\n"));
1655 			pf_print_state(state);
1656 			printf("\n");
1657 		}
1658 		dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1659 		    | PFSS_PAWS_IDLED;
1660 	}
1661 
1662 	if (got_ts && src->scrub && dst->scrub &&
1663 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1664 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1665 		/* Validate that the timestamps are "in-window".
1666 		 * RFC1323 describes TCP Timestamp options that allow
1667 		 * measurement of RTT (round trip time) and PAWS
1668 		 * (protection against wrapped sequence numbers).  PAWS
1669 		 * gives us a set of rules for rejecting packets on
1670 		 * long fat pipes (packets that were somehow delayed
1671 		 * in transit longer than the time it took to send the
1672 		 * full TCP sequence space of 4Gb).  We can use these
1673 		 * rules and infer a few others that will let us treat
1674 		 * the 32bit timestamp and the 32bit echoed timestamp
1675 		 * as sequence numbers to prevent a blind attacker from
1676 		 * inserting packets into a connection.
1677 		 *
1678 		 * RFC1323 tells us:
1679 		 *  - The timestamp on this packet must be greater than
1680 		 *    or equal to the last value echoed by the other
1681 		 *    endpoint.  The RFC says those will be discarded
1682 		 *    since it is a dup that has already been acked.
1683 		 *    This gives us a lowerbound on the timestamp.
1684 		 *        timestamp >= other last echoed timestamp
1685 		 *  - The timestamp will be less than or equal to
1686 		 *    the last timestamp plus the time between the
1687 		 *    last packet and now.  The RFC defines the max
1688 		 *    clock rate as 1ms.  We will allow clocks to be
1689 		 *    up to 10% fast and will allow a total difference
1690 		 *    or 30 seconds due to a route change.  And this
1691 		 *    gives us an upperbound on the timestamp.
1692 		 *        timestamp <= last timestamp + max ticks
1693 		 *    We have to be careful here.  Windows will send an
1694 		 *    initial timestamp of zero and then initialize it
1695 		 *    to a random value after the 3whs; presumably to
1696 		 *    avoid a DoS by having to call an expensive RNG
1697 		 *    during a SYN flood.  Proof MS has at least one
1698 		 *    good security geek.
1699 		 *
1700 		 *  - The TCP timestamp option must also echo the other
1701 		 *    endpoints timestamp.  The timestamp echoed is the
1702 		 *    one carried on the earliest unacknowledged segment
1703 		 *    on the left edge of the sequence window.  The RFC
1704 		 *    states that the host will reject any echoed
1705 		 *    timestamps that were larger than any ever sent.
1706 		 *    This gives us an upperbound on the TS echo.
1707 		 *        tescr <= largest_tsval
1708 		 *  - The lowerbound on the TS echo is a little more
1709 		 *    tricky to determine.  The other endpoint's echoed
1710 		 *    values will not decrease.  But there may be
1711 		 *    network conditions that re-order packets and
1712 		 *    cause our view of them to decrease.  For now the
1713 		 *    only lowerbound we can safely determine is that
1714 		 *    the TS echo will never be less than the original
1715 		 *    TS.  XXX There is probably a better lowerbound.
1716 		 *    Remove TS_MAX_CONN with better lowerbound check.
1717 		 *        tescr >= other original TS
1718 		 *
1719 		 * It is also important to note that the fastest
1720 		 * timestamp clock of 1ms will wrap its 32bit space in
1721 		 * 24 days.  So we just disable TS checking after 24
1722 		 * days of idle time.  We actually must use a 12d
1723 		 * connection limit until we can come up with a better
1724 		 * lowerbound to the TS echo check.
1725 		 */
1726 		struct timeval delta_ts;
1727 		int ts_fudge;
1728 
1729 
1730 		/*
1731 		 * PFTM_TS_DIFF is how many seconds of leeway to allow
1732 		 * a host's timestamp.  This can happen if the previous
1733 		 * packet got delayed in transit for much longer than
1734 		 * this packet.
1735 		 */
1736 		if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1737 			ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1738 
1739 		/* Calculate max ticks since the last timestamp */
1740 #define TS_MAXFREQ	1100		/* RFC max TS freq of 1Khz + 10% skew */
1741 #define TS_MICROSECS	1000000		/* microseconds per second */
1742 		delta_ts = uptime;
1743 		timevalsub(&delta_ts, &src->scrub->pfss_last);
1744 		tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1745 		tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1746 
1747 		if ((src->state >= TCPS_ESTABLISHED &&
1748 		    dst->state >= TCPS_ESTABLISHED) &&
1749 		    (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1750 		    SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1751 		    (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1752 		    SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1753 			/* Bad RFC1323 implementation or an insertion attack.
1754 			 *
1755 			 * - Solaris 2.6 and 2.7 are known to send another ACK
1756 			 *   after the FIN,FIN|ACK,ACK closing that carries
1757 			 *   an old timestamp.
1758 			 */
1759 
1760 			DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1761 			    SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1762 			    SEQ_GT(tsval, src->scrub->pfss_tsval +
1763 			    tsval_from_last) ? '1' : ' ',
1764 			    SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1765 			    SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1766 			DPFPRINTF((" tsval: %u  tsecr: %u  +ticks: %u  "
1767 			    "idle: %jus %lums\n",
1768 			    tsval, tsecr, tsval_from_last,
1769 			    (uintmax_t)delta_ts.tv_sec,
1770 			    delta_ts.tv_usec / 1000));
1771 			DPFPRINTF((" src->tsval: %u  tsecr: %u\n",
1772 			    src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1773 			DPFPRINTF((" dst->tsval: %u  tsecr: %u  tsval0: %u"
1774 			    "\n", dst->scrub->pfss_tsval,
1775 			    dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1776 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1777 				pf_print_state(state);
1778 				pf_print_flags(th->th_flags);
1779 				printf("\n");
1780 			}
1781 			REASON_SET(reason, PFRES_TS);
1782 			return (PF_DROP);
1783 		}
1784 
1785 		/* XXX I'd really like to require tsecr but it's optional */
1786 
1787 	} else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1788 	    ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1789 	    || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1790 	    src->scrub && dst->scrub &&
1791 	    (src->scrub->pfss_flags & PFSS_PAWS) &&
1792 	    (dst->scrub->pfss_flags & PFSS_PAWS)) {
1793 		/* Didn't send a timestamp.  Timestamps aren't really useful
1794 		 * when:
1795 		 *  - connection opening or closing (often not even sent).
1796 		 *    but we must not let an attacker to put a FIN on a
1797 		 *    data packet to sneak it through our ESTABLISHED check.
1798 		 *  - on a TCP reset.  RFC suggests not even looking at TS.
1799 		 *  - on an empty ACK.  The TS will not be echoed so it will
1800 		 *    probably not help keep the RTT calculation in sync and
1801 		 *    there isn't as much danger when the sequence numbers
1802 		 *    got wrapped.  So some stacks don't include TS on empty
1803 		 *    ACKs :-(
1804 		 *
1805 		 * To minimize the disruption to mostly RFC1323 conformant
1806 		 * stacks, we will only require timestamps on data packets.
1807 		 *
1808 		 * And what do ya know, we cannot require timestamps on data
1809 		 * packets.  There appear to be devices that do legitimate
1810 		 * TCP connection hijacking.  There are HTTP devices that allow
1811 		 * a 3whs (with timestamps) and then buffer the HTTP request.
1812 		 * If the intermediate device has the HTTP response cache, it
1813 		 * will spoof the response but not bother timestamping its
1814 		 * packets.  So we can look for the presence of a timestamp in
1815 		 * the first data packet and if there, require it in all future
1816 		 * packets.
1817 		 */
1818 
1819 		if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1820 			/*
1821 			 * Hey!  Someone tried to sneak a packet in.  Or the
1822 			 * stack changed its RFC1323 behavior?!?!
1823 			 */
1824 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1825 				DPFPRINTF(("Did not receive expected RFC1323 "
1826 				    "timestamp\n"));
1827 				pf_print_state(state);
1828 				pf_print_flags(th->th_flags);
1829 				printf("\n");
1830 			}
1831 			REASON_SET(reason, PFRES_TS);
1832 			return (PF_DROP);
1833 		}
1834 	}
1835 
1836 
1837 	/*
1838 	 * We will note if a host sends his data packets with or without
1839 	 * timestamps.  And require all data packets to contain a timestamp
1840 	 * if the first does.  PAWS implicitly requires that all data packets be
1841 	 * timestamped.  But I think there are middle-man devices that hijack
1842 	 * TCP streams immediately after the 3whs and don't timestamp their
1843 	 * packets (seen in a WWW accelerator or cache).
1844 	 */
1845 	if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1846 	    (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1847 		if (got_ts)
1848 			src->scrub->pfss_flags |= PFSS_DATA_TS;
1849 		else {
1850 			src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1851 			if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1852 			    (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1853 				/* Don't warn if other host rejected RFC1323 */
1854 				DPFPRINTF(("Broken RFC1323 stack did not "
1855 				    "timestamp data packet. Disabled PAWS "
1856 				    "security.\n"));
1857 				pf_print_state(state);
1858 				pf_print_flags(th->th_flags);
1859 				printf("\n");
1860 			}
1861 		}
1862 	}
1863 
1864 
1865 	/*
1866 	 * Update PAWS values
1867 	 */
1868 	if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1869 	    (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1870 		getmicrouptime(&src->scrub->pfss_last);
1871 		if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1872 		    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1873 			src->scrub->pfss_tsval = tsval;
1874 
1875 		if (tsecr) {
1876 			if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1877 			    (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1878 				src->scrub->pfss_tsecr = tsecr;
1879 
1880 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1881 			    (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1882 			    src->scrub->pfss_tsval0 == 0)) {
1883 				/* tsval0 MUST be the lowest timestamp */
1884 				src->scrub->pfss_tsval0 = tsval;
1885 			}
1886 
1887 			/* Only fully initialized after a TS gets echoed */
1888 			if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1889 				src->scrub->pfss_flags |= PFSS_PAWS;
1890 		}
1891 	}
1892 
1893 	/* I have a dream....  TCP segment reassembly.... */
1894 	return (0);
1895 }
1896 
1897 static int
1898 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1899     int off, sa_family_t af)
1900 {
1901 	u_int16_t	*mss;
1902 	int		 thoff;
1903 	int		 opt, cnt, optlen = 0;
1904 	int		 rewrite = 0;
1905 	u_char		 opts[TCP_MAXOLEN];
1906 	u_char		*optp = opts;
1907 
1908 	thoff = th->th_off << 2;
1909 	cnt = thoff - sizeof(struct tcphdr);
1910 
1911 	if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1912 	    NULL, NULL, af))
1913 		return (rewrite);
1914 
1915 	for (; cnt > 0; cnt -= optlen, optp += optlen) {
1916 		opt = optp[0];
1917 		if (opt == TCPOPT_EOL)
1918 			break;
1919 		if (opt == TCPOPT_NOP)
1920 			optlen = 1;
1921 		else {
1922 			if (cnt < 2)
1923 				break;
1924 			optlen = optp[1];
1925 			if (optlen < 2 || optlen > cnt)
1926 				break;
1927 		}
1928 		switch (opt) {
1929 		case TCPOPT_MAXSEG:
1930 			mss = (u_int16_t *)(optp + 2);
1931 			if ((ntohs(*mss)) > r->max_mss) {
1932 				th->th_sum = pf_proto_cksum_fixup(m,
1933 				    th->th_sum, *mss, htons(r->max_mss), 0);
1934 				*mss = htons(r->max_mss);
1935 				rewrite = 1;
1936 			}
1937 			break;
1938 		default:
1939 			break;
1940 		}
1941 	}
1942 
1943 	if (rewrite)
1944 		m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1945 
1946 	return (rewrite);
1947 }
1948 
1949 #ifdef INET
1950 static void
1951 pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
1952 {
1953 	struct mbuf		*m = *m0;
1954 	struct ip		*h = mtod(m, struct ip *);
1955 
1956 	/* Clear IP_DF if no-df was requested */
1957 	if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1958 		u_int16_t ip_off = h->ip_off;
1959 
1960 		h->ip_off &= htons(~IP_DF);
1961 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1962 	}
1963 
1964 	/* Enforce a minimum ttl, may cause endless packet loops */
1965 	if (min_ttl && h->ip_ttl < min_ttl) {
1966 		u_int16_t ip_ttl = h->ip_ttl;
1967 
1968 		h->ip_ttl = min_ttl;
1969 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1970 	}
1971 
1972 	/* Enforce tos */
1973 	if (flags & PFRULE_SET_TOS) {
1974 		u_int16_t	ov, nv;
1975 
1976 		ov = *(u_int16_t *)h;
1977 		h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK);
1978 		nv = *(u_int16_t *)h;
1979 
1980 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1981 	}
1982 
1983 	/* random-id, but not for fragments */
1984 	if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
1985 		uint16_t ip_id = h->ip_id;
1986 
1987 		ip_fillid(h);
1988 		h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1989 	}
1990 }
1991 #endif /* INET */
1992 
1993 #ifdef INET6
1994 static void
1995 pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
1996 {
1997 	struct mbuf		*m = *m0;
1998 	struct ip6_hdr		*h = mtod(m, struct ip6_hdr *);
1999 
2000 	/* Enforce a minimum ttl, may cause endless packet loops */
2001 	if (min_ttl && h->ip6_hlim < min_ttl)
2002 		h->ip6_hlim = min_ttl;
2003 }
2004 #endif
2005