1 /* $OpenBSD: pf_norm.c,v 1.113 2008/05/07 07:07:29 markus Exp $ */
4 * Copyright (c) 2010 The DragonFly Project. All rights reserved.
6 * Copyright 2001 Niels Provos <provos@citi.umich.edu>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "opt_inet6.h"
33 #include <sys/param.h>
34 #include <sys/systm.h>
36 #include <sys/filio.h>
37 #include <sys/fcntl.h>
38 #include <sys/socket.h>
39 #include <sys/kernel.h>
43 #include <net/if_types.h>
45 #include <net/route.h>
46 #include <net/pf/if_pflog.h>
48 #include <netinet/in.h>
49 #include <netinet/in_var.h>
50 #include <netinet/in_systm.h>
51 #include <netinet/ip.h>
52 #include <netinet/ip_var.h>
53 #include <netinet/tcp.h>
54 #include <netinet/tcp_seq.h>
55 #include <netinet/udp.h>
56 #include <netinet/ip_icmp.h>
59 #include <netinet/ip6.h>
62 #include <net/pf/pfvar.h>
64 #define PFFRAG_SEENLAST 0x0001 /* Seen the last fragment for this */
65 #define PFFRAG_NOBUFFER 0x0002 /* Non-buffering fragment cache */
66 #define PFFRAG_DROP 0x0004 /* Drop all fragments */
67 #define BUFFER_FRAGMENTS(fr) (!((fr)->fr_flags & PFFRAG_NOBUFFER))
70 TAILQ_HEAD(pf_fragqueue, pf_fragment) pf_fragqueue;
71 TAILQ_HEAD(pf_cachequeue, pf_fragment) pf_cachequeue;
73 static __inline int pf_frag_compare(struct pf_fragment *,
74 struct pf_fragment *);
75 RB_HEAD(pf_frag_tree, pf_fragment) pf_frag_tree, pf_cache_tree;
76 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
77 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
79 /* Private prototypes */
80 void pf_ip2key(struct pf_fragment *, struct ip *);
81 void pf_remove_fragment(struct pf_fragment *);
82 void pf_flush_fragments(void);
83 void pf_free_fragment(struct pf_fragment *);
84 struct pf_fragment *pf_find_fragment(struct ip *, struct pf_frag_tree *);
85 struct mbuf *pf_reassemble(struct mbuf **, struct pf_fragment **,
86 struct pf_frent *, int);
87 struct mbuf *pf_fragcache(struct mbuf **, struct ip*,
88 struct pf_fragment **, int, int, int *);
89 int pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
90 struct tcphdr *, int, sa_family_t);
92 #define DPFPRINTF(x) do { \
93 if (pf_status.debug >= PF_DEBUG_MISC) { \
94 kprintf("%s: ", __func__); \
99 static MALLOC_DEFINE(M_PFFRAGPL, "pffrag", "pf fragment pool list");
100 static MALLOC_DEFINE(M_PFCACHEPL, "pffrcache", "pf fragment cache pool list");
101 static MALLOC_DEFINE(M_PFFRENTPL, "pffrent", "pf frent pool list");
102 static MALLOC_DEFINE(M_PFCENTPL, "pffrcent", "pf fragment cent pool list");
103 static MALLOC_DEFINE(M_PFSTATESCRUBPL, "pfstatescrub", "pf state scrub pool list");
106 struct malloc_type *pf_frent_pl, *pf_frag_pl, *pf_cache_pl, *pf_cent_pl;
107 struct malloc_type *pf_state_scrub_pl;
108 int pf_nfrents, pf_ncache;
111 pf_normalize_init(void)
114 pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
115 pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
116 pool_sethardlimit(&pf_cache_pl, PFFRAG_FRCACHE_HIWAT, NULL, 0);
117 pool_sethardlimit(&pf_cent_pl, PFFRAG_FRCENT_HIWAT, NULL, 0);
120 TAILQ_INIT(&pf_fragqueue);
121 TAILQ_INIT(&pf_cachequeue);
125 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
129 if ((diff = a->fr_id - b->fr_id))
131 else if ((diff = a->fr_p - b->fr_p))
133 else if (a->fr_src.s_addr < b->fr_src.s_addr)
135 else if (a->fr_src.s_addr > b->fr_src.s_addr)
137 else if (a->fr_dst.s_addr < b->fr_dst.s_addr)
139 else if (a->fr_dst.s_addr > b->fr_dst.s_addr)
145 pf_purge_expired_fragments(void)
147 struct pf_fragment *frag;
148 u_int32_t expire = time_second -
149 pf_default_rule.timeout[PFTM_FRAG];
151 while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
152 KASSERT((BUFFER_FRAGMENTS(frag)),
153 ("BUFFER_FRAGMENTS(frag) == 0: %s", __func__));
154 if (frag->fr_timeout > expire)
157 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
158 pf_free_fragment(frag);
161 while ((frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue)) != NULL) {
162 KASSERT((!BUFFER_FRAGMENTS(frag)),
163 ("BUFFER_FRAGMENTS(frag) != 0: %s", __func__));
164 if (frag->fr_timeout > expire)
167 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
168 pf_free_fragment(frag);
169 KASSERT((TAILQ_EMPTY(&pf_cachequeue) ||
170 TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag),
171 ("!(TAILQ_EMPTY() || TAILQ_LAST() == farg): %s",
177 * Try to flush old fragments to make space for new ones
181 pf_flush_fragments(void)
183 struct pf_fragment *frag;
186 goal = pf_nfrents * 9 / 10;
187 DPFPRINTF(("trying to free > %d frents\n",
189 while (goal < pf_nfrents) {
190 frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue);
193 pf_free_fragment(frag);
197 goal = pf_ncache * 9 / 10;
198 DPFPRINTF(("trying to free > %d cache entries\n",
200 while (goal < pf_ncache) {
201 frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue);
204 pf_free_fragment(frag);
208 /* Frees the fragments and all associated entries */
211 pf_free_fragment(struct pf_fragment *frag)
213 struct pf_frent *frent;
214 struct pf_frcache *frcache;
216 /* Free all fragments */
217 if (BUFFER_FRAGMENTS(frag)) {
218 for (frent = LIST_FIRST(&frag->fr_queue); frent;
219 frent = LIST_FIRST(&frag->fr_queue)) {
220 LIST_REMOVE(frent, fr_next);
222 m_freem(frent->fr_m);
223 kfree(frent, M_PFFRENTPL);
227 for (frcache = LIST_FIRST(&frag->fr_cache); frcache;
228 frcache = LIST_FIRST(&frag->fr_cache)) {
229 LIST_REMOVE(frcache, fr_next);
231 KASSERT((LIST_EMPTY(&frag->fr_cache) ||
232 LIST_FIRST(&frag->fr_cache)->fr_off >
234 ("! (LIST_EMPTY() || LIST_FIRST()->fr_off >"
235 " frcache->fr_end): %s", __func__));
237 kfree(frcache, M_PFCENTPL);
242 pf_remove_fragment(frag);
246 pf_ip2key(struct pf_fragment *key, struct ip *ip)
248 key->fr_p = ip->ip_p;
249 key->fr_id = ip->ip_id;
250 key->fr_src.s_addr = ip->ip_src.s_addr;
251 key->fr_dst.s_addr = ip->ip_dst.s_addr;
255 pf_find_fragment(struct ip *ip, struct pf_frag_tree *tree)
257 struct pf_fragment key;
258 struct pf_fragment *frag;
262 frag = RB_FIND(pf_frag_tree, tree, &key);
264 /* XXX Are we sure we want to update the timeout? */
265 frag->fr_timeout = time_second;
266 if (BUFFER_FRAGMENTS(frag)) {
267 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
268 TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
270 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
271 TAILQ_INSERT_HEAD(&pf_cachequeue, frag, frag_next);
278 /* Removes a fragment from the fragment queue and frees the fragment */
281 pf_remove_fragment(struct pf_fragment *frag)
283 if (BUFFER_FRAGMENTS(frag)) {
284 RB_REMOVE(pf_frag_tree, &pf_frag_tree, frag);
285 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
286 kfree(frag, M_PFFRAGPL);
288 RB_REMOVE(pf_frag_tree, &pf_cache_tree, frag);
289 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
290 kfree(frag, M_PFCACHEPL);
294 #define FR_IP_OFF(fr) (((fr)->fr_ip->ip_off & IP_OFFMASK) << 3)
296 pf_reassemble(struct mbuf **m0, struct pf_fragment **frag,
297 struct pf_frent *frent, int mff)
299 struct mbuf *m = *m0, *m2;
300 struct pf_frent *frea, *next;
301 struct pf_frent *frep = NULL;
302 struct ip *ip = frent->fr_ip;
303 int hlen = ip->ip_hl << 2;
304 u_int16_t off = (ip->ip_off & IP_OFFMASK) << 3;
305 u_int16_t ip_len = ip->ip_len - ip->ip_hl * 4;
306 u_int16_t max = ip_len + off;
308 KASSERT((*frag == NULL || BUFFER_FRAGMENTS(*frag)),
309 ("! (*frag == NULL || BUFFER_FRAGMENTS(*frag)): %s", __func__));
311 /* Strip off ip header */
315 /* Create a new reassembly queue for this packet */
317 *frag = kmalloc(sizeof(struct pf_fragment), M_PFFRAGPL, M_NOWAIT);
319 pf_flush_fragments();
320 *frag = kmalloc(sizeof(struct pf_fragment), M_PFFRAGPL, M_NOWAIT);
325 (*frag)->fr_flags = 0;
327 (*frag)->fr_src = frent->fr_ip->ip_src;
328 (*frag)->fr_dst = frent->fr_ip->ip_dst;
329 (*frag)->fr_p = frent->fr_ip->ip_p;
330 (*frag)->fr_id = frent->fr_ip->ip_id;
331 (*frag)->fr_timeout = time_second;
332 LIST_INIT(&(*frag)->fr_queue);
334 RB_INSERT(pf_frag_tree, &pf_frag_tree, *frag);
335 TAILQ_INSERT_HEAD(&pf_fragqueue, *frag, frag_next);
337 /* We do not have a previous fragment */
343 * Find a fragment after the current one:
344 * - off contains the real shifted offset.
346 LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
347 if (FR_IP_OFF(frea) > off)
352 KASSERT((frep != NULL || frea != NULL),
353 ("!(frep != NULL || frea != NULL): %s", __func__));
356 FR_IP_OFF(frep) + frep->fr_ip->ip_len - frep->fr_ip->ip_hl *
361 precut = FR_IP_OFF(frep) + frep->fr_ip->ip_len -
362 frep->fr_ip->ip_hl * 4 - off;
363 if (precut >= ip_len)
365 m_adj(frent->fr_m, precut);
366 DPFPRINTF(("overlap -%d\n", precut));
367 /* Enforce 8 byte boundaries */
368 ip->ip_off = ip->ip_off + (precut >> 3);
369 off = (ip->ip_off & IP_OFFMASK) << 3;
374 for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
379 aftercut = ip_len + off - FR_IP_OFF(frea);
380 DPFPRINTF(("adjust overlap %d\n", aftercut));
381 if (aftercut < frea->fr_ip->ip_len - frea->fr_ip->ip_hl
384 frea->fr_ip->ip_len =
385 frea->fr_ip->ip_len - aftercut;
386 frea->fr_ip->ip_off = frea->fr_ip->ip_off +
388 m_adj(frea->fr_m, aftercut);
392 /* This fragment is completely overlapped, lose it */
393 next = LIST_NEXT(frea, fr_next);
395 LIST_REMOVE(frea, fr_next);
396 kfree(frea, M_PFFRENTPL);
401 /* Update maximum data size */
402 if ((*frag)->fr_max < max)
403 (*frag)->fr_max = max;
404 /* This is the last segment */
406 (*frag)->fr_flags |= PFFRAG_SEENLAST;
409 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
411 LIST_INSERT_AFTER(frep, frent, fr_next);
413 /* Check if we are completely reassembled */
414 if (!((*frag)->fr_flags & PFFRAG_SEENLAST))
417 /* Check if we have all the data */
419 for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
420 next = LIST_NEXT(frep, fr_next);
422 off += frep->fr_ip->ip_len - frep->fr_ip->ip_hl * 4;
423 if (off < (*frag)->fr_max &&
424 (next == NULL || FR_IP_OFF(next) != off))
426 DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
427 off, next == NULL ? -1 : FR_IP_OFF(next),
432 DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
433 if (off < (*frag)->fr_max)
436 /* We have all the data */
437 frent = LIST_FIRST(&(*frag)->fr_queue);
438 KASSERT((frent != NULL), ("frent == NULL: %s", __func__));
439 if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
440 DPFPRINTF(("drop: too big: %d\n", off));
441 pf_free_fragment(*frag);
445 next = LIST_NEXT(frent, fr_next);
447 /* Magic from ip_input */
453 kfree(frent, M_PFFRENTPL);
455 for (frent = next; frent != NULL; frent = next) {
456 next = LIST_NEXT(frent, fr_next);
459 kfree(frent, M_PFFRENTPL);
464 ip->ip_src = (*frag)->fr_src;
465 ip->ip_dst = (*frag)->fr_dst;
467 /* Remove from fragment queue */
468 pf_remove_fragment(*frag);
471 hlen = ip->ip_hl << 2;
472 ip->ip_len = off + hlen;
476 /* some debugging cruft by sklower, below, will go away soon */
477 /* XXX this should be done elsewhere */
478 if (m->m_flags & M_PKTHDR) {
480 for (m2 = m; m2; m2 = m2->m_next)
482 m->m_pkthdr.len = plen;
485 DPFPRINTF(("complete: %p(%d)\n", m, ip->ip_len));
489 /* Oops - fail safe - drop packet */
490 kfree(frent, M_PFFRENTPL);
497 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
498 int drop, int *nomem)
500 struct mbuf *m = *m0;
501 struct pf_frcache *frp, *fra, *cur = NULL;
502 int ip_len = h->ip_len - (h->ip_hl << 2);
503 u_int16_t off = h->ip_off << 3;
504 u_int16_t max = ip_len + off;
507 KASSERT((*frag == NULL || !BUFFER_FRAGMENTS(*frag)),
508 ("!(*frag == NULL || !BUFFER_FRAGMENTS(*frag)): %s", __func__));
510 /* Create a new range queue for this packet */
512 *frag = kmalloc(sizeof(struct pf_fragment), M_PFCACHEPL, M_NOWAIT);
514 pf_flush_fragments();
515 *frag = kmalloc(sizeof(struct pf_fragment), M_PFCACHEPL, M_NOWAIT);
520 /* Get an entry for the queue */
521 cur = kmalloc(sizeof(struct pf_frcache), M_PFCENTPL, M_NOWAIT);
523 kfree(*frag, M_PFCACHEPL);
529 (*frag)->fr_flags = PFFRAG_NOBUFFER;
531 (*frag)->fr_src = h->ip_src;
532 (*frag)->fr_dst = h->ip_dst;
533 (*frag)->fr_p = h->ip_p;
534 (*frag)->fr_id = h->ip_id;
535 (*frag)->fr_timeout = time_second;
539 LIST_INIT(&(*frag)->fr_cache);
540 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
542 RB_INSERT(pf_frag_tree, &pf_cache_tree, *frag);
543 TAILQ_INSERT_HEAD(&pf_cachequeue, *frag, frag_next);
545 DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off, max));
551 * Find a fragment after the current one:
552 * - off contains the real shifted offset.
555 LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
556 if (fra->fr_off > off)
561 KASSERT((frp != NULL || fra != NULL),
562 ("!(frp != NULL || fra != NULL): %s", __func__));
567 precut = frp->fr_end - off;
568 if (precut >= ip_len) {
569 /* Fragment is entirely a duplicate */
570 DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
571 h->ip_id, frp->fr_off, frp->fr_end, off, max));
575 /* They are adjacent. Fixup cache entry */
576 DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
577 h->ip_id, frp->fr_off, frp->fr_end, off, max));
579 } else if (precut > 0) {
580 /* The first part of this payload overlaps with a
581 * fragment that has already been passed.
582 * Need to trim off the first part of the payload.
583 * But to do so easily, we need to create another
584 * mbuf to throw the original header into.
587 DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
588 h->ip_id, precut, frp->fr_off, frp->fr_end, off,
593 /* Update the previous frag to encompass this one */
597 /* XXX Optimization opportunity
598 * This is a very heavy way to trim the payload.
599 * we could do it much faster by diddling mbuf
600 * internals but that would be even less legible
601 * than this mbuf magic. For my next trick,
602 * I'll pull a rabbit out of my laptop.
604 *m0 = m_dup(m, MB_DONTWAIT);
605 /* From KAME Project : We have missed this! */
606 m_adj(*m0, (h->ip_hl << 2) -
607 (*m0)->m_pkthdr.len);
610 KASSERT(((*m0)->m_next == NULL),
611 ("(*m0)->m_next != NULL: %s",
613 m_adj(m, precut + (h->ip_hl << 2));
616 if (m->m_flags & M_PKTHDR) {
619 for (t = m; t; t = t->m_next)
621 m->m_pkthdr.len = plen;
625 h = mtod(m, struct ip *);
627 KASSERT(((int)m->m_len ==
629 ("m->m_len != h->ip_len - precut: %s",
631 h->ip_off = h->ip_off +
633 h->ip_len = h->ip_len - precut;
638 /* There is a gap between fragments */
640 DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
641 h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
644 cur = kmalloc(sizeof(struct pf_frcache), M_PFCENTPL, M_NOWAIT);
651 LIST_INSERT_AFTER(frp, cur, fr_next);
659 aftercut = max - fra->fr_off;
661 /* Adjacent fragments */
662 DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
663 h->ip_id, off, max, fra->fr_off, fra->fr_end));
666 } else if (aftercut > 0) {
667 /* Need to chop off the tail of this fragment */
668 DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
669 h->ip_id, aftercut, off, max, fra->fr_off,
678 if (m->m_flags & M_PKTHDR) {
681 for (t = m; t; t = t->m_next)
683 m->m_pkthdr.len = plen;
685 h = mtod(m, struct ip *);
686 KASSERT(((int)m->m_len == h->ip_len - aftercut),
687 ("m->m_len != h->ip_len - aftercut: %s",
689 h->ip_len = h->ip_len - aftercut;
693 } else if (frp == NULL) {
694 /* There is a gap between fragments */
695 DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
696 h->ip_id, -aftercut, off, max, fra->fr_off,
699 cur = kmalloc(sizeof(struct pf_frcache), M_PFCENTPL, M_NOWAIT);
706 LIST_INSERT_BEFORE(fra, cur, fr_next);
710 /* Need to glue together two separate fragment descriptors */
712 if (cur && fra->fr_off <= cur->fr_end) {
713 /* Need to merge in a previous 'cur' */
714 DPFPRINTF(("fragcache[%d]: adjacent(merge "
715 "%d-%d) %d-%d (%d-%d)\n",
716 h->ip_id, cur->fr_off, cur->fr_end, off,
717 max, fra->fr_off, fra->fr_end));
718 fra->fr_off = cur->fr_off;
719 LIST_REMOVE(cur, fr_next);
720 kfree(cur, M_PFCENTPL);
724 } else if (frp && fra->fr_off <= frp->fr_end) {
725 /* Need to merge in a modified 'frp' */
726 KASSERT((cur == NULL), ("cur != NULL: %s",
728 DPFPRINTF(("fragcache[%d]: adjacent(merge "
729 "%d-%d) %d-%d (%d-%d)\n",
730 h->ip_id, frp->fr_off, frp->fr_end, off,
731 max, fra->fr_off, fra->fr_end));
732 fra->fr_off = frp->fr_off;
733 LIST_REMOVE(frp, fr_next);
734 kfree(frp, M_PFCENTPL);
744 * We must keep tracking the overall fragment even when
745 * we're going to drop it anyway so that we know when to
746 * free the overall descriptor. Thus we drop the frag late.
753 /* Update maximum data size */
754 if ((*frag)->fr_max < max)
755 (*frag)->fr_max = max;
757 /* This is the last segment */
759 (*frag)->fr_flags |= PFFRAG_SEENLAST;
761 /* Check if we are completely reassembled */
762 if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
763 LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
764 LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
765 /* Remove from fragment queue */
766 DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
768 pf_free_fragment(*frag);
777 /* Still need to pay attention to !IP_MF */
778 if (!mff && *frag != NULL)
779 (*frag)->fr_flags |= PFFRAG_SEENLAST;
786 /* Still need to pay attention to !IP_MF */
787 if (!mff && *frag != NULL)
788 (*frag)->fr_flags |= PFFRAG_SEENLAST;
791 /* This fragment has been deemed bad. Don't reass */
792 if (((*frag)->fr_flags & PFFRAG_DROP) == 0)
793 DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
795 (*frag)->fr_flags |= PFFRAG_DROP;
803 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
806 struct mbuf *m = *m0;
808 struct pf_frent *frent;
809 struct pf_fragment *frag = NULL;
810 struct ip *h = mtod(m, struct ip *);
811 int mff = (h->ip_off & IP_MF);
812 int hlen = h->ip_hl << 2;
813 u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;
819 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
822 if (pfi_kif_match(r->kif, kif) == r->ifnot)
823 r = r->skip[PF_SKIP_IFP].ptr;
824 else if (r->direction && r->direction != dir)
825 r = r->skip[PF_SKIP_DIR].ptr;
826 else if (r->af && r->af != AF_INET)
827 r = r->skip[PF_SKIP_AF].ptr;
828 else if (r->proto && r->proto != h->ip_p)
829 r = r->skip[PF_SKIP_PROTO].ptr;
830 else if (PF_MISMATCHAW(&r->src.addr,
831 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
833 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
834 else if (PF_MISMATCHAW(&r->dst.addr,
835 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
837 r = r->skip[PF_SKIP_DST_ADDR].ptr;
838 else if (r->match_tag && !pf_match_tag(m, r, &tag))
839 r = TAILQ_NEXT(r, entries);
844 if (r == NULL || r->action == PF_NOSCRUB)
847 r->packets[dir == PF_OUT]++;
848 r->bytes[dir == PF_OUT] += pd->tot_len;
851 /* Check for illegal packets */
852 if (hlen < (int)sizeof(struct ip))
855 if (hlen > h->ip_len)
858 /* Clear IP_DF if the rule uses the no-df option */
859 if (r->rule_flag & PFRULE_NODF && h->ip_off & IP_DF) {
860 u_int16_t ip_off = h->ip_off;
863 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
866 /* We will need other tests here */
867 if (!fragoff && !mff)
870 /* We're dealing with a fragment now. Don't allow fragments
871 * with IP_DF to enter the cache. If the flag was cleared by
872 * no-df above, fine. Otherwise drop it.
874 if (h->ip_off & IP_DF) {
875 DPFPRINTF(("IP_DF\n"));
879 ip_len = h->ip_len - hlen;
880 ip_off = (h->ip_off & IP_OFFMASK) << 3;
882 /* All fragments are 8 byte aligned */
883 if (mff && (ip_len & 0x7)) {
884 DPFPRINTF(("mff and %d\n", ip_len));
888 /* Respect maximum length */
889 if (fragoff + ip_len > IP_MAXPACKET) {
890 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
893 max = fragoff + ip_len;
895 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
896 /* Fully buffer all of the fragments */
898 frag = pf_find_fragment(h, &pf_frag_tree);
900 /* Check if we saw the last fragment already */
901 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
905 /* Get an entry for the fragment queue */
906 frent = kmalloc(sizeof(struct pf_frent), M_PFFRENTPL, M_NOWAIT);
908 REASON_SET(reason, PFRES_MEMORY);
915 /* Might return a completely reassembled mbuf, or NULL */
916 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
917 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
922 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
925 h = mtod(m, struct ip *);
927 /* non-buffering fragment cache (drops or masks overlaps) */
930 if (dir == PF_OUT && m->m_pkthdr.pf.flags & PF_TAG_FRAGCACHE) {
932 * Already passed the fragment cache in the
933 * input direction. If we continued, it would
934 * appear to be a dup and would be dropped.
939 frag = pf_find_fragment(h, &pf_cache_tree);
941 /* Check if we saw the last fragment already */
942 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
943 max > frag->fr_max) {
944 if (r->rule_flag & PFRULE_FRAGDROP)
945 frag->fr_flags |= PFFRAG_DROP;
949 *m0 = m = pf_fragcache(m0, h, &frag, mff,
950 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
958 m->m_pkthdr.pf.flags |= PF_TAG_FRAGCACHE;
960 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
966 /* At this point, only IP_DF is allowed in ip_off */
967 if (h->ip_off & ~IP_DF) {
968 u_int16_t ip_off = h->ip_off;
971 h->ip_sum = pf_cksum_fixup(h->ip_sum, htons(ip_off), htons(h->ip_off), 0);
974 /* Enforce a minimum ttl, may cause endless packet loops */
975 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
976 u_int16_t ip_ttl = h->ip_ttl;
978 h->ip_ttl = r->min_ttl;
979 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
983 if (r->rule_flag & PFRULE_SET_TOS) {
986 ov = *(u_int16_t *)h;
987 h->ip_tos = r->set_tos;
988 nv = *(u_int16_t *)h;
990 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
993 if (r->rule_flag & PFRULE_RANDOMID) {
994 u_int16_t ip_id = h->ip_id;
996 h->ip_id = ip_randomid();
997 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
999 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1000 pd->flags |= PFDESC_IP_REAS;
1005 /* Enforce a minimum ttl, may cause endless packet loops */
1006 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
1007 u_int16_t ip_ttl = h->ip_ttl;
1009 h->ip_ttl = r->min_ttl;
1010 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1013 if (r->rule_flag & PFRULE_SET_TOS) {
1016 ov = *(u_int16_t *)h;
1017 h->ip_tos = r->set_tos;
1018 nv = *(u_int16_t *)h;
1020 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1022 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1023 pd->flags |= PFDESC_IP_REAS;
1027 REASON_SET(reason, PFRES_MEMORY);
1028 if (r != NULL && r->log)
1029 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1033 REASON_SET(reason, PFRES_NORM);
1034 if (r != NULL && r->log)
1035 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1039 DPFPRINTF(("dropping bad fragment\n"));
1041 /* Free associated fragments */
1043 pf_free_fragment(frag);
1045 REASON_SET(reason, PFRES_FRAG);
1046 if (r != NULL && r->log)
1047 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1054 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1055 u_short *reason, struct pf_pdesc *pd)
1057 struct mbuf *m = *m0;
1059 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1063 struct ip6_opt_jumbo jumbo;
1064 struct ip6_frag frag;
1065 u_int32_t jumbolen = 0, plen;
1066 u_int16_t fragoff = 0;
1072 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1075 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1076 r = r->skip[PF_SKIP_IFP].ptr;
1077 else if (r->direction && r->direction != dir)
1078 r = r->skip[PF_SKIP_DIR].ptr;
1079 else if (r->af && r->af != AF_INET6)
1080 r = r->skip[PF_SKIP_AF].ptr;
1081 #if 0 /* header chain! */
1082 else if (r->proto && r->proto != h->ip6_nxt)
1083 r = r->skip[PF_SKIP_PROTO].ptr;
1085 else if (PF_MISMATCHAW(&r->src.addr,
1086 (struct pf_addr *)&h->ip6_src, AF_INET6,
1088 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1089 else if (PF_MISMATCHAW(&r->dst.addr,
1090 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1092 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1097 if (r == NULL || r->action == PF_NOSCRUB)
1100 r->packets[dir == PF_OUT]++;
1101 r->bytes[dir == PF_OUT] += pd->tot_len;
1104 /* Check for illegal packets */
1105 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1108 off = sizeof(struct ip6_hdr);
1113 case IPPROTO_FRAGMENT:
1117 case IPPROTO_ROUTING:
1118 case IPPROTO_DSTOPTS:
1119 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1122 if (proto == IPPROTO_AH)
1123 off += (ext.ip6e_len + 2) * 4;
1125 off += (ext.ip6e_len + 1) * 8;
1126 proto = ext.ip6e_nxt;
1128 case IPPROTO_HOPOPTS:
1129 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1132 optend = off + (ext.ip6e_len + 1) * 8;
1133 ooff = off + sizeof(ext);
1135 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1136 sizeof(opt.ip6o_type), NULL, NULL,
1139 if (opt.ip6o_type == IP6OPT_PAD1) {
1143 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1144 NULL, NULL, AF_INET6))
1146 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1148 switch (opt.ip6o_type) {
1150 if (h->ip6_plen != 0)
1152 if (!pf_pull_hdr(m, ooff, &jumbo,
1153 sizeof(jumbo), NULL, NULL,
1156 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1158 jumbolen = ntohl(jumbolen);
1159 if (jumbolen <= IPV6_MAXPACKET)
1161 if (sizeof(struct ip6_hdr) + jumbolen !=
1168 ooff += sizeof(opt) + opt.ip6o_len;
1169 } while (ooff < optend);
1172 proto = ext.ip6e_nxt;
1178 } while (!terminal);
1180 /* jumbo payload option must be present, or plen > 0 */
1181 if (ntohs(h->ip6_plen) == 0)
1184 plen = ntohs(h->ip6_plen);
1187 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1190 /* Enforce a minimum ttl, may cause endless packet loops */
1191 if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1192 h->ip6_hlim = r->min_ttl;
1197 if (ntohs(h->ip6_plen) == 0 || jumbolen)
1199 plen = ntohs(h->ip6_plen);
1201 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1203 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1204 if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1207 /* do something about it */
1208 /* remember to set pd->flags |= PFDESC_IP_REAS */
1212 REASON_SET(reason, PFRES_SHORT);
1213 if (r != NULL && r->log)
1214 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1218 REASON_SET(reason, PFRES_NORM);
1219 if (r != NULL && r->log)
1220 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1224 REASON_SET(reason, PFRES_FRAG);
1225 if (r != NULL && r->log)
1226 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1232 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1233 int off, void *h, struct pf_pdesc *pd)
1235 struct pf_rule *r, *rm = NULL;
1236 struct tcphdr *th = pd->hdr.tcp;
1240 sa_family_t af = pd->af;
1242 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1245 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1246 r = r->skip[PF_SKIP_IFP].ptr;
1247 else if (r->direction && r->direction != dir)
1248 r = r->skip[PF_SKIP_DIR].ptr;
1249 else if (r->af && r->af != af)
1250 r = r->skip[PF_SKIP_AF].ptr;
1251 else if (r->proto && r->proto != pd->proto)
1252 r = r->skip[PF_SKIP_PROTO].ptr;
1253 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1255 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1256 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1257 r->src.port[0], r->src.port[1], th->th_sport))
1258 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1259 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1261 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1262 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1263 r->dst.port[0], r->dst.port[1], th->th_dport))
1264 r = r->skip[PF_SKIP_DST_PORT].ptr;
1265 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1266 pf_osfp_fingerprint(pd, m, off, th),
1268 r = TAILQ_NEXT(r, entries);
1275 if (rm == NULL || rm->action == PF_NOSCRUB)
1278 r->packets[dir == PF_OUT]++;
1279 r->bytes[dir == PF_OUT] += pd->tot_len;
1282 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1283 pd->flags |= PFDESC_TCP_NORM;
1285 flags = th->th_flags;
1286 if (flags & TH_SYN) {
1287 /* Illegal packet */
1294 /* Illegal packet */
1295 if (!(flags & (TH_ACK|TH_RST)))
1299 if (!(flags & TH_ACK)) {
1300 /* These flags are only valid if ACK is set */
1301 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1305 /* Check for illegal header length */
1306 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1309 /* If flags changed, or reserved data set, then adjust */
1310 if (flags != th->th_flags || th->th_x2 != 0) {
1313 ov = *(u_int16_t *)(&th->th_ack + 1);
1314 th->th_flags = flags;
1316 nv = *(u_int16_t *)(&th->th_ack + 1);
1318 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1322 /* Remove urgent pointer, if TH_URG is not set */
1323 if (!(flags & TH_URG) && th->th_urp) {
1324 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1329 /* Process options */
1330 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1333 /* copy back packet headers if we sanitized */
1335 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1340 REASON_SET(&reason, PFRES_NORM);
1341 if (rm != NULL && r->log)
1342 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL, pd);
1347 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1348 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1350 u_int32_t tsval, tsecr;
1354 KASSERT((src->scrub == NULL),
1355 ("pf_normalize_tcp_init: src->scrub != NULL"));
1357 src->scrub = kmalloc(sizeof(struct pf_state_scrub), M_PFSTATESCRUBPL,
1359 if (src->scrub == NULL)
1365 struct ip *h = mtod(m, struct ip *);
1366 src->scrub->pfss_ttl = h->ip_ttl;
1372 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1373 src->scrub->pfss_ttl = h->ip6_hlim;
1381 * All normalizations below are only begun if we see the start of
1382 * the connections. They must all set an enabled bit in pfss_flags
1384 if ((th->th_flags & TH_SYN) == 0)
1388 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1389 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1390 /* Diddle with TCP options */
1392 opt = hdr + sizeof(struct tcphdr);
1393 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1394 while (hlen >= TCPOLEN_TIMESTAMP) {
1396 case TCPOPT_EOL: /* FALLTHROUGH */
1401 case TCPOPT_TIMESTAMP:
1402 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1403 src->scrub->pfss_flags |=
1405 src->scrub->pfss_ts_mod = karc4random();
1407 /* note PFSS_PAWS not set yet */
1408 memcpy(&tsval, &opt[2],
1410 memcpy(&tsecr, &opt[6],
1412 src->scrub->pfss_tsval0 = ntohl(tsval);
1413 src->scrub->pfss_tsval = ntohl(tsval);
1414 src->scrub->pfss_tsecr = ntohl(tsecr);
1415 getmicrouptime(&src->scrub->pfss_last);
1419 hlen -= MAX(opt[1], 2);
1420 opt += MAX(opt[1], 2);
1430 pf_normalize_tcp_cleanup(struct pf_state *state)
1432 if (state->src.scrub)
1433 kfree(state->src.scrub, M_PFSTATESCRUBPL);
1434 if (state->dst.scrub)
1435 kfree(state->dst.scrub, M_PFSTATESCRUBPL);
1437 /* Someday... flush the TCP segment reassembly descriptors. */
1441 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1442 u_short *reason, struct tcphdr *th, struct pf_state *state,
1443 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1445 struct timeval uptime;
1446 u_int32_t tsval, tsecr;
1447 u_int tsval_from_last;
1453 KASSERT((src->scrub || dst->scrub),
1454 ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1457 * Enforce the minimum TTL seen for this connection. Negate a common
1458 * technique to evade an intrusion detection system and confuse
1459 * firewall state code.
1465 struct ip *h = mtod(m, struct ip *);
1466 if (h->ip_ttl > src->scrub->pfss_ttl)
1467 src->scrub->pfss_ttl = h->ip_ttl;
1468 h->ip_ttl = src->scrub->pfss_ttl;
1476 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1477 if (h->ip6_hlim > src->scrub->pfss_ttl)
1478 src->scrub->pfss_ttl = h->ip6_hlim;
1479 h->ip6_hlim = src->scrub->pfss_ttl;
1486 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1487 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1488 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1489 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1490 /* Diddle with TCP options */
1492 opt = hdr + sizeof(struct tcphdr);
1493 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1494 while (hlen >= TCPOLEN_TIMESTAMP) {
1496 case TCPOPT_EOL: /* FALLTHROUGH */
1501 case TCPOPT_TIMESTAMP:
1502 /* Modulate the timestamps. Can be used for
1503 * NAT detection, OS uptime determination or
1508 /* Huh? Multiple timestamps!? */
1509 if (pf_status.debug >= PF_DEBUG_MISC) {
1510 DPFPRINTF(("multiple TS??"));
1511 pf_print_state(state);
1514 REASON_SET(reason, PFRES_TS);
1517 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1518 memcpy(&tsval, &opt[2],
1520 if (tsval && src->scrub &&
1521 (src->scrub->pfss_flags &
1523 tsval = ntohl(tsval);
1524 pf_change_a(&opt[2],
1527 src->scrub->pfss_ts_mod),
1532 /* Modulate TS reply iff valid (!0) */
1533 memcpy(&tsecr, &opt[6],
1535 if (tsecr && dst->scrub &&
1536 (dst->scrub->pfss_flags &
1538 tsecr = ntohl(tsecr)
1539 - dst->scrub->pfss_ts_mod;
1540 pf_change_a(&opt[6],
1541 &th->th_sum, htonl(tsecr),
1549 hlen -= MAX(opt[1], 2);
1550 opt += MAX(opt[1], 2);
1555 /* Copyback the options, caller copys back header */
1557 m_copyback(m, off + sizeof(struct tcphdr),
1558 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1559 sizeof(struct tcphdr));
1565 * Must invalidate PAWS checks on connections idle for too long.
1566 * The fastest allowed timestamp clock is 1ms. That turns out to
1567 * be about 24 days before it wraps. XXX Right now our lowerbound
1568 * TS echo check only works for the first 12 days of a connection
1569 * when the TS has exhausted half its 32bit space
1571 #define TS_MAX_IDLE (24*24*60*60)
1572 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1574 getmicrouptime(&uptime);
1575 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1576 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1577 time_second - state->creation > TS_MAX_CONN)) {
1578 if (pf_status.debug >= PF_DEBUG_MISC) {
1579 DPFPRINTF(("src idled out of PAWS\n"));
1580 pf_print_state(state);
1583 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1586 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1587 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1588 if (pf_status.debug >= PF_DEBUG_MISC) {
1589 DPFPRINTF(("dst idled out of PAWS\n"));
1590 pf_print_state(state);
1593 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1597 if (got_ts && src->scrub && dst->scrub &&
1598 (src->scrub->pfss_flags & PFSS_PAWS) &&
1599 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1600 /* Validate that the timestamps are "in-window".
1601 * RFC1323 describes TCP Timestamp options that allow
1602 * measurement of RTT (round trip time) and PAWS
1603 * (protection against wrapped sequence numbers). PAWS
1604 * gives us a set of rules for rejecting packets on
1605 * long fat pipes (packets that were somehow delayed
1606 * in transit longer than the time it took to send the
1607 * full TCP sequence space of 4Gb). We can use these
1608 * rules and infer a few others that will let us treat
1609 * the 32bit timestamp and the 32bit echoed timestamp
1610 * as sequence numbers to prevent a blind attacker from
1611 * inserting packets into a connection.
1614 * - The timestamp on this packet must be greater than
1615 * or equal to the last value echoed by the other
1616 * endpoint. The RFC says those will be discarded
1617 * since it is a dup that has already been acked.
1618 * This gives us a lowerbound on the timestamp.
1619 * timestamp >= other last echoed timestamp
1620 * - The timestamp will be less than or equal to
1621 * the last timestamp plus the time between the
1622 * last packet and now. The RFC defines the max
1623 * clock rate as 1ms. We will allow clocks to be
1624 * up to 10% fast and will allow a total difference
1625 * or 30 seconds due to a route change. And this
1626 * gives us an upperbound on the timestamp.
1627 * timestamp <= last timestamp + max ticks
1628 * We have to be careful here. Windows will send an
1629 * initial timestamp of zero and then initialize it
1630 * to a random value after the 3whs; presumably to
1631 * avoid a DoS by having to call an expensive RNG
1632 * during a SYN flood. Proof MS has at least one
1633 * good security geek.
1635 * - The TCP timestamp option must also echo the other
1636 * endpoints timestamp. The timestamp echoed is the
1637 * one carried on the earliest unacknowledged segment
1638 * on the left edge of the sequence window. The RFC
1639 * states that the host will reject any echoed
1640 * timestamps that were larger than any ever sent.
1641 * This gives us an upperbound on the TS echo.
1642 * tescr <= largest_tsval
1643 * - The lowerbound on the TS echo is a little more
1644 * tricky to determine. The other endpoint's echoed
1645 * values will not decrease. But there may be
1646 * network conditions that re-order packets and
1647 * cause our view of them to decrease. For now the
1648 * only lowerbound we can safely determine is that
1649 * the TS echo will never be less than the original
1650 * TS. XXX There is probably a better lowerbound.
1651 * Remove TS_MAX_CONN with better lowerbound check.
1652 * tescr >= other original TS
1654 * It is also important to note that the fastest
1655 * timestamp clock of 1ms will wrap its 32bit space in
1656 * 24 days. So we just disable TS checking after 24
1657 * days of idle time. We actually must use a 12d
1658 * connection limit until we can come up with a better
1659 * lowerbound to the TS echo check.
1661 struct timeval delta_ts;
1666 * PFTM_TS_DIFF is how many seconds of leeway to allow
1667 * a host's timestamp. This can happen if the previous
1668 * packet got delayed in transit for much longer than
1671 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1672 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1675 /* Calculate max ticks since the last timestamp */
1676 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1677 #define TS_MICROSECS 1000000 /* microseconds per second */
1679 #define timersub(tvp, uvp, vvp) \
1681 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
1682 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
1683 if ((vvp)->tv_usec < 0) { \
1685 (vvp)->tv_usec += 1000000; \
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);
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.
1703 * - Solaris 2.6 and 2.7 are known to send another ACK
1704 * after the FIN,FIN|ACK,ACK closing that carries
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: %u tsecr: %u +ticks: %u "
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: %u tsecr: %u\n",
1719 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1720 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
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);
1728 REASON_SET(reason, PFRES_TS);
1732 /* XXX I'd really like to require tsecr but it's optional */
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
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
1752 * To minimize the disruption to mostly RFC1323 conformant
1753 * stacks, we will only require timestamps on data packets.
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
1766 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1768 * Hey! Someone tried to sneak a packet in. Or the
1769 * stack changed its RFC1323 behavior?!?!
1771 if (pf_status.debug >= PF_DEBUG_MISC) {
1772 DPFPRINTF(("Did not receive expected RFC1323 "
1774 pf_print_state(state);
1775 pf_print_flags(th->th_flags);
1778 REASON_SET(reason, PFRES_TS);
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).
1792 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1793 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1795 src->scrub->pfss_flags |= PFSS_DATA_TS;
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 "
1804 pf_print_state(state);
1805 pf_print_flags(th->th_flags);
1813 * Update PAWS values
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;
1823 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1824 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1825 src->scrub->pfss_tsecr = tsecr;
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;
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;
1840 /* I have a dream.... TCP segment reassembly.... */
1845 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1846 int off, sa_family_t af)
1850 int opt, cnt, optlen = 0;
1852 u_char opts[TCP_MAXOLEN];
1853 u_char *optp = opts;
1855 thoff = th->th_off << 2;
1856 cnt = thoff - sizeof(struct tcphdr);
1858 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1862 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1864 if (opt == TCPOPT_EOL)
1866 if (opt == TCPOPT_NOP)
1872 if (optlen < 2 || optlen > cnt)
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);
1891 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);