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_var.h>
65 #include <net/if_types.h>
66 #include <net/if_vlan_var.h>
67 #include <net/route.h>
68 #include <net/radix_mpath.h>
72 #include <net/pfvar.h>
73 #include <net/if_pflog.h>
74 #include <net/if_pfsync.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/in_var.h>
78 #include <netinet/in_fib.h>
79 #include <netinet/ip.h>
80 #include <netinet/ip_fw.h>
81 #include <netinet/ip_icmp.h>
82 #include <netinet/icmp_var.h>
83 #include <netinet/ip_var.h>
84 #include <netinet/tcp.h>
85 #include <netinet/tcp_fsm.h>
86 #include <netinet/tcp_seq.h>
87 #include <netinet/tcp_timer.h>
88 #include <netinet/tcp_var.h>
89 #include <netinet/udp.h>
90 #include <netinet/udp_var.h>
92 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
95 #include <netinet/ip6.h>
96 #include <netinet/icmp6.h>
97 #include <netinet6/nd6.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/in6_pcb.h>
100 #include <netinet6/in6_fib.h>
101 #include <netinet6/scope6_var.h>
104 #include <machine/in_cksum.h>
105 #include <security/mac/mac_framework.h>
107 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
114 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
115 VNET_DEFINE(struct pf_palist, pf_pabuf);
116 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
117 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
118 VNET_DEFINE(struct pf_kstatus, pf_status);
120 VNET_DEFINE(u_int32_t, ticket_altqs_active);
121 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
122 VNET_DEFINE(int, altqs_inactive_open);
123 VNET_DEFINE(u_int32_t, ticket_pabuf);
125 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
126 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
127 VNET_DEFINE(u_char, pf_tcp_secret[16]);
128 #define V_pf_tcp_secret VNET(pf_tcp_secret)
129 VNET_DEFINE(int, pf_tcp_secret_init);
130 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
131 VNET_DEFINE(int, pf_tcp_iss_off);
132 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
133 VNET_DECLARE(int, pf_vnet_active);
134 #define V_pf_vnet_active VNET(pf_vnet_active)
137 * Queue for pf_intr() sends.
139 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
140 struct pf_send_entry {
141 STAILQ_ENTRY(pf_send_entry) pfse_next;
156 STAILQ_HEAD(pf_send_head, pf_send_entry);
157 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
158 #define V_pf_sendqueue VNET(pf_sendqueue)
160 static struct mtx pf_sendqueue_mtx;
161 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
162 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
163 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
166 * Queue for pf_overload_task() tasks.
168 struct pf_overload_entry {
169 SLIST_ENTRY(pf_overload_entry) next;
173 struct pf_rule *rule;
176 SLIST_HEAD(pf_overload_head, pf_overload_entry);
177 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
178 #define V_pf_overloadqueue VNET(pf_overloadqueue)
179 static VNET_DEFINE(struct task, pf_overloadtask);
180 #define V_pf_overloadtask VNET(pf_overloadtask)
182 static struct mtx pf_overloadqueue_mtx;
183 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
184 "pf overload/flush queue", MTX_DEF);
185 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
186 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
188 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
189 struct mtx pf_unlnkdrules_mtx;
190 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
193 static VNET_DEFINE(uma_zone_t, pf_sources_z);
194 #define V_pf_sources_z VNET(pf_sources_z)
195 uma_zone_t pf_mtag_z;
196 VNET_DEFINE(uma_zone_t, pf_state_z);
197 VNET_DEFINE(uma_zone_t, pf_state_key_z);
199 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
200 #define PFID_CPUBITS 8
201 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
202 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
203 #define PFID_MAXID (~PFID_CPUMASK)
204 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
206 static void pf_src_tree_remove_state(struct pf_state *);
207 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
209 static void pf_add_threshold(struct pf_threshold *);
210 static int pf_check_threshold(struct pf_threshold *);
212 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
213 u_int16_t *, u_int16_t *, struct pf_addr *,
214 u_int16_t, u_int8_t, sa_family_t);
215 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
216 struct tcphdr *, struct pf_state_peer *);
217 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
218 struct pf_addr *, struct pf_addr *, u_int16_t,
219 u_int16_t *, u_int16_t *, u_int16_t *,
220 u_int16_t *, u_int8_t, sa_family_t);
221 static void pf_send_tcp(struct mbuf *,
222 const struct pf_rule *, sa_family_t,
223 const struct pf_addr *, const struct pf_addr *,
224 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
225 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
226 u_int16_t, struct ifnet *);
227 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
228 sa_family_t, struct pf_rule *);
229 static void pf_detach_state(struct pf_state *);
230 static int pf_state_key_attach(struct pf_state_key *,
231 struct pf_state_key *, struct pf_state *);
232 static void pf_state_key_detach(struct pf_state *, int);
233 static int pf_state_key_ctor(void *, int, void *, int);
234 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
235 static int pf_test_rule(struct pf_rule **, struct pf_state **,
236 int, struct pfi_kif *, struct mbuf *, int,
237 struct pf_pdesc *, struct pf_rule **,
238 struct pf_ruleset **, struct inpcb *);
239 static int pf_create_state(struct pf_rule *, struct pf_rule *,
240 struct pf_rule *, struct pf_pdesc *,
241 struct pf_src_node *, struct pf_state_key *,
242 struct pf_state_key *, struct mbuf *, int,
243 u_int16_t, u_int16_t, int *, struct pfi_kif *,
244 struct pf_state **, int, u_int16_t, u_int16_t,
246 static int pf_test_fragment(struct pf_rule **, int,
247 struct pfi_kif *, struct mbuf *, void *,
248 struct pf_pdesc *, struct pf_rule **,
249 struct pf_ruleset **);
250 static int pf_tcp_track_full(struct pf_state_peer *,
251 struct pf_state_peer *, struct pf_state **,
252 struct pfi_kif *, struct mbuf *, int,
253 struct pf_pdesc *, u_short *, int *);
254 static int pf_tcp_track_sloppy(struct pf_state_peer *,
255 struct pf_state_peer *, struct pf_state **,
256 struct pf_pdesc *, u_short *);
257 static int pf_test_state_tcp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260 static int pf_test_state_udp(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, int,
262 void *, struct pf_pdesc *);
263 static int pf_test_state_icmp(struct pf_state **, int,
264 struct pfi_kif *, struct mbuf *, int,
265 void *, struct pf_pdesc *, u_short *);
266 static int pf_test_state_other(struct pf_state **, int,
267 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
268 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
270 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
272 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
274 static int pf_check_proto_cksum(struct mbuf *, int, int,
275 u_int8_t, sa_family_t);
276 static void pf_print_state_parts(struct pf_state *,
277 struct pf_state_key *, struct pf_state_key *);
278 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
279 struct pf_addr_wrap *);
280 static struct pf_state *pf_find_state(struct pfi_kif *,
281 struct pf_state_key_cmp *, u_int);
282 static int pf_src_connlimit(struct pf_state **);
283 static void pf_overload_task(void *v, int pending);
284 static int pf_insert_src_node(struct pf_src_node **,
285 struct pf_rule *, struct pf_addr *, sa_family_t);
286 static u_int pf_purge_expired_states(u_int, int);
287 static void pf_purge_unlinked_rules(void);
288 static int pf_mtag_uminit(void *, int, int);
289 static void pf_mtag_free(struct m_tag *);
291 static void pf_route(struct mbuf **, struct pf_rule *, int,
292 struct ifnet *, struct pf_state *,
293 struct pf_pdesc *, struct inpcb *);
296 static void pf_change_a6(struct pf_addr *, u_int16_t *,
297 struct pf_addr *, u_int8_t);
298 static void pf_route6(struct mbuf **, struct pf_rule *, int,
299 struct ifnet *, struct pf_state *,
300 struct pf_pdesc *, struct inpcb *);
303 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
305 extern int pf_end_threads;
307 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
309 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
310 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
312 #define STATE_LOOKUP(i, k, d, s, pd) \
314 (s) = pf_find_state((i), (k), (d)); \
317 if (PACKET_LOOPED(pd)) \
319 if ((d) == PF_OUT && \
320 (((s)->rule.ptr->rt == PF_ROUTETO && \
321 (s)->rule.ptr->direction == PF_OUT) || \
322 ((s)->rule.ptr->rt == PF_REPLYTO && \
323 (s)->rule.ptr->direction == PF_IN)) && \
324 (s)->rt_kif != NULL && \
325 (s)->rt_kif != (i)) \
329 #define BOUND_IFACE(r, k) \
330 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
332 #define STATE_INC_COUNTERS(s) \
334 counter_u64_add(s->rule.ptr->states_cur, 1); \
335 counter_u64_add(s->rule.ptr->states_tot, 1); \
336 if (s->anchor.ptr != NULL) { \
337 counter_u64_add(s->anchor.ptr->states_cur, 1); \
338 counter_u64_add(s->anchor.ptr->states_tot, 1); \
340 if (s->nat_rule.ptr != NULL) { \
341 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
342 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
346 #define STATE_DEC_COUNTERS(s) \
348 if (s->nat_rule.ptr != NULL) \
349 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
350 if (s->anchor.ptr != NULL) \
351 counter_u64_add(s->anchor.ptr->states_cur, -1); \
352 counter_u64_add(s->rule.ptr->states_cur, -1); \
355 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
356 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
357 VNET_DEFINE(struct pf_idhash *, pf_idhash);
358 VNET_DEFINE(struct pf_srchash *, pf_srchash);
360 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
363 u_long pf_srchashmask;
364 static u_long pf_hashsize;
365 static u_long pf_srchashsize;
366 u_long pf_ioctl_maxcount = 65535;
368 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
369 &pf_hashsize, 0, "Size of pf(4) states hashtable");
370 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
371 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
372 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RDTUN,
373 &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
375 VNET_DEFINE(void *, pf_swi_cookie);
377 VNET_DEFINE(uint32_t, pf_hashseed);
378 #define V_pf_hashseed VNET(pf_hashseed)
381 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
387 if (a->addr32[0] > b->addr32[0])
389 if (a->addr32[0] < b->addr32[0])
395 if (a->addr32[3] > b->addr32[3])
397 if (a->addr32[3] < b->addr32[3])
399 if (a->addr32[2] > b->addr32[2])
401 if (a->addr32[2] < b->addr32[2])
403 if (a->addr32[1] > b->addr32[1])
405 if (a->addr32[1] < b->addr32[1])
407 if (a->addr32[0] > b->addr32[0])
409 if (a->addr32[0] < b->addr32[0])
414 panic("%s: unknown address family %u", __func__, af);
419 static __inline uint32_t
420 pf_hashkey(struct pf_state_key *sk)
424 h = murmur3_32_hash32((uint32_t *)sk,
425 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
428 return (h & pf_hashmask);
431 static __inline uint32_t
432 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
438 h = murmur3_32_hash32((uint32_t *)&addr->v4,
439 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
442 h = murmur3_32_hash32((uint32_t *)&addr->v6,
443 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
446 panic("%s: unknown address family %u", __func__, af);
449 return (h & pf_srchashmask);
454 pf_state_hash(struct pf_state *s)
456 u_int32_t hv = (intptr_t)s / sizeof(*s);
458 hv ^= crc32(&s->src, sizeof(s->src));
459 hv ^= crc32(&s->dst, sizeof(s->dst));
468 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
473 dst->addr32[0] = src->addr32[0];
477 dst->addr32[0] = src->addr32[0];
478 dst->addr32[1] = src->addr32[1];
479 dst->addr32[2] = src->addr32[2];
480 dst->addr32[3] = src->addr32[3];
487 pf_init_threshold(struct pf_threshold *threshold,
488 u_int32_t limit, u_int32_t seconds)
490 threshold->limit = limit * PF_THRESHOLD_MULT;
491 threshold->seconds = seconds;
492 threshold->count = 0;
493 threshold->last = time_uptime;
497 pf_add_threshold(struct pf_threshold *threshold)
499 u_int32_t t = time_uptime, diff = t - threshold->last;
501 if (diff >= threshold->seconds)
502 threshold->count = 0;
504 threshold->count -= threshold->count * diff /
506 threshold->count += PF_THRESHOLD_MULT;
511 pf_check_threshold(struct pf_threshold *threshold)
513 return (threshold->count > threshold->limit);
517 pf_src_connlimit(struct pf_state **state)
519 struct pf_overload_entry *pfoe;
522 PF_STATE_LOCK_ASSERT(*state);
524 (*state)->src_node->conn++;
525 (*state)->src.tcp_est = 1;
526 pf_add_threshold(&(*state)->src_node->conn_rate);
528 if ((*state)->rule.ptr->max_src_conn &&
529 (*state)->rule.ptr->max_src_conn <
530 (*state)->src_node->conn) {
531 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
535 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
536 pf_check_threshold(&(*state)->src_node->conn_rate)) {
537 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
544 /* Kill this state. */
545 (*state)->timeout = PFTM_PURGE;
546 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
548 if ((*state)->rule.ptr->overload_tbl == NULL)
551 /* Schedule overloading and flushing task. */
552 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
554 return (1); /* too bad :( */
556 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
557 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
558 pfoe->rule = (*state)->rule.ptr;
559 pfoe->dir = (*state)->direction;
561 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
562 PF_OVERLOADQ_UNLOCK();
563 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
569 pf_overload_task(void *v, int pending)
571 struct pf_overload_head queue;
573 struct pf_overload_entry *pfoe, *pfoe1;
576 CURVNET_SET((struct vnet *)v);
579 queue = V_pf_overloadqueue;
580 SLIST_INIT(&V_pf_overloadqueue);
581 PF_OVERLOADQ_UNLOCK();
583 bzero(&p, sizeof(p));
584 SLIST_FOREACH(pfoe, &queue, next) {
585 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
586 if (V_pf_status.debug >= PF_DEBUG_MISC) {
587 printf("%s: blocking address ", __func__);
588 pf_print_host(&pfoe->addr, 0, pfoe->af);
592 p.pfra_af = pfoe->af;
597 p.pfra_ip4addr = pfoe->addr.v4;
603 p.pfra_ip6addr = pfoe->addr.v6;
609 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
614 * Remove those entries, that don't need flushing.
616 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
617 if (pfoe->rule->flush == 0) {
618 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
619 free(pfoe, M_PFTEMP);
622 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
624 /* If nothing to flush, return. */
625 if (SLIST_EMPTY(&queue)) {
630 for (int i = 0; i <= pf_hashmask; i++) {
631 struct pf_idhash *ih = &V_pf_idhash[i];
632 struct pf_state_key *sk;
636 LIST_FOREACH(s, &ih->states, entry) {
637 sk = s->key[PF_SK_WIRE];
638 SLIST_FOREACH(pfoe, &queue, next)
639 if (sk->af == pfoe->af &&
640 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
641 pfoe->rule == s->rule.ptr) &&
642 ((pfoe->dir == PF_OUT &&
643 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
644 (pfoe->dir == PF_IN &&
645 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
646 s->timeout = PFTM_PURGE;
647 s->src.state = s->dst.state = TCPS_CLOSED;
651 PF_HASHROW_UNLOCK(ih);
653 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
654 free(pfoe, M_PFTEMP);
655 if (V_pf_status.debug >= PF_DEBUG_MISC)
656 printf("%s: %u states killed", __func__, killed);
662 * Can return locked on failure, so that we can consistently
663 * allocate and insert a new one.
666 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
669 struct pf_srchash *sh;
670 struct pf_src_node *n;
672 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
674 sh = &V_pf_srchash[pf_hashsrc(src, af)];
676 LIST_FOREACH(n, &sh->nodes, entry)
677 if (n->rule.ptr == rule && n->af == af &&
678 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
679 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
683 PF_HASHROW_UNLOCK(sh);
684 } else if (returnlocked == 0)
685 PF_HASHROW_UNLOCK(sh);
691 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
692 struct pf_addr *src, sa_family_t af)
695 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
696 rule->rpool.opts & PF_POOL_STICKYADDR),
697 ("%s for non-tracking rule %p", __func__, rule));
700 *sn = pf_find_src_node(src, rule, af, 1);
703 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
705 PF_HASHROW_ASSERT(sh);
707 if (!rule->max_src_nodes ||
708 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
709 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
711 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
714 PF_HASHROW_UNLOCK(sh);
718 pf_init_threshold(&(*sn)->conn_rate,
719 rule->max_src_conn_rate.limit,
720 rule->max_src_conn_rate.seconds);
723 (*sn)->rule.ptr = rule;
724 PF_ACPY(&(*sn)->addr, src, af);
725 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
726 (*sn)->creation = time_uptime;
727 (*sn)->ruletype = rule->action;
729 if ((*sn)->rule.ptr != NULL)
730 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
731 PF_HASHROW_UNLOCK(sh);
732 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
734 if (rule->max_src_states &&
735 (*sn)->states >= rule->max_src_states) {
736 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
745 pf_unlink_src_node(struct pf_src_node *src)
748 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
749 LIST_REMOVE(src, entry);
751 counter_u64_add(src->rule.ptr->src_nodes, -1);
755 pf_free_src_nodes(struct pf_src_node_list *head)
757 struct pf_src_node *sn, *tmp;
760 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
761 uma_zfree(V_pf_sources_z, sn);
765 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
774 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
775 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
779 /* Per-vnet data storage structures initialization. */
783 struct pf_keyhash *kh;
784 struct pf_idhash *ih;
785 struct pf_srchash *sh;
788 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
789 pf_hashsize = PF_HASHSIZ;
790 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
791 pf_srchashsize = PF_SRCHASHSIZ;
793 V_pf_hashseed = arc4random();
795 /* States and state keys storage. */
796 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
797 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
798 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
799 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
800 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
802 V_pf_state_key_z = uma_zcreate("pf state keys",
803 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
806 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
807 M_PFHASH, M_NOWAIT | M_ZERO);
808 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
809 M_PFHASH, M_NOWAIT | M_ZERO);
810 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
811 printf("pf: Unable to allocate memory for "
812 "state_hashsize %lu.\n", pf_hashsize);
814 free(V_pf_keyhash, M_PFHASH);
815 free(V_pf_idhash, M_PFHASH);
817 pf_hashsize = PF_HASHSIZ;
818 V_pf_keyhash = mallocarray(pf_hashsize,
819 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
820 V_pf_idhash = mallocarray(pf_hashsize,
821 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
824 pf_hashmask = pf_hashsize - 1;
825 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
827 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
828 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
832 V_pf_sources_z = uma_zcreate("pf source nodes",
833 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
835 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
836 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
837 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
839 V_pf_srchash = mallocarray(pf_srchashsize,
840 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
841 if (V_pf_srchash == NULL) {
842 printf("pf: Unable to allocate memory for "
843 "source_hashsize %lu.\n", pf_srchashsize);
845 pf_srchashsize = PF_SRCHASHSIZ;
846 V_pf_srchash = mallocarray(pf_srchashsize,
847 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
850 pf_srchashmask = pf_srchashsize - 1;
851 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
852 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
855 TAILQ_INIT(&V_pf_altqs[0]);
856 TAILQ_INIT(&V_pf_altqs[1]);
857 TAILQ_INIT(&V_pf_pabuf);
858 V_pf_altqs_active = &V_pf_altqs[0];
859 V_pf_altqs_inactive = &V_pf_altqs[1];
861 /* Send & overload+flush queues. */
862 STAILQ_INIT(&V_pf_sendqueue);
863 SLIST_INIT(&V_pf_overloadqueue);
864 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
866 /* Unlinked, but may be referenced rules. */
867 TAILQ_INIT(&V_pf_unlinked_rules);
874 uma_zdestroy(pf_mtag_z);
880 struct pf_keyhash *kh;
881 struct pf_idhash *ih;
882 struct pf_srchash *sh;
883 struct pf_send_entry *pfse, *next;
886 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
888 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
890 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
892 mtx_destroy(&kh->lock);
893 mtx_destroy(&ih->lock);
895 free(V_pf_keyhash, M_PFHASH);
896 free(V_pf_idhash, M_PFHASH);
898 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
899 KASSERT(LIST_EMPTY(&sh->nodes),
900 ("%s: source node hash not empty", __func__));
901 mtx_destroy(&sh->lock);
903 free(V_pf_srchash, M_PFHASH);
905 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
906 m_freem(pfse->pfse_m);
907 free(pfse, M_PFTEMP);
910 uma_zdestroy(V_pf_sources_z);
911 uma_zdestroy(V_pf_state_z);
912 uma_zdestroy(V_pf_state_key_z);
916 pf_mtag_uminit(void *mem, int size, int how)
920 t = (struct m_tag *)mem;
921 t->m_tag_cookie = MTAG_ABI_COMPAT;
922 t->m_tag_id = PACKET_TAG_PF;
923 t->m_tag_len = sizeof(struct pf_mtag);
924 t->m_tag_free = pf_mtag_free;
930 pf_mtag_free(struct m_tag *t)
933 uma_zfree(pf_mtag_z, t);
937 pf_get_mtag(struct mbuf *m)
941 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
942 return ((struct pf_mtag *)(mtag + 1));
944 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
947 bzero(mtag + 1, sizeof(struct pf_mtag));
948 m_tag_prepend(m, mtag);
950 return ((struct pf_mtag *)(mtag + 1));
954 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
957 struct pf_keyhash *khs, *khw, *kh;
958 struct pf_state_key *sk, *cur;
959 struct pf_state *si, *olds = NULL;
962 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
963 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
964 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
967 * We need to lock hash slots of both keys. To avoid deadlock
968 * we always lock the slot with lower address first. Unlock order
971 * We also need to lock ID hash slot before dropping key
972 * locks. On success we return with ID hash slot locked.
976 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
977 PF_HASHROW_LOCK(khs);
979 khs = &V_pf_keyhash[pf_hashkey(sks)];
980 khw = &V_pf_keyhash[pf_hashkey(skw)];
982 PF_HASHROW_LOCK(khs);
983 } else if (khs < khw) {
984 PF_HASHROW_LOCK(khs);
985 PF_HASHROW_LOCK(khw);
987 PF_HASHROW_LOCK(khw);
988 PF_HASHROW_LOCK(khs);
992 #define KEYS_UNLOCK() do { \
994 PF_HASHROW_UNLOCK(khs); \
995 PF_HASHROW_UNLOCK(khw); \
997 PF_HASHROW_UNLOCK(khs); \
1001 * First run: start with wire key.
1008 LIST_FOREACH(cur, &kh->keys, entry)
1009 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1013 /* Key exists. Check for same kif, if none, add to key. */
1014 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1015 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1017 PF_HASHROW_LOCK(ih);
1018 if (si->kif == s->kif &&
1019 si->direction == s->direction) {
1020 if (sk->proto == IPPROTO_TCP &&
1021 si->src.state >= TCPS_FIN_WAIT_2 &&
1022 si->dst.state >= TCPS_FIN_WAIT_2) {
1024 * New state matches an old >FIN_WAIT_2
1025 * state. We can't drop key hash locks,
1026 * thus we can't unlink it properly.
1028 * As a workaround we drop it into
1029 * TCPS_CLOSED state, schedule purge
1030 * ASAP and push it into the very end
1031 * of the slot TAILQ, so that it won't
1032 * conflict with our new state.
1034 si->src.state = si->dst.state =
1036 si->timeout = PFTM_PURGE;
1039 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1040 printf("pf: %s key attach "
1042 (idx == PF_SK_WIRE) ?
1045 pf_print_state_parts(s,
1046 (idx == PF_SK_WIRE) ?
1048 (idx == PF_SK_STACK) ?
1050 printf(", existing: ");
1051 pf_print_state_parts(si,
1052 (idx == PF_SK_WIRE) ?
1054 (idx == PF_SK_STACK) ?
1058 PF_HASHROW_UNLOCK(ih);
1060 uma_zfree(V_pf_state_key_z, sk);
1061 if (idx == PF_SK_STACK)
1063 return (EEXIST); /* collision! */
1066 PF_HASHROW_UNLOCK(ih);
1068 uma_zfree(V_pf_state_key_z, sk);
1071 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1076 /* List is sorted, if-bound states before floating. */
1077 if (s->kif == V_pfi_all)
1078 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1080 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1083 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1084 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1090 * Attach done. See how should we (or should not?)
1091 * attach a second key.
1094 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1098 } else if (sks != NULL) {
1100 * Continue attaching with stack key.
1112 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1113 ("%s failure", __func__));
1120 pf_detach_state(struct pf_state *s)
1122 struct pf_state_key *sks = s->key[PF_SK_STACK];
1123 struct pf_keyhash *kh;
1126 kh = &V_pf_keyhash[pf_hashkey(sks)];
1127 PF_HASHROW_LOCK(kh);
1128 if (s->key[PF_SK_STACK] != NULL)
1129 pf_state_key_detach(s, PF_SK_STACK);
1131 * If both point to same key, then we are done.
1133 if (sks == s->key[PF_SK_WIRE]) {
1134 pf_state_key_detach(s, PF_SK_WIRE);
1135 PF_HASHROW_UNLOCK(kh);
1138 PF_HASHROW_UNLOCK(kh);
1141 if (s->key[PF_SK_WIRE] != NULL) {
1142 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1143 PF_HASHROW_LOCK(kh);
1144 if (s->key[PF_SK_WIRE] != NULL)
1145 pf_state_key_detach(s, PF_SK_WIRE);
1146 PF_HASHROW_UNLOCK(kh);
1151 pf_state_key_detach(struct pf_state *s, int idx)
1153 struct pf_state_key *sk = s->key[idx];
1155 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1157 PF_HASHROW_ASSERT(kh);
1159 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1162 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1163 LIST_REMOVE(sk, entry);
1164 uma_zfree(V_pf_state_key_z, sk);
1169 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1171 struct pf_state_key *sk = mem;
1173 bzero(sk, sizeof(struct pf_state_key_cmp));
1174 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1175 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1180 struct pf_state_key *
1181 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1182 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1184 struct pf_state_key *sk;
1186 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1190 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1191 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1192 sk->port[pd->sidx] = sport;
1193 sk->port[pd->didx] = dport;
1194 sk->proto = pd->proto;
1200 struct pf_state_key *
1201 pf_state_key_clone(struct pf_state_key *orig)
1203 struct pf_state_key *sk;
1205 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1209 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1215 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1216 struct pf_state_key *sks, struct pf_state *s)
1218 struct pf_idhash *ih;
1219 struct pf_state *cur;
1222 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1223 ("%s: sks not pristine", __func__));
1224 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1225 ("%s: skw not pristine", __func__));
1226 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1230 if (s->id == 0 && s->creatorid == 0) {
1231 /* XXX: should be atomic, but probability of collision low */
1232 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1233 V_pf_stateid[curcpu] = 1;
1234 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1235 s->id = htobe64(s->id);
1236 s->creatorid = V_pf_status.hostid;
1239 /* Returns with ID locked on success. */
1240 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1243 ih = &V_pf_idhash[PF_IDHASH(s)];
1244 PF_HASHROW_ASSERT(ih);
1245 LIST_FOREACH(cur, &ih->states, entry)
1246 if (cur->id == s->id && cur->creatorid == s->creatorid)
1250 PF_HASHROW_UNLOCK(ih);
1251 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1252 printf("pf: state ID collision: "
1253 "id: %016llx creatorid: %08x\n",
1254 (unsigned long long)be64toh(s->id),
1255 ntohl(s->creatorid));
1260 LIST_INSERT_HEAD(&ih->states, s, entry);
1261 /* One for keys, one for ID hash. */
1262 refcount_init(&s->refs, 2);
1264 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1265 if (V_pfsync_insert_state_ptr != NULL)
1266 V_pfsync_insert_state_ptr(s);
1268 /* Returns locked. */
1273 * Find state by ID: returns with locked row on success.
1276 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1278 struct pf_idhash *ih;
1281 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1283 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1285 PF_HASHROW_LOCK(ih);
1286 LIST_FOREACH(s, &ih->states, entry)
1287 if (s->id == id && s->creatorid == creatorid)
1291 PF_HASHROW_UNLOCK(ih);
1297 * Find state by key.
1298 * Returns with ID hash slot locked on success.
1300 static struct pf_state *
1301 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1303 struct pf_keyhash *kh;
1304 struct pf_state_key *sk;
1308 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1310 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1312 PF_HASHROW_LOCK(kh);
1313 LIST_FOREACH(sk, &kh->keys, entry)
1314 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1317 PF_HASHROW_UNLOCK(kh);
1321 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1323 /* List is sorted, if-bound states before floating ones. */
1324 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1325 if (s->kif == V_pfi_all || s->kif == kif) {
1327 PF_HASHROW_UNLOCK(kh);
1328 if (s->timeout >= PFTM_MAX) {
1330 * State is either being processed by
1331 * pf_unlink_state() in an other thread, or
1332 * is scheduled for immediate expiry.
1339 PF_HASHROW_UNLOCK(kh);
1345 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1347 struct pf_keyhash *kh;
1348 struct pf_state_key *sk;
1349 struct pf_state *s, *ret = NULL;
1352 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1354 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1356 PF_HASHROW_LOCK(kh);
1357 LIST_FOREACH(sk, &kh->keys, entry)
1358 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1361 PF_HASHROW_UNLOCK(kh);
1376 panic("%s: dir %u", __func__, dir);
1379 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1381 PF_HASHROW_UNLOCK(kh);
1395 PF_HASHROW_UNLOCK(kh);
1400 /* END state table stuff */
1403 pf_send(struct pf_send_entry *pfse)
1407 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1409 swi_sched(V_pf_swi_cookie, 0);
1415 struct pf_send_head queue;
1416 struct pf_send_entry *pfse, *next;
1418 CURVNET_SET((struct vnet *)v);
1421 queue = V_pf_sendqueue;
1422 STAILQ_INIT(&V_pf_sendqueue);
1425 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1426 switch (pfse->pfse_type) {
1429 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1432 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1433 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1438 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1442 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1443 pfse->icmpopts.code, pfse->icmpopts.mtu);
1447 panic("%s: unknown type", __func__);
1449 free(pfse, M_PFTEMP);
1455 pf_purge_thread(void *unused __unused)
1457 VNET_ITERATOR_DECL(vnet_iter);
1460 PF_RULES_RLOCK_TRACKER;
1464 rm_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1468 VNET_FOREACH(vnet_iter) {
1469 CURVNET_SET(vnet_iter);
1471 if (pf_end_threads) {
1473 wakeup(pf_purge_thread);
1477 /* Wait while V_pf_default_rule.timeout is initialized. */
1478 if (V_pf_vnet_active == 0) {
1483 /* Process 1/interval fraction of the state table every run. */
1484 idx = pf_purge_expired_states(idx, pf_hashmask /
1485 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1487 /* Purge other expired types every PFTM_INTERVAL seconds. */
1490 * Order is important:
1491 * - states and src nodes reference rules
1492 * - states and rules reference kifs
1494 pf_purge_expired_fragments();
1495 pf_purge_expired_src_nodes();
1496 pf_purge_unlinked_rules();
1501 VNET_LIST_RUNLOCK();
1507 pf_unload_vnet_purge(void)
1511 * To cleanse up all kifs and rules we need
1512 * two runs: first one clears reference flags,
1513 * then pf_purge_expired_states() doesn't
1514 * raise them, and then second run frees.
1516 pf_purge_unlinked_rules();
1520 * Now purge everything.
1522 pf_purge_expired_states(0, pf_hashmask);
1523 pf_purge_expired_fragments();
1524 pf_purge_expired_src_nodes();
1527 * Now all kifs & rules should be unreferenced,
1528 * thus should be successfully freed.
1530 pf_purge_unlinked_rules();
1536 pf_state_expires(const struct pf_state *state)
1543 /* handle all PFTM_* > PFTM_MAX here */
1544 if (state->timeout == PFTM_PURGE)
1545 return (time_uptime);
1546 KASSERT(state->timeout != PFTM_UNLINKED,
1547 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1548 KASSERT((state->timeout < PFTM_MAX),
1549 ("pf_state_expires: timeout > PFTM_MAX"));
1550 timeout = state->rule.ptr->timeout[state->timeout];
1552 timeout = V_pf_default_rule.timeout[state->timeout];
1553 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1554 if (start && state->rule.ptr != &V_pf_default_rule) {
1555 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1556 states = counter_u64_fetch(state->rule.ptr->states_cur);
1558 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1559 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1560 states = V_pf_status.states;
1562 if (end && states > start && start < end) {
1564 timeout = (u_int64_t)timeout * (end - states) /
1566 return (state->expire + timeout);
1569 return (time_uptime);
1571 return (state->expire + timeout);
1575 pf_purge_expired_src_nodes()
1577 struct pf_src_node_list freelist;
1578 struct pf_srchash *sh;
1579 struct pf_src_node *cur, *next;
1582 LIST_INIT(&freelist);
1583 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1584 PF_HASHROW_LOCK(sh);
1585 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1586 if (cur->states == 0 && cur->expire <= time_uptime) {
1587 pf_unlink_src_node(cur);
1588 LIST_INSERT_HEAD(&freelist, cur, entry);
1589 } else if (cur->rule.ptr != NULL)
1590 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1591 PF_HASHROW_UNLOCK(sh);
1594 pf_free_src_nodes(&freelist);
1596 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1600 pf_src_tree_remove_state(struct pf_state *s)
1602 struct pf_src_node *sn;
1603 struct pf_srchash *sh;
1606 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1607 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1608 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1610 if (s->src_node != NULL) {
1612 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1613 PF_HASHROW_LOCK(sh);
1616 if (--sn->states == 0)
1617 sn->expire = time_uptime + timeout;
1618 PF_HASHROW_UNLOCK(sh);
1620 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1621 sn = s->nat_src_node;
1622 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1623 PF_HASHROW_LOCK(sh);
1624 if (--sn->states == 0)
1625 sn->expire = time_uptime + timeout;
1626 PF_HASHROW_UNLOCK(sh);
1628 s->src_node = s->nat_src_node = NULL;
1632 * Unlink and potentilly free a state. Function may be
1633 * called with ID hash row locked, but always returns
1634 * unlocked, since it needs to go through key hash locking.
1637 pf_unlink_state(struct pf_state *s, u_int flags)
1639 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1641 if ((flags & PF_ENTER_LOCKED) == 0)
1642 PF_HASHROW_LOCK(ih);
1644 PF_HASHROW_ASSERT(ih);
1646 if (s->timeout == PFTM_UNLINKED) {
1648 * State is being processed
1649 * by pf_unlink_state() in
1652 PF_HASHROW_UNLOCK(ih);
1653 return (0); /* XXXGL: undefined actually */
1656 if (s->src.state == PF_TCPS_PROXY_DST) {
1657 /* XXX wire key the right one? */
1658 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1659 &s->key[PF_SK_WIRE]->addr[1],
1660 &s->key[PF_SK_WIRE]->addr[0],
1661 s->key[PF_SK_WIRE]->port[1],
1662 s->key[PF_SK_WIRE]->port[0],
1663 s->src.seqhi, s->src.seqlo + 1,
1664 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1667 LIST_REMOVE(s, entry);
1668 pf_src_tree_remove_state(s);
1670 if (V_pfsync_delete_state_ptr != NULL)
1671 V_pfsync_delete_state_ptr(s);
1673 STATE_DEC_COUNTERS(s);
1675 s->timeout = PFTM_UNLINKED;
1677 PF_HASHROW_UNLOCK(ih);
1680 refcount_release(&s->refs);
1682 return (pf_release_state(s));
1686 pf_free_state(struct pf_state *cur)
1689 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1690 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1693 pf_normalize_tcp_cleanup(cur);
1694 uma_zfree(V_pf_state_z, cur);
1695 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1699 * Called only from pf_purge_thread(), thus serialized.
1702 pf_purge_expired_states(u_int i, int maxcheck)
1704 struct pf_idhash *ih;
1707 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1710 * Go through hash and unlink states that expire now.
1712 while (maxcheck > 0) {
1714 ih = &V_pf_idhash[i];
1716 /* only take the lock if we expect to do work */
1717 if (!LIST_EMPTY(&ih->states)) {
1719 PF_HASHROW_LOCK(ih);
1720 LIST_FOREACH(s, &ih->states, entry) {
1721 if (pf_state_expires(s) <= time_uptime) {
1722 V_pf_status.states -=
1723 pf_unlink_state(s, PF_ENTER_LOCKED);
1726 s->rule.ptr->rule_flag |= PFRULE_REFS;
1727 if (s->nat_rule.ptr != NULL)
1728 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1729 if (s->anchor.ptr != NULL)
1730 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1731 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1733 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1735 PF_HASHROW_UNLOCK(ih);
1738 /* Return when we hit end of hash. */
1739 if (++i > pf_hashmask) {
1740 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1747 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1753 pf_purge_unlinked_rules()
1755 struct pf_rulequeue tmpq;
1756 struct pf_rule *r, *r1;
1759 * If we have overloading task pending, then we'd
1760 * better skip purging this time. There is a tiny
1761 * probability that overloading task references
1762 * an already unlinked rule.
1764 PF_OVERLOADQ_LOCK();
1765 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1766 PF_OVERLOADQ_UNLOCK();
1769 PF_OVERLOADQ_UNLOCK();
1772 * Do naive mark-and-sweep garbage collecting of old rules.
1773 * Reference flag is raised by pf_purge_expired_states()
1774 * and pf_purge_expired_src_nodes().
1776 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1777 * use a temporary queue.
1780 PF_UNLNKDRULES_LOCK();
1781 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1782 if (!(r->rule_flag & PFRULE_REFS)) {
1783 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1784 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1786 r->rule_flag &= ~PFRULE_REFS;
1788 PF_UNLNKDRULES_UNLOCK();
1790 if (!TAILQ_EMPTY(&tmpq)) {
1792 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1793 TAILQ_REMOVE(&tmpq, r, entries);
1801 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1806 u_int32_t a = ntohl(addr->addr32[0]);
1807 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1819 u_int8_t i, curstart, curend, maxstart, maxend;
1820 curstart = curend = maxstart = maxend = 255;
1821 for (i = 0; i < 8; i++) {
1822 if (!addr->addr16[i]) {
1823 if (curstart == 255)
1827 if ((curend - curstart) >
1828 (maxend - maxstart)) {
1829 maxstart = curstart;
1832 curstart = curend = 255;
1835 if ((curend - curstart) >
1836 (maxend - maxstart)) {
1837 maxstart = curstart;
1840 for (i = 0; i < 8; i++) {
1841 if (i >= maxstart && i <= maxend) {
1847 b = ntohs(addr->addr16[i]);
1864 pf_print_state(struct pf_state *s)
1866 pf_print_state_parts(s, NULL, NULL);
1870 pf_print_state_parts(struct pf_state *s,
1871 struct pf_state_key *skwp, struct pf_state_key *sksp)
1873 struct pf_state_key *skw, *sks;
1874 u_int8_t proto, dir;
1876 /* Do our best to fill these, but they're skipped if NULL */
1877 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1878 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1879 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1880 dir = s ? s->direction : 0;
1898 case IPPROTO_ICMPV6:
1902 printf("%u", proto);
1915 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1917 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1922 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1924 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1929 if (proto == IPPROTO_TCP) {
1930 printf(" [lo=%u high=%u win=%u modulator=%u",
1931 s->src.seqlo, s->src.seqhi,
1932 s->src.max_win, s->src.seqdiff);
1933 if (s->src.wscale && s->dst.wscale)
1934 printf(" wscale=%u",
1935 s->src.wscale & PF_WSCALE_MASK);
1937 printf(" [lo=%u high=%u win=%u modulator=%u",
1938 s->dst.seqlo, s->dst.seqhi,
1939 s->dst.max_win, s->dst.seqdiff);
1940 if (s->src.wscale && s->dst.wscale)
1941 printf(" wscale=%u",
1942 s->dst.wscale & PF_WSCALE_MASK);
1945 printf(" %u:%u", s->src.state, s->dst.state);
1950 pf_print_flags(u_int8_t f)
1972 #define PF_SET_SKIP_STEPS(i) \
1974 while (head[i] != cur) { \
1975 head[i]->skip[i].ptr = cur; \
1976 head[i] = TAILQ_NEXT(head[i], entries); \
1981 pf_calc_skip_steps(struct pf_rulequeue *rules)
1983 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1986 cur = TAILQ_FIRST(rules);
1988 for (i = 0; i < PF_SKIP_COUNT; ++i)
1990 while (cur != NULL) {
1992 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1993 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1994 if (cur->direction != prev->direction)
1995 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1996 if (cur->af != prev->af)
1997 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1998 if (cur->proto != prev->proto)
1999 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2000 if (cur->src.neg != prev->src.neg ||
2001 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2002 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2003 if (cur->src.port[0] != prev->src.port[0] ||
2004 cur->src.port[1] != prev->src.port[1] ||
2005 cur->src.port_op != prev->src.port_op)
2006 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2007 if (cur->dst.neg != prev->dst.neg ||
2008 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2009 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2010 if (cur->dst.port[0] != prev->dst.port[0] ||
2011 cur->dst.port[1] != prev->dst.port[1] ||
2012 cur->dst.port_op != prev->dst.port_op)
2013 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2016 cur = TAILQ_NEXT(cur, entries);
2018 for (i = 0; i < PF_SKIP_COUNT; ++i)
2019 PF_SET_SKIP_STEPS(i);
2023 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2025 if (aw1->type != aw2->type)
2027 switch (aw1->type) {
2028 case PF_ADDR_ADDRMASK:
2030 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2032 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2035 case PF_ADDR_DYNIFTL:
2036 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2037 case PF_ADDR_NOROUTE:
2038 case PF_ADDR_URPFFAILED:
2041 return (aw1->p.tbl != aw2->p.tbl);
2043 printf("invalid address type: %d\n", aw1->type);
2049 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2050 * header isn't always a full checksum. In some cases (i.e. output) it's a
2051 * pseudo-header checksum, which is a partial checksum over src/dst IP
2052 * addresses, protocol number and length.
2054 * That means we have the following cases:
2055 * * Input or forwarding: we don't have TSO, the checksum fields are full
2056 * checksums, we need to update the checksum whenever we change anything.
2057 * * Output (i.e. the checksum is a pseudo-header checksum):
2058 * x The field being updated is src/dst address or affects the length of
2059 * the packet. We need to update the pseudo-header checksum (note that this
2060 * checksum is not ones' complement).
2061 * x Some other field is being modified (e.g. src/dst port numbers): We
2062 * don't have to update anything.
2065 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2071 l = cksum + old - new;
2072 l = (l >> 16) + (l & 65535);
2080 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2081 u_int16_t new, u_int8_t udp)
2083 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2086 return (pf_cksum_fixup(cksum, old, new, udp));
2090 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2091 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2097 PF_ACPY(&ao, a, af);
2100 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2108 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2109 ao.addr16[0], an->addr16[0], 0),
2110 ao.addr16[1], an->addr16[1], 0);
2113 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2114 ao.addr16[0], an->addr16[0], u),
2115 ao.addr16[1], an->addr16[1], u);
2117 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2122 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2123 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2124 pf_cksum_fixup(pf_cksum_fixup(*pc,
2125 ao.addr16[0], an->addr16[0], u),
2126 ao.addr16[1], an->addr16[1], u),
2127 ao.addr16[2], an->addr16[2], u),
2128 ao.addr16[3], an->addr16[3], u),
2129 ao.addr16[4], an->addr16[4], u),
2130 ao.addr16[5], an->addr16[5], u),
2131 ao.addr16[6], an->addr16[6], u),
2132 ao.addr16[7], an->addr16[7], u);
2134 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2139 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2140 CSUM_DELAY_DATA_IPV6)) {
2147 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2149 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2153 memcpy(&ao, a, sizeof(ao));
2154 memcpy(a, &an, sizeof(u_int32_t));
2155 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2156 ao % 65536, an % 65536, u);
2160 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2164 memcpy(&ao, a, sizeof(ao));
2165 memcpy(a, &an, sizeof(u_int32_t));
2167 *c = pf_proto_cksum_fixup(m,
2168 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2169 ao % 65536, an % 65536, udp);
2174 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2178 PF_ACPY(&ao, a, AF_INET6);
2179 PF_ACPY(a, an, AF_INET6);
2181 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2182 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2183 pf_cksum_fixup(pf_cksum_fixup(*c,
2184 ao.addr16[0], an->addr16[0], u),
2185 ao.addr16[1], an->addr16[1], u),
2186 ao.addr16[2], an->addr16[2], u),
2187 ao.addr16[3], an->addr16[3], u),
2188 ao.addr16[4], an->addr16[4], u),
2189 ao.addr16[5], an->addr16[5], u),
2190 ao.addr16[6], an->addr16[6], u),
2191 ao.addr16[7], an->addr16[7], u);
2196 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2197 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2198 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2200 struct pf_addr oia, ooa;
2202 PF_ACPY(&oia, ia, af);
2204 PF_ACPY(&ooa, oa, af);
2206 /* Change inner protocol port, fix inner protocol checksum. */
2208 u_int16_t oip = *ip;
2215 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2216 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2218 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2220 /* Change inner ip address, fix inner ip and icmp checksums. */
2221 PF_ACPY(ia, na, af);
2225 u_int32_t oh2c = *h2c;
2227 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2228 oia.addr16[0], ia->addr16[0], 0),
2229 oia.addr16[1], ia->addr16[1], 0);
2230 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2231 oia.addr16[0], ia->addr16[0], 0),
2232 oia.addr16[1], ia->addr16[1], 0);
2233 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2239 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2240 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2241 pf_cksum_fixup(pf_cksum_fixup(*ic,
2242 oia.addr16[0], ia->addr16[0], u),
2243 oia.addr16[1], ia->addr16[1], u),
2244 oia.addr16[2], ia->addr16[2], u),
2245 oia.addr16[3], ia->addr16[3], u),
2246 oia.addr16[4], ia->addr16[4], u),
2247 oia.addr16[5], ia->addr16[5], u),
2248 oia.addr16[6], ia->addr16[6], u),
2249 oia.addr16[7], ia->addr16[7], u);
2253 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2255 PF_ACPY(oa, na, af);
2259 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2260 ooa.addr16[0], oa->addr16[0], 0),
2261 ooa.addr16[1], oa->addr16[1], 0);
2266 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2267 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2268 pf_cksum_fixup(pf_cksum_fixup(*ic,
2269 ooa.addr16[0], oa->addr16[0], u),
2270 ooa.addr16[1], oa->addr16[1], u),
2271 ooa.addr16[2], oa->addr16[2], u),
2272 ooa.addr16[3], oa->addr16[3], u),
2273 ooa.addr16[4], oa->addr16[4], u),
2274 ooa.addr16[5], oa->addr16[5], u),
2275 ooa.addr16[6], oa->addr16[6], u),
2276 ooa.addr16[7], oa->addr16[7], u);
2285 * Need to modulate the sequence numbers in the TCP SACK option
2286 * (credits to Krzysztof Pfaff for report and patch)
2289 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2290 struct tcphdr *th, struct pf_state_peer *dst)
2292 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2293 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2294 int copyback = 0, i, olen;
2295 struct sackblk sack;
2297 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2298 if (hlen < TCPOLEN_SACKLEN ||
2299 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2302 while (hlen >= TCPOLEN_SACKLEN) {
2305 case TCPOPT_EOL: /* FALLTHROUGH */
2313 if (olen >= TCPOLEN_SACKLEN) {
2314 for (i = 2; i + TCPOLEN_SACK <= olen;
2315 i += TCPOLEN_SACK) {
2316 memcpy(&sack, &opt[i], sizeof(sack));
2317 pf_change_proto_a(m, &sack.start, &th->th_sum,
2318 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2319 pf_change_proto_a(m, &sack.end, &th->th_sum,
2320 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2321 memcpy(&opt[i], &sack, sizeof(sack));
2335 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2340 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2341 const struct pf_addr *saddr, const struct pf_addr *daddr,
2342 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2343 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2344 u_int16_t rtag, struct ifnet *ifp)
2346 struct pf_send_entry *pfse;
2350 struct ip *h = NULL;
2353 struct ip6_hdr *h6 = NULL;
2357 struct pf_mtag *pf_mtag;
2362 /* maximum segment size tcp option */
2363 tlen = sizeof(struct tcphdr);
2370 len = sizeof(struct ip) + tlen;
2375 len = sizeof(struct ip6_hdr) + tlen;
2379 panic("%s: unsupported af %d", __func__, af);
2382 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2383 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2386 m = m_gethdr(M_NOWAIT, MT_DATA);
2388 free(pfse, M_PFTEMP);
2392 mac_netinet_firewall_send(m);
2394 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2395 free(pfse, M_PFTEMP);
2400 m->m_flags |= M_SKIP_FIREWALL;
2401 pf_mtag->tag = rtag;
2403 if (r != NULL && r->rtableid >= 0)
2404 M_SETFIB(m, r->rtableid);
2407 if (r != NULL && r->qid) {
2408 pf_mtag->qid = r->qid;
2410 /* add hints for ecn */
2411 pf_mtag->hdr = mtod(m, struct ip *);
2414 m->m_data += max_linkhdr;
2415 m->m_pkthdr.len = m->m_len = len;
2416 m->m_pkthdr.rcvif = NULL;
2417 bzero(m->m_data, len);
2421 h = mtod(m, struct ip *);
2423 /* IP header fields included in the TCP checksum */
2424 h->ip_p = IPPROTO_TCP;
2425 h->ip_len = htons(tlen);
2426 h->ip_src.s_addr = saddr->v4.s_addr;
2427 h->ip_dst.s_addr = daddr->v4.s_addr;
2429 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2434 h6 = mtod(m, struct ip6_hdr *);
2436 /* IP header fields included in the TCP checksum */
2437 h6->ip6_nxt = IPPROTO_TCP;
2438 h6->ip6_plen = htons(tlen);
2439 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2440 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2442 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2448 th->th_sport = sport;
2449 th->th_dport = dport;
2450 th->th_seq = htonl(seq);
2451 th->th_ack = htonl(ack);
2452 th->th_off = tlen >> 2;
2453 th->th_flags = flags;
2454 th->th_win = htons(win);
2457 opt = (char *)(th + 1);
2458 opt[0] = TCPOPT_MAXSEG;
2461 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2468 th->th_sum = in_cksum(m, len);
2470 /* Finish the IP header */
2472 h->ip_hl = sizeof(*h) >> 2;
2473 h->ip_tos = IPTOS_LOWDELAY;
2474 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2475 h->ip_len = htons(len);
2476 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2479 pfse->pfse_type = PFSE_IP;
2485 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2486 sizeof(struct ip6_hdr), tlen);
2488 h6->ip6_vfc |= IPV6_VERSION;
2489 h6->ip6_hlim = IPV6_DEFHLIM;
2491 pfse->pfse_type = PFSE_IP6;
2500 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2501 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2502 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2505 struct pf_addr * const saddr = pd->src;
2506 struct pf_addr * const daddr = pd->dst;
2507 sa_family_t af = pd->af;
2509 /* undo NAT changes, if they have taken place */
2511 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2512 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2514 *pd->sport = sk->port[pd->sidx];
2516 *pd->dport = sk->port[pd->didx];
2518 *pd->proto_sum = bproto_sum;
2520 *pd->ip_sum = bip_sum;
2521 m_copyback(m, off, hdrlen, pd->hdr.any);
2523 if (pd->proto == IPPROTO_TCP &&
2524 ((r->rule_flag & PFRULE_RETURNRST) ||
2525 (r->rule_flag & PFRULE_RETURN)) &&
2526 !(th->th_flags & TH_RST)) {
2527 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2539 h4 = mtod(m, struct ip *);
2540 len = ntohs(h4->ip_len) - off;
2545 h6 = mtod(m, struct ip6_hdr *);
2546 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2551 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2552 REASON_SET(reason, PFRES_PROTCKSUM);
2554 if (th->th_flags & TH_SYN)
2556 if (th->th_flags & TH_FIN)
2558 pf_send_tcp(m, r, af, pd->dst,
2559 pd->src, th->th_dport, th->th_sport,
2560 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2561 r->return_ttl, 1, 0, kif->pfik_ifp);
2563 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2565 pf_send_icmp(m, r->return_icmp >> 8,
2566 r->return_icmp & 255, af, r);
2567 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2569 pf_send_icmp(m, r->return_icmp6 >> 8,
2570 r->return_icmp6 & 255, af, r);
2575 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2579 KASSERT(prio <= PF_PRIO_MAX,
2580 ("%s with invalid pcp", __func__));
2582 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2584 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2585 sizeof(uint8_t), M_NOWAIT);
2588 m_tag_prepend(m, mtag);
2591 *(uint8_t *)(mtag + 1) = prio;
2596 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2601 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2605 if (prio == PF_PRIO_ZERO)
2608 mpcp = *(uint8_t *)(mtag + 1);
2610 return (mpcp == prio);
2614 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2617 struct pf_send_entry *pfse;
2619 struct pf_mtag *pf_mtag;
2621 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2622 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2626 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2627 free(pfse, M_PFTEMP);
2631 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2632 free(pfse, M_PFTEMP);
2636 m0->m_flags |= M_SKIP_FIREWALL;
2638 if (r->rtableid >= 0)
2639 M_SETFIB(m0, r->rtableid);
2643 pf_mtag->qid = r->qid;
2644 /* add hints for ecn */
2645 pf_mtag->hdr = mtod(m0, struct ip *);
2652 pfse->pfse_type = PFSE_ICMP;
2657 pfse->pfse_type = PFSE_ICMP6;
2662 pfse->icmpopts.type = type;
2663 pfse->icmpopts.code = code;
2668 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2669 * If n is 0, they match if they are equal. If n is != 0, they match if they
2673 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2674 struct pf_addr *b, sa_family_t af)
2681 if ((a->addr32[0] & m->addr32[0]) ==
2682 (b->addr32[0] & m->addr32[0]))
2688 if (((a->addr32[0] & m->addr32[0]) ==
2689 (b->addr32[0] & m->addr32[0])) &&
2690 ((a->addr32[1] & m->addr32[1]) ==
2691 (b->addr32[1] & m->addr32[1])) &&
2692 ((a->addr32[2] & m->addr32[2]) ==
2693 (b->addr32[2] & m->addr32[2])) &&
2694 ((a->addr32[3] & m->addr32[3]) ==
2695 (b->addr32[3] & m->addr32[3])))
2714 * Return 1 if b <= a <= e, otherwise return 0.
2717 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2718 struct pf_addr *a, sa_family_t af)
2723 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2724 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2733 for (i = 0; i < 4; ++i)
2734 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2736 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2739 for (i = 0; i < 4; ++i)
2740 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2742 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2752 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2756 return ((p > a1) && (p < a2));
2758 return ((p < a1) || (p > a2));
2760 return ((p >= a1) && (p <= a2));
2774 return (0); /* never reached */
2778 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2783 return (pf_match(op, a1, a2, p));
2787 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2789 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2791 return (pf_match(op, a1, a2, u));
2795 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2797 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2799 return (pf_match(op, a1, a2, g));
2803 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2808 return ((!r->match_tag_not && r->match_tag == *tag) ||
2809 (r->match_tag_not && r->match_tag != *tag));
2813 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2816 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2818 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2821 pd->pf_mtag->tag = tag;
2826 #define PF_ANCHOR_STACKSIZE 32
2827 struct pf_anchor_stackframe {
2828 struct pf_ruleset *rs;
2829 struct pf_rule *r; /* XXX: + match bit */
2830 struct pf_anchor *child;
2834 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2836 #define PF_ANCHORSTACK_MATCH 0x00000001
2837 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2839 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2840 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2841 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2842 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2843 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2847 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2848 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2851 struct pf_anchor_stackframe *f;
2857 if (*depth >= PF_ANCHOR_STACKSIZE) {
2858 printf("%s: anchor stack overflow on %s\n",
2859 __func__, (*r)->anchor->name);
2860 *r = TAILQ_NEXT(*r, entries);
2862 } else if (*depth == 0 && a != NULL)
2864 f = stack + (*depth)++;
2867 if ((*r)->anchor_wildcard) {
2868 struct pf_anchor_node *parent = &(*r)->anchor->children;
2870 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2874 *rs = &f->child->ruleset;
2877 *rs = &(*r)->anchor->ruleset;
2879 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2883 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2884 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2887 struct pf_anchor_stackframe *f;
2896 f = stack + *depth - 1;
2897 fr = PF_ANCHOR_RULE(f);
2898 if (f->child != NULL) {
2899 struct pf_anchor_node *parent;
2902 * This block traverses through
2903 * a wildcard anchor.
2905 parent = &fr->anchor->children;
2906 if (match != NULL && *match) {
2908 * If any of "*" matched, then
2909 * "foo/ *" matched, mark frame
2912 PF_ANCHOR_SET_MATCH(f);
2915 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2916 if (f->child != NULL) {
2917 *rs = &f->child->ruleset;
2918 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2926 if (*depth == 0 && a != NULL)
2929 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2931 *r = TAILQ_NEXT(fr, entries);
2932 } while (*r == NULL);
2939 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2940 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2945 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2946 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2950 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2951 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2952 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2953 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2954 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2955 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2956 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2957 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2963 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2968 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2972 if (addr->addr32[3] == 0xffffffff) {
2973 addr->addr32[3] = 0;
2974 if (addr->addr32[2] == 0xffffffff) {
2975 addr->addr32[2] = 0;
2976 if (addr->addr32[1] == 0xffffffff) {
2977 addr->addr32[1] = 0;
2979 htonl(ntohl(addr->addr32[0]) + 1);
2982 htonl(ntohl(addr->addr32[1]) + 1);
2985 htonl(ntohl(addr->addr32[2]) + 1);
2988 htonl(ntohl(addr->addr32[3]) + 1);
2995 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2997 struct pf_addr *saddr, *daddr;
2998 u_int16_t sport, dport;
2999 struct inpcbinfo *pi;
3002 pd->lookup.uid = UID_MAX;
3003 pd->lookup.gid = GID_MAX;
3005 switch (pd->proto) {
3007 if (pd->hdr.tcp == NULL)
3009 sport = pd->hdr.tcp->th_sport;
3010 dport = pd->hdr.tcp->th_dport;
3014 if (pd->hdr.udp == NULL)
3016 sport = pd->hdr.udp->uh_sport;
3017 dport = pd->hdr.udp->uh_dport;
3023 if (direction == PF_IN) {
3038 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3039 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3041 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3042 daddr->v4, dport, INPLOOKUP_WILDCARD |
3043 INPLOOKUP_RLOCKPCB, NULL, m);
3051 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3052 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3054 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3055 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3056 INPLOOKUP_RLOCKPCB, NULL, m);
3066 INP_RLOCK_ASSERT(inp);
3067 pd->lookup.uid = inp->inp_cred->cr_uid;
3068 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3075 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3079 u_int8_t *opt, optlen;
3080 u_int8_t wscale = 0;
3082 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3083 if (hlen <= sizeof(struct tcphdr))
3085 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3087 opt = hdr + sizeof(struct tcphdr);
3088 hlen -= sizeof(struct tcphdr);
3098 if (wscale > TCP_MAX_WINSHIFT)
3099 wscale = TCP_MAX_WINSHIFT;
3100 wscale |= PF_WSCALE_FLAG;
3115 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3119 u_int8_t *opt, optlen;
3120 u_int16_t mss = V_tcp_mssdflt;
3122 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3123 if (hlen <= sizeof(struct tcphdr))
3125 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3127 opt = hdr + sizeof(struct tcphdr);
3128 hlen -= sizeof(struct tcphdr);
3129 while (hlen >= TCPOLEN_MAXSEG) {
3137 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3153 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3156 struct nhop4_basic nh4;
3159 struct nhop6_basic nh6;
3160 struct in6_addr dst6;
3169 hlen = sizeof(struct ip);
3170 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3171 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3176 hlen = sizeof(struct ip6_hdr);
3177 in6_splitscope(&addr->v6, &dst6, &scopeid);
3178 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3179 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3184 mss = max(V_tcp_mssdflt, mss);
3185 mss = min(mss, offer);
3186 mss = max(mss, 64); /* sanity - at least max opt space */
3191 pf_tcp_iss(struct pf_pdesc *pd)
3194 u_int32_t digest[4];
3196 if (V_pf_tcp_secret_init == 0) {
3197 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3198 MD5Init(&V_pf_tcp_secret_ctx);
3199 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3200 sizeof(V_pf_tcp_secret));
3201 V_pf_tcp_secret_init = 1;
3204 ctx = V_pf_tcp_secret_ctx;
3206 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3207 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3208 if (pd->af == AF_INET6) {
3209 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3210 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3212 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3213 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3215 MD5Final((u_char *)digest, &ctx);
3216 V_pf_tcp_iss_off += 4096;
3217 #define ISN_RANDOM_INCREMENT (4096 - 1)
3218 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3220 #undef ISN_RANDOM_INCREMENT
3224 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3225 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3226 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3228 struct pf_rule *nr = NULL;
3229 struct pf_addr * const saddr = pd->src;
3230 struct pf_addr * const daddr = pd->dst;
3231 sa_family_t af = pd->af;
3232 struct pf_rule *r, *a = NULL;
3233 struct pf_ruleset *ruleset = NULL;
3234 struct pf_src_node *nsn = NULL;
3235 struct tcphdr *th = pd->hdr.tcp;
3236 struct pf_state_key *sk = NULL, *nk = NULL;
3238 int rewrite = 0, hdrlen = 0;
3239 int tag = -1, rtableid = -1;
3243 u_int16_t sport = 0, dport = 0;
3244 u_int16_t bproto_sum = 0, bip_sum = 0;
3245 u_int8_t icmptype = 0, icmpcode = 0;
3246 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3251 INP_LOCK_ASSERT(inp);
3252 pd->lookup.uid = inp->inp_cred->cr_uid;
3253 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3254 pd->lookup.done = 1;
3257 switch (pd->proto) {
3259 sport = th->th_sport;
3260 dport = th->th_dport;
3261 hdrlen = sizeof(*th);
3264 sport = pd->hdr.udp->uh_sport;
3265 dport = pd->hdr.udp->uh_dport;
3266 hdrlen = sizeof(*pd->hdr.udp);
3270 if (pd->af != AF_INET)
3272 sport = dport = pd->hdr.icmp->icmp_id;
3273 hdrlen = sizeof(*pd->hdr.icmp);
3274 icmptype = pd->hdr.icmp->icmp_type;
3275 icmpcode = pd->hdr.icmp->icmp_code;
3277 if (icmptype == ICMP_UNREACH ||
3278 icmptype == ICMP_SOURCEQUENCH ||
3279 icmptype == ICMP_REDIRECT ||
3280 icmptype == ICMP_TIMXCEED ||
3281 icmptype == ICMP_PARAMPROB)
3286 case IPPROTO_ICMPV6:
3289 sport = dport = pd->hdr.icmp6->icmp6_id;
3290 hdrlen = sizeof(*pd->hdr.icmp6);
3291 icmptype = pd->hdr.icmp6->icmp6_type;
3292 icmpcode = pd->hdr.icmp6->icmp6_code;
3294 if (icmptype == ICMP6_DST_UNREACH ||
3295 icmptype == ICMP6_PACKET_TOO_BIG ||
3296 icmptype == ICMP6_TIME_EXCEEDED ||
3297 icmptype == ICMP6_PARAM_PROB)
3302 sport = dport = hdrlen = 0;
3306 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3308 /* check packet for BINAT/NAT/RDR */
3309 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3310 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3311 KASSERT(sk != NULL, ("%s: null sk", __func__));
3312 KASSERT(nk != NULL, ("%s: null nk", __func__));
3315 bip_sum = *pd->ip_sum;
3317 switch (pd->proto) {
3319 bproto_sum = th->th_sum;
3320 pd->proto_sum = &th->th_sum;
3322 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3323 nk->port[pd->sidx] != sport) {
3324 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3325 &th->th_sum, &nk->addr[pd->sidx],
3326 nk->port[pd->sidx], 0, af);
3327 pd->sport = &th->th_sport;
3328 sport = th->th_sport;
3331 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3332 nk->port[pd->didx] != dport) {
3333 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3334 &th->th_sum, &nk->addr[pd->didx],
3335 nk->port[pd->didx], 0, af);
3336 dport = th->th_dport;
3337 pd->dport = &th->th_dport;
3342 bproto_sum = pd->hdr.udp->uh_sum;
3343 pd->proto_sum = &pd->hdr.udp->uh_sum;
3345 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3346 nk->port[pd->sidx] != sport) {
3347 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3348 pd->ip_sum, &pd->hdr.udp->uh_sum,
3349 &nk->addr[pd->sidx],
3350 nk->port[pd->sidx], 1, af);
3351 sport = pd->hdr.udp->uh_sport;
3352 pd->sport = &pd->hdr.udp->uh_sport;
3355 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3356 nk->port[pd->didx] != dport) {
3357 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3358 pd->ip_sum, &pd->hdr.udp->uh_sum,
3359 &nk->addr[pd->didx],
3360 nk->port[pd->didx], 1, af);
3361 dport = pd->hdr.udp->uh_dport;
3362 pd->dport = &pd->hdr.udp->uh_dport;
3368 nk->port[0] = nk->port[1];
3369 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3370 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3371 nk->addr[pd->sidx].v4.s_addr, 0);
3373 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3374 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3375 nk->addr[pd->didx].v4.s_addr, 0);
3377 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3378 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3379 pd->hdr.icmp->icmp_cksum, sport,
3381 pd->hdr.icmp->icmp_id = nk->port[1];
3382 pd->sport = &pd->hdr.icmp->icmp_id;
3384 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3388 case IPPROTO_ICMPV6:
3389 nk->port[0] = nk->port[1];
3390 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3391 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3392 &nk->addr[pd->sidx], 0);
3394 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3395 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3396 &nk->addr[pd->didx], 0);
3405 &nk->addr[pd->sidx], AF_INET))
3406 pf_change_a(&saddr->v4.s_addr,
3408 nk->addr[pd->sidx].v4.s_addr, 0);
3411 &nk->addr[pd->didx], AF_INET))
3412 pf_change_a(&daddr->v4.s_addr,
3414 nk->addr[pd->didx].v4.s_addr, 0);
3420 &nk->addr[pd->sidx], AF_INET6))
3421 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3424 &nk->addr[pd->didx], AF_INET6))
3425 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3438 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3439 r = r->skip[PF_SKIP_IFP].ptr;
3440 else if (r->direction && r->direction != direction)
3441 r = r->skip[PF_SKIP_DIR].ptr;
3442 else if (r->af && r->af != af)
3443 r = r->skip[PF_SKIP_AF].ptr;
3444 else if (r->proto && r->proto != pd->proto)
3445 r = r->skip[PF_SKIP_PROTO].ptr;
3446 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3447 r->src.neg, kif, M_GETFIB(m)))
3448 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3449 /* tcp/udp only. port_op always 0 in other cases */
3450 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3451 r->src.port[0], r->src.port[1], sport))
3452 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3453 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3454 r->dst.neg, NULL, M_GETFIB(m)))
3455 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3456 /* tcp/udp only. port_op always 0 in other cases */
3457 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3458 r->dst.port[0], r->dst.port[1], dport))
3459 r = r->skip[PF_SKIP_DST_PORT].ptr;
3460 /* icmp only. type always 0 in other cases */
3461 else if (r->type && r->type != icmptype + 1)
3462 r = TAILQ_NEXT(r, entries);
3463 /* icmp only. type always 0 in other cases */
3464 else if (r->code && r->code != icmpcode + 1)
3465 r = TAILQ_NEXT(r, entries);
3466 else if (r->tos && !(r->tos == pd->tos))
3467 r = TAILQ_NEXT(r, entries);
3468 else if (r->rule_flag & PFRULE_FRAGMENT)
3469 r = TAILQ_NEXT(r, entries);
3470 else if (pd->proto == IPPROTO_TCP &&
3471 (r->flagset & th->th_flags) != r->flags)
3472 r = TAILQ_NEXT(r, entries);
3473 /* tcp/udp only. uid.op always 0 in other cases */
3474 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3475 pf_socket_lookup(direction, pd, m), 1)) &&
3476 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3478 r = TAILQ_NEXT(r, entries);
3479 /* tcp/udp only. gid.op always 0 in other cases */
3480 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3481 pf_socket_lookup(direction, pd, m), 1)) &&
3482 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3484 r = TAILQ_NEXT(r, entries);
3486 !pf_match_ieee8021q_pcp(r->prio, m))
3487 r = TAILQ_NEXT(r, entries);
3489 r->prob <= arc4random())
3490 r = TAILQ_NEXT(r, entries);
3491 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3492 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3493 r = TAILQ_NEXT(r, entries);
3494 else if (r->os_fingerprint != PF_OSFP_ANY &&
3495 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3496 pf_osfp_fingerprint(pd, m, off, th),
3497 r->os_fingerprint)))
3498 r = TAILQ_NEXT(r, entries);
3502 if (r->rtableid >= 0)
3503 rtableid = r->rtableid;
3504 if (r->anchor == NULL) {
3511 r = TAILQ_NEXT(r, entries);
3513 pf_step_into_anchor(anchor_stack, &asd,
3514 &ruleset, PF_RULESET_FILTER, &r, &a,
3517 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3518 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3525 REASON_SET(&reason, PFRES_MATCH);
3527 if (r->log || (nr != NULL && nr->log)) {
3529 m_copyback(m, off, hdrlen, pd->hdr.any);
3530 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3534 if ((r->action == PF_DROP) &&
3535 ((r->rule_flag & PFRULE_RETURNRST) ||
3536 (r->rule_flag & PFRULE_RETURNICMP) ||
3537 (r->rule_flag & PFRULE_RETURN))) {
3538 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3539 bip_sum, hdrlen, &reason);
3542 if (r->action == PF_DROP)
3545 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3546 REASON_SET(&reason, PFRES_MEMORY);
3550 M_SETFIB(m, rtableid);
3552 if (!state_icmp && (r->keep_state || nr != NULL ||
3553 (pd->flags & PFDESC_TCP_NORM))) {
3555 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3556 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3558 if (action != PF_PASS) {
3559 if (action == PF_DROP &&
3560 (r->rule_flag & PFRULE_RETURN))
3561 pf_return(r, nr, pd, sk, off, m, th, kif,
3562 bproto_sum, bip_sum, hdrlen, &reason);
3567 uma_zfree(V_pf_state_key_z, sk);
3569 uma_zfree(V_pf_state_key_z, nk);
3572 /* copy back packet headers if we performed NAT operations */
3574 m_copyback(m, off, hdrlen, pd->hdr.any);
3576 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3577 direction == PF_OUT &&
3578 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3580 * We want the state created, but we dont
3581 * want to send this in case a partner
3582 * firewall has to know about it to allow
3583 * replies through it.
3591 uma_zfree(V_pf_state_key_z, sk);
3593 uma_zfree(V_pf_state_key_z, nk);
3598 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3599 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3600 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3601 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3602 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3604 struct pf_state *s = NULL;
3605 struct pf_src_node *sn = NULL;
3606 struct tcphdr *th = pd->hdr.tcp;
3607 u_int16_t mss = V_tcp_mssdflt;
3610 /* check maximums */
3611 if (r->max_states &&
3612 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3613 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3614 REASON_SET(&reason, PFRES_MAXSTATES);
3617 /* src node for filter rule */
3618 if ((r->rule_flag & PFRULE_SRCTRACK ||
3619 r->rpool.opts & PF_POOL_STICKYADDR) &&
3620 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3621 REASON_SET(&reason, PFRES_SRCLIMIT);
3624 /* src node for translation rule */
3625 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3626 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3627 REASON_SET(&reason, PFRES_SRCLIMIT);
3630 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3632 REASON_SET(&reason, PFRES_MEMORY);
3636 s->nat_rule.ptr = nr;
3638 STATE_INC_COUNTERS(s);
3640 s->state_flags |= PFSTATE_ALLOWOPTS;
3641 if (r->rule_flag & PFRULE_STATESLOPPY)
3642 s->state_flags |= PFSTATE_SLOPPY;
3643 s->log = r->log & PF_LOG_ALL;
3644 s->sync_state = PFSYNC_S_NONE;
3646 s->log |= nr->log & PF_LOG_ALL;
3647 switch (pd->proto) {
3649 s->src.seqlo = ntohl(th->th_seq);
3650 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3651 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3652 r->keep_state == PF_STATE_MODULATE) {
3653 /* Generate sequence number modulator */
3654 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3657 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3658 htonl(s->src.seqlo + s->src.seqdiff), 0);
3662 if (th->th_flags & TH_SYN) {
3664 s->src.wscale = pf_get_wscale(m, off,
3665 th->th_off, pd->af);
3667 s->src.max_win = MAX(ntohs(th->th_win), 1);
3668 if (s->src.wscale & PF_WSCALE_MASK) {
3669 /* Remove scale factor from initial window */
3670 int win = s->src.max_win;
3671 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3672 s->src.max_win = (win - 1) >>
3673 (s->src.wscale & PF_WSCALE_MASK);
3675 if (th->th_flags & TH_FIN)
3679 s->src.state = TCPS_SYN_SENT;
3680 s->dst.state = TCPS_CLOSED;
3681 s->timeout = PFTM_TCP_FIRST_PACKET;
3684 s->src.state = PFUDPS_SINGLE;
3685 s->dst.state = PFUDPS_NO_TRAFFIC;
3686 s->timeout = PFTM_UDP_FIRST_PACKET;
3690 case IPPROTO_ICMPV6:
3692 s->timeout = PFTM_ICMP_FIRST_PACKET;
3695 s->src.state = PFOTHERS_SINGLE;
3696 s->dst.state = PFOTHERS_NO_TRAFFIC;
3697 s->timeout = PFTM_OTHER_FIRST_PACKET;
3700 if (r->rt && r->rt != PF_FASTROUTE) {
3701 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3702 REASON_SET(&reason, PFRES_MAPFAILED);
3703 pf_src_tree_remove_state(s);
3704 STATE_DEC_COUNTERS(s);
3705 uma_zfree(V_pf_state_z, s);
3708 s->rt_kif = r->rpool.cur->kif;
3711 s->creation = time_uptime;
3712 s->expire = time_uptime;
3717 /* XXX We only modify one side for now. */
3718 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3719 s->nat_src_node = nsn;
3721 if (pd->proto == IPPROTO_TCP) {
3722 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3723 off, pd, th, &s->src, &s->dst)) {
3724 REASON_SET(&reason, PFRES_MEMORY);
3725 pf_src_tree_remove_state(s);
3726 STATE_DEC_COUNTERS(s);
3727 uma_zfree(V_pf_state_z, s);
3730 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3731 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3732 &s->src, &s->dst, rewrite)) {
3733 /* This really shouldn't happen!!! */
3734 DPFPRINTF(PF_DEBUG_URGENT,
3735 ("pf_normalize_tcp_stateful failed on first pkt"));
3736 pf_normalize_tcp_cleanup(s);
3737 pf_src_tree_remove_state(s);
3738 STATE_DEC_COUNTERS(s);
3739 uma_zfree(V_pf_state_z, s);
3743 s->direction = pd->dir;
3746 * sk/nk could already been setup by pf_get_translation().
3749 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3750 __func__, nr, sk, nk));
3751 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3756 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3757 __func__, nr, sk, nk));
3759 /* Swap sk/nk for PF_OUT. */
3760 if (pf_state_insert(BOUND_IFACE(r, kif),
3761 (pd->dir == PF_IN) ? sk : nk,
3762 (pd->dir == PF_IN) ? nk : sk, s)) {
3763 if (pd->proto == IPPROTO_TCP)
3764 pf_normalize_tcp_cleanup(s);
3765 REASON_SET(&reason, PFRES_STATEINS);
3766 pf_src_tree_remove_state(s);
3767 STATE_DEC_COUNTERS(s);
3768 uma_zfree(V_pf_state_z, s);
3775 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3776 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3777 s->src.state = PF_TCPS_PROXY_SRC;
3778 /* undo NAT changes, if they have taken place */
3780 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3781 if (pd->dir == PF_OUT)
3782 skt = s->key[PF_SK_STACK];
3783 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3784 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3786 *pd->sport = skt->port[pd->sidx];
3788 *pd->dport = skt->port[pd->didx];
3790 *pd->proto_sum = bproto_sum;
3792 *pd->ip_sum = bip_sum;
3793 m_copyback(m, off, hdrlen, pd->hdr.any);
3795 s->src.seqhi = htonl(arc4random());
3796 /* Find mss option */
3797 int rtid = M_GETFIB(m);
3798 mss = pf_get_mss(m, off, th->th_off, pd->af);
3799 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3800 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3802 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3803 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3804 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3805 REASON_SET(&reason, PFRES_SYNPROXY);
3806 return (PF_SYNPROXY_DROP);
3813 uma_zfree(V_pf_state_key_z, sk);
3815 uma_zfree(V_pf_state_key_z, nk);
3818 struct pf_srchash *sh;
3820 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3821 PF_HASHROW_LOCK(sh);
3822 if (--sn->states == 0 && sn->expire == 0) {
3823 pf_unlink_src_node(sn);
3824 uma_zfree(V_pf_sources_z, sn);
3826 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3828 PF_HASHROW_UNLOCK(sh);
3831 if (nsn != sn && nsn != NULL) {
3832 struct pf_srchash *sh;
3834 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3835 PF_HASHROW_LOCK(sh);
3836 if (--nsn->states == 0 && nsn->expire == 0) {
3837 pf_unlink_src_node(nsn);
3838 uma_zfree(V_pf_sources_z, nsn);
3840 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3842 PF_HASHROW_UNLOCK(sh);
3849 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3850 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3851 struct pf_ruleset **rsm)
3853 struct pf_rule *r, *a = NULL;
3854 struct pf_ruleset *ruleset = NULL;
3855 sa_family_t af = pd->af;
3860 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3864 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3867 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3868 r = r->skip[PF_SKIP_IFP].ptr;
3869 else if (r->direction && r->direction != direction)
3870 r = r->skip[PF_SKIP_DIR].ptr;
3871 else if (r->af && r->af != af)
3872 r = r->skip[PF_SKIP_AF].ptr;
3873 else if (r->proto && r->proto != pd->proto)
3874 r = r->skip[PF_SKIP_PROTO].ptr;
3875 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3876 r->src.neg, kif, M_GETFIB(m)))
3877 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3878 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3879 r->dst.neg, NULL, M_GETFIB(m)))
3880 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3881 else if (r->tos && !(r->tos == pd->tos))
3882 r = TAILQ_NEXT(r, entries);
3883 else if (r->os_fingerprint != PF_OSFP_ANY)
3884 r = TAILQ_NEXT(r, entries);
3885 else if (pd->proto == IPPROTO_UDP &&
3886 (r->src.port_op || r->dst.port_op))
3887 r = TAILQ_NEXT(r, entries);
3888 else if (pd->proto == IPPROTO_TCP &&
3889 (r->src.port_op || r->dst.port_op || r->flagset))
3890 r = TAILQ_NEXT(r, entries);
3891 else if ((pd->proto == IPPROTO_ICMP ||
3892 pd->proto == IPPROTO_ICMPV6) &&
3893 (r->type || r->code))
3894 r = TAILQ_NEXT(r, entries);
3896 !pf_match_ieee8021q_pcp(r->prio, m))
3897 r = TAILQ_NEXT(r, entries);
3898 else if (r->prob && r->prob <=
3899 (arc4random() % (UINT_MAX - 1) + 1))
3900 r = TAILQ_NEXT(r, entries);
3901 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3902 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3903 r = TAILQ_NEXT(r, entries);
3905 if (r->anchor == NULL) {
3912 r = TAILQ_NEXT(r, entries);
3914 pf_step_into_anchor(anchor_stack, &asd,
3915 &ruleset, PF_RULESET_FILTER, &r, &a,
3918 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3919 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3926 REASON_SET(&reason, PFRES_MATCH);
3929 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3932 if (r->action != PF_PASS)
3935 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3936 REASON_SET(&reason, PFRES_MEMORY);
3944 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3945 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3946 struct pf_pdesc *pd, u_short *reason, int *copyback)
3948 struct tcphdr *th = pd->hdr.tcp;
3949 u_int16_t win = ntohs(th->th_win);
3950 u_int32_t ack, end, seq, orig_seq;
3954 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3955 sws = src->wscale & PF_WSCALE_MASK;
3956 dws = dst->wscale & PF_WSCALE_MASK;
3961 * Sequence tracking algorithm from Guido van Rooij's paper:
3962 * http://www.madison-gurkha.com/publications/tcp_filtering/
3966 orig_seq = seq = ntohl(th->th_seq);
3967 if (src->seqlo == 0) {
3968 /* First packet from this end. Set its state */
3970 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3971 src->scrub == NULL) {
3972 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3973 REASON_SET(reason, PFRES_MEMORY);
3978 /* Deferred generation of sequence number modulator */
3979 if (dst->seqdiff && !src->seqdiff) {
3980 /* use random iss for the TCP server */
3981 while ((src->seqdiff = arc4random() - seq) == 0)
3983 ack = ntohl(th->th_ack) - dst->seqdiff;
3984 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3986 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3989 ack = ntohl(th->th_ack);
3992 end = seq + pd->p_len;
3993 if (th->th_flags & TH_SYN) {
3995 if (dst->wscale & PF_WSCALE_FLAG) {
3996 src->wscale = pf_get_wscale(m, off, th->th_off,
3998 if (src->wscale & PF_WSCALE_FLAG) {
3999 /* Remove scale factor from initial
4001 sws = src->wscale & PF_WSCALE_MASK;
4002 win = ((u_int32_t)win + (1 << sws) - 1)
4004 dws = dst->wscale & PF_WSCALE_MASK;
4006 /* fixup other window */
4007 dst->max_win <<= dst->wscale &
4009 /* in case of a retrans SYN|ACK */
4014 if (th->th_flags & TH_FIN)
4018 if (src->state < TCPS_SYN_SENT)
4019 src->state = TCPS_SYN_SENT;
4022 * May need to slide the window (seqhi may have been set by
4023 * the crappy stack check or if we picked up the connection
4024 * after establishment)
4026 if (src->seqhi == 1 ||
4027 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4028 src->seqhi = end + MAX(1, dst->max_win << dws);
4029 if (win > src->max_win)
4033 ack = ntohl(th->th_ack) - dst->seqdiff;
4035 /* Modulate sequence numbers */
4036 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4038 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4041 end = seq + pd->p_len;
4042 if (th->th_flags & TH_SYN)
4044 if (th->th_flags & TH_FIN)
4048 if ((th->th_flags & TH_ACK) == 0) {
4049 /* Let it pass through the ack skew check */
4051 } else if ((ack == 0 &&
4052 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4053 /* broken tcp stacks do not set ack */
4054 (dst->state < TCPS_SYN_SENT)) {
4056 * Many stacks (ours included) will set the ACK number in an
4057 * FIN|ACK if the SYN times out -- no sequence to ACK.
4063 /* Ease sequencing restrictions on no data packets */
4068 ackskew = dst->seqlo - ack;
4072 * Need to demodulate the sequence numbers in any TCP SACK options
4073 * (Selective ACK). We could optionally validate the SACK values
4074 * against the current ACK window, either forwards or backwards, but
4075 * I'm not confident that SACK has been implemented properly
4076 * everywhere. It wouldn't surprise me if several stacks accidentally
4077 * SACK too far backwards of previously ACKed data. There really aren't
4078 * any security implications of bad SACKing unless the target stack
4079 * doesn't validate the option length correctly. Someone trying to
4080 * spoof into a TCP connection won't bother blindly sending SACK
4083 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4084 if (pf_modulate_sack(m, off, pd, th, dst))
4089 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4090 if (SEQ_GEQ(src->seqhi, end) &&
4091 /* Last octet inside other's window space */
4092 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4093 /* Retrans: not more than one window back */
4094 (ackskew >= -MAXACKWINDOW) &&
4095 /* Acking not more than one reassembled fragment backwards */
4096 (ackskew <= (MAXACKWINDOW << sws)) &&
4097 /* Acking not more than one window forward */
4098 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4099 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4100 (pd->flags & PFDESC_IP_REAS) == 0)) {
4101 /* Require an exact/+1 sequence match on resets when possible */
4103 if (dst->scrub || src->scrub) {
4104 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4105 *state, src, dst, copyback))
4109 /* update max window */
4110 if (src->max_win < win)
4112 /* synchronize sequencing */
4113 if (SEQ_GT(end, src->seqlo))
4115 /* slide the window of what the other end can send */
4116 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4117 dst->seqhi = ack + MAX((win << sws), 1);
4121 if (th->th_flags & TH_SYN)
4122 if (src->state < TCPS_SYN_SENT)
4123 src->state = TCPS_SYN_SENT;
4124 if (th->th_flags & TH_FIN)
4125 if (src->state < TCPS_CLOSING)
4126 src->state = TCPS_CLOSING;
4127 if (th->th_flags & TH_ACK) {
4128 if (dst->state == TCPS_SYN_SENT) {
4129 dst->state = TCPS_ESTABLISHED;
4130 if (src->state == TCPS_ESTABLISHED &&
4131 (*state)->src_node != NULL &&
4132 pf_src_connlimit(state)) {
4133 REASON_SET(reason, PFRES_SRCLIMIT);
4136 } else if (dst->state == TCPS_CLOSING)
4137 dst->state = TCPS_FIN_WAIT_2;
4139 if (th->th_flags & TH_RST)
4140 src->state = dst->state = TCPS_TIME_WAIT;
4142 /* update expire time */
4143 (*state)->expire = time_uptime;
4144 if (src->state >= TCPS_FIN_WAIT_2 &&
4145 dst->state >= TCPS_FIN_WAIT_2)
4146 (*state)->timeout = PFTM_TCP_CLOSED;
4147 else if (src->state >= TCPS_CLOSING &&
4148 dst->state >= TCPS_CLOSING)
4149 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4150 else if (src->state < TCPS_ESTABLISHED ||
4151 dst->state < TCPS_ESTABLISHED)
4152 (*state)->timeout = PFTM_TCP_OPENING;
4153 else if (src->state >= TCPS_CLOSING ||
4154 dst->state >= TCPS_CLOSING)
4155 (*state)->timeout = PFTM_TCP_CLOSING;
4157 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4159 /* Fall through to PASS packet */
4161 } else if ((dst->state < TCPS_SYN_SENT ||
4162 dst->state >= TCPS_FIN_WAIT_2 ||
4163 src->state >= TCPS_FIN_WAIT_2) &&
4164 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4165 /* Within a window forward of the originating packet */
4166 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4167 /* Within a window backward of the originating packet */
4170 * This currently handles three situations:
4171 * 1) Stupid stacks will shotgun SYNs before their peer
4173 * 2) When PF catches an already established stream (the
4174 * firewall rebooted, the state table was flushed, routes
4176 * 3) Packets get funky immediately after the connection
4177 * closes (this should catch Solaris spurious ACK|FINs
4178 * that web servers like to spew after a close)
4180 * This must be a little more careful than the above code
4181 * since packet floods will also be caught here. We don't
4182 * update the TTL here to mitigate the damage of a packet
4183 * flood and so the same code can handle awkward establishment
4184 * and a loosened connection close.
4185 * In the establishment case, a correct peer response will
4186 * validate the connection, go through the normal state code
4187 * and keep updating the state TTL.
4190 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4191 printf("pf: loose state match: ");
4192 pf_print_state(*state);
4193 pf_print_flags(th->th_flags);
4194 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4195 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4196 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4197 (unsigned long long)(*state)->packets[1],
4198 pd->dir == PF_IN ? "in" : "out",
4199 pd->dir == (*state)->direction ? "fwd" : "rev");
4202 if (dst->scrub || src->scrub) {
4203 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4204 *state, src, dst, copyback))
4208 /* update max window */
4209 if (src->max_win < win)
4211 /* synchronize sequencing */
4212 if (SEQ_GT(end, src->seqlo))
4214 /* slide the window of what the other end can send */
4215 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4216 dst->seqhi = ack + MAX((win << sws), 1);
4219 * Cannot set dst->seqhi here since this could be a shotgunned
4220 * SYN and not an already established connection.
4223 if (th->th_flags & TH_FIN)
4224 if (src->state < TCPS_CLOSING)
4225 src->state = TCPS_CLOSING;
4226 if (th->th_flags & TH_RST)
4227 src->state = dst->state = TCPS_TIME_WAIT;
4229 /* Fall through to PASS packet */
4232 if ((*state)->dst.state == TCPS_SYN_SENT &&
4233 (*state)->src.state == TCPS_SYN_SENT) {
4234 /* Send RST for state mismatches during handshake */
4235 if (!(th->th_flags & TH_RST))
4236 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4237 pd->dst, pd->src, th->th_dport,
4238 th->th_sport, ntohl(th->th_ack), 0,
4240 (*state)->rule.ptr->return_ttl, 1, 0,
4245 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4246 printf("pf: BAD state: ");
4247 pf_print_state(*state);
4248 pf_print_flags(th->th_flags);
4249 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4250 "pkts=%llu:%llu dir=%s,%s\n",
4251 seq, orig_seq, ack, pd->p_len, ackskew,
4252 (unsigned long long)(*state)->packets[0],
4253 (unsigned long long)(*state)->packets[1],
4254 pd->dir == PF_IN ? "in" : "out",
4255 pd->dir == (*state)->direction ? "fwd" : "rev");
4256 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4257 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4258 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4260 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4261 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4262 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4263 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4265 REASON_SET(reason, PFRES_BADSTATE);
4273 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4274 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4276 struct tcphdr *th = pd->hdr.tcp;
4278 if (th->th_flags & TH_SYN)
4279 if (src->state < TCPS_SYN_SENT)
4280 src->state = TCPS_SYN_SENT;
4281 if (th->th_flags & TH_FIN)
4282 if (src->state < TCPS_CLOSING)
4283 src->state = TCPS_CLOSING;
4284 if (th->th_flags & TH_ACK) {
4285 if (dst->state == TCPS_SYN_SENT) {
4286 dst->state = TCPS_ESTABLISHED;
4287 if (src->state == TCPS_ESTABLISHED &&
4288 (*state)->src_node != NULL &&
4289 pf_src_connlimit(state)) {
4290 REASON_SET(reason, PFRES_SRCLIMIT);
4293 } else if (dst->state == TCPS_CLOSING) {
4294 dst->state = TCPS_FIN_WAIT_2;
4295 } else if (src->state == TCPS_SYN_SENT &&
4296 dst->state < TCPS_SYN_SENT) {
4298 * Handle a special sloppy case where we only see one
4299 * half of the connection. If there is a ACK after
4300 * the initial SYN without ever seeing a packet from
4301 * the destination, set the connection to established.
4303 dst->state = src->state = TCPS_ESTABLISHED;
4304 if ((*state)->src_node != NULL &&
4305 pf_src_connlimit(state)) {
4306 REASON_SET(reason, PFRES_SRCLIMIT);
4309 } else if (src->state == TCPS_CLOSING &&
4310 dst->state == TCPS_ESTABLISHED &&
4313 * Handle the closing of half connections where we
4314 * don't see the full bidirectional FIN/ACK+ACK
4317 dst->state = TCPS_CLOSING;
4320 if (th->th_flags & TH_RST)
4321 src->state = dst->state = TCPS_TIME_WAIT;
4323 /* update expire time */
4324 (*state)->expire = time_uptime;
4325 if (src->state >= TCPS_FIN_WAIT_2 &&
4326 dst->state >= TCPS_FIN_WAIT_2)
4327 (*state)->timeout = PFTM_TCP_CLOSED;
4328 else if (src->state >= TCPS_CLOSING &&
4329 dst->state >= TCPS_CLOSING)
4330 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4331 else if (src->state < TCPS_ESTABLISHED ||
4332 dst->state < TCPS_ESTABLISHED)
4333 (*state)->timeout = PFTM_TCP_OPENING;
4334 else if (src->state >= TCPS_CLOSING ||
4335 dst->state >= TCPS_CLOSING)
4336 (*state)->timeout = PFTM_TCP_CLOSING;
4338 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4344 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4345 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4348 struct pf_state_key_cmp key;
4349 struct tcphdr *th = pd->hdr.tcp;
4351 struct pf_state_peer *src, *dst;
4352 struct pf_state_key *sk;
4354 bzero(&key, sizeof(key));
4356 key.proto = IPPROTO_TCP;
4357 if (direction == PF_IN) { /* wire side, straight */
4358 PF_ACPY(&key.addr[0], pd->src, key.af);
4359 PF_ACPY(&key.addr[1], pd->dst, key.af);
4360 key.port[0] = th->th_sport;
4361 key.port[1] = th->th_dport;
4362 } else { /* stack side, reverse */
4363 PF_ACPY(&key.addr[1], pd->src, key.af);
4364 PF_ACPY(&key.addr[0], pd->dst, key.af);
4365 key.port[1] = th->th_sport;
4366 key.port[0] = th->th_dport;
4369 STATE_LOOKUP(kif, &key, direction, *state, pd);
4371 if (direction == (*state)->direction) {
4372 src = &(*state)->src;
4373 dst = &(*state)->dst;
4375 src = &(*state)->dst;
4376 dst = &(*state)->src;
4379 sk = (*state)->key[pd->didx];
4381 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4382 if (direction != (*state)->direction) {
4383 REASON_SET(reason, PFRES_SYNPROXY);
4384 return (PF_SYNPROXY_DROP);
4386 if (th->th_flags & TH_SYN) {
4387 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4388 REASON_SET(reason, PFRES_SYNPROXY);
4391 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4392 pd->src, th->th_dport, th->th_sport,
4393 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4394 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4395 REASON_SET(reason, PFRES_SYNPROXY);
4396 return (PF_SYNPROXY_DROP);
4397 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4398 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4399 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4400 REASON_SET(reason, PFRES_SYNPROXY);
4402 } else if ((*state)->src_node != NULL &&
4403 pf_src_connlimit(state)) {
4404 REASON_SET(reason, PFRES_SRCLIMIT);
4407 (*state)->src.state = PF_TCPS_PROXY_DST;
4409 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4410 if (direction == (*state)->direction) {
4411 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4412 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4413 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4414 REASON_SET(reason, PFRES_SYNPROXY);
4417 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4418 if ((*state)->dst.seqhi == 1)
4419 (*state)->dst.seqhi = htonl(arc4random());
4420 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4421 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4422 sk->port[pd->sidx], sk->port[pd->didx],
4423 (*state)->dst.seqhi, 0, TH_SYN, 0,
4424 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4425 REASON_SET(reason, PFRES_SYNPROXY);
4426 return (PF_SYNPROXY_DROP);
4427 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4429 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4430 REASON_SET(reason, PFRES_SYNPROXY);
4433 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4434 (*state)->dst.seqlo = ntohl(th->th_seq);
4435 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4436 pd->src, th->th_dport, th->th_sport,
4437 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4438 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4439 (*state)->tag, NULL);
4440 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4441 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4442 sk->port[pd->sidx], sk->port[pd->didx],
4443 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4444 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4445 (*state)->src.seqdiff = (*state)->dst.seqhi -
4446 (*state)->src.seqlo;
4447 (*state)->dst.seqdiff = (*state)->src.seqhi -
4448 (*state)->dst.seqlo;
4449 (*state)->src.seqhi = (*state)->src.seqlo +
4450 (*state)->dst.max_win;
4451 (*state)->dst.seqhi = (*state)->dst.seqlo +
4452 (*state)->src.max_win;
4453 (*state)->src.wscale = (*state)->dst.wscale = 0;
4454 (*state)->src.state = (*state)->dst.state =
4456 REASON_SET(reason, PFRES_SYNPROXY);
4457 return (PF_SYNPROXY_DROP);
4461 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4462 dst->state >= TCPS_FIN_WAIT_2 &&
4463 src->state >= TCPS_FIN_WAIT_2) {
4464 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4465 printf("pf: state reuse ");
4466 pf_print_state(*state);
4467 pf_print_flags(th->th_flags);
4470 /* XXX make sure it's the same direction ?? */
4471 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4472 pf_unlink_state(*state, PF_ENTER_LOCKED);
4477 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4478 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4481 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4482 ©back) == PF_DROP)
4486 /* translate source/destination address, if necessary */
4487 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4488 struct pf_state_key *nk = (*state)->key[pd->didx];
4490 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4491 nk->port[pd->sidx] != th->th_sport)
4492 pf_change_ap(m, pd->src, &th->th_sport,
4493 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4494 nk->port[pd->sidx], 0, pd->af);
4496 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4497 nk->port[pd->didx] != th->th_dport)
4498 pf_change_ap(m, pd->dst, &th->th_dport,
4499 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4500 nk->port[pd->didx], 0, pd->af);
4504 /* Copyback sequence modulation or stateful scrub changes if needed */
4506 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4512 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4513 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4515 struct pf_state_peer *src, *dst;
4516 struct pf_state_key_cmp key;
4517 struct udphdr *uh = pd->hdr.udp;
4519 bzero(&key, sizeof(key));
4521 key.proto = IPPROTO_UDP;
4522 if (direction == PF_IN) { /* wire side, straight */
4523 PF_ACPY(&key.addr[0], pd->src, key.af);
4524 PF_ACPY(&key.addr[1], pd->dst, key.af);
4525 key.port[0] = uh->uh_sport;
4526 key.port[1] = uh->uh_dport;
4527 } else { /* stack side, reverse */
4528 PF_ACPY(&key.addr[1], pd->src, key.af);
4529 PF_ACPY(&key.addr[0], pd->dst, key.af);
4530 key.port[1] = uh->uh_sport;
4531 key.port[0] = uh->uh_dport;
4534 STATE_LOOKUP(kif, &key, direction, *state, pd);
4536 if (direction == (*state)->direction) {
4537 src = &(*state)->src;
4538 dst = &(*state)->dst;
4540 src = &(*state)->dst;
4541 dst = &(*state)->src;
4545 if (src->state < PFUDPS_SINGLE)
4546 src->state = PFUDPS_SINGLE;
4547 if (dst->state == PFUDPS_SINGLE)
4548 dst->state = PFUDPS_MULTIPLE;
4550 /* update expire time */
4551 (*state)->expire = time_uptime;
4552 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4553 (*state)->timeout = PFTM_UDP_MULTIPLE;
4555 (*state)->timeout = PFTM_UDP_SINGLE;
4557 /* translate source/destination address, if necessary */
4558 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4559 struct pf_state_key *nk = (*state)->key[pd->didx];
4561 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4562 nk->port[pd->sidx] != uh->uh_sport)
4563 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4564 &uh->uh_sum, &nk->addr[pd->sidx],
4565 nk->port[pd->sidx], 1, pd->af);
4567 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4568 nk->port[pd->didx] != uh->uh_dport)
4569 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4570 &uh->uh_sum, &nk->addr[pd->didx],
4571 nk->port[pd->didx], 1, pd->af);
4572 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4579 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4580 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4582 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4583 u_int16_t icmpid = 0, *icmpsum;
4584 u_int8_t icmptype, icmpcode;
4586 struct pf_state_key_cmp key;
4588 bzero(&key, sizeof(key));
4589 switch (pd->proto) {
4592 icmptype = pd->hdr.icmp->icmp_type;
4593 icmpcode = pd->hdr.icmp->icmp_code;
4594 icmpid = pd->hdr.icmp->icmp_id;
4595 icmpsum = &pd->hdr.icmp->icmp_cksum;
4597 if (icmptype == ICMP_UNREACH ||
4598 icmptype == ICMP_SOURCEQUENCH ||
4599 icmptype == ICMP_REDIRECT ||
4600 icmptype == ICMP_TIMXCEED ||
4601 icmptype == ICMP_PARAMPROB)
4606 case IPPROTO_ICMPV6:
4607 icmptype = pd->hdr.icmp6->icmp6_type;
4608 icmpcode = pd->hdr.icmp6->icmp6_code;
4609 icmpid = pd->hdr.icmp6->icmp6_id;
4610 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4612 if (icmptype == ICMP6_DST_UNREACH ||
4613 icmptype == ICMP6_PACKET_TOO_BIG ||
4614 icmptype == ICMP6_TIME_EXCEEDED ||
4615 icmptype == ICMP6_PARAM_PROB)
4624 * ICMP query/reply message not related to a TCP/UDP packet.
4625 * Search for an ICMP state.
4628 key.proto = pd->proto;
4629 key.port[0] = key.port[1] = icmpid;
4630 if (direction == PF_IN) { /* wire side, straight */
4631 PF_ACPY(&key.addr[0], pd->src, key.af);
4632 PF_ACPY(&key.addr[1], pd->dst, key.af);
4633 } else { /* stack side, reverse */
4634 PF_ACPY(&key.addr[1], pd->src, key.af);
4635 PF_ACPY(&key.addr[0], pd->dst, key.af);
4638 STATE_LOOKUP(kif, &key, direction, *state, pd);
4640 (*state)->expire = time_uptime;
4641 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4643 /* translate source/destination address, if necessary */
4644 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4645 struct pf_state_key *nk = (*state)->key[pd->didx];
4650 if (PF_ANEQ(pd->src,
4651 &nk->addr[pd->sidx], AF_INET))
4652 pf_change_a(&saddr->v4.s_addr,
4654 nk->addr[pd->sidx].v4.s_addr, 0);
4656 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4658 pf_change_a(&daddr->v4.s_addr,
4660 nk->addr[pd->didx].v4.s_addr, 0);
4663 pd->hdr.icmp->icmp_id) {
4664 pd->hdr.icmp->icmp_cksum =
4666 pd->hdr.icmp->icmp_cksum, icmpid,
4667 nk->port[pd->sidx], 0);
4668 pd->hdr.icmp->icmp_id =
4672 m_copyback(m, off, ICMP_MINLEN,
4673 (caddr_t )pd->hdr.icmp);
4678 if (PF_ANEQ(pd->src,
4679 &nk->addr[pd->sidx], AF_INET6))
4681 &pd->hdr.icmp6->icmp6_cksum,
4682 &nk->addr[pd->sidx], 0);
4684 if (PF_ANEQ(pd->dst,
4685 &nk->addr[pd->didx], AF_INET6))
4687 &pd->hdr.icmp6->icmp6_cksum,
4688 &nk->addr[pd->didx], 0);
4690 m_copyback(m, off, sizeof(struct icmp6_hdr),
4691 (caddr_t )pd->hdr.icmp6);
4700 * ICMP error message in response to a TCP/UDP packet.
4701 * Extract the inner TCP/UDP header and search for that state.
4704 struct pf_pdesc pd2;
4705 bzero(&pd2, sizeof pd2);
4710 struct ip6_hdr h2_6;
4717 /* Payload packet is from the opposite direction. */
4718 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4719 pd2.didx = (direction == PF_IN) ? 0 : 1;
4723 /* offset of h2 in mbuf chain */
4724 ipoff2 = off + ICMP_MINLEN;
4726 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4727 NULL, reason, pd2.af)) {
4728 DPFPRINTF(PF_DEBUG_MISC,
4729 ("pf: ICMP error message too short "
4734 * ICMP error messages don't refer to non-first
4737 if (h2.ip_off & htons(IP_OFFMASK)) {
4738 REASON_SET(reason, PFRES_FRAG);
4742 /* offset of protocol header that follows h2 */
4743 off2 = ipoff2 + (h2.ip_hl << 2);
4745 pd2.proto = h2.ip_p;
4746 pd2.src = (struct pf_addr *)&h2.ip_src;
4747 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4748 pd2.ip_sum = &h2.ip_sum;
4753 ipoff2 = off + sizeof(struct icmp6_hdr);
4755 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4756 NULL, reason, pd2.af)) {
4757 DPFPRINTF(PF_DEBUG_MISC,
4758 ("pf: ICMP error message too short "
4762 pd2.proto = h2_6.ip6_nxt;
4763 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4764 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4766 off2 = ipoff2 + sizeof(h2_6);
4768 switch (pd2.proto) {
4769 case IPPROTO_FRAGMENT:
4771 * ICMPv6 error messages for
4772 * non-first fragments
4774 REASON_SET(reason, PFRES_FRAG);
4777 case IPPROTO_HOPOPTS:
4778 case IPPROTO_ROUTING:
4779 case IPPROTO_DSTOPTS: {
4780 /* get next header and header length */
4781 struct ip6_ext opt6;
4783 if (!pf_pull_hdr(m, off2, &opt6,
4784 sizeof(opt6), NULL, reason,
4786 DPFPRINTF(PF_DEBUG_MISC,
4787 ("pf: ICMPv6 short opt\n"));
4790 if (pd2.proto == IPPROTO_AH)
4791 off2 += (opt6.ip6e_len + 2) * 4;
4793 off2 += (opt6.ip6e_len + 1) * 8;
4794 pd2.proto = opt6.ip6e_nxt;
4795 /* goto the next header */
4802 } while (!terminal);
4807 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4808 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4809 printf("pf: BAD ICMP %d:%d outer dst: ",
4810 icmptype, icmpcode);
4811 pf_print_host(pd->src, 0, pd->af);
4813 pf_print_host(pd->dst, 0, pd->af);
4814 printf(" inner src: ");
4815 pf_print_host(pd2.src, 0, pd2.af);
4817 pf_print_host(pd2.dst, 0, pd2.af);
4820 REASON_SET(reason, PFRES_BADSTATE);
4824 switch (pd2.proto) {
4828 struct pf_state_peer *src, *dst;
4833 * Only the first 8 bytes of the TCP header can be
4834 * expected. Don't access any TCP header fields after
4835 * th_seq, an ackskew test is not possible.
4837 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4839 DPFPRINTF(PF_DEBUG_MISC,
4840 ("pf: ICMP error message too short "
4846 key.proto = IPPROTO_TCP;
4847 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4848 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4849 key.port[pd2.sidx] = th.th_sport;
4850 key.port[pd2.didx] = th.th_dport;
4852 STATE_LOOKUP(kif, &key, direction, *state, pd);
4854 if (direction == (*state)->direction) {
4855 src = &(*state)->dst;
4856 dst = &(*state)->src;
4858 src = &(*state)->src;
4859 dst = &(*state)->dst;
4862 if (src->wscale && dst->wscale)
4863 dws = dst->wscale & PF_WSCALE_MASK;
4867 /* Demodulate sequence number */
4868 seq = ntohl(th.th_seq) - src->seqdiff;
4870 pf_change_a(&th.th_seq, icmpsum,
4875 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4876 (!SEQ_GEQ(src->seqhi, seq) ||
4877 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4878 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4879 printf("pf: BAD ICMP %d:%d ",
4880 icmptype, icmpcode);
4881 pf_print_host(pd->src, 0, pd->af);
4883 pf_print_host(pd->dst, 0, pd->af);
4885 pf_print_state(*state);
4886 printf(" seq=%u\n", seq);
4888 REASON_SET(reason, PFRES_BADSTATE);
4891 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4892 printf("pf: OK ICMP %d:%d ",
4893 icmptype, icmpcode);
4894 pf_print_host(pd->src, 0, pd->af);
4896 pf_print_host(pd->dst, 0, pd->af);
4898 pf_print_state(*state);
4899 printf(" seq=%u\n", seq);
4903 /* translate source/destination address, if necessary */
4904 if ((*state)->key[PF_SK_WIRE] !=
4905 (*state)->key[PF_SK_STACK]) {
4906 struct pf_state_key *nk =
4907 (*state)->key[pd->didx];
4909 if (PF_ANEQ(pd2.src,
4910 &nk->addr[pd2.sidx], pd2.af) ||
4911 nk->port[pd2.sidx] != th.th_sport)
4912 pf_change_icmp(pd2.src, &th.th_sport,
4913 daddr, &nk->addr[pd2.sidx],
4914 nk->port[pd2.sidx], NULL,
4915 pd2.ip_sum, icmpsum,
4916 pd->ip_sum, 0, pd2.af);
4918 if (PF_ANEQ(pd2.dst,
4919 &nk->addr[pd2.didx], pd2.af) ||
4920 nk->port[pd2.didx] != th.th_dport)
4921 pf_change_icmp(pd2.dst, &th.th_dport,
4922 saddr, &nk->addr[pd2.didx],
4923 nk->port[pd2.didx], NULL,
4924 pd2.ip_sum, icmpsum,
4925 pd->ip_sum, 0, pd2.af);
4933 m_copyback(m, off, ICMP_MINLEN,
4934 (caddr_t )pd->hdr.icmp);
4935 m_copyback(m, ipoff2, sizeof(h2),
4942 sizeof(struct icmp6_hdr),
4943 (caddr_t )pd->hdr.icmp6);
4944 m_copyback(m, ipoff2, sizeof(h2_6),
4949 m_copyback(m, off2, 8, (caddr_t)&th);
4958 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4959 NULL, reason, pd2.af)) {
4960 DPFPRINTF(PF_DEBUG_MISC,
4961 ("pf: ICMP error message too short "
4967 key.proto = IPPROTO_UDP;
4968 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4969 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4970 key.port[pd2.sidx] = uh.uh_sport;
4971 key.port[pd2.didx] = uh.uh_dport;
4973 STATE_LOOKUP(kif, &key, direction, *state, pd);
4975 /* translate source/destination address, if necessary */
4976 if ((*state)->key[PF_SK_WIRE] !=
4977 (*state)->key[PF_SK_STACK]) {
4978 struct pf_state_key *nk =
4979 (*state)->key[pd->didx];
4981 if (PF_ANEQ(pd2.src,
4982 &nk->addr[pd2.sidx], pd2.af) ||
4983 nk->port[pd2.sidx] != uh.uh_sport)
4984 pf_change_icmp(pd2.src, &uh.uh_sport,
4985 daddr, &nk->addr[pd2.sidx],
4986 nk->port[pd2.sidx], &uh.uh_sum,
4987 pd2.ip_sum, icmpsum,
4988 pd->ip_sum, 1, pd2.af);
4990 if (PF_ANEQ(pd2.dst,
4991 &nk->addr[pd2.didx], pd2.af) ||
4992 nk->port[pd2.didx] != uh.uh_dport)
4993 pf_change_icmp(pd2.dst, &uh.uh_dport,
4994 saddr, &nk->addr[pd2.didx],
4995 nk->port[pd2.didx], &uh.uh_sum,
4996 pd2.ip_sum, icmpsum,
4997 pd->ip_sum, 1, pd2.af);
5002 m_copyback(m, off, ICMP_MINLEN,
5003 (caddr_t )pd->hdr.icmp);
5004 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5010 sizeof(struct icmp6_hdr),
5011 (caddr_t )pd->hdr.icmp6);
5012 m_copyback(m, ipoff2, sizeof(h2_6),
5017 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5023 case IPPROTO_ICMP: {
5026 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5027 NULL, reason, pd2.af)) {
5028 DPFPRINTF(PF_DEBUG_MISC,
5029 ("pf: ICMP error message too short i"
5035 key.proto = IPPROTO_ICMP;
5036 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5037 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5038 key.port[0] = key.port[1] = iih.icmp_id;
5040 STATE_LOOKUP(kif, &key, direction, *state, pd);
5042 /* translate source/destination address, if necessary */
5043 if ((*state)->key[PF_SK_WIRE] !=
5044 (*state)->key[PF_SK_STACK]) {
5045 struct pf_state_key *nk =
5046 (*state)->key[pd->didx];
5048 if (PF_ANEQ(pd2.src,
5049 &nk->addr[pd2.sidx], pd2.af) ||
5050 nk->port[pd2.sidx] != iih.icmp_id)
5051 pf_change_icmp(pd2.src, &iih.icmp_id,
5052 daddr, &nk->addr[pd2.sidx],
5053 nk->port[pd2.sidx], NULL,
5054 pd2.ip_sum, icmpsum,
5055 pd->ip_sum, 0, AF_INET);
5057 if (PF_ANEQ(pd2.dst,
5058 &nk->addr[pd2.didx], pd2.af) ||
5059 nk->port[pd2.didx] != iih.icmp_id)
5060 pf_change_icmp(pd2.dst, &iih.icmp_id,
5061 saddr, &nk->addr[pd2.didx],
5062 nk->port[pd2.didx], NULL,
5063 pd2.ip_sum, icmpsum,
5064 pd->ip_sum, 0, AF_INET);
5066 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5067 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5068 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5075 case IPPROTO_ICMPV6: {
5076 struct icmp6_hdr iih;
5078 if (!pf_pull_hdr(m, off2, &iih,
5079 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5080 DPFPRINTF(PF_DEBUG_MISC,
5081 ("pf: ICMP error message too short "
5087 key.proto = IPPROTO_ICMPV6;
5088 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5089 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5090 key.port[0] = key.port[1] = iih.icmp6_id;
5092 STATE_LOOKUP(kif, &key, direction, *state, pd);
5094 /* translate source/destination address, if necessary */
5095 if ((*state)->key[PF_SK_WIRE] !=
5096 (*state)->key[PF_SK_STACK]) {
5097 struct pf_state_key *nk =
5098 (*state)->key[pd->didx];
5100 if (PF_ANEQ(pd2.src,
5101 &nk->addr[pd2.sidx], pd2.af) ||
5102 nk->port[pd2.sidx] != iih.icmp6_id)
5103 pf_change_icmp(pd2.src, &iih.icmp6_id,
5104 daddr, &nk->addr[pd2.sidx],
5105 nk->port[pd2.sidx], NULL,
5106 pd2.ip_sum, icmpsum,
5107 pd->ip_sum, 0, AF_INET6);
5109 if (PF_ANEQ(pd2.dst,
5110 &nk->addr[pd2.didx], pd2.af) ||
5111 nk->port[pd2.didx] != iih.icmp6_id)
5112 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5113 saddr, &nk->addr[pd2.didx],
5114 nk->port[pd2.didx], NULL,
5115 pd2.ip_sum, icmpsum,
5116 pd->ip_sum, 0, AF_INET6);
5118 m_copyback(m, off, sizeof(struct icmp6_hdr),
5119 (caddr_t)pd->hdr.icmp6);
5120 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5121 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5130 key.proto = pd2.proto;
5131 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5132 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5133 key.port[0] = key.port[1] = 0;
5135 STATE_LOOKUP(kif, &key, direction, *state, pd);
5137 /* translate source/destination address, if necessary */
5138 if ((*state)->key[PF_SK_WIRE] !=
5139 (*state)->key[PF_SK_STACK]) {
5140 struct pf_state_key *nk =
5141 (*state)->key[pd->didx];
5143 if (PF_ANEQ(pd2.src,
5144 &nk->addr[pd2.sidx], pd2.af))
5145 pf_change_icmp(pd2.src, NULL, daddr,
5146 &nk->addr[pd2.sidx], 0, NULL,
5147 pd2.ip_sum, icmpsum,
5148 pd->ip_sum, 0, pd2.af);
5150 if (PF_ANEQ(pd2.dst,
5151 &nk->addr[pd2.didx], pd2.af))
5152 pf_change_icmp(pd2.dst, NULL, saddr,
5153 &nk->addr[pd2.didx], 0, NULL,
5154 pd2.ip_sum, icmpsum,
5155 pd->ip_sum, 0, pd2.af);
5160 m_copyback(m, off, ICMP_MINLEN,
5161 (caddr_t)pd->hdr.icmp);
5162 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5168 sizeof(struct icmp6_hdr),
5169 (caddr_t )pd->hdr.icmp6);
5170 m_copyback(m, ipoff2, sizeof(h2_6),
5184 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5185 struct mbuf *m, struct pf_pdesc *pd)
5187 struct pf_state_peer *src, *dst;
5188 struct pf_state_key_cmp key;
5190 bzero(&key, sizeof(key));
5192 key.proto = pd->proto;
5193 if (direction == PF_IN) {
5194 PF_ACPY(&key.addr[0], pd->src, key.af);
5195 PF_ACPY(&key.addr[1], pd->dst, key.af);
5196 key.port[0] = key.port[1] = 0;
5198 PF_ACPY(&key.addr[1], pd->src, key.af);
5199 PF_ACPY(&key.addr[0], pd->dst, key.af);
5200 key.port[1] = key.port[0] = 0;
5203 STATE_LOOKUP(kif, &key, direction, *state, pd);
5205 if (direction == (*state)->direction) {
5206 src = &(*state)->src;
5207 dst = &(*state)->dst;
5209 src = &(*state)->dst;
5210 dst = &(*state)->src;
5214 if (src->state < PFOTHERS_SINGLE)
5215 src->state = PFOTHERS_SINGLE;
5216 if (dst->state == PFOTHERS_SINGLE)
5217 dst->state = PFOTHERS_MULTIPLE;
5219 /* update expire time */
5220 (*state)->expire = time_uptime;
5221 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5222 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5224 (*state)->timeout = PFTM_OTHER_SINGLE;
5226 /* translate source/destination address, if necessary */
5227 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5228 struct pf_state_key *nk = (*state)->key[pd->didx];
5230 KASSERT(nk, ("%s: nk is null", __func__));
5231 KASSERT(pd, ("%s: pd is null", __func__));
5232 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5233 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5237 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5238 pf_change_a(&pd->src->v4.s_addr,
5240 nk->addr[pd->sidx].v4.s_addr,
5244 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5245 pf_change_a(&pd->dst->v4.s_addr,
5247 nk->addr[pd->didx].v4.s_addr,
5254 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5255 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5257 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5258 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5266 * ipoff and off are measured from the start of the mbuf chain.
5267 * h must be at "ipoff" on the mbuf chain.
5270 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5271 u_short *actionp, u_short *reasonp, sa_family_t af)
5276 struct ip *h = mtod(m, struct ip *);
5277 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5281 ACTION_SET(actionp, PF_PASS);
5283 ACTION_SET(actionp, PF_DROP);
5284 REASON_SET(reasonp, PFRES_FRAG);
5288 if (m->m_pkthdr.len < off + len ||
5289 ntohs(h->ip_len) < off + len) {
5290 ACTION_SET(actionp, PF_DROP);
5291 REASON_SET(reasonp, PFRES_SHORT);
5299 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5301 if (m->m_pkthdr.len < off + len ||
5302 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5303 (unsigned)(off + len)) {
5304 ACTION_SET(actionp, PF_DROP);
5305 REASON_SET(reasonp, PFRES_SHORT);
5312 m_copydata(m, off, len, p);
5318 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5321 struct radix_node_head *rnh;
5322 struct sockaddr_in *dst;
5326 struct sockaddr_in6 *dst6;
5327 struct route_in6 ro;
5331 struct radix_node *rn;
5336 /* XXX: stick to table 0 for now */
5337 rnh = rt_tables_get_rnh(0, af);
5338 if (rnh != NULL && rn_mpath_capable(rnh))
5340 bzero(&ro, sizeof(ro));
5343 dst = satosin(&ro.ro_dst);
5344 dst->sin_family = AF_INET;
5345 dst->sin_len = sizeof(*dst);
5346 dst->sin_addr = addr->v4;
5351 * Skip check for addresses with embedded interface scope,
5352 * as they would always match anyway.
5354 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5356 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5357 dst6->sin6_family = AF_INET6;
5358 dst6->sin6_len = sizeof(*dst6);
5359 dst6->sin6_addr = addr->v6;
5366 /* Skip checks for ipsec interfaces */
5367 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5373 in6_rtalloc_ign(&ro, 0, rtableid);
5378 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5383 if (ro.ro_rt != NULL) {
5384 /* No interface given, this is a no-route check */
5388 if (kif->pfik_ifp == NULL) {
5393 /* Perform uRPF check if passed input interface */
5395 rn = (struct radix_node *)ro.ro_rt;
5397 rt = (struct rtentry *)rn;
5400 if (kif->pfik_ifp == ifp)
5402 rn = rn_mpath_next(rn);
5403 } while (check_mpath == 1 && rn != NULL && ret == 0);
5407 if (ro.ro_rt != NULL)
5414 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5418 struct nhop4_basic nh4;
5421 struct nhop6_basic nh6;
5425 struct radix_node_head *rnh;
5427 /* XXX: stick to table 0 for now */
5428 rnh = rt_tables_get_rnh(0, af);
5429 if (rnh != NULL && rn_mpath_capable(rnh))
5430 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5433 * Skip check for addresses with embedded interface scope,
5434 * as they would always match anyway.
5436 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5439 if (af != AF_INET && af != AF_INET6)
5442 /* Skip checks for ipsec interfaces */
5443 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5451 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5458 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5465 /* No interface given, this is a no-route check */
5469 if (kif->pfik_ifp == NULL)
5472 /* Perform uRPF check if passed input interface */
5473 if (kif->pfik_ifp == ifp)
5480 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5481 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5483 struct mbuf *m0, *m1;
5484 struct sockaddr_in dst;
5486 struct ifnet *ifp = NULL;
5487 struct pf_addr naddr;
5488 struct pf_src_node *sn = NULL;
5490 uint16_t ip_len, ip_off;
5492 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5493 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5496 if ((pd->pf_mtag == NULL &&
5497 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5498 pd->pf_mtag->routed++ > 3) {
5504 if (r->rt == PF_DUPTO) {
5505 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5511 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5519 ip = mtod(m0, struct ip *);
5521 bzero(&dst, sizeof(dst));
5522 dst.sin_family = AF_INET;
5523 dst.sin_len = sizeof(dst);
5524 dst.sin_addr = ip->ip_dst;
5526 if (r->rt == PF_FASTROUTE) {
5527 struct nhop4_basic nh4;
5532 if (fib4_lookup_nh_basic(M_GETFIB(m0), ip->ip_dst, 0,
5533 m0->m_pkthdr.flowid, &nh4) != 0) {
5534 KMOD_IPSTAT_INC(ips_noroute);
5535 error = EHOSTUNREACH;
5540 dst.sin_addr = nh4.nh_addr;
5542 bzero(&naddr, sizeof(naddr));
5544 if (TAILQ_EMPTY(&r->rpool.list)) {
5545 DPFPRINTF(PF_DEBUG_URGENT,
5546 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5550 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5552 if (!PF_AZERO(&naddr, AF_INET))
5553 dst.sin_addr.s_addr = naddr.v4.s_addr;
5554 ifp = r->rpool.cur->kif ?
5555 r->rpool.cur->kif->pfik_ifp : NULL;
5557 if (!PF_AZERO(&s->rt_addr, AF_INET))
5558 dst.sin_addr.s_addr =
5559 s->rt_addr.v4.s_addr;
5560 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5568 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5570 else if (m0 == NULL)
5572 if (m0->m_len < sizeof(struct ip)) {
5573 DPFPRINTF(PF_DEBUG_URGENT,
5574 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5577 ip = mtod(m0, struct ip *);
5580 if (ifp->if_flags & IFF_LOOPBACK)
5581 m0->m_flags |= M_SKIP_FIREWALL;
5583 ip_len = ntohs(ip->ip_len);
5584 ip_off = ntohs(ip->ip_off);
5586 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5587 m0->m_pkthdr.csum_flags |= CSUM_IP;
5588 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5589 in_delayed_cksum(m0);
5590 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5593 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5594 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5595 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5600 * If small enough for interface, or the interface will take
5601 * care of the fragmentation for us, we can just send directly.
5603 if (ip_len <= ifp->if_mtu ||
5604 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5606 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5607 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5608 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5610 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5611 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5615 /* Balk when DF bit is set or the interface didn't support TSO. */
5616 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5618 KMOD_IPSTAT_INC(ips_cantfrag);
5619 if (r->rt != PF_DUPTO) {
5620 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5627 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5631 for (; m0; m0 = m1) {
5633 m0->m_nextpkt = NULL;
5635 m_clrprotoflags(m0);
5636 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5642 KMOD_IPSTAT_INC(ips_fragmented);
5645 if (r->rt != PF_DUPTO)
5660 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5661 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5664 struct sockaddr_in6 dst;
5665 struct ip6_hdr *ip6;
5666 struct ifnet *ifp = NULL;
5667 struct pf_addr naddr;
5668 struct pf_src_node *sn = NULL;
5670 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5671 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5674 if ((pd->pf_mtag == NULL &&
5675 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5676 pd->pf_mtag->routed++ > 3) {
5682 if (r->rt == PF_DUPTO) {
5683 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5689 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5697 ip6 = mtod(m0, struct ip6_hdr *);
5699 bzero(&dst, sizeof(dst));
5700 dst.sin6_family = AF_INET6;
5701 dst.sin6_len = sizeof(dst);
5702 dst.sin6_addr = ip6->ip6_dst;
5704 /* Cheat. XXX why only in the v6 case??? */
5705 if (r->rt == PF_FASTROUTE) {
5708 m0->m_flags |= M_SKIP_FIREWALL;
5709 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5714 bzero(&naddr, sizeof(naddr));
5716 if (TAILQ_EMPTY(&r->rpool.list)) {
5717 DPFPRINTF(PF_DEBUG_URGENT,
5718 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5722 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5724 if (!PF_AZERO(&naddr, AF_INET6))
5725 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5727 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5729 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5730 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5731 &s->rt_addr, AF_INET6);
5732 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5742 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5744 else if (m0 == NULL)
5746 if (m0->m_len < sizeof(struct ip6_hdr)) {
5747 DPFPRINTF(PF_DEBUG_URGENT,
5748 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5752 ip6 = mtod(m0, struct ip6_hdr *);
5755 if (ifp->if_flags & IFF_LOOPBACK)
5756 m0->m_flags |= M_SKIP_FIREWALL;
5758 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5759 ~ifp->if_hwassist) {
5760 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5761 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5762 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5766 * If the packet is too large for the outgoing interface,
5767 * send back an icmp6 error.
5769 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5770 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5771 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5772 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5774 in6_ifstat_inc(ifp, ifs6_in_toobig);
5775 if (r->rt != PF_DUPTO)
5776 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5782 if (r->rt != PF_DUPTO)
5796 * FreeBSD supports cksum offloads for the following drivers.
5797 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5798 * ti(4), txp(4), xl(4)
5800 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5801 * network driver performed cksum including pseudo header, need to verify
5804 * network driver performed cksum, needs to additional pseudo header
5805 * cksum computation with partial csum_data(i.e. lack of H/W support for
5806 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5808 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5809 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5811 * Also, set csum_data to 0xffff to force cksum validation.
5814 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5820 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5822 if (m->m_pkthdr.len < off + len)
5827 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5828 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5829 sum = m->m_pkthdr.csum_data;
5831 ip = mtod(m, struct ip *);
5832 sum = in_pseudo(ip->ip_src.s_addr,
5833 ip->ip_dst.s_addr, htonl((u_short)len +
5834 m->m_pkthdr.csum_data + IPPROTO_TCP));
5841 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5842 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5843 sum = m->m_pkthdr.csum_data;
5845 ip = mtod(m, struct ip *);
5846 sum = in_pseudo(ip->ip_src.s_addr,
5847 ip->ip_dst.s_addr, htonl((u_short)len +
5848 m->m_pkthdr.csum_data + IPPROTO_UDP));
5856 case IPPROTO_ICMPV6:
5866 if (p == IPPROTO_ICMP) {
5871 sum = in_cksum(m, len);
5875 if (m->m_len < sizeof(struct ip))
5877 sum = in4_cksum(m, p, off, len);
5882 if (m->m_len < sizeof(struct ip6_hdr))
5884 sum = in6_cksum(m, p, off, len);
5895 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5900 KMOD_UDPSTAT_INC(udps_badsum);
5906 KMOD_ICMPSTAT_INC(icps_checksum);
5911 case IPPROTO_ICMPV6:
5913 KMOD_ICMP6STAT_INC(icp6s_checksum);
5920 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5921 m->m_pkthdr.csum_flags |=
5922 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5923 m->m_pkthdr.csum_data = 0xffff;
5932 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5934 struct pfi_kif *kif;
5935 u_short action, reason = 0, log = 0;
5936 struct mbuf *m = *m0;
5937 struct ip *h = NULL;
5938 struct m_tag *ipfwtag;
5939 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5940 struct pf_state *s = NULL;
5941 struct pf_ruleset *ruleset = NULL;
5943 int off, dirndx, pqid = 0;
5945 PF_RULES_RLOCK_TRACKER;
5949 if (!V_pf_status.running)
5952 memset(&pd, 0, sizeof(pd));
5954 kif = (struct pfi_kif *)ifp->if_pf_kif;
5957 DPFPRINTF(PF_DEBUG_URGENT,
5958 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5961 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5964 if (m->m_flags & M_SKIP_FIREWALL)
5967 pd.pf_mtag = pf_find_mtag(m);
5971 if (ip_divert_ptr != NULL &&
5972 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5973 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5974 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5975 if (pd.pf_mtag == NULL &&
5976 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5980 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5981 m_tag_delete(m, ipfwtag);
5983 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5984 m->m_flags |= M_FASTFWD_OURS;
5985 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5987 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5988 /* We do IP header normalization and packet reassembly here */
5992 m = *m0; /* pf_normalize messes with m0 */
5993 h = mtod(m, struct ip *);
5995 off = h->ip_hl << 2;
5996 if (off < (int)sizeof(struct ip)) {
5998 REASON_SET(&reason, PFRES_SHORT);
6003 pd.src = (struct pf_addr *)&h->ip_src;
6004 pd.dst = (struct pf_addr *)&h->ip_dst;
6005 pd.sport = pd.dport = NULL;
6006 pd.ip_sum = &h->ip_sum;
6007 pd.proto_sum = NULL;
6010 pd.sidx = (dir == PF_IN) ? 0 : 1;
6011 pd.didx = (dir == PF_IN) ? 1 : 0;
6014 pd.tot_len = ntohs(h->ip_len);
6016 /* handle fragments that didn't get reassembled by normalization */
6017 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
6018 action = pf_test_fragment(&r, dir, kif, m, h,
6029 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6030 &action, &reason, AF_INET)) {
6031 log = action != PF_PASS;
6034 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6035 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6037 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6038 if (action == PF_DROP)
6040 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6042 if (action == PF_PASS) {
6043 if (V_pfsync_update_state_ptr != NULL)
6044 V_pfsync_update_state_ptr(s);
6048 } else if (s == NULL)
6049 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6058 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6059 &action, &reason, AF_INET)) {
6060 log = action != PF_PASS;
6063 if (uh.uh_dport == 0 ||
6064 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6065 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6067 REASON_SET(&reason, PFRES_SHORT);
6070 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6071 if (action == PF_PASS) {
6072 if (V_pfsync_update_state_ptr != NULL)
6073 V_pfsync_update_state_ptr(s);
6077 } else if (s == NULL)
6078 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6083 case IPPROTO_ICMP: {
6087 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6088 &action, &reason, AF_INET)) {
6089 log = action != PF_PASS;
6092 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6094 if (action == PF_PASS) {
6095 if (V_pfsync_update_state_ptr != NULL)
6096 V_pfsync_update_state_ptr(s);
6100 } else if (s == NULL)
6101 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6107 case IPPROTO_ICMPV6: {
6109 DPFPRINTF(PF_DEBUG_MISC,
6110 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6116 action = pf_test_state_other(&s, dir, kif, m, &pd);
6117 if (action == PF_PASS) {
6118 if (V_pfsync_update_state_ptr != NULL)
6119 V_pfsync_update_state_ptr(s);
6123 } else if (s == NULL)
6124 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6131 if (action == PF_PASS && h->ip_hl > 5 &&
6132 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6134 REASON_SET(&reason, PFRES_IPOPTIONS);
6136 DPFPRINTF(PF_DEBUG_MISC,
6137 ("pf: dropping packet with ip options\n"));
6140 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6142 REASON_SET(&reason, PFRES_MEMORY);
6144 if (r->rtableid >= 0)
6145 M_SETFIB(m, r->rtableid);
6147 if (r->scrub_flags & PFSTATE_SETPRIO) {
6148 if (pd.tos & IPTOS_LOWDELAY)
6150 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6152 REASON_SET(&reason, PFRES_MEMORY);
6154 DPFPRINTF(PF_DEBUG_MISC,
6155 ("pf: failed to allocate 802.1q mtag\n"));
6160 if (action == PF_PASS && r->qid) {
6161 if (pd.pf_mtag == NULL &&
6162 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6164 REASON_SET(&reason, PFRES_MEMORY);
6167 pd.pf_mtag->qid_hash = pf_state_hash(s);
6168 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6169 pd.pf_mtag->qid = r->pqid;
6171 pd.pf_mtag->qid = r->qid;
6172 /* Add hints for ecn. */
6173 pd.pf_mtag->hdr = h;
6180 * connections redirected to loopback should not match sockets
6181 * bound specifically to loopback due to security implications,
6182 * see tcp_input() and in_pcblookup_listen().
6184 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6185 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6186 (s->nat_rule.ptr->action == PF_RDR ||
6187 s->nat_rule.ptr->action == PF_BINAT) &&
6188 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6189 m->m_flags |= M_SKIP_FIREWALL;
6191 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6192 !PACKET_LOOPED(&pd)) {
6194 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6195 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6196 if (ipfwtag != NULL) {
6197 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6198 ntohs(r->divert.port);
6199 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6204 m_tag_prepend(m, ipfwtag);
6205 if (m->m_flags & M_FASTFWD_OURS) {
6206 if (pd.pf_mtag == NULL &&
6207 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6209 REASON_SET(&reason, PFRES_MEMORY);
6211 DPFPRINTF(PF_DEBUG_MISC,
6212 ("pf: failed to allocate tag\n"));
6214 pd.pf_mtag->flags |=
6215 PF_FASTFWD_OURS_PRESENT;
6216 m->m_flags &= ~M_FASTFWD_OURS;
6219 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6224 /* XXX: ipfw has the same behaviour! */
6226 REASON_SET(&reason, PFRES_MEMORY);
6228 DPFPRINTF(PF_DEBUG_MISC,
6229 ("pf: failed to allocate divert tag\n"));
6236 if (s != NULL && s->nat_rule.ptr != NULL &&
6237 s->nat_rule.ptr->log & PF_LOG_ALL)
6238 lr = s->nat_rule.ptr;
6241 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6245 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6246 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6248 if (action == PF_PASS || r->action == PF_DROP) {
6249 dirndx = (dir == PF_OUT);
6250 r->packets[dirndx]++;
6251 r->bytes[dirndx] += pd.tot_len;
6253 a->packets[dirndx]++;
6254 a->bytes[dirndx] += pd.tot_len;
6257 if (s->nat_rule.ptr != NULL) {
6258 s->nat_rule.ptr->packets[dirndx]++;
6259 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6261 if (s->src_node != NULL) {
6262 s->src_node->packets[dirndx]++;
6263 s->src_node->bytes[dirndx] += pd.tot_len;
6265 if (s->nat_src_node != NULL) {
6266 s->nat_src_node->packets[dirndx]++;
6267 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6269 dirndx = (dir == s->direction) ? 0 : 1;
6270 s->packets[dirndx]++;
6271 s->bytes[dirndx] += pd.tot_len;
6274 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6275 if (nr != NULL && r == &V_pf_default_rule)
6277 if (tr->src.addr.type == PF_ADDR_TABLE)
6278 pfr_update_stats(tr->src.addr.p.tbl,
6279 (s == NULL) ? pd.src :
6280 &s->key[(s->direction == PF_IN)]->
6281 addr[(s->direction == PF_OUT)],
6282 pd.af, pd.tot_len, dir == PF_OUT,
6283 r->action == PF_PASS, tr->src.neg);
6284 if (tr->dst.addr.type == PF_ADDR_TABLE)
6285 pfr_update_stats(tr->dst.addr.p.tbl,
6286 (s == NULL) ? pd.dst :
6287 &s->key[(s->direction == PF_IN)]->
6288 addr[(s->direction == PF_IN)],
6289 pd.af, pd.tot_len, dir == PF_OUT,
6290 r->action == PF_PASS, tr->dst.neg);
6294 case PF_SYNPROXY_DROP:
6305 /* pf_route() returns unlocked. */
6307 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6321 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6323 struct pfi_kif *kif;
6324 u_short action, reason = 0, log = 0;
6325 struct mbuf *m = *m0, *n = NULL;
6327 struct ip6_hdr *h = NULL;
6328 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6329 struct pf_state *s = NULL;
6330 struct pf_ruleset *ruleset = NULL;
6332 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6334 PF_RULES_RLOCK_TRACKER;
6337 if (!V_pf_status.running)
6340 memset(&pd, 0, sizeof(pd));
6341 pd.pf_mtag = pf_find_mtag(m);
6343 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6346 kif = (struct pfi_kif *)ifp->if_pf_kif;
6348 DPFPRINTF(PF_DEBUG_URGENT,
6349 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6352 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6355 if (m->m_flags & M_SKIP_FIREWALL)
6360 /* We do IP header normalization and packet reassembly here */
6361 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6365 m = *m0; /* pf_normalize messes with m0 */
6366 h = mtod(m, struct ip6_hdr *);
6370 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6371 * will do something bad, so drop the packet for now.
6373 if (htons(h->ip6_plen) == 0) {
6375 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6380 pd.src = (struct pf_addr *)&h->ip6_src;
6381 pd.dst = (struct pf_addr *)&h->ip6_dst;
6382 pd.sport = pd.dport = NULL;
6384 pd.proto_sum = NULL;
6386 pd.sidx = (dir == PF_IN) ? 0 : 1;
6387 pd.didx = (dir == PF_IN) ? 1 : 0;
6390 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6392 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6393 pd.proto = h->ip6_nxt;
6396 case IPPROTO_FRAGMENT:
6397 action = pf_test_fragment(&r, dir, kif, m, h,
6399 if (action == PF_DROP)
6400 REASON_SET(&reason, PFRES_FRAG);
6402 case IPPROTO_ROUTING: {
6403 struct ip6_rthdr rthdr;
6406 DPFPRINTF(PF_DEBUG_MISC,
6407 ("pf: IPv6 more than one rthdr\n"));
6409 REASON_SET(&reason, PFRES_IPOPTIONS);
6413 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6415 DPFPRINTF(PF_DEBUG_MISC,
6416 ("pf: IPv6 short rthdr\n"));
6418 REASON_SET(&reason, PFRES_SHORT);
6422 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6423 DPFPRINTF(PF_DEBUG_MISC,
6424 ("pf: IPv6 rthdr0\n"));
6426 REASON_SET(&reason, PFRES_IPOPTIONS);
6433 case IPPROTO_HOPOPTS:
6434 case IPPROTO_DSTOPTS: {
6435 /* get next header and header length */
6436 struct ip6_ext opt6;
6438 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6439 NULL, &reason, pd.af)) {
6440 DPFPRINTF(PF_DEBUG_MISC,
6441 ("pf: IPv6 short opt\n"));
6446 if (pd.proto == IPPROTO_AH)
6447 off += (opt6.ip6e_len + 2) * 4;
6449 off += (opt6.ip6e_len + 1) * 8;
6450 pd.proto = opt6.ip6e_nxt;
6451 /* goto the next header */
6458 } while (!terminal);
6460 /* if there's no routing header, use unmodified mbuf for checksumming */
6470 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6471 &action, &reason, AF_INET6)) {
6472 log = action != PF_PASS;
6475 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6476 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6477 if (action == PF_DROP)
6479 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6481 if (action == PF_PASS) {
6482 if (V_pfsync_update_state_ptr != NULL)
6483 V_pfsync_update_state_ptr(s);
6487 } else if (s == NULL)
6488 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6497 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6498 &action, &reason, AF_INET6)) {
6499 log = action != PF_PASS;
6502 if (uh.uh_dport == 0 ||
6503 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6504 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6506 REASON_SET(&reason, PFRES_SHORT);
6509 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6510 if (action == PF_PASS) {
6511 if (V_pfsync_update_state_ptr != NULL)
6512 V_pfsync_update_state_ptr(s);
6516 } else if (s == NULL)
6517 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6522 case IPPROTO_ICMP: {
6524 DPFPRINTF(PF_DEBUG_MISC,
6525 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6529 case IPPROTO_ICMPV6: {
6530 struct icmp6_hdr ih;
6533 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6534 &action, &reason, AF_INET6)) {
6535 log = action != PF_PASS;
6538 action = pf_test_state_icmp(&s, dir, kif,
6539 m, off, h, &pd, &reason);
6540 if (action == PF_PASS) {
6541 if (V_pfsync_update_state_ptr != NULL)
6542 V_pfsync_update_state_ptr(s);
6546 } else if (s == NULL)
6547 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6553 action = pf_test_state_other(&s, dir, kif, m, &pd);
6554 if (action == PF_PASS) {
6555 if (V_pfsync_update_state_ptr != NULL)
6556 V_pfsync_update_state_ptr(s);
6560 } else if (s == NULL)
6561 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6573 /* handle dangerous IPv6 extension headers. */
6574 if (action == PF_PASS && rh_cnt &&
6575 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6577 REASON_SET(&reason, PFRES_IPOPTIONS);
6579 DPFPRINTF(PF_DEBUG_MISC,
6580 ("pf: dropping packet with dangerous v6 headers\n"));
6583 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6585 REASON_SET(&reason, PFRES_MEMORY);
6587 if (r->rtableid >= 0)
6588 M_SETFIB(m, r->rtableid);
6590 if (r->scrub_flags & PFSTATE_SETPRIO) {
6591 if (pd.tos & IPTOS_LOWDELAY)
6593 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6595 REASON_SET(&reason, PFRES_MEMORY);
6597 DPFPRINTF(PF_DEBUG_MISC,
6598 ("pf: failed to allocate 802.1q mtag\n"));
6603 if (action == PF_PASS && r->qid) {
6604 if (pd.pf_mtag == NULL &&
6605 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6607 REASON_SET(&reason, PFRES_MEMORY);
6610 pd.pf_mtag->qid_hash = pf_state_hash(s);
6611 if (pd.tos & IPTOS_LOWDELAY)
6612 pd.pf_mtag->qid = r->pqid;
6614 pd.pf_mtag->qid = r->qid;
6615 /* Add hints for ecn. */
6616 pd.pf_mtag->hdr = h;
6621 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6622 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6623 (s->nat_rule.ptr->action == PF_RDR ||
6624 s->nat_rule.ptr->action == PF_BINAT) &&
6625 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6626 m->m_flags |= M_SKIP_FIREWALL;
6628 /* XXX: Anybody working on it?! */
6630 printf("pf: divert(9) is not supported for IPv6\n");
6635 if (s != NULL && s->nat_rule.ptr != NULL &&
6636 s->nat_rule.ptr->log & PF_LOG_ALL)
6637 lr = s->nat_rule.ptr;
6640 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6644 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6645 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6647 if (action == PF_PASS || r->action == PF_DROP) {
6648 dirndx = (dir == PF_OUT);
6649 r->packets[dirndx]++;
6650 r->bytes[dirndx] += pd.tot_len;
6652 a->packets[dirndx]++;
6653 a->bytes[dirndx] += pd.tot_len;
6656 if (s->nat_rule.ptr != NULL) {
6657 s->nat_rule.ptr->packets[dirndx]++;
6658 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6660 if (s->src_node != NULL) {
6661 s->src_node->packets[dirndx]++;
6662 s->src_node->bytes[dirndx] += pd.tot_len;
6664 if (s->nat_src_node != NULL) {
6665 s->nat_src_node->packets[dirndx]++;
6666 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6668 dirndx = (dir == s->direction) ? 0 : 1;
6669 s->packets[dirndx]++;
6670 s->bytes[dirndx] += pd.tot_len;
6673 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6674 if (nr != NULL && r == &V_pf_default_rule)
6676 if (tr->src.addr.type == PF_ADDR_TABLE)
6677 pfr_update_stats(tr->src.addr.p.tbl,
6678 (s == NULL) ? pd.src :
6679 &s->key[(s->direction == PF_IN)]->addr[0],
6680 pd.af, pd.tot_len, dir == PF_OUT,
6681 r->action == PF_PASS, tr->src.neg);
6682 if (tr->dst.addr.type == PF_ADDR_TABLE)
6683 pfr_update_stats(tr->dst.addr.p.tbl,
6684 (s == NULL) ? pd.dst :
6685 &s->key[(s->direction == PF_IN)]->addr[1],
6686 pd.af, pd.tot_len, dir == PF_OUT,
6687 r->action == PF_PASS, tr->dst.neg);
6691 case PF_SYNPROXY_DROP:
6702 /* pf_route6() returns unlocked. */
6704 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6713 /* If reassembled packet passed, create new fragments. */
6714 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6715 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6716 action = pf_refragment6(ifp, m0, mtag);