2 /* $OpenBSD: pf_norm.c,v 1.97 2004/09/21 16:59:12 aaron Exp $ */
5 * Copyright 2001 Niels Provos <provos@citi.umich.edu>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include "opt_inet6.h"
34 #define NPFLOG DEV_PFLOG
42 #include <sys/param.h>
43 #include <sys/systm.h>
45 #include <sys/filio.h>
46 #include <sys/fcntl.h>
47 #include <sys/socket.h>
48 #include <sys/kernel.h>
53 #include <dev/rndvar.h>
56 #include <net/if_types.h>
58 #include <net/route.h>
59 #include <net/if_pflog.h>
61 #include <netinet/in.h>
62 #include <netinet/in_var.h>
63 #include <netinet/in_systm.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_var.h>
66 #include <netinet/tcp.h>
67 #include <netinet/tcp_seq.h>
68 #include <netinet/udp.h>
69 #include <netinet/ip_icmp.h>
72 #include <netinet/ip6.h>
75 #include <net/pfvar.h>
81 LIST_ENTRY(pf_frent) fr_next;
87 LIST_ENTRY(pf_frcache) fr_next;
93 #define PFFRAG_SEENLAST 0x0001 /* Seen the last fragment for this */
94 #define PFFRAG_NOBUFFER 0x0002 /* Non-buffering fragment cache */
95 #define PFFRAG_DROP 0x0004 /* Drop all fragments */
96 #define BUFFER_FRAGMENTS(fr) (!((fr)->fr_flags & PFFRAG_NOBUFFER))
100 RB_ENTRY(pf_fragment) fr_entry;
101 TAILQ_ENTRY(pf_fragment) frag_next;
102 struct in_addr fr_src;
103 struct in_addr fr_dst;
104 u_int8_t fr_p; /* protocol of this fragment */
105 u_int8_t fr_flags; /* status flags */
106 u_int16_t fr_id; /* fragment id for reassemble */
107 u_int16_t fr_max; /* fragment data max */
108 u_int32_t fr_timeout;
109 #define fr_queue fr_u.fru_queue
110 #define fr_cache fr_u.fru_cache
112 LIST_HEAD(pf_fragq, pf_frent) fru_queue; /* buffering */
113 LIST_HEAD(pf_cacheq, pf_frcache) fru_cache; /* non-buf */
118 TAILQ_HEAD(pf_fragqueue, pf_fragment) pf_fragqueue;
119 TAILQ_HEAD(pf_cachequeue, pf_fragment) pf_cachequeue;
122 static __inline int pf_frag_compare(struct pf_fragment *,
123 struct pf_fragment *);
125 static int pf_frag_compare(struct pf_fragment *,
126 struct pf_fragment *);
128 RB_HEAD(pf_frag_tree, pf_fragment) pf_frag_tree, pf_cache_tree;
129 RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
130 RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
132 /* Private prototypes */
133 void pf_ip2key(struct pf_fragment *, struct ip *);
134 void pf_remove_fragment(struct pf_fragment *);
135 void pf_flush_fragments(void);
136 void pf_free_fragment(struct pf_fragment *);
137 struct pf_fragment *pf_find_fragment(struct ip *, struct pf_frag_tree *);
138 struct mbuf *pf_reassemble(struct mbuf **, struct pf_fragment **,
139 struct pf_frent *, int);
140 struct mbuf *pf_fragcache(struct mbuf **, struct ip*,
141 struct pf_fragment **, int, int, int *);
142 int pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
143 struct tcphdr *, int);
145 #define DPFPRINTF(x) do { \
146 if (pf_status.debug >= PF_DEBUG_MISC) { \
147 printf("%s: ", __func__); \
154 uma_zone_t pf_frent_pl, pf_frag_pl, pf_cache_pl, pf_cent_pl;
155 uma_zone_t pf_state_scrub_pl;
157 struct pool pf_frent_pl, pf_frag_pl, pf_cache_pl, pf_cent_pl;
158 struct pool pf_state_scrub_pl;
160 int pf_nfrents, pf_ncache;
163 pf_normalize_init(void)
168 * No high water mark support(It's hint not hard limit).
169 * uma_zone_set_max(pf_frag_pl, PFFRAG_FRAG_HIWAT);
171 uma_zone_set_max(pf_frent_pl, PFFRAG_FRENT_HIWAT);
172 uma_zone_set_max(pf_cache_pl, PFFRAG_FRCACHE_HIWAT);
173 uma_zone_set_max(pf_cent_pl, PFFRAG_FRCENT_HIWAT);
175 pool_init(&pf_frent_pl, sizeof(struct pf_frent), 0, 0, 0, "pffrent",
177 pool_init(&pf_frag_pl, sizeof(struct pf_fragment), 0, 0, 0, "pffrag",
179 pool_init(&pf_cache_pl, sizeof(struct pf_fragment), 0, 0, 0,
181 pool_init(&pf_cent_pl, sizeof(struct pf_frcache), 0, 0, 0, "pffrcent",
183 pool_init(&pf_state_scrub_pl, sizeof(struct pf_state_scrub), 0, 0, 0,
186 pool_sethiwat(&pf_frag_pl, PFFRAG_FRAG_HIWAT);
187 pool_sethardlimit(&pf_frent_pl, PFFRAG_FRENT_HIWAT, NULL, 0);
188 pool_sethardlimit(&pf_cache_pl, PFFRAG_FRCACHE_HIWAT, NULL, 0);
189 pool_sethardlimit(&pf_cent_pl, PFFRAG_FRCENT_HIWAT, NULL, 0);
192 TAILQ_INIT(&pf_fragqueue);
193 TAILQ_INIT(&pf_cachequeue);
201 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
205 if ((diff = a->fr_id - b->fr_id))
207 else if ((diff = a->fr_p - b->fr_p))
209 else if (a->fr_src.s_addr < b->fr_src.s_addr)
211 else if (a->fr_src.s_addr > b->fr_src.s_addr)
213 else if (a->fr_dst.s_addr < b->fr_dst.s_addr)
215 else if (a->fr_dst.s_addr > b->fr_dst.s_addr)
221 pf_purge_expired_fragments(void)
223 struct pf_fragment *frag;
224 u_int32_t expire = time_second -
225 pf_default_rule.timeout[PFTM_FRAG];
227 while ((frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue)) != NULL) {
229 KASSERT((BUFFER_FRAGMENTS(frag)),
230 ("BUFFER_FRAGMENTS(frag) == 0: %s", __FUNCTION__));
232 KASSERT(BUFFER_FRAGMENTS(frag));
234 if (frag->fr_timeout > expire)
237 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
238 pf_free_fragment(frag);
241 while ((frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue)) != NULL) {
243 KASSERT((!BUFFER_FRAGMENTS(frag)),
244 ("BUFFER_FRAGMENTS(frag) != 0: %s", __FUNCTION__));
246 KASSERT(!BUFFER_FRAGMENTS(frag));
248 if (frag->fr_timeout > expire)
251 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
252 pf_free_fragment(frag);
254 KASSERT((TAILQ_EMPTY(&pf_cachequeue) ||
255 TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag),
256 ("!(TAILQ_EMPTY() || TAILQ_LAST() == farg): %s",
259 KASSERT(TAILQ_EMPTY(&pf_cachequeue) ||
260 TAILQ_LAST(&pf_cachequeue, pf_cachequeue) != frag);
266 * Try to flush old fragments to make space for new ones
270 pf_flush_fragments(void)
272 struct pf_fragment *frag;
275 goal = pf_nfrents * 9 / 10;
276 DPFPRINTF(("trying to free > %d frents\n",
278 while (goal < pf_nfrents) {
279 frag = TAILQ_LAST(&pf_fragqueue, pf_fragqueue);
282 pf_free_fragment(frag);
286 goal = pf_ncache * 9 / 10;
287 DPFPRINTF(("trying to free > %d cache entries\n",
289 while (goal < pf_ncache) {
290 frag = TAILQ_LAST(&pf_cachequeue, pf_cachequeue);
293 pf_free_fragment(frag);
297 /* Frees the fragments and all associated entries */
300 pf_free_fragment(struct pf_fragment *frag)
302 struct pf_frent *frent;
303 struct pf_frcache *frcache;
305 /* Free all fragments */
306 if (BUFFER_FRAGMENTS(frag)) {
307 for (frent = LIST_FIRST(&frag->fr_queue); frent;
308 frent = LIST_FIRST(&frag->fr_queue)) {
309 LIST_REMOVE(frent, fr_next);
311 m_freem(frent->fr_m);
312 pool_put(&pf_frent_pl, frent);
316 for (frcache = LIST_FIRST(&frag->fr_cache); frcache;
317 frcache = LIST_FIRST(&frag->fr_cache)) {
318 LIST_REMOVE(frcache, fr_next);
321 KASSERT((LIST_EMPTY(&frag->fr_cache) ||
322 LIST_FIRST(&frag->fr_cache)->fr_off >
324 ("! (LIST_EMPTY() || LIST_FIRST()->fr_off >"
325 " frcache->fr_end): %s", __FUNCTION__));
327 KASSERT(LIST_EMPTY(&frag->fr_cache) ||
328 LIST_FIRST(&frag->fr_cache)->fr_off >
332 pool_put(&pf_cent_pl, frcache);
337 pf_remove_fragment(frag);
341 pf_ip2key(struct pf_fragment *key, struct ip *ip)
343 key->fr_p = ip->ip_p;
344 key->fr_id = ip->ip_id;
345 key->fr_src.s_addr = ip->ip_src.s_addr;
346 key->fr_dst.s_addr = ip->ip_dst.s_addr;
350 pf_find_fragment(struct ip *ip, struct pf_frag_tree *tree)
352 struct pf_fragment key;
353 struct pf_fragment *frag;
357 frag = RB_FIND(pf_frag_tree, tree, &key);
359 /* XXX Are we sure we want to update the timeout? */
360 frag->fr_timeout = time_second;
361 if (BUFFER_FRAGMENTS(frag)) {
362 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
363 TAILQ_INSERT_HEAD(&pf_fragqueue, frag, frag_next);
365 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
366 TAILQ_INSERT_HEAD(&pf_cachequeue, frag, frag_next);
373 /* Removes a fragment from the fragment queue and frees the fragment */
376 pf_remove_fragment(struct pf_fragment *frag)
378 if (BUFFER_FRAGMENTS(frag)) {
379 RB_REMOVE(pf_frag_tree, &pf_frag_tree, frag);
380 TAILQ_REMOVE(&pf_fragqueue, frag, frag_next);
381 pool_put(&pf_frag_pl, frag);
383 RB_REMOVE(pf_frag_tree, &pf_cache_tree, frag);
384 TAILQ_REMOVE(&pf_cachequeue, frag, frag_next);
385 pool_put(&pf_cache_pl, frag);
389 #define FR_IP_OFF(fr) ((ntohs((fr)->fr_ip->ip_off) & IP_OFFMASK) << 3)
391 pf_reassemble(struct mbuf **m0, struct pf_fragment **frag,
392 struct pf_frent *frent, int mff)
394 struct mbuf *m = *m0, *m2;
395 struct pf_frent *frea, *next;
396 struct pf_frent *frep = NULL;
397 struct ip *ip = frent->fr_ip;
398 int hlen = ip->ip_hl << 2;
399 u_int16_t off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
400 u_int16_t ip_len = ntohs(ip->ip_len) - ip->ip_hl * 4;
401 u_int16_t max = ip_len + off;
404 KASSERT((*frag == NULL || BUFFER_FRAGMENTS(*frag)),
405 ("! (*frag == NULL || BUFFER_FRAGMENTS(*frag)): %s", __FUNCTION__));
407 KASSERT(*frag == NULL || BUFFER_FRAGMENTS(*frag));
410 /* Strip off ip header */
414 /* Create a new reassembly queue for this packet */
416 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
418 pf_flush_fragments();
419 *frag = pool_get(&pf_frag_pl, PR_NOWAIT);
424 (*frag)->fr_flags = 0;
426 (*frag)->fr_src = frent->fr_ip->ip_src;
427 (*frag)->fr_dst = frent->fr_ip->ip_dst;
428 (*frag)->fr_p = frent->fr_ip->ip_p;
429 (*frag)->fr_id = frent->fr_ip->ip_id;
430 (*frag)->fr_timeout = time_second;
431 LIST_INIT(&(*frag)->fr_queue);
433 RB_INSERT(pf_frag_tree, &pf_frag_tree, *frag);
434 TAILQ_INSERT_HEAD(&pf_fragqueue, *frag, frag_next);
436 /* We do not have a previous fragment */
442 * Find a fragment after the current one:
443 * - off contains the real shifted offset.
445 LIST_FOREACH(frea, &(*frag)->fr_queue, fr_next) {
446 if (FR_IP_OFF(frea) > off)
452 KASSERT((frep != NULL || frea != NULL),
453 ("!(frep != NULL || frea != NULL): %s", __FUNCTION__));;
455 KASSERT(frep != NULL || frea != NULL);
459 FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl *
464 precut = FR_IP_OFF(frep) + ntohs(frep->fr_ip->ip_len) -
465 frep->fr_ip->ip_hl * 4 - off;
466 if (precut >= ip_len)
468 m_adj(frent->fr_m, precut);
469 DPFPRINTF(("overlap -%d\n", precut));
470 /* Enforce 8 byte boundaries */
471 ip->ip_off = htons(ntohs(ip->ip_off) + (precut >> 3));
472 off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
474 ip->ip_len = htons(ip_len);
477 for (; frea != NULL && ip_len + off > FR_IP_OFF(frea);
482 aftercut = ip_len + off - FR_IP_OFF(frea);
483 DPFPRINTF(("adjust overlap %d\n", aftercut));
484 if (aftercut < ntohs(frea->fr_ip->ip_len) - frea->fr_ip->ip_hl
487 frea->fr_ip->ip_len =
488 htons(ntohs(frea->fr_ip->ip_len) - aftercut);
489 frea->fr_ip->ip_off = htons(ntohs(frea->fr_ip->ip_off) +
491 m_adj(frea->fr_m, aftercut);
495 /* This fragment is completely overlapped, loose it */
496 next = LIST_NEXT(frea, fr_next);
498 LIST_REMOVE(frea, fr_next);
499 pool_put(&pf_frent_pl, frea);
504 /* Update maximum data size */
505 if ((*frag)->fr_max < max)
506 (*frag)->fr_max = max;
507 /* This is the last segment */
509 (*frag)->fr_flags |= PFFRAG_SEENLAST;
512 LIST_INSERT_HEAD(&(*frag)->fr_queue, frent, fr_next);
514 LIST_INSERT_AFTER(frep, frent, fr_next);
516 /* Check if we are completely reassembled */
517 if (!((*frag)->fr_flags & PFFRAG_SEENLAST))
520 /* Check if we have all the data */
522 for (frep = LIST_FIRST(&(*frag)->fr_queue); frep; frep = next) {
523 next = LIST_NEXT(frep, fr_next);
525 off += ntohs(frep->fr_ip->ip_len) - frep->fr_ip->ip_hl * 4;
526 if (off < (*frag)->fr_max &&
527 (next == NULL || FR_IP_OFF(next) != off))
529 DPFPRINTF(("missing fragment at %d, next %d, max %d\n",
530 off, next == NULL ? -1 : FR_IP_OFF(next),
535 DPFPRINTF(("%d < %d?\n", off, (*frag)->fr_max));
536 if (off < (*frag)->fr_max)
539 /* We have all the data */
540 frent = LIST_FIRST(&(*frag)->fr_queue);
542 KASSERT((frent != NULL), ("frent == NULL: %s", __FUNCTION__));
544 KASSERT(frent != NULL);
546 if ((frent->fr_ip->ip_hl << 2) + off > IP_MAXPACKET) {
547 DPFPRINTF(("drop: too big: %d\n", off));
548 pf_free_fragment(*frag);
552 next = LIST_NEXT(frent, fr_next);
554 /* Magic from ip_input */
560 pool_put(&pf_frent_pl, frent);
562 for (frent = next; frent != NULL; frent = next) {
563 next = LIST_NEXT(frent, fr_next);
566 pool_put(&pf_frent_pl, frent);
571 ip->ip_src = (*frag)->fr_src;
572 ip->ip_dst = (*frag)->fr_dst;
574 /* Remove from fragment queue */
575 pf_remove_fragment(*frag);
578 hlen = ip->ip_hl << 2;
579 ip->ip_len = htons(off + hlen);
583 /* some debugging cruft by sklower, below, will go away soon */
584 /* XXX this should be done elsewhere */
585 if (m->m_flags & M_PKTHDR) {
587 for (m2 = m; m2; m2 = m2->m_next)
589 m->m_pkthdr.len = plen;
592 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip->ip_len)));
596 /* Oops - fail safe - drop packet */
597 pool_put(&pf_frent_pl, frent);
604 pf_fragcache(struct mbuf **m0, struct ip *h, struct pf_fragment **frag, int mff,
605 int drop, int *nomem)
607 struct mbuf *m = *m0;
608 struct pf_frcache *frp, *fra, *cur = NULL;
609 int ip_len = ntohs(h->ip_len) - (h->ip_hl << 2);
610 u_int16_t off = ntohs(h->ip_off) << 3;
611 u_int16_t max = ip_len + off;
615 KASSERT((*frag == NULL || !BUFFER_FRAGMENTS(*frag)),
616 ("!(*frag == NULL || !BUFFER_FRAGMENTS(*frag)): %s", __FUNCTION__));
618 KASSERT(*frag == NULL || !BUFFER_FRAGMENTS(*frag));
621 /* Create a new range queue for this packet */
623 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
625 pf_flush_fragments();
626 *frag = pool_get(&pf_cache_pl, PR_NOWAIT);
631 /* Get an entry for the queue */
632 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
634 pool_put(&pf_cache_pl, *frag);
640 (*frag)->fr_flags = PFFRAG_NOBUFFER;
642 (*frag)->fr_src = h->ip_src;
643 (*frag)->fr_dst = h->ip_dst;
644 (*frag)->fr_p = h->ip_p;
645 (*frag)->fr_id = h->ip_id;
646 (*frag)->fr_timeout = time_second;
650 LIST_INIT(&(*frag)->fr_cache);
651 LIST_INSERT_HEAD(&(*frag)->fr_cache, cur, fr_next);
653 RB_INSERT(pf_frag_tree, &pf_cache_tree, *frag);
654 TAILQ_INSERT_HEAD(&pf_cachequeue, *frag, frag_next);
656 DPFPRINTF(("fragcache[%d]: new %d-%d\n", h->ip_id, off, max));
662 * Find a fragment after the current one:
663 * - off contains the real shifted offset.
666 LIST_FOREACH(fra, &(*frag)->fr_cache, fr_next) {
667 if (fra->fr_off > off)
673 KASSERT((frp != NULL || fra != NULL),
674 ("!(frp != NULL || fra != NULL): %s", __FUNCTION__));
676 KASSERT(frp != NULL || fra != NULL);
682 precut = frp->fr_end - off;
683 if (precut >= ip_len) {
684 /* Fragment is entirely a duplicate */
685 DPFPRINTF(("fragcache[%d]: dead (%d-%d) %d-%d\n",
686 h->ip_id, frp->fr_off, frp->fr_end, off, max));
690 /* They are adjacent. Fixup cache entry */
691 DPFPRINTF(("fragcache[%d]: adjacent (%d-%d) %d-%d\n",
692 h->ip_id, frp->fr_off, frp->fr_end, off, max));
694 } else if (precut > 0) {
695 /* The first part of this payload overlaps with a
696 * fragment that has already been passed.
697 * Need to trim off the first part of the payload.
698 * But to do so easily, we need to create another
699 * mbuf to throw the original header into.
702 DPFPRINTF(("fragcache[%d]: chop %d (%d-%d) %d-%d\n",
703 h->ip_id, precut, frp->fr_off, frp->fr_end, off,
708 /* Update the previous frag to encompass this one */
712 /* XXX Optimization opportunity
713 * This is a very heavy way to trim the payload.
714 * we could do it much faster by diddling mbuf
715 * internals but that would be even less legible
716 * than this mbuf magic. For my next trick,
717 * I'll pull a rabbit out of my laptop.
720 *m0 = m_dup(m, M_DONTWAIT);
722 *m0 = m_copym2(m, 0, h->ip_hl << 2, M_NOWAIT);
727 /* From KAME Project : We have missed this! */
728 m_adj(*m0, (h->ip_hl << 2) -
729 (*m0)->m_pkthdr.len);
731 KASSERT(((*m0)->m_next == NULL),
732 ("(*m0)->m_next != NULL: %s",
735 KASSERT((*m0)->m_next == NULL);
737 m_adj(m, precut + (h->ip_hl << 2));
740 if (m->m_flags & M_PKTHDR) {
743 for (t = m; t; t = t->m_next)
745 m->m_pkthdr.len = plen;
749 h = mtod(m, struct ip *);
752 KASSERT(((int)m->m_len ==
753 ntohs(h->ip_len) - precut),
754 ("m->m_len != ntohs(h->ip_len) - precut: %s",
757 KASSERT((int)m->m_len ==
758 ntohs(h->ip_len) - precut);
760 h->ip_off = htons(ntohs(h->ip_off) +
762 h->ip_len = htons(ntohs(h->ip_len) - precut);
767 /* There is a gap between fragments */
769 DPFPRINTF(("fragcache[%d]: gap %d (%d-%d) %d-%d\n",
770 h->ip_id, -precut, frp->fr_off, frp->fr_end, off,
773 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
780 LIST_INSERT_AFTER(frp, cur, fr_next);
788 aftercut = max - fra->fr_off;
790 /* Adjacent fragments */
791 DPFPRINTF(("fragcache[%d]: adjacent %d-%d (%d-%d)\n",
792 h->ip_id, off, max, fra->fr_off, fra->fr_end));
795 } else if (aftercut > 0) {
796 /* Need to chop off the tail of this fragment */
797 DPFPRINTF(("fragcache[%d]: chop %d %d-%d (%d-%d)\n",
798 h->ip_id, aftercut, off, max, fra->fr_off,
807 if (m->m_flags & M_PKTHDR) {
810 for (t = m; t; t = t->m_next)
812 m->m_pkthdr.len = plen;
814 h = mtod(m, struct ip *);
816 KASSERT(((int)m->m_len == ntohs(h->ip_len) - aftercut),
817 ("m->m_len != ntohs(h->ip_len) - aftercut: %s",
820 KASSERT((int)m->m_len ==
821 ntohs(h->ip_len) - aftercut);
823 h->ip_len = htons(ntohs(h->ip_len) - aftercut);
827 } else if (frp == NULL) {
828 /* There is a gap between fragments */
829 DPFPRINTF(("fragcache[%d]: gap %d %d-%d (%d-%d)\n",
830 h->ip_id, -aftercut, off, max, fra->fr_off,
833 cur = pool_get(&pf_cent_pl, PR_NOWAIT);
840 LIST_INSERT_BEFORE(fra, cur, fr_next);
844 /* Need to glue together two separate fragment descriptors */
846 if (cur && fra->fr_off <= cur->fr_end) {
847 /* Need to merge in a previous 'cur' */
848 DPFPRINTF(("fragcache[%d]: adjacent(merge "
849 "%d-%d) %d-%d (%d-%d)\n",
850 h->ip_id, cur->fr_off, cur->fr_end, off,
851 max, fra->fr_off, fra->fr_end));
852 fra->fr_off = cur->fr_off;
853 LIST_REMOVE(cur, fr_next);
854 pool_put(&pf_cent_pl, cur);
858 } else if (frp && fra->fr_off <= frp->fr_end) {
859 /* Need to merge in a modified 'frp' */
861 KASSERT((cur == NULL), ("cur != NULL: %s",
864 KASSERT(cur == NULL);
866 DPFPRINTF(("fragcache[%d]: adjacent(merge "
867 "%d-%d) %d-%d (%d-%d)\n",
868 h->ip_id, frp->fr_off, frp->fr_end, off,
869 max, fra->fr_off, fra->fr_end));
870 fra->fr_off = frp->fr_off;
871 LIST_REMOVE(frp, fr_next);
872 pool_put(&pf_cent_pl, frp);
882 * We must keep tracking the overall fragment even when
883 * we're going to drop it anyway so that we know when to
884 * free the overall descriptor. Thus we drop the frag late.
891 /* Update maximum data size */
892 if ((*frag)->fr_max < max)
893 (*frag)->fr_max = max;
895 /* This is the last segment */
897 (*frag)->fr_flags |= PFFRAG_SEENLAST;
899 /* Check if we are completely reassembled */
900 if (((*frag)->fr_flags & PFFRAG_SEENLAST) &&
901 LIST_FIRST(&(*frag)->fr_cache)->fr_off == 0 &&
902 LIST_FIRST(&(*frag)->fr_cache)->fr_end == (*frag)->fr_max) {
903 /* Remove from fragment queue */
904 DPFPRINTF(("fragcache[%d]: done 0-%d\n", h->ip_id,
906 pf_free_fragment(*frag);
915 /* Still need to pay attention to !IP_MF */
916 if (!mff && *frag != NULL)
917 (*frag)->fr_flags |= PFFRAG_SEENLAST;
924 /* Still need to pay attention to !IP_MF */
925 if (!mff && *frag != NULL)
926 (*frag)->fr_flags |= PFFRAG_SEENLAST;
929 /* This fragment has been deemed bad. Don't reass */
930 if (((*frag)->fr_flags & PFFRAG_DROP) == 0)
931 DPFPRINTF(("fragcache[%d]: dropping overall fragment\n",
933 (*frag)->fr_flags |= PFFRAG_DROP;
941 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
944 struct mbuf *m = *m0;
946 struct pf_frent *frent;
947 struct pf_fragment *frag = NULL;
948 struct ip *h = mtod(m, struct ip *);
949 int mff = (ntohs(h->ip_off) & IP_MF);
950 int hlen = h->ip_hl << 2;
951 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
956 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
959 if (r->kif != NULL &&
960 (r->kif != kif && r->kif != kif->pfik_parent) == !r->ifnot)
961 r = r->skip[PF_SKIP_IFP].ptr;
962 else if (r->direction && r->direction != dir)
963 r = r->skip[PF_SKIP_DIR].ptr;
964 else if (r->af && r->af != AF_INET)
965 r = r->skip[PF_SKIP_AF].ptr;
966 else if (r->proto && r->proto != h->ip_p)
967 r = r->skip[PF_SKIP_PROTO].ptr;
968 else if (PF_MISMATCHAW(&r->src.addr,
969 (struct pf_addr *)&h->ip_src.s_addr, AF_INET, r->src.neg))
970 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
971 else if (PF_MISMATCHAW(&r->dst.addr,
972 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET, r->dst.neg))
973 r = r->skip[PF_SKIP_DST_ADDR].ptr;
983 /* Check for illegal packets */
984 if (hlen < (int)sizeof(struct ip))
987 if (hlen > ntohs(h->ip_len))
990 /* Clear IP_DF if the rule uses the no-df option */
991 if (r->rule_flag & PFRULE_NODF)
992 h->ip_off &= htons(~IP_DF);
994 /* We will need other tests here */
995 if (!fragoff && !mff)
998 /* We're dealing with a fragment now. Don't allow fragments
999 * with IP_DF to enter the cache. If the flag was cleared by
1000 * no-df above, fine. Otherwise drop it.
1002 if (h->ip_off & htons(IP_DF)) {
1003 DPFPRINTF(("IP_DF\n"));
1007 ip_len = ntohs(h->ip_len) - hlen;
1008 ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1010 /* All fragments are 8 byte aligned */
1011 if (mff && (ip_len & 0x7)) {
1012 DPFPRINTF(("mff and %d\n", ip_len));
1016 /* Respect maximum length */
1017 if (fragoff + ip_len > IP_MAXPACKET) {
1018 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
1021 max = fragoff + ip_len;
1023 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0) {
1024 /* Fully buffer all of the fragments */
1026 frag = pf_find_fragment(h, &pf_frag_tree);
1028 /* Check if we saw the last fragment already */
1029 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
1033 /* Get an entry for the fragment queue */
1034 frent = pool_get(&pf_frent_pl, PR_NOWAIT);
1035 if (frent == NULL) {
1036 REASON_SET(reason, PFRES_MEMORY);
1043 /* Might return a completely reassembled mbuf, or NULL */
1044 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
1045 *m0 = m = pf_reassemble(m0, &frag, frent, mff);
1050 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
1053 h = mtod(m, struct ip *);
1055 /* non-buffering fragment cache (drops or masks overlaps) */
1058 if (dir == PF_OUT) {
1059 if (m_tag_find(m, PACKET_TAG_PF_FRAGCACHE, NULL) !=
1061 /* Already passed the fragment cache in the
1062 * input direction. If we continued, it would
1063 * appear to be a dup and would be dropped.
1069 frag = pf_find_fragment(h, &pf_cache_tree);
1071 /* Check if we saw the last fragment already */
1072 if (frag != NULL && (frag->fr_flags & PFFRAG_SEENLAST) &&
1073 max > frag->fr_max) {
1074 if (r->rule_flag & PFRULE_FRAGDROP)
1075 frag->fr_flags |= PFFRAG_DROP;
1079 *m0 = m = pf_fragcache(m0, h, &frag, mff,
1080 (r->rule_flag & PFRULE_FRAGDROP) ? 1 : 0, &nomem);
1090 mtag = m_tag_get(PACKET_TAG_PF_FRAGCACHE, 0, M_NOWAIT);
1093 m_tag_prepend(m, mtag);
1095 if (frag != NULL && (frag->fr_flags & PFFRAG_DROP))
1101 /* At this point, only IP_DF is allowed in ip_off */
1102 h->ip_off &= htons(IP_DF);
1104 /* Enforce a minimum ttl, may cause endless packet loops */
1105 if (r->min_ttl && h->ip_ttl < r->min_ttl)
1106 h->ip_ttl = r->min_ttl;
1108 if (r->rule_flag & PFRULE_RANDOMID) {
1109 u_int16_t ip_id = h->ip_id;
1111 h->ip_id = ip_randomid();
1112 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1114 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1115 pd->flags |= PFDESC_IP_REAS;
1120 /* Enforce a minimum ttl, may cause endless packet loops */
1121 if (r->min_ttl && h->ip_ttl < r->min_ttl)
1122 h->ip_ttl = r->min_ttl;
1123 if ((r->rule_flag & (PFRULE_FRAGCROP|PFRULE_FRAGDROP)) == 0)
1124 pd->flags |= PFDESC_IP_REAS;
1128 REASON_SET(reason, PFRES_MEMORY);
1129 if (r != NULL && r->log)
1130 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL);
1134 REASON_SET(reason, PFRES_NORM);
1135 if (r != NULL && r->log)
1136 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL);
1140 DPFPRINTF(("dropping bad fragment\n"));
1142 /* Free associated fragments */
1144 pf_free_fragment(frag);
1146 REASON_SET(reason, PFRES_FRAG);
1147 if (r != NULL && r->log)
1148 PFLOG_PACKET(kif, h, m, AF_INET, dir, *reason, r, NULL, NULL);
1155 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1156 u_short *reason, struct pf_pdesc *pd)
1158 struct mbuf *m = *m0;
1160 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1164 struct ip6_opt_jumbo jumbo;
1165 struct ip6_frag frag;
1166 u_int32_t jumbolen = 0, plen;
1167 u_int16_t fragoff = 0;
1173 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1176 if (r->kif != NULL &&
1177 (r->kif != kif && r->kif != kif->pfik_parent) == !r->ifnot)
1178 r = r->skip[PF_SKIP_IFP].ptr;
1179 else if (r->direction && r->direction != dir)
1180 r = r->skip[PF_SKIP_DIR].ptr;
1181 else if (r->af && r->af != AF_INET6)
1182 r = r->skip[PF_SKIP_AF].ptr;
1183 #if 0 /* header chain! */
1184 else if (r->proto && r->proto != h->ip6_nxt)
1185 r = r->skip[PF_SKIP_PROTO].ptr;
1187 else if (PF_MISMATCHAW(&r->src.addr,
1188 (struct pf_addr *)&h->ip6_src, AF_INET6, r->src.neg))
1189 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1190 else if (PF_MISMATCHAW(&r->dst.addr,
1191 (struct pf_addr *)&h->ip6_dst, AF_INET6, r->dst.neg))
1192 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1202 /* Check for illegal packets */
1203 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1206 off = sizeof(struct ip6_hdr);
1211 case IPPROTO_FRAGMENT:
1215 case IPPROTO_ROUTING:
1216 case IPPROTO_DSTOPTS:
1217 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1220 if (proto == IPPROTO_AH)
1221 off += (ext.ip6e_len + 2) * 4;
1223 off += (ext.ip6e_len + 1) * 8;
1224 proto = ext.ip6e_nxt;
1226 case IPPROTO_HOPOPTS:
1227 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1230 optend = off + (ext.ip6e_len + 1) * 8;
1231 ooff = off + sizeof(ext);
1233 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1234 sizeof(opt.ip6o_type), NULL, NULL,
1237 if (opt.ip6o_type == IP6OPT_PAD1) {
1241 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1242 NULL, NULL, AF_INET6))
1244 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1246 switch (opt.ip6o_type) {
1248 if (h->ip6_plen != 0)
1250 if (!pf_pull_hdr(m, ooff, &jumbo,
1251 sizeof(jumbo), NULL, NULL,
1254 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1256 jumbolen = ntohl(jumbolen);
1257 if (jumbolen <= IPV6_MAXPACKET)
1259 if (sizeof(struct ip6_hdr) + jumbolen !=
1266 ooff += sizeof(opt) + opt.ip6o_len;
1267 } while (ooff < optend);
1270 proto = ext.ip6e_nxt;
1276 } while (!terminal);
1278 /* jumbo payload option must be present, or plen > 0 */
1279 if (ntohs(h->ip6_plen) == 0)
1282 plen = ntohs(h->ip6_plen);
1285 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1288 /* Enforce a minimum ttl, may cause endless packet loops */
1289 if (r->min_ttl && h->ip6_hlim < r->min_ttl)
1290 h->ip6_hlim = r->min_ttl;
1295 if (ntohs(h->ip6_plen) == 0 || jumbolen)
1297 plen = ntohs(h->ip6_plen);
1299 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1301 fragoff = ntohs(frag.ip6f_offlg & IP6F_OFF_MASK);
1302 if (fragoff + (plen - off - sizeof(frag)) > IPV6_MAXPACKET)
1305 /* do something about it */
1306 /* remember to set pd->flags |= PFDESC_IP_REAS */
1310 REASON_SET(reason, PFRES_SHORT);
1311 if (r != NULL && r->log)
1312 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL);
1316 REASON_SET(reason, PFRES_NORM);
1317 if (r != NULL && r->log)
1318 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL);
1322 REASON_SET(reason, PFRES_FRAG);
1323 if (r != NULL && r->log)
1324 PFLOG_PACKET(kif, h, m, AF_INET6, dir, *reason, r, NULL, NULL);
1330 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1331 int off, void *h, struct pf_pdesc *pd)
1333 struct pf_rule *r, *rm = NULL;
1334 struct tcphdr *th = pd->hdr.tcp;
1338 sa_family_t af = pd->af;
1340 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1343 if (r->kif != NULL &&
1344 (r->kif != kif && r->kif != kif->pfik_parent) == !r->ifnot)
1345 r = r->skip[PF_SKIP_IFP].ptr;
1346 else if (r->direction && r->direction != dir)
1347 r = r->skip[PF_SKIP_DIR].ptr;
1348 else if (r->af && r->af != af)
1349 r = r->skip[PF_SKIP_AF].ptr;
1350 else if (r->proto && r->proto != pd->proto)
1351 r = r->skip[PF_SKIP_PROTO].ptr;
1352 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af, r->src.neg))
1353 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1354 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1355 r->src.port[0], r->src.port[1], th->th_sport))
1356 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1357 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af, r->dst.neg))
1358 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1359 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1360 r->dst.port[0], r->dst.port[1], th->th_dport))
1361 r = r->skip[PF_SKIP_DST_PORT].ptr;
1362 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1363 pf_osfp_fingerprint(pd, m, off, th),
1365 r = TAILQ_NEXT(r, entries);
1372 if (rm == NULL || rm->action == PF_NOSCRUB)
1377 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1378 pd->flags |= PFDESC_TCP_NORM;
1380 flags = th->th_flags;
1381 if (flags & TH_SYN) {
1382 /* Illegal packet */
1389 /* Illegal packet */
1390 if (!(flags & (TH_ACK|TH_RST)))
1394 if (!(flags & TH_ACK)) {
1395 /* These flags are only valid if ACK is set */
1396 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1400 /* Check for illegal header length */
1401 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1404 /* If flags changed, or reserved data set, then adjust */
1405 if (flags != th->th_flags || th->th_x2 != 0) {
1408 ov = *(u_int16_t *)(&th->th_ack + 1);
1409 th->th_flags = flags;
1411 nv = *(u_int16_t *)(&th->th_ack + 1);
1413 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1417 /* Remove urgent pointer, if TH_URG is not set */
1418 if (!(flags & TH_URG) && th->th_urp) {
1419 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1424 /* Process options */
1425 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off))
1428 /* copy back packet headers if we sanitized */
1430 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1435 REASON_SET(&reason, PFRES_NORM);
1436 if (rm != NULL && r->log)
1437 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, r, NULL, NULL);
1442 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1443 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1445 u_int32_t tsval, tsecr;
1450 KASSERT((src->scrub == NULL),
1451 ("pf_normalize_tcp_init: src->scrub != NULL"));
1453 KASSERT(src->scrub == NULL);
1456 src->scrub = pool_get(&pf_state_scrub_pl, PR_NOWAIT);
1457 if (src->scrub == NULL)
1459 bzero(src->scrub, sizeof(*src->scrub));
1464 struct ip *h = mtod(m, struct ip *);
1465 src->scrub->pfss_ttl = h->ip_ttl;
1471 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1472 src->scrub->pfss_ttl = h->ip6_hlim;
1480 * All normalizations below are only begun if we see the start of
1481 * the connections. They must all set an enabled bit in pfss_flags
1483 if ((th->th_flags & TH_SYN) == 0)
1487 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1488 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1489 /* Diddle with TCP options */
1491 opt = hdr + sizeof(struct tcphdr);
1492 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1493 while (hlen >= TCPOLEN_TIMESTAMP) {
1495 case TCPOPT_EOL: /* FALLTHROUGH */
1500 case TCPOPT_TIMESTAMP:
1501 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1502 src->scrub->pfss_flags |=
1504 src->scrub->pfss_ts_mod =
1505 htonl(arc4random());
1507 /* note PFSS_PAWS not set yet */
1508 memcpy(&tsval, &opt[2],
1510 memcpy(&tsecr, &opt[6],
1512 src->scrub->pfss_tsval0 = ntohl(tsval);
1513 src->scrub->pfss_tsval = ntohl(tsval);
1514 src->scrub->pfss_tsecr = ntohl(tsecr);
1515 getmicrouptime(&src->scrub->pfss_last);
1519 hlen -= MAX(opt[1], 2);
1520 opt += MAX(opt[1], 2);
1530 pf_normalize_tcp_cleanup(struct pf_state *state)
1532 if (state->src.scrub)
1533 pool_put(&pf_state_scrub_pl, state->src.scrub);
1534 if (state->dst.scrub)
1535 pool_put(&pf_state_scrub_pl, state->dst.scrub);
1537 /* Someday... flush the TCP segment reassembly descriptors. */
1541 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1542 u_short *reason, struct tcphdr *th, struct pf_state *state,
1543 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1545 struct timeval uptime;
1546 u_int32_t tsval, tsecr;
1547 u_int tsval_from_last;
1554 KASSERT((src->scrub || dst->scrub),
1555 ("pf_normalize_tcp_statefull: src->scrub && dst->scrub!"));
1557 KASSERT(src->scrub || dst->scrub);
1561 * Enforce the minimum TTL seen for this connection. Negate a common
1562 * technique to evade an intrusion detection system and confuse
1563 * firewall state code.
1569 struct ip *h = mtod(m, struct ip *);
1570 if (h->ip_ttl > src->scrub->pfss_ttl)
1571 src->scrub->pfss_ttl = h->ip_ttl;
1572 h->ip_ttl = src->scrub->pfss_ttl;
1580 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1581 if (h->ip6_hlim > src->scrub->pfss_ttl)
1582 src->scrub->pfss_ttl = h->ip6_hlim;
1583 h->ip6_hlim = src->scrub->pfss_ttl;
1590 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1591 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1592 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1593 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1594 /* Diddle with TCP options */
1596 opt = hdr + sizeof(struct tcphdr);
1597 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1598 while (hlen >= TCPOLEN_TIMESTAMP) {
1600 case TCPOPT_EOL: /* FALLTHROUGH */
1605 case TCPOPT_TIMESTAMP:
1606 /* Modulate the timestamps. Can be used for
1607 * NAT detection, OS uptime determination or
1612 /* Huh? Multiple timestamps!? */
1613 if (pf_status.debug >= PF_DEBUG_MISC) {
1614 DPFPRINTF(("multiple TS??"));
1615 pf_print_state(state);
1618 REASON_SET(reason, PFRES_TS);
1621 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1622 memcpy(&tsval, &opt[2],
1624 if (tsval && src->scrub &&
1625 (src->scrub->pfss_flags &
1627 tsval = ntohl(tsval);
1628 pf_change_a(&opt[2],
1631 src->scrub->pfss_ts_mod),
1636 /* Modulate TS reply iff valid (!0) */
1637 memcpy(&tsecr, &opt[6],
1639 if (tsecr && dst->scrub &&
1640 (dst->scrub->pfss_flags &
1642 tsecr = ntohl(tsecr)
1643 - dst->scrub->pfss_ts_mod;
1644 pf_change_a(&opt[6],
1645 &th->th_sum, htonl(tsecr),
1653 hlen -= MAX(opt[1], 2);
1654 opt += MAX(opt[1], 2);
1659 /* Copyback the options, caller copys back header */
1661 m_copyback(m, off + sizeof(struct tcphdr),
1662 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1663 sizeof(struct tcphdr));
1669 * Must invalidate PAWS checks on connections idle for too long.
1670 * The fastest allowed timestamp clock is 1ms. That turns out to
1671 * be about 24 days before it wraps. XXX Right now our lowerbound
1672 * TS echo check only works for the first 12 days of a connection
1673 * when the TS has exhausted half its 32bit space
1675 #define TS_MAX_IDLE (24*24*60*60)
1676 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1678 getmicrouptime(&uptime);
1679 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1680 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1681 time_second - state->creation > TS_MAX_CONN)) {
1682 if (pf_status.debug >= PF_DEBUG_MISC) {
1683 DPFPRINTF(("src idled out of PAWS\n"));
1684 pf_print_state(state);
1687 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1690 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1691 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1692 if (pf_status.debug >= PF_DEBUG_MISC) {
1693 DPFPRINTF(("dst idled out of PAWS\n"));
1694 pf_print_state(state);
1697 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1701 if (got_ts && src->scrub && dst->scrub &&
1702 (src->scrub->pfss_flags & PFSS_PAWS) &&
1703 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1704 /* Validate that the timestamps are "in-window".
1705 * RFC1323 describes TCP Timestamp options that allow
1706 * measurement of RTT (round trip time) and PAWS
1707 * (protection against wrapped sequence numbers). PAWS
1708 * gives us a set of rules for rejecting packets on
1709 * long fat pipes (packets that were somehow delayed
1710 * in transit longer than the time it took to send the
1711 * full TCP sequence space of 4Gb). We can use these
1712 * rules and infer a few others that will let us treat
1713 * the 32bit timestamp and the 32bit echoed timestamp
1714 * as sequence numbers to prevent a blind attacker from
1715 * inserting packets into a connection.
1718 * - The timestamp on this packet must be greater than
1719 * or equal to the last value echoed by the other
1720 * endpoint. The RFC says those will be discarded
1721 * since it is a dup that has already been acked.
1722 * This gives us a lowerbound on the timestamp.
1723 * timestamp >= other last echoed timestamp
1724 * - The timestamp will be less than or equal to
1725 * the last timestamp plus the time between the
1726 * last packet and now. The RFC defines the max
1727 * clock rate as 1ms. We will allow clocks to be
1728 * up to 10% fast and will allow a total difference
1729 * or 30 seconds due to a route change. And this
1730 * gives us an upperbound on the timestamp.
1731 * timestamp <= last timestamp + max ticks
1732 * We have to be careful here. Windows will send an
1733 * initial timestamp of zero and then initialize it
1734 * to a random value after the 3whs; presumably to
1735 * avoid a DoS by having to call an expensive RNG
1736 * during a SYN flood. Proof MS has at least one
1737 * good security geek.
1739 * - The TCP timestamp option must also echo the other
1740 * endpoints timestamp. The timestamp echoed is the
1741 * one carried on the earliest unacknowledged segment
1742 * on the left edge of the sequence window. The RFC
1743 * states that the host will reject any echoed
1744 * timestamps that were larger than any ever sent.
1745 * This gives us an upperbound on the TS echo.
1746 * tescr <= largest_tsval
1747 * - The lowerbound on the TS echo is a little more
1748 * tricky to determine. The other endpoint's echoed
1749 * values will not decrease. But there may be
1750 * network conditions that re-order packets and
1751 * cause our view of them to decrease. For now the
1752 * only lowerbound we can safely determine is that
1753 * the TS echo will never be less than the orginal
1754 * TS. XXX There is probably a better lowerbound.
1755 * Remove TS_MAX_CONN with better lowerbound check.
1756 * tescr >= other original TS
1758 * It is also important to note that the fastest
1759 * timestamp clock of 1ms will wrap its 32bit space in
1760 * 24 days. So we just disable TS checking after 24
1761 * days of idle time. We actually must use a 12d
1762 * connection limit until we can come up with a better
1763 * lowerbound to the TS echo check.
1765 struct timeval delta_ts;
1770 * PFTM_TS_DIFF is how many seconds of leeway to allow
1771 * a host's timestamp. This can happen if the previous
1772 * packet got delayed in transit for much longer than
1775 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1776 ts_fudge = pf_default_rule.timeout[PFTM_TS_DIFF];
1779 /* Calculate max ticks since the last timestamp */
1780 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1781 #define TS_MICROSECS 1000000 /* microseconds per second */
1784 #define timersub(tvp, uvp, vvp) \
1786 (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
1787 (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
1788 if ((vvp)->tv_usec < 0) { \
1790 (vvp)->tv_usec += 1000000; \
1795 timersub(&uptime, &src->scrub->pfss_last, &delta_ts);
1796 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1797 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1800 if ((src->state >= TCPS_ESTABLISHED &&
1801 dst->state >= TCPS_ESTABLISHED) &&
1802 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1803 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1804 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1805 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1806 /* Bad RFC1323 implementation or an insertion attack.
1808 * - Solaris 2.6 and 2.7 are known to send another ACK
1809 * after the FIN,FIN|ACK,ACK closing that carries
1813 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1814 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1815 SEQ_GT(tsval, src->scrub->pfss_tsval +
1816 tsval_from_last) ? '1' : ' ',
1817 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1818 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1820 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1821 "idle: %jus %lums\n",
1822 tsval, tsecr, tsval_from_last,
1823 (uintmax_t)delta_ts.tv_sec,
1824 delta_ts.tv_usec / 1000));
1825 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1826 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1827 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1828 "\n", dst->scrub->pfss_tsval,
1829 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1831 DPFPRINTF((" tsval: %lu tsecr: %lu +ticks: %lu "
1832 "idle: %lus %lums\n",
1833 tsval, tsecr, tsval_from_last, delta_ts.tv_sec,
1834 delta_ts.tv_usec / 1000));
1835 DPFPRINTF((" src->tsval: %lu tsecr: %lu\n",
1836 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1837 DPFPRINTF((" dst->tsval: %lu tsecr: %lu tsval0: %lu"
1838 "\n", dst->scrub->pfss_tsval,
1839 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1841 if (pf_status.debug >= PF_DEBUG_MISC) {
1842 pf_print_state(state);
1843 pf_print_flags(th->th_flags);
1846 REASON_SET(reason, PFRES_TS);
1850 /* XXX I'd really like to require tsecr but it's optional */
1852 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1853 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1854 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1855 src->scrub && dst->scrub &&
1856 (src->scrub->pfss_flags & PFSS_PAWS) &&
1857 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1858 /* Didn't send a timestamp. Timestamps aren't really useful
1860 * - connection opening or closing (often not even sent).
1861 * but we must not let an attacker to put a FIN on a
1862 * data packet to sneak it through our ESTABLISHED check.
1863 * - on a TCP reset. RFC suggests not even looking at TS.
1864 * - on an empty ACK. The TS will not be echoed so it will
1865 * probably not help keep the RTT calculation in sync and
1866 * there isn't as much danger when the sequence numbers
1867 * got wrapped. So some stacks don't include TS on empty
1870 * To minimize the disruption to mostly RFC1323 conformant
1871 * stacks, we will only require timestamps on data packets.
1873 * And what do ya know, we cannot require timestamps on data
1874 * packets. There appear to be devices that do legitimate
1875 * TCP connection hijacking. There are HTTP devices that allow
1876 * a 3whs (with timestamps) and then buffer the HTTP request.
1877 * If the intermediate device has the HTTP response cache, it
1878 * will spoof the response but not bother timestamping its
1879 * packets. So we can look for the presence of a timestamp in
1880 * the first data packet and if there, require it in all future
1884 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1886 * Hey! Someone tried to sneak a packet in. Or the
1887 * stack changed its RFC1323 behavior?!?!
1889 if (pf_status.debug >= PF_DEBUG_MISC) {
1890 DPFPRINTF(("Did not receive expected RFC1323 "
1892 pf_print_state(state);
1893 pf_print_flags(th->th_flags);
1896 REASON_SET(reason, PFRES_TS);
1903 * We will note if a host sends his data packets with or without
1904 * timestamps. And require all data packets to contain a timestamp
1905 * if the first does. PAWS implicitly requires that all data packets be
1906 * timestamped. But I think there are middle-man devices that hijack
1907 * TCP streams immedietly after the 3whs and don't timestamp their
1908 * packets (seen in a WWW accelerator or cache).
1910 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1911 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1913 src->scrub->pfss_flags |= PFSS_DATA_TS;
1915 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1916 if (pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1917 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1918 /* Don't warn if other host rejected RFC1323 */
1919 DPFPRINTF(("Broken RFC1323 stack did not "
1920 "timestamp data packet. Disabled PAWS "
1922 pf_print_state(state);
1923 pf_print_flags(th->th_flags);
1931 * Update PAWS values
1933 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1934 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1935 getmicrouptime(&src->scrub->pfss_last);
1936 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1937 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1938 src->scrub->pfss_tsval = tsval;
1941 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1942 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1943 src->scrub->pfss_tsecr = tsecr;
1945 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1946 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1947 src->scrub->pfss_tsval0 == 0)) {
1948 /* tsval0 MUST be the lowest timestamp */
1949 src->scrub->pfss_tsval0 = tsval;
1952 /* Only fully initialized after a TS gets echoed */
1953 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1954 src->scrub->pfss_flags |= PFSS_PAWS;
1958 /* I have a dream.... TCP segment reassembly.... */
1963 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1968 int opt, cnt, optlen = 0;
1972 thoff = th->th_off << 2;
1973 cnt = thoff - sizeof(struct tcphdr);
1974 optp = mtod(m, caddr_t) + off + sizeof(struct tcphdr);
1976 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1978 if (opt == TCPOPT_EOL)
1980 if (opt == TCPOPT_NOP)
1986 if (optlen < 2 || optlen > cnt)
1991 mss = (u_int16_t *)(optp + 2);
1992 if ((ntohs(*mss)) > r->max_mss) {
1993 th->th_sum = pf_cksum_fixup(th->th_sum,
1994 *mss, htons(r->max_mss), 0);
1995 *mss = htons(r->max_mss);