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[4]);
117 VNET_DEFINE(struct pf_palist, pf_pabuf);
118 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
119 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_active);
120 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
121 VNET_DEFINE(struct pf_altqqueue *, pf_altq_ifs_inactive);
122 VNET_DEFINE(struct pf_kstatus, pf_status);
124 VNET_DEFINE(u_int32_t, ticket_altqs_active);
125 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
126 VNET_DEFINE(int, altqs_inactive_open);
127 VNET_DEFINE(u_int32_t, ticket_pabuf);
129 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
130 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
131 VNET_DEFINE(u_char, pf_tcp_secret[16]);
132 #define V_pf_tcp_secret VNET(pf_tcp_secret)
133 VNET_DEFINE(int, pf_tcp_secret_init);
134 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
135 VNET_DEFINE(int, pf_tcp_iss_off);
136 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
137 VNET_DECLARE(int, pf_vnet_active);
138 #define V_pf_vnet_active VNET(pf_vnet_active)
140 VNET_DEFINE_STATIC(uint32_t, pf_purge_idx);
141 #define V_pf_purge_idx VNET(pf_purge_idx)
144 * Queue for pf_intr() sends.
146 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
147 struct pf_send_entry {
148 STAILQ_ENTRY(pf_send_entry) pfse_next;
163 STAILQ_HEAD(pf_send_head, pf_send_entry);
164 VNET_DEFINE_STATIC(struct pf_send_head, pf_sendqueue);
165 #define V_pf_sendqueue VNET(pf_sendqueue)
167 static struct mtx pf_sendqueue_mtx;
168 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
169 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
170 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
173 * Queue for pf_overload_task() tasks.
175 struct pf_overload_entry {
176 SLIST_ENTRY(pf_overload_entry) next;
180 struct pf_rule *rule;
183 SLIST_HEAD(pf_overload_head, pf_overload_entry);
184 VNET_DEFINE_STATIC(struct pf_overload_head, pf_overloadqueue);
185 #define V_pf_overloadqueue VNET(pf_overloadqueue)
186 VNET_DEFINE_STATIC(struct task, pf_overloadtask);
187 #define V_pf_overloadtask VNET(pf_overloadtask)
189 static struct mtx pf_overloadqueue_mtx;
190 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
191 "pf overload/flush queue", MTX_DEF);
192 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
193 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
195 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
196 struct mtx pf_unlnkdrules_mtx;
197 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
200 VNET_DEFINE_STATIC(uma_zone_t, pf_sources_z);
201 #define V_pf_sources_z VNET(pf_sources_z)
202 uma_zone_t pf_mtag_z;
203 VNET_DEFINE(uma_zone_t, pf_state_z);
204 VNET_DEFINE(uma_zone_t, pf_state_key_z);
206 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
207 #define PFID_CPUBITS 8
208 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
209 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
210 #define PFID_MAXID (~PFID_CPUMASK)
211 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
213 static void pf_src_tree_remove_state(struct pf_state *);
214 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
216 static void pf_add_threshold(struct pf_threshold *);
217 static int pf_check_threshold(struct pf_threshold *);
219 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
220 u_int16_t *, u_int16_t *, struct pf_addr *,
221 u_int16_t, u_int8_t, sa_family_t);
222 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
223 struct tcphdr *, struct pf_state_peer *);
224 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
225 struct pf_addr *, struct pf_addr *, u_int16_t,
226 u_int16_t *, u_int16_t *, u_int16_t *,
227 u_int16_t *, u_int8_t, sa_family_t);
228 static void pf_send_tcp(struct mbuf *,
229 const struct pf_rule *, sa_family_t,
230 const struct pf_addr *, const struct pf_addr *,
231 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
232 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
233 u_int16_t, struct ifnet *);
234 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
235 sa_family_t, struct pf_rule *);
236 static void pf_detach_state(struct pf_state *);
237 static int pf_state_key_attach(struct pf_state_key *,
238 struct pf_state_key *, struct pf_state *);
239 static void pf_state_key_detach(struct pf_state *, int);
240 static int pf_state_key_ctor(void *, int, void *, int);
241 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
242 static int pf_test_rule(struct pf_rule **, struct pf_state **,
243 int, struct pfi_kif *, struct mbuf *, int,
244 struct pf_pdesc *, struct pf_rule **,
245 struct pf_ruleset **, struct inpcb *);
246 static int pf_create_state(struct pf_rule *, struct pf_rule *,
247 struct pf_rule *, struct pf_pdesc *,
248 struct pf_src_node *, struct pf_state_key *,
249 struct pf_state_key *, struct mbuf *, int,
250 u_int16_t, u_int16_t, int *, struct pfi_kif *,
251 struct pf_state **, int, u_int16_t, u_int16_t,
253 static int pf_test_fragment(struct pf_rule **, int,
254 struct pfi_kif *, struct mbuf *, void *,
255 struct pf_pdesc *, struct pf_rule **,
256 struct pf_ruleset **);
257 static int pf_tcp_track_full(struct pf_state_peer *,
258 struct pf_state_peer *, struct pf_state **,
259 struct pfi_kif *, struct mbuf *, int,
260 struct pf_pdesc *, u_short *, int *);
261 static int pf_tcp_track_sloppy(struct pf_state_peer *,
262 struct pf_state_peer *, struct pf_state **,
263 struct pf_pdesc *, u_short *);
264 static int pf_test_state_tcp(struct pf_state **, int,
265 struct pfi_kif *, struct mbuf *, int,
266 void *, struct pf_pdesc *, u_short *);
267 static int pf_test_state_udp(struct pf_state **, int,
268 struct pfi_kif *, struct mbuf *, int,
269 void *, struct pf_pdesc *);
270 static int pf_test_state_icmp(struct pf_state **, int,
271 struct pfi_kif *, struct mbuf *, int,
272 void *, struct pf_pdesc *, u_short *);
273 static int pf_test_state_other(struct pf_state **, int,
274 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
275 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
277 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
279 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
281 static int pf_check_proto_cksum(struct mbuf *, int, int,
282 u_int8_t, sa_family_t);
283 static void pf_print_state_parts(struct pf_state *,
284 struct pf_state_key *, struct pf_state_key *);
285 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
286 struct pf_addr_wrap *);
287 static struct pf_state *pf_find_state(struct pfi_kif *,
288 struct pf_state_key_cmp *, u_int);
289 static int pf_src_connlimit(struct pf_state **);
290 static void pf_overload_task(void *v, int pending);
291 static int pf_insert_src_node(struct pf_src_node **,
292 struct pf_rule *, struct pf_addr *, sa_family_t);
293 static u_int pf_purge_expired_states(u_int, int);
294 static void pf_purge_unlinked_rules(void);
295 static int pf_mtag_uminit(void *, int, int);
296 static void pf_mtag_free(struct m_tag *);
298 static void pf_route(struct mbuf **, struct pf_rule *, int,
299 struct ifnet *, struct pf_state *,
300 struct pf_pdesc *, struct inpcb *);
303 static void pf_change_a6(struct pf_addr *, u_int16_t *,
304 struct pf_addr *, u_int8_t);
305 static void pf_route6(struct mbuf **, struct pf_rule *, int,
306 struct ifnet *, struct pf_state *,
307 struct pf_pdesc *, struct inpcb *);
310 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
312 extern int pf_end_threads;
313 extern struct proc *pf_purge_proc;
315 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
317 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
318 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
320 #define STATE_LOOKUP(i, k, d, s, pd) \
322 (s) = pf_find_state((i), (k), (d)); \
325 if (PACKET_LOOPED(pd)) \
327 if ((d) == PF_OUT && \
328 (((s)->rule.ptr->rt == PF_ROUTETO && \
329 (s)->rule.ptr->direction == PF_OUT) || \
330 ((s)->rule.ptr->rt == PF_REPLYTO && \
331 (s)->rule.ptr->direction == PF_IN)) && \
332 (s)->rt_kif != NULL && \
333 (s)->rt_kif != (i)) \
337 #define BOUND_IFACE(r, k) \
338 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
340 #define STATE_INC_COUNTERS(s) \
342 counter_u64_add(s->rule.ptr->states_cur, 1); \
343 counter_u64_add(s->rule.ptr->states_tot, 1); \
344 if (s->anchor.ptr != NULL) { \
345 counter_u64_add(s->anchor.ptr->states_cur, 1); \
346 counter_u64_add(s->anchor.ptr->states_tot, 1); \
348 if (s->nat_rule.ptr != NULL) { \
349 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
350 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
354 #define STATE_DEC_COUNTERS(s) \
356 if (s->nat_rule.ptr != NULL) \
357 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
358 if (s->anchor.ptr != NULL) \
359 counter_u64_add(s->anchor.ptr->states_cur, -1); \
360 counter_u64_add(s->rule.ptr->states_cur, -1); \
363 MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
364 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
365 VNET_DEFINE(struct pf_idhash *, pf_idhash);
366 VNET_DEFINE(struct pf_srchash *, pf_srchash);
368 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
371 u_long pf_srchashmask;
372 static u_long pf_hashsize;
373 static u_long pf_srchashsize;
374 u_long pf_ioctl_maxcount = 65535;
376 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
377 &pf_hashsize, 0, "Size of pf(4) states hashtable");
378 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
379 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
380 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RDTUN,
381 &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
383 VNET_DEFINE(void *, pf_swi_cookie);
385 VNET_DEFINE(uint32_t, pf_hashseed);
386 #define V_pf_hashseed VNET(pf_hashseed)
389 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
395 if (a->addr32[0] > b->addr32[0])
397 if (a->addr32[0] < b->addr32[0])
403 if (a->addr32[3] > b->addr32[3])
405 if (a->addr32[3] < b->addr32[3])
407 if (a->addr32[2] > b->addr32[2])
409 if (a->addr32[2] < b->addr32[2])
411 if (a->addr32[1] > b->addr32[1])
413 if (a->addr32[1] < b->addr32[1])
415 if (a->addr32[0] > b->addr32[0])
417 if (a->addr32[0] < b->addr32[0])
422 panic("%s: unknown address family %u", __func__, af);
427 static __inline uint32_t
428 pf_hashkey(struct pf_state_key *sk)
432 h = murmur3_32_hash32((uint32_t *)sk,
433 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
436 return (h & pf_hashmask);
439 static __inline uint32_t
440 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
446 h = murmur3_32_hash32((uint32_t *)&addr->v4,
447 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
450 h = murmur3_32_hash32((uint32_t *)&addr->v6,
451 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
454 panic("%s: unknown address family %u", __func__, af);
457 return (h & pf_srchashmask);
462 pf_state_hash(struct pf_state *s)
464 u_int32_t hv = (intptr_t)s / sizeof(*s);
466 hv ^= crc32(&s->src, sizeof(s->src));
467 hv ^= crc32(&s->dst, sizeof(s->dst));
476 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
481 dst->addr32[0] = src->addr32[0];
485 dst->addr32[0] = src->addr32[0];
486 dst->addr32[1] = src->addr32[1];
487 dst->addr32[2] = src->addr32[2];
488 dst->addr32[3] = src->addr32[3];
495 pf_init_threshold(struct pf_threshold *threshold,
496 u_int32_t limit, u_int32_t seconds)
498 threshold->limit = limit * PF_THRESHOLD_MULT;
499 threshold->seconds = seconds;
500 threshold->count = 0;
501 threshold->last = time_uptime;
505 pf_add_threshold(struct pf_threshold *threshold)
507 u_int32_t t = time_uptime, diff = t - threshold->last;
509 if (diff >= threshold->seconds)
510 threshold->count = 0;
512 threshold->count -= threshold->count * diff /
514 threshold->count += PF_THRESHOLD_MULT;
519 pf_check_threshold(struct pf_threshold *threshold)
521 return (threshold->count > threshold->limit);
525 pf_src_connlimit(struct pf_state **state)
527 struct pf_overload_entry *pfoe;
530 PF_STATE_LOCK_ASSERT(*state);
532 (*state)->src_node->conn++;
533 (*state)->src.tcp_est = 1;
534 pf_add_threshold(&(*state)->src_node->conn_rate);
536 if ((*state)->rule.ptr->max_src_conn &&
537 (*state)->rule.ptr->max_src_conn <
538 (*state)->src_node->conn) {
539 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
543 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
544 pf_check_threshold(&(*state)->src_node->conn_rate)) {
545 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
552 /* Kill this state. */
553 (*state)->timeout = PFTM_PURGE;
554 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
556 if ((*state)->rule.ptr->overload_tbl == NULL)
559 /* Schedule overloading and flushing task. */
560 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
562 return (1); /* too bad :( */
564 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
565 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
566 pfoe->rule = (*state)->rule.ptr;
567 pfoe->dir = (*state)->direction;
569 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
570 PF_OVERLOADQ_UNLOCK();
571 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
577 pf_overload_task(void *v, int pending)
579 struct pf_overload_head queue;
581 struct pf_overload_entry *pfoe, *pfoe1;
584 CURVNET_SET((struct vnet *)v);
587 queue = V_pf_overloadqueue;
588 SLIST_INIT(&V_pf_overloadqueue);
589 PF_OVERLOADQ_UNLOCK();
591 bzero(&p, sizeof(p));
592 SLIST_FOREACH(pfoe, &queue, next) {
593 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
594 if (V_pf_status.debug >= PF_DEBUG_MISC) {
595 printf("%s: blocking address ", __func__);
596 pf_print_host(&pfoe->addr, 0, pfoe->af);
600 p.pfra_af = pfoe->af;
605 p.pfra_ip4addr = pfoe->addr.v4;
611 p.pfra_ip6addr = pfoe->addr.v6;
617 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
622 * Remove those entries, that don't need flushing.
624 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
625 if (pfoe->rule->flush == 0) {
626 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
627 free(pfoe, M_PFTEMP);
630 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
632 /* If nothing to flush, return. */
633 if (SLIST_EMPTY(&queue)) {
638 for (int i = 0; i <= pf_hashmask; i++) {
639 struct pf_idhash *ih = &V_pf_idhash[i];
640 struct pf_state_key *sk;
644 LIST_FOREACH(s, &ih->states, entry) {
645 sk = s->key[PF_SK_WIRE];
646 SLIST_FOREACH(pfoe, &queue, next)
647 if (sk->af == pfoe->af &&
648 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
649 pfoe->rule == s->rule.ptr) &&
650 ((pfoe->dir == PF_OUT &&
651 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
652 (pfoe->dir == PF_IN &&
653 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
654 s->timeout = PFTM_PURGE;
655 s->src.state = s->dst.state = TCPS_CLOSED;
659 PF_HASHROW_UNLOCK(ih);
661 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
662 free(pfoe, M_PFTEMP);
663 if (V_pf_status.debug >= PF_DEBUG_MISC)
664 printf("%s: %u states killed", __func__, killed);
670 * Can return locked on failure, so that we can consistently
671 * allocate and insert a new one.
674 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
677 struct pf_srchash *sh;
678 struct pf_src_node *n;
680 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
682 sh = &V_pf_srchash[pf_hashsrc(src, af)];
684 LIST_FOREACH(n, &sh->nodes, entry)
685 if (n->rule.ptr == rule && n->af == af &&
686 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
687 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
691 PF_HASHROW_UNLOCK(sh);
692 } else if (returnlocked == 0)
693 PF_HASHROW_UNLOCK(sh);
699 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
700 struct pf_addr *src, sa_family_t af)
703 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
704 rule->rpool.opts & PF_POOL_STICKYADDR),
705 ("%s for non-tracking rule %p", __func__, rule));
708 *sn = pf_find_src_node(src, rule, af, 1);
711 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
713 PF_HASHROW_ASSERT(sh);
715 if (!rule->max_src_nodes ||
716 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
717 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
719 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
722 PF_HASHROW_UNLOCK(sh);
726 pf_init_threshold(&(*sn)->conn_rate,
727 rule->max_src_conn_rate.limit,
728 rule->max_src_conn_rate.seconds);
731 (*sn)->rule.ptr = rule;
732 PF_ACPY(&(*sn)->addr, src, af);
733 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
734 (*sn)->creation = time_uptime;
735 (*sn)->ruletype = rule->action;
737 if ((*sn)->rule.ptr != NULL)
738 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
739 PF_HASHROW_UNLOCK(sh);
740 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
742 if (rule->max_src_states &&
743 (*sn)->states >= rule->max_src_states) {
744 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
753 pf_unlink_src_node(struct pf_src_node *src)
756 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
757 LIST_REMOVE(src, entry);
759 counter_u64_add(src->rule.ptr->src_nodes, -1);
763 pf_free_src_nodes(struct pf_src_node_list *head)
765 struct pf_src_node *sn, *tmp;
768 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
769 uma_zfree(V_pf_sources_z, sn);
773 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
782 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
783 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
787 /* Per-vnet data storage structures initialization. */
791 struct pf_keyhash *kh;
792 struct pf_idhash *ih;
793 struct pf_srchash *sh;
796 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
797 pf_hashsize = PF_HASHSIZ;
798 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
799 pf_srchashsize = PF_SRCHASHSIZ;
801 V_pf_hashseed = arc4random();
803 /* States and state keys storage. */
804 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
805 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
806 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
807 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
808 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
810 V_pf_state_key_z = uma_zcreate("pf state keys",
811 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
814 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
815 M_PFHASH, M_NOWAIT | M_ZERO);
816 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
817 M_PFHASH, M_NOWAIT | M_ZERO);
818 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
819 printf("pf: Unable to allocate memory for "
820 "state_hashsize %lu.\n", pf_hashsize);
822 free(V_pf_keyhash, M_PFHASH);
823 free(V_pf_idhash, M_PFHASH);
825 pf_hashsize = PF_HASHSIZ;
826 V_pf_keyhash = mallocarray(pf_hashsize,
827 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
828 V_pf_idhash = mallocarray(pf_hashsize,
829 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
832 pf_hashmask = pf_hashsize - 1;
833 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
835 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
836 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
840 V_pf_sources_z = uma_zcreate("pf source nodes",
841 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
843 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
844 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
845 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
847 V_pf_srchash = mallocarray(pf_srchashsize,
848 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
849 if (V_pf_srchash == NULL) {
850 printf("pf: Unable to allocate memory for "
851 "source_hashsize %lu.\n", pf_srchashsize);
853 pf_srchashsize = PF_SRCHASHSIZ;
854 V_pf_srchash = mallocarray(pf_srchashsize,
855 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
858 pf_srchashmask = pf_srchashsize - 1;
859 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
860 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
863 TAILQ_INIT(&V_pf_altqs[0]);
864 TAILQ_INIT(&V_pf_altqs[1]);
865 TAILQ_INIT(&V_pf_altqs[2]);
866 TAILQ_INIT(&V_pf_altqs[3]);
867 TAILQ_INIT(&V_pf_pabuf);
868 V_pf_altqs_active = &V_pf_altqs[0];
869 V_pf_altq_ifs_active = &V_pf_altqs[1];
870 V_pf_altqs_inactive = &V_pf_altqs[2];
871 V_pf_altq_ifs_inactive = &V_pf_altqs[3];
873 /* Send & overload+flush queues. */
874 STAILQ_INIT(&V_pf_sendqueue);
875 SLIST_INIT(&V_pf_overloadqueue);
876 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
878 /* Unlinked, but may be referenced rules. */
879 TAILQ_INIT(&V_pf_unlinked_rules);
886 uma_zdestroy(pf_mtag_z);
892 struct pf_keyhash *kh;
893 struct pf_idhash *ih;
894 struct pf_srchash *sh;
895 struct pf_send_entry *pfse, *next;
898 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
900 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
902 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
904 mtx_destroy(&kh->lock);
905 mtx_destroy(&ih->lock);
907 free(V_pf_keyhash, M_PFHASH);
908 free(V_pf_idhash, M_PFHASH);
910 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
911 KASSERT(LIST_EMPTY(&sh->nodes),
912 ("%s: source node hash not empty", __func__));
913 mtx_destroy(&sh->lock);
915 free(V_pf_srchash, M_PFHASH);
917 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
918 m_freem(pfse->pfse_m);
919 free(pfse, M_PFTEMP);
922 uma_zdestroy(V_pf_sources_z);
923 uma_zdestroy(V_pf_state_z);
924 uma_zdestroy(V_pf_state_key_z);
928 pf_mtag_uminit(void *mem, int size, int how)
932 t = (struct m_tag *)mem;
933 t->m_tag_cookie = MTAG_ABI_COMPAT;
934 t->m_tag_id = PACKET_TAG_PF;
935 t->m_tag_len = sizeof(struct pf_mtag);
936 t->m_tag_free = pf_mtag_free;
942 pf_mtag_free(struct m_tag *t)
945 uma_zfree(pf_mtag_z, t);
949 pf_get_mtag(struct mbuf *m)
953 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
954 return ((struct pf_mtag *)(mtag + 1));
956 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
959 bzero(mtag + 1, sizeof(struct pf_mtag));
960 m_tag_prepend(m, mtag);
962 return ((struct pf_mtag *)(mtag + 1));
966 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
969 struct pf_keyhash *khs, *khw, *kh;
970 struct pf_state_key *sk, *cur;
971 struct pf_state *si, *olds = NULL;
974 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
975 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
976 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
979 * We need to lock hash slots of both keys. To avoid deadlock
980 * we always lock the slot with lower address first. Unlock order
983 * We also need to lock ID hash slot before dropping key
984 * locks. On success we return with ID hash slot locked.
988 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
989 PF_HASHROW_LOCK(khs);
991 khs = &V_pf_keyhash[pf_hashkey(sks)];
992 khw = &V_pf_keyhash[pf_hashkey(skw)];
994 PF_HASHROW_LOCK(khs);
995 } else if (khs < khw) {
996 PF_HASHROW_LOCK(khs);
997 PF_HASHROW_LOCK(khw);
999 PF_HASHROW_LOCK(khw);
1000 PF_HASHROW_LOCK(khs);
1004 #define KEYS_UNLOCK() do { \
1006 PF_HASHROW_UNLOCK(khs); \
1007 PF_HASHROW_UNLOCK(khw); \
1009 PF_HASHROW_UNLOCK(khs); \
1013 * First run: start with wire key.
1020 LIST_FOREACH(cur, &kh->keys, entry)
1021 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1025 /* Key exists. Check for same kif, if none, add to key. */
1026 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1027 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1029 PF_HASHROW_LOCK(ih);
1030 if (si->kif == s->kif &&
1031 si->direction == s->direction) {
1032 if (sk->proto == IPPROTO_TCP &&
1033 si->src.state >= TCPS_FIN_WAIT_2 &&
1034 si->dst.state >= TCPS_FIN_WAIT_2) {
1036 * New state matches an old >FIN_WAIT_2
1037 * state. We can't drop key hash locks,
1038 * thus we can't unlink it properly.
1040 * As a workaround we drop it into
1041 * TCPS_CLOSED state, schedule purge
1042 * ASAP and push it into the very end
1043 * of the slot TAILQ, so that it won't
1044 * conflict with our new state.
1046 si->src.state = si->dst.state =
1048 si->timeout = PFTM_PURGE;
1051 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1052 printf("pf: %s key attach "
1054 (idx == PF_SK_WIRE) ?
1057 pf_print_state_parts(s,
1058 (idx == PF_SK_WIRE) ?
1060 (idx == PF_SK_STACK) ?
1062 printf(", existing: ");
1063 pf_print_state_parts(si,
1064 (idx == PF_SK_WIRE) ?
1066 (idx == PF_SK_STACK) ?
1070 PF_HASHROW_UNLOCK(ih);
1072 uma_zfree(V_pf_state_key_z, sk);
1073 if (idx == PF_SK_STACK)
1075 return (EEXIST); /* collision! */
1078 PF_HASHROW_UNLOCK(ih);
1080 uma_zfree(V_pf_state_key_z, sk);
1083 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1088 /* List is sorted, if-bound states before floating. */
1089 if (s->kif == V_pfi_all)
1090 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1092 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1095 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1096 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1102 * Attach done. See how should we (or should not?)
1103 * attach a second key.
1106 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1110 } else if (sks != NULL) {
1112 * Continue attaching with stack key.
1124 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1125 ("%s failure", __func__));
1132 pf_detach_state(struct pf_state *s)
1134 struct pf_state_key *sks = s->key[PF_SK_STACK];
1135 struct pf_keyhash *kh;
1138 kh = &V_pf_keyhash[pf_hashkey(sks)];
1139 PF_HASHROW_LOCK(kh);
1140 if (s->key[PF_SK_STACK] != NULL)
1141 pf_state_key_detach(s, PF_SK_STACK);
1143 * If both point to same key, then we are done.
1145 if (sks == s->key[PF_SK_WIRE]) {
1146 pf_state_key_detach(s, PF_SK_WIRE);
1147 PF_HASHROW_UNLOCK(kh);
1150 PF_HASHROW_UNLOCK(kh);
1153 if (s->key[PF_SK_WIRE] != NULL) {
1154 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1155 PF_HASHROW_LOCK(kh);
1156 if (s->key[PF_SK_WIRE] != NULL)
1157 pf_state_key_detach(s, PF_SK_WIRE);
1158 PF_HASHROW_UNLOCK(kh);
1163 pf_state_key_detach(struct pf_state *s, int idx)
1165 struct pf_state_key *sk = s->key[idx];
1167 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1169 PF_HASHROW_ASSERT(kh);
1171 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1174 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1175 LIST_REMOVE(sk, entry);
1176 uma_zfree(V_pf_state_key_z, sk);
1181 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1183 struct pf_state_key *sk = mem;
1185 bzero(sk, sizeof(struct pf_state_key_cmp));
1186 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1187 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1192 struct pf_state_key *
1193 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1194 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1196 struct pf_state_key *sk;
1198 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1202 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1203 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1204 sk->port[pd->sidx] = sport;
1205 sk->port[pd->didx] = dport;
1206 sk->proto = pd->proto;
1212 struct pf_state_key *
1213 pf_state_key_clone(struct pf_state_key *orig)
1215 struct pf_state_key *sk;
1217 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1221 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1227 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1228 struct pf_state_key *sks, struct pf_state *s)
1230 struct pf_idhash *ih;
1231 struct pf_state *cur;
1234 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1235 ("%s: sks not pristine", __func__));
1236 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1237 ("%s: skw not pristine", __func__));
1238 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1242 if (s->id == 0 && s->creatorid == 0) {
1243 /* XXX: should be atomic, but probability of collision low */
1244 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1245 V_pf_stateid[curcpu] = 1;
1246 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1247 s->id = htobe64(s->id);
1248 s->creatorid = V_pf_status.hostid;
1251 /* Returns with ID locked on success. */
1252 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1255 ih = &V_pf_idhash[PF_IDHASH(s)];
1256 PF_HASHROW_ASSERT(ih);
1257 LIST_FOREACH(cur, &ih->states, entry)
1258 if (cur->id == s->id && cur->creatorid == s->creatorid)
1262 PF_HASHROW_UNLOCK(ih);
1263 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1264 printf("pf: state ID collision: "
1265 "id: %016llx creatorid: %08x\n",
1266 (unsigned long long)be64toh(s->id),
1267 ntohl(s->creatorid));
1272 LIST_INSERT_HEAD(&ih->states, s, entry);
1273 /* One for keys, one for ID hash. */
1274 refcount_init(&s->refs, 2);
1276 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1277 if (V_pfsync_insert_state_ptr != NULL)
1278 V_pfsync_insert_state_ptr(s);
1280 /* Returns locked. */
1285 * Find state by ID: returns with locked row on success.
1288 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1290 struct pf_idhash *ih;
1293 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1295 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1297 PF_HASHROW_LOCK(ih);
1298 LIST_FOREACH(s, &ih->states, entry)
1299 if (s->id == id && s->creatorid == creatorid)
1303 PF_HASHROW_UNLOCK(ih);
1309 * Find state by key.
1310 * Returns with ID hash slot locked on success.
1312 static struct pf_state *
1313 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1315 struct pf_keyhash *kh;
1316 struct pf_state_key *sk;
1320 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1322 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1324 PF_HASHROW_LOCK(kh);
1325 LIST_FOREACH(sk, &kh->keys, entry)
1326 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1329 PF_HASHROW_UNLOCK(kh);
1333 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1335 /* List is sorted, if-bound states before floating ones. */
1336 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1337 if (s->kif == V_pfi_all || s->kif == kif) {
1339 PF_HASHROW_UNLOCK(kh);
1340 if (s->timeout >= PFTM_MAX) {
1342 * State is either being processed by
1343 * pf_unlink_state() in an other thread, or
1344 * is scheduled for immediate expiry.
1351 PF_HASHROW_UNLOCK(kh);
1357 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1359 struct pf_keyhash *kh;
1360 struct pf_state_key *sk;
1361 struct pf_state *s, *ret = NULL;
1364 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1366 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1368 PF_HASHROW_LOCK(kh);
1369 LIST_FOREACH(sk, &kh->keys, entry)
1370 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1373 PF_HASHROW_UNLOCK(kh);
1388 panic("%s: dir %u", __func__, dir);
1391 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1393 PF_HASHROW_UNLOCK(kh);
1407 PF_HASHROW_UNLOCK(kh);
1412 /* END state table stuff */
1415 pf_send(struct pf_send_entry *pfse)
1419 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1421 swi_sched(V_pf_swi_cookie, 0);
1427 struct pf_send_head queue;
1428 struct pf_send_entry *pfse, *next;
1430 CURVNET_SET((struct vnet *)v);
1433 queue = V_pf_sendqueue;
1434 STAILQ_INIT(&V_pf_sendqueue);
1437 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1438 switch (pfse->pfse_type) {
1441 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1444 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1445 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1450 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1454 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1455 pfse->icmpopts.code, pfse->icmpopts.mtu);
1459 panic("%s: unknown type", __func__);
1461 free(pfse, M_PFTEMP);
1467 pf_purge_thread(void *unused __unused)
1469 VNET_ITERATOR_DECL(vnet_iter);
1471 sx_xlock(&pf_end_lock);
1472 while (pf_end_threads == 0) {
1473 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1476 VNET_FOREACH(vnet_iter) {
1477 CURVNET_SET(vnet_iter);
1480 /* Wait until V_pf_default_rule is initialized. */
1481 if (V_pf_vnet_active == 0) {
1487 * Process 1/interval fraction of the state
1491 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1492 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1495 * Purge other expired types every
1496 * PFTM_INTERVAL seconds.
1498 if (V_pf_purge_idx == 0) {
1500 * Order is important:
1501 * - states and src nodes reference rules
1502 * - states and rules reference kifs
1504 pf_purge_expired_fragments();
1505 pf_purge_expired_src_nodes();
1506 pf_purge_unlinked_rules();
1511 VNET_LIST_RUNLOCK();
1515 sx_xunlock(&pf_end_lock);
1520 pf_unload_vnet_purge(void)
1524 * To cleanse up all kifs and rules we need
1525 * two runs: first one clears reference flags,
1526 * then pf_purge_expired_states() doesn't
1527 * raise them, and then second run frees.
1529 pf_purge_unlinked_rules();
1533 * Now purge everything.
1535 pf_purge_expired_states(0, pf_hashmask);
1536 pf_purge_fragments(UINT_MAX);
1537 pf_purge_expired_src_nodes();
1540 * Now all kifs & rules should be unreferenced,
1541 * thus should be successfully freed.
1543 pf_purge_unlinked_rules();
1549 pf_state_expires(const struct pf_state *state)
1556 /* handle all PFTM_* > PFTM_MAX here */
1557 if (state->timeout == PFTM_PURGE)
1558 return (time_uptime);
1559 KASSERT(state->timeout != PFTM_UNLINKED,
1560 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1561 KASSERT((state->timeout < PFTM_MAX),
1562 ("pf_state_expires: timeout > PFTM_MAX"));
1563 timeout = state->rule.ptr->timeout[state->timeout];
1565 timeout = V_pf_default_rule.timeout[state->timeout];
1566 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1567 if (start && state->rule.ptr != &V_pf_default_rule) {
1568 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1569 states = counter_u64_fetch(state->rule.ptr->states_cur);
1571 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1572 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1573 states = V_pf_status.states;
1575 if (end && states > start && start < end) {
1577 timeout = (u_int64_t)timeout * (end - states) /
1579 return (state->expire + timeout);
1582 return (time_uptime);
1584 return (state->expire + timeout);
1588 pf_purge_expired_src_nodes()
1590 struct pf_src_node_list freelist;
1591 struct pf_srchash *sh;
1592 struct pf_src_node *cur, *next;
1595 LIST_INIT(&freelist);
1596 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1597 PF_HASHROW_LOCK(sh);
1598 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1599 if (cur->states == 0 && cur->expire <= time_uptime) {
1600 pf_unlink_src_node(cur);
1601 LIST_INSERT_HEAD(&freelist, cur, entry);
1602 } else if (cur->rule.ptr != NULL)
1603 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1604 PF_HASHROW_UNLOCK(sh);
1607 pf_free_src_nodes(&freelist);
1609 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1613 pf_src_tree_remove_state(struct pf_state *s)
1615 struct pf_src_node *sn;
1616 struct pf_srchash *sh;
1619 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1620 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1621 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1623 if (s->src_node != NULL) {
1625 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1626 PF_HASHROW_LOCK(sh);
1629 if (--sn->states == 0)
1630 sn->expire = time_uptime + timeout;
1631 PF_HASHROW_UNLOCK(sh);
1633 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1634 sn = s->nat_src_node;
1635 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1636 PF_HASHROW_LOCK(sh);
1637 if (--sn->states == 0)
1638 sn->expire = time_uptime + timeout;
1639 PF_HASHROW_UNLOCK(sh);
1641 s->src_node = s->nat_src_node = NULL;
1645 * Unlink and potentilly free a state. Function may be
1646 * called with ID hash row locked, but always returns
1647 * unlocked, since it needs to go through key hash locking.
1650 pf_unlink_state(struct pf_state *s, u_int flags)
1652 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1654 if ((flags & PF_ENTER_LOCKED) == 0)
1655 PF_HASHROW_LOCK(ih);
1657 PF_HASHROW_ASSERT(ih);
1659 if (s->timeout == PFTM_UNLINKED) {
1661 * State is being processed
1662 * by pf_unlink_state() in
1665 PF_HASHROW_UNLOCK(ih);
1666 return (0); /* XXXGL: undefined actually */
1669 if (s->src.state == PF_TCPS_PROXY_DST) {
1670 /* XXX wire key the right one? */
1671 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1672 &s->key[PF_SK_WIRE]->addr[1],
1673 &s->key[PF_SK_WIRE]->addr[0],
1674 s->key[PF_SK_WIRE]->port[1],
1675 s->key[PF_SK_WIRE]->port[0],
1676 s->src.seqhi, s->src.seqlo + 1,
1677 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1680 LIST_REMOVE(s, entry);
1681 pf_src_tree_remove_state(s);
1683 if (V_pfsync_delete_state_ptr != NULL)
1684 V_pfsync_delete_state_ptr(s);
1686 STATE_DEC_COUNTERS(s);
1688 s->timeout = PFTM_UNLINKED;
1690 PF_HASHROW_UNLOCK(ih);
1693 /* pf_state_insert() initialises refs to 2, so we can never release the
1694 * last reference here, only in pf_release_state(). */
1695 (void)refcount_release(&s->refs);
1697 return (pf_release_state(s));
1701 pf_free_state(struct pf_state *cur)
1704 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1705 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1708 pf_normalize_tcp_cleanup(cur);
1709 uma_zfree(V_pf_state_z, cur);
1710 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1714 * Called only from pf_purge_thread(), thus serialized.
1717 pf_purge_expired_states(u_int i, int maxcheck)
1719 struct pf_idhash *ih;
1722 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1725 * Go through hash and unlink states that expire now.
1727 while (maxcheck > 0) {
1729 ih = &V_pf_idhash[i];
1731 /* only take the lock if we expect to do work */
1732 if (!LIST_EMPTY(&ih->states)) {
1734 PF_HASHROW_LOCK(ih);
1735 LIST_FOREACH(s, &ih->states, entry) {
1736 if (pf_state_expires(s) <= time_uptime) {
1737 V_pf_status.states -=
1738 pf_unlink_state(s, PF_ENTER_LOCKED);
1741 s->rule.ptr->rule_flag |= PFRULE_REFS;
1742 if (s->nat_rule.ptr != NULL)
1743 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1744 if (s->anchor.ptr != NULL)
1745 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1746 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1748 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1750 PF_HASHROW_UNLOCK(ih);
1753 /* Return when we hit end of hash. */
1754 if (++i > pf_hashmask) {
1755 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1762 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1768 pf_purge_unlinked_rules()
1770 struct pf_rulequeue tmpq;
1771 struct pf_rule *r, *r1;
1774 * If we have overloading task pending, then we'd
1775 * better skip purging this time. There is a tiny
1776 * probability that overloading task references
1777 * an already unlinked rule.
1779 PF_OVERLOADQ_LOCK();
1780 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1781 PF_OVERLOADQ_UNLOCK();
1784 PF_OVERLOADQ_UNLOCK();
1787 * Do naive mark-and-sweep garbage collecting of old rules.
1788 * Reference flag is raised by pf_purge_expired_states()
1789 * and pf_purge_expired_src_nodes().
1791 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1792 * use a temporary queue.
1795 PF_UNLNKDRULES_LOCK();
1796 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1797 if (!(r->rule_flag & PFRULE_REFS)) {
1798 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1799 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1801 r->rule_flag &= ~PFRULE_REFS;
1803 PF_UNLNKDRULES_UNLOCK();
1805 if (!TAILQ_EMPTY(&tmpq)) {
1807 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1808 TAILQ_REMOVE(&tmpq, r, entries);
1816 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1821 u_int32_t a = ntohl(addr->addr32[0]);
1822 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1834 u_int8_t i, curstart, curend, maxstart, maxend;
1835 curstart = curend = maxstart = maxend = 255;
1836 for (i = 0; i < 8; i++) {
1837 if (!addr->addr16[i]) {
1838 if (curstart == 255)
1842 if ((curend - curstart) >
1843 (maxend - maxstart)) {
1844 maxstart = curstart;
1847 curstart = curend = 255;
1850 if ((curend - curstart) >
1851 (maxend - maxstart)) {
1852 maxstart = curstart;
1855 for (i = 0; i < 8; i++) {
1856 if (i >= maxstart && i <= maxend) {
1862 b = ntohs(addr->addr16[i]);
1879 pf_print_state(struct pf_state *s)
1881 pf_print_state_parts(s, NULL, NULL);
1885 pf_print_state_parts(struct pf_state *s,
1886 struct pf_state_key *skwp, struct pf_state_key *sksp)
1888 struct pf_state_key *skw, *sks;
1889 u_int8_t proto, dir;
1891 /* Do our best to fill these, but they're skipped if NULL */
1892 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1893 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1894 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1895 dir = s ? s->direction : 0;
1913 case IPPROTO_ICMPV6:
1917 printf("%u", proto);
1930 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1932 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1937 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1939 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1944 if (proto == IPPROTO_TCP) {
1945 printf(" [lo=%u high=%u win=%u modulator=%u",
1946 s->src.seqlo, s->src.seqhi,
1947 s->src.max_win, s->src.seqdiff);
1948 if (s->src.wscale && s->dst.wscale)
1949 printf(" wscale=%u",
1950 s->src.wscale & PF_WSCALE_MASK);
1952 printf(" [lo=%u high=%u win=%u modulator=%u",
1953 s->dst.seqlo, s->dst.seqhi,
1954 s->dst.max_win, s->dst.seqdiff);
1955 if (s->src.wscale && s->dst.wscale)
1956 printf(" wscale=%u",
1957 s->dst.wscale & PF_WSCALE_MASK);
1960 printf(" %u:%u", s->src.state, s->dst.state);
1965 pf_print_flags(u_int8_t f)
1987 #define PF_SET_SKIP_STEPS(i) \
1989 while (head[i] != cur) { \
1990 head[i]->skip[i].ptr = cur; \
1991 head[i] = TAILQ_NEXT(head[i], entries); \
1996 pf_calc_skip_steps(struct pf_rulequeue *rules)
1998 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
2001 cur = TAILQ_FIRST(rules);
2003 for (i = 0; i < PF_SKIP_COUNT; ++i)
2005 while (cur != NULL) {
2007 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
2008 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
2009 if (cur->direction != prev->direction)
2010 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
2011 if (cur->af != prev->af)
2012 PF_SET_SKIP_STEPS(PF_SKIP_AF);
2013 if (cur->proto != prev->proto)
2014 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2015 if (cur->src.neg != prev->src.neg ||
2016 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2017 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2018 if (cur->src.port[0] != prev->src.port[0] ||
2019 cur->src.port[1] != prev->src.port[1] ||
2020 cur->src.port_op != prev->src.port_op)
2021 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2022 if (cur->dst.neg != prev->dst.neg ||
2023 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2024 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2025 if (cur->dst.port[0] != prev->dst.port[0] ||
2026 cur->dst.port[1] != prev->dst.port[1] ||
2027 cur->dst.port_op != prev->dst.port_op)
2028 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2031 cur = TAILQ_NEXT(cur, entries);
2033 for (i = 0; i < PF_SKIP_COUNT; ++i)
2034 PF_SET_SKIP_STEPS(i);
2038 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2040 if (aw1->type != aw2->type)
2042 switch (aw1->type) {
2043 case PF_ADDR_ADDRMASK:
2045 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2047 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2050 case PF_ADDR_DYNIFTL:
2051 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2052 case PF_ADDR_NOROUTE:
2053 case PF_ADDR_URPFFAILED:
2056 return (aw1->p.tbl != aw2->p.tbl);
2058 printf("invalid address type: %d\n", aw1->type);
2064 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2065 * header isn't always a full checksum. In some cases (i.e. output) it's a
2066 * pseudo-header checksum, which is a partial checksum over src/dst IP
2067 * addresses, protocol number and length.
2069 * That means we have the following cases:
2070 * * Input or forwarding: we don't have TSO, the checksum fields are full
2071 * checksums, we need to update the checksum whenever we change anything.
2072 * * Output (i.e. the checksum is a pseudo-header checksum):
2073 * x The field being updated is src/dst address or affects the length of
2074 * the packet. We need to update the pseudo-header checksum (note that this
2075 * checksum is not ones' complement).
2076 * x Some other field is being modified (e.g. src/dst port numbers): We
2077 * don't have to update anything.
2080 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2086 l = cksum + old - new;
2087 l = (l >> 16) + (l & 65535);
2095 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2096 u_int16_t new, u_int8_t udp)
2098 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2101 return (pf_cksum_fixup(cksum, old, new, udp));
2105 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2106 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2112 PF_ACPY(&ao, a, af);
2115 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2123 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2124 ao.addr16[0], an->addr16[0], 0),
2125 ao.addr16[1], an->addr16[1], 0);
2128 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2129 ao.addr16[0], an->addr16[0], u),
2130 ao.addr16[1], an->addr16[1], u);
2132 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2137 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2138 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2139 pf_cksum_fixup(pf_cksum_fixup(*pc,
2140 ao.addr16[0], an->addr16[0], u),
2141 ao.addr16[1], an->addr16[1], u),
2142 ao.addr16[2], an->addr16[2], u),
2143 ao.addr16[3], an->addr16[3], u),
2144 ao.addr16[4], an->addr16[4], u),
2145 ao.addr16[5], an->addr16[5], u),
2146 ao.addr16[6], an->addr16[6], u),
2147 ao.addr16[7], an->addr16[7], u);
2149 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2154 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2155 CSUM_DELAY_DATA_IPV6)) {
2162 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2164 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2168 memcpy(&ao, a, sizeof(ao));
2169 memcpy(a, &an, sizeof(u_int32_t));
2170 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2171 ao % 65536, an % 65536, u);
2175 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2179 memcpy(&ao, a, sizeof(ao));
2180 memcpy(a, &an, sizeof(u_int32_t));
2182 *c = pf_proto_cksum_fixup(m,
2183 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2184 ao % 65536, an % 65536, udp);
2189 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2193 PF_ACPY(&ao, a, AF_INET6);
2194 PF_ACPY(a, an, AF_INET6);
2196 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2197 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2198 pf_cksum_fixup(pf_cksum_fixup(*c,
2199 ao.addr16[0], an->addr16[0], u),
2200 ao.addr16[1], an->addr16[1], u),
2201 ao.addr16[2], an->addr16[2], u),
2202 ao.addr16[3], an->addr16[3], u),
2203 ao.addr16[4], an->addr16[4], u),
2204 ao.addr16[5], an->addr16[5], u),
2205 ao.addr16[6], an->addr16[6], u),
2206 ao.addr16[7], an->addr16[7], u);
2211 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2212 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2213 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2215 struct pf_addr oia, ooa;
2217 PF_ACPY(&oia, ia, af);
2219 PF_ACPY(&ooa, oa, af);
2221 /* Change inner protocol port, fix inner protocol checksum. */
2223 u_int16_t oip = *ip;
2230 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2231 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2233 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2235 /* Change inner ip address, fix inner ip and icmp checksums. */
2236 PF_ACPY(ia, na, af);
2240 u_int32_t oh2c = *h2c;
2242 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2243 oia.addr16[0], ia->addr16[0], 0),
2244 oia.addr16[1], ia->addr16[1], 0);
2245 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2246 oia.addr16[0], ia->addr16[0], 0),
2247 oia.addr16[1], ia->addr16[1], 0);
2248 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2254 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2255 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2256 pf_cksum_fixup(pf_cksum_fixup(*ic,
2257 oia.addr16[0], ia->addr16[0], u),
2258 oia.addr16[1], ia->addr16[1], u),
2259 oia.addr16[2], ia->addr16[2], u),
2260 oia.addr16[3], ia->addr16[3], u),
2261 oia.addr16[4], ia->addr16[4], u),
2262 oia.addr16[5], ia->addr16[5], u),
2263 oia.addr16[6], ia->addr16[6], u),
2264 oia.addr16[7], ia->addr16[7], u);
2268 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2270 PF_ACPY(oa, na, af);
2274 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2275 ooa.addr16[0], oa->addr16[0], 0),
2276 ooa.addr16[1], oa->addr16[1], 0);
2281 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2282 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2283 pf_cksum_fixup(pf_cksum_fixup(*ic,
2284 ooa.addr16[0], oa->addr16[0], u),
2285 ooa.addr16[1], oa->addr16[1], u),
2286 ooa.addr16[2], oa->addr16[2], u),
2287 ooa.addr16[3], oa->addr16[3], u),
2288 ooa.addr16[4], oa->addr16[4], u),
2289 ooa.addr16[5], oa->addr16[5], u),
2290 ooa.addr16[6], oa->addr16[6], u),
2291 ooa.addr16[7], oa->addr16[7], u);
2300 * Need to modulate the sequence numbers in the TCP SACK option
2301 * (credits to Krzysztof Pfaff for report and patch)
2304 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2305 struct tcphdr *th, struct pf_state_peer *dst)
2307 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2308 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2309 int copyback = 0, i, olen;
2310 struct sackblk sack;
2312 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2313 if (hlen < TCPOLEN_SACKLEN ||
2314 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2317 while (hlen >= TCPOLEN_SACKLEN) {
2320 case TCPOPT_EOL: /* FALLTHROUGH */
2328 if (olen >= TCPOLEN_SACKLEN) {
2329 for (i = 2; i + TCPOLEN_SACK <= olen;
2330 i += TCPOLEN_SACK) {
2331 memcpy(&sack, &opt[i], sizeof(sack));
2332 pf_change_proto_a(m, &sack.start, &th->th_sum,
2333 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2334 pf_change_proto_a(m, &sack.end, &th->th_sum,
2335 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2336 memcpy(&opt[i], &sack, sizeof(sack));
2350 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2355 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2356 const struct pf_addr *saddr, const struct pf_addr *daddr,
2357 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2358 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2359 u_int16_t rtag, struct ifnet *ifp)
2361 struct pf_send_entry *pfse;
2365 struct ip *h = NULL;
2368 struct ip6_hdr *h6 = NULL;
2372 struct pf_mtag *pf_mtag;
2377 /* maximum segment size tcp option */
2378 tlen = sizeof(struct tcphdr);
2385 len = sizeof(struct ip) + tlen;
2390 len = sizeof(struct ip6_hdr) + tlen;
2394 panic("%s: unsupported af %d", __func__, af);
2397 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2398 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2401 m = m_gethdr(M_NOWAIT, MT_DATA);
2403 free(pfse, M_PFTEMP);
2407 mac_netinet_firewall_send(m);
2409 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2410 free(pfse, M_PFTEMP);
2415 m->m_flags |= M_SKIP_FIREWALL;
2416 pf_mtag->tag = rtag;
2418 if (r != NULL && r->rtableid >= 0)
2419 M_SETFIB(m, r->rtableid);
2422 if (r != NULL && r->qid) {
2423 pf_mtag->qid = r->qid;
2425 /* add hints for ecn */
2426 pf_mtag->hdr = mtod(m, struct ip *);
2429 m->m_data += max_linkhdr;
2430 m->m_pkthdr.len = m->m_len = len;
2431 m->m_pkthdr.rcvif = NULL;
2432 bzero(m->m_data, len);
2436 h = mtod(m, struct ip *);
2438 /* IP header fields included in the TCP checksum */
2439 h->ip_p = IPPROTO_TCP;
2440 h->ip_len = htons(tlen);
2441 h->ip_src.s_addr = saddr->v4.s_addr;
2442 h->ip_dst.s_addr = daddr->v4.s_addr;
2444 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2449 h6 = mtod(m, struct ip6_hdr *);
2451 /* IP header fields included in the TCP checksum */
2452 h6->ip6_nxt = IPPROTO_TCP;
2453 h6->ip6_plen = htons(tlen);
2454 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2455 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2457 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2463 th->th_sport = sport;
2464 th->th_dport = dport;
2465 th->th_seq = htonl(seq);
2466 th->th_ack = htonl(ack);
2467 th->th_off = tlen >> 2;
2468 th->th_flags = flags;
2469 th->th_win = htons(win);
2472 opt = (char *)(th + 1);
2473 opt[0] = TCPOPT_MAXSEG;
2476 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2483 th->th_sum = in_cksum(m, len);
2485 /* Finish the IP header */
2487 h->ip_hl = sizeof(*h) >> 2;
2488 h->ip_tos = IPTOS_LOWDELAY;
2489 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2490 h->ip_len = htons(len);
2491 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2494 pfse->pfse_type = PFSE_IP;
2500 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2501 sizeof(struct ip6_hdr), tlen);
2503 h6->ip6_vfc |= IPV6_VERSION;
2504 h6->ip6_hlim = IPV6_DEFHLIM;
2506 pfse->pfse_type = PFSE_IP6;
2515 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2516 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2517 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2520 struct pf_addr * const saddr = pd->src;
2521 struct pf_addr * const daddr = pd->dst;
2522 sa_family_t af = pd->af;
2524 /* undo NAT changes, if they have taken place */
2526 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2527 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2529 *pd->sport = sk->port[pd->sidx];
2531 *pd->dport = sk->port[pd->didx];
2533 *pd->proto_sum = bproto_sum;
2535 *pd->ip_sum = bip_sum;
2536 m_copyback(m, off, hdrlen, pd->hdr.any);
2538 if (pd->proto == IPPROTO_TCP &&
2539 ((r->rule_flag & PFRULE_RETURNRST) ||
2540 (r->rule_flag & PFRULE_RETURN)) &&
2541 !(th->th_flags & TH_RST)) {
2542 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2554 h4 = mtod(m, struct ip *);
2555 len = ntohs(h4->ip_len) - off;
2560 h6 = mtod(m, struct ip6_hdr *);
2561 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2566 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2567 REASON_SET(reason, PFRES_PROTCKSUM);
2569 if (th->th_flags & TH_SYN)
2571 if (th->th_flags & TH_FIN)
2573 pf_send_tcp(m, r, af, pd->dst,
2574 pd->src, th->th_dport, th->th_sport,
2575 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2576 r->return_ttl, 1, 0, kif->pfik_ifp);
2578 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2580 pf_send_icmp(m, r->return_icmp >> 8,
2581 r->return_icmp & 255, af, r);
2582 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2584 pf_send_icmp(m, r->return_icmp6 >> 8,
2585 r->return_icmp6 & 255, af, r);
2590 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2594 KASSERT(prio <= PF_PRIO_MAX,
2595 ("%s with invalid pcp", __func__));
2597 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2599 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2600 sizeof(uint8_t), M_NOWAIT);
2603 m_tag_prepend(m, mtag);
2606 *(uint8_t *)(mtag + 1) = prio;
2611 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2616 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2620 if (prio == PF_PRIO_ZERO)
2623 mpcp = *(uint8_t *)(mtag + 1);
2625 return (mpcp == prio);
2629 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2632 struct pf_send_entry *pfse;
2634 struct pf_mtag *pf_mtag;
2636 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2637 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2641 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2642 free(pfse, M_PFTEMP);
2646 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2647 free(pfse, M_PFTEMP);
2651 m0->m_flags |= M_SKIP_FIREWALL;
2653 if (r->rtableid >= 0)
2654 M_SETFIB(m0, r->rtableid);
2658 pf_mtag->qid = r->qid;
2659 /* add hints for ecn */
2660 pf_mtag->hdr = mtod(m0, struct ip *);
2667 pfse->pfse_type = PFSE_ICMP;
2672 pfse->pfse_type = PFSE_ICMP6;
2677 pfse->icmpopts.type = type;
2678 pfse->icmpopts.code = code;
2683 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2684 * If n is 0, they match if they are equal. If n is != 0, they match if they
2688 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2689 struct pf_addr *b, sa_family_t af)
2696 if ((a->addr32[0] & m->addr32[0]) ==
2697 (b->addr32[0] & m->addr32[0]))
2703 if (((a->addr32[0] & m->addr32[0]) ==
2704 (b->addr32[0] & m->addr32[0])) &&
2705 ((a->addr32[1] & m->addr32[1]) ==
2706 (b->addr32[1] & m->addr32[1])) &&
2707 ((a->addr32[2] & m->addr32[2]) ==
2708 (b->addr32[2] & m->addr32[2])) &&
2709 ((a->addr32[3] & m->addr32[3]) ==
2710 (b->addr32[3] & m->addr32[3])))
2729 * Return 1 if b <= a <= e, otherwise return 0.
2732 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2733 struct pf_addr *a, sa_family_t af)
2738 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2739 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2748 for (i = 0; i < 4; ++i)
2749 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2751 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2754 for (i = 0; i < 4; ++i)
2755 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2757 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2767 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2771 return ((p > a1) && (p < a2));
2773 return ((p < a1) || (p > a2));
2775 return ((p >= a1) && (p <= a2));
2789 return (0); /* never reached */
2793 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2798 return (pf_match(op, a1, a2, p));
2802 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2804 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2806 return (pf_match(op, a1, a2, u));
2810 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2812 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2814 return (pf_match(op, a1, a2, g));
2818 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2823 return ((!r->match_tag_not && r->match_tag == *tag) ||
2824 (r->match_tag_not && r->match_tag != *tag));
2828 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2831 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2833 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2836 pd->pf_mtag->tag = tag;
2841 #define PF_ANCHOR_STACKSIZE 32
2842 struct pf_anchor_stackframe {
2843 struct pf_ruleset *rs;
2844 struct pf_rule *r; /* XXX: + match bit */
2845 struct pf_anchor *child;
2849 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2851 #define PF_ANCHORSTACK_MATCH 0x00000001
2852 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2854 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2855 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2856 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2857 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2858 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2862 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2863 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2866 struct pf_anchor_stackframe *f;
2872 if (*depth >= PF_ANCHOR_STACKSIZE) {
2873 printf("%s: anchor stack overflow on %s\n",
2874 __func__, (*r)->anchor->name);
2875 *r = TAILQ_NEXT(*r, entries);
2877 } else if (*depth == 0 && a != NULL)
2879 f = stack + (*depth)++;
2882 if ((*r)->anchor_wildcard) {
2883 struct pf_anchor_node *parent = &(*r)->anchor->children;
2885 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2889 *rs = &f->child->ruleset;
2892 *rs = &(*r)->anchor->ruleset;
2894 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2898 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2899 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2902 struct pf_anchor_stackframe *f;
2911 f = stack + *depth - 1;
2912 fr = PF_ANCHOR_RULE(f);
2913 if (f->child != NULL) {
2914 struct pf_anchor_node *parent;
2917 * This block traverses through
2918 * a wildcard anchor.
2920 parent = &fr->anchor->children;
2921 if (match != NULL && *match) {
2923 * If any of "*" matched, then
2924 * "foo/ *" matched, mark frame
2927 PF_ANCHOR_SET_MATCH(f);
2930 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2931 if (f->child != NULL) {
2932 *rs = &f->child->ruleset;
2933 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2941 if (*depth == 0 && a != NULL)
2944 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2946 *r = TAILQ_NEXT(fr, entries);
2947 } while (*r == NULL);
2954 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2955 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2960 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2961 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2965 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2966 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2967 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2968 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2969 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2970 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2971 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2972 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2978 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2983 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2987 if (addr->addr32[3] == 0xffffffff) {
2988 addr->addr32[3] = 0;
2989 if (addr->addr32[2] == 0xffffffff) {
2990 addr->addr32[2] = 0;
2991 if (addr->addr32[1] == 0xffffffff) {
2992 addr->addr32[1] = 0;
2994 htonl(ntohl(addr->addr32[0]) + 1);
2997 htonl(ntohl(addr->addr32[1]) + 1);
3000 htonl(ntohl(addr->addr32[2]) + 1);
3003 htonl(ntohl(addr->addr32[3]) + 1);
3010 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3012 struct pf_addr *saddr, *daddr;
3013 u_int16_t sport, dport;
3014 struct inpcbinfo *pi;
3017 pd->lookup.uid = UID_MAX;
3018 pd->lookup.gid = GID_MAX;
3020 switch (pd->proto) {
3022 if (pd->hdr.tcp == NULL)
3024 sport = pd->hdr.tcp->th_sport;
3025 dport = pd->hdr.tcp->th_dport;
3029 if (pd->hdr.udp == NULL)
3031 sport = pd->hdr.udp->uh_sport;
3032 dport = pd->hdr.udp->uh_dport;
3038 if (direction == PF_IN) {
3053 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3054 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3056 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3057 daddr->v4, dport, INPLOOKUP_WILDCARD |
3058 INPLOOKUP_RLOCKPCB, NULL, m);
3066 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3067 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3069 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3070 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3071 INPLOOKUP_RLOCKPCB, NULL, m);
3081 INP_RLOCK_ASSERT(inp);
3082 pd->lookup.uid = inp->inp_cred->cr_uid;
3083 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3090 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3094 u_int8_t *opt, optlen;
3095 u_int8_t wscale = 0;
3097 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3098 if (hlen <= sizeof(struct tcphdr))
3100 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3102 opt = hdr + sizeof(struct tcphdr);
3103 hlen -= sizeof(struct tcphdr);
3113 if (wscale > TCP_MAX_WINSHIFT)
3114 wscale = TCP_MAX_WINSHIFT;
3115 wscale |= PF_WSCALE_FLAG;
3130 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3134 u_int8_t *opt, optlen;
3135 u_int16_t mss = V_tcp_mssdflt;
3137 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3138 if (hlen <= sizeof(struct tcphdr))
3140 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3142 opt = hdr + sizeof(struct tcphdr);
3143 hlen -= sizeof(struct tcphdr);
3144 while (hlen >= TCPOLEN_MAXSEG) {
3152 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3168 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3171 struct nhop4_basic nh4;
3174 struct nhop6_basic nh6;
3175 struct in6_addr dst6;
3184 hlen = sizeof(struct ip);
3185 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3186 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3191 hlen = sizeof(struct ip6_hdr);
3192 in6_splitscope(&addr->v6, &dst6, &scopeid);
3193 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3194 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3199 mss = max(V_tcp_mssdflt, mss);
3200 mss = min(mss, offer);
3201 mss = max(mss, 64); /* sanity - at least max opt space */
3206 pf_tcp_iss(struct pf_pdesc *pd)
3209 u_int32_t digest[4];
3211 if (V_pf_tcp_secret_init == 0) {
3212 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3213 MD5Init(&V_pf_tcp_secret_ctx);
3214 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3215 sizeof(V_pf_tcp_secret));
3216 V_pf_tcp_secret_init = 1;
3219 ctx = V_pf_tcp_secret_ctx;
3221 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3222 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3223 if (pd->af == AF_INET6) {
3224 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3225 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3227 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3228 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3230 MD5Final((u_char *)digest, &ctx);
3231 V_pf_tcp_iss_off += 4096;
3232 #define ISN_RANDOM_INCREMENT (4096 - 1)
3233 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3235 #undef ISN_RANDOM_INCREMENT
3239 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3240 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3241 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3243 struct pf_rule *nr = NULL;
3244 struct pf_addr * const saddr = pd->src;
3245 struct pf_addr * const daddr = pd->dst;
3246 sa_family_t af = pd->af;
3247 struct pf_rule *r, *a = NULL;
3248 struct pf_ruleset *ruleset = NULL;
3249 struct pf_src_node *nsn = NULL;
3250 struct tcphdr *th = pd->hdr.tcp;
3251 struct pf_state_key *sk = NULL, *nk = NULL;
3253 int rewrite = 0, hdrlen = 0;
3254 int tag = -1, rtableid = -1;
3258 u_int16_t sport = 0, dport = 0;
3259 u_int16_t bproto_sum = 0, bip_sum = 0;
3260 u_int8_t icmptype = 0, icmpcode = 0;
3261 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3266 INP_LOCK_ASSERT(inp);
3267 pd->lookup.uid = inp->inp_cred->cr_uid;
3268 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3269 pd->lookup.done = 1;
3272 switch (pd->proto) {
3274 sport = th->th_sport;
3275 dport = th->th_dport;
3276 hdrlen = sizeof(*th);
3279 sport = pd->hdr.udp->uh_sport;
3280 dport = pd->hdr.udp->uh_dport;
3281 hdrlen = sizeof(*pd->hdr.udp);
3285 if (pd->af != AF_INET)
3287 sport = dport = pd->hdr.icmp->icmp_id;
3288 hdrlen = sizeof(*pd->hdr.icmp);
3289 icmptype = pd->hdr.icmp->icmp_type;
3290 icmpcode = pd->hdr.icmp->icmp_code;
3292 if (icmptype == ICMP_UNREACH ||
3293 icmptype == ICMP_SOURCEQUENCH ||
3294 icmptype == ICMP_REDIRECT ||
3295 icmptype == ICMP_TIMXCEED ||
3296 icmptype == ICMP_PARAMPROB)
3301 case IPPROTO_ICMPV6:
3304 sport = dport = pd->hdr.icmp6->icmp6_id;
3305 hdrlen = sizeof(*pd->hdr.icmp6);
3306 icmptype = pd->hdr.icmp6->icmp6_type;
3307 icmpcode = pd->hdr.icmp6->icmp6_code;
3309 if (icmptype == ICMP6_DST_UNREACH ||
3310 icmptype == ICMP6_PACKET_TOO_BIG ||
3311 icmptype == ICMP6_TIME_EXCEEDED ||
3312 icmptype == ICMP6_PARAM_PROB)
3317 sport = dport = hdrlen = 0;
3321 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3323 /* check packet for BINAT/NAT/RDR */
3324 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3325 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3326 KASSERT(sk != NULL, ("%s: null sk", __func__));
3327 KASSERT(nk != NULL, ("%s: null nk", __func__));
3330 bip_sum = *pd->ip_sum;
3332 switch (pd->proto) {
3334 bproto_sum = th->th_sum;
3335 pd->proto_sum = &th->th_sum;
3337 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3338 nk->port[pd->sidx] != sport) {
3339 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3340 &th->th_sum, &nk->addr[pd->sidx],
3341 nk->port[pd->sidx], 0, af);
3342 pd->sport = &th->th_sport;
3343 sport = th->th_sport;
3346 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3347 nk->port[pd->didx] != dport) {
3348 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3349 &th->th_sum, &nk->addr[pd->didx],
3350 nk->port[pd->didx], 0, af);
3351 dport = th->th_dport;
3352 pd->dport = &th->th_dport;
3357 bproto_sum = pd->hdr.udp->uh_sum;
3358 pd->proto_sum = &pd->hdr.udp->uh_sum;
3360 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3361 nk->port[pd->sidx] != sport) {
3362 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3363 pd->ip_sum, &pd->hdr.udp->uh_sum,
3364 &nk->addr[pd->sidx],
3365 nk->port[pd->sidx], 1, af);
3366 sport = pd->hdr.udp->uh_sport;
3367 pd->sport = &pd->hdr.udp->uh_sport;
3370 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3371 nk->port[pd->didx] != dport) {
3372 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3373 pd->ip_sum, &pd->hdr.udp->uh_sum,
3374 &nk->addr[pd->didx],
3375 nk->port[pd->didx], 1, af);
3376 dport = pd->hdr.udp->uh_dport;
3377 pd->dport = &pd->hdr.udp->uh_dport;
3383 nk->port[0] = nk->port[1];
3384 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3385 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3386 nk->addr[pd->sidx].v4.s_addr, 0);
3388 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3389 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3390 nk->addr[pd->didx].v4.s_addr, 0);
3392 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3393 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3394 pd->hdr.icmp->icmp_cksum, sport,
3396 pd->hdr.icmp->icmp_id = nk->port[1];
3397 pd->sport = &pd->hdr.icmp->icmp_id;
3399 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3403 case IPPROTO_ICMPV6:
3404 nk->port[0] = nk->port[1];
3405 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3406 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3407 &nk->addr[pd->sidx], 0);
3409 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3410 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3411 &nk->addr[pd->didx], 0);
3420 &nk->addr[pd->sidx], AF_INET))
3421 pf_change_a(&saddr->v4.s_addr,
3423 nk->addr[pd->sidx].v4.s_addr, 0);
3426 &nk->addr[pd->didx], AF_INET))
3427 pf_change_a(&daddr->v4.s_addr,
3429 nk->addr[pd->didx].v4.s_addr, 0);
3435 &nk->addr[pd->sidx], AF_INET6))
3436 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3439 &nk->addr[pd->didx], AF_INET6))
3440 PF_ACPY(daddr, &nk->addr[pd->didx], af);
3453 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3454 r = r->skip[PF_SKIP_IFP].ptr;
3455 else if (r->direction && r->direction != direction)
3456 r = r->skip[PF_SKIP_DIR].ptr;
3457 else if (r->af && r->af != af)
3458 r = r->skip[PF_SKIP_AF].ptr;
3459 else if (r->proto && r->proto != pd->proto)
3460 r = r->skip[PF_SKIP_PROTO].ptr;
3461 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3462 r->src.neg, kif, M_GETFIB(m)))
3463 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3464 /* tcp/udp only. port_op always 0 in other cases */
3465 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3466 r->src.port[0], r->src.port[1], sport))
3467 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3468 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3469 r->dst.neg, NULL, M_GETFIB(m)))
3470 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3471 /* tcp/udp only. port_op always 0 in other cases */
3472 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3473 r->dst.port[0], r->dst.port[1], dport))
3474 r = r->skip[PF_SKIP_DST_PORT].ptr;
3475 /* icmp only. type always 0 in other cases */
3476 else if (r->type && r->type != icmptype + 1)
3477 r = TAILQ_NEXT(r, entries);
3478 /* icmp only. type always 0 in other cases */
3479 else if (r->code && r->code != icmpcode + 1)
3480 r = TAILQ_NEXT(r, entries);
3481 else if (r->tos && !(r->tos == pd->tos))
3482 r = TAILQ_NEXT(r, entries);
3483 else if (r->rule_flag & PFRULE_FRAGMENT)
3484 r = TAILQ_NEXT(r, entries);
3485 else if (pd->proto == IPPROTO_TCP &&
3486 (r->flagset & th->th_flags) != r->flags)
3487 r = TAILQ_NEXT(r, entries);
3488 /* tcp/udp only. uid.op always 0 in other cases */
3489 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3490 pf_socket_lookup(direction, pd, m), 1)) &&
3491 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3493 r = TAILQ_NEXT(r, entries);
3494 /* tcp/udp only. gid.op always 0 in other cases */
3495 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3496 pf_socket_lookup(direction, pd, m), 1)) &&
3497 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3499 r = TAILQ_NEXT(r, entries);
3501 !pf_match_ieee8021q_pcp(r->prio, m))
3502 r = TAILQ_NEXT(r, entries);
3504 r->prob <= arc4random())
3505 r = TAILQ_NEXT(r, entries);
3506 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3507 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3508 r = TAILQ_NEXT(r, entries);
3509 else if (r->os_fingerprint != PF_OSFP_ANY &&
3510 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3511 pf_osfp_fingerprint(pd, m, off, th),
3512 r->os_fingerprint)))
3513 r = TAILQ_NEXT(r, entries);
3517 if (r->rtableid >= 0)
3518 rtableid = r->rtableid;
3519 if (r->anchor == NULL) {
3526 r = TAILQ_NEXT(r, entries);
3528 pf_step_into_anchor(anchor_stack, &asd,
3529 &ruleset, PF_RULESET_FILTER, &r, &a,
3532 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3533 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3540 REASON_SET(&reason, PFRES_MATCH);
3542 if (r->log || (nr != NULL && nr->log)) {
3544 m_copyback(m, off, hdrlen, pd->hdr.any);
3545 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3549 if ((r->action == PF_DROP) &&
3550 ((r->rule_flag & PFRULE_RETURNRST) ||
3551 (r->rule_flag & PFRULE_RETURNICMP) ||
3552 (r->rule_flag & PFRULE_RETURN))) {
3553 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3554 bip_sum, hdrlen, &reason);
3557 if (r->action == PF_DROP)
3560 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3561 REASON_SET(&reason, PFRES_MEMORY);
3565 M_SETFIB(m, rtableid);
3567 if (!state_icmp && (r->keep_state || nr != NULL ||
3568 (pd->flags & PFDESC_TCP_NORM))) {
3570 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3571 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3573 if (action != PF_PASS) {
3574 if (action == PF_DROP &&
3575 (r->rule_flag & PFRULE_RETURN))
3576 pf_return(r, nr, pd, sk, off, m, th, kif,
3577 bproto_sum, bip_sum, hdrlen, &reason);
3582 uma_zfree(V_pf_state_key_z, sk);
3584 uma_zfree(V_pf_state_key_z, nk);
3587 /* copy back packet headers if we performed NAT operations */
3589 m_copyback(m, off, hdrlen, pd->hdr.any);
3591 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3592 direction == PF_OUT &&
3593 V_pfsync_defer_ptr != NULL && V_pfsync_defer_ptr(*sm, m))
3595 * We want the state created, but we dont
3596 * want to send this in case a partner
3597 * firewall has to know about it to allow
3598 * replies through it.
3606 uma_zfree(V_pf_state_key_z, sk);
3608 uma_zfree(V_pf_state_key_z, nk);
3613 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3614 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3615 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3616 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3617 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3619 struct pf_state *s = NULL;
3620 struct pf_src_node *sn = NULL;
3621 struct tcphdr *th = pd->hdr.tcp;
3622 u_int16_t mss = V_tcp_mssdflt;
3625 /* check maximums */
3626 if (r->max_states &&
3627 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3628 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3629 REASON_SET(&reason, PFRES_MAXSTATES);
3632 /* src node for filter rule */
3633 if ((r->rule_flag & PFRULE_SRCTRACK ||
3634 r->rpool.opts & PF_POOL_STICKYADDR) &&
3635 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3636 REASON_SET(&reason, PFRES_SRCLIMIT);
3639 /* src node for translation rule */
3640 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3641 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3642 REASON_SET(&reason, PFRES_SRCLIMIT);
3645 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3647 REASON_SET(&reason, PFRES_MEMORY);
3651 s->nat_rule.ptr = nr;
3653 STATE_INC_COUNTERS(s);
3655 s->state_flags |= PFSTATE_ALLOWOPTS;
3656 if (r->rule_flag & PFRULE_STATESLOPPY)
3657 s->state_flags |= PFSTATE_SLOPPY;
3658 s->log = r->log & PF_LOG_ALL;
3659 s->sync_state = PFSYNC_S_NONE;
3661 s->log |= nr->log & PF_LOG_ALL;
3662 switch (pd->proto) {
3664 s->src.seqlo = ntohl(th->th_seq);
3665 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3666 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3667 r->keep_state == PF_STATE_MODULATE) {
3668 /* Generate sequence number modulator */
3669 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3672 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3673 htonl(s->src.seqlo + s->src.seqdiff), 0);
3677 if (th->th_flags & TH_SYN) {
3679 s->src.wscale = pf_get_wscale(m, off,
3680 th->th_off, pd->af);
3682 s->src.max_win = MAX(ntohs(th->th_win), 1);
3683 if (s->src.wscale & PF_WSCALE_MASK) {
3684 /* Remove scale factor from initial window */
3685 int win = s->src.max_win;
3686 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3687 s->src.max_win = (win - 1) >>
3688 (s->src.wscale & PF_WSCALE_MASK);
3690 if (th->th_flags & TH_FIN)
3694 s->src.state = TCPS_SYN_SENT;
3695 s->dst.state = TCPS_CLOSED;
3696 s->timeout = PFTM_TCP_FIRST_PACKET;
3699 s->src.state = PFUDPS_SINGLE;
3700 s->dst.state = PFUDPS_NO_TRAFFIC;
3701 s->timeout = PFTM_UDP_FIRST_PACKET;
3705 case IPPROTO_ICMPV6:
3707 s->timeout = PFTM_ICMP_FIRST_PACKET;
3710 s->src.state = PFOTHERS_SINGLE;
3711 s->dst.state = PFOTHERS_NO_TRAFFIC;
3712 s->timeout = PFTM_OTHER_FIRST_PACKET;
3716 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3717 REASON_SET(&reason, PFRES_MAPFAILED);
3718 pf_src_tree_remove_state(s);
3719 STATE_DEC_COUNTERS(s);
3720 uma_zfree(V_pf_state_z, s);
3723 s->rt_kif = r->rpool.cur->kif;
3726 s->creation = time_uptime;
3727 s->expire = time_uptime;
3732 /* XXX We only modify one side for now. */
3733 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3734 s->nat_src_node = nsn;
3736 if (pd->proto == IPPROTO_TCP) {
3737 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3738 off, pd, th, &s->src, &s->dst)) {
3739 REASON_SET(&reason, PFRES_MEMORY);
3740 pf_src_tree_remove_state(s);
3741 STATE_DEC_COUNTERS(s);
3742 uma_zfree(V_pf_state_z, s);
3745 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3746 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3747 &s->src, &s->dst, rewrite)) {
3748 /* This really shouldn't happen!!! */
3749 DPFPRINTF(PF_DEBUG_URGENT,
3750 ("pf_normalize_tcp_stateful failed on first pkt"));
3751 pf_normalize_tcp_cleanup(s);
3752 pf_src_tree_remove_state(s);
3753 STATE_DEC_COUNTERS(s);
3754 uma_zfree(V_pf_state_z, s);
3758 s->direction = pd->dir;
3761 * sk/nk could already been setup by pf_get_translation().
3764 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3765 __func__, nr, sk, nk));
3766 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3771 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3772 __func__, nr, sk, nk));
3774 /* Swap sk/nk for PF_OUT. */
3775 if (pf_state_insert(BOUND_IFACE(r, kif),
3776 (pd->dir == PF_IN) ? sk : nk,
3777 (pd->dir == PF_IN) ? nk : sk, s)) {
3778 if (pd->proto == IPPROTO_TCP)
3779 pf_normalize_tcp_cleanup(s);
3780 REASON_SET(&reason, PFRES_STATEINS);
3781 pf_src_tree_remove_state(s);
3782 STATE_DEC_COUNTERS(s);
3783 uma_zfree(V_pf_state_z, s);
3790 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3791 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3792 s->src.state = PF_TCPS_PROXY_SRC;
3793 /* undo NAT changes, if they have taken place */
3795 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3796 if (pd->dir == PF_OUT)
3797 skt = s->key[PF_SK_STACK];
3798 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3799 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3801 *pd->sport = skt->port[pd->sidx];
3803 *pd->dport = skt->port[pd->didx];
3805 *pd->proto_sum = bproto_sum;
3807 *pd->ip_sum = bip_sum;
3808 m_copyback(m, off, hdrlen, pd->hdr.any);
3810 s->src.seqhi = htonl(arc4random());
3811 /* Find mss option */
3812 int rtid = M_GETFIB(m);
3813 mss = pf_get_mss(m, off, th->th_off, pd->af);
3814 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3815 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3817 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3818 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3819 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3820 REASON_SET(&reason, PFRES_SYNPROXY);
3821 return (PF_SYNPROXY_DROP);
3828 uma_zfree(V_pf_state_key_z, sk);
3830 uma_zfree(V_pf_state_key_z, nk);
3833 struct pf_srchash *sh;
3835 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3836 PF_HASHROW_LOCK(sh);
3837 if (--sn->states == 0 && sn->expire == 0) {
3838 pf_unlink_src_node(sn);
3839 uma_zfree(V_pf_sources_z, sn);
3841 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3843 PF_HASHROW_UNLOCK(sh);
3846 if (nsn != sn && nsn != NULL) {
3847 struct pf_srchash *sh;
3849 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3850 PF_HASHROW_LOCK(sh);
3851 if (--nsn->states == 0 && nsn->expire == 0) {
3852 pf_unlink_src_node(nsn);
3853 uma_zfree(V_pf_sources_z, nsn);
3855 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3857 PF_HASHROW_UNLOCK(sh);
3864 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3865 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3866 struct pf_ruleset **rsm)
3868 struct pf_rule *r, *a = NULL;
3869 struct pf_ruleset *ruleset = NULL;
3870 sa_family_t af = pd->af;
3875 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3879 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3882 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3883 r = r->skip[PF_SKIP_IFP].ptr;
3884 else if (r->direction && r->direction != direction)
3885 r = r->skip[PF_SKIP_DIR].ptr;
3886 else if (r->af && r->af != af)
3887 r = r->skip[PF_SKIP_AF].ptr;
3888 else if (r->proto && r->proto != pd->proto)
3889 r = r->skip[PF_SKIP_PROTO].ptr;
3890 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3891 r->src.neg, kif, M_GETFIB(m)))
3892 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3893 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3894 r->dst.neg, NULL, M_GETFIB(m)))
3895 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3896 else if (r->tos && !(r->tos == pd->tos))
3897 r = TAILQ_NEXT(r, entries);
3898 else if (r->os_fingerprint != PF_OSFP_ANY)
3899 r = TAILQ_NEXT(r, entries);
3900 else if (pd->proto == IPPROTO_UDP &&
3901 (r->src.port_op || r->dst.port_op))
3902 r = TAILQ_NEXT(r, entries);
3903 else if (pd->proto == IPPROTO_TCP &&
3904 (r->src.port_op || r->dst.port_op || r->flagset))
3905 r = TAILQ_NEXT(r, entries);
3906 else if ((pd->proto == IPPROTO_ICMP ||
3907 pd->proto == IPPROTO_ICMPV6) &&
3908 (r->type || r->code))
3909 r = TAILQ_NEXT(r, entries);
3911 !pf_match_ieee8021q_pcp(r->prio, m))
3912 r = TAILQ_NEXT(r, entries);
3913 else if (r->prob && r->prob <=
3914 (arc4random() % (UINT_MAX - 1) + 1))
3915 r = TAILQ_NEXT(r, entries);
3916 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3917 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3918 r = TAILQ_NEXT(r, entries);
3920 if (r->anchor == NULL) {
3927 r = TAILQ_NEXT(r, entries);
3929 pf_step_into_anchor(anchor_stack, &asd,
3930 &ruleset, PF_RULESET_FILTER, &r, &a,
3933 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3934 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3941 REASON_SET(&reason, PFRES_MATCH);
3944 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3947 if (r->action != PF_PASS)
3950 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3951 REASON_SET(&reason, PFRES_MEMORY);
3959 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3960 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3961 struct pf_pdesc *pd, u_short *reason, int *copyback)
3963 struct tcphdr *th = pd->hdr.tcp;
3964 u_int16_t win = ntohs(th->th_win);
3965 u_int32_t ack, end, seq, orig_seq;
3969 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3970 sws = src->wscale & PF_WSCALE_MASK;
3971 dws = dst->wscale & PF_WSCALE_MASK;
3976 * Sequence tracking algorithm from Guido van Rooij's paper:
3977 * http://www.madison-gurkha.com/publications/tcp_filtering/
3981 orig_seq = seq = ntohl(th->th_seq);
3982 if (src->seqlo == 0) {
3983 /* First packet from this end. Set its state */
3985 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3986 src->scrub == NULL) {
3987 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3988 REASON_SET(reason, PFRES_MEMORY);
3993 /* Deferred generation of sequence number modulator */
3994 if (dst->seqdiff && !src->seqdiff) {
3995 /* use random iss for the TCP server */
3996 while ((src->seqdiff = arc4random() - seq) == 0)
3998 ack = ntohl(th->th_ack) - dst->seqdiff;
3999 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4001 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4004 ack = ntohl(th->th_ack);
4007 end = seq + pd->p_len;
4008 if (th->th_flags & TH_SYN) {
4010 if (dst->wscale & PF_WSCALE_FLAG) {
4011 src->wscale = pf_get_wscale(m, off, th->th_off,
4013 if (src->wscale & PF_WSCALE_FLAG) {
4014 /* Remove scale factor from initial
4016 sws = src->wscale & PF_WSCALE_MASK;
4017 win = ((u_int32_t)win + (1 << sws) - 1)
4019 dws = dst->wscale & PF_WSCALE_MASK;
4021 /* fixup other window */
4022 dst->max_win <<= dst->wscale &
4024 /* in case of a retrans SYN|ACK */
4029 if (th->th_flags & TH_FIN)
4033 if (src->state < TCPS_SYN_SENT)
4034 src->state = TCPS_SYN_SENT;
4037 * May need to slide the window (seqhi may have been set by
4038 * the crappy stack check or if we picked up the connection
4039 * after establishment)
4041 if (src->seqhi == 1 ||
4042 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4043 src->seqhi = end + MAX(1, dst->max_win << dws);
4044 if (win > src->max_win)
4048 ack = ntohl(th->th_ack) - dst->seqdiff;
4050 /* Modulate sequence numbers */
4051 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4053 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4056 end = seq + pd->p_len;
4057 if (th->th_flags & TH_SYN)
4059 if (th->th_flags & TH_FIN)
4063 if ((th->th_flags & TH_ACK) == 0) {
4064 /* Let it pass through the ack skew check */
4066 } else if ((ack == 0 &&
4067 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4068 /* broken tcp stacks do not set ack */
4069 (dst->state < TCPS_SYN_SENT)) {
4071 * Many stacks (ours included) will set the ACK number in an
4072 * FIN|ACK if the SYN times out -- no sequence to ACK.
4078 /* Ease sequencing restrictions on no data packets */
4083 ackskew = dst->seqlo - ack;
4087 * Need to demodulate the sequence numbers in any TCP SACK options
4088 * (Selective ACK). We could optionally validate the SACK values
4089 * against the current ACK window, either forwards or backwards, but
4090 * I'm not confident that SACK has been implemented properly
4091 * everywhere. It wouldn't surprise me if several stacks accidentally
4092 * SACK too far backwards of previously ACKed data. There really aren't
4093 * any security implications of bad SACKing unless the target stack
4094 * doesn't validate the option length correctly. Someone trying to
4095 * spoof into a TCP connection won't bother blindly sending SACK
4098 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4099 if (pf_modulate_sack(m, off, pd, th, dst))
4104 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4105 if (SEQ_GEQ(src->seqhi, end) &&
4106 /* Last octet inside other's window space */
4107 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4108 /* Retrans: not more than one window back */
4109 (ackskew >= -MAXACKWINDOW) &&
4110 /* Acking not more than one reassembled fragment backwards */
4111 (ackskew <= (MAXACKWINDOW << sws)) &&
4112 /* Acking not more than one window forward */
4113 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4114 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4115 (pd->flags & PFDESC_IP_REAS) == 0)) {
4116 /* Require an exact/+1 sequence match on resets when possible */
4118 if (dst->scrub || src->scrub) {
4119 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4120 *state, src, dst, copyback))
4124 /* update max window */
4125 if (src->max_win < win)
4127 /* synchronize sequencing */
4128 if (SEQ_GT(end, src->seqlo))
4130 /* slide the window of what the other end can send */
4131 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4132 dst->seqhi = ack + MAX((win << sws), 1);
4136 if (th->th_flags & TH_SYN)
4137 if (src->state < TCPS_SYN_SENT)
4138 src->state = TCPS_SYN_SENT;
4139 if (th->th_flags & TH_FIN)
4140 if (src->state < TCPS_CLOSING)
4141 src->state = TCPS_CLOSING;
4142 if (th->th_flags & TH_ACK) {
4143 if (dst->state == TCPS_SYN_SENT) {
4144 dst->state = TCPS_ESTABLISHED;
4145 if (src->state == TCPS_ESTABLISHED &&
4146 (*state)->src_node != NULL &&
4147 pf_src_connlimit(state)) {
4148 REASON_SET(reason, PFRES_SRCLIMIT);
4151 } else if (dst->state == TCPS_CLOSING)
4152 dst->state = TCPS_FIN_WAIT_2;
4154 if (th->th_flags & TH_RST)
4155 src->state = dst->state = TCPS_TIME_WAIT;
4157 /* update expire time */
4158 (*state)->expire = time_uptime;
4159 if (src->state >= TCPS_FIN_WAIT_2 &&
4160 dst->state >= TCPS_FIN_WAIT_2)
4161 (*state)->timeout = PFTM_TCP_CLOSED;
4162 else if (src->state >= TCPS_CLOSING &&
4163 dst->state >= TCPS_CLOSING)
4164 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4165 else if (src->state < TCPS_ESTABLISHED ||
4166 dst->state < TCPS_ESTABLISHED)
4167 (*state)->timeout = PFTM_TCP_OPENING;
4168 else if (src->state >= TCPS_CLOSING ||
4169 dst->state >= TCPS_CLOSING)
4170 (*state)->timeout = PFTM_TCP_CLOSING;
4172 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4174 /* Fall through to PASS packet */
4176 } else if ((dst->state < TCPS_SYN_SENT ||
4177 dst->state >= TCPS_FIN_WAIT_2 ||
4178 src->state >= TCPS_FIN_WAIT_2) &&
4179 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4180 /* Within a window forward of the originating packet */
4181 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4182 /* Within a window backward of the originating packet */
4185 * This currently handles three situations:
4186 * 1) Stupid stacks will shotgun SYNs before their peer
4188 * 2) When PF catches an already established stream (the
4189 * firewall rebooted, the state table was flushed, routes
4191 * 3) Packets get funky immediately after the connection
4192 * closes (this should catch Solaris spurious ACK|FINs
4193 * that web servers like to spew after a close)
4195 * This must be a little more careful than the above code
4196 * since packet floods will also be caught here. We don't
4197 * update the TTL here to mitigate the damage of a packet
4198 * flood and so the same code can handle awkward establishment
4199 * and a loosened connection close.
4200 * In the establishment case, a correct peer response will
4201 * validate the connection, go through the normal state code
4202 * and keep updating the state TTL.
4205 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4206 printf("pf: loose state match: ");
4207 pf_print_state(*state);
4208 pf_print_flags(th->th_flags);
4209 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4210 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4211 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4212 (unsigned long long)(*state)->packets[1],
4213 pd->dir == PF_IN ? "in" : "out",
4214 pd->dir == (*state)->direction ? "fwd" : "rev");
4217 if (dst->scrub || src->scrub) {
4218 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4219 *state, src, dst, copyback))
4223 /* update max window */
4224 if (src->max_win < win)
4226 /* synchronize sequencing */
4227 if (SEQ_GT(end, src->seqlo))
4229 /* slide the window of what the other end can send */
4230 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4231 dst->seqhi = ack + MAX((win << sws), 1);
4234 * Cannot set dst->seqhi here since this could be a shotgunned
4235 * SYN and not an already established connection.
4238 if (th->th_flags & TH_FIN)
4239 if (src->state < TCPS_CLOSING)
4240 src->state = TCPS_CLOSING;
4241 if (th->th_flags & TH_RST)
4242 src->state = dst->state = TCPS_TIME_WAIT;
4244 /* Fall through to PASS packet */
4247 if ((*state)->dst.state == TCPS_SYN_SENT &&
4248 (*state)->src.state == TCPS_SYN_SENT) {
4249 /* Send RST for state mismatches during handshake */
4250 if (!(th->th_flags & TH_RST))
4251 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4252 pd->dst, pd->src, th->th_dport,
4253 th->th_sport, ntohl(th->th_ack), 0,
4255 (*state)->rule.ptr->return_ttl, 1, 0,
4260 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4261 printf("pf: BAD state: ");
4262 pf_print_state(*state);
4263 pf_print_flags(th->th_flags);
4264 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4265 "pkts=%llu:%llu dir=%s,%s\n",
4266 seq, orig_seq, ack, pd->p_len, ackskew,
4267 (unsigned long long)(*state)->packets[0],
4268 (unsigned long long)(*state)->packets[1],
4269 pd->dir == PF_IN ? "in" : "out",
4270 pd->dir == (*state)->direction ? "fwd" : "rev");
4271 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4272 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4273 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4275 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4276 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4277 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4278 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4280 REASON_SET(reason, PFRES_BADSTATE);
4288 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4289 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4291 struct tcphdr *th = pd->hdr.tcp;
4293 if (th->th_flags & TH_SYN)
4294 if (src->state < TCPS_SYN_SENT)
4295 src->state = TCPS_SYN_SENT;
4296 if (th->th_flags & TH_FIN)
4297 if (src->state < TCPS_CLOSING)
4298 src->state = TCPS_CLOSING;
4299 if (th->th_flags & TH_ACK) {
4300 if (dst->state == TCPS_SYN_SENT) {
4301 dst->state = TCPS_ESTABLISHED;
4302 if (src->state == TCPS_ESTABLISHED &&
4303 (*state)->src_node != NULL &&
4304 pf_src_connlimit(state)) {
4305 REASON_SET(reason, PFRES_SRCLIMIT);
4308 } else if (dst->state == TCPS_CLOSING) {
4309 dst->state = TCPS_FIN_WAIT_2;
4310 } else if (src->state == TCPS_SYN_SENT &&
4311 dst->state < TCPS_SYN_SENT) {
4313 * Handle a special sloppy case where we only see one
4314 * half of the connection. If there is a ACK after
4315 * the initial SYN without ever seeing a packet from
4316 * the destination, set the connection to established.
4318 dst->state = src->state = TCPS_ESTABLISHED;
4319 if ((*state)->src_node != NULL &&
4320 pf_src_connlimit(state)) {
4321 REASON_SET(reason, PFRES_SRCLIMIT);
4324 } else if (src->state == TCPS_CLOSING &&
4325 dst->state == TCPS_ESTABLISHED &&
4328 * Handle the closing of half connections where we
4329 * don't see the full bidirectional FIN/ACK+ACK
4332 dst->state = TCPS_CLOSING;
4335 if (th->th_flags & TH_RST)
4336 src->state = dst->state = TCPS_TIME_WAIT;
4338 /* update expire time */
4339 (*state)->expire = time_uptime;
4340 if (src->state >= TCPS_FIN_WAIT_2 &&
4341 dst->state >= TCPS_FIN_WAIT_2)
4342 (*state)->timeout = PFTM_TCP_CLOSED;
4343 else if (src->state >= TCPS_CLOSING &&
4344 dst->state >= TCPS_CLOSING)
4345 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4346 else if (src->state < TCPS_ESTABLISHED ||
4347 dst->state < TCPS_ESTABLISHED)
4348 (*state)->timeout = PFTM_TCP_OPENING;
4349 else if (src->state >= TCPS_CLOSING ||
4350 dst->state >= TCPS_CLOSING)
4351 (*state)->timeout = PFTM_TCP_CLOSING;
4353 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4359 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4360 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4363 struct pf_state_key_cmp key;
4364 struct tcphdr *th = pd->hdr.tcp;
4366 struct pf_state_peer *src, *dst;
4367 struct pf_state_key *sk;
4369 bzero(&key, sizeof(key));
4371 key.proto = IPPROTO_TCP;
4372 if (direction == PF_IN) { /* wire side, straight */
4373 PF_ACPY(&key.addr[0], pd->src, key.af);
4374 PF_ACPY(&key.addr[1], pd->dst, key.af);
4375 key.port[0] = th->th_sport;
4376 key.port[1] = th->th_dport;
4377 } else { /* stack side, reverse */
4378 PF_ACPY(&key.addr[1], pd->src, key.af);
4379 PF_ACPY(&key.addr[0], pd->dst, key.af);
4380 key.port[1] = th->th_sport;
4381 key.port[0] = th->th_dport;
4384 STATE_LOOKUP(kif, &key, direction, *state, pd);
4386 if (direction == (*state)->direction) {
4387 src = &(*state)->src;
4388 dst = &(*state)->dst;
4390 src = &(*state)->dst;
4391 dst = &(*state)->src;
4394 sk = (*state)->key[pd->didx];
4396 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4397 if (direction != (*state)->direction) {
4398 REASON_SET(reason, PFRES_SYNPROXY);
4399 return (PF_SYNPROXY_DROP);
4401 if (th->th_flags & TH_SYN) {
4402 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4403 REASON_SET(reason, PFRES_SYNPROXY);
4406 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4407 pd->src, th->th_dport, th->th_sport,
4408 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4409 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4410 REASON_SET(reason, PFRES_SYNPROXY);
4411 return (PF_SYNPROXY_DROP);
4412 } else if ((th->th_flags & (TH_ACK|TH_RST|TH_FIN)) != TH_ACK ||
4413 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4414 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4415 REASON_SET(reason, PFRES_SYNPROXY);
4417 } else if ((*state)->src_node != NULL &&
4418 pf_src_connlimit(state)) {
4419 REASON_SET(reason, PFRES_SRCLIMIT);
4422 (*state)->src.state = PF_TCPS_PROXY_DST;
4424 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4425 if (direction == (*state)->direction) {
4426 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4427 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4428 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4429 REASON_SET(reason, PFRES_SYNPROXY);
4432 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4433 if ((*state)->dst.seqhi == 1)
4434 (*state)->dst.seqhi = htonl(arc4random());
4435 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4436 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4437 sk->port[pd->sidx], sk->port[pd->didx],
4438 (*state)->dst.seqhi, 0, TH_SYN, 0,
4439 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4440 REASON_SET(reason, PFRES_SYNPROXY);
4441 return (PF_SYNPROXY_DROP);
4442 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4444 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4445 REASON_SET(reason, PFRES_SYNPROXY);
4448 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4449 (*state)->dst.seqlo = ntohl(th->th_seq);
4450 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4451 pd->src, th->th_dport, th->th_sport,
4452 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4453 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4454 (*state)->tag, NULL);
4455 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4456 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4457 sk->port[pd->sidx], sk->port[pd->didx],
4458 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4459 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4460 (*state)->src.seqdiff = (*state)->dst.seqhi -
4461 (*state)->src.seqlo;
4462 (*state)->dst.seqdiff = (*state)->src.seqhi -
4463 (*state)->dst.seqlo;
4464 (*state)->src.seqhi = (*state)->src.seqlo +
4465 (*state)->dst.max_win;
4466 (*state)->dst.seqhi = (*state)->dst.seqlo +
4467 (*state)->src.max_win;
4468 (*state)->src.wscale = (*state)->dst.wscale = 0;
4469 (*state)->src.state = (*state)->dst.state =
4471 REASON_SET(reason, PFRES_SYNPROXY);
4472 return (PF_SYNPROXY_DROP);
4476 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4477 dst->state >= TCPS_FIN_WAIT_2 &&
4478 src->state >= TCPS_FIN_WAIT_2) {
4479 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4480 printf("pf: state reuse ");
4481 pf_print_state(*state);
4482 pf_print_flags(th->th_flags);
4485 /* XXX make sure it's the same direction ?? */
4486 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4487 pf_unlink_state(*state, PF_ENTER_LOCKED);
4492 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4493 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4496 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4497 ©back) == PF_DROP)
4501 /* translate source/destination address, if necessary */
4502 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4503 struct pf_state_key *nk = (*state)->key[pd->didx];
4505 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4506 nk->port[pd->sidx] != th->th_sport)
4507 pf_change_ap(m, pd->src, &th->th_sport,
4508 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4509 nk->port[pd->sidx], 0, pd->af);
4511 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4512 nk->port[pd->didx] != th->th_dport)
4513 pf_change_ap(m, pd->dst, &th->th_dport,
4514 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4515 nk->port[pd->didx], 0, pd->af);
4519 /* Copyback sequence modulation or stateful scrub changes if needed */
4521 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4527 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4528 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4530 struct pf_state_peer *src, *dst;
4531 struct pf_state_key_cmp key;
4532 struct udphdr *uh = pd->hdr.udp;
4534 bzero(&key, sizeof(key));
4536 key.proto = IPPROTO_UDP;
4537 if (direction == PF_IN) { /* wire side, straight */
4538 PF_ACPY(&key.addr[0], pd->src, key.af);
4539 PF_ACPY(&key.addr[1], pd->dst, key.af);
4540 key.port[0] = uh->uh_sport;
4541 key.port[1] = uh->uh_dport;
4542 } else { /* stack side, reverse */
4543 PF_ACPY(&key.addr[1], pd->src, key.af);
4544 PF_ACPY(&key.addr[0], pd->dst, key.af);
4545 key.port[1] = uh->uh_sport;
4546 key.port[0] = uh->uh_dport;
4549 STATE_LOOKUP(kif, &key, direction, *state, pd);
4551 if (direction == (*state)->direction) {
4552 src = &(*state)->src;
4553 dst = &(*state)->dst;
4555 src = &(*state)->dst;
4556 dst = &(*state)->src;
4560 if (src->state < PFUDPS_SINGLE)
4561 src->state = PFUDPS_SINGLE;
4562 if (dst->state == PFUDPS_SINGLE)
4563 dst->state = PFUDPS_MULTIPLE;
4565 /* update expire time */
4566 (*state)->expire = time_uptime;
4567 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4568 (*state)->timeout = PFTM_UDP_MULTIPLE;
4570 (*state)->timeout = PFTM_UDP_SINGLE;
4572 /* translate source/destination address, if necessary */
4573 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4574 struct pf_state_key *nk = (*state)->key[pd->didx];
4576 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4577 nk->port[pd->sidx] != uh->uh_sport)
4578 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4579 &uh->uh_sum, &nk->addr[pd->sidx],
4580 nk->port[pd->sidx], 1, pd->af);
4582 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4583 nk->port[pd->didx] != uh->uh_dport)
4584 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4585 &uh->uh_sum, &nk->addr[pd->didx],
4586 nk->port[pd->didx], 1, pd->af);
4587 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4594 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4595 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4597 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4598 u_int16_t icmpid = 0, *icmpsum;
4599 u_int8_t icmptype, icmpcode;
4601 struct pf_state_key_cmp key;
4603 bzero(&key, sizeof(key));
4604 switch (pd->proto) {
4607 icmptype = pd->hdr.icmp->icmp_type;
4608 icmpcode = pd->hdr.icmp->icmp_code;
4609 icmpid = pd->hdr.icmp->icmp_id;
4610 icmpsum = &pd->hdr.icmp->icmp_cksum;
4612 if (icmptype == ICMP_UNREACH ||
4613 icmptype == ICMP_SOURCEQUENCH ||
4614 icmptype == ICMP_REDIRECT ||
4615 icmptype == ICMP_TIMXCEED ||
4616 icmptype == ICMP_PARAMPROB)
4621 case IPPROTO_ICMPV6:
4622 icmptype = pd->hdr.icmp6->icmp6_type;
4623 icmpcode = pd->hdr.icmp6->icmp6_code;
4624 icmpid = pd->hdr.icmp6->icmp6_id;
4625 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4627 if (icmptype == ICMP6_DST_UNREACH ||
4628 icmptype == ICMP6_PACKET_TOO_BIG ||
4629 icmptype == ICMP6_TIME_EXCEEDED ||
4630 icmptype == ICMP6_PARAM_PROB)
4639 * ICMP query/reply message not related to a TCP/UDP packet.
4640 * Search for an ICMP state.
4643 key.proto = pd->proto;
4644 key.port[0] = key.port[1] = icmpid;
4645 if (direction == PF_IN) { /* wire side, straight */
4646 PF_ACPY(&key.addr[0], pd->src, key.af);
4647 PF_ACPY(&key.addr[1], pd->dst, key.af);
4648 } else { /* stack side, reverse */
4649 PF_ACPY(&key.addr[1], pd->src, key.af);
4650 PF_ACPY(&key.addr[0], pd->dst, key.af);
4653 STATE_LOOKUP(kif, &key, direction, *state, pd);
4655 (*state)->expire = time_uptime;
4656 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4658 /* translate source/destination address, if necessary */
4659 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4660 struct pf_state_key *nk = (*state)->key[pd->didx];
4665 if (PF_ANEQ(pd->src,
4666 &nk->addr[pd->sidx], AF_INET))
4667 pf_change_a(&saddr->v4.s_addr,
4669 nk->addr[pd->sidx].v4.s_addr, 0);
4671 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4673 pf_change_a(&daddr->v4.s_addr,
4675 nk->addr[pd->didx].v4.s_addr, 0);
4678 pd->hdr.icmp->icmp_id) {
4679 pd->hdr.icmp->icmp_cksum =
4681 pd->hdr.icmp->icmp_cksum, icmpid,
4682 nk->port[pd->sidx], 0);
4683 pd->hdr.icmp->icmp_id =
4687 m_copyback(m, off, ICMP_MINLEN,
4688 (caddr_t )pd->hdr.icmp);
4693 if (PF_ANEQ(pd->src,
4694 &nk->addr[pd->sidx], AF_INET6))
4696 &pd->hdr.icmp6->icmp6_cksum,
4697 &nk->addr[pd->sidx], 0);
4699 if (PF_ANEQ(pd->dst,
4700 &nk->addr[pd->didx], AF_INET6))
4702 &pd->hdr.icmp6->icmp6_cksum,
4703 &nk->addr[pd->didx], 0);
4705 m_copyback(m, off, sizeof(struct icmp6_hdr),
4706 (caddr_t )pd->hdr.icmp6);
4715 * ICMP error message in response to a TCP/UDP packet.
4716 * Extract the inner TCP/UDP header and search for that state.
4719 struct pf_pdesc pd2;
4720 bzero(&pd2, sizeof pd2);
4725 struct ip6_hdr h2_6;
4732 /* Payload packet is from the opposite direction. */
4733 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4734 pd2.didx = (direction == PF_IN) ? 0 : 1;
4738 /* offset of h2 in mbuf chain */
4739 ipoff2 = off + ICMP_MINLEN;
4741 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4742 NULL, reason, pd2.af)) {
4743 DPFPRINTF(PF_DEBUG_MISC,
4744 ("pf: ICMP error message too short "
4749 * ICMP error messages don't refer to non-first
4752 if (h2.ip_off & htons(IP_OFFMASK)) {
4753 REASON_SET(reason, PFRES_FRAG);
4757 /* offset of protocol header that follows h2 */
4758 off2 = ipoff2 + (h2.ip_hl << 2);
4760 pd2.proto = h2.ip_p;
4761 pd2.src = (struct pf_addr *)&h2.ip_src;
4762 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4763 pd2.ip_sum = &h2.ip_sum;
4768 ipoff2 = off + sizeof(struct icmp6_hdr);
4770 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4771 NULL, reason, pd2.af)) {
4772 DPFPRINTF(PF_DEBUG_MISC,
4773 ("pf: ICMP error message too short "
4777 pd2.proto = h2_6.ip6_nxt;
4778 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4779 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4781 off2 = ipoff2 + sizeof(h2_6);
4783 switch (pd2.proto) {
4784 case IPPROTO_FRAGMENT:
4786 * ICMPv6 error messages for
4787 * non-first fragments
4789 REASON_SET(reason, PFRES_FRAG);
4792 case IPPROTO_HOPOPTS:
4793 case IPPROTO_ROUTING:
4794 case IPPROTO_DSTOPTS: {
4795 /* get next header and header length */
4796 struct ip6_ext opt6;
4798 if (!pf_pull_hdr(m, off2, &opt6,
4799 sizeof(opt6), NULL, reason,
4801 DPFPRINTF(PF_DEBUG_MISC,
4802 ("pf: ICMPv6 short opt\n"));
4805 if (pd2.proto == IPPROTO_AH)
4806 off2 += (opt6.ip6e_len + 2) * 4;
4808 off2 += (opt6.ip6e_len + 1) * 8;
4809 pd2.proto = opt6.ip6e_nxt;
4810 /* goto the next header */
4817 } while (!terminal);
4822 if (PF_ANEQ(pd->dst, pd2.src, pd->af)) {
4823 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4824 printf("pf: BAD ICMP %d:%d outer dst: ",
4825 icmptype, icmpcode);
4826 pf_print_host(pd->src, 0, pd->af);
4828 pf_print_host(pd->dst, 0, pd->af);
4829 printf(" inner src: ");
4830 pf_print_host(pd2.src, 0, pd2.af);
4832 pf_print_host(pd2.dst, 0, pd2.af);
4835 REASON_SET(reason, PFRES_BADSTATE);
4839 switch (pd2.proto) {
4843 struct pf_state_peer *src, *dst;
4848 * Only the first 8 bytes of the TCP header can be
4849 * expected. Don't access any TCP header fields after
4850 * th_seq, an ackskew test is not possible.
4852 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4854 DPFPRINTF(PF_DEBUG_MISC,
4855 ("pf: ICMP error message too short "
4861 key.proto = IPPROTO_TCP;
4862 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4863 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4864 key.port[pd2.sidx] = th.th_sport;
4865 key.port[pd2.didx] = th.th_dport;
4867 STATE_LOOKUP(kif, &key, direction, *state, pd);
4869 if (direction == (*state)->direction) {
4870 src = &(*state)->dst;
4871 dst = &(*state)->src;
4873 src = &(*state)->src;
4874 dst = &(*state)->dst;
4877 if (src->wscale && dst->wscale)
4878 dws = dst->wscale & PF_WSCALE_MASK;
4882 /* Demodulate sequence number */
4883 seq = ntohl(th.th_seq) - src->seqdiff;
4885 pf_change_a(&th.th_seq, icmpsum,
4890 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4891 (!SEQ_GEQ(src->seqhi, seq) ||
4892 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4893 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4894 printf("pf: BAD ICMP %d:%d ",
4895 icmptype, icmpcode);
4896 pf_print_host(pd->src, 0, pd->af);
4898 pf_print_host(pd->dst, 0, pd->af);
4900 pf_print_state(*state);
4901 printf(" seq=%u\n", seq);
4903 REASON_SET(reason, PFRES_BADSTATE);
4906 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4907 printf("pf: OK ICMP %d:%d ",
4908 icmptype, icmpcode);
4909 pf_print_host(pd->src, 0, pd->af);
4911 pf_print_host(pd->dst, 0, pd->af);
4913 pf_print_state(*state);
4914 printf(" seq=%u\n", seq);
4918 /* translate source/destination address, if necessary */
4919 if ((*state)->key[PF_SK_WIRE] !=
4920 (*state)->key[PF_SK_STACK]) {
4921 struct pf_state_key *nk =
4922 (*state)->key[pd->didx];
4924 if (PF_ANEQ(pd2.src,
4925 &nk->addr[pd2.sidx], pd2.af) ||
4926 nk->port[pd2.sidx] != th.th_sport)
4927 pf_change_icmp(pd2.src, &th.th_sport,
4928 daddr, &nk->addr[pd2.sidx],
4929 nk->port[pd2.sidx], NULL,
4930 pd2.ip_sum, icmpsum,
4931 pd->ip_sum, 0, pd2.af);
4933 if (PF_ANEQ(pd2.dst,
4934 &nk->addr[pd2.didx], pd2.af) ||
4935 nk->port[pd2.didx] != th.th_dport)
4936 pf_change_icmp(pd2.dst, &th.th_dport,
4937 saddr, &nk->addr[pd2.didx],
4938 nk->port[pd2.didx], NULL,
4939 pd2.ip_sum, icmpsum,
4940 pd->ip_sum, 0, pd2.af);
4948 m_copyback(m, off, ICMP_MINLEN,
4949 (caddr_t )pd->hdr.icmp);
4950 m_copyback(m, ipoff2, sizeof(h2),
4957 sizeof(struct icmp6_hdr),
4958 (caddr_t )pd->hdr.icmp6);
4959 m_copyback(m, ipoff2, sizeof(h2_6),
4964 m_copyback(m, off2, 8, (caddr_t)&th);
4973 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4974 NULL, reason, pd2.af)) {
4975 DPFPRINTF(PF_DEBUG_MISC,
4976 ("pf: ICMP error message too short "
4982 key.proto = IPPROTO_UDP;
4983 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4984 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4985 key.port[pd2.sidx] = uh.uh_sport;
4986 key.port[pd2.didx] = uh.uh_dport;
4988 STATE_LOOKUP(kif, &key, direction, *state, pd);
4990 /* translate source/destination address, if necessary */
4991 if ((*state)->key[PF_SK_WIRE] !=
4992 (*state)->key[PF_SK_STACK]) {
4993 struct pf_state_key *nk =
4994 (*state)->key[pd->didx];
4996 if (PF_ANEQ(pd2.src,
4997 &nk->addr[pd2.sidx], pd2.af) ||
4998 nk->port[pd2.sidx] != uh.uh_sport)
4999 pf_change_icmp(pd2.src, &uh.uh_sport,
5000 daddr, &nk->addr[pd2.sidx],
5001 nk->port[pd2.sidx], &uh.uh_sum,
5002 pd2.ip_sum, icmpsum,
5003 pd->ip_sum, 1, pd2.af);
5005 if (PF_ANEQ(pd2.dst,
5006 &nk->addr[pd2.didx], pd2.af) ||
5007 nk->port[pd2.didx] != uh.uh_dport)
5008 pf_change_icmp(pd2.dst, &uh.uh_dport,
5009 saddr, &nk->addr[pd2.didx],
5010 nk->port[pd2.didx], &uh.uh_sum,
5011 pd2.ip_sum, icmpsum,
5012 pd->ip_sum, 1, pd2.af);
5017 m_copyback(m, off, ICMP_MINLEN,
5018 (caddr_t )pd->hdr.icmp);
5019 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5025 sizeof(struct icmp6_hdr),
5026 (caddr_t )pd->hdr.icmp6);
5027 m_copyback(m, ipoff2, sizeof(h2_6),
5032 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5038 case IPPROTO_ICMP: {
5041 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5042 NULL, reason, pd2.af)) {
5043 DPFPRINTF(PF_DEBUG_MISC,
5044 ("pf: ICMP error message too short i"
5050 key.proto = IPPROTO_ICMP;
5051 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5052 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5053 key.port[0] = key.port[1] = iih.icmp_id;
5055 STATE_LOOKUP(kif, &key, direction, *state, pd);
5057 /* translate source/destination address, if necessary */
5058 if ((*state)->key[PF_SK_WIRE] !=
5059 (*state)->key[PF_SK_STACK]) {
5060 struct pf_state_key *nk =
5061 (*state)->key[pd->didx];
5063 if (PF_ANEQ(pd2.src,
5064 &nk->addr[pd2.sidx], pd2.af) ||
5065 nk->port[pd2.sidx] != iih.icmp_id)
5066 pf_change_icmp(pd2.src, &iih.icmp_id,
5067 daddr, &nk->addr[pd2.sidx],
5068 nk->port[pd2.sidx], NULL,
5069 pd2.ip_sum, icmpsum,
5070 pd->ip_sum, 0, AF_INET);
5072 if (PF_ANEQ(pd2.dst,
5073 &nk->addr[pd2.didx], pd2.af) ||
5074 nk->port[pd2.didx] != iih.icmp_id)
5075 pf_change_icmp(pd2.dst, &iih.icmp_id,
5076 saddr, &nk->addr[pd2.didx],
5077 nk->port[pd2.didx], NULL,
5078 pd2.ip_sum, icmpsum,
5079 pd->ip_sum, 0, AF_INET);
5081 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5082 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5083 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5090 case IPPROTO_ICMPV6: {
5091 struct icmp6_hdr iih;
5093 if (!pf_pull_hdr(m, off2, &iih,
5094 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5095 DPFPRINTF(PF_DEBUG_MISC,
5096 ("pf: ICMP error message too short "
5102 key.proto = IPPROTO_ICMPV6;
5103 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5104 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5105 key.port[0] = key.port[1] = iih.icmp6_id;
5107 STATE_LOOKUP(kif, &key, direction, *state, pd);
5109 /* translate source/destination address, if necessary */
5110 if ((*state)->key[PF_SK_WIRE] !=
5111 (*state)->key[PF_SK_STACK]) {
5112 struct pf_state_key *nk =
5113 (*state)->key[pd->didx];
5115 if (PF_ANEQ(pd2.src,
5116 &nk->addr[pd2.sidx], pd2.af) ||
5117 nk->port[pd2.sidx] != iih.icmp6_id)
5118 pf_change_icmp(pd2.src, &iih.icmp6_id,
5119 daddr, &nk->addr[pd2.sidx],
5120 nk->port[pd2.sidx], NULL,
5121 pd2.ip_sum, icmpsum,
5122 pd->ip_sum, 0, AF_INET6);
5124 if (PF_ANEQ(pd2.dst,
5125 &nk->addr[pd2.didx], pd2.af) ||
5126 nk->port[pd2.didx] != iih.icmp6_id)
5127 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5128 saddr, &nk->addr[pd2.didx],
5129 nk->port[pd2.didx], NULL,
5130 pd2.ip_sum, icmpsum,
5131 pd->ip_sum, 0, AF_INET6);
5133 m_copyback(m, off, sizeof(struct icmp6_hdr),
5134 (caddr_t)pd->hdr.icmp6);
5135 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5136 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5145 key.proto = pd2.proto;
5146 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5147 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5148 key.port[0] = key.port[1] = 0;
5150 STATE_LOOKUP(kif, &key, direction, *state, pd);
5152 /* translate source/destination address, if necessary */
5153 if ((*state)->key[PF_SK_WIRE] !=
5154 (*state)->key[PF_SK_STACK]) {
5155 struct pf_state_key *nk =
5156 (*state)->key[pd->didx];
5158 if (PF_ANEQ(pd2.src,
5159 &nk->addr[pd2.sidx], pd2.af))
5160 pf_change_icmp(pd2.src, NULL, daddr,
5161 &nk->addr[pd2.sidx], 0, NULL,
5162 pd2.ip_sum, icmpsum,
5163 pd->ip_sum, 0, pd2.af);
5165 if (PF_ANEQ(pd2.dst,
5166 &nk->addr[pd2.didx], pd2.af))
5167 pf_change_icmp(pd2.dst, NULL, saddr,
5168 &nk->addr[pd2.didx], 0, NULL,
5169 pd2.ip_sum, icmpsum,
5170 pd->ip_sum, 0, pd2.af);
5175 m_copyback(m, off, ICMP_MINLEN,
5176 (caddr_t)pd->hdr.icmp);
5177 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5183 sizeof(struct icmp6_hdr),
5184 (caddr_t )pd->hdr.icmp6);
5185 m_copyback(m, ipoff2, sizeof(h2_6),
5199 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5200 struct mbuf *m, struct pf_pdesc *pd)
5202 struct pf_state_peer *src, *dst;
5203 struct pf_state_key_cmp key;
5205 bzero(&key, sizeof(key));
5207 key.proto = pd->proto;
5208 if (direction == PF_IN) {
5209 PF_ACPY(&key.addr[0], pd->src, key.af);
5210 PF_ACPY(&key.addr[1], pd->dst, key.af);
5211 key.port[0] = key.port[1] = 0;
5213 PF_ACPY(&key.addr[1], pd->src, key.af);
5214 PF_ACPY(&key.addr[0], pd->dst, key.af);
5215 key.port[1] = key.port[0] = 0;
5218 STATE_LOOKUP(kif, &key, direction, *state, pd);
5220 if (direction == (*state)->direction) {
5221 src = &(*state)->src;
5222 dst = &(*state)->dst;
5224 src = &(*state)->dst;
5225 dst = &(*state)->src;
5229 if (src->state < PFOTHERS_SINGLE)
5230 src->state = PFOTHERS_SINGLE;
5231 if (dst->state == PFOTHERS_SINGLE)
5232 dst->state = PFOTHERS_MULTIPLE;
5234 /* update expire time */
5235 (*state)->expire = time_uptime;
5236 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5237 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5239 (*state)->timeout = PFTM_OTHER_SINGLE;
5241 /* translate source/destination address, if necessary */
5242 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5243 struct pf_state_key *nk = (*state)->key[pd->didx];
5245 KASSERT(nk, ("%s: nk is null", __func__));
5246 KASSERT(pd, ("%s: pd is null", __func__));
5247 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5248 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5252 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5253 pf_change_a(&pd->src->v4.s_addr,
5255 nk->addr[pd->sidx].v4.s_addr,
5259 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5260 pf_change_a(&pd->dst->v4.s_addr,
5262 nk->addr[pd->didx].v4.s_addr,
5269 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5270 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5272 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5273 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5281 * ipoff and off are measured from the start of the mbuf chain.
5282 * h must be at "ipoff" on the mbuf chain.
5285 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5286 u_short *actionp, u_short *reasonp, sa_family_t af)
5291 struct ip *h = mtod(m, struct ip *);
5292 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5296 ACTION_SET(actionp, PF_PASS);
5298 ACTION_SET(actionp, PF_DROP);
5299 REASON_SET(reasonp, PFRES_FRAG);
5303 if (m->m_pkthdr.len < off + len ||
5304 ntohs(h->ip_len) < off + len) {
5305 ACTION_SET(actionp, PF_DROP);
5306 REASON_SET(reasonp, PFRES_SHORT);
5314 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5316 if (m->m_pkthdr.len < off + len ||
5317 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5318 (unsigned)(off + len)) {
5319 ACTION_SET(actionp, PF_DROP);
5320 REASON_SET(reasonp, PFRES_SHORT);
5327 m_copydata(m, off, len, p);
5333 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5336 struct radix_node_head *rnh;
5337 struct sockaddr_in *dst;
5341 struct sockaddr_in6 *dst6;
5342 struct route_in6 ro;
5346 struct radix_node *rn;
5351 /* XXX: stick to table 0 for now */
5352 rnh = rt_tables_get_rnh(0, af);
5353 if (rnh != NULL && rn_mpath_capable(rnh))
5355 bzero(&ro, sizeof(ro));
5358 dst = satosin(&ro.ro_dst);
5359 dst->sin_family = AF_INET;
5360 dst->sin_len = sizeof(*dst);
5361 dst->sin_addr = addr->v4;
5366 * Skip check for addresses with embedded interface scope,
5367 * as they would always match anyway.
5369 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5371 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5372 dst6->sin6_family = AF_INET6;
5373 dst6->sin6_len = sizeof(*dst6);
5374 dst6->sin6_addr = addr->v6;
5381 /* Skip checks for ipsec interfaces */
5382 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5388 in6_rtalloc_ign(&ro, 0, rtableid);
5393 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5398 if (ro.ro_rt != NULL) {
5399 /* No interface given, this is a no-route check */
5403 if (kif->pfik_ifp == NULL) {
5408 /* Perform uRPF check if passed input interface */
5410 rn = (struct radix_node *)ro.ro_rt;
5412 rt = (struct rtentry *)rn;
5415 if (kif->pfik_ifp == ifp)
5417 rn = rn_mpath_next(rn);
5418 } while (check_mpath == 1 && rn != NULL && ret == 0);
5422 if (ro.ro_rt != NULL)
5429 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5433 struct nhop4_basic nh4;
5436 struct nhop6_basic nh6;
5440 struct radix_node_head *rnh;
5442 /* XXX: stick to table 0 for now */
5443 rnh = rt_tables_get_rnh(0, af);
5444 if (rnh != NULL && rn_mpath_capable(rnh))
5445 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5448 * Skip check for addresses with embedded interface scope,
5449 * as they would always match anyway.
5451 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5454 if (af != AF_INET && af != AF_INET6)
5457 /* Skip checks for ipsec interfaces */
5458 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5466 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5473 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5480 /* No interface given, this is a no-route check */
5484 if (kif->pfik_ifp == NULL)
5487 /* Perform uRPF check if passed input interface */
5488 if (kif->pfik_ifp == ifp)
5495 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5496 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5498 struct mbuf *m0, *m1;
5499 struct sockaddr_in dst;
5501 struct ifnet *ifp = NULL;
5502 struct pf_addr naddr;
5503 struct pf_src_node *sn = NULL;
5505 uint16_t ip_len, ip_off;
5507 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5508 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5511 if ((pd->pf_mtag == NULL &&
5512 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5513 pd->pf_mtag->routed++ > 3) {
5519 if (r->rt == PF_DUPTO) {
5520 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5526 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5534 ip = mtod(m0, struct ip *);
5536 bzero(&dst, sizeof(dst));
5537 dst.sin_family = AF_INET;
5538 dst.sin_len = sizeof(dst);
5539 dst.sin_addr = ip->ip_dst;
5541 bzero(&naddr, sizeof(naddr));
5543 if (TAILQ_EMPTY(&r->rpool.list)) {
5544 DPFPRINTF(PF_DEBUG_URGENT,
5545 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5549 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5551 if (!PF_AZERO(&naddr, AF_INET))
5552 dst.sin_addr.s_addr = naddr.v4.s_addr;
5553 ifp = r->rpool.cur->kif ?
5554 r->rpool.cur->kif->pfik_ifp : NULL;
5556 if (!PF_AZERO(&s->rt_addr, AF_INET))
5557 dst.sin_addr.s_addr =
5558 s->rt_addr.v4.s_addr;
5559 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5566 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5568 else if (m0 == NULL)
5570 if (m0->m_len < sizeof(struct ip)) {
5571 DPFPRINTF(PF_DEBUG_URGENT,
5572 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5575 ip = mtod(m0, struct ip *);
5578 if (ifp->if_flags & IFF_LOOPBACK)
5579 m0->m_flags |= M_SKIP_FIREWALL;
5581 ip_len = ntohs(ip->ip_len);
5582 ip_off = ntohs(ip->ip_off);
5584 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5585 m0->m_pkthdr.csum_flags |= CSUM_IP;
5586 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5587 in_delayed_cksum(m0);
5588 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5591 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5592 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5593 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5598 * If small enough for interface, or the interface will take
5599 * care of the fragmentation for us, we can just send directly.
5601 if (ip_len <= ifp->if_mtu ||
5602 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5604 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5605 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5606 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5608 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5609 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5613 /* Balk when DF bit is set or the interface didn't support TSO. */
5614 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5616 KMOD_IPSTAT_INC(ips_cantfrag);
5617 if (r->rt != PF_DUPTO) {
5618 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5625 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5629 for (; m0; m0 = m1) {
5631 m0->m_nextpkt = NULL;
5633 m_clrprotoflags(m0);
5634 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5640 KMOD_IPSTAT_INC(ips_fragmented);
5643 if (r->rt != PF_DUPTO)
5658 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5659 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5662 struct sockaddr_in6 dst;
5663 struct ip6_hdr *ip6;
5664 struct ifnet *ifp = NULL;
5665 struct pf_addr naddr;
5666 struct pf_src_node *sn = NULL;
5668 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5669 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5672 if ((pd->pf_mtag == NULL &&
5673 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5674 pd->pf_mtag->routed++ > 3) {
5680 if (r->rt == PF_DUPTO) {
5681 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5687 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5695 ip6 = mtod(m0, struct ip6_hdr *);
5697 bzero(&dst, sizeof(dst));
5698 dst.sin6_family = AF_INET6;
5699 dst.sin6_len = sizeof(dst);
5700 dst.sin6_addr = ip6->ip6_dst;
5702 bzero(&naddr, sizeof(naddr));
5704 if (TAILQ_EMPTY(&r->rpool.list)) {
5705 DPFPRINTF(PF_DEBUG_URGENT,
5706 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5710 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5712 if (!PF_AZERO(&naddr, AF_INET6))
5713 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5715 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5717 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5718 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5719 &s->rt_addr, AF_INET6);
5720 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5730 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5732 else if (m0 == NULL)
5734 if (m0->m_len < sizeof(struct ip6_hdr)) {
5735 DPFPRINTF(PF_DEBUG_URGENT,
5736 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5740 ip6 = mtod(m0, struct ip6_hdr *);
5743 if (ifp->if_flags & IFF_LOOPBACK)
5744 m0->m_flags |= M_SKIP_FIREWALL;
5746 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5747 ~ifp->if_hwassist) {
5748 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5749 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5750 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5754 * If the packet is too large for the outgoing interface,
5755 * send back an icmp6 error.
5757 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5758 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5759 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5760 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5762 in6_ifstat_inc(ifp, ifs6_in_toobig);
5763 if (r->rt != PF_DUPTO)
5764 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5770 if (r->rt != PF_DUPTO)
5784 * FreeBSD supports cksum offloads for the following drivers.
5785 * em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5787 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5788 * network driver performed cksum including pseudo header, need to verify
5791 * network driver performed cksum, needs to additional pseudo header
5792 * cksum computation with partial csum_data(i.e. lack of H/W support for
5793 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5795 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5796 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5798 * Also, set csum_data to 0xffff to force cksum validation.
5801 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5807 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5809 if (m->m_pkthdr.len < off + len)
5814 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5815 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5816 sum = m->m_pkthdr.csum_data;
5818 ip = mtod(m, struct ip *);
5819 sum = in_pseudo(ip->ip_src.s_addr,
5820 ip->ip_dst.s_addr, htonl((u_short)len +
5821 m->m_pkthdr.csum_data + IPPROTO_TCP));
5828 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5829 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5830 sum = m->m_pkthdr.csum_data;
5832 ip = mtod(m, struct ip *);
5833 sum = in_pseudo(ip->ip_src.s_addr,
5834 ip->ip_dst.s_addr, htonl((u_short)len +
5835 m->m_pkthdr.csum_data + IPPROTO_UDP));
5843 case IPPROTO_ICMPV6:
5853 if (p == IPPROTO_ICMP) {
5858 sum = in_cksum(m, len);
5862 if (m->m_len < sizeof(struct ip))
5864 sum = in4_cksum(m, p, off, len);
5869 if (m->m_len < sizeof(struct ip6_hdr))
5871 sum = in6_cksum(m, p, off, len);
5882 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5887 KMOD_UDPSTAT_INC(udps_badsum);
5893 KMOD_ICMPSTAT_INC(icps_checksum);
5898 case IPPROTO_ICMPV6:
5900 KMOD_ICMP6STAT_INC(icp6s_checksum);
5907 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5908 m->m_pkthdr.csum_flags |=
5909 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5910 m->m_pkthdr.csum_data = 0xffff;
5919 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5921 struct pfi_kif *kif;
5922 u_short action, reason = 0, log = 0;
5923 struct mbuf *m = *m0;
5924 struct ip *h = NULL;
5925 struct m_tag *ipfwtag;
5926 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5927 struct pf_state *s = NULL;
5928 struct pf_ruleset *ruleset = NULL;
5930 int off, dirndx, pqid = 0;
5932 PF_RULES_RLOCK_TRACKER;
5936 if (!V_pf_status.running)
5939 memset(&pd, 0, sizeof(pd));
5941 kif = (struct pfi_kif *)ifp->if_pf_kif;
5944 DPFPRINTF(PF_DEBUG_URGENT,
5945 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5948 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5951 if (m->m_flags & M_SKIP_FIREWALL)
5954 pd.pf_mtag = pf_find_mtag(m);
5958 if (ip_divert_ptr != NULL &&
5959 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5960 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5961 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5962 if (pd.pf_mtag == NULL &&
5963 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5967 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5968 m_tag_delete(m, ipfwtag);
5970 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5971 m->m_flags |= M_FASTFWD_OURS;
5972 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5974 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5975 /* We do IP header normalization and packet reassembly here */
5979 m = *m0; /* pf_normalize messes with m0 */
5980 h = mtod(m, struct ip *);
5982 off = h->ip_hl << 2;
5983 if (off < (int)sizeof(struct ip)) {
5985 REASON_SET(&reason, PFRES_SHORT);
5990 pd.src = (struct pf_addr *)&h->ip_src;
5991 pd.dst = (struct pf_addr *)&h->ip_dst;
5992 pd.sport = pd.dport = NULL;
5993 pd.ip_sum = &h->ip_sum;
5994 pd.proto_sum = NULL;
5997 pd.sidx = (dir == PF_IN) ? 0 : 1;
5998 pd.didx = (dir == PF_IN) ? 1 : 0;
6000 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
6001 pd.tot_len = ntohs(h->ip_len);
6003 /* handle fragments that didn't get reassembled by normalization */
6004 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
6005 action = pf_test_fragment(&r, dir, kif, m, h,
6016 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6017 &action, &reason, AF_INET)) {
6018 log = action != PF_PASS;
6021 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6022 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6024 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6025 if (action == PF_DROP)
6027 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6029 if (action == PF_PASS) {
6030 if (V_pfsync_update_state_ptr != NULL)
6031 V_pfsync_update_state_ptr(s);
6035 } else if (s == NULL)
6036 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6045 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6046 &action, &reason, AF_INET)) {
6047 log = action != PF_PASS;
6050 if (uh.uh_dport == 0 ||
6051 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6052 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6054 REASON_SET(&reason, PFRES_SHORT);
6057 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6058 if (action == PF_PASS) {
6059 if (V_pfsync_update_state_ptr != NULL)
6060 V_pfsync_update_state_ptr(s);
6064 } else if (s == NULL)
6065 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6070 case IPPROTO_ICMP: {
6074 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6075 &action, &reason, AF_INET)) {
6076 log = action != PF_PASS;
6079 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6081 if (action == PF_PASS) {
6082 if (V_pfsync_update_state_ptr != NULL)
6083 V_pfsync_update_state_ptr(s);
6087 } else if (s == NULL)
6088 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6094 case IPPROTO_ICMPV6: {
6096 DPFPRINTF(PF_DEBUG_MISC,
6097 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6103 action = pf_test_state_other(&s, dir, kif, m, &pd);
6104 if (action == PF_PASS) {
6105 if (V_pfsync_update_state_ptr != NULL)
6106 V_pfsync_update_state_ptr(s);
6110 } else if (s == NULL)
6111 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6118 if (action == PF_PASS && h->ip_hl > 5 &&
6119 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6121 REASON_SET(&reason, PFRES_IPOPTIONS);
6123 DPFPRINTF(PF_DEBUG_MISC,
6124 ("pf: dropping packet with ip options\n"));
6127 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6129 REASON_SET(&reason, PFRES_MEMORY);
6131 if (r->rtableid >= 0)
6132 M_SETFIB(m, r->rtableid);
6134 if (r->scrub_flags & PFSTATE_SETPRIO) {
6135 if (pd.tos & IPTOS_LOWDELAY)
6137 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6139 REASON_SET(&reason, PFRES_MEMORY);
6141 DPFPRINTF(PF_DEBUG_MISC,
6142 ("pf: failed to allocate 802.1q mtag\n"));
6147 if (action == PF_PASS && r->qid) {
6148 if (pd.pf_mtag == NULL &&
6149 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6151 REASON_SET(&reason, PFRES_MEMORY);
6154 pd.pf_mtag->qid_hash = pf_state_hash(s);
6155 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6156 pd.pf_mtag->qid = r->pqid;
6158 pd.pf_mtag->qid = r->qid;
6159 /* Add hints for ecn. */
6160 pd.pf_mtag->hdr = h;
6167 * connections redirected to loopback should not match sockets
6168 * bound specifically to loopback due to security implications,
6169 * see tcp_input() and in_pcblookup_listen().
6171 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6172 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6173 (s->nat_rule.ptr->action == PF_RDR ||
6174 s->nat_rule.ptr->action == PF_BINAT) &&
6175 IN_LOOPBACK(ntohl(pd.dst->v4.s_addr)))
6176 m->m_flags |= M_SKIP_FIREWALL;
6178 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6179 !PACKET_LOOPED(&pd)) {
6181 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6182 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6183 if (ipfwtag != NULL) {
6184 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6185 ntohs(r->divert.port);
6186 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6191 m_tag_prepend(m, ipfwtag);
6192 if (m->m_flags & M_FASTFWD_OURS) {
6193 if (pd.pf_mtag == NULL &&
6194 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6196 REASON_SET(&reason, PFRES_MEMORY);
6198 DPFPRINTF(PF_DEBUG_MISC,
6199 ("pf: failed to allocate tag\n"));
6201 pd.pf_mtag->flags |=
6202 PF_FASTFWD_OURS_PRESENT;
6203 m->m_flags &= ~M_FASTFWD_OURS;
6206 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6211 /* XXX: ipfw has the same behaviour! */
6213 REASON_SET(&reason, PFRES_MEMORY);
6215 DPFPRINTF(PF_DEBUG_MISC,
6216 ("pf: failed to allocate divert tag\n"));
6223 if (s != NULL && s->nat_rule.ptr != NULL &&
6224 s->nat_rule.ptr->log & PF_LOG_ALL)
6225 lr = s->nat_rule.ptr;
6228 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6232 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6233 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6235 if (action == PF_PASS || r->action == PF_DROP) {
6236 dirndx = (dir == PF_OUT);
6237 r->packets[dirndx]++;
6238 r->bytes[dirndx] += pd.tot_len;
6240 a->packets[dirndx]++;
6241 a->bytes[dirndx] += pd.tot_len;
6244 if (s->nat_rule.ptr != NULL) {
6245 s->nat_rule.ptr->packets[dirndx]++;
6246 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6248 if (s->src_node != NULL) {
6249 s->src_node->packets[dirndx]++;
6250 s->src_node->bytes[dirndx] += pd.tot_len;
6252 if (s->nat_src_node != NULL) {
6253 s->nat_src_node->packets[dirndx]++;
6254 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6256 dirndx = (dir == s->direction) ? 0 : 1;
6257 s->packets[dirndx]++;
6258 s->bytes[dirndx] += pd.tot_len;
6261 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6262 if (nr != NULL && r == &V_pf_default_rule)
6264 if (tr->src.addr.type == PF_ADDR_TABLE)
6265 pfr_update_stats(tr->src.addr.p.tbl,
6266 (s == NULL) ? pd.src :
6267 &s->key[(s->direction == PF_IN)]->
6268 addr[(s->direction == PF_OUT)],
6269 pd.af, pd.tot_len, dir == PF_OUT,
6270 r->action == PF_PASS, tr->src.neg);
6271 if (tr->dst.addr.type == PF_ADDR_TABLE)
6272 pfr_update_stats(tr->dst.addr.p.tbl,
6273 (s == NULL) ? pd.dst :
6274 &s->key[(s->direction == PF_IN)]->
6275 addr[(s->direction == PF_IN)],
6276 pd.af, pd.tot_len, dir == PF_OUT,
6277 r->action == PF_PASS, tr->dst.neg);
6281 case PF_SYNPROXY_DROP:
6292 /* pf_route() returns unlocked. */
6294 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6308 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6310 struct pfi_kif *kif;
6311 u_short action, reason = 0, log = 0;
6312 struct mbuf *m = *m0, *n = NULL;
6314 struct ip6_hdr *h = NULL;
6315 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6316 struct pf_state *s = NULL;
6317 struct pf_ruleset *ruleset = NULL;
6319 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6321 PF_RULES_RLOCK_TRACKER;
6324 if (!V_pf_status.running)
6327 memset(&pd, 0, sizeof(pd));
6328 pd.pf_mtag = pf_find_mtag(m);
6330 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6333 kif = (struct pfi_kif *)ifp->if_pf_kif;
6335 DPFPRINTF(PF_DEBUG_URGENT,
6336 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6339 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6342 if (m->m_flags & M_SKIP_FIREWALL)
6347 /* We do IP header normalization and packet reassembly here */
6348 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6352 m = *m0; /* pf_normalize messes with m0 */
6353 h = mtod(m, struct ip6_hdr *);
6357 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6358 * will do something bad, so drop the packet for now.
6360 if (htons(h->ip6_plen) == 0) {
6362 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6367 pd.src = (struct pf_addr *)&h->ip6_src;
6368 pd.dst = (struct pf_addr *)&h->ip6_dst;
6369 pd.sport = pd.dport = NULL;
6371 pd.proto_sum = NULL;
6373 pd.sidx = (dir == PF_IN) ? 0 : 1;
6374 pd.didx = (dir == PF_IN) ? 1 : 0;
6377 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6379 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6380 pd.proto = h->ip6_nxt;
6383 case IPPROTO_FRAGMENT:
6384 action = pf_test_fragment(&r, dir, kif, m, h,
6386 if (action == PF_DROP)
6387 REASON_SET(&reason, PFRES_FRAG);
6389 case IPPROTO_ROUTING: {
6390 struct ip6_rthdr rthdr;
6393 DPFPRINTF(PF_DEBUG_MISC,
6394 ("pf: IPv6 more than one rthdr\n"));
6396 REASON_SET(&reason, PFRES_IPOPTIONS);
6400 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6402 DPFPRINTF(PF_DEBUG_MISC,
6403 ("pf: IPv6 short rthdr\n"));
6405 REASON_SET(&reason, PFRES_SHORT);
6409 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6410 DPFPRINTF(PF_DEBUG_MISC,
6411 ("pf: IPv6 rthdr0\n"));
6413 REASON_SET(&reason, PFRES_IPOPTIONS);
6420 case IPPROTO_HOPOPTS:
6421 case IPPROTO_DSTOPTS: {
6422 /* get next header and header length */
6423 struct ip6_ext opt6;
6425 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6426 NULL, &reason, pd.af)) {
6427 DPFPRINTF(PF_DEBUG_MISC,
6428 ("pf: IPv6 short opt\n"));
6433 if (pd.proto == IPPROTO_AH)
6434 off += (opt6.ip6e_len + 2) * 4;
6436 off += (opt6.ip6e_len + 1) * 8;
6437 pd.proto = opt6.ip6e_nxt;
6438 /* goto the next header */
6445 } while (!terminal);
6447 /* if there's no routing header, use unmodified mbuf for checksumming */
6457 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6458 &action, &reason, AF_INET6)) {
6459 log = action != PF_PASS;
6462 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6463 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6464 if (action == PF_DROP)
6466 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6468 if (action == PF_PASS) {
6469 if (V_pfsync_update_state_ptr != NULL)
6470 V_pfsync_update_state_ptr(s);
6474 } else if (s == NULL)
6475 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6484 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6485 &action, &reason, AF_INET6)) {
6486 log = action != PF_PASS;
6489 if (uh.uh_dport == 0 ||
6490 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6491 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6493 REASON_SET(&reason, PFRES_SHORT);
6496 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6497 if (action == PF_PASS) {
6498 if (V_pfsync_update_state_ptr != NULL)
6499 V_pfsync_update_state_ptr(s);
6503 } else if (s == NULL)
6504 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6509 case IPPROTO_ICMP: {
6511 DPFPRINTF(PF_DEBUG_MISC,
6512 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6516 case IPPROTO_ICMPV6: {
6517 struct icmp6_hdr ih;
6520 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6521 &action, &reason, AF_INET6)) {
6522 log = action != PF_PASS;
6525 action = pf_test_state_icmp(&s, dir, kif,
6526 m, off, h, &pd, &reason);
6527 if (action == PF_PASS) {
6528 if (V_pfsync_update_state_ptr != NULL)
6529 V_pfsync_update_state_ptr(s);
6533 } else if (s == NULL)
6534 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6540 action = pf_test_state_other(&s, dir, kif, m, &pd);
6541 if (action == PF_PASS) {
6542 if (V_pfsync_update_state_ptr != NULL)
6543 V_pfsync_update_state_ptr(s);
6547 } else if (s == NULL)
6548 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6560 /* handle dangerous IPv6 extension headers. */
6561 if (action == PF_PASS && rh_cnt &&
6562 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6564 REASON_SET(&reason, PFRES_IPOPTIONS);
6566 DPFPRINTF(PF_DEBUG_MISC,
6567 ("pf: dropping packet with dangerous v6 headers\n"));
6570 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6572 REASON_SET(&reason, PFRES_MEMORY);
6574 if (r->rtableid >= 0)
6575 M_SETFIB(m, r->rtableid);
6577 if (r->scrub_flags & PFSTATE_SETPRIO) {
6578 if (pd.tos & IPTOS_LOWDELAY)
6580 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6582 REASON_SET(&reason, PFRES_MEMORY);
6584 DPFPRINTF(PF_DEBUG_MISC,
6585 ("pf: failed to allocate 802.1q mtag\n"));
6590 if (action == PF_PASS && r->qid) {
6591 if (pd.pf_mtag == NULL &&
6592 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6594 REASON_SET(&reason, PFRES_MEMORY);
6597 pd.pf_mtag->qid_hash = pf_state_hash(s);
6598 if (pd.tos & IPTOS_LOWDELAY)
6599 pd.pf_mtag->qid = r->pqid;
6601 pd.pf_mtag->qid = r->qid;
6602 /* Add hints for ecn. */
6603 pd.pf_mtag->hdr = h;
6608 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6609 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6610 (s->nat_rule.ptr->action == PF_RDR ||
6611 s->nat_rule.ptr->action == PF_BINAT) &&
6612 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6613 m->m_flags |= M_SKIP_FIREWALL;
6615 /* XXX: Anybody working on it?! */
6617 printf("pf: divert(9) is not supported for IPv6\n");
6622 if (s != NULL && s->nat_rule.ptr != NULL &&
6623 s->nat_rule.ptr->log & PF_LOG_ALL)
6624 lr = s->nat_rule.ptr;
6627 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6631 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6632 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6634 if (action == PF_PASS || r->action == PF_DROP) {
6635 dirndx = (dir == PF_OUT);
6636 r->packets[dirndx]++;
6637 r->bytes[dirndx] += pd.tot_len;
6639 a->packets[dirndx]++;
6640 a->bytes[dirndx] += pd.tot_len;
6643 if (s->nat_rule.ptr != NULL) {
6644 s->nat_rule.ptr->packets[dirndx]++;
6645 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6647 if (s->src_node != NULL) {
6648 s->src_node->packets[dirndx]++;
6649 s->src_node->bytes[dirndx] += pd.tot_len;
6651 if (s->nat_src_node != NULL) {
6652 s->nat_src_node->packets[dirndx]++;
6653 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6655 dirndx = (dir == s->direction) ? 0 : 1;
6656 s->packets[dirndx]++;
6657 s->bytes[dirndx] += pd.tot_len;
6660 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6661 if (nr != NULL && r == &V_pf_default_rule)
6663 if (tr->src.addr.type == PF_ADDR_TABLE)
6664 pfr_update_stats(tr->src.addr.p.tbl,
6665 (s == NULL) ? pd.src :
6666 &s->key[(s->direction == PF_IN)]->addr[0],
6667 pd.af, pd.tot_len, dir == PF_OUT,
6668 r->action == PF_PASS, tr->src.neg);
6669 if (tr->dst.addr.type == PF_ADDR_TABLE)
6670 pfr_update_stats(tr->dst.addr.p.tbl,
6671 (s == NULL) ? pd.dst :
6672 &s->key[(s->direction == PF_IN)]->addr[1],
6673 pd.af, pd.tot_len, dir == PF_OUT,
6674 r->action == PF_PASS, tr->dst.neg);
6678 case PF_SYNPROXY_DROP:
6689 /* pf_route6() returns unlocked. */
6691 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6700 /* If reassembled packet passed, create new fragments. */
6701 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6702 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6703 action = pf_refragment6(ifp, m0, mtag);