1 /* $OpenBSD: pf_norm.c,v 1.109 2007/05/28 17:16:39 henning 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);
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;
813 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
816 if (pfi_kif_match(r->kif, kif) == r->ifnot)
817 r = r->skip[PF_SKIP_IFP].ptr;
818 else if (r->direction && r->direction != dir)
819 r = r->skip[PF_SKIP_DIR].ptr;
820 else if (r->af && r->af != AF_INET)
821 r = r->skip[PF_SKIP_AF].ptr;
822 else if (r->proto && r->proto != h->ip_p)
823 r = r->skip[PF_SKIP_PROTO].ptr;
824 else if (PF_MISMATCHAW(&r->src.addr,
825 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
827 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
828 else if (PF_MISMATCHAW(&r->dst.addr,
829 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
831 r = r->skip[PF_SKIP_DST_ADDR].ptr;
836 if (r == NULL || r->action == PF_NOSCRUB)
839 r->packets[dir == PF_OUT]++;
840 r->bytes[dir == PF_OUT] += pd->tot_len;
843 /* Check for illegal packets */
844 if (hlen < (int)sizeof(struct ip))
847 if (hlen > h->ip_len)
850 /* Clear IP_DF if the rule uses the no-df option */
851 if (r->rule_flag & PFRULE_NODF && h->ip_off & IP_DF) {
852 u_int16_t ip_off = h->ip_off;
855 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
858 /* We will need other tests here */
859 if (!fragoff && !mff)
862 /* We're dealing with a fragment now. Don't allow fragments
863 * with IP_DF to enter the cache. If the flag was cleared by
864 * no-df above, fine. Otherwise drop it.
866 if (h->ip_off & IP_DF) {
867 DPFPRINTF(("IP_DF\n"));
871 ip_len = h->ip_len - hlen;
872 ip_off = (h->ip_off & IP_OFFMASK) << 3;
874 /* All fragments are 8 byte aligned */
875 if (mff && (ip_len & 0x7)) {
876 DPFPRINTF(("mff and %d\n", ip_len));
880 /* Respect maximum length */
881 if (fragoff + ip_len > IP_MAXPACKET) {
882 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
885 max = fragoff + ip_len;
887 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
888 /* Fully buffer all of the fragments */
890 frag = pf_find_fragment(h, &pf_frag_tree);
892 /* Check if we saw the last fragment already */
893 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
897 /* Get an entry for the fragment queue */
898 frent = pool_get(&pf_frent_pl, PR_NOWAIT);
900 REASON_SET(reason, PFRES_MEMORY);
907 /* Might return a completely reassembled mbuf, or NULL */
908 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
909 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
914 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
917 h = mtod(m, struct ip *);
919 /* non-buffering fragment cache (drops or masks overlaps) */
922 if (dir == PF_OUT && m->m_pkthdr.pf.flags & PF_TAG_FRAGCACHE) {
924 * Already passed the fragment cache in the
925 * input direction. If we continued, it would
926 * appear to be a dup and would be dropped.
931 frag = pf_find_fragment(h, &pf_cache_tree);
933 /* Check if we saw the last fragment already */
934 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
935 max > frag->fr_max) {
936 if (r->rule_flag & PFRULE_FRAGDROP)
937 frag->fr_flags |= PFFRAG_DROP;
941 *m0 = m = pf_fragcache(m0, h, &frag, mff,
942 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
950 m->m_pkthdr.pf.flags |= PF_TAG_FRAGCACHE;
952 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
958 /* At this point, only IP_DF is allowed in ip_off */
959 if (h->ip_off & ~IP_DF) {
960 u_int16_t ip_off = h->ip_off;
963 h->ip_sum = pf_cksum_fixup(h->ip_sum, htons(ip_off), htons(h->ip_off), 0);
966 /* Enforce a minimum ttl, may cause endless packet loops */
967 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
968 u_int16_t ip_ttl = h->ip_ttl;
970 h->ip_ttl = r->min_ttl;
971 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
974 if (r->rule_flag & PFRULE_RANDOMID) {
975 u_int16_t ip_id = h->ip_id;
977 h->ip_id = ip_randomid();
978 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
980 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
981 pd->flags |= PFDESC_IP_REAS;
986 /* Enforce a minimum ttl, may cause endless packet loops */
987 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
988 u_int16_t ip_ttl = h->ip_ttl;
990 h->ip_ttl = r->min_ttl;
991 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
993 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
994 pd->flags |= PFDESC_IP_REAS;
998 REASON_SET(reason, PFRES_MEMORY);
999 if (r != NULL && r->log)
1000 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1004 REASON_SET(reason, PFRES_NORM);
1005 if (r != NULL && r->log)
1006 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1010 DPFPRINTF(("dropping bad fragment\n"));
1012 /* Free associated fragments */
1014 pf_free_fragment(frag);
1016 REASON_SET(reason, PFRES_FRAG);
1017 if (r != NULL && r->log)
1018 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1025 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1026 u_short *reason, struct pf_pdesc *pd)
1028 struct mbuf *m = *m0;
1030 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1034 struct ip6_opt_jumbo jumbo;
1035 struct ip6_frag frag;
1036 u_int32_t jumbolen = 0, plen;
1037 u_int16_t fragoff = 0;
1043 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1046 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1047 r = r->skip[PF_SKIP_IFP].ptr;
1048 else if (r->direction && r->direction != dir)
1049 r = r->skip[PF_SKIP_DIR].ptr;
1050 else if (r->af && r->af != AF_INET6)
1051 r = r->skip[PF_SKIP_AF].ptr;
1052 #if 0 /* header chain! */
1053 else if (r->proto && r->proto != h->ip6_nxt)
1054 r = r->skip[PF_SKIP_PROTO].ptr;
1056 else if (PF_MISMATCHAW(&r->src.addr,
1057 (struct pf_addr *)&h->ip6_src, AF_INET6,
1059 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1060 else if (PF_MISMATCHAW(&r->dst.addr,
1061 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1063 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1068 if (r == NULL || r->action == PF_NOSCRUB)
1071 r->packets[dir == PF_OUT]++;
1072 r->bytes[dir == PF_OUT] += pd->tot_len;
1075 /* Check for illegal packets */
1076 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1079 off = sizeof(struct ip6_hdr);
1084 case IPPROTO_FRAGMENT:
1088 case IPPROTO_ROUTING:
1089 case IPPROTO_DSTOPTS:
1090 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1093 if (proto == IPPROTO_AH)
1094 off += (ext.ip6e_len + 2) * 4;
1096 off += (ext.ip6e_len + 1) * 8;
1097 proto = ext.ip6e_nxt;
1099 case IPPROTO_HOPOPTS:
1100 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1103 optend = off + (ext.ip6e_len + 1) * 8;
1104 ooff = off + sizeof(ext);
1106 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1107 sizeof(opt.ip6o_type), NULL, NULL,
1110 if (opt.ip6o_type == IP6OPT_PAD1) {
1114 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1115 NULL, NULL, AF_INET6))
1117 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1119 switch (opt.ip6o_type) {
1121 if (h->ip6_plen != 0)
1123 if (!pf_pull_hdr(m, ooff, &jumbo,
1124 sizeof(jumbo), NULL, NULL,
1127 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1129 jumbolen = ntohl(jumbolen);
1130 if (jumbolen <= IPV6_MAXPACKET)
1132 if (sizeof(struct ip6_hdr) + jumbolen !=
1139 ooff += sizeof(opt) + opt.ip6o_len;
1140 } while (ooff < optend);
1143 proto = ext.ip6e_nxt;
1149 } while (!terminal);
1151 /* jumbo payload option must be present, or plen > 0 */
1152 if (ntohs(h->ip6_plen) == 0)
1155 plen = ntohs(h->ip6_plen);
1158 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1161 /* Enforce a minimum ttl, may cause endless packet loops */
1162 if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1163 h->ip6_hlim = r->min_ttl;
1168 if (ntohs(h->ip6_plen) == 0 || jumbolen)
1170 plen = ntohs(h->ip6_plen);
1172 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1174 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1175 if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1178 /* do something about it */
1179 /* remember to set pd->flags |= PFDESC_IP_REAS */
1183 REASON_SET(reason, PFRES_SHORT);
1184 if (r != NULL && r->log)
1185 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1189 REASON_SET(reason, PFRES_NORM);
1190 if (r != NULL && r->log)
1191 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1195 REASON_SET(reason, PFRES_FRAG);
1196 if (r != NULL && r->log)
1197 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1203 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1204 int off, void *h, struct pf_pdesc *pd)
1206 struct pf_rule *r, *rm = NULL;
1207 struct tcphdr *th = pd->hdr.tcp;
1211 sa_family_t af = pd->af;
1213 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1216 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1217 r = r->skip[PF_SKIP_IFP].ptr;
1218 else if (r->direction && r->direction != dir)
1219 r = r->skip[PF_SKIP_DIR].ptr;
1220 else if (r->af && r->af != af)
1221 r = r->skip[PF_SKIP_AF].ptr;
1222 else if (r->proto && r->proto != pd->proto)
1223 r = r->skip[PF_SKIP_PROTO].ptr;
1224 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1226 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1227 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1228 r->src.port[0], r->src.port[1], th->th_sport))
1229 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1230 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1232 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1233 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1234 r->dst.port[0], r->dst.port[1], th->th_dport))
1235 r = r->skip[PF_SKIP_DST_PORT].ptr;
1236 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1237 pf_osfp_fingerprint(pd, m, off, th),
1239 r = TAILQ_NEXT(r, entries);
1246 if (rm == NULL || rm->action == PF_NOSCRUB)
1249 r->packets[dir == PF_OUT]++;
1250 r->bytes[dir == PF_OUT] += pd->tot_len;
1253 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1254 pd->flags |= PFDESC_TCP_NORM;
1256 flags = th->th_flags;
1257 if (flags & TH_SYN) {
1258 /* Illegal packet */
1265 /* Illegal packet */
1266 if (!(flags & (TH_ACK|TH_RST)))
1270 if (!(flags & TH_ACK)) {
1271 /* These flags are only valid if ACK is set */
1272 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1276 /* Check for illegal header length */
1277 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1280 /* If flags changed, or reserved data set, then adjust */
1281 if (flags != th->th_flags || th->th_x2 != 0) {
1284 ov = *(u_int16_t *)(&th->th_ack + 1);
1285 th->th_flags = flags;
1287 nv = *(u_int16_t *)(&th->th_ack + 1);
1289 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1293 /* Remove urgent pointer, if TH_URG is not set */
1294 if (!(flags & TH_URG) && th->th_urp) {
1295 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1300 /* Process options */
1301 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off))
1304 /* copy back packet headers if we sanitized */
1306 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1311 REASON_SET(&reason, PFRES_NORM);
1312 if (rm != NULL && r->log)
1313 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL, pd);
1318 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1319 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1321 u_int32_t tsval, tsecr;
1325 KASSERT((src->scrub == NULL),
1326 ("pf_normalize_tcp_init: src->scrub != NULL"));
1328 src->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
1329 if (src->scrub == NULL)
1331 bzero(src->scrub, sizeof(*src->scrub));
1336 struct ip *h = mtod(m, struct ip *);
1337 src->scrub->pfss_ttl = h->ip_ttl;
1343 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1344 src->scrub->pfss_ttl = h->ip6_hlim;
1352 * All normalizations below are only begun if we see the start of
1353 * the connections. They must all set an enabled bit in pfss_flags
1355 if ((th->th_flags & TH_SYN) == 0)
1359 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1360 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1361 /* Diddle with TCP options */
1363 opt = hdr + sizeof(struct tcphdr);
1364 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1365 while (hlen >= TCPOLEN_TIMESTAMP) {
1367 case TCPOPT_EOL: /* FALLTHROUGH */
1372 case TCPOPT_TIMESTAMP:
1373 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1374 src->scrub->pfss_flags |=
1376 src->scrub->pfss_ts_mod = karc4random();
1378 /* note PFSS_PAWS not set yet */
1379 memcpy(&tsval, &opt[2],
1381 memcpy(&tsecr, &opt[6],
1383 src->scrub->pfss_tsval0 = ntohl(tsval);
1384 src->scrub->pfss_tsval = ntohl(tsval);
1385 src->scrub->pfss_tsecr = ntohl(tsecr);
1386 getmicrouptime(&src->scrub->pfss_last);
1390 hlen -= MAX(opt[1], 2);
1391 opt += MAX(opt[1], 2);
1401 pf_normalize_tcp_cleanup(struct pf_state *state)
1403 if (state->src.scrub)
1404 pool_put(&pf_state_scrub_pl, state->src.scrub);
1405 if (state->dst.scrub)
1406 pool_put(&pf_state_scrub_pl, state->dst.scrub);
1408 /* Someday... flush the TCP segment reassembly descriptors. */
1412 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1413 u_short *reason, struct tcphdr *th, struct pf_state *state,
1414 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1416 struct timeval uptime;
1417 u_int32_t tsval, tsecr;
1418 u_int tsval_from_last;
1424 KASSERT((src->scrub || dst->scrub),
1425 ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1428 * Enforce the minimum TTL seen for this connection. Negate a common
1429 * technique to evade an intrusion detection system and confuse
1430 * firewall state code.
1436 struct ip *h = mtod(m, struct ip *);
1437 if (h->ip_ttl > src->scrub->pfss_ttl)
1438 src->scrub->pfss_ttl = h->ip_ttl;
1439 h->ip_ttl = src->scrub->pfss_ttl;
1447 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1448 if (h->ip6_hlim > src->scrub->pfss_ttl)
1449 src->scrub->pfss_ttl = h->ip6_hlim;
1450 h->ip6_hlim = src->scrub->pfss_ttl;
1457 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1458 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1459 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1460 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1461 /* Diddle with TCP options */
1463 opt = hdr + sizeof(struct tcphdr);
1464 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1465 while (hlen >= TCPOLEN_TIMESTAMP) {
1467 case TCPOPT_EOL: /* FALLTHROUGH */
1472 case TCPOPT_TIMESTAMP:
1473 /* Modulate the timestamps. Can be used for
1474 * NAT detection, OS uptime determination or
1479 /* Huh? Multiple timestamps!? */
1480 if (pf_status.debug >= PF_DEBUG_MISC) {
1481 DPFPRINTF(("multiple TS??"));
1482 pf_print_state(state);
1485 REASON_SET(reason, PFRES_TS);
1488 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1489 memcpy(&tsval, &opt[2],
1491 if (tsval && src->scrub &&
1492 (src->scrub->pfss_flags &
1494 tsval = ntohl(tsval);
1495 pf_change_a(&opt[2],
1498 src->scrub->pfss_ts_mod),
1503 /* Modulate TS reply iff valid (!0) */
1504 memcpy(&tsecr, &opt[6],
1506 if (tsecr && dst->scrub &&
1507 (dst->scrub->pfss_flags &
1509 tsecr = ntohl(tsecr)
1510 - dst->scrub->pfss_ts_mod;
1511 pf_change_a(&opt[6],
1512 &th->th_sum, htonl(tsecr),
1520 hlen -= MAX(opt[1], 2);
1521 opt += MAX(opt[1], 2);
1526 /* Copyback the options, caller copys back header */
1528 m_copyback(m, off + sizeof(struct tcphdr),
1529 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1530 sizeof(struct tcphdr));
1536 * Must invalidate PAWS checks on connections idle for too long.
1537 * The fastest allowed timestamp clock is 1ms. That turns out to
1538 * be about 24 days before it wraps. XXX Right now our lowerbound
1539 * TS echo check only works for the first 12 days of a connection
1540 * when the TS has exhausted half its 32bit space
1542 #define TS_MAX_IDLE (24*24*60*60)
1543 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1545 getmicrouptime(&uptime);
1546 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1547 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1548 time_second - state->creation > TS_MAX_CONN)) {
1549 if (pf_status.debug >= PF_DEBUG_MISC) {
1550 DPFPRINTF(("src idled out of PAWS\n"));
1551 pf_print_state(state);
1554 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1557 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1558 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1559 if (pf_status.debug >= PF_DEBUG_MISC) {
1560 DPFPRINTF(("dst idled out of PAWS\n"));
1561 pf_print_state(state);
1564 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1568 if (got_ts && src->scrub && dst->scrub &&
1569 (src->scrub->pfss_flags & PFSS_PAWS) &&
1570 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1571 /* Validate that the timestamps are "in-window".
1572 * RFC1323 describes TCP Timestamp options that allow
1573 * measurement of RTT (round trip time) and PAWS
1574 * (protection against wrapped sequence numbers). PAWS
1575 * gives us a set of rules for rejecting packets on
1576 * long fat pipes (packets that were somehow delayed
1577 * in transit longer than the time it took to send the
1578 * full TCP sequence space of 4Gb). We can use these
1579 * rules and infer a few others that will let us treat
1580 * the 32bit timestamp and the 32bit echoed timestamp
1581 * as sequence numbers to prevent a blind attacker from
1582 * inserting packets into a connection.
1585 * - The timestamp on this packet must be greater than
1586 * or equal to the last value echoed by the other
1587 * endpoint. The RFC says those will be discarded
1588 * since it is a dup that has already been acked.
1589 * This gives us a lowerbound on the timestamp.
1590 * timestamp >= other last echoed timestamp
1591 * - The timestamp will be less than or equal to
1592 * the last timestamp plus the time between the
1593 * last packet and now. The RFC defines the max
1594 * clock rate as 1ms. We will allow clocks to be
1595 * up to 10% fast and will allow a total difference
1596 * or 30 seconds due to a route change. And this
1597 * gives us an upperbound on the timestamp.
1598 * timestamp <= last timestamp + max ticks
1599 * We have to be careful here. Windows will send an
1600 * initial timestamp of zero and then initialize it
1601 * to a random value after the 3whs; presumably to
1602 * avoid a DoS by having to call an expensive RNG
1603 * during a SYN flood. Proof MS has at least one
1604 * good security geek.
1606 * - The TCP timestamp option must also echo the other
1607 * endpoints timestamp. The timestamp echoed is the
1608 * one carried on the earliest unacknowledged segment
1609 * on the left edge of the sequence window. The RFC
1610 * states that the host will reject any echoed
1611 * timestamps that were larger than any ever sent.
1612 * This gives us an upperbound on the TS echo.
1613 * tescr <= largest_tsval
1614 * - The lowerbound on the TS echo is a little more
1615 * tricky to determine. The other endpoint's echoed
1616 * values will not decrease. But there may be
1617 * network conditions that re-order packets and
1618 * cause our view of them to decrease. For now the
1619 * only lowerbound we can safely determine is that
1620 * the TS echo will never be less than the original
1621 * TS. XXX There is probably a better lowerbound.
1622 * Remove TS_MAX_CONN with better lowerbound check.
1623 * tescr >= other original TS
1625 * It is also important to note that the fastest
1626 * timestamp clock of 1ms will wrap its 32bit space in
1627 * 24 days. So we just disable TS checking after 24
1628 * days of idle time. We actually must use a 12d
1629 * connection limit until we can come up with a better
1630 * lowerbound to the TS echo check.
1632 struct timeval delta_ts;
1637 * PFTM_TS_DIFF is how many seconds of leeway to allow
1638 * a host's timestamp. This can happen if the previous
1639 * packet got delayed in transit for much longer than
1642 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1643 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1646 /* Calculate max ticks since the last timestamp */
1647 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1648 #define TS_MICROSECS 1000000 /* microseconds per second */
1650 #define timersub(tvp, uvp, vvp) \
1652 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
1653 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
1654 if ((vvp)->tv_usec < 0) { \
1656 (vvp)->tv_usec += 1000000; \
1661 timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1662 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1663 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1666 if ((src->state >= TCPS_ESTABLISHED &&
1667 dst->state >= TCPS_ESTABLISHED) &&
1668 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1669 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1670 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1671 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1672 /* Bad RFC1323 implementation or an insertion attack.
1674 * - Solaris 2.6 and 2.7 are known to send another ACK
1675 * after the FIN,FIN|ACK,ACK closing that carries
1679 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1680 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1681 SEQ_GT(tsval, src->scrub->pfss_tsval +
1682 tsval_from_last) ? '1' : ' ',
1683 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1684 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1685 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1686 "idle: %lus %lums\n",
1687 tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
1688 delta_ts.tv_usec / 1000));
1689 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1690 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1691 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1692 "\n", dst->scrub->pfss_tsval,
1693 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1694 if (pf_status.debug >= PF_DEBUG_MISC) {
1695 pf_print_state(state);
1696 pf_print_flags(th->th_flags);
1699 REASON_SET(reason, PFRES_TS);
1703 /* XXX I'd really like to require tsecr but it's optional */
1705 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1706 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1707 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1708 src->scrub && dst->scrub &&
1709 (src->scrub->pfss_flags & PFSS_PAWS) &&
1710 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1711 /* Didn't send a timestamp. Timestamps aren't really useful
1713 * - connection opening or closing (often not even sent).
1714 * but we must not let an attacker to put a FIN on a
1715 * data packet to sneak it through our ESTABLISHED check.
1716 * - on a TCP reset. RFC suggests not even looking at TS.
1717 * - on an empty ACK. The TS will not be echoed so it will
1718 * probably not help keep the RTT calculation in sync and
1719 * there isn't as much danger when the sequence numbers
1720 * got wrapped. So some stacks don't include TS on empty
1723 * To minimize the disruption to mostly RFC1323 conformant
1724 * stacks, we will only require timestamps on data packets.
1726 * And what do ya know, we cannot require timestamps on data
1727 * packets. There appear to be devices that do legitimate
1728 * TCP connection hijacking. There are HTTP devices that allow
1729 * a 3whs (with timestamps) and then buffer the HTTP request.
1730 * If the intermediate device has the HTTP response cache, it
1731 * will spoof the response but not bother timestamping its
1732 * packets. So we can look for the presence of a timestamp in
1733 * the first data packet and if there, require it in all future
1737 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1739 * Hey! Someone tried to sneak a packet in. Or the
1740 * stack changed its RFC1323 behavior?!?!
1742 if (pf_status.debug >= PF_DEBUG_MISC) {
1743 DPFPRINTF(("Did not receive expected RFC1323 "
1745 pf_print_state(state);
1746 pf_print_flags(th->th_flags);
1749 REASON_SET(reason, PFRES_TS);
1756 * We will note if a host sends his data packets with or without
1757 * timestamps. And require all data packets to contain a timestamp
1758 * if the first does. PAWS implicitly requires that all data packets be
1759 * timestamped. But I think there are middle-man devices that hijack
1760 * TCP streams immediately after the 3whs and don't timestamp their
1761 * packets (seen in a WWW accelerator or cache).
1763 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1764 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1766 src->scrub->pfss_flags |= PFSS_DATA_TS;
1768 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1769 if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1770 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1771 /* Don't warn if other host rejected RFC1323 */
1772 DPFPRINTF(("Broken RFC1323 stack did not "
1773 "timestamp data packet. Disabled PAWS "
1775 pf_print_state(state);
1776 pf_print_flags(th->th_flags);
1784 * Update PAWS values
1786 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1787 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1788 getmicrouptime(&src->scrub->pfss_last);
1789 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1790 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1791 src->scrub->pfss_tsval = tsval;
1794 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1795 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1796 src->scrub->pfss_tsecr = tsecr;
1798 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1799 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1800 src->scrub->pfss_tsval0 == 0)) {
1801 /* tsval0 MUST be the lowest timestamp */
1802 src->scrub->pfss_tsval0 = tsval;
1805 /* Only fully initialized after a TS gets echoed */
1806 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1807 src->scrub->pfss_flags |= PFSS_PAWS;
1811 /* I have a dream.... TCP segment reassembly.... */
1816 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1821 int opt, cnt, optlen = 0;
1825 thoff = th->th_off << 2;
1826 cnt = thoff - sizeof(struct tcphdr);
1827 optp = mtod(m, caddr_t) + off + sizeof(struct tcphdr);
1829 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1831 if (opt == TCPOPT_EOL)
1833 if (opt == TCPOPT_NOP)
1839 if (optlen < 2 || optlen > cnt)
1844 mss = (u_int16_t *)(optp + 2);
1845 if ((ntohs(*mss)) > r->max_mss) {
1846 th->th_sum = pf_cksum_fixup(th->th_sum,
1847 *mss, htons(r->max_mss), 0);
1848 *mss = htons(r->max_mss);