2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
35 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 #include "opt_inet6.h"
46 #include <sys/param.h>
48 #include <sys/endian.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/limits.h>
56 #include <sys/random.h>
57 #include <sys/refcount.h>
58 #include <sys/socket.h>
59 #include <sys/sysctl.h>
60 #include <sys/taskqueue.h>
61 #include <sys/ucred.h>
64 #include <net/if_types.h>
65 #include <net/route.h>
66 #include <net/radix_mpath.h>
69 #include <net/pfvar.h>
70 #include <net/if_pflog.h>
71 #include <net/if_pfsync.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/in_var.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/icmp_var.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/tcp.h>
81 #include <netinet/tcp_fsm.h>
82 #include <netinet/tcp_seq.h>
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #include <netinet/udp.h>
86 #include <netinet/udp_var.h>
88 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
91 #include <netinet/ip6.h>
92 #include <netinet/icmp6.h>
93 #include <netinet6/nd6.h>
94 #include <netinet6/ip6_var.h>
95 #include <netinet6/in6_pcb.h>
98 #include <machine/in_cksum.h>
99 #include <security/mac/mac_framework.h>
101 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
108 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
109 VNET_DEFINE(struct pf_palist, pf_pabuf);
110 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
111 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
112 VNET_DEFINE(struct pf_kstatus, pf_status);
114 VNET_DEFINE(u_int32_t, ticket_altqs_active);
115 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
116 VNET_DEFINE(int, altqs_inactive_open);
117 VNET_DEFINE(u_int32_t, ticket_pabuf);
119 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
120 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
121 VNET_DEFINE(u_char, pf_tcp_secret[16]);
122 #define V_pf_tcp_secret VNET(pf_tcp_secret)
123 VNET_DEFINE(int, pf_tcp_secret_init);
124 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
125 VNET_DEFINE(int, pf_tcp_iss_off);
126 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
129 * Queue for pf_intr() sends.
131 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
132 struct pf_send_entry {
133 STAILQ_ENTRY(pf_send_entry) pfse_next;
150 #define pfse_icmp_type u.icmpopts.type
151 #define pfse_icmp_code u.icmpopts.code
152 #define pfse_icmp_mtu u.icmpopts.mtu
155 STAILQ_HEAD(pf_send_head, pf_send_entry);
156 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157 #define V_pf_sendqueue VNET(pf_sendqueue)
159 static struct mtx pf_sendqueue_mtx;
160 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
161 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
164 * Queue for pf_overload_task() tasks.
166 struct pf_overload_entry {
167 SLIST_ENTRY(pf_overload_entry) next;
171 struct pf_rule *rule;
174 SLIST_HEAD(pf_overload_head, pf_overload_entry);
175 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
176 #define V_pf_overloadqueue VNET(pf_overloadqueue)
177 static VNET_DEFINE(struct task, pf_overloadtask);
178 #define V_pf_overloadtask VNET(pf_overloadtask)
180 static struct mtx pf_overloadqueue_mtx;
181 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
182 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
184 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
185 struct mtx pf_unlnkdrules_mtx;
187 static VNET_DEFINE(uma_zone_t, pf_sources_z);
188 #define V_pf_sources_z VNET(pf_sources_z)
189 uma_zone_t pf_mtag_z;
190 VNET_DEFINE(uma_zone_t, pf_state_z);
191 VNET_DEFINE(uma_zone_t, pf_state_key_z);
193 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
194 #define PFID_CPUBITS 8
195 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
196 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
197 #define PFID_MAXID (~PFID_CPUMASK)
198 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
200 static void pf_src_tree_remove_state(struct pf_state *);
201 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
203 static void pf_add_threshold(struct pf_threshold *);
204 static int pf_check_threshold(struct pf_threshold *);
206 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
207 u_int16_t *, u_int16_t *, struct pf_addr *,
208 u_int16_t, u_int8_t, sa_family_t);
209 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
210 struct tcphdr *, struct pf_state_peer *);
211 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
212 struct pf_addr *, struct pf_addr *, u_int16_t,
213 u_int16_t *, u_int16_t *, u_int16_t *,
214 u_int16_t *, u_int8_t, sa_family_t);
215 static void pf_send_tcp(struct mbuf *,
216 const struct pf_rule *, sa_family_t,
217 const struct pf_addr *, const struct pf_addr *,
218 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
219 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
220 u_int16_t, struct ifnet *);
221 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
222 sa_family_t, struct pf_rule *);
223 static void pf_detach_state(struct pf_state *);
224 static int pf_state_key_attach(struct pf_state_key *,
225 struct pf_state_key *, struct pf_state *);
226 static void pf_state_key_detach(struct pf_state *, int);
227 static int pf_state_key_ctor(void *, int, void *, int);
228 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
229 static int pf_test_rule(struct pf_rule **, struct pf_state **,
230 int, struct pfi_kif *, struct mbuf *, int,
231 struct pf_pdesc *, struct pf_rule **,
232 struct pf_ruleset **, struct inpcb *);
233 static int pf_create_state(struct pf_rule *, struct pf_rule *,
234 struct pf_rule *, struct pf_pdesc *,
235 struct pf_src_node *, struct pf_state_key *,
236 struct pf_state_key *, struct mbuf *, int,
237 u_int16_t, u_int16_t, int *, struct pfi_kif *,
238 struct pf_state **, int, u_int16_t, u_int16_t,
240 static int pf_test_fragment(struct pf_rule **, int,
241 struct pfi_kif *, struct mbuf *, void *,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **);
244 static int pf_tcp_track_full(struct pf_state_peer *,
245 struct pf_state_peer *, struct pf_state **,
246 struct pfi_kif *, struct mbuf *, int,
247 struct pf_pdesc *, u_short *, int *);
248 static int pf_tcp_track_sloppy(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pf_pdesc *, u_short *);
251 static int pf_test_state_tcp(struct pf_state **, int,
252 struct pfi_kif *, struct mbuf *, int,
253 void *, struct pf_pdesc *, u_short *);
254 static int pf_test_state_udp(struct pf_state **, int,
255 struct pfi_kif *, struct mbuf *, int,
256 void *, struct pf_pdesc *);
257 static int pf_test_state_icmp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260 static int pf_test_state_other(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
262 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
264 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
266 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
268 static int pf_check_proto_cksum(struct mbuf *, int, int,
269 u_int8_t, sa_family_t);
270 static void pf_print_state_parts(struct pf_state *,
271 struct pf_state_key *, struct pf_state_key *);
272 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
273 struct pf_addr_wrap *);
274 static struct pf_state *pf_find_state(struct pfi_kif *,
275 struct pf_state_key_cmp *, u_int);
276 static int pf_src_connlimit(struct pf_state **);
277 static void pf_overload_task(void *v, int pending);
278 static int pf_insert_src_node(struct pf_src_node **,
279 struct pf_rule *, struct pf_addr *, sa_family_t);
280 static u_int pf_purge_expired_states(u_int, int);
281 static void pf_purge_unlinked_rules(void);
282 static int pf_mtag_uminit(void *, int, int);
283 static void pf_mtag_free(struct m_tag *);
285 static void pf_route(struct mbuf **, struct pf_rule *, int,
286 struct ifnet *, struct pf_state *,
290 static void pf_change_a6(struct pf_addr *, u_int16_t *,
291 struct pf_addr *, u_int8_t);
292 static void pf_route6(struct mbuf **, struct pf_rule *, int,
293 struct ifnet *, struct pf_state *,
297 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
299 VNET_DECLARE(int, pf_end_threads);
301 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
303 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
304 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
306 #define STATE_LOOKUP(i, k, d, s, pd) \
308 (s) = pf_find_state((i), (k), (d)); \
311 if (PACKET_LOOPED(pd)) \
313 if ((d) == PF_OUT && \
314 (((s)->rule.ptr->rt == PF_ROUTETO && \
315 (s)->rule.ptr->direction == PF_OUT) || \
316 ((s)->rule.ptr->rt == PF_REPLYTO && \
317 (s)->rule.ptr->direction == PF_IN)) && \
318 (s)->rt_kif != NULL && \
319 (s)->rt_kif != (i)) \
323 #define BOUND_IFACE(r, k) \
324 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
326 #define STATE_INC_COUNTERS(s) \
328 counter_u64_add(s->rule.ptr->states_cur, 1); \
329 counter_u64_add(s->rule.ptr->states_tot, 1); \
330 if (s->anchor.ptr != NULL) { \
331 counter_u64_add(s->anchor.ptr->states_cur, 1); \
332 counter_u64_add(s->anchor.ptr->states_tot, 1); \
334 if (s->nat_rule.ptr != NULL) { \
335 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
336 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
340 #define STATE_DEC_COUNTERS(s) \
342 if (s->nat_rule.ptr != NULL) \
343 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
344 if (s->anchor.ptr != NULL) \
345 counter_u64_add(s->anchor.ptr->states_cur, -1); \
346 counter_u64_add(s->rule.ptr->states_cur, -1); \
349 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
350 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
351 VNET_DEFINE(struct pf_idhash *, pf_idhash);
352 VNET_DEFINE(struct pf_srchash *, pf_srchash);
354 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
357 u_long pf_srchashmask;
358 static u_long pf_hashsize;
359 static u_long pf_srchashsize;
361 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
362 &pf_hashsize, 0, "Size of pf(4) states hashtable");
363 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
364 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
366 VNET_DEFINE(void *, pf_swi_cookie);
368 VNET_DEFINE(uint32_t, pf_hashseed);
369 #define V_pf_hashseed VNET(pf_hashseed)
372 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
378 if (a->addr32[0] > b->addr32[0])
380 if (a->addr32[0] < b->addr32[0])
386 if (a->addr32[3] > b->addr32[3])
388 if (a->addr32[3] < b->addr32[3])
390 if (a->addr32[2] > b->addr32[2])
392 if (a->addr32[2] < b->addr32[2])
394 if (a->addr32[1] > b->addr32[1])
396 if (a->addr32[1] < b->addr32[1])
398 if (a->addr32[0] > b->addr32[0])
400 if (a->addr32[0] < b->addr32[0])
405 panic("%s: unknown address family %u", __func__, af);
410 static __inline uint32_t
411 pf_hashkey(struct pf_state_key *sk)
415 h = murmur3_aligned_32((uint32_t *)sk,
416 sizeof(struct pf_state_key_cmp),
419 return (h & pf_hashmask);
422 static __inline uint32_t
423 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
429 h = murmur3_aligned_32((uint32_t *)&addr->v4,
430 sizeof(addr->v4), V_pf_hashseed);
433 h = murmur3_aligned_32((uint32_t *)&addr->v6,
434 sizeof(addr->v6), V_pf_hashseed);
437 panic("%s: unknown address family %u", __func__, af);
440 return (h & pf_srchashmask);
445 pf_state_hash(struct pf_state *s)
447 u_int32_t hv = (intptr_t)s / sizeof(*s);
449 hv ^= crc32(&s->src, sizeof(s->src));
450 hv ^= crc32(&s->dst, sizeof(s->dst));
459 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
464 dst->addr32[0] = src->addr32[0];
468 dst->addr32[0] = src->addr32[0];
469 dst->addr32[1] = src->addr32[1];
470 dst->addr32[2] = src->addr32[2];
471 dst->addr32[3] = src->addr32[3];
478 pf_init_threshold(struct pf_threshold *threshold,
479 u_int32_t limit, u_int32_t seconds)
481 threshold->limit = limit * PF_THRESHOLD_MULT;
482 threshold->seconds = seconds;
483 threshold->count = 0;
484 threshold->last = time_uptime;
488 pf_add_threshold(struct pf_threshold *threshold)
490 u_int32_t t = time_uptime, diff = t - threshold->last;
492 if (diff >= threshold->seconds)
493 threshold->count = 0;
495 threshold->count -= threshold->count * diff /
497 threshold->count += PF_THRESHOLD_MULT;
502 pf_check_threshold(struct pf_threshold *threshold)
504 return (threshold->count > threshold->limit);
508 pf_src_connlimit(struct pf_state **state)
510 struct pf_overload_entry *pfoe;
513 PF_STATE_LOCK_ASSERT(*state);
515 (*state)->src_node->conn++;
516 (*state)->src.tcp_est = 1;
517 pf_add_threshold(&(*state)->src_node->conn_rate);
519 if ((*state)->rule.ptr->max_src_conn &&
520 (*state)->rule.ptr->max_src_conn <
521 (*state)->src_node->conn) {
522 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
526 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
527 pf_check_threshold(&(*state)->src_node->conn_rate)) {
528 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
535 /* Kill this state. */
536 (*state)->timeout = PFTM_PURGE;
537 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
539 if ((*state)->rule.ptr->overload_tbl == NULL)
542 /* Schedule overloading and flushing task. */
543 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
545 return (1); /* too bad :( */
547 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
548 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
549 pfoe->rule = (*state)->rule.ptr;
550 pfoe->dir = (*state)->direction;
552 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
553 PF_OVERLOADQ_UNLOCK();
554 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
560 pf_overload_task(void *v, int pending)
562 struct pf_overload_head queue;
564 struct pf_overload_entry *pfoe, *pfoe1;
567 CURVNET_SET((struct vnet *)v);
570 queue = V_pf_overloadqueue;
571 SLIST_INIT(&V_pf_overloadqueue);
572 PF_OVERLOADQ_UNLOCK();
574 bzero(&p, sizeof(p));
575 SLIST_FOREACH(pfoe, &queue, next) {
576 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
577 if (V_pf_status.debug >= PF_DEBUG_MISC) {
578 printf("%s: blocking address ", __func__);
579 pf_print_host(&pfoe->addr, 0, pfoe->af);
583 p.pfra_af = pfoe->af;
588 p.pfra_ip4addr = pfoe->addr.v4;
594 p.pfra_ip6addr = pfoe->addr.v6;
600 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
605 * Remove those entries, that don't need flushing.
607 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
608 if (pfoe->rule->flush == 0) {
609 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
610 free(pfoe, M_PFTEMP);
613 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
615 /* If nothing to flush, return. */
616 if (SLIST_EMPTY(&queue)) {
621 for (int i = 0; i <= pf_hashmask; i++) {
622 struct pf_idhash *ih = &V_pf_idhash[i];
623 struct pf_state_key *sk;
627 LIST_FOREACH(s, &ih->states, entry) {
628 sk = s->key[PF_SK_WIRE];
629 SLIST_FOREACH(pfoe, &queue, next)
630 if (sk->af == pfoe->af &&
631 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
632 pfoe->rule == s->rule.ptr) &&
633 ((pfoe->dir == PF_OUT &&
634 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
635 (pfoe->dir == PF_IN &&
636 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
637 s->timeout = PFTM_PURGE;
638 s->src.state = s->dst.state = TCPS_CLOSED;
642 PF_HASHROW_UNLOCK(ih);
644 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
645 free(pfoe, M_PFTEMP);
646 if (V_pf_status.debug >= PF_DEBUG_MISC)
647 printf("%s: %u states killed", __func__, killed);
653 * Can return locked on failure, so that we can consistently
654 * allocate and insert a new one.
657 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
660 struct pf_srchash *sh;
661 struct pf_src_node *n;
663 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
665 sh = &V_pf_srchash[pf_hashsrc(src, af)];
667 LIST_FOREACH(n, &sh->nodes, entry)
668 if (n->rule.ptr == rule && n->af == af &&
669 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
670 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
674 PF_HASHROW_UNLOCK(sh);
675 } else if (returnlocked == 0)
676 PF_HASHROW_UNLOCK(sh);
682 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
683 struct pf_addr *src, sa_family_t af)
686 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
687 rule->rpool.opts & PF_POOL_STICKYADDR),
688 ("%s for non-tracking rule %p", __func__, rule));
691 *sn = pf_find_src_node(src, rule, af, 1);
694 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
696 PF_HASHROW_ASSERT(sh);
698 if (!rule->max_src_nodes ||
699 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
700 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
702 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
705 PF_HASHROW_UNLOCK(sh);
709 pf_init_threshold(&(*sn)->conn_rate,
710 rule->max_src_conn_rate.limit,
711 rule->max_src_conn_rate.seconds);
714 (*sn)->rule.ptr = rule;
715 PF_ACPY(&(*sn)->addr, src, af);
716 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
717 (*sn)->creation = time_uptime;
718 (*sn)->ruletype = rule->action;
720 if ((*sn)->rule.ptr != NULL)
721 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
722 PF_HASHROW_UNLOCK(sh);
723 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
725 if (rule->max_src_states &&
726 (*sn)->states >= rule->max_src_states) {
727 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
736 pf_unlink_src_node(struct pf_src_node *src)
739 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
740 LIST_REMOVE(src, entry);
742 counter_u64_add(src->rule.ptr->src_nodes, -1);
746 pf_free_src_nodes(struct pf_src_node_list *head)
748 struct pf_src_node *sn, *tmp;
751 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
752 uma_zfree(V_pf_sources_z, sn);
756 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
765 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
766 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
770 /* Per-vnet data storage structures initialization. */
774 struct pf_keyhash *kh;
775 struct pf_idhash *ih;
776 struct pf_srchash *sh;
779 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &pf_hashsize);
780 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
781 pf_hashsize = PF_HASHSIZ;
782 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &pf_srchashsize);
783 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
784 pf_srchashsize = PF_HASHSIZ / 4;
786 V_pf_hashseed = arc4random();
788 /* States and state keys storage. */
789 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
790 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
791 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
792 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
793 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
795 V_pf_state_key_z = uma_zcreate("pf state keys",
796 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
798 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
799 M_PFHASH, M_WAITOK | M_ZERO);
800 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
801 M_PFHASH, M_WAITOK | M_ZERO);
802 pf_hashmask = pf_hashsize - 1;
803 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
805 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
806 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
810 V_pf_sources_z = uma_zcreate("pf source nodes",
811 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
813 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
814 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
815 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
816 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
817 M_PFHASH, M_WAITOK|M_ZERO);
818 pf_srchashmask = pf_srchashsize - 1;
819 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
820 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
823 TAILQ_INIT(&V_pf_altqs[0]);
824 TAILQ_INIT(&V_pf_altqs[1]);
825 TAILQ_INIT(&V_pf_pabuf);
826 V_pf_altqs_active = &V_pf_altqs[0];
827 V_pf_altqs_inactive = &V_pf_altqs[1];
830 /* Send & overload+flush queues. */
831 STAILQ_INIT(&V_pf_sendqueue);
832 SLIST_INIT(&V_pf_overloadqueue);
833 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
834 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
835 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
838 /* Unlinked, but may be referenced rules. */
839 TAILQ_INIT(&V_pf_unlinked_rules);
840 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
847 uma_zdestroy(pf_mtag_z);
853 struct pf_keyhash *kh;
854 struct pf_idhash *ih;
855 struct pf_srchash *sh;
856 struct pf_send_entry *pfse, *next;
859 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
861 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
863 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
865 mtx_destroy(&kh->lock);
866 mtx_destroy(&ih->lock);
868 free(V_pf_keyhash, M_PFHASH);
869 free(V_pf_idhash, M_PFHASH);
871 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
872 KASSERT(LIST_EMPTY(&sh->nodes),
873 ("%s: source node hash not empty", __func__));
874 mtx_destroy(&sh->lock);
876 free(V_pf_srchash, M_PFHASH);
878 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
879 m_freem(pfse->pfse_m);
880 free(pfse, M_PFTEMP);
883 mtx_destroy(&pf_sendqueue_mtx);
884 mtx_destroy(&pf_overloadqueue_mtx);
885 mtx_destroy(&pf_unlnkdrules_mtx);
887 uma_zdestroy(V_pf_sources_z);
888 uma_zdestroy(V_pf_state_z);
889 uma_zdestroy(V_pf_state_key_z);
893 pf_mtag_uminit(void *mem, int size, int how)
897 t = (struct m_tag *)mem;
898 t->m_tag_cookie = MTAG_ABI_COMPAT;
899 t->m_tag_id = PACKET_TAG_PF;
900 t->m_tag_len = sizeof(struct pf_mtag);
901 t->m_tag_free = pf_mtag_free;
907 pf_mtag_free(struct m_tag *t)
910 uma_zfree(pf_mtag_z, t);
914 pf_get_mtag(struct mbuf *m)
918 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
919 return ((struct pf_mtag *)(mtag + 1));
921 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
924 bzero(mtag + 1, sizeof(struct pf_mtag));
925 m_tag_prepend(m, mtag);
927 return ((struct pf_mtag *)(mtag + 1));
931 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
934 struct pf_keyhash *khs, *khw, *kh;
935 struct pf_state_key *sk, *cur;
936 struct pf_state *si, *olds = NULL;
939 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
940 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
941 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
944 * We need to lock hash slots of both keys. To avoid deadlock
945 * we always lock the slot with lower address first. Unlock order
948 * We also need to lock ID hash slot before dropping key
949 * locks. On success we return with ID hash slot locked.
953 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
954 PF_HASHROW_LOCK(khs);
956 khs = &V_pf_keyhash[pf_hashkey(sks)];
957 khw = &V_pf_keyhash[pf_hashkey(skw)];
959 PF_HASHROW_LOCK(khs);
960 } else if (khs < khw) {
961 PF_HASHROW_LOCK(khs);
962 PF_HASHROW_LOCK(khw);
964 PF_HASHROW_LOCK(khw);
965 PF_HASHROW_LOCK(khs);
969 #define KEYS_UNLOCK() do { \
971 PF_HASHROW_UNLOCK(khs); \
972 PF_HASHROW_UNLOCK(khw); \
974 PF_HASHROW_UNLOCK(khs); \
978 * First run: start with wire key.
985 LIST_FOREACH(cur, &kh->keys, entry)
986 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
990 /* Key exists. Check for same kif, if none, add to key. */
991 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
992 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
995 if (si->kif == s->kif &&
996 si->direction == s->direction) {
997 if (sk->proto == IPPROTO_TCP &&
998 si->src.state >= TCPS_FIN_WAIT_2 &&
999 si->dst.state >= TCPS_FIN_WAIT_2) {
1001 * New state matches an old >FIN_WAIT_2
1002 * state. We can't drop key hash locks,
1003 * thus we can't unlink it properly.
1005 * As a workaround we drop it into
1006 * TCPS_CLOSED state, schedule purge
1007 * ASAP and push it into the very end
1008 * of the slot TAILQ, so that it won't
1009 * conflict with our new state.
1011 si->src.state = si->dst.state =
1013 si->timeout = PFTM_PURGE;
1016 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1017 printf("pf: %s key attach "
1019 (idx == PF_SK_WIRE) ?
1022 pf_print_state_parts(s,
1023 (idx == PF_SK_WIRE) ?
1025 (idx == PF_SK_STACK) ?
1027 printf(", existing: ");
1028 pf_print_state_parts(si,
1029 (idx == PF_SK_WIRE) ?
1031 (idx == PF_SK_STACK) ?
1035 PF_HASHROW_UNLOCK(ih);
1037 uma_zfree(V_pf_state_key_z, sk);
1038 if (idx == PF_SK_STACK)
1040 return (EEXIST); /* collision! */
1043 PF_HASHROW_UNLOCK(ih);
1045 uma_zfree(V_pf_state_key_z, sk);
1048 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1053 /* List is sorted, if-bound states before floating. */
1054 if (s->kif == V_pfi_all)
1055 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1057 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1060 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1061 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1067 * Attach done. See how should we (or should not?)
1068 * attach a second key.
1071 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1075 } else if (sks != NULL) {
1077 * Continue attaching with stack key.
1089 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1090 ("%s failure", __func__));
1097 pf_detach_state(struct pf_state *s)
1099 struct pf_state_key *sks = s->key[PF_SK_STACK];
1100 struct pf_keyhash *kh;
1103 kh = &V_pf_keyhash[pf_hashkey(sks)];
1104 PF_HASHROW_LOCK(kh);
1105 if (s->key[PF_SK_STACK] != NULL)
1106 pf_state_key_detach(s, PF_SK_STACK);
1108 * If both point to same key, then we are done.
1110 if (sks == s->key[PF_SK_WIRE]) {
1111 pf_state_key_detach(s, PF_SK_WIRE);
1112 PF_HASHROW_UNLOCK(kh);
1115 PF_HASHROW_UNLOCK(kh);
1118 if (s->key[PF_SK_WIRE] != NULL) {
1119 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1120 PF_HASHROW_LOCK(kh);
1121 if (s->key[PF_SK_WIRE] != NULL)
1122 pf_state_key_detach(s, PF_SK_WIRE);
1123 PF_HASHROW_UNLOCK(kh);
1128 pf_state_key_detach(struct pf_state *s, int idx)
1130 struct pf_state_key *sk = s->key[idx];
1132 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1134 PF_HASHROW_ASSERT(kh);
1136 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1139 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1140 LIST_REMOVE(sk, entry);
1141 uma_zfree(V_pf_state_key_z, sk);
1146 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1148 struct pf_state_key *sk = mem;
1150 bzero(sk, sizeof(struct pf_state_key_cmp));
1151 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1152 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1157 struct pf_state_key *
1158 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1159 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1161 struct pf_state_key *sk;
1163 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1167 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1168 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1169 sk->port[pd->sidx] = sport;
1170 sk->port[pd->didx] = dport;
1171 sk->proto = pd->proto;
1177 struct pf_state_key *
1178 pf_state_key_clone(struct pf_state_key *orig)
1180 struct pf_state_key *sk;
1182 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1186 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1192 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1193 struct pf_state_key *sks, struct pf_state *s)
1195 struct pf_idhash *ih;
1196 struct pf_state *cur;
1199 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1200 ("%s: sks not pristine", __func__));
1201 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1202 ("%s: skw not pristine", __func__));
1203 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1207 if (s->id == 0 && s->creatorid == 0) {
1208 /* XXX: should be atomic, but probability of collision low */
1209 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1210 V_pf_stateid[curcpu] = 1;
1211 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1212 s->id = htobe64(s->id);
1213 s->creatorid = V_pf_status.hostid;
1216 /* Returns with ID locked on success. */
1217 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1220 ih = &V_pf_idhash[PF_IDHASH(s)];
1221 PF_HASHROW_ASSERT(ih);
1222 LIST_FOREACH(cur, &ih->states, entry)
1223 if (cur->id == s->id && cur->creatorid == s->creatorid)
1227 PF_HASHROW_UNLOCK(ih);
1228 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1229 printf("pf: state ID collision: "
1230 "id: %016llx creatorid: %08x\n",
1231 (unsigned long long)be64toh(s->id),
1232 ntohl(s->creatorid));
1237 LIST_INSERT_HEAD(&ih->states, s, entry);
1238 /* One for keys, one for ID hash. */
1239 refcount_init(&s->refs, 2);
1241 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1242 if (pfsync_insert_state_ptr != NULL)
1243 pfsync_insert_state_ptr(s);
1245 /* Returns locked. */
1250 * Find state by ID: returns with locked row on success.
1253 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1255 struct pf_idhash *ih;
1258 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1260 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1262 PF_HASHROW_LOCK(ih);
1263 LIST_FOREACH(s, &ih->states, entry)
1264 if (s->id == id && s->creatorid == creatorid)
1268 PF_HASHROW_UNLOCK(ih);
1274 * Find state by key.
1275 * Returns with ID hash slot locked on success.
1277 static struct pf_state *
1278 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1280 struct pf_keyhash *kh;
1281 struct pf_state_key *sk;
1285 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1287 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1289 PF_HASHROW_LOCK(kh);
1290 LIST_FOREACH(sk, &kh->keys, entry)
1291 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1294 PF_HASHROW_UNLOCK(kh);
1298 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1300 /* List is sorted, if-bound states before floating ones. */
1301 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1302 if (s->kif == V_pfi_all || s->kif == kif) {
1304 PF_HASHROW_UNLOCK(kh);
1305 if (s->timeout >= PFTM_MAX) {
1307 * State is either being processed by
1308 * pf_unlink_state() in an other thread, or
1309 * is scheduled for immediate expiry.
1316 PF_HASHROW_UNLOCK(kh);
1322 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1324 struct pf_keyhash *kh;
1325 struct pf_state_key *sk;
1326 struct pf_state *s, *ret = NULL;
1329 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1331 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1333 PF_HASHROW_LOCK(kh);
1334 LIST_FOREACH(sk, &kh->keys, entry)
1335 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1338 PF_HASHROW_UNLOCK(kh);
1353 panic("%s: dir %u", __func__, dir);
1356 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1358 PF_HASHROW_UNLOCK(kh);
1372 PF_HASHROW_UNLOCK(kh);
1377 /* END state table stuff */
1380 pf_send(struct pf_send_entry *pfse)
1384 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1386 swi_sched(V_pf_swi_cookie, 0);
1392 struct pf_send_head queue;
1393 struct pf_send_entry *pfse, *next;
1395 CURVNET_SET((struct vnet *)v);
1398 queue = V_pf_sendqueue;
1399 STAILQ_INIT(&V_pf_sendqueue);
1402 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1403 switch (pfse->pfse_type) {
1406 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1409 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1410 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1415 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1419 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1420 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1424 panic("%s: unknown type", __func__);
1426 free(pfse, M_PFTEMP);
1432 pf_purge_thread(void *v)
1436 CURVNET_SET((struct vnet *)v);
1440 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1442 if (V_pf_end_threads) {
1444 * To cleanse up all kifs and rules we need
1445 * two runs: first one clears reference flags,
1446 * then pf_purge_expired_states() doesn't
1447 * raise them, and then second run frees.
1450 pf_purge_unlinked_rules();
1454 * Now purge everything.
1456 pf_purge_expired_states(0, pf_hashmask);
1457 pf_purge_expired_fragments();
1458 pf_purge_expired_src_nodes();
1461 * Now all kifs & rules should be unreferenced,
1462 * thus should be successfully freed.
1464 pf_purge_unlinked_rules();
1468 * Announce success and exit.
1473 wakeup(pf_purge_thread);
1478 /* Process 1/interval fraction of the state table every run. */
1479 idx = pf_purge_expired_states(idx, pf_hashmask /
1480 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1482 /* Purge other expired types every PFTM_INTERVAL seconds. */
1485 * Order is important:
1486 * - states and src nodes reference rules
1487 * - states and rules reference kifs
1489 pf_purge_expired_fragments();
1490 pf_purge_expired_src_nodes();
1491 pf_purge_unlinked_rules();
1500 pf_state_expires(const struct pf_state *state)
1507 /* handle all PFTM_* > PFTM_MAX here */
1508 if (state->timeout == PFTM_PURGE)
1509 return (time_uptime);
1510 KASSERT(state->timeout != PFTM_UNLINKED,
1511 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1512 KASSERT((state->timeout < PFTM_MAX),
1513 ("pf_state_expires: timeout > PFTM_MAX"));
1514 timeout = state->rule.ptr->timeout[state->timeout];
1516 timeout = V_pf_default_rule.timeout[state->timeout];
1517 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1519 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1520 states = counter_u64_fetch(state->rule.ptr->states_cur);
1522 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1523 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1524 states = V_pf_status.states;
1526 if (end && states > start && start < end) {
1528 return (state->expire + timeout * (end - states) /
1531 return (time_uptime);
1533 return (state->expire + timeout);
1537 pf_purge_expired_src_nodes()
1539 struct pf_src_node_list freelist;
1540 struct pf_srchash *sh;
1541 struct pf_src_node *cur, *next;
1544 LIST_INIT(&freelist);
1545 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1546 PF_HASHROW_LOCK(sh);
1547 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1548 if (cur->states == 0 && cur->expire <= time_uptime) {
1549 pf_unlink_src_node(cur);
1550 LIST_INSERT_HEAD(&freelist, cur, entry);
1551 } else if (cur->rule.ptr != NULL)
1552 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1553 PF_HASHROW_UNLOCK(sh);
1556 pf_free_src_nodes(&freelist);
1558 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1562 pf_src_tree_remove_state(struct pf_state *s)
1564 struct pf_src_node *sn;
1565 struct pf_srchash *sh;
1568 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1569 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1570 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1572 if (s->src_node != NULL) {
1574 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1575 PF_HASHROW_LOCK(sh);
1578 if (--sn->states == 0)
1579 sn->expire = time_uptime + timeout;
1580 PF_HASHROW_UNLOCK(sh);
1582 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1583 sn = s->nat_src_node;
1584 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1585 PF_HASHROW_LOCK(sh);
1586 if (--sn->states == 0)
1587 sn->expire = time_uptime + timeout;
1588 PF_HASHROW_UNLOCK(sh);
1590 s->src_node = s->nat_src_node = NULL;
1594 * Unlink and potentilly free a state. Function may be
1595 * called with ID hash row locked, but always returns
1596 * unlocked, since it needs to go through key hash locking.
1599 pf_unlink_state(struct pf_state *s, u_int flags)
1601 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1603 if ((flags & PF_ENTER_LOCKED) == 0)
1604 PF_HASHROW_LOCK(ih);
1606 PF_HASHROW_ASSERT(ih);
1608 if (s->timeout == PFTM_UNLINKED) {
1610 * State is being processed
1611 * by pf_unlink_state() in
1614 PF_HASHROW_UNLOCK(ih);
1615 return (0); /* XXXGL: undefined actually */
1618 if (s->src.state == PF_TCPS_PROXY_DST) {
1619 /* XXX wire key the right one? */
1620 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1621 &s->key[PF_SK_WIRE]->addr[1],
1622 &s->key[PF_SK_WIRE]->addr[0],
1623 s->key[PF_SK_WIRE]->port[1],
1624 s->key[PF_SK_WIRE]->port[0],
1625 s->src.seqhi, s->src.seqlo + 1,
1626 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1629 LIST_REMOVE(s, entry);
1630 pf_src_tree_remove_state(s);
1632 if (pfsync_delete_state_ptr != NULL)
1633 pfsync_delete_state_ptr(s);
1635 STATE_DEC_COUNTERS(s);
1637 s->timeout = PFTM_UNLINKED;
1639 PF_HASHROW_UNLOCK(ih);
1642 refcount_release(&s->refs);
1644 return (pf_release_state(s));
1648 pf_free_state(struct pf_state *cur)
1651 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1652 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1655 pf_normalize_tcp_cleanup(cur);
1656 uma_zfree(V_pf_state_z, cur);
1657 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1661 * Called only from pf_purge_thread(), thus serialized.
1664 pf_purge_expired_states(u_int i, int maxcheck)
1666 struct pf_idhash *ih;
1669 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1672 * Go through hash and unlink states that expire now.
1674 while (maxcheck > 0) {
1676 ih = &V_pf_idhash[i];
1678 PF_HASHROW_LOCK(ih);
1679 LIST_FOREACH(s, &ih->states, entry) {
1680 if (pf_state_expires(s) <= time_uptime) {
1681 V_pf_status.states -=
1682 pf_unlink_state(s, PF_ENTER_LOCKED);
1685 s->rule.ptr->rule_flag |= PFRULE_REFS;
1686 if (s->nat_rule.ptr != NULL)
1687 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1688 if (s->anchor.ptr != NULL)
1689 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1690 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1692 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1694 PF_HASHROW_UNLOCK(ih);
1696 /* Return when we hit end of hash. */
1697 if (++i > pf_hashmask) {
1698 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1705 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1711 pf_purge_unlinked_rules()
1713 struct pf_rulequeue tmpq;
1714 struct pf_rule *r, *r1;
1717 * If we have overloading task pending, then we'd
1718 * better skip purging this time. There is a tiny
1719 * probability that overloading task references
1720 * an already unlinked rule.
1722 PF_OVERLOADQ_LOCK();
1723 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1724 PF_OVERLOADQ_UNLOCK();
1727 PF_OVERLOADQ_UNLOCK();
1730 * Do naive mark-and-sweep garbage collecting of old rules.
1731 * Reference flag is raised by pf_purge_expired_states()
1732 * and pf_purge_expired_src_nodes().
1734 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1735 * use a temporary queue.
1738 PF_UNLNKDRULES_LOCK();
1739 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1740 if (!(r->rule_flag & PFRULE_REFS)) {
1741 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1742 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1744 r->rule_flag &= ~PFRULE_REFS;
1746 PF_UNLNKDRULES_UNLOCK();
1748 if (!TAILQ_EMPTY(&tmpq)) {
1750 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1751 TAILQ_REMOVE(&tmpq, r, entries);
1759 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1764 u_int32_t a = ntohl(addr->addr32[0]);
1765 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1777 u_int8_t i, curstart, curend, maxstart, maxend;
1778 curstart = curend = maxstart = maxend = 255;
1779 for (i = 0; i < 8; i++) {
1780 if (!addr->addr16[i]) {
1781 if (curstart == 255)
1785 if ((curend - curstart) >
1786 (maxend - maxstart)) {
1787 maxstart = curstart;
1790 curstart = curend = 255;
1793 if ((curend - curstart) >
1794 (maxend - maxstart)) {
1795 maxstart = curstart;
1798 for (i = 0; i < 8; i++) {
1799 if (i >= maxstart && i <= maxend) {
1805 b = ntohs(addr->addr16[i]);
1822 pf_print_state(struct pf_state *s)
1824 pf_print_state_parts(s, NULL, NULL);
1828 pf_print_state_parts(struct pf_state *s,
1829 struct pf_state_key *skwp, struct pf_state_key *sksp)
1831 struct pf_state_key *skw, *sks;
1832 u_int8_t proto, dir;
1834 /* Do our best to fill these, but they're skipped if NULL */
1835 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1836 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1837 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1838 dir = s ? s->direction : 0;
1856 case IPPROTO_ICMPV6:
1860 printf("%u", skw->proto);
1873 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1875 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1880 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1882 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1887 if (proto == IPPROTO_TCP) {
1888 printf(" [lo=%u high=%u win=%u modulator=%u",
1889 s->src.seqlo, s->src.seqhi,
1890 s->src.max_win, s->src.seqdiff);
1891 if (s->src.wscale && s->dst.wscale)
1892 printf(" wscale=%u",
1893 s->src.wscale & PF_WSCALE_MASK);
1895 printf(" [lo=%u high=%u win=%u modulator=%u",
1896 s->dst.seqlo, s->dst.seqhi,
1897 s->dst.max_win, s->dst.seqdiff);
1898 if (s->src.wscale && s->dst.wscale)
1899 printf(" wscale=%u",
1900 s->dst.wscale & PF_WSCALE_MASK);
1903 printf(" %u:%u", s->src.state, s->dst.state);
1908 pf_print_flags(u_int8_t f)
1930 #define PF_SET_SKIP_STEPS(i) \
1932 while (head[i] != cur) { \
1933 head[i]->skip[i].ptr = cur; \
1934 head[i] = TAILQ_NEXT(head[i], entries); \
1939 pf_calc_skip_steps(struct pf_rulequeue *rules)
1941 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1944 cur = TAILQ_FIRST(rules);
1946 for (i = 0; i < PF_SKIP_COUNT; ++i)
1948 while (cur != NULL) {
1950 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1951 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1952 if (cur->direction != prev->direction)
1953 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1954 if (cur->af != prev->af)
1955 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1956 if (cur->proto != prev->proto)
1957 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1958 if (cur->src.neg != prev->src.neg ||
1959 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1960 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1961 if (cur->src.port[0] != prev->src.port[0] ||
1962 cur->src.port[1] != prev->src.port[1] ||
1963 cur->src.port_op != prev->src.port_op)
1964 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1965 if (cur->dst.neg != prev->dst.neg ||
1966 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1967 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1968 if (cur->dst.port[0] != prev->dst.port[0] ||
1969 cur->dst.port[1] != prev->dst.port[1] ||
1970 cur->dst.port_op != prev->dst.port_op)
1971 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1974 cur = TAILQ_NEXT(cur, entries);
1976 for (i = 0; i < PF_SKIP_COUNT; ++i)
1977 PF_SET_SKIP_STEPS(i);
1981 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1983 if (aw1->type != aw2->type)
1985 switch (aw1->type) {
1986 case PF_ADDR_ADDRMASK:
1988 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
1990 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
1993 case PF_ADDR_DYNIFTL:
1994 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1995 case PF_ADDR_NOROUTE:
1996 case PF_ADDR_URPFFAILED:
1999 return (aw1->p.tbl != aw2->p.tbl);
2001 printf("invalid address type: %d\n", aw1->type);
2007 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2008 * header isn't always a full checksum. In some cases (i.e. output) it's a
2009 * pseudo-header checksum, which is a partial checksum over src/dst IP
2010 * addresses, protocol number and length.
2012 * That means we have the following cases:
2013 * * Input or forwarding: we don't have TSO, the checksum fields are full
2014 * checksums, we need to update the checksum whenever we change anything.
2015 * * Output (i.e. the checksum is a pseudo-header checksum):
2016 * x The field being updated is src/dst address or affects the length of
2017 * the packet. We need to update the pseudo-header checksum (note that this
2018 * checksum is not ones' complement).
2019 * x Some other field is being modified (e.g. src/dst port numbers): We
2020 * don't have to update anything.
2023 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2029 l = cksum + old - new;
2030 l = (l >> 16) + (l & 65535);
2038 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2039 u_int16_t new, u_int8_t udp)
2041 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2044 return (pf_cksum_fixup(cksum, old, new, udp));
2048 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2049 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2055 PF_ACPY(&ao, a, af);
2058 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2066 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2067 ao.addr16[0], an->addr16[0], 0),
2068 ao.addr16[1], an->addr16[1], 0);
2071 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2072 ao.addr16[0], an->addr16[0], u),
2073 ao.addr16[1], an->addr16[1], u);
2075 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2080 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2081 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2082 pf_cksum_fixup(pf_cksum_fixup(*pc,
2083 ao.addr16[0], an->addr16[0], u),
2084 ao.addr16[1], an->addr16[1], u),
2085 ao.addr16[2], an->addr16[2], u),
2086 ao.addr16[3], an->addr16[3], u),
2087 ao.addr16[4], an->addr16[4], u),
2088 ao.addr16[5], an->addr16[5], u),
2089 ao.addr16[6], an->addr16[6], u),
2090 ao.addr16[7], an->addr16[7], u);
2092 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2097 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2098 CSUM_DELAY_DATA_IPV6)) {
2105 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2107 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2111 memcpy(&ao, a, sizeof(ao));
2112 memcpy(a, &an, sizeof(u_int32_t));
2113 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2114 ao % 65536, an % 65536, u);
2118 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2122 memcpy(&ao, a, sizeof(ao));
2123 memcpy(a, &an, sizeof(u_int32_t));
2125 *c = pf_proto_cksum_fixup(m,
2126 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2127 ao % 65536, an % 65536, udp);
2132 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2136 PF_ACPY(&ao, a, AF_INET6);
2137 PF_ACPY(a, an, AF_INET6);
2139 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2140 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2141 pf_cksum_fixup(pf_cksum_fixup(*c,
2142 ao.addr16[0], an->addr16[0], u),
2143 ao.addr16[1], an->addr16[1], u),
2144 ao.addr16[2], an->addr16[2], u),
2145 ao.addr16[3], an->addr16[3], u),
2146 ao.addr16[4], an->addr16[4], u),
2147 ao.addr16[5], an->addr16[5], u),
2148 ao.addr16[6], an->addr16[6], u),
2149 ao.addr16[7], an->addr16[7], u);
2154 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2155 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2156 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2158 struct pf_addr oia, ooa;
2160 PF_ACPY(&oia, ia, af);
2162 PF_ACPY(&ooa, oa, af);
2164 /* Change inner protocol port, fix inner protocol checksum. */
2166 u_int16_t oip = *ip;
2173 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2174 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2176 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2178 /* Change inner ip address, fix inner ip and icmp checksums. */
2179 PF_ACPY(ia, na, af);
2183 u_int32_t oh2c = *h2c;
2185 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2186 oia.addr16[0], ia->addr16[0], 0),
2187 oia.addr16[1], ia->addr16[1], 0);
2188 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2189 oia.addr16[0], ia->addr16[0], 0),
2190 oia.addr16[1], ia->addr16[1], 0);
2191 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2197 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2198 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2199 pf_cksum_fixup(pf_cksum_fixup(*ic,
2200 oia.addr16[0], ia->addr16[0], u),
2201 oia.addr16[1], ia->addr16[1], u),
2202 oia.addr16[2], ia->addr16[2], u),
2203 oia.addr16[3], ia->addr16[3], u),
2204 oia.addr16[4], ia->addr16[4], u),
2205 oia.addr16[5], ia->addr16[5], u),
2206 oia.addr16[6], ia->addr16[6], u),
2207 oia.addr16[7], ia->addr16[7], u);
2211 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2213 PF_ACPY(oa, na, af);
2217 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2218 ooa.addr16[0], oa->addr16[0], 0),
2219 ooa.addr16[1], oa->addr16[1], 0);
2224 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2225 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2226 pf_cksum_fixup(pf_cksum_fixup(*ic,
2227 ooa.addr16[0], oa->addr16[0], u),
2228 ooa.addr16[1], oa->addr16[1], u),
2229 ooa.addr16[2], oa->addr16[2], u),
2230 ooa.addr16[3], oa->addr16[3], u),
2231 ooa.addr16[4], oa->addr16[4], u),
2232 ooa.addr16[5], oa->addr16[5], u),
2233 ooa.addr16[6], oa->addr16[6], u),
2234 ooa.addr16[7], oa->addr16[7], u);
2243 * Need to modulate the sequence numbers in the TCP SACK option
2244 * (credits to Krzysztof Pfaff for report and patch)
2247 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2248 struct tcphdr *th, struct pf_state_peer *dst)
2250 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2251 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2252 int copyback = 0, i, olen;
2253 struct sackblk sack;
2255 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2256 if (hlen < TCPOLEN_SACKLEN ||
2257 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2260 while (hlen >= TCPOLEN_SACKLEN) {
2263 case TCPOPT_EOL: /* FALLTHROUGH */
2271 if (olen >= TCPOLEN_SACKLEN) {
2272 for (i = 2; i + TCPOLEN_SACK <= olen;
2273 i += TCPOLEN_SACK) {
2274 memcpy(&sack, &opt[i], sizeof(sack));
2275 pf_change_proto_a(m, &sack.start, &th->th_sum,
2276 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2277 pf_change_proto_a(m, &sack.end, &th->th_sum,
2278 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2279 memcpy(&opt[i], &sack, sizeof(sack));
2293 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2298 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2299 const struct pf_addr *saddr, const struct pf_addr *daddr,
2300 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2301 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2302 u_int16_t rtag, struct ifnet *ifp)
2304 struct pf_send_entry *pfse;
2308 struct ip *h = NULL;
2311 struct ip6_hdr *h6 = NULL;
2315 struct pf_mtag *pf_mtag;
2320 /* maximum segment size tcp option */
2321 tlen = sizeof(struct tcphdr);
2328 len = sizeof(struct ip) + tlen;
2333 len = sizeof(struct ip6_hdr) + tlen;
2337 panic("%s: unsupported af %d", __func__, af);
2340 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2341 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2344 m = m_gethdr(M_NOWAIT, MT_DATA);
2346 free(pfse, M_PFTEMP);
2350 mac_netinet_firewall_send(m);
2352 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2353 free(pfse, M_PFTEMP);
2358 m->m_flags |= M_SKIP_FIREWALL;
2359 pf_mtag->tag = rtag;
2361 if (r != NULL && r->rtableid >= 0)
2362 M_SETFIB(m, r->rtableid);
2365 if (r != NULL && r->qid) {
2366 pf_mtag->qid = r->qid;
2368 /* add hints for ecn */
2369 pf_mtag->hdr = mtod(m, struct ip *);
2372 m->m_data += max_linkhdr;
2373 m->m_pkthdr.len = m->m_len = len;
2374 m->m_pkthdr.rcvif = NULL;
2375 bzero(m->m_data, len);
2379 h = mtod(m, struct ip *);
2381 /* IP header fields included in the TCP checksum */
2382 h->ip_p = IPPROTO_TCP;
2383 h->ip_len = htons(tlen);
2384 h->ip_src.s_addr = saddr->v4.s_addr;
2385 h->ip_dst.s_addr = daddr->v4.s_addr;
2387 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2392 h6 = mtod(m, struct ip6_hdr *);
2394 /* IP header fields included in the TCP checksum */
2395 h6->ip6_nxt = IPPROTO_TCP;
2396 h6->ip6_plen = htons(tlen);
2397 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2398 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2400 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2406 th->th_sport = sport;
2407 th->th_dport = dport;
2408 th->th_seq = htonl(seq);
2409 th->th_ack = htonl(ack);
2410 th->th_off = tlen >> 2;
2411 th->th_flags = flags;
2412 th->th_win = htons(win);
2415 opt = (char *)(th + 1);
2416 opt[0] = TCPOPT_MAXSEG;
2419 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2426 th->th_sum = in_cksum(m, len);
2428 /* Finish the IP header */
2430 h->ip_hl = sizeof(*h) >> 2;
2431 h->ip_tos = IPTOS_LOWDELAY;
2432 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2433 h->ip_len = htons(len);
2434 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2437 pfse->pfse_type = PFSE_IP;
2443 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2444 sizeof(struct ip6_hdr), tlen);
2446 h6->ip6_vfc |= IPV6_VERSION;
2447 h6->ip6_hlim = IPV6_DEFHLIM;
2449 pfse->pfse_type = PFSE_IP6;
2458 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2461 struct pf_send_entry *pfse;
2463 struct pf_mtag *pf_mtag;
2465 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2466 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2470 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2471 free(pfse, M_PFTEMP);
2475 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2476 free(pfse, M_PFTEMP);
2480 m0->m_flags |= M_SKIP_FIREWALL;
2482 if (r->rtableid >= 0)
2483 M_SETFIB(m0, r->rtableid);
2487 pf_mtag->qid = r->qid;
2488 /* add hints for ecn */
2489 pf_mtag->hdr = mtod(m0, struct ip *);
2496 pfse->pfse_type = PFSE_ICMP;
2501 pfse->pfse_type = PFSE_ICMP6;
2506 pfse->pfse_icmp_type = type;
2507 pfse->pfse_icmp_code = code;
2512 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2513 * If n is 0, they match if they are equal. If n is != 0, they match if they
2517 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2518 struct pf_addr *b, sa_family_t af)
2525 if ((a->addr32[0] & m->addr32[0]) ==
2526 (b->addr32[0] & m->addr32[0]))
2532 if (((a->addr32[0] & m->addr32[0]) ==
2533 (b->addr32[0] & m->addr32[0])) &&
2534 ((a->addr32[1] & m->addr32[1]) ==
2535 (b->addr32[1] & m->addr32[1])) &&
2536 ((a->addr32[2] & m->addr32[2]) ==
2537 (b->addr32[2] & m->addr32[2])) &&
2538 ((a->addr32[3] & m->addr32[3]) ==
2539 (b->addr32[3] & m->addr32[3])))
2558 * Return 1 if b <= a <= e, otherwise return 0.
2561 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2562 struct pf_addr *a, sa_family_t af)
2567 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2568 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2577 for (i = 0; i < 4; ++i)
2578 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2580 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2583 for (i = 0; i < 4; ++i)
2584 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2586 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2596 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2600 return ((p > a1) && (p < a2));
2602 return ((p < a1) || (p > a2));
2604 return ((p >= a1) && (p <= a2));
2618 return (0); /* never reached */
2622 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2627 return (pf_match(op, a1, a2, p));
2631 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2633 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2635 return (pf_match(op, a1, a2, u));
2639 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2641 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2643 return (pf_match(op, a1, a2, g));
2647 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2652 return ((!r->match_tag_not && r->match_tag == *tag) ||
2653 (r->match_tag_not && r->match_tag != *tag));
2657 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2660 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2662 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2665 pd->pf_mtag->tag = tag;
2670 #define PF_ANCHOR_STACKSIZE 32
2671 struct pf_anchor_stackframe {
2672 struct pf_ruleset *rs;
2673 struct pf_rule *r; /* XXX: + match bit */
2674 struct pf_anchor *child;
2678 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2680 #define PF_ANCHORSTACK_MATCH 0x00000001
2681 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2683 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2684 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2685 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2686 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2687 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2691 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2692 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2695 struct pf_anchor_stackframe *f;
2701 if (*depth >= PF_ANCHOR_STACKSIZE) {
2702 printf("%s: anchor stack overflow on %s\n",
2703 __func__, (*r)->anchor->name);
2704 *r = TAILQ_NEXT(*r, entries);
2706 } else if (*depth == 0 && a != NULL)
2708 f = stack + (*depth)++;
2711 if ((*r)->anchor_wildcard) {
2712 struct pf_anchor_node *parent = &(*r)->anchor->children;
2714 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2718 *rs = &f->child->ruleset;
2721 *rs = &(*r)->anchor->ruleset;
2723 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2727 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2728 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2731 struct pf_anchor_stackframe *f;
2740 f = stack + *depth - 1;
2741 fr = PF_ANCHOR_RULE(f);
2742 if (f->child != NULL) {
2743 struct pf_anchor_node *parent;
2746 * This block traverses through
2747 * a wildcard anchor.
2749 parent = &fr->anchor->children;
2750 if (match != NULL && *match) {
2752 * If any of "*" matched, then
2753 * "foo/ *" matched, mark frame
2756 PF_ANCHOR_SET_MATCH(f);
2759 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2760 if (f->child != NULL) {
2761 *rs = &f->child->ruleset;
2762 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2770 if (*depth == 0 && a != NULL)
2773 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2775 *r = TAILQ_NEXT(fr, entries);
2776 } while (*r == NULL);
2783 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2784 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2789 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2790 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2794 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2795 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2796 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2797 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2798 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2799 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2800 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2801 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2807 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2812 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2816 if (addr->addr32[3] == 0xffffffff) {
2817 addr->addr32[3] = 0;
2818 if (addr->addr32[2] == 0xffffffff) {
2819 addr->addr32[2] = 0;
2820 if (addr->addr32[1] == 0xffffffff) {
2821 addr->addr32[1] = 0;
2823 htonl(ntohl(addr->addr32[0]) + 1);
2826 htonl(ntohl(addr->addr32[1]) + 1);
2829 htonl(ntohl(addr->addr32[2]) + 1);
2832 htonl(ntohl(addr->addr32[3]) + 1);
2839 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2841 struct pf_addr *saddr, *daddr;
2842 u_int16_t sport, dport;
2843 struct inpcbinfo *pi;
2846 pd->lookup.uid = UID_MAX;
2847 pd->lookup.gid = GID_MAX;
2849 switch (pd->proto) {
2851 if (pd->hdr.tcp == NULL)
2853 sport = pd->hdr.tcp->th_sport;
2854 dport = pd->hdr.tcp->th_dport;
2858 if (pd->hdr.udp == NULL)
2860 sport = pd->hdr.udp->uh_sport;
2861 dport = pd->hdr.udp->uh_dport;
2867 if (direction == PF_IN) {
2882 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2883 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2885 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2886 daddr->v4, dport, INPLOOKUP_WILDCARD |
2887 INPLOOKUP_RLOCKPCB, NULL, m);
2895 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2896 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2898 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2899 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2900 INPLOOKUP_RLOCKPCB, NULL, m);
2910 INP_RLOCK_ASSERT(inp);
2911 pd->lookup.uid = inp->inp_cred->cr_uid;
2912 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2919 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2923 u_int8_t *opt, optlen;
2924 u_int8_t wscale = 0;
2926 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2927 if (hlen <= sizeof(struct tcphdr))
2929 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2931 opt = hdr + sizeof(struct tcphdr);
2932 hlen -= sizeof(struct tcphdr);
2942 if (wscale > TCP_MAX_WINSHIFT)
2943 wscale = TCP_MAX_WINSHIFT;
2944 wscale |= PF_WSCALE_FLAG;
2959 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2963 u_int8_t *opt, optlen;
2964 u_int16_t mss = V_tcp_mssdflt;
2966 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2967 if (hlen <= sizeof(struct tcphdr))
2969 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2971 opt = hdr + sizeof(struct tcphdr);
2972 hlen -= sizeof(struct tcphdr);
2973 while (hlen >= TCPOLEN_MAXSEG) {
2981 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2997 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3000 struct sockaddr_in *dst;
3004 struct sockaddr_in6 *dst6;
3005 struct route_in6 ro6;
3007 struct rtentry *rt = NULL;
3009 u_int16_t mss = V_tcp_mssdflt;
3014 hlen = sizeof(struct ip);
3015 bzero(&ro, sizeof(ro));
3016 dst = (struct sockaddr_in *)&ro.ro_dst;
3017 dst->sin_family = AF_INET;
3018 dst->sin_len = sizeof(*dst);
3019 dst->sin_addr = addr->v4;
3020 in_rtalloc_ign(&ro, 0, rtableid);
3026 hlen = sizeof(struct ip6_hdr);
3027 bzero(&ro6, sizeof(ro6));
3028 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3029 dst6->sin6_family = AF_INET6;
3030 dst6->sin6_len = sizeof(*dst6);
3031 dst6->sin6_addr = addr->v6;
3032 in6_rtalloc_ign(&ro6, 0, rtableid);
3038 if (rt && rt->rt_ifp) {
3039 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3040 mss = max(V_tcp_mssdflt, mss);
3043 mss = min(mss, offer);
3044 mss = max(mss, 64); /* sanity - at least max opt space */
3049 pf_tcp_iss(struct pf_pdesc *pd)
3052 u_int32_t digest[4];
3054 if (V_pf_tcp_secret_init == 0) {
3055 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3056 MD5Init(&V_pf_tcp_secret_ctx);
3057 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3058 sizeof(V_pf_tcp_secret));
3059 V_pf_tcp_secret_init = 1;
3062 ctx = V_pf_tcp_secret_ctx;
3064 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3065 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3066 if (pd->af == AF_INET6) {
3067 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3068 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3070 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3071 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3073 MD5Final((u_char *)digest, &ctx);
3074 V_pf_tcp_iss_off += 4096;
3075 #define ISN_RANDOM_INCREMENT (4096 - 1)
3076 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3078 #undef ISN_RANDOM_INCREMENT
3082 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3083 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3084 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3086 struct pf_rule *nr = NULL;
3087 struct pf_addr * const saddr = pd->src;
3088 struct pf_addr * const daddr = pd->dst;
3089 sa_family_t af = pd->af;
3090 struct pf_rule *r, *a = NULL;
3091 struct pf_ruleset *ruleset = NULL;
3092 struct pf_src_node *nsn = NULL;
3093 struct tcphdr *th = pd->hdr.tcp;
3094 struct pf_state_key *sk = NULL, *nk = NULL;
3096 int rewrite = 0, hdrlen = 0;
3097 int tag = -1, rtableid = -1;
3101 u_int16_t sport = 0, dport = 0;
3102 u_int16_t bproto_sum = 0, bip_sum = 0;
3103 u_int8_t icmptype = 0, icmpcode = 0;
3104 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3109 INP_LOCK_ASSERT(inp);
3110 pd->lookup.uid = inp->inp_cred->cr_uid;
3111 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3112 pd->lookup.done = 1;
3115 switch (pd->proto) {
3117 sport = th->th_sport;
3118 dport = th->th_dport;
3119 hdrlen = sizeof(*th);
3122 sport = pd->hdr.udp->uh_sport;
3123 dport = pd->hdr.udp->uh_dport;
3124 hdrlen = sizeof(*pd->hdr.udp);
3128 if (pd->af != AF_INET)
3130 sport = dport = pd->hdr.icmp->icmp_id;
3131 hdrlen = sizeof(*pd->hdr.icmp);
3132 icmptype = pd->hdr.icmp->icmp_type;
3133 icmpcode = pd->hdr.icmp->icmp_code;
3135 if (icmptype == ICMP_UNREACH ||
3136 icmptype == ICMP_SOURCEQUENCH ||
3137 icmptype == ICMP_REDIRECT ||
3138 icmptype == ICMP_TIMXCEED ||
3139 icmptype == ICMP_PARAMPROB)
3144 case IPPROTO_ICMPV6:
3147 sport = dport = pd->hdr.icmp6->icmp6_id;
3148 hdrlen = sizeof(*pd->hdr.icmp6);
3149 icmptype = pd->hdr.icmp6->icmp6_type;
3150 icmpcode = pd->hdr.icmp6->icmp6_code;
3152 if (icmptype == ICMP6_DST_UNREACH ||
3153 icmptype == ICMP6_PACKET_TOO_BIG ||
3154 icmptype == ICMP6_TIME_EXCEEDED ||
3155 icmptype == ICMP6_PARAM_PROB)
3160 sport = dport = hdrlen = 0;
3164 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3166 /* check packet for BINAT/NAT/RDR */
3167 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3168 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3169 KASSERT(sk != NULL, ("%s: null sk", __func__));
3170 KASSERT(nk != NULL, ("%s: null nk", __func__));
3173 bip_sum = *pd->ip_sum;
3175 switch (pd->proto) {
3177 bproto_sum = th->th_sum;
3178 pd->proto_sum = &th->th_sum;
3180 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3181 nk->port[pd->sidx] != sport) {
3182 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3183 &th->th_sum, &nk->addr[pd->sidx],
3184 nk->port[pd->sidx], 0, af);
3185 pd->sport = &th->th_sport;
3186 sport = th->th_sport;
3189 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3190 nk->port[pd->didx] != dport) {
3191 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3192 &th->th_sum, &nk->addr[pd->didx],
3193 nk->port[pd->didx], 0, af);
3194 dport = th->th_dport;
3195 pd->dport = &th->th_dport;
3200 bproto_sum = pd->hdr.udp->uh_sum;
3201 pd->proto_sum = &pd->hdr.udp->uh_sum;
3203 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3204 nk->port[pd->sidx] != sport) {
3205 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3206 pd->ip_sum, &pd->hdr.udp->uh_sum,
3207 &nk->addr[pd->sidx],
3208 nk->port[pd->sidx], 1, af);
3209 sport = pd->hdr.udp->uh_sport;
3210 pd->sport = &pd->hdr.udp->uh_sport;
3213 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3214 nk->port[pd->didx] != dport) {
3215 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3216 pd->ip_sum, &pd->hdr.udp->uh_sum,
3217 &nk->addr[pd->didx],
3218 nk->port[pd->didx], 1, af);
3219 dport = pd->hdr.udp->uh_dport;
3220 pd->dport = &pd->hdr.udp->uh_dport;
3226 nk->port[0] = nk->port[1];
3227 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3228 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3229 nk->addr[pd->sidx].v4.s_addr, 0);
3231 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3232 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3233 nk->addr[pd->didx].v4.s_addr, 0);
3235 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3236 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3237 pd->hdr.icmp->icmp_cksum, sport,
3239 pd->hdr.icmp->icmp_id = nk->port[1];
3240 pd->sport = &pd->hdr.icmp->icmp_id;
3242 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3246 case IPPROTO_ICMPV6:
3247 nk->port[0] = nk->port[1];
3248 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3249 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3250 &nk->addr[pd->sidx], 0);
3252 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3253 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3254 &nk->addr[pd->didx], 0);
3263 &nk->addr[pd->sidx], AF_INET))
3264 pf_change_a(&saddr->v4.s_addr,
3266 nk->addr[pd->sidx].v4.s_addr, 0);
3269 &nk->addr[pd->didx], AF_INET))
3270 pf_change_a(&daddr->v4.s_addr,
3272 nk->addr[pd->didx].v4.s_addr, 0);
3278 &nk->addr[pd->sidx], AF_INET6))
3279 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3282 &nk->addr[pd->didx], AF_INET6))
3283 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3296 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3297 r = r->skip[PF_SKIP_IFP].ptr;
3298 else if (r->direction && r->direction != direction)
3299 r = r->skip[PF_SKIP_DIR].ptr;
3300 else if (r->af && r->af != af)
3301 r = r->skip[PF_SKIP_AF].ptr;
3302 else if (r->proto && r->proto != pd->proto)
3303 r = r->skip[PF_SKIP_PROTO].ptr;
3304 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3305 r->src.neg, kif, M_GETFIB(m)))
3306 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3307 /* tcp/udp only. port_op always 0 in other cases */
3308 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3309 r->src.port[0], r->src.port[1], sport))
3310 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3311 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3312 r->dst.neg, NULL, M_GETFIB(m)))
3313 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3314 /* tcp/udp only. port_op always 0 in other cases */
3315 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3316 r->dst.port[0], r->dst.port[1], dport))
3317 r = r->skip[PF_SKIP_DST_PORT].ptr;
3318 /* icmp only. type always 0 in other cases */
3319 else if (r->type && r->type != icmptype + 1)
3320 r = TAILQ_NEXT(r, entries);
3321 /* icmp only. type always 0 in other cases */
3322 else if (r->code && r->code != icmpcode + 1)
3323 r = TAILQ_NEXT(r, entries);
3324 else if (r->tos && !(r->tos == pd->tos))
3325 r = TAILQ_NEXT(r, entries);
3326 else if (r->rule_flag & PFRULE_FRAGMENT)
3327 r = TAILQ_NEXT(r, entries);
3328 else if (pd->proto == IPPROTO_TCP &&
3329 (r->flagset & th->th_flags) != r->flags)
3330 r = TAILQ_NEXT(r, entries);
3331 /* tcp/udp only. uid.op always 0 in other cases */
3332 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3333 pf_socket_lookup(direction, pd, m), 1)) &&
3334 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3336 r = TAILQ_NEXT(r, entries);
3337 /* tcp/udp only. gid.op always 0 in other cases */
3338 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3339 pf_socket_lookup(direction, pd, m), 1)) &&
3340 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3342 r = TAILQ_NEXT(r, entries);
3344 r->prob <= arc4random())
3345 r = TAILQ_NEXT(r, entries);
3346 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3347 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3348 r = TAILQ_NEXT(r, entries);
3349 else if (r->os_fingerprint != PF_OSFP_ANY &&
3350 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3351 pf_osfp_fingerprint(pd, m, off, th),
3352 r->os_fingerprint)))
3353 r = TAILQ_NEXT(r, entries);
3357 if (r->rtableid >= 0)
3358 rtableid = r->rtableid;
3359 if (r->anchor == NULL) {
3366 r = TAILQ_NEXT(r, entries);
3368 pf_step_into_anchor(anchor_stack, &asd,
3369 &ruleset, PF_RULESET_FILTER, &r, &a,
3372 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3373 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3380 REASON_SET(&reason, PFRES_MATCH);
3382 if (r->log || (nr != NULL && nr->log)) {
3384 m_copyback(m, off, hdrlen, pd->hdr.any);
3385 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3389 if ((r->action == PF_DROP) &&
3390 ((r->rule_flag & PFRULE_RETURNRST) ||
3391 (r->rule_flag & PFRULE_RETURNICMP) ||
3392 (r->rule_flag & PFRULE_RETURN))) {
3393 /* undo NAT changes, if they have taken place */
3395 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3396 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3398 *pd->sport = sk->port[pd->sidx];
3400 *pd->dport = sk->port[pd->didx];
3402 *pd->proto_sum = bproto_sum;
3404 *pd->ip_sum = bip_sum;
3405 m_copyback(m, off, hdrlen, pd->hdr.any);
3407 if (pd->proto == IPPROTO_TCP &&
3408 ((r->rule_flag & PFRULE_RETURNRST) ||
3409 (r->rule_flag & PFRULE_RETURN)) &&
3410 !(th->th_flags & TH_RST)) {
3411 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3423 h4 = mtod(m, struct ip *);
3424 len = ntohs(h4->ip_len) - off;
3429 h6 = mtod(m, struct ip6_hdr *);
3430 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3435 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3436 REASON_SET(&reason, PFRES_PROTCKSUM);
3438 if (th->th_flags & TH_SYN)
3440 if (th->th_flags & TH_FIN)
3442 pf_send_tcp(m, r, af, pd->dst,
3443 pd->src, th->th_dport, th->th_sport,
3444 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3445 r->return_ttl, 1, 0, kif->pfik_ifp);
3447 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3449 pf_send_icmp(m, r->return_icmp >> 8,
3450 r->return_icmp & 255, af, r);
3451 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3453 pf_send_icmp(m, r->return_icmp6 >> 8,
3454 r->return_icmp6 & 255, af, r);
3457 if (r->action == PF_DROP)
3460 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3461 REASON_SET(&reason, PFRES_MEMORY);
3465 M_SETFIB(m, rtableid);
3467 if (!state_icmp && (r->keep_state || nr != NULL ||
3468 (pd->flags & PFDESC_TCP_NORM))) {
3470 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3471 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3473 if (action != PF_PASS)
3477 uma_zfree(V_pf_state_key_z, sk);
3479 uma_zfree(V_pf_state_key_z, nk);
3482 /* copy back packet headers if we performed NAT operations */
3484 m_copyback(m, off, hdrlen, pd->hdr.any);
3486 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3487 direction == PF_OUT &&
3488 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3490 * We want the state created, but we dont
3491 * want to send this in case a partner
3492 * firewall has to know about it to allow
3493 * replies through it.
3501 uma_zfree(V_pf_state_key_z, sk);
3503 uma_zfree(V_pf_state_key_z, nk);
3508 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3509 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3510 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3511 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3512 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3514 struct pf_state *s = NULL;
3515 struct pf_src_node *sn = NULL;
3516 struct tcphdr *th = pd->hdr.tcp;
3517 u_int16_t mss = V_tcp_mssdflt;
3520 /* check maximums */
3521 if (r->max_states &&
3522 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3523 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3524 REASON_SET(&reason, PFRES_MAXSTATES);
3527 /* src node for filter rule */
3528 if ((r->rule_flag & PFRULE_SRCTRACK ||
3529 r->rpool.opts & PF_POOL_STICKYADDR) &&
3530 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3531 REASON_SET(&reason, PFRES_SRCLIMIT);
3534 /* src node for translation rule */
3535 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3536 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3537 REASON_SET(&reason, PFRES_SRCLIMIT);
3540 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3542 REASON_SET(&reason, PFRES_MEMORY);
3546 s->nat_rule.ptr = nr;
3548 STATE_INC_COUNTERS(s);
3550 s->state_flags |= PFSTATE_ALLOWOPTS;
3551 if (r->rule_flag & PFRULE_STATESLOPPY)
3552 s->state_flags |= PFSTATE_SLOPPY;
3553 s->log = r->log & PF_LOG_ALL;
3554 s->sync_state = PFSYNC_S_NONE;
3556 s->log |= nr->log & PF_LOG_ALL;
3557 switch (pd->proto) {
3559 s->src.seqlo = ntohl(th->th_seq);
3560 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3561 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3562 r->keep_state == PF_STATE_MODULATE) {
3563 /* Generate sequence number modulator */
3564 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3567 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3568 htonl(s->src.seqlo + s->src.seqdiff), 0);
3572 if (th->th_flags & TH_SYN) {
3574 s->src.wscale = pf_get_wscale(m, off,
3575 th->th_off, pd->af);
3577 s->src.max_win = MAX(ntohs(th->th_win), 1);
3578 if (s->src.wscale & PF_WSCALE_MASK) {
3579 /* Remove scale factor from initial window */
3580 int win = s->src.max_win;
3581 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3582 s->src.max_win = (win - 1) >>
3583 (s->src.wscale & PF_WSCALE_MASK);
3585 if (th->th_flags & TH_FIN)
3589 s->src.state = TCPS_SYN_SENT;
3590 s->dst.state = TCPS_CLOSED;
3591 s->timeout = PFTM_TCP_FIRST_PACKET;
3594 s->src.state = PFUDPS_SINGLE;
3595 s->dst.state = PFUDPS_NO_TRAFFIC;
3596 s->timeout = PFTM_UDP_FIRST_PACKET;
3600 case IPPROTO_ICMPV6:
3602 s->timeout = PFTM_ICMP_FIRST_PACKET;
3605 s->src.state = PFOTHERS_SINGLE;
3606 s->dst.state = PFOTHERS_NO_TRAFFIC;
3607 s->timeout = PFTM_OTHER_FIRST_PACKET;
3610 if (r->rt && r->rt != PF_FASTROUTE) {
3611 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3612 REASON_SET(&reason, PFRES_BADSTATE);
3613 pf_src_tree_remove_state(s);
3614 STATE_DEC_COUNTERS(s);
3615 uma_zfree(V_pf_state_z, s);
3618 s->rt_kif = r->rpool.cur->kif;
3621 s->creation = time_uptime;
3622 s->expire = time_uptime;
3627 /* XXX We only modify one side for now. */
3628 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3629 s->nat_src_node = nsn;
3631 if (pd->proto == IPPROTO_TCP) {
3632 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3633 off, pd, th, &s->src, &s->dst)) {
3634 REASON_SET(&reason, PFRES_MEMORY);
3635 pf_src_tree_remove_state(s);
3636 STATE_DEC_COUNTERS(s);
3637 uma_zfree(V_pf_state_z, s);
3640 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3641 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3642 &s->src, &s->dst, rewrite)) {
3643 /* This really shouldn't happen!!! */
3644 DPFPRINTF(PF_DEBUG_URGENT,
3645 ("pf_normalize_tcp_stateful failed on first pkt"));
3646 pf_normalize_tcp_cleanup(s);
3647 pf_src_tree_remove_state(s);
3648 STATE_DEC_COUNTERS(s);
3649 uma_zfree(V_pf_state_z, s);
3653 s->direction = pd->dir;
3656 * sk/nk could already been setup by pf_get_translation().
3659 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3660 __func__, nr, sk, nk));
3661 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3666 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3667 __func__, nr, sk, nk));
3669 /* Swap sk/nk for PF_OUT. */
3670 if (pf_state_insert(BOUND_IFACE(r, kif),
3671 (pd->dir == PF_IN) ? sk : nk,
3672 (pd->dir == PF_IN) ? nk : sk, s)) {
3673 if (pd->proto == IPPROTO_TCP)
3674 pf_normalize_tcp_cleanup(s);
3675 REASON_SET(&reason, PFRES_STATEINS);
3676 pf_src_tree_remove_state(s);
3677 STATE_DEC_COUNTERS(s);
3678 uma_zfree(V_pf_state_z, s);
3685 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3686 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3687 s->src.state = PF_TCPS_PROXY_SRC;
3688 /* undo NAT changes, if they have taken place */
3690 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3691 if (pd->dir == PF_OUT)
3692 skt = s->key[PF_SK_STACK];
3693 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3694 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3696 *pd->sport = skt->port[pd->sidx];
3698 *pd->dport = skt->port[pd->didx];
3700 *pd->proto_sum = bproto_sum;
3702 *pd->ip_sum = bip_sum;
3703 m_copyback(m, off, hdrlen, pd->hdr.any);
3705 s->src.seqhi = htonl(arc4random());
3706 /* Find mss option */
3707 int rtid = M_GETFIB(m);
3708 mss = pf_get_mss(m, off, th->th_off, pd->af);
3709 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3710 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3712 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3713 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3714 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3715 REASON_SET(&reason, PFRES_SYNPROXY);
3716 return (PF_SYNPROXY_DROP);
3723 uma_zfree(V_pf_state_key_z, sk);
3725 uma_zfree(V_pf_state_key_z, nk);
3728 struct pf_srchash *sh;
3730 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3731 PF_HASHROW_LOCK(sh);
3732 if (--sn->states == 0 && sn->expire == 0) {
3733 pf_unlink_src_node(sn);
3734 uma_zfree(V_pf_sources_z, sn);
3736 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3738 PF_HASHROW_UNLOCK(sh);
3741 if (nsn != sn && nsn != NULL) {
3742 struct pf_srchash *sh;
3744 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3745 PF_HASHROW_LOCK(sh);
3746 if (--nsn->states == 0 && nsn->expire == 0) {
3747 pf_unlink_src_node(nsn);
3748 uma_zfree(V_pf_sources_z, nsn);
3750 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3752 PF_HASHROW_UNLOCK(sh);
3759 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3760 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3761 struct pf_ruleset **rsm)
3763 struct pf_rule *r, *a = NULL;
3764 struct pf_ruleset *ruleset = NULL;
3765 sa_family_t af = pd->af;
3770 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3774 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3777 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3778 r = r->skip[PF_SKIP_IFP].ptr;
3779 else if (r->direction && r->direction != direction)
3780 r = r->skip[PF_SKIP_DIR].ptr;
3781 else if (r->af && r->af != af)
3782 r = r->skip[PF_SKIP_AF].ptr;
3783 else if (r->proto && r->proto != pd->proto)
3784 r = r->skip[PF_SKIP_PROTO].ptr;
3785 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3786 r->src.neg, kif, M_GETFIB(m)))
3787 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3788 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3789 r->dst.neg, NULL, M_GETFIB(m)))
3790 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3791 else if (r->tos && !(r->tos == pd->tos))
3792 r = TAILQ_NEXT(r, entries);
3793 else if (r->os_fingerprint != PF_OSFP_ANY)
3794 r = TAILQ_NEXT(r, entries);
3795 else if (pd->proto == IPPROTO_UDP &&
3796 (r->src.port_op || r->dst.port_op))
3797 r = TAILQ_NEXT(r, entries);
3798 else if (pd->proto == IPPROTO_TCP &&
3799 (r->src.port_op || r->dst.port_op || r->flagset))
3800 r = TAILQ_NEXT(r, entries);
3801 else if ((pd->proto == IPPROTO_ICMP ||
3802 pd->proto == IPPROTO_ICMPV6) &&
3803 (r->type || r->code))
3804 r = TAILQ_NEXT(r, entries);
3805 else if (r->prob && r->prob <=
3806 (arc4random() % (UINT_MAX - 1) + 1))
3807 r = TAILQ_NEXT(r, entries);
3808 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3809 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3810 r = TAILQ_NEXT(r, entries);
3812 if (r->anchor == NULL) {
3819 r = TAILQ_NEXT(r, entries);
3821 pf_step_into_anchor(anchor_stack, &asd,
3822 &ruleset, PF_RULESET_FILTER, &r, &a,
3825 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3826 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3833 REASON_SET(&reason, PFRES_MATCH);
3836 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3839 if (r->action != PF_PASS)
3842 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3843 REASON_SET(&reason, PFRES_MEMORY);
3851 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3852 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3853 struct pf_pdesc *pd, u_short *reason, int *copyback)
3855 struct tcphdr *th = pd->hdr.tcp;
3856 u_int16_t win = ntohs(th->th_win);
3857 u_int32_t ack, end, seq, orig_seq;
3861 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3862 sws = src->wscale & PF_WSCALE_MASK;
3863 dws = dst->wscale & PF_WSCALE_MASK;
3868 * Sequence tracking algorithm from Guido van Rooij's paper:
3869 * http://www.madison-gurkha.com/publications/tcp_filtering/
3873 orig_seq = seq = ntohl(th->th_seq);
3874 if (src->seqlo == 0) {
3875 /* First packet from this end. Set its state */
3877 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3878 src->scrub == NULL) {
3879 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3880 REASON_SET(reason, PFRES_MEMORY);
3885 /* Deferred generation of sequence number modulator */
3886 if (dst->seqdiff && !src->seqdiff) {
3887 /* use random iss for the TCP server */
3888 while ((src->seqdiff = arc4random() - seq) == 0)
3890 ack = ntohl(th->th_ack) - dst->seqdiff;
3891 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3893 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3896 ack = ntohl(th->th_ack);
3899 end = seq + pd->p_len;
3900 if (th->th_flags & TH_SYN) {
3902 if (dst->wscale & PF_WSCALE_FLAG) {
3903 src->wscale = pf_get_wscale(m, off, th->th_off,
3905 if (src->wscale & PF_WSCALE_FLAG) {
3906 /* Remove scale factor from initial
3908 sws = src->wscale & PF_WSCALE_MASK;
3909 win = ((u_int32_t)win + (1 << sws) - 1)
3911 dws = dst->wscale & PF_WSCALE_MASK;
3913 /* fixup other window */
3914 dst->max_win <<= dst->wscale &
3916 /* in case of a retrans SYN|ACK */
3921 if (th->th_flags & TH_FIN)
3925 if (src->state < TCPS_SYN_SENT)
3926 src->state = TCPS_SYN_SENT;
3929 * May need to slide the window (seqhi may have been set by
3930 * the crappy stack check or if we picked up the connection
3931 * after establishment)
3933 if (src->seqhi == 1 ||
3934 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3935 src->seqhi = end + MAX(1, dst->max_win << dws);
3936 if (win > src->max_win)
3940 ack = ntohl(th->th_ack) - dst->seqdiff;
3942 /* Modulate sequence numbers */
3943 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3945 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3948 end = seq + pd->p_len;
3949 if (th->th_flags & TH_SYN)
3951 if (th->th_flags & TH_FIN)
3955 if ((th->th_flags & TH_ACK) == 0) {
3956 /* Let it pass through the ack skew check */
3958 } else if ((ack == 0 &&
3959 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3960 /* broken tcp stacks do not set ack */
3961 (dst->state < TCPS_SYN_SENT)) {
3963 * Many stacks (ours included) will set the ACK number in an
3964 * FIN|ACK if the SYN times out -- no sequence to ACK.
3970 /* Ease sequencing restrictions on no data packets */
3975 ackskew = dst->seqlo - ack;
3979 * Need to demodulate the sequence numbers in any TCP SACK options
3980 * (Selective ACK). We could optionally validate the SACK values
3981 * against the current ACK window, either forwards or backwards, but
3982 * I'm not confident that SACK has been implemented properly
3983 * everywhere. It wouldn't surprise me if several stacks accidently
3984 * SACK too far backwards of previously ACKed data. There really aren't
3985 * any security implications of bad SACKing unless the target stack
3986 * doesn't validate the option length correctly. Someone trying to
3987 * spoof into a TCP connection won't bother blindly sending SACK
3990 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3991 if (pf_modulate_sack(m, off, pd, th, dst))
3996 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
3997 if (SEQ_GEQ(src->seqhi, end) &&
3998 /* Last octet inside other's window space */
3999 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4000 /* Retrans: not more than one window back */
4001 (ackskew >= -MAXACKWINDOW) &&
4002 /* Acking not more than one reassembled fragment backwards */
4003 (ackskew <= (MAXACKWINDOW << sws)) &&
4004 /* Acking not more than one window forward */
4005 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4006 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4007 (pd->flags & PFDESC_IP_REAS) == 0)) {
4008 /* Require an exact/+1 sequence match on resets when possible */
4010 if (dst->scrub || src->scrub) {
4011 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4012 *state, src, dst, copyback))
4016 /* update max window */
4017 if (src->max_win < win)
4019 /* synchronize sequencing */
4020 if (SEQ_GT(end, src->seqlo))
4022 /* slide the window of what the other end can send */
4023 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4024 dst->seqhi = ack + MAX((win << sws), 1);
4028 if (th->th_flags & TH_SYN)
4029 if (src->state < TCPS_SYN_SENT)
4030 src->state = TCPS_SYN_SENT;
4031 if (th->th_flags & TH_FIN)
4032 if (src->state < TCPS_CLOSING)
4033 src->state = TCPS_CLOSING;
4034 if (th->th_flags & TH_ACK) {
4035 if (dst->state == TCPS_SYN_SENT) {
4036 dst->state = TCPS_ESTABLISHED;
4037 if (src->state == TCPS_ESTABLISHED &&
4038 (*state)->src_node != NULL &&
4039 pf_src_connlimit(state)) {
4040 REASON_SET(reason, PFRES_SRCLIMIT);
4043 } else if (dst->state == TCPS_CLOSING)
4044 dst->state = TCPS_FIN_WAIT_2;
4046 if (th->th_flags & TH_RST)
4047 src->state = dst->state = TCPS_TIME_WAIT;
4049 /* update expire time */
4050 (*state)->expire = time_uptime;
4051 if (src->state >= TCPS_FIN_WAIT_2 &&
4052 dst->state >= TCPS_FIN_WAIT_2)
4053 (*state)->timeout = PFTM_TCP_CLOSED;
4054 else if (src->state >= TCPS_CLOSING &&
4055 dst->state >= TCPS_CLOSING)
4056 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4057 else if (src->state < TCPS_ESTABLISHED ||
4058 dst->state < TCPS_ESTABLISHED)
4059 (*state)->timeout = PFTM_TCP_OPENING;
4060 else if (src->state >= TCPS_CLOSING ||
4061 dst->state >= TCPS_CLOSING)
4062 (*state)->timeout = PFTM_TCP_CLOSING;
4064 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4066 /* Fall through to PASS packet */
4068 } else if ((dst->state < TCPS_SYN_SENT ||
4069 dst->state >= TCPS_FIN_WAIT_2 ||
4070 src->state >= TCPS_FIN_WAIT_2) &&
4071 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4072 /* Within a window forward of the originating packet */
4073 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4074 /* Within a window backward of the originating packet */
4077 * This currently handles three situations:
4078 * 1) Stupid stacks will shotgun SYNs before their peer
4080 * 2) When PF catches an already established stream (the
4081 * firewall rebooted, the state table was flushed, routes
4083 * 3) Packets get funky immediately after the connection
4084 * closes (this should catch Solaris spurious ACK|FINs
4085 * that web servers like to spew after a close)
4087 * This must be a little more careful than the above code
4088 * since packet floods will also be caught here. We don't
4089 * update the TTL here to mitigate the damage of a packet
4090 * flood and so the same code can handle awkward establishment
4091 * and a loosened connection close.
4092 * In the establishment case, a correct peer response will
4093 * validate the connection, go through the normal state code
4094 * and keep updating the state TTL.
4097 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4098 printf("pf: loose state match: ");
4099 pf_print_state(*state);
4100 pf_print_flags(th->th_flags);
4101 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4102 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4103 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4104 (unsigned long long)(*state)->packets[1],
4105 pd->dir == PF_IN ? "in" : "out",
4106 pd->dir == (*state)->direction ? "fwd" : "rev");
4109 if (dst->scrub || src->scrub) {
4110 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4111 *state, src, dst, copyback))
4115 /* update max window */
4116 if (src->max_win < win)
4118 /* synchronize sequencing */
4119 if (SEQ_GT(end, src->seqlo))
4121 /* slide the window of what the other end can send */
4122 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4123 dst->seqhi = ack + MAX((win << sws), 1);
4126 * Cannot set dst->seqhi here since this could be a shotgunned
4127 * SYN and not an already established connection.
4130 if (th->th_flags & TH_FIN)
4131 if (src->state < TCPS_CLOSING)
4132 src->state = TCPS_CLOSING;
4133 if (th->th_flags & TH_RST)
4134 src->state = dst->state = TCPS_TIME_WAIT;
4136 /* Fall through to PASS packet */
4139 if ((*state)->dst.state == TCPS_SYN_SENT &&
4140 (*state)->src.state == TCPS_SYN_SENT) {
4141 /* Send RST for state mismatches during handshake */
4142 if (!(th->th_flags & TH_RST))
4143 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4144 pd->dst, pd->src, th->th_dport,
4145 th->th_sport, ntohl(th->th_ack), 0,
4147 (*state)->rule.ptr->return_ttl, 1, 0,
4152 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4153 printf("pf: BAD state: ");
4154 pf_print_state(*state);
4155 pf_print_flags(th->th_flags);
4156 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4157 "pkts=%llu:%llu dir=%s,%s\n",
4158 seq, orig_seq, ack, pd->p_len, ackskew,
4159 (unsigned long long)(*state)->packets[0],
4160 (unsigned long long)(*state)->packets[1],
4161 pd->dir == PF_IN ? "in" : "out",
4162 pd->dir == (*state)->direction ? "fwd" : "rev");
4163 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4164 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4165 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4167 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4168 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4169 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4170 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4172 REASON_SET(reason, PFRES_BADSTATE);
4180 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4181 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4183 struct tcphdr *th = pd->hdr.tcp;
4185 if (th->th_flags & TH_SYN)
4186 if (src->state < TCPS_SYN_SENT)
4187 src->state = TCPS_SYN_SENT;
4188 if (th->th_flags & TH_FIN)
4189 if (src->state < TCPS_CLOSING)
4190 src->state = TCPS_CLOSING;
4191 if (th->th_flags & TH_ACK) {
4192 if (dst->state == TCPS_SYN_SENT) {
4193 dst->state = TCPS_ESTABLISHED;
4194 if (src->state == TCPS_ESTABLISHED &&
4195 (*state)->src_node != NULL &&
4196 pf_src_connlimit(state)) {
4197 REASON_SET(reason, PFRES_SRCLIMIT);
4200 } else if (dst->state == TCPS_CLOSING) {
4201 dst->state = TCPS_FIN_WAIT_2;
4202 } else if (src->state == TCPS_SYN_SENT &&
4203 dst->state < TCPS_SYN_SENT) {
4205 * Handle a special sloppy case where we only see one
4206 * half of the connection. If there is a ACK after
4207 * the initial SYN without ever seeing a packet from
4208 * the destination, set the connection to established.
4210 dst->state = src->state = TCPS_ESTABLISHED;
4211 if ((*state)->src_node != NULL &&
4212 pf_src_connlimit(state)) {
4213 REASON_SET(reason, PFRES_SRCLIMIT);
4216 } else if (src->state == TCPS_CLOSING &&
4217 dst->state == TCPS_ESTABLISHED &&
4220 * Handle the closing of half connections where we
4221 * don't see the full bidirectional FIN/ACK+ACK
4224 dst->state = TCPS_CLOSING;
4227 if (th->th_flags & TH_RST)
4228 src->state = dst->state = TCPS_TIME_WAIT;
4230 /* update expire time */
4231 (*state)->expire = time_uptime;
4232 if (src->state >= TCPS_FIN_WAIT_2 &&
4233 dst->state >= TCPS_FIN_WAIT_2)
4234 (*state)->timeout = PFTM_TCP_CLOSED;
4235 else if (src->state >= TCPS_CLOSING &&
4236 dst->state >= TCPS_CLOSING)
4237 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4238 else if (src->state < TCPS_ESTABLISHED ||
4239 dst->state < TCPS_ESTABLISHED)
4240 (*state)->timeout = PFTM_TCP_OPENING;
4241 else if (src->state >= TCPS_CLOSING ||
4242 dst->state >= TCPS_CLOSING)
4243 (*state)->timeout = PFTM_TCP_CLOSING;
4245 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4251 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4252 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4255 struct pf_state_key_cmp key;
4256 struct tcphdr *th = pd->hdr.tcp;
4258 struct pf_state_peer *src, *dst;
4259 struct pf_state_key *sk;
4261 bzero(&key, sizeof(key));
4263 key.proto = IPPROTO_TCP;
4264 if (direction == PF_IN) { /* wire side, straight */
4265 PF_ACPY(&key.addr[0], pd->src, key.af);
4266 PF_ACPY(&key.addr[1], pd->dst, key.af);
4267 key.port[0] = th->th_sport;
4268 key.port[1] = th->th_dport;
4269 } else { /* stack side, reverse */
4270 PF_ACPY(&key.addr[1], pd->src, key.af);
4271 PF_ACPY(&key.addr[0], pd->dst, key.af);
4272 key.port[1] = th->th_sport;
4273 key.port[0] = th->th_dport;
4276 STATE_LOOKUP(kif, &key, direction, *state, pd);
4278 if (direction == (*state)->direction) {
4279 src = &(*state)->src;
4280 dst = &(*state)->dst;
4282 src = &(*state)->dst;
4283 dst = &(*state)->src;
4286 sk = (*state)->key[pd->didx];
4288 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4289 if (direction != (*state)->direction) {
4290 REASON_SET(reason, PFRES_SYNPROXY);
4291 return (PF_SYNPROXY_DROP);
4293 if (th->th_flags & TH_SYN) {
4294 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4295 REASON_SET(reason, PFRES_SYNPROXY);
4298 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4299 pd->src, th->th_dport, th->th_sport,
4300 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4301 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4302 REASON_SET(reason, PFRES_SYNPROXY);
4303 return (PF_SYNPROXY_DROP);
4304 } else if (!(th->th_flags & TH_ACK) ||
4305 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4306 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4307 REASON_SET(reason, PFRES_SYNPROXY);
4309 } else if ((*state)->src_node != NULL &&
4310 pf_src_connlimit(state)) {
4311 REASON_SET(reason, PFRES_SRCLIMIT);
4314 (*state)->src.state = PF_TCPS_PROXY_DST;
4316 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4317 if (direction == (*state)->direction) {
4318 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4319 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4320 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4321 REASON_SET(reason, PFRES_SYNPROXY);
4324 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4325 if ((*state)->dst.seqhi == 1)
4326 (*state)->dst.seqhi = htonl(arc4random());
4327 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4328 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4329 sk->port[pd->sidx], sk->port[pd->didx],
4330 (*state)->dst.seqhi, 0, TH_SYN, 0,
4331 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4332 REASON_SET(reason, PFRES_SYNPROXY);
4333 return (PF_SYNPROXY_DROP);
4334 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4336 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4337 REASON_SET(reason, PFRES_SYNPROXY);
4340 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4341 (*state)->dst.seqlo = ntohl(th->th_seq);
4342 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4343 pd->src, th->th_dport, th->th_sport,
4344 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4345 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4346 (*state)->tag, NULL);
4347 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4348 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4349 sk->port[pd->sidx], sk->port[pd->didx],
4350 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4351 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4352 (*state)->src.seqdiff = (*state)->dst.seqhi -
4353 (*state)->src.seqlo;
4354 (*state)->dst.seqdiff = (*state)->src.seqhi -
4355 (*state)->dst.seqlo;
4356 (*state)->src.seqhi = (*state)->src.seqlo +
4357 (*state)->dst.max_win;
4358 (*state)->dst.seqhi = (*state)->dst.seqlo +
4359 (*state)->src.max_win;
4360 (*state)->src.wscale = (*state)->dst.wscale = 0;
4361 (*state)->src.state = (*state)->dst.state =
4363 REASON_SET(reason, PFRES_SYNPROXY);
4364 return (PF_SYNPROXY_DROP);
4368 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4369 dst->state >= TCPS_FIN_WAIT_2 &&
4370 src->state >= TCPS_FIN_WAIT_2) {
4371 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4372 printf("pf: state reuse ");
4373 pf_print_state(*state);
4374 pf_print_flags(th->th_flags);
4377 /* XXX make sure it's the same direction ?? */
4378 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4379 pf_unlink_state(*state, PF_ENTER_LOCKED);
4384 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4385 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4388 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4389 ©back) == PF_DROP)
4393 /* translate source/destination address, if necessary */
4394 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4395 struct pf_state_key *nk = (*state)->key[pd->didx];
4397 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4398 nk->port[pd->sidx] != th->th_sport)
4399 pf_change_ap(m, pd->src, &th->th_sport,
4400 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4401 nk->port[pd->sidx], 0, pd->af);
4403 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4404 nk->port[pd->didx] != th->th_dport)
4405 pf_change_ap(m, pd->dst, &th->th_dport,
4406 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4407 nk->port[pd->didx], 0, pd->af);
4411 /* Copyback sequence modulation or stateful scrub changes if needed */
4413 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4419 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4420 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4422 struct pf_state_peer *src, *dst;
4423 struct pf_state_key_cmp key;
4424 struct udphdr *uh = pd->hdr.udp;
4426 bzero(&key, sizeof(key));
4428 key.proto = IPPROTO_UDP;
4429 if (direction == PF_IN) { /* wire side, straight */
4430 PF_ACPY(&key.addr[0], pd->src, key.af);
4431 PF_ACPY(&key.addr[1], pd->dst, key.af);
4432 key.port[0] = uh->uh_sport;
4433 key.port[1] = uh->uh_dport;
4434 } else { /* stack side, reverse */
4435 PF_ACPY(&key.addr[1], pd->src, key.af);
4436 PF_ACPY(&key.addr[0], pd->dst, key.af);
4437 key.port[1] = uh->uh_sport;
4438 key.port[0] = uh->uh_dport;
4441 STATE_LOOKUP(kif, &key, direction, *state, pd);
4443 if (direction == (*state)->direction) {
4444 src = &(*state)->src;
4445 dst = &(*state)->dst;
4447 src = &(*state)->dst;
4448 dst = &(*state)->src;
4452 if (src->state < PFUDPS_SINGLE)
4453 src->state = PFUDPS_SINGLE;
4454 if (dst->state == PFUDPS_SINGLE)
4455 dst->state = PFUDPS_MULTIPLE;
4457 /* update expire time */
4458 (*state)->expire = time_uptime;
4459 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4460 (*state)->timeout = PFTM_UDP_MULTIPLE;
4462 (*state)->timeout = PFTM_UDP_SINGLE;
4464 /* translate source/destination address, if necessary */
4465 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4466 struct pf_state_key *nk = (*state)->key[pd->didx];
4468 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4469 nk->port[pd->sidx] != uh->uh_sport)
4470 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4471 &uh->uh_sum, &nk->addr[pd->sidx],
4472 nk->port[pd->sidx], 1, pd->af);
4474 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4475 nk->port[pd->didx] != uh->uh_dport)
4476 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4477 &uh->uh_sum, &nk->addr[pd->didx],
4478 nk->port[pd->didx], 1, pd->af);
4479 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4486 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4487 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4489 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4490 u_int16_t icmpid = 0, *icmpsum;
4493 struct pf_state_key_cmp key;
4495 bzero(&key, sizeof(key));
4496 switch (pd->proto) {
4499 icmptype = pd->hdr.icmp->icmp_type;
4500 icmpid = pd->hdr.icmp->icmp_id;
4501 icmpsum = &pd->hdr.icmp->icmp_cksum;
4503 if (icmptype == ICMP_UNREACH ||
4504 icmptype == ICMP_SOURCEQUENCH ||
4505 icmptype == ICMP_REDIRECT ||
4506 icmptype == ICMP_TIMXCEED ||
4507 icmptype == ICMP_PARAMPROB)
4512 case IPPROTO_ICMPV6:
4513 icmptype = pd->hdr.icmp6->icmp6_type;
4514 icmpid = pd->hdr.icmp6->icmp6_id;
4515 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4517 if (icmptype == ICMP6_DST_UNREACH ||
4518 icmptype == ICMP6_PACKET_TOO_BIG ||
4519 icmptype == ICMP6_TIME_EXCEEDED ||
4520 icmptype == ICMP6_PARAM_PROB)
4529 * ICMP query/reply message not related to a TCP/UDP packet.
4530 * Search for an ICMP state.
4533 key.proto = pd->proto;
4534 key.port[0] = key.port[1] = icmpid;
4535 if (direction == PF_IN) { /* wire side, straight */
4536 PF_ACPY(&key.addr[0], pd->src, key.af);
4537 PF_ACPY(&key.addr[1], pd->dst, key.af);
4538 } else { /* stack side, reverse */
4539 PF_ACPY(&key.addr[1], pd->src, key.af);
4540 PF_ACPY(&key.addr[0], pd->dst, key.af);
4543 STATE_LOOKUP(kif, &key, direction, *state, pd);
4545 (*state)->expire = time_uptime;
4546 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4548 /* translate source/destination address, if necessary */
4549 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4550 struct pf_state_key *nk = (*state)->key[pd->didx];
4555 if (PF_ANEQ(pd->src,
4556 &nk->addr[pd->sidx], AF_INET))
4557 pf_change_a(&saddr->v4.s_addr,
4559 nk->addr[pd->sidx].v4.s_addr, 0);
4561 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4563 pf_change_a(&daddr->v4.s_addr,
4565 nk->addr[pd->didx].v4.s_addr, 0);
4568 pd->hdr.icmp->icmp_id) {
4569 pd->hdr.icmp->icmp_cksum =
4571 pd->hdr.icmp->icmp_cksum, icmpid,
4572 nk->port[pd->sidx], 0);
4573 pd->hdr.icmp->icmp_id =
4577 m_copyback(m, off, ICMP_MINLEN,
4578 (caddr_t )pd->hdr.icmp);
4583 if (PF_ANEQ(pd->src,
4584 &nk->addr[pd->sidx], AF_INET6))
4586 &pd->hdr.icmp6->icmp6_cksum,
4587 &nk->addr[pd->sidx], 0);
4589 if (PF_ANEQ(pd->dst,
4590 &nk->addr[pd->didx], AF_INET6))
4592 &pd->hdr.icmp6->icmp6_cksum,
4593 &nk->addr[pd->didx], 0);
4595 m_copyback(m, off, sizeof(struct icmp6_hdr),
4596 (caddr_t )pd->hdr.icmp6);
4605 * ICMP error message in response to a TCP/UDP packet.
4606 * Extract the inner TCP/UDP header and search for that state.
4609 struct pf_pdesc pd2;
4610 bzero(&pd2, sizeof pd2);
4615 struct ip6_hdr h2_6;
4622 /* Payload packet is from the opposite direction. */
4623 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4624 pd2.didx = (direction == PF_IN) ? 0 : 1;
4628 /* offset of h2 in mbuf chain */
4629 ipoff2 = off + ICMP_MINLEN;
4631 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4632 NULL, reason, pd2.af)) {
4633 DPFPRINTF(PF_DEBUG_MISC,
4634 ("pf: ICMP error message too short "
4639 * ICMP error messages don't refer to non-first
4642 if (h2.ip_off & htons(IP_OFFMASK)) {
4643 REASON_SET(reason, PFRES_FRAG);
4647 /* offset of protocol header that follows h2 */
4648 off2 = ipoff2 + (h2.ip_hl << 2);
4650 pd2.proto = h2.ip_p;
4651 pd2.src = (struct pf_addr *)&h2.ip_src;
4652 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4653 pd2.ip_sum = &h2.ip_sum;
4658 ipoff2 = off + sizeof(struct icmp6_hdr);
4660 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4661 NULL, reason, pd2.af)) {
4662 DPFPRINTF(PF_DEBUG_MISC,
4663 ("pf: ICMP error message too short "
4667 pd2.proto = h2_6.ip6_nxt;
4668 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4669 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4671 off2 = ipoff2 + sizeof(h2_6);
4673 switch (pd2.proto) {
4674 case IPPROTO_FRAGMENT:
4676 * ICMPv6 error messages for
4677 * non-first fragments
4679 REASON_SET(reason, PFRES_FRAG);
4682 case IPPROTO_HOPOPTS:
4683 case IPPROTO_ROUTING:
4684 case IPPROTO_DSTOPTS: {
4685 /* get next header and header length */
4686 struct ip6_ext opt6;
4688 if (!pf_pull_hdr(m, off2, &opt6,
4689 sizeof(opt6), NULL, reason,
4691 DPFPRINTF(PF_DEBUG_MISC,
4692 ("pf: ICMPv6 short opt\n"));
4695 if (pd2.proto == IPPROTO_AH)
4696 off2 += (opt6.ip6e_len + 2) * 4;
4698 off2 += (opt6.ip6e_len + 1) * 8;
4699 pd2.proto = opt6.ip6e_nxt;
4700 /* goto the next header */
4707 } while (!terminal);
4712 switch (pd2.proto) {
4716 struct pf_state_peer *src, *dst;
4721 * Only the first 8 bytes of the TCP header can be
4722 * expected. Don't access any TCP header fields after
4723 * th_seq, an ackskew test is not possible.
4725 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4727 DPFPRINTF(PF_DEBUG_MISC,
4728 ("pf: ICMP error message too short "
4734 key.proto = IPPROTO_TCP;
4735 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4736 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4737 key.port[pd2.sidx] = th.th_sport;
4738 key.port[pd2.didx] = th.th_dport;
4740 STATE_LOOKUP(kif, &key, direction, *state, pd);
4742 if (direction == (*state)->direction) {
4743 src = &(*state)->dst;
4744 dst = &(*state)->src;
4746 src = &(*state)->src;
4747 dst = &(*state)->dst;
4750 if (src->wscale && dst->wscale)
4751 dws = dst->wscale & PF_WSCALE_MASK;
4755 /* Demodulate sequence number */
4756 seq = ntohl(th.th_seq) - src->seqdiff;
4758 pf_change_a(&th.th_seq, icmpsum,
4763 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4764 (!SEQ_GEQ(src->seqhi, seq) ||
4765 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4766 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4767 printf("pf: BAD ICMP %d:%d ",
4768 icmptype, pd->hdr.icmp->icmp_code);
4769 pf_print_host(pd->src, 0, pd->af);
4771 pf_print_host(pd->dst, 0, pd->af);
4773 pf_print_state(*state);
4774 printf(" seq=%u\n", seq);
4776 REASON_SET(reason, PFRES_BADSTATE);
4779 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4780 printf("pf: OK ICMP %d:%d ",
4781 icmptype, pd->hdr.icmp->icmp_code);
4782 pf_print_host(pd->src, 0, pd->af);
4784 pf_print_host(pd->dst, 0, pd->af);
4786 pf_print_state(*state);
4787 printf(" seq=%u\n", seq);
4791 /* translate source/destination address, if necessary */
4792 if ((*state)->key[PF_SK_WIRE] !=
4793 (*state)->key[PF_SK_STACK]) {
4794 struct pf_state_key *nk =
4795 (*state)->key[pd->didx];
4797 if (PF_ANEQ(pd2.src,
4798 &nk->addr[pd2.sidx], pd2.af) ||
4799 nk->port[pd2.sidx] != th.th_sport)
4800 pf_change_icmp(pd2.src, &th.th_sport,
4801 daddr, &nk->addr[pd2.sidx],
4802 nk->port[pd2.sidx], NULL,
4803 pd2.ip_sum, icmpsum,
4804 pd->ip_sum, 0, pd2.af);
4806 if (PF_ANEQ(pd2.dst,
4807 &nk->addr[pd2.didx], pd2.af) ||
4808 nk->port[pd2.didx] != th.th_dport)
4809 pf_change_icmp(pd2.dst, &th.th_dport,
4810 saddr, &nk->addr[pd2.didx],
4811 nk->port[pd2.didx], NULL,
4812 pd2.ip_sum, icmpsum,
4813 pd->ip_sum, 0, pd2.af);
4821 m_copyback(m, off, ICMP_MINLEN,
4822 (caddr_t )pd->hdr.icmp);
4823 m_copyback(m, ipoff2, sizeof(h2),
4830 sizeof(struct icmp6_hdr),
4831 (caddr_t )pd->hdr.icmp6);
4832 m_copyback(m, ipoff2, sizeof(h2_6),
4837 m_copyback(m, off2, 8, (caddr_t)&th);
4846 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4847 NULL, reason, pd2.af)) {
4848 DPFPRINTF(PF_DEBUG_MISC,
4849 ("pf: ICMP error message too short "
4855 key.proto = IPPROTO_UDP;
4856 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4857 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4858 key.port[pd2.sidx] = uh.uh_sport;
4859 key.port[pd2.didx] = uh.uh_dport;
4861 STATE_LOOKUP(kif, &key, direction, *state, pd);
4863 /* translate source/destination address, if necessary */
4864 if ((*state)->key[PF_SK_WIRE] !=
4865 (*state)->key[PF_SK_STACK]) {
4866 struct pf_state_key *nk =
4867 (*state)->key[pd->didx];
4869 if (PF_ANEQ(pd2.src,
4870 &nk->addr[pd2.sidx], pd2.af) ||
4871 nk->port[pd2.sidx] != uh.uh_sport)
4872 pf_change_icmp(pd2.src, &uh.uh_sport,
4873 daddr, &nk->addr[pd2.sidx],
4874 nk->port[pd2.sidx], &uh.uh_sum,
4875 pd2.ip_sum, icmpsum,
4876 pd->ip_sum, 1, pd2.af);
4878 if (PF_ANEQ(pd2.dst,
4879 &nk->addr[pd2.didx], pd2.af) ||
4880 nk->port[pd2.didx] != uh.uh_dport)
4881 pf_change_icmp(pd2.dst, &uh.uh_dport,
4882 saddr, &nk->addr[pd2.didx],
4883 nk->port[pd2.didx], &uh.uh_sum,
4884 pd2.ip_sum, icmpsum,
4885 pd->ip_sum, 1, pd2.af);
4890 m_copyback(m, off, ICMP_MINLEN,
4891 (caddr_t )pd->hdr.icmp);
4892 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4898 sizeof(struct icmp6_hdr),
4899 (caddr_t )pd->hdr.icmp6);
4900 m_copyback(m, ipoff2, sizeof(h2_6),
4905 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4911 case IPPROTO_ICMP: {
4914 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4915 NULL, reason, pd2.af)) {
4916 DPFPRINTF(PF_DEBUG_MISC,
4917 ("pf: ICMP error message too short i"
4923 key.proto = IPPROTO_ICMP;
4924 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4925 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4926 key.port[0] = key.port[1] = iih.icmp_id;
4928 STATE_LOOKUP(kif, &key, direction, *state, pd);
4930 /* translate source/destination address, if necessary */
4931 if ((*state)->key[PF_SK_WIRE] !=
4932 (*state)->key[PF_SK_STACK]) {
4933 struct pf_state_key *nk =
4934 (*state)->key[pd->didx];
4936 if (PF_ANEQ(pd2.src,
4937 &nk->addr[pd2.sidx], pd2.af) ||
4938 nk->port[pd2.sidx] != iih.icmp_id)
4939 pf_change_icmp(pd2.src, &iih.icmp_id,
4940 daddr, &nk->addr[pd2.sidx],
4941 nk->port[pd2.sidx], NULL,
4942 pd2.ip_sum, icmpsum,
4943 pd->ip_sum, 0, AF_INET);
4945 if (PF_ANEQ(pd2.dst,
4946 &nk->addr[pd2.didx], pd2.af) ||
4947 nk->port[pd2.didx] != iih.icmp_id)
4948 pf_change_icmp(pd2.dst, &iih.icmp_id,
4949 saddr, &nk->addr[pd2.didx],
4950 nk->port[pd2.didx], NULL,
4951 pd2.ip_sum, icmpsum,
4952 pd->ip_sum, 0, AF_INET);
4954 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4955 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4956 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4963 case IPPROTO_ICMPV6: {
4964 struct icmp6_hdr iih;
4966 if (!pf_pull_hdr(m, off2, &iih,
4967 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4968 DPFPRINTF(PF_DEBUG_MISC,
4969 ("pf: ICMP error message too short "
4975 key.proto = IPPROTO_ICMPV6;
4976 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4977 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4978 key.port[0] = key.port[1] = iih.icmp6_id;
4980 STATE_LOOKUP(kif, &key, direction, *state, pd);
4982 /* translate source/destination address, if necessary */
4983 if ((*state)->key[PF_SK_WIRE] !=
4984 (*state)->key[PF_SK_STACK]) {
4985 struct pf_state_key *nk =
4986 (*state)->key[pd->didx];
4988 if (PF_ANEQ(pd2.src,
4989 &nk->addr[pd2.sidx], pd2.af) ||
4990 nk->port[pd2.sidx] != iih.icmp6_id)
4991 pf_change_icmp(pd2.src, &iih.icmp6_id,
4992 daddr, &nk->addr[pd2.sidx],
4993 nk->port[pd2.sidx], NULL,
4994 pd2.ip_sum, icmpsum,
4995 pd->ip_sum, 0, AF_INET6);
4997 if (PF_ANEQ(pd2.dst,
4998 &nk->addr[pd2.didx], pd2.af) ||
4999 nk->port[pd2.didx] != iih.icmp6_id)
5000 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5001 saddr, &nk->addr[pd2.didx],
5002 nk->port[pd2.didx], NULL,
5003 pd2.ip_sum, icmpsum,
5004 pd->ip_sum, 0, AF_INET6);
5006 m_copyback(m, off, sizeof(struct icmp6_hdr),
5007 (caddr_t)pd->hdr.icmp6);
5008 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5009 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5018 key.proto = pd2.proto;
5019 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5020 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5021 key.port[0] = key.port[1] = 0;
5023 STATE_LOOKUP(kif, &key, direction, *state, pd);
5025 /* translate source/destination address, if necessary */
5026 if ((*state)->key[PF_SK_WIRE] !=
5027 (*state)->key[PF_SK_STACK]) {
5028 struct pf_state_key *nk =
5029 (*state)->key[pd->didx];
5031 if (PF_ANEQ(pd2.src,
5032 &nk->addr[pd2.sidx], pd2.af))
5033 pf_change_icmp(pd2.src, NULL, daddr,
5034 &nk->addr[pd2.sidx], 0, NULL,
5035 pd2.ip_sum, icmpsum,
5036 pd->ip_sum, 0, pd2.af);
5038 if (PF_ANEQ(pd2.dst,
5039 &nk->addr[pd2.didx], pd2.af))
5040 pf_change_icmp(pd2.dst, NULL, saddr,
5041 &nk->addr[pd2.didx], 0, NULL,
5042 pd2.ip_sum, icmpsum,
5043 pd->ip_sum, 0, pd2.af);
5048 m_copyback(m, off, ICMP_MINLEN,
5049 (caddr_t)pd->hdr.icmp);
5050 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5056 sizeof(struct icmp6_hdr),
5057 (caddr_t )pd->hdr.icmp6);
5058 m_copyback(m, ipoff2, sizeof(h2_6),
5072 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5073 struct mbuf *m, struct pf_pdesc *pd)
5075 struct pf_state_peer *src, *dst;
5076 struct pf_state_key_cmp key;
5078 bzero(&key, sizeof(key));
5080 key.proto = pd->proto;
5081 if (direction == PF_IN) {
5082 PF_ACPY(&key.addr[0], pd->src, key.af);
5083 PF_ACPY(&key.addr[1], pd->dst, key.af);
5084 key.port[0] = key.port[1] = 0;
5086 PF_ACPY(&key.addr[1], pd->src, key.af);
5087 PF_ACPY(&key.addr[0], pd->dst, key.af);
5088 key.port[1] = key.port[0] = 0;
5091 STATE_LOOKUP(kif, &key, direction, *state, pd);
5093 if (direction == (*state)->direction) {
5094 src = &(*state)->src;
5095 dst = &(*state)->dst;
5097 src = &(*state)->dst;
5098 dst = &(*state)->src;
5102 if (src->state < PFOTHERS_SINGLE)
5103 src->state = PFOTHERS_SINGLE;
5104 if (dst->state == PFOTHERS_SINGLE)
5105 dst->state = PFOTHERS_MULTIPLE;
5107 /* update expire time */
5108 (*state)->expire = time_uptime;
5109 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5110 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5112 (*state)->timeout = PFTM_OTHER_SINGLE;
5114 /* translate source/destination address, if necessary */
5115 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5116 struct pf_state_key *nk = (*state)->key[pd->didx];
5118 KASSERT(nk, ("%s: nk is null", __func__));
5119 KASSERT(pd, ("%s: pd is null", __func__));
5120 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5121 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5125 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5126 pf_change_a(&pd->src->v4.s_addr,
5128 nk->addr[pd->sidx].v4.s_addr,
5132 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5133 pf_change_a(&pd->dst->v4.s_addr,
5135 nk->addr[pd->didx].v4.s_addr,
5142 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5143 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5145 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5146 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5154 * ipoff and off are measured from the start of the mbuf chain.
5155 * h must be at "ipoff" on the mbuf chain.
5158 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5159 u_short *actionp, u_short *reasonp, sa_family_t af)
5164 struct ip *h = mtod(m, struct ip *);
5165 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5169 ACTION_SET(actionp, PF_PASS);
5171 ACTION_SET(actionp, PF_DROP);
5172 REASON_SET(reasonp, PFRES_FRAG);
5176 if (m->m_pkthdr.len < off + len ||
5177 ntohs(h->ip_len) < off + len) {
5178 ACTION_SET(actionp, PF_DROP);
5179 REASON_SET(reasonp, PFRES_SHORT);
5187 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5189 if (m->m_pkthdr.len < off + len ||
5190 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5191 (unsigned)(off + len)) {
5192 ACTION_SET(actionp, PF_DROP);
5193 REASON_SET(reasonp, PFRES_SHORT);
5200 m_copydata(m, off, len, p);
5205 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5209 struct radix_node_head *rnh;
5211 struct sockaddr_in *dst;
5215 struct sockaddr_in6 *dst6;
5216 struct route_in6 ro;
5220 struct radix_node *rn;
5226 /* XXX: stick to table 0 for now */
5227 rnh = rt_tables_get_rnh(0, af);
5228 if (rnh != NULL && rn_mpath_capable(rnh))
5231 bzero(&ro, sizeof(ro));
5234 dst = satosin(&ro.ro_dst);
5235 dst->sin_family = AF_INET;
5236 dst->sin_len = sizeof(*dst);
5237 dst->sin_addr = addr->v4;
5242 * Skip check for addresses with embedded interface scope,
5243 * as they would always match anyway.
5245 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5247 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5248 dst6->sin6_family = AF_INET6;
5249 dst6->sin6_len = sizeof(*dst6);
5250 dst6->sin6_addr = addr->v6;
5257 /* Skip checks for ipsec interfaces */
5258 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5264 in6_rtalloc_ign(&ro, 0, rtableid);
5269 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5273 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5277 if (ro.ro_rt != NULL) {
5278 /* No interface given, this is a no-route check */
5282 if (kif->pfik_ifp == NULL) {
5287 /* Perform uRPF check if passed input interface */
5289 rn = (struct radix_node *)ro.ro_rt;
5291 rt = (struct rtentry *)rn;
5294 if (kif->pfik_ifp == ifp)
5297 rn = rn_mpath_next(rn);
5299 } while (check_mpath == 1 && rn != NULL && ret == 0);
5303 if (ro.ro_rt != NULL)
5310 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5311 struct pf_state *s, struct pf_pdesc *pd)
5313 struct mbuf *m0, *m1;
5314 struct sockaddr_in dst;
5316 struct ifnet *ifp = NULL;
5317 struct pf_addr naddr;
5318 struct pf_src_node *sn = NULL;
5320 uint16_t ip_len, ip_off;
5322 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5323 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5326 if ((pd->pf_mtag == NULL &&
5327 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5328 pd->pf_mtag->routed++ > 3) {
5334 if (r->rt == PF_DUPTO) {
5335 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5341 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5349 ip = mtod(m0, struct ip *);
5351 bzero(&dst, sizeof(dst));
5352 dst.sin_family = AF_INET;
5353 dst.sin_len = sizeof(dst);
5354 dst.sin_addr = ip->ip_dst;
5356 if (r->rt == PF_FASTROUTE) {
5361 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5363 KMOD_IPSTAT_INC(ips_noroute);
5364 error = EHOSTUNREACH;
5369 counter_u64_add(rt->rt_pksent, 1);
5371 if (rt->rt_flags & RTF_GATEWAY)
5372 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5375 if (TAILQ_EMPTY(&r->rpool.list)) {
5376 DPFPRINTF(PF_DEBUG_URGENT,
5377 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5381 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5383 if (!PF_AZERO(&naddr, AF_INET))
5384 dst.sin_addr.s_addr = naddr.v4.s_addr;
5385 ifp = r->rpool.cur->kif ?
5386 r->rpool.cur->kif->pfik_ifp : NULL;
5388 if (!PF_AZERO(&s->rt_addr, AF_INET))
5389 dst.sin_addr.s_addr =
5390 s->rt_addr.v4.s_addr;
5391 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5399 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5401 else if (m0 == NULL)
5403 if (m0->m_len < sizeof(struct ip)) {
5404 DPFPRINTF(PF_DEBUG_URGENT,
5405 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5408 ip = mtod(m0, struct ip *);
5411 if (ifp->if_flags & IFF_LOOPBACK)
5412 m0->m_flags |= M_SKIP_FIREWALL;
5414 ip_len = ntohs(ip->ip_len);
5415 ip_off = ntohs(ip->ip_off);
5417 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5418 m0->m_pkthdr.csum_flags |= CSUM_IP;
5419 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5420 in_delayed_cksum(m0);
5421 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5424 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5425 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5426 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5431 * If small enough for interface, or the interface will take
5432 * care of the fragmentation for us, we can just send directly.
5434 if (ip_len <= ifp->if_mtu ||
5435 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5436 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5438 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5439 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5440 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5442 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5443 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5447 /* Balk when DF bit is set or the interface didn't support TSO. */
5448 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5450 KMOD_IPSTAT_INC(ips_cantfrag);
5451 if (r->rt != PF_DUPTO) {
5452 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5459 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5463 for (; m0; m0 = m1) {
5465 m0->m_nextpkt = NULL;
5467 m_clrprotoflags(m0);
5468 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5474 KMOD_IPSTAT_INC(ips_fragmented);
5477 if (r->rt != PF_DUPTO)
5492 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5493 struct pf_state *s, struct pf_pdesc *pd)
5496 struct sockaddr_in6 dst;
5497 struct ip6_hdr *ip6;
5498 struct ifnet *ifp = NULL;
5499 struct pf_addr naddr;
5500 struct pf_src_node *sn = NULL;
5502 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5503 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5506 if ((pd->pf_mtag == NULL &&
5507 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5508 pd->pf_mtag->routed++ > 3) {
5514 if (r->rt == PF_DUPTO) {
5515 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5521 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5529 ip6 = mtod(m0, struct ip6_hdr *);
5531 bzero(&dst, sizeof(dst));
5532 dst.sin6_family = AF_INET6;
5533 dst.sin6_len = sizeof(dst);
5534 dst.sin6_addr = ip6->ip6_dst;
5536 /* Cheat. XXX why only in the v6 case??? */
5537 if (r->rt == PF_FASTROUTE) {
5540 m0->m_flags |= M_SKIP_FIREWALL;
5541 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5546 if (TAILQ_EMPTY(&r->rpool.list)) {
5547 DPFPRINTF(PF_DEBUG_URGENT,
5548 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5552 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5554 if (!PF_AZERO(&naddr, AF_INET6))
5555 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5557 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5559 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5560 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5561 &s->rt_addr, AF_INET6);
5562 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5572 if (pf_test6(PF_FWD, ifp, &m0, NULL) != PF_PASS)
5574 else if (m0 == NULL)
5576 if (m0->m_len < sizeof(struct ip6_hdr)) {
5577 DPFPRINTF(PF_DEBUG_URGENT,
5578 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5582 ip6 = mtod(m0, struct ip6_hdr *);
5585 if (ifp->if_flags & IFF_LOOPBACK)
5586 m0->m_flags |= M_SKIP_FIREWALL;
5588 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5589 ~ifp->if_hwassist) {
5590 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5591 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5592 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5596 * If the packet is too large for the outgoing interface,
5597 * send back an icmp6 error.
5599 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5600 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5601 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5602 nd6_output(ifp, ifp, m0, &dst, NULL);
5604 in6_ifstat_inc(ifp, ifs6_in_toobig);
5605 if (r->rt != PF_DUPTO)
5606 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5612 if (r->rt != PF_DUPTO)
5626 * FreeBSD supports cksum offloads for the following drivers.
5627 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5628 * ti(4), txp(4), xl(4)
5630 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5631 * network driver performed cksum including pseudo header, need to verify
5634 * network driver performed cksum, needs to additional pseudo header
5635 * cksum computation with partial csum_data(i.e. lack of H/W support for
5636 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5638 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5639 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5641 * Also, set csum_data to 0xffff to force cksum validation.
5644 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5650 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5652 if (m->m_pkthdr.len < off + len)
5657 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5658 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5659 sum = m->m_pkthdr.csum_data;
5661 ip = mtod(m, struct ip *);
5662 sum = in_pseudo(ip->ip_src.s_addr,
5663 ip->ip_dst.s_addr, htonl((u_short)len +
5664 m->m_pkthdr.csum_data + IPPROTO_TCP));
5671 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5672 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5673 sum = m->m_pkthdr.csum_data;
5675 ip = mtod(m, struct ip *);
5676 sum = in_pseudo(ip->ip_src.s_addr,
5677 ip->ip_dst.s_addr, htonl((u_short)len +
5678 m->m_pkthdr.csum_data + IPPROTO_UDP));
5686 case IPPROTO_ICMPV6:
5696 if (p == IPPROTO_ICMP) {
5701 sum = in_cksum(m, len);
5705 if (m->m_len < sizeof(struct ip))
5707 sum = in4_cksum(m, p, off, len);
5712 if (m->m_len < sizeof(struct ip6_hdr))
5714 sum = in6_cksum(m, p, off, len);
5725 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5730 KMOD_UDPSTAT_INC(udps_badsum);
5736 KMOD_ICMPSTAT_INC(icps_checksum);
5741 case IPPROTO_ICMPV6:
5743 KMOD_ICMP6STAT_INC(icp6s_checksum);
5750 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5751 m->m_pkthdr.csum_flags |=
5752 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5753 m->m_pkthdr.csum_data = 0xffff;
5762 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5764 struct pfi_kif *kif;
5765 u_short action, reason = 0, log = 0;
5766 struct mbuf *m = *m0;
5767 struct ip *h = NULL;
5768 struct m_tag *ipfwtag;
5769 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5770 struct pf_state *s = NULL;
5771 struct pf_ruleset *ruleset = NULL;
5773 int off, dirndx, pqid = 0;
5777 if (!V_pf_status.running)
5780 memset(&pd, 0, sizeof(pd));
5782 kif = (struct pfi_kif *)ifp->if_pf_kif;
5785 DPFPRINTF(PF_DEBUG_URGENT,
5786 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5789 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5792 if (m->m_flags & M_SKIP_FIREWALL)
5795 pd.pf_mtag = pf_find_mtag(m);
5799 if (ip_divert_ptr != NULL &&
5800 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5801 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5802 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5803 if (pd.pf_mtag == NULL &&
5804 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5808 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5809 m_tag_delete(m, ipfwtag);
5811 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5812 m->m_flags |= M_FASTFWD_OURS;
5813 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5815 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5816 /* We do IP header normalization and packet reassembly here */
5820 m = *m0; /* pf_normalize messes with m0 */
5821 h = mtod(m, struct ip *);
5823 off = h->ip_hl << 2;
5824 if (off < (int)sizeof(struct ip)) {
5826 REASON_SET(&reason, PFRES_SHORT);
5831 pd.src = (struct pf_addr *)&h->ip_src;
5832 pd.dst = (struct pf_addr *)&h->ip_dst;
5833 pd.sport = pd.dport = NULL;
5834 pd.ip_sum = &h->ip_sum;
5835 pd.proto_sum = NULL;
5838 pd.sidx = (dir == PF_IN) ? 0 : 1;
5839 pd.didx = (dir == PF_IN) ? 1 : 0;
5842 pd.tot_len = ntohs(h->ip_len);
5844 /* handle fragments that didn't get reassembled by normalization */
5845 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5846 action = pf_test_fragment(&r, dir, kif, m, h,
5857 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5858 &action, &reason, AF_INET)) {
5859 log = action != PF_PASS;
5862 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5863 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5865 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5866 if (action == PF_DROP)
5868 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5870 if (action == PF_PASS) {
5871 if (pfsync_update_state_ptr != NULL)
5872 pfsync_update_state_ptr(s);
5876 } else if (s == NULL)
5877 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5886 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5887 &action, &reason, AF_INET)) {
5888 log = action != PF_PASS;
5891 if (uh.uh_dport == 0 ||
5892 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5893 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5895 REASON_SET(&reason, PFRES_SHORT);
5898 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5899 if (action == PF_PASS) {
5900 if (pfsync_update_state_ptr != NULL)
5901 pfsync_update_state_ptr(s);
5905 } else if (s == NULL)
5906 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5911 case IPPROTO_ICMP: {
5915 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5916 &action, &reason, AF_INET)) {
5917 log = action != PF_PASS;
5920 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5922 if (action == PF_PASS) {
5923 if (pfsync_update_state_ptr != NULL)
5924 pfsync_update_state_ptr(s);
5928 } else if (s == NULL)
5929 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5935 case IPPROTO_ICMPV6: {
5937 DPFPRINTF(PF_DEBUG_MISC,
5938 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5944 action = pf_test_state_other(&s, dir, kif, m, &pd);
5945 if (action == PF_PASS) {
5946 if (pfsync_update_state_ptr != NULL)
5947 pfsync_update_state_ptr(s);
5951 } else if (s == NULL)
5952 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5959 if (action == PF_PASS && h->ip_hl > 5 &&
5960 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5962 REASON_SET(&reason, PFRES_IPOPTIONS);
5964 DPFPRINTF(PF_DEBUG_MISC,
5965 ("pf: dropping packet with ip options\n"));
5968 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5970 REASON_SET(&reason, PFRES_MEMORY);
5972 if (r->rtableid >= 0)
5973 M_SETFIB(m, r->rtableid);
5976 if (action == PF_PASS && r->qid) {
5977 if (pd.pf_mtag == NULL &&
5978 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5980 REASON_SET(&reason, PFRES_MEMORY);
5983 pd.pf_mtag->qid_hash = pf_state_hash(s);
5984 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5985 pd.pf_mtag->qid = r->pqid;
5987 pd.pf_mtag->qid = r->qid;
5988 /* Add hints for ecn. */
5989 pd.pf_mtag->hdr = h;
5996 * connections redirected to loopback should not match sockets
5997 * bound specifically to loopback due to security implications,
5998 * see tcp_input() and in_pcblookup_listen().
6000 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6001 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6002 (s->nat_rule.ptr->action == PF_RDR ||
6003 s->nat_rule.ptr->action == PF_BINAT) &&
6004 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6005 m->m_flags |= M_SKIP_FIREWALL;
6007 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6008 !PACKET_LOOPED(&pd)) {
6010 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6011 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6012 if (ipfwtag != NULL) {
6013 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6014 ntohs(r->divert.port);
6015 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6020 m_tag_prepend(m, ipfwtag);
6021 if (m->m_flags & M_FASTFWD_OURS) {
6022 if (pd.pf_mtag == NULL &&
6023 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6025 REASON_SET(&reason, PFRES_MEMORY);
6027 DPFPRINTF(PF_DEBUG_MISC,
6028 ("pf: failed to allocate tag\n"));
6030 pd.pf_mtag->flags |=
6031 PF_FASTFWD_OURS_PRESENT;
6032 m->m_flags &= ~M_FASTFWD_OURS;
6035 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6040 /* XXX: ipfw has the same behaviour! */
6042 REASON_SET(&reason, PFRES_MEMORY);
6044 DPFPRINTF(PF_DEBUG_MISC,
6045 ("pf: failed to allocate divert tag\n"));
6052 if (s != NULL && s->nat_rule.ptr != NULL &&
6053 s->nat_rule.ptr->log & PF_LOG_ALL)
6054 lr = s->nat_rule.ptr;
6057 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6061 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6062 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6064 if (action == PF_PASS || r->action == PF_DROP) {
6065 dirndx = (dir == PF_OUT);
6066 r->packets[dirndx]++;
6067 r->bytes[dirndx] += pd.tot_len;
6069 a->packets[dirndx]++;
6070 a->bytes[dirndx] += pd.tot_len;
6073 if (s->nat_rule.ptr != NULL) {
6074 s->nat_rule.ptr->packets[dirndx]++;
6075 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6077 if (s->src_node != NULL) {
6078 s->src_node->packets[dirndx]++;
6079 s->src_node->bytes[dirndx] += pd.tot_len;
6081 if (s->nat_src_node != NULL) {
6082 s->nat_src_node->packets[dirndx]++;
6083 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6085 dirndx = (dir == s->direction) ? 0 : 1;
6086 s->packets[dirndx]++;
6087 s->bytes[dirndx] += pd.tot_len;
6090 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6091 if (nr != NULL && r == &V_pf_default_rule)
6093 if (tr->src.addr.type == PF_ADDR_TABLE)
6094 pfr_update_stats(tr->src.addr.p.tbl,
6095 (s == NULL) ? pd.src :
6096 &s->key[(s->direction == PF_IN)]->
6097 addr[(s->direction == PF_OUT)],
6098 pd.af, pd.tot_len, dir == PF_OUT,
6099 r->action == PF_PASS, tr->src.neg);
6100 if (tr->dst.addr.type == PF_ADDR_TABLE)
6101 pfr_update_stats(tr->dst.addr.p.tbl,
6102 (s == NULL) ? pd.dst :
6103 &s->key[(s->direction == PF_IN)]->
6104 addr[(s->direction == PF_IN)],
6105 pd.af, pd.tot_len, dir == PF_OUT,
6106 r->action == PF_PASS, tr->dst.neg);
6110 case PF_SYNPROXY_DROP:
6121 /* pf_route() returns unlocked. */
6123 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6137 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6139 struct pfi_kif *kif;
6140 u_short action, reason = 0, log = 0;
6141 struct mbuf *m = *m0, *n = NULL;
6143 struct ip6_hdr *h = NULL;
6144 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6145 struct pf_state *s = NULL;
6146 struct pf_ruleset *ruleset = NULL;
6148 int off, terminal = 0, dirndx, rh_cnt = 0;
6153 /* Detect packet forwarding.
6154 * If the input interface is different from the output interface we're
6156 * We do need to be careful about bridges. If the
6157 * net.link.bridge.pfil_bridge sysctl is set we can be filtering on a
6158 * bridge, so if the input interface is a bridge member and the output
6159 * interface is its bridge or a member of the same bridge we're not
6160 * actually forwarding but bridging.
6162 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif &&
6163 (m->m_pkthdr.rcvif->if_bridge == NULL ||
6164 (m->m_pkthdr.rcvif->if_bridge != ifp->if_softc &&
6165 m->m_pkthdr.rcvif->if_bridge != ifp->if_bridge)))
6171 if (!V_pf_status.running)
6174 memset(&pd, 0, sizeof(pd));
6175 pd.pf_mtag = pf_find_mtag(m);
6177 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6180 kif = (struct pfi_kif *)ifp->if_pf_kif;
6182 DPFPRINTF(PF_DEBUG_URGENT,
6183 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6186 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6189 if (m->m_flags & M_SKIP_FIREWALL)
6194 /* We do IP header normalization and packet reassembly here */
6195 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6199 m = *m0; /* pf_normalize messes with m0 */
6200 h = mtod(m, struct ip6_hdr *);
6204 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6205 * will do something bad, so drop the packet for now.
6207 if (htons(h->ip6_plen) == 0) {
6209 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6214 pd.src = (struct pf_addr *)&h->ip6_src;
6215 pd.dst = (struct pf_addr *)&h->ip6_dst;
6216 pd.sport = pd.dport = NULL;
6218 pd.proto_sum = NULL;
6220 pd.sidx = (dir == PF_IN) ? 0 : 1;
6221 pd.didx = (dir == PF_IN) ? 1 : 0;
6224 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6226 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6227 pd.proto = h->ip6_nxt;
6230 case IPPROTO_FRAGMENT:
6231 action = pf_test_fragment(&r, dir, kif, m, h,
6233 if (action == PF_DROP)
6234 REASON_SET(&reason, PFRES_FRAG);
6236 case IPPROTO_ROUTING: {
6237 struct ip6_rthdr rthdr;
6240 DPFPRINTF(PF_DEBUG_MISC,
6241 ("pf: IPv6 more than one rthdr\n"));
6243 REASON_SET(&reason, PFRES_IPOPTIONS);
6247 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6249 DPFPRINTF(PF_DEBUG_MISC,
6250 ("pf: IPv6 short rthdr\n"));
6252 REASON_SET(&reason, PFRES_SHORT);
6256 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6257 DPFPRINTF(PF_DEBUG_MISC,
6258 ("pf: IPv6 rthdr0\n"));
6260 REASON_SET(&reason, PFRES_IPOPTIONS);
6267 case IPPROTO_HOPOPTS:
6268 case IPPROTO_DSTOPTS: {
6269 /* get next header and header length */
6270 struct ip6_ext opt6;
6272 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6273 NULL, &reason, pd.af)) {
6274 DPFPRINTF(PF_DEBUG_MISC,
6275 ("pf: IPv6 short opt\n"));
6280 if (pd.proto == IPPROTO_AH)
6281 off += (opt6.ip6e_len + 2) * 4;
6283 off += (opt6.ip6e_len + 1) * 8;
6284 pd.proto = opt6.ip6e_nxt;
6285 /* goto the next header */
6292 } while (!terminal);
6294 /* if there's no routing header, use unmodified mbuf for checksumming */
6304 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6305 &action, &reason, AF_INET6)) {
6306 log = action != PF_PASS;
6309 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6310 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6311 if (action == PF_DROP)
6313 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6315 if (action == PF_PASS) {
6316 if (pfsync_update_state_ptr != NULL)
6317 pfsync_update_state_ptr(s);
6321 } else if (s == NULL)
6322 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6331 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6332 &action, &reason, AF_INET6)) {
6333 log = action != PF_PASS;
6336 if (uh.uh_dport == 0 ||
6337 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6338 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6340 REASON_SET(&reason, PFRES_SHORT);
6343 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6344 if (action == PF_PASS) {
6345 if (pfsync_update_state_ptr != NULL)
6346 pfsync_update_state_ptr(s);
6350 } else if (s == NULL)
6351 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6356 case IPPROTO_ICMP: {
6358 DPFPRINTF(PF_DEBUG_MISC,
6359 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6363 case IPPROTO_ICMPV6: {
6364 struct icmp6_hdr ih;
6367 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6368 &action, &reason, AF_INET6)) {
6369 log = action != PF_PASS;
6372 action = pf_test_state_icmp(&s, dir, kif,
6373 m, off, h, &pd, &reason);
6374 if (action == PF_PASS) {
6375 if (pfsync_update_state_ptr != NULL)
6376 pfsync_update_state_ptr(s);
6380 } else if (s == NULL)
6381 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6387 action = pf_test_state_other(&s, dir, kif, m, &pd);
6388 if (action == PF_PASS) {
6389 if (pfsync_update_state_ptr != NULL)
6390 pfsync_update_state_ptr(s);
6394 } else if (s == NULL)
6395 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6407 /* handle dangerous IPv6 extension headers. */
6408 if (action == PF_PASS && rh_cnt &&
6409 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6411 REASON_SET(&reason, PFRES_IPOPTIONS);
6413 DPFPRINTF(PF_DEBUG_MISC,
6414 ("pf: dropping packet with dangerous v6 headers\n"));
6417 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6419 REASON_SET(&reason, PFRES_MEMORY);
6421 if (r->rtableid >= 0)
6422 M_SETFIB(m, r->rtableid);
6425 if (action == PF_PASS && r->qid) {
6426 if (pd.pf_mtag == NULL &&
6427 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6429 REASON_SET(&reason, PFRES_MEMORY);
6432 pd.pf_mtag->qid_hash = pf_state_hash(s);
6433 if (pd.tos & IPTOS_LOWDELAY)
6434 pd.pf_mtag->qid = r->pqid;
6436 pd.pf_mtag->qid = r->qid;
6437 /* Add hints for ecn. */
6438 pd.pf_mtag->hdr = h;
6443 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6444 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6445 (s->nat_rule.ptr->action == PF_RDR ||
6446 s->nat_rule.ptr->action == PF_BINAT) &&
6447 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6448 m->m_flags |= M_SKIP_FIREWALL;
6450 /* XXX: Anybody working on it?! */
6452 printf("pf: divert(9) is not supported for IPv6\n");
6457 if (s != NULL && s->nat_rule.ptr != NULL &&
6458 s->nat_rule.ptr->log & PF_LOG_ALL)
6459 lr = s->nat_rule.ptr;
6462 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6466 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6467 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6469 if (action == PF_PASS || r->action == PF_DROP) {
6470 dirndx = (dir == PF_OUT);
6471 r->packets[dirndx]++;
6472 r->bytes[dirndx] += pd.tot_len;
6474 a->packets[dirndx]++;
6475 a->bytes[dirndx] += pd.tot_len;
6478 if (s->nat_rule.ptr != NULL) {
6479 s->nat_rule.ptr->packets[dirndx]++;
6480 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6482 if (s->src_node != NULL) {
6483 s->src_node->packets[dirndx]++;
6484 s->src_node->bytes[dirndx] += pd.tot_len;
6486 if (s->nat_src_node != NULL) {
6487 s->nat_src_node->packets[dirndx]++;
6488 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6490 dirndx = (dir == s->direction) ? 0 : 1;
6491 s->packets[dirndx]++;
6492 s->bytes[dirndx] += pd.tot_len;
6495 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6496 if (nr != NULL && r == &V_pf_default_rule)
6498 if (tr->src.addr.type == PF_ADDR_TABLE)
6499 pfr_update_stats(tr->src.addr.p.tbl,
6500 (s == NULL) ? pd.src :
6501 &s->key[(s->direction == PF_IN)]->addr[0],
6502 pd.af, pd.tot_len, dir == PF_OUT,
6503 r->action == PF_PASS, tr->src.neg);
6504 if (tr->dst.addr.type == PF_ADDR_TABLE)
6505 pfr_update_stats(tr->dst.addr.p.tbl,
6506 (s == NULL) ? pd.dst :
6507 &s->key[(s->direction == PF_IN)]->addr[1],
6508 pd.af, pd.tot_len, dir == PF_OUT,
6509 r->action == PF_PASS, tr->dst.neg);
6513 case PF_SYNPROXY_DROP:
6524 /* pf_route6() returns unlocked. */
6526 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6535 /* If reassembled packet passed, create new fragments. */
6536 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6537 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6538 action = pf_refragment6(ifp, m0, mtag);