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>
71 #include <net/pfvar.h>
72 #include <net/if_pflog.h>
73 #include <net/if_pfsync.h>
75 #include <netinet/in_pcb.h>
76 #include <netinet/in_var.h>
77 #include <netinet/in_fib.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_fw.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/icmp_var.h>
82 #include <netinet/ip_var.h>
83 #include <netinet/tcp.h>
84 #include <netinet/tcp_fsm.h>
85 #include <netinet/tcp_seq.h>
86 #include <netinet/tcp_timer.h>
87 #include <netinet/tcp_var.h>
88 #include <netinet/udp.h>
89 #include <netinet/udp_var.h>
91 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
94 #include <netinet/ip6.h>
95 #include <netinet/icmp6.h>
96 #include <netinet6/nd6.h>
97 #include <netinet6/ip6_var.h>
98 #include <netinet6/in6_pcb.h>
99 #include <netinet6/in6_fib.h>
100 #include <netinet6/scope6_var.h>
103 #include <machine/in_cksum.h>
104 #include <security/mac/mac_framework.h>
106 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
113 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
114 VNET_DEFINE(struct pf_palist, pf_pabuf);
115 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
116 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
117 VNET_DEFINE(struct pf_kstatus, pf_status);
119 VNET_DEFINE(u_int32_t, ticket_altqs_active);
120 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
121 VNET_DEFINE(int, altqs_inactive_open);
122 VNET_DEFINE(u_int32_t, ticket_pabuf);
124 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
125 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
126 VNET_DEFINE(u_char, pf_tcp_secret[16]);
127 #define V_pf_tcp_secret VNET(pf_tcp_secret)
128 VNET_DEFINE(int, pf_tcp_secret_init);
129 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
130 VNET_DEFINE(int, pf_tcp_iss_off);
131 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
132 VNET_DECLARE(int, pf_vnet_active);
133 #define V_pf_vnet_active VNET(pf_vnet_active)
136 * Queue for pf_intr() sends.
138 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
139 struct pf_send_entry {
140 STAILQ_ENTRY(pf_send_entry) pfse_next;
155 STAILQ_HEAD(pf_send_head, pf_send_entry);
156 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157 #define V_pf_sendqueue VNET(pf_sendqueue)
159 static struct mtx pf_sendqueue_mtx;
160 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
161 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
162 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
165 * Queue for pf_overload_task() tasks.
167 struct pf_overload_entry {
168 SLIST_ENTRY(pf_overload_entry) next;
172 struct pf_rule *rule;
175 SLIST_HEAD(pf_overload_head, pf_overload_entry);
176 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
177 #define V_pf_overloadqueue VNET(pf_overloadqueue)
178 static VNET_DEFINE(struct task, pf_overloadtask);
179 #define V_pf_overloadtask VNET(pf_overloadtask)
181 static struct mtx pf_overloadqueue_mtx;
182 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
183 "pf overload/flush queue", MTX_DEF);
184 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
185 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
187 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
188 struct mtx pf_unlnkdrules_mtx;
189 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
192 static VNET_DEFINE(uma_zone_t, pf_sources_z);
193 #define V_pf_sources_z VNET(pf_sources_z)
194 uma_zone_t pf_mtag_z;
195 VNET_DEFINE(uma_zone_t, pf_state_z);
196 VNET_DEFINE(uma_zone_t, pf_state_key_z);
198 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
199 #define PFID_CPUBITS 8
200 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
201 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
202 #define PFID_MAXID (~PFID_CPUMASK)
203 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
205 static void pf_src_tree_remove_state(struct pf_state *);
206 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
208 static void pf_add_threshold(struct pf_threshold *);
209 static int pf_check_threshold(struct pf_threshold *);
211 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
212 u_int16_t *, u_int16_t *, struct pf_addr *,
213 u_int16_t, u_int8_t, sa_family_t);
214 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
215 struct tcphdr *, struct pf_state_peer *);
216 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
217 struct pf_addr *, struct pf_addr *, u_int16_t,
218 u_int16_t *, u_int16_t *, u_int16_t *,
219 u_int16_t *, u_int8_t, sa_family_t);
220 static void pf_send_tcp(struct mbuf *,
221 const struct pf_rule *, sa_family_t,
222 const struct pf_addr *, const struct pf_addr *,
223 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
224 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
225 u_int16_t, struct ifnet *);
226 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
227 sa_family_t, struct pf_rule *);
228 static void pf_detach_state(struct pf_state *);
229 static int pf_state_key_attach(struct pf_state_key *,
230 struct pf_state_key *, struct pf_state *);
231 static void pf_state_key_detach(struct pf_state *, int);
232 static int pf_state_key_ctor(void *, int, void *, int);
233 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
234 static int pf_test_rule(struct pf_rule **, struct pf_state **,
235 int, struct pfi_kif *, struct mbuf *, int,
236 struct pf_pdesc *, struct pf_rule **,
237 struct pf_ruleset **, struct inpcb *);
238 static int pf_create_state(struct pf_rule *, struct pf_rule *,
239 struct pf_rule *, struct pf_pdesc *,
240 struct pf_src_node *, struct pf_state_key *,
241 struct pf_state_key *, struct mbuf *, int,
242 u_int16_t, u_int16_t, int *, struct pfi_kif *,
243 struct pf_state **, int, u_int16_t, u_int16_t,
245 static int pf_test_fragment(struct pf_rule **, int,
246 struct pfi_kif *, struct mbuf *, void *,
247 struct pf_pdesc *, struct pf_rule **,
248 struct pf_ruleset **);
249 static int pf_tcp_track_full(struct pf_state_peer *,
250 struct pf_state_peer *, struct pf_state **,
251 struct pfi_kif *, struct mbuf *, int,
252 struct pf_pdesc *, u_short *, int *);
253 static int pf_tcp_track_sloppy(struct pf_state_peer *,
254 struct pf_state_peer *, struct pf_state **,
255 struct pf_pdesc *, u_short *);
256 static int pf_test_state_tcp(struct pf_state **, int,
257 struct pfi_kif *, struct mbuf *, int,
258 void *, struct pf_pdesc *, u_short *);
259 static int pf_test_state_udp(struct pf_state **, int,
260 struct pfi_kif *, struct mbuf *, int,
261 void *, struct pf_pdesc *);
262 static int pf_test_state_icmp(struct pf_state **, int,
263 struct pfi_kif *, struct mbuf *, int,
264 void *, struct pf_pdesc *, u_short *);
265 static int pf_test_state_other(struct pf_state **, int,
266 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
267 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
269 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
271 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
273 static int pf_check_proto_cksum(struct mbuf *, int, int,
274 u_int8_t, sa_family_t);
275 static void pf_print_state_parts(struct pf_state *,
276 struct pf_state_key *, struct pf_state_key *);
277 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
278 struct pf_addr_wrap *);
279 static struct pf_state *pf_find_state(struct pfi_kif *,
280 struct pf_state_key_cmp *, u_int);
281 static int pf_src_connlimit(struct pf_state **);
282 static void pf_overload_task(void *v, int pending);
283 static int pf_insert_src_node(struct pf_src_node **,
284 struct pf_rule *, struct pf_addr *, sa_family_t);
285 static u_int pf_purge_expired_states(u_int, int);
286 static void pf_purge_unlinked_rules(void);
287 static int pf_mtag_uminit(void *, int, int);
288 static void pf_mtag_free(struct m_tag *);
290 static void pf_route(struct mbuf **, struct pf_rule *, int,
291 struct ifnet *, struct pf_state *,
295 static void pf_change_a6(struct pf_addr *, u_int16_t *,
296 struct pf_addr *, u_int8_t);
297 static void pf_route6(struct mbuf **, struct pf_rule *, int,
298 struct ifnet *, struct pf_state *,
302 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
304 extern int pf_end_threads;
305 extern struct proc *pf_purge_proc;
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_HASHSIZ / 4;
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,
802 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
803 M_PFHASH, M_WAITOK | M_ZERO);
804 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
805 M_PFHASH, M_WAITOK | M_ZERO);
806 pf_hashmask = pf_hashsize - 1;
807 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
809 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
810 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
814 V_pf_sources_z = uma_zcreate("pf source nodes",
815 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
817 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
818 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
819 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
820 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
821 M_PFHASH, M_WAITOK|M_ZERO);
822 pf_srchashmask = pf_srchashsize - 1;
823 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
824 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
827 TAILQ_INIT(&V_pf_altqs[0]);
828 TAILQ_INIT(&V_pf_altqs[1]);
829 TAILQ_INIT(&V_pf_pabuf);
830 V_pf_altqs_active = &V_pf_altqs[0];
831 V_pf_altqs_inactive = &V_pf_altqs[1];
833 /* Send & overload+flush queues. */
834 STAILQ_INIT(&V_pf_sendqueue);
835 SLIST_INIT(&V_pf_overloadqueue);
836 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
838 /* Unlinked, but may be referenced rules. */
839 TAILQ_INIT(&V_pf_unlinked_rules);
846 uma_zdestroy(pf_mtag_z);
852 struct pf_keyhash *kh;
853 struct pf_idhash *ih;
854 struct pf_srchash *sh;
855 struct pf_send_entry *pfse, *next;
858 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
860 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
862 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
864 mtx_destroy(&kh->lock);
865 mtx_destroy(&ih->lock);
867 free(V_pf_keyhash, M_PFHASH);
868 free(V_pf_idhash, M_PFHASH);
870 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
871 KASSERT(LIST_EMPTY(&sh->nodes),
872 ("%s: source node hash not empty", __func__));
873 mtx_destroy(&sh->lock);
875 free(V_pf_srchash, M_PFHASH);
877 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
878 m_freem(pfse->pfse_m);
879 free(pfse, M_PFTEMP);
882 uma_zdestroy(V_pf_sources_z);
883 uma_zdestroy(V_pf_state_z);
884 uma_zdestroy(V_pf_state_key_z);
888 pf_mtag_uminit(void *mem, int size, int how)
892 t = (struct m_tag *)mem;
893 t->m_tag_cookie = MTAG_ABI_COMPAT;
894 t->m_tag_id = PACKET_TAG_PF;
895 t->m_tag_len = sizeof(struct pf_mtag);
896 t->m_tag_free = pf_mtag_free;
902 pf_mtag_free(struct m_tag *t)
905 uma_zfree(pf_mtag_z, t);
909 pf_get_mtag(struct mbuf *m)
913 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
914 return ((struct pf_mtag *)(mtag + 1));
916 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
919 bzero(mtag + 1, sizeof(struct pf_mtag));
920 m_tag_prepend(m, mtag);
922 return ((struct pf_mtag *)(mtag + 1));
926 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
929 struct pf_keyhash *khs, *khw, *kh;
930 struct pf_state_key *sk, *cur;
931 struct pf_state *si, *olds = NULL;
934 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
935 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
936 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
939 * We need to lock hash slots of both keys. To avoid deadlock
940 * we always lock the slot with lower address first. Unlock order
943 * We also need to lock ID hash slot before dropping key
944 * locks. On success we return with ID hash slot locked.
948 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
949 PF_HASHROW_LOCK(khs);
951 khs = &V_pf_keyhash[pf_hashkey(sks)];
952 khw = &V_pf_keyhash[pf_hashkey(skw)];
954 PF_HASHROW_LOCK(khs);
955 } else if (khs < khw) {
956 PF_HASHROW_LOCK(khs);
957 PF_HASHROW_LOCK(khw);
959 PF_HASHROW_LOCK(khw);
960 PF_HASHROW_LOCK(khs);
964 #define KEYS_UNLOCK() do { \
966 PF_HASHROW_UNLOCK(khs); \
967 PF_HASHROW_UNLOCK(khw); \
969 PF_HASHROW_UNLOCK(khs); \
973 * First run: start with wire key.
980 LIST_FOREACH(cur, &kh->keys, entry)
981 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
985 /* Key exists. Check for same kif, if none, add to key. */
986 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
987 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
990 if (si->kif == s->kif &&
991 si->direction == s->direction) {
992 if (sk->proto == IPPROTO_TCP &&
993 si->src.state >= TCPS_FIN_WAIT_2 &&
994 si->dst.state >= TCPS_FIN_WAIT_2) {
996 * New state matches an old >FIN_WAIT_2
997 * state. We can't drop key hash locks,
998 * thus we can't unlink it properly.
1000 * As a workaround we drop it into
1001 * TCPS_CLOSED state, schedule purge
1002 * ASAP and push it into the very end
1003 * of the slot TAILQ, so that it won't
1004 * conflict with our new state.
1006 si->src.state = si->dst.state =
1008 si->timeout = PFTM_PURGE;
1011 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1012 printf("pf: %s key attach "
1014 (idx == PF_SK_WIRE) ?
1017 pf_print_state_parts(s,
1018 (idx == PF_SK_WIRE) ?
1020 (idx == PF_SK_STACK) ?
1022 printf(", existing: ");
1023 pf_print_state_parts(si,
1024 (idx == PF_SK_WIRE) ?
1026 (idx == PF_SK_STACK) ?
1030 PF_HASHROW_UNLOCK(ih);
1032 uma_zfree(V_pf_state_key_z, sk);
1033 if (idx == PF_SK_STACK)
1035 return (EEXIST); /* collision! */
1038 PF_HASHROW_UNLOCK(ih);
1040 uma_zfree(V_pf_state_key_z, sk);
1043 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1048 /* List is sorted, if-bound states before floating. */
1049 if (s->kif == V_pfi_all)
1050 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1052 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1055 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1056 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1062 * Attach done. See how should we (or should not?)
1063 * attach a second key.
1066 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1070 } else if (sks != NULL) {
1072 * Continue attaching with stack key.
1084 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1085 ("%s failure", __func__));
1092 pf_detach_state(struct pf_state *s)
1094 struct pf_state_key *sks = s->key[PF_SK_STACK];
1095 struct pf_keyhash *kh;
1098 kh = &V_pf_keyhash[pf_hashkey(sks)];
1099 PF_HASHROW_LOCK(kh);
1100 if (s->key[PF_SK_STACK] != NULL)
1101 pf_state_key_detach(s, PF_SK_STACK);
1103 * If both point to same key, then we are done.
1105 if (sks == s->key[PF_SK_WIRE]) {
1106 pf_state_key_detach(s, PF_SK_WIRE);
1107 PF_HASHROW_UNLOCK(kh);
1110 PF_HASHROW_UNLOCK(kh);
1113 if (s->key[PF_SK_WIRE] != NULL) {
1114 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1115 PF_HASHROW_LOCK(kh);
1116 if (s->key[PF_SK_WIRE] != NULL)
1117 pf_state_key_detach(s, PF_SK_WIRE);
1118 PF_HASHROW_UNLOCK(kh);
1123 pf_state_key_detach(struct pf_state *s, int idx)
1125 struct pf_state_key *sk = s->key[idx];
1127 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1129 PF_HASHROW_ASSERT(kh);
1131 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1134 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1135 LIST_REMOVE(sk, entry);
1136 uma_zfree(V_pf_state_key_z, sk);
1141 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1143 struct pf_state_key *sk = mem;
1145 bzero(sk, sizeof(struct pf_state_key_cmp));
1146 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1147 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1152 struct pf_state_key *
1153 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1154 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1156 struct pf_state_key *sk;
1158 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1162 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1163 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1164 sk->port[pd->sidx] = sport;
1165 sk->port[pd->didx] = dport;
1166 sk->proto = pd->proto;
1172 struct pf_state_key *
1173 pf_state_key_clone(struct pf_state_key *orig)
1175 struct pf_state_key *sk;
1177 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1181 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1187 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1188 struct pf_state_key *sks, struct pf_state *s)
1190 struct pf_idhash *ih;
1191 struct pf_state *cur;
1194 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1195 ("%s: sks not pristine", __func__));
1196 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1197 ("%s: skw not pristine", __func__));
1198 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1202 if (s->id == 0 && s->creatorid == 0) {
1203 /* XXX: should be atomic, but probability of collision low */
1204 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1205 V_pf_stateid[curcpu] = 1;
1206 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1207 s->id = htobe64(s->id);
1208 s->creatorid = V_pf_status.hostid;
1211 /* Returns with ID locked on success. */
1212 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1215 ih = &V_pf_idhash[PF_IDHASH(s)];
1216 PF_HASHROW_ASSERT(ih);
1217 LIST_FOREACH(cur, &ih->states, entry)
1218 if (cur->id == s->id && cur->creatorid == s->creatorid)
1222 PF_HASHROW_UNLOCK(ih);
1223 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1224 printf("pf: state ID collision: "
1225 "id: %016llx creatorid: %08x\n",
1226 (unsigned long long)be64toh(s->id),
1227 ntohl(s->creatorid));
1232 LIST_INSERT_HEAD(&ih->states, s, entry);
1233 /* One for keys, one for ID hash. */
1234 refcount_init(&s->refs, 2);
1236 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1237 if (pfsync_insert_state_ptr != NULL)
1238 pfsync_insert_state_ptr(s);
1240 /* Returns locked. */
1245 * Find state by ID: returns with locked row on success.
1248 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1250 struct pf_idhash *ih;
1253 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1255 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1257 PF_HASHROW_LOCK(ih);
1258 LIST_FOREACH(s, &ih->states, entry)
1259 if (s->id == id && s->creatorid == creatorid)
1263 PF_HASHROW_UNLOCK(ih);
1269 * Find state by key.
1270 * Returns with ID hash slot locked on success.
1272 static struct pf_state *
1273 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1275 struct pf_keyhash *kh;
1276 struct pf_state_key *sk;
1280 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1282 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1284 PF_HASHROW_LOCK(kh);
1285 LIST_FOREACH(sk, &kh->keys, entry)
1286 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1289 PF_HASHROW_UNLOCK(kh);
1293 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1295 /* List is sorted, if-bound states before floating ones. */
1296 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1297 if (s->kif == V_pfi_all || s->kif == kif) {
1299 PF_HASHROW_UNLOCK(kh);
1300 if (s->timeout >= PFTM_MAX) {
1302 * State is either being processed by
1303 * pf_unlink_state() in an other thread, or
1304 * is scheduled for immediate expiry.
1311 PF_HASHROW_UNLOCK(kh);
1317 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1319 struct pf_keyhash *kh;
1320 struct pf_state_key *sk;
1321 struct pf_state *s, *ret = NULL;
1324 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1326 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1328 PF_HASHROW_LOCK(kh);
1329 LIST_FOREACH(sk, &kh->keys, entry)
1330 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1333 PF_HASHROW_UNLOCK(kh);
1348 panic("%s: dir %u", __func__, dir);
1351 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1353 PF_HASHROW_UNLOCK(kh);
1367 PF_HASHROW_UNLOCK(kh);
1372 /* END state table stuff */
1375 pf_send(struct pf_send_entry *pfse)
1379 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1381 swi_sched(V_pf_swi_cookie, 0);
1387 struct pf_send_head queue;
1388 struct pf_send_entry *pfse, *next;
1390 CURVNET_SET((struct vnet *)v);
1393 queue = V_pf_sendqueue;
1394 STAILQ_INIT(&V_pf_sendqueue);
1397 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1398 switch (pfse->pfse_type) {
1401 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1404 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1405 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1410 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1414 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1415 pfse->icmpopts.code, pfse->icmpopts.mtu);
1419 panic("%s: unknown type", __func__);
1421 free(pfse, M_PFTEMP);
1427 pf_purge_thread(void *unused __unused)
1429 VNET_ITERATOR_DECL(vnet_iter);
1432 sx_xlock(&pf_end_lock);
1433 while (pf_end_threads == 0) {
1434 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1437 VNET_FOREACH(vnet_iter) {
1438 CURVNET_SET(vnet_iter);
1441 /* Wait until V_pf_default_rule is initialized. */
1442 if (V_pf_vnet_active == 0) {
1448 * Process 1/interval fraction of the state
1451 idx = pf_purge_expired_states(idx, pf_hashmask /
1452 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1455 * Purge other expired types every
1456 * PFTM_INTERVAL seconds.
1460 * Order is important:
1461 * - states and src nodes reference rules
1462 * - states and rules reference kifs
1464 pf_purge_expired_fragments();
1465 pf_purge_expired_src_nodes();
1466 pf_purge_unlinked_rules();
1471 VNET_LIST_RUNLOCK();
1475 sx_xunlock(&pf_end_lock);
1480 pf_unload_vnet_purge(void)
1484 * To cleanse up all kifs and rules we need
1485 * two runs: first one clears reference flags,
1486 * then pf_purge_expired_states() doesn't
1487 * raise them, and then second run frees.
1489 pf_purge_unlinked_rules();
1493 * Now purge everything.
1495 pf_purge_expired_states(0, pf_hashmask);
1496 pf_purge_expired_fragments();
1497 pf_purge_expired_src_nodes();
1500 * Now all kifs & rules should be unreferenced,
1501 * thus should be successfully freed.
1503 pf_purge_unlinked_rules();
1509 pf_state_expires(const struct pf_state *state)
1516 /* handle all PFTM_* > PFTM_MAX here */
1517 if (state->timeout == PFTM_PURGE)
1518 return (time_uptime);
1519 KASSERT(state->timeout != PFTM_UNLINKED,
1520 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1521 KASSERT((state->timeout < PFTM_MAX),
1522 ("pf_state_expires: timeout > PFTM_MAX"));
1523 timeout = state->rule.ptr->timeout[state->timeout];
1525 timeout = V_pf_default_rule.timeout[state->timeout];
1526 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1528 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1529 states = counter_u64_fetch(state->rule.ptr->states_cur);
1531 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1532 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1533 states = V_pf_status.states;
1535 if (end && states > start && start < end) {
1537 return (state->expire + timeout * (end - states) /
1540 return (time_uptime);
1542 return (state->expire + timeout);
1546 pf_purge_expired_src_nodes()
1548 struct pf_src_node_list freelist;
1549 struct pf_srchash *sh;
1550 struct pf_src_node *cur, *next;
1553 LIST_INIT(&freelist);
1554 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1555 PF_HASHROW_LOCK(sh);
1556 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1557 if (cur->states == 0 && cur->expire <= time_uptime) {
1558 pf_unlink_src_node(cur);
1559 LIST_INSERT_HEAD(&freelist, cur, entry);
1560 } else if (cur->rule.ptr != NULL)
1561 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1562 PF_HASHROW_UNLOCK(sh);
1565 pf_free_src_nodes(&freelist);
1567 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1571 pf_src_tree_remove_state(struct pf_state *s)
1573 struct pf_src_node *sn;
1574 struct pf_srchash *sh;
1577 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1578 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1579 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1581 if (s->src_node != NULL) {
1583 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1584 PF_HASHROW_LOCK(sh);
1587 if (--sn->states == 0)
1588 sn->expire = time_uptime + timeout;
1589 PF_HASHROW_UNLOCK(sh);
1591 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1592 sn = s->nat_src_node;
1593 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1594 PF_HASHROW_LOCK(sh);
1595 if (--sn->states == 0)
1596 sn->expire = time_uptime + timeout;
1597 PF_HASHROW_UNLOCK(sh);
1599 s->src_node = s->nat_src_node = NULL;
1603 * Unlink and potentilly free a state. Function may be
1604 * called with ID hash row locked, but always returns
1605 * unlocked, since it needs to go through key hash locking.
1608 pf_unlink_state(struct pf_state *s, u_int flags)
1610 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1612 if ((flags & PF_ENTER_LOCKED) == 0)
1613 PF_HASHROW_LOCK(ih);
1615 PF_HASHROW_ASSERT(ih);
1617 if (s->timeout == PFTM_UNLINKED) {
1619 * State is being processed
1620 * by pf_unlink_state() in
1623 PF_HASHROW_UNLOCK(ih);
1624 return (0); /* XXXGL: undefined actually */
1627 if (s->src.state == PF_TCPS_PROXY_DST) {
1628 /* XXX wire key the right one? */
1629 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1630 &s->key[PF_SK_WIRE]->addr[1],
1631 &s->key[PF_SK_WIRE]->addr[0],
1632 s->key[PF_SK_WIRE]->port[1],
1633 s->key[PF_SK_WIRE]->port[0],
1634 s->src.seqhi, s->src.seqlo + 1,
1635 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1638 LIST_REMOVE(s, entry);
1639 pf_src_tree_remove_state(s);
1641 if (pfsync_delete_state_ptr != NULL)
1642 pfsync_delete_state_ptr(s);
1644 STATE_DEC_COUNTERS(s);
1646 s->timeout = PFTM_UNLINKED;
1648 PF_HASHROW_UNLOCK(ih);
1651 refcount_release(&s->refs);
1653 return (pf_release_state(s));
1657 pf_free_state(struct pf_state *cur)
1660 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1661 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1664 pf_normalize_tcp_cleanup(cur);
1665 uma_zfree(V_pf_state_z, cur);
1666 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1670 * Called only from pf_purge_thread(), thus serialized.
1673 pf_purge_expired_states(u_int i, int maxcheck)
1675 struct pf_idhash *ih;
1678 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1681 * Go through hash and unlink states that expire now.
1683 while (maxcheck > 0) {
1685 ih = &V_pf_idhash[i];
1687 PF_HASHROW_LOCK(ih);
1688 LIST_FOREACH(s, &ih->states, entry) {
1689 if (pf_state_expires(s) <= time_uptime) {
1690 V_pf_status.states -=
1691 pf_unlink_state(s, PF_ENTER_LOCKED);
1694 s->rule.ptr->rule_flag |= PFRULE_REFS;
1695 if (s->nat_rule.ptr != NULL)
1696 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1697 if (s->anchor.ptr != NULL)
1698 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1699 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1701 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1703 PF_HASHROW_UNLOCK(ih);
1705 /* Return when we hit end of hash. */
1706 if (++i > pf_hashmask) {
1707 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1714 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1720 pf_purge_unlinked_rules()
1722 struct pf_rulequeue tmpq;
1723 struct pf_rule *r, *r1;
1726 * If we have overloading task pending, then we'd
1727 * better skip purging this time. There is a tiny
1728 * probability that overloading task references
1729 * an already unlinked rule.
1731 PF_OVERLOADQ_LOCK();
1732 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1733 PF_OVERLOADQ_UNLOCK();
1736 PF_OVERLOADQ_UNLOCK();
1739 * Do naive mark-and-sweep garbage collecting of old rules.
1740 * Reference flag is raised by pf_purge_expired_states()
1741 * and pf_purge_expired_src_nodes().
1743 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1744 * use a temporary queue.
1747 PF_UNLNKDRULES_LOCK();
1748 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1749 if (!(r->rule_flag & PFRULE_REFS)) {
1750 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1751 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1753 r->rule_flag &= ~PFRULE_REFS;
1755 PF_UNLNKDRULES_UNLOCK();
1757 if (!TAILQ_EMPTY(&tmpq)) {
1759 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1760 TAILQ_REMOVE(&tmpq, r, entries);
1768 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1773 u_int32_t a = ntohl(addr->addr32[0]);
1774 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1786 u_int8_t i, curstart, curend, maxstart, maxend;
1787 curstart = curend = maxstart = maxend = 255;
1788 for (i = 0; i < 8; i++) {
1789 if (!addr->addr16[i]) {
1790 if (curstart == 255)
1794 if ((curend - curstart) >
1795 (maxend - maxstart)) {
1796 maxstart = curstart;
1799 curstart = curend = 255;
1802 if ((curend - curstart) >
1803 (maxend - maxstart)) {
1804 maxstart = curstart;
1807 for (i = 0; i < 8; i++) {
1808 if (i >= maxstart && i <= maxend) {
1814 b = ntohs(addr->addr16[i]);
1831 pf_print_state(struct pf_state *s)
1833 pf_print_state_parts(s, NULL, NULL);
1837 pf_print_state_parts(struct pf_state *s,
1838 struct pf_state_key *skwp, struct pf_state_key *sksp)
1840 struct pf_state_key *skw, *sks;
1841 u_int8_t proto, dir;
1843 /* Do our best to fill these, but they're skipped if NULL */
1844 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1845 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1846 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1847 dir = s ? s->direction : 0;
1865 case IPPROTO_ICMPV6:
1869 printf("%u", proto);
1882 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1884 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1889 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1891 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1896 if (proto == IPPROTO_TCP) {
1897 printf(" [lo=%u high=%u win=%u modulator=%u",
1898 s->src.seqlo, s->src.seqhi,
1899 s->src.max_win, s->src.seqdiff);
1900 if (s->src.wscale && s->dst.wscale)
1901 printf(" wscale=%u",
1902 s->src.wscale & PF_WSCALE_MASK);
1904 printf(" [lo=%u high=%u win=%u modulator=%u",
1905 s->dst.seqlo, s->dst.seqhi,
1906 s->dst.max_win, s->dst.seqdiff);
1907 if (s->src.wscale && s->dst.wscale)
1908 printf(" wscale=%u",
1909 s->dst.wscale & PF_WSCALE_MASK);
1912 printf(" %u:%u", s->src.state, s->dst.state);
1917 pf_print_flags(u_int8_t f)
1939 #define PF_SET_SKIP_STEPS(i) \
1941 while (head[i] != cur) { \
1942 head[i]->skip[i].ptr = cur; \
1943 head[i] = TAILQ_NEXT(head[i], entries); \
1948 pf_calc_skip_steps(struct pf_rulequeue *rules)
1950 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1953 cur = TAILQ_FIRST(rules);
1955 for (i = 0; i < PF_SKIP_COUNT; ++i)
1957 while (cur != NULL) {
1959 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1960 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1961 if (cur->direction != prev->direction)
1962 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1963 if (cur->af != prev->af)
1964 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1965 if (cur->proto != prev->proto)
1966 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1967 if (cur->src.neg != prev->src.neg ||
1968 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1969 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1970 if (cur->src.port[0] != prev->src.port[0] ||
1971 cur->src.port[1] != prev->src.port[1] ||
1972 cur->src.port_op != prev->src.port_op)
1973 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1974 if (cur->dst.neg != prev->dst.neg ||
1975 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1976 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1977 if (cur->dst.port[0] != prev->dst.port[0] ||
1978 cur->dst.port[1] != prev->dst.port[1] ||
1979 cur->dst.port_op != prev->dst.port_op)
1980 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1983 cur = TAILQ_NEXT(cur, entries);
1985 for (i = 0; i < PF_SKIP_COUNT; ++i)
1986 PF_SET_SKIP_STEPS(i);
1990 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1992 if (aw1->type != aw2->type)
1994 switch (aw1->type) {
1995 case PF_ADDR_ADDRMASK:
1997 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
1999 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2002 case PF_ADDR_DYNIFTL:
2003 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2004 case PF_ADDR_NOROUTE:
2005 case PF_ADDR_URPFFAILED:
2008 return (aw1->p.tbl != aw2->p.tbl);
2010 printf("invalid address type: %d\n", aw1->type);
2016 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2017 * header isn't always a full checksum. In some cases (i.e. output) it's a
2018 * pseudo-header checksum, which is a partial checksum over src/dst IP
2019 * addresses, protocol number and length.
2021 * That means we have the following cases:
2022 * * Input or forwarding: we don't have TSO, the checksum fields are full
2023 * checksums, we need to update the checksum whenever we change anything.
2024 * * Output (i.e. the checksum is a pseudo-header checksum):
2025 * x The field being updated is src/dst address or affects the length of
2026 * the packet. We need to update the pseudo-header checksum (note that this
2027 * checksum is not ones' complement).
2028 * x Some other field is being modified (e.g. src/dst port numbers): We
2029 * don't have to update anything.
2032 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2038 l = cksum + old - new;
2039 l = (l >> 16) + (l & 65535);
2047 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2048 u_int16_t new, u_int8_t udp)
2050 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2053 return (pf_cksum_fixup(cksum, old, new, udp));
2057 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2058 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2064 PF_ACPY(&ao, a, af);
2067 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2075 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2076 ao.addr16[0], an->addr16[0], 0),
2077 ao.addr16[1], an->addr16[1], 0);
2080 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2081 ao.addr16[0], an->addr16[0], u),
2082 ao.addr16[1], an->addr16[1], u);
2084 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2089 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2090 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2091 pf_cksum_fixup(pf_cksum_fixup(*pc,
2092 ao.addr16[0], an->addr16[0], u),
2093 ao.addr16[1], an->addr16[1], u),
2094 ao.addr16[2], an->addr16[2], u),
2095 ao.addr16[3], an->addr16[3], u),
2096 ao.addr16[4], an->addr16[4], u),
2097 ao.addr16[5], an->addr16[5], u),
2098 ao.addr16[6], an->addr16[6], u),
2099 ao.addr16[7], an->addr16[7], u);
2101 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2106 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2107 CSUM_DELAY_DATA_IPV6)) {
2114 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2116 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2120 memcpy(&ao, a, sizeof(ao));
2121 memcpy(a, &an, sizeof(u_int32_t));
2122 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2123 ao % 65536, an % 65536, u);
2127 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2131 memcpy(&ao, a, sizeof(ao));
2132 memcpy(a, &an, sizeof(u_int32_t));
2134 *c = pf_proto_cksum_fixup(m,
2135 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2136 ao % 65536, an % 65536, udp);
2141 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2145 PF_ACPY(&ao, a, AF_INET6);
2146 PF_ACPY(a, an, AF_INET6);
2148 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2149 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2150 pf_cksum_fixup(pf_cksum_fixup(*c,
2151 ao.addr16[0], an->addr16[0], u),
2152 ao.addr16[1], an->addr16[1], u),
2153 ao.addr16[2], an->addr16[2], u),
2154 ao.addr16[3], an->addr16[3], u),
2155 ao.addr16[4], an->addr16[4], u),
2156 ao.addr16[5], an->addr16[5], u),
2157 ao.addr16[6], an->addr16[6], u),
2158 ao.addr16[7], an->addr16[7], u);
2163 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2164 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2165 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2167 struct pf_addr oia, ooa;
2169 PF_ACPY(&oia, ia, af);
2171 PF_ACPY(&ooa, oa, af);
2173 /* Change inner protocol port, fix inner protocol checksum. */
2175 u_int16_t oip = *ip;
2182 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2183 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2185 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2187 /* Change inner ip address, fix inner ip and icmp checksums. */
2188 PF_ACPY(ia, na, af);
2192 u_int32_t oh2c = *h2c;
2194 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2195 oia.addr16[0], ia->addr16[0], 0),
2196 oia.addr16[1], ia->addr16[1], 0);
2197 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2198 oia.addr16[0], ia->addr16[0], 0),
2199 oia.addr16[1], ia->addr16[1], 0);
2200 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2206 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2207 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2208 pf_cksum_fixup(pf_cksum_fixup(*ic,
2209 oia.addr16[0], ia->addr16[0], u),
2210 oia.addr16[1], ia->addr16[1], u),
2211 oia.addr16[2], ia->addr16[2], u),
2212 oia.addr16[3], ia->addr16[3], u),
2213 oia.addr16[4], ia->addr16[4], u),
2214 oia.addr16[5], ia->addr16[5], u),
2215 oia.addr16[6], ia->addr16[6], u),
2216 oia.addr16[7], ia->addr16[7], u);
2220 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2222 PF_ACPY(oa, na, af);
2226 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2227 ooa.addr16[0], oa->addr16[0], 0),
2228 ooa.addr16[1], oa->addr16[1], 0);
2233 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2234 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2235 pf_cksum_fixup(pf_cksum_fixup(*ic,
2236 ooa.addr16[0], oa->addr16[0], u),
2237 ooa.addr16[1], oa->addr16[1], u),
2238 ooa.addr16[2], oa->addr16[2], u),
2239 ooa.addr16[3], oa->addr16[3], u),
2240 ooa.addr16[4], oa->addr16[4], u),
2241 ooa.addr16[5], oa->addr16[5], u),
2242 ooa.addr16[6], oa->addr16[6], u),
2243 ooa.addr16[7], oa->addr16[7], u);
2252 * Need to modulate the sequence numbers in the TCP SACK option
2253 * (credits to Krzysztof Pfaff for report and patch)
2256 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2257 struct tcphdr *th, struct pf_state_peer *dst)
2259 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2260 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2261 int copyback = 0, i, olen;
2262 struct sackblk sack;
2264 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2265 if (hlen < TCPOLEN_SACKLEN ||
2266 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2269 while (hlen >= TCPOLEN_SACKLEN) {
2272 case TCPOPT_EOL: /* FALLTHROUGH */
2280 if (olen >= TCPOLEN_SACKLEN) {
2281 for (i = 2; i + TCPOLEN_SACK <= olen;
2282 i += TCPOLEN_SACK) {
2283 memcpy(&sack, &opt[i], sizeof(sack));
2284 pf_change_proto_a(m, &sack.start, &th->th_sum,
2285 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2286 pf_change_proto_a(m, &sack.end, &th->th_sum,
2287 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2288 memcpy(&opt[i], &sack, sizeof(sack));
2302 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2307 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2308 const struct pf_addr *saddr, const struct pf_addr *daddr,
2309 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2310 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2311 u_int16_t rtag, struct ifnet *ifp)
2313 struct pf_send_entry *pfse;
2317 struct ip *h = NULL;
2320 struct ip6_hdr *h6 = NULL;
2324 struct pf_mtag *pf_mtag;
2329 /* maximum segment size tcp option */
2330 tlen = sizeof(struct tcphdr);
2337 len = sizeof(struct ip) + tlen;
2342 len = sizeof(struct ip6_hdr) + tlen;
2346 panic("%s: unsupported af %d", __func__, af);
2349 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2350 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2353 m = m_gethdr(M_NOWAIT, MT_DATA);
2355 free(pfse, M_PFTEMP);
2359 mac_netinet_firewall_send(m);
2361 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2362 free(pfse, M_PFTEMP);
2367 m->m_flags |= M_SKIP_FIREWALL;
2368 pf_mtag->tag = rtag;
2370 if (r != NULL && r->rtableid >= 0)
2371 M_SETFIB(m, r->rtableid);
2374 if (r != NULL && r->qid) {
2375 pf_mtag->qid = r->qid;
2377 /* add hints for ecn */
2378 pf_mtag->hdr = mtod(m, struct ip *);
2381 m->m_data += max_linkhdr;
2382 m->m_pkthdr.len = m->m_len = len;
2383 m->m_pkthdr.rcvif = NULL;
2384 bzero(m->m_data, len);
2388 h = mtod(m, struct ip *);
2390 /* IP header fields included in the TCP checksum */
2391 h->ip_p = IPPROTO_TCP;
2392 h->ip_len = htons(tlen);
2393 h->ip_src.s_addr = saddr->v4.s_addr;
2394 h->ip_dst.s_addr = daddr->v4.s_addr;
2396 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2401 h6 = mtod(m, struct ip6_hdr *);
2403 /* IP header fields included in the TCP checksum */
2404 h6->ip6_nxt = IPPROTO_TCP;
2405 h6->ip6_plen = htons(tlen);
2406 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2407 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2409 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2415 th->th_sport = sport;
2416 th->th_dport = dport;
2417 th->th_seq = htonl(seq);
2418 th->th_ack = htonl(ack);
2419 th->th_off = tlen >> 2;
2420 th->th_flags = flags;
2421 th->th_win = htons(win);
2424 opt = (char *)(th + 1);
2425 opt[0] = TCPOPT_MAXSEG;
2428 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2435 th->th_sum = in_cksum(m, len);
2437 /* Finish the IP header */
2439 h->ip_hl = sizeof(*h) >> 2;
2440 h->ip_tos = IPTOS_LOWDELAY;
2441 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2442 h->ip_len = htons(len);
2443 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2446 pfse->pfse_type = PFSE_IP;
2452 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2453 sizeof(struct ip6_hdr), tlen);
2455 h6->ip6_vfc |= IPV6_VERSION;
2456 h6->ip6_hlim = IPV6_DEFHLIM;
2458 pfse->pfse_type = PFSE_IP6;
2467 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2471 KASSERT(prio <= PF_PRIO_MAX,
2472 ("%s with invalid pcp", __func__));
2474 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2476 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2477 sizeof(uint8_t), M_NOWAIT);
2480 m_tag_prepend(m, mtag);
2483 *(uint8_t *)(mtag + 1) = prio;
2488 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2493 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2497 if (prio == PF_PRIO_ZERO)
2500 mpcp = *(uint8_t *)(mtag + 1);
2502 return (mpcp == prio);
2506 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2509 struct pf_send_entry *pfse;
2511 struct pf_mtag *pf_mtag;
2513 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2514 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2518 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2519 free(pfse, M_PFTEMP);
2523 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2524 free(pfse, M_PFTEMP);
2528 m0->m_flags |= M_SKIP_FIREWALL;
2530 if (r->rtableid >= 0)
2531 M_SETFIB(m0, r->rtableid);
2535 pf_mtag->qid = r->qid;
2536 /* add hints for ecn */
2537 pf_mtag->hdr = mtod(m0, struct ip *);
2544 pfse->pfse_type = PFSE_ICMP;
2549 pfse->pfse_type = PFSE_ICMP6;
2554 pfse->icmpopts.type = type;
2555 pfse->icmpopts.code = code;
2560 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2561 * If n is 0, they match if they are equal. If n is != 0, they match if they
2565 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2566 struct pf_addr *b, sa_family_t af)
2573 if ((a->addr32[0] & m->addr32[0]) ==
2574 (b->addr32[0] & m->addr32[0]))
2580 if (((a->addr32[0] & m->addr32[0]) ==
2581 (b->addr32[0] & m->addr32[0])) &&
2582 ((a->addr32[1] & m->addr32[1]) ==
2583 (b->addr32[1] & m->addr32[1])) &&
2584 ((a->addr32[2] & m->addr32[2]) ==
2585 (b->addr32[2] & m->addr32[2])) &&
2586 ((a->addr32[3] & m->addr32[3]) ==
2587 (b->addr32[3] & m->addr32[3])))
2606 * Return 1 if b <= a <= e, otherwise return 0.
2609 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2610 struct pf_addr *a, sa_family_t af)
2615 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2616 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2625 for (i = 0; i < 4; ++i)
2626 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2628 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2631 for (i = 0; i < 4; ++i)
2632 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2634 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2644 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2648 return ((p > a1) && (p < a2));
2650 return ((p < a1) || (p > a2));
2652 return ((p >= a1) && (p <= a2));
2666 return (0); /* never reached */
2670 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2675 return (pf_match(op, a1, a2, p));
2679 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2681 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2683 return (pf_match(op, a1, a2, u));
2687 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2689 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2691 return (pf_match(op, a1, a2, g));
2695 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2700 return ((!r->match_tag_not && r->match_tag == *tag) ||
2701 (r->match_tag_not && r->match_tag != *tag));
2705 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2708 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2710 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2713 pd->pf_mtag->tag = tag;
2718 #define PF_ANCHOR_STACKSIZE 32
2719 struct pf_anchor_stackframe {
2720 struct pf_ruleset *rs;
2721 struct pf_rule *r; /* XXX: + match bit */
2722 struct pf_anchor *child;
2726 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2728 #define PF_ANCHORSTACK_MATCH 0x00000001
2729 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2731 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2732 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2733 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2734 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2735 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2739 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2740 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2743 struct pf_anchor_stackframe *f;
2749 if (*depth >= PF_ANCHOR_STACKSIZE) {
2750 printf("%s: anchor stack overflow on %s\n",
2751 __func__, (*r)->anchor->name);
2752 *r = TAILQ_NEXT(*r, entries);
2754 } else if (*depth == 0 && a != NULL)
2756 f = stack + (*depth)++;
2759 if ((*r)->anchor_wildcard) {
2760 struct pf_anchor_node *parent = &(*r)->anchor->children;
2762 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2766 *rs = &f->child->ruleset;
2769 *rs = &(*r)->anchor->ruleset;
2771 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2775 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2776 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2779 struct pf_anchor_stackframe *f;
2788 f = stack + *depth - 1;
2789 fr = PF_ANCHOR_RULE(f);
2790 if (f->child != NULL) {
2791 struct pf_anchor_node *parent;
2794 * This block traverses through
2795 * a wildcard anchor.
2797 parent = &fr->anchor->children;
2798 if (match != NULL && *match) {
2800 * If any of "*" matched, then
2801 * "foo/ *" matched, mark frame
2804 PF_ANCHOR_SET_MATCH(f);
2807 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2808 if (f->child != NULL) {
2809 *rs = &f->child->ruleset;
2810 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2818 if (*depth == 0 && a != NULL)
2821 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2823 *r = TAILQ_NEXT(fr, entries);
2824 } while (*r == NULL);
2831 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2832 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2837 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2838 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2842 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2843 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2844 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2845 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2846 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2847 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2848 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2849 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2855 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2860 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2864 if (addr->addr32[3] == 0xffffffff) {
2865 addr->addr32[3] = 0;
2866 if (addr->addr32[2] == 0xffffffff) {
2867 addr->addr32[2] = 0;
2868 if (addr->addr32[1] == 0xffffffff) {
2869 addr->addr32[1] = 0;
2871 htonl(ntohl(addr->addr32[0]) + 1);
2874 htonl(ntohl(addr->addr32[1]) + 1);
2877 htonl(ntohl(addr->addr32[2]) + 1);
2880 htonl(ntohl(addr->addr32[3]) + 1);
2887 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2889 struct pf_addr *saddr, *daddr;
2890 u_int16_t sport, dport;
2891 struct inpcbinfo *pi;
2894 pd->lookup.uid = UID_MAX;
2895 pd->lookup.gid = GID_MAX;
2897 switch (pd->proto) {
2899 if (pd->hdr.tcp == NULL)
2901 sport = pd->hdr.tcp->th_sport;
2902 dport = pd->hdr.tcp->th_dport;
2906 if (pd->hdr.udp == NULL)
2908 sport = pd->hdr.udp->uh_sport;
2909 dport = pd->hdr.udp->uh_dport;
2915 if (direction == PF_IN) {
2930 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2931 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2933 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2934 daddr->v4, dport, INPLOOKUP_WILDCARD |
2935 INPLOOKUP_RLOCKPCB, NULL, m);
2943 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2944 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2946 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2947 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2948 INPLOOKUP_RLOCKPCB, NULL, m);
2958 INP_RLOCK_ASSERT(inp);
2959 pd->lookup.uid = inp->inp_cred->cr_uid;
2960 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2967 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2971 u_int8_t *opt, optlen;
2972 u_int8_t wscale = 0;
2974 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2975 if (hlen <= sizeof(struct tcphdr))
2977 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2979 opt = hdr + sizeof(struct tcphdr);
2980 hlen -= sizeof(struct tcphdr);
2990 if (wscale > TCP_MAX_WINSHIFT)
2991 wscale = TCP_MAX_WINSHIFT;
2992 wscale |= PF_WSCALE_FLAG;
3007 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3011 u_int8_t *opt, optlen;
3012 u_int16_t mss = V_tcp_mssdflt;
3014 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3015 if (hlen <= sizeof(struct tcphdr))
3017 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3019 opt = hdr + sizeof(struct tcphdr);
3020 hlen -= sizeof(struct tcphdr);
3021 while (hlen >= TCPOLEN_MAXSEG) {
3029 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3045 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3048 struct nhop4_basic nh4;
3051 struct nhop6_basic nh6;
3052 struct in6_addr dst6;
3061 hlen = sizeof(struct ip);
3062 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3063 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3068 hlen = sizeof(struct ip6_hdr);
3069 in6_splitscope(&addr->v6, &dst6, &scopeid);
3070 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3071 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3076 mss = max(V_tcp_mssdflt, mss);
3077 mss = min(mss, offer);
3078 mss = max(mss, 64); /* sanity - at least max opt space */
3083 pf_tcp_iss(struct pf_pdesc *pd)
3086 u_int32_t digest[4];
3088 if (V_pf_tcp_secret_init == 0) {
3089 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3090 MD5Init(&V_pf_tcp_secret_ctx);
3091 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3092 sizeof(V_pf_tcp_secret));
3093 V_pf_tcp_secret_init = 1;
3096 ctx = V_pf_tcp_secret_ctx;
3098 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3099 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3100 if (pd->af == AF_INET6) {
3101 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3102 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3104 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3105 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3107 MD5Final((u_char *)digest, &ctx);
3108 V_pf_tcp_iss_off += 4096;
3109 #define ISN_RANDOM_INCREMENT (4096 - 1)
3110 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3112 #undef ISN_RANDOM_INCREMENT
3116 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3117 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3118 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3120 struct pf_rule *nr = NULL;
3121 struct pf_addr * const saddr = pd->src;
3122 struct pf_addr * const daddr = pd->dst;
3123 sa_family_t af = pd->af;
3124 struct pf_rule *r, *a = NULL;
3125 struct pf_ruleset *ruleset = NULL;
3126 struct pf_src_node *nsn = NULL;
3127 struct tcphdr *th = pd->hdr.tcp;
3128 struct pf_state_key *sk = NULL, *nk = NULL;
3130 int rewrite = 0, hdrlen = 0;
3131 int tag = -1, rtableid = -1;
3135 u_int16_t sport = 0, dport = 0;
3136 u_int16_t bproto_sum = 0, bip_sum = 0;
3137 u_int8_t icmptype = 0, icmpcode = 0;
3138 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3143 INP_LOCK_ASSERT(inp);
3144 pd->lookup.uid = inp->inp_cred->cr_uid;
3145 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3146 pd->lookup.done = 1;
3149 switch (pd->proto) {
3151 sport = th->th_sport;
3152 dport = th->th_dport;
3153 hdrlen = sizeof(*th);
3156 sport = pd->hdr.udp->uh_sport;
3157 dport = pd->hdr.udp->uh_dport;
3158 hdrlen = sizeof(*pd->hdr.udp);
3162 if (pd->af != AF_INET)
3164 sport = dport = pd->hdr.icmp->icmp_id;
3165 hdrlen = sizeof(*pd->hdr.icmp);
3166 icmptype = pd->hdr.icmp->icmp_type;
3167 icmpcode = pd->hdr.icmp->icmp_code;
3169 if (icmptype == ICMP_UNREACH ||
3170 icmptype == ICMP_SOURCEQUENCH ||
3171 icmptype == ICMP_REDIRECT ||
3172 icmptype == ICMP_TIMXCEED ||
3173 icmptype == ICMP_PARAMPROB)
3178 case IPPROTO_ICMPV6:
3181 sport = dport = pd->hdr.icmp6->icmp6_id;
3182 hdrlen = sizeof(*pd->hdr.icmp6);
3183 icmptype = pd->hdr.icmp6->icmp6_type;
3184 icmpcode = pd->hdr.icmp6->icmp6_code;
3186 if (icmptype == ICMP6_DST_UNREACH ||
3187 icmptype == ICMP6_PACKET_TOO_BIG ||
3188 icmptype == ICMP6_TIME_EXCEEDED ||
3189 icmptype == ICMP6_PARAM_PROB)
3194 sport = dport = hdrlen = 0;
3198 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3200 /* check packet for BINAT/NAT/RDR */
3201 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3202 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3203 KASSERT(sk != NULL, ("%s: null sk", __func__));
3204 KASSERT(nk != NULL, ("%s: null nk", __func__));
3207 bip_sum = *pd->ip_sum;
3209 switch (pd->proto) {
3211 bproto_sum = th->th_sum;
3212 pd->proto_sum = &th->th_sum;
3214 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3215 nk->port[pd->sidx] != sport) {
3216 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3217 &th->th_sum, &nk->addr[pd->sidx],
3218 nk->port[pd->sidx], 0, af);
3219 pd->sport = &th->th_sport;
3220 sport = th->th_sport;
3223 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3224 nk->port[pd->didx] != dport) {
3225 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3226 &th->th_sum, &nk->addr[pd->didx],
3227 nk->port[pd->didx], 0, af);
3228 dport = th->th_dport;
3229 pd->dport = &th->th_dport;
3234 bproto_sum = pd->hdr.udp->uh_sum;
3235 pd->proto_sum = &pd->hdr.udp->uh_sum;
3237 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3238 nk->port[pd->sidx] != sport) {
3239 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3240 pd->ip_sum, &pd->hdr.udp->uh_sum,
3241 &nk->addr[pd->sidx],
3242 nk->port[pd->sidx], 1, af);
3243 sport = pd->hdr.udp->uh_sport;
3244 pd->sport = &pd->hdr.udp->uh_sport;
3247 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3248 nk->port[pd->didx] != dport) {
3249 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3250 pd->ip_sum, &pd->hdr.udp->uh_sum,
3251 &nk->addr[pd->didx],
3252 nk->port[pd->didx], 1, af);
3253 dport = pd->hdr.udp->uh_dport;
3254 pd->dport = &pd->hdr.udp->uh_dport;
3260 nk->port[0] = nk->port[1];
3261 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3262 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3263 nk->addr[pd->sidx].v4.s_addr, 0);
3265 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3266 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3267 nk->addr[pd->didx].v4.s_addr, 0);
3269 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3270 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3271 pd->hdr.icmp->icmp_cksum, sport,
3273 pd->hdr.icmp->icmp_id = nk->port[1];
3274 pd->sport = &pd->hdr.icmp->icmp_id;
3276 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3280 case IPPROTO_ICMPV6:
3281 nk->port[0] = nk->port[1];
3282 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3283 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3284 &nk->addr[pd->sidx], 0);
3286 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3287 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3288 &nk->addr[pd->didx], 0);
3297 &nk->addr[pd->sidx], AF_INET))
3298 pf_change_a(&saddr->v4.s_addr,
3300 nk->addr[pd->sidx].v4.s_addr, 0);
3303 &nk->addr[pd->didx], AF_INET))
3304 pf_change_a(&daddr->v4.s_addr,
3306 nk->addr[pd->didx].v4.s_addr, 0);
3312 &nk->addr[pd->sidx], AF_INET6))
3313 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3316 &nk->addr[pd->didx], AF_INET6))
3317 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3330 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3331 r = r->skip[PF_SKIP_IFP].ptr;
3332 else if (r->direction && r->direction != direction)
3333 r = r->skip[PF_SKIP_DIR].ptr;
3334 else if (r->af && r->af != af)
3335 r = r->skip[PF_SKIP_AF].ptr;
3336 else if (r->proto && r->proto != pd->proto)
3337 r = r->skip[PF_SKIP_PROTO].ptr;
3338 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3339 r->src.neg, kif, M_GETFIB(m)))
3340 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3341 /* tcp/udp only. port_op always 0 in other cases */
3342 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3343 r->src.port[0], r->src.port[1], sport))
3344 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3345 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3346 r->dst.neg, NULL, M_GETFIB(m)))
3347 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3348 /* tcp/udp only. port_op always 0 in other cases */
3349 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3350 r->dst.port[0], r->dst.port[1], dport))
3351 r = r->skip[PF_SKIP_DST_PORT].ptr;
3352 /* icmp only. type always 0 in other cases */
3353 else if (r->type && r->type != icmptype + 1)
3354 r = TAILQ_NEXT(r, entries);
3355 /* icmp only. type always 0 in other cases */
3356 else if (r->code && r->code != icmpcode + 1)
3357 r = TAILQ_NEXT(r, entries);
3358 else if (r->tos && !(r->tos == pd->tos))
3359 r = TAILQ_NEXT(r, entries);
3360 else if (r->rule_flag & PFRULE_FRAGMENT)
3361 r = TAILQ_NEXT(r, entries);
3362 else if (pd->proto == IPPROTO_TCP &&
3363 (r->flagset & th->th_flags) != r->flags)
3364 r = TAILQ_NEXT(r, entries);
3365 /* tcp/udp only. uid.op always 0 in other cases */
3366 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3367 pf_socket_lookup(direction, pd, m), 1)) &&
3368 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3370 r = TAILQ_NEXT(r, entries);
3371 /* tcp/udp only. gid.op always 0 in other cases */
3372 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3373 pf_socket_lookup(direction, pd, m), 1)) &&
3374 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3376 r = TAILQ_NEXT(r, entries);
3378 !pf_match_ieee8021q_pcp(r->prio, m))
3379 r = TAILQ_NEXT(r, entries);
3381 r->prob <= arc4random())
3382 r = TAILQ_NEXT(r, entries);
3383 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3384 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3385 r = TAILQ_NEXT(r, entries);
3386 else if (r->os_fingerprint != PF_OSFP_ANY &&
3387 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3388 pf_osfp_fingerprint(pd, m, off, th),
3389 r->os_fingerprint)))
3390 r = TAILQ_NEXT(r, entries);
3394 if (r->rtableid >= 0)
3395 rtableid = r->rtableid;
3396 if (r->anchor == NULL) {
3403 r = TAILQ_NEXT(r, entries);
3405 pf_step_into_anchor(anchor_stack, &asd,
3406 &ruleset, PF_RULESET_FILTER, &r, &a,
3409 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3410 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3417 REASON_SET(&reason, PFRES_MATCH);
3419 if (r->log || (nr != NULL && nr->log)) {
3421 m_copyback(m, off, hdrlen, pd->hdr.any);
3422 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3426 if ((r->action == PF_DROP) &&
3427 ((r->rule_flag & PFRULE_RETURNRST) ||
3428 (r->rule_flag & PFRULE_RETURNICMP) ||
3429 (r->rule_flag & PFRULE_RETURN))) {
3430 /* undo NAT changes, if they have taken place */
3432 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3433 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3435 *pd->sport = sk->port[pd->sidx];
3437 *pd->dport = sk->port[pd->didx];
3439 *pd->proto_sum = bproto_sum;
3441 *pd->ip_sum = bip_sum;
3442 m_copyback(m, off, hdrlen, pd->hdr.any);
3444 if (pd->proto == IPPROTO_TCP &&
3445 ((r->rule_flag & PFRULE_RETURNRST) ||
3446 (r->rule_flag & PFRULE_RETURN)) &&
3447 !(th->th_flags & TH_RST)) {
3448 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3460 h4 = mtod(m, struct ip *);
3461 len = ntohs(h4->ip_len) - off;
3466 h6 = mtod(m, struct ip6_hdr *);
3467 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3472 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3473 REASON_SET(&reason, PFRES_PROTCKSUM);
3475 if (th->th_flags & TH_SYN)
3477 if (th->th_flags & TH_FIN)
3479 pf_send_tcp(m, r, af, pd->dst,
3480 pd->src, th->th_dport, th->th_sport,
3481 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3482 r->return_ttl, 1, 0, kif->pfik_ifp);
3484 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3486 pf_send_icmp(m, r->return_icmp >> 8,
3487 r->return_icmp & 255, af, r);
3488 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3490 pf_send_icmp(m, r->return_icmp6 >> 8,
3491 r->return_icmp6 & 255, af, r);
3494 if (r->action == PF_DROP)
3497 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3498 REASON_SET(&reason, PFRES_MEMORY);
3502 M_SETFIB(m, rtableid);
3504 if (!state_icmp && (r->keep_state || nr != NULL ||
3505 (pd->flags & PFDESC_TCP_NORM))) {
3507 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3508 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3510 if (action != PF_PASS)
3514 uma_zfree(V_pf_state_key_z, sk);
3516 uma_zfree(V_pf_state_key_z, nk);
3519 /* copy back packet headers if we performed NAT operations */
3521 m_copyback(m, off, hdrlen, pd->hdr.any);
3523 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3524 direction == PF_OUT &&
3525 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3527 * We want the state created, but we dont
3528 * want to send this in case a partner
3529 * firewall has to know about it to allow
3530 * replies through it.
3538 uma_zfree(V_pf_state_key_z, sk);
3540 uma_zfree(V_pf_state_key_z, nk);
3545 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3546 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3547 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3548 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3549 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3551 struct pf_state *s = NULL;
3552 struct pf_src_node *sn = NULL;
3553 struct tcphdr *th = pd->hdr.tcp;
3554 u_int16_t mss = V_tcp_mssdflt;
3557 /* check maximums */
3558 if (r->max_states &&
3559 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3560 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3561 REASON_SET(&reason, PFRES_MAXSTATES);
3564 /* src node for filter rule */
3565 if ((r->rule_flag & PFRULE_SRCTRACK ||
3566 r->rpool.opts & PF_POOL_STICKYADDR) &&
3567 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3568 REASON_SET(&reason, PFRES_SRCLIMIT);
3571 /* src node for translation rule */
3572 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3573 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3574 REASON_SET(&reason, PFRES_SRCLIMIT);
3577 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3579 REASON_SET(&reason, PFRES_MEMORY);
3583 s->nat_rule.ptr = nr;
3585 STATE_INC_COUNTERS(s);
3587 s->state_flags |= PFSTATE_ALLOWOPTS;
3588 if (r->rule_flag & PFRULE_STATESLOPPY)
3589 s->state_flags |= PFSTATE_SLOPPY;
3590 s->log = r->log & PF_LOG_ALL;
3591 s->sync_state = PFSYNC_S_NONE;
3593 s->log |= nr->log & PF_LOG_ALL;
3594 switch (pd->proto) {
3596 s->src.seqlo = ntohl(th->th_seq);
3597 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3598 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3599 r->keep_state == PF_STATE_MODULATE) {
3600 /* Generate sequence number modulator */
3601 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3604 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3605 htonl(s->src.seqlo + s->src.seqdiff), 0);
3609 if (th->th_flags & TH_SYN) {
3611 s->src.wscale = pf_get_wscale(m, off,
3612 th->th_off, pd->af);
3614 s->src.max_win = MAX(ntohs(th->th_win), 1);
3615 if (s->src.wscale & PF_WSCALE_MASK) {
3616 /* Remove scale factor from initial window */
3617 int win = s->src.max_win;
3618 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3619 s->src.max_win = (win - 1) >>
3620 (s->src.wscale & PF_WSCALE_MASK);
3622 if (th->th_flags & TH_FIN)
3626 s->src.state = TCPS_SYN_SENT;
3627 s->dst.state = TCPS_CLOSED;
3628 s->timeout = PFTM_TCP_FIRST_PACKET;
3631 s->src.state = PFUDPS_SINGLE;
3632 s->dst.state = PFUDPS_NO_TRAFFIC;
3633 s->timeout = PFTM_UDP_FIRST_PACKET;
3637 case IPPROTO_ICMPV6:
3639 s->timeout = PFTM_ICMP_FIRST_PACKET;
3642 s->src.state = PFOTHERS_SINGLE;
3643 s->dst.state = PFOTHERS_NO_TRAFFIC;
3644 s->timeout = PFTM_OTHER_FIRST_PACKET;
3648 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3649 REASON_SET(&reason, PFRES_MAPFAILED);
3650 pf_src_tree_remove_state(s);
3651 STATE_DEC_COUNTERS(s);
3652 uma_zfree(V_pf_state_z, s);
3655 s->rt_kif = r->rpool.cur->kif;
3658 s->creation = time_uptime;
3659 s->expire = time_uptime;
3664 /* XXX We only modify one side for now. */
3665 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3666 s->nat_src_node = nsn;
3668 if (pd->proto == IPPROTO_TCP) {
3669 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3670 off, pd, th, &s->src, &s->dst)) {
3671 REASON_SET(&reason, PFRES_MEMORY);
3672 pf_src_tree_remove_state(s);
3673 STATE_DEC_COUNTERS(s);
3674 uma_zfree(V_pf_state_z, s);
3677 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3678 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3679 &s->src, &s->dst, rewrite)) {
3680 /* This really shouldn't happen!!! */
3681 DPFPRINTF(PF_DEBUG_URGENT,
3682 ("pf_normalize_tcp_stateful failed on first pkt"));
3683 pf_normalize_tcp_cleanup(s);
3684 pf_src_tree_remove_state(s);
3685 STATE_DEC_COUNTERS(s);
3686 uma_zfree(V_pf_state_z, s);
3690 s->direction = pd->dir;
3693 * sk/nk could already been setup by pf_get_translation().
3696 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3697 __func__, nr, sk, nk));
3698 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3703 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3704 __func__, nr, sk, nk));
3706 /* Swap sk/nk for PF_OUT. */
3707 if (pf_state_insert(BOUND_IFACE(r, kif),
3708 (pd->dir == PF_IN) ? sk : nk,
3709 (pd->dir == PF_IN) ? nk : sk, s)) {
3710 if (pd->proto == IPPROTO_TCP)
3711 pf_normalize_tcp_cleanup(s);
3712 REASON_SET(&reason, PFRES_STATEINS);
3713 pf_src_tree_remove_state(s);
3714 STATE_DEC_COUNTERS(s);
3715 uma_zfree(V_pf_state_z, s);
3722 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3723 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3724 s->src.state = PF_TCPS_PROXY_SRC;
3725 /* undo NAT changes, if they have taken place */
3727 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3728 if (pd->dir == PF_OUT)
3729 skt = s->key[PF_SK_STACK];
3730 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3731 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3733 *pd->sport = skt->port[pd->sidx];
3735 *pd->dport = skt->port[pd->didx];
3737 *pd->proto_sum = bproto_sum;
3739 *pd->ip_sum = bip_sum;
3740 m_copyback(m, off, hdrlen, pd->hdr.any);
3742 s->src.seqhi = htonl(arc4random());
3743 /* Find mss option */
3744 int rtid = M_GETFIB(m);
3745 mss = pf_get_mss(m, off, th->th_off, pd->af);
3746 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3747 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3749 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3750 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3751 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3752 REASON_SET(&reason, PFRES_SYNPROXY);
3753 return (PF_SYNPROXY_DROP);
3760 uma_zfree(V_pf_state_key_z, sk);
3762 uma_zfree(V_pf_state_key_z, nk);
3765 struct pf_srchash *sh;
3767 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3768 PF_HASHROW_LOCK(sh);
3769 if (--sn->states == 0 && sn->expire == 0) {
3770 pf_unlink_src_node(sn);
3771 uma_zfree(V_pf_sources_z, sn);
3773 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3775 PF_HASHROW_UNLOCK(sh);
3778 if (nsn != sn && nsn != NULL) {
3779 struct pf_srchash *sh;
3781 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3782 PF_HASHROW_LOCK(sh);
3783 if (--nsn->states == 0 && nsn->expire == 0) {
3784 pf_unlink_src_node(nsn);
3785 uma_zfree(V_pf_sources_z, nsn);
3787 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3789 PF_HASHROW_UNLOCK(sh);
3796 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3797 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3798 struct pf_ruleset **rsm)
3800 struct pf_rule *r, *a = NULL;
3801 struct pf_ruleset *ruleset = NULL;
3802 sa_family_t af = pd->af;
3807 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3811 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3814 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3815 r = r->skip[PF_SKIP_IFP].ptr;
3816 else if (r->direction && r->direction != direction)
3817 r = r->skip[PF_SKIP_DIR].ptr;
3818 else if (r->af && r->af != af)
3819 r = r->skip[PF_SKIP_AF].ptr;
3820 else if (r->proto && r->proto != pd->proto)
3821 r = r->skip[PF_SKIP_PROTO].ptr;
3822 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3823 r->src.neg, kif, M_GETFIB(m)))
3824 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3825 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3826 r->dst.neg, NULL, M_GETFIB(m)))
3827 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3828 else if (r->tos && !(r->tos == pd->tos))
3829 r = TAILQ_NEXT(r, entries);
3830 else if (r->os_fingerprint != PF_OSFP_ANY)
3831 r = TAILQ_NEXT(r, entries);
3832 else if (pd->proto == IPPROTO_UDP &&
3833 (r->src.port_op || r->dst.port_op))
3834 r = TAILQ_NEXT(r, entries);
3835 else if (pd->proto == IPPROTO_TCP &&
3836 (r->src.port_op || r->dst.port_op || r->flagset))
3837 r = TAILQ_NEXT(r, entries);
3838 else if ((pd->proto == IPPROTO_ICMP ||
3839 pd->proto == IPPROTO_ICMPV6) &&
3840 (r->type || r->code))
3841 r = TAILQ_NEXT(r, entries);
3843 !pf_match_ieee8021q_pcp(r->prio, m))
3844 r = TAILQ_NEXT(r, entries);
3845 else if (r->prob && r->prob <=
3846 (arc4random() % (UINT_MAX - 1) + 1))
3847 r = TAILQ_NEXT(r, entries);
3848 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3849 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3850 r = TAILQ_NEXT(r, entries);
3852 if (r->anchor == NULL) {
3859 r = TAILQ_NEXT(r, entries);
3861 pf_step_into_anchor(anchor_stack, &asd,
3862 &ruleset, PF_RULESET_FILTER, &r, &a,
3865 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3866 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3873 REASON_SET(&reason, PFRES_MATCH);
3876 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3879 if (r->action != PF_PASS)
3882 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3883 REASON_SET(&reason, PFRES_MEMORY);
3891 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3892 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3893 struct pf_pdesc *pd, u_short *reason, int *copyback)
3895 struct tcphdr *th = pd->hdr.tcp;
3896 u_int16_t win = ntohs(th->th_win);
3897 u_int32_t ack, end, seq, orig_seq;
3901 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3902 sws = src->wscale & PF_WSCALE_MASK;
3903 dws = dst->wscale & PF_WSCALE_MASK;
3908 * Sequence tracking algorithm from Guido van Rooij's paper:
3909 * http://www.madison-gurkha.com/publications/tcp_filtering/
3913 orig_seq = seq = ntohl(th->th_seq);
3914 if (src->seqlo == 0) {
3915 /* First packet from this end. Set its state */
3917 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3918 src->scrub == NULL) {
3919 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3920 REASON_SET(reason, PFRES_MEMORY);
3925 /* Deferred generation of sequence number modulator */
3926 if (dst->seqdiff && !src->seqdiff) {
3927 /* use random iss for the TCP server */
3928 while ((src->seqdiff = arc4random() - seq) == 0)
3930 ack = ntohl(th->th_ack) - dst->seqdiff;
3931 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3933 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3936 ack = ntohl(th->th_ack);
3939 end = seq + pd->p_len;
3940 if (th->th_flags & TH_SYN) {
3942 if (dst->wscale & PF_WSCALE_FLAG) {
3943 src->wscale = pf_get_wscale(m, off, th->th_off,
3945 if (src->wscale & PF_WSCALE_FLAG) {
3946 /* Remove scale factor from initial
3948 sws = src->wscale & PF_WSCALE_MASK;
3949 win = ((u_int32_t)win + (1 << sws) - 1)
3951 dws = dst->wscale & PF_WSCALE_MASK;
3953 /* fixup other window */
3954 dst->max_win <<= dst->wscale &
3956 /* in case of a retrans SYN|ACK */
3961 if (th->th_flags & TH_FIN)
3965 if (src->state < TCPS_SYN_SENT)
3966 src->state = TCPS_SYN_SENT;
3969 * May need to slide the window (seqhi may have been set by
3970 * the crappy stack check or if we picked up the connection
3971 * after establishment)
3973 if (src->seqhi == 1 ||
3974 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3975 src->seqhi = end + MAX(1, dst->max_win << dws);
3976 if (win > src->max_win)
3980 ack = ntohl(th->th_ack) - dst->seqdiff;
3982 /* Modulate sequence numbers */
3983 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3985 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3988 end = seq + pd->p_len;
3989 if (th->th_flags & TH_SYN)
3991 if (th->th_flags & TH_FIN)
3995 if ((th->th_flags & TH_ACK) == 0) {
3996 /* Let it pass through the ack skew check */
3998 } else if ((ack == 0 &&
3999 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4000 /* broken tcp stacks do not set ack */
4001 (dst->state < TCPS_SYN_SENT)) {
4003 * Many stacks (ours included) will set the ACK number in an
4004 * FIN|ACK if the SYN times out -- no sequence to ACK.
4010 /* Ease sequencing restrictions on no data packets */
4015 ackskew = dst->seqlo - ack;
4019 * Need to demodulate the sequence numbers in any TCP SACK options
4020 * (Selective ACK). We could optionally validate the SACK values
4021 * against the current ACK window, either forwards or backwards, but
4022 * I'm not confident that SACK has been implemented properly
4023 * everywhere. It wouldn't surprise me if several stacks accidentally
4024 * SACK too far backwards of previously ACKed data. There really aren't
4025 * any security implications of bad SACKing unless the target stack
4026 * doesn't validate the option length correctly. Someone trying to
4027 * spoof into a TCP connection won't bother blindly sending SACK
4030 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4031 if (pf_modulate_sack(m, off, pd, th, dst))
4036 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4037 if (SEQ_GEQ(src->seqhi, end) &&
4038 /* Last octet inside other's window space */
4039 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4040 /* Retrans: not more than one window back */
4041 (ackskew >= -MAXACKWINDOW) &&
4042 /* Acking not more than one reassembled fragment backwards */
4043 (ackskew <= (MAXACKWINDOW << sws)) &&
4044 /* Acking not more than one window forward */
4045 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4046 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4047 (pd->flags & PFDESC_IP_REAS) == 0)) {
4048 /* Require an exact/+1 sequence match on resets when possible */
4050 if (dst->scrub || src->scrub) {
4051 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4052 *state, src, dst, copyback))
4056 /* update max window */
4057 if (src->max_win < win)
4059 /* synchronize sequencing */
4060 if (SEQ_GT(end, src->seqlo))
4062 /* slide the window of what the other end can send */
4063 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4064 dst->seqhi = ack + MAX((win << sws), 1);
4068 if (th->th_flags & TH_SYN)
4069 if (src->state < TCPS_SYN_SENT)
4070 src->state = TCPS_SYN_SENT;
4071 if (th->th_flags & TH_FIN)
4072 if (src->state < TCPS_CLOSING)
4073 src->state = TCPS_CLOSING;
4074 if (th->th_flags & TH_ACK) {
4075 if (dst->state == TCPS_SYN_SENT) {
4076 dst->state = TCPS_ESTABLISHED;
4077 if (src->state == TCPS_ESTABLISHED &&
4078 (*state)->src_node != NULL &&
4079 pf_src_connlimit(state)) {
4080 REASON_SET(reason, PFRES_SRCLIMIT);
4083 } else if (dst->state == TCPS_CLOSING)
4084 dst->state = TCPS_FIN_WAIT_2;
4086 if (th->th_flags & TH_RST)
4087 src->state = dst->state = TCPS_TIME_WAIT;
4089 /* update expire time */
4090 (*state)->expire = time_uptime;
4091 if (src->state >= TCPS_FIN_WAIT_2 &&
4092 dst->state >= TCPS_FIN_WAIT_2)
4093 (*state)->timeout = PFTM_TCP_CLOSED;
4094 else if (src->state >= TCPS_CLOSING &&
4095 dst->state >= TCPS_CLOSING)
4096 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4097 else if (src->state < TCPS_ESTABLISHED ||
4098 dst->state < TCPS_ESTABLISHED)
4099 (*state)->timeout = PFTM_TCP_OPENING;
4100 else if (src->state >= TCPS_CLOSING ||
4101 dst->state >= TCPS_CLOSING)
4102 (*state)->timeout = PFTM_TCP_CLOSING;
4104 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4106 /* Fall through to PASS packet */
4108 } else if ((dst->state < TCPS_SYN_SENT ||
4109 dst->state >= TCPS_FIN_WAIT_2 ||
4110 src->state >= TCPS_FIN_WAIT_2) &&
4111 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4112 /* Within a window forward of the originating packet */
4113 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4114 /* Within a window backward of the originating packet */
4117 * This currently handles three situations:
4118 * 1) Stupid stacks will shotgun SYNs before their peer
4120 * 2) When PF catches an already established stream (the
4121 * firewall rebooted, the state table was flushed, routes
4123 * 3) Packets get funky immediately after the connection
4124 * closes (this should catch Solaris spurious ACK|FINs
4125 * that web servers like to spew after a close)
4127 * This must be a little more careful than the above code
4128 * since packet floods will also be caught here. We don't
4129 * update the TTL here to mitigate the damage of a packet
4130 * flood and so the same code can handle awkward establishment
4131 * and a loosened connection close.
4132 * In the establishment case, a correct peer response will
4133 * validate the connection, go through the normal state code
4134 * and keep updating the state TTL.
4137 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4138 printf("pf: loose state match: ");
4139 pf_print_state(*state);
4140 pf_print_flags(th->th_flags);
4141 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4142 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4143 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4144 (unsigned long long)(*state)->packets[1],
4145 pd->dir == PF_IN ? "in" : "out",
4146 pd->dir == (*state)->direction ? "fwd" : "rev");
4149 if (dst->scrub || src->scrub) {
4150 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4151 *state, src, dst, copyback))
4155 /* update max window */
4156 if (src->max_win < win)
4158 /* synchronize sequencing */
4159 if (SEQ_GT(end, src->seqlo))
4161 /* slide the window of what the other end can send */
4162 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4163 dst->seqhi = ack + MAX((win << sws), 1);
4166 * Cannot set dst->seqhi here since this could be a shotgunned
4167 * SYN and not an already established connection.
4170 if (th->th_flags & TH_FIN)
4171 if (src->state < TCPS_CLOSING)
4172 src->state = TCPS_CLOSING;
4173 if (th->th_flags & TH_RST)
4174 src->state = dst->state = TCPS_TIME_WAIT;
4176 /* Fall through to PASS packet */
4179 if ((*state)->dst.state == TCPS_SYN_SENT &&
4180 (*state)->src.state == TCPS_SYN_SENT) {
4181 /* Send RST for state mismatches during handshake */
4182 if (!(th->th_flags & TH_RST))
4183 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4184 pd->dst, pd->src, th->th_dport,
4185 th->th_sport, ntohl(th->th_ack), 0,
4187 (*state)->rule.ptr->return_ttl, 1, 0,
4192 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4193 printf("pf: BAD state: ");
4194 pf_print_state(*state);
4195 pf_print_flags(th->th_flags);
4196 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4197 "pkts=%llu:%llu dir=%s,%s\n",
4198 seq, orig_seq, ack, pd->p_len, ackskew,
4199 (unsigned long long)(*state)->packets[0],
4200 (unsigned long long)(*state)->packets[1],
4201 pd->dir == PF_IN ? "in" : "out",
4202 pd->dir == (*state)->direction ? "fwd" : "rev");
4203 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4204 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4205 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4207 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4208 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4209 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4210 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4212 REASON_SET(reason, PFRES_BADSTATE);
4220 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4221 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4223 struct tcphdr *th = pd->hdr.tcp;
4225 if (th->th_flags & TH_SYN)
4226 if (src->state < TCPS_SYN_SENT)
4227 src->state = TCPS_SYN_SENT;
4228 if (th->th_flags & TH_FIN)
4229 if (src->state < TCPS_CLOSING)
4230 src->state = TCPS_CLOSING;
4231 if (th->th_flags & TH_ACK) {
4232 if (dst->state == TCPS_SYN_SENT) {
4233 dst->state = TCPS_ESTABLISHED;
4234 if (src->state == TCPS_ESTABLISHED &&
4235 (*state)->src_node != NULL &&
4236 pf_src_connlimit(state)) {
4237 REASON_SET(reason, PFRES_SRCLIMIT);
4240 } else if (dst->state == TCPS_CLOSING) {
4241 dst->state = TCPS_FIN_WAIT_2;
4242 } else if (src->state == TCPS_SYN_SENT &&
4243 dst->state < TCPS_SYN_SENT) {
4245 * Handle a special sloppy case where we only see one
4246 * half of the connection. If there is a ACK after
4247 * the initial SYN without ever seeing a packet from
4248 * the destination, set the connection to established.
4250 dst->state = src->state = TCPS_ESTABLISHED;
4251 if ((*state)->src_node != NULL &&
4252 pf_src_connlimit(state)) {
4253 REASON_SET(reason, PFRES_SRCLIMIT);
4256 } else if (src->state == TCPS_CLOSING &&
4257 dst->state == TCPS_ESTABLISHED &&
4260 * Handle the closing of half connections where we
4261 * don't see the full bidirectional FIN/ACK+ACK
4264 dst->state = TCPS_CLOSING;
4267 if (th->th_flags & TH_RST)
4268 src->state = dst->state = TCPS_TIME_WAIT;
4270 /* update expire time */
4271 (*state)->expire = time_uptime;
4272 if (src->state >= TCPS_FIN_WAIT_2 &&
4273 dst->state >= TCPS_FIN_WAIT_2)
4274 (*state)->timeout = PFTM_TCP_CLOSED;
4275 else if (src->state >= TCPS_CLOSING &&
4276 dst->state >= TCPS_CLOSING)
4277 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4278 else if (src->state < TCPS_ESTABLISHED ||
4279 dst->state < TCPS_ESTABLISHED)
4280 (*state)->timeout = PFTM_TCP_OPENING;
4281 else if (src->state >= TCPS_CLOSING ||
4282 dst->state >= TCPS_CLOSING)
4283 (*state)->timeout = PFTM_TCP_CLOSING;
4285 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4291 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4292 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4295 struct pf_state_key_cmp key;
4296 struct tcphdr *th = pd->hdr.tcp;
4298 struct pf_state_peer *src, *dst;
4299 struct pf_state_key *sk;
4301 bzero(&key, sizeof(key));
4303 key.proto = IPPROTO_TCP;
4304 if (direction == PF_IN) { /* wire side, straight */
4305 PF_ACPY(&key.addr[0], pd->src, key.af);
4306 PF_ACPY(&key.addr[1], pd->dst, key.af);
4307 key.port[0] = th->th_sport;
4308 key.port[1] = th->th_dport;
4309 } else { /* stack side, reverse */
4310 PF_ACPY(&key.addr[1], pd->src, key.af);
4311 PF_ACPY(&key.addr[0], pd->dst, key.af);
4312 key.port[1] = th->th_sport;
4313 key.port[0] = th->th_dport;
4316 STATE_LOOKUP(kif, &key, direction, *state, pd);
4318 if (direction == (*state)->direction) {
4319 src = &(*state)->src;
4320 dst = &(*state)->dst;
4322 src = &(*state)->dst;
4323 dst = &(*state)->src;
4326 sk = (*state)->key[pd->didx];
4328 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4329 if (direction != (*state)->direction) {
4330 REASON_SET(reason, PFRES_SYNPROXY);
4331 return (PF_SYNPROXY_DROP);
4333 if (th->th_flags & TH_SYN) {
4334 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4335 REASON_SET(reason, PFRES_SYNPROXY);
4338 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4339 pd->src, th->th_dport, th->th_sport,
4340 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4341 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4342 REASON_SET(reason, PFRES_SYNPROXY);
4343 return (PF_SYNPROXY_DROP);
4344 } else if (!(th->th_flags & TH_ACK) ||
4345 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4346 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4347 REASON_SET(reason, PFRES_SYNPROXY);
4349 } else if ((*state)->src_node != NULL &&
4350 pf_src_connlimit(state)) {
4351 REASON_SET(reason, PFRES_SRCLIMIT);
4354 (*state)->src.state = PF_TCPS_PROXY_DST;
4356 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4357 if (direction == (*state)->direction) {
4358 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4359 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4360 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4361 REASON_SET(reason, PFRES_SYNPROXY);
4364 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4365 if ((*state)->dst.seqhi == 1)
4366 (*state)->dst.seqhi = htonl(arc4random());
4367 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4368 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4369 sk->port[pd->sidx], sk->port[pd->didx],
4370 (*state)->dst.seqhi, 0, TH_SYN, 0,
4371 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4372 REASON_SET(reason, PFRES_SYNPROXY);
4373 return (PF_SYNPROXY_DROP);
4374 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4376 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4377 REASON_SET(reason, PFRES_SYNPROXY);
4380 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4381 (*state)->dst.seqlo = ntohl(th->th_seq);
4382 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4383 pd->src, th->th_dport, th->th_sport,
4384 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4385 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4386 (*state)->tag, NULL);
4387 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4388 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4389 sk->port[pd->sidx], sk->port[pd->didx],
4390 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4391 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4392 (*state)->src.seqdiff = (*state)->dst.seqhi -
4393 (*state)->src.seqlo;
4394 (*state)->dst.seqdiff = (*state)->src.seqhi -
4395 (*state)->dst.seqlo;
4396 (*state)->src.seqhi = (*state)->src.seqlo +
4397 (*state)->dst.max_win;
4398 (*state)->dst.seqhi = (*state)->dst.seqlo +
4399 (*state)->src.max_win;
4400 (*state)->src.wscale = (*state)->dst.wscale = 0;
4401 (*state)->src.state = (*state)->dst.state =
4403 REASON_SET(reason, PFRES_SYNPROXY);
4404 return (PF_SYNPROXY_DROP);
4408 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4409 dst->state >= TCPS_FIN_WAIT_2 &&
4410 src->state >= TCPS_FIN_WAIT_2) {
4411 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4412 printf("pf: state reuse ");
4413 pf_print_state(*state);
4414 pf_print_flags(th->th_flags);
4417 /* XXX make sure it's the same direction ?? */
4418 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4419 pf_unlink_state(*state, PF_ENTER_LOCKED);
4424 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4425 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4428 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4429 ©back) == PF_DROP)
4433 /* translate source/destination address, if necessary */
4434 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4435 struct pf_state_key *nk = (*state)->key[pd->didx];
4437 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4438 nk->port[pd->sidx] != th->th_sport)
4439 pf_change_ap(m, pd->src, &th->th_sport,
4440 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4441 nk->port[pd->sidx], 0, pd->af);
4443 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4444 nk->port[pd->didx] != th->th_dport)
4445 pf_change_ap(m, pd->dst, &th->th_dport,
4446 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4447 nk->port[pd->didx], 0, pd->af);
4451 /* Copyback sequence modulation or stateful scrub changes if needed */
4453 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4459 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4460 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4462 struct pf_state_peer *src, *dst;
4463 struct pf_state_key_cmp key;
4464 struct udphdr *uh = pd->hdr.udp;
4466 bzero(&key, sizeof(key));
4468 key.proto = IPPROTO_UDP;
4469 if (direction == PF_IN) { /* wire side, straight */
4470 PF_ACPY(&key.addr[0], pd->src, key.af);
4471 PF_ACPY(&key.addr[1], pd->dst, key.af);
4472 key.port[0] = uh->uh_sport;
4473 key.port[1] = uh->uh_dport;
4474 } else { /* stack side, reverse */
4475 PF_ACPY(&key.addr[1], pd->src, key.af);
4476 PF_ACPY(&key.addr[0], pd->dst, key.af);
4477 key.port[1] = uh->uh_sport;
4478 key.port[0] = uh->uh_dport;
4481 STATE_LOOKUP(kif, &key, direction, *state, pd);
4483 if (direction == (*state)->direction) {
4484 src = &(*state)->src;
4485 dst = &(*state)->dst;
4487 src = &(*state)->dst;
4488 dst = &(*state)->src;
4492 if (src->state < PFUDPS_SINGLE)
4493 src->state = PFUDPS_SINGLE;
4494 if (dst->state == PFUDPS_SINGLE)
4495 dst->state = PFUDPS_MULTIPLE;
4497 /* update expire time */
4498 (*state)->expire = time_uptime;
4499 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4500 (*state)->timeout = PFTM_UDP_MULTIPLE;
4502 (*state)->timeout = PFTM_UDP_SINGLE;
4504 /* translate source/destination address, if necessary */
4505 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4506 struct pf_state_key *nk = (*state)->key[pd->didx];
4508 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4509 nk->port[pd->sidx] != uh->uh_sport)
4510 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4511 &uh->uh_sum, &nk->addr[pd->sidx],
4512 nk->port[pd->sidx], 1, pd->af);
4514 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4515 nk->port[pd->didx] != uh->uh_dport)
4516 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4517 &uh->uh_sum, &nk->addr[pd->didx],
4518 nk->port[pd->didx], 1, pd->af);
4519 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4526 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4527 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4529 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4530 u_int16_t icmpid = 0, *icmpsum;
4533 struct pf_state_key_cmp key;
4535 bzero(&key, sizeof(key));
4536 switch (pd->proto) {
4539 icmptype = pd->hdr.icmp->icmp_type;
4540 icmpid = pd->hdr.icmp->icmp_id;
4541 icmpsum = &pd->hdr.icmp->icmp_cksum;
4543 if (icmptype == ICMP_UNREACH ||
4544 icmptype == ICMP_SOURCEQUENCH ||
4545 icmptype == ICMP_REDIRECT ||
4546 icmptype == ICMP_TIMXCEED ||
4547 icmptype == ICMP_PARAMPROB)
4552 case IPPROTO_ICMPV6:
4553 icmptype = pd->hdr.icmp6->icmp6_type;
4554 icmpid = pd->hdr.icmp6->icmp6_id;
4555 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4557 if (icmptype == ICMP6_DST_UNREACH ||
4558 icmptype == ICMP6_PACKET_TOO_BIG ||
4559 icmptype == ICMP6_TIME_EXCEEDED ||
4560 icmptype == ICMP6_PARAM_PROB)
4569 * ICMP query/reply message not related to a TCP/UDP packet.
4570 * Search for an ICMP state.
4573 key.proto = pd->proto;
4574 key.port[0] = key.port[1] = icmpid;
4575 if (direction == PF_IN) { /* wire side, straight */
4576 PF_ACPY(&key.addr[0], pd->src, key.af);
4577 PF_ACPY(&key.addr[1], pd->dst, key.af);
4578 } else { /* stack side, reverse */
4579 PF_ACPY(&key.addr[1], pd->src, key.af);
4580 PF_ACPY(&key.addr[0], pd->dst, key.af);
4583 STATE_LOOKUP(kif, &key, direction, *state, pd);
4585 (*state)->expire = time_uptime;
4586 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4588 /* translate source/destination address, if necessary */
4589 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4590 struct pf_state_key *nk = (*state)->key[pd->didx];
4595 if (PF_ANEQ(pd->src,
4596 &nk->addr[pd->sidx], AF_INET))
4597 pf_change_a(&saddr->v4.s_addr,
4599 nk->addr[pd->sidx].v4.s_addr, 0);
4601 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4603 pf_change_a(&daddr->v4.s_addr,
4605 nk->addr[pd->didx].v4.s_addr, 0);
4608 pd->hdr.icmp->icmp_id) {
4609 pd->hdr.icmp->icmp_cksum =
4611 pd->hdr.icmp->icmp_cksum, icmpid,
4612 nk->port[pd->sidx], 0);
4613 pd->hdr.icmp->icmp_id =
4617 m_copyback(m, off, ICMP_MINLEN,
4618 (caddr_t )pd->hdr.icmp);
4623 if (PF_ANEQ(pd->src,
4624 &nk->addr[pd->sidx], AF_INET6))
4626 &pd->hdr.icmp6->icmp6_cksum,
4627 &nk->addr[pd->sidx], 0);
4629 if (PF_ANEQ(pd->dst,
4630 &nk->addr[pd->didx], AF_INET6))
4632 &pd->hdr.icmp6->icmp6_cksum,
4633 &nk->addr[pd->didx], 0);
4635 m_copyback(m, off, sizeof(struct icmp6_hdr),
4636 (caddr_t )pd->hdr.icmp6);
4645 * ICMP error message in response to a TCP/UDP packet.
4646 * Extract the inner TCP/UDP header and search for that state.
4649 struct pf_pdesc pd2;
4650 bzero(&pd2, sizeof pd2);
4655 struct ip6_hdr h2_6;
4662 /* Payload packet is from the opposite direction. */
4663 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4664 pd2.didx = (direction == PF_IN) ? 0 : 1;
4668 /* offset of h2 in mbuf chain */
4669 ipoff2 = off + ICMP_MINLEN;
4671 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4672 NULL, reason, pd2.af)) {
4673 DPFPRINTF(PF_DEBUG_MISC,
4674 ("pf: ICMP error message too short "
4679 * ICMP error messages don't refer to non-first
4682 if (h2.ip_off & htons(IP_OFFMASK)) {
4683 REASON_SET(reason, PFRES_FRAG);
4687 /* offset of protocol header that follows h2 */
4688 off2 = ipoff2 + (h2.ip_hl << 2);
4690 pd2.proto = h2.ip_p;
4691 pd2.src = (struct pf_addr *)&h2.ip_src;
4692 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4693 pd2.ip_sum = &h2.ip_sum;
4698 ipoff2 = off + sizeof(struct icmp6_hdr);
4700 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4701 NULL, reason, pd2.af)) {
4702 DPFPRINTF(PF_DEBUG_MISC,
4703 ("pf: ICMP error message too short "
4707 pd2.proto = h2_6.ip6_nxt;
4708 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4709 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4711 off2 = ipoff2 + sizeof(h2_6);
4713 switch (pd2.proto) {
4714 case IPPROTO_FRAGMENT:
4716 * ICMPv6 error messages for
4717 * non-first fragments
4719 REASON_SET(reason, PFRES_FRAG);
4722 case IPPROTO_HOPOPTS:
4723 case IPPROTO_ROUTING:
4724 case IPPROTO_DSTOPTS: {
4725 /* get next header and header length */
4726 struct ip6_ext opt6;
4728 if (!pf_pull_hdr(m, off2, &opt6,
4729 sizeof(opt6), NULL, reason,
4731 DPFPRINTF(PF_DEBUG_MISC,
4732 ("pf: ICMPv6 short opt\n"));
4735 if (pd2.proto == IPPROTO_AH)
4736 off2 += (opt6.ip6e_len + 2) * 4;
4738 off2 += (opt6.ip6e_len + 1) * 8;
4739 pd2.proto = opt6.ip6e_nxt;
4740 /* goto the next header */
4747 } while (!terminal);
4752 switch (pd2.proto) {
4756 struct pf_state_peer *src, *dst;
4761 * Only the first 8 bytes of the TCP header can be
4762 * expected. Don't access any TCP header fields after
4763 * th_seq, an ackskew test is not possible.
4765 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4767 DPFPRINTF(PF_DEBUG_MISC,
4768 ("pf: ICMP error message too short "
4774 key.proto = IPPROTO_TCP;
4775 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4776 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4777 key.port[pd2.sidx] = th.th_sport;
4778 key.port[pd2.didx] = th.th_dport;
4780 STATE_LOOKUP(kif, &key, direction, *state, pd);
4782 if (direction == (*state)->direction) {
4783 src = &(*state)->dst;
4784 dst = &(*state)->src;
4786 src = &(*state)->src;
4787 dst = &(*state)->dst;
4790 if (src->wscale && dst->wscale)
4791 dws = dst->wscale & PF_WSCALE_MASK;
4795 /* Demodulate sequence number */
4796 seq = ntohl(th.th_seq) - src->seqdiff;
4798 pf_change_a(&th.th_seq, icmpsum,
4803 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4804 (!SEQ_GEQ(src->seqhi, seq) ||
4805 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4806 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4807 printf("pf: BAD ICMP %d:%d ",
4808 icmptype, pd->hdr.icmp->icmp_code);
4809 pf_print_host(pd->src, 0, pd->af);
4811 pf_print_host(pd->dst, 0, pd->af);
4813 pf_print_state(*state);
4814 printf(" seq=%u\n", seq);
4816 REASON_SET(reason, PFRES_BADSTATE);
4819 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4820 printf("pf: OK ICMP %d:%d ",
4821 icmptype, pd->hdr.icmp->icmp_code);
4822 pf_print_host(pd->src, 0, pd->af);
4824 pf_print_host(pd->dst, 0, pd->af);
4826 pf_print_state(*state);
4827 printf(" seq=%u\n", seq);
4831 /* translate source/destination address, if necessary */
4832 if ((*state)->key[PF_SK_WIRE] !=
4833 (*state)->key[PF_SK_STACK]) {
4834 struct pf_state_key *nk =
4835 (*state)->key[pd->didx];
4837 if (PF_ANEQ(pd2.src,
4838 &nk->addr[pd2.sidx], pd2.af) ||
4839 nk->port[pd2.sidx] != th.th_sport)
4840 pf_change_icmp(pd2.src, &th.th_sport,
4841 daddr, &nk->addr[pd2.sidx],
4842 nk->port[pd2.sidx], NULL,
4843 pd2.ip_sum, icmpsum,
4844 pd->ip_sum, 0, pd2.af);
4846 if (PF_ANEQ(pd2.dst,
4847 &nk->addr[pd2.didx], pd2.af) ||
4848 nk->port[pd2.didx] != th.th_dport)
4849 pf_change_icmp(pd2.dst, &th.th_dport,
4850 saddr, &nk->addr[pd2.didx],
4851 nk->port[pd2.didx], NULL,
4852 pd2.ip_sum, icmpsum,
4853 pd->ip_sum, 0, pd2.af);
4861 m_copyback(m, off, ICMP_MINLEN,
4862 (caddr_t )pd->hdr.icmp);
4863 m_copyback(m, ipoff2, sizeof(h2),
4870 sizeof(struct icmp6_hdr),
4871 (caddr_t )pd->hdr.icmp6);
4872 m_copyback(m, ipoff2, sizeof(h2_6),
4877 m_copyback(m, off2, 8, (caddr_t)&th);
4886 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4887 NULL, reason, pd2.af)) {
4888 DPFPRINTF(PF_DEBUG_MISC,
4889 ("pf: ICMP error message too short "
4895 key.proto = IPPROTO_UDP;
4896 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4897 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4898 key.port[pd2.sidx] = uh.uh_sport;
4899 key.port[pd2.didx] = uh.uh_dport;
4901 STATE_LOOKUP(kif, &key, direction, *state, pd);
4903 /* translate source/destination address, if necessary */
4904 if ((*state)->key[PF_SK_WIRE] !=
4905 (*state)->key[PF_SK_STACK]) {
4906 struct pf_state_key *nk =
4907 (*state)->key[pd->didx];
4909 if (PF_ANEQ(pd2.src,
4910 &nk->addr[pd2.sidx], pd2.af) ||
4911 nk->port[pd2.sidx] != uh.uh_sport)
4912 pf_change_icmp(pd2.src, &uh.uh_sport,
4913 daddr, &nk->addr[pd2.sidx],
4914 nk->port[pd2.sidx], &uh.uh_sum,
4915 pd2.ip_sum, icmpsum,
4916 pd->ip_sum, 1, pd2.af);
4918 if (PF_ANEQ(pd2.dst,
4919 &nk->addr[pd2.didx], pd2.af) ||
4920 nk->port[pd2.didx] != uh.uh_dport)
4921 pf_change_icmp(pd2.dst, &uh.uh_dport,
4922 saddr, &nk->addr[pd2.didx],
4923 nk->port[pd2.didx], &uh.uh_sum,
4924 pd2.ip_sum, icmpsum,
4925 pd->ip_sum, 1, pd2.af);
4930 m_copyback(m, off, ICMP_MINLEN,
4931 (caddr_t )pd->hdr.icmp);
4932 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4938 sizeof(struct icmp6_hdr),
4939 (caddr_t )pd->hdr.icmp6);
4940 m_copyback(m, ipoff2, sizeof(h2_6),
4945 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4951 case IPPROTO_ICMP: {
4954 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4955 NULL, reason, pd2.af)) {
4956 DPFPRINTF(PF_DEBUG_MISC,
4957 ("pf: ICMP error message too short i"
4963 key.proto = IPPROTO_ICMP;
4964 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4965 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4966 key.port[0] = key.port[1] = iih.icmp_id;
4968 STATE_LOOKUP(kif, &key, direction, *state, pd);
4970 /* translate source/destination address, if necessary */
4971 if ((*state)->key[PF_SK_WIRE] !=
4972 (*state)->key[PF_SK_STACK]) {
4973 struct pf_state_key *nk =
4974 (*state)->key[pd->didx];
4976 if (PF_ANEQ(pd2.src,
4977 &nk->addr[pd2.sidx], pd2.af) ||
4978 nk->port[pd2.sidx] != iih.icmp_id)
4979 pf_change_icmp(pd2.src, &iih.icmp_id,
4980 daddr, &nk->addr[pd2.sidx],
4981 nk->port[pd2.sidx], NULL,
4982 pd2.ip_sum, icmpsum,
4983 pd->ip_sum, 0, AF_INET);
4985 if (PF_ANEQ(pd2.dst,
4986 &nk->addr[pd2.didx], pd2.af) ||
4987 nk->port[pd2.didx] != iih.icmp_id)
4988 pf_change_icmp(pd2.dst, &iih.icmp_id,
4989 saddr, &nk->addr[pd2.didx],
4990 nk->port[pd2.didx], NULL,
4991 pd2.ip_sum, icmpsum,
4992 pd->ip_sum, 0, AF_INET);
4994 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4995 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4996 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5003 case IPPROTO_ICMPV6: {
5004 struct icmp6_hdr iih;
5006 if (!pf_pull_hdr(m, off2, &iih,
5007 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5008 DPFPRINTF(PF_DEBUG_MISC,
5009 ("pf: ICMP error message too short "
5015 key.proto = IPPROTO_ICMPV6;
5016 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5017 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5018 key.port[0] = key.port[1] = iih.icmp6_id;
5020 STATE_LOOKUP(kif, &key, direction, *state, pd);
5022 /* translate source/destination address, if necessary */
5023 if ((*state)->key[PF_SK_WIRE] !=
5024 (*state)->key[PF_SK_STACK]) {
5025 struct pf_state_key *nk =
5026 (*state)->key[pd->didx];
5028 if (PF_ANEQ(pd2.src,
5029 &nk->addr[pd2.sidx], pd2.af) ||
5030 nk->port[pd2.sidx] != iih.icmp6_id)
5031 pf_change_icmp(pd2.src, &iih.icmp6_id,
5032 daddr, &nk->addr[pd2.sidx],
5033 nk->port[pd2.sidx], NULL,
5034 pd2.ip_sum, icmpsum,
5035 pd->ip_sum, 0, AF_INET6);
5037 if (PF_ANEQ(pd2.dst,
5038 &nk->addr[pd2.didx], pd2.af) ||
5039 nk->port[pd2.didx] != iih.icmp6_id)
5040 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5041 saddr, &nk->addr[pd2.didx],
5042 nk->port[pd2.didx], NULL,
5043 pd2.ip_sum, icmpsum,
5044 pd->ip_sum, 0, AF_INET6);
5046 m_copyback(m, off, sizeof(struct icmp6_hdr),
5047 (caddr_t)pd->hdr.icmp6);
5048 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5049 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5058 key.proto = pd2.proto;
5059 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5060 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5061 key.port[0] = key.port[1] = 0;
5063 STATE_LOOKUP(kif, &key, direction, *state, pd);
5065 /* translate source/destination address, if necessary */
5066 if ((*state)->key[PF_SK_WIRE] !=
5067 (*state)->key[PF_SK_STACK]) {
5068 struct pf_state_key *nk =
5069 (*state)->key[pd->didx];
5071 if (PF_ANEQ(pd2.src,
5072 &nk->addr[pd2.sidx], pd2.af))
5073 pf_change_icmp(pd2.src, NULL, daddr,
5074 &nk->addr[pd2.sidx], 0, NULL,
5075 pd2.ip_sum, icmpsum,
5076 pd->ip_sum, 0, pd2.af);
5078 if (PF_ANEQ(pd2.dst,
5079 &nk->addr[pd2.didx], pd2.af))
5080 pf_change_icmp(pd2.dst, NULL, saddr,
5081 &nk->addr[pd2.didx], 0, NULL,
5082 pd2.ip_sum, icmpsum,
5083 pd->ip_sum, 0, pd2.af);
5088 m_copyback(m, off, ICMP_MINLEN,
5089 (caddr_t)pd->hdr.icmp);
5090 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5096 sizeof(struct icmp6_hdr),
5097 (caddr_t )pd->hdr.icmp6);
5098 m_copyback(m, ipoff2, sizeof(h2_6),
5112 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5113 struct mbuf *m, struct pf_pdesc *pd)
5115 struct pf_state_peer *src, *dst;
5116 struct pf_state_key_cmp key;
5118 bzero(&key, sizeof(key));
5120 key.proto = pd->proto;
5121 if (direction == PF_IN) {
5122 PF_ACPY(&key.addr[0], pd->src, key.af);
5123 PF_ACPY(&key.addr[1], pd->dst, key.af);
5124 key.port[0] = key.port[1] = 0;
5126 PF_ACPY(&key.addr[1], pd->src, key.af);
5127 PF_ACPY(&key.addr[0], pd->dst, key.af);
5128 key.port[1] = key.port[0] = 0;
5131 STATE_LOOKUP(kif, &key, direction, *state, pd);
5133 if (direction == (*state)->direction) {
5134 src = &(*state)->src;
5135 dst = &(*state)->dst;
5137 src = &(*state)->dst;
5138 dst = &(*state)->src;
5142 if (src->state < PFOTHERS_SINGLE)
5143 src->state = PFOTHERS_SINGLE;
5144 if (dst->state == PFOTHERS_SINGLE)
5145 dst->state = PFOTHERS_MULTIPLE;
5147 /* update expire time */
5148 (*state)->expire = time_uptime;
5149 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5150 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5152 (*state)->timeout = PFTM_OTHER_SINGLE;
5154 /* translate source/destination address, if necessary */
5155 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5156 struct pf_state_key *nk = (*state)->key[pd->didx];
5158 KASSERT(nk, ("%s: nk is null", __func__));
5159 KASSERT(pd, ("%s: pd is null", __func__));
5160 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5161 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5165 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5166 pf_change_a(&pd->src->v4.s_addr,
5168 nk->addr[pd->sidx].v4.s_addr,
5172 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5173 pf_change_a(&pd->dst->v4.s_addr,
5175 nk->addr[pd->didx].v4.s_addr,
5182 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5183 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5185 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5186 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5194 * ipoff and off are measured from the start of the mbuf chain.
5195 * h must be at "ipoff" on the mbuf chain.
5198 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5199 u_short *actionp, u_short *reasonp, sa_family_t af)
5204 struct ip *h = mtod(m, struct ip *);
5205 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5209 ACTION_SET(actionp, PF_PASS);
5211 ACTION_SET(actionp, PF_DROP);
5212 REASON_SET(reasonp, PFRES_FRAG);
5216 if (m->m_pkthdr.len < off + len ||
5217 ntohs(h->ip_len) < off + len) {
5218 ACTION_SET(actionp, PF_DROP);
5219 REASON_SET(reasonp, PFRES_SHORT);
5227 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5229 if (m->m_pkthdr.len < off + len ||
5230 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5231 (unsigned)(off + len)) {
5232 ACTION_SET(actionp, PF_DROP);
5233 REASON_SET(reasonp, PFRES_SHORT);
5240 m_copydata(m, off, len, p);
5246 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5249 struct radix_node_head *rnh;
5250 struct sockaddr_in *dst;
5254 struct sockaddr_in6 *dst6;
5255 struct route_in6 ro;
5259 struct radix_node *rn;
5264 /* XXX: stick to table 0 for now */
5265 rnh = rt_tables_get_rnh(0, af);
5266 if (rnh != NULL && rn_mpath_capable(rnh))
5268 bzero(&ro, sizeof(ro));
5271 dst = satosin(&ro.ro_dst);
5272 dst->sin_family = AF_INET;
5273 dst->sin_len = sizeof(*dst);
5274 dst->sin_addr = addr->v4;
5279 * Skip check for addresses with embedded interface scope,
5280 * as they would always match anyway.
5282 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5284 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5285 dst6->sin6_family = AF_INET6;
5286 dst6->sin6_len = sizeof(*dst6);
5287 dst6->sin6_addr = addr->v6;
5294 /* Skip checks for ipsec interfaces */
5295 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5301 in6_rtalloc_ign(&ro, 0, rtableid);
5306 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5311 if (ro.ro_rt != NULL) {
5312 /* No interface given, this is a no-route check */
5316 if (kif->pfik_ifp == NULL) {
5321 /* Perform uRPF check if passed input interface */
5323 rn = (struct radix_node *)ro.ro_rt;
5325 rt = (struct rtentry *)rn;
5328 if (kif->pfik_ifp == ifp)
5330 rn = rn_mpath_next(rn);
5331 } while (check_mpath == 1 && rn != NULL && ret == 0);
5335 if (ro.ro_rt != NULL)
5342 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5346 struct nhop4_basic nh4;
5349 struct nhop6_basic nh6;
5353 struct radix_node_head *rnh;
5355 /* XXX: stick to table 0 for now */
5356 rnh = rt_tables_get_rnh(0, af);
5357 if (rnh != NULL && rn_mpath_capable(rnh))
5358 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5361 * Skip check for addresses with embedded interface scope,
5362 * as they would always match anyway.
5364 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5367 if (af != AF_INET && af != AF_INET6)
5370 /* Skip checks for ipsec interfaces */
5371 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5379 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5386 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5393 /* No interface given, this is a no-route check */
5397 if (kif->pfik_ifp == NULL)
5400 /* Perform uRPF check if passed input interface */
5401 if (kif->pfik_ifp == ifp)
5408 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5409 struct pf_state *s, struct pf_pdesc *pd)
5411 struct mbuf *m0, *m1;
5412 struct sockaddr_in dst;
5414 struct ifnet *ifp = NULL;
5415 struct pf_addr naddr;
5416 struct pf_src_node *sn = NULL;
5418 uint16_t ip_len, ip_off;
5420 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5421 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5424 if ((pd->pf_mtag == NULL &&
5425 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5426 pd->pf_mtag->routed++ > 3) {
5432 if (r->rt == PF_DUPTO) {
5433 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5439 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5447 ip = mtod(m0, struct ip *);
5449 bzero(&dst, sizeof(dst));
5450 dst.sin_family = AF_INET;
5451 dst.sin_len = sizeof(dst);
5452 dst.sin_addr = ip->ip_dst;
5454 if (TAILQ_EMPTY(&r->rpool.list)) {
5455 DPFPRINTF(PF_DEBUG_URGENT,
5456 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5460 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5462 if (!PF_AZERO(&naddr, AF_INET))
5463 dst.sin_addr.s_addr = naddr.v4.s_addr;
5464 ifp = r->rpool.cur->kif ?
5465 r->rpool.cur->kif->pfik_ifp : NULL;
5467 if (!PF_AZERO(&s->rt_addr, AF_INET))
5468 dst.sin_addr.s_addr =
5469 s->rt_addr.v4.s_addr;
5470 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5477 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5479 else if (m0 == NULL)
5481 if (m0->m_len < sizeof(struct ip)) {
5482 DPFPRINTF(PF_DEBUG_URGENT,
5483 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5486 ip = mtod(m0, struct ip *);
5489 if (ifp->if_flags & IFF_LOOPBACK)
5490 m0->m_flags |= M_SKIP_FIREWALL;
5492 ip_len = ntohs(ip->ip_len);
5493 ip_off = ntohs(ip->ip_off);
5495 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5496 m0->m_pkthdr.csum_flags |= CSUM_IP;
5497 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5498 in_delayed_cksum(m0);
5499 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5502 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5503 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5504 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5509 * If small enough for interface, or the interface will take
5510 * care of the fragmentation for us, we can just send directly.
5512 if (ip_len <= ifp->if_mtu ||
5513 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5515 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5516 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5517 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5519 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5520 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5524 /* Balk when DF bit is set or the interface didn't support TSO. */
5525 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5527 KMOD_IPSTAT_INC(ips_cantfrag);
5528 if (r->rt != PF_DUPTO) {
5529 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5536 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5540 for (; m0; m0 = m1) {
5542 m0->m_nextpkt = NULL;
5544 m_clrprotoflags(m0);
5545 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5551 KMOD_IPSTAT_INC(ips_fragmented);
5554 if (r->rt != PF_DUPTO)
5569 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5570 struct pf_state *s, struct pf_pdesc *pd)
5573 struct sockaddr_in6 dst;
5574 struct ip6_hdr *ip6;
5575 struct ifnet *ifp = NULL;
5576 struct pf_addr naddr;
5577 struct pf_src_node *sn = NULL;
5579 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5580 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5583 if ((pd->pf_mtag == NULL &&
5584 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5585 pd->pf_mtag->routed++ > 3) {
5591 if (r->rt == PF_DUPTO) {
5592 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5598 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5606 ip6 = mtod(m0, struct ip6_hdr *);
5608 bzero(&dst, sizeof(dst));
5609 dst.sin6_family = AF_INET6;
5610 dst.sin6_len = sizeof(dst);
5611 dst.sin6_addr = ip6->ip6_dst;
5613 if (TAILQ_EMPTY(&r->rpool.list)) {
5614 DPFPRINTF(PF_DEBUG_URGENT,
5615 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5619 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5621 if (!PF_AZERO(&naddr, AF_INET6))
5622 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5624 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5626 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5627 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5628 &s->rt_addr, AF_INET6);
5629 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5639 if (pf_test6(PF_FWD, ifp, &m0, NULL) != PF_PASS)
5641 else if (m0 == NULL)
5643 if (m0->m_len < sizeof(struct ip6_hdr)) {
5644 DPFPRINTF(PF_DEBUG_URGENT,
5645 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5649 ip6 = mtod(m0, struct ip6_hdr *);
5652 if (ifp->if_flags & IFF_LOOPBACK)
5653 m0->m_flags |= M_SKIP_FIREWALL;
5655 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5656 ~ifp->if_hwassist) {
5657 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5658 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5659 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5663 * If the packet is too large for the outgoing interface,
5664 * send back an icmp6 error.
5666 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5667 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5668 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5669 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5671 in6_ifstat_inc(ifp, ifs6_in_toobig);
5672 if (r->rt != PF_DUPTO)
5673 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5679 if (r->rt != PF_DUPTO)
5693 * FreeBSD supports cksum offloads for the following drivers.
5694 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5695 * ti(4), txp(4), xl(4)
5697 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5698 * network driver performed cksum including pseudo header, need to verify
5701 * network driver performed cksum, needs to additional pseudo header
5702 * cksum computation with partial csum_data(i.e. lack of H/W support for
5703 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5705 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5706 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5708 * Also, set csum_data to 0xffff to force cksum validation.
5711 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5717 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5719 if (m->m_pkthdr.len < off + len)
5724 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5725 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5726 sum = m->m_pkthdr.csum_data;
5728 ip = mtod(m, struct ip *);
5729 sum = in_pseudo(ip->ip_src.s_addr,
5730 ip->ip_dst.s_addr, htonl((u_short)len +
5731 m->m_pkthdr.csum_data + IPPROTO_TCP));
5738 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5739 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5740 sum = m->m_pkthdr.csum_data;
5742 ip = mtod(m, struct ip *);
5743 sum = in_pseudo(ip->ip_src.s_addr,
5744 ip->ip_dst.s_addr, htonl((u_short)len +
5745 m->m_pkthdr.csum_data + IPPROTO_UDP));
5753 case IPPROTO_ICMPV6:
5763 if (p == IPPROTO_ICMP) {
5768 sum = in_cksum(m, len);
5772 if (m->m_len < sizeof(struct ip))
5774 sum = in4_cksum(m, p, off, len);
5779 if (m->m_len < sizeof(struct ip6_hdr))
5781 sum = in6_cksum(m, p, off, len);
5792 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5797 KMOD_UDPSTAT_INC(udps_badsum);
5803 KMOD_ICMPSTAT_INC(icps_checksum);
5808 case IPPROTO_ICMPV6:
5810 KMOD_ICMP6STAT_INC(icp6s_checksum);
5817 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5818 m->m_pkthdr.csum_flags |=
5819 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5820 m->m_pkthdr.csum_data = 0xffff;
5829 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5831 struct pfi_kif *kif;
5832 u_short action, reason = 0, log = 0;
5833 struct mbuf *m = *m0;
5834 struct ip *h = NULL;
5835 struct m_tag *ipfwtag;
5836 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5837 struct pf_state *s = NULL;
5838 struct pf_ruleset *ruleset = NULL;
5840 int off, dirndx, pqid = 0;
5844 if (!V_pf_status.running)
5847 memset(&pd, 0, sizeof(pd));
5849 kif = (struct pfi_kif *)ifp->if_pf_kif;
5852 DPFPRINTF(PF_DEBUG_URGENT,
5853 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5856 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5859 if (m->m_flags & M_SKIP_FIREWALL)
5862 pd.pf_mtag = pf_find_mtag(m);
5866 if (ip_divert_ptr != NULL &&
5867 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5868 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5869 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5870 if (pd.pf_mtag == NULL &&
5871 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5875 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5876 m_tag_delete(m, ipfwtag);
5878 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5879 m->m_flags |= M_FASTFWD_OURS;
5880 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5882 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5883 /* We do IP header normalization and packet reassembly here */
5887 m = *m0; /* pf_normalize messes with m0 */
5888 h = mtod(m, struct ip *);
5890 off = h->ip_hl << 2;
5891 if (off < (int)sizeof(struct ip)) {
5893 REASON_SET(&reason, PFRES_SHORT);
5898 pd.src = (struct pf_addr *)&h->ip_src;
5899 pd.dst = (struct pf_addr *)&h->ip_dst;
5900 pd.sport = pd.dport = NULL;
5901 pd.ip_sum = &h->ip_sum;
5902 pd.proto_sum = NULL;
5905 pd.sidx = (dir == PF_IN) ? 0 : 1;
5906 pd.didx = (dir == PF_IN) ? 1 : 0;
5908 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5909 pd.tot_len = ntohs(h->ip_len);
5911 /* handle fragments that didn't get reassembled by normalization */
5912 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5913 action = pf_test_fragment(&r, dir, kif, m, h,
5924 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5925 &action, &reason, AF_INET)) {
5926 log = action != PF_PASS;
5929 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5930 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5932 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5933 if (action == PF_DROP)
5935 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5937 if (action == PF_PASS) {
5938 if (pfsync_update_state_ptr != NULL)
5939 pfsync_update_state_ptr(s);
5943 } else if (s == NULL)
5944 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5953 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5954 &action, &reason, AF_INET)) {
5955 log = action != PF_PASS;
5958 if (uh.uh_dport == 0 ||
5959 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5960 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5962 REASON_SET(&reason, PFRES_SHORT);
5965 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5966 if (action == PF_PASS) {
5967 if (pfsync_update_state_ptr != NULL)
5968 pfsync_update_state_ptr(s);
5972 } else if (s == NULL)
5973 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5978 case IPPROTO_ICMP: {
5982 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5983 &action, &reason, AF_INET)) {
5984 log = action != PF_PASS;
5987 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5989 if (action == PF_PASS) {
5990 if (pfsync_update_state_ptr != NULL)
5991 pfsync_update_state_ptr(s);
5995 } else if (s == NULL)
5996 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6002 case IPPROTO_ICMPV6: {
6004 DPFPRINTF(PF_DEBUG_MISC,
6005 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6011 action = pf_test_state_other(&s, dir, kif, m, &pd);
6012 if (action == PF_PASS) {
6013 if (pfsync_update_state_ptr != NULL)
6014 pfsync_update_state_ptr(s);
6018 } else if (s == NULL)
6019 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6026 if (action == PF_PASS && h->ip_hl > 5 &&
6027 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6029 REASON_SET(&reason, PFRES_IPOPTIONS);
6031 DPFPRINTF(PF_DEBUG_MISC,
6032 ("pf: dropping packet with ip options\n"));
6035 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6037 REASON_SET(&reason, PFRES_MEMORY);
6039 if (r->rtableid >= 0)
6040 M_SETFIB(m, r->rtableid);
6042 if (r->scrub_flags & PFSTATE_SETPRIO) {
6043 if (pd.tos & IPTOS_LOWDELAY)
6045 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6047 REASON_SET(&reason, PFRES_MEMORY);
6049 DPFPRINTF(PF_DEBUG_MISC,
6050 ("pf: failed to allocate 802.1q mtag\n"));
6055 if (action == PF_PASS && r->qid) {
6056 if (pd.pf_mtag == NULL &&
6057 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6059 REASON_SET(&reason, PFRES_MEMORY);
6062 pd.pf_mtag->qid_hash = pf_state_hash(s);
6063 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6064 pd.pf_mtag->qid = r->pqid;
6066 pd.pf_mtag->qid = r->qid;
6067 /* Add hints for ecn. */
6068 pd.pf_mtag->hdr = h;
6075 * connections redirected to loopback should not match sockets
6076 * bound specifically to loopback due to security implications,
6077 * see tcp_input() and in_pcblookup_listen().
6079 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6080 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6081 (s->nat_rule.ptr->action == PF_RDR ||
6082 s->nat_rule.ptr->action == PF_BINAT) &&
6083 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6084 m->m_flags |= M_SKIP_FIREWALL;
6086 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6087 !PACKET_LOOPED(&pd)) {
6089 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6090 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6091 if (ipfwtag != NULL) {
6092 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6093 ntohs(r->divert.port);
6094 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6099 m_tag_prepend(m, ipfwtag);
6100 if (m->m_flags & M_FASTFWD_OURS) {
6101 if (pd.pf_mtag == NULL &&
6102 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6104 REASON_SET(&reason, PFRES_MEMORY);
6106 DPFPRINTF(PF_DEBUG_MISC,
6107 ("pf: failed to allocate tag\n"));
6109 pd.pf_mtag->flags |=
6110 PF_FASTFWD_OURS_PRESENT;
6111 m->m_flags &= ~M_FASTFWD_OURS;
6114 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6119 /* XXX: ipfw has the same behaviour! */
6121 REASON_SET(&reason, PFRES_MEMORY);
6123 DPFPRINTF(PF_DEBUG_MISC,
6124 ("pf: failed to allocate divert tag\n"));
6131 if (s != NULL && s->nat_rule.ptr != NULL &&
6132 s->nat_rule.ptr->log & PF_LOG_ALL)
6133 lr = s->nat_rule.ptr;
6136 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6140 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6141 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6143 if (action == PF_PASS || r->action == PF_DROP) {
6144 dirndx = (dir == PF_OUT);
6145 r->packets[dirndx]++;
6146 r->bytes[dirndx] += pd.tot_len;
6148 a->packets[dirndx]++;
6149 a->bytes[dirndx] += pd.tot_len;
6152 if (s->nat_rule.ptr != NULL) {
6153 s->nat_rule.ptr->packets[dirndx]++;
6154 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6156 if (s->src_node != NULL) {
6157 s->src_node->packets[dirndx]++;
6158 s->src_node->bytes[dirndx] += pd.tot_len;
6160 if (s->nat_src_node != NULL) {
6161 s->nat_src_node->packets[dirndx]++;
6162 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6164 dirndx = (dir == s->direction) ? 0 : 1;
6165 s->packets[dirndx]++;
6166 s->bytes[dirndx] += pd.tot_len;
6169 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6170 if (nr != NULL && r == &V_pf_default_rule)
6172 if (tr->src.addr.type == PF_ADDR_TABLE)
6173 pfr_update_stats(tr->src.addr.p.tbl,
6174 (s == NULL) ? pd.src :
6175 &s->key[(s->direction == PF_IN)]->
6176 addr[(s->direction == PF_OUT)],
6177 pd.af, pd.tot_len, dir == PF_OUT,
6178 r->action == PF_PASS, tr->src.neg);
6179 if (tr->dst.addr.type == PF_ADDR_TABLE)
6180 pfr_update_stats(tr->dst.addr.p.tbl,
6181 (s == NULL) ? pd.dst :
6182 &s->key[(s->direction == PF_IN)]->
6183 addr[(s->direction == PF_IN)],
6184 pd.af, pd.tot_len, dir == PF_OUT,
6185 r->action == PF_PASS, tr->dst.neg);
6189 case PF_SYNPROXY_DROP:
6200 /* pf_route() returns unlocked. */
6202 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6216 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6218 struct pfi_kif *kif;
6219 u_short action, reason = 0, log = 0;
6220 struct mbuf *m = *m0, *n = NULL;
6222 struct ip6_hdr *h = NULL;
6223 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6224 struct pf_state *s = NULL;
6225 struct pf_ruleset *ruleset = NULL;
6227 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6232 /* Detect packet forwarding.
6233 * If the input interface is different from the output interface we're
6235 * We do need to be careful about bridges. If the
6236 * net.link.bridge.pfil_bridge sysctl is set we can be filtering on a
6237 * bridge, so if the input interface is a bridge member and the output
6238 * interface is its bridge or a member of the same bridge we're not
6239 * actually forwarding but bridging.
6241 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif &&
6242 (m->m_pkthdr.rcvif->if_bridge == NULL ||
6243 (m->m_pkthdr.rcvif->if_bridge != ifp->if_softc &&
6244 m->m_pkthdr.rcvif->if_bridge != ifp->if_bridge)))
6250 if (!V_pf_status.running)
6253 memset(&pd, 0, sizeof(pd));
6254 pd.pf_mtag = pf_find_mtag(m);
6256 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6259 kif = (struct pfi_kif *)ifp->if_pf_kif;
6261 DPFPRINTF(PF_DEBUG_URGENT,
6262 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6265 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6268 if (m->m_flags & M_SKIP_FIREWALL)
6273 /* We do IP header normalization and packet reassembly here */
6274 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6278 m = *m0; /* pf_normalize messes with m0 */
6279 h = mtod(m, struct ip6_hdr *);
6283 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6284 * will do something bad, so drop the packet for now.
6286 if (htons(h->ip6_plen) == 0) {
6288 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6293 pd.src = (struct pf_addr *)&h->ip6_src;
6294 pd.dst = (struct pf_addr *)&h->ip6_dst;
6295 pd.sport = pd.dport = NULL;
6297 pd.proto_sum = NULL;
6299 pd.sidx = (dir == PF_IN) ? 0 : 1;
6300 pd.didx = (dir == PF_IN) ? 1 : 0;
6303 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6305 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6306 pd.proto = h->ip6_nxt;
6309 case IPPROTO_FRAGMENT:
6310 action = pf_test_fragment(&r, dir, kif, m, h,
6312 if (action == PF_DROP)
6313 REASON_SET(&reason, PFRES_FRAG);
6315 case IPPROTO_ROUTING: {
6316 struct ip6_rthdr rthdr;
6319 DPFPRINTF(PF_DEBUG_MISC,
6320 ("pf: IPv6 more than one rthdr\n"));
6322 REASON_SET(&reason, PFRES_IPOPTIONS);
6326 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6328 DPFPRINTF(PF_DEBUG_MISC,
6329 ("pf: IPv6 short rthdr\n"));
6331 REASON_SET(&reason, PFRES_SHORT);
6335 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6336 DPFPRINTF(PF_DEBUG_MISC,
6337 ("pf: IPv6 rthdr0\n"));
6339 REASON_SET(&reason, PFRES_IPOPTIONS);
6346 case IPPROTO_HOPOPTS:
6347 case IPPROTO_DSTOPTS: {
6348 /* get next header and header length */
6349 struct ip6_ext opt6;
6351 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6352 NULL, &reason, pd.af)) {
6353 DPFPRINTF(PF_DEBUG_MISC,
6354 ("pf: IPv6 short opt\n"));
6359 if (pd.proto == IPPROTO_AH)
6360 off += (opt6.ip6e_len + 2) * 4;
6362 off += (opt6.ip6e_len + 1) * 8;
6363 pd.proto = opt6.ip6e_nxt;
6364 /* goto the next header */
6371 } while (!terminal);
6373 /* if there's no routing header, use unmodified mbuf for checksumming */
6383 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6384 &action, &reason, AF_INET6)) {
6385 log = action != PF_PASS;
6388 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6389 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6390 if (action == PF_DROP)
6392 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6394 if (action == PF_PASS) {
6395 if (pfsync_update_state_ptr != NULL)
6396 pfsync_update_state_ptr(s);
6400 } else if (s == NULL)
6401 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6410 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6411 &action, &reason, AF_INET6)) {
6412 log = action != PF_PASS;
6415 if (uh.uh_dport == 0 ||
6416 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6417 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6419 REASON_SET(&reason, PFRES_SHORT);
6422 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6423 if (action == PF_PASS) {
6424 if (pfsync_update_state_ptr != NULL)
6425 pfsync_update_state_ptr(s);
6429 } else if (s == NULL)
6430 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6435 case IPPROTO_ICMP: {
6437 DPFPRINTF(PF_DEBUG_MISC,
6438 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6442 case IPPROTO_ICMPV6: {
6443 struct icmp6_hdr ih;
6446 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6447 &action, &reason, AF_INET6)) {
6448 log = action != PF_PASS;
6451 action = pf_test_state_icmp(&s, dir, kif,
6452 m, off, h, &pd, &reason);
6453 if (action == PF_PASS) {
6454 if (pfsync_update_state_ptr != NULL)
6455 pfsync_update_state_ptr(s);
6459 } else if (s == NULL)
6460 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6466 action = pf_test_state_other(&s, dir, kif, m, &pd);
6467 if (action == PF_PASS) {
6468 if (pfsync_update_state_ptr != NULL)
6469 pfsync_update_state_ptr(s);
6473 } else if (s == NULL)
6474 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6486 /* handle dangerous IPv6 extension headers. */
6487 if (action == PF_PASS && rh_cnt &&
6488 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6490 REASON_SET(&reason, PFRES_IPOPTIONS);
6492 DPFPRINTF(PF_DEBUG_MISC,
6493 ("pf: dropping packet with dangerous v6 headers\n"));
6496 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6498 REASON_SET(&reason, PFRES_MEMORY);
6500 if (r->rtableid >= 0)
6501 M_SETFIB(m, r->rtableid);
6503 if (r->scrub_flags & PFSTATE_SETPRIO) {
6504 if (pd.tos & IPTOS_LOWDELAY)
6506 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6508 REASON_SET(&reason, PFRES_MEMORY);
6510 DPFPRINTF(PF_DEBUG_MISC,
6511 ("pf: failed to allocate 802.1q mtag\n"));
6516 if (action == PF_PASS && r->qid) {
6517 if (pd.pf_mtag == NULL &&
6518 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6520 REASON_SET(&reason, PFRES_MEMORY);
6523 pd.pf_mtag->qid_hash = pf_state_hash(s);
6524 if (pd.tos & IPTOS_LOWDELAY)
6525 pd.pf_mtag->qid = r->pqid;
6527 pd.pf_mtag->qid = r->qid;
6528 /* Add hints for ecn. */
6529 pd.pf_mtag->hdr = h;
6534 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6535 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6536 (s->nat_rule.ptr->action == PF_RDR ||
6537 s->nat_rule.ptr->action == PF_BINAT) &&
6538 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6539 m->m_flags |= M_SKIP_FIREWALL;
6541 /* XXX: Anybody working on it?! */
6543 printf("pf: divert(9) is not supported for IPv6\n");
6548 if (s != NULL && s->nat_rule.ptr != NULL &&
6549 s->nat_rule.ptr->log & PF_LOG_ALL)
6550 lr = s->nat_rule.ptr;
6553 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6557 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6558 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6560 if (action == PF_PASS || r->action == PF_DROP) {
6561 dirndx = (dir == PF_OUT);
6562 r->packets[dirndx]++;
6563 r->bytes[dirndx] += pd.tot_len;
6565 a->packets[dirndx]++;
6566 a->bytes[dirndx] += pd.tot_len;
6569 if (s->nat_rule.ptr != NULL) {
6570 s->nat_rule.ptr->packets[dirndx]++;
6571 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6573 if (s->src_node != NULL) {
6574 s->src_node->packets[dirndx]++;
6575 s->src_node->bytes[dirndx] += pd.tot_len;
6577 if (s->nat_src_node != NULL) {
6578 s->nat_src_node->packets[dirndx]++;
6579 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6581 dirndx = (dir == s->direction) ? 0 : 1;
6582 s->packets[dirndx]++;
6583 s->bytes[dirndx] += pd.tot_len;
6586 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6587 if (nr != NULL && r == &V_pf_default_rule)
6589 if (tr->src.addr.type == PF_ADDR_TABLE)
6590 pfr_update_stats(tr->src.addr.p.tbl,
6591 (s == NULL) ? pd.src :
6592 &s->key[(s->direction == PF_IN)]->addr[0],
6593 pd.af, pd.tot_len, dir == PF_OUT,
6594 r->action == PF_PASS, tr->src.neg);
6595 if (tr->dst.addr.type == PF_ADDR_TABLE)
6596 pfr_update_stats(tr->dst.addr.p.tbl,
6597 (s == NULL) ? pd.dst :
6598 &s->key[(s->direction == PF_IN)]->addr[1],
6599 pd.af, pd.tot_len, dir == PF_OUT,
6600 r->action == PF_PASS, tr->dst.neg);
6604 case PF_SYNPROXY_DROP:
6615 /* pf_route6() returns unlocked. */
6617 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6626 /* If reassembled packet passed, create new fragments. */
6627 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6628 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6629 action = pf_refragment6(ifp, m0, mtag);