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_SRCTRACK ||
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);
1488 /* Wait until V_pf_default_rule is initialized. */
1489 if (V_pf_vnet_active == 0) {
1495 * Process 1/interval fraction of the state
1499 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1500 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1503 * Purge other expired types every
1504 * PFTM_INTERVAL seconds.
1506 if (V_pf_purge_idx == 0) {
1508 * Order is important:
1509 * - states and src nodes reference rules
1510 * - states and rules reference kifs
1512 pf_purge_expired_fragments();
1513 pf_purge_expired_src_nodes();
1514 pf_purge_unlinked_rules();
1519 VNET_LIST_RUNLOCK();
1523 sx_xunlock(&pf_end_lock);
1528 pf_unload_vnet_purge(void)
1532 * To cleanse up all kifs and rules we need
1533 * two runs: first one clears reference flags,
1534 * then pf_purge_expired_states() doesn't
1535 * raise them, and then second run frees.
1537 pf_purge_unlinked_rules();
1541 * Now purge everything.
1543 pf_purge_expired_states(0, pf_hashmask);
1544 pf_purge_fragments(UINT_MAX);
1545 pf_purge_expired_src_nodes();
1548 * Now all kifs & rules should be unreferenced,
1549 * thus should be successfully freed.
1551 pf_purge_unlinked_rules();
1556 pf_state_expires(const struct pf_state *state)
1563 /* handle all PFTM_* > PFTM_MAX here */
1564 if (state->timeout == PFTM_PURGE)
1565 return (time_uptime);
1566 KASSERT(state->timeout != PFTM_UNLINKED,
1567 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1568 KASSERT((state->timeout < PFTM_MAX),
1569 ("pf_state_expires: timeout > PFTM_MAX"));
1570 timeout = state->rule.ptr->timeout[state->timeout];
1572 timeout = V_pf_default_rule.timeout[state->timeout];
1573 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1574 if (start && state->rule.ptr != &V_pf_default_rule) {
1575 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1576 states = counter_u64_fetch(state->rule.ptr->states_cur);
1578 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1579 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1580 states = V_pf_status.states;
1582 if (end && states > start && start < end) {
1584 timeout = (u_int64_t)timeout * (end - states) /
1586 return (state->expire + timeout);
1589 return (time_uptime);
1591 return (state->expire + timeout);
1595 pf_purge_expired_src_nodes()
1597 struct pf_src_node_list freelist;
1598 struct pf_srchash *sh;
1599 struct pf_src_node *cur, *next;
1602 LIST_INIT(&freelist);
1603 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1604 PF_HASHROW_LOCK(sh);
1605 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1606 if (cur->states == 0 && cur->expire <= time_uptime) {
1607 pf_unlink_src_node(cur);
1608 LIST_INSERT_HEAD(&freelist, cur, entry);
1609 } else if (cur->rule.ptr != NULL)
1610 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1611 PF_HASHROW_UNLOCK(sh);
1614 pf_free_src_nodes(&freelist);
1616 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1620 pf_src_tree_remove_state(struct pf_state *s)
1622 struct pf_src_node *sn;
1623 struct pf_srchash *sh;
1626 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1627 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1628 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1630 if (s->src_node != NULL) {
1632 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1633 PF_HASHROW_LOCK(sh);
1636 if (--sn->states == 0)
1637 sn->expire = time_uptime + timeout;
1638 PF_HASHROW_UNLOCK(sh);
1640 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1641 sn = s->nat_src_node;
1642 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1643 PF_HASHROW_LOCK(sh);
1644 if (--sn->states == 0)
1645 sn->expire = time_uptime + timeout;
1646 PF_HASHROW_UNLOCK(sh);
1648 s->src_node = s->nat_src_node = NULL;
1652 * Unlink and potentilly free a state. Function may be
1653 * called with ID hash row locked, but always returns
1654 * unlocked, since it needs to go through key hash locking.
1657 pf_unlink_state(struct pf_state *s, u_int flags)
1659 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1661 if ((flags & PF_ENTER_LOCKED) == 0)
1662 PF_HASHROW_LOCK(ih);
1664 PF_HASHROW_ASSERT(ih);
1666 if (s->timeout == PFTM_UNLINKED) {
1668 * State is being processed
1669 * by pf_unlink_state() in
1672 PF_HASHROW_UNLOCK(ih);
1673 return (0); /* XXXGL: undefined actually */
1676 if (s->src.state == PF_TCPS_PROXY_DST) {
1677 /* XXX wire key the right one? */
1678 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1679 &s->key[PF_SK_WIRE]->addr[1],
1680 &s->key[PF_SK_WIRE]->addr[0],
1681 s->key[PF_SK_WIRE]->port[1],
1682 s->key[PF_SK_WIRE]->port[0],
1683 s->src.seqhi, s->src.seqlo + 1,
1684 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1687 LIST_REMOVE(s, entry);
1688 pf_src_tree_remove_state(s);
1690 if (V_pfsync_delete_state_ptr != NULL)
1691 V_pfsync_delete_state_ptr(s);
1693 STATE_DEC_COUNTERS(s);
1695 s->timeout = PFTM_UNLINKED;
1697 PF_HASHROW_UNLOCK(ih);
1700 /* pf_state_insert() initialises refs to 2, so we can never release the
1701 * last reference here, only in pf_release_state(). */
1702 (void)refcount_release(&s->refs);
1704 return (pf_release_state(s));
1708 pf_free_state(struct pf_state *cur)
1711 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1712 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1715 pf_normalize_tcp_cleanup(cur);
1716 uma_zfree(V_pf_state_z, cur);
1717 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1721 * Called only from pf_purge_thread(), thus serialized.
1724 pf_purge_expired_states(u_int i, int maxcheck)
1726 struct pf_idhash *ih;
1729 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1732 * Go through hash and unlink states that expire now.
1734 while (maxcheck > 0) {
1735 ih = &V_pf_idhash[i];
1737 /* only take the lock if we expect to do work */
1738 if (!LIST_EMPTY(&ih->states)) {
1740 PF_HASHROW_LOCK(ih);
1741 LIST_FOREACH(s, &ih->states, entry) {
1742 if (pf_state_expires(s) <= time_uptime) {
1743 V_pf_status.states -=
1744 pf_unlink_state(s, PF_ENTER_LOCKED);
1747 s->rule.ptr->rule_flag |= PFRULE_REFS;
1748 if (s->nat_rule.ptr != NULL)
1749 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1750 if (s->anchor.ptr != NULL)
1751 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1752 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1754 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1756 PF_HASHROW_UNLOCK(ih);
1759 /* Return when we hit end of hash. */
1760 if (++i > pf_hashmask) {
1761 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1768 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1774 pf_purge_unlinked_rules()
1776 struct pf_rulequeue tmpq;
1777 struct pf_rule *r, *r1;
1780 * If we have overloading task pending, then we'd
1781 * better skip purging this time. There is a tiny
1782 * probability that overloading task references
1783 * an already unlinked rule.
1785 PF_OVERLOADQ_LOCK();
1786 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1787 PF_OVERLOADQ_UNLOCK();
1790 PF_OVERLOADQ_UNLOCK();
1793 * Do naive mark-and-sweep garbage collecting of old rules.
1794 * Reference flag is raised by pf_purge_expired_states()
1795 * and pf_purge_expired_src_nodes().
1797 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1798 * use a temporary queue.
1801 PF_UNLNKDRULES_LOCK();
1802 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1803 if (!(r->rule_flag & PFRULE_REFS)) {
1804 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1805 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1807 r->rule_flag &= ~PFRULE_REFS;
1809 PF_UNLNKDRULES_UNLOCK();
1811 if (!TAILQ_EMPTY(&tmpq)) {
1813 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1814 TAILQ_REMOVE(&tmpq, r, entries);
1822 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1827 u_int32_t a = ntohl(addr->addr32[0]);
1828 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1840 u_int8_t i, curstart, curend, maxstart, maxend;
1841 curstart = curend = maxstart = maxend = 255;
1842 for (i = 0; i < 8; i++) {
1843 if (!addr->addr16[i]) {
1844 if (curstart == 255)
1848 if ((curend - curstart) >
1849 (maxend - maxstart)) {
1850 maxstart = curstart;
1853 curstart = curend = 255;
1856 if ((curend - curstart) >
1857 (maxend - maxstart)) {
1858 maxstart = curstart;
1861 for (i = 0; i < 8; i++) {
1862 if (i >= maxstart && i <= maxend) {
1868 b = ntohs(addr->addr16[i]);
1885 pf_print_state(struct pf_state *s)
1887 pf_print_state_parts(s, NULL, NULL);
1891 pf_print_state_parts(struct pf_state *s,
1892 struct pf_state_key *skwp, struct pf_state_key *sksp)
1894 struct pf_state_key *skw, *sks;
1895 u_int8_t proto, dir;
1897 /* Do our best to fill these, but they're skipped if NULL */
1898 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1899 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1900 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1901 dir = s ? s->direction : 0;
1919 case IPPROTO_ICMPV6:
1923 printf("%u", proto);
1936 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1938 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1943 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1945 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1950 if (proto == IPPROTO_TCP) {
1951 printf(" [lo=%u high=%u win=%u modulator=%u",
1952 s->src.seqlo, s->src.seqhi,
1953 s->src.max_win, s->src.seqdiff);
1954 if (s->src.wscale && s->dst.wscale)
1955 printf(" wscale=%u",
1956 s->src.wscale & PF_WSCALE_MASK);
1958 printf(" [lo=%u high=%u win=%u modulator=%u",
1959 s->dst.seqlo, s->dst.seqhi,
1960 s->dst.max_win, s->dst.seqdiff);
1961 if (s->src.wscale && s->dst.wscale)
1962 printf(" wscale=%u",
1963 s->dst.wscale & PF_WSCALE_MASK);
1966 printf(" %u:%u", s->src.state, s->dst.state);
1971 pf_print_flags(u_int8_t f)
1993 #define PF_SET_SKIP_STEPS(i) \
1995 while (head[i] != cur) { \
1996 head[i]->skip[i].ptr = cur; \
1997 head[i] = TAILQ_NEXT(head[i], entries); \
2002 pf_calc_skip_steps(struct pf_rulequeue *rules)
2004 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
2007 cur = TAILQ_FIRST(rules);
2009 for (i = 0; i < PF_SKIP_COUNT; ++i)
2011 while (cur != NULL) {
2012 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2013 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2014 if (cur->direction != prev->direction)
2015 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2016 if (cur->af != prev->af)
2017 PF_SET_SKIP_STEPS(PF_SKIP_AF);
2018 if (cur->proto != prev->proto)
2019 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2020 if (cur->src.neg != prev->src.neg ||
2021 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2022 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2023 if (cur->src.port[0] != prev->src.port[0] ||
2024 cur->src.port[1] != prev->src.port[1] ||
2025 cur->src.port_op != prev->src.port_op)
2026 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2027 if (cur->dst.neg != prev->dst.neg ||
2028 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2029 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2030 if (cur->dst.port[0] != prev->dst.port[0] ||
2031 cur->dst.port[1] != prev->dst.port[1] ||
2032 cur->dst.port_op != prev->dst.port_op)
2033 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2036 cur = TAILQ_NEXT(cur, entries);
2038 for (i = 0; i < PF_SKIP_COUNT; ++i)
2039 PF_SET_SKIP_STEPS(i);
2043 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2045 if (aw1->type != aw2->type)
2047 switch (aw1->type) {
2048 case PF_ADDR_ADDRMASK:
2050 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2052 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2055 case PF_ADDR_DYNIFTL:
2056 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2057 case PF_ADDR_NOROUTE:
2058 case PF_ADDR_URPFFAILED:
2061 return (aw1->p.tbl != aw2->p.tbl);
2063 printf("invalid address type: %d\n", aw1->type);
2069 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2070 * header isn't always a full checksum. In some cases (i.e. output) it's a
2071 * pseudo-header checksum, which is a partial checksum over src/dst IP
2072 * addresses, protocol number and length.
2074 * That means we have the following cases:
2075 * * Input or forwarding: we don't have TSO, the checksum fields are full
2076 * checksums, we need to update the checksum whenever we change anything.
2077 * * Output (i.e. the checksum is a pseudo-header checksum):
2078 * x The field being updated is src/dst address or affects the length of
2079 * the packet. We need to update the pseudo-header checksum (note that this
2080 * checksum is not ones' complement).
2081 * x Some other field is being modified (e.g. src/dst port numbers): We
2082 * don't have to update anything.
2085 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2091 l = cksum + old - new;
2092 l = (l >> 16) + (l & 65535);
2100 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2101 u_int16_t new, u_int8_t udp)
2103 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2106 return (pf_cksum_fixup(cksum, old, new, udp));
2110 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2111 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2117 PF_ACPY(&ao, a, af);
2120 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2128 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2129 ao.addr16[0], an->addr16[0], 0),
2130 ao.addr16[1], an->addr16[1], 0);
2133 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2134 ao.addr16[0], an->addr16[0], u),
2135 ao.addr16[1], an->addr16[1], u);
2137 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2142 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2143 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2144 pf_cksum_fixup(pf_cksum_fixup(*pc,
2145 ao.addr16[0], an->addr16[0], u),
2146 ao.addr16[1], an->addr16[1], u),
2147 ao.addr16[2], an->addr16[2], u),
2148 ao.addr16[3], an->addr16[3], u),
2149 ao.addr16[4], an->addr16[4], u),
2150 ao.addr16[5], an->addr16[5], u),
2151 ao.addr16[6], an->addr16[6], u),
2152 ao.addr16[7], an->addr16[7], u);
2154 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2159 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2160 CSUM_DELAY_DATA_IPV6)) {
2167 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2169 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2173 memcpy(&ao, a, sizeof(ao));
2174 memcpy(a, &an, sizeof(u_int32_t));
2175 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2176 ao % 65536, an % 65536, u);
2180 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2184 memcpy(&ao, a, sizeof(ao));
2185 memcpy(a, &an, sizeof(u_int32_t));
2187 *c = pf_proto_cksum_fixup(m,
2188 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2189 ao % 65536, an % 65536, udp);
2194 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2198 PF_ACPY(&ao, a, AF_INET6);
2199 PF_ACPY(a, an, AF_INET6);
2201 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2202 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2203 pf_cksum_fixup(pf_cksum_fixup(*c,
2204 ao.addr16[0], an->addr16[0], u),
2205 ao.addr16[1], an->addr16[1], u),
2206 ao.addr16[2], an->addr16[2], u),
2207 ao.addr16[3], an->addr16[3], u),
2208 ao.addr16[4], an->addr16[4], u),
2209 ao.addr16[5], an->addr16[5], u),
2210 ao.addr16[6], an->addr16[6], u),
2211 ao.addr16[7], an->addr16[7], u);
2216 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2217 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2218 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2220 struct pf_addr oia, ooa;
2222 PF_ACPY(&oia, ia, af);
2224 PF_ACPY(&ooa, oa, af);
2226 /* Change inner protocol port, fix inner protocol checksum. */
2228 u_int16_t oip = *ip;
2235 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2236 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2238 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2240 /* Change inner ip address, fix inner ip and icmp checksums. */
2241 PF_ACPY(ia, na, af);
2245 u_int32_t oh2c = *h2c;
2247 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2248 oia.addr16[0], ia->addr16[0], 0),
2249 oia.addr16[1], ia->addr16[1], 0);
2250 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2251 oia.addr16[0], ia->addr16[0], 0),
2252 oia.addr16[1], ia->addr16[1], 0);
2253 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2259 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2260 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2261 pf_cksum_fixup(pf_cksum_fixup(*ic,
2262 oia.addr16[0], ia->addr16[0], u),
2263 oia.addr16[1], ia->addr16[1], u),
2264 oia.addr16[2], ia->addr16[2], u),
2265 oia.addr16[3], ia->addr16[3], u),
2266 oia.addr16[4], ia->addr16[4], u),
2267 oia.addr16[5], ia->addr16[5], u),
2268 oia.addr16[6], ia->addr16[6], u),
2269 oia.addr16[7], ia->addr16[7], u);
2273 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2275 PF_ACPY(oa, na, af);
2279 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2280 ooa.addr16[0], oa->addr16[0], 0),
2281 ooa.addr16[1], oa->addr16[1], 0);
2286 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2287 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2288 pf_cksum_fixup(pf_cksum_fixup(*ic,
2289 ooa.addr16[0], oa->addr16[0], u),
2290 ooa.addr16[1], oa->addr16[1], u),
2291 ooa.addr16[2], oa->addr16[2], u),
2292 ooa.addr16[3], oa->addr16[3], u),
2293 ooa.addr16[4], oa->addr16[4], u),
2294 ooa.addr16[5], oa->addr16[5], u),
2295 ooa.addr16[6], oa->addr16[6], u),
2296 ooa.addr16[7], oa->addr16[7], u);
2304 * Need to modulate the sequence numbers in the TCP SACK option
2305 * (credits to Krzysztof Pfaff for report and patch)
2308 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2309 struct tcphdr *th, struct pf_state_peer *dst)
2311 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2312 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2313 int copyback = 0, i, olen;
2314 struct sackblk sack;
2316 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2317 if (hlen < TCPOLEN_SACKLEN ||
2318 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2321 while (hlen >= TCPOLEN_SACKLEN) {
2324 case TCPOPT_EOL: /* FALLTHROUGH */
2332 if (olen >= TCPOLEN_SACKLEN) {
2333 for (i = 2; i + TCPOLEN_SACK <= olen;
2334 i += TCPOLEN_SACK) {
2335 memcpy(&sack, &opt[i], sizeof(sack));
2336 pf_change_proto_a(m, &sack.start, &th->th_sum,
2337 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2338 pf_change_proto_a(m, &sack.end, &th->th_sum,
2339 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2340 memcpy(&opt[i], &sack, sizeof(sack));
2354 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2359 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2360 const struct pf_addr *saddr, const struct pf_addr *daddr,
2361 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2362 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2363 u_int16_t rtag, struct ifnet *ifp)
2365 struct pf_send_entry *pfse;
2369 struct ip *h = NULL;
2372 struct ip6_hdr *h6 = NULL;
2376 struct pf_mtag *pf_mtag;
2381 /* maximum segment size tcp option */
2382 tlen = sizeof(struct tcphdr);
2389 len = sizeof(struct ip) + tlen;
2394 len = sizeof(struct ip6_hdr) + tlen;
2398 panic("%s: unsupported af %d", __func__, af);
2401 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2402 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2405 m = m_gethdr(M_NOWAIT, MT_DATA);
2407 free(pfse, M_PFTEMP);
2411 mac_netinet_firewall_send(m);
2413 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2414 free(pfse, M_PFTEMP);
2419 m->m_flags |= M_SKIP_FIREWALL;
2420 pf_mtag->tag = rtag;
2422 if (r != NULL && r->rtableid >= 0)
2423 M_SETFIB(m, r->rtableid);
2426 if (r != NULL && r->qid) {
2427 pf_mtag->qid = r->qid;
2429 /* add hints for ecn */
2430 pf_mtag->hdr = mtod(m, struct ip *);
2433 m->m_data += max_linkhdr;
2434 m->m_pkthdr.len = m->m_len = len;
2435 m->m_pkthdr.rcvif = NULL;
2436 bzero(m->m_data, len);
2440 h = mtod(m, struct ip *);
2442 /* IP header fields included in the TCP checksum */
2443 h->ip_p = IPPROTO_TCP;
2444 h->ip_len = htons(tlen);
2445 h->ip_src.s_addr = saddr->v4.s_addr;
2446 h->ip_dst.s_addr = daddr->v4.s_addr;
2448 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2453 h6 = mtod(m, struct ip6_hdr *);
2455 /* IP header fields included in the TCP checksum */
2456 h6->ip6_nxt = IPPROTO_TCP;
2457 h6->ip6_plen = htons(tlen);
2458 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2459 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2461 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2467 th->th_sport = sport;
2468 th->th_dport = dport;
2469 th->th_seq = htonl(seq);
2470 th->th_ack = htonl(ack);
2471 th->th_off = tlen >> 2;
2472 th->th_flags = flags;
2473 th->th_win = htons(win);
2476 opt = (char *)(th + 1);
2477 opt[0] = TCPOPT_MAXSEG;
2480 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2487 th->th_sum = in_cksum(m, len);
2489 /* Finish the IP header */
2491 h->ip_hl = sizeof(*h) >> 2;
2492 h->ip_tos = IPTOS_LOWDELAY;
2493 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2494 h->ip_len = htons(len);
2495 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2498 pfse->pfse_type = PFSE_IP;
2504 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2505 sizeof(struct ip6_hdr), tlen);
2507 h6->ip6_vfc |= IPV6_VERSION;
2508 h6->ip6_hlim = IPV6_DEFHLIM;
2510 pfse->pfse_type = PFSE_IP6;
2519 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2520 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2521 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2524 struct pf_addr * const saddr = pd->src;
2525 struct pf_addr * const daddr = pd->dst;
2526 sa_family_t af = pd->af;
2528 /* undo NAT changes, if they have taken place */
2530 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2531 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2533 *pd->sport = sk->port[pd->sidx];
2535 *pd->dport = sk->port[pd->didx];
2537 *pd->proto_sum = bproto_sum;
2539 *pd->ip_sum = bip_sum;
2540 m_copyback(m, off, hdrlen, pd->hdr.any);
2542 if (pd->proto == IPPROTO_TCP &&
2543 ((r->rule_flag & PFRULE_RETURNRST) ||
2544 (r->rule_flag & PFRULE_RETURN)) &&
2545 !(th->th_flags & TH_RST)) {
2546 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2558 h4 = mtod(m, struct ip *);
2559 len = ntohs(h4->ip_len) - off;
2564 h6 = mtod(m, struct ip6_hdr *);
2565 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2570 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2571 REASON_SET(reason, PFRES_PROTCKSUM);
2573 if (th->th_flags & TH_SYN)
2575 if (th->th_flags & TH_FIN)
2577 pf_send_tcp(m, r, af, pd->dst,
2578 pd->src, th->th_dport, th->th_sport,
2579 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2580 r->return_ttl, 1, 0, kif->pfik_ifp);
2582 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2584 pf_send_icmp(m, r->return_icmp >> 8,
2585 r->return_icmp & 255, af, r);
2586 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2588 pf_send_icmp(m, r->return_icmp6 >> 8,
2589 r->return_icmp6 & 255, af, r);
2593 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2597 KASSERT(prio <= PF_PRIO_MAX,
2598 ("%s with invalid pcp", __func__));
2600 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2602 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2603 sizeof(uint8_t), M_NOWAIT);
2606 m_tag_prepend(m, mtag);
2609 *(uint8_t *)(mtag + 1) = prio;
2614 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2619 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2623 if (prio == PF_PRIO_ZERO)
2626 mpcp = *(uint8_t *)(mtag + 1);
2628 return (mpcp == prio);
2632 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2635 struct pf_send_entry *pfse;
2637 struct pf_mtag *pf_mtag;
2639 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2640 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2644 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2645 free(pfse, M_PFTEMP);
2649 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2650 free(pfse, M_PFTEMP);
2654 m0->m_flags |= M_SKIP_FIREWALL;
2656 if (r->rtableid >= 0)
2657 M_SETFIB(m0, r->rtableid);
2661 pf_mtag->qid = r->qid;
2662 /* add hints for ecn */
2663 pf_mtag->hdr = mtod(m0, struct ip *);
2670 pfse->pfse_type = PFSE_ICMP;
2675 pfse->pfse_type = PFSE_ICMP6;
2680 pfse->icmpopts.type = type;
2681 pfse->icmpopts.code = code;
2686 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2687 * If n is 0, they match if they are equal. If n is != 0, they match if they
2691 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2692 struct pf_addr *b, sa_family_t af)
2699 if ((a->addr32[0] & m->addr32[0]) ==
2700 (b->addr32[0] & m->addr32[0]))
2706 if (((a->addr32[0] & m->addr32[0]) ==
2707 (b->addr32[0] & m->addr32[0])) &&
2708 ((a->addr32[1] & m->addr32[1]) ==
2709 (b->addr32[1] & m->addr32[1])) &&
2710 ((a->addr32[2] & m->addr32[2]) ==
2711 (b->addr32[2] & m->addr32[2])) &&
2712 ((a->addr32[3] & m->addr32[3]) ==
2713 (b->addr32[3] & m->addr32[3])))
2732 * Return 1 if b <= a <= e, otherwise return 0.
2735 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2736 struct pf_addr *a, sa_family_t af)
2741 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2742 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2751 for (i = 0; i < 4; ++i)
2752 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2754 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2757 for (i = 0; i < 4; ++i)
2758 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2760 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2770 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2774 return ((p > a1) && (p < a2));
2776 return ((p < a1) || (p > a2));
2778 return ((p >= a1) && (p <= a2));
2792 return (0); /* never reached */
2796 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2801 return (pf_match(op, a1, a2, p));
2805 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2807 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2809 return (pf_match(op, a1, a2, u));
2813 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2815 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2817 return (pf_match(op, a1, a2, g));
2821 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2826 return ((!r->match_tag_not && r->match_tag == *tag) ||
2827 (r->match_tag_not && r->match_tag != *tag));
2831 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2834 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2836 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2839 pd->pf_mtag->tag = tag;
2844 #define PF_ANCHOR_STACKSIZE 32
2845 struct pf_anchor_stackframe {
2846 struct pf_ruleset *rs;
2847 struct pf_rule *r; /* XXX: + match bit */
2848 struct pf_anchor *child;
2852 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2854 #define PF_ANCHORSTACK_MATCH 0x00000001
2855 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2857 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2858 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2859 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2860 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2861 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2865 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2866 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2869 struct pf_anchor_stackframe *f;
2875 if (*depth >= PF_ANCHOR_STACKSIZE) {
2876 printf("%s: anchor stack overflow on %s\n",
2877 __func__, (*r)->anchor->name);
2878 *r = TAILQ_NEXT(*r, entries);
2880 } else if (*depth == 0 && a != NULL)
2882 f = stack + (*depth)++;
2885 if ((*r)->anchor_wildcard) {
2886 struct pf_anchor_node *parent = &(*r)->anchor->children;
2888 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2892 *rs = &f->child->ruleset;
2895 *rs = &(*r)->anchor->ruleset;
2897 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2901 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2902 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2905 struct pf_anchor_stackframe *f;
2914 f = stack + *depth - 1;
2915 fr = PF_ANCHOR_RULE(f);
2916 if (f->child != NULL) {
2917 struct pf_anchor_node *parent;
2920 * This block traverses through
2921 * a wildcard anchor.
2923 parent = &fr->anchor->children;
2924 if (match != NULL && *match) {
2926 * If any of "*" matched, then
2927 * "foo/ *" matched, mark frame
2930 PF_ANCHOR_SET_MATCH(f);
2933 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2934 if (f->child != NULL) {
2935 *rs = &f->child->ruleset;
2936 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2944 if (*depth == 0 && a != NULL)
2947 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2949 *r = TAILQ_NEXT(fr, entries);
2950 } while (*r == NULL);
2957 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2958 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2963 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2964 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2968 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2969 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2970 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2971 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2972 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2973 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2974 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2975 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2981 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2986 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2990 if (addr->addr32[3] == 0xffffffff) {
2991 addr->addr32[3] = 0;
2992 if (addr->addr32[2] == 0xffffffff) {
2993 addr->addr32[2] = 0;
2994 if (addr->addr32[1] == 0xffffffff) {
2995 addr->addr32[1] = 0;
2997 htonl(ntohl(addr->addr32[0]) + 1);
3000 htonl(ntohl(addr->addr32[1]) + 1);
3003 htonl(ntohl(addr->addr32[2]) + 1);
3006 htonl(ntohl(addr->addr32[3]) + 1);
3013 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3015 struct pf_addr *saddr, *daddr;
3016 u_int16_t sport, dport;
3017 struct inpcbinfo *pi;
3020 pd->lookup.uid = UID_MAX;
3021 pd->lookup.gid = GID_MAX;
3023 switch (pd->proto) {
3025 if (pd->hdr.tcp == NULL)
3027 sport = pd->hdr.tcp->th_sport;
3028 dport = pd->hdr.tcp->th_dport;
3032 if (pd->hdr.udp == NULL)
3034 sport = pd->hdr.udp->uh_sport;
3035 dport = pd->hdr.udp->uh_dport;
3041 if (direction == PF_IN) {
3056 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3057 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3059 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3060 daddr->v4, dport, INPLOOKUP_WILDCARD |
3061 INPLOOKUP_RLOCKPCB, NULL, m);
3069 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3070 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3072 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3073 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3074 INPLOOKUP_RLOCKPCB, NULL, m);
3084 INP_RLOCK_ASSERT(inp);
3085 pd->lookup.uid = inp->inp_cred->cr_uid;
3086 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3093 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3097 u_int8_t *opt, optlen;
3098 u_int8_t wscale = 0;
3100 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3101 if (hlen <= sizeof(struct tcphdr))
3103 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3105 opt = hdr + sizeof(struct tcphdr);
3106 hlen -= sizeof(struct tcphdr);
3116 if (wscale > TCP_MAX_WINSHIFT)
3117 wscale = TCP_MAX_WINSHIFT;
3118 wscale |= PF_WSCALE_FLAG;
3133 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3137 u_int8_t *opt, optlen;
3138 u_int16_t mss = V_tcp_mssdflt;
3140 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3141 if (hlen <= sizeof(struct tcphdr))
3143 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3145 opt = hdr + sizeof(struct tcphdr);
3146 hlen -= sizeof(struct tcphdr);
3147 while (hlen >= TCPOLEN_MAXSEG) {
3155 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3171 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3173 struct nhop_object *nh;
3175 struct in6_addr dst6;
3186 hlen = sizeof(struct ip);
3187 nh = fib4_lookup(rtableid, addr->v4, 0, 0, 0);
3189 mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3194 hlen = sizeof(struct ip6_hdr);
3195 in6_splitscope(&addr->v6, &dst6, &scopeid);
3196 nh = fib6_lookup(rtableid, &dst6, scopeid, 0, 0);
3198 mss = nh->nh_mtu - hlen - sizeof(struct tcphdr);
3203 mss = max(V_tcp_mssdflt, mss);
3204 mss = min(mss, offer);
3205 mss = max(mss, 64); /* sanity - at least max opt space */
3210 pf_tcp_iss(struct pf_pdesc *pd)
3213 u_int32_t digest[4];
3215 if (V_pf_tcp_secret_init == 0) {
3216 arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3217 MD5Init(&V_pf_tcp_secret_ctx);
3218 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3219 sizeof(V_pf_tcp_secret));
3220 V_pf_tcp_secret_init = 1;
3223 ctx = V_pf_tcp_secret_ctx;
3225 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3226 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3227 if (pd->af == AF_INET6) {
3228 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3229 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3231 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3232 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3234 MD5Final((u_char *)digest, &ctx);
3235 V_pf_tcp_iss_off += 4096;
3236 #define ISN_RANDOM_INCREMENT (4096 - 1)
3237 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3239 #undef ISN_RANDOM_INCREMENT
3243 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3244 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3245 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3247 struct pf_rule *nr = NULL;
3248 struct pf_addr * const saddr = pd->src;
3249 struct pf_addr * const daddr = pd->dst;
3250 sa_family_t af = pd->af;
3251 struct pf_rule *r, *a = NULL;
3252 struct pf_ruleset *ruleset = NULL;
3253 struct pf_src_node *nsn = NULL;
3254 struct tcphdr *th = pd->hdr.tcp;
3255 struct pf_state_key *sk = NULL, *nk = NULL;
3257 int rewrite = 0, hdrlen = 0;
3258 int tag = -1, rtableid = -1;
3262 u_int16_t sport = 0, dport = 0;
3263 u_int16_t bproto_sum = 0, bip_sum = 0;
3264 u_int8_t icmptype = 0, icmpcode = 0;
3265 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3270 INP_LOCK_ASSERT(inp);
3271 pd->lookup.uid = inp->inp_cred->cr_uid;
3272 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3273 pd->lookup.done = 1;
3276 switch (pd->proto) {
3278 sport = th->th_sport;
3279 dport = th->th_dport;
3280 hdrlen = sizeof(*th);
3283 sport = pd->hdr.udp->uh_sport;
3284 dport = pd->hdr.udp->uh_dport;
3285 hdrlen = sizeof(*pd->hdr.udp);
3289 if (pd->af != AF_INET)
3291 sport = dport = pd->hdr.icmp->icmp_id;
3292 hdrlen = sizeof(*pd->hdr.icmp);
3293 icmptype = pd->hdr.icmp->icmp_type;
3294 icmpcode = pd->hdr.icmp->icmp_code;
3296 if (icmptype == ICMP_UNREACH ||
3297 icmptype == ICMP_SOURCEQUENCH ||
3298 icmptype == ICMP_REDIRECT ||
3299 icmptype == ICMP_TIMXCEED ||
3300 icmptype == ICMP_PARAMPROB)
3305 case IPPROTO_ICMPV6:
3308 sport = dport = pd->hdr.icmp6->icmp6_id;
3309 hdrlen = sizeof(*pd->hdr.icmp6);
3310 icmptype = pd->hdr.icmp6->icmp6_type;
3311 icmpcode = pd->hdr.icmp6->icmp6_code;
3313 if (icmptype == ICMP6_DST_UNREACH ||
3314 icmptype == ICMP6_PACKET_TOO_BIG ||
3315 icmptype == ICMP6_TIME_EXCEEDED ||
3316 icmptype == ICMP6_PARAM_PROB)
3321 sport = dport = hdrlen = 0;
3325 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3327 /* check packet for BINAT/NAT/RDR */
3328 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3329 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3330 KASSERT(sk != NULL, ("%s: null sk", __func__));
3331 KASSERT(nk != NULL, ("%s: null nk", __func__));
3334 bip_sum = *pd->ip_sum;
3336 switch (pd->proto) {
3338 bproto_sum = th->th_sum;
3339 pd->proto_sum = &th->th_sum;
3341 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3342 nk->port[pd->sidx] != sport) {
3343 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3344 &th->th_sum, &nk->addr[pd->sidx],
3345 nk->port[pd->sidx], 0, af);
3346 pd->sport = &th->th_sport;
3347 sport = th->th_sport;
3350 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3351 nk->port[pd->didx] != dport) {
3352 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3353 &th->th_sum, &nk->addr[pd->didx],
3354 nk->port[pd->didx], 0, af);
3355 dport = th->th_dport;
3356 pd->dport = &th->th_dport;
3361 bproto_sum = pd->hdr.udp->uh_sum;
3362 pd->proto_sum = &pd->hdr.udp->uh_sum;
3364 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3365 nk->port[pd->sidx] != sport) {
3366 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3367 pd->ip_sum, &pd->hdr.udp->uh_sum,
3368 &nk->addr[pd->sidx],
3369 nk->port[pd->sidx], 1, af);
3370 sport = pd->hdr.udp->uh_sport;
3371 pd->sport = &pd->hdr.udp->uh_sport;
3374 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3375 nk->port[pd->didx] != dport) {
3376 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3377 pd->ip_sum, &pd->hdr.udp->uh_sum,
3378 &nk->addr[pd->didx],
3379 nk->port[pd->didx], 1, af);
3380 dport = pd->hdr.udp->uh_dport;
3381 pd->dport = &pd->hdr.udp->uh_dport;
3387 nk->port[0] = nk->port[1];
3388 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3389 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3390 nk->addr[pd->sidx].v4.s_addr, 0);
3392 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3393 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3394 nk->addr[pd->didx].v4.s_addr, 0);
3396 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3397 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3398 pd->hdr.icmp->icmp_cksum, sport,
3400 pd->hdr.icmp->icmp_id = nk->port[1];
3401 pd->sport = &pd->hdr.icmp->icmp_id;
3403 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3407 case IPPROTO_ICMPV6:
3408 nk->port[0] = nk->port[1];
3409 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3410 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3411 &nk->addr[pd->sidx], 0);
3413 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3414 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3415 &nk->addr[pd->didx], 0);
3424 &nk->addr[pd->sidx], AF_INET))
3425 pf_change_a(&saddr->v4.s_addr,
3427 nk->addr[pd->sidx].v4.s_addr, 0);
3430 &nk->addr[pd->didx], AF_INET))
3431 pf_change_a(&daddr->v4.s_addr,
3433 nk->addr[pd->didx].v4.s_addr, 0);
3439 &nk->addr[pd->sidx], AF_INET6))
3440 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3443 &nk->addr[pd->didx], AF_INET6))
3444 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3457 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3458 r = r->skip[PF_SKIP_IFP].ptr;
3459 else if (r->direction && r->direction != direction)
3460 r = r->skip[PF_SKIP_DIR].ptr;
3461 else if (r->af && r->af != af)
3462 r = r->skip[PF_SKIP_AF].ptr;
3463 else if (r->proto && r->proto != pd->proto)
3464 r = r->skip[PF_SKIP_PROTO].ptr;
3465 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3466 r->src.neg, kif, M_GETFIB(m)))
3467 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3468 /* tcp/udp only. port_op always 0 in other cases */
3469 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3470 r->src.port[0], r->src.port[1], sport))
3471 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3472 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3473 r->dst.neg, NULL, M_GETFIB(m)))
3474 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3475 /* tcp/udp only. port_op always 0 in other cases */
3476 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3477 r->dst.port[0], r->dst.port[1], dport))
3478 r = r->skip[PF_SKIP_DST_PORT].ptr;
3479 /* icmp only. type always 0 in other cases */
3480 else if (r->type && r->type != icmptype + 1)
3481 r = TAILQ_NEXT(r, entries);
3482 /* icmp only. type always 0 in other cases */
3483 else if (r->code && r->code != icmpcode + 1)
3484 r = TAILQ_NEXT(r, entries);
3485 else if (r->tos && !(r->tos == pd->tos))
3486 r = TAILQ_NEXT(r, entries);
3487 else if (r->rule_flag & PFRULE_FRAGMENT)
3488 r = TAILQ_NEXT(r, entries);
3489 else if (pd->proto == IPPROTO_TCP &&
3490 (r->flagset & th->th_flags) != r->flags)
3491 r = TAILQ_NEXT(r, entries);
3492 /* tcp/udp only. uid.op always 0 in other cases */
3493 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3494 pf_socket_lookup(direction, pd, m), 1)) &&
3495 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3497 r = TAILQ_NEXT(r, entries);
3498 /* tcp/udp only. gid.op always 0 in other cases */
3499 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3500 pf_socket_lookup(direction, pd, m), 1)) &&
3501 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3503 r = TAILQ_NEXT(r, entries);
3505 !pf_match_ieee8021q_pcp(r->prio, m))
3506 r = TAILQ_NEXT(r, entries);
3508 r->prob <= arc4random())
3509 r = TAILQ_NEXT(r, entries);
3510 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3511 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3512 r = TAILQ_NEXT(r, entries);
3513 else if (r->os_fingerprint != PF_OSFP_ANY &&
3514 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3515 pf_osfp_fingerprint(pd, m, off, th),
3516 r->os_fingerprint)))
3517 r = TAILQ_NEXT(r, entries);
3521 if (r->rtableid >= 0)
3522 rtableid = r->rtableid;
3523 if (r->anchor == NULL) {
3530 r = TAILQ_NEXT(r, entries);
3532 pf_step_into_anchor(anchor_stack, &asd,
3533 &ruleset, PF_RULESET_FILTER, &r, &a,
3536 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3537 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3544 REASON_SET(&reason, PFRES_MATCH);
3546 if (r->log || (nr != NULL && nr->log)) {
3548 m_copyback(m, off, hdrlen, pd->hdr.any);
3549 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3553 if ((r->action == PF_DROP) &&
3554 ((r->rule_flag & PFRULE_RETURNRST) ||
3555 (r->rule_flag & PFRULE_RETURNICMP) ||
3556 (r->rule_flag & PFRULE_RETURN))) {
3557 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3558 bip_sum, hdrlen, &reason);
3561 if (r->action == PF_DROP)
3564 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3565 REASON_SET(&reason, PFRES_MEMORY);
3569 M_SETFIB(m, rtableid);
3571 if (!state_icmp && (r->keep_state || nr != NULL ||
3572 (pd->flags & PFDESC_TCP_NORM))) {
3574 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3575 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3577 if (action != PF_PASS) {
3578 if (action == PF_DROP &&
3579 (r->rule_flag & PFRULE_RETURN))
3580 pf_return(r, nr, pd, sk, off, m, th, kif,
3581 bproto_sum, bip_sum, hdrlen, &reason);
3586 uma_zfree(V_pf_state_key_z, sk);
3588 uma_zfree(V_pf_state_key_z, nk);
3591 /* copy back packet headers if we performed NAT operations */
3593 m_copyback(m, off, hdrlen, pd->hdr.any);
3595 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3596 direction == PF_OUT &&
3597 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3599 * We want the state created, but we dont
3600 * want to send this in case a partner
3601 * firewall has to know about it to allow
3602 * replies through it.
3610 uma_zfree(V_pf_state_key_z, sk);
3612 uma_zfree(V_pf_state_key_z, nk);
3617 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3618 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3619 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3620 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3621 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3623 struct pf_state *s = NULL;
3624 struct pf_src_node *sn = NULL;
3625 struct tcphdr *th = pd->hdr.tcp;
3626 u_int16_t mss = V_tcp_mssdflt;
3629 /* check maximums */
3630 if (r->max_states &&
3631 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3632 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3633 REASON_SET(&reason, PFRES_MAXSTATES);
3636 /* src node for filter rule */
3637 if ((r->rule_flag & PFRULE_SRCTRACK ||
3638 r->rpool.opts & PF_POOL_STICKYADDR) &&
3639 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3640 REASON_SET(&reason, PFRES_SRCLIMIT);
3643 /* src node for translation rule */
3644 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3645 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3646 REASON_SET(&reason, PFRES_SRCLIMIT);
3649 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3651 REASON_SET(&reason, PFRES_MEMORY);
3655 s->nat_rule.ptr = nr;
3657 STATE_INC_COUNTERS(s);
3659 s->state_flags |= PFSTATE_ALLOWOPTS;
3660 if (r->rule_flag & PFRULE_STATESLOPPY)
3661 s->state_flags |= PFSTATE_SLOPPY;
3662 s->log = r->log & PF_LOG_ALL;
3663 s->sync_state = PFSYNC_S_NONE;
3665 s->log |= nr->log & PF_LOG_ALL;
3666 switch (pd->proto) {
3668 s->src.seqlo = ntohl(th->th_seq);
3669 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3670 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3671 r->keep_state == PF_STATE_MODULATE) {
3672 /* Generate sequence number modulator */
3673 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3676 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3677 htonl(s->src.seqlo + s->src.seqdiff), 0);
3681 if (th->th_flags & TH_SYN) {
3683 s->src.wscale = pf_get_wscale(m, off,
3684 th->th_off, pd->af);
3686 s->src.max_win = MAX(ntohs(th->th_win), 1);
3687 if (s->src.wscale & PF_WSCALE_MASK) {
3688 /* Remove scale factor from initial window */
3689 int win = s->src.max_win;
3690 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3691 s->src.max_win = (win - 1) >>
3692 (s->src.wscale & PF_WSCALE_MASK);
3694 if (th->th_flags & TH_FIN)
3698 s->src.state = TCPS_SYN_SENT;
3699 s->dst.state = TCPS_CLOSED;
3700 s->timeout = PFTM_TCP_FIRST_PACKET;
3703 s->src.state = PFUDPS_SINGLE;
3704 s->dst.state = PFUDPS_NO_TRAFFIC;
3705 s->timeout = PFTM_UDP_FIRST_PACKET;
3709 case IPPROTO_ICMPV6:
3711 s->timeout = PFTM_ICMP_FIRST_PACKET;
3714 s->src.state = PFOTHERS_SINGLE;
3715 s->dst.state = PFOTHERS_NO_TRAFFIC;
3716 s->timeout = PFTM_OTHER_FIRST_PACKET;
3720 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3721 REASON_SET(&reason, PFRES_MAPFAILED);
3722 pf_src_tree_remove_state(s);
3723 STATE_DEC_COUNTERS(s);
3724 uma_zfree(V_pf_state_z, s);
3727 s->rt_kif = r->rpool.cur->kif;
3730 s->creation = time_uptime;
3731 s->expire = time_uptime;
3736 /* XXX We only modify one side for now. */
3737 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3738 s->nat_src_node = nsn;
3740 if (pd->proto == IPPROTO_TCP) {
3741 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3742 off, pd, th, &s->src, &s->dst)) {
3743 REASON_SET(&reason, PFRES_MEMORY);
3744 pf_src_tree_remove_state(s);
3745 STATE_DEC_COUNTERS(s);
3746 uma_zfree(V_pf_state_z, s);
3749 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3750 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3751 &s->src, &s->dst, rewrite)) {
3752 /* This really shouldn't happen!!! */
3753 DPFPRINTF(PF_DEBUG_URGENT,
3754 ("pf_normalize_tcp_stateful failed on first "
3756 pf_normalize_tcp_cleanup(s);
3757 pf_src_tree_remove_state(s);
3758 STATE_DEC_COUNTERS(s);
3759 uma_zfree(V_pf_state_z, s);
3763 s->direction = pd->dir;
3766 * sk/nk could already been setup by pf_get_translation().
3769 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3770 __func__, nr, sk, nk));
3771 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3776 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3777 __func__, nr, sk, nk));
3779 /* Swap sk/nk for PF_OUT. */
3780 if (pf_state_insert(BOUND_IFACE(r, kif),
3781 (pd->dir == PF_IN) ? sk : nk,
3782 (pd->dir == PF_IN) ? nk : sk, s)) {
3783 if (pd->proto == IPPROTO_TCP)
3784 pf_normalize_tcp_cleanup(s);
3785 REASON_SET(&reason, PFRES_STATEINS);
3786 pf_src_tree_remove_state(s);
3787 STATE_DEC_COUNTERS(s);
3788 uma_zfree(V_pf_state_z, s);
3795 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3796 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3797 s->src.state = PF_TCPS_PROXY_SRC;
3798 /* undo NAT changes, if they have taken place */
3800 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3801 if (pd->dir == PF_OUT)
3802 skt = s->key[PF_SK_STACK];
3803 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3804 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3806 *pd->sport = skt->port[pd->sidx];
3808 *pd->dport = skt->port[pd->didx];
3810 *pd->proto_sum = bproto_sum;
3812 *pd->ip_sum = bip_sum;
3813 m_copyback(m, off, hdrlen, pd->hdr.any);
3815 s->src.seqhi = htonl(arc4random());
3816 /* Find mss option */
3817 int rtid = M_GETFIB(m);
3818 mss = pf_get_mss(m, off, th->th_off, pd->af);
3819 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3820 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3822 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3823 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3824 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3825 REASON_SET(&reason, PFRES_SYNPROXY);
3826 return (PF_SYNPROXY_DROP);
3833 uma_zfree(V_pf_state_key_z, sk);
3835 uma_zfree(V_pf_state_key_z, nk);
3838 struct pf_srchash *sh;
3840 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3841 PF_HASHROW_LOCK(sh);
3842 if (--sn->states == 0 && sn->expire == 0) {
3843 pf_unlink_src_node(sn);
3844 uma_zfree(V_pf_sources_z, sn);
3846 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3848 PF_HASHROW_UNLOCK(sh);
3851 if (nsn != sn && nsn != NULL) {
3852 struct pf_srchash *sh;
3854 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3855 PF_HASHROW_LOCK(sh);
3856 if (--nsn->states == 0 && nsn->expire == 0) {
3857 pf_unlink_src_node(nsn);
3858 uma_zfree(V_pf_sources_z, nsn);
3860 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3862 PF_HASHROW_UNLOCK(sh);
3869 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3870 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3871 struct pf_ruleset **rsm)
3873 struct pf_rule *r, *a = NULL;
3874 struct pf_ruleset *ruleset = NULL;
3875 sa_family_t af = pd->af;
3880 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3884 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3887 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3888 r = r->skip[PF_SKIP_IFP].ptr;
3889 else if (r->direction && r->direction != direction)
3890 r = r->skip[PF_SKIP_DIR].ptr;
3891 else if (r->af && r->af != af)
3892 r = r->skip[PF_SKIP_AF].ptr;
3893 else if (r->proto && r->proto != pd->proto)
3894 r = r->skip[PF_SKIP_PROTO].ptr;
3895 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3896 r->src.neg, kif, M_GETFIB(m)))
3897 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3898 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3899 r->dst.neg, NULL, M_GETFIB(m)))
3900 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3901 else if (r->tos && !(r->tos == pd->tos))
3902 r = TAILQ_NEXT(r, entries);
3903 else if (r->os_fingerprint != PF_OSFP_ANY)
3904 r = TAILQ_NEXT(r, entries);
3905 else if (pd->proto == IPPROTO_UDP &&
3906 (r->src.port_op || r->dst.port_op))
3907 r = TAILQ_NEXT(r, entries);
3908 else if (pd->proto == IPPROTO_TCP &&
3909 (r->src.port_op || r->dst.port_op || r->flagset))
3910 r = TAILQ_NEXT(r, entries);
3911 else if ((pd->proto == IPPROTO_ICMP ||
3912 pd->proto == IPPROTO_ICMPV6) &&
3913 (r->type || r->code))
3914 r = TAILQ_NEXT(r, entries);
3916 !pf_match_ieee8021q_pcp(r->prio, m))
3917 r = TAILQ_NEXT(r, entries);
3918 else if (r->prob && r->prob <=
3919 (arc4random() % (UINT_MAX - 1) + 1))
3920 r = TAILQ_NEXT(r, entries);
3921 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3922 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3923 r = TAILQ_NEXT(r, entries);
3925 if (r->anchor == NULL) {
3932 r = TAILQ_NEXT(r, entries);
3934 pf_step_into_anchor(anchor_stack, &asd,
3935 &ruleset, PF_RULESET_FILTER, &r, &a,
3938 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3939 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3946 REASON_SET(&reason, PFRES_MATCH);
3949 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3952 if (r->action != PF_PASS)
3955 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3956 REASON_SET(&reason, PFRES_MEMORY);
3964 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3965 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3966 struct pf_pdesc *pd, u_short *reason, int *copyback)
3968 struct tcphdr *th = pd->hdr.tcp;
3969 u_int16_t win = ntohs(th->th_win);
3970 u_int32_t ack, end, seq, orig_seq;
3974 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3975 sws = src->wscale & PF_WSCALE_MASK;
3976 dws = dst->wscale & PF_WSCALE_MASK;
3981 * Sequence tracking algorithm from Guido van Rooij's paper:
3982 * http://www.madison-gurkha.com/publications/tcp_filtering/
3986 orig_seq = seq = ntohl(th->th_seq);
3987 if (src->seqlo == 0) {
3988 /* First packet from this end. Set its state */
3990 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3991 src->scrub == NULL) {
3992 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3993 REASON_SET(reason, PFRES_MEMORY);
3998 /* Deferred generation of sequence number modulator */
3999 if (dst->seqdiff && !src->seqdiff) {
4000 /* use random iss for the TCP server */
4001 while ((src->seqdiff = arc4random() - seq) == 0)
4003 ack = ntohl(th->th_ack) - dst->seqdiff;
4004 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4006 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4009 ack = ntohl(th->th_ack);
4012 end = seq + pd->p_len;
4013 if (th->th_flags & TH_SYN) {
4015 if (dst->wscale & PF_WSCALE_FLAG) {
4016 src->wscale = pf_get_wscale(m, off, th->th_off,
4018 if (src->wscale & PF_WSCALE_FLAG) {
4019 /* Remove scale factor from initial
4021 sws = src->wscale & PF_WSCALE_MASK;
4022 win = ((u_int32_t)win + (1 << sws) - 1)
4024 dws = dst->wscale & PF_WSCALE_MASK;
4026 /* fixup other window */
4027 dst->max_win <<= dst->wscale &
4029 /* in case of a retrans SYN|ACK */
4034 if (th->th_flags & TH_FIN)
4038 if (src->state < TCPS_SYN_SENT)
4039 src->state = TCPS_SYN_SENT;
4042 * May need to slide the window (seqhi may have been set by
4043 * the crappy stack check or if we picked up the connection
4044 * after establishment)
4046 if (src->seqhi == 1 ||
4047 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4048 src->seqhi = end + MAX(1, dst->max_win << dws);
4049 if (win > src->max_win)
4053 ack = ntohl(th->th_ack) - dst->seqdiff;
4055 /* Modulate sequence numbers */
4056 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4058 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4061 end = seq + pd->p_len;
4062 if (th->th_flags & TH_SYN)
4064 if (th->th_flags & TH_FIN)
4068 if ((th->th_flags & TH_ACK) == 0) {
4069 /* Let it pass through the ack skew check */
4071 } else if ((ack == 0 &&
4072 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4073 /* broken tcp stacks do not set ack */
4074 (dst->state < TCPS_SYN_SENT)) {
4076 * Many stacks (ours included) will set the ACK number in an
4077 * FIN|ACK if the SYN times out -- no sequence to ACK.
4083 /* Ease sequencing restrictions on no data packets */
4088 ackskew = dst->seqlo - ack;
4091 * Need to demodulate the sequence numbers in any TCP SACK options
4092 * (Selective ACK). We could optionally validate the SACK values
4093 * against the current ACK window, either forwards or backwards, but
4094 * I'm not confident that SACK has been implemented properly
4095 * everywhere. It wouldn't surprise me if several stacks accidentally
4096 * SACK too far backwards of previously ACKed data. There really aren't
4097 * any security implications of bad SACKing unless the target stack
4098 * doesn't validate the option length correctly. Someone trying to
4099 * spoof into a TCP connection won't bother blindly sending SACK
4102 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4103 if (pf_modulate_sack(m, off, pd, th, dst))
4107 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4108 if (SEQ_GEQ(src->seqhi, end) &&
4109 /* Last octet inside other's window space */
4110 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4111 /* Retrans: not more than one window back */
4112 (ackskew >= -MAXACKWINDOW) &&
4113 /* Acking not more than one reassembled fragment backwards */
4114 (ackskew <= (MAXACKWINDOW << sws)) &&
4115 /* Acking not more than one window forward */
4116 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4117 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4118 (pd->flags & PFDESC_IP_REAS) == 0)) {
4119 /* Require an exact/+1 sequence match on resets when possible */
4121 if (dst->scrub || src->scrub) {
4122 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4123 *state, src, dst, copyback))
4127 /* update max window */
4128 if (src->max_win < win)
4130 /* synchronize sequencing */
4131 if (SEQ_GT(end, src->seqlo))
4133 /* slide the window of what the other end can send */
4134 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4135 dst->seqhi = ack + MAX((win << sws), 1);
4138 if (th->th_flags & TH_SYN)
4139 if (src->state < TCPS_SYN_SENT)
4140 src->state = TCPS_SYN_SENT;
4141 if (th->th_flags & TH_FIN)
4142 if (src->state < TCPS_CLOSING)
4143 src->state = TCPS_CLOSING;
4144 if (th->th_flags & TH_ACK) {
4145 if (dst->state == TCPS_SYN_SENT) {
4146 dst->state = TCPS_ESTABLISHED;
4147 if (src->state == TCPS_ESTABLISHED &&
4148 (*state)->src_node != NULL &&
4149 pf_src_connlimit(state)) {
4150 REASON_SET(reason, PFRES_SRCLIMIT);
4153 } else if (dst->state == TCPS_CLOSING)
4154 dst->state = TCPS_FIN_WAIT_2;
4156 if (th->th_flags & TH_RST)
4157 src->state = dst->state = TCPS_TIME_WAIT;
4159 /* update expire time */
4160 (*state)->expire = time_uptime;
4161 if (src->state >= TCPS_FIN_WAIT_2 &&
4162 dst->state >= TCPS_FIN_WAIT_2)
4163 (*state)->timeout = PFTM_TCP_CLOSED;
4164 else if (src->state >= TCPS_CLOSING &&
4165 dst->state >= TCPS_CLOSING)
4166 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4167 else if (src->state < TCPS_ESTABLISHED ||
4168 dst->state < TCPS_ESTABLISHED)
4169 (*state)->timeout = PFTM_TCP_OPENING;
4170 else if (src->state >= TCPS_CLOSING ||
4171 dst->state >= TCPS_CLOSING)
4172 (*state)->timeout = PFTM_TCP_CLOSING;
4174 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4176 /* Fall through to PASS packet */
4178 } else if ((dst->state < TCPS_SYN_SENT ||
4179 dst->state >= TCPS_FIN_WAIT_2 ||
4180 src->state >= TCPS_FIN_WAIT_2) &&
4181 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4182 /* Within a window forward of the originating packet */
4183 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4184 /* Within a window backward of the originating packet */
4187 * This currently handles three situations:
4188 * 1) Stupid stacks will shotgun SYNs before their peer
4190 * 2) When PF catches an already established stream (the
4191 * firewall rebooted, the state table was flushed, routes
4193 * 3) Packets get funky immediately after the connection
4194 * closes (this should catch Solaris spurious ACK|FINs
4195 * that web servers like to spew after a close)
4197 * This must be a little more careful than the above code
4198 * since packet floods will also be caught here. We don't
4199 * update the TTL here to mitigate the damage of a packet
4200 * flood and so the same code can handle awkward establishment
4201 * and a loosened connection close.
4202 * In the establishment case, a correct peer response will
4203 * validate the connection, go through the normal state code
4204 * and keep updating the state TTL.
4207 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4208 printf("pf: loose state match: ");
4209 pf_print_state(*state);
4210 pf_print_flags(th->th_flags);
4211 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4212 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4213 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4214 (unsigned long long)(*state)->packets[1],
4215 pd->dir == PF_IN ? "in" : "out",
4216 pd->dir == (*state)->direction ? "fwd" : "rev");
4219 if (dst->scrub || src->scrub) {
4220 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4221 *state, src, dst, copyback))
4225 /* update max window */
4226 if (src->max_win < win)
4228 /* synchronize sequencing */
4229 if (SEQ_GT(end, src->seqlo))
4231 /* slide the window of what the other end can send */
4232 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4233 dst->seqhi = ack + MAX((win << sws), 1);
4236 * Cannot set dst->seqhi here since this could be a shotgunned
4237 * SYN and not an already established connection.
4240 if (th->th_flags & TH_FIN)
4241 if (src->state < TCPS_CLOSING)
4242 src->state = TCPS_CLOSING;
4243 if (th->th_flags & TH_RST)
4244 src->state = dst->state = TCPS_TIME_WAIT;
4246 /* Fall through to PASS packet */
4249 if ((*state)->dst.state == TCPS_SYN_SENT &&
4250 (*state)->src.state == TCPS_SYN_SENT) {
4251 /* Send RST for state mismatches during handshake */
4252 if (!(th->th_flags & TH_RST))
4253 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4254 pd->dst, pd->src, th->th_dport,
4255 th->th_sport, ntohl(th->th_ack), 0,
4257 (*state)->rule.ptr->return_ttl, 1, 0,
4262 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4263 printf("pf: BAD state: ");
4264 pf_print_state(*state);
4265 pf_print_flags(th->th_flags);
4266 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4267 "pkts=%llu:%llu dir=%s,%s\n",
4268 seq, orig_seq, ack, pd->p_len, ackskew,
4269 (unsigned long long)(*state)->packets[0],
4270 (unsigned long long)(*state)->packets[1],
4271 pd->dir == PF_IN ? "in" : "out",
4272 pd->dir == (*state)->direction ? "fwd" : "rev");
4273 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4274 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4275 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4277 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4278 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4279 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4280 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4282 REASON_SET(reason, PFRES_BADSTATE);
4290 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4291 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4293 struct tcphdr *th = pd->hdr.tcp;
4295 if (th->th_flags & TH_SYN)
4296 if (src->state < TCPS_SYN_SENT)
4297 src->state = TCPS_SYN_SENT;
4298 if (th->th_flags & TH_FIN)
4299 if (src->state < TCPS_CLOSING)
4300 src->state = TCPS_CLOSING;
4301 if (th->th_flags & TH_ACK) {
4302 if (dst->state == TCPS_SYN_SENT) {
4303 dst->state = TCPS_ESTABLISHED;
4304 if (src->state == TCPS_ESTABLISHED &&
4305 (*state)->src_node != NULL &&
4306 pf_src_connlimit(state)) {
4307 REASON_SET(reason, PFRES_SRCLIMIT);
4310 } else if (dst->state == TCPS_CLOSING) {
4311 dst->state = TCPS_FIN_WAIT_2;
4312 } else if (src->state == TCPS_SYN_SENT &&
4313 dst->state < TCPS_SYN_SENT) {
4315 * Handle a special sloppy case where we only see one
4316 * half of the connection. If there is a ACK after
4317 * the initial SYN without ever seeing a packet from
4318 * the destination, set the connection to established.
4320 dst->state = src->state = TCPS_ESTABLISHED;
4321 if ((*state)->src_node != NULL &&
4322 pf_src_connlimit(state)) {
4323 REASON_SET(reason, PFRES_SRCLIMIT);
4326 } else if (src->state == TCPS_CLOSING &&
4327 dst->state == TCPS_ESTABLISHED &&
4330 * Handle the closing of half connections where we
4331 * don't see the full bidirectional FIN/ACK+ACK
4334 dst->state = TCPS_CLOSING;
4337 if (th->th_flags & TH_RST)
4338 src->state = dst->state = TCPS_TIME_WAIT;
4340 /* update expire time */
4341 (*state)->expire = time_uptime;
4342 if (src->state >= TCPS_FIN_WAIT_2 &&
4343 dst->state >= TCPS_FIN_WAIT_2)
4344 (*state)->timeout = PFTM_TCP_CLOSED;
4345 else if (src->state >= TCPS_CLOSING &&
4346 dst->state >= TCPS_CLOSING)
4347 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4348 else if (src->state < TCPS_ESTABLISHED ||
4349 dst->state < TCPS_ESTABLISHED)
4350 (*state)->timeout = PFTM_TCP_OPENING;
4351 else if (src->state >= TCPS_CLOSING ||
4352 dst->state >= TCPS_CLOSING)
4353 (*state)->timeout = PFTM_TCP_CLOSING;
4355 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4361 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4362 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4365 struct pf_state_key_cmp key;
4366 struct tcphdr *th = pd->hdr.tcp;
4368 struct pf_state_peer *src, *dst;
4369 struct pf_state_key *sk;
4371 bzero(&key, sizeof(key));
4373 key.proto = IPPROTO_TCP;
4374 if (direction == PF_IN) { /* wire side, straight */
4375 PF_ACPY(&key.addr[0], pd->src, key.af);
4376 PF_ACPY(&key.addr[1], pd->dst, key.af);
4377 key.port[0] = th->th_sport;
4378 key.port[1] = th->th_dport;
4379 } else { /* stack side, reverse */
4380 PF_ACPY(&key.addr[1], pd->src, key.af);
4381 PF_ACPY(&key.addr[0], pd->dst, key.af);
4382 key.port[1] = th->th_sport;
4383 key.port[0] = th->th_dport;
4386 STATE_LOOKUP(kif, &key, direction, *state, pd);
4388 if (direction == (*state)->direction) {
4389 src = &(*state)->src;
4390 dst = &(*state)->dst;
4392 src = &(*state)->dst;
4393 dst = &(*state)->src;
4396 sk = (*state)->key[pd->didx];
4398 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4399 if (direction != (*state)->direction) {
4400 REASON_SET(reason, PFRES_SYNPROXY);
4401 return (PF_SYNPROXY_DROP);
4403 if (th->th_flags & TH_SYN) {
4404 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4405 REASON_SET(reason, PFRES_SYNPROXY);
4408 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4409 pd->src, th->th_dport, th->th_sport,
4410 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4411 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4412 REASON_SET(reason, PFRES_SYNPROXY);
4413 return (PF_SYNPROXY_DROP);
4414 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4415 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4416 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4417 REASON_SET(reason, PFRES_SYNPROXY);
4419 } else if ((*state)->src_node != NULL &&
4420 pf_src_connlimit(state)) {
4421 REASON_SET(reason, PFRES_SRCLIMIT);
4424 (*state)->src.state = PF_TCPS_PROXY_DST;
4426 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4427 if (direction == (*state)->direction) {
4428 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4429 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4430 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4431 REASON_SET(reason, PFRES_SYNPROXY);
4434 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4435 if ((*state)->dst.seqhi == 1)
4436 (*state)->dst.seqhi = htonl(arc4random());
4437 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4438 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4439 sk->port[pd->sidx], sk->port[pd->didx],
4440 (*state)->dst.seqhi, 0, TH_SYN, 0,
4441 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4442 REASON_SET(reason, PFRES_SYNPROXY);
4443 return (PF_SYNPROXY_DROP);
4444 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4446 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4447 REASON_SET(reason, PFRES_SYNPROXY);
4450 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4451 (*state)->dst.seqlo = ntohl(th->th_seq);
4452 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4453 pd->src, th->th_dport, th->th_sport,
4454 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4455 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4456 (*state)->tag, NULL);
4457 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4458 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4459 sk->port[pd->sidx], sk->port[pd->didx],
4460 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4461 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4462 (*state)->src.seqdiff = (*state)->dst.seqhi -
4463 (*state)->src.seqlo;
4464 (*state)->dst.seqdiff = (*state)->src.seqhi -
4465 (*state)->dst.seqlo;
4466 (*state)->src.seqhi = (*state)->src.seqlo +
4467 (*state)->dst.max_win;
4468 (*state)->dst.seqhi = (*state)->dst.seqlo +
4469 (*state)->src.max_win;
4470 (*state)->src.wscale = (*state)->dst.wscale = 0;
4471 (*state)->src.state = (*state)->dst.state =
4473 REASON_SET(reason, PFRES_SYNPROXY);
4474 return (PF_SYNPROXY_DROP);
4478 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4479 dst->state >= TCPS_FIN_WAIT_2 &&
4480 src->state >= TCPS_FIN_WAIT_2) {
4481 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4482 printf("pf: state reuse ");
4483 pf_print_state(*state);
4484 pf_print_flags(th->th_flags);
4487 /* XXX make sure it's the same direction ?? */
4488 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4489 pf_unlink_state(*state, PF_ENTER_LOCKED);
4494 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4495 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4498 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4499 ©back) == PF_DROP)
4503 /* translate source/destination address, if necessary */
4504 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4505 struct pf_state_key *nk = (*state)->key[pd->didx];
4507 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4508 nk->port[pd->sidx] != th->th_sport)
4509 pf_change_ap(m, pd->src, &th->th_sport,
4510 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4511 nk->port[pd->sidx], 0, pd->af);
4513 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4514 nk->port[pd->didx] != th->th_dport)
4515 pf_change_ap(m, pd->dst, &th->th_dport,
4516 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4517 nk->port[pd->didx], 0, pd->af);
4521 /* Copyback sequence modulation or stateful scrub changes if needed */
4523 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4529 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4530 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4532 struct pf_state_peer *src, *dst;
4533 struct pf_state_key_cmp key;
4534 struct udphdr *uh = pd->hdr.udp;
4536 bzero(&key, sizeof(key));
4538 key.proto = IPPROTO_UDP;
4539 if (direction == PF_IN) { /* wire side, straight */
4540 PF_ACPY(&key.addr[0], pd->src, key.af);
4541 PF_ACPY(&key.addr[1], pd->dst, key.af);
4542 key.port[0] = uh->uh_sport;
4543 key.port[1] = uh->uh_dport;
4544 } else { /* stack side, reverse */
4545 PF_ACPY(&key.addr[1], pd->src, key.af);
4546 PF_ACPY(&key.addr[0], pd->dst, key.af);
4547 key.port[1] = uh->uh_sport;
4548 key.port[0] = uh->uh_dport;
4551 STATE_LOOKUP(kif, &key, direction, *state, pd);
4553 if (direction == (*state)->direction) {
4554 src = &(*state)->src;
4555 dst = &(*state)->dst;
4557 src = &(*state)->dst;
4558 dst = &(*state)->src;
4562 if (src->state < PFUDPS_SINGLE)
4563 src->state = PFUDPS_SINGLE;
4564 if (dst->state == PFUDPS_SINGLE)
4565 dst->state = PFUDPS_MULTIPLE;
4567 /* update expire time */
4568 (*state)->expire = time_uptime;
4569 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4570 (*state)->timeout = PFTM_UDP_MULTIPLE;
4572 (*state)->timeout = PFTM_UDP_SINGLE;
4574 /* translate source/destination address, if necessary */
4575 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4576 struct pf_state_key *nk = (*state)->key[pd->didx];
4578 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4579 nk->port[pd->sidx] != uh->uh_sport)
4580 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4581 &uh->uh_sum, &nk->addr[pd->sidx],
4582 nk->port[pd->sidx], 1, pd->af);
4584 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4585 nk->port[pd->didx] != uh->uh_dport)
4586 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4587 &uh->uh_sum, &nk->addr[pd->didx],
4588 nk->port[pd->didx], 1, pd->af);
4589 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4596 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4597 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4599 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4600 u_int16_t icmpid = 0, *icmpsum;
4601 u_int8_t icmptype, icmpcode;
4603 struct pf_state_key_cmp key;
4605 bzero(&key, sizeof(key));
4606 switch (pd->proto) {
4609 icmptype = pd->hdr.icmp->icmp_type;
4610 icmpcode = pd->hdr.icmp->icmp_code;
4611 icmpid = pd->hdr.icmp->icmp_id;
4612 icmpsum = &pd->hdr.icmp->icmp_cksum;
4614 if (icmptype == ICMP_UNREACH ||
4615 icmptype == ICMP_SOURCEQUENCH ||
4616 icmptype == ICMP_REDIRECT ||
4617 icmptype == ICMP_TIMXCEED ||
4618 icmptype == ICMP_PARAMPROB)
4623 case IPPROTO_ICMPV6:
4624 icmptype = pd->hdr.icmp6->icmp6_type;
4625 icmpcode = pd->hdr.icmp6->icmp6_code;
4626 icmpid = pd->hdr.icmp6->icmp6_id;
4627 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4629 if (icmptype == ICMP6_DST_UNREACH ||
4630 icmptype == ICMP6_PACKET_TOO_BIG ||
4631 icmptype == ICMP6_TIME_EXCEEDED ||
4632 icmptype == ICMP6_PARAM_PROB)
4640 * ICMP query/reply message not related to a TCP/UDP packet.
4641 * Search for an ICMP state.
4644 key.proto = pd->proto;
4645 key.port[0] = key.port[1] = icmpid;
4646 if (direction == PF_IN) { /* wire side, straight */
4647 PF_ACPY(&key.addr[0], pd->src, key.af);
4648 PF_ACPY(&key.addr[1], pd->dst, key.af);
4649 } else { /* stack side, reverse */
4650 PF_ACPY(&key.addr[1], pd->src, key.af);
4651 PF_ACPY(&key.addr[0], pd->dst, key.af);
4654 STATE_LOOKUP(kif, &key, direction, *state, pd);
4656 (*state)->expire = time_uptime;
4657 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4659 /* translate source/destination address, if necessary */
4660 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4661 struct pf_state_key *nk = (*state)->key[pd->didx];
4666 if (PF_ANEQ(pd->src,
4667 &nk->addr[pd->sidx], AF_INET))
4668 pf_change_a(&saddr->v4.s_addr,
4670 nk->addr[pd->sidx].v4.s_addr, 0);
4672 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4674 pf_change_a(&daddr->v4.s_addr,
4676 nk->addr[pd->didx].v4.s_addr, 0);
4679 pd->hdr.icmp->icmp_id) {
4680 pd->hdr.icmp->icmp_cksum =
4682 pd->hdr.icmp->icmp_cksum, icmpid,
4683 nk->port[pd->sidx], 0);
4684 pd->hdr.icmp->icmp_id =
4688 m_copyback(m, off, ICMP_MINLEN,
4689 (caddr_t )pd->hdr.icmp);
4694 if (PF_ANEQ(pd->src,
4695 &nk->addr[pd->sidx], AF_INET6))
4697 &pd->hdr.icmp6->icmp6_cksum,
4698 &nk->addr[pd->sidx], 0);
4700 if (PF_ANEQ(pd->dst,
4701 &nk->addr[pd->didx], AF_INET6))
4703 &pd->hdr.icmp6->icmp6_cksum,
4704 &nk->addr[pd->didx], 0);
4706 m_copyback(m, off, sizeof(struct icmp6_hdr),
4707 (caddr_t )pd->hdr.icmp6);
4716 * ICMP error message in response to a TCP/UDP packet.
4717 * Extract the inner TCP/UDP header and search for that state.
4720 struct pf_pdesc pd2;
4721 bzero(&pd2, sizeof pd2);
4726 struct ip6_hdr h2_6;
4733 /* Payload packet is from the opposite direction. */
4734 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4735 pd2.didx = (direction == PF_IN) ? 0 : 1;
4739 /* offset of h2 in mbuf chain */
4740 ipoff2 = off + ICMP_MINLEN;
4742 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4743 NULL, reason, pd2.af)) {
4744 DPFPRINTF(PF_DEBUG_MISC,
4745 ("pf: ICMP error message too short "
4750 * ICMP error messages don't refer to non-first
4753 if (h2.ip_off & htons(IP_OFFMASK)) {
4754 REASON_SET(reason, PFRES_FRAG);
4758 /* offset of protocol header that follows h2 */
4759 off2 = ipoff2 + (h2.ip_hl << 2);
4761 pd2.proto = h2.ip_p;
4762 pd2.src = (struct pf_addr *)&h2.ip_src;
4763 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4764 pd2.ip_sum = &h2.ip_sum;
4769 ipoff2 = off + sizeof(struct icmp6_hdr);
4771 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4772 NULL, reason, pd2.af)) {
4773 DPFPRINTF(PF_DEBUG_MISC,
4774 ("pf: ICMP error message too short "
4778 pd2.proto = h2_6.ip6_nxt;
4779 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4780 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4782 off2 = ipoff2 + sizeof(h2_6);
4784 switch (pd2.proto) {
4785 case IPPROTO_FRAGMENT:
4787 * ICMPv6 error messages for
4788 * non-first fragments
4790 REASON_SET(reason, PFRES_FRAG);
4793 case IPPROTO_HOPOPTS:
4794 case IPPROTO_ROUTING:
4795 case IPPROTO_DSTOPTS: {
4796 /* get next header and header length */
4797 struct ip6_ext opt6;
4799 if (!pf_pull_hdr(m, off2, &opt6,
4800 sizeof(opt6), NULL, reason,
4802 DPFPRINTF(PF_DEBUG_MISC,
4803 ("pf: ICMPv6 short opt\n"));
4806 if (pd2.proto == IPPROTO_AH)
4807 off2 += (opt6.ip6e_len + 2) * 4;
4809 off2 += (opt6.ip6e_len + 1) * 8;
4810 pd2.proto = opt6.ip6e_nxt;
4811 /* goto the next header */
4818 } while (!terminal);
4823 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4824 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4825 printf("pf: BAD ICMP %d:%d outer dst: ",
4826 icmptype, icmpcode);
4827 pf_print_host(pd->src, 0, pd->af);
4829 pf_print_host(pd->dst, 0, pd->af);
4830 printf(" inner src: ");
4831 pf_print_host(pd2.src, 0, pd2.af);
4833 pf_print_host(pd2.dst, 0, pd2.af);
4836 REASON_SET(reason, PFRES_BADSTATE);
4840 switch (pd2.proto) {
4844 struct pf_state_peer *src, *dst;
4849 * Only the first 8 bytes of the TCP header can be
4850 * expected. Don't access any TCP header fields after
4851 * th_seq, an ackskew test is not possible.
4853 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4855 DPFPRINTF(PF_DEBUG_MISC,
4856 ("pf: ICMP error message too short "
4862 key.proto = IPPROTO_TCP;
4863 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4864 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4865 key.port[pd2.sidx] = th.th_sport;
4866 key.port[pd2.didx] = th.th_dport;
4868 STATE_LOOKUP(kif, &key, direction, *state, pd);
4870 if (direction == (*state)->direction) {
4871 src = &(*state)->dst;
4872 dst = &(*state)->src;
4874 src = &(*state)->src;
4875 dst = &(*state)->dst;
4878 if (src->wscale && dst->wscale)
4879 dws = dst->wscale & PF_WSCALE_MASK;
4883 /* Demodulate sequence number */
4884 seq = ntohl(th.th_seq) - src->seqdiff;
4886 pf_change_a(&th.th_seq, icmpsum,
4891 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4892 (!SEQ_GEQ(src->seqhi, seq) ||
4893 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4894 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4895 printf("pf: BAD ICMP %d:%d ",
4896 icmptype, icmpcode);
4897 pf_print_host(pd->src, 0, pd->af);
4899 pf_print_host(pd->dst, 0, pd->af);
4901 pf_print_state(*state);
4902 printf(" seq=%u\n", seq);
4904 REASON_SET(reason, PFRES_BADSTATE);
4907 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4908 printf("pf: OK ICMP %d:%d ",
4909 icmptype, icmpcode);
4910 pf_print_host(pd->src, 0, pd->af);
4912 pf_print_host(pd->dst, 0, pd->af);
4914 pf_print_state(*state);
4915 printf(" seq=%u\n", seq);
4919 /* translate source/destination address, if necessary */
4920 if ((*state)->key[PF_SK_WIRE] !=
4921 (*state)->key[PF_SK_STACK]) {
4922 struct pf_state_key *nk =
4923 (*state)->key[pd->didx];
4925 if (PF_ANEQ(pd2.src,
4926 &nk->addr[pd2.sidx], pd2.af) ||
4927 nk->port[pd2.sidx] != th.th_sport)
4928 pf_change_icmp(pd2.src, &th.th_sport,
4929 daddr, &nk->addr[pd2.sidx],
4930 nk->port[pd2.sidx], NULL,
4931 pd2.ip_sum, icmpsum,
4932 pd->ip_sum, 0, pd2.af);
4934 if (PF_ANEQ(pd2.dst,
4935 &nk->addr[pd2.didx], pd2.af) ||
4936 nk->port[pd2.didx] != th.th_dport)
4937 pf_change_icmp(pd2.dst, &th.th_dport,
4938 saddr, &nk->addr[pd2.didx],
4939 nk->port[pd2.didx], NULL,
4940 pd2.ip_sum, icmpsum,
4941 pd->ip_sum, 0, pd2.af);
4949 m_copyback(m, off, ICMP_MINLEN,
4950 (caddr_t )pd->hdr.icmp);
4951 m_copyback(m, ipoff2, sizeof(h2),
4958 sizeof(struct icmp6_hdr),
4959 (caddr_t )pd->hdr.icmp6);
4960 m_copyback(m, ipoff2, sizeof(h2_6),
4965 m_copyback(m, off2, 8, (caddr_t)&th);
4974 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4975 NULL, reason, pd2.af)) {
4976 DPFPRINTF(PF_DEBUG_MISC,
4977 ("pf: ICMP error message too short "
4983 key.proto = IPPROTO_UDP;
4984 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4985 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4986 key.port[pd2.sidx] = uh.uh_sport;
4987 key.port[pd2.didx] = uh.uh_dport;
4989 STATE_LOOKUP(kif, &key, direction, *state, pd);
4991 /* translate source/destination address, if necessary */
4992 if ((*state)->key[PF_SK_WIRE] !=
4993 (*state)->key[PF_SK_STACK]) {
4994 struct pf_state_key *nk =
4995 (*state)->key[pd->didx];
4997 if (PF_ANEQ(pd2.src,
4998 &nk->addr[pd2.sidx], pd2.af) ||
4999 nk->port[pd2.sidx] != uh.uh_sport)
5000 pf_change_icmp(pd2.src, &uh.uh_sport,
5001 daddr, &nk->addr[pd2.sidx],
5002 nk->port[pd2.sidx], &uh.uh_sum,
5003 pd2.ip_sum, icmpsum,
5004 pd->ip_sum, 1, pd2.af);
5006 if (PF_ANEQ(pd2.dst,
5007 &nk->addr[pd2.didx], pd2.af) ||
5008 nk->port[pd2.didx] != uh.uh_dport)
5009 pf_change_icmp(pd2.dst, &uh.uh_dport,
5010 saddr, &nk->addr[pd2.didx],
5011 nk->port[pd2.didx], &uh.uh_sum,
5012 pd2.ip_sum, icmpsum,
5013 pd->ip_sum, 1, pd2.af);
5018 m_copyback(m, off, ICMP_MINLEN,
5019 (caddr_t )pd->hdr.icmp);
5020 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5026 sizeof(struct icmp6_hdr),
5027 (caddr_t )pd->hdr.icmp6);
5028 m_copyback(m, ipoff2, sizeof(h2_6),
5033 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5039 case IPPROTO_ICMP: {
5042 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5043 NULL, reason, pd2.af)) {
5044 DPFPRINTF(PF_DEBUG_MISC,
5045 ("pf: ICMP error message too short i"
5051 key.proto = IPPROTO_ICMP;
5052 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5053 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5054 key.port[0] = key.port[1] = iih.icmp_id;
5056 STATE_LOOKUP(kif, &key, direction, *state, pd);
5058 /* translate source/destination address, if necessary */
5059 if ((*state)->key[PF_SK_WIRE] !=
5060 (*state)->key[PF_SK_STACK]) {
5061 struct pf_state_key *nk =
5062 (*state)->key[pd->didx];
5064 if (PF_ANEQ(pd2.src,
5065 &nk->addr[pd2.sidx], pd2.af) ||
5066 nk->port[pd2.sidx] != iih.icmp_id)
5067 pf_change_icmp(pd2.src, &iih.icmp_id,
5068 daddr, &nk->addr[pd2.sidx],
5069 nk->port[pd2.sidx], NULL,
5070 pd2.ip_sum, icmpsum,
5071 pd->ip_sum, 0, AF_INET);
5073 if (PF_ANEQ(pd2.dst,
5074 &nk->addr[pd2.didx], pd2.af) ||
5075 nk->port[pd2.didx] != iih.icmp_id)
5076 pf_change_icmp(pd2.dst, &iih.icmp_id,
5077 saddr, &nk->addr[pd2.didx],
5078 nk->port[pd2.didx], NULL,
5079 pd2.ip_sum, icmpsum,
5080 pd->ip_sum, 0, AF_INET);
5082 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5083 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5084 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5091 case IPPROTO_ICMPV6: {
5092 struct icmp6_hdr iih;
5094 if (!pf_pull_hdr(m, off2, &iih,
5095 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5096 DPFPRINTF(PF_DEBUG_MISC,
5097 ("pf: ICMP error message too short "
5103 key.proto = IPPROTO_ICMPV6;
5104 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5105 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5106 key.port[0] = key.port[1] = iih.icmp6_id;
5108 STATE_LOOKUP(kif, &key, direction, *state, pd);
5110 /* translate source/destination address, if necessary */
5111 if ((*state)->key[PF_SK_WIRE] !=
5112 (*state)->key[PF_SK_STACK]) {
5113 struct pf_state_key *nk =
5114 (*state)->key[pd->didx];
5116 if (PF_ANEQ(pd2.src,
5117 &nk->addr[pd2.sidx], pd2.af) ||
5118 nk->port[pd2.sidx] != iih.icmp6_id)
5119 pf_change_icmp(pd2.src, &iih.icmp6_id,
5120 daddr, &nk->addr[pd2.sidx],
5121 nk->port[pd2.sidx], NULL,
5122 pd2.ip_sum, icmpsum,
5123 pd->ip_sum, 0, AF_INET6);
5125 if (PF_ANEQ(pd2.dst,
5126 &nk->addr[pd2.didx], pd2.af) ||
5127 nk->port[pd2.didx] != iih.icmp6_id)
5128 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5129 saddr, &nk->addr[pd2.didx],
5130 nk->port[pd2.didx], NULL,
5131 pd2.ip_sum, icmpsum,
5132 pd->ip_sum, 0, AF_INET6);
5134 m_copyback(m, off, sizeof(struct icmp6_hdr),
5135 (caddr_t)pd->hdr.icmp6);
5136 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5137 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5146 key.proto = pd2.proto;
5147 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5148 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5149 key.port[0] = key.port[1] = 0;
5151 STATE_LOOKUP(kif, &key, direction, *state, pd);
5153 /* translate source/destination address, if necessary */
5154 if ((*state)->key[PF_SK_WIRE] !=
5155 (*state)->key[PF_SK_STACK]) {
5156 struct pf_state_key *nk =
5157 (*state)->key[pd->didx];
5159 if (PF_ANEQ(pd2.src,
5160 &nk->addr[pd2.sidx], pd2.af))
5161 pf_change_icmp(pd2.src, NULL, daddr,
5162 &nk->addr[pd2.sidx], 0, NULL,
5163 pd2.ip_sum, icmpsum,
5164 pd->ip_sum, 0, pd2.af);
5166 if (PF_ANEQ(pd2.dst,
5167 &nk->addr[pd2.didx], pd2.af))
5168 pf_change_icmp(pd2.dst, NULL, saddr,
5169 &nk->addr[pd2.didx], 0, NULL,
5170 pd2.ip_sum, icmpsum,
5171 pd->ip_sum, 0, pd2.af);
5176 m_copyback(m, off, ICMP_MINLEN,
5177 (caddr_t)pd->hdr.icmp);
5178 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5184 sizeof(struct icmp6_hdr),
5185 (caddr_t )pd->hdr.icmp6);
5186 m_copyback(m, ipoff2, sizeof(h2_6),
5200 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5201 struct mbuf *m, struct pf_pdesc *pd)
5203 struct pf_state_peer *src, *dst;
5204 struct pf_state_key_cmp key;
5206 bzero(&key, sizeof(key));
5208 key.proto = pd->proto;
5209 if (direction == PF_IN) {
5210 PF_ACPY(&key.addr[0], pd->src, key.af);
5211 PF_ACPY(&key.addr[1], pd->dst, key.af);
5212 key.port[0] = key.port[1] = 0;
5214 PF_ACPY(&key.addr[1], pd->src, key.af);
5215 PF_ACPY(&key.addr[0], pd->dst, key.af);
5216 key.port[1] = key.port[0] = 0;
5219 STATE_LOOKUP(kif, &key, direction, *state, pd);
5221 if (direction == (*state)->direction) {
5222 src = &(*state)->src;
5223 dst = &(*state)->dst;
5225 src = &(*state)->dst;
5226 dst = &(*state)->src;
5230 if (src->state < PFOTHERS_SINGLE)
5231 src->state = PFOTHERS_SINGLE;
5232 if (dst->state == PFOTHERS_SINGLE)
5233 dst->state = PFOTHERS_MULTIPLE;
5235 /* update expire time */
5236 (*state)->expire = time_uptime;
5237 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5238 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5240 (*state)->timeout = PFTM_OTHER_SINGLE;
5242 /* translate source/destination address, if necessary */
5243 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5244 struct pf_state_key *nk = (*state)->key[pd->didx];
5246 KASSERT(nk, ("%s: nk is null", __func__));
5247 KASSERT(pd, ("%s: pd is null", __func__));
5248 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5249 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5253 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5254 pf_change_a(&pd->src->v4.s_addr,
5256 nk->addr[pd->sidx].v4.s_addr,
5259 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5260 pf_change_a(&pd->dst->v4.s_addr,
5262 nk->addr[pd->didx].v4.s_addr,
5269 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5270 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5272 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5273 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5281 * ipoff and off are measured from the start of the mbuf chain.
5282 * h must be at "ipoff" on the mbuf chain.
5285 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5286 u_short *actionp, u_short *reasonp, sa_family_t af)
5291 struct ip *h = mtod(m, struct ip *);
5292 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5296 ACTION_SET(actionp, PF_PASS);
5298 ACTION_SET(actionp, PF_DROP);
5299 REASON_SET(reasonp, PFRES_FRAG);
5303 if (m->m_pkthdr.len < off + len ||
5304 ntohs(h->ip_len) < off + len) {
5305 ACTION_SET(actionp, PF_DROP);
5306 REASON_SET(reasonp, PFRES_SHORT);
5314 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5316 if (m->m_pkthdr.len < off + len ||
5317 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5318 (unsigned)(off + len)) {
5319 ACTION_SET(actionp, PF_DROP);
5320 REASON_SET(reasonp, PFRES_SHORT);
5327 m_copydata(m, off, len, p);
5332 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5338 * Skip check for addresses with embedded interface scope,
5339 * as they would always match anyway.
5341 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5344 if (af != AF_INET && af != AF_INET6)
5347 /* Skip checks for ipsec interfaces */
5348 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5351 ifp = (kif != NULL) ? kif->pfik_ifp : NULL;
5356 return (fib6_check_urpf(rtableid, &addr->v6, 0, NHR_NONE,
5361 return (fib4_check_urpf(rtableid, addr->v4, 0, NHR_NONE,
5371 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5372 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5374 struct mbuf *m0, *m1;
5375 struct sockaddr_in dst;
5377 struct ifnet *ifp = NULL;
5378 struct pf_addr naddr;
5379 struct pf_src_node *sn = NULL;
5381 uint16_t ip_len, ip_off;
5383 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5384 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5387 if ((pd->pf_mtag == NULL &&
5388 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5389 pd->pf_mtag->routed++ > 3) {
5395 if (r->rt == PF_DUPTO) {
5396 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5402 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5410 ip = mtod(m0, struct ip *);
5412 bzero(&dst, sizeof(dst));
5413 dst.sin_family = AF_INET;
5414 dst.sin_len = sizeof(dst);
5415 dst.sin_addr = ip->ip_dst;
5417 bzero(&naddr, sizeof(naddr));
5419 if (TAILQ_EMPTY(&r->rpool.list)) {
5420 DPFPRINTF(PF_DEBUG_URGENT,
5421 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5425 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5427 if (!PF_AZERO(&naddr, AF_INET))
5428 dst.sin_addr.s_addr = naddr.v4.s_addr;
5429 ifp = r->rpool.cur->kif ?
5430 r->rpool.cur->kif->pfik_ifp : NULL;
5432 if (!PF_AZERO(&s->rt_addr, AF_INET))
5433 dst.sin_addr.s_addr =
5434 s->rt_addr.v4.s_addr;
5435 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5442 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5444 else if (m0 == NULL)
5446 if (m0->m_len < sizeof(struct ip)) {
5447 DPFPRINTF(PF_DEBUG_URGENT,
5448 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5451 ip = mtod(m0, struct ip *);
5454 if (ifp->if_flags & IFF_LOOPBACK)
5455 m0->m_flags |= M_SKIP_FIREWALL;
5457 ip_len = ntohs(ip->ip_len);
5458 ip_off = ntohs(ip->ip_off);
5460 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5461 m0->m_pkthdr.csum_flags |= CSUM_IP;
5462 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5463 in_delayed_cksum(m0);
5464 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5466 #if defined(SCTP) || defined(SCTP_SUPPORT)
5467 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5468 sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
5469 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5474 * If small enough for interface, or the interface will take
5475 * care of the fragmentation for us, we can just send directly.
5477 if (ip_len <= ifp->if_mtu ||
5478 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5480 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5481 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5482 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5484 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5485 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5489 /* Balk when DF bit is set or the interface didn't support TSO. */
5490 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5492 KMOD_IPSTAT_INC(ips_cantfrag);
5493 if (r->rt != PF_DUPTO) {
5494 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5501 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5505 for (; m0; m0 = m1) {
5507 m0->m_nextpkt = NULL;
5509 m_clrprotoflags(m0);
5510 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5516 KMOD_IPSTAT_INC(ips_fragmented);
5519 if (r->rt != PF_DUPTO)
5534 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5535 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5538 struct sockaddr_in6 dst;
5539 struct ip6_hdr *ip6;
5540 struct ifnet *ifp = NULL;
5541 struct pf_addr naddr;
5542 struct pf_src_node *sn = NULL;
5544 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5545 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5548 if ((pd->pf_mtag == NULL &&
5549 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5550 pd->pf_mtag->routed++ > 3) {
5556 if (r->rt == PF_DUPTO) {
5557 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5563 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5571 ip6 = mtod(m0, struct ip6_hdr *);
5573 bzero(&dst, sizeof(dst));
5574 dst.sin6_family = AF_INET6;
5575 dst.sin6_len = sizeof(dst);
5576 dst.sin6_addr = ip6->ip6_dst;
5578 bzero(&naddr, sizeof(naddr));
5580 if (TAILQ_EMPTY(&r->rpool.list)) {
5581 DPFPRINTF(PF_DEBUG_URGENT,
5582 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5586 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5588 if (!PF_AZERO(&naddr, AF_INET6))
5589 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5591 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5593 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5594 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5595 &s->rt_addr, AF_INET6);
5596 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5606 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5608 else if (m0 == NULL)
5610 if (m0->m_len < sizeof(struct ip6_hdr)) {
5611 DPFPRINTF(PF_DEBUG_URGENT,
5612 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5616 ip6 = mtod(m0, struct ip6_hdr *);
5619 if (ifp->if_flags & IFF_LOOPBACK)
5620 m0->m_flags |= M_SKIP_FIREWALL;
5622 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5623 ~ifp->if_hwassist) {
5624 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5625 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5626 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5630 * If the packet is too large for the outgoing interface,
5631 * send back an icmp6 error.
5633 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5634 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5635 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5636 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5638 in6_ifstat_inc(ifp, ifs6_in_toobig);
5639 if (r->rt != PF_DUPTO)
5640 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5646 if (r->rt != PF_DUPTO)
5660 * FreeBSD supports cksum offloads for the following drivers.
5661 * em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5663 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5664 * network driver performed cksum including pseudo header, need to verify
5667 * network driver performed cksum, needs to additional pseudo header
5668 * cksum computation with partial csum_data(i.e. lack of H/W support for
5669 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5671 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5672 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5674 * Also, set csum_data to 0xffff to force cksum validation.
5677 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5683 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5685 if (m->m_pkthdr.len < off + len)
5690 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5691 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5692 sum = m->m_pkthdr.csum_data;
5694 ip = mtod(m, struct ip *);
5695 sum = in_pseudo(ip->ip_src.s_addr,
5696 ip->ip_dst.s_addr, htonl((u_short)len +
5697 m->m_pkthdr.csum_data + IPPROTO_TCP));
5704 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5705 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5706 sum = m->m_pkthdr.csum_data;
5708 ip = mtod(m, struct ip *);
5709 sum = in_pseudo(ip->ip_src.s_addr,
5710 ip->ip_dst.s_addr, htonl((u_short)len +
5711 m->m_pkthdr.csum_data + IPPROTO_UDP));
5719 case IPPROTO_ICMPV6:
5729 if (p == IPPROTO_ICMP) {
5734 sum = in_cksum(m, len);
5738 if (m->m_len < sizeof(struct ip))
5740 sum = in4_cksum(m, p, off, len);
5745 if (m->m_len < sizeof(struct ip6_hdr))
5747 sum = in6_cksum(m, p, off, len);
5758 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5763 KMOD_UDPSTAT_INC(udps_badsum);
5769 KMOD_ICMPSTAT_INC(icps_checksum);
5774 case IPPROTO_ICMPV6:
5776 KMOD_ICMP6STAT_INC(icp6s_checksum);
5783 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5784 m->m_pkthdr.csum_flags |=
5785 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5786 m->m_pkthdr.csum_data = 0xffff;
5794 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5796 struct pfi_kif *kif;
5797 u_short action, reason = 0, log = 0;
5798 struct mbuf *m = *m0;
5799 struct ip *h = NULL;
5800 struct m_tag *ipfwtag;
5801 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5802 struct pf_state *s = NULL;
5803 struct pf_ruleset *ruleset = NULL;
5805 int off, dirndx, pqid = 0;
5807 PF_RULES_RLOCK_TRACKER;
5811 if (!V_pf_status.running)
5814 memset(&pd, 0, sizeof(pd));
5816 kif = (struct pfi_kif *)ifp->if_pf_kif;
5819 DPFPRINTF(PF_DEBUG_URGENT,
5820 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5823 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5826 if (m->m_flags & M_SKIP_FIREWALL)
5829 pd.pf_mtag = pf_find_mtag(m);
5833 if (ip_divert_ptr != NULL &&
5834 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5835 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5836 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5837 if (pd.pf_mtag == NULL &&
5838 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5842 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5843 m_tag_delete(m, ipfwtag);
5845 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5846 m->m_flags |= M_FASTFWD_OURS;
5847 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5849 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5850 /* We do IP header normalization and packet reassembly here */
5854 m = *m0; /* pf_normalize messes with m0 */
5855 h = mtod(m, struct ip *);
5857 off = h->ip_hl << 2;
5858 if (off < (int)sizeof(struct ip)) {
5860 REASON_SET(&reason, PFRES_SHORT);
5865 pd.src = (struct pf_addr *)&h->ip_src;
5866 pd.dst = (struct pf_addr *)&h->ip_dst;
5867 pd.sport = pd.dport = NULL;
5868 pd.ip_sum = &h->ip_sum;
5869 pd.proto_sum = NULL;
5872 pd.sidx = (dir == PF_IN) ? 0 : 1;
5873 pd.didx = (dir == PF_IN) ? 1 : 0;
5875 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5876 pd.tot_len = ntohs(h->ip_len);
5878 /* handle fragments that didn't get reassembled by normalization */
5879 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5880 action = pf_test_fragment(&r, dir, kif, m, h,
5890 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5891 &action, &reason, AF_INET)) {
5892 log = action != PF_PASS;
5895 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5896 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5898 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5899 if (action == PF_DROP)
5901 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5903 if (action == PF_PASS) {
5904 if (V_pfsync_update_state_ptr != NULL)
5905 V_pfsync_update_state_ptr(s);
5909 } else if (s == NULL)
5910 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5919 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5920 &action, &reason, AF_INET)) {
5921 log = action != PF_PASS;
5924 if (uh.uh_dport == 0 ||
5925 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5926 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5928 REASON_SET(&reason, PFRES_SHORT);
5931 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5932 if (action == PF_PASS) {
5933 if (V_pfsync_update_state_ptr != NULL)
5934 V_pfsync_update_state_ptr(s);
5938 } else if (s == NULL)
5939 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5944 case IPPROTO_ICMP: {
5948 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5949 &action, &reason, AF_INET)) {
5950 log = action != PF_PASS;
5953 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5955 if (action == PF_PASS) {
5956 if (V_pfsync_update_state_ptr != NULL)
5957 V_pfsync_update_state_ptr(s);
5961 } else if (s == NULL)
5962 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5968 case IPPROTO_ICMPV6: {
5970 DPFPRINTF(PF_DEBUG_MISC,
5971 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5977 action = pf_test_state_other(&s, dir, kif, m, &pd);
5978 if (action == PF_PASS) {
5979 if (V_pfsync_update_state_ptr != NULL)
5980 V_pfsync_update_state_ptr(s);
5984 } else if (s == NULL)
5985 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5992 if (action == PF_PASS && h->ip_hl > 5 &&
5993 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5995 REASON_SET(&reason, PFRES_IPOPTIONS);
5997 DPFPRINTF(PF_DEBUG_MISC,
5998 ("pf: dropping packet with ip options\n"));
6001 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6003 REASON_SET(&reason, PFRES_MEMORY);
6005 if (r->rtableid >= 0)
6006 M_SETFIB(m, r->rtableid);
6008 if (r->scrub_flags & PFSTATE_SETPRIO) {
6009 if (pd.tos & IPTOS_LOWDELAY)
6011 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6013 REASON_SET(&reason, PFRES_MEMORY);
6015 DPFPRINTF(PF_DEBUG_MISC,
6016 ("pf: failed to allocate 802.1q mtag\n"));
6021 if (action == PF_PASS && r->qid) {
6022 if (pd.pf_mtag == NULL &&
6023 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6025 REASON_SET(&reason, PFRES_MEMORY);
6028 pd.pf_mtag->qid_hash = pf_state_hash(s);
6029 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6030 pd.pf_mtag->qid = r->pqid;
6032 pd.pf_mtag->qid = r->qid;
6033 /* Add hints for ecn. */
6034 pd.pf_mtag->hdr = h;
6040 * connections redirected to loopback should not match sockets
6041 * bound specifically to loopback due to security implications,
6042 * see tcp_input() and in_pcblookup_listen().
6044 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6045 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6046 (s->nat_rule.ptr->action == PF_RDR ||
6047 s->nat_rule.ptr->action == PF_BINAT) &&
6048 IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
6049 m->m_flags |= M_SKIP_FIREWALL;
6051 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6052 !PACKET_LOOPED(&pd)) {
6053 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6054 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6055 if (ipfwtag != NULL) {
6056 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6057 ntohs(r->divert.port);
6058 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6063 m_tag_prepend(m, ipfwtag);
6064 if (m->m_flags & M_FASTFWD_OURS) {
6065 if (pd.pf_mtag == NULL &&
6066 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6068 REASON_SET(&reason, PFRES_MEMORY);
6070 DPFPRINTF(PF_DEBUG_MISC,
6071 ("pf: failed to allocate tag\n"));
6073 pd.pf_mtag->flags |=
6074 PF_FASTFWD_OURS_PRESENT;
6075 m->m_flags &= ~M_FASTFWD_OURS;
6078 ip_divert_ptr(*m0, dir == PF_IN);
6083 /* XXX: ipfw has the same behaviour! */
6085 REASON_SET(&reason, PFRES_MEMORY);
6087 DPFPRINTF(PF_DEBUG_MISC,
6088 ("pf: failed to allocate divert tag\n"));
6095 if (s != NULL && s->nat_rule.ptr != NULL &&
6096 s->nat_rule.ptr->log & PF_LOG_ALL)
6097 lr = s->nat_rule.ptr;
6100 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6104 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6105 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6107 if (action == PF_PASS || r->action == PF_DROP) {
6108 dirndx = (dir == PF_OUT);
6109 r->packets[dirndx]++;
6110 r->bytes[dirndx] += pd.tot_len;
6112 a->packets[dirndx]++;
6113 a->bytes[dirndx] += pd.tot_len;
6116 if (s->nat_rule.ptr != NULL) {
6117 s->nat_rule.ptr->packets[dirndx]++;
6118 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6120 if (s->src_node != NULL) {
6121 s->src_node->packets[dirndx]++;
6122 s->src_node->bytes[dirndx] += pd.tot_len;
6124 if (s->nat_src_node != NULL) {
6125 s->nat_src_node->packets[dirndx]++;
6126 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6128 dirndx = (dir == s->direction) ? 0 : 1;
6129 s->packets[dirndx]++;
6130 s->bytes[dirndx] += pd.tot_len;
6133 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6134 if (nr != NULL && r == &V_pf_default_rule)
6136 if (tr->src.addr.type == PF_ADDR_TABLE)
6137 pfr_update_stats(tr->src.addr.p.tbl,
6138 (s == NULL) ? pd.src :
6139 &s->key[(s->direction == PF_IN)]->
6140 addr[(s->direction == PF_OUT)],
6141 pd.af, pd.tot_len, dir == PF_OUT,
6142 r->action == PF_PASS, tr->src.neg);
6143 if (tr->dst.addr.type == PF_ADDR_TABLE)
6144 pfr_update_stats(tr->dst.addr.p.tbl,
6145 (s == NULL) ? pd.dst :
6146 &s->key[(s->direction == PF_IN)]->
6147 addr[(s->direction == PF_IN)],
6148 pd.af, pd.tot_len, dir == PF_OUT,
6149 r->action == PF_PASS, tr->dst.neg);
6153 case PF_SYNPROXY_DROP:
6164 /* pf_route() returns unlocked. */
6166 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6180 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6182 struct pfi_kif *kif;
6183 u_short action, reason = 0, log = 0;
6184 struct mbuf *m = *m0, *n = NULL;
6186 struct ip6_hdr *h = NULL;
6187 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6188 struct pf_state *s = NULL;
6189 struct pf_ruleset *ruleset = NULL;
6191 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6193 PF_RULES_RLOCK_TRACKER;
6196 if (!V_pf_status.running)
6199 memset(&pd, 0, sizeof(pd));
6200 pd.pf_mtag = pf_find_mtag(m);
6202 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6205 kif = (struct pfi_kif *)ifp->if_pf_kif;
6207 DPFPRINTF(PF_DEBUG_URGENT,
6208 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6211 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6214 if (m->m_flags & M_SKIP_FIREWALL)
6219 /* We do IP header normalization and packet reassembly here */
6220 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6224 m = *m0; /* pf_normalize messes with m0 */
6225 h = mtod(m, struct ip6_hdr *);
6228 * we do not support jumbogram. if we keep going, zero ip6_plen
6229 * will do something bad, so drop the packet for now.
6231 if (htons(h->ip6_plen) == 0) {
6233 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6237 pd.src = (struct pf_addr *)&h->ip6_src;
6238 pd.dst = (struct pf_addr *)&h->ip6_dst;
6239 pd.sport = pd.dport = NULL;
6241 pd.proto_sum = NULL;
6243 pd.sidx = (dir == PF_IN) ? 0 : 1;
6244 pd.didx = (dir == PF_IN) ? 1 : 0;
6247 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6249 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6250 pd.proto = h->ip6_nxt;
6253 case IPPROTO_FRAGMENT:
6254 action = pf_test_fragment(&r, dir, kif, m, h,
6256 if (action == PF_DROP)
6257 REASON_SET(&reason, PFRES_FRAG);
6259 case IPPROTO_ROUTING: {
6260 struct ip6_rthdr rthdr;
6263 DPFPRINTF(PF_DEBUG_MISC,
6264 ("pf: IPv6 more than one rthdr\n"));
6266 REASON_SET(&reason, PFRES_IPOPTIONS);
6270 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6272 DPFPRINTF(PF_DEBUG_MISC,
6273 ("pf: IPv6 short rthdr\n"));
6275 REASON_SET(&reason, PFRES_SHORT);
6279 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6280 DPFPRINTF(PF_DEBUG_MISC,
6281 ("pf: IPv6 rthdr0\n"));
6283 REASON_SET(&reason, PFRES_IPOPTIONS);
6290 case IPPROTO_HOPOPTS:
6291 case IPPROTO_DSTOPTS: {
6292 /* get next header and header length */
6293 struct ip6_ext opt6;
6295 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6296 NULL, &reason, pd.af)) {
6297 DPFPRINTF(PF_DEBUG_MISC,
6298 ("pf: IPv6 short opt\n"));
6303 if (pd.proto == IPPROTO_AH)
6304 off += (opt6.ip6e_len + 2) * 4;
6306 off += (opt6.ip6e_len + 1) * 8;
6307 pd.proto = opt6.ip6e_nxt;
6308 /* goto the next header */
6315 } while (!terminal);
6317 /* if there's no routing header, use unmodified mbuf for checksumming */
6326 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6327 &action, &reason, AF_INET6)) {
6328 log = action != PF_PASS;
6331 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6332 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6333 if (action == PF_DROP)
6335 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6337 if (action == PF_PASS) {
6338 if (V_pfsync_update_state_ptr != NULL)
6339 V_pfsync_update_state_ptr(s);
6343 } else if (s == NULL)
6344 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6353 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6354 &action, &reason, AF_INET6)) {
6355 log = action != PF_PASS;
6358 if (uh.uh_dport == 0 ||
6359 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6360 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6362 REASON_SET(&reason, PFRES_SHORT);
6365 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6366 if (action == PF_PASS) {
6367 if (V_pfsync_update_state_ptr != NULL)
6368 V_pfsync_update_state_ptr(s);
6372 } else if (s == NULL)
6373 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6378 case IPPROTO_ICMP: {
6380 DPFPRINTF(PF_DEBUG_MISC,
6381 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6385 case IPPROTO_ICMPV6: {
6386 struct icmp6_hdr ih;
6389 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6390 &action, &reason, AF_INET6)) {
6391 log = action != PF_PASS;
6394 action = pf_test_state_icmp(&s, dir, kif,
6395 m, off, h, &pd, &reason);
6396 if (action == PF_PASS) {
6397 if (V_pfsync_update_state_ptr != NULL)
6398 V_pfsync_update_state_ptr(s);
6402 } else if (s == NULL)
6403 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6409 action = pf_test_state_other(&s, dir, kif, m, &pd);
6410 if (action == PF_PASS) {
6411 if (V_pfsync_update_state_ptr != NULL)
6412 V_pfsync_update_state_ptr(s);
6416 } else if (s == NULL)
6417 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6429 /* handle dangerous IPv6 extension headers. */
6430 if (action == PF_PASS && rh_cnt &&
6431 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6433 REASON_SET(&reason, PFRES_IPOPTIONS);
6435 DPFPRINTF(PF_DEBUG_MISC,
6436 ("pf: dropping packet with dangerous v6 headers\n"));
6439 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6441 REASON_SET(&reason, PFRES_MEMORY);
6443 if (r->rtableid >= 0)
6444 M_SETFIB(m, r->rtableid);
6446 if (r->scrub_flags & PFSTATE_SETPRIO) {
6447 if (pd.tos & IPTOS_LOWDELAY)
6449 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6451 REASON_SET(&reason, PFRES_MEMORY);
6453 DPFPRINTF(PF_DEBUG_MISC,
6454 ("pf: failed to allocate 802.1q mtag\n"));
6459 if (action == PF_PASS && r->qid) {
6460 if (pd.pf_mtag == NULL &&
6461 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6463 REASON_SET(&reason, PFRES_MEMORY);
6466 pd.pf_mtag->qid_hash = pf_state_hash(s);
6467 if (pd.tos & IPTOS_LOWDELAY)
6468 pd.pf_mtag->qid = r->pqid;
6470 pd.pf_mtag->qid = r->qid;
6471 /* Add hints for ecn. */
6472 pd.pf_mtag->hdr = h;
6477 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6478 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6479 (s->nat_rule.ptr->action == PF_RDR ||
6480 s->nat_rule.ptr->action == PF_BINAT) &&
6481 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6482 m->m_flags |= M_SKIP_FIREWALL;
6484 /* XXX: Anybody working on it?! */
6486 printf("pf: divert(9) is not supported for IPv6\n");
6491 if (s != NULL && s->nat_rule.ptr != NULL &&
6492 s->nat_rule.ptr->log & PF_LOG_ALL)
6493 lr = s->nat_rule.ptr;
6496 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6500 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6501 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6503 if (action == PF_PASS || r->action == PF_DROP) {
6504 dirndx = (dir == PF_OUT);
6505 r->packets[dirndx]++;
6506 r->bytes[dirndx] += pd.tot_len;
6508 a->packets[dirndx]++;
6509 a->bytes[dirndx] += pd.tot_len;
6512 if (s->nat_rule.ptr != NULL) {
6513 s->nat_rule.ptr->packets[dirndx]++;
6514 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6516 if (s->src_node != NULL) {
6517 s->src_node->packets[dirndx]++;
6518 s->src_node->bytes[dirndx] += pd.tot_len;
6520 if (s->nat_src_node != NULL) {
6521 s->nat_src_node->packets[dirndx]++;
6522 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6524 dirndx = (dir == s->direction) ? 0 : 1;
6525 s->packets[dirndx]++;
6526 s->bytes[dirndx] += pd.tot_len;
6529 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6530 if (nr != NULL && r == &V_pf_default_rule)
6532 if (tr->src.addr.type == PF_ADDR_TABLE)
6533 pfr_update_stats(tr->src.addr.p.tbl,
6534 (s == NULL) ? pd.src :
6535 &s->key[(s->direction == PF_IN)]->addr[0],
6536 pd.af, pd.tot_len, dir == PF_OUT,
6537 r->action == PF_PASS, tr->src.neg);
6538 if (tr->dst.addr.type == PF_ADDR_TABLE)
6539 pfr_update_stats(tr->dst.addr.p.tbl,
6540 (s == NULL) ? pd.dst :
6541 &s->key[(s->direction == PF_IN)]->addr[1],
6542 pd.af, pd.tot_len, dir == PF_OUT,
6543 r->action == PF_PASS, tr->dst.neg);
6547 case PF_SYNPROXY_DROP:
6558 /* pf_route6() returns unlocked. */
6560 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6569 /* If reassembled packet passed, create new fragments. */
6570 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6571 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6572 action = pf_refragment6(ifp, m0, mtag);