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)
135 static VNET_DEFINE(uint32_t, pf_purge_idx);
136 #define V_pf_purge_idx VNET(pf_purge_idx)
139 * Queue for pf_intr() sends.
141 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
142 struct pf_send_entry {
143 STAILQ_ENTRY(pf_send_entry) pfse_next;
158 STAILQ_HEAD(pf_send_head, pf_send_entry);
159 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
160 #define V_pf_sendqueue VNET(pf_sendqueue)
162 static struct mtx pf_sendqueue_mtx;
163 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
164 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
165 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
168 * Queue for pf_overload_task() tasks.
170 struct pf_overload_entry {
171 SLIST_ENTRY(pf_overload_entry) next;
175 struct pf_rule *rule;
178 SLIST_HEAD(pf_overload_head, pf_overload_entry);
179 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
180 #define V_pf_overloadqueue VNET(pf_overloadqueue)
181 static VNET_DEFINE(struct task, pf_overloadtask);
182 #define V_pf_overloadtask VNET(pf_overloadtask)
184 static struct mtx pf_overloadqueue_mtx;
185 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
186 "pf overload/flush queue", MTX_DEF);
187 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
188 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
190 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
191 struct mtx pf_unlnkdrules_mtx;
192 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
195 static VNET_DEFINE(uma_zone_t, pf_sources_z);
196 #define V_pf_sources_z VNET(pf_sources_z)
197 uma_zone_t pf_mtag_z;
198 VNET_DEFINE(uma_zone_t, pf_state_z);
199 VNET_DEFINE(uma_zone_t, pf_state_key_z);
201 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
202 #define PFID_CPUBITS 8
203 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
204 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
205 #define PFID_MAXID (~PFID_CPUMASK)
206 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
208 static void pf_src_tree_remove_state(struct pf_state *);
209 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
211 static void pf_add_threshold(struct pf_threshold *);
212 static int pf_check_threshold(struct pf_threshold *);
214 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
215 u_int16_t *, u_int16_t *, struct pf_addr *,
216 u_int16_t, u_int8_t, sa_family_t);
217 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
218 struct tcphdr *, struct pf_state_peer *);
219 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
220 struct pf_addr *, struct pf_addr *, u_int16_t,
221 u_int16_t *, u_int16_t *, u_int16_t *,
222 u_int16_t *, u_int8_t, sa_family_t);
223 static void pf_send_tcp(struct mbuf *,
224 const struct pf_rule *, sa_family_t,
225 const struct pf_addr *, const struct pf_addr *,
226 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
227 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
228 u_int16_t, struct ifnet *);
229 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
230 sa_family_t, struct pf_rule *);
231 static void pf_detach_state(struct pf_state *);
232 static int pf_state_key_attach(struct pf_state_key *,
233 struct pf_state_key *, struct pf_state *);
234 static void pf_state_key_detach(struct pf_state *, int);
235 static int pf_state_key_ctor(void *, int, void *, int);
236 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
237 static int pf_test_rule(struct pf_rule **, struct pf_state **,
238 int, struct pfi_kif *, struct mbuf *, int,
239 struct pf_pdesc *, struct pf_rule **,
240 struct pf_ruleset **, struct inpcb *);
241 static int pf_create_state(struct pf_rule *, struct pf_rule *,
242 struct pf_rule *, struct pf_pdesc *,
243 struct pf_src_node *, struct pf_state_key *,
244 struct pf_state_key *, struct mbuf *, int,
245 u_int16_t, u_int16_t, int *, struct pfi_kif *,
246 struct pf_state **, int, u_int16_t, u_int16_t,
248 static int pf_test_fragment(struct pf_rule **, int,
249 struct pfi_kif *, struct mbuf *, void *,
250 struct pf_pdesc *, struct pf_rule **,
251 struct pf_ruleset **);
252 static int pf_tcp_track_full(struct pf_state_peer *,
253 struct pf_state_peer *, struct pf_state **,
254 struct pfi_kif *, struct mbuf *, int,
255 struct pf_pdesc *, u_short *, int *);
256 static int pf_tcp_track_sloppy(struct pf_state_peer *,
257 struct pf_state_peer *, struct pf_state **,
258 struct pf_pdesc *, u_short *);
259 static int pf_test_state_tcp(struct pf_state **, int,
260 struct pfi_kif *, struct mbuf *, int,
261 void *, struct pf_pdesc *, u_short *);
262 static int pf_test_state_udp(struct pf_state **, int,
263 struct pfi_kif *, struct mbuf *, int,
264 void *, struct pf_pdesc *);
265 static int pf_test_state_icmp(struct pf_state **, int,
266 struct pfi_kif *, struct mbuf *, int,
267 void *, struct pf_pdesc *, u_short *);
268 static int pf_test_state_other(struct pf_state **, int,
269 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
270 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
272 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
274 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
276 static int pf_check_proto_cksum(struct mbuf *, int, int,
277 u_int8_t, sa_family_t);
278 static void pf_print_state_parts(struct pf_state *,
279 struct pf_state_key *, struct pf_state_key *);
280 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
281 struct pf_addr_wrap *);
282 static struct pf_state *pf_find_state(struct pfi_kif *,
283 struct pf_state_key_cmp *, u_int);
284 static int pf_src_connlimit(struct pf_state **);
285 static void pf_overload_task(void *v, int pending);
286 static int pf_insert_src_node(struct pf_src_node **,
287 struct pf_rule *, struct pf_addr *, sa_family_t);
288 static u_int pf_purge_expired_states(u_int, int);
289 static void pf_purge_unlinked_rules(void);
290 static int pf_mtag_uminit(void *, int, int);
291 static void pf_mtag_free(struct m_tag *);
293 static void pf_route(struct mbuf **, struct pf_rule *, int,
294 struct ifnet *, struct pf_state *,
298 static void pf_change_a6(struct pf_addr *, u_int16_t *,
299 struct pf_addr *, u_int8_t);
300 static void pf_route6(struct mbuf **, struct pf_rule *, int,
301 struct ifnet *, struct pf_state *,
305 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
307 extern int pf_end_threads;
308 extern struct proc *pf_purge_proc;
310 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
312 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
313 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
315 #define STATE_LOOKUP(i, k, d, s, pd) \
317 (s) = pf_find_state((i), (k), (d)); \
320 if (PACKET_LOOPED(pd)) \
322 if ((d) == PF_OUT && \
323 (((s)->rule.ptr->rt == PF_ROUTETO && \
324 (s)->rule.ptr->direction == PF_OUT) || \
325 ((s)->rule.ptr->rt == PF_REPLYTO && \
326 (s)->rule.ptr->direction == PF_IN)) && \
327 (s)->rt_kif != NULL && \
328 (s)->rt_kif != (i)) \
332 #define BOUND_IFACE(r, k) \
333 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
335 #define STATE_INC_COUNTERS(s) \
337 counter_u64_add(s->rule.ptr->states_cur, 1); \
338 counter_u64_add(s->rule.ptr->states_tot, 1); \
339 if (s->anchor.ptr != NULL) { \
340 counter_u64_add(s->anchor.ptr->states_cur, 1); \
341 counter_u64_add(s->anchor.ptr->states_tot, 1); \
343 if (s->nat_rule.ptr != NULL) { \
344 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
345 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
349 #define STATE_DEC_COUNTERS(s) \
351 if (s->nat_rule.ptr != NULL) \
352 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
353 if (s->anchor.ptr != NULL) \
354 counter_u64_add(s->anchor.ptr->states_cur, -1); \
355 counter_u64_add(s->rule.ptr->states_cur, -1); \
358 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
359 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
360 VNET_DEFINE(struct pf_idhash *, pf_idhash);
361 VNET_DEFINE(struct pf_srchash *, pf_srchash);
363 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
366 u_long pf_srchashmask;
367 static u_long pf_hashsize;
368 static u_long pf_srchashsize;
370 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
371 &pf_hashsize, 0, "Size of pf(4) states hashtable");
372 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
373 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
375 VNET_DEFINE(void *, pf_swi_cookie);
377 VNET_DEFINE(uint32_t, pf_hashseed);
378 #define V_pf_hashseed VNET(pf_hashseed)
381 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
387 if (a->addr32[0] > b->addr32[0])
389 if (a->addr32[0] < b->addr32[0])
395 if (a->addr32[3] > b->addr32[3])
397 if (a->addr32[3] < b->addr32[3])
399 if (a->addr32[2] > b->addr32[2])
401 if (a->addr32[2] < b->addr32[2])
403 if (a->addr32[1] > b->addr32[1])
405 if (a->addr32[1] < b->addr32[1])
407 if (a->addr32[0] > b->addr32[0])
409 if (a->addr32[0] < b->addr32[0])
414 panic("%s: unknown address family %u", __func__, af);
419 static __inline uint32_t
420 pf_hashkey(struct pf_state_key *sk)
424 h = murmur3_32_hash32((uint32_t *)sk,
425 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
428 return (h & pf_hashmask);
431 static __inline uint32_t
432 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
438 h = murmur3_32_hash32((uint32_t *)&addr->v4,
439 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
442 h = murmur3_32_hash32((uint32_t *)&addr->v6,
443 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
446 panic("%s: unknown address family %u", __func__, af);
449 return (h & pf_srchashmask);
454 pf_state_hash(struct pf_state *s)
456 u_int32_t hv = (intptr_t)s / sizeof(*s);
458 hv ^= crc32(&s->src, sizeof(s->src));
459 hv ^= crc32(&s->dst, sizeof(s->dst));
468 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
473 dst->addr32[0] = src->addr32[0];
477 dst->addr32[0] = src->addr32[0];
478 dst->addr32[1] = src->addr32[1];
479 dst->addr32[2] = src->addr32[2];
480 dst->addr32[3] = src->addr32[3];
487 pf_init_threshold(struct pf_threshold *threshold,
488 u_int32_t limit, u_int32_t seconds)
490 threshold->limit = limit * PF_THRESHOLD_MULT;
491 threshold->seconds = seconds;
492 threshold->count = 0;
493 threshold->last = time_uptime;
497 pf_add_threshold(struct pf_threshold *threshold)
499 u_int32_t t = time_uptime, diff = t - threshold->last;
501 if (diff >= threshold->seconds)
502 threshold->count = 0;
504 threshold->count -= threshold->count * diff /
506 threshold->count += PF_THRESHOLD_MULT;
511 pf_check_threshold(struct pf_threshold *threshold)
513 return (threshold->count > threshold->limit);
517 pf_src_connlimit(struct pf_state **state)
519 struct pf_overload_entry *pfoe;
522 PF_STATE_LOCK_ASSERT(*state);
524 (*state)->src_node->conn++;
525 (*state)->src.tcp_est = 1;
526 pf_add_threshold(&(*state)->src_node->conn_rate);
528 if ((*state)->rule.ptr->max_src_conn &&
529 (*state)->rule.ptr->max_src_conn <
530 (*state)->src_node->conn) {
531 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
535 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
536 pf_check_threshold(&(*state)->src_node->conn_rate)) {
537 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
544 /* Kill this state. */
545 (*state)->timeout = PFTM_PURGE;
546 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
548 if ((*state)->rule.ptr->overload_tbl == NULL)
551 /* Schedule overloading and flushing task. */
552 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
554 return (1); /* too bad :( */
556 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
557 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
558 pfoe->rule = (*state)->rule.ptr;
559 pfoe->dir = (*state)->direction;
561 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
562 PF_OVERLOADQ_UNLOCK();
563 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
569 pf_overload_task(void *v, int pending)
571 struct pf_overload_head queue;
573 struct pf_overload_entry *pfoe, *pfoe1;
576 CURVNET_SET((struct vnet *)v);
579 queue = V_pf_overloadqueue;
580 SLIST_INIT(&V_pf_overloadqueue);
581 PF_OVERLOADQ_UNLOCK();
583 bzero(&p, sizeof(p));
584 SLIST_FOREACH(pfoe, &queue, next) {
585 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
586 if (V_pf_status.debug >= PF_DEBUG_MISC) {
587 printf("%s: blocking address ", __func__);
588 pf_print_host(&pfoe->addr, 0, pfoe->af);
592 p.pfra_af = pfoe->af;
597 p.pfra_ip4addr = pfoe->addr.v4;
603 p.pfra_ip6addr = pfoe->addr.v6;
609 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
614 * Remove those entries, that don't need flushing.
616 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
617 if (pfoe->rule->flush == 0) {
618 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
619 free(pfoe, M_PFTEMP);
622 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
624 /* If nothing to flush, return. */
625 if (SLIST_EMPTY(&queue)) {
630 for (int i = 0; i <= pf_hashmask; i++) {
631 struct pf_idhash *ih = &V_pf_idhash[i];
632 struct pf_state_key *sk;
636 LIST_FOREACH(s, &ih->states, entry) {
637 sk = s->key[PF_SK_WIRE];
638 SLIST_FOREACH(pfoe, &queue, next)
639 if (sk->af == pfoe->af &&
640 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
641 pfoe->rule == s->rule.ptr) &&
642 ((pfoe->dir == PF_OUT &&
643 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
644 (pfoe->dir == PF_IN &&
645 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
646 s->timeout = PFTM_PURGE;
647 s->src.state = s->dst.state = TCPS_CLOSED;
651 PF_HASHROW_UNLOCK(ih);
653 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
654 free(pfoe, M_PFTEMP);
655 if (V_pf_status.debug >= PF_DEBUG_MISC)
656 printf("%s: %u states killed", __func__, killed);
662 * Can return locked on failure, so that we can consistently
663 * allocate and insert a new one.
666 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
669 struct pf_srchash *sh;
670 struct pf_src_node *n;
672 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
674 sh = &V_pf_srchash[pf_hashsrc(src, af)];
676 LIST_FOREACH(n, &sh->nodes, entry)
677 if (n->rule.ptr == rule && n->af == af &&
678 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
679 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
683 PF_HASHROW_UNLOCK(sh);
684 } else if (returnlocked == 0)
685 PF_HASHROW_UNLOCK(sh);
691 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
692 struct pf_addr *src, sa_family_t af)
695 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
696 rule->rpool.opts & PF_POOL_STICKYADDR),
697 ("%s for non-tracking rule %p", __func__, rule));
700 *sn = pf_find_src_node(src, rule, af, 1);
703 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
705 PF_HASHROW_ASSERT(sh);
707 if (!rule->max_src_nodes ||
708 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
709 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
711 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
714 PF_HASHROW_UNLOCK(sh);
718 pf_init_threshold(&(*sn)->conn_rate,
719 rule->max_src_conn_rate.limit,
720 rule->max_src_conn_rate.seconds);
723 (*sn)->rule.ptr = rule;
724 PF_ACPY(&(*sn)->addr, src, af);
725 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
726 (*sn)->creation = time_uptime;
727 (*sn)->ruletype = rule->action;
729 if ((*sn)->rule.ptr != NULL)
730 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
731 PF_HASHROW_UNLOCK(sh);
732 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
734 if (rule->max_src_states &&
735 (*sn)->states >= rule->max_src_states) {
736 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
745 pf_unlink_src_node(struct pf_src_node *src)
748 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
749 LIST_REMOVE(src, entry);
751 counter_u64_add(src->rule.ptr->src_nodes, -1);
755 pf_free_src_nodes(struct pf_src_node_list *head)
757 struct pf_src_node *sn, *tmp;
760 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
761 uma_zfree(V_pf_sources_z, sn);
765 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
774 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
775 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
779 /* Per-vnet data storage structures initialization. */
783 struct pf_keyhash *kh;
784 struct pf_idhash *ih;
785 struct pf_srchash *sh;
788 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
789 pf_hashsize = PF_HASHSIZ;
790 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
791 pf_srchashsize = PF_HASHSIZ / 4;
793 V_pf_hashseed = arc4random();
795 /* States and state keys storage. */
796 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
797 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
798 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
799 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
800 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
802 V_pf_state_key_z = uma_zcreate("pf state keys",
803 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
805 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
806 M_PFHASH, M_WAITOK | M_ZERO);
807 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
808 M_PFHASH, M_WAITOK | M_ZERO);
809 pf_hashmask = pf_hashsize - 1;
810 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
812 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
813 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
817 V_pf_sources_z = uma_zcreate("pf source nodes",
818 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
820 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
821 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
822 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
823 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
824 M_PFHASH, M_WAITOK|M_ZERO);
825 pf_srchashmask = pf_srchashsize - 1;
826 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
827 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
830 TAILQ_INIT(&V_pf_altqs[0]);
831 TAILQ_INIT(&V_pf_altqs[1]);
832 TAILQ_INIT(&V_pf_pabuf);
833 V_pf_altqs_active = &V_pf_altqs[0];
834 V_pf_altqs_inactive = &V_pf_altqs[1];
836 /* Send & overload+flush queues. */
837 STAILQ_INIT(&V_pf_sendqueue);
838 SLIST_INIT(&V_pf_overloadqueue);
839 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
841 /* Unlinked, but may be referenced rules. */
842 TAILQ_INIT(&V_pf_unlinked_rules);
849 uma_zdestroy(pf_mtag_z);
855 struct pf_keyhash *kh;
856 struct pf_idhash *ih;
857 struct pf_srchash *sh;
858 struct pf_send_entry *pfse, *next;
861 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
863 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
865 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
867 mtx_destroy(&kh->lock);
868 mtx_destroy(&ih->lock);
870 free(V_pf_keyhash, M_PFHASH);
871 free(V_pf_idhash, M_PFHASH);
873 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
874 KASSERT(LIST_EMPTY(&sh->nodes),
875 ("%s: source node hash not empty", __func__));
876 mtx_destroy(&sh->lock);
878 free(V_pf_srchash, M_PFHASH);
880 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
881 m_freem(pfse->pfse_m);
882 free(pfse, M_PFTEMP);
885 uma_zdestroy(V_pf_sources_z);
886 uma_zdestroy(V_pf_state_z);
887 uma_zdestroy(V_pf_state_key_z);
891 pf_mtag_uminit(void *mem, int size, int how)
895 t = (struct m_tag *)mem;
896 t->m_tag_cookie = MTAG_ABI_COMPAT;
897 t->m_tag_id = PACKET_TAG_PF;
898 t->m_tag_len = sizeof(struct pf_mtag);
899 t->m_tag_free = pf_mtag_free;
905 pf_mtag_free(struct m_tag *t)
908 uma_zfree(pf_mtag_z, t);
912 pf_get_mtag(struct mbuf *m)
916 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
917 return ((struct pf_mtag *)(mtag + 1));
919 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
922 bzero(mtag + 1, sizeof(struct pf_mtag));
923 m_tag_prepend(m, mtag);
925 return ((struct pf_mtag *)(mtag + 1));
929 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
932 struct pf_keyhash *khs, *khw, *kh;
933 struct pf_state_key *sk, *cur;
934 struct pf_state *si, *olds = NULL;
937 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
938 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
939 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
942 * We need to lock hash slots of both keys. To avoid deadlock
943 * we always lock the slot with lower address first. Unlock order
946 * We also need to lock ID hash slot before dropping key
947 * locks. On success we return with ID hash slot locked.
951 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
952 PF_HASHROW_LOCK(khs);
954 khs = &V_pf_keyhash[pf_hashkey(sks)];
955 khw = &V_pf_keyhash[pf_hashkey(skw)];
957 PF_HASHROW_LOCK(khs);
958 } else if (khs < khw) {
959 PF_HASHROW_LOCK(khs);
960 PF_HASHROW_LOCK(khw);
962 PF_HASHROW_LOCK(khw);
963 PF_HASHROW_LOCK(khs);
967 #define KEYS_UNLOCK() do { \
969 PF_HASHROW_UNLOCK(khs); \
970 PF_HASHROW_UNLOCK(khw); \
972 PF_HASHROW_UNLOCK(khs); \
976 * First run: start with wire key.
983 LIST_FOREACH(cur, &kh->keys, entry)
984 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
988 /* Key exists. Check for same kif, if none, add to key. */
989 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
990 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
993 if (si->kif == s->kif &&
994 si->direction == s->direction) {
995 if (sk->proto == IPPROTO_TCP &&
996 si->src.state >= TCPS_FIN_WAIT_2 &&
997 si->dst.state >= TCPS_FIN_WAIT_2) {
999 * New state matches an old >FIN_WAIT_2
1000 * state. We can't drop key hash locks,
1001 * thus we can't unlink it properly.
1003 * As a workaround we drop it into
1004 * TCPS_CLOSED state, schedule purge
1005 * ASAP and push it into the very end
1006 * of the slot TAILQ, so that it won't
1007 * conflict with our new state.
1009 si->src.state = si->dst.state =
1011 si->timeout = PFTM_PURGE;
1014 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1015 printf("pf: %s key attach "
1017 (idx == PF_SK_WIRE) ?
1020 pf_print_state_parts(s,
1021 (idx == PF_SK_WIRE) ?
1023 (idx == PF_SK_STACK) ?
1025 printf(", existing: ");
1026 pf_print_state_parts(si,
1027 (idx == PF_SK_WIRE) ?
1029 (idx == PF_SK_STACK) ?
1033 PF_HASHROW_UNLOCK(ih);
1035 uma_zfree(V_pf_state_key_z, sk);
1036 if (idx == PF_SK_STACK)
1038 return (EEXIST); /* collision! */
1041 PF_HASHROW_UNLOCK(ih);
1043 uma_zfree(V_pf_state_key_z, sk);
1046 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1051 /* List is sorted, if-bound states before floating. */
1052 if (s->kif == V_pfi_all)
1053 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1055 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1058 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1059 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1065 * Attach done. See how should we (or should not?)
1066 * attach a second key.
1069 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1073 } else if (sks != NULL) {
1075 * Continue attaching with stack key.
1087 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1088 ("%s failure", __func__));
1095 pf_detach_state(struct pf_state *s)
1097 struct pf_state_key *sks = s->key[PF_SK_STACK];
1098 struct pf_keyhash *kh;
1101 kh = &V_pf_keyhash[pf_hashkey(sks)];
1102 PF_HASHROW_LOCK(kh);
1103 if (s->key[PF_SK_STACK] != NULL)
1104 pf_state_key_detach(s, PF_SK_STACK);
1106 * If both point to same key, then we are done.
1108 if (sks == s->key[PF_SK_WIRE]) {
1109 pf_state_key_detach(s, PF_SK_WIRE);
1110 PF_HASHROW_UNLOCK(kh);
1113 PF_HASHROW_UNLOCK(kh);
1116 if (s->key[PF_SK_WIRE] != NULL) {
1117 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1118 PF_HASHROW_LOCK(kh);
1119 if (s->key[PF_SK_WIRE] != NULL)
1120 pf_state_key_detach(s, PF_SK_WIRE);
1121 PF_HASHROW_UNLOCK(kh);
1126 pf_state_key_detach(struct pf_state *s, int idx)
1128 struct pf_state_key *sk = s->key[idx];
1130 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1132 PF_HASHROW_ASSERT(kh);
1134 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1137 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1138 LIST_REMOVE(sk, entry);
1139 uma_zfree(V_pf_state_key_z, sk);
1144 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1146 struct pf_state_key *sk = mem;
1148 bzero(sk, sizeof(struct pf_state_key_cmp));
1149 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1150 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1155 struct pf_state_key *
1156 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1157 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1159 struct pf_state_key *sk;
1161 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1165 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1166 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1167 sk->port[pd->sidx] = sport;
1168 sk->port[pd->didx] = dport;
1169 sk->proto = pd->proto;
1175 struct pf_state_key *
1176 pf_state_key_clone(struct pf_state_key *orig)
1178 struct pf_state_key *sk;
1180 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1184 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1190 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1191 struct pf_state_key *sks, struct pf_state *s)
1193 struct pf_idhash *ih;
1194 struct pf_state *cur;
1197 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1198 ("%s: sks not pristine", __func__));
1199 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1200 ("%s: skw not pristine", __func__));
1201 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1205 if (s->id == 0 && s->creatorid == 0) {
1206 /* XXX: should be atomic, but probability of collision low */
1207 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1208 V_pf_stateid[curcpu] = 1;
1209 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1210 s->id = htobe64(s->id);
1211 s->creatorid = V_pf_status.hostid;
1214 /* Returns with ID locked on success. */
1215 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1218 ih = &V_pf_idhash[PF_IDHASH(s)];
1219 PF_HASHROW_ASSERT(ih);
1220 LIST_FOREACH(cur, &ih->states, entry)
1221 if (cur->id == s->id && cur->creatorid == s->creatorid)
1225 PF_HASHROW_UNLOCK(ih);
1226 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1227 printf("pf: state ID collision: "
1228 "id: %016llx creatorid: %08x\n",
1229 (unsigned long long)be64toh(s->id),
1230 ntohl(s->creatorid));
1235 LIST_INSERT_HEAD(&ih->states, s, entry);
1236 /* One for keys, one for ID hash. */
1237 refcount_init(&s->refs, 2);
1239 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1240 if (pfsync_insert_state_ptr != NULL)
1241 pfsync_insert_state_ptr(s);
1243 /* Returns locked. */
1248 * Find state by ID: returns with locked row on success.
1251 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1253 struct pf_idhash *ih;
1256 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1258 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1260 PF_HASHROW_LOCK(ih);
1261 LIST_FOREACH(s, &ih->states, entry)
1262 if (s->id == id && s->creatorid == creatorid)
1266 PF_HASHROW_UNLOCK(ih);
1272 * Find state by key.
1273 * Returns with ID hash slot locked on success.
1275 static struct pf_state *
1276 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1278 struct pf_keyhash *kh;
1279 struct pf_state_key *sk;
1283 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1285 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1287 PF_HASHROW_LOCK(kh);
1288 LIST_FOREACH(sk, &kh->keys, entry)
1289 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1292 PF_HASHROW_UNLOCK(kh);
1296 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1298 /* List is sorted, if-bound states before floating ones. */
1299 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1300 if (s->kif == V_pfi_all || s->kif == kif) {
1302 PF_HASHROW_UNLOCK(kh);
1303 if (s->timeout >= PFTM_MAX) {
1305 * State is either being processed by
1306 * pf_unlink_state() in an other thread, or
1307 * is scheduled for immediate expiry.
1314 PF_HASHROW_UNLOCK(kh);
1320 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1322 struct pf_keyhash *kh;
1323 struct pf_state_key *sk;
1324 struct pf_state *s, *ret = NULL;
1327 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1329 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1331 PF_HASHROW_LOCK(kh);
1332 LIST_FOREACH(sk, &kh->keys, entry)
1333 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1336 PF_HASHROW_UNLOCK(kh);
1351 panic("%s: dir %u", __func__, dir);
1354 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1356 PF_HASHROW_UNLOCK(kh);
1370 PF_HASHROW_UNLOCK(kh);
1375 /* END state table stuff */
1378 pf_send(struct pf_send_entry *pfse)
1382 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1384 swi_sched(V_pf_swi_cookie, 0);
1390 struct pf_send_head queue;
1391 struct pf_send_entry *pfse, *next;
1393 CURVNET_SET((struct vnet *)v);
1396 queue = V_pf_sendqueue;
1397 STAILQ_INIT(&V_pf_sendqueue);
1400 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1401 switch (pfse->pfse_type) {
1404 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1407 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1408 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1413 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1417 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1418 pfse->icmpopts.code, pfse->icmpopts.mtu);
1422 panic("%s: unknown type", __func__);
1424 free(pfse, M_PFTEMP);
1430 pf_purge_thread(void *unused __unused)
1432 VNET_ITERATOR_DECL(vnet_iter);
1434 sx_xlock(&pf_end_lock);
1435 while (pf_end_threads == 0) {
1436 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1439 VNET_FOREACH(vnet_iter) {
1440 CURVNET_SET(vnet_iter);
1443 /* Wait until V_pf_default_rule is initialized. */
1444 if (V_pf_vnet_active == 0) {
1450 * Process 1/interval fraction of the state
1454 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1455 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1458 * Purge other expired types every
1459 * PFTM_INTERVAL seconds.
1461 if (V_pf_purge_idx == 0) {
1463 * Order is important:
1464 * - states and src nodes reference rules
1465 * - states and rules reference kifs
1467 pf_purge_expired_fragments();
1468 pf_purge_expired_src_nodes();
1469 pf_purge_unlinked_rules();
1474 VNET_LIST_RUNLOCK();
1478 sx_xunlock(&pf_end_lock);
1483 pf_unload_vnet_purge(void)
1487 * To cleanse up all kifs and rules we need
1488 * two runs: first one clears reference flags,
1489 * then pf_purge_expired_states() doesn't
1490 * raise them, and then second run frees.
1492 pf_purge_unlinked_rules();
1496 * Now purge everything.
1498 pf_purge_expired_states(0, pf_hashmask);
1499 pf_purge_expired_fragments();
1500 pf_purge_expired_src_nodes();
1503 * Now all kifs & rules should be unreferenced,
1504 * thus should be successfully freed.
1506 pf_purge_unlinked_rules();
1512 pf_state_expires(const struct pf_state *state)
1519 /* handle all PFTM_* > PFTM_MAX here */
1520 if (state->timeout == PFTM_PURGE)
1521 return (time_uptime);
1522 KASSERT(state->timeout != PFTM_UNLINKED,
1523 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1524 KASSERT((state->timeout < PFTM_MAX),
1525 ("pf_state_expires: timeout > PFTM_MAX"));
1526 timeout = state->rule.ptr->timeout[state->timeout];
1528 timeout = V_pf_default_rule.timeout[state->timeout];
1529 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1531 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1532 states = counter_u64_fetch(state->rule.ptr->states_cur);
1534 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1535 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1536 states = V_pf_status.states;
1538 if (end && states > start && start < end) {
1540 return (state->expire + timeout * (end - states) /
1543 return (time_uptime);
1545 return (state->expire + timeout);
1549 pf_purge_expired_src_nodes()
1551 struct pf_src_node_list freelist;
1552 struct pf_srchash *sh;
1553 struct pf_src_node *cur, *next;
1556 LIST_INIT(&freelist);
1557 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1558 PF_HASHROW_LOCK(sh);
1559 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1560 if (cur->states == 0 && cur->expire <= time_uptime) {
1561 pf_unlink_src_node(cur);
1562 LIST_INSERT_HEAD(&freelist, cur, entry);
1563 } else if (cur->rule.ptr != NULL)
1564 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1565 PF_HASHROW_UNLOCK(sh);
1568 pf_free_src_nodes(&freelist);
1570 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1574 pf_src_tree_remove_state(struct pf_state *s)
1576 struct pf_src_node *sn;
1577 struct pf_srchash *sh;
1580 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1581 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1582 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1584 if (s->src_node != NULL) {
1586 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1587 PF_HASHROW_LOCK(sh);
1590 if (--sn->states == 0)
1591 sn->expire = time_uptime + timeout;
1592 PF_HASHROW_UNLOCK(sh);
1594 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1595 sn = s->nat_src_node;
1596 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1597 PF_HASHROW_LOCK(sh);
1598 if (--sn->states == 0)
1599 sn->expire = time_uptime + timeout;
1600 PF_HASHROW_UNLOCK(sh);
1602 s->src_node = s->nat_src_node = NULL;
1606 * Unlink and potentilly free a state. Function may be
1607 * called with ID hash row locked, but always returns
1608 * unlocked, since it needs to go through key hash locking.
1611 pf_unlink_state(struct pf_state *s, u_int flags)
1613 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1615 if ((flags & PF_ENTER_LOCKED) == 0)
1616 PF_HASHROW_LOCK(ih);
1618 PF_HASHROW_ASSERT(ih);
1620 if (s->timeout == PFTM_UNLINKED) {
1622 * State is being processed
1623 * by pf_unlink_state() in
1626 PF_HASHROW_UNLOCK(ih);
1627 return (0); /* XXXGL: undefined actually */
1630 if (s->src.state == PF_TCPS_PROXY_DST) {
1631 /* XXX wire key the right one? */
1632 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1633 &s->key[PF_SK_WIRE]->addr[1],
1634 &s->key[PF_SK_WIRE]->addr[0],
1635 s->key[PF_SK_WIRE]->port[1],
1636 s->key[PF_SK_WIRE]->port[0],
1637 s->src.seqhi, s->src.seqlo + 1,
1638 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1641 LIST_REMOVE(s, entry);
1642 pf_src_tree_remove_state(s);
1644 if (pfsync_delete_state_ptr != NULL)
1645 pfsync_delete_state_ptr(s);
1647 STATE_DEC_COUNTERS(s);
1649 s->timeout = PFTM_UNLINKED;
1651 PF_HASHROW_UNLOCK(ih);
1654 refcount_release(&s->refs);
1656 return (pf_release_state(s));
1660 pf_free_state(struct pf_state *cur)
1663 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1664 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1667 pf_normalize_tcp_cleanup(cur);
1668 uma_zfree(V_pf_state_z, cur);
1669 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1673 * Called only from pf_purge_thread(), thus serialized.
1676 pf_purge_expired_states(u_int i, int maxcheck)
1678 struct pf_idhash *ih;
1681 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1684 * Go through hash and unlink states that expire now.
1686 while (maxcheck > 0) {
1688 ih = &V_pf_idhash[i];
1690 PF_HASHROW_LOCK(ih);
1691 LIST_FOREACH(s, &ih->states, entry) {
1692 if (pf_state_expires(s) <= time_uptime) {
1693 V_pf_status.states -=
1694 pf_unlink_state(s, PF_ENTER_LOCKED);
1697 s->rule.ptr->rule_flag |= PFRULE_REFS;
1698 if (s->nat_rule.ptr != NULL)
1699 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1700 if (s->anchor.ptr != NULL)
1701 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1702 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1704 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1706 PF_HASHROW_UNLOCK(ih);
1708 /* Return when we hit end of hash. */
1709 if (++i > pf_hashmask) {
1710 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1717 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1723 pf_purge_unlinked_rules()
1725 struct pf_rulequeue tmpq;
1726 struct pf_rule *r, *r1;
1729 * If we have overloading task pending, then we'd
1730 * better skip purging this time. There is a tiny
1731 * probability that overloading task references
1732 * an already unlinked rule.
1734 PF_OVERLOADQ_LOCK();
1735 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1736 PF_OVERLOADQ_UNLOCK();
1739 PF_OVERLOADQ_UNLOCK();
1742 * Do naive mark-and-sweep garbage collecting of old rules.
1743 * Reference flag is raised by pf_purge_expired_states()
1744 * and pf_purge_expired_src_nodes().
1746 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1747 * use a temporary queue.
1750 PF_UNLNKDRULES_LOCK();
1751 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1752 if (!(r->rule_flag & PFRULE_REFS)) {
1753 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1754 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1756 r->rule_flag &= ~PFRULE_REFS;
1758 PF_UNLNKDRULES_UNLOCK();
1760 if (!TAILQ_EMPTY(&tmpq)) {
1762 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1763 TAILQ_REMOVE(&tmpq, r, entries);
1771 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1776 u_int32_t a = ntohl(addr->addr32[0]);
1777 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1789 u_int8_t i, curstart, curend, maxstart, maxend;
1790 curstart = curend = maxstart = maxend = 255;
1791 for (i = 0; i < 8; i++) {
1792 if (!addr->addr16[i]) {
1793 if (curstart == 255)
1797 if ((curend - curstart) >
1798 (maxend - maxstart)) {
1799 maxstart = curstart;
1802 curstart = curend = 255;
1805 if ((curend - curstart) >
1806 (maxend - maxstart)) {
1807 maxstart = curstart;
1810 for (i = 0; i < 8; i++) {
1811 if (i >= maxstart && i <= maxend) {
1817 b = ntohs(addr->addr16[i]);
1834 pf_print_state(struct pf_state *s)
1836 pf_print_state_parts(s, NULL, NULL);
1840 pf_print_state_parts(struct pf_state *s,
1841 struct pf_state_key *skwp, struct pf_state_key *sksp)
1843 struct pf_state_key *skw, *sks;
1844 u_int8_t proto, dir;
1846 /* Do our best to fill these, but they're skipped if NULL */
1847 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1848 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1849 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1850 dir = s ? s->direction : 0;
1868 case IPPROTO_ICMPV6:
1872 printf("%u", proto);
1885 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1887 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1892 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1894 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1899 if (proto == IPPROTO_TCP) {
1900 printf(" [lo=%u high=%u win=%u modulator=%u",
1901 s->src.seqlo, s->src.seqhi,
1902 s->src.max_win, s->src.seqdiff);
1903 if (s->src.wscale && s->dst.wscale)
1904 printf(" wscale=%u",
1905 s->src.wscale & PF_WSCALE_MASK);
1907 printf(" [lo=%u high=%u win=%u modulator=%u",
1908 s->dst.seqlo, s->dst.seqhi,
1909 s->dst.max_win, s->dst.seqdiff);
1910 if (s->src.wscale && s->dst.wscale)
1911 printf(" wscale=%u",
1912 s->dst.wscale & PF_WSCALE_MASK);
1915 printf(" %u:%u", s->src.state, s->dst.state);
1920 pf_print_flags(u_int8_t f)
1942 #define PF_SET_SKIP_STEPS(i) \
1944 while (head[i] != cur) { \
1945 head[i]->skip[i].ptr = cur; \
1946 head[i] = TAILQ_NEXT(head[i], entries); \
1951 pf_calc_skip_steps(struct pf_rulequeue *rules)
1953 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1956 cur = TAILQ_FIRST(rules);
1958 for (i = 0; i < PF_SKIP_COUNT; ++i)
1960 while (cur != NULL) {
1962 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1963 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1964 if (cur->direction != prev->direction)
1965 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1966 if (cur->af != prev->af)
1967 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1968 if (cur->proto != prev->proto)
1969 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1970 if (cur->src.neg != prev->src.neg ||
1971 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1972 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1973 if (cur->src.port[0] != prev->src.port[0] ||
1974 cur->src.port[1] != prev->src.port[1] ||
1975 cur->src.port_op != prev->src.port_op)
1976 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1977 if (cur->dst.neg != prev->dst.neg ||
1978 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1979 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1980 if (cur->dst.port[0] != prev->dst.port[0] ||
1981 cur->dst.port[1] != prev->dst.port[1] ||
1982 cur->dst.port_op != prev->dst.port_op)
1983 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1986 cur = TAILQ_NEXT(cur, entries);
1988 for (i = 0; i < PF_SKIP_COUNT; ++i)
1989 PF_SET_SKIP_STEPS(i);
1993 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1995 if (aw1->type != aw2->type)
1997 switch (aw1->type) {
1998 case PF_ADDR_ADDRMASK:
2000 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2002 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2005 case PF_ADDR_DYNIFTL:
2006 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2007 case PF_ADDR_NOROUTE:
2008 case PF_ADDR_URPFFAILED:
2011 return (aw1->p.tbl != aw2->p.tbl);
2013 printf("invalid address type: %d\n", aw1->type);
2019 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2020 * header isn't always a full checksum. In some cases (i.e. output) it's a
2021 * pseudo-header checksum, which is a partial checksum over src/dst IP
2022 * addresses, protocol number and length.
2024 * That means we have the following cases:
2025 * * Input or forwarding: we don't have TSO, the checksum fields are full
2026 * checksums, we need to update the checksum whenever we change anything.
2027 * * Output (i.e. the checksum is a pseudo-header checksum):
2028 * x The field being updated is src/dst address or affects the length of
2029 * the packet. We need to update the pseudo-header checksum (note that this
2030 * checksum is not ones' complement).
2031 * x Some other field is being modified (e.g. src/dst port numbers): We
2032 * don't have to update anything.
2035 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2041 l = cksum + old - new;
2042 l = (l >> 16) + (l & 65535);
2050 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2051 u_int16_t new, u_int8_t udp)
2053 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2056 return (pf_cksum_fixup(cksum, old, new, udp));
2060 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2061 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2067 PF_ACPY(&ao, a, af);
2070 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2078 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2079 ao.addr16[0], an->addr16[0], 0),
2080 ao.addr16[1], an->addr16[1], 0);
2083 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2084 ao.addr16[0], an->addr16[0], u),
2085 ao.addr16[1], an->addr16[1], u);
2087 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2092 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2093 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2094 pf_cksum_fixup(pf_cksum_fixup(*pc,
2095 ao.addr16[0], an->addr16[0], u),
2096 ao.addr16[1], an->addr16[1], u),
2097 ao.addr16[2], an->addr16[2], u),
2098 ao.addr16[3], an->addr16[3], u),
2099 ao.addr16[4], an->addr16[4], u),
2100 ao.addr16[5], an->addr16[5], u),
2101 ao.addr16[6], an->addr16[6], u),
2102 ao.addr16[7], an->addr16[7], u);
2104 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2109 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2110 CSUM_DELAY_DATA_IPV6)) {
2117 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2119 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2123 memcpy(&ao, a, sizeof(ao));
2124 memcpy(a, &an, sizeof(u_int32_t));
2125 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2126 ao % 65536, an % 65536, u);
2130 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2134 memcpy(&ao, a, sizeof(ao));
2135 memcpy(a, &an, sizeof(u_int32_t));
2137 *c = pf_proto_cksum_fixup(m,
2138 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2139 ao % 65536, an % 65536, udp);
2144 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2148 PF_ACPY(&ao, a, AF_INET6);
2149 PF_ACPY(a, an, AF_INET6);
2151 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2152 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2153 pf_cksum_fixup(pf_cksum_fixup(*c,
2154 ao.addr16[0], an->addr16[0], u),
2155 ao.addr16[1], an->addr16[1], u),
2156 ao.addr16[2], an->addr16[2], u),
2157 ao.addr16[3], an->addr16[3], u),
2158 ao.addr16[4], an->addr16[4], u),
2159 ao.addr16[5], an->addr16[5], u),
2160 ao.addr16[6], an->addr16[6], u),
2161 ao.addr16[7], an->addr16[7], u);
2166 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2167 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2168 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2170 struct pf_addr oia, ooa;
2172 PF_ACPY(&oia, ia, af);
2174 PF_ACPY(&ooa, oa, af);
2176 /* Change inner protocol port, fix inner protocol checksum. */
2178 u_int16_t oip = *ip;
2185 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2186 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2188 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2190 /* Change inner ip address, fix inner ip and icmp checksums. */
2191 PF_ACPY(ia, na, af);
2195 u_int32_t oh2c = *h2c;
2197 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2198 oia.addr16[0], ia->addr16[0], 0),
2199 oia.addr16[1], ia->addr16[1], 0);
2200 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2201 oia.addr16[0], ia->addr16[0], 0),
2202 oia.addr16[1], ia->addr16[1], 0);
2203 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2209 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2210 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2211 pf_cksum_fixup(pf_cksum_fixup(*ic,
2212 oia.addr16[0], ia->addr16[0], u),
2213 oia.addr16[1], ia->addr16[1], u),
2214 oia.addr16[2], ia->addr16[2], u),
2215 oia.addr16[3], ia->addr16[3], u),
2216 oia.addr16[4], ia->addr16[4], u),
2217 oia.addr16[5], ia->addr16[5], u),
2218 oia.addr16[6], ia->addr16[6], u),
2219 oia.addr16[7], ia->addr16[7], u);
2223 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2225 PF_ACPY(oa, na, af);
2229 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2230 ooa.addr16[0], oa->addr16[0], 0),
2231 ooa.addr16[1], oa->addr16[1], 0);
2236 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2237 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2238 pf_cksum_fixup(pf_cksum_fixup(*ic,
2239 ooa.addr16[0], oa->addr16[0], u),
2240 ooa.addr16[1], oa->addr16[1], u),
2241 ooa.addr16[2], oa->addr16[2], u),
2242 ooa.addr16[3], oa->addr16[3], u),
2243 ooa.addr16[4], oa->addr16[4], u),
2244 ooa.addr16[5], oa->addr16[5], u),
2245 ooa.addr16[6], oa->addr16[6], u),
2246 ooa.addr16[7], oa->addr16[7], u);
2255 * Need to modulate the sequence numbers in the TCP SACK option
2256 * (credits to Krzysztof Pfaff for report and patch)
2259 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2260 struct tcphdr *th, struct pf_state_peer *dst)
2262 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2263 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2264 int copyback = 0, i, olen;
2265 struct sackblk sack;
2267 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2268 if (hlen < TCPOLEN_SACKLEN ||
2269 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2272 while (hlen >= TCPOLEN_SACKLEN) {
2275 case TCPOPT_EOL: /* FALLTHROUGH */
2283 if (olen >= TCPOLEN_SACKLEN) {
2284 for (i = 2; i + TCPOLEN_SACK <= olen;
2285 i += TCPOLEN_SACK) {
2286 memcpy(&sack, &opt[i], sizeof(sack));
2287 pf_change_proto_a(m, &sack.start, &th->th_sum,
2288 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2289 pf_change_proto_a(m, &sack.end, &th->th_sum,
2290 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2291 memcpy(&opt[i], &sack, sizeof(sack));
2305 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2310 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2311 const struct pf_addr *saddr, const struct pf_addr *daddr,
2312 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2313 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2314 u_int16_t rtag, struct ifnet *ifp)
2316 struct pf_send_entry *pfse;
2320 struct ip *h = NULL;
2323 struct ip6_hdr *h6 = NULL;
2327 struct pf_mtag *pf_mtag;
2332 /* maximum segment size tcp option */
2333 tlen = sizeof(struct tcphdr);
2340 len = sizeof(struct ip) + tlen;
2345 len = sizeof(struct ip6_hdr) + tlen;
2349 panic("%s: unsupported af %d", __func__, af);
2352 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2353 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2356 m = m_gethdr(M_NOWAIT, MT_DATA);
2358 free(pfse, M_PFTEMP);
2362 mac_netinet_firewall_send(m);
2364 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2365 free(pfse, M_PFTEMP);
2370 m->m_flags |= M_SKIP_FIREWALL;
2371 pf_mtag->tag = rtag;
2373 if (r != NULL && r->rtableid >= 0)
2374 M_SETFIB(m, r->rtableid);
2377 if (r != NULL && r->qid) {
2378 pf_mtag->qid = r->qid;
2380 /* add hints for ecn */
2381 pf_mtag->hdr = mtod(m, struct ip *);
2384 m->m_data += max_linkhdr;
2385 m->m_pkthdr.len = m->m_len = len;
2386 m->m_pkthdr.rcvif = NULL;
2387 bzero(m->m_data, len);
2391 h = mtod(m, struct ip *);
2393 /* IP header fields included in the TCP checksum */
2394 h->ip_p = IPPROTO_TCP;
2395 h->ip_len = htons(tlen);
2396 h->ip_src.s_addr = saddr->v4.s_addr;
2397 h->ip_dst.s_addr = daddr->v4.s_addr;
2399 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2404 h6 = mtod(m, struct ip6_hdr *);
2406 /* IP header fields included in the TCP checksum */
2407 h6->ip6_nxt = IPPROTO_TCP;
2408 h6->ip6_plen = htons(tlen);
2409 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2410 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2412 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2418 th->th_sport = sport;
2419 th->th_dport = dport;
2420 th->th_seq = htonl(seq);
2421 th->th_ack = htonl(ack);
2422 th->th_off = tlen >> 2;
2423 th->th_flags = flags;
2424 th->th_win = htons(win);
2427 opt = (char *)(th + 1);
2428 opt[0] = TCPOPT_MAXSEG;
2431 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2438 th->th_sum = in_cksum(m, len);
2440 /* Finish the IP header */
2442 h->ip_hl = sizeof(*h) >> 2;
2443 h->ip_tos = IPTOS_LOWDELAY;
2444 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2445 h->ip_len = htons(len);
2446 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2449 pfse->pfse_type = PFSE_IP;
2455 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2456 sizeof(struct ip6_hdr), tlen);
2458 h6->ip6_vfc |= IPV6_VERSION;
2459 h6->ip6_hlim = IPV6_DEFHLIM;
2461 pfse->pfse_type = PFSE_IP6;
2470 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2474 KASSERT(prio <= PF_PRIO_MAX,
2475 ("%s with invalid pcp", __func__));
2477 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2479 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2480 sizeof(uint8_t), M_NOWAIT);
2483 m_tag_prepend(m, mtag);
2486 *(uint8_t *)(mtag + 1) = prio;
2491 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2496 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2500 if (prio == PF_PRIO_ZERO)
2503 mpcp = *(uint8_t *)(mtag + 1);
2505 return (mpcp == prio);
2509 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2512 struct pf_send_entry *pfse;
2514 struct pf_mtag *pf_mtag;
2516 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2517 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2521 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2522 free(pfse, M_PFTEMP);
2526 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2527 free(pfse, M_PFTEMP);
2531 m0->m_flags |= M_SKIP_FIREWALL;
2533 if (r->rtableid >= 0)
2534 M_SETFIB(m0, r->rtableid);
2538 pf_mtag->qid = r->qid;
2539 /* add hints for ecn */
2540 pf_mtag->hdr = mtod(m0, struct ip *);
2547 pfse->pfse_type = PFSE_ICMP;
2552 pfse->pfse_type = PFSE_ICMP6;
2557 pfse->icmpopts.type = type;
2558 pfse->icmpopts.code = code;
2563 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2564 * If n is 0, they match if they are equal. If n is != 0, they match if they
2568 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2569 struct pf_addr *b, sa_family_t af)
2576 if ((a->addr32[0] & m->addr32[0]) ==
2577 (b->addr32[0] & m->addr32[0]))
2583 if (((a->addr32[0] & m->addr32[0]) ==
2584 (b->addr32[0] & m->addr32[0])) &&
2585 ((a->addr32[1] & m->addr32[1]) ==
2586 (b->addr32[1] & m->addr32[1])) &&
2587 ((a->addr32[2] & m->addr32[2]) ==
2588 (b->addr32[2] & m->addr32[2])) &&
2589 ((a->addr32[3] & m->addr32[3]) ==
2590 (b->addr32[3] & m->addr32[3])))
2609 * Return 1 if b <= a <= e, otherwise return 0.
2612 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2613 struct pf_addr *a, sa_family_t af)
2618 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2619 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2628 for (i = 0; i < 4; ++i)
2629 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2631 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2634 for (i = 0; i < 4; ++i)
2635 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2637 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2647 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2651 return ((p > a1) && (p < a2));
2653 return ((p < a1) || (p > a2));
2655 return ((p >= a1) && (p <= a2));
2669 return (0); /* never reached */
2673 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2678 return (pf_match(op, a1, a2, p));
2682 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2684 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2686 return (pf_match(op, a1, a2, u));
2690 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2692 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2694 return (pf_match(op, a1, a2, g));
2698 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2703 return ((!r->match_tag_not && r->match_tag == *tag) ||
2704 (r->match_tag_not && r->match_tag != *tag));
2708 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2711 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2713 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2716 pd->pf_mtag->tag = tag;
2721 #define PF_ANCHOR_STACKSIZE 32
2722 struct pf_anchor_stackframe {
2723 struct pf_ruleset *rs;
2724 struct pf_rule *r; /* XXX: + match bit */
2725 struct pf_anchor *child;
2729 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2731 #define PF_ANCHORSTACK_MATCH 0x00000001
2732 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2734 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2735 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2736 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2737 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2738 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2742 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2743 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2746 struct pf_anchor_stackframe *f;
2752 if (*depth >= PF_ANCHOR_STACKSIZE) {
2753 printf("%s: anchor stack overflow on %s\n",
2754 __func__, (*r)->anchor->name);
2755 *r = TAILQ_NEXT(*r, entries);
2757 } else if (*depth == 0 && a != NULL)
2759 f = stack + (*depth)++;
2762 if ((*r)->anchor_wildcard) {
2763 struct pf_anchor_node *parent = &(*r)->anchor->children;
2765 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2769 *rs = &f->child->ruleset;
2772 *rs = &(*r)->anchor->ruleset;
2774 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2778 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2779 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2782 struct pf_anchor_stackframe *f;
2791 f = stack + *depth - 1;
2792 fr = PF_ANCHOR_RULE(f);
2793 if (f->child != NULL) {
2794 struct pf_anchor_node *parent;
2797 * This block traverses through
2798 * a wildcard anchor.
2800 parent = &fr->anchor->children;
2801 if (match != NULL && *match) {
2803 * If any of "*" matched, then
2804 * "foo/ *" matched, mark frame
2807 PF_ANCHOR_SET_MATCH(f);
2810 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2811 if (f->child != NULL) {
2812 *rs = &f->child->ruleset;
2813 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2821 if (*depth == 0 && a != NULL)
2824 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2826 *r = TAILQ_NEXT(fr, entries);
2827 } while (*r == NULL);
2834 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2835 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2840 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2841 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2845 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2846 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2847 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2848 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2849 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2850 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2851 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2852 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2858 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2863 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2867 if (addr->addr32[3] == 0xffffffff) {
2868 addr->addr32[3] = 0;
2869 if (addr->addr32[2] == 0xffffffff) {
2870 addr->addr32[2] = 0;
2871 if (addr->addr32[1] == 0xffffffff) {
2872 addr->addr32[1] = 0;
2874 htonl(ntohl(addr->addr32[0]) + 1);
2877 htonl(ntohl(addr->addr32[1]) + 1);
2880 htonl(ntohl(addr->addr32[2]) + 1);
2883 htonl(ntohl(addr->addr32[3]) + 1);
2890 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2892 struct pf_addr *saddr, *daddr;
2893 u_int16_t sport, dport;
2894 struct inpcbinfo *pi;
2897 pd->lookup.uid = UID_MAX;
2898 pd->lookup.gid = GID_MAX;
2900 switch (pd->proto) {
2902 if (pd->hdr.tcp == NULL)
2904 sport = pd->hdr.tcp->th_sport;
2905 dport = pd->hdr.tcp->th_dport;
2909 if (pd->hdr.udp == NULL)
2911 sport = pd->hdr.udp->uh_sport;
2912 dport = pd->hdr.udp->uh_dport;
2918 if (direction == PF_IN) {
2933 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2934 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2936 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2937 daddr->v4, dport, INPLOOKUP_WILDCARD |
2938 INPLOOKUP_RLOCKPCB, NULL, m);
2946 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2947 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2949 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2950 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2951 INPLOOKUP_RLOCKPCB, NULL, m);
2961 INP_RLOCK_ASSERT(inp);
2962 pd->lookup.uid = inp->inp_cred->cr_uid;
2963 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2970 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2974 u_int8_t *opt, optlen;
2975 u_int8_t wscale = 0;
2977 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2978 if (hlen <= sizeof(struct tcphdr))
2980 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2982 opt = hdr + sizeof(struct tcphdr);
2983 hlen -= sizeof(struct tcphdr);
2993 if (wscale > TCP_MAX_WINSHIFT)
2994 wscale = TCP_MAX_WINSHIFT;
2995 wscale |= PF_WSCALE_FLAG;
3010 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3014 u_int8_t *opt, optlen;
3015 u_int16_t mss = V_tcp_mssdflt;
3017 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3018 if (hlen <= sizeof(struct tcphdr))
3020 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3022 opt = hdr + sizeof(struct tcphdr);
3023 hlen -= sizeof(struct tcphdr);
3024 while (hlen >= TCPOLEN_MAXSEG) {
3032 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3048 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3051 struct nhop4_basic nh4;
3054 struct nhop6_basic nh6;
3055 struct in6_addr dst6;
3064 hlen = sizeof(struct ip);
3065 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3066 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3071 hlen = sizeof(struct ip6_hdr);
3072 in6_splitscope(&addr->v6, &dst6, &scopeid);
3073 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3074 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3079 mss = max(V_tcp_mssdflt, mss);
3080 mss = min(mss, offer);
3081 mss = max(mss, 64); /* sanity - at least max opt space */
3086 pf_tcp_iss(struct pf_pdesc *pd)
3089 u_int32_t digest[4];
3091 if (V_pf_tcp_secret_init == 0) {
3092 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3093 MD5Init(&V_pf_tcp_secret_ctx);
3094 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3095 sizeof(V_pf_tcp_secret));
3096 V_pf_tcp_secret_init = 1;
3099 ctx = V_pf_tcp_secret_ctx;
3101 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3102 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3103 if (pd->af == AF_INET6) {
3104 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3105 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3107 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3108 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3110 MD5Final((u_char *)digest, &ctx);
3111 V_pf_tcp_iss_off += 4096;
3112 #define ISN_RANDOM_INCREMENT (4096 - 1)
3113 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3115 #undef ISN_RANDOM_INCREMENT
3119 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3120 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3121 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3123 struct pf_rule *nr = NULL;
3124 struct pf_addr * const saddr = pd->src;
3125 struct pf_addr * const daddr = pd->dst;
3126 sa_family_t af = pd->af;
3127 struct pf_rule *r, *a = NULL;
3128 struct pf_ruleset *ruleset = NULL;
3129 struct pf_src_node *nsn = NULL;
3130 struct tcphdr *th = pd->hdr.tcp;
3131 struct pf_state_key *sk = NULL, *nk = NULL;
3133 int rewrite = 0, hdrlen = 0;
3134 int tag = -1, rtableid = -1;
3138 u_int16_t sport = 0, dport = 0;
3139 u_int16_t bproto_sum = 0, bip_sum = 0;
3140 u_int8_t icmptype = 0, icmpcode = 0;
3141 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3146 INP_LOCK_ASSERT(inp);
3147 pd->lookup.uid = inp->inp_cred->cr_uid;
3148 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3149 pd->lookup.done = 1;
3152 switch (pd->proto) {
3154 sport = th->th_sport;
3155 dport = th->th_dport;
3156 hdrlen = sizeof(*th);
3159 sport = pd->hdr.udp->uh_sport;
3160 dport = pd->hdr.udp->uh_dport;
3161 hdrlen = sizeof(*pd->hdr.udp);
3165 if (pd->af != AF_INET)
3167 sport = dport = pd->hdr.icmp->icmp_id;
3168 hdrlen = sizeof(*pd->hdr.icmp);
3169 icmptype = pd->hdr.icmp->icmp_type;
3170 icmpcode = pd->hdr.icmp->icmp_code;
3172 if (icmptype == ICMP_UNREACH ||
3173 icmptype == ICMP_SOURCEQUENCH ||
3174 icmptype == ICMP_REDIRECT ||
3175 icmptype == ICMP_TIMXCEED ||
3176 icmptype == ICMP_PARAMPROB)
3181 case IPPROTO_ICMPV6:
3184 sport = dport = pd->hdr.icmp6->icmp6_id;
3185 hdrlen = sizeof(*pd->hdr.icmp6);
3186 icmptype = pd->hdr.icmp6->icmp6_type;
3187 icmpcode = pd->hdr.icmp6->icmp6_code;
3189 if (icmptype == ICMP6_DST_UNREACH ||
3190 icmptype == ICMP6_PACKET_TOO_BIG ||
3191 icmptype == ICMP6_TIME_EXCEEDED ||
3192 icmptype == ICMP6_PARAM_PROB)
3197 sport = dport = hdrlen = 0;
3201 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3203 /* check packet for BINAT/NAT/RDR */
3204 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3205 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3206 KASSERT(sk != NULL, ("%s: null sk", __func__));
3207 KASSERT(nk != NULL, ("%s: null nk", __func__));
3210 bip_sum = *pd->ip_sum;
3212 switch (pd->proto) {
3214 bproto_sum = th->th_sum;
3215 pd->proto_sum = &th->th_sum;
3217 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3218 nk->port[pd->sidx] != sport) {
3219 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3220 &th->th_sum, &nk->addr[pd->sidx],
3221 nk->port[pd->sidx], 0, af);
3222 pd->sport = &th->th_sport;
3223 sport = th->th_sport;
3226 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3227 nk->port[pd->didx] != dport) {
3228 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3229 &th->th_sum, &nk->addr[pd->didx],
3230 nk->port[pd->didx], 0, af);
3231 dport = th->th_dport;
3232 pd->dport = &th->th_dport;
3237 bproto_sum = pd->hdr.udp->uh_sum;
3238 pd->proto_sum = &pd->hdr.udp->uh_sum;
3240 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3241 nk->port[pd->sidx] != sport) {
3242 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3243 pd->ip_sum, &pd->hdr.udp->uh_sum,
3244 &nk->addr[pd->sidx],
3245 nk->port[pd->sidx], 1, af);
3246 sport = pd->hdr.udp->uh_sport;
3247 pd->sport = &pd->hdr.udp->uh_sport;
3250 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3251 nk->port[pd->didx] != dport) {
3252 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3253 pd->ip_sum, &pd->hdr.udp->uh_sum,
3254 &nk->addr[pd->didx],
3255 nk->port[pd->didx], 1, af);
3256 dport = pd->hdr.udp->uh_dport;
3257 pd->dport = &pd->hdr.udp->uh_dport;
3263 nk->port[0] = nk->port[1];
3264 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3265 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3266 nk->addr[pd->sidx].v4.s_addr, 0);
3268 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3269 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3270 nk->addr[pd->didx].v4.s_addr, 0);
3272 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3273 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3274 pd->hdr.icmp->icmp_cksum, sport,
3276 pd->hdr.icmp->icmp_id = nk->port[1];
3277 pd->sport = &pd->hdr.icmp->icmp_id;
3279 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3283 case IPPROTO_ICMPV6:
3284 nk->port[0] = nk->port[1];
3285 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3286 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3287 &nk->addr[pd->sidx], 0);
3289 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3290 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3291 &nk->addr[pd->didx], 0);
3300 &nk->addr[pd->sidx], AF_INET))
3301 pf_change_a(&saddr->v4.s_addr,
3303 nk->addr[pd->sidx].v4.s_addr, 0);
3306 &nk->addr[pd->didx], AF_INET))
3307 pf_change_a(&daddr->v4.s_addr,
3309 nk->addr[pd->didx].v4.s_addr, 0);
3315 &nk->addr[pd->sidx], AF_INET6))
3316 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3319 &nk->addr[pd->didx], AF_INET6))
3320 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3333 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3334 r = r->skip[PF_SKIP_IFP].ptr;
3335 else if (r->direction && r->direction != direction)
3336 r = r->skip[PF_SKIP_DIR].ptr;
3337 else if (r->af && r->af != af)
3338 r = r->skip[PF_SKIP_AF].ptr;
3339 else if (r->proto && r->proto != pd->proto)
3340 r = r->skip[PF_SKIP_PROTO].ptr;
3341 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3342 r->src.neg, kif, M_GETFIB(m)))
3343 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3344 /* tcp/udp only. port_op always 0 in other cases */
3345 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3346 r->src.port[0], r->src.port[1], sport))
3347 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3348 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3349 r->dst.neg, NULL, M_GETFIB(m)))
3350 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3351 /* tcp/udp only. port_op always 0 in other cases */
3352 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3353 r->dst.port[0], r->dst.port[1], dport))
3354 r = r->skip[PF_SKIP_DST_PORT].ptr;
3355 /* icmp only. type always 0 in other cases */
3356 else if (r->type && r->type != icmptype + 1)
3357 r = TAILQ_NEXT(r, entries);
3358 /* icmp only. type always 0 in other cases */
3359 else if (r->code && r->code != icmpcode + 1)
3360 r = TAILQ_NEXT(r, entries);
3361 else if (r->tos && !(r->tos == pd->tos))
3362 r = TAILQ_NEXT(r, entries);
3363 else if (r->rule_flag & PFRULE_FRAGMENT)
3364 r = TAILQ_NEXT(r, entries);
3365 else if (pd->proto == IPPROTO_TCP &&
3366 (r->flagset & th->th_flags) != r->flags)
3367 r = TAILQ_NEXT(r, entries);
3368 /* tcp/udp only. uid.op always 0 in other cases */
3369 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3370 pf_socket_lookup(direction, pd, m), 1)) &&
3371 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3373 r = TAILQ_NEXT(r, entries);
3374 /* tcp/udp only. gid.op always 0 in other cases */
3375 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3376 pf_socket_lookup(direction, pd, m), 1)) &&
3377 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3379 r = TAILQ_NEXT(r, entries);
3381 !pf_match_ieee8021q_pcp(r->prio, m))
3382 r = TAILQ_NEXT(r, entries);
3384 r->prob <= arc4random())
3385 r = TAILQ_NEXT(r, entries);
3386 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3387 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3388 r = TAILQ_NEXT(r, entries);
3389 else if (r->os_fingerprint != PF_OSFP_ANY &&
3390 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3391 pf_osfp_fingerprint(pd, m, off, th),
3392 r->os_fingerprint)))
3393 r = TAILQ_NEXT(r, entries);
3397 if (r->rtableid >= 0)
3398 rtableid = r->rtableid;
3399 if (r->anchor == NULL) {
3406 r = TAILQ_NEXT(r, entries);
3408 pf_step_into_anchor(anchor_stack, &asd,
3409 &ruleset, PF_RULESET_FILTER, &r, &a,
3412 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3413 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3420 REASON_SET(&reason, PFRES_MATCH);
3422 if (r->log || (nr != NULL && nr->log)) {
3424 m_copyback(m, off, hdrlen, pd->hdr.any);
3425 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3429 if ((r->action == PF_DROP) &&
3430 ((r->rule_flag & PFRULE_RETURNRST) ||
3431 (r->rule_flag & PFRULE_RETURNICMP) ||
3432 (r->rule_flag & PFRULE_RETURN))) {
3433 /* undo NAT changes, if they have taken place */
3435 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3436 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3438 *pd->sport = sk->port[pd->sidx];
3440 *pd->dport = sk->port[pd->didx];
3442 *pd->proto_sum = bproto_sum;
3444 *pd->ip_sum = bip_sum;
3445 m_copyback(m, off, hdrlen, pd->hdr.any);
3447 if (pd->proto == IPPROTO_TCP &&
3448 ((r->rule_flag & PFRULE_RETURNRST) ||
3449 (r->rule_flag & PFRULE_RETURN)) &&
3450 !(th->th_flags & TH_RST)) {
3451 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3463 h4 = mtod(m, struct ip *);
3464 len = ntohs(h4->ip_len) - off;
3469 h6 = mtod(m, struct ip6_hdr *);
3470 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3475 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3476 REASON_SET(&reason, PFRES_PROTCKSUM);
3478 if (th->th_flags & TH_SYN)
3480 if (th->th_flags & TH_FIN)
3482 pf_send_tcp(m, r, af, pd->dst,
3483 pd->src, th->th_dport, th->th_sport,
3484 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3485 r->return_ttl, 1, 0, kif->pfik_ifp);
3487 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3489 pf_send_icmp(m, r->return_icmp >> 8,
3490 r->return_icmp & 255, af, r);
3491 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3493 pf_send_icmp(m, r->return_icmp6 >> 8,
3494 r->return_icmp6 & 255, af, r);
3497 if (r->action == PF_DROP)
3500 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3501 REASON_SET(&reason, PFRES_MEMORY);
3505 M_SETFIB(m, rtableid);
3507 if (!state_icmp && (r->keep_state || nr != NULL ||
3508 (pd->flags & PFDESC_TCP_NORM))) {
3510 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3511 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3513 if (action != PF_PASS)
3517 uma_zfree(V_pf_state_key_z, sk);
3519 uma_zfree(V_pf_state_key_z, nk);
3522 /* copy back packet headers if we performed NAT operations */
3524 m_copyback(m, off, hdrlen, pd->hdr.any);
3526 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3527 direction == PF_OUT &&
3528 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3530 * We want the state created, but we dont
3531 * want to send this in case a partner
3532 * firewall has to know about it to allow
3533 * replies through it.
3541 uma_zfree(V_pf_state_key_z, sk);
3543 uma_zfree(V_pf_state_key_z, nk);
3548 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3549 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3550 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3551 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3552 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3554 struct pf_state *s = NULL;
3555 struct pf_src_node *sn = NULL;
3556 struct tcphdr *th = pd->hdr.tcp;
3557 u_int16_t mss = V_tcp_mssdflt;
3560 /* check maximums */
3561 if (r->max_states &&
3562 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3563 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3564 REASON_SET(&reason, PFRES_MAXSTATES);
3567 /* src node for filter rule */
3568 if ((r->rule_flag & PFRULE_SRCTRACK ||
3569 r->rpool.opts & PF_POOL_STICKYADDR) &&
3570 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3571 REASON_SET(&reason, PFRES_SRCLIMIT);
3574 /* src node for translation rule */
3575 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3576 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3577 REASON_SET(&reason, PFRES_SRCLIMIT);
3580 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3582 REASON_SET(&reason, PFRES_MEMORY);
3586 s->nat_rule.ptr = nr;
3588 STATE_INC_COUNTERS(s);
3590 s->state_flags |= PFSTATE_ALLOWOPTS;
3591 if (r->rule_flag & PFRULE_STATESLOPPY)
3592 s->state_flags |= PFSTATE_SLOPPY;
3593 s->log = r->log & PF_LOG_ALL;
3594 s->sync_state = PFSYNC_S_NONE;
3596 s->log |= nr->log & PF_LOG_ALL;
3597 switch (pd->proto) {
3599 s->src.seqlo = ntohl(th->th_seq);
3600 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3601 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3602 r->keep_state == PF_STATE_MODULATE) {
3603 /* Generate sequence number modulator */
3604 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3607 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3608 htonl(s->src.seqlo + s->src.seqdiff), 0);
3612 if (th->th_flags & TH_SYN) {
3614 s->src.wscale = pf_get_wscale(m, off,
3615 th->th_off, pd->af);
3617 s->src.max_win = MAX(ntohs(th->th_win), 1);
3618 if (s->src.wscale & PF_WSCALE_MASK) {
3619 /* Remove scale factor from initial window */
3620 int win = s->src.max_win;
3621 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3622 s->src.max_win = (win - 1) >>
3623 (s->src.wscale & PF_WSCALE_MASK);
3625 if (th->th_flags & TH_FIN)
3629 s->src.state = TCPS_SYN_SENT;
3630 s->dst.state = TCPS_CLOSED;
3631 s->timeout = PFTM_TCP_FIRST_PACKET;
3634 s->src.state = PFUDPS_SINGLE;
3635 s->dst.state = PFUDPS_NO_TRAFFIC;
3636 s->timeout = PFTM_UDP_FIRST_PACKET;
3640 case IPPROTO_ICMPV6:
3642 s->timeout = PFTM_ICMP_FIRST_PACKET;
3645 s->src.state = PFOTHERS_SINGLE;
3646 s->dst.state = PFOTHERS_NO_TRAFFIC;
3647 s->timeout = PFTM_OTHER_FIRST_PACKET;
3651 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3652 REASON_SET(&reason, PFRES_MAPFAILED);
3653 pf_src_tree_remove_state(s);
3654 STATE_DEC_COUNTERS(s);
3655 uma_zfree(V_pf_state_z, s);
3658 s->rt_kif = r->rpool.cur->kif;
3661 s->creation = time_uptime;
3662 s->expire = time_uptime;
3667 /* XXX We only modify one side for now. */
3668 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3669 s->nat_src_node = nsn;
3671 if (pd->proto == IPPROTO_TCP) {
3672 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3673 off, pd, th, &s->src, &s->dst)) {
3674 REASON_SET(&reason, PFRES_MEMORY);
3675 pf_src_tree_remove_state(s);
3676 STATE_DEC_COUNTERS(s);
3677 uma_zfree(V_pf_state_z, s);
3680 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3681 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3682 &s->src, &s->dst, rewrite)) {
3683 /* This really shouldn't happen!!! */
3684 DPFPRINTF(PF_DEBUG_URGENT,
3685 ("pf_normalize_tcp_stateful failed on first pkt"));
3686 pf_normalize_tcp_cleanup(s);
3687 pf_src_tree_remove_state(s);
3688 STATE_DEC_COUNTERS(s);
3689 uma_zfree(V_pf_state_z, s);
3693 s->direction = pd->dir;
3696 * sk/nk could already been setup by pf_get_translation().
3699 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3700 __func__, nr, sk, nk));
3701 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3706 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3707 __func__, nr, sk, nk));
3709 /* Swap sk/nk for PF_OUT. */
3710 if (pf_state_insert(BOUND_IFACE(r, kif),
3711 (pd->dir == PF_IN) ? sk : nk,
3712 (pd->dir == PF_IN) ? nk : sk, s)) {
3713 if (pd->proto == IPPROTO_TCP)
3714 pf_normalize_tcp_cleanup(s);
3715 REASON_SET(&reason, PFRES_STATEINS);
3716 pf_src_tree_remove_state(s);
3717 STATE_DEC_COUNTERS(s);
3718 uma_zfree(V_pf_state_z, s);
3725 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3726 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3727 s->src.state = PF_TCPS_PROXY_SRC;
3728 /* undo NAT changes, if they have taken place */
3730 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3731 if (pd->dir == PF_OUT)
3732 skt = s->key[PF_SK_STACK];
3733 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3734 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3736 *pd->sport = skt->port[pd->sidx];
3738 *pd->dport = skt->port[pd->didx];
3740 *pd->proto_sum = bproto_sum;
3742 *pd->ip_sum = bip_sum;
3743 m_copyback(m, off, hdrlen, pd->hdr.any);
3745 s->src.seqhi = htonl(arc4random());
3746 /* Find mss option */
3747 int rtid = M_GETFIB(m);
3748 mss = pf_get_mss(m, off, th->th_off, pd->af);
3749 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3750 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3752 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3753 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3754 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3755 REASON_SET(&reason, PFRES_SYNPROXY);
3756 return (PF_SYNPROXY_DROP);
3763 uma_zfree(V_pf_state_key_z, sk);
3765 uma_zfree(V_pf_state_key_z, nk);
3768 struct pf_srchash *sh;
3770 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3771 PF_HASHROW_LOCK(sh);
3772 if (--sn->states == 0 && sn->expire == 0) {
3773 pf_unlink_src_node(sn);
3774 uma_zfree(V_pf_sources_z, sn);
3776 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3778 PF_HASHROW_UNLOCK(sh);
3781 if (nsn != sn && nsn != NULL) {
3782 struct pf_srchash *sh;
3784 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3785 PF_HASHROW_LOCK(sh);
3786 if (--nsn->states == 0 && nsn->expire == 0) {
3787 pf_unlink_src_node(nsn);
3788 uma_zfree(V_pf_sources_z, nsn);
3790 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3792 PF_HASHROW_UNLOCK(sh);
3799 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3800 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3801 struct pf_ruleset **rsm)
3803 struct pf_rule *r, *a = NULL;
3804 struct pf_ruleset *ruleset = NULL;
3805 sa_family_t af = pd->af;
3810 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3814 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3817 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3818 r = r->skip[PF_SKIP_IFP].ptr;
3819 else if (r->direction && r->direction != direction)
3820 r = r->skip[PF_SKIP_DIR].ptr;
3821 else if (r->af && r->af != af)
3822 r = r->skip[PF_SKIP_AF].ptr;
3823 else if (r->proto && r->proto != pd->proto)
3824 r = r->skip[PF_SKIP_PROTO].ptr;
3825 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3826 r->src.neg, kif, M_GETFIB(m)))
3827 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3828 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3829 r->dst.neg, NULL, M_GETFIB(m)))
3830 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3831 else if (r->tos && !(r->tos == pd->tos))
3832 r = TAILQ_NEXT(r, entries);
3833 else if (r->os_fingerprint != PF_OSFP_ANY)
3834 r = TAILQ_NEXT(r, entries);
3835 else if (pd->proto == IPPROTO_UDP &&
3836 (r->src.port_op || r->dst.port_op))
3837 r = TAILQ_NEXT(r, entries);
3838 else if (pd->proto == IPPROTO_TCP &&
3839 (r->src.port_op || r->dst.port_op || r->flagset))
3840 r = TAILQ_NEXT(r, entries);
3841 else if ((pd->proto == IPPROTO_ICMP ||
3842 pd->proto == IPPROTO_ICMPV6) &&
3843 (r->type || r->code))
3844 r = TAILQ_NEXT(r, entries);
3846 !pf_match_ieee8021q_pcp(r->prio, m))
3847 r = TAILQ_NEXT(r, entries);
3848 else if (r->prob && r->prob <=
3849 (arc4random() % (UINT_MAX - 1) + 1))
3850 r = TAILQ_NEXT(r, entries);
3851 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3852 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3853 r = TAILQ_NEXT(r, entries);
3855 if (r->anchor == NULL) {
3862 r = TAILQ_NEXT(r, entries);
3864 pf_step_into_anchor(anchor_stack, &asd,
3865 &ruleset, PF_RULESET_FILTER, &r, &a,
3868 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3869 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3876 REASON_SET(&reason, PFRES_MATCH);
3879 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3882 if (r->action != PF_PASS)
3885 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3886 REASON_SET(&reason, PFRES_MEMORY);
3894 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3895 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3896 struct pf_pdesc *pd, u_short *reason, int *copyback)
3898 struct tcphdr *th = pd->hdr.tcp;
3899 u_int16_t win = ntohs(th->th_win);
3900 u_int32_t ack, end, seq, orig_seq;
3904 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3905 sws = src->wscale & PF_WSCALE_MASK;
3906 dws = dst->wscale & PF_WSCALE_MASK;
3911 * Sequence tracking algorithm from Guido van Rooij's paper:
3912 * http://www.madison-gurkha.com/publications/tcp_filtering/
3916 orig_seq = seq = ntohl(th->th_seq);
3917 if (src->seqlo == 0) {
3918 /* First packet from this end. Set its state */
3920 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3921 src->scrub == NULL) {
3922 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3923 REASON_SET(reason, PFRES_MEMORY);
3928 /* Deferred generation of sequence number modulator */
3929 if (dst->seqdiff && !src->seqdiff) {
3930 /* use random iss for the TCP server */
3931 while ((src->seqdiff = arc4random() - seq) == 0)
3933 ack = ntohl(th->th_ack) - dst->seqdiff;
3934 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3936 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3939 ack = ntohl(th->th_ack);
3942 end = seq + pd->p_len;
3943 if (th->th_flags & TH_SYN) {
3945 if (dst->wscale & PF_WSCALE_FLAG) {
3946 src->wscale = pf_get_wscale(m, off, th->th_off,
3948 if (src->wscale & PF_WSCALE_FLAG) {
3949 /* Remove scale factor from initial
3951 sws = src->wscale & PF_WSCALE_MASK;
3952 win = ((u_int32_t)win + (1 << sws) - 1)
3954 dws = dst->wscale & PF_WSCALE_MASK;
3956 /* fixup other window */
3957 dst->max_win <<= dst->wscale &
3959 /* in case of a retrans SYN|ACK */
3964 if (th->th_flags & TH_FIN)
3968 if (src->state < TCPS_SYN_SENT)
3969 src->state = TCPS_SYN_SENT;
3972 * May need to slide the window (seqhi may have been set by
3973 * the crappy stack check or if we picked up the connection
3974 * after establishment)
3976 if (src->seqhi == 1 ||
3977 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3978 src->seqhi = end + MAX(1, dst->max_win << dws);
3979 if (win > src->max_win)
3983 ack = ntohl(th->th_ack) - dst->seqdiff;
3985 /* Modulate sequence numbers */
3986 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3988 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3991 end = seq + pd->p_len;
3992 if (th->th_flags & TH_SYN)
3994 if (th->th_flags & TH_FIN)
3998 if ((th->th_flags & TH_ACK) == 0) {
3999 /* Let it pass through the ack skew check */
4001 } else if ((ack == 0 &&
4002 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4003 /* broken tcp stacks do not set ack */
4004 (dst->state < TCPS_SYN_SENT)) {
4006 * Many stacks (ours included) will set the ACK number in an
4007 * FIN|ACK if the SYN times out -- no sequence to ACK.
4013 /* Ease sequencing restrictions on no data packets */
4018 ackskew = dst->seqlo - ack;
4022 * Need to demodulate the sequence numbers in any TCP SACK options
4023 * (Selective ACK). We could optionally validate the SACK values
4024 * against the current ACK window, either forwards or backwards, but
4025 * I'm not confident that SACK has been implemented properly
4026 * everywhere. It wouldn't surprise me if several stacks accidentally
4027 * SACK too far backwards of previously ACKed data. There really aren't
4028 * any security implications of bad SACKing unless the target stack
4029 * doesn't validate the option length correctly. Someone trying to
4030 * spoof into a TCP connection won't bother blindly sending SACK
4033 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4034 if (pf_modulate_sack(m, off, pd, th, dst))
4039 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4040 if (SEQ_GEQ(src->seqhi, end) &&
4041 /* Last octet inside other's window space */
4042 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4043 /* Retrans: not more than one window back */
4044 (ackskew >= -MAXACKWINDOW) &&
4045 /* Acking not more than one reassembled fragment backwards */
4046 (ackskew <= (MAXACKWINDOW << sws)) &&
4047 /* Acking not more than one window forward */
4048 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4049 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4050 (pd->flags & PFDESC_IP_REAS) == 0)) {
4051 /* Require an exact/+1 sequence match on resets when possible */
4053 if (dst->scrub || src->scrub) {
4054 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4055 *state, src, dst, copyback))
4059 /* update max window */
4060 if (src->max_win < win)
4062 /* synchronize sequencing */
4063 if (SEQ_GT(end, src->seqlo))
4065 /* slide the window of what the other end can send */
4066 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4067 dst->seqhi = ack + MAX((win << sws), 1);
4071 if (th->th_flags & TH_SYN)
4072 if (src->state < TCPS_SYN_SENT)
4073 src->state = TCPS_SYN_SENT;
4074 if (th->th_flags & TH_FIN)
4075 if (src->state < TCPS_CLOSING)
4076 src->state = TCPS_CLOSING;
4077 if (th->th_flags & TH_ACK) {
4078 if (dst->state == TCPS_SYN_SENT) {
4079 dst->state = TCPS_ESTABLISHED;
4080 if (src->state == TCPS_ESTABLISHED &&
4081 (*state)->src_node != NULL &&
4082 pf_src_connlimit(state)) {
4083 REASON_SET(reason, PFRES_SRCLIMIT);
4086 } else if (dst->state == TCPS_CLOSING)
4087 dst->state = TCPS_FIN_WAIT_2;
4089 if (th->th_flags & TH_RST)
4090 src->state = dst->state = TCPS_TIME_WAIT;
4092 /* update expire time */
4093 (*state)->expire = time_uptime;
4094 if (src->state >= TCPS_FIN_WAIT_2 &&
4095 dst->state >= TCPS_FIN_WAIT_2)
4096 (*state)->timeout = PFTM_TCP_CLOSED;
4097 else if (src->state >= TCPS_CLOSING &&
4098 dst->state >= TCPS_CLOSING)
4099 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4100 else if (src->state < TCPS_ESTABLISHED ||
4101 dst->state < TCPS_ESTABLISHED)
4102 (*state)->timeout = PFTM_TCP_OPENING;
4103 else if (src->state >= TCPS_CLOSING ||
4104 dst->state >= TCPS_CLOSING)
4105 (*state)->timeout = PFTM_TCP_CLOSING;
4107 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4109 /* Fall through to PASS packet */
4111 } else if ((dst->state < TCPS_SYN_SENT ||
4112 dst->state >= TCPS_FIN_WAIT_2 ||
4113 src->state >= TCPS_FIN_WAIT_2) &&
4114 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4115 /* Within a window forward of the originating packet */
4116 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4117 /* Within a window backward of the originating packet */
4120 * This currently handles three situations:
4121 * 1) Stupid stacks will shotgun SYNs before their peer
4123 * 2) When PF catches an already established stream (the
4124 * firewall rebooted, the state table was flushed, routes
4126 * 3) Packets get funky immediately after the connection
4127 * closes (this should catch Solaris spurious ACK|FINs
4128 * that web servers like to spew after a close)
4130 * This must be a little more careful than the above code
4131 * since packet floods will also be caught here. We don't
4132 * update the TTL here to mitigate the damage of a packet
4133 * flood and so the same code can handle awkward establishment
4134 * and a loosened connection close.
4135 * In the establishment case, a correct peer response will
4136 * validate the connection, go through the normal state code
4137 * and keep updating the state TTL.
4140 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4141 printf("pf: loose state match: ");
4142 pf_print_state(*state);
4143 pf_print_flags(th->th_flags);
4144 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4145 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4146 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4147 (unsigned long long)(*state)->packets[1],
4148 pd->dir == PF_IN ? "in" : "out",
4149 pd->dir == (*state)->direction ? "fwd" : "rev");
4152 if (dst->scrub || src->scrub) {
4153 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4154 *state, src, dst, copyback))
4158 /* update max window */
4159 if (src->max_win < win)
4161 /* synchronize sequencing */
4162 if (SEQ_GT(end, src->seqlo))
4164 /* slide the window of what the other end can send */
4165 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4166 dst->seqhi = ack + MAX((win << sws), 1);
4169 * Cannot set dst->seqhi here since this could be a shotgunned
4170 * SYN and not an already established connection.
4173 if (th->th_flags & TH_FIN)
4174 if (src->state < TCPS_CLOSING)
4175 src->state = TCPS_CLOSING;
4176 if (th->th_flags & TH_RST)
4177 src->state = dst->state = TCPS_TIME_WAIT;
4179 /* Fall through to PASS packet */
4182 if ((*state)->dst.state == TCPS_SYN_SENT &&
4183 (*state)->src.state == TCPS_SYN_SENT) {
4184 /* Send RST for state mismatches during handshake */
4185 if (!(th->th_flags & TH_RST))
4186 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4187 pd->dst, pd->src, th->th_dport,
4188 th->th_sport, ntohl(th->th_ack), 0,
4190 (*state)->rule.ptr->return_ttl, 1, 0,
4195 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4196 printf("pf: BAD state: ");
4197 pf_print_state(*state);
4198 pf_print_flags(th->th_flags);
4199 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4200 "pkts=%llu:%llu dir=%s,%s\n",
4201 seq, orig_seq, ack, pd->p_len, ackskew,
4202 (unsigned long long)(*state)->packets[0],
4203 (unsigned long long)(*state)->packets[1],
4204 pd->dir == PF_IN ? "in" : "out",
4205 pd->dir == (*state)->direction ? "fwd" : "rev");
4206 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4207 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4208 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4210 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4211 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4212 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4213 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4215 REASON_SET(reason, PFRES_BADSTATE);
4223 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4224 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4226 struct tcphdr *th = pd->hdr.tcp;
4228 if (th->th_flags & TH_SYN)
4229 if (src->state < TCPS_SYN_SENT)
4230 src->state = TCPS_SYN_SENT;
4231 if (th->th_flags & TH_FIN)
4232 if (src->state < TCPS_CLOSING)
4233 src->state = TCPS_CLOSING;
4234 if (th->th_flags & TH_ACK) {
4235 if (dst->state == TCPS_SYN_SENT) {
4236 dst->state = TCPS_ESTABLISHED;
4237 if (src->state == TCPS_ESTABLISHED &&
4238 (*state)->src_node != NULL &&
4239 pf_src_connlimit(state)) {
4240 REASON_SET(reason, PFRES_SRCLIMIT);
4243 } else if (dst->state == TCPS_CLOSING) {
4244 dst->state = TCPS_FIN_WAIT_2;
4245 } else if (src->state == TCPS_SYN_SENT &&
4246 dst->state < TCPS_SYN_SENT) {
4248 * Handle a special sloppy case where we only see one
4249 * half of the connection. If there is a ACK after
4250 * the initial SYN without ever seeing a packet from
4251 * the destination, set the connection to established.
4253 dst->state = src->state = TCPS_ESTABLISHED;
4254 if ((*state)->src_node != NULL &&
4255 pf_src_connlimit(state)) {
4256 REASON_SET(reason, PFRES_SRCLIMIT);
4259 } else if (src->state == TCPS_CLOSING &&
4260 dst->state == TCPS_ESTABLISHED &&
4263 * Handle the closing of half connections where we
4264 * don't see the full bidirectional FIN/ACK+ACK
4267 dst->state = TCPS_CLOSING;
4270 if (th->th_flags & TH_RST)
4271 src->state = dst->state = TCPS_TIME_WAIT;
4273 /* update expire time */
4274 (*state)->expire = time_uptime;
4275 if (src->state >= TCPS_FIN_WAIT_2 &&
4276 dst->state >= TCPS_FIN_WAIT_2)
4277 (*state)->timeout = PFTM_TCP_CLOSED;
4278 else if (src->state >= TCPS_CLOSING &&
4279 dst->state >= TCPS_CLOSING)
4280 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4281 else if (src->state < TCPS_ESTABLISHED ||
4282 dst->state < TCPS_ESTABLISHED)
4283 (*state)->timeout = PFTM_TCP_OPENING;
4284 else if (src->state >= TCPS_CLOSING ||
4285 dst->state >= TCPS_CLOSING)
4286 (*state)->timeout = PFTM_TCP_CLOSING;
4288 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4294 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4295 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4298 struct pf_state_key_cmp key;
4299 struct tcphdr *th = pd->hdr.tcp;
4301 struct pf_state_peer *src, *dst;
4302 struct pf_state_key *sk;
4304 bzero(&key, sizeof(key));
4306 key.proto = IPPROTO_TCP;
4307 if (direction == PF_IN) { /* wire side, straight */
4308 PF_ACPY(&key.addr[0], pd->src, key.af);
4309 PF_ACPY(&key.addr[1], pd->dst, key.af);
4310 key.port[0] = th->th_sport;
4311 key.port[1] = th->th_dport;
4312 } else { /* stack side, reverse */
4313 PF_ACPY(&key.addr[1], pd->src, key.af);
4314 PF_ACPY(&key.addr[0], pd->dst, key.af);
4315 key.port[1] = th->th_sport;
4316 key.port[0] = th->th_dport;
4319 STATE_LOOKUP(kif, &key, direction, *state, pd);
4321 if (direction == (*state)->direction) {
4322 src = &(*state)->src;
4323 dst = &(*state)->dst;
4325 src = &(*state)->dst;
4326 dst = &(*state)->src;
4329 sk = (*state)->key[pd->didx];
4331 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4332 if (direction != (*state)->direction) {
4333 REASON_SET(reason, PFRES_SYNPROXY);
4334 return (PF_SYNPROXY_DROP);
4336 if (th->th_flags & TH_SYN) {
4337 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4338 REASON_SET(reason, PFRES_SYNPROXY);
4341 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4342 pd->src, th->th_dport, th->th_sport,
4343 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4344 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4345 REASON_SET(reason, PFRES_SYNPROXY);
4346 return (PF_SYNPROXY_DROP);
4347 } else if (!(th->th_flags & TH_ACK) ||
4348 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4349 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4350 REASON_SET(reason, PFRES_SYNPROXY);
4352 } else if ((*state)->src_node != NULL &&
4353 pf_src_connlimit(state)) {
4354 REASON_SET(reason, PFRES_SRCLIMIT);
4357 (*state)->src.state = PF_TCPS_PROXY_DST;
4359 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4360 if (direction == (*state)->direction) {
4361 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4362 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4363 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4364 REASON_SET(reason, PFRES_SYNPROXY);
4367 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4368 if ((*state)->dst.seqhi == 1)
4369 (*state)->dst.seqhi = htonl(arc4random());
4370 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4371 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4372 sk->port[pd->sidx], sk->port[pd->didx],
4373 (*state)->dst.seqhi, 0, TH_SYN, 0,
4374 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4375 REASON_SET(reason, PFRES_SYNPROXY);
4376 return (PF_SYNPROXY_DROP);
4377 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4379 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4380 REASON_SET(reason, PFRES_SYNPROXY);
4383 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4384 (*state)->dst.seqlo = ntohl(th->th_seq);
4385 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4386 pd->src, th->th_dport, th->th_sport,
4387 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4388 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4389 (*state)->tag, NULL);
4390 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4391 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4392 sk->port[pd->sidx], sk->port[pd->didx],
4393 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4394 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4395 (*state)->src.seqdiff = (*state)->dst.seqhi -
4396 (*state)->src.seqlo;
4397 (*state)->dst.seqdiff = (*state)->src.seqhi -
4398 (*state)->dst.seqlo;
4399 (*state)->src.seqhi = (*state)->src.seqlo +
4400 (*state)->dst.max_win;
4401 (*state)->dst.seqhi = (*state)->dst.seqlo +
4402 (*state)->src.max_win;
4403 (*state)->src.wscale = (*state)->dst.wscale = 0;
4404 (*state)->src.state = (*state)->dst.state =
4406 REASON_SET(reason, PFRES_SYNPROXY);
4407 return (PF_SYNPROXY_DROP);
4411 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4412 dst->state >= TCPS_FIN_WAIT_2 &&
4413 src->state >= TCPS_FIN_WAIT_2) {
4414 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4415 printf("pf: state reuse ");
4416 pf_print_state(*state);
4417 pf_print_flags(th->th_flags);
4420 /* XXX make sure it's the same direction ?? */
4421 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4422 pf_unlink_state(*state, PF_ENTER_LOCKED);
4427 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4428 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4431 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4432 ©back) == PF_DROP)
4436 /* translate source/destination address, if necessary */
4437 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4438 struct pf_state_key *nk = (*state)->key[pd->didx];
4440 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4441 nk->port[pd->sidx] != th->th_sport)
4442 pf_change_ap(m, pd->src, &th->th_sport,
4443 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4444 nk->port[pd->sidx], 0, pd->af);
4446 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4447 nk->port[pd->didx] != th->th_dport)
4448 pf_change_ap(m, pd->dst, &th->th_dport,
4449 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4450 nk->port[pd->didx], 0, pd->af);
4454 /* Copyback sequence modulation or stateful scrub changes if needed */
4456 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4462 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4463 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4465 struct pf_state_peer *src, *dst;
4466 struct pf_state_key_cmp key;
4467 struct udphdr *uh = pd->hdr.udp;
4469 bzero(&key, sizeof(key));
4471 key.proto = IPPROTO_UDP;
4472 if (direction == PF_IN) { /* wire side, straight */
4473 PF_ACPY(&key.addr[0], pd->src, key.af);
4474 PF_ACPY(&key.addr[1], pd->dst, key.af);
4475 key.port[0] = uh->uh_sport;
4476 key.port[1] = uh->uh_dport;
4477 } else { /* stack side, reverse */
4478 PF_ACPY(&key.addr[1], pd->src, key.af);
4479 PF_ACPY(&key.addr[0], pd->dst, key.af);
4480 key.port[1] = uh->uh_sport;
4481 key.port[0] = uh->uh_dport;
4484 STATE_LOOKUP(kif, &key, direction, *state, pd);
4486 if (direction == (*state)->direction) {
4487 src = &(*state)->src;
4488 dst = &(*state)->dst;
4490 src = &(*state)->dst;
4491 dst = &(*state)->src;
4495 if (src->state < PFUDPS_SINGLE)
4496 src->state = PFUDPS_SINGLE;
4497 if (dst->state == PFUDPS_SINGLE)
4498 dst->state = PFUDPS_MULTIPLE;
4500 /* update expire time */
4501 (*state)->expire = time_uptime;
4502 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4503 (*state)->timeout = PFTM_UDP_MULTIPLE;
4505 (*state)->timeout = PFTM_UDP_SINGLE;
4507 /* translate source/destination address, if necessary */
4508 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4509 struct pf_state_key *nk = (*state)->key[pd->didx];
4511 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4512 nk->port[pd->sidx] != uh->uh_sport)
4513 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4514 &uh->uh_sum, &nk->addr[pd->sidx],
4515 nk->port[pd->sidx], 1, pd->af);
4517 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4518 nk->port[pd->didx] != uh->uh_dport)
4519 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4520 &uh->uh_sum, &nk->addr[pd->didx],
4521 nk->port[pd->didx], 1, pd->af);
4522 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4529 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4530 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4532 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4533 u_int16_t icmpid = 0, *icmpsum;
4536 struct pf_state_key_cmp key;
4538 bzero(&key, sizeof(key));
4539 switch (pd->proto) {
4542 icmptype = pd->hdr.icmp->icmp_type;
4543 icmpid = pd->hdr.icmp->icmp_id;
4544 icmpsum = &pd->hdr.icmp->icmp_cksum;
4546 if (icmptype == ICMP_UNREACH ||
4547 icmptype == ICMP_SOURCEQUENCH ||
4548 icmptype == ICMP_REDIRECT ||
4549 icmptype == ICMP_TIMXCEED ||
4550 icmptype == ICMP_PARAMPROB)
4555 case IPPROTO_ICMPV6:
4556 icmptype = pd->hdr.icmp6->icmp6_type;
4557 icmpid = pd->hdr.icmp6->icmp6_id;
4558 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4560 if (icmptype == ICMP6_DST_UNREACH ||
4561 icmptype == ICMP6_PACKET_TOO_BIG ||
4562 icmptype == ICMP6_TIME_EXCEEDED ||
4563 icmptype == ICMP6_PARAM_PROB)
4572 * ICMP query/reply message not related to a TCP/UDP packet.
4573 * Search for an ICMP state.
4576 key.proto = pd->proto;
4577 key.port[0] = key.port[1] = icmpid;
4578 if (direction == PF_IN) { /* wire side, straight */
4579 PF_ACPY(&key.addr[0], pd->src, key.af);
4580 PF_ACPY(&key.addr[1], pd->dst, key.af);
4581 } else { /* stack side, reverse */
4582 PF_ACPY(&key.addr[1], pd->src, key.af);
4583 PF_ACPY(&key.addr[0], pd->dst, key.af);
4586 STATE_LOOKUP(kif, &key, direction, *state, pd);
4588 (*state)->expire = time_uptime;
4589 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4591 /* translate source/destination address, if necessary */
4592 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4593 struct pf_state_key *nk = (*state)->key[pd->didx];
4598 if (PF_ANEQ(pd->src,
4599 &nk->addr[pd->sidx], AF_INET))
4600 pf_change_a(&saddr->v4.s_addr,
4602 nk->addr[pd->sidx].v4.s_addr, 0);
4604 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4606 pf_change_a(&daddr->v4.s_addr,
4608 nk->addr[pd->didx].v4.s_addr, 0);
4611 pd->hdr.icmp->icmp_id) {
4612 pd->hdr.icmp->icmp_cksum =
4614 pd->hdr.icmp->icmp_cksum, icmpid,
4615 nk->port[pd->sidx], 0);
4616 pd->hdr.icmp->icmp_id =
4620 m_copyback(m, off, ICMP_MINLEN,
4621 (caddr_t )pd->hdr.icmp);
4626 if (PF_ANEQ(pd->src,
4627 &nk->addr[pd->sidx], AF_INET6))
4629 &pd->hdr.icmp6->icmp6_cksum,
4630 &nk->addr[pd->sidx], 0);
4632 if (PF_ANEQ(pd->dst,
4633 &nk->addr[pd->didx], AF_INET6))
4635 &pd->hdr.icmp6->icmp6_cksum,
4636 &nk->addr[pd->didx], 0);
4638 m_copyback(m, off, sizeof(struct icmp6_hdr),
4639 (caddr_t )pd->hdr.icmp6);
4648 * ICMP error message in response to a TCP/UDP packet.
4649 * Extract the inner TCP/UDP header and search for that state.
4652 struct pf_pdesc pd2;
4653 bzero(&pd2, sizeof pd2);
4658 struct ip6_hdr h2_6;
4665 /* Payload packet is from the opposite direction. */
4666 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4667 pd2.didx = (direction == PF_IN) ? 0 : 1;
4671 /* offset of h2 in mbuf chain */
4672 ipoff2 = off + ICMP_MINLEN;
4674 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4675 NULL, reason, pd2.af)) {
4676 DPFPRINTF(PF_DEBUG_MISC,
4677 ("pf: ICMP error message too short "
4682 * ICMP error messages don't refer to non-first
4685 if (h2.ip_off & htons(IP_OFFMASK)) {
4686 REASON_SET(reason, PFRES_FRAG);
4690 /* offset of protocol header that follows h2 */
4691 off2 = ipoff2 + (h2.ip_hl << 2);
4693 pd2.proto = h2.ip_p;
4694 pd2.src = (struct pf_addr *)&h2.ip_src;
4695 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4696 pd2.ip_sum = &h2.ip_sum;
4701 ipoff2 = off + sizeof(struct icmp6_hdr);
4703 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4704 NULL, reason, pd2.af)) {
4705 DPFPRINTF(PF_DEBUG_MISC,
4706 ("pf: ICMP error message too short "
4710 pd2.proto = h2_6.ip6_nxt;
4711 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4712 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4714 off2 = ipoff2 + sizeof(h2_6);
4716 switch (pd2.proto) {
4717 case IPPROTO_FRAGMENT:
4719 * ICMPv6 error messages for
4720 * non-first fragments
4722 REASON_SET(reason, PFRES_FRAG);
4725 case IPPROTO_HOPOPTS:
4726 case IPPROTO_ROUTING:
4727 case IPPROTO_DSTOPTS: {
4728 /* get next header and header length */
4729 struct ip6_ext opt6;
4731 if (!pf_pull_hdr(m, off2, &opt6,
4732 sizeof(opt6), NULL, reason,
4734 DPFPRINTF(PF_DEBUG_MISC,
4735 ("pf: ICMPv6 short opt\n"));
4738 if (pd2.proto == IPPROTO_AH)
4739 off2 += (opt6.ip6e_len + 2) * 4;
4741 off2 += (opt6.ip6e_len + 1) * 8;
4742 pd2.proto = opt6.ip6e_nxt;
4743 /* goto the next header */
4750 } while (!terminal);
4755 switch (pd2.proto) {
4759 struct pf_state_peer *src, *dst;
4764 * Only the first 8 bytes of the TCP header can be
4765 * expected. Don't access any TCP header fields after
4766 * th_seq, an ackskew test is not possible.
4768 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4770 DPFPRINTF(PF_DEBUG_MISC,
4771 ("pf: ICMP error message too short "
4777 key.proto = IPPROTO_TCP;
4778 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4779 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4780 key.port[pd2.sidx] = th.th_sport;
4781 key.port[pd2.didx] = th.th_dport;
4783 STATE_LOOKUP(kif, &key, direction, *state, pd);
4785 if (direction == (*state)->direction) {
4786 src = &(*state)->dst;
4787 dst = &(*state)->src;
4789 src = &(*state)->src;
4790 dst = &(*state)->dst;
4793 if (src->wscale && dst->wscale)
4794 dws = dst->wscale & PF_WSCALE_MASK;
4798 /* Demodulate sequence number */
4799 seq = ntohl(th.th_seq) - src->seqdiff;
4801 pf_change_a(&th.th_seq, icmpsum,
4806 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4807 (!SEQ_GEQ(src->seqhi, seq) ||
4808 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4809 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4810 printf("pf: BAD ICMP %d:%d ",
4811 icmptype, pd->hdr.icmp->icmp_code);
4812 pf_print_host(pd->src, 0, pd->af);
4814 pf_print_host(pd->dst, 0, pd->af);
4816 pf_print_state(*state);
4817 printf(" seq=%u\n", seq);
4819 REASON_SET(reason, PFRES_BADSTATE);
4822 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4823 printf("pf: OK ICMP %d:%d ",
4824 icmptype, pd->hdr.icmp->icmp_code);
4825 pf_print_host(pd->src, 0, pd->af);
4827 pf_print_host(pd->dst, 0, pd->af);
4829 pf_print_state(*state);
4830 printf(" seq=%u\n", seq);
4834 /* translate source/destination address, if necessary */
4835 if ((*state)->key[PF_SK_WIRE] !=
4836 (*state)->key[PF_SK_STACK]) {
4837 struct pf_state_key *nk =
4838 (*state)->key[pd->didx];
4840 if (PF_ANEQ(pd2.src,
4841 &nk->addr[pd2.sidx], pd2.af) ||
4842 nk->port[pd2.sidx] != th.th_sport)
4843 pf_change_icmp(pd2.src, &th.th_sport,
4844 daddr, &nk->addr[pd2.sidx],
4845 nk->port[pd2.sidx], NULL,
4846 pd2.ip_sum, icmpsum,
4847 pd->ip_sum, 0, pd2.af);
4849 if (PF_ANEQ(pd2.dst,
4850 &nk->addr[pd2.didx], pd2.af) ||
4851 nk->port[pd2.didx] != th.th_dport)
4852 pf_change_icmp(pd2.dst, &th.th_dport,
4853 saddr, &nk->addr[pd2.didx],
4854 nk->port[pd2.didx], NULL,
4855 pd2.ip_sum, icmpsum,
4856 pd->ip_sum, 0, pd2.af);
4864 m_copyback(m, off, ICMP_MINLEN,
4865 (caddr_t )pd->hdr.icmp);
4866 m_copyback(m, ipoff2, sizeof(h2),
4873 sizeof(struct icmp6_hdr),
4874 (caddr_t )pd->hdr.icmp6);
4875 m_copyback(m, ipoff2, sizeof(h2_6),
4880 m_copyback(m, off2, 8, (caddr_t)&th);
4889 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4890 NULL, reason, pd2.af)) {
4891 DPFPRINTF(PF_DEBUG_MISC,
4892 ("pf: ICMP error message too short "
4898 key.proto = IPPROTO_UDP;
4899 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4900 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4901 key.port[pd2.sidx] = uh.uh_sport;
4902 key.port[pd2.didx] = uh.uh_dport;
4904 STATE_LOOKUP(kif, &key, direction, *state, pd);
4906 /* translate source/destination address, if necessary */
4907 if ((*state)->key[PF_SK_WIRE] !=
4908 (*state)->key[PF_SK_STACK]) {
4909 struct pf_state_key *nk =
4910 (*state)->key[pd->didx];
4912 if (PF_ANEQ(pd2.src,
4913 &nk->addr[pd2.sidx], pd2.af) ||
4914 nk->port[pd2.sidx] != uh.uh_sport)
4915 pf_change_icmp(pd2.src, &uh.uh_sport,
4916 daddr, &nk->addr[pd2.sidx],
4917 nk->port[pd2.sidx], &uh.uh_sum,
4918 pd2.ip_sum, icmpsum,
4919 pd->ip_sum, 1, pd2.af);
4921 if (PF_ANEQ(pd2.dst,
4922 &nk->addr[pd2.didx], pd2.af) ||
4923 nk->port[pd2.didx] != uh.uh_dport)
4924 pf_change_icmp(pd2.dst, &uh.uh_dport,
4925 saddr, &nk->addr[pd2.didx],
4926 nk->port[pd2.didx], &uh.uh_sum,
4927 pd2.ip_sum, icmpsum,
4928 pd->ip_sum, 1, pd2.af);
4933 m_copyback(m, off, ICMP_MINLEN,
4934 (caddr_t )pd->hdr.icmp);
4935 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4941 sizeof(struct icmp6_hdr),
4942 (caddr_t )pd->hdr.icmp6);
4943 m_copyback(m, ipoff2, sizeof(h2_6),
4948 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4954 case IPPROTO_ICMP: {
4957 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4958 NULL, reason, pd2.af)) {
4959 DPFPRINTF(PF_DEBUG_MISC,
4960 ("pf: ICMP error message too short i"
4966 key.proto = IPPROTO_ICMP;
4967 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4968 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4969 key.port[0] = key.port[1] = iih.icmp_id;
4971 STATE_LOOKUP(kif, &key, direction, *state, pd);
4973 /* translate source/destination address, if necessary */
4974 if ((*state)->key[PF_SK_WIRE] !=
4975 (*state)->key[PF_SK_STACK]) {
4976 struct pf_state_key *nk =
4977 (*state)->key[pd->didx];
4979 if (PF_ANEQ(pd2.src,
4980 &nk->addr[pd2.sidx], pd2.af) ||
4981 nk->port[pd2.sidx] != iih.icmp_id)
4982 pf_change_icmp(pd2.src, &iih.icmp_id,
4983 daddr, &nk->addr[pd2.sidx],
4984 nk->port[pd2.sidx], NULL,
4985 pd2.ip_sum, icmpsum,
4986 pd->ip_sum, 0, AF_INET);
4988 if (PF_ANEQ(pd2.dst,
4989 &nk->addr[pd2.didx], pd2.af) ||
4990 nk->port[pd2.didx] != iih.icmp_id)
4991 pf_change_icmp(pd2.dst, &iih.icmp_id,
4992 saddr, &nk->addr[pd2.didx],
4993 nk->port[pd2.didx], NULL,
4994 pd2.ip_sum, icmpsum,
4995 pd->ip_sum, 0, AF_INET);
4997 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4998 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4999 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5006 case IPPROTO_ICMPV6: {
5007 struct icmp6_hdr iih;
5009 if (!pf_pull_hdr(m, off2, &iih,
5010 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5011 DPFPRINTF(PF_DEBUG_MISC,
5012 ("pf: ICMP error message too short "
5018 key.proto = IPPROTO_ICMPV6;
5019 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5020 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5021 key.port[0] = key.port[1] = iih.icmp6_id;
5023 STATE_LOOKUP(kif, &key, direction, *state, pd);
5025 /* translate source/destination address, if necessary */
5026 if ((*state)->key[PF_SK_WIRE] !=
5027 (*state)->key[PF_SK_STACK]) {
5028 struct pf_state_key *nk =
5029 (*state)->key[pd->didx];
5031 if (PF_ANEQ(pd2.src,
5032 &nk->addr[pd2.sidx], pd2.af) ||
5033 nk->port[pd2.sidx] != iih.icmp6_id)
5034 pf_change_icmp(pd2.src, &iih.icmp6_id,
5035 daddr, &nk->addr[pd2.sidx],
5036 nk->port[pd2.sidx], NULL,
5037 pd2.ip_sum, icmpsum,
5038 pd->ip_sum, 0, AF_INET6);
5040 if (PF_ANEQ(pd2.dst,
5041 &nk->addr[pd2.didx], pd2.af) ||
5042 nk->port[pd2.didx] != iih.icmp6_id)
5043 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5044 saddr, &nk->addr[pd2.didx],
5045 nk->port[pd2.didx], NULL,
5046 pd2.ip_sum, icmpsum,
5047 pd->ip_sum, 0, AF_INET6);
5049 m_copyback(m, off, sizeof(struct icmp6_hdr),
5050 (caddr_t)pd->hdr.icmp6);
5051 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5052 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5061 key.proto = pd2.proto;
5062 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5063 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5064 key.port[0] = key.port[1] = 0;
5066 STATE_LOOKUP(kif, &key, direction, *state, pd);
5068 /* translate source/destination address, if necessary */
5069 if ((*state)->key[PF_SK_WIRE] !=
5070 (*state)->key[PF_SK_STACK]) {
5071 struct pf_state_key *nk =
5072 (*state)->key[pd->didx];
5074 if (PF_ANEQ(pd2.src,
5075 &nk->addr[pd2.sidx], pd2.af))
5076 pf_change_icmp(pd2.src, NULL, daddr,
5077 &nk->addr[pd2.sidx], 0, NULL,
5078 pd2.ip_sum, icmpsum,
5079 pd->ip_sum, 0, pd2.af);
5081 if (PF_ANEQ(pd2.dst,
5082 &nk->addr[pd2.didx], pd2.af))
5083 pf_change_icmp(pd2.dst, NULL, saddr,
5084 &nk->addr[pd2.didx], 0, NULL,
5085 pd2.ip_sum, icmpsum,
5086 pd->ip_sum, 0, pd2.af);
5091 m_copyback(m, off, ICMP_MINLEN,
5092 (caddr_t)pd->hdr.icmp);
5093 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5099 sizeof(struct icmp6_hdr),
5100 (caddr_t )pd->hdr.icmp6);
5101 m_copyback(m, ipoff2, sizeof(h2_6),
5115 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5116 struct mbuf *m, struct pf_pdesc *pd)
5118 struct pf_state_peer *src, *dst;
5119 struct pf_state_key_cmp key;
5121 bzero(&key, sizeof(key));
5123 key.proto = pd->proto;
5124 if (direction == PF_IN) {
5125 PF_ACPY(&key.addr[0], pd->src, key.af);
5126 PF_ACPY(&key.addr[1], pd->dst, key.af);
5127 key.port[0] = key.port[1] = 0;
5129 PF_ACPY(&key.addr[1], pd->src, key.af);
5130 PF_ACPY(&key.addr[0], pd->dst, key.af);
5131 key.port[1] = key.port[0] = 0;
5134 STATE_LOOKUP(kif, &key, direction, *state, pd);
5136 if (direction == (*state)->direction) {
5137 src = &(*state)->src;
5138 dst = &(*state)->dst;
5140 src = &(*state)->dst;
5141 dst = &(*state)->src;
5145 if (src->state < PFOTHERS_SINGLE)
5146 src->state = PFOTHERS_SINGLE;
5147 if (dst->state == PFOTHERS_SINGLE)
5148 dst->state = PFOTHERS_MULTIPLE;
5150 /* update expire time */
5151 (*state)->expire = time_uptime;
5152 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5153 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5155 (*state)->timeout = PFTM_OTHER_SINGLE;
5157 /* translate source/destination address, if necessary */
5158 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5159 struct pf_state_key *nk = (*state)->key[pd->didx];
5161 KASSERT(nk, ("%s: nk is null", __func__));
5162 KASSERT(pd, ("%s: pd is null", __func__));
5163 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5164 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5168 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5169 pf_change_a(&pd->src->v4.s_addr,
5171 nk->addr[pd->sidx].v4.s_addr,
5175 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5176 pf_change_a(&pd->dst->v4.s_addr,
5178 nk->addr[pd->didx].v4.s_addr,
5185 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5186 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5188 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5189 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5197 * ipoff and off are measured from the start of the mbuf chain.
5198 * h must be at "ipoff" on the mbuf chain.
5201 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5202 u_short *actionp, u_short *reasonp, sa_family_t af)
5207 struct ip *h = mtod(m, struct ip *);
5208 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5212 ACTION_SET(actionp, PF_PASS);
5214 ACTION_SET(actionp, PF_DROP);
5215 REASON_SET(reasonp, PFRES_FRAG);
5219 if (m->m_pkthdr.len < off + len ||
5220 ntohs(h->ip_len) < off + len) {
5221 ACTION_SET(actionp, PF_DROP);
5222 REASON_SET(reasonp, PFRES_SHORT);
5230 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5232 if (m->m_pkthdr.len < off + len ||
5233 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5234 (unsigned)(off + len)) {
5235 ACTION_SET(actionp, PF_DROP);
5236 REASON_SET(reasonp, PFRES_SHORT);
5243 m_copydata(m, off, len, p);
5249 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5252 struct radix_node_head *rnh;
5253 struct sockaddr_in *dst;
5257 struct sockaddr_in6 *dst6;
5258 struct route_in6 ro;
5262 struct radix_node *rn;
5267 /* XXX: stick to table 0 for now */
5268 rnh = rt_tables_get_rnh(0, af);
5269 if (rnh != NULL && rn_mpath_capable(rnh))
5271 bzero(&ro, sizeof(ro));
5274 dst = satosin(&ro.ro_dst);
5275 dst->sin_family = AF_INET;
5276 dst->sin_len = sizeof(*dst);
5277 dst->sin_addr = addr->v4;
5282 * Skip check for addresses with embedded interface scope,
5283 * as they would always match anyway.
5285 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5287 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5288 dst6->sin6_family = AF_INET6;
5289 dst6->sin6_len = sizeof(*dst6);
5290 dst6->sin6_addr = addr->v6;
5297 /* Skip checks for ipsec interfaces */
5298 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5304 in6_rtalloc_ign(&ro, 0, rtableid);
5309 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5314 if (ro.ro_rt != NULL) {
5315 /* No interface given, this is a no-route check */
5319 if (kif->pfik_ifp == NULL) {
5324 /* Perform uRPF check if passed input interface */
5326 rn = (struct radix_node *)ro.ro_rt;
5328 rt = (struct rtentry *)rn;
5331 if (kif->pfik_ifp == ifp)
5333 rn = rn_mpath_next(rn);
5334 } while (check_mpath == 1 && rn != NULL && ret == 0);
5338 if (ro.ro_rt != NULL)
5345 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5349 struct nhop4_basic nh4;
5352 struct nhop6_basic nh6;
5356 struct radix_node_head *rnh;
5358 /* XXX: stick to table 0 for now */
5359 rnh = rt_tables_get_rnh(0, af);
5360 if (rnh != NULL && rn_mpath_capable(rnh))
5361 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5364 * Skip check for addresses with embedded interface scope,
5365 * as they would always match anyway.
5367 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5370 if (af != AF_INET && af != AF_INET6)
5373 /* Skip checks for ipsec interfaces */
5374 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5382 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5389 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5396 /* No interface given, this is a no-route check */
5400 if (kif->pfik_ifp == NULL)
5403 /* Perform uRPF check if passed input interface */
5404 if (kif->pfik_ifp == ifp)
5411 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5412 struct pf_state *s, struct pf_pdesc *pd)
5414 struct mbuf *m0, *m1;
5415 struct sockaddr_in dst;
5417 struct ifnet *ifp = NULL;
5418 struct pf_addr naddr;
5419 struct pf_src_node *sn = NULL;
5421 uint16_t ip_len, ip_off;
5423 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5424 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5427 if ((pd->pf_mtag == NULL &&
5428 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5429 pd->pf_mtag->routed++ > 3) {
5435 if (r->rt == PF_DUPTO) {
5436 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5442 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5450 ip = mtod(m0, struct ip *);
5452 bzero(&dst, sizeof(dst));
5453 dst.sin_family = AF_INET;
5454 dst.sin_len = sizeof(dst);
5455 dst.sin_addr = ip->ip_dst;
5457 if (TAILQ_EMPTY(&r->rpool.list)) {
5458 DPFPRINTF(PF_DEBUG_URGENT,
5459 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5463 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5465 if (!PF_AZERO(&naddr, AF_INET))
5466 dst.sin_addr.s_addr = naddr.v4.s_addr;
5467 ifp = r->rpool.cur->kif ?
5468 r->rpool.cur->kif->pfik_ifp : NULL;
5470 if (!PF_AZERO(&s->rt_addr, AF_INET))
5471 dst.sin_addr.s_addr =
5472 s->rt_addr.v4.s_addr;
5473 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5480 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5482 else if (m0 == NULL)
5484 if (m0->m_len < sizeof(struct ip)) {
5485 DPFPRINTF(PF_DEBUG_URGENT,
5486 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5489 ip = mtod(m0, struct ip *);
5492 if (ifp->if_flags & IFF_LOOPBACK)
5493 m0->m_flags |= M_SKIP_FIREWALL;
5495 ip_len = ntohs(ip->ip_len);
5496 ip_off = ntohs(ip->ip_off);
5498 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5499 m0->m_pkthdr.csum_flags |= CSUM_IP;
5500 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5501 in_delayed_cksum(m0);
5502 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5505 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5506 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5507 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5512 * If small enough for interface, or the interface will take
5513 * care of the fragmentation for us, we can just send directly.
5515 if (ip_len <= ifp->if_mtu ||
5516 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5518 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5519 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5520 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5522 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5523 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5527 /* Balk when DF bit is set or the interface didn't support TSO. */
5528 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5530 KMOD_IPSTAT_INC(ips_cantfrag);
5531 if (r->rt != PF_DUPTO) {
5532 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5539 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5543 for (; m0; m0 = m1) {
5545 m0->m_nextpkt = NULL;
5547 m_clrprotoflags(m0);
5548 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5554 KMOD_IPSTAT_INC(ips_fragmented);
5557 if (r->rt != PF_DUPTO)
5572 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5573 struct pf_state *s, struct pf_pdesc *pd)
5576 struct sockaddr_in6 dst;
5577 struct ip6_hdr *ip6;
5578 struct ifnet *ifp = NULL;
5579 struct pf_addr naddr;
5580 struct pf_src_node *sn = NULL;
5582 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5583 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5586 if ((pd->pf_mtag == NULL &&
5587 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5588 pd->pf_mtag->routed++ > 3) {
5594 if (r->rt == PF_DUPTO) {
5595 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5601 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5609 ip6 = mtod(m0, struct ip6_hdr *);
5611 bzero(&dst, sizeof(dst));
5612 dst.sin6_family = AF_INET6;
5613 dst.sin6_len = sizeof(dst);
5614 dst.sin6_addr = ip6->ip6_dst;
5616 if (TAILQ_EMPTY(&r->rpool.list)) {
5617 DPFPRINTF(PF_DEBUG_URGENT,
5618 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5622 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5624 if (!PF_AZERO(&naddr, AF_INET6))
5625 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5627 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5629 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5630 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5631 &s->rt_addr, AF_INET6);
5632 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5642 if (pf_test6(PF_FWD, ifp, &m0, NULL) != PF_PASS)
5644 else if (m0 == NULL)
5646 if (m0->m_len < sizeof(struct ip6_hdr)) {
5647 DPFPRINTF(PF_DEBUG_URGENT,
5648 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5652 ip6 = mtod(m0, struct ip6_hdr *);
5655 if (ifp->if_flags & IFF_LOOPBACK)
5656 m0->m_flags |= M_SKIP_FIREWALL;
5658 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5659 ~ifp->if_hwassist) {
5660 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5661 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5662 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5666 * If the packet is too large for the outgoing interface,
5667 * send back an icmp6 error.
5669 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5670 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5671 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5672 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5674 in6_ifstat_inc(ifp, ifs6_in_toobig);
5675 if (r->rt != PF_DUPTO)
5676 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5682 if (r->rt != PF_DUPTO)
5696 * FreeBSD supports cksum offloads for the following drivers.
5697 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5698 * ti(4), txp(4), xl(4)
5700 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5701 * network driver performed cksum including pseudo header, need to verify
5704 * network driver performed cksum, needs to additional pseudo header
5705 * cksum computation with partial csum_data(i.e. lack of H/W support for
5706 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5708 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5709 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5711 * Also, set csum_data to 0xffff to force cksum validation.
5714 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5720 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5722 if (m->m_pkthdr.len < off + len)
5727 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5728 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5729 sum = m->m_pkthdr.csum_data;
5731 ip = mtod(m, struct ip *);
5732 sum = in_pseudo(ip->ip_src.s_addr,
5733 ip->ip_dst.s_addr, htonl((u_short)len +
5734 m->m_pkthdr.csum_data + IPPROTO_TCP));
5741 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5742 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5743 sum = m->m_pkthdr.csum_data;
5745 ip = mtod(m, struct ip *);
5746 sum = in_pseudo(ip->ip_src.s_addr,
5747 ip->ip_dst.s_addr, htonl((u_short)len +
5748 m->m_pkthdr.csum_data + IPPROTO_UDP));
5756 case IPPROTO_ICMPV6:
5766 if (p == IPPROTO_ICMP) {
5771 sum = in_cksum(m, len);
5775 if (m->m_len < sizeof(struct ip))
5777 sum = in4_cksum(m, p, off, len);
5782 if (m->m_len < sizeof(struct ip6_hdr))
5784 sum = in6_cksum(m, p, off, len);
5795 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5800 KMOD_UDPSTAT_INC(udps_badsum);
5806 KMOD_ICMPSTAT_INC(icps_checksum);
5811 case IPPROTO_ICMPV6:
5813 KMOD_ICMP6STAT_INC(icp6s_checksum);
5820 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5821 m->m_pkthdr.csum_flags |=
5822 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5823 m->m_pkthdr.csum_data = 0xffff;
5832 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5834 struct pfi_kif *kif;
5835 u_short action, reason = 0, log = 0;
5836 struct mbuf *m = *m0;
5837 struct ip *h = NULL;
5838 struct m_tag *ipfwtag;
5839 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5840 struct pf_state *s = NULL;
5841 struct pf_ruleset *ruleset = NULL;
5843 int off, dirndx, pqid = 0;
5847 if (!V_pf_status.running)
5850 memset(&pd, 0, sizeof(pd));
5852 kif = (struct pfi_kif *)ifp->if_pf_kif;
5855 DPFPRINTF(PF_DEBUG_URGENT,
5856 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5859 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5862 if (m->m_flags & M_SKIP_FIREWALL)
5865 pd.pf_mtag = pf_find_mtag(m);
5869 if (ip_divert_ptr != NULL &&
5870 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5871 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5872 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5873 if (pd.pf_mtag == NULL &&
5874 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5878 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5879 m_tag_delete(m, ipfwtag);
5881 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5882 m->m_flags |= M_FASTFWD_OURS;
5883 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5885 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5886 /* We do IP header normalization and packet reassembly here */
5890 m = *m0; /* pf_normalize messes with m0 */
5891 h = mtod(m, struct ip *);
5893 off = h->ip_hl << 2;
5894 if (off < (int)sizeof(struct ip)) {
5896 REASON_SET(&reason, PFRES_SHORT);
5901 pd.src = (struct pf_addr *)&h->ip_src;
5902 pd.dst = (struct pf_addr *)&h->ip_dst;
5903 pd.sport = pd.dport = NULL;
5904 pd.ip_sum = &h->ip_sum;
5905 pd.proto_sum = NULL;
5908 pd.sidx = (dir == PF_IN) ? 0 : 1;
5909 pd.didx = (dir == PF_IN) ? 1 : 0;
5911 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5912 pd.tot_len = ntohs(h->ip_len);
5914 /* handle fragments that didn't get reassembled by normalization */
5915 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5916 action = pf_test_fragment(&r, dir, kif, m, h,
5927 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5928 &action, &reason, AF_INET)) {
5929 log = action != PF_PASS;
5932 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5933 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5935 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5936 if (action == PF_DROP)
5938 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5940 if (action == PF_PASS) {
5941 if (pfsync_update_state_ptr != NULL)
5942 pfsync_update_state_ptr(s);
5946 } else if (s == NULL)
5947 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5956 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5957 &action, &reason, AF_INET)) {
5958 log = action != PF_PASS;
5961 if (uh.uh_dport == 0 ||
5962 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5963 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5965 REASON_SET(&reason, PFRES_SHORT);
5968 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5969 if (action == PF_PASS) {
5970 if (pfsync_update_state_ptr != NULL)
5971 pfsync_update_state_ptr(s);
5975 } else if (s == NULL)
5976 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5981 case IPPROTO_ICMP: {
5985 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5986 &action, &reason, AF_INET)) {
5987 log = action != PF_PASS;
5990 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5992 if (action == PF_PASS) {
5993 if (pfsync_update_state_ptr != NULL)
5994 pfsync_update_state_ptr(s);
5998 } else if (s == NULL)
5999 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6005 case IPPROTO_ICMPV6: {
6007 DPFPRINTF(PF_DEBUG_MISC,
6008 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6014 action = pf_test_state_other(&s, dir, kif, m, &pd);
6015 if (action == PF_PASS) {
6016 if (pfsync_update_state_ptr != NULL)
6017 pfsync_update_state_ptr(s);
6021 } else if (s == NULL)
6022 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6029 if (action == PF_PASS && h->ip_hl > 5 &&
6030 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6032 REASON_SET(&reason, PFRES_IPOPTIONS);
6034 DPFPRINTF(PF_DEBUG_MISC,
6035 ("pf: dropping packet with ip options\n"));
6038 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6040 REASON_SET(&reason, PFRES_MEMORY);
6042 if (r->rtableid >= 0)
6043 M_SETFIB(m, r->rtableid);
6045 if (r->scrub_flags & PFSTATE_SETPRIO) {
6046 if (pd.tos & IPTOS_LOWDELAY)
6048 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6050 REASON_SET(&reason, PFRES_MEMORY);
6052 DPFPRINTF(PF_DEBUG_MISC,
6053 ("pf: failed to allocate 802.1q mtag\n"));
6058 if (action == PF_PASS && r->qid) {
6059 if (pd.pf_mtag == NULL &&
6060 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6062 REASON_SET(&reason, PFRES_MEMORY);
6065 pd.pf_mtag->qid_hash = pf_state_hash(s);
6066 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6067 pd.pf_mtag->qid = r->pqid;
6069 pd.pf_mtag->qid = r->qid;
6070 /* Add hints for ecn. */
6071 pd.pf_mtag->hdr = h;
6078 * connections redirected to loopback should not match sockets
6079 * bound specifically to loopback due to security implications,
6080 * see tcp_input() and in_pcblookup_listen().
6082 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6083 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6084 (s->nat_rule.ptr->action == PF_RDR ||
6085 s->nat_rule.ptr->action == PF_BINAT) &&
6086 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6087 m->m_flags |= M_SKIP_FIREWALL;
6089 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6090 !PACKET_LOOPED(&pd)) {
6092 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6093 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6094 if (ipfwtag != NULL) {
6095 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6096 ntohs(r->divert.port);
6097 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6102 m_tag_prepend(m, ipfwtag);
6103 if (m->m_flags & M_FASTFWD_OURS) {
6104 if (pd.pf_mtag == NULL &&
6105 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6107 REASON_SET(&reason, PFRES_MEMORY);
6109 DPFPRINTF(PF_DEBUG_MISC,
6110 ("pf: failed to allocate tag\n"));
6112 pd.pf_mtag->flags |=
6113 PF_FASTFWD_OURS_PRESENT;
6114 m->m_flags &= ~M_FASTFWD_OURS;
6117 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6122 /* XXX: ipfw has the same behaviour! */
6124 REASON_SET(&reason, PFRES_MEMORY);
6126 DPFPRINTF(PF_DEBUG_MISC,
6127 ("pf: failed to allocate divert tag\n"));
6134 if (s != NULL && s->nat_rule.ptr != NULL &&
6135 s->nat_rule.ptr->log & PF_LOG_ALL)
6136 lr = s->nat_rule.ptr;
6139 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6143 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6144 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6146 if (action == PF_PASS || r->action == PF_DROP) {
6147 dirndx = (dir == PF_OUT);
6148 r->packets[dirndx]++;
6149 r->bytes[dirndx] += pd.tot_len;
6151 a->packets[dirndx]++;
6152 a->bytes[dirndx] += pd.tot_len;
6155 if (s->nat_rule.ptr != NULL) {
6156 s->nat_rule.ptr->packets[dirndx]++;
6157 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6159 if (s->src_node != NULL) {
6160 s->src_node->packets[dirndx]++;
6161 s->src_node->bytes[dirndx] += pd.tot_len;
6163 if (s->nat_src_node != NULL) {
6164 s->nat_src_node->packets[dirndx]++;
6165 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6167 dirndx = (dir == s->direction) ? 0 : 1;
6168 s->packets[dirndx]++;
6169 s->bytes[dirndx] += pd.tot_len;
6172 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6173 if (nr != NULL && r == &V_pf_default_rule)
6175 if (tr->src.addr.type == PF_ADDR_TABLE)
6176 pfr_update_stats(tr->src.addr.p.tbl,
6177 (s == NULL) ? pd.src :
6178 &s->key[(s->direction == PF_IN)]->
6179 addr[(s->direction == PF_OUT)],
6180 pd.af, pd.tot_len, dir == PF_OUT,
6181 r->action == PF_PASS, tr->src.neg);
6182 if (tr->dst.addr.type == PF_ADDR_TABLE)
6183 pfr_update_stats(tr->dst.addr.p.tbl,
6184 (s == NULL) ? pd.dst :
6185 &s->key[(s->direction == PF_IN)]->
6186 addr[(s->direction == PF_IN)],
6187 pd.af, pd.tot_len, dir == PF_OUT,
6188 r->action == PF_PASS, tr->dst.neg);
6192 case PF_SYNPROXY_DROP:
6203 /* pf_route() returns unlocked. */
6205 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6219 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6221 struct pfi_kif *kif;
6222 u_short action, reason = 0, log = 0;
6223 struct mbuf *m = *m0, *n = NULL;
6225 struct ip6_hdr *h = NULL;
6226 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6227 struct pf_state *s = NULL;
6228 struct pf_ruleset *ruleset = NULL;
6230 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6235 /* Detect packet forwarding.
6236 * If the input interface is different from the output interface we're
6238 * We do need to be careful about bridges. If the
6239 * net.link.bridge.pfil_bridge sysctl is set we can be filtering on a
6240 * bridge, so if the input interface is a bridge member and the output
6241 * interface is its bridge or a member of the same bridge we're not
6242 * actually forwarding but bridging.
6244 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif &&
6245 (m->m_pkthdr.rcvif->if_bridge == NULL ||
6246 (m->m_pkthdr.rcvif->if_bridge != ifp->if_softc &&
6247 m->m_pkthdr.rcvif->if_bridge != ifp->if_bridge)))
6253 if (!V_pf_status.running)
6256 memset(&pd, 0, sizeof(pd));
6257 pd.pf_mtag = pf_find_mtag(m);
6259 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6262 kif = (struct pfi_kif *)ifp->if_pf_kif;
6264 DPFPRINTF(PF_DEBUG_URGENT,
6265 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6268 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6271 if (m->m_flags & M_SKIP_FIREWALL)
6276 /* We do IP header normalization and packet reassembly here */
6277 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6281 m = *m0; /* pf_normalize messes with m0 */
6282 h = mtod(m, struct ip6_hdr *);
6286 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6287 * will do something bad, so drop the packet for now.
6289 if (htons(h->ip6_plen) == 0) {
6291 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6296 pd.src = (struct pf_addr *)&h->ip6_src;
6297 pd.dst = (struct pf_addr *)&h->ip6_dst;
6298 pd.sport = pd.dport = NULL;
6300 pd.proto_sum = NULL;
6302 pd.sidx = (dir == PF_IN) ? 0 : 1;
6303 pd.didx = (dir == PF_IN) ? 1 : 0;
6306 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6308 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6309 pd.proto = h->ip6_nxt;
6312 case IPPROTO_FRAGMENT:
6313 action = pf_test_fragment(&r, dir, kif, m, h,
6315 if (action == PF_DROP)
6316 REASON_SET(&reason, PFRES_FRAG);
6318 case IPPROTO_ROUTING: {
6319 struct ip6_rthdr rthdr;
6322 DPFPRINTF(PF_DEBUG_MISC,
6323 ("pf: IPv6 more than one rthdr\n"));
6325 REASON_SET(&reason, PFRES_IPOPTIONS);
6329 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6331 DPFPRINTF(PF_DEBUG_MISC,
6332 ("pf: IPv6 short rthdr\n"));
6334 REASON_SET(&reason, PFRES_SHORT);
6338 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6339 DPFPRINTF(PF_DEBUG_MISC,
6340 ("pf: IPv6 rthdr0\n"));
6342 REASON_SET(&reason, PFRES_IPOPTIONS);
6349 case IPPROTO_HOPOPTS:
6350 case IPPROTO_DSTOPTS: {
6351 /* get next header and header length */
6352 struct ip6_ext opt6;
6354 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6355 NULL, &reason, pd.af)) {
6356 DPFPRINTF(PF_DEBUG_MISC,
6357 ("pf: IPv6 short opt\n"));
6362 if (pd.proto == IPPROTO_AH)
6363 off += (opt6.ip6e_len + 2) * 4;
6365 off += (opt6.ip6e_len + 1) * 8;
6366 pd.proto = opt6.ip6e_nxt;
6367 /* goto the next header */
6374 } while (!terminal);
6376 /* if there's no routing header, use unmodified mbuf for checksumming */
6386 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6387 &action, &reason, AF_INET6)) {
6388 log = action != PF_PASS;
6391 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6392 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6393 if (action == PF_DROP)
6395 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6397 if (action == PF_PASS) {
6398 if (pfsync_update_state_ptr != NULL)
6399 pfsync_update_state_ptr(s);
6403 } else if (s == NULL)
6404 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6413 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6414 &action, &reason, AF_INET6)) {
6415 log = action != PF_PASS;
6418 if (uh.uh_dport == 0 ||
6419 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6420 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6422 REASON_SET(&reason, PFRES_SHORT);
6425 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6426 if (action == PF_PASS) {
6427 if (pfsync_update_state_ptr != NULL)
6428 pfsync_update_state_ptr(s);
6432 } else if (s == NULL)
6433 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6438 case IPPROTO_ICMP: {
6440 DPFPRINTF(PF_DEBUG_MISC,
6441 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6445 case IPPROTO_ICMPV6: {
6446 struct icmp6_hdr ih;
6449 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6450 &action, &reason, AF_INET6)) {
6451 log = action != PF_PASS;
6454 action = pf_test_state_icmp(&s, dir, kif,
6455 m, off, h, &pd, &reason);
6456 if (action == PF_PASS) {
6457 if (pfsync_update_state_ptr != NULL)
6458 pfsync_update_state_ptr(s);
6462 } else if (s == NULL)
6463 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6469 action = pf_test_state_other(&s, dir, kif, m, &pd);
6470 if (action == PF_PASS) {
6471 if (pfsync_update_state_ptr != NULL)
6472 pfsync_update_state_ptr(s);
6476 } else if (s == NULL)
6477 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6489 /* handle dangerous IPv6 extension headers. */
6490 if (action == PF_PASS && rh_cnt &&
6491 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6493 REASON_SET(&reason, PFRES_IPOPTIONS);
6495 DPFPRINTF(PF_DEBUG_MISC,
6496 ("pf: dropping packet with dangerous v6 headers\n"));
6499 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6501 REASON_SET(&reason, PFRES_MEMORY);
6503 if (r->rtableid >= 0)
6504 M_SETFIB(m, r->rtableid);
6506 if (r->scrub_flags & PFSTATE_SETPRIO) {
6507 if (pd.tos & IPTOS_LOWDELAY)
6509 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6511 REASON_SET(&reason, PFRES_MEMORY);
6513 DPFPRINTF(PF_DEBUG_MISC,
6514 ("pf: failed to allocate 802.1q mtag\n"));
6519 if (action == PF_PASS && r->qid) {
6520 if (pd.pf_mtag == NULL &&
6521 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6523 REASON_SET(&reason, PFRES_MEMORY);
6526 pd.pf_mtag->qid_hash = pf_state_hash(s);
6527 if (pd.tos & IPTOS_LOWDELAY)
6528 pd.pf_mtag->qid = r->pqid;
6530 pd.pf_mtag->qid = r->qid;
6531 /* Add hints for ecn. */
6532 pd.pf_mtag->hdr = h;
6537 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6538 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6539 (s->nat_rule.ptr->action == PF_RDR ||
6540 s->nat_rule.ptr->action == PF_BINAT) &&
6541 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6542 m->m_flags |= M_SKIP_FIREWALL;
6544 /* XXX: Anybody working on it?! */
6546 printf("pf: divert(9) is not supported for IPv6\n");
6551 if (s != NULL && s->nat_rule.ptr != NULL &&
6552 s->nat_rule.ptr->log & PF_LOG_ALL)
6553 lr = s->nat_rule.ptr;
6556 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6560 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6561 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6563 if (action == PF_PASS || r->action == PF_DROP) {
6564 dirndx = (dir == PF_OUT);
6565 r->packets[dirndx]++;
6566 r->bytes[dirndx] += pd.tot_len;
6568 a->packets[dirndx]++;
6569 a->bytes[dirndx] += pd.tot_len;
6572 if (s->nat_rule.ptr != NULL) {
6573 s->nat_rule.ptr->packets[dirndx]++;
6574 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6576 if (s->src_node != NULL) {
6577 s->src_node->packets[dirndx]++;
6578 s->src_node->bytes[dirndx] += pd.tot_len;
6580 if (s->nat_src_node != NULL) {
6581 s->nat_src_node->packets[dirndx]++;
6582 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6584 dirndx = (dir == s->direction) ? 0 : 1;
6585 s->packets[dirndx]++;
6586 s->bytes[dirndx] += pd.tot_len;
6589 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6590 if (nr != NULL && r == &V_pf_default_rule)
6592 if (tr->src.addr.type == PF_ADDR_TABLE)
6593 pfr_update_stats(tr->src.addr.p.tbl,
6594 (s == NULL) ? pd.src :
6595 &s->key[(s->direction == PF_IN)]->addr[0],
6596 pd.af, pd.tot_len, dir == PF_OUT,
6597 r->action == PF_PASS, tr->src.neg);
6598 if (tr->dst.addr.type == PF_ADDR_TABLE)
6599 pfr_update_stats(tr->dst.addr.p.tbl,
6600 (s == NULL) ? pd.dst :
6601 &s->key[(s->direction == PF_IN)]->addr[1],
6602 pd.af, pd.tot_len, dir == PF_OUT,
6603 r->action == PF_PASS, tr->dst.neg);
6607 case PF_SYNPROXY_DROP:
6618 /* pf_route6() returns unlocked. */
6620 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6629 /* If reassembled packet passed, create new fragments. */
6630 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6631 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6632 action = pf_refragment6(ifp, m0, mtag);