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_proto_cksum_fixup(m, 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_proto_cksum_fixup(m, th->th_sum, th->th_urp,
1230 /* Process options */
1231 if (r->max_mss && pf_normalize_tcpopt(r, m, th, off, pd->af))
1234 /* copy back packet headers if we sanitized */
1236 m_copyback(m, off, sizeof(*th), (caddr_t)th);
1241 REASON_SET(&reason, PFRES_NORM);
1242 if (rm != NULL && r->log)
1243 PFLOG_PACKET(kif, m, AF_INET, dir, reason, r, NULL, NULL, pd,
1249 pf_normalize_tcp_init(struct mbuf *m, int off, struct pf_pdesc *pd,
1250 struct tcphdr *th, struct pf_state_peer *src, struct pf_state_peer *dst)
1252 u_int32_t tsval, tsecr;
1256 KASSERT((src->scrub == NULL),
1257 ("pf_normalize_tcp_init: src->scrub != NULL"));
1259 src->scrub = uma_zalloc(V_pf_state_scrub_z, M_ZERO | M_NOWAIT);
1260 if (src->scrub == NULL)
1266 struct ip *h = mtod(m, struct ip *);
1267 src->scrub->pfss_ttl = h->ip_ttl;
1273 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1274 src->scrub->pfss_ttl = h->ip6_hlim;
1282 * All normalizations below are only begun if we see the start of
1283 * the connections. They must all set an enabled bit in pfss_flags
1285 if ((th->th_flags & TH_SYN) == 0)
1289 if (th->th_off > (sizeof(struct tcphdr) >> 2) && src->scrub &&
1290 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1291 /* Diddle with TCP options */
1293 opt = hdr + sizeof(struct tcphdr);
1294 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1295 while (hlen >= TCPOLEN_TIMESTAMP) {
1297 case TCPOPT_EOL: /* FALLTHROUGH */
1302 case TCPOPT_TIMESTAMP:
1303 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1304 src->scrub->pfss_flags |=
1306 src->scrub->pfss_ts_mod =
1307 htonl(arc4random());
1309 /* note PFSS_PAWS not set yet */
1310 memcpy(&tsval, &opt[2],
1312 memcpy(&tsecr, &opt[6],
1314 src->scrub->pfss_tsval0 = ntohl(tsval);
1315 src->scrub->pfss_tsval = ntohl(tsval);
1316 src->scrub->pfss_tsecr = ntohl(tsecr);
1317 getmicrouptime(&src->scrub->pfss_last);
1321 hlen -= MAX(opt[1], 2);
1322 opt += MAX(opt[1], 2);
1332 pf_normalize_tcp_cleanup(struct pf_state *state)
1334 if (state->src.scrub)
1335 uma_zfree(V_pf_state_scrub_z, state->src.scrub);
1336 if (state->dst.scrub)
1337 uma_zfree(V_pf_state_scrub_z, state->dst.scrub);
1339 /* Someday... flush the TCP segment reassembly descriptors. */
1343 pf_normalize_tcp_stateful(struct mbuf *m, int off, struct pf_pdesc *pd,
1344 u_short *reason, struct tcphdr *th, struct pf_state *state,
1345 struct pf_state_peer *src, struct pf_state_peer *dst, int *writeback)
1347 struct timeval uptime;
1348 u_int32_t tsval, tsecr;
1349 u_int tsval_from_last;
1355 KASSERT((src->scrub || dst->scrub),
1356 ("%s: src->scrub && dst->scrub!", __func__));
1359 * Enforce the minimum TTL seen for this connection. Negate a common
1360 * technique to evade an intrusion detection system and confuse
1361 * firewall state code.
1367 struct ip *h = mtod(m, struct ip *);
1368 if (h->ip_ttl > src->scrub->pfss_ttl)
1369 src->scrub->pfss_ttl = h->ip_ttl;
1370 h->ip_ttl = src->scrub->pfss_ttl;
1378 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1379 if (h->ip6_hlim > src->scrub->pfss_ttl)
1380 src->scrub->pfss_ttl = h->ip6_hlim;
1381 h->ip6_hlim = src->scrub->pfss_ttl;
1388 if (th->th_off > (sizeof(struct tcphdr) >> 2) &&
1389 ((src->scrub && (src->scrub->pfss_flags & PFSS_TIMESTAMP)) ||
1390 (dst->scrub && (dst->scrub->pfss_flags & PFSS_TIMESTAMP))) &&
1391 pf_pull_hdr(m, off, hdr, th->th_off << 2, NULL, NULL, pd->af)) {
1392 /* Diddle with TCP options */
1394 opt = hdr + sizeof(struct tcphdr);
1395 hlen = (th->th_off << 2) - sizeof(struct tcphdr);
1396 while (hlen >= TCPOLEN_TIMESTAMP) {
1398 case TCPOPT_EOL: /* FALLTHROUGH */
1403 case TCPOPT_TIMESTAMP:
1404 /* Modulate the timestamps. Can be used for
1405 * NAT detection, OS uptime determination or
1410 /* Huh? Multiple timestamps!? */
1411 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1412 DPFPRINTF(("multiple TS??"));
1413 pf_print_state(state);
1416 REASON_SET(reason, PFRES_TS);
1419 if (opt[1] >= TCPOLEN_TIMESTAMP) {
1420 memcpy(&tsval, &opt[2],
1422 if (tsval && src->scrub &&
1423 (src->scrub->pfss_flags &
1425 tsval = ntohl(tsval);
1426 pf_change_proto_a(m, &opt[2],
1429 src->scrub->pfss_ts_mod),
1434 /* Modulate TS reply iff valid (!0) */
1435 memcpy(&tsecr, &opt[6],
1437 if (tsecr && dst->scrub &&
1438 (dst->scrub->pfss_flags &
1440 tsecr = ntohl(tsecr)
1441 - dst->scrub->pfss_ts_mod;
1442 pf_change_proto_a(m, &opt[6],
1443 &th->th_sum, htonl(tsecr),
1451 hlen -= MAX(opt[1], 2);
1452 opt += MAX(opt[1], 2);
1457 /* Copyback the options, caller copys back header */
1459 m_copyback(m, off + sizeof(struct tcphdr),
1460 (th->th_off << 2) - sizeof(struct tcphdr), hdr +
1461 sizeof(struct tcphdr));
1467 * Must invalidate PAWS checks on connections idle for too long.
1468 * The fastest allowed timestamp clock is 1ms. That turns out to
1469 * be about 24 days before it wraps. XXX Right now our lowerbound
1470 * TS echo check only works for the first 12 days of a connection
1471 * when the TS has exhausted half its 32bit space
1473 #define TS_MAX_IDLE (24*24*60*60)
1474 #define TS_MAX_CONN (12*24*60*60) /* XXX remove when better tsecr check */
1476 getmicrouptime(&uptime);
1477 if (src->scrub && (src->scrub->pfss_flags & PFSS_PAWS) &&
1478 (uptime.tv_sec - src->scrub->pfss_last.tv_sec > TS_MAX_IDLE ||
1479 time_uptime - state->creation > TS_MAX_CONN)) {
1480 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1481 DPFPRINTF(("src idled out of PAWS\n"));
1482 pf_print_state(state);
1485 src->scrub->pfss_flags = (src->scrub->pfss_flags & ~PFSS_PAWS)
1488 if (dst->scrub && (dst->scrub->pfss_flags & PFSS_PAWS) &&
1489 uptime.tv_sec - dst->scrub->pfss_last.tv_sec > TS_MAX_IDLE) {
1490 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1491 DPFPRINTF(("dst idled out of PAWS\n"));
1492 pf_print_state(state);
1495 dst->scrub->pfss_flags = (dst->scrub->pfss_flags & ~PFSS_PAWS)
1499 if (got_ts && src->scrub && dst->scrub &&
1500 (src->scrub->pfss_flags & PFSS_PAWS) &&
1501 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1502 /* Validate that the timestamps are "in-window".
1503 * RFC1323 describes TCP Timestamp options that allow
1504 * measurement of RTT (round trip time) and PAWS
1505 * (protection against wrapped sequence numbers). PAWS
1506 * gives us a set of rules for rejecting packets on
1507 * long fat pipes (packets that were somehow delayed
1508 * in transit longer than the time it took to send the
1509 * full TCP sequence space of 4Gb). We can use these
1510 * rules and infer a few others that will let us treat
1511 * the 32bit timestamp and the 32bit echoed timestamp
1512 * as sequence numbers to prevent a blind attacker from
1513 * inserting packets into a connection.
1516 * - The timestamp on this packet must be greater than
1517 * or equal to the last value echoed by the other
1518 * endpoint. The RFC says those will be discarded
1519 * since it is a dup that has already been acked.
1520 * This gives us a lowerbound on the timestamp.
1521 * timestamp >= other last echoed timestamp
1522 * - The timestamp will be less than or equal to
1523 * the last timestamp plus the time between the
1524 * last packet and now. The RFC defines the max
1525 * clock rate as 1ms. We will allow clocks to be
1526 * up to 10% fast and will allow a total difference
1527 * or 30 seconds due to a route change. And this
1528 * gives us an upperbound on the timestamp.
1529 * timestamp <= last timestamp + max ticks
1530 * We have to be careful here. Windows will send an
1531 * initial timestamp of zero and then initialize it
1532 * to a random value after the 3whs; presumably to
1533 * avoid a DoS by having to call an expensive RNG
1534 * during a SYN flood. Proof MS has at least one
1535 * good security geek.
1537 * - The TCP timestamp option must also echo the other
1538 * endpoints timestamp. The timestamp echoed is the
1539 * one carried on the earliest unacknowledged segment
1540 * on the left edge of the sequence window. The RFC
1541 * states that the host will reject any echoed
1542 * timestamps that were larger than any ever sent.
1543 * This gives us an upperbound on the TS echo.
1544 * tescr <= largest_tsval
1545 * - The lowerbound on the TS echo is a little more
1546 * tricky to determine. The other endpoint's echoed
1547 * values will not decrease. But there may be
1548 * network conditions that re-order packets and
1549 * cause our view of them to decrease. For now the
1550 * only lowerbound we can safely determine is that
1551 * the TS echo will never be less than the original
1552 * TS. XXX There is probably a better lowerbound.
1553 * Remove TS_MAX_CONN with better lowerbound check.
1554 * tescr >= other original TS
1556 * It is also important to note that the fastest
1557 * timestamp clock of 1ms will wrap its 32bit space in
1558 * 24 days. So we just disable TS checking after 24
1559 * days of idle time. We actually must use a 12d
1560 * connection limit until we can come up with a better
1561 * lowerbound to the TS echo check.
1563 struct timeval delta_ts;
1568 * PFTM_TS_DIFF is how many seconds of leeway to allow
1569 * a host's timestamp. This can happen if the previous
1570 * packet got delayed in transit for much longer than
1573 if ((ts_fudge = state->rule.ptr->timeout[PFTM_TS_DIFF]) == 0)
1574 ts_fudge = V_pf_default_rule.timeout[PFTM_TS_DIFF];
1576 /* Calculate max ticks since the last timestamp */
1577 #define TS_MAXFREQ 1100 /* RFC max TS freq of 1Khz + 10% skew */
1578 #define TS_MICROSECS 1000000 /* microseconds per second */
1580 timevalsub(&delta_ts, &src->scrub->pfss_last);
1581 tsval_from_last = (delta_ts.tv_sec + ts_fudge) * TS_MAXFREQ;
1582 tsval_from_last += delta_ts.tv_usec / (TS_MICROSECS/TS_MAXFREQ);
1584 if ((src->state >= TCPS_ESTABLISHED &&
1585 dst->state >= TCPS_ESTABLISHED) &&
1586 (SEQ_LT(tsval, dst->scrub->pfss_tsecr) ||
1587 SEQ_GT(tsval, src->scrub->pfss_tsval + tsval_from_last) ||
1588 (tsecr && (SEQ_GT(tsecr, dst->scrub->pfss_tsval) ||
1589 SEQ_LT(tsecr, dst->scrub->pfss_tsval0))))) {
1590 /* Bad RFC1323 implementation or an insertion attack.
1592 * - Solaris 2.6 and 2.7 are known to send another ACK
1593 * after the FIN,FIN|ACK,ACK closing that carries
1597 DPFPRINTF(("Timestamp failed %c%c%c%c\n",
1598 SEQ_LT(tsval, dst->scrub->pfss_tsecr) ? '0' : ' ',
1599 SEQ_GT(tsval, src->scrub->pfss_tsval +
1600 tsval_from_last) ? '1' : ' ',
1601 SEQ_GT(tsecr, dst->scrub->pfss_tsval) ? '2' : ' ',
1602 SEQ_LT(tsecr, dst->scrub->pfss_tsval0)? '3' : ' '));
1603 DPFPRINTF((" tsval: %u tsecr: %u +ticks: %u "
1604 "idle: %jus %lums\n",
1605 tsval, tsecr, tsval_from_last,
1606 (uintmax_t)delta_ts.tv_sec,
1607 delta_ts.tv_usec / 1000));
1608 DPFPRINTF((" src->tsval: %u tsecr: %u\n",
1609 src->scrub->pfss_tsval, src->scrub->pfss_tsecr));
1610 DPFPRINTF((" dst->tsval: %u tsecr: %u tsval0: %u"
1611 "\n", dst->scrub->pfss_tsval,
1612 dst->scrub->pfss_tsecr, dst->scrub->pfss_tsval0));
1613 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1614 pf_print_state(state);
1615 pf_print_flags(th->th_flags);
1618 REASON_SET(reason, PFRES_TS);
1622 /* XXX I'd really like to require tsecr but it's optional */
1624 } else if (!got_ts && (th->th_flags & TH_RST) == 0 &&
1625 ((src->state == TCPS_ESTABLISHED && dst->state == TCPS_ESTABLISHED)
1626 || pd->p_len > 0 || (th->th_flags & TH_SYN)) &&
1627 src->scrub && dst->scrub &&
1628 (src->scrub->pfss_flags & PFSS_PAWS) &&
1629 (dst->scrub->pfss_flags & PFSS_PAWS)) {
1630 /* Didn't send a timestamp. Timestamps aren't really useful
1632 * - connection opening or closing (often not even sent).
1633 * but we must not let an attacker to put a FIN on a
1634 * data packet to sneak it through our ESTABLISHED check.
1635 * - on a TCP reset. RFC suggests not even looking at TS.
1636 * - on an empty ACK. The TS will not be echoed so it will
1637 * probably not help keep the RTT calculation in sync and
1638 * there isn't as much danger when the sequence numbers
1639 * got wrapped. So some stacks don't include TS on empty
1642 * To minimize the disruption to mostly RFC1323 conformant
1643 * stacks, we will only require timestamps on data packets.
1645 * And what do ya know, we cannot require timestamps on data
1646 * packets. There appear to be devices that do legitimate
1647 * TCP connection hijacking. There are HTTP devices that allow
1648 * a 3whs (with timestamps) and then buffer the HTTP request.
1649 * If the intermediate device has the HTTP response cache, it
1650 * will spoof the response but not bother timestamping its
1651 * packets. So we can look for the presence of a timestamp in
1652 * the first data packet and if there, require it in all future
1656 if (pd->p_len > 0 && (src->scrub->pfss_flags & PFSS_DATA_TS)) {
1658 * Hey! Someone tried to sneak a packet in. Or the
1659 * stack changed its RFC1323 behavior?!?!
1661 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1662 DPFPRINTF(("Did not receive expected RFC1323 "
1664 pf_print_state(state);
1665 pf_print_flags(th->th_flags);
1668 REASON_SET(reason, PFRES_TS);
1675 * We will note if a host sends his data packets with or without
1676 * timestamps. And require all data packets to contain a timestamp
1677 * if the first does. PAWS implicitly requires that all data packets be
1678 * timestamped. But I think there are middle-man devices that hijack
1679 * TCP streams immediately after the 3whs and don't timestamp their
1680 * packets (seen in a WWW accelerator or cache).
1682 if (pd->p_len > 0 && src->scrub && (src->scrub->pfss_flags &
1683 (PFSS_TIMESTAMP|PFSS_DATA_TS|PFSS_DATA_NOTS)) == PFSS_TIMESTAMP) {
1685 src->scrub->pfss_flags |= PFSS_DATA_TS;
1687 src->scrub->pfss_flags |= PFSS_DATA_NOTS;
1688 if (V_pf_status.debug >= PF_DEBUG_MISC && dst->scrub &&
1689 (dst->scrub->pfss_flags & PFSS_TIMESTAMP)) {
1690 /* Don't warn if other host rejected RFC1323 */
1691 DPFPRINTF(("Broken RFC1323 stack did not "
1692 "timestamp data packet. Disabled PAWS "
1694 pf_print_state(state);
1695 pf_print_flags(th->th_flags);
1703 * Update PAWS values
1705 if (got_ts && src->scrub && PFSS_TIMESTAMP == (src->scrub->pfss_flags &
1706 (PFSS_PAWS_IDLED|PFSS_TIMESTAMP))) {
1707 getmicrouptime(&src->scrub->pfss_last);
1708 if (SEQ_GEQ(tsval, src->scrub->pfss_tsval) ||
1709 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1710 src->scrub->pfss_tsval = tsval;
1713 if (SEQ_GEQ(tsecr, src->scrub->pfss_tsecr) ||
1714 (src->scrub->pfss_flags & PFSS_PAWS) == 0)
1715 src->scrub->pfss_tsecr = tsecr;
1717 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0 &&
1718 (SEQ_LT(tsval, src->scrub->pfss_tsval0) ||
1719 src->scrub->pfss_tsval0 == 0)) {
1720 /* tsval0 MUST be the lowest timestamp */
1721 src->scrub->pfss_tsval0 = tsval;
1724 /* Only fully initialized after a TS gets echoed */
1725 if ((src->scrub->pfss_flags & PFSS_PAWS) == 0)
1726 src->scrub->pfss_flags |= PFSS_PAWS;
1730 /* I have a dream.... TCP segment reassembly.... */
1735 pf_normalize_tcpopt(struct pf_rule *r, struct mbuf *m, struct tcphdr *th,
1736 int off, sa_family_t af)
1740 int opt, cnt, optlen = 0;
1742 u_char opts[TCP_MAXOLEN];
1743 u_char *optp = opts;
1745 thoff = th->th_off << 2;
1746 cnt = thoff - sizeof(struct tcphdr);
1748 if (cnt > 0 && !pf_pull_hdr(m, off + sizeof(*th), opts, cnt,
1752 for (; cnt > 0; cnt -= optlen, optp += optlen) {
1754 if (opt == TCPOPT_EOL)
1756 if (opt == TCPOPT_NOP)
1762 if (optlen < 2 || optlen > cnt)
1767 mss = (u_int16_t *)(optp + 2);
1768 if ((ntohs(*mss)) > r->max_mss) {
1769 th->th_sum = pf_proto_cksum_fixup(m,
1770 th->th_sum, *mss, htons(r->max_mss), 0);
1771 *mss = htons(r->max_mss);
1781 m_copyback(m, off + sizeof(*th), thoff - sizeof(*th), opts);
1788 pf_scrub_ip(struct mbuf **m0, u_int32_t flags, u_int8_t min_ttl, u_int8_t tos)
1790 struct mbuf *m = *m0;
1791 struct ip *h = mtod(m, struct ip *);
1793 /* Clear IP_DF if no-df was requested */
1794 if (flags & PFRULE_NODF && h->ip_off & htons(IP_DF)) {
1795 u_int16_t ip_off = h->ip_off;
1797 h->ip_off &= htons(~IP_DF);
1798 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_off, h->ip_off, 0);
1801 /* Enforce a minimum ttl, may cause endless packet loops */
1802 if (min_ttl && h->ip_ttl < min_ttl) {
1803 u_int16_t ip_ttl = h->ip_ttl;
1805 h->ip_ttl = min_ttl;
1806 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_ttl, h->ip_ttl, 0);
1810 if (flags & PFRULE_SET_TOS) {
1813 ov = *(u_int16_t *)h;
1815 nv = *(u_int16_t *)h;
1817 h->ip_sum = pf_cksum_fixup(h->ip_sum, ov, nv, 0);
1820 /* random-id, but not for fragments */
1821 if (flags & PFRULE_RANDOMID && !(h->ip_off & ~htons(IP_DF))) {
1822 uint16_t ip_id = h->ip_id;
1825 h->ip_sum = pf_cksum_fixup(h->ip_sum, ip_id, h->ip_id, 0);
1832 pf_scrub_ip6(struct mbuf **m0, u_int8_t min_ttl)
1834 struct mbuf *m = *m0;
1835 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
1837 /* Enforce a minimum ttl, may cause endless packet loops */
1838 if (min_ttl && h->ip6_hlim < min_ttl)
1839 h->ip6_hlim = min_ttl;