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$");
44 #include "opt_inet6.h"
49 #include <sys/param.h>
51 #include <sys/endian.h>
52 #include <sys/gsb_crc32.h>
54 #include <sys/interrupt.h>
55 #include <sys/kernel.h>
56 #include <sys/kthread.h>
57 #include <sys/limits.h>
60 #include <sys/random.h>
61 #include <sys/refcount.h>
62 #include <sys/socket.h>
63 #include <sys/sysctl.h>
64 #include <sys/taskqueue.h>
65 #include <sys/ucred.h>
68 #include <net/if_var.h>
69 #include <net/if_types.h>
70 #include <net/if_vlan_var.h>
71 #include <net/route.h>
72 #include <net/radix_mpath.h>
76 #include <net/pfvar.h>
77 #include <net/if_pflog.h>
78 #include <net/if_pfsync.h>
80 #include <netinet/in_pcb.h>
81 #include <netinet/in_var.h>
82 #include <netinet/in_fib.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_fw.h>
85 #include <netinet/ip_icmp.h>
86 #include <netinet/icmp_var.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/udp.h>
94 #include <netinet/udp_var.h>
97 #include <netinet/ip6.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/nd6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/in6_pcb.h>
102 #include <netinet6/in6_fib.h>
103 #include <netinet6/scope6_var.h>
107 #include <netinet/sctp_crc32.h>
110 #include <machine/in_cksum.h>
111 #include <security/mac/mac_framework.h>
113 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
120 VNET_DEFINE(struct pf_altqqueue, pf_altqs[4]);
121 VNET_DEFINE(struct pf_palist, pf_pabuf);
122 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
123 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_active);
124 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
125 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_inactive);
126 VNET_DEFINE(struct pf_kstatus, pf_status);
128 VNET_DEFINE(u_int32_t, ticket_altqs_active);
129 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
130 VNET_DEFINE(int, altqs_inactive_open);
131 VNET_DEFINE(u_int32_t, ticket_pabuf);
133 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
134 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
135 VNET_DEFINE(u_char, pf_tcp_secret[16]);
136 #define V_pf_tcp_secret VNET(pf_tcp_secret)
137 VNET_DEFINE(int, pf_tcp_secret_init);
138 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
139 VNET_DEFINE(int, pf_tcp_iss_off);
140 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
141 VNET_DECLARE(int, pf_vnet_active);
142 #define V_pf_vnet_active VNET(pf_vnet_active)
144 VNET_DEFINE_STATIC(uint32_t, pf_purge_idx);
145 #define V_pf_purge_idx VNET(pf_purge_idx)
148 * Queue for pf_intr() sends.
150 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
151 struct pf_send_entry {
152 STAILQ_ENTRY(pf_send_entry) pfse_next;
167 STAILQ_HEAD(pf_send_head, pf_send_entry);
168 VNET_DEFINE_STATIC(struct pf_send_head, pf_sendqueue);
169 #define V_pf_sendqueue VNET(pf_sendqueue)
171 static struct mtx pf_sendqueue_mtx;
172 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
173 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
174 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
177 * Queue for pf_overload_task() tasks.
179 struct pf_overload_entry {
180 SLIST_ENTRY(pf_overload_entry) next;
184 struct pf_rule *rule;
187 SLIST_HEAD(pf_overload_head, pf_overload_entry);
188 VNET_DEFINE_STATIC(struct pf_overload_head, pf_overloadqueue);
189 #define V_pf_overloadqueue VNET(pf_overloadqueue)
190 VNET_DEFINE_STATIC(struct task, pf_overloadtask);
191 #define V_pf_overloadtask VNET(pf_overloadtask)
193 static struct mtx pf_overloadqueue_mtx;
194 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
195 "pf overload/flush queue", MTX_DEF);
196 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
197 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
199 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
200 struct mtx pf_unlnkdrules_mtx;
201 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
204 VNET_DEFINE_STATIC(uma_zone_t, pf_sources_z);
205 #define V_pf_sources_z VNET(pf_sources_z)
206 uma_zone_t pf_mtag_z;
207 VNET_DEFINE(uma_zone_t, pf_state_z);
208 VNET_DEFINE(uma_zone_t, pf_state_key_z);
210 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
211 #define PFID_CPUBITS 8
212 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
213 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
214 #define PFID_MAXID (~PFID_CPUMASK)
215 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
217 static void pf_src_tree_remove_state(struct pf_state *);
218 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
220 static void pf_add_threshold(struct pf_threshold *);
221 static int pf_check_threshold(struct pf_threshold *);
223 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
224 u_int16_t *, u_int16_t *, struct pf_addr *,
225 u_int16_t, u_int8_t, sa_family_t);
226 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
227 struct tcphdr *, struct pf_state_peer *);
228 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
229 struct pf_addr *, struct pf_addr *, u_int16_t,
230 u_int16_t *, u_int16_t *, u_int16_t *,
231 u_int16_t *, u_int8_t, sa_family_t);
232 static void pf_send_tcp(struct mbuf *,
233 const struct pf_rule *, sa_family_t,
234 const struct pf_addr *, const struct pf_addr *,
235 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
236 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
237 u_int16_t, struct ifnet *);
238 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
239 sa_family_t, struct pf_rule *);
240 static void pf_detach_state(struct pf_state *);
241 static int pf_state_key_attach(struct pf_state_key *,
242 struct pf_state_key *, struct pf_state *);
243 static void pf_state_key_detach(struct pf_state *, int);
244 static int pf_state_key_ctor(void *, int, void *, int);
245 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
246 static int pf_test_rule(struct pf_rule **, struct pf_state **,
247 int, struct pfi_kif *, struct mbuf *, int,
248 struct pf_pdesc *, struct pf_rule **,
249 struct pf_ruleset **, struct inpcb *);
250 static int pf_create_state(struct pf_rule *, struct pf_rule *,
251 struct pf_rule *, struct pf_pdesc *,
252 struct pf_src_node *, struct pf_state_key *,
253 struct pf_state_key *, struct mbuf *, int,
254 u_int16_t, u_int16_t, int *, struct pfi_kif *,
255 struct pf_state **, int, u_int16_t, u_int16_t,
257 static int pf_test_fragment(struct pf_rule **, int,
258 struct pfi_kif *, struct mbuf *, void *,
259 struct pf_pdesc *, struct pf_rule **,
260 struct pf_ruleset **);
261 static int pf_tcp_track_full(struct pf_state_peer *,
262 struct pf_state_peer *, struct pf_state **,
263 struct pfi_kif *, struct mbuf *, int,
264 struct pf_pdesc *, u_short *, int *);
265 static int pf_tcp_track_sloppy(struct pf_state_peer *,
266 struct pf_state_peer *, struct pf_state **,
267 struct pf_pdesc *, u_short *);
268 static int pf_test_state_tcp(struct pf_state **, int,
269 struct pfi_kif *, struct mbuf *, int,
270 void *, struct pf_pdesc *, u_short *);
271 static int pf_test_state_udp(struct pf_state **, int,
272 struct pfi_kif *, struct mbuf *, int,
273 void *, struct pf_pdesc *);
274 static int pf_test_state_icmp(struct pf_state **, int,
275 struct pfi_kif *, struct mbuf *, int,
276 void *, struct pf_pdesc *, u_short *);
277 static int pf_test_state_other(struct pf_state **, int,
278 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
279 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
281 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
283 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
285 static int pf_check_proto_cksum(struct mbuf *, int, int,
286 u_int8_t, sa_family_t);
287 static void pf_print_state_parts(struct pf_state *,
288 struct pf_state_key *, struct pf_state_key *);
289 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
290 struct pf_addr_wrap *);
291 static struct pf_state *pf_find_state(struct pfi_kif *,
292 struct pf_state_key_cmp *, u_int);
293 static int pf_src_connlimit(struct pf_state **);
294 static void pf_overload_task(void *v, int pending);
295 static int pf_insert_src_node(struct pf_src_node **,
296 struct pf_rule *, struct pf_addr *, sa_family_t);
297 static u_int pf_purge_expired_states(u_int, int);
298 static void pf_purge_unlinked_rules(void);
299 static int pf_mtag_uminit(void *, int, int);
300 static void pf_mtag_free(struct m_tag *);
302 static void pf_route(struct mbuf **, struct pf_rule *, int,
303 struct ifnet *, struct pf_state *,
304 struct pf_pdesc *, struct inpcb *);
307 static void pf_change_a6(struct pf_addr *, u_int16_t *,
308 struct pf_addr *, u_int8_t);
309 static void pf_route6(struct mbuf **, struct pf_rule *, int,
310 struct ifnet *, struct pf_state *,
311 struct pf_pdesc *, struct inpcb *);
314 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
316 extern int pf_end_threads;
317 extern struct proc *pf_purge_proc;
319 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
321 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
322 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
324 #define STATE_LOOKUP(i, k, d, s, pd) \
326 (s) = pf_find_state((i), (k), (d)); \
329 if (PACKET_LOOPED(pd)) \
331 if ((d) == PF_OUT && \
332 (((s)->rule.ptr->rt == PF_ROUTETO && \
333 (s)->rule.ptr->direction == PF_OUT) || \
334 ((s)->rule.ptr->rt == PF_REPLYTO && \
335 (s)->rule.ptr->direction == PF_IN)) && \
336 (s)->rt_kif != NULL && \
337 (s)->rt_kif != (i)) \
341 #define BOUND_IFACE(r, k) \
342 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
344 #define STATE_INC_COUNTERS(s) \
346 counter_u64_add(s->rule.ptr->states_cur, 1); \
347 counter_u64_add(s->rule.ptr->states_tot, 1); \
348 if (s->anchor.ptr != NULL) { \
349 counter_u64_add(s->anchor.ptr->states_cur, 1); \
350 counter_u64_add(s->anchor.ptr->states_tot, 1); \
352 if (s->nat_rule.ptr != NULL) { \
353 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
354 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
358 #define STATE_DEC_COUNTERS(s) \
360 if (s->nat_rule.ptr != NULL) \
361 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
362 if (s->anchor.ptr != NULL) \
363 counter_u64_add(s->anchor.ptr->states_cur, -1); \
364 counter_u64_add(s->rule.ptr->states_cur, -1); \
367 MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
368 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
369 VNET_DEFINE(struct pf_idhash *, pf_idhash);
370 VNET_DEFINE(struct pf_srchash *, pf_srchash);
372 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
375 u_long pf_srchashmask;
376 static u_long pf_hashsize;
377 static u_long pf_srchashsize;
378 u_long pf_ioctl_maxcount = 65535;
380 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
381 &pf_hashsize, 0, "Size of pf(4) states hashtable");
382 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
383 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
384 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RW,
385 &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
387 VNET_DEFINE(void *, pf_swi_cookie);
389 VNET_DEFINE(uint32_t, pf_hashseed);
390 #define V_pf_hashseed VNET(pf_hashseed)
393 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
399 if (a->addr32[0] > b->addr32[0])
401 if (a->addr32[0] < b->addr32[0])
407 if (a->addr32[3] > b->addr32[3])
409 if (a->addr32[3] < b->addr32[3])
411 if (a->addr32[2] > b->addr32[2])
413 if (a->addr32[2] < b->addr32[2])
415 if (a->addr32[1] > b->addr32[1])
417 if (a->addr32[1] < b->addr32[1])
419 if (a->addr32[0] > b->addr32[0])
421 if (a->addr32[0] < b->addr32[0])
426 panic("%s: unknown address family %u", __func__, af);
431 static __inline uint32_t
432 pf_hashkey(struct pf_state_key *sk)
436 h = murmur3_32_hash32((uint32_t *)sk,
437 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
440 return (h & pf_hashmask);
443 static __inline uint32_t
444 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
450 h = murmur3_32_hash32((uint32_t *)&addr->v4,
451 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
454 h = murmur3_32_hash32((uint32_t *)&addr->v6,
455 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
458 panic("%s: unknown address family %u", __func__, af);
461 return (h & pf_srchashmask);
466 pf_state_hash(struct pf_state *s)
468 u_int32_t hv = (intptr_t)s / sizeof(*s);
470 hv ^= crc32(&s->src, sizeof(s->src));
471 hv ^= crc32(&s->dst, sizeof(s->dst));
480 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
485 dst->addr32[0] = src->addr32[0];
489 dst->addr32[0] = src->addr32[0];
490 dst->addr32[1] = src->addr32[1];
491 dst->addr32[2] = src->addr32[2];
492 dst->addr32[3] = src->addr32[3];
499 pf_init_threshold(struct pf_threshold *threshold,
500 u_int32_t limit, u_int32_t seconds)
502 threshold->limit = limit * PF_THRESHOLD_MULT;
503 threshold->seconds = seconds;
504 threshold->count = 0;
505 threshold->last = time_uptime;
509 pf_add_threshold(struct pf_threshold *threshold)
511 u_int32_t t = time_uptime, diff = t - threshold->last;
513 if (diff >= threshold->seconds)
514 threshold->count = 0;
516 threshold->count -= threshold->count * diff /
518 threshold->count += PF_THRESHOLD_MULT;
523 pf_check_threshold(struct pf_threshold *threshold)
525 return (threshold->count > threshold->limit);
529 pf_src_connlimit(struct pf_state **state)
531 struct pf_overload_entry *pfoe;
534 PF_STATE_LOCK_ASSERT(*state);
536 (*state)->src_node->conn++;
537 (*state)->src.tcp_est = 1;
538 pf_add_threshold(&(*state)->src_node->conn_rate);
540 if ((*state)->rule.ptr->max_src_conn &&
541 (*state)->rule.ptr->max_src_conn <
542 (*state)->src_node->conn) {
543 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
547 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
548 pf_check_threshold(&(*state)->src_node->conn_rate)) {
549 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
556 /* Kill this state. */
557 (*state)->timeout = PFTM_PURGE;
558 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
560 if ((*state)->rule.ptr->overload_tbl == NULL)
563 /* Schedule overloading and flushing task. */
564 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
566 return (1); /* too bad :( */
568 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
569 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
570 pfoe->rule = (*state)->rule.ptr;
571 pfoe->dir = (*state)->direction;
573 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
574 PF_OVERLOADQ_UNLOCK();
575 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
581 pf_overload_task(void *v, int pending)
583 struct pf_overload_head queue;
585 struct pf_overload_entry *pfoe, *pfoe1;
588 CURVNET_SET((struct vnet *)v);
591 queue = V_pf_overloadqueue;
592 SLIST_INIT(&V_pf_overloadqueue);
593 PF_OVERLOADQ_UNLOCK();
595 bzero(&p, sizeof(p));
596 SLIST_FOREACH(pfoe, &queue, next) {
597 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
598 if (V_pf_status.debug >= PF_DEBUG_MISC) {
599 printf("%s: blocking address ", __func__);
600 pf_print_host(&pfoe->addr, 0, pfoe->af);
604 p.pfra_af = pfoe->af;
609 p.pfra_ip4addr = pfoe->addr.v4;
615 p.pfra_ip6addr = pfoe->addr.v6;
621 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
626 * Remove those entries, that don't need flushing.
628 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
629 if (pfoe->rule->flush == 0) {
630 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
631 free(pfoe, M_PFTEMP);
634 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
636 /* If nothing to flush, return. */
637 if (SLIST_EMPTY(&queue)) {
642 for (int i = 0; i <= pf_hashmask; i++) {
643 struct pf_idhash *ih = &V_pf_idhash[i];
644 struct pf_state_key *sk;
648 LIST_FOREACH(s, &ih->states, entry) {
649 sk = s->key[PF_SK_WIRE];
650 SLIST_FOREACH(pfoe, &queue, next)
651 if (sk->af == pfoe->af &&
652 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
653 pfoe->rule == s->rule.ptr) &&
654 ((pfoe->dir == PF_OUT &&
655 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
656 (pfoe->dir == PF_IN &&
657 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
658 s->timeout = PFTM_PURGE;
659 s->src.state = s->dst.state = TCPS_CLOSED;
663 PF_HASHROW_UNLOCK(ih);
665 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
666 free(pfoe, M_PFTEMP);
667 if (V_pf_status.debug >= PF_DEBUG_MISC)
668 printf("%s: %u states killed", __func__, killed);
674 * Can return locked on failure, so that we can consistently
675 * allocate and insert a new one.
678 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
681 struct pf_srchash *sh;
682 struct pf_src_node *n;
684 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
686 sh = &V_pf_srchash[pf_hashsrc(src, af)];
688 LIST_FOREACH(n, &sh->nodes, entry)
689 if (n->rule.ptr == rule && n->af == af &&
690 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
691 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
695 PF_HASHROW_UNLOCK(sh);
696 } else if (returnlocked == 0)
697 PF_HASHROW_UNLOCK(sh);
703 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
704 struct pf_addr *src, sa_family_t af)
707 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
708 rule->rpool.opts & PF_POOL_STICKYADDR),
709 ("%s for non-tracking rule %p", __func__, rule));
712 *sn = pf_find_src_node(src, rule, af, 1);
715 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
717 PF_HASHROW_ASSERT(sh);
719 if (!rule->max_src_nodes ||
720 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
721 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
723 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
726 PF_HASHROW_UNLOCK(sh);
730 pf_init_threshold(&(*sn)->conn_rate,
731 rule->max_src_conn_rate.limit,
732 rule->max_src_conn_rate.seconds);
735 (*sn)->rule.ptr = rule;
736 PF_ACPY(&(*sn)->addr, src, af);
737 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
738 (*sn)->creation = time_uptime;
739 (*sn)->ruletype = rule->action;
741 if ((*sn)->rule.ptr != NULL)
742 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
743 PF_HASHROW_UNLOCK(sh);
744 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
746 if (rule->max_src_states &&
747 (*sn)->states >= rule->max_src_states) {
748 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
757 pf_unlink_src_node(struct pf_src_node *src)
760 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
761 LIST_REMOVE(src, entry);
763 counter_u64_add(src->rule.ptr->src_nodes, -1);
767 pf_free_src_nodes(struct pf_src_node_list *head)
769 struct pf_src_node *sn, *tmp;
772 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
773 uma_zfree(V_pf_sources_z, sn);
777 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
786 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
787 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
791 /* Per-vnet data storage structures initialization. */
795 struct pf_keyhash *kh;
796 struct pf_idhash *ih;
797 struct pf_srchash *sh;
800 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
801 pf_hashsize = PF_HASHSIZ;
802 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
803 pf_srchashsize = PF_SRCHASHSIZ;
805 V_pf_hashseed = arc4random();
807 /* States and state keys storage. */
808 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
809 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
810 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
811 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
812 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
814 V_pf_state_key_z = uma_zcreate("pf state keys",
815 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
818 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
819 M_PFHASH, M_NOWAIT | M_ZERO);
820 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
821 M_PFHASH, M_NOWAIT | M_ZERO);
822 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
823 printf("pf: Unable to allocate memory for "
824 "state_hashsize %lu.\n", pf_hashsize);
826 free(V_pf_keyhash, M_PFHASH);
827 free(V_pf_idhash, M_PFHASH);
829 pf_hashsize = PF_HASHSIZ;
830 V_pf_keyhash = mallocarray(pf_hashsize,
831 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
832 V_pf_idhash = mallocarray(pf_hashsize,
833 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
836 pf_hashmask = pf_hashsize - 1;
837 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
839 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
840 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
844 V_pf_sources_z = uma_zcreate("pf source nodes",
845 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
847 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
848 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
849 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
851 V_pf_srchash = mallocarray(pf_srchashsize,
852 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
853 if (V_pf_srchash == NULL) {
854 printf("pf: Unable to allocate memory for "
855 "source_hashsize %lu.\n", pf_srchashsize);
857 pf_srchashsize = PF_SRCHASHSIZ;
858 V_pf_srchash = mallocarray(pf_srchashsize,
859 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
862 pf_srchashmask = pf_srchashsize - 1;
863 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
864 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
867 TAILQ_INIT(&V_pf_altqs[0]);
868 TAILQ_INIT(&V_pf_altqs[1]);
869 TAILQ_INIT(&V_pf_altqs[2]);
870 TAILQ_INIT(&V_pf_altqs[3]);
871 TAILQ_INIT(&V_pf_pabuf);
872 V_pf_altqs_active = &V_pf_altqs[0];
873 V_pf_altq_ifs_active = &V_pf_altqs[1];
874 V_pf_altqs_inactive = &V_pf_altqs[2];
875 V_pf_altq_ifs_inactive = &V_pf_altqs[3];
877 /* Send & overload+flush queues. */
878 STAILQ_INIT(&V_pf_sendqueue);
879 SLIST_INIT(&V_pf_overloadqueue);
880 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
882 /* Unlinked, but may be referenced rules. */
883 TAILQ_INIT(&V_pf_unlinked_rules);
890 uma_zdestroy(pf_mtag_z);
896 struct pf_keyhash *kh;
897 struct pf_idhash *ih;
898 struct pf_srchash *sh;
899 struct pf_send_entry *pfse, *next;
902 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
904 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
906 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
908 mtx_destroy(&kh->lock);
909 mtx_destroy(&ih->lock);
911 free(V_pf_keyhash, M_PFHASH);
912 free(V_pf_idhash, M_PFHASH);
914 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
915 KASSERT(LIST_EMPTY(&sh->nodes),
916 ("%s: source node hash not empty", __func__));
917 mtx_destroy(&sh->lock);
919 free(V_pf_srchash, M_PFHASH);
921 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
922 m_freem(pfse->pfse_m);
923 free(pfse, M_PFTEMP);
926 uma_zdestroy(V_pf_sources_z);
927 uma_zdestroy(V_pf_state_z);
928 uma_zdestroy(V_pf_state_key_z);
932 pf_mtag_uminit(void *mem, int size, int how)
936 t = (struct m_tag *)mem;
937 t->m_tag_cookie = MTAG_ABI_COMPAT;
938 t->m_tag_id = PACKET_TAG_PF;
939 t->m_tag_len = sizeof(struct pf_mtag);
940 t->m_tag_free = pf_mtag_free;
946 pf_mtag_free(struct m_tag *t)
949 uma_zfree(pf_mtag_z, t);
953 pf_get_mtag(struct mbuf *m)
957 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
958 return ((struct pf_mtag *)(mtag + 1));
960 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
963 bzero(mtag + 1, sizeof(struct pf_mtag));
964 m_tag_prepend(m, mtag);
966 return ((struct pf_mtag *)(mtag + 1));
970 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
973 struct pf_keyhash *khs, *khw, *kh;
974 struct pf_state_key *sk, *cur;
975 struct pf_state *si, *olds = NULL;
978 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
979 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
980 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
983 * We need to lock hash slots of both keys. To avoid deadlock
984 * we always lock the slot with lower address first. Unlock order
987 * We also need to lock ID hash slot before dropping key
988 * locks. On success we return with ID hash slot locked.
992 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
993 PF_HASHROW_LOCK(khs);
995 khs = &V_pf_keyhash[pf_hashkey(sks)];
996 khw = &V_pf_keyhash[pf_hashkey(skw)];
998 PF_HASHROW_LOCK(khs);
999 } else if (khs < khw) {
1000 PF_HASHROW_LOCK(khs);
1001 PF_HASHROW_LOCK(khw);
1003 PF_HASHROW_LOCK(khw);
1004 PF_HASHROW_LOCK(khs);
1008 #define KEYS_UNLOCK() do { \
1010 PF_HASHROW_UNLOCK(khs); \
1011 PF_HASHROW_UNLOCK(khw); \
1013 PF_HASHROW_UNLOCK(khs); \
1017 * First run: start with wire key.
1024 LIST_FOREACH(cur, &kh->keys, entry)
1025 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1029 /* Key exists. Check for same kif, if none, add to key. */
1030 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1031 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1033 PF_HASHROW_LOCK(ih);
1034 if (si->kif == s->kif &&
1035 si->direction == s->direction) {
1036 if (sk->proto == IPPROTO_TCP &&
1037 si->src.state >= TCPS_FIN_WAIT_2 &&
1038 si->dst.state >= TCPS_FIN_WAIT_2) {
1040 * New state matches an old >FIN_WAIT_2
1041 * state. We can't drop key hash locks,
1042 * thus we can't unlink it properly.
1044 * As a workaround we drop it into
1045 * TCPS_CLOSED state, schedule purge
1046 * ASAP and push it into the very end
1047 * of the slot TAILQ, so that it won't
1048 * conflict with our new state.
1050 si->src.state = si->dst.state =
1052 si->timeout = PFTM_PURGE;
1055 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1056 printf("pf: %s key attach "
1058 (idx == PF_SK_WIRE) ?
1061 pf_print_state_parts(s,
1062 (idx == PF_SK_WIRE) ?
1064 (idx == PF_SK_STACK) ?
1066 printf(", existing: ");
1067 pf_print_state_parts(si,
1068 (idx == PF_SK_WIRE) ?
1070 (idx == PF_SK_STACK) ?
1074 PF_HASHROW_UNLOCK(ih);
1076 uma_zfree(V_pf_state_key_z, sk);
1077 if (idx == PF_SK_STACK)
1079 return (EEXIST); /* collision! */
1082 PF_HASHROW_UNLOCK(ih);
1084 uma_zfree(V_pf_state_key_z, sk);
1087 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1092 /* List is sorted, if-bound states before floating. */
1093 if (s->kif == V_pfi_all)
1094 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1096 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1099 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1100 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1106 * Attach done. See how should we (or should not?)
1107 * attach a second key.
1110 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1114 } else if (sks != NULL) {
1116 * Continue attaching with stack key.
1128 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1129 ("%s failure", __func__));
1136 pf_detach_state(struct pf_state *s)
1138 struct pf_state_key *sks = s->key[PF_SK_STACK];
1139 struct pf_keyhash *kh;
1142 kh = &V_pf_keyhash[pf_hashkey(sks)];
1143 PF_HASHROW_LOCK(kh);
1144 if (s->key[PF_SK_STACK] != NULL)
1145 pf_state_key_detach(s, PF_SK_STACK);
1147 * If both point to same key, then we are done.
1149 if (sks == s->key[PF_SK_WIRE]) {
1150 pf_state_key_detach(s, PF_SK_WIRE);
1151 PF_HASHROW_UNLOCK(kh);
1154 PF_HASHROW_UNLOCK(kh);
1157 if (s->key[PF_SK_WIRE] != NULL) {
1158 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1159 PF_HASHROW_LOCK(kh);
1160 if (s->key[PF_SK_WIRE] != NULL)
1161 pf_state_key_detach(s, PF_SK_WIRE);
1162 PF_HASHROW_UNLOCK(kh);
1167 pf_state_key_detach(struct pf_state *s, int idx)
1169 struct pf_state_key *sk = s->key[idx];
1171 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1173 PF_HASHROW_ASSERT(kh);
1175 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1178 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1179 LIST_REMOVE(sk, entry);
1180 uma_zfree(V_pf_state_key_z, sk);
1185 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1187 struct pf_state_key *sk = mem;
1189 bzero(sk, sizeof(struct pf_state_key_cmp));
1190 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1191 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1196 struct pf_state_key *
1197 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1198 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1200 struct pf_state_key *sk;
1202 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1206 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1207 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1208 sk->port[pd->sidx] = sport;
1209 sk->port[pd->didx] = dport;
1210 sk->proto = pd->proto;
1216 struct pf_state_key *
1217 pf_state_key_clone(struct pf_state_key *orig)
1219 struct pf_state_key *sk;
1221 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1225 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1231 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1232 struct pf_state_key *sks, struct pf_state *s)
1234 struct pf_idhash *ih;
1235 struct pf_state *cur;
1238 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1239 ("%s: sks not pristine", __func__));
1240 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1241 ("%s: skw not pristine", __func__));
1242 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1246 if (s->id == 0 && s->creatorid == 0) {
1247 /* XXX: should be atomic, but probability of collision low */
1248 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1249 V_pf_stateid[curcpu] = 1;
1250 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1251 s->id = htobe64(s->id);
1252 s->creatorid = V_pf_status.hostid;
1255 /* Returns with ID locked on success. */
1256 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1259 ih = &V_pf_idhash[PF_IDHASH(s)];
1260 PF_HASHROW_ASSERT(ih);
1261 LIST_FOREACH(cur, &ih->states, entry)
1262 if (cur->id == s->id && cur->creatorid == s->creatorid)
1266 PF_HASHROW_UNLOCK(ih);
1267 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1268 printf("pf: state ID collision: "
1269 "id: %016llx creatorid: %08x\n",
1270 (unsigned long long)be64toh(s->id),
1271 ntohl(s->creatorid));
1276 LIST_INSERT_HEAD(&ih->states, s, entry);
1277 /* One for keys, one for ID hash. */
1278 refcount_init(&s->refs, 2);
1280 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1281 if (V_pfsync_insert_state_ptr != NULL)
1282 V_pfsync_insert_state_ptr(s);
1284 /* Returns locked. */
1289 * Find state by ID: returns with locked row on success.
1292 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1294 struct pf_idhash *ih;
1297 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1299 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1301 PF_HASHROW_LOCK(ih);
1302 LIST_FOREACH(s, &ih->states, entry)
1303 if (s->id == id && s->creatorid == creatorid)
1307 PF_HASHROW_UNLOCK(ih);
1313 * Find state by key.
1314 * Returns with ID hash slot locked on success.
1316 static struct pf_state *
1317 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1319 struct pf_keyhash *kh;
1320 struct pf_state_key *sk;
1324 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1326 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1328 PF_HASHROW_LOCK(kh);
1329 LIST_FOREACH(sk, &kh->keys, entry)
1330 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1333 PF_HASHROW_UNLOCK(kh);
1337 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1339 /* List is sorted, if-bound states before floating ones. */
1340 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1341 if (s->kif == V_pfi_all || s->kif == kif) {
1343 PF_HASHROW_UNLOCK(kh);
1344 if (s->timeout >= PFTM_MAX) {
1346 * State is either being processed by
1347 * pf_unlink_state() in an other thread, or
1348 * is scheduled for immediate expiry.
1355 PF_HASHROW_UNLOCK(kh);
1361 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1363 struct pf_keyhash *kh;
1364 struct pf_state_key *sk;
1365 struct pf_state *s, *ret = NULL;
1368 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1370 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1372 PF_HASHROW_LOCK(kh);
1373 LIST_FOREACH(sk, &kh->keys, entry)
1374 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1377 PF_HASHROW_UNLOCK(kh);
1392 panic("%s: dir %u", __func__, dir);
1395 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1397 PF_HASHROW_UNLOCK(kh);
1411 PF_HASHROW_UNLOCK(kh);
1416 /* END state table stuff */
1419 pf_send(struct pf_send_entry *pfse)
1423 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1425 swi_sched(V_pf_swi_cookie, 0);
1431 struct epoch_tracker et;
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 NET_EPOCH_ENTER(et);
1444 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1445 switch (pfse->pfse_type) {
1448 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1451 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1452 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1457 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1461 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1462 pfse->icmpopts.code, pfse->icmpopts.mtu);
1466 panic("%s: unknown type", __func__);
1468 free(pfse, M_PFTEMP);
1475 pf_purge_thread(void *unused __unused)
1477 VNET_ITERATOR_DECL(vnet_iter);
1479 sx_xlock(&pf_end_lock);
1480 while (pf_end_threads == 0) {
1481 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1484 VNET_FOREACH(vnet_iter) {
1485 CURVNET_SET(vnet_iter);
1488 /* Wait until V_pf_default_rule is initialized. */
1489 if (V_pf_vnet_active == 0) {
1495 * Process 1/interval fraction of the state
1499 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1500 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1503 * Purge other expired types every
1504 * PFTM_INTERVAL seconds.
1506 if (V_pf_purge_idx == 0) {
1508 * Order is important:
1509 * - states and src nodes reference rules
1510 * - states and rules reference kifs
1512 pf_purge_expired_fragments();
1513 pf_purge_expired_src_nodes();
1514 pf_purge_unlinked_rules();
1519 VNET_LIST_RUNLOCK();
1523 sx_xunlock(&pf_end_lock);
1528 pf_unload_vnet_purge(void)
1532 * To cleanse up all kifs and rules we need
1533 * two runs: first one clears reference flags,
1534 * then pf_purge_expired_states() doesn't
1535 * raise them, and then second run frees.
1537 pf_purge_unlinked_rules();
1541 * Now purge everything.
1543 pf_purge_expired_states(0, pf_hashmask);
1544 pf_purge_fragments(UINT_MAX);
1545 pf_purge_expired_src_nodes();
1548 * Now all kifs & rules should be unreferenced,
1549 * thus should be successfully freed.
1551 pf_purge_unlinked_rules();
1557 pf_state_expires(const struct pf_state *state)
1564 /* handle all PFTM_* > PFTM_MAX here */
1565 if (state->timeout == PFTM_PURGE)
1566 return (time_uptime);
1567 KASSERT(state->timeout != PFTM_UNLINKED,
1568 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1569 KASSERT((state->timeout < PFTM_MAX),
1570 ("pf_state_expires: timeout > PFTM_MAX"));
1571 timeout = state->rule.ptr->timeout[state->timeout];
1573 timeout = V_pf_default_rule.timeout[state->timeout];
1574 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1575 if (start && state->rule.ptr != &V_pf_default_rule) {
1576 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1577 states = counter_u64_fetch(state->rule.ptr->states_cur);
1579 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1580 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1581 states = V_pf_status.states;
1583 if (end && states > start && start < end) {
1585 timeout = (u_int64_t)timeout * (end - states) /
1587 return (state->expire + timeout);
1590 return (time_uptime);
1592 return (state->expire + timeout);
1596 pf_purge_expired_src_nodes()
1598 struct pf_src_node_list freelist;
1599 struct pf_srchash *sh;
1600 struct pf_src_node *cur, *next;
1603 LIST_INIT(&freelist);
1604 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1605 PF_HASHROW_LOCK(sh);
1606 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1607 if (cur->states == 0 && cur->expire <= time_uptime) {
1608 pf_unlink_src_node(cur);
1609 LIST_INSERT_HEAD(&freelist, cur, entry);
1610 } else if (cur->rule.ptr != NULL)
1611 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1612 PF_HASHROW_UNLOCK(sh);
1615 pf_free_src_nodes(&freelist);
1617 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1621 pf_src_tree_remove_state(struct pf_state *s)
1623 struct pf_src_node *sn;
1624 struct pf_srchash *sh;
1627 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1628 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1629 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1631 if (s->src_node != NULL) {
1633 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1634 PF_HASHROW_LOCK(sh);
1637 if (--sn->states == 0)
1638 sn->expire = time_uptime + timeout;
1639 PF_HASHROW_UNLOCK(sh);
1641 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1642 sn = s->nat_src_node;
1643 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1644 PF_HASHROW_LOCK(sh);
1645 if (--sn->states == 0)
1646 sn->expire = time_uptime + timeout;
1647 PF_HASHROW_UNLOCK(sh);
1649 s->src_node = s->nat_src_node = NULL;
1653 * Unlink and potentilly free a state. Function may be
1654 * called with ID hash row locked, but always returns
1655 * unlocked, since it needs to go through key hash locking.
1658 pf_unlink_state(struct pf_state *s, u_int flags)
1660 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1662 if ((flags & PF_ENTER_LOCKED) == 0)
1663 PF_HASHROW_LOCK(ih);
1665 PF_HASHROW_ASSERT(ih);
1667 if (s->timeout == PFTM_UNLINKED) {
1669 * State is being processed
1670 * by pf_unlink_state() in
1673 PF_HASHROW_UNLOCK(ih);
1674 return (0); /* XXXGL: undefined actually */
1677 if (s->src.state == PF_TCPS_PROXY_DST) {
1678 /* XXX wire key the right one? */
1679 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1680 &s->key[PF_SK_WIRE]->addr[1],
1681 &s->key[PF_SK_WIRE]->addr[0],
1682 s->key[PF_SK_WIRE]->port[1],
1683 s->key[PF_SK_WIRE]->port[0],
1684 s->src.seqhi, s->src.seqlo + 1,
1685 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1688 LIST_REMOVE(s, entry);
1689 pf_src_tree_remove_state(s);
1691 if (V_pfsync_delete_state_ptr != NULL)
1692 V_pfsync_delete_state_ptr(s);
1694 STATE_DEC_COUNTERS(s);
1696 s->timeout = PFTM_UNLINKED;
1698 PF_HASHROW_UNLOCK(ih);
1701 /* pf_state_insert() initialises refs to 2, so we can never release the
1702 * last reference here, only in pf_release_state(). */
1703 (void)refcount_release(&s->refs);
1705 return (pf_release_state(s));
1709 pf_free_state(struct pf_state *cur)
1712 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1713 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1716 pf_normalize_tcp_cleanup(cur);
1717 uma_zfree(V_pf_state_z, cur);
1718 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1722 * Called only from pf_purge_thread(), thus serialized.
1725 pf_purge_expired_states(u_int i, int maxcheck)
1727 struct pf_idhash *ih;
1730 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1733 * Go through hash and unlink states that expire now.
1735 while (maxcheck > 0) {
1737 ih = &V_pf_idhash[i];
1739 /* only take the lock if we expect to do work */
1740 if (!LIST_EMPTY(&ih->states)) {
1742 PF_HASHROW_LOCK(ih);
1743 LIST_FOREACH(s, &ih->states, entry) {
1744 if (pf_state_expires(s) <= time_uptime) {
1745 V_pf_status.states -=
1746 pf_unlink_state(s, PF_ENTER_LOCKED);
1749 s->rule.ptr->rule_flag |= PFRULE_REFS;
1750 if (s->nat_rule.ptr != NULL)
1751 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1752 if (s->anchor.ptr != NULL)
1753 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1754 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1756 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1758 PF_HASHROW_UNLOCK(ih);
1761 /* Return when we hit end of hash. */
1762 if (++i > pf_hashmask) {
1763 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1770 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1776 pf_purge_unlinked_rules()
1778 struct pf_rulequeue tmpq;
1779 struct pf_rule *r, *r1;
1782 * If we have overloading task pending, then we'd
1783 * better skip purging this time. There is a tiny
1784 * probability that overloading task references
1785 * an already unlinked rule.
1787 PF_OVERLOADQ_LOCK();
1788 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1789 PF_OVERLOADQ_UNLOCK();
1792 PF_OVERLOADQ_UNLOCK();
1795 * Do naive mark-and-sweep garbage collecting of old rules.
1796 * Reference flag is raised by pf_purge_expired_states()
1797 * and pf_purge_expired_src_nodes().
1799 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1800 * use a temporary queue.
1803 PF_UNLNKDRULES_LOCK();
1804 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1805 if (!(r->rule_flag & PFRULE_REFS)) {
1806 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1807 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1809 r->rule_flag &= ~PFRULE_REFS;
1811 PF_UNLNKDRULES_UNLOCK();
1813 if (!TAILQ_EMPTY(&tmpq)) {
1815 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1816 TAILQ_REMOVE(&tmpq, r, entries);
1824 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1829 u_int32_t a = ntohl(addr->addr32[0]);
1830 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1842 u_int8_t i, curstart, curend, maxstart, maxend;
1843 curstart = curend = maxstart = maxend = 255;
1844 for (i = 0; i < 8; i++) {
1845 if (!addr->addr16[i]) {
1846 if (curstart == 255)
1850 if ((curend - curstart) >
1851 (maxend - maxstart)) {
1852 maxstart = curstart;
1855 curstart = curend = 255;
1858 if ((curend - curstart) >
1859 (maxend - maxstart)) {
1860 maxstart = curstart;
1863 for (i = 0; i < 8; i++) {
1864 if (i >= maxstart && i <= maxend) {
1870 b = ntohs(addr->addr16[i]);
1887 pf_print_state(struct pf_state *s)
1889 pf_print_state_parts(s, NULL, NULL);
1893 pf_print_state_parts(struct pf_state *s,
1894 struct pf_state_key *skwp, struct pf_state_key *sksp)
1896 struct pf_state_key *skw, *sks;
1897 u_int8_t proto, dir;
1899 /* Do our best to fill these, but they're skipped if NULL */
1900 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1901 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1902 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1903 dir = s ? s->direction : 0;
1921 case IPPROTO_ICMPV6:
1925 printf("%u", proto);
1938 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1940 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1945 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1947 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1952 if (proto == IPPROTO_TCP) {
1953 printf(" [lo=%u high=%u win=%u modulator=%u",
1954 s->src.seqlo, s->src.seqhi,
1955 s->src.max_win, s->src.seqdiff);
1956 if (s->src.wscale && s->dst.wscale)
1957 printf(" wscale=%u",
1958 s->src.wscale & PF_WSCALE_MASK);
1960 printf(" [lo=%u high=%u win=%u modulator=%u",
1961 s->dst.seqlo, s->dst.seqhi,
1962 s->dst.max_win, s->dst.seqdiff);
1963 if (s->src.wscale && s->dst.wscale)
1964 printf(" wscale=%u",
1965 s->dst.wscale & PF_WSCALE_MASK);
1968 printf(" %u:%u", s->src.state, s->dst.state);
1973 pf_print_flags(u_int8_t f)
1995 #define PF_SET_SKIP_STEPS(i) \
1997 while (head[i] != cur) { \
1998 head[i]->skip[i].ptr = cur; \
1999 head[i] = TAILQ_NEXT(head[i], entries); \
2004 pf_calc_skip_steps(struct pf_rulequeue *rules)
2006 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
2009 cur = TAILQ_FIRST(rules);
2011 for (i = 0; i < PF_SKIP_COUNT; ++i)
2013 while (cur != NULL) {
2015 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2016 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2017 if (cur->direction != prev->direction)
2018 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2019 if (cur->af != prev->af)
2020 PF_SET_SKIP_STEPS(PF_SKIP_AF);
2021 if (cur->proto != prev->proto)
2022 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2023 if (cur->src.neg != prev->src.neg ||
2024 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2025 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2026 if (cur->src.port[0] != prev->src.port[0] ||
2027 cur->src.port[1] != prev->src.port[1] ||
2028 cur->src.port_op != prev->src.port_op)
2029 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2030 if (cur->dst.neg != prev->dst.neg ||
2031 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2032 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2033 if (cur->dst.port[0] != prev->dst.port[0] ||
2034 cur->dst.port[1] != prev->dst.port[1] ||
2035 cur->dst.port_op != prev->dst.port_op)
2036 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2039 cur = TAILQ_NEXT(cur, entries);
2041 for (i = 0; i < PF_SKIP_COUNT; ++i)
2042 PF_SET_SKIP_STEPS(i);
2046 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2048 if (aw1->type != aw2->type)
2050 switch (aw1->type) {
2051 case PF_ADDR_ADDRMASK:
2053 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2055 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2058 case PF_ADDR_DYNIFTL:
2059 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2060 case PF_ADDR_NOROUTE:
2061 case PF_ADDR_URPFFAILED:
2064 return (aw1->p.tbl != aw2->p.tbl);
2066 printf("invalid address type: %d\n", aw1->type);
2072 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2073 * header isn't always a full checksum. In some cases (i.e. output) it's a
2074 * pseudo-header checksum, which is a partial checksum over src/dst IP
2075 * addresses, protocol number and length.
2077 * That means we have the following cases:
2078 * * Input or forwarding: we don't have TSO, the checksum fields are full
2079 * checksums, we need to update the checksum whenever we change anything.
2080 * * Output (i.e. the checksum is a pseudo-header checksum):
2081 * x The field being updated is src/dst address or affects the length of
2082 * the packet. We need to update the pseudo-header checksum (note that this
2083 * checksum is not ones' complement).
2084 * x Some other field is being modified (e.g. src/dst port numbers): We
2085 * don't have to update anything.
2088 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2094 l = cksum + old - new;
2095 l = (l >> 16) + (l & 65535);
2103 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2104 u_int16_t new, u_int8_t udp)
2106 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2109 return (pf_cksum_fixup(cksum, old, new, udp));
2113 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2114 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2120 PF_ACPY(&ao, a, af);
2123 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2131 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2132 ao.addr16[0], an->addr16[0], 0),
2133 ao.addr16[1], an->addr16[1], 0);
2136 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2137 ao.addr16[0], an->addr16[0], u),
2138 ao.addr16[1], an->addr16[1], u);
2140 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2145 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2146 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2147 pf_cksum_fixup(pf_cksum_fixup(*pc,
2148 ao.addr16[0], an->addr16[0], u),
2149 ao.addr16[1], an->addr16[1], u),
2150 ao.addr16[2], an->addr16[2], u),
2151 ao.addr16[3], an->addr16[3], u),
2152 ao.addr16[4], an->addr16[4], u),
2153 ao.addr16[5], an->addr16[5], u),
2154 ao.addr16[6], an->addr16[6], u),
2155 ao.addr16[7], an->addr16[7], u);
2157 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2162 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2163 CSUM_DELAY_DATA_IPV6)) {
2170 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2172 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2176 memcpy(&ao, a, sizeof(ao));
2177 memcpy(a, &an, sizeof(u_int32_t));
2178 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2179 ao % 65536, an % 65536, u);
2183 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2187 memcpy(&ao, a, sizeof(ao));
2188 memcpy(a, &an, sizeof(u_int32_t));
2190 *c = pf_proto_cksum_fixup(m,
2191 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2192 ao % 65536, an % 65536, udp);
2197 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2201 PF_ACPY(&ao, a, AF_INET6);
2202 PF_ACPY(a, an, AF_INET6);
2204 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2205 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2206 pf_cksum_fixup(pf_cksum_fixup(*c,
2207 ao.addr16[0], an->addr16[0], u),
2208 ao.addr16[1], an->addr16[1], u),
2209 ao.addr16[2], an->addr16[2], u),
2210 ao.addr16[3], an->addr16[3], u),
2211 ao.addr16[4], an->addr16[4], u),
2212 ao.addr16[5], an->addr16[5], u),
2213 ao.addr16[6], an->addr16[6], u),
2214 ao.addr16[7], an->addr16[7], u);
2219 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2220 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2221 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2223 struct pf_addr oia, ooa;
2225 PF_ACPY(&oia, ia, af);
2227 PF_ACPY(&ooa, oa, af);
2229 /* Change inner protocol port, fix inner protocol checksum. */
2231 u_int16_t oip = *ip;
2238 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2239 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2241 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2243 /* Change inner ip address, fix inner ip and icmp checksums. */
2244 PF_ACPY(ia, na, af);
2248 u_int32_t oh2c = *h2c;
2250 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2251 oia.addr16[0], ia->addr16[0], 0),
2252 oia.addr16[1], ia->addr16[1], 0);
2253 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2254 oia.addr16[0], ia->addr16[0], 0),
2255 oia.addr16[1], ia->addr16[1], 0);
2256 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2262 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2263 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2264 pf_cksum_fixup(pf_cksum_fixup(*ic,
2265 oia.addr16[0], ia->addr16[0], u),
2266 oia.addr16[1], ia->addr16[1], u),
2267 oia.addr16[2], ia->addr16[2], u),
2268 oia.addr16[3], ia->addr16[3], u),
2269 oia.addr16[4], ia->addr16[4], u),
2270 oia.addr16[5], ia->addr16[5], u),
2271 oia.addr16[6], ia->addr16[6], u),
2272 oia.addr16[7], ia->addr16[7], u);
2276 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2278 PF_ACPY(oa, na, af);
2282 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2283 ooa.addr16[0], oa->addr16[0], 0),
2284 ooa.addr16[1], oa->addr16[1], 0);
2289 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2290 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2291 pf_cksum_fixup(pf_cksum_fixup(*ic,
2292 ooa.addr16[0], oa->addr16[0], u),
2293 ooa.addr16[1], oa->addr16[1], u),
2294 ooa.addr16[2], oa->addr16[2], u),
2295 ooa.addr16[3], oa->addr16[3], u),
2296 ooa.addr16[4], oa->addr16[4], u),
2297 ooa.addr16[5], oa->addr16[5], u),
2298 ooa.addr16[6], oa->addr16[6], u),
2299 ooa.addr16[7], oa->addr16[7], u);
2308 * Need to modulate the sequence numbers in the TCP SACK option
2309 * (credits to Krzysztof Pfaff for report and patch)
2312 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2313 struct tcphdr *th, struct pf_state_peer *dst)
2315 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2316 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2317 int copyback = 0, i, olen;
2318 struct sackblk sack;
2320 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2321 if (hlen < TCPOLEN_SACKLEN ||
2322 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2325 while (hlen >= TCPOLEN_SACKLEN) {
2328 case TCPOPT_EOL: /* FALLTHROUGH */
2336 if (olen >= TCPOLEN_SACKLEN) {
2337 for (i = 2; i + TCPOLEN_SACK <= olen;
2338 i += TCPOLEN_SACK) {
2339 memcpy(&sack, &opt[i], sizeof(sack));
2340 pf_change_proto_a(m, &sack.start, &th->th_sum,
2341 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2342 pf_change_proto_a(m, &sack.end, &th->th_sum,
2343 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2344 memcpy(&opt[i], &sack, sizeof(sack));
2358 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2363 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2364 const struct pf_addr *saddr, const struct pf_addr *daddr,
2365 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2366 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2367 u_int16_t rtag, struct ifnet *ifp)
2369 struct pf_send_entry *pfse;
2373 struct ip *h = NULL;
2376 struct ip6_hdr *h6 = NULL;
2380 struct pf_mtag *pf_mtag;
2385 /* maximum segment size tcp option */
2386 tlen = sizeof(struct tcphdr);
2393 len = sizeof(struct ip) + tlen;
2398 len = sizeof(struct ip6_hdr) + tlen;
2402 panic("%s: unsupported af %d", __func__, af);
2405 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2406 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2409 m = m_gethdr(M_NOWAIT, MT_DATA);
2411 free(pfse, M_PFTEMP);
2415 mac_netinet_firewall_send(m);
2417 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2418 free(pfse, M_PFTEMP);
2423 m->m_flags |= M_SKIP_FIREWALL;
2424 pf_mtag->tag = rtag;
2426 if (r != NULL && r->rtableid >= 0)
2427 M_SETFIB(m, r->rtableid);
2430 if (r != NULL && r->qid) {
2431 pf_mtag->qid = r->qid;
2433 /* add hints for ecn */
2434 pf_mtag->hdr = mtod(m, struct ip *);
2437 m->m_data += max_linkhdr;
2438 m->m_pkthdr.len = m->m_len = len;
2439 m->m_pkthdr.rcvif = NULL;
2440 bzero(m->m_data, len);
2444 h = mtod(m, struct ip *);
2446 /* IP header fields included in the TCP checksum */
2447 h->ip_p = IPPROTO_TCP;
2448 h->ip_len = htons(tlen);
2449 h->ip_src.s_addr = saddr->v4.s_addr;
2450 h->ip_dst.s_addr = daddr->v4.s_addr;
2452 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2457 h6 = mtod(m, struct ip6_hdr *);
2459 /* IP header fields included in the TCP checksum */
2460 h6->ip6_nxt = IPPROTO_TCP;
2461 h6->ip6_plen = htons(tlen);
2462 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2463 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2465 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2471 th->th_sport = sport;
2472 th->th_dport = dport;
2473 th->th_seq = htonl(seq);
2474 th->th_ack = htonl(ack);
2475 th->th_off = tlen >> 2;
2476 th->th_flags = flags;
2477 th->th_win = htons(win);
2480 opt = (char *)(th + 1);
2481 opt[0] = TCPOPT_MAXSEG;
2484 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2491 th->th_sum = in_cksum(m, len);
2493 /* Finish the IP header */
2495 h->ip_hl = sizeof(*h) >> 2;
2496 h->ip_tos = IPTOS_LOWDELAY;
2497 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2498 h->ip_len = htons(len);
2499 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2502 pfse->pfse_type = PFSE_IP;
2508 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2509 sizeof(struct ip6_hdr), tlen);
2511 h6->ip6_vfc |= IPV6_VERSION;
2512 h6->ip6_hlim = IPV6_DEFHLIM;
2514 pfse->pfse_type = PFSE_IP6;
2523 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2524 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2525 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2528 struct pf_addr * const saddr = pd->src;
2529 struct pf_addr * const daddr = pd->dst;
2530 sa_family_t af = pd->af;
2532 /* undo NAT changes, if they have taken place */
2534 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2535 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2537 *pd->sport = sk->port[pd->sidx];
2539 *pd->dport = sk->port[pd->didx];
2541 *pd->proto_sum = bproto_sum;
2543 *pd->ip_sum = bip_sum;
2544 m_copyback(m, off, hdrlen, pd->hdr.any);
2546 if (pd->proto == IPPROTO_TCP &&
2547 ((r->rule_flag & PFRULE_RETURNRST) ||
2548 (r->rule_flag & PFRULE_RETURN)) &&
2549 !(th->th_flags & TH_RST)) {
2550 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2562 h4 = mtod(m, struct ip *);
2563 len = ntohs(h4->ip_len) - off;
2568 h6 = mtod(m, struct ip6_hdr *);
2569 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2574 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2575 REASON_SET(reason, PFRES_PROTCKSUM);
2577 if (th->th_flags & TH_SYN)
2579 if (th->th_flags & TH_FIN)
2581 pf_send_tcp(m, r, af, pd->dst,
2582 pd->src, th->th_dport, th->th_sport,
2583 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2584 r->return_ttl, 1, 0, kif->pfik_ifp);
2586 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2588 pf_send_icmp(m, r->return_icmp >> 8,
2589 r->return_icmp & 255, af, r);
2590 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2592 pf_send_icmp(m, r->return_icmp6 >> 8,
2593 r->return_icmp6 & 255, af, r);
2598 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2602 KASSERT(prio <= PF_PRIO_MAX,
2603 ("%s with invalid pcp", __func__));
2605 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2607 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2608 sizeof(uint8_t), M_NOWAIT);
2611 m_tag_prepend(m, mtag);
2614 *(uint8_t *)(mtag + 1) = prio;
2619 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2624 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2628 if (prio == PF_PRIO_ZERO)
2631 mpcp = *(uint8_t *)(mtag + 1);
2633 return (mpcp == prio);
2637 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2640 struct pf_send_entry *pfse;
2642 struct pf_mtag *pf_mtag;
2644 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2645 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2649 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2650 free(pfse, M_PFTEMP);
2654 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2655 free(pfse, M_PFTEMP);
2659 m0->m_flags |= M_SKIP_FIREWALL;
2661 if (r->rtableid >= 0)
2662 M_SETFIB(m0, r->rtableid);
2666 pf_mtag->qid = r->qid;
2667 /* add hints for ecn */
2668 pf_mtag->hdr = mtod(m0, struct ip *);
2675 pfse->pfse_type = PFSE_ICMP;
2680 pfse->pfse_type = PFSE_ICMP6;
2685 pfse->icmpopts.type = type;
2686 pfse->icmpopts.code = code;
2691 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2692 * If n is 0, they match if they are equal. If n is != 0, they match if they
2696 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2697 struct pf_addr *b, sa_family_t af)
2704 if ((a->addr32[0] & m->addr32[0]) ==
2705 (b->addr32[0] & m->addr32[0]))
2711 if (((a->addr32[0] & m->addr32[0]) ==
2712 (b->addr32[0] & m->addr32[0])) &&
2713 ((a->addr32[1] & m->addr32[1]) ==
2714 (b->addr32[1] & m->addr32[1])) &&
2715 ((a->addr32[2] & m->addr32[2]) ==
2716 (b->addr32[2] & m->addr32[2])) &&
2717 ((a->addr32[3] & m->addr32[3]) ==
2718 (b->addr32[3] & m->addr32[3])))
2737 * Return 1 if b <= a <= e, otherwise return 0.
2740 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2741 struct pf_addr *a, sa_family_t af)
2746 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2747 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2756 for (i = 0; i < 4; ++i)
2757 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2759 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2762 for (i = 0; i < 4; ++i)
2763 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2765 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2775 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2779 return ((p > a1) && (p < a2));
2781 return ((p < a1) || (p > a2));
2783 return ((p >= a1) && (p <= a2));
2797 return (0); /* never reached */
2801 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2806 return (pf_match(op, a1, a2, p));
2810 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2812 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2814 return (pf_match(op, a1, a2, u));
2818 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2820 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2822 return (pf_match(op, a1, a2, g));
2826 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2831 return ((!r->match_tag_not && r->match_tag == *tag) ||
2832 (r->match_tag_not && r->match_tag != *tag));
2836 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2839 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2841 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2844 pd->pf_mtag->tag = tag;
2849 #define PF_ANCHOR_STACKSIZE 32
2850 struct pf_anchor_stackframe {
2851 struct pf_ruleset *rs;
2852 struct pf_rule *r; /* XXX: + match bit */
2853 struct pf_anchor *child;
2857 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2859 #define PF_ANCHORSTACK_MATCH 0x00000001
2860 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2862 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2863 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2864 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2865 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2866 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2870 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2871 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2874 struct pf_anchor_stackframe *f;
2880 if (*depth >= PF_ANCHOR_STACKSIZE) {
2881 printf("%s: anchor stack overflow on %s\n",
2882 __func__, (*r)->anchor->name);
2883 *r = TAILQ_NEXT(*r, entries);
2885 } else if (*depth == 0 && a != NULL)
2887 f = stack + (*depth)++;
2890 if ((*r)->anchor_wildcard) {
2891 struct pf_anchor_node *parent = &(*r)->anchor->children;
2893 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2897 *rs = &f->child->ruleset;
2900 *rs = &(*r)->anchor->ruleset;
2902 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2906 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2907 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2910 struct pf_anchor_stackframe *f;
2919 f = stack + *depth - 1;
2920 fr = PF_ANCHOR_RULE(f);
2921 if (f->child != NULL) {
2922 struct pf_anchor_node *parent;
2925 * This block traverses through
2926 * a wildcard anchor.
2928 parent = &fr->anchor->children;
2929 if (match != NULL && *match) {
2931 * If any of "*" matched, then
2932 * "foo/ *" matched, mark frame
2935 PF_ANCHOR_SET_MATCH(f);
2938 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2939 if (f->child != NULL) {
2940 *rs = &f->child->ruleset;
2941 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2949 if (*depth == 0 && a != NULL)
2952 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2954 *r = TAILQ_NEXT(fr, entries);
2955 } while (*r == NULL);
2962 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2963 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2968 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2969 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2973 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2974 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2975 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2976 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2977 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2978 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2979 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2980 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2986 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2991 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2995 if (addr->addr32[3] == 0xffffffff) {
2996 addr->addr32[3] = 0;
2997 if (addr->addr32[2] == 0xffffffff) {
2998 addr->addr32[2] = 0;
2999 if (addr->addr32[1] == 0xffffffff) {
3000 addr->addr32[1] = 0;
3002 htonl(ntohl(addr->addr32[0]) + 1);
3005 htonl(ntohl(addr->addr32[1]) + 1);
3008 htonl(ntohl(addr->addr32[2]) + 1);
3011 htonl(ntohl(addr->addr32[3]) + 1);
3018 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3020 struct pf_addr *saddr, *daddr;
3021 u_int16_t sport, dport;
3022 struct inpcbinfo *pi;
3025 pd->lookup.uid = UID_MAX;
3026 pd->lookup.gid = GID_MAX;
3028 switch (pd->proto) {
3030 if (pd->hdr.tcp == NULL)
3032 sport = pd->hdr.tcp->th_sport;
3033 dport = pd->hdr.tcp->th_dport;
3037 if (pd->hdr.udp == NULL)
3039 sport = pd->hdr.udp->uh_sport;
3040 dport = pd->hdr.udp->uh_dport;
3046 if (direction == PF_IN) {
3061 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3062 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3064 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3065 daddr->v4, dport, INPLOOKUP_WILDCARD |
3066 INPLOOKUP_RLOCKPCB, NULL, m);
3074 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3075 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3077 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3078 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3079 INPLOOKUP_RLOCKPCB, NULL, m);
3089 INP_RLOCK_ASSERT(inp);
3090 pd->lookup.uid = inp->inp_cred->cr_uid;
3091 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3098 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3102 u_int8_t *opt, optlen;
3103 u_int8_t wscale = 0;
3105 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3106 if (hlen <= sizeof(struct tcphdr))
3108 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3110 opt = hdr + sizeof(struct tcphdr);
3111 hlen -= sizeof(struct tcphdr);
3121 if (wscale > TCP_MAX_WINSHIFT)
3122 wscale = TCP_MAX_WINSHIFT;
3123 wscale |= PF_WSCALE_FLAG;
3138 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3142 u_int8_t *opt, optlen;
3143 u_int16_t mss = V_tcp_mssdflt;
3145 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3146 if (hlen <= sizeof(struct tcphdr))
3148 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3150 opt = hdr + sizeof(struct tcphdr);
3151 hlen -= sizeof(struct tcphdr);
3152 while (hlen >= TCPOLEN_MAXSEG) {
3160 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3176 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3179 struct nhop4_basic nh4;
3182 struct nhop6_basic nh6;
3183 struct in6_addr dst6;
3192 hlen = sizeof(struct ip);
3193 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3194 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3199 hlen = sizeof(struct ip6_hdr);
3200 in6_splitscope(&addr->v6, &dst6, &scopeid);
3201 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3202 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3207 mss = max(V_tcp_mssdflt, mss);
3208 mss = min(mss, offer);
3209 mss = max(mss, 64); /* sanity - at least max opt space */
3214 pf_tcp_iss(struct pf_pdesc *pd)
3217 u_int32_t digest[4];
3219 if (V_pf_tcp_secret_init == 0) {
3220 arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3221 MD5Init(&V_pf_tcp_secret_ctx);
3222 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3223 sizeof(V_pf_tcp_secret));
3224 V_pf_tcp_secret_init = 1;
3227 ctx = V_pf_tcp_secret_ctx;
3229 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3230 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3231 if (pd->af == AF_INET6) {
3232 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3233 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3235 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3236 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3238 MD5Final((u_char *)digest, &ctx);
3239 V_pf_tcp_iss_off += 4096;
3240 #define ISN_RANDOM_INCREMENT (4096 - 1)
3241 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3243 #undef ISN_RANDOM_INCREMENT
3247 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3248 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3249 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3251 struct pf_rule *nr = NULL;
3252 struct pf_addr * const saddr = pd->src;
3253 struct pf_addr * const daddr = pd->dst;
3254 sa_family_t af = pd->af;
3255 struct pf_rule *r, *a = NULL;
3256 struct pf_ruleset *ruleset = NULL;
3257 struct pf_src_node *nsn = NULL;
3258 struct tcphdr *th = pd->hdr.tcp;
3259 struct pf_state_key *sk = NULL, *nk = NULL;
3261 int rewrite = 0, hdrlen = 0;
3262 int tag = -1, rtableid = -1;
3266 u_int16_t sport = 0, dport = 0;
3267 u_int16_t bproto_sum = 0, bip_sum = 0;
3268 u_int8_t icmptype = 0, icmpcode = 0;
3269 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3274 INP_LOCK_ASSERT(inp);
3275 pd->lookup.uid = inp->inp_cred->cr_uid;
3276 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3277 pd->lookup.done = 1;
3280 switch (pd->proto) {
3282 sport = th->th_sport;
3283 dport = th->th_dport;
3284 hdrlen = sizeof(*th);
3287 sport = pd->hdr.udp->uh_sport;
3288 dport = pd->hdr.udp->uh_dport;
3289 hdrlen = sizeof(*pd->hdr.udp);
3293 if (pd->af != AF_INET)
3295 sport = dport = pd->hdr.icmp->icmp_id;
3296 hdrlen = sizeof(*pd->hdr.icmp);
3297 icmptype = pd->hdr.icmp->icmp_type;
3298 icmpcode = pd->hdr.icmp->icmp_code;
3300 if (icmptype == ICMP_UNREACH ||
3301 icmptype == ICMP_SOURCEQUENCH ||
3302 icmptype == ICMP_REDIRECT ||
3303 icmptype == ICMP_TIMXCEED ||
3304 icmptype == ICMP_PARAMPROB)
3309 case IPPROTO_ICMPV6:
3312 sport = dport = pd->hdr.icmp6->icmp6_id;
3313 hdrlen = sizeof(*pd->hdr.icmp6);
3314 icmptype = pd->hdr.icmp6->icmp6_type;
3315 icmpcode = pd->hdr.icmp6->icmp6_code;
3317 if (icmptype == ICMP6_DST_UNREACH ||
3318 icmptype == ICMP6_PACKET_TOO_BIG ||
3319 icmptype == ICMP6_TIME_EXCEEDED ||
3320 icmptype == ICMP6_PARAM_PROB)
3325 sport = dport = hdrlen = 0;
3329 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3331 /* check packet for BINAT/NAT/RDR */
3332 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3333 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3334 KASSERT(sk != NULL, ("%s: null sk", __func__));
3335 KASSERT(nk != NULL, ("%s: null nk", __func__));
3338 bip_sum = *pd->ip_sum;
3340 switch (pd->proto) {
3342 bproto_sum = th->th_sum;
3343 pd->proto_sum = &th->th_sum;
3345 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3346 nk->port[pd->sidx] != sport) {
3347 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3348 &th->th_sum, &nk->addr[pd->sidx],
3349 nk->port[pd->sidx], 0, af);
3350 pd->sport = &th->th_sport;
3351 sport = th->th_sport;
3354 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3355 nk->port[pd->didx] != dport) {
3356 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3357 &th->th_sum, &nk->addr[pd->didx],
3358 nk->port[pd->didx], 0, af);
3359 dport = th->th_dport;
3360 pd->dport = &th->th_dport;
3365 bproto_sum = pd->hdr.udp->uh_sum;
3366 pd->proto_sum = &pd->hdr.udp->uh_sum;
3368 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3369 nk->port[pd->sidx] != sport) {
3370 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3371 pd->ip_sum, &pd->hdr.udp->uh_sum,
3372 &nk->addr[pd->sidx],
3373 nk->port[pd->sidx], 1, af);
3374 sport = pd->hdr.udp->uh_sport;
3375 pd->sport = &pd->hdr.udp->uh_sport;
3378 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3379 nk->port[pd->didx] != dport) {
3380 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3381 pd->ip_sum, &pd->hdr.udp->uh_sum,
3382 &nk->addr[pd->didx],
3383 nk->port[pd->didx], 1, af);
3384 dport = pd->hdr.udp->uh_dport;
3385 pd->dport = &pd->hdr.udp->uh_dport;
3391 nk->port[0] = nk->port[1];
3392 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3393 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3394 nk->addr[pd->sidx].v4.s_addr, 0);
3396 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3397 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3398 nk->addr[pd->didx].v4.s_addr, 0);
3400 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3401 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3402 pd->hdr.icmp->icmp_cksum, sport,
3404 pd->hdr.icmp->icmp_id = nk->port[1];
3405 pd->sport = &pd->hdr.icmp->icmp_id;
3407 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3411 case IPPROTO_ICMPV6:
3412 nk->port[0] = nk->port[1];
3413 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3414 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3415 &nk->addr[pd->sidx], 0);
3417 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3418 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3419 &nk->addr[pd->didx], 0);
3428 &nk->addr[pd->sidx], AF_INET))
3429 pf_change_a(&saddr->v4.s_addr,
3431 nk->addr[pd->sidx].v4.s_addr, 0);
3434 &nk->addr[pd->didx], AF_INET))
3435 pf_change_a(&daddr->v4.s_addr,
3437 nk->addr[pd->didx].v4.s_addr, 0);
3443 &nk->addr[pd->sidx], AF_INET6))
3444 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3447 &nk->addr[pd->didx], AF_INET6))
3448 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3461 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3462 r = r->skip[PF_SKIP_IFP].ptr;
3463 else if (r->direction && r->direction != direction)
3464 r = r->skip[PF_SKIP_DIR].ptr;
3465 else if (r->af && r->af != af)
3466 r = r->skip[PF_SKIP_AF].ptr;
3467 else if (r->proto && r->proto != pd->proto)
3468 r = r->skip[PF_SKIP_PROTO].ptr;
3469 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3470 r->src.neg, kif, M_GETFIB(m)))
3471 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3472 /* tcp/udp only. port_op always 0 in other cases */
3473 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3474 r->src.port[0], r->src.port[1], sport))
3475 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3476 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3477 r->dst.neg, NULL, M_GETFIB(m)))
3478 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3479 /* tcp/udp only. port_op always 0 in other cases */
3480 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3481 r->dst.port[0], r->dst.port[1], dport))
3482 r = r->skip[PF_SKIP_DST_PORT].ptr;
3483 /* icmp only. type always 0 in other cases */
3484 else if (r->type && r->type != icmptype + 1)
3485 r = TAILQ_NEXT(r, entries);
3486 /* icmp only. type always 0 in other cases */
3487 else if (r->code && r->code != icmpcode + 1)
3488 r = TAILQ_NEXT(r, entries);
3489 else if (r->tos && !(r->tos == pd->tos))
3490 r = TAILQ_NEXT(r, entries);
3491 else if (r->rule_flag & PFRULE_FRAGMENT)
3492 r = TAILQ_NEXT(r, entries);
3493 else if (pd->proto == IPPROTO_TCP &&
3494 (r->flagset & th->th_flags) != r->flags)
3495 r = TAILQ_NEXT(r, entries);
3496 /* tcp/udp only. uid.op always 0 in other cases */
3497 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3498 pf_socket_lookup(direction, pd, m), 1)) &&
3499 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3501 r = TAILQ_NEXT(r, entries);
3502 /* tcp/udp only. gid.op always 0 in other cases */
3503 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3504 pf_socket_lookup(direction, pd, m), 1)) &&
3505 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3507 r = TAILQ_NEXT(r, entries);
3509 !pf_match_ieee8021q_pcp(r->prio, m))
3510 r = TAILQ_NEXT(r, entries);
3512 r->prob <= arc4random())
3513 r = TAILQ_NEXT(r, entries);
3514 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3515 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3516 r = TAILQ_NEXT(r, entries);
3517 else if (r->os_fingerprint != PF_OSFP_ANY &&
3518 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3519 pf_osfp_fingerprint(pd, m, off, th),
3520 r->os_fingerprint)))
3521 r = TAILQ_NEXT(r, entries);
3525 if (r->rtableid >= 0)
3526 rtableid = r->rtableid;
3527 if (r->anchor == NULL) {
3534 r = TAILQ_NEXT(r, entries);
3536 pf_step_into_anchor(anchor_stack, &asd,
3537 &ruleset, PF_RULESET_FILTER, &r, &a,
3540 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3541 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3548 REASON_SET(&reason, PFRES_MATCH);
3550 if (r->log || (nr != NULL && nr->log)) {
3552 m_copyback(m, off, hdrlen, pd->hdr.any);
3553 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3557 if ((r->action == PF_DROP) &&
3558 ((r->rule_flag & PFRULE_RETURNRST) ||
3559 (r->rule_flag & PFRULE_RETURNICMP) ||
3560 (r->rule_flag & PFRULE_RETURN))) {
3561 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3562 bip_sum, hdrlen, &reason);
3565 if (r->action == PF_DROP)
3568 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3569 REASON_SET(&reason, PFRES_MEMORY);
3573 M_SETFIB(m, rtableid);
3575 if (!state_icmp && (r->keep_state || nr != NULL ||
3576 (pd->flags & PFDESC_TCP_NORM))) {
3578 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3579 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3581 if (action != PF_PASS) {
3582 if (action == PF_DROP &&
3583 (r->rule_flag & PFRULE_RETURN))
3584 pf_return(r, nr, pd, sk, off, m, th, kif,
3585 bproto_sum, bip_sum, hdrlen, &reason);
3590 uma_zfree(V_pf_state_key_z, sk);
3592 uma_zfree(V_pf_state_key_z, nk);
3595 /* copy back packet headers if we performed NAT operations */
3597 m_copyback(m, off, hdrlen, pd->hdr.any);
3599 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3600 direction == PF_OUT &&
3601 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3603 * We want the state created, but we dont
3604 * want to send this in case a partner
3605 * firewall has to know about it to allow
3606 * replies through it.
3614 uma_zfree(V_pf_state_key_z, sk);
3616 uma_zfree(V_pf_state_key_z, nk);
3621 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3622 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3623 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3624 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3625 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3627 struct pf_state *s = NULL;
3628 struct pf_src_node *sn = NULL;
3629 struct tcphdr *th = pd->hdr.tcp;
3630 u_int16_t mss = V_tcp_mssdflt;
3633 /* check maximums */
3634 if (r->max_states &&
3635 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3636 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3637 REASON_SET(&reason, PFRES_MAXSTATES);
3640 /* src node for filter rule */
3641 if ((r->rule_flag & PFRULE_SRCTRACK ||
3642 r->rpool.opts & PF_POOL_STICKYADDR) &&
3643 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3644 REASON_SET(&reason, PFRES_SRCLIMIT);
3647 /* src node for translation rule */
3648 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3649 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3650 REASON_SET(&reason, PFRES_SRCLIMIT);
3653 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3655 REASON_SET(&reason, PFRES_MEMORY);
3659 s->nat_rule.ptr = nr;
3661 STATE_INC_COUNTERS(s);
3663 s->state_flags |= PFSTATE_ALLOWOPTS;
3664 if (r->rule_flag & PFRULE_STATESLOPPY)
3665 s->state_flags |= PFSTATE_SLOPPY;
3666 s->log = r->log & PF_LOG_ALL;
3667 s->sync_state = PFSYNC_S_NONE;
3669 s->log |= nr->log & PF_LOG_ALL;
3670 switch (pd->proto) {
3672 s->src.seqlo = ntohl(th->th_seq);
3673 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3674 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3675 r->keep_state == PF_STATE_MODULATE) {
3676 /* Generate sequence number modulator */
3677 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3680 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3681 htonl(s->src.seqlo + s->src.seqdiff), 0);
3685 if (th->th_flags & TH_SYN) {
3687 s->src.wscale = pf_get_wscale(m, off,
3688 th->th_off, pd->af);
3690 s->src.max_win = MAX(ntohs(th->th_win), 1);
3691 if (s->src.wscale & PF_WSCALE_MASK) {
3692 /* Remove scale factor from initial window */
3693 int win = s->src.max_win;
3694 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3695 s->src.max_win = (win - 1) >>
3696 (s->src.wscale & PF_WSCALE_MASK);
3698 if (th->th_flags & TH_FIN)
3702 s->src.state = TCPS_SYN_SENT;
3703 s->dst.state = TCPS_CLOSED;
3704 s->timeout = PFTM_TCP_FIRST_PACKET;
3707 s->src.state = PFUDPS_SINGLE;
3708 s->dst.state = PFUDPS_NO_TRAFFIC;
3709 s->timeout = PFTM_UDP_FIRST_PACKET;
3713 case IPPROTO_ICMPV6:
3715 s->timeout = PFTM_ICMP_FIRST_PACKET;
3718 s->src.state = PFOTHERS_SINGLE;
3719 s->dst.state = PFOTHERS_NO_TRAFFIC;
3720 s->timeout = PFTM_OTHER_FIRST_PACKET;
3724 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3725 REASON_SET(&reason, PFRES_MAPFAILED);
3726 pf_src_tree_remove_state(s);
3727 STATE_DEC_COUNTERS(s);
3728 uma_zfree(V_pf_state_z, s);
3731 s->rt_kif = r->rpool.cur->kif;
3734 s->creation = time_uptime;
3735 s->expire = time_uptime;
3740 /* XXX We only modify one side for now. */
3741 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3742 s->nat_src_node = nsn;
3744 if (pd->proto == IPPROTO_TCP) {
3745 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3746 off, pd, th, &s->src, &s->dst)) {
3747 REASON_SET(&reason, PFRES_MEMORY);
3748 pf_src_tree_remove_state(s);
3749 STATE_DEC_COUNTERS(s);
3750 uma_zfree(V_pf_state_z, s);
3753 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3754 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3755 &s->src, &s->dst, rewrite)) {
3756 /* This really shouldn't happen!!! */
3757 DPFPRINTF(PF_DEBUG_URGENT,
3758 ("pf_normalize_tcp_stateful failed on first "
3760 pf_normalize_tcp_cleanup(s);
3761 pf_src_tree_remove_state(s);
3762 STATE_DEC_COUNTERS(s);
3763 uma_zfree(V_pf_state_z, s);
3767 s->direction = pd->dir;
3770 * sk/nk could already been setup by pf_get_translation().
3773 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3774 __func__, nr, sk, nk));
3775 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3780 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3781 __func__, nr, sk, nk));
3783 /* Swap sk/nk for PF_OUT. */
3784 if (pf_state_insert(BOUND_IFACE(r, kif),
3785 (pd->dir == PF_IN) ? sk : nk,
3786 (pd->dir == PF_IN) ? nk : sk, s)) {
3787 if (pd->proto == IPPROTO_TCP)
3788 pf_normalize_tcp_cleanup(s);
3789 REASON_SET(&reason, PFRES_STATEINS);
3790 pf_src_tree_remove_state(s);
3791 STATE_DEC_COUNTERS(s);
3792 uma_zfree(V_pf_state_z, s);
3799 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3800 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3801 s->src.state = PF_TCPS_PROXY_SRC;
3802 /* undo NAT changes, if they have taken place */
3804 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3805 if (pd->dir == PF_OUT)
3806 skt = s->key[PF_SK_STACK];
3807 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3808 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3810 *pd->sport = skt->port[pd->sidx];
3812 *pd->dport = skt->port[pd->didx];
3814 *pd->proto_sum = bproto_sum;
3816 *pd->ip_sum = bip_sum;
3817 m_copyback(m, off, hdrlen, pd->hdr.any);
3819 s->src.seqhi = htonl(arc4random());
3820 /* Find mss option */
3821 int rtid = M_GETFIB(m);
3822 mss = pf_get_mss(m, off, th->th_off, pd->af);
3823 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3824 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3826 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3827 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3828 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3829 REASON_SET(&reason, PFRES_SYNPROXY);
3830 return (PF_SYNPROXY_DROP);
3837 uma_zfree(V_pf_state_key_z, sk);
3839 uma_zfree(V_pf_state_key_z, nk);
3842 struct pf_srchash *sh;
3844 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3845 PF_HASHROW_LOCK(sh);
3846 if (--sn->states == 0 && sn->expire == 0) {
3847 pf_unlink_src_node(sn);
3848 uma_zfree(V_pf_sources_z, sn);
3850 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3852 PF_HASHROW_UNLOCK(sh);
3855 if (nsn != sn && nsn != NULL) {
3856 struct pf_srchash *sh;
3858 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3859 PF_HASHROW_LOCK(sh);
3860 if (--nsn->states == 0 && nsn->expire == 0) {
3861 pf_unlink_src_node(nsn);
3862 uma_zfree(V_pf_sources_z, nsn);
3864 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3866 PF_HASHROW_UNLOCK(sh);
3873 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3874 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3875 struct pf_ruleset **rsm)
3877 struct pf_rule *r, *a = NULL;
3878 struct pf_ruleset *ruleset = NULL;
3879 sa_family_t af = pd->af;
3884 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3888 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3891 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3892 r = r->skip[PF_SKIP_IFP].ptr;
3893 else if (r->direction && r->direction != direction)
3894 r = r->skip[PF_SKIP_DIR].ptr;
3895 else if (r->af && r->af != af)
3896 r = r->skip[PF_SKIP_AF].ptr;
3897 else if (r->proto && r->proto != pd->proto)
3898 r = r->skip[PF_SKIP_PROTO].ptr;
3899 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3900 r->src.neg, kif, M_GETFIB(m)))
3901 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3902 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3903 r->dst.neg, NULL, M_GETFIB(m)))
3904 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3905 else if (r->tos && !(r->tos == pd->tos))
3906 r = TAILQ_NEXT(r, entries);
3907 else if (r->os_fingerprint != PF_OSFP_ANY)
3908 r = TAILQ_NEXT(r, entries);
3909 else if (pd->proto == IPPROTO_UDP &&
3910 (r->src.port_op || r->dst.port_op))
3911 r = TAILQ_NEXT(r, entries);
3912 else if (pd->proto == IPPROTO_TCP &&
3913 (r->src.port_op || r->dst.port_op || r->flagset))
3914 r = TAILQ_NEXT(r, entries);
3915 else if ((pd->proto == IPPROTO_ICMP ||
3916 pd->proto == IPPROTO_ICMPV6) &&
3917 (r->type || r->code))
3918 r = TAILQ_NEXT(r, entries);
3920 !pf_match_ieee8021q_pcp(r->prio, m))
3921 r = TAILQ_NEXT(r, entries);
3922 else if (r->prob && r->prob <=
3923 (arc4random() % (UINT_MAX - 1) + 1))
3924 r = TAILQ_NEXT(r, entries);
3925 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3926 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3927 r = TAILQ_NEXT(r, entries);
3929 if (r->anchor == NULL) {
3936 r = TAILQ_NEXT(r, entries);
3938 pf_step_into_anchor(anchor_stack, &asd,
3939 &ruleset, PF_RULESET_FILTER, &r, &a,
3942 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3943 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3950 REASON_SET(&reason, PFRES_MATCH);
3953 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3956 if (r->action != PF_PASS)
3959 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3960 REASON_SET(&reason, PFRES_MEMORY);
3968 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3969 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3970 struct pf_pdesc *pd, u_short *reason, int *copyback)
3972 struct tcphdr *th = pd->hdr.tcp;
3973 u_int16_t win = ntohs(th->th_win);
3974 u_int32_t ack, end, seq, orig_seq;
3978 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3979 sws = src->wscale & PF_WSCALE_MASK;
3980 dws = dst->wscale & PF_WSCALE_MASK;
3985 * Sequence tracking algorithm from Guido van Rooij's paper:
3986 * http://www.madison-gurkha.com/publications/tcp_filtering/
3990 orig_seq = seq = ntohl(th->th_seq);
3991 if (src->seqlo == 0) {
3992 /* First packet from this end. Set its state */
3994 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3995 src->scrub == NULL) {
3996 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3997 REASON_SET(reason, PFRES_MEMORY);
4002 /* Deferred generation of sequence number modulator */
4003 if (dst->seqdiff && !src->seqdiff) {
4004 /* use random iss for the TCP server */
4005 while ((src->seqdiff = arc4random() - seq) == 0)
4007 ack = ntohl(th->th_ack) - dst->seqdiff;
4008 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4010 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4013 ack = ntohl(th->th_ack);
4016 end = seq + pd->p_len;
4017 if (th->th_flags & TH_SYN) {
4019 if (dst->wscale & PF_WSCALE_FLAG) {
4020 src->wscale = pf_get_wscale(m, off, th->th_off,
4022 if (src->wscale & PF_WSCALE_FLAG) {
4023 /* Remove scale factor from initial
4025 sws = src->wscale & PF_WSCALE_MASK;
4026 win = ((u_int32_t)win + (1 << sws) - 1)
4028 dws = dst->wscale & PF_WSCALE_MASK;
4030 /* fixup other window */
4031 dst->max_win <<= dst->wscale &
4033 /* in case of a retrans SYN|ACK */
4038 if (th->th_flags & TH_FIN)
4042 if (src->state < TCPS_SYN_SENT)
4043 src->state = TCPS_SYN_SENT;
4046 * May need to slide the window (seqhi may have been set by
4047 * the crappy stack check or if we picked up the connection
4048 * after establishment)
4050 if (src->seqhi == 1 ||
4051 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4052 src->seqhi = end + MAX(1, dst->max_win << dws);
4053 if (win > src->max_win)
4057 ack = ntohl(th->th_ack) - dst->seqdiff;
4059 /* Modulate sequence numbers */
4060 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4062 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4065 end = seq + pd->p_len;
4066 if (th->th_flags & TH_SYN)
4068 if (th->th_flags & TH_FIN)
4072 if ((th->th_flags & TH_ACK) == 0) {
4073 /* Let it pass through the ack skew check */
4075 } else if ((ack == 0 &&
4076 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4077 /* broken tcp stacks do not set ack */
4078 (dst->state < TCPS_SYN_SENT)) {
4080 * Many stacks (ours included) will set the ACK number in an
4081 * FIN|ACK if the SYN times out -- no sequence to ACK.
4087 /* Ease sequencing restrictions on no data packets */
4092 ackskew = dst->seqlo - ack;
4096 * Need to demodulate the sequence numbers in any TCP SACK options
4097 * (Selective ACK). We could optionally validate the SACK values
4098 * against the current ACK window, either forwards or backwards, but
4099 * I'm not confident that SACK has been implemented properly
4100 * everywhere. It wouldn't surprise me if several stacks accidentally
4101 * SACK too far backwards of previously ACKed data. There really aren't
4102 * any security implications of bad SACKing unless the target stack
4103 * doesn't validate the option length correctly. Someone trying to
4104 * spoof into a TCP connection won't bother blindly sending SACK
4107 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4108 if (pf_modulate_sack(m, off, pd, th, dst))
4113 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4114 if (SEQ_GEQ(src->seqhi, end) &&
4115 /* Last octet inside other's window space */
4116 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4117 /* Retrans: not more than one window back */
4118 (ackskew >= -MAXACKWINDOW) &&
4119 /* Acking not more than one reassembled fragment backwards */
4120 (ackskew <= (MAXACKWINDOW << sws)) &&
4121 /* Acking not more than one window forward */
4122 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4123 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4124 (pd->flags & PFDESC_IP_REAS) == 0)) {
4125 /* Require an exact/+1 sequence match on resets when possible */
4127 if (dst->scrub || src->scrub) {
4128 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4129 *state, src, dst, copyback))
4133 /* update max window */
4134 if (src->max_win < win)
4136 /* synchronize sequencing */
4137 if (SEQ_GT(end, src->seqlo))
4139 /* slide the window of what the other end can send */
4140 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4141 dst->seqhi = ack + MAX((win << sws), 1);
4145 if (th->th_flags & TH_SYN)
4146 if (src->state < TCPS_SYN_SENT)
4147 src->state = TCPS_SYN_SENT;
4148 if (th->th_flags & TH_FIN)
4149 if (src->state < TCPS_CLOSING)
4150 src->state = TCPS_CLOSING;
4151 if (th->th_flags & TH_ACK) {
4152 if (dst->state == TCPS_SYN_SENT) {
4153 dst->state = TCPS_ESTABLISHED;
4154 if (src->state == TCPS_ESTABLISHED &&
4155 (*state)->src_node != NULL &&
4156 pf_src_connlimit(state)) {
4157 REASON_SET(reason, PFRES_SRCLIMIT);
4160 } else if (dst->state == TCPS_CLOSING)
4161 dst->state = TCPS_FIN_WAIT_2;
4163 if (th->th_flags & TH_RST)
4164 src->state = dst->state = TCPS_TIME_WAIT;
4166 /* update expire time */
4167 (*state)->expire = time_uptime;
4168 if (src->state >= TCPS_FIN_WAIT_2 &&
4169 dst->state >= TCPS_FIN_WAIT_2)
4170 (*state)->timeout = PFTM_TCP_CLOSED;
4171 else if (src->state >= TCPS_CLOSING &&
4172 dst->state >= TCPS_CLOSING)
4173 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4174 else if (src->state < TCPS_ESTABLISHED ||
4175 dst->state < TCPS_ESTABLISHED)
4176 (*state)->timeout = PFTM_TCP_OPENING;
4177 else if (src->state >= TCPS_CLOSING ||
4178 dst->state >= TCPS_CLOSING)
4179 (*state)->timeout = PFTM_TCP_CLOSING;
4181 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4183 /* Fall through to PASS packet */
4185 } else if ((dst->state < TCPS_SYN_SENT ||
4186 dst->state >= TCPS_FIN_WAIT_2 ||
4187 src->state >= TCPS_FIN_WAIT_2) &&
4188 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4189 /* Within a window forward of the originating packet */
4190 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4191 /* Within a window backward of the originating packet */
4194 * This currently handles three situations:
4195 * 1) Stupid stacks will shotgun SYNs before their peer
4197 * 2) When PF catches an already established stream (the
4198 * firewall rebooted, the state table was flushed, routes
4200 * 3) Packets get funky immediately after the connection
4201 * closes (this should catch Solaris spurious ACK|FINs
4202 * that web servers like to spew after a close)
4204 * This must be a little more careful than the above code
4205 * since packet floods will also be caught here. We don't
4206 * update the TTL here to mitigate the damage of a packet
4207 * flood and so the same code can handle awkward establishment
4208 * and a loosened connection close.
4209 * In the establishment case, a correct peer response will
4210 * validate the connection, go through the normal state code
4211 * and keep updating the state TTL.
4214 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4215 printf("pf: loose state match: ");
4216 pf_print_state(*state);
4217 pf_print_flags(th->th_flags);
4218 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4219 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4220 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4221 (unsigned long long)(*state)->packets[1],
4222 pd->dir == PF_IN ? "in" : "out",
4223 pd->dir == (*state)->direction ? "fwd" : "rev");
4226 if (dst->scrub || src->scrub) {
4227 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4228 *state, src, dst, copyback))
4232 /* update max window */
4233 if (src->max_win < win)
4235 /* synchronize sequencing */
4236 if (SEQ_GT(end, src->seqlo))
4238 /* slide the window of what the other end can send */
4239 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4240 dst->seqhi = ack + MAX((win << sws), 1);
4243 * Cannot set dst->seqhi here since this could be a shotgunned
4244 * SYN and not an already established connection.
4247 if (th->th_flags & TH_FIN)
4248 if (src->state < TCPS_CLOSING)
4249 src->state = TCPS_CLOSING;
4250 if (th->th_flags & TH_RST)
4251 src->state = dst->state = TCPS_TIME_WAIT;
4253 /* Fall through to PASS packet */
4256 if ((*state)->dst.state == TCPS_SYN_SENT &&
4257 (*state)->src.state == TCPS_SYN_SENT) {
4258 /* Send RST for state mismatches during handshake */
4259 if (!(th->th_flags & TH_RST))
4260 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4261 pd->dst, pd->src, th->th_dport,
4262 th->th_sport, ntohl(th->th_ack), 0,
4264 (*state)->rule.ptr->return_ttl, 1, 0,
4269 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4270 printf("pf: BAD state: ");
4271 pf_print_state(*state);
4272 pf_print_flags(th->th_flags);
4273 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4274 "pkts=%llu:%llu dir=%s,%s\n",
4275 seq, orig_seq, ack, pd->p_len, ackskew,
4276 (unsigned long long)(*state)->packets[0],
4277 (unsigned long long)(*state)->packets[1],
4278 pd->dir == PF_IN ? "in" : "out",
4279 pd->dir == (*state)->direction ? "fwd" : "rev");
4280 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4281 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4282 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4284 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4285 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4286 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4287 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4289 REASON_SET(reason, PFRES_BADSTATE);
4297 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4298 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4300 struct tcphdr *th = pd->hdr.tcp;
4302 if (th->th_flags & TH_SYN)
4303 if (src->state < TCPS_SYN_SENT)
4304 src->state = TCPS_SYN_SENT;
4305 if (th->th_flags & TH_FIN)
4306 if (src->state < TCPS_CLOSING)
4307 src->state = TCPS_CLOSING;
4308 if (th->th_flags & TH_ACK) {
4309 if (dst->state == TCPS_SYN_SENT) {
4310 dst->state = TCPS_ESTABLISHED;
4311 if (src->state == TCPS_ESTABLISHED &&
4312 (*state)->src_node != NULL &&
4313 pf_src_connlimit(state)) {
4314 REASON_SET(reason, PFRES_SRCLIMIT);
4317 } else if (dst->state == TCPS_CLOSING) {
4318 dst->state = TCPS_FIN_WAIT_2;
4319 } else if (src->state == TCPS_SYN_SENT &&
4320 dst->state < TCPS_SYN_SENT) {
4322 * Handle a special sloppy case where we only see one
4323 * half of the connection. If there is a ACK after
4324 * the initial SYN without ever seeing a packet from
4325 * the destination, set the connection to established.
4327 dst->state = src->state = TCPS_ESTABLISHED;
4328 if ((*state)->src_node != NULL &&
4329 pf_src_connlimit(state)) {
4330 REASON_SET(reason, PFRES_SRCLIMIT);
4333 } else if (src->state == TCPS_CLOSING &&
4334 dst->state == TCPS_ESTABLISHED &&
4337 * Handle the closing of half connections where we
4338 * don't see the full bidirectional FIN/ACK+ACK
4341 dst->state = TCPS_CLOSING;
4344 if (th->th_flags & TH_RST)
4345 src->state = dst->state = TCPS_TIME_WAIT;
4347 /* update expire time */
4348 (*state)->expire = time_uptime;
4349 if (src->state >= TCPS_FIN_WAIT_2 &&
4350 dst->state >= TCPS_FIN_WAIT_2)
4351 (*state)->timeout = PFTM_TCP_CLOSED;
4352 else if (src->state >= TCPS_CLOSING &&
4353 dst->state >= TCPS_CLOSING)
4354 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4355 else if (src->state < TCPS_ESTABLISHED ||
4356 dst->state < TCPS_ESTABLISHED)
4357 (*state)->timeout = PFTM_TCP_OPENING;
4358 else if (src->state >= TCPS_CLOSING ||
4359 dst->state >= TCPS_CLOSING)
4360 (*state)->timeout = PFTM_TCP_CLOSING;
4362 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4368 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4369 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4372 struct pf_state_key_cmp key;
4373 struct tcphdr *th = pd->hdr.tcp;
4375 struct pf_state_peer *src, *dst;
4376 struct pf_state_key *sk;
4378 bzero(&key, sizeof(key));
4380 key.proto = IPPROTO_TCP;
4381 if (direction == PF_IN) { /* wire side, straight */
4382 PF_ACPY(&key.addr[0], pd->src, key.af);
4383 PF_ACPY(&key.addr[1], pd->dst, key.af);
4384 key.port[0] = th->th_sport;
4385 key.port[1] = th->th_dport;
4386 } else { /* stack side, reverse */
4387 PF_ACPY(&key.addr[1], pd->src, key.af);
4388 PF_ACPY(&key.addr[0], pd->dst, key.af);
4389 key.port[1] = th->th_sport;
4390 key.port[0] = th->th_dport;
4393 STATE_LOOKUP(kif, &key, direction, *state, pd);
4395 if (direction == (*state)->direction) {
4396 src = &(*state)->src;
4397 dst = &(*state)->dst;
4399 src = &(*state)->dst;
4400 dst = &(*state)->src;
4403 sk = (*state)->key[pd->didx];
4405 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4406 if (direction != (*state)->direction) {
4407 REASON_SET(reason, PFRES_SYNPROXY);
4408 return (PF_SYNPROXY_DROP);
4410 if (th->th_flags & TH_SYN) {
4411 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4412 REASON_SET(reason, PFRES_SYNPROXY);
4415 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4416 pd->src, th->th_dport, th->th_sport,
4417 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4418 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4419 REASON_SET(reason, PFRES_SYNPROXY);
4420 return (PF_SYNPROXY_DROP);
4421 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4422 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4423 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4424 REASON_SET(reason, PFRES_SYNPROXY);
4426 } else if ((*state)->src_node != NULL &&
4427 pf_src_connlimit(state)) {
4428 REASON_SET(reason, PFRES_SRCLIMIT);
4431 (*state)->src.state = PF_TCPS_PROXY_DST;
4433 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4434 if (direction == (*state)->direction) {
4435 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4436 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4437 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4438 REASON_SET(reason, PFRES_SYNPROXY);
4441 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4442 if ((*state)->dst.seqhi == 1)
4443 (*state)->dst.seqhi = htonl(arc4random());
4444 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4445 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4446 sk->port[pd->sidx], sk->port[pd->didx],
4447 (*state)->dst.seqhi, 0, TH_SYN, 0,
4448 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4449 REASON_SET(reason, PFRES_SYNPROXY);
4450 return (PF_SYNPROXY_DROP);
4451 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4453 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4454 REASON_SET(reason, PFRES_SYNPROXY);
4457 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4458 (*state)->dst.seqlo = ntohl(th->th_seq);
4459 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4460 pd->src, th->th_dport, th->th_sport,
4461 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4462 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4463 (*state)->tag, NULL);
4464 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4465 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4466 sk->port[pd->sidx], sk->port[pd->didx],
4467 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4468 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4469 (*state)->src.seqdiff = (*state)->dst.seqhi -
4470 (*state)->src.seqlo;
4471 (*state)->dst.seqdiff = (*state)->src.seqhi -
4472 (*state)->dst.seqlo;
4473 (*state)->src.seqhi = (*state)->src.seqlo +
4474 (*state)->dst.max_win;
4475 (*state)->dst.seqhi = (*state)->dst.seqlo +
4476 (*state)->src.max_win;
4477 (*state)->src.wscale = (*state)->dst.wscale = 0;
4478 (*state)->src.state = (*state)->dst.state =
4480 REASON_SET(reason, PFRES_SYNPROXY);
4481 return (PF_SYNPROXY_DROP);
4485 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4486 dst->state >= TCPS_FIN_WAIT_2 &&
4487 src->state >= TCPS_FIN_WAIT_2) {
4488 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4489 printf("pf: state reuse ");
4490 pf_print_state(*state);
4491 pf_print_flags(th->th_flags);
4494 /* XXX make sure it's the same direction ?? */
4495 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4496 pf_unlink_state(*state, PF_ENTER_LOCKED);
4501 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4502 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4505 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4506 ©back) == PF_DROP)
4510 /* translate source/destination address, if necessary */
4511 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4512 struct pf_state_key *nk = (*state)->key[pd->didx];
4514 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4515 nk->port[pd->sidx] != th->th_sport)
4516 pf_change_ap(m, pd->src, &th->th_sport,
4517 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4518 nk->port[pd->sidx], 0, pd->af);
4520 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4521 nk->port[pd->didx] != th->th_dport)
4522 pf_change_ap(m, pd->dst, &th->th_dport,
4523 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4524 nk->port[pd->didx], 0, pd->af);
4528 /* Copyback sequence modulation or stateful scrub changes if needed */
4530 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4536 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4537 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4539 struct pf_state_peer *src, *dst;
4540 struct pf_state_key_cmp key;
4541 struct udphdr *uh = pd->hdr.udp;
4543 bzero(&key, sizeof(key));
4545 key.proto = IPPROTO_UDP;
4546 if (direction == PF_IN) { /* wire side, straight */
4547 PF_ACPY(&key.addr[0], pd->src, key.af);
4548 PF_ACPY(&key.addr[1], pd->dst, key.af);
4549 key.port[0] = uh->uh_sport;
4550 key.port[1] = uh->uh_dport;
4551 } else { /* stack side, reverse */
4552 PF_ACPY(&key.addr[1], pd->src, key.af);
4553 PF_ACPY(&key.addr[0], pd->dst, key.af);
4554 key.port[1] = uh->uh_sport;
4555 key.port[0] = uh->uh_dport;
4558 STATE_LOOKUP(kif, &key, direction, *state, pd);
4560 if (direction == (*state)->direction) {
4561 src = &(*state)->src;
4562 dst = &(*state)->dst;
4564 src = &(*state)->dst;
4565 dst = &(*state)->src;
4569 if (src->state < PFUDPS_SINGLE)
4570 src->state = PFUDPS_SINGLE;
4571 if (dst->state == PFUDPS_SINGLE)
4572 dst->state = PFUDPS_MULTIPLE;
4574 /* update expire time */
4575 (*state)->expire = time_uptime;
4576 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4577 (*state)->timeout = PFTM_UDP_MULTIPLE;
4579 (*state)->timeout = PFTM_UDP_SINGLE;
4581 /* translate source/destination address, if necessary */
4582 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4583 struct pf_state_key *nk = (*state)->key[pd->didx];
4585 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4586 nk->port[pd->sidx] != uh->uh_sport)
4587 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4588 &uh->uh_sum, &nk->addr[pd->sidx],
4589 nk->port[pd->sidx], 1, pd->af);
4591 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4592 nk->port[pd->didx] != uh->uh_dport)
4593 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4594 &uh->uh_sum, &nk->addr[pd->didx],
4595 nk->port[pd->didx], 1, pd->af);
4596 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4603 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4604 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4606 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4607 u_int16_t icmpid = 0, *icmpsum;
4608 u_int8_t icmptype, icmpcode;
4610 struct pf_state_key_cmp key;
4612 bzero(&key, sizeof(key));
4613 switch (pd->proto) {
4616 icmptype = pd->hdr.icmp->icmp_type;
4617 icmpcode = pd->hdr.icmp->icmp_code;
4618 icmpid = pd->hdr.icmp->icmp_id;
4619 icmpsum = &pd->hdr.icmp->icmp_cksum;
4621 if (icmptype == ICMP_UNREACH ||
4622 icmptype == ICMP_SOURCEQUENCH ||
4623 icmptype == ICMP_REDIRECT ||
4624 icmptype == ICMP_TIMXCEED ||
4625 icmptype == ICMP_PARAMPROB)
4630 case IPPROTO_ICMPV6:
4631 icmptype = pd->hdr.icmp6->icmp6_type;
4632 icmpcode = pd->hdr.icmp6->icmp6_code;
4633 icmpid = pd->hdr.icmp6->icmp6_id;
4634 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4636 if (icmptype == ICMP6_DST_UNREACH ||
4637 icmptype == ICMP6_PACKET_TOO_BIG ||
4638 icmptype == ICMP6_TIME_EXCEEDED ||
4639 icmptype == ICMP6_PARAM_PROB)
4648 * ICMP query/reply message not related to a TCP/UDP packet.
4649 * Search for an ICMP state.
4652 key.proto = pd->proto;
4653 key.port[0] = key.port[1] = icmpid;
4654 if (direction == PF_IN) { /* wire side, straight */
4655 PF_ACPY(&key.addr[0], pd->src, key.af);
4656 PF_ACPY(&key.addr[1], pd->dst, key.af);
4657 } else { /* stack side, reverse */
4658 PF_ACPY(&key.addr[1], pd->src, key.af);
4659 PF_ACPY(&key.addr[0], pd->dst, key.af);
4662 STATE_LOOKUP(kif, &key, direction, *state, pd);
4664 (*state)->expire = time_uptime;
4665 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4667 /* translate source/destination address, if necessary */
4668 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4669 struct pf_state_key *nk = (*state)->key[pd->didx];
4674 if (PF_ANEQ(pd->src,
4675 &nk->addr[pd->sidx], AF_INET))
4676 pf_change_a(&saddr->v4.s_addr,
4678 nk->addr[pd->sidx].v4.s_addr, 0);
4680 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4682 pf_change_a(&daddr->v4.s_addr,
4684 nk->addr[pd->didx].v4.s_addr, 0);
4687 pd->hdr.icmp->icmp_id) {
4688 pd->hdr.icmp->icmp_cksum =
4690 pd->hdr.icmp->icmp_cksum, icmpid,
4691 nk->port[pd->sidx], 0);
4692 pd->hdr.icmp->icmp_id =
4696 m_copyback(m, off, ICMP_MINLEN,
4697 (caddr_t )pd->hdr.icmp);
4702 if (PF_ANEQ(pd->src,
4703 &nk->addr[pd->sidx], AF_INET6))
4705 &pd->hdr.icmp6->icmp6_cksum,
4706 &nk->addr[pd->sidx], 0);
4708 if (PF_ANEQ(pd->dst,
4709 &nk->addr[pd->didx], AF_INET6))
4711 &pd->hdr.icmp6->icmp6_cksum,
4712 &nk->addr[pd->didx], 0);
4714 m_copyback(m, off, sizeof(struct icmp6_hdr),
4715 (caddr_t )pd->hdr.icmp6);
4724 * ICMP error message in response to a TCP/UDP packet.
4725 * Extract the inner TCP/UDP header and search for that state.
4728 struct pf_pdesc pd2;
4729 bzero(&pd2, sizeof pd2);
4734 struct ip6_hdr h2_6;
4741 /* Payload packet is from the opposite direction. */
4742 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4743 pd2.didx = (direction == PF_IN) ? 0 : 1;
4747 /* offset of h2 in mbuf chain */
4748 ipoff2 = off + ICMP_MINLEN;
4750 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4751 NULL, reason, pd2.af)) {
4752 DPFPRINTF(PF_DEBUG_MISC,
4753 ("pf: ICMP error message too short "
4758 * ICMP error messages don't refer to non-first
4761 if (h2.ip_off & htons(IP_OFFMASK)) {
4762 REASON_SET(reason, PFRES_FRAG);
4766 /* offset of protocol header that follows h2 */
4767 off2 = ipoff2 + (h2.ip_hl << 2);
4769 pd2.proto = h2.ip_p;
4770 pd2.src = (struct pf_addr *)&h2.ip_src;
4771 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4772 pd2.ip_sum = &h2.ip_sum;
4777 ipoff2 = off + sizeof(struct icmp6_hdr);
4779 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4780 NULL, reason, pd2.af)) {
4781 DPFPRINTF(PF_DEBUG_MISC,
4782 ("pf: ICMP error message too short "
4786 pd2.proto = h2_6.ip6_nxt;
4787 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4788 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4790 off2 = ipoff2 + sizeof(h2_6);
4792 switch (pd2.proto) {
4793 case IPPROTO_FRAGMENT:
4795 * ICMPv6 error messages for
4796 * non-first fragments
4798 REASON_SET(reason, PFRES_FRAG);
4801 case IPPROTO_HOPOPTS:
4802 case IPPROTO_ROUTING:
4803 case IPPROTO_DSTOPTS: {
4804 /* get next header and header length */
4805 struct ip6_ext opt6;
4807 if (!pf_pull_hdr(m, off2, &opt6,
4808 sizeof(opt6), NULL, reason,
4810 DPFPRINTF(PF_DEBUG_MISC,
4811 ("pf: ICMPv6 short opt\n"));
4814 if (pd2.proto == IPPROTO_AH)
4815 off2 += (opt6.ip6e_len + 2) * 4;
4817 off2 += (opt6.ip6e_len + 1) * 8;
4818 pd2.proto = opt6.ip6e_nxt;
4819 /* goto the next header */
4826 } while (!terminal);
4831 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4832 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4833 printf("pf: BAD ICMP %d:%d outer dst: ",
4834 icmptype, icmpcode);
4835 pf_print_host(pd->src, 0, pd->af);
4837 pf_print_host(pd->dst, 0, pd->af);
4838 printf(" inner src: ");
4839 pf_print_host(pd2.src, 0, pd2.af);
4841 pf_print_host(pd2.dst, 0, pd2.af);
4844 REASON_SET(reason, PFRES_BADSTATE);
4848 switch (pd2.proto) {
4852 struct pf_state_peer *src, *dst;
4857 * Only the first 8 bytes of the TCP header can be
4858 * expected. Don't access any TCP header fields after
4859 * th_seq, an ackskew test is not possible.
4861 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4863 DPFPRINTF(PF_DEBUG_MISC,
4864 ("pf: ICMP error message too short "
4870 key.proto = IPPROTO_TCP;
4871 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4872 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4873 key.port[pd2.sidx] = th.th_sport;
4874 key.port[pd2.didx] = th.th_dport;
4876 STATE_LOOKUP(kif, &key, direction, *state, pd);
4878 if (direction == (*state)->direction) {
4879 src = &(*state)->dst;
4880 dst = &(*state)->src;
4882 src = &(*state)->src;
4883 dst = &(*state)->dst;
4886 if (src->wscale && dst->wscale)
4887 dws = dst->wscale & PF_WSCALE_MASK;
4891 /* Demodulate sequence number */
4892 seq = ntohl(th.th_seq) - src->seqdiff;
4894 pf_change_a(&th.th_seq, icmpsum,
4899 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4900 (!SEQ_GEQ(src->seqhi, seq) ||
4901 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4902 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4903 printf("pf: BAD ICMP %d:%d ",
4904 icmptype, icmpcode);
4905 pf_print_host(pd->src, 0, pd->af);
4907 pf_print_host(pd->dst, 0, pd->af);
4909 pf_print_state(*state);
4910 printf(" seq=%u\n", seq);
4912 REASON_SET(reason, PFRES_BADSTATE);
4915 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4916 printf("pf: OK ICMP %d:%d ",
4917 icmptype, icmpcode);
4918 pf_print_host(pd->src, 0, pd->af);
4920 pf_print_host(pd->dst, 0, pd->af);
4922 pf_print_state(*state);
4923 printf(" seq=%u\n", seq);
4927 /* translate source/destination address, if necessary */
4928 if ((*state)->key[PF_SK_WIRE] !=
4929 (*state)->key[PF_SK_STACK]) {
4930 struct pf_state_key *nk =
4931 (*state)->key[pd->didx];
4933 if (PF_ANEQ(pd2.src,
4934 &nk->addr[pd2.sidx], pd2.af) ||
4935 nk->port[pd2.sidx] != th.th_sport)
4936 pf_change_icmp(pd2.src, &th.th_sport,
4937 daddr, &nk->addr[pd2.sidx],
4938 nk->port[pd2.sidx], NULL,
4939 pd2.ip_sum, icmpsum,
4940 pd->ip_sum, 0, pd2.af);
4942 if (PF_ANEQ(pd2.dst,
4943 &nk->addr[pd2.didx], pd2.af) ||
4944 nk->port[pd2.didx] != th.th_dport)
4945 pf_change_icmp(pd2.dst, &th.th_dport,
4946 saddr, &nk->addr[pd2.didx],
4947 nk->port[pd2.didx], NULL,
4948 pd2.ip_sum, icmpsum,
4949 pd->ip_sum, 0, pd2.af);
4957 m_copyback(m, off, ICMP_MINLEN,
4958 (caddr_t )pd->hdr.icmp);
4959 m_copyback(m, ipoff2, sizeof(h2),
4966 sizeof(struct icmp6_hdr),
4967 (caddr_t )pd->hdr.icmp6);
4968 m_copyback(m, ipoff2, sizeof(h2_6),
4973 m_copyback(m, off2, 8, (caddr_t)&th);
4982 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4983 NULL, reason, pd2.af)) {
4984 DPFPRINTF(PF_DEBUG_MISC,
4985 ("pf: ICMP error message too short "
4991 key.proto = IPPROTO_UDP;
4992 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4993 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4994 key.port[pd2.sidx] = uh.uh_sport;
4995 key.port[pd2.didx] = uh.uh_dport;
4997 STATE_LOOKUP(kif, &key, direction, *state, pd);
4999 /* translate source/destination address, if necessary */
5000 if ((*state)->key[PF_SK_WIRE] !=
5001 (*state)->key[PF_SK_STACK]) {
5002 struct pf_state_key *nk =
5003 (*state)->key[pd->didx];
5005 if (PF_ANEQ(pd2.src,
5006 &nk->addr[pd2.sidx], pd2.af) ||
5007 nk->port[pd2.sidx] != uh.uh_sport)
5008 pf_change_icmp(pd2.src, &uh.uh_sport,
5009 daddr, &nk->addr[pd2.sidx],
5010 nk->port[pd2.sidx], &uh.uh_sum,
5011 pd2.ip_sum, icmpsum,
5012 pd->ip_sum, 1, pd2.af);
5014 if (PF_ANEQ(pd2.dst,
5015 &nk->addr[pd2.didx], pd2.af) ||
5016 nk->port[pd2.didx] != uh.uh_dport)
5017 pf_change_icmp(pd2.dst, &uh.uh_dport,
5018 saddr, &nk->addr[pd2.didx],
5019 nk->port[pd2.didx], &uh.uh_sum,
5020 pd2.ip_sum, icmpsum,
5021 pd->ip_sum, 1, pd2.af);
5026 m_copyback(m, off, ICMP_MINLEN,
5027 (caddr_t )pd->hdr.icmp);
5028 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5034 sizeof(struct icmp6_hdr),
5035 (caddr_t )pd->hdr.icmp6);
5036 m_copyback(m, ipoff2, sizeof(h2_6),
5041 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5047 case IPPROTO_ICMP: {
5050 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5051 NULL, reason, pd2.af)) {
5052 DPFPRINTF(PF_DEBUG_MISC,
5053 ("pf: ICMP error message too short i"
5059 key.proto = IPPROTO_ICMP;
5060 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5061 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5062 key.port[0] = key.port[1] = iih.icmp_id;
5064 STATE_LOOKUP(kif, &key, direction, *state, pd);
5066 /* translate source/destination address, if necessary */
5067 if ((*state)->key[PF_SK_WIRE] !=
5068 (*state)->key[PF_SK_STACK]) {
5069 struct pf_state_key *nk =
5070 (*state)->key[pd->didx];
5072 if (PF_ANEQ(pd2.src,
5073 &nk->addr[pd2.sidx], pd2.af) ||
5074 nk->port[pd2.sidx] != iih.icmp_id)
5075 pf_change_icmp(pd2.src, &iih.icmp_id,
5076 daddr, &nk->addr[pd2.sidx],
5077 nk->port[pd2.sidx], NULL,
5078 pd2.ip_sum, icmpsum,
5079 pd->ip_sum, 0, AF_INET);
5081 if (PF_ANEQ(pd2.dst,
5082 &nk->addr[pd2.didx], pd2.af) ||
5083 nk->port[pd2.didx] != iih.icmp_id)
5084 pf_change_icmp(pd2.dst, &iih.icmp_id,
5085 saddr, &nk->addr[pd2.didx],
5086 nk->port[pd2.didx], NULL,
5087 pd2.ip_sum, icmpsum,
5088 pd->ip_sum, 0, AF_INET);
5090 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5091 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5092 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5099 case IPPROTO_ICMPV6: {
5100 struct icmp6_hdr iih;
5102 if (!pf_pull_hdr(m, off2, &iih,
5103 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5104 DPFPRINTF(PF_DEBUG_MISC,
5105 ("pf: ICMP error message too short "
5111 key.proto = IPPROTO_ICMPV6;
5112 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5113 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5114 key.port[0] = key.port[1] = iih.icmp6_id;
5116 STATE_LOOKUP(kif, &key, direction, *state, pd);
5118 /* translate source/destination address, if necessary */
5119 if ((*state)->key[PF_SK_WIRE] !=
5120 (*state)->key[PF_SK_STACK]) {
5121 struct pf_state_key *nk =
5122 (*state)->key[pd->didx];
5124 if (PF_ANEQ(pd2.src,
5125 &nk->addr[pd2.sidx], pd2.af) ||
5126 nk->port[pd2.sidx] != iih.icmp6_id)
5127 pf_change_icmp(pd2.src, &iih.icmp6_id,
5128 daddr, &nk->addr[pd2.sidx],
5129 nk->port[pd2.sidx], NULL,
5130 pd2.ip_sum, icmpsum,
5131 pd->ip_sum, 0, AF_INET6);
5133 if (PF_ANEQ(pd2.dst,
5134 &nk->addr[pd2.didx], pd2.af) ||
5135 nk->port[pd2.didx] != iih.icmp6_id)
5136 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5137 saddr, &nk->addr[pd2.didx],
5138 nk->port[pd2.didx], NULL,
5139 pd2.ip_sum, icmpsum,
5140 pd->ip_sum, 0, AF_INET6);
5142 m_copyback(m, off, sizeof(struct icmp6_hdr),
5143 (caddr_t)pd->hdr.icmp6);
5144 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5145 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5154 key.proto = pd2.proto;
5155 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5156 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5157 key.port[0] = key.port[1] = 0;
5159 STATE_LOOKUP(kif, &key, direction, *state, pd);
5161 /* translate source/destination address, if necessary */
5162 if ((*state)->key[PF_SK_WIRE] !=
5163 (*state)->key[PF_SK_STACK]) {
5164 struct pf_state_key *nk =
5165 (*state)->key[pd->didx];
5167 if (PF_ANEQ(pd2.src,
5168 &nk->addr[pd2.sidx], pd2.af))
5169 pf_change_icmp(pd2.src, NULL, daddr,
5170 &nk->addr[pd2.sidx], 0, NULL,
5171 pd2.ip_sum, icmpsum,
5172 pd->ip_sum, 0, pd2.af);
5174 if (PF_ANEQ(pd2.dst,
5175 &nk->addr[pd2.didx], pd2.af))
5176 pf_change_icmp(pd2.dst, NULL, saddr,
5177 &nk->addr[pd2.didx], 0, NULL,
5178 pd2.ip_sum, icmpsum,
5179 pd->ip_sum, 0, pd2.af);
5184 m_copyback(m, off, ICMP_MINLEN,
5185 (caddr_t)pd->hdr.icmp);
5186 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5192 sizeof(struct icmp6_hdr),
5193 (caddr_t )pd->hdr.icmp6);
5194 m_copyback(m, ipoff2, sizeof(h2_6),
5208 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5209 struct mbuf *m, struct pf_pdesc *pd)
5211 struct pf_state_peer *src, *dst;
5212 struct pf_state_key_cmp key;
5214 bzero(&key, sizeof(key));
5216 key.proto = pd->proto;
5217 if (direction == PF_IN) {
5218 PF_ACPY(&key.addr[0], pd->src, key.af);
5219 PF_ACPY(&key.addr[1], pd->dst, key.af);
5220 key.port[0] = key.port[1] = 0;
5222 PF_ACPY(&key.addr[1], pd->src, key.af);
5223 PF_ACPY(&key.addr[0], pd->dst, key.af);
5224 key.port[1] = key.port[0] = 0;
5227 STATE_LOOKUP(kif, &key, direction, *state, pd);
5229 if (direction == (*state)->direction) {
5230 src = &(*state)->src;
5231 dst = &(*state)->dst;
5233 src = &(*state)->dst;
5234 dst = &(*state)->src;
5238 if (src->state < PFOTHERS_SINGLE)
5239 src->state = PFOTHERS_SINGLE;
5240 if (dst->state == PFOTHERS_SINGLE)
5241 dst->state = PFOTHERS_MULTIPLE;
5243 /* update expire time */
5244 (*state)->expire = time_uptime;
5245 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5246 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5248 (*state)->timeout = PFTM_OTHER_SINGLE;
5250 /* translate source/destination address, if necessary */
5251 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5252 struct pf_state_key *nk = (*state)->key[pd->didx];
5254 KASSERT(nk, ("%s: nk is null", __func__));
5255 KASSERT(pd, ("%s: pd is null", __func__));
5256 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5257 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5261 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5262 pf_change_a(&pd->src->v4.s_addr,
5264 nk->addr[pd->sidx].v4.s_addr,
5268 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5269 pf_change_a(&pd->dst->v4.s_addr,
5271 nk->addr[pd->didx].v4.s_addr,
5278 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5279 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5281 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5282 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5290 * ipoff and off are measured from the start of the mbuf chain.
5291 * h must be at "ipoff" on the mbuf chain.
5294 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5295 u_short *actionp, u_short *reasonp, sa_family_t af)
5300 struct ip *h = mtod(m, struct ip *);
5301 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5305 ACTION_SET(actionp, PF_PASS);
5307 ACTION_SET(actionp, PF_DROP);
5308 REASON_SET(reasonp, PFRES_FRAG);
5312 if (m->m_pkthdr.len < off + len ||
5313 ntohs(h->ip_len) < off + len) {
5314 ACTION_SET(actionp, PF_DROP);
5315 REASON_SET(reasonp, PFRES_SHORT);
5323 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5325 if (m->m_pkthdr.len < off + len ||
5326 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5327 (unsigned)(off + len)) {
5328 ACTION_SET(actionp, PF_DROP);
5329 REASON_SET(reasonp, PFRES_SHORT);
5336 m_copydata(m, off, len, p);
5342 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5345 struct radix_node_head *rnh;
5346 struct sockaddr_in *dst;
5350 struct sockaddr_in6 *dst6;
5351 struct route_in6 ro;
5355 struct radix_node *rn;
5360 /* XXX: stick to table 0 for now */
5361 rnh = rt_tables_get_rnh(0, af);
5362 if (rnh != NULL && rn_mpath_capable(rnh))
5364 bzero(&ro, sizeof(ro));
5367 dst = satosin(&ro.ro_dst);
5368 dst->sin_family = AF_INET;
5369 dst->sin_len = sizeof(*dst);
5370 dst->sin_addr = addr->v4;
5375 * Skip check for addresses with embedded interface scope,
5376 * as they would always match anyway.
5378 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5380 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5381 dst6->sin6_family = AF_INET6;
5382 dst6->sin6_len = sizeof(*dst6);
5383 dst6->sin6_addr = addr->v6;
5390 /* Skip checks for ipsec interfaces */
5391 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5397 in6_rtalloc_ign(&ro, 0, rtableid);
5402 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5407 if (ro.ro_rt != NULL) {
5408 /* No interface given, this is a no-route check */
5412 if (kif->pfik_ifp == NULL) {
5417 /* Perform uRPF check if passed input interface */
5419 rn = (struct radix_node *)ro.ro_rt;
5421 rt = (struct rtentry *)rn;
5424 if (kif->pfik_ifp == ifp)
5426 rn = rn_mpath_next(rn);
5427 } while (check_mpath == 1 && rn != NULL && ret == 0);
5431 if (ro.ro_rt != NULL)
5438 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5442 struct nhop4_basic nh4;
5445 struct nhop6_basic nh6;
5449 struct radix_node_head *rnh;
5451 /* XXX: stick to table 0 for now */
5452 rnh = rt_tables_get_rnh(0, af);
5453 if (rnh != NULL && rn_mpath_capable(rnh))
5454 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5457 * Skip check for addresses with embedded interface scope,
5458 * as they would always match anyway.
5460 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5463 if (af != AF_INET && af != AF_INET6)
5466 /* Skip checks for ipsec interfaces */
5467 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5475 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5482 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5489 /* No interface given, this is a no-route check */
5493 if (kif->pfik_ifp == NULL)
5496 /* Perform uRPF check if passed input interface */
5497 if (kif->pfik_ifp == ifp)
5504 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5505 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5507 struct mbuf *m0, *m1;
5508 struct sockaddr_in dst;
5510 struct ifnet *ifp = NULL;
5511 struct pf_addr naddr;
5512 struct pf_src_node *sn = NULL;
5514 uint16_t ip_len, ip_off;
5516 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5517 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5520 if ((pd->pf_mtag == NULL &&
5521 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5522 pd->pf_mtag->routed++ > 3) {
5528 if (r->rt == PF_DUPTO) {
5529 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5535 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5543 ip = mtod(m0, struct ip *);
5545 bzero(&dst, sizeof(dst));
5546 dst.sin_family = AF_INET;
5547 dst.sin_len = sizeof(dst);
5548 dst.sin_addr = ip->ip_dst;
5550 bzero(&naddr, sizeof(naddr));
5552 if (TAILQ_EMPTY(&r->rpool.list)) {
5553 DPFPRINTF(PF_DEBUG_URGENT,
5554 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5558 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5560 if (!PF_AZERO(&naddr, AF_INET))
5561 dst.sin_addr.s_addr = naddr.v4.s_addr;
5562 ifp = r->rpool.cur->kif ?
5563 r->rpool.cur->kif->pfik_ifp : NULL;
5565 if (!PF_AZERO(&s->rt_addr, AF_INET))
5566 dst.sin_addr.s_addr =
5567 s->rt_addr.v4.s_addr;
5568 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5575 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5577 else if (m0 == NULL)
5579 if (m0->m_len < sizeof(struct ip)) {
5580 DPFPRINTF(PF_DEBUG_URGENT,
5581 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5584 ip = mtod(m0, struct ip *);
5587 if (ifp->if_flags & IFF_LOOPBACK)
5588 m0->m_flags |= M_SKIP_FIREWALL;
5590 ip_len = ntohs(ip->ip_len);
5591 ip_off = ntohs(ip->ip_off);
5593 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5594 m0->m_pkthdr.csum_flags |= CSUM_IP;
5595 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5596 in_delayed_cksum(m0);
5597 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5600 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5601 sctp_delayed_cksum(m0, (uint32_t)(ip->ip_hl << 2));
5602 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5607 * If small enough for interface, or the interface will take
5608 * care of the fragmentation for us, we can just send directly.
5610 if (ip_len <= ifp->if_mtu ||
5611 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5613 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5614 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5615 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5617 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5618 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5622 /* Balk when DF bit is set or the interface didn't support TSO. */
5623 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5625 KMOD_IPSTAT_INC(ips_cantfrag);
5626 if (r->rt != PF_DUPTO) {
5627 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5634 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5638 for (; m0; m0 = m1) {
5640 m0->m_nextpkt = NULL;
5642 m_clrprotoflags(m0);
5643 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5649 KMOD_IPSTAT_INC(ips_fragmented);
5652 if (r->rt != PF_DUPTO)
5667 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5668 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5671 struct sockaddr_in6 dst;
5672 struct ip6_hdr *ip6;
5673 struct ifnet *ifp = NULL;
5674 struct pf_addr naddr;
5675 struct pf_src_node *sn = NULL;
5677 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5678 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5681 if ((pd->pf_mtag == NULL &&
5682 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5683 pd->pf_mtag->routed++ > 3) {
5689 if (r->rt == PF_DUPTO) {
5690 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5696 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5704 ip6 = mtod(m0, struct ip6_hdr *);
5706 bzero(&dst, sizeof(dst));
5707 dst.sin6_family = AF_INET6;
5708 dst.sin6_len = sizeof(dst);
5709 dst.sin6_addr = ip6->ip6_dst;
5711 bzero(&naddr, sizeof(naddr));
5713 if (TAILQ_EMPTY(&r->rpool.list)) {
5714 DPFPRINTF(PF_DEBUG_URGENT,
5715 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5719 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5721 if (!PF_AZERO(&naddr, AF_INET6))
5722 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5724 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5726 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5727 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5728 &s->rt_addr, AF_INET6);
5729 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5739 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5741 else if (m0 == NULL)
5743 if (m0->m_len < sizeof(struct ip6_hdr)) {
5744 DPFPRINTF(PF_DEBUG_URGENT,
5745 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5749 ip6 = mtod(m0, struct ip6_hdr *);
5752 if (ifp->if_flags & IFF_LOOPBACK)
5753 m0->m_flags |= M_SKIP_FIREWALL;
5755 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5756 ~ifp->if_hwassist) {
5757 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5758 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5759 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5763 * If the packet is too large for the outgoing interface,
5764 * send back an icmp6 error.
5766 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5767 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5768 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5769 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5771 in6_ifstat_inc(ifp, ifs6_in_toobig);
5772 if (r->rt != PF_DUPTO)
5773 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5779 if (r->rt != PF_DUPTO)
5793 * FreeBSD supports cksum offloads for the following drivers.
5794 * em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5796 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5797 * network driver performed cksum including pseudo header, need to verify
5800 * network driver performed cksum, needs to additional pseudo header
5801 * cksum computation with partial csum_data(i.e. lack of H/W support for
5802 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5804 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5805 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5807 * Also, set csum_data to 0xffff to force cksum validation.
5810 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5816 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5818 if (m->m_pkthdr.len < off + len)
5823 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5824 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5825 sum = m->m_pkthdr.csum_data;
5827 ip = mtod(m, struct ip *);
5828 sum = in_pseudo(ip->ip_src.s_addr,
5829 ip->ip_dst.s_addr, htonl((u_short)len +
5830 m->m_pkthdr.csum_data + IPPROTO_TCP));
5837 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5838 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5839 sum = m->m_pkthdr.csum_data;
5841 ip = mtod(m, struct ip *);
5842 sum = in_pseudo(ip->ip_src.s_addr,
5843 ip->ip_dst.s_addr, htonl((u_short)len +
5844 m->m_pkthdr.csum_data + IPPROTO_UDP));
5852 case IPPROTO_ICMPV6:
5862 if (p == IPPROTO_ICMP) {
5867 sum = in_cksum(m, len);
5871 if (m->m_len < sizeof(struct ip))
5873 sum = in4_cksum(m, p, off, len);
5878 if (m->m_len < sizeof(struct ip6_hdr))
5880 sum = in6_cksum(m, p, off, len);
5891 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5896 KMOD_UDPSTAT_INC(udps_badsum);
5902 KMOD_ICMPSTAT_INC(icps_checksum);
5907 case IPPROTO_ICMPV6:
5909 KMOD_ICMP6STAT_INC(icp6s_checksum);
5916 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5917 m->m_pkthdr.csum_flags |=
5918 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5919 m->m_pkthdr.csum_data = 0xffff;
5928 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5930 struct pfi_kif *kif;
5931 u_short action, reason = 0, log = 0;
5932 struct mbuf *m = *m0;
5933 struct ip *h = NULL;
5934 struct m_tag *ipfwtag;
5935 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5936 struct pf_state *s = NULL;
5937 struct pf_ruleset *ruleset = NULL;
5939 int off, dirndx, pqid = 0;
5941 PF_RULES_RLOCK_TRACKER;
5945 if (!V_pf_status.running)
5948 memset(&pd, 0, sizeof(pd));
5950 kif = (struct pfi_kif *)ifp->if_pf_kif;
5953 DPFPRINTF(PF_DEBUG_URGENT,
5954 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5957 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5960 if (m->m_flags & M_SKIP_FIREWALL)
5963 pd.pf_mtag = pf_find_mtag(m);
5967 if (ip_divert_ptr != NULL &&
5968 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5969 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5970 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5971 if (pd.pf_mtag == NULL &&
5972 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5976 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5977 m_tag_delete(m, ipfwtag);
5979 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5980 m->m_flags |= M_FASTFWD_OURS;
5981 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5983 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5984 /* We do IP header normalization and packet reassembly here */
5988 m = *m0; /* pf_normalize messes with m0 */
5989 h = mtod(m, struct ip *);
5991 off = h->ip_hl << 2;
5992 if (off < (int)sizeof(struct ip)) {
5994 REASON_SET(&reason, PFRES_SHORT);
5999 pd.src = (struct pf_addr *)&h->ip_src;
6000 pd.dst = (struct pf_addr *)&h->ip_dst;
6001 pd.sport = pd.dport = NULL;
6002 pd.ip_sum = &h->ip_sum;
6003 pd.proto_sum = NULL;
6006 pd.sidx = (dir == PF_IN) ? 0 : 1;
6007 pd.didx = (dir == PF_IN) ? 1 : 0;
6009 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
6010 pd.tot_len = ntohs(h->ip_len);
6012 /* handle fragments that didn't get reassembled by normalization */
6013 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
6014 action = pf_test_fragment(&r, dir, kif, m, h,
6025 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6026 &action, &reason, AF_INET)) {
6027 log = action != PF_PASS;
6030 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6031 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6033 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6034 if (action == PF_DROP)
6036 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6038 if (action == PF_PASS) {
6039 if (V_pfsync_update_state_ptr != NULL)
6040 V_pfsync_update_state_ptr(s);
6044 } else if (s == NULL)
6045 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6054 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6055 &action, &reason, AF_INET)) {
6056 log = action != PF_PASS;
6059 if (uh.uh_dport == 0 ||
6060 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6061 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6063 REASON_SET(&reason, PFRES_SHORT);
6066 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6067 if (action == PF_PASS) {
6068 if (V_pfsync_update_state_ptr != NULL)
6069 V_pfsync_update_state_ptr(s);
6073 } else if (s == NULL)
6074 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6079 case IPPROTO_ICMP: {
6083 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6084 &action, &reason, AF_INET)) {
6085 log = action != PF_PASS;
6088 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6090 if (action == PF_PASS) {
6091 if (V_pfsync_update_state_ptr != NULL)
6092 V_pfsync_update_state_ptr(s);
6096 } else if (s == NULL)
6097 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6103 case IPPROTO_ICMPV6: {
6105 DPFPRINTF(PF_DEBUG_MISC,
6106 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6112 action = pf_test_state_other(&s, dir, kif, m, &pd);
6113 if (action == PF_PASS) {
6114 if (V_pfsync_update_state_ptr != NULL)
6115 V_pfsync_update_state_ptr(s);
6119 } else if (s == NULL)
6120 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6127 if (action == PF_PASS && h->ip_hl > 5 &&
6128 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6130 REASON_SET(&reason, PFRES_IPOPTIONS);
6132 DPFPRINTF(PF_DEBUG_MISC,
6133 ("pf: dropping packet with ip options\n"));
6136 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6138 REASON_SET(&reason, PFRES_MEMORY);
6140 if (r->rtableid >= 0)
6141 M_SETFIB(m, r->rtableid);
6143 if (r->scrub_flags & PFSTATE_SETPRIO) {
6144 if (pd.tos & IPTOS_LOWDELAY)
6146 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6148 REASON_SET(&reason, PFRES_MEMORY);
6150 DPFPRINTF(PF_DEBUG_MISC,
6151 ("pf: failed to allocate 802.1q mtag\n"));
6156 if (action == PF_PASS && r->qid) {
6157 if (pd.pf_mtag == NULL &&
6158 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6160 REASON_SET(&reason, PFRES_MEMORY);
6163 pd.pf_mtag->qid_hash = pf_state_hash(s);
6164 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6165 pd.pf_mtag->qid = r->pqid;
6167 pd.pf_mtag->qid = r->qid;
6168 /* Add hints for ecn. */
6169 pd.pf_mtag->hdr = h;
6176 * connections redirected to loopback should not match sockets
6177 * bound specifically to loopback due to security implications,
6178 * see tcp_input() and in_pcblookup_listen().
6180 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6181 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6182 (s->nat_rule.ptr->action == PF_RDR ||
6183 s->nat_rule.ptr->action == PF_BINAT) &&
6184 IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
6185 m->m_flags |= M_SKIP_FIREWALL;
6187 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6188 !PACKET_LOOPED(&pd)) {
6190 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6191 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6192 if (ipfwtag != NULL) {
6193 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6194 ntohs(r->divert.port);
6195 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6200 m_tag_prepend(m, ipfwtag);
6201 if (m->m_flags & M_FASTFWD_OURS) {
6202 if (pd.pf_mtag == NULL &&
6203 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6205 REASON_SET(&reason, PFRES_MEMORY);
6207 DPFPRINTF(PF_DEBUG_MISC,
6208 ("pf: failed to allocate tag\n"));
6210 pd.pf_mtag->flags |=
6211 PF_FASTFWD_OURS_PRESENT;
6212 m->m_flags &= ~M_FASTFWD_OURS;
6215 ip_divert_ptr(*m0, dir == PF_IN);
6220 /* XXX: ipfw has the same behaviour! */
6222 REASON_SET(&reason, PFRES_MEMORY);
6224 DPFPRINTF(PF_DEBUG_MISC,
6225 ("pf: failed to allocate divert tag\n"));
6232 if (s != NULL && s->nat_rule.ptr != NULL &&
6233 s->nat_rule.ptr->log & PF_LOG_ALL)
6234 lr = s->nat_rule.ptr;
6237 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6241 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6242 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6244 if (action == PF_PASS || r->action == PF_DROP) {
6245 dirndx = (dir == PF_OUT);
6246 r->packets[dirndx]++;
6247 r->bytes[dirndx] += pd.tot_len;
6249 a->packets[dirndx]++;
6250 a->bytes[dirndx] += pd.tot_len;
6253 if (s->nat_rule.ptr != NULL) {
6254 s->nat_rule.ptr->packets[dirndx]++;
6255 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6257 if (s->src_node != NULL) {
6258 s->src_node->packets[dirndx]++;
6259 s->src_node->bytes[dirndx] += pd.tot_len;
6261 if (s->nat_src_node != NULL) {
6262 s->nat_src_node->packets[dirndx]++;
6263 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6265 dirndx = (dir == s->direction) ? 0 : 1;
6266 s->packets[dirndx]++;
6267 s->bytes[dirndx] += pd.tot_len;
6270 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6271 if (nr != NULL && r == &V_pf_default_rule)
6273 if (tr->src.addr.type == PF_ADDR_TABLE)
6274 pfr_update_stats(tr->src.addr.p.tbl,
6275 (s == NULL) ? pd.src :
6276 &s->key[(s->direction == PF_IN)]->
6277 addr[(s->direction == PF_OUT)],
6278 pd.af, pd.tot_len, dir == PF_OUT,
6279 r->action == PF_PASS, tr->src.neg);
6280 if (tr->dst.addr.type == PF_ADDR_TABLE)
6281 pfr_update_stats(tr->dst.addr.p.tbl,
6282 (s == NULL) ? pd.dst :
6283 &s->key[(s->direction == PF_IN)]->
6284 addr[(s->direction == PF_IN)],
6285 pd.af, pd.tot_len, dir == PF_OUT,
6286 r->action == PF_PASS, tr->dst.neg);
6290 case PF_SYNPROXY_DROP:
6301 /* pf_route() returns unlocked. */
6303 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6317 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6319 struct pfi_kif *kif;
6320 u_short action, reason = 0, log = 0;
6321 struct mbuf *m = *m0, *n = NULL;
6323 struct ip6_hdr *h = NULL;
6324 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6325 struct pf_state *s = NULL;
6326 struct pf_ruleset *ruleset = NULL;
6328 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6330 PF_RULES_RLOCK_TRACKER;
6333 if (!V_pf_status.running)
6336 memset(&pd, 0, sizeof(pd));
6337 pd.pf_mtag = pf_find_mtag(m);
6339 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6342 kif = (struct pfi_kif *)ifp->if_pf_kif;
6344 DPFPRINTF(PF_DEBUG_URGENT,
6345 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6348 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6351 if (m->m_flags & M_SKIP_FIREWALL)
6356 /* We do IP header normalization and packet reassembly here */
6357 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6361 m = *m0; /* pf_normalize messes with m0 */
6362 h = mtod(m, struct ip6_hdr *);
6365 * we do not support jumbogram. if we keep going, zero ip6_plen
6366 * will do something bad, so drop the packet for now.
6368 if (htons(h->ip6_plen) == 0) {
6370 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6374 pd.src = (struct pf_addr *)&h->ip6_src;
6375 pd.dst = (struct pf_addr *)&h->ip6_dst;
6376 pd.sport = pd.dport = NULL;
6378 pd.proto_sum = NULL;
6380 pd.sidx = (dir == PF_IN) ? 0 : 1;
6381 pd.didx = (dir == PF_IN) ? 1 : 0;
6384 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6386 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6387 pd.proto = h->ip6_nxt;
6390 case IPPROTO_FRAGMENT:
6391 action = pf_test_fragment(&r, dir, kif, m, h,
6393 if (action == PF_DROP)
6394 REASON_SET(&reason, PFRES_FRAG);
6396 case IPPROTO_ROUTING: {
6397 struct ip6_rthdr rthdr;
6400 DPFPRINTF(PF_DEBUG_MISC,
6401 ("pf: IPv6 more than one rthdr\n"));
6403 REASON_SET(&reason, PFRES_IPOPTIONS);
6407 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6409 DPFPRINTF(PF_DEBUG_MISC,
6410 ("pf: IPv6 short rthdr\n"));
6412 REASON_SET(&reason, PFRES_SHORT);
6416 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6417 DPFPRINTF(PF_DEBUG_MISC,
6418 ("pf: IPv6 rthdr0\n"));
6420 REASON_SET(&reason, PFRES_IPOPTIONS);
6427 case IPPROTO_HOPOPTS:
6428 case IPPROTO_DSTOPTS: {
6429 /* get next header and header length */
6430 struct ip6_ext opt6;
6432 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6433 NULL, &reason, pd.af)) {
6434 DPFPRINTF(PF_DEBUG_MISC,
6435 ("pf: IPv6 short opt\n"));
6440 if (pd.proto == IPPROTO_AH)
6441 off += (opt6.ip6e_len + 2) * 4;
6443 off += (opt6.ip6e_len + 1) * 8;
6444 pd.proto = opt6.ip6e_nxt;
6445 /* goto the next header */
6452 } while (!terminal);
6454 /* if there's no routing header, use unmodified mbuf for checksumming */
6464 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6465 &action, &reason, AF_INET6)) {
6466 log = action != PF_PASS;
6469 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6470 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6471 if (action == PF_DROP)
6473 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6475 if (action == PF_PASS) {
6476 if (V_pfsync_update_state_ptr != NULL)
6477 V_pfsync_update_state_ptr(s);
6481 } else if (s == NULL)
6482 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6491 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6492 &action, &reason, AF_INET6)) {
6493 log = action != PF_PASS;
6496 if (uh.uh_dport == 0 ||
6497 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6498 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6500 REASON_SET(&reason, PFRES_SHORT);
6503 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6504 if (action == PF_PASS) {
6505 if (V_pfsync_update_state_ptr != NULL)
6506 V_pfsync_update_state_ptr(s);
6510 } else if (s == NULL)
6511 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6516 case IPPROTO_ICMP: {
6518 DPFPRINTF(PF_DEBUG_MISC,
6519 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6523 case IPPROTO_ICMPV6: {
6524 struct icmp6_hdr ih;
6527 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6528 &action, &reason, AF_INET6)) {
6529 log = action != PF_PASS;
6532 action = pf_test_state_icmp(&s, dir, kif,
6533 m, off, h, &pd, &reason);
6534 if (action == PF_PASS) {
6535 if (V_pfsync_update_state_ptr != NULL)
6536 V_pfsync_update_state_ptr(s);
6540 } else if (s == NULL)
6541 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6547 action = pf_test_state_other(&s, dir, kif, m, &pd);
6548 if (action == PF_PASS) {
6549 if (V_pfsync_update_state_ptr != NULL)
6550 V_pfsync_update_state_ptr(s);
6554 } else if (s == NULL)
6555 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6567 /* handle dangerous IPv6 extension headers. */
6568 if (action == PF_PASS && rh_cnt &&
6569 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6571 REASON_SET(&reason, PFRES_IPOPTIONS);
6573 DPFPRINTF(PF_DEBUG_MISC,
6574 ("pf: dropping packet with dangerous v6 headers\n"));
6577 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6579 REASON_SET(&reason, PFRES_MEMORY);
6581 if (r->rtableid >= 0)
6582 M_SETFIB(m, r->rtableid);
6584 if (r->scrub_flags & PFSTATE_SETPRIO) {
6585 if (pd.tos & IPTOS_LOWDELAY)
6587 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6589 REASON_SET(&reason, PFRES_MEMORY);
6591 DPFPRINTF(PF_DEBUG_MISC,
6592 ("pf: failed to allocate 802.1q mtag\n"));
6597 if (action == PF_PASS && r->qid) {
6598 if (pd.pf_mtag == NULL &&
6599 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6601 REASON_SET(&reason, PFRES_MEMORY);
6604 pd.pf_mtag->qid_hash = pf_state_hash(s);
6605 if (pd.tos & IPTOS_LOWDELAY)
6606 pd.pf_mtag->qid = r->pqid;
6608 pd.pf_mtag->qid = r->qid;
6609 /* Add hints for ecn. */
6610 pd.pf_mtag->hdr = h;
6615 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6616 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6617 (s->nat_rule.ptr->action == PF_RDR ||
6618 s->nat_rule.ptr->action == PF_BINAT) &&
6619 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6620 m->m_flags |= M_SKIP_FIREWALL;
6622 /* XXX: Anybody working on it?! */
6624 printf("pf: divert(9) is not supported for IPv6\n");
6629 if (s != NULL && s->nat_rule.ptr != NULL &&
6630 s->nat_rule.ptr->log & PF_LOG_ALL)
6631 lr = s->nat_rule.ptr;
6634 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6638 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6639 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6641 if (action == PF_PASS || r->action == PF_DROP) {
6642 dirndx = (dir == PF_OUT);
6643 r->packets[dirndx]++;
6644 r->bytes[dirndx] += pd.tot_len;
6646 a->packets[dirndx]++;
6647 a->bytes[dirndx] += pd.tot_len;
6650 if (s->nat_rule.ptr != NULL) {
6651 s->nat_rule.ptr->packets[dirndx]++;
6652 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6654 if (s->src_node != NULL) {
6655 s->src_node->packets[dirndx]++;
6656 s->src_node->bytes[dirndx] += pd.tot_len;
6658 if (s->nat_src_node != NULL) {
6659 s->nat_src_node->packets[dirndx]++;
6660 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6662 dirndx = (dir == s->direction) ? 0 : 1;
6663 s->packets[dirndx]++;
6664 s->bytes[dirndx] += pd.tot_len;
6667 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6668 if (nr != NULL && r == &V_pf_default_rule)
6670 if (tr->src.addr.type == PF_ADDR_TABLE)
6671 pfr_update_stats(tr->src.addr.p.tbl,
6672 (s == NULL) ? pd.src :
6673 &s->key[(s->direction == PF_IN)]->addr[0],
6674 pd.af, pd.tot_len, dir == PF_OUT,
6675 r->action == PF_PASS, tr->src.neg);
6676 if (tr->dst.addr.type == PF_ADDR_TABLE)
6677 pfr_update_stats(tr->dst.addr.p.tbl,
6678 (s == NULL) ? pd.dst :
6679 &s->key[(s->direction == PF_IN)]->addr[1],
6680 pd.af, pd.tot_len, dir == PF_OUT,
6681 r->action == PF_PASS, tr->dst.neg);
6685 case PF_SYNPROXY_DROP:
6696 /* pf_route6() returns unlocked. */
6698 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6707 /* If reassembled packet passed, create new fragments. */
6708 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6709 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6710 action = pf_refragment6(ifp, m0, mtag);