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