2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
35 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 #include "opt_inet6.h"
46 #include <sys/param.h>
48 #include <sys/endian.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/limits.h>
56 #include <sys/random.h>
57 #include <sys/refcount.h>
58 #include <sys/socket.h>
59 #include <sys/sysctl.h>
60 #include <sys/taskqueue.h>
61 #include <sys/ucred.h>
64 #include <net/if_types.h>
65 #include <net/route.h>
66 #include <net/radix_mpath.h>
69 #include <net/pfvar.h>
70 #include <net/if_pflog.h>
71 #include <net/if_pfsync.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/in_var.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/icmp_var.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/tcp.h>
81 #include <netinet/tcp_fsm.h>
82 #include <netinet/tcp_seq.h>
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #include <netinet/udp.h>
86 #include <netinet/udp_var.h>
88 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
91 #include <netinet/ip6.h>
92 #include <netinet/icmp6.h>
93 #include <netinet6/nd6.h>
94 #include <netinet6/ip6_var.h>
95 #include <netinet6/in6_pcb.h>
98 #include <machine/in_cksum.h>
99 #include <security/mac/mac_framework.h>
101 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
108 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
109 VNET_DEFINE(struct pf_palist, pf_pabuf);
110 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
111 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
112 VNET_DEFINE(struct pf_kstatus, pf_status);
114 VNET_DEFINE(u_int32_t, ticket_altqs_active);
115 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
116 VNET_DEFINE(int, altqs_inactive_open);
117 VNET_DEFINE(u_int32_t, ticket_pabuf);
119 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
120 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
121 VNET_DEFINE(u_char, pf_tcp_secret[16]);
122 #define V_pf_tcp_secret VNET(pf_tcp_secret)
123 VNET_DEFINE(int, pf_tcp_secret_init);
124 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
125 VNET_DEFINE(int, pf_tcp_iss_off);
126 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
129 * Queue for pf_intr() sends.
131 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
132 struct pf_send_entry {
133 STAILQ_ENTRY(pf_send_entry) pfse_next;
150 #define pfse_icmp_type u.icmpopts.type
151 #define pfse_icmp_code u.icmpopts.code
152 #define pfse_icmp_mtu u.icmpopts.mtu
155 STAILQ_HEAD(pf_send_head, pf_send_entry);
156 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157 #define V_pf_sendqueue VNET(pf_sendqueue)
159 static struct mtx pf_sendqueue_mtx;
160 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
161 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
164 * Queue for pf_overload_task() tasks.
166 struct pf_overload_entry {
167 SLIST_ENTRY(pf_overload_entry) next;
171 struct pf_rule *rule;
174 SLIST_HEAD(pf_overload_head, pf_overload_entry);
175 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
176 #define V_pf_overloadqueue VNET(pf_overloadqueue)
177 static VNET_DEFINE(struct task, pf_overloadtask);
178 #define V_pf_overloadtask VNET(pf_overloadtask)
180 static struct mtx pf_overloadqueue_mtx;
181 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
182 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
184 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
185 struct mtx pf_unlnkdrules_mtx;
187 static VNET_DEFINE(uma_zone_t, pf_sources_z);
188 #define V_pf_sources_z VNET(pf_sources_z)
189 uma_zone_t pf_mtag_z;
190 VNET_DEFINE(uma_zone_t, pf_state_z);
191 VNET_DEFINE(uma_zone_t, pf_state_key_z);
193 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
194 #define PFID_CPUBITS 8
195 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
196 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
197 #define PFID_MAXID (~PFID_CPUMASK)
198 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
200 static void pf_src_tree_remove_state(struct pf_state *);
201 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
203 static void pf_add_threshold(struct pf_threshold *);
204 static int pf_check_threshold(struct pf_threshold *);
206 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
207 u_int16_t *, u_int16_t *, struct pf_addr *,
208 u_int16_t, u_int8_t, sa_family_t);
209 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
210 struct tcphdr *, struct pf_state_peer *);
211 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
212 struct pf_addr *, struct pf_addr *, u_int16_t,
213 u_int16_t *, u_int16_t *, u_int16_t *,
214 u_int16_t *, u_int8_t, sa_family_t);
215 static void pf_send_tcp(struct mbuf *,
216 const struct pf_rule *, sa_family_t,
217 const struct pf_addr *, const struct pf_addr *,
218 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
219 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
220 u_int16_t, struct ifnet *);
221 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
222 sa_family_t, struct pf_rule *);
223 static void pf_detach_state(struct pf_state *);
224 static int pf_state_key_attach(struct pf_state_key *,
225 struct pf_state_key *, struct pf_state *);
226 static void pf_state_key_detach(struct pf_state *, int);
227 static int pf_state_key_ctor(void *, int, void *, int);
228 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
229 static int pf_test_rule(struct pf_rule **, struct pf_state **,
230 int, struct pfi_kif *, struct mbuf *, int,
231 struct pf_pdesc *, struct pf_rule **,
232 struct pf_ruleset **, struct inpcb *);
233 static int pf_create_state(struct pf_rule *, struct pf_rule *,
234 struct pf_rule *, struct pf_pdesc *,
235 struct pf_src_node *, struct pf_state_key *,
236 struct pf_state_key *, struct mbuf *, int,
237 u_int16_t, u_int16_t, int *, struct pfi_kif *,
238 struct pf_state **, int, u_int16_t, u_int16_t,
240 static int pf_test_fragment(struct pf_rule **, int,
241 struct pfi_kif *, struct mbuf *, void *,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **);
244 static int pf_tcp_track_full(struct pf_state_peer *,
245 struct pf_state_peer *, struct pf_state **,
246 struct pfi_kif *, struct mbuf *, int,
247 struct pf_pdesc *, u_short *, int *);
248 static int pf_tcp_track_sloppy(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pf_pdesc *, u_short *);
251 static int pf_test_state_tcp(struct pf_state **, int,
252 struct pfi_kif *, struct mbuf *, int,
253 void *, struct pf_pdesc *, u_short *);
254 static int pf_test_state_udp(struct pf_state **, int,
255 struct pfi_kif *, struct mbuf *, int,
256 void *, struct pf_pdesc *);
257 static int pf_test_state_icmp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260 static int pf_test_state_other(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
262 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
264 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
266 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
268 static int pf_check_proto_cksum(struct mbuf *, int, int,
269 u_int8_t, sa_family_t);
270 static void pf_print_state_parts(struct pf_state *,
271 struct pf_state_key *, struct pf_state_key *);
272 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
273 struct pf_addr_wrap *);
274 static struct pf_state *pf_find_state(struct pfi_kif *,
275 struct pf_state_key_cmp *, u_int);
276 static int pf_src_connlimit(struct pf_state **);
277 static void pf_overload_task(void *v, int pending);
278 static int pf_insert_src_node(struct pf_src_node **,
279 struct pf_rule *, struct pf_addr *, sa_family_t);
280 static u_int pf_purge_expired_states(u_int, int);
281 static void pf_purge_unlinked_rules(void);
282 static int pf_mtag_uminit(void *, int, int);
283 static void pf_mtag_free(struct m_tag *);
285 static void pf_route(struct mbuf **, struct pf_rule *, int,
286 struct ifnet *, struct pf_state *,
287 struct pf_pdesc *, struct inpcb *);
290 static void pf_change_a6(struct pf_addr *, u_int16_t *,
291 struct pf_addr *, u_int8_t);
292 static void pf_route6(struct mbuf **, struct pf_rule *, int,
293 struct ifnet *, struct pf_state *,
294 struct pf_pdesc *, struct inpcb *);
297 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
299 VNET_DECLARE(int, pf_end_threads);
301 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
303 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
304 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
306 #define STATE_LOOKUP(i, k, d, s, pd) \
308 (s) = pf_find_state((i), (k), (d)); \
311 if (PACKET_LOOPED(pd)) \
313 if ((d) == PF_OUT && \
314 (((s)->rule.ptr->rt == PF_ROUTETO && \
315 (s)->rule.ptr->direction == PF_OUT) || \
316 ((s)->rule.ptr->rt == PF_REPLYTO && \
317 (s)->rule.ptr->direction == PF_IN)) && \
318 (s)->rt_kif != NULL && \
319 (s)->rt_kif != (i)) \
323 #define BOUND_IFACE(r, k) \
324 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
326 #define STATE_INC_COUNTERS(s) \
328 counter_u64_add(s->rule.ptr->states_cur, 1); \
329 counter_u64_add(s->rule.ptr->states_tot, 1); \
330 if (s->anchor.ptr != NULL) { \
331 counter_u64_add(s->anchor.ptr->states_cur, 1); \
332 counter_u64_add(s->anchor.ptr->states_tot, 1); \
334 if (s->nat_rule.ptr != NULL) { \
335 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
336 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
340 #define STATE_DEC_COUNTERS(s) \
342 if (s->nat_rule.ptr != NULL) \
343 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
344 if (s->anchor.ptr != NULL) \
345 counter_u64_add(s->anchor.ptr->states_cur, -1); \
346 counter_u64_add(s->rule.ptr->states_cur, -1); \
349 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
350 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
351 VNET_DEFINE(struct pf_idhash *, pf_idhash);
352 VNET_DEFINE(struct pf_srchash *, pf_srchash);
354 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
357 u_long pf_srchashmask;
358 static u_long pf_hashsize;
359 static u_long pf_srchashsize;
361 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
362 &pf_hashsize, 0, "Size of pf(4) states hashtable");
363 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
364 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
366 VNET_DEFINE(void *, pf_swi_cookie);
368 VNET_DEFINE(uint32_t, pf_hashseed);
369 #define V_pf_hashseed VNET(pf_hashseed)
372 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
378 if (a->addr32[0] > b->addr32[0])
380 if (a->addr32[0] < b->addr32[0])
386 if (a->addr32[3] > b->addr32[3])
388 if (a->addr32[3] < b->addr32[3])
390 if (a->addr32[2] > b->addr32[2])
392 if (a->addr32[2] < b->addr32[2])
394 if (a->addr32[1] > b->addr32[1])
396 if (a->addr32[1] < b->addr32[1])
398 if (a->addr32[0] > b->addr32[0])
400 if (a->addr32[0] < b->addr32[0])
405 panic("%s: unknown address family %u", __func__, af);
410 static __inline uint32_t
411 pf_hashkey(struct pf_state_key *sk)
415 h = murmur3_aligned_32((uint32_t *)sk,
416 sizeof(struct pf_state_key_cmp),
419 return (h & pf_hashmask);
422 static __inline uint32_t
423 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
429 h = murmur3_aligned_32((uint32_t *)&addr->v4,
430 sizeof(addr->v4), V_pf_hashseed);
433 h = murmur3_aligned_32((uint32_t *)&addr->v6,
434 sizeof(addr->v6), V_pf_hashseed);
437 panic("%s: unknown address family %u", __func__, af);
440 return (h & pf_srchashmask);
445 pf_state_hash(struct pf_state *s)
447 u_int32_t hv = (intptr_t)s / sizeof(*s);
449 hv ^= crc32(&s->src, sizeof(s->src));
450 hv ^= crc32(&s->dst, sizeof(s->dst));
459 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
464 dst->addr32[0] = src->addr32[0];
468 dst->addr32[0] = src->addr32[0];
469 dst->addr32[1] = src->addr32[1];
470 dst->addr32[2] = src->addr32[2];
471 dst->addr32[3] = src->addr32[3];
478 pf_init_threshold(struct pf_threshold *threshold,
479 u_int32_t limit, u_int32_t seconds)
481 threshold->limit = limit * PF_THRESHOLD_MULT;
482 threshold->seconds = seconds;
483 threshold->count = 0;
484 threshold->last = time_uptime;
488 pf_add_threshold(struct pf_threshold *threshold)
490 u_int32_t t = time_uptime, diff = t - threshold->last;
492 if (diff >= threshold->seconds)
493 threshold->count = 0;
495 threshold->count -= threshold->count * diff /
497 threshold->count += PF_THRESHOLD_MULT;
502 pf_check_threshold(struct pf_threshold *threshold)
504 return (threshold->count > threshold->limit);
508 pf_src_connlimit(struct pf_state **state)
510 struct pf_overload_entry *pfoe;
513 PF_STATE_LOCK_ASSERT(*state);
515 (*state)->src_node->conn++;
516 (*state)->src.tcp_est = 1;
517 pf_add_threshold(&(*state)->src_node->conn_rate);
519 if ((*state)->rule.ptr->max_src_conn &&
520 (*state)->rule.ptr->max_src_conn <
521 (*state)->src_node->conn) {
522 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
526 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
527 pf_check_threshold(&(*state)->src_node->conn_rate)) {
528 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
535 /* Kill this state. */
536 (*state)->timeout = PFTM_PURGE;
537 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
539 if ((*state)->rule.ptr->overload_tbl == NULL)
542 /* Schedule overloading and flushing task. */
543 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
545 return (1); /* too bad :( */
547 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
548 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
549 pfoe->rule = (*state)->rule.ptr;
550 pfoe->dir = (*state)->direction;
552 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
553 PF_OVERLOADQ_UNLOCK();
554 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
560 pf_overload_task(void *v, int pending)
562 struct pf_overload_head queue;
564 struct pf_overload_entry *pfoe, *pfoe1;
567 CURVNET_SET((struct vnet *)v);
570 queue = V_pf_overloadqueue;
571 SLIST_INIT(&V_pf_overloadqueue);
572 PF_OVERLOADQ_UNLOCK();
574 bzero(&p, sizeof(p));
575 SLIST_FOREACH(pfoe, &queue, next) {
576 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
577 if (V_pf_status.debug >= PF_DEBUG_MISC) {
578 printf("%s: blocking address ", __func__);
579 pf_print_host(&pfoe->addr, 0, pfoe->af);
583 p.pfra_af = pfoe->af;
588 p.pfra_ip4addr = pfoe->addr.v4;
594 p.pfra_ip6addr = pfoe->addr.v6;
600 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
605 * Remove those entries, that don't need flushing.
607 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
608 if (pfoe->rule->flush == 0) {
609 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
610 free(pfoe, M_PFTEMP);
613 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
615 /* If nothing to flush, return. */
616 if (SLIST_EMPTY(&queue)) {
621 for (int i = 0; i <= pf_hashmask; i++) {
622 struct pf_idhash *ih = &V_pf_idhash[i];
623 struct pf_state_key *sk;
627 LIST_FOREACH(s, &ih->states, entry) {
628 sk = s->key[PF_SK_WIRE];
629 SLIST_FOREACH(pfoe, &queue, next)
630 if (sk->af == pfoe->af &&
631 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
632 pfoe->rule == s->rule.ptr) &&
633 ((pfoe->dir == PF_OUT &&
634 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
635 (pfoe->dir == PF_IN &&
636 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
637 s->timeout = PFTM_PURGE;
638 s->src.state = s->dst.state = TCPS_CLOSED;
642 PF_HASHROW_UNLOCK(ih);
644 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
645 free(pfoe, M_PFTEMP);
646 if (V_pf_status.debug >= PF_DEBUG_MISC)
647 printf("%s: %u states killed", __func__, killed);
653 * Can return locked on failure, so that we can consistently
654 * allocate and insert a new one.
657 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
660 struct pf_srchash *sh;
661 struct pf_src_node *n;
663 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
665 sh = &V_pf_srchash[pf_hashsrc(src, af)];
667 LIST_FOREACH(n, &sh->nodes, entry)
668 if (n->rule.ptr == rule && n->af == af &&
669 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
670 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
674 PF_HASHROW_UNLOCK(sh);
675 } else if (returnlocked == 0)
676 PF_HASHROW_UNLOCK(sh);
682 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
683 struct pf_addr *src, sa_family_t af)
686 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
687 rule->rpool.opts & PF_POOL_STICKYADDR),
688 ("%s for non-tracking rule %p", __func__, rule));
691 *sn = pf_find_src_node(src, rule, af, 1);
694 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
696 PF_HASHROW_ASSERT(sh);
698 if (!rule->max_src_nodes ||
699 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
700 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
702 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
705 PF_HASHROW_UNLOCK(sh);
709 pf_init_threshold(&(*sn)->conn_rate,
710 rule->max_src_conn_rate.limit,
711 rule->max_src_conn_rate.seconds);
714 (*sn)->rule.ptr = rule;
715 PF_ACPY(&(*sn)->addr, src, af);
716 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
717 (*sn)->creation = time_uptime;
718 (*sn)->ruletype = rule->action;
720 if ((*sn)->rule.ptr != NULL)
721 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
722 PF_HASHROW_UNLOCK(sh);
723 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
725 if (rule->max_src_states &&
726 (*sn)->states >= rule->max_src_states) {
727 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
736 pf_unlink_src_node(struct pf_src_node *src)
739 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
740 LIST_REMOVE(src, entry);
742 counter_u64_add(src->rule.ptr->src_nodes, -1);
746 pf_free_src_nodes(struct pf_src_node_list *head)
748 struct pf_src_node *sn, *tmp;
751 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
752 uma_zfree(V_pf_sources_z, sn);
756 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
765 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
766 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
770 /* Per-vnet data storage structures initialization. */
774 struct pf_keyhash *kh;
775 struct pf_idhash *ih;
776 struct pf_srchash *sh;
779 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &pf_hashsize);
780 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
781 pf_hashsize = PF_HASHSIZ;
782 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &pf_srchashsize);
783 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
784 pf_srchashsize = PF_SRCHASHSIZ;
786 V_pf_hashseed = arc4random();
788 /* States and state keys storage. */
789 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
790 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
791 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
792 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
793 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
795 V_pf_state_key_z = uma_zcreate("pf state keys",
796 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
799 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
800 M_PFHASH, M_NOWAIT | M_ZERO);
801 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
802 M_PFHASH, M_NOWAIT | M_ZERO);
803 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
804 printf("pf: Unable to allocate memory for "
805 "state_hashsize %lu.\n", pf_hashsize);
807 free(V_pf_keyhash, M_PFHASH);
808 free(V_pf_idhash, M_PFHASH);
810 pf_hashsize = PF_HASHSIZ;
811 V_pf_keyhash = mallocarray(pf_hashsize,
812 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
813 V_pf_idhash = mallocarray(pf_hashsize,
814 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
817 pf_hashmask = pf_hashsize - 1;
818 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
820 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
821 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
825 V_pf_sources_z = uma_zcreate("pf source nodes",
826 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
828 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
829 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
830 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
832 V_pf_srchash = mallocarray(pf_srchashsize,
833 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
834 if (V_pf_srchash == NULL) {
835 printf("pf: Unable to allocate memory for "
836 "source_hashsize %lu.\n", pf_srchashsize);
838 pf_srchashsize = PF_SRCHASHSIZ;
839 V_pf_srchash = mallocarray(pf_srchashsize,
840 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
843 pf_srchashmask = pf_srchashsize - 1;
844 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
845 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
848 TAILQ_INIT(&V_pf_altqs[0]);
849 TAILQ_INIT(&V_pf_altqs[1]);
850 TAILQ_INIT(&V_pf_pabuf);
851 V_pf_altqs_active = &V_pf_altqs[0];
852 V_pf_altqs_inactive = &V_pf_altqs[1];
855 /* Send & overload+flush queues. */
856 STAILQ_INIT(&V_pf_sendqueue);
857 SLIST_INIT(&V_pf_overloadqueue);
858 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
859 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
860 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
863 /* Unlinked, but may be referenced rules. */
864 TAILQ_INIT(&V_pf_unlinked_rules);
865 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
872 uma_zdestroy(pf_mtag_z);
878 struct pf_keyhash *kh;
879 struct pf_idhash *ih;
880 struct pf_srchash *sh;
881 struct pf_send_entry *pfse, *next;
884 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
886 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
888 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
890 mtx_destroy(&kh->lock);
891 mtx_destroy(&ih->lock);
893 free(V_pf_keyhash, M_PFHASH);
894 free(V_pf_idhash, M_PFHASH);
896 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
897 KASSERT(LIST_EMPTY(&sh->nodes),
898 ("%s: source node hash not empty", __func__));
899 mtx_destroy(&sh->lock);
901 free(V_pf_srchash, M_PFHASH);
903 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
904 m_freem(pfse->pfse_m);
905 free(pfse, M_PFTEMP);
908 mtx_destroy(&pf_sendqueue_mtx);
909 mtx_destroy(&pf_overloadqueue_mtx);
910 mtx_destroy(&pf_unlnkdrules_mtx);
912 uma_zdestroy(V_pf_sources_z);
913 uma_zdestroy(V_pf_state_z);
914 uma_zdestroy(V_pf_state_key_z);
918 pf_mtag_uminit(void *mem, int size, int how)
922 t = (struct m_tag *)mem;
923 t->m_tag_cookie = MTAG_ABI_COMPAT;
924 t->m_tag_id = PACKET_TAG_PF;
925 t->m_tag_len = sizeof(struct pf_mtag);
926 t->m_tag_free = pf_mtag_free;
932 pf_mtag_free(struct m_tag *t)
935 uma_zfree(pf_mtag_z, t);
939 pf_get_mtag(struct mbuf *m)
943 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
944 return ((struct pf_mtag *)(mtag + 1));
946 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
949 bzero(mtag + 1, sizeof(struct pf_mtag));
950 m_tag_prepend(m, mtag);
952 return ((struct pf_mtag *)(mtag + 1));
956 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
959 struct pf_keyhash *khs, *khw, *kh;
960 struct pf_state_key *sk, *cur;
961 struct pf_state *si, *olds = NULL;
964 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
965 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
966 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
969 * We need to lock hash slots of both keys. To avoid deadlock
970 * we always lock the slot with lower address first. Unlock order
973 * We also need to lock ID hash slot before dropping key
974 * locks. On success we return with ID hash slot locked.
978 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
979 PF_HASHROW_LOCK(khs);
981 khs = &V_pf_keyhash[pf_hashkey(sks)];
982 khw = &V_pf_keyhash[pf_hashkey(skw)];
984 PF_HASHROW_LOCK(khs);
985 } else if (khs < khw) {
986 PF_HASHROW_LOCK(khs);
987 PF_HASHROW_LOCK(khw);
989 PF_HASHROW_LOCK(khw);
990 PF_HASHROW_LOCK(khs);
994 #define KEYS_UNLOCK() do { \
996 PF_HASHROW_UNLOCK(khs); \
997 PF_HASHROW_UNLOCK(khw); \
999 PF_HASHROW_UNLOCK(khs); \
1003 * First run: start with wire key.
1010 LIST_FOREACH(cur, &kh->keys, entry)
1011 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1015 /* Key exists. Check for same kif, if none, add to key. */
1016 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1017 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1019 PF_HASHROW_LOCK(ih);
1020 if (si->kif == s->kif &&
1021 si->direction == s->direction) {
1022 if (sk->proto == IPPROTO_TCP &&
1023 si->src.state >= TCPS_FIN_WAIT_2 &&
1024 si->dst.state >= TCPS_FIN_WAIT_2) {
1026 * New state matches an old >FIN_WAIT_2
1027 * state. We can't drop key hash locks,
1028 * thus we can't unlink it properly.
1030 * As a workaround we drop it into
1031 * TCPS_CLOSED state, schedule purge
1032 * ASAP and push it into the very end
1033 * of the slot TAILQ, so that it won't
1034 * conflict with our new state.
1036 si->src.state = si->dst.state =
1038 si->timeout = PFTM_PURGE;
1041 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1042 printf("pf: %s key attach "
1044 (idx == PF_SK_WIRE) ?
1047 pf_print_state_parts(s,
1048 (idx == PF_SK_WIRE) ?
1050 (idx == PF_SK_STACK) ?
1052 printf(", existing: ");
1053 pf_print_state_parts(si,
1054 (idx == PF_SK_WIRE) ?
1056 (idx == PF_SK_STACK) ?
1060 PF_HASHROW_UNLOCK(ih);
1062 uma_zfree(V_pf_state_key_z, sk);
1063 if (idx == PF_SK_STACK)
1065 return (EEXIST); /* collision! */
1068 PF_HASHROW_UNLOCK(ih);
1070 uma_zfree(V_pf_state_key_z, sk);
1073 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1078 /* List is sorted, if-bound states before floating. */
1079 if (s->kif == V_pfi_all)
1080 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1082 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1085 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1086 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1092 * Attach done. See how should we (or should not?)
1093 * attach a second key.
1096 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1100 } else if (sks != NULL) {
1102 * Continue attaching with stack key.
1114 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1115 ("%s failure", __func__));
1122 pf_detach_state(struct pf_state *s)
1124 struct pf_state_key *sks = s->key[PF_SK_STACK];
1125 struct pf_keyhash *kh;
1128 kh = &V_pf_keyhash[pf_hashkey(sks)];
1129 PF_HASHROW_LOCK(kh);
1130 if (s->key[PF_SK_STACK] != NULL)
1131 pf_state_key_detach(s, PF_SK_STACK);
1133 * If both point to same key, then we are done.
1135 if (sks == s->key[PF_SK_WIRE]) {
1136 pf_state_key_detach(s, PF_SK_WIRE);
1137 PF_HASHROW_UNLOCK(kh);
1140 PF_HASHROW_UNLOCK(kh);
1143 if (s->key[PF_SK_WIRE] != NULL) {
1144 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1145 PF_HASHROW_LOCK(kh);
1146 if (s->key[PF_SK_WIRE] != NULL)
1147 pf_state_key_detach(s, PF_SK_WIRE);
1148 PF_HASHROW_UNLOCK(kh);
1153 pf_state_key_detach(struct pf_state *s, int idx)
1155 struct pf_state_key *sk = s->key[idx];
1157 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1159 PF_HASHROW_ASSERT(kh);
1161 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1164 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1165 LIST_REMOVE(sk, entry);
1166 uma_zfree(V_pf_state_key_z, sk);
1171 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1173 struct pf_state_key *sk = mem;
1175 bzero(sk, sizeof(struct pf_state_key_cmp));
1176 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1177 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1182 struct pf_state_key *
1183 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1184 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1186 struct pf_state_key *sk;
1188 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1192 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1193 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1194 sk->port[pd->sidx] = sport;
1195 sk->port[pd->didx] = dport;
1196 sk->proto = pd->proto;
1202 struct pf_state_key *
1203 pf_state_key_clone(struct pf_state_key *orig)
1205 struct pf_state_key *sk;
1207 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1211 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1217 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1218 struct pf_state_key *sks, struct pf_state *s)
1220 struct pf_idhash *ih;
1221 struct pf_state *cur;
1224 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1225 ("%s: sks not pristine", __func__));
1226 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1227 ("%s: skw not pristine", __func__));
1228 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1232 if (s->id == 0 && s->creatorid == 0) {
1233 /* XXX: should be atomic, but probability of collision low */
1234 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1235 V_pf_stateid[curcpu] = 1;
1236 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1237 s->id = htobe64(s->id);
1238 s->creatorid = V_pf_status.hostid;
1241 /* Returns with ID locked on success. */
1242 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1245 ih = &V_pf_idhash[PF_IDHASH(s)];
1246 PF_HASHROW_ASSERT(ih);
1247 LIST_FOREACH(cur, &ih->states, entry)
1248 if (cur->id == s->id && cur->creatorid == s->creatorid)
1252 PF_HASHROW_UNLOCK(ih);
1253 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1254 printf("pf: state ID collision: "
1255 "id: %016llx creatorid: %08x\n",
1256 (unsigned long long)be64toh(s->id),
1257 ntohl(s->creatorid));
1262 LIST_INSERT_HEAD(&ih->states, s, entry);
1263 /* One for keys, one for ID hash. */
1264 refcount_init(&s->refs, 2);
1266 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1267 if (pfsync_insert_state_ptr != NULL)
1268 pfsync_insert_state_ptr(s);
1270 /* Returns locked. */
1275 * Find state by ID: returns with locked row on success.
1278 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1280 struct pf_idhash *ih;
1283 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1285 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1287 PF_HASHROW_LOCK(ih);
1288 LIST_FOREACH(s, &ih->states, entry)
1289 if (s->id == id && s->creatorid == creatorid)
1293 PF_HASHROW_UNLOCK(ih);
1299 * Find state by key.
1300 * Returns with ID hash slot locked on success.
1302 static struct pf_state *
1303 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1305 struct pf_keyhash *kh;
1306 struct pf_state_key *sk;
1310 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1312 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1314 PF_HASHROW_LOCK(kh);
1315 LIST_FOREACH(sk, &kh->keys, entry)
1316 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1319 PF_HASHROW_UNLOCK(kh);
1323 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1325 /* List is sorted, if-bound states before floating ones. */
1326 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1327 if (s->kif == V_pfi_all || s->kif == kif) {
1329 PF_HASHROW_UNLOCK(kh);
1330 if (s->timeout >= PFTM_MAX) {
1332 * State is either being processed by
1333 * pf_unlink_state() in an other thread, or
1334 * is scheduled for immediate expiry.
1341 PF_HASHROW_UNLOCK(kh);
1347 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1349 struct pf_keyhash *kh;
1350 struct pf_state_key *sk;
1351 struct pf_state *s, *ret = NULL;
1354 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1356 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1358 PF_HASHROW_LOCK(kh);
1359 LIST_FOREACH(sk, &kh->keys, entry)
1360 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1363 PF_HASHROW_UNLOCK(kh);
1378 panic("%s: dir %u", __func__, dir);
1381 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1383 PF_HASHROW_UNLOCK(kh);
1397 PF_HASHROW_UNLOCK(kh);
1402 /* END state table stuff */
1405 pf_send(struct pf_send_entry *pfse)
1409 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1411 swi_sched(V_pf_swi_cookie, 0);
1417 struct pf_send_head queue;
1418 struct pf_send_entry *pfse, *next;
1420 CURVNET_SET((struct vnet *)v);
1423 queue = V_pf_sendqueue;
1424 STAILQ_INIT(&V_pf_sendqueue);
1427 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1428 switch (pfse->pfse_type) {
1431 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1434 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1435 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1440 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1444 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1445 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1449 panic("%s: unknown type", __func__);
1451 free(pfse, M_PFTEMP);
1457 pf_purge_thread(void *v)
1461 CURVNET_SET((struct vnet *)v);
1465 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1467 if (V_pf_end_threads) {
1469 * To cleanse up all kifs and rules we need
1470 * two runs: first one clears reference flags,
1471 * then pf_purge_expired_states() doesn't
1472 * raise them, and then second run frees.
1475 pf_purge_unlinked_rules();
1479 * Now purge everything.
1481 pf_purge_expired_states(0, pf_hashmask);
1482 pf_purge_expired_fragments();
1483 pf_purge_expired_src_nodes();
1486 * Now all kifs & rules should be unreferenced,
1487 * thus should be successfully freed.
1489 pf_purge_unlinked_rules();
1493 * Announce success and exit.
1498 wakeup(pf_purge_thread);
1503 /* Process 1/interval fraction of the state table every run. */
1504 idx = pf_purge_expired_states(idx, pf_hashmask /
1505 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1507 /* Purge other expired types every PFTM_INTERVAL seconds. */
1510 * Order is important:
1511 * - states and src nodes reference rules
1512 * - states and rules reference kifs
1514 pf_purge_expired_fragments();
1515 pf_purge_expired_src_nodes();
1516 pf_purge_unlinked_rules();
1525 pf_state_expires(const struct pf_state *state)
1532 /* handle all PFTM_* > PFTM_MAX here */
1533 if (state->timeout == PFTM_PURGE)
1534 return (time_uptime);
1535 KASSERT(state->timeout != PFTM_UNLINKED,
1536 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1537 KASSERT((state->timeout < PFTM_MAX),
1538 ("pf_state_expires: timeout > PFTM_MAX"));
1539 timeout = state->rule.ptr->timeout[state->timeout];
1541 timeout = V_pf_default_rule.timeout[state->timeout];
1542 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1544 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1545 states = counter_u64_fetch(state->rule.ptr->states_cur);
1547 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1548 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1549 states = V_pf_status.states;
1551 if (end && states > start && start < end) {
1553 return (state->expire + timeout * (end - states) /
1556 return (time_uptime);
1558 return (state->expire + timeout);
1562 pf_purge_expired_src_nodes()
1564 struct pf_src_node_list freelist;
1565 struct pf_srchash *sh;
1566 struct pf_src_node *cur, *next;
1569 LIST_INIT(&freelist);
1570 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1571 PF_HASHROW_LOCK(sh);
1572 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1573 if (cur->states == 0 && cur->expire <= time_uptime) {
1574 pf_unlink_src_node(cur);
1575 LIST_INSERT_HEAD(&freelist, cur, entry);
1576 } else if (cur->rule.ptr != NULL)
1577 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1578 PF_HASHROW_UNLOCK(sh);
1581 pf_free_src_nodes(&freelist);
1583 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1587 pf_src_tree_remove_state(struct pf_state *s)
1589 struct pf_src_node *sn;
1590 struct pf_srchash *sh;
1593 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1594 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1595 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1597 if (s->src_node != NULL) {
1599 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1600 PF_HASHROW_LOCK(sh);
1603 if (--sn->states == 0)
1604 sn->expire = time_uptime + timeout;
1605 PF_HASHROW_UNLOCK(sh);
1607 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1608 sn = s->nat_src_node;
1609 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1610 PF_HASHROW_LOCK(sh);
1611 if (--sn->states == 0)
1612 sn->expire = time_uptime + timeout;
1613 PF_HASHROW_UNLOCK(sh);
1615 s->src_node = s->nat_src_node = NULL;
1619 * Unlink and potentilly free a state. Function may be
1620 * called with ID hash row locked, but always returns
1621 * unlocked, since it needs to go through key hash locking.
1624 pf_unlink_state(struct pf_state *s, u_int flags)
1626 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1628 if ((flags & PF_ENTER_LOCKED) == 0)
1629 PF_HASHROW_LOCK(ih);
1631 PF_HASHROW_ASSERT(ih);
1633 if (s->timeout == PFTM_UNLINKED) {
1635 * State is being processed
1636 * by pf_unlink_state() in
1639 PF_HASHROW_UNLOCK(ih);
1640 return (0); /* XXXGL: undefined actually */
1643 if (s->src.state == PF_TCPS_PROXY_DST) {
1644 /* XXX wire key the right one? */
1645 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1646 &s->key[PF_SK_WIRE]->addr[1],
1647 &s->key[PF_SK_WIRE]->addr[0],
1648 s->key[PF_SK_WIRE]->port[1],
1649 s->key[PF_SK_WIRE]->port[0],
1650 s->src.seqhi, s->src.seqlo + 1,
1651 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1654 LIST_REMOVE(s, entry);
1655 pf_src_tree_remove_state(s);
1657 if (pfsync_delete_state_ptr != NULL)
1658 pfsync_delete_state_ptr(s);
1660 STATE_DEC_COUNTERS(s);
1662 s->timeout = PFTM_UNLINKED;
1664 PF_HASHROW_UNLOCK(ih);
1667 refcount_release(&s->refs);
1669 return (pf_release_state(s));
1673 pf_free_state(struct pf_state *cur)
1676 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1677 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1680 pf_normalize_tcp_cleanup(cur);
1681 uma_zfree(V_pf_state_z, cur);
1682 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1686 * Called only from pf_purge_thread(), thus serialized.
1689 pf_purge_expired_states(u_int i, int maxcheck)
1691 struct pf_idhash *ih;
1694 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1697 * Go through hash and unlink states that expire now.
1699 while (maxcheck > 0) {
1701 ih = &V_pf_idhash[i];
1703 PF_HASHROW_LOCK(ih);
1704 LIST_FOREACH(s, &ih->states, entry) {
1705 if (pf_state_expires(s) <= time_uptime) {
1706 V_pf_status.states -=
1707 pf_unlink_state(s, PF_ENTER_LOCKED);
1710 s->rule.ptr->rule_flag |= PFRULE_REFS;
1711 if (s->nat_rule.ptr != NULL)
1712 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1713 if (s->anchor.ptr != NULL)
1714 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1715 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1717 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1719 PF_HASHROW_UNLOCK(ih);
1721 /* Return when we hit end of hash. */
1722 if (++i > pf_hashmask) {
1723 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1730 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1736 pf_purge_unlinked_rules()
1738 struct pf_rulequeue tmpq;
1739 struct pf_rule *r, *r1;
1742 * If we have overloading task pending, then we'd
1743 * better skip purging this time. There is a tiny
1744 * probability that overloading task references
1745 * an already unlinked rule.
1747 PF_OVERLOADQ_LOCK();
1748 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1749 PF_OVERLOADQ_UNLOCK();
1752 PF_OVERLOADQ_UNLOCK();
1755 * Do naive mark-and-sweep garbage collecting of old rules.
1756 * Reference flag is raised by pf_purge_expired_states()
1757 * and pf_purge_expired_src_nodes().
1759 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1760 * use a temporary queue.
1763 PF_UNLNKDRULES_LOCK();
1764 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1765 if (!(r->rule_flag & PFRULE_REFS)) {
1766 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1767 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1769 r->rule_flag &= ~PFRULE_REFS;
1771 PF_UNLNKDRULES_UNLOCK();
1773 if (!TAILQ_EMPTY(&tmpq)) {
1775 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1776 TAILQ_REMOVE(&tmpq, r, entries);
1784 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1789 u_int32_t a = ntohl(addr->addr32[0]);
1790 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1802 u_int8_t i, curstart, curend, maxstart, maxend;
1803 curstart = curend = maxstart = maxend = 255;
1804 for (i = 0; i < 8; i++) {
1805 if (!addr->addr16[i]) {
1806 if (curstart == 255)
1810 if ((curend - curstart) >
1811 (maxend - maxstart)) {
1812 maxstart = curstart;
1815 curstart = curend = 255;
1818 if ((curend - curstart) >
1819 (maxend - maxstart)) {
1820 maxstart = curstart;
1823 for (i = 0; i < 8; i++) {
1824 if (i >= maxstart && i <= maxend) {
1830 b = ntohs(addr->addr16[i]);
1847 pf_print_state(struct pf_state *s)
1849 pf_print_state_parts(s, NULL, NULL);
1853 pf_print_state_parts(struct pf_state *s,
1854 struct pf_state_key *skwp, struct pf_state_key *sksp)
1856 struct pf_state_key *skw, *sks;
1857 u_int8_t proto, dir;
1859 /* Do our best to fill these, but they're skipped if NULL */
1860 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1861 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1862 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1863 dir = s ? s->direction : 0;
1881 case IPPROTO_ICMPV6:
1885 printf("%u", skw->proto);
1898 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1900 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1905 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1907 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1912 if (proto == IPPROTO_TCP) {
1913 printf(" [lo=%u high=%u win=%u modulator=%u",
1914 s->src.seqlo, s->src.seqhi,
1915 s->src.max_win, s->src.seqdiff);
1916 if (s->src.wscale && s->dst.wscale)
1917 printf(" wscale=%u",
1918 s->src.wscale & PF_WSCALE_MASK);
1920 printf(" [lo=%u high=%u win=%u modulator=%u",
1921 s->dst.seqlo, s->dst.seqhi,
1922 s->dst.max_win, s->dst.seqdiff);
1923 if (s->src.wscale && s->dst.wscale)
1924 printf(" wscale=%u",
1925 s->dst.wscale & PF_WSCALE_MASK);
1928 printf(" %u:%u", s->src.state, s->dst.state);
1933 pf_print_flags(u_int8_t f)
1955 #define PF_SET_SKIP_STEPS(i) \
1957 while (head[i] != cur) { \
1958 head[i]->skip[i].ptr = cur; \
1959 head[i] = TAILQ_NEXT(head[i], entries); \
1964 pf_calc_skip_steps(struct pf_rulequeue *rules)
1966 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1969 cur = TAILQ_FIRST(rules);
1971 for (i = 0; i < PF_SKIP_COUNT; ++i)
1973 while (cur != NULL) {
1975 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1976 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1977 if (cur->direction != prev->direction)
1978 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1979 if (cur->af != prev->af)
1980 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1981 if (cur->proto != prev->proto)
1982 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1983 if (cur->src.neg != prev->src.neg ||
1984 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1985 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1986 if (cur->src.port[0] != prev->src.port[0] ||
1987 cur->src.port[1] != prev->src.port[1] ||
1988 cur->src.port_op != prev->src.port_op)
1989 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1990 if (cur->dst.neg != prev->dst.neg ||
1991 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1992 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1993 if (cur->dst.port[0] != prev->dst.port[0] ||
1994 cur->dst.port[1] != prev->dst.port[1] ||
1995 cur->dst.port_op != prev->dst.port_op)
1996 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1999 cur = TAILQ_NEXT(cur, entries);
2001 for (i = 0; i < PF_SKIP_COUNT; ++i)
2002 PF_SET_SKIP_STEPS(i);
2006 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2008 if (aw1->type != aw2->type)
2010 switch (aw1->type) {
2011 case PF_ADDR_ADDRMASK:
2013 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2015 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2018 case PF_ADDR_DYNIFTL:
2019 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2020 case PF_ADDR_NOROUTE:
2021 case PF_ADDR_URPFFAILED:
2024 return (aw1->p.tbl != aw2->p.tbl);
2026 printf("invalid address type: %d\n", aw1->type);
2032 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2033 * header isn't always a full checksum. In some cases (i.e. output) it's a
2034 * pseudo-header checksum, which is a partial checksum over src/dst IP
2035 * addresses, protocol number and length.
2037 * That means we have the following cases:
2038 * * Input or forwarding: we don't have TSO, the checksum fields are full
2039 * checksums, we need to update the checksum whenever we change anything.
2040 * * Output (i.e. the checksum is a pseudo-header checksum):
2041 * x The field being updated is src/dst address or affects the length of
2042 * the packet. We need to update the pseudo-header checksum (note that this
2043 * checksum is not ones' complement).
2044 * x Some other field is being modified (e.g. src/dst port numbers): We
2045 * don't have to update anything.
2048 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2054 l = cksum + old - new;
2055 l = (l >> 16) + (l & 65535);
2063 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2064 u_int16_t new, u_int8_t udp)
2066 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2069 return (pf_cksum_fixup(cksum, old, new, udp));
2073 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2074 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2080 PF_ACPY(&ao, a, af);
2083 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2091 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2092 ao.addr16[0], an->addr16[0], 0),
2093 ao.addr16[1], an->addr16[1], 0);
2096 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2097 ao.addr16[0], an->addr16[0], u),
2098 ao.addr16[1], an->addr16[1], u);
2100 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2105 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2106 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2107 pf_cksum_fixup(pf_cksum_fixup(*pc,
2108 ao.addr16[0], an->addr16[0], u),
2109 ao.addr16[1], an->addr16[1], u),
2110 ao.addr16[2], an->addr16[2], u),
2111 ao.addr16[3], an->addr16[3], u),
2112 ao.addr16[4], an->addr16[4], u),
2113 ao.addr16[5], an->addr16[5], u),
2114 ao.addr16[6], an->addr16[6], u),
2115 ao.addr16[7], an->addr16[7], u);
2117 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2122 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2123 CSUM_DELAY_DATA_IPV6)) {
2130 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2132 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2136 memcpy(&ao, a, sizeof(ao));
2137 memcpy(a, &an, sizeof(u_int32_t));
2138 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2139 ao % 65536, an % 65536, u);
2143 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2147 memcpy(&ao, a, sizeof(ao));
2148 memcpy(a, &an, sizeof(u_int32_t));
2150 *c = pf_proto_cksum_fixup(m,
2151 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2152 ao % 65536, an % 65536, udp);
2157 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2161 PF_ACPY(&ao, a, AF_INET6);
2162 PF_ACPY(a, an, AF_INET6);
2164 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2165 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2166 pf_cksum_fixup(pf_cksum_fixup(*c,
2167 ao.addr16[0], an->addr16[0], u),
2168 ao.addr16[1], an->addr16[1], u),
2169 ao.addr16[2], an->addr16[2], u),
2170 ao.addr16[3], an->addr16[3], u),
2171 ao.addr16[4], an->addr16[4], u),
2172 ao.addr16[5], an->addr16[5], u),
2173 ao.addr16[6], an->addr16[6], u),
2174 ao.addr16[7], an->addr16[7], u);
2179 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2180 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2181 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2183 struct pf_addr oia, ooa;
2185 PF_ACPY(&oia, ia, af);
2187 PF_ACPY(&ooa, oa, af);
2189 /* Change inner protocol port, fix inner protocol checksum. */
2191 u_int16_t oip = *ip;
2198 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2199 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2201 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2203 /* Change inner ip address, fix inner ip and icmp checksums. */
2204 PF_ACPY(ia, na, af);
2208 u_int32_t oh2c = *h2c;
2210 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2211 oia.addr16[0], ia->addr16[0], 0),
2212 oia.addr16[1], ia->addr16[1], 0);
2213 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2214 oia.addr16[0], ia->addr16[0], 0),
2215 oia.addr16[1], ia->addr16[1], 0);
2216 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2222 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2223 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2224 pf_cksum_fixup(pf_cksum_fixup(*ic,
2225 oia.addr16[0], ia->addr16[0], u),
2226 oia.addr16[1], ia->addr16[1], u),
2227 oia.addr16[2], ia->addr16[2], u),
2228 oia.addr16[3], ia->addr16[3], u),
2229 oia.addr16[4], ia->addr16[4], u),
2230 oia.addr16[5], ia->addr16[5], u),
2231 oia.addr16[6], ia->addr16[6], u),
2232 oia.addr16[7], ia->addr16[7], u);
2236 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2238 PF_ACPY(oa, na, af);
2242 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2243 ooa.addr16[0], oa->addr16[0], 0),
2244 ooa.addr16[1], oa->addr16[1], 0);
2249 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2250 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2251 pf_cksum_fixup(pf_cksum_fixup(*ic,
2252 ooa.addr16[0], oa->addr16[0], u),
2253 ooa.addr16[1], oa->addr16[1], u),
2254 ooa.addr16[2], oa->addr16[2], u),
2255 ooa.addr16[3], oa->addr16[3], u),
2256 ooa.addr16[4], oa->addr16[4], u),
2257 ooa.addr16[5], oa->addr16[5], u),
2258 ooa.addr16[6], oa->addr16[6], u),
2259 ooa.addr16[7], oa->addr16[7], u);
2268 * Need to modulate the sequence numbers in the TCP SACK option
2269 * (credits to Krzysztof Pfaff for report and patch)
2272 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2273 struct tcphdr *th, struct pf_state_peer *dst)
2275 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2276 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2277 int copyback = 0, i, olen;
2278 struct sackblk sack;
2280 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2281 if (hlen < TCPOLEN_SACKLEN ||
2282 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2285 while (hlen >= TCPOLEN_SACKLEN) {
2288 case TCPOPT_EOL: /* FALLTHROUGH */
2296 if (olen >= TCPOLEN_SACKLEN) {
2297 for (i = 2; i + TCPOLEN_SACK <= olen;
2298 i += TCPOLEN_SACK) {
2299 memcpy(&sack, &opt[i], sizeof(sack));
2300 pf_change_proto_a(m, &sack.start, &th->th_sum,
2301 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2302 pf_change_proto_a(m, &sack.end, &th->th_sum,
2303 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2304 memcpy(&opt[i], &sack, sizeof(sack));
2318 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2323 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2324 const struct pf_addr *saddr, const struct pf_addr *daddr,
2325 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2326 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2327 u_int16_t rtag, struct ifnet *ifp)
2329 struct pf_send_entry *pfse;
2333 struct ip *h = NULL;
2336 struct ip6_hdr *h6 = NULL;
2340 struct pf_mtag *pf_mtag;
2345 /* maximum segment size tcp option */
2346 tlen = sizeof(struct tcphdr);
2353 len = sizeof(struct ip) + tlen;
2358 len = sizeof(struct ip6_hdr) + tlen;
2362 panic("%s: unsupported af %d", __func__, af);
2365 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2366 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2369 m = m_gethdr(M_NOWAIT, MT_DATA);
2371 free(pfse, M_PFTEMP);
2375 mac_netinet_firewall_send(m);
2377 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2378 free(pfse, M_PFTEMP);
2383 m->m_flags |= M_SKIP_FIREWALL;
2384 pf_mtag->tag = rtag;
2386 if (r != NULL && r->rtableid >= 0)
2387 M_SETFIB(m, r->rtableid);
2390 if (r != NULL && r->qid) {
2391 pf_mtag->qid = r->qid;
2393 /* add hints for ecn */
2394 pf_mtag->hdr = mtod(m, struct ip *);
2397 m->m_data += max_linkhdr;
2398 m->m_pkthdr.len = m->m_len = len;
2399 m->m_pkthdr.rcvif = NULL;
2400 bzero(m->m_data, len);
2404 h = mtod(m, struct ip *);
2406 /* IP header fields included in the TCP checksum */
2407 h->ip_p = IPPROTO_TCP;
2408 h->ip_len = htons(tlen);
2409 h->ip_src.s_addr = saddr->v4.s_addr;
2410 h->ip_dst.s_addr = daddr->v4.s_addr;
2412 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2417 h6 = mtod(m, struct ip6_hdr *);
2419 /* IP header fields included in the TCP checksum */
2420 h6->ip6_nxt = IPPROTO_TCP;
2421 h6->ip6_plen = htons(tlen);
2422 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2423 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2425 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2431 th->th_sport = sport;
2432 th->th_dport = dport;
2433 th->th_seq = htonl(seq);
2434 th->th_ack = htonl(ack);
2435 th->th_off = tlen >> 2;
2436 th->th_flags = flags;
2437 th->th_win = htons(win);
2440 opt = (char *)(th + 1);
2441 opt[0] = TCPOPT_MAXSEG;
2444 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2451 th->th_sum = in_cksum(m, len);
2453 /* Finish the IP header */
2455 h->ip_hl = sizeof(*h) >> 2;
2456 h->ip_tos = IPTOS_LOWDELAY;
2457 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2458 h->ip_len = htons(len);
2459 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2462 pfse->pfse_type = PFSE_IP;
2468 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2469 sizeof(struct ip6_hdr), tlen);
2471 h6->ip6_vfc |= IPV6_VERSION;
2472 h6->ip6_hlim = IPV6_DEFHLIM;
2474 pfse->pfse_type = PFSE_IP6;
2483 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2486 struct pf_send_entry *pfse;
2488 struct pf_mtag *pf_mtag;
2490 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2491 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2495 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2496 free(pfse, M_PFTEMP);
2500 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2501 free(pfse, M_PFTEMP);
2505 m0->m_flags |= M_SKIP_FIREWALL;
2507 if (r->rtableid >= 0)
2508 M_SETFIB(m0, r->rtableid);
2512 pf_mtag->qid = r->qid;
2513 /* add hints for ecn */
2514 pf_mtag->hdr = mtod(m0, struct ip *);
2521 pfse->pfse_type = PFSE_ICMP;
2526 pfse->pfse_type = PFSE_ICMP6;
2531 pfse->pfse_icmp_type = type;
2532 pfse->pfse_icmp_code = code;
2537 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2538 * If n is 0, they match if they are equal. If n is != 0, they match if they
2542 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2543 struct pf_addr *b, sa_family_t af)
2550 if ((a->addr32[0] & m->addr32[0]) ==
2551 (b->addr32[0] & m->addr32[0]))
2557 if (((a->addr32[0] & m->addr32[0]) ==
2558 (b->addr32[0] & m->addr32[0])) &&
2559 ((a->addr32[1] & m->addr32[1]) ==
2560 (b->addr32[1] & m->addr32[1])) &&
2561 ((a->addr32[2] & m->addr32[2]) ==
2562 (b->addr32[2] & m->addr32[2])) &&
2563 ((a->addr32[3] & m->addr32[3]) ==
2564 (b->addr32[3] & m->addr32[3])))
2583 * Return 1 if b <= a <= e, otherwise return 0.
2586 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2587 struct pf_addr *a, sa_family_t af)
2592 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2593 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2602 for (i = 0; i < 4; ++i)
2603 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2605 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2608 for (i = 0; i < 4; ++i)
2609 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2611 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2621 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2625 return ((p > a1) && (p < a2));
2627 return ((p < a1) || (p > a2));
2629 return ((p >= a1) && (p <= a2));
2643 return (0); /* never reached */
2647 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2652 return (pf_match(op, a1, a2, p));
2656 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2658 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2660 return (pf_match(op, a1, a2, u));
2664 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2666 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2668 return (pf_match(op, a1, a2, g));
2672 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2677 return ((!r->match_tag_not && r->match_tag == *tag) ||
2678 (r->match_tag_not && r->match_tag != *tag));
2682 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2685 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2687 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2690 pd->pf_mtag->tag = tag;
2695 #define PF_ANCHOR_STACKSIZE 32
2696 struct pf_anchor_stackframe {
2697 struct pf_ruleset *rs;
2698 struct pf_rule *r; /* XXX: + match bit */
2699 struct pf_anchor *child;
2703 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2705 #define PF_ANCHORSTACK_MATCH 0x00000001
2706 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2708 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2709 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2710 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2711 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2712 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2716 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2717 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2720 struct pf_anchor_stackframe *f;
2726 if (*depth >= PF_ANCHOR_STACKSIZE) {
2727 printf("%s: anchor stack overflow on %s\n",
2728 __func__, (*r)->anchor->name);
2729 *r = TAILQ_NEXT(*r, entries);
2731 } else if (*depth == 0 && a != NULL)
2733 f = stack + (*depth)++;
2736 if ((*r)->anchor_wildcard) {
2737 struct pf_anchor_node *parent = &(*r)->anchor->children;
2739 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2743 *rs = &f->child->ruleset;
2746 *rs = &(*r)->anchor->ruleset;
2748 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2752 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2753 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2756 struct pf_anchor_stackframe *f;
2765 f = stack + *depth - 1;
2766 fr = PF_ANCHOR_RULE(f);
2767 if (f->child != NULL) {
2768 struct pf_anchor_node *parent;
2771 * This block traverses through
2772 * a wildcard anchor.
2774 parent = &fr->anchor->children;
2775 if (match != NULL && *match) {
2777 * If any of "*" matched, then
2778 * "foo/ *" matched, mark frame
2781 PF_ANCHOR_SET_MATCH(f);
2784 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2785 if (f->child != NULL) {
2786 *rs = &f->child->ruleset;
2787 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2795 if (*depth == 0 && a != NULL)
2798 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2800 *r = TAILQ_NEXT(fr, entries);
2801 } while (*r == NULL);
2808 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2809 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2814 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2815 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2819 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2820 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2821 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2822 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2823 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2824 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2825 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2826 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2832 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2837 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2841 if (addr->addr32[3] == 0xffffffff) {
2842 addr->addr32[3] = 0;
2843 if (addr->addr32[2] == 0xffffffff) {
2844 addr->addr32[2] = 0;
2845 if (addr->addr32[1] == 0xffffffff) {
2846 addr->addr32[1] = 0;
2848 htonl(ntohl(addr->addr32[0]) + 1);
2851 htonl(ntohl(addr->addr32[1]) + 1);
2854 htonl(ntohl(addr->addr32[2]) + 1);
2857 htonl(ntohl(addr->addr32[3]) + 1);
2864 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2866 struct pf_addr *saddr, *daddr;
2867 u_int16_t sport, dport;
2868 struct inpcbinfo *pi;
2871 pd->lookup.uid = UID_MAX;
2872 pd->lookup.gid = GID_MAX;
2874 switch (pd->proto) {
2876 if (pd->hdr.tcp == NULL)
2878 sport = pd->hdr.tcp->th_sport;
2879 dport = pd->hdr.tcp->th_dport;
2883 if (pd->hdr.udp == NULL)
2885 sport = pd->hdr.udp->uh_sport;
2886 dport = pd->hdr.udp->uh_dport;
2892 if (direction == PF_IN) {
2907 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2908 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2910 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2911 daddr->v4, dport, INPLOOKUP_WILDCARD |
2912 INPLOOKUP_RLOCKPCB, NULL, m);
2920 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2921 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2923 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2924 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2925 INPLOOKUP_RLOCKPCB, NULL, m);
2935 INP_RLOCK_ASSERT(inp);
2936 pd->lookup.uid = inp->inp_cred->cr_uid;
2937 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2944 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2948 u_int8_t *opt, optlen;
2949 u_int8_t wscale = 0;
2951 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2952 if (hlen <= sizeof(struct tcphdr))
2954 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2956 opt = hdr + sizeof(struct tcphdr);
2957 hlen -= sizeof(struct tcphdr);
2967 if (wscale > TCP_MAX_WINSHIFT)
2968 wscale = TCP_MAX_WINSHIFT;
2969 wscale |= PF_WSCALE_FLAG;
2984 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2988 u_int8_t *opt, optlen;
2989 u_int16_t mss = V_tcp_mssdflt;
2991 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2992 if (hlen <= sizeof(struct tcphdr))
2994 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2996 opt = hdr + sizeof(struct tcphdr);
2997 hlen -= sizeof(struct tcphdr);
2998 while (hlen >= TCPOLEN_MAXSEG) {
3006 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3022 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3025 struct sockaddr_in *dst;
3029 struct sockaddr_in6 *dst6;
3030 struct route_in6 ro6;
3032 struct rtentry *rt = NULL;
3034 u_int16_t mss = V_tcp_mssdflt;
3039 hlen = sizeof(struct ip);
3040 bzero(&ro, sizeof(ro));
3041 dst = (struct sockaddr_in *)&ro.ro_dst;
3042 dst->sin_family = AF_INET;
3043 dst->sin_len = sizeof(*dst);
3044 dst->sin_addr = addr->v4;
3045 in_rtalloc_ign(&ro, 0, rtableid);
3051 hlen = sizeof(struct ip6_hdr);
3052 bzero(&ro6, sizeof(ro6));
3053 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3054 dst6->sin6_family = AF_INET6;
3055 dst6->sin6_len = sizeof(*dst6);
3056 dst6->sin6_addr = addr->v6;
3057 in6_rtalloc_ign(&ro6, 0, rtableid);
3063 if (rt && rt->rt_ifp) {
3064 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3065 mss = max(V_tcp_mssdflt, mss);
3068 mss = min(mss, offer);
3069 mss = max(mss, 64); /* sanity - at least max opt space */
3074 pf_tcp_iss(struct pf_pdesc *pd)
3077 u_int32_t digest[4];
3079 if (V_pf_tcp_secret_init == 0) {
3080 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3081 MD5Init(&V_pf_tcp_secret_ctx);
3082 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3083 sizeof(V_pf_tcp_secret));
3084 V_pf_tcp_secret_init = 1;
3087 ctx = V_pf_tcp_secret_ctx;
3089 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3090 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3091 if (pd->af == AF_INET6) {
3092 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3093 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3095 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3096 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3098 MD5Final((u_char *)digest, &ctx);
3099 V_pf_tcp_iss_off += 4096;
3100 #define ISN_RANDOM_INCREMENT (4096 - 1)
3101 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3103 #undef ISN_RANDOM_INCREMENT
3107 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3108 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3109 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3111 struct pf_rule *nr = NULL;
3112 struct pf_addr * const saddr = pd->src;
3113 struct pf_addr * const daddr = pd->dst;
3114 sa_family_t af = pd->af;
3115 struct pf_rule *r, *a = NULL;
3116 struct pf_ruleset *ruleset = NULL;
3117 struct pf_src_node *nsn = NULL;
3118 struct tcphdr *th = pd->hdr.tcp;
3119 struct pf_state_key *sk = NULL, *nk = NULL;
3121 int rewrite = 0, hdrlen = 0;
3122 int tag = -1, rtableid = -1;
3126 u_int16_t sport = 0, dport = 0;
3127 u_int16_t bproto_sum = 0, bip_sum = 0;
3128 u_int8_t icmptype = 0, icmpcode = 0;
3129 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3134 INP_LOCK_ASSERT(inp);
3135 pd->lookup.uid = inp->inp_cred->cr_uid;
3136 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3137 pd->lookup.done = 1;
3140 switch (pd->proto) {
3142 sport = th->th_sport;
3143 dport = th->th_dport;
3144 hdrlen = sizeof(*th);
3147 sport = pd->hdr.udp->uh_sport;
3148 dport = pd->hdr.udp->uh_dport;
3149 hdrlen = sizeof(*pd->hdr.udp);
3153 if (pd->af != AF_INET)
3155 sport = dport = pd->hdr.icmp->icmp_id;
3156 hdrlen = sizeof(*pd->hdr.icmp);
3157 icmptype = pd->hdr.icmp->icmp_type;
3158 icmpcode = pd->hdr.icmp->icmp_code;
3160 if (icmptype == ICMP_UNREACH ||
3161 icmptype == ICMP_SOURCEQUENCH ||
3162 icmptype == ICMP_REDIRECT ||
3163 icmptype == ICMP_TIMXCEED ||
3164 icmptype == ICMP_PARAMPROB)
3169 case IPPROTO_ICMPV6:
3172 sport = dport = pd->hdr.icmp6->icmp6_id;
3173 hdrlen = sizeof(*pd->hdr.icmp6);
3174 icmptype = pd->hdr.icmp6->icmp6_type;
3175 icmpcode = pd->hdr.icmp6->icmp6_code;
3177 if (icmptype == ICMP6_DST_UNREACH ||
3178 icmptype == ICMP6_PACKET_TOO_BIG ||
3179 icmptype == ICMP6_TIME_EXCEEDED ||
3180 icmptype == ICMP6_PARAM_PROB)
3185 sport = dport = hdrlen = 0;
3189 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3191 /* check packet for BINAT/NAT/RDR */
3192 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3193 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3194 KASSERT(sk != NULL, ("%s: null sk", __func__));
3195 KASSERT(nk != NULL, ("%s: null nk", __func__));
3198 bip_sum = *pd->ip_sum;
3200 switch (pd->proto) {
3202 bproto_sum = th->th_sum;
3203 pd->proto_sum = &th->th_sum;
3205 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3206 nk->port[pd->sidx] != sport) {
3207 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3208 &th->th_sum, &nk->addr[pd->sidx],
3209 nk->port[pd->sidx], 0, af);
3210 pd->sport = &th->th_sport;
3211 sport = th->th_sport;
3214 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3215 nk->port[pd->didx] != dport) {
3216 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3217 &th->th_sum, &nk->addr[pd->didx],
3218 nk->port[pd->didx], 0, af);
3219 dport = th->th_dport;
3220 pd->dport = &th->th_dport;
3225 bproto_sum = pd->hdr.udp->uh_sum;
3226 pd->proto_sum = &pd->hdr.udp->uh_sum;
3228 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3229 nk->port[pd->sidx] != sport) {
3230 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3231 pd->ip_sum, &pd->hdr.udp->uh_sum,
3232 &nk->addr[pd->sidx],
3233 nk->port[pd->sidx], 1, af);
3234 sport = pd->hdr.udp->uh_sport;
3235 pd->sport = &pd->hdr.udp->uh_sport;
3238 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3239 nk->port[pd->didx] != dport) {
3240 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3241 pd->ip_sum, &pd->hdr.udp->uh_sum,
3242 &nk->addr[pd->didx],
3243 nk->port[pd->didx], 1, af);
3244 dport = pd->hdr.udp->uh_dport;
3245 pd->dport = &pd->hdr.udp->uh_dport;
3251 nk->port[0] = nk->port[1];
3252 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3253 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3254 nk->addr[pd->sidx].v4.s_addr, 0);
3256 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3257 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3258 nk->addr[pd->didx].v4.s_addr, 0);
3260 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3261 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3262 pd->hdr.icmp->icmp_cksum, sport,
3264 pd->hdr.icmp->icmp_id = nk->port[1];
3265 pd->sport = &pd->hdr.icmp->icmp_id;
3267 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3271 case IPPROTO_ICMPV6:
3272 nk->port[0] = nk->port[1];
3273 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3274 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3275 &nk->addr[pd->sidx], 0);
3277 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3278 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3279 &nk->addr[pd->didx], 0);
3288 &nk->addr[pd->sidx], AF_INET))
3289 pf_change_a(&saddr->v4.s_addr,
3291 nk->addr[pd->sidx].v4.s_addr, 0);
3294 &nk->addr[pd->didx], AF_INET))
3295 pf_change_a(&daddr->v4.s_addr,
3297 nk->addr[pd->didx].v4.s_addr, 0);
3303 &nk->addr[pd->sidx], AF_INET6))
3304 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3307 &nk->addr[pd->didx], AF_INET6))
3308 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3321 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3322 r = r->skip[PF_SKIP_IFP].ptr;
3323 else if (r->direction && r->direction != direction)
3324 r = r->skip[PF_SKIP_DIR].ptr;
3325 else if (r->af && r->af != af)
3326 r = r->skip[PF_SKIP_AF].ptr;
3327 else if (r->proto && r->proto != pd->proto)
3328 r = r->skip[PF_SKIP_PROTO].ptr;
3329 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3330 r->src.neg, kif, M_GETFIB(m)))
3331 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3332 /* tcp/udp only. port_op always 0 in other cases */
3333 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3334 r->src.port[0], r->src.port[1], sport))
3335 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3336 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3337 r->dst.neg, NULL, M_GETFIB(m)))
3338 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3339 /* tcp/udp only. port_op always 0 in other cases */
3340 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3341 r->dst.port[0], r->dst.port[1], dport))
3342 r = r->skip[PF_SKIP_DST_PORT].ptr;
3343 /* icmp only. type always 0 in other cases */
3344 else if (r->type && r->type != icmptype + 1)
3345 r = TAILQ_NEXT(r, entries);
3346 /* icmp only. type always 0 in other cases */
3347 else if (r->code && r->code != icmpcode + 1)
3348 r = TAILQ_NEXT(r, entries);
3349 else if (r->tos && !(r->tos == pd->tos))
3350 r = TAILQ_NEXT(r, entries);
3351 else if (r->rule_flag & PFRULE_FRAGMENT)
3352 r = TAILQ_NEXT(r, entries);
3353 else if (pd->proto == IPPROTO_TCP &&
3354 (r->flagset & th->th_flags) != r->flags)
3355 r = TAILQ_NEXT(r, entries);
3356 /* tcp/udp only. uid.op always 0 in other cases */
3357 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3358 pf_socket_lookup(direction, pd, m), 1)) &&
3359 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3361 r = TAILQ_NEXT(r, entries);
3362 /* tcp/udp only. gid.op always 0 in other cases */
3363 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3364 pf_socket_lookup(direction, pd, m), 1)) &&
3365 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3367 r = TAILQ_NEXT(r, entries);
3369 r->prob <= arc4random())
3370 r = TAILQ_NEXT(r, entries);
3371 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3372 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3373 r = TAILQ_NEXT(r, entries);
3374 else if (r->os_fingerprint != PF_OSFP_ANY &&
3375 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3376 pf_osfp_fingerprint(pd, m, off, th),
3377 r->os_fingerprint)))
3378 r = TAILQ_NEXT(r, entries);
3382 if (r->rtableid >= 0)
3383 rtableid = r->rtableid;
3384 if (r->anchor == NULL) {
3391 r = TAILQ_NEXT(r, entries);
3393 pf_step_into_anchor(anchor_stack, &asd,
3394 &ruleset, PF_RULESET_FILTER, &r, &a,
3397 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3398 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3405 REASON_SET(&reason, PFRES_MATCH);
3407 if (r->log || (nr != NULL && nr->log)) {
3409 m_copyback(m, off, hdrlen, pd->hdr.any);
3410 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3414 if ((r->action == PF_DROP) &&
3415 ((r->rule_flag & PFRULE_RETURNRST) ||
3416 (r->rule_flag & PFRULE_RETURNICMP) ||
3417 (r->rule_flag & PFRULE_RETURN))) {
3418 /* undo NAT changes, if they have taken place */
3420 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3421 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3423 *pd->sport = sk->port[pd->sidx];
3425 *pd->dport = sk->port[pd->didx];
3427 *pd->proto_sum = bproto_sum;
3429 *pd->ip_sum = bip_sum;
3430 m_copyback(m, off, hdrlen, pd->hdr.any);
3432 if (pd->proto == IPPROTO_TCP &&
3433 ((r->rule_flag & PFRULE_RETURNRST) ||
3434 (r->rule_flag & PFRULE_RETURN)) &&
3435 !(th->th_flags & TH_RST)) {
3436 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3448 h4 = mtod(m, struct ip *);
3449 len = ntohs(h4->ip_len) - off;
3454 h6 = mtod(m, struct ip6_hdr *);
3455 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3460 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3461 REASON_SET(&reason, PFRES_PROTCKSUM);
3463 if (th->th_flags & TH_SYN)
3465 if (th->th_flags & TH_FIN)
3467 pf_send_tcp(m, r, af, pd->dst,
3468 pd->src, th->th_dport, th->th_sport,
3469 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3470 r->return_ttl, 1, 0, kif->pfik_ifp);
3472 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3474 pf_send_icmp(m, r->return_icmp >> 8,
3475 r->return_icmp & 255, af, r);
3476 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3478 pf_send_icmp(m, r->return_icmp6 >> 8,
3479 r->return_icmp6 & 255, af, r);
3482 if (r->action == PF_DROP)
3485 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3486 REASON_SET(&reason, PFRES_MEMORY);
3490 M_SETFIB(m, rtableid);
3492 if (!state_icmp && (r->keep_state || nr != NULL ||
3493 (pd->flags & PFDESC_TCP_NORM))) {
3495 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3496 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3498 if (action != PF_PASS)
3502 uma_zfree(V_pf_state_key_z, sk);
3504 uma_zfree(V_pf_state_key_z, nk);
3507 /* copy back packet headers if we performed NAT operations */
3509 m_copyback(m, off, hdrlen, pd->hdr.any);
3511 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3512 direction == PF_OUT &&
3513 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3515 * We want the state created, but we dont
3516 * want to send this in case a partner
3517 * firewall has to know about it to allow
3518 * replies through it.
3526 uma_zfree(V_pf_state_key_z, sk);
3528 uma_zfree(V_pf_state_key_z, nk);
3533 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3534 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3535 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3536 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3537 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3539 struct pf_state *s = NULL;
3540 struct pf_src_node *sn = NULL;
3541 struct tcphdr *th = pd->hdr.tcp;
3542 u_int16_t mss = V_tcp_mssdflt;
3545 /* check maximums */
3546 if (r->max_states &&
3547 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3548 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3549 REASON_SET(&reason, PFRES_MAXSTATES);
3552 /* src node for filter rule */
3553 if ((r->rule_flag & PFRULE_SRCTRACK ||
3554 r->rpool.opts & PF_POOL_STICKYADDR) &&
3555 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3556 REASON_SET(&reason, PFRES_SRCLIMIT);
3559 /* src node for translation rule */
3560 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3561 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3562 REASON_SET(&reason, PFRES_SRCLIMIT);
3565 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3567 REASON_SET(&reason, PFRES_MEMORY);
3571 s->nat_rule.ptr = nr;
3573 STATE_INC_COUNTERS(s);
3575 s->state_flags |= PFSTATE_ALLOWOPTS;
3576 if (r->rule_flag & PFRULE_STATESLOPPY)
3577 s->state_flags |= PFSTATE_SLOPPY;
3578 s->log = r->log & PF_LOG_ALL;
3579 s->sync_state = PFSYNC_S_NONE;
3581 s->log |= nr->log & PF_LOG_ALL;
3582 switch (pd->proto) {
3584 s->src.seqlo = ntohl(th->th_seq);
3585 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3586 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3587 r->keep_state == PF_STATE_MODULATE) {
3588 /* Generate sequence number modulator */
3589 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3592 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3593 htonl(s->src.seqlo + s->src.seqdiff), 0);
3597 if (th->th_flags & TH_SYN) {
3599 s->src.wscale = pf_get_wscale(m, off,
3600 th->th_off, pd->af);
3602 s->src.max_win = MAX(ntohs(th->th_win), 1);
3603 if (s->src.wscale & PF_WSCALE_MASK) {
3604 /* Remove scale factor from initial window */
3605 int win = s->src.max_win;
3606 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3607 s->src.max_win = (win - 1) >>
3608 (s->src.wscale & PF_WSCALE_MASK);
3610 if (th->th_flags & TH_FIN)
3614 s->src.state = TCPS_SYN_SENT;
3615 s->dst.state = TCPS_CLOSED;
3616 s->timeout = PFTM_TCP_FIRST_PACKET;
3619 s->src.state = PFUDPS_SINGLE;
3620 s->dst.state = PFUDPS_NO_TRAFFIC;
3621 s->timeout = PFTM_UDP_FIRST_PACKET;
3625 case IPPROTO_ICMPV6:
3627 s->timeout = PFTM_ICMP_FIRST_PACKET;
3630 s->src.state = PFOTHERS_SINGLE;
3631 s->dst.state = PFOTHERS_NO_TRAFFIC;
3632 s->timeout = PFTM_OTHER_FIRST_PACKET;
3635 if (r->rt && r->rt != PF_FASTROUTE) {
3636 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3637 REASON_SET(&reason, PFRES_BADSTATE);
3638 pf_src_tree_remove_state(s);
3639 STATE_DEC_COUNTERS(s);
3640 uma_zfree(V_pf_state_z, s);
3643 s->rt_kif = r->rpool.cur->kif;
3646 s->creation = time_uptime;
3647 s->expire = time_uptime;
3652 /* XXX We only modify one side for now. */
3653 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3654 s->nat_src_node = nsn;
3656 if (pd->proto == IPPROTO_TCP) {
3657 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3658 off, pd, th, &s->src, &s->dst)) {
3659 REASON_SET(&reason, PFRES_MEMORY);
3660 pf_src_tree_remove_state(s);
3661 STATE_DEC_COUNTERS(s);
3662 uma_zfree(V_pf_state_z, s);
3665 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3666 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3667 &s->src, &s->dst, rewrite)) {
3668 /* This really shouldn't happen!!! */
3669 DPFPRINTF(PF_DEBUG_URGENT,
3670 ("pf_normalize_tcp_stateful failed on first pkt"));
3671 pf_normalize_tcp_cleanup(s);
3672 pf_src_tree_remove_state(s);
3673 STATE_DEC_COUNTERS(s);
3674 uma_zfree(V_pf_state_z, s);
3678 s->direction = pd->dir;
3681 * sk/nk could already been setup by pf_get_translation().
3684 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3685 __func__, nr, sk, nk));
3686 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3691 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3692 __func__, nr, sk, nk));
3694 /* Swap sk/nk for PF_OUT. */
3695 if (pf_state_insert(BOUND_IFACE(r, kif),
3696 (pd->dir == PF_IN) ? sk : nk,
3697 (pd->dir == PF_IN) ? nk : sk, s)) {
3698 if (pd->proto == IPPROTO_TCP)
3699 pf_normalize_tcp_cleanup(s);
3700 REASON_SET(&reason, PFRES_STATEINS);
3701 pf_src_tree_remove_state(s);
3702 STATE_DEC_COUNTERS(s);
3703 uma_zfree(V_pf_state_z, s);
3710 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3711 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3712 s->src.state = PF_TCPS_PROXY_SRC;
3713 /* undo NAT changes, if they have taken place */
3715 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3716 if (pd->dir == PF_OUT)
3717 skt = s->key[PF_SK_STACK];
3718 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3719 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3721 *pd->sport = skt->port[pd->sidx];
3723 *pd->dport = skt->port[pd->didx];
3725 *pd->proto_sum = bproto_sum;
3727 *pd->ip_sum = bip_sum;
3728 m_copyback(m, off, hdrlen, pd->hdr.any);
3730 s->src.seqhi = htonl(arc4random());
3731 /* Find mss option */
3732 int rtid = M_GETFIB(m);
3733 mss = pf_get_mss(m, off, th->th_off, pd->af);
3734 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3735 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3737 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3738 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3739 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3740 REASON_SET(&reason, PFRES_SYNPROXY);
3741 return (PF_SYNPROXY_DROP);
3748 uma_zfree(V_pf_state_key_z, sk);
3750 uma_zfree(V_pf_state_key_z, nk);
3753 struct pf_srchash *sh;
3755 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3756 PF_HASHROW_LOCK(sh);
3757 if (--sn->states == 0 && sn->expire == 0) {
3758 pf_unlink_src_node(sn);
3759 uma_zfree(V_pf_sources_z, sn);
3761 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3763 PF_HASHROW_UNLOCK(sh);
3766 if (nsn != sn && nsn != NULL) {
3767 struct pf_srchash *sh;
3769 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3770 PF_HASHROW_LOCK(sh);
3771 if (--nsn->states == 0 && nsn->expire == 0) {
3772 pf_unlink_src_node(nsn);
3773 uma_zfree(V_pf_sources_z, nsn);
3775 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3777 PF_HASHROW_UNLOCK(sh);
3784 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3785 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3786 struct pf_ruleset **rsm)
3788 struct pf_rule *r, *a = NULL;
3789 struct pf_ruleset *ruleset = NULL;
3790 sa_family_t af = pd->af;
3795 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3799 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3802 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3803 r = r->skip[PF_SKIP_IFP].ptr;
3804 else if (r->direction && r->direction != direction)
3805 r = r->skip[PF_SKIP_DIR].ptr;
3806 else if (r->af && r->af != af)
3807 r = r->skip[PF_SKIP_AF].ptr;
3808 else if (r->proto && r->proto != pd->proto)
3809 r = r->skip[PF_SKIP_PROTO].ptr;
3810 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3811 r->src.neg, kif, M_GETFIB(m)))
3812 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3813 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3814 r->dst.neg, NULL, M_GETFIB(m)))
3815 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3816 else if (r->tos && !(r->tos == pd->tos))
3817 r = TAILQ_NEXT(r, entries);
3818 else if (r->os_fingerprint != PF_OSFP_ANY)
3819 r = TAILQ_NEXT(r, entries);
3820 else if (pd->proto == IPPROTO_UDP &&
3821 (r->src.port_op || r->dst.port_op))
3822 r = TAILQ_NEXT(r, entries);
3823 else if (pd->proto == IPPROTO_TCP &&
3824 (r->src.port_op || r->dst.port_op || r->flagset))
3825 r = TAILQ_NEXT(r, entries);
3826 else if ((pd->proto == IPPROTO_ICMP ||
3827 pd->proto == IPPROTO_ICMPV6) &&
3828 (r->type || r->code))
3829 r = TAILQ_NEXT(r, entries);
3830 else if (r->prob && r->prob <=
3831 (arc4random() % (UINT_MAX - 1) + 1))
3832 r = TAILQ_NEXT(r, entries);
3833 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3834 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3835 r = TAILQ_NEXT(r, entries);
3837 if (r->anchor == NULL) {
3844 r = TAILQ_NEXT(r, entries);
3846 pf_step_into_anchor(anchor_stack, &asd,
3847 &ruleset, PF_RULESET_FILTER, &r, &a,
3850 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3851 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3858 REASON_SET(&reason, PFRES_MATCH);
3861 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3864 if (r->action != PF_PASS)
3867 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3868 REASON_SET(&reason, PFRES_MEMORY);
3876 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3877 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3878 struct pf_pdesc *pd, u_short *reason, int *copyback)
3880 struct tcphdr *th = pd->hdr.tcp;
3881 u_int16_t win = ntohs(th->th_win);
3882 u_int32_t ack, end, seq, orig_seq;
3886 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3887 sws = src->wscale & PF_WSCALE_MASK;
3888 dws = dst->wscale & PF_WSCALE_MASK;
3893 * Sequence tracking algorithm from Guido van Rooij's paper:
3894 * http://www.madison-gurkha.com/publications/tcp_filtering/
3898 orig_seq = seq = ntohl(th->th_seq);
3899 if (src->seqlo == 0) {
3900 /* First packet from this end. Set its state */
3902 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3903 src->scrub == NULL) {
3904 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3905 REASON_SET(reason, PFRES_MEMORY);
3910 /* Deferred generation of sequence number modulator */
3911 if (dst->seqdiff && !src->seqdiff) {
3912 /* use random iss for the TCP server */
3913 while ((src->seqdiff = arc4random() - seq) == 0)
3915 ack = ntohl(th->th_ack) - dst->seqdiff;
3916 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3918 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3921 ack = ntohl(th->th_ack);
3924 end = seq + pd->p_len;
3925 if (th->th_flags & TH_SYN) {
3927 if (dst->wscale & PF_WSCALE_FLAG) {
3928 src->wscale = pf_get_wscale(m, off, th->th_off,
3930 if (src->wscale & PF_WSCALE_FLAG) {
3931 /* Remove scale factor from initial
3933 sws = src->wscale & PF_WSCALE_MASK;
3934 win = ((u_int32_t)win + (1 << sws) - 1)
3936 dws = dst->wscale & PF_WSCALE_MASK;
3938 /* fixup other window */
3939 dst->max_win <<= dst->wscale &
3941 /* in case of a retrans SYN|ACK */
3946 if (th->th_flags & TH_FIN)
3950 if (src->state < TCPS_SYN_SENT)
3951 src->state = TCPS_SYN_SENT;
3954 * May need to slide the window (seqhi may have been set by
3955 * the crappy stack check or if we picked up the connection
3956 * after establishment)
3958 if (src->seqhi == 1 ||
3959 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3960 src->seqhi = end + MAX(1, dst->max_win << dws);
3961 if (win > src->max_win)
3965 ack = ntohl(th->th_ack) - dst->seqdiff;
3967 /* Modulate sequence numbers */
3968 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3970 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3973 end = seq + pd->p_len;
3974 if (th->th_flags & TH_SYN)
3976 if (th->th_flags & TH_FIN)
3980 if ((th->th_flags & TH_ACK) == 0) {
3981 /* Let it pass through the ack skew check */
3983 } else if ((ack == 0 &&
3984 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3985 /* broken tcp stacks do not set ack */
3986 (dst->state < TCPS_SYN_SENT)) {
3988 * Many stacks (ours included) will set the ACK number in an
3989 * FIN|ACK if the SYN times out -- no sequence to ACK.
3995 /* Ease sequencing restrictions on no data packets */
4000 ackskew = dst->seqlo - ack;
4004 * Need to demodulate the sequence numbers in any TCP SACK options
4005 * (Selective ACK). We could optionally validate the SACK values
4006 * against the current ACK window, either forwards or backwards, but
4007 * I'm not confident that SACK has been implemented properly
4008 * everywhere. It wouldn't surprise me if several stacks accidently
4009 * SACK too far backwards of previously ACKed data. There really aren't
4010 * any security implications of bad SACKing unless the target stack
4011 * doesn't validate the option length correctly. Someone trying to
4012 * spoof into a TCP connection won't bother blindly sending SACK
4015 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4016 if (pf_modulate_sack(m, off, pd, th, dst))
4021 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4022 if (SEQ_GEQ(src->seqhi, end) &&
4023 /* Last octet inside other's window space */
4024 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4025 /* Retrans: not more than one window back */
4026 (ackskew >= -MAXACKWINDOW) &&
4027 /* Acking not more than one reassembled fragment backwards */
4028 (ackskew <= (MAXACKWINDOW << sws)) &&
4029 /* Acking not more than one window forward */
4030 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4031 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4032 (pd->flags & PFDESC_IP_REAS) == 0)) {
4033 /* Require an exact/+1 sequence match on resets when possible */
4035 if (dst->scrub || src->scrub) {
4036 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4037 *state, src, dst, copyback))
4041 /* update max window */
4042 if (src->max_win < win)
4044 /* synchronize sequencing */
4045 if (SEQ_GT(end, src->seqlo))
4047 /* slide the window of what the other end can send */
4048 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4049 dst->seqhi = ack + MAX((win << sws), 1);
4053 if (th->th_flags & TH_SYN)
4054 if (src->state < TCPS_SYN_SENT)
4055 src->state = TCPS_SYN_SENT;
4056 if (th->th_flags & TH_FIN)
4057 if (src->state < TCPS_CLOSING)
4058 src->state = TCPS_CLOSING;
4059 if (th->th_flags & TH_ACK) {
4060 if (dst->state == TCPS_SYN_SENT) {
4061 dst->state = TCPS_ESTABLISHED;
4062 if (src->state == TCPS_ESTABLISHED &&
4063 (*state)->src_node != NULL &&
4064 pf_src_connlimit(state)) {
4065 REASON_SET(reason, PFRES_SRCLIMIT);
4068 } else if (dst->state == TCPS_CLOSING)
4069 dst->state = TCPS_FIN_WAIT_2;
4071 if (th->th_flags & TH_RST)
4072 src->state = dst->state = TCPS_TIME_WAIT;
4074 /* update expire time */
4075 (*state)->expire = time_uptime;
4076 if (src->state >= TCPS_FIN_WAIT_2 &&
4077 dst->state >= TCPS_FIN_WAIT_2)
4078 (*state)->timeout = PFTM_TCP_CLOSED;
4079 else if (src->state >= TCPS_CLOSING &&
4080 dst->state >= TCPS_CLOSING)
4081 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4082 else if (src->state < TCPS_ESTABLISHED ||
4083 dst->state < TCPS_ESTABLISHED)
4084 (*state)->timeout = PFTM_TCP_OPENING;
4085 else if (src->state >= TCPS_CLOSING ||
4086 dst->state >= TCPS_CLOSING)
4087 (*state)->timeout = PFTM_TCP_CLOSING;
4089 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4091 /* Fall through to PASS packet */
4093 } else if ((dst->state < TCPS_SYN_SENT ||
4094 dst->state >= TCPS_FIN_WAIT_2 ||
4095 src->state >= TCPS_FIN_WAIT_2) &&
4096 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4097 /* Within a window forward of the originating packet */
4098 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4099 /* Within a window backward of the originating packet */
4102 * This currently handles three situations:
4103 * 1) Stupid stacks will shotgun SYNs before their peer
4105 * 2) When PF catches an already established stream (the
4106 * firewall rebooted, the state table was flushed, routes
4108 * 3) Packets get funky immediately after the connection
4109 * closes (this should catch Solaris spurious ACK|FINs
4110 * that web servers like to spew after a close)
4112 * This must be a little more careful than the above code
4113 * since packet floods will also be caught here. We don't
4114 * update the TTL here to mitigate the damage of a packet
4115 * flood and so the same code can handle awkward establishment
4116 * and a loosened connection close.
4117 * In the establishment case, a correct peer response will
4118 * validate the connection, go through the normal state code
4119 * and keep updating the state TTL.
4122 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4123 printf("pf: loose state match: ");
4124 pf_print_state(*state);
4125 pf_print_flags(th->th_flags);
4126 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4127 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4128 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4129 (unsigned long long)(*state)->packets[1],
4130 pd->dir == PF_IN ? "in" : "out",
4131 pd->dir == (*state)->direction ? "fwd" : "rev");
4134 if (dst->scrub || src->scrub) {
4135 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4136 *state, src, dst, copyback))
4140 /* update max window */
4141 if (src->max_win < win)
4143 /* synchronize sequencing */
4144 if (SEQ_GT(end, src->seqlo))
4146 /* slide the window of what the other end can send */
4147 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4148 dst->seqhi = ack + MAX((win << sws), 1);
4151 * Cannot set dst->seqhi here since this could be a shotgunned
4152 * SYN and not an already established connection.
4155 if (th->th_flags & TH_FIN)
4156 if (src->state < TCPS_CLOSING)
4157 src->state = TCPS_CLOSING;
4158 if (th->th_flags & TH_RST)
4159 src->state = dst->state = TCPS_TIME_WAIT;
4161 /* Fall through to PASS packet */
4164 if ((*state)->dst.state == TCPS_SYN_SENT &&
4165 (*state)->src.state == TCPS_SYN_SENT) {
4166 /* Send RST for state mismatches during handshake */
4167 if (!(th->th_flags & TH_RST))
4168 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4169 pd->dst, pd->src, th->th_dport,
4170 th->th_sport, ntohl(th->th_ack), 0,
4172 (*state)->rule.ptr->return_ttl, 1, 0,
4177 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4178 printf("pf: BAD state: ");
4179 pf_print_state(*state);
4180 pf_print_flags(th->th_flags);
4181 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4182 "pkts=%llu:%llu dir=%s,%s\n",
4183 seq, orig_seq, ack, pd->p_len, ackskew,
4184 (unsigned long long)(*state)->packets[0],
4185 (unsigned long long)(*state)->packets[1],
4186 pd->dir == PF_IN ? "in" : "out",
4187 pd->dir == (*state)->direction ? "fwd" : "rev");
4188 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4189 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4190 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4192 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4193 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4194 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4195 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4197 REASON_SET(reason, PFRES_BADSTATE);
4205 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4206 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4208 struct tcphdr *th = pd->hdr.tcp;
4210 if (th->th_flags & TH_SYN)
4211 if (src->state < TCPS_SYN_SENT)
4212 src->state = TCPS_SYN_SENT;
4213 if (th->th_flags & TH_FIN)
4214 if (src->state < TCPS_CLOSING)
4215 src->state = TCPS_CLOSING;
4216 if (th->th_flags & TH_ACK) {
4217 if (dst->state == TCPS_SYN_SENT) {
4218 dst->state = TCPS_ESTABLISHED;
4219 if (src->state == TCPS_ESTABLISHED &&
4220 (*state)->src_node != NULL &&
4221 pf_src_connlimit(state)) {
4222 REASON_SET(reason, PFRES_SRCLIMIT);
4225 } else if (dst->state == TCPS_CLOSING) {
4226 dst->state = TCPS_FIN_WAIT_2;
4227 } else if (src->state == TCPS_SYN_SENT &&
4228 dst->state < TCPS_SYN_SENT) {
4230 * Handle a special sloppy case where we only see one
4231 * half of the connection. If there is a ACK after
4232 * the initial SYN without ever seeing a packet from
4233 * the destination, set the connection to established.
4235 dst->state = src->state = TCPS_ESTABLISHED;
4236 if ((*state)->src_node != NULL &&
4237 pf_src_connlimit(state)) {
4238 REASON_SET(reason, PFRES_SRCLIMIT);
4241 } else if (src->state == TCPS_CLOSING &&
4242 dst->state == TCPS_ESTABLISHED &&
4245 * Handle the closing of half connections where we
4246 * don't see the full bidirectional FIN/ACK+ACK
4249 dst->state = TCPS_CLOSING;
4252 if (th->th_flags & TH_RST)
4253 src->state = dst->state = TCPS_TIME_WAIT;
4255 /* update expire time */
4256 (*state)->expire = time_uptime;
4257 if (src->state >= TCPS_FIN_WAIT_2 &&
4258 dst->state >= TCPS_FIN_WAIT_2)
4259 (*state)->timeout = PFTM_TCP_CLOSED;
4260 else if (src->state >= TCPS_CLOSING &&
4261 dst->state >= TCPS_CLOSING)
4262 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4263 else if (src->state < TCPS_ESTABLISHED ||
4264 dst->state < TCPS_ESTABLISHED)
4265 (*state)->timeout = PFTM_TCP_OPENING;
4266 else if (src->state >= TCPS_CLOSING ||
4267 dst->state >= TCPS_CLOSING)
4268 (*state)->timeout = PFTM_TCP_CLOSING;
4270 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4276 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4277 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4280 struct pf_state_key_cmp key;
4281 struct tcphdr *th = pd->hdr.tcp;
4283 struct pf_state_peer *src, *dst;
4284 struct pf_state_key *sk;
4286 bzero(&key, sizeof(key));
4288 key.proto = IPPROTO_TCP;
4289 if (direction == PF_IN) { /* wire side, straight */
4290 PF_ACPY(&key.addr[0], pd->src, key.af);
4291 PF_ACPY(&key.addr[1], pd->dst, key.af);
4292 key.port[0] = th->th_sport;
4293 key.port[1] = th->th_dport;
4294 } else { /* stack side, reverse */
4295 PF_ACPY(&key.addr[1], pd->src, key.af);
4296 PF_ACPY(&key.addr[0], pd->dst, key.af);
4297 key.port[1] = th->th_sport;
4298 key.port[0] = th->th_dport;
4301 STATE_LOOKUP(kif, &key, direction, *state, pd);
4303 if (direction == (*state)->direction) {
4304 src = &(*state)->src;
4305 dst = &(*state)->dst;
4307 src = &(*state)->dst;
4308 dst = &(*state)->src;
4311 sk = (*state)->key[pd->didx];
4313 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4314 if (direction != (*state)->direction) {
4315 REASON_SET(reason, PFRES_SYNPROXY);
4316 return (PF_SYNPROXY_DROP);
4318 if (th->th_flags & TH_SYN) {
4319 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4320 REASON_SET(reason, PFRES_SYNPROXY);
4323 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4324 pd->src, th->th_dport, th->th_sport,
4325 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4326 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4327 REASON_SET(reason, PFRES_SYNPROXY);
4328 return (PF_SYNPROXY_DROP);
4329 } else if (!(th->th_flags & TH_ACK) ||
4330 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4331 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4332 REASON_SET(reason, PFRES_SYNPROXY);
4334 } else if ((*state)->src_node != NULL &&
4335 pf_src_connlimit(state)) {
4336 REASON_SET(reason, PFRES_SRCLIMIT);
4339 (*state)->src.state = PF_TCPS_PROXY_DST;
4341 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4342 if (direction == (*state)->direction) {
4343 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4344 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4345 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4346 REASON_SET(reason, PFRES_SYNPROXY);
4349 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4350 if ((*state)->dst.seqhi == 1)
4351 (*state)->dst.seqhi = htonl(arc4random());
4352 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4353 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4354 sk->port[pd->sidx], sk->port[pd->didx],
4355 (*state)->dst.seqhi, 0, TH_SYN, 0,
4356 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4357 REASON_SET(reason, PFRES_SYNPROXY);
4358 return (PF_SYNPROXY_DROP);
4359 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4361 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4362 REASON_SET(reason, PFRES_SYNPROXY);
4365 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4366 (*state)->dst.seqlo = ntohl(th->th_seq);
4367 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4368 pd->src, th->th_dport, th->th_sport,
4369 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4370 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4371 (*state)->tag, NULL);
4372 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4373 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4374 sk->port[pd->sidx], sk->port[pd->didx],
4375 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4376 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4377 (*state)->src.seqdiff = (*state)->dst.seqhi -
4378 (*state)->src.seqlo;
4379 (*state)->dst.seqdiff = (*state)->src.seqhi -
4380 (*state)->dst.seqlo;
4381 (*state)->src.seqhi = (*state)->src.seqlo +
4382 (*state)->dst.max_win;
4383 (*state)->dst.seqhi = (*state)->dst.seqlo +
4384 (*state)->src.max_win;
4385 (*state)->src.wscale = (*state)->dst.wscale = 0;
4386 (*state)->src.state = (*state)->dst.state =
4388 REASON_SET(reason, PFRES_SYNPROXY);
4389 return (PF_SYNPROXY_DROP);
4393 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4394 dst->state >= TCPS_FIN_WAIT_2 &&
4395 src->state >= TCPS_FIN_WAIT_2) {
4396 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4397 printf("pf: state reuse ");
4398 pf_print_state(*state);
4399 pf_print_flags(th->th_flags);
4402 /* XXX make sure it's the same direction ?? */
4403 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4404 pf_unlink_state(*state, PF_ENTER_LOCKED);
4409 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4410 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4413 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4414 ©back) == PF_DROP)
4418 /* translate source/destination address, if necessary */
4419 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4420 struct pf_state_key *nk = (*state)->key[pd->didx];
4422 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4423 nk->port[pd->sidx] != th->th_sport)
4424 pf_change_ap(m, pd->src, &th->th_sport,
4425 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4426 nk->port[pd->sidx], 0, pd->af);
4428 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4429 nk->port[pd->didx] != th->th_dport)
4430 pf_change_ap(m, pd->dst, &th->th_dport,
4431 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4432 nk->port[pd->didx], 0, pd->af);
4436 /* Copyback sequence modulation or stateful scrub changes if needed */
4438 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4444 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4445 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4447 struct pf_state_peer *src, *dst;
4448 struct pf_state_key_cmp key;
4449 struct udphdr *uh = pd->hdr.udp;
4451 bzero(&key, sizeof(key));
4453 key.proto = IPPROTO_UDP;
4454 if (direction == PF_IN) { /* wire side, straight */
4455 PF_ACPY(&key.addr[0], pd->src, key.af);
4456 PF_ACPY(&key.addr[1], pd->dst, key.af);
4457 key.port[0] = uh->uh_sport;
4458 key.port[1] = uh->uh_dport;
4459 } else { /* stack side, reverse */
4460 PF_ACPY(&key.addr[1], pd->src, key.af);
4461 PF_ACPY(&key.addr[0], pd->dst, key.af);
4462 key.port[1] = uh->uh_sport;
4463 key.port[0] = uh->uh_dport;
4466 STATE_LOOKUP(kif, &key, direction, *state, pd);
4468 if (direction == (*state)->direction) {
4469 src = &(*state)->src;
4470 dst = &(*state)->dst;
4472 src = &(*state)->dst;
4473 dst = &(*state)->src;
4477 if (src->state < PFUDPS_SINGLE)
4478 src->state = PFUDPS_SINGLE;
4479 if (dst->state == PFUDPS_SINGLE)
4480 dst->state = PFUDPS_MULTIPLE;
4482 /* update expire time */
4483 (*state)->expire = time_uptime;
4484 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4485 (*state)->timeout = PFTM_UDP_MULTIPLE;
4487 (*state)->timeout = PFTM_UDP_SINGLE;
4489 /* translate source/destination address, if necessary */
4490 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4491 struct pf_state_key *nk = (*state)->key[pd->didx];
4493 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4494 nk->port[pd->sidx] != uh->uh_sport)
4495 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4496 &uh->uh_sum, &nk->addr[pd->sidx],
4497 nk->port[pd->sidx], 1, pd->af);
4499 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4500 nk->port[pd->didx] != uh->uh_dport)
4501 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4502 &uh->uh_sum, &nk->addr[pd->didx],
4503 nk->port[pd->didx], 1, pd->af);
4504 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4511 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4512 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4514 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4515 u_int16_t icmpid = 0, *icmpsum;
4518 struct pf_state_key_cmp key;
4520 bzero(&key, sizeof(key));
4521 switch (pd->proto) {
4524 icmptype = pd->hdr.icmp->icmp_type;
4525 icmpid = pd->hdr.icmp->icmp_id;
4526 icmpsum = &pd->hdr.icmp->icmp_cksum;
4528 if (icmptype == ICMP_UNREACH ||
4529 icmptype == ICMP_SOURCEQUENCH ||
4530 icmptype == ICMP_REDIRECT ||
4531 icmptype == ICMP_TIMXCEED ||
4532 icmptype == ICMP_PARAMPROB)
4537 case IPPROTO_ICMPV6:
4538 icmptype = pd->hdr.icmp6->icmp6_type;
4539 icmpid = pd->hdr.icmp6->icmp6_id;
4540 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4542 if (icmptype == ICMP6_DST_UNREACH ||
4543 icmptype == ICMP6_PACKET_TOO_BIG ||
4544 icmptype == ICMP6_TIME_EXCEEDED ||
4545 icmptype == ICMP6_PARAM_PROB)
4554 * ICMP query/reply message not related to a TCP/UDP packet.
4555 * Search for an ICMP state.
4558 key.proto = pd->proto;
4559 key.port[0] = key.port[1] = icmpid;
4560 if (direction == PF_IN) { /* wire side, straight */
4561 PF_ACPY(&key.addr[0], pd->src, key.af);
4562 PF_ACPY(&key.addr[1], pd->dst, key.af);
4563 } else { /* stack side, reverse */
4564 PF_ACPY(&key.addr[1], pd->src, key.af);
4565 PF_ACPY(&key.addr[0], pd->dst, key.af);
4568 STATE_LOOKUP(kif, &key, direction, *state, pd);
4570 (*state)->expire = time_uptime;
4571 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4573 /* translate source/destination address, if necessary */
4574 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4575 struct pf_state_key *nk = (*state)->key[pd->didx];
4580 if (PF_ANEQ(pd->src,
4581 &nk->addr[pd->sidx], AF_INET))
4582 pf_change_a(&saddr->v4.s_addr,
4584 nk->addr[pd->sidx].v4.s_addr, 0);
4586 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4588 pf_change_a(&daddr->v4.s_addr,
4590 nk->addr[pd->didx].v4.s_addr, 0);
4593 pd->hdr.icmp->icmp_id) {
4594 pd->hdr.icmp->icmp_cksum =
4596 pd->hdr.icmp->icmp_cksum, icmpid,
4597 nk->port[pd->sidx], 0);
4598 pd->hdr.icmp->icmp_id =
4602 m_copyback(m, off, ICMP_MINLEN,
4603 (caddr_t )pd->hdr.icmp);
4608 if (PF_ANEQ(pd->src,
4609 &nk->addr[pd->sidx], AF_INET6))
4611 &pd->hdr.icmp6->icmp6_cksum,
4612 &nk->addr[pd->sidx], 0);
4614 if (PF_ANEQ(pd->dst,
4615 &nk->addr[pd->didx], AF_INET6))
4617 &pd->hdr.icmp6->icmp6_cksum,
4618 &nk->addr[pd->didx], 0);
4620 m_copyback(m, off, sizeof(struct icmp6_hdr),
4621 (caddr_t )pd->hdr.icmp6);
4630 * ICMP error message in response to a TCP/UDP packet.
4631 * Extract the inner TCP/UDP header and search for that state.
4634 struct pf_pdesc pd2;
4635 bzero(&pd2, sizeof pd2);
4640 struct ip6_hdr h2_6;
4647 /* Payload packet is from the opposite direction. */
4648 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4649 pd2.didx = (direction == PF_IN) ? 0 : 1;
4653 /* offset of h2 in mbuf chain */
4654 ipoff2 = off + ICMP_MINLEN;
4656 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4657 NULL, reason, pd2.af)) {
4658 DPFPRINTF(PF_DEBUG_MISC,
4659 ("pf: ICMP error message too short "
4664 * ICMP error messages don't refer to non-first
4667 if (h2.ip_off & htons(IP_OFFMASK)) {
4668 REASON_SET(reason, PFRES_FRAG);
4672 /* offset of protocol header that follows h2 */
4673 off2 = ipoff2 + (h2.ip_hl << 2);
4675 pd2.proto = h2.ip_p;
4676 pd2.src = (struct pf_addr *)&h2.ip_src;
4677 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4678 pd2.ip_sum = &h2.ip_sum;
4683 ipoff2 = off + sizeof(struct icmp6_hdr);
4685 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4686 NULL, reason, pd2.af)) {
4687 DPFPRINTF(PF_DEBUG_MISC,
4688 ("pf: ICMP error message too short "
4692 pd2.proto = h2_6.ip6_nxt;
4693 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4694 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4696 off2 = ipoff2 + sizeof(h2_6);
4698 switch (pd2.proto) {
4699 case IPPROTO_FRAGMENT:
4701 * ICMPv6 error messages for
4702 * non-first fragments
4704 REASON_SET(reason, PFRES_FRAG);
4707 case IPPROTO_HOPOPTS:
4708 case IPPROTO_ROUTING:
4709 case IPPROTO_DSTOPTS: {
4710 /* get next header and header length */
4711 struct ip6_ext opt6;
4713 if (!pf_pull_hdr(m, off2, &opt6,
4714 sizeof(opt6), NULL, reason,
4716 DPFPRINTF(PF_DEBUG_MISC,
4717 ("pf: ICMPv6 short opt\n"));
4720 if (pd2.proto == IPPROTO_AH)
4721 off2 += (opt6.ip6e_len + 2) * 4;
4723 off2 += (opt6.ip6e_len + 1) * 8;
4724 pd2.proto = opt6.ip6e_nxt;
4725 /* goto the next header */
4732 } while (!terminal);
4737 switch (pd2.proto) {
4741 struct pf_state_peer *src, *dst;
4746 * Only the first 8 bytes of the TCP header can be
4747 * expected. Don't access any TCP header fields after
4748 * th_seq, an ackskew test is not possible.
4750 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4752 DPFPRINTF(PF_DEBUG_MISC,
4753 ("pf: ICMP error message too short "
4759 key.proto = IPPROTO_TCP;
4760 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4761 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4762 key.port[pd2.sidx] = th.th_sport;
4763 key.port[pd2.didx] = th.th_dport;
4765 STATE_LOOKUP(kif, &key, direction, *state, pd);
4767 if (direction == (*state)->direction) {
4768 src = &(*state)->dst;
4769 dst = &(*state)->src;
4771 src = &(*state)->src;
4772 dst = &(*state)->dst;
4775 if (src->wscale && dst->wscale)
4776 dws = dst->wscale & PF_WSCALE_MASK;
4780 /* Demodulate sequence number */
4781 seq = ntohl(th.th_seq) - src->seqdiff;
4783 pf_change_a(&th.th_seq, icmpsum,
4788 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4789 (!SEQ_GEQ(src->seqhi, seq) ||
4790 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4791 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4792 printf("pf: BAD ICMP %d:%d ",
4793 icmptype, pd->hdr.icmp->icmp_code);
4794 pf_print_host(pd->src, 0, pd->af);
4796 pf_print_host(pd->dst, 0, pd->af);
4798 pf_print_state(*state);
4799 printf(" seq=%u\n", seq);
4801 REASON_SET(reason, PFRES_BADSTATE);
4804 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4805 printf("pf: OK ICMP %d:%d ",
4806 icmptype, pd->hdr.icmp->icmp_code);
4807 pf_print_host(pd->src, 0, pd->af);
4809 pf_print_host(pd->dst, 0, pd->af);
4811 pf_print_state(*state);
4812 printf(" seq=%u\n", seq);
4816 /* translate source/destination address, if necessary */
4817 if ((*state)->key[PF_SK_WIRE] !=
4818 (*state)->key[PF_SK_STACK]) {
4819 struct pf_state_key *nk =
4820 (*state)->key[pd->didx];
4822 if (PF_ANEQ(pd2.src,
4823 &nk->addr[pd2.sidx], pd2.af) ||
4824 nk->port[pd2.sidx] != th.th_sport)
4825 pf_change_icmp(pd2.src, &th.th_sport,
4826 daddr, &nk->addr[pd2.sidx],
4827 nk->port[pd2.sidx], NULL,
4828 pd2.ip_sum, icmpsum,
4829 pd->ip_sum, 0, pd2.af);
4831 if (PF_ANEQ(pd2.dst,
4832 &nk->addr[pd2.didx], pd2.af) ||
4833 nk->port[pd2.didx] != th.th_dport)
4834 pf_change_icmp(pd2.dst, &th.th_dport,
4835 saddr, &nk->addr[pd2.didx],
4836 nk->port[pd2.didx], NULL,
4837 pd2.ip_sum, icmpsum,
4838 pd->ip_sum, 0, pd2.af);
4846 m_copyback(m, off, ICMP_MINLEN,
4847 (caddr_t )pd->hdr.icmp);
4848 m_copyback(m, ipoff2, sizeof(h2),
4855 sizeof(struct icmp6_hdr),
4856 (caddr_t )pd->hdr.icmp6);
4857 m_copyback(m, ipoff2, sizeof(h2_6),
4862 m_copyback(m, off2, 8, (caddr_t)&th);
4871 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4872 NULL, reason, pd2.af)) {
4873 DPFPRINTF(PF_DEBUG_MISC,
4874 ("pf: ICMP error message too short "
4880 key.proto = IPPROTO_UDP;
4881 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4882 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4883 key.port[pd2.sidx] = uh.uh_sport;
4884 key.port[pd2.didx] = uh.uh_dport;
4886 STATE_LOOKUP(kif, &key, direction, *state, pd);
4888 /* translate source/destination address, if necessary */
4889 if ((*state)->key[PF_SK_WIRE] !=
4890 (*state)->key[PF_SK_STACK]) {
4891 struct pf_state_key *nk =
4892 (*state)->key[pd->didx];
4894 if (PF_ANEQ(pd2.src,
4895 &nk->addr[pd2.sidx], pd2.af) ||
4896 nk->port[pd2.sidx] != uh.uh_sport)
4897 pf_change_icmp(pd2.src, &uh.uh_sport,
4898 daddr, &nk->addr[pd2.sidx],
4899 nk->port[pd2.sidx], &uh.uh_sum,
4900 pd2.ip_sum, icmpsum,
4901 pd->ip_sum, 1, pd2.af);
4903 if (PF_ANEQ(pd2.dst,
4904 &nk->addr[pd2.didx], pd2.af) ||
4905 nk->port[pd2.didx] != uh.uh_dport)
4906 pf_change_icmp(pd2.dst, &uh.uh_dport,
4907 saddr, &nk->addr[pd2.didx],
4908 nk->port[pd2.didx], &uh.uh_sum,
4909 pd2.ip_sum, icmpsum,
4910 pd->ip_sum, 1, pd2.af);
4915 m_copyback(m, off, ICMP_MINLEN,
4916 (caddr_t )pd->hdr.icmp);
4917 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4923 sizeof(struct icmp6_hdr),
4924 (caddr_t )pd->hdr.icmp6);
4925 m_copyback(m, ipoff2, sizeof(h2_6),
4930 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4936 case IPPROTO_ICMP: {
4939 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4940 NULL, reason, pd2.af)) {
4941 DPFPRINTF(PF_DEBUG_MISC,
4942 ("pf: ICMP error message too short i"
4948 key.proto = IPPROTO_ICMP;
4949 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4950 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4951 key.port[0] = key.port[1] = iih.icmp_id;
4953 STATE_LOOKUP(kif, &key, direction, *state, pd);
4955 /* translate source/destination address, if necessary */
4956 if ((*state)->key[PF_SK_WIRE] !=
4957 (*state)->key[PF_SK_STACK]) {
4958 struct pf_state_key *nk =
4959 (*state)->key[pd->didx];
4961 if (PF_ANEQ(pd2.src,
4962 &nk->addr[pd2.sidx], pd2.af) ||
4963 nk->port[pd2.sidx] != iih.icmp_id)
4964 pf_change_icmp(pd2.src, &iih.icmp_id,
4965 daddr, &nk->addr[pd2.sidx],
4966 nk->port[pd2.sidx], NULL,
4967 pd2.ip_sum, icmpsum,
4968 pd->ip_sum, 0, AF_INET);
4970 if (PF_ANEQ(pd2.dst,
4971 &nk->addr[pd2.didx], pd2.af) ||
4972 nk->port[pd2.didx] != iih.icmp_id)
4973 pf_change_icmp(pd2.dst, &iih.icmp_id,
4974 saddr, &nk->addr[pd2.didx],
4975 nk->port[pd2.didx], NULL,
4976 pd2.ip_sum, icmpsum,
4977 pd->ip_sum, 0, AF_INET);
4979 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4980 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4981 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4988 case IPPROTO_ICMPV6: {
4989 struct icmp6_hdr iih;
4991 if (!pf_pull_hdr(m, off2, &iih,
4992 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4993 DPFPRINTF(PF_DEBUG_MISC,
4994 ("pf: ICMP error message too short "
5000 key.proto = IPPROTO_ICMPV6;
5001 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5002 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5003 key.port[0] = key.port[1] = iih.icmp6_id;
5005 STATE_LOOKUP(kif, &key, direction, *state, pd);
5007 /* translate source/destination address, if necessary */
5008 if ((*state)->key[PF_SK_WIRE] !=
5009 (*state)->key[PF_SK_STACK]) {
5010 struct pf_state_key *nk =
5011 (*state)->key[pd->didx];
5013 if (PF_ANEQ(pd2.src,
5014 &nk->addr[pd2.sidx], pd2.af) ||
5015 nk->port[pd2.sidx] != iih.icmp6_id)
5016 pf_change_icmp(pd2.src, &iih.icmp6_id,
5017 daddr, &nk->addr[pd2.sidx],
5018 nk->port[pd2.sidx], NULL,
5019 pd2.ip_sum, icmpsum,
5020 pd->ip_sum, 0, AF_INET6);
5022 if (PF_ANEQ(pd2.dst,
5023 &nk->addr[pd2.didx], pd2.af) ||
5024 nk->port[pd2.didx] != iih.icmp6_id)
5025 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5026 saddr, &nk->addr[pd2.didx],
5027 nk->port[pd2.didx], NULL,
5028 pd2.ip_sum, icmpsum,
5029 pd->ip_sum, 0, AF_INET6);
5031 m_copyback(m, off, sizeof(struct icmp6_hdr),
5032 (caddr_t)pd->hdr.icmp6);
5033 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5034 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5043 key.proto = pd2.proto;
5044 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5045 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5046 key.port[0] = key.port[1] = 0;
5048 STATE_LOOKUP(kif, &key, direction, *state, pd);
5050 /* translate source/destination address, if necessary */
5051 if ((*state)->key[PF_SK_WIRE] !=
5052 (*state)->key[PF_SK_STACK]) {
5053 struct pf_state_key *nk =
5054 (*state)->key[pd->didx];
5056 if (PF_ANEQ(pd2.src,
5057 &nk->addr[pd2.sidx], pd2.af))
5058 pf_change_icmp(pd2.src, NULL, daddr,
5059 &nk->addr[pd2.sidx], 0, NULL,
5060 pd2.ip_sum, icmpsum,
5061 pd->ip_sum, 0, pd2.af);
5063 if (PF_ANEQ(pd2.dst,
5064 &nk->addr[pd2.didx], pd2.af))
5065 pf_change_icmp(pd2.dst, NULL, saddr,
5066 &nk->addr[pd2.didx], 0, NULL,
5067 pd2.ip_sum, icmpsum,
5068 pd->ip_sum, 0, pd2.af);
5073 m_copyback(m, off, ICMP_MINLEN,
5074 (caddr_t)pd->hdr.icmp);
5075 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5081 sizeof(struct icmp6_hdr),
5082 (caddr_t )pd->hdr.icmp6);
5083 m_copyback(m, ipoff2, sizeof(h2_6),
5097 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5098 struct mbuf *m, struct pf_pdesc *pd)
5100 struct pf_state_peer *src, *dst;
5101 struct pf_state_key_cmp key;
5103 bzero(&key, sizeof(key));
5105 key.proto = pd->proto;
5106 if (direction == PF_IN) {
5107 PF_ACPY(&key.addr[0], pd->src, key.af);
5108 PF_ACPY(&key.addr[1], pd->dst, key.af);
5109 key.port[0] = key.port[1] = 0;
5111 PF_ACPY(&key.addr[1], pd->src, key.af);
5112 PF_ACPY(&key.addr[0], pd->dst, key.af);
5113 key.port[1] = key.port[0] = 0;
5116 STATE_LOOKUP(kif, &key, direction, *state, pd);
5118 if (direction == (*state)->direction) {
5119 src = &(*state)->src;
5120 dst = &(*state)->dst;
5122 src = &(*state)->dst;
5123 dst = &(*state)->src;
5127 if (src->state < PFOTHERS_SINGLE)
5128 src->state = PFOTHERS_SINGLE;
5129 if (dst->state == PFOTHERS_SINGLE)
5130 dst->state = PFOTHERS_MULTIPLE;
5132 /* update expire time */
5133 (*state)->expire = time_uptime;
5134 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5135 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5137 (*state)->timeout = PFTM_OTHER_SINGLE;
5139 /* translate source/destination address, if necessary */
5140 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5141 struct pf_state_key *nk = (*state)->key[pd->didx];
5143 KASSERT(nk, ("%s: nk is null", __func__));
5144 KASSERT(pd, ("%s: pd is null", __func__));
5145 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5146 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5150 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5151 pf_change_a(&pd->src->v4.s_addr,
5153 nk->addr[pd->sidx].v4.s_addr,
5157 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5158 pf_change_a(&pd->dst->v4.s_addr,
5160 nk->addr[pd->didx].v4.s_addr,
5167 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5168 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5170 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5171 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5179 * ipoff and off are measured from the start of the mbuf chain.
5180 * h must be at "ipoff" on the mbuf chain.
5183 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5184 u_short *actionp, u_short *reasonp, sa_family_t af)
5189 struct ip *h = mtod(m, struct ip *);
5190 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5194 ACTION_SET(actionp, PF_PASS);
5196 ACTION_SET(actionp, PF_DROP);
5197 REASON_SET(reasonp, PFRES_FRAG);
5201 if (m->m_pkthdr.len < off + len ||
5202 ntohs(h->ip_len) < off + len) {
5203 ACTION_SET(actionp, PF_DROP);
5204 REASON_SET(reasonp, PFRES_SHORT);
5212 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5214 if (m->m_pkthdr.len < off + len ||
5215 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5216 (unsigned)(off + len)) {
5217 ACTION_SET(actionp, PF_DROP);
5218 REASON_SET(reasonp, PFRES_SHORT);
5225 m_copydata(m, off, len, p);
5230 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5234 struct radix_node_head *rnh;
5236 struct sockaddr_in *dst;
5240 struct sockaddr_in6 *dst6;
5241 struct route_in6 ro;
5245 struct radix_node *rn;
5251 /* XXX: stick to table 0 for now */
5252 rnh = rt_tables_get_rnh(0, af);
5253 if (rnh != NULL && rn_mpath_capable(rnh))
5256 bzero(&ro, sizeof(ro));
5259 dst = satosin(&ro.ro_dst);
5260 dst->sin_family = AF_INET;
5261 dst->sin_len = sizeof(*dst);
5262 dst->sin_addr = addr->v4;
5267 * Skip check for addresses with embedded interface scope,
5268 * as they would always match anyway.
5270 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5272 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5273 dst6->sin6_family = AF_INET6;
5274 dst6->sin6_len = sizeof(*dst6);
5275 dst6->sin6_addr = addr->v6;
5282 /* Skip checks for ipsec interfaces */
5283 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5289 in6_rtalloc_ign(&ro, 0, rtableid);
5294 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5298 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5302 if (ro.ro_rt != NULL) {
5303 /* No interface given, this is a no-route check */
5307 if (kif->pfik_ifp == NULL) {
5312 /* Perform uRPF check if passed input interface */
5314 rn = (struct radix_node *)ro.ro_rt;
5316 rt = (struct rtentry *)rn;
5319 if (kif->pfik_ifp == ifp)
5322 rn = rn_mpath_next(rn);
5324 } while (check_mpath == 1 && rn != NULL && ret == 0);
5328 if (ro.ro_rt != NULL)
5335 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5336 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5338 struct mbuf *m0, *m1;
5339 struct sockaddr_in dst;
5341 struct ifnet *ifp = NULL;
5342 struct pf_addr naddr;
5343 struct pf_src_node *sn = NULL;
5345 uint16_t ip_len, ip_off;
5347 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5348 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5351 if ((pd->pf_mtag == NULL &&
5352 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5353 pd->pf_mtag->routed++ > 3) {
5359 if (r->rt == PF_DUPTO) {
5360 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5366 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5374 ip = mtod(m0, struct ip *);
5376 bzero(&dst, sizeof(dst));
5377 dst.sin_family = AF_INET;
5378 dst.sin_len = sizeof(dst);
5379 dst.sin_addr = ip->ip_dst;
5381 if (r->rt == PF_FASTROUTE) {
5386 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5388 KMOD_IPSTAT_INC(ips_noroute);
5389 error = EHOSTUNREACH;
5394 counter_u64_add(rt->rt_pksent, 1);
5396 if (rt->rt_flags & RTF_GATEWAY)
5397 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5400 if (TAILQ_EMPTY(&r->rpool.list)) {
5401 DPFPRINTF(PF_DEBUG_URGENT,
5402 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5406 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5408 if (!PF_AZERO(&naddr, AF_INET))
5409 dst.sin_addr.s_addr = naddr.v4.s_addr;
5410 ifp = r->rpool.cur->kif ?
5411 r->rpool.cur->kif->pfik_ifp : NULL;
5413 if (!PF_AZERO(&s->rt_addr, AF_INET))
5414 dst.sin_addr.s_addr =
5415 s->rt_addr.v4.s_addr;
5416 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5424 if (pf_test(PF_OUT, ifp, &m0, inp) != PF_PASS)
5426 else if (m0 == NULL)
5428 if (m0->m_len < sizeof(struct ip)) {
5429 DPFPRINTF(PF_DEBUG_URGENT,
5430 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5433 ip = mtod(m0, struct ip *);
5436 if (ifp->if_flags & IFF_LOOPBACK)
5437 m0->m_flags |= M_SKIP_FIREWALL;
5439 ip_len = ntohs(ip->ip_len);
5440 ip_off = ntohs(ip->ip_off);
5442 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5443 m0->m_pkthdr.csum_flags |= CSUM_IP;
5444 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5445 in_delayed_cksum(m0);
5446 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5449 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5450 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5451 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5456 * If small enough for interface, or the interface will take
5457 * care of the fragmentation for us, we can just send directly.
5459 if (ip_len <= ifp->if_mtu ||
5460 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5461 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5463 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5464 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5465 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5467 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5468 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5472 /* Balk when DF bit is set or the interface didn't support TSO. */
5473 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5475 KMOD_IPSTAT_INC(ips_cantfrag);
5476 if (r->rt != PF_DUPTO) {
5477 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5484 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5488 for (; m0; m0 = m1) {
5490 m0->m_nextpkt = NULL;
5492 m_clrprotoflags(m0);
5493 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5499 KMOD_IPSTAT_INC(ips_fragmented);
5502 if (r->rt != PF_DUPTO)
5517 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5518 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5521 struct sockaddr_in6 dst;
5522 struct ip6_hdr *ip6;
5523 struct ifnet *ifp = NULL;
5524 struct pf_addr naddr;
5525 struct pf_src_node *sn = NULL;
5527 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5528 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5531 if ((pd->pf_mtag == NULL &&
5532 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5533 pd->pf_mtag->routed++ > 3) {
5539 if (r->rt == PF_DUPTO) {
5540 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5546 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5554 ip6 = mtod(m0, struct ip6_hdr *);
5556 bzero(&dst, sizeof(dst));
5557 dst.sin6_family = AF_INET6;
5558 dst.sin6_len = sizeof(dst);
5559 dst.sin6_addr = ip6->ip6_dst;
5561 /* Cheat. XXX why only in the v6 case??? */
5562 if (r->rt == PF_FASTROUTE) {
5565 m0->m_flags |= M_SKIP_FIREWALL;
5566 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5571 if (TAILQ_EMPTY(&r->rpool.list)) {
5572 DPFPRINTF(PF_DEBUG_URGENT,
5573 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5577 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5579 if (!PF_AZERO(&naddr, AF_INET6))
5580 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5582 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5584 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5585 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5586 &s->rt_addr, AF_INET6);
5587 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5597 if (pf_test6(PF_FWD, ifp, &m0, inp) != PF_PASS)
5599 else if (m0 == NULL)
5601 if (m0->m_len < sizeof(struct ip6_hdr)) {
5602 DPFPRINTF(PF_DEBUG_URGENT,
5603 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5607 ip6 = mtod(m0, struct ip6_hdr *);
5610 if (ifp->if_flags & IFF_LOOPBACK)
5611 m0->m_flags |= M_SKIP_FIREWALL;
5613 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5614 ~ifp->if_hwassist) {
5615 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5616 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5617 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5621 * If the packet is too large for the outgoing interface,
5622 * send back an icmp6 error.
5624 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5625 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5626 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5627 nd6_output(ifp, ifp, m0, &dst, NULL);
5629 in6_ifstat_inc(ifp, ifs6_in_toobig);
5630 if (r->rt != PF_DUPTO)
5631 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5637 if (r->rt != PF_DUPTO)
5651 * FreeBSD supports cksum offloads for the following drivers.
5652 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5653 * ti(4), txp(4), xl(4)
5655 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5656 * network driver performed cksum including pseudo header, need to verify
5659 * network driver performed cksum, needs to additional pseudo header
5660 * cksum computation with partial csum_data(i.e. lack of H/W support for
5661 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5663 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5664 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5666 * Also, set csum_data to 0xffff to force cksum validation.
5669 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5675 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5677 if (m->m_pkthdr.len < off + len)
5682 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5683 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5684 sum = m->m_pkthdr.csum_data;
5686 ip = mtod(m, struct ip *);
5687 sum = in_pseudo(ip->ip_src.s_addr,
5688 ip->ip_dst.s_addr, htonl((u_short)len +
5689 m->m_pkthdr.csum_data + IPPROTO_TCP));
5696 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5697 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5698 sum = m->m_pkthdr.csum_data;
5700 ip = mtod(m, struct ip *);
5701 sum = in_pseudo(ip->ip_src.s_addr,
5702 ip->ip_dst.s_addr, htonl((u_short)len +
5703 m->m_pkthdr.csum_data + IPPROTO_UDP));
5711 case IPPROTO_ICMPV6:
5721 if (p == IPPROTO_ICMP) {
5726 sum = in_cksum(m, len);
5730 if (m->m_len < sizeof(struct ip))
5732 sum = in4_cksum(m, p, off, len);
5737 if (m->m_len < sizeof(struct ip6_hdr))
5739 sum = in6_cksum(m, p, off, len);
5750 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5755 KMOD_UDPSTAT_INC(udps_badsum);
5761 KMOD_ICMPSTAT_INC(icps_checksum);
5766 case IPPROTO_ICMPV6:
5768 KMOD_ICMP6STAT_INC(icp6s_checksum);
5775 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5776 m->m_pkthdr.csum_flags |=
5777 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5778 m->m_pkthdr.csum_data = 0xffff;
5787 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5789 struct pfi_kif *kif;
5790 u_short action, reason = 0, log = 0;
5791 struct mbuf *m = *m0;
5792 struct ip *h = NULL;
5793 struct m_tag *ipfwtag;
5794 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5795 struct pf_state *s = NULL;
5796 struct pf_ruleset *ruleset = NULL;
5798 int off, dirndx, pqid = 0;
5802 if (!V_pf_status.running)
5805 memset(&pd, 0, sizeof(pd));
5807 kif = (struct pfi_kif *)ifp->if_pf_kif;
5810 DPFPRINTF(PF_DEBUG_URGENT,
5811 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5814 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5817 if (m->m_flags & M_SKIP_FIREWALL)
5820 pd.pf_mtag = pf_find_mtag(m);
5824 if (ip_divert_ptr != NULL &&
5825 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5826 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5827 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5828 if (pd.pf_mtag == NULL &&
5829 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5833 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5834 m_tag_delete(m, ipfwtag);
5836 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5837 m->m_flags |= M_FASTFWD_OURS;
5838 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5840 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5841 /* We do IP header normalization and packet reassembly here */
5845 m = *m0; /* pf_normalize messes with m0 */
5846 h = mtod(m, struct ip *);
5848 off = h->ip_hl << 2;
5849 if (off < (int)sizeof(struct ip)) {
5851 REASON_SET(&reason, PFRES_SHORT);
5856 pd.src = (struct pf_addr *)&h->ip_src;
5857 pd.dst = (struct pf_addr *)&h->ip_dst;
5858 pd.sport = pd.dport = NULL;
5859 pd.ip_sum = &h->ip_sum;
5860 pd.proto_sum = NULL;
5863 pd.sidx = (dir == PF_IN) ? 0 : 1;
5864 pd.didx = (dir == PF_IN) ? 1 : 0;
5867 pd.tot_len = ntohs(h->ip_len);
5869 /* handle fragments that didn't get reassembled by normalization */
5870 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5871 action = pf_test_fragment(&r, dir, kif, m, h,
5882 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5883 &action, &reason, AF_INET)) {
5884 log = action != PF_PASS;
5887 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5888 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5890 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5891 if (action == PF_DROP)
5893 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5895 if (action == PF_PASS) {
5896 if (pfsync_update_state_ptr != NULL)
5897 pfsync_update_state_ptr(s);
5901 } else if (s == NULL)
5902 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5911 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5912 &action, &reason, AF_INET)) {
5913 log = action != PF_PASS;
5916 if (uh.uh_dport == 0 ||
5917 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5918 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5920 REASON_SET(&reason, PFRES_SHORT);
5923 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5924 if (action == PF_PASS) {
5925 if (pfsync_update_state_ptr != NULL)
5926 pfsync_update_state_ptr(s);
5930 } else if (s == NULL)
5931 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5936 case IPPROTO_ICMP: {
5940 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5941 &action, &reason, AF_INET)) {
5942 log = action != PF_PASS;
5945 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5947 if (action == PF_PASS) {
5948 if (pfsync_update_state_ptr != NULL)
5949 pfsync_update_state_ptr(s);
5953 } else if (s == NULL)
5954 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5960 case IPPROTO_ICMPV6: {
5962 DPFPRINTF(PF_DEBUG_MISC,
5963 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5969 action = pf_test_state_other(&s, dir, kif, m, &pd);
5970 if (action == PF_PASS) {
5971 if (pfsync_update_state_ptr != NULL)
5972 pfsync_update_state_ptr(s);
5976 } else if (s == NULL)
5977 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5984 if (action == PF_PASS && h->ip_hl > 5 &&
5985 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5987 REASON_SET(&reason, PFRES_IPOPTIONS);
5989 DPFPRINTF(PF_DEBUG_MISC,
5990 ("pf: dropping packet with ip options\n"));
5993 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5995 REASON_SET(&reason, PFRES_MEMORY);
5997 if (r->rtableid >= 0)
5998 M_SETFIB(m, r->rtableid);
6001 if (action == PF_PASS && r->qid) {
6002 if (pd.pf_mtag == NULL &&
6003 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6005 REASON_SET(&reason, PFRES_MEMORY);
6008 pd.pf_mtag->qid_hash = pf_state_hash(s);
6009 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6010 pd.pf_mtag->qid = r->pqid;
6012 pd.pf_mtag->qid = r->qid;
6013 /* Add hints for ecn. */
6014 pd.pf_mtag->hdr = h;
6021 * connections redirected to loopback should not match sockets
6022 * bound specifically to loopback due to security implications,
6023 * see tcp_input() and in_pcblookup_listen().
6025 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6026 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6027 (s->nat_rule.ptr->action == PF_RDR ||
6028 s->nat_rule.ptr->action == PF_BINAT) &&
6029 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6030 m->m_flags |= M_SKIP_FIREWALL;
6032 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6033 !PACKET_LOOPED(&pd)) {
6035 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6036 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6037 if (ipfwtag != NULL) {
6038 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6039 ntohs(r->divert.port);
6040 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6045 m_tag_prepend(m, ipfwtag);
6046 if (m->m_flags & M_FASTFWD_OURS) {
6047 if (pd.pf_mtag == NULL &&
6048 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6050 REASON_SET(&reason, PFRES_MEMORY);
6052 DPFPRINTF(PF_DEBUG_MISC,
6053 ("pf: failed to allocate tag\n"));
6055 pd.pf_mtag->flags |=
6056 PF_FASTFWD_OURS_PRESENT;
6057 m->m_flags &= ~M_FASTFWD_OURS;
6060 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6065 /* XXX: ipfw has the same behaviour! */
6067 REASON_SET(&reason, PFRES_MEMORY);
6069 DPFPRINTF(PF_DEBUG_MISC,
6070 ("pf: failed to allocate divert tag\n"));
6077 if (s != NULL && s->nat_rule.ptr != NULL &&
6078 s->nat_rule.ptr->log & PF_LOG_ALL)
6079 lr = s->nat_rule.ptr;
6082 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6086 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6087 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6089 if (action == PF_PASS || r->action == PF_DROP) {
6090 dirndx = (dir == PF_OUT);
6091 r->packets[dirndx]++;
6092 r->bytes[dirndx] += pd.tot_len;
6094 a->packets[dirndx]++;
6095 a->bytes[dirndx] += pd.tot_len;
6098 if (s->nat_rule.ptr != NULL) {
6099 s->nat_rule.ptr->packets[dirndx]++;
6100 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6102 if (s->src_node != NULL) {
6103 s->src_node->packets[dirndx]++;
6104 s->src_node->bytes[dirndx] += pd.tot_len;
6106 if (s->nat_src_node != NULL) {
6107 s->nat_src_node->packets[dirndx]++;
6108 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6110 dirndx = (dir == s->direction) ? 0 : 1;
6111 s->packets[dirndx]++;
6112 s->bytes[dirndx] += pd.tot_len;
6115 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6116 if (nr != NULL && r == &V_pf_default_rule)
6118 if (tr->src.addr.type == PF_ADDR_TABLE)
6119 pfr_update_stats(tr->src.addr.p.tbl,
6120 (s == NULL) ? pd.src :
6121 &s->key[(s->direction == PF_IN)]->
6122 addr[(s->direction == PF_OUT)],
6123 pd.af, pd.tot_len, dir == PF_OUT,
6124 r->action == PF_PASS, tr->src.neg);
6125 if (tr->dst.addr.type == PF_ADDR_TABLE)
6126 pfr_update_stats(tr->dst.addr.p.tbl,
6127 (s == NULL) ? pd.dst :
6128 &s->key[(s->direction == PF_IN)]->
6129 addr[(s->direction == PF_IN)],
6130 pd.af, pd.tot_len, dir == PF_OUT,
6131 r->action == PF_PASS, tr->dst.neg);
6135 case PF_SYNPROXY_DROP:
6146 /* pf_route() returns unlocked. */
6148 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6162 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6164 struct pfi_kif *kif;
6165 u_short action, reason = 0, log = 0;
6166 struct mbuf *m = *m0, *n = NULL;
6168 struct ip6_hdr *h = NULL;
6169 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6170 struct pf_state *s = NULL;
6171 struct pf_ruleset *ruleset = NULL;
6173 int off, terminal = 0, dirndx, rh_cnt = 0;
6178 /* Detect packet forwarding.
6179 * If the input interface is different from the output interface we're
6181 * We do need to be careful about bridges. If the
6182 * net.link.bridge.pfil_bridge sysctl is set we can be filtering on a
6183 * bridge, so if the input interface is a bridge member and the output
6184 * interface is its bridge or a member of the same bridge we're not
6185 * actually forwarding but bridging.
6187 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif &&
6188 (m->m_pkthdr.rcvif->if_bridge == NULL ||
6189 (m->m_pkthdr.rcvif->if_bridge != ifp->if_softc &&
6190 m->m_pkthdr.rcvif->if_bridge != ifp->if_bridge)))
6196 if (!V_pf_status.running)
6199 memset(&pd, 0, sizeof(pd));
6200 pd.pf_mtag = pf_find_mtag(m);
6202 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6205 kif = (struct pfi_kif *)ifp->if_pf_kif;
6207 DPFPRINTF(PF_DEBUG_URGENT,
6208 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6211 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6214 if (m->m_flags & M_SKIP_FIREWALL)
6219 /* We do IP header normalization and packet reassembly here */
6220 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6224 m = *m0; /* pf_normalize messes with m0 */
6225 h = mtod(m, struct ip6_hdr *);
6229 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6230 * will do something bad, so drop the packet for now.
6232 if (htons(h->ip6_plen) == 0) {
6234 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6239 pd.src = (struct pf_addr *)&h->ip6_src;
6240 pd.dst = (struct pf_addr *)&h->ip6_dst;
6241 pd.sport = pd.dport = NULL;
6243 pd.proto_sum = NULL;
6245 pd.sidx = (dir == PF_IN) ? 0 : 1;
6246 pd.didx = (dir == PF_IN) ? 1 : 0;
6249 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6251 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6252 pd.proto = h->ip6_nxt;
6255 case IPPROTO_FRAGMENT:
6256 action = pf_test_fragment(&r, dir, kif, m, h,
6258 if (action == PF_DROP)
6259 REASON_SET(&reason, PFRES_FRAG);
6261 case IPPROTO_ROUTING: {
6262 struct ip6_rthdr rthdr;
6265 DPFPRINTF(PF_DEBUG_MISC,
6266 ("pf: IPv6 more than one rthdr\n"));
6268 REASON_SET(&reason, PFRES_IPOPTIONS);
6272 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6274 DPFPRINTF(PF_DEBUG_MISC,
6275 ("pf: IPv6 short rthdr\n"));
6277 REASON_SET(&reason, PFRES_SHORT);
6281 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6282 DPFPRINTF(PF_DEBUG_MISC,
6283 ("pf: IPv6 rthdr0\n"));
6285 REASON_SET(&reason, PFRES_IPOPTIONS);
6292 case IPPROTO_HOPOPTS:
6293 case IPPROTO_DSTOPTS: {
6294 /* get next header and header length */
6295 struct ip6_ext opt6;
6297 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6298 NULL, &reason, pd.af)) {
6299 DPFPRINTF(PF_DEBUG_MISC,
6300 ("pf: IPv6 short opt\n"));
6305 if (pd.proto == IPPROTO_AH)
6306 off += (opt6.ip6e_len + 2) * 4;
6308 off += (opt6.ip6e_len + 1) * 8;
6309 pd.proto = opt6.ip6e_nxt;
6310 /* goto the next header */
6317 } while (!terminal);
6319 /* if there's no routing header, use unmodified mbuf for checksumming */
6329 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6330 &action, &reason, AF_INET6)) {
6331 log = action != PF_PASS;
6334 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6335 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6336 if (action == PF_DROP)
6338 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6340 if (action == PF_PASS) {
6341 if (pfsync_update_state_ptr != NULL)
6342 pfsync_update_state_ptr(s);
6346 } else if (s == NULL)
6347 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6356 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6357 &action, &reason, AF_INET6)) {
6358 log = action != PF_PASS;
6361 if (uh.uh_dport == 0 ||
6362 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6363 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6365 REASON_SET(&reason, PFRES_SHORT);
6368 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6369 if (action == PF_PASS) {
6370 if (pfsync_update_state_ptr != NULL)
6371 pfsync_update_state_ptr(s);
6375 } else if (s == NULL)
6376 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6381 case IPPROTO_ICMP: {
6383 DPFPRINTF(PF_DEBUG_MISC,
6384 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6388 case IPPROTO_ICMPV6: {
6389 struct icmp6_hdr ih;
6392 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6393 &action, &reason, AF_INET6)) {
6394 log = action != PF_PASS;
6397 action = pf_test_state_icmp(&s, dir, kif,
6398 m, off, h, &pd, &reason);
6399 if (action == PF_PASS) {
6400 if (pfsync_update_state_ptr != NULL)
6401 pfsync_update_state_ptr(s);
6405 } else if (s == NULL)
6406 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6412 action = pf_test_state_other(&s, dir, kif, m, &pd);
6413 if (action == PF_PASS) {
6414 if (pfsync_update_state_ptr != NULL)
6415 pfsync_update_state_ptr(s);
6419 } else if (s == NULL)
6420 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6432 /* handle dangerous IPv6 extension headers. */
6433 if (action == PF_PASS && rh_cnt &&
6434 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6436 REASON_SET(&reason, PFRES_IPOPTIONS);
6438 DPFPRINTF(PF_DEBUG_MISC,
6439 ("pf: dropping packet with dangerous v6 headers\n"));
6442 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6444 REASON_SET(&reason, PFRES_MEMORY);
6446 if (r->rtableid >= 0)
6447 M_SETFIB(m, r->rtableid);
6450 if (action == PF_PASS && r->qid) {
6451 if (pd.pf_mtag == NULL &&
6452 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6454 REASON_SET(&reason, PFRES_MEMORY);
6457 pd.pf_mtag->qid_hash = pf_state_hash(s);
6458 if (pd.tos & IPTOS_LOWDELAY)
6459 pd.pf_mtag->qid = r->pqid;
6461 pd.pf_mtag->qid = r->qid;
6462 /* Add hints for ecn. */
6463 pd.pf_mtag->hdr = h;
6468 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6469 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6470 (s->nat_rule.ptr->action == PF_RDR ||
6471 s->nat_rule.ptr->action == PF_BINAT) &&
6472 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6473 m->m_flags |= M_SKIP_FIREWALL;
6475 /* XXX: Anybody working on it?! */
6477 printf("pf: divert(9) is not supported for IPv6\n");
6482 if (s != NULL && s->nat_rule.ptr != NULL &&
6483 s->nat_rule.ptr->log & PF_LOG_ALL)
6484 lr = s->nat_rule.ptr;
6487 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6491 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6492 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6494 if (action == PF_PASS || r->action == PF_DROP) {
6495 dirndx = (dir == PF_OUT);
6496 r->packets[dirndx]++;
6497 r->bytes[dirndx] += pd.tot_len;
6499 a->packets[dirndx]++;
6500 a->bytes[dirndx] += pd.tot_len;
6503 if (s->nat_rule.ptr != NULL) {
6504 s->nat_rule.ptr->packets[dirndx]++;
6505 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6507 if (s->src_node != NULL) {
6508 s->src_node->packets[dirndx]++;
6509 s->src_node->bytes[dirndx] += pd.tot_len;
6511 if (s->nat_src_node != NULL) {
6512 s->nat_src_node->packets[dirndx]++;
6513 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6515 dirndx = (dir == s->direction) ? 0 : 1;
6516 s->packets[dirndx]++;
6517 s->bytes[dirndx] += pd.tot_len;
6520 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6521 if (nr != NULL && r == &V_pf_default_rule)
6523 if (tr->src.addr.type == PF_ADDR_TABLE)
6524 pfr_update_stats(tr->src.addr.p.tbl,
6525 (s == NULL) ? pd.src :
6526 &s->key[(s->direction == PF_IN)]->addr[0],
6527 pd.af, pd.tot_len, dir == PF_OUT,
6528 r->action == PF_PASS, tr->src.neg);
6529 if (tr->dst.addr.type == PF_ADDR_TABLE)
6530 pfr_update_stats(tr->dst.addr.p.tbl,
6531 (s == NULL) ? pd.dst :
6532 &s->key[(s->direction == PF_IN)]->addr[1],
6533 pd.af, pd.tot_len, dir == PF_OUT,
6534 r->action == PF_PASS, tr->dst.neg);
6538 case PF_SYNPROXY_DROP:
6549 /* pf_route6() returns unlocked. */
6551 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6560 /* If reassembled packet passed, create new fragments. */
6561 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6562 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6563 action = pf_refragment6(ifp, m0, mtag);