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>
71 #include <net/pfvar.h>
72 #include <net/if_pflog.h>
73 #include <net/if_pfsync.h>
75 #include <netinet/in_pcb.h>
76 #include <netinet/in_var.h>
77 #include <netinet/in_fib.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_fw.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/icmp_var.h>
82 #include <netinet/ip_var.h>
83 #include <netinet/tcp.h>
84 #include <netinet/tcp_fsm.h>
85 #include <netinet/tcp_seq.h>
86 #include <netinet/tcp_timer.h>
87 #include <netinet/tcp_var.h>
88 #include <netinet/udp.h>
89 #include <netinet/udp_var.h>
91 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
94 #include <netinet/ip6.h>
95 #include <netinet/icmp6.h>
96 #include <netinet6/nd6.h>
97 #include <netinet6/ip6_var.h>
98 #include <netinet6/in6_pcb.h>
99 #include <netinet6/in6_fib.h>
100 #include <netinet6/scope6_var.h>
103 #include <machine/in_cksum.h>
104 #include <security/mac/mac_framework.h>
106 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
113 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
114 VNET_DEFINE(struct pf_palist, pf_pabuf);
115 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
116 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
117 VNET_DEFINE(struct pf_kstatus, pf_status);
119 VNET_DEFINE(u_int32_t, ticket_altqs_active);
120 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
121 VNET_DEFINE(int, altqs_inactive_open);
122 VNET_DEFINE(u_int32_t, ticket_pabuf);
124 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
125 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
126 VNET_DEFINE(u_char, pf_tcp_secret[16]);
127 #define V_pf_tcp_secret VNET(pf_tcp_secret)
128 VNET_DEFINE(int, pf_tcp_secret_init);
129 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
130 VNET_DEFINE(int, pf_tcp_iss_off);
131 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
132 VNET_DECLARE(int, pf_vnet_active);
133 #define V_pf_vnet_active VNET(pf_vnet_active)
136 * Queue for pf_intr() sends.
138 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
139 struct pf_send_entry {
140 STAILQ_ENTRY(pf_send_entry) pfse_next;
155 STAILQ_HEAD(pf_send_head, pf_send_entry);
156 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157 #define V_pf_sendqueue VNET(pf_sendqueue)
159 static struct mtx pf_sendqueue_mtx;
160 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
161 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
162 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
165 * Queue for pf_overload_task() tasks.
167 struct pf_overload_entry {
168 SLIST_ENTRY(pf_overload_entry) next;
172 struct pf_rule *rule;
175 SLIST_HEAD(pf_overload_head, pf_overload_entry);
176 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
177 #define V_pf_overloadqueue VNET(pf_overloadqueue)
178 static VNET_DEFINE(struct task, pf_overloadtask);
179 #define V_pf_overloadtask VNET(pf_overloadtask)
181 static struct mtx pf_overloadqueue_mtx;
182 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
183 "pf overload/flush queue", MTX_DEF);
184 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
185 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
187 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
188 struct mtx pf_unlnkdrules_mtx;
189 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
192 static VNET_DEFINE(uma_zone_t, pf_sources_z);
193 #define V_pf_sources_z VNET(pf_sources_z)
194 uma_zone_t pf_mtag_z;
195 VNET_DEFINE(uma_zone_t, pf_state_z);
196 VNET_DEFINE(uma_zone_t, pf_state_key_z);
198 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
199 #define PFID_CPUBITS 8
200 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
201 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
202 #define PFID_MAXID (~PFID_CPUMASK)
203 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
205 static void pf_src_tree_remove_state(struct pf_state *);
206 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
208 static void pf_add_threshold(struct pf_threshold *);
209 static int pf_check_threshold(struct pf_threshold *);
211 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
212 u_int16_t *, u_int16_t *, struct pf_addr *,
213 u_int16_t, u_int8_t, sa_family_t);
214 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
215 struct tcphdr *, struct pf_state_peer *);
216 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
217 struct pf_addr *, struct pf_addr *, u_int16_t,
218 u_int16_t *, u_int16_t *, u_int16_t *,
219 u_int16_t *, u_int8_t, sa_family_t);
220 static void pf_send_tcp(struct mbuf *,
221 const struct pf_rule *, sa_family_t,
222 const struct pf_addr *, const struct pf_addr *,
223 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
224 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
225 u_int16_t, struct ifnet *);
226 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
227 sa_family_t, struct pf_rule *);
228 static void pf_detach_state(struct pf_state *);
229 static int pf_state_key_attach(struct pf_state_key *,
230 struct pf_state_key *, struct pf_state *);
231 static void pf_state_key_detach(struct pf_state *, int);
232 static int pf_state_key_ctor(void *, int, void *, int);
233 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
234 static int pf_test_rule(struct pf_rule **, struct pf_state **,
235 int, struct pfi_kif *, struct mbuf *, int,
236 struct pf_pdesc *, struct pf_rule **,
237 struct pf_ruleset **, struct inpcb *);
238 static int pf_create_state(struct pf_rule *, struct pf_rule *,
239 struct pf_rule *, struct pf_pdesc *,
240 struct pf_src_node *, struct pf_state_key *,
241 struct pf_state_key *, struct mbuf *, int,
242 u_int16_t, u_int16_t, int *, struct pfi_kif *,
243 struct pf_state **, int, u_int16_t, u_int16_t,
245 static int pf_test_fragment(struct pf_rule **, int,
246 struct pfi_kif *, struct mbuf *, void *,
247 struct pf_pdesc *, struct pf_rule **,
248 struct pf_ruleset **);
249 static int pf_tcp_track_full(struct pf_state_peer *,
250 struct pf_state_peer *, struct pf_state **,
251 struct pfi_kif *, struct mbuf *, int,
252 struct pf_pdesc *, u_short *, int *);
253 static int pf_tcp_track_sloppy(struct pf_state_peer *,
254 struct pf_state_peer *, struct pf_state **,
255 struct pf_pdesc *, u_short *);
256 static int pf_test_state_tcp(struct pf_state **, int,
257 struct pfi_kif *, struct mbuf *, int,
258 void *, struct pf_pdesc *, u_short *);
259 static int pf_test_state_udp(struct pf_state **, int,
260 struct pfi_kif *, struct mbuf *, int,
261 void *, struct pf_pdesc *);
262 static int pf_test_state_icmp(struct pf_state **, int,
263 struct pfi_kif *, struct mbuf *, int,
264 void *, struct pf_pdesc *, u_short *);
265 static int pf_test_state_other(struct pf_state **, int,
266 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
267 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
269 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
271 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
273 static int pf_check_proto_cksum(struct mbuf *, int, int,
274 u_int8_t, sa_family_t);
275 static void pf_print_state_parts(struct pf_state *,
276 struct pf_state_key *, struct pf_state_key *);
277 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
278 struct pf_addr_wrap *);
279 static struct pf_state *pf_find_state(struct pfi_kif *,
280 struct pf_state_key_cmp *, u_int);
281 static int pf_src_connlimit(struct pf_state **);
282 static void pf_overload_task(void *v, int pending);
283 static int pf_insert_src_node(struct pf_src_node **,
284 struct pf_rule *, struct pf_addr *, sa_family_t);
285 static u_int pf_purge_expired_states(u_int, int);
286 static void pf_purge_unlinked_rules(void);
287 static int pf_mtag_uminit(void *, int, int);
288 static void pf_mtag_free(struct m_tag *);
290 static void pf_route(struct mbuf **, struct pf_rule *, int,
291 struct ifnet *, struct pf_state *,
295 static void pf_change_a6(struct pf_addr *, u_int16_t *,
296 struct pf_addr *, u_int8_t);
297 static void pf_route6(struct mbuf **, struct pf_rule *, int,
298 struct ifnet *, struct pf_state *,
302 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
304 extern int pf_end_threads;
306 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
308 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
309 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
311 #define STATE_LOOKUP(i, k, d, s, pd) \
313 (s) = pf_find_state((i), (k), (d)); \
316 if (PACKET_LOOPED(pd)) \
318 if ((d) == PF_OUT && \
319 (((s)->rule.ptr->rt == PF_ROUTETO && \
320 (s)->rule.ptr->direction == PF_OUT) || \
321 ((s)->rule.ptr->rt == PF_REPLYTO && \
322 (s)->rule.ptr->direction == PF_IN)) && \
323 (s)->rt_kif != NULL && \
324 (s)->rt_kif != (i)) \
328 #define BOUND_IFACE(r, k) \
329 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
331 #define STATE_INC_COUNTERS(s) \
333 counter_u64_add(s->rule.ptr->states_cur, 1); \
334 counter_u64_add(s->rule.ptr->states_tot, 1); \
335 if (s->anchor.ptr != NULL) { \
336 counter_u64_add(s->anchor.ptr->states_cur, 1); \
337 counter_u64_add(s->anchor.ptr->states_tot, 1); \
339 if (s->nat_rule.ptr != NULL) { \
340 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
341 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
345 #define STATE_DEC_COUNTERS(s) \
347 if (s->nat_rule.ptr != NULL) \
348 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
349 if (s->anchor.ptr != NULL) \
350 counter_u64_add(s->anchor.ptr->states_cur, -1); \
351 counter_u64_add(s->rule.ptr->states_cur, -1); \
354 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
355 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
356 VNET_DEFINE(struct pf_idhash *, pf_idhash);
357 VNET_DEFINE(struct pf_srchash *, pf_srchash);
359 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
362 u_long pf_srchashmask;
363 static u_long pf_hashsize;
364 static u_long pf_srchashsize;
366 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
367 &pf_hashsize, 0, "Size of pf(4) states hashtable");
368 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
369 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
371 VNET_DEFINE(void *, pf_swi_cookie);
373 VNET_DEFINE(uint32_t, pf_hashseed);
374 #define V_pf_hashseed VNET(pf_hashseed)
377 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
383 if (a->addr32[0] > b->addr32[0])
385 if (a->addr32[0] < b->addr32[0])
391 if (a->addr32[3] > b->addr32[3])
393 if (a->addr32[3] < b->addr32[3])
395 if (a->addr32[2] > b->addr32[2])
397 if (a->addr32[2] < b->addr32[2])
399 if (a->addr32[1] > b->addr32[1])
401 if (a->addr32[1] < b->addr32[1])
403 if (a->addr32[0] > b->addr32[0])
405 if (a->addr32[0] < b->addr32[0])
410 panic("%s: unknown address family %u", __func__, af);
415 static __inline uint32_t
416 pf_hashkey(struct pf_state_key *sk)
420 h = murmur3_32_hash32((uint32_t *)sk,
421 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
424 return (h & pf_hashmask);
427 static __inline uint32_t
428 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
434 h = murmur3_32_hash32((uint32_t *)&addr->v4,
435 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
438 h = murmur3_32_hash32((uint32_t *)&addr->v6,
439 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
442 panic("%s: unknown address family %u", __func__, af);
445 return (h & pf_srchashmask);
450 pf_state_hash(struct pf_state *s)
452 u_int32_t hv = (intptr_t)s / sizeof(*s);
454 hv ^= crc32(&s->src, sizeof(s->src));
455 hv ^= crc32(&s->dst, sizeof(s->dst));
464 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
469 dst->addr32[0] = src->addr32[0];
473 dst->addr32[0] = src->addr32[0];
474 dst->addr32[1] = src->addr32[1];
475 dst->addr32[2] = src->addr32[2];
476 dst->addr32[3] = src->addr32[3];
483 pf_init_threshold(struct pf_threshold *threshold,
484 u_int32_t limit, u_int32_t seconds)
486 threshold->limit = limit * PF_THRESHOLD_MULT;
487 threshold->seconds = seconds;
488 threshold->count = 0;
489 threshold->last = time_uptime;
493 pf_add_threshold(struct pf_threshold *threshold)
495 u_int32_t t = time_uptime, diff = t - threshold->last;
497 if (diff >= threshold->seconds)
498 threshold->count = 0;
500 threshold->count -= threshold->count * diff /
502 threshold->count += PF_THRESHOLD_MULT;
507 pf_check_threshold(struct pf_threshold *threshold)
509 return (threshold->count > threshold->limit);
513 pf_src_connlimit(struct pf_state **state)
515 struct pf_overload_entry *pfoe;
518 PF_STATE_LOCK_ASSERT(*state);
520 (*state)->src_node->conn++;
521 (*state)->src.tcp_est = 1;
522 pf_add_threshold(&(*state)->src_node->conn_rate);
524 if ((*state)->rule.ptr->max_src_conn &&
525 (*state)->rule.ptr->max_src_conn <
526 (*state)->src_node->conn) {
527 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
531 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
532 pf_check_threshold(&(*state)->src_node->conn_rate)) {
533 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
540 /* Kill this state. */
541 (*state)->timeout = PFTM_PURGE;
542 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
544 if ((*state)->rule.ptr->overload_tbl == NULL)
547 /* Schedule overloading and flushing task. */
548 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
550 return (1); /* too bad :( */
552 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
553 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
554 pfoe->rule = (*state)->rule.ptr;
555 pfoe->dir = (*state)->direction;
557 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
558 PF_OVERLOADQ_UNLOCK();
559 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
565 pf_overload_task(void *v, int pending)
567 struct pf_overload_head queue;
569 struct pf_overload_entry *pfoe, *pfoe1;
572 CURVNET_SET((struct vnet *)v);
575 queue = V_pf_overloadqueue;
576 SLIST_INIT(&V_pf_overloadqueue);
577 PF_OVERLOADQ_UNLOCK();
579 bzero(&p, sizeof(p));
580 SLIST_FOREACH(pfoe, &queue, next) {
581 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
582 if (V_pf_status.debug >= PF_DEBUG_MISC) {
583 printf("%s: blocking address ", __func__);
584 pf_print_host(&pfoe->addr, 0, pfoe->af);
588 p.pfra_af = pfoe->af;
593 p.pfra_ip4addr = pfoe->addr.v4;
599 p.pfra_ip6addr = pfoe->addr.v6;
605 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
610 * Remove those entries, that don't need flushing.
612 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
613 if (pfoe->rule->flush == 0) {
614 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
615 free(pfoe, M_PFTEMP);
618 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
620 /* If nothing to flush, return. */
621 if (SLIST_EMPTY(&queue)) {
626 for (int i = 0; i <= pf_hashmask; i++) {
627 struct pf_idhash *ih = &V_pf_idhash[i];
628 struct pf_state_key *sk;
632 LIST_FOREACH(s, &ih->states, entry) {
633 sk = s->key[PF_SK_WIRE];
634 SLIST_FOREACH(pfoe, &queue, next)
635 if (sk->af == pfoe->af &&
636 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
637 pfoe->rule == s->rule.ptr) &&
638 ((pfoe->dir == PF_OUT &&
639 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
640 (pfoe->dir == PF_IN &&
641 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
642 s->timeout = PFTM_PURGE;
643 s->src.state = s->dst.state = TCPS_CLOSED;
647 PF_HASHROW_UNLOCK(ih);
649 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
650 free(pfoe, M_PFTEMP);
651 if (V_pf_status.debug >= PF_DEBUG_MISC)
652 printf("%s: %u states killed", __func__, killed);
658 * Can return locked on failure, so that we can consistently
659 * allocate and insert a new one.
662 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
665 struct pf_srchash *sh;
666 struct pf_src_node *n;
668 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
670 sh = &V_pf_srchash[pf_hashsrc(src, af)];
672 LIST_FOREACH(n, &sh->nodes, entry)
673 if (n->rule.ptr == rule && n->af == af &&
674 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
675 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
679 PF_HASHROW_UNLOCK(sh);
680 } else if (returnlocked == 0)
681 PF_HASHROW_UNLOCK(sh);
687 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
688 struct pf_addr *src, sa_family_t af)
691 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
692 rule->rpool.opts & PF_POOL_STICKYADDR),
693 ("%s for non-tracking rule %p", __func__, rule));
696 *sn = pf_find_src_node(src, rule, af, 1);
699 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
701 PF_HASHROW_ASSERT(sh);
703 if (!rule->max_src_nodes ||
704 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
705 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
707 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
710 PF_HASHROW_UNLOCK(sh);
714 pf_init_threshold(&(*sn)->conn_rate,
715 rule->max_src_conn_rate.limit,
716 rule->max_src_conn_rate.seconds);
719 (*sn)->rule.ptr = rule;
720 PF_ACPY(&(*sn)->addr, src, af);
721 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
722 (*sn)->creation = time_uptime;
723 (*sn)->ruletype = rule->action;
725 if ((*sn)->rule.ptr != NULL)
726 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
727 PF_HASHROW_UNLOCK(sh);
728 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
730 if (rule->max_src_states &&
731 (*sn)->states >= rule->max_src_states) {
732 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
741 pf_unlink_src_node(struct pf_src_node *src)
744 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
745 LIST_REMOVE(src, entry);
747 counter_u64_add(src->rule.ptr->src_nodes, -1);
751 pf_free_src_nodes(struct pf_src_node_list *head)
753 struct pf_src_node *sn, *tmp;
756 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
757 uma_zfree(V_pf_sources_z, sn);
761 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
770 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
771 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
775 /* Per-vnet data storage structures initialization. */
779 struct pf_keyhash *kh;
780 struct pf_idhash *ih;
781 struct pf_srchash *sh;
784 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
785 pf_hashsize = PF_HASHSIZ;
786 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
787 pf_srchashsize = PF_HASHSIZ / 4;
789 V_pf_hashseed = arc4random();
791 /* States and state keys storage. */
792 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
793 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
794 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
795 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
796 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
798 V_pf_state_key_z = uma_zcreate("pf state keys",
799 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
801 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
802 M_PFHASH, M_WAITOK | M_ZERO);
803 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
804 M_PFHASH, M_WAITOK | M_ZERO);
805 pf_hashmask = pf_hashsize - 1;
806 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
808 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
809 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
813 V_pf_sources_z = uma_zcreate("pf source nodes",
814 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
816 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
817 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
818 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
819 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
820 M_PFHASH, M_WAITOK|M_ZERO);
821 pf_srchashmask = pf_srchashsize - 1;
822 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
823 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
826 TAILQ_INIT(&V_pf_altqs[0]);
827 TAILQ_INIT(&V_pf_altqs[1]);
828 TAILQ_INIT(&V_pf_pabuf);
829 V_pf_altqs_active = &V_pf_altqs[0];
830 V_pf_altqs_inactive = &V_pf_altqs[1];
832 /* Send & overload+flush queues. */
833 STAILQ_INIT(&V_pf_sendqueue);
834 SLIST_INIT(&V_pf_overloadqueue);
835 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
837 /* Unlinked, but may be referenced rules. */
838 TAILQ_INIT(&V_pf_unlinked_rules);
845 uma_zdestroy(pf_mtag_z);
851 struct pf_keyhash *kh;
852 struct pf_idhash *ih;
853 struct pf_srchash *sh;
854 struct pf_send_entry *pfse, *next;
857 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
859 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
861 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
863 mtx_destroy(&kh->lock);
864 mtx_destroy(&ih->lock);
866 free(V_pf_keyhash, M_PFHASH);
867 free(V_pf_idhash, M_PFHASH);
869 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
870 KASSERT(LIST_EMPTY(&sh->nodes),
871 ("%s: source node hash not empty", __func__));
872 mtx_destroy(&sh->lock);
874 free(V_pf_srchash, M_PFHASH);
876 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
877 m_freem(pfse->pfse_m);
878 free(pfse, M_PFTEMP);
881 uma_zdestroy(V_pf_sources_z);
882 uma_zdestroy(V_pf_state_z);
883 uma_zdestroy(V_pf_state_key_z);
887 pf_mtag_uminit(void *mem, int size, int how)
891 t = (struct m_tag *)mem;
892 t->m_tag_cookie = MTAG_ABI_COMPAT;
893 t->m_tag_id = PACKET_TAG_PF;
894 t->m_tag_len = sizeof(struct pf_mtag);
895 t->m_tag_free = pf_mtag_free;
901 pf_mtag_free(struct m_tag *t)
904 uma_zfree(pf_mtag_z, t);
908 pf_get_mtag(struct mbuf *m)
912 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
913 return ((struct pf_mtag *)(mtag + 1));
915 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
918 bzero(mtag + 1, sizeof(struct pf_mtag));
919 m_tag_prepend(m, mtag);
921 return ((struct pf_mtag *)(mtag + 1));
925 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
928 struct pf_keyhash *khs, *khw, *kh;
929 struct pf_state_key *sk, *cur;
930 struct pf_state *si, *olds = NULL;
933 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
934 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
935 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
938 * We need to lock hash slots of both keys. To avoid deadlock
939 * we always lock the slot with lower address first. Unlock order
942 * We also need to lock ID hash slot before dropping key
943 * locks. On success we return with ID hash slot locked.
947 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
948 PF_HASHROW_LOCK(khs);
950 khs = &V_pf_keyhash[pf_hashkey(sks)];
951 khw = &V_pf_keyhash[pf_hashkey(skw)];
953 PF_HASHROW_LOCK(khs);
954 } else if (khs < khw) {
955 PF_HASHROW_LOCK(khs);
956 PF_HASHROW_LOCK(khw);
958 PF_HASHROW_LOCK(khw);
959 PF_HASHROW_LOCK(khs);
963 #define KEYS_UNLOCK() do { \
965 PF_HASHROW_UNLOCK(khs); \
966 PF_HASHROW_UNLOCK(khw); \
968 PF_HASHROW_UNLOCK(khs); \
972 * First run: start with wire key.
979 LIST_FOREACH(cur, &kh->keys, entry)
980 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
984 /* Key exists. Check for same kif, if none, add to key. */
985 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
986 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
989 if (si->kif == s->kif &&
990 si->direction == s->direction) {
991 if (sk->proto == IPPROTO_TCP &&
992 si->src.state >= TCPS_FIN_WAIT_2 &&
993 si->dst.state >= TCPS_FIN_WAIT_2) {
995 * New state matches an old >FIN_WAIT_2
996 * state. We can't drop key hash locks,
997 * thus we can't unlink it properly.
999 * As a workaround we drop it into
1000 * TCPS_CLOSED state, schedule purge
1001 * ASAP and push it into the very end
1002 * of the slot TAILQ, so that it won't
1003 * conflict with our new state.
1005 si->src.state = si->dst.state =
1007 si->timeout = PFTM_PURGE;
1010 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1011 printf("pf: %s key attach "
1013 (idx == PF_SK_WIRE) ?
1016 pf_print_state_parts(s,
1017 (idx == PF_SK_WIRE) ?
1019 (idx == PF_SK_STACK) ?
1021 printf(", existing: ");
1022 pf_print_state_parts(si,
1023 (idx == PF_SK_WIRE) ?
1025 (idx == PF_SK_STACK) ?
1029 PF_HASHROW_UNLOCK(ih);
1031 uma_zfree(V_pf_state_key_z, sk);
1032 if (idx == PF_SK_STACK)
1034 return (EEXIST); /* collision! */
1037 PF_HASHROW_UNLOCK(ih);
1039 uma_zfree(V_pf_state_key_z, sk);
1042 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1047 /* List is sorted, if-bound states before floating. */
1048 if (s->kif == V_pfi_all)
1049 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1051 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1054 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1055 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1061 * Attach done. See how should we (or should not?)
1062 * attach a second key.
1065 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1069 } else if (sks != NULL) {
1071 * Continue attaching with stack key.
1083 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1084 ("%s failure", __func__));
1091 pf_detach_state(struct pf_state *s)
1093 struct pf_state_key *sks = s->key[PF_SK_STACK];
1094 struct pf_keyhash *kh;
1097 kh = &V_pf_keyhash[pf_hashkey(sks)];
1098 PF_HASHROW_LOCK(kh);
1099 if (s->key[PF_SK_STACK] != NULL)
1100 pf_state_key_detach(s, PF_SK_STACK);
1102 * If both point to same key, then we are done.
1104 if (sks == s->key[PF_SK_WIRE]) {
1105 pf_state_key_detach(s, PF_SK_WIRE);
1106 PF_HASHROW_UNLOCK(kh);
1109 PF_HASHROW_UNLOCK(kh);
1112 if (s->key[PF_SK_WIRE] != NULL) {
1113 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1114 PF_HASHROW_LOCK(kh);
1115 if (s->key[PF_SK_WIRE] != NULL)
1116 pf_state_key_detach(s, PF_SK_WIRE);
1117 PF_HASHROW_UNLOCK(kh);
1122 pf_state_key_detach(struct pf_state *s, int idx)
1124 struct pf_state_key *sk = s->key[idx];
1126 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1128 PF_HASHROW_ASSERT(kh);
1130 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1133 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1134 LIST_REMOVE(sk, entry);
1135 uma_zfree(V_pf_state_key_z, sk);
1140 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1142 struct pf_state_key *sk = mem;
1144 bzero(sk, sizeof(struct pf_state_key_cmp));
1145 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1146 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1151 struct pf_state_key *
1152 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1153 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1155 struct pf_state_key *sk;
1157 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1161 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1162 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1163 sk->port[pd->sidx] = sport;
1164 sk->port[pd->didx] = dport;
1165 sk->proto = pd->proto;
1171 struct pf_state_key *
1172 pf_state_key_clone(struct pf_state_key *orig)
1174 struct pf_state_key *sk;
1176 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1180 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1186 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1187 struct pf_state_key *sks, struct pf_state *s)
1189 struct pf_idhash *ih;
1190 struct pf_state *cur;
1193 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1194 ("%s: sks not pristine", __func__));
1195 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1196 ("%s: skw not pristine", __func__));
1197 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1201 if (s->id == 0 && s->creatorid == 0) {
1202 /* XXX: should be atomic, but probability of collision low */
1203 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1204 V_pf_stateid[curcpu] = 1;
1205 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1206 s->id = htobe64(s->id);
1207 s->creatorid = V_pf_status.hostid;
1210 /* Returns with ID locked on success. */
1211 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1214 ih = &V_pf_idhash[PF_IDHASH(s)];
1215 PF_HASHROW_ASSERT(ih);
1216 LIST_FOREACH(cur, &ih->states, entry)
1217 if (cur->id == s->id && cur->creatorid == s->creatorid)
1221 PF_HASHROW_UNLOCK(ih);
1222 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1223 printf("pf: state ID collision: "
1224 "id: %016llx creatorid: %08x\n",
1225 (unsigned long long)be64toh(s->id),
1226 ntohl(s->creatorid));
1231 LIST_INSERT_HEAD(&ih->states, s, entry);
1232 /* One for keys, one for ID hash. */
1233 refcount_init(&s->refs, 2);
1235 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1236 if (pfsync_insert_state_ptr != NULL)
1237 pfsync_insert_state_ptr(s);
1239 /* Returns locked. */
1244 * Find state by ID: returns with locked row on success.
1247 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1249 struct pf_idhash *ih;
1252 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1254 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1256 PF_HASHROW_LOCK(ih);
1257 LIST_FOREACH(s, &ih->states, entry)
1258 if (s->id == id && s->creatorid == creatorid)
1262 PF_HASHROW_UNLOCK(ih);
1268 * Find state by key.
1269 * Returns with ID hash slot locked on success.
1271 static struct pf_state *
1272 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1274 struct pf_keyhash *kh;
1275 struct pf_state_key *sk;
1279 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1281 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1283 PF_HASHROW_LOCK(kh);
1284 LIST_FOREACH(sk, &kh->keys, entry)
1285 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1288 PF_HASHROW_UNLOCK(kh);
1292 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1294 /* List is sorted, if-bound states before floating ones. */
1295 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1296 if (s->kif == V_pfi_all || s->kif == kif) {
1298 PF_HASHROW_UNLOCK(kh);
1299 if (s->timeout >= PFTM_MAX) {
1301 * State is either being processed by
1302 * pf_unlink_state() in an other thread, or
1303 * is scheduled for immediate expiry.
1310 PF_HASHROW_UNLOCK(kh);
1316 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1318 struct pf_keyhash *kh;
1319 struct pf_state_key *sk;
1320 struct pf_state *s, *ret = NULL;
1323 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1325 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1327 PF_HASHROW_LOCK(kh);
1328 LIST_FOREACH(sk, &kh->keys, entry)
1329 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1332 PF_HASHROW_UNLOCK(kh);
1347 panic("%s: dir %u", __func__, dir);
1350 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1352 PF_HASHROW_UNLOCK(kh);
1366 PF_HASHROW_UNLOCK(kh);
1371 /* END state table stuff */
1374 pf_send(struct pf_send_entry *pfse)
1378 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1380 swi_sched(V_pf_swi_cookie, 0);
1386 struct pf_send_head queue;
1387 struct pf_send_entry *pfse, *next;
1389 CURVNET_SET((struct vnet *)v);
1392 queue = V_pf_sendqueue;
1393 STAILQ_INIT(&V_pf_sendqueue);
1396 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1397 switch (pfse->pfse_type) {
1400 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1403 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1404 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1409 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1413 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1414 pfse->icmpopts.code, pfse->icmpopts.mtu);
1418 panic("%s: unknown type", __func__);
1420 free(pfse, M_PFTEMP);
1426 pf_purge_thread(void *unused __unused)
1428 VNET_ITERATOR_DECL(vnet_iter);
1433 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1437 VNET_FOREACH(vnet_iter) {
1438 CURVNET_SET(vnet_iter);
1440 if (pf_end_threads) {
1442 wakeup(pf_purge_thread);
1446 /* Wait until V_pf_default_rule is initialized. */
1447 if (V_pf_vnet_active == 0) {
1453 * Process 1/interval fraction of the state
1456 idx = pf_purge_expired_states(idx, pf_hashmask /
1457 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1460 * Purge other expired types every
1461 * PFTM_INTERVAL seconds.
1465 * Order is important:
1466 * - states and src nodes reference rules
1467 * - states and rules reference kifs
1469 pf_purge_expired_fragments();
1470 pf_purge_expired_src_nodes();
1471 pf_purge_unlinked_rules();
1476 VNET_LIST_RUNLOCK();
1482 pf_unload_vnet_purge(void)
1486 * To cleanse up all kifs and rules we need
1487 * two runs: first one clears reference flags,
1488 * then pf_purge_expired_states() doesn't
1489 * raise them, and then second run frees.
1491 pf_purge_unlinked_rules();
1495 * Now purge everything.
1497 pf_purge_expired_states(0, pf_hashmask);
1498 pf_purge_expired_fragments();
1499 pf_purge_expired_src_nodes();
1502 * Now all kifs & rules should be unreferenced,
1503 * thus should be successfully freed.
1505 pf_purge_unlinked_rules();
1511 pf_state_expires(const struct pf_state *state)
1518 /* handle all PFTM_* > PFTM_MAX here */
1519 if (state->timeout == PFTM_PURGE)
1520 return (time_uptime);
1521 KASSERT(state->timeout != PFTM_UNLINKED,
1522 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1523 KASSERT((state->timeout < PFTM_MAX),
1524 ("pf_state_expires: timeout > PFTM_MAX"));
1525 timeout = state->rule.ptr->timeout[state->timeout];
1527 timeout = V_pf_default_rule.timeout[state->timeout];
1528 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1530 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1531 states = counter_u64_fetch(state->rule.ptr->states_cur);
1533 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1534 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1535 states = V_pf_status.states;
1537 if (end && states > start && start < end) {
1539 return (state->expire + timeout * (end - states) /
1542 return (time_uptime);
1544 return (state->expire + timeout);
1548 pf_purge_expired_src_nodes()
1550 struct pf_src_node_list freelist;
1551 struct pf_srchash *sh;
1552 struct pf_src_node *cur, *next;
1555 LIST_INIT(&freelist);
1556 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1557 PF_HASHROW_LOCK(sh);
1558 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1559 if (cur->states == 0 && cur->expire <= time_uptime) {
1560 pf_unlink_src_node(cur);
1561 LIST_INSERT_HEAD(&freelist, cur, entry);
1562 } else if (cur->rule.ptr != NULL)
1563 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1564 PF_HASHROW_UNLOCK(sh);
1567 pf_free_src_nodes(&freelist);
1569 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1573 pf_src_tree_remove_state(struct pf_state *s)
1575 struct pf_src_node *sn;
1576 struct pf_srchash *sh;
1579 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1580 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1581 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1583 if (s->src_node != NULL) {
1585 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1586 PF_HASHROW_LOCK(sh);
1589 if (--sn->states == 0)
1590 sn->expire = time_uptime + timeout;
1591 PF_HASHROW_UNLOCK(sh);
1593 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1594 sn = s->nat_src_node;
1595 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1596 PF_HASHROW_LOCK(sh);
1597 if (--sn->states == 0)
1598 sn->expire = time_uptime + timeout;
1599 PF_HASHROW_UNLOCK(sh);
1601 s->src_node = s->nat_src_node = NULL;
1605 * Unlink and potentilly free a state. Function may be
1606 * called with ID hash row locked, but always returns
1607 * unlocked, since it needs to go through key hash locking.
1610 pf_unlink_state(struct pf_state *s, u_int flags)
1612 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1614 if ((flags & PF_ENTER_LOCKED) == 0)
1615 PF_HASHROW_LOCK(ih);
1617 PF_HASHROW_ASSERT(ih);
1619 if (s->timeout == PFTM_UNLINKED) {
1621 * State is being processed
1622 * by pf_unlink_state() in
1625 PF_HASHROW_UNLOCK(ih);
1626 return (0); /* XXXGL: undefined actually */
1629 if (s->src.state == PF_TCPS_PROXY_DST) {
1630 /* XXX wire key the right one? */
1631 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1632 &s->key[PF_SK_WIRE]->addr[1],
1633 &s->key[PF_SK_WIRE]->addr[0],
1634 s->key[PF_SK_WIRE]->port[1],
1635 s->key[PF_SK_WIRE]->port[0],
1636 s->src.seqhi, s->src.seqlo + 1,
1637 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1640 LIST_REMOVE(s, entry);
1641 pf_src_tree_remove_state(s);
1643 if (pfsync_delete_state_ptr != NULL)
1644 pfsync_delete_state_ptr(s);
1646 STATE_DEC_COUNTERS(s);
1648 s->timeout = PFTM_UNLINKED;
1650 PF_HASHROW_UNLOCK(ih);
1653 refcount_release(&s->refs);
1655 return (pf_release_state(s));
1659 pf_free_state(struct pf_state *cur)
1662 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1663 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1666 pf_normalize_tcp_cleanup(cur);
1667 uma_zfree(V_pf_state_z, cur);
1668 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1672 * Called only from pf_purge_thread(), thus serialized.
1675 pf_purge_expired_states(u_int i, int maxcheck)
1677 struct pf_idhash *ih;
1680 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1683 * Go through hash and unlink states that expire now.
1685 while (maxcheck > 0) {
1687 ih = &V_pf_idhash[i];
1689 PF_HASHROW_LOCK(ih);
1690 LIST_FOREACH(s, &ih->states, entry) {
1691 if (pf_state_expires(s) <= time_uptime) {
1692 V_pf_status.states -=
1693 pf_unlink_state(s, PF_ENTER_LOCKED);
1696 s->rule.ptr->rule_flag |= PFRULE_REFS;
1697 if (s->nat_rule.ptr != NULL)
1698 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1699 if (s->anchor.ptr != NULL)
1700 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1701 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1703 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1705 PF_HASHROW_UNLOCK(ih);
1707 /* Return when we hit end of hash. */
1708 if (++i > pf_hashmask) {
1709 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1716 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1722 pf_purge_unlinked_rules()
1724 struct pf_rulequeue tmpq;
1725 struct pf_rule *r, *r1;
1728 * If we have overloading task pending, then we'd
1729 * better skip purging this time. There is a tiny
1730 * probability that overloading task references
1731 * an already unlinked rule.
1733 PF_OVERLOADQ_LOCK();
1734 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1735 PF_OVERLOADQ_UNLOCK();
1738 PF_OVERLOADQ_UNLOCK();
1741 * Do naive mark-and-sweep garbage collecting of old rules.
1742 * Reference flag is raised by pf_purge_expired_states()
1743 * and pf_purge_expired_src_nodes().
1745 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1746 * use a temporary queue.
1749 PF_UNLNKDRULES_LOCK();
1750 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1751 if (!(r->rule_flag & PFRULE_REFS)) {
1752 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1753 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1755 r->rule_flag &= ~PFRULE_REFS;
1757 PF_UNLNKDRULES_UNLOCK();
1759 if (!TAILQ_EMPTY(&tmpq)) {
1761 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1762 TAILQ_REMOVE(&tmpq, r, entries);
1770 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1775 u_int32_t a = ntohl(addr->addr32[0]);
1776 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1788 u_int8_t i, curstart, curend, maxstart, maxend;
1789 curstart = curend = maxstart = maxend = 255;
1790 for (i = 0; i < 8; i++) {
1791 if (!addr->addr16[i]) {
1792 if (curstart == 255)
1796 if ((curend - curstart) >
1797 (maxend - maxstart)) {
1798 maxstart = curstart;
1801 curstart = curend = 255;
1804 if ((curend - curstart) >
1805 (maxend - maxstart)) {
1806 maxstart = curstart;
1809 for (i = 0; i < 8; i++) {
1810 if (i >= maxstart && i <= maxend) {
1816 b = ntohs(addr->addr16[i]);
1833 pf_print_state(struct pf_state *s)
1835 pf_print_state_parts(s, NULL, NULL);
1839 pf_print_state_parts(struct pf_state *s,
1840 struct pf_state_key *skwp, struct pf_state_key *sksp)
1842 struct pf_state_key *skw, *sks;
1843 u_int8_t proto, dir;
1845 /* Do our best to fill these, but they're skipped if NULL */
1846 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1847 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1848 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1849 dir = s ? s->direction : 0;
1867 case IPPROTO_ICMPV6:
1871 printf("%u", proto);
1884 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1886 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1891 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1893 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1898 if (proto == IPPROTO_TCP) {
1899 printf(" [lo=%u high=%u win=%u modulator=%u",
1900 s->src.seqlo, s->src.seqhi,
1901 s->src.max_win, s->src.seqdiff);
1902 if (s->src.wscale && s->dst.wscale)
1903 printf(" wscale=%u",
1904 s->src.wscale & PF_WSCALE_MASK);
1906 printf(" [lo=%u high=%u win=%u modulator=%u",
1907 s->dst.seqlo, s->dst.seqhi,
1908 s->dst.max_win, s->dst.seqdiff);
1909 if (s->src.wscale && s->dst.wscale)
1910 printf(" wscale=%u",
1911 s->dst.wscale & PF_WSCALE_MASK);
1914 printf(" %u:%u", s->src.state, s->dst.state);
1919 pf_print_flags(u_int8_t f)
1941 #define PF_SET_SKIP_STEPS(i) \
1943 while (head[i] != cur) { \
1944 head[i]->skip[i].ptr = cur; \
1945 head[i] = TAILQ_NEXT(head[i], entries); \
1950 pf_calc_skip_steps(struct pf_rulequeue *rules)
1952 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1955 cur = TAILQ_FIRST(rules);
1957 for (i = 0; i < PF_SKIP_COUNT; ++i)
1959 while (cur != NULL) {
1961 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1962 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1963 if (cur->direction != prev->direction)
1964 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1965 if (cur->af != prev->af)
1966 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1967 if (cur->proto != prev->proto)
1968 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1969 if (cur->src.neg != prev->src.neg ||
1970 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1971 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1972 if (cur->src.port[0] != prev->src.port[0] ||
1973 cur->src.port[1] != prev->src.port[1] ||
1974 cur->src.port_op != prev->src.port_op)
1975 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1976 if (cur->dst.neg != prev->dst.neg ||
1977 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1978 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1979 if (cur->dst.port[0] != prev->dst.port[0] ||
1980 cur->dst.port[1] != prev->dst.port[1] ||
1981 cur->dst.port_op != prev->dst.port_op)
1982 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1985 cur = TAILQ_NEXT(cur, entries);
1987 for (i = 0; i < PF_SKIP_COUNT; ++i)
1988 PF_SET_SKIP_STEPS(i);
1992 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1994 if (aw1->type != aw2->type)
1996 switch (aw1->type) {
1997 case PF_ADDR_ADDRMASK:
1999 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2001 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2004 case PF_ADDR_DYNIFTL:
2005 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2006 case PF_ADDR_NOROUTE:
2007 case PF_ADDR_URPFFAILED:
2010 return (aw1->p.tbl != aw2->p.tbl);
2012 printf("invalid address type: %d\n", aw1->type);
2018 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2019 * header isn't always a full checksum. In some cases (i.e. output) it's a
2020 * pseudo-header checksum, which is a partial checksum over src/dst IP
2021 * addresses, protocol number and length.
2023 * That means we have the following cases:
2024 * * Input or forwarding: we don't have TSO, the checksum fields are full
2025 * checksums, we need to update the checksum whenever we change anything.
2026 * * Output (i.e. the checksum is a pseudo-header checksum):
2027 * x The field being updated is src/dst address or affects the length of
2028 * the packet. We need to update the pseudo-header checksum (note that this
2029 * checksum is not ones' complement).
2030 * x Some other field is being modified (e.g. src/dst port numbers): We
2031 * don't have to update anything.
2034 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2040 l = cksum + old - new;
2041 l = (l >> 16) + (l & 65535);
2049 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2050 u_int16_t new, u_int8_t udp)
2052 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2055 return (pf_cksum_fixup(cksum, old, new, udp));
2059 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2060 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2066 PF_ACPY(&ao, a, af);
2069 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2077 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2078 ao.addr16[0], an->addr16[0], 0),
2079 ao.addr16[1], an->addr16[1], 0);
2082 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2083 ao.addr16[0], an->addr16[0], u),
2084 ao.addr16[1], an->addr16[1], u);
2086 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2091 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2092 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2093 pf_cksum_fixup(pf_cksum_fixup(*pc,
2094 ao.addr16[0], an->addr16[0], u),
2095 ao.addr16[1], an->addr16[1], u),
2096 ao.addr16[2], an->addr16[2], u),
2097 ao.addr16[3], an->addr16[3], u),
2098 ao.addr16[4], an->addr16[4], u),
2099 ao.addr16[5], an->addr16[5], u),
2100 ao.addr16[6], an->addr16[6], u),
2101 ao.addr16[7], an->addr16[7], u);
2103 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2108 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2109 CSUM_DELAY_DATA_IPV6)) {
2116 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2118 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2122 memcpy(&ao, a, sizeof(ao));
2123 memcpy(a, &an, sizeof(u_int32_t));
2124 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2125 ao % 65536, an % 65536, u);
2129 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2133 memcpy(&ao, a, sizeof(ao));
2134 memcpy(a, &an, sizeof(u_int32_t));
2136 *c = pf_proto_cksum_fixup(m,
2137 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2138 ao % 65536, an % 65536, udp);
2143 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2147 PF_ACPY(&ao, a, AF_INET6);
2148 PF_ACPY(a, an, AF_INET6);
2150 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2151 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2152 pf_cksum_fixup(pf_cksum_fixup(*c,
2153 ao.addr16[0], an->addr16[0], u),
2154 ao.addr16[1], an->addr16[1], u),
2155 ao.addr16[2], an->addr16[2], u),
2156 ao.addr16[3], an->addr16[3], u),
2157 ao.addr16[4], an->addr16[4], u),
2158 ao.addr16[5], an->addr16[5], u),
2159 ao.addr16[6], an->addr16[6], u),
2160 ao.addr16[7], an->addr16[7], u);
2165 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2166 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2167 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2169 struct pf_addr oia, ooa;
2171 PF_ACPY(&oia, ia, af);
2173 PF_ACPY(&ooa, oa, af);
2175 /* Change inner protocol port, fix inner protocol checksum. */
2177 u_int16_t oip = *ip;
2184 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2185 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2187 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2189 /* Change inner ip address, fix inner ip and icmp checksums. */
2190 PF_ACPY(ia, na, af);
2194 u_int32_t oh2c = *h2c;
2196 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2197 oia.addr16[0], ia->addr16[0], 0),
2198 oia.addr16[1], ia->addr16[1], 0);
2199 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2200 oia.addr16[0], ia->addr16[0], 0),
2201 oia.addr16[1], ia->addr16[1], 0);
2202 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2208 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2209 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2210 pf_cksum_fixup(pf_cksum_fixup(*ic,
2211 oia.addr16[0], ia->addr16[0], u),
2212 oia.addr16[1], ia->addr16[1], u),
2213 oia.addr16[2], ia->addr16[2], u),
2214 oia.addr16[3], ia->addr16[3], u),
2215 oia.addr16[4], ia->addr16[4], u),
2216 oia.addr16[5], ia->addr16[5], u),
2217 oia.addr16[6], ia->addr16[6], u),
2218 oia.addr16[7], ia->addr16[7], u);
2222 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2224 PF_ACPY(oa, na, af);
2228 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2229 ooa.addr16[0], oa->addr16[0], 0),
2230 ooa.addr16[1], oa->addr16[1], 0);
2235 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2236 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2237 pf_cksum_fixup(pf_cksum_fixup(*ic,
2238 ooa.addr16[0], oa->addr16[0], u),
2239 ooa.addr16[1], oa->addr16[1], u),
2240 ooa.addr16[2], oa->addr16[2], u),
2241 ooa.addr16[3], oa->addr16[3], u),
2242 ooa.addr16[4], oa->addr16[4], u),
2243 ooa.addr16[5], oa->addr16[5], u),
2244 ooa.addr16[6], oa->addr16[6], u),
2245 ooa.addr16[7], oa->addr16[7], u);
2254 * Need to modulate the sequence numbers in the TCP SACK option
2255 * (credits to Krzysztof Pfaff for report and patch)
2258 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2259 struct tcphdr *th, struct pf_state_peer *dst)
2261 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2262 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2263 int copyback = 0, i, olen;
2264 struct sackblk sack;
2266 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2267 if (hlen < TCPOLEN_SACKLEN ||
2268 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2271 while (hlen >= TCPOLEN_SACKLEN) {
2274 case TCPOPT_EOL: /* FALLTHROUGH */
2282 if (olen >= TCPOLEN_SACKLEN) {
2283 for (i = 2; i + TCPOLEN_SACK <= olen;
2284 i += TCPOLEN_SACK) {
2285 memcpy(&sack, &opt[i], sizeof(sack));
2286 pf_change_proto_a(m, &sack.start, &th->th_sum,
2287 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2288 pf_change_proto_a(m, &sack.end, &th->th_sum,
2289 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2290 memcpy(&opt[i], &sack, sizeof(sack));
2304 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2309 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2310 const struct pf_addr *saddr, const struct pf_addr *daddr,
2311 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2312 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2313 u_int16_t rtag, struct ifnet *ifp)
2315 struct pf_send_entry *pfse;
2319 struct ip *h = NULL;
2322 struct ip6_hdr *h6 = NULL;
2326 struct pf_mtag *pf_mtag;
2331 /* maximum segment size tcp option */
2332 tlen = sizeof(struct tcphdr);
2339 len = sizeof(struct ip) + tlen;
2344 len = sizeof(struct ip6_hdr) + tlen;
2348 panic("%s: unsupported af %d", __func__, af);
2351 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2352 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2355 m = m_gethdr(M_NOWAIT, MT_DATA);
2357 free(pfse, M_PFTEMP);
2361 mac_netinet_firewall_send(m);
2363 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2364 free(pfse, M_PFTEMP);
2369 m->m_flags |= M_SKIP_FIREWALL;
2370 pf_mtag->tag = rtag;
2372 if (r != NULL && r->rtableid >= 0)
2373 M_SETFIB(m, r->rtableid);
2376 if (r != NULL && r->qid) {
2377 pf_mtag->qid = r->qid;
2379 /* add hints for ecn */
2380 pf_mtag->hdr = mtod(m, struct ip *);
2383 m->m_data += max_linkhdr;
2384 m->m_pkthdr.len = m->m_len = len;
2385 m->m_pkthdr.rcvif = NULL;
2386 bzero(m->m_data, len);
2390 h = mtod(m, struct ip *);
2392 /* IP header fields included in the TCP checksum */
2393 h->ip_p = IPPROTO_TCP;
2394 h->ip_len = htons(tlen);
2395 h->ip_src.s_addr = saddr->v4.s_addr;
2396 h->ip_dst.s_addr = daddr->v4.s_addr;
2398 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2403 h6 = mtod(m, struct ip6_hdr *);
2405 /* IP header fields included in the TCP checksum */
2406 h6->ip6_nxt = IPPROTO_TCP;
2407 h6->ip6_plen = htons(tlen);
2408 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2409 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2411 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2417 th->th_sport = sport;
2418 th->th_dport = dport;
2419 th->th_seq = htonl(seq);
2420 th->th_ack = htonl(ack);
2421 th->th_off = tlen >> 2;
2422 th->th_flags = flags;
2423 th->th_win = htons(win);
2426 opt = (char *)(th + 1);
2427 opt[0] = TCPOPT_MAXSEG;
2430 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2437 th->th_sum = in_cksum(m, len);
2439 /* Finish the IP header */
2441 h->ip_hl = sizeof(*h) >> 2;
2442 h->ip_tos = IPTOS_LOWDELAY;
2443 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2444 h->ip_len = htons(len);
2445 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2448 pfse->pfse_type = PFSE_IP;
2454 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2455 sizeof(struct ip6_hdr), tlen);
2457 h6->ip6_vfc |= IPV6_VERSION;
2458 h6->ip6_hlim = IPV6_DEFHLIM;
2460 pfse->pfse_type = PFSE_IP6;
2469 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2473 KASSERT(prio <= PF_PRIO_MAX,
2474 ("%s with invalid pcp", __func__));
2476 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2478 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2479 sizeof(uint8_t), M_NOWAIT);
2482 m_tag_prepend(m, mtag);
2485 *(uint8_t *)(mtag + 1) = prio;
2490 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2495 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2499 if (prio == PF_PRIO_ZERO)
2502 mpcp = *(uint8_t *)(mtag + 1);
2504 return (mpcp == prio);
2508 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2511 struct pf_send_entry *pfse;
2513 struct pf_mtag *pf_mtag;
2515 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2516 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2520 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2521 free(pfse, M_PFTEMP);
2525 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2526 free(pfse, M_PFTEMP);
2530 m0->m_flags |= M_SKIP_FIREWALL;
2532 if (r->rtableid >= 0)
2533 M_SETFIB(m0, r->rtableid);
2537 pf_mtag->qid = r->qid;
2538 /* add hints for ecn */
2539 pf_mtag->hdr = mtod(m0, struct ip *);
2546 pfse->pfse_type = PFSE_ICMP;
2551 pfse->pfse_type = PFSE_ICMP6;
2556 pfse->icmpopts.type = type;
2557 pfse->icmpopts.code = code;
2562 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2563 * If n is 0, they match if they are equal. If n is != 0, they match if they
2567 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2568 struct pf_addr *b, sa_family_t af)
2575 if ((a->addr32[0] & m->addr32[0]) ==
2576 (b->addr32[0] & m->addr32[0]))
2582 if (((a->addr32[0] & m->addr32[0]) ==
2583 (b->addr32[0] & m->addr32[0])) &&
2584 ((a->addr32[1] & m->addr32[1]) ==
2585 (b->addr32[1] & m->addr32[1])) &&
2586 ((a->addr32[2] & m->addr32[2]) ==
2587 (b->addr32[2] & m->addr32[2])) &&
2588 ((a->addr32[3] & m->addr32[3]) ==
2589 (b->addr32[3] & m->addr32[3])))
2608 * Return 1 if b <= a <= e, otherwise return 0.
2611 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2612 struct pf_addr *a, sa_family_t af)
2617 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2618 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2627 for (i = 0; i < 4; ++i)
2628 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2630 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2633 for (i = 0; i < 4; ++i)
2634 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2636 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2646 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2650 return ((p > a1) && (p < a2));
2652 return ((p < a1) || (p > a2));
2654 return ((p >= a1) && (p <= a2));
2668 return (0); /* never reached */
2672 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2677 return (pf_match(op, a1, a2, p));
2681 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2683 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2685 return (pf_match(op, a1, a2, u));
2689 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2691 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2693 return (pf_match(op, a1, a2, g));
2697 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2702 return ((!r->match_tag_not && r->match_tag == *tag) ||
2703 (r->match_tag_not && r->match_tag != *tag));
2707 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2710 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2712 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2715 pd->pf_mtag->tag = tag;
2720 #define PF_ANCHOR_STACKSIZE 32
2721 struct pf_anchor_stackframe {
2722 struct pf_ruleset *rs;
2723 struct pf_rule *r; /* XXX: + match bit */
2724 struct pf_anchor *child;
2728 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2730 #define PF_ANCHORSTACK_MATCH 0x00000001
2731 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2733 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2734 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2735 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2736 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2737 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2741 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2742 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2745 struct pf_anchor_stackframe *f;
2751 if (*depth >= PF_ANCHOR_STACKSIZE) {
2752 printf("%s: anchor stack overflow on %s\n",
2753 __func__, (*r)->anchor->name);
2754 *r = TAILQ_NEXT(*r, entries);
2756 } else if (*depth == 0 && a != NULL)
2758 f = stack + (*depth)++;
2761 if ((*r)->anchor_wildcard) {
2762 struct pf_anchor_node *parent = &(*r)->anchor->children;
2764 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2768 *rs = &f->child->ruleset;
2771 *rs = &(*r)->anchor->ruleset;
2773 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2777 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2778 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2781 struct pf_anchor_stackframe *f;
2790 f = stack + *depth - 1;
2791 fr = PF_ANCHOR_RULE(f);
2792 if (f->child != NULL) {
2793 struct pf_anchor_node *parent;
2796 * This block traverses through
2797 * a wildcard anchor.
2799 parent = &fr->anchor->children;
2800 if (match != NULL && *match) {
2802 * If any of "*" matched, then
2803 * "foo/ *" matched, mark frame
2806 PF_ANCHOR_SET_MATCH(f);
2809 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2810 if (f->child != NULL) {
2811 *rs = &f->child->ruleset;
2812 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2820 if (*depth == 0 && a != NULL)
2823 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2825 *r = TAILQ_NEXT(fr, entries);
2826 } while (*r == NULL);
2833 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2834 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2839 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2840 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2844 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2845 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2846 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2847 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2848 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2849 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2850 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2851 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2857 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2862 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2866 if (addr->addr32[3] == 0xffffffff) {
2867 addr->addr32[3] = 0;
2868 if (addr->addr32[2] == 0xffffffff) {
2869 addr->addr32[2] = 0;
2870 if (addr->addr32[1] == 0xffffffff) {
2871 addr->addr32[1] = 0;
2873 htonl(ntohl(addr->addr32[0]) + 1);
2876 htonl(ntohl(addr->addr32[1]) + 1);
2879 htonl(ntohl(addr->addr32[2]) + 1);
2882 htonl(ntohl(addr->addr32[3]) + 1);
2889 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2891 struct pf_addr *saddr, *daddr;
2892 u_int16_t sport, dport;
2893 struct inpcbinfo *pi;
2896 pd->lookup.uid = UID_MAX;
2897 pd->lookup.gid = GID_MAX;
2899 switch (pd->proto) {
2901 if (pd->hdr.tcp == NULL)
2903 sport = pd->hdr.tcp->th_sport;
2904 dport = pd->hdr.tcp->th_dport;
2908 if (pd->hdr.udp == NULL)
2910 sport = pd->hdr.udp->uh_sport;
2911 dport = pd->hdr.udp->uh_dport;
2917 if (direction == PF_IN) {
2932 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2933 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2935 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2936 daddr->v4, dport, INPLOOKUP_WILDCARD |
2937 INPLOOKUP_RLOCKPCB, NULL, m);
2945 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2946 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2948 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2949 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2950 INPLOOKUP_RLOCKPCB, NULL, m);
2960 INP_RLOCK_ASSERT(inp);
2961 pd->lookup.uid = inp->inp_cred->cr_uid;
2962 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2969 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2973 u_int8_t *opt, optlen;
2974 u_int8_t wscale = 0;
2976 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2977 if (hlen <= sizeof(struct tcphdr))
2979 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2981 opt = hdr + sizeof(struct tcphdr);
2982 hlen -= sizeof(struct tcphdr);
2992 if (wscale > TCP_MAX_WINSHIFT)
2993 wscale = TCP_MAX_WINSHIFT;
2994 wscale |= PF_WSCALE_FLAG;
3009 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3013 u_int8_t *opt, optlen;
3014 u_int16_t mss = V_tcp_mssdflt;
3016 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3017 if (hlen <= sizeof(struct tcphdr))
3019 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3021 opt = hdr + sizeof(struct tcphdr);
3022 hlen -= sizeof(struct tcphdr);
3023 while (hlen >= TCPOLEN_MAXSEG) {
3031 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3047 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3050 struct nhop4_basic nh4;
3053 struct nhop6_basic nh6;
3054 struct in6_addr dst6;
3063 hlen = sizeof(struct ip);
3064 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3065 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3070 hlen = sizeof(struct ip6_hdr);
3071 in6_splitscope(&addr->v6, &dst6, &scopeid);
3072 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3073 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3078 mss = max(V_tcp_mssdflt, mss);
3079 mss = min(mss, offer);
3080 mss = max(mss, 64); /* sanity - at least max opt space */
3085 pf_tcp_iss(struct pf_pdesc *pd)
3088 u_int32_t digest[4];
3090 if (V_pf_tcp_secret_init == 0) {
3091 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3092 MD5Init(&V_pf_tcp_secret_ctx);
3093 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3094 sizeof(V_pf_tcp_secret));
3095 V_pf_tcp_secret_init = 1;
3098 ctx = V_pf_tcp_secret_ctx;
3100 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3101 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3102 if (pd->af == AF_INET6) {
3103 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3104 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3106 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3107 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3109 MD5Final((u_char *)digest, &ctx);
3110 V_pf_tcp_iss_off += 4096;
3111 #define ISN_RANDOM_INCREMENT (4096 - 1)
3112 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3114 #undef ISN_RANDOM_INCREMENT
3118 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3119 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3120 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3122 struct pf_rule *nr = NULL;
3123 struct pf_addr * const saddr = pd->src;
3124 struct pf_addr * const daddr = pd->dst;
3125 sa_family_t af = pd->af;
3126 struct pf_rule *r, *a = NULL;
3127 struct pf_ruleset *ruleset = NULL;
3128 struct pf_src_node *nsn = NULL;
3129 struct tcphdr *th = pd->hdr.tcp;
3130 struct pf_state_key *sk = NULL, *nk = NULL;
3132 int rewrite = 0, hdrlen = 0;
3133 int tag = -1, rtableid = -1;
3137 u_int16_t sport = 0, dport = 0;
3138 u_int16_t bproto_sum = 0, bip_sum = 0;
3139 u_int8_t icmptype = 0, icmpcode = 0;
3140 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3145 INP_LOCK_ASSERT(inp);
3146 pd->lookup.uid = inp->inp_cred->cr_uid;
3147 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3148 pd->lookup.done = 1;
3151 switch (pd->proto) {
3153 sport = th->th_sport;
3154 dport = th->th_dport;
3155 hdrlen = sizeof(*th);
3158 sport = pd->hdr.udp->uh_sport;
3159 dport = pd->hdr.udp->uh_dport;
3160 hdrlen = sizeof(*pd->hdr.udp);
3164 if (pd->af != AF_INET)
3166 sport = dport = pd->hdr.icmp->icmp_id;
3167 hdrlen = sizeof(*pd->hdr.icmp);
3168 icmptype = pd->hdr.icmp->icmp_type;
3169 icmpcode = pd->hdr.icmp->icmp_code;
3171 if (icmptype == ICMP_UNREACH ||
3172 icmptype == ICMP_SOURCEQUENCH ||
3173 icmptype == ICMP_REDIRECT ||
3174 icmptype == ICMP_TIMXCEED ||
3175 icmptype == ICMP_PARAMPROB)
3180 case IPPROTO_ICMPV6:
3183 sport = dport = pd->hdr.icmp6->icmp6_id;
3184 hdrlen = sizeof(*pd->hdr.icmp6);
3185 icmptype = pd->hdr.icmp6->icmp6_type;
3186 icmpcode = pd->hdr.icmp6->icmp6_code;
3188 if (icmptype == ICMP6_DST_UNREACH ||
3189 icmptype == ICMP6_PACKET_TOO_BIG ||
3190 icmptype == ICMP6_TIME_EXCEEDED ||
3191 icmptype == ICMP6_PARAM_PROB)
3196 sport = dport = hdrlen = 0;
3200 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3202 /* check packet for BINAT/NAT/RDR */
3203 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3204 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3205 KASSERT(sk != NULL, ("%s: null sk", __func__));
3206 KASSERT(nk != NULL, ("%s: null nk", __func__));
3209 bip_sum = *pd->ip_sum;
3211 switch (pd->proto) {
3213 bproto_sum = th->th_sum;
3214 pd->proto_sum = &th->th_sum;
3216 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3217 nk->port[pd->sidx] != sport) {
3218 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3219 &th->th_sum, &nk->addr[pd->sidx],
3220 nk->port[pd->sidx], 0, af);
3221 pd->sport = &th->th_sport;
3222 sport = th->th_sport;
3225 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3226 nk->port[pd->didx] != dport) {
3227 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3228 &th->th_sum, &nk->addr[pd->didx],
3229 nk->port[pd->didx], 0, af);
3230 dport = th->th_dport;
3231 pd->dport = &th->th_dport;
3236 bproto_sum = pd->hdr.udp->uh_sum;
3237 pd->proto_sum = &pd->hdr.udp->uh_sum;
3239 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3240 nk->port[pd->sidx] != sport) {
3241 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3242 pd->ip_sum, &pd->hdr.udp->uh_sum,
3243 &nk->addr[pd->sidx],
3244 nk->port[pd->sidx], 1, af);
3245 sport = pd->hdr.udp->uh_sport;
3246 pd->sport = &pd->hdr.udp->uh_sport;
3249 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3250 nk->port[pd->didx] != dport) {
3251 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3252 pd->ip_sum, &pd->hdr.udp->uh_sum,
3253 &nk->addr[pd->didx],
3254 nk->port[pd->didx], 1, af);
3255 dport = pd->hdr.udp->uh_dport;
3256 pd->dport = &pd->hdr.udp->uh_dport;
3262 nk->port[0] = nk->port[1];
3263 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3264 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3265 nk->addr[pd->sidx].v4.s_addr, 0);
3267 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3268 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3269 nk->addr[pd->didx].v4.s_addr, 0);
3271 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3272 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3273 pd->hdr.icmp->icmp_cksum, sport,
3275 pd->hdr.icmp->icmp_id = nk->port[1];
3276 pd->sport = &pd->hdr.icmp->icmp_id;
3278 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3282 case IPPROTO_ICMPV6:
3283 nk->port[0] = nk->port[1];
3284 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3285 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3286 &nk->addr[pd->sidx], 0);
3288 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3289 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3290 &nk->addr[pd->didx], 0);
3299 &nk->addr[pd->sidx], AF_INET))
3300 pf_change_a(&saddr->v4.s_addr,
3302 nk->addr[pd->sidx].v4.s_addr, 0);
3305 &nk->addr[pd->didx], AF_INET))
3306 pf_change_a(&daddr->v4.s_addr,
3308 nk->addr[pd->didx].v4.s_addr, 0);
3314 &nk->addr[pd->sidx], AF_INET6))
3315 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3318 &nk->addr[pd->didx], AF_INET6))
3319 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3332 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3333 r = r->skip[PF_SKIP_IFP].ptr;
3334 else if (r->direction && r->direction != direction)
3335 r = r->skip[PF_SKIP_DIR].ptr;
3336 else if (r->af && r->af != af)
3337 r = r->skip[PF_SKIP_AF].ptr;
3338 else if (r->proto && r->proto != pd->proto)
3339 r = r->skip[PF_SKIP_PROTO].ptr;
3340 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3341 r->src.neg, kif, M_GETFIB(m)))
3342 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3343 /* tcp/udp only. port_op always 0 in other cases */
3344 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3345 r->src.port[0], r->src.port[1], sport))
3346 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3347 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3348 r->dst.neg, NULL, M_GETFIB(m)))
3349 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3350 /* tcp/udp only. port_op always 0 in other cases */
3351 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3352 r->dst.port[0], r->dst.port[1], dport))
3353 r = r->skip[PF_SKIP_DST_PORT].ptr;
3354 /* icmp only. type always 0 in other cases */
3355 else if (r->type && r->type != icmptype + 1)
3356 r = TAILQ_NEXT(r, entries);
3357 /* icmp only. type always 0 in other cases */
3358 else if (r->code && r->code != icmpcode + 1)
3359 r = TAILQ_NEXT(r, entries);
3360 else if (r->tos && !(r->tos == pd->tos))
3361 r = TAILQ_NEXT(r, entries);
3362 else if (r->rule_flag & PFRULE_FRAGMENT)
3363 r = TAILQ_NEXT(r, entries);
3364 else if (pd->proto == IPPROTO_TCP &&
3365 (r->flagset & th->th_flags) != r->flags)
3366 r = TAILQ_NEXT(r, entries);
3367 /* tcp/udp only. uid.op always 0 in other cases */
3368 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3369 pf_socket_lookup(direction, pd, m), 1)) &&
3370 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3372 r = TAILQ_NEXT(r, entries);
3373 /* tcp/udp only. gid.op always 0 in other cases */
3374 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3375 pf_socket_lookup(direction, pd, m), 1)) &&
3376 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3378 r = TAILQ_NEXT(r, entries);
3380 !pf_match_ieee8021q_pcp(r->prio, m))
3381 r = TAILQ_NEXT(r, entries);
3383 r->prob <= arc4random())
3384 r = TAILQ_NEXT(r, entries);
3385 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3386 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3387 r = TAILQ_NEXT(r, entries);
3388 else if (r->os_fingerprint != PF_OSFP_ANY &&
3389 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3390 pf_osfp_fingerprint(pd, m, off, th),
3391 r->os_fingerprint)))
3392 r = TAILQ_NEXT(r, entries);
3396 if (r->rtableid >= 0)
3397 rtableid = r->rtableid;
3398 if (r->anchor == NULL) {
3405 r = TAILQ_NEXT(r, entries);
3407 pf_step_into_anchor(anchor_stack, &asd,
3408 &ruleset, PF_RULESET_FILTER, &r, &a,
3411 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3412 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3419 REASON_SET(&reason, PFRES_MATCH);
3421 if (r->log || (nr != NULL && nr->log)) {
3423 m_copyback(m, off, hdrlen, pd->hdr.any);
3424 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3428 if ((r->action == PF_DROP) &&
3429 ((r->rule_flag & PFRULE_RETURNRST) ||
3430 (r->rule_flag & PFRULE_RETURNICMP) ||
3431 (r->rule_flag & PFRULE_RETURN))) {
3432 /* undo NAT changes, if they have taken place */
3434 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3435 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3437 *pd->sport = sk->port[pd->sidx];
3439 *pd->dport = sk->port[pd->didx];
3441 *pd->proto_sum = bproto_sum;
3443 *pd->ip_sum = bip_sum;
3444 m_copyback(m, off, hdrlen, pd->hdr.any);
3446 if (pd->proto == IPPROTO_TCP &&
3447 ((r->rule_flag & PFRULE_RETURNRST) ||
3448 (r->rule_flag & PFRULE_RETURN)) &&
3449 !(th->th_flags & TH_RST)) {
3450 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3462 h4 = mtod(m, struct ip *);
3463 len = ntohs(h4->ip_len) - off;
3468 h6 = mtod(m, struct ip6_hdr *);
3469 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3474 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3475 REASON_SET(&reason, PFRES_PROTCKSUM);
3477 if (th->th_flags & TH_SYN)
3479 if (th->th_flags & TH_FIN)
3481 pf_send_tcp(m, r, af, pd->dst,
3482 pd->src, th->th_dport, th->th_sport,
3483 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3484 r->return_ttl, 1, 0, kif->pfik_ifp);
3486 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3488 pf_send_icmp(m, r->return_icmp >> 8,
3489 r->return_icmp & 255, af, r);
3490 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3492 pf_send_icmp(m, r->return_icmp6 >> 8,
3493 r->return_icmp6 & 255, af, r);
3496 if (r->action == PF_DROP)
3499 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3500 REASON_SET(&reason, PFRES_MEMORY);
3504 M_SETFIB(m, rtableid);
3506 if (!state_icmp && (r->keep_state || nr != NULL ||
3507 (pd->flags & PFDESC_TCP_NORM))) {
3509 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3510 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3512 if (action != PF_PASS)
3516 uma_zfree(V_pf_state_key_z, sk);
3518 uma_zfree(V_pf_state_key_z, nk);
3521 /* copy back packet headers if we performed NAT operations */
3523 m_copyback(m, off, hdrlen, pd->hdr.any);
3525 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3526 direction == PF_OUT &&
3527 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3529 * We want the state created, but we dont
3530 * want to send this in case a partner
3531 * firewall has to know about it to allow
3532 * replies through it.
3540 uma_zfree(V_pf_state_key_z, sk);
3542 uma_zfree(V_pf_state_key_z, nk);
3547 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3548 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3549 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3550 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3551 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3553 struct pf_state *s = NULL;
3554 struct pf_src_node *sn = NULL;
3555 struct tcphdr *th = pd->hdr.tcp;
3556 u_int16_t mss = V_tcp_mssdflt;
3559 /* check maximums */
3560 if (r->max_states &&
3561 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3562 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3563 REASON_SET(&reason, PFRES_MAXSTATES);
3566 /* src node for filter rule */
3567 if ((r->rule_flag & PFRULE_SRCTRACK ||
3568 r->rpool.opts & PF_POOL_STICKYADDR) &&
3569 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3570 REASON_SET(&reason, PFRES_SRCLIMIT);
3573 /* src node for translation rule */
3574 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3575 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3576 REASON_SET(&reason, PFRES_SRCLIMIT);
3579 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3581 REASON_SET(&reason, PFRES_MEMORY);
3585 s->nat_rule.ptr = nr;
3587 STATE_INC_COUNTERS(s);
3589 s->state_flags |= PFSTATE_ALLOWOPTS;
3590 if (r->rule_flag & PFRULE_STATESLOPPY)
3591 s->state_flags |= PFSTATE_SLOPPY;
3592 s->log = r->log & PF_LOG_ALL;
3593 s->sync_state = PFSYNC_S_NONE;
3595 s->log |= nr->log & PF_LOG_ALL;
3596 switch (pd->proto) {
3598 s->src.seqlo = ntohl(th->th_seq);
3599 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3600 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3601 r->keep_state == PF_STATE_MODULATE) {
3602 /* Generate sequence number modulator */
3603 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3606 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3607 htonl(s->src.seqlo + s->src.seqdiff), 0);
3611 if (th->th_flags & TH_SYN) {
3613 s->src.wscale = pf_get_wscale(m, off,
3614 th->th_off, pd->af);
3616 s->src.max_win = MAX(ntohs(th->th_win), 1);
3617 if (s->src.wscale & PF_WSCALE_MASK) {
3618 /* Remove scale factor from initial window */
3619 int win = s->src.max_win;
3620 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3621 s->src.max_win = (win - 1) >>
3622 (s->src.wscale & PF_WSCALE_MASK);
3624 if (th->th_flags & TH_FIN)
3628 s->src.state = TCPS_SYN_SENT;
3629 s->dst.state = TCPS_CLOSED;
3630 s->timeout = PFTM_TCP_FIRST_PACKET;
3633 s->src.state = PFUDPS_SINGLE;
3634 s->dst.state = PFUDPS_NO_TRAFFIC;
3635 s->timeout = PFTM_UDP_FIRST_PACKET;
3639 case IPPROTO_ICMPV6:
3641 s->timeout = PFTM_ICMP_FIRST_PACKET;
3644 s->src.state = PFOTHERS_SINGLE;
3645 s->dst.state = PFOTHERS_NO_TRAFFIC;
3646 s->timeout = PFTM_OTHER_FIRST_PACKET;
3650 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3651 REASON_SET(&reason, PFRES_MAPFAILED);
3652 pf_src_tree_remove_state(s);
3653 STATE_DEC_COUNTERS(s);
3654 uma_zfree(V_pf_state_z, s);
3657 s->rt_kif = r->rpool.cur->kif;
3660 s->creation = time_uptime;
3661 s->expire = time_uptime;
3666 /* XXX We only modify one side for now. */
3667 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3668 s->nat_src_node = nsn;
3670 if (pd->proto == IPPROTO_TCP) {
3671 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3672 off, pd, th, &s->src, &s->dst)) {
3673 REASON_SET(&reason, PFRES_MEMORY);
3674 pf_src_tree_remove_state(s);
3675 STATE_DEC_COUNTERS(s);
3676 uma_zfree(V_pf_state_z, s);
3679 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3680 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3681 &s->src, &s->dst, rewrite)) {
3682 /* This really shouldn't happen!!! */
3683 DPFPRINTF(PF_DEBUG_URGENT,
3684 ("pf_normalize_tcp_stateful failed on first pkt"));
3685 pf_normalize_tcp_cleanup(s);
3686 pf_src_tree_remove_state(s);
3687 STATE_DEC_COUNTERS(s);
3688 uma_zfree(V_pf_state_z, s);
3692 s->direction = pd->dir;
3695 * sk/nk could already been setup by pf_get_translation().
3698 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3699 __func__, nr, sk, nk));
3700 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3705 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3706 __func__, nr, sk, nk));
3708 /* Swap sk/nk for PF_OUT. */
3709 if (pf_state_insert(BOUND_IFACE(r, kif),
3710 (pd->dir == PF_IN) ? sk : nk,
3711 (pd->dir == PF_IN) ? nk : sk, s)) {
3712 if (pd->proto == IPPROTO_TCP)
3713 pf_normalize_tcp_cleanup(s);
3714 REASON_SET(&reason, PFRES_STATEINS);
3715 pf_src_tree_remove_state(s);
3716 STATE_DEC_COUNTERS(s);
3717 uma_zfree(V_pf_state_z, s);
3724 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3725 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3726 s->src.state = PF_TCPS_PROXY_SRC;
3727 /* undo NAT changes, if they have taken place */
3729 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3730 if (pd->dir == PF_OUT)
3731 skt = s->key[PF_SK_STACK];
3732 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3733 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3735 *pd->sport = skt->port[pd->sidx];
3737 *pd->dport = skt->port[pd->didx];
3739 *pd->proto_sum = bproto_sum;
3741 *pd->ip_sum = bip_sum;
3742 m_copyback(m, off, hdrlen, pd->hdr.any);
3744 s->src.seqhi = htonl(arc4random());
3745 /* Find mss option */
3746 int rtid = M_GETFIB(m);
3747 mss = pf_get_mss(m, off, th->th_off, pd->af);
3748 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3749 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3751 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3752 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3753 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3754 REASON_SET(&reason, PFRES_SYNPROXY);
3755 return (PF_SYNPROXY_DROP);
3762 uma_zfree(V_pf_state_key_z, sk);
3764 uma_zfree(V_pf_state_key_z, nk);
3767 struct pf_srchash *sh;
3769 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3770 PF_HASHROW_LOCK(sh);
3771 if (--sn->states == 0 && sn->expire == 0) {
3772 pf_unlink_src_node(sn);
3773 uma_zfree(V_pf_sources_z, sn);
3775 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3777 PF_HASHROW_UNLOCK(sh);
3780 if (nsn != sn && nsn != NULL) {
3781 struct pf_srchash *sh;
3783 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3784 PF_HASHROW_LOCK(sh);
3785 if (--nsn->states == 0 && nsn->expire == 0) {
3786 pf_unlink_src_node(nsn);
3787 uma_zfree(V_pf_sources_z, nsn);
3789 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3791 PF_HASHROW_UNLOCK(sh);
3798 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3799 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3800 struct pf_ruleset **rsm)
3802 struct pf_rule *r, *a = NULL;
3803 struct pf_ruleset *ruleset = NULL;
3804 sa_family_t af = pd->af;
3809 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3813 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3816 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3817 r = r->skip[PF_SKIP_IFP].ptr;
3818 else if (r->direction && r->direction != direction)
3819 r = r->skip[PF_SKIP_DIR].ptr;
3820 else if (r->af && r->af != af)
3821 r = r->skip[PF_SKIP_AF].ptr;
3822 else if (r->proto && r->proto != pd->proto)
3823 r = r->skip[PF_SKIP_PROTO].ptr;
3824 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3825 r->src.neg, kif, M_GETFIB(m)))
3826 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3827 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3828 r->dst.neg, NULL, M_GETFIB(m)))
3829 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3830 else if (r->tos && !(r->tos == pd->tos))
3831 r = TAILQ_NEXT(r, entries);
3832 else if (r->os_fingerprint != PF_OSFP_ANY)
3833 r = TAILQ_NEXT(r, entries);
3834 else if (pd->proto == IPPROTO_UDP &&
3835 (r->src.port_op || r->dst.port_op))
3836 r = TAILQ_NEXT(r, entries);
3837 else if (pd->proto == IPPROTO_TCP &&
3838 (r->src.port_op || r->dst.port_op || r->flagset))
3839 r = TAILQ_NEXT(r, entries);
3840 else if ((pd->proto == IPPROTO_ICMP ||
3841 pd->proto == IPPROTO_ICMPV6) &&
3842 (r->type || r->code))
3843 r = TAILQ_NEXT(r, entries);
3845 !pf_match_ieee8021q_pcp(r->prio, m))
3846 r = TAILQ_NEXT(r, entries);
3847 else if (r->prob && r->prob <=
3848 (arc4random() % (UINT_MAX - 1) + 1))
3849 r = TAILQ_NEXT(r, entries);
3850 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3851 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3852 r = TAILQ_NEXT(r, entries);
3854 if (r->anchor == NULL) {
3861 r = TAILQ_NEXT(r, entries);
3863 pf_step_into_anchor(anchor_stack, &asd,
3864 &ruleset, PF_RULESET_FILTER, &r, &a,
3867 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3868 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3875 REASON_SET(&reason, PFRES_MATCH);
3878 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3881 if (r->action != PF_PASS)
3884 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3885 REASON_SET(&reason, PFRES_MEMORY);
3893 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3894 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3895 struct pf_pdesc *pd, u_short *reason, int *copyback)
3897 struct tcphdr *th = pd->hdr.tcp;
3898 u_int16_t win = ntohs(th->th_win);
3899 u_int32_t ack, end, seq, orig_seq;
3903 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3904 sws = src->wscale & PF_WSCALE_MASK;
3905 dws = dst->wscale & PF_WSCALE_MASK;
3910 * Sequence tracking algorithm from Guido van Rooij's paper:
3911 * http://www.madison-gurkha.com/publications/tcp_filtering/
3915 orig_seq = seq = ntohl(th->th_seq);
3916 if (src->seqlo == 0) {
3917 /* First packet from this end. Set its state */
3919 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3920 src->scrub == NULL) {
3921 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3922 REASON_SET(reason, PFRES_MEMORY);
3927 /* Deferred generation of sequence number modulator */
3928 if (dst->seqdiff && !src->seqdiff) {
3929 /* use random iss for the TCP server */
3930 while ((src->seqdiff = arc4random() - seq) == 0)
3932 ack = ntohl(th->th_ack) - dst->seqdiff;
3933 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3935 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3938 ack = ntohl(th->th_ack);
3941 end = seq + pd->p_len;
3942 if (th->th_flags & TH_SYN) {
3944 if (dst->wscale & PF_WSCALE_FLAG) {
3945 src->wscale = pf_get_wscale(m, off, th->th_off,
3947 if (src->wscale & PF_WSCALE_FLAG) {
3948 /* Remove scale factor from initial
3950 sws = src->wscale & PF_WSCALE_MASK;
3951 win = ((u_int32_t)win + (1 << sws) - 1)
3953 dws = dst->wscale & PF_WSCALE_MASK;
3955 /* fixup other window */
3956 dst->max_win <<= dst->wscale &
3958 /* in case of a retrans SYN|ACK */
3963 if (th->th_flags & TH_FIN)
3967 if (src->state < TCPS_SYN_SENT)
3968 src->state = TCPS_SYN_SENT;
3971 * May need to slide the window (seqhi may have been set by
3972 * the crappy stack check or if we picked up the connection
3973 * after establishment)
3975 if (src->seqhi == 1 ||
3976 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3977 src->seqhi = end + MAX(1, dst->max_win << dws);
3978 if (win > src->max_win)
3982 ack = ntohl(th->th_ack) - dst->seqdiff;
3984 /* Modulate sequence numbers */
3985 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3987 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3990 end = seq + pd->p_len;
3991 if (th->th_flags & TH_SYN)
3993 if (th->th_flags & TH_FIN)
3997 if ((th->th_flags & TH_ACK) == 0) {
3998 /* Let it pass through the ack skew check */
4000 } else if ((ack == 0 &&
4001 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4002 /* broken tcp stacks do not set ack */
4003 (dst->state < TCPS_SYN_SENT)) {
4005 * Many stacks (ours included) will set the ACK number in an
4006 * FIN|ACK if the SYN times out -- no sequence to ACK.
4012 /* Ease sequencing restrictions on no data packets */
4017 ackskew = dst->seqlo - ack;
4021 * Need to demodulate the sequence numbers in any TCP SACK options
4022 * (Selective ACK). We could optionally validate the SACK values
4023 * against the current ACK window, either forwards or backwards, but
4024 * I'm not confident that SACK has been implemented properly
4025 * everywhere. It wouldn't surprise me if several stacks accidentally
4026 * SACK too far backwards of previously ACKed data. There really aren't
4027 * any security implications of bad SACKing unless the target stack
4028 * doesn't validate the option length correctly. Someone trying to
4029 * spoof into a TCP connection won't bother blindly sending SACK
4032 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4033 if (pf_modulate_sack(m, off, pd, th, dst))
4038 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4039 if (SEQ_GEQ(src->seqhi, end) &&
4040 /* Last octet inside other's window space */
4041 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4042 /* Retrans: not more than one window back */
4043 (ackskew >= -MAXACKWINDOW) &&
4044 /* Acking not more than one reassembled fragment backwards */
4045 (ackskew <= (MAXACKWINDOW << sws)) &&
4046 /* Acking not more than one window forward */
4047 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4048 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4049 (pd->flags & PFDESC_IP_REAS) == 0)) {
4050 /* Require an exact/+1 sequence match on resets when possible */
4052 if (dst->scrub || src->scrub) {
4053 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4054 *state, src, dst, copyback))
4058 /* update max window */
4059 if (src->max_win < win)
4061 /* synchronize sequencing */
4062 if (SEQ_GT(end, src->seqlo))
4064 /* slide the window of what the other end can send */
4065 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4066 dst->seqhi = ack + MAX((win << sws), 1);
4070 if (th->th_flags & TH_SYN)
4071 if (src->state < TCPS_SYN_SENT)
4072 src->state = TCPS_SYN_SENT;
4073 if (th->th_flags & TH_FIN)
4074 if (src->state < TCPS_CLOSING)
4075 src->state = TCPS_CLOSING;
4076 if (th->th_flags & TH_ACK) {
4077 if (dst->state == TCPS_SYN_SENT) {
4078 dst->state = TCPS_ESTABLISHED;
4079 if (src->state == TCPS_ESTABLISHED &&
4080 (*state)->src_node != NULL &&
4081 pf_src_connlimit(state)) {
4082 REASON_SET(reason, PFRES_SRCLIMIT);
4085 } else if (dst->state == TCPS_CLOSING)
4086 dst->state = TCPS_FIN_WAIT_2;
4088 if (th->th_flags & TH_RST)
4089 src->state = dst->state = TCPS_TIME_WAIT;
4091 /* update expire time */
4092 (*state)->expire = time_uptime;
4093 if (src->state >= TCPS_FIN_WAIT_2 &&
4094 dst->state >= TCPS_FIN_WAIT_2)
4095 (*state)->timeout = PFTM_TCP_CLOSED;
4096 else if (src->state >= TCPS_CLOSING &&
4097 dst->state >= TCPS_CLOSING)
4098 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4099 else if (src->state < TCPS_ESTABLISHED ||
4100 dst->state < TCPS_ESTABLISHED)
4101 (*state)->timeout = PFTM_TCP_OPENING;
4102 else if (src->state >= TCPS_CLOSING ||
4103 dst->state >= TCPS_CLOSING)
4104 (*state)->timeout = PFTM_TCP_CLOSING;
4106 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4108 /* Fall through to PASS packet */
4110 } else if ((dst->state < TCPS_SYN_SENT ||
4111 dst->state >= TCPS_FIN_WAIT_2 ||
4112 src->state >= TCPS_FIN_WAIT_2) &&
4113 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4114 /* Within a window forward of the originating packet */
4115 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4116 /* Within a window backward of the originating packet */
4119 * This currently handles three situations:
4120 * 1) Stupid stacks will shotgun SYNs before their peer
4122 * 2) When PF catches an already established stream (the
4123 * firewall rebooted, the state table was flushed, routes
4125 * 3) Packets get funky immediately after the connection
4126 * closes (this should catch Solaris spurious ACK|FINs
4127 * that web servers like to spew after a close)
4129 * This must be a little more careful than the above code
4130 * since packet floods will also be caught here. We don't
4131 * update the TTL here to mitigate the damage of a packet
4132 * flood and so the same code can handle awkward establishment
4133 * and a loosened connection close.
4134 * In the establishment case, a correct peer response will
4135 * validate the connection, go through the normal state code
4136 * and keep updating the state TTL.
4139 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4140 printf("pf: loose state match: ");
4141 pf_print_state(*state);
4142 pf_print_flags(th->th_flags);
4143 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4144 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4145 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4146 (unsigned long long)(*state)->packets[1],
4147 pd->dir == PF_IN ? "in" : "out",
4148 pd->dir == (*state)->direction ? "fwd" : "rev");
4151 if (dst->scrub || src->scrub) {
4152 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4153 *state, src, dst, copyback))
4157 /* update max window */
4158 if (src->max_win < win)
4160 /* synchronize sequencing */
4161 if (SEQ_GT(end, src->seqlo))
4163 /* slide the window of what the other end can send */
4164 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4165 dst->seqhi = ack + MAX((win << sws), 1);
4168 * Cannot set dst->seqhi here since this could be a shotgunned
4169 * SYN and not an already established connection.
4172 if (th->th_flags & TH_FIN)
4173 if (src->state < TCPS_CLOSING)
4174 src->state = TCPS_CLOSING;
4175 if (th->th_flags & TH_RST)
4176 src->state = dst->state = TCPS_TIME_WAIT;
4178 /* Fall through to PASS packet */
4181 if ((*state)->dst.state == TCPS_SYN_SENT &&
4182 (*state)->src.state == TCPS_SYN_SENT) {
4183 /* Send RST for state mismatches during handshake */
4184 if (!(th->th_flags & TH_RST))
4185 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4186 pd->dst, pd->src, th->th_dport,
4187 th->th_sport, ntohl(th->th_ack), 0,
4189 (*state)->rule.ptr->return_ttl, 1, 0,
4194 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4195 printf("pf: BAD state: ");
4196 pf_print_state(*state);
4197 pf_print_flags(th->th_flags);
4198 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4199 "pkts=%llu:%llu dir=%s,%s\n",
4200 seq, orig_seq, ack, pd->p_len, ackskew,
4201 (unsigned long long)(*state)->packets[0],
4202 (unsigned long long)(*state)->packets[1],
4203 pd->dir == PF_IN ? "in" : "out",
4204 pd->dir == (*state)->direction ? "fwd" : "rev");
4205 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4206 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4207 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4209 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4210 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4211 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4212 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4214 REASON_SET(reason, PFRES_BADSTATE);
4222 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4223 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4225 struct tcphdr *th = pd->hdr.tcp;
4227 if (th->th_flags & TH_SYN)
4228 if (src->state < TCPS_SYN_SENT)
4229 src->state = TCPS_SYN_SENT;
4230 if (th->th_flags & TH_FIN)
4231 if (src->state < TCPS_CLOSING)
4232 src->state = TCPS_CLOSING;
4233 if (th->th_flags & TH_ACK) {
4234 if (dst->state == TCPS_SYN_SENT) {
4235 dst->state = TCPS_ESTABLISHED;
4236 if (src->state == TCPS_ESTABLISHED &&
4237 (*state)->src_node != NULL &&
4238 pf_src_connlimit(state)) {
4239 REASON_SET(reason, PFRES_SRCLIMIT);
4242 } else if (dst->state == TCPS_CLOSING) {
4243 dst->state = TCPS_FIN_WAIT_2;
4244 } else if (src->state == TCPS_SYN_SENT &&
4245 dst->state < TCPS_SYN_SENT) {
4247 * Handle a special sloppy case where we only see one
4248 * half of the connection. If there is a ACK after
4249 * the initial SYN without ever seeing a packet from
4250 * the destination, set the connection to established.
4252 dst->state = src->state = TCPS_ESTABLISHED;
4253 if ((*state)->src_node != NULL &&
4254 pf_src_connlimit(state)) {
4255 REASON_SET(reason, PFRES_SRCLIMIT);
4258 } else if (src->state == TCPS_CLOSING &&
4259 dst->state == TCPS_ESTABLISHED &&
4262 * Handle the closing of half connections where we
4263 * don't see the full bidirectional FIN/ACK+ACK
4266 dst->state = TCPS_CLOSING;
4269 if (th->th_flags & TH_RST)
4270 src->state = dst->state = TCPS_TIME_WAIT;
4272 /* update expire time */
4273 (*state)->expire = time_uptime;
4274 if (src->state >= TCPS_FIN_WAIT_2 &&
4275 dst->state >= TCPS_FIN_WAIT_2)
4276 (*state)->timeout = PFTM_TCP_CLOSED;
4277 else if (src->state >= TCPS_CLOSING &&
4278 dst->state >= TCPS_CLOSING)
4279 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4280 else if (src->state < TCPS_ESTABLISHED ||
4281 dst->state < TCPS_ESTABLISHED)
4282 (*state)->timeout = PFTM_TCP_OPENING;
4283 else if (src->state >= TCPS_CLOSING ||
4284 dst->state >= TCPS_CLOSING)
4285 (*state)->timeout = PFTM_TCP_CLOSING;
4287 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4293 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4294 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4297 struct pf_state_key_cmp key;
4298 struct tcphdr *th = pd->hdr.tcp;
4300 struct pf_state_peer *src, *dst;
4301 struct pf_state_key *sk;
4303 bzero(&key, sizeof(key));
4305 key.proto = IPPROTO_TCP;
4306 if (direction == PF_IN) { /* wire side, straight */
4307 PF_ACPY(&key.addr[0], pd->src, key.af);
4308 PF_ACPY(&key.addr[1], pd->dst, key.af);
4309 key.port[0] = th->th_sport;
4310 key.port[1] = th->th_dport;
4311 } else { /* stack side, reverse */
4312 PF_ACPY(&key.addr[1], pd->src, key.af);
4313 PF_ACPY(&key.addr[0], pd->dst, key.af);
4314 key.port[1] = th->th_sport;
4315 key.port[0] = th->th_dport;
4318 STATE_LOOKUP(kif, &key, direction, *state, pd);
4320 if (direction == (*state)->direction) {
4321 src = &(*state)->src;
4322 dst = &(*state)->dst;
4324 src = &(*state)->dst;
4325 dst = &(*state)->src;
4328 sk = (*state)->key[pd->didx];
4330 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4331 if (direction != (*state)->direction) {
4332 REASON_SET(reason, PFRES_SYNPROXY);
4333 return (PF_SYNPROXY_DROP);
4335 if (th->th_flags & TH_SYN) {
4336 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4337 REASON_SET(reason, PFRES_SYNPROXY);
4340 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4341 pd->src, th->th_dport, th->th_sport,
4342 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4343 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4344 REASON_SET(reason, PFRES_SYNPROXY);
4345 return (PF_SYNPROXY_DROP);
4346 } else if (!(th->th_flags & TH_ACK) ||
4347 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4348 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4349 REASON_SET(reason, PFRES_SYNPROXY);
4351 } else if ((*state)->src_node != NULL &&
4352 pf_src_connlimit(state)) {
4353 REASON_SET(reason, PFRES_SRCLIMIT);
4356 (*state)->src.state = PF_TCPS_PROXY_DST;
4358 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4359 if (direction == (*state)->direction) {
4360 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4361 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4362 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4363 REASON_SET(reason, PFRES_SYNPROXY);
4366 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4367 if ((*state)->dst.seqhi == 1)
4368 (*state)->dst.seqhi = htonl(arc4random());
4369 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4370 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4371 sk->port[pd->sidx], sk->port[pd->didx],
4372 (*state)->dst.seqhi, 0, TH_SYN, 0,
4373 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4374 REASON_SET(reason, PFRES_SYNPROXY);
4375 return (PF_SYNPROXY_DROP);
4376 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4378 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4379 REASON_SET(reason, PFRES_SYNPROXY);
4382 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4383 (*state)->dst.seqlo = ntohl(th->th_seq);
4384 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4385 pd->src, th->th_dport, th->th_sport,
4386 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4387 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4388 (*state)->tag, NULL);
4389 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4390 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4391 sk->port[pd->sidx], sk->port[pd->didx],
4392 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4393 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4394 (*state)->src.seqdiff = (*state)->dst.seqhi -
4395 (*state)->src.seqlo;
4396 (*state)->dst.seqdiff = (*state)->src.seqhi -
4397 (*state)->dst.seqlo;
4398 (*state)->src.seqhi = (*state)->src.seqlo +
4399 (*state)->dst.max_win;
4400 (*state)->dst.seqhi = (*state)->dst.seqlo +
4401 (*state)->src.max_win;
4402 (*state)->src.wscale = (*state)->dst.wscale = 0;
4403 (*state)->src.state = (*state)->dst.state =
4405 REASON_SET(reason, PFRES_SYNPROXY);
4406 return (PF_SYNPROXY_DROP);
4410 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4411 dst->state >= TCPS_FIN_WAIT_2 &&
4412 src->state >= TCPS_FIN_WAIT_2) {
4413 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4414 printf("pf: state reuse ");
4415 pf_print_state(*state);
4416 pf_print_flags(th->th_flags);
4419 /* XXX make sure it's the same direction ?? */
4420 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4421 pf_unlink_state(*state, PF_ENTER_LOCKED);
4426 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4427 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4430 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4431 ©back) == PF_DROP)
4435 /* translate source/destination address, if necessary */
4436 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4437 struct pf_state_key *nk = (*state)->key[pd->didx];
4439 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4440 nk->port[pd->sidx] != th->th_sport)
4441 pf_change_ap(m, pd->src, &th->th_sport,
4442 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4443 nk->port[pd->sidx], 0, pd->af);
4445 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4446 nk->port[pd->didx] != th->th_dport)
4447 pf_change_ap(m, pd->dst, &th->th_dport,
4448 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4449 nk->port[pd->didx], 0, pd->af);
4453 /* Copyback sequence modulation or stateful scrub changes if needed */
4455 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4461 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4462 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4464 struct pf_state_peer *src, *dst;
4465 struct pf_state_key_cmp key;
4466 struct udphdr *uh = pd->hdr.udp;
4468 bzero(&key, sizeof(key));
4470 key.proto = IPPROTO_UDP;
4471 if (direction == PF_IN) { /* wire side, straight */
4472 PF_ACPY(&key.addr[0], pd->src, key.af);
4473 PF_ACPY(&key.addr[1], pd->dst, key.af);
4474 key.port[0] = uh->uh_sport;
4475 key.port[1] = uh->uh_dport;
4476 } else { /* stack side, reverse */
4477 PF_ACPY(&key.addr[1], pd->src, key.af);
4478 PF_ACPY(&key.addr[0], pd->dst, key.af);
4479 key.port[1] = uh->uh_sport;
4480 key.port[0] = uh->uh_dport;
4483 STATE_LOOKUP(kif, &key, direction, *state, pd);
4485 if (direction == (*state)->direction) {
4486 src = &(*state)->src;
4487 dst = &(*state)->dst;
4489 src = &(*state)->dst;
4490 dst = &(*state)->src;
4494 if (src->state < PFUDPS_SINGLE)
4495 src->state = PFUDPS_SINGLE;
4496 if (dst->state == PFUDPS_SINGLE)
4497 dst->state = PFUDPS_MULTIPLE;
4499 /* update expire time */
4500 (*state)->expire = time_uptime;
4501 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4502 (*state)->timeout = PFTM_UDP_MULTIPLE;
4504 (*state)->timeout = PFTM_UDP_SINGLE;
4506 /* translate source/destination address, if necessary */
4507 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4508 struct pf_state_key *nk = (*state)->key[pd->didx];
4510 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4511 nk->port[pd->sidx] != uh->uh_sport)
4512 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4513 &uh->uh_sum, &nk->addr[pd->sidx],
4514 nk->port[pd->sidx], 1, pd->af);
4516 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4517 nk->port[pd->didx] != uh->uh_dport)
4518 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4519 &uh->uh_sum, &nk->addr[pd->didx],
4520 nk->port[pd->didx], 1, pd->af);
4521 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4528 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4529 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4531 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4532 u_int16_t icmpid = 0, *icmpsum;
4535 struct pf_state_key_cmp key;
4537 bzero(&key, sizeof(key));
4538 switch (pd->proto) {
4541 icmptype = pd->hdr.icmp->icmp_type;
4542 icmpid = pd->hdr.icmp->icmp_id;
4543 icmpsum = &pd->hdr.icmp->icmp_cksum;
4545 if (icmptype == ICMP_UNREACH ||
4546 icmptype == ICMP_SOURCEQUENCH ||
4547 icmptype == ICMP_REDIRECT ||
4548 icmptype == ICMP_TIMXCEED ||
4549 icmptype == ICMP_PARAMPROB)
4554 case IPPROTO_ICMPV6:
4555 icmptype = pd->hdr.icmp6->icmp6_type;
4556 icmpid = pd->hdr.icmp6->icmp6_id;
4557 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4559 if (icmptype == ICMP6_DST_UNREACH ||
4560 icmptype == ICMP6_PACKET_TOO_BIG ||
4561 icmptype == ICMP6_TIME_EXCEEDED ||
4562 icmptype == ICMP6_PARAM_PROB)
4571 * ICMP query/reply message not related to a TCP/UDP packet.
4572 * Search for an ICMP state.
4575 key.proto = pd->proto;
4576 key.port[0] = key.port[1] = icmpid;
4577 if (direction == PF_IN) { /* wire side, straight */
4578 PF_ACPY(&key.addr[0], pd->src, key.af);
4579 PF_ACPY(&key.addr[1], pd->dst, key.af);
4580 } else { /* stack side, reverse */
4581 PF_ACPY(&key.addr[1], pd->src, key.af);
4582 PF_ACPY(&key.addr[0], pd->dst, key.af);
4585 STATE_LOOKUP(kif, &key, direction, *state, pd);
4587 (*state)->expire = time_uptime;
4588 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4590 /* translate source/destination address, if necessary */
4591 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4592 struct pf_state_key *nk = (*state)->key[pd->didx];
4597 if (PF_ANEQ(pd->src,
4598 &nk->addr[pd->sidx], AF_INET))
4599 pf_change_a(&saddr->v4.s_addr,
4601 nk->addr[pd->sidx].v4.s_addr, 0);
4603 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4605 pf_change_a(&daddr->v4.s_addr,
4607 nk->addr[pd->didx].v4.s_addr, 0);
4610 pd->hdr.icmp->icmp_id) {
4611 pd->hdr.icmp->icmp_cksum =
4613 pd->hdr.icmp->icmp_cksum, icmpid,
4614 nk->port[pd->sidx], 0);
4615 pd->hdr.icmp->icmp_id =
4619 m_copyback(m, off, ICMP_MINLEN,
4620 (caddr_t )pd->hdr.icmp);
4625 if (PF_ANEQ(pd->src,
4626 &nk->addr[pd->sidx], AF_INET6))
4628 &pd->hdr.icmp6->icmp6_cksum,
4629 &nk->addr[pd->sidx], 0);
4631 if (PF_ANEQ(pd->dst,
4632 &nk->addr[pd->didx], AF_INET6))
4634 &pd->hdr.icmp6->icmp6_cksum,
4635 &nk->addr[pd->didx], 0);
4637 m_copyback(m, off, sizeof(struct icmp6_hdr),
4638 (caddr_t )pd->hdr.icmp6);
4647 * ICMP error message in response to a TCP/UDP packet.
4648 * Extract the inner TCP/UDP header and search for that state.
4651 struct pf_pdesc pd2;
4652 bzero(&pd2, sizeof pd2);
4657 struct ip6_hdr h2_6;
4664 /* Payload packet is from the opposite direction. */
4665 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4666 pd2.didx = (direction == PF_IN) ? 0 : 1;
4670 /* offset of h2 in mbuf chain */
4671 ipoff2 = off + ICMP_MINLEN;
4673 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4674 NULL, reason, pd2.af)) {
4675 DPFPRINTF(PF_DEBUG_MISC,
4676 ("pf: ICMP error message too short "
4681 * ICMP error messages don't refer to non-first
4684 if (h2.ip_off & htons(IP_OFFMASK)) {
4685 REASON_SET(reason, PFRES_FRAG);
4689 /* offset of protocol header that follows h2 */
4690 off2 = ipoff2 + (h2.ip_hl << 2);
4692 pd2.proto = h2.ip_p;
4693 pd2.src = (struct pf_addr *)&h2.ip_src;
4694 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4695 pd2.ip_sum = &h2.ip_sum;
4700 ipoff2 = off + sizeof(struct icmp6_hdr);
4702 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4703 NULL, reason, pd2.af)) {
4704 DPFPRINTF(PF_DEBUG_MISC,
4705 ("pf: ICMP error message too short "
4709 pd2.proto = h2_6.ip6_nxt;
4710 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4711 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4713 off2 = ipoff2 + sizeof(h2_6);
4715 switch (pd2.proto) {
4716 case IPPROTO_FRAGMENT:
4718 * ICMPv6 error messages for
4719 * non-first fragments
4721 REASON_SET(reason, PFRES_FRAG);
4724 case IPPROTO_HOPOPTS:
4725 case IPPROTO_ROUTING:
4726 case IPPROTO_DSTOPTS: {
4727 /* get next header and header length */
4728 struct ip6_ext opt6;
4730 if (!pf_pull_hdr(m, off2, &opt6,
4731 sizeof(opt6), NULL, reason,
4733 DPFPRINTF(PF_DEBUG_MISC,
4734 ("pf: ICMPv6 short opt\n"));
4737 if (pd2.proto == IPPROTO_AH)
4738 off2 += (opt6.ip6e_len + 2) * 4;
4740 off2 += (opt6.ip6e_len + 1) * 8;
4741 pd2.proto = opt6.ip6e_nxt;
4742 /* goto the next header */
4749 } while (!terminal);
4754 switch (pd2.proto) {
4758 struct pf_state_peer *src, *dst;
4763 * Only the first 8 bytes of the TCP header can be
4764 * expected. Don't access any TCP header fields after
4765 * th_seq, an ackskew test is not possible.
4767 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4769 DPFPRINTF(PF_DEBUG_MISC,
4770 ("pf: ICMP error message too short "
4776 key.proto = IPPROTO_TCP;
4777 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4778 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4779 key.port[pd2.sidx] = th.th_sport;
4780 key.port[pd2.didx] = th.th_dport;
4782 STATE_LOOKUP(kif, &key, direction, *state, pd);
4784 if (direction == (*state)->direction) {
4785 src = &(*state)->dst;
4786 dst = &(*state)->src;
4788 src = &(*state)->src;
4789 dst = &(*state)->dst;
4792 if (src->wscale && dst->wscale)
4793 dws = dst->wscale & PF_WSCALE_MASK;
4797 /* Demodulate sequence number */
4798 seq = ntohl(th.th_seq) - src->seqdiff;
4800 pf_change_a(&th.th_seq, icmpsum,
4805 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4806 (!SEQ_GEQ(src->seqhi, seq) ||
4807 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4808 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4809 printf("pf: BAD ICMP %d:%d ",
4810 icmptype, pd->hdr.icmp->icmp_code);
4811 pf_print_host(pd->src, 0, pd->af);
4813 pf_print_host(pd->dst, 0, pd->af);
4815 pf_print_state(*state);
4816 printf(" seq=%u\n", seq);
4818 REASON_SET(reason, PFRES_BADSTATE);
4821 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4822 printf("pf: OK ICMP %d:%d ",
4823 icmptype, pd->hdr.icmp->icmp_code);
4824 pf_print_host(pd->src, 0, pd->af);
4826 pf_print_host(pd->dst, 0, pd->af);
4828 pf_print_state(*state);
4829 printf(" seq=%u\n", seq);
4833 /* translate source/destination address, if necessary */
4834 if ((*state)->key[PF_SK_WIRE] !=
4835 (*state)->key[PF_SK_STACK]) {
4836 struct pf_state_key *nk =
4837 (*state)->key[pd->didx];
4839 if (PF_ANEQ(pd2.src,
4840 &nk->addr[pd2.sidx], pd2.af) ||
4841 nk->port[pd2.sidx] != th.th_sport)
4842 pf_change_icmp(pd2.src, &th.th_sport,
4843 daddr, &nk->addr[pd2.sidx],
4844 nk->port[pd2.sidx], NULL,
4845 pd2.ip_sum, icmpsum,
4846 pd->ip_sum, 0, pd2.af);
4848 if (PF_ANEQ(pd2.dst,
4849 &nk->addr[pd2.didx], pd2.af) ||
4850 nk->port[pd2.didx] != th.th_dport)
4851 pf_change_icmp(pd2.dst, &th.th_dport,
4852 saddr, &nk->addr[pd2.didx],
4853 nk->port[pd2.didx], NULL,
4854 pd2.ip_sum, icmpsum,
4855 pd->ip_sum, 0, pd2.af);
4863 m_copyback(m, off, ICMP_MINLEN,
4864 (caddr_t )pd->hdr.icmp);
4865 m_copyback(m, ipoff2, sizeof(h2),
4872 sizeof(struct icmp6_hdr),
4873 (caddr_t )pd->hdr.icmp6);
4874 m_copyback(m, ipoff2, sizeof(h2_6),
4879 m_copyback(m, off2, 8, (caddr_t)&th);
4888 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4889 NULL, reason, pd2.af)) {
4890 DPFPRINTF(PF_DEBUG_MISC,
4891 ("pf: ICMP error message too short "
4897 key.proto = IPPROTO_UDP;
4898 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4899 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4900 key.port[pd2.sidx] = uh.uh_sport;
4901 key.port[pd2.didx] = uh.uh_dport;
4903 STATE_LOOKUP(kif, &key, direction, *state, pd);
4905 /* translate source/destination address, if necessary */
4906 if ((*state)->key[PF_SK_WIRE] !=
4907 (*state)->key[PF_SK_STACK]) {
4908 struct pf_state_key *nk =
4909 (*state)->key[pd->didx];
4911 if (PF_ANEQ(pd2.src,
4912 &nk->addr[pd2.sidx], pd2.af) ||
4913 nk->port[pd2.sidx] != uh.uh_sport)
4914 pf_change_icmp(pd2.src, &uh.uh_sport,
4915 daddr, &nk->addr[pd2.sidx],
4916 nk->port[pd2.sidx], &uh.uh_sum,
4917 pd2.ip_sum, icmpsum,
4918 pd->ip_sum, 1, pd2.af);
4920 if (PF_ANEQ(pd2.dst,
4921 &nk->addr[pd2.didx], pd2.af) ||
4922 nk->port[pd2.didx] != uh.uh_dport)
4923 pf_change_icmp(pd2.dst, &uh.uh_dport,
4924 saddr, &nk->addr[pd2.didx],
4925 nk->port[pd2.didx], &uh.uh_sum,
4926 pd2.ip_sum, icmpsum,
4927 pd->ip_sum, 1, pd2.af);
4932 m_copyback(m, off, ICMP_MINLEN,
4933 (caddr_t )pd->hdr.icmp);
4934 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4940 sizeof(struct icmp6_hdr),
4941 (caddr_t )pd->hdr.icmp6);
4942 m_copyback(m, ipoff2, sizeof(h2_6),
4947 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4953 case IPPROTO_ICMP: {
4956 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4957 NULL, reason, pd2.af)) {
4958 DPFPRINTF(PF_DEBUG_MISC,
4959 ("pf: ICMP error message too short i"
4965 key.proto = IPPROTO_ICMP;
4966 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4967 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4968 key.port[0] = key.port[1] = iih.icmp_id;
4970 STATE_LOOKUP(kif, &key, direction, *state, pd);
4972 /* translate source/destination address, if necessary */
4973 if ((*state)->key[PF_SK_WIRE] !=
4974 (*state)->key[PF_SK_STACK]) {
4975 struct pf_state_key *nk =
4976 (*state)->key[pd->didx];
4978 if (PF_ANEQ(pd2.src,
4979 &nk->addr[pd2.sidx], pd2.af) ||
4980 nk->port[pd2.sidx] != iih.icmp_id)
4981 pf_change_icmp(pd2.src, &iih.icmp_id,
4982 daddr, &nk->addr[pd2.sidx],
4983 nk->port[pd2.sidx], NULL,
4984 pd2.ip_sum, icmpsum,
4985 pd->ip_sum, 0, AF_INET);
4987 if (PF_ANEQ(pd2.dst,
4988 &nk->addr[pd2.didx], pd2.af) ||
4989 nk->port[pd2.didx] != iih.icmp_id)
4990 pf_change_icmp(pd2.dst, &iih.icmp_id,
4991 saddr, &nk->addr[pd2.didx],
4992 nk->port[pd2.didx], NULL,
4993 pd2.ip_sum, icmpsum,
4994 pd->ip_sum, 0, AF_INET);
4996 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4997 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4998 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5005 case IPPROTO_ICMPV6: {
5006 struct icmp6_hdr iih;
5008 if (!pf_pull_hdr(m, off2, &iih,
5009 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5010 DPFPRINTF(PF_DEBUG_MISC,
5011 ("pf: ICMP error message too short "
5017 key.proto = IPPROTO_ICMPV6;
5018 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5019 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5020 key.port[0] = key.port[1] = iih.icmp6_id;
5022 STATE_LOOKUP(kif, &key, direction, *state, pd);
5024 /* translate source/destination address, if necessary */
5025 if ((*state)->key[PF_SK_WIRE] !=
5026 (*state)->key[PF_SK_STACK]) {
5027 struct pf_state_key *nk =
5028 (*state)->key[pd->didx];
5030 if (PF_ANEQ(pd2.src,
5031 &nk->addr[pd2.sidx], pd2.af) ||
5032 nk->port[pd2.sidx] != iih.icmp6_id)
5033 pf_change_icmp(pd2.src, &iih.icmp6_id,
5034 daddr, &nk->addr[pd2.sidx],
5035 nk->port[pd2.sidx], NULL,
5036 pd2.ip_sum, icmpsum,
5037 pd->ip_sum, 0, AF_INET6);
5039 if (PF_ANEQ(pd2.dst,
5040 &nk->addr[pd2.didx], pd2.af) ||
5041 nk->port[pd2.didx] != iih.icmp6_id)
5042 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5043 saddr, &nk->addr[pd2.didx],
5044 nk->port[pd2.didx], NULL,
5045 pd2.ip_sum, icmpsum,
5046 pd->ip_sum, 0, AF_INET6);
5048 m_copyback(m, off, sizeof(struct icmp6_hdr),
5049 (caddr_t)pd->hdr.icmp6);
5050 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5051 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5060 key.proto = pd2.proto;
5061 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5062 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5063 key.port[0] = key.port[1] = 0;
5065 STATE_LOOKUP(kif, &key, direction, *state, pd);
5067 /* translate source/destination address, if necessary */
5068 if ((*state)->key[PF_SK_WIRE] !=
5069 (*state)->key[PF_SK_STACK]) {
5070 struct pf_state_key *nk =
5071 (*state)->key[pd->didx];
5073 if (PF_ANEQ(pd2.src,
5074 &nk->addr[pd2.sidx], pd2.af))
5075 pf_change_icmp(pd2.src, NULL, daddr,
5076 &nk->addr[pd2.sidx], 0, NULL,
5077 pd2.ip_sum, icmpsum,
5078 pd->ip_sum, 0, pd2.af);
5080 if (PF_ANEQ(pd2.dst,
5081 &nk->addr[pd2.didx], pd2.af))
5082 pf_change_icmp(pd2.dst, NULL, saddr,
5083 &nk->addr[pd2.didx], 0, NULL,
5084 pd2.ip_sum, icmpsum,
5085 pd->ip_sum, 0, pd2.af);
5090 m_copyback(m, off, ICMP_MINLEN,
5091 (caddr_t)pd->hdr.icmp);
5092 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5098 sizeof(struct icmp6_hdr),
5099 (caddr_t )pd->hdr.icmp6);
5100 m_copyback(m, ipoff2, sizeof(h2_6),
5114 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5115 struct mbuf *m, struct pf_pdesc *pd)
5117 struct pf_state_peer *src, *dst;
5118 struct pf_state_key_cmp key;
5120 bzero(&key, sizeof(key));
5122 key.proto = pd->proto;
5123 if (direction == PF_IN) {
5124 PF_ACPY(&key.addr[0], pd->src, key.af);
5125 PF_ACPY(&key.addr[1], pd->dst, key.af);
5126 key.port[0] = key.port[1] = 0;
5128 PF_ACPY(&key.addr[1], pd->src, key.af);
5129 PF_ACPY(&key.addr[0], pd->dst, key.af);
5130 key.port[1] = key.port[0] = 0;
5133 STATE_LOOKUP(kif, &key, direction, *state, pd);
5135 if (direction == (*state)->direction) {
5136 src = &(*state)->src;
5137 dst = &(*state)->dst;
5139 src = &(*state)->dst;
5140 dst = &(*state)->src;
5144 if (src->state < PFOTHERS_SINGLE)
5145 src->state = PFOTHERS_SINGLE;
5146 if (dst->state == PFOTHERS_SINGLE)
5147 dst->state = PFOTHERS_MULTIPLE;
5149 /* update expire time */
5150 (*state)->expire = time_uptime;
5151 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5152 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5154 (*state)->timeout = PFTM_OTHER_SINGLE;
5156 /* translate source/destination address, if necessary */
5157 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5158 struct pf_state_key *nk = (*state)->key[pd->didx];
5160 KASSERT(nk, ("%s: nk is null", __func__));
5161 KASSERT(pd, ("%s: pd is null", __func__));
5162 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5163 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5167 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5168 pf_change_a(&pd->src->v4.s_addr,
5170 nk->addr[pd->sidx].v4.s_addr,
5174 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5175 pf_change_a(&pd->dst->v4.s_addr,
5177 nk->addr[pd->didx].v4.s_addr,
5184 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5185 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5187 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5188 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5196 * ipoff and off are measured from the start of the mbuf chain.
5197 * h must be at "ipoff" on the mbuf chain.
5200 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5201 u_short *actionp, u_short *reasonp, sa_family_t af)
5206 struct ip *h = mtod(m, struct ip *);
5207 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5211 ACTION_SET(actionp, PF_PASS);
5213 ACTION_SET(actionp, PF_DROP);
5214 REASON_SET(reasonp, PFRES_FRAG);
5218 if (m->m_pkthdr.len < off + len ||
5219 ntohs(h->ip_len) < off + len) {
5220 ACTION_SET(actionp, PF_DROP);
5221 REASON_SET(reasonp, PFRES_SHORT);
5229 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5231 if (m->m_pkthdr.len < off + len ||
5232 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5233 (unsigned)(off + len)) {
5234 ACTION_SET(actionp, PF_DROP);
5235 REASON_SET(reasonp, PFRES_SHORT);
5242 m_copydata(m, off, len, p);
5248 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5251 struct radix_node_head *rnh;
5252 struct sockaddr_in *dst;
5256 struct sockaddr_in6 *dst6;
5257 struct route_in6 ro;
5261 struct radix_node *rn;
5266 /* XXX: stick to table 0 for now */
5267 rnh = rt_tables_get_rnh(0, af);
5268 if (rnh != NULL && rn_mpath_capable(rnh))
5270 bzero(&ro, sizeof(ro));
5273 dst = satosin(&ro.ro_dst);
5274 dst->sin_family = AF_INET;
5275 dst->sin_len = sizeof(*dst);
5276 dst->sin_addr = addr->v4;
5281 * Skip check for addresses with embedded interface scope,
5282 * as they would always match anyway.
5284 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5286 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5287 dst6->sin6_family = AF_INET6;
5288 dst6->sin6_len = sizeof(*dst6);
5289 dst6->sin6_addr = addr->v6;
5296 /* Skip checks for ipsec interfaces */
5297 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5303 in6_rtalloc_ign(&ro, 0, rtableid);
5308 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5313 if (ro.ro_rt != NULL) {
5314 /* No interface given, this is a no-route check */
5318 if (kif->pfik_ifp == NULL) {
5323 /* Perform uRPF check if passed input interface */
5325 rn = (struct radix_node *)ro.ro_rt;
5327 rt = (struct rtentry *)rn;
5330 if (kif->pfik_ifp == ifp)
5332 rn = rn_mpath_next(rn);
5333 } while (check_mpath == 1 && rn != NULL && ret == 0);
5337 if (ro.ro_rt != NULL)
5344 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5348 struct nhop4_basic nh4;
5351 struct nhop6_basic nh6;
5355 struct radix_node_head *rnh;
5357 /* XXX: stick to table 0 for now */
5358 rnh = rt_tables_get_rnh(0, af);
5359 if (rnh != NULL && rn_mpath_capable(rnh))
5360 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5363 * Skip check for addresses with embedded interface scope,
5364 * as they would always match anyway.
5366 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5369 if (af != AF_INET && af != AF_INET6)
5372 /* Skip checks for ipsec interfaces */
5373 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5381 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5388 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5395 /* No interface given, this is a no-route check */
5399 if (kif->pfik_ifp == NULL)
5402 /* Perform uRPF check if passed input interface */
5403 if (kif->pfik_ifp == ifp)
5410 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5411 struct pf_state *s, struct pf_pdesc *pd)
5413 struct mbuf *m0, *m1;
5414 struct sockaddr_in dst;
5416 struct ifnet *ifp = NULL;
5417 struct pf_addr naddr;
5418 struct pf_src_node *sn = NULL;
5420 uint16_t ip_len, ip_off;
5422 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5423 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5426 if ((pd->pf_mtag == NULL &&
5427 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5428 pd->pf_mtag->routed++ > 3) {
5434 if (r->rt == PF_DUPTO) {
5435 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5441 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5449 ip = mtod(m0, struct ip *);
5451 bzero(&dst, sizeof(dst));
5452 dst.sin_family = AF_INET;
5453 dst.sin_len = sizeof(dst);
5454 dst.sin_addr = ip->ip_dst;
5456 if (TAILQ_EMPTY(&r->rpool.list)) {
5457 DPFPRINTF(PF_DEBUG_URGENT,
5458 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5462 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5464 if (!PF_AZERO(&naddr, AF_INET))
5465 dst.sin_addr.s_addr = naddr.v4.s_addr;
5466 ifp = r->rpool.cur->kif ?
5467 r->rpool.cur->kif->pfik_ifp : NULL;
5469 if (!PF_AZERO(&s->rt_addr, AF_INET))
5470 dst.sin_addr.s_addr =
5471 s->rt_addr.v4.s_addr;
5472 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5479 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5481 else if (m0 == NULL)
5483 if (m0->m_len < sizeof(struct ip)) {
5484 DPFPRINTF(PF_DEBUG_URGENT,
5485 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5488 ip = mtod(m0, struct ip *);
5491 if (ifp->if_flags & IFF_LOOPBACK)
5492 m0->m_flags |= M_SKIP_FIREWALL;
5494 ip_len = ntohs(ip->ip_len);
5495 ip_off = ntohs(ip->ip_off);
5497 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5498 m0->m_pkthdr.csum_flags |= CSUM_IP;
5499 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5500 in_delayed_cksum(m0);
5501 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5504 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5505 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5506 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5511 * If small enough for interface, or the interface will take
5512 * care of the fragmentation for us, we can just send directly.
5514 if (ip_len <= ifp->if_mtu ||
5515 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5517 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5518 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5519 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5521 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5522 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5526 /* Balk when DF bit is set or the interface didn't support TSO. */
5527 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5529 KMOD_IPSTAT_INC(ips_cantfrag);
5530 if (r->rt != PF_DUPTO) {
5531 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5538 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5542 for (; m0; m0 = m1) {
5544 m0->m_nextpkt = NULL;
5546 m_clrprotoflags(m0);
5547 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5553 KMOD_IPSTAT_INC(ips_fragmented);
5556 if (r->rt != PF_DUPTO)
5571 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5572 struct pf_state *s, struct pf_pdesc *pd)
5575 struct sockaddr_in6 dst;
5576 struct ip6_hdr *ip6;
5577 struct ifnet *ifp = NULL;
5578 struct pf_addr naddr;
5579 struct pf_src_node *sn = NULL;
5581 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5582 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5585 if ((pd->pf_mtag == NULL &&
5586 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5587 pd->pf_mtag->routed++ > 3) {
5593 if (r->rt == PF_DUPTO) {
5594 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5600 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5608 ip6 = mtod(m0, struct ip6_hdr *);
5610 bzero(&dst, sizeof(dst));
5611 dst.sin6_family = AF_INET6;
5612 dst.sin6_len = sizeof(dst);
5613 dst.sin6_addr = ip6->ip6_dst;
5615 if (TAILQ_EMPTY(&r->rpool.list)) {
5616 DPFPRINTF(PF_DEBUG_URGENT,
5617 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5621 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5623 if (!PF_AZERO(&naddr, AF_INET6))
5624 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5626 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5628 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5629 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5630 &s->rt_addr, AF_INET6);
5631 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5641 if (pf_test6(PF_FWD, ifp, &m0, NULL) != PF_PASS)
5643 else if (m0 == NULL)
5645 if (m0->m_len < sizeof(struct ip6_hdr)) {
5646 DPFPRINTF(PF_DEBUG_URGENT,
5647 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5651 ip6 = mtod(m0, struct ip6_hdr *);
5654 if (ifp->if_flags & IFF_LOOPBACK)
5655 m0->m_flags |= M_SKIP_FIREWALL;
5657 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5658 ~ifp->if_hwassist) {
5659 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5660 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5661 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5665 * If the packet is too large for the outgoing interface,
5666 * send back an icmp6 error.
5668 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5669 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5670 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5671 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5673 in6_ifstat_inc(ifp, ifs6_in_toobig);
5674 if (r->rt != PF_DUPTO)
5675 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5681 if (r->rt != PF_DUPTO)
5695 * FreeBSD supports cksum offloads for the following drivers.
5696 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5697 * ti(4), txp(4), xl(4)
5699 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5700 * network driver performed cksum including pseudo header, need to verify
5703 * network driver performed cksum, needs to additional pseudo header
5704 * cksum computation with partial csum_data(i.e. lack of H/W support for
5705 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5707 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5708 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5710 * Also, set csum_data to 0xffff to force cksum validation.
5713 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5719 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5721 if (m->m_pkthdr.len < off + len)
5726 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5727 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5728 sum = m->m_pkthdr.csum_data;
5730 ip = mtod(m, struct ip *);
5731 sum = in_pseudo(ip->ip_src.s_addr,
5732 ip->ip_dst.s_addr, htonl((u_short)len +
5733 m->m_pkthdr.csum_data + IPPROTO_TCP));
5740 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5741 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5742 sum = m->m_pkthdr.csum_data;
5744 ip = mtod(m, struct ip *);
5745 sum = in_pseudo(ip->ip_src.s_addr,
5746 ip->ip_dst.s_addr, htonl((u_short)len +
5747 m->m_pkthdr.csum_data + IPPROTO_UDP));
5755 case IPPROTO_ICMPV6:
5765 if (p == IPPROTO_ICMP) {
5770 sum = in_cksum(m, len);
5774 if (m->m_len < sizeof(struct ip))
5776 sum = in4_cksum(m, p, off, len);
5781 if (m->m_len < sizeof(struct ip6_hdr))
5783 sum = in6_cksum(m, p, off, len);
5794 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5799 KMOD_UDPSTAT_INC(udps_badsum);
5805 KMOD_ICMPSTAT_INC(icps_checksum);
5810 case IPPROTO_ICMPV6:
5812 KMOD_ICMP6STAT_INC(icp6s_checksum);
5819 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5820 m->m_pkthdr.csum_flags |=
5821 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5822 m->m_pkthdr.csum_data = 0xffff;
5831 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5833 struct pfi_kif *kif;
5834 u_short action, reason = 0, log = 0;
5835 struct mbuf *m = *m0;
5836 struct ip *h = NULL;
5837 struct m_tag *ipfwtag;
5838 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5839 struct pf_state *s = NULL;
5840 struct pf_ruleset *ruleset = NULL;
5842 int off, dirndx, pqid = 0;
5846 if (!V_pf_status.running)
5849 memset(&pd, 0, sizeof(pd));
5851 kif = (struct pfi_kif *)ifp->if_pf_kif;
5854 DPFPRINTF(PF_DEBUG_URGENT,
5855 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5858 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5861 if (m->m_flags & M_SKIP_FIREWALL)
5864 pd.pf_mtag = pf_find_mtag(m);
5868 if (ip_divert_ptr != NULL &&
5869 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5870 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5871 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5872 if (pd.pf_mtag == NULL &&
5873 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5877 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5878 m_tag_delete(m, ipfwtag);
5880 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5881 m->m_flags |= M_FASTFWD_OURS;
5882 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5884 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5885 /* We do IP header normalization and packet reassembly here */
5889 m = *m0; /* pf_normalize messes with m0 */
5890 h = mtod(m, struct ip *);
5892 off = h->ip_hl << 2;
5893 if (off < (int)sizeof(struct ip)) {
5895 REASON_SET(&reason, PFRES_SHORT);
5900 pd.src = (struct pf_addr *)&h->ip_src;
5901 pd.dst = (struct pf_addr *)&h->ip_dst;
5902 pd.sport = pd.dport = NULL;
5903 pd.ip_sum = &h->ip_sum;
5904 pd.proto_sum = NULL;
5907 pd.sidx = (dir == PF_IN) ? 0 : 1;
5908 pd.didx = (dir == PF_IN) ? 1 : 0;
5910 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5911 pd.tot_len = ntohs(h->ip_len);
5913 /* handle fragments that didn't get reassembled by normalization */
5914 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5915 action = pf_test_fragment(&r, dir, kif, m, h,
5926 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5927 &action, &reason, AF_INET)) {
5928 log = action != PF_PASS;
5931 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5932 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5934 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5935 if (action == PF_DROP)
5937 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5939 if (action == PF_PASS) {
5940 if (pfsync_update_state_ptr != NULL)
5941 pfsync_update_state_ptr(s);
5945 } else if (s == NULL)
5946 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5955 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5956 &action, &reason, AF_INET)) {
5957 log = action != PF_PASS;
5960 if (uh.uh_dport == 0 ||
5961 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5962 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5964 REASON_SET(&reason, PFRES_SHORT);
5967 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5968 if (action == PF_PASS) {
5969 if (pfsync_update_state_ptr != NULL)
5970 pfsync_update_state_ptr(s);
5974 } else if (s == NULL)
5975 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5980 case IPPROTO_ICMP: {
5984 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5985 &action, &reason, AF_INET)) {
5986 log = action != PF_PASS;
5989 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5991 if (action == PF_PASS) {
5992 if (pfsync_update_state_ptr != NULL)
5993 pfsync_update_state_ptr(s);
5997 } else if (s == NULL)
5998 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6004 case IPPROTO_ICMPV6: {
6006 DPFPRINTF(PF_DEBUG_MISC,
6007 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6013 action = pf_test_state_other(&s, dir, kif, m, &pd);
6014 if (action == PF_PASS) {
6015 if (pfsync_update_state_ptr != NULL)
6016 pfsync_update_state_ptr(s);
6020 } else if (s == NULL)
6021 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6028 if (action == PF_PASS && h->ip_hl > 5 &&
6029 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6031 REASON_SET(&reason, PFRES_IPOPTIONS);
6033 DPFPRINTF(PF_DEBUG_MISC,
6034 ("pf: dropping packet with ip options\n"));
6037 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6039 REASON_SET(&reason, PFRES_MEMORY);
6041 if (r->rtableid >= 0)
6042 M_SETFIB(m, r->rtableid);
6044 if (r->scrub_flags & PFSTATE_SETPRIO) {
6045 if (pd.tos & IPTOS_LOWDELAY)
6047 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6049 REASON_SET(&reason, PFRES_MEMORY);
6051 DPFPRINTF(PF_DEBUG_MISC,
6052 ("pf: failed to allocate 802.1q mtag\n"));
6057 if (action == PF_PASS && r->qid) {
6058 if (pd.pf_mtag == NULL &&
6059 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6061 REASON_SET(&reason, PFRES_MEMORY);
6064 pd.pf_mtag->qid_hash = pf_state_hash(s);
6065 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6066 pd.pf_mtag->qid = r->pqid;
6068 pd.pf_mtag->qid = r->qid;
6069 /* Add hints for ecn. */
6070 pd.pf_mtag->hdr = h;
6077 * connections redirected to loopback should not match sockets
6078 * bound specifically to loopback due to security implications,
6079 * see tcp_input() and in_pcblookup_listen().
6081 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6082 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6083 (s->nat_rule.ptr->action == PF_RDR ||
6084 s->nat_rule.ptr->action == PF_BINAT) &&
6085 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6086 m->m_flags |= M_SKIP_FIREWALL;
6088 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6089 !PACKET_LOOPED(&pd)) {
6091 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6092 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6093 if (ipfwtag != NULL) {
6094 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6095 ntohs(r->divert.port);
6096 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6101 m_tag_prepend(m, ipfwtag);
6102 if (m->m_flags & M_FASTFWD_OURS) {
6103 if (pd.pf_mtag == NULL &&
6104 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6106 REASON_SET(&reason, PFRES_MEMORY);
6108 DPFPRINTF(PF_DEBUG_MISC,
6109 ("pf: failed to allocate tag\n"));
6111 pd.pf_mtag->flags |=
6112 PF_FASTFWD_OURS_PRESENT;
6113 m->m_flags &= ~M_FASTFWD_OURS;
6116 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6121 /* XXX: ipfw has the same behaviour! */
6123 REASON_SET(&reason, PFRES_MEMORY);
6125 DPFPRINTF(PF_DEBUG_MISC,
6126 ("pf: failed to allocate divert tag\n"));
6133 if (s != NULL && s->nat_rule.ptr != NULL &&
6134 s->nat_rule.ptr->log & PF_LOG_ALL)
6135 lr = s->nat_rule.ptr;
6138 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6142 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6143 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6145 if (action == PF_PASS || r->action == PF_DROP) {
6146 dirndx = (dir == PF_OUT);
6147 r->packets[dirndx]++;
6148 r->bytes[dirndx] += pd.tot_len;
6150 a->packets[dirndx]++;
6151 a->bytes[dirndx] += pd.tot_len;
6154 if (s->nat_rule.ptr != NULL) {
6155 s->nat_rule.ptr->packets[dirndx]++;
6156 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6158 if (s->src_node != NULL) {
6159 s->src_node->packets[dirndx]++;
6160 s->src_node->bytes[dirndx] += pd.tot_len;
6162 if (s->nat_src_node != NULL) {
6163 s->nat_src_node->packets[dirndx]++;
6164 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6166 dirndx = (dir == s->direction) ? 0 : 1;
6167 s->packets[dirndx]++;
6168 s->bytes[dirndx] += pd.tot_len;
6171 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6172 if (nr != NULL && r == &V_pf_default_rule)
6174 if (tr->src.addr.type == PF_ADDR_TABLE)
6175 pfr_update_stats(tr->src.addr.p.tbl,
6176 (s == NULL) ? pd.src :
6177 &s->key[(s->direction == PF_IN)]->
6178 addr[(s->direction == PF_OUT)],
6179 pd.af, pd.tot_len, dir == PF_OUT,
6180 r->action == PF_PASS, tr->src.neg);
6181 if (tr->dst.addr.type == PF_ADDR_TABLE)
6182 pfr_update_stats(tr->dst.addr.p.tbl,
6183 (s == NULL) ? pd.dst :
6184 &s->key[(s->direction == PF_IN)]->
6185 addr[(s->direction == PF_IN)],
6186 pd.af, pd.tot_len, dir == PF_OUT,
6187 r->action == PF_PASS, tr->dst.neg);
6191 case PF_SYNPROXY_DROP:
6202 /* pf_route() returns unlocked. */
6204 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6218 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6220 struct pfi_kif *kif;
6221 u_short action, reason = 0, log = 0;
6222 struct mbuf *m = *m0, *n = NULL;
6224 struct ip6_hdr *h = NULL;
6225 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6226 struct pf_state *s = NULL;
6227 struct pf_ruleset *ruleset = NULL;
6229 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6234 /* Detect packet forwarding.
6235 * If the input interface is different from the output interface we're
6237 * We do need to be careful about bridges. If the
6238 * net.link.bridge.pfil_bridge sysctl is set we can be filtering on a
6239 * bridge, so if the input interface is a bridge member and the output
6240 * interface is its bridge or a member of the same bridge we're not
6241 * actually forwarding but bridging.
6243 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif &&
6244 (m->m_pkthdr.rcvif->if_bridge == NULL ||
6245 (m->m_pkthdr.rcvif->if_bridge != ifp->if_softc &&
6246 m->m_pkthdr.rcvif->if_bridge != ifp->if_bridge)))
6249 if (!V_pf_status.running)
6252 memset(&pd, 0, sizeof(pd));
6253 pd.pf_mtag = pf_find_mtag(m);
6255 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6258 kif = (struct pfi_kif *)ifp->if_pf_kif;
6260 DPFPRINTF(PF_DEBUG_URGENT,
6261 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6264 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6267 if (m->m_flags & M_SKIP_FIREWALL)
6272 /* We do IP header normalization and packet reassembly here */
6273 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6277 m = *m0; /* pf_normalize messes with m0 */
6278 h = mtod(m, struct ip6_hdr *);
6282 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6283 * will do something bad, so drop the packet for now.
6285 if (htons(h->ip6_plen) == 0) {
6287 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6292 pd.src = (struct pf_addr *)&h->ip6_src;
6293 pd.dst = (struct pf_addr *)&h->ip6_dst;
6294 pd.sport = pd.dport = NULL;
6296 pd.proto_sum = NULL;
6298 pd.sidx = (dir == PF_IN) ? 0 : 1;
6299 pd.didx = (dir == PF_IN) ? 1 : 0;
6302 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6304 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6305 pd.proto = h->ip6_nxt;
6308 case IPPROTO_FRAGMENT:
6309 action = pf_test_fragment(&r, dir, kif, m, h,
6311 if (action == PF_DROP)
6312 REASON_SET(&reason, PFRES_FRAG);
6314 case IPPROTO_ROUTING: {
6315 struct ip6_rthdr rthdr;
6318 DPFPRINTF(PF_DEBUG_MISC,
6319 ("pf: IPv6 more than one rthdr\n"));
6321 REASON_SET(&reason, PFRES_IPOPTIONS);
6325 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6327 DPFPRINTF(PF_DEBUG_MISC,
6328 ("pf: IPv6 short rthdr\n"));
6330 REASON_SET(&reason, PFRES_SHORT);
6334 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6335 DPFPRINTF(PF_DEBUG_MISC,
6336 ("pf: IPv6 rthdr0\n"));
6338 REASON_SET(&reason, PFRES_IPOPTIONS);
6345 case IPPROTO_HOPOPTS:
6346 case IPPROTO_DSTOPTS: {
6347 /* get next header and header length */
6348 struct ip6_ext opt6;
6350 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6351 NULL, &reason, pd.af)) {
6352 DPFPRINTF(PF_DEBUG_MISC,
6353 ("pf: IPv6 short opt\n"));
6358 if (pd.proto == IPPROTO_AH)
6359 off += (opt6.ip6e_len + 2) * 4;
6361 off += (opt6.ip6e_len + 1) * 8;
6362 pd.proto = opt6.ip6e_nxt;
6363 /* goto the next header */
6370 } while (!terminal);
6372 /* if there's no routing header, use unmodified mbuf for checksumming */
6382 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6383 &action, &reason, AF_INET6)) {
6384 log = action != PF_PASS;
6387 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6388 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6389 if (action == PF_DROP)
6391 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6393 if (action == PF_PASS) {
6394 if (pfsync_update_state_ptr != NULL)
6395 pfsync_update_state_ptr(s);
6399 } else if (s == NULL)
6400 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6409 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6410 &action, &reason, AF_INET6)) {
6411 log = action != PF_PASS;
6414 if (uh.uh_dport == 0 ||
6415 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6416 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6418 REASON_SET(&reason, PFRES_SHORT);
6421 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6422 if (action == PF_PASS) {
6423 if (pfsync_update_state_ptr != NULL)
6424 pfsync_update_state_ptr(s);
6428 } else if (s == NULL)
6429 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6434 case IPPROTO_ICMP: {
6436 DPFPRINTF(PF_DEBUG_MISC,
6437 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6441 case IPPROTO_ICMPV6: {
6442 struct icmp6_hdr ih;
6445 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6446 &action, &reason, AF_INET6)) {
6447 log = action != PF_PASS;
6450 action = pf_test_state_icmp(&s, dir, kif,
6451 m, off, h, &pd, &reason);
6452 if (action == PF_PASS) {
6453 if (pfsync_update_state_ptr != NULL)
6454 pfsync_update_state_ptr(s);
6458 } else if (s == NULL)
6459 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6465 action = pf_test_state_other(&s, dir, kif, m, &pd);
6466 if (action == PF_PASS) {
6467 if (pfsync_update_state_ptr != NULL)
6468 pfsync_update_state_ptr(s);
6472 } else if (s == NULL)
6473 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6485 /* handle dangerous IPv6 extension headers. */
6486 if (action == PF_PASS && rh_cnt &&
6487 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6489 REASON_SET(&reason, PFRES_IPOPTIONS);
6491 DPFPRINTF(PF_DEBUG_MISC,
6492 ("pf: dropping packet with dangerous v6 headers\n"));
6495 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6497 REASON_SET(&reason, PFRES_MEMORY);
6499 if (r->rtableid >= 0)
6500 M_SETFIB(m, r->rtableid);
6502 if (r->scrub_flags & PFSTATE_SETPRIO) {
6503 if (pd.tos & IPTOS_LOWDELAY)
6505 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6507 REASON_SET(&reason, PFRES_MEMORY);
6509 DPFPRINTF(PF_DEBUG_MISC,
6510 ("pf: failed to allocate 802.1q mtag\n"));
6515 if (action == PF_PASS && r->qid) {
6516 if (pd.pf_mtag == NULL &&
6517 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6519 REASON_SET(&reason, PFRES_MEMORY);
6522 pd.pf_mtag->qid_hash = pf_state_hash(s);
6523 if (pd.tos & IPTOS_LOWDELAY)
6524 pd.pf_mtag->qid = r->pqid;
6526 pd.pf_mtag->qid = r->qid;
6527 /* Add hints for ecn. */
6528 pd.pf_mtag->hdr = h;
6533 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6534 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6535 (s->nat_rule.ptr->action == PF_RDR ||
6536 s->nat_rule.ptr->action == PF_BINAT) &&
6537 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6538 m->m_flags |= M_SKIP_FIREWALL;
6540 /* XXX: Anybody working on it?! */
6542 printf("pf: divert(9) is not supported for IPv6\n");
6547 if (s != NULL && s->nat_rule.ptr != NULL &&
6548 s->nat_rule.ptr->log & PF_LOG_ALL)
6549 lr = s->nat_rule.ptr;
6552 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6556 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6557 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6559 if (action == PF_PASS || r->action == PF_DROP) {
6560 dirndx = (dir == PF_OUT);
6561 r->packets[dirndx]++;
6562 r->bytes[dirndx] += pd.tot_len;
6564 a->packets[dirndx]++;
6565 a->bytes[dirndx] += pd.tot_len;
6568 if (s->nat_rule.ptr != NULL) {
6569 s->nat_rule.ptr->packets[dirndx]++;
6570 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6572 if (s->src_node != NULL) {
6573 s->src_node->packets[dirndx]++;
6574 s->src_node->bytes[dirndx] += pd.tot_len;
6576 if (s->nat_src_node != NULL) {
6577 s->nat_src_node->packets[dirndx]++;
6578 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6580 dirndx = (dir == s->direction) ? 0 : 1;
6581 s->packets[dirndx]++;
6582 s->bytes[dirndx] += pd.tot_len;
6585 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6586 if (nr != NULL && r == &V_pf_default_rule)
6588 if (tr->src.addr.type == PF_ADDR_TABLE)
6589 pfr_update_stats(tr->src.addr.p.tbl,
6590 (s == NULL) ? pd.src :
6591 &s->key[(s->direction == PF_IN)]->addr[0],
6592 pd.af, pd.tot_len, dir == PF_OUT,
6593 r->action == PF_PASS, tr->src.neg);
6594 if (tr->dst.addr.type == PF_ADDR_TABLE)
6595 pfr_update_stats(tr->dst.addr.p.tbl,
6596 (s == NULL) ? pd.dst :
6597 &s->key[(s->direction == PF_IN)]->addr[1],
6598 pd.af, pd.tot_len, dir == PF_OUT,
6599 r->action == PF_PASS, tr->dst.neg);
6603 case PF_SYNPROXY_DROP:
6614 /* pf_route6() returns unlocked. */
6616 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6625 /* If reassembled packet passed, create new fragments. */
6626 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6627 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6628 action = pf_refragment6(ifp, m0, mtag);