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>
41 #include <vm/vm_zone.h>
44 #include <net/if_types.h>
46 #include <net/route.h>
47 #include <net/pf/if_pflog.h>
49 #include <netinet/in.h>
50 #include <netinet/in_var.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
53 #include <netinet/ip_var.h>
54 #include <netinet/tcp.h>
55 #include <netinet/tcp_seq.h>
56 #include <netinet/udp.h>
57 #include <netinet/ip_icmp.h>
60 #include <netinet/ip6.h>
63 #include <net/pf/pfvar.h>
65 #define PFFRAG_SEENLAST 0x0001 /* Seen the last fragment for this */
66 #define PFFRAG_NOBUFFER 0x0002 /* Non-buffering fragment cache */
67 #define PFFRAG_DROP 0x0004 /* Drop all fragments */
68 #define BUFFER_FRAGMENTS(fr) (!((fr)->fr_flags & PFFRAG_NOBUFFER))
71 TAILQ_HEAD(pf_fragqueue, pf_fragment) pf_fragqueue;
72 TAILQ_HEAD(pf_cachequeue, pf_fragment) pf_cachequeue;
74 static __inline int pf_frag_compare(struct pf_fragment *,
75 struct pf_fragment *);
76 RB_HEAD(pf_frag_tree, pf_fragment) pf_frag_tree, pf_cache_tree;
77 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
78 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
80 /* Private prototypes */
81 void pf_ip2key(struct pf_fragment *, struct ip *);
82 void pf_remove_fragment(struct pf_fragment *);
83 void pf_flush_fragments(void);
84 void pf_free_fragment(struct pf_fragment *);
85 struct pf_fragment *pf_find_fragment(struct ip *, struct pf_frag_tree *);
86 struct mbuf *pf_reassemble(struct mbuf **, struct pf_fragment **,
87 struct pf_frent *, int);
88 struct mbuf *pf_fragcache(struct mbuf **, struct ip*,
89 struct pf_fragment **, int, int, int *);
90 int pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
91 struct tcphdr *, int, sa_family_t);
93 #define DPFPRINTF(x) do { \
94 if (pf_status.debug >= PF_DEBUG_MISC) { \
95 kprintf("%s: ", __func__); \
101 vm_zone_t pf_frent_pl, pf_frag_pl, pf_cache_pl, pf_cent_pl;
102 vm_zone_t pf_state_scrub_pl;
103 int pf_nfrents, pf_ncache;
106 pf_normalize_init(void)
109 pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
110 pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
111 pool_sethardlimit(&pf_cache_pl, PFFRAG_FRCACHE_HIWAT, NULL, 0);
112 pool_sethardlimit(&pf_cent_pl, PFFRAG_FRCENT_HIWAT, NULL, 0);
115 TAILQ_INIT(&pf_fragqueue);
116 TAILQ_INIT(&pf_cachequeue);
120 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
124 if ((diff = a->fr_id - b->fr_id))
126 else if ((diff = a->fr_p - b->fr_p))
128 else if (a->fr_src.s_addr < b->fr_src.s_addr)
130 else if (a->fr_src.s_addr > b->fr_src.s_addr)
132 else if (a->fr_dst.s_addr < b->fr_dst.s_addr)
134 else if (a->fr_dst.s_addr > b->fr_dst.s_addr)
140 pf_purge_expired_fragments(void)
142 struct pf_fragment *frag;
143 u_int32_t expire = time_second -
144 pf_default_rule.timeout[PFTM_FRAG];
146 while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
147 KASSERT((BUFFER_FRAGMENTS(frag)),
148 ("BUFFER_FRAGMENTS(frag) == 0: %s", __func__));
149 if (frag->fr_timeout > expire)
152 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
153 pf_free_fragment(frag);
156 while ((frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue)) != NULL) {
157 KASSERT((!BUFFER_FRAGMENTS(frag)),
158 ("BUFFER_FRAGMENTS(frag) != 0: %s", __func__));
159 if (frag->fr_timeout > expire)
162 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
163 pf_free_fragment(frag);
164 KASSERT((TAILQ_EMPTY(&pf_cachequeue) ||
165 TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag),
166 ("!(TAILQ_EMPTY() || TAILQ_LAST() == farg): %s",
172 * Try to flush old fragments to make space for new ones
176 pf_flush_fragments(void)
178 struct pf_fragment *frag;
181 goal = pf_nfrents * 9 / 10;
182 DPFPRINTF(("trying to free > %d frents\n",
184 while (goal < pf_nfrents) {
185 frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue);
188 pf_free_fragment(frag);
192 goal = pf_ncache * 9 / 10;
193 DPFPRINTF(("trying to free > %d cache entries\n",
195 while (goal < pf_ncache) {
196 frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue);
199 pf_free_fragment(frag);
203 /* Frees the fragments and all associated entries */
206 pf_free_fragment(struct pf_fragment *frag)
208 struct pf_frent *frent;
209 struct pf_frcache *frcache;
211 /* Free all fragments */
212 if (BUFFER_FRAGMENTS(frag)) {
213 for (frent = LIST_FIRST(&frag->fr_queue); frent;
214 frent = LIST_FIRST(&frag->fr_queue)) {
215 LIST_REMOVE(frent, fr_next);
217 m_freem(frent->fr_m);
218 pool_put(&pf_frent_pl, frent);
222 for (frcache = LIST_FIRST(&frag->fr_cache); frcache;
223 frcache = LIST_FIRST(&frag->fr_cache)) {
224 LIST_REMOVE(frcache, fr_next);
226 KASSERT((LIST_EMPTY(&frag->fr_cache) ||
227 LIST_FIRST(&frag->fr_cache)->fr_off >
229 ("! (LIST_EMPTY() || LIST_FIRST()->fr_off >"
230 " frcache->fr_end): %s", __func__));
232 pool_put(&pf_cent_pl, frcache);
237 pf_remove_fragment(frag);
241 pf_ip2key(struct pf_fragment *key, struct ip *ip)
243 key->fr_p = ip->ip_p;
244 key->fr_id = ip->ip_id;
245 key->fr_src.s_addr = ip->ip_src.s_addr;
246 key->fr_dst.s_addr = ip->ip_dst.s_addr;
250 pf_find_fragment(struct ip *ip, struct pf_frag_tree *tree)
252 struct pf_fragment key;
253 struct pf_fragment *frag;
257 frag = RB_FIND(pf_frag_tree, tree, &key);
259 /* XXX Are we sure we want to update the timeout? */
260 frag->fr_timeout = time_second;
261 if (BUFFER_FRAGMENTS(frag)) {
262 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
263 TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
265 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
266 TAILQ_INSERT_HEAD(&pf_cachequeue, frag, frag_next);
273 /* Removes a fragment from the fragment queue and frees the fragment */
276 pf_remove_fragment(struct pf_fragment *frag)
278 if (BUFFER_FRAGMENTS(frag)) {
279 RB_REMOVE(pf_frag_tree, &pf_frag_tree, frag);
280 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
281 pool_put(&pf_frag_pl, frag);
283 RB_REMOVE(pf_frag_tree, &pf_cache_tree, frag);
284 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
285 pool_put(&pf_cache_pl, frag);
289 #define FR_IP_OFF(fr) (((fr)->fr_ip->ip_off & IP_OFFMASK) << 3)
291 pf_reassemble(struct mbuf **m0, struct pf_fragment **frag,
292 struct pf_frent *frent, int mff)
294 struct mbuf *m = *m0, *m2;
295 struct pf_frent *frea, *next;
296 struct pf_frent *frep = NULL;
297 struct ip *ip = frent->fr_ip;
298 int hlen = ip->ip_hl << 2;
299 u_int16_t off = (ip->ip_off & IP_OFFMASK) << 3;
300 u_int16_t ip_len = ip->ip_len - ip->ip_hl * 4;
301 u_int16_t max = ip_len + off;
303 KASSERT((*frag == NULL || BUFFER_FRAGMENTS(*frag)),
304 ("! (*frag == NULL || BUFFER_FRAGMENTS(*frag)): %s", __func__));
306 /* Strip off ip header */
310 /* Create a new reassembly queue for this packet */
312 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
314 pf_flush_fragments();
315 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
320 (*frag)->fr_flags = 0;
322 (*frag)->fr_src = frent->fr_ip->ip_src;
323 (*frag)->fr_dst = frent->fr_ip->ip_dst;
324 (*frag)->fr_p = frent->fr_ip->ip_p;
325 (*frag)->fr_id = frent->fr_ip->ip_id;
326 (*frag)->fr_timeout = time_second;
327 LIST_INIT(&(*frag)->fr_queue);
329 RB_INSERT(pf_frag_tree, &pf_frag_tree, *frag);
330 TAILQ_INSERT_HEAD(&pf_fragqueue, *frag, frag_next);
332 /* We do not have a previous fragment */
338 * Find a fragment after the current one:
339 * - off contains the real shifted offset.
341 LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
342 if (FR_IP_OFF(frea) > off)
347 KASSERT((frep != NULL || frea != NULL),
348 ("!(frep != NULL || frea != NULL): %s", __func__));
351 FR_IP_OFF(frep) + frep->fr_ip->ip_len - frep->fr_ip->ip_hl *
356 precut = FR_IP_OFF(frep) + frep->fr_ip->ip_len -
357 frep->fr_ip->ip_hl * 4 - off;
358 if (precut >= ip_len)
360 m_adj(frent->fr_m, precut);
361 DPFPRINTF(("overlap -%d\n", precut));
362 /* Enforce 8 byte boundaries */
363 ip->ip_off = ip->ip_off + (precut >> 3);
364 off = (ip->ip_off & IP_OFFMASK) << 3;
369 for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
374 aftercut = ip_len + off - FR_IP_OFF(frea);
375 DPFPRINTF(("adjust overlap %d\n", aftercut));
376 if (aftercut < frea->fr_ip->ip_len - frea->fr_ip->ip_hl
379 frea->fr_ip->ip_len =
380 frea->fr_ip->ip_len - aftercut;
381 frea->fr_ip->ip_off = frea->fr_ip->ip_off +
383 m_adj(frea->fr_m, aftercut);
387 /* This fragment is completely overlapped, lose it */
388 next = LIST_NEXT(frea, fr_next);
390 LIST_REMOVE(frea, fr_next);
391 pool_put(&pf_frent_pl, frea);
396 /* Update maximum data size */
397 if ((*frag)->fr_max < max)
398 (*frag)->fr_max = max;
399 /* This is the last segment */
401 (*frag)->fr_flags |= PFFRAG_SEENLAST;
404 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
406 LIST_INSERT_AFTER(frep, frent, fr_next);
408 /* Check if we are completely reassembled */
409 if (!((*frag)->fr_flags & PFFRAG_SEENLAST))
412 /* Check if we have all the data */
414 for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
415 next = LIST_NEXT(frep, fr_next);
417 off += frep->fr_ip->ip_len - frep->fr_ip->ip_hl * 4;
418 if (off < (*frag)->fr_max &&
419 (next == NULL || FR_IP_OFF(next) != off))
421 DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
422 off, next == NULL ? -1 : FR_IP_OFF(next),
427 DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
428 if (off < (*frag)->fr_max)
431 /* We have all the data */
432 frent = LIST_FIRST(&(*frag)->fr_queue);
433 KASSERT((frent != NULL), ("frent == NULL: %s", __func__));
434 if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
435 DPFPRINTF(("drop: too big: %d\n", off));
436 pf_free_fragment(*frag);
440 next = LIST_NEXT(frent, fr_next);
442 /* Magic from ip_input */
448 pool_put(&pf_frent_pl, frent);
450 for (frent = next; frent != NULL; frent = next) {
451 next = LIST_NEXT(frent, fr_next);
454 pool_put(&pf_frent_pl, frent);
459 ip->ip_src = (*frag)->fr_src;
460 ip->ip_dst = (*frag)->fr_dst;
462 /* Remove from fragment queue */
463 pf_remove_fragment(*frag);
466 hlen = ip->ip_hl << 2;
467 ip->ip_len = off + hlen;
471 /* some debugging cruft by sklower, below, will go away soon */
472 /* XXX this should be done elsewhere */
473 if (m->m_flags & M_PKTHDR) {
475 for (m2 = m; m2; m2 = m2->m_next)
477 m->m_pkthdr.len = plen;
480 DPFPRINTF(("complete: %p(%d)\n", m, ip->ip_len));
484 /* Oops - fail safe - drop packet */
485 pool_put(&pf_frent_pl, frent);
492 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
493 int drop, int *nomem)
495 struct mbuf *m = *m0;
496 struct pf_frcache *frp, *fra, *cur = NULL;
497 int ip_len = h->ip_len - (h->ip_hl << 2);
498 u_int16_t off = h->ip_off << 3;
499 u_int16_t max = ip_len + off;
502 KASSERT((*frag == NULL || !BUFFER_FRAGMENTS(*frag)),
503 ("!(*frag == NULL || !BUFFER_FRAGMENTS(*frag)): %s", __func__));
505 /* Create a new range queue for this packet */
507 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
509 pf_flush_fragments();
510 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
515 /* Get an entry for the queue */
516 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
518 pool_put(&pf_cache_pl, *frag);
524 (*frag)->fr_flags = PFFRAG_NOBUFFER;
526 (*frag)->fr_src = h->ip_src;
527 (*frag)->fr_dst = h->ip_dst;
528 (*frag)->fr_p = h->ip_p;
529 (*frag)->fr_id = h->ip_id;
530 (*frag)->fr_timeout = time_second;
534 LIST_INIT(&(*frag)->fr_cache);
535 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
537 RB_INSERT(pf_frag_tree, &pf_cache_tree, *frag);
538 TAILQ_INSERT_HEAD(&pf_cachequeue, *frag, frag_next);
540 DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off, max));
546 * Find a fragment after the current one:
547 * - off contains the real shifted offset.
550 LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
551 if (fra->fr_off > off)
556 KASSERT((frp != NULL || fra != NULL),
557 ("!(frp != NULL || fra != NULL): %s", __func__));
562 precut = frp->fr_end - off;
563 if (precut >= ip_len) {
564 /* Fragment is entirely a duplicate */
565 DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
566 h->ip_id, frp->fr_off, frp->fr_end, off, max));
570 /* They are adjacent. Fixup cache entry */
571 DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
572 h->ip_id, frp->fr_off, frp->fr_end, off, max));
574 } else if (precut > 0) {
575 /* The first part of this payload overlaps with a
576 * fragment that has already been passed.
577 * Need to trim off the first part of the payload.
578 * But to do so easily, we need to create another
579 * mbuf to throw the original header into.
582 DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
583 h->ip_id, precut, frp->fr_off, frp->fr_end, off,
588 /* Update the previous frag to encompass this one */
592 /* XXX Optimization opportunity
593 * This is a very heavy way to trim the payload.
594 * we could do it much faster by diddling mbuf
595 * internals but that would be even less legible
596 * than this mbuf magic. For my next trick,
597 * I'll pull a rabbit out of my laptop.
599 *m0 = m_dup(m, MB_DONTWAIT);
600 /* From KAME Project : We have missed this! */
601 m_adj(*m0, (h->ip_hl << 2) -
602 (*m0)->m_pkthdr.len);
605 KASSERT(((*m0)->m_next == NULL),
606 ("(*m0)->m_next != NULL: %s",
608 m_adj(m, precut + (h->ip_hl << 2));
611 if (m->m_flags & M_PKTHDR) {
614 for (t = m; t; t = t->m_next)
616 m->m_pkthdr.len = plen;
620 h = mtod(m, struct ip *);
622 KASSERT(((int)m->m_len ==
624 ("m->m_len != h->ip_len - precut: %s",
626 h->ip_off = h->ip_off +
628 h->ip_len = h->ip_len - precut;
633 /* There is a gap between fragments */
635 DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
636 h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
639 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
646 LIST_INSERT_AFTER(frp, cur, fr_next);
654 aftercut = max - fra->fr_off;
656 /* Adjacent fragments */
657 DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
658 h->ip_id, off, max, fra->fr_off, fra->fr_end));
661 } else if (aftercut > 0) {
662 /* Need to chop off the tail of this fragment */
663 DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
664 h->ip_id, aftercut, off, max, fra->fr_off,
673 if (m->m_flags & M_PKTHDR) {
676 for (t = m; t; t = t->m_next)
678 m->m_pkthdr.len = plen;
680 h = mtod(m, struct ip *);
681 KASSERT(((int)m->m_len == h->ip_len - aftercut),
682 ("m->m_len != h->ip_len - aftercut: %s",
684 h->ip_len = h->ip_len - aftercut;
688 } else if (frp == NULL) {
689 /* There is a gap between fragments */
690 DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
691 h->ip_id, -aftercut, off, max, fra->fr_off,
694 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
701 LIST_INSERT_BEFORE(fra, cur, fr_next);
705 /* Need to glue together two separate fragment descriptors */
707 if (cur && fra->fr_off <= cur->fr_end) {
708 /* Need to merge in a previous 'cur' */
709 DPFPRINTF(("fragcache[%d]: adjacent(merge "
710 "%d-%d) %d-%d (%d-%d)\n",
711 h->ip_id, cur->fr_off, cur->fr_end, off,
712 max, fra->fr_off, fra->fr_end));
713 fra->fr_off = cur->fr_off;
714 LIST_REMOVE(cur, fr_next);
715 pool_put(&pf_cent_pl, cur);
719 } else if (frp && fra->fr_off <= frp->fr_end) {
720 /* Need to merge in a modified 'frp' */
721 KASSERT((cur == NULL), ("cur != NULL: %s",
723 DPFPRINTF(("fragcache[%d]: adjacent(merge "
724 "%d-%d) %d-%d (%d-%d)\n",
725 h->ip_id, frp->fr_off, frp->fr_end, off,
726 max, fra->fr_off, fra->fr_end));
727 fra->fr_off = frp->fr_off;
728 LIST_REMOVE(frp, fr_next);
729 pool_put(&pf_cent_pl, frp);
739 * We must keep tracking the overall fragment even when
740 * we're going to drop it anyway so that we know when to
741 * free the overall descriptor. Thus we drop the frag late.
748 /* Update maximum data size */
749 if ((*frag)->fr_max < max)
750 (*frag)->fr_max = max;
752 /* This is the last segment */
754 (*frag)->fr_flags |= PFFRAG_SEENLAST;
756 /* Check if we are completely reassembled */
757 if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
758 LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
759 LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
760 /* Remove from fragment queue */
761 DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
763 pf_free_fragment(*frag);
772 /* Still need to pay attention to !IP_MF */
773 if (!mff && *frag != NULL)
774 (*frag)->fr_flags |= PFFRAG_SEENLAST;
781 /* Still need to pay attention to !IP_MF */
782 if (!mff && *frag != NULL)
783 (*frag)->fr_flags |= PFFRAG_SEENLAST;
786 /* This fragment has been deemed bad. Don't reass */
787 if (((*frag)->fr_flags & PFFRAG_DROP) == 0)
788 DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
790 (*frag)->fr_flags |= PFFRAG_DROP;
798 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
801 struct mbuf *m = *m0;
803 struct pf_frent *frent;
804 struct pf_fragment *frag = NULL;
805 struct ip *h = mtod(m, struct ip *);
806 int mff = (h->ip_off & IP_MF);
807 int hlen = h->ip_hl << 2;
808 u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;
814 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
817 if (pfi_kif_match(r->kif, kif) == r->ifnot)
818 r = r->skip[PF_SKIP_IFP].ptr;
819 else if (r->direction && r->direction != dir)
820 r = r->skip[PF_SKIP_DIR].ptr;
821 else if (r->af && r->af != AF_INET)
822 r = r->skip[PF_SKIP_AF].ptr;
823 else if (r->proto && r->proto != h->ip_p)
824 r = r->skip[PF_SKIP_PROTO].ptr;
825 else if (PF_MISMATCHAW(&r->src.addr,
826 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
828 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
829 else if (PF_MISMATCHAW(&r->dst.addr,
830 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
832 r = r->skip[PF_SKIP_DST_ADDR].ptr;
833 else if (r->match_tag && !pf_match_tag(m, r, &tag))
834 r = TAILQ_NEXT(r, entries);
839 if (r == NULL || r->action == PF_NOSCRUB)
842 r->packets[dir == PF_OUT]++;
843 r->bytes[dir == PF_OUT] += pd->tot_len;
846 /* Check for illegal packets */
847 if (hlen < (int)sizeof(struct ip))
850 if (hlen > h->ip_len)
853 /* Clear IP_DF if the rule uses the no-df option */
854 if (r->rule_flag & PFRULE_NODF && h->ip_off & IP_DF) {
855 u_int16_t ip_off = h->ip_off;
858 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
861 /* We will need other tests here */
862 if (!fragoff && !mff)
865 /* We're dealing with a fragment now. Don't allow fragments
866 * with IP_DF to enter the cache. If the flag was cleared by
867 * no-df above, fine. Otherwise drop it.
869 if (h->ip_off & IP_DF) {
870 DPFPRINTF(("IP_DF\n"));
874 ip_len = h->ip_len - hlen;
875 ip_off = (h->ip_off & IP_OFFMASK) << 3;
877 /* All fragments are 8 byte aligned */
878 if (mff && (ip_len & 0x7)) {
879 DPFPRINTF(("mff and %d\n", ip_len));
883 /* Respect maximum length */
884 if (fragoff + ip_len > IP_MAXPACKET) {
885 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
888 max = fragoff + ip_len;
890 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
891 /* Fully buffer all of the fragments */
893 frag = pf_find_fragment(h, &pf_frag_tree);
895 /* Check if we saw the last fragment already */
896 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
900 /* Get an entry for the fragment queue */
901 frent = pool_get(&pf_frent_pl, PR_NOWAIT);
903 REASON_SET(reason, PFRES_MEMORY);
910 /* Might return a completely reassembled mbuf, or NULL */
911 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
912 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
917 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
920 h = mtod(m, struct ip *);
922 /* non-buffering fragment cache (drops or masks overlaps) */
925 if (dir == PF_OUT && m->m_pkthdr.pf.flags & PF_TAG_FRAGCACHE) {
927 * Already passed the fragment cache in the
928 * input direction. If we continued, it would
929 * appear to be a dup and would be dropped.
934 frag = pf_find_fragment(h, &pf_cache_tree);
936 /* Check if we saw the last fragment already */
937 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
938 max > frag->fr_max) {
939 if (r->rule_flag & PFRULE_FRAGDROP)
940 frag->fr_flags |= PFFRAG_DROP;
944 *m0 = m = pf_fragcache(m0, h, &frag, mff,
945 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
953 m->m_pkthdr.pf.flags |= PF_TAG_FRAGCACHE;
955 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
961 /* At this point, only IP_DF is allowed in ip_off */
962 if (h->ip_off & ~IP_DF) {
963 u_int16_t ip_off = h->ip_off;
966 h->ip_sum = pf_cksum_fixup(h->ip_sum, htons(ip_off), htons(h->ip_off), 0);
969 /* Enforce a minimum ttl, may cause endless packet loops */
970 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
971 u_int16_t ip_ttl = h->ip_ttl;
973 h->ip_ttl = r->min_ttl;
974 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
978 if (r->rule_flag & PFRULE_SET_TOS) {
981 ov = *(u_int16_t *)h;
982 h->ip_tos = r->set_tos;
983 nv = *(u_int16_t *)h;
985 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
988 if (r->rule_flag & PFRULE_RANDOMID) {
989 u_int16_t ip_id = h->ip_id;
991 h->ip_id = ip_randomid();
992 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
994 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
995 pd->flags |= PFDESC_IP_REAS;
1000 /* Enforce a minimum ttl, may cause endless packet loops */
1001 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
1002 u_int16_t ip_ttl = h->ip_ttl;
1004 h->ip_ttl = r->min_ttl;
1005 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1008 if (r->rule_flag & PFRULE_SET_TOS) {
1011 ov = *(u_int16_t *)h;
1012 h->ip_tos = r->set_tos;
1013 nv = *(u_int16_t *)h;
1015 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1017 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1018 pd->flags |= PFDESC_IP_REAS;
1022 REASON_SET(reason, PFRES_MEMORY);
1023 if (r != NULL && r->log)
1024 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1028 REASON_SET(reason, PFRES_NORM);
1029 if (r != NULL && r->log)
1030 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1034 DPFPRINTF(("dropping bad fragment\n"));
1036 /* Free associated fragments */
1038 pf_free_fragment(frag);
1040 REASON_SET(reason, PFRES_FRAG);
1041 if (r != NULL && r->log)
1042 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1049 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1050 u_short *reason, struct pf_pdesc *pd)
1052 struct mbuf *m = *m0;
1054 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1058 struct ip6_opt_jumbo jumbo;
1059 struct ip6_frag frag;
1060 u_int32_t jumbolen = 0, plen;
1061 u_int16_t fragoff = 0;
1067 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1070 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1071 r = r->skip[PF_SKIP_IFP].ptr;
1072 else if (r->direction && r->direction != dir)
1073 r = r->skip[PF_SKIP_DIR].ptr;
1074 else if (r->af && r->af != AF_INET6)
1075 r = r->skip[PF_SKIP_AF].ptr;
1076 #if 0 /* header chain! */
1077 else if (r->proto && r->proto != h->ip6_nxt)
1078 r = r->skip[PF_SKIP_PROTO].ptr;
1080 else if (PF_MISMATCHAW(&r->src.addr,
1081 (struct pf_addr *)&h->ip6_src, AF_INET6,
1083 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1084 else if (PF_MISMATCHAW(&r->dst.addr,
1085 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1087 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1092 if (r == NULL || r->action == PF_NOSCRUB)
1095 r->packets[dir == PF_OUT]++;
1096 r->bytes[dir == PF_OUT] += pd->tot_len;
1099 /* Check for illegal packets */
1100 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1103 off = sizeof(struct ip6_hdr);
1108 case IPPROTO_FRAGMENT:
1112 case IPPROTO_ROUTING:
1113 case IPPROTO_DSTOPTS:
1114 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1117 if (proto == IPPROTO_AH)
1118 off += (ext.ip6e_len + 2) * 4;
1120 off += (ext.ip6e_len + 1) * 8;
1121 proto = ext.ip6e_nxt;
1123 case IPPROTO_HOPOPTS:
1124 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1127 optend = off + (ext.ip6e_len + 1) * 8;
1128 ooff = off + sizeof(ext);
1130 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1131 sizeof(opt.ip6o_type), NULL, NULL,
1134 if (opt.ip6o_type == IP6OPT_PAD1) {
1138 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1139 NULL, NULL, AF_INET6))
1141 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1143 switch (opt.ip6o_type) {
1145 if (h->ip6_plen != 0)
1147 if (!pf_pull_hdr(m, ooff, &jumbo,
1148 sizeof(jumbo), NULL, NULL,
1151 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1153 jumbolen = ntohl(jumbolen);
1154 if (jumbolen <= IPV6_MAXPACKET)
1156 if (sizeof(struct ip6_hdr) + jumbolen !=
1163 ooff += sizeof(opt) + opt.ip6o_len;
1164 } while (ooff < optend);
1167 proto = ext.ip6e_nxt;
1173 } while (!terminal);
1175 /* jumbo payload option must be present, or plen > 0 */
1176 if (ntohs(h->ip6_plen) == 0)
1179 plen = ntohs(h->ip6_plen);
1182 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1185 /* Enforce a minimum ttl, may cause endless packet loops */
1186 if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1187 h->ip6_hlim = r->min_ttl;
1192 if (ntohs(h->ip6_plen) == 0 || jumbolen)
1194 plen = ntohs(h->ip6_plen);
1196 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1198 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1199 if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1202 /* do something about it */
1203 /* remember to set pd->flags |= PFDESC_IP_REAS */
1207 REASON_SET(reason, PFRES_SHORT);
1208 if (r != NULL && r->log)
1209 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1213 REASON_SET(reason, PFRES_NORM);
1214 if (r != NULL && r->log)
1215 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1219 REASON_SET(reason, PFRES_FRAG);
1220 if (r != NULL && r->log)
1221 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1227 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1228 int off, void *h, struct pf_pdesc *pd)
1230 struct pf_rule *r, *rm = NULL;
1231 struct tcphdr *th = pd->hdr.tcp;
1235 sa_family_t af = pd->af;
1237 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1240 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1241 r = r->skip[PF_SKIP_IFP].ptr;
1242 else if (r->direction && r->direction != dir)
1243 r = r->skip[PF_SKIP_DIR].ptr;
1244 else if (r->af && r->af != af)
1245 r = r->skip[PF_SKIP_AF].ptr;
1246 else if (r->proto && r->proto != pd->proto)
1247 r = r->skip[PF_SKIP_PROTO].ptr;
1248 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1250 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1251 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1252 r->src.port[0], r->src.port[1], th->th_sport))
1253 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1254 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1256 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1257 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1258 r->dst.port[0], r->dst.port[1], th->th_dport))
1259 r = r->skip[PF_SKIP_DST_PORT].ptr;
1260 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1261 pf_osfp_fingerprint(pd, m, off, th),
1263 r = TAILQ_NEXT(r, entries);
1270 if (rm == NULL || rm->action == PF_NOSCRUB)
1273 r->packets[dir == PF_OUT]++;
1274 r->bytes[dir == PF_OUT] += pd->tot_len;
1277 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1278 pd->flags |= PFDESC_TCP_NORM;
1280 flags = th->th_flags;
1281 if (flags & TH_SYN) {
1282 /* Illegal packet */
1289 /* Illegal packet */
1290 if (!(flags & (TH_ACK|TH_RST)))
1294 if (!(flags & TH_ACK)) {
1295 /* These flags are only valid if ACK is set */
1296 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1300 /* Check for illegal header length */
1301 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1304 /* If flags changed, or reserved data set, then adjust */
1305 if (flags != th->th_flags || th->th_x2 != 0) {
1308 ov = *(u_int16_t *)(&th->th_ack + 1);
1309 th->th_flags = flags;
1311 nv = *(u_int16_t *)(&th->th_ack + 1);
1313 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1317 /* Remove urgent pointer, if TH_URG is not set */
1318 if (!(flags & TH_URG) && th->th_urp) {
1319 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1324 /* Process options */
1325 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1328 /* copy back packet headers if we sanitized */
1330 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1335 REASON_SET(&reason, PFRES_NORM);
1336 if (rm != NULL && r->log)
1337 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL, pd);
1342 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1343 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1345 u_int32_t tsval, tsecr;
1349 KASSERT((src->scrub == NULL),
1350 ("pf_normalize_tcp_init: src->scrub != NULL"));
1352 src->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
1353 if (src->scrub == NULL)
1355 bzero(src->scrub, sizeof(*src->scrub));
1360 struct ip *h = mtod(m, struct ip *);
1361 src->scrub->pfss_ttl = h->ip_ttl;
1367 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1368 src->scrub->pfss_ttl = h->ip6_hlim;
1376 * All normalizations below are only begun if we see the start of
1377 * the connections. They must all set an enabled bit in pfss_flags
1379 if ((th->th_flags & TH_SYN) == 0)
1383 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1384 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1385 /* Diddle with TCP options */
1387 opt = hdr + sizeof(struct tcphdr);
1388 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1389 while (hlen >= TCPOLEN_TIMESTAMP) {
1391 case TCPOPT_EOL: /* FALLTHROUGH */
1396 case TCPOPT_TIMESTAMP:
1397 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1398 src->scrub->pfss_flags |=
1400 src->scrub->pfss_ts_mod = karc4random();
1402 /* note PFSS_PAWS not set yet */
1403 memcpy(&tsval, &opt[2],
1405 memcpy(&tsecr, &opt[6],
1407 src->scrub->pfss_tsval0 = ntohl(tsval);
1408 src->scrub->pfss_tsval = ntohl(tsval);
1409 src->scrub->pfss_tsecr = ntohl(tsecr);
1410 getmicrouptime(&src->scrub->pfss_last);
1414 hlen -= MAX(opt[1], 2);
1415 opt += MAX(opt[1], 2);
1425 pf_normalize_tcp_cleanup(struct pf_state *state)
1427 if (state->src.scrub)
1428 pool_put(&pf_state_scrub_pl, state->src.scrub);
1429 if (state->dst.scrub)
1430 pool_put(&pf_state_scrub_pl, state->dst.scrub);
1432 /* Someday... flush the TCP segment reassembly descriptors. */
1436 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1437 u_short *reason, struct tcphdr *th, struct pf_state *state,
1438 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1440 struct timeval uptime;
1441 u_int32_t tsval, tsecr;
1442 u_int tsval_from_last;
1448 KASSERT((src->scrub || dst->scrub),
1449 ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1452 * Enforce the minimum TTL seen for this connection. Negate a common
1453 * technique to evade an intrusion detection system and confuse
1454 * firewall state code.
1460 struct ip *h = mtod(m, struct ip *);
1461 if (h->ip_ttl > src->scrub->pfss_ttl)
1462 src->scrub->pfss_ttl = h->ip_ttl;
1463 h->ip_ttl = src->scrub->pfss_ttl;
1471 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1472 if (h->ip6_hlim > src->scrub->pfss_ttl)
1473 src->scrub->pfss_ttl = h->ip6_hlim;
1474 h->ip6_hlim = src->scrub->pfss_ttl;
1481 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1482 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1483 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1484 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1485 /* Diddle with TCP options */
1487 opt = hdr + sizeof(struct tcphdr);
1488 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1489 while (hlen >= TCPOLEN_TIMESTAMP) {
1491 case TCPOPT_EOL: /* FALLTHROUGH */
1496 case TCPOPT_TIMESTAMP:
1497 /* Modulate the timestamps. Can be used for
1498 * NAT detection, OS uptime determination or
1503 /* Huh? Multiple timestamps!? */
1504 if (pf_status.debug >= PF_DEBUG_MISC) {
1505 DPFPRINTF(("multiple TS??"));
1506 pf_print_state(state);
1509 REASON_SET(reason, PFRES_TS);
1512 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1513 memcpy(&tsval, &opt[2],
1515 if (tsval && src->scrub &&
1516 (src->scrub->pfss_flags &
1518 tsval = ntohl(tsval);
1519 pf_change_a(&opt[2],
1522 src->scrub->pfss_ts_mod),
1527 /* Modulate TS reply iff valid (!0) */
1528 memcpy(&tsecr, &opt[6],
1530 if (tsecr && dst->scrub &&
1531 (dst->scrub->pfss_flags &
1533 tsecr = ntohl(tsecr)
1534 - dst->scrub->pfss_ts_mod;
1535 pf_change_a(&opt[6],
1536 &th->th_sum, htonl(tsecr),
1544 hlen -= MAX(opt[1], 2);
1545 opt += MAX(opt[1], 2);
1550 /* Copyback the options, caller copys back header */
1552 m_copyback(m, off + sizeof(struct tcphdr),
1553 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1554 sizeof(struct tcphdr));
1560 * Must invalidate PAWS checks on connections idle for too long.
1561 * The fastest allowed timestamp clock is 1ms. That turns out to
1562 * be about 24 days before it wraps. XXX Right now our lowerbound
1563 * TS echo check only works for the first 12 days of a connection
1564 * when the TS has exhausted half its 32bit space
1566 #define TS_MAX_IDLE (24*24*60*60)
1567 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1569 getmicrouptime(&uptime);
1570 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1571 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1572 time_second - state->creation > TS_MAX_CONN)) {
1573 if (pf_status.debug >= PF_DEBUG_MISC) {
1574 DPFPRINTF(("src idled out of PAWS\n"));
1575 pf_print_state(state);
1578 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1581 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1582 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1583 if (pf_status.debug >= PF_DEBUG_MISC) {
1584 DPFPRINTF(("dst idled out of PAWS\n"));
1585 pf_print_state(state);
1588 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1592 if (got_ts && src->scrub && dst->scrub &&
1593 (src->scrub->pfss_flags & PFSS_PAWS) &&
1594 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1595 /* Validate that the timestamps are "in-window".
1596 * RFC1323 describes TCP Timestamp options that allow
1597 * measurement of RTT (round trip time) and PAWS
1598 * (protection against wrapped sequence numbers). PAWS
1599 * gives us a set of rules for rejecting packets on
1600 * long fat pipes (packets that were somehow delayed
1601 * in transit longer than the time it took to send the
1602 * full TCP sequence space of 4Gb). We can use these
1603 * rules and infer a few others that will let us treat
1604 * the 32bit timestamp and the 32bit echoed timestamp
1605 * as sequence numbers to prevent a blind attacker from
1606 * inserting packets into a connection.
1609 * - The timestamp on this packet must be greater than
1610 * or equal to the last value echoed by the other
1611 * endpoint. The RFC says those will be discarded
1612 * since it is a dup that has already been acked.
1613 * This gives us a lowerbound on the timestamp.
1614 * timestamp >= other last echoed timestamp
1615 * - The timestamp will be less than or equal to
1616 * the last timestamp plus the time between the
1617 * last packet and now. The RFC defines the max
1618 * clock rate as 1ms. We will allow clocks to be
1619 * up to 10% fast and will allow a total difference
1620 * or 30 seconds due to a route change. And this
1621 * gives us an upperbound on the timestamp.
1622 * timestamp <= last timestamp + max ticks
1623 * We have to be careful here. Windows will send an
1624 * initial timestamp of zero and then initialize it
1625 * to a random value after the 3whs; presumably to
1626 * avoid a DoS by having to call an expensive RNG
1627 * during a SYN flood. Proof MS has at least one
1628 * good security geek.
1630 * - The TCP timestamp option must also echo the other
1631 * endpoints timestamp. The timestamp echoed is the
1632 * one carried on the earliest unacknowledged segment
1633 * on the left edge of the sequence window. The RFC
1634 * states that the host will reject any echoed
1635 * timestamps that were larger than any ever sent.
1636 * This gives us an upperbound on the TS echo.
1637 * tescr <= largest_tsval
1638 * - The lowerbound on the TS echo is a little more
1639 * tricky to determine. The other endpoint's echoed
1640 * values will not decrease. But there may be
1641 * network conditions that re-order packets and
1642 * cause our view of them to decrease. For now the
1643 * only lowerbound we can safely determine is that
1644 * the TS echo will never be less than the original
1645 * TS. XXX There is probably a better lowerbound.
1646 * Remove TS_MAX_CONN with better lowerbound check.
1647 * tescr >= other original TS
1649 * It is also important to note that the fastest
1650 * timestamp clock of 1ms will wrap its 32bit space in
1651 * 24 days. So we just disable TS checking after 24
1652 * days of idle time. We actually must use a 12d
1653 * connection limit until we can come up with a better
1654 * lowerbound to the TS echo check.
1656 struct timeval delta_ts;
1661 * PFTM_TS_DIFF is how many seconds of leeway to allow
1662 * a host's timestamp. This can happen if the previous
1663 * packet got delayed in transit for much longer than
1666 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1667 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1670 /* Calculate max ticks since the last timestamp */
1671 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1672 #define TS_MICROSECS 1000000 /* microseconds per second */
1674 #define timersub(tvp, uvp, vvp) \
1676 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
1677 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
1678 if ((vvp)->tv_usec < 0) { \
1680 (vvp)->tv_usec += 1000000; \
1685 timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1686 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1687 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1690 if ((src->state >= TCPS_ESTABLISHED &&
1691 dst->state >= TCPS_ESTABLISHED) &&
1692 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1693 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1694 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1695 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1696 /* Bad RFC1323 implementation or an insertion attack.
1698 * - Solaris 2.6 and 2.7 are known to send another ACK
1699 * after the FIN,FIN|ACK,ACK closing that carries
1703 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1704 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1705 SEQ_GT(tsval, src->scrub->pfss_tsval +
1706 tsval_from_last) ? '1' : ' ',
1707 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1708 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1709 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1710 "idle: %lus %lums\n",
1711 tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
1712 delta_ts.tv_usec / 1000));
1713 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1714 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1715 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1716 "\n", dst->scrub->pfss_tsval,
1717 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1718 if (pf_status.debug >= PF_DEBUG_MISC) {
1719 pf_print_state(state);
1720 pf_print_flags(th->th_flags);
1723 REASON_SET(reason, PFRES_TS);
1727 /* XXX I'd really like to require tsecr but it's optional */
1729 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1730 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1731 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1732 src->scrub && dst->scrub &&
1733 (src->scrub->pfss_flags & PFSS_PAWS) &&
1734 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1735 /* Didn't send a timestamp. Timestamps aren't really useful
1737 * - connection opening or closing (often not even sent).
1738 * but we must not let an attacker to put a FIN on a
1739 * data packet to sneak it through our ESTABLISHED check.
1740 * - on a TCP reset. RFC suggests not even looking at TS.
1741 * - on an empty ACK. The TS will not be echoed so it will
1742 * probably not help keep the RTT calculation in sync and
1743 * there isn't as much danger when the sequence numbers
1744 * got wrapped. So some stacks don't include TS on empty
1747 * To minimize the disruption to mostly RFC1323 conformant
1748 * stacks, we will only require timestamps on data packets.
1750 * And what do ya know, we cannot require timestamps on data
1751 * packets. There appear to be devices that do legitimate
1752 * TCP connection hijacking. There are HTTP devices that allow
1753 * a 3whs (with timestamps) and then buffer the HTTP request.
1754 * If the intermediate device has the HTTP response cache, it
1755 * will spoof the response but not bother timestamping its
1756 * packets. So we can look for the presence of a timestamp in
1757 * the first data packet and if there, require it in all future
1761 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1763 * Hey! Someone tried to sneak a packet in. Or the
1764 * stack changed its RFC1323 behavior?!?!
1766 if (pf_status.debug >= PF_DEBUG_MISC) {
1767 DPFPRINTF(("Did not receive expected RFC1323 "
1769 pf_print_state(state);
1770 pf_print_flags(th->th_flags);
1773 REASON_SET(reason, PFRES_TS);
1780 * We will note if a host sends his data packets with or without
1781 * timestamps. And require all data packets to contain a timestamp
1782 * if the first does. PAWS implicitly requires that all data packets be
1783 * timestamped. But I think there are middle-man devices that hijack
1784 * TCP streams immediately after the 3whs and don't timestamp their
1785 * packets (seen in a WWW accelerator or cache).
1787 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1788 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1790 src->scrub->pfss_flags |= PFSS_DATA_TS;
1792 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1793 if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1794 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1795 /* Don't warn if other host rejected RFC1323 */
1796 DPFPRINTF(("Broken RFC1323 stack did not "
1797 "timestamp data packet. Disabled PAWS "
1799 pf_print_state(state);
1800 pf_print_flags(th->th_flags);
1808 * Update PAWS values
1810 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1811 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1812 getmicrouptime(&src->scrub->pfss_last);
1813 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1814 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1815 src->scrub->pfss_tsval = tsval;
1818 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1819 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1820 src->scrub->pfss_tsecr = tsecr;
1822 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1823 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1824 src->scrub->pfss_tsval0 == 0)) {
1825 /* tsval0 MUST be the lowest timestamp */
1826 src->scrub->pfss_tsval0 = tsval;
1829 /* Only fully initialized after a TS gets echoed */
1830 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1831 src->scrub->pfss_flags |= PFSS_PAWS;
1835 /* I have a dream.... TCP segment reassembly.... */
1840 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1841 int off, sa_family_t af)
1845 int opt, cnt, optlen = 0;
1847 u_char opts[TCP_MAXOLEN];
1848 u_char *optp = opts;
1850 thoff = th->th_off << 2;
1851 cnt = thoff - sizeof(struct tcphdr);
1853 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1857 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1859 if (opt == TCPOPT_EOL)
1861 if (opt == TCPOPT_NOP)
1867 if (optlen < 2 || optlen > cnt)
1872 mss = (u_int16_t *)(optp + 2);
1873 if ((ntohs(*mss)) > r->max_mss) {
1874 th->th_sum = pf_cksum_fixup(th->th_sum,
1875 *mss, htons(r->max_mss), 0);
1876 *mss = htons(r->max_mss);
1886 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);