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;
818 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
821 if (pfi_kif_match(r->kif, kif) == r->ifnot)
822 r = r->skip[PF_SKIP_IFP].ptr;
823 else if (r->direction && r->direction != dir)
824 r = r->skip[PF_SKIP_DIR].ptr;
825 else if (r->af && r->af != AF_INET)
826 r = r->skip[PF_SKIP_AF].ptr;
827 else if (r->proto && r->proto != h->ip_p)
828 r = r->skip[PF_SKIP_PROTO].ptr;
829 else if (PF_MISMATCHAW(&r->src.addr,
830 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
832 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
833 else if (PF_MISMATCHAW(&r->dst.addr,
834 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
836 r = r->skip[PF_SKIP_DST_ADDR].ptr;
837 else if (r->match_tag && !pf_match_tag(m, r, &tag))
838 r = TAILQ_NEXT(r, entries);
843 if (r == NULL || r->action == PF_NOSCRUB)
846 r->packets[dir == PF_OUT]++;
847 r->bytes[dir == PF_OUT] += pd->tot_len;
850 /* Check for illegal packets */
851 if (hlen < (int)sizeof(struct ip))
854 if (hlen > h->ip_len)
857 /* Clear IP_DF if the rule uses the no-df option */
858 if (r->rule_flag & PFRULE_NODF && h->ip_off & IP_DF) {
859 u_int16_t ip_off = h->ip_off;
862 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
865 /* We will need other tests here */
866 if (!fragoff && !mff)
869 /* We're dealing with a fragment now. Don't allow fragments
870 * with IP_DF to enter the cache. If the flag was cleared by
871 * no-df above, fine. Otherwise drop it.
873 if (h->ip_off & IP_DF) {
874 DPFPRINTF(("IP_DF\n"));
878 ip_len = h->ip_len - hlen;
880 /* All fragments are 8 byte aligned */
881 if (mff && (ip_len & 0x7)) {
882 DPFPRINTF(("mff and %d\n", ip_len));
886 /* Respect maximum length */
887 if (fragoff + ip_len > IP_MAXPACKET) {
888 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
891 max = fragoff + ip_len;
893 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
894 /* Fully buffer all of the fragments */
896 frag = pf_find_fragment(h, &pf_frag_tree);
898 /* Check if we saw the last fragment already */
899 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
903 /* Get an entry for the fragment queue */
904 frent = kmalloc(sizeof(struct pf_frent), M_PFFRENTPL, M_NOWAIT);
906 REASON_SET(reason, PFRES_MEMORY);
913 /* Might return a completely reassembled mbuf, or NULL */
914 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
915 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
920 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
923 h = mtod(m, struct ip *);
925 /* non-buffering fragment cache (drops or masks overlaps) */
928 if (dir == PF_OUT && m->m_pkthdr.pf.flags & PF_TAG_FRAGCACHE) {
930 * Already passed the fragment cache in the
931 * input direction. If we continued, it would
932 * appear to be a dup and would be dropped.
937 frag = pf_find_fragment(h, &pf_cache_tree);
939 /* Check if we saw the last fragment already */
940 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
941 max > frag->fr_max) {
942 if (r->rule_flag & PFRULE_FRAGDROP)
943 frag->fr_flags |= PFFRAG_DROP;
947 *m0 = m = pf_fragcache(m0, h, &frag, mff,
948 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
956 m->m_pkthdr.pf.flags |= PF_TAG_FRAGCACHE;
958 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
964 /* At this point, only IP_DF is allowed in ip_off */
965 if (h->ip_off & ~IP_DF) {
966 u_int16_t ip_off = h->ip_off;
969 h->ip_sum = pf_cksum_fixup(h->ip_sum, htons(ip_off), htons(h->ip_off), 0);
972 /* Enforce a minimum ttl, may cause endless packet loops */
973 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
974 u_int16_t ip_ttl = h->ip_ttl;
976 h->ip_ttl = r->min_ttl;
977 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
981 if (r->rule_flag & PFRULE_SET_TOS) {
984 ov = *(u_int16_t *)h;
985 h->ip_tos = r->set_tos;
986 nv = *(u_int16_t *)h;
988 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
991 if (r->rule_flag & PFRULE_RANDOMID) {
992 u_int16_t ip_id = h->ip_id;
994 h->ip_id = ip_randomid();
995 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
997 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
998 pd->flags |= PFDESC_IP_REAS;
1003 /* Enforce a minimum ttl, may cause endless packet loops */
1004 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
1005 u_int16_t ip_ttl = h->ip_ttl;
1007 h->ip_ttl = r->min_ttl;
1008 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1011 if (r->rule_flag & PFRULE_SET_TOS) {
1014 ov = *(u_int16_t *)h;
1015 h->ip_tos = r->set_tos;
1016 nv = *(u_int16_t *)h;
1018 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1020 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1021 pd->flags |= PFDESC_IP_REAS;
1025 REASON_SET(reason, PFRES_MEMORY);
1026 if (r != NULL && r->log)
1027 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1031 REASON_SET(reason, PFRES_NORM);
1032 if (r != NULL && r->log)
1033 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1037 DPFPRINTF(("dropping bad fragment\n"));
1039 /* Free associated fragments */
1041 pf_free_fragment(frag);
1043 REASON_SET(reason, PFRES_FRAG);
1044 if (r != NULL && r->log)
1045 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1052 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1053 u_short *reason, struct pf_pdesc *pd)
1055 struct mbuf *m = *m0;
1057 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1061 struct ip6_opt_jumbo jumbo;
1062 struct ip6_frag frag;
1063 u_int32_t jumbolen = 0, plen;
1064 u_int16_t fragoff = 0;
1070 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1073 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1074 r = r->skip[PF_SKIP_IFP].ptr;
1075 else if (r->direction && r->direction != dir)
1076 r = r->skip[PF_SKIP_DIR].ptr;
1077 else if (r->af && r->af != AF_INET6)
1078 r = r->skip[PF_SKIP_AF].ptr;
1079 #if 0 /* header chain! */
1080 else if (r->proto && r->proto != h->ip6_nxt)
1081 r = r->skip[PF_SKIP_PROTO].ptr;
1083 else if (PF_MISMATCHAW(&r->src.addr,
1084 (struct pf_addr *)&h->ip6_src, AF_INET6,
1086 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1087 else if (PF_MISMATCHAW(&r->dst.addr,
1088 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1090 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1095 if (r == NULL || r->action == PF_NOSCRUB)
1098 r->packets[dir == PF_OUT]++;
1099 r->bytes[dir == PF_OUT] += pd->tot_len;
1102 /* Check for illegal packets */
1103 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1106 off = sizeof(struct ip6_hdr);
1111 case IPPROTO_FRAGMENT:
1115 case IPPROTO_ROUTING:
1116 case IPPROTO_DSTOPTS:
1117 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1120 if (proto == IPPROTO_AH)
1121 off += (ext.ip6e_len + 2) * 4;
1123 off += (ext.ip6e_len + 1) * 8;
1124 proto = ext.ip6e_nxt;
1126 case IPPROTO_HOPOPTS:
1127 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1130 optend = off + (ext.ip6e_len + 1) * 8;
1131 ooff = off + sizeof(ext);
1133 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1134 sizeof(opt.ip6o_type), NULL, NULL,
1137 if (opt.ip6o_type == IP6OPT_PAD1) {
1141 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1142 NULL, NULL, AF_INET6))
1144 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1146 switch (opt.ip6o_type) {
1148 if (h->ip6_plen != 0)
1150 if (!pf_pull_hdr(m, ooff, &jumbo,
1151 sizeof(jumbo), NULL, NULL,
1154 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1156 jumbolen = ntohl(jumbolen);
1157 if (jumbolen <= IPV6_MAXPACKET)
1159 if (sizeof(struct ip6_hdr) + jumbolen !=
1166 ooff += sizeof(opt) + opt.ip6o_len;
1167 } while (ooff < optend);
1170 proto = ext.ip6e_nxt;
1176 } while (!terminal);
1178 /* jumbo payload option must be present, or plen > 0 */
1179 if (ntohs(h->ip6_plen) == 0)
1182 plen = ntohs(h->ip6_plen);
1185 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1188 /* Enforce a minimum ttl, may cause endless packet loops */
1189 if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1190 h->ip6_hlim = r->min_ttl;
1195 if (ntohs(h->ip6_plen) == 0 || jumbolen)
1197 plen = ntohs(h->ip6_plen);
1199 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1201 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1202 if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1205 /* do something about it */
1206 /* remember to set pd->flags |= PFDESC_IP_REAS */
1210 REASON_SET(reason, PFRES_SHORT);
1211 if (r != NULL && r->log)
1212 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1216 REASON_SET(reason, PFRES_NORM);
1217 if (r != NULL && r->log)
1218 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1222 REASON_SET(reason, PFRES_FRAG);
1223 if (r != NULL && r->log)
1224 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1230 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1231 int off, void *h, struct pf_pdesc *pd)
1233 struct pf_rule *r, *rm = NULL;
1234 struct tcphdr *th = pd->hdr.tcp;
1238 sa_family_t af = pd->af;
1240 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1243 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1244 r = r->skip[PF_SKIP_IFP].ptr;
1245 else if (r->direction && r->direction != dir)
1246 r = r->skip[PF_SKIP_DIR].ptr;
1247 else if (r->af && r->af != af)
1248 r = r->skip[PF_SKIP_AF].ptr;
1249 else if (r->proto && r->proto != pd->proto)
1250 r = r->skip[PF_SKIP_PROTO].ptr;
1251 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1253 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1254 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1255 r->src.port[0], r->src.port[1], th->th_sport))
1256 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1257 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1259 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1260 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1261 r->dst.port[0], r->dst.port[1], th->th_dport))
1262 r = r->skip[PF_SKIP_DST_PORT].ptr;
1263 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1264 pf_osfp_fingerprint(pd, m, off, th),
1266 r = TAILQ_NEXT(r, entries);
1273 if (rm == NULL || rm->action == PF_NOSCRUB)
1276 r->packets[dir == PF_OUT]++;
1277 r->bytes[dir == PF_OUT] += pd->tot_len;
1280 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1281 pd->flags |= PFDESC_TCP_NORM;
1283 flags = th->th_flags;
1284 if (flags & TH_SYN) {
1285 /* Illegal packet */
1292 /* Illegal packet */
1293 if (!(flags & (TH_ACK|TH_RST)))
1297 if (!(flags & TH_ACK)) {
1298 /* These flags are only valid if ACK is set */
1299 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1303 /* Check for illegal header length */
1304 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1307 /* If flags changed, or reserved data set, then adjust */
1308 if (flags != th->th_flags || th->th_x2 != 0) {
1311 ov = *(u_int16_t *)(&th->th_ack + 1);
1312 th->th_flags = flags;
1314 nv = *(u_int16_t *)(&th->th_ack + 1);
1316 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1320 /* Remove urgent pointer, if TH_URG is not set */
1321 if (!(flags & TH_URG) && th->th_urp) {
1322 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1327 /* Process options */
1328 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1331 /* copy back packet headers if we sanitized */
1333 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1338 REASON_SET(&reason, PFRES_NORM);
1339 if (rm != NULL && r->log)
1340 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL, pd);
1345 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1346 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1348 u_int32_t tsval, tsecr;
1352 KASSERT((src->scrub == NULL),
1353 ("pf_normalize_tcp_init: src->scrub != NULL"));
1355 src->scrub = kmalloc(sizeof(struct pf_state_scrub), M_PFSTATESCRUBPL,
1357 if (src->scrub == NULL)
1363 struct ip *h = mtod(m, struct ip *);
1364 src->scrub->pfss_ttl = h->ip_ttl;
1370 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1371 src->scrub->pfss_ttl = h->ip6_hlim;
1379 * All normalizations below are only begun if we see the start of
1380 * the connections. They must all set an enabled bit in pfss_flags
1382 if ((th->th_flags & TH_SYN) == 0)
1386 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1387 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1388 /* Diddle with TCP options */
1390 opt = hdr + sizeof(struct tcphdr);
1391 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1392 while (hlen >= TCPOLEN_TIMESTAMP) {
1394 case TCPOPT_EOL: /* FALLTHROUGH */
1399 case TCPOPT_TIMESTAMP:
1400 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1401 src->scrub->pfss_flags |=
1403 src->scrub->pfss_ts_mod = karc4random();
1405 /* note PFSS_PAWS not set yet */
1406 memcpy(&tsval, &opt[2],
1408 memcpy(&tsecr, &opt[6],
1410 src->scrub->pfss_tsval0 = ntohl(tsval);
1411 src->scrub->pfss_tsval = ntohl(tsval);
1412 src->scrub->pfss_tsecr = ntohl(tsecr);
1413 getmicrouptime(&src->scrub->pfss_last);
1417 hlen -= MAX(opt[1], 2);
1418 opt += MAX(opt[1], 2);
1428 pf_normalize_tcp_cleanup(struct pf_state *state)
1430 if (state->src.scrub)
1431 kfree(state->src.scrub, M_PFSTATESCRUBPL);
1432 if (state->dst.scrub)
1433 kfree(state->dst.scrub, M_PFSTATESCRUBPL);
1435 /* Someday... flush the TCP segment reassembly descriptors. */
1439 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1440 u_short *reason, struct tcphdr *th, struct pf_state *state,
1441 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1443 struct timeval uptime;
1444 u_int32_t tsval, tsecr;
1445 u_int tsval_from_last;
1451 KASSERT((src->scrub || dst->scrub),
1452 ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1455 * Enforce the minimum TTL seen for this connection. Negate a common
1456 * technique to evade an intrusion detection system and confuse
1457 * firewall state code.
1463 struct ip *h = mtod(m, struct ip *);
1464 if (h->ip_ttl > src->scrub->pfss_ttl)
1465 src->scrub->pfss_ttl = h->ip_ttl;
1466 h->ip_ttl = src->scrub->pfss_ttl;
1474 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1475 if (h->ip6_hlim > src->scrub->pfss_ttl)
1476 src->scrub->pfss_ttl = h->ip6_hlim;
1477 h->ip6_hlim = src->scrub->pfss_ttl;
1484 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1485 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1486 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1487 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1488 /* Diddle with TCP options */
1490 opt = hdr + sizeof(struct tcphdr);
1491 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1492 while (hlen >= TCPOLEN_TIMESTAMP) {
1494 case TCPOPT_EOL: /* FALLTHROUGH */
1499 case TCPOPT_TIMESTAMP:
1500 /* Modulate the timestamps. Can be used for
1501 * NAT detection, OS uptime determination or
1506 /* Huh? Multiple timestamps!? */
1507 if (pf_status.debug >= PF_DEBUG_MISC) {
1508 DPFPRINTF(("multiple TS??"));
1509 pf_print_state(state);
1512 REASON_SET(reason, PFRES_TS);
1515 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1516 memcpy(&tsval, &opt[2],
1518 if (tsval && src->scrub &&
1519 (src->scrub->pfss_flags &
1521 tsval = ntohl(tsval);
1522 pf_change_a(&opt[2],
1525 src->scrub->pfss_ts_mod),
1530 /* Modulate TS reply iff valid (!0) */
1531 memcpy(&tsecr, &opt[6],
1533 if (tsecr && dst->scrub &&
1534 (dst->scrub->pfss_flags &
1536 tsecr = ntohl(tsecr)
1537 - dst->scrub->pfss_ts_mod;
1538 pf_change_a(&opt[6],
1539 &th->th_sum, htonl(tsecr),
1547 hlen -= MAX(opt[1], 2);
1548 opt += MAX(opt[1], 2);
1553 /* Copyback the options, caller copys back header */
1555 m_copyback(m, off + sizeof(struct tcphdr),
1556 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1557 sizeof(struct tcphdr));
1563 * Must invalidate PAWS checks on connections idle for too long.
1564 * The fastest allowed timestamp clock is 1ms. That turns out to
1565 * be about 24 days before it wraps. XXX Right now our lowerbound
1566 * TS echo check only works for the first 12 days of a connection
1567 * when the TS has exhausted half its 32bit space
1569 #define TS_MAX_IDLE (24*24*60*60)
1570 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1572 getmicrouptime(&uptime);
1573 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1574 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1575 time_second - state->creation > TS_MAX_CONN)) {
1576 if (pf_status.debug >= PF_DEBUG_MISC) {
1577 DPFPRINTF(("src idled out of PAWS\n"));
1578 pf_print_state(state);
1581 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1584 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1585 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1586 if (pf_status.debug >= PF_DEBUG_MISC) {
1587 DPFPRINTF(("dst idled out of PAWS\n"));
1588 pf_print_state(state);
1591 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1595 if (got_ts && src->scrub && dst->scrub &&
1596 (src->scrub->pfss_flags & PFSS_PAWS) &&
1597 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1598 /* Validate that the timestamps are "in-window".
1599 * RFC1323 describes TCP Timestamp options that allow
1600 * measurement of RTT (round trip time) and PAWS
1601 * (protection against wrapped sequence numbers). PAWS
1602 * gives us a set of rules for rejecting packets on
1603 * long fat pipes (packets that were somehow delayed
1604 * in transit longer than the time it took to send the
1605 * full TCP sequence space of 4Gb). We can use these
1606 * rules and infer a few others that will let us treat
1607 * the 32bit timestamp and the 32bit echoed timestamp
1608 * as sequence numbers to prevent a blind attacker from
1609 * inserting packets into a connection.
1612 * - The timestamp on this packet must be greater than
1613 * or equal to the last value echoed by the other
1614 * endpoint. The RFC says those will be discarded
1615 * since it is a dup that has already been acked.
1616 * This gives us a lowerbound on the timestamp.
1617 * timestamp >= other last echoed timestamp
1618 * - The timestamp will be less than or equal to
1619 * the last timestamp plus the time between the
1620 * last packet and now. The RFC defines the max
1621 * clock rate as 1ms. We will allow clocks to be
1622 * up to 10% fast and will allow a total difference
1623 * or 30 seconds due to a route change. And this
1624 * gives us an upperbound on the timestamp.
1625 * timestamp <= last timestamp + max ticks
1626 * We have to be careful here. Windows will send an
1627 * initial timestamp of zero and then initialize it
1628 * to a random value after the 3whs; presumably to
1629 * avoid a DoS by having to call an expensive RNG
1630 * during a SYN flood. Proof MS has at least one
1631 * good security geek.
1633 * - The TCP timestamp option must also echo the other
1634 * endpoints timestamp. The timestamp echoed is the
1635 * one carried on the earliest unacknowledged segment
1636 * on the left edge of the sequence window. The RFC
1637 * states that the host will reject any echoed
1638 * timestamps that were larger than any ever sent.
1639 * This gives us an upperbound on the TS echo.
1640 * tescr <= largest_tsval
1641 * - The lowerbound on the TS echo is a little more
1642 * tricky to determine. The other endpoint's echoed
1643 * values will not decrease. But there may be
1644 * network conditions that re-order packets and
1645 * cause our view of them to decrease. For now the
1646 * only lowerbound we can safely determine is that
1647 * the TS echo will never be less than the original
1648 * TS. XXX There is probably a better lowerbound.
1649 * Remove TS_MAX_CONN with better lowerbound check.
1650 * tescr >= other original TS
1652 * It is also important to note that the fastest
1653 * timestamp clock of 1ms will wrap its 32bit space in
1654 * 24 days. So we just disable TS checking after 24
1655 * days of idle time. We actually must use a 12d
1656 * connection limit until we can come up with a better
1657 * lowerbound to the TS echo check.
1659 struct timeval delta_ts;
1664 * PFTM_TS_DIFF is how many seconds of leeway to allow
1665 * a host's timestamp. This can happen if the previous
1666 * packet got delayed in transit for much longer than
1669 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1670 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1673 /* Calculate max ticks since the last timestamp */
1674 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1675 #define TS_MICROSECS 1000000 /* microseconds per second */
1677 #define timersub(tvp, uvp, vvp) \
1679 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
1680 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
1681 if ((vvp)->tv_usec < 0) { \
1683 (vvp)->tv_usec += 1000000; \
1688 timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1689 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1690 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1693 if ((src->state >= TCPS_ESTABLISHED &&
1694 dst->state >= TCPS_ESTABLISHED) &&
1695 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1696 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1697 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1698 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1699 /* Bad RFC1323 implementation or an insertion attack.
1701 * - Solaris 2.6 and 2.7 are known to send another ACK
1702 * after the FIN,FIN|ACK,ACK closing that carries
1706 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1707 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1708 SEQ_GT(tsval, src->scrub->pfss_tsval +
1709 tsval_from_last) ? '1' : ' ',
1710 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1711 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1712 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1713 "idle: %lus %lums\n",
1714 tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
1715 delta_ts.tv_usec / 1000));
1716 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1717 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1718 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1719 "\n", dst->scrub->pfss_tsval,
1720 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1721 if (pf_status.debug >= PF_DEBUG_MISC) {
1722 pf_print_state(state);
1723 pf_print_flags(th->th_flags);
1726 REASON_SET(reason, PFRES_TS);
1730 /* XXX I'd really like to require tsecr but it's optional */
1732 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1733 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1734 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1735 src->scrub && dst->scrub &&
1736 (src->scrub->pfss_flags & PFSS_PAWS) &&
1737 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1738 /* Didn't send a timestamp. Timestamps aren't really useful
1740 * - connection opening or closing (often not even sent).
1741 * but we must not let an attacker to put a FIN on a
1742 * data packet to sneak it through our ESTABLISHED check.
1743 * - on a TCP reset. RFC suggests not even looking at TS.
1744 * - on an empty ACK. The TS will not be echoed so it will
1745 * probably not help keep the RTT calculation in sync and
1746 * there isn't as much danger when the sequence numbers
1747 * got wrapped. So some stacks don't include TS on empty
1750 * To minimize the disruption to mostly RFC1323 conformant
1751 * stacks, we will only require timestamps on data packets.
1753 * And what do ya know, we cannot require timestamps on data
1754 * packets. There appear to be devices that do legitimate
1755 * TCP connection hijacking. There are HTTP devices that allow
1756 * a 3whs (with timestamps) and then buffer the HTTP request.
1757 * If the intermediate device has the HTTP response cache, it
1758 * will spoof the response but not bother timestamping its
1759 * packets. So we can look for the presence of a timestamp in
1760 * the first data packet and if there, require it in all future
1764 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1766 * Hey! Someone tried to sneak a packet in. Or the
1767 * stack changed its RFC1323 behavior?!?!
1769 if (pf_status.debug >= PF_DEBUG_MISC) {
1770 DPFPRINTF(("Did not receive expected RFC1323 "
1772 pf_print_state(state);
1773 pf_print_flags(th->th_flags);
1776 REASON_SET(reason, PFRES_TS);
1783 * We will note if a host sends his data packets with or without
1784 * timestamps. And require all data packets to contain a timestamp
1785 * if the first does. PAWS implicitly requires that all data packets be
1786 * timestamped. But I think there are middle-man devices that hijack
1787 * TCP streams immediately after the 3whs and don't timestamp their
1788 * packets (seen in a WWW accelerator or cache).
1790 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1791 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1793 src->scrub->pfss_flags |= PFSS_DATA_TS;
1795 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1796 if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1797 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1798 /* Don't warn if other host rejected RFC1323 */
1799 DPFPRINTF(("Broken RFC1323 stack did not "
1800 "timestamp data packet. Disabled PAWS "
1802 pf_print_state(state);
1803 pf_print_flags(th->th_flags);
1811 * Update PAWS values
1813 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1814 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1815 getmicrouptime(&src->scrub->pfss_last);
1816 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1817 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1818 src->scrub->pfss_tsval = tsval;
1821 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1822 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1823 src->scrub->pfss_tsecr = tsecr;
1825 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1826 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1827 src->scrub->pfss_tsval0 == 0)) {
1828 /* tsval0 MUST be the lowest timestamp */
1829 src->scrub->pfss_tsval0 = tsval;
1832 /* Only fully initialized after a TS gets echoed */
1833 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1834 src->scrub->pfss_flags |= PFSS_PAWS;
1838 /* I have a dream.... TCP segment reassembly.... */
1843 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1844 int off, sa_family_t af)
1848 int opt, cnt, optlen = 0;
1850 u_char opts[TCP_MAXOLEN];
1851 u_char *optp = opts;
1853 thoff = th->th_off << 2;
1854 cnt = thoff - sizeof(struct tcphdr);
1856 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1860 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1862 if (opt == TCPOPT_EOL)
1864 if (opt == TCPOPT_NOP)
1870 if (optlen < 2 || optlen > cnt)
1875 mss = (u_int16_t *)(optp + 2);
1876 if ((ntohs(*mss)) > r->max_mss) {
1877 th->th_sum = pf_cksum_fixup(th->th_sum,
1878 *mss, htons(r->max_mss), 0);
1879 *mss = htons(r->max_mss);
1889 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);