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"
48 #include <sys/param.h>
50 #include <sys/endian.h>
52 #include <sys/interrupt.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/limits.h>
58 #include <sys/random.h>
59 #include <sys/refcount.h>
60 #include <sys/socket.h>
61 #include <sys/sysctl.h>
62 #include <sys/taskqueue.h>
63 #include <sys/ucred.h>
66 #include <net/if_var.h>
67 #include <net/if_types.h>
68 #include <net/if_vlan_var.h>
69 #include <net/route.h>
70 #include <net/radix_mpath.h>
74 #include <net/pfvar.h>
75 #include <net/if_pflog.h>
76 #include <net/if_pfsync.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_var.h>
80 #include <netinet/in_fib.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_fw.h>
83 #include <netinet/ip_icmp.h>
84 #include <netinet/icmp_var.h>
85 #include <netinet/ip_var.h>
86 #include <netinet/tcp.h>
87 #include <netinet/tcp_fsm.h>
88 #include <netinet/tcp_seq.h>
89 #include <netinet/tcp_timer.h>
90 #include <netinet/tcp_var.h>
91 #include <netinet/udp.h>
92 #include <netinet/udp_var.h>
95 #include <netinet/ip6.h>
96 #include <netinet/icmp6.h>
97 #include <netinet6/nd6.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/in6_pcb.h>
100 #include <netinet6/in6_fib.h>
101 #include <netinet6/scope6_var.h>
104 #include <machine/in_cksum.h>
105 #include <security/mac/mac_framework.h>
107 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
114 VNET_DEFINE(struct pf_altqqueue, pf_altqs[4]);
115 VNET_DEFINE(struct pf_palist, pf_pabuf);
116 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
117 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_active);
118 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
119 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_inactive);
120 VNET_DEFINE(struct pf_kstatus, pf_status);
122 VNET_DEFINE(u_int32_t, ticket_altqs_active);
123 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
124 VNET_DEFINE(int, altqs_inactive_open);
125 VNET_DEFINE(u_int32_t, ticket_pabuf);
127 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
128 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
129 VNET_DEFINE(u_char, pf_tcp_secret[16]);
130 #define V_pf_tcp_secret VNET(pf_tcp_secret)
131 VNET_DEFINE(int, pf_tcp_secret_init);
132 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
133 VNET_DEFINE(int, pf_tcp_iss_off);
134 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
135 VNET_DECLARE(int, pf_vnet_active);
136 #define V_pf_vnet_active VNET(pf_vnet_active)
138 VNET_DEFINE_STATIC(uint32_t, pf_purge_idx);
139 #define V_pf_purge_idx VNET(pf_purge_idx)
142 * Queue for pf_intr() sends.
144 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
145 struct pf_send_entry {
146 STAILQ_ENTRY(pf_send_entry) pfse_next;
161 STAILQ_HEAD(pf_send_head, pf_send_entry);
162 VNET_DEFINE_STATIC(struct pf_send_head, pf_sendqueue);
163 #define V_pf_sendqueue VNET(pf_sendqueue)
165 static struct mtx pf_sendqueue_mtx;
166 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
167 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
168 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
171 * Queue for pf_overload_task() tasks.
173 struct pf_overload_entry {
174 SLIST_ENTRY(pf_overload_entry) next;
178 struct pf_rule *rule;
181 SLIST_HEAD(pf_overload_head, pf_overload_entry);
182 VNET_DEFINE_STATIC(struct pf_overload_head, pf_overloadqueue);
183 #define V_pf_overloadqueue VNET(pf_overloadqueue)
184 VNET_DEFINE_STATIC(struct task, pf_overloadtask);
185 #define V_pf_overloadtask VNET(pf_overloadtask)
187 static struct mtx pf_overloadqueue_mtx;
188 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
189 "pf overload/flush queue", MTX_DEF);
190 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
191 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
193 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
194 struct mtx pf_unlnkdrules_mtx;
195 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
198 VNET_DEFINE_STATIC(uma_zone_t, pf_sources_z);
199 #define V_pf_sources_z VNET(pf_sources_z)
200 uma_zone_t pf_mtag_z;
201 VNET_DEFINE(uma_zone_t, pf_state_z);
202 VNET_DEFINE(uma_zone_t, pf_state_key_z);
204 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
205 #define PFID_CPUBITS 8
206 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
207 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
208 #define PFID_MAXID (~PFID_CPUMASK)
209 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
211 static void pf_src_tree_remove_state(struct pf_state *);
212 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
214 static void pf_add_threshold(struct pf_threshold *);
215 static int pf_check_threshold(struct pf_threshold *);
217 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
218 u_int16_t *, u_int16_t *, struct pf_addr *,
219 u_int16_t, u_int8_t, sa_family_t);
220 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
221 struct tcphdr *, struct pf_state_peer *);
222 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
223 struct pf_addr *, struct pf_addr *, u_int16_t,
224 u_int16_t *, u_int16_t *, u_int16_t *,
225 u_int16_t *, u_int8_t, sa_family_t);
226 static void pf_send_tcp(struct mbuf *,
227 const struct pf_rule *, sa_family_t,
228 const struct pf_addr *, const struct pf_addr *,
229 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
230 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
231 u_int16_t, struct ifnet *);
232 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
233 sa_family_t, struct pf_rule *);
234 static void pf_detach_state(struct pf_state *);
235 static int pf_state_key_attach(struct pf_state_key *,
236 struct pf_state_key *, struct pf_state *);
237 static void pf_state_key_detach(struct pf_state *, int);
238 static int pf_state_key_ctor(void *, int, void *, int);
239 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
240 static int pf_test_rule(struct pf_rule **, struct pf_state **,
241 int, struct pfi_kif *, struct mbuf *, int,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **, struct inpcb *);
244 static int pf_create_state(struct pf_rule *, struct pf_rule *,
245 struct pf_rule *, struct pf_pdesc *,
246 struct pf_src_node *, struct pf_state_key *,
247 struct pf_state_key *, struct mbuf *, int,
248 u_int16_t, u_int16_t, int *, struct pfi_kif *,
249 struct pf_state **, int, u_int16_t, u_int16_t,
251 static int pf_test_fragment(struct pf_rule **, int,
252 struct pfi_kif *, struct mbuf *, void *,
253 struct pf_pdesc *, struct pf_rule **,
254 struct pf_ruleset **);
255 static int pf_tcp_track_full(struct pf_state_peer *,
256 struct pf_state_peer *, struct pf_state **,
257 struct pfi_kif *, struct mbuf *, int,
258 struct pf_pdesc *, u_short *, int *);
259 static int pf_tcp_track_sloppy(struct pf_state_peer *,
260 struct pf_state_peer *, struct pf_state **,
261 struct pf_pdesc *, u_short *);
262 static int pf_test_state_tcp(struct pf_state **, int,
263 struct pfi_kif *, struct mbuf *, int,
264 void *, struct pf_pdesc *, u_short *);
265 static int pf_test_state_udp(struct pf_state **, int,
266 struct pfi_kif *, struct mbuf *, int,
267 void *, struct pf_pdesc *);
268 static int pf_test_state_icmp(struct pf_state **, int,
269 struct pfi_kif *, struct mbuf *, int,
270 void *, struct pf_pdesc *, u_short *);
271 static int pf_test_state_other(struct pf_state **, int,
272 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
273 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
275 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
277 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
279 static int pf_check_proto_cksum(struct mbuf *, int, int,
280 u_int8_t, sa_family_t);
281 static void pf_print_state_parts(struct pf_state *,
282 struct pf_state_key *, struct pf_state_key *);
283 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
284 struct pf_addr_wrap *);
285 static struct pf_state *pf_find_state(struct pfi_kif *,
286 struct pf_state_key_cmp *, u_int);
287 static int pf_src_connlimit(struct pf_state **);
288 static void pf_overload_task(void *v, int pending);
289 static int pf_insert_src_node(struct pf_src_node **,
290 struct pf_rule *, struct pf_addr *, sa_family_t);
291 static u_int pf_purge_expired_states(u_int, int);
292 static void pf_purge_unlinked_rules(void);
293 static int pf_mtag_uminit(void *, int, int);
294 static void pf_mtag_free(struct m_tag *);
296 static void pf_route(struct mbuf **, struct pf_rule *, int,
297 struct ifnet *, struct pf_state *,
298 struct pf_pdesc *, struct inpcb *);
301 static void pf_change_a6(struct pf_addr *, u_int16_t *,
302 struct pf_addr *, u_int8_t);
303 static void pf_route6(struct mbuf **, struct pf_rule *, int,
304 struct ifnet *, struct pf_state *,
305 struct pf_pdesc *, struct inpcb *);
308 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
310 extern int pf_end_threads;
311 extern struct proc *pf_purge_proc;
313 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
315 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
316 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
318 #define STATE_LOOKUP(i, k, d, s, pd) \
320 (s) = pf_find_state((i), (k), (d)); \
323 if (PACKET_LOOPED(pd)) \
325 if ((d) == PF_OUT && \
326 (((s)->rule.ptr->rt == PF_ROUTETO && \
327 (s)->rule.ptr->direction == PF_OUT) || \
328 ((s)->rule.ptr->rt == PF_REPLYTO && \
329 (s)->rule.ptr->direction == PF_IN)) && \
330 (s)->rt_kif != NULL && \
331 (s)->rt_kif != (i)) \
335 #define BOUND_IFACE(r, k) \
336 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
338 #define STATE_INC_COUNTERS(s) \
340 counter_u64_add(s->rule.ptr->states_cur, 1); \
341 counter_u64_add(s->rule.ptr->states_tot, 1); \
342 if (s->anchor.ptr != NULL) { \
343 counter_u64_add(s->anchor.ptr->states_cur, 1); \
344 counter_u64_add(s->anchor.ptr->states_tot, 1); \
346 if (s->nat_rule.ptr != NULL) { \
347 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
348 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
352 #define STATE_DEC_COUNTERS(s) \
354 if (s->nat_rule.ptr != NULL) \
355 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
356 if (s->anchor.ptr != NULL) \
357 counter_u64_add(s->anchor.ptr->states_cur, -1); \
358 counter_u64_add(s->rule.ptr->states_cur, -1); \
361 MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
362 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
363 VNET_DEFINE(struct pf_idhash *, pf_idhash);
364 VNET_DEFINE(struct pf_srchash *, pf_srchash);
366 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
369 u_long pf_srchashmask;
370 static u_long pf_hashsize;
371 static u_long pf_srchashsize;
372 u_long pf_ioctl_maxcount = 65535;
374 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
375 &pf_hashsize, 0, "Size of pf(4) states hashtable");
376 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
377 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
378 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RDTUN,
379 &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
381 VNET_DEFINE(void *, pf_swi_cookie);
383 VNET_DEFINE(uint32_t, pf_hashseed);
384 #define V_pf_hashseed VNET(pf_hashseed)
387 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
393 if (a->addr32[0] > b->addr32[0])
395 if (a->addr32[0] < b->addr32[0])
401 if (a->addr32[3] > b->addr32[3])
403 if (a->addr32[3] < b->addr32[3])
405 if (a->addr32[2] > b->addr32[2])
407 if (a->addr32[2] < b->addr32[2])
409 if (a->addr32[1] > b->addr32[1])
411 if (a->addr32[1] < b->addr32[1])
413 if (a->addr32[0] > b->addr32[0])
415 if (a->addr32[0] < b->addr32[0])
420 panic("%s: unknown address family %u", __func__, af);
425 static __inline uint32_t
426 pf_hashkey(struct pf_state_key *sk)
430 h = murmur3_32_hash32((uint32_t *)sk,
431 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
434 return (h & pf_hashmask);
437 static __inline uint32_t
438 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
444 h = murmur3_32_hash32((uint32_t *)&addr->v4,
445 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
448 h = murmur3_32_hash32((uint32_t *)&addr->v6,
449 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
452 panic("%s: unknown address family %u", __func__, af);
455 return (h & pf_srchashmask);
460 pf_state_hash(struct pf_state *s)
462 u_int32_t hv = (intptr_t)s / sizeof(*s);
464 hv ^= crc32(&s->src, sizeof(s->src));
465 hv ^= crc32(&s->dst, sizeof(s->dst));
474 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
479 dst->addr32[0] = src->addr32[0];
483 dst->addr32[0] = src->addr32[0];
484 dst->addr32[1] = src->addr32[1];
485 dst->addr32[2] = src->addr32[2];
486 dst->addr32[3] = src->addr32[3];
493 pf_init_threshold(struct pf_threshold *threshold,
494 u_int32_t limit, u_int32_t seconds)
496 threshold->limit = limit * PF_THRESHOLD_MULT;
497 threshold->seconds = seconds;
498 threshold->count = 0;
499 threshold->last = time_uptime;
503 pf_add_threshold(struct pf_threshold *threshold)
505 u_int32_t t = time_uptime, diff = t - threshold->last;
507 if (diff >= threshold->seconds)
508 threshold->count = 0;
510 threshold->count -= threshold->count * diff /
512 threshold->count += PF_THRESHOLD_MULT;
517 pf_check_threshold(struct pf_threshold *threshold)
519 return (threshold->count > threshold->limit);
523 pf_src_connlimit(struct pf_state **state)
525 struct pf_overload_entry *pfoe;
528 PF_STATE_LOCK_ASSERT(*state);
530 (*state)->src_node->conn++;
531 (*state)->src.tcp_est = 1;
532 pf_add_threshold(&(*state)->src_node->conn_rate);
534 if ((*state)->rule.ptr->max_src_conn &&
535 (*state)->rule.ptr->max_src_conn <
536 (*state)->src_node->conn) {
537 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
541 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
542 pf_check_threshold(&(*state)->src_node->conn_rate)) {
543 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
550 /* Kill this state. */
551 (*state)->timeout = PFTM_PURGE;
552 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
554 if ((*state)->rule.ptr->overload_tbl == NULL)
557 /* Schedule overloading and flushing task. */
558 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
560 return (1); /* too bad :( */
562 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
563 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
564 pfoe->rule = (*state)->rule.ptr;
565 pfoe->dir = (*state)->direction;
567 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
568 PF_OVERLOADQ_UNLOCK();
569 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
575 pf_overload_task(void *v, int pending)
577 struct pf_overload_head queue;
579 struct pf_overload_entry *pfoe, *pfoe1;
582 CURVNET_SET((struct vnet *)v);
585 queue = V_pf_overloadqueue;
586 SLIST_INIT(&V_pf_overloadqueue);
587 PF_OVERLOADQ_UNLOCK();
589 bzero(&p, sizeof(p));
590 SLIST_FOREACH(pfoe, &queue, next) {
591 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
592 if (V_pf_status.debug >= PF_DEBUG_MISC) {
593 printf("%s: blocking address ", __func__);
594 pf_print_host(&pfoe->addr, 0, pfoe->af);
598 p.pfra_af = pfoe->af;
603 p.pfra_ip4addr = pfoe->addr.v4;
609 p.pfra_ip6addr = pfoe->addr.v6;
615 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
620 * Remove those entries, that don't need flushing.
622 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
623 if (pfoe->rule->flush == 0) {
624 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
625 free(pfoe, M_PFTEMP);
628 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
630 /* If nothing to flush, return. */
631 if (SLIST_EMPTY(&queue)) {
636 for (int i = 0; i <= pf_hashmask; i++) {
637 struct pf_idhash *ih = &V_pf_idhash[i];
638 struct pf_state_key *sk;
642 LIST_FOREACH(s, &ih->states, entry) {
643 sk = s->key[PF_SK_WIRE];
644 SLIST_FOREACH(pfoe, &queue, next)
645 if (sk->af == pfoe->af &&
646 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
647 pfoe->rule == s->rule.ptr) &&
648 ((pfoe->dir == PF_OUT &&
649 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
650 (pfoe->dir == PF_IN &&
651 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
652 s->timeout = PFTM_PURGE;
653 s->src.state = s->dst.state = TCPS_CLOSED;
657 PF_HASHROW_UNLOCK(ih);
659 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
660 free(pfoe, M_PFTEMP);
661 if (V_pf_status.debug >= PF_DEBUG_MISC)
662 printf("%s: %u states killed", __func__, killed);
668 * Can return locked on failure, so that we can consistently
669 * allocate and insert a new one.
672 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
675 struct pf_srchash *sh;
676 struct pf_src_node *n;
678 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
680 sh = &V_pf_srchash[pf_hashsrc(src, af)];
682 LIST_FOREACH(n, &sh->nodes, entry)
683 if (n->rule.ptr == rule && n->af == af &&
684 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
685 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
689 PF_HASHROW_UNLOCK(sh);
690 } else if (returnlocked == 0)
691 PF_HASHROW_UNLOCK(sh);
697 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
698 struct pf_addr *src, sa_family_t af)
701 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
702 rule->rpool.opts & PF_POOL_STICKYADDR),
703 ("%s for non-tracking rule %p", __func__, rule));
706 *sn = pf_find_src_node(src, rule, af, 1);
709 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
711 PF_HASHROW_ASSERT(sh);
713 if (!rule->max_src_nodes ||
714 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
715 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
717 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
720 PF_HASHROW_UNLOCK(sh);
724 pf_init_threshold(&(*sn)->conn_rate,
725 rule->max_src_conn_rate.limit,
726 rule->max_src_conn_rate.seconds);
729 (*sn)->rule.ptr = rule;
730 PF_ACPY(&(*sn)->addr, src, af);
731 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
732 (*sn)->creation = time_uptime;
733 (*sn)->ruletype = rule->action;
735 if ((*sn)->rule.ptr != NULL)
736 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
737 PF_HASHROW_UNLOCK(sh);
738 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
740 if (rule->max_src_states &&
741 (*sn)->states >= rule->max_src_states) {
742 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
751 pf_unlink_src_node(struct pf_src_node *src)
754 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
755 LIST_REMOVE(src, entry);
757 counter_u64_add(src->rule.ptr->src_nodes, -1);
761 pf_free_src_nodes(struct pf_src_node_list *head)
763 struct pf_src_node *sn, *tmp;
766 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
767 uma_zfree(V_pf_sources_z, sn);
771 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
780 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
781 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
785 /* Per-vnet data storage structures initialization. */
789 struct pf_keyhash *kh;
790 struct pf_idhash *ih;
791 struct pf_srchash *sh;
794 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
795 pf_hashsize = PF_HASHSIZ;
796 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
797 pf_srchashsize = PF_SRCHASHSIZ;
799 V_pf_hashseed = arc4random();
801 /* States and state keys storage. */
802 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
803 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
804 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
805 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
806 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
808 V_pf_state_key_z = uma_zcreate("pf state keys",
809 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
812 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
813 M_PFHASH, M_NOWAIT | M_ZERO);
814 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
815 M_PFHASH, M_NOWAIT | M_ZERO);
816 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
817 printf("pf: Unable to allocate memory for "
818 "state_hashsize %lu.\n", pf_hashsize);
820 free(V_pf_keyhash, M_PFHASH);
821 free(V_pf_idhash, M_PFHASH);
823 pf_hashsize = PF_HASHSIZ;
824 V_pf_keyhash = mallocarray(pf_hashsize,
825 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
826 V_pf_idhash = mallocarray(pf_hashsize,
827 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
830 pf_hashmask = pf_hashsize - 1;
831 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
833 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
834 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
838 V_pf_sources_z = uma_zcreate("pf source nodes",
839 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
841 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
842 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
843 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
845 V_pf_srchash = mallocarray(pf_srchashsize,
846 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
847 if (V_pf_srchash == NULL) {
848 printf("pf: Unable to allocate memory for "
849 "source_hashsize %lu.\n", pf_srchashsize);
851 pf_srchashsize = PF_SRCHASHSIZ;
852 V_pf_srchash = mallocarray(pf_srchashsize,
853 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
856 pf_srchashmask = pf_srchashsize - 1;
857 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
858 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
861 TAILQ_INIT(&V_pf_altqs[0]);
862 TAILQ_INIT(&V_pf_altqs[1]);
863 TAILQ_INIT(&V_pf_altqs[2]);
864 TAILQ_INIT(&V_pf_altqs[3]);
865 TAILQ_INIT(&V_pf_pabuf);
866 V_pf_altqs_active = &V_pf_altqs[0];
867 V_pf_altq_ifs_active = &V_pf_altqs[1];
868 V_pf_altqs_inactive = &V_pf_altqs[2];
869 V_pf_altq_ifs_inactive = &V_pf_altqs[3];
871 /* Send & overload+flush queues. */
872 STAILQ_INIT(&V_pf_sendqueue);
873 SLIST_INIT(&V_pf_overloadqueue);
874 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
876 /* Unlinked, but may be referenced rules. */
877 TAILQ_INIT(&V_pf_unlinked_rules);
884 uma_zdestroy(pf_mtag_z);
890 struct pf_keyhash *kh;
891 struct pf_idhash *ih;
892 struct pf_srchash *sh;
893 struct pf_send_entry *pfse, *next;
896 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
898 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
900 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
902 mtx_destroy(&kh->lock);
903 mtx_destroy(&ih->lock);
905 free(V_pf_keyhash, M_PFHASH);
906 free(V_pf_idhash, M_PFHASH);
908 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
909 KASSERT(LIST_EMPTY(&sh->nodes),
910 ("%s: source node hash not empty", __func__));
911 mtx_destroy(&sh->lock);
913 free(V_pf_srchash, M_PFHASH);
915 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
916 m_freem(pfse->pfse_m);
917 free(pfse, M_PFTEMP);
920 uma_zdestroy(V_pf_sources_z);
921 uma_zdestroy(V_pf_state_z);
922 uma_zdestroy(V_pf_state_key_z);
926 pf_mtag_uminit(void *mem, int size, int how)
930 t = (struct m_tag *)mem;
931 t->m_tag_cookie = MTAG_ABI_COMPAT;
932 t->m_tag_id = PACKET_TAG_PF;
933 t->m_tag_len = sizeof(struct pf_mtag);
934 t->m_tag_free = pf_mtag_free;
940 pf_mtag_free(struct m_tag *t)
943 uma_zfree(pf_mtag_z, t);
947 pf_get_mtag(struct mbuf *m)
951 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
952 return ((struct pf_mtag *)(mtag + 1));
954 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
957 bzero(mtag + 1, sizeof(struct pf_mtag));
958 m_tag_prepend(m, mtag);
960 return ((struct pf_mtag *)(mtag + 1));
964 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
967 struct pf_keyhash *khs, *khw, *kh;
968 struct pf_state_key *sk, *cur;
969 struct pf_state *si, *olds = NULL;
972 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
973 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
974 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
977 * We need to lock hash slots of both keys. To avoid deadlock
978 * we always lock the slot with lower address first. Unlock order
981 * We also need to lock ID hash slot before dropping key
982 * locks. On success we return with ID hash slot locked.
986 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
987 PF_HASHROW_LOCK(khs);
989 khs = &V_pf_keyhash[pf_hashkey(sks)];
990 khw = &V_pf_keyhash[pf_hashkey(skw)];
992 PF_HASHROW_LOCK(khs);
993 } else if (khs < khw) {
994 PF_HASHROW_LOCK(khs);
995 PF_HASHROW_LOCK(khw);
997 PF_HASHROW_LOCK(khw);
998 PF_HASHROW_LOCK(khs);
1002 #define KEYS_UNLOCK() do { \
1004 PF_HASHROW_UNLOCK(khs); \
1005 PF_HASHROW_UNLOCK(khw); \
1007 PF_HASHROW_UNLOCK(khs); \
1011 * First run: start with wire key.
1018 LIST_FOREACH(cur, &kh->keys, entry)
1019 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1023 /* Key exists. Check for same kif, if none, add to key. */
1024 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1025 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1027 PF_HASHROW_LOCK(ih);
1028 if (si->kif == s->kif &&
1029 si->direction == s->direction) {
1030 if (sk->proto == IPPROTO_TCP &&
1031 si->src.state >= TCPS_FIN_WAIT_2 &&
1032 si->dst.state >= TCPS_FIN_WAIT_2) {
1034 * New state matches an old >FIN_WAIT_2
1035 * state. We can't drop key hash locks,
1036 * thus we can't unlink it properly.
1038 * As a workaround we drop it into
1039 * TCPS_CLOSED state, schedule purge
1040 * ASAP and push it into the very end
1041 * of the slot TAILQ, so that it won't
1042 * conflict with our new state.
1044 si->src.state = si->dst.state =
1046 si->timeout = PFTM_PURGE;
1049 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1050 printf("pf: %s key attach "
1052 (idx == PF_SK_WIRE) ?
1055 pf_print_state_parts(s,
1056 (idx == PF_SK_WIRE) ?
1058 (idx == PF_SK_STACK) ?
1060 printf(", existing: ");
1061 pf_print_state_parts(si,
1062 (idx == PF_SK_WIRE) ?
1064 (idx == PF_SK_STACK) ?
1068 PF_HASHROW_UNLOCK(ih);
1070 uma_zfree(V_pf_state_key_z, sk);
1071 if (idx == PF_SK_STACK)
1073 return (EEXIST); /* collision! */
1076 PF_HASHROW_UNLOCK(ih);
1078 uma_zfree(V_pf_state_key_z, sk);
1081 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1086 /* List is sorted, if-bound states before floating. */
1087 if (s->kif == V_pfi_all)
1088 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1090 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1093 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1094 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1100 * Attach done. See how should we (or should not?)
1101 * attach a second key.
1104 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1108 } else if (sks != NULL) {
1110 * Continue attaching with stack key.
1122 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1123 ("%s failure", __func__));
1130 pf_detach_state(struct pf_state *s)
1132 struct pf_state_key *sks = s->key[PF_SK_STACK];
1133 struct pf_keyhash *kh;
1136 kh = &V_pf_keyhash[pf_hashkey(sks)];
1137 PF_HASHROW_LOCK(kh);
1138 if (s->key[PF_SK_STACK] != NULL)
1139 pf_state_key_detach(s, PF_SK_STACK);
1141 * If both point to same key, then we are done.
1143 if (sks == s->key[PF_SK_WIRE]) {
1144 pf_state_key_detach(s, PF_SK_WIRE);
1145 PF_HASHROW_UNLOCK(kh);
1148 PF_HASHROW_UNLOCK(kh);
1151 if (s->key[PF_SK_WIRE] != NULL) {
1152 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1153 PF_HASHROW_LOCK(kh);
1154 if (s->key[PF_SK_WIRE] != NULL)
1155 pf_state_key_detach(s, PF_SK_WIRE);
1156 PF_HASHROW_UNLOCK(kh);
1161 pf_state_key_detach(struct pf_state *s, int idx)
1163 struct pf_state_key *sk = s->key[idx];
1165 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1167 PF_HASHROW_ASSERT(kh);
1169 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1172 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1173 LIST_REMOVE(sk, entry);
1174 uma_zfree(V_pf_state_key_z, sk);
1179 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1181 struct pf_state_key *sk = mem;
1183 bzero(sk, sizeof(struct pf_state_key_cmp));
1184 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1185 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1190 struct pf_state_key *
1191 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1192 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1194 struct pf_state_key *sk;
1196 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1200 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1201 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1202 sk->port[pd->sidx] = sport;
1203 sk->port[pd->didx] = dport;
1204 sk->proto = pd->proto;
1210 struct pf_state_key *
1211 pf_state_key_clone(struct pf_state_key *orig)
1213 struct pf_state_key *sk;
1215 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1219 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1225 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1226 struct pf_state_key *sks, struct pf_state *s)
1228 struct pf_idhash *ih;
1229 struct pf_state *cur;
1232 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1233 ("%s: sks not pristine", __func__));
1234 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1235 ("%s: skw not pristine", __func__));
1236 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1240 if (s->id == 0 && s->creatorid == 0) {
1241 /* XXX: should be atomic, but probability of collision low */
1242 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1243 V_pf_stateid[curcpu] = 1;
1244 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1245 s->id = htobe64(s->id);
1246 s->creatorid = V_pf_status.hostid;
1249 /* Returns with ID locked on success. */
1250 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1253 ih = &V_pf_idhash[PF_IDHASH(s)];
1254 PF_HASHROW_ASSERT(ih);
1255 LIST_FOREACH(cur, &ih->states, entry)
1256 if (cur->id == s->id && cur->creatorid == s->creatorid)
1260 PF_HASHROW_UNLOCK(ih);
1261 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1262 printf("pf: state ID collision: "
1263 "id: %016llx creatorid: %08x\n",
1264 (unsigned long long)be64toh(s->id),
1265 ntohl(s->creatorid));
1270 LIST_INSERT_HEAD(&ih->states, s, entry);
1271 /* One for keys, one for ID hash. */
1272 refcount_init(&s->refs, 2);
1274 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1275 if (V_pfsync_insert_state_ptr != NULL)
1276 V_pfsync_insert_state_ptr(s);
1278 /* Returns locked. */
1283 * Find state by ID: returns with locked row on success.
1286 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1288 struct pf_idhash *ih;
1291 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1293 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1295 PF_HASHROW_LOCK(ih);
1296 LIST_FOREACH(s, &ih->states, entry)
1297 if (s->id == id && s->creatorid == creatorid)
1301 PF_HASHROW_UNLOCK(ih);
1307 * Find state by key.
1308 * Returns with ID hash slot locked on success.
1310 static struct pf_state *
1311 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1313 struct pf_keyhash *kh;
1314 struct pf_state_key *sk;
1318 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1320 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1322 PF_HASHROW_LOCK(kh);
1323 LIST_FOREACH(sk, &kh->keys, entry)
1324 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1327 PF_HASHROW_UNLOCK(kh);
1331 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1333 /* List is sorted, if-bound states before floating ones. */
1334 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1335 if (s->kif == V_pfi_all || s->kif == kif) {
1337 PF_HASHROW_UNLOCK(kh);
1338 if (s->timeout >= PFTM_MAX) {
1340 * State is either being processed by
1341 * pf_unlink_state() in an other thread, or
1342 * is scheduled for immediate expiry.
1349 PF_HASHROW_UNLOCK(kh);
1355 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1357 struct pf_keyhash *kh;
1358 struct pf_state_key *sk;
1359 struct pf_state *s, *ret = NULL;
1362 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1364 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1366 PF_HASHROW_LOCK(kh);
1367 LIST_FOREACH(sk, &kh->keys, entry)
1368 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1371 PF_HASHROW_UNLOCK(kh);
1386 panic("%s: dir %u", __func__, dir);
1389 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1391 PF_HASHROW_UNLOCK(kh);
1405 PF_HASHROW_UNLOCK(kh);
1410 /* END state table stuff */
1413 pf_send(struct pf_send_entry *pfse)
1417 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1419 swi_sched(V_pf_swi_cookie, 0);
1425 struct pf_send_head queue;
1426 struct pf_send_entry *pfse, *next;
1428 CURVNET_SET((struct vnet *)v);
1431 queue = V_pf_sendqueue;
1432 STAILQ_INIT(&V_pf_sendqueue);
1435 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1436 switch (pfse->pfse_type) {
1439 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1442 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1443 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1448 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1452 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1453 pfse->icmpopts.code, pfse->icmpopts.mtu);
1457 panic("%s: unknown type", __func__);
1459 free(pfse, M_PFTEMP);
1465 pf_purge_thread(void *unused __unused)
1467 VNET_ITERATOR_DECL(vnet_iter);
1469 sx_xlock(&pf_end_lock);
1470 while (pf_end_threads == 0) {
1471 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1474 VNET_FOREACH(vnet_iter) {
1475 CURVNET_SET(vnet_iter);
1478 /* Wait until V_pf_default_rule is initialized. */
1479 if (V_pf_vnet_active == 0) {
1485 * Process 1/interval fraction of the state
1489 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1490 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1493 * Purge other expired types every
1494 * PFTM_INTERVAL seconds.
1496 if (V_pf_purge_idx == 0) {
1498 * Order is important:
1499 * - states and src nodes reference rules
1500 * - states and rules reference kifs
1502 pf_purge_expired_fragments();
1503 pf_purge_expired_src_nodes();
1504 pf_purge_unlinked_rules();
1509 VNET_LIST_RUNLOCK();
1513 sx_xunlock(&pf_end_lock);
1518 pf_unload_vnet_purge(void)
1522 * To cleanse up all kifs and rules we need
1523 * two runs: first one clears reference flags,
1524 * then pf_purge_expired_states() doesn't
1525 * raise them, and then second run frees.
1527 pf_purge_unlinked_rules();
1531 * Now purge everything.
1533 pf_purge_expired_states(0, pf_hashmask);
1534 pf_purge_fragments(UINT_MAX);
1535 pf_purge_expired_src_nodes();
1538 * Now all kifs & rules should be unreferenced,
1539 * thus should be successfully freed.
1541 pf_purge_unlinked_rules();
1547 pf_state_expires(const struct pf_state *state)
1554 /* handle all PFTM_* > PFTM_MAX here */
1555 if (state->timeout == PFTM_PURGE)
1556 return (time_uptime);
1557 KASSERT(state->timeout != PFTM_UNLINKED,
1558 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1559 KASSERT((state->timeout < PFTM_MAX),
1560 ("pf_state_expires: timeout > PFTM_MAX"));
1561 timeout = state->rule.ptr->timeout[state->timeout];
1563 timeout = V_pf_default_rule.timeout[state->timeout];
1564 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1565 if (start && state->rule.ptr != &V_pf_default_rule) {
1566 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1567 states = counter_u64_fetch(state->rule.ptr->states_cur);
1569 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1570 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1571 states = V_pf_status.states;
1573 if (end && states > start && start < end) {
1575 timeout = (u_int64_t)timeout * (end - states) /
1577 return (state->expire + timeout);
1580 return (time_uptime);
1582 return (state->expire + timeout);
1586 pf_purge_expired_src_nodes()
1588 struct pf_src_node_list freelist;
1589 struct pf_srchash *sh;
1590 struct pf_src_node *cur, *next;
1593 LIST_INIT(&freelist);
1594 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1595 PF_HASHROW_LOCK(sh);
1596 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1597 if (cur->states == 0 && cur->expire <= time_uptime) {
1598 pf_unlink_src_node(cur);
1599 LIST_INSERT_HEAD(&freelist, cur, entry);
1600 } else if (cur->rule.ptr != NULL)
1601 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1602 PF_HASHROW_UNLOCK(sh);
1605 pf_free_src_nodes(&freelist);
1607 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1611 pf_src_tree_remove_state(struct pf_state *s)
1613 struct pf_src_node *sn;
1614 struct pf_srchash *sh;
1617 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1618 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1619 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1621 if (s->src_node != NULL) {
1623 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1624 PF_HASHROW_LOCK(sh);
1627 if (--sn->states == 0)
1628 sn->expire = time_uptime + timeout;
1629 PF_HASHROW_UNLOCK(sh);
1631 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1632 sn = s->nat_src_node;
1633 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1634 PF_HASHROW_LOCK(sh);
1635 if (--sn->states == 0)
1636 sn->expire = time_uptime + timeout;
1637 PF_HASHROW_UNLOCK(sh);
1639 s->src_node = s->nat_src_node = NULL;
1643 * Unlink and potentilly free a state. Function may be
1644 * called with ID hash row locked, but always returns
1645 * unlocked, since it needs to go through key hash locking.
1648 pf_unlink_state(struct pf_state *s, u_int flags)
1650 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1652 if ((flags & PF_ENTER_LOCKED) == 0)
1653 PF_HASHROW_LOCK(ih);
1655 PF_HASHROW_ASSERT(ih);
1657 if (s->timeout == PFTM_UNLINKED) {
1659 * State is being processed
1660 * by pf_unlink_state() in
1663 PF_HASHROW_UNLOCK(ih);
1664 return (0); /* XXXGL: undefined actually */
1667 if (s->src.state == PF_TCPS_PROXY_DST) {
1668 /* XXX wire key the right one? */
1669 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1670 &s->key[PF_SK_WIRE]->addr[1],
1671 &s->key[PF_SK_WIRE]->addr[0],
1672 s->key[PF_SK_WIRE]->port[1],
1673 s->key[PF_SK_WIRE]->port[0],
1674 s->src.seqhi, s->src.seqlo + 1,
1675 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1678 LIST_REMOVE(s, entry);
1679 pf_src_tree_remove_state(s);
1681 if (V_pfsync_delete_state_ptr != NULL)
1682 V_pfsync_delete_state_ptr(s);
1684 STATE_DEC_COUNTERS(s);
1686 s->timeout = PFTM_UNLINKED;
1688 PF_HASHROW_UNLOCK(ih);
1691 /* pf_state_insert() initialises refs to 2, so we can never release the
1692 * last reference here, only in pf_release_state(). */
1693 (void)refcount_release(&s->refs);
1695 return (pf_release_state(s));
1699 pf_free_state(struct pf_state *cur)
1702 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1703 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1706 pf_normalize_tcp_cleanup(cur);
1707 uma_zfree(V_pf_state_z, cur);
1708 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1712 * Called only from pf_purge_thread(), thus serialized.
1715 pf_purge_expired_states(u_int i, int maxcheck)
1717 struct pf_idhash *ih;
1720 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1723 * Go through hash and unlink states that expire now.
1725 while (maxcheck > 0) {
1727 ih = &V_pf_idhash[i];
1729 /* only take the lock if we expect to do work */
1730 if (!LIST_EMPTY(&ih->states)) {
1732 PF_HASHROW_LOCK(ih);
1733 LIST_FOREACH(s, &ih->states, entry) {
1734 if (pf_state_expires(s) <= time_uptime) {
1735 V_pf_status.states -=
1736 pf_unlink_state(s, PF_ENTER_LOCKED);
1739 s->rule.ptr->rule_flag |= PFRULE_REFS;
1740 if (s->nat_rule.ptr != NULL)
1741 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1742 if (s->anchor.ptr != NULL)
1743 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1744 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1746 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1748 PF_HASHROW_UNLOCK(ih);
1751 /* Return when we hit end of hash. */
1752 if (++i > pf_hashmask) {
1753 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1760 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1766 pf_purge_unlinked_rules()
1768 struct pf_rulequeue tmpq;
1769 struct pf_rule *r, *r1;
1772 * If we have overloading task pending, then we'd
1773 * better skip purging this time. There is a tiny
1774 * probability that overloading task references
1775 * an already unlinked rule.
1777 PF_OVERLOADQ_LOCK();
1778 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1779 PF_OVERLOADQ_UNLOCK();
1782 PF_OVERLOADQ_UNLOCK();
1785 * Do naive mark-and-sweep garbage collecting of old rules.
1786 * Reference flag is raised by pf_purge_expired_states()
1787 * and pf_purge_expired_src_nodes().
1789 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1790 * use a temporary queue.
1793 PF_UNLNKDRULES_LOCK();
1794 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1795 if (!(r->rule_flag & PFRULE_REFS)) {
1796 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1797 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1799 r->rule_flag &= ~PFRULE_REFS;
1801 PF_UNLNKDRULES_UNLOCK();
1803 if (!TAILQ_EMPTY(&tmpq)) {
1805 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1806 TAILQ_REMOVE(&tmpq, r, entries);
1814 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1819 u_int32_t a = ntohl(addr->addr32[0]);
1820 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1832 u_int8_t i, curstart, curend, maxstart, maxend;
1833 curstart = curend = maxstart = maxend = 255;
1834 for (i = 0; i < 8; i++) {
1835 if (!addr->addr16[i]) {
1836 if (curstart == 255)
1840 if ((curend - curstart) >
1841 (maxend - maxstart)) {
1842 maxstart = curstart;
1845 curstart = curend = 255;
1848 if ((curend - curstart) >
1849 (maxend - maxstart)) {
1850 maxstart = curstart;
1853 for (i = 0; i < 8; i++) {
1854 if (i >= maxstart && i <= maxend) {
1860 b = ntohs(addr->addr16[i]);
1877 pf_print_state(struct pf_state *s)
1879 pf_print_state_parts(s, NULL, NULL);
1883 pf_print_state_parts(struct pf_state *s,
1884 struct pf_state_key *skwp, struct pf_state_key *sksp)
1886 struct pf_state_key *skw, *sks;
1887 u_int8_t proto, dir;
1889 /* Do our best to fill these, but they're skipped if NULL */
1890 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1891 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1892 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1893 dir = s ? s->direction : 0;
1911 case IPPROTO_ICMPV6:
1915 printf("%u", proto);
1928 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1930 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1935 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1937 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1942 if (proto == IPPROTO_TCP) {
1943 printf(" [lo=%u high=%u win=%u modulator=%u",
1944 s->src.seqlo, s->src.seqhi,
1945 s->src.max_win, s->src.seqdiff);
1946 if (s->src.wscale && s->dst.wscale)
1947 printf(" wscale=%u",
1948 s->src.wscale & PF_WSCALE_MASK);
1950 printf(" [lo=%u high=%u win=%u modulator=%u",
1951 s->dst.seqlo, s->dst.seqhi,
1952 s->dst.max_win, s->dst.seqdiff);
1953 if (s->src.wscale && s->dst.wscale)
1954 printf(" wscale=%u",
1955 s->dst.wscale & PF_WSCALE_MASK);
1958 printf(" %u:%u", s->src.state, s->dst.state);
1963 pf_print_flags(u_int8_t f)
1985 #define PF_SET_SKIP_STEPS(i) \
1987 while (head[i] != cur) { \
1988 head[i]->skip[i].ptr = cur; \
1989 head[i] = TAILQ_NEXT(head[i], entries); \
1994 pf_calc_skip_steps(struct pf_rulequeue *rules)
1996 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1999 cur = TAILQ_FIRST(rules);
2001 for (i = 0; i < PF_SKIP_COUNT; ++i)
2003 while (cur != NULL) {
2005 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2006 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2007 if (cur->direction != prev->direction)
2008 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2009 if (cur->af != prev->af)
2010 PF_SET_SKIP_STEPS(PF_SKIP_AF);
2011 if (cur->proto != prev->proto)
2012 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2013 if (cur->src.neg != prev->src.neg ||
2014 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2015 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2016 if (cur->src.port[0] != prev->src.port[0] ||
2017 cur->src.port[1] != prev->src.port[1] ||
2018 cur->src.port_op != prev->src.port_op)
2019 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2020 if (cur->dst.neg != prev->dst.neg ||
2021 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2022 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2023 if (cur->dst.port[0] != prev->dst.port[0] ||
2024 cur->dst.port[1] != prev->dst.port[1] ||
2025 cur->dst.port_op != prev->dst.port_op)
2026 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2029 cur = TAILQ_NEXT(cur, entries);
2031 for (i = 0; i < PF_SKIP_COUNT; ++i)
2032 PF_SET_SKIP_STEPS(i);
2036 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2038 if (aw1->type != aw2->type)
2040 switch (aw1->type) {
2041 case PF_ADDR_ADDRMASK:
2043 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2045 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2048 case PF_ADDR_DYNIFTL:
2049 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2050 case PF_ADDR_NOROUTE:
2051 case PF_ADDR_URPFFAILED:
2054 return (aw1->p.tbl != aw2->p.tbl);
2056 printf("invalid address type: %d\n", aw1->type);
2062 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2063 * header isn't always a full checksum. In some cases (i.e. output) it's a
2064 * pseudo-header checksum, which is a partial checksum over src/dst IP
2065 * addresses, protocol number and length.
2067 * That means we have the following cases:
2068 * * Input or forwarding: we don't have TSO, the checksum fields are full
2069 * checksums, we need to update the checksum whenever we change anything.
2070 * * Output (i.e. the checksum is a pseudo-header checksum):
2071 * x The field being updated is src/dst address or affects the length of
2072 * the packet. We need to update the pseudo-header checksum (note that this
2073 * checksum is not ones' complement).
2074 * x Some other field is being modified (e.g. src/dst port numbers): We
2075 * don't have to update anything.
2078 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2084 l = cksum + old - new;
2085 l = (l >> 16) + (l & 65535);
2093 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2094 u_int16_t new, u_int8_t udp)
2096 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2099 return (pf_cksum_fixup(cksum, old, new, udp));
2103 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2104 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2110 PF_ACPY(&ao, a, af);
2113 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2121 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2122 ao.addr16[0], an->addr16[0], 0),
2123 ao.addr16[1], an->addr16[1], 0);
2126 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2127 ao.addr16[0], an->addr16[0], u),
2128 ao.addr16[1], an->addr16[1], u);
2130 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2135 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2136 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2137 pf_cksum_fixup(pf_cksum_fixup(*pc,
2138 ao.addr16[0], an->addr16[0], u),
2139 ao.addr16[1], an->addr16[1], u),
2140 ao.addr16[2], an->addr16[2], u),
2141 ao.addr16[3], an->addr16[3], u),
2142 ao.addr16[4], an->addr16[4], u),
2143 ao.addr16[5], an->addr16[5], u),
2144 ao.addr16[6], an->addr16[6], u),
2145 ao.addr16[7], an->addr16[7], u);
2147 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2152 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2153 CSUM_DELAY_DATA_IPV6)) {
2160 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2162 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2166 memcpy(&ao, a, sizeof(ao));
2167 memcpy(a, &an, sizeof(u_int32_t));
2168 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2169 ao % 65536, an % 65536, u);
2173 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2177 memcpy(&ao, a, sizeof(ao));
2178 memcpy(a, &an, sizeof(u_int32_t));
2180 *c = pf_proto_cksum_fixup(m,
2181 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2182 ao % 65536, an % 65536, udp);
2187 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2191 PF_ACPY(&ao, a, AF_INET6);
2192 PF_ACPY(a, an, AF_INET6);
2194 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2195 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2196 pf_cksum_fixup(pf_cksum_fixup(*c,
2197 ao.addr16[0], an->addr16[0], u),
2198 ao.addr16[1], an->addr16[1], u),
2199 ao.addr16[2], an->addr16[2], u),
2200 ao.addr16[3], an->addr16[3], u),
2201 ao.addr16[4], an->addr16[4], u),
2202 ao.addr16[5], an->addr16[5], u),
2203 ao.addr16[6], an->addr16[6], u),
2204 ao.addr16[7], an->addr16[7], u);
2209 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2210 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2211 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2213 struct pf_addr oia, ooa;
2215 PF_ACPY(&oia, ia, af);
2217 PF_ACPY(&ooa, oa, af);
2219 /* Change inner protocol port, fix inner protocol checksum. */
2221 u_int16_t oip = *ip;
2228 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2229 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2231 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2233 /* Change inner ip address, fix inner ip and icmp checksums. */
2234 PF_ACPY(ia, na, af);
2238 u_int32_t oh2c = *h2c;
2240 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2241 oia.addr16[0], ia->addr16[0], 0),
2242 oia.addr16[1], ia->addr16[1], 0);
2243 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2244 oia.addr16[0], ia->addr16[0], 0),
2245 oia.addr16[1], ia->addr16[1], 0);
2246 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2252 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2253 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2254 pf_cksum_fixup(pf_cksum_fixup(*ic,
2255 oia.addr16[0], ia->addr16[0], u),
2256 oia.addr16[1], ia->addr16[1], u),
2257 oia.addr16[2], ia->addr16[2], u),
2258 oia.addr16[3], ia->addr16[3], u),
2259 oia.addr16[4], ia->addr16[4], u),
2260 oia.addr16[5], ia->addr16[5], u),
2261 oia.addr16[6], ia->addr16[6], u),
2262 oia.addr16[7], ia->addr16[7], u);
2266 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2268 PF_ACPY(oa, na, af);
2272 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2273 ooa.addr16[0], oa->addr16[0], 0),
2274 ooa.addr16[1], oa->addr16[1], 0);
2279 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2280 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2281 pf_cksum_fixup(pf_cksum_fixup(*ic,
2282 ooa.addr16[0], oa->addr16[0], u),
2283 ooa.addr16[1], oa->addr16[1], u),
2284 ooa.addr16[2], oa->addr16[2], u),
2285 ooa.addr16[3], oa->addr16[3], u),
2286 ooa.addr16[4], oa->addr16[4], u),
2287 ooa.addr16[5], oa->addr16[5], u),
2288 ooa.addr16[6], oa->addr16[6], u),
2289 ooa.addr16[7], oa->addr16[7], u);
2298 * Need to modulate the sequence numbers in the TCP SACK option
2299 * (credits to Krzysztof Pfaff for report and patch)
2302 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2303 struct tcphdr *th, struct pf_state_peer *dst)
2305 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2306 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2307 int copyback = 0, i, olen;
2308 struct sackblk sack;
2310 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2311 if (hlen < TCPOLEN_SACKLEN ||
2312 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2315 while (hlen >= TCPOLEN_SACKLEN) {
2318 case TCPOPT_EOL: /* FALLTHROUGH */
2326 if (olen >= TCPOLEN_SACKLEN) {
2327 for (i = 2; i + TCPOLEN_SACK <= olen;
2328 i += TCPOLEN_SACK) {
2329 memcpy(&sack, &opt[i], sizeof(sack));
2330 pf_change_proto_a(m, &sack.start, &th->th_sum,
2331 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2332 pf_change_proto_a(m, &sack.end, &th->th_sum,
2333 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2334 memcpy(&opt[i], &sack, sizeof(sack));
2348 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2353 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2354 const struct pf_addr *saddr, const struct pf_addr *daddr,
2355 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2356 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2357 u_int16_t rtag, struct ifnet *ifp)
2359 struct pf_send_entry *pfse;
2363 struct ip *h = NULL;
2366 struct ip6_hdr *h6 = NULL;
2370 struct pf_mtag *pf_mtag;
2375 /* maximum segment size tcp option */
2376 tlen = sizeof(struct tcphdr);
2383 len = sizeof(struct ip) + tlen;
2388 len = sizeof(struct ip6_hdr) + tlen;
2392 panic("%s: unsupported af %d", __func__, af);
2395 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2396 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2399 m = m_gethdr(M_NOWAIT, MT_DATA);
2401 free(pfse, M_PFTEMP);
2405 mac_netinet_firewall_send(m);
2407 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2408 free(pfse, M_PFTEMP);
2413 m->m_flags |= M_SKIP_FIREWALL;
2414 pf_mtag->tag = rtag;
2416 if (r != NULL && r->rtableid >= 0)
2417 M_SETFIB(m, r->rtableid);
2420 if (r != NULL && r->qid) {
2421 pf_mtag->qid = r->qid;
2423 /* add hints for ecn */
2424 pf_mtag->hdr = mtod(m, struct ip *);
2427 m->m_data += max_linkhdr;
2428 m->m_pkthdr.len = m->m_len = len;
2429 m->m_pkthdr.rcvif = NULL;
2430 bzero(m->m_data, len);
2434 h = mtod(m, struct ip *);
2436 /* IP header fields included in the TCP checksum */
2437 h->ip_p = IPPROTO_TCP;
2438 h->ip_len = htons(tlen);
2439 h->ip_src.s_addr = saddr->v4.s_addr;
2440 h->ip_dst.s_addr = daddr->v4.s_addr;
2442 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2447 h6 = mtod(m, struct ip6_hdr *);
2449 /* IP header fields included in the TCP checksum */
2450 h6->ip6_nxt = IPPROTO_TCP;
2451 h6->ip6_plen = htons(tlen);
2452 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2453 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2455 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2461 th->th_sport = sport;
2462 th->th_dport = dport;
2463 th->th_seq = htonl(seq);
2464 th->th_ack = htonl(ack);
2465 th->th_off = tlen >> 2;
2466 th->th_flags = flags;
2467 th->th_win = htons(win);
2470 opt = (char *)(th + 1);
2471 opt[0] = TCPOPT_MAXSEG;
2474 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2481 th->th_sum = in_cksum(m, len);
2483 /* Finish the IP header */
2485 h->ip_hl = sizeof(*h) >> 2;
2486 h->ip_tos = IPTOS_LOWDELAY;
2487 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2488 h->ip_len = htons(len);
2489 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2492 pfse->pfse_type = PFSE_IP;
2498 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2499 sizeof(struct ip6_hdr), tlen);
2501 h6->ip6_vfc |= IPV6_VERSION;
2502 h6->ip6_hlim = IPV6_DEFHLIM;
2504 pfse->pfse_type = PFSE_IP6;
2513 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2514 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2515 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2518 struct pf_addr * const saddr = pd->src;
2519 struct pf_addr * const daddr = pd->dst;
2520 sa_family_t af = pd->af;
2522 /* undo NAT changes, if they have taken place */
2524 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2525 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2527 *pd->sport = sk->port[pd->sidx];
2529 *pd->dport = sk->port[pd->didx];
2531 *pd->proto_sum = bproto_sum;
2533 *pd->ip_sum = bip_sum;
2534 m_copyback(m, off, hdrlen, pd->hdr.any);
2536 if (pd->proto == IPPROTO_TCP &&
2537 ((r->rule_flag & PFRULE_RETURNRST) ||
2538 (r->rule_flag & PFRULE_RETURN)) &&
2539 !(th->th_flags & TH_RST)) {
2540 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2552 h4 = mtod(m, struct ip *);
2553 len = ntohs(h4->ip_len) - off;
2558 h6 = mtod(m, struct ip6_hdr *);
2559 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2564 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2565 REASON_SET(reason, PFRES_PROTCKSUM);
2567 if (th->th_flags & TH_SYN)
2569 if (th->th_flags & TH_FIN)
2571 pf_send_tcp(m, r, af, pd->dst,
2572 pd->src, th->th_dport, th->th_sport,
2573 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2574 r->return_ttl, 1, 0, kif->pfik_ifp);
2576 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2578 pf_send_icmp(m, r->return_icmp >> 8,
2579 r->return_icmp & 255, af, r);
2580 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2582 pf_send_icmp(m, r->return_icmp6 >> 8,
2583 r->return_icmp6 & 255, af, r);
2588 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2592 KASSERT(prio <= PF_PRIO_MAX,
2593 ("%s with invalid pcp", __func__));
2595 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2597 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2598 sizeof(uint8_t), M_NOWAIT);
2601 m_tag_prepend(m, mtag);
2604 *(uint8_t *)(mtag + 1) = prio;
2609 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2614 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2618 if (prio == PF_PRIO_ZERO)
2621 mpcp = *(uint8_t *)(mtag + 1);
2623 return (mpcp == prio);
2627 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2630 struct pf_send_entry *pfse;
2632 struct pf_mtag *pf_mtag;
2634 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2635 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2639 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2640 free(pfse, M_PFTEMP);
2644 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2645 free(pfse, M_PFTEMP);
2649 m0->m_flags |= M_SKIP_FIREWALL;
2651 if (r->rtableid >= 0)
2652 M_SETFIB(m0, r->rtableid);
2656 pf_mtag->qid = r->qid;
2657 /* add hints for ecn */
2658 pf_mtag->hdr = mtod(m0, struct ip *);
2665 pfse->pfse_type = PFSE_ICMP;
2670 pfse->pfse_type = PFSE_ICMP6;
2675 pfse->icmpopts.type = type;
2676 pfse->icmpopts.code = code;
2681 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2682 * If n is 0, they match if they are equal. If n is != 0, they match if they
2686 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2687 struct pf_addr *b, sa_family_t af)
2694 if ((a->addr32[0] & m->addr32[0]) ==
2695 (b->addr32[0] & m->addr32[0]))
2701 if (((a->addr32[0] & m->addr32[0]) ==
2702 (b->addr32[0] & m->addr32[0])) &&
2703 ((a->addr32[1] & m->addr32[1]) ==
2704 (b->addr32[1] & m->addr32[1])) &&
2705 ((a->addr32[2] & m->addr32[2]) ==
2706 (b->addr32[2] & m->addr32[2])) &&
2707 ((a->addr32[3] & m->addr32[3]) ==
2708 (b->addr32[3] & m->addr32[3])))
2727 * Return 1 if b <= a <= e, otherwise return 0.
2730 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2731 struct pf_addr *a, sa_family_t af)
2736 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2737 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2746 for (i = 0; i < 4; ++i)
2747 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2749 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2752 for (i = 0; i < 4; ++i)
2753 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2755 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2765 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2769 return ((p > a1) && (p < a2));
2771 return ((p < a1) || (p > a2));
2773 return ((p >= a1) && (p <= a2));
2787 return (0); /* never reached */
2791 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2796 return (pf_match(op, a1, a2, p));
2800 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2802 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2804 return (pf_match(op, a1, a2, u));
2808 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2810 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2812 return (pf_match(op, a1, a2, g));
2816 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2821 return ((!r->match_tag_not && r->match_tag == *tag) ||
2822 (r->match_tag_not && r->match_tag != *tag));
2826 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2829 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2831 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2834 pd->pf_mtag->tag = tag;
2839 #define PF_ANCHOR_STACKSIZE 32
2840 struct pf_anchor_stackframe {
2841 struct pf_ruleset *rs;
2842 struct pf_rule *r; /* XXX: + match bit */
2843 struct pf_anchor *child;
2847 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2849 #define PF_ANCHORSTACK_MATCH 0x00000001
2850 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2852 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2853 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2854 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2855 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2856 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2860 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2861 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2864 struct pf_anchor_stackframe *f;
2870 if (*depth >= PF_ANCHOR_STACKSIZE) {
2871 printf("%s: anchor stack overflow on %s\n",
2872 __func__, (*r)->anchor->name);
2873 *r = TAILQ_NEXT(*r, entries);
2875 } else if (*depth == 0 && a != NULL)
2877 f = stack + (*depth)++;
2880 if ((*r)->anchor_wildcard) {
2881 struct pf_anchor_node *parent = &(*r)->anchor->children;
2883 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2887 *rs = &f->child->ruleset;
2890 *rs = &(*r)->anchor->ruleset;
2892 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2896 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2897 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2900 struct pf_anchor_stackframe *f;
2909 f = stack + *depth - 1;
2910 fr = PF_ANCHOR_RULE(f);
2911 if (f->child != NULL) {
2912 struct pf_anchor_node *parent;
2915 * This block traverses through
2916 * a wildcard anchor.
2918 parent = &fr->anchor->children;
2919 if (match != NULL && *match) {
2921 * If any of "*" matched, then
2922 * "foo/ *" matched, mark frame
2925 PF_ANCHOR_SET_MATCH(f);
2928 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2929 if (f->child != NULL) {
2930 *rs = &f->child->ruleset;
2931 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2939 if (*depth == 0 && a != NULL)
2942 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2944 *r = TAILQ_NEXT(fr, entries);
2945 } while (*r == NULL);
2952 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2953 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2958 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2959 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2963 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2964 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2965 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2966 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2967 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2968 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2969 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2970 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2976 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2981 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2985 if (addr->addr32[3] == 0xffffffff) {
2986 addr->addr32[3] = 0;
2987 if (addr->addr32[2] == 0xffffffff) {
2988 addr->addr32[2] = 0;
2989 if (addr->addr32[1] == 0xffffffff) {
2990 addr->addr32[1] = 0;
2992 htonl(ntohl(addr->addr32[0]) + 1);
2995 htonl(ntohl(addr->addr32[1]) + 1);
2998 htonl(ntohl(addr->addr32[2]) + 1);
3001 htonl(ntohl(addr->addr32[3]) + 1);
3008 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3010 struct pf_addr *saddr, *daddr;
3011 u_int16_t sport, dport;
3012 struct inpcbinfo *pi;
3015 pd->lookup.uid = UID_MAX;
3016 pd->lookup.gid = GID_MAX;
3018 switch (pd->proto) {
3020 if (pd->hdr.tcp == NULL)
3022 sport = pd->hdr.tcp->th_sport;
3023 dport = pd->hdr.tcp->th_dport;
3027 if (pd->hdr.udp == NULL)
3029 sport = pd->hdr.udp->uh_sport;
3030 dport = pd->hdr.udp->uh_dport;
3036 if (direction == PF_IN) {
3051 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3052 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3054 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3055 daddr->v4, dport, INPLOOKUP_WILDCARD |
3056 INPLOOKUP_RLOCKPCB, NULL, m);
3064 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3065 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3067 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3068 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3069 INPLOOKUP_RLOCKPCB, NULL, m);
3079 INP_RLOCK_ASSERT(inp);
3080 pd->lookup.uid = inp->inp_cred->cr_uid;
3081 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3088 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3092 u_int8_t *opt, optlen;
3093 u_int8_t wscale = 0;
3095 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3096 if (hlen <= sizeof(struct tcphdr))
3098 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3100 opt = hdr + sizeof(struct tcphdr);
3101 hlen -= sizeof(struct tcphdr);
3111 if (wscale > TCP_MAX_WINSHIFT)
3112 wscale = TCP_MAX_WINSHIFT;
3113 wscale |= PF_WSCALE_FLAG;
3128 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3132 u_int8_t *opt, optlen;
3133 u_int16_t mss = V_tcp_mssdflt;
3135 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3136 if (hlen <= sizeof(struct tcphdr))
3138 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3140 opt = hdr + sizeof(struct tcphdr);
3141 hlen -= sizeof(struct tcphdr);
3142 while (hlen >= TCPOLEN_MAXSEG) {
3150 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3166 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3169 struct nhop4_basic nh4;
3172 struct nhop6_basic nh6;
3173 struct in6_addr dst6;
3182 hlen = sizeof(struct ip);
3183 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3184 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3189 hlen = sizeof(struct ip6_hdr);
3190 in6_splitscope(&addr->v6, &dst6, &scopeid);
3191 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3192 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3197 mss = max(V_tcp_mssdflt, mss);
3198 mss = min(mss, offer);
3199 mss = max(mss, 64); /* sanity - at least max opt space */
3204 pf_tcp_iss(struct pf_pdesc *pd)
3207 u_int32_t digest[4];
3209 if (V_pf_tcp_secret_init == 0) {
3210 arc4random_buf(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3211 MD5Init(&V_pf_tcp_secret_ctx);
3212 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3213 sizeof(V_pf_tcp_secret));
3214 V_pf_tcp_secret_init = 1;
3217 ctx = V_pf_tcp_secret_ctx;
3219 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3220 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3221 if (pd->af == AF_INET6) {
3222 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3223 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3225 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3226 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3228 MD5Final((u_char *)digest, &ctx);
3229 V_pf_tcp_iss_off += 4096;
3230 #define ISN_RANDOM_INCREMENT (4096 - 1)
3231 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3233 #undef ISN_RANDOM_INCREMENT
3237 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3238 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3239 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3241 struct pf_rule *nr = NULL;
3242 struct pf_addr * const saddr = pd->src;
3243 struct pf_addr * const daddr = pd->dst;
3244 sa_family_t af = pd->af;
3245 struct pf_rule *r, *a = NULL;
3246 struct pf_ruleset *ruleset = NULL;
3247 struct pf_src_node *nsn = NULL;
3248 struct tcphdr *th = pd->hdr.tcp;
3249 struct pf_state_key *sk = NULL, *nk = NULL;
3251 int rewrite = 0, hdrlen = 0;
3252 int tag = -1, rtableid = -1;
3256 u_int16_t sport = 0, dport = 0;
3257 u_int16_t bproto_sum = 0, bip_sum = 0;
3258 u_int8_t icmptype = 0, icmpcode = 0;
3259 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3264 INP_LOCK_ASSERT(inp);
3265 pd->lookup.uid = inp->inp_cred->cr_uid;
3266 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3267 pd->lookup.done = 1;
3270 switch (pd->proto) {
3272 sport = th->th_sport;
3273 dport = th->th_dport;
3274 hdrlen = sizeof(*th);
3277 sport = pd->hdr.udp->uh_sport;
3278 dport = pd->hdr.udp->uh_dport;
3279 hdrlen = sizeof(*pd->hdr.udp);
3283 if (pd->af != AF_INET)
3285 sport = dport = pd->hdr.icmp->icmp_id;
3286 hdrlen = sizeof(*pd->hdr.icmp);
3287 icmptype = pd->hdr.icmp->icmp_type;
3288 icmpcode = pd->hdr.icmp->icmp_code;
3290 if (icmptype == ICMP_UNREACH ||
3291 icmptype == ICMP_SOURCEQUENCH ||
3292 icmptype == ICMP_REDIRECT ||
3293 icmptype == ICMP_TIMXCEED ||
3294 icmptype == ICMP_PARAMPROB)
3299 case IPPROTO_ICMPV6:
3302 sport = dport = pd->hdr.icmp6->icmp6_id;
3303 hdrlen = sizeof(*pd->hdr.icmp6);
3304 icmptype = pd->hdr.icmp6->icmp6_type;
3305 icmpcode = pd->hdr.icmp6->icmp6_code;
3307 if (icmptype == ICMP6_DST_UNREACH ||
3308 icmptype == ICMP6_PACKET_TOO_BIG ||
3309 icmptype == ICMP6_TIME_EXCEEDED ||
3310 icmptype == ICMP6_PARAM_PROB)
3315 sport = dport = hdrlen = 0;
3319 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3321 /* check packet for BINAT/NAT/RDR */
3322 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3323 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3324 KASSERT(sk != NULL, ("%s: null sk", __func__));
3325 KASSERT(nk != NULL, ("%s: null nk", __func__));
3328 bip_sum = *pd->ip_sum;
3330 switch (pd->proto) {
3332 bproto_sum = th->th_sum;
3333 pd->proto_sum = &th->th_sum;
3335 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3336 nk->port[pd->sidx] != sport) {
3337 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3338 &th->th_sum, &nk->addr[pd->sidx],
3339 nk->port[pd->sidx], 0, af);
3340 pd->sport = &th->th_sport;
3341 sport = th->th_sport;
3344 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3345 nk->port[pd->didx] != dport) {
3346 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3347 &th->th_sum, &nk->addr[pd->didx],
3348 nk->port[pd->didx], 0, af);
3349 dport = th->th_dport;
3350 pd->dport = &th->th_dport;
3355 bproto_sum = pd->hdr.udp->uh_sum;
3356 pd->proto_sum = &pd->hdr.udp->uh_sum;
3358 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3359 nk->port[pd->sidx] != sport) {
3360 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3361 pd->ip_sum, &pd->hdr.udp->uh_sum,
3362 &nk->addr[pd->sidx],
3363 nk->port[pd->sidx], 1, af);
3364 sport = pd->hdr.udp->uh_sport;
3365 pd->sport = &pd->hdr.udp->uh_sport;
3368 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3369 nk->port[pd->didx] != dport) {
3370 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3371 pd->ip_sum, &pd->hdr.udp->uh_sum,
3372 &nk->addr[pd->didx],
3373 nk->port[pd->didx], 1, af);
3374 dport = pd->hdr.udp->uh_dport;
3375 pd->dport = &pd->hdr.udp->uh_dport;
3381 nk->port[0] = nk->port[1];
3382 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3383 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3384 nk->addr[pd->sidx].v4.s_addr, 0);
3386 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3387 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3388 nk->addr[pd->didx].v4.s_addr, 0);
3390 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3391 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3392 pd->hdr.icmp->icmp_cksum, sport,
3394 pd->hdr.icmp->icmp_id = nk->port[1];
3395 pd->sport = &pd->hdr.icmp->icmp_id;
3397 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3401 case IPPROTO_ICMPV6:
3402 nk->port[0] = nk->port[1];
3403 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3404 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3405 &nk->addr[pd->sidx], 0);
3407 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3408 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3409 &nk->addr[pd->didx], 0);
3418 &nk->addr[pd->sidx], AF_INET))
3419 pf_change_a(&saddr->v4.s_addr,
3421 nk->addr[pd->sidx].v4.s_addr, 0);
3424 &nk->addr[pd->didx], AF_INET))
3425 pf_change_a(&daddr->v4.s_addr,
3427 nk->addr[pd->didx].v4.s_addr, 0);
3433 &nk->addr[pd->sidx], AF_INET6))
3434 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3437 &nk->addr[pd->didx], AF_INET6))
3438 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3451 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3452 r = r->skip[PF_SKIP_IFP].ptr;
3453 else if (r->direction && r->direction != direction)
3454 r = r->skip[PF_SKIP_DIR].ptr;
3455 else if (r->af && r->af != af)
3456 r = r->skip[PF_SKIP_AF].ptr;
3457 else if (r->proto && r->proto != pd->proto)
3458 r = r->skip[PF_SKIP_PROTO].ptr;
3459 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3460 r->src.neg, kif, M_GETFIB(m)))
3461 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3462 /* tcp/udp only. port_op always 0 in other cases */
3463 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3464 r->src.port[0], r->src.port[1], sport))
3465 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3466 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3467 r->dst.neg, NULL, M_GETFIB(m)))
3468 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3469 /* tcp/udp only. port_op always 0 in other cases */
3470 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3471 r->dst.port[0], r->dst.port[1], dport))
3472 r = r->skip[PF_SKIP_DST_PORT].ptr;
3473 /* icmp only. type always 0 in other cases */
3474 else if (r->type && r->type != icmptype + 1)
3475 r = TAILQ_NEXT(r, entries);
3476 /* icmp only. type always 0 in other cases */
3477 else if (r->code && r->code != icmpcode + 1)
3478 r = TAILQ_NEXT(r, entries);
3479 else if (r->tos && !(r->tos == pd->tos))
3480 r = TAILQ_NEXT(r, entries);
3481 else if (r->rule_flag & PFRULE_FRAGMENT)
3482 r = TAILQ_NEXT(r, entries);
3483 else if (pd->proto == IPPROTO_TCP &&
3484 (r->flagset & th->th_flags) != r->flags)
3485 r = TAILQ_NEXT(r, entries);
3486 /* tcp/udp only. uid.op always 0 in other cases */
3487 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3488 pf_socket_lookup(direction, pd, m), 1)) &&
3489 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3491 r = TAILQ_NEXT(r, entries);
3492 /* tcp/udp only. gid.op always 0 in other cases */
3493 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3494 pf_socket_lookup(direction, pd, m), 1)) &&
3495 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3497 r = TAILQ_NEXT(r, entries);
3499 !pf_match_ieee8021q_pcp(r->prio, m))
3500 r = TAILQ_NEXT(r, entries);
3502 r->prob <= arc4random())
3503 r = TAILQ_NEXT(r, entries);
3504 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3505 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3506 r = TAILQ_NEXT(r, entries);
3507 else if (r->os_fingerprint != PF_OSFP_ANY &&
3508 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3509 pf_osfp_fingerprint(pd, m, off, th),
3510 r->os_fingerprint)))
3511 r = TAILQ_NEXT(r, entries);
3515 if (r->rtableid >= 0)
3516 rtableid = r->rtableid;
3517 if (r->anchor == NULL) {
3524 r = TAILQ_NEXT(r, entries);
3526 pf_step_into_anchor(anchor_stack, &asd,
3527 &ruleset, PF_RULESET_FILTER, &r, &a,
3530 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3531 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3538 REASON_SET(&reason, PFRES_MATCH);
3540 if (r->log || (nr != NULL && nr->log)) {
3542 m_copyback(m, off, hdrlen, pd->hdr.any);
3543 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3547 if ((r->action == PF_DROP) &&
3548 ((r->rule_flag & PFRULE_RETURNRST) ||
3549 (r->rule_flag & PFRULE_RETURNICMP) ||
3550 (r->rule_flag & PFRULE_RETURN))) {
3551 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3552 bip_sum, hdrlen, &reason);
3555 if (r->action == PF_DROP)
3558 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3559 REASON_SET(&reason, PFRES_MEMORY);
3563 M_SETFIB(m, rtableid);
3565 if (!state_icmp && (r->keep_state || nr != NULL ||
3566 (pd->flags & PFDESC_TCP_NORM))) {
3568 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3569 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3571 if (action != PF_PASS) {
3572 if (action == PF_DROP &&
3573 (r->rule_flag & PFRULE_RETURN))
3574 pf_return(r, nr, pd, sk, off, m, th, kif,
3575 bproto_sum, bip_sum, hdrlen, &reason);
3580 uma_zfree(V_pf_state_key_z, sk);
3582 uma_zfree(V_pf_state_key_z, nk);
3585 /* copy back packet headers if we performed NAT operations */
3587 m_copyback(m, off, hdrlen, pd->hdr.any);
3589 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3590 direction == PF_OUT &&
3591 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3593 * We want the state created, but we dont
3594 * want to send this in case a partner
3595 * firewall has to know about it to allow
3596 * replies through it.
3604 uma_zfree(V_pf_state_key_z, sk);
3606 uma_zfree(V_pf_state_key_z, nk);
3611 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3612 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3613 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3614 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3615 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3617 struct pf_state *s = NULL;
3618 struct pf_src_node *sn = NULL;
3619 struct tcphdr *th = pd->hdr.tcp;
3620 u_int16_t mss = V_tcp_mssdflt;
3623 /* check maximums */
3624 if (r->max_states &&
3625 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3626 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3627 REASON_SET(&reason, PFRES_MAXSTATES);
3630 /* src node for filter rule */
3631 if ((r->rule_flag & PFRULE_SRCTRACK ||
3632 r->rpool.opts & PF_POOL_STICKYADDR) &&
3633 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3634 REASON_SET(&reason, PFRES_SRCLIMIT);
3637 /* src node for translation rule */
3638 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3639 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3640 REASON_SET(&reason, PFRES_SRCLIMIT);
3643 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3645 REASON_SET(&reason, PFRES_MEMORY);
3649 s->nat_rule.ptr = nr;
3651 STATE_INC_COUNTERS(s);
3653 s->state_flags |= PFSTATE_ALLOWOPTS;
3654 if (r->rule_flag & PFRULE_STATESLOPPY)
3655 s->state_flags |= PFSTATE_SLOPPY;
3656 s->log = r->log & PF_LOG_ALL;
3657 s->sync_state = PFSYNC_S_NONE;
3659 s->log |= nr->log & PF_LOG_ALL;
3660 switch (pd->proto) {
3662 s->src.seqlo = ntohl(th->th_seq);
3663 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3664 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3665 r->keep_state == PF_STATE_MODULATE) {
3666 /* Generate sequence number modulator */
3667 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3670 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3671 htonl(s->src.seqlo + s->src.seqdiff), 0);
3675 if (th->th_flags & TH_SYN) {
3677 s->src.wscale = pf_get_wscale(m, off,
3678 th->th_off, pd->af);
3680 s->src.max_win = MAX(ntohs(th->th_win), 1);
3681 if (s->src.wscale & PF_WSCALE_MASK) {
3682 /* Remove scale factor from initial window */
3683 int win = s->src.max_win;
3684 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3685 s->src.max_win = (win - 1) >>
3686 (s->src.wscale & PF_WSCALE_MASK);
3688 if (th->th_flags & TH_FIN)
3692 s->src.state = TCPS_SYN_SENT;
3693 s->dst.state = TCPS_CLOSED;
3694 s->timeout = PFTM_TCP_FIRST_PACKET;
3697 s->src.state = PFUDPS_SINGLE;
3698 s->dst.state = PFUDPS_NO_TRAFFIC;
3699 s->timeout = PFTM_UDP_FIRST_PACKET;
3703 case IPPROTO_ICMPV6:
3705 s->timeout = PFTM_ICMP_FIRST_PACKET;
3708 s->src.state = PFOTHERS_SINGLE;
3709 s->dst.state = PFOTHERS_NO_TRAFFIC;
3710 s->timeout = PFTM_OTHER_FIRST_PACKET;
3714 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3715 REASON_SET(&reason, PFRES_MAPFAILED);
3716 pf_src_tree_remove_state(s);
3717 STATE_DEC_COUNTERS(s);
3718 uma_zfree(V_pf_state_z, s);
3721 s->rt_kif = r->rpool.cur->kif;
3724 s->creation = time_uptime;
3725 s->expire = time_uptime;
3730 /* XXX We only modify one side for now. */
3731 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3732 s->nat_src_node = nsn;
3734 if (pd->proto == IPPROTO_TCP) {
3735 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3736 off, pd, th, &s->src, &s->dst)) {
3737 REASON_SET(&reason, PFRES_MEMORY);
3738 pf_src_tree_remove_state(s);
3739 STATE_DEC_COUNTERS(s);
3740 uma_zfree(V_pf_state_z, s);
3743 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3744 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3745 &s->src, &s->dst, rewrite)) {
3746 /* This really shouldn't happen!!! */
3747 DPFPRINTF(PF_DEBUG_URGENT,
3748 ("pf_normalize_tcp_stateful failed on first pkt"));
3749 pf_normalize_tcp_cleanup(s);
3750 pf_src_tree_remove_state(s);
3751 STATE_DEC_COUNTERS(s);
3752 uma_zfree(V_pf_state_z, s);
3756 s->direction = pd->dir;
3759 * sk/nk could already been setup by pf_get_translation().
3762 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3763 __func__, nr, sk, nk));
3764 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3769 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3770 __func__, nr, sk, nk));
3772 /* Swap sk/nk for PF_OUT. */
3773 if (pf_state_insert(BOUND_IFACE(r, kif),
3774 (pd->dir == PF_IN) ? sk : nk,
3775 (pd->dir == PF_IN) ? nk : sk, s)) {
3776 if (pd->proto == IPPROTO_TCP)
3777 pf_normalize_tcp_cleanup(s);
3778 REASON_SET(&reason, PFRES_STATEINS);
3779 pf_src_tree_remove_state(s);
3780 STATE_DEC_COUNTERS(s);
3781 uma_zfree(V_pf_state_z, s);
3788 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3789 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3790 s->src.state = PF_TCPS_PROXY_SRC;
3791 /* undo NAT changes, if they have taken place */
3793 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3794 if (pd->dir == PF_OUT)
3795 skt = s->key[PF_SK_STACK];
3796 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3797 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3799 *pd->sport = skt->port[pd->sidx];
3801 *pd->dport = skt->port[pd->didx];
3803 *pd->proto_sum = bproto_sum;
3805 *pd->ip_sum = bip_sum;
3806 m_copyback(m, off, hdrlen, pd->hdr.any);
3808 s->src.seqhi = htonl(arc4random());
3809 /* Find mss option */
3810 int rtid = M_GETFIB(m);
3811 mss = pf_get_mss(m, off, th->th_off, pd->af);
3812 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3813 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3815 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3816 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3817 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3818 REASON_SET(&reason, PFRES_SYNPROXY);
3819 return (PF_SYNPROXY_DROP);
3826 uma_zfree(V_pf_state_key_z, sk);
3828 uma_zfree(V_pf_state_key_z, nk);
3831 struct pf_srchash *sh;
3833 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3834 PF_HASHROW_LOCK(sh);
3835 if (--sn->states == 0 && sn->expire == 0) {
3836 pf_unlink_src_node(sn);
3837 uma_zfree(V_pf_sources_z, sn);
3839 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3841 PF_HASHROW_UNLOCK(sh);
3844 if (nsn != sn && nsn != NULL) {
3845 struct pf_srchash *sh;
3847 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3848 PF_HASHROW_LOCK(sh);
3849 if (--nsn->states == 0 && nsn->expire == 0) {
3850 pf_unlink_src_node(nsn);
3851 uma_zfree(V_pf_sources_z, nsn);
3853 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3855 PF_HASHROW_UNLOCK(sh);
3862 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3863 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3864 struct pf_ruleset **rsm)
3866 struct pf_rule *r, *a = NULL;
3867 struct pf_ruleset *ruleset = NULL;
3868 sa_family_t af = pd->af;
3873 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3877 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3880 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3881 r = r->skip[PF_SKIP_IFP].ptr;
3882 else if (r->direction && r->direction != direction)
3883 r = r->skip[PF_SKIP_DIR].ptr;
3884 else if (r->af && r->af != af)
3885 r = r->skip[PF_SKIP_AF].ptr;
3886 else if (r->proto && r->proto != pd->proto)
3887 r = r->skip[PF_SKIP_PROTO].ptr;
3888 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3889 r->src.neg, kif, M_GETFIB(m)))
3890 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3891 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3892 r->dst.neg, NULL, M_GETFIB(m)))
3893 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3894 else if (r->tos && !(r->tos == pd->tos))
3895 r = TAILQ_NEXT(r, entries);
3896 else if (r->os_fingerprint != PF_OSFP_ANY)
3897 r = TAILQ_NEXT(r, entries);
3898 else if (pd->proto == IPPROTO_UDP &&
3899 (r->src.port_op || r->dst.port_op))
3900 r = TAILQ_NEXT(r, entries);
3901 else if (pd->proto == IPPROTO_TCP &&
3902 (r->src.port_op || r->dst.port_op || r->flagset))
3903 r = TAILQ_NEXT(r, entries);
3904 else if ((pd->proto == IPPROTO_ICMP ||
3905 pd->proto == IPPROTO_ICMPV6) &&
3906 (r->type || r->code))
3907 r = TAILQ_NEXT(r, entries);
3909 !pf_match_ieee8021q_pcp(r->prio, m))
3910 r = TAILQ_NEXT(r, entries);
3911 else if (r->prob && r->prob <=
3912 (arc4random() % (UINT_MAX - 1) + 1))
3913 r = TAILQ_NEXT(r, entries);
3914 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3915 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3916 r = TAILQ_NEXT(r, entries);
3918 if (r->anchor == NULL) {
3925 r = TAILQ_NEXT(r, entries);
3927 pf_step_into_anchor(anchor_stack, &asd,
3928 &ruleset, PF_RULESET_FILTER, &r, &a,
3931 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3932 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3939 REASON_SET(&reason, PFRES_MATCH);
3942 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3945 if (r->action != PF_PASS)
3948 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3949 REASON_SET(&reason, PFRES_MEMORY);
3957 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3958 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3959 struct pf_pdesc *pd, u_short *reason, int *copyback)
3961 struct tcphdr *th = pd->hdr.tcp;
3962 u_int16_t win = ntohs(th->th_win);
3963 u_int32_t ack, end, seq, orig_seq;
3967 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3968 sws = src->wscale & PF_WSCALE_MASK;
3969 dws = dst->wscale & PF_WSCALE_MASK;
3974 * Sequence tracking algorithm from Guido van Rooij's paper:
3975 * http://www.madison-gurkha.com/publications/tcp_filtering/
3979 orig_seq = seq = ntohl(th->th_seq);
3980 if (src->seqlo == 0) {
3981 /* First packet from this end. Set its state */
3983 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3984 src->scrub == NULL) {
3985 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3986 REASON_SET(reason, PFRES_MEMORY);
3991 /* Deferred generation of sequence number modulator */
3992 if (dst->seqdiff && !src->seqdiff) {
3993 /* use random iss for the TCP server */
3994 while ((src->seqdiff = arc4random() - seq) == 0)
3996 ack = ntohl(th->th_ack) - dst->seqdiff;
3997 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3999 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4002 ack = ntohl(th->th_ack);
4005 end = seq + pd->p_len;
4006 if (th->th_flags & TH_SYN) {
4008 if (dst->wscale & PF_WSCALE_FLAG) {
4009 src->wscale = pf_get_wscale(m, off, th->th_off,
4011 if (src->wscale & PF_WSCALE_FLAG) {
4012 /* Remove scale factor from initial
4014 sws = src->wscale & PF_WSCALE_MASK;
4015 win = ((u_int32_t)win + (1 << sws) - 1)
4017 dws = dst->wscale & PF_WSCALE_MASK;
4019 /* fixup other window */
4020 dst->max_win <<= dst->wscale &
4022 /* in case of a retrans SYN|ACK */
4027 if (th->th_flags & TH_FIN)
4031 if (src->state < TCPS_SYN_SENT)
4032 src->state = TCPS_SYN_SENT;
4035 * May need to slide the window (seqhi may have been set by
4036 * the crappy stack check or if we picked up the connection
4037 * after establishment)
4039 if (src->seqhi == 1 ||
4040 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4041 src->seqhi = end + MAX(1, dst->max_win << dws);
4042 if (win > src->max_win)
4046 ack = ntohl(th->th_ack) - dst->seqdiff;
4048 /* Modulate sequence numbers */
4049 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4051 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4054 end = seq + pd->p_len;
4055 if (th->th_flags & TH_SYN)
4057 if (th->th_flags & TH_FIN)
4061 if ((th->th_flags & TH_ACK) == 0) {
4062 /* Let it pass through the ack skew check */
4064 } else if ((ack == 0 &&
4065 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4066 /* broken tcp stacks do not set ack */
4067 (dst->state < TCPS_SYN_SENT)) {
4069 * Many stacks (ours included) will set the ACK number in an
4070 * FIN|ACK if the SYN times out -- no sequence to ACK.
4076 /* Ease sequencing restrictions on no data packets */
4081 ackskew = dst->seqlo - ack;
4085 * Need to demodulate the sequence numbers in any TCP SACK options
4086 * (Selective ACK). We could optionally validate the SACK values
4087 * against the current ACK window, either forwards or backwards, but
4088 * I'm not confident that SACK has been implemented properly
4089 * everywhere. It wouldn't surprise me if several stacks accidentally
4090 * SACK too far backwards of previously ACKed data. There really aren't
4091 * any security implications of bad SACKing unless the target stack
4092 * doesn't validate the option length correctly. Someone trying to
4093 * spoof into a TCP connection won't bother blindly sending SACK
4096 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4097 if (pf_modulate_sack(m, off, pd, th, dst))
4102 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4103 if (SEQ_GEQ(src->seqhi, end) &&
4104 /* Last octet inside other's window space */
4105 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4106 /* Retrans: not more than one window back */
4107 (ackskew >= -MAXACKWINDOW) &&
4108 /* Acking not more than one reassembled fragment backwards */
4109 (ackskew <= (MAXACKWINDOW << sws)) &&
4110 /* Acking not more than one window forward */
4111 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4112 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4113 (pd->flags & PFDESC_IP_REAS) == 0)) {
4114 /* Require an exact/+1 sequence match on resets when possible */
4116 if (dst->scrub || src->scrub) {
4117 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4118 *state, src, dst, copyback))
4122 /* update max window */
4123 if (src->max_win < win)
4125 /* synchronize sequencing */
4126 if (SEQ_GT(end, src->seqlo))
4128 /* slide the window of what the other end can send */
4129 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4130 dst->seqhi = ack + MAX((win << sws), 1);
4134 if (th->th_flags & TH_SYN)
4135 if (src->state < TCPS_SYN_SENT)
4136 src->state = TCPS_SYN_SENT;
4137 if (th->th_flags & TH_FIN)
4138 if (src->state < TCPS_CLOSING)
4139 src->state = TCPS_CLOSING;
4140 if (th->th_flags & TH_ACK) {
4141 if (dst->state == TCPS_SYN_SENT) {
4142 dst->state = TCPS_ESTABLISHED;
4143 if (src->state == TCPS_ESTABLISHED &&
4144 (*state)->src_node != NULL &&
4145 pf_src_connlimit(state)) {
4146 REASON_SET(reason, PFRES_SRCLIMIT);
4149 } else if (dst->state == TCPS_CLOSING)
4150 dst->state = TCPS_FIN_WAIT_2;
4152 if (th->th_flags & TH_RST)
4153 src->state = dst->state = TCPS_TIME_WAIT;
4155 /* update expire time */
4156 (*state)->expire = time_uptime;
4157 if (src->state >= TCPS_FIN_WAIT_2 &&
4158 dst->state >= TCPS_FIN_WAIT_2)
4159 (*state)->timeout = PFTM_TCP_CLOSED;
4160 else if (src->state >= TCPS_CLOSING &&
4161 dst->state >= TCPS_CLOSING)
4162 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4163 else if (src->state < TCPS_ESTABLISHED ||
4164 dst->state < TCPS_ESTABLISHED)
4165 (*state)->timeout = PFTM_TCP_OPENING;
4166 else if (src->state >= TCPS_CLOSING ||
4167 dst->state >= TCPS_CLOSING)
4168 (*state)->timeout = PFTM_TCP_CLOSING;
4170 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4172 /* Fall through to PASS packet */
4174 } else if ((dst->state < TCPS_SYN_SENT ||
4175 dst->state >= TCPS_FIN_WAIT_2 ||
4176 src->state >= TCPS_FIN_WAIT_2) &&
4177 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4178 /* Within a window forward of the originating packet */
4179 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4180 /* Within a window backward of the originating packet */
4183 * This currently handles three situations:
4184 * 1) Stupid stacks will shotgun SYNs before their peer
4186 * 2) When PF catches an already established stream (the
4187 * firewall rebooted, the state table was flushed, routes
4189 * 3) Packets get funky immediately after the connection
4190 * closes (this should catch Solaris spurious ACK|FINs
4191 * that web servers like to spew after a close)
4193 * This must be a little more careful than the above code
4194 * since packet floods will also be caught here. We don't
4195 * update the TTL here to mitigate the damage of a packet
4196 * flood and so the same code can handle awkward establishment
4197 * and a loosened connection close.
4198 * In the establishment case, a correct peer response will
4199 * validate the connection, go through the normal state code
4200 * and keep updating the state TTL.
4203 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4204 printf("pf: loose state match: ");
4205 pf_print_state(*state);
4206 pf_print_flags(th->th_flags);
4207 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4208 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4209 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4210 (unsigned long long)(*state)->packets[1],
4211 pd->dir == PF_IN ? "in" : "out",
4212 pd->dir == (*state)->direction ? "fwd" : "rev");
4215 if (dst->scrub || src->scrub) {
4216 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4217 *state, src, dst, copyback))
4221 /* update max window */
4222 if (src->max_win < win)
4224 /* synchronize sequencing */
4225 if (SEQ_GT(end, src->seqlo))
4227 /* slide the window of what the other end can send */
4228 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4229 dst->seqhi = ack + MAX((win << sws), 1);
4232 * Cannot set dst->seqhi here since this could be a shotgunned
4233 * SYN and not an already established connection.
4236 if (th->th_flags & TH_FIN)
4237 if (src->state < TCPS_CLOSING)
4238 src->state = TCPS_CLOSING;
4239 if (th->th_flags & TH_RST)
4240 src->state = dst->state = TCPS_TIME_WAIT;
4242 /* Fall through to PASS packet */
4245 if ((*state)->dst.state == TCPS_SYN_SENT &&
4246 (*state)->src.state == TCPS_SYN_SENT) {
4247 /* Send RST for state mismatches during handshake */
4248 if (!(th->th_flags & TH_RST))
4249 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4250 pd->dst, pd->src, th->th_dport,
4251 th->th_sport, ntohl(th->th_ack), 0,
4253 (*state)->rule.ptr->return_ttl, 1, 0,
4258 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4259 printf("pf: BAD state: ");
4260 pf_print_state(*state);
4261 pf_print_flags(th->th_flags);
4262 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4263 "pkts=%llu:%llu dir=%s,%s\n",
4264 seq, orig_seq, ack, pd->p_len, ackskew,
4265 (unsigned long long)(*state)->packets[0],
4266 (unsigned long long)(*state)->packets[1],
4267 pd->dir == PF_IN ? "in" : "out",
4268 pd->dir == (*state)->direction ? "fwd" : "rev");
4269 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4270 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4271 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4273 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4274 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4275 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4276 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4278 REASON_SET(reason, PFRES_BADSTATE);
4286 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4287 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4289 struct tcphdr *th = pd->hdr.tcp;
4291 if (th->th_flags & TH_SYN)
4292 if (src->state < TCPS_SYN_SENT)
4293 src->state = TCPS_SYN_SENT;
4294 if (th->th_flags & TH_FIN)
4295 if (src->state < TCPS_CLOSING)
4296 src->state = TCPS_CLOSING;
4297 if (th->th_flags & TH_ACK) {
4298 if (dst->state == TCPS_SYN_SENT) {
4299 dst->state = TCPS_ESTABLISHED;
4300 if (src->state == TCPS_ESTABLISHED &&
4301 (*state)->src_node != NULL &&
4302 pf_src_connlimit(state)) {
4303 REASON_SET(reason, PFRES_SRCLIMIT);
4306 } else if (dst->state == TCPS_CLOSING) {
4307 dst->state = TCPS_FIN_WAIT_2;
4308 } else if (src->state == TCPS_SYN_SENT &&
4309 dst->state < TCPS_SYN_SENT) {
4311 * Handle a special sloppy case where we only see one
4312 * half of the connection. If there is a ACK after
4313 * the initial SYN without ever seeing a packet from
4314 * the destination, set the connection to established.
4316 dst->state = src->state = TCPS_ESTABLISHED;
4317 if ((*state)->src_node != NULL &&
4318 pf_src_connlimit(state)) {
4319 REASON_SET(reason, PFRES_SRCLIMIT);
4322 } else if (src->state == TCPS_CLOSING &&
4323 dst->state == TCPS_ESTABLISHED &&
4326 * Handle the closing of half connections where we
4327 * don't see the full bidirectional FIN/ACK+ACK
4330 dst->state = TCPS_CLOSING;
4333 if (th->th_flags & TH_RST)
4334 src->state = dst->state = TCPS_TIME_WAIT;
4336 /* update expire time */
4337 (*state)->expire = time_uptime;
4338 if (src->state >= TCPS_FIN_WAIT_2 &&
4339 dst->state >= TCPS_FIN_WAIT_2)
4340 (*state)->timeout = PFTM_TCP_CLOSED;
4341 else if (src->state >= TCPS_CLOSING &&
4342 dst->state >= TCPS_CLOSING)
4343 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4344 else if (src->state < TCPS_ESTABLISHED ||
4345 dst->state < TCPS_ESTABLISHED)
4346 (*state)->timeout = PFTM_TCP_OPENING;
4347 else if (src->state >= TCPS_CLOSING ||
4348 dst->state >= TCPS_CLOSING)
4349 (*state)->timeout = PFTM_TCP_CLOSING;
4351 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4357 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4358 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4361 struct pf_state_key_cmp key;
4362 struct tcphdr *th = pd->hdr.tcp;
4364 struct pf_state_peer *src, *dst;
4365 struct pf_state_key *sk;
4367 bzero(&key, sizeof(key));
4369 key.proto = IPPROTO_TCP;
4370 if (direction == PF_IN) { /* wire side, straight */
4371 PF_ACPY(&key.addr[0], pd->src, key.af);
4372 PF_ACPY(&key.addr[1], pd->dst, key.af);
4373 key.port[0] = th->th_sport;
4374 key.port[1] = th->th_dport;
4375 } else { /* stack side, reverse */
4376 PF_ACPY(&key.addr[1], pd->src, key.af);
4377 PF_ACPY(&key.addr[0], pd->dst, key.af);
4378 key.port[1] = th->th_sport;
4379 key.port[0] = th->th_dport;
4382 STATE_LOOKUP(kif, &key, direction, *state, pd);
4384 if (direction == (*state)->direction) {
4385 src = &(*state)->src;
4386 dst = &(*state)->dst;
4388 src = &(*state)->dst;
4389 dst = &(*state)->src;
4392 sk = (*state)->key[pd->didx];
4394 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4395 if (direction != (*state)->direction) {
4396 REASON_SET(reason, PFRES_SYNPROXY);
4397 return (PF_SYNPROXY_DROP);
4399 if (th->th_flags & TH_SYN) {
4400 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4401 REASON_SET(reason, PFRES_SYNPROXY);
4404 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4405 pd->src, th->th_dport, th->th_sport,
4406 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4407 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4408 REASON_SET(reason, PFRES_SYNPROXY);
4409 return (PF_SYNPROXY_DROP);
4410 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4411 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4412 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4413 REASON_SET(reason, PFRES_SYNPROXY);
4415 } else if ((*state)->src_node != NULL &&
4416 pf_src_connlimit(state)) {
4417 REASON_SET(reason, PFRES_SRCLIMIT);
4420 (*state)->src.state = PF_TCPS_PROXY_DST;
4422 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4423 if (direction == (*state)->direction) {
4424 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4425 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4426 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4427 REASON_SET(reason, PFRES_SYNPROXY);
4430 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4431 if ((*state)->dst.seqhi == 1)
4432 (*state)->dst.seqhi = htonl(arc4random());
4433 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4434 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4435 sk->port[pd->sidx], sk->port[pd->didx],
4436 (*state)->dst.seqhi, 0, TH_SYN, 0,
4437 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4438 REASON_SET(reason, PFRES_SYNPROXY);
4439 return (PF_SYNPROXY_DROP);
4440 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4442 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4443 REASON_SET(reason, PFRES_SYNPROXY);
4446 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4447 (*state)->dst.seqlo = ntohl(th->th_seq);
4448 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4449 pd->src, th->th_dport, th->th_sport,
4450 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4451 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4452 (*state)->tag, NULL);
4453 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4454 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4455 sk->port[pd->sidx], sk->port[pd->didx],
4456 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4457 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4458 (*state)->src.seqdiff = (*state)->dst.seqhi -
4459 (*state)->src.seqlo;
4460 (*state)->dst.seqdiff = (*state)->src.seqhi -
4461 (*state)->dst.seqlo;
4462 (*state)->src.seqhi = (*state)->src.seqlo +
4463 (*state)->dst.max_win;
4464 (*state)->dst.seqhi = (*state)->dst.seqlo +
4465 (*state)->src.max_win;
4466 (*state)->src.wscale = (*state)->dst.wscale = 0;
4467 (*state)->src.state = (*state)->dst.state =
4469 REASON_SET(reason, PFRES_SYNPROXY);
4470 return (PF_SYNPROXY_DROP);
4474 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4475 dst->state >= TCPS_FIN_WAIT_2 &&
4476 src->state >= TCPS_FIN_WAIT_2) {
4477 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4478 printf("pf: state reuse ");
4479 pf_print_state(*state);
4480 pf_print_flags(th->th_flags);
4483 /* XXX make sure it's the same direction ?? */
4484 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4485 pf_unlink_state(*state, PF_ENTER_LOCKED);
4490 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4491 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4494 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4495 ©back) == PF_DROP)
4499 /* translate source/destination address, if necessary */
4500 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4501 struct pf_state_key *nk = (*state)->key[pd->didx];
4503 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4504 nk->port[pd->sidx] != th->th_sport)
4505 pf_change_ap(m, pd->src, &th->th_sport,
4506 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4507 nk->port[pd->sidx], 0, pd->af);
4509 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4510 nk->port[pd->didx] != th->th_dport)
4511 pf_change_ap(m, pd->dst, &th->th_dport,
4512 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4513 nk->port[pd->didx], 0, pd->af);
4517 /* Copyback sequence modulation or stateful scrub changes if needed */
4519 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4525 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4526 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4528 struct pf_state_peer *src, *dst;
4529 struct pf_state_key_cmp key;
4530 struct udphdr *uh = pd->hdr.udp;
4532 bzero(&key, sizeof(key));
4534 key.proto = IPPROTO_UDP;
4535 if (direction == PF_IN) { /* wire side, straight */
4536 PF_ACPY(&key.addr[0], pd->src, key.af);
4537 PF_ACPY(&key.addr[1], pd->dst, key.af);
4538 key.port[0] = uh->uh_sport;
4539 key.port[1] = uh->uh_dport;
4540 } else { /* stack side, reverse */
4541 PF_ACPY(&key.addr[1], pd->src, key.af);
4542 PF_ACPY(&key.addr[0], pd->dst, key.af);
4543 key.port[1] = uh->uh_sport;
4544 key.port[0] = uh->uh_dport;
4547 STATE_LOOKUP(kif, &key, direction, *state, pd);
4549 if (direction == (*state)->direction) {
4550 src = &(*state)->src;
4551 dst = &(*state)->dst;
4553 src = &(*state)->dst;
4554 dst = &(*state)->src;
4558 if (src->state < PFUDPS_SINGLE)
4559 src->state = PFUDPS_SINGLE;
4560 if (dst->state == PFUDPS_SINGLE)
4561 dst->state = PFUDPS_MULTIPLE;
4563 /* update expire time */
4564 (*state)->expire = time_uptime;
4565 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4566 (*state)->timeout = PFTM_UDP_MULTIPLE;
4568 (*state)->timeout = PFTM_UDP_SINGLE;
4570 /* translate source/destination address, if necessary */
4571 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4572 struct pf_state_key *nk = (*state)->key[pd->didx];
4574 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4575 nk->port[pd->sidx] != uh->uh_sport)
4576 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4577 &uh->uh_sum, &nk->addr[pd->sidx],
4578 nk->port[pd->sidx], 1, pd->af);
4580 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4581 nk->port[pd->didx] != uh->uh_dport)
4582 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4583 &uh->uh_sum, &nk->addr[pd->didx],
4584 nk->port[pd->didx], 1, pd->af);
4585 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4592 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4593 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4595 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4596 u_int16_t icmpid = 0, *icmpsum;
4597 u_int8_t icmptype, icmpcode;
4599 struct pf_state_key_cmp key;
4601 bzero(&key, sizeof(key));
4602 switch (pd->proto) {
4605 icmptype = pd->hdr.icmp->icmp_type;
4606 icmpcode = pd->hdr.icmp->icmp_code;
4607 icmpid = pd->hdr.icmp->icmp_id;
4608 icmpsum = &pd->hdr.icmp->icmp_cksum;
4610 if (icmptype == ICMP_UNREACH ||
4611 icmptype == ICMP_SOURCEQUENCH ||
4612 icmptype == ICMP_REDIRECT ||
4613 icmptype == ICMP_TIMXCEED ||
4614 icmptype == ICMP_PARAMPROB)
4619 case IPPROTO_ICMPV6:
4620 icmptype = pd->hdr.icmp6->icmp6_type;
4621 icmpcode = pd->hdr.icmp6->icmp6_code;
4622 icmpid = pd->hdr.icmp6->icmp6_id;
4623 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4625 if (icmptype == ICMP6_DST_UNREACH ||
4626 icmptype == ICMP6_PACKET_TOO_BIG ||
4627 icmptype == ICMP6_TIME_EXCEEDED ||
4628 icmptype == ICMP6_PARAM_PROB)
4637 * ICMP query/reply message not related to a TCP/UDP packet.
4638 * Search for an ICMP state.
4641 key.proto = pd->proto;
4642 key.port[0] = key.port[1] = icmpid;
4643 if (direction == PF_IN) { /* wire side, straight */
4644 PF_ACPY(&key.addr[0], pd->src, key.af);
4645 PF_ACPY(&key.addr[1], pd->dst, key.af);
4646 } else { /* stack side, reverse */
4647 PF_ACPY(&key.addr[1], pd->src, key.af);
4648 PF_ACPY(&key.addr[0], pd->dst, key.af);
4651 STATE_LOOKUP(kif, &key, direction, *state, pd);
4653 (*state)->expire = time_uptime;
4654 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4656 /* translate source/destination address, if necessary */
4657 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4658 struct pf_state_key *nk = (*state)->key[pd->didx];
4663 if (PF_ANEQ(pd->src,
4664 &nk->addr[pd->sidx], AF_INET))
4665 pf_change_a(&saddr->v4.s_addr,
4667 nk->addr[pd->sidx].v4.s_addr, 0);
4669 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4671 pf_change_a(&daddr->v4.s_addr,
4673 nk->addr[pd->didx].v4.s_addr, 0);
4676 pd->hdr.icmp->icmp_id) {
4677 pd->hdr.icmp->icmp_cksum =
4679 pd->hdr.icmp->icmp_cksum, icmpid,
4680 nk->port[pd->sidx], 0);
4681 pd->hdr.icmp->icmp_id =
4685 m_copyback(m, off, ICMP_MINLEN,
4686 (caddr_t )pd->hdr.icmp);
4691 if (PF_ANEQ(pd->src,
4692 &nk->addr[pd->sidx], AF_INET6))
4694 &pd->hdr.icmp6->icmp6_cksum,
4695 &nk->addr[pd->sidx], 0);
4697 if (PF_ANEQ(pd->dst,
4698 &nk->addr[pd->didx], AF_INET6))
4700 &pd->hdr.icmp6->icmp6_cksum,
4701 &nk->addr[pd->didx], 0);
4703 m_copyback(m, off, sizeof(struct icmp6_hdr),
4704 (caddr_t )pd->hdr.icmp6);
4713 * ICMP error message in response to a TCP/UDP packet.
4714 * Extract the inner TCP/UDP header and search for that state.
4717 struct pf_pdesc pd2;
4718 bzero(&pd2, sizeof pd2);
4723 struct ip6_hdr h2_6;
4730 /* Payload packet is from the opposite direction. */
4731 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4732 pd2.didx = (direction == PF_IN) ? 0 : 1;
4736 /* offset of h2 in mbuf chain */
4737 ipoff2 = off + ICMP_MINLEN;
4739 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4740 NULL, reason, pd2.af)) {
4741 DPFPRINTF(PF_DEBUG_MISC,
4742 ("pf: ICMP error message too short "
4747 * ICMP error messages don't refer to non-first
4750 if (h2.ip_off & htons(IP_OFFMASK)) {
4751 REASON_SET(reason, PFRES_FRAG);
4755 /* offset of protocol header that follows h2 */
4756 off2 = ipoff2 + (h2.ip_hl << 2);
4758 pd2.proto = h2.ip_p;
4759 pd2.src = (struct pf_addr *)&h2.ip_src;
4760 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4761 pd2.ip_sum = &h2.ip_sum;
4766 ipoff2 = off + sizeof(struct icmp6_hdr);
4768 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4769 NULL, reason, pd2.af)) {
4770 DPFPRINTF(PF_DEBUG_MISC,
4771 ("pf: ICMP error message too short "
4775 pd2.proto = h2_6.ip6_nxt;
4776 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4777 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4779 off2 = ipoff2 + sizeof(h2_6);
4781 switch (pd2.proto) {
4782 case IPPROTO_FRAGMENT:
4784 * ICMPv6 error messages for
4785 * non-first fragments
4787 REASON_SET(reason, PFRES_FRAG);
4790 case IPPROTO_HOPOPTS:
4791 case IPPROTO_ROUTING:
4792 case IPPROTO_DSTOPTS: {
4793 /* get next header and header length */
4794 struct ip6_ext opt6;
4796 if (!pf_pull_hdr(m, off2, &opt6,
4797 sizeof(opt6), NULL, reason,
4799 DPFPRINTF(PF_DEBUG_MISC,
4800 ("pf: ICMPv6 short opt\n"));
4803 if (pd2.proto == IPPROTO_AH)
4804 off2 += (opt6.ip6e_len + 2) * 4;
4806 off2 += (opt6.ip6e_len + 1) * 8;
4807 pd2.proto = opt6.ip6e_nxt;
4808 /* goto the next header */
4815 } while (!terminal);
4820 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4821 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4822 printf("pf: BAD ICMP %d:%d outer dst: ",
4823 icmptype, icmpcode);
4824 pf_print_host(pd->src, 0, pd->af);
4826 pf_print_host(pd->dst, 0, pd->af);
4827 printf(" inner src: ");
4828 pf_print_host(pd2.src, 0, pd2.af);
4830 pf_print_host(pd2.dst, 0, pd2.af);
4833 REASON_SET(reason, PFRES_BADSTATE);
4837 switch (pd2.proto) {
4841 struct pf_state_peer *src, *dst;
4846 * Only the first 8 bytes of the TCP header can be
4847 * expected. Don't access any TCP header fields after
4848 * th_seq, an ackskew test is not possible.
4850 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4852 DPFPRINTF(PF_DEBUG_MISC,
4853 ("pf: ICMP error message too short "
4859 key.proto = IPPROTO_TCP;
4860 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4861 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4862 key.port[pd2.sidx] = th.th_sport;
4863 key.port[pd2.didx] = th.th_dport;
4865 STATE_LOOKUP(kif, &key, direction, *state, pd);
4867 if (direction == (*state)->direction) {
4868 src = &(*state)->dst;
4869 dst = &(*state)->src;
4871 src = &(*state)->src;
4872 dst = &(*state)->dst;
4875 if (src->wscale && dst->wscale)
4876 dws = dst->wscale & PF_WSCALE_MASK;
4880 /* Demodulate sequence number */
4881 seq = ntohl(th.th_seq) - src->seqdiff;
4883 pf_change_a(&th.th_seq, icmpsum,
4888 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4889 (!SEQ_GEQ(src->seqhi, seq) ||
4890 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4891 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4892 printf("pf: BAD ICMP %d:%d ",
4893 icmptype, icmpcode);
4894 pf_print_host(pd->src, 0, pd->af);
4896 pf_print_host(pd->dst, 0, pd->af);
4898 pf_print_state(*state);
4899 printf(" seq=%u\n", seq);
4901 REASON_SET(reason, PFRES_BADSTATE);
4904 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4905 printf("pf: OK ICMP %d:%d ",
4906 icmptype, icmpcode);
4907 pf_print_host(pd->src, 0, pd->af);
4909 pf_print_host(pd->dst, 0, pd->af);
4911 pf_print_state(*state);
4912 printf(" seq=%u\n", seq);
4916 /* translate source/destination address, if necessary */
4917 if ((*state)->key[PF_SK_WIRE] !=
4918 (*state)->key[PF_SK_STACK]) {
4919 struct pf_state_key *nk =
4920 (*state)->key[pd->didx];
4922 if (PF_ANEQ(pd2.src,
4923 &nk->addr[pd2.sidx], pd2.af) ||
4924 nk->port[pd2.sidx] != th.th_sport)
4925 pf_change_icmp(pd2.src, &th.th_sport,
4926 daddr, &nk->addr[pd2.sidx],
4927 nk->port[pd2.sidx], NULL,
4928 pd2.ip_sum, icmpsum,
4929 pd->ip_sum, 0, pd2.af);
4931 if (PF_ANEQ(pd2.dst,
4932 &nk->addr[pd2.didx], pd2.af) ||
4933 nk->port[pd2.didx] != th.th_dport)
4934 pf_change_icmp(pd2.dst, &th.th_dport,
4935 saddr, &nk->addr[pd2.didx],
4936 nk->port[pd2.didx], NULL,
4937 pd2.ip_sum, icmpsum,
4938 pd->ip_sum, 0, pd2.af);
4946 m_copyback(m, off, ICMP_MINLEN,
4947 (caddr_t )pd->hdr.icmp);
4948 m_copyback(m, ipoff2, sizeof(h2),
4955 sizeof(struct icmp6_hdr),
4956 (caddr_t )pd->hdr.icmp6);
4957 m_copyback(m, ipoff2, sizeof(h2_6),
4962 m_copyback(m, off2, 8, (caddr_t)&th);
4971 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4972 NULL, reason, pd2.af)) {
4973 DPFPRINTF(PF_DEBUG_MISC,
4974 ("pf: ICMP error message too short "
4980 key.proto = IPPROTO_UDP;
4981 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4982 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4983 key.port[pd2.sidx] = uh.uh_sport;
4984 key.port[pd2.didx] = uh.uh_dport;
4986 STATE_LOOKUP(kif, &key, direction, *state, pd);
4988 /* translate source/destination address, if necessary */
4989 if ((*state)->key[PF_SK_WIRE] !=
4990 (*state)->key[PF_SK_STACK]) {
4991 struct pf_state_key *nk =
4992 (*state)->key[pd->didx];
4994 if (PF_ANEQ(pd2.src,
4995 &nk->addr[pd2.sidx], pd2.af) ||
4996 nk->port[pd2.sidx] != uh.uh_sport)
4997 pf_change_icmp(pd2.src, &uh.uh_sport,
4998 daddr, &nk->addr[pd2.sidx],
4999 nk->port[pd2.sidx], &uh.uh_sum,
5000 pd2.ip_sum, icmpsum,
5001 pd->ip_sum, 1, pd2.af);
5003 if (PF_ANEQ(pd2.dst,
5004 &nk->addr[pd2.didx], pd2.af) ||
5005 nk->port[pd2.didx] != uh.uh_dport)
5006 pf_change_icmp(pd2.dst, &uh.uh_dport,
5007 saddr, &nk->addr[pd2.didx],
5008 nk->port[pd2.didx], &uh.uh_sum,
5009 pd2.ip_sum, icmpsum,
5010 pd->ip_sum, 1, pd2.af);
5015 m_copyback(m, off, ICMP_MINLEN,
5016 (caddr_t )pd->hdr.icmp);
5017 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5023 sizeof(struct icmp6_hdr),
5024 (caddr_t )pd->hdr.icmp6);
5025 m_copyback(m, ipoff2, sizeof(h2_6),
5030 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5036 case IPPROTO_ICMP: {
5039 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5040 NULL, reason, pd2.af)) {
5041 DPFPRINTF(PF_DEBUG_MISC,
5042 ("pf: ICMP error message too short i"
5048 key.proto = IPPROTO_ICMP;
5049 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5050 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5051 key.port[0] = key.port[1] = iih.icmp_id;
5053 STATE_LOOKUP(kif, &key, direction, *state, pd);
5055 /* translate source/destination address, if necessary */
5056 if ((*state)->key[PF_SK_WIRE] !=
5057 (*state)->key[PF_SK_STACK]) {
5058 struct pf_state_key *nk =
5059 (*state)->key[pd->didx];
5061 if (PF_ANEQ(pd2.src,
5062 &nk->addr[pd2.sidx], pd2.af) ||
5063 nk->port[pd2.sidx] != iih.icmp_id)
5064 pf_change_icmp(pd2.src, &iih.icmp_id,
5065 daddr, &nk->addr[pd2.sidx],
5066 nk->port[pd2.sidx], NULL,
5067 pd2.ip_sum, icmpsum,
5068 pd->ip_sum, 0, AF_INET);
5070 if (PF_ANEQ(pd2.dst,
5071 &nk->addr[pd2.didx], pd2.af) ||
5072 nk->port[pd2.didx] != iih.icmp_id)
5073 pf_change_icmp(pd2.dst, &iih.icmp_id,
5074 saddr, &nk->addr[pd2.didx],
5075 nk->port[pd2.didx], NULL,
5076 pd2.ip_sum, icmpsum,
5077 pd->ip_sum, 0, AF_INET);
5079 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5080 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5081 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5088 case IPPROTO_ICMPV6: {
5089 struct icmp6_hdr iih;
5091 if (!pf_pull_hdr(m, off2, &iih,
5092 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5093 DPFPRINTF(PF_DEBUG_MISC,
5094 ("pf: ICMP error message too short "
5100 key.proto = IPPROTO_ICMPV6;
5101 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5102 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5103 key.port[0] = key.port[1] = iih.icmp6_id;
5105 STATE_LOOKUP(kif, &key, direction, *state, pd);
5107 /* translate source/destination address, if necessary */
5108 if ((*state)->key[PF_SK_WIRE] !=
5109 (*state)->key[PF_SK_STACK]) {
5110 struct pf_state_key *nk =
5111 (*state)->key[pd->didx];
5113 if (PF_ANEQ(pd2.src,
5114 &nk->addr[pd2.sidx], pd2.af) ||
5115 nk->port[pd2.sidx] != iih.icmp6_id)
5116 pf_change_icmp(pd2.src, &iih.icmp6_id,
5117 daddr, &nk->addr[pd2.sidx],
5118 nk->port[pd2.sidx], NULL,
5119 pd2.ip_sum, icmpsum,
5120 pd->ip_sum, 0, AF_INET6);
5122 if (PF_ANEQ(pd2.dst,
5123 &nk->addr[pd2.didx], pd2.af) ||
5124 nk->port[pd2.didx] != iih.icmp6_id)
5125 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5126 saddr, &nk->addr[pd2.didx],
5127 nk->port[pd2.didx], NULL,
5128 pd2.ip_sum, icmpsum,
5129 pd->ip_sum, 0, AF_INET6);
5131 m_copyback(m, off, sizeof(struct icmp6_hdr),
5132 (caddr_t)pd->hdr.icmp6);
5133 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5134 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5143 key.proto = pd2.proto;
5144 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5145 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5146 key.port[0] = key.port[1] = 0;
5148 STATE_LOOKUP(kif, &key, direction, *state, pd);
5150 /* translate source/destination address, if necessary */
5151 if ((*state)->key[PF_SK_WIRE] !=
5152 (*state)->key[PF_SK_STACK]) {
5153 struct pf_state_key *nk =
5154 (*state)->key[pd->didx];
5156 if (PF_ANEQ(pd2.src,
5157 &nk->addr[pd2.sidx], pd2.af))
5158 pf_change_icmp(pd2.src, NULL, daddr,
5159 &nk->addr[pd2.sidx], 0, NULL,
5160 pd2.ip_sum, icmpsum,
5161 pd->ip_sum, 0, pd2.af);
5163 if (PF_ANEQ(pd2.dst,
5164 &nk->addr[pd2.didx], pd2.af))
5165 pf_change_icmp(pd2.dst, NULL, saddr,
5166 &nk->addr[pd2.didx], 0, NULL,
5167 pd2.ip_sum, icmpsum,
5168 pd->ip_sum, 0, pd2.af);
5173 m_copyback(m, off, ICMP_MINLEN,
5174 (caddr_t)pd->hdr.icmp);
5175 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5181 sizeof(struct icmp6_hdr),
5182 (caddr_t )pd->hdr.icmp6);
5183 m_copyback(m, ipoff2, sizeof(h2_6),
5197 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5198 struct mbuf *m, struct pf_pdesc *pd)
5200 struct pf_state_peer *src, *dst;
5201 struct pf_state_key_cmp key;
5203 bzero(&key, sizeof(key));
5205 key.proto = pd->proto;
5206 if (direction == PF_IN) {
5207 PF_ACPY(&key.addr[0], pd->src, key.af);
5208 PF_ACPY(&key.addr[1], pd->dst, key.af);
5209 key.port[0] = key.port[1] = 0;
5211 PF_ACPY(&key.addr[1], pd->src, key.af);
5212 PF_ACPY(&key.addr[0], pd->dst, key.af);
5213 key.port[1] = key.port[0] = 0;
5216 STATE_LOOKUP(kif, &key, direction, *state, pd);
5218 if (direction == (*state)->direction) {
5219 src = &(*state)->src;
5220 dst = &(*state)->dst;
5222 src = &(*state)->dst;
5223 dst = &(*state)->src;
5227 if (src->state < PFOTHERS_SINGLE)
5228 src->state = PFOTHERS_SINGLE;
5229 if (dst->state == PFOTHERS_SINGLE)
5230 dst->state = PFOTHERS_MULTIPLE;
5232 /* update expire time */
5233 (*state)->expire = time_uptime;
5234 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5235 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5237 (*state)->timeout = PFTM_OTHER_SINGLE;
5239 /* translate source/destination address, if necessary */
5240 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5241 struct pf_state_key *nk = (*state)->key[pd->didx];
5243 KASSERT(nk, ("%s: nk is null", __func__));
5244 KASSERT(pd, ("%s: pd is null", __func__));
5245 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5246 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5250 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5251 pf_change_a(&pd->src->v4.s_addr,
5253 nk->addr[pd->sidx].v4.s_addr,
5257 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5258 pf_change_a(&pd->dst->v4.s_addr,
5260 nk->addr[pd->didx].v4.s_addr,
5267 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5268 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5270 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5271 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5279 * ipoff and off are measured from the start of the mbuf chain.
5280 * h must be at "ipoff" on the mbuf chain.
5283 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5284 u_short *actionp, u_short *reasonp, sa_family_t af)
5289 struct ip *h = mtod(m, struct ip *);
5290 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5294 ACTION_SET(actionp, PF_PASS);
5296 ACTION_SET(actionp, PF_DROP);
5297 REASON_SET(reasonp, PFRES_FRAG);
5301 if (m->m_pkthdr.len < off + len ||
5302 ntohs(h->ip_len) < off + len) {
5303 ACTION_SET(actionp, PF_DROP);
5304 REASON_SET(reasonp, PFRES_SHORT);
5312 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5314 if (m->m_pkthdr.len < off + len ||
5315 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5316 (unsigned)(off + len)) {
5317 ACTION_SET(actionp, PF_DROP);
5318 REASON_SET(reasonp, PFRES_SHORT);
5325 m_copydata(m, off, len, p);
5331 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5334 struct radix_node_head *rnh;
5335 struct sockaddr_in *dst;
5339 struct sockaddr_in6 *dst6;
5340 struct route_in6 ro;
5344 struct radix_node *rn;
5349 /* XXX: stick to table 0 for now */
5350 rnh = rt_tables_get_rnh(0, af);
5351 if (rnh != NULL && rn_mpath_capable(rnh))
5353 bzero(&ro, sizeof(ro));
5356 dst = satosin(&ro.ro_dst);
5357 dst->sin_family = AF_INET;
5358 dst->sin_len = sizeof(*dst);
5359 dst->sin_addr = addr->v4;
5364 * Skip check for addresses with embedded interface scope,
5365 * as they would always match anyway.
5367 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5369 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5370 dst6->sin6_family = AF_INET6;
5371 dst6->sin6_len = sizeof(*dst6);
5372 dst6->sin6_addr = addr->v6;
5379 /* Skip checks for ipsec interfaces */
5380 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5386 in6_rtalloc_ign(&ro, 0, rtableid);
5391 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5396 if (ro.ro_rt != NULL) {
5397 /* No interface given, this is a no-route check */
5401 if (kif->pfik_ifp == NULL) {
5406 /* Perform uRPF check if passed input interface */
5408 rn = (struct radix_node *)ro.ro_rt;
5410 rt = (struct rtentry *)rn;
5413 if (kif->pfik_ifp == ifp)
5415 rn = rn_mpath_next(rn);
5416 } while (check_mpath == 1 && rn != NULL && ret == 0);
5420 if (ro.ro_rt != NULL)
5427 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5431 struct nhop4_basic nh4;
5434 struct nhop6_basic nh6;
5438 struct radix_node_head *rnh;
5440 /* XXX: stick to table 0 for now */
5441 rnh = rt_tables_get_rnh(0, af);
5442 if (rnh != NULL && rn_mpath_capable(rnh))
5443 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5446 * Skip check for addresses with embedded interface scope,
5447 * as they would always match anyway.
5449 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5452 if (af != AF_INET && af != AF_INET6)
5455 /* Skip checks for ipsec interfaces */
5456 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5464 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5471 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5478 /* No interface given, this is a no-route check */
5482 if (kif->pfik_ifp == NULL)
5485 /* Perform uRPF check if passed input interface */
5486 if (kif->pfik_ifp == ifp)
5493 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5494 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5496 struct mbuf *m0, *m1;
5497 struct sockaddr_in dst;
5499 struct ifnet *ifp = NULL;
5500 struct pf_addr naddr;
5501 struct pf_src_node *sn = NULL;
5503 uint16_t ip_len, ip_off;
5505 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5506 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5509 if ((pd->pf_mtag == NULL &&
5510 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5511 pd->pf_mtag->routed++ > 3) {
5517 if (r->rt == PF_DUPTO) {
5518 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5524 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5532 ip = mtod(m0, struct ip *);
5534 bzero(&dst, sizeof(dst));
5535 dst.sin_family = AF_INET;
5536 dst.sin_len = sizeof(dst);
5537 dst.sin_addr = ip->ip_dst;
5539 bzero(&naddr, sizeof(naddr));
5541 if (TAILQ_EMPTY(&r->rpool.list)) {
5542 DPFPRINTF(PF_DEBUG_URGENT,
5543 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5547 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5549 if (!PF_AZERO(&naddr, AF_INET))
5550 dst.sin_addr.s_addr = naddr.v4.s_addr;
5551 ifp = r->rpool.cur->kif ?
5552 r->rpool.cur->kif->pfik_ifp : NULL;
5554 if (!PF_AZERO(&s->rt_addr, AF_INET))
5555 dst.sin_addr.s_addr =
5556 s->rt_addr.v4.s_addr;
5557 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5564 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5566 else if (m0 == NULL)
5568 if (m0->m_len < sizeof(struct ip)) {
5569 DPFPRINTF(PF_DEBUG_URGENT,
5570 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5573 ip = mtod(m0, struct ip *);
5576 if (ifp->if_flags & IFF_LOOPBACK)
5577 m0->m_flags |= M_SKIP_FIREWALL;
5579 ip_len = ntohs(ip->ip_len);
5580 ip_off = ntohs(ip->ip_off);
5582 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5583 m0->m_pkthdr.csum_flags |= CSUM_IP;
5584 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5585 in_delayed_cksum(m0);
5586 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5589 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5590 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5591 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5596 * If small enough for interface, or the interface will take
5597 * care of the fragmentation for us, we can just send directly.
5599 if (ip_len <= ifp->if_mtu ||
5600 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5602 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5603 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5604 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5606 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5607 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5611 /* Balk when DF bit is set or the interface didn't support TSO. */
5612 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5614 KMOD_IPSTAT_INC(ips_cantfrag);
5615 if (r->rt != PF_DUPTO) {
5616 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5623 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5627 for (; m0; m0 = m1) {
5629 m0->m_nextpkt = NULL;
5631 m_clrprotoflags(m0);
5632 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5638 KMOD_IPSTAT_INC(ips_fragmented);
5641 if (r->rt != PF_DUPTO)
5656 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5657 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5660 struct sockaddr_in6 dst;
5661 struct ip6_hdr *ip6;
5662 struct ifnet *ifp = NULL;
5663 struct pf_addr naddr;
5664 struct pf_src_node *sn = NULL;
5666 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5667 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5670 if ((pd->pf_mtag == NULL &&
5671 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5672 pd->pf_mtag->routed++ > 3) {
5678 if (r->rt == PF_DUPTO) {
5679 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5685 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5693 ip6 = mtod(m0, struct ip6_hdr *);
5695 bzero(&dst, sizeof(dst));
5696 dst.sin6_family = AF_INET6;
5697 dst.sin6_len = sizeof(dst);
5698 dst.sin6_addr = ip6->ip6_dst;
5700 bzero(&naddr, sizeof(naddr));
5702 if (TAILQ_EMPTY(&r->rpool.list)) {
5703 DPFPRINTF(PF_DEBUG_URGENT,
5704 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5708 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5710 if (!PF_AZERO(&naddr, AF_INET6))
5711 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5713 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5715 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5716 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5717 &s->rt_addr, AF_INET6);
5718 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5728 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5730 else if (m0 == NULL)
5732 if (m0->m_len < sizeof(struct ip6_hdr)) {
5733 DPFPRINTF(PF_DEBUG_URGENT,
5734 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5738 ip6 = mtod(m0, struct ip6_hdr *);
5741 if (ifp->if_flags & IFF_LOOPBACK)
5742 m0->m_flags |= M_SKIP_FIREWALL;
5744 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5745 ~ifp->if_hwassist) {
5746 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5747 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5748 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5752 * If the packet is too large for the outgoing interface,
5753 * send back an icmp6 error.
5755 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5756 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5757 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5758 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5760 in6_ifstat_inc(ifp, ifs6_in_toobig);
5761 if (r->rt != PF_DUPTO)
5762 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5768 if (r->rt != PF_DUPTO)
5782 * FreeBSD supports cksum offloads for the following drivers.
5783 * em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5785 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5786 * network driver performed cksum including pseudo header, need to verify
5789 * network driver performed cksum, needs to additional pseudo header
5790 * cksum computation with partial csum_data(i.e. lack of H/W support for
5791 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5793 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5794 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5796 * Also, set csum_data to 0xffff to force cksum validation.
5799 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5805 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5807 if (m->m_pkthdr.len < off + len)
5812 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5813 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5814 sum = m->m_pkthdr.csum_data;
5816 ip = mtod(m, struct ip *);
5817 sum = in_pseudo(ip->ip_src.s_addr,
5818 ip->ip_dst.s_addr, htonl((u_short)len +
5819 m->m_pkthdr.csum_data + IPPROTO_TCP));
5826 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5827 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5828 sum = m->m_pkthdr.csum_data;
5830 ip = mtod(m, struct ip *);
5831 sum = in_pseudo(ip->ip_src.s_addr,
5832 ip->ip_dst.s_addr, htonl((u_short)len +
5833 m->m_pkthdr.csum_data + IPPROTO_UDP));
5841 case IPPROTO_ICMPV6:
5851 if (p == IPPROTO_ICMP) {
5856 sum = in_cksum(m, len);
5860 if (m->m_len < sizeof(struct ip))
5862 sum = in4_cksum(m, p, off, len);
5867 if (m->m_len < sizeof(struct ip6_hdr))
5869 sum = in6_cksum(m, p, off, len);
5880 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5885 KMOD_UDPSTAT_INC(udps_badsum);
5891 KMOD_ICMPSTAT_INC(icps_checksum);
5896 case IPPROTO_ICMPV6:
5898 KMOD_ICMP6STAT_INC(icp6s_checksum);
5905 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5906 m->m_pkthdr.csum_flags |=
5907 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5908 m->m_pkthdr.csum_data = 0xffff;
5917 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5919 struct pfi_kif *kif;
5920 u_short action, reason = 0, log = 0;
5921 struct mbuf *m = *m0;
5922 struct ip *h = NULL;
5923 struct m_tag *ipfwtag;
5924 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5925 struct pf_state *s = NULL;
5926 struct pf_ruleset *ruleset = NULL;
5928 int off, dirndx, pqid = 0;
5930 PF_RULES_RLOCK_TRACKER;
5934 if (!V_pf_status.running)
5937 memset(&pd, 0, sizeof(pd));
5939 kif = (struct pfi_kif *)ifp->if_pf_kif;
5942 DPFPRINTF(PF_DEBUG_URGENT,
5943 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5946 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5949 if (m->m_flags & M_SKIP_FIREWALL)
5952 pd.pf_mtag = pf_find_mtag(m);
5956 if (ip_divert_ptr != NULL &&
5957 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5958 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5959 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5960 if (pd.pf_mtag == NULL &&
5961 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5965 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5966 m_tag_delete(m, ipfwtag);
5968 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5969 m->m_flags |= M_FASTFWD_OURS;
5970 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5972 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5973 /* We do IP header normalization and packet reassembly here */
5977 m = *m0; /* pf_normalize messes with m0 */
5978 h = mtod(m, struct ip *);
5980 off = h->ip_hl << 2;
5981 if (off < (int)sizeof(struct ip)) {
5983 REASON_SET(&reason, PFRES_SHORT);
5988 pd.src = (struct pf_addr *)&h->ip_src;
5989 pd.dst = (struct pf_addr *)&h->ip_dst;
5990 pd.sport = pd.dport = NULL;
5991 pd.ip_sum = &h->ip_sum;
5992 pd.proto_sum = NULL;
5995 pd.sidx = (dir == PF_IN) ? 0 : 1;
5996 pd.didx = (dir == PF_IN) ? 1 : 0;
5998 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5999 pd.tot_len = ntohs(h->ip_len);
6001 /* handle fragments that didn't get reassembled by normalization */
6002 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
6003 action = pf_test_fragment(&r, dir, kif, m, h,
6014 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6015 &action, &reason, AF_INET)) {
6016 log = action != PF_PASS;
6019 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6020 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6022 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6023 if (action == PF_DROP)
6025 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6027 if (action == PF_PASS) {
6028 if (V_pfsync_update_state_ptr != NULL)
6029 V_pfsync_update_state_ptr(s);
6033 } else if (s == NULL)
6034 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6043 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6044 &action, &reason, AF_INET)) {
6045 log = action != PF_PASS;
6048 if (uh.uh_dport == 0 ||
6049 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6050 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6052 REASON_SET(&reason, PFRES_SHORT);
6055 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6056 if (action == PF_PASS) {
6057 if (V_pfsync_update_state_ptr != NULL)
6058 V_pfsync_update_state_ptr(s);
6062 } else if (s == NULL)
6063 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6068 case IPPROTO_ICMP: {
6072 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6073 &action, &reason, AF_INET)) {
6074 log = action != PF_PASS;
6077 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6079 if (action == PF_PASS) {
6080 if (V_pfsync_update_state_ptr != NULL)
6081 V_pfsync_update_state_ptr(s);
6085 } else if (s == NULL)
6086 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6092 case IPPROTO_ICMPV6: {
6094 DPFPRINTF(PF_DEBUG_MISC,
6095 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6101 action = pf_test_state_other(&s, dir, kif, m, &pd);
6102 if (action == PF_PASS) {
6103 if (V_pfsync_update_state_ptr != NULL)
6104 V_pfsync_update_state_ptr(s);
6108 } else if (s == NULL)
6109 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6116 if (action == PF_PASS && h->ip_hl > 5 &&
6117 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6119 REASON_SET(&reason, PFRES_IPOPTIONS);
6121 DPFPRINTF(PF_DEBUG_MISC,
6122 ("pf: dropping packet with ip options\n"));
6125 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6127 REASON_SET(&reason, PFRES_MEMORY);
6129 if (r->rtableid >= 0)
6130 M_SETFIB(m, r->rtableid);
6132 if (r->scrub_flags & PFSTATE_SETPRIO) {
6133 if (pd.tos & IPTOS_LOWDELAY)
6135 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6137 REASON_SET(&reason, PFRES_MEMORY);
6139 DPFPRINTF(PF_DEBUG_MISC,
6140 ("pf: failed to allocate 802.1q mtag\n"));
6145 if (action == PF_PASS && r->qid) {
6146 if (pd.pf_mtag == NULL &&
6147 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6149 REASON_SET(&reason, PFRES_MEMORY);
6152 pd.pf_mtag->qid_hash = pf_state_hash(s);
6153 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6154 pd.pf_mtag->qid = r->pqid;
6156 pd.pf_mtag->qid = r->qid;
6157 /* Add hints for ecn. */
6158 pd.pf_mtag->hdr = h;
6165 * connections redirected to loopback should not match sockets
6166 * bound specifically to loopback due to security implications,
6167 * see tcp_input() and in_pcblookup_listen().
6169 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6170 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6171 (s->nat_rule.ptr->action == PF_RDR ||
6172 s->nat_rule.ptr->action == PF_BINAT) &&
6173 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6174 m->m_flags |= M_SKIP_FIREWALL;
6176 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6177 !PACKET_LOOPED(&pd)) {
6179 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6180 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6181 if (ipfwtag != NULL) {
6182 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6183 ntohs(r->divert.port);
6184 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6189 m_tag_prepend(m, ipfwtag);
6190 if (m->m_flags & M_FASTFWD_OURS) {
6191 if (pd.pf_mtag == NULL &&
6192 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6194 REASON_SET(&reason, PFRES_MEMORY);
6196 DPFPRINTF(PF_DEBUG_MISC,
6197 ("pf: failed to allocate tag\n"));
6199 pd.pf_mtag->flags |=
6200 PF_FASTFWD_OURS_PRESENT;
6201 m->m_flags &= ~M_FASTFWD_OURS;
6204 ip_divert_ptr(*m0, dir == PF_IN);
6209 /* XXX: ipfw has the same behaviour! */
6211 REASON_SET(&reason, PFRES_MEMORY);
6213 DPFPRINTF(PF_DEBUG_MISC,
6214 ("pf: failed to allocate divert tag\n"));
6221 if (s != NULL && s->nat_rule.ptr != NULL &&
6222 s->nat_rule.ptr->log & PF_LOG_ALL)
6223 lr = s->nat_rule.ptr;
6226 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6230 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6231 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6233 if (action == PF_PASS || r->action == PF_DROP) {
6234 dirndx = (dir == PF_OUT);
6235 r->packets[dirndx]++;
6236 r->bytes[dirndx] += pd.tot_len;
6238 a->packets[dirndx]++;
6239 a->bytes[dirndx] += pd.tot_len;
6242 if (s->nat_rule.ptr != NULL) {
6243 s->nat_rule.ptr->packets[dirndx]++;
6244 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6246 if (s->src_node != NULL) {
6247 s->src_node->packets[dirndx]++;
6248 s->src_node->bytes[dirndx] += pd.tot_len;
6250 if (s->nat_src_node != NULL) {
6251 s->nat_src_node->packets[dirndx]++;
6252 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6254 dirndx = (dir == s->direction) ? 0 : 1;
6255 s->packets[dirndx]++;
6256 s->bytes[dirndx] += pd.tot_len;
6259 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6260 if (nr != NULL && r == &V_pf_default_rule)
6262 if (tr->src.addr.type == PF_ADDR_TABLE)
6263 pfr_update_stats(tr->src.addr.p.tbl,
6264 (s == NULL) ? pd.src :
6265 &s->key[(s->direction == PF_IN)]->
6266 addr[(s->direction == PF_OUT)],
6267 pd.af, pd.tot_len, dir == PF_OUT,
6268 r->action == PF_PASS, tr->src.neg);
6269 if (tr->dst.addr.type == PF_ADDR_TABLE)
6270 pfr_update_stats(tr->dst.addr.p.tbl,
6271 (s == NULL) ? pd.dst :
6272 &s->key[(s->direction == PF_IN)]->
6273 addr[(s->direction == PF_IN)],
6274 pd.af, pd.tot_len, dir == PF_OUT,
6275 r->action == PF_PASS, tr->dst.neg);
6279 case PF_SYNPROXY_DROP:
6290 /* pf_route() returns unlocked. */
6292 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6306 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6308 struct pfi_kif *kif;
6309 u_short action, reason = 0, log = 0;
6310 struct mbuf *m = *m0, *n = NULL;
6312 struct ip6_hdr *h = NULL;
6313 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6314 struct pf_state *s = NULL;
6315 struct pf_ruleset *ruleset = NULL;
6317 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6319 PF_RULES_RLOCK_TRACKER;
6322 if (!V_pf_status.running)
6325 memset(&pd, 0, sizeof(pd));
6326 pd.pf_mtag = pf_find_mtag(m);
6328 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6331 kif = (struct pfi_kif *)ifp->if_pf_kif;
6333 DPFPRINTF(PF_DEBUG_URGENT,
6334 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6337 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6340 if (m->m_flags & M_SKIP_FIREWALL)
6345 /* We do IP header normalization and packet reassembly here */
6346 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6350 m = *m0; /* pf_normalize messes with m0 */
6351 h = mtod(m, struct ip6_hdr *);
6355 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6356 * will do something bad, so drop the packet for now.
6358 if (htons(h->ip6_plen) == 0) {
6360 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6365 pd.src = (struct pf_addr *)&h->ip6_src;
6366 pd.dst = (struct pf_addr *)&h->ip6_dst;
6367 pd.sport = pd.dport = NULL;
6369 pd.proto_sum = NULL;
6371 pd.sidx = (dir == PF_IN) ? 0 : 1;
6372 pd.didx = (dir == PF_IN) ? 1 : 0;
6375 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6377 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6378 pd.proto = h->ip6_nxt;
6381 case IPPROTO_FRAGMENT:
6382 action = pf_test_fragment(&r, dir, kif, m, h,
6384 if (action == PF_DROP)
6385 REASON_SET(&reason, PFRES_FRAG);
6387 case IPPROTO_ROUTING: {
6388 struct ip6_rthdr rthdr;
6391 DPFPRINTF(PF_DEBUG_MISC,
6392 ("pf: IPv6 more than one rthdr\n"));
6394 REASON_SET(&reason, PFRES_IPOPTIONS);
6398 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6400 DPFPRINTF(PF_DEBUG_MISC,
6401 ("pf: IPv6 short rthdr\n"));
6403 REASON_SET(&reason, PFRES_SHORT);
6407 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6408 DPFPRINTF(PF_DEBUG_MISC,
6409 ("pf: IPv6 rthdr0\n"));
6411 REASON_SET(&reason, PFRES_IPOPTIONS);
6418 case IPPROTO_HOPOPTS:
6419 case IPPROTO_DSTOPTS: {
6420 /* get next header and header length */
6421 struct ip6_ext opt6;
6423 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6424 NULL, &reason, pd.af)) {
6425 DPFPRINTF(PF_DEBUG_MISC,
6426 ("pf: IPv6 short opt\n"));
6431 if (pd.proto == IPPROTO_AH)
6432 off += (opt6.ip6e_len + 2) * 4;
6434 off += (opt6.ip6e_len + 1) * 8;
6435 pd.proto = opt6.ip6e_nxt;
6436 /* goto the next header */
6443 } while (!terminal);
6445 /* if there's no routing header, use unmodified mbuf for checksumming */
6455 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6456 &action, &reason, AF_INET6)) {
6457 log = action != PF_PASS;
6460 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6461 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6462 if (action == PF_DROP)
6464 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6466 if (action == PF_PASS) {
6467 if (V_pfsync_update_state_ptr != NULL)
6468 V_pfsync_update_state_ptr(s);
6472 } else if (s == NULL)
6473 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6482 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6483 &action, &reason, AF_INET6)) {
6484 log = action != PF_PASS;
6487 if (uh.uh_dport == 0 ||
6488 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6489 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6491 REASON_SET(&reason, PFRES_SHORT);
6494 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6495 if (action == PF_PASS) {
6496 if (V_pfsync_update_state_ptr != NULL)
6497 V_pfsync_update_state_ptr(s);
6501 } else if (s == NULL)
6502 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6507 case IPPROTO_ICMP: {
6509 DPFPRINTF(PF_DEBUG_MISC,
6510 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6514 case IPPROTO_ICMPV6: {
6515 struct icmp6_hdr ih;
6518 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6519 &action, &reason, AF_INET6)) {
6520 log = action != PF_PASS;
6523 action = pf_test_state_icmp(&s, dir, kif,
6524 m, off, h, &pd, &reason);
6525 if (action == PF_PASS) {
6526 if (V_pfsync_update_state_ptr != NULL)
6527 V_pfsync_update_state_ptr(s);
6531 } else if (s == NULL)
6532 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6538 action = pf_test_state_other(&s, dir, kif, m, &pd);
6539 if (action == PF_PASS) {
6540 if (V_pfsync_update_state_ptr != NULL)
6541 V_pfsync_update_state_ptr(s);
6545 } else if (s == NULL)
6546 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6558 /* handle dangerous IPv6 extension headers. */
6559 if (action == PF_PASS && rh_cnt &&
6560 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6562 REASON_SET(&reason, PFRES_IPOPTIONS);
6564 DPFPRINTF(PF_DEBUG_MISC,
6565 ("pf: dropping packet with dangerous v6 headers\n"));
6568 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6570 REASON_SET(&reason, PFRES_MEMORY);
6572 if (r->rtableid >= 0)
6573 M_SETFIB(m, r->rtableid);
6575 if (r->scrub_flags & PFSTATE_SETPRIO) {
6576 if (pd.tos & IPTOS_LOWDELAY)
6578 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6580 REASON_SET(&reason, PFRES_MEMORY);
6582 DPFPRINTF(PF_DEBUG_MISC,
6583 ("pf: failed to allocate 802.1q mtag\n"));
6588 if (action == PF_PASS && r->qid) {
6589 if (pd.pf_mtag == NULL &&
6590 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6592 REASON_SET(&reason, PFRES_MEMORY);
6595 pd.pf_mtag->qid_hash = pf_state_hash(s);
6596 if (pd.tos & IPTOS_LOWDELAY)
6597 pd.pf_mtag->qid = r->pqid;
6599 pd.pf_mtag->qid = r->qid;
6600 /* Add hints for ecn. */
6601 pd.pf_mtag->hdr = h;
6606 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6607 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6608 (s->nat_rule.ptr->action == PF_RDR ||
6609 s->nat_rule.ptr->action == PF_BINAT) &&
6610 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6611 m->m_flags |= M_SKIP_FIREWALL;
6613 /* XXX: Anybody working on it?! */
6615 printf("pf: divert(9) is not supported for IPv6\n");
6620 if (s != NULL && s->nat_rule.ptr != NULL &&
6621 s->nat_rule.ptr->log & PF_LOG_ALL)
6622 lr = s->nat_rule.ptr;
6625 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6629 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6630 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6632 if (action == PF_PASS || r->action == PF_DROP) {
6633 dirndx = (dir == PF_OUT);
6634 r->packets[dirndx]++;
6635 r->bytes[dirndx] += pd.tot_len;
6637 a->packets[dirndx]++;
6638 a->bytes[dirndx] += pd.tot_len;
6641 if (s->nat_rule.ptr != NULL) {
6642 s->nat_rule.ptr->packets[dirndx]++;
6643 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6645 if (s->src_node != NULL) {
6646 s->src_node->packets[dirndx]++;
6647 s->src_node->bytes[dirndx] += pd.tot_len;
6649 if (s->nat_src_node != NULL) {
6650 s->nat_src_node->packets[dirndx]++;
6651 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6653 dirndx = (dir == s->direction) ? 0 : 1;
6654 s->packets[dirndx]++;
6655 s->bytes[dirndx] += pd.tot_len;
6658 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6659 if (nr != NULL && r == &V_pf_default_rule)
6661 if (tr->src.addr.type == PF_ADDR_TABLE)
6662 pfr_update_stats(tr->src.addr.p.tbl,
6663 (s == NULL) ? pd.src :
6664 &s->key[(s->direction == PF_IN)]->addr[0],
6665 pd.af, pd.tot_len, dir == PF_OUT,
6666 r->action == PF_PASS, tr->src.neg);
6667 if (tr->dst.addr.type == PF_ADDR_TABLE)
6668 pfr_update_stats(tr->dst.addr.p.tbl,
6669 (s == NULL) ? pd.dst :
6670 &s->key[(s->direction == PF_IN)]->addr[1],
6671 pd.af, pd.tot_len, dir == PF_OUT,
6672 r->action == PF_PASS, tr->dst.neg);
6676 case PF_SYNPROXY_DROP:
6687 /* pf_route6() returns unlocked. */
6689 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6698 /* If reassembled packet passed, create new fragments. */
6699 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6700 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6701 action = pf_refragment6(ifp, m0, mtag);