2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright 2001 Niels Provos <provos@citi.umich.edu>
5 * Copyright 2011-2018 Alexander Bluhm <bluhm@openbsd.org>
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.
28 * $OpenBSD: pf_norm.c,v 1.114 2009/01/29 14:11:45 henning Exp $
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
35 #include "opt_inet6.h"
38 #include <sys/param.h>
39 #include <sys/kernel.h>
42 #include <sys/mutex.h>
43 #include <sys/refcount.h>
44 #include <sys/socket.h>
48 #include <net/pfvar.h>
49 #include <net/if_pflog.h>
51 #include <netinet/in.h>
52 #include <netinet/ip.h>
53 #include <netinet/ip_var.h>
54 #include <netinet6/ip6_var.h>
55 #include <netinet/tcp.h>
56 #include <netinet/tcp_fsm.h>
57 #include <netinet/tcp_seq.h>
60 #include <netinet/ip6.h>
64 TAILQ_ENTRY(pf_frent) fr_next;
66 uint16_t fe_hdrlen; /* ipv4 header length with ip options
67 ipv6, extension, fragment header */
68 uint16_t fe_extoff; /* last extension header offset or 0 */
69 uint16_t fe_len; /* fragment length */
70 uint16_t fe_off; /* fragment offset */
71 uint16_t fe_mff; /* more fragment flag */
74 struct pf_fragment_cmp {
75 struct pf_addr frc_src;
76 struct pf_addr frc_dst;
83 struct pf_fragment_cmp fr_key;
84 #define fr_src fr_key.frc_src
85 #define fr_dst fr_key.frc_dst
86 #define fr_id fr_key.frc_id
87 #define fr_af fr_key.frc_af
88 #define fr_proto fr_key.frc_proto
90 /* pointers to queue element */
91 struct pf_frent *fr_firstoff[PF_FRAG_ENTRY_POINTS];
92 /* count entries between pointers */
93 uint8_t fr_entries[PF_FRAG_ENTRY_POINTS];
94 RB_ENTRY(pf_fragment) fr_entry;
95 TAILQ_ENTRY(pf_fragment) frag_next;
97 uint16_t fr_maxlen; /* maximum length of single fragment */
98 u_int16_t fr_holes; /* number of holes in the queue */
99 TAILQ_HEAD(pf_fragq, pf_frent) fr_queue;
102 struct pf_fragment_tag {
103 uint16_t ft_hdrlen; /* header length of reassembled pkt */
104 uint16_t ft_extoff; /* last extension header offset or 0 */
105 uint16_t ft_maxlen; /* maximum fragment payload length */
106 uint32_t ft_id; /* fragment id */
109 static struct mtx pf_frag_mtx;
110 MTX_SYSINIT(pf_frag_mtx, &pf_frag_mtx, "pf fragments", MTX_DEF);
111 #define PF_FRAG_LOCK() mtx_lock(&pf_frag_mtx)
112 #define PF_FRAG_UNLOCK() mtx_unlock(&pf_frag_mtx)
113 #define PF_FRAG_ASSERT() mtx_assert(&pf_frag_mtx, MA_OWNED)
115 VNET_DEFINE(uma_zone_t, pf_state_scrub_z); /* XXX: shared with pfsync */
117 VNET_DEFINE_STATIC(uma_zone_t, pf_frent_z);
118 #define V_pf_frent_z VNET(pf_frent_z)
119 VNET_DEFINE_STATIC(uma_zone_t, pf_frag_z);
120 #define V_pf_frag_z VNET(pf_frag_z)
122 TAILQ_HEAD(pf_fragqueue, pf_fragment);
123 TAILQ_HEAD(pf_cachequeue, pf_fragment);
124 VNET_DEFINE_STATIC(struct pf_fragqueue, pf_fragqueue);
125 #define V_pf_fragqueue VNET(pf_fragqueue)
126 RB_HEAD(pf_frag_tree, pf_fragment);
127 VNET_DEFINE_STATIC(struct pf_frag_tree, pf_frag_tree);
128 #define V_pf_frag_tree VNET(pf_frag_tree)
129 static int pf_frag_compare(struct pf_fragment *,
130 struct pf_fragment *);
131 static RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
132 static RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
134 static void pf_flush_fragments(void);
135 static void pf_free_fragment(struct pf_fragment *);
136 static void pf_remove_fragment(struct pf_fragment *);
137 static int pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
138 struct tcphdr *, int, sa_family_t);
139 static struct pf_frent *pf_create_fragment(u_short *);
140 static int pf_frent_holes(struct pf_frent *frent);
141 static struct pf_fragment *pf_find_fragment(struct pf_fragment_cmp *key,
142 struct pf_frag_tree *tree);
143 static inline int pf_frent_index(struct pf_frent *);
144 static int pf_frent_insert(struct pf_fragment *,
145 struct pf_frent *, struct pf_frent *);
146 void pf_frent_remove(struct pf_fragment *,
148 struct pf_frent *pf_frent_previous(struct pf_fragment *,
150 static struct pf_fragment *pf_fillup_fragment(struct pf_fragment_cmp *,
151 struct pf_frent *, u_short *);
152 static struct mbuf *pf_join_fragment(struct pf_fragment *);
154 static void pf_scrub_ip(struct mbuf **, uint32_t, uint8_t, uint8_t);
155 static int pf_reassemble(struct mbuf **, struct ip *, int, u_short *);
158 static int pf_reassemble6(struct mbuf **, struct ip6_hdr *,
159 struct ip6_frag *, uint16_t, uint16_t, u_short *);
160 static void pf_scrub_ip6(struct mbuf **, uint8_t);
163 #define DPFPRINTF(x) do { \
164 if (V_pf_status.debug >= PF_DEBUG_MISC) { \
165 printf("%s: ", __func__); \
172 pf_ip2key(struct ip *ip, int dir, struct pf_fragment_cmp *key)
175 key->frc_src.v4 = ip->ip_src;
176 key->frc_dst.v4 = ip->ip_dst;
177 key->frc_af = AF_INET;
178 key->frc_proto = ip->ip_p;
179 key->frc_id = ip->ip_id;
184 pf_normalize_init(void)
187 V_pf_frag_z = uma_zcreate("pf frags", sizeof(struct pf_fragment),
188 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
189 V_pf_frent_z = uma_zcreate("pf frag entries", sizeof(struct pf_frent),
190 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
191 V_pf_state_scrub_z = uma_zcreate("pf state scrubs",
192 sizeof(struct pf_state_scrub), NULL, NULL, NULL, NULL,
195 V_pf_limits[PF_LIMIT_FRAGS].zone = V_pf_frent_z;
196 V_pf_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT;
197 uma_zone_set_max(V_pf_frent_z, PFFRAG_FRENT_HIWAT);
198 uma_zone_set_warning(V_pf_frent_z, "PF frag entries limit reached");
200 TAILQ_INIT(&V_pf_fragqueue);
204 pf_normalize_cleanup(void)
207 uma_zdestroy(V_pf_state_scrub_z);
208 uma_zdestroy(V_pf_frent_z);
209 uma_zdestroy(V_pf_frag_z);
213 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
217 if ((diff = a->fr_id - b->fr_id) != 0)
219 if ((diff = a->fr_proto - b->fr_proto) != 0)
221 if ((diff = a->fr_af - b->fr_af) != 0)
223 if ((diff = pf_addr_cmp(&a->fr_src, &b->fr_src, a->fr_af)) != 0)
225 if ((diff = pf_addr_cmp(&a->fr_dst, &b->fr_dst, a->fr_af)) != 0)
231 pf_purge_expired_fragments(void)
233 u_int32_t expire = time_uptime -
234 V_pf_default_rule.timeout[PFTM_FRAG];
236 pf_purge_fragments(expire);
240 pf_purge_fragments(uint32_t expire)
242 struct pf_fragment *frag;
245 while ((frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue)) != NULL) {
246 if (frag->fr_timeout > expire)
249 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
250 pf_free_fragment(frag);
257 * Try to flush old fragments to make space for new ones
260 pf_flush_fragments(void)
262 struct pf_fragment *frag;
267 goal = uma_zone_get_cur(V_pf_frent_z) * 9 / 10;
268 DPFPRINTF(("trying to free %d frag entriess\n", goal));
269 while (goal < uma_zone_get_cur(V_pf_frent_z)) {
270 frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue);
272 pf_free_fragment(frag);
278 /* Frees the fragments and all associated entries */
280 pf_free_fragment(struct pf_fragment *frag)
282 struct pf_frent *frent;
286 /* Free all fragments */
287 for (frent = TAILQ_FIRST(&frag->fr_queue); frent;
288 frent = TAILQ_FIRST(&frag->fr_queue)) {
289 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
291 m_freem(frent->fe_m);
292 uma_zfree(V_pf_frent_z, frent);
295 pf_remove_fragment(frag);
298 static struct pf_fragment *
299 pf_find_fragment(struct pf_fragment_cmp *key, struct pf_frag_tree *tree)
301 struct pf_fragment *frag;
305 frag = RB_FIND(pf_frag_tree, tree, (struct pf_fragment *)key);
307 /* XXX Are we sure we want to update the timeout? */
308 frag->fr_timeout = time_uptime;
309 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
310 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
316 /* Removes a fragment from the fragment queue and frees the fragment */
318 pf_remove_fragment(struct pf_fragment *frag)
322 KASSERT(frag, ("frag != NULL"));
324 RB_REMOVE(pf_frag_tree, &V_pf_frag_tree, frag);
325 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
326 uma_zfree(V_pf_frag_z, frag);
329 static struct pf_frent *
330 pf_create_fragment(u_short *reason)
332 struct pf_frent *frent;
336 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
338 pf_flush_fragments();
339 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
341 REASON_SET(reason, PFRES_MEMORY);
350 * Calculate the additional holes that were created in the fragment
351 * queue by inserting this fragment. A fragment in the middle
352 * creates one more hole by splitting. For each connected side,
354 * Fragment entry must be in the queue when calling this function.
357 pf_frent_holes(struct pf_frent *frent)
359 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
360 struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
364 if (frent->fe_off == 0)
367 KASSERT(frent->fe_off != 0, ("frent->fe_off != 0"));
368 if (frent->fe_off == prev->fe_off + prev->fe_len)
375 KASSERT(frent->fe_mff, ("frent->fe_mff"));
376 if (next->fe_off == frent->fe_off + frent->fe_len)
383 pf_frent_index(struct pf_frent *frent)
386 * We have an array of 16 entry points to the queue. A full size
387 * 65535 octet IP packet can have 8192 fragments. So the queue
388 * traversal length is at most 512 and at most 16 entry points are
389 * checked. We need 128 additional bytes on a 64 bit architecture.
391 CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) ==
393 CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1);
395 return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS);
399 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent,
400 struct pf_frent *prev)
404 CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff);
407 * A packet has at most 65536 octets. With 16 entry points, each one
408 * spawns 4096 octets. We limit these to 64 fragments each, which
409 * means on average every fragment must have at least 64 octets.
411 index = pf_frent_index(frent);
412 if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT)
414 frag->fr_entries[index]++;
417 TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
419 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
420 ("overlapping fragment"));
421 TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next);
424 if (frag->fr_firstoff[index] == NULL) {
425 KASSERT(prev == NULL || pf_frent_index(prev) < index,
426 ("prev == NULL || pf_frent_index(pref) < index"));
427 frag->fr_firstoff[index] = frent;
429 if (frent->fe_off < frag->fr_firstoff[index]->fe_off) {
430 KASSERT(prev == NULL || pf_frent_index(prev) < index,
431 ("prev == NULL || pf_frent_index(pref) < index"));
432 frag->fr_firstoff[index] = frent;
434 KASSERT(prev != NULL, ("prev != NULL"));
435 KASSERT(pf_frent_index(prev) == index,
436 ("pf_frent_index(prev) == index"));
440 frag->fr_holes += pf_frent_holes(frent);
446 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent)
449 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
451 struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
454 frag->fr_holes -= pf_frent_holes(frent);
456 index = pf_frent_index(frent);
457 KASSERT(frag->fr_firstoff[index] != NULL, ("frent not found"));
458 if (frag->fr_firstoff[index]->fe_off == frent->fe_off) {
460 frag->fr_firstoff[index] = NULL;
462 KASSERT(frent->fe_off + frent->fe_len <= next->fe_off,
463 ("overlapping fragment"));
464 if (pf_frent_index(next) == index) {
465 frag->fr_firstoff[index] = next;
467 frag->fr_firstoff[index] = NULL;
471 KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off,
472 ("frag->fr_firstoff[index]->fe_off < frent->fe_off"));
473 KASSERT(prev != NULL, ("prev != NULL"));
474 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
475 ("overlapping fragment"));
476 KASSERT(pf_frent_index(prev) == index,
477 ("pf_frent_index(prev) == index"));
480 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
482 KASSERT(frag->fr_entries[index] > 0, ("No fragments remaining"));
483 frag->fr_entries[index]--;
487 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent)
489 struct pf_frent *prev, *next;
493 * If there are no fragments after frag, take the final one. Assume
494 * that the global queue is not empty.
496 prev = TAILQ_LAST(&frag->fr_queue, pf_fragq);
497 KASSERT(prev != NULL, ("prev != NULL"));
498 if (prev->fe_off <= frent->fe_off)
501 * We want to find a fragment entry that is before frag, but still
502 * close to it. Find the first fragment entry that is in the same
503 * entry point or in the first entry point after that. As we have
504 * already checked that there are entries behind frag, this will
507 for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS;
509 prev = frag->fr_firstoff[index];
513 KASSERT(prev != NULL, ("prev != NULL"));
515 * In prev we may have a fragment from the same entry point that is
516 * before frent, or one that is just one position behind frent.
517 * In the latter case, we go back one step and have the predecessor.
518 * There may be none if the new fragment will be the first one.
520 if (prev->fe_off > frent->fe_off) {
521 prev = TAILQ_PREV(prev, pf_fragq, fr_next);
524 KASSERT(prev->fe_off <= frent->fe_off,
525 ("prev->fe_off <= frent->fe_off"));
529 * In prev is the first fragment of the entry point. The offset
530 * of frag is behind it. Find the closest previous fragment.
532 for (next = TAILQ_NEXT(prev, fr_next); next != NULL;
533 next = TAILQ_NEXT(next, fr_next)) {
534 if (next->fe_off > frent->fe_off)
541 static struct pf_fragment *
542 pf_fillup_fragment(struct pf_fragment_cmp *key, struct pf_frent *frent,
545 struct pf_frent *after, *next, *prev;
546 struct pf_fragment *frag;
551 /* No empty fragments. */
552 if (frent->fe_len == 0) {
553 DPFPRINTF(("bad fragment: len 0"));
557 /* All fragments are 8 byte aligned. */
558 if (frent->fe_mff && (frent->fe_len & 0x7)) {
559 DPFPRINTF(("bad fragment: mff and len %d", frent->fe_len));
563 /* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET. */
564 if (frent->fe_off + frent->fe_len > IP_MAXPACKET) {
565 DPFPRINTF(("bad fragment: max packet %d",
566 frent->fe_off + frent->fe_len));
570 DPFPRINTF((key->frc_af == AF_INET ?
571 "reass frag %d @ %d-%d" : "reass frag %#08x @ %d-%d",
572 key->frc_id, frent->fe_off, frent->fe_off + frent->fe_len));
574 /* Fully buffer all of the fragments in this fragment queue. */
575 frag = pf_find_fragment(key, &V_pf_frag_tree);
577 /* Create a new reassembly queue for this packet. */
579 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
581 pf_flush_fragments();
582 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
584 REASON_SET(reason, PFRES_MEMORY);
589 *(struct pf_fragment_cmp *)frag = *key;
590 memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff));
591 memset(frag->fr_entries, 0, sizeof(frag->fr_entries));
592 frag->fr_timeout = time_uptime;
593 frag->fr_maxlen = frent->fe_len;
595 TAILQ_INIT(&frag->fr_queue);
597 RB_INSERT(pf_frag_tree, &V_pf_frag_tree, frag);
598 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
600 /* We do not have a previous fragment, cannot fail. */
601 pf_frent_insert(frag, frent, NULL);
606 KASSERT(!TAILQ_EMPTY(&frag->fr_queue), ("!TAILQ_EMPTY()->fr_queue"));
608 /* Remember maximum fragment len for refragmentation. */
609 if (frent->fe_len > frag->fr_maxlen)
610 frag->fr_maxlen = frent->fe_len;
612 /* Maximum data we have seen already. */
613 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
614 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
616 /* Non terminal fragments must have more fragments flag. */
617 if (frent->fe_off + frent->fe_len < total && !frent->fe_mff)
620 /* Check if we saw the last fragment already. */
621 if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) {
622 if (frent->fe_off + frent->fe_len > total ||
623 (frent->fe_off + frent->fe_len == total && frent->fe_mff))
626 if (frent->fe_off + frent->fe_len == total && !frent->fe_mff)
630 /* Find neighbors for newly inserted fragment */
631 prev = pf_frent_previous(frag, frent);
633 after = TAILQ_FIRST(&frag->fr_queue);
634 KASSERT(after != NULL, ("after != NULL"));
636 after = TAILQ_NEXT(prev, fr_next);
639 if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) {
642 precut = prev->fe_off + prev->fe_len - frent->fe_off;
643 if (precut >= frent->fe_len)
645 DPFPRINTF(("overlap -%d", precut));
646 m_adj(frent->fe_m, precut);
647 frent->fe_off += precut;
648 frent->fe_len -= precut;
651 for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off;
655 aftercut = frent->fe_off + frent->fe_len - after->fe_off;
656 DPFPRINTF(("adjust overlap %d", aftercut));
657 if (aftercut < after->fe_len) {
658 m_adj(after->fe_m, aftercut);
659 after->fe_off += aftercut;
660 after->fe_len -= aftercut;
664 /* This fragment is completely overlapped, lose it. */
665 next = TAILQ_NEXT(after, fr_next);
666 pf_frent_remove(frag, after);
667 m_freem(after->fe_m);
668 uma_zfree(V_pf_frent_z, after);
671 /* If part of the queue gets too long, there is not way to recover. */
672 if (pf_frent_insert(frag, frent, prev)) {
673 DPFPRINTF(("fragment queue limit exceeded"));
680 REASON_SET(reason, PFRES_FRAG);
682 uma_zfree(V_pf_frent_z, frent);
687 pf_join_fragment(struct pf_fragment *frag)
690 struct pf_frent *frent, *next;
692 frent = TAILQ_FIRST(&frag->fr_queue);
693 next = TAILQ_NEXT(frent, fr_next);
696 m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len);
697 uma_zfree(V_pf_frent_z, frent);
698 for (frent = next; frent != NULL; frent = next) {
699 next = TAILQ_NEXT(frent, fr_next);
702 /* Strip off ip header. */
703 m_adj(m2, frent->fe_hdrlen);
704 /* Strip off any trailing bytes. */
705 m_adj(m2, frent->fe_len - m2->m_pkthdr.len);
707 uma_zfree(V_pf_frent_z, frent);
711 /* Remove from fragment queue. */
712 pf_remove_fragment(frag);
719 pf_reassemble(struct mbuf **m0, struct ip *ip, int dir, u_short *reason)
721 struct mbuf *m = *m0;
722 struct pf_frent *frent;
723 struct pf_fragment *frag;
724 struct pf_fragment_cmp key;
725 uint16_t total, hdrlen;
727 /* Get an entry for the fragment queue */
728 if ((frent = pf_create_fragment(reason)) == NULL)
732 frent->fe_hdrlen = ip->ip_hl << 2;
733 frent->fe_extoff = 0;
734 frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
735 frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
736 frent->fe_mff = ntohs(ip->ip_off) & IP_MF;
738 pf_ip2key(ip, dir, &key);
740 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL)
743 /* The mbuf is part of the fragment entry, no direct free or access */
746 if (frag->fr_holes) {
747 DPFPRINTF(("frag %d, holes %d", frag->fr_id, frag->fr_holes));
748 return (PF_PASS); /* drop because *m0 is NULL, no error */
751 /* We have all the data */
752 frent = TAILQ_FIRST(&frag->fr_queue);
753 KASSERT(frent != NULL, ("frent != NULL"));
754 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
755 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
756 hdrlen = frent->fe_hdrlen;
758 m = *m0 = pf_join_fragment(frag);
761 if (m->m_flags & M_PKTHDR) {
763 for (m = *m0; m; m = m->m_next)
766 m->m_pkthdr.len = plen;
769 ip = mtod(m, struct ip *);
770 ip->ip_len = htons(hdrlen + total);
771 ip->ip_off &= ~(IP_MF|IP_OFFMASK);
773 if (hdrlen + total > IP_MAXPACKET) {
774 DPFPRINTF(("drop: too big: %d", total));
776 REASON_SET(reason, PFRES_SHORT);
777 /* PF_DROP requires a valid mbuf *m0 in pf_test() */
781 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip->ip_len)));
788 pf_reassemble6(struct mbuf **m0, struct ip6_hdr *ip6, struct ip6_frag *fraghdr,
789 uint16_t hdrlen, uint16_t extoff, u_short *reason)
791 struct mbuf *m = *m0;
792 struct pf_frent *frent;
793 struct pf_fragment *frag;
794 struct pf_fragment_cmp key;
796 struct pf_fragment_tag *ftag;
799 uint16_t total, maxlen;
804 /* Get an entry for the fragment queue. */
805 if ((frent = pf_create_fragment(reason)) == NULL) {
811 frent->fe_hdrlen = hdrlen;
812 frent->fe_extoff = extoff;
813 frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen;
814 frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK);
815 frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG;
817 key.frc_src.v6 = ip6->ip6_src;
818 key.frc_dst.v6 = ip6->ip6_dst;
819 key.frc_af = AF_INET6;
820 /* Only the first fragment's protocol is relevant. */
822 key.frc_id = fraghdr->ip6f_ident;
824 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL) {
829 /* The mbuf is part of the fragment entry, no direct free or access. */
832 if (frag->fr_holes) {
833 DPFPRINTF(("frag %d, holes %d", frag->fr_id, frag->fr_holes));
835 return (PF_PASS); /* Drop because *m0 is NULL, no error. */
838 /* We have all the data. */
839 frent = TAILQ_FIRST(&frag->fr_queue);
840 KASSERT(frent != NULL, ("frent != NULL"));
841 extoff = frent->fe_extoff;
842 maxlen = frag->fr_maxlen;
843 frag_id = frag->fr_id;
844 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
845 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
846 hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
848 m = *m0 = pf_join_fragment(frag);
853 /* Take protocol from first fragment header. */
854 m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off);
855 KASSERT(m, ("%s: short mbuf chain", __func__));
856 proto = *(mtod(m, caddr_t) + off);
859 /* Delete frag6 header */
860 if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0)
863 if (m->m_flags & M_PKTHDR) {
865 for (m = *m0; m; m = m->m_next)
868 m->m_pkthdr.len = plen;
871 if ((mtag = m_tag_get(PF_REASSEMBLED, sizeof(struct pf_fragment_tag),
874 ftag = (struct pf_fragment_tag *)(mtag + 1);
875 ftag->ft_hdrlen = hdrlen;
876 ftag->ft_extoff = extoff;
877 ftag->ft_maxlen = maxlen;
878 ftag->ft_id = frag_id;
879 m_tag_prepend(m, mtag);
881 ip6 = mtod(m, struct ip6_hdr *);
882 ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
884 /* Write protocol into next field of last extension header. */
885 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
887 KASSERT(m, ("%s: short mbuf chain", __func__));
888 *(mtod(m, char *) + off) = proto;
891 ip6->ip6_nxt = proto;
893 if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
894 DPFPRINTF(("drop: too big: %d", total));
896 REASON_SET(reason, PFRES_SHORT);
897 /* PF_DROP requires a valid mbuf *m0 in pf_test6(). */
901 DPFPRINTF(("complete: %p(%d)", m, ntohs(ip6->ip6_plen)));
905 REASON_SET(reason, PFRES_MEMORY);
906 /* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */
913 pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag)
915 struct mbuf *m = *m0, *t;
916 struct pf_fragment_tag *ftag = (struct pf_fragment_tag *)(mtag + 1);
919 uint16_t hdrlen, extoff, maxlen;
923 hdrlen = ftag->ft_hdrlen;
924 extoff = ftag->ft_extoff;
925 maxlen = ftag->ft_maxlen;
926 frag_id = ftag->ft_id;
927 m_tag_delete(m, mtag);
934 /* Use protocol from next field of last extension header */
935 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
937 KASSERT((m != NULL), ("pf_refragment6: short mbuf chain"));
938 proto = *(mtod(m, caddr_t) + off);
939 *(mtod(m, char *) + off) = IPPROTO_FRAGMENT;
944 hdr = mtod(m, struct ip6_hdr *);
945 proto = hdr->ip6_nxt;
946 hdr->ip6_nxt = IPPROTO_FRAGMENT;
949 /* The MTU must be a multiple of 8 bytes, or we risk doing the
950 * fragmentation wrong. */
951 maxlen = maxlen & ~7;
954 * Maxlen may be less than 8 if there was only a single
955 * fragment. As it was fragmented before, add a fragment
956 * header also for a single fragment. If total or maxlen
957 * is less than 8, ip6_fragment() will return EMSGSIZE and
958 * we drop the packet.
960 error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
961 m = (*m0)->m_nextpkt;
962 (*m0)->m_nextpkt = NULL;
964 /* The first mbuf contains the unfragmented packet. */
969 /* Drop expects an mbuf to free. */
970 DPFPRINTF(("refragment error %d", error));
973 for (t = m; m; m = t) {
976 m->m_flags |= M_SKIP_FIREWALL;
977 memset(&pd, 0, sizeof(pd));
978 pd.pf_mtag = pf_find_mtag(m);
991 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
994 struct mbuf *m = *m0;
996 struct ip *h = mtod(m, struct ip *);
997 int mff = (ntohs(h->ip_off) & IP_MF);
998 int hlen = h->ip_hl << 2;
999 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1008 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1011 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1012 r = r->skip[PF_SKIP_IFP].ptr;
1013 else if (r->direction && r->direction != dir)
1014 r = r->skip[PF_SKIP_DIR].ptr;
1015 else if (r->af && r->af != AF_INET)
1016 r = r->skip[PF_SKIP_AF].ptr;
1017 else if (r->proto && r->proto != h->ip_p)
1018 r = r->skip[PF_SKIP_PROTO].ptr;
1019 else if (PF_MISMATCHAW(&r->src.addr,
1020 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
1021 r->src.neg, kif, M_GETFIB(m)))
1022 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1023 else if (PF_MISMATCHAW(&r->dst.addr,
1024 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
1025 r->dst.neg, NULL, M_GETFIB(m)))
1026 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1027 else if (r->match_tag && !pf_match_tag(m, r, &tag,
1028 pd->pf_mtag ? pd->pf_mtag->tag : 0))
1029 r = TAILQ_NEXT(r, entries);
1034 if (r == NULL || r->action == PF_NOSCRUB)
1037 r->packets[dir == PF_OUT]++;
1038 r->bytes[dir == PF_OUT] += pd->tot_len;
1041 /* Check for illegal packets */
1042 if (hlen < (int)sizeof(struct ip)) {
1043 REASON_SET(reason, PFRES_NORM);
1047 if (hlen > ntohs(h->ip_len)) {
1048 REASON_SET(reason, PFRES_NORM);
1052 /* Clear IP_DF if the rule uses the no-df option */
1053 if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1054 u_int16_t ip_off = h->ip_off;
1056 h->ip_off &= htons(~IP_DF);
1057 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1060 /* We will need other tests here */
1061 if (!fragoff && !mff)
1064 /* We're dealing with a fragment now. Don't allow fragments
1065 * with IP_DF to enter the cache. If the flag was cleared by
1066 * no-df above, fine. Otherwise drop it.
1068 if (h->ip_off & htons(IP_DF)) {
1069 DPFPRINTF(("IP_DF\n"));
1073 ip_len = ntohs(h->ip_len) - hlen;
1074 ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1076 /* All fragments are 8 byte aligned */
1077 if (mff && (ip_len & 0x7)) {
1078 DPFPRINTF(("mff and %d\n", ip_len));
1082 /* Respect maximum length */
1083 if (fragoff + ip_len > IP_MAXPACKET) {
1084 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
1087 max = fragoff + ip_len;
1089 /* Fully buffer all of the fragments
1090 * Might return a completely reassembled mbuf, or NULL */
1092 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
1093 verdict = pf_reassemble(m0, h, dir, reason);
1096 if (verdict != PF_PASS)
1103 h = mtod(m, struct ip *);
1106 /* At this point, only IP_DF is allowed in ip_off */
1107 if (h->ip_off & ~htons(IP_DF)) {
1108 u_int16_t ip_off = h->ip_off;
1110 h->ip_off &= htons(IP_DF);
1111 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1114 pf_scrub_ip(&m, r->rule_flag, r->min_ttl, r->set_tos);
1119 DPFPRINTF(("dropping bad fragment\n"));
1120 REASON_SET(reason, PFRES_FRAG);
1122 if (r != NULL && r->log)
1123 PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
1132 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1133 u_short *reason, struct pf_pdesc *pd)
1135 struct mbuf *m = *m0;
1137 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1142 struct ip6_opt_jumbo jumbo;
1143 struct ip6_frag frag;
1144 u_int32_t jumbolen = 0, plen;
1152 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1155 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1156 r = r->skip[PF_SKIP_IFP].ptr;
1157 else if (r->direction && r->direction != dir)
1158 r = r->skip[PF_SKIP_DIR].ptr;
1159 else if (r->af && r->af != AF_INET6)
1160 r = r->skip[PF_SKIP_AF].ptr;
1161 #if 0 /* header chain! */
1162 else if (r->proto && r->proto != h->ip6_nxt)
1163 r = r->skip[PF_SKIP_PROTO].ptr;
1165 else if (PF_MISMATCHAW(&r->src.addr,
1166 (struct pf_addr *)&h->ip6_src, AF_INET6,
1167 r->src.neg, kif, M_GETFIB(m)))
1168 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1169 else if (PF_MISMATCHAW(&r->dst.addr,
1170 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1171 r->dst.neg, NULL, M_GETFIB(m)))
1172 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1177 if (r == NULL || r->action == PF_NOSCRUB)
1180 r->packets[dir == PF_OUT]++;
1181 r->bytes[dir == PF_OUT] += pd->tot_len;
1184 /* Check for illegal packets */
1185 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1189 off = sizeof(struct ip6_hdr);
1194 case IPPROTO_FRAGMENT:
1198 case IPPROTO_ROUTING:
1199 case IPPROTO_DSTOPTS:
1200 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1204 if (proto == IPPROTO_AH)
1205 off += (ext.ip6e_len + 2) * 4;
1207 off += (ext.ip6e_len + 1) * 8;
1208 proto = ext.ip6e_nxt;
1210 case IPPROTO_HOPOPTS:
1211 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1215 optend = off + (ext.ip6e_len + 1) * 8;
1216 ooff = off + sizeof(ext);
1218 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1219 sizeof(opt.ip6o_type), NULL, NULL,
1222 if (opt.ip6o_type == IP6OPT_PAD1) {
1226 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1227 NULL, NULL, AF_INET6))
1229 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1231 switch (opt.ip6o_type) {
1233 if (h->ip6_plen != 0)
1235 if (!pf_pull_hdr(m, ooff, &jumbo,
1236 sizeof(jumbo), NULL, NULL,
1239 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1241 jumbolen = ntohl(jumbolen);
1242 if (jumbolen <= IPV6_MAXPACKET)
1244 if (sizeof(struct ip6_hdr) + jumbolen !=
1251 ooff += sizeof(opt) + opt.ip6o_len;
1252 } while (ooff < optend);
1255 proto = ext.ip6e_nxt;
1261 } while (!terminal);
1263 /* jumbo payload option must be present, or plen > 0 */
1264 if (ntohs(h->ip6_plen) == 0)
1267 plen = ntohs(h->ip6_plen);
1270 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1273 pf_scrub_ip6(&m, r->min_ttl);
1278 /* Jumbo payload packets cannot be fragmented. */
1279 plen = ntohs(h->ip6_plen);
1280 if (plen == 0 || jumbolen)
1282 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1285 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1288 /* Offset now points to data portion. */
1289 off += sizeof(frag);
1291 /* Returns PF_DROP or *m0 is NULL or completely reassembled mbuf. */
1292 if (pf_reassemble6(m0, h, &frag, off, extoff, reason) != PF_PASS)
1298 pd->flags |= PFDESC_IP_REAS;
1302 REASON_SET(reason, PFRES_SHORT);
1303 if (r != NULL && r->log)
1304 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1309 REASON_SET(reason, PFRES_NORM);
1310 if (r != NULL && r->log)
1311 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1318 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1319 int off, void *h, struct pf_pdesc *pd)
1321 struct pf_rule *r, *rm = NULL;
1322 struct tcphdr *th = pd->hdr.tcp;
1326 sa_family_t af = pd->af;
1330 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1333 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1334 r = r->skip[PF_SKIP_IFP].ptr;
1335 else if (r->direction && r->direction != dir)
1336 r = r->skip[PF_SKIP_DIR].ptr;
1337 else if (r->af && r->af != af)
1338 r = r->skip[PF_SKIP_AF].ptr;
1339 else if (r->proto && r->proto != pd->proto)
1340 r = r->skip[PF_SKIP_PROTO].ptr;
1341 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1342 r->src.neg, kif, M_GETFIB(m)))
1343 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1344 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1345 r->src.port[0], r->src.port[1], th->th_sport))
1346 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1347 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1348 r->dst.neg, NULL, M_GETFIB(m)))
1349 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1350 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1351 r->dst.port[0], r->dst.port[1], th->th_dport))
1352 r = r->skip[PF_SKIP_DST_PORT].ptr;
1353 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1354 pf_osfp_fingerprint(pd, m, off, th),
1356 r = TAILQ_NEXT(r, entries);
1363 if (rm == NULL || rm->action == PF_NOSCRUB)
1366 r->packets[dir == PF_OUT]++;
1367 r->bytes[dir == PF_OUT] += pd->tot_len;
1370 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1371 pd->flags |= PFDESC_TCP_NORM;
1373 flags = th->th_flags;
1374 if (flags & TH_SYN) {
1375 /* Illegal packet */
1382 /* Illegal packet */
1383 if (!(flags & (TH_ACK|TH_RST)))
1387 if (!(flags & TH_ACK)) {
1388 /* These flags are only valid if ACK is set */
1389 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1393 /* Check for illegal header length */
1394 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1397 /* If flags changed, or reserved data set, then adjust */
1398 if (flags != th->th_flags || th->th_x2 != 0) {
1401 ov = *(u_int16_t *)(&th->th_ack + 1);
1402 th->th_flags = flags;
1404 nv = *(u_int16_t *)(&th->th_ack + 1);
1406 th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, ov, nv, 0);
1410 /* Remove urgent pointer, if TH_URG is not set */
1411 if (!(flags & TH_URG) && th->th_urp) {
1412 th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, th->th_urp,
1418 /* Process options */
1419 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1422 /* copy back packet headers if we sanitized */
1424 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1429 REASON_SET(&reason, PFRES_NORM);
1430 if (rm != NULL && r->log)
1431 PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1437 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1438 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1440 u_int32_t tsval, tsecr;
1444 KASSERT((src->scrub == NULL),
1445 ("pf_normalize_tcp_init: src->scrub != NULL"));
1447 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1448 if (src->scrub == NULL)
1454 struct ip *h = mtod(m, struct ip *);
1455 src->scrub->pfss_ttl = h->ip_ttl;
1461 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1462 src->scrub->pfss_ttl = h->ip6_hlim;
1470 * All normalizations below are only begun if we see the start of
1471 * the connections. They must all set an enabled bit in pfss_flags
1473 if ((th->th_flags & TH_SYN) == 0)
1477 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1478 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1479 /* Diddle with TCP options */
1481 opt = hdr + sizeof(struct tcphdr);
1482 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1483 while (hlen >= TCPOLEN_TIMESTAMP) {
1485 case TCPOPT_EOL: /* FALLTHROUGH */
1490 case TCPOPT_TIMESTAMP:
1491 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1492 src->scrub->pfss_flags |=
1494 src->scrub->pfss_ts_mod =
1495 htonl(arc4random());
1497 /* note PFSS_PAWS not set yet */
1498 memcpy(&tsval, &opt[2],
1500 memcpy(&tsecr, &opt[6],
1502 src->scrub->pfss_tsval0 = ntohl(tsval);
1503 src->scrub->pfss_tsval = ntohl(tsval);
1504 src->scrub->pfss_tsecr = ntohl(tsecr);
1505 getmicrouptime(&src->scrub->pfss_last);
1509 hlen -= MAX(opt[1], 2);
1510 opt += MAX(opt[1], 2);
1520 pf_normalize_tcp_cleanup(struct pf_state *state)
1522 if (state->src.scrub)
1523 uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1524 if (state->dst.scrub)
1525 uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1527 /* Someday... flush the TCP segment reassembly descriptors. */
1531 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1532 u_short *reason, struct tcphdr *th, struct pf_state *state,
1533 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1535 struct timeval uptime;
1536 u_int32_t tsval, tsecr;
1537 u_int tsval_from_last;
1543 KASSERT((src->scrub || dst->scrub),
1544 ("%s: src->scrub && dst->scrub!", __func__));
1547 * Enforce the minimum TTL seen for this connection. Negate a common
1548 * technique to evade an intrusion detection system and confuse
1549 * firewall state code.
1555 struct ip *h = mtod(m, struct ip *);
1556 if (h->ip_ttl > src->scrub->pfss_ttl)
1557 src->scrub->pfss_ttl = h->ip_ttl;
1558 h->ip_ttl = src->scrub->pfss_ttl;
1566 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1567 if (h->ip6_hlim > src->scrub->pfss_ttl)
1568 src->scrub->pfss_ttl = h->ip6_hlim;
1569 h->ip6_hlim = src->scrub->pfss_ttl;
1576 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1577 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1578 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1579 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1580 /* Diddle with TCP options */
1582 opt = hdr + sizeof(struct tcphdr);
1583 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1584 while (hlen >= TCPOLEN_TIMESTAMP) {
1586 case TCPOPT_EOL: /* FALLTHROUGH */
1591 case TCPOPT_TIMESTAMP:
1592 /* Modulate the timestamps. Can be used for
1593 * NAT detection, OS uptime determination or
1598 /* Huh? Multiple timestamps!? */
1599 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1600 DPFPRINTF(("multiple TS??"));
1601 pf_print_state(state);
1604 REASON_SET(reason, PFRES_TS);
1607 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1608 memcpy(&tsval, &opt[2],
1610 if (tsval && src->scrub &&
1611 (src->scrub->pfss_flags &
1613 tsval = ntohl(tsval);
1614 pf_change_proto_a(m, &opt[2],
1617 src->scrub->pfss_ts_mod),
1622 /* Modulate TS reply iff valid (!0) */
1623 memcpy(&tsecr, &opt[6],
1625 if (tsecr && dst->scrub &&
1626 (dst->scrub->pfss_flags &
1628 tsecr = ntohl(tsecr)
1629 - dst->scrub->pfss_ts_mod;
1630 pf_change_proto_a(m, &opt[6],
1631 &th->th_sum, htonl(tsecr),
1639 hlen -= MAX(opt[1], 2);
1640 opt += MAX(opt[1], 2);
1645 /* Copyback the options, caller copys back header */
1647 m_copyback(m, off + sizeof(struct tcphdr),
1648 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1649 sizeof(struct tcphdr));
1655 * Must invalidate PAWS checks on connections idle for too long.
1656 * The fastest allowed timestamp clock is 1ms. That turns out to
1657 * be about 24 days before it wraps. XXX Right now our lowerbound
1658 * TS echo check only works for the first 12 days of a connection
1659 * when the TS has exhausted half its 32bit space
1661 #define TS_MAX_IDLE (24*24*60*60)
1662 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1664 getmicrouptime(&uptime);
1665 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1666 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1667 time_uptime - state->creation > TS_MAX_CONN)) {
1668 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1669 DPFPRINTF(("src idled out of PAWS\n"));
1670 pf_print_state(state);
1673 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1676 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1677 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1678 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1679 DPFPRINTF(("dst idled out of PAWS\n"));
1680 pf_print_state(state);
1683 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1687 if (got_ts && src->scrub && dst->scrub &&
1688 (src->scrub->pfss_flags & PFSS_PAWS) &&
1689 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1690 /* Validate that the timestamps are "in-window".
1691 * RFC1323 describes TCP Timestamp options that allow
1692 * measurement of RTT (round trip time) and PAWS
1693 * (protection against wrapped sequence numbers). PAWS
1694 * gives us a set of rules for rejecting packets on
1695 * long fat pipes (packets that were somehow delayed
1696 * in transit longer than the time it took to send the
1697 * full TCP sequence space of 4Gb). We can use these
1698 * rules and infer a few others that will let us treat
1699 * the 32bit timestamp and the 32bit echoed timestamp
1700 * as sequence numbers to prevent a blind attacker from
1701 * inserting packets into a connection.
1704 * - The timestamp on this packet must be greater than
1705 * or equal to the last value echoed by the other
1706 * endpoint. The RFC says those will be discarded
1707 * since it is a dup that has already been acked.
1708 * This gives us a lowerbound on the timestamp.
1709 * timestamp >= other last echoed timestamp
1710 * - The timestamp will be less than or equal to
1711 * the last timestamp plus the time between the
1712 * last packet and now. The RFC defines the max
1713 * clock rate as 1ms. We will allow clocks to be
1714 * up to 10% fast and will allow a total difference
1715 * or 30 seconds due to a route change. And this
1716 * gives us an upperbound on the timestamp.
1717 * timestamp <= last timestamp + max ticks
1718 * We have to be careful here. Windows will send an
1719 * initial timestamp of zero and then initialize it
1720 * to a random value after the 3whs; presumably to
1721 * avoid a DoS by having to call an expensive RNG
1722 * during a SYN flood. Proof MS has at least one
1723 * good security geek.
1725 * - The TCP timestamp option must also echo the other
1726 * endpoints timestamp. The timestamp echoed is the
1727 * one carried on the earliest unacknowledged segment
1728 * on the left edge of the sequence window. The RFC
1729 * states that the host will reject any echoed
1730 * timestamps that were larger than any ever sent.
1731 * This gives us an upperbound on the TS echo.
1732 * tescr <= largest_tsval
1733 * - The lowerbound on the TS echo is a little more
1734 * tricky to determine. The other endpoint's echoed
1735 * values will not decrease. But there may be
1736 * network conditions that re-order packets and
1737 * cause our view of them to decrease. For now the
1738 * only lowerbound we can safely determine is that
1739 * the TS echo will never be less than the original
1740 * TS. XXX There is probably a better lowerbound.
1741 * Remove TS_MAX_CONN with better lowerbound check.
1742 * tescr >= other original TS
1744 * It is also important to note that the fastest
1745 * timestamp clock of 1ms will wrap its 32bit space in
1746 * 24 days. So we just disable TS checking after 24
1747 * days of idle time. We actually must use a 12d
1748 * connection limit until we can come up with a better
1749 * lowerbound to the TS echo check.
1751 struct timeval delta_ts;
1756 * PFTM_TS_DIFF is how many seconds of leeway to allow
1757 * a host's timestamp. This can happen if the previous
1758 * packet got delayed in transit for much longer than
1761 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1762 ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1764 /* Calculate max ticks since the last timestamp */
1765 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1766 #define TS_MICROSECS 1000000 /* microseconds per second */
1768 timevalsub(&delta_ts, &src->scrub->pfss_last);
1769 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1770 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1772 if ((src->state >= TCPS_ESTABLISHED &&
1773 dst->state >= TCPS_ESTABLISHED) &&
1774 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1775 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1776 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1777 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1778 /* Bad RFC1323 implementation or an insertion attack.
1780 * - Solaris 2.6 and 2.7 are known to send another ACK
1781 * after the FIN,FIN|ACK,ACK closing that carries
1785 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1786 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1787 SEQ_GT(tsval, src->scrub->pfss_tsval +
1788 tsval_from_last) ? '1' : ' ',
1789 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1790 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1791 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1792 "idle: %jus %lums\n",
1793 tsval, tsecr, tsval_from_last,
1794 (uintmax_t)delta_ts.tv_sec,
1795 delta_ts.tv_usec / 1000));
1796 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1797 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1798 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1799 "\n", dst->scrub->pfss_tsval,
1800 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1801 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1802 pf_print_state(state);
1803 pf_print_flags(th->th_flags);
1806 REASON_SET(reason, PFRES_TS);
1810 /* XXX I'd really like to require tsecr but it's optional */
1812 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1813 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1814 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1815 src->scrub && dst->scrub &&
1816 (src->scrub->pfss_flags & PFSS_PAWS) &&
1817 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1818 /* Didn't send a timestamp. Timestamps aren't really useful
1820 * - connection opening or closing (often not even sent).
1821 * but we must not let an attacker to put a FIN on a
1822 * data packet to sneak it through our ESTABLISHED check.
1823 * - on a TCP reset. RFC suggests not even looking at TS.
1824 * - on an empty ACK. The TS will not be echoed so it will
1825 * probably not help keep the RTT calculation in sync and
1826 * there isn't as much danger when the sequence numbers
1827 * got wrapped. So some stacks don't include TS on empty
1830 * To minimize the disruption to mostly RFC1323 conformant
1831 * stacks, we will only require timestamps on data packets.
1833 * And what do ya know, we cannot require timestamps on data
1834 * packets. There appear to be devices that do legitimate
1835 * TCP connection hijacking. There are HTTP devices that allow
1836 * a 3whs (with timestamps) and then buffer the HTTP request.
1837 * If the intermediate device has the HTTP response cache, it
1838 * will spoof the response but not bother timestamping its
1839 * packets. So we can look for the presence of a timestamp in
1840 * the first data packet and if there, require it in all future
1844 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1846 * Hey! Someone tried to sneak a packet in. Or the
1847 * stack changed its RFC1323 behavior?!?!
1849 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1850 DPFPRINTF(("Did not receive expected RFC1323 "
1852 pf_print_state(state);
1853 pf_print_flags(th->th_flags);
1856 REASON_SET(reason, PFRES_TS);
1863 * We will note if a host sends his data packets with or without
1864 * timestamps. And require all data packets to contain a timestamp
1865 * if the first does. PAWS implicitly requires that all data packets be
1866 * timestamped. But I think there are middle-man devices that hijack
1867 * TCP streams immediately after the 3whs and don't timestamp their
1868 * packets (seen in a WWW accelerator or cache).
1870 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1871 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1873 src->scrub->pfss_flags |= PFSS_DATA_TS;
1875 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1876 if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1877 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1878 /* Don't warn if other host rejected RFC1323 */
1879 DPFPRINTF(("Broken RFC1323 stack did not "
1880 "timestamp data packet. Disabled PAWS "
1882 pf_print_state(state);
1883 pf_print_flags(th->th_flags);
1891 * Update PAWS values
1893 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1894 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1895 getmicrouptime(&src->scrub->pfss_last);
1896 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1897 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1898 src->scrub->pfss_tsval = tsval;
1901 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1902 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1903 src->scrub->pfss_tsecr = tsecr;
1905 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1906 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1907 src->scrub->pfss_tsval0 == 0)) {
1908 /* tsval0 MUST be the lowest timestamp */
1909 src->scrub->pfss_tsval0 = tsval;
1912 /* Only fully initialized after a TS gets echoed */
1913 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1914 src->scrub->pfss_flags |= PFSS_PAWS;
1918 /* I have a dream.... TCP segment reassembly.... */
1923 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1924 int off, sa_family_t af)
1928 int opt, cnt, optlen = 0;
1930 u_char opts[TCP_MAXOLEN];
1931 u_char *optp = opts;
1933 thoff = th->th_off << 2;
1934 cnt = thoff - sizeof(struct tcphdr);
1936 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1940 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1942 if (opt == TCPOPT_EOL)
1944 if (opt == TCPOPT_NOP)
1950 if (optlen < 2 || optlen > cnt)
1955 mss = (u_int16_t *)(optp + 2);
1956 if ((ntohs(*mss)) > r->max_mss) {
1957 th->th_sum = pf_proto_cksum_fixup(m,
1958 th->th_sum, *mss, htons(r->max_mss), 0);
1959 *mss = htons(r->max_mss);
1969 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1976 pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
1978 struct mbuf *m = *m0;
1979 struct ip *h = mtod(m, struct ip *);
1981 /* Clear IP_DF if no-df was requested */
1982 if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1983 u_int16_t ip_off = h->ip_off;
1985 h->ip_off &= htons(~IP_DF);
1986 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1989 /* Enforce a minimum ttl, may cause endless packet loops */
1990 if (min_ttl && h->ip_ttl < min_ttl) {
1991 u_int16_t ip_ttl = h->ip_ttl;
1993 h->ip_ttl = min_ttl;
1994 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1998 if (flags & PFRULE_SET_TOS) {
2001 ov = *(u_int16_t *)h;
2002 h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK);
2003 nv = *(u_int16_t *)h;
2005 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
2008 /* random-id, but not for fragments */
2009 if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
2010 uint16_t ip_id = h->ip_id;
2013 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
2020 pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
2022 struct mbuf *m = *m0;
2023 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
2025 /* Enforce a minimum ttl, may cause endless packet loops */
2026 if (min_ttl && h->ip6_hlim < min_ttl)
2027 h->ip6_hlim = min_ttl;