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_var.h>
65 #include <net/if_types.h>
66 #include <net/if_vlan_var.h>
67 #include <net/route.h>
68 #include <net/radix_mpath.h>
72 #include <net/pfvar.h>
73 #include <net/if_pflog.h>
74 #include <net/if_pfsync.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/in_var.h>
78 #include <netinet/in_fib.h>
79 #include <netinet/ip.h>
80 #include <netinet/ip_fw.h>
81 #include <netinet/ip_icmp.h>
82 #include <netinet/icmp_var.h>
83 #include <netinet/ip_var.h>
84 #include <netinet/tcp.h>
85 #include <netinet/tcp_fsm.h>
86 #include <netinet/tcp_seq.h>
87 #include <netinet/tcp_timer.h>
88 #include <netinet/tcp_var.h>
89 #include <netinet/udp.h>
90 #include <netinet/udp_var.h>
92 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
95 #include <netinet/ip6.h>
96 #include <netinet/icmp6.h>
97 #include <netinet6/nd6.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/in6_pcb.h>
100 #include <netinet6/in6_fib.h>
101 #include <netinet6/scope6_var.h>
104 #include <machine/in_cksum.h>
105 #include <security/mac/mac_framework.h>
107 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
114 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
115 VNET_DEFINE(struct pf_palist, pf_pabuf);
116 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
117 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
118 VNET_DEFINE(struct pf_kstatus, pf_status);
120 VNET_DEFINE(u_int32_t, ticket_altqs_active);
121 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
122 VNET_DEFINE(int, altqs_inactive_open);
123 VNET_DEFINE(u_int32_t, ticket_pabuf);
125 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
126 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
127 VNET_DEFINE(u_char, pf_tcp_secret[16]);
128 #define V_pf_tcp_secret VNET(pf_tcp_secret)
129 VNET_DEFINE(int, pf_tcp_secret_init);
130 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
131 VNET_DEFINE(int, pf_tcp_iss_off);
132 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
133 VNET_DECLARE(int, pf_vnet_active);
134 #define V_pf_vnet_active VNET(pf_vnet_active)
137 * Queue for pf_intr() sends.
139 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
140 struct pf_send_entry {
141 STAILQ_ENTRY(pf_send_entry) pfse_next;
156 STAILQ_HEAD(pf_send_head, pf_send_entry);
157 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
158 #define V_pf_sendqueue VNET(pf_sendqueue)
160 static struct mtx pf_sendqueue_mtx;
161 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
162 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
163 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
166 * Queue for pf_overload_task() tasks.
168 struct pf_overload_entry {
169 SLIST_ENTRY(pf_overload_entry) next;
173 struct pf_rule *rule;
176 SLIST_HEAD(pf_overload_head, pf_overload_entry);
177 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
178 #define V_pf_overloadqueue VNET(pf_overloadqueue)
179 static VNET_DEFINE(struct task, pf_overloadtask);
180 #define V_pf_overloadtask VNET(pf_overloadtask)
182 static struct mtx pf_overloadqueue_mtx;
183 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
184 "pf overload/flush queue", MTX_DEF);
185 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
186 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
188 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
189 struct mtx pf_unlnkdrules_mtx;
190 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
193 static VNET_DEFINE(uma_zone_t, pf_sources_z);
194 #define V_pf_sources_z VNET(pf_sources_z)
195 uma_zone_t pf_mtag_z;
196 VNET_DEFINE(uma_zone_t, pf_state_z);
197 VNET_DEFINE(uma_zone_t, pf_state_key_z);
199 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
200 #define PFID_CPUBITS 8
201 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
202 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
203 #define PFID_MAXID (~PFID_CPUMASK)
204 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
206 static void pf_src_tree_remove_state(struct pf_state *);
207 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
209 static void pf_add_threshold(struct pf_threshold *);
210 static int pf_check_threshold(struct pf_threshold *);
212 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
213 u_int16_t *, u_int16_t *, struct pf_addr *,
214 u_int16_t, u_int8_t, sa_family_t);
215 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
216 struct tcphdr *, struct pf_state_peer *);
217 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
218 struct pf_addr *, struct pf_addr *, u_int16_t,
219 u_int16_t *, u_int16_t *, u_int16_t *,
220 u_int16_t *, u_int8_t, sa_family_t);
221 static void pf_send_tcp(struct mbuf *,
222 const struct pf_rule *, sa_family_t,
223 const struct pf_addr *, const struct pf_addr *,
224 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
225 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
226 u_int16_t, struct ifnet *);
227 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
228 sa_family_t, struct pf_rule *);
229 static void pf_detach_state(struct pf_state *);
230 static int pf_state_key_attach(struct pf_state_key *,
231 struct pf_state_key *, struct pf_state *);
232 static void pf_state_key_detach(struct pf_state *, int);
233 static int pf_state_key_ctor(void *, int, void *, int);
234 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
235 static int pf_test_rule(struct pf_rule **, struct pf_state **,
236 int, struct pfi_kif *, struct mbuf *, int,
237 struct pf_pdesc *, struct pf_rule **,
238 struct pf_ruleset **, struct inpcb *);
239 static int pf_create_state(struct pf_rule *, struct pf_rule *,
240 struct pf_rule *, struct pf_pdesc *,
241 struct pf_src_node *, struct pf_state_key *,
242 struct pf_state_key *, struct mbuf *, int,
243 u_int16_t, u_int16_t, int *, struct pfi_kif *,
244 struct pf_state **, int, u_int16_t, u_int16_t,
246 static int pf_test_fragment(struct pf_rule **, int,
247 struct pfi_kif *, struct mbuf *, void *,
248 struct pf_pdesc *, struct pf_rule **,
249 struct pf_ruleset **);
250 static int pf_tcp_track_full(struct pf_state_peer *,
251 struct pf_state_peer *, struct pf_state **,
252 struct pfi_kif *, struct mbuf *, int,
253 struct pf_pdesc *, u_short *, int *);
254 static int pf_tcp_track_sloppy(struct pf_state_peer *,
255 struct pf_state_peer *, struct pf_state **,
256 struct pf_pdesc *, u_short *);
257 static int pf_test_state_tcp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260 static int pf_test_state_udp(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, int,
262 void *, struct pf_pdesc *);
263 static int pf_test_state_icmp(struct pf_state **, int,
264 struct pfi_kif *, struct mbuf *, int,
265 void *, struct pf_pdesc *, u_short *);
266 static int pf_test_state_other(struct pf_state **, int,
267 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
268 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
270 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
272 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
274 static int pf_check_proto_cksum(struct mbuf *, int, int,
275 u_int8_t, sa_family_t);
276 static void pf_print_state_parts(struct pf_state *,
277 struct pf_state_key *, struct pf_state_key *);
278 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
279 struct pf_addr_wrap *);
280 static struct pf_state *pf_find_state(struct pfi_kif *,
281 struct pf_state_key_cmp *, u_int);
282 static int pf_src_connlimit(struct pf_state **);
283 static void pf_overload_task(void *v, int pending);
284 static int pf_insert_src_node(struct pf_src_node **,
285 struct pf_rule *, struct pf_addr *, sa_family_t);
286 static u_int pf_purge_expired_states(u_int, int);
287 static void pf_purge_unlinked_rules(void);
288 static int pf_mtag_uminit(void *, int, int);
289 static void pf_mtag_free(struct m_tag *);
291 static void pf_route(struct mbuf **, struct pf_rule *, int,
292 struct ifnet *, struct pf_state *,
293 struct pf_pdesc *, struct inpcb *);
296 static void pf_change_a6(struct pf_addr *, u_int16_t *,
297 struct pf_addr *, u_int8_t);
298 static void pf_route6(struct mbuf **, struct pf_rule *, int,
299 struct ifnet *, struct pf_state *,
300 struct pf_pdesc *, struct inpcb *);
303 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
305 extern int pf_end_threads;
307 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
309 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
310 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
312 #define STATE_LOOKUP(i, k, d, s, pd) \
314 (s) = pf_find_state((i), (k), (d)); \
317 if (PACKET_LOOPED(pd)) \
319 if ((d) == PF_OUT && \
320 (((s)->rule.ptr->rt == PF_ROUTETO && \
321 (s)->rule.ptr->direction == PF_OUT) || \
322 ((s)->rule.ptr->rt == PF_REPLYTO && \
323 (s)->rule.ptr->direction == PF_IN)) && \
324 (s)->rt_kif != NULL && \
325 (s)->rt_kif != (i)) \
329 #define BOUND_IFACE(r, k) \
330 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
332 #define STATE_INC_COUNTERS(s) \
334 counter_u64_add(s->rule.ptr->states_cur, 1); \
335 counter_u64_add(s->rule.ptr->states_tot, 1); \
336 if (s->anchor.ptr != NULL) { \
337 counter_u64_add(s->anchor.ptr->states_cur, 1); \
338 counter_u64_add(s->anchor.ptr->states_tot, 1); \
340 if (s->nat_rule.ptr != NULL) { \
341 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
342 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
346 #define STATE_DEC_COUNTERS(s) \
348 if (s->nat_rule.ptr != NULL) \
349 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
350 if (s->anchor.ptr != NULL) \
351 counter_u64_add(s->anchor.ptr->states_cur, -1); \
352 counter_u64_add(s->rule.ptr->states_cur, -1); \
355 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
356 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
357 VNET_DEFINE(struct pf_idhash *, pf_idhash);
358 VNET_DEFINE(struct pf_srchash *, pf_srchash);
360 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
363 u_long pf_srchashmask;
364 static u_long pf_hashsize;
365 static u_long pf_srchashsize;
367 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
368 &pf_hashsize, 0, "Size of pf(4) states hashtable");
369 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
370 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
372 VNET_DEFINE(void *, pf_swi_cookie);
374 VNET_DEFINE(uint32_t, pf_hashseed);
375 #define V_pf_hashseed VNET(pf_hashseed)
378 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
384 if (a->addr32[0] > b->addr32[0])
386 if (a->addr32[0] < b->addr32[0])
392 if (a->addr32[3] > b->addr32[3])
394 if (a->addr32[3] < b->addr32[3])
396 if (a->addr32[2] > b->addr32[2])
398 if (a->addr32[2] < b->addr32[2])
400 if (a->addr32[1] > b->addr32[1])
402 if (a->addr32[1] < b->addr32[1])
404 if (a->addr32[0] > b->addr32[0])
406 if (a->addr32[0] < b->addr32[0])
411 panic("%s: unknown address family %u", __func__, af);
416 static __inline uint32_t
417 pf_hashkey(struct pf_state_key *sk)
421 h = murmur3_32_hash32((uint32_t *)sk,
422 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
425 return (h & pf_hashmask);
428 static __inline uint32_t
429 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
435 h = murmur3_32_hash32((uint32_t *)&addr->v4,
436 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
439 h = murmur3_32_hash32((uint32_t *)&addr->v6,
440 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
443 panic("%s: unknown address family %u", __func__, af);
446 return (h & pf_srchashmask);
451 pf_state_hash(struct pf_state *s)
453 u_int32_t hv = (intptr_t)s / sizeof(*s);
455 hv ^= crc32(&s->src, sizeof(s->src));
456 hv ^= crc32(&s->dst, sizeof(s->dst));
465 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
470 dst->addr32[0] = src->addr32[0];
474 dst->addr32[0] = src->addr32[0];
475 dst->addr32[1] = src->addr32[1];
476 dst->addr32[2] = src->addr32[2];
477 dst->addr32[3] = src->addr32[3];
484 pf_init_threshold(struct pf_threshold *threshold,
485 u_int32_t limit, u_int32_t seconds)
487 threshold->limit = limit * PF_THRESHOLD_MULT;
488 threshold->seconds = seconds;
489 threshold->count = 0;
490 threshold->last = time_uptime;
494 pf_add_threshold(struct pf_threshold *threshold)
496 u_int32_t t = time_uptime, diff = t - threshold->last;
498 if (diff >= threshold->seconds)
499 threshold->count = 0;
501 threshold->count -= threshold->count * diff /
503 threshold->count += PF_THRESHOLD_MULT;
508 pf_check_threshold(struct pf_threshold *threshold)
510 return (threshold->count > threshold->limit);
514 pf_src_connlimit(struct pf_state **state)
516 struct pf_overload_entry *pfoe;
519 PF_STATE_LOCK_ASSERT(*state);
521 (*state)->src_node->conn++;
522 (*state)->src.tcp_est = 1;
523 pf_add_threshold(&(*state)->src_node->conn_rate);
525 if ((*state)->rule.ptr->max_src_conn &&
526 (*state)->rule.ptr->max_src_conn <
527 (*state)->src_node->conn) {
528 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
532 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
533 pf_check_threshold(&(*state)->src_node->conn_rate)) {
534 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
541 /* Kill this state. */
542 (*state)->timeout = PFTM_PURGE;
543 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
545 if ((*state)->rule.ptr->overload_tbl == NULL)
548 /* Schedule overloading and flushing task. */
549 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
551 return (1); /* too bad :( */
553 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
554 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
555 pfoe->rule = (*state)->rule.ptr;
556 pfoe->dir = (*state)->direction;
558 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
559 PF_OVERLOADQ_UNLOCK();
560 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
566 pf_overload_task(void *v, int pending)
568 struct pf_overload_head queue;
570 struct pf_overload_entry *pfoe, *pfoe1;
573 CURVNET_SET((struct vnet *)v);
576 queue = V_pf_overloadqueue;
577 SLIST_INIT(&V_pf_overloadqueue);
578 PF_OVERLOADQ_UNLOCK();
580 bzero(&p, sizeof(p));
581 SLIST_FOREACH(pfoe, &queue, next) {
582 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
583 if (V_pf_status.debug >= PF_DEBUG_MISC) {
584 printf("%s: blocking address ", __func__);
585 pf_print_host(&pfoe->addr, 0, pfoe->af);
589 p.pfra_af = pfoe->af;
594 p.pfra_ip4addr = pfoe->addr.v4;
600 p.pfra_ip6addr = pfoe->addr.v6;
606 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
611 * Remove those entries, that don't need flushing.
613 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
614 if (pfoe->rule->flush == 0) {
615 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
616 free(pfoe, M_PFTEMP);
619 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
621 /* If nothing to flush, return. */
622 if (SLIST_EMPTY(&queue)) {
627 for (int i = 0; i <= pf_hashmask; i++) {
628 struct pf_idhash *ih = &V_pf_idhash[i];
629 struct pf_state_key *sk;
633 LIST_FOREACH(s, &ih->states, entry) {
634 sk = s->key[PF_SK_WIRE];
635 SLIST_FOREACH(pfoe, &queue, next)
636 if (sk->af == pfoe->af &&
637 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
638 pfoe->rule == s->rule.ptr) &&
639 ((pfoe->dir == PF_OUT &&
640 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
641 (pfoe->dir == PF_IN &&
642 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
643 s->timeout = PFTM_PURGE;
644 s->src.state = s->dst.state = TCPS_CLOSED;
648 PF_HASHROW_UNLOCK(ih);
650 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
651 free(pfoe, M_PFTEMP);
652 if (V_pf_status.debug >= PF_DEBUG_MISC)
653 printf("%s: %u states killed", __func__, killed);
659 * Can return locked on failure, so that we can consistently
660 * allocate and insert a new one.
663 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
666 struct pf_srchash *sh;
667 struct pf_src_node *n;
669 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
671 sh = &V_pf_srchash[pf_hashsrc(src, af)];
673 LIST_FOREACH(n, &sh->nodes, entry)
674 if (n->rule.ptr == rule && n->af == af &&
675 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
676 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
680 PF_HASHROW_UNLOCK(sh);
681 } else if (returnlocked == 0)
682 PF_HASHROW_UNLOCK(sh);
688 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
689 struct pf_addr *src, sa_family_t af)
692 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
693 rule->rpool.opts & PF_POOL_STICKYADDR),
694 ("%s for non-tracking rule %p", __func__, rule));
697 *sn = pf_find_src_node(src, rule, af, 1);
700 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
702 PF_HASHROW_ASSERT(sh);
704 if (!rule->max_src_nodes ||
705 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
706 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
708 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
711 PF_HASHROW_UNLOCK(sh);
715 pf_init_threshold(&(*sn)->conn_rate,
716 rule->max_src_conn_rate.limit,
717 rule->max_src_conn_rate.seconds);
720 (*sn)->rule.ptr = rule;
721 PF_ACPY(&(*sn)->addr, src, af);
722 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
723 (*sn)->creation = time_uptime;
724 (*sn)->ruletype = rule->action;
726 if ((*sn)->rule.ptr != NULL)
727 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
728 PF_HASHROW_UNLOCK(sh);
729 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
731 if (rule->max_src_states &&
732 (*sn)->states >= rule->max_src_states) {
733 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
742 pf_unlink_src_node(struct pf_src_node *src)
745 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
746 LIST_REMOVE(src, entry);
748 counter_u64_add(src->rule.ptr->src_nodes, -1);
752 pf_free_src_nodes(struct pf_src_node_list *head)
754 struct pf_src_node *sn, *tmp;
757 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
758 uma_zfree(V_pf_sources_z, sn);
762 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
771 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
772 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
776 /* Per-vnet data storage structures initialization. */
780 struct pf_keyhash *kh;
781 struct pf_idhash *ih;
782 struct pf_srchash *sh;
785 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
786 pf_hashsize = PF_HASHSIZ;
787 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
788 pf_srchashsize = PF_SRCHASHSIZ;
790 V_pf_hashseed = arc4random();
792 /* States and state keys storage. */
793 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
794 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
795 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
796 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
797 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
799 V_pf_state_key_z = uma_zcreate("pf state keys",
800 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
803 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
804 M_PFHASH, M_NOWAIT | M_ZERO);
805 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
806 M_PFHASH, M_NOWAIT | M_ZERO);
807 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
808 printf("pf: Unable to allocate memory for "
809 "state_hashsize %lu.\n", pf_hashsize);
811 free(V_pf_keyhash, M_PFHASH);
812 free(V_pf_idhash, M_PFHASH);
814 pf_hashsize = PF_HASHSIZ;
815 V_pf_keyhash = mallocarray(pf_hashsize,
816 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
817 V_pf_idhash = mallocarray(pf_hashsize,
818 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
821 pf_hashmask = pf_hashsize - 1;
822 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
824 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
825 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
829 V_pf_sources_z = uma_zcreate("pf source nodes",
830 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
832 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
833 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
834 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
836 V_pf_srchash = mallocarray(pf_srchashsize,
837 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
838 if (V_pf_srchash == NULL) {
839 printf("pf: Unable to allocate memory for "
840 "source_hashsize %lu.\n", pf_srchashsize);
842 pf_srchashsize = PF_SRCHASHSIZ;
843 V_pf_srchash = mallocarray(pf_srchashsize,
844 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
847 pf_srchashmask = pf_srchashsize - 1;
848 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
849 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
852 TAILQ_INIT(&V_pf_altqs[0]);
853 TAILQ_INIT(&V_pf_altqs[1]);
854 TAILQ_INIT(&V_pf_pabuf);
855 V_pf_altqs_active = &V_pf_altqs[0];
856 V_pf_altqs_inactive = &V_pf_altqs[1];
858 /* Send & overload+flush queues. */
859 STAILQ_INIT(&V_pf_sendqueue);
860 SLIST_INIT(&V_pf_overloadqueue);
861 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
863 /* Unlinked, but may be referenced rules. */
864 TAILQ_INIT(&V_pf_unlinked_rules);
871 uma_zdestroy(pf_mtag_z);
877 struct pf_keyhash *kh;
878 struct pf_idhash *ih;
879 struct pf_srchash *sh;
880 struct pf_send_entry *pfse, *next;
883 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
885 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
887 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
889 mtx_destroy(&kh->lock);
890 mtx_destroy(&ih->lock);
892 free(V_pf_keyhash, M_PFHASH);
893 free(V_pf_idhash, M_PFHASH);
895 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
896 KASSERT(LIST_EMPTY(&sh->nodes),
897 ("%s: source node hash not empty", __func__));
898 mtx_destroy(&sh->lock);
900 free(V_pf_srchash, M_PFHASH);
902 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
903 m_freem(pfse->pfse_m);
904 free(pfse, M_PFTEMP);
907 uma_zdestroy(V_pf_sources_z);
908 uma_zdestroy(V_pf_state_z);
909 uma_zdestroy(V_pf_state_key_z);
913 pf_mtag_uminit(void *mem, int size, int how)
917 t = (struct m_tag *)mem;
918 t->m_tag_cookie = MTAG_ABI_COMPAT;
919 t->m_tag_id = PACKET_TAG_PF;
920 t->m_tag_len = sizeof(struct pf_mtag);
921 t->m_tag_free = pf_mtag_free;
927 pf_mtag_free(struct m_tag *t)
930 uma_zfree(pf_mtag_z, t);
934 pf_get_mtag(struct mbuf *m)
938 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
939 return ((struct pf_mtag *)(mtag + 1));
941 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
944 bzero(mtag + 1, sizeof(struct pf_mtag));
945 m_tag_prepend(m, mtag);
947 return ((struct pf_mtag *)(mtag + 1));
951 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
954 struct pf_keyhash *khs, *khw, *kh;
955 struct pf_state_key *sk, *cur;
956 struct pf_state *si, *olds = NULL;
959 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
960 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
961 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
964 * We need to lock hash slots of both keys. To avoid deadlock
965 * we always lock the slot with lower address first. Unlock order
968 * We also need to lock ID hash slot before dropping key
969 * locks. On success we return with ID hash slot locked.
973 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
974 PF_HASHROW_LOCK(khs);
976 khs = &V_pf_keyhash[pf_hashkey(sks)];
977 khw = &V_pf_keyhash[pf_hashkey(skw)];
979 PF_HASHROW_LOCK(khs);
980 } else if (khs < khw) {
981 PF_HASHROW_LOCK(khs);
982 PF_HASHROW_LOCK(khw);
984 PF_HASHROW_LOCK(khw);
985 PF_HASHROW_LOCK(khs);
989 #define KEYS_UNLOCK() do { \
991 PF_HASHROW_UNLOCK(khs); \
992 PF_HASHROW_UNLOCK(khw); \
994 PF_HASHROW_UNLOCK(khs); \
998 * First run: start with wire key.
1005 LIST_FOREACH(cur, &kh->keys, entry)
1006 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1010 /* Key exists. Check for same kif, if none, add to key. */
1011 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1012 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1014 PF_HASHROW_LOCK(ih);
1015 if (si->kif == s->kif &&
1016 si->direction == s->direction) {
1017 if (sk->proto == IPPROTO_TCP &&
1018 si->src.state >= TCPS_FIN_WAIT_2 &&
1019 si->dst.state >= TCPS_FIN_WAIT_2) {
1021 * New state matches an old >FIN_WAIT_2
1022 * state. We can't drop key hash locks,
1023 * thus we can't unlink it properly.
1025 * As a workaround we drop it into
1026 * TCPS_CLOSED state, schedule purge
1027 * ASAP and push it into the very end
1028 * of the slot TAILQ, so that it won't
1029 * conflict with our new state.
1031 si->src.state = si->dst.state =
1033 si->timeout = PFTM_PURGE;
1036 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1037 printf("pf: %s key attach "
1039 (idx == PF_SK_WIRE) ?
1042 pf_print_state_parts(s,
1043 (idx == PF_SK_WIRE) ?
1045 (idx == PF_SK_STACK) ?
1047 printf(", existing: ");
1048 pf_print_state_parts(si,
1049 (idx == PF_SK_WIRE) ?
1051 (idx == PF_SK_STACK) ?
1055 PF_HASHROW_UNLOCK(ih);
1057 uma_zfree(V_pf_state_key_z, sk);
1058 if (idx == PF_SK_STACK)
1060 return (EEXIST); /* collision! */
1063 PF_HASHROW_UNLOCK(ih);
1065 uma_zfree(V_pf_state_key_z, sk);
1068 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1073 /* List is sorted, if-bound states before floating. */
1074 if (s->kif == V_pfi_all)
1075 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1077 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1080 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1081 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1087 * Attach done. See how should we (or should not?)
1088 * attach a second key.
1091 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1095 } else if (sks != NULL) {
1097 * Continue attaching with stack key.
1109 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1110 ("%s failure", __func__));
1117 pf_detach_state(struct pf_state *s)
1119 struct pf_state_key *sks = s->key[PF_SK_STACK];
1120 struct pf_keyhash *kh;
1123 kh = &V_pf_keyhash[pf_hashkey(sks)];
1124 PF_HASHROW_LOCK(kh);
1125 if (s->key[PF_SK_STACK] != NULL)
1126 pf_state_key_detach(s, PF_SK_STACK);
1128 * If both point to same key, then we are done.
1130 if (sks == s->key[PF_SK_WIRE]) {
1131 pf_state_key_detach(s, PF_SK_WIRE);
1132 PF_HASHROW_UNLOCK(kh);
1135 PF_HASHROW_UNLOCK(kh);
1138 if (s->key[PF_SK_WIRE] != NULL) {
1139 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1140 PF_HASHROW_LOCK(kh);
1141 if (s->key[PF_SK_WIRE] != NULL)
1142 pf_state_key_detach(s, PF_SK_WIRE);
1143 PF_HASHROW_UNLOCK(kh);
1148 pf_state_key_detach(struct pf_state *s, int idx)
1150 struct pf_state_key *sk = s->key[idx];
1152 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1154 PF_HASHROW_ASSERT(kh);
1156 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1159 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1160 LIST_REMOVE(sk, entry);
1161 uma_zfree(V_pf_state_key_z, sk);
1166 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1168 struct pf_state_key *sk = mem;
1170 bzero(sk, sizeof(struct pf_state_key_cmp));
1171 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1172 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1177 struct pf_state_key *
1178 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1179 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1181 struct pf_state_key *sk;
1183 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1187 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1188 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1189 sk->port[pd->sidx] = sport;
1190 sk->port[pd->didx] = dport;
1191 sk->proto = pd->proto;
1197 struct pf_state_key *
1198 pf_state_key_clone(struct pf_state_key *orig)
1200 struct pf_state_key *sk;
1202 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1206 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1212 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1213 struct pf_state_key *sks, struct pf_state *s)
1215 struct pf_idhash *ih;
1216 struct pf_state *cur;
1219 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1220 ("%s: sks not pristine", __func__));
1221 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1222 ("%s: skw not pristine", __func__));
1223 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1227 if (s->id == 0 && s->creatorid == 0) {
1228 /* XXX: should be atomic, but probability of collision low */
1229 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1230 V_pf_stateid[curcpu] = 1;
1231 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1232 s->id = htobe64(s->id);
1233 s->creatorid = V_pf_status.hostid;
1236 /* Returns with ID locked on success. */
1237 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1240 ih = &V_pf_idhash[PF_IDHASH(s)];
1241 PF_HASHROW_ASSERT(ih);
1242 LIST_FOREACH(cur, &ih->states, entry)
1243 if (cur->id == s->id && cur->creatorid == s->creatorid)
1247 PF_HASHROW_UNLOCK(ih);
1248 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1249 printf("pf: state ID collision: "
1250 "id: %016llx creatorid: %08x\n",
1251 (unsigned long long)be64toh(s->id),
1252 ntohl(s->creatorid));
1257 LIST_INSERT_HEAD(&ih->states, s, entry);
1258 /* One for keys, one for ID hash. */
1259 refcount_init(&s->refs, 2);
1261 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1262 if (V_pfsync_insert_state_ptr != NULL)
1263 V_pfsync_insert_state_ptr(s);
1265 /* Returns locked. */
1270 * Find state by ID: returns with locked row on success.
1273 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1275 struct pf_idhash *ih;
1278 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1280 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1282 PF_HASHROW_LOCK(ih);
1283 LIST_FOREACH(s, &ih->states, entry)
1284 if (s->id == id && s->creatorid == creatorid)
1288 PF_HASHROW_UNLOCK(ih);
1294 * Find state by key.
1295 * Returns with ID hash slot locked on success.
1297 static struct pf_state *
1298 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1300 struct pf_keyhash *kh;
1301 struct pf_state_key *sk;
1305 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1307 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1309 PF_HASHROW_LOCK(kh);
1310 LIST_FOREACH(sk, &kh->keys, entry)
1311 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1314 PF_HASHROW_UNLOCK(kh);
1318 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1320 /* List is sorted, if-bound states before floating ones. */
1321 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1322 if (s->kif == V_pfi_all || s->kif == kif) {
1324 PF_HASHROW_UNLOCK(kh);
1325 if (s->timeout >= PFTM_MAX) {
1327 * State is either being processed by
1328 * pf_unlink_state() in an other thread, or
1329 * is scheduled for immediate expiry.
1336 PF_HASHROW_UNLOCK(kh);
1342 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1344 struct pf_keyhash *kh;
1345 struct pf_state_key *sk;
1346 struct pf_state *s, *ret = NULL;
1349 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1351 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1353 PF_HASHROW_LOCK(kh);
1354 LIST_FOREACH(sk, &kh->keys, entry)
1355 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1358 PF_HASHROW_UNLOCK(kh);
1373 panic("%s: dir %u", __func__, dir);
1376 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1378 PF_HASHROW_UNLOCK(kh);
1392 PF_HASHROW_UNLOCK(kh);
1397 /* END state table stuff */
1400 pf_send(struct pf_send_entry *pfse)
1404 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1406 swi_sched(V_pf_swi_cookie, 0);
1412 struct pf_send_head queue;
1413 struct pf_send_entry *pfse, *next;
1415 CURVNET_SET((struct vnet *)v);
1418 queue = V_pf_sendqueue;
1419 STAILQ_INIT(&V_pf_sendqueue);
1422 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1423 switch (pfse->pfse_type) {
1426 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1429 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1430 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1435 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1439 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1440 pfse->icmpopts.code, pfse->icmpopts.mtu);
1444 panic("%s: unknown type", __func__);
1446 free(pfse, M_PFTEMP);
1452 pf_purge_thread(void *unused __unused)
1454 VNET_ITERATOR_DECL(vnet_iter);
1457 PF_RULES_RLOCK_TRACKER;
1461 rm_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1465 VNET_FOREACH(vnet_iter) {
1466 CURVNET_SET(vnet_iter);
1468 if (pf_end_threads) {
1470 wakeup(pf_purge_thread);
1474 /* Wait while V_pf_default_rule.timeout is initialized. */
1475 if (V_pf_vnet_active == 0) {
1480 /* Process 1/interval fraction of the state table every run. */
1481 idx = pf_purge_expired_states(idx, pf_hashmask /
1482 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1484 /* Purge other expired types every PFTM_INTERVAL seconds. */
1487 * Order is important:
1488 * - states and src nodes reference rules
1489 * - states and rules reference kifs
1491 pf_purge_expired_fragments();
1492 pf_purge_expired_src_nodes();
1493 pf_purge_unlinked_rules();
1498 VNET_LIST_RUNLOCK();
1504 pf_unload_vnet_purge(void)
1508 * To cleanse up all kifs and rules we need
1509 * two runs: first one clears reference flags,
1510 * then pf_purge_expired_states() doesn't
1511 * raise them, and then second run frees.
1513 pf_purge_unlinked_rules();
1517 * Now purge everything.
1519 pf_purge_expired_states(0, pf_hashmask);
1520 pf_purge_expired_fragments();
1521 pf_purge_expired_src_nodes();
1524 * Now all kifs & rules should be unreferenced,
1525 * thus should be successfully freed.
1527 pf_purge_unlinked_rules();
1533 pf_state_expires(const struct pf_state *state)
1540 /* handle all PFTM_* > PFTM_MAX here */
1541 if (state->timeout == PFTM_PURGE)
1542 return (time_uptime);
1543 KASSERT(state->timeout != PFTM_UNLINKED,
1544 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1545 KASSERT((state->timeout < PFTM_MAX),
1546 ("pf_state_expires: timeout > PFTM_MAX"));
1547 timeout = state->rule.ptr->timeout[state->timeout];
1549 timeout = V_pf_default_rule.timeout[state->timeout];
1550 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1552 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1553 states = counter_u64_fetch(state->rule.ptr->states_cur);
1555 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1556 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1557 states = V_pf_status.states;
1559 if (end && states > start && start < end) {
1561 timeout = (u_int64_t)timeout * (end - states) /
1563 return (state->expire + timeout);
1566 return (time_uptime);
1568 return (state->expire + timeout);
1572 pf_purge_expired_src_nodes()
1574 struct pf_src_node_list freelist;
1575 struct pf_srchash *sh;
1576 struct pf_src_node *cur, *next;
1579 LIST_INIT(&freelist);
1580 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1581 PF_HASHROW_LOCK(sh);
1582 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1583 if (cur->states == 0 && cur->expire <= time_uptime) {
1584 pf_unlink_src_node(cur);
1585 LIST_INSERT_HEAD(&freelist, cur, entry);
1586 } else if (cur->rule.ptr != NULL)
1587 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1588 PF_HASHROW_UNLOCK(sh);
1591 pf_free_src_nodes(&freelist);
1593 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1597 pf_src_tree_remove_state(struct pf_state *s)
1599 struct pf_src_node *sn;
1600 struct pf_srchash *sh;
1603 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1604 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1605 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1607 if (s->src_node != NULL) {
1609 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1610 PF_HASHROW_LOCK(sh);
1613 if (--sn->states == 0)
1614 sn->expire = time_uptime + timeout;
1615 PF_HASHROW_UNLOCK(sh);
1617 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1618 sn = s->nat_src_node;
1619 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1620 PF_HASHROW_LOCK(sh);
1621 if (--sn->states == 0)
1622 sn->expire = time_uptime + timeout;
1623 PF_HASHROW_UNLOCK(sh);
1625 s->src_node = s->nat_src_node = NULL;
1629 * Unlink and potentilly free a state. Function may be
1630 * called with ID hash row locked, but always returns
1631 * unlocked, since it needs to go through key hash locking.
1634 pf_unlink_state(struct pf_state *s, u_int flags)
1636 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1638 if ((flags & PF_ENTER_LOCKED) == 0)
1639 PF_HASHROW_LOCK(ih);
1641 PF_HASHROW_ASSERT(ih);
1643 if (s->timeout == PFTM_UNLINKED) {
1645 * State is being processed
1646 * by pf_unlink_state() in
1649 PF_HASHROW_UNLOCK(ih);
1650 return (0); /* XXXGL: undefined actually */
1653 if (s->src.state == PF_TCPS_PROXY_DST) {
1654 /* XXX wire key the right one? */
1655 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1656 &s->key[PF_SK_WIRE]->addr[1],
1657 &s->key[PF_SK_WIRE]->addr[0],
1658 s->key[PF_SK_WIRE]->port[1],
1659 s->key[PF_SK_WIRE]->port[0],
1660 s->src.seqhi, s->src.seqlo + 1,
1661 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1664 LIST_REMOVE(s, entry);
1665 pf_src_tree_remove_state(s);
1667 if (V_pfsync_delete_state_ptr != NULL)
1668 V_pfsync_delete_state_ptr(s);
1670 STATE_DEC_COUNTERS(s);
1672 s->timeout = PFTM_UNLINKED;
1674 PF_HASHROW_UNLOCK(ih);
1677 refcount_release(&s->refs);
1679 return (pf_release_state(s));
1683 pf_free_state(struct pf_state *cur)
1686 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1687 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1690 pf_normalize_tcp_cleanup(cur);
1691 uma_zfree(V_pf_state_z, cur);
1692 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1696 * Called only from pf_purge_thread(), thus serialized.
1699 pf_purge_expired_states(u_int i, int maxcheck)
1701 struct pf_idhash *ih;
1704 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1707 * Go through hash and unlink states that expire now.
1709 while (maxcheck > 0) {
1711 ih = &V_pf_idhash[i];
1713 /* only take the lock if we expect to do work */
1714 if (!LIST_EMPTY(&ih->states)) {
1716 PF_HASHROW_LOCK(ih);
1717 LIST_FOREACH(s, &ih->states, entry) {
1718 if (pf_state_expires(s) <= time_uptime) {
1719 V_pf_status.states -=
1720 pf_unlink_state(s, PF_ENTER_LOCKED);
1723 s->rule.ptr->rule_flag |= PFRULE_REFS;
1724 if (s->nat_rule.ptr != NULL)
1725 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1726 if (s->anchor.ptr != NULL)
1727 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1728 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1730 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1732 PF_HASHROW_UNLOCK(ih);
1735 /* Return when we hit end of hash. */
1736 if (++i > pf_hashmask) {
1737 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1744 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1750 pf_purge_unlinked_rules()
1752 struct pf_rulequeue tmpq;
1753 struct pf_rule *r, *r1;
1756 * If we have overloading task pending, then we'd
1757 * better skip purging this time. There is a tiny
1758 * probability that overloading task references
1759 * an already unlinked rule.
1761 PF_OVERLOADQ_LOCK();
1762 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1763 PF_OVERLOADQ_UNLOCK();
1766 PF_OVERLOADQ_UNLOCK();
1769 * Do naive mark-and-sweep garbage collecting of old rules.
1770 * Reference flag is raised by pf_purge_expired_states()
1771 * and pf_purge_expired_src_nodes().
1773 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1774 * use a temporary queue.
1777 PF_UNLNKDRULES_LOCK();
1778 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1779 if (!(r->rule_flag & PFRULE_REFS)) {
1780 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1781 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1783 r->rule_flag &= ~PFRULE_REFS;
1785 PF_UNLNKDRULES_UNLOCK();
1787 if (!TAILQ_EMPTY(&tmpq)) {
1789 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1790 TAILQ_REMOVE(&tmpq, r, entries);
1798 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1803 u_int32_t a = ntohl(addr->addr32[0]);
1804 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1816 u_int8_t i, curstart, curend, maxstart, maxend;
1817 curstart = curend = maxstart = maxend = 255;
1818 for (i = 0; i < 8; i++) {
1819 if (!addr->addr16[i]) {
1820 if (curstart == 255)
1824 if ((curend - curstart) >
1825 (maxend - maxstart)) {
1826 maxstart = curstart;
1829 curstart = curend = 255;
1832 if ((curend - curstart) >
1833 (maxend - maxstart)) {
1834 maxstart = curstart;
1837 for (i = 0; i < 8; i++) {
1838 if (i >= maxstart && i <= maxend) {
1844 b = ntohs(addr->addr16[i]);
1861 pf_print_state(struct pf_state *s)
1863 pf_print_state_parts(s, NULL, NULL);
1867 pf_print_state_parts(struct pf_state *s,
1868 struct pf_state_key *skwp, struct pf_state_key *sksp)
1870 struct pf_state_key *skw, *sks;
1871 u_int8_t proto, dir;
1873 /* Do our best to fill these, but they're skipped if NULL */
1874 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1875 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1876 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1877 dir = s ? s->direction : 0;
1895 case IPPROTO_ICMPV6:
1899 printf("%u", proto);
1912 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1914 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1919 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1921 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1926 if (proto == IPPROTO_TCP) {
1927 printf(" [lo=%u high=%u win=%u modulator=%u",
1928 s->src.seqlo, s->src.seqhi,
1929 s->src.max_win, s->src.seqdiff);
1930 if (s->src.wscale && s->dst.wscale)
1931 printf(" wscale=%u",
1932 s->src.wscale & PF_WSCALE_MASK);
1934 printf(" [lo=%u high=%u win=%u modulator=%u",
1935 s->dst.seqlo, s->dst.seqhi,
1936 s->dst.max_win, s->dst.seqdiff);
1937 if (s->src.wscale && s->dst.wscale)
1938 printf(" wscale=%u",
1939 s->dst.wscale & PF_WSCALE_MASK);
1942 printf(" %u:%u", s->src.state, s->dst.state);
1947 pf_print_flags(u_int8_t f)
1969 #define PF_SET_SKIP_STEPS(i) \
1971 while (head[i] != cur) { \
1972 head[i]->skip[i].ptr = cur; \
1973 head[i] = TAILQ_NEXT(head[i], entries); \
1978 pf_calc_skip_steps(struct pf_rulequeue *rules)
1980 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1983 cur = TAILQ_FIRST(rules);
1985 for (i = 0; i < PF_SKIP_COUNT; ++i)
1987 while (cur != NULL) {
1989 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1990 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1991 if (cur->direction != prev->direction)
1992 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1993 if (cur->af != prev->af)
1994 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1995 if (cur->proto != prev->proto)
1996 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1997 if (cur->src.neg != prev->src.neg ||
1998 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1999 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2000 if (cur->src.port[0] != prev->src.port[0] ||
2001 cur->src.port[1] != prev->src.port[1] ||
2002 cur->src.port_op != prev->src.port_op)
2003 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2004 if (cur->dst.neg != prev->dst.neg ||
2005 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2006 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2007 if (cur->dst.port[0] != prev->dst.port[0] ||
2008 cur->dst.port[1] != prev->dst.port[1] ||
2009 cur->dst.port_op != prev->dst.port_op)
2010 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2013 cur = TAILQ_NEXT(cur, entries);
2015 for (i = 0; i < PF_SKIP_COUNT; ++i)
2016 PF_SET_SKIP_STEPS(i);
2020 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2022 if (aw1->type != aw2->type)
2024 switch (aw1->type) {
2025 case PF_ADDR_ADDRMASK:
2027 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2029 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2032 case PF_ADDR_DYNIFTL:
2033 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2034 case PF_ADDR_NOROUTE:
2035 case PF_ADDR_URPFFAILED:
2038 return (aw1->p.tbl != aw2->p.tbl);
2040 printf("invalid address type: %d\n", aw1->type);
2046 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2047 * header isn't always a full checksum. In some cases (i.e. output) it's a
2048 * pseudo-header checksum, which is a partial checksum over src/dst IP
2049 * addresses, protocol number and length.
2051 * That means we have the following cases:
2052 * * Input or forwarding: we don't have TSO, the checksum fields are full
2053 * checksums, we need to update the checksum whenever we change anything.
2054 * * Output (i.e. the checksum is a pseudo-header checksum):
2055 * x The field being updated is src/dst address or affects the length of
2056 * the packet. We need to update the pseudo-header checksum (note that this
2057 * checksum is not ones' complement).
2058 * x Some other field is being modified (e.g. src/dst port numbers): We
2059 * don't have to update anything.
2062 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2068 l = cksum + old - new;
2069 l = (l >> 16) + (l & 65535);
2077 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2078 u_int16_t new, u_int8_t udp)
2080 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2083 return (pf_cksum_fixup(cksum, old, new, udp));
2087 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2088 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2094 PF_ACPY(&ao, a, af);
2097 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2105 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2106 ao.addr16[0], an->addr16[0], 0),
2107 ao.addr16[1], an->addr16[1], 0);
2110 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2111 ao.addr16[0], an->addr16[0], u),
2112 ao.addr16[1], an->addr16[1], u);
2114 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2119 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2120 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2121 pf_cksum_fixup(pf_cksum_fixup(*pc,
2122 ao.addr16[0], an->addr16[0], u),
2123 ao.addr16[1], an->addr16[1], u),
2124 ao.addr16[2], an->addr16[2], u),
2125 ao.addr16[3], an->addr16[3], u),
2126 ao.addr16[4], an->addr16[4], u),
2127 ao.addr16[5], an->addr16[5], u),
2128 ao.addr16[6], an->addr16[6], u),
2129 ao.addr16[7], an->addr16[7], u);
2131 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2136 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2137 CSUM_DELAY_DATA_IPV6)) {
2144 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2146 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2150 memcpy(&ao, a, sizeof(ao));
2151 memcpy(a, &an, sizeof(u_int32_t));
2152 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2153 ao % 65536, an % 65536, u);
2157 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2161 memcpy(&ao, a, sizeof(ao));
2162 memcpy(a, &an, sizeof(u_int32_t));
2164 *c = pf_proto_cksum_fixup(m,
2165 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2166 ao % 65536, an % 65536, udp);
2171 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2175 PF_ACPY(&ao, a, AF_INET6);
2176 PF_ACPY(a, an, AF_INET6);
2178 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2179 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2180 pf_cksum_fixup(pf_cksum_fixup(*c,
2181 ao.addr16[0], an->addr16[0], u),
2182 ao.addr16[1], an->addr16[1], u),
2183 ao.addr16[2], an->addr16[2], u),
2184 ao.addr16[3], an->addr16[3], u),
2185 ao.addr16[4], an->addr16[4], u),
2186 ao.addr16[5], an->addr16[5], u),
2187 ao.addr16[6], an->addr16[6], u),
2188 ao.addr16[7], an->addr16[7], u);
2193 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2194 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2195 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2197 struct pf_addr oia, ooa;
2199 PF_ACPY(&oia, ia, af);
2201 PF_ACPY(&ooa, oa, af);
2203 /* Change inner protocol port, fix inner protocol checksum. */
2205 u_int16_t oip = *ip;
2212 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2213 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2215 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2217 /* Change inner ip address, fix inner ip and icmp checksums. */
2218 PF_ACPY(ia, na, af);
2222 u_int32_t oh2c = *h2c;
2224 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2225 oia.addr16[0], ia->addr16[0], 0),
2226 oia.addr16[1], ia->addr16[1], 0);
2227 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2228 oia.addr16[0], ia->addr16[0], 0),
2229 oia.addr16[1], ia->addr16[1], 0);
2230 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2236 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2237 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2238 pf_cksum_fixup(pf_cksum_fixup(*ic,
2239 oia.addr16[0], ia->addr16[0], u),
2240 oia.addr16[1], ia->addr16[1], u),
2241 oia.addr16[2], ia->addr16[2], u),
2242 oia.addr16[3], ia->addr16[3], u),
2243 oia.addr16[4], ia->addr16[4], u),
2244 oia.addr16[5], ia->addr16[5], u),
2245 oia.addr16[6], ia->addr16[6], u),
2246 oia.addr16[7], ia->addr16[7], u);
2250 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2252 PF_ACPY(oa, na, af);
2256 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2257 ooa.addr16[0], oa->addr16[0], 0),
2258 ooa.addr16[1], oa->addr16[1], 0);
2263 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2264 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2265 pf_cksum_fixup(pf_cksum_fixup(*ic,
2266 ooa.addr16[0], oa->addr16[0], u),
2267 ooa.addr16[1], oa->addr16[1], u),
2268 ooa.addr16[2], oa->addr16[2], u),
2269 ooa.addr16[3], oa->addr16[3], u),
2270 ooa.addr16[4], oa->addr16[4], u),
2271 ooa.addr16[5], oa->addr16[5], u),
2272 ooa.addr16[6], oa->addr16[6], u),
2273 ooa.addr16[7], oa->addr16[7], u);
2282 * Need to modulate the sequence numbers in the TCP SACK option
2283 * (credits to Krzysztof Pfaff for report and patch)
2286 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2287 struct tcphdr *th, struct pf_state_peer *dst)
2289 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2290 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2291 int copyback = 0, i, olen;
2292 struct sackblk sack;
2294 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2295 if (hlen < TCPOLEN_SACKLEN ||
2296 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2299 while (hlen >= TCPOLEN_SACKLEN) {
2302 case TCPOPT_EOL: /* FALLTHROUGH */
2310 if (olen >= TCPOLEN_SACKLEN) {
2311 for (i = 2; i + TCPOLEN_SACK <= olen;
2312 i += TCPOLEN_SACK) {
2313 memcpy(&sack, &opt[i], sizeof(sack));
2314 pf_change_proto_a(m, &sack.start, &th->th_sum,
2315 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2316 pf_change_proto_a(m, &sack.end, &th->th_sum,
2317 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2318 memcpy(&opt[i], &sack, sizeof(sack));
2332 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2337 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2338 const struct pf_addr *saddr, const struct pf_addr *daddr,
2339 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2340 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2341 u_int16_t rtag, struct ifnet *ifp)
2343 struct pf_send_entry *pfse;
2347 struct ip *h = NULL;
2350 struct ip6_hdr *h6 = NULL;
2354 struct pf_mtag *pf_mtag;
2359 /* maximum segment size tcp option */
2360 tlen = sizeof(struct tcphdr);
2367 len = sizeof(struct ip) + tlen;
2372 len = sizeof(struct ip6_hdr) + tlen;
2376 panic("%s: unsupported af %d", __func__, af);
2379 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2380 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2383 m = m_gethdr(M_NOWAIT, MT_DATA);
2385 free(pfse, M_PFTEMP);
2389 mac_netinet_firewall_send(m);
2391 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2392 free(pfse, M_PFTEMP);
2397 m->m_flags |= M_SKIP_FIREWALL;
2398 pf_mtag->tag = rtag;
2400 if (r != NULL && r->rtableid >= 0)
2401 M_SETFIB(m, r->rtableid);
2404 if (r != NULL && r->qid) {
2405 pf_mtag->qid = r->qid;
2407 /* add hints for ecn */
2408 pf_mtag->hdr = mtod(m, struct ip *);
2411 m->m_data += max_linkhdr;
2412 m->m_pkthdr.len = m->m_len = len;
2413 m->m_pkthdr.rcvif = NULL;
2414 bzero(m->m_data, len);
2418 h = mtod(m, struct ip *);
2420 /* IP header fields included in the TCP checksum */
2421 h->ip_p = IPPROTO_TCP;
2422 h->ip_len = htons(tlen);
2423 h->ip_src.s_addr = saddr->v4.s_addr;
2424 h->ip_dst.s_addr = daddr->v4.s_addr;
2426 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2431 h6 = mtod(m, struct ip6_hdr *);
2433 /* IP header fields included in the TCP checksum */
2434 h6->ip6_nxt = IPPROTO_TCP;
2435 h6->ip6_plen = htons(tlen);
2436 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2437 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2439 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2445 th->th_sport = sport;
2446 th->th_dport = dport;
2447 th->th_seq = htonl(seq);
2448 th->th_ack = htonl(ack);
2449 th->th_off = tlen >> 2;
2450 th->th_flags = flags;
2451 th->th_win = htons(win);
2454 opt = (char *)(th + 1);
2455 opt[0] = TCPOPT_MAXSEG;
2458 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2465 th->th_sum = in_cksum(m, len);
2467 /* Finish the IP header */
2469 h->ip_hl = sizeof(*h) >> 2;
2470 h->ip_tos = IPTOS_LOWDELAY;
2471 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2472 h->ip_len = htons(len);
2473 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2476 pfse->pfse_type = PFSE_IP;
2482 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2483 sizeof(struct ip6_hdr), tlen);
2485 h6->ip6_vfc |= IPV6_VERSION;
2486 h6->ip6_hlim = IPV6_DEFHLIM;
2488 pfse->pfse_type = PFSE_IP6;
2497 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2498 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2499 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2502 struct pf_addr * const saddr = pd->src;
2503 struct pf_addr * const daddr = pd->dst;
2504 sa_family_t af = pd->af;
2506 /* undo NAT changes, if they have taken place */
2508 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2509 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2511 *pd->sport = sk->port[pd->sidx];
2513 *pd->dport = sk->port[pd->didx];
2515 *pd->proto_sum = bproto_sum;
2517 *pd->ip_sum = bip_sum;
2518 m_copyback(m, off, hdrlen, pd->hdr.any);
2520 if (pd->proto == IPPROTO_TCP &&
2521 ((r->rule_flag & PFRULE_RETURNRST) ||
2522 (r->rule_flag & PFRULE_RETURN)) &&
2523 !(th->th_flags & TH_RST)) {
2524 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2536 h4 = mtod(m, struct ip *);
2537 len = ntohs(h4->ip_len) - off;
2542 h6 = mtod(m, struct ip6_hdr *);
2543 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2548 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2549 REASON_SET(reason, PFRES_PROTCKSUM);
2551 if (th->th_flags & TH_SYN)
2553 if (th->th_flags & TH_FIN)
2555 pf_send_tcp(m, r, af, pd->dst,
2556 pd->src, th->th_dport, th->th_sport,
2557 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2558 r->return_ttl, 1, 0, kif->pfik_ifp);
2560 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2562 pf_send_icmp(m, r->return_icmp >> 8,
2563 r->return_icmp & 255, af, r);
2564 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2566 pf_send_icmp(m, r->return_icmp6 >> 8,
2567 r->return_icmp6 & 255, af, r);
2572 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2576 KASSERT(prio <= PF_PRIO_MAX,
2577 ("%s with invalid pcp", __func__));
2579 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2581 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2582 sizeof(uint8_t), M_NOWAIT);
2585 m_tag_prepend(m, mtag);
2588 *(uint8_t *)(mtag + 1) = prio;
2593 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2598 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2602 if (prio == PF_PRIO_ZERO)
2605 mpcp = *(uint8_t *)(mtag + 1);
2607 return (mpcp == prio);
2611 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2614 struct pf_send_entry *pfse;
2616 struct pf_mtag *pf_mtag;
2618 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2619 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2623 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2624 free(pfse, M_PFTEMP);
2628 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2629 free(pfse, M_PFTEMP);
2633 m0->m_flags |= M_SKIP_FIREWALL;
2635 if (r->rtableid >= 0)
2636 M_SETFIB(m0, r->rtableid);
2640 pf_mtag->qid = r->qid;
2641 /* add hints for ecn */
2642 pf_mtag->hdr = mtod(m0, struct ip *);
2649 pfse->pfse_type = PFSE_ICMP;
2654 pfse->pfse_type = PFSE_ICMP6;
2659 pfse->icmpopts.type = type;
2660 pfse->icmpopts.code = code;
2665 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2666 * If n is 0, they match if they are equal. If n is != 0, they match if they
2670 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2671 struct pf_addr *b, sa_family_t af)
2678 if ((a->addr32[0] & m->addr32[0]) ==
2679 (b->addr32[0] & m->addr32[0]))
2685 if (((a->addr32[0] & m->addr32[0]) ==
2686 (b->addr32[0] & m->addr32[0])) &&
2687 ((a->addr32[1] & m->addr32[1]) ==
2688 (b->addr32[1] & m->addr32[1])) &&
2689 ((a->addr32[2] & m->addr32[2]) ==
2690 (b->addr32[2] & m->addr32[2])) &&
2691 ((a->addr32[3] & m->addr32[3]) ==
2692 (b->addr32[3] & m->addr32[3])))
2711 * Return 1 if b <= a <= e, otherwise return 0.
2714 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2715 struct pf_addr *a, sa_family_t af)
2720 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2721 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2730 for (i = 0; i < 4; ++i)
2731 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2733 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2736 for (i = 0; i < 4; ++i)
2737 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2739 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2749 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2753 return ((p > a1) && (p < a2));
2755 return ((p < a1) || (p > a2));
2757 return ((p >= a1) && (p <= a2));
2771 return (0); /* never reached */
2775 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2780 return (pf_match(op, a1, a2, p));
2784 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2786 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2788 return (pf_match(op, a1, a2, u));
2792 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2794 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2796 return (pf_match(op, a1, a2, g));
2800 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2805 return ((!r->match_tag_not && r->match_tag == *tag) ||
2806 (r->match_tag_not && r->match_tag != *tag));
2810 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2813 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2815 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2818 pd->pf_mtag->tag = tag;
2823 #define PF_ANCHOR_STACKSIZE 32
2824 struct pf_anchor_stackframe {
2825 struct pf_ruleset *rs;
2826 struct pf_rule *r; /* XXX: + match bit */
2827 struct pf_anchor *child;
2831 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2833 #define PF_ANCHORSTACK_MATCH 0x00000001
2834 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2836 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2837 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2838 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2839 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2840 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2844 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2845 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2848 struct pf_anchor_stackframe *f;
2854 if (*depth >= PF_ANCHOR_STACKSIZE) {
2855 printf("%s: anchor stack overflow on %s\n",
2856 __func__, (*r)->anchor->name);
2857 *r = TAILQ_NEXT(*r, entries);
2859 } else if (*depth == 0 && a != NULL)
2861 f = stack + (*depth)++;
2864 if ((*r)->anchor_wildcard) {
2865 struct pf_anchor_node *parent = &(*r)->anchor->children;
2867 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2871 *rs = &f->child->ruleset;
2874 *rs = &(*r)->anchor->ruleset;
2876 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2880 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2881 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2884 struct pf_anchor_stackframe *f;
2893 f = stack + *depth - 1;
2894 fr = PF_ANCHOR_RULE(f);
2895 if (f->child != NULL) {
2896 struct pf_anchor_node *parent;
2899 * This block traverses through
2900 * a wildcard anchor.
2902 parent = &fr->anchor->children;
2903 if (match != NULL && *match) {
2905 * If any of "*" matched, then
2906 * "foo/ *" matched, mark frame
2909 PF_ANCHOR_SET_MATCH(f);
2912 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2913 if (f->child != NULL) {
2914 *rs = &f->child->ruleset;
2915 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2923 if (*depth == 0 && a != NULL)
2926 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2928 *r = TAILQ_NEXT(fr, entries);
2929 } while (*r == NULL);
2936 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2937 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2942 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2943 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2947 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2948 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2949 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2950 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2951 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2952 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2953 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2954 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2960 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2965 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2969 if (addr->addr32[3] == 0xffffffff) {
2970 addr->addr32[3] = 0;
2971 if (addr->addr32[2] == 0xffffffff) {
2972 addr->addr32[2] = 0;
2973 if (addr->addr32[1] == 0xffffffff) {
2974 addr->addr32[1] = 0;
2976 htonl(ntohl(addr->addr32[0]) + 1);
2979 htonl(ntohl(addr->addr32[1]) + 1);
2982 htonl(ntohl(addr->addr32[2]) + 1);
2985 htonl(ntohl(addr->addr32[3]) + 1);
2992 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2994 struct pf_addr *saddr, *daddr;
2995 u_int16_t sport, dport;
2996 struct inpcbinfo *pi;
2999 pd->lookup.uid = UID_MAX;
3000 pd->lookup.gid = GID_MAX;
3002 switch (pd->proto) {
3004 if (pd->hdr.tcp == NULL)
3006 sport = pd->hdr.tcp->th_sport;
3007 dport = pd->hdr.tcp->th_dport;
3011 if (pd->hdr.udp == NULL)
3013 sport = pd->hdr.udp->uh_sport;
3014 dport = pd->hdr.udp->uh_dport;
3020 if (direction == PF_IN) {
3035 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3036 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3038 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3039 daddr->v4, dport, INPLOOKUP_WILDCARD |
3040 INPLOOKUP_RLOCKPCB, NULL, m);
3048 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3049 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3051 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3052 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3053 INPLOOKUP_RLOCKPCB, NULL, m);
3063 INP_RLOCK_ASSERT(inp);
3064 pd->lookup.uid = inp->inp_cred->cr_uid;
3065 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3072 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3076 u_int8_t *opt, optlen;
3077 u_int8_t wscale = 0;
3079 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3080 if (hlen <= sizeof(struct tcphdr))
3082 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3084 opt = hdr + sizeof(struct tcphdr);
3085 hlen -= sizeof(struct tcphdr);
3095 if (wscale > TCP_MAX_WINSHIFT)
3096 wscale = TCP_MAX_WINSHIFT;
3097 wscale |= PF_WSCALE_FLAG;
3112 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3116 u_int8_t *opt, optlen;
3117 u_int16_t mss = V_tcp_mssdflt;
3119 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3120 if (hlen <= sizeof(struct tcphdr))
3122 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3124 opt = hdr + sizeof(struct tcphdr);
3125 hlen -= sizeof(struct tcphdr);
3126 while (hlen >= TCPOLEN_MAXSEG) {
3134 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3150 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3153 struct nhop4_basic nh4;
3156 struct nhop6_basic nh6;
3157 struct in6_addr dst6;
3166 hlen = sizeof(struct ip);
3167 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3168 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3173 hlen = sizeof(struct ip6_hdr);
3174 in6_splitscope(&addr->v6, &dst6, &scopeid);
3175 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3176 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3181 mss = max(V_tcp_mssdflt, mss);
3182 mss = min(mss, offer);
3183 mss = max(mss, 64); /* sanity - at least max opt space */
3188 pf_tcp_iss(struct pf_pdesc *pd)
3191 u_int32_t digest[4];
3193 if (V_pf_tcp_secret_init == 0) {
3194 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3195 MD5Init(&V_pf_tcp_secret_ctx);
3196 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3197 sizeof(V_pf_tcp_secret));
3198 V_pf_tcp_secret_init = 1;
3201 ctx = V_pf_tcp_secret_ctx;
3203 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3204 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3205 if (pd->af == AF_INET6) {
3206 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3207 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3209 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3210 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3212 MD5Final((u_char *)digest, &ctx);
3213 V_pf_tcp_iss_off += 4096;
3214 #define ISN_RANDOM_INCREMENT (4096 - 1)
3215 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3217 #undef ISN_RANDOM_INCREMENT
3221 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3222 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3223 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3225 struct pf_rule *nr = NULL;
3226 struct pf_addr * const saddr = pd->src;
3227 struct pf_addr * const daddr = pd->dst;
3228 sa_family_t af = pd->af;
3229 struct pf_rule *r, *a = NULL;
3230 struct pf_ruleset *ruleset = NULL;
3231 struct pf_src_node *nsn = NULL;
3232 struct tcphdr *th = pd->hdr.tcp;
3233 struct pf_state_key *sk = NULL, *nk = NULL;
3235 int rewrite = 0, hdrlen = 0;
3236 int tag = -1, rtableid = -1;
3240 u_int16_t sport = 0, dport = 0;
3241 u_int16_t bproto_sum = 0, bip_sum = 0;
3242 u_int8_t icmptype = 0, icmpcode = 0;
3243 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3248 INP_LOCK_ASSERT(inp);
3249 pd->lookup.uid = inp->inp_cred->cr_uid;
3250 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3251 pd->lookup.done = 1;
3254 switch (pd->proto) {
3256 sport = th->th_sport;
3257 dport = th->th_dport;
3258 hdrlen = sizeof(*th);
3261 sport = pd->hdr.udp->uh_sport;
3262 dport = pd->hdr.udp->uh_dport;
3263 hdrlen = sizeof(*pd->hdr.udp);
3267 if (pd->af != AF_INET)
3269 sport = dport = pd->hdr.icmp->icmp_id;
3270 hdrlen = sizeof(*pd->hdr.icmp);
3271 icmptype = pd->hdr.icmp->icmp_type;
3272 icmpcode = pd->hdr.icmp->icmp_code;
3274 if (icmptype == ICMP_UNREACH ||
3275 icmptype == ICMP_SOURCEQUENCH ||
3276 icmptype == ICMP_REDIRECT ||
3277 icmptype == ICMP_TIMXCEED ||
3278 icmptype == ICMP_PARAMPROB)
3283 case IPPROTO_ICMPV6:
3286 sport = dport = pd->hdr.icmp6->icmp6_id;
3287 hdrlen = sizeof(*pd->hdr.icmp6);
3288 icmptype = pd->hdr.icmp6->icmp6_type;
3289 icmpcode = pd->hdr.icmp6->icmp6_code;
3291 if (icmptype == ICMP6_DST_UNREACH ||
3292 icmptype == ICMP6_PACKET_TOO_BIG ||
3293 icmptype == ICMP6_TIME_EXCEEDED ||
3294 icmptype == ICMP6_PARAM_PROB)
3299 sport = dport = hdrlen = 0;
3303 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3305 /* check packet for BINAT/NAT/RDR */
3306 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3307 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3308 KASSERT(sk != NULL, ("%s: null sk", __func__));
3309 KASSERT(nk != NULL, ("%s: null nk", __func__));
3312 bip_sum = *pd->ip_sum;
3314 switch (pd->proto) {
3316 bproto_sum = th->th_sum;
3317 pd->proto_sum = &th->th_sum;
3319 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3320 nk->port[pd->sidx] != sport) {
3321 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3322 &th->th_sum, &nk->addr[pd->sidx],
3323 nk->port[pd->sidx], 0, af);
3324 pd->sport = &th->th_sport;
3325 sport = th->th_sport;
3328 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3329 nk->port[pd->didx] != dport) {
3330 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3331 &th->th_sum, &nk->addr[pd->didx],
3332 nk->port[pd->didx], 0, af);
3333 dport = th->th_dport;
3334 pd->dport = &th->th_dport;
3339 bproto_sum = pd->hdr.udp->uh_sum;
3340 pd->proto_sum = &pd->hdr.udp->uh_sum;
3342 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3343 nk->port[pd->sidx] != sport) {
3344 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3345 pd->ip_sum, &pd->hdr.udp->uh_sum,
3346 &nk->addr[pd->sidx],
3347 nk->port[pd->sidx], 1, af);
3348 sport = pd->hdr.udp->uh_sport;
3349 pd->sport = &pd->hdr.udp->uh_sport;
3352 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3353 nk->port[pd->didx] != dport) {
3354 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3355 pd->ip_sum, &pd->hdr.udp->uh_sum,
3356 &nk->addr[pd->didx],
3357 nk->port[pd->didx], 1, af);
3358 dport = pd->hdr.udp->uh_dport;
3359 pd->dport = &pd->hdr.udp->uh_dport;
3365 nk->port[0] = nk->port[1];
3366 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3367 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3368 nk->addr[pd->sidx].v4.s_addr, 0);
3370 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3371 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3372 nk->addr[pd->didx].v4.s_addr, 0);
3374 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3375 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3376 pd->hdr.icmp->icmp_cksum, sport,
3378 pd->hdr.icmp->icmp_id = nk->port[1];
3379 pd->sport = &pd->hdr.icmp->icmp_id;
3381 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3385 case IPPROTO_ICMPV6:
3386 nk->port[0] = nk->port[1];
3387 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3388 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3389 &nk->addr[pd->sidx], 0);
3391 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3392 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3393 &nk->addr[pd->didx], 0);
3402 &nk->addr[pd->sidx], AF_INET))
3403 pf_change_a(&saddr->v4.s_addr,
3405 nk->addr[pd->sidx].v4.s_addr, 0);
3408 &nk->addr[pd->didx], AF_INET))
3409 pf_change_a(&daddr->v4.s_addr,
3411 nk->addr[pd->didx].v4.s_addr, 0);
3417 &nk->addr[pd->sidx], AF_INET6))
3418 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3421 &nk->addr[pd->didx], AF_INET6))
3422 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3435 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3436 r = r->skip[PF_SKIP_IFP].ptr;
3437 else if (r->direction && r->direction != direction)
3438 r = r->skip[PF_SKIP_DIR].ptr;
3439 else if (r->af && r->af != af)
3440 r = r->skip[PF_SKIP_AF].ptr;
3441 else if (r->proto && r->proto != pd->proto)
3442 r = r->skip[PF_SKIP_PROTO].ptr;
3443 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3444 r->src.neg, kif, M_GETFIB(m)))
3445 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3446 /* tcp/udp only. port_op always 0 in other cases */
3447 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3448 r->src.port[0], r->src.port[1], sport))
3449 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3450 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3451 r->dst.neg, NULL, M_GETFIB(m)))
3452 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3453 /* tcp/udp only. port_op always 0 in other cases */
3454 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3455 r->dst.port[0], r->dst.port[1], dport))
3456 r = r->skip[PF_SKIP_DST_PORT].ptr;
3457 /* icmp only. type always 0 in other cases */
3458 else if (r->type && r->type != icmptype + 1)
3459 r = TAILQ_NEXT(r, entries);
3460 /* icmp only. type always 0 in other cases */
3461 else if (r->code && r->code != icmpcode + 1)
3462 r = TAILQ_NEXT(r, entries);
3463 else if (r->tos && !(r->tos == pd->tos))
3464 r = TAILQ_NEXT(r, entries);
3465 else if (r->rule_flag & PFRULE_FRAGMENT)
3466 r = TAILQ_NEXT(r, entries);
3467 else if (pd->proto == IPPROTO_TCP &&
3468 (r->flagset & th->th_flags) != r->flags)
3469 r = TAILQ_NEXT(r, entries);
3470 /* tcp/udp only. uid.op always 0 in other cases */
3471 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3472 pf_socket_lookup(direction, pd, m), 1)) &&
3473 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3475 r = TAILQ_NEXT(r, entries);
3476 /* tcp/udp only. gid.op always 0 in other cases */
3477 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3478 pf_socket_lookup(direction, pd, m), 1)) &&
3479 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3481 r = TAILQ_NEXT(r, entries);
3483 !pf_match_ieee8021q_pcp(r->prio, m))
3484 r = TAILQ_NEXT(r, entries);
3486 r->prob <= arc4random())
3487 r = TAILQ_NEXT(r, entries);
3488 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3489 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3490 r = TAILQ_NEXT(r, entries);
3491 else if (r->os_fingerprint != PF_OSFP_ANY &&
3492 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3493 pf_osfp_fingerprint(pd, m, off, th),
3494 r->os_fingerprint)))
3495 r = TAILQ_NEXT(r, entries);
3499 if (r->rtableid >= 0)
3500 rtableid = r->rtableid;
3501 if (r->anchor == NULL) {
3508 r = TAILQ_NEXT(r, entries);
3510 pf_step_into_anchor(anchor_stack, &asd,
3511 &ruleset, PF_RULESET_FILTER, &r, &a,
3514 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3515 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3522 REASON_SET(&reason, PFRES_MATCH);
3524 if (r->log || (nr != NULL && nr->log)) {
3526 m_copyback(m, off, hdrlen, pd->hdr.any);
3527 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3531 if ((r->action == PF_DROP) &&
3532 ((r->rule_flag & PFRULE_RETURNRST) ||
3533 (r->rule_flag & PFRULE_RETURNICMP) ||
3534 (r->rule_flag & PFRULE_RETURN))) {
3535 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3536 bip_sum, hdrlen, &reason);
3539 if (r->action == PF_DROP)
3542 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3543 REASON_SET(&reason, PFRES_MEMORY);
3547 M_SETFIB(m, rtableid);
3549 if (!state_icmp && (r->keep_state || nr != NULL ||
3550 (pd->flags & PFDESC_TCP_NORM))) {
3552 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3553 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3555 if (action != PF_PASS) {
3556 if (action == PF_DROP &&
3557 (r->rule_flag & PFRULE_RETURN))
3558 pf_return(r, nr, pd, sk, off, m, th, kif,
3559 bproto_sum, bip_sum, hdrlen, &reason);
3564 uma_zfree(V_pf_state_key_z, sk);
3566 uma_zfree(V_pf_state_key_z, nk);
3569 /* copy back packet headers if we performed NAT operations */
3571 m_copyback(m, off, hdrlen, pd->hdr.any);
3573 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3574 direction == PF_OUT &&
3575 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3577 * We want the state created, but we dont
3578 * want to send this in case a partner
3579 * firewall has to know about it to allow
3580 * replies through it.
3588 uma_zfree(V_pf_state_key_z, sk);
3590 uma_zfree(V_pf_state_key_z, nk);
3595 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3596 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3597 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3598 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3599 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3601 struct pf_state *s = NULL;
3602 struct pf_src_node *sn = NULL;
3603 struct tcphdr *th = pd->hdr.tcp;
3604 u_int16_t mss = V_tcp_mssdflt;
3607 /* check maximums */
3608 if (r->max_states &&
3609 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3610 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3611 REASON_SET(&reason, PFRES_MAXSTATES);
3614 /* src node for filter rule */
3615 if ((r->rule_flag & PFRULE_SRCTRACK ||
3616 r->rpool.opts & PF_POOL_STICKYADDR) &&
3617 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3618 REASON_SET(&reason, PFRES_SRCLIMIT);
3621 /* src node for translation rule */
3622 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3623 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3624 REASON_SET(&reason, PFRES_SRCLIMIT);
3627 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3629 REASON_SET(&reason, PFRES_MEMORY);
3633 s->nat_rule.ptr = nr;
3635 STATE_INC_COUNTERS(s);
3637 s->state_flags |= PFSTATE_ALLOWOPTS;
3638 if (r->rule_flag & PFRULE_STATESLOPPY)
3639 s->state_flags |= PFSTATE_SLOPPY;
3640 s->log = r->log & PF_LOG_ALL;
3641 s->sync_state = PFSYNC_S_NONE;
3643 s->log |= nr->log & PF_LOG_ALL;
3644 switch (pd->proto) {
3646 s->src.seqlo = ntohl(th->th_seq);
3647 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3648 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3649 r->keep_state == PF_STATE_MODULATE) {
3650 /* Generate sequence number modulator */
3651 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3654 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3655 htonl(s->src.seqlo + s->src.seqdiff), 0);
3659 if (th->th_flags & TH_SYN) {
3661 s->src.wscale = pf_get_wscale(m, off,
3662 th->th_off, pd->af);
3664 s->src.max_win = MAX(ntohs(th->th_win), 1);
3665 if (s->src.wscale & PF_WSCALE_MASK) {
3666 /* Remove scale factor from initial window */
3667 int win = s->src.max_win;
3668 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3669 s->src.max_win = (win - 1) >>
3670 (s->src.wscale & PF_WSCALE_MASK);
3672 if (th->th_flags & TH_FIN)
3676 s->src.state = TCPS_SYN_SENT;
3677 s->dst.state = TCPS_CLOSED;
3678 s->timeout = PFTM_TCP_FIRST_PACKET;
3681 s->src.state = PFUDPS_SINGLE;
3682 s->dst.state = PFUDPS_NO_TRAFFIC;
3683 s->timeout = PFTM_UDP_FIRST_PACKET;
3687 case IPPROTO_ICMPV6:
3689 s->timeout = PFTM_ICMP_FIRST_PACKET;
3692 s->src.state = PFOTHERS_SINGLE;
3693 s->dst.state = PFOTHERS_NO_TRAFFIC;
3694 s->timeout = PFTM_OTHER_FIRST_PACKET;
3697 if (r->rt && r->rt != PF_FASTROUTE) {
3698 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3699 REASON_SET(&reason, PFRES_MAPFAILED);
3700 pf_src_tree_remove_state(s);
3701 STATE_DEC_COUNTERS(s);
3702 uma_zfree(V_pf_state_z, s);
3705 s->rt_kif = r->rpool.cur->kif;
3708 s->creation = time_uptime;
3709 s->expire = time_uptime;
3714 /* XXX We only modify one side for now. */
3715 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3716 s->nat_src_node = nsn;
3718 if (pd->proto == IPPROTO_TCP) {
3719 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3720 off, pd, th, &s->src, &s->dst)) {
3721 REASON_SET(&reason, PFRES_MEMORY);
3722 pf_src_tree_remove_state(s);
3723 STATE_DEC_COUNTERS(s);
3724 uma_zfree(V_pf_state_z, s);
3727 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3728 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3729 &s->src, &s->dst, rewrite)) {
3730 /* This really shouldn't happen!!! */
3731 DPFPRINTF(PF_DEBUG_URGENT,
3732 ("pf_normalize_tcp_stateful failed on first pkt"));
3733 pf_normalize_tcp_cleanup(s);
3734 pf_src_tree_remove_state(s);
3735 STATE_DEC_COUNTERS(s);
3736 uma_zfree(V_pf_state_z, s);
3740 s->direction = pd->dir;
3743 * sk/nk could already been setup by pf_get_translation().
3746 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3747 __func__, nr, sk, nk));
3748 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3753 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3754 __func__, nr, sk, nk));
3756 /* Swap sk/nk for PF_OUT. */
3757 if (pf_state_insert(BOUND_IFACE(r, kif),
3758 (pd->dir == PF_IN) ? sk : nk,
3759 (pd->dir == PF_IN) ? nk : sk, s)) {
3760 if (pd->proto == IPPROTO_TCP)
3761 pf_normalize_tcp_cleanup(s);
3762 REASON_SET(&reason, PFRES_STATEINS);
3763 pf_src_tree_remove_state(s);
3764 STATE_DEC_COUNTERS(s);
3765 uma_zfree(V_pf_state_z, s);
3772 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3773 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3774 s->src.state = PF_TCPS_PROXY_SRC;
3775 /* undo NAT changes, if they have taken place */
3777 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3778 if (pd->dir == PF_OUT)
3779 skt = s->key[PF_SK_STACK];
3780 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3781 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3783 *pd->sport = skt->port[pd->sidx];
3785 *pd->dport = skt->port[pd->didx];
3787 *pd->proto_sum = bproto_sum;
3789 *pd->ip_sum = bip_sum;
3790 m_copyback(m, off, hdrlen, pd->hdr.any);
3792 s->src.seqhi = htonl(arc4random());
3793 /* Find mss option */
3794 int rtid = M_GETFIB(m);
3795 mss = pf_get_mss(m, off, th->th_off, pd->af);
3796 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3797 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3799 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3800 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3801 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3802 REASON_SET(&reason, PFRES_SYNPROXY);
3803 return (PF_SYNPROXY_DROP);
3810 uma_zfree(V_pf_state_key_z, sk);
3812 uma_zfree(V_pf_state_key_z, nk);
3815 struct pf_srchash *sh;
3817 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3818 PF_HASHROW_LOCK(sh);
3819 if (--sn->states == 0 && sn->expire == 0) {
3820 pf_unlink_src_node(sn);
3821 uma_zfree(V_pf_sources_z, sn);
3823 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3825 PF_HASHROW_UNLOCK(sh);
3828 if (nsn != sn && nsn != NULL) {
3829 struct pf_srchash *sh;
3831 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3832 PF_HASHROW_LOCK(sh);
3833 if (--nsn->states == 0 && nsn->expire == 0) {
3834 pf_unlink_src_node(nsn);
3835 uma_zfree(V_pf_sources_z, nsn);
3837 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3839 PF_HASHROW_UNLOCK(sh);
3846 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3847 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3848 struct pf_ruleset **rsm)
3850 struct pf_rule *r, *a = NULL;
3851 struct pf_ruleset *ruleset = NULL;
3852 sa_family_t af = pd->af;
3857 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3861 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3864 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3865 r = r->skip[PF_SKIP_IFP].ptr;
3866 else if (r->direction && r->direction != direction)
3867 r = r->skip[PF_SKIP_DIR].ptr;
3868 else if (r->af && r->af != af)
3869 r = r->skip[PF_SKIP_AF].ptr;
3870 else if (r->proto && r->proto != pd->proto)
3871 r = r->skip[PF_SKIP_PROTO].ptr;
3872 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3873 r->src.neg, kif, M_GETFIB(m)))
3874 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3875 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3876 r->dst.neg, NULL, M_GETFIB(m)))
3877 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3878 else if (r->tos && !(r->tos == pd->tos))
3879 r = TAILQ_NEXT(r, entries);
3880 else if (r->os_fingerprint != PF_OSFP_ANY)
3881 r = TAILQ_NEXT(r, entries);
3882 else if (pd->proto == IPPROTO_UDP &&
3883 (r->src.port_op || r->dst.port_op))
3884 r = TAILQ_NEXT(r, entries);
3885 else if (pd->proto == IPPROTO_TCP &&
3886 (r->src.port_op || r->dst.port_op || r->flagset))
3887 r = TAILQ_NEXT(r, entries);
3888 else if ((pd->proto == IPPROTO_ICMP ||
3889 pd->proto == IPPROTO_ICMPV6) &&
3890 (r->type || r->code))
3891 r = TAILQ_NEXT(r, entries);
3893 !pf_match_ieee8021q_pcp(r->prio, m))
3894 r = TAILQ_NEXT(r, entries);
3895 else if (r->prob && r->prob <=
3896 (arc4random() % (UINT_MAX - 1) + 1))
3897 r = TAILQ_NEXT(r, entries);
3898 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3899 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3900 r = TAILQ_NEXT(r, entries);
3902 if (r->anchor == NULL) {
3909 r = TAILQ_NEXT(r, entries);
3911 pf_step_into_anchor(anchor_stack, &asd,
3912 &ruleset, PF_RULESET_FILTER, &r, &a,
3915 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3916 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3923 REASON_SET(&reason, PFRES_MATCH);
3926 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3929 if (r->action != PF_PASS)
3932 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3933 REASON_SET(&reason, PFRES_MEMORY);
3941 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3942 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3943 struct pf_pdesc *pd, u_short *reason, int *copyback)
3945 struct tcphdr *th = pd->hdr.tcp;
3946 u_int16_t win = ntohs(th->th_win);
3947 u_int32_t ack, end, seq, orig_seq;
3951 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3952 sws = src->wscale & PF_WSCALE_MASK;
3953 dws = dst->wscale & PF_WSCALE_MASK;
3958 * Sequence tracking algorithm from Guido van Rooij's paper:
3959 * http://www.madison-gurkha.com/publications/tcp_filtering/
3963 orig_seq = seq = ntohl(th->th_seq);
3964 if (src->seqlo == 0) {
3965 /* First packet from this end. Set its state */
3967 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3968 src->scrub == NULL) {
3969 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3970 REASON_SET(reason, PFRES_MEMORY);
3975 /* Deferred generation of sequence number modulator */
3976 if (dst->seqdiff && !src->seqdiff) {
3977 /* use random iss for the TCP server */
3978 while ((src->seqdiff = arc4random() - seq) == 0)
3980 ack = ntohl(th->th_ack) - dst->seqdiff;
3981 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3983 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3986 ack = ntohl(th->th_ack);
3989 end = seq + pd->p_len;
3990 if (th->th_flags & TH_SYN) {
3992 if (dst->wscale & PF_WSCALE_FLAG) {
3993 src->wscale = pf_get_wscale(m, off, th->th_off,
3995 if (src->wscale & PF_WSCALE_FLAG) {
3996 /* Remove scale factor from initial
3998 sws = src->wscale & PF_WSCALE_MASK;
3999 win = ((u_int32_t)win + (1 << sws) - 1)
4001 dws = dst->wscale & PF_WSCALE_MASK;
4003 /* fixup other window */
4004 dst->max_win <<= dst->wscale &
4006 /* in case of a retrans SYN|ACK */
4011 if (th->th_flags & TH_FIN)
4015 if (src->state < TCPS_SYN_SENT)
4016 src->state = TCPS_SYN_SENT;
4019 * May need to slide the window (seqhi may have been set by
4020 * the crappy stack check or if we picked up the connection
4021 * after establishment)
4023 if (src->seqhi == 1 ||
4024 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4025 src->seqhi = end + MAX(1, dst->max_win << dws);
4026 if (win > src->max_win)
4030 ack = ntohl(th->th_ack) - dst->seqdiff;
4032 /* Modulate sequence numbers */
4033 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4035 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4038 end = seq + pd->p_len;
4039 if (th->th_flags & TH_SYN)
4041 if (th->th_flags & TH_FIN)
4045 if ((th->th_flags & TH_ACK) == 0) {
4046 /* Let it pass through the ack skew check */
4048 } else if ((ack == 0 &&
4049 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4050 /* broken tcp stacks do not set ack */
4051 (dst->state < TCPS_SYN_SENT)) {
4053 * Many stacks (ours included) will set the ACK number in an
4054 * FIN|ACK if the SYN times out -- no sequence to ACK.
4060 /* Ease sequencing restrictions on no data packets */
4065 ackskew = dst->seqlo - ack;
4069 * Need to demodulate the sequence numbers in any TCP SACK options
4070 * (Selective ACK). We could optionally validate the SACK values
4071 * against the current ACK window, either forwards or backwards, but
4072 * I'm not confident that SACK has been implemented properly
4073 * everywhere. It wouldn't surprise me if several stacks accidentally
4074 * SACK too far backwards of previously ACKed data. There really aren't
4075 * any security implications of bad SACKing unless the target stack
4076 * doesn't validate the option length correctly. Someone trying to
4077 * spoof into a TCP connection won't bother blindly sending SACK
4080 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4081 if (pf_modulate_sack(m, off, pd, th, dst))
4086 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4087 if (SEQ_GEQ(src->seqhi, end) &&
4088 /* Last octet inside other's window space */
4089 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4090 /* Retrans: not more than one window back */
4091 (ackskew >= -MAXACKWINDOW) &&
4092 /* Acking not more than one reassembled fragment backwards */
4093 (ackskew <= (MAXACKWINDOW << sws)) &&
4094 /* Acking not more than one window forward */
4095 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4096 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4097 (pd->flags & PFDESC_IP_REAS) == 0)) {
4098 /* Require an exact/+1 sequence match on resets when possible */
4100 if (dst->scrub || src->scrub) {
4101 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4102 *state, src, dst, copyback))
4106 /* update max window */
4107 if (src->max_win < win)
4109 /* synchronize sequencing */
4110 if (SEQ_GT(end, src->seqlo))
4112 /* slide the window of what the other end can send */
4113 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4114 dst->seqhi = ack + MAX((win << sws), 1);
4118 if (th->th_flags & TH_SYN)
4119 if (src->state < TCPS_SYN_SENT)
4120 src->state = TCPS_SYN_SENT;
4121 if (th->th_flags & TH_FIN)
4122 if (src->state < TCPS_CLOSING)
4123 src->state = TCPS_CLOSING;
4124 if (th->th_flags & TH_ACK) {
4125 if (dst->state == TCPS_SYN_SENT) {
4126 dst->state = TCPS_ESTABLISHED;
4127 if (src->state == TCPS_ESTABLISHED &&
4128 (*state)->src_node != NULL &&
4129 pf_src_connlimit(state)) {
4130 REASON_SET(reason, PFRES_SRCLIMIT);
4133 } else if (dst->state == TCPS_CLOSING)
4134 dst->state = TCPS_FIN_WAIT_2;
4136 if (th->th_flags & TH_RST)
4137 src->state = dst->state = TCPS_TIME_WAIT;
4139 /* update expire time */
4140 (*state)->expire = time_uptime;
4141 if (src->state >= TCPS_FIN_WAIT_2 &&
4142 dst->state >= TCPS_FIN_WAIT_2)
4143 (*state)->timeout = PFTM_TCP_CLOSED;
4144 else if (src->state >= TCPS_CLOSING &&
4145 dst->state >= TCPS_CLOSING)
4146 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4147 else if (src->state < TCPS_ESTABLISHED ||
4148 dst->state < TCPS_ESTABLISHED)
4149 (*state)->timeout = PFTM_TCP_OPENING;
4150 else if (src->state >= TCPS_CLOSING ||
4151 dst->state >= TCPS_CLOSING)
4152 (*state)->timeout = PFTM_TCP_CLOSING;
4154 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4156 /* Fall through to PASS packet */
4158 } else if ((dst->state < TCPS_SYN_SENT ||
4159 dst->state >= TCPS_FIN_WAIT_2 ||
4160 src->state >= TCPS_FIN_WAIT_2) &&
4161 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4162 /* Within a window forward of the originating packet */
4163 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4164 /* Within a window backward of the originating packet */
4167 * This currently handles three situations:
4168 * 1) Stupid stacks will shotgun SYNs before their peer
4170 * 2) When PF catches an already established stream (the
4171 * firewall rebooted, the state table was flushed, routes
4173 * 3) Packets get funky immediately after the connection
4174 * closes (this should catch Solaris spurious ACK|FINs
4175 * that web servers like to spew after a close)
4177 * This must be a little more careful than the above code
4178 * since packet floods will also be caught here. We don't
4179 * update the TTL here to mitigate the damage of a packet
4180 * flood and so the same code can handle awkward establishment
4181 * and a loosened connection close.
4182 * In the establishment case, a correct peer response will
4183 * validate the connection, go through the normal state code
4184 * and keep updating the state TTL.
4187 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4188 printf("pf: loose state match: ");
4189 pf_print_state(*state);
4190 pf_print_flags(th->th_flags);
4191 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4192 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4193 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4194 (unsigned long long)(*state)->packets[1],
4195 pd->dir == PF_IN ? "in" : "out",
4196 pd->dir == (*state)->direction ? "fwd" : "rev");
4199 if (dst->scrub || src->scrub) {
4200 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4201 *state, src, dst, copyback))
4205 /* update max window */
4206 if (src->max_win < win)
4208 /* synchronize sequencing */
4209 if (SEQ_GT(end, src->seqlo))
4211 /* slide the window of what the other end can send */
4212 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4213 dst->seqhi = ack + MAX((win << sws), 1);
4216 * Cannot set dst->seqhi here since this could be a shotgunned
4217 * SYN and not an already established connection.
4220 if (th->th_flags & TH_FIN)
4221 if (src->state < TCPS_CLOSING)
4222 src->state = TCPS_CLOSING;
4223 if (th->th_flags & TH_RST)
4224 src->state = dst->state = TCPS_TIME_WAIT;
4226 /* Fall through to PASS packet */
4229 if ((*state)->dst.state == TCPS_SYN_SENT &&
4230 (*state)->src.state == TCPS_SYN_SENT) {
4231 /* Send RST for state mismatches during handshake */
4232 if (!(th->th_flags & TH_RST))
4233 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4234 pd->dst, pd->src, th->th_dport,
4235 th->th_sport, ntohl(th->th_ack), 0,
4237 (*state)->rule.ptr->return_ttl, 1, 0,
4242 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4243 printf("pf: BAD state: ");
4244 pf_print_state(*state);
4245 pf_print_flags(th->th_flags);
4246 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4247 "pkts=%llu:%llu dir=%s,%s\n",
4248 seq, orig_seq, ack, pd->p_len, ackskew,
4249 (unsigned long long)(*state)->packets[0],
4250 (unsigned long long)(*state)->packets[1],
4251 pd->dir == PF_IN ? "in" : "out",
4252 pd->dir == (*state)->direction ? "fwd" : "rev");
4253 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4254 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4255 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4257 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4258 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4259 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4260 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4262 REASON_SET(reason, PFRES_BADSTATE);
4270 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4271 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4273 struct tcphdr *th = pd->hdr.tcp;
4275 if (th->th_flags & TH_SYN)
4276 if (src->state < TCPS_SYN_SENT)
4277 src->state = TCPS_SYN_SENT;
4278 if (th->th_flags & TH_FIN)
4279 if (src->state < TCPS_CLOSING)
4280 src->state = TCPS_CLOSING;
4281 if (th->th_flags & TH_ACK) {
4282 if (dst->state == TCPS_SYN_SENT) {
4283 dst->state = TCPS_ESTABLISHED;
4284 if (src->state == TCPS_ESTABLISHED &&
4285 (*state)->src_node != NULL &&
4286 pf_src_connlimit(state)) {
4287 REASON_SET(reason, PFRES_SRCLIMIT);
4290 } else if (dst->state == TCPS_CLOSING) {
4291 dst->state = TCPS_FIN_WAIT_2;
4292 } else if (src->state == TCPS_SYN_SENT &&
4293 dst->state < TCPS_SYN_SENT) {
4295 * Handle a special sloppy case where we only see one
4296 * half of the connection. If there is a ACK after
4297 * the initial SYN without ever seeing a packet from
4298 * the destination, set the connection to established.
4300 dst->state = src->state = TCPS_ESTABLISHED;
4301 if ((*state)->src_node != NULL &&
4302 pf_src_connlimit(state)) {
4303 REASON_SET(reason, PFRES_SRCLIMIT);
4306 } else if (src->state == TCPS_CLOSING &&
4307 dst->state == TCPS_ESTABLISHED &&
4310 * Handle the closing of half connections where we
4311 * don't see the full bidirectional FIN/ACK+ACK
4314 dst->state = TCPS_CLOSING;
4317 if (th->th_flags & TH_RST)
4318 src->state = dst->state = TCPS_TIME_WAIT;
4320 /* update expire time */
4321 (*state)->expire = time_uptime;
4322 if (src->state >= TCPS_FIN_WAIT_2 &&
4323 dst->state >= TCPS_FIN_WAIT_2)
4324 (*state)->timeout = PFTM_TCP_CLOSED;
4325 else if (src->state >= TCPS_CLOSING &&
4326 dst->state >= TCPS_CLOSING)
4327 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4328 else if (src->state < TCPS_ESTABLISHED ||
4329 dst->state < TCPS_ESTABLISHED)
4330 (*state)->timeout = PFTM_TCP_OPENING;
4331 else if (src->state >= TCPS_CLOSING ||
4332 dst->state >= TCPS_CLOSING)
4333 (*state)->timeout = PFTM_TCP_CLOSING;
4335 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4341 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4342 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4345 struct pf_state_key_cmp key;
4346 struct tcphdr *th = pd->hdr.tcp;
4348 struct pf_state_peer *src, *dst;
4349 struct pf_state_key *sk;
4351 bzero(&key, sizeof(key));
4353 key.proto = IPPROTO_TCP;
4354 if (direction == PF_IN) { /* wire side, straight */
4355 PF_ACPY(&key.addr[0], pd->src, key.af);
4356 PF_ACPY(&key.addr[1], pd->dst, key.af);
4357 key.port[0] = th->th_sport;
4358 key.port[1] = th->th_dport;
4359 } else { /* stack side, reverse */
4360 PF_ACPY(&key.addr[1], pd->src, key.af);
4361 PF_ACPY(&key.addr[0], pd->dst, key.af);
4362 key.port[1] = th->th_sport;
4363 key.port[0] = th->th_dport;
4366 STATE_LOOKUP(kif, &key, direction, *state, pd);
4368 if (direction == (*state)->direction) {
4369 src = &(*state)->src;
4370 dst = &(*state)->dst;
4372 src = &(*state)->dst;
4373 dst = &(*state)->src;
4376 sk = (*state)->key[pd->didx];
4378 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4379 if (direction != (*state)->direction) {
4380 REASON_SET(reason, PFRES_SYNPROXY);
4381 return (PF_SYNPROXY_DROP);
4383 if (th->th_flags & TH_SYN) {
4384 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4385 REASON_SET(reason, PFRES_SYNPROXY);
4388 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4389 pd->src, th->th_dport, th->th_sport,
4390 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4391 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4392 REASON_SET(reason, PFRES_SYNPROXY);
4393 return (PF_SYNPROXY_DROP);
4394 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4395 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4396 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4397 REASON_SET(reason, PFRES_SYNPROXY);
4399 } else if ((*state)->src_node != NULL &&
4400 pf_src_connlimit(state)) {
4401 REASON_SET(reason, PFRES_SRCLIMIT);
4404 (*state)->src.state = PF_TCPS_PROXY_DST;
4406 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4407 if (direction == (*state)->direction) {
4408 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4409 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4410 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4411 REASON_SET(reason, PFRES_SYNPROXY);
4414 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4415 if ((*state)->dst.seqhi == 1)
4416 (*state)->dst.seqhi = htonl(arc4random());
4417 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4418 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4419 sk->port[pd->sidx], sk->port[pd->didx],
4420 (*state)->dst.seqhi, 0, TH_SYN, 0,
4421 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4422 REASON_SET(reason, PFRES_SYNPROXY);
4423 return (PF_SYNPROXY_DROP);
4424 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4426 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4427 REASON_SET(reason, PFRES_SYNPROXY);
4430 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4431 (*state)->dst.seqlo = ntohl(th->th_seq);
4432 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4433 pd->src, th->th_dport, th->th_sport,
4434 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4435 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4436 (*state)->tag, NULL);
4437 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4438 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4439 sk->port[pd->sidx], sk->port[pd->didx],
4440 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4441 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4442 (*state)->src.seqdiff = (*state)->dst.seqhi -
4443 (*state)->src.seqlo;
4444 (*state)->dst.seqdiff = (*state)->src.seqhi -
4445 (*state)->dst.seqlo;
4446 (*state)->src.seqhi = (*state)->src.seqlo +
4447 (*state)->dst.max_win;
4448 (*state)->dst.seqhi = (*state)->dst.seqlo +
4449 (*state)->src.max_win;
4450 (*state)->src.wscale = (*state)->dst.wscale = 0;
4451 (*state)->src.state = (*state)->dst.state =
4453 REASON_SET(reason, PFRES_SYNPROXY);
4454 return (PF_SYNPROXY_DROP);
4458 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4459 dst->state >= TCPS_FIN_WAIT_2 &&
4460 src->state >= TCPS_FIN_WAIT_2) {
4461 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4462 printf("pf: state reuse ");
4463 pf_print_state(*state);
4464 pf_print_flags(th->th_flags);
4467 /* XXX make sure it's the same direction ?? */
4468 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4469 pf_unlink_state(*state, PF_ENTER_LOCKED);
4474 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4475 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4478 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4479 ©back) == PF_DROP)
4483 /* translate source/destination address, if necessary */
4484 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4485 struct pf_state_key *nk = (*state)->key[pd->didx];
4487 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4488 nk->port[pd->sidx] != th->th_sport)
4489 pf_change_ap(m, pd->src, &th->th_sport,
4490 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4491 nk->port[pd->sidx], 0, pd->af);
4493 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4494 nk->port[pd->didx] != th->th_dport)
4495 pf_change_ap(m, pd->dst, &th->th_dport,
4496 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4497 nk->port[pd->didx], 0, pd->af);
4501 /* Copyback sequence modulation or stateful scrub changes if needed */
4503 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4509 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4510 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4512 struct pf_state_peer *src, *dst;
4513 struct pf_state_key_cmp key;
4514 struct udphdr *uh = pd->hdr.udp;
4516 bzero(&key, sizeof(key));
4518 key.proto = IPPROTO_UDP;
4519 if (direction == PF_IN) { /* wire side, straight */
4520 PF_ACPY(&key.addr[0], pd->src, key.af);
4521 PF_ACPY(&key.addr[1], pd->dst, key.af);
4522 key.port[0] = uh->uh_sport;
4523 key.port[1] = uh->uh_dport;
4524 } else { /* stack side, reverse */
4525 PF_ACPY(&key.addr[1], pd->src, key.af);
4526 PF_ACPY(&key.addr[0], pd->dst, key.af);
4527 key.port[1] = uh->uh_sport;
4528 key.port[0] = uh->uh_dport;
4531 STATE_LOOKUP(kif, &key, direction, *state, pd);
4533 if (direction == (*state)->direction) {
4534 src = &(*state)->src;
4535 dst = &(*state)->dst;
4537 src = &(*state)->dst;
4538 dst = &(*state)->src;
4542 if (src->state < PFUDPS_SINGLE)
4543 src->state = PFUDPS_SINGLE;
4544 if (dst->state == PFUDPS_SINGLE)
4545 dst->state = PFUDPS_MULTIPLE;
4547 /* update expire time */
4548 (*state)->expire = time_uptime;
4549 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4550 (*state)->timeout = PFTM_UDP_MULTIPLE;
4552 (*state)->timeout = PFTM_UDP_SINGLE;
4554 /* translate source/destination address, if necessary */
4555 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4556 struct pf_state_key *nk = (*state)->key[pd->didx];
4558 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4559 nk->port[pd->sidx] != uh->uh_sport)
4560 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4561 &uh->uh_sum, &nk->addr[pd->sidx],
4562 nk->port[pd->sidx], 1, pd->af);
4564 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4565 nk->port[pd->didx] != uh->uh_dport)
4566 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4567 &uh->uh_sum, &nk->addr[pd->didx],
4568 nk->port[pd->didx], 1, pd->af);
4569 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4576 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4577 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4579 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4580 u_int16_t icmpid = 0, *icmpsum;
4583 struct pf_state_key_cmp key;
4585 bzero(&key, sizeof(key));
4586 switch (pd->proto) {
4589 icmptype = pd->hdr.icmp->icmp_type;
4590 icmpid = pd->hdr.icmp->icmp_id;
4591 icmpsum = &pd->hdr.icmp->icmp_cksum;
4593 if (icmptype == ICMP_UNREACH ||
4594 icmptype == ICMP_SOURCEQUENCH ||
4595 icmptype == ICMP_REDIRECT ||
4596 icmptype == ICMP_TIMXCEED ||
4597 icmptype == ICMP_PARAMPROB)
4602 case IPPROTO_ICMPV6:
4603 icmptype = pd->hdr.icmp6->icmp6_type;
4604 icmpid = pd->hdr.icmp6->icmp6_id;
4605 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4607 if (icmptype == ICMP6_DST_UNREACH ||
4608 icmptype == ICMP6_PACKET_TOO_BIG ||
4609 icmptype == ICMP6_TIME_EXCEEDED ||
4610 icmptype == ICMP6_PARAM_PROB)
4619 * ICMP query/reply message not related to a TCP/UDP packet.
4620 * Search for an ICMP state.
4623 key.proto = pd->proto;
4624 key.port[0] = key.port[1] = icmpid;
4625 if (direction == PF_IN) { /* wire side, straight */
4626 PF_ACPY(&key.addr[0], pd->src, key.af);
4627 PF_ACPY(&key.addr[1], pd->dst, key.af);
4628 } else { /* stack side, reverse */
4629 PF_ACPY(&key.addr[1], pd->src, key.af);
4630 PF_ACPY(&key.addr[0], pd->dst, key.af);
4633 STATE_LOOKUP(kif, &key, direction, *state, pd);
4635 (*state)->expire = time_uptime;
4636 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4638 /* translate source/destination address, if necessary */
4639 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4640 struct pf_state_key *nk = (*state)->key[pd->didx];
4645 if (PF_ANEQ(pd->src,
4646 &nk->addr[pd->sidx], AF_INET))
4647 pf_change_a(&saddr->v4.s_addr,
4649 nk->addr[pd->sidx].v4.s_addr, 0);
4651 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4653 pf_change_a(&daddr->v4.s_addr,
4655 nk->addr[pd->didx].v4.s_addr, 0);
4658 pd->hdr.icmp->icmp_id) {
4659 pd->hdr.icmp->icmp_cksum =
4661 pd->hdr.icmp->icmp_cksum, icmpid,
4662 nk->port[pd->sidx], 0);
4663 pd->hdr.icmp->icmp_id =
4667 m_copyback(m, off, ICMP_MINLEN,
4668 (caddr_t )pd->hdr.icmp);
4673 if (PF_ANEQ(pd->src,
4674 &nk->addr[pd->sidx], AF_INET6))
4676 &pd->hdr.icmp6->icmp6_cksum,
4677 &nk->addr[pd->sidx], 0);
4679 if (PF_ANEQ(pd->dst,
4680 &nk->addr[pd->didx], AF_INET6))
4682 &pd->hdr.icmp6->icmp6_cksum,
4683 &nk->addr[pd->didx], 0);
4685 m_copyback(m, off, sizeof(struct icmp6_hdr),
4686 (caddr_t )pd->hdr.icmp6);
4695 * ICMP error message in response to a TCP/UDP packet.
4696 * Extract the inner TCP/UDP header and search for that state.
4699 struct pf_pdesc pd2;
4700 bzero(&pd2, sizeof pd2);
4705 struct ip6_hdr h2_6;
4712 /* Payload packet is from the opposite direction. */
4713 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4714 pd2.didx = (direction == PF_IN) ? 0 : 1;
4718 /* offset of h2 in mbuf chain */
4719 ipoff2 = off + ICMP_MINLEN;
4721 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4722 NULL, reason, pd2.af)) {
4723 DPFPRINTF(PF_DEBUG_MISC,
4724 ("pf: ICMP error message too short "
4729 * ICMP error messages don't refer to non-first
4732 if (h2.ip_off & htons(IP_OFFMASK)) {
4733 REASON_SET(reason, PFRES_FRAG);
4737 /* offset of protocol header that follows h2 */
4738 off2 = ipoff2 + (h2.ip_hl << 2);
4740 pd2.proto = h2.ip_p;
4741 pd2.src = (struct pf_addr *)&h2.ip_src;
4742 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4743 pd2.ip_sum = &h2.ip_sum;
4748 ipoff2 = off + sizeof(struct icmp6_hdr);
4750 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4751 NULL, reason, pd2.af)) {
4752 DPFPRINTF(PF_DEBUG_MISC,
4753 ("pf: ICMP error message too short "
4757 pd2.proto = h2_6.ip6_nxt;
4758 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4759 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4761 off2 = ipoff2 + sizeof(h2_6);
4763 switch (pd2.proto) {
4764 case IPPROTO_FRAGMENT:
4766 * ICMPv6 error messages for
4767 * non-first fragments
4769 REASON_SET(reason, PFRES_FRAG);
4772 case IPPROTO_HOPOPTS:
4773 case IPPROTO_ROUTING:
4774 case IPPROTO_DSTOPTS: {
4775 /* get next header and header length */
4776 struct ip6_ext opt6;
4778 if (!pf_pull_hdr(m, off2, &opt6,
4779 sizeof(opt6), NULL, reason,
4781 DPFPRINTF(PF_DEBUG_MISC,
4782 ("pf: ICMPv6 short opt\n"));
4785 if (pd2.proto == IPPROTO_AH)
4786 off2 += (opt6.ip6e_len + 2) * 4;
4788 off2 += (opt6.ip6e_len + 1) * 8;
4789 pd2.proto = opt6.ip6e_nxt;
4790 /* goto the next header */
4797 } while (!terminal);
4802 switch (pd2.proto) {
4806 struct pf_state_peer *src, *dst;
4811 * Only the first 8 bytes of the TCP header can be
4812 * expected. Don't access any TCP header fields after
4813 * th_seq, an ackskew test is not possible.
4815 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4817 DPFPRINTF(PF_DEBUG_MISC,
4818 ("pf: ICMP error message too short "
4824 key.proto = IPPROTO_TCP;
4825 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4826 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4827 key.port[pd2.sidx] = th.th_sport;
4828 key.port[pd2.didx] = th.th_dport;
4830 STATE_LOOKUP(kif, &key, direction, *state, pd);
4832 if (direction == (*state)->direction) {
4833 src = &(*state)->dst;
4834 dst = &(*state)->src;
4836 src = &(*state)->src;
4837 dst = &(*state)->dst;
4840 if (src->wscale && dst->wscale)
4841 dws = dst->wscale & PF_WSCALE_MASK;
4845 /* Demodulate sequence number */
4846 seq = ntohl(th.th_seq) - src->seqdiff;
4848 pf_change_a(&th.th_seq, icmpsum,
4853 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4854 (!SEQ_GEQ(src->seqhi, seq) ||
4855 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4856 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4857 printf("pf: BAD ICMP %d:%d ",
4858 icmptype, pd->hdr.icmp->icmp_code);
4859 pf_print_host(pd->src, 0, pd->af);
4861 pf_print_host(pd->dst, 0, pd->af);
4863 pf_print_state(*state);
4864 printf(" seq=%u\n", seq);
4866 REASON_SET(reason, PFRES_BADSTATE);
4869 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4870 printf("pf: OK ICMP %d:%d ",
4871 icmptype, pd->hdr.icmp->icmp_code);
4872 pf_print_host(pd->src, 0, pd->af);
4874 pf_print_host(pd->dst, 0, pd->af);
4876 pf_print_state(*state);
4877 printf(" seq=%u\n", seq);
4881 /* translate source/destination address, if necessary */
4882 if ((*state)->key[PF_SK_WIRE] !=
4883 (*state)->key[PF_SK_STACK]) {
4884 struct pf_state_key *nk =
4885 (*state)->key[pd->didx];
4887 if (PF_ANEQ(pd2.src,
4888 &nk->addr[pd2.sidx], pd2.af) ||
4889 nk->port[pd2.sidx] != th.th_sport)
4890 pf_change_icmp(pd2.src, &th.th_sport,
4891 daddr, &nk->addr[pd2.sidx],
4892 nk->port[pd2.sidx], NULL,
4893 pd2.ip_sum, icmpsum,
4894 pd->ip_sum, 0, pd2.af);
4896 if (PF_ANEQ(pd2.dst,
4897 &nk->addr[pd2.didx], pd2.af) ||
4898 nk->port[pd2.didx] != th.th_dport)
4899 pf_change_icmp(pd2.dst, &th.th_dport,
4900 saddr, &nk->addr[pd2.didx],
4901 nk->port[pd2.didx], NULL,
4902 pd2.ip_sum, icmpsum,
4903 pd->ip_sum, 0, pd2.af);
4911 m_copyback(m, off, ICMP_MINLEN,
4912 (caddr_t )pd->hdr.icmp);
4913 m_copyback(m, ipoff2, sizeof(h2),
4920 sizeof(struct icmp6_hdr),
4921 (caddr_t )pd->hdr.icmp6);
4922 m_copyback(m, ipoff2, sizeof(h2_6),
4927 m_copyback(m, off2, 8, (caddr_t)&th);
4936 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4937 NULL, reason, pd2.af)) {
4938 DPFPRINTF(PF_DEBUG_MISC,
4939 ("pf: ICMP error message too short "
4945 key.proto = IPPROTO_UDP;
4946 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4947 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4948 key.port[pd2.sidx] = uh.uh_sport;
4949 key.port[pd2.didx] = uh.uh_dport;
4951 STATE_LOOKUP(kif, &key, direction, *state, pd);
4953 /* translate source/destination address, if necessary */
4954 if ((*state)->key[PF_SK_WIRE] !=
4955 (*state)->key[PF_SK_STACK]) {
4956 struct pf_state_key *nk =
4957 (*state)->key[pd->didx];
4959 if (PF_ANEQ(pd2.src,
4960 &nk->addr[pd2.sidx], pd2.af) ||
4961 nk->port[pd2.sidx] != uh.uh_sport)
4962 pf_change_icmp(pd2.src, &uh.uh_sport,
4963 daddr, &nk->addr[pd2.sidx],
4964 nk->port[pd2.sidx], &uh.uh_sum,
4965 pd2.ip_sum, icmpsum,
4966 pd->ip_sum, 1, pd2.af);
4968 if (PF_ANEQ(pd2.dst,
4969 &nk->addr[pd2.didx], pd2.af) ||
4970 nk->port[pd2.didx] != uh.uh_dport)
4971 pf_change_icmp(pd2.dst, &uh.uh_dport,
4972 saddr, &nk->addr[pd2.didx],
4973 nk->port[pd2.didx], &uh.uh_sum,
4974 pd2.ip_sum, icmpsum,
4975 pd->ip_sum, 1, pd2.af);
4980 m_copyback(m, off, ICMP_MINLEN,
4981 (caddr_t )pd->hdr.icmp);
4982 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4988 sizeof(struct icmp6_hdr),
4989 (caddr_t )pd->hdr.icmp6);
4990 m_copyback(m, ipoff2, sizeof(h2_6),
4995 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5001 case IPPROTO_ICMP: {
5004 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5005 NULL, reason, pd2.af)) {
5006 DPFPRINTF(PF_DEBUG_MISC,
5007 ("pf: ICMP error message too short i"
5013 key.proto = IPPROTO_ICMP;
5014 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5015 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5016 key.port[0] = key.port[1] = iih.icmp_id;
5018 STATE_LOOKUP(kif, &key, direction, *state, pd);
5020 /* translate source/destination address, if necessary */
5021 if ((*state)->key[PF_SK_WIRE] !=
5022 (*state)->key[PF_SK_STACK]) {
5023 struct pf_state_key *nk =
5024 (*state)->key[pd->didx];
5026 if (PF_ANEQ(pd2.src,
5027 &nk->addr[pd2.sidx], pd2.af) ||
5028 nk->port[pd2.sidx] != iih.icmp_id)
5029 pf_change_icmp(pd2.src, &iih.icmp_id,
5030 daddr, &nk->addr[pd2.sidx],
5031 nk->port[pd2.sidx], NULL,
5032 pd2.ip_sum, icmpsum,
5033 pd->ip_sum, 0, AF_INET);
5035 if (PF_ANEQ(pd2.dst,
5036 &nk->addr[pd2.didx], pd2.af) ||
5037 nk->port[pd2.didx] != iih.icmp_id)
5038 pf_change_icmp(pd2.dst, &iih.icmp_id,
5039 saddr, &nk->addr[pd2.didx],
5040 nk->port[pd2.didx], NULL,
5041 pd2.ip_sum, icmpsum,
5042 pd->ip_sum, 0, AF_INET);
5044 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5045 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5046 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5053 case IPPROTO_ICMPV6: {
5054 struct icmp6_hdr iih;
5056 if (!pf_pull_hdr(m, off2, &iih,
5057 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5058 DPFPRINTF(PF_DEBUG_MISC,
5059 ("pf: ICMP error message too short "
5065 key.proto = IPPROTO_ICMPV6;
5066 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5067 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5068 key.port[0] = key.port[1] = iih.icmp6_id;
5070 STATE_LOOKUP(kif, &key, direction, *state, pd);
5072 /* translate source/destination address, if necessary */
5073 if ((*state)->key[PF_SK_WIRE] !=
5074 (*state)->key[PF_SK_STACK]) {
5075 struct pf_state_key *nk =
5076 (*state)->key[pd->didx];
5078 if (PF_ANEQ(pd2.src,
5079 &nk->addr[pd2.sidx], pd2.af) ||
5080 nk->port[pd2.sidx] != iih.icmp6_id)
5081 pf_change_icmp(pd2.src, &iih.icmp6_id,
5082 daddr, &nk->addr[pd2.sidx],
5083 nk->port[pd2.sidx], NULL,
5084 pd2.ip_sum, icmpsum,
5085 pd->ip_sum, 0, AF_INET6);
5087 if (PF_ANEQ(pd2.dst,
5088 &nk->addr[pd2.didx], pd2.af) ||
5089 nk->port[pd2.didx] != iih.icmp6_id)
5090 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5091 saddr, &nk->addr[pd2.didx],
5092 nk->port[pd2.didx], NULL,
5093 pd2.ip_sum, icmpsum,
5094 pd->ip_sum, 0, AF_INET6);
5096 m_copyback(m, off, sizeof(struct icmp6_hdr),
5097 (caddr_t)pd->hdr.icmp6);
5098 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5099 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5108 key.proto = pd2.proto;
5109 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5110 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5111 key.port[0] = key.port[1] = 0;
5113 STATE_LOOKUP(kif, &key, direction, *state, pd);
5115 /* translate source/destination address, if necessary */
5116 if ((*state)->key[PF_SK_WIRE] !=
5117 (*state)->key[PF_SK_STACK]) {
5118 struct pf_state_key *nk =
5119 (*state)->key[pd->didx];
5121 if (PF_ANEQ(pd2.src,
5122 &nk->addr[pd2.sidx], pd2.af))
5123 pf_change_icmp(pd2.src, NULL, daddr,
5124 &nk->addr[pd2.sidx], 0, NULL,
5125 pd2.ip_sum, icmpsum,
5126 pd->ip_sum, 0, pd2.af);
5128 if (PF_ANEQ(pd2.dst,
5129 &nk->addr[pd2.didx], pd2.af))
5130 pf_change_icmp(pd2.dst, NULL, saddr,
5131 &nk->addr[pd2.didx], 0, NULL,
5132 pd2.ip_sum, icmpsum,
5133 pd->ip_sum, 0, pd2.af);
5138 m_copyback(m, off, ICMP_MINLEN,
5139 (caddr_t)pd->hdr.icmp);
5140 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5146 sizeof(struct icmp6_hdr),
5147 (caddr_t )pd->hdr.icmp6);
5148 m_copyback(m, ipoff2, sizeof(h2_6),
5162 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5163 struct mbuf *m, struct pf_pdesc *pd)
5165 struct pf_state_peer *src, *dst;
5166 struct pf_state_key_cmp key;
5168 bzero(&key, sizeof(key));
5170 key.proto = pd->proto;
5171 if (direction == PF_IN) {
5172 PF_ACPY(&key.addr[0], pd->src, key.af);
5173 PF_ACPY(&key.addr[1], pd->dst, key.af);
5174 key.port[0] = key.port[1] = 0;
5176 PF_ACPY(&key.addr[1], pd->src, key.af);
5177 PF_ACPY(&key.addr[0], pd->dst, key.af);
5178 key.port[1] = key.port[0] = 0;
5181 STATE_LOOKUP(kif, &key, direction, *state, pd);
5183 if (direction == (*state)->direction) {
5184 src = &(*state)->src;
5185 dst = &(*state)->dst;
5187 src = &(*state)->dst;
5188 dst = &(*state)->src;
5192 if (src->state < PFOTHERS_SINGLE)
5193 src->state = PFOTHERS_SINGLE;
5194 if (dst->state == PFOTHERS_SINGLE)
5195 dst->state = PFOTHERS_MULTIPLE;
5197 /* update expire time */
5198 (*state)->expire = time_uptime;
5199 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5200 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5202 (*state)->timeout = PFTM_OTHER_SINGLE;
5204 /* translate source/destination address, if necessary */
5205 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5206 struct pf_state_key *nk = (*state)->key[pd->didx];
5208 KASSERT(nk, ("%s: nk is null", __func__));
5209 KASSERT(pd, ("%s: pd is null", __func__));
5210 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5211 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5215 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5216 pf_change_a(&pd->src->v4.s_addr,
5218 nk->addr[pd->sidx].v4.s_addr,
5222 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5223 pf_change_a(&pd->dst->v4.s_addr,
5225 nk->addr[pd->didx].v4.s_addr,
5232 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5233 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5235 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5236 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5244 * ipoff and off are measured from the start of the mbuf chain.
5245 * h must be at "ipoff" on the mbuf chain.
5248 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5249 u_short *actionp, u_short *reasonp, sa_family_t af)
5254 struct ip *h = mtod(m, struct ip *);
5255 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5259 ACTION_SET(actionp, PF_PASS);
5261 ACTION_SET(actionp, PF_DROP);
5262 REASON_SET(reasonp, PFRES_FRAG);
5266 if (m->m_pkthdr.len < off + len ||
5267 ntohs(h->ip_len) < off + len) {
5268 ACTION_SET(actionp, PF_DROP);
5269 REASON_SET(reasonp, PFRES_SHORT);
5277 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5279 if (m->m_pkthdr.len < off + len ||
5280 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5281 (unsigned)(off + len)) {
5282 ACTION_SET(actionp, PF_DROP);
5283 REASON_SET(reasonp, PFRES_SHORT);
5290 m_copydata(m, off, len, p);
5296 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5299 struct radix_node_head *rnh;
5300 struct sockaddr_in *dst;
5304 struct sockaddr_in6 *dst6;
5305 struct route_in6 ro;
5309 struct radix_node *rn;
5314 /* XXX: stick to table 0 for now */
5315 rnh = rt_tables_get_rnh(0, af);
5316 if (rnh != NULL && rn_mpath_capable(rnh))
5318 bzero(&ro, sizeof(ro));
5321 dst = satosin(&ro.ro_dst);
5322 dst->sin_family = AF_INET;
5323 dst->sin_len = sizeof(*dst);
5324 dst->sin_addr = addr->v4;
5329 * Skip check for addresses with embedded interface scope,
5330 * as they would always match anyway.
5332 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5334 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5335 dst6->sin6_family = AF_INET6;
5336 dst6->sin6_len = sizeof(*dst6);
5337 dst6->sin6_addr = addr->v6;
5344 /* Skip checks for ipsec interfaces */
5345 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5351 in6_rtalloc_ign(&ro, 0, rtableid);
5356 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5361 if (ro.ro_rt != NULL) {
5362 /* No interface given, this is a no-route check */
5366 if (kif->pfik_ifp == NULL) {
5371 /* Perform uRPF check if passed input interface */
5373 rn = (struct radix_node *)ro.ro_rt;
5375 rt = (struct rtentry *)rn;
5378 if (kif->pfik_ifp == ifp)
5380 rn = rn_mpath_next(rn);
5381 } while (check_mpath == 1 && rn != NULL && ret == 0);
5385 if (ro.ro_rt != NULL)
5392 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5396 struct nhop4_basic nh4;
5399 struct nhop6_basic nh6;
5403 struct radix_node_head *rnh;
5405 /* XXX: stick to table 0 for now */
5406 rnh = rt_tables_get_rnh(0, af);
5407 if (rnh != NULL && rn_mpath_capable(rnh))
5408 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5411 * Skip check for addresses with embedded interface scope,
5412 * as they would always match anyway.
5414 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5417 if (af != AF_INET && af != AF_INET6)
5420 /* Skip checks for ipsec interfaces */
5421 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5429 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5436 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5443 /* No interface given, this is a no-route check */
5447 if (kif->pfik_ifp == NULL)
5450 /* Perform uRPF check if passed input interface */
5451 if (kif->pfik_ifp == ifp)
5458 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5459 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5461 struct mbuf *m0, *m1;
5462 struct sockaddr_in dst;
5464 struct ifnet *ifp = NULL;
5465 struct pf_addr naddr;
5466 struct pf_src_node *sn = NULL;
5468 uint16_t ip_len, ip_off;
5470 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5471 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5474 if ((pd->pf_mtag == NULL &&
5475 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5476 pd->pf_mtag->routed++ > 3) {
5482 if (r->rt == PF_DUPTO) {
5483 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5489 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5497 ip = mtod(m0, struct ip *);
5499 bzero(&dst, sizeof(dst));
5500 dst.sin_family = AF_INET;
5501 dst.sin_len = sizeof(dst);
5502 dst.sin_addr = ip->ip_dst;
5504 if (r->rt == PF_FASTROUTE) {
5505 struct nhop4_basic nh4;
5510 if (fib4_lookup_nh_basic(M_GETFIB(m0), ip->ip_dst, 0,
5511 m0->m_pkthdr.flowid, &nh4) != 0) {
5512 KMOD_IPSTAT_INC(ips_noroute);
5513 error = EHOSTUNREACH;
5518 dst.sin_addr = nh4.nh_addr;
5520 bzero(&naddr, sizeof(naddr));
5522 if (TAILQ_EMPTY(&r->rpool.list)) {
5523 DPFPRINTF(PF_DEBUG_URGENT,
5524 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5528 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5530 if (!PF_AZERO(&naddr, AF_INET))
5531 dst.sin_addr.s_addr = naddr.v4.s_addr;
5532 ifp = r->rpool.cur->kif ?
5533 r->rpool.cur->kif->pfik_ifp : NULL;
5535 if (!PF_AZERO(&s->rt_addr, AF_INET))
5536 dst.sin_addr.s_addr =
5537 s->rt_addr.v4.s_addr;
5538 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5546 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5548 else if (m0 == NULL)
5550 if (m0->m_len < sizeof(struct ip)) {
5551 DPFPRINTF(PF_DEBUG_URGENT,
5552 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5555 ip = mtod(m0, struct ip *);
5558 if (ifp->if_flags & IFF_LOOPBACK)
5559 m0->m_flags |= M_SKIP_FIREWALL;
5561 ip_len = ntohs(ip->ip_len);
5562 ip_off = ntohs(ip->ip_off);
5564 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5565 m0->m_pkthdr.csum_flags |= CSUM_IP;
5566 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5567 in_delayed_cksum(m0);
5568 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5571 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5572 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5573 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5578 * If small enough for interface, or the interface will take
5579 * care of the fragmentation for us, we can just send directly.
5581 if (ip_len <= ifp->if_mtu ||
5582 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5584 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5585 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5586 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5588 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5589 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5593 /* Balk when DF bit is set or the interface didn't support TSO. */
5594 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5596 KMOD_IPSTAT_INC(ips_cantfrag);
5597 if (r->rt != PF_DUPTO) {
5598 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5605 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5609 for (; m0; m0 = m1) {
5611 m0->m_nextpkt = NULL;
5613 m_clrprotoflags(m0);
5614 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5620 KMOD_IPSTAT_INC(ips_fragmented);
5623 if (r->rt != PF_DUPTO)
5638 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5639 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5642 struct sockaddr_in6 dst;
5643 struct ip6_hdr *ip6;
5644 struct ifnet *ifp = NULL;
5645 struct pf_addr naddr;
5646 struct pf_src_node *sn = NULL;
5648 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5649 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5652 if ((pd->pf_mtag == NULL &&
5653 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5654 pd->pf_mtag->routed++ > 3) {
5660 if (r->rt == PF_DUPTO) {
5661 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5667 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5675 ip6 = mtod(m0, struct ip6_hdr *);
5677 bzero(&dst, sizeof(dst));
5678 dst.sin6_family = AF_INET6;
5679 dst.sin6_len = sizeof(dst);
5680 dst.sin6_addr = ip6->ip6_dst;
5682 /* Cheat. XXX why only in the v6 case??? */
5683 if (r->rt == PF_FASTROUTE) {
5686 m0->m_flags |= M_SKIP_FIREWALL;
5687 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5692 bzero(&naddr, sizeof(naddr));
5694 if (TAILQ_EMPTY(&r->rpool.list)) {
5695 DPFPRINTF(PF_DEBUG_URGENT,
5696 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5700 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5702 if (!PF_AZERO(&naddr, AF_INET6))
5703 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5705 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5707 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5708 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5709 &s->rt_addr, AF_INET6);
5710 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5720 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5722 else if (m0 == NULL)
5724 if (m0->m_len < sizeof(struct ip6_hdr)) {
5725 DPFPRINTF(PF_DEBUG_URGENT,
5726 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5730 ip6 = mtod(m0, struct ip6_hdr *);
5733 if (ifp->if_flags & IFF_LOOPBACK)
5734 m0->m_flags |= M_SKIP_FIREWALL;
5736 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5737 ~ifp->if_hwassist) {
5738 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5739 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5740 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5744 * If the packet is too large for the outgoing interface,
5745 * send back an icmp6 error.
5747 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5748 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5749 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5750 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5752 in6_ifstat_inc(ifp, ifs6_in_toobig);
5753 if (r->rt != PF_DUPTO)
5754 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5760 if (r->rt != PF_DUPTO)
5774 * FreeBSD supports cksum offloads for the following drivers.
5775 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5776 * ti(4), txp(4), xl(4)
5778 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5779 * network driver performed cksum including pseudo header, need to verify
5782 * network driver performed cksum, needs to additional pseudo header
5783 * cksum computation with partial csum_data(i.e. lack of H/W support for
5784 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5786 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5787 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5789 * Also, set csum_data to 0xffff to force cksum validation.
5792 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5798 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5800 if (m->m_pkthdr.len < off + len)
5805 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5806 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5807 sum = m->m_pkthdr.csum_data;
5809 ip = mtod(m, struct ip *);
5810 sum = in_pseudo(ip->ip_src.s_addr,
5811 ip->ip_dst.s_addr, htonl((u_short)len +
5812 m->m_pkthdr.csum_data + IPPROTO_TCP));
5819 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5820 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5821 sum = m->m_pkthdr.csum_data;
5823 ip = mtod(m, struct ip *);
5824 sum = in_pseudo(ip->ip_src.s_addr,
5825 ip->ip_dst.s_addr, htonl((u_short)len +
5826 m->m_pkthdr.csum_data + IPPROTO_UDP));
5834 case IPPROTO_ICMPV6:
5844 if (p == IPPROTO_ICMP) {
5849 sum = in_cksum(m, len);
5853 if (m->m_len < sizeof(struct ip))
5855 sum = in4_cksum(m, p, off, len);
5860 if (m->m_len < sizeof(struct ip6_hdr))
5862 sum = in6_cksum(m, p, off, len);
5873 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5878 KMOD_UDPSTAT_INC(udps_badsum);
5884 KMOD_ICMPSTAT_INC(icps_checksum);
5889 case IPPROTO_ICMPV6:
5891 KMOD_ICMP6STAT_INC(icp6s_checksum);
5898 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5899 m->m_pkthdr.csum_flags |=
5900 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5901 m->m_pkthdr.csum_data = 0xffff;
5910 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5912 struct pfi_kif *kif;
5913 u_short action, reason = 0, log = 0;
5914 struct mbuf *m = *m0;
5915 struct ip *h = NULL;
5916 struct m_tag *ipfwtag;
5917 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5918 struct pf_state *s = NULL;
5919 struct pf_ruleset *ruleset = NULL;
5921 int off, dirndx, pqid = 0;
5923 PF_RULES_RLOCK_TRACKER;
5927 if (!V_pf_status.running)
5930 memset(&pd, 0, sizeof(pd));
5932 kif = (struct pfi_kif *)ifp->if_pf_kif;
5935 DPFPRINTF(PF_DEBUG_URGENT,
5936 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5939 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5942 if (m->m_flags & M_SKIP_FIREWALL)
5945 pd.pf_mtag = pf_find_mtag(m);
5949 if (ip_divert_ptr != NULL &&
5950 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5951 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5952 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5953 if (pd.pf_mtag == NULL &&
5954 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5958 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5959 m_tag_delete(m, ipfwtag);
5961 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5962 m->m_flags |= M_FASTFWD_OURS;
5963 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5965 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5966 /* We do IP header normalization and packet reassembly here */
5970 m = *m0; /* pf_normalize messes with m0 */
5971 h = mtod(m, struct ip *);
5973 off = h->ip_hl << 2;
5974 if (off < (int)sizeof(struct ip)) {
5976 REASON_SET(&reason, PFRES_SHORT);
5981 pd.src = (struct pf_addr *)&h->ip_src;
5982 pd.dst = (struct pf_addr *)&h->ip_dst;
5983 pd.sport = pd.dport = NULL;
5984 pd.ip_sum = &h->ip_sum;
5985 pd.proto_sum = NULL;
5988 pd.sidx = (dir == PF_IN) ? 0 : 1;
5989 pd.didx = (dir == PF_IN) ? 1 : 0;
5992 pd.tot_len = ntohs(h->ip_len);
5994 /* handle fragments that didn't get reassembled by normalization */
5995 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5996 action = pf_test_fragment(&r, dir, kif, m, h,
6007 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6008 &action, &reason, AF_INET)) {
6009 log = action != PF_PASS;
6012 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6013 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6015 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6016 if (action == PF_DROP)
6018 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6020 if (action == PF_PASS) {
6021 if (V_pfsync_update_state_ptr != NULL)
6022 V_pfsync_update_state_ptr(s);
6026 } else if (s == NULL)
6027 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6036 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6037 &action, &reason, AF_INET)) {
6038 log = action != PF_PASS;
6041 if (uh.uh_dport == 0 ||
6042 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6043 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6045 REASON_SET(&reason, PFRES_SHORT);
6048 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6049 if (action == PF_PASS) {
6050 if (V_pfsync_update_state_ptr != NULL)
6051 V_pfsync_update_state_ptr(s);
6055 } else if (s == NULL)
6056 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6061 case IPPROTO_ICMP: {
6065 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6066 &action, &reason, AF_INET)) {
6067 log = action != PF_PASS;
6070 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6072 if (action == PF_PASS) {
6073 if (V_pfsync_update_state_ptr != NULL)
6074 V_pfsync_update_state_ptr(s);
6078 } else if (s == NULL)
6079 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6085 case IPPROTO_ICMPV6: {
6087 DPFPRINTF(PF_DEBUG_MISC,
6088 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6094 action = pf_test_state_other(&s, dir, kif, m, &pd);
6095 if (action == PF_PASS) {
6096 if (V_pfsync_update_state_ptr != NULL)
6097 V_pfsync_update_state_ptr(s);
6101 } else if (s == NULL)
6102 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6109 if (action == PF_PASS && h->ip_hl > 5 &&
6110 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6112 REASON_SET(&reason, PFRES_IPOPTIONS);
6114 DPFPRINTF(PF_DEBUG_MISC,
6115 ("pf: dropping packet with ip options\n"));
6118 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6120 REASON_SET(&reason, PFRES_MEMORY);
6122 if (r->rtableid >= 0)
6123 M_SETFIB(m, r->rtableid);
6125 if (r->scrub_flags & PFSTATE_SETPRIO) {
6126 if (pd.tos & IPTOS_LOWDELAY)
6128 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6130 REASON_SET(&reason, PFRES_MEMORY);
6132 DPFPRINTF(PF_DEBUG_MISC,
6133 ("pf: failed to allocate 802.1q mtag\n"));
6138 if (action == PF_PASS && r->qid) {
6139 if (pd.pf_mtag == NULL &&
6140 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6142 REASON_SET(&reason, PFRES_MEMORY);
6145 pd.pf_mtag->qid_hash = pf_state_hash(s);
6146 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6147 pd.pf_mtag->qid = r->pqid;
6149 pd.pf_mtag->qid = r->qid;
6150 /* Add hints for ecn. */
6151 pd.pf_mtag->hdr = h;
6158 * connections redirected to loopback should not match sockets
6159 * bound specifically to loopback due to security implications,
6160 * see tcp_input() and in_pcblookup_listen().
6162 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6163 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6164 (s->nat_rule.ptr->action == PF_RDR ||
6165 s->nat_rule.ptr->action == PF_BINAT) &&
6166 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6167 m->m_flags |= M_SKIP_FIREWALL;
6169 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6170 !PACKET_LOOPED(&pd)) {
6172 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6173 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6174 if (ipfwtag != NULL) {
6175 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6176 ntohs(r->divert.port);
6177 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6182 m_tag_prepend(m, ipfwtag);
6183 if (m->m_flags & M_FASTFWD_OURS) {
6184 if (pd.pf_mtag == NULL &&
6185 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6187 REASON_SET(&reason, PFRES_MEMORY);
6189 DPFPRINTF(PF_DEBUG_MISC,
6190 ("pf: failed to allocate tag\n"));
6192 pd.pf_mtag->flags |=
6193 PF_FASTFWD_OURS_PRESENT;
6194 m->m_flags &= ~M_FASTFWD_OURS;
6197 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6202 /* XXX: ipfw has the same behaviour! */
6204 REASON_SET(&reason, PFRES_MEMORY);
6206 DPFPRINTF(PF_DEBUG_MISC,
6207 ("pf: failed to allocate divert tag\n"));
6214 if (s != NULL && s->nat_rule.ptr != NULL &&
6215 s->nat_rule.ptr->log & PF_LOG_ALL)
6216 lr = s->nat_rule.ptr;
6219 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6223 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6224 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6226 if (action == PF_PASS || r->action == PF_DROP) {
6227 dirndx = (dir == PF_OUT);
6228 r->packets[dirndx]++;
6229 r->bytes[dirndx] += pd.tot_len;
6231 a->packets[dirndx]++;
6232 a->bytes[dirndx] += pd.tot_len;
6235 if (s->nat_rule.ptr != NULL) {
6236 s->nat_rule.ptr->packets[dirndx]++;
6237 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6239 if (s->src_node != NULL) {
6240 s->src_node->packets[dirndx]++;
6241 s->src_node->bytes[dirndx] += pd.tot_len;
6243 if (s->nat_src_node != NULL) {
6244 s->nat_src_node->packets[dirndx]++;
6245 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6247 dirndx = (dir == s->direction) ? 0 : 1;
6248 s->packets[dirndx]++;
6249 s->bytes[dirndx] += pd.tot_len;
6252 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6253 if (nr != NULL && r == &V_pf_default_rule)
6255 if (tr->src.addr.type == PF_ADDR_TABLE)
6256 pfr_update_stats(tr->src.addr.p.tbl,
6257 (s == NULL) ? pd.src :
6258 &s->key[(s->direction == PF_IN)]->
6259 addr[(s->direction == PF_OUT)],
6260 pd.af, pd.tot_len, dir == PF_OUT,
6261 r->action == PF_PASS, tr->src.neg);
6262 if (tr->dst.addr.type == PF_ADDR_TABLE)
6263 pfr_update_stats(tr->dst.addr.p.tbl,
6264 (s == NULL) ? pd.dst :
6265 &s->key[(s->direction == PF_IN)]->
6266 addr[(s->direction == PF_IN)],
6267 pd.af, pd.tot_len, dir == PF_OUT,
6268 r->action == PF_PASS, tr->dst.neg);
6272 case PF_SYNPROXY_DROP:
6283 /* pf_route() returns unlocked. */
6285 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6299 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6301 struct pfi_kif *kif;
6302 u_short action, reason = 0, log = 0;
6303 struct mbuf *m = *m0, *n = NULL;
6305 struct ip6_hdr *h = NULL;
6306 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6307 struct pf_state *s = NULL;
6308 struct pf_ruleset *ruleset = NULL;
6310 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6312 PF_RULES_RLOCK_TRACKER;
6315 if (!V_pf_status.running)
6318 memset(&pd, 0, sizeof(pd));
6319 pd.pf_mtag = pf_find_mtag(m);
6321 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6324 kif = (struct pfi_kif *)ifp->if_pf_kif;
6326 DPFPRINTF(PF_DEBUG_URGENT,
6327 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6330 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6333 if (m->m_flags & M_SKIP_FIREWALL)
6338 /* We do IP header normalization and packet reassembly here */
6339 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6343 m = *m0; /* pf_normalize messes with m0 */
6344 h = mtod(m, struct ip6_hdr *);
6348 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6349 * will do something bad, so drop the packet for now.
6351 if (htons(h->ip6_plen) == 0) {
6353 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6358 pd.src = (struct pf_addr *)&h->ip6_src;
6359 pd.dst = (struct pf_addr *)&h->ip6_dst;
6360 pd.sport = pd.dport = NULL;
6362 pd.proto_sum = NULL;
6364 pd.sidx = (dir == PF_IN) ? 0 : 1;
6365 pd.didx = (dir == PF_IN) ? 1 : 0;
6368 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6370 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6371 pd.proto = h->ip6_nxt;
6374 case IPPROTO_FRAGMENT:
6375 action = pf_test_fragment(&r, dir, kif, m, h,
6377 if (action == PF_DROP)
6378 REASON_SET(&reason, PFRES_FRAG);
6380 case IPPROTO_ROUTING: {
6381 struct ip6_rthdr rthdr;
6384 DPFPRINTF(PF_DEBUG_MISC,
6385 ("pf: IPv6 more than one rthdr\n"));
6387 REASON_SET(&reason, PFRES_IPOPTIONS);
6391 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6393 DPFPRINTF(PF_DEBUG_MISC,
6394 ("pf: IPv6 short rthdr\n"));
6396 REASON_SET(&reason, PFRES_SHORT);
6400 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6401 DPFPRINTF(PF_DEBUG_MISC,
6402 ("pf: IPv6 rthdr0\n"));
6404 REASON_SET(&reason, PFRES_IPOPTIONS);
6411 case IPPROTO_HOPOPTS:
6412 case IPPROTO_DSTOPTS: {
6413 /* get next header and header length */
6414 struct ip6_ext opt6;
6416 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6417 NULL, &reason, pd.af)) {
6418 DPFPRINTF(PF_DEBUG_MISC,
6419 ("pf: IPv6 short opt\n"));
6424 if (pd.proto == IPPROTO_AH)
6425 off += (opt6.ip6e_len + 2) * 4;
6427 off += (opt6.ip6e_len + 1) * 8;
6428 pd.proto = opt6.ip6e_nxt;
6429 /* goto the next header */
6436 } while (!terminal);
6438 /* if there's no routing header, use unmodified mbuf for checksumming */
6448 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6449 &action, &reason, AF_INET6)) {
6450 log = action != PF_PASS;
6453 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6454 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6455 if (action == PF_DROP)
6457 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6459 if (action == PF_PASS) {
6460 if (V_pfsync_update_state_ptr != NULL)
6461 V_pfsync_update_state_ptr(s);
6465 } else if (s == NULL)
6466 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6475 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6476 &action, &reason, AF_INET6)) {
6477 log = action != PF_PASS;
6480 if (uh.uh_dport == 0 ||
6481 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6482 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6484 REASON_SET(&reason, PFRES_SHORT);
6487 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6488 if (action == PF_PASS) {
6489 if (V_pfsync_update_state_ptr != NULL)
6490 V_pfsync_update_state_ptr(s);
6494 } else if (s == NULL)
6495 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6500 case IPPROTO_ICMP: {
6502 DPFPRINTF(PF_DEBUG_MISC,
6503 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6507 case IPPROTO_ICMPV6: {
6508 struct icmp6_hdr ih;
6511 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6512 &action, &reason, AF_INET6)) {
6513 log = action != PF_PASS;
6516 action = pf_test_state_icmp(&s, dir, kif,
6517 m, off, h, &pd, &reason);
6518 if (action == PF_PASS) {
6519 if (V_pfsync_update_state_ptr != NULL)
6520 V_pfsync_update_state_ptr(s);
6524 } else if (s == NULL)
6525 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6531 action = pf_test_state_other(&s, dir, kif, m, &pd);
6532 if (action == PF_PASS) {
6533 if (V_pfsync_update_state_ptr != NULL)
6534 V_pfsync_update_state_ptr(s);
6538 } else if (s == NULL)
6539 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6551 /* handle dangerous IPv6 extension headers. */
6552 if (action == PF_PASS && rh_cnt &&
6553 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6555 REASON_SET(&reason, PFRES_IPOPTIONS);
6557 DPFPRINTF(PF_DEBUG_MISC,
6558 ("pf: dropping packet with dangerous v6 headers\n"));
6561 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6563 REASON_SET(&reason, PFRES_MEMORY);
6565 if (r->rtableid >= 0)
6566 M_SETFIB(m, r->rtableid);
6568 if (r->scrub_flags & PFSTATE_SETPRIO) {
6569 if (pd.tos & IPTOS_LOWDELAY)
6571 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6573 REASON_SET(&reason, PFRES_MEMORY);
6575 DPFPRINTF(PF_DEBUG_MISC,
6576 ("pf: failed to allocate 802.1q mtag\n"));
6581 if (action == PF_PASS && r->qid) {
6582 if (pd.pf_mtag == NULL &&
6583 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6585 REASON_SET(&reason, PFRES_MEMORY);
6588 pd.pf_mtag->qid_hash = pf_state_hash(s);
6589 if (pd.tos & IPTOS_LOWDELAY)
6590 pd.pf_mtag->qid = r->pqid;
6592 pd.pf_mtag->qid = r->qid;
6593 /* Add hints for ecn. */
6594 pd.pf_mtag->hdr = h;
6599 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6600 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6601 (s->nat_rule.ptr->action == PF_RDR ||
6602 s->nat_rule.ptr->action == PF_BINAT) &&
6603 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6604 m->m_flags |= M_SKIP_FIREWALL;
6606 /* XXX: Anybody working on it?! */
6608 printf("pf: divert(9) is not supported for IPv6\n");
6613 if (s != NULL && s->nat_rule.ptr != NULL &&
6614 s->nat_rule.ptr->log & PF_LOG_ALL)
6615 lr = s->nat_rule.ptr;
6618 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6622 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6623 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6625 if (action == PF_PASS || r->action == PF_DROP) {
6626 dirndx = (dir == PF_OUT);
6627 r->packets[dirndx]++;
6628 r->bytes[dirndx] += pd.tot_len;
6630 a->packets[dirndx]++;
6631 a->bytes[dirndx] += pd.tot_len;
6634 if (s->nat_rule.ptr != NULL) {
6635 s->nat_rule.ptr->packets[dirndx]++;
6636 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6638 if (s->src_node != NULL) {
6639 s->src_node->packets[dirndx]++;
6640 s->src_node->bytes[dirndx] += pd.tot_len;
6642 if (s->nat_src_node != NULL) {
6643 s->nat_src_node->packets[dirndx]++;
6644 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6646 dirndx = (dir == s->direction) ? 0 : 1;
6647 s->packets[dirndx]++;
6648 s->bytes[dirndx] += pd.tot_len;
6651 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6652 if (nr != NULL && r == &V_pf_default_rule)
6654 if (tr->src.addr.type == PF_ADDR_TABLE)
6655 pfr_update_stats(tr->src.addr.p.tbl,
6656 (s == NULL) ? pd.src :
6657 &s->key[(s->direction == PF_IN)]->addr[0],
6658 pd.af, pd.tot_len, dir == PF_OUT,
6659 r->action == PF_PASS, tr->src.neg);
6660 if (tr->dst.addr.type == PF_ADDR_TABLE)
6661 pfr_update_stats(tr->dst.addr.p.tbl,
6662 (s == NULL) ? pd.dst :
6663 &s->key[(s->direction == PF_IN)]->addr[1],
6664 pd.af, pd.tot_len, dir == PF_OUT,
6665 r->action == PF_PASS, tr->dst.neg);
6669 case PF_SYNPROXY_DROP:
6680 /* pf_route6() returns unlocked. */
6682 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6691 /* If reassembled packet passed, create new fragments. */
6692 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6693 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6694 action = pf_refragment6(ifp, m0, mtag);