2 * Copyright 2001 Niels Provos <provos@citi.umich.edu>
3 * Copyright 2011 Alexander Bluhm <bluhm@openbsd.org>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 * $OpenBSD: pf_norm.c,v 1.114 2009/01/29 14:11:45 henning Exp $
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
33 #include "opt_inet6.h"
36 #include <sys/param.h>
37 #include <sys/kernel.h>
40 #include <sys/mutex.h>
41 #include <sys/refcount.h>
42 #include <sys/rwlock.h>
43 #include <sys/socket.h>
47 #include <net/pfvar.h>
48 #include <net/if_pflog.h>
50 #include <netinet/in.h>
51 #include <netinet/ip.h>
52 #include <netinet/ip_var.h>
53 #include <netinet6/ip6_var.h>
54 #include <netinet/tcp.h>
55 #include <netinet/tcp_fsm.h>
56 #include <netinet/tcp_seq.h>
59 #include <netinet/ip6.h>
63 TAILQ_ENTRY(pf_frent) fr_next;
65 uint16_t fe_hdrlen; /* ipv4 header lenght with ip options
66 ipv6, extension, fragment header */
67 uint16_t fe_extoff; /* last extension header offset or 0 */
68 uint16_t fe_len; /* fragment length */
69 uint16_t fe_off; /* fragment offset */
70 uint16_t fe_mff; /* more fragment flag */
73 struct pf_fragment_cmp {
74 struct pf_addr frc_src;
75 struct pf_addr frc_dst;
82 struct pf_fragment_cmp fr_key;
83 #define fr_src fr_key.frc_src
84 #define fr_dst fr_key.frc_dst
85 #define fr_id fr_key.frc_id
86 #define fr_af fr_key.frc_af
87 #define fr_proto fr_key.frc_proto
89 RB_ENTRY(pf_fragment) fr_entry;
90 TAILQ_ENTRY(pf_fragment) frag_next;
92 uint16_t fr_maxlen; /* maximum length of single fragment */
93 TAILQ_HEAD(pf_fragq, pf_frent) fr_queue;
96 struct pf_fragment_tag {
97 uint16_t ft_hdrlen; /* header length of reassembled pkt */
98 uint16_t ft_extoff; /* last extension header offset or 0 */
99 uint16_t ft_maxlen; /* maximum fragment payload length */
100 uint32_t ft_id; /* fragment id */
103 static struct mtx pf_frag_mtx;
104 MTX_SYSINIT(pf_frag_mtx, &pf_frag_mtx, "pf fragments", MTX_DEF);
105 #define PF_FRAG_LOCK() mtx_lock(&pf_frag_mtx)
106 #define PF_FRAG_UNLOCK() mtx_unlock(&pf_frag_mtx)
107 #define PF_FRAG_ASSERT() mtx_assert(&pf_frag_mtx, MA_OWNED)
109 VNET_DEFINE(uma_zone_t, pf_state_scrub_z); /* XXX: shared with pfsync */
111 static VNET_DEFINE(uma_zone_t, pf_frent_z);
112 #define V_pf_frent_z VNET(pf_frent_z)
113 static VNET_DEFINE(uma_zone_t, pf_frag_z);
114 #define V_pf_frag_z VNET(pf_frag_z)
116 TAILQ_HEAD(pf_fragqueue, pf_fragment);
117 TAILQ_HEAD(pf_cachequeue, pf_fragment);
118 static VNET_DEFINE(struct pf_fragqueue, pf_fragqueue);
119 #define V_pf_fragqueue VNET(pf_fragqueue)
120 RB_HEAD(pf_frag_tree, pf_fragment);
121 static VNET_DEFINE(struct pf_frag_tree, pf_frag_tree);
122 #define V_pf_frag_tree VNET(pf_frag_tree)
123 static int pf_frag_compare(struct pf_fragment *,
124 struct pf_fragment *);
125 static RB_PROTOTYPE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
126 static RB_GENERATE(pf_frag_tree, pf_fragment, fr_entry, pf_frag_compare);
128 static void pf_flush_fragments(void);
129 static void pf_free_fragment(struct pf_fragment *);
130 static void pf_remove_fragment(struct pf_fragment *);
131 static int pf_normalize_tcpopt(struct pf_rule *, struct mbuf *,
132 struct tcphdr *, int, sa_family_t);
133 static struct pf_frent *pf_create_fragment(u_short *);
134 static struct pf_fragment *pf_find_fragment(struct pf_fragment_cmp *key,
135 struct pf_frag_tree *tree);
136 static struct pf_fragment *pf_fillup_fragment(struct pf_fragment_cmp *,
137 struct pf_frent *, u_short *);
138 static int pf_isfull_fragment(struct pf_fragment *);
139 static struct mbuf *pf_join_fragment(struct pf_fragment *);
141 static void pf_scrub_ip(struct mbuf **, uint32_t, uint8_t, uint8_t);
142 static int pf_reassemble(struct mbuf **, struct ip *, int, u_short *);
145 static int pf_reassemble6(struct mbuf **, struct ip6_hdr *,
146 struct ip6_frag *, uint16_t, uint16_t, u_short *);
147 static void pf_scrub_ip6(struct mbuf **, uint8_t);
150 #define DPFPRINTF(x) do { \
151 if (V_pf_status.debug >= PF_DEBUG_MISC) { \
152 printf("%s: ", __func__); \
159 pf_ip2key(struct ip *ip, int dir, struct pf_fragment_cmp *key)
162 key->frc_src.v4 = ip->ip_src;
163 key->frc_dst.v4 = ip->ip_dst;
164 key->frc_af = AF_INET;
165 key->frc_proto = ip->ip_p;
166 key->frc_id = ip->ip_id;
171 pf_normalize_init(void)
174 V_pf_frag_z = uma_zcreate("pf frags", sizeof(struct pf_fragment),
175 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
176 V_pf_frent_z = uma_zcreate("pf frag entries", sizeof(struct pf_frent),
177 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
178 V_pf_state_scrub_z = uma_zcreate("pf state scrubs",
179 sizeof(struct pf_state_scrub), NULL, NULL, NULL, NULL,
182 V_pf_limits[PF_LIMIT_FRAGS].zone = V_pf_frent_z;
183 V_pf_limits[PF_LIMIT_FRAGS].limit = PFFRAG_FRENT_HIWAT;
184 uma_zone_set_max(V_pf_frent_z, PFFRAG_FRENT_HIWAT);
185 uma_zone_set_warning(V_pf_frent_z, "PF frag entries limit reached");
187 TAILQ_INIT(&V_pf_fragqueue);
191 pf_normalize_cleanup(void)
194 uma_zdestroy(V_pf_state_scrub_z);
195 uma_zdestroy(V_pf_frent_z);
196 uma_zdestroy(V_pf_frag_z);
200 pf_frag_compare(struct pf_fragment *a, struct pf_fragment *b)
204 if ((diff = a->fr_id - b->fr_id) != 0)
206 if ((diff = a->fr_proto - b->fr_proto) != 0)
208 if ((diff = a->fr_af - b->fr_af) != 0)
210 if ((diff = pf_addr_cmp(&a->fr_src, &b->fr_src, a->fr_af)) != 0)
212 if ((diff = pf_addr_cmp(&a->fr_dst, &b->fr_dst, a->fr_af)) != 0)
218 pf_purge_expired_fragments(void)
220 struct pf_fragment *frag;
221 u_int32_t expire = time_uptime -
222 V_pf_default_rule.timeout[PFTM_FRAG];
225 while ((frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue)) != NULL) {
226 if (frag->fr_timeout > expire)
229 DPFPRINTF(("expiring %d(%p)\n", frag->fr_id, frag));
230 pf_free_fragment(frag);
237 * Try to flush old fragments to make space for new ones
240 pf_flush_fragments(void)
242 struct pf_fragment *frag;
247 goal = uma_zone_get_cur(V_pf_frent_z) * 9 / 10;
248 DPFPRINTF(("trying to free %d frag entriess\n", goal));
249 while (goal < uma_zone_get_cur(V_pf_frent_z)) {
250 frag = TAILQ_LAST(&V_pf_fragqueue, pf_fragqueue);
252 pf_free_fragment(frag);
258 /* Frees the fragments and all associated entries */
260 pf_free_fragment(struct pf_fragment *frag)
262 struct pf_frent *frent;
266 /* Free all fragments */
267 for (frent = TAILQ_FIRST(&frag->fr_queue); frent;
268 frent = TAILQ_FIRST(&frag->fr_queue)) {
269 TAILQ_REMOVE(&frag->fr_queue, frent, fr_next);
271 m_freem(frent->fe_m);
272 uma_zfree(V_pf_frent_z, frent);
275 pf_remove_fragment(frag);
278 static struct pf_fragment *
279 pf_find_fragment(struct pf_fragment_cmp *key, struct pf_frag_tree *tree)
281 struct pf_fragment *frag;
285 frag = RB_FIND(pf_frag_tree, tree, (struct pf_fragment *)key);
287 /* XXX Are we sure we want to update the timeout? */
288 frag->fr_timeout = time_uptime;
289 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
290 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
296 /* Removes a fragment from the fragment queue and frees the fragment */
298 pf_remove_fragment(struct pf_fragment *frag)
303 RB_REMOVE(pf_frag_tree, &V_pf_frag_tree, frag);
304 TAILQ_REMOVE(&V_pf_fragqueue, frag, frag_next);
305 uma_zfree(V_pf_frag_z, frag);
308 static struct pf_frent *
309 pf_create_fragment(u_short *reason)
311 struct pf_frent *frent;
315 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
317 pf_flush_fragments();
318 frent = uma_zalloc(V_pf_frent_z, M_NOWAIT);
320 REASON_SET(reason, PFRES_MEMORY);
328 static struct pf_fragment *
329 pf_fillup_fragment(struct pf_fragment_cmp *key, struct pf_frent *frent,
332 struct pf_frent *after, *next, *prev;
333 struct pf_fragment *frag;
338 /* No empty fragments. */
339 if (frent->fe_len == 0) {
340 DPFPRINTF(("bad fragment: len 0"));
344 /* All fragments are 8 byte aligned. */
345 if (frent->fe_mff && (frent->fe_len & 0x7)) {
346 DPFPRINTF(("bad fragment: mff and len %d", frent->fe_len));
350 /* Respect maximum length, IP_MAXPACKET == IPV6_MAXPACKET. */
351 if (frent->fe_off + frent->fe_len > IP_MAXPACKET) {
352 DPFPRINTF(("bad fragment: max packet %d",
353 frent->fe_off + frent->fe_len));
357 DPFPRINTF((key->frc_af == AF_INET ?
358 "reass frag %d @ %d-%d" : "reass frag %#08x @ %d-%d",
359 key->frc_id, frent->fe_off, frent->fe_off + frent->fe_len));
361 /* Fully buffer all of the fragments in this fragment queue. */
362 frag = pf_find_fragment(key, &V_pf_frag_tree);
364 /* Create a new reassembly queue for this packet. */
366 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
368 pf_flush_fragments();
369 frag = uma_zalloc(V_pf_frag_z, M_NOWAIT);
371 REASON_SET(reason, PFRES_MEMORY);
376 *(struct pf_fragment_cmp *)frag = *key;
377 frag->fr_timeout = time_second;
378 frag->fr_maxlen = frent->fe_len;
379 TAILQ_INIT(&frag->fr_queue);
381 RB_INSERT(pf_frag_tree, &V_pf_frag_tree, frag);
382 TAILQ_INSERT_HEAD(&V_pf_fragqueue, frag, frag_next);
384 /* We do not have a previous fragment. */
385 TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
390 KASSERT(!TAILQ_EMPTY(&frag->fr_queue), ("!TAILQ_EMPTY()->fr_queue"));
392 /* Remember maximum fragment len for refragmentation. */
393 if (frent->fe_len > frag->fr_maxlen)
394 frag->fr_maxlen = frent->fe_len;
396 /* Maximum data we have seen already. */
397 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
398 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
400 /* Non terminal fragments must have more fragments flag. */
401 if (frent->fe_off + frent->fe_len < total && !frent->fe_mff)
404 /* Check if we saw the last fragment already. */
405 if (!TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff) {
406 if (frent->fe_off + frent->fe_len > total ||
407 (frent->fe_off + frent->fe_len == total && frent->fe_mff))
410 if (frent->fe_off + frent->fe_len == total && !frent->fe_mff)
414 /* Find a fragment after the current one. */
416 TAILQ_FOREACH(after, &frag->fr_queue, fr_next) {
417 if (after->fe_off > frent->fe_off)
422 KASSERT(prev != NULL || after != NULL,
423 ("prev != NULL || after != NULL"));
425 if (prev != NULL && prev->fe_off + prev->fe_len > frent->fe_off) {
428 precut = prev->fe_off + prev->fe_len - frent->fe_off;
429 if (precut >= frent->fe_len)
431 DPFPRINTF(("overlap -%d", precut));
432 m_adj(frent->fe_m, precut);
433 frent->fe_off += precut;
434 frent->fe_len -= precut;
437 for (; after != NULL && frent->fe_off + frent->fe_len > after->fe_off;
441 aftercut = frent->fe_off + frent->fe_len - after->fe_off;
442 DPFPRINTF(("adjust overlap %d", aftercut));
443 if (aftercut < after->fe_len) {
444 m_adj(after->fe_m, aftercut);
445 after->fe_off += aftercut;
446 after->fe_len -= aftercut;
450 /* This fragment is completely overlapped, lose it. */
451 next = TAILQ_NEXT(after, fr_next);
452 m_freem(after->fe_m);
453 TAILQ_REMOVE(&frag->fr_queue, after, fr_next);
454 uma_zfree(V_pf_frent_z, after);
458 TAILQ_INSERT_HEAD(&frag->fr_queue, frent, fr_next);
460 TAILQ_INSERT_AFTER(&frag->fr_queue, prev, frent, fr_next);
465 REASON_SET(reason, PFRES_FRAG);
467 uma_zfree(V_pf_frent_z, frent);
472 pf_isfull_fragment(struct pf_fragment *frag)
474 struct pf_frent *frent, *next;
477 /* Check if we are completely reassembled */
478 if (TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_mff)
481 /* Maximum data we have seen already */
482 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
483 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
485 /* Check if we have all the data */
487 for (frent = TAILQ_FIRST(&frag->fr_queue); frent; frent = next) {
488 next = TAILQ_NEXT(frent, fr_next);
490 off += frent->fe_len;
491 if (off < total && (next == NULL || next->fe_off != off)) {
492 DPFPRINTF(("missing fragment at %d, next %d, total %d",
493 off, next == NULL ? -1 : next->fe_off, total));
497 DPFPRINTF(("%d < %d?", off, total));
500 KASSERT(off == total, ("off == total"));
506 pf_join_fragment(struct pf_fragment *frag)
509 struct pf_frent *frent, *next;
511 frent = TAILQ_FIRST(&frag->fr_queue);
512 next = TAILQ_NEXT(frent, fr_next);
515 m_adj(m, (frent->fe_hdrlen + frent->fe_len) - m->m_pkthdr.len);
516 uma_zfree(V_pf_frent_z, frent);
517 for (frent = next; frent != NULL; frent = next) {
518 next = TAILQ_NEXT(frent, fr_next);
521 /* Strip off ip header. */
522 m_adj(m2, frent->fe_hdrlen);
523 /* Strip off any trailing bytes. */
524 m_adj(m2, frent->fe_len - m2->m_pkthdr.len);
526 uma_zfree(V_pf_frent_z, frent);
530 /* Remove from fragment queue. */
531 pf_remove_fragment(frag);
538 pf_reassemble(struct mbuf **m0, struct ip *ip, int dir, u_short *reason)
540 struct mbuf *m = *m0;
541 struct pf_frent *frent;
542 struct pf_fragment *frag;
543 struct pf_fragment_cmp key;
544 uint16_t total, hdrlen;
546 /* Get an entry for the fragment queue */
547 if ((frent = pf_create_fragment(reason)) == NULL)
551 frent->fe_hdrlen = ip->ip_hl << 2;
552 frent->fe_extoff = 0;
553 frent->fe_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
554 frent->fe_off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
555 frent->fe_mff = ntohs(ip->ip_off) & IP_MF;
557 pf_ip2key(ip, dir, &key);
559 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL)
562 /* The mbuf is part of the fragment entry, no direct free or access */
565 if (!pf_isfull_fragment(frag))
566 return (PF_PASS); /* drop because *m0 is NULL, no error */
568 /* We have all the data */
569 frent = TAILQ_FIRST(&frag->fr_queue);
570 KASSERT(frent != NULL, ("frent != NULL"));
571 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
572 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
573 hdrlen = frent->fe_hdrlen;
575 m = *m0 = pf_join_fragment(frag);
578 if (m->m_flags & M_PKTHDR) {
580 for (m = *m0; m; m = m->m_next)
583 m->m_pkthdr.len = plen;
586 ip = mtod(m, struct ip *);
587 ip->ip_len = htons(hdrlen + total);
588 ip->ip_off &= ~(IP_MF|IP_OFFMASK);
590 if (hdrlen + total > IP_MAXPACKET) {
591 DPFPRINTF(("drop: too big: %d", total));
593 REASON_SET(reason, PFRES_SHORT);
594 /* PF_DROP requires a valid mbuf *m0 in pf_test() */
598 DPFPRINTF(("complete: %p(%d)\n", m, ntohs(ip->ip_len)));
605 pf_reassemble6(struct mbuf **m0, struct ip6_hdr *ip6, struct ip6_frag *fraghdr,
606 uint16_t hdrlen, uint16_t extoff, u_short *reason)
608 struct mbuf *m = *m0;
609 struct pf_frent *frent;
610 struct pf_fragment *frag;
611 struct pf_fragment_cmp key;
613 struct pf_fragment_tag *ftag;
616 uint16_t total, maxlen;
621 /* Get an entry for the fragment queue. */
622 if ((frent = pf_create_fragment(reason)) == NULL) {
628 frent->fe_hdrlen = hdrlen;
629 frent->fe_extoff = extoff;
630 frent->fe_len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - hdrlen;
631 frent->fe_off = ntohs(fraghdr->ip6f_offlg & IP6F_OFF_MASK);
632 frent->fe_mff = fraghdr->ip6f_offlg & IP6F_MORE_FRAG;
634 key.frc_src.v6 = ip6->ip6_src;
635 key.frc_dst.v6 = ip6->ip6_dst;
636 key.frc_af = AF_INET6;
637 /* Only the first fragment's protocol is relevant. */
639 key.frc_id = fraghdr->ip6f_ident;
641 if ((frag = pf_fillup_fragment(&key, frent, reason)) == NULL) {
646 /* The mbuf is part of the fragment entry, no direct free or access. */
649 if (!pf_isfull_fragment(frag)) {
651 return (PF_PASS); /* Drop because *m0 is NULL, no error. */
654 /* We have all the data. */
655 extoff = frent->fe_extoff;
656 maxlen = frag->fr_maxlen;
657 frag_id = frag->fr_id;
658 frent = TAILQ_FIRST(&frag->fr_queue);
659 KASSERT(frent != NULL, ("frent != NULL"));
660 total = TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_off +
661 TAILQ_LAST(&frag->fr_queue, pf_fragq)->fe_len;
662 hdrlen = frent->fe_hdrlen - sizeof(struct ip6_frag);
664 m = *m0 = pf_join_fragment(frag);
669 /* Take protocol from first fragment header. */
670 m = m_getptr(m, hdrlen + offsetof(struct ip6_frag, ip6f_nxt), &off);
671 KASSERT(m, ("%s: short mbuf chain", __func__));
672 proto = *(mtod(m, caddr_t) + off);
675 /* Delete frag6 header */
676 if (ip6_deletefraghdr(m, hdrlen, M_NOWAIT) != 0)
679 if (m->m_flags & M_PKTHDR) {
681 for (m = *m0; m; m = m->m_next)
684 m->m_pkthdr.len = plen;
687 if ((mtag = m_tag_get(PF_REASSEMBLED, sizeof(struct pf_fragment_tag),
690 ftag = (struct pf_fragment_tag *)(mtag + 1);
691 ftag->ft_hdrlen = hdrlen;
692 ftag->ft_extoff = extoff;
693 ftag->ft_maxlen = maxlen;
694 ftag->ft_id = frag_id;
695 m_tag_prepend(m, mtag);
697 ip6 = mtod(m, struct ip6_hdr *);
698 ip6->ip6_plen = htons(hdrlen - sizeof(struct ip6_hdr) + total);
700 /* Write protocol into next field of last extension header. */
701 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
703 KASSERT(m, ("%s: short mbuf chain", __func__));
704 *(mtod(m, char *) + off) = proto;
707 ip6->ip6_nxt = proto;
709 if (hdrlen - sizeof(struct ip6_hdr) + total > IPV6_MAXPACKET) {
710 DPFPRINTF(("drop: too big: %d", total));
712 REASON_SET(reason, PFRES_SHORT);
713 /* PF_DROP requires a valid mbuf *m0 in pf_test6(). */
717 DPFPRINTF(("complete: %p(%d)", m, ntohs(ip6->ip6_plen)));
721 REASON_SET(reason, PFRES_MEMORY);
722 /* PF_DROP requires a valid mbuf *m0 in pf_test6(), will free later. */
729 pf_refragment6(struct ifnet *ifp, struct mbuf **m0, struct m_tag *mtag)
731 struct mbuf *m = *m0, *t;
732 struct pf_fragment_tag *ftag = (struct pf_fragment_tag *)(mtag + 1);
735 uint16_t hdrlen, extoff, maxlen;
739 hdrlen = ftag->ft_hdrlen;
740 extoff = ftag->ft_extoff;
741 maxlen = ftag->ft_maxlen;
742 frag_id = ftag->ft_id;
743 m_tag_delete(m, mtag);
750 /* Use protocol from next field of last extension header */
751 m = m_getptr(m, extoff + offsetof(struct ip6_ext, ip6e_nxt),
753 KASSERT((m != NULL), ("pf_refragment6: short mbuf chain"));
754 proto = *(mtod(m, caddr_t) + off);
755 *(mtod(m, char *) + off) = IPPROTO_FRAGMENT;
760 hdr = mtod(m, struct ip6_hdr *);
761 proto = hdr->ip6_nxt;
762 hdr->ip6_nxt = IPPROTO_FRAGMENT;
766 * Maxlen may be less than 8 if there was only a single
767 * fragment. As it was fragmented before, add a fragment
768 * header also for a single fragment. If total or maxlen
769 * is less than 8, ip6_fragment() will return EMSGSIZE and
770 * we drop the packet.
772 error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
773 m = (*m0)->m_nextpkt;
774 (*m0)->m_nextpkt = NULL;
776 /* The first mbuf contains the unfragmented packet. */
781 /* Drop expects an mbuf to free. */
782 DPFPRINTF(("refragment error %d", error));
785 for (t = m; m; m = t) {
788 m->m_flags |= M_SKIP_FIREWALL;
789 memset(&pd, 0, sizeof(pd));
790 pd.pf_mtag = pf_find_mtag(m);
803 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
806 struct mbuf *m = *m0;
808 struct ip *h = mtod(m, struct ip *);
809 int mff = (ntohs(h->ip_off) & IP_MF);
810 int hlen = h->ip_hl << 2;
811 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
820 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
823 if (pfi_kif_match(r->kif, kif) == r->ifnot)
824 r = r->skip[PF_SKIP_IFP].ptr;
825 else if (r->direction && r->direction != dir)
826 r = r->skip[PF_SKIP_DIR].ptr;
827 else if (r->af && r->af != AF_INET)
828 r = r->skip[PF_SKIP_AF].ptr;
829 else if (r->proto && r->proto != h->ip_p)
830 r = r->skip[PF_SKIP_PROTO].ptr;
831 else if (PF_MISMATCHAW(&r->src.addr,
832 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
833 r->src.neg, kif, M_GETFIB(m)))
834 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
835 else if (PF_MISMATCHAW(&r->dst.addr,
836 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
837 r->dst.neg, NULL, M_GETFIB(m)))
838 r = r->skip[PF_SKIP_DST_ADDR].ptr;
839 else if (r->match_tag && !pf_match_tag(m, r, &tag,
840 pd->pf_mtag ? pd->pf_mtag->tag : 0))
841 r = TAILQ_NEXT(r, entries);
846 if (r == NULL || r->action == PF_NOSCRUB)
849 r->packets[dir == PF_OUT]++;
850 r->bytes[dir == PF_OUT] += pd->tot_len;
853 /* Check for illegal packets */
854 if (hlen < (int)sizeof(struct ip)) {
855 REASON_SET(reason, PFRES_NORM);
859 if (hlen > ntohs(h->ip_len)) {
860 REASON_SET(reason, PFRES_NORM);
864 /* Clear IP_DF if the rule uses the no-df option */
865 if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
866 u_int16_t ip_off = h->ip_off;
868 h->ip_off &= htons(~IP_DF);
869 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
872 /* We will need other tests here */
873 if (!fragoff && !mff)
876 /* We're dealing with a fragment now. Don't allow fragments
877 * with IP_DF to enter the cache. If the flag was cleared by
878 * no-df above, fine. Otherwise drop it.
880 if (h->ip_off & htons(IP_DF)) {
881 DPFPRINTF(("IP_DF\n"));
885 ip_len = ntohs(h->ip_len) - hlen;
886 ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
888 /* All fragments are 8 byte aligned */
889 if (mff && (ip_len & 0x7)) {
890 DPFPRINTF(("mff and %d\n", ip_len));
894 /* Respect maximum length */
895 if (fragoff + ip_len > IP_MAXPACKET) {
896 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
899 max = fragoff + ip_len;
901 /* Fully buffer all of the fragments
902 * Might return a completely reassembled mbuf, or NULL */
904 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
905 verdict = pf_reassemble(m0, h, dir, reason);
908 if (verdict != PF_PASS)
915 h = mtod(m, struct ip *);
918 /* At this point, only IP_DF is allowed in ip_off */
919 if (h->ip_off & ~htons(IP_DF)) {
920 u_int16_t ip_off = h->ip_off;
922 h->ip_off &= htons(IP_DF);
923 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
926 pf_scrub_ip(&m, r->rule_flag, r->min_ttl, r->set_tos);
931 DPFPRINTF(("dropping bad fragment\n"));
932 REASON_SET(reason, PFRES_FRAG);
934 if (r != NULL && r->log)
935 PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
944 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
945 u_short *reason, struct pf_pdesc *pd)
947 struct mbuf *m = *m0;
949 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
954 struct ip6_opt_jumbo jumbo;
955 struct ip6_frag frag;
956 u_int32_t jumbolen = 0, plen;
964 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
967 if (pfi_kif_match(r->kif, kif) == r->ifnot)
968 r = r->skip[PF_SKIP_IFP].ptr;
969 else if (r->direction && r->direction != dir)
970 r = r->skip[PF_SKIP_DIR].ptr;
971 else if (r->af && r->af != AF_INET6)
972 r = r->skip[PF_SKIP_AF].ptr;
973 #if 0 /* header chain! */
974 else if (r->proto && r->proto != h->ip6_nxt)
975 r = r->skip[PF_SKIP_PROTO].ptr;
977 else if (PF_MISMATCHAW(&r->src.addr,
978 (struct pf_addr *)&h->ip6_src, AF_INET6,
979 r->src.neg, kif, M_GETFIB(m)))
980 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
981 else if (PF_MISMATCHAW(&r->dst.addr,
982 (struct pf_addr *)&h->ip6_dst, AF_INET6,
983 r->dst.neg, NULL, M_GETFIB(m)))
984 r = r->skip[PF_SKIP_DST_ADDR].ptr;
989 if (r == NULL || r->action == PF_NOSCRUB)
992 r->packets[dir == PF_OUT]++;
993 r->bytes[dir == PF_OUT] += pd->tot_len;
996 /* Check for illegal packets */
997 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1001 off = sizeof(struct ip6_hdr);
1006 case IPPROTO_FRAGMENT:
1010 case IPPROTO_ROUTING:
1011 case IPPROTO_DSTOPTS:
1012 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1016 if (proto == IPPROTO_AH)
1017 off += (ext.ip6e_len + 2) * 4;
1019 off += (ext.ip6e_len + 1) * 8;
1020 proto = ext.ip6e_nxt;
1022 case IPPROTO_HOPOPTS:
1023 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1027 optend = off + (ext.ip6e_len + 1) * 8;
1028 ooff = off + sizeof(ext);
1030 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1031 sizeof(opt.ip6o_type), NULL, NULL,
1034 if (opt.ip6o_type == IP6OPT_PAD1) {
1038 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1039 NULL, NULL, AF_INET6))
1041 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1043 switch (opt.ip6o_type) {
1045 if (h->ip6_plen != 0)
1047 if (!pf_pull_hdr(m, ooff, &jumbo,
1048 sizeof(jumbo), NULL, NULL,
1051 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1053 jumbolen = ntohl(jumbolen);
1054 if (jumbolen <= IPV6_MAXPACKET)
1056 if (sizeof(struct ip6_hdr) + jumbolen !=
1063 ooff += sizeof(opt) + opt.ip6o_len;
1064 } while (ooff < optend);
1067 proto = ext.ip6e_nxt;
1073 } while (!terminal);
1075 /* jumbo payload option must be present, or plen > 0 */
1076 if (ntohs(h->ip6_plen) == 0)
1079 plen = ntohs(h->ip6_plen);
1082 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1085 pf_scrub_ip6(&m, r->min_ttl);
1090 /* Jumbo payload packets cannot be fragmented. */
1091 plen = ntohs(h->ip6_plen);
1092 if (plen == 0 || jumbolen)
1094 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1097 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1100 /* Offset now points to data portion. */
1101 off += sizeof(frag);
1103 /* Returns PF_DROP or *m0 is NULL or completely reassembled mbuf. */
1104 if (pf_reassemble6(m0, h, &frag, off, extoff, reason) != PF_PASS)
1110 pd->flags |= PFDESC_IP_REAS;
1114 REASON_SET(reason, PFRES_SHORT);
1115 if (r != NULL && r->log)
1116 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1121 REASON_SET(reason, PFRES_NORM);
1122 if (r != NULL && r->log)
1123 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1130 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1131 int off, void *h, struct pf_pdesc *pd)
1133 struct pf_rule *r, *rm = NULL;
1134 struct tcphdr *th = pd->hdr.tcp;
1138 sa_family_t af = pd->af;
1142 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1145 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1146 r = r->skip[PF_SKIP_IFP].ptr;
1147 else if (r->direction && r->direction != dir)
1148 r = r->skip[PF_SKIP_DIR].ptr;
1149 else if (r->af && r->af != af)
1150 r = r->skip[PF_SKIP_AF].ptr;
1151 else if (r->proto && r->proto != pd->proto)
1152 r = r->skip[PF_SKIP_PROTO].ptr;
1153 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1154 r->src.neg, kif, M_GETFIB(m)))
1155 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1156 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1157 r->src.port[0], r->src.port[1], th->th_sport))
1158 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1159 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1160 r->dst.neg, NULL, M_GETFIB(m)))
1161 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1162 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1163 r->dst.port[0], r->dst.port[1], th->th_dport))
1164 r = r->skip[PF_SKIP_DST_PORT].ptr;
1165 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1166 pf_osfp_fingerprint(pd, m, off, th),
1168 r = TAILQ_NEXT(r, entries);
1175 if (rm == NULL || rm->action == PF_NOSCRUB)
1178 r->packets[dir == PF_OUT]++;
1179 r->bytes[dir == PF_OUT] += pd->tot_len;
1182 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1183 pd->flags |= PFDESC_TCP_NORM;
1185 flags = th->th_flags;
1186 if (flags & TH_SYN) {
1187 /* Illegal packet */
1194 /* Illegal packet */
1195 if (!(flags & (TH_ACK|TH_RST)))
1199 if (!(flags & TH_ACK)) {
1200 /* These flags are only valid if ACK is set */
1201 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1205 /* Check for illegal header length */
1206 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1209 /* If flags changed, or reserved data set, then adjust */
1210 if (flags != th->th_flags || th->th_x2 != 0) {
1213 ov = *(u_int16_t *)(&th->th_ack + 1);
1214 th->th_flags = flags;
1216 nv = *(u_int16_t *)(&th->th_ack + 1);
1218 th->th_sum = pf_cksum_fixup(th->th_sum, ov, nv, 0);
1222 /* Remove urgent pointer, if TH_URG is not set */
1223 if (!(flags & TH_URG) && th->th_urp) {
1224 th->th_sum = pf_cksum_fixup(th->th_sum, th->th_urp, 0, 0);
1229 /* Process options */
1230 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1233 /* copy back packet headers if we sanitized */
1235 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1240 REASON_SET(&reason, PFRES_NORM);
1241 if (rm != NULL && r->log)
1242 PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1248 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1249 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1251 u_int32_t tsval, tsecr;
1255 KASSERT((src->scrub == NULL),
1256 ("pf_normalize_tcp_init: src->scrub != NULL"));
1258 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1259 if (src->scrub == NULL)
1265 struct ip *h = mtod(m, struct ip *);
1266 src->scrub->pfss_ttl = h->ip_ttl;
1272 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1273 src->scrub->pfss_ttl = h->ip6_hlim;
1281 * All normalizations below are only begun if we see the start of
1282 * the connections. They must all set an enabled bit in pfss_flags
1284 if ((th->th_flags & TH_SYN) == 0)
1288 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1289 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1290 /* Diddle with TCP options */
1292 opt = hdr + sizeof(struct tcphdr);
1293 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1294 while (hlen >= TCPOLEN_TIMESTAMP) {
1296 case TCPOPT_EOL: /* FALLTHROUGH */
1301 case TCPOPT_TIMESTAMP:
1302 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1303 src->scrub->pfss_flags |=
1305 src->scrub->pfss_ts_mod =
1306 htonl(arc4random());
1308 /* note PFSS_PAWS not set yet */
1309 memcpy(&tsval, &opt[2],
1311 memcpy(&tsecr, &opt[6],
1313 src->scrub->pfss_tsval0 = ntohl(tsval);
1314 src->scrub->pfss_tsval = ntohl(tsval);
1315 src->scrub->pfss_tsecr = ntohl(tsecr);
1316 getmicrouptime(&src->scrub->pfss_last);
1320 hlen -= MAX(opt[1], 2);
1321 opt += MAX(opt[1], 2);
1331 pf_normalize_tcp_cleanup(struct pf_state *state)
1333 if (state->src.scrub)
1334 uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1335 if (state->dst.scrub)
1336 uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1338 /* Someday... flush the TCP segment reassembly descriptors. */
1342 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1343 u_short *reason, struct tcphdr *th, struct pf_state *state,
1344 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1346 struct timeval uptime;
1347 u_int32_t tsval, tsecr;
1348 u_int tsval_from_last;
1354 KASSERT((src->scrub || dst->scrub),
1355 ("%s: src->scrub && dst->scrub!", __func__));
1358 * Enforce the minimum TTL seen for this connection. Negate a common
1359 * technique to evade an intrusion detection system and confuse
1360 * firewall state code.
1366 struct ip *h = mtod(m, struct ip *);
1367 if (h->ip_ttl > src->scrub->pfss_ttl)
1368 src->scrub->pfss_ttl = h->ip_ttl;
1369 h->ip_ttl = src->scrub->pfss_ttl;
1377 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1378 if (h->ip6_hlim > src->scrub->pfss_ttl)
1379 src->scrub->pfss_ttl = h->ip6_hlim;
1380 h->ip6_hlim = src->scrub->pfss_ttl;
1387 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1388 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1389 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1390 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1391 /* Diddle with TCP options */
1393 opt = hdr + sizeof(struct tcphdr);
1394 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1395 while (hlen >= TCPOLEN_TIMESTAMP) {
1397 case TCPOPT_EOL: /* FALLTHROUGH */
1402 case TCPOPT_TIMESTAMP:
1403 /* Modulate the timestamps. Can be used for
1404 * NAT detection, OS uptime determination or
1409 /* Huh? Multiple timestamps!? */
1410 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1411 DPFPRINTF(("multiple TS??"));
1412 pf_print_state(state);
1415 REASON_SET(reason, PFRES_TS);
1418 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1419 memcpy(&tsval, &opt[2],
1421 if (tsval && src->scrub &&
1422 (src->scrub->pfss_flags &
1424 tsval = ntohl(tsval);
1425 pf_change_a(&opt[2],
1428 src->scrub->pfss_ts_mod),
1433 /* Modulate TS reply iff valid (!0) */
1434 memcpy(&tsecr, &opt[6],
1436 if (tsecr && dst->scrub &&
1437 (dst->scrub->pfss_flags &
1439 tsecr = ntohl(tsecr)
1440 - dst->scrub->pfss_ts_mod;
1441 pf_change_a(&opt[6],
1442 &th->th_sum, htonl(tsecr),
1450 hlen -= MAX(opt[1], 2);
1451 opt += MAX(opt[1], 2);
1456 /* Copyback the options, caller copys back header */
1458 m_copyback(m, off + sizeof(struct tcphdr),
1459 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1460 sizeof(struct tcphdr));
1466 * Must invalidate PAWS checks on connections idle for too long.
1467 * The fastest allowed timestamp clock is 1ms. That turns out to
1468 * be about 24 days before it wraps. XXX Right now our lowerbound
1469 * TS echo check only works for the first 12 days of a connection
1470 * when the TS has exhausted half its 32bit space
1472 #define TS_MAX_IDLE (24*24*60*60)
1473 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1475 getmicrouptime(&uptime);
1476 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1477 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1478 time_uptime - state->creation > TS_MAX_CONN)) {
1479 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1480 DPFPRINTF(("src idled out of PAWS\n"));
1481 pf_print_state(state);
1484 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1487 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1488 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1489 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1490 DPFPRINTF(("dst idled out of PAWS\n"));
1491 pf_print_state(state);
1494 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1498 if (got_ts && src->scrub && dst->scrub &&
1499 (src->scrub->pfss_flags & PFSS_PAWS) &&
1500 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1501 /* Validate that the timestamps are "in-window".
1502 * RFC1323 describes TCP Timestamp options that allow
1503 * measurement of RTT (round trip time) and PAWS
1504 * (protection against wrapped sequence numbers). PAWS
1505 * gives us a set of rules for rejecting packets on
1506 * long fat pipes (packets that were somehow delayed
1507 * in transit longer than the time it took to send the
1508 * full TCP sequence space of 4Gb). We can use these
1509 * rules and infer a few others that will let us treat
1510 * the 32bit timestamp and the 32bit echoed timestamp
1511 * as sequence numbers to prevent a blind attacker from
1512 * inserting packets into a connection.
1515 * - The timestamp on this packet must be greater than
1516 * or equal to the last value echoed by the other
1517 * endpoint. The RFC says those will be discarded
1518 * since it is a dup that has already been acked.
1519 * This gives us a lowerbound on the timestamp.
1520 * timestamp >= other last echoed timestamp
1521 * - The timestamp will be less than or equal to
1522 * the last timestamp plus the time between the
1523 * last packet and now. The RFC defines the max
1524 * clock rate as 1ms. We will allow clocks to be
1525 * up to 10% fast and will allow a total difference
1526 * or 30 seconds due to a route change. And this
1527 * gives us an upperbound on the timestamp.
1528 * timestamp <= last timestamp + max ticks
1529 * We have to be careful here. Windows will send an
1530 * initial timestamp of zero and then initialize it
1531 * to a random value after the 3whs; presumably to
1532 * avoid a DoS by having to call an expensive RNG
1533 * during a SYN flood. Proof MS has at least one
1534 * good security geek.
1536 * - The TCP timestamp option must also echo the other
1537 * endpoints timestamp. The timestamp echoed is the
1538 * one carried on the earliest unacknowledged segment
1539 * on the left edge of the sequence window. The RFC
1540 * states that the host will reject any echoed
1541 * timestamps that were larger than any ever sent.
1542 * This gives us an upperbound on the TS echo.
1543 * tescr <= largest_tsval
1544 * - The lowerbound on the TS echo is a little more
1545 * tricky to determine. The other endpoint's echoed
1546 * values will not decrease. But there may be
1547 * network conditions that re-order packets and
1548 * cause our view of them to decrease. For now the
1549 * only lowerbound we can safely determine is that
1550 * the TS echo will never be less than the original
1551 * TS. XXX There is probably a better lowerbound.
1552 * Remove TS_MAX_CONN with better lowerbound check.
1553 * tescr >= other original TS
1555 * It is also important to note that the fastest
1556 * timestamp clock of 1ms will wrap its 32bit space in
1557 * 24 days. So we just disable TS checking after 24
1558 * days of idle time. We actually must use a 12d
1559 * connection limit until we can come up with a better
1560 * lowerbound to the TS echo check.
1562 struct timeval delta_ts;
1567 * PFTM_TS_DIFF is how many seconds of leeway to allow
1568 * a host's timestamp. This can happen if the previous
1569 * packet got delayed in transit for much longer than
1572 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1573 ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1575 /* Calculate max ticks since the last timestamp */
1576 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1577 #define TS_MICROSECS 1000000 /* microseconds per second */
1579 timevalsub(&delta_ts, &src->scrub->pfss_last);
1580 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1581 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1583 if ((src->state >= TCPS_ESTABLISHED &&
1584 dst->state >= TCPS_ESTABLISHED) &&
1585 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1586 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1587 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1588 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1589 /* Bad RFC1323 implementation or an insertion attack.
1591 * - Solaris 2.6 and 2.7 are known to send another ACK
1592 * after the FIN,FIN|ACK,ACK closing that carries
1596 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1597 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1598 SEQ_GT(tsval, src->scrub->pfss_tsval +
1599 tsval_from_last) ? '1' : ' ',
1600 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1601 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1602 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1603 "idle: %jus %lums\n",
1604 tsval, tsecr, tsval_from_last,
1605 (uintmax_t)delta_ts.tv_sec,
1606 delta_ts.tv_usec / 1000));
1607 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1608 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1609 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1610 "\n", dst->scrub->pfss_tsval,
1611 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1612 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1613 pf_print_state(state);
1614 pf_print_flags(th->th_flags);
1617 REASON_SET(reason, PFRES_TS);
1621 /* XXX I'd really like to require tsecr but it's optional */
1623 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1624 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1625 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1626 src->scrub && dst->scrub &&
1627 (src->scrub->pfss_flags & PFSS_PAWS) &&
1628 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1629 /* Didn't send a timestamp. Timestamps aren't really useful
1631 * - connection opening or closing (often not even sent).
1632 * but we must not let an attacker to put a FIN on a
1633 * data packet to sneak it through our ESTABLISHED check.
1634 * - on a TCP reset. RFC suggests not even looking at TS.
1635 * - on an empty ACK. The TS will not be echoed so it will
1636 * probably not help keep the RTT calculation in sync and
1637 * there isn't as much danger when the sequence numbers
1638 * got wrapped. So some stacks don't include TS on empty
1641 * To minimize the disruption to mostly RFC1323 conformant
1642 * stacks, we will only require timestamps on data packets.
1644 * And what do ya know, we cannot require timestamps on data
1645 * packets. There appear to be devices that do legitimate
1646 * TCP connection hijacking. There are HTTP devices that allow
1647 * a 3whs (with timestamps) and then buffer the HTTP request.
1648 * If the intermediate device has the HTTP response cache, it
1649 * will spoof the response but not bother timestamping its
1650 * packets. So we can look for the presence of a timestamp in
1651 * the first data packet and if there, require it in all future
1655 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1657 * Hey! Someone tried to sneak a packet in. Or the
1658 * stack changed its RFC1323 behavior?!?!
1660 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1661 DPFPRINTF(("Did not receive expected RFC1323 "
1663 pf_print_state(state);
1664 pf_print_flags(th->th_flags);
1667 REASON_SET(reason, PFRES_TS);
1674 * We will note if a host sends his data packets with or without
1675 * timestamps. And require all data packets to contain a timestamp
1676 * if the first does. PAWS implicitly requires that all data packets be
1677 * timestamped. But I think there are middle-man devices that hijack
1678 * TCP streams immediately after the 3whs and don't timestamp their
1679 * packets (seen in a WWW accelerator or cache).
1681 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1682 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1684 src->scrub->pfss_flags |= PFSS_DATA_TS;
1686 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1687 if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1688 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1689 /* Don't warn if other host rejected RFC1323 */
1690 DPFPRINTF(("Broken RFC1323 stack did not "
1691 "timestamp data packet. Disabled PAWS "
1693 pf_print_state(state);
1694 pf_print_flags(th->th_flags);
1702 * Update PAWS values
1704 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1705 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1706 getmicrouptime(&src->scrub->pfss_last);
1707 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1708 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1709 src->scrub->pfss_tsval = tsval;
1712 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1713 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1714 src->scrub->pfss_tsecr = tsecr;
1716 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1717 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1718 src->scrub->pfss_tsval0 == 0)) {
1719 /* tsval0 MUST be the lowest timestamp */
1720 src->scrub->pfss_tsval0 = tsval;
1723 /* Only fully initialized after a TS gets echoed */
1724 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1725 src->scrub->pfss_flags |= PFSS_PAWS;
1729 /* I have a dream.... TCP segment reassembly.... */
1734 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1735 int off, sa_family_t af)
1739 int opt, cnt, optlen = 0;
1741 u_char opts[TCP_MAXOLEN];
1742 u_char *optp = opts;
1744 thoff = th->th_off << 2;
1745 cnt = thoff - sizeof(struct tcphdr);
1747 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1751 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1753 if (opt == TCPOPT_EOL)
1755 if (opt == TCPOPT_NOP)
1761 if (optlen < 2 || optlen > cnt)
1766 mss = (u_int16_t *)(optp + 2);
1767 if ((ntohs(*mss)) > r->max_mss) {
1768 th->th_sum = pf_cksum_fixup(th->th_sum,
1769 *mss, htons(r->max_mss), 0);
1770 *mss = htons(r->max_mss);
1780 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1787 pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
1789 struct mbuf *m = *m0;
1790 struct ip *h = mtod(m, struct ip *);
1792 /* Clear IP_DF if no-df was requested */
1793 if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1794 u_int16_t ip_off = h->ip_off;
1796 h->ip_off &= htons(~IP_DF);
1797 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1800 /* Enforce a minimum ttl, may cause endless packet loops */
1801 if (min_ttl && h->ip_ttl < min_ttl) {
1802 u_int16_t ip_ttl = h->ip_ttl;
1804 h->ip_ttl = min_ttl;
1805 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1809 if (flags & PFRULE_SET_TOS) {
1812 ov = *(u_int16_t *)h;
1814 nv = *(u_int16_t *)h;
1816 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1819 /* random-id, but not for fragments */
1820 if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
1821 uint16_t ip_id = h->ip_id;
1824 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1831 pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
1833 struct mbuf *m = *m0;
1834 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1836 /* Enforce a minimum ttl, may cause endless packet loops */
1837 if (min_ttl && h->ip6_hlim < min_ttl)
1838 h->ip6_hlim = min_ttl;