2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
35 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 #include "opt_inet6.h"
46 #include <sys/param.h>
48 #include <sys/endian.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/limits.h>
56 #include <sys/random.h>
57 #include <sys/refcount.h>
58 #include <sys/socket.h>
59 #include <sys/sysctl.h>
60 #include <sys/taskqueue.h>
61 #include <sys/ucred.h>
64 #include <net/if_types.h>
65 #include <net/route.h>
66 #include <net/radix_mpath.h>
69 #include <net/pfvar.h>
70 #include <net/if_pflog.h>
71 #include <net/if_pfsync.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/in_var.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/icmp_var.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/tcp.h>
81 #include <netinet/tcp_fsm.h>
82 #include <netinet/tcp_seq.h>
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #include <netinet/udp.h>
86 #include <netinet/udp_var.h>
88 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
91 #include <netinet/ip6.h>
92 #include <netinet/icmp6.h>
93 #include <netinet6/nd6.h>
94 #include <netinet6/ip6_var.h>
95 #include <netinet6/in6_pcb.h>
98 #include <machine/in_cksum.h>
99 #include <security/mac/mac_framework.h>
101 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
108 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
109 VNET_DEFINE(struct pf_palist, pf_pabuf);
110 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
111 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
112 VNET_DEFINE(struct pf_kstatus, pf_status);
114 VNET_DEFINE(u_int32_t, ticket_altqs_active);
115 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
116 VNET_DEFINE(int, altqs_inactive_open);
117 VNET_DEFINE(u_int32_t, ticket_pabuf);
119 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
120 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
121 VNET_DEFINE(u_char, pf_tcp_secret[16]);
122 #define V_pf_tcp_secret VNET(pf_tcp_secret)
123 VNET_DEFINE(int, pf_tcp_secret_init);
124 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
125 VNET_DEFINE(int, pf_tcp_iss_off);
126 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
129 * Queue for pf_intr() sends.
131 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
132 struct pf_send_entry {
133 STAILQ_ENTRY(pf_send_entry) pfse_next;
150 #define pfse_icmp_type u.icmpopts.type
151 #define pfse_icmp_code u.icmpopts.code
152 #define pfse_icmp_mtu u.icmpopts.mtu
155 STAILQ_HEAD(pf_send_head, pf_send_entry);
156 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157 #define V_pf_sendqueue VNET(pf_sendqueue)
159 static struct mtx pf_sendqueue_mtx;
160 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
161 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
164 * Queue for pf_overload_task() tasks.
166 struct pf_overload_entry {
167 SLIST_ENTRY(pf_overload_entry) next;
171 struct pf_rule *rule;
174 SLIST_HEAD(pf_overload_head, pf_overload_entry);
175 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
176 #define V_pf_overloadqueue VNET(pf_overloadqueue)
177 static VNET_DEFINE(struct task, pf_overloadtask);
178 #define V_pf_overloadtask VNET(pf_overloadtask)
180 static struct mtx pf_overloadqueue_mtx;
181 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
182 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
184 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
185 struct mtx pf_unlnkdrules_mtx;
187 static VNET_DEFINE(uma_zone_t, pf_sources_z);
188 #define V_pf_sources_z VNET(pf_sources_z)
189 uma_zone_t pf_mtag_z;
190 VNET_DEFINE(uma_zone_t, pf_state_z);
191 VNET_DEFINE(uma_zone_t, pf_state_key_z);
193 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
194 #define PFID_CPUBITS 8
195 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
196 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
197 #define PFID_MAXID (~PFID_CPUMASK)
198 CTASSERT((1 << PFID_CPUBITS) >= MAXCPU);
200 static void pf_src_tree_remove_state(struct pf_state *);
201 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
203 static void pf_add_threshold(struct pf_threshold *);
204 static int pf_check_threshold(struct pf_threshold *);
206 static void pf_change_ap(struct pf_addr *, u_int16_t *,
207 u_int16_t *, u_int16_t *, struct pf_addr *,
208 u_int16_t, u_int8_t, sa_family_t);
209 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
210 struct tcphdr *, struct pf_state_peer *);
211 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
212 struct pf_addr *, struct pf_addr *, u_int16_t,
213 u_int16_t *, u_int16_t *, u_int16_t *,
214 u_int16_t *, u_int8_t, sa_family_t);
215 static void pf_send_tcp(struct mbuf *,
216 const struct pf_rule *, sa_family_t,
217 const struct pf_addr *, const struct pf_addr *,
218 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
219 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
220 u_int16_t, struct ifnet *);
221 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
222 sa_family_t, struct pf_rule *);
223 static void pf_detach_state(struct pf_state *);
224 static int pf_state_key_attach(struct pf_state_key *,
225 struct pf_state_key *, struct pf_state *);
226 static void pf_state_key_detach(struct pf_state *, int);
227 static int pf_state_key_ctor(void *, int, void *, int);
228 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
229 static int pf_test_rule(struct pf_rule **, struct pf_state **,
230 int, struct pfi_kif *, struct mbuf *, int,
231 struct pf_pdesc *, struct pf_rule **,
232 struct pf_ruleset **, struct inpcb *);
233 static int pf_create_state(struct pf_rule *, struct pf_rule *,
234 struct pf_rule *, struct pf_pdesc *,
235 struct pf_src_node *, struct pf_state_key *,
236 struct pf_state_key *, struct mbuf *, int,
237 u_int16_t, u_int16_t, int *, struct pfi_kif *,
238 struct pf_state **, int, u_int16_t, u_int16_t,
240 static int pf_test_fragment(struct pf_rule **, int,
241 struct pfi_kif *, struct mbuf *, void *,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **);
244 static int pf_tcp_track_full(struct pf_state_peer *,
245 struct pf_state_peer *, struct pf_state **,
246 struct pfi_kif *, struct mbuf *, int,
247 struct pf_pdesc *, u_short *, int *);
248 static int pf_tcp_track_sloppy(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pf_pdesc *, u_short *);
251 static int pf_test_state_tcp(struct pf_state **, int,
252 struct pfi_kif *, struct mbuf *, int,
253 void *, struct pf_pdesc *, u_short *);
254 static int pf_test_state_udp(struct pf_state **, int,
255 struct pfi_kif *, struct mbuf *, int,
256 void *, struct pf_pdesc *);
257 static int pf_test_state_icmp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260 static int pf_test_state_other(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
262 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
264 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
266 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
268 static int pf_check_proto_cksum(struct mbuf *, int, int,
269 u_int8_t, sa_family_t);
270 static void pf_print_state_parts(struct pf_state *,
271 struct pf_state_key *, struct pf_state_key *);
272 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
273 struct pf_addr_wrap *);
274 static struct pf_state *pf_find_state(struct pfi_kif *,
275 struct pf_state_key_cmp *, u_int);
276 static int pf_src_connlimit(struct pf_state **);
277 static void pf_overload_task(void *v, int pending);
278 static int pf_insert_src_node(struct pf_src_node **,
279 struct pf_rule *, struct pf_addr *, sa_family_t);
280 static u_int pf_purge_expired_states(u_int, int);
281 static void pf_purge_unlinked_rules(void);
282 static int pf_mtag_uminit(void *, int, int);
283 static void pf_mtag_free(struct m_tag *);
285 static void pf_route(struct mbuf **, struct pf_rule *, int,
286 struct ifnet *, struct pf_state *,
290 static void pf_change_a6(struct pf_addr *, u_int16_t *,
291 struct pf_addr *, u_int8_t);
292 static void pf_route6(struct mbuf **, struct pf_rule *, int,
293 struct ifnet *, struct pf_state *,
297 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
299 VNET_DECLARE(int, pf_end_threads);
301 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
303 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
304 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
306 #define STATE_LOOKUP(i, k, d, s, pd) \
308 (s) = pf_find_state((i), (k), (d)); \
311 if (PACKET_LOOPED(pd)) \
313 if ((d) == PF_OUT && \
314 (((s)->rule.ptr->rt == PF_ROUTETO && \
315 (s)->rule.ptr->direction == PF_OUT) || \
316 ((s)->rule.ptr->rt == PF_REPLYTO && \
317 (s)->rule.ptr->direction == PF_IN)) && \
318 (s)->rt_kif != NULL && \
319 (s)->rt_kif != (i)) \
323 #define BOUND_IFACE(r, k) \
324 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
326 #define STATE_INC_COUNTERS(s) \
328 counter_u64_add(s->rule.ptr->states_cur, 1); \
329 counter_u64_add(s->rule.ptr->states_tot, 1); \
330 if (s->anchor.ptr != NULL) { \
331 counter_u64_add(s->anchor.ptr->states_cur, 1); \
332 counter_u64_add(s->anchor.ptr->states_tot, 1); \
334 if (s->nat_rule.ptr != NULL) { \
335 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
336 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
340 #define STATE_DEC_COUNTERS(s) \
342 if (s->nat_rule.ptr != NULL) \
343 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
344 if (s->anchor.ptr != NULL) \
345 counter_u64_add(s->anchor.ptr->states_cur, -1); \
346 counter_u64_add(s->rule.ptr->states_cur, -1); \
349 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
350 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
351 VNET_DEFINE(struct pf_idhash *, pf_idhash);
352 VNET_DEFINE(struct pf_srchash *, pf_srchash);
354 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
357 u_long pf_srchashmask;
358 static u_long pf_hashsize;
359 static u_long pf_srchashsize;
361 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
362 &pf_hashsize, 0, "Size of pf(4) states hashtable");
363 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
364 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
366 VNET_DEFINE(void *, pf_swi_cookie);
368 VNET_DEFINE(uint32_t, pf_hashseed);
369 #define V_pf_hashseed VNET(pf_hashseed)
372 pf_addr_cmp(struct pf_addr *a, struct pf_addr *b, sa_family_t af)
378 if (a->addr32[0] > b->addr32[0])
380 if (a->addr32[0] < b->addr32[0])
386 if (a->addr32[3] > b->addr32[3])
388 if (a->addr32[3] < b->addr32[3])
390 if (a->addr32[2] > b->addr32[2])
392 if (a->addr32[2] < b->addr32[2])
394 if (a->addr32[1] > b->addr32[1])
396 if (a->addr32[1] < b->addr32[1])
398 if (a->addr32[0] > b->addr32[0])
400 if (a->addr32[0] < b->addr32[0])
405 panic("%s: unknown address family %u", __func__, af);
410 static __inline uint32_t
411 pf_hashkey(struct pf_state_key *sk)
415 h = murmur3_aligned_32((uint32_t *)sk,
416 sizeof(struct pf_state_key_cmp),
419 return (h & pf_hashmask);
422 static __inline uint32_t
423 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
429 h = murmur3_aligned_32((uint32_t *)&addr->v4,
430 sizeof(addr->v4), V_pf_hashseed);
433 h = murmur3_aligned_32((uint32_t *)&addr->v6,
434 sizeof(addr->v6), V_pf_hashseed);
437 panic("%s: unknown address family %u", __func__, af);
440 return (h & pf_srchashmask);
445 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
450 dst->addr32[0] = src->addr32[0];
454 dst->addr32[0] = src->addr32[0];
455 dst->addr32[1] = src->addr32[1];
456 dst->addr32[2] = src->addr32[2];
457 dst->addr32[3] = src->addr32[3];
464 pf_init_threshold(struct pf_threshold *threshold,
465 u_int32_t limit, u_int32_t seconds)
467 threshold->limit = limit * PF_THRESHOLD_MULT;
468 threshold->seconds = seconds;
469 threshold->count = 0;
470 threshold->last = time_uptime;
474 pf_add_threshold(struct pf_threshold *threshold)
476 u_int32_t t = time_uptime, diff = t - threshold->last;
478 if (diff >= threshold->seconds)
479 threshold->count = 0;
481 threshold->count -= threshold->count * diff /
483 threshold->count += PF_THRESHOLD_MULT;
488 pf_check_threshold(struct pf_threshold *threshold)
490 return (threshold->count > threshold->limit);
494 pf_src_connlimit(struct pf_state **state)
496 struct pf_overload_entry *pfoe;
499 PF_STATE_LOCK_ASSERT(*state);
501 (*state)->src_node->conn++;
502 (*state)->src.tcp_est = 1;
503 pf_add_threshold(&(*state)->src_node->conn_rate);
505 if ((*state)->rule.ptr->max_src_conn &&
506 (*state)->rule.ptr->max_src_conn <
507 (*state)->src_node->conn) {
508 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
512 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
513 pf_check_threshold(&(*state)->src_node->conn_rate)) {
514 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
521 /* Kill this state. */
522 (*state)->timeout = PFTM_PURGE;
523 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
525 if ((*state)->rule.ptr->overload_tbl == NULL)
528 /* Schedule overloading and flushing task. */
529 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
531 return (1); /* too bad :( */
533 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
534 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
535 pfoe->rule = (*state)->rule.ptr;
536 pfoe->dir = (*state)->direction;
538 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
539 PF_OVERLOADQ_UNLOCK();
540 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
546 pf_overload_task(void *v, int pending)
548 struct pf_overload_head queue;
550 struct pf_overload_entry *pfoe, *pfoe1;
553 CURVNET_SET((struct vnet *)v);
556 queue = V_pf_overloadqueue;
557 SLIST_INIT(&V_pf_overloadqueue);
558 PF_OVERLOADQ_UNLOCK();
560 bzero(&p, sizeof(p));
561 SLIST_FOREACH(pfoe, &queue, next) {
562 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
563 if (V_pf_status.debug >= PF_DEBUG_MISC) {
564 printf("%s: blocking address ", __func__);
565 pf_print_host(&pfoe->addr, 0, pfoe->af);
569 p.pfra_af = pfoe->af;
574 p.pfra_ip4addr = pfoe->addr.v4;
580 p.pfra_ip6addr = pfoe->addr.v6;
586 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
591 * Remove those entries, that don't need flushing.
593 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
594 if (pfoe->rule->flush == 0) {
595 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
596 free(pfoe, M_PFTEMP);
599 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
601 /* If nothing to flush, return. */
602 if (SLIST_EMPTY(&queue)) {
607 for (int i = 0; i <= pf_hashmask; i++) {
608 struct pf_idhash *ih = &V_pf_idhash[i];
609 struct pf_state_key *sk;
613 LIST_FOREACH(s, &ih->states, entry) {
614 sk = s->key[PF_SK_WIRE];
615 SLIST_FOREACH(pfoe, &queue, next)
616 if (sk->af == pfoe->af &&
617 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
618 pfoe->rule == s->rule.ptr) &&
619 ((pfoe->dir == PF_OUT &&
620 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
621 (pfoe->dir == PF_IN &&
622 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
623 s->timeout = PFTM_PURGE;
624 s->src.state = s->dst.state = TCPS_CLOSED;
628 PF_HASHROW_UNLOCK(ih);
630 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
631 free(pfoe, M_PFTEMP);
632 if (V_pf_status.debug >= PF_DEBUG_MISC)
633 printf("%s: %u states killed", __func__, killed);
639 * Can return locked on failure, so that we can consistently
640 * allocate and insert a new one.
643 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
646 struct pf_srchash *sh;
647 struct pf_src_node *n;
649 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
651 sh = &V_pf_srchash[pf_hashsrc(src, af)];
653 LIST_FOREACH(n, &sh->nodes, entry)
654 if (n->rule.ptr == rule && n->af == af &&
655 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
656 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
658 if (n != NULL || returnlocked == 0)
659 PF_HASHROW_UNLOCK(sh);
665 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
666 struct pf_addr *src, sa_family_t af)
669 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
670 rule->rpool.opts & PF_POOL_STICKYADDR),
671 ("%s for non-tracking rule %p", __func__, rule));
674 *sn = pf_find_src_node(src, rule, af, 1);
677 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
679 PF_HASHROW_ASSERT(sh);
681 if (!rule->max_src_nodes ||
682 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
683 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
685 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
688 PF_HASHROW_UNLOCK(sh);
692 pf_init_threshold(&(*sn)->conn_rate,
693 rule->max_src_conn_rate.limit,
694 rule->max_src_conn_rate.seconds);
697 (*sn)->rule.ptr = rule;
698 PF_ACPY(&(*sn)->addr, src, af);
699 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
700 (*sn)->creation = time_uptime;
701 (*sn)->ruletype = rule->action;
702 if ((*sn)->rule.ptr != NULL)
703 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
704 PF_HASHROW_UNLOCK(sh);
705 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
707 if (rule->max_src_states &&
708 (*sn)->states >= rule->max_src_states) {
709 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
718 pf_unlink_src_node_locked(struct pf_src_node *src)
721 struct pf_srchash *sh;
723 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
724 PF_HASHROW_ASSERT(sh);
726 LIST_REMOVE(src, entry);
728 counter_u64_add(src->rule.ptr->src_nodes, -1);
729 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
733 pf_unlink_src_node(struct pf_src_node *src)
735 struct pf_srchash *sh;
737 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
739 pf_unlink_src_node_locked(src);
740 PF_HASHROW_UNLOCK(sh);
744 pf_free_src_node(struct pf_src_node *sn)
747 KASSERT(sn->states == 0, ("%s: %p has refs", __func__, sn));
748 uma_zfree(V_pf_sources_z, sn);
752 pf_free_src_nodes(struct pf_src_node_list *head)
754 struct pf_src_node *sn, *tmp;
757 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
758 pf_free_src_node(sn);
769 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
770 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
774 /* Per-vnet data storage structures initialization. */
778 struct pf_keyhash *kh;
779 struct pf_idhash *ih;
780 struct pf_srchash *sh;
783 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &pf_hashsize);
784 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
785 pf_hashsize = PF_HASHSIZ;
786 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &pf_srchashsize);
787 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
788 pf_srchashsize = PF_HASHSIZ / 4;
790 V_pf_hashseed = arc4random();
792 /* States and state keys storage. */
793 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
794 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
795 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
796 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
797 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
799 V_pf_state_key_z = uma_zcreate("pf state keys",
800 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
802 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
803 M_PFHASH, M_WAITOK | M_ZERO);
804 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
805 M_PFHASH, M_WAITOK | M_ZERO);
806 pf_hashmask = pf_hashsize - 1;
807 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
809 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
810 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
814 V_pf_sources_z = uma_zcreate("pf source nodes",
815 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
817 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
818 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
819 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
820 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
821 M_PFHASH, M_WAITOK|M_ZERO);
822 pf_srchashmask = pf_srchashsize - 1;
823 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
824 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
827 TAILQ_INIT(&V_pf_altqs[0]);
828 TAILQ_INIT(&V_pf_altqs[1]);
829 TAILQ_INIT(&V_pf_pabuf);
830 V_pf_altqs_active = &V_pf_altqs[0];
831 V_pf_altqs_inactive = &V_pf_altqs[1];
834 /* Send & overload+flush queues. */
835 STAILQ_INIT(&V_pf_sendqueue);
836 SLIST_INIT(&V_pf_overloadqueue);
837 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
838 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
839 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
842 /* Unlinked, but may be referenced rules. */
843 TAILQ_INIT(&V_pf_unlinked_rules);
844 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
851 uma_zdestroy(pf_mtag_z);
857 struct pf_keyhash *kh;
858 struct pf_idhash *ih;
859 struct pf_srchash *sh;
860 struct pf_send_entry *pfse, *next;
863 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
865 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
867 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
869 mtx_destroy(&kh->lock);
870 mtx_destroy(&ih->lock);
872 free(V_pf_keyhash, M_PFHASH);
873 free(V_pf_idhash, M_PFHASH);
875 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
876 KASSERT(LIST_EMPTY(&sh->nodes),
877 ("%s: source node hash not empty", __func__));
878 mtx_destroy(&sh->lock);
880 free(V_pf_srchash, M_PFHASH);
882 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
883 m_freem(pfse->pfse_m);
884 free(pfse, M_PFTEMP);
887 mtx_destroy(&pf_sendqueue_mtx);
888 mtx_destroy(&pf_overloadqueue_mtx);
889 mtx_destroy(&pf_unlnkdrules_mtx);
891 uma_zdestroy(V_pf_sources_z);
892 uma_zdestroy(V_pf_state_z);
893 uma_zdestroy(V_pf_state_key_z);
897 pf_mtag_uminit(void *mem, int size, int how)
901 t = (struct m_tag *)mem;
902 t->m_tag_cookie = MTAG_ABI_COMPAT;
903 t->m_tag_id = PACKET_TAG_PF;
904 t->m_tag_len = sizeof(struct pf_mtag);
905 t->m_tag_free = pf_mtag_free;
911 pf_mtag_free(struct m_tag *t)
914 uma_zfree(pf_mtag_z, t);
918 pf_get_mtag(struct mbuf *m)
922 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
923 return ((struct pf_mtag *)(mtag + 1));
925 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
928 bzero(mtag + 1, sizeof(struct pf_mtag));
929 m_tag_prepend(m, mtag);
931 return ((struct pf_mtag *)(mtag + 1));
935 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
938 struct pf_keyhash *khs, *khw, *kh;
939 struct pf_state_key *sk, *cur;
940 struct pf_state *si, *olds = NULL;
943 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
944 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
945 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
948 * We need to lock hash slots of both keys. To avoid deadlock
949 * we always lock the slot with lower address first. Unlock order
952 * We also need to lock ID hash slot before dropping key
953 * locks. On success we return with ID hash slot locked.
957 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
958 PF_HASHROW_LOCK(khs);
960 khs = &V_pf_keyhash[pf_hashkey(sks)];
961 khw = &V_pf_keyhash[pf_hashkey(skw)];
963 PF_HASHROW_LOCK(khs);
964 } else if (khs < khw) {
965 PF_HASHROW_LOCK(khs);
966 PF_HASHROW_LOCK(khw);
968 PF_HASHROW_LOCK(khw);
969 PF_HASHROW_LOCK(khs);
973 #define KEYS_UNLOCK() do { \
975 PF_HASHROW_UNLOCK(khs); \
976 PF_HASHROW_UNLOCK(khw); \
978 PF_HASHROW_UNLOCK(khs); \
982 * First run: start with wire key.
989 LIST_FOREACH(cur, &kh->keys, entry)
990 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
994 /* Key exists. Check for same kif, if none, add to key. */
995 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
996 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
999 if (si->kif == s->kif &&
1000 si->direction == s->direction) {
1001 if (sk->proto == IPPROTO_TCP &&
1002 si->src.state >= TCPS_FIN_WAIT_2 &&
1003 si->dst.state >= TCPS_FIN_WAIT_2) {
1005 * New state matches an old >FIN_WAIT_2
1006 * state. We can't drop key hash locks,
1007 * thus we can't unlink it properly.
1009 * As a workaround we drop it into
1010 * TCPS_CLOSED state, schedule purge
1011 * ASAP and push it into the very end
1012 * of the slot TAILQ, so that it won't
1013 * conflict with our new state.
1015 si->src.state = si->dst.state =
1017 si->timeout = PFTM_PURGE;
1020 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1021 printf("pf: %s key attach "
1023 (idx == PF_SK_WIRE) ?
1026 pf_print_state_parts(s,
1027 (idx == PF_SK_WIRE) ?
1029 (idx == PF_SK_STACK) ?
1031 printf(", existing: ");
1032 pf_print_state_parts(si,
1033 (idx == PF_SK_WIRE) ?
1035 (idx == PF_SK_STACK) ?
1039 PF_HASHROW_UNLOCK(ih);
1041 uma_zfree(V_pf_state_key_z, sk);
1042 if (idx == PF_SK_STACK)
1044 return (EEXIST); /* collision! */
1047 PF_HASHROW_UNLOCK(ih);
1049 uma_zfree(V_pf_state_key_z, sk);
1052 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1057 /* List is sorted, if-bound states before floating. */
1058 if (s->kif == V_pfi_all)
1059 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1061 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1064 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1065 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1071 * Attach done. See how should we (or should not?)
1072 * attach a second key.
1075 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1079 } else if (sks != NULL) {
1081 * Continue attaching with stack key.
1093 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1094 ("%s failure", __func__));
1101 pf_detach_state(struct pf_state *s)
1103 struct pf_state_key *sks = s->key[PF_SK_STACK];
1104 struct pf_keyhash *kh;
1107 kh = &V_pf_keyhash[pf_hashkey(sks)];
1108 PF_HASHROW_LOCK(kh);
1109 if (s->key[PF_SK_STACK] != NULL)
1110 pf_state_key_detach(s, PF_SK_STACK);
1112 * If both point to same key, then we are done.
1114 if (sks == s->key[PF_SK_WIRE]) {
1115 pf_state_key_detach(s, PF_SK_WIRE);
1116 PF_HASHROW_UNLOCK(kh);
1119 PF_HASHROW_UNLOCK(kh);
1122 if (s->key[PF_SK_WIRE] != NULL) {
1123 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1124 PF_HASHROW_LOCK(kh);
1125 if (s->key[PF_SK_WIRE] != NULL)
1126 pf_state_key_detach(s, PF_SK_WIRE);
1127 PF_HASHROW_UNLOCK(kh);
1132 pf_state_key_detach(struct pf_state *s, int idx)
1134 struct pf_state_key *sk = s->key[idx];
1136 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1138 PF_HASHROW_ASSERT(kh);
1140 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1143 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1144 LIST_REMOVE(sk, entry);
1145 uma_zfree(V_pf_state_key_z, sk);
1150 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1152 struct pf_state_key *sk = mem;
1154 bzero(sk, sizeof(struct pf_state_key_cmp));
1155 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1156 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1161 struct pf_state_key *
1162 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1163 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1165 struct pf_state_key *sk;
1167 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1171 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1172 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1173 sk->port[pd->sidx] = sport;
1174 sk->port[pd->didx] = dport;
1175 sk->proto = pd->proto;
1181 struct pf_state_key *
1182 pf_state_key_clone(struct pf_state_key *orig)
1184 struct pf_state_key *sk;
1186 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1190 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1196 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1197 struct pf_state_key *sks, struct pf_state *s)
1199 struct pf_idhash *ih;
1200 struct pf_state *cur;
1203 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1204 ("%s: sks not pristine", __func__));
1205 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1206 ("%s: skw not pristine", __func__));
1207 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1211 if (s->id == 0 && s->creatorid == 0) {
1212 /* XXX: should be atomic, but probability of collision low */
1213 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1214 V_pf_stateid[curcpu] = 1;
1215 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1216 s->id = htobe64(s->id);
1217 s->creatorid = V_pf_status.hostid;
1220 /* Returns with ID locked on success. */
1221 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1224 ih = &V_pf_idhash[PF_IDHASH(s)];
1225 PF_HASHROW_ASSERT(ih);
1226 LIST_FOREACH(cur, &ih->states, entry)
1227 if (cur->id == s->id && cur->creatorid == s->creatorid)
1231 PF_HASHROW_UNLOCK(ih);
1232 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1233 printf("pf: state ID collision: "
1234 "id: %016llx creatorid: %08x\n",
1235 (unsigned long long)be64toh(s->id),
1236 ntohl(s->creatorid));
1241 LIST_INSERT_HEAD(&ih->states, s, entry);
1242 /* One for keys, one for ID hash. */
1243 refcount_init(&s->refs, 2);
1245 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1246 if (pfsync_insert_state_ptr != NULL)
1247 pfsync_insert_state_ptr(s);
1249 /* Returns locked. */
1254 * Find state by ID: returns with locked row on success.
1257 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1259 struct pf_idhash *ih;
1262 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1264 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1266 PF_HASHROW_LOCK(ih);
1267 LIST_FOREACH(s, &ih->states, entry)
1268 if (s->id == id && s->creatorid == creatorid)
1272 PF_HASHROW_UNLOCK(ih);
1278 * Find state by key.
1279 * Returns with ID hash slot locked on success.
1281 static struct pf_state *
1282 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1284 struct pf_keyhash *kh;
1285 struct pf_state_key *sk;
1289 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1291 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1293 PF_HASHROW_LOCK(kh);
1294 LIST_FOREACH(sk, &kh->keys, entry)
1295 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1298 PF_HASHROW_UNLOCK(kh);
1302 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1304 /* List is sorted, if-bound states before floating ones. */
1305 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1306 if (s->kif == V_pfi_all || s->kif == kif) {
1308 PF_HASHROW_UNLOCK(kh);
1309 if (s->timeout >= PFTM_MAX) {
1311 * State is either being processed by
1312 * pf_unlink_state() in an other thread, or
1313 * is scheduled for immediate expiry.
1320 PF_HASHROW_UNLOCK(kh);
1326 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1328 struct pf_keyhash *kh;
1329 struct pf_state_key *sk;
1330 struct pf_state *s, *ret = NULL;
1333 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1335 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1337 PF_HASHROW_LOCK(kh);
1338 LIST_FOREACH(sk, &kh->keys, entry)
1339 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1342 PF_HASHROW_UNLOCK(kh);
1357 panic("%s: dir %u", __func__, dir);
1360 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1362 PF_HASHROW_UNLOCK(kh);
1376 PF_HASHROW_UNLOCK(kh);
1381 /* END state table stuff */
1384 pf_send(struct pf_send_entry *pfse)
1388 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1390 swi_sched(V_pf_swi_cookie, 0);
1396 struct pf_send_head queue;
1397 struct pf_send_entry *pfse, *next;
1399 CURVNET_SET((struct vnet *)v);
1402 queue = V_pf_sendqueue;
1403 STAILQ_INIT(&V_pf_sendqueue);
1406 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1407 switch (pfse->pfse_type) {
1410 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1413 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1414 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1419 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1423 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1424 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1428 panic("%s: unknown type", __func__);
1430 free(pfse, M_PFTEMP);
1436 pf_purge_thread(void *v)
1440 CURVNET_SET((struct vnet *)v);
1444 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1446 if (V_pf_end_threads) {
1448 * To cleanse up all kifs and rules we need
1449 * two runs: first one clears reference flags,
1450 * then pf_purge_expired_states() doesn't
1451 * raise them, and then second run frees.
1454 pf_purge_unlinked_rules();
1458 * Now purge everything.
1460 pf_purge_expired_states(0, pf_hashmask);
1461 pf_purge_expired_fragments();
1462 pf_purge_expired_src_nodes();
1465 * Now all kifs & rules should be unreferenced,
1466 * thus should be successfully freed.
1468 pf_purge_unlinked_rules();
1472 * Announce success and exit.
1477 wakeup(pf_purge_thread);
1482 /* Process 1/interval fraction of the state table every run. */
1483 idx = pf_purge_expired_states(idx, pf_hashmask /
1484 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1486 /* Purge other expired types every PFTM_INTERVAL seconds. */
1489 * Order is important:
1490 * - states and src nodes reference rules
1491 * - states and rules reference kifs
1493 pf_purge_expired_fragments();
1494 pf_purge_expired_src_nodes();
1495 pf_purge_unlinked_rules();
1504 pf_state_expires(const struct pf_state *state)
1511 /* handle all PFTM_* > PFTM_MAX here */
1512 if (state->timeout == PFTM_PURGE)
1513 return (time_uptime);
1514 KASSERT(state->timeout != PFTM_UNLINKED,
1515 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1516 KASSERT((state->timeout < PFTM_MAX),
1517 ("pf_state_expires: timeout > PFTM_MAX"));
1518 timeout = state->rule.ptr->timeout[state->timeout];
1520 timeout = V_pf_default_rule.timeout[state->timeout];
1521 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1523 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1524 states = counter_u64_fetch(state->rule.ptr->states_cur);
1526 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1527 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1528 states = V_pf_status.states;
1530 if (end && states > start && start < end) {
1532 return (state->expire + timeout * (end - states) /
1535 return (time_uptime);
1537 return (state->expire + timeout);
1541 pf_purge_expired_src_nodes()
1543 struct pf_src_node_list freelist;
1544 struct pf_srchash *sh;
1545 struct pf_src_node *cur, *next;
1548 LIST_INIT(&freelist);
1549 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1550 PF_HASHROW_LOCK(sh);
1551 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1552 if (cur->states == 0 && cur->expire <= time_uptime) {
1553 pf_unlink_src_node_locked(cur);
1554 LIST_INSERT_HEAD(&freelist, cur, entry);
1555 } else if (cur->rule.ptr != NULL)
1556 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1557 PF_HASHROW_UNLOCK(sh);
1560 pf_free_src_nodes(&freelist);
1562 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1566 pf_src_tree_remove_state(struct pf_state *s)
1570 if (s->src_node != NULL) {
1572 --s->src_node->conn;
1573 if (--s->src_node->states == 0) {
1574 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1577 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1578 s->src_node->expire = time_uptime + timeout;
1581 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1582 if (--s->nat_src_node->states == 0) {
1583 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1586 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1587 s->nat_src_node->expire = time_uptime + timeout;
1590 s->src_node = s->nat_src_node = NULL;
1594 * Unlink and potentilly free a state. Function may be
1595 * called with ID hash row locked, but always returns
1596 * unlocked, since it needs to go through key hash locking.
1599 pf_unlink_state(struct pf_state *s, u_int flags)
1601 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1603 if ((flags & PF_ENTER_LOCKED) == 0)
1604 PF_HASHROW_LOCK(ih);
1606 PF_HASHROW_ASSERT(ih);
1608 if (s->timeout == PFTM_UNLINKED) {
1610 * State is being processed
1611 * by pf_unlink_state() in
1614 PF_HASHROW_UNLOCK(ih);
1615 return (0); /* XXXGL: undefined actually */
1618 if (s->src.state == PF_TCPS_PROXY_DST) {
1619 /* XXX wire key the right one? */
1620 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1621 &s->key[PF_SK_WIRE]->addr[1],
1622 &s->key[PF_SK_WIRE]->addr[0],
1623 s->key[PF_SK_WIRE]->port[1],
1624 s->key[PF_SK_WIRE]->port[0],
1625 s->src.seqhi, s->src.seqlo + 1,
1626 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1629 LIST_REMOVE(s, entry);
1630 pf_src_tree_remove_state(s);
1632 if (pfsync_delete_state_ptr != NULL)
1633 pfsync_delete_state_ptr(s);
1635 STATE_DEC_COUNTERS(s);
1637 s->timeout = PFTM_UNLINKED;
1639 PF_HASHROW_UNLOCK(ih);
1642 refcount_release(&s->refs);
1644 return (pf_release_state(s));
1648 pf_free_state(struct pf_state *cur)
1651 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1652 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1655 pf_normalize_tcp_cleanup(cur);
1656 uma_zfree(V_pf_state_z, cur);
1657 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1661 * Called only from pf_purge_thread(), thus serialized.
1664 pf_purge_expired_states(u_int i, int maxcheck)
1666 struct pf_idhash *ih;
1669 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1672 * Go through hash and unlink states that expire now.
1674 while (maxcheck > 0) {
1676 ih = &V_pf_idhash[i];
1678 PF_HASHROW_LOCK(ih);
1679 LIST_FOREACH(s, &ih->states, entry) {
1680 if (pf_state_expires(s) <= time_uptime) {
1681 V_pf_status.states -=
1682 pf_unlink_state(s, PF_ENTER_LOCKED);
1685 s->rule.ptr->rule_flag |= PFRULE_REFS;
1686 if (s->nat_rule.ptr != NULL)
1687 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1688 if (s->anchor.ptr != NULL)
1689 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1690 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1692 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1694 PF_HASHROW_UNLOCK(ih);
1696 /* Return when we hit end of hash. */
1697 if (++i > pf_hashmask) {
1698 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1705 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1711 pf_purge_unlinked_rules()
1713 struct pf_rulequeue tmpq;
1714 struct pf_rule *r, *r1;
1717 * If we have overloading task pending, then we'd
1718 * better skip purging this time. There is a tiny
1719 * probability that overloading task references
1720 * an already unlinked rule.
1722 PF_OVERLOADQ_LOCK();
1723 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1724 PF_OVERLOADQ_UNLOCK();
1727 PF_OVERLOADQ_UNLOCK();
1730 * Do naive mark-and-sweep garbage collecting of old rules.
1731 * Reference flag is raised by pf_purge_expired_states()
1732 * and pf_purge_expired_src_nodes().
1734 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1735 * use a temporary queue.
1738 PF_UNLNKDRULES_LOCK();
1739 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1740 if (!(r->rule_flag & PFRULE_REFS)) {
1741 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1742 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1744 r->rule_flag &= ~PFRULE_REFS;
1746 PF_UNLNKDRULES_UNLOCK();
1748 if (!TAILQ_EMPTY(&tmpq)) {
1750 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1751 TAILQ_REMOVE(&tmpq, r, entries);
1759 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1764 u_int32_t a = ntohl(addr->addr32[0]);
1765 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1777 u_int8_t i, curstart, curend, maxstart, maxend;
1778 curstart = curend = maxstart = maxend = 255;
1779 for (i = 0; i < 8; i++) {
1780 if (!addr->addr16[i]) {
1781 if (curstart == 255)
1785 if ((curend - curstart) >
1786 (maxend - maxstart)) {
1787 maxstart = curstart;
1790 curstart = curend = 255;
1793 if ((curend - curstart) >
1794 (maxend - maxstart)) {
1795 maxstart = curstart;
1798 for (i = 0; i < 8; i++) {
1799 if (i >= maxstart && i <= maxend) {
1805 b = ntohs(addr->addr16[i]);
1822 pf_print_state(struct pf_state *s)
1824 pf_print_state_parts(s, NULL, NULL);
1828 pf_print_state_parts(struct pf_state *s,
1829 struct pf_state_key *skwp, struct pf_state_key *sksp)
1831 struct pf_state_key *skw, *sks;
1832 u_int8_t proto, dir;
1834 /* Do our best to fill these, but they're skipped if NULL */
1835 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1836 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1837 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1838 dir = s ? s->direction : 0;
1856 case IPPROTO_ICMPV6:
1860 printf("%u", skw->proto);
1873 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1875 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1880 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1882 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1887 if (proto == IPPROTO_TCP) {
1888 printf(" [lo=%u high=%u win=%u modulator=%u",
1889 s->src.seqlo, s->src.seqhi,
1890 s->src.max_win, s->src.seqdiff);
1891 if (s->src.wscale && s->dst.wscale)
1892 printf(" wscale=%u",
1893 s->src.wscale & PF_WSCALE_MASK);
1895 printf(" [lo=%u high=%u win=%u modulator=%u",
1896 s->dst.seqlo, s->dst.seqhi,
1897 s->dst.max_win, s->dst.seqdiff);
1898 if (s->src.wscale && s->dst.wscale)
1899 printf(" wscale=%u",
1900 s->dst.wscale & PF_WSCALE_MASK);
1903 printf(" %u:%u", s->src.state, s->dst.state);
1908 pf_print_flags(u_int8_t f)
1930 #define PF_SET_SKIP_STEPS(i) \
1932 while (head[i] != cur) { \
1933 head[i]->skip[i].ptr = cur; \
1934 head[i] = TAILQ_NEXT(head[i], entries); \
1939 pf_calc_skip_steps(struct pf_rulequeue *rules)
1941 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1944 cur = TAILQ_FIRST(rules);
1946 for (i = 0; i < PF_SKIP_COUNT; ++i)
1948 while (cur != NULL) {
1950 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1951 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1952 if (cur->direction != prev->direction)
1953 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1954 if (cur->af != prev->af)
1955 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1956 if (cur->proto != prev->proto)
1957 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1958 if (cur->src.neg != prev->src.neg ||
1959 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1960 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1961 if (cur->src.port[0] != prev->src.port[0] ||
1962 cur->src.port[1] != prev->src.port[1] ||
1963 cur->src.port_op != prev->src.port_op)
1964 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1965 if (cur->dst.neg != prev->dst.neg ||
1966 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1967 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1968 if (cur->dst.port[0] != prev->dst.port[0] ||
1969 cur->dst.port[1] != prev->dst.port[1] ||
1970 cur->dst.port_op != prev->dst.port_op)
1971 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1974 cur = TAILQ_NEXT(cur, entries);
1976 for (i = 0; i < PF_SKIP_COUNT; ++i)
1977 PF_SET_SKIP_STEPS(i);
1981 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1983 if (aw1->type != aw2->type)
1985 switch (aw1->type) {
1986 case PF_ADDR_ADDRMASK:
1988 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1990 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1993 case PF_ADDR_DYNIFTL:
1994 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1995 case PF_ADDR_NOROUTE:
1996 case PF_ADDR_URPFFAILED:
1999 return (aw1->p.tbl != aw2->p.tbl);
2001 printf("invalid address type: %d\n", aw1->type);
2007 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
2013 l = cksum + old - new;
2014 l = (l >> 16) + (l & 65535);
2022 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
2023 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
2028 PF_ACPY(&ao, a, af);
2036 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2037 ao.addr16[0], an->addr16[0], 0),
2038 ao.addr16[1], an->addr16[1], 0);
2040 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2041 ao.addr16[0], an->addr16[0], u),
2042 ao.addr16[1], an->addr16[1], u),
2048 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2049 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2050 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2051 ao.addr16[0], an->addr16[0], u),
2052 ao.addr16[1], an->addr16[1], u),
2053 ao.addr16[2], an->addr16[2], u),
2054 ao.addr16[3], an->addr16[3], u),
2055 ao.addr16[4], an->addr16[4], u),
2056 ao.addr16[5], an->addr16[5], u),
2057 ao.addr16[6], an->addr16[6], u),
2058 ao.addr16[7], an->addr16[7], u),
2066 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2068 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2072 memcpy(&ao, a, sizeof(ao));
2073 memcpy(a, &an, sizeof(u_int32_t));
2074 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2075 ao % 65536, an % 65536, u);
2080 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2084 PF_ACPY(&ao, a, AF_INET6);
2085 PF_ACPY(a, an, AF_INET6);
2087 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2088 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2089 pf_cksum_fixup(pf_cksum_fixup(*c,
2090 ao.addr16[0], an->addr16[0], u),
2091 ao.addr16[1], an->addr16[1], u),
2092 ao.addr16[2], an->addr16[2], u),
2093 ao.addr16[3], an->addr16[3], u),
2094 ao.addr16[4], an->addr16[4], u),
2095 ao.addr16[5], an->addr16[5], u),
2096 ao.addr16[6], an->addr16[6], u),
2097 ao.addr16[7], an->addr16[7], u);
2102 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2103 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2104 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2106 struct pf_addr oia, ooa;
2108 PF_ACPY(&oia, ia, af);
2110 PF_ACPY(&ooa, oa, af);
2112 /* Change inner protocol port, fix inner protocol checksum. */
2114 u_int16_t oip = *ip;
2121 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2122 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2124 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2126 /* Change inner ip address, fix inner ip and icmp checksums. */
2127 PF_ACPY(ia, na, af);
2131 u_int32_t oh2c = *h2c;
2133 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2134 oia.addr16[0], ia->addr16[0], 0),
2135 oia.addr16[1], ia->addr16[1], 0);
2136 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2137 oia.addr16[0], ia->addr16[0], 0),
2138 oia.addr16[1], ia->addr16[1], 0);
2139 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2145 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2146 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2147 pf_cksum_fixup(pf_cksum_fixup(*ic,
2148 oia.addr16[0], ia->addr16[0], u),
2149 oia.addr16[1], ia->addr16[1], u),
2150 oia.addr16[2], ia->addr16[2], u),
2151 oia.addr16[3], ia->addr16[3], u),
2152 oia.addr16[4], ia->addr16[4], u),
2153 oia.addr16[5], ia->addr16[5], u),
2154 oia.addr16[6], ia->addr16[6], u),
2155 oia.addr16[7], ia->addr16[7], u);
2159 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2161 PF_ACPY(oa, na, af);
2165 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2166 ooa.addr16[0], oa->addr16[0], 0),
2167 ooa.addr16[1], oa->addr16[1], 0);
2172 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2173 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2174 pf_cksum_fixup(pf_cksum_fixup(*ic,
2175 ooa.addr16[0], oa->addr16[0], u),
2176 ooa.addr16[1], oa->addr16[1], u),
2177 ooa.addr16[2], oa->addr16[2], u),
2178 ooa.addr16[3], oa->addr16[3], u),
2179 ooa.addr16[4], oa->addr16[4], u),
2180 ooa.addr16[5], oa->addr16[5], u),
2181 ooa.addr16[6], oa->addr16[6], u),
2182 ooa.addr16[7], oa->addr16[7], u);
2191 * Need to modulate the sequence numbers in the TCP SACK option
2192 * (credits to Krzysztof Pfaff for report and patch)
2195 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2196 struct tcphdr *th, struct pf_state_peer *dst)
2198 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2199 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2200 int copyback = 0, i, olen;
2201 struct sackblk sack;
2203 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2204 if (hlen < TCPOLEN_SACKLEN ||
2205 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2208 while (hlen >= TCPOLEN_SACKLEN) {
2211 case TCPOPT_EOL: /* FALLTHROUGH */
2219 if (olen >= TCPOLEN_SACKLEN) {
2220 for (i = 2; i + TCPOLEN_SACK <= olen;
2221 i += TCPOLEN_SACK) {
2222 memcpy(&sack, &opt[i], sizeof(sack));
2223 pf_change_a(&sack.start, &th->th_sum,
2224 htonl(ntohl(sack.start) -
2226 pf_change_a(&sack.end, &th->th_sum,
2227 htonl(ntohl(sack.end) -
2229 memcpy(&opt[i], &sack, sizeof(sack));
2243 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2248 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2249 const struct pf_addr *saddr, const struct pf_addr *daddr,
2250 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2251 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2252 u_int16_t rtag, struct ifnet *ifp)
2254 struct pf_send_entry *pfse;
2258 struct ip *h = NULL;
2261 struct ip6_hdr *h6 = NULL;
2265 struct pf_mtag *pf_mtag;
2270 /* maximum segment size tcp option */
2271 tlen = sizeof(struct tcphdr);
2278 len = sizeof(struct ip) + tlen;
2283 len = sizeof(struct ip6_hdr) + tlen;
2287 panic("%s: unsupported af %d", __func__, af);
2290 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2291 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2294 m = m_gethdr(M_NOWAIT, MT_DATA);
2296 free(pfse, M_PFTEMP);
2300 mac_netinet_firewall_send(m);
2302 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2303 free(pfse, M_PFTEMP);
2308 m->m_flags |= M_SKIP_FIREWALL;
2309 pf_mtag->tag = rtag;
2311 if (r != NULL && r->rtableid >= 0)
2312 M_SETFIB(m, r->rtableid);
2315 if (r != NULL && r->qid) {
2316 pf_mtag->qid = r->qid;
2318 /* add hints for ecn */
2319 pf_mtag->hdr = mtod(m, struct ip *);
2322 m->m_data += max_linkhdr;
2323 m->m_pkthdr.len = m->m_len = len;
2324 m->m_pkthdr.rcvif = NULL;
2325 bzero(m->m_data, len);
2329 h = mtod(m, struct ip *);
2331 /* IP header fields included in the TCP checksum */
2332 h->ip_p = IPPROTO_TCP;
2333 h->ip_len = htons(tlen);
2334 h->ip_src.s_addr = saddr->v4.s_addr;
2335 h->ip_dst.s_addr = daddr->v4.s_addr;
2337 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2342 h6 = mtod(m, struct ip6_hdr *);
2344 /* IP header fields included in the TCP checksum */
2345 h6->ip6_nxt = IPPROTO_TCP;
2346 h6->ip6_plen = htons(tlen);
2347 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2348 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2350 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2356 th->th_sport = sport;
2357 th->th_dport = dport;
2358 th->th_seq = htonl(seq);
2359 th->th_ack = htonl(ack);
2360 th->th_off = tlen >> 2;
2361 th->th_flags = flags;
2362 th->th_win = htons(win);
2365 opt = (char *)(th + 1);
2366 opt[0] = TCPOPT_MAXSEG;
2369 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2376 th->th_sum = in_cksum(m, len);
2378 /* Finish the IP header */
2380 h->ip_hl = sizeof(*h) >> 2;
2381 h->ip_tos = IPTOS_LOWDELAY;
2382 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2383 h->ip_len = htons(len);
2384 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2387 pfse->pfse_type = PFSE_IP;
2393 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2394 sizeof(struct ip6_hdr), tlen);
2396 h6->ip6_vfc |= IPV6_VERSION;
2397 h6->ip6_hlim = IPV6_DEFHLIM;
2399 pfse->pfse_type = PFSE_IP6;
2408 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2411 struct pf_send_entry *pfse;
2413 struct pf_mtag *pf_mtag;
2415 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2416 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2420 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2421 free(pfse, M_PFTEMP);
2425 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2426 free(pfse, M_PFTEMP);
2430 m0->m_flags |= M_SKIP_FIREWALL;
2432 if (r->rtableid >= 0)
2433 M_SETFIB(m0, r->rtableid);
2437 pf_mtag->qid = r->qid;
2438 /* add hints for ecn */
2439 pf_mtag->hdr = mtod(m0, struct ip *);
2446 pfse->pfse_type = PFSE_ICMP;
2451 pfse->pfse_type = PFSE_ICMP6;
2456 pfse->pfse_icmp_type = type;
2457 pfse->pfse_icmp_code = code;
2462 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2463 * If n is 0, they match if they are equal. If n is != 0, they match if they
2467 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2468 struct pf_addr *b, sa_family_t af)
2475 if ((a->addr32[0] & m->addr32[0]) ==
2476 (b->addr32[0] & m->addr32[0]))
2482 if (((a->addr32[0] & m->addr32[0]) ==
2483 (b->addr32[0] & m->addr32[0])) &&
2484 ((a->addr32[1] & m->addr32[1]) ==
2485 (b->addr32[1] & m->addr32[1])) &&
2486 ((a->addr32[2] & m->addr32[2]) ==
2487 (b->addr32[2] & m->addr32[2])) &&
2488 ((a->addr32[3] & m->addr32[3]) ==
2489 (b->addr32[3] & m->addr32[3])))
2508 * Return 1 if b <= a <= e, otherwise return 0.
2511 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2512 struct pf_addr *a, sa_family_t af)
2517 if ((a->addr32[0] < b->addr32[0]) ||
2518 (a->addr32[0] > e->addr32[0]))
2527 for (i = 0; i < 4; ++i)
2528 if (a->addr32[i] > b->addr32[i])
2530 else if (a->addr32[i] < b->addr32[i])
2533 for (i = 0; i < 4; ++i)
2534 if (a->addr32[i] < e->addr32[i])
2536 else if (a->addr32[i] > e->addr32[i])
2546 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2550 return ((p > a1) && (p < a2));
2552 return ((p < a1) || (p > a2));
2554 return ((p >= a1) && (p <= a2));
2568 return (0); /* never reached */
2572 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2577 return (pf_match(op, a1, a2, p));
2581 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2583 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2585 return (pf_match(op, a1, a2, u));
2589 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2591 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2593 return (pf_match(op, a1, a2, g));
2597 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2602 return ((!r->match_tag_not && r->match_tag == *tag) ||
2603 (r->match_tag_not && r->match_tag != *tag));
2607 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2610 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2612 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2615 pd->pf_mtag->tag = tag;
2620 #define PF_ANCHOR_STACKSIZE 32
2621 struct pf_anchor_stackframe {
2622 struct pf_ruleset *rs;
2623 struct pf_rule *r; /* XXX: + match bit */
2624 struct pf_anchor *child;
2628 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2630 #define PF_ANCHORSTACK_MATCH 0x00000001
2631 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2633 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2634 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2635 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2636 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2637 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2641 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2642 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2645 struct pf_anchor_stackframe *f;
2651 if (*depth >= PF_ANCHOR_STACKSIZE) {
2652 printf("%s: anchor stack overflow on %s\n",
2653 __func__, (*r)->anchor->name);
2654 *r = TAILQ_NEXT(*r, entries);
2656 } else if (*depth == 0 && a != NULL)
2658 f = stack + (*depth)++;
2661 if ((*r)->anchor_wildcard) {
2662 struct pf_anchor_node *parent = &(*r)->anchor->children;
2664 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2668 *rs = &f->child->ruleset;
2671 *rs = &(*r)->anchor->ruleset;
2673 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2677 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2678 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2681 struct pf_anchor_stackframe *f;
2690 f = stack + *depth - 1;
2691 fr = PF_ANCHOR_RULE(f);
2692 if (f->child != NULL) {
2693 struct pf_anchor_node *parent;
2696 * This block traverses through
2697 * a wildcard anchor.
2699 parent = &fr->anchor->children;
2700 if (match != NULL && *match) {
2702 * If any of "*" matched, then
2703 * "foo/ *" matched, mark frame
2706 PF_ANCHOR_SET_MATCH(f);
2709 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2710 if (f->child != NULL) {
2711 *rs = &f->child->ruleset;
2712 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2720 if (*depth == 0 && a != NULL)
2723 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2725 *r = TAILQ_NEXT(fr, entries);
2726 } while (*r == NULL);
2733 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2734 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2739 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2740 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2744 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2745 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2746 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2747 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2748 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2749 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2750 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2751 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2757 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2762 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2766 if (addr->addr32[3] == 0xffffffff) {
2767 addr->addr32[3] = 0;
2768 if (addr->addr32[2] == 0xffffffff) {
2769 addr->addr32[2] = 0;
2770 if (addr->addr32[1] == 0xffffffff) {
2771 addr->addr32[1] = 0;
2773 htonl(ntohl(addr->addr32[0]) + 1);
2776 htonl(ntohl(addr->addr32[1]) + 1);
2779 htonl(ntohl(addr->addr32[2]) + 1);
2782 htonl(ntohl(addr->addr32[3]) + 1);
2789 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2791 struct pf_addr *saddr, *daddr;
2792 u_int16_t sport, dport;
2793 struct inpcbinfo *pi;
2796 pd->lookup.uid = UID_MAX;
2797 pd->lookup.gid = GID_MAX;
2799 switch (pd->proto) {
2801 if (pd->hdr.tcp == NULL)
2803 sport = pd->hdr.tcp->th_sport;
2804 dport = pd->hdr.tcp->th_dport;
2808 if (pd->hdr.udp == NULL)
2810 sport = pd->hdr.udp->uh_sport;
2811 dport = pd->hdr.udp->uh_dport;
2817 if (direction == PF_IN) {
2832 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2833 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2835 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2836 daddr->v4, dport, INPLOOKUP_WILDCARD |
2837 INPLOOKUP_RLOCKPCB, NULL, m);
2845 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2846 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2848 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2849 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2850 INPLOOKUP_RLOCKPCB, NULL, m);
2860 INP_RLOCK_ASSERT(inp);
2861 pd->lookup.uid = inp->inp_cred->cr_uid;
2862 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2869 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2873 u_int8_t *opt, optlen;
2874 u_int8_t wscale = 0;
2876 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2877 if (hlen <= sizeof(struct tcphdr))
2879 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2881 opt = hdr + sizeof(struct tcphdr);
2882 hlen -= sizeof(struct tcphdr);
2892 if (wscale > TCP_MAX_WINSHIFT)
2893 wscale = TCP_MAX_WINSHIFT;
2894 wscale |= PF_WSCALE_FLAG;
2909 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2913 u_int8_t *opt, optlen;
2914 u_int16_t mss = V_tcp_mssdflt;
2916 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2917 if (hlen <= sizeof(struct tcphdr))
2919 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2921 opt = hdr + sizeof(struct tcphdr);
2922 hlen -= sizeof(struct tcphdr);
2923 while (hlen >= TCPOLEN_MAXSEG) {
2931 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2947 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2950 struct sockaddr_in *dst;
2954 struct sockaddr_in6 *dst6;
2955 struct route_in6 ro6;
2957 struct rtentry *rt = NULL;
2959 u_int16_t mss = V_tcp_mssdflt;
2964 hlen = sizeof(struct ip);
2965 bzero(&ro, sizeof(ro));
2966 dst = (struct sockaddr_in *)&ro.ro_dst;
2967 dst->sin_family = AF_INET;
2968 dst->sin_len = sizeof(*dst);
2969 dst->sin_addr = addr->v4;
2970 in_rtalloc_ign(&ro, 0, rtableid);
2976 hlen = sizeof(struct ip6_hdr);
2977 bzero(&ro6, sizeof(ro6));
2978 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2979 dst6->sin6_family = AF_INET6;
2980 dst6->sin6_len = sizeof(*dst6);
2981 dst6->sin6_addr = addr->v6;
2982 in6_rtalloc_ign(&ro6, 0, rtableid);
2988 if (rt && rt->rt_ifp) {
2989 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2990 mss = max(V_tcp_mssdflt, mss);
2993 mss = min(mss, offer);
2994 mss = max(mss, 64); /* sanity - at least max opt space */
2999 pf_tcp_iss(struct pf_pdesc *pd)
3002 u_int32_t digest[4];
3004 if (V_pf_tcp_secret_init == 0) {
3005 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3006 MD5Init(&V_pf_tcp_secret_ctx);
3007 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3008 sizeof(V_pf_tcp_secret));
3009 V_pf_tcp_secret_init = 1;
3012 ctx = V_pf_tcp_secret_ctx;
3014 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3015 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3016 if (pd->af == AF_INET6) {
3017 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3018 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3020 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3021 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3023 MD5Final((u_char *)digest, &ctx);
3024 V_pf_tcp_iss_off += 4096;
3025 #define ISN_RANDOM_INCREMENT (4096 - 1)
3026 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3028 #undef ISN_RANDOM_INCREMENT
3032 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3033 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3034 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3036 struct pf_rule *nr = NULL;
3037 struct pf_addr * const saddr = pd->src;
3038 struct pf_addr * const daddr = pd->dst;
3039 sa_family_t af = pd->af;
3040 struct pf_rule *r, *a = NULL;
3041 struct pf_ruleset *ruleset = NULL;
3042 struct pf_src_node *nsn = NULL;
3043 struct tcphdr *th = pd->hdr.tcp;
3044 struct pf_state_key *sk = NULL, *nk = NULL;
3046 int rewrite = 0, hdrlen = 0;
3047 int tag = -1, rtableid = -1;
3051 u_int16_t sport = 0, dport = 0;
3052 u_int16_t bproto_sum = 0, bip_sum = 0;
3053 u_int8_t icmptype = 0, icmpcode = 0;
3054 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3059 INP_LOCK_ASSERT(inp);
3060 pd->lookup.uid = inp->inp_cred->cr_uid;
3061 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3062 pd->lookup.done = 1;
3065 switch (pd->proto) {
3067 sport = th->th_sport;
3068 dport = th->th_dport;
3069 hdrlen = sizeof(*th);
3072 sport = pd->hdr.udp->uh_sport;
3073 dport = pd->hdr.udp->uh_dport;
3074 hdrlen = sizeof(*pd->hdr.udp);
3078 if (pd->af != AF_INET)
3080 sport = dport = pd->hdr.icmp->icmp_id;
3081 hdrlen = sizeof(*pd->hdr.icmp);
3082 icmptype = pd->hdr.icmp->icmp_type;
3083 icmpcode = pd->hdr.icmp->icmp_code;
3085 if (icmptype == ICMP_UNREACH ||
3086 icmptype == ICMP_SOURCEQUENCH ||
3087 icmptype == ICMP_REDIRECT ||
3088 icmptype == ICMP_TIMXCEED ||
3089 icmptype == ICMP_PARAMPROB)
3094 case IPPROTO_ICMPV6:
3097 sport = dport = pd->hdr.icmp6->icmp6_id;
3098 hdrlen = sizeof(*pd->hdr.icmp6);
3099 icmptype = pd->hdr.icmp6->icmp6_type;
3100 icmpcode = pd->hdr.icmp6->icmp6_code;
3102 if (icmptype == ICMP6_DST_UNREACH ||
3103 icmptype == ICMP6_PACKET_TOO_BIG ||
3104 icmptype == ICMP6_TIME_EXCEEDED ||
3105 icmptype == ICMP6_PARAM_PROB)
3110 sport = dport = hdrlen = 0;
3114 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3116 /* check packet for BINAT/NAT/RDR */
3117 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3118 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3119 KASSERT(sk != NULL, ("%s: null sk", __func__));
3120 KASSERT(nk != NULL, ("%s: null nk", __func__));
3123 bip_sum = *pd->ip_sum;
3125 switch (pd->proto) {
3127 bproto_sum = th->th_sum;
3128 pd->proto_sum = &th->th_sum;
3130 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3131 nk->port[pd->sidx] != sport) {
3132 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3133 &th->th_sum, &nk->addr[pd->sidx],
3134 nk->port[pd->sidx], 0, af);
3135 pd->sport = &th->th_sport;
3136 sport = th->th_sport;
3139 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3140 nk->port[pd->didx] != dport) {
3141 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3142 &th->th_sum, &nk->addr[pd->didx],
3143 nk->port[pd->didx], 0, af);
3144 dport = th->th_dport;
3145 pd->dport = &th->th_dport;
3150 bproto_sum = pd->hdr.udp->uh_sum;
3151 pd->proto_sum = &pd->hdr.udp->uh_sum;
3153 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3154 nk->port[pd->sidx] != sport) {
3155 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3156 pd->ip_sum, &pd->hdr.udp->uh_sum,
3157 &nk->addr[pd->sidx],
3158 nk->port[pd->sidx], 1, af);
3159 sport = pd->hdr.udp->uh_sport;
3160 pd->sport = &pd->hdr.udp->uh_sport;
3163 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3164 nk->port[pd->didx] != dport) {
3165 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3166 pd->ip_sum, &pd->hdr.udp->uh_sum,
3167 &nk->addr[pd->didx],
3168 nk->port[pd->didx], 1, af);
3169 dport = pd->hdr.udp->uh_dport;
3170 pd->dport = &pd->hdr.udp->uh_dport;
3176 nk->port[0] = nk->port[1];
3177 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3178 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3179 nk->addr[pd->sidx].v4.s_addr, 0);
3181 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3182 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3183 nk->addr[pd->didx].v4.s_addr, 0);
3185 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3186 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3187 pd->hdr.icmp->icmp_cksum, sport,
3189 pd->hdr.icmp->icmp_id = nk->port[1];
3190 pd->sport = &pd->hdr.icmp->icmp_id;
3192 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3196 case IPPROTO_ICMPV6:
3197 nk->port[0] = nk->port[1];
3198 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3199 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3200 &nk->addr[pd->sidx], 0);
3202 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3203 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3204 &nk->addr[pd->didx], 0);
3213 &nk->addr[pd->sidx], AF_INET))
3214 pf_change_a(&saddr->v4.s_addr,
3216 nk->addr[pd->sidx].v4.s_addr, 0);
3219 &nk->addr[pd->didx], AF_INET))
3220 pf_change_a(&daddr->v4.s_addr,
3222 nk->addr[pd->didx].v4.s_addr, 0);
3228 &nk->addr[pd->sidx], AF_INET6))
3229 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3232 &nk->addr[pd->didx], AF_INET6))
3233 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3246 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3247 r = r->skip[PF_SKIP_IFP].ptr;
3248 else if (r->direction && r->direction != direction)
3249 r = r->skip[PF_SKIP_DIR].ptr;
3250 else if (r->af && r->af != af)
3251 r = r->skip[PF_SKIP_AF].ptr;
3252 else if (r->proto && r->proto != pd->proto)
3253 r = r->skip[PF_SKIP_PROTO].ptr;
3254 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3255 r->src.neg, kif, M_GETFIB(m)))
3256 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3257 /* tcp/udp only. port_op always 0 in other cases */
3258 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3259 r->src.port[0], r->src.port[1], sport))
3260 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3261 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3262 r->dst.neg, NULL, M_GETFIB(m)))
3263 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3264 /* tcp/udp only. port_op always 0 in other cases */
3265 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3266 r->dst.port[0], r->dst.port[1], dport))
3267 r = r->skip[PF_SKIP_DST_PORT].ptr;
3268 /* icmp only. type always 0 in other cases */
3269 else if (r->type && r->type != icmptype + 1)
3270 r = TAILQ_NEXT(r, entries);
3271 /* icmp only. type always 0 in other cases */
3272 else if (r->code && r->code != icmpcode + 1)
3273 r = TAILQ_NEXT(r, entries);
3274 else if (r->tos && !(r->tos == pd->tos))
3275 r = TAILQ_NEXT(r, entries);
3276 else if (r->rule_flag & PFRULE_FRAGMENT)
3277 r = TAILQ_NEXT(r, entries);
3278 else if (pd->proto == IPPROTO_TCP &&
3279 (r->flagset & th->th_flags) != r->flags)
3280 r = TAILQ_NEXT(r, entries);
3281 /* tcp/udp only. uid.op always 0 in other cases */
3282 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3283 pf_socket_lookup(direction, pd, m), 1)) &&
3284 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3286 r = TAILQ_NEXT(r, entries);
3287 /* tcp/udp only. gid.op always 0 in other cases */
3288 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3289 pf_socket_lookup(direction, pd, m), 1)) &&
3290 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3292 r = TAILQ_NEXT(r, entries);
3294 r->prob <= arc4random())
3295 r = TAILQ_NEXT(r, entries);
3296 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3297 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3298 r = TAILQ_NEXT(r, entries);
3299 else if (r->os_fingerprint != PF_OSFP_ANY &&
3300 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3301 pf_osfp_fingerprint(pd, m, off, th),
3302 r->os_fingerprint)))
3303 r = TAILQ_NEXT(r, entries);
3307 if (r->rtableid >= 0)
3308 rtableid = r->rtableid;
3309 if (r->anchor == NULL) {
3316 r = TAILQ_NEXT(r, entries);
3318 pf_step_into_anchor(anchor_stack, &asd,
3319 &ruleset, PF_RULESET_FILTER, &r, &a,
3322 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3323 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3330 REASON_SET(&reason, PFRES_MATCH);
3332 if (r->log || (nr != NULL && nr->log)) {
3334 m_copyback(m, off, hdrlen, pd->hdr.any);
3335 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3339 if ((r->action == PF_DROP) &&
3340 ((r->rule_flag & PFRULE_RETURNRST) ||
3341 (r->rule_flag & PFRULE_RETURNICMP) ||
3342 (r->rule_flag & PFRULE_RETURN))) {
3343 /* undo NAT changes, if they have taken place */
3345 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3346 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3348 *pd->sport = sk->port[pd->sidx];
3350 *pd->dport = sk->port[pd->didx];
3352 *pd->proto_sum = bproto_sum;
3354 *pd->ip_sum = bip_sum;
3355 m_copyback(m, off, hdrlen, pd->hdr.any);
3357 if (pd->proto == IPPROTO_TCP &&
3358 ((r->rule_flag & PFRULE_RETURNRST) ||
3359 (r->rule_flag & PFRULE_RETURN)) &&
3360 !(th->th_flags & TH_RST)) {
3361 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3373 h4 = mtod(m, struct ip *);
3374 len = ntohs(h4->ip_len) - off;
3379 h6 = mtod(m, struct ip6_hdr *);
3380 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3385 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3386 REASON_SET(&reason, PFRES_PROTCKSUM);
3388 if (th->th_flags & TH_SYN)
3390 if (th->th_flags & TH_FIN)
3392 pf_send_tcp(m, r, af, pd->dst,
3393 pd->src, th->th_dport, th->th_sport,
3394 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3395 r->return_ttl, 1, 0, kif->pfik_ifp);
3397 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3399 pf_send_icmp(m, r->return_icmp >> 8,
3400 r->return_icmp & 255, af, r);
3401 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3403 pf_send_icmp(m, r->return_icmp6 >> 8,
3404 r->return_icmp6 & 255, af, r);
3407 if (r->action == PF_DROP)
3410 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3411 REASON_SET(&reason, PFRES_MEMORY);
3415 M_SETFIB(m, rtableid);
3417 if (!state_icmp && (r->keep_state || nr != NULL ||
3418 (pd->flags & PFDESC_TCP_NORM))) {
3420 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3421 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3423 if (action != PF_PASS)
3427 uma_zfree(V_pf_state_key_z, sk);
3429 uma_zfree(V_pf_state_key_z, nk);
3432 /* copy back packet headers if we performed NAT operations */
3434 m_copyback(m, off, hdrlen, pd->hdr.any);
3436 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3437 direction == PF_OUT &&
3438 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3440 * We want the state created, but we dont
3441 * want to send this in case a partner
3442 * firewall has to know about it to allow
3443 * replies through it.
3451 uma_zfree(V_pf_state_key_z, sk);
3453 uma_zfree(V_pf_state_key_z, nk);
3458 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3459 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3460 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3461 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3462 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3464 struct pf_state *s = NULL;
3465 struct pf_src_node *sn = NULL;
3466 struct tcphdr *th = pd->hdr.tcp;
3467 u_int16_t mss = V_tcp_mssdflt;
3470 /* check maximums */
3471 if (r->max_states &&
3472 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3473 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3474 REASON_SET(&reason, PFRES_MAXSTATES);
3477 /* src node for filter rule */
3478 if ((r->rule_flag & PFRULE_SRCTRACK ||
3479 r->rpool.opts & PF_POOL_STICKYADDR) &&
3480 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3481 REASON_SET(&reason, PFRES_SRCLIMIT);
3484 /* src node for translation rule */
3485 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3486 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3487 REASON_SET(&reason, PFRES_SRCLIMIT);
3490 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3492 REASON_SET(&reason, PFRES_MEMORY);
3496 s->nat_rule.ptr = nr;
3498 STATE_INC_COUNTERS(s);
3500 s->state_flags |= PFSTATE_ALLOWOPTS;
3501 if (r->rule_flag & PFRULE_STATESLOPPY)
3502 s->state_flags |= PFSTATE_SLOPPY;
3503 s->log = r->log & PF_LOG_ALL;
3504 s->sync_state = PFSYNC_S_NONE;
3506 s->log |= nr->log & PF_LOG_ALL;
3507 switch (pd->proto) {
3509 s->src.seqlo = ntohl(th->th_seq);
3510 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3511 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3512 r->keep_state == PF_STATE_MODULATE) {
3513 /* Generate sequence number modulator */
3514 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3517 pf_change_a(&th->th_seq, &th->th_sum,
3518 htonl(s->src.seqlo + s->src.seqdiff), 0);
3522 if (th->th_flags & TH_SYN) {
3524 s->src.wscale = pf_get_wscale(m, off,
3525 th->th_off, pd->af);
3527 s->src.max_win = MAX(ntohs(th->th_win), 1);
3528 if (s->src.wscale & PF_WSCALE_MASK) {
3529 /* Remove scale factor from initial window */
3530 int win = s->src.max_win;
3531 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3532 s->src.max_win = (win - 1) >>
3533 (s->src.wscale & PF_WSCALE_MASK);
3535 if (th->th_flags & TH_FIN)
3539 s->src.state = TCPS_SYN_SENT;
3540 s->dst.state = TCPS_CLOSED;
3541 s->timeout = PFTM_TCP_FIRST_PACKET;
3544 s->src.state = PFUDPS_SINGLE;
3545 s->dst.state = PFUDPS_NO_TRAFFIC;
3546 s->timeout = PFTM_UDP_FIRST_PACKET;
3550 case IPPROTO_ICMPV6:
3552 s->timeout = PFTM_ICMP_FIRST_PACKET;
3555 s->src.state = PFOTHERS_SINGLE;
3556 s->dst.state = PFOTHERS_NO_TRAFFIC;
3557 s->timeout = PFTM_OTHER_FIRST_PACKET;
3560 if (r->rt && r->rt != PF_FASTROUTE) {
3561 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3562 REASON_SET(&reason, PFRES_BADSTATE);
3563 pf_src_tree_remove_state(s);
3564 STATE_DEC_COUNTERS(s);
3565 uma_zfree(V_pf_state_z, s);
3568 s->rt_kif = r->rpool.cur->kif;
3571 s->creation = time_uptime;
3572 s->expire = time_uptime;
3576 s->src_node->states++;
3579 /* XXX We only modify one side for now. */
3580 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3581 s->nat_src_node = nsn;
3582 s->nat_src_node->states++;
3584 if (pd->proto == IPPROTO_TCP) {
3585 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3586 off, pd, th, &s->src, &s->dst)) {
3587 REASON_SET(&reason, PFRES_MEMORY);
3588 pf_src_tree_remove_state(s);
3589 STATE_DEC_COUNTERS(s);
3590 uma_zfree(V_pf_state_z, s);
3593 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3594 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3595 &s->src, &s->dst, rewrite)) {
3596 /* This really shouldn't happen!!! */
3597 DPFPRINTF(PF_DEBUG_URGENT,
3598 ("pf_normalize_tcp_stateful failed on first pkt"));
3599 pf_normalize_tcp_cleanup(s);
3600 pf_src_tree_remove_state(s);
3601 STATE_DEC_COUNTERS(s);
3602 uma_zfree(V_pf_state_z, s);
3606 s->direction = pd->dir;
3609 * sk/nk could already been setup by pf_get_translation().
3612 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3613 __func__, nr, sk, nk));
3614 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3619 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3620 __func__, nr, sk, nk));
3622 /* Swap sk/nk for PF_OUT. */
3623 if (pf_state_insert(BOUND_IFACE(r, kif),
3624 (pd->dir == PF_IN) ? sk : nk,
3625 (pd->dir == PF_IN) ? nk : sk, s)) {
3626 if (pd->proto == IPPROTO_TCP)
3627 pf_normalize_tcp_cleanup(s);
3628 REASON_SET(&reason, PFRES_STATEINS);
3629 pf_src_tree_remove_state(s);
3630 STATE_DEC_COUNTERS(s);
3631 uma_zfree(V_pf_state_z, s);
3638 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3639 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3640 s->src.state = PF_TCPS_PROXY_SRC;
3641 /* undo NAT changes, if they have taken place */
3643 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3644 if (pd->dir == PF_OUT)
3645 skt = s->key[PF_SK_STACK];
3646 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3647 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3649 *pd->sport = skt->port[pd->sidx];
3651 *pd->dport = skt->port[pd->didx];
3653 *pd->proto_sum = bproto_sum;
3655 *pd->ip_sum = bip_sum;
3656 m_copyback(m, off, hdrlen, pd->hdr.any);
3658 s->src.seqhi = htonl(arc4random());
3659 /* Find mss option */
3660 int rtid = M_GETFIB(m);
3661 mss = pf_get_mss(m, off, th->th_off, pd->af);
3662 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3663 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3665 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3666 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3667 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3668 REASON_SET(&reason, PFRES_SYNPROXY);
3669 return (PF_SYNPROXY_DROP);
3676 uma_zfree(V_pf_state_key_z, sk);
3678 uma_zfree(V_pf_state_key_z, nk);
3680 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3681 pf_unlink_src_node(sn);
3682 pf_free_src_node(sn);
3685 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3686 pf_unlink_src_node(nsn);
3687 pf_free_src_node(nsn);
3694 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3695 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3696 struct pf_ruleset **rsm)
3698 struct pf_rule *r, *a = NULL;
3699 struct pf_ruleset *ruleset = NULL;
3700 sa_family_t af = pd->af;
3705 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3709 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3712 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3713 r = r->skip[PF_SKIP_IFP].ptr;
3714 else if (r->direction && r->direction != direction)
3715 r = r->skip[PF_SKIP_DIR].ptr;
3716 else if (r->af && r->af != af)
3717 r = r->skip[PF_SKIP_AF].ptr;
3718 else if (r->proto && r->proto != pd->proto)
3719 r = r->skip[PF_SKIP_PROTO].ptr;
3720 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3721 r->src.neg, kif, M_GETFIB(m)))
3722 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3723 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3724 r->dst.neg, NULL, M_GETFIB(m)))
3725 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3726 else if (r->tos && !(r->tos == pd->tos))
3727 r = TAILQ_NEXT(r, entries);
3728 else if (r->os_fingerprint != PF_OSFP_ANY)
3729 r = TAILQ_NEXT(r, entries);
3730 else if (pd->proto == IPPROTO_UDP &&
3731 (r->src.port_op || r->dst.port_op))
3732 r = TAILQ_NEXT(r, entries);
3733 else if (pd->proto == IPPROTO_TCP &&
3734 (r->src.port_op || r->dst.port_op || r->flagset))
3735 r = TAILQ_NEXT(r, entries);
3736 else if ((pd->proto == IPPROTO_ICMP ||
3737 pd->proto == IPPROTO_ICMPV6) &&
3738 (r->type || r->code))
3739 r = TAILQ_NEXT(r, entries);
3740 else if (r->prob && r->prob <=
3741 (arc4random() % (UINT_MAX - 1) + 1))
3742 r = TAILQ_NEXT(r, entries);
3743 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3744 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3745 r = TAILQ_NEXT(r, entries);
3747 if (r->anchor == NULL) {
3754 r = TAILQ_NEXT(r, entries);
3756 pf_step_into_anchor(anchor_stack, &asd,
3757 &ruleset, PF_RULESET_FILTER, &r, &a,
3760 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3761 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3768 REASON_SET(&reason, PFRES_MATCH);
3771 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3774 if (r->action != PF_PASS)
3777 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3778 REASON_SET(&reason, PFRES_MEMORY);
3786 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3787 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3788 struct pf_pdesc *pd, u_short *reason, int *copyback)
3790 struct tcphdr *th = pd->hdr.tcp;
3791 u_int16_t win = ntohs(th->th_win);
3792 u_int32_t ack, end, seq, orig_seq;
3796 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3797 sws = src->wscale & PF_WSCALE_MASK;
3798 dws = dst->wscale & PF_WSCALE_MASK;
3803 * Sequence tracking algorithm from Guido van Rooij's paper:
3804 * http://www.madison-gurkha.com/publications/tcp_filtering/
3808 orig_seq = seq = ntohl(th->th_seq);
3809 if (src->seqlo == 0) {
3810 /* First packet from this end. Set its state */
3812 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3813 src->scrub == NULL) {
3814 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3815 REASON_SET(reason, PFRES_MEMORY);
3820 /* Deferred generation of sequence number modulator */
3821 if (dst->seqdiff && !src->seqdiff) {
3822 /* use random iss for the TCP server */
3823 while ((src->seqdiff = arc4random() - seq) == 0)
3825 ack = ntohl(th->th_ack) - dst->seqdiff;
3826 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3828 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3831 ack = ntohl(th->th_ack);
3834 end = seq + pd->p_len;
3835 if (th->th_flags & TH_SYN) {
3837 if (dst->wscale & PF_WSCALE_FLAG) {
3838 src->wscale = pf_get_wscale(m, off, th->th_off,
3840 if (src->wscale & PF_WSCALE_FLAG) {
3841 /* Remove scale factor from initial
3843 sws = src->wscale & PF_WSCALE_MASK;
3844 win = ((u_int32_t)win + (1 << sws) - 1)
3846 dws = dst->wscale & PF_WSCALE_MASK;
3848 /* fixup other window */
3849 dst->max_win <<= dst->wscale &
3851 /* in case of a retrans SYN|ACK */
3856 if (th->th_flags & TH_FIN)
3860 if (src->state < TCPS_SYN_SENT)
3861 src->state = TCPS_SYN_SENT;
3864 * May need to slide the window (seqhi may have been set by
3865 * the crappy stack check or if we picked up the connection
3866 * after establishment)
3868 if (src->seqhi == 1 ||
3869 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3870 src->seqhi = end + MAX(1, dst->max_win << dws);
3871 if (win > src->max_win)
3875 ack = ntohl(th->th_ack) - dst->seqdiff;
3877 /* Modulate sequence numbers */
3878 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3880 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3883 end = seq + pd->p_len;
3884 if (th->th_flags & TH_SYN)
3886 if (th->th_flags & TH_FIN)
3890 if ((th->th_flags & TH_ACK) == 0) {
3891 /* Let it pass through the ack skew check */
3893 } else if ((ack == 0 &&
3894 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3895 /* broken tcp stacks do not set ack */
3896 (dst->state < TCPS_SYN_SENT)) {
3898 * Many stacks (ours included) will set the ACK number in an
3899 * FIN|ACK if the SYN times out -- no sequence to ACK.
3905 /* Ease sequencing restrictions on no data packets */
3910 ackskew = dst->seqlo - ack;
3914 * Need to demodulate the sequence numbers in any TCP SACK options
3915 * (Selective ACK). We could optionally validate the SACK values
3916 * against the current ACK window, either forwards or backwards, but
3917 * I'm not confident that SACK has been implemented properly
3918 * everywhere. It wouldn't surprise me if several stacks accidently
3919 * SACK too far backwards of previously ACKed data. There really aren't
3920 * any security implications of bad SACKing unless the target stack
3921 * doesn't validate the option length correctly. Someone trying to
3922 * spoof into a TCP connection won't bother blindly sending SACK
3925 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3926 if (pf_modulate_sack(m, off, pd, th, dst))
3931 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
3932 if (SEQ_GEQ(src->seqhi, end) &&
3933 /* Last octet inside other's window space */
3934 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3935 /* Retrans: not more than one window back */
3936 (ackskew >= -MAXACKWINDOW) &&
3937 /* Acking not more than one reassembled fragment backwards */
3938 (ackskew <= (MAXACKWINDOW << sws)) &&
3939 /* Acking not more than one window forward */
3940 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3941 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3942 (pd->flags & PFDESC_IP_REAS) == 0)) {
3943 /* Require an exact/+1 sequence match on resets when possible */
3945 if (dst->scrub || src->scrub) {
3946 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3947 *state, src, dst, copyback))
3951 /* update max window */
3952 if (src->max_win < win)
3954 /* synchronize sequencing */
3955 if (SEQ_GT(end, src->seqlo))
3957 /* slide the window of what the other end can send */
3958 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3959 dst->seqhi = ack + MAX((win << sws), 1);
3963 if (th->th_flags & TH_SYN)
3964 if (src->state < TCPS_SYN_SENT)
3965 src->state = TCPS_SYN_SENT;
3966 if (th->th_flags & TH_FIN)
3967 if (src->state < TCPS_CLOSING)
3968 src->state = TCPS_CLOSING;
3969 if (th->th_flags & TH_ACK) {
3970 if (dst->state == TCPS_SYN_SENT) {
3971 dst->state = TCPS_ESTABLISHED;
3972 if (src->state == TCPS_ESTABLISHED &&
3973 (*state)->src_node != NULL &&
3974 pf_src_connlimit(state)) {
3975 REASON_SET(reason, PFRES_SRCLIMIT);
3978 } else if (dst->state == TCPS_CLOSING)
3979 dst->state = TCPS_FIN_WAIT_2;
3981 if (th->th_flags & TH_RST)
3982 src->state = dst->state = TCPS_TIME_WAIT;
3984 /* update expire time */
3985 (*state)->expire = time_uptime;
3986 if (src->state >= TCPS_FIN_WAIT_2 &&
3987 dst->state >= TCPS_FIN_WAIT_2)
3988 (*state)->timeout = PFTM_TCP_CLOSED;
3989 else if (src->state >= TCPS_CLOSING &&
3990 dst->state >= TCPS_CLOSING)
3991 (*state)->timeout = PFTM_TCP_FIN_WAIT;
3992 else if (src->state < TCPS_ESTABLISHED ||
3993 dst->state < TCPS_ESTABLISHED)
3994 (*state)->timeout = PFTM_TCP_OPENING;
3995 else if (src->state >= TCPS_CLOSING ||
3996 dst->state >= TCPS_CLOSING)
3997 (*state)->timeout = PFTM_TCP_CLOSING;
3999 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4001 /* Fall through to PASS packet */
4003 } else if ((dst->state < TCPS_SYN_SENT ||
4004 dst->state >= TCPS_FIN_WAIT_2 ||
4005 src->state >= TCPS_FIN_WAIT_2) &&
4006 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4007 /* Within a window forward of the originating packet */
4008 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4009 /* Within a window backward of the originating packet */
4012 * This currently handles three situations:
4013 * 1) Stupid stacks will shotgun SYNs before their peer
4015 * 2) When PF catches an already established stream (the
4016 * firewall rebooted, the state table was flushed, routes
4018 * 3) Packets get funky immediately after the connection
4019 * closes (this should catch Solaris spurious ACK|FINs
4020 * that web servers like to spew after a close)
4022 * This must be a little more careful than the above code
4023 * since packet floods will also be caught here. We don't
4024 * update the TTL here to mitigate the damage of a packet
4025 * flood and so the same code can handle awkward establishment
4026 * and a loosened connection close.
4027 * In the establishment case, a correct peer response will
4028 * validate the connection, go through the normal state code
4029 * and keep updating the state TTL.
4032 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4033 printf("pf: loose state match: ");
4034 pf_print_state(*state);
4035 pf_print_flags(th->th_flags);
4036 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4037 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4038 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4039 (unsigned long long)(*state)->packets[1],
4040 pd->dir == PF_IN ? "in" : "out",
4041 pd->dir == (*state)->direction ? "fwd" : "rev");
4044 if (dst->scrub || src->scrub) {
4045 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4046 *state, src, dst, copyback))
4050 /* update max window */
4051 if (src->max_win < win)
4053 /* synchronize sequencing */
4054 if (SEQ_GT(end, src->seqlo))
4056 /* slide the window of what the other end can send */
4057 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4058 dst->seqhi = ack + MAX((win << sws), 1);
4061 * Cannot set dst->seqhi here since this could be a shotgunned
4062 * SYN and not an already established connection.
4065 if (th->th_flags & TH_FIN)
4066 if (src->state < TCPS_CLOSING)
4067 src->state = TCPS_CLOSING;
4068 if (th->th_flags & TH_RST)
4069 src->state = dst->state = TCPS_TIME_WAIT;
4071 /* Fall through to PASS packet */
4074 if ((*state)->dst.state == TCPS_SYN_SENT &&
4075 (*state)->src.state == TCPS_SYN_SENT) {
4076 /* Send RST for state mismatches during handshake */
4077 if (!(th->th_flags & TH_RST))
4078 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4079 pd->dst, pd->src, th->th_dport,
4080 th->th_sport, ntohl(th->th_ack), 0,
4082 (*state)->rule.ptr->return_ttl, 1, 0,
4087 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4088 printf("pf: BAD state: ");
4089 pf_print_state(*state);
4090 pf_print_flags(th->th_flags);
4091 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4092 "pkts=%llu:%llu dir=%s,%s\n",
4093 seq, orig_seq, ack, pd->p_len, ackskew,
4094 (unsigned long long)(*state)->packets[0],
4095 (unsigned long long)(*state)->packets[1],
4096 pd->dir == PF_IN ? "in" : "out",
4097 pd->dir == (*state)->direction ? "fwd" : "rev");
4098 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4099 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4100 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4102 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4103 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4104 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4105 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4107 REASON_SET(reason, PFRES_BADSTATE);
4115 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4116 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4118 struct tcphdr *th = pd->hdr.tcp;
4120 if (th->th_flags & TH_SYN)
4121 if (src->state < TCPS_SYN_SENT)
4122 src->state = TCPS_SYN_SENT;
4123 if (th->th_flags & TH_FIN)
4124 if (src->state < TCPS_CLOSING)
4125 src->state = TCPS_CLOSING;
4126 if (th->th_flags & TH_ACK) {
4127 if (dst->state == TCPS_SYN_SENT) {
4128 dst->state = TCPS_ESTABLISHED;
4129 if (src->state == TCPS_ESTABLISHED &&
4130 (*state)->src_node != NULL &&
4131 pf_src_connlimit(state)) {
4132 REASON_SET(reason, PFRES_SRCLIMIT);
4135 } else if (dst->state == TCPS_CLOSING) {
4136 dst->state = TCPS_FIN_WAIT_2;
4137 } else if (src->state == TCPS_SYN_SENT &&
4138 dst->state < TCPS_SYN_SENT) {
4140 * Handle a special sloppy case where we only see one
4141 * half of the connection. If there is a ACK after
4142 * the initial SYN without ever seeing a packet from
4143 * the destination, set the connection to established.
4145 dst->state = src->state = TCPS_ESTABLISHED;
4146 if ((*state)->src_node != NULL &&
4147 pf_src_connlimit(state)) {
4148 REASON_SET(reason, PFRES_SRCLIMIT);
4151 } else if (src->state == TCPS_CLOSING &&
4152 dst->state == TCPS_ESTABLISHED &&
4155 * Handle the closing of half connections where we
4156 * don't see the full bidirectional FIN/ACK+ACK
4159 dst->state = TCPS_CLOSING;
4162 if (th->th_flags & TH_RST)
4163 src->state = dst->state = TCPS_TIME_WAIT;
4165 /* update expire time */
4166 (*state)->expire = time_uptime;
4167 if (src->state >= TCPS_FIN_WAIT_2 &&
4168 dst->state >= TCPS_FIN_WAIT_2)
4169 (*state)->timeout = PFTM_TCP_CLOSED;
4170 else if (src->state >= TCPS_CLOSING &&
4171 dst->state >= TCPS_CLOSING)
4172 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4173 else if (src->state < TCPS_ESTABLISHED ||
4174 dst->state < TCPS_ESTABLISHED)
4175 (*state)->timeout = PFTM_TCP_OPENING;
4176 else if (src->state >= TCPS_CLOSING ||
4177 dst->state >= TCPS_CLOSING)
4178 (*state)->timeout = PFTM_TCP_CLOSING;
4180 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4186 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4187 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4190 struct pf_state_key_cmp key;
4191 struct tcphdr *th = pd->hdr.tcp;
4193 struct pf_state_peer *src, *dst;
4194 struct pf_state_key *sk;
4196 bzero(&key, sizeof(key));
4198 key.proto = IPPROTO_TCP;
4199 if (direction == PF_IN) { /* wire side, straight */
4200 PF_ACPY(&key.addr[0], pd->src, key.af);
4201 PF_ACPY(&key.addr[1], pd->dst, key.af);
4202 key.port[0] = th->th_sport;
4203 key.port[1] = th->th_dport;
4204 } else { /* stack side, reverse */
4205 PF_ACPY(&key.addr[1], pd->src, key.af);
4206 PF_ACPY(&key.addr[0], pd->dst, key.af);
4207 key.port[1] = th->th_sport;
4208 key.port[0] = th->th_dport;
4211 STATE_LOOKUP(kif, &key, direction, *state, pd);
4213 if (direction == (*state)->direction) {
4214 src = &(*state)->src;
4215 dst = &(*state)->dst;
4217 src = &(*state)->dst;
4218 dst = &(*state)->src;
4221 sk = (*state)->key[pd->didx];
4223 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4224 if (direction != (*state)->direction) {
4225 REASON_SET(reason, PFRES_SYNPROXY);
4226 return (PF_SYNPROXY_DROP);
4228 if (th->th_flags & TH_SYN) {
4229 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4230 REASON_SET(reason, PFRES_SYNPROXY);
4233 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4234 pd->src, th->th_dport, th->th_sport,
4235 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4236 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4237 REASON_SET(reason, PFRES_SYNPROXY);
4238 return (PF_SYNPROXY_DROP);
4239 } else if (!(th->th_flags & TH_ACK) ||
4240 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4241 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4242 REASON_SET(reason, PFRES_SYNPROXY);
4244 } else if ((*state)->src_node != NULL &&
4245 pf_src_connlimit(state)) {
4246 REASON_SET(reason, PFRES_SRCLIMIT);
4249 (*state)->src.state = PF_TCPS_PROXY_DST;
4251 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4252 if (direction == (*state)->direction) {
4253 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4254 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4255 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4256 REASON_SET(reason, PFRES_SYNPROXY);
4259 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4260 if ((*state)->dst.seqhi == 1)
4261 (*state)->dst.seqhi = htonl(arc4random());
4262 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4263 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4264 sk->port[pd->sidx], sk->port[pd->didx],
4265 (*state)->dst.seqhi, 0, TH_SYN, 0,
4266 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4267 REASON_SET(reason, PFRES_SYNPROXY);
4268 return (PF_SYNPROXY_DROP);
4269 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4271 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4272 REASON_SET(reason, PFRES_SYNPROXY);
4275 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4276 (*state)->dst.seqlo = ntohl(th->th_seq);
4277 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4278 pd->src, th->th_dport, th->th_sport,
4279 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4280 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4281 (*state)->tag, NULL);
4282 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4283 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4284 sk->port[pd->sidx], sk->port[pd->didx],
4285 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4286 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4287 (*state)->src.seqdiff = (*state)->dst.seqhi -
4288 (*state)->src.seqlo;
4289 (*state)->dst.seqdiff = (*state)->src.seqhi -
4290 (*state)->dst.seqlo;
4291 (*state)->src.seqhi = (*state)->src.seqlo +
4292 (*state)->dst.max_win;
4293 (*state)->dst.seqhi = (*state)->dst.seqlo +
4294 (*state)->src.max_win;
4295 (*state)->src.wscale = (*state)->dst.wscale = 0;
4296 (*state)->src.state = (*state)->dst.state =
4298 REASON_SET(reason, PFRES_SYNPROXY);
4299 return (PF_SYNPROXY_DROP);
4303 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4304 dst->state >= TCPS_FIN_WAIT_2 &&
4305 src->state >= TCPS_FIN_WAIT_2) {
4306 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4307 printf("pf: state reuse ");
4308 pf_print_state(*state);
4309 pf_print_flags(th->th_flags);
4312 /* XXX make sure it's the same direction ?? */
4313 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4314 pf_unlink_state(*state, PF_ENTER_LOCKED);
4319 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4320 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4323 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4324 ©back) == PF_DROP)
4328 /* translate source/destination address, if necessary */
4329 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4330 struct pf_state_key *nk = (*state)->key[pd->didx];
4332 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4333 nk->port[pd->sidx] != th->th_sport)
4334 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4335 &th->th_sum, &nk->addr[pd->sidx],
4336 nk->port[pd->sidx], 0, pd->af);
4338 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4339 nk->port[pd->didx] != th->th_dport)
4340 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4341 &th->th_sum, &nk->addr[pd->didx],
4342 nk->port[pd->didx], 0, pd->af);
4346 /* Copyback sequence modulation or stateful scrub changes if needed */
4348 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4354 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4355 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4357 struct pf_state_peer *src, *dst;
4358 struct pf_state_key_cmp key;
4359 struct udphdr *uh = pd->hdr.udp;
4361 bzero(&key, sizeof(key));
4363 key.proto = IPPROTO_UDP;
4364 if (direction == PF_IN) { /* wire side, straight */
4365 PF_ACPY(&key.addr[0], pd->src, key.af);
4366 PF_ACPY(&key.addr[1], pd->dst, key.af);
4367 key.port[0] = uh->uh_sport;
4368 key.port[1] = uh->uh_dport;
4369 } else { /* stack side, reverse */
4370 PF_ACPY(&key.addr[1], pd->src, key.af);
4371 PF_ACPY(&key.addr[0], pd->dst, key.af);
4372 key.port[1] = uh->uh_sport;
4373 key.port[0] = uh->uh_dport;
4376 STATE_LOOKUP(kif, &key, direction, *state, pd);
4378 if (direction == (*state)->direction) {
4379 src = &(*state)->src;
4380 dst = &(*state)->dst;
4382 src = &(*state)->dst;
4383 dst = &(*state)->src;
4387 if (src->state < PFUDPS_SINGLE)
4388 src->state = PFUDPS_SINGLE;
4389 if (dst->state == PFUDPS_SINGLE)
4390 dst->state = PFUDPS_MULTIPLE;
4392 /* update expire time */
4393 (*state)->expire = time_uptime;
4394 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4395 (*state)->timeout = PFTM_UDP_MULTIPLE;
4397 (*state)->timeout = PFTM_UDP_SINGLE;
4399 /* translate source/destination address, if necessary */
4400 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4401 struct pf_state_key *nk = (*state)->key[pd->didx];
4403 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4404 nk->port[pd->sidx] != uh->uh_sport)
4405 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4406 &uh->uh_sum, &nk->addr[pd->sidx],
4407 nk->port[pd->sidx], 1, pd->af);
4409 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4410 nk->port[pd->didx] != uh->uh_dport)
4411 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4412 &uh->uh_sum, &nk->addr[pd->didx],
4413 nk->port[pd->didx], 1, pd->af);
4414 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4421 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4422 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4424 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4425 u_int16_t icmpid = 0, *icmpsum;
4428 struct pf_state_key_cmp key;
4430 bzero(&key, sizeof(key));
4431 switch (pd->proto) {
4434 icmptype = pd->hdr.icmp->icmp_type;
4435 icmpid = pd->hdr.icmp->icmp_id;
4436 icmpsum = &pd->hdr.icmp->icmp_cksum;
4438 if (icmptype == ICMP_UNREACH ||
4439 icmptype == ICMP_SOURCEQUENCH ||
4440 icmptype == ICMP_REDIRECT ||
4441 icmptype == ICMP_TIMXCEED ||
4442 icmptype == ICMP_PARAMPROB)
4447 case IPPROTO_ICMPV6:
4448 icmptype = pd->hdr.icmp6->icmp6_type;
4449 icmpid = pd->hdr.icmp6->icmp6_id;
4450 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4452 if (icmptype == ICMP6_DST_UNREACH ||
4453 icmptype == ICMP6_PACKET_TOO_BIG ||
4454 icmptype == ICMP6_TIME_EXCEEDED ||
4455 icmptype == ICMP6_PARAM_PROB)
4464 * ICMP query/reply message not related to a TCP/UDP packet.
4465 * Search for an ICMP state.
4468 key.proto = pd->proto;
4469 key.port[0] = key.port[1] = icmpid;
4470 if (direction == PF_IN) { /* wire side, straight */
4471 PF_ACPY(&key.addr[0], pd->src, key.af);
4472 PF_ACPY(&key.addr[1], pd->dst, key.af);
4473 } else { /* stack side, reverse */
4474 PF_ACPY(&key.addr[1], pd->src, key.af);
4475 PF_ACPY(&key.addr[0], pd->dst, key.af);
4478 STATE_LOOKUP(kif, &key, direction, *state, pd);
4480 (*state)->expire = time_uptime;
4481 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4483 /* translate source/destination address, if necessary */
4484 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4485 struct pf_state_key *nk = (*state)->key[pd->didx];
4490 if (PF_ANEQ(pd->src,
4491 &nk->addr[pd->sidx], AF_INET))
4492 pf_change_a(&saddr->v4.s_addr,
4494 nk->addr[pd->sidx].v4.s_addr, 0);
4496 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4498 pf_change_a(&daddr->v4.s_addr,
4500 nk->addr[pd->didx].v4.s_addr, 0);
4503 pd->hdr.icmp->icmp_id) {
4504 pd->hdr.icmp->icmp_cksum =
4506 pd->hdr.icmp->icmp_cksum, icmpid,
4507 nk->port[pd->sidx], 0);
4508 pd->hdr.icmp->icmp_id =
4512 m_copyback(m, off, ICMP_MINLEN,
4513 (caddr_t )pd->hdr.icmp);
4518 if (PF_ANEQ(pd->src,
4519 &nk->addr[pd->sidx], AF_INET6))
4521 &pd->hdr.icmp6->icmp6_cksum,
4522 &nk->addr[pd->sidx], 0);
4524 if (PF_ANEQ(pd->dst,
4525 &nk->addr[pd->didx], AF_INET6))
4527 &pd->hdr.icmp6->icmp6_cksum,
4528 &nk->addr[pd->didx], 0);
4530 m_copyback(m, off, sizeof(struct icmp6_hdr),
4531 (caddr_t )pd->hdr.icmp6);
4540 * ICMP error message in response to a TCP/UDP packet.
4541 * Extract the inner TCP/UDP header and search for that state.
4544 struct pf_pdesc pd2;
4545 bzero(&pd2, sizeof pd2);
4550 struct ip6_hdr h2_6;
4557 /* Payload packet is from the opposite direction. */
4558 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4559 pd2.didx = (direction == PF_IN) ? 0 : 1;
4563 /* offset of h2 in mbuf chain */
4564 ipoff2 = off + ICMP_MINLEN;
4566 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4567 NULL, reason, pd2.af)) {
4568 DPFPRINTF(PF_DEBUG_MISC,
4569 ("pf: ICMP error message too short "
4574 * ICMP error messages don't refer to non-first
4577 if (h2.ip_off & htons(IP_OFFMASK)) {
4578 REASON_SET(reason, PFRES_FRAG);
4582 /* offset of protocol header that follows h2 */
4583 off2 = ipoff2 + (h2.ip_hl << 2);
4585 pd2.proto = h2.ip_p;
4586 pd2.src = (struct pf_addr *)&h2.ip_src;
4587 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4588 pd2.ip_sum = &h2.ip_sum;
4593 ipoff2 = off + sizeof(struct icmp6_hdr);
4595 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4596 NULL, reason, pd2.af)) {
4597 DPFPRINTF(PF_DEBUG_MISC,
4598 ("pf: ICMP error message too short "
4602 pd2.proto = h2_6.ip6_nxt;
4603 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4604 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4606 off2 = ipoff2 + sizeof(h2_6);
4608 switch (pd2.proto) {
4609 case IPPROTO_FRAGMENT:
4611 * ICMPv6 error messages for
4612 * non-first fragments
4614 REASON_SET(reason, PFRES_FRAG);
4617 case IPPROTO_HOPOPTS:
4618 case IPPROTO_ROUTING:
4619 case IPPROTO_DSTOPTS: {
4620 /* get next header and header length */
4621 struct ip6_ext opt6;
4623 if (!pf_pull_hdr(m, off2, &opt6,
4624 sizeof(opt6), NULL, reason,
4626 DPFPRINTF(PF_DEBUG_MISC,
4627 ("pf: ICMPv6 short opt\n"));
4630 if (pd2.proto == IPPROTO_AH)
4631 off2 += (opt6.ip6e_len + 2) * 4;
4633 off2 += (opt6.ip6e_len + 1) * 8;
4634 pd2.proto = opt6.ip6e_nxt;
4635 /* goto the next header */
4642 } while (!terminal);
4647 switch (pd2.proto) {
4651 struct pf_state_peer *src, *dst;
4656 * Only the first 8 bytes of the TCP header can be
4657 * expected. Don't access any TCP header fields after
4658 * th_seq, an ackskew test is not possible.
4660 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4662 DPFPRINTF(PF_DEBUG_MISC,
4663 ("pf: ICMP error message too short "
4669 key.proto = IPPROTO_TCP;
4670 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4671 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4672 key.port[pd2.sidx] = th.th_sport;
4673 key.port[pd2.didx] = th.th_dport;
4675 STATE_LOOKUP(kif, &key, direction, *state, pd);
4677 if (direction == (*state)->direction) {
4678 src = &(*state)->dst;
4679 dst = &(*state)->src;
4681 src = &(*state)->src;
4682 dst = &(*state)->dst;
4685 if (src->wscale && dst->wscale)
4686 dws = dst->wscale & PF_WSCALE_MASK;
4690 /* Demodulate sequence number */
4691 seq = ntohl(th.th_seq) - src->seqdiff;
4693 pf_change_a(&th.th_seq, icmpsum,
4698 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4699 (!SEQ_GEQ(src->seqhi, seq) ||
4700 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4701 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4702 printf("pf: BAD ICMP %d:%d ",
4703 icmptype, pd->hdr.icmp->icmp_code);
4704 pf_print_host(pd->src, 0, pd->af);
4706 pf_print_host(pd->dst, 0, pd->af);
4708 pf_print_state(*state);
4709 printf(" seq=%u\n", seq);
4711 REASON_SET(reason, PFRES_BADSTATE);
4714 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4715 printf("pf: OK ICMP %d:%d ",
4716 icmptype, pd->hdr.icmp->icmp_code);
4717 pf_print_host(pd->src, 0, pd->af);
4719 pf_print_host(pd->dst, 0, pd->af);
4721 pf_print_state(*state);
4722 printf(" seq=%u\n", seq);
4726 /* translate source/destination address, if necessary */
4727 if ((*state)->key[PF_SK_WIRE] !=
4728 (*state)->key[PF_SK_STACK]) {
4729 struct pf_state_key *nk =
4730 (*state)->key[pd->didx];
4732 if (PF_ANEQ(pd2.src,
4733 &nk->addr[pd2.sidx], pd2.af) ||
4734 nk->port[pd2.sidx] != th.th_sport)
4735 pf_change_icmp(pd2.src, &th.th_sport,
4736 daddr, &nk->addr[pd2.sidx],
4737 nk->port[pd2.sidx], NULL,
4738 pd2.ip_sum, icmpsum,
4739 pd->ip_sum, 0, pd2.af);
4741 if (PF_ANEQ(pd2.dst,
4742 &nk->addr[pd2.didx], pd2.af) ||
4743 nk->port[pd2.didx] != th.th_dport)
4744 pf_change_icmp(pd2.dst, &th.th_dport,
4745 NULL, /* XXX Inbound NAT? */
4746 &nk->addr[pd2.didx],
4747 nk->port[pd2.didx], NULL,
4748 pd2.ip_sum, icmpsum,
4749 pd->ip_sum, 0, pd2.af);
4757 m_copyback(m, off, ICMP_MINLEN,
4758 (caddr_t )pd->hdr.icmp);
4759 m_copyback(m, ipoff2, sizeof(h2),
4766 sizeof(struct icmp6_hdr),
4767 (caddr_t )pd->hdr.icmp6);
4768 m_copyback(m, ipoff2, sizeof(h2_6),
4773 m_copyback(m, off2, 8, (caddr_t)&th);
4782 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4783 NULL, reason, pd2.af)) {
4784 DPFPRINTF(PF_DEBUG_MISC,
4785 ("pf: ICMP error message too short "
4791 key.proto = IPPROTO_UDP;
4792 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4793 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4794 key.port[pd2.sidx] = uh.uh_sport;
4795 key.port[pd2.didx] = uh.uh_dport;
4797 STATE_LOOKUP(kif, &key, direction, *state, pd);
4799 /* translate source/destination address, if necessary */
4800 if ((*state)->key[PF_SK_WIRE] !=
4801 (*state)->key[PF_SK_STACK]) {
4802 struct pf_state_key *nk =
4803 (*state)->key[pd->didx];
4805 if (PF_ANEQ(pd2.src,
4806 &nk->addr[pd2.sidx], pd2.af) ||
4807 nk->port[pd2.sidx] != uh.uh_sport)
4808 pf_change_icmp(pd2.src, &uh.uh_sport,
4809 daddr, &nk->addr[pd2.sidx],
4810 nk->port[pd2.sidx], &uh.uh_sum,
4811 pd2.ip_sum, icmpsum,
4812 pd->ip_sum, 1, pd2.af);
4814 if (PF_ANEQ(pd2.dst,
4815 &nk->addr[pd2.didx], pd2.af) ||
4816 nk->port[pd2.didx] != uh.uh_dport)
4817 pf_change_icmp(pd2.dst, &uh.uh_dport,
4818 NULL, /* XXX Inbound NAT? */
4819 &nk->addr[pd2.didx],
4820 nk->port[pd2.didx], &uh.uh_sum,
4821 pd2.ip_sum, icmpsum,
4822 pd->ip_sum, 1, pd2.af);
4827 m_copyback(m, off, ICMP_MINLEN,
4828 (caddr_t )pd->hdr.icmp);
4829 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4835 sizeof(struct icmp6_hdr),
4836 (caddr_t )pd->hdr.icmp6);
4837 m_copyback(m, ipoff2, sizeof(h2_6),
4842 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4848 case IPPROTO_ICMP: {
4851 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4852 NULL, reason, pd2.af)) {
4853 DPFPRINTF(PF_DEBUG_MISC,
4854 ("pf: ICMP error message too short i"
4860 key.proto = IPPROTO_ICMP;
4861 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4862 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4863 key.port[0] = key.port[1] = iih.icmp_id;
4865 STATE_LOOKUP(kif, &key, direction, *state, pd);
4867 /* translate source/destination address, if necessary */
4868 if ((*state)->key[PF_SK_WIRE] !=
4869 (*state)->key[PF_SK_STACK]) {
4870 struct pf_state_key *nk =
4871 (*state)->key[pd->didx];
4873 if (PF_ANEQ(pd2.src,
4874 &nk->addr[pd2.sidx], pd2.af) ||
4875 nk->port[pd2.sidx] != iih.icmp_id)
4876 pf_change_icmp(pd2.src, &iih.icmp_id,
4877 daddr, &nk->addr[pd2.sidx],
4878 nk->port[pd2.sidx], NULL,
4879 pd2.ip_sum, icmpsum,
4880 pd->ip_sum, 0, AF_INET);
4882 if (PF_ANEQ(pd2.dst,
4883 &nk->addr[pd2.didx], pd2.af) ||
4884 nk->port[pd2.didx] != iih.icmp_id)
4885 pf_change_icmp(pd2.dst, &iih.icmp_id,
4886 NULL, /* XXX Inbound NAT? */
4887 &nk->addr[pd2.didx],
4888 nk->port[pd2.didx], NULL,
4889 pd2.ip_sum, icmpsum,
4890 pd->ip_sum, 0, AF_INET);
4892 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4893 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4894 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4901 case IPPROTO_ICMPV6: {
4902 struct icmp6_hdr iih;
4904 if (!pf_pull_hdr(m, off2, &iih,
4905 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4906 DPFPRINTF(PF_DEBUG_MISC,
4907 ("pf: ICMP error message too short "
4913 key.proto = IPPROTO_ICMPV6;
4914 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4915 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4916 key.port[0] = key.port[1] = iih.icmp6_id;
4918 STATE_LOOKUP(kif, &key, direction, *state, pd);
4920 /* translate source/destination address, if necessary */
4921 if ((*state)->key[PF_SK_WIRE] !=
4922 (*state)->key[PF_SK_STACK]) {
4923 struct pf_state_key *nk =
4924 (*state)->key[pd->didx];
4926 if (PF_ANEQ(pd2.src,
4927 &nk->addr[pd2.sidx], pd2.af) ||
4928 nk->port[pd2.sidx] != iih.icmp6_id)
4929 pf_change_icmp(pd2.src, &iih.icmp6_id,
4930 daddr, &nk->addr[pd2.sidx],
4931 nk->port[pd2.sidx], NULL,
4932 pd2.ip_sum, icmpsum,
4933 pd->ip_sum, 0, AF_INET6);
4935 if (PF_ANEQ(pd2.dst,
4936 &nk->addr[pd2.didx], pd2.af) ||
4937 nk->port[pd2.didx] != iih.icmp6_id)
4938 pf_change_icmp(pd2.dst, &iih.icmp6_id,
4939 NULL, /* XXX Inbound NAT? */
4940 &nk->addr[pd2.didx],
4941 nk->port[pd2.didx], NULL,
4942 pd2.ip_sum, icmpsum,
4943 pd->ip_sum, 0, AF_INET6);
4945 m_copyback(m, off, sizeof(struct icmp6_hdr),
4946 (caddr_t)pd->hdr.icmp6);
4947 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4948 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4957 key.proto = pd2.proto;
4958 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4959 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4960 key.port[0] = key.port[1] = 0;
4962 STATE_LOOKUP(kif, &key, direction, *state, pd);
4964 /* translate source/destination address, if necessary */
4965 if ((*state)->key[PF_SK_WIRE] !=
4966 (*state)->key[PF_SK_STACK]) {
4967 struct pf_state_key *nk =
4968 (*state)->key[pd->didx];
4970 if (PF_ANEQ(pd2.src,
4971 &nk->addr[pd2.sidx], pd2.af))
4972 pf_change_icmp(pd2.src, NULL, daddr,
4973 &nk->addr[pd2.sidx], 0, NULL,
4974 pd2.ip_sum, icmpsum,
4975 pd->ip_sum, 0, pd2.af);
4977 if (PF_ANEQ(pd2.dst,
4978 &nk->addr[pd2.didx], pd2.af))
4979 pf_change_icmp(pd2.src, NULL,
4980 NULL, /* XXX Inbound NAT? */
4981 &nk->addr[pd2.didx], 0, NULL,
4982 pd2.ip_sum, icmpsum,
4983 pd->ip_sum, 0, pd2.af);
4988 m_copyback(m, off, ICMP_MINLEN,
4989 (caddr_t)pd->hdr.icmp);
4990 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4996 sizeof(struct icmp6_hdr),
4997 (caddr_t )pd->hdr.icmp6);
4998 m_copyback(m, ipoff2, sizeof(h2_6),
5012 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5013 struct mbuf *m, struct pf_pdesc *pd)
5015 struct pf_state_peer *src, *dst;
5016 struct pf_state_key_cmp key;
5018 bzero(&key, sizeof(key));
5020 key.proto = pd->proto;
5021 if (direction == PF_IN) {
5022 PF_ACPY(&key.addr[0], pd->src, key.af);
5023 PF_ACPY(&key.addr[1], pd->dst, key.af);
5024 key.port[0] = key.port[1] = 0;
5026 PF_ACPY(&key.addr[1], pd->src, key.af);
5027 PF_ACPY(&key.addr[0], pd->dst, key.af);
5028 key.port[1] = key.port[0] = 0;
5031 STATE_LOOKUP(kif, &key, direction, *state, pd);
5033 if (direction == (*state)->direction) {
5034 src = &(*state)->src;
5035 dst = &(*state)->dst;
5037 src = &(*state)->dst;
5038 dst = &(*state)->src;
5042 if (src->state < PFOTHERS_SINGLE)
5043 src->state = PFOTHERS_SINGLE;
5044 if (dst->state == PFOTHERS_SINGLE)
5045 dst->state = PFOTHERS_MULTIPLE;
5047 /* update expire time */
5048 (*state)->expire = time_uptime;
5049 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5050 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5052 (*state)->timeout = PFTM_OTHER_SINGLE;
5054 /* translate source/destination address, if necessary */
5055 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5056 struct pf_state_key *nk = (*state)->key[pd->didx];
5058 KASSERT(nk, ("%s: nk is null", __func__));
5059 KASSERT(pd, ("%s: pd is null", __func__));
5060 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5061 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5065 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5066 pf_change_a(&pd->src->v4.s_addr,
5068 nk->addr[pd->sidx].v4.s_addr,
5072 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5073 pf_change_a(&pd->dst->v4.s_addr,
5075 nk->addr[pd->didx].v4.s_addr,
5082 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5083 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5085 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5086 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5094 * ipoff and off are measured from the start of the mbuf chain.
5095 * h must be at "ipoff" on the mbuf chain.
5098 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5099 u_short *actionp, u_short *reasonp, sa_family_t af)
5104 struct ip *h = mtod(m, struct ip *);
5105 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5109 ACTION_SET(actionp, PF_PASS);
5111 ACTION_SET(actionp, PF_DROP);
5112 REASON_SET(reasonp, PFRES_FRAG);
5116 if (m->m_pkthdr.len < off + len ||
5117 ntohs(h->ip_len) < off + len) {
5118 ACTION_SET(actionp, PF_DROP);
5119 REASON_SET(reasonp, PFRES_SHORT);
5127 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5129 if (m->m_pkthdr.len < off + len ||
5130 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5131 (unsigned)(off + len)) {
5132 ACTION_SET(actionp, PF_DROP);
5133 REASON_SET(reasonp, PFRES_SHORT);
5140 m_copydata(m, off, len, p);
5145 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5149 struct radix_node_head *rnh;
5151 struct sockaddr_in *dst;
5155 struct sockaddr_in6 *dst6;
5156 struct route_in6 ro;
5160 struct radix_node *rn;
5166 /* XXX: stick to table 0 for now */
5167 rnh = rt_tables_get_rnh(0, af);
5168 if (rnh != NULL && rn_mpath_capable(rnh))
5171 bzero(&ro, sizeof(ro));
5174 dst = satosin(&ro.ro_dst);
5175 dst->sin_family = AF_INET;
5176 dst->sin_len = sizeof(*dst);
5177 dst->sin_addr = addr->v4;
5182 * Skip check for addresses with embedded interface scope,
5183 * as they would always match anyway.
5185 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5187 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5188 dst6->sin6_family = AF_INET6;
5189 dst6->sin6_len = sizeof(*dst6);
5190 dst6->sin6_addr = addr->v6;
5197 /* Skip checks for ipsec interfaces */
5198 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5204 in6_rtalloc_ign(&ro, 0, rtableid);
5209 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5213 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5217 if (ro.ro_rt != NULL) {
5218 /* No interface given, this is a no-route check */
5222 if (kif->pfik_ifp == NULL) {
5227 /* Perform uRPF check if passed input interface */
5229 rn = (struct radix_node *)ro.ro_rt;
5231 rt = (struct rtentry *)rn;
5234 if (kif->pfik_ifp == ifp)
5237 rn = rn_mpath_next(rn);
5239 } while (check_mpath == 1 && rn != NULL && ret == 0);
5243 if (ro.ro_rt != NULL)
5250 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5251 struct pf_state *s, struct pf_pdesc *pd)
5253 struct mbuf *m0, *m1;
5254 struct sockaddr_in dst;
5256 struct ifnet *ifp = NULL;
5257 struct pf_addr naddr;
5258 struct pf_src_node *sn = NULL;
5260 uint16_t ip_len, ip_off;
5262 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5263 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5266 if ((pd->pf_mtag == NULL &&
5267 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5268 pd->pf_mtag->routed++ > 3) {
5274 if (r->rt == PF_DUPTO) {
5275 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5281 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5289 ip = mtod(m0, struct ip *);
5291 bzero(&dst, sizeof(dst));
5292 dst.sin_family = AF_INET;
5293 dst.sin_len = sizeof(dst);
5294 dst.sin_addr = ip->ip_dst;
5296 if (r->rt == PF_FASTROUTE) {
5301 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5303 KMOD_IPSTAT_INC(ips_noroute);
5304 error = EHOSTUNREACH;
5309 counter_u64_add(rt->rt_pksent, 1);
5311 if (rt->rt_flags & RTF_GATEWAY)
5312 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5315 if (TAILQ_EMPTY(&r->rpool.list)) {
5316 DPFPRINTF(PF_DEBUG_URGENT,
5317 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5321 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5323 if (!PF_AZERO(&naddr, AF_INET))
5324 dst.sin_addr.s_addr = naddr.v4.s_addr;
5325 ifp = r->rpool.cur->kif ?
5326 r->rpool.cur->kif->pfik_ifp : NULL;
5328 if (!PF_AZERO(&s->rt_addr, AF_INET))
5329 dst.sin_addr.s_addr =
5330 s->rt_addr.v4.s_addr;
5331 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5339 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5341 else if (m0 == NULL)
5343 if (m0->m_len < sizeof(struct ip)) {
5344 DPFPRINTF(PF_DEBUG_URGENT,
5345 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5348 ip = mtod(m0, struct ip *);
5351 if (ifp->if_flags & IFF_LOOPBACK)
5352 m0->m_flags |= M_SKIP_FIREWALL;
5354 ip_len = ntohs(ip->ip_len);
5355 ip_off = ntohs(ip->ip_off);
5357 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5358 m0->m_pkthdr.csum_flags |= CSUM_IP;
5359 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5360 in_delayed_cksum(m0);
5361 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5364 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5365 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5366 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5371 * If small enough for interface, or the interface will take
5372 * care of the fragmentation for us, we can just send directly.
5374 if (ip_len <= ifp->if_mtu ||
5375 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5376 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5378 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5379 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5380 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5382 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5383 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5387 /* Balk when DF bit is set or the interface didn't support TSO. */
5388 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5390 KMOD_IPSTAT_INC(ips_cantfrag);
5391 if (r->rt != PF_DUPTO) {
5392 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5399 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5403 for (; m0; m0 = m1) {
5405 m0->m_nextpkt = NULL;
5407 m_clrprotoflags(m0);
5408 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5414 KMOD_IPSTAT_INC(ips_fragmented);
5417 if (r->rt != PF_DUPTO)
5432 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5433 struct pf_state *s, struct pf_pdesc *pd)
5436 struct sockaddr_in6 dst;
5437 struct ip6_hdr *ip6;
5438 struct ifnet *ifp = NULL;
5439 struct pf_addr naddr;
5440 struct pf_src_node *sn = NULL;
5442 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5443 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5446 if ((pd->pf_mtag == NULL &&
5447 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5448 pd->pf_mtag->routed++ > 3) {
5454 if (r->rt == PF_DUPTO) {
5455 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5461 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5469 ip6 = mtod(m0, struct ip6_hdr *);
5471 bzero(&dst, sizeof(dst));
5472 dst.sin6_family = AF_INET6;
5473 dst.sin6_len = sizeof(dst);
5474 dst.sin6_addr = ip6->ip6_dst;
5476 /* Cheat. XXX why only in the v6 case??? */
5477 if (r->rt == PF_FASTROUTE) {
5480 m0->m_flags |= M_SKIP_FIREWALL;
5481 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5486 if (TAILQ_EMPTY(&r->rpool.list)) {
5487 DPFPRINTF(PF_DEBUG_URGENT,
5488 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5492 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5494 if (!PF_AZERO(&naddr, AF_INET6))
5495 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5497 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5499 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5500 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5501 &s->rt_addr, AF_INET6);
5502 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5512 if (pf_test6(PF_FWD, ifp, &m0, NULL) != PF_PASS)
5514 else if (m0 == NULL)
5516 if (m0->m_len < sizeof(struct ip6_hdr)) {
5517 DPFPRINTF(PF_DEBUG_URGENT,
5518 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5522 ip6 = mtod(m0, struct ip6_hdr *);
5525 if (ifp->if_flags & IFF_LOOPBACK)
5526 m0->m_flags |= M_SKIP_FIREWALL;
5529 * If the packet is too large for the outgoing interface,
5530 * send back an icmp6 error.
5532 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5533 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5534 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5535 nd6_output(ifp, ifp, m0, &dst, NULL);
5537 in6_ifstat_inc(ifp, ifs6_in_toobig);
5538 if (r->rt != PF_DUPTO)
5539 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5545 if (r->rt != PF_DUPTO)
5559 * FreeBSD supports cksum offloads for the following drivers.
5560 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5561 * ti(4), txp(4), xl(4)
5563 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5564 * network driver performed cksum including pseudo header, need to verify
5567 * network driver performed cksum, needs to additional pseudo header
5568 * cksum computation with partial csum_data(i.e. lack of H/W support for
5569 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5571 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5572 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5574 * Also, set csum_data to 0xffff to force cksum validation.
5577 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5583 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5585 if (m->m_pkthdr.len < off + len)
5590 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5591 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5592 sum = m->m_pkthdr.csum_data;
5594 ip = mtod(m, struct ip *);
5595 sum = in_pseudo(ip->ip_src.s_addr,
5596 ip->ip_dst.s_addr, htonl((u_short)len +
5597 m->m_pkthdr.csum_data + IPPROTO_TCP));
5604 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5605 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5606 sum = m->m_pkthdr.csum_data;
5608 ip = mtod(m, struct ip *);
5609 sum = in_pseudo(ip->ip_src.s_addr,
5610 ip->ip_dst.s_addr, htonl((u_short)len +
5611 m->m_pkthdr.csum_data + IPPROTO_UDP));
5619 case IPPROTO_ICMPV6:
5629 if (p == IPPROTO_ICMP) {
5634 sum = in_cksum(m, len);
5638 if (m->m_len < sizeof(struct ip))
5640 sum = in4_cksum(m, p, off, len);
5645 if (m->m_len < sizeof(struct ip6_hdr))
5647 sum = in6_cksum(m, p, off, len);
5658 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5663 KMOD_UDPSTAT_INC(udps_badsum);
5669 KMOD_ICMPSTAT_INC(icps_checksum);
5674 case IPPROTO_ICMPV6:
5676 KMOD_ICMP6STAT_INC(icp6s_checksum);
5683 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5684 m->m_pkthdr.csum_flags |=
5685 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5686 m->m_pkthdr.csum_data = 0xffff;
5695 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5697 struct pfi_kif *kif;
5698 u_short action, reason = 0, log = 0;
5699 struct mbuf *m = *m0;
5700 struct ip *h = NULL;
5701 struct m_tag *ipfwtag;
5702 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5703 struct pf_state *s = NULL;
5704 struct pf_ruleset *ruleset = NULL;
5706 int off, dirndx, pqid = 0;
5710 if (!V_pf_status.running)
5713 memset(&pd, 0, sizeof(pd));
5715 kif = (struct pfi_kif *)ifp->if_pf_kif;
5718 DPFPRINTF(PF_DEBUG_URGENT,
5719 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5722 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5725 if (m->m_flags & M_SKIP_FIREWALL)
5728 pd.pf_mtag = pf_find_mtag(m);
5732 if (ip_divert_ptr != NULL &&
5733 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5734 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5735 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5736 if (pd.pf_mtag == NULL &&
5737 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5741 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5742 m_tag_delete(m, ipfwtag);
5744 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5745 m->m_flags |= M_FASTFWD_OURS;
5746 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5748 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5749 /* We do IP header normalization and packet reassembly here */
5753 m = *m0; /* pf_normalize messes with m0 */
5754 h = mtod(m, struct ip *);
5756 off = h->ip_hl << 2;
5757 if (off < (int)sizeof(struct ip)) {
5759 REASON_SET(&reason, PFRES_SHORT);
5764 pd.src = (struct pf_addr *)&h->ip_src;
5765 pd.dst = (struct pf_addr *)&h->ip_dst;
5766 pd.sport = pd.dport = NULL;
5767 pd.ip_sum = &h->ip_sum;
5768 pd.proto_sum = NULL;
5771 pd.sidx = (dir == PF_IN) ? 0 : 1;
5772 pd.didx = (dir == PF_IN) ? 1 : 0;
5775 pd.tot_len = ntohs(h->ip_len);
5777 /* handle fragments that didn't get reassembled by normalization */
5778 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5779 action = pf_test_fragment(&r, dir, kif, m, h,
5790 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5791 &action, &reason, AF_INET)) {
5792 log = action != PF_PASS;
5795 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5796 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5798 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5799 if (action == PF_DROP)
5801 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5803 if (action == PF_PASS) {
5804 if (pfsync_update_state_ptr != NULL)
5805 pfsync_update_state_ptr(s);
5809 } else if (s == NULL)
5810 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5819 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5820 &action, &reason, AF_INET)) {
5821 log = action != PF_PASS;
5824 if (uh.uh_dport == 0 ||
5825 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5826 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5828 REASON_SET(&reason, PFRES_SHORT);
5831 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5832 if (action == PF_PASS) {
5833 if (pfsync_update_state_ptr != NULL)
5834 pfsync_update_state_ptr(s);
5838 } else if (s == NULL)
5839 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5844 case IPPROTO_ICMP: {
5848 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5849 &action, &reason, AF_INET)) {
5850 log = action != PF_PASS;
5853 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5855 if (action == PF_PASS) {
5856 if (pfsync_update_state_ptr != NULL)
5857 pfsync_update_state_ptr(s);
5861 } else if (s == NULL)
5862 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5868 case IPPROTO_ICMPV6: {
5870 DPFPRINTF(PF_DEBUG_MISC,
5871 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5877 action = pf_test_state_other(&s, dir, kif, m, &pd);
5878 if (action == PF_PASS) {
5879 if (pfsync_update_state_ptr != NULL)
5880 pfsync_update_state_ptr(s);
5884 } else if (s == NULL)
5885 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5892 if (action == PF_PASS && h->ip_hl > 5 &&
5893 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5895 REASON_SET(&reason, PFRES_IPOPTIONS);
5897 DPFPRINTF(PF_DEBUG_MISC,
5898 ("pf: dropping packet with ip options\n"));
5901 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5903 REASON_SET(&reason, PFRES_MEMORY);
5905 if (r->rtableid >= 0)
5906 M_SETFIB(m, r->rtableid);
5909 if (action == PF_PASS && r->qid) {
5910 if (pd.pf_mtag == NULL &&
5911 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5913 REASON_SET(&reason, PFRES_MEMORY);
5915 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5916 pd.pf_mtag->qid = r->pqid;
5918 pd.pf_mtag->qid = r->qid;
5919 /* add hints for ecn */
5920 pd.pf_mtag->hdr = h;
5926 * connections redirected to loopback should not match sockets
5927 * bound specifically to loopback due to security implications,
5928 * see tcp_input() and in_pcblookup_listen().
5930 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5931 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5932 (s->nat_rule.ptr->action == PF_RDR ||
5933 s->nat_rule.ptr->action == PF_BINAT) &&
5934 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5935 m->m_flags |= M_SKIP_FIREWALL;
5937 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5938 !PACKET_LOOPED(&pd)) {
5940 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5941 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5942 if (ipfwtag != NULL) {
5943 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5944 ntohs(r->divert.port);
5945 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5950 m_tag_prepend(m, ipfwtag);
5951 if (m->m_flags & M_FASTFWD_OURS) {
5952 if (pd.pf_mtag == NULL &&
5953 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5955 REASON_SET(&reason, PFRES_MEMORY);
5957 DPFPRINTF(PF_DEBUG_MISC,
5958 ("pf: failed to allocate tag\n"));
5960 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5961 m->m_flags &= ~M_FASTFWD_OURS;
5963 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
5968 /* XXX: ipfw has the same behaviour! */
5970 REASON_SET(&reason, PFRES_MEMORY);
5972 DPFPRINTF(PF_DEBUG_MISC,
5973 ("pf: failed to allocate divert tag\n"));
5980 if (s != NULL && s->nat_rule.ptr != NULL &&
5981 s->nat_rule.ptr->log & PF_LOG_ALL)
5982 lr = s->nat_rule.ptr;
5985 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5989 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5990 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5992 if (action == PF_PASS || r->action == PF_DROP) {
5993 dirndx = (dir == PF_OUT);
5994 r->packets[dirndx]++;
5995 r->bytes[dirndx] += pd.tot_len;
5997 a->packets[dirndx]++;
5998 a->bytes[dirndx] += pd.tot_len;
6001 if (s->nat_rule.ptr != NULL) {
6002 s->nat_rule.ptr->packets[dirndx]++;
6003 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6005 if (s->src_node != NULL) {
6006 s->src_node->packets[dirndx]++;
6007 s->src_node->bytes[dirndx] += pd.tot_len;
6009 if (s->nat_src_node != NULL) {
6010 s->nat_src_node->packets[dirndx]++;
6011 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6013 dirndx = (dir == s->direction) ? 0 : 1;
6014 s->packets[dirndx]++;
6015 s->bytes[dirndx] += pd.tot_len;
6018 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6019 if (nr != NULL && r == &V_pf_default_rule)
6021 if (tr->src.addr.type == PF_ADDR_TABLE)
6022 pfr_update_stats(tr->src.addr.p.tbl,
6023 (s == NULL) ? pd.src :
6024 &s->key[(s->direction == PF_IN)]->
6025 addr[(s->direction == PF_OUT)],
6026 pd.af, pd.tot_len, dir == PF_OUT,
6027 r->action == PF_PASS, tr->src.neg);
6028 if (tr->dst.addr.type == PF_ADDR_TABLE)
6029 pfr_update_stats(tr->dst.addr.p.tbl,
6030 (s == NULL) ? pd.dst :
6031 &s->key[(s->direction == PF_IN)]->
6032 addr[(s->direction == PF_IN)],
6033 pd.af, pd.tot_len, dir == PF_OUT,
6034 r->action == PF_PASS, tr->dst.neg);
6038 case PF_SYNPROXY_DROP:
6049 /* pf_route() returns unlocked. */
6051 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6065 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6067 struct pfi_kif *kif;
6068 u_short action, reason = 0, log = 0;
6069 struct mbuf *m = *m0, *n = NULL;
6071 struct ip6_hdr *h = NULL;
6072 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6073 struct pf_state *s = NULL;
6074 struct pf_ruleset *ruleset = NULL;
6076 int off, terminal = 0, dirndx, rh_cnt = 0;
6081 if (dir == PF_OUT && m->m_pkthdr.rcvif && ifp != m->m_pkthdr.rcvif)
6084 if (!V_pf_status.running)
6087 memset(&pd, 0, sizeof(pd));
6088 pd.pf_mtag = pf_find_mtag(m);
6090 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6093 kif = (struct pfi_kif *)ifp->if_pf_kif;
6095 DPFPRINTF(PF_DEBUG_URGENT,
6096 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6099 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6102 if (m->m_flags & M_SKIP_FIREWALL)
6107 /* We do IP header normalization and packet reassembly here */
6108 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6112 m = *m0; /* pf_normalize messes with m0 */
6113 h = mtod(m, struct ip6_hdr *);
6117 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6118 * will do something bad, so drop the packet for now.
6120 if (htons(h->ip6_plen) == 0) {
6122 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6127 pd.src = (struct pf_addr *)&h->ip6_src;
6128 pd.dst = (struct pf_addr *)&h->ip6_dst;
6129 pd.sport = pd.dport = NULL;
6131 pd.proto_sum = NULL;
6133 pd.sidx = (dir == PF_IN) ? 0 : 1;
6134 pd.didx = (dir == PF_IN) ? 1 : 0;
6137 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6139 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6140 pd.proto = h->ip6_nxt;
6143 case IPPROTO_FRAGMENT:
6144 action = pf_test_fragment(&r, dir, kif, m, h,
6146 if (action == PF_DROP)
6147 REASON_SET(&reason, PFRES_FRAG);
6149 case IPPROTO_ROUTING: {
6150 struct ip6_rthdr rthdr;
6153 DPFPRINTF(PF_DEBUG_MISC,
6154 ("pf: IPv6 more than one rthdr\n"));
6156 REASON_SET(&reason, PFRES_IPOPTIONS);
6160 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6162 DPFPRINTF(PF_DEBUG_MISC,
6163 ("pf: IPv6 short rthdr\n"));
6165 REASON_SET(&reason, PFRES_SHORT);
6169 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6170 DPFPRINTF(PF_DEBUG_MISC,
6171 ("pf: IPv6 rthdr0\n"));
6173 REASON_SET(&reason, PFRES_IPOPTIONS);
6180 case IPPROTO_HOPOPTS:
6181 case IPPROTO_DSTOPTS: {
6182 /* get next header and header length */
6183 struct ip6_ext opt6;
6185 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6186 NULL, &reason, pd.af)) {
6187 DPFPRINTF(PF_DEBUG_MISC,
6188 ("pf: IPv6 short opt\n"));
6193 if (pd.proto == IPPROTO_AH)
6194 off += (opt6.ip6e_len + 2) * 4;
6196 off += (opt6.ip6e_len + 1) * 8;
6197 pd.proto = opt6.ip6e_nxt;
6198 /* goto the next header */
6205 } while (!terminal);
6207 /* if there's no routing header, use unmodified mbuf for checksumming */
6217 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6218 &action, &reason, AF_INET6)) {
6219 log = action != PF_PASS;
6222 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6223 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6224 if (action == PF_DROP)
6226 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6228 if (action == PF_PASS) {
6229 if (pfsync_update_state_ptr != NULL)
6230 pfsync_update_state_ptr(s);
6234 } else if (s == NULL)
6235 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6244 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6245 &action, &reason, AF_INET6)) {
6246 log = action != PF_PASS;
6249 if (uh.uh_dport == 0 ||
6250 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6251 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6253 REASON_SET(&reason, PFRES_SHORT);
6256 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6257 if (action == PF_PASS) {
6258 if (pfsync_update_state_ptr != NULL)
6259 pfsync_update_state_ptr(s);
6263 } else if (s == NULL)
6264 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6269 case IPPROTO_ICMP: {
6271 DPFPRINTF(PF_DEBUG_MISC,
6272 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6276 case IPPROTO_ICMPV6: {
6277 struct icmp6_hdr ih;
6280 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6281 &action, &reason, AF_INET6)) {
6282 log = action != PF_PASS;
6285 action = pf_test_state_icmp(&s, dir, kif,
6286 m, off, h, &pd, &reason);
6287 if (action == PF_PASS) {
6288 if (pfsync_update_state_ptr != NULL)
6289 pfsync_update_state_ptr(s);
6293 } else if (s == NULL)
6294 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6300 action = pf_test_state_other(&s, dir, kif, m, &pd);
6301 if (action == PF_PASS) {
6302 if (pfsync_update_state_ptr != NULL)
6303 pfsync_update_state_ptr(s);
6307 } else if (s == NULL)
6308 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6320 /* handle dangerous IPv6 extension headers. */
6321 if (action == PF_PASS && rh_cnt &&
6322 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6324 REASON_SET(&reason, PFRES_IPOPTIONS);
6326 DPFPRINTF(PF_DEBUG_MISC,
6327 ("pf: dropping packet with dangerous v6 headers\n"));
6330 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6332 REASON_SET(&reason, PFRES_MEMORY);
6334 if (r->rtableid >= 0)
6335 M_SETFIB(m, r->rtableid);
6338 if (action == PF_PASS && r->qid) {
6339 if (pd.pf_mtag == NULL &&
6340 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6342 REASON_SET(&reason, PFRES_MEMORY);
6344 if (pd.tos & IPTOS_LOWDELAY)
6345 pd.pf_mtag->qid = r->pqid;
6347 pd.pf_mtag->qid = r->qid;
6348 /* add hints for ecn */
6349 pd.pf_mtag->hdr = h;
6353 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6354 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6355 (s->nat_rule.ptr->action == PF_RDR ||
6356 s->nat_rule.ptr->action == PF_BINAT) &&
6357 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6358 m->m_flags |= M_SKIP_FIREWALL;
6360 /* XXX: Anybody working on it?! */
6362 printf("pf: divert(9) is not supported for IPv6\n");
6367 if (s != NULL && s->nat_rule.ptr != NULL &&
6368 s->nat_rule.ptr->log & PF_LOG_ALL)
6369 lr = s->nat_rule.ptr;
6372 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6376 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6377 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6379 if (action == PF_PASS || r->action == PF_DROP) {
6380 dirndx = (dir == PF_OUT);
6381 r->packets[dirndx]++;
6382 r->bytes[dirndx] += pd.tot_len;
6384 a->packets[dirndx]++;
6385 a->bytes[dirndx] += pd.tot_len;
6388 if (s->nat_rule.ptr != NULL) {
6389 s->nat_rule.ptr->packets[dirndx]++;
6390 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6392 if (s->src_node != NULL) {
6393 s->src_node->packets[dirndx]++;
6394 s->src_node->bytes[dirndx] += pd.tot_len;
6396 if (s->nat_src_node != NULL) {
6397 s->nat_src_node->packets[dirndx]++;
6398 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6400 dirndx = (dir == s->direction) ? 0 : 1;
6401 s->packets[dirndx]++;
6402 s->bytes[dirndx] += pd.tot_len;
6405 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6406 if (nr != NULL && r == &V_pf_default_rule)
6408 if (tr->src.addr.type == PF_ADDR_TABLE)
6409 pfr_update_stats(tr->src.addr.p.tbl,
6410 (s == NULL) ? pd.src :
6411 &s->key[(s->direction == PF_IN)]->addr[0],
6412 pd.af, pd.tot_len, dir == PF_OUT,
6413 r->action == PF_PASS, tr->src.neg);
6414 if (tr->dst.addr.type == PF_ADDR_TABLE)
6415 pfr_update_stats(tr->dst.addr.p.tbl,
6416 (s == NULL) ? pd.dst :
6417 &s->key[(s->direction == PF_IN)]->addr[1],
6418 pd.af, pd.tot_len, dir == PF_OUT,
6419 r->action == PF_PASS, tr->dst.neg);
6423 case PF_SYNPROXY_DROP:
6434 /* pf_route6() returns unlocked. */
6436 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6445 /* If reassembled packet passed, create new fragments. */
6446 if (action == PF_PASS && *m0 && fwdir == PF_FWD &&
6447 (mtag = m_tag_find(m, PF_REASSEMBLED, NULL)) != NULL)
6448 action = pf_refragment6(ifp, m0, mtag);