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_var.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[MAXCPU];
72 TAILQ_HEAD(pf_cachequeue, pf_fragment) pf_cachequeue[MAXCPU];
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[MAXCPU],
77 pf_cache_tree[MAXCPU];
78 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
79 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
81 /* Private prototypes */
82 void pf_ip2key(struct pf_fragment *, struct ip *);
83 void pf_remove_fragment(struct pf_fragment *);
84 void pf_flush_fragments(void);
85 void pf_free_fragment(struct pf_fragment *);
86 struct pf_fragment *pf_find_fragment(struct ip *, struct pf_frag_tree *);
87 struct mbuf *pf_reassemble(struct mbuf **, struct pf_fragment **,
88 struct pf_frent *, int);
89 struct mbuf *pf_fragcache(struct mbuf **, struct ip*,
90 struct pf_fragment **, int, int, int *);
91 int pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
92 struct tcphdr *, int, sa_family_t);
94 #define DPFPRINTF(x) do { \
95 if (pf_status.debug >= PF_DEBUG_MISC) { \
96 kprintf("%s: ", __func__); \
101 static MALLOC_DEFINE(M_PFFRAGPL, "pffrag", "pf fragment pool list");
102 static MALLOC_DEFINE(M_PFCACHEPL, "pffrcache", "pf fragment cache pool list");
103 static MALLOC_DEFINE(M_PFFRENTPL, "pffrent", "pf frent pool list");
104 static MALLOC_DEFINE(M_PFCENTPL, "pffrcent", "pf fragment cent pool list");
105 static MALLOC_DEFINE(M_PFSTATESCRUBPL, "pfstatescrub", "pf state scrub pool list");
108 struct malloc_type *pf_frent_pl, *pf_frag_pl, *pf_cache_pl, *pf_cent_pl;
109 struct malloc_type *pf_state_scrub_pl;
110 int pf_nfrents, pf_ncache;
113 pf_normalize_init(void)
118 pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
119 pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
120 pool_sethardlimit(&pf_cache_pl, PFFRAG_FRCACHE_HIWAT, NULL, 0);
121 pool_sethardlimit(&pf_cent_pl, PFFRAG_FRCENT_HIWAT, NULL, 0);
124 for (n = 0; n < MAXCPU; ++n) {
125 TAILQ_INIT(&pf_fragqueue[n]);
126 TAILQ_INIT(&pf_cachequeue[n]);
127 RB_INIT(&pf_frag_tree[n]);
128 RB_INIT(&pf_cache_tree[n]);
133 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
137 if ((diff = a->fr_id - b->fr_id))
139 else if ((diff = a->fr_p - b->fr_p))
141 else if (a->fr_src.s_addr < b->fr_src.s_addr)
143 else if (a->fr_src.s_addr > b->fr_src.s_addr)
145 else if (a->fr_dst.s_addr < b->fr_dst.s_addr)
147 else if (a->fr_dst.s_addr > b->fr_dst.s_addr)
153 pf_purge_expired_fragments(void)
155 struct pf_fragment *frag;
157 int cpu = mycpu->gd_cpuid;
159 expire = time_second - pf_default_rule.timeout[PFTM_FRAG];
161 while ((frag = TAILQ_LAST(&pf_fragqueue[cpu], pf_fragqueue)) != 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);
171 while ((frag = TAILQ_LAST(&pf_cachequeue[cpu], pf_cachequeue)) != NULL) {
172 KASSERT((!BUFFER_FRAGMENTS(frag)),
173 ("BUFFER_FRAGMENTS(frag) != 0: %s", __func__));
174 if (frag->fr_timeout > expire)
177 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
178 pf_free_fragment(frag);
179 KASSERT((TAILQ_EMPTY(&pf_cachequeue[cpu]) ||
180 TAILQ_LAST(&pf_cachequeue[cpu], pf_cachequeue) != frag),
181 ("!(TAILQ_EMPTY() || TAILQ_LAST() == farg): %s",
187 * Try to flush old fragments to make space for new ones
191 pf_flush_fragments(void)
193 struct pf_fragment *frag;
195 int cpu = mycpu->gd_cpuid;
197 goal = pf_nfrents * 9 / 10;
198 DPFPRINTF(("trying to free > %d frents\n",
200 while (goal < pf_nfrents) {
201 frag = TAILQ_LAST(&pf_fragqueue[cpu], pf_fragqueue);
204 pf_free_fragment(frag);
208 goal = pf_ncache * 9 / 10;
209 DPFPRINTF(("trying to free > %d cache entries\n",
211 while (goal < pf_ncache) {
212 frag = TAILQ_LAST(&pf_cachequeue[cpu], pf_cachequeue);
215 pf_free_fragment(frag);
219 /* Frees the fragments and all associated entries */
222 pf_free_fragment(struct pf_fragment *frag)
224 struct pf_frent *frent;
225 struct pf_frcache *frcache;
227 /* Free all fragments */
228 if (BUFFER_FRAGMENTS(frag)) {
229 for (frent = LIST_FIRST(&frag->fr_queue); frent;
230 frent = LIST_FIRST(&frag->fr_queue)) {
231 LIST_REMOVE(frent, fr_next);
233 m_freem(frent->fr_m);
234 kfree(frent, M_PFFRENTPL);
238 for (frcache = LIST_FIRST(&frag->fr_cache); frcache;
239 frcache = LIST_FIRST(&frag->fr_cache)) {
240 LIST_REMOVE(frcache, fr_next);
242 KASSERT((LIST_EMPTY(&frag->fr_cache) ||
243 LIST_FIRST(&frag->fr_cache)->fr_off >
245 ("! (LIST_EMPTY() || LIST_FIRST()->fr_off >"
246 " frcache->fr_end): %s", __func__));
248 kfree(frcache, M_PFCENTPL);
253 pf_remove_fragment(frag);
257 pf_ip2key(struct pf_fragment *key, struct ip *ip)
259 key->fr_p = ip->ip_p;
260 key->fr_id = ip->ip_id;
261 key->fr_src.s_addr = ip->ip_src.s_addr;
262 key->fr_dst.s_addr = ip->ip_dst.s_addr;
266 pf_find_fragment(struct ip *ip, struct pf_frag_tree *tree)
268 struct pf_fragment key;
269 struct pf_fragment *frag;
270 int cpu = mycpu->gd_cpuid;
274 frag = RB_FIND(pf_frag_tree, tree, &key);
276 /* XXX Are we sure we want to update the timeout? */
277 frag->fr_timeout = time_second;
278 if (BUFFER_FRAGMENTS(frag)) {
279 TAILQ_REMOVE(&pf_fragqueue[cpu], frag, frag_next);
280 TAILQ_INSERT_HEAD(&pf_fragqueue[cpu], frag, frag_next);
282 TAILQ_REMOVE(&pf_cachequeue[cpu], frag, frag_next);
283 TAILQ_INSERT_HEAD(&pf_cachequeue[cpu], frag, frag_next);
290 /* Removes a fragment from the fragment queue and frees the fragment */
293 pf_remove_fragment(struct pf_fragment *frag)
295 int cpu = mycpu->gd_cpuid;
297 if (BUFFER_FRAGMENTS(frag)) {
298 RB_REMOVE(pf_frag_tree, &pf_frag_tree[cpu], frag);
299 TAILQ_REMOVE(&pf_fragqueue[cpu], frag, frag_next);
300 kfree(frag, M_PFFRAGPL);
302 RB_REMOVE(pf_frag_tree, &pf_cache_tree[cpu], frag);
303 TAILQ_REMOVE(&pf_cachequeue[cpu], frag, frag_next);
304 kfree(frag, M_PFCACHEPL);
308 #define FR_IP_OFF(fr) (((fr)->fr_ip->ip_off & IP_OFFMASK) << 3)
310 pf_reassemble(struct mbuf **m0, struct pf_fragment **frag,
311 struct pf_frent *frent, int mff)
313 struct mbuf *m = *m0, *m2;
314 struct pf_frent *frea, *next;
315 struct pf_frent *frep = NULL;
316 struct ip *ip = frent->fr_ip;
317 int hlen = ip->ip_hl << 2;
318 u_int16_t off = (ip->ip_off & IP_OFFMASK) << 3;
319 u_int16_t ip_len = ip->ip_len - ip->ip_hl * 4;
320 u_int16_t max = ip_len + off;
321 int cpu = mycpu->gd_cpuid;
323 KASSERT((*frag == NULL || BUFFER_FRAGMENTS(*frag)),
324 ("! (*frag == NULL || BUFFER_FRAGMENTS(*frag)): %s", __func__));
326 /* Strip off ip header */
330 /* Create a new reassembly queue for this packet */
332 *frag = kmalloc(sizeof(struct pf_fragment), M_PFFRAGPL, M_NOWAIT);
334 pf_flush_fragments();
335 *frag = kmalloc(sizeof(struct pf_fragment), M_PFFRAGPL, M_NOWAIT);
340 (*frag)->fr_flags = 0;
342 (*frag)->fr_src = frent->fr_ip->ip_src;
343 (*frag)->fr_dst = frent->fr_ip->ip_dst;
344 (*frag)->fr_p = frent->fr_ip->ip_p;
345 (*frag)->fr_id = frent->fr_ip->ip_id;
346 (*frag)->fr_timeout = time_second;
347 LIST_INIT(&(*frag)->fr_queue);
349 RB_INSERT(pf_frag_tree, &pf_frag_tree[cpu], *frag);
350 TAILQ_INSERT_HEAD(&pf_fragqueue[cpu], *frag, frag_next);
352 /* We do not have a previous fragment */
358 * Find a fragment after the current one:
359 * - off contains the real shifted offset.
361 LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
362 if (FR_IP_OFF(frea) > off)
367 KASSERT((frep != NULL || frea != NULL),
368 ("!(frep != NULL || frea != NULL): %s", __func__));
371 FR_IP_OFF(frep) + frep->fr_ip->ip_len - frep->fr_ip->ip_hl *
376 precut = FR_IP_OFF(frep) + frep->fr_ip->ip_len -
377 frep->fr_ip->ip_hl * 4 - off;
378 if (precut >= ip_len)
380 m_adj(frent->fr_m, precut);
381 DPFPRINTF(("overlap -%d\n", precut));
382 /* Enforce 8 byte boundaries */
383 ip->ip_off = ip->ip_off + (precut >> 3);
384 off = (ip->ip_off & IP_OFFMASK) << 3;
389 for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
394 aftercut = ip_len + off - FR_IP_OFF(frea);
395 DPFPRINTF(("adjust overlap %d\n", aftercut));
396 if (aftercut < frea->fr_ip->ip_len - frea->fr_ip->ip_hl
399 frea->fr_ip->ip_len =
400 frea->fr_ip->ip_len - aftercut;
401 frea->fr_ip->ip_off = frea->fr_ip->ip_off +
403 m_adj(frea->fr_m, aftercut);
407 /* This fragment is completely overlapped, lose it */
408 next = LIST_NEXT(frea, fr_next);
410 LIST_REMOVE(frea, fr_next);
411 kfree(frea, M_PFFRENTPL);
416 /* Update maximum data size */
417 if ((*frag)->fr_max < max)
418 (*frag)->fr_max = max;
419 /* This is the last segment */
421 (*frag)->fr_flags |= PFFRAG_SEENLAST;
424 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
426 LIST_INSERT_AFTER(frep, frent, fr_next);
428 /* Check if we are completely reassembled */
429 if (!((*frag)->fr_flags & PFFRAG_SEENLAST))
432 /* Check if we have all the data */
434 for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
435 next = LIST_NEXT(frep, fr_next);
437 off += frep->fr_ip->ip_len - frep->fr_ip->ip_hl * 4;
438 if (off < (*frag)->fr_max &&
439 (next == NULL || FR_IP_OFF(next) != off))
441 DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
442 off, next == NULL ? -1 : FR_IP_OFF(next),
447 DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
448 if (off < (*frag)->fr_max)
451 /* We have all the data */
452 frent = LIST_FIRST(&(*frag)->fr_queue);
453 KASSERT((frent != NULL), ("frent == NULL: %s", __func__));
454 if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
455 DPFPRINTF(("drop: too big: %d\n", off));
456 pf_free_fragment(*frag);
460 next = LIST_NEXT(frent, fr_next);
462 /* Magic from ip_input */
468 kfree(frent, M_PFFRENTPL);
470 for (frent = next; frent != NULL; frent = next) {
471 next = LIST_NEXT(frent, fr_next);
474 kfree(frent, M_PFFRENTPL);
479 ip->ip_src = (*frag)->fr_src;
480 ip->ip_dst = (*frag)->fr_dst;
482 /* Remove from fragment queue */
483 pf_remove_fragment(*frag);
486 hlen = ip->ip_hl << 2;
487 ip->ip_len = off + hlen;
491 /* some debugging cruft by sklower, below, will go away soon */
492 /* XXX this should be done elsewhere */
493 if (m->m_flags & M_PKTHDR) {
495 for (m2 = m; m2; m2 = m2->m_next)
497 m->m_pkthdr.len = plen;
500 DPFPRINTF(("complete: %p(%d)\n", m, ip->ip_len));
504 /* Oops - fail safe - drop packet */
505 kfree(frent, M_PFFRENTPL);
512 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
513 int drop, int *nomem)
515 struct mbuf *m = *m0;
516 struct pf_frcache *frp, *fra, *cur = NULL;
517 int ip_len = h->ip_len - (h->ip_hl << 2);
518 u_int16_t off = h->ip_off << 3;
519 u_int16_t max = ip_len + off;
521 int cpu = mycpu->gd_cpuid;
523 KASSERT((*frag == NULL || !BUFFER_FRAGMENTS(*frag)),
524 ("!(*frag == NULL || !BUFFER_FRAGMENTS(*frag)): %s", __func__));
526 /* Create a new range queue for this packet */
528 *frag = kmalloc(sizeof(struct pf_fragment), M_PFCACHEPL, M_NOWAIT);
530 pf_flush_fragments();
531 *frag = kmalloc(sizeof(struct pf_fragment), M_PFCACHEPL, M_NOWAIT);
536 /* Get an entry for the queue */
537 cur = kmalloc(sizeof(struct pf_frcache), M_PFCENTPL, M_NOWAIT);
539 kfree(*frag, M_PFCACHEPL);
545 (*frag)->fr_flags = PFFRAG_NOBUFFER;
547 (*frag)->fr_src = h->ip_src;
548 (*frag)->fr_dst = h->ip_dst;
549 (*frag)->fr_p = h->ip_p;
550 (*frag)->fr_id = h->ip_id;
551 (*frag)->fr_timeout = time_second;
555 LIST_INIT(&(*frag)->fr_cache);
556 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
558 RB_INSERT(pf_frag_tree, &pf_cache_tree[cpu], *frag);
559 TAILQ_INSERT_HEAD(&pf_cachequeue[cpu], *frag, frag_next);
561 DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off, max));
567 * Find a fragment after the current one:
568 * - off contains the real shifted offset.
571 LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
572 if (fra->fr_off > off)
577 KASSERT((frp != NULL || fra != NULL),
578 ("!(frp != NULL || fra != NULL): %s", __func__));
583 precut = frp->fr_end - off;
584 if (precut >= ip_len) {
585 /* Fragment is entirely a duplicate */
586 DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
587 h->ip_id, frp->fr_off, frp->fr_end, off, max));
591 /* They are adjacent. Fixup cache entry */
592 DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
593 h->ip_id, frp->fr_off, frp->fr_end, off, max));
595 } else if (precut > 0) {
596 /* The first part of this payload overlaps with a
597 * fragment that has already been passed.
598 * Need to trim off the first part of the payload.
599 * But to do so easily, we need to create another
600 * mbuf to throw the original header into.
603 DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
604 h->ip_id, precut, frp->fr_off, frp->fr_end, off,
609 /* Update the previous frag to encompass this one */
613 /* XXX Optimization opportunity
614 * This is a very heavy way to trim the payload.
615 * we could do it much faster by diddling mbuf
616 * internals but that would be even less legible
617 * than this mbuf magic. For my next trick,
618 * I'll pull a rabbit out of my laptop.
620 *m0 = m_dup(m, M_NOWAIT);
621 /* From KAME Project : We have missed this! */
622 m_adj(*m0, (h->ip_hl << 2) -
623 (*m0)->m_pkthdr.len);
626 KASSERT(((*m0)->m_next == NULL),
627 ("(*m0)->m_next != NULL: %s",
629 m_adj(m, precut + (h->ip_hl << 2));
632 if (m->m_flags & M_PKTHDR) {
635 for (t = m; t; t = t->m_next)
637 m->m_pkthdr.len = plen;
641 h = mtod(m, struct ip *);
643 KASSERT(((int)m->m_len ==
645 ("m->m_len != h->ip_len - precut: %s",
647 h->ip_off = h->ip_off +
649 h->ip_len = h->ip_len - precut;
654 /* There is a gap between fragments */
656 DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
657 h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
660 cur = kmalloc(sizeof(struct pf_frcache), M_PFCENTPL, M_NOWAIT);
667 LIST_INSERT_AFTER(frp, cur, fr_next);
675 aftercut = max - fra->fr_off;
677 /* Adjacent fragments */
678 DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
679 h->ip_id, off, max, fra->fr_off, fra->fr_end));
682 } else if (aftercut > 0) {
683 /* Need to chop off the tail of this fragment */
684 DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
685 h->ip_id, aftercut, off, max, fra->fr_off,
694 if (m->m_flags & M_PKTHDR) {
697 for (t = m; t; t = t->m_next)
699 m->m_pkthdr.len = plen;
701 h = mtod(m, struct ip *);
702 KASSERT(((int)m->m_len == h->ip_len - aftercut),
703 ("m->m_len != h->ip_len - aftercut: %s",
705 h->ip_len = h->ip_len - aftercut;
709 } else if (frp == NULL) {
710 /* There is a gap between fragments */
711 DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
712 h->ip_id, -aftercut, off, max, fra->fr_off,
715 cur = kmalloc(sizeof(struct pf_frcache), M_PFCENTPL, M_NOWAIT);
722 LIST_INSERT_BEFORE(fra, cur, fr_next);
726 /* Need to glue together two separate fragment descriptors */
728 if (cur && fra->fr_off <= cur->fr_end) {
729 /* Need to merge in a previous 'cur' */
730 DPFPRINTF(("fragcache[%d]: adjacent(merge "
731 "%d-%d) %d-%d (%d-%d)\n",
732 h->ip_id, cur->fr_off, cur->fr_end, off,
733 max, fra->fr_off, fra->fr_end));
734 fra->fr_off = cur->fr_off;
735 LIST_REMOVE(cur, fr_next);
736 kfree(cur, M_PFCENTPL);
740 } else if (frp && fra->fr_off <= frp->fr_end) {
741 /* Need to merge in a modified 'frp' */
742 KASSERT((cur == NULL), ("cur != NULL: %s",
744 DPFPRINTF(("fragcache[%d]: adjacent(merge "
745 "%d-%d) %d-%d (%d-%d)\n",
746 h->ip_id, frp->fr_off, frp->fr_end, off,
747 max, fra->fr_off, fra->fr_end));
748 fra->fr_off = frp->fr_off;
749 LIST_REMOVE(frp, fr_next);
750 kfree(frp, M_PFCENTPL);
760 * We must keep tracking the overall fragment even when
761 * we're going to drop it anyway so that we know when to
762 * free the overall descriptor. Thus we drop the frag late.
769 /* Update maximum data size */
770 if ((*frag)->fr_max < max)
771 (*frag)->fr_max = max;
773 /* This is the last segment */
775 (*frag)->fr_flags |= PFFRAG_SEENLAST;
777 /* Check if we are completely reassembled */
778 if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
779 LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
780 LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
781 /* Remove from fragment queue */
782 DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
784 pf_free_fragment(*frag);
793 /* Still need to pay attention to !IP_MF */
794 if (!mff && *frag != NULL)
795 (*frag)->fr_flags |= PFFRAG_SEENLAST;
802 /* Still need to pay attention to !IP_MF */
803 if (!mff && *frag != NULL)
804 (*frag)->fr_flags |= PFFRAG_SEENLAST;
807 /* This fragment has been deemed bad. Don't reass */
808 if (((*frag)->fr_flags & PFFRAG_DROP) == 0)
809 DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
811 (*frag)->fr_flags |= PFFRAG_DROP;
819 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
822 struct mbuf *m = *m0;
824 struct pf_frent *frent;
825 struct pf_fragment *frag = NULL;
826 struct ip *h = mtod(m, struct ip *);
827 int mff = (h->ip_off & IP_MF);
828 int hlen = h->ip_hl << 2;
829 u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;
833 int cpu = mycpu->gd_cpuid;
835 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
838 if (pfi_kif_match(r->kif, kif) == r->ifnot)
839 r = r->skip[PF_SKIP_IFP].ptr;
840 else if (r->direction && r->direction != dir)
841 r = r->skip[PF_SKIP_DIR].ptr;
842 else if (r->af && r->af != AF_INET)
843 r = r->skip[PF_SKIP_AF].ptr;
844 else if (r->proto && r->proto != h->ip_p)
845 r = r->skip[PF_SKIP_PROTO].ptr;
846 else if (PF_MISMATCHAW(&r->src.addr,
847 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
849 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
850 else if (PF_MISMATCHAW(&r->dst.addr,
851 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
853 r = r->skip[PF_SKIP_DST_ADDR].ptr;
854 else if (r->match_tag && !pf_match_tag(m, r, &tag))
855 r = TAILQ_NEXT(r, entries);
860 if (r == NULL || r->action == PF_NOSCRUB)
863 r->packets[dir == PF_OUT]++;
864 r->bytes[dir == PF_OUT] += pd->tot_len;
867 /* Check for illegal packets */
868 if (hlen < (int)sizeof(struct ip))
871 if (hlen > h->ip_len)
874 /* Clear IP_DF if the rule uses the no-df option */
875 if (r->rule_flag & PFRULE_NODF && h->ip_off & IP_DF) {
876 u_int16_t ip_off = h->ip_off;
879 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
882 /* We will need other tests here */
883 if (!fragoff && !mff)
886 /* A fragment; rehash required. */
887 m->m_flags &= ~M_HASH;
889 /* We're dealing with a fragment now. Don't allow fragments
890 * with IP_DF to enter the cache. If the flag was cleared by
891 * no-df above, fine. Otherwise drop it.
893 if (h->ip_off & IP_DF) {
894 DPFPRINTF(("IP_DF\n"));
898 ip_len = h->ip_len - hlen;
900 /* All fragments are 8 byte aligned */
901 if (mff && (ip_len & 0x7)) {
902 DPFPRINTF(("mff and %d\n", ip_len));
906 /* Respect maximum length */
907 if (fragoff + ip_len > IP_MAXPACKET) {
908 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
911 max = fragoff + ip_len;
913 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
914 /* Fully buffer all of the fragments */
916 frag = pf_find_fragment(h, &pf_frag_tree[cpu]);
918 /* Check if we saw the last fragment already */
919 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
923 /* Get an entry for the fragment queue */
924 frent = kmalloc(sizeof(struct pf_frent), M_PFFRENTPL, M_NOWAIT);
926 REASON_SET(reason, PFRES_MEMORY);
933 /* Might return a completely reassembled mbuf, or NULL */
934 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
935 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
940 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
943 h = mtod(m, struct ip *);
945 /* non-buffering fragment cache (drops or masks overlaps) */
948 if (dir == PF_OUT && m->m_pkthdr.pf.flags & PF_TAG_FRAGCACHE) {
950 * Already passed the fragment cache in the
951 * input direction. If we continued, it would
952 * appear to be a dup and would be dropped.
957 frag = pf_find_fragment(h, &pf_cache_tree[cpu]);
959 /* Check if we saw the last fragment already */
960 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
961 max > frag->fr_max) {
962 if (r->rule_flag & PFRULE_FRAGDROP)
963 frag->fr_flags |= PFFRAG_DROP;
967 *m0 = m = pf_fragcache(m0, h, &frag, mff,
968 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
976 m->m_pkthdr.pf.flags |= PF_TAG_FRAGCACHE;
978 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
984 /* At this point, only IP_DF is allowed in ip_off */
985 if (h->ip_off & ~IP_DF) {
986 u_int16_t ip_off = h->ip_off;
989 h->ip_sum = pf_cksum_fixup(h->ip_sum, htons(ip_off), htons(h->ip_off), 0);
992 /* Enforce a minimum ttl, may cause endless packet loops */
993 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
994 u_int16_t ip_ttl = h->ip_ttl;
996 h->ip_ttl = r->min_ttl;
997 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1001 if (r->rule_flag & PFRULE_SET_TOS) {
1004 ov = *(u_int16_t *)h;
1005 h->ip_tos = r->set_tos;
1006 nv = *(u_int16_t *)h;
1008 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1011 if (r->rule_flag & PFRULE_RANDOMID) {
1012 u_int16_t ip_id = h->ip_id;
1014 h->ip_id = ip_randomid();
1015 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1017 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1018 pd->flags |= PFDESC_IP_REAS;
1023 /* Enforce a minimum ttl, may cause endless packet loops */
1024 if (r->min_ttl && h->ip_ttl < r->min_ttl) {
1025 u_int16_t ip_ttl = h->ip_ttl;
1027 h->ip_ttl = r->min_ttl;
1028 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1031 if (r->rule_flag & PFRULE_SET_TOS) {
1034 ov = *(u_int16_t *)h;
1035 h->ip_tos = r->set_tos;
1036 nv = *(u_int16_t *)h;
1038 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1040 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1041 pd->flags |= PFDESC_IP_REAS;
1045 REASON_SET(reason, PFRES_MEMORY);
1046 if (r != NULL && r->log)
1047 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1051 REASON_SET(reason, PFRES_NORM);
1052 if (r != NULL && r->log)
1053 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1057 DPFPRINTF(("dropping bad fragment\n"));
1059 /* Free associated fragments */
1061 pf_free_fragment(frag);
1063 REASON_SET(reason, PFRES_FRAG);
1064 if (r != NULL && r->log)
1065 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL, pd);
1072 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1073 u_short *reason, struct pf_pdesc *pd)
1075 struct mbuf *m = *m0;
1077 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1081 struct ip6_opt_jumbo jumbo;
1082 struct ip6_frag frag;
1083 u_int32_t jumbolen = 0, plen;
1084 u_int16_t fragoff = 0;
1090 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1093 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1094 r = r->skip[PF_SKIP_IFP].ptr;
1095 else if (r->direction && r->direction != dir)
1096 r = r->skip[PF_SKIP_DIR].ptr;
1097 else if (r->af && r->af != AF_INET6)
1098 r = r->skip[PF_SKIP_AF].ptr;
1099 #if 0 /* header chain! */
1100 else if (r->proto && r->proto != h->ip6_nxt)
1101 r = r->skip[PF_SKIP_PROTO].ptr;
1103 else if (PF_MISMATCHAW(&r->src.addr,
1104 (struct pf_addr *)&h->ip6_src, AF_INET6,
1106 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1107 else if (PF_MISMATCHAW(&r->dst.addr,
1108 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1110 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1115 if (r == NULL || r->action == PF_NOSCRUB)
1118 r->packets[dir == PF_OUT]++;
1119 r->bytes[dir == PF_OUT] += pd->tot_len;
1122 /* Check for illegal packets */
1123 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1126 off = sizeof(struct ip6_hdr);
1131 case IPPROTO_FRAGMENT:
1135 case IPPROTO_ROUTING:
1136 case IPPROTO_DSTOPTS:
1137 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1140 if (proto == IPPROTO_AH)
1141 off += (ext.ip6e_len + 2) * 4;
1143 off += (ext.ip6e_len + 1) * 8;
1144 proto = ext.ip6e_nxt;
1146 case IPPROTO_HOPOPTS:
1147 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1150 optend = off + (ext.ip6e_len + 1) * 8;
1151 ooff = off + sizeof(ext);
1153 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1154 sizeof(opt.ip6o_type), NULL, NULL,
1157 if (opt.ip6o_type == IP6OPT_PAD1) {
1161 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1162 NULL, NULL, AF_INET6))
1164 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1166 switch (opt.ip6o_type) {
1168 if (h->ip6_plen != 0)
1170 if (!pf_pull_hdr(m, ooff, &jumbo,
1171 sizeof(jumbo), NULL, NULL,
1174 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1176 jumbolen = ntohl(jumbolen);
1177 if (jumbolen <= IPV6_MAXPACKET)
1179 if (sizeof(struct ip6_hdr) + jumbolen !=
1186 ooff += sizeof(opt) + opt.ip6o_len;
1187 } while (ooff < optend);
1190 proto = ext.ip6e_nxt;
1196 } while (!terminal);
1198 /* jumbo payload option must be present, or plen > 0 */
1199 if (ntohs(h->ip6_plen) == 0)
1202 plen = ntohs(h->ip6_plen);
1205 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1208 /* Enforce a minimum ttl, may cause endless packet loops */
1209 if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1210 h->ip6_hlim = r->min_ttl;
1215 if (ntohs(h->ip6_plen) == 0 || jumbolen)
1217 plen = ntohs(h->ip6_plen);
1219 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1221 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1222 if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1225 /* do something about it */
1226 /* remember to set pd->flags |= PFDESC_IP_REAS */
1230 REASON_SET(reason, PFRES_SHORT);
1231 if (r != NULL && r->log)
1232 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1236 REASON_SET(reason, PFRES_NORM);
1237 if (r != NULL && r->log)
1238 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1242 REASON_SET(reason, PFRES_FRAG);
1243 if (r != NULL && r->log)
1244 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL, pd);
1250 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1251 int off, void *h, struct pf_pdesc *pd)
1253 struct pf_rule *r, *rm = NULL;
1254 struct tcphdr *th = pd->hdr.tcp;
1258 sa_family_t af = pd->af;
1260 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1263 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1264 r = r->skip[PF_SKIP_IFP].ptr;
1265 else if (r->direction && r->direction != dir)
1266 r = r->skip[PF_SKIP_DIR].ptr;
1267 else if (r->af && r->af != af)
1268 r = r->skip[PF_SKIP_AF].ptr;
1269 else if (r->proto && r->proto != pd->proto)
1270 r = r->skip[PF_SKIP_PROTO].ptr;
1271 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1273 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1274 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1275 r->src.port[0], r->src.port[1], th->th_sport))
1276 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1277 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1279 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1280 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1281 r->dst.port[0], r->dst.port[1], th->th_dport))
1282 r = r->skip[PF_SKIP_DST_PORT].ptr;
1283 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1284 pf_osfp_fingerprint(pd, m, off, th),
1286 r = TAILQ_NEXT(r, entries);
1293 if (rm == NULL || rm->action == PF_NOSCRUB)
1296 r->packets[dir == PF_OUT]++;
1297 r->bytes[dir == PF_OUT] += pd->tot_len;
1300 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1301 pd->flags |= PFDESC_TCP_NORM;
1303 flags = th->th_flags;
1304 if (flags & TH_SYN) {
1305 /* Illegal packet */
1312 /* Illegal packet */
1313 if (!(flags & (TH_ACK|TH_RST)))
1317 if (!(flags & TH_ACK)) {
1318 /* These flags are only valid if ACK is set */
1319 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1323 /* Check for illegal header length */
1324 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1327 /* If flags changed, or reserved data set, then adjust */
1328 if (flags != th->th_flags || th->th_x2 != 0) {
1331 ov = *(u_int16_t *)(&th->th_ack + 1);
1332 th->th_flags = flags;
1334 nv = *(u_int16_t *)(&th->th_ack + 1);
1336 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1340 /* Remove urgent pointer, if TH_URG is not set */
1341 if (!(flags & TH_URG) && th->th_urp) {
1342 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1347 /* Process options */
1348 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1351 /* copy back packet headers if we sanitized */
1353 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1358 REASON_SET(&reason, PFRES_NORM);
1359 if (rm != NULL && r->log)
1360 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL, pd);
1365 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1366 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1368 u_int32_t tsval, tsecr;
1372 KASSERT((src->scrub == NULL),
1373 ("pf_normalize_tcp_init: src->scrub != NULL"));
1375 src->scrub = kmalloc(sizeof(struct pf_state_scrub), M_PFSTATESCRUBPL,
1377 if (src->scrub == NULL)
1383 struct ip *h = mtod(m, struct ip *);
1384 src->scrub->pfss_ttl = h->ip_ttl;
1390 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1391 src->scrub->pfss_ttl = h->ip6_hlim;
1399 * All normalizations below are only begun if we see the start of
1400 * the connections. They must all set an enabled bit in pfss_flags
1402 if ((th->th_flags & TH_SYN) == 0)
1406 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1407 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1408 /* Diddle with TCP options */
1410 opt = hdr + sizeof(struct tcphdr);
1411 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1412 while (hlen >= TCPOLEN_TIMESTAMP) {
1414 case TCPOPT_EOL: /* FALLTHROUGH */
1419 case TCPOPT_TIMESTAMP:
1420 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1421 src->scrub->pfss_flags |=
1423 src->scrub->pfss_ts_mod = karc4random();
1425 /* note PFSS_PAWS not set yet */
1426 memcpy(&tsval, &opt[2],
1428 memcpy(&tsecr, &opt[6],
1430 src->scrub->pfss_tsval0 = ntohl(tsval);
1431 src->scrub->pfss_tsval = ntohl(tsval);
1432 src->scrub->pfss_tsecr = ntohl(tsecr);
1433 getmicrouptime(&src->scrub->pfss_last);
1437 hlen -= MAX(opt[1], 2);
1438 opt += MAX(opt[1], 2);
1448 pf_normalize_tcp_cleanup(struct pf_state *state)
1450 if (state->src.scrub)
1451 kfree(state->src.scrub, M_PFSTATESCRUBPL);
1452 if (state->dst.scrub)
1453 kfree(state->dst.scrub, M_PFSTATESCRUBPL);
1455 /* Someday... flush the TCP segment reassembly descriptors. */
1459 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1460 u_short *reason, struct tcphdr *th, struct pf_state *state,
1461 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1463 struct timeval uptime;
1464 u_int32_t tsval, tsecr;
1465 u_int tsval_from_last;
1471 KASSERT((src->scrub || dst->scrub),
1472 ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1474 tsval = 0; /* avoid gcc complaint */
1475 tsecr = 0; /* avoid gcc complaint */
1478 * Enforce the minimum TTL seen for this connection. Negate a common
1479 * technique to evade an intrusion detection system and confuse
1480 * firewall state code.
1486 struct ip *h = mtod(m, struct ip *);
1487 if (h->ip_ttl > src->scrub->pfss_ttl)
1488 src->scrub->pfss_ttl = h->ip_ttl;
1489 h->ip_ttl = src->scrub->pfss_ttl;
1497 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1498 if (h->ip6_hlim > src->scrub->pfss_ttl)
1499 src->scrub->pfss_ttl = h->ip6_hlim;
1500 h->ip6_hlim = src->scrub->pfss_ttl;
1507 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1508 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1509 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1510 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1511 /* Diddle with TCP options */
1513 opt = hdr + sizeof(struct tcphdr);
1514 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1515 while (hlen >= TCPOLEN_TIMESTAMP) {
1517 case TCPOPT_EOL: /* FALLTHROUGH */
1522 case TCPOPT_TIMESTAMP:
1523 /* Modulate the timestamps. Can be used for
1524 * NAT detection, OS uptime determination or
1529 /* Huh? Multiple timestamps!? */
1530 if (pf_status.debug >= PF_DEBUG_MISC) {
1531 DPFPRINTF(("multiple TS??"));
1532 pf_print_state(state);
1535 REASON_SET(reason, PFRES_TS);
1538 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1539 memcpy(&tsval, &opt[2],
1541 if (tsval && src->scrub &&
1542 (src->scrub->pfss_flags &
1544 tsval = ntohl(tsval);
1545 pf_change_a(&opt[2],
1548 src->scrub->pfss_ts_mod),
1553 /* Modulate TS reply iff valid (!0) */
1554 memcpy(&tsecr, &opt[6],
1556 if (tsecr && dst->scrub &&
1557 (dst->scrub->pfss_flags &
1559 tsecr = ntohl(tsecr)
1560 - dst->scrub->pfss_ts_mod;
1561 pf_change_a(&opt[6],
1562 &th->th_sum, htonl(tsecr),
1570 hlen -= MAX(opt[1], 2);
1571 opt += MAX(opt[1], 2);
1576 /* Copyback the options, caller copys back header */
1578 m_copyback(m, off + sizeof(struct tcphdr),
1579 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1580 sizeof(struct tcphdr));
1586 * Must invalidate PAWS checks on connections idle for too long.
1587 * The fastest allowed timestamp clock is 1ms. That turns out to
1588 * be about 24 days before it wraps. XXX Right now our lowerbound
1589 * TS echo check only works for the first 12 days of a connection
1590 * when the TS has exhausted half its 32bit space
1592 #define TS_MAX_IDLE (24*24*60*60)
1593 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1595 getmicrouptime(&uptime);
1596 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1597 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1598 time_second - state->creation > TS_MAX_CONN)) {
1599 if (pf_status.debug >= PF_DEBUG_MISC) {
1600 DPFPRINTF(("src idled out of PAWS\n"));
1601 pf_print_state(state);
1604 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1607 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1608 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1609 if (pf_status.debug >= PF_DEBUG_MISC) {
1610 DPFPRINTF(("dst idled out of PAWS\n"));
1611 pf_print_state(state);
1614 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1618 if (got_ts && src->scrub && dst->scrub &&
1619 (src->scrub->pfss_flags & PFSS_PAWS) &&
1620 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1621 /* Validate that the timestamps are "in-window".
1622 * RFC1323 describes TCP Timestamp options that allow
1623 * measurement of RTT (round trip time) and PAWS
1624 * (protection against wrapped sequence numbers). PAWS
1625 * gives us a set of rules for rejecting packets on
1626 * long fat pipes (packets that were somehow delayed
1627 * in transit longer than the time it took to send the
1628 * full TCP sequence space of 4Gb). We can use these
1629 * rules and infer a few others that will let us treat
1630 * the 32bit timestamp and the 32bit echoed timestamp
1631 * as sequence numbers to prevent a blind attacker from
1632 * inserting packets into a connection.
1635 * - The timestamp on this packet must be greater than
1636 * or equal to the last value echoed by the other
1637 * endpoint. The RFC says those will be discarded
1638 * since it is a dup that has already been acked.
1639 * This gives us a lowerbound on the timestamp.
1640 * timestamp >= other last echoed timestamp
1641 * - The timestamp will be less than or equal to
1642 * the last timestamp plus the time between the
1643 * last packet and now. The RFC defines the max
1644 * clock rate as 1ms. We will allow clocks to be
1645 * up to 10% fast and will allow a total difference
1646 * or 30 seconds due to a route change. And this
1647 * gives us an upperbound on the timestamp.
1648 * timestamp <= last timestamp + max ticks
1649 * We have to be careful here. Windows will send an
1650 * initial timestamp of zero and then initialize it
1651 * to a random value after the 3whs; presumably to
1652 * avoid a DoS by having to call an expensive RNG
1653 * during a SYN flood. Proof MS has at least one
1654 * good security geek.
1656 * - The TCP timestamp option must also echo the other
1657 * endpoints timestamp. The timestamp echoed is the
1658 * one carried on the earliest unacknowledged segment
1659 * on the left edge of the sequence window. The RFC
1660 * states that the host will reject any echoed
1661 * timestamps that were larger than any ever sent.
1662 * This gives us an upperbound on the TS echo.
1663 * tescr <= largest_tsval
1664 * - The lowerbound on the TS echo is a little more
1665 * tricky to determine. The other endpoint's echoed
1666 * values will not decrease. But there may be
1667 * network conditions that re-order packets and
1668 * cause our view of them to decrease. For now the
1669 * only lowerbound we can safely determine is that
1670 * the TS echo will never be less than the original
1671 * TS. XXX There is probably a better lowerbound.
1672 * Remove TS_MAX_CONN with better lowerbound check.
1673 * tescr >= other original TS
1675 * It is also important to note that the fastest
1676 * timestamp clock of 1ms will wrap its 32bit space in
1677 * 24 days. So we just disable TS checking after 24
1678 * days of idle time. We actually must use a 12d
1679 * connection limit until we can come up with a better
1680 * lowerbound to the TS echo check.
1682 struct timeval delta_ts;
1687 * PFTM_TS_DIFF is how many seconds of leeway to allow
1688 * a host's timestamp. This can happen if the previous
1689 * packet got delayed in transit for much longer than
1692 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1693 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1696 /* Calculate max ticks since the last timestamp */
1697 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1698 #define TS_MICROSECS 1000000 /* microseconds per second */
1700 #define timersub(tvp, uvp, vvp) \
1702 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
1703 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
1704 if ((vvp)->tv_usec < 0) { \
1706 (vvp)->tv_usec += 1000000; \
1711 timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1712 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1713 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1716 if ((src->state >= TCPS_ESTABLISHED &&
1717 dst->state >= TCPS_ESTABLISHED) &&
1718 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1719 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1720 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1721 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1722 /* Bad RFC1323 implementation or an insertion attack.
1724 * - Solaris 2.6 and 2.7 are known to send another ACK
1725 * after the FIN,FIN|ACK,ACK closing that carries
1729 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1730 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1731 SEQ_GT(tsval, src->scrub->pfss_tsval +
1732 tsval_from_last) ? '1' : ' ',
1733 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1734 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1735 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1736 "idle: %lus %lums\n",
1737 tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
1738 delta_ts.tv_usec / 1000));
1739 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1740 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1741 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1742 "\n", dst->scrub->pfss_tsval,
1743 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1744 if (pf_status.debug >= PF_DEBUG_MISC) {
1745 pf_print_state(state);
1746 pf_print_flags(th->th_flags);
1749 REASON_SET(reason, PFRES_TS);
1753 /* XXX I'd really like to require tsecr but it's optional */
1755 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1756 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1757 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1758 src->scrub && dst->scrub &&
1759 (src->scrub->pfss_flags & PFSS_PAWS) &&
1760 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1761 /* Didn't send a timestamp. Timestamps aren't really useful
1763 * - connection opening or closing (often not even sent).
1764 * but we must not let an attacker to put a FIN on a
1765 * data packet to sneak it through our ESTABLISHED check.
1766 * - on a TCP reset. RFC suggests not even looking at TS.
1767 * - on an empty ACK. The TS will not be echoed so it will
1768 * probably not help keep the RTT calculation in sync and
1769 * there isn't as much danger when the sequence numbers
1770 * got wrapped. So some stacks don't include TS on empty
1773 * To minimize the disruption to mostly RFC1323 conformant
1774 * stacks, we will only require timestamps on data packets.
1776 * And what do ya know, we cannot require timestamps on data
1777 * packets. There appear to be devices that do legitimate
1778 * TCP connection hijacking. There are HTTP devices that allow
1779 * a 3whs (with timestamps) and then buffer the HTTP request.
1780 * If the intermediate device has the HTTP response cache, it
1781 * will spoof the response but not bother timestamping its
1782 * packets. So we can look for the presence of a timestamp in
1783 * the first data packet and if there, require it in all future
1787 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1789 * Hey! Someone tried to sneak a packet in. Or the
1790 * stack changed its RFC1323 behavior?!?!
1792 if (pf_status.debug >= PF_DEBUG_MISC) {
1793 DPFPRINTF(("Did not receive expected RFC1323 "
1795 pf_print_state(state);
1796 pf_print_flags(th->th_flags);
1799 REASON_SET(reason, PFRES_TS);
1806 * We will note if a host sends his data packets with or without
1807 * timestamps. And require all data packets to contain a timestamp
1808 * if the first does. PAWS implicitly requires that all data packets be
1809 * timestamped. But I think there are middle-man devices that hijack
1810 * TCP streams immediately after the 3whs and don't timestamp their
1811 * packets (seen in a WWW accelerator or cache).
1813 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1814 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1816 src->scrub->pfss_flags |= PFSS_DATA_TS;
1818 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1819 if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1820 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1821 /* Don't warn if other host rejected RFC1323 */
1822 DPFPRINTF(("Broken RFC1323 stack did not "
1823 "timestamp data packet. Disabled PAWS "
1825 pf_print_state(state);
1826 pf_print_flags(th->th_flags);
1834 * Update PAWS values
1836 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1837 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1838 getmicrouptime(&src->scrub->pfss_last);
1839 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1840 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1841 src->scrub->pfss_tsval = tsval;
1844 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1845 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1846 src->scrub->pfss_tsecr = tsecr;
1848 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1849 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1850 src->scrub->pfss_tsval0 == 0)) {
1851 /* tsval0 MUST be the lowest timestamp */
1852 src->scrub->pfss_tsval0 = tsval;
1855 /* Only fully initialized after a TS gets echoed */
1856 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1857 src->scrub->pfss_flags |= PFSS_PAWS;
1861 /* I have a dream.... TCP segment reassembly.... */
1866 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1867 int off, sa_family_t af)
1871 int opt, cnt, optlen = 0;
1873 u_char opts[TCP_MAXOLEN];
1874 u_char *optp = opts;
1876 thoff = th->th_off << 2;
1877 cnt = thoff - sizeof(struct tcphdr);
1879 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1883 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1885 if (opt == TCPOPT_EOL)
1887 if (opt == TCPOPT_NOP)
1893 if (optlen < 2 || optlen > cnt)
1898 mss = (u_int16_t *)(optp + 2);
1899 if ((ntohs(*mss)) > r->max_mss) {
1900 th->th_sum = pf_cksum_fixup(th->th_sum,
1901 *mss, htons(r->max_mss), 0);
1902 *mss = htons(r->max_mss);
1912 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);