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 length 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_uptime;
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;
765 /* The MTU must be a multiple of 8 bytes, or we risk doing the
766 * fragmentation wrong. */
767 maxlen = maxlen & ~7;
770 * Maxlen may be less than 8 if there was only a single
771 * fragment. As it was fragmented before, add a fragment
772 * header also for a single fragment. If total or maxlen
773 * is less than 8, ip6_fragment() will return EMSGSIZE and
774 * we drop the packet.
776 error = ip6_fragment(ifp, m, hdrlen, proto, maxlen, frag_id);
777 m = (*m0)->m_nextpkt;
778 (*m0)->m_nextpkt = NULL;
780 /* The first mbuf contains the unfragmented packet. */
785 /* Drop expects an mbuf to free. */
786 DPFPRINTF(("refragment error %d", error));
789 for (t = m; m; m = t) {
792 m->m_flags |= M_SKIP_FIREWALL;
793 memset(&pd, 0, sizeof(pd));
794 pd.pf_mtag = pf_find_mtag(m);
807 pf_normalize_ip(struct mbuf **m0, int dir, struct pfi_kif *kif, u_short *reason,
810 struct mbuf *m = *m0;
812 struct ip *h = mtod(m, struct ip *);
813 int mff = (ntohs(h->ip_off) & IP_MF);
814 int hlen = h->ip_hl << 2;
815 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
824 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
827 if (pfi_kif_match(r->kif, kif) == r->ifnot)
828 r = r->skip[PF_SKIP_IFP].ptr;
829 else if (r->direction && r->direction != dir)
830 r = r->skip[PF_SKIP_DIR].ptr;
831 else if (r->af && r->af != AF_INET)
832 r = r->skip[PF_SKIP_AF].ptr;
833 else if (r->proto && r->proto != h->ip_p)
834 r = r->skip[PF_SKIP_PROTO].ptr;
835 else if (PF_MISMATCHAW(&r->src.addr,
836 (struct pf_addr *)&h->ip_src.s_addr, AF_INET,
837 r->src.neg, kif, M_GETFIB(m)))
838 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
839 else if (PF_MISMATCHAW(&r->dst.addr,
840 (struct pf_addr *)&h->ip_dst.s_addr, AF_INET,
841 r->dst.neg, NULL, M_GETFIB(m)))
842 r = r->skip[PF_SKIP_DST_ADDR].ptr;
843 else if (r->match_tag && !pf_match_tag(m, r, &tag,
844 pd->pf_mtag ? pd->pf_mtag->tag : 0))
845 r = TAILQ_NEXT(r, entries);
850 if (r == NULL || r->action == PF_NOSCRUB)
853 r->packets[dir == PF_OUT]++;
854 r->bytes[dir == PF_OUT] += pd->tot_len;
857 /* Check for illegal packets */
858 if (hlen < (int)sizeof(struct ip)) {
859 REASON_SET(reason, PFRES_NORM);
863 if (hlen > ntohs(h->ip_len)) {
864 REASON_SET(reason, PFRES_NORM);
868 /* Clear IP_DF if the rule uses the no-df option */
869 if (r->rule_flag & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
870 u_int16_t ip_off = h->ip_off;
872 h->ip_off &= htons(~IP_DF);
873 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
876 /* We will need other tests here */
877 if (!fragoff && !mff)
880 /* We're dealing with a fragment now. Don't allow fragments
881 * with IP_DF to enter the cache. If the flag was cleared by
882 * no-df above, fine. Otherwise drop it.
884 if (h->ip_off & htons(IP_DF)) {
885 DPFPRINTF(("IP_DF\n"));
889 ip_len = ntohs(h->ip_len) - hlen;
890 ip_off = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
892 /* All fragments are 8 byte aligned */
893 if (mff && (ip_len & 0x7)) {
894 DPFPRINTF(("mff and %d\n", ip_len));
898 /* Respect maximum length */
899 if (fragoff + ip_len > IP_MAXPACKET) {
900 DPFPRINTF(("max packet %d\n", fragoff + ip_len));
903 max = fragoff + ip_len;
905 /* Fully buffer all of the fragments
906 * Might return a completely reassembled mbuf, or NULL */
908 DPFPRINTF(("reass frag %d @ %d-%d\n", h->ip_id, fragoff, max));
909 verdict = pf_reassemble(m0, h, dir, reason);
912 if (verdict != PF_PASS)
919 h = mtod(m, struct ip *);
922 /* At this point, only IP_DF is allowed in ip_off */
923 if (h->ip_off & ~htons(IP_DF)) {
924 u_int16_t ip_off = h->ip_off;
926 h->ip_off &= htons(IP_DF);
927 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
930 pf_scrub_ip(&m, r->rule_flag, r->min_ttl, r->set_tos);
935 DPFPRINTF(("dropping bad fragment\n"));
936 REASON_SET(reason, PFRES_FRAG);
938 if (r != NULL && r->log)
939 PFLOG_PACKET(kif, m, AF_INET, dir, *reason, r, NULL, NULL, pd,
948 pf_normalize_ip6(struct mbuf **m0, int dir, struct pfi_kif *kif,
949 u_short *reason, struct pf_pdesc *pd)
951 struct mbuf *m = *m0;
953 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
958 struct ip6_opt_jumbo jumbo;
959 struct ip6_frag frag;
960 u_int32_t jumbolen = 0, plen;
968 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
971 if (pfi_kif_match(r->kif, kif) == r->ifnot)
972 r = r->skip[PF_SKIP_IFP].ptr;
973 else if (r->direction && r->direction != dir)
974 r = r->skip[PF_SKIP_DIR].ptr;
975 else if (r->af && r->af != AF_INET6)
976 r = r->skip[PF_SKIP_AF].ptr;
977 #if 0 /* header chain! */
978 else if (r->proto && r->proto != h->ip6_nxt)
979 r = r->skip[PF_SKIP_PROTO].ptr;
981 else if (PF_MISMATCHAW(&r->src.addr,
982 (struct pf_addr *)&h->ip6_src, AF_INET6,
983 r->src.neg, kif, M_GETFIB(m)))
984 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
985 else if (PF_MISMATCHAW(&r->dst.addr,
986 (struct pf_addr *)&h->ip6_dst, AF_INET6,
987 r->dst.neg, NULL, M_GETFIB(m)))
988 r = r->skip[PF_SKIP_DST_ADDR].ptr;
993 if (r == NULL || r->action == PF_NOSCRUB)
996 r->packets[dir == PF_OUT]++;
997 r->bytes[dir == PF_OUT] += pd->tot_len;
1000 /* Check for illegal packets */
1001 if (sizeof(struct ip6_hdr) + IPV6_MAXPACKET < m->m_pkthdr.len)
1005 off = sizeof(struct ip6_hdr);
1010 case IPPROTO_FRAGMENT:
1014 case IPPROTO_ROUTING:
1015 case IPPROTO_DSTOPTS:
1016 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1020 if (proto == IPPROTO_AH)
1021 off += (ext.ip6e_len + 2) * 4;
1023 off += (ext.ip6e_len + 1) * 8;
1024 proto = ext.ip6e_nxt;
1026 case IPPROTO_HOPOPTS:
1027 if (!pf_pull_hdr(m, off, &ext, sizeof(ext), NULL,
1031 optend = off + (ext.ip6e_len + 1) * 8;
1032 ooff = off + sizeof(ext);
1034 if (!pf_pull_hdr(m, ooff, &opt.ip6o_type,
1035 sizeof(opt.ip6o_type), NULL, NULL,
1038 if (opt.ip6o_type == IP6OPT_PAD1) {
1042 if (!pf_pull_hdr(m, ooff, &opt, sizeof(opt),
1043 NULL, NULL, AF_INET6))
1045 if (ooff + sizeof(opt) + opt.ip6o_len > optend)
1047 switch (opt.ip6o_type) {
1049 if (h->ip6_plen != 0)
1051 if (!pf_pull_hdr(m, ooff, &jumbo,
1052 sizeof(jumbo), NULL, NULL,
1055 memcpy(&jumbolen, jumbo.ip6oj_jumbo_len,
1057 jumbolen = ntohl(jumbolen);
1058 if (jumbolen <= IPV6_MAXPACKET)
1060 if (sizeof(struct ip6_hdr) + jumbolen !=
1067 ooff += sizeof(opt) + opt.ip6o_len;
1068 } while (ooff < optend);
1071 proto = ext.ip6e_nxt;
1077 } while (!terminal);
1079 /* jumbo payload option must be present, or plen > 0 */
1080 if (ntohs(h->ip6_plen) == 0)
1083 plen = ntohs(h->ip6_plen);
1086 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1089 pf_scrub_ip6(&m, r->min_ttl);
1094 /* Jumbo payload packets cannot be fragmented. */
1095 plen = ntohs(h->ip6_plen);
1096 if (plen == 0 || jumbolen)
1098 if (sizeof(struct ip6_hdr) + plen > m->m_pkthdr.len)
1101 if (!pf_pull_hdr(m, off, &frag, sizeof(frag), NULL, NULL, AF_INET6))
1104 /* Offset now points to data portion. */
1105 off += sizeof(frag);
1107 /* Returns PF_DROP or *m0 is NULL or completely reassembled mbuf. */
1108 if (pf_reassemble6(m0, h, &frag, off, extoff, reason) != PF_PASS)
1114 pd->flags |= PFDESC_IP_REAS;
1118 REASON_SET(reason, PFRES_SHORT);
1119 if (r != NULL && r->log)
1120 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1125 REASON_SET(reason, PFRES_NORM);
1126 if (r != NULL && r->log)
1127 PFLOG_PACKET(kif, m, AF_INET6, dir, *reason, r, NULL, NULL, pd,
1134 pf_normalize_tcp(int dir, struct pfi_kif *kif, struct mbuf *m, int ipoff,
1135 int off, void *h, struct pf_pdesc *pd)
1137 struct pf_rule *r, *rm = NULL;
1138 struct tcphdr *th = pd->hdr.tcp;
1142 sa_family_t af = pd->af;
1146 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_SCRUB].active.ptr);
1149 if (pfi_kif_match(r->kif, kif) == r->ifnot)
1150 r = r->skip[PF_SKIP_IFP].ptr;
1151 else if (r->direction && r->direction != dir)
1152 r = r->skip[PF_SKIP_DIR].ptr;
1153 else if (r->af && r->af != af)
1154 r = r->skip[PF_SKIP_AF].ptr;
1155 else if (r->proto && r->proto != pd->proto)
1156 r = r->skip[PF_SKIP_PROTO].ptr;
1157 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
1158 r->src.neg, kif, M_GETFIB(m)))
1159 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
1160 else if (r->src.port_op && !pf_match_port(r->src.port_op,
1161 r->src.port[0], r->src.port[1], th->th_sport))
1162 r = r->skip[PF_SKIP_SRC_PORT].ptr;
1163 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
1164 r->dst.neg, NULL, M_GETFIB(m)))
1165 r = r->skip[PF_SKIP_DST_ADDR].ptr;
1166 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
1167 r->dst.port[0], r->dst.port[1], th->th_dport))
1168 r = r->skip[PF_SKIP_DST_PORT].ptr;
1169 else if (r->os_fingerprint != PF_OSFP_ANY && !pf_osfp_match(
1170 pf_osfp_fingerprint(pd, m, off, th),
1172 r = TAILQ_NEXT(r, entries);
1179 if (rm == NULL || rm->action == PF_NOSCRUB)
1182 r->packets[dir == PF_OUT]++;
1183 r->bytes[dir == PF_OUT] += pd->tot_len;
1186 if (rm->rule_flag & PFRULE_REASSEMBLE_TCP)
1187 pd->flags |= PFDESC_TCP_NORM;
1189 flags = th->th_flags;
1190 if (flags & TH_SYN) {
1191 /* Illegal packet */
1198 /* Illegal packet */
1199 if (!(flags & (TH_ACK|TH_RST)))
1203 if (!(flags & TH_ACK)) {
1204 /* These flags are only valid if ACK is set */
1205 if ((flags & TH_FIN) || (flags & TH_PUSH) || (flags & TH_URG))
1209 /* Check for illegal header length */
1210 if (th->th_off < (sizeof(struct tcphdr) >> 2))
1213 /* If flags changed, or reserved data set, then adjust */
1214 if (flags != th->th_flags || th->th_x2 != 0) {
1217 ov = *(u_int16_t *)(&th->th_ack + 1);
1218 th->th_flags = flags;
1220 nv = *(u_int16_t *)(&th->th_ack + 1);
1222 th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, ov, nv, 0);
1226 /* Remove urgent pointer, if TH_URG is not set */
1227 if (!(flags & TH_URG) && th->th_urp) {
1228 th->th_sum = pf_proto_cksum_fixup(m, th->th_sum, th->th_urp,
1234 /* Process options */
1235 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1238 /* copy back packet headers if we sanitized */
1240 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1245 REASON_SET(&reason, PFRES_NORM);
1246 if (rm != NULL && r->log)
1247 PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1253 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1254 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1256 u_int32_t tsval, tsecr;
1260 KASSERT((src->scrub == NULL),
1261 ("pf_normalize_tcp_init: src->scrub != NULL"));
1263 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1264 if (src->scrub == NULL)
1270 struct ip *h = mtod(m, struct ip *);
1271 src->scrub->pfss_ttl = h->ip_ttl;
1277 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1278 src->scrub->pfss_ttl = h->ip6_hlim;
1286 * All normalizations below are only begun if we see the start of
1287 * the connections. They must all set an enabled bit in pfss_flags
1289 if ((th->th_flags & TH_SYN) == 0)
1293 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1294 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1295 /* Diddle with TCP options */
1297 opt = hdr + sizeof(struct tcphdr);
1298 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1299 while (hlen >= TCPOLEN_TIMESTAMP) {
1301 case TCPOPT_EOL: /* FALLTHROUGH */
1306 case TCPOPT_TIMESTAMP:
1307 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1308 src->scrub->pfss_flags |=
1310 src->scrub->pfss_ts_mod =
1311 htonl(arc4random());
1313 /* note PFSS_PAWS not set yet */
1314 memcpy(&tsval, &opt[2],
1316 memcpy(&tsecr, &opt[6],
1318 src->scrub->pfss_tsval0 = ntohl(tsval);
1319 src->scrub->pfss_tsval = ntohl(tsval);
1320 src->scrub->pfss_tsecr = ntohl(tsecr);
1321 getmicrouptime(&src->scrub->pfss_last);
1325 hlen -= MAX(opt[1], 2);
1326 opt += MAX(opt[1], 2);
1336 pf_normalize_tcp_cleanup(struct pf_state *state)
1338 if (state->src.scrub)
1339 uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1340 if (state->dst.scrub)
1341 uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1343 /* Someday... flush the TCP segment reassembly descriptors. */
1347 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1348 u_short *reason, struct tcphdr *th, struct pf_state *state,
1349 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1351 struct timeval uptime;
1352 u_int32_t tsval, tsecr;
1353 u_int tsval_from_last;
1359 KASSERT((src->scrub || dst->scrub),
1360 ("%s: src->scrub && dst->scrub!", __func__));
1363 * Enforce the minimum TTL seen for this connection. Negate a common
1364 * technique to evade an intrusion detection system and confuse
1365 * firewall state code.
1371 struct ip *h = mtod(m, struct ip *);
1372 if (h->ip_ttl > src->scrub->pfss_ttl)
1373 src->scrub->pfss_ttl = h->ip_ttl;
1374 h->ip_ttl = src->scrub->pfss_ttl;
1382 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1383 if (h->ip6_hlim > src->scrub->pfss_ttl)
1384 src->scrub->pfss_ttl = h->ip6_hlim;
1385 h->ip6_hlim = src->scrub->pfss_ttl;
1392 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1393 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1394 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1395 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1396 /* Diddle with TCP options */
1398 opt = hdr + sizeof(struct tcphdr);
1399 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1400 while (hlen >= TCPOLEN_TIMESTAMP) {
1402 case TCPOPT_EOL: /* FALLTHROUGH */
1407 case TCPOPT_TIMESTAMP:
1408 /* Modulate the timestamps. Can be used for
1409 * NAT detection, OS uptime determination or
1414 /* Huh? Multiple timestamps!? */
1415 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1416 DPFPRINTF(("multiple TS??"));
1417 pf_print_state(state);
1420 REASON_SET(reason, PFRES_TS);
1423 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1424 memcpy(&tsval, &opt[2],
1426 if (tsval && src->scrub &&
1427 (src->scrub->pfss_flags &
1429 tsval = ntohl(tsval);
1430 pf_change_proto_a(m, &opt[2],
1433 src->scrub->pfss_ts_mod),
1438 /* Modulate TS reply iff valid (!0) */
1439 memcpy(&tsecr, &opt[6],
1441 if (tsecr && dst->scrub &&
1442 (dst->scrub->pfss_flags &
1444 tsecr = ntohl(tsecr)
1445 - dst->scrub->pfss_ts_mod;
1446 pf_change_proto_a(m, &opt[6],
1447 &th->th_sum, htonl(tsecr),
1455 hlen -= MAX(opt[1], 2);
1456 opt += MAX(opt[1], 2);
1461 /* Copyback the options, caller copys back header */
1463 m_copyback(m, off + sizeof(struct tcphdr),
1464 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1465 sizeof(struct tcphdr));
1471 * Must invalidate PAWS checks on connections idle for too long.
1472 * The fastest allowed timestamp clock is 1ms. That turns out to
1473 * be about 24 days before it wraps. XXX Right now our lowerbound
1474 * TS echo check only works for the first 12 days of a connection
1475 * when the TS has exhausted half its 32bit space
1477 #define TS_MAX_IDLE (24*24*60*60)
1478 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1480 getmicrouptime(&uptime);
1481 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1482 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1483 time_uptime - state->creation > TS_MAX_CONN)) {
1484 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1485 DPFPRINTF(("src idled out of PAWS\n"));
1486 pf_print_state(state);
1489 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1492 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1493 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1494 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1495 DPFPRINTF(("dst idled out of PAWS\n"));
1496 pf_print_state(state);
1499 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1503 if (got_ts && src->scrub && dst->scrub &&
1504 (src->scrub->pfss_flags & PFSS_PAWS) &&
1505 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1506 /* Validate that the timestamps are "in-window".
1507 * RFC1323 describes TCP Timestamp options that allow
1508 * measurement of RTT (round trip time) and PAWS
1509 * (protection against wrapped sequence numbers). PAWS
1510 * gives us a set of rules for rejecting packets on
1511 * long fat pipes (packets that were somehow delayed
1512 * in transit longer than the time it took to send the
1513 * full TCP sequence space of 4Gb). We can use these
1514 * rules and infer a few others that will let us treat
1515 * the 32bit timestamp and the 32bit echoed timestamp
1516 * as sequence numbers to prevent a blind attacker from
1517 * inserting packets into a connection.
1520 * - The timestamp on this packet must be greater than
1521 * or equal to the last value echoed by the other
1522 * endpoint. The RFC says those will be discarded
1523 * since it is a dup that has already been acked.
1524 * This gives us a lowerbound on the timestamp.
1525 * timestamp >= other last echoed timestamp
1526 * - The timestamp will be less than or equal to
1527 * the last timestamp plus the time between the
1528 * last packet and now. The RFC defines the max
1529 * clock rate as 1ms. We will allow clocks to be
1530 * up to 10% fast and will allow a total difference
1531 * or 30 seconds due to a route change. And this
1532 * gives us an upperbound on the timestamp.
1533 * timestamp <= last timestamp + max ticks
1534 * We have to be careful here. Windows will send an
1535 * initial timestamp of zero and then initialize it
1536 * to a random value after the 3whs; presumably to
1537 * avoid a DoS by having to call an expensive RNG
1538 * during a SYN flood. Proof MS has at least one
1539 * good security geek.
1541 * - The TCP timestamp option must also echo the other
1542 * endpoints timestamp. The timestamp echoed is the
1543 * one carried on the earliest unacknowledged segment
1544 * on the left edge of the sequence window. The RFC
1545 * states that the host will reject any echoed
1546 * timestamps that were larger than any ever sent.
1547 * This gives us an upperbound on the TS echo.
1548 * tescr <= largest_tsval
1549 * - The lowerbound on the TS echo is a little more
1550 * tricky to determine. The other endpoint's echoed
1551 * values will not decrease. But there may be
1552 * network conditions that re-order packets and
1553 * cause our view of them to decrease. For now the
1554 * only lowerbound we can safely determine is that
1555 * the TS echo will never be less than the original
1556 * TS. XXX There is probably a better lowerbound.
1557 * Remove TS_MAX_CONN with better lowerbound check.
1558 * tescr >= other original TS
1560 * It is also important to note that the fastest
1561 * timestamp clock of 1ms will wrap its 32bit space in
1562 * 24 days. So we just disable TS checking after 24
1563 * days of idle time. We actually must use a 12d
1564 * connection limit until we can come up with a better
1565 * lowerbound to the TS echo check.
1567 struct timeval delta_ts;
1572 * PFTM_TS_DIFF is how many seconds of leeway to allow
1573 * a host's timestamp. This can happen if the previous
1574 * packet got delayed in transit for much longer than
1577 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1578 ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1580 /* Calculate max ticks since the last timestamp */
1581 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1582 #define TS_MICROSECS 1000000 /* microseconds per second */
1584 timevalsub(&delta_ts, &src->scrub->pfss_last);
1585 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1586 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1588 if ((src->state >= TCPS_ESTABLISHED &&
1589 dst->state >= TCPS_ESTABLISHED) &&
1590 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1591 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1592 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1593 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1594 /* Bad RFC1323 implementation or an insertion attack.
1596 * - Solaris 2.6 and 2.7 are known to send another ACK
1597 * after the FIN,FIN|ACK,ACK closing that carries
1601 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1602 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1603 SEQ_GT(tsval, src->scrub->pfss_tsval +
1604 tsval_from_last) ? '1' : ' ',
1605 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1606 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1607 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1608 "idle: %jus %lums\n",
1609 tsval, tsecr, tsval_from_last,
1610 (uintmax_t)delta_ts.tv_sec,
1611 delta_ts.tv_usec / 1000));
1612 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1613 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1614 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1615 "\n", dst->scrub->pfss_tsval,
1616 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1617 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1618 pf_print_state(state);
1619 pf_print_flags(th->th_flags);
1622 REASON_SET(reason, PFRES_TS);
1626 /* XXX I'd really like to require tsecr but it's optional */
1628 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1629 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1630 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1631 src->scrub && dst->scrub &&
1632 (src->scrub->pfss_flags & PFSS_PAWS) &&
1633 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1634 /* Didn't send a timestamp. Timestamps aren't really useful
1636 * - connection opening or closing (often not even sent).
1637 * but we must not let an attacker to put a FIN on a
1638 * data packet to sneak it through our ESTABLISHED check.
1639 * - on a TCP reset. RFC suggests not even looking at TS.
1640 * - on an empty ACK. The TS will not be echoed so it will
1641 * probably not help keep the RTT calculation in sync and
1642 * there isn't as much danger when the sequence numbers
1643 * got wrapped. So some stacks don't include TS on empty
1646 * To minimize the disruption to mostly RFC1323 conformant
1647 * stacks, we will only require timestamps on data packets.
1649 * And what do ya know, we cannot require timestamps on data
1650 * packets. There appear to be devices that do legitimate
1651 * TCP connection hijacking. There are HTTP devices that allow
1652 * a 3whs (with timestamps) and then buffer the HTTP request.
1653 * If the intermediate device has the HTTP response cache, it
1654 * will spoof the response but not bother timestamping its
1655 * packets. So we can look for the presence of a timestamp in
1656 * the first data packet and if there, require it in all future
1660 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1662 * Hey! Someone tried to sneak a packet in. Or the
1663 * stack changed its RFC1323 behavior?!?!
1665 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1666 DPFPRINTF(("Did not receive expected RFC1323 "
1668 pf_print_state(state);
1669 pf_print_flags(th->th_flags);
1672 REASON_SET(reason, PFRES_TS);
1679 * We will note if a host sends his data packets with or without
1680 * timestamps. And require all data packets to contain a timestamp
1681 * if the first does. PAWS implicitly requires that all data packets be
1682 * timestamped. But I think there are middle-man devices that hijack
1683 * TCP streams immediately after the 3whs and don't timestamp their
1684 * packets (seen in a WWW accelerator or cache).
1686 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1687 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1689 src->scrub->pfss_flags |= PFSS_DATA_TS;
1691 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1692 if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1693 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1694 /* Don't warn if other host rejected RFC1323 */
1695 DPFPRINTF(("Broken RFC1323 stack did not "
1696 "timestamp data packet. Disabled PAWS "
1698 pf_print_state(state);
1699 pf_print_flags(th->th_flags);
1707 * Update PAWS values
1709 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1710 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1711 getmicrouptime(&src->scrub->pfss_last);
1712 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1713 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1714 src->scrub->pfss_tsval = tsval;
1717 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1718 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1719 src->scrub->pfss_tsecr = tsecr;
1721 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1722 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1723 src->scrub->pfss_tsval0 == 0)) {
1724 /* tsval0 MUST be the lowest timestamp */
1725 src->scrub->pfss_tsval0 = tsval;
1728 /* Only fully initialized after a TS gets echoed */
1729 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1730 src->scrub->pfss_flags |= PFSS_PAWS;
1734 /* I have a dream.... TCP segment reassembly.... */
1739 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1740 int off, sa_family_t af)
1744 int opt, cnt, optlen = 0;
1746 u_char opts[TCP_MAXOLEN];
1747 u_char *optp = opts;
1749 thoff = th->th_off << 2;
1750 cnt = thoff - sizeof(struct tcphdr);
1752 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1756 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1758 if (opt == TCPOPT_EOL)
1760 if (opt == TCPOPT_NOP)
1766 if (optlen < 2 || optlen > cnt)
1771 mss = (u_int16_t *)(optp + 2);
1772 if ((ntohs(*mss)) > r->max_mss) {
1773 th->th_sum = pf_proto_cksum_fixup(m,
1774 th->th_sum, *mss, htons(r->max_mss), 0);
1775 *mss = htons(r->max_mss);
1785 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1792 pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
1794 struct mbuf *m = *m0;
1795 struct ip *h = mtod(m, struct ip *);
1797 /* Clear IP_DF if no-df was requested */
1798 if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1799 u_int16_t ip_off = h->ip_off;
1801 h->ip_off &= htons(~IP_DF);
1802 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1805 /* Enforce a minimum ttl, may cause endless packet loops */
1806 if (min_ttl && h->ip_ttl < min_ttl) {
1807 u_int16_t ip_ttl = h->ip_ttl;
1809 h->ip_ttl = min_ttl;
1810 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1814 if (flags & PFRULE_SET_TOS) {
1817 ov = *(u_int16_t *)h;
1818 h->ip_tos = tos | (h->ip_tos & IPTOS_ECN_MASK);
1819 nv = *(u_int16_t *)h;
1821 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1824 /* random-id, but not for fragments */
1825 if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
1826 uint16_t ip_id = h->ip_id;
1829 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1836 pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
1838 struct mbuf *m = *m0;
1839 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1841 /* Enforce a minimum ttl, may cause endless packet loops */
1842 if (min_ttl && h->ip6_hlim < min_ttl)
1843 h->ip6_hlim = min_ttl;