2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2001 Daniel Hartmeier
5 * Copyright (c) 2002 - 2008 Henning Brauer
6 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * - Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * - Redistributions in binary form must reproduce the above
16 * copyright notice, this list of conditions and the following
17 * disclaimer in the documentation and/or other materials provided
18 * with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
33 * Effort sponsored in part by the Defense Advanced Research Projects
34 * Agency (DARPA) and Air Force Research Laboratory, Air Force
35 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
37 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
44 #include "opt_inet6.h"
48 #include <sys/param.h>
50 #include <sys/endian.h>
52 #include <sys/interrupt.h>
53 #include <sys/kernel.h>
54 #include <sys/kthread.h>
55 #include <sys/limits.h>
58 #include <sys/random.h>
59 #include <sys/refcount.h>
60 #include <sys/socket.h>
61 #include <sys/sysctl.h>
62 #include <sys/taskqueue.h>
63 #include <sys/ucred.h>
66 #include <net/if_var.h>
67 #include <net/if_types.h>
68 #include <net/if_vlan_var.h>
69 #include <net/route.h>
70 #include <net/radix_mpath.h>
74 #include <net/pfvar.h>
75 #include <net/if_pflog.h>
76 #include <net/if_pfsync.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_var.h>
80 #include <netinet/in_fib.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_fw.h>
83 #include <netinet/ip_icmp.h>
84 #include <netinet/icmp_var.h>
85 #include <netinet/ip_var.h>
86 #include <netinet/tcp.h>
87 #include <netinet/tcp_fsm.h>
88 #include <netinet/tcp_seq.h>
89 #include <netinet/tcp_timer.h>
90 #include <netinet/tcp_var.h>
91 #include <netinet/udp.h>
92 #include <netinet/udp_var.h>
94 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
97 #include <netinet/ip6.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/nd6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/in6_pcb.h>
102 #include <netinet6/in6_fib.h>
103 #include <netinet6/scope6_var.h>
106 #include <machine/in_cksum.h>
107 #include <security/mac/mac_framework.h>
109 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
116 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
117 VNET_DEFINE(struct pf_palist, pf_pabuf);
118 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
119 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
120 VNET_DEFINE(struct pf_kstatus, pf_status);
122 VNET_DEFINE(u_int32_t, ticket_altqs_active);
123 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
124 VNET_DEFINE(int, altqs_inactive_open);
125 VNET_DEFINE(u_int32_t, ticket_pabuf);
127 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
128 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
129 VNET_DEFINE(u_char, pf_tcp_secret[16]);
130 #define V_pf_tcp_secret VNET(pf_tcp_secret)
131 VNET_DEFINE(int, pf_tcp_secret_init);
132 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
133 VNET_DEFINE(int, pf_tcp_iss_off);
134 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
135 VNET_DECLARE(int, pf_vnet_active);
136 #define V_pf_vnet_active VNET(pf_vnet_active)
138 static VNET_DEFINE(uint32_t, pf_purge_idx);
139 #define V_pf_purge_idx VNET(pf_purge_idx)
142 * Queue for pf_intr() sends.
144 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
145 struct pf_send_entry {
146 STAILQ_ENTRY(pf_send_entry) pfse_next;
161 STAILQ_HEAD(pf_send_head, pf_send_entry);
162 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
163 #define V_pf_sendqueue VNET(pf_sendqueue)
165 static struct mtx pf_sendqueue_mtx;
166 MTX_SYSINIT(pf_sendqueue_mtx, &pf_sendqueue_mtx, "pf send queue", MTX_DEF);
167 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
168 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
171 * Queue for pf_overload_task() tasks.
173 struct pf_overload_entry {
174 SLIST_ENTRY(pf_overload_entry) next;
178 struct pf_rule *rule;
181 SLIST_HEAD(pf_overload_head, pf_overload_entry);
182 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
183 #define V_pf_overloadqueue VNET(pf_overloadqueue)
184 static VNET_DEFINE(struct task, pf_overloadtask);
185 #define V_pf_overloadtask VNET(pf_overloadtask)
187 static struct mtx pf_overloadqueue_mtx;
188 MTX_SYSINIT(pf_overloadqueue_mtx, &pf_overloadqueue_mtx,
189 "pf overload/flush queue", MTX_DEF);
190 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
191 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
193 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
194 struct mtx pf_unlnkdrules_mtx;
195 MTX_SYSINIT(pf_unlnkdrules_mtx, &pf_unlnkdrules_mtx, "pf unlinked rules",
198 static VNET_DEFINE(uma_zone_t, pf_sources_z);
199 #define V_pf_sources_z VNET(pf_sources_z)
200 uma_zone_t pf_mtag_z;
201 VNET_DEFINE(uma_zone_t, pf_state_z);
202 VNET_DEFINE(uma_zone_t, pf_state_key_z);
204 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
205 #define PFID_CPUBITS 8
206 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
207 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
208 #define PFID_MAXID (~PFID_CPUMASK)
209 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
211 static void pf_src_tree_remove_state(struct pf_state *);
212 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
214 static void pf_add_threshold(struct pf_threshold *);
215 static int pf_check_threshold(struct pf_threshold *);
217 static void pf_change_ap(struct mbuf *, struct pf_addr *, u_int16_t *,
218 u_int16_t *, u_int16_t *, struct pf_addr *,
219 u_int16_t, u_int8_t, sa_family_t);
220 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
221 struct tcphdr *, struct pf_state_peer *);
222 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
223 struct pf_addr *, struct pf_addr *, u_int16_t,
224 u_int16_t *, u_int16_t *, u_int16_t *,
225 u_int16_t *, u_int8_t, sa_family_t);
226 static void pf_send_tcp(struct mbuf *,
227 const struct pf_rule *, sa_family_t,
228 const struct pf_addr *, const struct pf_addr *,
229 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
230 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
231 u_int16_t, struct ifnet *);
232 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
233 sa_family_t, struct pf_rule *);
234 static void pf_detach_state(struct pf_state *);
235 static int pf_state_key_attach(struct pf_state_key *,
236 struct pf_state_key *, struct pf_state *);
237 static void pf_state_key_detach(struct pf_state *, int);
238 static int pf_state_key_ctor(void *, int, void *, int);
239 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
240 static int pf_test_rule(struct pf_rule **, struct pf_state **,
241 int, struct pfi_kif *, struct mbuf *, int,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **, struct inpcb *);
244 static int pf_create_state(struct pf_rule *, struct pf_rule *,
245 struct pf_rule *, struct pf_pdesc *,
246 struct pf_src_node *, struct pf_state_key *,
247 struct pf_state_key *, struct mbuf *, int,
248 u_int16_t, u_int16_t, int *, struct pfi_kif *,
249 struct pf_state **, int, u_int16_t, u_int16_t,
251 static int pf_test_fragment(struct pf_rule **, int,
252 struct pfi_kif *, struct mbuf *, void *,
253 struct pf_pdesc *, struct pf_rule **,
254 struct pf_ruleset **);
255 static int pf_tcp_track_full(struct pf_state_peer *,
256 struct pf_state_peer *, struct pf_state **,
257 struct pfi_kif *, struct mbuf *, int,
258 struct pf_pdesc *, u_short *, int *);
259 static int pf_tcp_track_sloppy(struct pf_state_peer *,
260 struct pf_state_peer *, struct pf_state **,
261 struct pf_pdesc *, u_short *);
262 static int pf_test_state_tcp(struct pf_state **, int,
263 struct pfi_kif *, struct mbuf *, int,
264 void *, struct pf_pdesc *, u_short *);
265 static int pf_test_state_udp(struct pf_state **, int,
266 struct pfi_kif *, struct mbuf *, int,
267 void *, struct pf_pdesc *);
268 static int pf_test_state_icmp(struct pf_state **, int,
269 struct pfi_kif *, struct mbuf *, int,
270 void *, struct pf_pdesc *, u_short *);
271 static int pf_test_state_other(struct pf_state **, int,
272 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
273 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
275 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
277 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
279 static int pf_check_proto_cksum(struct mbuf *, int, int,
280 u_int8_t, sa_family_t);
281 static void pf_print_state_parts(struct pf_state *,
282 struct pf_state_key *, struct pf_state_key *);
283 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
284 struct pf_addr_wrap *);
285 static struct pf_state *pf_find_state(struct pfi_kif *,
286 struct pf_state_key_cmp *, u_int);
287 static int pf_src_connlimit(struct pf_state **);
288 static void pf_overload_task(void *v, int pending);
289 static int pf_insert_src_node(struct pf_src_node **,
290 struct pf_rule *, struct pf_addr *, sa_family_t);
291 static u_int pf_purge_expired_states(u_int, int);
292 static void pf_purge_unlinked_rules(void);
293 static int pf_mtag_uminit(void *, int, int);
294 static void pf_mtag_free(struct m_tag *);
296 static void pf_route(struct mbuf **, struct pf_rule *, int,
297 struct ifnet *, struct pf_state *,
298 struct pf_pdesc *, struct inpcb *);
301 static void pf_change_a6(struct pf_addr *, u_int16_t *,
302 struct pf_addr *, u_int8_t);
303 static void pf_route6(struct mbuf **, struct pf_rule *, int,
304 struct ifnet *, struct pf_state *,
305 struct pf_pdesc *, struct inpcb *);
308 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
310 extern int pf_end_threads;
311 extern struct proc *pf_purge_proc;
313 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
315 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
316 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
318 #define STATE_LOOKUP(i, k, d, s, pd) \
320 (s) = pf_find_state((i), (k), (d)); \
323 if (PACKET_LOOPED(pd)) \
325 if ((d) == PF_OUT && \
326 (((s)->rule.ptr->rt == PF_ROUTETO && \
327 (s)->rule.ptr->direction == PF_OUT) || \
328 ((s)->rule.ptr->rt == PF_REPLYTO && \
329 (s)->rule.ptr->direction == PF_IN)) && \
330 (s)->rt_kif != NULL && \
331 (s)->rt_kif != (i)) \
335 #define BOUND_IFACE(r, k) \
336 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
338 #define STATE_INC_COUNTERS(s) \
340 counter_u64_add(s->rule.ptr->states_cur, 1); \
341 counter_u64_add(s->rule.ptr->states_tot, 1); \
342 if (s->anchor.ptr != NULL) { \
343 counter_u64_add(s->anchor.ptr->states_cur, 1); \
344 counter_u64_add(s->anchor.ptr->states_tot, 1); \
346 if (s->nat_rule.ptr != NULL) { \
347 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
348 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
352 #define STATE_DEC_COUNTERS(s) \
354 if (s->nat_rule.ptr != NULL) \
355 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
356 if (s->anchor.ptr != NULL) \
357 counter_u64_add(s->anchor.ptr->states_cur, -1); \
358 counter_u64_add(s->rule.ptr->states_cur, -1); \
361 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
362 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
363 VNET_DEFINE(struct pf_idhash *, pf_idhash);
364 VNET_DEFINE(struct pf_srchash *, pf_srchash);
366 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
369 u_long pf_srchashmask;
370 static u_long pf_hashsize;
371 static u_long pf_srchashsize;
372 u_long pf_ioctl_maxcount = 65535;
374 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
375 &pf_hashsize, 0, "Size of pf(4) states hashtable");
376 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
377 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
378 SYSCTL_ULONG(_net_pf, OID_AUTO, request_maxcount, CTLFLAG_RDTUN,
379 &pf_ioctl_maxcount, 0, "Maximum number of tables, addresses, ... in a single ioctl() call");
381 VNET_DEFINE(void *, pf_swi_cookie);
383 VNET_DEFINE(uint32_t, pf_hashseed);
384 #define V_pf_hashseed VNET(pf_hashseed)
387 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
393 if (a->addr32[0] > b->addr32[0])
395 if (a->addr32[0] < b->addr32[0])
401 if (a->addr32[3] > b->addr32[3])
403 if (a->addr32[3] < b->addr32[3])
405 if (a->addr32[2] > b->addr32[2])
407 if (a->addr32[2] < b->addr32[2])
409 if (a->addr32[1] > b->addr32[1])
411 if (a->addr32[1] < b->addr32[1])
413 if (a->addr32[0] > b->addr32[0])
415 if (a->addr32[0] < b->addr32[0])
420 panic("%s: unknown address family %u", __func__, af);
425 static __inline uint32_t
426 pf_hashkey(struct pf_state_key *sk)
430 h = murmur3_32_hash32((uint32_t *)sk,
431 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
434 return (h & pf_hashmask);
437 static __inline uint32_t
438 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
444 h = murmur3_32_hash32((uint32_t *)&addr->v4,
445 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
448 h = murmur3_32_hash32((uint32_t *)&addr->v6,
449 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
452 panic("%s: unknown address family %u", __func__, af);
455 return (h & pf_srchashmask);
460 pf_state_hash(struct pf_state *s)
462 u_int32_t hv = (intptr_t)s / sizeof(*s);
464 hv ^= crc32(&s->src, sizeof(s->src));
465 hv ^= crc32(&s->dst, sizeof(s->dst));
474 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
479 dst->addr32[0] = src->addr32[0];
483 dst->addr32[0] = src->addr32[0];
484 dst->addr32[1] = src->addr32[1];
485 dst->addr32[2] = src->addr32[2];
486 dst->addr32[3] = src->addr32[3];
493 pf_init_threshold(struct pf_threshold *threshold,
494 u_int32_t limit, u_int32_t seconds)
496 threshold->limit = limit * PF_THRESHOLD_MULT;
497 threshold->seconds = seconds;
498 threshold->count = 0;
499 threshold->last = time_uptime;
503 pf_add_threshold(struct pf_threshold *threshold)
505 u_int32_t t = time_uptime, diff = t - threshold->last;
507 if (diff >= threshold->seconds)
508 threshold->count = 0;
510 threshold->count -= threshold->count * diff /
512 threshold->count += PF_THRESHOLD_MULT;
517 pf_check_threshold(struct pf_threshold *threshold)
519 return (threshold->count > threshold->limit);
523 pf_src_connlimit(struct pf_state **state)
525 struct pf_overload_entry *pfoe;
528 PF_STATE_LOCK_ASSERT(*state);
530 (*state)->src_node->conn++;
531 (*state)->src.tcp_est = 1;
532 pf_add_threshold(&(*state)->src_node->conn_rate);
534 if ((*state)->rule.ptr->max_src_conn &&
535 (*state)->rule.ptr->max_src_conn <
536 (*state)->src_node->conn) {
537 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
541 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
542 pf_check_threshold(&(*state)->src_node->conn_rate)) {
543 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
550 /* Kill this state. */
551 (*state)->timeout = PFTM_PURGE;
552 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
554 if ((*state)->rule.ptr->overload_tbl == NULL)
557 /* Schedule overloading and flushing task. */
558 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
560 return (1); /* too bad :( */
562 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
563 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
564 pfoe->rule = (*state)->rule.ptr;
565 pfoe->dir = (*state)->direction;
567 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
568 PF_OVERLOADQ_UNLOCK();
569 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
575 pf_overload_task(void *v, int pending)
577 struct pf_overload_head queue;
579 struct pf_overload_entry *pfoe, *pfoe1;
582 CURVNET_SET((struct vnet *)v);
585 queue = V_pf_overloadqueue;
586 SLIST_INIT(&V_pf_overloadqueue);
587 PF_OVERLOADQ_UNLOCK();
589 bzero(&p, sizeof(p));
590 SLIST_FOREACH(pfoe, &queue, next) {
591 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
592 if (V_pf_status.debug >= PF_DEBUG_MISC) {
593 printf("%s: blocking address ", __func__);
594 pf_print_host(&pfoe->addr, 0, pfoe->af);
598 p.pfra_af = pfoe->af;
603 p.pfra_ip4addr = pfoe->addr.v4;
609 p.pfra_ip6addr = pfoe->addr.v6;
615 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
620 * Remove those entries, that don't need flushing.
622 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
623 if (pfoe->rule->flush == 0) {
624 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
625 free(pfoe, M_PFTEMP);
628 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
630 /* If nothing to flush, return. */
631 if (SLIST_EMPTY(&queue)) {
636 for (int i = 0; i <= pf_hashmask; i++) {
637 struct pf_idhash *ih = &V_pf_idhash[i];
638 struct pf_state_key *sk;
642 LIST_FOREACH(s, &ih->states, entry) {
643 sk = s->key[PF_SK_WIRE];
644 SLIST_FOREACH(pfoe, &queue, next)
645 if (sk->af == pfoe->af &&
646 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
647 pfoe->rule == s->rule.ptr) &&
648 ((pfoe->dir == PF_OUT &&
649 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
650 (pfoe->dir == PF_IN &&
651 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
652 s->timeout = PFTM_PURGE;
653 s->src.state = s->dst.state = TCPS_CLOSED;
657 PF_HASHROW_UNLOCK(ih);
659 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
660 free(pfoe, M_PFTEMP);
661 if (V_pf_status.debug >= PF_DEBUG_MISC)
662 printf("%s: %u states killed", __func__, killed);
668 * Can return locked on failure, so that we can consistently
669 * allocate and insert a new one.
672 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
675 struct pf_srchash *sh;
676 struct pf_src_node *n;
678 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
680 sh = &V_pf_srchash[pf_hashsrc(src, af)];
682 LIST_FOREACH(n, &sh->nodes, entry)
683 if (n->rule.ptr == rule && n->af == af &&
684 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
685 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
689 PF_HASHROW_UNLOCK(sh);
690 } else if (returnlocked == 0)
691 PF_HASHROW_UNLOCK(sh);
697 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
698 struct pf_addr *src, sa_family_t af)
701 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
702 rule->rpool.opts & PF_POOL_STICKYADDR),
703 ("%s for non-tracking rule %p", __func__, rule));
706 *sn = pf_find_src_node(src, rule, af, 1);
709 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
711 PF_HASHROW_ASSERT(sh);
713 if (!rule->max_src_nodes ||
714 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
715 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
717 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
720 PF_HASHROW_UNLOCK(sh);
724 pf_init_threshold(&(*sn)->conn_rate,
725 rule->max_src_conn_rate.limit,
726 rule->max_src_conn_rate.seconds);
729 (*sn)->rule.ptr = rule;
730 PF_ACPY(&(*sn)->addr, src, af);
731 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
732 (*sn)->creation = time_uptime;
733 (*sn)->ruletype = rule->action;
735 if ((*sn)->rule.ptr != NULL)
736 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
737 PF_HASHROW_UNLOCK(sh);
738 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
740 if (rule->max_src_states &&
741 (*sn)->states >= rule->max_src_states) {
742 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
751 pf_unlink_src_node(struct pf_src_node *src)
754 PF_HASHROW_ASSERT(&V_pf_srchash[pf_hashsrc(&src->addr, src->af)]);
755 LIST_REMOVE(src, entry);
757 counter_u64_add(src->rule.ptr->src_nodes, -1);
761 pf_free_src_nodes(struct pf_src_node_list *head)
763 struct pf_src_node *sn, *tmp;
766 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
767 uma_zfree(V_pf_sources_z, sn);
771 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], count);
780 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
781 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
785 /* Per-vnet data storage structures initialization. */
789 struct pf_keyhash *kh;
790 struct pf_idhash *ih;
791 struct pf_srchash *sh;
794 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
795 pf_hashsize = PF_HASHSIZ;
796 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
797 pf_srchashsize = PF_SRCHASHSIZ;
799 V_pf_hashseed = arc4random();
801 /* States and state keys storage. */
802 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
803 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
804 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
805 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
806 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
808 V_pf_state_key_z = uma_zcreate("pf state keys",
809 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
812 V_pf_keyhash = mallocarray(pf_hashsize, sizeof(struct pf_keyhash),
813 M_PFHASH, M_NOWAIT | M_ZERO);
814 V_pf_idhash = mallocarray(pf_hashsize, sizeof(struct pf_idhash),
815 M_PFHASH, M_NOWAIT | M_ZERO);
816 if (V_pf_keyhash == NULL || V_pf_idhash == NULL) {
817 printf("pf: Unable to allocate memory for "
818 "state_hashsize %lu.\n", pf_hashsize);
820 free(V_pf_keyhash, M_PFHASH);
821 free(V_pf_idhash, M_PFHASH);
823 pf_hashsize = PF_HASHSIZ;
824 V_pf_keyhash = mallocarray(pf_hashsize,
825 sizeof(struct pf_keyhash), M_PFHASH, M_WAITOK | M_ZERO);
826 V_pf_idhash = mallocarray(pf_hashsize,
827 sizeof(struct pf_idhash), M_PFHASH, M_WAITOK | M_ZERO);
830 pf_hashmask = pf_hashsize - 1;
831 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
833 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
834 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
838 V_pf_sources_z = uma_zcreate("pf source nodes",
839 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
841 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
842 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
843 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
845 V_pf_srchash = mallocarray(pf_srchashsize,
846 sizeof(struct pf_srchash), M_PFHASH, M_NOWAIT | M_ZERO);
847 if (V_pf_srchash == NULL) {
848 printf("pf: Unable to allocate memory for "
849 "source_hashsize %lu.\n", pf_srchashsize);
851 pf_srchashsize = PF_SRCHASHSIZ;
852 V_pf_srchash = mallocarray(pf_srchashsize,
853 sizeof(struct pf_srchash), M_PFHASH, M_WAITOK | M_ZERO);
856 pf_srchashmask = pf_srchashsize - 1;
857 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
858 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
861 TAILQ_INIT(&V_pf_altqs[0]);
862 TAILQ_INIT(&V_pf_altqs[1]);
863 TAILQ_INIT(&V_pf_pabuf);
864 V_pf_altqs_active = &V_pf_altqs[0];
865 V_pf_altqs_inactive = &V_pf_altqs[1];
867 /* Send & overload+flush queues. */
868 STAILQ_INIT(&V_pf_sendqueue);
869 SLIST_INIT(&V_pf_overloadqueue);
870 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
872 /* Unlinked, but may be referenced rules. */
873 TAILQ_INIT(&V_pf_unlinked_rules);
880 uma_zdestroy(pf_mtag_z);
886 struct pf_keyhash *kh;
887 struct pf_idhash *ih;
888 struct pf_srchash *sh;
889 struct pf_send_entry *pfse, *next;
892 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
894 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
896 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
898 mtx_destroy(&kh->lock);
899 mtx_destroy(&ih->lock);
901 free(V_pf_keyhash, M_PFHASH);
902 free(V_pf_idhash, M_PFHASH);
904 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
905 KASSERT(LIST_EMPTY(&sh->nodes),
906 ("%s: source node hash not empty", __func__));
907 mtx_destroy(&sh->lock);
909 free(V_pf_srchash, M_PFHASH);
911 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
912 m_freem(pfse->pfse_m);
913 free(pfse, M_PFTEMP);
916 uma_zdestroy(V_pf_sources_z);
917 uma_zdestroy(V_pf_state_z);
918 uma_zdestroy(V_pf_state_key_z);
922 pf_mtag_uminit(void *mem, int size, int how)
926 t = (struct m_tag *)mem;
927 t->m_tag_cookie = MTAG_ABI_COMPAT;
928 t->m_tag_id = PACKET_TAG_PF;
929 t->m_tag_len = sizeof(struct pf_mtag);
930 t->m_tag_free = pf_mtag_free;
936 pf_mtag_free(struct m_tag *t)
939 uma_zfree(pf_mtag_z, t);
943 pf_get_mtag(struct mbuf *m)
947 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
948 return ((struct pf_mtag *)(mtag + 1));
950 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
953 bzero(mtag + 1, sizeof(struct pf_mtag));
954 m_tag_prepend(m, mtag);
956 return ((struct pf_mtag *)(mtag + 1));
960 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
963 struct pf_keyhash *khs, *khw, *kh;
964 struct pf_state_key *sk, *cur;
965 struct pf_state *si, *olds = NULL;
968 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
969 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
970 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
973 * We need to lock hash slots of both keys. To avoid deadlock
974 * we always lock the slot with lower address first. Unlock order
977 * We also need to lock ID hash slot before dropping key
978 * locks. On success we return with ID hash slot locked.
982 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
983 PF_HASHROW_LOCK(khs);
985 khs = &V_pf_keyhash[pf_hashkey(sks)];
986 khw = &V_pf_keyhash[pf_hashkey(skw)];
988 PF_HASHROW_LOCK(khs);
989 } else if (khs < khw) {
990 PF_HASHROW_LOCK(khs);
991 PF_HASHROW_LOCK(khw);
993 PF_HASHROW_LOCK(khw);
994 PF_HASHROW_LOCK(khs);
998 #define KEYS_UNLOCK() do { \
1000 PF_HASHROW_UNLOCK(khs); \
1001 PF_HASHROW_UNLOCK(khw); \
1003 PF_HASHROW_UNLOCK(khs); \
1007 * First run: start with wire key.
1014 LIST_FOREACH(cur, &kh->keys, entry)
1015 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
1019 /* Key exists. Check for same kif, if none, add to key. */
1020 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
1021 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
1023 PF_HASHROW_LOCK(ih);
1024 if (si->kif == s->kif &&
1025 si->direction == s->direction) {
1026 if (sk->proto == IPPROTO_TCP &&
1027 si->src.state >= TCPS_FIN_WAIT_2 &&
1028 si->dst.state >= TCPS_FIN_WAIT_2) {
1030 * New state matches an old >FIN_WAIT_2
1031 * state. We can't drop key hash locks,
1032 * thus we can't unlink it properly.
1034 * As a workaround we drop it into
1035 * TCPS_CLOSED state, schedule purge
1036 * ASAP and push it into the very end
1037 * of the slot TAILQ, so that it won't
1038 * conflict with our new state.
1040 si->src.state = si->dst.state =
1042 si->timeout = PFTM_PURGE;
1045 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1046 printf("pf: %s key attach "
1048 (idx == PF_SK_WIRE) ?
1051 pf_print_state_parts(s,
1052 (idx == PF_SK_WIRE) ?
1054 (idx == PF_SK_STACK) ?
1056 printf(", existing: ");
1057 pf_print_state_parts(si,
1058 (idx == PF_SK_WIRE) ?
1060 (idx == PF_SK_STACK) ?
1064 PF_HASHROW_UNLOCK(ih);
1066 uma_zfree(V_pf_state_key_z, sk);
1067 if (idx == PF_SK_STACK)
1069 return (EEXIST); /* collision! */
1072 PF_HASHROW_UNLOCK(ih);
1074 uma_zfree(V_pf_state_key_z, sk);
1077 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1082 /* List is sorted, if-bound states before floating. */
1083 if (s->kif == V_pfi_all)
1084 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1086 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1089 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1090 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1096 * Attach done. See how should we (or should not?)
1097 * attach a second key.
1100 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1104 } else if (sks != NULL) {
1106 * Continue attaching with stack key.
1118 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1119 ("%s failure", __func__));
1126 pf_detach_state(struct pf_state *s)
1128 struct pf_state_key *sks = s->key[PF_SK_STACK];
1129 struct pf_keyhash *kh;
1132 kh = &V_pf_keyhash[pf_hashkey(sks)];
1133 PF_HASHROW_LOCK(kh);
1134 if (s->key[PF_SK_STACK] != NULL)
1135 pf_state_key_detach(s, PF_SK_STACK);
1137 * If both point to same key, then we are done.
1139 if (sks == s->key[PF_SK_WIRE]) {
1140 pf_state_key_detach(s, PF_SK_WIRE);
1141 PF_HASHROW_UNLOCK(kh);
1144 PF_HASHROW_UNLOCK(kh);
1147 if (s->key[PF_SK_WIRE] != NULL) {
1148 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1149 PF_HASHROW_LOCK(kh);
1150 if (s->key[PF_SK_WIRE] != NULL)
1151 pf_state_key_detach(s, PF_SK_WIRE);
1152 PF_HASHROW_UNLOCK(kh);
1157 pf_state_key_detach(struct pf_state *s, int idx)
1159 struct pf_state_key *sk = s->key[idx];
1161 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1163 PF_HASHROW_ASSERT(kh);
1165 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1168 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1169 LIST_REMOVE(sk, entry);
1170 uma_zfree(V_pf_state_key_z, sk);
1175 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1177 struct pf_state_key *sk = mem;
1179 bzero(sk, sizeof(struct pf_state_key_cmp));
1180 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1181 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1186 struct pf_state_key *
1187 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1188 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1190 struct pf_state_key *sk;
1192 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1196 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1197 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1198 sk->port[pd->sidx] = sport;
1199 sk->port[pd->didx] = dport;
1200 sk->proto = pd->proto;
1206 struct pf_state_key *
1207 pf_state_key_clone(struct pf_state_key *orig)
1209 struct pf_state_key *sk;
1211 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1215 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1221 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1222 struct pf_state_key *sks, struct pf_state *s)
1224 struct pf_idhash *ih;
1225 struct pf_state *cur;
1228 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1229 ("%s: sks not pristine", __func__));
1230 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1231 ("%s: skw not pristine", __func__));
1232 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1236 if (s->id == 0 && s->creatorid == 0) {
1237 /* XXX: should be atomic, but probability of collision low */
1238 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1239 V_pf_stateid[curcpu] = 1;
1240 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1241 s->id = htobe64(s->id);
1242 s->creatorid = V_pf_status.hostid;
1245 /* Returns with ID locked on success. */
1246 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1249 ih = &V_pf_idhash[PF_IDHASH(s)];
1250 PF_HASHROW_ASSERT(ih);
1251 LIST_FOREACH(cur, &ih->states, entry)
1252 if (cur->id == s->id && cur->creatorid == s->creatorid)
1256 PF_HASHROW_UNLOCK(ih);
1257 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1258 printf("pf: state ID collision: "
1259 "id: %016llx creatorid: %08x\n",
1260 (unsigned long long)be64toh(s->id),
1261 ntohl(s->creatorid));
1266 LIST_INSERT_HEAD(&ih->states, s, entry);
1267 /* One for keys, one for ID hash. */
1268 refcount_init(&s->refs, 2);
1270 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1271 if (pfsync_insert_state_ptr != NULL)
1272 pfsync_insert_state_ptr(s);
1274 /* Returns locked. */
1279 * Find state by ID: returns with locked row on success.
1282 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1284 struct pf_idhash *ih;
1287 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1289 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1291 PF_HASHROW_LOCK(ih);
1292 LIST_FOREACH(s, &ih->states, entry)
1293 if (s->id == id && s->creatorid == creatorid)
1297 PF_HASHROW_UNLOCK(ih);
1303 * Find state by key.
1304 * Returns with ID hash slot locked on success.
1306 static struct pf_state *
1307 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1309 struct pf_keyhash *kh;
1310 struct pf_state_key *sk;
1314 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1316 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1318 PF_HASHROW_LOCK(kh);
1319 LIST_FOREACH(sk, &kh->keys, entry)
1320 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1323 PF_HASHROW_UNLOCK(kh);
1327 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1329 /* List is sorted, if-bound states before floating ones. */
1330 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1331 if (s->kif == V_pfi_all || s->kif == kif) {
1333 PF_HASHROW_UNLOCK(kh);
1334 if (s->timeout >= PFTM_MAX) {
1336 * State is either being processed by
1337 * pf_unlink_state() in an other thread, or
1338 * is scheduled for immediate expiry.
1345 PF_HASHROW_UNLOCK(kh);
1351 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1353 struct pf_keyhash *kh;
1354 struct pf_state_key *sk;
1355 struct pf_state *s, *ret = NULL;
1358 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1360 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1362 PF_HASHROW_LOCK(kh);
1363 LIST_FOREACH(sk, &kh->keys, entry)
1364 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1367 PF_HASHROW_UNLOCK(kh);
1382 panic("%s: dir %u", __func__, dir);
1385 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1387 PF_HASHROW_UNLOCK(kh);
1401 PF_HASHROW_UNLOCK(kh);
1406 /* END state table stuff */
1409 pf_send(struct pf_send_entry *pfse)
1413 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1415 swi_sched(V_pf_swi_cookie, 0);
1421 struct pf_send_head queue;
1422 struct pf_send_entry *pfse, *next;
1424 CURVNET_SET((struct vnet *)v);
1427 queue = V_pf_sendqueue;
1428 STAILQ_INIT(&V_pf_sendqueue);
1431 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1432 switch (pfse->pfse_type) {
1435 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1438 icmp_error(pfse->pfse_m, pfse->icmpopts.type,
1439 pfse->icmpopts.code, 0, pfse->icmpopts.mtu);
1444 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1448 icmp6_error(pfse->pfse_m, pfse->icmpopts.type,
1449 pfse->icmpopts.code, pfse->icmpopts.mtu);
1453 panic("%s: unknown type", __func__);
1455 free(pfse, M_PFTEMP);
1461 pf_purge_thread(void *unused __unused)
1463 VNET_ITERATOR_DECL(vnet_iter);
1465 sx_xlock(&pf_end_lock);
1466 while (pf_end_threads == 0) {
1467 sx_sleep(pf_purge_thread, &pf_end_lock, 0, "pftm", hz / 10);
1470 VNET_FOREACH(vnet_iter) {
1471 CURVNET_SET(vnet_iter);
1474 /* Wait until V_pf_default_rule is initialized. */
1475 if (V_pf_vnet_active == 0) {
1481 * Process 1/interval fraction of the state
1485 pf_purge_expired_states(V_pf_purge_idx, pf_hashmask /
1486 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1489 * Purge other expired types every
1490 * PFTM_INTERVAL seconds.
1492 if (V_pf_purge_idx == 0) {
1494 * Order is important:
1495 * - states and src nodes reference rules
1496 * - states and rules reference kifs
1498 pf_purge_expired_fragments();
1499 pf_purge_expired_src_nodes();
1500 pf_purge_unlinked_rules();
1505 VNET_LIST_RUNLOCK();
1509 sx_xunlock(&pf_end_lock);
1514 pf_unload_vnet_purge(void)
1518 * To cleanse up all kifs and rules we need
1519 * two runs: first one clears reference flags,
1520 * then pf_purge_expired_states() doesn't
1521 * raise them, and then second run frees.
1523 pf_purge_unlinked_rules();
1527 * Now purge everything.
1529 pf_purge_expired_states(0, pf_hashmask);
1530 pf_purge_fragments(UINT_MAX);
1531 pf_purge_expired_src_nodes();
1534 * Now all kifs & rules should be unreferenced,
1535 * thus should be successfully freed.
1537 pf_purge_unlinked_rules();
1543 pf_state_expires(const struct pf_state *state)
1550 /* handle all PFTM_* > PFTM_MAX here */
1551 if (state->timeout == PFTM_PURGE)
1552 return (time_uptime);
1553 KASSERT(state->timeout != PFTM_UNLINKED,
1554 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1555 KASSERT((state->timeout < PFTM_MAX),
1556 ("pf_state_expires: timeout > PFTM_MAX"));
1557 timeout = state->rule.ptr->timeout[state->timeout];
1559 timeout = V_pf_default_rule.timeout[state->timeout];
1560 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1562 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1563 states = counter_u64_fetch(state->rule.ptr->states_cur);
1565 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1566 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1567 states = V_pf_status.states;
1569 if (end && states > start && start < end) {
1571 return (state->expire + timeout * (end - states) /
1574 return (time_uptime);
1576 return (state->expire + timeout);
1580 pf_purge_expired_src_nodes()
1582 struct pf_src_node_list freelist;
1583 struct pf_srchash *sh;
1584 struct pf_src_node *cur, *next;
1587 LIST_INIT(&freelist);
1588 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1589 PF_HASHROW_LOCK(sh);
1590 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1591 if (cur->states == 0 && cur->expire <= time_uptime) {
1592 pf_unlink_src_node(cur);
1593 LIST_INSERT_HEAD(&freelist, cur, entry);
1594 } else if (cur->rule.ptr != NULL)
1595 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1596 PF_HASHROW_UNLOCK(sh);
1599 pf_free_src_nodes(&freelist);
1601 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1605 pf_src_tree_remove_state(struct pf_state *s)
1607 struct pf_src_node *sn;
1608 struct pf_srchash *sh;
1611 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE] ?
1612 s->rule.ptr->timeout[PFTM_SRC_NODE] :
1613 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1615 if (s->src_node != NULL) {
1617 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1618 PF_HASHROW_LOCK(sh);
1621 if (--sn->states == 0)
1622 sn->expire = time_uptime + timeout;
1623 PF_HASHROW_UNLOCK(sh);
1625 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1626 sn = s->nat_src_node;
1627 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
1628 PF_HASHROW_LOCK(sh);
1629 if (--sn->states == 0)
1630 sn->expire = time_uptime + timeout;
1631 PF_HASHROW_UNLOCK(sh);
1633 s->src_node = s->nat_src_node = NULL;
1637 * Unlink and potentilly free a state. Function may be
1638 * called with ID hash row locked, but always returns
1639 * unlocked, since it needs to go through key hash locking.
1642 pf_unlink_state(struct pf_state *s, u_int flags)
1644 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1646 if ((flags & PF_ENTER_LOCKED) == 0)
1647 PF_HASHROW_LOCK(ih);
1649 PF_HASHROW_ASSERT(ih);
1651 if (s->timeout == PFTM_UNLINKED) {
1653 * State is being processed
1654 * by pf_unlink_state() in
1657 PF_HASHROW_UNLOCK(ih);
1658 return (0); /* XXXGL: undefined actually */
1661 if (s->src.state == PF_TCPS_PROXY_DST) {
1662 /* XXX wire key the right one? */
1663 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1664 &s->key[PF_SK_WIRE]->addr[1],
1665 &s->key[PF_SK_WIRE]->addr[0],
1666 s->key[PF_SK_WIRE]->port[1],
1667 s->key[PF_SK_WIRE]->port[0],
1668 s->src.seqhi, s->src.seqlo + 1,
1669 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1672 LIST_REMOVE(s, entry);
1673 pf_src_tree_remove_state(s);
1675 if (pfsync_delete_state_ptr != NULL)
1676 pfsync_delete_state_ptr(s);
1678 STATE_DEC_COUNTERS(s);
1680 s->timeout = PFTM_UNLINKED;
1682 PF_HASHROW_UNLOCK(ih);
1685 /* pf_state_insert() initialises refs to 2, so we can never release the
1686 * last reference here, only in pf_release_state(). */
1687 (void)refcount_release(&s->refs);
1689 return (pf_release_state(s));
1693 pf_free_state(struct pf_state *cur)
1696 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1697 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1700 pf_normalize_tcp_cleanup(cur);
1701 uma_zfree(V_pf_state_z, cur);
1702 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1706 * Called only from pf_purge_thread(), thus serialized.
1709 pf_purge_expired_states(u_int i, int maxcheck)
1711 struct pf_idhash *ih;
1714 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1717 * Go through hash and unlink states that expire now.
1719 while (maxcheck > 0) {
1721 ih = &V_pf_idhash[i];
1723 PF_HASHROW_LOCK(ih);
1724 LIST_FOREACH(s, &ih->states, entry) {
1725 if (pf_state_expires(s) <= time_uptime) {
1726 V_pf_status.states -=
1727 pf_unlink_state(s, PF_ENTER_LOCKED);
1730 s->rule.ptr->rule_flag |= PFRULE_REFS;
1731 if (s->nat_rule.ptr != NULL)
1732 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1733 if (s->anchor.ptr != NULL)
1734 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1735 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1737 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1739 PF_HASHROW_UNLOCK(ih);
1741 /* Return when we hit end of hash. */
1742 if (++i > pf_hashmask) {
1743 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1750 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1756 pf_purge_unlinked_rules()
1758 struct pf_rulequeue tmpq;
1759 struct pf_rule *r, *r1;
1762 * If we have overloading task pending, then we'd
1763 * better skip purging this time. There is a tiny
1764 * probability that overloading task references
1765 * an already unlinked rule.
1767 PF_OVERLOADQ_LOCK();
1768 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1769 PF_OVERLOADQ_UNLOCK();
1772 PF_OVERLOADQ_UNLOCK();
1775 * Do naive mark-and-sweep garbage collecting of old rules.
1776 * Reference flag is raised by pf_purge_expired_states()
1777 * and pf_purge_expired_src_nodes().
1779 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1780 * use a temporary queue.
1783 PF_UNLNKDRULES_LOCK();
1784 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1785 if (!(r->rule_flag & PFRULE_REFS)) {
1786 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1787 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1789 r->rule_flag &= ~PFRULE_REFS;
1791 PF_UNLNKDRULES_UNLOCK();
1793 if (!TAILQ_EMPTY(&tmpq)) {
1795 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1796 TAILQ_REMOVE(&tmpq, r, entries);
1804 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1809 u_int32_t a = ntohl(addr->addr32[0]);
1810 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1822 u_int8_t i, curstart, curend, maxstart, maxend;
1823 curstart = curend = maxstart = maxend = 255;
1824 for (i = 0; i < 8; i++) {
1825 if (!addr->addr16[i]) {
1826 if (curstart == 255)
1830 if ((curend - curstart) >
1831 (maxend - maxstart)) {
1832 maxstart = curstart;
1835 curstart = curend = 255;
1838 if ((curend - curstart) >
1839 (maxend - maxstart)) {
1840 maxstart = curstart;
1843 for (i = 0; i < 8; i++) {
1844 if (i >= maxstart && i <= maxend) {
1850 b = ntohs(addr->addr16[i]);
1867 pf_print_state(struct pf_state *s)
1869 pf_print_state_parts(s, NULL, NULL);
1873 pf_print_state_parts(struct pf_state *s,
1874 struct pf_state_key *skwp, struct pf_state_key *sksp)
1876 struct pf_state_key *skw, *sks;
1877 u_int8_t proto, dir;
1879 /* Do our best to fill these, but they're skipped if NULL */
1880 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1881 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1882 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1883 dir = s ? s->direction : 0;
1901 case IPPROTO_ICMPV6:
1905 printf("%u", proto);
1918 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1920 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1925 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1927 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1932 if (proto == IPPROTO_TCP) {
1933 printf(" [lo=%u high=%u win=%u modulator=%u",
1934 s->src.seqlo, s->src.seqhi,
1935 s->src.max_win, s->src.seqdiff);
1936 if (s->src.wscale && s->dst.wscale)
1937 printf(" wscale=%u",
1938 s->src.wscale & PF_WSCALE_MASK);
1940 printf(" [lo=%u high=%u win=%u modulator=%u",
1941 s->dst.seqlo, s->dst.seqhi,
1942 s->dst.max_win, s->dst.seqdiff);
1943 if (s->src.wscale && s->dst.wscale)
1944 printf(" wscale=%u",
1945 s->dst.wscale & PF_WSCALE_MASK);
1948 printf(" %u:%u", s->src.state, s->dst.state);
1953 pf_print_flags(u_int8_t f)
1975 #define PF_SET_SKIP_STEPS(i) \
1977 while (head[i] != cur) { \
1978 head[i]->skip[i].ptr = cur; \
1979 head[i] = TAILQ_NEXT(head[i], entries); \
1984 pf_calc_skip_steps(struct pf_rulequeue *rules)
1986 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1989 cur = TAILQ_FIRST(rules);
1991 for (i = 0; i < PF_SKIP_COUNT; ++i)
1993 while (cur != NULL) {
1995 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1996 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1997 if (cur->direction != prev->direction)
1998 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1999 if (cur->af != prev->af)
2000 PF_SET_SKIP_STEPS(PF_SKIP_AF);
2001 if (cur->proto != prev->proto)
2002 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
2003 if (cur->src.neg != prev->src.neg ||
2004 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
2005 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
2006 if (cur->src.port[0] != prev->src.port[0] ||
2007 cur->src.port[1] != prev->src.port[1] ||
2008 cur->src.port_op != prev->src.port_op)
2009 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
2010 if (cur->dst.neg != prev->dst.neg ||
2011 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
2012 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
2013 if (cur->dst.port[0] != prev->dst.port[0] ||
2014 cur->dst.port[1] != prev->dst.port[1] ||
2015 cur->dst.port_op != prev->dst.port_op)
2016 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
2019 cur = TAILQ_NEXT(cur, entries);
2021 for (i = 0; i < PF_SKIP_COUNT; ++i)
2022 PF_SET_SKIP_STEPS(i);
2026 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
2028 if (aw1->type != aw2->type)
2030 switch (aw1->type) {
2031 case PF_ADDR_ADDRMASK:
2033 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, AF_INET6))
2035 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, AF_INET6))
2038 case PF_ADDR_DYNIFTL:
2039 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
2040 case PF_ADDR_NOROUTE:
2041 case PF_ADDR_URPFFAILED:
2044 return (aw1->p.tbl != aw2->p.tbl);
2046 printf("invalid address type: %d\n", aw1->type);
2052 * Checksum updates are a little complicated because the checksum in the TCP/UDP
2053 * header isn't always a full checksum. In some cases (i.e. output) it's a
2054 * pseudo-header checksum, which is a partial checksum over src/dst IP
2055 * addresses, protocol number and length.
2057 * That means we have the following cases:
2058 * * Input or forwarding: we don't have TSO, the checksum fields are full
2059 * checksums, we need to update the checksum whenever we change anything.
2060 * * Output (i.e. the checksum is a pseudo-header checksum):
2061 * x The field being updated is src/dst address or affects the length of
2062 * the packet. We need to update the pseudo-header checksum (note that this
2063 * checksum is not ones' complement).
2064 * x Some other field is being modified (e.g. src/dst port numbers): We
2065 * don't have to update anything.
2068 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2074 l = cksum + old - new;
2075 l = (l >> 16) + (l & 65535);
2083 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2084 u_int16_t new, u_int8_t udp)
2086 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2089 return (pf_cksum_fixup(cksum, old, new, udp));
2093 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2094 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2100 PF_ACPY(&ao, a, af);
2103 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2111 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2112 ao.addr16[0], an->addr16[0], 0),
2113 ao.addr16[1], an->addr16[1], 0);
2116 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2117 ao.addr16[0], an->addr16[0], u),
2118 ao.addr16[1], an->addr16[1], u);
2120 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2125 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2126 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2127 pf_cksum_fixup(pf_cksum_fixup(*pc,
2128 ao.addr16[0], an->addr16[0], u),
2129 ao.addr16[1], an->addr16[1], u),
2130 ao.addr16[2], an->addr16[2], u),
2131 ao.addr16[3], an->addr16[3], u),
2132 ao.addr16[4], an->addr16[4], u),
2133 ao.addr16[5], an->addr16[5], u),
2134 ao.addr16[6], an->addr16[6], u),
2135 ao.addr16[7], an->addr16[7], u);
2137 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2142 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2143 CSUM_DELAY_DATA_IPV6)) {
2150 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2152 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2156 memcpy(&ao, a, sizeof(ao));
2157 memcpy(a, &an, sizeof(u_int32_t));
2158 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2159 ao % 65536, an % 65536, u);
2163 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2167 memcpy(&ao, a, sizeof(ao));
2168 memcpy(a, &an, sizeof(u_int32_t));
2170 *c = pf_proto_cksum_fixup(m,
2171 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2172 ao % 65536, an % 65536, udp);
2177 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2181 PF_ACPY(&ao, a, AF_INET6);
2182 PF_ACPY(a, an, AF_INET6);
2184 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2185 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2186 pf_cksum_fixup(pf_cksum_fixup(*c,
2187 ao.addr16[0], an->addr16[0], u),
2188 ao.addr16[1], an->addr16[1], u),
2189 ao.addr16[2], an->addr16[2], u),
2190 ao.addr16[3], an->addr16[3], u),
2191 ao.addr16[4], an->addr16[4], u),
2192 ao.addr16[5], an->addr16[5], u),
2193 ao.addr16[6], an->addr16[6], u),
2194 ao.addr16[7], an->addr16[7], u);
2199 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2200 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2201 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2203 struct pf_addr oia, ooa;
2205 PF_ACPY(&oia, ia, af);
2207 PF_ACPY(&ooa, oa, af);
2209 /* Change inner protocol port, fix inner protocol checksum. */
2211 u_int16_t oip = *ip;
2218 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2219 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2221 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2223 /* Change inner ip address, fix inner ip and icmp checksums. */
2224 PF_ACPY(ia, na, af);
2228 u_int32_t oh2c = *h2c;
2230 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2231 oia.addr16[0], ia->addr16[0], 0),
2232 oia.addr16[1], ia->addr16[1], 0);
2233 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2234 oia.addr16[0], ia->addr16[0], 0),
2235 oia.addr16[1], ia->addr16[1], 0);
2236 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2242 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2243 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2244 pf_cksum_fixup(pf_cksum_fixup(*ic,
2245 oia.addr16[0], ia->addr16[0], u),
2246 oia.addr16[1], ia->addr16[1], u),
2247 oia.addr16[2], ia->addr16[2], u),
2248 oia.addr16[3], ia->addr16[3], u),
2249 oia.addr16[4], ia->addr16[4], u),
2250 oia.addr16[5], ia->addr16[5], u),
2251 oia.addr16[6], ia->addr16[6], u),
2252 oia.addr16[7], ia->addr16[7], u);
2256 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2258 PF_ACPY(oa, na, af);
2262 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2263 ooa.addr16[0], oa->addr16[0], 0),
2264 ooa.addr16[1], oa->addr16[1], 0);
2269 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2270 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2271 pf_cksum_fixup(pf_cksum_fixup(*ic,
2272 ooa.addr16[0], oa->addr16[0], u),
2273 ooa.addr16[1], oa->addr16[1], u),
2274 ooa.addr16[2], oa->addr16[2], u),
2275 ooa.addr16[3], oa->addr16[3], u),
2276 ooa.addr16[4], oa->addr16[4], u),
2277 ooa.addr16[5], oa->addr16[5], u),
2278 ooa.addr16[6], oa->addr16[6], u),
2279 ooa.addr16[7], oa->addr16[7], u);
2288 * Need to modulate the sequence numbers in the TCP SACK option
2289 * (credits to Krzysztof Pfaff for report and patch)
2292 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2293 struct tcphdr *th, struct pf_state_peer *dst)
2295 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2296 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2297 int copyback = 0, i, olen;
2298 struct sackblk sack;
2300 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2301 if (hlen < TCPOLEN_SACKLEN ||
2302 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2305 while (hlen >= TCPOLEN_SACKLEN) {
2308 case TCPOPT_EOL: /* FALLTHROUGH */
2316 if (olen >= TCPOLEN_SACKLEN) {
2317 for (i = 2; i + TCPOLEN_SACK <= olen;
2318 i += TCPOLEN_SACK) {
2319 memcpy(&sack, &opt[i], sizeof(sack));
2320 pf_change_proto_a(m, &sack.start, &th->th_sum,
2321 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2322 pf_change_proto_a(m, &sack.end, &th->th_sum,
2323 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2324 memcpy(&opt[i], &sack, sizeof(sack));
2338 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2343 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2344 const struct pf_addr *saddr, const struct pf_addr *daddr,
2345 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2346 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2347 u_int16_t rtag, struct ifnet *ifp)
2349 struct pf_send_entry *pfse;
2353 struct ip *h = NULL;
2356 struct ip6_hdr *h6 = NULL;
2360 struct pf_mtag *pf_mtag;
2365 /* maximum segment size tcp option */
2366 tlen = sizeof(struct tcphdr);
2373 len = sizeof(struct ip) + tlen;
2378 len = sizeof(struct ip6_hdr) + tlen;
2382 panic("%s: unsupported af %d", __func__, af);
2385 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2386 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2389 m = m_gethdr(M_NOWAIT, MT_DATA);
2391 free(pfse, M_PFTEMP);
2395 mac_netinet_firewall_send(m);
2397 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2398 free(pfse, M_PFTEMP);
2403 m->m_flags |= M_SKIP_FIREWALL;
2404 pf_mtag->tag = rtag;
2406 if (r != NULL && r->rtableid >= 0)
2407 M_SETFIB(m, r->rtableid);
2410 if (r != NULL && r->qid) {
2411 pf_mtag->qid = r->qid;
2413 /* add hints for ecn */
2414 pf_mtag->hdr = mtod(m, struct ip *);
2417 m->m_data += max_linkhdr;
2418 m->m_pkthdr.len = m->m_len = len;
2419 m->m_pkthdr.rcvif = NULL;
2420 bzero(m->m_data, len);
2424 h = mtod(m, struct ip *);
2426 /* IP header fields included in the TCP checksum */
2427 h->ip_p = IPPROTO_TCP;
2428 h->ip_len = htons(tlen);
2429 h->ip_src.s_addr = saddr->v4.s_addr;
2430 h->ip_dst.s_addr = daddr->v4.s_addr;
2432 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2437 h6 = mtod(m, struct ip6_hdr *);
2439 /* IP header fields included in the TCP checksum */
2440 h6->ip6_nxt = IPPROTO_TCP;
2441 h6->ip6_plen = htons(tlen);
2442 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2443 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2445 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2451 th->th_sport = sport;
2452 th->th_dport = dport;
2453 th->th_seq = htonl(seq);
2454 th->th_ack = htonl(ack);
2455 th->th_off = tlen >> 2;
2456 th->th_flags = flags;
2457 th->th_win = htons(win);
2460 opt = (char *)(th + 1);
2461 opt[0] = TCPOPT_MAXSEG;
2464 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2471 th->th_sum = in_cksum(m, len);
2473 /* Finish the IP header */
2475 h->ip_hl = sizeof(*h) >> 2;
2476 h->ip_tos = IPTOS_LOWDELAY;
2477 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2478 h->ip_len = htons(len);
2479 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2482 pfse->pfse_type = PFSE_IP;
2488 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2489 sizeof(struct ip6_hdr), tlen);
2491 h6->ip6_vfc |= IPV6_VERSION;
2492 h6->ip6_hlim = IPV6_DEFHLIM;
2494 pfse->pfse_type = PFSE_IP6;
2503 pf_return(struct pf_rule *r, struct pf_rule *nr, struct pf_pdesc *pd,
2504 struct pf_state_key *sk, int off, struct mbuf *m, struct tcphdr *th,
2505 struct pfi_kif *kif, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen,
2508 struct pf_addr * const saddr = pd->src;
2509 struct pf_addr * const daddr = pd->dst;
2510 sa_family_t af = pd->af;
2512 /* undo NAT changes, if they have taken place */
2514 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
2515 PF_ACPY(daddr, &sk->addr[pd->didx], af);
2517 *pd->sport = sk->port[pd->sidx];
2519 *pd->dport = sk->port[pd->didx];
2521 *pd->proto_sum = bproto_sum;
2523 *pd->ip_sum = bip_sum;
2524 m_copyback(m, off, hdrlen, pd->hdr.any);
2526 if (pd->proto == IPPROTO_TCP &&
2527 ((r->rule_flag & PFRULE_RETURNRST) ||
2528 (r->rule_flag & PFRULE_RETURN)) &&
2529 !(th->th_flags & TH_RST)) {
2530 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
2542 h4 = mtod(m, struct ip *);
2543 len = ntohs(h4->ip_len) - off;
2548 h6 = mtod(m, struct ip6_hdr *);
2549 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
2554 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
2555 REASON_SET(reason, PFRES_PROTCKSUM);
2557 if (th->th_flags & TH_SYN)
2559 if (th->th_flags & TH_FIN)
2561 pf_send_tcp(m, r, af, pd->dst,
2562 pd->src, th->th_dport, th->th_sport,
2563 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
2564 r->return_ttl, 1, 0, kif->pfik_ifp);
2566 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
2568 pf_send_icmp(m, r->return_icmp >> 8,
2569 r->return_icmp & 255, af, r);
2570 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
2572 pf_send_icmp(m, r->return_icmp6 >> 8,
2573 r->return_icmp6 & 255, af, r);
2578 pf_ieee8021q_setpcp(struct mbuf *m, u_int8_t prio)
2582 KASSERT(prio <= PF_PRIO_MAX,
2583 ("%s with invalid pcp", __func__));
2585 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_OUT, NULL);
2587 mtag = m_tag_alloc(MTAG_8021Q, MTAG_8021Q_PCP_OUT,
2588 sizeof(uint8_t), M_NOWAIT);
2591 m_tag_prepend(m, mtag);
2594 *(uint8_t *)(mtag + 1) = prio;
2599 pf_match_ieee8021q_pcp(u_int8_t prio, struct mbuf *m)
2604 mtag = m_tag_locate(m, MTAG_8021Q, MTAG_8021Q_PCP_IN, NULL);
2608 if (prio == PF_PRIO_ZERO)
2611 mpcp = *(uint8_t *)(mtag + 1);
2613 return (mpcp == prio);
2617 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2620 struct pf_send_entry *pfse;
2622 struct pf_mtag *pf_mtag;
2624 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2625 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2629 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2630 free(pfse, M_PFTEMP);
2634 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2635 free(pfse, M_PFTEMP);
2639 m0->m_flags |= M_SKIP_FIREWALL;
2641 if (r->rtableid >= 0)
2642 M_SETFIB(m0, r->rtableid);
2646 pf_mtag->qid = r->qid;
2647 /* add hints for ecn */
2648 pf_mtag->hdr = mtod(m0, struct ip *);
2655 pfse->pfse_type = PFSE_ICMP;
2660 pfse->pfse_type = PFSE_ICMP6;
2665 pfse->icmpopts.type = type;
2666 pfse->icmpopts.code = code;
2671 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2672 * If n is 0, they match if they are equal. If n is != 0, they match if they
2676 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2677 struct pf_addr *b, sa_family_t af)
2684 if ((a->addr32[0] & m->addr32[0]) ==
2685 (b->addr32[0] & m->addr32[0]))
2691 if (((a->addr32[0] & m->addr32[0]) ==
2692 (b->addr32[0] & m->addr32[0])) &&
2693 ((a->addr32[1] & m->addr32[1]) ==
2694 (b->addr32[1] & m->addr32[1])) &&
2695 ((a->addr32[2] & m->addr32[2]) ==
2696 (b->addr32[2] & m->addr32[2])) &&
2697 ((a->addr32[3] & m->addr32[3]) ==
2698 (b->addr32[3] & m->addr32[3])))
2717 * Return 1 if b <= a <= e, otherwise return 0.
2720 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2721 struct pf_addr *a, sa_family_t af)
2726 if ((ntohl(a->addr32[0]) < ntohl(b->addr32[0])) ||
2727 (ntohl(a->addr32[0]) > ntohl(e->addr32[0])))
2736 for (i = 0; i < 4; ++i)
2737 if (ntohl(a->addr32[i]) > ntohl(b->addr32[i]))
2739 else if (ntohl(a->addr32[i]) < ntohl(b->addr32[i]))
2742 for (i = 0; i < 4; ++i)
2743 if (ntohl(a->addr32[i]) < ntohl(e->addr32[i]))
2745 else if (ntohl(a->addr32[i]) > ntohl(e->addr32[i]))
2755 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2759 return ((p > a1) && (p < a2));
2761 return ((p < a1) || (p > a2));
2763 return ((p >= a1) && (p <= a2));
2777 return (0); /* never reached */
2781 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2786 return (pf_match(op, a1, a2, p));
2790 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2792 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2794 return (pf_match(op, a1, a2, u));
2798 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2800 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2802 return (pf_match(op, a1, a2, g));
2806 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2811 return ((!r->match_tag_not && r->match_tag == *tag) ||
2812 (r->match_tag_not && r->match_tag != *tag));
2816 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2819 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2821 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2824 pd->pf_mtag->tag = tag;
2829 #define PF_ANCHOR_STACKSIZE 32
2830 struct pf_anchor_stackframe {
2831 struct pf_ruleset *rs;
2832 struct pf_rule *r; /* XXX: + match bit */
2833 struct pf_anchor *child;
2837 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2839 #define PF_ANCHORSTACK_MATCH 0x00000001
2840 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2842 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2843 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2844 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2845 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2846 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2850 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2851 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2854 struct pf_anchor_stackframe *f;
2860 if (*depth >= PF_ANCHOR_STACKSIZE) {
2861 printf("%s: anchor stack overflow on %s\n",
2862 __func__, (*r)->anchor->name);
2863 *r = TAILQ_NEXT(*r, entries);
2865 } else if (*depth == 0 && a != NULL)
2867 f = stack + (*depth)++;
2870 if ((*r)->anchor_wildcard) {
2871 struct pf_anchor_node *parent = &(*r)->anchor->children;
2873 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2877 *rs = &f->child->ruleset;
2880 *rs = &(*r)->anchor->ruleset;
2882 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2886 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2887 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2890 struct pf_anchor_stackframe *f;
2899 f = stack + *depth - 1;
2900 fr = PF_ANCHOR_RULE(f);
2901 if (f->child != NULL) {
2902 struct pf_anchor_node *parent;
2905 * This block traverses through
2906 * a wildcard anchor.
2908 parent = &fr->anchor->children;
2909 if (match != NULL && *match) {
2911 * If any of "*" matched, then
2912 * "foo/ *" matched, mark frame
2915 PF_ANCHOR_SET_MATCH(f);
2918 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2919 if (f->child != NULL) {
2920 *rs = &f->child->ruleset;
2921 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2929 if (*depth == 0 && a != NULL)
2932 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2934 *r = TAILQ_NEXT(fr, entries);
2935 } while (*r == NULL);
2942 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2943 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2948 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2949 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2953 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2954 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2955 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2956 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2957 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2958 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2959 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2960 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2966 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2971 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2975 if (addr->addr32[3] == 0xffffffff) {
2976 addr->addr32[3] = 0;
2977 if (addr->addr32[2] == 0xffffffff) {
2978 addr->addr32[2] = 0;
2979 if (addr->addr32[1] == 0xffffffff) {
2980 addr->addr32[1] = 0;
2982 htonl(ntohl(addr->addr32[0]) + 1);
2985 htonl(ntohl(addr->addr32[1]) + 1);
2988 htonl(ntohl(addr->addr32[2]) + 1);
2991 htonl(ntohl(addr->addr32[3]) + 1);
2998 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
3000 struct pf_addr *saddr, *daddr;
3001 u_int16_t sport, dport;
3002 struct inpcbinfo *pi;
3005 pd->lookup.uid = UID_MAX;
3006 pd->lookup.gid = GID_MAX;
3008 switch (pd->proto) {
3010 if (pd->hdr.tcp == NULL)
3012 sport = pd->hdr.tcp->th_sport;
3013 dport = pd->hdr.tcp->th_dport;
3017 if (pd->hdr.udp == NULL)
3019 sport = pd->hdr.udp->uh_sport;
3020 dport = pd->hdr.udp->uh_dport;
3026 if (direction == PF_IN) {
3041 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
3042 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3044 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
3045 daddr->v4, dport, INPLOOKUP_WILDCARD |
3046 INPLOOKUP_RLOCKPCB, NULL, m);
3054 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
3055 dport, INPLOOKUP_RLOCKPCB, NULL, m);
3057 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
3058 &daddr->v6, dport, INPLOOKUP_WILDCARD |
3059 INPLOOKUP_RLOCKPCB, NULL, m);
3069 INP_RLOCK_ASSERT(inp);
3070 pd->lookup.uid = inp->inp_cred->cr_uid;
3071 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3078 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3082 u_int8_t *opt, optlen;
3083 u_int8_t wscale = 0;
3085 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3086 if (hlen <= sizeof(struct tcphdr))
3088 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3090 opt = hdr + sizeof(struct tcphdr);
3091 hlen -= sizeof(struct tcphdr);
3101 if (wscale > TCP_MAX_WINSHIFT)
3102 wscale = TCP_MAX_WINSHIFT;
3103 wscale |= PF_WSCALE_FLAG;
3118 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3122 u_int8_t *opt, optlen;
3123 u_int16_t mss = V_tcp_mssdflt;
3125 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3126 if (hlen <= sizeof(struct tcphdr))
3128 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3130 opt = hdr + sizeof(struct tcphdr);
3131 hlen -= sizeof(struct tcphdr);
3132 while (hlen >= TCPOLEN_MAXSEG) {
3140 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3156 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3159 struct nhop4_basic nh4;
3162 struct nhop6_basic nh6;
3163 struct in6_addr dst6;
3172 hlen = sizeof(struct ip);
3173 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) == 0)
3174 mss = nh4.nh_mtu - hlen - sizeof(struct tcphdr);
3179 hlen = sizeof(struct ip6_hdr);
3180 in6_splitscope(&addr->v6, &dst6, &scopeid);
3181 if (fib6_lookup_nh_basic(rtableid, &dst6, scopeid, 0,0,&nh6)==0)
3182 mss = nh6.nh_mtu - hlen - sizeof(struct tcphdr);
3187 mss = max(V_tcp_mssdflt, mss);
3188 mss = min(mss, offer);
3189 mss = max(mss, 64); /* sanity - at least max opt space */
3194 pf_tcp_iss(struct pf_pdesc *pd)
3197 u_int32_t digest[4];
3199 if (V_pf_tcp_secret_init == 0) {
3200 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3201 MD5Init(&V_pf_tcp_secret_ctx);
3202 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3203 sizeof(V_pf_tcp_secret));
3204 V_pf_tcp_secret_init = 1;
3207 ctx = V_pf_tcp_secret_ctx;
3209 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3210 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3211 if (pd->af == AF_INET6) {
3212 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3213 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3215 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3216 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3218 MD5Final((u_char *)digest, &ctx);
3219 V_pf_tcp_iss_off += 4096;
3220 #define ISN_RANDOM_INCREMENT (4096 - 1)
3221 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3223 #undef ISN_RANDOM_INCREMENT
3227 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3228 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3229 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3231 struct pf_rule *nr = NULL;
3232 struct pf_addr * const saddr = pd->src;
3233 struct pf_addr * const daddr = pd->dst;
3234 sa_family_t af = pd->af;
3235 struct pf_rule *r, *a = NULL;
3236 struct pf_ruleset *ruleset = NULL;
3237 struct pf_src_node *nsn = NULL;
3238 struct tcphdr *th = pd->hdr.tcp;
3239 struct pf_state_key *sk = NULL, *nk = NULL;
3241 int rewrite = 0, hdrlen = 0;
3242 int tag = -1, rtableid = -1;
3246 u_int16_t sport = 0, dport = 0;
3247 u_int16_t bproto_sum = 0, bip_sum = 0;
3248 u_int8_t icmptype = 0, icmpcode = 0;
3249 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3254 INP_LOCK_ASSERT(inp);
3255 pd->lookup.uid = inp->inp_cred->cr_uid;
3256 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3257 pd->lookup.done = 1;
3260 switch (pd->proto) {
3262 sport = th->th_sport;
3263 dport = th->th_dport;
3264 hdrlen = sizeof(*th);
3267 sport = pd->hdr.udp->uh_sport;
3268 dport = pd->hdr.udp->uh_dport;
3269 hdrlen = sizeof(*pd->hdr.udp);
3273 if (pd->af != AF_INET)
3275 sport = dport = pd->hdr.icmp->icmp_id;
3276 hdrlen = sizeof(*pd->hdr.icmp);
3277 icmptype = pd->hdr.icmp->icmp_type;
3278 icmpcode = pd->hdr.icmp->icmp_code;
3280 if (icmptype == ICMP_UNREACH ||
3281 icmptype == ICMP_SOURCEQUENCH ||
3282 icmptype == ICMP_REDIRECT ||
3283 icmptype == ICMP_TIMXCEED ||
3284 icmptype == ICMP_PARAMPROB)
3289 case IPPROTO_ICMPV6:
3292 sport = dport = pd->hdr.icmp6->icmp6_id;
3293 hdrlen = sizeof(*pd->hdr.icmp6);
3294 icmptype = pd->hdr.icmp6->icmp6_type;
3295 icmpcode = pd->hdr.icmp6->icmp6_code;
3297 if (icmptype == ICMP6_DST_UNREACH ||
3298 icmptype == ICMP6_PACKET_TOO_BIG ||
3299 icmptype == ICMP6_TIME_EXCEEDED ||
3300 icmptype == ICMP6_PARAM_PROB)
3305 sport = dport = hdrlen = 0;
3309 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3311 /* check packet for BINAT/NAT/RDR */
3312 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3313 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3314 KASSERT(sk != NULL, ("%s: null sk", __func__));
3315 KASSERT(nk != NULL, ("%s: null nk", __func__));
3318 bip_sum = *pd->ip_sum;
3320 switch (pd->proto) {
3322 bproto_sum = th->th_sum;
3323 pd->proto_sum = &th->th_sum;
3325 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3326 nk->port[pd->sidx] != sport) {
3327 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3328 &th->th_sum, &nk->addr[pd->sidx],
3329 nk->port[pd->sidx], 0, af);
3330 pd->sport = &th->th_sport;
3331 sport = th->th_sport;
3334 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3335 nk->port[pd->didx] != dport) {
3336 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3337 &th->th_sum, &nk->addr[pd->didx],
3338 nk->port[pd->didx], 0, af);
3339 dport = th->th_dport;
3340 pd->dport = &th->th_dport;
3345 bproto_sum = pd->hdr.udp->uh_sum;
3346 pd->proto_sum = &pd->hdr.udp->uh_sum;
3348 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3349 nk->port[pd->sidx] != sport) {
3350 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3351 pd->ip_sum, &pd->hdr.udp->uh_sum,
3352 &nk->addr[pd->sidx],
3353 nk->port[pd->sidx], 1, af);
3354 sport = pd->hdr.udp->uh_sport;
3355 pd->sport = &pd->hdr.udp->uh_sport;
3358 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3359 nk->port[pd->didx] != dport) {
3360 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3361 pd->ip_sum, &pd->hdr.udp->uh_sum,
3362 &nk->addr[pd->didx],
3363 nk->port[pd->didx], 1, af);
3364 dport = pd->hdr.udp->uh_dport;
3365 pd->dport = &pd->hdr.udp->uh_dport;
3371 nk->port[0] = nk->port[1];
3372 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3373 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3374 nk->addr[pd->sidx].v4.s_addr, 0);
3376 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3377 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3378 nk->addr[pd->didx].v4.s_addr, 0);
3380 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3381 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3382 pd->hdr.icmp->icmp_cksum, sport,
3384 pd->hdr.icmp->icmp_id = nk->port[1];
3385 pd->sport = &pd->hdr.icmp->icmp_id;
3387 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3391 case IPPROTO_ICMPV6:
3392 nk->port[0] = nk->port[1];
3393 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3394 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3395 &nk->addr[pd->sidx], 0);
3397 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3398 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3399 &nk->addr[pd->didx], 0);
3408 &nk->addr[pd->sidx], AF_INET))
3409 pf_change_a(&saddr->v4.s_addr,
3411 nk->addr[pd->sidx].v4.s_addr, 0);
3414 &nk->addr[pd->didx], AF_INET))
3415 pf_change_a(&daddr->v4.s_addr,
3417 nk->addr[pd->didx].v4.s_addr, 0);
3423 &nk->addr[pd->sidx], AF_INET6))
3424 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3427 &nk->addr[pd->didx], AF_INET6))
3428 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3441 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3442 r = r->skip[PF_SKIP_IFP].ptr;
3443 else if (r->direction && r->direction != direction)
3444 r = r->skip[PF_SKIP_DIR].ptr;
3445 else if (r->af && r->af != af)
3446 r = r->skip[PF_SKIP_AF].ptr;
3447 else if (r->proto && r->proto != pd->proto)
3448 r = r->skip[PF_SKIP_PROTO].ptr;
3449 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3450 r->src.neg, kif, M_GETFIB(m)))
3451 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3452 /* tcp/udp only. port_op always 0 in other cases */
3453 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3454 r->src.port[0], r->src.port[1], sport))
3455 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3456 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3457 r->dst.neg, NULL, M_GETFIB(m)))
3458 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3459 /* tcp/udp only. port_op always 0 in other cases */
3460 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3461 r->dst.port[0], r->dst.port[1], dport))
3462 r = r->skip[PF_SKIP_DST_PORT].ptr;
3463 /* icmp only. type always 0 in other cases */
3464 else if (r->type && r->type != icmptype + 1)
3465 r = TAILQ_NEXT(r, entries);
3466 /* icmp only. type always 0 in other cases */
3467 else if (r->code && r->code != icmpcode + 1)
3468 r = TAILQ_NEXT(r, entries);
3469 else if (r->tos && !(r->tos == pd->tos))
3470 r = TAILQ_NEXT(r, entries);
3471 else if (r->rule_flag & PFRULE_FRAGMENT)
3472 r = TAILQ_NEXT(r, entries);
3473 else if (pd->proto == IPPROTO_TCP &&
3474 (r->flagset & th->th_flags) != r->flags)
3475 r = TAILQ_NEXT(r, entries);
3476 /* tcp/udp only. uid.op always 0 in other cases */
3477 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3478 pf_socket_lookup(direction, pd, m), 1)) &&
3479 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3481 r = TAILQ_NEXT(r, entries);
3482 /* tcp/udp only. gid.op always 0 in other cases */
3483 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3484 pf_socket_lookup(direction, pd, m), 1)) &&
3485 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3487 r = TAILQ_NEXT(r, entries);
3489 !pf_match_ieee8021q_pcp(r->prio, m))
3490 r = TAILQ_NEXT(r, entries);
3492 r->prob <= arc4random())
3493 r = TAILQ_NEXT(r, entries);
3494 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3495 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3496 r = TAILQ_NEXT(r, entries);
3497 else if (r->os_fingerprint != PF_OSFP_ANY &&
3498 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3499 pf_osfp_fingerprint(pd, m, off, th),
3500 r->os_fingerprint)))
3501 r = TAILQ_NEXT(r, entries);
3505 if (r->rtableid >= 0)
3506 rtableid = r->rtableid;
3507 if (r->anchor == NULL) {
3514 r = TAILQ_NEXT(r, entries);
3516 pf_step_into_anchor(anchor_stack, &asd,
3517 &ruleset, PF_RULESET_FILTER, &r, &a,
3520 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3521 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3528 REASON_SET(&reason, PFRES_MATCH);
3530 if (r->log || (nr != NULL && nr->log)) {
3532 m_copyback(m, off, hdrlen, pd->hdr.any);
3533 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3537 if ((r->action == PF_DROP) &&
3538 ((r->rule_flag & PFRULE_RETURNRST) ||
3539 (r->rule_flag & PFRULE_RETURNICMP) ||
3540 (r->rule_flag & PFRULE_RETURN))) {
3541 pf_return(r, nr, pd, sk, off, m, th, kif, bproto_sum,
3542 bip_sum, hdrlen, &reason);
3545 if (r->action == PF_DROP)
3548 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3549 REASON_SET(&reason, PFRES_MEMORY);
3553 M_SETFIB(m, rtableid);
3555 if (!state_icmp && (r->keep_state || nr != NULL ||
3556 (pd->flags & PFDESC_TCP_NORM))) {
3558 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3559 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3561 if (action != PF_PASS) {
3562 if (action == PF_DROP &&
3563 (r->rule_flag & PFRULE_RETURN))
3564 pf_return(r, nr, pd, sk, off, m, th, kif,
3565 bproto_sum, bip_sum, hdrlen, &reason);
3570 uma_zfree(V_pf_state_key_z, sk);
3572 uma_zfree(V_pf_state_key_z, nk);
3575 /* copy back packet headers if we performed NAT operations */
3577 m_copyback(m, off, hdrlen, pd->hdr.any);
3579 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3580 direction == PF_OUT &&
3581 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3583 * We want the state created, but we dont
3584 * want to send this in case a partner
3585 * firewall has to know about it to allow
3586 * replies through it.
3594 uma_zfree(V_pf_state_key_z, sk);
3596 uma_zfree(V_pf_state_key_z, nk);
3601 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3602 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3603 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3604 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3605 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3607 struct pf_state *s = NULL;
3608 struct pf_src_node *sn = NULL;
3609 struct tcphdr *th = pd->hdr.tcp;
3610 u_int16_t mss = V_tcp_mssdflt;
3613 /* check maximums */
3614 if (r->max_states &&
3615 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3616 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3617 REASON_SET(&reason, PFRES_MAXSTATES);
3620 /* src node for filter rule */
3621 if ((r->rule_flag & PFRULE_SRCTRACK ||
3622 r->rpool.opts & PF_POOL_STICKYADDR) &&
3623 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3624 REASON_SET(&reason, PFRES_SRCLIMIT);
3627 /* src node for translation rule */
3628 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3629 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3630 REASON_SET(&reason, PFRES_SRCLIMIT);
3633 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3635 REASON_SET(&reason, PFRES_MEMORY);
3639 s->nat_rule.ptr = nr;
3641 STATE_INC_COUNTERS(s);
3643 s->state_flags |= PFSTATE_ALLOWOPTS;
3644 if (r->rule_flag & PFRULE_STATESLOPPY)
3645 s->state_flags |= PFSTATE_SLOPPY;
3646 s->log = r->log & PF_LOG_ALL;
3647 s->sync_state = PFSYNC_S_NONE;
3649 s->log |= nr->log & PF_LOG_ALL;
3650 switch (pd->proto) {
3652 s->src.seqlo = ntohl(th->th_seq);
3653 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3654 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3655 r->keep_state == PF_STATE_MODULATE) {
3656 /* Generate sequence number modulator */
3657 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3660 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3661 htonl(s->src.seqlo + s->src.seqdiff), 0);
3665 if (th->th_flags & TH_SYN) {
3667 s->src.wscale = pf_get_wscale(m, off,
3668 th->th_off, pd->af);
3670 s->src.max_win = MAX(ntohs(th->th_win), 1);
3671 if (s->src.wscale & PF_WSCALE_MASK) {
3672 /* Remove scale factor from initial window */
3673 int win = s->src.max_win;
3674 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3675 s->src.max_win = (win - 1) >>
3676 (s->src.wscale & PF_WSCALE_MASK);
3678 if (th->th_flags & TH_FIN)
3682 s->src.state = TCPS_SYN_SENT;
3683 s->dst.state = TCPS_CLOSED;
3684 s->timeout = PFTM_TCP_FIRST_PACKET;
3687 s->src.state = PFUDPS_SINGLE;
3688 s->dst.state = PFUDPS_NO_TRAFFIC;
3689 s->timeout = PFTM_UDP_FIRST_PACKET;
3693 case IPPROTO_ICMPV6:
3695 s->timeout = PFTM_ICMP_FIRST_PACKET;
3698 s->src.state = PFOTHERS_SINGLE;
3699 s->dst.state = PFOTHERS_NO_TRAFFIC;
3700 s->timeout = PFTM_OTHER_FIRST_PACKET;
3704 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3705 REASON_SET(&reason, PFRES_MAPFAILED);
3706 pf_src_tree_remove_state(s);
3707 STATE_DEC_COUNTERS(s);
3708 uma_zfree(V_pf_state_z, s);
3711 s->rt_kif = r->rpool.cur->kif;
3714 s->creation = time_uptime;
3715 s->expire = time_uptime;
3720 /* XXX We only modify one side for now. */
3721 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3722 s->nat_src_node = nsn;
3724 if (pd->proto == IPPROTO_TCP) {
3725 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3726 off, pd, th, &s->src, &s->dst)) {
3727 REASON_SET(&reason, PFRES_MEMORY);
3728 pf_src_tree_remove_state(s);
3729 STATE_DEC_COUNTERS(s);
3730 uma_zfree(V_pf_state_z, s);
3733 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3734 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3735 &s->src, &s->dst, rewrite)) {
3736 /* This really shouldn't happen!!! */
3737 DPFPRINTF(PF_DEBUG_URGENT,
3738 ("pf_normalize_tcp_stateful failed on first pkt"));
3739 pf_normalize_tcp_cleanup(s);
3740 pf_src_tree_remove_state(s);
3741 STATE_DEC_COUNTERS(s);
3742 uma_zfree(V_pf_state_z, s);
3746 s->direction = pd->dir;
3749 * sk/nk could already been setup by pf_get_translation().
3752 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3753 __func__, nr, sk, nk));
3754 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3759 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3760 __func__, nr, sk, nk));
3762 /* Swap sk/nk for PF_OUT. */
3763 if (pf_state_insert(BOUND_IFACE(r, kif),
3764 (pd->dir == PF_IN) ? sk : nk,
3765 (pd->dir == PF_IN) ? nk : sk, s)) {
3766 if (pd->proto == IPPROTO_TCP)
3767 pf_normalize_tcp_cleanup(s);
3768 REASON_SET(&reason, PFRES_STATEINS);
3769 pf_src_tree_remove_state(s);
3770 STATE_DEC_COUNTERS(s);
3771 uma_zfree(V_pf_state_z, s);
3778 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3779 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3780 s->src.state = PF_TCPS_PROXY_SRC;
3781 /* undo NAT changes, if they have taken place */
3783 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3784 if (pd->dir == PF_OUT)
3785 skt = s->key[PF_SK_STACK];
3786 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3787 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3789 *pd->sport = skt->port[pd->sidx];
3791 *pd->dport = skt->port[pd->didx];
3793 *pd->proto_sum = bproto_sum;
3795 *pd->ip_sum = bip_sum;
3796 m_copyback(m, off, hdrlen, pd->hdr.any);
3798 s->src.seqhi = htonl(arc4random());
3799 /* Find mss option */
3800 int rtid = M_GETFIB(m);
3801 mss = pf_get_mss(m, off, th->th_off, pd->af);
3802 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3803 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3805 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3806 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3807 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3808 REASON_SET(&reason, PFRES_SYNPROXY);
3809 return (PF_SYNPROXY_DROP);
3816 uma_zfree(V_pf_state_key_z, sk);
3818 uma_zfree(V_pf_state_key_z, nk);
3821 struct pf_srchash *sh;
3823 sh = &V_pf_srchash[pf_hashsrc(&sn->addr, sn->af)];
3824 PF_HASHROW_LOCK(sh);
3825 if (--sn->states == 0 && sn->expire == 0) {
3826 pf_unlink_src_node(sn);
3827 uma_zfree(V_pf_sources_z, sn);
3829 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3831 PF_HASHROW_UNLOCK(sh);
3834 if (nsn != sn && nsn != NULL) {
3835 struct pf_srchash *sh;
3837 sh = &V_pf_srchash[pf_hashsrc(&nsn->addr, nsn->af)];
3838 PF_HASHROW_LOCK(sh);
3839 if (--nsn->states == 0 && nsn->expire == 0) {
3840 pf_unlink_src_node(nsn);
3841 uma_zfree(V_pf_sources_z, nsn);
3843 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
3845 PF_HASHROW_UNLOCK(sh);
3852 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3853 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3854 struct pf_ruleset **rsm)
3856 struct pf_rule *r, *a = NULL;
3857 struct pf_ruleset *ruleset = NULL;
3858 sa_family_t af = pd->af;
3863 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3867 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3870 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3871 r = r->skip[PF_SKIP_IFP].ptr;
3872 else if (r->direction && r->direction != direction)
3873 r = r->skip[PF_SKIP_DIR].ptr;
3874 else if (r->af && r->af != af)
3875 r = r->skip[PF_SKIP_AF].ptr;
3876 else if (r->proto && r->proto != pd->proto)
3877 r = r->skip[PF_SKIP_PROTO].ptr;
3878 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3879 r->src.neg, kif, M_GETFIB(m)))
3880 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3881 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3882 r->dst.neg, NULL, M_GETFIB(m)))
3883 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3884 else if (r->tos && !(r->tos == pd->tos))
3885 r = TAILQ_NEXT(r, entries);
3886 else if (r->os_fingerprint != PF_OSFP_ANY)
3887 r = TAILQ_NEXT(r, entries);
3888 else if (pd->proto == IPPROTO_UDP &&
3889 (r->src.port_op || r->dst.port_op))
3890 r = TAILQ_NEXT(r, entries);
3891 else if (pd->proto == IPPROTO_TCP &&
3892 (r->src.port_op || r->dst.port_op || r->flagset))
3893 r = TAILQ_NEXT(r, entries);
3894 else if ((pd->proto == IPPROTO_ICMP ||
3895 pd->proto == IPPROTO_ICMPV6) &&
3896 (r->type || r->code))
3897 r = TAILQ_NEXT(r, entries);
3899 !pf_match_ieee8021q_pcp(r->prio, m))
3900 r = TAILQ_NEXT(r, entries);
3901 else if (r->prob && r->prob <=
3902 (arc4random() % (UINT_MAX - 1) + 1))
3903 r = TAILQ_NEXT(r, entries);
3904 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3905 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3906 r = TAILQ_NEXT(r, entries);
3908 if (r->anchor == NULL) {
3915 r = TAILQ_NEXT(r, entries);
3917 pf_step_into_anchor(anchor_stack, &asd,
3918 &ruleset, PF_RULESET_FILTER, &r, &a,
3921 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3922 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3929 REASON_SET(&reason, PFRES_MATCH);
3932 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3935 if (r->action != PF_PASS)
3938 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3939 REASON_SET(&reason, PFRES_MEMORY);
3947 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3948 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3949 struct pf_pdesc *pd, u_short *reason, int *copyback)
3951 struct tcphdr *th = pd->hdr.tcp;
3952 u_int16_t win = ntohs(th->th_win);
3953 u_int32_t ack, end, seq, orig_seq;
3957 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3958 sws = src->wscale & PF_WSCALE_MASK;
3959 dws = dst->wscale & PF_WSCALE_MASK;
3964 * Sequence tracking algorithm from Guido van Rooij's paper:
3965 * http://www.madison-gurkha.com/publications/tcp_filtering/
3969 orig_seq = seq = ntohl(th->th_seq);
3970 if (src->seqlo == 0) {
3971 /* First packet from this end. Set its state */
3973 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3974 src->scrub == NULL) {
3975 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3976 REASON_SET(reason, PFRES_MEMORY);
3981 /* Deferred generation of sequence number modulator */
3982 if (dst->seqdiff && !src->seqdiff) {
3983 /* use random iss for the TCP server */
3984 while ((src->seqdiff = arc4random() - seq) == 0)
3986 ack = ntohl(th->th_ack) - dst->seqdiff;
3987 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3989 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3992 ack = ntohl(th->th_ack);
3995 end = seq + pd->p_len;
3996 if (th->th_flags & TH_SYN) {
3998 if (dst->wscale & PF_WSCALE_FLAG) {
3999 src->wscale = pf_get_wscale(m, off, th->th_off,
4001 if (src->wscale & PF_WSCALE_FLAG) {
4002 /* Remove scale factor from initial
4004 sws = src->wscale & PF_WSCALE_MASK;
4005 win = ((u_int32_t)win + (1 << sws) - 1)
4007 dws = dst->wscale & PF_WSCALE_MASK;
4009 /* fixup other window */
4010 dst->max_win <<= dst->wscale &
4012 /* in case of a retrans SYN|ACK */
4017 if (th->th_flags & TH_FIN)
4021 if (src->state < TCPS_SYN_SENT)
4022 src->state = TCPS_SYN_SENT;
4025 * May need to slide the window (seqhi may have been set by
4026 * the crappy stack check or if we picked up the connection
4027 * after establishment)
4029 if (src->seqhi == 1 ||
4030 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4031 src->seqhi = end + MAX(1, dst->max_win << dws);
4032 if (win > src->max_win)
4036 ack = ntohl(th->th_ack) - dst->seqdiff;
4038 /* Modulate sequence numbers */
4039 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
4041 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
4044 end = seq + pd->p_len;
4045 if (th->th_flags & TH_SYN)
4047 if (th->th_flags & TH_FIN)
4051 if ((th->th_flags & TH_ACK) == 0) {
4052 /* Let it pass through the ack skew check */
4054 } else if ((ack == 0 &&
4055 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4056 /* broken tcp stacks do not set ack */
4057 (dst->state < TCPS_SYN_SENT)) {
4059 * Many stacks (ours included) will set the ACK number in an
4060 * FIN|ACK if the SYN times out -- no sequence to ACK.
4066 /* Ease sequencing restrictions on no data packets */
4071 ackskew = dst->seqlo - ack;
4075 * Need to demodulate the sequence numbers in any TCP SACK options
4076 * (Selective ACK). We could optionally validate the SACK values
4077 * against the current ACK window, either forwards or backwards, but
4078 * I'm not confident that SACK has been implemented properly
4079 * everywhere. It wouldn't surprise me if several stacks accidentally
4080 * SACK too far backwards of previously ACKed data. There really aren't
4081 * any security implications of bad SACKing unless the target stack
4082 * doesn't validate the option length correctly. Someone trying to
4083 * spoof into a TCP connection won't bother blindly sending SACK
4086 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4087 if (pf_modulate_sack(m, off, pd, th, dst))
4092 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4093 if (SEQ_GEQ(src->seqhi, end) &&
4094 /* Last octet inside other's window space */
4095 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4096 /* Retrans: not more than one window back */
4097 (ackskew >= -MAXACKWINDOW) &&
4098 /* Acking not more than one reassembled fragment backwards */
4099 (ackskew <= (MAXACKWINDOW << sws)) &&
4100 /* Acking not more than one window forward */
4101 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4102 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4103 (pd->flags & PFDESC_IP_REAS) == 0)) {
4104 /* Require an exact/+1 sequence match on resets when possible */
4106 if (dst->scrub || src->scrub) {
4107 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4108 *state, src, dst, copyback))
4112 /* update max window */
4113 if (src->max_win < win)
4115 /* synchronize sequencing */
4116 if (SEQ_GT(end, src->seqlo))
4118 /* slide the window of what the other end can send */
4119 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4120 dst->seqhi = ack + MAX((win << sws), 1);
4124 if (th->th_flags & TH_SYN)
4125 if (src->state < TCPS_SYN_SENT)
4126 src->state = TCPS_SYN_SENT;
4127 if (th->th_flags & TH_FIN)
4128 if (src->state < TCPS_CLOSING)
4129 src->state = TCPS_CLOSING;
4130 if (th->th_flags & TH_ACK) {
4131 if (dst->state == TCPS_SYN_SENT) {
4132 dst->state = TCPS_ESTABLISHED;
4133 if (src->state == TCPS_ESTABLISHED &&
4134 (*state)->src_node != NULL &&
4135 pf_src_connlimit(state)) {
4136 REASON_SET(reason, PFRES_SRCLIMIT);
4139 } else if (dst->state == TCPS_CLOSING)
4140 dst->state = TCPS_FIN_WAIT_2;
4142 if (th->th_flags & TH_RST)
4143 src->state = dst->state = TCPS_TIME_WAIT;
4145 /* update expire time */
4146 (*state)->expire = time_uptime;
4147 if (src->state >= TCPS_FIN_WAIT_2 &&
4148 dst->state >= TCPS_FIN_WAIT_2)
4149 (*state)->timeout = PFTM_TCP_CLOSED;
4150 else if (src->state >= TCPS_CLOSING &&
4151 dst->state >= TCPS_CLOSING)
4152 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4153 else if (src->state < TCPS_ESTABLISHED ||
4154 dst->state < TCPS_ESTABLISHED)
4155 (*state)->timeout = PFTM_TCP_OPENING;
4156 else if (src->state >= TCPS_CLOSING ||
4157 dst->state >= TCPS_CLOSING)
4158 (*state)->timeout = PFTM_TCP_CLOSING;
4160 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4162 /* Fall through to PASS packet */
4164 } else if ((dst->state < TCPS_SYN_SENT ||
4165 dst->state >= TCPS_FIN_WAIT_2 ||
4166 src->state >= TCPS_FIN_WAIT_2) &&
4167 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4168 /* Within a window forward of the originating packet */
4169 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4170 /* Within a window backward of the originating packet */
4173 * This currently handles three situations:
4174 * 1) Stupid stacks will shotgun SYNs before their peer
4176 * 2) When PF catches an already established stream (the
4177 * firewall rebooted, the state table was flushed, routes
4179 * 3) Packets get funky immediately after the connection
4180 * closes (this should catch Solaris spurious ACK|FINs
4181 * that web servers like to spew after a close)
4183 * This must be a little more careful than the above code
4184 * since packet floods will also be caught here. We don't
4185 * update the TTL here to mitigate the damage of a packet
4186 * flood and so the same code can handle awkward establishment
4187 * and a loosened connection close.
4188 * In the establishment case, a correct peer response will
4189 * validate the connection, go through the normal state code
4190 * and keep updating the state TTL.
4193 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4194 printf("pf: loose state match: ");
4195 pf_print_state(*state);
4196 pf_print_flags(th->th_flags);
4197 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4198 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4199 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4200 (unsigned long long)(*state)->packets[1],
4201 pd->dir == PF_IN ? "in" : "out",
4202 pd->dir == (*state)->direction ? "fwd" : "rev");
4205 if (dst->scrub || src->scrub) {
4206 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4207 *state, src, dst, copyback))
4211 /* update max window */
4212 if (src->max_win < win)
4214 /* synchronize sequencing */
4215 if (SEQ_GT(end, src->seqlo))
4217 /* slide the window of what the other end can send */
4218 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4219 dst->seqhi = ack + MAX((win << sws), 1);
4222 * Cannot set dst->seqhi here since this could be a shotgunned
4223 * SYN and not an already established connection.
4226 if (th->th_flags & TH_FIN)
4227 if (src->state < TCPS_CLOSING)
4228 src->state = TCPS_CLOSING;
4229 if (th->th_flags & TH_RST)
4230 src->state = dst->state = TCPS_TIME_WAIT;
4232 /* Fall through to PASS packet */
4235 if ((*state)->dst.state == TCPS_SYN_SENT &&
4236 (*state)->src.state == TCPS_SYN_SENT) {
4237 /* Send RST for state mismatches during handshake */
4238 if (!(th->th_flags & TH_RST))
4239 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4240 pd->dst, pd->src, th->th_dport,
4241 th->th_sport, ntohl(th->th_ack), 0,
4243 (*state)->rule.ptr->return_ttl, 1, 0,
4248 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4249 printf("pf: BAD state: ");
4250 pf_print_state(*state);
4251 pf_print_flags(th->th_flags);
4252 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4253 "pkts=%llu:%llu dir=%s,%s\n",
4254 seq, orig_seq, ack, pd->p_len, ackskew,
4255 (unsigned long long)(*state)->packets[0],
4256 (unsigned long long)(*state)->packets[1],
4257 pd->dir == PF_IN ? "in" : "out",
4258 pd->dir == (*state)->direction ? "fwd" : "rev");
4259 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4260 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4261 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4263 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4264 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4265 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4266 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4268 REASON_SET(reason, PFRES_BADSTATE);
4276 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4277 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4279 struct tcphdr *th = pd->hdr.tcp;
4281 if (th->th_flags & TH_SYN)
4282 if (src->state < TCPS_SYN_SENT)
4283 src->state = TCPS_SYN_SENT;
4284 if (th->th_flags & TH_FIN)
4285 if (src->state < TCPS_CLOSING)
4286 src->state = TCPS_CLOSING;
4287 if (th->th_flags & TH_ACK) {
4288 if (dst->state == TCPS_SYN_SENT) {
4289 dst->state = TCPS_ESTABLISHED;
4290 if (src->state == TCPS_ESTABLISHED &&
4291 (*state)->src_node != NULL &&
4292 pf_src_connlimit(state)) {
4293 REASON_SET(reason, PFRES_SRCLIMIT);
4296 } else if (dst->state == TCPS_CLOSING) {
4297 dst->state = TCPS_FIN_WAIT_2;
4298 } else if (src->state == TCPS_SYN_SENT &&
4299 dst->state < TCPS_SYN_SENT) {
4301 * Handle a special sloppy case where we only see one
4302 * half of the connection. If there is a ACK after
4303 * the initial SYN without ever seeing a packet from
4304 * the destination, set the connection to established.
4306 dst->state = src->state = TCPS_ESTABLISHED;
4307 if ((*state)->src_node != NULL &&
4308 pf_src_connlimit(state)) {
4309 REASON_SET(reason, PFRES_SRCLIMIT);
4312 } else if (src->state == TCPS_CLOSING &&
4313 dst->state == TCPS_ESTABLISHED &&
4316 * Handle the closing of half connections where we
4317 * don't see the full bidirectional FIN/ACK+ACK
4320 dst->state = TCPS_CLOSING;
4323 if (th->th_flags & TH_RST)
4324 src->state = dst->state = TCPS_TIME_WAIT;
4326 /* update expire time */
4327 (*state)->expire = time_uptime;
4328 if (src->state >= TCPS_FIN_WAIT_2 &&
4329 dst->state >= TCPS_FIN_WAIT_2)
4330 (*state)->timeout = PFTM_TCP_CLOSED;
4331 else if (src->state >= TCPS_CLOSING &&
4332 dst->state >= TCPS_CLOSING)
4333 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4334 else if (src->state < TCPS_ESTABLISHED ||
4335 dst->state < TCPS_ESTABLISHED)
4336 (*state)->timeout = PFTM_TCP_OPENING;
4337 else if (src->state >= TCPS_CLOSING ||
4338 dst->state >= TCPS_CLOSING)
4339 (*state)->timeout = PFTM_TCP_CLOSING;
4341 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4347 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4348 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4351 struct pf_state_key_cmp key;
4352 struct tcphdr *th = pd->hdr.tcp;
4354 struct pf_state_peer *src, *dst;
4355 struct pf_state_key *sk;
4357 bzero(&key, sizeof(key));
4359 key.proto = IPPROTO_TCP;
4360 if (direction == PF_IN) { /* wire side, straight */
4361 PF_ACPY(&key.addr[0], pd->src, key.af);
4362 PF_ACPY(&key.addr[1], pd->dst, key.af);
4363 key.port[0] = th->th_sport;
4364 key.port[1] = th->th_dport;
4365 } else { /* stack side, reverse */
4366 PF_ACPY(&key.addr[1], pd->src, key.af);
4367 PF_ACPY(&key.addr[0], pd->dst, key.af);
4368 key.port[1] = th->th_sport;
4369 key.port[0] = th->th_dport;
4372 STATE_LOOKUP(kif, &key, direction, *state, pd);
4374 if (direction == (*state)->direction) {
4375 src = &(*state)->src;
4376 dst = &(*state)->dst;
4378 src = &(*state)->dst;
4379 dst = &(*state)->src;
4382 sk = (*state)->key[pd->didx];
4384 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4385 if (direction != (*state)->direction) {
4386 REASON_SET(reason, PFRES_SYNPROXY);
4387 return (PF_SYNPROXY_DROP);
4389 if (th->th_flags & TH_SYN) {
4390 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4391 REASON_SET(reason, PFRES_SYNPROXY);
4394 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4395 pd->src, th->th_dport, th->th_sport,
4396 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4397 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4398 REASON_SET(reason, PFRES_SYNPROXY);
4399 return (PF_SYNPROXY_DROP);
4400 } else if (!(th->th_flags & TH_ACK) ||
4401 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4402 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4403 REASON_SET(reason, PFRES_SYNPROXY);
4405 } else if ((*state)->src_node != NULL &&
4406 pf_src_connlimit(state)) {
4407 REASON_SET(reason, PFRES_SRCLIMIT);
4410 (*state)->src.state = PF_TCPS_PROXY_DST;
4412 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4413 if (direction == (*state)->direction) {
4414 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4415 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4416 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4417 REASON_SET(reason, PFRES_SYNPROXY);
4420 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4421 if ((*state)->dst.seqhi == 1)
4422 (*state)->dst.seqhi = htonl(arc4random());
4423 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4424 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4425 sk->port[pd->sidx], sk->port[pd->didx],
4426 (*state)->dst.seqhi, 0, TH_SYN, 0,
4427 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4428 REASON_SET(reason, PFRES_SYNPROXY);
4429 return (PF_SYNPROXY_DROP);
4430 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4432 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4433 REASON_SET(reason, PFRES_SYNPROXY);
4436 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4437 (*state)->dst.seqlo = ntohl(th->th_seq);
4438 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4439 pd->src, th->th_dport, th->th_sport,
4440 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4441 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4442 (*state)->tag, NULL);
4443 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4444 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4445 sk->port[pd->sidx], sk->port[pd->didx],
4446 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4447 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4448 (*state)->src.seqdiff = (*state)->dst.seqhi -
4449 (*state)->src.seqlo;
4450 (*state)->dst.seqdiff = (*state)->src.seqhi -
4451 (*state)->dst.seqlo;
4452 (*state)->src.seqhi = (*state)->src.seqlo +
4453 (*state)->dst.max_win;
4454 (*state)->dst.seqhi = (*state)->dst.seqlo +
4455 (*state)->src.max_win;
4456 (*state)->src.wscale = (*state)->dst.wscale = 0;
4457 (*state)->src.state = (*state)->dst.state =
4459 REASON_SET(reason, PFRES_SYNPROXY);
4460 return (PF_SYNPROXY_DROP);
4464 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4465 dst->state >= TCPS_FIN_WAIT_2 &&
4466 src->state >= TCPS_FIN_WAIT_2) {
4467 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4468 printf("pf: state reuse ");
4469 pf_print_state(*state);
4470 pf_print_flags(th->th_flags);
4473 /* XXX make sure it's the same direction ?? */
4474 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4475 pf_unlink_state(*state, PF_ENTER_LOCKED);
4480 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4481 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4484 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4485 ©back) == PF_DROP)
4489 /* translate source/destination address, if necessary */
4490 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4491 struct pf_state_key *nk = (*state)->key[pd->didx];
4493 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4494 nk->port[pd->sidx] != th->th_sport)
4495 pf_change_ap(m, pd->src, &th->th_sport,
4496 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4497 nk->port[pd->sidx], 0, pd->af);
4499 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4500 nk->port[pd->didx] != th->th_dport)
4501 pf_change_ap(m, pd->dst, &th->th_dport,
4502 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4503 nk->port[pd->didx], 0, pd->af);
4507 /* Copyback sequence modulation or stateful scrub changes if needed */
4509 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4515 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4516 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4518 struct pf_state_peer *src, *dst;
4519 struct pf_state_key_cmp key;
4520 struct udphdr *uh = pd->hdr.udp;
4522 bzero(&key, sizeof(key));
4524 key.proto = IPPROTO_UDP;
4525 if (direction == PF_IN) { /* wire side, straight */
4526 PF_ACPY(&key.addr[0], pd->src, key.af);
4527 PF_ACPY(&key.addr[1], pd->dst, key.af);
4528 key.port[0] = uh->uh_sport;
4529 key.port[1] = uh->uh_dport;
4530 } else { /* stack side, reverse */
4531 PF_ACPY(&key.addr[1], pd->src, key.af);
4532 PF_ACPY(&key.addr[0], pd->dst, key.af);
4533 key.port[1] = uh->uh_sport;
4534 key.port[0] = uh->uh_dport;
4537 STATE_LOOKUP(kif, &key, direction, *state, pd);
4539 if (direction == (*state)->direction) {
4540 src = &(*state)->src;
4541 dst = &(*state)->dst;
4543 src = &(*state)->dst;
4544 dst = &(*state)->src;
4548 if (src->state < PFUDPS_SINGLE)
4549 src->state = PFUDPS_SINGLE;
4550 if (dst->state == PFUDPS_SINGLE)
4551 dst->state = PFUDPS_MULTIPLE;
4553 /* update expire time */
4554 (*state)->expire = time_uptime;
4555 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4556 (*state)->timeout = PFTM_UDP_MULTIPLE;
4558 (*state)->timeout = PFTM_UDP_SINGLE;
4560 /* translate source/destination address, if necessary */
4561 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4562 struct pf_state_key *nk = (*state)->key[pd->didx];
4564 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4565 nk->port[pd->sidx] != uh->uh_sport)
4566 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4567 &uh->uh_sum, &nk->addr[pd->sidx],
4568 nk->port[pd->sidx], 1, pd->af);
4570 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4571 nk->port[pd->didx] != uh->uh_dport)
4572 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4573 &uh->uh_sum, &nk->addr[pd->didx],
4574 nk->port[pd->didx], 1, pd->af);
4575 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4582 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4583 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4585 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4586 u_int16_t icmpid = 0, *icmpsum;
4589 struct pf_state_key_cmp key;
4591 bzero(&key, sizeof(key));
4592 switch (pd->proto) {
4595 icmptype = pd->hdr.icmp->icmp_type;
4596 icmpid = pd->hdr.icmp->icmp_id;
4597 icmpsum = &pd->hdr.icmp->icmp_cksum;
4599 if (icmptype == ICMP_UNREACH ||
4600 icmptype == ICMP_SOURCEQUENCH ||
4601 icmptype == ICMP_REDIRECT ||
4602 icmptype == ICMP_TIMXCEED ||
4603 icmptype == ICMP_PARAMPROB)
4608 case IPPROTO_ICMPV6:
4609 icmptype = pd->hdr.icmp6->icmp6_type;
4610 icmpid = pd->hdr.icmp6->icmp6_id;
4611 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4613 if (icmptype == ICMP6_DST_UNREACH ||
4614 icmptype == ICMP6_PACKET_TOO_BIG ||
4615 icmptype == ICMP6_TIME_EXCEEDED ||
4616 icmptype == ICMP6_PARAM_PROB)
4625 * ICMP query/reply message not related to a TCP/UDP packet.
4626 * Search for an ICMP state.
4629 key.proto = pd->proto;
4630 key.port[0] = key.port[1] = icmpid;
4631 if (direction == PF_IN) { /* wire side, straight */
4632 PF_ACPY(&key.addr[0], pd->src, key.af);
4633 PF_ACPY(&key.addr[1], pd->dst, key.af);
4634 } else { /* stack side, reverse */
4635 PF_ACPY(&key.addr[1], pd->src, key.af);
4636 PF_ACPY(&key.addr[0], pd->dst, key.af);
4639 STATE_LOOKUP(kif, &key, direction, *state, pd);
4641 (*state)->expire = time_uptime;
4642 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4644 /* translate source/destination address, if necessary */
4645 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4646 struct pf_state_key *nk = (*state)->key[pd->didx];
4651 if (PF_ANEQ(pd->src,
4652 &nk->addr[pd->sidx], AF_INET))
4653 pf_change_a(&saddr->v4.s_addr,
4655 nk->addr[pd->sidx].v4.s_addr, 0);
4657 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4659 pf_change_a(&daddr->v4.s_addr,
4661 nk->addr[pd->didx].v4.s_addr, 0);
4664 pd->hdr.icmp->icmp_id) {
4665 pd->hdr.icmp->icmp_cksum =
4667 pd->hdr.icmp->icmp_cksum, icmpid,
4668 nk->port[pd->sidx], 0);
4669 pd->hdr.icmp->icmp_id =
4673 m_copyback(m, off, ICMP_MINLEN,
4674 (caddr_t )pd->hdr.icmp);
4679 if (PF_ANEQ(pd->src,
4680 &nk->addr[pd->sidx], AF_INET6))
4682 &pd->hdr.icmp6->icmp6_cksum,
4683 &nk->addr[pd->sidx], 0);
4685 if (PF_ANEQ(pd->dst,
4686 &nk->addr[pd->didx], AF_INET6))
4688 &pd->hdr.icmp6->icmp6_cksum,
4689 &nk->addr[pd->didx], 0);
4691 m_copyback(m, off, sizeof(struct icmp6_hdr),
4692 (caddr_t )pd->hdr.icmp6);
4701 * ICMP error message in response to a TCP/UDP packet.
4702 * Extract the inner TCP/UDP header and search for that state.
4705 struct pf_pdesc pd2;
4706 bzero(&pd2, sizeof pd2);
4711 struct ip6_hdr h2_6;
4718 /* Payload packet is from the opposite direction. */
4719 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4720 pd2.didx = (direction == PF_IN) ? 0 : 1;
4724 /* offset of h2 in mbuf chain */
4725 ipoff2 = off + ICMP_MINLEN;
4727 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4728 NULL, reason, pd2.af)) {
4729 DPFPRINTF(PF_DEBUG_MISC,
4730 ("pf: ICMP error message too short "
4735 * ICMP error messages don't refer to non-first
4738 if (h2.ip_off & htons(IP_OFFMASK)) {
4739 REASON_SET(reason, PFRES_FRAG);
4743 /* offset of protocol header that follows h2 */
4744 off2 = ipoff2 + (h2.ip_hl << 2);
4746 pd2.proto = h2.ip_p;
4747 pd2.src = (struct pf_addr *)&h2.ip_src;
4748 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4749 pd2.ip_sum = &h2.ip_sum;
4754 ipoff2 = off + sizeof(struct icmp6_hdr);
4756 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4757 NULL, reason, pd2.af)) {
4758 DPFPRINTF(PF_DEBUG_MISC,
4759 ("pf: ICMP error message too short "
4763 pd2.proto = h2_6.ip6_nxt;
4764 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4765 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4767 off2 = ipoff2 + sizeof(h2_6);
4769 switch (pd2.proto) {
4770 case IPPROTO_FRAGMENT:
4772 * ICMPv6 error messages for
4773 * non-first fragments
4775 REASON_SET(reason, PFRES_FRAG);
4778 case IPPROTO_HOPOPTS:
4779 case IPPROTO_ROUTING:
4780 case IPPROTO_DSTOPTS: {
4781 /* get next header and header length */
4782 struct ip6_ext opt6;
4784 if (!pf_pull_hdr(m, off2, &opt6,
4785 sizeof(opt6), NULL, reason,
4787 DPFPRINTF(PF_DEBUG_MISC,
4788 ("pf: ICMPv6 short opt\n"));
4791 if (pd2.proto == IPPROTO_AH)
4792 off2 += (opt6.ip6e_len + 2) * 4;
4794 off2 += (opt6.ip6e_len + 1) * 8;
4795 pd2.proto = opt6.ip6e_nxt;
4796 /* goto the next header */
4803 } while (!terminal);
4808 switch (pd2.proto) {
4812 struct pf_state_peer *src, *dst;
4817 * Only the first 8 bytes of the TCP header can be
4818 * expected. Don't access any TCP header fields after
4819 * th_seq, an ackskew test is not possible.
4821 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4823 DPFPRINTF(PF_DEBUG_MISC,
4824 ("pf: ICMP error message too short "
4830 key.proto = IPPROTO_TCP;
4831 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4832 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4833 key.port[pd2.sidx] = th.th_sport;
4834 key.port[pd2.didx] = th.th_dport;
4836 STATE_LOOKUP(kif, &key, direction, *state, pd);
4838 if (direction == (*state)->direction) {
4839 src = &(*state)->dst;
4840 dst = &(*state)->src;
4842 src = &(*state)->src;
4843 dst = &(*state)->dst;
4846 if (src->wscale && dst->wscale)
4847 dws = dst->wscale & PF_WSCALE_MASK;
4851 /* Demodulate sequence number */
4852 seq = ntohl(th.th_seq) - src->seqdiff;
4854 pf_change_a(&th.th_seq, icmpsum,
4859 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4860 (!SEQ_GEQ(src->seqhi, seq) ||
4861 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4862 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4863 printf("pf: BAD ICMP %d:%d ",
4864 icmptype, pd->hdr.icmp->icmp_code);
4865 pf_print_host(pd->src, 0, pd->af);
4867 pf_print_host(pd->dst, 0, pd->af);
4869 pf_print_state(*state);
4870 printf(" seq=%u\n", seq);
4872 REASON_SET(reason, PFRES_BADSTATE);
4875 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4876 printf("pf: OK ICMP %d:%d ",
4877 icmptype, pd->hdr.icmp->icmp_code);
4878 pf_print_host(pd->src, 0, pd->af);
4880 pf_print_host(pd->dst, 0, pd->af);
4882 pf_print_state(*state);
4883 printf(" seq=%u\n", seq);
4887 /* translate source/destination address, if necessary */
4888 if ((*state)->key[PF_SK_WIRE] !=
4889 (*state)->key[PF_SK_STACK]) {
4890 struct pf_state_key *nk =
4891 (*state)->key[pd->didx];
4893 if (PF_ANEQ(pd2.src,
4894 &nk->addr[pd2.sidx], pd2.af) ||
4895 nk->port[pd2.sidx] != th.th_sport)
4896 pf_change_icmp(pd2.src, &th.th_sport,
4897 daddr, &nk->addr[pd2.sidx],
4898 nk->port[pd2.sidx], NULL,
4899 pd2.ip_sum, icmpsum,
4900 pd->ip_sum, 0, pd2.af);
4902 if (PF_ANEQ(pd2.dst,
4903 &nk->addr[pd2.didx], pd2.af) ||
4904 nk->port[pd2.didx] != th.th_dport)
4905 pf_change_icmp(pd2.dst, &th.th_dport,
4906 saddr, &nk->addr[pd2.didx],
4907 nk->port[pd2.didx], NULL,
4908 pd2.ip_sum, icmpsum,
4909 pd->ip_sum, 0, pd2.af);
4917 m_copyback(m, off, ICMP_MINLEN,
4918 (caddr_t )pd->hdr.icmp);
4919 m_copyback(m, ipoff2, sizeof(h2),
4926 sizeof(struct icmp6_hdr),
4927 (caddr_t )pd->hdr.icmp6);
4928 m_copyback(m, ipoff2, sizeof(h2_6),
4933 m_copyback(m, off2, 8, (caddr_t)&th);
4942 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4943 NULL, reason, pd2.af)) {
4944 DPFPRINTF(PF_DEBUG_MISC,
4945 ("pf: ICMP error message too short "
4951 key.proto = IPPROTO_UDP;
4952 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4953 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4954 key.port[pd2.sidx] = uh.uh_sport;
4955 key.port[pd2.didx] = uh.uh_dport;
4957 STATE_LOOKUP(kif, &key, direction, *state, pd);
4959 /* translate source/destination address, if necessary */
4960 if ((*state)->key[PF_SK_WIRE] !=
4961 (*state)->key[PF_SK_STACK]) {
4962 struct pf_state_key *nk =
4963 (*state)->key[pd->didx];
4965 if (PF_ANEQ(pd2.src,
4966 &nk->addr[pd2.sidx], pd2.af) ||
4967 nk->port[pd2.sidx] != uh.uh_sport)
4968 pf_change_icmp(pd2.src, &uh.uh_sport,
4969 daddr, &nk->addr[pd2.sidx],
4970 nk->port[pd2.sidx], &uh.uh_sum,
4971 pd2.ip_sum, icmpsum,
4972 pd->ip_sum, 1, pd2.af);
4974 if (PF_ANEQ(pd2.dst,
4975 &nk->addr[pd2.didx], pd2.af) ||
4976 nk->port[pd2.didx] != uh.uh_dport)
4977 pf_change_icmp(pd2.dst, &uh.uh_dport,
4978 saddr, &nk->addr[pd2.didx],
4979 nk->port[pd2.didx], &uh.uh_sum,
4980 pd2.ip_sum, icmpsum,
4981 pd->ip_sum, 1, pd2.af);
4986 m_copyback(m, off, ICMP_MINLEN,
4987 (caddr_t )pd->hdr.icmp);
4988 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4994 sizeof(struct icmp6_hdr),
4995 (caddr_t )pd->hdr.icmp6);
4996 m_copyback(m, ipoff2, sizeof(h2_6),
5001 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5007 case IPPROTO_ICMP: {
5010 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5011 NULL, reason, pd2.af)) {
5012 DPFPRINTF(PF_DEBUG_MISC,
5013 ("pf: ICMP error message too short i"
5019 key.proto = IPPROTO_ICMP;
5020 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5021 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5022 key.port[0] = key.port[1] = iih.icmp_id;
5024 STATE_LOOKUP(kif, &key, direction, *state, pd);
5026 /* translate source/destination address, if necessary */
5027 if ((*state)->key[PF_SK_WIRE] !=
5028 (*state)->key[PF_SK_STACK]) {
5029 struct pf_state_key *nk =
5030 (*state)->key[pd->didx];
5032 if (PF_ANEQ(pd2.src,
5033 &nk->addr[pd2.sidx], pd2.af) ||
5034 nk->port[pd2.sidx] != iih.icmp_id)
5035 pf_change_icmp(pd2.src, &iih.icmp_id,
5036 daddr, &nk->addr[pd2.sidx],
5037 nk->port[pd2.sidx], NULL,
5038 pd2.ip_sum, icmpsum,
5039 pd->ip_sum, 0, AF_INET);
5041 if (PF_ANEQ(pd2.dst,
5042 &nk->addr[pd2.didx], pd2.af) ||
5043 nk->port[pd2.didx] != iih.icmp_id)
5044 pf_change_icmp(pd2.dst, &iih.icmp_id,
5045 saddr, &nk->addr[pd2.didx],
5046 nk->port[pd2.didx], NULL,
5047 pd2.ip_sum, icmpsum,
5048 pd->ip_sum, 0, AF_INET);
5050 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5051 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5052 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5059 case IPPROTO_ICMPV6: {
5060 struct icmp6_hdr iih;
5062 if (!pf_pull_hdr(m, off2, &iih,
5063 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5064 DPFPRINTF(PF_DEBUG_MISC,
5065 ("pf: ICMP error message too short "
5071 key.proto = IPPROTO_ICMPV6;
5072 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5073 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5074 key.port[0] = key.port[1] = iih.icmp6_id;
5076 STATE_LOOKUP(kif, &key, direction, *state, pd);
5078 /* translate source/destination address, if necessary */
5079 if ((*state)->key[PF_SK_WIRE] !=
5080 (*state)->key[PF_SK_STACK]) {
5081 struct pf_state_key *nk =
5082 (*state)->key[pd->didx];
5084 if (PF_ANEQ(pd2.src,
5085 &nk->addr[pd2.sidx], pd2.af) ||
5086 nk->port[pd2.sidx] != iih.icmp6_id)
5087 pf_change_icmp(pd2.src, &iih.icmp6_id,
5088 daddr, &nk->addr[pd2.sidx],
5089 nk->port[pd2.sidx], NULL,
5090 pd2.ip_sum, icmpsum,
5091 pd->ip_sum, 0, AF_INET6);
5093 if (PF_ANEQ(pd2.dst,
5094 &nk->addr[pd2.didx], pd2.af) ||
5095 nk->port[pd2.didx] != iih.icmp6_id)
5096 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5097 saddr, &nk->addr[pd2.didx],
5098 nk->port[pd2.didx], NULL,
5099 pd2.ip_sum, icmpsum,
5100 pd->ip_sum, 0, AF_INET6);
5102 m_copyback(m, off, sizeof(struct icmp6_hdr),
5103 (caddr_t)pd->hdr.icmp6);
5104 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5105 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5114 key.proto = pd2.proto;
5115 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5116 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5117 key.port[0] = key.port[1] = 0;
5119 STATE_LOOKUP(kif, &key, direction, *state, pd);
5121 /* translate source/destination address, if necessary */
5122 if ((*state)->key[PF_SK_WIRE] !=
5123 (*state)->key[PF_SK_STACK]) {
5124 struct pf_state_key *nk =
5125 (*state)->key[pd->didx];
5127 if (PF_ANEQ(pd2.src,
5128 &nk->addr[pd2.sidx], pd2.af))
5129 pf_change_icmp(pd2.src, NULL, daddr,
5130 &nk->addr[pd2.sidx], 0, NULL,
5131 pd2.ip_sum, icmpsum,
5132 pd->ip_sum, 0, pd2.af);
5134 if (PF_ANEQ(pd2.dst,
5135 &nk->addr[pd2.didx], pd2.af))
5136 pf_change_icmp(pd2.dst, NULL, saddr,
5137 &nk->addr[pd2.didx], 0, NULL,
5138 pd2.ip_sum, icmpsum,
5139 pd->ip_sum, 0, pd2.af);
5144 m_copyback(m, off, ICMP_MINLEN,
5145 (caddr_t)pd->hdr.icmp);
5146 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5152 sizeof(struct icmp6_hdr),
5153 (caddr_t )pd->hdr.icmp6);
5154 m_copyback(m, ipoff2, sizeof(h2_6),
5168 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5169 struct mbuf *m, struct pf_pdesc *pd)
5171 struct pf_state_peer *src, *dst;
5172 struct pf_state_key_cmp key;
5174 bzero(&key, sizeof(key));
5176 key.proto = pd->proto;
5177 if (direction == PF_IN) {
5178 PF_ACPY(&key.addr[0], pd->src, key.af);
5179 PF_ACPY(&key.addr[1], pd->dst, key.af);
5180 key.port[0] = key.port[1] = 0;
5182 PF_ACPY(&key.addr[1], pd->src, key.af);
5183 PF_ACPY(&key.addr[0], pd->dst, key.af);
5184 key.port[1] = key.port[0] = 0;
5187 STATE_LOOKUP(kif, &key, direction, *state, pd);
5189 if (direction == (*state)->direction) {
5190 src = &(*state)->src;
5191 dst = &(*state)->dst;
5193 src = &(*state)->dst;
5194 dst = &(*state)->src;
5198 if (src->state < PFOTHERS_SINGLE)
5199 src->state = PFOTHERS_SINGLE;
5200 if (dst->state == PFOTHERS_SINGLE)
5201 dst->state = PFOTHERS_MULTIPLE;
5203 /* update expire time */
5204 (*state)->expire = time_uptime;
5205 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5206 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5208 (*state)->timeout = PFTM_OTHER_SINGLE;
5210 /* translate source/destination address, if necessary */
5211 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5212 struct pf_state_key *nk = (*state)->key[pd->didx];
5214 KASSERT(nk, ("%s: nk is null", __func__));
5215 KASSERT(pd, ("%s: pd is null", __func__));
5216 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5217 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5221 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5222 pf_change_a(&pd->src->v4.s_addr,
5224 nk->addr[pd->sidx].v4.s_addr,
5228 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5229 pf_change_a(&pd->dst->v4.s_addr,
5231 nk->addr[pd->didx].v4.s_addr,
5238 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5239 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5241 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5242 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5250 * ipoff and off are measured from the start of the mbuf chain.
5251 * h must be at "ipoff" on the mbuf chain.
5254 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5255 u_short *actionp, u_short *reasonp, sa_family_t af)
5260 struct ip *h = mtod(m, struct ip *);
5261 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5265 ACTION_SET(actionp, PF_PASS);
5267 ACTION_SET(actionp, PF_DROP);
5268 REASON_SET(reasonp, PFRES_FRAG);
5272 if (m->m_pkthdr.len < off + len ||
5273 ntohs(h->ip_len) < off + len) {
5274 ACTION_SET(actionp, PF_DROP);
5275 REASON_SET(reasonp, PFRES_SHORT);
5283 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5285 if (m->m_pkthdr.len < off + len ||
5286 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5287 (unsigned)(off + len)) {
5288 ACTION_SET(actionp, PF_DROP);
5289 REASON_SET(reasonp, PFRES_SHORT);
5296 m_copydata(m, off, len, p);
5302 pf_routable_oldmpath(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5305 struct radix_node_head *rnh;
5306 struct sockaddr_in *dst;
5310 struct sockaddr_in6 *dst6;
5311 struct route_in6 ro;
5315 struct radix_node *rn;
5320 /* XXX: stick to table 0 for now */
5321 rnh = rt_tables_get_rnh(0, af);
5322 if (rnh != NULL && rn_mpath_capable(rnh))
5324 bzero(&ro, sizeof(ro));
5327 dst = satosin(&ro.ro_dst);
5328 dst->sin_family = AF_INET;
5329 dst->sin_len = sizeof(*dst);
5330 dst->sin_addr = addr->v4;
5335 * Skip check for addresses with embedded interface scope,
5336 * as they would always match anyway.
5338 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5340 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5341 dst6->sin6_family = AF_INET6;
5342 dst6->sin6_len = sizeof(*dst6);
5343 dst6->sin6_addr = addr->v6;
5350 /* Skip checks for ipsec interfaces */
5351 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5357 in6_rtalloc_ign(&ro, 0, rtableid);
5362 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5367 if (ro.ro_rt != NULL) {
5368 /* No interface given, this is a no-route check */
5372 if (kif->pfik_ifp == NULL) {
5377 /* Perform uRPF check if passed input interface */
5379 rn = (struct radix_node *)ro.ro_rt;
5381 rt = (struct rtentry *)rn;
5384 if (kif->pfik_ifp == ifp)
5386 rn = rn_mpath_next(rn);
5387 } while (check_mpath == 1 && rn != NULL && ret == 0);
5391 if (ro.ro_rt != NULL)
5398 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5402 struct nhop4_basic nh4;
5405 struct nhop6_basic nh6;
5409 struct radix_node_head *rnh;
5411 /* XXX: stick to table 0 for now */
5412 rnh = rt_tables_get_rnh(0, af);
5413 if (rnh != NULL && rn_mpath_capable(rnh))
5414 return (pf_routable_oldmpath(addr, af, kif, rtableid));
5417 * Skip check for addresses with embedded interface scope,
5418 * as they would always match anyway.
5420 if (af == AF_INET6 && IN6_IS_SCOPE_EMBED(&addr->v6))
5423 if (af != AF_INET && af != AF_INET6)
5426 /* Skip checks for ipsec interfaces */
5427 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5435 if (fib6_lookup_nh_basic(rtableid, &addr->v6, 0, 0, 0, &nh6)!=0)
5442 if (fib4_lookup_nh_basic(rtableid, addr->v4, 0, 0, &nh4) != 0)
5449 /* No interface given, this is a no-route check */
5453 if (kif->pfik_ifp == NULL)
5456 /* Perform uRPF check if passed input interface */
5457 if (kif->pfik_ifp == ifp)
5464 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5465 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5467 struct mbuf *m0, *m1;
5468 struct sockaddr_in dst;
5470 struct ifnet *ifp = NULL;
5471 struct pf_addr naddr;
5472 struct pf_src_node *sn = NULL;
5474 uint16_t ip_len, ip_off;
5476 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5477 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5480 if ((pd->pf_mtag == NULL &&
5481 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5482 pd->pf_mtag->routed++ > 3) {
5488 if (r->rt == PF_DUPTO) {
5489 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5495 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5503 ip = mtod(m0, struct ip *);
5505 bzero(&dst, sizeof(dst));
5506 dst.sin_family = AF_INET;
5507 dst.sin_len = sizeof(dst);
5508 dst.sin_addr = ip->ip_dst;
5510 if (TAILQ_EMPTY(&r->rpool.list)) {
5511 DPFPRINTF(PF_DEBUG_URGENT,
5512 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5516 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5518 if (!PF_AZERO(&naddr, AF_INET))
5519 dst.sin_addr.s_addr = naddr.v4.s_addr;
5520 ifp = r->rpool.cur->kif ?
5521 r->rpool.cur->kif->pfik_ifp : NULL;
5523 if (!PF_AZERO(&s->rt_addr, AF_INET))
5524 dst.sin_addr.s_addr =
5525 s->rt_addr.v4.s_addr;
5526 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5533 if (pf_test(PF_OUT, 0, ifp, &m0, inp) != PF_PASS)
5535 else if (m0 == NULL)
5537 if (m0->m_len < sizeof(struct ip)) {
5538 DPFPRINTF(PF_DEBUG_URGENT,
5539 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5542 ip = mtod(m0, struct ip *);
5545 if (ifp->if_flags & IFF_LOOPBACK)
5546 m0->m_flags |= M_SKIP_FIREWALL;
5548 ip_len = ntohs(ip->ip_len);
5549 ip_off = ntohs(ip->ip_off);
5551 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5552 m0->m_pkthdr.csum_flags |= CSUM_IP;
5553 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5554 in_delayed_cksum(m0);
5555 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5558 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5559 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5560 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5565 * If small enough for interface, or the interface will take
5566 * care of the fragmentation for us, we can just send directly.
5568 if (ip_len <= ifp->if_mtu ||
5569 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
5571 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5572 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5573 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5575 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5576 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5580 /* Balk when DF bit is set or the interface didn't support TSO. */
5581 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5583 KMOD_IPSTAT_INC(ips_cantfrag);
5584 if (r->rt != PF_DUPTO) {
5585 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5592 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5596 for (; m0; m0 = m1) {
5598 m0->m_nextpkt = NULL;
5600 m_clrprotoflags(m0);
5601 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5607 KMOD_IPSTAT_INC(ips_fragmented);
5610 if (r->rt != PF_DUPTO)
5625 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5626 struct pf_state *s, struct pf_pdesc *pd, struct inpcb *inp)
5629 struct sockaddr_in6 dst;
5630 struct ip6_hdr *ip6;
5631 struct ifnet *ifp = NULL;
5632 struct pf_addr naddr;
5633 struct pf_src_node *sn = NULL;
5635 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5636 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5639 if ((pd->pf_mtag == NULL &&
5640 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5641 pd->pf_mtag->routed++ > 3) {
5647 if (r->rt == PF_DUPTO) {
5648 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5654 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5662 ip6 = mtod(m0, struct ip6_hdr *);
5664 bzero(&dst, sizeof(dst));
5665 dst.sin6_family = AF_INET6;
5666 dst.sin6_len = sizeof(dst);
5667 dst.sin6_addr = ip6->ip6_dst;
5669 if (TAILQ_EMPTY(&r->rpool.list)) {
5670 DPFPRINTF(PF_DEBUG_URGENT,
5671 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5675 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5677 if (!PF_AZERO(&naddr, AF_INET6))
5678 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5680 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5682 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5683 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5684 &s->rt_addr, AF_INET6);
5685 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5695 if (pf_test6(PF_OUT, PFIL_FWD, ifp, &m0, inp) != PF_PASS)
5697 else if (m0 == NULL)
5699 if (m0->m_len < sizeof(struct ip6_hdr)) {
5700 DPFPRINTF(PF_DEBUG_URGENT,
5701 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5705 ip6 = mtod(m0, struct ip6_hdr *);
5708 if (ifp->if_flags & IFF_LOOPBACK)
5709 m0->m_flags |= M_SKIP_FIREWALL;
5711 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5712 ~ifp->if_hwassist) {
5713 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5714 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5715 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5719 * If the packet is too large for the outgoing interface,
5720 * send back an icmp6 error.
5722 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5723 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5724 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5725 nd6_output_ifp(ifp, ifp, m0, &dst, NULL);
5727 in6_ifstat_inc(ifp, ifs6_in_toobig);
5728 if (r->rt != PF_DUPTO)
5729 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5735 if (r->rt != PF_DUPTO)
5749 * FreeBSD supports cksum offloads for the following drivers.
5750 * em(4), fxp(4), lge(4), ndis(4), nge(4), re(4), ti(4), txp(4), xl(4)
5752 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5753 * network driver performed cksum including pseudo header, need to verify
5756 * network driver performed cksum, needs to additional pseudo header
5757 * cksum computation with partial csum_data(i.e. lack of H/W support for
5758 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5760 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5761 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5763 * Also, set csum_data to 0xffff to force cksum validation.
5766 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5772 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5774 if (m->m_pkthdr.len < off + len)
5779 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5780 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5781 sum = m->m_pkthdr.csum_data;
5783 ip = mtod(m, struct ip *);
5784 sum = in_pseudo(ip->ip_src.s_addr,
5785 ip->ip_dst.s_addr, htonl((u_short)len +
5786 m->m_pkthdr.csum_data + IPPROTO_TCP));
5793 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5794 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5795 sum = m->m_pkthdr.csum_data;
5797 ip = mtod(m, struct ip *);
5798 sum = in_pseudo(ip->ip_src.s_addr,
5799 ip->ip_dst.s_addr, htonl((u_short)len +
5800 m->m_pkthdr.csum_data + IPPROTO_UDP));
5808 case IPPROTO_ICMPV6:
5818 if (p == IPPROTO_ICMP) {
5823 sum = in_cksum(m, len);
5827 if (m->m_len < sizeof(struct ip))
5829 sum = in4_cksum(m, p, off, len);
5834 if (m->m_len < sizeof(struct ip6_hdr))
5836 sum = in6_cksum(m, p, off, len);
5847 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5852 KMOD_UDPSTAT_INC(udps_badsum);
5858 KMOD_ICMPSTAT_INC(icps_checksum);
5863 case IPPROTO_ICMPV6:
5865 KMOD_ICMP6STAT_INC(icp6s_checksum);
5872 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5873 m->m_pkthdr.csum_flags |=
5874 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5875 m->m_pkthdr.csum_data = 0xffff;
5884 pf_test(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5886 struct pfi_kif *kif;
5887 u_short action, reason = 0, log = 0;
5888 struct mbuf *m = *m0;
5889 struct ip *h = NULL;
5890 struct m_tag *ipfwtag;
5891 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5892 struct pf_state *s = NULL;
5893 struct pf_ruleset *ruleset = NULL;
5895 int off, dirndx, pqid = 0;
5897 PF_RULES_RLOCK_TRACKER;
5901 if (!V_pf_status.running)
5904 memset(&pd, 0, sizeof(pd));
5906 kif = (struct pfi_kif *)ifp->if_pf_kif;
5909 DPFPRINTF(PF_DEBUG_URGENT,
5910 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5913 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5916 if (m->m_flags & M_SKIP_FIREWALL)
5919 pd.pf_mtag = pf_find_mtag(m);
5923 if (ip_divert_ptr != NULL &&
5924 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5925 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5926 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5927 if (pd.pf_mtag == NULL &&
5928 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5932 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5933 m_tag_delete(m, ipfwtag);
5935 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5936 m->m_flags |= M_FASTFWD_OURS;
5937 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5939 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5940 /* We do IP header normalization and packet reassembly here */
5944 m = *m0; /* pf_normalize messes with m0 */
5945 h = mtod(m, struct ip *);
5947 off = h->ip_hl << 2;
5948 if (off < (int)sizeof(struct ip)) {
5950 REASON_SET(&reason, PFRES_SHORT);
5955 pd.src = (struct pf_addr *)&h->ip_src;
5956 pd.dst = (struct pf_addr *)&h->ip_dst;
5957 pd.sport = pd.dport = NULL;
5958 pd.ip_sum = &h->ip_sum;
5959 pd.proto_sum = NULL;
5962 pd.sidx = (dir == PF_IN) ? 0 : 1;
5963 pd.didx = (dir == PF_IN) ? 1 : 0;
5965 pd.tos = h->ip_tos & ~IPTOS_ECN_MASK;
5966 pd.tot_len = ntohs(h->ip_len);
5968 /* handle fragments that didn't get reassembled by normalization */
5969 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5970 action = pf_test_fragment(&r, dir, kif, m, h,
5981 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5982 &action, &reason, AF_INET)) {
5983 log = action != PF_PASS;
5986 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5987 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5989 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5990 if (action == PF_DROP)
5992 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5994 if (action == PF_PASS) {
5995 if (pfsync_update_state_ptr != NULL)
5996 pfsync_update_state_ptr(s);
6000 } else if (s == NULL)
6001 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6010 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6011 &action, &reason, AF_INET)) {
6012 log = action != PF_PASS;
6015 if (uh.uh_dport == 0 ||
6016 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6017 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6019 REASON_SET(&reason, PFRES_SHORT);
6022 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6023 if (action == PF_PASS) {
6024 if (pfsync_update_state_ptr != NULL)
6025 pfsync_update_state_ptr(s);
6029 } else if (s == NULL)
6030 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6035 case IPPROTO_ICMP: {
6039 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6040 &action, &reason, AF_INET)) {
6041 log = action != PF_PASS;
6044 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6046 if (action == PF_PASS) {
6047 if (pfsync_update_state_ptr != NULL)
6048 pfsync_update_state_ptr(s);
6052 } else if (s == NULL)
6053 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6059 case IPPROTO_ICMPV6: {
6061 DPFPRINTF(PF_DEBUG_MISC,
6062 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6068 action = pf_test_state_other(&s, dir, kif, m, &pd);
6069 if (action == PF_PASS) {
6070 if (pfsync_update_state_ptr != NULL)
6071 pfsync_update_state_ptr(s);
6075 } else if (s == NULL)
6076 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6083 if (action == PF_PASS && h->ip_hl > 5 &&
6084 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6086 REASON_SET(&reason, PFRES_IPOPTIONS);
6088 DPFPRINTF(PF_DEBUG_MISC,
6089 ("pf: dropping packet with ip options\n"));
6092 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6094 REASON_SET(&reason, PFRES_MEMORY);
6096 if (r->rtableid >= 0)
6097 M_SETFIB(m, r->rtableid);
6099 if (r->scrub_flags & PFSTATE_SETPRIO) {
6100 if (pd.tos & IPTOS_LOWDELAY)
6102 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6104 REASON_SET(&reason, PFRES_MEMORY);
6106 DPFPRINTF(PF_DEBUG_MISC,
6107 ("pf: failed to allocate 802.1q mtag\n"));
6112 if (action == PF_PASS && r->qid) {
6113 if (pd.pf_mtag == NULL &&
6114 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6116 REASON_SET(&reason, PFRES_MEMORY);
6119 pd.pf_mtag->qid_hash = pf_state_hash(s);
6120 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6121 pd.pf_mtag->qid = r->pqid;
6123 pd.pf_mtag->qid = r->qid;
6124 /* Add hints for ecn. */
6125 pd.pf_mtag->hdr = h;
6132 * connections redirected to loopback should not match sockets
6133 * bound specifically to loopback due to security implications,
6134 * see tcp_input() and in_pcblookup_listen().
6136 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6137 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6138 (s->nat_rule.ptr->action == PF_RDR ||
6139 s->nat_rule.ptr->action == PF_BINAT) &&
6140 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6141 m->m_flags |= M_SKIP_FIREWALL;
6143 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6144 !PACKET_LOOPED(&pd)) {
6146 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6147 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6148 if (ipfwtag != NULL) {
6149 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6150 ntohs(r->divert.port);
6151 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6156 m_tag_prepend(m, ipfwtag);
6157 if (m->m_flags & M_FASTFWD_OURS) {
6158 if (pd.pf_mtag == NULL &&
6159 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6161 REASON_SET(&reason, PFRES_MEMORY);
6163 DPFPRINTF(PF_DEBUG_MISC,
6164 ("pf: failed to allocate tag\n"));
6166 pd.pf_mtag->flags |=
6167 PF_FASTFWD_OURS_PRESENT;
6168 m->m_flags &= ~M_FASTFWD_OURS;
6171 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6176 /* XXX: ipfw has the same behaviour! */
6178 REASON_SET(&reason, PFRES_MEMORY);
6180 DPFPRINTF(PF_DEBUG_MISC,
6181 ("pf: failed to allocate divert tag\n"));
6188 if (s != NULL && s->nat_rule.ptr != NULL &&
6189 s->nat_rule.ptr->log & PF_LOG_ALL)
6190 lr = s->nat_rule.ptr;
6193 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6197 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6198 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6200 if (action == PF_PASS || r->action == PF_DROP) {
6201 dirndx = (dir == PF_OUT);
6202 r->packets[dirndx]++;
6203 r->bytes[dirndx] += pd.tot_len;
6205 a->packets[dirndx]++;
6206 a->bytes[dirndx] += pd.tot_len;
6209 if (s->nat_rule.ptr != NULL) {
6210 s->nat_rule.ptr->packets[dirndx]++;
6211 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6213 if (s->src_node != NULL) {
6214 s->src_node->packets[dirndx]++;
6215 s->src_node->bytes[dirndx] += pd.tot_len;
6217 if (s->nat_src_node != NULL) {
6218 s->nat_src_node->packets[dirndx]++;
6219 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6221 dirndx = (dir == s->direction) ? 0 : 1;
6222 s->packets[dirndx]++;
6223 s->bytes[dirndx] += pd.tot_len;
6226 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6227 if (nr != NULL && r == &V_pf_default_rule)
6229 if (tr->src.addr.type == PF_ADDR_TABLE)
6230 pfr_update_stats(tr->src.addr.p.tbl,
6231 (s == NULL) ? pd.src :
6232 &s->key[(s->direction == PF_IN)]->
6233 addr[(s->direction == PF_OUT)],
6234 pd.af, pd.tot_len, dir == PF_OUT,
6235 r->action == PF_PASS, tr->src.neg);
6236 if (tr->dst.addr.type == PF_ADDR_TABLE)
6237 pfr_update_stats(tr->dst.addr.p.tbl,
6238 (s == NULL) ? pd.dst :
6239 &s->key[(s->direction == PF_IN)]->
6240 addr[(s->direction == PF_IN)],
6241 pd.af, pd.tot_len, dir == PF_OUT,
6242 r->action == PF_PASS, tr->dst.neg);
6246 case PF_SYNPROXY_DROP:
6257 /* pf_route() returns unlocked. */
6259 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6273 pf_test6(int dir, int pflags, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6275 struct pfi_kif *kif;
6276 u_short action, reason = 0, log = 0;
6277 struct mbuf *m = *m0, *n = NULL;
6279 struct ip6_hdr *h = NULL;
6280 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6281 struct pf_state *s = NULL;
6282 struct pf_ruleset *ruleset = NULL;
6284 int off, terminal = 0, dirndx, rh_cnt = 0, pqid = 0;
6286 PF_RULES_RLOCK_TRACKER;
6289 if (!V_pf_status.running)
6292 memset(&pd, 0, sizeof(pd));
6293 pd.pf_mtag = pf_find_mtag(m);
6295 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6298 kif = (struct pfi_kif *)ifp->if_pf_kif;
6300 DPFPRINTF(PF_DEBUG_URGENT,
6301 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6304 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6307 if (m->m_flags & M_SKIP_FIREWALL)
6312 /* We do IP header normalization and packet reassembly here */
6313 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6317 m = *m0; /* pf_normalize messes with m0 */
6318 h = mtod(m, struct ip6_hdr *);
6322 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6323 * will do something bad, so drop the packet for now.
6325 if (htons(h->ip6_plen) == 0) {
6327 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6332 pd.src = (struct pf_addr *)&h->ip6_src;
6333 pd.dst = (struct pf_addr *)&h->ip6_dst;
6334 pd.sport = pd.dport = NULL;
6336 pd.proto_sum = NULL;
6338 pd.sidx = (dir == PF_IN) ? 0 : 1;
6339 pd.didx = (dir == PF_IN) ? 1 : 0;
6342 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6344 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6345 pd.proto = h->ip6_nxt;
6348 case IPPROTO_FRAGMENT:
6349 action = pf_test_fragment(&r, dir, kif, m, h,
6351 if (action == PF_DROP)
6352 REASON_SET(&reason, PFRES_FRAG);
6354 case IPPROTO_ROUTING: {
6355 struct ip6_rthdr rthdr;
6358 DPFPRINTF(PF_DEBUG_MISC,
6359 ("pf: IPv6 more than one rthdr\n"));
6361 REASON_SET(&reason, PFRES_IPOPTIONS);
6365 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6367 DPFPRINTF(PF_DEBUG_MISC,
6368 ("pf: IPv6 short rthdr\n"));
6370 REASON_SET(&reason, PFRES_SHORT);
6374 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6375 DPFPRINTF(PF_DEBUG_MISC,
6376 ("pf: IPv6 rthdr0\n"));
6378 REASON_SET(&reason, PFRES_IPOPTIONS);
6385 case IPPROTO_HOPOPTS:
6386 case IPPROTO_DSTOPTS: {
6387 /* get next header and header length */
6388 struct ip6_ext opt6;
6390 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6391 NULL, &reason, pd.af)) {
6392 DPFPRINTF(PF_DEBUG_MISC,
6393 ("pf: IPv6 short opt\n"));
6398 if (pd.proto == IPPROTO_AH)
6399 off += (opt6.ip6e_len + 2) * 4;
6401 off += (opt6.ip6e_len + 1) * 8;
6402 pd.proto = opt6.ip6e_nxt;
6403 /* goto the next header */
6410 } while (!terminal);
6412 /* if there's no routing header, use unmodified mbuf for checksumming */
6422 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6423 &action, &reason, AF_INET6)) {
6424 log = action != PF_PASS;
6427 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6428 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6429 if (action == PF_DROP)
6431 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6433 if (action == PF_PASS) {
6434 if (pfsync_update_state_ptr != NULL)
6435 pfsync_update_state_ptr(s);
6439 } else if (s == NULL)
6440 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6449 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6450 &action, &reason, AF_INET6)) {
6451 log = action != PF_PASS;
6454 if (uh.uh_dport == 0 ||
6455 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6456 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6458 REASON_SET(&reason, PFRES_SHORT);
6461 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6462 if (action == PF_PASS) {
6463 if (pfsync_update_state_ptr != NULL)
6464 pfsync_update_state_ptr(s);
6468 } else if (s == NULL)
6469 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6474 case IPPROTO_ICMP: {
6476 DPFPRINTF(PF_DEBUG_MISC,
6477 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6481 case IPPROTO_ICMPV6: {
6482 struct icmp6_hdr ih;
6485 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6486 &action, &reason, AF_INET6)) {
6487 log = action != PF_PASS;
6490 action = pf_test_state_icmp(&s, dir, kif,
6491 m, off, h, &pd, &reason);
6492 if (action == PF_PASS) {
6493 if (pfsync_update_state_ptr != NULL)
6494 pfsync_update_state_ptr(s);
6498 } else if (s == NULL)
6499 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6505 action = pf_test_state_other(&s, dir, kif, m, &pd);
6506 if (action == PF_PASS) {
6507 if (pfsync_update_state_ptr != NULL)
6508 pfsync_update_state_ptr(s);
6512 } else if (s == NULL)
6513 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6525 /* handle dangerous IPv6 extension headers. */
6526 if (action == PF_PASS && rh_cnt &&
6527 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6529 REASON_SET(&reason, PFRES_IPOPTIONS);
6531 DPFPRINTF(PF_DEBUG_MISC,
6532 ("pf: dropping packet with dangerous v6 headers\n"));
6535 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6537 REASON_SET(&reason, PFRES_MEMORY);
6539 if (r->rtableid >= 0)
6540 M_SETFIB(m, r->rtableid);
6542 if (r->scrub_flags & PFSTATE_SETPRIO) {
6543 if (pd.tos & IPTOS_LOWDELAY)
6545 if (pf_ieee8021q_setpcp(m, r->set_prio[pqid])) {
6547 REASON_SET(&reason, PFRES_MEMORY);
6549 DPFPRINTF(PF_DEBUG_MISC,
6550 ("pf: failed to allocate 802.1q mtag\n"));
6555 if (action == PF_PASS && r->qid) {
6556 if (pd.pf_mtag == NULL &&
6557 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6559 REASON_SET(&reason, PFRES_MEMORY);
6562 pd.pf_mtag->qid_hash = pf_state_hash(s);
6563 if (pd.tos & IPTOS_LOWDELAY)
6564 pd.pf_mtag->qid = r->pqid;
6566 pd.pf_mtag->qid = r->qid;
6567 /* Add hints for ecn. */
6568 pd.pf_mtag->hdr = h;
6573 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6574 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6575 (s->nat_rule.ptr->action == PF_RDR ||
6576 s->nat_rule.ptr->action == PF_BINAT) &&
6577 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6578 m->m_flags |= M_SKIP_FIREWALL;
6580 /* XXX: Anybody working on it?! */
6582 printf("pf: divert(9) is not supported for IPv6\n");
6587 if (s != NULL && s->nat_rule.ptr != NULL &&
6588 s->nat_rule.ptr->log & PF_LOG_ALL)
6589 lr = s->nat_rule.ptr;
6592 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6596 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6597 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6599 if (action == PF_PASS || r->action == PF_DROP) {
6600 dirndx = (dir == PF_OUT);
6601 r->packets[dirndx]++;
6602 r->bytes[dirndx] += pd.tot_len;
6604 a->packets[dirndx]++;
6605 a->bytes[dirndx] += pd.tot_len;
6608 if (s->nat_rule.ptr != NULL) {
6609 s->nat_rule.ptr->packets[dirndx]++;
6610 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6612 if (s->src_node != NULL) {
6613 s->src_node->packets[dirndx]++;
6614 s->src_node->bytes[dirndx] += pd.tot_len;
6616 if (s->nat_src_node != NULL) {
6617 s->nat_src_node->packets[dirndx]++;
6618 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6620 dirndx = (dir == s->direction) ? 0 : 1;
6621 s->packets[dirndx]++;
6622 s->bytes[dirndx] += pd.tot_len;
6625 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6626 if (nr != NULL && r == &V_pf_default_rule)
6628 if (tr->src.addr.type == PF_ADDR_TABLE)
6629 pfr_update_stats(tr->src.addr.p.tbl,
6630 (s == NULL) ? pd.src :
6631 &s->key[(s->direction == PF_IN)]->addr[0],
6632 pd.af, pd.tot_len, dir == PF_OUT,
6633 r->action == PF_PASS, tr->src.neg);
6634 if (tr->dst.addr.type == PF_ADDR_TABLE)
6635 pfr_update_stats(tr->dst.addr.p.tbl,
6636 (s == NULL) ? pd.dst :
6637 &s->key[(s->direction == PF_IN)]->addr[1],
6638 pd.af, pd.tot_len, dir == PF_OUT,
6639 r->action == PF_PASS, tr->dst.neg);
6643 case PF_SYNPROXY_DROP:
6654 /* pf_route6() returns unlocked. */
6656 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd, inp);
6665 /* If reassembled packet passed, create new fragments. */
6666 if (action == PF_PASS && *m0 && (pflags & PFIL_FWD) &&
6667 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6668 action = pf_refragment6(ifp, m0, mtag);