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