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 VNET_DEFINE_STATIC(struct mtx, pf_frag_mtx);
110 #define V_pf_frag_mtx VNET(pf_frag_mtx)
111 #define PF_FRAG_LOCK() mtx_lock(&V_pf_frag_mtx)
112 #define PF_FRAG_UNLOCK() mtx_unlock(&V_pf_frag_mtx)
113 #define PF_FRAG_ASSERT() mtx_assert(&V_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_krule *, 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 mtx_init(&V_pf_frag_mtx, "pf fragments", NULL, MTX_DEF);
197 V_pf_limits[PF_LIMIT_FRAGS].zone = V_pf_frent_z;
198 V_pf_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT;
199 uma_zone_set_max(V_pf_frent_z, PFFRAG_FRENT_HIWAT);
200 uma_zone_set_warning(V_pf_frent_z, "PF frag entries limit reached");
202 TAILQ_INIT(&V_pf_fragqueue);
206 pf_normalize_cleanup(void)
209 uma_zdestroy(V_pf_state_scrub_z);
210 uma_zdestroy(V_pf_frent_z);
211 uma_zdestroy(V_pf_frag_z);
213 mtx_destroy(&V_pf_frag_mtx);
217 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
221 if ((diff = a->fr_id - b->fr_id) != 0)
223 if ((diff = a->fr_proto - b->fr_proto) != 0)
225 if ((diff = a->fr_af - b->fr_af) != 0)
227 if ((diff = pf_addr_cmp(&a->fr_src, &b->fr_src, a->fr_af)) != 0)
229 if ((diff = pf_addr_cmp(&a->fr_dst, &b->fr_dst, a->fr_af)) != 0)
235 pf_purge_expired_fragments(void)
237 u_int32_t expire = time_uptime -
238 V_pf_default_rule.timeout[PFTM_FRAG];
240 pf_purge_fragments(expire);
244 pf_purge_fragments(uint32_t expire)
246 struct pf_fragment *frag;
249 while ((frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue)) != NULL) {
250 if (frag->fr_timeout > expire)
253 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
254 pf_free_fragment(frag);
261 * Try to flush old fragments to make space for new ones
264 pf_flush_fragments(void)
266 struct pf_fragment *frag;
271 goal = uma_zone_get_cur(V_pf_frent_z) * 9 / 10;
272 DPFPRINTF(("trying to free %d frag entriess\n", goal));
273 while (goal < uma_zone_get_cur(V_pf_frent_z)) {
274 frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue);
276 pf_free_fragment(frag);
282 /* Frees the fragments and all associated entries */
284 pf_free_fragment(struct pf_fragment *frag)
286 struct pf_frent *frent;
290 /* Free all fragments */
291 for (frent = TAILQ_FIRST(&frag->fr_queue); frent;
292 frent = TAILQ_FIRST(&frag->fr_queue)) {
293 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
295 m_freem(frent->fe_m);
296 uma_zfree(V_pf_frent_z, frent);
299 pf_remove_fragment(frag);
302 static struct pf_fragment *
303 pf_find_fragment(struct pf_fragment_cmp *key, struct pf_frag_tree *tree)
305 struct pf_fragment *frag;
309 frag = RB_FIND(pf_frag_tree, tree, (struct pf_fragment *)key);
311 /* XXX Are we sure we want to update the timeout? */
312 frag->fr_timeout = time_uptime;
313 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
314 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
320 /* Removes a fragment from the fragment queue and frees the fragment */
322 pf_remove_fragment(struct pf_fragment *frag)
326 KASSERT(frag, ("frag != NULL"));
328 RB_REMOVE(pf_frag_tree, &V_pf_frag_tree, frag);
329 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
330 uma_zfree(V_pf_frag_z, frag);
333 static struct pf_frent *
334 pf_create_fragment(u_short *reason)
336 struct pf_frent *frent;
340 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
342 pf_flush_fragments();
343 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
345 REASON_SET(reason, PFRES_MEMORY);
354 * Calculate the additional holes that were created in the fragment
355 * queue by inserting this fragment. A fragment in the middle
356 * creates one more hole by splitting. For each connected side,
358 * Fragment entry must be in the queue when calling this function.
361 pf_frent_holes(struct pf_frent *frent)
363 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
364 struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
368 if (frent->fe_off == 0)
371 KASSERT(frent->fe_off != 0, ("frent->fe_off != 0"));
372 if (frent->fe_off == prev->fe_off + prev->fe_len)
379 KASSERT(frent->fe_mff, ("frent->fe_mff"));
380 if (next->fe_off == frent->fe_off + frent->fe_len)
387 pf_frent_index(struct pf_frent *frent)
390 * We have an array of 16 entry points to the queue. A full size
391 * 65535 octet IP packet can have 8192 fragments. So the queue
392 * traversal length is at most 512 and at most 16 entry points are
393 * checked. We need 128 additional bytes on a 64 bit architecture.
395 CTASSERT(((u_int16_t)0xffff &~ 7) / (0x10000 / PF_FRAG_ENTRY_POINTS) ==
397 CTASSERT(((u_int16_t)0xffff >> 3) / PF_FRAG_ENTRY_POINTS == 512 - 1);
399 return frent->fe_off / (0x10000 / PF_FRAG_ENTRY_POINTS);
403 pf_frent_insert(struct pf_fragment *frag, struct pf_frent *frent,
404 struct pf_frent *prev)
408 CTASSERT(PF_FRAG_ENTRY_LIMIT <= 0xff);
411 * A packet has at most 65536 octets. With 16 entry points, each one
412 * spawns 4096 octets. We limit these to 64 fragments each, which
413 * means on average every fragment must have at least 64 octets.
415 index = pf_frent_index(frent);
416 if (frag->fr_entries[index] >= PF_FRAG_ENTRY_LIMIT)
418 frag->fr_entries[index]++;
421 TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
423 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
424 ("overlapping fragment"));
425 TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next);
428 if (frag->fr_firstoff[index] == NULL) {
429 KASSERT(prev == NULL || pf_frent_index(prev) < index,
430 ("prev == NULL || pf_frent_index(pref) < index"));
431 frag->fr_firstoff[index] = frent;
433 if (frent->fe_off < frag->fr_firstoff[index]->fe_off) {
434 KASSERT(prev == NULL || pf_frent_index(prev) < index,
435 ("prev == NULL || pf_frent_index(pref) < index"));
436 frag->fr_firstoff[index] = frent;
438 KASSERT(prev != NULL, ("prev != NULL"));
439 KASSERT(pf_frent_index(prev) == index,
440 ("pf_frent_index(prev) == index"));
444 frag->fr_holes += pf_frent_holes(frent);
450 pf_frent_remove(struct pf_fragment *frag, struct pf_frent *frent)
453 struct pf_frent *prev = TAILQ_PREV(frent, pf_fragq, fr_next);
455 struct pf_frent *next = TAILQ_NEXT(frent, fr_next);
458 frag->fr_holes -= pf_frent_holes(frent);
460 index = pf_frent_index(frent);
461 KASSERT(frag->fr_firstoff[index] != NULL, ("frent not found"));
462 if (frag->fr_firstoff[index]->fe_off == frent->fe_off) {
464 frag->fr_firstoff[index] = NULL;
466 KASSERT(frent->fe_off + frent->fe_len <= next->fe_off,
467 ("overlapping fragment"));
468 if (pf_frent_index(next) == index) {
469 frag->fr_firstoff[index] = next;
471 frag->fr_firstoff[index] = NULL;
475 KASSERT(frag->fr_firstoff[index]->fe_off < frent->fe_off,
476 ("frag->fr_firstoff[index]->fe_off < frent->fe_off"));
477 KASSERT(prev != NULL, ("prev != NULL"));
478 KASSERT(prev->fe_off + prev->fe_len <= frent->fe_off,
479 ("overlapping fragment"));
480 KASSERT(pf_frent_index(prev) == index,
481 ("pf_frent_index(prev) == index"));
484 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
486 KASSERT(frag->fr_entries[index] > 0, ("No fragments remaining"));
487 frag->fr_entries[index]--;
491 pf_frent_previous(struct pf_fragment *frag, struct pf_frent *frent)
493 struct pf_frent *prev, *next;
497 * If there are no fragments after frag, take the final one. Assume
498 * that the global queue is not empty.
500 prev = TAILQ_LAST(&frag->fr_queue, pf_fragq);
501 KASSERT(prev != NULL, ("prev != NULL"));
502 if (prev->fe_off <= frent->fe_off)
505 * We want to find a fragment entry that is before frag, but still
506 * close to it. Find the first fragment entry that is in the same
507 * entry point or in the first entry point after that. As we have
508 * already checked that there are entries behind frag, this will
511 for (index = pf_frent_index(frent); index < PF_FRAG_ENTRY_POINTS;
513 prev = frag->fr_firstoff[index];
517 KASSERT(prev != NULL, ("prev != NULL"));
519 * In prev we may have a fragment from the same entry point that is
520 * before frent, or one that is just one position behind frent.
521 * In the latter case, we go back one step and have the predecessor.
522 * There may be none if the new fragment will be the first one.
524 if (prev->fe_off > frent->fe_off) {
525 prev = TAILQ_PREV(prev, pf_fragq, fr_next);
528 KASSERT(prev->fe_off <= frent->fe_off,
529 ("prev->fe_off <= frent->fe_off"));
533 * In prev is the first fragment of the entry point. The offset
534 * of frag is behind it. Find the closest previous fragment.
536 for (next = TAILQ_NEXT(prev, fr_next); next != NULL;
537 next = TAILQ_NEXT(next, fr_next)) {
538 if (next->fe_off > frent->fe_off)
545 static struct pf_fragment *
546 pf_fillup_fragment(struct pf_fragment_cmp *key, struct pf_frent *frent,
549 struct pf_frent *after, *next, *prev;
550 struct pf_fragment *frag;
555 /* No empty fragments. */
556 if (frent->fe_len == 0) {
557 DPFPRINTF(("bad fragment: len 0\n"));
561 /* All fragments are 8 byte aligned. */
562 if (frent->fe_mff && (frent->fe_len & 0x7)) {
563 DPFPRINTF(("bad fragment: mff and len %d\n", frent->fe_len));
567 /* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET. */
568 if (frent->fe_off + frent->fe_len > IP_MAXPACKET) {
569 DPFPRINTF(("bad fragment: max packet %d\n",
570 frent->fe_off + frent->fe_len));
574 DPFPRINTF((key->frc_af == AF_INET ?
575 "reass frag %d @ %d-%d\n" : "reass frag %#08x @ %d-%d\n",
576 key->frc_id, frent->fe_off, frent->fe_off + frent->fe_len));
578 /* Fully buffer all of the fragments in this fragment queue. */
579 frag = pf_find_fragment(key, &V_pf_frag_tree);
581 /* Create a new reassembly queue for this packet. */
583 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
585 pf_flush_fragments();
586 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
588 REASON_SET(reason, PFRES_MEMORY);
593 *(struct pf_fragment_cmp *)frag = *key;
594 memset(frag->fr_firstoff, 0, sizeof(frag->fr_firstoff));
595 memset(frag->fr_entries, 0, sizeof(frag->fr_entries));
596 frag->fr_timeout = time_uptime;
597 frag->fr_maxlen = frent->fe_len;
599 TAILQ_INIT(&frag->fr_queue);
601 RB_INSERT(pf_frag_tree, &V_pf_frag_tree, frag);
602 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
604 /* We do not have a previous fragment, cannot fail. */
605 pf_frent_insert(frag, frent, NULL);
610 KASSERT(!TAILQ_EMPTY(&frag->fr_queue), ("!TAILQ_EMPTY()->fr_queue"));
612 /* Remember maximum fragment len for refragmentation. */
613 if (frent->fe_len > frag->fr_maxlen)
614 frag->fr_maxlen = frent->fe_len;
616 /* Maximum data we have seen already. */
617 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
618 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
620 /* Non terminal fragments must have more fragments flag. */
621 if (frent->fe_off + frent->fe_len < total && !frent->fe_mff)
624 /* Check if we saw the last fragment already. */
625 if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) {
626 if (frent->fe_off + frent->fe_len > total ||
627 (frent->fe_off + frent->fe_len == total && frent->fe_mff))
630 if (frent->fe_off + frent->fe_len == total && !frent->fe_mff)
634 /* Find neighbors for newly inserted fragment */
635 prev = pf_frent_previous(frag, frent);
637 after = TAILQ_FIRST(&frag->fr_queue);
638 KASSERT(after != NULL, ("after != NULL"));
640 after = TAILQ_NEXT(prev, fr_next);
643 if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) {
646 precut = prev->fe_off + prev->fe_len - frent->fe_off;
647 if (precut >= frent->fe_len)
649 DPFPRINTF(("overlap -%d\n", precut));
650 m_adj(frent->fe_m, precut);
651 frent->fe_off += precut;
652 frent->fe_len -= precut;
655 for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off;
659 aftercut = frent->fe_off + frent->fe_len - after->fe_off;
660 DPFPRINTF(("adjust overlap %d\n", aftercut));
661 if (aftercut < after->fe_len) {
662 m_adj(after->fe_m, aftercut);
663 after->fe_off += aftercut;
664 after->fe_len -= aftercut;
668 /* This fragment is completely overlapped, lose it. */
669 next = TAILQ_NEXT(after, fr_next);
670 pf_frent_remove(frag, after);
671 m_freem(after->fe_m);
672 uma_zfree(V_pf_frent_z, after);
675 /* If part of the queue gets too long, there is not way to recover. */
676 if (pf_frent_insert(frag, frent, prev)) {
677 DPFPRINTF(("fragment queue limit exceeded\n"));
684 REASON_SET(reason, PFRES_FRAG);
686 uma_zfree(V_pf_frent_z, frent);
691 pf_join_fragment(struct pf_fragment *frag)
694 struct pf_frent *frent, *next;
696 frent = TAILQ_FIRST(&frag->fr_queue);
697 next = TAILQ_NEXT(frent, fr_next);
700 m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len);
701 uma_zfree(V_pf_frent_z, frent);
702 for (frent = next; frent != NULL; frent = next) {
703 next = TAILQ_NEXT(frent, fr_next);
706 /* Strip off ip header. */
707 m_adj(m2, frent->fe_hdrlen);
708 /* Strip off any trailing bytes. */
709 m_adj(m2, frent->fe_len - m2->m_pkthdr.len);
711 uma_zfree(V_pf_frent_z, frent);
715 /* Remove from fragment queue. */
716 pf_remove_fragment(frag);
723 pf_reassemble(struct mbuf **m0, struct ip *ip, int dir, u_short *reason)
725 struct mbuf *m = *m0;
726 struct pf_frent *frent;
727 struct pf_fragment *frag;
728 struct pf_fragment_cmp key;
729 uint16_t total, hdrlen;
731 /* Get an entry for the fragment queue */
732 if ((frent = pf_create_fragment(reason)) == NULL)
736 frent->fe_hdrlen = ip->ip_hl << 2;
737 frent->fe_extoff = 0;
738 frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
739 frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
740 frent->fe_mff = ntohs(ip->ip_off) & IP_MF;
742 pf_ip2key(ip, dir, &key);
744 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL)
747 /* The mbuf is part of the fragment entry, no direct free or access */
750 if (frag->fr_holes) {
751 DPFPRINTF(("frag %d, holes %d\n", frag->fr_id, frag->fr_holes));
752 return (PF_PASS); /* drop because *m0 is NULL, no error */
755 /* We have all the data */
756 frent = TAILQ_FIRST(&frag->fr_queue);
757 KASSERT(frent != NULL, ("frent != NULL"));
758 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
759 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
760 hdrlen = frent->fe_hdrlen;
762 m = *m0 = pf_join_fragment(frag);
765 if (m->m_flags & M_PKTHDR) {
767 for (m = *m0; m; m = m->m_next)
770 m->m_pkthdr.len = plen;
773 ip = mtod(m, struct ip *);
774 ip->ip_len = htons(hdrlen + total);
775 ip->ip_off &= ~(IP_MF|IP_OFFMASK);
777 if (hdrlen + total > IP_MAXPACKET) {
778 DPFPRINTF(("drop: too big: %d\n", total));
780 REASON_SET(reason, PFRES_SHORT);
781 /* PF_DROP requires a valid mbuf *m0 in pf_test() */
785 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip->ip_len)));
792 pf_reassemble6(struct mbuf **m0, struct ip6_hdr *ip6, struct ip6_frag *fraghdr,
793 uint16_t hdrlen, uint16_t extoff, u_short *reason)
795 struct mbuf *m = *m0;
796 struct pf_frent *frent;
797 struct pf_fragment *frag;
798 struct pf_fragment_cmp key;
800 struct pf_fragment_tag *ftag;
803 uint16_t total, maxlen;
808 /* Get an entry for the fragment queue. */
809 if ((frent = pf_create_fragment(reason)) == NULL) {
815 frent->fe_hdrlen = hdrlen;
816 frent->fe_extoff = extoff;
817 frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen;
818 frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK);
819 frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG;
821 key.frc_src.v6 = ip6->ip6_src;
822 key.frc_dst.v6 = ip6->ip6_dst;
823 key.frc_af = AF_INET6;
824 /* Only the first fragment's protocol is relevant. */
826 key.frc_id = fraghdr->ip6f_ident;
828 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL) {
833 /* The mbuf is part of the fragment entry, no direct free or access. */
836 if (frag->fr_holes) {
837 DPFPRINTF(("frag %d, holes %d\n", frag->fr_id,
840 return (PF_PASS); /* Drop because *m0 is NULL, no error. */
843 /* We have all the data. */
844 frent = TAILQ_FIRST(&frag->fr_queue);
845 KASSERT(frent != NULL, ("frent != NULL"));
846 extoff = frent->fe_extoff;
847 maxlen = frag->fr_maxlen;
848 frag_id = frag->fr_id;
849 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
850 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
851 hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
853 m = *m0 = pf_join_fragment(frag);
858 /* Take protocol from first fragment header. */
859 m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off);
860 KASSERT(m, ("%s: short mbuf chain", __func__));
861 proto = *(mtod(m, caddr_t) + off);
864 /* Delete frag6 header */
865 if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0)
868 if (m->m_flags & M_PKTHDR) {
870 for (m = *m0; m; m = m->m_next)
873 m->m_pkthdr.len = plen;
876 if ((mtag = m_tag_get(PF_REASSEMBLED, sizeof(struct pf_fragment_tag),
879 ftag = (struct pf_fragment_tag *)(mtag + 1);
880 ftag->ft_hdrlen = hdrlen;
881 ftag->ft_extoff = extoff;
882 ftag->ft_maxlen = maxlen;
883 ftag->ft_id = frag_id;
884 m_tag_prepend(m, mtag);
886 ip6 = mtod(m, struct ip6_hdr *);
887 ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
889 /* Write protocol into next field of last extension header. */
890 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
892 KASSERT(m, ("%s: short mbuf chain", __func__));
893 *(mtod(m, char *) + off) = proto;
896 ip6->ip6_nxt = proto;
898 if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
899 DPFPRINTF(("drop: too big: %d\n", total));
901 REASON_SET(reason, PFRES_SHORT);
902 /* PF_DROP requires a valid mbuf *m0 in pf_test6(). */
906 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip6->ip6_plen)));
910 REASON_SET(reason, PFRES_MEMORY);
911 /* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */
918 pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag)
920 struct mbuf *m = *m0, *t;
921 struct pf_fragment_tag *ftag = (struct pf_fragment_tag *)(mtag + 1);
924 uint16_t hdrlen, extoff, maxlen;
928 hdrlen = ftag->ft_hdrlen;
929 extoff = ftag->ft_extoff;
930 maxlen = ftag->ft_maxlen;
931 frag_id = ftag->ft_id;
932 m_tag_delete(m, mtag);
939 /* Use protocol from next field of last extension header */
940 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
942 KASSERT((m != NULL), ("pf_refragment6: short mbuf chain"));
943 proto = *(mtod(m, caddr_t) + off);
944 *(mtod(m, char *) + off) = IPPROTO_FRAGMENT;
949 hdr = mtod(m, struct ip6_hdr *);
950 proto = hdr->ip6_nxt;
951 hdr->ip6_nxt = IPPROTO_FRAGMENT;
954 /* The MTU must be a multiple of 8 bytes, or we risk doing the
955 * fragmentation wrong. */
956 maxlen = maxlen & ~7;
959 * Maxlen may be less than 8 if there was only a single
960 * fragment. As it was fragmented before, add a fragment
961 * header also for a single fragment. If total or maxlen
962 * is less than 8, ip6_fragment() will return EMSGSIZE and
963 * we drop the packet.
965 error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
966 m = (*m0)->m_nextpkt;
967 (*m0)->m_nextpkt = NULL;
969 /* The first mbuf contains the unfragmented packet. */
974 /* Drop expects an mbuf to free. */
975 DPFPRINTF(("refragment error %d\n", error));
978 for (t = m; m; m = t) {
981 m->m_flags |= M_SKIP_FIREWALL;
982 memset(&pd, 0, sizeof(pd));
983 pd.pf_mtag = pf_find_mtag(m);
996 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
999 struct mbuf *m = *m0;
1001 struct ip *h = mtod(m, struct ip *);
1002 int mff = (ntohs(h->ip_off) & IP_MF);
1003 int hlen = h->ip_hl << 2;
1004 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1013 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1016 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1017 r = r->skip[PF_SKIP_IFP].ptr;
1018 else if (r->direction && r->direction != dir)
1019 r = r->skip[PF_SKIP_DIR].ptr;
1020 else if (r->af && r->af != AF_INET)
1021 r = r->skip[PF_SKIP_AF].ptr;
1022 else if (r->proto && r->proto != h->ip_p)
1023 r = r->skip[PF_SKIP_PROTO].ptr;
1024 else if (PF_MISMATCHAW(&r->src.addr,
1025 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
1026 r->src.neg, kif, M_GETFIB(m)))
1027 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1028 else if (PF_MISMATCHAW(&r->dst.addr,
1029 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
1030 r->dst.neg, NULL, M_GETFIB(m)))
1031 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1032 else if (r->match_tag && !pf_match_tag(m, r, &tag,
1033 pd->pf_mtag ? pd->pf_mtag->tag : 0))
1034 r = TAILQ_NEXT(r, entries);
1039 if (r == NULL || r->action == PF_NOSCRUB)
1042 r->packets[dir == PF_OUT]++;
1043 r->bytes[dir == PF_OUT] += pd->tot_len;
1046 /* Check for illegal packets */
1047 if (hlen < (int)sizeof(struct ip)) {
1048 REASON_SET(reason, PFRES_NORM);
1052 if (hlen > ntohs(h->ip_len)) {
1053 REASON_SET(reason, PFRES_NORM);
1057 /* Clear IP_DF if the rule uses the no-df option */
1058 if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1059 u_int16_t ip_off = h->ip_off;
1061 h->ip_off &= htons(~IP_DF);
1062 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1065 /* We will need other tests here */
1066 if (!fragoff && !mff)
1069 /* We're dealing with a fragment now. Don't allow fragments
1070 * with IP_DF to enter the cache. If the flag was cleared by
1071 * no-df above, fine. Otherwise drop it.
1073 if (h->ip_off & htons(IP_DF)) {
1074 DPFPRINTF(("IP_DF\n"));
1078 ip_len = ntohs(h->ip_len) - hlen;
1079 ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
1081 /* All fragments are 8 byte aligned */
1082 if (mff && (ip_len & 0x7)) {
1083 DPFPRINTF(("mff and %d\n", ip_len));
1087 /* Respect maximum length */
1088 if (fragoff + ip_len > IP_MAXPACKET) {
1089 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
1092 max = fragoff + ip_len;
1094 /* Fully buffer all of the fragments
1095 * Might return a completely reassembled mbuf, or NULL */
1097 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
1098 verdict = pf_reassemble(m0, h, dir, reason);
1101 if (verdict != PF_PASS)
1108 h = mtod(m, struct ip *);
1111 /* At this point, only IP_DF is allowed in ip_off */
1112 if (h->ip_off & ~htons(IP_DF)) {
1113 u_int16_t ip_off = h->ip_off;
1115 h->ip_off &= htons(IP_DF);
1116 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1119 pf_scrub_ip(&m, r->rule_flag, r->min_ttl, r->set_tos);
1124 DPFPRINTF(("dropping bad fragment\n"));
1125 REASON_SET(reason, PFRES_FRAG);
1127 if (r != NULL && r->log)
1128 PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
1137 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
1138 u_short *reason, struct pf_pdesc *pd)
1140 struct mbuf *m = *m0;
1142 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1147 struct ip6_frag frag;
1156 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1159 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1160 r = r->skip[PF_SKIP_IFP].ptr;
1161 else if (r->direction && r->direction != dir)
1162 r = r->skip[PF_SKIP_DIR].ptr;
1163 else if (r->af && r->af != AF_INET6)
1164 r = r->skip[PF_SKIP_AF].ptr;
1165 #if 0 /* header chain! */
1166 else if (r->proto && r->proto != h->ip6_nxt)
1167 r = r->skip[PF_SKIP_PROTO].ptr;
1169 else if (PF_MISMATCHAW(&r->src.addr,
1170 (struct pf_addr *)&h->ip6_src, AF_INET6,
1171 r->src.neg, kif, M_GETFIB(m)))
1172 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1173 else if (PF_MISMATCHAW(&r->dst.addr,
1174 (struct pf_addr *)&h->ip6_dst, AF_INET6,
1175 r->dst.neg, NULL, M_GETFIB(m)))
1176 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1181 if (r == NULL || r->action == PF_NOSCRUB)
1184 r->packets[dir == PF_OUT]++;
1185 r->bytes[dir == PF_OUT] += pd->tot_len;
1188 /* Check for illegal packets */
1189 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1192 plen = ntohs(h->ip6_plen);
1193 /* jumbo payload option not supported */
1198 off = sizeof(struct ip6_hdr);
1203 case IPPROTO_FRAGMENT:
1207 case IPPROTO_ROUTING:
1208 case IPPROTO_DSTOPTS:
1209 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1213 if (proto == IPPROTO_AH)
1214 off += (ext.ip6e_len + 2) * 4;
1216 off += (ext.ip6e_len + 1) * 8;
1217 proto = ext.ip6e_nxt;
1219 case IPPROTO_HOPOPTS:
1220 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1224 optend = off + (ext.ip6e_len + 1) * 8;
1225 ooff = off + sizeof(ext);
1227 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1228 sizeof(opt.ip6o_type), NULL, NULL,
1231 if (opt.ip6o_type == IP6OPT_PAD1) {
1235 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1236 NULL, NULL, AF_INET6))
1238 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1240 if (opt.ip6o_type == IP6OPT_JUMBO)
1242 ooff += sizeof(opt) + opt.ip6o_len;
1243 } while (ooff < optend);
1246 proto = ext.ip6e_nxt;
1252 } while (!terminal);
1254 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1257 pf_scrub_ip6(&m, r->min_ttl);
1262 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1265 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1268 /* Offset now points to data portion. */
1269 off += sizeof(frag);
1271 /* Returns PF_DROP or *m0 is NULL or completely reassembled mbuf. */
1272 if (pf_reassemble6(m0, h, &frag, off, extoff, reason) != PF_PASS)
1278 pd->flags |= PFDESC_IP_REAS;
1282 REASON_SET(reason, PFRES_SHORT);
1283 if (r != NULL && r->log)
1284 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1289 REASON_SET(reason, PFRES_NORM);
1290 if (r != NULL && r->log)
1291 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1298 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1299 int off, void *h, struct pf_pdesc *pd)
1301 struct pf_krule *r, *rm = NULL;
1302 struct tcphdr *th = pd->hdr.tcp;
1306 sa_family_t af = pd->af;
1310 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1313 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1314 r = r->skip[PF_SKIP_IFP].ptr;
1315 else if (r->direction && r->direction != dir)
1316 r = r->skip[PF_SKIP_DIR].ptr;
1317 else if (r->af && r->af != af)
1318 r = r->skip[PF_SKIP_AF].ptr;
1319 else if (r->proto && r->proto != pd->proto)
1320 r = r->skip[PF_SKIP_PROTO].ptr;
1321 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1322 r->src.neg, kif, M_GETFIB(m)))
1323 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1324 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1325 r->src.port[0], r->src.port[1], th->th_sport))
1326 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1327 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1328 r->dst.neg, NULL, M_GETFIB(m)))
1329 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1330 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1331 r->dst.port[0], r->dst.port[1], th->th_dport))
1332 r = r->skip[PF_SKIP_DST_PORT].ptr;
1333 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1334 pf_osfp_fingerprint(pd, m, off, th),
1336 r = TAILQ_NEXT(r, entries);
1343 if (rm == NULL || rm->action == PF_NOSCRUB)
1346 r->packets[dir == PF_OUT]++;
1347 r->bytes[dir == PF_OUT] += pd->tot_len;
1350 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1351 pd->flags |= PFDESC_TCP_NORM;
1353 flags = th->th_flags;
1354 if (flags & TH_SYN) {
1355 /* Illegal packet */
1362 /* Illegal packet */
1363 if (!(flags & (TH_ACK|TH_RST)))
1367 if (!(flags & TH_ACK)) {
1368 /* These flags are only valid if ACK is set */
1369 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1373 /* Check for illegal header length */
1374 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1377 /* If flags changed, or reserved data set, then adjust */
1378 if (flags != th->th_flags || th->th_x2 != 0) {
1381 ov = *(u_int16_t *)(&th->th_ack + 1);
1382 th->th_flags = flags;
1384 nv = *(u_int16_t *)(&th->th_ack + 1);
1386 th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, ov, nv, 0);
1390 /* Remove urgent pointer, if TH_URG is not set */
1391 if (!(flags & TH_URG) && th->th_urp) {
1392 th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, th->th_urp,
1398 /* Process options */
1399 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1402 /* copy back packet headers if we sanitized */
1404 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1409 REASON_SET(&reason, PFRES_NORM);
1410 if (rm != NULL && r->log)
1411 PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1417 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1418 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1420 u_int32_t tsval, tsecr;
1424 KASSERT((src->scrub == NULL),
1425 ("pf_normalize_tcp_init: src->scrub != NULL"));
1427 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1428 if (src->scrub == NULL)
1434 struct ip *h = mtod(m, struct ip *);
1435 src->scrub->pfss_ttl = h->ip_ttl;
1441 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1442 src->scrub->pfss_ttl = h->ip6_hlim;
1449 * All normalizations below are only begun if we see the start of
1450 * the connections. They must all set an enabled bit in pfss_flags
1452 if ((th->th_flags & TH_SYN) == 0)
1455 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1456 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1457 /* Diddle with TCP options */
1459 opt = hdr + sizeof(struct tcphdr);
1460 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1461 while (hlen >= TCPOLEN_TIMESTAMP) {
1463 case TCPOPT_EOL: /* FALLTHROUGH */
1468 case TCPOPT_TIMESTAMP:
1469 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1470 src->scrub->pfss_flags |=
1472 src->scrub->pfss_ts_mod =
1473 htonl(arc4random());
1475 /* note PFSS_PAWS not set yet */
1476 memcpy(&tsval, &opt[2],
1478 memcpy(&tsecr, &opt[6],
1480 src->scrub->pfss_tsval0 = ntohl(tsval);
1481 src->scrub->pfss_tsval = ntohl(tsval);
1482 src->scrub->pfss_tsecr = ntohl(tsecr);
1483 getmicrouptime(&src->scrub->pfss_last);
1487 hlen -= MAX(opt[1], 2);
1488 opt += MAX(opt[1], 2);
1498 pf_normalize_tcp_cleanup(struct pf_state *state)
1500 if (state->src.scrub)
1501 uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1502 if (state->dst.scrub)
1503 uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1505 /* Someday... flush the TCP segment reassembly descriptors. */
1509 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1510 u_short *reason, struct tcphdr *th, struct pf_state *state,
1511 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1513 struct timeval uptime;
1514 u_int32_t tsval, tsecr;
1515 u_int tsval_from_last;
1522 KASSERT((src->scrub || dst->scrub),
1523 ("%s: src->scrub && dst->scrub!", __func__));
1526 * Enforce the minimum TTL seen for this connection. Negate a common
1527 * technique to evade an intrusion detection system and confuse
1528 * firewall state code.
1534 struct ip *h = mtod(m, struct ip *);
1535 if (h->ip_ttl > src->scrub->pfss_ttl)
1536 src->scrub->pfss_ttl = h->ip_ttl;
1537 h->ip_ttl = src->scrub->pfss_ttl;
1545 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1546 if (h->ip6_hlim > src->scrub->pfss_ttl)
1547 src->scrub->pfss_ttl = h->ip6_hlim;
1548 h->ip6_hlim = src->scrub->pfss_ttl;
1555 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1556 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1557 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1558 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1559 /* Diddle with TCP options */
1561 opt = hdr + sizeof(struct tcphdr);
1562 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1563 while (hlen >= TCPOLEN_TIMESTAMP) {
1564 startoff = opt - (hdr + sizeof(struct tcphdr));
1566 case TCPOPT_EOL: /* FALLTHROUGH */
1571 case TCPOPT_TIMESTAMP:
1572 /* Modulate the timestamps. Can be used for
1573 * NAT detection, OS uptime determination or
1578 /* Huh? Multiple timestamps!? */
1579 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1580 DPFPRINTF(("multiple TS??\n"));
1581 pf_print_state(state);
1584 REASON_SET(reason, PFRES_TS);
1587 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1588 memcpy(&tsval, &opt[2],
1590 if (tsval && src->scrub &&
1591 (src->scrub->pfss_flags &
1593 tsval = ntohl(tsval);
1594 pf_patch_32_unaligned(m,
1598 src->scrub->pfss_ts_mod),
1599 PF_ALGNMNT(startoff),
1604 /* Modulate TS reply iff valid (!0) */
1605 memcpy(&tsecr, &opt[6],
1607 if (tsecr && dst->scrub &&
1608 (dst->scrub->pfss_flags &
1610 tsecr = ntohl(tsecr)
1611 - dst->scrub->pfss_ts_mod;
1612 pf_patch_32_unaligned(m,
1616 PF_ALGNMNT(startoff),
1624 hlen -= MAX(opt[1], 2);
1625 opt += MAX(opt[1], 2);
1630 /* Copyback the options, caller copys back header */
1632 m_copyback(m, off + sizeof(struct tcphdr),
1633 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1634 sizeof(struct tcphdr));
1639 * Must invalidate PAWS checks on connections idle for too long.
1640 * The fastest allowed timestamp clock is 1ms. That turns out to
1641 * be about 24 days before it wraps. XXX Right now our lowerbound
1642 * TS echo check only works for the first 12 days of a connection
1643 * when the TS has exhausted half its 32bit space
1645 #define TS_MAX_IDLE (24*24*60*60)
1646 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1648 getmicrouptime(&uptime);
1649 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1650 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1651 time_uptime - state->creation > TS_MAX_CONN)) {
1652 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1653 DPFPRINTF(("src idled out of PAWS\n"));
1654 pf_print_state(state);
1657 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1660 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1661 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1662 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1663 DPFPRINTF(("dst idled out of PAWS\n"));
1664 pf_print_state(state);
1667 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1671 if (got_ts && src->scrub && dst->scrub &&
1672 (src->scrub->pfss_flags & PFSS_PAWS) &&
1673 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1674 /* Validate that the timestamps are "in-window".
1675 * RFC1323 describes TCP Timestamp options that allow
1676 * measurement of RTT (round trip time) and PAWS
1677 * (protection against wrapped sequence numbers). PAWS
1678 * gives us a set of rules for rejecting packets on
1679 * long fat pipes (packets that were somehow delayed
1680 * in transit longer than the time it took to send the
1681 * full TCP sequence space of 4Gb). We can use these
1682 * rules and infer a few others that will let us treat
1683 * the 32bit timestamp and the 32bit echoed timestamp
1684 * as sequence numbers to prevent a blind attacker from
1685 * inserting packets into a connection.
1688 * - The timestamp on this packet must be greater than
1689 * or equal to the last value echoed by the other
1690 * endpoint. The RFC says those will be discarded
1691 * since it is a dup that has already been acked.
1692 * This gives us a lowerbound on the timestamp.
1693 * timestamp >= other last echoed timestamp
1694 * - The timestamp will be less than or equal to
1695 * the last timestamp plus the time between the
1696 * last packet and now. The RFC defines the max
1697 * clock rate as 1ms. We will allow clocks to be
1698 * up to 10% fast and will allow a total difference
1699 * or 30 seconds due to a route change. And this
1700 * gives us an upperbound on the timestamp.
1701 * timestamp <= last timestamp + max ticks
1702 * We have to be careful here. Windows will send an
1703 * initial timestamp of zero and then initialize it
1704 * to a random value after the 3whs; presumably to
1705 * avoid a DoS by having to call an expensive RNG
1706 * during a SYN flood. Proof MS has at least one
1707 * good security geek.
1709 * - The TCP timestamp option must also echo the other
1710 * endpoints timestamp. The timestamp echoed is the
1711 * one carried on the earliest unacknowledged segment
1712 * on the left edge of the sequence window. The RFC
1713 * states that the host will reject any echoed
1714 * timestamps that were larger than any ever sent.
1715 * This gives us an upperbound on the TS echo.
1716 * tescr <= largest_tsval
1717 * - The lowerbound on the TS echo is a little more
1718 * tricky to determine. The other endpoint's echoed
1719 * values will not decrease. But there may be
1720 * network conditions that re-order packets and
1721 * cause our view of them to decrease. For now the
1722 * only lowerbound we can safely determine is that
1723 * the TS echo will never be less than the original
1724 * TS. XXX There is probably a better lowerbound.
1725 * Remove TS_MAX_CONN with better lowerbound check.
1726 * tescr >= other original TS
1728 * It is also important to note that the fastest
1729 * timestamp clock of 1ms will wrap its 32bit space in
1730 * 24 days. So we just disable TS checking after 24
1731 * days of idle time. We actually must use a 12d
1732 * connection limit until we can come up with a better
1733 * lowerbound to the TS echo check.
1735 struct timeval delta_ts;
1739 * PFTM_TS_DIFF is how many seconds of leeway to allow
1740 * a host's timestamp. This can happen if the previous
1741 * packet got delayed in transit for much longer than
1744 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1745 ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1747 /* Calculate max ticks since the last timestamp */
1748 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1749 #define TS_MICROSECS 1000000 /* microseconds per second */
1751 timevalsub(&delta_ts, &src->scrub->pfss_last);
1752 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1753 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1755 if ((src->state >= TCPS_ESTABLISHED &&
1756 dst->state >= TCPS_ESTABLISHED) &&
1757 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1758 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1759 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1760 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1761 /* Bad RFC1323 implementation or an insertion attack.
1763 * - Solaris 2.6 and 2.7 are known to send another ACK
1764 * after the FIN,FIN|ACK,ACK closing that carries
1768 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1769 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1770 SEQ_GT(tsval, src->scrub->pfss_tsval +
1771 tsval_from_last) ? '1' : ' ',
1772 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1773 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1774 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1775 "idle: %jus %lums\n",
1776 tsval, tsecr, tsval_from_last,
1777 (uintmax_t)delta_ts.tv_sec,
1778 delta_ts.tv_usec / 1000));
1779 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1780 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1781 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1782 "\n", dst->scrub->pfss_tsval,
1783 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1784 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1785 pf_print_state(state);
1786 pf_print_flags(th->th_flags);
1789 REASON_SET(reason, PFRES_TS);
1793 /* XXX I'd really like to require tsecr but it's optional */
1795 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1796 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1797 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1798 src->scrub && dst->scrub &&
1799 (src->scrub->pfss_flags & PFSS_PAWS) &&
1800 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1801 /* Didn't send a timestamp. Timestamps aren't really useful
1803 * - connection opening or closing (often not even sent).
1804 * but we must not let an attacker to put a FIN on a
1805 * data packet to sneak it through our ESTABLISHED check.
1806 * - on a TCP reset. RFC suggests not even looking at TS.
1807 * - on an empty ACK. The TS will not be echoed so it will
1808 * probably not help keep the RTT calculation in sync and
1809 * there isn't as much danger when the sequence numbers
1810 * got wrapped. So some stacks don't include TS on empty
1813 * To minimize the disruption to mostly RFC1323 conformant
1814 * stacks, we will only require timestamps on data packets.
1816 * And what do ya know, we cannot require timestamps on data
1817 * packets. There appear to be devices that do legitimate
1818 * TCP connection hijacking. There are HTTP devices that allow
1819 * a 3whs (with timestamps) and then buffer the HTTP request.
1820 * If the intermediate device has the HTTP response cache, it
1821 * will spoof the response but not bother timestamping its
1822 * packets. So we can look for the presence of a timestamp in
1823 * the first data packet and if there, require it in all future
1827 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1829 * Hey! Someone tried to sneak a packet in. Or the
1830 * stack changed its RFC1323 behavior?!?!
1832 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1833 DPFPRINTF(("Did not receive expected RFC1323 "
1835 pf_print_state(state);
1836 pf_print_flags(th->th_flags);
1839 REASON_SET(reason, PFRES_TS);
1845 * We will note if a host sends his data packets with or without
1846 * timestamps. And require all data packets to contain a timestamp
1847 * if the first does. PAWS implicitly requires that all data packets be
1848 * timestamped. But I think there are middle-man devices that hijack
1849 * TCP streams immediately after the 3whs and don't timestamp their
1850 * packets (seen in a WWW accelerator or cache).
1852 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1853 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1855 src->scrub->pfss_flags |= PFSS_DATA_TS;
1857 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1858 if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1859 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1860 /* Don't warn if other host rejected RFC1323 */
1861 DPFPRINTF(("Broken RFC1323 stack did not "
1862 "timestamp data packet. Disabled PAWS "
1864 pf_print_state(state);
1865 pf_print_flags(th->th_flags);
1872 * Update PAWS values
1874 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1875 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1876 getmicrouptime(&src->scrub->pfss_last);
1877 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1878 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1879 src->scrub->pfss_tsval = tsval;
1882 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1883 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1884 src->scrub->pfss_tsecr = tsecr;
1886 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1887 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1888 src->scrub->pfss_tsval0 == 0)) {
1889 /* tsval0 MUST be the lowest timestamp */
1890 src->scrub->pfss_tsval0 = tsval;
1893 /* Only fully initialized after a TS gets echoed */
1894 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1895 src->scrub->pfss_flags |= PFSS_PAWS;
1899 /* I have a dream.... TCP segment reassembly.... */
1904 pf_normalize_tcpopt(struct pf_krule *r, struct mbuf *m, struct tcphdr *th,
1905 int off, sa_family_t af)
1909 int opt, cnt, optlen = 0;
1911 u_char opts[TCP_MAXOLEN];
1912 u_char *optp = opts;
1915 thoff = th->th_off << 2;
1916 cnt = thoff - sizeof(struct tcphdr);
1918 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1922 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1923 startoff = optp - opts;
1925 if (opt == TCPOPT_EOL)
1927 if (opt == TCPOPT_NOP)
1933 if (optlen < 2 || optlen > cnt)
1938 mss = (u_int16_t *)(optp + 2);
1939 if ((ntohs(*mss)) > r->max_mss) {
1940 pf_patch_16_unaligned(m,
1942 mss, htons(r->max_mss),
1943 PF_ALGNMNT(startoff),
1954 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1961 pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
1963 struct mbuf *m = *m0;
1964 struct ip *h = mtod(m, struct ip *);
1966 /* Clear IP_DF if no-df was requested */
1967 if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1968 u_int16_t ip_off = h->ip_off;
1970 h->ip_off &= htons(~IP_DF);
1971 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1974 /* Enforce a minimum ttl, may cause endless packet loops */
1975 if (min_ttl && h->ip_ttl < min_ttl) {
1976 u_int16_t ip_ttl = h->ip_ttl;
1978 h->ip_ttl = min_ttl;
1979 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1983 if (flags & PFRULE_SET_TOS) {
1986 ov = *(u_int16_t *)h;
1987 h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK);
1988 nv = *(u_int16_t *)h;
1990 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1993 /* random-id, but not for fragments */
1994 if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
1995 uint16_t ip_id = h->ip_id;
1998 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
2005 pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
2007 struct mbuf *m = *m0;
2008 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
2010 /* Enforce a minimum ttl, may cause endless packet loops */
2011 if (min_ttl && h->ip6_hlim < min_ttl)
2012 h->ip6_hlim = min_ttl;