2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2001 Daniel Hartmeier
5 * Copyright (c) 2002 - 2008 Henning Brauer
6 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * - Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * - Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials provided
18 * with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
33 * Effort sponsored in part by the Defense Advanced Research Projects
34 * Agency (DARPA) and Air Force Research Laboratory, Air Force
35 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
37 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
45 #include "opt_inet6.h"
49 #include <sys/param.h>
51 #include <sys/endian.h>
52 #include <sys/gsb_crc32.h>
54 #include <sys/interrupt.h>
55 #include <sys/kernel.h>
56 #include <sys/kthread.h>
57 #include <sys/limits.h>
60 #include <sys/random.h>
61 #include <sys/refcount.h>
62 #include <sys/socket.h>
63 #include <sys/sysctl.h>
64 #include <sys/taskqueue.h>
65 #include <sys/ucred.h>
68 #include <net/if_var.h>
69 #include <net/if_types.h>
70 #include <net/if_vlan_var.h>
71 #include <net/route.h>
72 #include <net/route/nhop.h>
76 #include <net/pfvar.h>
77 #include <net/if_pflog.h>
78 #include <net/if_pfsync.h>
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_var.h>
82 #include <netinet/in_fib.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_fw.h>
85 #include <netinet/ip_icmp.h>
86 #include <netinet/icmp_var.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/udp.h>
94 #include <netinet/udp_var.h>
97 #include <netinet/ip6.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/nd6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/in6_pcb.h>
102 #include <netinet6/in6_fib.h>
103 #include <netinet6/scope6_var.h>
106 #if defined(SCTP) || defined(SCTP_SUPPORT)
107 #include <netinet/sctp_crc32.h>
110 #include <machine/in_cksum.h>
111 #include <security/mac/mac_framework.h>
113 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
120 VNET_DEFINE(struct pf_altqqueue, pf_altqs[4]);
121 VNET_DEFINE(struct pf_palist, pf_pabuf);
122 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
123 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_active);
124 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
125 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_inactive);
126 VNET_DEFINE(struct pf_kstatus, pf_status);
128 VNET_DEFINE(u_int32_t, ticket_altqs_active);
129 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
130 VNET_DEFINE(int, altqs_inactive_open);
131 VNET_DEFINE(u_int32_t, ticket_pabuf);
133 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
134 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
135 VNET_DEFINE(u_char, pf_tcp_secret[16]);
136 #define V_pf_tcp_secret VNET(pf_tcp_secret)
137 VNET_DEFINE(int, pf_tcp_secret_init);
138 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
139 VNET_DEFINE(int, pf_tcp_iss_off);
140 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
141 VNET_DECLARE(int, pf_vnet_active);
142 #define V_pf_vnet_active VNET(pf_vnet_active)
144 VNET_DEFINE_STATIC(uint32_t, pf_purge_idx);
145 #define V_pf_purge_idx VNET(pf_purge_idx)
148 * Queue for pf_intr() sends.
150 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
151 struct pf_send_entry {
152 STAILQ_ENTRY(pf_send_entry) pfse_next;
167 STAILQ_HEAD(pf_send_head, pf_send_entry);
168 VNET_DEFINE_STATIC(struct pf_send_head, pf_sendqueue);
169 #define V_pf_sendqueue VNET(pf_sendqueue)
171 static struct mtx pf_sendqueue_mtx;
172 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
173 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
174 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
177 * Queue for pf_overload_task() tasks.
179 struct pf_overload_entry {
180 SLIST_ENTRY(pf_overload_entry) next;
184 struct pf_rule *rule;
187 SLIST_HEAD(pf_overload_head, pf_overload_entry);
188 VNET_DEFINE_STATIC(struct pf_overload_head, pf_overloadqueue);
189 #define V_pf_overloadqueue VNET(pf_overloadqueue)
190 VNET_DEFINE_STATIC(struct task, pf_overloadtask);
191 #define V_pf_overloadtask VNET(pf_overloadtask)
193 static struct mtx pf_overloadqueue_mtx;
194 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
195 "pf overload/flush queue", MTX_DEF);
196 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
197 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
199 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
200 struct mtx pf_unlnkdrules_mtx;
201 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
204 VNET_DEFINE_STATIC(uma_zone_t, pf_sources_z);
205 #define V_pf_sources_z VNET(pf_sources_z)
206 uma_zone_t pf_mtag_z;
207 VNET_DEFINE(uma_zone_t, pf_state_z);
208 VNET_DEFINE(uma_zone_t, pf_state_key_z);
210 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
211 #define PFID_CPUBITS 8
212 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
213 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
214 #define PFID_MAXID (~PFID_CPUMASK)
215 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
217 static void pf_src_tree_remove_state(struct pf_state *);
218 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
220 static void pf_add_threshold(struct pf_threshold *);
221 static int pf_check_threshold(struct pf_threshold *);
223 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
224 u_int16_t *, u_int16_t *, struct pf_addr *,
225 u_int16_t, u_int8_t, sa_family_t);
226 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
227 struct tcphdr *, struct pf_state_peer *);
228 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
229 struct pf_addr *, struct pf_addr *, u_int16_t,
230 u_int16_t *, u_int16_t *, u_int16_t *,
231 u_int16_t *, u_int8_t, sa_family_t);
232 static void pf_send_tcp(struct mbuf *,
233 const struct pf_rule *, sa_family_t,
234 const struct pf_addr *, const struct pf_addr *,
235 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
236 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
237 u_int16_t, struct ifnet *);
238 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
239 sa_family_t, struct pf_rule *);
240 static void pf_detach_state(struct pf_state *);
241 static int pf_state_key_attach(struct pf_state_key *,
242 struct pf_state_key *, struct pf_state *);
243 static void pf_state_key_detach(struct pf_state *, int);
244 static int pf_state_key_ctor(void *, int, void *, int);
245 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
246 static int pf_test_rule(struct pf_rule **, struct pf_state **,
247 int, struct pfi_kif *, struct mbuf *, int,
248 struct pf_pdesc *, struct pf_rule **,
249 struct pf_ruleset **, struct inpcb *);
250 static int pf_create_state(struct pf_rule *, struct pf_rule *,
251 struct pf_rule *, struct pf_pdesc *,
252 struct pf_src_node *, struct pf_state_key *,
253 struct pf_state_key *, struct mbuf *, int,
254 u_int16_t, u_int16_t, int *, struct pfi_kif *,
255 struct pf_state **, int, u_int16_t, u_int16_t,
257 static int pf_test_fragment(struct pf_rule **, int,
258 struct pfi_kif *, struct mbuf *, void *,
259 struct pf_pdesc *, struct pf_rule **,
260 struct pf_ruleset **);
261 static int pf_tcp_track_full(struct pf_state_peer *,
262 struct pf_state_peer *, struct pf_state **,
263 struct pfi_kif *, struct mbuf *, int,
264 struct pf_pdesc *, u_short *, int *);
265 static int pf_tcp_track_sloppy(struct pf_state_peer *,
266 struct pf_state_peer *, struct pf_state **,
267 struct pf_pdesc *, u_short *);
268 static int pf_test_state_tcp(struct pf_state **, int,
269 struct pfi_kif *, struct mbuf *, int,
270 void *, struct pf_pdesc *, u_short *);
271 static int pf_test_state_udp(struct pf_state **, int,
272 struct pfi_kif *, struct mbuf *, int,
273 void *, struct pf_pdesc *);
274 static int pf_test_state_icmp(struct pf_state **, int,
275 struct pfi_kif *, struct mbuf *, int,
276 void *, struct pf_pdesc *, u_short *);
277 static int pf_test_state_other(struct pf_state **, int,
278 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
279 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
281 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
283 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
285 static int pf_check_proto_cksum(struct mbuf *, int, int,
286 u_int8_t, sa_family_t);
287 static void pf_print_state_parts(struct pf_state *,
288 struct pf_state_key *, struct pf_state_key *);
289 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
290 struct pf_addr_wrap *);
291 static struct pf_state *pf_find_state(struct pfi_kif *,
292 struct pf_state_key_cmp *, u_int);
293 static int pf_src_connlimit(struct pf_state **);
294 static void pf_overload_task(void *v, int pending);
295 static int pf_insert_src_node(struct pf_src_node **,
296 struct pf_rule *, struct pf_addr *, sa_family_t);
297 static u_int pf_purge_expired_states(u_int, int);
298 static void pf_purge_unlinked_rules(void);
299 static int pf_mtag_uminit(void *, int, int);
300 static void pf_mtag_free(struct m_tag *);
302 static void pf_route(struct mbuf **, struct pf_rule *, int,
303 struct ifnet *, struct pf_state *,
304 struct pf_pdesc *, struct inpcb *);
307 static void pf_change_a6(struct pf_addr *, u_int16_t *,
308 struct pf_addr *, u_int8_t);
309 static void pf_route6(struct mbuf **, struct pf_rule *, int,
310 struct ifnet *, struct pf_state *,
311 struct pf_pdesc *, struct inpcb *);
314 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
316 extern int pf_end_threads;
317 extern struct proc *pf_purge_proc;
319 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
321 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
322 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
324 #define STATE_LOOKUP(i, k, d, s, pd) \
326 (s) = pf_find_state((i), (k), (d)); \
329 if (PACKET_LOOPED(pd)) \
331 if ((d) == PF_OUT && \
332 (((s)->rule.ptr->rt == PF_ROUTETO && \
333 (s)->rule.ptr->direction == PF_OUT) || \
334 ((s)->rule.ptr->rt == PF_REPLYTO && \
335 (s)->rule.ptr->direction == PF_IN)) && \
336 (s)->rt_kif != NULL && \
337 (s)->rt_kif != (i)) \
341 #define BOUND_IFACE(r, k) \
342 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
344 #define STATE_INC_COUNTERS(s) \
346 counter_u64_add(s->rule.ptr->states_cur, 1); \
347 counter_u64_add(s->rule.ptr->states_tot, 1); \
348 if (s->anchor.ptr != NULL) { \
349 counter_u64_add(s->anchor.ptr->states_cur, 1); \
350 counter_u64_add(s->anchor.ptr->states_tot, 1); \
352 if (s->nat_rule.ptr != NULL) { \
353 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
354 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
358 #define STATE_DEC_COUNTERS(s) \
360 if (s->nat_rule.ptr != NULL) \
361 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
362 if (s->anchor.ptr != NULL) \
363 counter_u64_add(s->anchor.ptr->states_cur, -1); \
364 counter_u64_add(s->rule.ptr->states_cur, -1); \
367 MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
368 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
369 VNET_DEFINE(struct pf_idhash *, pf_idhash);
370 VNET_DEFINE(struct pf_srchash *, pf_srchash);
372 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
376 u_long pf_srchashmask;
377 static u_long pf_hashsize;
378 static u_long pf_srchashsize;
379 u_long pf_ioctl_maxcount = 65535;
381 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
382 &pf_hashsize, 0, "Size of pf(4) states hashtable");
383 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
384 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
385 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RW,
386 &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
388 VNET_DEFINE(void *, pf_swi_cookie);
390 VNET_DEFINE(uint32_t, pf_hashseed);
391 #define V_pf_hashseed VNET(pf_hashseed)
394 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
400 if (a->addr32[0] > b->addr32[0])
402 if (a->addr32[0] < b->addr32[0])
408 if (a->addr32[3] > b->addr32[3])
410 if (a->addr32[3] < b->addr32[3])
412 if (a->addr32[2] > b->addr32[2])
414 if (a->addr32[2] < b->addr32[2])
416 if (a->addr32[1] > b->addr32[1])
418 if (a->addr32[1] < b->addr32[1])
420 if (a->addr32[0] > b->addr32[0])
422 if (a->addr32[0] < b->addr32[0])
427 panic("%s: unknown address family %u", __func__, af);
432 static __inline uint32_t
433 pf_hashkey(struct pf_state_key *sk)
437 h = murmur3_32_hash32((uint32_t *)sk,
438 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
441 return (h & pf_hashmask);
444 static __inline uint32_t
445 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
451 h = murmur3_32_hash32((uint32_t *)&addr->v4,
452 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
455 h = murmur3_32_hash32((uint32_t *)&addr->v6,
456 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
459 panic("%s: unknown address family %u", __func__, af);
462 return (h & pf_srchashmask);
467 pf_state_hash(struct pf_state *s)
469 u_int32_t hv = (intptr_t)s / sizeof(*s);
471 hv ^= crc32(&s->src, sizeof(s->src));
472 hv ^= crc32(&s->dst, sizeof(s->dst));
481 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
486 dst->addr32[0] = src->addr32[0];
490 dst->addr32[0] = src->addr32[0];
491 dst->addr32[1] = src->addr32[1];
492 dst->addr32[2] = src->addr32[2];
493 dst->addr32[3] = src->addr32[3];
500 pf_init_threshold(struct pf_threshold *threshold,
501 u_int32_t limit, u_int32_t seconds)
503 threshold->limit = limit * PF_THRESHOLD_MULT;
504 threshold->seconds = seconds;
505 threshold->count = 0;
506 threshold->last = time_uptime;
510 pf_add_threshold(struct pf_threshold *threshold)
512 u_int32_t t = time_uptime, diff = t - threshold->last;
514 if (diff >= threshold->seconds)
515 threshold->count = 0;
517 threshold->count -= threshold->count * diff /
519 threshold->count += PF_THRESHOLD_MULT;
524 pf_check_threshold(struct pf_threshold *threshold)
526 return (threshold->count > threshold->limit);
530 pf_src_connlimit(struct pf_state **state)
532 struct pf_overload_entry *pfoe;
535 PF_STATE_LOCK_ASSERT(*state);
537 (*state)->src_node->conn++;
538 (*state)->src.tcp_est = 1;
539 pf_add_threshold(&(*state)->src_node->conn_rate);
541 if ((*state)->rule.ptr->max_src_conn &&
542 (*state)->rule.ptr->max_src_conn <
543 (*state)->src_node->conn) {
544 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
548 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
549 pf_check_threshold(&(*state)->src_node->conn_rate)) {
550 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
557 /* Kill this state. */
558 (*state)->timeout = PFTM_PURGE;
559 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
561 if ((*state)->rule.ptr->overload_tbl == NULL)
564 /* Schedule overloading and flushing task. */
565 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
567 return (1); /* too bad :( */
569 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
570 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
571 pfoe->rule = (*state)->rule.ptr;
572 pfoe->dir = (*state)->direction;
574 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
575 PF_OVERLOADQ_UNLOCK();
576 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
582 pf_overload_task(void *v, int pending)
584 struct pf_overload_head queue;
586 struct pf_overload_entry *pfoe, *pfoe1;
589 CURVNET_SET((struct vnet *)v);
592 queue = V_pf_overloadqueue;
593 SLIST_INIT(&V_pf_overloadqueue);
594 PF_OVERLOADQ_UNLOCK();
596 bzero(&p, sizeof(p));
597 SLIST_FOREACH(pfoe, &queue, next) {
598 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
599 if (V_pf_status.debug >= PF_DEBUG_MISC) {
600 printf("%s: blocking address ", __func__);
601 pf_print_host(&pfoe->addr, 0, pfoe->af);
605 p.pfra_af = pfoe->af;
610 p.pfra_ip4addr = pfoe->addr.v4;
616 p.pfra_ip6addr = pfoe->addr.v6;
622 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
627 * Remove those entries, that don't need flushing.
629 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
630 if (pfoe->rule->flush == 0) {
631 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
632 free(pfoe, M_PFTEMP);
635 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
637 /* If nothing to flush, return. */
638 if (SLIST_EMPTY(&queue)) {
643 for (int i = 0; i <= pf_hashmask; i++) {
644 struct pf_idhash *ih = &V_pf_idhash[i];
645 struct pf_state_key *sk;
649 LIST_FOREACH(s, &ih->states, entry) {
650 sk = s->key[PF_SK_WIRE];
651 SLIST_FOREACH(pfoe, &queue, next)
652 if (sk->af == pfoe->af &&
653 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
654 pfoe->rule == s->rule.ptr) &&
655 ((pfoe->dir == PF_OUT &&
656 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
657 (pfoe->dir == PF_IN &&
658 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
659 s->timeout = PFTM_PURGE;
660 s->src.state = s->dst.state = TCPS_CLOSED;
664 PF_HASHROW_UNLOCK(ih);
666 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
667 free(pfoe, M_PFTEMP);
668 if (V_pf_status.debug >= PF_DEBUG_MISC)
669 printf("%s: %u states killed", __func__, killed);
675 * Can return locked on failure, so that we can consistently
676 * allocate and insert a new one.
679 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
682 struct pf_srchash *sh;
683 struct pf_src_node *n;
685 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
687 sh = &V_pf_srchash[pf_hashsrc(src, af)];
689 LIST_FOREACH(n, &sh->nodes, entry)
690 if (n->rule.ptr == rule && n->af == af &&
691 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
692 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
696 PF_HASHROW_UNLOCK(sh);
697 } else if (returnlocked == 0)
698 PF_HASHROW_UNLOCK(sh);
704 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
705 struct pf_addr *src, sa_family_t af)
708 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
709 rule->rpool.opts & PF_POOL_STICKYADDR),
710 ("%s for non-tracking rule %p", __func__, rule));
713 *sn = pf_find_src_node(src, rule, af, 1);
716 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
718 PF_HASHROW_ASSERT(sh);
720 if (!rule->max_src_nodes ||
721 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
722 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
724 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
727 PF_HASHROW_UNLOCK(sh);
731 pf_init_threshold(&(*sn)->conn_rate,
732 rule->max_src_conn_rate.limit,
733 rule->max_src_conn_rate.seconds);
736 (*sn)->rule.ptr = rule;
737 PF_ACPY(&(*sn)->addr, src, af);
738 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
739 (*sn)->creation = time_uptime;
740 (*sn)->ruletype = rule->action;
742 if ((*sn)->rule.ptr != NULL)
743 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
744 PF_HASHROW_UNLOCK(sh);
745 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
747 if (rule->max_src_states &&
748 (*sn)->states >= rule->max_src_states) {
749 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
758 pf_unlink_src_node(struct pf_src_node *src)
761 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
762 LIST_REMOVE(src, entry);
764 counter_u64_add(src->rule.ptr->src_nodes, -1);
768 pf_free_src_nodes(struct pf_src_node_list *head)
770 struct pf_src_node *sn, *tmp;
773 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
774 uma_zfree(V_pf_sources_z, sn);
778 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
787 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
788 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
792 /* Per-vnet data storage structures initialization. */
796 struct pf_keyhash *kh;
797 struct pf_idhash *ih;
798 struct pf_srchash *sh;
801 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
802 pf_hashsize = PF_HASHSIZ;
803 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
804 pf_srchashsize = PF_SRCHASHSIZ;
806 V_pf_hashseed = arc4random();
808 /* States and state keys storage. */
809 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
810 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
811 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
812 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
813 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
815 V_pf_state_key_z = uma_zcreate("pf state keys",
816 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
819 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
820 M_PFHASH, M_NOWAIT | M_ZERO);
821 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
822 M_PFHASH, M_NOWAIT | M_ZERO);
823 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
824 printf("pf: Unable to allocate memory for "
825 "state_hashsize %lu.\n", pf_hashsize);
827 free(V_pf_keyhash, M_PFHASH);
828 free(V_pf_idhash, M_PFHASH);
830 pf_hashsize = PF_HASHSIZ;
831 V_pf_keyhash = mallocarray(pf_hashsize,
832 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
833 V_pf_idhash = mallocarray(pf_hashsize,
834 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
837 pf_hashmask = pf_hashsize - 1;
838 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
840 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
841 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
845 V_pf_sources_z = uma_zcreate("pf source nodes",
846 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
848 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
849 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
850 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
852 V_pf_srchash = mallocarray(pf_srchashsize,
853 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
854 if (V_pf_srchash == NULL) {
855 printf("pf: Unable to allocate memory for "
856 "source_hashsize %lu.\n", pf_srchashsize);
858 pf_srchashsize = PF_SRCHASHSIZ;
859 V_pf_srchash = mallocarray(pf_srchashsize,
860 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
863 pf_srchashmask = pf_srchashsize - 1;
864 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
865 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
868 TAILQ_INIT(&V_pf_altqs[0]);
869 TAILQ_INIT(&V_pf_altqs[1]);
870 TAILQ_INIT(&V_pf_altqs[2]);
871 TAILQ_INIT(&V_pf_altqs[3]);
872 TAILQ_INIT(&V_pf_pabuf);
873 V_pf_altqs_active = &V_pf_altqs[0];
874 V_pf_altq_ifs_active = &V_pf_altqs[1];
875 V_pf_altqs_inactive = &V_pf_altqs[2];
876 V_pf_altq_ifs_inactive = &V_pf_altqs[3];
878 /* Send & overload+flush queues. */
879 STAILQ_INIT(&V_pf_sendqueue);
880 SLIST_INIT(&V_pf_overloadqueue);
881 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
883 /* Unlinked, but may be referenced rules. */
884 TAILQ_INIT(&V_pf_unlinked_rules);
891 uma_zdestroy(pf_mtag_z);
897 struct pf_keyhash *kh;
898 struct pf_idhash *ih;
899 struct pf_srchash *sh;
900 struct pf_send_entry *pfse, *next;
903 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
905 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
907 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
909 mtx_destroy(&kh->lock);
910 mtx_destroy(&ih->lock);
912 free(V_pf_keyhash, M_PFHASH);
913 free(V_pf_idhash, M_PFHASH);
915 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
916 KASSERT(LIST_EMPTY(&sh->nodes),
917 ("%s: source node hash not empty", __func__));
918 mtx_destroy(&sh->lock);
920 free(V_pf_srchash, M_PFHASH);
922 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
923 m_freem(pfse->pfse_m);
924 free(pfse, M_PFTEMP);
927 uma_zdestroy(V_pf_sources_z);
928 uma_zdestroy(V_pf_state_z);
929 uma_zdestroy(V_pf_state_key_z);
933 pf_mtag_uminit(void *mem, int size, int how)
937 t = (struct m_tag *)mem;
938 t->m_tag_cookie = MTAG_ABI_COMPAT;
939 t->m_tag_id = PACKET_TAG_PF;
940 t->m_tag_len = sizeof(struct pf_mtag);
941 t->m_tag_free = pf_mtag_free;
947 pf_mtag_free(struct m_tag *t)
950 uma_zfree(pf_mtag_z, t);
954 pf_get_mtag(struct mbuf *m)
958 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
959 return ((struct pf_mtag *)(mtag + 1));
961 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
964 bzero(mtag + 1, sizeof(struct pf_mtag));
965 m_tag_prepend(m, mtag);
967 return ((struct pf_mtag *)(mtag + 1));
971 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
974 struct pf_keyhash *khs, *khw, *kh;
975 struct pf_state_key *sk, *cur;
976 struct pf_state *si, *olds = NULL;
979 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
980 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
981 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
984 * We need to lock hash slots of both keys. To avoid deadlock
985 * we always lock the slot with lower address first. Unlock order
988 * We also need to lock ID hash slot before dropping key
989 * locks. On success we return with ID hash slot locked.
993 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
994 PF_HASHROW_LOCK(khs);
996 khs = &V_pf_keyhash[pf_hashkey(sks)];
997 khw = &V_pf_keyhash[pf_hashkey(skw)];
999 PF_HASHROW_LOCK(khs);
1000 } else if (khs < khw) {
1001 PF_HASHROW_LOCK(khs);
1002 PF_HASHROW_LOCK(khw);
1004 PF_HASHROW_LOCK(khw);
1005 PF_HASHROW_LOCK(khs);
1009 #define KEYS_UNLOCK() do { \
1011 PF_HASHROW_UNLOCK(khs); \
1012 PF_HASHROW_UNLOCK(khw); \
1014 PF_HASHROW_UNLOCK(khs); \
1018 * First run: start with wire key.
1025 LIST_FOREACH(cur, &kh->keys, entry)
1026 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1030 /* Key exists. Check for same kif, if none, add to key. */
1031 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1032 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1034 PF_HASHROW_LOCK(ih);
1035 if (si->kif == s->kif &&
1036 si->direction == s->direction) {
1037 if (sk->proto == IPPROTO_TCP &&
1038 si->src.state >= TCPS_FIN_WAIT_2 &&
1039 si->dst.state >= TCPS_FIN_WAIT_2) {
1041 * New state matches an old >FIN_WAIT_2
1042 * state. We can't drop key hash locks,
1043 * thus we can't unlink it properly.
1045 * As a workaround we drop it into
1046 * TCPS_CLOSED state, schedule purge
1047 * ASAP and push it into the very end
1048 * of the slot TAILQ, so that it won't
1049 * conflict with our new state.
1051 si->src.state = si->dst.state =
1053 si->timeout = PFTM_PURGE;
1056 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1057 printf("pf: %s key attach "
1059 (idx == PF_SK_WIRE) ?
1062 pf_print_state_parts(s,
1063 (idx == PF_SK_WIRE) ?
1065 (idx == PF_SK_STACK) ?
1067 printf(", existing: ");
1068 pf_print_state_parts(si,
1069 (idx == PF_SK_WIRE) ?
1071 (idx == PF_SK_STACK) ?
1075 PF_HASHROW_UNLOCK(ih);
1077 uma_zfree(V_pf_state_key_z, sk);
1078 if (idx == PF_SK_STACK)
1080 return (EEXIST); /* collision! */
1083 PF_HASHROW_UNLOCK(ih);
1085 uma_zfree(V_pf_state_key_z, sk);
1088 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1093 /* List is sorted, if-bound states before floating. */
1094 if (s->kif == V_pfi_all)
1095 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1097 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1100 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1101 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1107 * Attach done. See how should we (or should not?)
1108 * attach a second key.
1111 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1115 } else if (sks != NULL) {
1117 * Continue attaching with stack key.
1129 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1130 ("%s failure", __func__));
1137 pf_detach_state(struct pf_state *s)
1139 struct pf_state_key *sks = s->key[PF_SK_STACK];
1140 struct pf_keyhash *kh;
1143 kh = &V_pf_keyhash[pf_hashkey(sks)];
1144 PF_HASHROW_LOCK(kh);
1145 if (s->key[PF_SK_STACK] != NULL)
1146 pf_state_key_detach(s, PF_SK_STACK);
1148 * If both point to same key, then we are done.
1150 if (sks == s->key[PF_SK_WIRE]) {
1151 pf_state_key_detach(s, PF_SK_WIRE);
1152 PF_HASHROW_UNLOCK(kh);
1155 PF_HASHROW_UNLOCK(kh);
1158 if (s->key[PF_SK_WIRE] != NULL) {
1159 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1160 PF_HASHROW_LOCK(kh);
1161 if (s->key[PF_SK_WIRE] != NULL)
1162 pf_state_key_detach(s, PF_SK_WIRE);
1163 PF_HASHROW_UNLOCK(kh);
1168 pf_state_key_detach(struct pf_state *s, int idx)
1170 struct pf_state_key *sk = s->key[idx];
1172 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1174 PF_HASHROW_ASSERT(kh);
1176 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1179 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1180 LIST_REMOVE(sk, entry);
1181 uma_zfree(V_pf_state_key_z, sk);
1186 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1188 struct pf_state_key *sk = mem;
1190 bzero(sk, sizeof(struct pf_state_key_cmp));
1191 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1192 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1197 struct pf_state_key *
1198 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1199 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1201 struct pf_state_key *sk;
1203 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1207 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1208 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1209 sk->port[pd->sidx] = sport;
1210 sk->port[pd->didx] = dport;
1211 sk->proto = pd->proto;
1217 struct pf_state_key *
1218 pf_state_key_clone(struct pf_state_key *orig)
1220 struct pf_state_key *sk;
1222 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1226 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1232 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1233 struct pf_state_key *sks, struct pf_state *s)
1235 struct pf_idhash *ih;
1236 struct pf_state *cur;
1239 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1240 ("%s: sks not pristine", __func__));
1241 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1242 ("%s: skw not pristine", __func__));
1243 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1247 if (s->id == 0 && s->creatorid == 0) {
1248 /* XXX: should be atomic, but probability of collision low */
1249 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1250 V_pf_stateid[curcpu] = 1;
1251 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1252 s->id = htobe64(s->id);
1253 s->creatorid = V_pf_status.hostid;
1256 /* Returns with ID locked on success. */
1257 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1260 ih = &V_pf_idhash[PF_IDHASH(s)];
1261 PF_HASHROW_ASSERT(ih);
1262 LIST_FOREACH(cur, &ih->states, entry)
1263 if (cur->id == s->id && cur->creatorid == s->creatorid)
1267 PF_HASHROW_UNLOCK(ih);
1268 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1269 printf("pf: state ID collision: "
1270 "id: %016llx creatorid: %08x\n",
1271 (unsigned long long)be64toh(s->id),
1272 ntohl(s->creatorid));
1277 LIST_INSERT_HEAD(&ih->states, s, entry);
1278 /* One for keys, one for ID hash. */
1279 refcount_init(&s->refs, 2);
1281 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1282 if (V_pfsync_insert_state_ptr != NULL)
1283 V_pfsync_insert_state_ptr(s);
1285 /* Returns locked. */
1290 * Find state by ID: returns with locked row on success.
1293 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1295 struct pf_idhash *ih;
1298 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1300 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1302 PF_HASHROW_LOCK(ih);
1303 LIST_FOREACH(s, &ih->states, entry)
1304 if (s->id == id && s->creatorid == creatorid)
1308 PF_HASHROW_UNLOCK(ih);
1314 * Find state by key.
1315 * Returns with ID hash slot locked on success.
1317 static struct pf_state *
1318 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1320 struct pf_keyhash *kh;
1321 struct pf_state_key *sk;
1325 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1327 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1329 PF_HASHROW_LOCK(kh);
1330 LIST_FOREACH(sk, &kh->keys, entry)
1331 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1334 PF_HASHROW_UNLOCK(kh);
1338 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1340 /* List is sorted, if-bound states before floating ones. */
1341 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1342 if (s->kif == V_pfi_all || s->kif == kif) {
1344 PF_HASHROW_UNLOCK(kh);
1345 if (s->timeout >= PFTM_MAX) {
1347 * State is either being processed by
1348 * pf_unlink_state() in an other thread, or
1349 * is scheduled for immediate expiry.
1356 PF_HASHROW_UNLOCK(kh);
1362 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1364 struct pf_keyhash *kh;
1365 struct pf_state_key *sk;
1366 struct pf_state *s, *ret = NULL;
1369 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1371 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1373 PF_HASHROW_LOCK(kh);
1374 LIST_FOREACH(sk, &kh->keys, entry)
1375 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1378 PF_HASHROW_UNLOCK(kh);
1393 panic("%s: dir %u", __func__, dir);
1396 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1398 PF_HASHROW_UNLOCK(kh);
1412 PF_HASHROW_UNLOCK(kh);
1417 /* END state table stuff */
1420 pf_send(struct pf_send_entry *pfse)
1424 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1426 swi_sched(V_pf_swi_cookie, 0);
1432 struct epoch_tracker et;
1433 struct pf_send_head queue;
1434 struct pf_send_entry *pfse, *next;
1436 CURVNET_SET((struct vnet *)v);
1439 queue = V_pf_sendqueue;
1440 STAILQ_INIT(&V_pf_sendqueue);
1443 NET_EPOCH_ENTER(et);
1445 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1446 switch (pfse->pfse_type) {
1449 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1452 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1453 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1458 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1462 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1463 pfse->icmpopts.code, pfse->icmpopts.mtu);
1467 panic("%s: unknown type", __func__);
1469 free(pfse, M_PFTEMP);
1476 pf_purge_thread(void *unused __unused)
1478 VNET_ITERATOR_DECL(vnet_iter);
1480 sx_xlock(&pf_end_lock);
1481 while (pf_end_threads == 0) {
1482 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1485 VNET_FOREACH(vnet_iter) {
1486 CURVNET_SET(vnet_iter);
1489 /* Wait until V_pf_default_rule is initialized. */
1490 if (V_pf_vnet_active == 0) {
1496 * Process 1/interval fraction of the state
1500 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1501 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1504 * Purge other expired types every
1505 * PFTM_INTERVAL seconds.
1507 if (V_pf_purge_idx == 0) {
1509 * Order is important:
1510 * - states and src nodes reference rules
1511 * - states and rules reference kifs
1513 pf_purge_expired_fragments();
1514 pf_purge_expired_src_nodes();
1515 pf_purge_unlinked_rules();
1520 VNET_LIST_RUNLOCK();
1524 sx_xunlock(&pf_end_lock);
1529 pf_unload_vnet_purge(void)
1533 * To cleanse up all kifs and rules we need
1534 * two runs: first one clears reference flags,
1535 * then pf_purge_expired_states() doesn't
1536 * raise them, and then second run frees.
1538 pf_purge_unlinked_rules();
1542 * Now purge everything.
1544 pf_purge_expired_states(0, pf_hashmask);
1545 pf_purge_fragments(UINT_MAX);
1546 pf_purge_expired_src_nodes();
1549 * Now all kifs & rules should be unreferenced,
1550 * thus should be successfully freed.
1552 pf_purge_unlinked_rules();
1558 pf_state_expires(const struct pf_state *state)
1565 /* handle all PFTM_* > PFTM_MAX here */
1566 if (state->timeout == PFTM_PURGE)
1567 return (time_uptime);
1568 KASSERT(state->timeout != PFTM_UNLINKED,
1569 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1570 KASSERT((state->timeout < PFTM_MAX),
1571 ("pf_state_expires: timeout > PFTM_MAX"));
1572 timeout = state->rule.ptr->timeout[state->timeout];
1574 timeout = V_pf_default_rule.timeout[state->timeout];
1575 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1576 if (start && state->rule.ptr != &V_pf_default_rule) {
1577 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1578 states = counter_u64_fetch(state->rule.ptr->states_cur);
1580 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1581 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1582 states = V_pf_status.states;
1584 if (end && states > start && start < end) {
1586 timeout = (u_int64_t)timeout * (end - states) /
1588 return (state->expire + timeout);
1591 return (time_uptime);
1593 return (state->expire + timeout);
1597 pf_purge_expired_src_nodes()
1599 struct pf_src_node_list freelist;
1600 struct pf_srchash *sh;
1601 struct pf_src_node *cur, *next;
1604 LIST_INIT(&freelist);
1605 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1606 PF_HASHROW_LOCK(sh);
1607 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1608 if (cur->states == 0 && cur->expire <= time_uptime) {
1609 pf_unlink_src_node(cur);
1610 LIST_INSERT_HEAD(&freelist, cur, entry);
1611 } else if (cur->rule.ptr != NULL)
1612 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1613 PF_HASHROW_UNLOCK(sh);
1616 pf_free_src_nodes(&freelist);
1618 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1622 pf_src_tree_remove_state(struct pf_state *s)
1624 struct pf_src_node *sn;
1625 struct pf_srchash *sh;
1628 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1629 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1630 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1632 if (s->src_node != NULL) {
1634 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1635 PF_HASHROW_LOCK(sh);
1638 if (--sn->states == 0)
1639 sn->expire = time_uptime + timeout;
1640 PF_HASHROW_UNLOCK(sh);
1642 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1643 sn = s->nat_src_node;
1644 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1645 PF_HASHROW_LOCK(sh);
1646 if (--sn->states == 0)
1647 sn->expire = time_uptime + timeout;
1648 PF_HASHROW_UNLOCK(sh);
1650 s->src_node = s->nat_src_node = NULL;
1654 * Unlink and potentilly free a state. Function may be
1655 * called with ID hash row locked, but always returns
1656 * unlocked, since it needs to go through key hash locking.
1659 pf_unlink_state(struct pf_state *s, u_int flags)
1661 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1663 if ((flags & PF_ENTER_LOCKED) == 0)
1664 PF_HASHROW_LOCK(ih);
1666 PF_HASHROW_ASSERT(ih);
1668 if (s->timeout == PFTM_UNLINKED) {
1670 * State is being processed
1671 * by pf_unlink_state() in
1674 PF_HASHROW_UNLOCK(ih);
1675 return (0); /* XXXGL: undefined actually */
1678 if (s->src.state == PF_TCPS_PROXY_DST) {
1679 /* XXX wire key the right one? */
1680 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1681 &s->key[PF_SK_WIRE]->addr[1],
1682 &s->key[PF_SK_WIRE]->addr[0],
1683 s->key[PF_SK_WIRE]->port[1],
1684 s->key[PF_SK_WIRE]->port[0],
1685 s->src.seqhi, s->src.seqlo + 1,
1686 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1689 LIST_REMOVE(s, entry);
1690 pf_src_tree_remove_state(s);
1692 if (V_pfsync_delete_state_ptr != NULL)
1693 V_pfsync_delete_state_ptr(s);
1695 STATE_DEC_COUNTERS(s);
1697 s->timeout = PFTM_UNLINKED;
1699 PF_HASHROW_UNLOCK(ih);
1702 /* pf_state_insert() initialises refs to 2, so we can never release the
1703 * last reference here, only in pf_release_state(). */
1704 (void)refcount_release(&s->refs);
1706 return (pf_release_state(s));
1710 pf_free_state(struct pf_state *cur)
1713 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1714 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1717 pf_normalize_tcp_cleanup(cur);
1718 uma_zfree(V_pf_state_z, cur);
1719 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1723 * Called only from pf_purge_thread(), thus serialized.
1726 pf_purge_expired_states(u_int i, int maxcheck)
1728 struct pf_idhash *ih;
1731 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1734 * Go through hash and unlink states that expire now.
1736 while (maxcheck > 0) {
1738 ih = &V_pf_idhash[i];
1740 /* only take the lock if we expect to do work */
1741 if (!LIST_EMPTY(&ih->states)) {
1743 PF_HASHROW_LOCK(ih);
1744 LIST_FOREACH(s, &ih->states, entry) {
1745 if (pf_state_expires(s) <= time_uptime) {
1746 V_pf_status.states -=
1747 pf_unlink_state(s, PF_ENTER_LOCKED);
1750 s->rule.ptr->rule_flag |= PFRULE_REFS;
1751 if (s->nat_rule.ptr != NULL)
1752 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1753 if (s->anchor.ptr != NULL)
1754 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1755 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1757 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1759 PF_HASHROW_UNLOCK(ih);
1762 /* Return when we hit end of hash. */
1763 if (++i > pf_hashmask) {
1764 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1771 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1777 pf_purge_unlinked_rules()
1779 struct pf_rulequeue tmpq;
1780 struct pf_rule *r, *r1;
1783 * If we have overloading task pending, then we'd
1784 * better skip purging this time. There is a tiny
1785 * probability that overloading task references
1786 * an already unlinked rule.
1788 PF_OVERLOADQ_LOCK();
1789 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1790 PF_OVERLOADQ_UNLOCK();
1793 PF_OVERLOADQ_UNLOCK();
1796 * Do naive mark-and-sweep garbage collecting of old rules.
1797 * Reference flag is raised by pf_purge_expired_states()
1798 * and pf_purge_expired_src_nodes().
1800 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1801 * use a temporary queue.
1804 PF_UNLNKDRULES_LOCK();
1805 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1806 if (!(r->rule_flag & PFRULE_REFS)) {
1807 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1808 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1810 r->rule_flag &= ~PFRULE_REFS;
1812 PF_UNLNKDRULES_UNLOCK();
1814 if (!TAILQ_EMPTY(&tmpq)) {
1816 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1817 TAILQ_REMOVE(&tmpq, r, entries);
1825 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1830 u_int32_t a = ntohl(addr->addr32[0]);
1831 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1843 u_int8_t i, curstart, curend, maxstart, maxend;
1844 curstart = curend = maxstart = maxend = 255;
1845 for (i = 0; i < 8; i++) {
1846 if (!addr->addr16[i]) {
1847 if (curstart == 255)
1851 if ((curend - curstart) >
1852 (maxend - maxstart)) {
1853 maxstart = curstart;
1856 curstart = curend = 255;
1859 if ((curend - curstart) >
1860 (maxend - maxstart)) {
1861 maxstart = curstart;
1864 for (i = 0; i < 8; i++) {
1865 if (i >= maxstart && i <= maxend) {
1871 b = ntohs(addr->addr16[i]);
1888 pf_print_state(struct pf_state *s)
1890 pf_print_state_parts(s, NULL, NULL);
1894 pf_print_state_parts(struct pf_state *s,
1895 struct pf_state_key *skwp, struct pf_state_key *sksp)
1897 struct pf_state_key *skw, *sks;
1898 u_int8_t proto, dir;
1900 /* Do our best to fill these, but they're skipped if NULL */
1901 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1902 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1903 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1904 dir = s ? s->direction : 0;
1922 case IPPROTO_ICMPV6:
1926 printf("%u", proto);
1939 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1941 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1946 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1948 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1953 if (proto == IPPROTO_TCP) {
1954 printf(" [lo=%u high=%u win=%u modulator=%u",
1955 s->src.seqlo, s->src.seqhi,
1956 s->src.max_win, s->src.seqdiff);
1957 if (s->src.wscale && s->dst.wscale)
1958 printf(" wscale=%u",
1959 s->src.wscale & PF_WSCALE_MASK);
1961 printf(" [lo=%u high=%u win=%u modulator=%u",
1962 s->dst.seqlo, s->dst.seqhi,
1963 s->dst.max_win, s->dst.seqdiff);
1964 if (s->src.wscale && s->dst.wscale)
1965 printf(" wscale=%u",
1966 s->dst.wscale & PF_WSCALE_MASK);
1969 printf(" %u:%u", s->src.state, s->dst.state);
1974 pf_print_flags(u_int8_t f)
1996 #define PF_SET_SKIP_STEPS(i) \
1998 while (head[i] != cur) { \
1999 head[i]->skip[i].ptr = cur; \
2000 head[i] = TAILQ_NEXT(head[i], entries); \
2005 pf_calc_skip_steps(struct pf_rulequeue *rules)
2007 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
2010 cur = TAILQ_FIRST(rules);
2012 for (i = 0; i < PF_SKIP_COUNT; ++i)
2014 while (cur != NULL) {
2016 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2017 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2018 if (cur->direction != prev->direction)
2019 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2020 if (cur->af != prev->af)
2021 PF_SET_SKIP_STEPS(PF_SKIP_AF);
2022 if (cur->proto != prev->proto)
2023 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2024 if (cur->src.neg != prev->src.neg ||
2025 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2026 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2027 if (cur->src.port[0] != prev->src.port[0] ||
2028 cur->src.port[1] != prev->src.port[1] ||
2029 cur->src.port_op != prev->src.port_op)
2030 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2031 if (cur->dst.neg != prev->dst.neg ||
2032 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2033 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2034 if (cur->dst.port[0] != prev->dst.port[0] ||
2035 cur->dst.port[1] != prev->dst.port[1] ||
2036 cur->dst.port_op != prev->dst.port_op)
2037 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2040 cur = TAILQ_NEXT(cur, entries);
2042 for (i = 0; i < PF_SKIP_COUNT; ++i)
2043 PF_SET_SKIP_STEPS(i);
2047 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2049 if (aw1->type != aw2->type)
2051 switch (aw1->type) {
2052 case PF_ADDR_ADDRMASK:
2054 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2056 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2059 case PF_ADDR_DYNIFTL:
2060 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2061 case PF_ADDR_NOROUTE:
2062 case PF_ADDR_URPFFAILED:
2065 return (aw1->p.tbl != aw2->p.tbl);
2067 printf("invalid address type: %d\n", aw1->type);
2073 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2074 * header isn't always a full checksum. In some cases (i.e. output) it's a
2075 * pseudo-header checksum, which is a partial checksum over src/dst IP
2076 * addresses, protocol number and length.
2078 * That means we have the following cases:
2079 * * Input or forwarding: we don't have TSO, the checksum fields are full
2080 * checksums, we need to update the checksum whenever we change anything.
2081 * * Output (i.e. the checksum is a pseudo-header checksum):
2082 * x The field being updated is src/dst address or affects the length of
2083 * the packet. We need to update the pseudo-header checksum (note that this
2084 * checksum is not ones' complement).
2085 * x Some other field is being modified (e.g. src/dst port numbers): We
2086 * don't have to update anything.
2089 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2095 l = cksum + old - new;
2096 l = (l >> 16) + (l & 65535);
2104 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2105 u_int16_t new, u_int8_t udp)
2107 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2110 return (pf_cksum_fixup(cksum, old, new, udp));
2114 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2115 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2121 PF_ACPY(&ao, a, af);
2124 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2132 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2133 ao.addr16[0], an->addr16[0], 0),
2134 ao.addr16[1], an->addr16[1], 0);
2137 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2138 ao.addr16[0], an->addr16[0], u),
2139 ao.addr16[1], an->addr16[1], u);
2141 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2146 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2147 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2148 pf_cksum_fixup(pf_cksum_fixup(*pc,
2149 ao.addr16[0], an->addr16[0], u),
2150 ao.addr16[1], an->addr16[1], u),
2151 ao.addr16[2], an->addr16[2], u),
2152 ao.addr16[3], an->addr16[3], u),
2153 ao.addr16[4], an->addr16[4], u),
2154 ao.addr16[5], an->addr16[5], u),
2155 ao.addr16[6], an->addr16[6], u),
2156 ao.addr16[7], an->addr16[7], u);
2158 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2163 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2164 CSUM_DELAY_DATA_IPV6)) {
2171 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2173 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2177 memcpy(&ao, a, sizeof(ao));
2178 memcpy(a, &an, sizeof(u_int32_t));
2179 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2180 ao % 65536, an % 65536, u);
2184 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2188 memcpy(&ao, a, sizeof(ao));
2189 memcpy(a, &an, sizeof(u_int32_t));
2191 *c = pf_proto_cksum_fixup(m,
2192 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2193 ao % 65536, an % 65536, udp);
2198 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2202 PF_ACPY(&ao, a, AF_INET6);
2203 PF_ACPY(a, an, AF_INET6);
2205 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2206 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2207 pf_cksum_fixup(pf_cksum_fixup(*c,
2208 ao.addr16[0], an->addr16[0], u),
2209 ao.addr16[1], an->addr16[1], u),
2210 ao.addr16[2], an->addr16[2], u),
2211 ao.addr16[3], an->addr16[3], u),
2212 ao.addr16[4], an->addr16[4], u),
2213 ao.addr16[5], an->addr16[5], u),
2214 ao.addr16[6], an->addr16[6], u),
2215 ao.addr16[7], an->addr16[7], u);
2220 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2221 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2222 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2224 struct pf_addr oia, ooa;
2226 PF_ACPY(&oia, ia, af);
2228 PF_ACPY(&ooa, oa, af);
2230 /* Change inner protocol port, fix inner protocol checksum. */
2232 u_int16_t oip = *ip;
2239 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2240 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2242 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2244 /* Change inner ip address, fix inner ip and icmp checksums. */
2245 PF_ACPY(ia, na, af);
2249 u_int32_t oh2c = *h2c;
2251 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2252 oia.addr16[0], ia->addr16[0], 0),
2253 oia.addr16[1], ia->addr16[1], 0);
2254 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2255 oia.addr16[0], ia->addr16[0], 0),
2256 oia.addr16[1], ia->addr16[1], 0);
2257 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2263 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2264 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2265 pf_cksum_fixup(pf_cksum_fixup(*ic,
2266 oia.addr16[0], ia->addr16[0], u),
2267 oia.addr16[1], ia->addr16[1], u),
2268 oia.addr16[2], ia->addr16[2], u),
2269 oia.addr16[3], ia->addr16[3], u),
2270 oia.addr16[4], ia->addr16[4], u),
2271 oia.addr16[5], ia->addr16[5], u),
2272 oia.addr16[6], ia->addr16[6], u),
2273 oia.addr16[7], ia->addr16[7], u);
2277 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2279 PF_ACPY(oa, na, af);
2283 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2284 ooa.addr16[0], oa->addr16[0], 0),
2285 ooa.addr16[1], oa->addr16[1], 0);
2290 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2291 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2292 pf_cksum_fixup(pf_cksum_fixup(*ic,
2293 ooa.addr16[0], oa->addr16[0], u),
2294 ooa.addr16[1], oa->addr16[1], u),
2295 ooa.addr16[2], oa->addr16[2], u),
2296 ooa.addr16[3], oa->addr16[3], u),
2297 ooa.addr16[4], oa->addr16[4], u),
2298 ooa.addr16[5], oa->addr16[5], u),
2299 ooa.addr16[6], oa->addr16[6], u),
2300 ooa.addr16[7], oa->addr16[7], u);
2309 * Need to modulate the sequence numbers in the TCP SACK option
2310 * (credits to Krzysztof Pfaff for report and patch)
2313 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2314 struct tcphdr *th, struct pf_state_peer *dst)
2316 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2317 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2318 int copyback = 0, i, olen;
2319 struct sackblk sack;
2321 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2322 if (hlen < TCPOLEN_SACKLEN ||
2323 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2326 while (hlen >= TCPOLEN_SACKLEN) {
2329 case TCPOPT_EOL: /* FALLTHROUGH */
2337 if (olen >= TCPOLEN_SACKLEN) {
2338 for (i = 2; i + TCPOLEN_SACK <= olen;
2339 i += TCPOLEN_SACK) {
2340 memcpy(&sack, &opt[i], sizeof(sack));
2341 pf_change_proto_a(m, &sack.start, &th->th_sum,
2342 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2343 pf_change_proto_a(m, &sack.end, &th->th_sum,
2344 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2345 memcpy(&opt[i], &sack, sizeof(sack));
2359 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2364 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2365 const struct pf_addr *saddr, const struct pf_addr *daddr,
2366 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2367 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2368 u_int16_t rtag, struct ifnet *ifp)
2370 struct pf_send_entry *pfse;
2374 struct ip *h = NULL;
2377 struct ip6_hdr *h6 = NULL;
2381 struct pf_mtag *pf_mtag;
2386 /* maximum segment size tcp option */
2387 tlen = sizeof(struct tcphdr);
2394 len = sizeof(struct ip) + tlen;
2399 len = sizeof(struct ip6_hdr) + tlen;
2403 panic("%s: unsupported af %d", __func__, af);
2406 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2407 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2410 m = m_gethdr(M_NOWAIT, MT_DATA);
2412 free(pfse, M_PFTEMP);
2416 mac_netinet_firewall_send(m);
2418 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2419 free(pfse, M_PFTEMP);
2424 m->m_flags |= M_SKIP_FIREWALL;
2425 pf_mtag->tag = rtag;
2427 if (r != NULL && r->rtableid >= 0)
2428 M_SETFIB(m, r->rtableid);
2431 if (r != NULL && r->qid) {
2432 pf_mtag->qid = r->qid;
2434 /* add hints for ecn */
2435 pf_mtag->hdr = mtod(m, struct ip *);
2438 m->m_data += max_linkhdr;
2439 m->m_pkthdr.len = m->m_len = len;
2440 m->m_pkthdr.rcvif = NULL;
2441 bzero(m->m_data, len);
2445 h = mtod(m, struct ip *);
2447 /* IP header fields included in the TCP checksum */
2448 h->ip_p = IPPROTO_TCP;
2449 h->ip_len = htons(tlen);
2450 h->ip_src.s_addr = saddr->v4.s_addr;
2451 h->ip_dst.s_addr = daddr->v4.s_addr;
2453 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2458 h6 = mtod(m, struct ip6_hdr *);
2460 /* IP header fields included in the TCP checksum */
2461 h6->ip6_nxt = IPPROTO_TCP;
2462 h6->ip6_plen = htons(tlen);
2463 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2464 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2466 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2472 th->th_sport = sport;
2473 th->th_dport = dport;
2474 th->th_seq = htonl(seq);
2475 th->th_ack = htonl(ack);
2476 th->th_off = tlen >> 2;
2477 th->th_flags = flags;
2478 th->th_win = htons(win);
2481 opt = (char *)(th + 1);
2482 opt[0] = TCPOPT_MAXSEG;
2485 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2492 th->th_sum = in_cksum(m, len);
2494 /* Finish the IP header */
2496 h->ip_hl = sizeof(*h) >> 2;
2497 h->ip_tos = IPTOS_LOWDELAY;
2498 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2499 h->ip_len = htons(len);
2500 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2503 pfse->pfse_type = PFSE_IP;
2509 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2510 sizeof(struct ip6_hdr), tlen);
2512 h6->ip6_vfc |= IPV6_VERSION;
2513 h6->ip6_hlim = IPV6_DEFHLIM;
2515 pfse->pfse_type = PFSE_IP6;
2524 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2525 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2526 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2529 struct pf_addr * const saddr = pd->src;
2530 struct pf_addr * const daddr = pd->dst;
2531 sa_family_t af = pd->af;
2533 /* undo NAT changes, if they have taken place */
2535 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2536 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2538 *pd->sport = sk->port[pd->sidx];
2540 *pd->dport = sk->port[pd->didx];
2542 *pd->proto_sum = bproto_sum;
2544 *pd->ip_sum = bip_sum;
2545 m_copyback(m, off, hdrlen, pd->hdr.any);
2547 if (pd->proto == IPPROTO_TCP &&
2548 ((r->rule_flag & PFRULE_RETURNRST) ||
2549 (r->rule_flag & PFRULE_RETURN)) &&
2550 !(th->th_flags & TH_RST)) {
2551 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2563 h4 = mtod(m, struct ip *);
2564 len = ntohs(h4->ip_len) - off;
2569 h6 = mtod(m, struct ip6_hdr *);
2570 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2575 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2576 REASON_SET(reason, PFRES_PROTCKSUM);
2578 if (th->th_flags & TH_SYN)
2580 if (th->th_flags & TH_FIN)
2582 pf_send_tcp(m, r, af, pd->dst,
2583 pd->src, th->th_dport, th->th_sport,
2584 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2585 r->return_ttl, 1, 0, kif->pfik_ifp);
2587 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2589 pf_send_icmp(m, r->return_icmp >> 8,
2590 r->return_icmp & 255, af, r);
2591 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2593 pf_send_icmp(m, r->return_icmp6 >> 8,
2594 r->return_icmp6 & 255, af, r);
2599 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2603 KASSERT(prio <= PF_PRIO_MAX,
2604 ("%s with invalid pcp", __func__));
2606 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2608 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2609 sizeof(uint8_t), M_NOWAIT);
2612 m_tag_prepend(m, mtag);
2615 *(uint8_t *)(mtag + 1) = prio;
2620 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2625 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2629 if (prio == PF_PRIO_ZERO)
2632 mpcp = *(uint8_t *)(mtag + 1);
2634 return (mpcp == prio);
2638 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2641 struct pf_send_entry *pfse;
2643 struct pf_mtag *pf_mtag;
2645 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2646 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2650 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2651 free(pfse, M_PFTEMP);
2655 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2656 free(pfse, M_PFTEMP);
2660 m0->m_flags |= M_SKIP_FIREWALL;
2662 if (r->rtableid >= 0)
2663 M_SETFIB(m0, r->rtableid);
2667 pf_mtag->qid = r->qid;
2668 /* add hints for ecn */
2669 pf_mtag->hdr = mtod(m0, struct ip *);
2676 pfse->pfse_type = PFSE_ICMP;
2681 pfse->pfse_type = PFSE_ICMP6;
2686 pfse->icmpopts.type = type;
2687 pfse->icmpopts.code = code;
2692 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2693 * If n is 0, they match if they are equal. If n is != 0, they match if they
2697 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2698 struct pf_addr *b, sa_family_t af)
2705 if ((a->addr32[0] & m->addr32[0]) ==
2706 (b->addr32[0] & m->addr32[0]))
2712 if (((a->addr32[0] & m->addr32[0]) ==
2713 (b->addr32[0] & m->addr32[0])) &&
2714 ((a->addr32[1] & m->addr32[1]) ==
2715 (b->addr32[1] & m->addr32[1])) &&
2716 ((a->addr32[2] & m->addr32[2]) ==
2717 (b->addr32[2] & m->addr32[2])) &&
2718 ((a->addr32[3] & m->addr32[3]) ==
2719 (b->addr32[3] & m->addr32[3])))
2738 * Return 1 if b <= a <= e, otherwise return 0.
2741 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2742 struct pf_addr *a, sa_family_t af)
2747 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2748 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2757 for (i = 0; i < 4; ++i)
2758 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2760 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2763 for (i = 0; i < 4; ++i)
2764 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2766 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2776 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2780 return ((p > a1) && (p < a2));
2782 return ((p < a1) || (p > a2));
2784 return ((p >= a1) && (p <= a2));
2798 return (0); /* never reached */
2802 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2807 return (pf_match(op, a1, a2, p));
2811 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2813 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2815 return (pf_match(op, a1, a2, u));
2819 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2821 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2823 return (pf_match(op, a1, a2, g));
2827 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2832 return ((!r->match_tag_not && r->match_tag == *tag) ||
2833 (r->match_tag_not && r->match_tag != *tag));
2837 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2840 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2842 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2845 pd->pf_mtag->tag = tag;
2850 #define PF_ANCHOR_STACKSIZE 32
2851 struct pf_anchor_stackframe {
2852 struct pf_ruleset *rs;
2853 struct pf_rule *r; /* XXX: + match bit */
2854 struct pf_anchor *child;
2858 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2860 #define PF_ANCHORSTACK_MATCH 0x00000001
2861 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2863 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2864 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2865 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2866 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2867 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2871 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2872 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2875 struct pf_anchor_stackframe *f;
2881 if (*depth >= PF_ANCHOR_STACKSIZE) {
2882 printf("%s: anchor stack overflow on %s\n",
2883 __func__, (*r)->anchor->name);
2884 *r = TAILQ_NEXT(*r, entries);
2886 } else if (*depth == 0 && a != NULL)
2888 f = stack + (*depth)++;
2891 if ((*r)->anchor_wildcard) {
2892 struct pf_anchor_node *parent = &(*r)->anchor->children;
2894 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2898 *rs = &f->child->ruleset;
2901 *rs = &(*r)->anchor->ruleset;
2903 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2907 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2908 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2911 struct pf_anchor_stackframe *f;
2920 f = stack + *depth - 1;
2921 fr = PF_ANCHOR_RULE(f);
2922 if (f->child != NULL) {
2923 struct pf_anchor_node *parent;
2926 * This block traverses through
2927 * a wildcard anchor.
2929 parent = &fr->anchor->children;
2930 if (match != NULL && *match) {
2932 * If any of "*" matched, then
2933 * "foo/ *" matched, mark frame
2936 PF_ANCHOR_SET_MATCH(f);
2939 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2940 if (f->child != NULL) {
2941 *rs = &f->child->ruleset;
2942 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2950 if (*depth == 0 && a != NULL)
2953 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2955 *r = TAILQ_NEXT(fr, entries);
2956 } while (*r == NULL);
2963 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2964 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2969 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2970 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2974 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2975 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2976 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2977 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2978 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2979 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2980 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2981 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2987 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2992 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2996 if (addr->addr32[3] == 0xffffffff) {
2997 addr->addr32[3] = 0;
2998 if (addr->addr32[2] == 0xffffffff) {
2999 addr->addr32[2] = 0;
3000 if (addr->addr32[1] == 0xffffffff) {
3001 addr->addr32[1] = 0;
3003 htonl(ntohl(addr->addr32[0]) + 1);
3006 htonl(ntohl(addr->addr32[1]) + 1);
3009 htonl(ntohl(addr->addr32[2]) + 1);
3012 htonl(ntohl(addr->addr32[3]) + 1);
3019 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3021 struct pf_addr *saddr, *daddr;
3022 u_int16_t sport, dport;
3023 struct inpcbinfo *pi;
3026 pd->lookup.uid = UID_MAX;
3027 pd->lookup.gid = GID_MAX;
3029 switch (pd->proto) {
3031 if (pd->hdr.tcp == NULL)
3033 sport = pd->hdr.tcp->th_sport;
3034 dport = pd->hdr.tcp->th_dport;
3038 if (pd->hdr.udp == NULL)
3040 sport = pd->hdr.udp->uh_sport;
3041 dport = pd->hdr.udp->uh_dport;
3047 if (direction == PF_IN) {
3062 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3063 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3065 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3066 daddr->v4, dport, INPLOOKUP_WILDCARD |
3067 INPLOOKUP_RLOCKPCB, NULL, m);
3075 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3076 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3078 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3079 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3080 INPLOOKUP_RLOCKPCB, NULL, m);
3090 INP_RLOCK_ASSERT(inp);
3091 pd->lookup.uid = inp->inp_cred->cr_uid;
3092 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3099 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3103 u_int8_t *opt, optlen;
3104 u_int8_t wscale = 0;
3106 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3107 if (hlen <= sizeof(struct tcphdr))
3109 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3111 opt = hdr + sizeof(struct tcphdr);
3112 hlen -= sizeof(struct tcphdr);
3122 if (wscale > TCP_MAX_WINSHIFT)
3123 wscale = TCP_MAX_WINSHIFT;
3124 wscale |= PF_WSCALE_FLAG;
3139 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3143 u_int8_t *opt, optlen;
3144 u_int16_t mss = V_tcp_mssdflt;
3146 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3147 if (hlen <= sizeof(struct tcphdr))
3149 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3151 opt = hdr + sizeof(struct tcphdr);
3152 hlen -= sizeof(struct tcphdr);
3153 while (hlen >= TCPOLEN_MAXSEG) {
3161 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3177 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3179 struct nhop_object *nh;
3181 struct in6_addr dst6;
3192 hlen = sizeof(struct ip);
3193 nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
3195 mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3200 hlen = sizeof(struct ip6_hdr);
3201 in6_splitscope(&addr->v6, &dst6, &scopeid);
3202 nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
3204 mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3209 mss = max(V_tcp_mssdflt, mss);
3210 mss = min(mss, offer);
3211 mss = max(mss, 64); /* sanity - at least max opt space */
3216 pf_tcp_iss(struct pf_pdesc *pd)
3219 u_int32_t digest[4];
3221 if (V_pf_tcp_secret_init == 0) {
3222 arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3223 MD5Init(&V_pf_tcp_secret_ctx);
3224 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3225 sizeof(V_pf_tcp_secret));
3226 V_pf_tcp_secret_init = 1;
3229 ctx = V_pf_tcp_secret_ctx;
3231 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3232 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3233 if (pd->af == AF_INET6) {
3234 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3235 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3237 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3238 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3240 MD5Final((u_char *)digest, &ctx);
3241 V_pf_tcp_iss_off += 4096;
3242 #define ISN_RANDOM_INCREMENT (4096 - 1)
3243 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3245 #undef ISN_RANDOM_INCREMENT
3249 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3250 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3251 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3253 struct pf_rule *nr = NULL;
3254 struct pf_addr * const saddr = pd->src;
3255 struct pf_addr * const daddr = pd->dst;
3256 sa_family_t af = pd->af;
3257 struct pf_rule *r, *a = NULL;
3258 struct pf_ruleset *ruleset = NULL;
3259 struct pf_src_node *nsn = NULL;
3260 struct tcphdr *th = pd->hdr.tcp;
3261 struct pf_state_key *sk = NULL, *nk = NULL;
3263 int rewrite = 0, hdrlen = 0;
3264 int tag = -1, rtableid = -1;
3268 u_int16_t sport = 0, dport = 0;
3269 u_int16_t bproto_sum = 0, bip_sum = 0;
3270 u_int8_t icmptype = 0, icmpcode = 0;
3271 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3276 INP_LOCK_ASSERT(inp);
3277 pd->lookup.uid = inp->inp_cred->cr_uid;
3278 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3279 pd->lookup.done = 1;
3282 switch (pd->proto) {
3284 sport = th->th_sport;
3285 dport = th->th_dport;
3286 hdrlen = sizeof(*th);
3289 sport = pd->hdr.udp->uh_sport;
3290 dport = pd->hdr.udp->uh_dport;
3291 hdrlen = sizeof(*pd->hdr.udp);
3295 if (pd->af != AF_INET)
3297 sport = dport = pd->hdr.icmp->icmp_id;
3298 hdrlen = sizeof(*pd->hdr.icmp);
3299 icmptype = pd->hdr.icmp->icmp_type;
3300 icmpcode = pd->hdr.icmp->icmp_code;
3302 if (icmptype == ICMP_UNREACH ||
3303 icmptype == ICMP_SOURCEQUENCH ||
3304 icmptype == ICMP_REDIRECT ||
3305 icmptype == ICMP_TIMXCEED ||
3306 icmptype == ICMP_PARAMPROB)
3311 case IPPROTO_ICMPV6:
3314 sport = dport = pd->hdr.icmp6->icmp6_id;
3315 hdrlen = sizeof(*pd->hdr.icmp6);
3316 icmptype = pd->hdr.icmp6->icmp6_type;
3317 icmpcode = pd->hdr.icmp6->icmp6_code;
3319 if (icmptype == ICMP6_DST_UNREACH ||
3320 icmptype == ICMP6_PACKET_TOO_BIG ||
3321 icmptype == ICMP6_TIME_EXCEEDED ||
3322 icmptype == ICMP6_PARAM_PROB)
3327 sport = dport = hdrlen = 0;
3331 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3333 /* check packet for BINAT/NAT/RDR */
3334 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3335 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3336 KASSERT(sk != NULL, ("%s: null sk", __func__));
3337 KASSERT(nk != NULL, ("%s: null nk", __func__));
3340 bip_sum = *pd->ip_sum;
3342 switch (pd->proto) {
3344 bproto_sum = th->th_sum;
3345 pd->proto_sum = &th->th_sum;
3347 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3348 nk->port[pd->sidx] != sport) {
3349 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3350 &th->th_sum, &nk->addr[pd->sidx],
3351 nk->port[pd->sidx], 0, af);
3352 pd->sport = &th->th_sport;
3353 sport = th->th_sport;
3356 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3357 nk->port[pd->didx] != dport) {
3358 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3359 &th->th_sum, &nk->addr[pd->didx],
3360 nk->port[pd->didx], 0, af);
3361 dport = th->th_dport;
3362 pd->dport = &th->th_dport;
3367 bproto_sum = pd->hdr.udp->uh_sum;
3368 pd->proto_sum = &pd->hdr.udp->uh_sum;
3370 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3371 nk->port[pd->sidx] != sport) {
3372 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3373 pd->ip_sum, &pd->hdr.udp->uh_sum,
3374 &nk->addr[pd->sidx],
3375 nk->port[pd->sidx], 1, af);
3376 sport = pd->hdr.udp->uh_sport;
3377 pd->sport = &pd->hdr.udp->uh_sport;
3380 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3381 nk->port[pd->didx] != dport) {
3382 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3383 pd->ip_sum, &pd->hdr.udp->uh_sum,
3384 &nk->addr[pd->didx],
3385 nk->port[pd->didx], 1, af);
3386 dport = pd->hdr.udp->uh_dport;
3387 pd->dport = &pd->hdr.udp->uh_dport;
3393 nk->port[0] = nk->port[1];
3394 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3395 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3396 nk->addr[pd->sidx].v4.s_addr, 0);
3398 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3399 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3400 nk->addr[pd->didx].v4.s_addr, 0);
3402 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3403 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3404 pd->hdr.icmp->icmp_cksum, sport,
3406 pd->hdr.icmp->icmp_id = nk->port[1];
3407 pd->sport = &pd->hdr.icmp->icmp_id;
3409 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3413 case IPPROTO_ICMPV6:
3414 nk->port[0] = nk->port[1];
3415 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3416 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3417 &nk->addr[pd->sidx], 0);
3419 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3420 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3421 &nk->addr[pd->didx], 0);
3430 &nk->addr[pd->sidx], AF_INET))
3431 pf_change_a(&saddr->v4.s_addr,
3433 nk->addr[pd->sidx].v4.s_addr, 0);
3436 &nk->addr[pd->didx], AF_INET))
3437 pf_change_a(&daddr->v4.s_addr,
3439 nk->addr[pd->didx].v4.s_addr, 0);
3445 &nk->addr[pd->sidx], AF_INET6))
3446 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3449 &nk->addr[pd->didx], AF_INET6))
3450 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3463 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3464 r = r->skip[PF_SKIP_IFP].ptr;
3465 else if (r->direction && r->direction != direction)
3466 r = r->skip[PF_SKIP_DIR].ptr;
3467 else if (r->af && r->af != af)
3468 r = r->skip[PF_SKIP_AF].ptr;
3469 else if (r->proto && r->proto != pd->proto)
3470 r = r->skip[PF_SKIP_PROTO].ptr;
3471 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3472 r->src.neg, kif, M_GETFIB(m)))
3473 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3474 /* tcp/udp only. port_op always 0 in other cases */
3475 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3476 r->src.port[0], r->src.port[1], sport))
3477 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3478 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3479 r->dst.neg, NULL, M_GETFIB(m)))
3480 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3481 /* tcp/udp only. port_op always 0 in other cases */
3482 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3483 r->dst.port[0], r->dst.port[1], dport))
3484 r = r->skip[PF_SKIP_DST_PORT].ptr;
3485 /* icmp only. type always 0 in other cases */
3486 else if (r->type && r->type != icmptype + 1)
3487 r = TAILQ_NEXT(r, entries);
3488 /* icmp only. type always 0 in other cases */
3489 else if (r->code && r->code != icmpcode + 1)
3490 r = TAILQ_NEXT(r, entries);
3491 else if (r->tos && !(r->tos == pd->tos))
3492 r = TAILQ_NEXT(r, entries);
3493 else if (r->rule_flag & PFRULE_FRAGMENT)
3494 r = TAILQ_NEXT(r, entries);
3495 else if (pd->proto == IPPROTO_TCP &&
3496 (r->flagset & th->th_flags) != r->flags)
3497 r = TAILQ_NEXT(r, entries);
3498 /* tcp/udp only. uid.op always 0 in other cases */
3499 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3500 pf_socket_lookup(direction, pd, m), 1)) &&
3501 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3503 r = TAILQ_NEXT(r, entries);
3504 /* tcp/udp only. gid.op always 0 in other cases */
3505 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3506 pf_socket_lookup(direction, pd, m), 1)) &&
3507 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3509 r = TAILQ_NEXT(r, entries);
3511 !pf_match_ieee8021q_pcp(r->prio, m))
3512 r = TAILQ_NEXT(r, entries);
3514 r->prob <= arc4random())
3515 r = TAILQ_NEXT(r, entries);
3516 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3517 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3518 r = TAILQ_NEXT(r, entries);
3519 else if (r->os_fingerprint != PF_OSFP_ANY &&
3520 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3521 pf_osfp_fingerprint(pd, m, off, th),
3522 r->os_fingerprint)))
3523 r = TAILQ_NEXT(r, entries);
3527 if (r->rtableid >= 0)
3528 rtableid = r->rtableid;
3529 if (r->anchor == NULL) {
3536 r = TAILQ_NEXT(r, entries);
3538 pf_step_into_anchor(anchor_stack, &asd,
3539 &ruleset, PF_RULESET_FILTER, &r, &a,
3542 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3543 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3550 REASON_SET(&reason, PFRES_MATCH);
3552 if (r->log || (nr != NULL && nr->log)) {
3554 m_copyback(m, off, hdrlen, pd->hdr.any);
3555 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3559 if ((r->action == PF_DROP) &&
3560 ((r->rule_flag & PFRULE_RETURNRST) ||
3561 (r->rule_flag & PFRULE_RETURNICMP) ||
3562 (r->rule_flag & PFRULE_RETURN))) {
3563 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3564 bip_sum, hdrlen, &reason);
3567 if (r->action == PF_DROP)
3570 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3571 REASON_SET(&reason, PFRES_MEMORY);
3575 M_SETFIB(m, rtableid);
3577 if (!state_icmp && (r->keep_state || nr != NULL ||
3578 (pd->flags & PFDESC_TCP_NORM))) {
3580 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3581 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3583 if (action != PF_PASS) {
3584 if (action == PF_DROP &&
3585 (r->rule_flag & PFRULE_RETURN))
3586 pf_return(r, nr, pd, sk, off, m, th, kif,
3587 bproto_sum, bip_sum, hdrlen, &reason);
3592 uma_zfree(V_pf_state_key_z, sk);
3594 uma_zfree(V_pf_state_key_z, nk);
3597 /* copy back packet headers if we performed NAT operations */
3599 m_copyback(m, off, hdrlen, pd->hdr.any);
3601 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3602 direction == PF_OUT &&
3603 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3605 * We want the state created, but we dont
3606 * want to send this in case a partner
3607 * firewall has to know about it to allow
3608 * replies through it.
3616 uma_zfree(V_pf_state_key_z, sk);
3618 uma_zfree(V_pf_state_key_z, nk);
3623 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3624 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3625 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3626 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3627 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3629 struct pf_state *s = NULL;
3630 struct pf_src_node *sn = NULL;
3631 struct tcphdr *th = pd->hdr.tcp;
3632 u_int16_t mss = V_tcp_mssdflt;
3635 /* check maximums */
3636 if (r->max_states &&
3637 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3638 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3639 REASON_SET(&reason, PFRES_MAXSTATES);
3642 /* src node for filter rule */
3643 if ((r->rule_flag & PFRULE_SRCTRACK ||
3644 r->rpool.opts & PF_POOL_STICKYADDR) &&
3645 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3646 REASON_SET(&reason, PFRES_SRCLIMIT);
3649 /* src node for translation rule */
3650 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3651 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3652 REASON_SET(&reason, PFRES_SRCLIMIT);
3655 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3657 REASON_SET(&reason, PFRES_MEMORY);
3661 s->nat_rule.ptr = nr;
3663 STATE_INC_COUNTERS(s);
3665 s->state_flags |= PFSTATE_ALLOWOPTS;
3666 if (r->rule_flag & PFRULE_STATESLOPPY)
3667 s->state_flags |= PFSTATE_SLOPPY;
3668 s->log = r->log & PF_LOG_ALL;
3669 s->sync_state = PFSYNC_S_NONE;
3671 s->log |= nr->log & PF_LOG_ALL;
3672 switch (pd->proto) {
3674 s->src.seqlo = ntohl(th->th_seq);
3675 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3676 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3677 r->keep_state == PF_STATE_MODULATE) {
3678 /* Generate sequence number modulator */
3679 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3682 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3683 htonl(s->src.seqlo + s->src.seqdiff), 0);
3687 if (th->th_flags & TH_SYN) {
3689 s->src.wscale = pf_get_wscale(m, off,
3690 th->th_off, pd->af);
3692 s->src.max_win = MAX(ntohs(th->th_win), 1);
3693 if (s->src.wscale & PF_WSCALE_MASK) {
3694 /* Remove scale factor from initial window */
3695 int win = s->src.max_win;
3696 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3697 s->src.max_win = (win - 1) >>
3698 (s->src.wscale & PF_WSCALE_MASK);
3700 if (th->th_flags & TH_FIN)
3704 s->src.state = TCPS_SYN_SENT;
3705 s->dst.state = TCPS_CLOSED;
3706 s->timeout = PFTM_TCP_FIRST_PACKET;
3709 s->src.state = PFUDPS_SINGLE;
3710 s->dst.state = PFUDPS_NO_TRAFFIC;
3711 s->timeout = PFTM_UDP_FIRST_PACKET;
3715 case IPPROTO_ICMPV6:
3717 s->timeout = PFTM_ICMP_FIRST_PACKET;
3720 s->src.state = PFOTHERS_SINGLE;
3721 s->dst.state = PFOTHERS_NO_TRAFFIC;
3722 s->timeout = PFTM_OTHER_FIRST_PACKET;
3726 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3727 REASON_SET(&reason, PFRES_MAPFAILED);
3728 pf_src_tree_remove_state(s);
3729 STATE_DEC_COUNTERS(s);
3730 uma_zfree(V_pf_state_z, s);
3733 s->rt_kif = r->rpool.cur->kif;
3736 s->creation = time_uptime;
3737 s->expire = time_uptime;
3742 /* XXX We only modify one side for now. */
3743 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3744 s->nat_src_node = nsn;
3746 if (pd->proto == IPPROTO_TCP) {
3747 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3748 off, pd, th, &s->src, &s->dst)) {
3749 REASON_SET(&reason, PFRES_MEMORY);
3750 pf_src_tree_remove_state(s);
3751 STATE_DEC_COUNTERS(s);
3752 uma_zfree(V_pf_state_z, s);
3755 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3756 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3757 &s->src, &s->dst, rewrite)) {
3758 /* This really shouldn't happen!!! */
3759 DPFPRINTF(PF_DEBUG_URGENT,
3760 ("pf_normalize_tcp_stateful failed on first "
3762 pf_normalize_tcp_cleanup(s);
3763 pf_src_tree_remove_state(s);
3764 STATE_DEC_COUNTERS(s);
3765 uma_zfree(V_pf_state_z, s);
3769 s->direction = pd->dir;
3772 * sk/nk could already been setup by pf_get_translation().
3775 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3776 __func__, nr, sk, nk));
3777 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3782 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3783 __func__, nr, sk, nk));
3785 /* Swap sk/nk for PF_OUT. */
3786 if (pf_state_insert(BOUND_IFACE(r, kif),
3787 (pd->dir == PF_IN) ? sk : nk,
3788 (pd->dir == PF_IN) ? nk : sk, s)) {
3789 if (pd->proto == IPPROTO_TCP)
3790 pf_normalize_tcp_cleanup(s);
3791 REASON_SET(&reason, PFRES_STATEINS);
3792 pf_src_tree_remove_state(s);
3793 STATE_DEC_COUNTERS(s);
3794 uma_zfree(V_pf_state_z, s);
3801 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3802 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3803 s->src.state = PF_TCPS_PROXY_SRC;
3804 /* undo NAT changes, if they have taken place */
3806 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3807 if (pd->dir == PF_OUT)
3808 skt = s->key[PF_SK_STACK];
3809 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3810 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3812 *pd->sport = skt->port[pd->sidx];
3814 *pd->dport = skt->port[pd->didx];
3816 *pd->proto_sum = bproto_sum;
3818 *pd->ip_sum = bip_sum;
3819 m_copyback(m, off, hdrlen, pd->hdr.any);
3821 s->src.seqhi = htonl(arc4random());
3822 /* Find mss option */
3823 int rtid = M_GETFIB(m);
3824 mss = pf_get_mss(m, off, th->th_off, pd->af);
3825 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3826 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3828 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3829 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3830 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3831 REASON_SET(&reason, PFRES_SYNPROXY);
3832 return (PF_SYNPROXY_DROP);
3839 uma_zfree(V_pf_state_key_z, sk);
3841 uma_zfree(V_pf_state_key_z, nk);
3844 struct pf_srchash *sh;
3846 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3847 PF_HASHROW_LOCK(sh);
3848 if (--sn->states == 0 && sn->expire == 0) {
3849 pf_unlink_src_node(sn);
3850 uma_zfree(V_pf_sources_z, sn);
3852 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3854 PF_HASHROW_UNLOCK(sh);
3857 if (nsn != sn && nsn != NULL) {
3858 struct pf_srchash *sh;
3860 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3861 PF_HASHROW_LOCK(sh);
3862 if (--nsn->states == 0 && nsn->expire == 0) {
3863 pf_unlink_src_node(nsn);
3864 uma_zfree(V_pf_sources_z, nsn);
3866 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3868 PF_HASHROW_UNLOCK(sh);
3875 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3876 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3877 struct pf_ruleset **rsm)
3879 struct pf_rule *r, *a = NULL;
3880 struct pf_ruleset *ruleset = NULL;
3881 sa_family_t af = pd->af;
3886 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3890 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3893 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3894 r = r->skip[PF_SKIP_IFP].ptr;
3895 else if (r->direction && r->direction != direction)
3896 r = r->skip[PF_SKIP_DIR].ptr;
3897 else if (r->af && r->af != af)
3898 r = r->skip[PF_SKIP_AF].ptr;
3899 else if (r->proto && r->proto != pd->proto)
3900 r = r->skip[PF_SKIP_PROTO].ptr;
3901 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3902 r->src.neg, kif, M_GETFIB(m)))
3903 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3904 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3905 r->dst.neg, NULL, M_GETFIB(m)))
3906 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3907 else if (r->tos && !(r->tos == pd->tos))
3908 r = TAILQ_NEXT(r, entries);
3909 else if (r->os_fingerprint != PF_OSFP_ANY)
3910 r = TAILQ_NEXT(r, entries);
3911 else if (pd->proto == IPPROTO_UDP &&
3912 (r->src.port_op || r->dst.port_op))
3913 r = TAILQ_NEXT(r, entries);
3914 else if (pd->proto == IPPROTO_TCP &&
3915 (r->src.port_op || r->dst.port_op || r->flagset))
3916 r = TAILQ_NEXT(r, entries);
3917 else if ((pd->proto == IPPROTO_ICMP ||
3918 pd->proto == IPPROTO_ICMPV6) &&
3919 (r->type || r->code))
3920 r = TAILQ_NEXT(r, entries);
3922 !pf_match_ieee8021q_pcp(r->prio, m))
3923 r = TAILQ_NEXT(r, entries);
3924 else if (r->prob && r->prob <=
3925 (arc4random() % (UINT_MAX - 1) + 1))
3926 r = TAILQ_NEXT(r, entries);
3927 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3928 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3929 r = TAILQ_NEXT(r, entries);
3931 if (r->anchor == NULL) {
3938 r = TAILQ_NEXT(r, entries);
3940 pf_step_into_anchor(anchor_stack, &asd,
3941 &ruleset, PF_RULESET_FILTER, &r, &a,
3944 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3945 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3952 REASON_SET(&reason, PFRES_MATCH);
3955 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3958 if (r->action != PF_PASS)
3961 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3962 REASON_SET(&reason, PFRES_MEMORY);
3970 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3971 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3972 struct pf_pdesc *pd, u_short *reason, int *copyback)
3974 struct tcphdr *th = pd->hdr.tcp;
3975 u_int16_t win = ntohs(th->th_win);
3976 u_int32_t ack, end, seq, orig_seq;
3980 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3981 sws = src->wscale & PF_WSCALE_MASK;
3982 dws = dst->wscale & PF_WSCALE_MASK;
3987 * Sequence tracking algorithm from Guido van Rooij's paper:
3988 * http://www.madison-gurkha.com/publications/tcp_filtering/
3992 orig_seq = seq = ntohl(th->th_seq);
3993 if (src->seqlo == 0) {
3994 /* First packet from this end. Set its state */
3996 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3997 src->scrub == NULL) {
3998 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3999 REASON_SET(reason, PFRES_MEMORY);
4004 /* Deferred generation of sequence number modulator */
4005 if (dst->seqdiff && !src->seqdiff) {
4006 /* use random iss for the TCP server */
4007 while ((src->seqdiff = arc4random() - seq) == 0)
4009 ack = ntohl(th->th_ack) - dst->seqdiff;
4010 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4012 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4015 ack = ntohl(th->th_ack);
4018 end = seq + pd->p_len;
4019 if (th->th_flags & TH_SYN) {
4021 if (dst->wscale & PF_WSCALE_FLAG) {
4022 src->wscale = pf_get_wscale(m, off, th->th_off,
4024 if (src->wscale & PF_WSCALE_FLAG) {
4025 /* Remove scale factor from initial
4027 sws = src->wscale & PF_WSCALE_MASK;
4028 win = ((u_int32_t)win + (1 << sws) - 1)
4030 dws = dst->wscale & PF_WSCALE_MASK;
4032 /* fixup other window */
4033 dst->max_win <<= dst->wscale &
4035 /* in case of a retrans SYN|ACK */
4040 if (th->th_flags & TH_FIN)
4044 if (src->state < TCPS_SYN_SENT)
4045 src->state = TCPS_SYN_SENT;
4048 * May need to slide the window (seqhi may have been set by
4049 * the crappy stack check or if we picked up the connection
4050 * after establishment)
4052 if (src->seqhi == 1 ||
4053 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4054 src->seqhi = end + MAX(1, dst->max_win << dws);
4055 if (win > src->max_win)
4059 ack = ntohl(th->th_ack) - dst->seqdiff;
4061 /* Modulate sequence numbers */
4062 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4064 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4067 end = seq + pd->p_len;
4068 if (th->th_flags & TH_SYN)
4070 if (th->th_flags & TH_FIN)
4074 if ((th->th_flags & TH_ACK) == 0) {
4075 /* Let it pass through the ack skew check */
4077 } else if ((ack == 0 &&
4078 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4079 /* broken tcp stacks do not set ack */
4080 (dst->state < TCPS_SYN_SENT)) {
4082 * Many stacks (ours included) will set the ACK number in an
4083 * FIN|ACK if the SYN times out -- no sequence to ACK.
4089 /* Ease sequencing restrictions on no data packets */
4094 ackskew = dst->seqlo - ack;
4098 * Need to demodulate the sequence numbers in any TCP SACK options
4099 * (Selective ACK). We could optionally validate the SACK values
4100 * against the current ACK window, either forwards or backwards, but
4101 * I'm not confident that SACK has been implemented properly
4102 * everywhere. It wouldn't surprise me if several stacks accidentally
4103 * SACK too far backwards of previously ACKed data. There really aren't
4104 * any security implications of bad SACKing unless the target stack
4105 * doesn't validate the option length correctly. Someone trying to
4106 * spoof into a TCP connection won't bother blindly sending SACK
4109 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4110 if (pf_modulate_sack(m, off, pd, th, dst))
4115 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4116 if (SEQ_GEQ(src->seqhi, end) &&
4117 /* Last octet inside other's window space */
4118 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4119 /* Retrans: not more than one window back */
4120 (ackskew >= -MAXACKWINDOW) &&
4121 /* Acking not more than one reassembled fragment backwards */
4122 (ackskew <= (MAXACKWINDOW << sws)) &&
4123 /* Acking not more than one window forward */
4124 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4125 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4126 (pd->flags & PFDESC_IP_REAS) == 0)) {
4127 /* Require an exact/+1 sequence match on resets when possible */
4129 if (dst->scrub || src->scrub) {
4130 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4131 *state, src, dst, copyback))
4135 /* update max window */
4136 if (src->max_win < win)
4138 /* synchronize sequencing */
4139 if (SEQ_GT(end, src->seqlo))
4141 /* slide the window of what the other end can send */
4142 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4143 dst->seqhi = ack + MAX((win << sws), 1);
4147 if (th->th_flags & TH_SYN)
4148 if (src->state < TCPS_SYN_SENT)
4149 src->state = TCPS_SYN_SENT;
4150 if (th->th_flags & TH_FIN)
4151 if (src->state < TCPS_CLOSING)
4152 src->state = TCPS_CLOSING;
4153 if (th->th_flags & TH_ACK) {
4154 if (dst->state == TCPS_SYN_SENT) {
4155 dst->state = TCPS_ESTABLISHED;
4156 if (src->state == TCPS_ESTABLISHED &&
4157 (*state)->src_node != NULL &&
4158 pf_src_connlimit(state)) {
4159 REASON_SET(reason, PFRES_SRCLIMIT);
4162 } else if (dst->state == TCPS_CLOSING)
4163 dst->state = TCPS_FIN_WAIT_2;
4165 if (th->th_flags & TH_RST)
4166 src->state = dst->state = TCPS_TIME_WAIT;
4168 /* update expire time */
4169 (*state)->expire = time_uptime;
4170 if (src->state >= TCPS_FIN_WAIT_2 &&
4171 dst->state >= TCPS_FIN_WAIT_2)
4172 (*state)->timeout = PFTM_TCP_CLOSED;
4173 else if (src->state >= TCPS_CLOSING &&
4174 dst->state >= TCPS_CLOSING)
4175 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4176 else if (src->state < TCPS_ESTABLISHED ||
4177 dst->state < TCPS_ESTABLISHED)
4178 (*state)->timeout = PFTM_TCP_OPENING;
4179 else if (src->state >= TCPS_CLOSING ||
4180 dst->state >= TCPS_CLOSING)
4181 (*state)->timeout = PFTM_TCP_CLOSING;
4183 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4185 /* Fall through to PASS packet */
4187 } else if ((dst->state < TCPS_SYN_SENT ||
4188 dst->state >= TCPS_FIN_WAIT_2 ||
4189 src->state >= TCPS_FIN_WAIT_2) &&
4190 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4191 /* Within a window forward of the originating packet */
4192 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4193 /* Within a window backward of the originating packet */
4196 * This currently handles three situations:
4197 * 1) Stupid stacks will shotgun SYNs before their peer
4199 * 2) When PF catches an already established stream (the
4200 * firewall rebooted, the state table was flushed, routes
4202 * 3) Packets get funky immediately after the connection
4203 * closes (this should catch Solaris spurious ACK|FINs
4204 * that web servers like to spew after a close)
4206 * This must be a little more careful than the above code
4207 * since packet floods will also be caught here. We don't
4208 * update the TTL here to mitigate the damage of a packet
4209 * flood and so the same code can handle awkward establishment
4210 * and a loosened connection close.
4211 * In the establishment case, a correct peer response will
4212 * validate the connection, go through the normal state code
4213 * and keep updating the state TTL.
4216 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4217 printf("pf: loose state match: ");
4218 pf_print_state(*state);
4219 pf_print_flags(th->th_flags);
4220 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4221 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4222 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4223 (unsigned long long)(*state)->packets[1],
4224 pd->dir == PF_IN ? "in" : "out",
4225 pd->dir == (*state)->direction ? "fwd" : "rev");
4228 if (dst->scrub || src->scrub) {
4229 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4230 *state, src, dst, copyback))
4234 /* update max window */
4235 if (src->max_win < win)
4237 /* synchronize sequencing */
4238 if (SEQ_GT(end, src->seqlo))
4240 /* slide the window of what the other end can send */
4241 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4242 dst->seqhi = ack + MAX((win << sws), 1);
4245 * Cannot set dst->seqhi here since this could be a shotgunned
4246 * SYN and not an already established connection.
4249 if (th->th_flags & TH_FIN)
4250 if (src->state < TCPS_CLOSING)
4251 src->state = TCPS_CLOSING;
4252 if (th->th_flags & TH_RST)
4253 src->state = dst->state = TCPS_TIME_WAIT;
4255 /* Fall through to PASS packet */
4258 if ((*state)->dst.state == TCPS_SYN_SENT &&
4259 (*state)->src.state == TCPS_SYN_SENT) {
4260 /* Send RST for state mismatches during handshake */
4261 if (!(th->th_flags & TH_RST))
4262 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4263 pd->dst, pd->src, th->th_dport,
4264 th->th_sport, ntohl(th->th_ack), 0,
4266 (*state)->rule.ptr->return_ttl, 1, 0,
4271 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4272 printf("pf: BAD state: ");
4273 pf_print_state(*state);
4274 pf_print_flags(th->th_flags);
4275 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4276 "pkts=%llu:%llu dir=%s,%s\n",
4277 seq, orig_seq, ack, pd->p_len, ackskew,
4278 (unsigned long long)(*state)->packets[0],
4279 (unsigned long long)(*state)->packets[1],
4280 pd->dir == PF_IN ? "in" : "out",
4281 pd->dir == (*state)->direction ? "fwd" : "rev");
4282 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4283 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4284 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4286 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4287 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4288 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4289 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4291 REASON_SET(reason, PFRES_BADSTATE);
4299 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4300 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4302 struct tcphdr *th = pd->hdr.tcp;
4304 if (th->th_flags & TH_SYN)
4305 if (src->state < TCPS_SYN_SENT)
4306 src->state = TCPS_SYN_SENT;
4307 if (th->th_flags & TH_FIN)
4308 if (src->state < TCPS_CLOSING)
4309 src->state = TCPS_CLOSING;
4310 if (th->th_flags & TH_ACK) {
4311 if (dst->state == TCPS_SYN_SENT) {
4312 dst->state = TCPS_ESTABLISHED;
4313 if (src->state == TCPS_ESTABLISHED &&
4314 (*state)->src_node != NULL &&
4315 pf_src_connlimit(state)) {
4316 REASON_SET(reason, PFRES_SRCLIMIT);
4319 } else if (dst->state == TCPS_CLOSING) {
4320 dst->state = TCPS_FIN_WAIT_2;
4321 } else if (src->state == TCPS_SYN_SENT &&
4322 dst->state < TCPS_SYN_SENT) {
4324 * Handle a special sloppy case where we only see one
4325 * half of the connection. If there is a ACK after
4326 * the initial SYN without ever seeing a packet from
4327 * the destination, set the connection to established.
4329 dst->state = src->state = TCPS_ESTABLISHED;
4330 if ((*state)->src_node != NULL &&
4331 pf_src_connlimit(state)) {
4332 REASON_SET(reason, PFRES_SRCLIMIT);
4335 } else if (src->state == TCPS_CLOSING &&
4336 dst->state == TCPS_ESTABLISHED &&
4339 * Handle the closing of half connections where we
4340 * don't see the full bidirectional FIN/ACK+ACK
4343 dst->state = TCPS_CLOSING;
4346 if (th->th_flags & TH_RST)
4347 src->state = dst->state = TCPS_TIME_WAIT;
4349 /* update expire time */
4350 (*state)->expire = time_uptime;
4351 if (src->state >= TCPS_FIN_WAIT_2 &&
4352 dst->state >= TCPS_FIN_WAIT_2)
4353 (*state)->timeout = PFTM_TCP_CLOSED;
4354 else if (src->state >= TCPS_CLOSING &&
4355 dst->state >= TCPS_CLOSING)
4356 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4357 else if (src->state < TCPS_ESTABLISHED ||
4358 dst->state < TCPS_ESTABLISHED)
4359 (*state)->timeout = PFTM_TCP_OPENING;
4360 else if (src->state >= TCPS_CLOSING ||
4361 dst->state >= TCPS_CLOSING)
4362 (*state)->timeout = PFTM_TCP_CLOSING;
4364 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4370 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4371 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4374 struct pf_state_key_cmp key;
4375 struct tcphdr *th = pd->hdr.tcp;
4377 struct pf_state_peer *src, *dst;
4378 struct pf_state_key *sk;
4380 bzero(&key, sizeof(key));
4382 key.proto = IPPROTO_TCP;
4383 if (direction == PF_IN) { /* wire side, straight */
4384 PF_ACPY(&key.addr[0], pd->src, key.af);
4385 PF_ACPY(&key.addr[1], pd->dst, key.af);
4386 key.port[0] = th->th_sport;
4387 key.port[1] = th->th_dport;
4388 } else { /* stack side, reverse */
4389 PF_ACPY(&key.addr[1], pd->src, key.af);
4390 PF_ACPY(&key.addr[0], pd->dst, key.af);
4391 key.port[1] = th->th_sport;
4392 key.port[0] = th->th_dport;
4395 STATE_LOOKUP(kif, &key, direction, *state, pd);
4397 if (direction == (*state)->direction) {
4398 src = &(*state)->src;
4399 dst = &(*state)->dst;
4401 src = &(*state)->dst;
4402 dst = &(*state)->src;
4405 sk = (*state)->key[pd->didx];
4407 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4408 if (direction != (*state)->direction) {
4409 REASON_SET(reason, PFRES_SYNPROXY);
4410 return (PF_SYNPROXY_DROP);
4412 if (th->th_flags & TH_SYN) {
4413 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4414 REASON_SET(reason, PFRES_SYNPROXY);
4417 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4418 pd->src, th->th_dport, th->th_sport,
4419 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4420 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4421 REASON_SET(reason, PFRES_SYNPROXY);
4422 return (PF_SYNPROXY_DROP);
4423 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4424 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4425 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4426 REASON_SET(reason, PFRES_SYNPROXY);
4428 } else if ((*state)->src_node != NULL &&
4429 pf_src_connlimit(state)) {
4430 REASON_SET(reason, PFRES_SRCLIMIT);
4433 (*state)->src.state = PF_TCPS_PROXY_DST;
4435 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4436 if (direction == (*state)->direction) {
4437 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4438 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4439 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4440 REASON_SET(reason, PFRES_SYNPROXY);
4443 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4444 if ((*state)->dst.seqhi == 1)
4445 (*state)->dst.seqhi = htonl(arc4random());
4446 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4447 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4448 sk->port[pd->sidx], sk->port[pd->didx],
4449 (*state)->dst.seqhi, 0, TH_SYN, 0,
4450 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4451 REASON_SET(reason, PFRES_SYNPROXY);
4452 return (PF_SYNPROXY_DROP);
4453 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4455 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4456 REASON_SET(reason, PFRES_SYNPROXY);
4459 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4460 (*state)->dst.seqlo = ntohl(th->th_seq);
4461 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4462 pd->src, th->th_dport, th->th_sport,
4463 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4464 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4465 (*state)->tag, NULL);
4466 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4467 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4468 sk->port[pd->sidx], sk->port[pd->didx],
4469 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4470 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4471 (*state)->src.seqdiff = (*state)->dst.seqhi -
4472 (*state)->src.seqlo;
4473 (*state)->dst.seqdiff = (*state)->src.seqhi -
4474 (*state)->dst.seqlo;
4475 (*state)->src.seqhi = (*state)->src.seqlo +
4476 (*state)->dst.max_win;
4477 (*state)->dst.seqhi = (*state)->dst.seqlo +
4478 (*state)->src.max_win;
4479 (*state)->src.wscale = (*state)->dst.wscale = 0;
4480 (*state)->src.state = (*state)->dst.state =
4482 REASON_SET(reason, PFRES_SYNPROXY);
4483 return (PF_SYNPROXY_DROP);
4487 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4488 dst->state >= TCPS_FIN_WAIT_2 &&
4489 src->state >= TCPS_FIN_WAIT_2) {
4490 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4491 printf("pf: state reuse ");
4492 pf_print_state(*state);
4493 pf_print_flags(th->th_flags);
4496 /* XXX make sure it's the same direction ?? */
4497 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4498 pf_unlink_state(*state, PF_ENTER_LOCKED);
4503 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4504 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4507 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4508 ©back) == PF_DROP)
4512 /* translate source/destination address, if necessary */
4513 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4514 struct pf_state_key *nk = (*state)->key[pd->didx];
4516 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4517 nk->port[pd->sidx] != th->th_sport)
4518 pf_change_ap(m, pd->src, &th->th_sport,
4519 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4520 nk->port[pd->sidx], 0, pd->af);
4522 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4523 nk->port[pd->didx] != th->th_dport)
4524 pf_change_ap(m, pd->dst, &th->th_dport,
4525 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4526 nk->port[pd->didx], 0, pd->af);
4530 /* Copyback sequence modulation or stateful scrub changes if needed */
4532 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4538 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4539 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4541 struct pf_state_peer *src, *dst;
4542 struct pf_state_key_cmp key;
4543 struct udphdr *uh = pd->hdr.udp;
4545 bzero(&key, sizeof(key));
4547 key.proto = IPPROTO_UDP;
4548 if (direction == PF_IN) { /* wire side, straight */
4549 PF_ACPY(&key.addr[0], pd->src, key.af);
4550 PF_ACPY(&key.addr[1], pd->dst, key.af);
4551 key.port[0] = uh->uh_sport;
4552 key.port[1] = uh->uh_dport;
4553 } else { /* stack side, reverse */
4554 PF_ACPY(&key.addr[1], pd->src, key.af);
4555 PF_ACPY(&key.addr[0], pd->dst, key.af);
4556 key.port[1] = uh->uh_sport;
4557 key.port[0] = uh->uh_dport;
4560 STATE_LOOKUP(kif, &key, direction, *state, pd);
4562 if (direction == (*state)->direction) {
4563 src = &(*state)->src;
4564 dst = &(*state)->dst;
4566 src = &(*state)->dst;
4567 dst = &(*state)->src;
4571 if (src->state < PFUDPS_SINGLE)
4572 src->state = PFUDPS_SINGLE;
4573 if (dst->state == PFUDPS_SINGLE)
4574 dst->state = PFUDPS_MULTIPLE;
4576 /* update expire time */
4577 (*state)->expire = time_uptime;
4578 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4579 (*state)->timeout = PFTM_UDP_MULTIPLE;
4581 (*state)->timeout = PFTM_UDP_SINGLE;
4583 /* translate source/destination address, if necessary */
4584 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4585 struct pf_state_key *nk = (*state)->key[pd->didx];
4587 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4588 nk->port[pd->sidx] != uh->uh_sport)
4589 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4590 &uh->uh_sum, &nk->addr[pd->sidx],
4591 nk->port[pd->sidx], 1, pd->af);
4593 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4594 nk->port[pd->didx] != uh->uh_dport)
4595 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4596 &uh->uh_sum, &nk->addr[pd->didx],
4597 nk->port[pd->didx], 1, pd->af);
4598 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4605 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4606 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4608 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4609 u_int16_t icmpid = 0, *icmpsum;
4610 u_int8_t icmptype, icmpcode;
4612 struct pf_state_key_cmp key;
4614 bzero(&key, sizeof(key));
4615 switch (pd->proto) {
4618 icmptype = pd->hdr.icmp->icmp_type;
4619 icmpcode = pd->hdr.icmp->icmp_code;
4620 icmpid = pd->hdr.icmp->icmp_id;
4621 icmpsum = &pd->hdr.icmp->icmp_cksum;
4623 if (icmptype == ICMP_UNREACH ||
4624 icmptype == ICMP_SOURCEQUENCH ||
4625 icmptype == ICMP_REDIRECT ||
4626 icmptype == ICMP_TIMXCEED ||
4627 icmptype == ICMP_PARAMPROB)
4632 case IPPROTO_ICMPV6:
4633 icmptype = pd->hdr.icmp6->icmp6_type;
4634 icmpcode = pd->hdr.icmp6->icmp6_code;
4635 icmpid = pd->hdr.icmp6->icmp6_id;
4636 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4638 if (icmptype == ICMP6_DST_UNREACH ||
4639 icmptype == ICMP6_PACKET_TOO_BIG ||
4640 icmptype == ICMP6_TIME_EXCEEDED ||
4641 icmptype == ICMP6_PARAM_PROB)
4650 * ICMP query/reply message not related to a TCP/UDP packet.
4651 * Search for an ICMP state.
4654 key.proto = pd->proto;
4655 key.port[0] = key.port[1] = icmpid;
4656 if (direction == PF_IN) { /* wire side, straight */
4657 PF_ACPY(&key.addr[0], pd->src, key.af);
4658 PF_ACPY(&key.addr[1], pd->dst, key.af);
4659 } else { /* stack side, reverse */
4660 PF_ACPY(&key.addr[1], pd->src, key.af);
4661 PF_ACPY(&key.addr[0], pd->dst, key.af);
4664 STATE_LOOKUP(kif, &key, direction, *state, pd);
4666 (*state)->expire = time_uptime;
4667 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4669 /* translate source/destination address, if necessary */
4670 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4671 struct pf_state_key *nk = (*state)->key[pd->didx];
4676 if (PF_ANEQ(pd->src,
4677 &nk->addr[pd->sidx], AF_INET))
4678 pf_change_a(&saddr->v4.s_addr,
4680 nk->addr[pd->sidx].v4.s_addr, 0);
4682 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4684 pf_change_a(&daddr->v4.s_addr,
4686 nk->addr[pd->didx].v4.s_addr, 0);
4689 pd->hdr.icmp->icmp_id) {
4690 pd->hdr.icmp->icmp_cksum =
4692 pd->hdr.icmp->icmp_cksum, icmpid,
4693 nk->port[pd->sidx], 0);
4694 pd->hdr.icmp->icmp_id =
4698 m_copyback(m, off, ICMP_MINLEN,
4699 (caddr_t )pd->hdr.icmp);
4704 if (PF_ANEQ(pd->src,
4705 &nk->addr[pd->sidx], AF_INET6))
4707 &pd->hdr.icmp6->icmp6_cksum,
4708 &nk->addr[pd->sidx], 0);
4710 if (PF_ANEQ(pd->dst,
4711 &nk->addr[pd->didx], AF_INET6))
4713 &pd->hdr.icmp6->icmp6_cksum,
4714 &nk->addr[pd->didx], 0);
4716 m_copyback(m, off, sizeof(struct icmp6_hdr),
4717 (caddr_t )pd->hdr.icmp6);
4726 * ICMP error message in response to a TCP/UDP packet.
4727 * Extract the inner TCP/UDP header and search for that state.
4730 struct pf_pdesc pd2;
4731 bzero(&pd2, sizeof pd2);
4736 struct ip6_hdr h2_6;
4743 /* Payload packet is from the opposite direction. */
4744 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4745 pd2.didx = (direction == PF_IN) ? 0 : 1;
4749 /* offset of h2 in mbuf chain */
4750 ipoff2 = off + ICMP_MINLEN;
4752 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4753 NULL, reason, pd2.af)) {
4754 DPFPRINTF(PF_DEBUG_MISC,
4755 ("pf: ICMP error message too short "
4760 * ICMP error messages don't refer to non-first
4763 if (h2.ip_off & htons(IP_OFFMASK)) {
4764 REASON_SET(reason, PFRES_FRAG);
4768 /* offset of protocol header that follows h2 */
4769 off2 = ipoff2 + (h2.ip_hl << 2);
4771 pd2.proto = h2.ip_p;
4772 pd2.src = (struct pf_addr *)&h2.ip_src;
4773 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4774 pd2.ip_sum = &h2.ip_sum;
4779 ipoff2 = off + sizeof(struct icmp6_hdr);
4781 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4782 NULL, reason, pd2.af)) {
4783 DPFPRINTF(PF_DEBUG_MISC,
4784 ("pf: ICMP error message too short "
4788 pd2.proto = h2_6.ip6_nxt;
4789 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4790 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4792 off2 = ipoff2 + sizeof(h2_6);
4794 switch (pd2.proto) {
4795 case IPPROTO_FRAGMENT:
4797 * ICMPv6 error messages for
4798 * non-first fragments
4800 REASON_SET(reason, PFRES_FRAG);
4803 case IPPROTO_HOPOPTS:
4804 case IPPROTO_ROUTING:
4805 case IPPROTO_DSTOPTS: {
4806 /* get next header and header length */
4807 struct ip6_ext opt6;
4809 if (!pf_pull_hdr(m, off2, &opt6,
4810 sizeof(opt6), NULL, reason,
4812 DPFPRINTF(PF_DEBUG_MISC,
4813 ("pf: ICMPv6 short opt\n"));
4816 if (pd2.proto == IPPROTO_AH)
4817 off2 += (opt6.ip6e_len + 2) * 4;
4819 off2 += (opt6.ip6e_len + 1) * 8;
4820 pd2.proto = opt6.ip6e_nxt;
4821 /* goto the next header */
4828 } while (!terminal);
4833 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4834 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4835 printf("pf: BAD ICMP %d:%d outer dst: ",
4836 icmptype, icmpcode);
4837 pf_print_host(pd->src, 0, pd->af);
4839 pf_print_host(pd->dst, 0, pd->af);
4840 printf(" inner src: ");
4841 pf_print_host(pd2.src, 0, pd2.af);
4843 pf_print_host(pd2.dst, 0, pd2.af);
4846 REASON_SET(reason, PFRES_BADSTATE);
4850 switch (pd2.proto) {
4854 struct pf_state_peer *src, *dst;
4859 * Only the first 8 bytes of the TCP header can be
4860 * expected. Don't access any TCP header fields after
4861 * th_seq, an ackskew test is not possible.
4863 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4865 DPFPRINTF(PF_DEBUG_MISC,
4866 ("pf: ICMP error message too short "
4872 key.proto = IPPROTO_TCP;
4873 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4874 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4875 key.port[pd2.sidx] = th.th_sport;
4876 key.port[pd2.didx] = th.th_dport;
4878 STATE_LOOKUP(kif, &key, direction, *state, pd);
4880 if (direction == (*state)->direction) {
4881 src = &(*state)->dst;
4882 dst = &(*state)->src;
4884 src = &(*state)->src;
4885 dst = &(*state)->dst;
4888 if (src->wscale && dst->wscale)
4889 dws = dst->wscale & PF_WSCALE_MASK;
4893 /* Demodulate sequence number */
4894 seq = ntohl(th.th_seq) - src->seqdiff;
4896 pf_change_a(&th.th_seq, icmpsum,
4901 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4902 (!SEQ_GEQ(src->seqhi, seq) ||
4903 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4904 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4905 printf("pf: BAD ICMP %d:%d ",
4906 icmptype, icmpcode);
4907 pf_print_host(pd->src, 0, pd->af);
4909 pf_print_host(pd->dst, 0, pd->af);
4911 pf_print_state(*state);
4912 printf(" seq=%u\n", seq);
4914 REASON_SET(reason, PFRES_BADSTATE);
4917 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4918 printf("pf: OK ICMP %d:%d ",
4919 icmptype, icmpcode);
4920 pf_print_host(pd->src, 0, pd->af);
4922 pf_print_host(pd->dst, 0, pd->af);
4924 pf_print_state(*state);
4925 printf(" seq=%u\n", seq);
4929 /* translate source/destination address, if necessary */
4930 if ((*state)->key[PF_SK_WIRE] !=
4931 (*state)->key[PF_SK_STACK]) {
4932 struct pf_state_key *nk =
4933 (*state)->key[pd->didx];
4935 if (PF_ANEQ(pd2.src,
4936 &nk->addr[pd2.sidx], pd2.af) ||
4937 nk->port[pd2.sidx] != th.th_sport)
4938 pf_change_icmp(pd2.src, &th.th_sport,
4939 daddr, &nk->addr[pd2.sidx],
4940 nk->port[pd2.sidx], NULL,
4941 pd2.ip_sum, icmpsum,
4942 pd->ip_sum, 0, pd2.af);
4944 if (PF_ANEQ(pd2.dst,
4945 &nk->addr[pd2.didx], pd2.af) ||
4946 nk->port[pd2.didx] != th.th_dport)
4947 pf_change_icmp(pd2.dst, &th.th_dport,
4948 saddr, &nk->addr[pd2.didx],
4949 nk->port[pd2.didx], NULL,
4950 pd2.ip_sum, icmpsum,
4951 pd->ip_sum, 0, pd2.af);
4959 m_copyback(m, off, ICMP_MINLEN,
4960 (caddr_t )pd->hdr.icmp);
4961 m_copyback(m, ipoff2, sizeof(h2),
4968 sizeof(struct icmp6_hdr),
4969 (caddr_t )pd->hdr.icmp6);
4970 m_copyback(m, ipoff2, sizeof(h2_6),
4975 m_copyback(m, off2, 8, (caddr_t)&th);
4984 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4985 NULL, reason, pd2.af)) {
4986 DPFPRINTF(PF_DEBUG_MISC,
4987 ("pf: ICMP error message too short "
4993 key.proto = IPPROTO_UDP;
4994 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4995 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4996 key.port[pd2.sidx] = uh.uh_sport;
4997 key.port[pd2.didx] = uh.uh_dport;
4999 STATE_LOOKUP(kif, &key, direction, *state, pd);
5001 /* translate source/destination address, if necessary */
5002 if ((*state)->key[PF_SK_WIRE] !=
5003 (*state)->key[PF_SK_STACK]) {
5004 struct pf_state_key *nk =
5005 (*state)->key[pd->didx];
5007 if (PF_ANEQ(pd2.src,
5008 &nk->addr[pd2.sidx], pd2.af) ||
5009 nk->port[pd2.sidx] != uh.uh_sport)
5010 pf_change_icmp(pd2.src, &uh.uh_sport,
5011 daddr, &nk->addr[pd2.sidx],
5012 nk->port[pd2.sidx], &uh.uh_sum,
5013 pd2.ip_sum, icmpsum,
5014 pd->ip_sum, 1, pd2.af);
5016 if (PF_ANEQ(pd2.dst,
5017 &nk->addr[pd2.didx], pd2.af) ||
5018 nk->port[pd2.didx] != uh.uh_dport)
5019 pf_change_icmp(pd2.dst, &uh.uh_dport,
5020 saddr, &nk->addr[pd2.didx],
5021 nk->port[pd2.didx], &uh.uh_sum,
5022 pd2.ip_sum, icmpsum,
5023 pd->ip_sum, 1, pd2.af);
5028 m_copyback(m, off, ICMP_MINLEN,
5029 (caddr_t )pd->hdr.icmp);
5030 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5036 sizeof(struct icmp6_hdr),
5037 (caddr_t )pd->hdr.icmp6);
5038 m_copyback(m, ipoff2, sizeof(h2_6),
5043 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5049 case IPPROTO_ICMP: {
5052 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5053 NULL, reason, pd2.af)) {
5054 DPFPRINTF(PF_DEBUG_MISC,
5055 ("pf: ICMP error message too short i"
5061 key.proto = IPPROTO_ICMP;
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] = iih.icmp_id;
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 nk->port[pd2.sidx] != iih.icmp_id)
5077 pf_change_icmp(pd2.src, &iih.icmp_id,
5078 daddr, &nk->addr[pd2.sidx],
5079 nk->port[pd2.sidx], NULL,
5080 pd2.ip_sum, icmpsum,
5081 pd->ip_sum, 0, AF_INET);
5083 if (PF_ANEQ(pd2.dst,
5084 &nk->addr[pd2.didx], pd2.af) ||
5085 nk->port[pd2.didx] != iih.icmp_id)
5086 pf_change_icmp(pd2.dst, &iih.icmp_id,
5087 saddr, &nk->addr[pd2.didx],
5088 nk->port[pd2.didx], NULL,
5089 pd2.ip_sum, icmpsum,
5090 pd->ip_sum, 0, AF_INET);
5092 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5093 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5094 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5101 case IPPROTO_ICMPV6: {
5102 struct icmp6_hdr iih;
5104 if (!pf_pull_hdr(m, off2, &iih,
5105 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5106 DPFPRINTF(PF_DEBUG_MISC,
5107 ("pf: ICMP error message too short "
5113 key.proto = IPPROTO_ICMPV6;
5114 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5115 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5116 key.port[0] = key.port[1] = iih.icmp6_id;
5118 STATE_LOOKUP(kif, &key, direction, *state, pd);
5120 /* translate source/destination address, if necessary */
5121 if ((*state)->key[PF_SK_WIRE] !=
5122 (*state)->key[PF_SK_STACK]) {
5123 struct pf_state_key *nk =
5124 (*state)->key[pd->didx];
5126 if (PF_ANEQ(pd2.src,
5127 &nk->addr[pd2.sidx], pd2.af) ||
5128 nk->port[pd2.sidx] != iih.icmp6_id)
5129 pf_change_icmp(pd2.src, &iih.icmp6_id,
5130 daddr, &nk->addr[pd2.sidx],
5131 nk->port[pd2.sidx], NULL,
5132 pd2.ip_sum, icmpsum,
5133 pd->ip_sum, 0, AF_INET6);
5135 if (PF_ANEQ(pd2.dst,
5136 &nk->addr[pd2.didx], pd2.af) ||
5137 nk->port[pd2.didx] != iih.icmp6_id)
5138 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5139 saddr, &nk->addr[pd2.didx],
5140 nk->port[pd2.didx], NULL,
5141 pd2.ip_sum, icmpsum,
5142 pd->ip_sum, 0, AF_INET6);
5144 m_copyback(m, off, sizeof(struct icmp6_hdr),
5145 (caddr_t)pd->hdr.icmp6);
5146 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5147 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5156 key.proto = pd2.proto;
5157 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5158 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5159 key.port[0] = key.port[1] = 0;
5161 STATE_LOOKUP(kif, &key, direction, *state, pd);
5163 /* translate source/destination address, if necessary */
5164 if ((*state)->key[PF_SK_WIRE] !=
5165 (*state)->key[PF_SK_STACK]) {
5166 struct pf_state_key *nk =
5167 (*state)->key[pd->didx];
5169 if (PF_ANEQ(pd2.src,
5170 &nk->addr[pd2.sidx], pd2.af))
5171 pf_change_icmp(pd2.src, NULL, daddr,
5172 &nk->addr[pd2.sidx], 0, NULL,
5173 pd2.ip_sum, icmpsum,
5174 pd->ip_sum, 0, pd2.af);
5176 if (PF_ANEQ(pd2.dst,
5177 &nk->addr[pd2.didx], pd2.af))
5178 pf_change_icmp(pd2.dst, NULL, saddr,
5179 &nk->addr[pd2.didx], 0, NULL,
5180 pd2.ip_sum, icmpsum,
5181 pd->ip_sum, 0, pd2.af);
5186 m_copyback(m, off, ICMP_MINLEN,
5187 (caddr_t)pd->hdr.icmp);
5188 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5194 sizeof(struct icmp6_hdr),
5195 (caddr_t )pd->hdr.icmp6);
5196 m_copyback(m, ipoff2, sizeof(h2_6),
5210 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5211 struct mbuf *m, struct pf_pdesc *pd)
5213 struct pf_state_peer *src, *dst;
5214 struct pf_state_key_cmp key;
5216 bzero(&key, sizeof(key));
5218 key.proto = pd->proto;
5219 if (direction == PF_IN) {
5220 PF_ACPY(&key.addr[0], pd->src, key.af);
5221 PF_ACPY(&key.addr[1], pd->dst, key.af);
5222 key.port[0] = key.port[1] = 0;
5224 PF_ACPY(&key.addr[1], pd->src, key.af);
5225 PF_ACPY(&key.addr[0], pd->dst, key.af);
5226 key.port[1] = key.port[0] = 0;
5229 STATE_LOOKUP(kif, &key, direction, *state, pd);
5231 if (direction == (*state)->direction) {
5232 src = &(*state)->src;
5233 dst = &(*state)->dst;
5235 src = &(*state)->dst;
5236 dst = &(*state)->src;
5240 if (src->state < PFOTHERS_SINGLE)
5241 src->state = PFOTHERS_SINGLE;
5242 if (dst->state == PFOTHERS_SINGLE)
5243 dst->state = PFOTHERS_MULTIPLE;
5245 /* update expire time */
5246 (*state)->expire = time_uptime;
5247 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5248 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5250 (*state)->timeout = PFTM_OTHER_SINGLE;
5252 /* translate source/destination address, if necessary */
5253 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5254 struct pf_state_key *nk = (*state)->key[pd->didx];
5256 KASSERT(nk, ("%s: nk is null", __func__));
5257 KASSERT(pd, ("%s: pd is null", __func__));
5258 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5259 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5263 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5264 pf_change_a(&pd->src->v4.s_addr,
5266 nk->addr[pd->sidx].v4.s_addr,
5270 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5271 pf_change_a(&pd->dst->v4.s_addr,
5273 nk->addr[pd->didx].v4.s_addr,
5280 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5281 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5283 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5284 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5292 * ipoff and off are measured from the start of the mbuf chain.
5293 * h must be at "ipoff" on the mbuf chain.
5296 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5297 u_short *actionp, u_short *reasonp, sa_family_t af)
5302 struct ip *h = mtod(m, struct ip *);
5303 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5307 ACTION_SET(actionp, PF_PASS);
5309 ACTION_SET(actionp, PF_DROP);
5310 REASON_SET(reasonp, PFRES_FRAG);
5314 if (m->m_pkthdr.len < off + len ||
5315 ntohs(h->ip_len) < off + len) {
5316 ACTION_SET(actionp, PF_DROP);
5317 REASON_SET(reasonp, PFRES_SHORT);
5325 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5327 if (m->m_pkthdr.len < off + len ||
5328 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5329 (unsigned)(off + len)) {
5330 ACTION_SET(actionp, PF_DROP);
5331 REASON_SET(reasonp, PFRES_SHORT);
5338 m_copydata(m, off, len, p);
5343 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5349 * Skip check for addresses with embedded interface scope,
5350 * as they would always match anyway.
5352 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5355 if (af != AF_INET && af != AF_INET6)
5358 /* Skip checks for ipsec interfaces */
5359 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5362 ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
5367 return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
5372 return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
5382 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5383 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5385 struct mbuf *m0, *m1;
5386 struct sockaddr_in dst;
5388 struct ifnet *ifp = NULL;
5389 struct pf_addr naddr;
5390 struct pf_src_node *sn = NULL;
5392 uint16_t ip_len, ip_off;
5394 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5395 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5398 if ((pd->pf_mtag == NULL &&
5399 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5400 pd->pf_mtag->routed++ > 3) {
5406 if (r->rt == PF_DUPTO) {
5407 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5413 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5421 ip = mtod(m0, struct ip *);
5423 bzero(&dst, sizeof(dst));
5424 dst.sin_family = AF_INET;
5425 dst.sin_len = sizeof(dst);
5426 dst.sin_addr = ip->ip_dst;
5428 bzero(&naddr, sizeof(naddr));
5430 if (TAILQ_EMPTY(&r->rpool.list)) {
5431 DPFPRINTF(PF_DEBUG_URGENT,
5432 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5436 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5438 if (!PF_AZERO(&naddr, AF_INET))
5439 dst.sin_addr.s_addr = naddr.v4.s_addr;
5440 ifp = r->rpool.cur->kif ?
5441 r->rpool.cur->kif->pfik_ifp : NULL;
5443 if (!PF_AZERO(&s->rt_addr, AF_INET))
5444 dst.sin_addr.s_addr =
5445 s->rt_addr.v4.s_addr;
5446 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5453 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5455 else if (m0 == NULL)
5457 if (m0->m_len < sizeof(struct ip)) {
5458 DPFPRINTF(PF_DEBUG_URGENT,
5459 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5462 ip = mtod(m0, struct ip *);
5465 if (ifp->if_flags & IFF_LOOPBACK)
5466 m0->m_flags |= M_SKIP_FIREWALL;
5468 ip_len = ntohs(ip->ip_len);
5469 ip_off = ntohs(ip->ip_off);
5471 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5472 m0->m_pkthdr.csum_flags |= CSUM_IP;
5473 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5474 in_delayed_cksum(m0);
5475 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5477 #if defined(SCTP) || defined(SCTP_SUPPORT)
5478 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5479 sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
5480 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5485 * If small enough for interface, or the interface will take
5486 * care of the fragmentation for us, we can just send directly.
5488 if (ip_len <= ifp->if_mtu ||
5489 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5491 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5492 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5493 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5495 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5496 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5500 /* Balk when DF bit is set or the interface didn't support TSO. */
5501 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5503 KMOD_IPSTAT_INC(ips_cantfrag);
5504 if (r->rt != PF_DUPTO) {
5505 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5512 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5516 for (; m0; m0 = m1) {
5518 m0->m_nextpkt = NULL;
5520 m_clrprotoflags(m0);
5521 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5527 KMOD_IPSTAT_INC(ips_fragmented);
5530 if (r->rt != PF_DUPTO)
5545 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5546 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5549 struct sockaddr_in6 dst;
5550 struct ip6_hdr *ip6;
5551 struct ifnet *ifp = NULL;
5552 struct pf_addr naddr;
5553 struct pf_src_node *sn = NULL;
5555 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5556 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5559 if ((pd->pf_mtag == NULL &&
5560 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5561 pd->pf_mtag->routed++ > 3) {
5567 if (r->rt == PF_DUPTO) {
5568 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5574 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5582 ip6 = mtod(m0, struct ip6_hdr *);
5584 bzero(&dst, sizeof(dst));
5585 dst.sin6_family = AF_INET6;
5586 dst.sin6_len = sizeof(dst);
5587 dst.sin6_addr = ip6->ip6_dst;
5589 bzero(&naddr, sizeof(naddr));
5591 if (TAILQ_EMPTY(&r->rpool.list)) {
5592 DPFPRINTF(PF_DEBUG_URGENT,
5593 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5597 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5599 if (!PF_AZERO(&naddr, AF_INET6))
5600 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5602 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5604 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5605 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5606 &s->rt_addr, AF_INET6);
5607 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5617 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5619 else if (m0 == NULL)
5621 if (m0->m_len < sizeof(struct ip6_hdr)) {
5622 DPFPRINTF(PF_DEBUG_URGENT,
5623 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5627 ip6 = mtod(m0, struct ip6_hdr *);
5630 if (ifp->if_flags & IFF_LOOPBACK)
5631 m0->m_flags |= M_SKIP_FIREWALL;
5633 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5634 ~ifp->if_hwassist) {
5635 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5636 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5637 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5641 * If the packet is too large for the outgoing interface,
5642 * send back an icmp6 error.
5644 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5645 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5646 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5647 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5649 in6_ifstat_inc(ifp, ifs6_in_toobig);
5650 if (r->rt != PF_DUPTO)
5651 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5657 if (r->rt != PF_DUPTO)
5671 * FreeBSD supports cksum offloads for the following drivers.
5672 * em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5674 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5675 * network driver performed cksum including pseudo header, need to verify
5678 * network driver performed cksum, needs to additional pseudo header
5679 * cksum computation with partial csum_data(i.e. lack of H/W support for
5680 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5682 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5683 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5685 * Also, set csum_data to 0xffff to force cksum validation.
5688 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5694 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5696 if (m->m_pkthdr.len < off + len)
5701 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5702 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5703 sum = m->m_pkthdr.csum_data;
5705 ip = mtod(m, struct ip *);
5706 sum = in_pseudo(ip->ip_src.s_addr,
5707 ip->ip_dst.s_addr, htonl((u_short)len +
5708 m->m_pkthdr.csum_data + IPPROTO_TCP));
5715 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5716 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5717 sum = m->m_pkthdr.csum_data;
5719 ip = mtod(m, struct ip *);
5720 sum = in_pseudo(ip->ip_src.s_addr,
5721 ip->ip_dst.s_addr, htonl((u_short)len +
5722 m->m_pkthdr.csum_data + IPPROTO_UDP));
5730 case IPPROTO_ICMPV6:
5740 if (p == IPPROTO_ICMP) {
5745 sum = in_cksum(m, len);
5749 if (m->m_len < sizeof(struct ip))
5751 sum = in4_cksum(m, p, off, len);
5756 if (m->m_len < sizeof(struct ip6_hdr))
5758 sum = in6_cksum(m, p, off, len);
5769 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5774 KMOD_UDPSTAT_INC(udps_badsum);
5780 KMOD_ICMPSTAT_INC(icps_checksum);
5785 case IPPROTO_ICMPV6:
5787 KMOD_ICMP6STAT_INC(icp6s_checksum);
5794 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5795 m->m_pkthdr.csum_flags |=
5796 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5797 m->m_pkthdr.csum_data = 0xffff;
5806 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5808 struct pfi_kif *kif;
5809 u_short action, reason = 0, log = 0;
5810 struct mbuf *m = *m0;
5811 struct ip *h = NULL;
5812 struct m_tag *ipfwtag;
5813 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5814 struct pf_state *s = NULL;
5815 struct pf_ruleset *ruleset = NULL;
5817 int off, dirndx, pqid = 0;
5819 PF_RULES_RLOCK_TRACKER;
5823 if (!V_pf_status.running)
5826 memset(&pd, 0, sizeof(pd));
5828 kif = (struct pfi_kif *)ifp->if_pf_kif;
5831 DPFPRINTF(PF_DEBUG_URGENT,
5832 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5835 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5838 if (m->m_flags & M_SKIP_FIREWALL)
5841 pd.pf_mtag = pf_find_mtag(m);
5845 if (ip_divert_ptr != NULL &&
5846 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5847 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5848 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5849 if (pd.pf_mtag == NULL &&
5850 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5854 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5855 m_tag_delete(m, ipfwtag);
5857 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5858 m->m_flags |= M_FASTFWD_OURS;
5859 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5861 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5862 /* We do IP header normalization and packet reassembly here */
5866 m = *m0; /* pf_normalize messes with m0 */
5867 h = mtod(m, struct ip *);
5869 off = h->ip_hl << 2;
5870 if (off < (int)sizeof(struct ip)) {
5872 REASON_SET(&reason, PFRES_SHORT);
5877 pd.src = (struct pf_addr *)&h->ip_src;
5878 pd.dst = (struct pf_addr *)&h->ip_dst;
5879 pd.sport = pd.dport = NULL;
5880 pd.ip_sum = &h->ip_sum;
5881 pd.proto_sum = NULL;
5884 pd.sidx = (dir == PF_IN) ? 0 : 1;
5885 pd.didx = (dir == PF_IN) ? 1 : 0;
5887 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5888 pd.tot_len = ntohs(h->ip_len);
5890 /* handle fragments that didn't get reassembled by normalization */
5891 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5892 action = pf_test_fragment(&r, dir, kif, m, h,
5903 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5904 &action, &reason, AF_INET)) {
5905 log = action != PF_PASS;
5908 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5909 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5911 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5912 if (action == PF_DROP)
5914 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5916 if (action == PF_PASS) {
5917 if (V_pfsync_update_state_ptr != NULL)
5918 V_pfsync_update_state_ptr(s);
5922 } else if (s == NULL)
5923 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5932 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5933 &action, &reason, AF_INET)) {
5934 log = action != PF_PASS;
5937 if (uh.uh_dport == 0 ||
5938 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5939 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5941 REASON_SET(&reason, PFRES_SHORT);
5944 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5945 if (action == PF_PASS) {
5946 if (V_pfsync_update_state_ptr != NULL)
5947 V_pfsync_update_state_ptr(s);
5951 } else if (s == NULL)
5952 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5957 case IPPROTO_ICMP: {
5961 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5962 &action, &reason, AF_INET)) {
5963 log = action != PF_PASS;
5966 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5968 if (action == PF_PASS) {
5969 if (V_pfsync_update_state_ptr != NULL)
5970 V_pfsync_update_state_ptr(s);
5974 } else if (s == NULL)
5975 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5981 case IPPROTO_ICMPV6: {
5983 DPFPRINTF(PF_DEBUG_MISC,
5984 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5990 action = pf_test_state_other(&s, dir, kif, m, &pd);
5991 if (action == PF_PASS) {
5992 if (V_pfsync_update_state_ptr != NULL)
5993 V_pfsync_update_state_ptr(s);
5997 } else if (s == NULL)
5998 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6005 if (action == PF_PASS && h->ip_hl > 5 &&
6006 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6008 REASON_SET(&reason, PFRES_IPOPTIONS);
6010 DPFPRINTF(PF_DEBUG_MISC,
6011 ("pf: dropping packet with ip options\n"));
6014 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6016 REASON_SET(&reason, PFRES_MEMORY);
6018 if (r->rtableid >= 0)
6019 M_SETFIB(m, r->rtableid);
6021 if (r->scrub_flags & PFSTATE_SETPRIO) {
6022 if (pd.tos & IPTOS_LOWDELAY)
6024 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6026 REASON_SET(&reason, PFRES_MEMORY);
6028 DPFPRINTF(PF_DEBUG_MISC,
6029 ("pf: failed to allocate 802.1q mtag\n"));
6034 if (action == PF_PASS && r->qid) {
6035 if (pd.pf_mtag == NULL &&
6036 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6038 REASON_SET(&reason, PFRES_MEMORY);
6041 pd.pf_mtag->qid_hash = pf_state_hash(s);
6042 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6043 pd.pf_mtag->qid = r->pqid;
6045 pd.pf_mtag->qid = r->qid;
6046 /* Add hints for ecn. */
6047 pd.pf_mtag->hdr = h;
6054 * connections redirected to loopback should not match sockets
6055 * bound specifically to loopback due to security implications,
6056 * see tcp_input() and in_pcblookup_listen().
6058 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6059 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6060 (s->nat_rule.ptr->action == PF_RDR ||
6061 s->nat_rule.ptr->action == PF_BINAT) &&
6062 IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
6063 m->m_flags |= M_SKIP_FIREWALL;
6065 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6066 !PACKET_LOOPED(&pd)) {
6068 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6069 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6070 if (ipfwtag != NULL) {
6071 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6072 ntohs(r->divert.port);
6073 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6078 m_tag_prepend(m, ipfwtag);
6079 if (m->m_flags & M_FASTFWD_OURS) {
6080 if (pd.pf_mtag == NULL &&
6081 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6083 REASON_SET(&reason, PFRES_MEMORY);
6085 DPFPRINTF(PF_DEBUG_MISC,
6086 ("pf: failed to allocate tag\n"));
6088 pd.pf_mtag->flags |=
6089 PF_FASTFWD_OURS_PRESENT;
6090 m->m_flags &= ~M_FASTFWD_OURS;
6093 ip_divert_ptr(*m0, dir == PF_IN);
6098 /* XXX: ipfw has the same behaviour! */
6100 REASON_SET(&reason, PFRES_MEMORY);
6102 DPFPRINTF(PF_DEBUG_MISC,
6103 ("pf: failed to allocate divert tag\n"));
6110 if (s != NULL && s->nat_rule.ptr != NULL &&
6111 s->nat_rule.ptr->log & PF_LOG_ALL)
6112 lr = s->nat_rule.ptr;
6115 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6119 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6120 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6122 if (action == PF_PASS || r->action == PF_DROP) {
6123 dirndx = (dir == PF_OUT);
6124 r->packets[dirndx]++;
6125 r->bytes[dirndx] += pd.tot_len;
6127 a->packets[dirndx]++;
6128 a->bytes[dirndx] += pd.tot_len;
6131 if (s->nat_rule.ptr != NULL) {
6132 s->nat_rule.ptr->packets[dirndx]++;
6133 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6135 if (s->src_node != NULL) {
6136 s->src_node->packets[dirndx]++;
6137 s->src_node->bytes[dirndx] += pd.tot_len;
6139 if (s->nat_src_node != NULL) {
6140 s->nat_src_node->packets[dirndx]++;
6141 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6143 dirndx = (dir == s->direction) ? 0 : 1;
6144 s->packets[dirndx]++;
6145 s->bytes[dirndx] += pd.tot_len;
6148 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6149 if (nr != NULL && r == &V_pf_default_rule)
6151 if (tr->src.addr.type == PF_ADDR_TABLE)
6152 pfr_update_stats(tr->src.addr.p.tbl,
6153 (s == NULL) ? pd.src :
6154 &s->key[(s->direction == PF_IN)]->
6155 addr[(s->direction == PF_OUT)],
6156 pd.af, pd.tot_len, dir == PF_OUT,
6157 r->action == PF_PASS, tr->src.neg);
6158 if (tr->dst.addr.type == PF_ADDR_TABLE)
6159 pfr_update_stats(tr->dst.addr.p.tbl,
6160 (s == NULL) ? pd.dst :
6161 &s->key[(s->direction == PF_IN)]->
6162 addr[(s->direction == PF_IN)],
6163 pd.af, pd.tot_len, dir == PF_OUT,
6164 r->action == PF_PASS, tr->dst.neg);
6168 case PF_SYNPROXY_DROP:
6179 /* pf_route() returns unlocked. */
6181 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6195 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6197 struct pfi_kif *kif;
6198 u_short action, reason = 0, log = 0;
6199 struct mbuf *m = *m0, *n = NULL;
6201 struct ip6_hdr *h = NULL;
6202 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6203 struct pf_state *s = NULL;
6204 struct pf_ruleset *ruleset = NULL;
6206 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6208 PF_RULES_RLOCK_TRACKER;
6211 if (!V_pf_status.running)
6214 memset(&pd, 0, sizeof(pd));
6215 pd.pf_mtag = pf_find_mtag(m);
6217 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6220 kif = (struct pfi_kif *)ifp->if_pf_kif;
6222 DPFPRINTF(PF_DEBUG_URGENT,
6223 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6226 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6229 if (m->m_flags & M_SKIP_FIREWALL)
6234 /* We do IP header normalization and packet reassembly here */
6235 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6239 m = *m0; /* pf_normalize messes with m0 */
6240 h = mtod(m, struct ip6_hdr *);
6243 * we do not support jumbogram. if we keep going, zero ip6_plen
6244 * will do something bad, so drop the packet for now.
6246 if (htons(h->ip6_plen) == 0) {
6248 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6252 pd.src = (struct pf_addr *)&h->ip6_src;
6253 pd.dst = (struct pf_addr *)&h->ip6_dst;
6254 pd.sport = pd.dport = NULL;
6256 pd.proto_sum = NULL;
6258 pd.sidx = (dir == PF_IN) ? 0 : 1;
6259 pd.didx = (dir == PF_IN) ? 1 : 0;
6262 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6264 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6265 pd.proto = h->ip6_nxt;
6268 case IPPROTO_FRAGMENT:
6269 action = pf_test_fragment(&r, dir, kif, m, h,
6271 if (action == PF_DROP)
6272 REASON_SET(&reason, PFRES_FRAG);
6274 case IPPROTO_ROUTING: {
6275 struct ip6_rthdr rthdr;
6278 DPFPRINTF(PF_DEBUG_MISC,
6279 ("pf: IPv6 more than one rthdr\n"));
6281 REASON_SET(&reason, PFRES_IPOPTIONS);
6285 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6287 DPFPRINTF(PF_DEBUG_MISC,
6288 ("pf: IPv6 short rthdr\n"));
6290 REASON_SET(&reason, PFRES_SHORT);
6294 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6295 DPFPRINTF(PF_DEBUG_MISC,
6296 ("pf: IPv6 rthdr0\n"));
6298 REASON_SET(&reason, PFRES_IPOPTIONS);
6305 case IPPROTO_HOPOPTS:
6306 case IPPROTO_DSTOPTS: {
6307 /* get next header and header length */
6308 struct ip6_ext opt6;
6310 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6311 NULL, &reason, pd.af)) {
6312 DPFPRINTF(PF_DEBUG_MISC,
6313 ("pf: IPv6 short opt\n"));
6318 if (pd.proto == IPPROTO_AH)
6319 off += (opt6.ip6e_len + 2) * 4;
6321 off += (opt6.ip6e_len + 1) * 8;
6322 pd.proto = opt6.ip6e_nxt;
6323 /* goto the next header */
6330 } while (!terminal);
6332 /* if there's no routing header, use unmodified mbuf for checksumming */
6342 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6343 &action, &reason, AF_INET6)) {
6344 log = action != PF_PASS;
6347 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6348 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6349 if (action == PF_DROP)
6351 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6353 if (action == PF_PASS) {
6354 if (V_pfsync_update_state_ptr != NULL)
6355 V_pfsync_update_state_ptr(s);
6359 } else if (s == NULL)
6360 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6369 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6370 &action, &reason, AF_INET6)) {
6371 log = action != PF_PASS;
6374 if (uh.uh_dport == 0 ||
6375 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6376 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6378 REASON_SET(&reason, PFRES_SHORT);
6381 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6382 if (action == PF_PASS) {
6383 if (V_pfsync_update_state_ptr != NULL)
6384 V_pfsync_update_state_ptr(s);
6388 } else if (s == NULL)
6389 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6394 case IPPROTO_ICMP: {
6396 DPFPRINTF(PF_DEBUG_MISC,
6397 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6401 case IPPROTO_ICMPV6: {
6402 struct icmp6_hdr ih;
6405 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6406 &action, &reason, AF_INET6)) {
6407 log = action != PF_PASS;
6410 action = pf_test_state_icmp(&s, dir, kif,
6411 m, off, h, &pd, &reason);
6412 if (action == PF_PASS) {
6413 if (V_pfsync_update_state_ptr != NULL)
6414 V_pfsync_update_state_ptr(s);
6418 } else if (s == NULL)
6419 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6425 action = pf_test_state_other(&s, dir, kif, m, &pd);
6426 if (action == PF_PASS) {
6427 if (V_pfsync_update_state_ptr != NULL)
6428 V_pfsync_update_state_ptr(s);
6432 } else if (s == NULL)
6433 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6445 /* handle dangerous IPv6 extension headers. */
6446 if (action == PF_PASS && rh_cnt &&
6447 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6449 REASON_SET(&reason, PFRES_IPOPTIONS);
6451 DPFPRINTF(PF_DEBUG_MISC,
6452 ("pf: dropping packet with dangerous v6 headers\n"));
6455 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6457 REASON_SET(&reason, PFRES_MEMORY);
6459 if (r->rtableid >= 0)
6460 M_SETFIB(m, r->rtableid);
6462 if (r->scrub_flags & PFSTATE_SETPRIO) {
6463 if (pd.tos & IPTOS_LOWDELAY)
6465 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6467 REASON_SET(&reason, PFRES_MEMORY);
6469 DPFPRINTF(PF_DEBUG_MISC,
6470 ("pf: failed to allocate 802.1q mtag\n"));
6475 if (action == PF_PASS && r->qid) {
6476 if (pd.pf_mtag == NULL &&
6477 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6479 REASON_SET(&reason, PFRES_MEMORY);
6482 pd.pf_mtag->qid_hash = pf_state_hash(s);
6483 if (pd.tos & IPTOS_LOWDELAY)
6484 pd.pf_mtag->qid = r->pqid;
6486 pd.pf_mtag->qid = r->qid;
6487 /* Add hints for ecn. */
6488 pd.pf_mtag->hdr = h;
6493 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6494 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6495 (s->nat_rule.ptr->action == PF_RDR ||
6496 s->nat_rule.ptr->action == PF_BINAT) &&
6497 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6498 m->m_flags |= M_SKIP_FIREWALL;
6500 /* XXX: Anybody working on it?! */
6502 printf("pf: divert(9) is not supported for IPv6\n");
6507 if (s != NULL && s->nat_rule.ptr != NULL &&
6508 s->nat_rule.ptr->log & PF_LOG_ALL)
6509 lr = s->nat_rule.ptr;
6512 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6516 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6517 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6519 if (action == PF_PASS || r->action == PF_DROP) {
6520 dirndx = (dir == PF_OUT);
6521 r->packets[dirndx]++;
6522 r->bytes[dirndx] += pd.tot_len;
6524 a->packets[dirndx]++;
6525 a->bytes[dirndx] += pd.tot_len;
6528 if (s->nat_rule.ptr != NULL) {
6529 s->nat_rule.ptr->packets[dirndx]++;
6530 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6532 if (s->src_node != NULL) {
6533 s->src_node->packets[dirndx]++;
6534 s->src_node->bytes[dirndx] += pd.tot_len;
6536 if (s->nat_src_node != NULL) {
6537 s->nat_src_node->packets[dirndx]++;
6538 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6540 dirndx = (dir == s->direction) ? 0 : 1;
6541 s->packets[dirndx]++;
6542 s->bytes[dirndx] += pd.tot_len;
6545 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6546 if (nr != NULL && r == &V_pf_default_rule)
6548 if (tr->src.addr.type == PF_ADDR_TABLE)
6549 pfr_update_stats(tr->src.addr.p.tbl,
6550 (s == NULL) ? pd.src :
6551 &s->key[(s->direction == PF_IN)]->addr[0],
6552 pd.af, pd.tot_len, dir == PF_OUT,
6553 r->action == PF_PASS, tr->src.neg);
6554 if (tr->dst.addr.type == PF_ADDR_TABLE)
6555 pfr_update_stats(tr->dst.addr.p.tbl,
6556 (s == NULL) ? pd.dst :
6557 &s->key[(s->direction == PF_IN)]->addr[1],
6558 pd.af, pd.tot_len, dir == PF_OUT,
6559 r->action == PF_PASS, tr->dst.neg);
6563 case PF_SYNPROXY_DROP:
6574 /* pf_route6() returns unlocked. */
6576 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6585 /* If reassembled packet passed, create new fragments. */
6586 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6587 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6588 action = pf_refragment6(ifp, m0, mtag);