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>
53 #include <sys/interrupt.h>
54 #include <sys/kernel.h>
55 #include <sys/kthread.h>
56 #include <sys/limits.h>
59 #include <sys/random.h>
60 #include <sys/refcount.h>
61 #include <sys/socket.h>
62 #include <sys/sysctl.h>
63 #include <sys/taskqueue.h>
64 #include <sys/ucred.h>
67 #include <net/if_var.h>
68 #include <net/if_types.h>
69 #include <net/if_vlan_var.h>
70 #include <net/route.h>
71 #include <net/radix_mpath.h>
75 #include <net/pfvar.h>
76 #include <net/if_pflog.h>
77 #include <net/if_pfsync.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/in_var.h>
81 #include <netinet/in_fib.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_fw.h>
84 #include <netinet/ip_icmp.h>
85 #include <netinet/icmp_var.h>
86 #include <netinet/ip_var.h>
87 #include <netinet/tcp.h>
88 #include <netinet/tcp_fsm.h>
89 #include <netinet/tcp_seq.h>
90 #include <netinet/tcp_timer.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet/udp.h>
93 #include <netinet/udp_var.h>
95 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
98 #include <netinet/ip6.h>
99 #include <netinet/icmp6.h>
100 #include <netinet6/nd6.h>
101 #include <netinet6/ip6_var.h>
102 #include <netinet6/in6_pcb.h>
103 #include <netinet6/in6_fib.h>
104 #include <netinet6/scope6_var.h>
107 #if defined(SCTP) || defined(SCTP_SUPPORT)
108 #include <netinet/sctp_crc32.h>
111 #include <machine/in_cksum.h>
112 #include <security/mac/mac_framework.h>
114 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
121 VNET_DEFINE(struct pf_altqqueue, pf_altqs[4]);
122 VNET_DEFINE(struct pf_palist, pf_pabuf);
123 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
124 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_active);
125 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
126 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_inactive);
127 VNET_DEFINE(struct pf_kstatus, pf_status);
129 VNET_DEFINE(u_int32_t, ticket_altqs_active);
130 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
131 VNET_DEFINE(int, altqs_inactive_open);
132 VNET_DEFINE(u_int32_t, ticket_pabuf);
134 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
135 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
136 VNET_DEFINE(u_char, pf_tcp_secret[16]);
137 #define V_pf_tcp_secret VNET(pf_tcp_secret)
138 VNET_DEFINE(int, pf_tcp_secret_init);
139 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
140 VNET_DEFINE(int, pf_tcp_iss_off);
141 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
142 VNET_DECLARE(int, pf_vnet_active);
143 #define V_pf_vnet_active VNET(pf_vnet_active)
145 VNET_DEFINE_STATIC(uint32_t, pf_purge_idx);
146 #define V_pf_purge_idx VNET(pf_purge_idx)
149 * Queue for pf_intr() sends.
151 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
152 struct pf_send_entry {
153 STAILQ_ENTRY(pf_send_entry) pfse_next;
168 STAILQ_HEAD(pf_send_head, pf_send_entry);
169 VNET_DEFINE_STATIC(struct pf_send_head, pf_sendqueue);
170 #define V_pf_sendqueue VNET(pf_sendqueue)
172 static struct mtx pf_sendqueue_mtx;
173 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
174 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
175 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
178 * Queue for pf_overload_task() tasks.
180 struct pf_overload_entry {
181 SLIST_ENTRY(pf_overload_entry) next;
185 struct pf_rule *rule;
188 SLIST_HEAD(pf_overload_head, pf_overload_entry);
189 VNET_DEFINE_STATIC(struct pf_overload_head, pf_overloadqueue);
190 #define V_pf_overloadqueue VNET(pf_overloadqueue)
191 VNET_DEFINE_STATIC(struct task, pf_overloadtask);
192 #define V_pf_overloadtask VNET(pf_overloadtask)
194 static struct mtx pf_overloadqueue_mtx;
195 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
196 "pf overload/flush queue", MTX_DEF);
197 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
198 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
200 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
201 struct mtx pf_unlnkdrules_mtx;
202 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
205 VNET_DEFINE_STATIC(uma_zone_t, pf_sources_z);
206 #define V_pf_sources_z VNET(pf_sources_z)
207 uma_zone_t pf_mtag_z;
208 VNET_DEFINE(uma_zone_t, pf_state_z);
209 VNET_DEFINE(uma_zone_t, pf_state_key_z);
211 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
212 #define PFID_CPUBITS 8
213 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
214 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
215 #define PFID_MAXID (~PFID_CPUMASK)
216 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
218 static void pf_src_tree_remove_state(struct pf_state *);
219 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
221 static void pf_add_threshold(struct pf_threshold *);
222 static int pf_check_threshold(struct pf_threshold *);
224 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
225 u_int16_t *, u_int16_t *, struct pf_addr *,
226 u_int16_t, u_int8_t, sa_family_t);
227 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
228 struct tcphdr *, struct pf_state_peer *);
229 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
230 struct pf_addr *, struct pf_addr *, u_int16_t,
231 u_int16_t *, u_int16_t *, u_int16_t *,
232 u_int16_t *, u_int8_t, sa_family_t);
233 static void pf_send_tcp(struct mbuf *,
234 const struct pf_rule *, sa_family_t,
235 const struct pf_addr *, const struct pf_addr *,
236 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
237 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
238 u_int16_t, struct ifnet *);
239 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
240 sa_family_t, struct pf_rule *);
241 static void pf_detach_state(struct pf_state *);
242 static int pf_state_key_attach(struct pf_state_key *,
243 struct pf_state_key *, struct pf_state *);
244 static void pf_state_key_detach(struct pf_state *, int);
245 static int pf_state_key_ctor(void *, int, void *, int);
246 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
247 static int pf_test_rule(struct pf_rule **, struct pf_state **,
248 int, struct pfi_kif *, struct mbuf *, int,
249 struct pf_pdesc *, struct pf_rule **,
250 struct pf_ruleset **, struct inpcb *);
251 static int pf_create_state(struct pf_rule *, struct pf_rule *,
252 struct pf_rule *, struct pf_pdesc *,
253 struct pf_src_node *, struct pf_state_key *,
254 struct pf_state_key *, struct mbuf *, int,
255 u_int16_t, u_int16_t, int *, struct pfi_kif *,
256 struct pf_state **, int, u_int16_t, u_int16_t,
258 static int pf_test_fragment(struct pf_rule **, int,
259 struct pfi_kif *, struct mbuf *, void *,
260 struct pf_pdesc *, struct pf_rule **,
261 struct pf_ruleset **);
262 static int pf_tcp_track_full(struct pf_state_peer *,
263 struct pf_state_peer *, struct pf_state **,
264 struct pfi_kif *, struct mbuf *, int,
265 struct pf_pdesc *, u_short *, int *);
266 static int pf_tcp_track_sloppy(struct pf_state_peer *,
267 struct pf_state_peer *, struct pf_state **,
268 struct pf_pdesc *, u_short *);
269 static int pf_test_state_tcp(struct pf_state **, int,
270 struct pfi_kif *, struct mbuf *, int,
271 void *, struct pf_pdesc *, u_short *);
272 static int pf_test_state_udp(struct pf_state **, int,
273 struct pfi_kif *, struct mbuf *, int,
274 void *, struct pf_pdesc *);
275 static int pf_test_state_icmp(struct pf_state **, int,
276 struct pfi_kif *, struct mbuf *, int,
277 void *, struct pf_pdesc *, u_short *);
278 static int pf_test_state_other(struct pf_state **, int,
279 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
280 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
282 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
284 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
286 static int pf_check_proto_cksum(struct mbuf *, int, int,
287 u_int8_t, sa_family_t);
288 static void pf_print_state_parts(struct pf_state *,
289 struct pf_state_key *, struct pf_state_key *);
290 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
291 struct pf_addr_wrap *);
292 static struct pf_state *pf_find_state(struct pfi_kif *,
293 struct pf_state_key_cmp *, u_int);
294 static int pf_src_connlimit(struct pf_state **);
295 static void pf_overload_task(void *v, int pending);
296 static int pf_insert_src_node(struct pf_src_node **,
297 struct pf_rule *, struct pf_addr *, sa_family_t);
298 static u_int pf_purge_expired_states(u_int, int);
299 static void pf_purge_unlinked_rules(void);
300 static int pf_mtag_uminit(void *, int, int);
301 static void pf_mtag_free(struct m_tag *);
303 static void pf_route(struct mbuf **, struct pf_rule *, int,
304 struct ifnet *, struct pf_state *,
305 struct pf_pdesc *, struct inpcb *);
308 static void pf_change_a6(struct pf_addr *, u_int16_t *,
309 struct pf_addr *, u_int8_t);
310 static void pf_route6(struct mbuf **, struct pf_rule *, int,
311 struct ifnet *, struct pf_state *,
312 struct pf_pdesc *, struct inpcb *);
315 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
317 extern int pf_end_threads;
318 extern struct proc *pf_purge_proc;
320 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
322 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
323 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
325 #define STATE_LOOKUP(i, k, d, s, pd) \
327 (s) = pf_find_state((i), (k), (d)); \
330 if (PACKET_LOOPED(pd)) \
332 if ((d) == PF_OUT && \
333 (((s)->rule.ptr->rt == PF_ROUTETO && \
334 (s)->rule.ptr->direction == PF_OUT) || \
335 ((s)->rule.ptr->rt == PF_REPLYTO && \
336 (s)->rule.ptr->direction == PF_IN)) && \
337 (s)->rt_kif != NULL && \
338 (s)->rt_kif != (i)) \
342 #define BOUND_IFACE(r, k) \
343 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
345 #define STATE_INC_COUNTERS(s) \
347 counter_u64_add(s->rule.ptr->states_cur, 1); \
348 counter_u64_add(s->rule.ptr->states_tot, 1); \
349 if (s->anchor.ptr != NULL) { \
350 counter_u64_add(s->anchor.ptr->states_cur, 1); \
351 counter_u64_add(s->anchor.ptr->states_tot, 1); \
353 if (s->nat_rule.ptr != NULL) { \
354 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
355 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
359 #define STATE_DEC_COUNTERS(s) \
361 if (s->nat_rule.ptr != NULL) \
362 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
363 if (s->anchor.ptr != NULL) \
364 counter_u64_add(s->anchor.ptr->states_cur, -1); \
365 counter_u64_add(s->rule.ptr->states_cur, -1); \
368 MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
369 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
370 VNET_DEFINE(struct pf_idhash *, pf_idhash);
371 VNET_DEFINE(struct pf_srchash *, pf_srchash);
373 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
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_RWTUN,
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 pf_send_head queue;
1433 struct pf_send_entry *pfse, *next;
1435 CURVNET_SET((struct vnet *)v);
1438 queue = V_pf_sendqueue;
1439 STAILQ_INIT(&V_pf_sendqueue);
1442 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1443 switch (pfse->pfse_type) {
1446 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1449 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1450 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1455 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1459 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1460 pfse->icmpopts.code, pfse->icmpopts.mtu);
1464 panic("%s: unknown type", __func__);
1466 free(pfse, M_PFTEMP);
1472 pf_purge_thread(void *unused __unused)
1474 VNET_ITERATOR_DECL(vnet_iter);
1476 sx_xlock(&pf_end_lock);
1477 while (pf_end_threads == 0) {
1478 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1481 VNET_FOREACH(vnet_iter) {
1482 CURVNET_SET(vnet_iter);
1485 /* Wait until V_pf_default_rule is initialized. */
1486 if (V_pf_vnet_active == 0) {
1492 * Process 1/interval fraction of the state
1496 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1497 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1500 * Purge other expired types every
1501 * PFTM_INTERVAL seconds.
1503 if (V_pf_purge_idx == 0) {
1505 * Order is important:
1506 * - states and src nodes reference rules
1507 * - states and rules reference kifs
1509 pf_purge_expired_fragments();
1510 pf_purge_expired_src_nodes();
1511 pf_purge_unlinked_rules();
1516 VNET_LIST_RUNLOCK();
1520 sx_xunlock(&pf_end_lock);
1525 pf_unload_vnet_purge(void)
1529 * To cleanse up all kifs and rules we need
1530 * two runs: first one clears reference flags,
1531 * then pf_purge_expired_states() doesn't
1532 * raise them, and then second run frees.
1534 pf_purge_unlinked_rules();
1538 * Now purge everything.
1540 pf_purge_expired_states(0, pf_hashmask);
1541 pf_purge_fragments(UINT_MAX);
1542 pf_purge_expired_src_nodes();
1545 * Now all kifs & rules should be unreferenced,
1546 * thus should be successfully freed.
1548 pf_purge_unlinked_rules();
1554 pf_state_expires(const struct pf_state *state)
1561 /* handle all PFTM_* > PFTM_MAX here */
1562 if (state->timeout == PFTM_PURGE)
1563 return (time_uptime);
1564 KASSERT(state->timeout != PFTM_UNLINKED,
1565 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1566 KASSERT((state->timeout < PFTM_MAX),
1567 ("pf_state_expires: timeout > PFTM_MAX"));
1568 timeout = state->rule.ptr->timeout[state->timeout];
1570 timeout = V_pf_default_rule.timeout[state->timeout];
1571 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1572 if (start && state->rule.ptr != &V_pf_default_rule) {
1573 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1574 states = counter_u64_fetch(state->rule.ptr->states_cur);
1576 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1577 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1578 states = V_pf_status.states;
1580 if (end && states > start && start < end) {
1582 timeout = (u_int64_t)timeout * (end - states) /
1584 return (state->expire + timeout);
1587 return (time_uptime);
1589 return (state->expire + timeout);
1593 pf_purge_expired_src_nodes()
1595 struct pf_src_node_list freelist;
1596 struct pf_srchash *sh;
1597 struct pf_src_node *cur, *next;
1600 LIST_INIT(&freelist);
1601 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1602 PF_HASHROW_LOCK(sh);
1603 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1604 if (cur->states == 0 && cur->expire <= time_uptime) {
1605 pf_unlink_src_node(cur);
1606 LIST_INSERT_HEAD(&freelist, cur, entry);
1607 } else if (cur->rule.ptr != NULL)
1608 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1609 PF_HASHROW_UNLOCK(sh);
1612 pf_free_src_nodes(&freelist);
1614 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1618 pf_src_tree_remove_state(struct pf_state *s)
1620 struct pf_src_node *sn;
1621 struct pf_srchash *sh;
1624 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1625 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1626 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1628 if (s->src_node != NULL) {
1630 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1631 PF_HASHROW_LOCK(sh);
1634 if (--sn->states == 0)
1635 sn->expire = time_uptime + timeout;
1636 PF_HASHROW_UNLOCK(sh);
1638 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1639 sn = s->nat_src_node;
1640 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1641 PF_HASHROW_LOCK(sh);
1642 if (--sn->states == 0)
1643 sn->expire = time_uptime + timeout;
1644 PF_HASHROW_UNLOCK(sh);
1646 s->src_node = s->nat_src_node = NULL;
1650 * Unlink and potentilly free a state. Function may be
1651 * called with ID hash row locked, but always returns
1652 * unlocked, since it needs to go through key hash locking.
1655 pf_unlink_state(struct pf_state *s, u_int flags)
1657 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1659 if ((flags & PF_ENTER_LOCKED) == 0)
1660 PF_HASHROW_LOCK(ih);
1662 PF_HASHROW_ASSERT(ih);
1664 if (s->timeout == PFTM_UNLINKED) {
1666 * State is being processed
1667 * by pf_unlink_state() in
1670 PF_HASHROW_UNLOCK(ih);
1671 return (0); /* XXXGL: undefined actually */
1674 if (s->src.state == PF_TCPS_PROXY_DST) {
1675 /* XXX wire key the right one? */
1676 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1677 &s->key[PF_SK_WIRE]->addr[1],
1678 &s->key[PF_SK_WIRE]->addr[0],
1679 s->key[PF_SK_WIRE]->port[1],
1680 s->key[PF_SK_WIRE]->port[0],
1681 s->src.seqhi, s->src.seqlo + 1,
1682 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1685 LIST_REMOVE(s, entry);
1686 pf_src_tree_remove_state(s);
1688 if (V_pfsync_delete_state_ptr != NULL)
1689 V_pfsync_delete_state_ptr(s);
1691 STATE_DEC_COUNTERS(s);
1693 s->timeout = PFTM_UNLINKED;
1695 PF_HASHROW_UNLOCK(ih);
1698 /* pf_state_insert() initialises refs to 2, so we can never release the
1699 * last reference here, only in pf_release_state(). */
1700 (void)refcount_release(&s->refs);
1702 return (pf_release_state(s));
1706 pf_free_state(struct pf_state *cur)
1709 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1710 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1713 pf_normalize_tcp_cleanup(cur);
1714 uma_zfree(V_pf_state_z, cur);
1715 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1719 * Called only from pf_purge_thread(), thus serialized.
1722 pf_purge_expired_states(u_int i, int maxcheck)
1724 struct pf_idhash *ih;
1727 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1730 * Go through hash and unlink states that expire now.
1732 while (maxcheck > 0) {
1734 ih = &V_pf_idhash[i];
1736 /* only take the lock if we expect to do work */
1737 if (!LIST_EMPTY(&ih->states)) {
1739 PF_HASHROW_LOCK(ih);
1740 LIST_FOREACH(s, &ih->states, entry) {
1741 if (pf_state_expires(s) <= time_uptime) {
1742 V_pf_status.states -=
1743 pf_unlink_state(s, PF_ENTER_LOCKED);
1746 s->rule.ptr->rule_flag |= PFRULE_REFS;
1747 if (s->nat_rule.ptr != NULL)
1748 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1749 if (s->anchor.ptr != NULL)
1750 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1751 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1753 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1755 PF_HASHROW_UNLOCK(ih);
1758 /* Return when we hit end of hash. */
1759 if (++i > pf_hashmask) {
1760 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1767 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1773 pf_purge_unlinked_rules()
1775 struct pf_rulequeue tmpq;
1776 struct pf_rule *r, *r1;
1779 * If we have overloading task pending, then we'd
1780 * better skip purging this time. There is a tiny
1781 * probability that overloading task references
1782 * an already unlinked rule.
1784 PF_OVERLOADQ_LOCK();
1785 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1786 PF_OVERLOADQ_UNLOCK();
1789 PF_OVERLOADQ_UNLOCK();
1792 * Do naive mark-and-sweep garbage collecting of old rules.
1793 * Reference flag is raised by pf_purge_expired_states()
1794 * and pf_purge_expired_src_nodes().
1796 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1797 * use a temporary queue.
1800 PF_UNLNKDRULES_LOCK();
1801 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1802 if (!(r->rule_flag & PFRULE_REFS)) {
1803 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1804 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1806 r->rule_flag &= ~PFRULE_REFS;
1808 PF_UNLNKDRULES_UNLOCK();
1810 if (!TAILQ_EMPTY(&tmpq)) {
1812 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1813 TAILQ_REMOVE(&tmpq, r, entries);
1821 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1826 u_int32_t a = ntohl(addr->addr32[0]);
1827 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1839 u_int8_t i, curstart, curend, maxstart, maxend;
1840 curstart = curend = maxstart = maxend = 255;
1841 for (i = 0; i < 8; i++) {
1842 if (!addr->addr16[i]) {
1843 if (curstart == 255)
1847 if ((curend - curstart) >
1848 (maxend - maxstart)) {
1849 maxstart = curstart;
1852 curstart = curend = 255;
1855 if ((curend - curstart) >
1856 (maxend - maxstart)) {
1857 maxstart = curstart;
1860 for (i = 0; i < 8; i++) {
1861 if (i >= maxstart && i <= maxend) {
1867 b = ntohs(addr->addr16[i]);
1884 pf_print_state(struct pf_state *s)
1886 pf_print_state_parts(s, NULL, NULL);
1890 pf_print_state_parts(struct pf_state *s,
1891 struct pf_state_key *skwp, struct pf_state_key *sksp)
1893 struct pf_state_key *skw, *sks;
1894 u_int8_t proto, dir;
1896 /* Do our best to fill these, but they're skipped if NULL */
1897 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1898 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1899 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1900 dir = s ? s->direction : 0;
1918 case IPPROTO_ICMPV6:
1922 printf("%u", proto);
1935 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1937 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1942 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1944 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1949 if (proto == IPPROTO_TCP) {
1950 printf(" [lo=%u high=%u win=%u modulator=%u",
1951 s->src.seqlo, s->src.seqhi,
1952 s->src.max_win, s->src.seqdiff);
1953 if (s->src.wscale && s->dst.wscale)
1954 printf(" wscale=%u",
1955 s->src.wscale & PF_WSCALE_MASK);
1957 printf(" [lo=%u high=%u win=%u modulator=%u",
1958 s->dst.seqlo, s->dst.seqhi,
1959 s->dst.max_win, s->dst.seqdiff);
1960 if (s->src.wscale && s->dst.wscale)
1961 printf(" wscale=%u",
1962 s->dst.wscale & PF_WSCALE_MASK);
1965 printf(" %u:%u", s->src.state, s->dst.state);
1970 pf_print_flags(u_int8_t f)
1992 #define PF_SET_SKIP_STEPS(i) \
1994 while (head[i] != cur) { \
1995 head[i]->skip[i].ptr = cur; \
1996 head[i] = TAILQ_NEXT(head[i], entries); \
2001 pf_calc_skip_steps(struct pf_rulequeue *rules)
2003 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
2006 cur = TAILQ_FIRST(rules);
2008 for (i = 0; i < PF_SKIP_COUNT; ++i)
2010 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);
2305 * Need to modulate the sequence numbers in the TCP SACK option
2306 * (credits to Krzysztof Pfaff for report and patch)
2309 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2310 struct tcphdr *th, struct pf_state_peer *dst)
2312 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2313 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2314 int copyback = 0, i, olen;
2315 struct sackblk sack;
2317 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2318 if (hlen < TCPOLEN_SACKLEN ||
2319 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2322 while (hlen >= TCPOLEN_SACKLEN) {
2325 case TCPOPT_EOL: /* FALLTHROUGH */
2333 if (olen >= TCPOLEN_SACKLEN) {
2334 for (i = 2; i + TCPOLEN_SACK <= olen;
2335 i += TCPOLEN_SACK) {
2336 memcpy(&sack, &opt[i], sizeof(sack));
2337 pf_change_proto_a(m, &sack.start, &th->th_sum,
2338 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2339 pf_change_proto_a(m, &sack.end, &th->th_sum,
2340 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2341 memcpy(&opt[i], &sack, sizeof(sack));
2355 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2360 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2361 const struct pf_addr *saddr, const struct pf_addr *daddr,
2362 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2363 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2364 u_int16_t rtag, struct ifnet *ifp)
2366 struct pf_send_entry *pfse;
2370 struct ip *h = NULL;
2373 struct ip6_hdr *h6 = NULL;
2377 struct pf_mtag *pf_mtag;
2382 /* maximum segment size tcp option */
2383 tlen = sizeof(struct tcphdr);
2390 len = sizeof(struct ip) + tlen;
2395 len = sizeof(struct ip6_hdr) + tlen;
2399 panic("%s: unsupported af %d", __func__, af);
2402 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2403 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2406 m = m_gethdr(M_NOWAIT, MT_DATA);
2408 free(pfse, M_PFTEMP);
2412 mac_netinet_firewall_send(m);
2414 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2415 free(pfse, M_PFTEMP);
2420 m->m_flags |= M_SKIP_FIREWALL;
2421 pf_mtag->tag = rtag;
2423 if (r != NULL && r->rtableid >= 0)
2424 M_SETFIB(m, r->rtableid);
2427 if (r != NULL && r->qid) {
2428 pf_mtag->qid = r->qid;
2430 /* add hints for ecn */
2431 pf_mtag->hdr = mtod(m, struct ip *);
2434 m->m_data += max_linkhdr;
2435 m->m_pkthdr.len = m->m_len = len;
2436 m->m_pkthdr.rcvif = NULL;
2437 bzero(m->m_data, len);
2441 h = mtod(m, struct ip *);
2443 /* IP header fields included in the TCP checksum */
2444 h->ip_p = IPPROTO_TCP;
2445 h->ip_len = htons(tlen);
2446 h->ip_src.s_addr = saddr->v4.s_addr;
2447 h->ip_dst.s_addr = daddr->v4.s_addr;
2449 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2454 h6 = mtod(m, struct ip6_hdr *);
2456 /* IP header fields included in the TCP checksum */
2457 h6->ip6_nxt = IPPROTO_TCP;
2458 h6->ip6_plen = htons(tlen);
2459 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2460 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2462 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2468 th->th_sport = sport;
2469 th->th_dport = dport;
2470 th->th_seq = htonl(seq);
2471 th->th_ack = htonl(ack);
2472 th->th_off = tlen >> 2;
2473 th->th_flags = flags;
2474 th->th_win = htons(win);
2477 opt = (char *)(th + 1);
2478 opt[0] = TCPOPT_MAXSEG;
2481 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2488 th->th_sum = in_cksum(m, len);
2490 /* Finish the IP header */
2492 h->ip_hl = sizeof(*h) >> 2;
2493 h->ip_tos = IPTOS_LOWDELAY;
2494 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2495 h->ip_len = htons(len);
2496 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2499 pfse->pfse_type = PFSE_IP;
2505 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2506 sizeof(struct ip6_hdr), tlen);
2508 h6->ip6_vfc |= IPV6_VERSION;
2509 h6->ip6_hlim = IPV6_DEFHLIM;
2511 pfse->pfse_type = PFSE_IP6;
2520 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2521 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2522 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2525 struct pf_addr * const saddr = pd->src;
2526 struct pf_addr * const daddr = pd->dst;
2527 sa_family_t af = pd->af;
2529 /* undo NAT changes, if they have taken place */
2531 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2532 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2534 *pd->sport = sk->port[pd->sidx];
2536 *pd->dport = sk->port[pd->didx];
2538 *pd->proto_sum = bproto_sum;
2540 *pd->ip_sum = bip_sum;
2541 m_copyback(m, off, hdrlen, pd->hdr.any);
2543 if (pd->proto == IPPROTO_TCP &&
2544 ((r->rule_flag & PFRULE_RETURNRST) ||
2545 (r->rule_flag & PFRULE_RETURN)) &&
2546 !(th->th_flags & TH_RST)) {
2547 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2559 h4 = mtod(m, struct ip *);
2560 len = ntohs(h4->ip_len) - off;
2565 h6 = mtod(m, struct ip6_hdr *);
2566 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2571 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2572 REASON_SET(reason, PFRES_PROTCKSUM);
2574 if (th->th_flags & TH_SYN)
2576 if (th->th_flags & TH_FIN)
2578 pf_send_tcp(m, r, af, pd->dst,
2579 pd->src, th->th_dport, th->th_sport,
2580 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2581 r->return_ttl, 1, 0, kif->pfik_ifp);
2583 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2585 pf_send_icmp(m, r->return_icmp >> 8,
2586 r->return_icmp & 255, af, r);
2587 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2589 pf_send_icmp(m, r->return_icmp6 >> 8,
2590 r->return_icmp6 & 255, af, r);
2595 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2599 KASSERT(prio <= PF_PRIO_MAX,
2600 ("%s with invalid pcp", __func__));
2602 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2604 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2605 sizeof(uint8_t), M_NOWAIT);
2608 m_tag_prepend(m, mtag);
2611 *(uint8_t *)(mtag + 1) = prio;
2616 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2621 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2625 if (prio == PF_PRIO_ZERO)
2628 mpcp = *(uint8_t *)(mtag + 1);
2630 return (mpcp == prio);
2634 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2637 struct pf_send_entry *pfse;
2639 struct pf_mtag *pf_mtag;
2641 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2642 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2646 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2647 free(pfse, M_PFTEMP);
2651 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2652 free(pfse, M_PFTEMP);
2656 m0->m_flags |= M_SKIP_FIREWALL;
2658 if (r->rtableid >= 0)
2659 M_SETFIB(m0, r->rtableid);
2663 pf_mtag->qid = r->qid;
2664 /* add hints for ecn */
2665 pf_mtag->hdr = mtod(m0, struct ip *);
2672 pfse->pfse_type = PFSE_ICMP;
2677 pfse->pfse_type = PFSE_ICMP6;
2682 pfse->icmpopts.type = type;
2683 pfse->icmpopts.code = code;
2688 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2689 * If n is 0, they match if they are equal. If n is != 0, they match if they
2693 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2694 struct pf_addr *b, sa_family_t af)
2701 if ((a->addr32[0] & m->addr32[0]) ==
2702 (b->addr32[0] & m->addr32[0]))
2708 if (((a->addr32[0] & m->addr32[0]) ==
2709 (b->addr32[0] & m->addr32[0])) &&
2710 ((a->addr32[1] & m->addr32[1]) ==
2711 (b->addr32[1] & m->addr32[1])) &&
2712 ((a->addr32[2] & m->addr32[2]) ==
2713 (b->addr32[2] & m->addr32[2])) &&
2714 ((a->addr32[3] & m->addr32[3]) ==
2715 (b->addr32[3] & m->addr32[3])))
2734 * Return 1 if b <= a <= e, otherwise return 0.
2737 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2738 struct pf_addr *a, sa_family_t af)
2743 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2744 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2753 for (i = 0; i < 4; ++i)
2754 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2756 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2759 for (i = 0; i < 4; ++i)
2760 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2762 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2772 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2776 return ((p > a1) && (p < a2));
2778 return ((p < a1) || (p > a2));
2780 return ((p >= a1) && (p <= a2));
2794 return (0); /* never reached */
2798 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2803 return (pf_match(op, a1, a2, p));
2807 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2809 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2811 return (pf_match(op, a1, a2, u));
2815 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2817 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2819 return (pf_match(op, a1, a2, g));
2823 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2828 return ((!r->match_tag_not && r->match_tag == *tag) ||
2829 (r->match_tag_not && r->match_tag != *tag));
2833 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2836 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2838 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2841 pd->pf_mtag->tag = tag;
2846 #define PF_ANCHOR_STACKSIZE 32
2847 struct pf_anchor_stackframe {
2848 struct pf_ruleset *rs;
2849 struct pf_rule *r; /* XXX: + match bit */
2850 struct pf_anchor *child;
2854 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2856 #define PF_ANCHORSTACK_MATCH 0x00000001
2857 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2859 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2860 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2861 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2862 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2863 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2867 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2868 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2871 struct pf_anchor_stackframe *f;
2877 if (*depth >= PF_ANCHOR_STACKSIZE) {
2878 printf("%s: anchor stack overflow on %s\n",
2879 __func__, (*r)->anchor->name);
2880 *r = TAILQ_NEXT(*r, entries);
2882 } else if (*depth == 0 && a != NULL)
2884 f = stack + (*depth)++;
2887 if ((*r)->anchor_wildcard) {
2888 struct pf_anchor_node *parent = &(*r)->anchor->children;
2890 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2894 *rs = &f->child->ruleset;
2897 *rs = &(*r)->anchor->ruleset;
2899 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2903 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2904 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2907 struct pf_anchor_stackframe *f;
2916 f = stack + *depth - 1;
2917 fr = PF_ANCHOR_RULE(f);
2918 if (f->child != NULL) {
2919 struct pf_anchor_node *parent;
2922 * This block traverses through
2923 * a wildcard anchor.
2925 parent = &fr->anchor->children;
2926 if (match != NULL && *match) {
2928 * If any of "*" matched, then
2929 * "foo/ *" matched, mark frame
2932 PF_ANCHOR_SET_MATCH(f);
2935 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2936 if (f->child != NULL) {
2937 *rs = &f->child->ruleset;
2938 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2946 if (*depth == 0 && a != NULL)
2949 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2951 *r = TAILQ_NEXT(fr, entries);
2952 } while (*r == NULL);
2959 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2960 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2965 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2966 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2970 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2971 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2972 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2973 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2974 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2975 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2976 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2977 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2983 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2988 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2992 if (addr->addr32[3] == 0xffffffff) {
2993 addr->addr32[3] = 0;
2994 if (addr->addr32[2] == 0xffffffff) {
2995 addr->addr32[2] = 0;
2996 if (addr->addr32[1] == 0xffffffff) {
2997 addr->addr32[1] = 0;
2999 htonl(ntohl(addr->addr32[0]) + 1);
3002 htonl(ntohl(addr->addr32[1]) + 1);
3005 htonl(ntohl(addr->addr32[2]) + 1);
3008 htonl(ntohl(addr->addr32[3]) + 1);
3015 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3017 struct pf_addr *saddr, *daddr;
3018 u_int16_t sport, dport;
3019 struct inpcbinfo *pi;
3022 pd->lookup.uid = UID_MAX;
3023 pd->lookup.gid = GID_MAX;
3025 switch (pd->proto) {
3027 if (pd->hdr.tcp == NULL)
3029 sport = pd->hdr.tcp->th_sport;
3030 dport = pd->hdr.tcp->th_dport;
3034 if (pd->hdr.udp == NULL)
3036 sport = pd->hdr.udp->uh_sport;
3037 dport = pd->hdr.udp->uh_dport;
3043 if (direction == PF_IN) {
3058 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3059 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3061 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3062 daddr->v4, dport, INPLOOKUP_WILDCARD |
3063 INPLOOKUP_RLOCKPCB, NULL, m);
3071 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3072 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3074 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3075 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3076 INPLOOKUP_RLOCKPCB, NULL, m);
3086 INP_RLOCK_ASSERT(inp);
3087 pd->lookup.uid = inp->inp_cred->cr_uid;
3088 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3095 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3099 u_int8_t *opt, optlen;
3100 u_int8_t wscale = 0;
3102 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3103 if (hlen <= sizeof(struct tcphdr))
3105 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3107 opt = hdr + sizeof(struct tcphdr);
3108 hlen -= sizeof(struct tcphdr);
3118 if (wscale > TCP_MAX_WINSHIFT)
3119 wscale = TCP_MAX_WINSHIFT;
3120 wscale |= PF_WSCALE_FLAG;
3135 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3139 u_int8_t *opt, optlen;
3140 u_int16_t mss = V_tcp_mssdflt;
3142 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3143 if (hlen <= sizeof(struct tcphdr))
3145 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3147 opt = hdr + sizeof(struct tcphdr);
3148 hlen -= sizeof(struct tcphdr);
3149 while (hlen >= TCPOLEN_MAXSEG) {
3157 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3173 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3176 struct nhop4_basic nh4;
3179 struct nhop6_basic nh6;
3180 struct in6_addr dst6;
3189 hlen = sizeof(struct ip);
3190 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3191 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3196 hlen = sizeof(struct ip6_hdr);
3197 in6_splitscope(&addr->v6, &dst6, &scopeid);
3198 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3199 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3204 mss = max(V_tcp_mssdflt, mss);
3205 mss = min(mss, offer);
3206 mss = max(mss, 64); /* sanity - at least max opt space */
3211 pf_tcp_iss(struct pf_pdesc *pd)
3214 u_int32_t digest[4];
3216 if (V_pf_tcp_secret_init == 0) {
3217 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3218 MD5Init(&V_pf_tcp_secret_ctx);
3219 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3220 sizeof(V_pf_tcp_secret));
3221 V_pf_tcp_secret_init = 1;
3224 ctx = V_pf_tcp_secret_ctx;
3226 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3227 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3228 if (pd->af == AF_INET6) {
3229 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3230 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3232 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3233 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3235 MD5Final((u_char *)digest, &ctx);
3236 V_pf_tcp_iss_off += 4096;
3237 #define ISN_RANDOM_INCREMENT (4096 - 1)
3238 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3240 #undef ISN_RANDOM_INCREMENT
3244 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3245 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3246 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3248 struct pf_rule *nr = NULL;
3249 struct pf_addr * const saddr = pd->src;
3250 struct pf_addr * const daddr = pd->dst;
3251 sa_family_t af = pd->af;
3252 struct pf_rule *r, *a = NULL;
3253 struct pf_ruleset *ruleset = NULL;
3254 struct pf_src_node *nsn = NULL;
3255 struct tcphdr *th = pd->hdr.tcp;
3256 struct pf_state_key *sk = NULL, *nk = NULL;
3258 int rewrite = 0, hdrlen = 0;
3259 int tag = -1, rtableid = -1;
3263 u_int16_t sport = 0, dport = 0;
3264 u_int16_t bproto_sum = 0, bip_sum = 0;
3265 u_int8_t icmptype = 0, icmpcode = 0;
3266 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3271 INP_LOCK_ASSERT(inp);
3272 pd->lookup.uid = inp->inp_cred->cr_uid;
3273 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3274 pd->lookup.done = 1;
3277 switch (pd->proto) {
3279 sport = th->th_sport;
3280 dport = th->th_dport;
3281 hdrlen = sizeof(*th);
3284 sport = pd->hdr.udp->uh_sport;
3285 dport = pd->hdr.udp->uh_dport;
3286 hdrlen = sizeof(*pd->hdr.udp);
3290 if (pd->af != AF_INET)
3292 sport = dport = pd->hdr.icmp->icmp_id;
3293 hdrlen = sizeof(*pd->hdr.icmp);
3294 icmptype = pd->hdr.icmp->icmp_type;
3295 icmpcode = pd->hdr.icmp->icmp_code;
3297 if (icmptype == ICMP_UNREACH ||
3298 icmptype == ICMP_SOURCEQUENCH ||
3299 icmptype == ICMP_REDIRECT ||
3300 icmptype == ICMP_TIMXCEED ||
3301 icmptype == ICMP_PARAMPROB)
3306 case IPPROTO_ICMPV6:
3309 sport = dport = pd->hdr.icmp6->icmp6_id;
3310 hdrlen = sizeof(*pd->hdr.icmp6);
3311 icmptype = pd->hdr.icmp6->icmp6_type;
3312 icmpcode = pd->hdr.icmp6->icmp6_code;
3314 if (icmptype == ICMP6_DST_UNREACH ||
3315 icmptype == ICMP6_PACKET_TOO_BIG ||
3316 icmptype == ICMP6_TIME_EXCEEDED ||
3317 icmptype == ICMP6_PARAM_PROB)
3322 sport = dport = hdrlen = 0;
3326 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3328 /* check packet for BINAT/NAT/RDR */
3329 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3330 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3331 KASSERT(sk != NULL, ("%s: null sk", __func__));
3332 KASSERT(nk != NULL, ("%s: null nk", __func__));
3335 bip_sum = *pd->ip_sum;
3337 switch (pd->proto) {
3339 bproto_sum = th->th_sum;
3340 pd->proto_sum = &th->th_sum;
3342 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3343 nk->port[pd->sidx] != sport) {
3344 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3345 &th->th_sum, &nk->addr[pd->sidx],
3346 nk->port[pd->sidx], 0, af);
3347 pd->sport = &th->th_sport;
3348 sport = th->th_sport;
3351 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3352 nk->port[pd->didx] != dport) {
3353 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3354 &th->th_sum, &nk->addr[pd->didx],
3355 nk->port[pd->didx], 0, af);
3356 dport = th->th_dport;
3357 pd->dport = &th->th_dport;
3362 bproto_sum = pd->hdr.udp->uh_sum;
3363 pd->proto_sum = &pd->hdr.udp->uh_sum;
3365 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3366 nk->port[pd->sidx] != sport) {
3367 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3368 pd->ip_sum, &pd->hdr.udp->uh_sum,
3369 &nk->addr[pd->sidx],
3370 nk->port[pd->sidx], 1, af);
3371 sport = pd->hdr.udp->uh_sport;
3372 pd->sport = &pd->hdr.udp->uh_sport;
3375 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3376 nk->port[pd->didx] != dport) {
3377 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3378 pd->ip_sum, &pd->hdr.udp->uh_sum,
3379 &nk->addr[pd->didx],
3380 nk->port[pd->didx], 1, af);
3381 dport = pd->hdr.udp->uh_dport;
3382 pd->dport = &pd->hdr.udp->uh_dport;
3388 nk->port[0] = nk->port[1];
3389 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3390 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3391 nk->addr[pd->sidx].v4.s_addr, 0);
3393 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3394 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3395 nk->addr[pd->didx].v4.s_addr, 0);
3397 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3398 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3399 pd->hdr.icmp->icmp_cksum, sport,
3401 pd->hdr.icmp->icmp_id = nk->port[1];
3402 pd->sport = &pd->hdr.icmp->icmp_id;
3404 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3408 case IPPROTO_ICMPV6:
3409 nk->port[0] = nk->port[1];
3410 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3411 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3412 &nk->addr[pd->sidx], 0);
3414 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3415 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3416 &nk->addr[pd->didx], 0);
3425 &nk->addr[pd->sidx], AF_INET))
3426 pf_change_a(&saddr->v4.s_addr,
3428 nk->addr[pd->sidx].v4.s_addr, 0);
3431 &nk->addr[pd->didx], AF_INET))
3432 pf_change_a(&daddr->v4.s_addr,
3434 nk->addr[pd->didx].v4.s_addr, 0);
3440 &nk->addr[pd->sidx], AF_INET6))
3441 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3444 &nk->addr[pd->didx], AF_INET6))
3445 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3458 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3459 r = r->skip[PF_SKIP_IFP].ptr;
3460 else if (r->direction && r->direction != direction)
3461 r = r->skip[PF_SKIP_DIR].ptr;
3462 else if (r->af && r->af != af)
3463 r = r->skip[PF_SKIP_AF].ptr;
3464 else if (r->proto && r->proto != pd->proto)
3465 r = r->skip[PF_SKIP_PROTO].ptr;
3466 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3467 r->src.neg, kif, M_GETFIB(m)))
3468 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3469 /* tcp/udp only. port_op always 0 in other cases */
3470 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3471 r->src.port[0], r->src.port[1], sport))
3472 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3473 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3474 r->dst.neg, NULL, M_GETFIB(m)))
3475 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3476 /* tcp/udp only. port_op always 0 in other cases */
3477 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3478 r->dst.port[0], r->dst.port[1], dport))
3479 r = r->skip[PF_SKIP_DST_PORT].ptr;
3480 /* icmp only. type always 0 in other cases */
3481 else if (r->type && r->type != icmptype + 1)
3482 r = TAILQ_NEXT(r, entries);
3483 /* icmp only. type always 0 in other cases */
3484 else if (r->code && r->code != icmpcode + 1)
3485 r = TAILQ_NEXT(r, entries);
3486 else if (r->tos && !(r->tos == pd->tos))
3487 r = TAILQ_NEXT(r, entries);
3488 else if (r->rule_flag & PFRULE_FRAGMENT)
3489 r = TAILQ_NEXT(r, entries);
3490 else if (pd->proto == IPPROTO_TCP &&
3491 (r->flagset & th->th_flags) != r->flags)
3492 r = TAILQ_NEXT(r, entries);
3493 /* tcp/udp only. uid.op always 0 in other cases */
3494 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3495 pf_socket_lookup(direction, pd, m), 1)) &&
3496 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3498 r = TAILQ_NEXT(r, entries);
3499 /* tcp/udp only. gid.op always 0 in other cases */
3500 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3501 pf_socket_lookup(direction, pd, m), 1)) &&
3502 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3504 r = TAILQ_NEXT(r, entries);
3506 !pf_match_ieee8021q_pcp(r->prio, m))
3507 r = TAILQ_NEXT(r, entries);
3509 r->prob <= arc4random())
3510 r = TAILQ_NEXT(r, entries);
3511 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3512 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3513 r = TAILQ_NEXT(r, entries);
3514 else if (r->os_fingerprint != PF_OSFP_ANY &&
3515 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3516 pf_osfp_fingerprint(pd, m, off, th),
3517 r->os_fingerprint)))
3518 r = TAILQ_NEXT(r, entries);
3522 if (r->rtableid >= 0)
3523 rtableid = r->rtableid;
3524 if (r->anchor == NULL) {
3531 r = TAILQ_NEXT(r, entries);
3533 pf_step_into_anchor(anchor_stack, &asd,
3534 &ruleset, PF_RULESET_FILTER, &r, &a,
3537 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3538 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3545 REASON_SET(&reason, PFRES_MATCH);
3547 if (r->log || (nr != NULL && nr->log)) {
3549 m_copyback(m, off, hdrlen, pd->hdr.any);
3550 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3554 if ((r->action == PF_DROP) &&
3555 ((r->rule_flag & PFRULE_RETURNRST) ||
3556 (r->rule_flag & PFRULE_RETURNICMP) ||
3557 (r->rule_flag & PFRULE_RETURN))) {
3558 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3559 bip_sum, hdrlen, &reason);
3562 if (r->action == PF_DROP)
3565 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3566 REASON_SET(&reason, PFRES_MEMORY);
3570 M_SETFIB(m, rtableid);
3572 if (!state_icmp && (r->keep_state || nr != NULL ||
3573 (pd->flags & PFDESC_TCP_NORM))) {
3575 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3576 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3578 if (action != PF_PASS) {
3579 if (action == PF_DROP &&
3580 (r->rule_flag & PFRULE_RETURN))
3581 pf_return(r, nr, pd, sk, off, m, th, kif,
3582 bproto_sum, bip_sum, hdrlen, &reason);
3587 uma_zfree(V_pf_state_key_z, sk);
3589 uma_zfree(V_pf_state_key_z, nk);
3592 /* copy back packet headers if we performed NAT operations */
3594 m_copyback(m, off, hdrlen, pd->hdr.any);
3596 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3597 direction == PF_OUT &&
3598 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3600 * We want the state created, but we dont
3601 * want to send this in case a partner
3602 * firewall has to know about it to allow
3603 * replies through it.
3611 uma_zfree(V_pf_state_key_z, sk);
3613 uma_zfree(V_pf_state_key_z, nk);
3618 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3619 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3620 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3621 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3622 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3624 struct pf_state *s = NULL;
3625 struct pf_src_node *sn = NULL;
3626 struct tcphdr *th = pd->hdr.tcp;
3627 u_int16_t mss = V_tcp_mssdflt;
3630 /* check maximums */
3631 if (r->max_states &&
3632 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3633 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3634 REASON_SET(&reason, PFRES_MAXSTATES);
3637 /* src node for filter rule */
3638 if ((r->rule_flag & PFRULE_SRCTRACK ||
3639 r->rpool.opts & PF_POOL_STICKYADDR) &&
3640 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3641 REASON_SET(&reason, PFRES_SRCLIMIT);
3644 /* src node for translation rule */
3645 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3646 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3647 REASON_SET(&reason, PFRES_SRCLIMIT);
3650 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3652 REASON_SET(&reason, PFRES_MEMORY);
3656 s->nat_rule.ptr = nr;
3658 STATE_INC_COUNTERS(s);
3660 s->state_flags |= PFSTATE_ALLOWOPTS;
3661 if (r->rule_flag & PFRULE_STATESLOPPY)
3662 s->state_flags |= PFSTATE_SLOPPY;
3663 s->log = r->log & PF_LOG_ALL;
3664 s->sync_state = PFSYNC_S_NONE;
3666 s->log |= nr->log & PF_LOG_ALL;
3667 switch (pd->proto) {
3669 s->src.seqlo = ntohl(th->th_seq);
3670 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3671 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3672 r->keep_state == PF_STATE_MODULATE) {
3673 /* Generate sequence number modulator */
3674 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3677 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3678 htonl(s->src.seqlo + s->src.seqdiff), 0);
3682 if (th->th_flags & TH_SYN) {
3684 s->src.wscale = pf_get_wscale(m, off,
3685 th->th_off, pd->af);
3687 s->src.max_win = MAX(ntohs(th->th_win), 1);
3688 if (s->src.wscale & PF_WSCALE_MASK) {
3689 /* Remove scale factor from initial window */
3690 int win = s->src.max_win;
3691 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3692 s->src.max_win = (win - 1) >>
3693 (s->src.wscale & PF_WSCALE_MASK);
3695 if (th->th_flags & TH_FIN)
3699 s->src.state = TCPS_SYN_SENT;
3700 s->dst.state = TCPS_CLOSED;
3701 s->timeout = PFTM_TCP_FIRST_PACKET;
3704 s->src.state = PFUDPS_SINGLE;
3705 s->dst.state = PFUDPS_NO_TRAFFIC;
3706 s->timeout = PFTM_UDP_FIRST_PACKET;
3710 case IPPROTO_ICMPV6:
3712 s->timeout = PFTM_ICMP_FIRST_PACKET;
3715 s->src.state = PFOTHERS_SINGLE;
3716 s->dst.state = PFOTHERS_NO_TRAFFIC;
3717 s->timeout = PFTM_OTHER_FIRST_PACKET;
3721 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3722 REASON_SET(&reason, PFRES_MAPFAILED);
3723 pf_src_tree_remove_state(s);
3724 STATE_DEC_COUNTERS(s);
3725 uma_zfree(V_pf_state_z, s);
3728 s->rt_kif = r->rpool.cur->kif;
3731 s->creation = time_uptime;
3732 s->expire = time_uptime;
3737 /* XXX We only modify one side for now. */
3738 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3739 s->nat_src_node = nsn;
3741 if (pd->proto == IPPROTO_TCP) {
3742 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3743 off, pd, th, &s->src, &s->dst)) {
3744 REASON_SET(&reason, PFRES_MEMORY);
3745 pf_src_tree_remove_state(s);
3746 STATE_DEC_COUNTERS(s);
3747 uma_zfree(V_pf_state_z, s);
3750 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3751 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3752 &s->src, &s->dst, rewrite)) {
3753 /* This really shouldn't happen!!! */
3754 DPFPRINTF(PF_DEBUG_URGENT,
3755 ("pf_normalize_tcp_stateful failed on first pkt"));
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;
4092 * Need to demodulate the sequence numbers in any TCP SACK options
4093 * (Selective ACK). We could optionally validate the SACK values
4094 * against the current ACK window, either forwards or backwards, but
4095 * I'm not confident that SACK has been implemented properly
4096 * everywhere. It wouldn't surprise me if several stacks accidentally
4097 * SACK too far backwards of previously ACKed data. There really aren't
4098 * any security implications of bad SACKing unless the target stack
4099 * doesn't validate the option length correctly. Someone trying to
4100 * spoof into a TCP connection won't bother blindly sending SACK
4103 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4104 if (pf_modulate_sack(m, off, pd, th, dst))
4109 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4110 if (SEQ_GEQ(src->seqhi, end) &&
4111 /* Last octet inside other's window space */
4112 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4113 /* Retrans: not more than one window back */
4114 (ackskew >= -MAXACKWINDOW) &&
4115 /* Acking not more than one reassembled fragment backwards */
4116 (ackskew <= (MAXACKWINDOW << sws)) &&
4117 /* Acking not more than one window forward */
4118 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4119 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4120 (pd->flags & PFDESC_IP_REAS) == 0)) {
4121 /* Require an exact/+1 sequence match on resets when possible */
4123 if (dst->scrub || src->scrub) {
4124 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4125 *state, src, dst, copyback))
4129 /* update max window */
4130 if (src->max_win < win)
4132 /* synchronize sequencing */
4133 if (SEQ_GT(end, src->seqlo))
4135 /* slide the window of what the other end can send */
4136 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4137 dst->seqhi = ack + MAX((win << sws), 1);
4141 if (th->th_flags & TH_SYN)
4142 if (src->state < TCPS_SYN_SENT)
4143 src->state = TCPS_SYN_SENT;
4144 if (th->th_flags & TH_FIN)
4145 if (src->state < TCPS_CLOSING)
4146 src->state = TCPS_CLOSING;
4147 if (th->th_flags & TH_ACK) {
4148 if (dst->state == TCPS_SYN_SENT) {
4149 dst->state = TCPS_ESTABLISHED;
4150 if (src->state == TCPS_ESTABLISHED &&
4151 (*state)->src_node != NULL &&
4152 pf_src_connlimit(state)) {
4153 REASON_SET(reason, PFRES_SRCLIMIT);
4156 } else if (dst->state == TCPS_CLOSING)
4157 dst->state = TCPS_FIN_WAIT_2;
4159 if (th->th_flags & TH_RST)
4160 src->state = dst->state = TCPS_TIME_WAIT;
4162 /* update expire time */
4163 (*state)->expire = time_uptime;
4164 if (src->state >= TCPS_FIN_WAIT_2 &&
4165 dst->state >= TCPS_FIN_WAIT_2)
4166 (*state)->timeout = PFTM_TCP_CLOSED;
4167 else if (src->state >= TCPS_CLOSING &&
4168 dst->state >= TCPS_CLOSING)
4169 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4170 else if (src->state < TCPS_ESTABLISHED ||
4171 dst->state < TCPS_ESTABLISHED)
4172 (*state)->timeout = PFTM_TCP_OPENING;
4173 else if (src->state >= TCPS_CLOSING ||
4174 dst->state >= TCPS_CLOSING)
4175 (*state)->timeout = PFTM_TCP_CLOSING;
4177 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4179 /* Fall through to PASS packet */
4181 } else if ((dst->state < TCPS_SYN_SENT ||
4182 dst->state >= TCPS_FIN_WAIT_2 ||
4183 src->state >= TCPS_FIN_WAIT_2) &&
4184 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4185 /* Within a window forward of the originating packet */
4186 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4187 /* Within a window backward of the originating packet */
4190 * This currently handles three situations:
4191 * 1) Stupid stacks will shotgun SYNs before their peer
4193 * 2) When PF catches an already established stream (the
4194 * firewall rebooted, the state table was flushed, routes
4196 * 3) Packets get funky immediately after the connection
4197 * closes (this should catch Solaris spurious ACK|FINs
4198 * that web servers like to spew after a close)
4200 * This must be a little more careful than the above code
4201 * since packet floods will also be caught here. We don't
4202 * update the TTL here to mitigate the damage of a packet
4203 * flood and so the same code can handle awkward establishment
4204 * and a loosened connection close.
4205 * In the establishment case, a correct peer response will
4206 * validate the connection, go through the normal state code
4207 * and keep updating the state TTL.
4210 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4211 printf("pf: loose state match: ");
4212 pf_print_state(*state);
4213 pf_print_flags(th->th_flags);
4214 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4215 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4216 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4217 (unsigned long long)(*state)->packets[1],
4218 pd->dir == PF_IN ? "in" : "out",
4219 pd->dir == (*state)->direction ? "fwd" : "rev");
4222 if (dst->scrub || src->scrub) {
4223 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4224 *state, src, dst, copyback))
4228 /* update max window */
4229 if (src->max_win < win)
4231 /* synchronize sequencing */
4232 if (SEQ_GT(end, src->seqlo))
4234 /* slide the window of what the other end can send */
4235 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4236 dst->seqhi = ack + MAX((win << sws), 1);
4239 * Cannot set dst->seqhi here since this could be a shotgunned
4240 * SYN and not an already established connection.
4243 if (th->th_flags & TH_FIN)
4244 if (src->state < TCPS_CLOSING)
4245 src->state = TCPS_CLOSING;
4246 if (th->th_flags & TH_RST)
4247 src->state = dst->state = TCPS_TIME_WAIT;
4249 /* Fall through to PASS packet */
4252 if ((*state)->dst.state == TCPS_SYN_SENT &&
4253 (*state)->src.state == TCPS_SYN_SENT) {
4254 /* Send RST for state mismatches during handshake */
4255 if (!(th->th_flags & TH_RST))
4256 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4257 pd->dst, pd->src, th->th_dport,
4258 th->th_sport, ntohl(th->th_ack), 0,
4260 (*state)->rule.ptr->return_ttl, 1, 0,
4265 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4266 printf("pf: BAD state: ");
4267 pf_print_state(*state);
4268 pf_print_flags(th->th_flags);
4269 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4270 "pkts=%llu:%llu dir=%s,%s\n",
4271 seq, orig_seq, ack, pd->p_len, ackskew,
4272 (unsigned long long)(*state)->packets[0],
4273 (unsigned long long)(*state)->packets[1],
4274 pd->dir == PF_IN ? "in" : "out",
4275 pd->dir == (*state)->direction ? "fwd" : "rev");
4276 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4277 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4278 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4280 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4281 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4282 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4283 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4285 REASON_SET(reason, PFRES_BADSTATE);
4293 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4294 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4296 struct tcphdr *th = pd->hdr.tcp;
4298 if (th->th_flags & TH_SYN)
4299 if (src->state < TCPS_SYN_SENT)
4300 src->state = TCPS_SYN_SENT;
4301 if (th->th_flags & TH_FIN)
4302 if (src->state < TCPS_CLOSING)
4303 src->state = TCPS_CLOSING;
4304 if (th->th_flags & TH_ACK) {
4305 if (dst->state == TCPS_SYN_SENT) {
4306 dst->state = TCPS_ESTABLISHED;
4307 if (src->state == TCPS_ESTABLISHED &&
4308 (*state)->src_node != NULL &&
4309 pf_src_connlimit(state)) {
4310 REASON_SET(reason, PFRES_SRCLIMIT);
4313 } else if (dst->state == TCPS_CLOSING) {
4314 dst->state = TCPS_FIN_WAIT_2;
4315 } else if (src->state == TCPS_SYN_SENT &&
4316 dst->state < TCPS_SYN_SENT) {
4318 * Handle a special sloppy case where we only see one
4319 * half of the connection. If there is a ACK after
4320 * the initial SYN without ever seeing a packet from
4321 * the destination, set the connection to established.
4323 dst->state = src->state = TCPS_ESTABLISHED;
4324 if ((*state)->src_node != NULL &&
4325 pf_src_connlimit(state)) {
4326 REASON_SET(reason, PFRES_SRCLIMIT);
4329 } else if (src->state == TCPS_CLOSING &&
4330 dst->state == TCPS_ESTABLISHED &&
4333 * Handle the closing of half connections where we
4334 * don't see the full bidirectional FIN/ACK+ACK
4337 dst->state = TCPS_CLOSING;
4340 if (th->th_flags & TH_RST)
4341 src->state = dst->state = TCPS_TIME_WAIT;
4343 /* update expire time */
4344 (*state)->expire = time_uptime;
4345 if (src->state >= TCPS_FIN_WAIT_2 &&
4346 dst->state >= TCPS_FIN_WAIT_2)
4347 (*state)->timeout = PFTM_TCP_CLOSED;
4348 else if (src->state >= TCPS_CLOSING &&
4349 dst->state >= TCPS_CLOSING)
4350 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4351 else if (src->state < TCPS_ESTABLISHED ||
4352 dst->state < TCPS_ESTABLISHED)
4353 (*state)->timeout = PFTM_TCP_OPENING;
4354 else if (src->state >= TCPS_CLOSING ||
4355 dst->state >= TCPS_CLOSING)
4356 (*state)->timeout = PFTM_TCP_CLOSING;
4358 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4364 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4365 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4368 struct pf_state_key_cmp key;
4369 struct tcphdr *th = pd->hdr.tcp;
4371 struct pf_state_peer *src, *dst;
4372 struct pf_state_key *sk;
4374 bzero(&key, sizeof(key));
4376 key.proto = IPPROTO_TCP;
4377 if (direction == PF_IN) { /* wire side, straight */
4378 PF_ACPY(&key.addr[0], pd->src, key.af);
4379 PF_ACPY(&key.addr[1], pd->dst, key.af);
4380 key.port[0] = th->th_sport;
4381 key.port[1] = th->th_dport;
4382 } else { /* stack side, reverse */
4383 PF_ACPY(&key.addr[1], pd->src, key.af);
4384 PF_ACPY(&key.addr[0], pd->dst, key.af);
4385 key.port[1] = th->th_sport;
4386 key.port[0] = th->th_dport;
4389 STATE_LOOKUP(kif, &key, direction, *state, pd);
4391 if (direction == (*state)->direction) {
4392 src = &(*state)->src;
4393 dst = &(*state)->dst;
4395 src = &(*state)->dst;
4396 dst = &(*state)->src;
4399 sk = (*state)->key[pd->didx];
4401 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4402 if (direction != (*state)->direction) {
4403 REASON_SET(reason, PFRES_SYNPROXY);
4404 return (PF_SYNPROXY_DROP);
4406 if (th->th_flags & TH_SYN) {
4407 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4408 REASON_SET(reason, PFRES_SYNPROXY);
4411 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4412 pd->src, th->th_dport, th->th_sport,
4413 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4414 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4415 REASON_SET(reason, PFRES_SYNPROXY);
4416 return (PF_SYNPROXY_DROP);
4417 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4418 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4419 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4420 REASON_SET(reason, PFRES_SYNPROXY);
4422 } else if ((*state)->src_node != NULL &&
4423 pf_src_connlimit(state)) {
4424 REASON_SET(reason, PFRES_SRCLIMIT);
4427 (*state)->src.state = PF_TCPS_PROXY_DST;
4429 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4430 if (direction == (*state)->direction) {
4431 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4432 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4433 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4434 REASON_SET(reason, PFRES_SYNPROXY);
4437 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4438 if ((*state)->dst.seqhi == 1)
4439 (*state)->dst.seqhi = htonl(arc4random());
4440 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4441 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4442 sk->port[pd->sidx], sk->port[pd->didx],
4443 (*state)->dst.seqhi, 0, TH_SYN, 0,
4444 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4445 REASON_SET(reason, PFRES_SYNPROXY);
4446 return (PF_SYNPROXY_DROP);
4447 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4449 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4450 REASON_SET(reason, PFRES_SYNPROXY);
4453 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4454 (*state)->dst.seqlo = ntohl(th->th_seq);
4455 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4456 pd->src, th->th_dport, th->th_sport,
4457 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4458 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4459 (*state)->tag, NULL);
4460 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4461 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4462 sk->port[pd->sidx], sk->port[pd->didx],
4463 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4464 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4465 (*state)->src.seqdiff = (*state)->dst.seqhi -
4466 (*state)->src.seqlo;
4467 (*state)->dst.seqdiff = (*state)->src.seqhi -
4468 (*state)->dst.seqlo;
4469 (*state)->src.seqhi = (*state)->src.seqlo +
4470 (*state)->dst.max_win;
4471 (*state)->dst.seqhi = (*state)->dst.seqlo +
4472 (*state)->src.max_win;
4473 (*state)->src.wscale = (*state)->dst.wscale = 0;
4474 (*state)->src.state = (*state)->dst.state =
4476 REASON_SET(reason, PFRES_SYNPROXY);
4477 return (PF_SYNPROXY_DROP);
4481 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4482 dst->state >= TCPS_FIN_WAIT_2 &&
4483 src->state >= TCPS_FIN_WAIT_2) {
4484 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4485 printf("pf: state reuse ");
4486 pf_print_state(*state);
4487 pf_print_flags(th->th_flags);
4490 /* XXX make sure it's the same direction ?? */
4491 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4492 pf_unlink_state(*state, PF_ENTER_LOCKED);
4497 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4498 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4501 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4502 ©back) == PF_DROP)
4506 /* translate source/destination address, if necessary */
4507 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4508 struct pf_state_key *nk = (*state)->key[pd->didx];
4510 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4511 nk->port[pd->sidx] != th->th_sport)
4512 pf_change_ap(m, pd->src, &th->th_sport,
4513 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4514 nk->port[pd->sidx], 0, pd->af);
4516 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4517 nk->port[pd->didx] != th->th_dport)
4518 pf_change_ap(m, pd->dst, &th->th_dport,
4519 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4520 nk->port[pd->didx], 0, pd->af);
4524 /* Copyback sequence modulation or stateful scrub changes if needed */
4526 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4532 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4533 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4535 struct pf_state_peer *src, *dst;
4536 struct pf_state_key_cmp key;
4537 struct udphdr *uh = pd->hdr.udp;
4539 bzero(&key, sizeof(key));
4541 key.proto = IPPROTO_UDP;
4542 if (direction == PF_IN) { /* wire side, straight */
4543 PF_ACPY(&key.addr[0], pd->src, key.af);
4544 PF_ACPY(&key.addr[1], pd->dst, key.af);
4545 key.port[0] = uh->uh_sport;
4546 key.port[1] = uh->uh_dport;
4547 } else { /* stack side, reverse */
4548 PF_ACPY(&key.addr[1], pd->src, key.af);
4549 PF_ACPY(&key.addr[0], pd->dst, key.af);
4550 key.port[1] = uh->uh_sport;
4551 key.port[0] = uh->uh_dport;
4554 STATE_LOOKUP(kif, &key, direction, *state, pd);
4556 if (direction == (*state)->direction) {
4557 src = &(*state)->src;
4558 dst = &(*state)->dst;
4560 src = &(*state)->dst;
4561 dst = &(*state)->src;
4565 if (src->state < PFUDPS_SINGLE)
4566 src->state = PFUDPS_SINGLE;
4567 if (dst->state == PFUDPS_SINGLE)
4568 dst->state = PFUDPS_MULTIPLE;
4570 /* update expire time */
4571 (*state)->expire = time_uptime;
4572 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4573 (*state)->timeout = PFTM_UDP_MULTIPLE;
4575 (*state)->timeout = PFTM_UDP_SINGLE;
4577 /* translate source/destination address, if necessary */
4578 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4579 struct pf_state_key *nk = (*state)->key[pd->didx];
4581 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4582 nk->port[pd->sidx] != uh->uh_sport)
4583 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4584 &uh->uh_sum, &nk->addr[pd->sidx],
4585 nk->port[pd->sidx], 1, pd->af);
4587 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4588 nk->port[pd->didx] != uh->uh_dport)
4589 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4590 &uh->uh_sum, &nk->addr[pd->didx],
4591 nk->port[pd->didx], 1, pd->af);
4592 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4599 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4600 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4602 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4603 u_int16_t icmpid = 0, *icmpsum;
4604 u_int8_t icmptype, icmpcode;
4606 struct pf_state_key_cmp key;
4608 bzero(&key, sizeof(key));
4609 switch (pd->proto) {
4612 icmptype = pd->hdr.icmp->icmp_type;
4613 icmpcode = pd->hdr.icmp->icmp_code;
4614 icmpid = pd->hdr.icmp->icmp_id;
4615 icmpsum = &pd->hdr.icmp->icmp_cksum;
4617 if (icmptype == ICMP_UNREACH ||
4618 icmptype == ICMP_SOURCEQUENCH ||
4619 icmptype == ICMP_REDIRECT ||
4620 icmptype == ICMP_TIMXCEED ||
4621 icmptype == ICMP_PARAMPROB)
4626 case IPPROTO_ICMPV6:
4627 icmptype = pd->hdr.icmp6->icmp6_type;
4628 icmpcode = pd->hdr.icmp6->icmp6_code;
4629 icmpid = pd->hdr.icmp6->icmp6_id;
4630 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4632 if (icmptype == ICMP6_DST_UNREACH ||
4633 icmptype == ICMP6_PACKET_TOO_BIG ||
4634 icmptype == ICMP6_TIME_EXCEEDED ||
4635 icmptype == ICMP6_PARAM_PROB)
4644 * ICMP query/reply message not related to a TCP/UDP packet.
4645 * Search for an ICMP state.
4648 key.proto = pd->proto;
4649 key.port[0] = key.port[1] = icmpid;
4650 if (direction == PF_IN) { /* wire side, straight */
4651 PF_ACPY(&key.addr[0], pd->src, key.af);
4652 PF_ACPY(&key.addr[1], pd->dst, key.af);
4653 } else { /* stack side, reverse */
4654 PF_ACPY(&key.addr[1], pd->src, key.af);
4655 PF_ACPY(&key.addr[0], pd->dst, key.af);
4658 STATE_LOOKUP(kif, &key, direction, *state, pd);
4660 (*state)->expire = time_uptime;
4661 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4663 /* translate source/destination address, if necessary */
4664 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4665 struct pf_state_key *nk = (*state)->key[pd->didx];
4670 if (PF_ANEQ(pd->src,
4671 &nk->addr[pd->sidx], AF_INET))
4672 pf_change_a(&saddr->v4.s_addr,
4674 nk->addr[pd->sidx].v4.s_addr, 0);
4676 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4678 pf_change_a(&daddr->v4.s_addr,
4680 nk->addr[pd->didx].v4.s_addr, 0);
4683 pd->hdr.icmp->icmp_id) {
4684 pd->hdr.icmp->icmp_cksum =
4686 pd->hdr.icmp->icmp_cksum, icmpid,
4687 nk->port[pd->sidx], 0);
4688 pd->hdr.icmp->icmp_id =
4692 m_copyback(m, off, ICMP_MINLEN,
4693 (caddr_t )pd->hdr.icmp);
4698 if (PF_ANEQ(pd->src,
4699 &nk->addr[pd->sidx], AF_INET6))
4701 &pd->hdr.icmp6->icmp6_cksum,
4702 &nk->addr[pd->sidx], 0);
4704 if (PF_ANEQ(pd->dst,
4705 &nk->addr[pd->didx], AF_INET6))
4707 &pd->hdr.icmp6->icmp6_cksum,
4708 &nk->addr[pd->didx], 0);
4710 m_copyback(m, off, sizeof(struct icmp6_hdr),
4711 (caddr_t )pd->hdr.icmp6);
4720 * ICMP error message in response to a TCP/UDP packet.
4721 * Extract the inner TCP/UDP header and search for that state.
4724 struct pf_pdesc pd2;
4725 bzero(&pd2, sizeof pd2);
4730 struct ip6_hdr h2_6;
4737 /* Payload packet is from the opposite direction. */
4738 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4739 pd2.didx = (direction == PF_IN) ? 0 : 1;
4743 /* offset of h2 in mbuf chain */
4744 ipoff2 = off + ICMP_MINLEN;
4746 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4747 NULL, reason, pd2.af)) {
4748 DPFPRINTF(PF_DEBUG_MISC,
4749 ("pf: ICMP error message too short "
4754 * ICMP error messages don't refer to non-first
4757 if (h2.ip_off & htons(IP_OFFMASK)) {
4758 REASON_SET(reason, PFRES_FRAG);
4762 /* offset of protocol header that follows h2 */
4763 off2 = ipoff2 + (h2.ip_hl << 2);
4765 pd2.proto = h2.ip_p;
4766 pd2.src = (struct pf_addr *)&h2.ip_src;
4767 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4768 pd2.ip_sum = &h2.ip_sum;
4773 ipoff2 = off + sizeof(struct icmp6_hdr);
4775 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4776 NULL, reason, pd2.af)) {
4777 DPFPRINTF(PF_DEBUG_MISC,
4778 ("pf: ICMP error message too short "
4782 pd2.proto = h2_6.ip6_nxt;
4783 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4784 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4786 off2 = ipoff2 + sizeof(h2_6);
4788 switch (pd2.proto) {
4789 case IPPROTO_FRAGMENT:
4791 * ICMPv6 error messages for
4792 * non-first fragments
4794 REASON_SET(reason, PFRES_FRAG);
4797 case IPPROTO_HOPOPTS:
4798 case IPPROTO_ROUTING:
4799 case IPPROTO_DSTOPTS: {
4800 /* get next header and header length */
4801 struct ip6_ext opt6;
4803 if (!pf_pull_hdr(m, off2, &opt6,
4804 sizeof(opt6), NULL, reason,
4806 DPFPRINTF(PF_DEBUG_MISC,
4807 ("pf: ICMPv6 short opt\n"));
4810 if (pd2.proto == IPPROTO_AH)
4811 off2 += (opt6.ip6e_len + 2) * 4;
4813 off2 += (opt6.ip6e_len + 1) * 8;
4814 pd2.proto = opt6.ip6e_nxt;
4815 /* goto the next header */
4822 } while (!terminal);
4827 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4828 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4829 printf("pf: BAD ICMP %d:%d outer dst: ",
4830 icmptype, icmpcode);
4831 pf_print_host(pd->src, 0, pd->af);
4833 pf_print_host(pd->dst, 0, pd->af);
4834 printf(" inner src: ");
4835 pf_print_host(pd2.src, 0, pd2.af);
4837 pf_print_host(pd2.dst, 0, pd2.af);
4840 REASON_SET(reason, PFRES_BADSTATE);
4844 switch (pd2.proto) {
4848 struct pf_state_peer *src, *dst;
4853 * Only the first 8 bytes of the TCP header can be
4854 * expected. Don't access any TCP header fields after
4855 * th_seq, an ackskew test is not possible.
4857 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4859 DPFPRINTF(PF_DEBUG_MISC,
4860 ("pf: ICMP error message too short "
4866 key.proto = IPPROTO_TCP;
4867 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4868 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4869 key.port[pd2.sidx] = th.th_sport;
4870 key.port[pd2.didx] = th.th_dport;
4872 STATE_LOOKUP(kif, &key, direction, *state, pd);
4874 if (direction == (*state)->direction) {
4875 src = &(*state)->dst;
4876 dst = &(*state)->src;
4878 src = &(*state)->src;
4879 dst = &(*state)->dst;
4882 if (src->wscale && dst->wscale)
4883 dws = dst->wscale & PF_WSCALE_MASK;
4887 /* Demodulate sequence number */
4888 seq = ntohl(th.th_seq) - src->seqdiff;
4890 pf_change_a(&th.th_seq, icmpsum,
4895 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4896 (!SEQ_GEQ(src->seqhi, seq) ||
4897 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4898 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4899 printf("pf: BAD ICMP %d:%d ",
4900 icmptype, icmpcode);
4901 pf_print_host(pd->src, 0, pd->af);
4903 pf_print_host(pd->dst, 0, pd->af);
4905 pf_print_state(*state);
4906 printf(" seq=%u\n", seq);
4908 REASON_SET(reason, PFRES_BADSTATE);
4911 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4912 printf("pf: OK ICMP %d:%d ",
4913 icmptype, icmpcode);
4914 pf_print_host(pd->src, 0, pd->af);
4916 pf_print_host(pd->dst, 0, pd->af);
4918 pf_print_state(*state);
4919 printf(" seq=%u\n", seq);
4923 /* translate source/destination address, if necessary */
4924 if ((*state)->key[PF_SK_WIRE] !=
4925 (*state)->key[PF_SK_STACK]) {
4926 struct pf_state_key *nk =
4927 (*state)->key[pd->didx];
4929 if (PF_ANEQ(pd2.src,
4930 &nk->addr[pd2.sidx], pd2.af) ||
4931 nk->port[pd2.sidx] != th.th_sport)
4932 pf_change_icmp(pd2.src, &th.th_sport,
4933 daddr, &nk->addr[pd2.sidx],
4934 nk->port[pd2.sidx], NULL,
4935 pd2.ip_sum, icmpsum,
4936 pd->ip_sum, 0, pd2.af);
4938 if (PF_ANEQ(pd2.dst,
4939 &nk->addr[pd2.didx], pd2.af) ||
4940 nk->port[pd2.didx] != th.th_dport)
4941 pf_change_icmp(pd2.dst, &th.th_dport,
4942 saddr, &nk->addr[pd2.didx],
4943 nk->port[pd2.didx], NULL,
4944 pd2.ip_sum, icmpsum,
4945 pd->ip_sum, 0, pd2.af);
4953 m_copyback(m, off, ICMP_MINLEN,
4954 (caddr_t )pd->hdr.icmp);
4955 m_copyback(m, ipoff2, sizeof(h2),
4962 sizeof(struct icmp6_hdr),
4963 (caddr_t )pd->hdr.icmp6);
4964 m_copyback(m, ipoff2, sizeof(h2_6),
4969 m_copyback(m, off2, 8, (caddr_t)&th);
4978 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4979 NULL, reason, pd2.af)) {
4980 DPFPRINTF(PF_DEBUG_MISC,
4981 ("pf: ICMP error message too short "
4987 key.proto = IPPROTO_UDP;
4988 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4989 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4990 key.port[pd2.sidx] = uh.uh_sport;
4991 key.port[pd2.didx] = uh.uh_dport;
4993 STATE_LOOKUP(kif, &key, direction, *state, pd);
4995 /* translate source/destination address, if necessary */
4996 if ((*state)->key[PF_SK_WIRE] !=
4997 (*state)->key[PF_SK_STACK]) {
4998 struct pf_state_key *nk =
4999 (*state)->key[pd->didx];
5001 if (PF_ANEQ(pd2.src,
5002 &nk->addr[pd2.sidx], pd2.af) ||
5003 nk->port[pd2.sidx] != uh.uh_sport)
5004 pf_change_icmp(pd2.src, &uh.uh_sport,
5005 daddr, &nk->addr[pd2.sidx],
5006 nk->port[pd2.sidx], &uh.uh_sum,
5007 pd2.ip_sum, icmpsum,
5008 pd->ip_sum, 1, pd2.af);
5010 if (PF_ANEQ(pd2.dst,
5011 &nk->addr[pd2.didx], pd2.af) ||
5012 nk->port[pd2.didx] != uh.uh_dport)
5013 pf_change_icmp(pd2.dst, &uh.uh_dport,
5014 saddr, &nk->addr[pd2.didx],
5015 nk->port[pd2.didx], &uh.uh_sum,
5016 pd2.ip_sum, icmpsum,
5017 pd->ip_sum, 1, pd2.af);
5022 m_copyback(m, off, ICMP_MINLEN,
5023 (caddr_t )pd->hdr.icmp);
5024 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5030 sizeof(struct icmp6_hdr),
5031 (caddr_t )pd->hdr.icmp6);
5032 m_copyback(m, ipoff2, sizeof(h2_6),
5037 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5043 case IPPROTO_ICMP: {
5046 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5047 NULL, reason, pd2.af)) {
5048 DPFPRINTF(PF_DEBUG_MISC,
5049 ("pf: ICMP error message too short i"
5055 key.proto = IPPROTO_ICMP;
5056 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5057 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5058 key.port[0] = key.port[1] = iih.icmp_id;
5060 STATE_LOOKUP(kif, &key, direction, *state, pd);
5062 /* translate source/destination address, if necessary */
5063 if ((*state)->key[PF_SK_WIRE] !=
5064 (*state)->key[PF_SK_STACK]) {
5065 struct pf_state_key *nk =
5066 (*state)->key[pd->didx];
5068 if (PF_ANEQ(pd2.src,
5069 &nk->addr[pd2.sidx], pd2.af) ||
5070 nk->port[pd2.sidx] != iih.icmp_id)
5071 pf_change_icmp(pd2.src, &iih.icmp_id,
5072 daddr, &nk->addr[pd2.sidx],
5073 nk->port[pd2.sidx], NULL,
5074 pd2.ip_sum, icmpsum,
5075 pd->ip_sum, 0, AF_INET);
5077 if (PF_ANEQ(pd2.dst,
5078 &nk->addr[pd2.didx], pd2.af) ||
5079 nk->port[pd2.didx] != iih.icmp_id)
5080 pf_change_icmp(pd2.dst, &iih.icmp_id,
5081 saddr, &nk->addr[pd2.didx],
5082 nk->port[pd2.didx], NULL,
5083 pd2.ip_sum, icmpsum,
5084 pd->ip_sum, 0, AF_INET);
5086 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5087 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5088 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5095 case IPPROTO_ICMPV6: {
5096 struct icmp6_hdr iih;
5098 if (!pf_pull_hdr(m, off2, &iih,
5099 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5100 DPFPRINTF(PF_DEBUG_MISC,
5101 ("pf: ICMP error message too short "
5107 key.proto = IPPROTO_ICMPV6;
5108 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5109 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5110 key.port[0] = key.port[1] = iih.icmp6_id;
5112 STATE_LOOKUP(kif, &key, direction, *state, pd);
5114 /* translate source/destination address, if necessary */
5115 if ((*state)->key[PF_SK_WIRE] !=
5116 (*state)->key[PF_SK_STACK]) {
5117 struct pf_state_key *nk =
5118 (*state)->key[pd->didx];
5120 if (PF_ANEQ(pd2.src,
5121 &nk->addr[pd2.sidx], pd2.af) ||
5122 nk->port[pd2.sidx] != iih.icmp6_id)
5123 pf_change_icmp(pd2.src, &iih.icmp6_id,
5124 daddr, &nk->addr[pd2.sidx],
5125 nk->port[pd2.sidx], NULL,
5126 pd2.ip_sum, icmpsum,
5127 pd->ip_sum, 0, AF_INET6);
5129 if (PF_ANEQ(pd2.dst,
5130 &nk->addr[pd2.didx], pd2.af) ||
5131 nk->port[pd2.didx] != iih.icmp6_id)
5132 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5133 saddr, &nk->addr[pd2.didx],
5134 nk->port[pd2.didx], NULL,
5135 pd2.ip_sum, icmpsum,
5136 pd->ip_sum, 0, AF_INET6);
5138 m_copyback(m, off, sizeof(struct icmp6_hdr),
5139 (caddr_t)pd->hdr.icmp6);
5140 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5141 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5150 key.proto = pd2.proto;
5151 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5152 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5153 key.port[0] = key.port[1] = 0;
5155 STATE_LOOKUP(kif, &key, direction, *state, pd);
5157 /* translate source/destination address, if necessary */
5158 if ((*state)->key[PF_SK_WIRE] !=
5159 (*state)->key[PF_SK_STACK]) {
5160 struct pf_state_key *nk =
5161 (*state)->key[pd->didx];
5163 if (PF_ANEQ(pd2.src,
5164 &nk->addr[pd2.sidx], pd2.af))
5165 pf_change_icmp(pd2.src, NULL, daddr,
5166 &nk->addr[pd2.sidx], 0, NULL,
5167 pd2.ip_sum, icmpsum,
5168 pd->ip_sum, 0, pd2.af);
5170 if (PF_ANEQ(pd2.dst,
5171 &nk->addr[pd2.didx], pd2.af))
5172 pf_change_icmp(pd2.dst, NULL, saddr,
5173 &nk->addr[pd2.didx], 0, NULL,
5174 pd2.ip_sum, icmpsum,
5175 pd->ip_sum, 0, pd2.af);
5180 m_copyback(m, off, ICMP_MINLEN,
5181 (caddr_t)pd->hdr.icmp);
5182 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5188 sizeof(struct icmp6_hdr),
5189 (caddr_t )pd->hdr.icmp6);
5190 m_copyback(m, ipoff2, sizeof(h2_6),
5204 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5205 struct mbuf *m, struct pf_pdesc *pd)
5207 struct pf_state_peer *src, *dst;
5208 struct pf_state_key_cmp key;
5210 bzero(&key, sizeof(key));
5212 key.proto = pd->proto;
5213 if (direction == PF_IN) {
5214 PF_ACPY(&key.addr[0], pd->src, key.af);
5215 PF_ACPY(&key.addr[1], pd->dst, key.af);
5216 key.port[0] = key.port[1] = 0;
5218 PF_ACPY(&key.addr[1], pd->src, key.af);
5219 PF_ACPY(&key.addr[0], pd->dst, key.af);
5220 key.port[1] = key.port[0] = 0;
5223 STATE_LOOKUP(kif, &key, direction, *state, pd);
5225 if (direction == (*state)->direction) {
5226 src = &(*state)->src;
5227 dst = &(*state)->dst;
5229 src = &(*state)->dst;
5230 dst = &(*state)->src;
5234 if (src->state < PFOTHERS_SINGLE)
5235 src->state = PFOTHERS_SINGLE;
5236 if (dst->state == PFOTHERS_SINGLE)
5237 dst->state = PFOTHERS_MULTIPLE;
5239 /* update expire time */
5240 (*state)->expire = time_uptime;
5241 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5242 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5244 (*state)->timeout = PFTM_OTHER_SINGLE;
5246 /* translate source/destination address, if necessary */
5247 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5248 struct pf_state_key *nk = (*state)->key[pd->didx];
5250 KASSERT(nk, ("%s: nk is null", __func__));
5251 KASSERT(pd, ("%s: pd is null", __func__));
5252 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5253 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5257 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5258 pf_change_a(&pd->src->v4.s_addr,
5260 nk->addr[pd->sidx].v4.s_addr,
5264 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5265 pf_change_a(&pd->dst->v4.s_addr,
5267 nk->addr[pd->didx].v4.s_addr,
5274 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5275 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5277 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5278 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5286 * ipoff and off are measured from the start of the mbuf chain.
5287 * h must be at "ipoff" on the mbuf chain.
5290 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5291 u_short *actionp, u_short *reasonp, sa_family_t af)
5296 struct ip *h = mtod(m, struct ip *);
5297 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5301 ACTION_SET(actionp, PF_PASS);
5303 ACTION_SET(actionp, PF_DROP);
5304 REASON_SET(reasonp, PFRES_FRAG);
5308 if (m->m_pkthdr.len < off + len ||
5309 ntohs(h->ip_len) < off + len) {
5310 ACTION_SET(actionp, PF_DROP);
5311 REASON_SET(reasonp, PFRES_SHORT);
5319 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5321 if (m->m_pkthdr.len < off + len ||
5322 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5323 (unsigned)(off + len)) {
5324 ACTION_SET(actionp, PF_DROP);
5325 REASON_SET(reasonp, PFRES_SHORT);
5332 m_copydata(m, off, len, p);
5338 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5341 struct radix_node_head *rnh;
5342 struct sockaddr_in *dst;
5346 struct sockaddr_in6 *dst6;
5347 struct route_in6 ro;
5351 struct radix_node *rn;
5356 /* XXX: stick to table 0 for now */
5357 rnh = rt_tables_get_rnh(0, af);
5358 if (rnh != NULL && rn_mpath_capable(rnh))
5360 bzero(&ro, sizeof(ro));
5363 dst = satosin(&ro.ro_dst);
5364 dst->sin_family = AF_INET;
5365 dst->sin_len = sizeof(*dst);
5366 dst->sin_addr = addr->v4;
5371 * Skip check for addresses with embedded interface scope,
5372 * as they would always match anyway.
5374 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5376 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5377 dst6->sin6_family = AF_INET6;
5378 dst6->sin6_len = sizeof(*dst6);
5379 dst6->sin6_addr = addr->v6;
5386 /* Skip checks for ipsec interfaces */
5387 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5393 in6_rtalloc_ign(&ro, 0, rtableid);
5398 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5403 if (ro.ro_rt != NULL) {
5404 /* No interface given, this is a no-route check */
5408 if (kif->pfik_ifp == NULL) {
5413 /* Perform uRPF check if passed input interface */
5415 rn = (struct radix_node *)ro.ro_rt;
5417 rt = (struct rtentry *)rn;
5420 if (kif->pfik_ifp == ifp)
5422 rn = rn_mpath_next(rn);
5423 } while (check_mpath == 1 && rn != NULL && ret == 0);
5427 if (ro.ro_rt != NULL)
5434 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5438 struct nhop4_basic nh4;
5441 struct nhop6_basic nh6;
5445 struct radix_node_head *rnh;
5447 /* XXX: stick to table 0 for now */
5448 rnh = rt_tables_get_rnh(0, af);
5449 if (rnh != NULL && rn_mpath_capable(rnh))
5450 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5453 * Skip check for addresses with embedded interface scope,
5454 * as they would always match anyway.
5456 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5459 if (af != AF_INET && af != AF_INET6)
5462 /* Skip checks for ipsec interfaces */
5463 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5471 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5478 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5485 /* No interface given, this is a no-route check */
5489 if (kif->pfik_ifp == NULL)
5492 /* Perform uRPF check if passed input interface */
5493 if (kif->pfik_ifp == ifp)
5500 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5501 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5503 struct mbuf *m0, *m1;
5504 struct sockaddr_in dst;
5506 struct ifnet *ifp = NULL;
5507 struct pf_addr naddr;
5508 struct pf_src_node *sn = NULL;
5510 uint16_t ip_len, ip_off;
5512 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5513 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5516 if ((pd->pf_mtag == NULL &&
5517 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5518 pd->pf_mtag->routed++ > 3) {
5524 if (r->rt == PF_DUPTO) {
5525 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5531 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5539 ip = mtod(m0, struct ip *);
5541 bzero(&dst, sizeof(dst));
5542 dst.sin_family = AF_INET;
5543 dst.sin_len = sizeof(dst);
5544 dst.sin_addr = ip->ip_dst;
5546 bzero(&naddr, sizeof(naddr));
5548 if (TAILQ_EMPTY(&r->rpool.list)) {
5549 DPFPRINTF(PF_DEBUG_URGENT,
5550 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5554 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5556 if (!PF_AZERO(&naddr, AF_INET))
5557 dst.sin_addr.s_addr = naddr.v4.s_addr;
5558 ifp = r->rpool.cur->kif ?
5559 r->rpool.cur->kif->pfik_ifp : NULL;
5561 if (!PF_AZERO(&s->rt_addr, AF_INET))
5562 dst.sin_addr.s_addr =
5563 s->rt_addr.v4.s_addr;
5564 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5571 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5573 else if (m0 == NULL)
5575 if (m0->m_len < sizeof(struct ip)) {
5576 DPFPRINTF(PF_DEBUG_URGENT,
5577 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5580 ip = mtod(m0, struct ip *);
5583 if (ifp->if_flags & IFF_LOOPBACK)
5584 m0->m_flags |= M_SKIP_FIREWALL;
5586 ip_len = ntohs(ip->ip_len);
5587 ip_off = ntohs(ip->ip_off);
5589 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5590 m0->m_pkthdr.csum_flags |= CSUM_IP;
5591 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5592 in_delayed_cksum(m0);
5593 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5595 #if defined(SCTP) || defined(SCTP_SUPPORT)
5596 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5597 sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
5598 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5603 * If small enough for interface, or the interface will take
5604 * care of the fragmentation for us, we can just send directly.
5606 if (ip_len <= ifp->if_mtu ||
5607 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5609 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5610 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5611 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5613 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5614 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5618 /* Balk when DF bit is set or the interface didn't support TSO. */
5619 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5621 KMOD_IPSTAT_INC(ips_cantfrag);
5622 if (r->rt != PF_DUPTO) {
5623 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5630 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5634 for (; m0; m0 = m1) {
5636 m0->m_nextpkt = NULL;
5638 m_clrprotoflags(m0);
5639 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5645 KMOD_IPSTAT_INC(ips_fragmented);
5648 if (r->rt != PF_DUPTO)
5663 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5664 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5667 struct sockaddr_in6 dst;
5668 struct ip6_hdr *ip6;
5669 struct ifnet *ifp = NULL;
5670 struct pf_addr naddr;
5671 struct pf_src_node *sn = NULL;
5673 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5674 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5677 if ((pd->pf_mtag == NULL &&
5678 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5679 pd->pf_mtag->routed++ > 3) {
5685 if (r->rt == PF_DUPTO) {
5686 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5692 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5700 ip6 = mtod(m0, struct ip6_hdr *);
5702 bzero(&dst, sizeof(dst));
5703 dst.sin6_family = AF_INET6;
5704 dst.sin6_len = sizeof(dst);
5705 dst.sin6_addr = ip6->ip6_dst;
5707 bzero(&naddr, sizeof(naddr));
5709 if (TAILQ_EMPTY(&r->rpool.list)) {
5710 DPFPRINTF(PF_DEBUG_URGENT,
5711 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5715 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5717 if (!PF_AZERO(&naddr, AF_INET6))
5718 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5720 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5722 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5723 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5724 &s->rt_addr, AF_INET6);
5725 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5735 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5737 else if (m0 == NULL)
5739 if (m0->m_len < sizeof(struct ip6_hdr)) {
5740 DPFPRINTF(PF_DEBUG_URGENT,
5741 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5745 ip6 = mtod(m0, struct ip6_hdr *);
5748 if (ifp->if_flags & IFF_LOOPBACK)
5749 m0->m_flags |= M_SKIP_FIREWALL;
5751 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5752 ~ifp->if_hwassist) {
5753 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5754 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5755 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5759 * If the packet is too large for the outgoing interface,
5760 * send back an icmp6 error.
5762 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5763 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5764 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5765 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5767 in6_ifstat_inc(ifp, ifs6_in_toobig);
5768 if (r->rt != PF_DUPTO)
5769 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5775 if (r->rt != PF_DUPTO)
5789 * FreeBSD supports cksum offloads for the following drivers.
5790 * em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5792 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5793 * network driver performed cksum including pseudo header, need to verify
5796 * network driver performed cksum, needs to additional pseudo header
5797 * cksum computation with partial csum_data(i.e. lack of H/W support for
5798 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5800 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5801 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5803 * Also, set csum_data to 0xffff to force cksum validation.
5806 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5812 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5814 if (m->m_pkthdr.len < off + len)
5819 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5820 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5821 sum = m->m_pkthdr.csum_data;
5823 ip = mtod(m, struct ip *);
5824 sum = in_pseudo(ip->ip_src.s_addr,
5825 ip->ip_dst.s_addr, htonl((u_short)len +
5826 m->m_pkthdr.csum_data + IPPROTO_TCP));
5833 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5834 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5835 sum = m->m_pkthdr.csum_data;
5837 ip = mtod(m, struct ip *);
5838 sum = in_pseudo(ip->ip_src.s_addr,
5839 ip->ip_dst.s_addr, htonl((u_short)len +
5840 m->m_pkthdr.csum_data + IPPROTO_UDP));
5848 case IPPROTO_ICMPV6:
5858 if (p == IPPROTO_ICMP) {
5863 sum = in_cksum(m, len);
5867 if (m->m_len < sizeof(struct ip))
5869 sum = in4_cksum(m, p, off, len);
5874 if (m->m_len < sizeof(struct ip6_hdr))
5876 sum = in6_cksum(m, p, off, len);
5887 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5892 KMOD_UDPSTAT_INC(udps_badsum);
5898 KMOD_ICMPSTAT_INC(icps_checksum);
5903 case IPPROTO_ICMPV6:
5905 KMOD_ICMP6STAT_INC(icp6s_checksum);
5912 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5913 m->m_pkthdr.csum_flags |=
5914 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5915 m->m_pkthdr.csum_data = 0xffff;
5924 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5926 struct pfi_kif *kif;
5927 u_short action, reason = 0, log = 0;
5928 struct mbuf *m = *m0;
5929 struct ip *h = NULL;
5930 struct m_tag *ipfwtag;
5931 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5932 struct pf_state *s = NULL;
5933 struct pf_ruleset *ruleset = NULL;
5935 int off, dirndx, pqid = 0;
5937 PF_RULES_RLOCK_TRACKER;
5941 if (!V_pf_status.running)
5944 memset(&pd, 0, sizeof(pd));
5946 kif = (struct pfi_kif *)ifp->if_pf_kif;
5949 DPFPRINTF(PF_DEBUG_URGENT,
5950 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5953 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5956 if (m->m_flags & M_SKIP_FIREWALL)
5959 pd.pf_mtag = pf_find_mtag(m);
5963 if (ip_divert_ptr != NULL &&
5964 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5965 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5966 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5967 if (pd.pf_mtag == NULL &&
5968 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5972 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5973 m_tag_delete(m, ipfwtag);
5975 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5976 m->m_flags |= M_FASTFWD_OURS;
5977 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5979 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5980 /* We do IP header normalization and packet reassembly here */
5984 m = *m0; /* pf_normalize messes with m0 */
5985 h = mtod(m, struct ip *);
5987 off = h->ip_hl << 2;
5988 if (off < (int)sizeof(struct ip)) {
5990 REASON_SET(&reason, PFRES_SHORT);
5995 pd.src = (struct pf_addr *)&h->ip_src;
5996 pd.dst = (struct pf_addr *)&h->ip_dst;
5997 pd.sport = pd.dport = NULL;
5998 pd.ip_sum = &h->ip_sum;
5999 pd.proto_sum = NULL;
6002 pd.sidx = (dir == PF_IN) ? 0 : 1;
6003 pd.didx = (dir == PF_IN) ? 1 : 0;
6005 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
6006 pd.tot_len = ntohs(h->ip_len);
6008 /* handle fragments that didn't get reassembled by normalization */
6009 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
6010 action = pf_test_fragment(&r, dir, kif, m, h,
6021 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6022 &action, &reason, AF_INET)) {
6023 log = action != PF_PASS;
6026 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6027 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6029 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6030 if (action == PF_DROP)
6032 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6034 if (action == PF_PASS) {
6035 if (V_pfsync_update_state_ptr != NULL)
6036 V_pfsync_update_state_ptr(s);
6040 } else if (s == NULL)
6041 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6050 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6051 &action, &reason, AF_INET)) {
6052 log = action != PF_PASS;
6055 if (uh.uh_dport == 0 ||
6056 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6057 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6059 REASON_SET(&reason, PFRES_SHORT);
6062 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6063 if (action == PF_PASS) {
6064 if (V_pfsync_update_state_ptr != NULL)
6065 V_pfsync_update_state_ptr(s);
6069 } else if (s == NULL)
6070 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6075 case IPPROTO_ICMP: {
6079 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6080 &action, &reason, AF_INET)) {
6081 log = action != PF_PASS;
6084 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6086 if (action == PF_PASS) {
6087 if (V_pfsync_update_state_ptr != NULL)
6088 V_pfsync_update_state_ptr(s);
6092 } else if (s == NULL)
6093 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6099 case IPPROTO_ICMPV6: {
6101 DPFPRINTF(PF_DEBUG_MISC,
6102 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6108 action = pf_test_state_other(&s, dir, kif, m, &pd);
6109 if (action == PF_PASS) {
6110 if (V_pfsync_update_state_ptr != NULL)
6111 V_pfsync_update_state_ptr(s);
6115 } else if (s == NULL)
6116 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6123 if (action == PF_PASS && h->ip_hl > 5 &&
6124 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6126 REASON_SET(&reason, PFRES_IPOPTIONS);
6128 DPFPRINTF(PF_DEBUG_MISC,
6129 ("pf: dropping packet with ip options\n"));
6132 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6134 REASON_SET(&reason, PFRES_MEMORY);
6136 if (r->rtableid >= 0)
6137 M_SETFIB(m, r->rtableid);
6139 if (r->scrub_flags & PFSTATE_SETPRIO) {
6140 if (pd.tos & IPTOS_LOWDELAY)
6142 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6144 REASON_SET(&reason, PFRES_MEMORY);
6146 DPFPRINTF(PF_DEBUG_MISC,
6147 ("pf: failed to allocate 802.1q mtag\n"));
6152 if (action == PF_PASS && r->qid) {
6153 if (pd.pf_mtag == NULL &&
6154 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6156 REASON_SET(&reason, PFRES_MEMORY);
6159 pd.pf_mtag->qid_hash = pf_state_hash(s);
6160 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6161 pd.pf_mtag->qid = r->pqid;
6163 pd.pf_mtag->qid = r->qid;
6164 /* Add hints for ecn. */
6165 pd.pf_mtag->hdr = h;
6172 * connections redirected to loopback should not match sockets
6173 * bound specifically to loopback due to security implications,
6174 * see tcp_input() and in_pcblookup_listen().
6176 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6177 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6178 (s->nat_rule.ptr->action == PF_RDR ||
6179 s->nat_rule.ptr->action == PF_BINAT) &&
6180 IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
6181 m->m_flags |= M_SKIP_FIREWALL;
6183 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6184 !PACKET_LOOPED(&pd)) {
6186 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6187 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6188 if (ipfwtag != NULL) {
6189 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6190 ntohs(r->divert.port);
6191 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6196 m_tag_prepend(m, ipfwtag);
6197 if (m->m_flags & M_FASTFWD_OURS) {
6198 if (pd.pf_mtag == NULL &&
6199 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6201 REASON_SET(&reason, PFRES_MEMORY);
6203 DPFPRINTF(PF_DEBUG_MISC,
6204 ("pf: failed to allocate tag\n"));
6206 pd.pf_mtag->flags |=
6207 PF_FASTFWD_OURS_PRESENT;
6208 m->m_flags &= ~M_FASTFWD_OURS;
6211 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6216 /* XXX: ipfw has the same behaviour! */
6218 REASON_SET(&reason, PFRES_MEMORY);
6220 DPFPRINTF(PF_DEBUG_MISC,
6221 ("pf: failed to allocate divert tag\n"));
6228 if (s != NULL && s->nat_rule.ptr != NULL &&
6229 s->nat_rule.ptr->log & PF_LOG_ALL)
6230 lr = s->nat_rule.ptr;
6233 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6237 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6238 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6240 if (action == PF_PASS || r->action == PF_DROP) {
6241 dirndx = (dir == PF_OUT);
6242 r->packets[dirndx]++;
6243 r->bytes[dirndx] += pd.tot_len;
6245 a->packets[dirndx]++;
6246 a->bytes[dirndx] += pd.tot_len;
6249 if (s->nat_rule.ptr != NULL) {
6250 s->nat_rule.ptr->packets[dirndx]++;
6251 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6253 if (s->src_node != NULL) {
6254 s->src_node->packets[dirndx]++;
6255 s->src_node->bytes[dirndx] += pd.tot_len;
6257 if (s->nat_src_node != NULL) {
6258 s->nat_src_node->packets[dirndx]++;
6259 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6261 dirndx = (dir == s->direction) ? 0 : 1;
6262 s->packets[dirndx]++;
6263 s->bytes[dirndx] += pd.tot_len;
6266 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6267 if (nr != NULL && r == &V_pf_default_rule)
6269 if (tr->src.addr.type == PF_ADDR_TABLE)
6270 pfr_update_stats(tr->src.addr.p.tbl,
6271 (s == NULL) ? pd.src :
6272 &s->key[(s->direction == PF_IN)]->
6273 addr[(s->direction == PF_OUT)],
6274 pd.af, pd.tot_len, dir == PF_OUT,
6275 r->action == PF_PASS, tr->src.neg);
6276 if (tr->dst.addr.type == PF_ADDR_TABLE)
6277 pfr_update_stats(tr->dst.addr.p.tbl,
6278 (s == NULL) ? pd.dst :
6279 &s->key[(s->direction == PF_IN)]->
6280 addr[(s->direction == PF_IN)],
6281 pd.af, pd.tot_len, dir == PF_OUT,
6282 r->action == PF_PASS, tr->dst.neg);
6286 case PF_SYNPROXY_DROP:
6297 /* pf_route() returns unlocked. */
6299 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6313 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6315 struct pfi_kif *kif;
6316 u_short action, reason = 0, log = 0;
6317 struct mbuf *m = *m0, *n = NULL;
6319 struct ip6_hdr *h = NULL;
6320 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6321 struct pf_state *s = NULL;
6322 struct pf_ruleset *ruleset = NULL;
6324 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6326 PF_RULES_RLOCK_TRACKER;
6329 if (!V_pf_status.running)
6332 memset(&pd, 0, sizeof(pd));
6333 pd.pf_mtag = pf_find_mtag(m);
6335 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6338 kif = (struct pfi_kif *)ifp->if_pf_kif;
6340 DPFPRINTF(PF_DEBUG_URGENT,
6341 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6344 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6347 if (m->m_flags & M_SKIP_FIREWALL)
6352 /* We do IP header normalization and packet reassembly here */
6353 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6357 m = *m0; /* pf_normalize messes with m0 */
6358 h = mtod(m, struct ip6_hdr *);
6362 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6363 * will do something bad, so drop the packet for now.
6365 if (htons(h->ip6_plen) == 0) {
6367 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6372 pd.src = (struct pf_addr *)&h->ip6_src;
6373 pd.dst = (struct pf_addr *)&h->ip6_dst;
6374 pd.sport = pd.dport = NULL;
6376 pd.proto_sum = NULL;
6378 pd.sidx = (dir == PF_IN) ? 0 : 1;
6379 pd.didx = (dir == PF_IN) ? 1 : 0;
6382 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6384 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6385 pd.proto = h->ip6_nxt;
6388 case IPPROTO_FRAGMENT:
6389 action = pf_test_fragment(&r, dir, kif, m, h,
6391 if (action == PF_DROP)
6392 REASON_SET(&reason, PFRES_FRAG);
6394 case IPPROTO_ROUTING: {
6395 struct ip6_rthdr rthdr;
6398 DPFPRINTF(PF_DEBUG_MISC,
6399 ("pf: IPv6 more than one rthdr\n"));
6401 REASON_SET(&reason, PFRES_IPOPTIONS);
6405 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6407 DPFPRINTF(PF_DEBUG_MISC,
6408 ("pf: IPv6 short rthdr\n"));
6410 REASON_SET(&reason, PFRES_SHORT);
6414 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6415 DPFPRINTF(PF_DEBUG_MISC,
6416 ("pf: IPv6 rthdr0\n"));
6418 REASON_SET(&reason, PFRES_IPOPTIONS);
6425 case IPPROTO_HOPOPTS:
6426 case IPPROTO_DSTOPTS: {
6427 /* get next header and header length */
6428 struct ip6_ext opt6;
6430 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6431 NULL, &reason, pd.af)) {
6432 DPFPRINTF(PF_DEBUG_MISC,
6433 ("pf: IPv6 short opt\n"));
6438 if (pd.proto == IPPROTO_AH)
6439 off += (opt6.ip6e_len + 2) * 4;
6441 off += (opt6.ip6e_len + 1) * 8;
6442 pd.proto = opt6.ip6e_nxt;
6443 /* goto the next header */
6450 } while (!terminal);
6452 /* if there's no routing header, use unmodified mbuf for checksumming */
6462 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6463 &action, &reason, AF_INET6)) {
6464 log = action != PF_PASS;
6467 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6468 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6469 if (action == PF_DROP)
6471 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6473 if (action == PF_PASS) {
6474 if (V_pfsync_update_state_ptr != NULL)
6475 V_pfsync_update_state_ptr(s);
6479 } else if (s == NULL)
6480 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6489 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6490 &action, &reason, AF_INET6)) {
6491 log = action != PF_PASS;
6494 if (uh.uh_dport == 0 ||
6495 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6496 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6498 REASON_SET(&reason, PFRES_SHORT);
6501 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6502 if (action == PF_PASS) {
6503 if (V_pfsync_update_state_ptr != NULL)
6504 V_pfsync_update_state_ptr(s);
6508 } else if (s == NULL)
6509 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6514 case IPPROTO_ICMP: {
6516 DPFPRINTF(PF_DEBUG_MISC,
6517 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6521 case IPPROTO_ICMPV6: {
6522 struct icmp6_hdr ih;
6525 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6526 &action, &reason, AF_INET6)) {
6527 log = action != PF_PASS;
6530 action = pf_test_state_icmp(&s, dir, kif,
6531 m, off, h, &pd, &reason);
6532 if (action == PF_PASS) {
6533 if (V_pfsync_update_state_ptr != NULL)
6534 V_pfsync_update_state_ptr(s);
6538 } else if (s == NULL)
6539 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6545 action = pf_test_state_other(&s, dir, kif, m, &pd);
6546 if (action == PF_PASS) {
6547 if (V_pfsync_update_state_ptr != NULL)
6548 V_pfsync_update_state_ptr(s);
6552 } else if (s == NULL)
6553 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6565 /* handle dangerous IPv6 extension headers. */
6566 if (action == PF_PASS && rh_cnt &&
6567 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6569 REASON_SET(&reason, PFRES_IPOPTIONS);
6571 DPFPRINTF(PF_DEBUG_MISC,
6572 ("pf: dropping packet with dangerous v6 headers\n"));
6575 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6577 REASON_SET(&reason, PFRES_MEMORY);
6579 if (r->rtableid >= 0)
6580 M_SETFIB(m, r->rtableid);
6582 if (r->scrub_flags & PFSTATE_SETPRIO) {
6583 if (pd.tos & IPTOS_LOWDELAY)
6585 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6587 REASON_SET(&reason, PFRES_MEMORY);
6589 DPFPRINTF(PF_DEBUG_MISC,
6590 ("pf: failed to allocate 802.1q mtag\n"));
6595 if (action == PF_PASS && r->qid) {
6596 if (pd.pf_mtag == NULL &&
6597 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6599 REASON_SET(&reason, PFRES_MEMORY);
6602 pd.pf_mtag->qid_hash = pf_state_hash(s);
6603 if (pd.tos & IPTOS_LOWDELAY)
6604 pd.pf_mtag->qid = r->pqid;
6606 pd.pf_mtag->qid = r->qid;
6607 /* Add hints for ecn. */
6608 pd.pf_mtag->hdr = h;
6613 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6614 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6615 (s->nat_rule.ptr->action == PF_RDR ||
6616 s->nat_rule.ptr->action == PF_BINAT) &&
6617 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6618 m->m_flags |= M_SKIP_FIREWALL;
6620 /* XXX: Anybody working on it?! */
6622 printf("pf: divert(9) is not supported for IPv6\n");
6627 if (s != NULL && s->nat_rule.ptr != NULL &&
6628 s->nat_rule.ptr->log & PF_LOG_ALL)
6629 lr = s->nat_rule.ptr;
6632 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6636 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6637 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6639 if (action == PF_PASS || r->action == PF_DROP) {
6640 dirndx = (dir == PF_OUT);
6641 r->packets[dirndx]++;
6642 r->bytes[dirndx] += pd.tot_len;
6644 a->packets[dirndx]++;
6645 a->bytes[dirndx] += pd.tot_len;
6648 if (s->nat_rule.ptr != NULL) {
6649 s->nat_rule.ptr->packets[dirndx]++;
6650 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6652 if (s->src_node != NULL) {
6653 s->src_node->packets[dirndx]++;
6654 s->src_node->bytes[dirndx] += pd.tot_len;
6656 if (s->nat_src_node != NULL) {
6657 s->nat_src_node->packets[dirndx]++;
6658 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6660 dirndx = (dir == s->direction) ? 0 : 1;
6661 s->packets[dirndx]++;
6662 s->bytes[dirndx] += pd.tot_len;
6665 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6666 if (nr != NULL && r == &V_pf_default_rule)
6668 if (tr->src.addr.type == PF_ADDR_TABLE)
6669 pfr_update_stats(tr->src.addr.p.tbl,
6670 (s == NULL) ? pd.src :
6671 &s->key[(s->direction == PF_IN)]->addr[0],
6672 pd.af, pd.tot_len, dir == PF_OUT,
6673 r->action == PF_PASS, tr->src.neg);
6674 if (tr->dst.addr.type == PF_ADDR_TABLE)
6675 pfr_update_stats(tr->dst.addr.p.tbl,
6676 (s == NULL) ? pd.dst :
6677 &s->key[(s->direction == PF_IN)]->addr[1],
6678 pd.af, pd.tot_len, dir == PF_OUT,
6679 r->action == PF_PASS, tr->dst.neg);
6683 case PF_SYNPROXY_DROP:
6694 /* pf_route6() returns unlocked. */
6696 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6705 /* If reassembled packet passed, create new fragments. */
6706 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6707 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6708 action = pf_refragment6(ifp, m0, mtag);