1 /* $OpenBSD: pf_norm.c,v 1.107 2006/04/16 00:59:52 pascoe Exp $ */
4 * Copyright 2001 Niels Provos <provos@citi.umich.edu>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
30 #include "opt_inet6.h"
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
37 #define NPFLOG DEV_PFLOG
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/filio.h>
49 #include <sys/fcntl.h>
50 #include <sys/socket.h>
51 #include <sys/kernel.h>
56 #include <dev/rndvar.h>
59 #include <net/if_types.h>
61 #include <net/route.h>
62 #include <net/if_pflog.h>
64 #include <netinet/in.h>
65 #include <netinet/in_var.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_var.h>
69 #include <netinet/tcp.h>
70 #include <netinet/tcp_seq.h>
71 #include <netinet/udp.h>
72 #include <netinet/ip_icmp.h>
75 #include <netinet/ip6.h>
78 #include <net/pfvar.h>
84 LIST_ENTRY(pf_frent) fr_next;
90 LIST_ENTRY(pf_frcache) fr_next;
96 #define PFFRAG_SEENLAST 0x0001 /* Seen the last fragment for this */
97 #define PFFRAG_NOBUFFER 0x0002 /* Non-buffering fragment cache */
98 #define PFFRAG_DROP 0x0004 /* Drop all fragments */
99 #define BUFFER_FRAGMENTS(fr) (!((fr)->fr_flags & PFFRAG_NOBUFFER))
103 RB_ENTRY(pf_fragment) fr_entry;
104 TAILQ_ENTRY(pf_fragment) frag_next;
105 struct in_addr fr_src;
106 struct in_addr fr_dst;
107 u_int8_t fr_p; /* protocol of this fragment */
108 u_int8_t fr_flags; /* status flags */
109 u_int16_t fr_id; /* fragment id for reassemble */
110 u_int16_t fr_max; /* fragment data max */
111 u_int32_t fr_timeout;
112 #define fr_queue fr_u.fru_queue
113 #define fr_cache fr_u.fru_cache
115 LIST_HEAD(pf_fragq, pf_frent) fru_queue; /* buffering */
116 LIST_HEAD(pf_cacheq, pf_frcache) fru_cache; /* non-buf */
121 TAILQ_HEAD(pf_fragqueue, pf_fragment) pf_fragqueue;
122 TAILQ_HEAD(pf_cachequeue, pf_fragment) pf_cachequeue;
125 static __inline int pf_frag_compare(struct pf_fragment *,
126 struct pf_fragment *);
128 static int pf_frag_compare(struct pf_fragment *,
129 struct pf_fragment *);
131 RB_HEAD(pf_frag_tree, pf_fragment) pf_frag_tree, pf_cache_tree;
132 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
133 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
135 /* Private prototypes */
136 void pf_ip2key(struct pf_fragment *, struct ip *);
137 void pf_remove_fragment(struct pf_fragment *);
138 void pf_flush_fragments(void);
139 void pf_free_fragment(struct pf_fragment *);
140 struct pf_fragment *pf_find_fragment(struct ip *, struct pf_frag_tree *);
141 struct mbuf *pf_reassemble(struct mbuf **, struct pf_fragment **,
142 struct pf_frent *, int);
143 struct mbuf *pf_fragcache(struct mbuf **, struct ip*,
144 struct pf_fragment **, int, int, int *);
145 int pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
146 struct tcphdr *, int);
148 #define DPFPRINTF(x) do { \
149 if (pf_status.debug >= PF_DEBUG_MISC) { \
150 printf("%s: ", __func__); \
157 uma_zone_t pf_frent_pl, pf_frag_pl, pf_cache_pl, pf_cent_pl;
158 uma_zone_t pf_state_scrub_pl;
160 struct pool pf_frent_pl, pf_frag_pl, pf_cache_pl, pf_cent_pl;
161 struct pool pf_state_scrub_pl;
163 int pf_nfrents, pf_ncache;
166 pf_normalize_init(void)
171 * No high water mark support(It's hint not hard limit).
172 * uma_zone_set_max(pf_frag_pl, PFFRAG_FRAG_HIWAT);
174 uma_zone_set_max(pf_frent_pl, PFFRAG_FRENT_HIWAT);
175 uma_zone_set_max(pf_cache_pl, PFFRAG_FRCACHE_HIWAT);
176 uma_zone_set_max(pf_cent_pl, PFFRAG_FRCENT_HIWAT);
178 pool_init(&pf_frent_pl, sizeof(struct pf_frent), 0, 0, 0, "pffrent",
180 pool_init(&pf_frag_pl, sizeof(struct pf_fragment), 0, 0, 0, "pffrag",
182 pool_init(&pf_cache_pl, sizeof(struct pf_fragment), 0, 0, 0,
184 pool_init(&pf_cent_pl, sizeof(struct pf_frcache), 0, 0, 0, "pffrcent",
186 pool_init(&pf_state_scrub_pl, sizeof(struct pf_state_scrub), 0, 0, 0,
189 pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
190 pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
191 pool_sethardlimit(&pf_cache_pl, PFFRAG_FRCACHE_HIWAT, NULL, 0);
192 pool_sethardlimit(&pf_cent_pl, PFFRAG_FRCENT_HIWAT, NULL, 0);
195 TAILQ_INIT(&pf_fragqueue);
196 TAILQ_INIT(&pf_cachequeue);
204 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
208 if ((diff = a->fr_id - b->fr_id))
210 else if ((diff = a->fr_p - b->fr_p))
212 else if (a->fr_src.s_addr < b->fr_src.s_addr)
214 else if (a->fr_src.s_addr > b->fr_src.s_addr)
216 else if (a->fr_dst.s_addr < b->fr_dst.s_addr)
218 else if (a->fr_dst.s_addr > b->fr_dst.s_addr)
224 pf_purge_expired_fragments(void)
226 struct pf_fragment *frag;
227 u_int32_t expire = time_second -
228 pf_default_rule.timeout[PFTM_FRAG];
230 while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
232 KASSERT((BUFFER_FRAGMENTS(frag)),
233 ("BUFFER_FRAGMENTS(frag) == 0: %s", __FUNCTION__));
235 KASSERT(BUFFER_FRAGMENTS(frag));
237 if (frag->fr_timeout > expire)
240 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
241 pf_free_fragment(frag);
244 while ((frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue)) != NULL) {
246 KASSERT((!BUFFER_FRAGMENTS(frag)),
247 ("BUFFER_FRAGMENTS(frag) != 0: %s", __FUNCTION__));
249 KASSERT(!BUFFER_FRAGMENTS(frag));
251 if (frag->fr_timeout > expire)
254 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
255 pf_free_fragment(frag);
257 KASSERT((TAILQ_EMPTY(&pf_cachequeue) ||
258 TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag),
259 ("!(TAILQ_EMPTY() || TAILQ_LAST() == farg): %s",
262 KASSERT(TAILQ_EMPTY(&pf_cachequeue) ||
263 TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag);
269 * Try to flush old fragments to make space for new ones
273 pf_flush_fragments(void)
275 struct pf_fragment *frag;
278 goal = pf_nfrents * 9 / 10;
279 DPFPRINTF(("trying to free > %d frents\n",
281 while (goal < pf_nfrents) {
282 frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue);
285 pf_free_fragment(frag);
289 goal = pf_ncache * 9 / 10;
290 DPFPRINTF(("trying to free > %d cache entries\n",
292 while (goal < pf_ncache) {
293 frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue);
296 pf_free_fragment(frag);
300 /* Frees the fragments and all associated entries */
303 pf_free_fragment(struct pf_fragment *frag)
305 struct pf_frent *frent;
306 struct pf_frcache *frcache;
308 /* Free all fragments */
309 if (BUFFER_FRAGMENTS(frag)) {
310 for (frent = LIST_FIRST(&frag->fr_queue); frent;
311 frent = LIST_FIRST(&frag->fr_queue)) {
312 LIST_REMOVE(frent, fr_next);
314 m_freem(frent->fr_m);
315 pool_put(&pf_frent_pl, frent);
319 for (frcache = LIST_FIRST(&frag->fr_cache); frcache;
320 frcache = LIST_FIRST(&frag->fr_cache)) {
321 LIST_REMOVE(frcache, fr_next);
324 KASSERT((LIST_EMPTY(&frag->fr_cache) ||
325 LIST_FIRST(&frag->fr_cache)->fr_off >
327 ("! (LIST_EMPTY() || LIST_FIRST()->fr_off >"
328 " frcache->fr_end): %s", __FUNCTION__));
330 KASSERT(LIST_EMPTY(&frag->fr_cache) ||
331 LIST_FIRST(&frag->fr_cache)->fr_off >
335 pool_put(&pf_cent_pl, frcache);
340 pf_remove_fragment(frag);
344 pf_ip2key(struct pf_fragment *key, struct ip *ip)
346 key->fr_p = ip->ip_p;
347 key->fr_id = ip->ip_id;
348 key->fr_src.s_addr = ip->ip_src.s_addr;
349 key->fr_dst.s_addr = ip->ip_dst.s_addr;
353 pf_find_fragment(struct ip *ip, struct pf_frag_tree *tree)
355 struct pf_fragment key;
356 struct pf_fragment *frag;
360 frag = RB_FIND(pf_frag_tree, tree, &key);
362 /* XXX Are we sure we want to update the timeout? */
363 frag->fr_timeout = time_second;
364 if (BUFFER_FRAGMENTS(frag)) {
365 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
366 TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
368 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
369 TAILQ_INSERT_HEAD(&pf_cachequeue, frag, frag_next);
376 /* Removes a fragment from the fragment queue and frees the fragment */
379 pf_remove_fragment(struct pf_fragment *frag)
381 if (BUFFER_FRAGMENTS(frag)) {
382 RB_REMOVE(pf_frag_tree, &pf_frag_tree, frag);
383 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
384 pool_put(&pf_frag_pl, frag);
386 RB_REMOVE(pf_frag_tree, &pf_cache_tree, frag);
387 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
388 pool_put(&pf_cache_pl, frag);
392 #define FR_IP_OFF(fr) ((ntohs((fr)->fr_ip->ip_off) & IP_OFFMASK) << 3)
394 pf_reassemble(struct mbuf **m0, struct pf_fragment **frag,
395 struct pf_frent *frent, int mff)
397 struct mbuf *m = *m0, *m2;
398 struct pf_frent *frea, *next;
399 struct pf_frent *frep = NULL;
400 struct ip *ip = frent->fr_ip;
401 int hlen = ip->ip_hl << 2;
402 u_int16_t off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
403 u_int16_t ip_len = ntohs(ip->ip_len) - ip->ip_hl * 4;
404 u_int16_t max = ip_len + off;
407 KASSERT((*frag == NULL || BUFFER_FRAGMENTS(*frag)),
408 ("! (*frag == NULL || BUFFER_FRAGMENTS(*frag)): %s", __FUNCTION__));
410 KASSERT(*frag == NULL || BUFFER_FRAGMENTS(*frag));
413 /* Strip off ip header */
417 /* Create a new reassembly queue for this packet */
419 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
421 pf_flush_fragments();
422 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
427 (*frag)->fr_flags = 0;
429 (*frag)->fr_src = frent->fr_ip->ip_src;
430 (*frag)->fr_dst = frent->fr_ip->ip_dst;
431 (*frag)->fr_p = frent->fr_ip->ip_p;
432 (*frag)->fr_id = frent->fr_ip->ip_id;
433 (*frag)->fr_timeout = time_second;
434 LIST_INIT(&(*frag)->fr_queue);
436 RB_INSERT(pf_frag_tree, &pf_frag_tree, *frag);
437 TAILQ_INSERT_HEAD(&pf_fragqueue, *frag, frag_next);
439 /* We do not have a previous fragment */
445 * Find a fragment after the current one:
446 * - off contains the real shifted offset.
448 LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
449 if (FR_IP_OFF(frea) > off)
455 KASSERT((frep != NULL || frea != NULL),
456 ("!(frep != NULL || frea != NULL): %s", __FUNCTION__));;
458 KASSERT(frep != NULL || frea != NULL);
462 FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl *
467 precut = FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) -
468 frep->fr_ip->ip_hl * 4 - off;
469 if (precut >= ip_len)
471 m_adj(frent->fr_m, precut);
472 DPFPRINTF(("overlap -%d\n", precut));
473 /* Enforce 8 byte boundaries */
474 ip->ip_off = htons(ntohs(ip->ip_off) + (precut >> 3));
475 off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
477 ip->ip_len = htons(ip_len);
480 for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
485 aftercut = ip_len + off - FR_IP_OFF(frea);
486 DPFPRINTF(("adjust overlap %d\n", aftercut));
487 if (aftercut < ntohs(frea->fr_ip->ip_len) - frea->fr_ip->ip_hl
490 frea->fr_ip->ip_len =
491 htons(ntohs(frea->fr_ip->ip_len) - aftercut);
492 frea->fr_ip->ip_off = htons(ntohs(frea->fr_ip->ip_off) +
494 m_adj(frea->fr_m, aftercut);
498 /* This fragment is completely overlapped, lose it */
499 next = LIST_NEXT(frea, fr_next);
501 LIST_REMOVE(frea, fr_next);
502 pool_put(&pf_frent_pl, frea);
507 /* Update maximum data size */
508 if ((*frag)->fr_max < max)
509 (*frag)->fr_max = max;
510 /* This is the last segment */
512 (*frag)->fr_flags |= PFFRAG_SEENLAST;
515 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
517 LIST_INSERT_AFTER(frep, frent, fr_next);
519 /* Check if we are completely reassembled */
520 if (!((*frag)->fr_flags & PFFRAG_SEENLAST))
523 /* Check if we have all the data */
525 for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
526 next = LIST_NEXT(frep, fr_next);
528 off += ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl * 4;
529 if (off < (*frag)->fr_max &&
530 (next == NULL || FR_IP_OFF(next) != off))
532 DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
533 off, next == NULL ? -1 : FR_IP_OFF(next),
538 DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
539 if (off < (*frag)->fr_max)
542 /* We have all the data */
543 frent = LIST_FIRST(&(*frag)->fr_queue);
545 KASSERT((frent != NULL), ("frent == NULL: %s", __FUNCTION__));
547 KASSERT(frent != NULL);
549 if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
550 DPFPRINTF(("drop: too big: %d\n", off));
551 pf_free_fragment(*frag);
555 next = LIST_NEXT(frent, fr_next);
557 /* Magic from ip_input */
563 pool_put(&pf_frent_pl, frent);
565 for (frent = next; frent != NULL; frent = next) {
566 next = LIST_NEXT(frent, fr_next);
569 pool_put(&pf_frent_pl, frent);
572 m->m_pkthdr.csum_flags &= m2->m_pkthdr.csum_flags;
573 m->m_pkthdr.csum_data += m2->m_pkthdr.csum_data;
578 while (m->m_pkthdr.csum_data & 0xffff0000)
579 m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
580 (m->m_pkthdr.csum_data >> 16);
583 ip->ip_src = (*frag)->fr_src;
584 ip->ip_dst = (*frag)->fr_dst;
586 /* Remove from fragment queue */
587 pf_remove_fragment(*frag);
590 hlen = ip->ip_hl << 2;
591 ip->ip_len = htons(off + hlen);
595 /* some debugging cruft by sklower, below, will go away soon */
596 /* XXX this should be done elsewhere */
597 if (m->m_flags & M_PKTHDR) {
599 for (m2 = m; m2; m2 = m2->m_next)
601 m->m_pkthdr.len = plen;
604 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip->ip_len)));
608 /* Oops - fail safe - drop packet */
609 pool_put(&pf_frent_pl, frent);
616 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
617 int drop, int *nomem)
619 struct mbuf *m = *m0;
620 struct pf_frcache *frp, *fra, *cur = NULL;
621 int ip_len = ntohs(h->ip_len) - (h->ip_hl << 2);
622 u_int16_t off = ntohs(h->ip_off) << 3;
623 u_int16_t max = ip_len + off;
627 KASSERT((*frag == NULL || !BUFFER_FRAGMENTS(*frag)),
628 ("!(*frag == NULL || !BUFFER_FRAGMENTS(*frag)): %s", __FUNCTION__));
630 KASSERT(*frag == NULL || !BUFFER_FRAGMENTS(*frag));
633 /* Create a new range queue for this packet */
635 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
637 pf_flush_fragments();
638 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
643 /* Get an entry for the queue */
644 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
646 pool_put(&pf_cache_pl, *frag);
652 (*frag)->fr_flags = PFFRAG_NOBUFFER;
654 (*frag)->fr_src = h->ip_src;
655 (*frag)->fr_dst = h->ip_dst;
656 (*frag)->fr_p = h->ip_p;
657 (*frag)->fr_id = h->ip_id;
658 (*frag)->fr_timeout = time_second;
662 LIST_INIT(&(*frag)->fr_cache);
663 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
665 RB_INSERT(pf_frag_tree, &pf_cache_tree, *frag);
666 TAILQ_INSERT_HEAD(&pf_cachequeue, *frag, frag_next);
668 DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off, max));
674 * Find a fragment after the current one:
675 * - off contains the real shifted offset.
678 LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
679 if (fra->fr_off > off)
685 KASSERT((frp != NULL || fra != NULL),
686 ("!(frp != NULL || fra != NULL): %s", __FUNCTION__));
688 KASSERT(frp != NULL || fra != NULL);
694 precut = frp->fr_end - off;
695 if (precut >= ip_len) {
696 /* Fragment is entirely a duplicate */
697 DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
698 h->ip_id, frp->fr_off, frp->fr_end, off, max));
702 /* They are adjacent. Fixup cache entry */
703 DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
704 h->ip_id, frp->fr_off, frp->fr_end, off, max));
706 } else if (precut > 0) {
707 /* The first part of this payload overlaps with a
708 * fragment that has already been passed.
709 * Need to trim off the first part of the payload.
710 * But to do so easily, we need to create another
711 * mbuf to throw the original header into.
714 DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
715 h->ip_id, precut, frp->fr_off, frp->fr_end, off,
720 /* Update the previous frag to encompass this one */
724 /* XXX Optimization opportunity
725 * This is a very heavy way to trim the payload.
726 * we could do it much faster by diddling mbuf
727 * internals but that would be even less legible
728 * than this mbuf magic. For my next trick,
729 * I'll pull a rabbit out of my laptop.
732 *m0 = m_dup(m, M_DONTWAIT);
734 *m0 = m_copym2(m, 0, h->ip_hl << 2, M_NOWAIT);
739 /* From KAME Project : We have missed this! */
740 m_adj(*m0, (h->ip_hl << 2) -
741 (*m0)->m_pkthdr.len);
743 KASSERT(((*m0)->m_next == NULL),
744 ("(*m0)->m_next != NULL: %s",
747 KASSERT((*m0)->m_next == NULL);
749 m_adj(m, precut + (h->ip_hl << 2));
752 if (m->m_flags & M_PKTHDR) {
755 for (t = m; t; t = t->m_next)
757 m->m_pkthdr.len = plen;
761 h = mtod(m, struct ip *);
764 KASSERT(((int)m->m_len ==
765 ntohs(h->ip_len) - precut),
766 ("m->m_len != ntohs(h->ip_len) - precut: %s",
769 KASSERT((int)m->m_len ==
770 ntohs(h->ip_len) - precut);
772 h->ip_off = htons(ntohs(h->ip_off) +
774 h->ip_len = htons(ntohs(h->ip_len) - precut);
779 /* There is a gap between fragments */
781 DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
782 h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
785 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
792 LIST_INSERT_AFTER(frp, cur, fr_next);
800 aftercut = max - fra->fr_off;
802 /* Adjacent fragments */
803 DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
804 h->ip_id, off, max, fra->fr_off, fra->fr_end));
807 } else if (aftercut > 0) {
808 /* Need to chop off the tail of this fragment */
809 DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
810 h->ip_id, aftercut, off, max, fra->fr_off,
819 if (m->m_flags & M_PKTHDR) {
822 for (t = m; t; t = t->m_next)
824 m->m_pkthdr.len = plen;
826 h = mtod(m, struct ip *);
828 KASSERT(((int)m->m_len == ntohs(h->ip_len) - aftercut),
829 ("m->m_len != ntohs(h->ip_len) - aftercut: %s",
832 KASSERT((int)m->m_len ==
833 ntohs(h->ip_len) - aftercut);
835 h->ip_len = htons(ntohs(h->ip_len) - aftercut);
839 } else if (frp == NULL) {
840 /* There is a gap between fragments */
841 DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
842 h->ip_id, -aftercut, off, max, fra->fr_off,
845 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
852 LIST_INSERT_BEFORE(fra, cur, fr_next);
856 /* Need to glue together two separate fragment descriptors */
858 if (cur && fra->fr_off <= cur->fr_end) {
859 /* Need to merge in a previous 'cur' */
860 DPFPRINTF(("fragcache[%d]: adjacent(merge "
861 "%d-%d) %d-%d (%d-%d)\n",
862 h->ip_id, cur->fr_off, cur->fr_end, off,
863 max, fra->fr_off, fra->fr_end));
864 fra->fr_off = cur->fr_off;
865 LIST_REMOVE(cur, fr_next);
866 pool_put(&pf_cent_pl, cur);
870 } else if (frp && fra->fr_off <= frp->fr_end) {
871 /* Need to merge in a modified 'frp' */
873 KASSERT((cur == NULL), ("cur != NULL: %s",
876 KASSERT(cur == NULL);
878 DPFPRINTF(("fragcache[%d]: adjacent(merge "
879 "%d-%d) %d-%d (%d-%d)\n",
880 h->ip_id, frp->fr_off, frp->fr_end, off,
881 max, fra->fr_off, fra->fr_end));
882 fra->fr_off = frp->fr_off;
883 LIST_REMOVE(frp, fr_next);
884 pool_put(&pf_cent_pl, frp);
894 * We must keep tracking the overall fragment even when
895 * we're going to drop it anyway so that we know when to
896 * free the overall descriptor. Thus we drop the frag late.
903 /* Update maximum data size */
904 if ((*frag)->fr_max < max)
905 (*frag)->fr_max = max;
907 /* This is the last segment */
909 (*frag)->fr_flags |= PFFRAG_SEENLAST;
911 /* Check if we are completely reassembled */
912 if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
913 LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
914 LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
915 /* Remove from fragment queue */
916 DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
918 pf_free_fragment(*frag);
927 /* Still need to pay attention to !IP_MF */
928 if (!mff && *frag != NULL)
929 (*frag)->fr_flags |= PFFRAG_SEENLAST;
936 /* Still need to pay attention to !IP_MF */
937 if (!mff && *frag != NULL)
938 (*frag)->fr_flags |= PFFRAG_SEENLAST;
941 /* This fragment has been deemed bad. Don't reass */
942 if (((*frag)->fr_flags & PFFRAG_DROP) == 0)
943 DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
945 (*frag)->fr_flags |= PFFRAG_DROP;
953 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
956 struct mbuf *m = *m0;
958 struct pf_frent *frent;
959 struct pf_fragment *frag = NULL;
960 struct ip *h = mtod(m, struct ip *);
961 int mff = (ntohs(h->ip_off) & IP_MF);
962 int hlen = h->ip_hl << 2;
963 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
968 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
971 if (pfi_kif_match(r->kif, kif) == r->ifnot)
972 r = r->skip[PF_SKIP_IFP].ptr;
973 else if (r->direction && r->direction != dir)
974 r = r->skip[PF_SKIP_DIR].ptr;
975 else if (r->af && r->af != AF_INET)
976 r = r->skip[PF_SKIP_AF].ptr;
977 else if (r->proto && r->proto != h->ip_p)
978 r = r->skip[PF_SKIP_PROTO].ptr;
979 else if (PF_MISMATCHAW(&r->src.addr,
980 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
982 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
983 else if (PF_MISMATCHAW(&r->dst.addr,
984 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
986 r = r->skip[PF_SKIP_DST_ADDR].ptr;
991 if (r == NULL || r->action == PF_NOSCRUB)
994 r->packets[dir == PF_OUT]++;
995 r->bytes[dir == PF_OUT] += pd->tot_len;
998 /* Check for illegal packets */
999 if (hlen < (int)sizeof(struct ip))
1002 if (hlen > ntohs(h->ip_len))
1005 /* Clear IP_DF if the rule uses the no-df option */
1006 if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1007 u_int16_t ip_off = h->ip_off;
1009 h->ip_off &= htons(~IP_DF);
1010 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1013 /* We will need other tests here */
1014 if (!fragoff && !mff)
1017 /* We're dealing with a fragment now. Don't allow fragments
1018 * with IP_DF to enter the cache. If the flag was cleared by
1019 * no-df above, fine. Otherwise drop it.
1021 if (h->ip_off & htons(IP_DF)) {
1022 DPFPRINTF(("IP_DF\n"));
1026 ip_len = ntohs(h->ip_len) - hlen;
1027 ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1029 /* All fragments are 8 byte aligned */
1030 if (mff && (ip_len & 0x7)) {
1031 DPFPRINTF(("mff and %d\n", ip_len));
1035 /* Respect maximum length */
1036 if (fragoff + ip_len > IP_MAXPACKET) {
1037 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
1040 max = fragoff + ip_len;
1042 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
1043 /* Fully buffer all of the fragments */
1045 frag = pf_find_fragment(h, &pf_frag_tree);
1047 /* Check if we saw the last fragment already */
1048 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
1052 /* Get an entry for the fragment queue */
1053 frent = pool_get(&pf_frent_pl, PR_NOWAIT);
1054 if (frent == NULL) {
1055 REASON_SET(reason, PFRES_MEMORY);
1062 /* Might return a completely reassembled mbuf, or NULL */
1063 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
1064 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
1069 /* use mtag from concatenated mbuf chain */
1070 pd->pf_mtag = pf_find_mtag(m);
1072 if (pd->pf_mtag == NULL) {
1073 printf("%s: pf_find_mtag returned NULL(1)\n", __func__);
1074 if ((pd->pf_mtag = pf_get_mtag(m)) == NULL) {
1081 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
1084 h = mtod(m, struct ip *);
1086 /* non-buffering fragment cache (drops or masks overlaps) */
1089 if (dir == PF_OUT && pd->pf_mtag->flags & PF_TAG_FRAGCACHE) {
1091 * Already passed the fragment cache in the
1092 * input direction. If we continued, it would
1093 * appear to be a dup and would be dropped.
1098 frag = pf_find_fragment(h, &pf_cache_tree);
1100 /* Check if we saw the last fragment already */
1101 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
1102 max > frag->fr_max) {
1103 if (r->rule_flag & PFRULE_FRAGDROP)
1104 frag->fr_flags |= PFFRAG_DROP;
1108 *m0 = m = pf_fragcache(m0, h, &frag, mff,
1109 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
1116 /* use mtag from copied and trimmed mbuf chain */
1117 pd->pf_mtag = pf_find_mtag(m);
1119 if (pd->pf_mtag == NULL) {
1120 printf("%s: pf_find_mtag returned NULL(2)\n", __func__);
1121 if ((pd->pf_mtag = pf_get_mtag(m)) == NULL) {
1129 pd->pf_mtag->flags |= PF_TAG_FRAGCACHE;
1131 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
1137 /* At this point, only IP_DF is allowed in ip_off */
1138 if (h->ip_off & ~htons(IP_DF)) {
1139 u_int16_t ip_off = h->ip_off;
1141 h->ip_off &= htons(IP_DF);
1142 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1145 /* Enforce a minimum ttl, may cause endless packet loops */
1146 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
1147 u_int16_t ip_ttl = h->ip_ttl;
1149 h->ip_ttl = r->min_ttl;
1150 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1153 if (r->rule_flag & PFRULE_RANDOMID) {
1154 u_int16_t ip_id = h->ip_id;
1156 h->ip_id = ip_randomid();
1157 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1159 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1160 pd->flags |= PFDESC_IP_REAS;
1165 /* Enforce a minimum ttl, may cause endless packet loops */
1166 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
1167 u_int16_t ip_ttl = h->ip_ttl;
1169 h->ip_ttl = r->min_ttl;
1170 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1172 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1173 pd->flags |= PFDESC_IP_REAS;
1177 REASON_SET(reason, PFRES_MEMORY);
1178 if (r != NULL && r->log)
1179 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1183 REASON_SET(reason, PFRES_NORM);
1184 if (r != NULL && r->log)
1185 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1189 DPFPRINTF(("dropping bad fragment\n"));
1191 /* Free associated fragments */
1193 pf_free_fragment(frag);
1195 REASON_SET(reason, PFRES_FRAG);
1196 if (r != NULL && r->log)
1197 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1204 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1205 u_short *reason, struct pf_pdesc *pd)
1207 struct mbuf *m = *m0;
1209 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1213 struct ip6_opt_jumbo jumbo;
1214 struct ip6_frag frag;
1215 u_int32_t jumbolen = 0, plen;
1216 u_int16_t fragoff = 0;
1222 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1225 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1226 r = r->skip[PF_SKIP_IFP].ptr;
1227 else if (r->direction && r->direction != dir)
1228 r = r->skip[PF_SKIP_DIR].ptr;
1229 else if (r->af && r->af != AF_INET6)
1230 r = r->skip[PF_SKIP_AF].ptr;
1231 #if 0 /* header chain! */
1232 else if (r->proto && r->proto != h->ip6_nxt)
1233 r = r->skip[PF_SKIP_PROTO].ptr;
1235 else if (PF_MISMATCHAW(&r->src.addr,
1236 (struct pf_addr *)&h->ip6_src, AF_INET6,
1238 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1239 else if (PF_MISMATCHAW(&r->dst.addr,
1240 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1242 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1247 if (r == NULL || r->action == PF_NOSCRUB)
1250 r->packets[dir == PF_OUT]++;
1251 r->bytes[dir == PF_OUT] += pd->tot_len;
1254 /* Check for illegal packets */
1255 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1258 off = sizeof(struct ip6_hdr);
1263 case IPPROTO_FRAGMENT:
1267 case IPPROTO_ROUTING:
1268 case IPPROTO_DSTOPTS:
1269 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1272 if (proto == IPPROTO_AH)
1273 off += (ext.ip6e_len + 2) * 4;
1275 off += (ext.ip6e_len + 1) * 8;
1276 proto = ext.ip6e_nxt;
1278 case IPPROTO_HOPOPTS:
1279 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1282 optend = off + (ext.ip6e_len + 1) * 8;
1283 ooff = off + sizeof(ext);
1285 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1286 sizeof(opt.ip6o_type), NULL, NULL,
1289 if (opt.ip6o_type == IP6OPT_PAD1) {
1293 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1294 NULL, NULL, AF_INET6))
1296 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1298 switch (opt.ip6o_type) {
1300 if (h->ip6_plen != 0)
1302 if (!pf_pull_hdr(m, ooff, &jumbo,
1303 sizeof(jumbo), NULL, NULL,
1306 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1308 jumbolen = ntohl(jumbolen);
1309 if (jumbolen <= IPV6_MAXPACKET)
1311 if (sizeof(struct ip6_hdr) + jumbolen !=
1318 ooff += sizeof(opt) + opt.ip6o_len;
1319 } while (ooff < optend);
1322 proto = ext.ip6e_nxt;
1328 } while (!terminal);
1330 /* jumbo payload option must be present, or plen > 0 */
1331 if (ntohs(h->ip6_plen) == 0)
1334 plen = ntohs(h->ip6_plen);
1337 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1340 /* Enforce a minimum ttl, may cause endless packet loops */
1341 if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1342 h->ip6_hlim = r->min_ttl;
1347 if (ntohs(h->ip6_plen) == 0 || jumbolen)
1349 plen = ntohs(h->ip6_plen);
1351 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1353 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1354 if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1357 /* do something about it */
1358 /* remember to set pd->flags |= PFDESC_IP_REAS */
1362 REASON_SET(reason, PFRES_SHORT);
1363 if (r != NULL && r->log)
1364 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1368 REASON_SET(reason, PFRES_NORM);
1369 if (r != NULL && r->log)
1370 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1374 REASON_SET(reason, PFRES_FRAG);
1375 if (r != NULL && r->log)
1376 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1382 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1383 int off, void *h, struct pf_pdesc *pd)
1385 struct pf_rule *r, *rm = NULL;
1386 struct tcphdr *th = pd->hdr.tcp;
1390 sa_family_t af = pd->af;
1392 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1395 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1396 r = r->skip[PF_SKIP_IFP].ptr;
1397 else if (r->direction && r->direction != dir)
1398 r = r->skip[PF_SKIP_DIR].ptr;
1399 else if (r->af && r->af != af)
1400 r = r->skip[PF_SKIP_AF].ptr;
1401 else if (r->proto && r->proto != pd->proto)
1402 r = r->skip[PF_SKIP_PROTO].ptr;
1403 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1405 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1406 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1407 r->src.port[0], r->src.port[1], th->th_sport))
1408 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1409 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1411 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1412 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1413 r->dst.port[0], r->dst.port[1], th->th_dport))
1414 r = r->skip[PF_SKIP_DST_PORT].ptr;
1415 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1416 pf_osfp_fingerprint(pd, m, off, th),
1418 r = TAILQ_NEXT(r, entries);
1425 if (rm == NULL || rm->action == PF_NOSCRUB)
1428 r->packets[dir == PF_OUT]++;
1429 r->bytes[dir == PF_OUT] += pd->tot_len;
1432 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1433 pd->flags |= PFDESC_TCP_NORM;
1435 flags = th->th_flags;
1436 if (flags & TH_SYN) {
1437 /* Illegal packet */
1444 /* Illegal packet */
1445 if (!(flags & (TH_ACK|TH_RST)))
1449 if (!(flags & TH_ACK)) {
1450 /* These flags are only valid if ACK is set */
1451 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1455 /* Check for illegal header length */
1456 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1459 /* If flags changed, or reserved data set, then adjust */
1460 if (flags != th->th_flags || th->th_x2 != 0) {
1463 ov = *(u_int16_t *)(&th->th_ack + 1);
1464 th->th_flags = flags;
1466 nv = *(u_int16_t *)(&th->th_ack + 1);
1468 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1472 /* Remove urgent pointer, if TH_URG is not set */
1473 if (!(flags & TH_URG) && th->th_urp) {
1474 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1479 /* Process options */
1480 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off))
1483 /* copy back packet headers if we sanitized */
1485 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1490 REASON_SET(&reason, PFRES_NORM);
1491 if (rm != NULL && r->log)
1492 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL, pd);
1497 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1498 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1500 u_int32_t tsval, tsecr;
1505 KASSERT((src->scrub == NULL),
1506 ("pf_normalize_tcp_init: src->scrub != NULL"));
1508 KASSERT(src->scrub == NULL);
1511 src->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
1512 if (src->scrub == NULL)
1514 bzero(src->scrub, sizeof(*src->scrub));
1519 struct ip *h = mtod(m, struct ip *);
1520 src->scrub->pfss_ttl = h->ip_ttl;
1526 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1527 src->scrub->pfss_ttl = h->ip6_hlim;
1535 * All normalizations below are only begun if we see the start of
1536 * the connections. They must all set an enabled bit in pfss_flags
1538 if ((th->th_flags & TH_SYN) == 0)
1542 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1543 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1544 /* Diddle with TCP options */
1546 opt = hdr + sizeof(struct tcphdr);
1547 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1548 while (hlen >= TCPOLEN_TIMESTAMP) {
1550 case TCPOPT_EOL: /* FALLTHROUGH */
1555 case TCPOPT_TIMESTAMP:
1556 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1557 src->scrub->pfss_flags |=
1559 src->scrub->pfss_ts_mod =
1560 htonl(arc4random());
1562 /* note PFSS_PAWS not set yet */
1563 memcpy(&tsval, &opt[2],
1565 memcpy(&tsecr, &opt[6],
1567 src->scrub->pfss_tsval0 = ntohl(tsval);
1568 src->scrub->pfss_tsval = ntohl(tsval);
1569 src->scrub->pfss_tsecr = ntohl(tsecr);
1570 getmicrouptime(&src->scrub->pfss_last);
1574 hlen -= MAX(opt[1], 2);
1575 opt += MAX(opt[1], 2);
1585 pf_normalize_tcp_cleanup(struct pf_state *state)
1587 if (state->src.scrub)
1588 pool_put(&pf_state_scrub_pl, state->src.scrub);
1589 if (state->dst.scrub)
1590 pool_put(&pf_state_scrub_pl, state->dst.scrub);
1592 /* Someday... flush the TCP segment reassembly descriptors. */
1596 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1597 u_short *reason, struct tcphdr *th, struct pf_state *state,
1598 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1600 struct timeval uptime;
1601 u_int32_t tsval, tsecr;
1602 u_int tsval_from_last;
1609 KASSERT((src->scrub || dst->scrub),
1610 ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1612 KASSERT(src->scrub || dst->scrub);
1616 * Enforce the minimum TTL seen for this connection. Negate a common
1617 * technique to evade an intrusion detection system and confuse
1618 * firewall state code.
1624 struct ip *h = mtod(m, struct ip *);
1625 if (h->ip_ttl > src->scrub->pfss_ttl)
1626 src->scrub->pfss_ttl = h->ip_ttl;
1627 h->ip_ttl = src->scrub->pfss_ttl;
1635 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1636 if (h->ip6_hlim > src->scrub->pfss_ttl)
1637 src->scrub->pfss_ttl = h->ip6_hlim;
1638 h->ip6_hlim = src->scrub->pfss_ttl;
1645 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1646 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1647 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1648 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1649 /* Diddle with TCP options */
1651 opt = hdr + sizeof(struct tcphdr);
1652 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1653 while (hlen >= TCPOLEN_TIMESTAMP) {
1655 case TCPOPT_EOL: /* FALLTHROUGH */
1660 case TCPOPT_TIMESTAMP:
1661 /* Modulate the timestamps. Can be used for
1662 * NAT detection, OS uptime determination or
1667 /* Huh? Multiple timestamps!? */
1668 if (pf_status.debug >= PF_DEBUG_MISC) {
1669 DPFPRINTF(("multiple TS??"));
1670 pf_print_state(state);
1673 REASON_SET(reason, PFRES_TS);
1676 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1677 memcpy(&tsval, &opt[2],
1679 if (tsval && src->scrub &&
1680 (src->scrub->pfss_flags &
1682 tsval = ntohl(tsval);
1683 pf_change_a(&opt[2],
1686 src->scrub->pfss_ts_mod),
1691 /* Modulate TS reply iff valid (!0) */
1692 memcpy(&tsecr, &opt[6],
1694 if (tsecr && dst->scrub &&
1695 (dst->scrub->pfss_flags &
1697 tsecr = ntohl(tsecr)
1698 - dst->scrub->pfss_ts_mod;
1699 pf_change_a(&opt[6],
1700 &th->th_sum, htonl(tsecr),
1708 hlen -= MAX(opt[1], 2);
1709 opt += MAX(opt[1], 2);
1714 /* Copyback the options, caller copys back header */
1716 m_copyback(m, off + sizeof(struct tcphdr),
1717 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1718 sizeof(struct tcphdr));
1724 * Must invalidate PAWS checks on connections idle for too long.
1725 * The fastest allowed timestamp clock is 1ms. That turns out to
1726 * be about 24 days before it wraps. XXX Right now our lowerbound
1727 * TS echo check only works for the first 12 days of a connection
1728 * when the TS has exhausted half its 32bit space
1730 #define TS_MAX_IDLE (24*24*60*60)
1731 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1733 getmicrouptime(&uptime);
1734 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1735 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1736 time_second - state->creation > TS_MAX_CONN)) {
1737 if (pf_status.debug >= PF_DEBUG_MISC) {
1738 DPFPRINTF(("src idled out of PAWS\n"));
1739 pf_print_state(state);
1742 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1745 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1746 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1747 if (pf_status.debug >= PF_DEBUG_MISC) {
1748 DPFPRINTF(("dst idled out of PAWS\n"));
1749 pf_print_state(state);
1752 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1756 if (got_ts && src->scrub && dst->scrub &&
1757 (src->scrub->pfss_flags & PFSS_PAWS) &&
1758 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1759 /* Validate that the timestamps are "in-window".
1760 * RFC1323 describes TCP Timestamp options that allow
1761 * measurement of RTT (round trip time) and PAWS
1762 * (protection against wrapped sequence numbers). PAWS
1763 * gives us a set of rules for rejecting packets on
1764 * long fat pipes (packets that were somehow delayed
1765 * in transit longer than the time it took to send the
1766 * full TCP sequence space of 4Gb). We can use these
1767 * rules and infer a few others that will let us treat
1768 * the 32bit timestamp and the 32bit echoed timestamp
1769 * as sequence numbers to prevent a blind attacker from
1770 * inserting packets into a connection.
1773 * - The timestamp on this packet must be greater than
1774 * or equal to the last value echoed by the other
1775 * endpoint. The RFC says those will be discarded
1776 * since it is a dup that has already been acked.
1777 * This gives us a lowerbound on the timestamp.
1778 * timestamp >= other last echoed timestamp
1779 * - The timestamp will be less than or equal to
1780 * the last timestamp plus the time between the
1781 * last packet and now. The RFC defines the max
1782 * clock rate as 1ms. We will allow clocks to be
1783 * up to 10% fast and will allow a total difference
1784 * or 30 seconds due to a route change. And this
1785 * gives us an upperbound on the timestamp.
1786 * timestamp <= last timestamp + max ticks
1787 * We have to be careful here. Windows will send an
1788 * initial timestamp of zero and then initialize it
1789 * to a random value after the 3whs; presumably to
1790 * avoid a DoS by having to call an expensive RNG
1791 * during a SYN flood. Proof MS has at least one
1792 * good security geek.
1794 * - The TCP timestamp option must also echo the other
1795 * endpoints timestamp. The timestamp echoed is the
1796 * one carried on the earliest unacknowledged segment
1797 * on the left edge of the sequence window. The RFC
1798 * states that the host will reject any echoed
1799 * timestamps that were larger than any ever sent.
1800 * This gives us an upperbound on the TS echo.
1801 * tescr <= largest_tsval
1802 * - The lowerbound on the TS echo is a little more
1803 * tricky to determine. The other endpoint's echoed
1804 * values will not decrease. But there may be
1805 * network conditions that re-order packets and
1806 * cause our view of them to decrease. For now the
1807 * only lowerbound we can safely determine is that
1808 * the TS echo will never be less than the orginal
1809 * TS. XXX There is probably a better lowerbound.
1810 * Remove TS_MAX_CONN with better lowerbound check.
1811 * tescr >= other original TS
1813 * It is also important to note that the fastest
1814 * timestamp clock of 1ms will wrap its 32bit space in
1815 * 24 days. So we just disable TS checking after 24
1816 * days of idle time. We actually must use a 12d
1817 * connection limit until we can come up with a better
1818 * lowerbound to the TS echo check.
1820 struct timeval delta_ts;
1825 * PFTM_TS_DIFF is how many seconds of leeway to allow
1826 * a host's timestamp. This can happen if the previous
1827 * packet got delayed in transit for much longer than
1830 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1831 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1834 /* Calculate max ticks since the last timestamp */
1835 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1836 #define TS_MICROSECS 1000000 /* microseconds per second */
1839 #define timersub(tvp, uvp, vvp) \
1841 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
1842 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
1843 if ((vvp)->tv_usec < 0) { \
1845 (vvp)->tv_usec += 1000000; \
1850 timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1851 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1852 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1855 if ((src->state >= TCPS_ESTABLISHED &&
1856 dst->state >= TCPS_ESTABLISHED) &&
1857 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1858 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1859 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1860 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1861 /* Bad RFC1323 implementation or an insertion attack.
1863 * - Solaris 2.6 and 2.7 are known to send another ACK
1864 * after the FIN,FIN|ACK,ACK closing that carries
1868 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1869 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1870 SEQ_GT(tsval, src->scrub->pfss_tsval +
1871 tsval_from_last) ? '1' : ' ',
1872 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1873 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1875 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1876 "idle: %jus %lums\n",
1877 tsval, tsecr, tsval_from_last,
1878 (uintmax_t)delta_ts.tv_sec,
1879 delta_ts.tv_usec / 1000));
1880 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1881 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1882 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1883 "\n", dst->scrub->pfss_tsval,
1884 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1886 DPFPRINTF((" tsval: %lu tsecr: %lu +ticks: %lu "
1887 "idle: %lus %lums\n",
1888 tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
1889 delta_ts.tv_usec / 1000));
1890 DPFPRINTF((" src->tsval: %lu tsecr: %lu\n",
1891 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1892 DPFPRINTF((" dst->tsval: %lu tsecr: %lu tsval0: %lu"
1893 "\n", dst->scrub->pfss_tsval,
1894 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1896 if (pf_status.debug >= PF_DEBUG_MISC) {
1897 pf_print_state(state);
1898 pf_print_flags(th->th_flags);
1901 REASON_SET(reason, PFRES_TS);
1905 /* XXX I'd really like to require tsecr but it's optional */
1907 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1908 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1909 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1910 src->scrub && dst->scrub &&
1911 (src->scrub->pfss_flags & PFSS_PAWS) &&
1912 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1913 /* Didn't send a timestamp. Timestamps aren't really useful
1915 * - connection opening or closing (often not even sent).
1916 * but we must not let an attacker to put a FIN on a
1917 * data packet to sneak it through our ESTABLISHED check.
1918 * - on a TCP reset. RFC suggests not even looking at TS.
1919 * - on an empty ACK. The TS will not be echoed so it will
1920 * probably not help keep the RTT calculation in sync and
1921 * there isn't as much danger when the sequence numbers
1922 * got wrapped. So some stacks don't include TS on empty
1925 * To minimize the disruption to mostly RFC1323 conformant
1926 * stacks, we will only require timestamps on data packets.
1928 * And what do ya know, we cannot require timestamps on data
1929 * packets. There appear to be devices that do legitimate
1930 * TCP connection hijacking. There are HTTP devices that allow
1931 * a 3whs (with timestamps) and then buffer the HTTP request.
1932 * If the intermediate device has the HTTP response cache, it
1933 * will spoof the response but not bother timestamping its
1934 * packets. So we can look for the presence of a timestamp in
1935 * the first data packet and if there, require it in all future
1939 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1941 * Hey! Someone tried to sneak a packet in. Or the
1942 * stack changed its RFC1323 behavior?!?!
1944 if (pf_status.debug >= PF_DEBUG_MISC) {
1945 DPFPRINTF(("Did not receive expected RFC1323 "
1947 pf_print_state(state);
1948 pf_print_flags(th->th_flags);
1951 REASON_SET(reason, PFRES_TS);
1958 * We will note if a host sends his data packets with or without
1959 * timestamps. And require all data packets to contain a timestamp
1960 * if the first does. PAWS implicitly requires that all data packets be
1961 * timestamped. But I think there are middle-man devices that hijack
1962 * TCP streams immediately after the 3whs and don't timestamp their
1963 * packets (seen in a WWW accelerator or cache).
1965 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1966 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1968 src->scrub->pfss_flags |= PFSS_DATA_TS;
1970 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1971 if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1972 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1973 /* Don't warn if other host rejected RFC1323 */
1974 DPFPRINTF(("Broken RFC1323 stack did not "
1975 "timestamp data packet. Disabled PAWS "
1977 pf_print_state(state);
1978 pf_print_flags(th->th_flags);
1986 * Update PAWS values
1988 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1989 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1990 getmicrouptime(&src->scrub->pfss_last);
1991 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1992 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1993 src->scrub->pfss_tsval = tsval;
1996 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1997 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1998 src->scrub->pfss_tsecr = tsecr;
2000 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
2001 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
2002 src->scrub->pfss_tsval0 == 0)) {
2003 /* tsval0 MUST be the lowest timestamp */
2004 src->scrub->pfss_tsval0 = tsval;
2007 /* Only fully initialized after a TS gets echoed */
2008 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
2009 src->scrub->pfss_flags |= PFSS_PAWS;
2013 /* I have a dream.... TCP segment reassembly.... */
2018 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
2023 int opt, cnt, optlen = 0;
2027 thoff = th->th_off << 2;
2028 cnt = thoff - sizeof(struct tcphdr);
2029 optp = mtod(m, caddr_t) + off + sizeof(struct tcphdr);
2031 for (; cnt > 0; cnt -= optlen, optp += optlen) {
2033 if (opt == TCPOPT_EOL)
2035 if (opt == TCPOPT_NOP)
2041 if (optlen < 2 || optlen > cnt)
2046 mss = (u_int16_t *)(optp + 2);
2047 if ((ntohs(*mss)) > r->max_mss) {
2048 th->th_sum = pf_cksum_fixup(th->th_sum,
2049 *mss, htons(r->max_mss), 0);
2050 *mss = htons(r->max_mss);