2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2001 Daniel Hartmeier
5 * Copyright (c) 2002 - 2008 Henning Brauer
6 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * - Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * - Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials provided
18 * with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
33 * Effort sponsored in part by the Defense Advanced Research Projects
34 * Agency (DARPA) and Air Force Research Laboratory, Air Force
35 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
37 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
44 #include "opt_inet6.h"
48 #include <sys/param.h>
50 #include <sys/endian.h>
52 #include <sys/interrupt.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/limits.h>
58 #include <sys/random.h>
59 #include <sys/refcount.h>
60 #include <sys/socket.h>
61 #include <sys/sysctl.h>
62 #include <sys/taskqueue.h>
63 #include <sys/ucred.h>
66 #include <net/if_var.h>
67 #include <net/if_types.h>
68 #include <net/if_vlan_var.h>
69 #include <net/route.h>
70 #include <net/radix_mpath.h>
74 #include <net/pfvar.h>
75 #include <net/if_pflog.h>
76 #include <net/if_pfsync.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_var.h>
80 #include <netinet/in_fib.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_fw.h>
83 #include <netinet/ip_icmp.h>
84 #include <netinet/icmp_var.h>
85 #include <netinet/ip_var.h>
86 #include <netinet/tcp.h>
87 #include <netinet/tcp_fsm.h>
88 #include <netinet/tcp_seq.h>
89 #include <netinet/tcp_timer.h>
90 #include <netinet/tcp_var.h>
91 #include <netinet/udp.h>
92 #include <netinet/udp_var.h>
94 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
97 #include <netinet/ip6.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/nd6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/in6_pcb.h>
102 #include <netinet6/in6_fib.h>
103 #include <netinet6/scope6_var.h>
106 #include <machine/in_cksum.h>
107 #include <security/mac/mac_framework.h>
109 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
116 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
117 VNET_DEFINE(struct pf_palist, pf_pabuf);
118 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
119 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
120 VNET_DEFINE(struct pf_kstatus, pf_status);
122 VNET_DEFINE(u_int32_t, ticket_altqs_active);
123 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
124 VNET_DEFINE(int, altqs_inactive_open);
125 VNET_DEFINE(u_int32_t, ticket_pabuf);
127 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
128 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
129 VNET_DEFINE(u_char, pf_tcp_secret[16]);
130 #define V_pf_tcp_secret VNET(pf_tcp_secret)
131 VNET_DEFINE(int, pf_tcp_secret_init);
132 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
133 VNET_DEFINE(int, pf_tcp_iss_off);
134 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
135 VNET_DECLARE(int, pf_vnet_active);
136 #define V_pf_vnet_active VNET(pf_vnet_active)
138 static VNET_DEFINE(uint32_t, pf_purge_idx);
139 #define V_pf_purge_idx VNET(pf_purge_idx)
142 * Queue for pf_intr() sends.
144 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
145 struct pf_send_entry {
146 STAILQ_ENTRY(pf_send_entry) pfse_next;
161 STAILQ_HEAD(pf_send_head, pf_send_entry);
162 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
163 #define V_pf_sendqueue VNET(pf_sendqueue)
165 static struct mtx pf_sendqueue_mtx;
166 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
167 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
168 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
171 * Queue for pf_overload_task() tasks.
173 struct pf_overload_entry {
174 SLIST_ENTRY(pf_overload_entry) next;
178 struct pf_rule *rule;
181 SLIST_HEAD(pf_overload_head, pf_overload_entry);
182 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
183 #define V_pf_overloadqueue VNET(pf_overloadqueue)
184 static VNET_DEFINE(struct task, pf_overloadtask);
185 #define V_pf_overloadtask VNET(pf_overloadtask)
187 static struct mtx pf_overloadqueue_mtx;
188 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
189 "pf overload/flush queue", MTX_DEF);
190 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
191 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
193 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
194 struct mtx pf_unlnkdrules_mtx;
195 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
198 static VNET_DEFINE(uma_zone_t, pf_sources_z);
199 #define V_pf_sources_z VNET(pf_sources_z)
200 uma_zone_t pf_mtag_z;
201 VNET_DEFINE(uma_zone_t, pf_state_z);
202 VNET_DEFINE(uma_zone_t, pf_state_key_z);
204 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
205 #define PFID_CPUBITS 8
206 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
207 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
208 #define PFID_MAXID (~PFID_CPUMASK)
209 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
211 static void pf_src_tree_remove_state(struct pf_state *);
212 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
214 static void pf_add_threshold(struct pf_threshold *);
215 static int pf_check_threshold(struct pf_threshold *);
217 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
218 u_int16_t *, u_int16_t *, struct pf_addr *,
219 u_int16_t, u_int8_t, sa_family_t);
220 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
221 struct tcphdr *, struct pf_state_peer *);
222 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
223 struct pf_addr *, struct pf_addr *, u_int16_t,
224 u_int16_t *, u_int16_t *, u_int16_t *,
225 u_int16_t *, u_int8_t, sa_family_t);
226 static void pf_send_tcp(struct mbuf *,
227 const struct pf_rule *, sa_family_t,
228 const struct pf_addr *, const struct pf_addr *,
229 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
230 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
231 u_int16_t, struct ifnet *);
232 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
233 sa_family_t, struct pf_rule *);
234 static void pf_detach_state(struct pf_state *);
235 static int pf_state_key_attach(struct pf_state_key *,
236 struct pf_state_key *, struct pf_state *);
237 static void pf_state_key_detach(struct pf_state *, int);
238 static int pf_state_key_ctor(void *, int, void *, int);
239 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
240 static int pf_test_rule(struct pf_rule **, struct pf_state **,
241 int, struct pfi_kif *, struct mbuf *, int,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **, struct inpcb *);
244 static int pf_create_state(struct pf_rule *, struct pf_rule *,
245 struct pf_rule *, struct pf_pdesc *,
246 struct pf_src_node *, struct pf_state_key *,
247 struct pf_state_key *, struct mbuf *, int,
248 u_int16_t, u_int16_t, int *, struct pfi_kif *,
249 struct pf_state **, int, u_int16_t, u_int16_t,
251 static int pf_test_fragment(struct pf_rule **, int,
252 struct pfi_kif *, struct mbuf *, void *,
253 struct pf_pdesc *, struct pf_rule **,
254 struct pf_ruleset **);
255 static int pf_tcp_track_full(struct pf_state_peer *,
256 struct pf_state_peer *, struct pf_state **,
257 struct pfi_kif *, struct mbuf *, int,
258 struct pf_pdesc *, u_short *, int *);
259 static int pf_tcp_track_sloppy(struct pf_state_peer *,
260 struct pf_state_peer *, struct pf_state **,
261 struct pf_pdesc *, u_short *);
262 static int pf_test_state_tcp(struct pf_state **, int,
263 struct pfi_kif *, struct mbuf *, int,
264 void *, struct pf_pdesc *, u_short *);
265 static int pf_test_state_udp(struct pf_state **, int,
266 struct pfi_kif *, struct mbuf *, int,
267 void *, struct pf_pdesc *);
268 static int pf_test_state_icmp(struct pf_state **, int,
269 struct pfi_kif *, struct mbuf *, int,
270 void *, struct pf_pdesc *, u_short *);
271 static int pf_test_state_other(struct pf_state **, int,
272 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
273 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
275 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
277 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
279 static int pf_check_proto_cksum(struct mbuf *, int, int,
280 u_int8_t, sa_family_t);
281 static void pf_print_state_parts(struct pf_state *,
282 struct pf_state_key *, struct pf_state_key *);
283 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
284 struct pf_addr_wrap *);
285 static struct pf_state *pf_find_state(struct pfi_kif *,
286 struct pf_state_key_cmp *, u_int);
287 static int pf_src_connlimit(struct pf_state **);
288 static void pf_overload_task(void *v, int pending);
289 static int pf_insert_src_node(struct pf_src_node **,
290 struct pf_rule *, struct pf_addr *, sa_family_t);
291 static u_int pf_purge_expired_states(u_int, int);
292 static void pf_purge_unlinked_rules(void);
293 static int pf_mtag_uminit(void *, int, int);
294 static void pf_mtag_free(struct m_tag *);
296 static void pf_route(struct mbuf **, struct pf_rule *, int,
297 struct ifnet *, struct pf_state *,
301 static void pf_change_a6(struct pf_addr *, u_int16_t *,
302 struct pf_addr *, u_int8_t);
303 static void pf_route6(struct mbuf **, struct pf_rule *, int,
304 struct ifnet *, struct pf_state *,
308 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
310 extern int pf_end_threads;
311 extern struct proc *pf_purge_proc;
313 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
315 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
316 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
318 #define STATE_LOOKUP(i, k, d, s, pd) \
320 (s) = pf_find_state((i), (k), (d)); \
323 if (PACKET_LOOPED(pd)) \
325 if ((d) == PF_OUT && \
326 (((s)->rule.ptr->rt == PF_ROUTETO && \
327 (s)->rule.ptr->direction == PF_OUT) || \
328 ((s)->rule.ptr->rt == PF_REPLYTO && \
329 (s)->rule.ptr->direction == PF_IN)) && \
330 (s)->rt_kif != NULL && \
331 (s)->rt_kif != (i)) \
335 #define BOUND_IFACE(r, k) \
336 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
338 #define STATE_INC_COUNTERS(s) \
340 counter_u64_add(s->rule.ptr->states_cur, 1); \
341 counter_u64_add(s->rule.ptr->states_tot, 1); \
342 if (s->anchor.ptr != NULL) { \
343 counter_u64_add(s->anchor.ptr->states_cur, 1); \
344 counter_u64_add(s->anchor.ptr->states_tot, 1); \
346 if (s->nat_rule.ptr != NULL) { \
347 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
348 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
352 #define STATE_DEC_COUNTERS(s) \
354 if (s->nat_rule.ptr != NULL) \
355 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
356 if (s->anchor.ptr != NULL) \
357 counter_u64_add(s->anchor.ptr->states_cur, -1); \
358 counter_u64_add(s->rule.ptr->states_cur, -1); \
361 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
362 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
363 VNET_DEFINE(struct pf_idhash *, pf_idhash);
364 VNET_DEFINE(struct pf_srchash *, pf_srchash);
366 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
369 u_long pf_srchashmask;
370 static u_long pf_hashsize;
371 static u_long pf_srchashsize;
373 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
374 &pf_hashsize, 0, "Size of pf(4) states hashtable");
375 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
376 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
378 VNET_DEFINE(void *, pf_swi_cookie);
380 VNET_DEFINE(uint32_t, pf_hashseed);
381 #define V_pf_hashseed VNET(pf_hashseed)
384 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
390 if (a->addr32[0] > b->addr32[0])
392 if (a->addr32[0] < b->addr32[0])
398 if (a->addr32[3] > b->addr32[3])
400 if (a->addr32[3] < b->addr32[3])
402 if (a->addr32[2] > b->addr32[2])
404 if (a->addr32[2] < b->addr32[2])
406 if (a->addr32[1] > b->addr32[1])
408 if (a->addr32[1] < b->addr32[1])
410 if (a->addr32[0] > b->addr32[0])
412 if (a->addr32[0] < b->addr32[0])
417 panic("%s: unknown address family %u", __func__, af);
422 static __inline uint32_t
423 pf_hashkey(struct pf_state_key *sk)
427 h = murmur3_32_hash32((uint32_t *)sk,
428 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
431 return (h & pf_hashmask);
434 static __inline uint32_t
435 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
441 h = murmur3_32_hash32((uint32_t *)&addr->v4,
442 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
445 h = murmur3_32_hash32((uint32_t *)&addr->v6,
446 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
449 panic("%s: unknown address family %u", __func__, af);
452 return (h & pf_srchashmask);
457 pf_state_hash(struct pf_state *s)
459 u_int32_t hv = (intptr_t)s / sizeof(*s);
461 hv ^= crc32(&s->src, sizeof(s->src));
462 hv ^= crc32(&s->dst, sizeof(s->dst));
471 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
476 dst->addr32[0] = src->addr32[0];
480 dst->addr32[0] = src->addr32[0];
481 dst->addr32[1] = src->addr32[1];
482 dst->addr32[2] = src->addr32[2];
483 dst->addr32[3] = src->addr32[3];
490 pf_init_threshold(struct pf_threshold *threshold,
491 u_int32_t limit, u_int32_t seconds)
493 threshold->limit = limit * PF_THRESHOLD_MULT;
494 threshold->seconds = seconds;
495 threshold->count = 0;
496 threshold->last = time_uptime;
500 pf_add_threshold(struct pf_threshold *threshold)
502 u_int32_t t = time_uptime, diff = t - threshold->last;
504 if (diff >= threshold->seconds)
505 threshold->count = 0;
507 threshold->count -= threshold->count * diff /
509 threshold->count += PF_THRESHOLD_MULT;
514 pf_check_threshold(struct pf_threshold *threshold)
516 return (threshold->count > threshold->limit);
520 pf_src_connlimit(struct pf_state **state)
522 struct pf_overload_entry *pfoe;
525 PF_STATE_LOCK_ASSERT(*state);
527 (*state)->src_node->conn++;
528 (*state)->src.tcp_est = 1;
529 pf_add_threshold(&(*state)->src_node->conn_rate);
531 if ((*state)->rule.ptr->max_src_conn &&
532 (*state)->rule.ptr->max_src_conn <
533 (*state)->src_node->conn) {
534 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
538 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
539 pf_check_threshold(&(*state)->src_node->conn_rate)) {
540 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
547 /* Kill this state. */
548 (*state)->timeout = PFTM_PURGE;
549 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
551 if ((*state)->rule.ptr->overload_tbl == NULL)
554 /* Schedule overloading and flushing task. */
555 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
557 return (1); /* too bad :( */
559 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
560 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
561 pfoe->rule = (*state)->rule.ptr;
562 pfoe->dir = (*state)->direction;
564 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
565 PF_OVERLOADQ_UNLOCK();
566 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
572 pf_overload_task(void *v, int pending)
574 struct pf_overload_head queue;
576 struct pf_overload_entry *pfoe, *pfoe1;
579 CURVNET_SET((struct vnet *)v);
582 queue = V_pf_overloadqueue;
583 SLIST_INIT(&V_pf_overloadqueue);
584 PF_OVERLOADQ_UNLOCK();
586 bzero(&p, sizeof(p));
587 SLIST_FOREACH(pfoe, &queue, next) {
588 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
589 if (V_pf_status.debug >= PF_DEBUG_MISC) {
590 printf("%s: blocking address ", __func__);
591 pf_print_host(&pfoe->addr, 0, pfoe->af);
595 p.pfra_af = pfoe->af;
600 p.pfra_ip4addr = pfoe->addr.v4;
606 p.pfra_ip6addr = pfoe->addr.v6;
612 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
617 * Remove those entries, that don't need flushing.
619 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
620 if (pfoe->rule->flush == 0) {
621 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
622 free(pfoe, M_PFTEMP);
625 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
627 /* If nothing to flush, return. */
628 if (SLIST_EMPTY(&queue)) {
633 for (int i = 0; i <= pf_hashmask; i++) {
634 struct pf_idhash *ih = &V_pf_idhash[i];
635 struct pf_state_key *sk;
639 LIST_FOREACH(s, &ih->states, entry) {
640 sk = s->key[PF_SK_WIRE];
641 SLIST_FOREACH(pfoe, &queue, next)
642 if (sk->af == pfoe->af &&
643 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
644 pfoe->rule == s->rule.ptr) &&
645 ((pfoe->dir == PF_OUT &&
646 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
647 (pfoe->dir == PF_IN &&
648 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
649 s->timeout = PFTM_PURGE;
650 s->src.state = s->dst.state = TCPS_CLOSED;
654 PF_HASHROW_UNLOCK(ih);
656 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
657 free(pfoe, M_PFTEMP);
658 if (V_pf_status.debug >= PF_DEBUG_MISC)
659 printf("%s: %u states killed", __func__, killed);
665 * Can return locked on failure, so that we can consistently
666 * allocate and insert a new one.
669 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
672 struct pf_srchash *sh;
673 struct pf_src_node *n;
675 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
677 sh = &V_pf_srchash[pf_hashsrc(src, af)];
679 LIST_FOREACH(n, &sh->nodes, entry)
680 if (n->rule.ptr == rule && n->af == af &&
681 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
682 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
686 PF_HASHROW_UNLOCK(sh);
687 } else if (returnlocked == 0)
688 PF_HASHROW_UNLOCK(sh);
694 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
695 struct pf_addr *src, sa_family_t af)
698 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
699 rule->rpool.opts & PF_POOL_STICKYADDR),
700 ("%s for non-tracking rule %p", __func__, rule));
703 *sn = pf_find_src_node(src, rule, af, 1);
706 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
708 PF_HASHROW_ASSERT(sh);
710 if (!rule->max_src_nodes ||
711 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
712 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
714 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
717 PF_HASHROW_UNLOCK(sh);
721 pf_init_threshold(&(*sn)->conn_rate,
722 rule->max_src_conn_rate.limit,
723 rule->max_src_conn_rate.seconds);
726 (*sn)->rule.ptr = rule;
727 PF_ACPY(&(*sn)->addr, src, af);
728 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
729 (*sn)->creation = time_uptime;
730 (*sn)->ruletype = rule->action;
732 if ((*sn)->rule.ptr != NULL)
733 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
734 PF_HASHROW_UNLOCK(sh);
735 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
737 if (rule->max_src_states &&
738 (*sn)->states >= rule->max_src_states) {
739 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
748 pf_unlink_src_node(struct pf_src_node *src)
751 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
752 LIST_REMOVE(src, entry);
754 counter_u64_add(src->rule.ptr->src_nodes, -1);
758 pf_free_src_nodes(struct pf_src_node_list *head)
760 struct pf_src_node *sn, *tmp;
763 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
764 uma_zfree(V_pf_sources_z, sn);
768 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
777 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
778 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
782 /* Per-vnet data storage structures initialization. */
786 struct pf_keyhash *kh;
787 struct pf_idhash *ih;
788 struct pf_srchash *sh;
791 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
792 pf_hashsize = PF_HASHSIZ;
793 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
794 pf_srchashsize = PF_SRCHASHSIZ;
796 V_pf_hashseed = arc4random();
798 /* States and state keys storage. */
799 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
800 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
801 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
802 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
803 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
805 V_pf_state_key_z = uma_zcreate("pf state keys",
806 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
809 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
810 M_PFHASH, M_NOWAIT | M_ZERO);
811 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
812 M_PFHASH, M_NOWAIT | M_ZERO);
813 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
814 printf("pf: Unable to allocate memory for "
815 "state_hashsize %lu.\n", pf_hashsize);
817 free(V_pf_keyhash, M_PFHASH);
818 free(V_pf_idhash, M_PFHASH);
820 pf_hashsize = PF_HASHSIZ;
821 V_pf_keyhash = mallocarray(pf_hashsize,
822 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
823 V_pf_idhash = mallocarray(pf_hashsize,
824 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
827 pf_hashmask = pf_hashsize - 1;
828 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
830 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
831 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
835 V_pf_sources_z = uma_zcreate("pf source nodes",
836 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
838 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
839 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
840 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
842 V_pf_srchash = mallocarray(pf_srchashsize,
843 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
844 if (V_pf_srchash == NULL) {
845 printf("pf: Unable to allocate memory for "
846 "source_hashsize %lu.\n", pf_srchashsize);
848 pf_srchashsize = PF_SRCHASHSIZ;
849 V_pf_srchash = mallocarray(pf_srchashsize,
850 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
853 pf_srchashmask = pf_srchashsize - 1;
854 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
855 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
858 TAILQ_INIT(&V_pf_altqs[0]);
859 TAILQ_INIT(&V_pf_altqs[1]);
860 TAILQ_INIT(&V_pf_pabuf);
861 V_pf_altqs_active = &V_pf_altqs[0];
862 V_pf_altqs_inactive = &V_pf_altqs[1];
864 /* Send & overload+flush queues. */
865 STAILQ_INIT(&V_pf_sendqueue);
866 SLIST_INIT(&V_pf_overloadqueue);
867 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
869 /* Unlinked, but may be referenced rules. */
870 TAILQ_INIT(&V_pf_unlinked_rules);
877 uma_zdestroy(pf_mtag_z);
883 struct pf_keyhash *kh;
884 struct pf_idhash *ih;
885 struct pf_srchash *sh;
886 struct pf_send_entry *pfse, *next;
889 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
891 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
893 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
895 mtx_destroy(&kh->lock);
896 mtx_destroy(&ih->lock);
898 free(V_pf_keyhash, M_PFHASH);
899 free(V_pf_idhash, M_PFHASH);
901 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
902 KASSERT(LIST_EMPTY(&sh->nodes),
903 ("%s: source node hash not empty", __func__));
904 mtx_destroy(&sh->lock);
906 free(V_pf_srchash, M_PFHASH);
908 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
909 m_freem(pfse->pfse_m);
910 free(pfse, M_PFTEMP);
913 uma_zdestroy(V_pf_sources_z);
914 uma_zdestroy(V_pf_state_z);
915 uma_zdestroy(V_pf_state_key_z);
919 pf_mtag_uminit(void *mem, int size, int how)
923 t = (struct m_tag *)mem;
924 t->m_tag_cookie = MTAG_ABI_COMPAT;
925 t->m_tag_id = PACKET_TAG_PF;
926 t->m_tag_len = sizeof(struct pf_mtag);
927 t->m_tag_free = pf_mtag_free;
933 pf_mtag_free(struct m_tag *t)
936 uma_zfree(pf_mtag_z, t);
940 pf_get_mtag(struct mbuf *m)
944 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
945 return ((struct pf_mtag *)(mtag + 1));
947 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
950 bzero(mtag + 1, sizeof(struct pf_mtag));
951 m_tag_prepend(m, mtag);
953 return ((struct pf_mtag *)(mtag + 1));
957 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
960 struct pf_keyhash *khs, *khw, *kh;
961 struct pf_state_key *sk, *cur;
962 struct pf_state *si, *olds = NULL;
965 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
966 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
967 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
970 * We need to lock hash slots of both keys. To avoid deadlock
971 * we always lock the slot with lower address first. Unlock order
974 * We also need to lock ID hash slot before dropping key
975 * locks. On success we return with ID hash slot locked.
979 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
980 PF_HASHROW_LOCK(khs);
982 khs = &V_pf_keyhash[pf_hashkey(sks)];
983 khw = &V_pf_keyhash[pf_hashkey(skw)];
985 PF_HASHROW_LOCK(khs);
986 } else if (khs < khw) {
987 PF_HASHROW_LOCK(khs);
988 PF_HASHROW_LOCK(khw);
990 PF_HASHROW_LOCK(khw);
991 PF_HASHROW_LOCK(khs);
995 #define KEYS_UNLOCK() do { \
997 PF_HASHROW_UNLOCK(khs); \
998 PF_HASHROW_UNLOCK(khw); \
1000 PF_HASHROW_UNLOCK(khs); \
1004 * First run: start with wire key.
1011 LIST_FOREACH(cur, &kh->keys, entry)
1012 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1016 /* Key exists. Check for same kif, if none, add to key. */
1017 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1018 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1020 PF_HASHROW_LOCK(ih);
1021 if (si->kif == s->kif &&
1022 si->direction == s->direction) {
1023 if (sk->proto == IPPROTO_TCP &&
1024 si->src.state >= TCPS_FIN_WAIT_2 &&
1025 si->dst.state >= TCPS_FIN_WAIT_2) {
1027 * New state matches an old >FIN_WAIT_2
1028 * state. We can't drop key hash locks,
1029 * thus we can't unlink it properly.
1031 * As a workaround we drop it into
1032 * TCPS_CLOSED state, schedule purge
1033 * ASAP and push it into the very end
1034 * of the slot TAILQ, so that it won't
1035 * conflict with our new state.
1037 si->src.state = si->dst.state =
1039 si->timeout = PFTM_PURGE;
1042 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1043 printf("pf: %s key attach "
1045 (idx == PF_SK_WIRE) ?
1048 pf_print_state_parts(s,
1049 (idx == PF_SK_WIRE) ?
1051 (idx == PF_SK_STACK) ?
1053 printf(", existing: ");
1054 pf_print_state_parts(si,
1055 (idx == PF_SK_WIRE) ?
1057 (idx == PF_SK_STACK) ?
1061 PF_HASHROW_UNLOCK(ih);
1063 uma_zfree(V_pf_state_key_z, sk);
1064 if (idx == PF_SK_STACK)
1066 return (EEXIST); /* collision! */
1069 PF_HASHROW_UNLOCK(ih);
1071 uma_zfree(V_pf_state_key_z, sk);
1074 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1079 /* List is sorted, if-bound states before floating. */
1080 if (s->kif == V_pfi_all)
1081 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1083 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1086 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1087 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1093 * Attach done. See how should we (or should not?)
1094 * attach a second key.
1097 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1101 } else if (sks != NULL) {
1103 * Continue attaching with stack key.
1115 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1116 ("%s failure", __func__));
1123 pf_detach_state(struct pf_state *s)
1125 struct pf_state_key *sks = s->key[PF_SK_STACK];
1126 struct pf_keyhash *kh;
1129 kh = &V_pf_keyhash[pf_hashkey(sks)];
1130 PF_HASHROW_LOCK(kh);
1131 if (s->key[PF_SK_STACK] != NULL)
1132 pf_state_key_detach(s, PF_SK_STACK);
1134 * If both point to same key, then we are done.
1136 if (sks == s->key[PF_SK_WIRE]) {
1137 pf_state_key_detach(s, PF_SK_WIRE);
1138 PF_HASHROW_UNLOCK(kh);
1141 PF_HASHROW_UNLOCK(kh);
1144 if (s->key[PF_SK_WIRE] != NULL) {
1145 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1146 PF_HASHROW_LOCK(kh);
1147 if (s->key[PF_SK_WIRE] != NULL)
1148 pf_state_key_detach(s, PF_SK_WIRE);
1149 PF_HASHROW_UNLOCK(kh);
1154 pf_state_key_detach(struct pf_state *s, int idx)
1156 struct pf_state_key *sk = s->key[idx];
1158 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1160 PF_HASHROW_ASSERT(kh);
1162 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1165 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1166 LIST_REMOVE(sk, entry);
1167 uma_zfree(V_pf_state_key_z, sk);
1172 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1174 struct pf_state_key *sk = mem;
1176 bzero(sk, sizeof(struct pf_state_key_cmp));
1177 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1178 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1183 struct pf_state_key *
1184 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1185 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1187 struct pf_state_key *sk;
1189 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1193 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1194 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1195 sk->port[pd->sidx] = sport;
1196 sk->port[pd->didx] = dport;
1197 sk->proto = pd->proto;
1203 struct pf_state_key *
1204 pf_state_key_clone(struct pf_state_key *orig)
1206 struct pf_state_key *sk;
1208 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1212 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1218 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1219 struct pf_state_key *sks, struct pf_state *s)
1221 struct pf_idhash *ih;
1222 struct pf_state *cur;
1225 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1226 ("%s: sks not pristine", __func__));
1227 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1228 ("%s: skw not pristine", __func__));
1229 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1233 if (s->id == 0 && s->creatorid == 0) {
1234 /* XXX: should be atomic, but probability of collision low */
1235 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1236 V_pf_stateid[curcpu] = 1;
1237 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1238 s->id = htobe64(s->id);
1239 s->creatorid = V_pf_status.hostid;
1242 /* Returns with ID locked on success. */
1243 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1246 ih = &V_pf_idhash[PF_IDHASH(s)];
1247 PF_HASHROW_ASSERT(ih);
1248 LIST_FOREACH(cur, &ih->states, entry)
1249 if (cur->id == s->id && cur->creatorid == s->creatorid)
1253 PF_HASHROW_UNLOCK(ih);
1254 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1255 printf("pf: state ID collision: "
1256 "id: %016llx creatorid: %08x\n",
1257 (unsigned long long)be64toh(s->id),
1258 ntohl(s->creatorid));
1263 LIST_INSERT_HEAD(&ih->states, s, entry);
1264 /* One for keys, one for ID hash. */
1265 refcount_init(&s->refs, 2);
1267 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1268 if (pfsync_insert_state_ptr != NULL)
1269 pfsync_insert_state_ptr(s);
1271 /* Returns locked. */
1276 * Find state by ID: returns with locked row on success.
1279 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1281 struct pf_idhash *ih;
1284 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1286 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1288 PF_HASHROW_LOCK(ih);
1289 LIST_FOREACH(s, &ih->states, entry)
1290 if (s->id == id && s->creatorid == creatorid)
1294 PF_HASHROW_UNLOCK(ih);
1300 * Find state by key.
1301 * Returns with ID hash slot locked on success.
1303 static struct pf_state *
1304 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1306 struct pf_keyhash *kh;
1307 struct pf_state_key *sk;
1311 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1313 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1315 PF_HASHROW_LOCK(kh);
1316 LIST_FOREACH(sk, &kh->keys, entry)
1317 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1320 PF_HASHROW_UNLOCK(kh);
1324 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1326 /* List is sorted, if-bound states before floating ones. */
1327 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1328 if (s->kif == V_pfi_all || s->kif == kif) {
1330 PF_HASHROW_UNLOCK(kh);
1331 if (s->timeout >= PFTM_MAX) {
1333 * State is either being processed by
1334 * pf_unlink_state() in an other thread, or
1335 * is scheduled for immediate expiry.
1342 PF_HASHROW_UNLOCK(kh);
1348 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1350 struct pf_keyhash *kh;
1351 struct pf_state_key *sk;
1352 struct pf_state *s, *ret = NULL;
1355 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1357 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1359 PF_HASHROW_LOCK(kh);
1360 LIST_FOREACH(sk, &kh->keys, entry)
1361 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1364 PF_HASHROW_UNLOCK(kh);
1379 panic("%s: dir %u", __func__, dir);
1382 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1384 PF_HASHROW_UNLOCK(kh);
1398 PF_HASHROW_UNLOCK(kh);
1403 /* END state table stuff */
1406 pf_send(struct pf_send_entry *pfse)
1410 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1412 swi_sched(V_pf_swi_cookie, 0);
1418 struct pf_send_head queue;
1419 struct pf_send_entry *pfse, *next;
1421 CURVNET_SET((struct vnet *)v);
1424 queue = V_pf_sendqueue;
1425 STAILQ_INIT(&V_pf_sendqueue);
1428 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1429 switch (pfse->pfse_type) {
1432 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1435 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1436 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1441 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1445 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1446 pfse->icmpopts.code, pfse->icmpopts.mtu);
1450 panic("%s: unknown type", __func__);
1452 free(pfse, M_PFTEMP);
1458 pf_purge_thread(void *unused __unused)
1460 VNET_ITERATOR_DECL(vnet_iter);
1462 sx_xlock(&pf_end_lock);
1463 while (pf_end_threads == 0) {
1464 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1467 VNET_FOREACH(vnet_iter) {
1468 CURVNET_SET(vnet_iter);
1471 /* Wait until V_pf_default_rule is initialized. */
1472 if (V_pf_vnet_active == 0) {
1478 * Process 1/interval fraction of the state
1482 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1483 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1486 * Purge other expired types every
1487 * PFTM_INTERVAL seconds.
1489 if (V_pf_purge_idx == 0) {
1491 * Order is important:
1492 * - states and src nodes reference rules
1493 * - states and rules reference kifs
1495 pf_purge_expired_fragments();
1496 pf_purge_expired_src_nodes();
1497 pf_purge_unlinked_rules();
1502 VNET_LIST_RUNLOCK();
1506 sx_xunlock(&pf_end_lock);
1511 pf_unload_vnet_purge(void)
1515 * To cleanse up all kifs and rules we need
1516 * two runs: first one clears reference flags,
1517 * then pf_purge_expired_states() doesn't
1518 * raise them, and then second run frees.
1520 pf_purge_unlinked_rules();
1524 * Now purge everything.
1526 pf_purge_expired_states(0, pf_hashmask);
1527 pf_purge_fragments(UINT_MAX);
1528 pf_purge_expired_src_nodes();
1531 * Now all kifs & rules should be unreferenced,
1532 * thus should be successfully freed.
1534 pf_purge_unlinked_rules();
1540 pf_state_expires(const struct pf_state *state)
1547 /* handle all PFTM_* > PFTM_MAX here */
1548 if (state->timeout == PFTM_PURGE)
1549 return (time_uptime);
1550 KASSERT(state->timeout != PFTM_UNLINKED,
1551 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1552 KASSERT((state->timeout < PFTM_MAX),
1553 ("pf_state_expires: timeout > PFTM_MAX"));
1554 timeout = state->rule.ptr->timeout[state->timeout];
1556 timeout = V_pf_default_rule.timeout[state->timeout];
1557 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1559 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1560 states = counter_u64_fetch(state->rule.ptr->states_cur);
1562 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1563 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1564 states = V_pf_status.states;
1566 if (end && states > start && start < end) {
1568 return (state->expire + timeout * (end - states) /
1571 return (time_uptime);
1573 return (state->expire + timeout);
1577 pf_purge_expired_src_nodes()
1579 struct pf_src_node_list freelist;
1580 struct pf_srchash *sh;
1581 struct pf_src_node *cur, *next;
1584 LIST_INIT(&freelist);
1585 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1586 PF_HASHROW_LOCK(sh);
1587 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1588 if (cur->states == 0 && cur->expire <= time_uptime) {
1589 pf_unlink_src_node(cur);
1590 LIST_INSERT_HEAD(&freelist, cur, entry);
1591 } else if (cur->rule.ptr != NULL)
1592 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1593 PF_HASHROW_UNLOCK(sh);
1596 pf_free_src_nodes(&freelist);
1598 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1602 pf_src_tree_remove_state(struct pf_state *s)
1604 struct pf_src_node *sn;
1605 struct pf_srchash *sh;
1608 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1609 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1610 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1612 if (s->src_node != NULL) {
1614 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1615 PF_HASHROW_LOCK(sh);
1618 if (--sn->states == 0)
1619 sn->expire = time_uptime + timeout;
1620 PF_HASHROW_UNLOCK(sh);
1622 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1623 sn = s->nat_src_node;
1624 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1625 PF_HASHROW_LOCK(sh);
1626 if (--sn->states == 0)
1627 sn->expire = time_uptime + timeout;
1628 PF_HASHROW_UNLOCK(sh);
1630 s->src_node = s->nat_src_node = NULL;
1634 * Unlink and potentilly free a state. Function may be
1635 * called with ID hash row locked, but always returns
1636 * unlocked, since it needs to go through key hash locking.
1639 pf_unlink_state(struct pf_state *s, u_int flags)
1641 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1643 if ((flags & PF_ENTER_LOCKED) == 0)
1644 PF_HASHROW_LOCK(ih);
1646 PF_HASHROW_ASSERT(ih);
1648 if (s->timeout == PFTM_UNLINKED) {
1650 * State is being processed
1651 * by pf_unlink_state() in
1654 PF_HASHROW_UNLOCK(ih);
1655 return (0); /* XXXGL: undefined actually */
1658 if (s->src.state == PF_TCPS_PROXY_DST) {
1659 /* XXX wire key the right one? */
1660 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1661 &s->key[PF_SK_WIRE]->addr[1],
1662 &s->key[PF_SK_WIRE]->addr[0],
1663 s->key[PF_SK_WIRE]->port[1],
1664 s->key[PF_SK_WIRE]->port[0],
1665 s->src.seqhi, s->src.seqlo + 1,
1666 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1669 LIST_REMOVE(s, entry);
1670 pf_src_tree_remove_state(s);
1672 if (pfsync_delete_state_ptr != NULL)
1673 pfsync_delete_state_ptr(s);
1675 STATE_DEC_COUNTERS(s);
1677 s->timeout = PFTM_UNLINKED;
1679 PF_HASHROW_UNLOCK(ih);
1682 /* pf_state_insert() initialises refs to 2, so we can never release the
1683 * last reference here, only in pf_release_state(). */
1684 (void)refcount_release(&s->refs);
1686 return (pf_release_state(s));
1690 pf_free_state(struct pf_state *cur)
1693 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1694 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1697 pf_normalize_tcp_cleanup(cur);
1698 uma_zfree(V_pf_state_z, cur);
1699 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1703 * Called only from pf_purge_thread(), thus serialized.
1706 pf_purge_expired_states(u_int i, int maxcheck)
1708 struct pf_idhash *ih;
1711 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1714 * Go through hash and unlink states that expire now.
1716 while (maxcheck > 0) {
1718 ih = &V_pf_idhash[i];
1720 PF_HASHROW_LOCK(ih);
1721 LIST_FOREACH(s, &ih->states, entry) {
1722 if (pf_state_expires(s) <= time_uptime) {
1723 V_pf_status.states -=
1724 pf_unlink_state(s, PF_ENTER_LOCKED);
1727 s->rule.ptr->rule_flag |= PFRULE_REFS;
1728 if (s->nat_rule.ptr != NULL)
1729 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1730 if (s->anchor.ptr != NULL)
1731 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1732 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1734 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1736 PF_HASHROW_UNLOCK(ih);
1738 /* Return when we hit end of hash. */
1739 if (++i > pf_hashmask) {
1740 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1747 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1753 pf_purge_unlinked_rules()
1755 struct pf_rulequeue tmpq;
1756 struct pf_rule *r, *r1;
1759 * If we have overloading task pending, then we'd
1760 * better skip purging this time. There is a tiny
1761 * probability that overloading task references
1762 * an already unlinked rule.
1764 PF_OVERLOADQ_LOCK();
1765 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1766 PF_OVERLOADQ_UNLOCK();
1769 PF_OVERLOADQ_UNLOCK();
1772 * Do naive mark-and-sweep garbage collecting of old rules.
1773 * Reference flag is raised by pf_purge_expired_states()
1774 * and pf_purge_expired_src_nodes().
1776 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1777 * use a temporary queue.
1780 PF_UNLNKDRULES_LOCK();
1781 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1782 if (!(r->rule_flag & PFRULE_REFS)) {
1783 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1784 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1786 r->rule_flag &= ~PFRULE_REFS;
1788 PF_UNLNKDRULES_UNLOCK();
1790 if (!TAILQ_EMPTY(&tmpq)) {
1792 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1793 TAILQ_REMOVE(&tmpq, r, entries);
1801 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1806 u_int32_t a = ntohl(addr->addr32[0]);
1807 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1819 u_int8_t i, curstart, curend, maxstart, maxend;
1820 curstart = curend = maxstart = maxend = 255;
1821 for (i = 0; i < 8; i++) {
1822 if (!addr->addr16[i]) {
1823 if (curstart == 255)
1827 if ((curend - curstart) >
1828 (maxend - maxstart)) {
1829 maxstart = curstart;
1832 curstart = curend = 255;
1835 if ((curend - curstart) >
1836 (maxend - maxstart)) {
1837 maxstart = curstart;
1840 for (i = 0; i < 8; i++) {
1841 if (i >= maxstart && i <= maxend) {
1847 b = ntohs(addr->addr16[i]);
1864 pf_print_state(struct pf_state *s)
1866 pf_print_state_parts(s, NULL, NULL);
1870 pf_print_state_parts(struct pf_state *s,
1871 struct pf_state_key *skwp, struct pf_state_key *sksp)
1873 struct pf_state_key *skw, *sks;
1874 u_int8_t proto, dir;
1876 /* Do our best to fill these, but they're skipped if NULL */
1877 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1878 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1879 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1880 dir = s ? s->direction : 0;
1898 case IPPROTO_ICMPV6:
1902 printf("%u", proto);
1915 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1917 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1922 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1924 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1929 if (proto == IPPROTO_TCP) {
1930 printf(" [lo=%u high=%u win=%u modulator=%u",
1931 s->src.seqlo, s->src.seqhi,
1932 s->src.max_win, s->src.seqdiff);
1933 if (s->src.wscale && s->dst.wscale)
1934 printf(" wscale=%u",
1935 s->src.wscale & PF_WSCALE_MASK);
1937 printf(" [lo=%u high=%u win=%u modulator=%u",
1938 s->dst.seqlo, s->dst.seqhi,
1939 s->dst.max_win, s->dst.seqdiff);
1940 if (s->src.wscale && s->dst.wscale)
1941 printf(" wscale=%u",
1942 s->dst.wscale & PF_WSCALE_MASK);
1945 printf(" %u:%u", s->src.state, s->dst.state);
1950 pf_print_flags(u_int8_t f)
1972 #define PF_SET_SKIP_STEPS(i) \
1974 while (head[i] != cur) { \
1975 head[i]->skip[i].ptr = cur; \
1976 head[i] = TAILQ_NEXT(head[i], entries); \
1981 pf_calc_skip_steps(struct pf_rulequeue *rules)
1983 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1986 cur = TAILQ_FIRST(rules);
1988 for (i = 0; i < PF_SKIP_COUNT; ++i)
1990 while (cur != NULL) {
1992 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1993 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1994 if (cur->direction != prev->direction)
1995 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1996 if (cur->af != prev->af)
1997 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1998 if (cur->proto != prev->proto)
1999 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2000 if (cur->src.neg != prev->src.neg ||
2001 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2002 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2003 if (cur->src.port[0] != prev->src.port[0] ||
2004 cur->src.port[1] != prev->src.port[1] ||
2005 cur->src.port_op != prev->src.port_op)
2006 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2007 if (cur->dst.neg != prev->dst.neg ||
2008 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2009 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2010 if (cur->dst.port[0] != prev->dst.port[0] ||
2011 cur->dst.port[1] != prev->dst.port[1] ||
2012 cur->dst.port_op != prev->dst.port_op)
2013 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2016 cur = TAILQ_NEXT(cur, entries);
2018 for (i = 0; i < PF_SKIP_COUNT; ++i)
2019 PF_SET_SKIP_STEPS(i);
2023 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2025 if (aw1->type != aw2->type)
2027 switch (aw1->type) {
2028 case PF_ADDR_ADDRMASK:
2030 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2032 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2035 case PF_ADDR_DYNIFTL:
2036 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2037 case PF_ADDR_NOROUTE:
2038 case PF_ADDR_URPFFAILED:
2041 return (aw1->p.tbl != aw2->p.tbl);
2043 printf("invalid address type: %d\n", aw1->type);
2049 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2050 * header isn't always a full checksum. In some cases (i.e. output) it's a
2051 * pseudo-header checksum, which is a partial checksum over src/dst IP
2052 * addresses, protocol number and length.
2054 * That means we have the following cases:
2055 * * Input or forwarding: we don't have TSO, the checksum fields are full
2056 * checksums, we need to update the checksum whenever we change anything.
2057 * * Output (i.e. the checksum is a pseudo-header checksum):
2058 * x The field being updated is src/dst address or affects the length of
2059 * the packet. We need to update the pseudo-header checksum (note that this
2060 * checksum is not ones' complement).
2061 * x Some other field is being modified (e.g. src/dst port numbers): We
2062 * don't have to update anything.
2065 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2071 l = cksum + old - new;
2072 l = (l >> 16) + (l & 65535);
2080 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2081 u_int16_t new, u_int8_t udp)
2083 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2086 return (pf_cksum_fixup(cksum, old, new, udp));
2090 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2091 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2097 PF_ACPY(&ao, a, af);
2100 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2108 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2109 ao.addr16[0], an->addr16[0], 0),
2110 ao.addr16[1], an->addr16[1], 0);
2113 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2114 ao.addr16[0], an->addr16[0], u),
2115 ao.addr16[1], an->addr16[1], u);
2117 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2122 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2123 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2124 pf_cksum_fixup(pf_cksum_fixup(*pc,
2125 ao.addr16[0], an->addr16[0], u),
2126 ao.addr16[1], an->addr16[1], u),
2127 ao.addr16[2], an->addr16[2], u),
2128 ao.addr16[3], an->addr16[3], u),
2129 ao.addr16[4], an->addr16[4], u),
2130 ao.addr16[5], an->addr16[5], u),
2131 ao.addr16[6], an->addr16[6], u),
2132 ao.addr16[7], an->addr16[7], u);
2134 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2139 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2140 CSUM_DELAY_DATA_IPV6)) {
2147 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2149 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2153 memcpy(&ao, a, sizeof(ao));
2154 memcpy(a, &an, sizeof(u_int32_t));
2155 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2156 ao % 65536, an % 65536, u);
2160 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2164 memcpy(&ao, a, sizeof(ao));
2165 memcpy(a, &an, sizeof(u_int32_t));
2167 *c = pf_proto_cksum_fixup(m,
2168 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2169 ao % 65536, an % 65536, udp);
2174 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2178 PF_ACPY(&ao, a, AF_INET6);
2179 PF_ACPY(a, an, AF_INET6);
2181 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2182 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2183 pf_cksum_fixup(pf_cksum_fixup(*c,
2184 ao.addr16[0], an->addr16[0], u),
2185 ao.addr16[1], an->addr16[1], u),
2186 ao.addr16[2], an->addr16[2], u),
2187 ao.addr16[3], an->addr16[3], u),
2188 ao.addr16[4], an->addr16[4], u),
2189 ao.addr16[5], an->addr16[5], u),
2190 ao.addr16[6], an->addr16[6], u),
2191 ao.addr16[7], an->addr16[7], u);
2196 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2197 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2198 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2200 struct pf_addr oia, ooa;
2202 PF_ACPY(&oia, ia, af);
2204 PF_ACPY(&ooa, oa, af);
2206 /* Change inner protocol port, fix inner protocol checksum. */
2208 u_int16_t oip = *ip;
2215 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2216 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2218 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2220 /* Change inner ip address, fix inner ip and icmp checksums. */
2221 PF_ACPY(ia, na, af);
2225 u_int32_t oh2c = *h2c;
2227 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2228 oia.addr16[0], ia->addr16[0], 0),
2229 oia.addr16[1], ia->addr16[1], 0);
2230 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2231 oia.addr16[0], ia->addr16[0], 0),
2232 oia.addr16[1], ia->addr16[1], 0);
2233 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2239 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2240 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2241 pf_cksum_fixup(pf_cksum_fixup(*ic,
2242 oia.addr16[0], ia->addr16[0], u),
2243 oia.addr16[1], ia->addr16[1], u),
2244 oia.addr16[2], ia->addr16[2], u),
2245 oia.addr16[3], ia->addr16[3], u),
2246 oia.addr16[4], ia->addr16[4], u),
2247 oia.addr16[5], ia->addr16[5], u),
2248 oia.addr16[6], ia->addr16[6], u),
2249 oia.addr16[7], ia->addr16[7], u);
2253 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2255 PF_ACPY(oa, na, af);
2259 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2260 ooa.addr16[0], oa->addr16[0], 0),
2261 ooa.addr16[1], oa->addr16[1], 0);
2266 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2267 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2268 pf_cksum_fixup(pf_cksum_fixup(*ic,
2269 ooa.addr16[0], oa->addr16[0], u),
2270 ooa.addr16[1], oa->addr16[1], u),
2271 ooa.addr16[2], oa->addr16[2], u),
2272 ooa.addr16[3], oa->addr16[3], u),
2273 ooa.addr16[4], oa->addr16[4], u),
2274 ooa.addr16[5], oa->addr16[5], u),
2275 ooa.addr16[6], oa->addr16[6], u),
2276 ooa.addr16[7], oa->addr16[7], u);
2285 * Need to modulate the sequence numbers in the TCP SACK option
2286 * (credits to Krzysztof Pfaff for report and patch)
2289 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2290 struct tcphdr *th, struct pf_state_peer *dst)
2292 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2293 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2294 int copyback = 0, i, olen;
2295 struct sackblk sack;
2297 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2298 if (hlen < TCPOLEN_SACKLEN ||
2299 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2302 while (hlen >= TCPOLEN_SACKLEN) {
2305 case TCPOPT_EOL: /* FALLTHROUGH */
2313 if (olen >= TCPOLEN_SACKLEN) {
2314 for (i = 2; i + TCPOLEN_SACK <= olen;
2315 i += TCPOLEN_SACK) {
2316 memcpy(&sack, &opt[i], sizeof(sack));
2317 pf_change_proto_a(m, &sack.start, &th->th_sum,
2318 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2319 pf_change_proto_a(m, &sack.end, &th->th_sum,
2320 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2321 memcpy(&opt[i], &sack, sizeof(sack));
2335 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2340 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2341 const struct pf_addr *saddr, const struct pf_addr *daddr,
2342 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2343 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2344 u_int16_t rtag, struct ifnet *ifp)
2346 struct pf_send_entry *pfse;
2350 struct ip *h = NULL;
2353 struct ip6_hdr *h6 = NULL;
2357 struct pf_mtag *pf_mtag;
2362 /* maximum segment size tcp option */
2363 tlen = sizeof(struct tcphdr);
2370 len = sizeof(struct ip) + tlen;
2375 len = sizeof(struct ip6_hdr) + tlen;
2379 panic("%s: unsupported af %d", __func__, af);
2382 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2383 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2386 m = m_gethdr(M_NOWAIT, MT_DATA);
2388 free(pfse, M_PFTEMP);
2392 mac_netinet_firewall_send(m);
2394 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2395 free(pfse, M_PFTEMP);
2400 m->m_flags |= M_SKIP_FIREWALL;
2401 pf_mtag->tag = rtag;
2403 if (r != NULL && r->rtableid >= 0)
2404 M_SETFIB(m, r->rtableid);
2407 if (r != NULL && r->qid) {
2408 pf_mtag->qid = r->qid;
2410 /* add hints for ecn */
2411 pf_mtag->hdr = mtod(m, struct ip *);
2414 m->m_data += max_linkhdr;
2415 m->m_pkthdr.len = m->m_len = len;
2416 m->m_pkthdr.rcvif = NULL;
2417 bzero(m->m_data, len);
2421 h = mtod(m, struct ip *);
2423 /* IP header fields included in the TCP checksum */
2424 h->ip_p = IPPROTO_TCP;
2425 h->ip_len = htons(tlen);
2426 h->ip_src.s_addr = saddr->v4.s_addr;
2427 h->ip_dst.s_addr = daddr->v4.s_addr;
2429 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2434 h6 = mtod(m, struct ip6_hdr *);
2436 /* IP header fields included in the TCP checksum */
2437 h6->ip6_nxt = IPPROTO_TCP;
2438 h6->ip6_plen = htons(tlen);
2439 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2440 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2442 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2448 th->th_sport = sport;
2449 th->th_dport = dport;
2450 th->th_seq = htonl(seq);
2451 th->th_ack = htonl(ack);
2452 th->th_off = tlen >> 2;
2453 th->th_flags = flags;
2454 th->th_win = htons(win);
2457 opt = (char *)(th + 1);
2458 opt[0] = TCPOPT_MAXSEG;
2461 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2468 th->th_sum = in_cksum(m, len);
2470 /* Finish the IP header */
2472 h->ip_hl = sizeof(*h) >> 2;
2473 h->ip_tos = IPTOS_LOWDELAY;
2474 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2475 h->ip_len = htons(len);
2476 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2479 pfse->pfse_type = PFSE_IP;
2485 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2486 sizeof(struct ip6_hdr), tlen);
2488 h6->ip6_vfc |= IPV6_VERSION;
2489 h6->ip6_hlim = IPV6_DEFHLIM;
2491 pfse->pfse_type = PFSE_IP6;
2500 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2504 KASSERT(prio <= PF_PRIO_MAX,
2505 ("%s with invalid pcp", __func__));
2507 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2509 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2510 sizeof(uint8_t), M_NOWAIT);
2513 m_tag_prepend(m, mtag);
2516 *(uint8_t *)(mtag + 1) = prio;
2521 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2526 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2530 if (prio == PF_PRIO_ZERO)
2533 mpcp = *(uint8_t *)(mtag + 1);
2535 return (mpcp == prio);
2539 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2542 struct pf_send_entry *pfse;
2544 struct pf_mtag *pf_mtag;
2546 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2547 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2551 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2552 free(pfse, M_PFTEMP);
2556 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2557 free(pfse, M_PFTEMP);
2561 m0->m_flags |= M_SKIP_FIREWALL;
2563 if (r->rtableid >= 0)
2564 M_SETFIB(m0, r->rtableid);
2568 pf_mtag->qid = r->qid;
2569 /* add hints for ecn */
2570 pf_mtag->hdr = mtod(m0, struct ip *);
2577 pfse->pfse_type = PFSE_ICMP;
2582 pfse->pfse_type = PFSE_ICMP6;
2587 pfse->icmpopts.type = type;
2588 pfse->icmpopts.code = code;
2593 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2594 * If n is 0, they match if they are equal. If n is != 0, they match if they
2598 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2599 struct pf_addr *b, sa_family_t af)
2606 if ((a->addr32[0] & m->addr32[0]) ==
2607 (b->addr32[0] & m->addr32[0]))
2613 if (((a->addr32[0] & m->addr32[0]) ==
2614 (b->addr32[0] & m->addr32[0])) &&
2615 ((a->addr32[1] & m->addr32[1]) ==
2616 (b->addr32[1] & m->addr32[1])) &&
2617 ((a->addr32[2] & m->addr32[2]) ==
2618 (b->addr32[2] & m->addr32[2])) &&
2619 ((a->addr32[3] & m->addr32[3]) ==
2620 (b->addr32[3] & m->addr32[3])))
2639 * Return 1 if b <= a <= e, otherwise return 0.
2642 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2643 struct pf_addr *a, sa_family_t af)
2648 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2649 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2658 for (i = 0; i < 4; ++i)
2659 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2661 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2664 for (i = 0; i < 4; ++i)
2665 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2667 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2677 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2681 return ((p > a1) && (p < a2));
2683 return ((p < a1) || (p > a2));
2685 return ((p >= a1) && (p <= a2));
2699 return (0); /* never reached */
2703 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2708 return (pf_match(op, a1, a2, p));
2712 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2714 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2716 return (pf_match(op, a1, a2, u));
2720 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2722 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2724 return (pf_match(op, a1, a2, g));
2728 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2733 return ((!r->match_tag_not && r->match_tag == *tag) ||
2734 (r->match_tag_not && r->match_tag != *tag));
2738 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2741 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2743 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2746 pd->pf_mtag->tag = tag;
2751 #define PF_ANCHOR_STACKSIZE 32
2752 struct pf_anchor_stackframe {
2753 struct pf_ruleset *rs;
2754 struct pf_rule *r; /* XXX: + match bit */
2755 struct pf_anchor *child;
2759 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2761 #define PF_ANCHORSTACK_MATCH 0x00000001
2762 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2764 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2765 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2766 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2767 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2768 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2772 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2773 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2776 struct pf_anchor_stackframe *f;
2782 if (*depth >= PF_ANCHOR_STACKSIZE) {
2783 printf("%s: anchor stack overflow on %s\n",
2784 __func__, (*r)->anchor->name);
2785 *r = TAILQ_NEXT(*r, entries);
2787 } else if (*depth == 0 && a != NULL)
2789 f = stack + (*depth)++;
2792 if ((*r)->anchor_wildcard) {
2793 struct pf_anchor_node *parent = &(*r)->anchor->children;
2795 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2799 *rs = &f->child->ruleset;
2802 *rs = &(*r)->anchor->ruleset;
2804 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2808 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2809 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2812 struct pf_anchor_stackframe *f;
2821 f = stack + *depth - 1;
2822 fr = PF_ANCHOR_RULE(f);
2823 if (f->child != NULL) {
2824 struct pf_anchor_node *parent;
2827 * This block traverses through
2828 * a wildcard anchor.
2830 parent = &fr->anchor->children;
2831 if (match != NULL && *match) {
2833 * If any of "*" matched, then
2834 * "foo/ *" matched, mark frame
2837 PF_ANCHOR_SET_MATCH(f);
2840 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2841 if (f->child != NULL) {
2842 *rs = &f->child->ruleset;
2843 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2851 if (*depth == 0 && a != NULL)
2854 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2856 *r = TAILQ_NEXT(fr, entries);
2857 } while (*r == NULL);
2864 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2865 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2870 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2871 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2875 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2876 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2877 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2878 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2879 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2880 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2881 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2882 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2888 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2893 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2897 if (addr->addr32[3] == 0xffffffff) {
2898 addr->addr32[3] = 0;
2899 if (addr->addr32[2] == 0xffffffff) {
2900 addr->addr32[2] = 0;
2901 if (addr->addr32[1] == 0xffffffff) {
2902 addr->addr32[1] = 0;
2904 htonl(ntohl(addr->addr32[0]) + 1);
2907 htonl(ntohl(addr->addr32[1]) + 1);
2910 htonl(ntohl(addr->addr32[2]) + 1);
2913 htonl(ntohl(addr->addr32[3]) + 1);
2920 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2922 struct pf_addr *saddr, *daddr;
2923 u_int16_t sport, dport;
2924 struct inpcbinfo *pi;
2927 pd->lookup.uid = UID_MAX;
2928 pd->lookup.gid = GID_MAX;
2930 switch (pd->proto) {
2932 if (pd->hdr.tcp == NULL)
2934 sport = pd->hdr.tcp->th_sport;
2935 dport = pd->hdr.tcp->th_dport;
2939 if (pd->hdr.udp == NULL)
2941 sport = pd->hdr.udp->uh_sport;
2942 dport = pd->hdr.udp->uh_dport;
2948 if (direction == PF_IN) {
2963 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2964 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2966 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2967 daddr->v4, dport, INPLOOKUP_WILDCARD |
2968 INPLOOKUP_RLOCKPCB, NULL, m);
2976 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2977 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2979 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2980 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2981 INPLOOKUP_RLOCKPCB, NULL, m);
2991 INP_RLOCK_ASSERT(inp);
2992 pd->lookup.uid = inp->inp_cred->cr_uid;
2993 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3000 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3004 u_int8_t *opt, optlen;
3005 u_int8_t wscale = 0;
3007 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3008 if (hlen <= sizeof(struct tcphdr))
3010 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3012 opt = hdr + sizeof(struct tcphdr);
3013 hlen -= sizeof(struct tcphdr);
3023 if (wscale > TCP_MAX_WINSHIFT)
3024 wscale = TCP_MAX_WINSHIFT;
3025 wscale |= PF_WSCALE_FLAG;
3040 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3044 u_int8_t *opt, optlen;
3045 u_int16_t mss = V_tcp_mssdflt;
3047 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3048 if (hlen <= sizeof(struct tcphdr))
3050 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3052 opt = hdr + sizeof(struct tcphdr);
3053 hlen -= sizeof(struct tcphdr);
3054 while (hlen >= TCPOLEN_MAXSEG) {
3062 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3078 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3081 struct nhop4_basic nh4;
3084 struct nhop6_basic nh6;
3085 struct in6_addr dst6;
3094 hlen = sizeof(struct ip);
3095 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3096 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3101 hlen = sizeof(struct ip6_hdr);
3102 in6_splitscope(&addr->v6, &dst6, &scopeid);
3103 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3104 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3109 mss = max(V_tcp_mssdflt, mss);
3110 mss = min(mss, offer);
3111 mss = max(mss, 64); /* sanity - at least max opt space */
3116 pf_tcp_iss(struct pf_pdesc *pd)
3119 u_int32_t digest[4];
3121 if (V_pf_tcp_secret_init == 0) {
3122 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3123 MD5Init(&V_pf_tcp_secret_ctx);
3124 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3125 sizeof(V_pf_tcp_secret));
3126 V_pf_tcp_secret_init = 1;
3129 ctx = V_pf_tcp_secret_ctx;
3131 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3132 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3133 if (pd->af == AF_INET6) {
3134 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3135 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3137 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3138 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3140 MD5Final((u_char *)digest, &ctx);
3141 V_pf_tcp_iss_off += 4096;
3142 #define ISN_RANDOM_INCREMENT (4096 - 1)
3143 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3145 #undef ISN_RANDOM_INCREMENT
3149 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3150 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3151 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3153 struct pf_rule *nr = NULL;
3154 struct pf_addr * const saddr = pd->src;
3155 struct pf_addr * const daddr = pd->dst;
3156 sa_family_t af = pd->af;
3157 struct pf_rule *r, *a = NULL;
3158 struct pf_ruleset *ruleset = NULL;
3159 struct pf_src_node *nsn = NULL;
3160 struct tcphdr *th = pd->hdr.tcp;
3161 struct pf_state_key *sk = NULL, *nk = NULL;
3163 int rewrite = 0, hdrlen = 0;
3164 int tag = -1, rtableid = -1;
3168 u_int16_t sport = 0, dport = 0;
3169 u_int16_t bproto_sum = 0, bip_sum = 0;
3170 u_int8_t icmptype = 0, icmpcode = 0;
3171 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3176 INP_LOCK_ASSERT(inp);
3177 pd->lookup.uid = inp->inp_cred->cr_uid;
3178 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3179 pd->lookup.done = 1;
3182 switch (pd->proto) {
3184 sport = th->th_sport;
3185 dport = th->th_dport;
3186 hdrlen = sizeof(*th);
3189 sport = pd->hdr.udp->uh_sport;
3190 dport = pd->hdr.udp->uh_dport;
3191 hdrlen = sizeof(*pd->hdr.udp);
3195 if (pd->af != AF_INET)
3197 sport = dport = pd->hdr.icmp->icmp_id;
3198 hdrlen = sizeof(*pd->hdr.icmp);
3199 icmptype = pd->hdr.icmp->icmp_type;
3200 icmpcode = pd->hdr.icmp->icmp_code;
3202 if (icmptype == ICMP_UNREACH ||
3203 icmptype == ICMP_SOURCEQUENCH ||
3204 icmptype == ICMP_REDIRECT ||
3205 icmptype == ICMP_TIMXCEED ||
3206 icmptype == ICMP_PARAMPROB)
3211 case IPPROTO_ICMPV6:
3214 sport = dport = pd->hdr.icmp6->icmp6_id;
3215 hdrlen = sizeof(*pd->hdr.icmp6);
3216 icmptype = pd->hdr.icmp6->icmp6_type;
3217 icmpcode = pd->hdr.icmp6->icmp6_code;
3219 if (icmptype == ICMP6_DST_UNREACH ||
3220 icmptype == ICMP6_PACKET_TOO_BIG ||
3221 icmptype == ICMP6_TIME_EXCEEDED ||
3222 icmptype == ICMP6_PARAM_PROB)
3227 sport = dport = hdrlen = 0;
3231 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3233 /* check packet for BINAT/NAT/RDR */
3234 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3235 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3236 KASSERT(sk != NULL, ("%s: null sk", __func__));
3237 KASSERT(nk != NULL, ("%s: null nk", __func__));
3240 bip_sum = *pd->ip_sum;
3242 switch (pd->proto) {
3244 bproto_sum = th->th_sum;
3245 pd->proto_sum = &th->th_sum;
3247 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3248 nk->port[pd->sidx] != sport) {
3249 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3250 &th->th_sum, &nk->addr[pd->sidx],
3251 nk->port[pd->sidx], 0, af);
3252 pd->sport = &th->th_sport;
3253 sport = th->th_sport;
3256 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3257 nk->port[pd->didx] != dport) {
3258 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3259 &th->th_sum, &nk->addr[pd->didx],
3260 nk->port[pd->didx], 0, af);
3261 dport = th->th_dport;
3262 pd->dport = &th->th_dport;
3267 bproto_sum = pd->hdr.udp->uh_sum;
3268 pd->proto_sum = &pd->hdr.udp->uh_sum;
3270 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3271 nk->port[pd->sidx] != sport) {
3272 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3273 pd->ip_sum, &pd->hdr.udp->uh_sum,
3274 &nk->addr[pd->sidx],
3275 nk->port[pd->sidx], 1, af);
3276 sport = pd->hdr.udp->uh_sport;
3277 pd->sport = &pd->hdr.udp->uh_sport;
3280 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3281 nk->port[pd->didx] != dport) {
3282 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3283 pd->ip_sum, &pd->hdr.udp->uh_sum,
3284 &nk->addr[pd->didx],
3285 nk->port[pd->didx], 1, af);
3286 dport = pd->hdr.udp->uh_dport;
3287 pd->dport = &pd->hdr.udp->uh_dport;
3293 nk->port[0] = nk->port[1];
3294 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3295 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3296 nk->addr[pd->sidx].v4.s_addr, 0);
3298 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3299 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3300 nk->addr[pd->didx].v4.s_addr, 0);
3302 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3303 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3304 pd->hdr.icmp->icmp_cksum, sport,
3306 pd->hdr.icmp->icmp_id = nk->port[1];
3307 pd->sport = &pd->hdr.icmp->icmp_id;
3309 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3313 case IPPROTO_ICMPV6:
3314 nk->port[0] = nk->port[1];
3315 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3316 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3317 &nk->addr[pd->sidx], 0);
3319 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3320 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3321 &nk->addr[pd->didx], 0);
3330 &nk->addr[pd->sidx], AF_INET))
3331 pf_change_a(&saddr->v4.s_addr,
3333 nk->addr[pd->sidx].v4.s_addr, 0);
3336 &nk->addr[pd->didx], AF_INET))
3337 pf_change_a(&daddr->v4.s_addr,
3339 nk->addr[pd->didx].v4.s_addr, 0);
3345 &nk->addr[pd->sidx], AF_INET6))
3346 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3349 &nk->addr[pd->didx], AF_INET6))
3350 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3363 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3364 r = r->skip[PF_SKIP_IFP].ptr;
3365 else if (r->direction && r->direction != direction)
3366 r = r->skip[PF_SKIP_DIR].ptr;
3367 else if (r->af && r->af != af)
3368 r = r->skip[PF_SKIP_AF].ptr;
3369 else if (r->proto && r->proto != pd->proto)
3370 r = r->skip[PF_SKIP_PROTO].ptr;
3371 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3372 r->src.neg, kif, M_GETFIB(m)))
3373 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3374 /* tcp/udp only. port_op always 0 in other cases */
3375 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3376 r->src.port[0], r->src.port[1], sport))
3377 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3378 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3379 r->dst.neg, NULL, M_GETFIB(m)))
3380 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3381 /* tcp/udp only. port_op always 0 in other cases */
3382 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3383 r->dst.port[0], r->dst.port[1], dport))
3384 r = r->skip[PF_SKIP_DST_PORT].ptr;
3385 /* icmp only. type always 0 in other cases */
3386 else if (r->type && r->type != icmptype + 1)
3387 r = TAILQ_NEXT(r, entries);
3388 /* icmp only. type always 0 in other cases */
3389 else if (r->code && r->code != icmpcode + 1)
3390 r = TAILQ_NEXT(r, entries);
3391 else if (r->tos && !(r->tos == pd->tos))
3392 r = TAILQ_NEXT(r, entries);
3393 else if (r->rule_flag & PFRULE_FRAGMENT)
3394 r = TAILQ_NEXT(r, entries);
3395 else if (pd->proto == IPPROTO_TCP &&
3396 (r->flagset & th->th_flags) != r->flags)
3397 r = TAILQ_NEXT(r, entries);
3398 /* tcp/udp only. uid.op always 0 in other cases */
3399 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3400 pf_socket_lookup(direction, pd, m), 1)) &&
3401 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3403 r = TAILQ_NEXT(r, entries);
3404 /* tcp/udp only. gid.op always 0 in other cases */
3405 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3406 pf_socket_lookup(direction, pd, m), 1)) &&
3407 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3409 r = TAILQ_NEXT(r, entries);
3411 !pf_match_ieee8021q_pcp(r->prio, m))
3412 r = TAILQ_NEXT(r, entries);
3414 r->prob <= arc4random())
3415 r = TAILQ_NEXT(r, entries);
3416 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3417 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3418 r = TAILQ_NEXT(r, entries);
3419 else if (r->os_fingerprint != PF_OSFP_ANY &&
3420 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3421 pf_osfp_fingerprint(pd, m, off, th),
3422 r->os_fingerprint)))
3423 r = TAILQ_NEXT(r, entries);
3427 if (r->rtableid >= 0)
3428 rtableid = r->rtableid;
3429 if (r->anchor == NULL) {
3436 r = TAILQ_NEXT(r, entries);
3438 pf_step_into_anchor(anchor_stack, &asd,
3439 &ruleset, PF_RULESET_FILTER, &r, &a,
3442 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3443 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3450 REASON_SET(&reason, PFRES_MATCH);
3452 if (r->log || (nr != NULL && nr->log)) {
3454 m_copyback(m, off, hdrlen, pd->hdr.any);
3455 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3459 if ((r->action == PF_DROP) &&
3460 ((r->rule_flag & PFRULE_RETURNRST) ||
3461 (r->rule_flag & PFRULE_RETURNICMP) ||
3462 (r->rule_flag & PFRULE_RETURN))) {
3463 /* undo NAT changes, if they have taken place */
3465 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3466 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3468 *pd->sport = sk->port[pd->sidx];
3470 *pd->dport = sk->port[pd->didx];
3472 *pd->proto_sum = bproto_sum;
3474 *pd->ip_sum = bip_sum;
3475 m_copyback(m, off, hdrlen, pd->hdr.any);
3477 if (pd->proto == IPPROTO_TCP &&
3478 ((r->rule_flag & PFRULE_RETURNRST) ||
3479 (r->rule_flag & PFRULE_RETURN)) &&
3480 !(th->th_flags & TH_RST)) {
3481 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3493 h4 = mtod(m, struct ip *);
3494 len = ntohs(h4->ip_len) - off;
3499 h6 = mtod(m, struct ip6_hdr *);
3500 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3505 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3506 REASON_SET(&reason, PFRES_PROTCKSUM);
3508 if (th->th_flags & TH_SYN)
3510 if (th->th_flags & TH_FIN)
3512 pf_send_tcp(m, r, af, pd->dst,
3513 pd->src, th->th_dport, th->th_sport,
3514 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3515 r->return_ttl, 1, 0, kif->pfik_ifp);
3517 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3519 pf_send_icmp(m, r->return_icmp >> 8,
3520 r->return_icmp & 255, af, r);
3521 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3523 pf_send_icmp(m, r->return_icmp6 >> 8,
3524 r->return_icmp6 & 255, af, r);
3527 if (r->action == PF_DROP)
3530 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3531 REASON_SET(&reason, PFRES_MEMORY);
3535 M_SETFIB(m, rtableid);
3537 if (!state_icmp && (r->keep_state || nr != NULL ||
3538 (pd->flags & PFDESC_TCP_NORM))) {
3540 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3541 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3543 if (action != PF_PASS)
3547 uma_zfree(V_pf_state_key_z, sk);
3549 uma_zfree(V_pf_state_key_z, nk);
3552 /* copy back packet headers if we performed NAT operations */
3554 m_copyback(m, off, hdrlen, pd->hdr.any);
3556 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3557 direction == PF_OUT &&
3558 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3560 * We want the state created, but we dont
3561 * want to send this in case a partner
3562 * firewall has to know about it to allow
3563 * replies through it.
3571 uma_zfree(V_pf_state_key_z, sk);
3573 uma_zfree(V_pf_state_key_z, nk);
3578 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3579 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3580 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3581 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3582 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3584 struct pf_state *s = NULL;
3585 struct pf_src_node *sn = NULL;
3586 struct tcphdr *th = pd->hdr.tcp;
3587 u_int16_t mss = V_tcp_mssdflt;
3590 /* check maximums */
3591 if (r->max_states &&
3592 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3593 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3594 REASON_SET(&reason, PFRES_MAXSTATES);
3597 /* src node for filter rule */
3598 if ((r->rule_flag & PFRULE_SRCTRACK ||
3599 r->rpool.opts & PF_POOL_STICKYADDR) &&
3600 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3601 REASON_SET(&reason, PFRES_SRCLIMIT);
3604 /* src node for translation rule */
3605 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3606 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3607 REASON_SET(&reason, PFRES_SRCLIMIT);
3610 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3612 REASON_SET(&reason, PFRES_MEMORY);
3616 s->nat_rule.ptr = nr;
3618 STATE_INC_COUNTERS(s);
3620 s->state_flags |= PFSTATE_ALLOWOPTS;
3621 if (r->rule_flag & PFRULE_STATESLOPPY)
3622 s->state_flags |= PFSTATE_SLOPPY;
3623 s->log = r->log & PF_LOG_ALL;
3624 s->sync_state = PFSYNC_S_NONE;
3626 s->log |= nr->log & PF_LOG_ALL;
3627 switch (pd->proto) {
3629 s->src.seqlo = ntohl(th->th_seq);
3630 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3631 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3632 r->keep_state == PF_STATE_MODULATE) {
3633 /* Generate sequence number modulator */
3634 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3637 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3638 htonl(s->src.seqlo + s->src.seqdiff), 0);
3642 if (th->th_flags & TH_SYN) {
3644 s->src.wscale = pf_get_wscale(m, off,
3645 th->th_off, pd->af);
3647 s->src.max_win = MAX(ntohs(th->th_win), 1);
3648 if (s->src.wscale & PF_WSCALE_MASK) {
3649 /* Remove scale factor from initial window */
3650 int win = s->src.max_win;
3651 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3652 s->src.max_win = (win - 1) >>
3653 (s->src.wscale & PF_WSCALE_MASK);
3655 if (th->th_flags & TH_FIN)
3659 s->src.state = TCPS_SYN_SENT;
3660 s->dst.state = TCPS_CLOSED;
3661 s->timeout = PFTM_TCP_FIRST_PACKET;
3664 s->src.state = PFUDPS_SINGLE;
3665 s->dst.state = PFUDPS_NO_TRAFFIC;
3666 s->timeout = PFTM_UDP_FIRST_PACKET;
3670 case IPPROTO_ICMPV6:
3672 s->timeout = PFTM_ICMP_FIRST_PACKET;
3675 s->src.state = PFOTHERS_SINGLE;
3676 s->dst.state = PFOTHERS_NO_TRAFFIC;
3677 s->timeout = PFTM_OTHER_FIRST_PACKET;
3681 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3682 REASON_SET(&reason, PFRES_MAPFAILED);
3683 pf_src_tree_remove_state(s);
3684 STATE_DEC_COUNTERS(s);
3685 uma_zfree(V_pf_state_z, s);
3688 s->rt_kif = r->rpool.cur->kif;
3691 s->creation = time_uptime;
3692 s->expire = time_uptime;
3697 /* XXX We only modify one side for now. */
3698 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3699 s->nat_src_node = nsn;
3701 if (pd->proto == IPPROTO_TCP) {
3702 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3703 off, pd, th, &s->src, &s->dst)) {
3704 REASON_SET(&reason, PFRES_MEMORY);
3705 pf_src_tree_remove_state(s);
3706 STATE_DEC_COUNTERS(s);
3707 uma_zfree(V_pf_state_z, s);
3710 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3711 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3712 &s->src, &s->dst, rewrite)) {
3713 /* This really shouldn't happen!!! */
3714 DPFPRINTF(PF_DEBUG_URGENT,
3715 ("pf_normalize_tcp_stateful failed on first pkt"));
3716 pf_normalize_tcp_cleanup(s);
3717 pf_src_tree_remove_state(s);
3718 STATE_DEC_COUNTERS(s);
3719 uma_zfree(V_pf_state_z, s);
3723 s->direction = pd->dir;
3726 * sk/nk could already been setup by pf_get_translation().
3729 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3730 __func__, nr, sk, nk));
3731 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3736 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3737 __func__, nr, sk, nk));
3739 /* Swap sk/nk for PF_OUT. */
3740 if (pf_state_insert(BOUND_IFACE(r, kif),
3741 (pd->dir == PF_IN) ? sk : nk,
3742 (pd->dir == PF_IN) ? nk : sk, s)) {
3743 if (pd->proto == IPPROTO_TCP)
3744 pf_normalize_tcp_cleanup(s);
3745 REASON_SET(&reason, PFRES_STATEINS);
3746 pf_src_tree_remove_state(s);
3747 STATE_DEC_COUNTERS(s);
3748 uma_zfree(V_pf_state_z, s);
3755 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3756 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3757 s->src.state = PF_TCPS_PROXY_SRC;
3758 /* undo NAT changes, if they have taken place */
3760 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3761 if (pd->dir == PF_OUT)
3762 skt = s->key[PF_SK_STACK];
3763 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3764 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3766 *pd->sport = skt->port[pd->sidx];
3768 *pd->dport = skt->port[pd->didx];
3770 *pd->proto_sum = bproto_sum;
3772 *pd->ip_sum = bip_sum;
3773 m_copyback(m, off, hdrlen, pd->hdr.any);
3775 s->src.seqhi = htonl(arc4random());
3776 /* Find mss option */
3777 int rtid = M_GETFIB(m);
3778 mss = pf_get_mss(m, off, th->th_off, pd->af);
3779 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3780 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3782 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3783 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3784 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3785 REASON_SET(&reason, PFRES_SYNPROXY);
3786 return (PF_SYNPROXY_DROP);
3793 uma_zfree(V_pf_state_key_z, sk);
3795 uma_zfree(V_pf_state_key_z, nk);
3798 struct pf_srchash *sh;
3800 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3801 PF_HASHROW_LOCK(sh);
3802 if (--sn->states == 0 && sn->expire == 0) {
3803 pf_unlink_src_node(sn);
3804 uma_zfree(V_pf_sources_z, sn);
3806 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3808 PF_HASHROW_UNLOCK(sh);
3811 if (nsn != sn && nsn != NULL) {
3812 struct pf_srchash *sh;
3814 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3815 PF_HASHROW_LOCK(sh);
3816 if (--nsn->states == 0 && nsn->expire == 0) {
3817 pf_unlink_src_node(nsn);
3818 uma_zfree(V_pf_sources_z, nsn);
3820 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3822 PF_HASHROW_UNLOCK(sh);
3829 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3830 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3831 struct pf_ruleset **rsm)
3833 struct pf_rule *r, *a = NULL;
3834 struct pf_ruleset *ruleset = NULL;
3835 sa_family_t af = pd->af;
3840 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3844 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3847 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3848 r = r->skip[PF_SKIP_IFP].ptr;
3849 else if (r->direction && r->direction != direction)
3850 r = r->skip[PF_SKIP_DIR].ptr;
3851 else if (r->af && r->af != af)
3852 r = r->skip[PF_SKIP_AF].ptr;
3853 else if (r->proto && r->proto != pd->proto)
3854 r = r->skip[PF_SKIP_PROTO].ptr;
3855 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3856 r->src.neg, kif, M_GETFIB(m)))
3857 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3858 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3859 r->dst.neg, NULL, M_GETFIB(m)))
3860 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3861 else if (r->tos && !(r->tos == pd->tos))
3862 r = TAILQ_NEXT(r, entries);
3863 else if (r->os_fingerprint != PF_OSFP_ANY)
3864 r = TAILQ_NEXT(r, entries);
3865 else if (pd->proto == IPPROTO_UDP &&
3866 (r->src.port_op || r->dst.port_op))
3867 r = TAILQ_NEXT(r, entries);
3868 else if (pd->proto == IPPROTO_TCP &&
3869 (r->src.port_op || r->dst.port_op || r->flagset))
3870 r = TAILQ_NEXT(r, entries);
3871 else if ((pd->proto == IPPROTO_ICMP ||
3872 pd->proto == IPPROTO_ICMPV6) &&
3873 (r->type || r->code))
3874 r = TAILQ_NEXT(r, entries);
3876 !pf_match_ieee8021q_pcp(r->prio, m))
3877 r = TAILQ_NEXT(r, entries);
3878 else if (r->prob && r->prob <=
3879 (arc4random() % (UINT_MAX - 1) + 1))
3880 r = TAILQ_NEXT(r, entries);
3881 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3882 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3883 r = TAILQ_NEXT(r, entries);
3885 if (r->anchor == NULL) {
3892 r = TAILQ_NEXT(r, entries);
3894 pf_step_into_anchor(anchor_stack, &asd,
3895 &ruleset, PF_RULESET_FILTER, &r, &a,
3898 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3899 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3906 REASON_SET(&reason, PFRES_MATCH);
3909 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3912 if (r->action != PF_PASS)
3915 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3916 REASON_SET(&reason, PFRES_MEMORY);
3924 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3925 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3926 struct pf_pdesc *pd, u_short *reason, int *copyback)
3928 struct tcphdr *th = pd->hdr.tcp;
3929 u_int16_t win = ntohs(th->th_win);
3930 u_int32_t ack, end, seq, orig_seq;
3934 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3935 sws = src->wscale & PF_WSCALE_MASK;
3936 dws = dst->wscale & PF_WSCALE_MASK;
3941 * Sequence tracking algorithm from Guido van Rooij's paper:
3942 * http://www.madison-gurkha.com/publications/tcp_filtering/
3946 orig_seq = seq = ntohl(th->th_seq);
3947 if (src->seqlo == 0) {
3948 /* First packet from this end. Set its state */
3950 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3951 src->scrub == NULL) {
3952 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3953 REASON_SET(reason, PFRES_MEMORY);
3958 /* Deferred generation of sequence number modulator */
3959 if (dst->seqdiff && !src->seqdiff) {
3960 /* use random iss for the TCP server */
3961 while ((src->seqdiff = arc4random() - seq) == 0)
3963 ack = ntohl(th->th_ack) - dst->seqdiff;
3964 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3966 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3969 ack = ntohl(th->th_ack);
3972 end = seq + pd->p_len;
3973 if (th->th_flags & TH_SYN) {
3975 if (dst->wscale & PF_WSCALE_FLAG) {
3976 src->wscale = pf_get_wscale(m, off, th->th_off,
3978 if (src->wscale & PF_WSCALE_FLAG) {
3979 /* Remove scale factor from initial
3981 sws = src->wscale & PF_WSCALE_MASK;
3982 win = ((u_int32_t)win + (1 << sws) - 1)
3984 dws = dst->wscale & PF_WSCALE_MASK;
3986 /* fixup other window */
3987 dst->max_win <<= dst->wscale &
3989 /* in case of a retrans SYN|ACK */
3994 if (th->th_flags & TH_FIN)
3998 if (src->state < TCPS_SYN_SENT)
3999 src->state = TCPS_SYN_SENT;
4002 * May need to slide the window (seqhi may have been set by
4003 * the crappy stack check or if we picked up the connection
4004 * after establishment)
4006 if (src->seqhi == 1 ||
4007 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4008 src->seqhi = end + MAX(1, dst->max_win << dws);
4009 if (win > src->max_win)
4013 ack = ntohl(th->th_ack) - dst->seqdiff;
4015 /* Modulate sequence numbers */
4016 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4018 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4021 end = seq + pd->p_len;
4022 if (th->th_flags & TH_SYN)
4024 if (th->th_flags & TH_FIN)
4028 if ((th->th_flags & TH_ACK) == 0) {
4029 /* Let it pass through the ack skew check */
4031 } else if ((ack == 0 &&
4032 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4033 /* broken tcp stacks do not set ack */
4034 (dst->state < TCPS_SYN_SENT)) {
4036 * Many stacks (ours included) will set the ACK number in an
4037 * FIN|ACK if the SYN times out -- no sequence to ACK.
4043 /* Ease sequencing restrictions on no data packets */
4048 ackskew = dst->seqlo - ack;
4052 * Need to demodulate the sequence numbers in any TCP SACK options
4053 * (Selective ACK). We could optionally validate the SACK values
4054 * against the current ACK window, either forwards or backwards, but
4055 * I'm not confident that SACK has been implemented properly
4056 * everywhere. It wouldn't surprise me if several stacks accidentally
4057 * SACK too far backwards of previously ACKed data. There really aren't
4058 * any security implications of bad SACKing unless the target stack
4059 * doesn't validate the option length correctly. Someone trying to
4060 * spoof into a TCP connection won't bother blindly sending SACK
4063 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4064 if (pf_modulate_sack(m, off, pd, th, dst))
4069 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4070 if (SEQ_GEQ(src->seqhi, end) &&
4071 /* Last octet inside other's window space */
4072 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4073 /* Retrans: not more than one window back */
4074 (ackskew >= -MAXACKWINDOW) &&
4075 /* Acking not more than one reassembled fragment backwards */
4076 (ackskew <= (MAXACKWINDOW << sws)) &&
4077 /* Acking not more than one window forward */
4078 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4079 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4080 (pd->flags & PFDESC_IP_REAS) == 0)) {
4081 /* Require an exact/+1 sequence match on resets when possible */
4083 if (dst->scrub || src->scrub) {
4084 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4085 *state, src, dst, copyback))
4089 /* update max window */
4090 if (src->max_win < win)
4092 /* synchronize sequencing */
4093 if (SEQ_GT(end, src->seqlo))
4095 /* slide the window of what the other end can send */
4096 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4097 dst->seqhi = ack + MAX((win << sws), 1);
4101 if (th->th_flags & TH_SYN)
4102 if (src->state < TCPS_SYN_SENT)
4103 src->state = TCPS_SYN_SENT;
4104 if (th->th_flags & TH_FIN)
4105 if (src->state < TCPS_CLOSING)
4106 src->state = TCPS_CLOSING;
4107 if (th->th_flags & TH_ACK) {
4108 if (dst->state == TCPS_SYN_SENT) {
4109 dst->state = TCPS_ESTABLISHED;
4110 if (src->state == TCPS_ESTABLISHED &&
4111 (*state)->src_node != NULL &&
4112 pf_src_connlimit(state)) {
4113 REASON_SET(reason, PFRES_SRCLIMIT);
4116 } else if (dst->state == TCPS_CLOSING)
4117 dst->state = TCPS_FIN_WAIT_2;
4119 if (th->th_flags & TH_RST)
4120 src->state = dst->state = TCPS_TIME_WAIT;
4122 /* update expire time */
4123 (*state)->expire = time_uptime;
4124 if (src->state >= TCPS_FIN_WAIT_2 &&
4125 dst->state >= TCPS_FIN_WAIT_2)
4126 (*state)->timeout = PFTM_TCP_CLOSED;
4127 else if (src->state >= TCPS_CLOSING &&
4128 dst->state >= TCPS_CLOSING)
4129 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4130 else if (src->state < TCPS_ESTABLISHED ||
4131 dst->state < TCPS_ESTABLISHED)
4132 (*state)->timeout = PFTM_TCP_OPENING;
4133 else if (src->state >= TCPS_CLOSING ||
4134 dst->state >= TCPS_CLOSING)
4135 (*state)->timeout = PFTM_TCP_CLOSING;
4137 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4139 /* Fall through to PASS packet */
4141 } else if ((dst->state < TCPS_SYN_SENT ||
4142 dst->state >= TCPS_FIN_WAIT_2 ||
4143 src->state >= TCPS_FIN_WAIT_2) &&
4144 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4145 /* Within a window forward of the originating packet */
4146 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4147 /* Within a window backward of the originating packet */
4150 * This currently handles three situations:
4151 * 1) Stupid stacks will shotgun SYNs before their peer
4153 * 2) When PF catches an already established stream (the
4154 * firewall rebooted, the state table was flushed, routes
4156 * 3) Packets get funky immediately after the connection
4157 * closes (this should catch Solaris spurious ACK|FINs
4158 * that web servers like to spew after a close)
4160 * This must be a little more careful than the above code
4161 * since packet floods will also be caught here. We don't
4162 * update the TTL here to mitigate the damage of a packet
4163 * flood and so the same code can handle awkward establishment
4164 * and a loosened connection close.
4165 * In the establishment case, a correct peer response will
4166 * validate the connection, go through the normal state code
4167 * and keep updating the state TTL.
4170 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4171 printf("pf: loose state match: ");
4172 pf_print_state(*state);
4173 pf_print_flags(th->th_flags);
4174 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4175 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4176 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4177 (unsigned long long)(*state)->packets[1],
4178 pd->dir == PF_IN ? "in" : "out",
4179 pd->dir == (*state)->direction ? "fwd" : "rev");
4182 if (dst->scrub || src->scrub) {
4183 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4184 *state, src, dst, copyback))
4188 /* update max window */
4189 if (src->max_win < win)
4191 /* synchronize sequencing */
4192 if (SEQ_GT(end, src->seqlo))
4194 /* slide the window of what the other end can send */
4195 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4196 dst->seqhi = ack + MAX((win << sws), 1);
4199 * Cannot set dst->seqhi here since this could be a shotgunned
4200 * SYN and not an already established connection.
4203 if (th->th_flags & TH_FIN)
4204 if (src->state < TCPS_CLOSING)
4205 src->state = TCPS_CLOSING;
4206 if (th->th_flags & TH_RST)
4207 src->state = dst->state = TCPS_TIME_WAIT;
4209 /* Fall through to PASS packet */
4212 if ((*state)->dst.state == TCPS_SYN_SENT &&
4213 (*state)->src.state == TCPS_SYN_SENT) {
4214 /* Send RST for state mismatches during handshake */
4215 if (!(th->th_flags & TH_RST))
4216 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4217 pd->dst, pd->src, th->th_dport,
4218 th->th_sport, ntohl(th->th_ack), 0,
4220 (*state)->rule.ptr->return_ttl, 1, 0,
4225 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4226 printf("pf: BAD state: ");
4227 pf_print_state(*state);
4228 pf_print_flags(th->th_flags);
4229 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4230 "pkts=%llu:%llu dir=%s,%s\n",
4231 seq, orig_seq, ack, pd->p_len, ackskew,
4232 (unsigned long long)(*state)->packets[0],
4233 (unsigned long long)(*state)->packets[1],
4234 pd->dir == PF_IN ? "in" : "out",
4235 pd->dir == (*state)->direction ? "fwd" : "rev");
4236 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4237 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4238 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4240 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4241 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4242 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4243 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4245 REASON_SET(reason, PFRES_BADSTATE);
4253 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4254 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4256 struct tcphdr *th = pd->hdr.tcp;
4258 if (th->th_flags & TH_SYN)
4259 if (src->state < TCPS_SYN_SENT)
4260 src->state = TCPS_SYN_SENT;
4261 if (th->th_flags & TH_FIN)
4262 if (src->state < TCPS_CLOSING)
4263 src->state = TCPS_CLOSING;
4264 if (th->th_flags & TH_ACK) {
4265 if (dst->state == TCPS_SYN_SENT) {
4266 dst->state = TCPS_ESTABLISHED;
4267 if (src->state == TCPS_ESTABLISHED &&
4268 (*state)->src_node != NULL &&
4269 pf_src_connlimit(state)) {
4270 REASON_SET(reason, PFRES_SRCLIMIT);
4273 } else if (dst->state == TCPS_CLOSING) {
4274 dst->state = TCPS_FIN_WAIT_2;
4275 } else if (src->state == TCPS_SYN_SENT &&
4276 dst->state < TCPS_SYN_SENT) {
4278 * Handle a special sloppy case where we only see one
4279 * half of the connection. If there is a ACK after
4280 * the initial SYN without ever seeing a packet from
4281 * the destination, set the connection to established.
4283 dst->state = src->state = TCPS_ESTABLISHED;
4284 if ((*state)->src_node != NULL &&
4285 pf_src_connlimit(state)) {
4286 REASON_SET(reason, PFRES_SRCLIMIT);
4289 } else if (src->state == TCPS_CLOSING &&
4290 dst->state == TCPS_ESTABLISHED &&
4293 * Handle the closing of half connections where we
4294 * don't see the full bidirectional FIN/ACK+ACK
4297 dst->state = TCPS_CLOSING;
4300 if (th->th_flags & TH_RST)
4301 src->state = dst->state = TCPS_TIME_WAIT;
4303 /* update expire time */
4304 (*state)->expire = time_uptime;
4305 if (src->state >= TCPS_FIN_WAIT_2 &&
4306 dst->state >= TCPS_FIN_WAIT_2)
4307 (*state)->timeout = PFTM_TCP_CLOSED;
4308 else if (src->state >= TCPS_CLOSING &&
4309 dst->state >= TCPS_CLOSING)
4310 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4311 else if (src->state < TCPS_ESTABLISHED ||
4312 dst->state < TCPS_ESTABLISHED)
4313 (*state)->timeout = PFTM_TCP_OPENING;
4314 else if (src->state >= TCPS_CLOSING ||
4315 dst->state >= TCPS_CLOSING)
4316 (*state)->timeout = PFTM_TCP_CLOSING;
4318 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4324 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4325 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4328 struct pf_state_key_cmp key;
4329 struct tcphdr *th = pd->hdr.tcp;
4331 struct pf_state_peer *src, *dst;
4332 struct pf_state_key *sk;
4334 bzero(&key, sizeof(key));
4336 key.proto = IPPROTO_TCP;
4337 if (direction == PF_IN) { /* wire side, straight */
4338 PF_ACPY(&key.addr[0], pd->src, key.af);
4339 PF_ACPY(&key.addr[1], pd->dst, key.af);
4340 key.port[0] = th->th_sport;
4341 key.port[1] = th->th_dport;
4342 } else { /* stack side, reverse */
4343 PF_ACPY(&key.addr[1], pd->src, key.af);
4344 PF_ACPY(&key.addr[0], pd->dst, key.af);
4345 key.port[1] = th->th_sport;
4346 key.port[0] = th->th_dport;
4349 STATE_LOOKUP(kif, &key, direction, *state, pd);
4351 if (direction == (*state)->direction) {
4352 src = &(*state)->src;
4353 dst = &(*state)->dst;
4355 src = &(*state)->dst;
4356 dst = &(*state)->src;
4359 sk = (*state)->key[pd->didx];
4361 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4362 if (direction != (*state)->direction) {
4363 REASON_SET(reason, PFRES_SYNPROXY);
4364 return (PF_SYNPROXY_DROP);
4366 if (th->th_flags & TH_SYN) {
4367 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4368 REASON_SET(reason, PFRES_SYNPROXY);
4371 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4372 pd->src, th->th_dport, th->th_sport,
4373 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4374 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4375 REASON_SET(reason, PFRES_SYNPROXY);
4376 return (PF_SYNPROXY_DROP);
4377 } else if (!(th->th_flags & TH_ACK) ||
4378 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4379 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4380 REASON_SET(reason, PFRES_SYNPROXY);
4382 } else if ((*state)->src_node != NULL &&
4383 pf_src_connlimit(state)) {
4384 REASON_SET(reason, PFRES_SRCLIMIT);
4387 (*state)->src.state = PF_TCPS_PROXY_DST;
4389 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4390 if (direction == (*state)->direction) {
4391 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4392 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4393 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4394 REASON_SET(reason, PFRES_SYNPROXY);
4397 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4398 if ((*state)->dst.seqhi == 1)
4399 (*state)->dst.seqhi = htonl(arc4random());
4400 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4401 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4402 sk->port[pd->sidx], sk->port[pd->didx],
4403 (*state)->dst.seqhi, 0, TH_SYN, 0,
4404 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4405 REASON_SET(reason, PFRES_SYNPROXY);
4406 return (PF_SYNPROXY_DROP);
4407 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4409 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4410 REASON_SET(reason, PFRES_SYNPROXY);
4413 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4414 (*state)->dst.seqlo = ntohl(th->th_seq);
4415 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4416 pd->src, th->th_dport, th->th_sport,
4417 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4418 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4419 (*state)->tag, NULL);
4420 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4421 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4422 sk->port[pd->sidx], sk->port[pd->didx],
4423 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4424 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4425 (*state)->src.seqdiff = (*state)->dst.seqhi -
4426 (*state)->src.seqlo;
4427 (*state)->dst.seqdiff = (*state)->src.seqhi -
4428 (*state)->dst.seqlo;
4429 (*state)->src.seqhi = (*state)->src.seqlo +
4430 (*state)->dst.max_win;
4431 (*state)->dst.seqhi = (*state)->dst.seqlo +
4432 (*state)->src.max_win;
4433 (*state)->src.wscale = (*state)->dst.wscale = 0;
4434 (*state)->src.state = (*state)->dst.state =
4436 REASON_SET(reason, PFRES_SYNPROXY);
4437 return (PF_SYNPROXY_DROP);
4441 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4442 dst->state >= TCPS_FIN_WAIT_2 &&
4443 src->state >= TCPS_FIN_WAIT_2) {
4444 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4445 printf("pf: state reuse ");
4446 pf_print_state(*state);
4447 pf_print_flags(th->th_flags);
4450 /* XXX make sure it's the same direction ?? */
4451 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4452 pf_unlink_state(*state, PF_ENTER_LOCKED);
4457 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4458 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4461 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4462 ©back) == PF_DROP)
4466 /* translate source/destination address, if necessary */
4467 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4468 struct pf_state_key *nk = (*state)->key[pd->didx];
4470 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4471 nk->port[pd->sidx] != th->th_sport)
4472 pf_change_ap(m, pd->src, &th->th_sport,
4473 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4474 nk->port[pd->sidx], 0, pd->af);
4476 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4477 nk->port[pd->didx] != th->th_dport)
4478 pf_change_ap(m, pd->dst, &th->th_dport,
4479 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4480 nk->port[pd->didx], 0, pd->af);
4484 /* Copyback sequence modulation or stateful scrub changes if needed */
4486 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4492 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4493 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4495 struct pf_state_peer *src, *dst;
4496 struct pf_state_key_cmp key;
4497 struct udphdr *uh = pd->hdr.udp;
4499 bzero(&key, sizeof(key));
4501 key.proto = IPPROTO_UDP;
4502 if (direction == PF_IN) { /* wire side, straight */
4503 PF_ACPY(&key.addr[0], pd->src, key.af);
4504 PF_ACPY(&key.addr[1], pd->dst, key.af);
4505 key.port[0] = uh->uh_sport;
4506 key.port[1] = uh->uh_dport;
4507 } else { /* stack side, reverse */
4508 PF_ACPY(&key.addr[1], pd->src, key.af);
4509 PF_ACPY(&key.addr[0], pd->dst, key.af);
4510 key.port[1] = uh->uh_sport;
4511 key.port[0] = uh->uh_dport;
4514 STATE_LOOKUP(kif, &key, direction, *state, pd);
4516 if (direction == (*state)->direction) {
4517 src = &(*state)->src;
4518 dst = &(*state)->dst;
4520 src = &(*state)->dst;
4521 dst = &(*state)->src;
4525 if (src->state < PFUDPS_SINGLE)
4526 src->state = PFUDPS_SINGLE;
4527 if (dst->state == PFUDPS_SINGLE)
4528 dst->state = PFUDPS_MULTIPLE;
4530 /* update expire time */
4531 (*state)->expire = time_uptime;
4532 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4533 (*state)->timeout = PFTM_UDP_MULTIPLE;
4535 (*state)->timeout = PFTM_UDP_SINGLE;
4537 /* translate source/destination address, if necessary */
4538 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4539 struct pf_state_key *nk = (*state)->key[pd->didx];
4541 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4542 nk->port[pd->sidx] != uh->uh_sport)
4543 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4544 &uh->uh_sum, &nk->addr[pd->sidx],
4545 nk->port[pd->sidx], 1, pd->af);
4547 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4548 nk->port[pd->didx] != uh->uh_dport)
4549 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4550 &uh->uh_sum, &nk->addr[pd->didx],
4551 nk->port[pd->didx], 1, pd->af);
4552 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4559 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4560 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4562 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4563 u_int16_t icmpid = 0, *icmpsum;
4566 struct pf_state_key_cmp key;
4568 bzero(&key, sizeof(key));
4569 switch (pd->proto) {
4572 icmptype = pd->hdr.icmp->icmp_type;
4573 icmpid = pd->hdr.icmp->icmp_id;
4574 icmpsum = &pd->hdr.icmp->icmp_cksum;
4576 if (icmptype == ICMP_UNREACH ||
4577 icmptype == ICMP_SOURCEQUENCH ||
4578 icmptype == ICMP_REDIRECT ||
4579 icmptype == ICMP_TIMXCEED ||
4580 icmptype == ICMP_PARAMPROB)
4585 case IPPROTO_ICMPV6:
4586 icmptype = pd->hdr.icmp6->icmp6_type;
4587 icmpid = pd->hdr.icmp6->icmp6_id;
4588 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4590 if (icmptype == ICMP6_DST_UNREACH ||
4591 icmptype == ICMP6_PACKET_TOO_BIG ||
4592 icmptype == ICMP6_TIME_EXCEEDED ||
4593 icmptype == ICMP6_PARAM_PROB)
4602 * ICMP query/reply message not related to a TCP/UDP packet.
4603 * Search for an ICMP state.
4606 key.proto = pd->proto;
4607 key.port[0] = key.port[1] = icmpid;
4608 if (direction == PF_IN) { /* wire side, straight */
4609 PF_ACPY(&key.addr[0], pd->src, key.af);
4610 PF_ACPY(&key.addr[1], pd->dst, key.af);
4611 } else { /* stack side, reverse */
4612 PF_ACPY(&key.addr[1], pd->src, key.af);
4613 PF_ACPY(&key.addr[0], pd->dst, key.af);
4616 STATE_LOOKUP(kif, &key, direction, *state, pd);
4618 (*state)->expire = time_uptime;
4619 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4621 /* translate source/destination address, if necessary */
4622 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4623 struct pf_state_key *nk = (*state)->key[pd->didx];
4628 if (PF_ANEQ(pd->src,
4629 &nk->addr[pd->sidx], AF_INET))
4630 pf_change_a(&saddr->v4.s_addr,
4632 nk->addr[pd->sidx].v4.s_addr, 0);
4634 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4636 pf_change_a(&daddr->v4.s_addr,
4638 nk->addr[pd->didx].v4.s_addr, 0);
4641 pd->hdr.icmp->icmp_id) {
4642 pd->hdr.icmp->icmp_cksum =
4644 pd->hdr.icmp->icmp_cksum, icmpid,
4645 nk->port[pd->sidx], 0);
4646 pd->hdr.icmp->icmp_id =
4650 m_copyback(m, off, ICMP_MINLEN,
4651 (caddr_t )pd->hdr.icmp);
4656 if (PF_ANEQ(pd->src,
4657 &nk->addr[pd->sidx], AF_INET6))
4659 &pd->hdr.icmp6->icmp6_cksum,
4660 &nk->addr[pd->sidx], 0);
4662 if (PF_ANEQ(pd->dst,
4663 &nk->addr[pd->didx], AF_INET6))
4665 &pd->hdr.icmp6->icmp6_cksum,
4666 &nk->addr[pd->didx], 0);
4668 m_copyback(m, off, sizeof(struct icmp6_hdr),
4669 (caddr_t )pd->hdr.icmp6);
4678 * ICMP error message in response to a TCP/UDP packet.
4679 * Extract the inner TCP/UDP header and search for that state.
4682 struct pf_pdesc pd2;
4683 bzero(&pd2, sizeof pd2);
4688 struct ip6_hdr h2_6;
4695 /* Payload packet is from the opposite direction. */
4696 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4697 pd2.didx = (direction == PF_IN) ? 0 : 1;
4701 /* offset of h2 in mbuf chain */
4702 ipoff2 = off + ICMP_MINLEN;
4704 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4705 NULL, reason, pd2.af)) {
4706 DPFPRINTF(PF_DEBUG_MISC,
4707 ("pf: ICMP error message too short "
4712 * ICMP error messages don't refer to non-first
4715 if (h2.ip_off & htons(IP_OFFMASK)) {
4716 REASON_SET(reason, PFRES_FRAG);
4720 /* offset of protocol header that follows h2 */
4721 off2 = ipoff2 + (h2.ip_hl << 2);
4723 pd2.proto = h2.ip_p;
4724 pd2.src = (struct pf_addr *)&h2.ip_src;
4725 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4726 pd2.ip_sum = &h2.ip_sum;
4731 ipoff2 = off + sizeof(struct icmp6_hdr);
4733 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4734 NULL, reason, pd2.af)) {
4735 DPFPRINTF(PF_DEBUG_MISC,
4736 ("pf: ICMP error message too short "
4740 pd2.proto = h2_6.ip6_nxt;
4741 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4742 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4744 off2 = ipoff2 + sizeof(h2_6);
4746 switch (pd2.proto) {
4747 case IPPROTO_FRAGMENT:
4749 * ICMPv6 error messages for
4750 * non-first fragments
4752 REASON_SET(reason, PFRES_FRAG);
4755 case IPPROTO_HOPOPTS:
4756 case IPPROTO_ROUTING:
4757 case IPPROTO_DSTOPTS: {
4758 /* get next header and header length */
4759 struct ip6_ext opt6;
4761 if (!pf_pull_hdr(m, off2, &opt6,
4762 sizeof(opt6), NULL, reason,
4764 DPFPRINTF(PF_DEBUG_MISC,
4765 ("pf: ICMPv6 short opt\n"));
4768 if (pd2.proto == IPPROTO_AH)
4769 off2 += (opt6.ip6e_len + 2) * 4;
4771 off2 += (opt6.ip6e_len + 1) * 8;
4772 pd2.proto = opt6.ip6e_nxt;
4773 /* goto the next header */
4780 } while (!terminal);
4785 switch (pd2.proto) {
4789 struct pf_state_peer *src, *dst;
4794 * Only the first 8 bytes of the TCP header can be
4795 * expected. Don't access any TCP header fields after
4796 * th_seq, an ackskew test is not possible.
4798 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4800 DPFPRINTF(PF_DEBUG_MISC,
4801 ("pf: ICMP error message too short "
4807 key.proto = IPPROTO_TCP;
4808 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4809 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4810 key.port[pd2.sidx] = th.th_sport;
4811 key.port[pd2.didx] = th.th_dport;
4813 STATE_LOOKUP(kif, &key, direction, *state, pd);
4815 if (direction == (*state)->direction) {
4816 src = &(*state)->dst;
4817 dst = &(*state)->src;
4819 src = &(*state)->src;
4820 dst = &(*state)->dst;
4823 if (src->wscale && dst->wscale)
4824 dws = dst->wscale & PF_WSCALE_MASK;
4828 /* Demodulate sequence number */
4829 seq = ntohl(th.th_seq) - src->seqdiff;
4831 pf_change_a(&th.th_seq, icmpsum,
4836 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4837 (!SEQ_GEQ(src->seqhi, seq) ||
4838 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4839 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4840 printf("pf: BAD ICMP %d:%d ",
4841 icmptype, pd->hdr.icmp->icmp_code);
4842 pf_print_host(pd->src, 0, pd->af);
4844 pf_print_host(pd->dst, 0, pd->af);
4846 pf_print_state(*state);
4847 printf(" seq=%u\n", seq);
4849 REASON_SET(reason, PFRES_BADSTATE);
4852 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4853 printf("pf: OK ICMP %d:%d ",
4854 icmptype, pd->hdr.icmp->icmp_code);
4855 pf_print_host(pd->src, 0, pd->af);
4857 pf_print_host(pd->dst, 0, pd->af);
4859 pf_print_state(*state);
4860 printf(" seq=%u\n", seq);
4864 /* translate source/destination address, if necessary */
4865 if ((*state)->key[PF_SK_WIRE] !=
4866 (*state)->key[PF_SK_STACK]) {
4867 struct pf_state_key *nk =
4868 (*state)->key[pd->didx];
4870 if (PF_ANEQ(pd2.src,
4871 &nk->addr[pd2.sidx], pd2.af) ||
4872 nk->port[pd2.sidx] != th.th_sport)
4873 pf_change_icmp(pd2.src, &th.th_sport,
4874 daddr, &nk->addr[pd2.sidx],
4875 nk->port[pd2.sidx], NULL,
4876 pd2.ip_sum, icmpsum,
4877 pd->ip_sum, 0, pd2.af);
4879 if (PF_ANEQ(pd2.dst,
4880 &nk->addr[pd2.didx], pd2.af) ||
4881 nk->port[pd2.didx] != th.th_dport)
4882 pf_change_icmp(pd2.dst, &th.th_dport,
4883 saddr, &nk->addr[pd2.didx],
4884 nk->port[pd2.didx], NULL,
4885 pd2.ip_sum, icmpsum,
4886 pd->ip_sum, 0, pd2.af);
4894 m_copyback(m, off, ICMP_MINLEN,
4895 (caddr_t )pd->hdr.icmp);
4896 m_copyback(m, ipoff2, sizeof(h2),
4903 sizeof(struct icmp6_hdr),
4904 (caddr_t )pd->hdr.icmp6);
4905 m_copyback(m, ipoff2, sizeof(h2_6),
4910 m_copyback(m, off2, 8, (caddr_t)&th);
4919 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4920 NULL, reason, pd2.af)) {
4921 DPFPRINTF(PF_DEBUG_MISC,
4922 ("pf: ICMP error message too short "
4928 key.proto = IPPROTO_UDP;
4929 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4930 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4931 key.port[pd2.sidx] = uh.uh_sport;
4932 key.port[pd2.didx] = uh.uh_dport;
4934 STATE_LOOKUP(kif, &key, direction, *state, pd);
4936 /* translate source/destination address, if necessary */
4937 if ((*state)->key[PF_SK_WIRE] !=
4938 (*state)->key[PF_SK_STACK]) {
4939 struct pf_state_key *nk =
4940 (*state)->key[pd->didx];
4942 if (PF_ANEQ(pd2.src,
4943 &nk->addr[pd2.sidx], pd2.af) ||
4944 nk->port[pd2.sidx] != uh.uh_sport)
4945 pf_change_icmp(pd2.src, &uh.uh_sport,
4946 daddr, &nk->addr[pd2.sidx],
4947 nk->port[pd2.sidx], &uh.uh_sum,
4948 pd2.ip_sum, icmpsum,
4949 pd->ip_sum, 1, pd2.af);
4951 if (PF_ANEQ(pd2.dst,
4952 &nk->addr[pd2.didx], pd2.af) ||
4953 nk->port[pd2.didx] != uh.uh_dport)
4954 pf_change_icmp(pd2.dst, &uh.uh_dport,
4955 saddr, &nk->addr[pd2.didx],
4956 nk->port[pd2.didx], &uh.uh_sum,
4957 pd2.ip_sum, icmpsum,
4958 pd->ip_sum, 1, pd2.af);
4963 m_copyback(m, off, ICMP_MINLEN,
4964 (caddr_t )pd->hdr.icmp);
4965 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4971 sizeof(struct icmp6_hdr),
4972 (caddr_t )pd->hdr.icmp6);
4973 m_copyback(m, ipoff2, sizeof(h2_6),
4978 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4984 case IPPROTO_ICMP: {
4987 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4988 NULL, reason, pd2.af)) {
4989 DPFPRINTF(PF_DEBUG_MISC,
4990 ("pf: ICMP error message too short i"
4996 key.proto = IPPROTO_ICMP;
4997 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4998 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4999 key.port[0] = key.port[1] = iih.icmp_id;
5001 STATE_LOOKUP(kif, &key, direction, *state, pd);
5003 /* translate source/destination address, if necessary */
5004 if ((*state)->key[PF_SK_WIRE] !=
5005 (*state)->key[PF_SK_STACK]) {
5006 struct pf_state_key *nk =
5007 (*state)->key[pd->didx];
5009 if (PF_ANEQ(pd2.src,
5010 &nk->addr[pd2.sidx], pd2.af) ||
5011 nk->port[pd2.sidx] != iih.icmp_id)
5012 pf_change_icmp(pd2.src, &iih.icmp_id,
5013 daddr, &nk->addr[pd2.sidx],
5014 nk->port[pd2.sidx], NULL,
5015 pd2.ip_sum, icmpsum,
5016 pd->ip_sum, 0, AF_INET);
5018 if (PF_ANEQ(pd2.dst,
5019 &nk->addr[pd2.didx], pd2.af) ||
5020 nk->port[pd2.didx] != iih.icmp_id)
5021 pf_change_icmp(pd2.dst, &iih.icmp_id,
5022 saddr, &nk->addr[pd2.didx],
5023 nk->port[pd2.didx], NULL,
5024 pd2.ip_sum, icmpsum,
5025 pd->ip_sum, 0, AF_INET);
5027 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5028 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5029 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5036 case IPPROTO_ICMPV6: {
5037 struct icmp6_hdr iih;
5039 if (!pf_pull_hdr(m, off2, &iih,
5040 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5041 DPFPRINTF(PF_DEBUG_MISC,
5042 ("pf: ICMP error message too short "
5048 key.proto = IPPROTO_ICMPV6;
5049 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5050 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5051 key.port[0] = key.port[1] = iih.icmp6_id;
5053 STATE_LOOKUP(kif, &key, direction, *state, pd);
5055 /* translate source/destination address, if necessary */
5056 if ((*state)->key[PF_SK_WIRE] !=
5057 (*state)->key[PF_SK_STACK]) {
5058 struct pf_state_key *nk =
5059 (*state)->key[pd->didx];
5061 if (PF_ANEQ(pd2.src,
5062 &nk->addr[pd2.sidx], pd2.af) ||
5063 nk->port[pd2.sidx] != iih.icmp6_id)
5064 pf_change_icmp(pd2.src, &iih.icmp6_id,
5065 daddr, &nk->addr[pd2.sidx],
5066 nk->port[pd2.sidx], NULL,
5067 pd2.ip_sum, icmpsum,
5068 pd->ip_sum, 0, AF_INET6);
5070 if (PF_ANEQ(pd2.dst,
5071 &nk->addr[pd2.didx], pd2.af) ||
5072 nk->port[pd2.didx] != iih.icmp6_id)
5073 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5074 saddr, &nk->addr[pd2.didx],
5075 nk->port[pd2.didx], NULL,
5076 pd2.ip_sum, icmpsum,
5077 pd->ip_sum, 0, AF_INET6);
5079 m_copyback(m, off, sizeof(struct icmp6_hdr),
5080 (caddr_t)pd->hdr.icmp6);
5081 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5082 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5091 key.proto = pd2.proto;
5092 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5093 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5094 key.port[0] = key.port[1] = 0;
5096 STATE_LOOKUP(kif, &key, direction, *state, pd);
5098 /* translate source/destination address, if necessary */
5099 if ((*state)->key[PF_SK_WIRE] !=
5100 (*state)->key[PF_SK_STACK]) {
5101 struct pf_state_key *nk =
5102 (*state)->key[pd->didx];
5104 if (PF_ANEQ(pd2.src,
5105 &nk->addr[pd2.sidx], pd2.af))
5106 pf_change_icmp(pd2.src, NULL, daddr,
5107 &nk->addr[pd2.sidx], 0, NULL,
5108 pd2.ip_sum, icmpsum,
5109 pd->ip_sum, 0, pd2.af);
5111 if (PF_ANEQ(pd2.dst,
5112 &nk->addr[pd2.didx], pd2.af))
5113 pf_change_icmp(pd2.dst, NULL, saddr,
5114 &nk->addr[pd2.didx], 0, NULL,
5115 pd2.ip_sum, icmpsum,
5116 pd->ip_sum, 0, pd2.af);
5121 m_copyback(m, off, ICMP_MINLEN,
5122 (caddr_t)pd->hdr.icmp);
5123 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5129 sizeof(struct icmp6_hdr),
5130 (caddr_t )pd->hdr.icmp6);
5131 m_copyback(m, ipoff2, sizeof(h2_6),
5145 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5146 struct mbuf *m, struct pf_pdesc *pd)
5148 struct pf_state_peer *src, *dst;
5149 struct pf_state_key_cmp key;
5151 bzero(&key, sizeof(key));
5153 key.proto = pd->proto;
5154 if (direction == PF_IN) {
5155 PF_ACPY(&key.addr[0], pd->src, key.af);
5156 PF_ACPY(&key.addr[1], pd->dst, key.af);
5157 key.port[0] = key.port[1] = 0;
5159 PF_ACPY(&key.addr[1], pd->src, key.af);
5160 PF_ACPY(&key.addr[0], pd->dst, key.af);
5161 key.port[1] = key.port[0] = 0;
5164 STATE_LOOKUP(kif, &key, direction, *state, pd);
5166 if (direction == (*state)->direction) {
5167 src = &(*state)->src;
5168 dst = &(*state)->dst;
5170 src = &(*state)->dst;
5171 dst = &(*state)->src;
5175 if (src->state < PFOTHERS_SINGLE)
5176 src->state = PFOTHERS_SINGLE;
5177 if (dst->state == PFOTHERS_SINGLE)
5178 dst->state = PFOTHERS_MULTIPLE;
5180 /* update expire time */
5181 (*state)->expire = time_uptime;
5182 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5183 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5185 (*state)->timeout = PFTM_OTHER_SINGLE;
5187 /* translate source/destination address, if necessary */
5188 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5189 struct pf_state_key *nk = (*state)->key[pd->didx];
5191 KASSERT(nk, ("%s: nk is null", __func__));
5192 KASSERT(pd, ("%s: pd is null", __func__));
5193 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5194 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5198 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5199 pf_change_a(&pd->src->v4.s_addr,
5201 nk->addr[pd->sidx].v4.s_addr,
5205 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5206 pf_change_a(&pd->dst->v4.s_addr,
5208 nk->addr[pd->didx].v4.s_addr,
5215 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5216 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5218 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5219 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5227 * ipoff and off are measured from the start of the mbuf chain.
5228 * h must be at "ipoff" on the mbuf chain.
5231 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5232 u_short *actionp, u_short *reasonp, sa_family_t af)
5237 struct ip *h = mtod(m, struct ip *);
5238 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5242 ACTION_SET(actionp, PF_PASS);
5244 ACTION_SET(actionp, PF_DROP);
5245 REASON_SET(reasonp, PFRES_FRAG);
5249 if (m->m_pkthdr.len < off + len ||
5250 ntohs(h->ip_len) < off + len) {
5251 ACTION_SET(actionp, PF_DROP);
5252 REASON_SET(reasonp, PFRES_SHORT);
5260 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5262 if (m->m_pkthdr.len < off + len ||
5263 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5264 (unsigned)(off + len)) {
5265 ACTION_SET(actionp, PF_DROP);
5266 REASON_SET(reasonp, PFRES_SHORT);
5273 m_copydata(m, off, len, p);
5279 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5282 struct radix_node_head *rnh;
5283 struct sockaddr_in *dst;
5287 struct sockaddr_in6 *dst6;
5288 struct route_in6 ro;
5292 struct radix_node *rn;
5297 /* XXX: stick to table 0 for now */
5298 rnh = rt_tables_get_rnh(0, af);
5299 if (rnh != NULL && rn_mpath_capable(rnh))
5301 bzero(&ro, sizeof(ro));
5304 dst = satosin(&ro.ro_dst);
5305 dst->sin_family = AF_INET;
5306 dst->sin_len = sizeof(*dst);
5307 dst->sin_addr = addr->v4;
5312 * Skip check for addresses with embedded interface scope,
5313 * as they would always match anyway.
5315 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5317 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5318 dst6->sin6_family = AF_INET6;
5319 dst6->sin6_len = sizeof(*dst6);
5320 dst6->sin6_addr = addr->v6;
5327 /* Skip checks for ipsec interfaces */
5328 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5334 in6_rtalloc_ign(&ro, 0, rtableid);
5339 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5344 if (ro.ro_rt != NULL) {
5345 /* No interface given, this is a no-route check */
5349 if (kif->pfik_ifp == NULL) {
5354 /* Perform uRPF check if passed input interface */
5356 rn = (struct radix_node *)ro.ro_rt;
5358 rt = (struct rtentry *)rn;
5361 if (kif->pfik_ifp == ifp)
5363 rn = rn_mpath_next(rn);
5364 } while (check_mpath == 1 && rn != NULL && ret == 0);
5368 if (ro.ro_rt != NULL)
5375 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5379 struct nhop4_basic nh4;
5382 struct nhop6_basic nh6;
5386 struct radix_node_head *rnh;
5388 /* XXX: stick to table 0 for now */
5389 rnh = rt_tables_get_rnh(0, af);
5390 if (rnh != NULL && rn_mpath_capable(rnh))
5391 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5394 * Skip check for addresses with embedded interface scope,
5395 * as they would always match anyway.
5397 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5400 if (af != AF_INET && af != AF_INET6)
5403 /* Skip checks for ipsec interfaces */
5404 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5412 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5419 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5426 /* No interface given, this is a no-route check */
5430 if (kif->pfik_ifp == NULL)
5433 /* Perform uRPF check if passed input interface */
5434 if (kif->pfik_ifp == ifp)
5441 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5442 struct pf_state *s, struct pf_pdesc *pd)
5444 struct mbuf *m0, *m1;
5445 struct sockaddr_in dst;
5447 struct ifnet *ifp = NULL;
5448 struct pf_addr naddr;
5449 struct pf_src_node *sn = NULL;
5451 uint16_t ip_len, ip_off;
5453 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5454 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5457 if ((pd->pf_mtag == NULL &&
5458 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5459 pd->pf_mtag->routed++ > 3) {
5465 if (r->rt == PF_DUPTO) {
5466 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5472 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5480 ip = mtod(m0, struct ip *);
5482 bzero(&dst, sizeof(dst));
5483 dst.sin_family = AF_INET;
5484 dst.sin_len = sizeof(dst);
5485 dst.sin_addr = ip->ip_dst;
5487 if (TAILQ_EMPTY(&r->rpool.list)) {
5488 DPFPRINTF(PF_DEBUG_URGENT,
5489 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5493 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5495 if (!PF_AZERO(&naddr, AF_INET))
5496 dst.sin_addr.s_addr = naddr.v4.s_addr;
5497 ifp = r->rpool.cur->kif ?
5498 r->rpool.cur->kif->pfik_ifp : NULL;
5500 if (!PF_AZERO(&s->rt_addr, AF_INET))
5501 dst.sin_addr.s_addr =
5502 s->rt_addr.v4.s_addr;
5503 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5510 if (pf_test(PF_OUT, 0, ifp, &m0, NULL) != PF_PASS)
5512 else if (m0 == NULL)
5514 if (m0->m_len < sizeof(struct ip)) {
5515 DPFPRINTF(PF_DEBUG_URGENT,
5516 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5519 ip = mtod(m0, struct ip *);
5522 if (ifp->if_flags & IFF_LOOPBACK)
5523 m0->m_flags |= M_SKIP_FIREWALL;
5525 ip_len = ntohs(ip->ip_len);
5526 ip_off = ntohs(ip->ip_off);
5528 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5529 m0->m_pkthdr.csum_flags |= CSUM_IP;
5530 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5531 in_delayed_cksum(m0);
5532 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5535 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5536 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5537 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5542 * If small enough for interface, or the interface will take
5543 * care of the fragmentation for us, we can just send directly.
5545 if (ip_len <= ifp->if_mtu ||
5546 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5548 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5549 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5550 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5552 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5553 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5557 /* Balk when DF bit is set or the interface didn't support TSO. */
5558 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5560 KMOD_IPSTAT_INC(ips_cantfrag);
5561 if (r->rt != PF_DUPTO) {
5562 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5569 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5573 for (; m0; m0 = m1) {
5575 m0->m_nextpkt = NULL;
5577 m_clrprotoflags(m0);
5578 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5584 KMOD_IPSTAT_INC(ips_fragmented);
5587 if (r->rt != PF_DUPTO)
5602 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5603 struct pf_state *s, struct pf_pdesc *pd)
5606 struct sockaddr_in6 dst;
5607 struct ip6_hdr *ip6;
5608 struct ifnet *ifp = NULL;
5609 struct pf_addr naddr;
5610 struct pf_src_node *sn = NULL;
5612 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5613 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5616 if ((pd->pf_mtag == NULL &&
5617 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5618 pd->pf_mtag->routed++ > 3) {
5624 if (r->rt == PF_DUPTO) {
5625 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5631 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5639 ip6 = mtod(m0, struct ip6_hdr *);
5641 bzero(&dst, sizeof(dst));
5642 dst.sin6_family = AF_INET6;
5643 dst.sin6_len = sizeof(dst);
5644 dst.sin6_addr = ip6->ip6_dst;
5646 if (TAILQ_EMPTY(&r->rpool.list)) {
5647 DPFPRINTF(PF_DEBUG_URGENT,
5648 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5652 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5654 if (!PF_AZERO(&naddr, AF_INET6))
5655 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5657 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5659 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5660 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5661 &s->rt_addr, AF_INET6);
5662 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5672 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, NULL) != PF_PASS)
5674 else if (m0 == NULL)
5676 if (m0->m_len < sizeof(struct ip6_hdr)) {
5677 DPFPRINTF(PF_DEBUG_URGENT,
5678 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5682 ip6 = mtod(m0, struct ip6_hdr *);
5685 if (ifp->if_flags & IFF_LOOPBACK)
5686 m0->m_flags |= M_SKIP_FIREWALL;
5688 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5689 ~ifp->if_hwassist) {
5690 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5691 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5692 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5696 * If the packet is too large for the outgoing interface,
5697 * send back an icmp6 error.
5699 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5700 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5701 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5702 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5704 in6_ifstat_inc(ifp, ifs6_in_toobig);
5705 if (r->rt != PF_DUPTO)
5706 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5712 if (r->rt != PF_DUPTO)
5726 * FreeBSD supports cksum offloads for the following drivers.
5727 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5728 * ti(4), txp(4), xl(4)
5730 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5731 * network driver performed cksum including pseudo header, need to verify
5734 * network driver performed cksum, needs to additional pseudo header
5735 * cksum computation with partial csum_data(i.e. lack of H/W support for
5736 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5738 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5739 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5741 * Also, set csum_data to 0xffff to force cksum validation.
5744 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5750 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5752 if (m->m_pkthdr.len < off + len)
5757 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5758 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5759 sum = m->m_pkthdr.csum_data;
5761 ip = mtod(m, struct ip *);
5762 sum = in_pseudo(ip->ip_src.s_addr,
5763 ip->ip_dst.s_addr, htonl((u_short)len +
5764 m->m_pkthdr.csum_data + IPPROTO_TCP));
5771 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5772 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5773 sum = m->m_pkthdr.csum_data;
5775 ip = mtod(m, struct ip *);
5776 sum = in_pseudo(ip->ip_src.s_addr,
5777 ip->ip_dst.s_addr, htonl((u_short)len +
5778 m->m_pkthdr.csum_data + IPPROTO_UDP));
5786 case IPPROTO_ICMPV6:
5796 if (p == IPPROTO_ICMP) {
5801 sum = in_cksum(m, len);
5805 if (m->m_len < sizeof(struct ip))
5807 sum = in4_cksum(m, p, off, len);
5812 if (m->m_len < sizeof(struct ip6_hdr))
5814 sum = in6_cksum(m, p, off, len);
5825 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5830 KMOD_UDPSTAT_INC(udps_badsum);
5836 KMOD_ICMPSTAT_INC(icps_checksum);
5841 case IPPROTO_ICMPV6:
5843 KMOD_ICMP6STAT_INC(icp6s_checksum);
5850 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5851 m->m_pkthdr.csum_flags |=
5852 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5853 m->m_pkthdr.csum_data = 0xffff;
5862 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5864 struct pfi_kif *kif;
5865 u_short action, reason = 0, log = 0;
5866 struct mbuf *m = *m0;
5867 struct ip *h = NULL;
5868 struct m_tag *ipfwtag;
5869 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5870 struct pf_state *s = NULL;
5871 struct pf_ruleset *ruleset = NULL;
5873 int off, dirndx, pqid = 0;
5877 if (!V_pf_status.running)
5880 memset(&pd, 0, sizeof(pd));
5882 kif = (struct pfi_kif *)ifp->if_pf_kif;
5885 DPFPRINTF(PF_DEBUG_URGENT,
5886 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5889 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5892 if (m->m_flags & M_SKIP_FIREWALL)
5895 pd.pf_mtag = pf_find_mtag(m);
5899 if (ip_divert_ptr != NULL &&
5900 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5901 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5902 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5903 if (pd.pf_mtag == NULL &&
5904 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5908 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5909 m_tag_delete(m, ipfwtag);
5911 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5912 m->m_flags |= M_FASTFWD_OURS;
5913 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5915 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5916 /* We do IP header normalization and packet reassembly here */
5920 m = *m0; /* pf_normalize messes with m0 */
5921 h = mtod(m, struct ip *);
5923 off = h->ip_hl << 2;
5924 if (off < (int)sizeof(struct ip)) {
5926 REASON_SET(&reason, PFRES_SHORT);
5931 pd.src = (struct pf_addr *)&h->ip_src;
5932 pd.dst = (struct pf_addr *)&h->ip_dst;
5933 pd.sport = pd.dport = NULL;
5934 pd.ip_sum = &h->ip_sum;
5935 pd.proto_sum = NULL;
5938 pd.sidx = (dir == PF_IN) ? 0 : 1;
5939 pd.didx = (dir == PF_IN) ? 1 : 0;
5941 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5942 pd.tot_len = ntohs(h->ip_len);
5944 /* handle fragments that didn't get reassembled by normalization */
5945 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5946 action = pf_test_fragment(&r, dir, kif, m, h,
5957 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5958 &action, &reason, AF_INET)) {
5959 log = action != PF_PASS;
5962 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5963 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5965 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5966 if (action == PF_DROP)
5968 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5970 if (action == PF_PASS) {
5971 if (pfsync_update_state_ptr != NULL)
5972 pfsync_update_state_ptr(s);
5976 } else if (s == NULL)
5977 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5986 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5987 &action, &reason, AF_INET)) {
5988 log = action != PF_PASS;
5991 if (uh.uh_dport == 0 ||
5992 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5993 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5995 REASON_SET(&reason, PFRES_SHORT);
5998 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5999 if (action == PF_PASS) {
6000 if (pfsync_update_state_ptr != NULL)
6001 pfsync_update_state_ptr(s);
6005 } else if (s == NULL)
6006 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6011 case IPPROTO_ICMP: {
6015 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6016 &action, &reason, AF_INET)) {
6017 log = action != PF_PASS;
6020 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6022 if (action == PF_PASS) {
6023 if (pfsync_update_state_ptr != NULL)
6024 pfsync_update_state_ptr(s);
6028 } else if (s == NULL)
6029 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6035 case IPPROTO_ICMPV6: {
6037 DPFPRINTF(PF_DEBUG_MISC,
6038 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6044 action = pf_test_state_other(&s, dir, kif, m, &pd);
6045 if (action == PF_PASS) {
6046 if (pfsync_update_state_ptr != NULL)
6047 pfsync_update_state_ptr(s);
6051 } else if (s == NULL)
6052 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6059 if (action == PF_PASS && h->ip_hl > 5 &&
6060 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6062 REASON_SET(&reason, PFRES_IPOPTIONS);
6064 DPFPRINTF(PF_DEBUG_MISC,
6065 ("pf: dropping packet with ip options\n"));
6068 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6070 REASON_SET(&reason, PFRES_MEMORY);
6072 if (r->rtableid >= 0)
6073 M_SETFIB(m, r->rtableid);
6075 if (r->scrub_flags & PFSTATE_SETPRIO) {
6076 if (pd.tos & IPTOS_LOWDELAY)
6078 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6080 REASON_SET(&reason, PFRES_MEMORY);
6082 DPFPRINTF(PF_DEBUG_MISC,
6083 ("pf: failed to allocate 802.1q mtag\n"));
6088 if (action == PF_PASS && r->qid) {
6089 if (pd.pf_mtag == NULL &&
6090 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6092 REASON_SET(&reason, PFRES_MEMORY);
6095 pd.pf_mtag->qid_hash = pf_state_hash(s);
6096 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6097 pd.pf_mtag->qid = r->pqid;
6099 pd.pf_mtag->qid = r->qid;
6100 /* Add hints for ecn. */
6101 pd.pf_mtag->hdr = h;
6108 * connections redirected to loopback should not match sockets
6109 * bound specifically to loopback due to security implications,
6110 * see tcp_input() and in_pcblookup_listen().
6112 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6113 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6114 (s->nat_rule.ptr->action == PF_RDR ||
6115 s->nat_rule.ptr->action == PF_BINAT) &&
6116 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6117 m->m_flags |= M_SKIP_FIREWALL;
6119 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6120 !PACKET_LOOPED(&pd)) {
6122 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6123 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6124 if (ipfwtag != NULL) {
6125 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6126 ntohs(r->divert.port);
6127 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6132 m_tag_prepend(m, ipfwtag);
6133 if (m->m_flags & M_FASTFWD_OURS) {
6134 if (pd.pf_mtag == NULL &&
6135 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6137 REASON_SET(&reason, PFRES_MEMORY);
6139 DPFPRINTF(PF_DEBUG_MISC,
6140 ("pf: failed to allocate tag\n"));
6142 pd.pf_mtag->flags |=
6143 PF_FASTFWD_OURS_PRESENT;
6144 m->m_flags &= ~M_FASTFWD_OURS;
6147 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6152 /* XXX: ipfw has the same behaviour! */
6154 REASON_SET(&reason, PFRES_MEMORY);
6156 DPFPRINTF(PF_DEBUG_MISC,
6157 ("pf: failed to allocate divert tag\n"));
6164 if (s != NULL && s->nat_rule.ptr != NULL &&
6165 s->nat_rule.ptr->log & PF_LOG_ALL)
6166 lr = s->nat_rule.ptr;
6169 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6173 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6174 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6176 if (action == PF_PASS || r->action == PF_DROP) {
6177 dirndx = (dir == PF_OUT);
6178 r->packets[dirndx]++;
6179 r->bytes[dirndx] += pd.tot_len;
6181 a->packets[dirndx]++;
6182 a->bytes[dirndx] += pd.tot_len;
6185 if (s->nat_rule.ptr != NULL) {
6186 s->nat_rule.ptr->packets[dirndx]++;
6187 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6189 if (s->src_node != NULL) {
6190 s->src_node->packets[dirndx]++;
6191 s->src_node->bytes[dirndx] += pd.tot_len;
6193 if (s->nat_src_node != NULL) {
6194 s->nat_src_node->packets[dirndx]++;
6195 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6197 dirndx = (dir == s->direction) ? 0 : 1;
6198 s->packets[dirndx]++;
6199 s->bytes[dirndx] += pd.tot_len;
6202 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6203 if (nr != NULL && r == &V_pf_default_rule)
6205 if (tr->src.addr.type == PF_ADDR_TABLE)
6206 pfr_update_stats(tr->src.addr.p.tbl,
6207 (s == NULL) ? pd.src :
6208 &s->key[(s->direction == PF_IN)]->
6209 addr[(s->direction == PF_OUT)],
6210 pd.af, pd.tot_len, dir == PF_OUT,
6211 r->action == PF_PASS, tr->src.neg);
6212 if (tr->dst.addr.type == PF_ADDR_TABLE)
6213 pfr_update_stats(tr->dst.addr.p.tbl,
6214 (s == NULL) ? pd.dst :
6215 &s->key[(s->direction == PF_IN)]->
6216 addr[(s->direction == PF_IN)],
6217 pd.af, pd.tot_len, dir == PF_OUT,
6218 r->action == PF_PASS, tr->dst.neg);
6222 case PF_SYNPROXY_DROP:
6233 /* pf_route() returns unlocked. */
6235 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6249 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6251 struct pfi_kif *kif;
6252 u_short action, reason = 0, log = 0;
6253 struct mbuf *m = *m0, *n = NULL;
6255 struct ip6_hdr *h = NULL;
6256 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6257 struct pf_state *s = NULL;
6258 struct pf_ruleset *ruleset = NULL;
6260 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6264 if (!V_pf_status.running)
6267 memset(&pd, 0, sizeof(pd));
6268 pd.pf_mtag = pf_find_mtag(m);
6270 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6273 kif = (struct pfi_kif *)ifp->if_pf_kif;
6275 DPFPRINTF(PF_DEBUG_URGENT,
6276 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6279 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6282 if (m->m_flags & M_SKIP_FIREWALL)
6287 /* We do IP header normalization and packet reassembly here */
6288 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6292 m = *m0; /* pf_normalize messes with m0 */
6293 h = mtod(m, struct ip6_hdr *);
6297 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6298 * will do something bad, so drop the packet for now.
6300 if (htons(h->ip6_plen) == 0) {
6302 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6307 pd.src = (struct pf_addr *)&h->ip6_src;
6308 pd.dst = (struct pf_addr *)&h->ip6_dst;
6309 pd.sport = pd.dport = NULL;
6311 pd.proto_sum = NULL;
6313 pd.sidx = (dir == PF_IN) ? 0 : 1;
6314 pd.didx = (dir == PF_IN) ? 1 : 0;
6317 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6319 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6320 pd.proto = h->ip6_nxt;
6323 case IPPROTO_FRAGMENT:
6324 action = pf_test_fragment(&r, dir, kif, m, h,
6326 if (action == PF_DROP)
6327 REASON_SET(&reason, PFRES_FRAG);
6329 case IPPROTO_ROUTING: {
6330 struct ip6_rthdr rthdr;
6333 DPFPRINTF(PF_DEBUG_MISC,
6334 ("pf: IPv6 more than one rthdr\n"));
6336 REASON_SET(&reason, PFRES_IPOPTIONS);
6340 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6342 DPFPRINTF(PF_DEBUG_MISC,
6343 ("pf: IPv6 short rthdr\n"));
6345 REASON_SET(&reason, PFRES_SHORT);
6349 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6350 DPFPRINTF(PF_DEBUG_MISC,
6351 ("pf: IPv6 rthdr0\n"));
6353 REASON_SET(&reason, PFRES_IPOPTIONS);
6360 case IPPROTO_HOPOPTS:
6361 case IPPROTO_DSTOPTS: {
6362 /* get next header and header length */
6363 struct ip6_ext opt6;
6365 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6366 NULL, &reason, pd.af)) {
6367 DPFPRINTF(PF_DEBUG_MISC,
6368 ("pf: IPv6 short opt\n"));
6373 if (pd.proto == IPPROTO_AH)
6374 off += (opt6.ip6e_len + 2) * 4;
6376 off += (opt6.ip6e_len + 1) * 8;
6377 pd.proto = opt6.ip6e_nxt;
6378 /* goto the next header */
6385 } while (!terminal);
6387 /* if there's no routing header, use unmodified mbuf for checksumming */
6397 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6398 &action, &reason, AF_INET6)) {
6399 log = action != PF_PASS;
6402 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6403 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6404 if (action == PF_DROP)
6406 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6408 if (action == PF_PASS) {
6409 if (pfsync_update_state_ptr != NULL)
6410 pfsync_update_state_ptr(s);
6414 } else if (s == NULL)
6415 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6424 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6425 &action, &reason, AF_INET6)) {
6426 log = action != PF_PASS;
6429 if (uh.uh_dport == 0 ||
6430 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6431 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6433 REASON_SET(&reason, PFRES_SHORT);
6436 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6437 if (action == PF_PASS) {
6438 if (pfsync_update_state_ptr != NULL)
6439 pfsync_update_state_ptr(s);
6443 } else if (s == NULL)
6444 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6449 case IPPROTO_ICMP: {
6451 DPFPRINTF(PF_DEBUG_MISC,
6452 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6456 case IPPROTO_ICMPV6: {
6457 struct icmp6_hdr ih;
6460 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6461 &action, &reason, AF_INET6)) {
6462 log = action != PF_PASS;
6465 action = pf_test_state_icmp(&s, dir, kif,
6466 m, off, h, &pd, &reason);
6467 if (action == PF_PASS) {
6468 if (pfsync_update_state_ptr != NULL)
6469 pfsync_update_state_ptr(s);
6473 } else if (s == NULL)
6474 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6480 action = pf_test_state_other(&s, dir, kif, m, &pd);
6481 if (action == PF_PASS) {
6482 if (pfsync_update_state_ptr != NULL)
6483 pfsync_update_state_ptr(s);
6487 } else if (s == NULL)
6488 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6500 /* handle dangerous IPv6 extension headers. */
6501 if (action == PF_PASS && rh_cnt &&
6502 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6504 REASON_SET(&reason, PFRES_IPOPTIONS);
6506 DPFPRINTF(PF_DEBUG_MISC,
6507 ("pf: dropping packet with dangerous v6 headers\n"));
6510 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6512 REASON_SET(&reason, PFRES_MEMORY);
6514 if (r->rtableid >= 0)
6515 M_SETFIB(m, r->rtableid);
6517 if (r->scrub_flags & PFSTATE_SETPRIO) {
6518 if (pd.tos & IPTOS_LOWDELAY)
6520 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6522 REASON_SET(&reason, PFRES_MEMORY);
6524 DPFPRINTF(PF_DEBUG_MISC,
6525 ("pf: failed to allocate 802.1q mtag\n"));
6530 if (action == PF_PASS && r->qid) {
6531 if (pd.pf_mtag == NULL &&
6532 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6534 REASON_SET(&reason, PFRES_MEMORY);
6537 pd.pf_mtag->qid_hash = pf_state_hash(s);
6538 if (pd.tos & IPTOS_LOWDELAY)
6539 pd.pf_mtag->qid = r->pqid;
6541 pd.pf_mtag->qid = r->qid;
6542 /* Add hints for ecn. */
6543 pd.pf_mtag->hdr = h;
6548 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6549 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6550 (s->nat_rule.ptr->action == PF_RDR ||
6551 s->nat_rule.ptr->action == PF_BINAT) &&
6552 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6553 m->m_flags |= M_SKIP_FIREWALL;
6555 /* XXX: Anybody working on it?! */
6557 printf("pf: divert(9) is not supported for IPv6\n");
6562 if (s != NULL && s->nat_rule.ptr != NULL &&
6563 s->nat_rule.ptr->log & PF_LOG_ALL)
6564 lr = s->nat_rule.ptr;
6567 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6571 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6572 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6574 if (action == PF_PASS || r->action == PF_DROP) {
6575 dirndx = (dir == PF_OUT);
6576 r->packets[dirndx]++;
6577 r->bytes[dirndx] += pd.tot_len;
6579 a->packets[dirndx]++;
6580 a->bytes[dirndx] += pd.tot_len;
6583 if (s->nat_rule.ptr != NULL) {
6584 s->nat_rule.ptr->packets[dirndx]++;
6585 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6587 if (s->src_node != NULL) {
6588 s->src_node->packets[dirndx]++;
6589 s->src_node->bytes[dirndx] += pd.tot_len;
6591 if (s->nat_src_node != NULL) {
6592 s->nat_src_node->packets[dirndx]++;
6593 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6595 dirndx = (dir == s->direction) ? 0 : 1;
6596 s->packets[dirndx]++;
6597 s->bytes[dirndx] += pd.tot_len;
6600 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6601 if (nr != NULL && r == &V_pf_default_rule)
6603 if (tr->src.addr.type == PF_ADDR_TABLE)
6604 pfr_update_stats(tr->src.addr.p.tbl,
6605 (s == NULL) ? pd.src :
6606 &s->key[(s->direction == PF_IN)]->addr[0],
6607 pd.af, pd.tot_len, dir == PF_OUT,
6608 r->action == PF_PASS, tr->src.neg);
6609 if (tr->dst.addr.type == PF_ADDR_TABLE)
6610 pfr_update_stats(tr->dst.addr.p.tbl,
6611 (s == NULL) ? pd.dst :
6612 &s->key[(s->direction == PF_IN)]->addr[1],
6613 pd.af, pd.tot_len, dir == PF_OUT,
6614 r->action == PF_PASS, tr->dst.neg);
6618 case PF_SYNPROXY_DROP:
6629 /* pf_route6() returns unlocked. */
6631 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6640 /* If reassembled packet passed, create new fragments. */
6641 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6642 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6643 action = pf_refragment6(ifp, m0, mtag);