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 mbuf *, 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(u_long, pf_hashmask);
353 VNET_DEFINE(struct pf_srchash *, pf_srchash);
354 VNET_DEFINE(u_long, pf_srchashmask);
356 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
358 VNET_DEFINE(u_long, pf_hashsize);
359 #define V_pf_hashsize VNET(pf_hashsize)
360 SYSCTL_VNET_UINT(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
361 &VNET_NAME(pf_hashsize), 0, "Size of pf(4) states hashtable");
363 VNET_DEFINE(u_long, pf_srchashsize);
364 #define V_pf_srchashsize VNET(pf_srchashsize)
365 SYSCTL_VNET_UINT(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
366 &VNET_NAME(pf_srchashsize), 0, "Size of pf(4) source nodes hashtable");
368 VNET_DEFINE(void *, pf_swi_cookie);
370 VNET_DEFINE(uint32_t, pf_hashseed);
371 #define V_pf_hashseed VNET(pf_hashseed)
373 static __inline uint32_t
374 pf_hashkey(struct pf_state_key *sk)
378 h = jenkins_hash32((uint32_t *)sk,
379 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
382 return (h & V_pf_hashmask);
385 static __inline uint32_t
386 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
392 h = jenkins_hash32((uint32_t *)&addr->v4,
393 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
396 h = jenkins_hash32((uint32_t *)&addr->v6,
397 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
400 panic("%s: unknown address family %u", __func__, af);
403 return (h & V_pf_srchashmask);
408 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
413 dst->addr32[0] = src->addr32[0];
417 dst->addr32[0] = src->addr32[0];
418 dst->addr32[1] = src->addr32[1];
419 dst->addr32[2] = src->addr32[2];
420 dst->addr32[3] = src->addr32[3];
427 pf_init_threshold(struct pf_threshold *threshold,
428 u_int32_t limit, u_int32_t seconds)
430 threshold->limit = limit * PF_THRESHOLD_MULT;
431 threshold->seconds = seconds;
432 threshold->count = 0;
433 threshold->last = time_uptime;
437 pf_add_threshold(struct pf_threshold *threshold)
439 u_int32_t t = time_uptime, diff = t - threshold->last;
441 if (diff >= threshold->seconds)
442 threshold->count = 0;
444 threshold->count -= threshold->count * diff /
446 threshold->count += PF_THRESHOLD_MULT;
451 pf_check_threshold(struct pf_threshold *threshold)
453 return (threshold->count > threshold->limit);
457 pf_src_connlimit(struct pf_state **state)
459 struct pf_overload_entry *pfoe;
462 PF_STATE_LOCK_ASSERT(*state);
464 (*state)->src_node->conn++;
465 (*state)->src.tcp_est = 1;
466 pf_add_threshold(&(*state)->src_node->conn_rate);
468 if ((*state)->rule.ptr->max_src_conn &&
469 (*state)->rule.ptr->max_src_conn <
470 (*state)->src_node->conn) {
471 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
475 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
476 pf_check_threshold(&(*state)->src_node->conn_rate)) {
477 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
484 /* Kill this state. */
485 (*state)->timeout = PFTM_PURGE;
486 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
488 if ((*state)->rule.ptr->overload_tbl == NULL)
491 /* Schedule overloading and flushing task. */
492 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
494 return (1); /* too bad :( */
496 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
497 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
498 pfoe->rule = (*state)->rule.ptr;
499 pfoe->dir = (*state)->direction;
501 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
502 PF_OVERLOADQ_UNLOCK();
503 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
509 pf_overload_task(void *v, int pending)
511 struct pf_overload_head queue;
513 struct pf_overload_entry *pfoe, *pfoe1;
516 CURVNET_SET((struct vnet *)v);
519 queue = V_pf_overloadqueue;
520 SLIST_INIT(&V_pf_overloadqueue);
521 PF_OVERLOADQ_UNLOCK();
523 bzero(&p, sizeof(p));
524 SLIST_FOREACH(pfoe, &queue, next) {
525 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
526 if (V_pf_status.debug >= PF_DEBUG_MISC) {
527 printf("%s: blocking address ", __func__);
528 pf_print_host(&pfoe->addr, 0, pfoe->af);
532 p.pfra_af = pfoe->af;
537 p.pfra_ip4addr = pfoe->addr.v4;
543 p.pfra_ip6addr = pfoe->addr.v6;
549 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
554 * Remove those entries, that don't need flushing.
556 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
557 if (pfoe->rule->flush == 0) {
558 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
559 free(pfoe, M_PFTEMP);
562 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
564 /* If nothing to flush, return. */
565 if (SLIST_EMPTY(&queue)) {
570 for (int i = 0; i <= V_pf_hashmask; i++) {
571 struct pf_idhash *ih = &V_pf_idhash[i];
572 struct pf_state_key *sk;
576 LIST_FOREACH(s, &ih->states, entry) {
577 sk = s->key[PF_SK_WIRE];
578 SLIST_FOREACH(pfoe, &queue, next)
579 if (sk->af == pfoe->af &&
580 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
581 pfoe->rule == s->rule.ptr) &&
582 ((pfoe->dir == PF_OUT &&
583 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
584 (pfoe->dir == PF_IN &&
585 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
586 s->timeout = PFTM_PURGE;
587 s->src.state = s->dst.state = TCPS_CLOSED;
591 PF_HASHROW_UNLOCK(ih);
593 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
594 free(pfoe, M_PFTEMP);
595 if (V_pf_status.debug >= PF_DEBUG_MISC)
596 printf("%s: %u states killed", __func__, killed);
602 * Can return locked on failure, so that we can consistently
603 * allocate and insert a new one.
606 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
609 struct pf_srchash *sh;
610 struct pf_src_node *n;
612 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
614 sh = &V_pf_srchash[pf_hashsrc(src, af)];
616 LIST_FOREACH(n, &sh->nodes, entry)
617 if (n->rule.ptr == rule && n->af == af &&
618 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
619 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
621 if (n != NULL || returnlocked == 0)
622 PF_HASHROW_UNLOCK(sh);
628 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
629 struct pf_addr *src, sa_family_t af)
632 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
633 rule->rpool.opts & PF_POOL_STICKYADDR),
634 ("%s for non-tracking rule %p", __func__, rule));
637 *sn = pf_find_src_node(src, rule, af, 1);
640 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
642 PF_HASHROW_ASSERT(sh);
644 if (!rule->max_src_nodes ||
645 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
646 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
648 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
651 PF_HASHROW_UNLOCK(sh);
655 pf_init_threshold(&(*sn)->conn_rate,
656 rule->max_src_conn_rate.limit,
657 rule->max_src_conn_rate.seconds);
660 (*sn)->rule.ptr = rule;
661 PF_ACPY(&(*sn)->addr, src, af);
662 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
663 (*sn)->creation = time_uptime;
664 (*sn)->ruletype = rule->action;
665 if ((*sn)->rule.ptr != NULL)
666 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
667 PF_HASHROW_UNLOCK(sh);
668 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
670 if (rule->max_src_states &&
671 (*sn)->states >= rule->max_src_states) {
672 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
681 pf_unlink_src_node_locked(struct pf_src_node *src)
684 struct pf_srchash *sh;
686 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
687 PF_HASHROW_ASSERT(sh);
689 LIST_REMOVE(src, entry);
691 counter_u64_add(src->rule.ptr->src_nodes, -1);
692 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
696 pf_unlink_src_node(struct pf_src_node *src)
698 struct pf_srchash *sh;
700 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
702 pf_unlink_src_node_locked(src);
703 PF_HASHROW_UNLOCK(sh);
707 pf_free_src_node(struct pf_src_node *sn)
710 KASSERT(sn->states == 0, ("%s: %p has refs", __func__, sn));
711 uma_zfree(V_pf_sources_z, sn);
715 pf_free_src_nodes(struct pf_src_node_list *head)
717 struct pf_src_node *sn, *tmp;
720 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
721 pf_free_src_node(sn);
732 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
733 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
737 /* Per-vnet data storage structures initialization. */
741 struct pf_keyhash *kh;
742 struct pf_idhash *ih;
743 struct pf_srchash *sh;
746 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &V_pf_hashsize);
747 if (V_pf_hashsize == 0 || !powerof2(V_pf_hashsize))
748 V_pf_hashsize = PF_HASHSIZ;
749 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &V_pf_srchashsize);
750 if (V_pf_srchashsize == 0 || !powerof2(V_pf_srchashsize))
751 V_pf_srchashsize = PF_HASHSIZ / 4;
753 V_pf_hashseed = arc4random();
755 /* States and state keys storage. */
756 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
757 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
758 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
759 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
760 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
762 V_pf_state_key_z = uma_zcreate("pf state keys",
763 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
765 V_pf_keyhash = malloc(V_pf_hashsize * sizeof(struct pf_keyhash),
766 M_PFHASH, M_WAITOK | M_ZERO);
767 V_pf_idhash = malloc(V_pf_hashsize * sizeof(struct pf_idhash),
768 M_PFHASH, M_WAITOK | M_ZERO);
769 V_pf_hashmask = V_pf_hashsize - 1;
770 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
772 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
773 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
777 V_pf_sources_z = uma_zcreate("pf source nodes",
778 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
780 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
781 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
782 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
783 V_pf_srchash = malloc(V_pf_srchashsize * sizeof(struct pf_srchash),
784 M_PFHASH, M_WAITOK|M_ZERO);
785 V_pf_srchashmask = V_pf_srchashsize - 1;
786 for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++)
787 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
790 TAILQ_INIT(&V_pf_altqs[0]);
791 TAILQ_INIT(&V_pf_altqs[1]);
792 TAILQ_INIT(&V_pf_pabuf);
793 V_pf_altqs_active = &V_pf_altqs[0];
794 V_pf_altqs_inactive = &V_pf_altqs[1];
797 /* Send & overload+flush queues. */
798 STAILQ_INIT(&V_pf_sendqueue);
799 SLIST_INIT(&V_pf_overloadqueue);
800 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
801 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
802 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
805 /* Unlinked, but may be referenced rules. */
806 TAILQ_INIT(&V_pf_unlinked_rules);
807 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
814 uma_zdestroy(pf_mtag_z);
820 struct pf_keyhash *kh;
821 struct pf_idhash *ih;
822 struct pf_srchash *sh;
823 struct pf_send_entry *pfse, *next;
826 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
828 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
830 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
832 mtx_destroy(&kh->lock);
833 mtx_destroy(&ih->lock);
835 free(V_pf_keyhash, M_PFHASH);
836 free(V_pf_idhash, M_PFHASH);
838 for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
839 KASSERT(LIST_EMPTY(&sh->nodes),
840 ("%s: source node hash not empty", __func__));
841 mtx_destroy(&sh->lock);
843 free(V_pf_srchash, M_PFHASH);
845 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
846 m_freem(pfse->pfse_m);
847 free(pfse, M_PFTEMP);
850 mtx_destroy(&pf_sendqueue_mtx);
851 mtx_destroy(&pf_overloadqueue_mtx);
852 mtx_destroy(&pf_unlnkdrules_mtx);
854 uma_zdestroy(V_pf_sources_z);
855 uma_zdestroy(V_pf_state_z);
856 uma_zdestroy(V_pf_state_key_z);
860 pf_mtag_uminit(void *mem, int size, int how)
864 t = (struct m_tag *)mem;
865 t->m_tag_cookie = MTAG_ABI_COMPAT;
866 t->m_tag_id = PACKET_TAG_PF;
867 t->m_tag_len = sizeof(struct pf_mtag);
868 t->m_tag_free = pf_mtag_free;
874 pf_mtag_free(struct m_tag *t)
877 uma_zfree(pf_mtag_z, t);
881 pf_get_mtag(struct mbuf *m)
885 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
886 return ((struct pf_mtag *)(mtag + 1));
888 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
891 bzero(mtag + 1, sizeof(struct pf_mtag));
892 m_tag_prepend(m, mtag);
894 return ((struct pf_mtag *)(mtag + 1));
898 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
901 struct pf_keyhash *khs, *khw, *kh;
902 struct pf_state_key *sk, *cur;
903 struct pf_state *si, *olds = NULL;
906 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
907 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
908 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
911 * We need to lock hash slots of both keys. To avoid deadlock
912 * we always lock the slot with lower address first. Unlock order
915 * We also need to lock ID hash slot before dropping key
916 * locks. On success we return with ID hash slot locked.
920 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
921 PF_HASHROW_LOCK(khs);
923 khs = &V_pf_keyhash[pf_hashkey(sks)];
924 khw = &V_pf_keyhash[pf_hashkey(skw)];
926 PF_HASHROW_LOCK(khs);
927 } else if (khs < khw) {
928 PF_HASHROW_LOCK(khs);
929 PF_HASHROW_LOCK(khw);
931 PF_HASHROW_LOCK(khw);
932 PF_HASHROW_LOCK(khs);
936 #define KEYS_UNLOCK() do { \
938 PF_HASHROW_UNLOCK(khs); \
939 PF_HASHROW_UNLOCK(khw); \
941 PF_HASHROW_UNLOCK(khs); \
945 * First run: start with wire key.
952 LIST_FOREACH(cur, &kh->keys, entry)
953 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
957 /* Key exists. Check for same kif, if none, add to key. */
958 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
959 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
962 if (si->kif == s->kif &&
963 si->direction == s->direction) {
964 if (sk->proto == IPPROTO_TCP &&
965 si->src.state >= TCPS_FIN_WAIT_2 &&
966 si->dst.state >= TCPS_FIN_WAIT_2) {
968 * New state matches an old >FIN_WAIT_2
969 * state. We can't drop key hash locks,
970 * thus we can't unlink it properly.
972 * As a workaround we drop it into
973 * TCPS_CLOSED state, schedule purge
974 * ASAP and push it into the very end
975 * of the slot TAILQ, so that it won't
976 * conflict with our new state.
978 si->src.state = si->dst.state =
980 si->timeout = PFTM_PURGE;
983 if (V_pf_status.debug >= PF_DEBUG_MISC) {
984 printf("pf: %s key attach "
986 (idx == PF_SK_WIRE) ?
989 pf_print_state_parts(s,
990 (idx == PF_SK_WIRE) ?
992 (idx == PF_SK_STACK) ?
994 printf(", existing: ");
995 pf_print_state_parts(si,
996 (idx == PF_SK_WIRE) ?
998 (idx == PF_SK_STACK) ?
1002 PF_HASHROW_UNLOCK(ih);
1004 uma_zfree(V_pf_state_key_z, sk);
1005 if (idx == PF_SK_STACK)
1007 return (EEXIST); /* collision! */
1010 PF_HASHROW_UNLOCK(ih);
1012 uma_zfree(V_pf_state_key_z, sk);
1015 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1020 /* List is sorted, if-bound states before floating. */
1021 if (s->kif == V_pfi_all)
1022 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1024 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1027 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1028 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1034 * Attach done. See how should we (or should not?)
1035 * attach a second key.
1038 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1042 } else if (sks != NULL) {
1044 * Continue attaching with stack key.
1056 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1057 ("%s failure", __func__));
1064 pf_detach_state(struct pf_state *s)
1066 struct pf_state_key *sks = s->key[PF_SK_STACK];
1067 struct pf_keyhash *kh;
1070 kh = &V_pf_keyhash[pf_hashkey(sks)];
1071 PF_HASHROW_LOCK(kh);
1072 if (s->key[PF_SK_STACK] != NULL)
1073 pf_state_key_detach(s, PF_SK_STACK);
1075 * If both point to same key, then we are done.
1077 if (sks == s->key[PF_SK_WIRE]) {
1078 pf_state_key_detach(s, PF_SK_WIRE);
1079 PF_HASHROW_UNLOCK(kh);
1082 PF_HASHROW_UNLOCK(kh);
1085 if (s->key[PF_SK_WIRE] != NULL) {
1086 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1087 PF_HASHROW_LOCK(kh);
1088 if (s->key[PF_SK_WIRE] != NULL)
1089 pf_state_key_detach(s, PF_SK_WIRE);
1090 PF_HASHROW_UNLOCK(kh);
1095 pf_state_key_detach(struct pf_state *s, int idx)
1097 struct pf_state_key *sk = s->key[idx];
1099 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1101 PF_HASHROW_ASSERT(kh);
1103 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1106 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1107 LIST_REMOVE(sk, entry);
1108 uma_zfree(V_pf_state_key_z, sk);
1113 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1115 struct pf_state_key *sk = mem;
1117 bzero(sk, sizeof(struct pf_state_key_cmp));
1118 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1119 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1124 struct pf_state_key *
1125 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1126 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1128 struct pf_state_key *sk;
1130 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1134 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1135 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1136 sk->port[pd->sidx] = sport;
1137 sk->port[pd->didx] = dport;
1138 sk->proto = pd->proto;
1144 struct pf_state_key *
1145 pf_state_key_clone(struct pf_state_key *orig)
1147 struct pf_state_key *sk;
1149 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1153 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1159 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1160 struct pf_state_key *sks, struct pf_state *s)
1162 struct pf_idhash *ih;
1163 struct pf_state *cur;
1166 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1167 ("%s: sks not pristine", __func__));
1168 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1169 ("%s: skw not pristine", __func__));
1170 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1174 if (s->id == 0 && s->creatorid == 0) {
1175 /* XXX: should be atomic, but probability of collision low */
1176 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1177 V_pf_stateid[curcpu] = 1;
1178 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1179 s->id = htobe64(s->id);
1180 s->creatorid = V_pf_status.hostid;
1183 /* Returns with ID locked on success. */
1184 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1187 ih = &V_pf_idhash[PF_IDHASH(s)];
1188 PF_HASHROW_ASSERT(ih);
1189 LIST_FOREACH(cur, &ih->states, entry)
1190 if (cur->id == s->id && cur->creatorid == s->creatorid)
1194 PF_HASHROW_UNLOCK(ih);
1195 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1196 printf("pf: state ID collision: "
1197 "id: %016llx creatorid: %08x\n",
1198 (unsigned long long)be64toh(s->id),
1199 ntohl(s->creatorid));
1204 LIST_INSERT_HEAD(&ih->states, s, entry);
1205 /* One for keys, one for ID hash. */
1206 refcount_init(&s->refs, 2);
1208 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1209 if (pfsync_insert_state_ptr != NULL)
1210 pfsync_insert_state_ptr(s);
1212 /* Returns locked. */
1217 * Find state by ID: returns with locked row on success.
1220 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1222 struct pf_idhash *ih;
1225 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1227 ih = &V_pf_idhash[(be64toh(id) % (V_pf_hashmask + 1))];
1229 PF_HASHROW_LOCK(ih);
1230 LIST_FOREACH(s, &ih->states, entry)
1231 if (s->id == id && s->creatorid == creatorid)
1235 PF_HASHROW_UNLOCK(ih);
1241 * Find state by key.
1242 * Returns with ID hash slot locked on success.
1244 static struct pf_state *
1245 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1247 struct pf_keyhash *kh;
1248 struct pf_state_key *sk;
1252 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1254 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1256 PF_HASHROW_LOCK(kh);
1257 LIST_FOREACH(sk, &kh->keys, entry)
1258 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1261 PF_HASHROW_UNLOCK(kh);
1265 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1267 /* List is sorted, if-bound states before floating ones. */
1268 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1269 if (s->kif == V_pfi_all || s->kif == kif) {
1271 PF_HASHROW_UNLOCK(kh);
1272 if (s->timeout >= PFTM_MAX) {
1274 * State is either being processed by
1275 * pf_unlink_state() in an other thread, or
1276 * is scheduled for immediate expiry.
1283 PF_HASHROW_UNLOCK(kh);
1289 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1291 struct pf_keyhash *kh;
1292 struct pf_state_key *sk;
1293 struct pf_state *s, *ret = NULL;
1296 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1298 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1300 PF_HASHROW_LOCK(kh);
1301 LIST_FOREACH(sk, &kh->keys, entry)
1302 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1305 PF_HASHROW_UNLOCK(kh);
1320 panic("%s: dir %u", __func__, dir);
1323 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1325 PF_HASHROW_UNLOCK(kh);
1339 PF_HASHROW_UNLOCK(kh);
1344 /* END state table stuff */
1347 pf_send(struct pf_send_entry *pfse)
1351 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1353 swi_sched(V_pf_swi_cookie, 0);
1359 struct pf_send_head queue;
1360 struct pf_send_entry *pfse, *next;
1362 CURVNET_SET((struct vnet *)v);
1365 queue = V_pf_sendqueue;
1366 STAILQ_INIT(&V_pf_sendqueue);
1369 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1370 switch (pfse->pfse_type) {
1373 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1376 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1377 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1382 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1386 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1387 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1391 panic("%s: unknown type", __func__);
1393 free(pfse, M_PFTEMP);
1399 pf_purge_thread(void *v)
1403 CURVNET_SET((struct vnet *)v);
1407 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1409 if (V_pf_end_threads) {
1411 * To cleanse up all kifs and rules we need
1412 * two runs: first one clears reference flags,
1413 * then pf_purge_expired_states() doesn't
1414 * raise them, and then second run frees.
1417 pf_purge_unlinked_rules();
1421 * Now purge everything.
1423 pf_purge_expired_states(0, V_pf_hashmask);
1424 pf_purge_expired_fragments();
1425 pf_purge_expired_src_nodes();
1428 * Now all kifs & rules should be unreferenced,
1429 * thus should be successfully freed.
1431 pf_purge_unlinked_rules();
1435 * Announce success and exit.
1440 wakeup(pf_purge_thread);
1445 /* Process 1/interval fraction of the state table every run. */
1446 idx = pf_purge_expired_states(idx, V_pf_hashmask /
1447 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1449 /* Purge other expired types every PFTM_INTERVAL seconds. */
1452 * Order is important:
1453 * - states and src nodes reference rules
1454 * - states and rules reference kifs
1456 pf_purge_expired_fragments();
1457 pf_purge_expired_src_nodes();
1458 pf_purge_unlinked_rules();
1467 pf_state_expires(const struct pf_state *state)
1474 /* handle all PFTM_* > PFTM_MAX here */
1475 if (state->timeout == PFTM_PURGE)
1476 return (time_uptime);
1477 KASSERT(state->timeout != PFTM_UNLINKED,
1478 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1479 KASSERT((state->timeout < PFTM_MAX),
1480 ("pf_state_expires: timeout > PFTM_MAX"));
1481 timeout = state->rule.ptr->timeout[state->timeout];
1483 timeout = V_pf_default_rule.timeout[state->timeout];
1484 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1486 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1487 states = counter_u64_fetch(state->rule.ptr->states_cur);
1489 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1490 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1491 states = V_pf_status.states;
1493 if (end && states > start && start < end) {
1495 return (state->expire + timeout * (end - states) /
1498 return (time_uptime);
1500 return (state->expire + timeout);
1504 pf_purge_expired_src_nodes()
1506 struct pf_src_node_list freelist;
1507 struct pf_srchash *sh;
1508 struct pf_src_node *cur, *next;
1511 LIST_INIT(&freelist);
1512 for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
1513 PF_HASHROW_LOCK(sh);
1514 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1515 if (cur->states == 0 && cur->expire <= time_uptime) {
1516 pf_unlink_src_node_locked(cur);
1517 LIST_INSERT_HEAD(&freelist, cur, entry);
1518 } else if (cur->rule.ptr != NULL)
1519 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1520 PF_HASHROW_UNLOCK(sh);
1523 pf_free_src_nodes(&freelist);
1525 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1529 pf_src_tree_remove_state(struct pf_state *s)
1533 if (s->src_node != NULL) {
1535 --s->src_node->conn;
1536 if (--s->src_node->states == 0) {
1537 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1540 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1541 s->src_node->expire = time_uptime + timeout;
1544 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1545 if (--s->nat_src_node->states == 0) {
1546 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1549 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1550 s->nat_src_node->expire = time_uptime + timeout;
1553 s->src_node = s->nat_src_node = NULL;
1557 * Unlink and potentilly free a state. Function may be
1558 * called with ID hash row locked, but always returns
1559 * unlocked, since it needs to go through key hash locking.
1562 pf_unlink_state(struct pf_state *s, u_int flags)
1564 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1566 if ((flags & PF_ENTER_LOCKED) == 0)
1567 PF_HASHROW_LOCK(ih);
1569 PF_HASHROW_ASSERT(ih);
1571 if (s->timeout == PFTM_UNLINKED) {
1573 * State is being processed
1574 * by pf_unlink_state() in
1577 PF_HASHROW_UNLOCK(ih);
1578 return (0); /* XXXGL: undefined actually */
1581 if (s->src.state == PF_TCPS_PROXY_DST) {
1582 /* XXX wire key the right one? */
1583 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1584 &s->key[PF_SK_WIRE]->addr[1],
1585 &s->key[PF_SK_WIRE]->addr[0],
1586 s->key[PF_SK_WIRE]->port[1],
1587 s->key[PF_SK_WIRE]->port[0],
1588 s->src.seqhi, s->src.seqlo + 1,
1589 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1592 LIST_REMOVE(s, entry);
1593 pf_src_tree_remove_state(s);
1595 if (pfsync_delete_state_ptr != NULL)
1596 pfsync_delete_state_ptr(s);
1598 STATE_DEC_COUNTERS(s);
1600 s->timeout = PFTM_UNLINKED;
1602 PF_HASHROW_UNLOCK(ih);
1605 refcount_release(&s->refs);
1607 return (pf_release_state(s));
1611 pf_free_state(struct pf_state *cur)
1614 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1615 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1618 pf_normalize_tcp_cleanup(cur);
1619 uma_zfree(V_pf_state_z, cur);
1620 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1624 * Called only from pf_purge_thread(), thus serialized.
1627 pf_purge_expired_states(u_int i, int maxcheck)
1629 struct pf_idhash *ih;
1632 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1635 * Go through hash and unlink states that expire now.
1637 while (maxcheck > 0) {
1639 ih = &V_pf_idhash[i];
1641 PF_HASHROW_LOCK(ih);
1642 LIST_FOREACH(s, &ih->states, entry) {
1643 if (pf_state_expires(s) <= time_uptime) {
1644 V_pf_status.states -=
1645 pf_unlink_state(s, PF_ENTER_LOCKED);
1648 s->rule.ptr->rule_flag |= PFRULE_REFS;
1649 if (s->nat_rule.ptr != NULL)
1650 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1651 if (s->anchor.ptr != NULL)
1652 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1653 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1655 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1657 PF_HASHROW_UNLOCK(ih);
1659 /* Return when we hit end of hash. */
1660 if (++i > V_pf_hashmask) {
1661 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1668 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1674 pf_purge_unlinked_rules()
1676 struct pf_rulequeue tmpq;
1677 struct pf_rule *r, *r1;
1680 * If we have overloading task pending, then we'd
1681 * better skip purging this time. There is a tiny
1682 * probability that overloading task references
1683 * an already unlinked rule.
1685 PF_OVERLOADQ_LOCK();
1686 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1687 PF_OVERLOADQ_UNLOCK();
1690 PF_OVERLOADQ_UNLOCK();
1693 * Do naive mark-and-sweep garbage collecting of old rules.
1694 * Reference flag is raised by pf_purge_expired_states()
1695 * and pf_purge_expired_src_nodes().
1697 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1698 * use a temporary queue.
1701 PF_UNLNKDRULES_LOCK();
1702 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1703 if (!(r->rule_flag & PFRULE_REFS)) {
1704 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1705 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1707 r->rule_flag &= ~PFRULE_REFS;
1709 PF_UNLNKDRULES_UNLOCK();
1711 if (!TAILQ_EMPTY(&tmpq)) {
1713 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1714 TAILQ_REMOVE(&tmpq, r, entries);
1722 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1727 u_int32_t a = ntohl(addr->addr32[0]);
1728 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1740 u_int8_t i, curstart, curend, maxstart, maxend;
1741 curstart = curend = maxstart = maxend = 255;
1742 for (i = 0; i < 8; i++) {
1743 if (!addr->addr16[i]) {
1744 if (curstart == 255)
1748 if ((curend - curstart) >
1749 (maxend - maxstart)) {
1750 maxstart = curstart;
1753 curstart = curend = 255;
1756 if ((curend - curstart) >
1757 (maxend - maxstart)) {
1758 maxstart = curstart;
1761 for (i = 0; i < 8; i++) {
1762 if (i >= maxstart && i <= maxend) {
1768 b = ntohs(addr->addr16[i]);
1785 pf_print_state(struct pf_state *s)
1787 pf_print_state_parts(s, NULL, NULL);
1791 pf_print_state_parts(struct pf_state *s,
1792 struct pf_state_key *skwp, struct pf_state_key *sksp)
1794 struct pf_state_key *skw, *sks;
1795 u_int8_t proto, dir;
1797 /* Do our best to fill these, but they're skipped if NULL */
1798 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1799 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1800 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1801 dir = s ? s->direction : 0;
1819 case IPPROTO_ICMPV6:
1823 printf("%u", skw->proto);
1836 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1838 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1843 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1845 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1850 if (proto == IPPROTO_TCP) {
1851 printf(" [lo=%u high=%u win=%u modulator=%u",
1852 s->src.seqlo, s->src.seqhi,
1853 s->src.max_win, s->src.seqdiff);
1854 if (s->src.wscale && s->dst.wscale)
1855 printf(" wscale=%u",
1856 s->src.wscale & PF_WSCALE_MASK);
1858 printf(" [lo=%u high=%u win=%u modulator=%u",
1859 s->dst.seqlo, s->dst.seqhi,
1860 s->dst.max_win, s->dst.seqdiff);
1861 if (s->src.wscale && s->dst.wscale)
1862 printf(" wscale=%u",
1863 s->dst.wscale & PF_WSCALE_MASK);
1866 printf(" %u:%u", s->src.state, s->dst.state);
1871 pf_print_flags(u_int8_t f)
1893 #define PF_SET_SKIP_STEPS(i) \
1895 while (head[i] != cur) { \
1896 head[i]->skip[i].ptr = cur; \
1897 head[i] = TAILQ_NEXT(head[i], entries); \
1902 pf_calc_skip_steps(struct pf_rulequeue *rules)
1904 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1907 cur = TAILQ_FIRST(rules);
1909 for (i = 0; i < PF_SKIP_COUNT; ++i)
1911 while (cur != NULL) {
1913 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1914 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1915 if (cur->direction != prev->direction)
1916 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1917 if (cur->af != prev->af)
1918 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1919 if (cur->proto != prev->proto)
1920 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1921 if (cur->src.neg != prev->src.neg ||
1922 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1923 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1924 if (cur->src.port[0] != prev->src.port[0] ||
1925 cur->src.port[1] != prev->src.port[1] ||
1926 cur->src.port_op != prev->src.port_op)
1927 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1928 if (cur->dst.neg != prev->dst.neg ||
1929 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1930 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1931 if (cur->dst.port[0] != prev->dst.port[0] ||
1932 cur->dst.port[1] != prev->dst.port[1] ||
1933 cur->dst.port_op != prev->dst.port_op)
1934 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1937 cur = TAILQ_NEXT(cur, entries);
1939 for (i = 0; i < PF_SKIP_COUNT; ++i)
1940 PF_SET_SKIP_STEPS(i);
1944 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1946 if (aw1->type != aw2->type)
1948 switch (aw1->type) {
1949 case PF_ADDR_ADDRMASK:
1951 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1953 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1956 case PF_ADDR_DYNIFTL:
1957 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1958 case PF_ADDR_NOROUTE:
1959 case PF_ADDR_URPFFAILED:
1962 return (aw1->p.tbl != aw2->p.tbl);
1964 printf("invalid address type: %d\n", aw1->type);
1970 * Checksum updates are a little complicated because the checksum in the TCP/UDP
1971 * header isn't always a full checksum. In some cases (i.e. output) it's a
1972 * pseudo-header checksum, which is a partial checksum over src/dst IP
1973 * addresses, protocol number and length.
1975 * That means we have the following cases:
1976 * * Input or forwarding: we don't have TSO, the checksum fields are full
1977 * checksums, we need to update the checksum whenever we change anything.
1978 * * Output (i.e. the checksum is a pseudo-header checksum):
1979 * x The field being updated is src/dst address or affects the length of
1980 * the packet. We need to update the pseudo-header checksum (note that this
1981 * checksum is not ones' complement).
1982 * x Some other field is being modified (e.g. src/dst port numbers): We
1983 * don't have to update anything.
1986 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1992 l = cksum + old - new;
1993 l = (l >> 16) + (l & 65535);
2001 pf_proto_cksum_fixup(struct mbuf *m, u_int16_t cksum, u_int16_t old,
2002 u_int16_t new, u_int8_t udp)
2004 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2007 return (pf_cksum_fixup(cksum, old, new, udp));
2011 pf_change_ap(struct mbuf *m, struct pf_addr *a, u_int16_t *p, u_int16_t *ic,
2012 u_int16_t *pc, struct pf_addr *an, u_int16_t pn, u_int8_t u,
2018 PF_ACPY(&ao, a, af);
2021 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA | CSUM_DELAY_DATA_IPV6))
2029 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2030 ao.addr16[0], an->addr16[0], 0),
2031 ao.addr16[1], an->addr16[1], 0);
2034 *pc = pf_cksum_fixup(pf_cksum_fixup(*pc,
2035 ao.addr16[0], an->addr16[0], u),
2036 ao.addr16[1], an->addr16[1], u);
2038 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2043 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2044 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2045 pf_cksum_fixup(pf_cksum_fixup(*pc,
2046 ao.addr16[0], an->addr16[0], u),
2047 ao.addr16[1], an->addr16[1], u),
2048 ao.addr16[2], an->addr16[2], u),
2049 ao.addr16[3], an->addr16[3], u),
2050 ao.addr16[4], an->addr16[4], u),
2051 ao.addr16[5], an->addr16[5], u),
2052 ao.addr16[6], an->addr16[6], u),
2053 ao.addr16[7], an->addr16[7], u);
2055 *pc = pf_proto_cksum_fixup(m, *pc, po, pn, u);
2060 if (m->m_pkthdr.csum_flags & (CSUM_DELAY_DATA |
2061 CSUM_DELAY_DATA_IPV6)) {
2068 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2070 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2074 memcpy(&ao, a, sizeof(ao));
2075 memcpy(a, &an, sizeof(u_int32_t));
2076 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2077 ao % 65536, an % 65536, u);
2081 pf_change_proto_a(struct mbuf *m, void *a, u_int16_t *c, u_int32_t an, u_int8_t udp)
2085 memcpy(&ao, a, sizeof(ao));
2086 memcpy(a, &an, sizeof(u_int32_t));
2088 *c = pf_proto_cksum_fixup(m,
2089 pf_proto_cksum_fixup(m, *c, ao / 65536, an / 65536, udp),
2090 ao % 65536, an % 65536, udp);
2095 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2099 PF_ACPY(&ao, a, AF_INET6);
2100 PF_ACPY(a, an, AF_INET6);
2102 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2103 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2104 pf_cksum_fixup(pf_cksum_fixup(*c,
2105 ao.addr16[0], an->addr16[0], u),
2106 ao.addr16[1], an->addr16[1], u),
2107 ao.addr16[2], an->addr16[2], u),
2108 ao.addr16[3], an->addr16[3], u),
2109 ao.addr16[4], an->addr16[4], u),
2110 ao.addr16[5], an->addr16[5], u),
2111 ao.addr16[6], an->addr16[6], u),
2112 ao.addr16[7], an->addr16[7], u);
2117 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2118 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2119 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2121 struct pf_addr oia, ooa;
2123 PF_ACPY(&oia, ia, af);
2125 PF_ACPY(&ooa, oa, af);
2127 /* Change inner protocol port, fix inner protocol checksum. */
2129 u_int16_t oip = *ip;
2136 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2137 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2139 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2141 /* Change inner ip address, fix inner ip and icmp checksums. */
2142 PF_ACPY(ia, na, af);
2146 u_int32_t oh2c = *h2c;
2148 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2149 oia.addr16[0], ia->addr16[0], 0),
2150 oia.addr16[1], ia->addr16[1], 0);
2151 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2152 oia.addr16[0], ia->addr16[0], 0),
2153 oia.addr16[1], ia->addr16[1], 0);
2154 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2160 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2161 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2162 pf_cksum_fixup(pf_cksum_fixup(*ic,
2163 oia.addr16[0], ia->addr16[0], u),
2164 oia.addr16[1], ia->addr16[1], u),
2165 oia.addr16[2], ia->addr16[2], u),
2166 oia.addr16[3], ia->addr16[3], u),
2167 oia.addr16[4], ia->addr16[4], u),
2168 oia.addr16[5], ia->addr16[5], u),
2169 oia.addr16[6], ia->addr16[6], u),
2170 oia.addr16[7], ia->addr16[7], u);
2174 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2176 PF_ACPY(oa, na, af);
2180 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2181 ooa.addr16[0], oa->addr16[0], 0),
2182 ooa.addr16[1], oa->addr16[1], 0);
2187 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2188 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2189 pf_cksum_fixup(pf_cksum_fixup(*ic,
2190 ooa.addr16[0], oa->addr16[0], u),
2191 ooa.addr16[1], oa->addr16[1], u),
2192 ooa.addr16[2], oa->addr16[2], u),
2193 ooa.addr16[3], oa->addr16[3], u),
2194 ooa.addr16[4], oa->addr16[4], u),
2195 ooa.addr16[5], oa->addr16[5], u),
2196 ooa.addr16[6], oa->addr16[6], u),
2197 ooa.addr16[7], oa->addr16[7], u);
2206 * Need to modulate the sequence numbers in the TCP SACK option
2207 * (credits to Krzysztof Pfaff for report and patch)
2210 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2211 struct tcphdr *th, struct pf_state_peer *dst)
2213 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2214 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2215 int copyback = 0, i, olen;
2216 struct sackblk sack;
2218 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2219 if (hlen < TCPOLEN_SACKLEN ||
2220 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2223 while (hlen >= TCPOLEN_SACKLEN) {
2226 case TCPOPT_EOL: /* FALLTHROUGH */
2234 if (olen >= TCPOLEN_SACKLEN) {
2235 for (i = 2; i + TCPOLEN_SACK <= olen;
2236 i += TCPOLEN_SACK) {
2237 memcpy(&sack, &opt[i], sizeof(sack));
2238 pf_change_proto_a(m, &sack.start, &th->th_sum,
2239 htonl(ntohl(sack.start) - dst->seqdiff), 0);
2240 pf_change_proto_a(m, &sack.end, &th->th_sum,
2241 htonl(ntohl(sack.end) - dst->seqdiff), 0);
2242 memcpy(&opt[i], &sack, sizeof(sack));
2256 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2261 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2262 const struct pf_addr *saddr, const struct pf_addr *daddr,
2263 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2264 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2265 u_int16_t rtag, struct ifnet *ifp)
2267 struct pf_send_entry *pfse;
2271 struct ip *h = NULL;
2274 struct ip6_hdr *h6 = NULL;
2278 struct pf_mtag *pf_mtag;
2283 /* maximum segment size tcp option */
2284 tlen = sizeof(struct tcphdr);
2291 len = sizeof(struct ip) + tlen;
2296 len = sizeof(struct ip6_hdr) + tlen;
2300 panic("%s: unsupported af %d", __func__, af);
2303 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2304 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2307 m = m_gethdr(M_NOWAIT, MT_DATA);
2309 free(pfse, M_PFTEMP);
2313 mac_netinet_firewall_send(m);
2315 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2316 free(pfse, M_PFTEMP);
2321 m->m_flags |= M_SKIP_FIREWALL;
2322 pf_mtag->tag = rtag;
2324 if (r != NULL && r->rtableid >= 0)
2325 M_SETFIB(m, r->rtableid);
2328 if (r != NULL && r->qid) {
2329 pf_mtag->qid = r->qid;
2331 /* add hints for ecn */
2332 pf_mtag->hdr = mtod(m, struct ip *);
2335 m->m_data += max_linkhdr;
2336 m->m_pkthdr.len = m->m_len = len;
2337 m->m_pkthdr.rcvif = NULL;
2338 bzero(m->m_data, len);
2342 h = mtod(m, struct ip *);
2344 /* IP header fields included in the TCP checksum */
2345 h->ip_p = IPPROTO_TCP;
2346 h->ip_len = htons(tlen);
2347 h->ip_src.s_addr = saddr->v4.s_addr;
2348 h->ip_dst.s_addr = daddr->v4.s_addr;
2350 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2355 h6 = mtod(m, struct ip6_hdr *);
2357 /* IP header fields included in the TCP checksum */
2358 h6->ip6_nxt = IPPROTO_TCP;
2359 h6->ip6_plen = htons(tlen);
2360 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2361 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2363 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2369 th->th_sport = sport;
2370 th->th_dport = dport;
2371 th->th_seq = htonl(seq);
2372 th->th_ack = htonl(ack);
2373 th->th_off = tlen >> 2;
2374 th->th_flags = flags;
2375 th->th_win = htons(win);
2378 opt = (char *)(th + 1);
2379 opt[0] = TCPOPT_MAXSEG;
2382 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2389 th->th_sum = in_cksum(m, len);
2391 /* Finish the IP header */
2393 h->ip_hl = sizeof(*h) >> 2;
2394 h->ip_tos = IPTOS_LOWDELAY;
2395 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2396 h->ip_len = htons(len);
2397 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2400 pfse->pfse_type = PFSE_IP;
2406 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2407 sizeof(struct ip6_hdr), tlen);
2409 h6->ip6_vfc |= IPV6_VERSION;
2410 h6->ip6_hlim = IPV6_DEFHLIM;
2412 pfse->pfse_type = PFSE_IP6;
2421 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2424 struct pf_send_entry *pfse;
2426 struct pf_mtag *pf_mtag;
2428 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2429 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2433 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2434 free(pfse, M_PFTEMP);
2438 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2439 free(pfse, M_PFTEMP);
2443 m0->m_flags |= M_SKIP_FIREWALL;
2445 if (r->rtableid >= 0)
2446 M_SETFIB(m0, r->rtableid);
2450 pf_mtag->qid = r->qid;
2451 /* add hints for ecn */
2452 pf_mtag->hdr = mtod(m0, struct ip *);
2459 pfse->pfse_type = PFSE_ICMP;
2464 pfse->pfse_type = PFSE_ICMP6;
2469 pfse->pfse_icmp_type = type;
2470 pfse->pfse_icmp_code = code;
2475 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2476 * If n is 0, they match if they are equal. If n is != 0, they match if they
2480 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2481 struct pf_addr *b, sa_family_t af)
2488 if ((a->addr32[0] & m->addr32[0]) ==
2489 (b->addr32[0] & m->addr32[0]))
2495 if (((a->addr32[0] & m->addr32[0]) ==
2496 (b->addr32[0] & m->addr32[0])) &&
2497 ((a->addr32[1] & m->addr32[1]) ==
2498 (b->addr32[1] & m->addr32[1])) &&
2499 ((a->addr32[2] & m->addr32[2]) ==
2500 (b->addr32[2] & m->addr32[2])) &&
2501 ((a->addr32[3] & m->addr32[3]) ==
2502 (b->addr32[3] & m->addr32[3])))
2521 * Return 1 if b <= a <= e, otherwise return 0.
2524 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2525 struct pf_addr *a, sa_family_t af)
2530 if ((a->addr32[0] < b->addr32[0]) ||
2531 (a->addr32[0] > e->addr32[0]))
2540 for (i = 0; i < 4; ++i)
2541 if (a->addr32[i] > b->addr32[i])
2543 else if (a->addr32[i] < b->addr32[i])
2546 for (i = 0; i < 4; ++i)
2547 if (a->addr32[i] < e->addr32[i])
2549 else if (a->addr32[i] > e->addr32[i])
2559 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2563 return ((p > a1) && (p < a2));
2565 return ((p < a1) || (p > a2));
2567 return ((p >= a1) && (p <= a2));
2581 return (0); /* never reached */
2585 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2590 return (pf_match(op, a1, a2, p));
2594 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2596 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2598 return (pf_match(op, a1, a2, u));
2602 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2604 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2606 return (pf_match(op, a1, a2, g));
2610 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2615 return ((!r->match_tag_not && r->match_tag == *tag) ||
2616 (r->match_tag_not && r->match_tag != *tag));
2620 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2623 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2625 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2628 pd->pf_mtag->tag = tag;
2633 #define PF_ANCHOR_STACKSIZE 32
2634 struct pf_anchor_stackframe {
2635 struct pf_ruleset *rs;
2636 struct pf_rule *r; /* XXX: + match bit */
2637 struct pf_anchor *child;
2641 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2643 #define PF_ANCHORSTACK_MATCH 0x00000001
2644 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2646 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2647 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2648 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2649 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2650 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2654 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2655 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2658 struct pf_anchor_stackframe *f;
2664 if (*depth >= PF_ANCHOR_STACKSIZE) {
2665 printf("%s: anchor stack overflow on %s\n",
2666 __func__, (*r)->anchor->name);
2667 *r = TAILQ_NEXT(*r, entries);
2669 } else if (*depth == 0 && a != NULL)
2671 f = stack + (*depth)++;
2674 if ((*r)->anchor_wildcard) {
2675 struct pf_anchor_node *parent = &(*r)->anchor->children;
2677 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2681 *rs = &f->child->ruleset;
2684 *rs = &(*r)->anchor->ruleset;
2686 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2690 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2691 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2694 struct pf_anchor_stackframe *f;
2703 f = stack + *depth - 1;
2704 fr = PF_ANCHOR_RULE(f);
2705 if (f->child != NULL) {
2706 struct pf_anchor_node *parent;
2709 * This block traverses through
2710 * a wildcard anchor.
2712 parent = &fr->anchor->children;
2713 if (match != NULL && *match) {
2715 * If any of "*" matched, then
2716 * "foo/ *" matched, mark frame
2719 PF_ANCHOR_SET_MATCH(f);
2722 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2723 if (f->child != NULL) {
2724 *rs = &f->child->ruleset;
2725 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2733 if (*depth == 0 && a != NULL)
2736 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2738 *r = TAILQ_NEXT(fr, entries);
2739 } while (*r == NULL);
2746 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2747 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2752 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2753 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2757 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2758 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2759 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2760 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2761 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2762 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2763 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2764 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2770 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2775 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2779 if (addr->addr32[3] == 0xffffffff) {
2780 addr->addr32[3] = 0;
2781 if (addr->addr32[2] == 0xffffffff) {
2782 addr->addr32[2] = 0;
2783 if (addr->addr32[1] == 0xffffffff) {
2784 addr->addr32[1] = 0;
2786 htonl(ntohl(addr->addr32[0]) + 1);
2789 htonl(ntohl(addr->addr32[1]) + 1);
2792 htonl(ntohl(addr->addr32[2]) + 1);
2795 htonl(ntohl(addr->addr32[3]) + 1);
2802 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2804 struct pf_addr *saddr, *daddr;
2805 u_int16_t sport, dport;
2806 struct inpcbinfo *pi;
2809 pd->lookup.uid = UID_MAX;
2810 pd->lookup.gid = GID_MAX;
2812 switch (pd->proto) {
2814 if (pd->hdr.tcp == NULL)
2816 sport = pd->hdr.tcp->th_sport;
2817 dport = pd->hdr.tcp->th_dport;
2821 if (pd->hdr.udp == NULL)
2823 sport = pd->hdr.udp->uh_sport;
2824 dport = pd->hdr.udp->uh_dport;
2830 if (direction == PF_IN) {
2845 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2846 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2848 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2849 daddr->v4, dport, INPLOOKUP_WILDCARD |
2850 INPLOOKUP_RLOCKPCB, NULL, m);
2858 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2859 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2861 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2862 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2863 INPLOOKUP_RLOCKPCB, NULL, m);
2873 INP_RLOCK_ASSERT(inp);
2874 pd->lookup.uid = inp->inp_cred->cr_uid;
2875 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2882 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2886 u_int8_t *opt, optlen;
2887 u_int8_t wscale = 0;
2889 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2890 if (hlen <= sizeof(struct tcphdr))
2892 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2894 opt = hdr + sizeof(struct tcphdr);
2895 hlen -= sizeof(struct tcphdr);
2905 if (wscale > TCP_MAX_WINSHIFT)
2906 wscale = TCP_MAX_WINSHIFT;
2907 wscale |= PF_WSCALE_FLAG;
2922 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2926 u_int8_t *opt, optlen;
2927 u_int16_t mss = V_tcp_mssdflt;
2929 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2930 if (hlen <= sizeof(struct tcphdr))
2932 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2934 opt = hdr + sizeof(struct tcphdr);
2935 hlen -= sizeof(struct tcphdr);
2936 while (hlen >= TCPOLEN_MAXSEG) {
2944 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2960 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2963 struct sockaddr_in *dst;
2967 struct sockaddr_in6 *dst6;
2968 struct route_in6 ro6;
2970 struct rtentry *rt = NULL;
2972 u_int16_t mss = V_tcp_mssdflt;
2977 hlen = sizeof(struct ip);
2978 bzero(&ro, sizeof(ro));
2979 dst = (struct sockaddr_in *)&ro.ro_dst;
2980 dst->sin_family = AF_INET;
2981 dst->sin_len = sizeof(*dst);
2982 dst->sin_addr = addr->v4;
2983 in_rtalloc_ign(&ro, 0, rtableid);
2989 hlen = sizeof(struct ip6_hdr);
2990 bzero(&ro6, sizeof(ro6));
2991 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2992 dst6->sin6_family = AF_INET6;
2993 dst6->sin6_len = sizeof(*dst6);
2994 dst6->sin6_addr = addr->v6;
2995 in6_rtalloc_ign(&ro6, 0, rtableid);
3001 if (rt && rt->rt_ifp) {
3002 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3003 mss = max(V_tcp_mssdflt, mss);
3006 mss = min(mss, offer);
3007 mss = max(mss, 64); /* sanity - at least max opt space */
3012 pf_tcp_iss(struct pf_pdesc *pd)
3015 u_int32_t digest[4];
3017 if (V_pf_tcp_secret_init == 0) {
3018 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3019 MD5Init(&V_pf_tcp_secret_ctx);
3020 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3021 sizeof(V_pf_tcp_secret));
3022 V_pf_tcp_secret_init = 1;
3025 ctx = V_pf_tcp_secret_ctx;
3027 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3028 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3029 if (pd->af == AF_INET6) {
3030 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3031 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3033 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3034 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3036 MD5Final((u_char *)digest, &ctx);
3037 V_pf_tcp_iss_off += 4096;
3038 #define ISN_RANDOM_INCREMENT (4096 - 1)
3039 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3041 #undef ISN_RANDOM_INCREMENT
3045 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3046 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3047 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3049 struct pf_rule *nr = NULL;
3050 struct pf_addr * const saddr = pd->src;
3051 struct pf_addr * const daddr = pd->dst;
3052 sa_family_t af = pd->af;
3053 struct pf_rule *r, *a = NULL;
3054 struct pf_ruleset *ruleset = NULL;
3055 struct pf_src_node *nsn = NULL;
3056 struct tcphdr *th = pd->hdr.tcp;
3057 struct pf_state_key *sk = NULL, *nk = NULL;
3059 int rewrite = 0, hdrlen = 0;
3060 int tag = -1, rtableid = -1;
3064 u_int16_t sport = 0, dport = 0;
3065 u_int16_t bproto_sum = 0, bip_sum = 0;
3066 u_int8_t icmptype = 0, icmpcode = 0;
3067 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3072 INP_LOCK_ASSERT(inp);
3073 pd->lookup.uid = inp->inp_cred->cr_uid;
3074 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3075 pd->lookup.done = 1;
3078 switch (pd->proto) {
3080 sport = th->th_sport;
3081 dport = th->th_dport;
3082 hdrlen = sizeof(*th);
3085 sport = pd->hdr.udp->uh_sport;
3086 dport = pd->hdr.udp->uh_dport;
3087 hdrlen = sizeof(*pd->hdr.udp);
3091 if (pd->af != AF_INET)
3093 sport = dport = pd->hdr.icmp->icmp_id;
3094 hdrlen = sizeof(*pd->hdr.icmp);
3095 icmptype = pd->hdr.icmp->icmp_type;
3096 icmpcode = pd->hdr.icmp->icmp_code;
3098 if (icmptype == ICMP_UNREACH ||
3099 icmptype == ICMP_SOURCEQUENCH ||
3100 icmptype == ICMP_REDIRECT ||
3101 icmptype == ICMP_TIMXCEED ||
3102 icmptype == ICMP_PARAMPROB)
3107 case IPPROTO_ICMPV6:
3110 sport = dport = pd->hdr.icmp6->icmp6_id;
3111 hdrlen = sizeof(*pd->hdr.icmp6);
3112 icmptype = pd->hdr.icmp6->icmp6_type;
3113 icmpcode = pd->hdr.icmp6->icmp6_code;
3115 if (icmptype == ICMP6_DST_UNREACH ||
3116 icmptype == ICMP6_PACKET_TOO_BIG ||
3117 icmptype == ICMP6_TIME_EXCEEDED ||
3118 icmptype == ICMP6_PARAM_PROB)
3123 sport = dport = hdrlen = 0;
3127 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3129 /* check packet for BINAT/NAT/RDR */
3130 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3131 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3132 KASSERT(sk != NULL, ("%s: null sk", __func__));
3133 KASSERT(nk != NULL, ("%s: null nk", __func__));
3136 bip_sum = *pd->ip_sum;
3138 switch (pd->proto) {
3140 bproto_sum = th->th_sum;
3141 pd->proto_sum = &th->th_sum;
3143 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3144 nk->port[pd->sidx] != sport) {
3145 pf_change_ap(m, saddr, &th->th_sport, pd->ip_sum,
3146 &th->th_sum, &nk->addr[pd->sidx],
3147 nk->port[pd->sidx], 0, af);
3148 pd->sport = &th->th_sport;
3149 sport = th->th_sport;
3152 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3153 nk->port[pd->didx] != dport) {
3154 pf_change_ap(m, daddr, &th->th_dport, pd->ip_sum,
3155 &th->th_sum, &nk->addr[pd->didx],
3156 nk->port[pd->didx], 0, af);
3157 dport = th->th_dport;
3158 pd->dport = &th->th_dport;
3163 bproto_sum = pd->hdr.udp->uh_sum;
3164 pd->proto_sum = &pd->hdr.udp->uh_sum;
3166 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3167 nk->port[pd->sidx] != sport) {
3168 pf_change_ap(m, saddr, &pd->hdr.udp->uh_sport,
3169 pd->ip_sum, &pd->hdr.udp->uh_sum,
3170 &nk->addr[pd->sidx],
3171 nk->port[pd->sidx], 1, af);
3172 sport = pd->hdr.udp->uh_sport;
3173 pd->sport = &pd->hdr.udp->uh_sport;
3176 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3177 nk->port[pd->didx] != dport) {
3178 pf_change_ap(m, daddr, &pd->hdr.udp->uh_dport,
3179 pd->ip_sum, &pd->hdr.udp->uh_sum,
3180 &nk->addr[pd->didx],
3181 nk->port[pd->didx], 1, af);
3182 dport = pd->hdr.udp->uh_dport;
3183 pd->dport = &pd->hdr.udp->uh_dport;
3189 nk->port[0] = nk->port[1];
3190 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3191 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3192 nk->addr[pd->sidx].v4.s_addr, 0);
3194 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3195 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3196 nk->addr[pd->didx].v4.s_addr, 0);
3198 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3199 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3200 pd->hdr.icmp->icmp_cksum, sport,
3202 pd->hdr.icmp->icmp_id = nk->port[1];
3203 pd->sport = &pd->hdr.icmp->icmp_id;
3205 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3209 case IPPROTO_ICMPV6:
3210 nk->port[0] = nk->port[1];
3211 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3212 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3213 &nk->addr[pd->sidx], 0);
3215 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3216 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3217 &nk->addr[pd->didx], 0);
3226 &nk->addr[pd->sidx], AF_INET))
3227 pf_change_a(&saddr->v4.s_addr,
3229 nk->addr[pd->sidx].v4.s_addr, 0);
3232 &nk->addr[pd->didx], AF_INET))
3233 pf_change_a(&daddr->v4.s_addr,
3235 nk->addr[pd->didx].v4.s_addr, 0);
3241 &nk->addr[pd->sidx], AF_INET6))
3242 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3245 &nk->addr[pd->didx], AF_INET6))
3246 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3259 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3260 r = r->skip[PF_SKIP_IFP].ptr;
3261 else if (r->direction && r->direction != direction)
3262 r = r->skip[PF_SKIP_DIR].ptr;
3263 else if (r->af && r->af != af)
3264 r = r->skip[PF_SKIP_AF].ptr;
3265 else if (r->proto && r->proto != pd->proto)
3266 r = r->skip[PF_SKIP_PROTO].ptr;
3267 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3268 r->src.neg, kif, M_GETFIB(m)))
3269 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3270 /* tcp/udp only. port_op always 0 in other cases */
3271 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3272 r->src.port[0], r->src.port[1], sport))
3273 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3274 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3275 r->dst.neg, NULL, M_GETFIB(m)))
3276 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3277 /* tcp/udp only. port_op always 0 in other cases */
3278 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3279 r->dst.port[0], r->dst.port[1], dport))
3280 r = r->skip[PF_SKIP_DST_PORT].ptr;
3281 /* icmp only. type always 0 in other cases */
3282 else if (r->type && r->type != icmptype + 1)
3283 r = TAILQ_NEXT(r, entries);
3284 /* icmp only. type always 0 in other cases */
3285 else if (r->code && r->code != icmpcode + 1)
3286 r = TAILQ_NEXT(r, entries);
3287 else if (r->tos && !(r->tos == pd->tos))
3288 r = TAILQ_NEXT(r, entries);
3289 else if (r->rule_flag & PFRULE_FRAGMENT)
3290 r = TAILQ_NEXT(r, entries);
3291 else if (pd->proto == IPPROTO_TCP &&
3292 (r->flagset & th->th_flags) != r->flags)
3293 r = TAILQ_NEXT(r, entries);
3294 /* tcp/udp only. uid.op always 0 in other cases */
3295 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3296 pf_socket_lookup(direction, pd, m), 1)) &&
3297 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3299 r = TAILQ_NEXT(r, entries);
3300 /* tcp/udp only. gid.op always 0 in other cases */
3301 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3302 pf_socket_lookup(direction, pd, m), 1)) &&
3303 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3305 r = TAILQ_NEXT(r, entries);
3307 r->prob <= arc4random())
3308 r = TAILQ_NEXT(r, entries);
3309 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3310 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3311 r = TAILQ_NEXT(r, entries);
3312 else if (r->os_fingerprint != PF_OSFP_ANY &&
3313 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3314 pf_osfp_fingerprint(pd, m, off, th),
3315 r->os_fingerprint)))
3316 r = TAILQ_NEXT(r, entries);
3320 if (r->rtableid >= 0)
3321 rtableid = r->rtableid;
3322 if (r->anchor == NULL) {
3329 r = TAILQ_NEXT(r, entries);
3331 pf_step_into_anchor(anchor_stack, &asd,
3332 &ruleset, PF_RULESET_FILTER, &r, &a,
3335 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3336 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3343 REASON_SET(&reason, PFRES_MATCH);
3345 if (r->log || (nr != NULL && nr->log)) {
3347 m_copyback(m, off, hdrlen, pd->hdr.any);
3348 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3352 if ((r->action == PF_DROP) &&
3353 ((r->rule_flag & PFRULE_RETURNRST) ||
3354 (r->rule_flag & PFRULE_RETURNICMP) ||
3355 (r->rule_flag & PFRULE_RETURN))) {
3356 /* undo NAT changes, if they have taken place */
3358 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3359 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3361 *pd->sport = sk->port[pd->sidx];
3363 *pd->dport = sk->port[pd->didx];
3365 *pd->proto_sum = bproto_sum;
3367 *pd->ip_sum = bip_sum;
3368 m_copyback(m, off, hdrlen, pd->hdr.any);
3370 if (pd->proto == IPPROTO_TCP &&
3371 ((r->rule_flag & PFRULE_RETURNRST) ||
3372 (r->rule_flag & PFRULE_RETURN)) &&
3373 !(th->th_flags & TH_RST)) {
3374 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3386 h4 = mtod(m, struct ip *);
3387 len = ntohs(h4->ip_len) - off;
3392 h6 = mtod(m, struct ip6_hdr *);
3393 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3398 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3399 REASON_SET(&reason, PFRES_PROTCKSUM);
3401 if (th->th_flags & TH_SYN)
3403 if (th->th_flags & TH_FIN)
3405 pf_send_tcp(m, r, af, pd->dst,
3406 pd->src, th->th_dport, th->th_sport,
3407 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3408 r->return_ttl, 1, 0, kif->pfik_ifp);
3410 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3412 pf_send_icmp(m, r->return_icmp >> 8,
3413 r->return_icmp & 255, af, r);
3414 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3416 pf_send_icmp(m, r->return_icmp6 >> 8,
3417 r->return_icmp6 & 255, af, r);
3420 if (r->action == PF_DROP)
3423 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3424 REASON_SET(&reason, PFRES_MEMORY);
3428 M_SETFIB(m, rtableid);
3430 if (!state_icmp && (r->keep_state || nr != NULL ||
3431 (pd->flags & PFDESC_TCP_NORM))) {
3433 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3434 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3436 if (action != PF_PASS)
3440 uma_zfree(V_pf_state_key_z, sk);
3442 uma_zfree(V_pf_state_key_z, nk);
3445 /* copy back packet headers if we performed NAT operations */
3447 m_copyback(m, off, hdrlen, pd->hdr.any);
3449 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3450 direction == PF_OUT &&
3451 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3453 * We want the state created, but we dont
3454 * want to send this in case a partner
3455 * firewall has to know about it to allow
3456 * replies through it.
3464 uma_zfree(V_pf_state_key_z, sk);
3466 uma_zfree(V_pf_state_key_z, nk);
3471 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3472 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3473 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3474 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3475 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3477 struct pf_state *s = NULL;
3478 struct pf_src_node *sn = NULL;
3479 struct tcphdr *th = pd->hdr.tcp;
3480 u_int16_t mss = V_tcp_mssdflt;
3483 /* check maximums */
3484 if (r->max_states &&
3485 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3486 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3487 REASON_SET(&reason, PFRES_MAXSTATES);
3490 /* src node for filter rule */
3491 if ((r->rule_flag & PFRULE_SRCTRACK ||
3492 r->rpool.opts & PF_POOL_STICKYADDR) &&
3493 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3494 REASON_SET(&reason, PFRES_SRCLIMIT);
3497 /* src node for translation rule */
3498 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3499 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3500 REASON_SET(&reason, PFRES_SRCLIMIT);
3503 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3505 REASON_SET(&reason, PFRES_MEMORY);
3509 s->nat_rule.ptr = nr;
3511 STATE_INC_COUNTERS(s);
3513 s->state_flags |= PFSTATE_ALLOWOPTS;
3514 if (r->rule_flag & PFRULE_STATESLOPPY)
3515 s->state_flags |= PFSTATE_SLOPPY;
3516 s->log = r->log & PF_LOG_ALL;
3517 s->sync_state = PFSYNC_S_NONE;
3519 s->log |= nr->log & PF_LOG_ALL;
3520 switch (pd->proto) {
3522 s->src.seqlo = ntohl(th->th_seq);
3523 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3524 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3525 r->keep_state == PF_STATE_MODULATE) {
3526 /* Generate sequence number modulator */
3527 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3530 pf_change_proto_a(m, &th->th_seq, &th->th_sum,
3531 htonl(s->src.seqlo + s->src.seqdiff), 0);
3535 if (th->th_flags & TH_SYN) {
3537 s->src.wscale = pf_get_wscale(m, off,
3538 th->th_off, pd->af);
3540 s->src.max_win = MAX(ntohs(th->th_win), 1);
3541 if (s->src.wscale & PF_WSCALE_MASK) {
3542 /* Remove scale factor from initial window */
3543 int win = s->src.max_win;
3544 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3545 s->src.max_win = (win - 1) >>
3546 (s->src.wscale & PF_WSCALE_MASK);
3548 if (th->th_flags & TH_FIN)
3552 s->src.state = TCPS_SYN_SENT;
3553 s->dst.state = TCPS_CLOSED;
3554 s->timeout = PFTM_TCP_FIRST_PACKET;
3557 s->src.state = PFUDPS_SINGLE;
3558 s->dst.state = PFUDPS_NO_TRAFFIC;
3559 s->timeout = PFTM_UDP_FIRST_PACKET;
3563 case IPPROTO_ICMPV6:
3565 s->timeout = PFTM_ICMP_FIRST_PACKET;
3568 s->src.state = PFOTHERS_SINGLE;
3569 s->dst.state = PFOTHERS_NO_TRAFFIC;
3570 s->timeout = PFTM_OTHER_FIRST_PACKET;
3573 if (r->rt && r->rt != PF_FASTROUTE) {
3574 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3575 REASON_SET(&reason, PFRES_BADSTATE);
3576 pf_src_tree_remove_state(s);
3577 STATE_DEC_COUNTERS(s);
3578 uma_zfree(V_pf_state_z, s);
3581 s->rt_kif = r->rpool.cur->kif;
3584 s->creation = time_uptime;
3585 s->expire = time_uptime;
3589 s->src_node->states++;
3592 /* XXX We only modify one side for now. */
3593 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3594 s->nat_src_node = nsn;
3595 s->nat_src_node->states++;
3597 if (pd->proto == IPPROTO_TCP) {
3598 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3599 off, pd, th, &s->src, &s->dst)) {
3600 REASON_SET(&reason, PFRES_MEMORY);
3601 pf_src_tree_remove_state(s);
3602 STATE_DEC_COUNTERS(s);
3603 uma_zfree(V_pf_state_z, s);
3606 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3607 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3608 &s->src, &s->dst, rewrite)) {
3609 /* This really shouldn't happen!!! */
3610 DPFPRINTF(PF_DEBUG_URGENT,
3611 ("pf_normalize_tcp_stateful failed on first pkt"));
3612 pf_normalize_tcp_cleanup(s);
3613 pf_src_tree_remove_state(s);
3614 STATE_DEC_COUNTERS(s);
3615 uma_zfree(V_pf_state_z, s);
3619 s->direction = pd->dir;
3622 * sk/nk could already been setup by pf_get_translation().
3625 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3626 __func__, nr, sk, nk));
3627 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3632 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3633 __func__, nr, sk, nk));
3635 /* Swap sk/nk for PF_OUT. */
3636 if (pf_state_insert(BOUND_IFACE(r, kif),
3637 (pd->dir == PF_IN) ? sk : nk,
3638 (pd->dir == PF_IN) ? nk : sk, s)) {
3639 if (pd->proto == IPPROTO_TCP)
3640 pf_normalize_tcp_cleanup(s);
3641 REASON_SET(&reason, PFRES_STATEINS);
3642 pf_src_tree_remove_state(s);
3643 STATE_DEC_COUNTERS(s);
3644 uma_zfree(V_pf_state_z, s);
3651 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3652 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3653 s->src.state = PF_TCPS_PROXY_SRC;
3654 /* undo NAT changes, if they have taken place */
3656 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3657 if (pd->dir == PF_OUT)
3658 skt = s->key[PF_SK_STACK];
3659 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3660 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3662 *pd->sport = skt->port[pd->sidx];
3664 *pd->dport = skt->port[pd->didx];
3666 *pd->proto_sum = bproto_sum;
3668 *pd->ip_sum = bip_sum;
3669 m_copyback(m, off, hdrlen, pd->hdr.any);
3671 s->src.seqhi = htonl(arc4random());
3672 /* Find mss option */
3673 int rtid = M_GETFIB(m);
3674 mss = pf_get_mss(m, off, th->th_off, pd->af);
3675 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3676 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3678 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3679 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3680 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3681 REASON_SET(&reason, PFRES_SYNPROXY);
3682 return (PF_SYNPROXY_DROP);
3689 uma_zfree(V_pf_state_key_z, sk);
3691 uma_zfree(V_pf_state_key_z, nk);
3693 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3694 pf_unlink_src_node(sn);
3695 pf_free_src_node(sn);
3698 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3699 pf_unlink_src_node(nsn);
3700 pf_free_src_node(nsn);
3707 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3708 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3709 struct pf_ruleset **rsm)
3711 struct pf_rule *r, *a = NULL;
3712 struct pf_ruleset *ruleset = NULL;
3713 sa_family_t af = pd->af;
3718 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3722 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3725 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3726 r = r->skip[PF_SKIP_IFP].ptr;
3727 else if (r->direction && r->direction != direction)
3728 r = r->skip[PF_SKIP_DIR].ptr;
3729 else if (r->af && r->af != af)
3730 r = r->skip[PF_SKIP_AF].ptr;
3731 else if (r->proto && r->proto != pd->proto)
3732 r = r->skip[PF_SKIP_PROTO].ptr;
3733 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3734 r->src.neg, kif, M_GETFIB(m)))
3735 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3736 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3737 r->dst.neg, NULL, M_GETFIB(m)))
3738 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3739 else if (r->tos && !(r->tos == pd->tos))
3740 r = TAILQ_NEXT(r, entries);
3741 else if (r->os_fingerprint != PF_OSFP_ANY)
3742 r = TAILQ_NEXT(r, entries);
3743 else if (pd->proto == IPPROTO_UDP &&
3744 (r->src.port_op || r->dst.port_op))
3745 r = TAILQ_NEXT(r, entries);
3746 else if (pd->proto == IPPROTO_TCP &&
3747 (r->src.port_op || r->dst.port_op || r->flagset))
3748 r = TAILQ_NEXT(r, entries);
3749 else if ((pd->proto == IPPROTO_ICMP ||
3750 pd->proto == IPPROTO_ICMPV6) &&
3751 (r->type || r->code))
3752 r = TAILQ_NEXT(r, entries);
3753 else if (r->prob && r->prob <=
3754 (arc4random() % (UINT_MAX - 1) + 1))
3755 r = TAILQ_NEXT(r, entries);
3756 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3757 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3758 r = TAILQ_NEXT(r, entries);
3760 if (r->anchor == NULL) {
3767 r = TAILQ_NEXT(r, entries);
3769 pf_step_into_anchor(anchor_stack, &asd,
3770 &ruleset, PF_RULESET_FILTER, &r, &a,
3773 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3774 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3781 REASON_SET(&reason, PFRES_MATCH);
3784 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3787 if (r->action != PF_PASS)
3790 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3791 REASON_SET(&reason, PFRES_MEMORY);
3799 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3800 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3801 struct pf_pdesc *pd, u_short *reason, int *copyback)
3803 struct tcphdr *th = pd->hdr.tcp;
3804 u_int16_t win = ntohs(th->th_win);
3805 u_int32_t ack, end, seq, orig_seq;
3809 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3810 sws = src->wscale & PF_WSCALE_MASK;
3811 dws = dst->wscale & PF_WSCALE_MASK;
3816 * Sequence tracking algorithm from Guido van Rooij's paper:
3817 * http://www.madison-gurkha.com/publications/tcp_filtering/
3821 orig_seq = seq = ntohl(th->th_seq);
3822 if (src->seqlo == 0) {
3823 /* First packet from this end. Set its state */
3825 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3826 src->scrub == NULL) {
3827 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3828 REASON_SET(reason, PFRES_MEMORY);
3833 /* Deferred generation of sequence number modulator */
3834 if (dst->seqdiff && !src->seqdiff) {
3835 /* use random iss for the TCP server */
3836 while ((src->seqdiff = arc4random() - seq) == 0)
3838 ack = ntohl(th->th_ack) - dst->seqdiff;
3839 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3841 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3844 ack = ntohl(th->th_ack);
3847 end = seq + pd->p_len;
3848 if (th->th_flags & TH_SYN) {
3850 if (dst->wscale & PF_WSCALE_FLAG) {
3851 src->wscale = pf_get_wscale(m, off, th->th_off,
3853 if (src->wscale & PF_WSCALE_FLAG) {
3854 /* Remove scale factor from initial
3856 sws = src->wscale & PF_WSCALE_MASK;
3857 win = ((u_int32_t)win + (1 << sws) - 1)
3859 dws = dst->wscale & PF_WSCALE_MASK;
3861 /* fixup other window */
3862 dst->max_win <<= dst->wscale &
3864 /* in case of a retrans SYN|ACK */
3869 if (th->th_flags & TH_FIN)
3873 if (src->state < TCPS_SYN_SENT)
3874 src->state = TCPS_SYN_SENT;
3877 * May need to slide the window (seqhi may have been set by
3878 * the crappy stack check or if we picked up the connection
3879 * after establishment)
3881 if (src->seqhi == 1 ||
3882 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3883 src->seqhi = end + MAX(1, dst->max_win << dws);
3884 if (win > src->max_win)
3888 ack = ntohl(th->th_ack) - dst->seqdiff;
3890 /* Modulate sequence numbers */
3891 pf_change_proto_a(m, &th->th_seq, &th->th_sum, htonl(seq +
3893 pf_change_proto_a(m, &th->th_ack, &th->th_sum, htonl(ack), 0);
3896 end = seq + pd->p_len;
3897 if (th->th_flags & TH_SYN)
3899 if (th->th_flags & TH_FIN)
3903 if ((th->th_flags & TH_ACK) == 0) {
3904 /* Let it pass through the ack skew check */
3906 } else if ((ack == 0 &&
3907 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3908 /* broken tcp stacks do not set ack */
3909 (dst->state < TCPS_SYN_SENT)) {
3911 * Many stacks (ours included) will set the ACK number in an
3912 * FIN|ACK if the SYN times out -- no sequence to ACK.
3918 /* Ease sequencing restrictions on no data packets */
3923 ackskew = dst->seqlo - ack;
3927 * Need to demodulate the sequence numbers in any TCP SACK options
3928 * (Selective ACK). We could optionally validate the SACK values
3929 * against the current ACK window, either forwards or backwards, but
3930 * I'm not confident that SACK has been implemented properly
3931 * everywhere. It wouldn't surprise me if several stacks accidently
3932 * SACK too far backwards of previously ACKed data. There really aren't
3933 * any security implications of bad SACKing unless the target stack
3934 * doesn't validate the option length correctly. Someone trying to
3935 * spoof into a TCP connection won't bother blindly sending SACK
3938 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3939 if (pf_modulate_sack(m, off, pd, th, dst))
3944 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
3945 if (SEQ_GEQ(src->seqhi, end) &&
3946 /* Last octet inside other's window space */
3947 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3948 /* Retrans: not more than one window back */
3949 (ackskew >= -MAXACKWINDOW) &&
3950 /* Acking not more than one reassembled fragment backwards */
3951 (ackskew <= (MAXACKWINDOW << sws)) &&
3952 /* Acking not more than one window forward */
3953 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3954 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3955 (pd->flags & PFDESC_IP_REAS) == 0)) {
3956 /* Require an exact/+1 sequence match on resets when possible */
3958 if (dst->scrub || src->scrub) {
3959 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3960 *state, src, dst, copyback))
3964 /* update max window */
3965 if (src->max_win < win)
3967 /* synchronize sequencing */
3968 if (SEQ_GT(end, src->seqlo))
3970 /* slide the window of what the other end can send */
3971 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3972 dst->seqhi = ack + MAX((win << sws), 1);
3976 if (th->th_flags & TH_SYN)
3977 if (src->state < TCPS_SYN_SENT)
3978 src->state = TCPS_SYN_SENT;
3979 if (th->th_flags & TH_FIN)
3980 if (src->state < TCPS_CLOSING)
3981 src->state = TCPS_CLOSING;
3982 if (th->th_flags & TH_ACK) {
3983 if (dst->state == TCPS_SYN_SENT) {
3984 dst->state = TCPS_ESTABLISHED;
3985 if (src->state == TCPS_ESTABLISHED &&
3986 (*state)->src_node != NULL &&
3987 pf_src_connlimit(state)) {
3988 REASON_SET(reason, PFRES_SRCLIMIT);
3991 } else if (dst->state == TCPS_CLOSING)
3992 dst->state = TCPS_FIN_WAIT_2;
3994 if (th->th_flags & TH_RST)
3995 src->state = dst->state = TCPS_TIME_WAIT;
3997 /* update expire time */
3998 (*state)->expire = time_uptime;
3999 if (src->state >= TCPS_FIN_WAIT_2 &&
4000 dst->state >= TCPS_FIN_WAIT_2)
4001 (*state)->timeout = PFTM_TCP_CLOSED;
4002 else if (src->state >= TCPS_CLOSING &&
4003 dst->state >= TCPS_CLOSING)
4004 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4005 else if (src->state < TCPS_ESTABLISHED ||
4006 dst->state < TCPS_ESTABLISHED)
4007 (*state)->timeout = PFTM_TCP_OPENING;
4008 else if (src->state >= TCPS_CLOSING ||
4009 dst->state >= TCPS_CLOSING)
4010 (*state)->timeout = PFTM_TCP_CLOSING;
4012 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4014 /* Fall through to PASS packet */
4016 } else if ((dst->state < TCPS_SYN_SENT ||
4017 dst->state >= TCPS_FIN_WAIT_2 ||
4018 src->state >= TCPS_FIN_WAIT_2) &&
4019 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4020 /* Within a window forward of the originating packet */
4021 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4022 /* Within a window backward of the originating packet */
4025 * This currently handles three situations:
4026 * 1) Stupid stacks will shotgun SYNs before their peer
4028 * 2) When PF catches an already established stream (the
4029 * firewall rebooted, the state table was flushed, routes
4031 * 3) Packets get funky immediately after the connection
4032 * closes (this should catch Solaris spurious ACK|FINs
4033 * that web servers like to spew after a close)
4035 * This must be a little more careful than the above code
4036 * since packet floods will also be caught here. We don't
4037 * update the TTL here to mitigate the damage of a packet
4038 * flood and so the same code can handle awkward establishment
4039 * and a loosened connection close.
4040 * In the establishment case, a correct peer response will
4041 * validate the connection, go through the normal state code
4042 * and keep updating the state TTL.
4045 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4046 printf("pf: loose state match: ");
4047 pf_print_state(*state);
4048 pf_print_flags(th->th_flags);
4049 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4050 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4051 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4052 (unsigned long long)(*state)->packets[1],
4053 pd->dir == PF_IN ? "in" : "out",
4054 pd->dir == (*state)->direction ? "fwd" : "rev");
4057 if (dst->scrub || src->scrub) {
4058 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4059 *state, src, dst, copyback))
4063 /* update max window */
4064 if (src->max_win < win)
4066 /* synchronize sequencing */
4067 if (SEQ_GT(end, src->seqlo))
4069 /* slide the window of what the other end can send */
4070 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4071 dst->seqhi = ack + MAX((win << sws), 1);
4074 * Cannot set dst->seqhi here since this could be a shotgunned
4075 * SYN and not an already established connection.
4078 if (th->th_flags & TH_FIN)
4079 if (src->state < TCPS_CLOSING)
4080 src->state = TCPS_CLOSING;
4081 if (th->th_flags & TH_RST)
4082 src->state = dst->state = TCPS_TIME_WAIT;
4084 /* Fall through to PASS packet */
4087 if ((*state)->dst.state == TCPS_SYN_SENT &&
4088 (*state)->src.state == TCPS_SYN_SENT) {
4089 /* Send RST for state mismatches during handshake */
4090 if (!(th->th_flags & TH_RST))
4091 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4092 pd->dst, pd->src, th->th_dport,
4093 th->th_sport, ntohl(th->th_ack), 0,
4095 (*state)->rule.ptr->return_ttl, 1, 0,
4100 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4101 printf("pf: BAD state: ");
4102 pf_print_state(*state);
4103 pf_print_flags(th->th_flags);
4104 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4105 "pkts=%llu:%llu dir=%s,%s\n",
4106 seq, orig_seq, ack, pd->p_len, ackskew,
4107 (unsigned long long)(*state)->packets[0],
4108 (unsigned long long)(*state)->packets[1],
4109 pd->dir == PF_IN ? "in" : "out",
4110 pd->dir == (*state)->direction ? "fwd" : "rev");
4111 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4112 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4113 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4115 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4116 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4117 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4118 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4120 REASON_SET(reason, PFRES_BADSTATE);
4128 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4129 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4131 struct tcphdr *th = pd->hdr.tcp;
4133 if (th->th_flags & TH_SYN)
4134 if (src->state < TCPS_SYN_SENT)
4135 src->state = TCPS_SYN_SENT;
4136 if (th->th_flags & TH_FIN)
4137 if (src->state < TCPS_CLOSING)
4138 src->state = TCPS_CLOSING;
4139 if (th->th_flags & TH_ACK) {
4140 if (dst->state == TCPS_SYN_SENT) {
4141 dst->state = TCPS_ESTABLISHED;
4142 if (src->state == TCPS_ESTABLISHED &&
4143 (*state)->src_node != NULL &&
4144 pf_src_connlimit(state)) {
4145 REASON_SET(reason, PFRES_SRCLIMIT);
4148 } else if (dst->state == TCPS_CLOSING) {
4149 dst->state = TCPS_FIN_WAIT_2;
4150 } else if (src->state == TCPS_SYN_SENT &&
4151 dst->state < TCPS_SYN_SENT) {
4153 * Handle a special sloppy case where we only see one
4154 * half of the connection. If there is a ACK after
4155 * the initial SYN without ever seeing a packet from
4156 * the destination, set the connection to established.
4158 dst->state = src->state = TCPS_ESTABLISHED;
4159 if ((*state)->src_node != NULL &&
4160 pf_src_connlimit(state)) {
4161 REASON_SET(reason, PFRES_SRCLIMIT);
4164 } else if (src->state == TCPS_CLOSING &&
4165 dst->state == TCPS_ESTABLISHED &&
4168 * Handle the closing of half connections where we
4169 * don't see the full bidirectional FIN/ACK+ACK
4172 dst->state = TCPS_CLOSING;
4175 if (th->th_flags & TH_RST)
4176 src->state = dst->state = TCPS_TIME_WAIT;
4178 /* update expire time */
4179 (*state)->expire = time_uptime;
4180 if (src->state >= TCPS_FIN_WAIT_2 &&
4181 dst->state >= TCPS_FIN_WAIT_2)
4182 (*state)->timeout = PFTM_TCP_CLOSED;
4183 else if (src->state >= TCPS_CLOSING &&
4184 dst->state >= TCPS_CLOSING)
4185 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4186 else if (src->state < TCPS_ESTABLISHED ||
4187 dst->state < TCPS_ESTABLISHED)
4188 (*state)->timeout = PFTM_TCP_OPENING;
4189 else if (src->state >= TCPS_CLOSING ||
4190 dst->state >= TCPS_CLOSING)
4191 (*state)->timeout = PFTM_TCP_CLOSING;
4193 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4199 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4200 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4203 struct pf_state_key_cmp key;
4204 struct tcphdr *th = pd->hdr.tcp;
4206 struct pf_state_peer *src, *dst;
4207 struct pf_state_key *sk;
4209 bzero(&key, sizeof(key));
4211 key.proto = IPPROTO_TCP;
4212 if (direction == PF_IN) { /* wire side, straight */
4213 PF_ACPY(&key.addr[0], pd->src, key.af);
4214 PF_ACPY(&key.addr[1], pd->dst, key.af);
4215 key.port[0] = th->th_sport;
4216 key.port[1] = th->th_dport;
4217 } else { /* stack side, reverse */
4218 PF_ACPY(&key.addr[1], pd->src, key.af);
4219 PF_ACPY(&key.addr[0], pd->dst, key.af);
4220 key.port[1] = th->th_sport;
4221 key.port[0] = th->th_dport;
4224 STATE_LOOKUP(kif, &key, direction, *state, pd);
4226 if (direction == (*state)->direction) {
4227 src = &(*state)->src;
4228 dst = &(*state)->dst;
4230 src = &(*state)->dst;
4231 dst = &(*state)->src;
4234 sk = (*state)->key[pd->didx];
4236 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4237 if (direction != (*state)->direction) {
4238 REASON_SET(reason, PFRES_SYNPROXY);
4239 return (PF_SYNPROXY_DROP);
4241 if (th->th_flags & TH_SYN) {
4242 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4243 REASON_SET(reason, PFRES_SYNPROXY);
4246 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4247 pd->src, th->th_dport, th->th_sport,
4248 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4249 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4250 REASON_SET(reason, PFRES_SYNPROXY);
4251 return (PF_SYNPROXY_DROP);
4252 } else if (!(th->th_flags & TH_ACK) ||
4253 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4254 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4255 REASON_SET(reason, PFRES_SYNPROXY);
4257 } else if ((*state)->src_node != NULL &&
4258 pf_src_connlimit(state)) {
4259 REASON_SET(reason, PFRES_SRCLIMIT);
4262 (*state)->src.state = PF_TCPS_PROXY_DST;
4264 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4265 if (direction == (*state)->direction) {
4266 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4267 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4268 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4269 REASON_SET(reason, PFRES_SYNPROXY);
4272 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4273 if ((*state)->dst.seqhi == 1)
4274 (*state)->dst.seqhi = htonl(arc4random());
4275 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4276 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4277 sk->port[pd->sidx], sk->port[pd->didx],
4278 (*state)->dst.seqhi, 0, TH_SYN, 0,
4279 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4280 REASON_SET(reason, PFRES_SYNPROXY);
4281 return (PF_SYNPROXY_DROP);
4282 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4284 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4285 REASON_SET(reason, PFRES_SYNPROXY);
4288 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4289 (*state)->dst.seqlo = ntohl(th->th_seq);
4290 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4291 pd->src, th->th_dport, th->th_sport,
4292 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4293 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4294 (*state)->tag, NULL);
4295 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4296 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4297 sk->port[pd->sidx], sk->port[pd->didx],
4298 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4299 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4300 (*state)->src.seqdiff = (*state)->dst.seqhi -
4301 (*state)->src.seqlo;
4302 (*state)->dst.seqdiff = (*state)->src.seqhi -
4303 (*state)->dst.seqlo;
4304 (*state)->src.seqhi = (*state)->src.seqlo +
4305 (*state)->dst.max_win;
4306 (*state)->dst.seqhi = (*state)->dst.seqlo +
4307 (*state)->src.max_win;
4308 (*state)->src.wscale = (*state)->dst.wscale = 0;
4309 (*state)->src.state = (*state)->dst.state =
4311 REASON_SET(reason, PFRES_SYNPROXY);
4312 return (PF_SYNPROXY_DROP);
4316 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4317 dst->state >= TCPS_FIN_WAIT_2 &&
4318 src->state >= TCPS_FIN_WAIT_2) {
4319 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4320 printf("pf: state reuse ");
4321 pf_print_state(*state);
4322 pf_print_flags(th->th_flags);
4325 /* XXX make sure it's the same direction ?? */
4326 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4327 pf_unlink_state(*state, PF_ENTER_LOCKED);
4332 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4333 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4336 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4337 ©back) == PF_DROP)
4341 /* translate source/destination address, if necessary */
4342 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4343 struct pf_state_key *nk = (*state)->key[pd->didx];
4345 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4346 nk->port[pd->sidx] != th->th_sport)
4347 pf_change_ap(m, pd->src, &th->th_sport,
4348 pd->ip_sum, &th->th_sum, &nk->addr[pd->sidx],
4349 nk->port[pd->sidx], 0, pd->af);
4351 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4352 nk->port[pd->didx] != th->th_dport)
4353 pf_change_ap(m, pd->dst, &th->th_dport,
4354 pd->ip_sum, &th->th_sum, &nk->addr[pd->didx],
4355 nk->port[pd->didx], 0, pd->af);
4359 /* Copyback sequence modulation or stateful scrub changes if needed */
4361 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4367 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4368 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4370 struct pf_state_peer *src, *dst;
4371 struct pf_state_key_cmp key;
4372 struct udphdr *uh = pd->hdr.udp;
4374 bzero(&key, sizeof(key));
4376 key.proto = IPPROTO_UDP;
4377 if (direction == PF_IN) { /* wire side, straight */
4378 PF_ACPY(&key.addr[0], pd->src, key.af);
4379 PF_ACPY(&key.addr[1], pd->dst, key.af);
4380 key.port[0] = uh->uh_sport;
4381 key.port[1] = uh->uh_dport;
4382 } else { /* stack side, reverse */
4383 PF_ACPY(&key.addr[1], pd->src, key.af);
4384 PF_ACPY(&key.addr[0], pd->dst, key.af);
4385 key.port[1] = uh->uh_sport;
4386 key.port[0] = uh->uh_dport;
4389 STATE_LOOKUP(kif, &key, direction, *state, pd);
4391 if (direction == (*state)->direction) {
4392 src = &(*state)->src;
4393 dst = &(*state)->dst;
4395 src = &(*state)->dst;
4396 dst = &(*state)->src;
4400 if (src->state < PFUDPS_SINGLE)
4401 src->state = PFUDPS_SINGLE;
4402 if (dst->state == PFUDPS_SINGLE)
4403 dst->state = PFUDPS_MULTIPLE;
4405 /* update expire time */
4406 (*state)->expire = time_uptime;
4407 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4408 (*state)->timeout = PFTM_UDP_MULTIPLE;
4410 (*state)->timeout = PFTM_UDP_SINGLE;
4412 /* translate source/destination address, if necessary */
4413 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4414 struct pf_state_key *nk = (*state)->key[pd->didx];
4416 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4417 nk->port[pd->sidx] != uh->uh_sport)
4418 pf_change_ap(m, pd->src, &uh->uh_sport, pd->ip_sum,
4419 &uh->uh_sum, &nk->addr[pd->sidx],
4420 nk->port[pd->sidx], 1, pd->af);
4422 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4423 nk->port[pd->didx] != uh->uh_dport)
4424 pf_change_ap(m, pd->dst, &uh->uh_dport, pd->ip_sum,
4425 &uh->uh_sum, &nk->addr[pd->didx],
4426 nk->port[pd->didx], 1, pd->af);
4427 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4434 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4435 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4437 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4438 u_int16_t icmpid = 0, *icmpsum;
4441 struct pf_state_key_cmp key;
4443 bzero(&key, sizeof(key));
4444 switch (pd->proto) {
4447 icmptype = pd->hdr.icmp->icmp_type;
4448 icmpid = pd->hdr.icmp->icmp_id;
4449 icmpsum = &pd->hdr.icmp->icmp_cksum;
4451 if (icmptype == ICMP_UNREACH ||
4452 icmptype == ICMP_SOURCEQUENCH ||
4453 icmptype == ICMP_REDIRECT ||
4454 icmptype == ICMP_TIMXCEED ||
4455 icmptype == ICMP_PARAMPROB)
4460 case IPPROTO_ICMPV6:
4461 icmptype = pd->hdr.icmp6->icmp6_type;
4462 icmpid = pd->hdr.icmp6->icmp6_id;
4463 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4465 if (icmptype == ICMP6_DST_UNREACH ||
4466 icmptype == ICMP6_PACKET_TOO_BIG ||
4467 icmptype == ICMP6_TIME_EXCEEDED ||
4468 icmptype == ICMP6_PARAM_PROB)
4477 * ICMP query/reply message not related to a TCP/UDP packet.
4478 * Search for an ICMP state.
4481 key.proto = pd->proto;
4482 key.port[0] = key.port[1] = icmpid;
4483 if (direction == PF_IN) { /* wire side, straight */
4484 PF_ACPY(&key.addr[0], pd->src, key.af);
4485 PF_ACPY(&key.addr[1], pd->dst, key.af);
4486 } else { /* stack side, reverse */
4487 PF_ACPY(&key.addr[1], pd->src, key.af);
4488 PF_ACPY(&key.addr[0], pd->dst, key.af);
4491 STATE_LOOKUP(kif, &key, direction, *state, pd);
4493 (*state)->expire = time_uptime;
4494 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4496 /* translate source/destination address, if necessary */
4497 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4498 struct pf_state_key *nk = (*state)->key[pd->didx];
4503 if (PF_ANEQ(pd->src,
4504 &nk->addr[pd->sidx], AF_INET))
4505 pf_change_a(&saddr->v4.s_addr,
4507 nk->addr[pd->sidx].v4.s_addr, 0);
4509 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4511 pf_change_a(&daddr->v4.s_addr,
4513 nk->addr[pd->didx].v4.s_addr, 0);
4516 pd->hdr.icmp->icmp_id) {
4517 pd->hdr.icmp->icmp_cksum =
4519 pd->hdr.icmp->icmp_cksum, icmpid,
4520 nk->port[pd->sidx], 0);
4521 pd->hdr.icmp->icmp_id =
4525 m_copyback(m, off, ICMP_MINLEN,
4526 (caddr_t )pd->hdr.icmp);
4531 if (PF_ANEQ(pd->src,
4532 &nk->addr[pd->sidx], AF_INET6))
4534 &pd->hdr.icmp6->icmp6_cksum,
4535 &nk->addr[pd->sidx], 0);
4537 if (PF_ANEQ(pd->dst,
4538 &nk->addr[pd->didx], AF_INET6))
4540 &pd->hdr.icmp6->icmp6_cksum,
4541 &nk->addr[pd->didx], 0);
4543 m_copyback(m, off, sizeof(struct icmp6_hdr),
4544 (caddr_t )pd->hdr.icmp6);
4553 * ICMP error message in response to a TCP/UDP packet.
4554 * Extract the inner TCP/UDP header and search for that state.
4557 struct pf_pdesc pd2;
4558 bzero(&pd2, sizeof pd2);
4563 struct ip6_hdr h2_6;
4570 /* Payload packet is from the opposite direction. */
4571 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4572 pd2.didx = (direction == PF_IN) ? 0 : 1;
4576 /* offset of h2 in mbuf chain */
4577 ipoff2 = off + ICMP_MINLEN;
4579 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4580 NULL, reason, pd2.af)) {
4581 DPFPRINTF(PF_DEBUG_MISC,
4582 ("pf: ICMP error message too short "
4587 * ICMP error messages don't refer to non-first
4590 if (h2.ip_off & htons(IP_OFFMASK)) {
4591 REASON_SET(reason, PFRES_FRAG);
4595 /* offset of protocol header that follows h2 */
4596 off2 = ipoff2 + (h2.ip_hl << 2);
4598 pd2.proto = h2.ip_p;
4599 pd2.src = (struct pf_addr *)&h2.ip_src;
4600 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4601 pd2.ip_sum = &h2.ip_sum;
4606 ipoff2 = off + sizeof(struct icmp6_hdr);
4608 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4609 NULL, reason, pd2.af)) {
4610 DPFPRINTF(PF_DEBUG_MISC,
4611 ("pf: ICMP error message too short "
4615 pd2.proto = h2_6.ip6_nxt;
4616 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4617 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4619 off2 = ipoff2 + sizeof(h2_6);
4621 switch (pd2.proto) {
4622 case IPPROTO_FRAGMENT:
4624 * ICMPv6 error messages for
4625 * non-first fragments
4627 REASON_SET(reason, PFRES_FRAG);
4630 case IPPROTO_HOPOPTS:
4631 case IPPROTO_ROUTING:
4632 case IPPROTO_DSTOPTS: {
4633 /* get next header and header length */
4634 struct ip6_ext opt6;
4636 if (!pf_pull_hdr(m, off2, &opt6,
4637 sizeof(opt6), NULL, reason,
4639 DPFPRINTF(PF_DEBUG_MISC,
4640 ("pf: ICMPv6 short opt\n"));
4643 if (pd2.proto == IPPROTO_AH)
4644 off2 += (opt6.ip6e_len + 2) * 4;
4646 off2 += (opt6.ip6e_len + 1) * 8;
4647 pd2.proto = opt6.ip6e_nxt;
4648 /* goto the next header */
4655 } while (!terminal);
4660 switch (pd2.proto) {
4664 struct pf_state_peer *src, *dst;
4669 * Only the first 8 bytes of the TCP header can be
4670 * expected. Don't access any TCP header fields after
4671 * th_seq, an ackskew test is not possible.
4673 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4675 DPFPRINTF(PF_DEBUG_MISC,
4676 ("pf: ICMP error message too short "
4682 key.proto = IPPROTO_TCP;
4683 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4684 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4685 key.port[pd2.sidx] = th.th_sport;
4686 key.port[pd2.didx] = th.th_dport;
4688 STATE_LOOKUP(kif, &key, direction, *state, pd);
4690 if (direction == (*state)->direction) {
4691 src = &(*state)->dst;
4692 dst = &(*state)->src;
4694 src = &(*state)->src;
4695 dst = &(*state)->dst;
4698 if (src->wscale && dst->wscale)
4699 dws = dst->wscale & PF_WSCALE_MASK;
4703 /* Demodulate sequence number */
4704 seq = ntohl(th.th_seq) - src->seqdiff;
4706 pf_change_a(&th.th_seq, icmpsum,
4711 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4712 (!SEQ_GEQ(src->seqhi, seq) ||
4713 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4714 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4715 printf("pf: BAD 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);
4724 REASON_SET(reason, PFRES_BADSTATE);
4727 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4728 printf("pf: OK ICMP %d:%d ",
4729 icmptype, pd->hdr.icmp->icmp_code);
4730 pf_print_host(pd->src, 0, pd->af);
4732 pf_print_host(pd->dst, 0, pd->af);
4734 pf_print_state(*state);
4735 printf(" seq=%u\n", seq);
4739 /* translate source/destination address, if necessary */
4740 if ((*state)->key[PF_SK_WIRE] !=
4741 (*state)->key[PF_SK_STACK]) {
4742 struct pf_state_key *nk =
4743 (*state)->key[pd->didx];
4745 if (PF_ANEQ(pd2.src,
4746 &nk->addr[pd2.sidx], pd2.af) ||
4747 nk->port[pd2.sidx] != th.th_sport)
4748 pf_change_icmp(pd2.src, &th.th_sport,
4749 daddr, &nk->addr[pd2.sidx],
4750 nk->port[pd2.sidx], NULL,
4751 pd2.ip_sum, icmpsum,
4752 pd->ip_sum, 0, pd2.af);
4754 if (PF_ANEQ(pd2.dst,
4755 &nk->addr[pd2.didx], pd2.af) ||
4756 nk->port[pd2.didx] != th.th_dport)
4757 pf_change_icmp(pd2.dst, &th.th_dport,
4758 NULL, /* XXX Inbound NAT? */
4759 &nk->addr[pd2.didx],
4760 nk->port[pd2.didx], NULL,
4761 pd2.ip_sum, icmpsum,
4762 pd->ip_sum, 0, pd2.af);
4770 m_copyback(m, off, ICMP_MINLEN,
4771 (caddr_t )pd->hdr.icmp);
4772 m_copyback(m, ipoff2, sizeof(h2),
4779 sizeof(struct icmp6_hdr),
4780 (caddr_t )pd->hdr.icmp6);
4781 m_copyback(m, ipoff2, sizeof(h2_6),
4786 m_copyback(m, off2, 8, (caddr_t)&th);
4795 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4796 NULL, reason, pd2.af)) {
4797 DPFPRINTF(PF_DEBUG_MISC,
4798 ("pf: ICMP error message too short "
4804 key.proto = IPPROTO_UDP;
4805 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4806 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4807 key.port[pd2.sidx] = uh.uh_sport;
4808 key.port[pd2.didx] = uh.uh_dport;
4810 STATE_LOOKUP(kif, &key, direction, *state, pd);
4812 /* translate source/destination address, if necessary */
4813 if ((*state)->key[PF_SK_WIRE] !=
4814 (*state)->key[PF_SK_STACK]) {
4815 struct pf_state_key *nk =
4816 (*state)->key[pd->didx];
4818 if (PF_ANEQ(pd2.src,
4819 &nk->addr[pd2.sidx], pd2.af) ||
4820 nk->port[pd2.sidx] != uh.uh_sport)
4821 pf_change_icmp(pd2.src, &uh.uh_sport,
4822 daddr, &nk->addr[pd2.sidx],
4823 nk->port[pd2.sidx], &uh.uh_sum,
4824 pd2.ip_sum, icmpsum,
4825 pd->ip_sum, 1, pd2.af);
4827 if (PF_ANEQ(pd2.dst,
4828 &nk->addr[pd2.didx], pd2.af) ||
4829 nk->port[pd2.didx] != uh.uh_dport)
4830 pf_change_icmp(pd2.dst, &uh.uh_dport,
4831 NULL, /* XXX Inbound NAT? */
4832 &nk->addr[pd2.didx],
4833 nk->port[pd2.didx], &uh.uh_sum,
4834 pd2.ip_sum, icmpsum,
4835 pd->ip_sum, 1, pd2.af);
4840 m_copyback(m, off, ICMP_MINLEN,
4841 (caddr_t )pd->hdr.icmp);
4842 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4848 sizeof(struct icmp6_hdr),
4849 (caddr_t )pd->hdr.icmp6);
4850 m_copyback(m, ipoff2, sizeof(h2_6),
4855 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4861 case IPPROTO_ICMP: {
4864 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4865 NULL, reason, pd2.af)) {
4866 DPFPRINTF(PF_DEBUG_MISC,
4867 ("pf: ICMP error message too short i"
4873 key.proto = IPPROTO_ICMP;
4874 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4875 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4876 key.port[0] = key.port[1] = iih.icmp_id;
4878 STATE_LOOKUP(kif, &key, direction, *state, pd);
4880 /* translate source/destination address, if necessary */
4881 if ((*state)->key[PF_SK_WIRE] !=
4882 (*state)->key[PF_SK_STACK]) {
4883 struct pf_state_key *nk =
4884 (*state)->key[pd->didx];
4886 if (PF_ANEQ(pd2.src,
4887 &nk->addr[pd2.sidx], pd2.af) ||
4888 nk->port[pd2.sidx] != iih.icmp_id)
4889 pf_change_icmp(pd2.src, &iih.icmp_id,
4890 daddr, &nk->addr[pd2.sidx],
4891 nk->port[pd2.sidx], NULL,
4892 pd2.ip_sum, icmpsum,
4893 pd->ip_sum, 0, AF_INET);
4895 if (PF_ANEQ(pd2.dst,
4896 &nk->addr[pd2.didx], pd2.af) ||
4897 nk->port[pd2.didx] != iih.icmp_id)
4898 pf_change_icmp(pd2.dst, &iih.icmp_id,
4899 NULL, /* XXX Inbound NAT? */
4900 &nk->addr[pd2.didx],
4901 nk->port[pd2.didx], NULL,
4902 pd2.ip_sum, icmpsum,
4903 pd->ip_sum, 0, AF_INET);
4905 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4906 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4907 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4914 case IPPROTO_ICMPV6: {
4915 struct icmp6_hdr iih;
4917 if (!pf_pull_hdr(m, off2, &iih,
4918 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4919 DPFPRINTF(PF_DEBUG_MISC,
4920 ("pf: ICMP error message too short "
4926 key.proto = IPPROTO_ICMPV6;
4927 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4928 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4929 key.port[0] = key.port[1] = iih.icmp6_id;
4931 STATE_LOOKUP(kif, &key, direction, *state, pd);
4933 /* translate source/destination address, if necessary */
4934 if ((*state)->key[PF_SK_WIRE] !=
4935 (*state)->key[PF_SK_STACK]) {
4936 struct pf_state_key *nk =
4937 (*state)->key[pd->didx];
4939 if (PF_ANEQ(pd2.src,
4940 &nk->addr[pd2.sidx], pd2.af) ||
4941 nk->port[pd2.sidx] != iih.icmp6_id)
4942 pf_change_icmp(pd2.src, &iih.icmp6_id,
4943 daddr, &nk->addr[pd2.sidx],
4944 nk->port[pd2.sidx], NULL,
4945 pd2.ip_sum, icmpsum,
4946 pd->ip_sum, 0, AF_INET6);
4948 if (PF_ANEQ(pd2.dst,
4949 &nk->addr[pd2.didx], pd2.af) ||
4950 nk->port[pd2.didx] != iih.icmp6_id)
4951 pf_change_icmp(pd2.dst, &iih.icmp6_id,
4952 NULL, /* XXX Inbound NAT? */
4953 &nk->addr[pd2.didx],
4954 nk->port[pd2.didx], NULL,
4955 pd2.ip_sum, icmpsum,
4956 pd->ip_sum, 0, AF_INET6);
4958 m_copyback(m, off, sizeof(struct icmp6_hdr),
4959 (caddr_t)pd->hdr.icmp6);
4960 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4961 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4970 key.proto = pd2.proto;
4971 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4972 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4973 key.port[0] = key.port[1] = 0;
4975 STATE_LOOKUP(kif, &key, direction, *state, pd);
4977 /* translate source/destination address, if necessary */
4978 if ((*state)->key[PF_SK_WIRE] !=
4979 (*state)->key[PF_SK_STACK]) {
4980 struct pf_state_key *nk =
4981 (*state)->key[pd->didx];
4983 if (PF_ANEQ(pd2.src,
4984 &nk->addr[pd2.sidx], pd2.af))
4985 pf_change_icmp(pd2.src, NULL, daddr,
4986 &nk->addr[pd2.sidx], 0, NULL,
4987 pd2.ip_sum, icmpsum,
4988 pd->ip_sum, 0, pd2.af);
4990 if (PF_ANEQ(pd2.dst,
4991 &nk->addr[pd2.didx], pd2.af))
4992 pf_change_icmp(pd2.src, NULL,
4993 NULL, /* XXX Inbound NAT? */
4994 &nk->addr[pd2.didx], 0, NULL,
4995 pd2.ip_sum, icmpsum,
4996 pd->ip_sum, 0, pd2.af);
5001 m_copyback(m, off, ICMP_MINLEN,
5002 (caddr_t)pd->hdr.icmp);
5003 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5009 sizeof(struct icmp6_hdr),
5010 (caddr_t )pd->hdr.icmp6);
5011 m_copyback(m, ipoff2, sizeof(h2_6),
5025 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5026 struct mbuf *m, struct pf_pdesc *pd)
5028 struct pf_state_peer *src, *dst;
5029 struct pf_state_key_cmp key;
5031 bzero(&key, sizeof(key));
5033 key.proto = pd->proto;
5034 if (direction == PF_IN) {
5035 PF_ACPY(&key.addr[0], pd->src, key.af);
5036 PF_ACPY(&key.addr[1], pd->dst, key.af);
5037 key.port[0] = key.port[1] = 0;
5039 PF_ACPY(&key.addr[1], pd->src, key.af);
5040 PF_ACPY(&key.addr[0], pd->dst, key.af);
5041 key.port[1] = key.port[0] = 0;
5044 STATE_LOOKUP(kif, &key, direction, *state, pd);
5046 if (direction == (*state)->direction) {
5047 src = &(*state)->src;
5048 dst = &(*state)->dst;
5050 src = &(*state)->dst;
5051 dst = &(*state)->src;
5055 if (src->state < PFOTHERS_SINGLE)
5056 src->state = PFOTHERS_SINGLE;
5057 if (dst->state == PFOTHERS_SINGLE)
5058 dst->state = PFOTHERS_MULTIPLE;
5060 /* update expire time */
5061 (*state)->expire = time_uptime;
5062 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5063 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5065 (*state)->timeout = PFTM_OTHER_SINGLE;
5067 /* translate source/destination address, if necessary */
5068 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5069 struct pf_state_key *nk = (*state)->key[pd->didx];
5071 KASSERT(nk, ("%s: nk is null", __func__));
5072 KASSERT(pd, ("%s: pd is null", __func__));
5073 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5074 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5078 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5079 pf_change_a(&pd->src->v4.s_addr,
5081 nk->addr[pd->sidx].v4.s_addr,
5085 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5086 pf_change_a(&pd->dst->v4.s_addr,
5088 nk->addr[pd->didx].v4.s_addr,
5095 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5096 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5098 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5099 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5107 * ipoff and off are measured from the start of the mbuf chain.
5108 * h must be at "ipoff" on the mbuf chain.
5111 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5112 u_short *actionp, u_short *reasonp, sa_family_t af)
5117 struct ip *h = mtod(m, struct ip *);
5118 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5122 ACTION_SET(actionp, PF_PASS);
5124 ACTION_SET(actionp, PF_DROP);
5125 REASON_SET(reasonp, PFRES_FRAG);
5129 if (m->m_pkthdr.len < off + len ||
5130 ntohs(h->ip_len) < off + len) {
5131 ACTION_SET(actionp, PF_DROP);
5132 REASON_SET(reasonp, PFRES_SHORT);
5140 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5142 if (m->m_pkthdr.len < off + len ||
5143 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5144 (unsigned)(off + len)) {
5145 ACTION_SET(actionp, PF_DROP);
5146 REASON_SET(reasonp, PFRES_SHORT);
5153 m_copydata(m, off, len, p);
5158 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5162 struct radix_node_head *rnh;
5164 struct sockaddr_in *dst;
5168 struct sockaddr_in6 *dst6;
5169 struct route_in6 ro;
5173 struct radix_node *rn;
5179 /* XXX: stick to table 0 for now */
5180 rnh = rt_tables_get_rnh(0, af);
5181 if (rnh != NULL && rn_mpath_capable(rnh))
5184 bzero(&ro, sizeof(ro));
5187 dst = satosin(&ro.ro_dst);
5188 dst->sin_family = AF_INET;
5189 dst->sin_len = sizeof(*dst);
5190 dst->sin_addr = addr->v4;
5195 * Skip check for addresses with embedded interface scope,
5196 * as they would always match anyway.
5198 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5200 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5201 dst6->sin6_family = AF_INET6;
5202 dst6->sin6_len = sizeof(*dst6);
5203 dst6->sin6_addr = addr->v6;
5210 /* Skip checks for ipsec interfaces */
5211 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5217 in6_rtalloc_ign(&ro, 0, rtableid);
5222 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5226 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5230 if (ro.ro_rt != NULL) {
5231 /* No interface given, this is a no-route check */
5235 if (kif->pfik_ifp == NULL) {
5240 /* Perform uRPF check if passed input interface */
5242 rn = (struct radix_node *)ro.ro_rt;
5244 rt = (struct rtentry *)rn;
5247 if (kif->pfik_ifp == ifp)
5250 rn = rn_mpath_next(rn);
5252 } while (check_mpath == 1 && rn != NULL && ret == 0);
5256 if (ro.ro_rt != NULL)
5263 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5264 struct pf_state *s, struct pf_pdesc *pd)
5266 struct mbuf *m0, *m1;
5267 struct sockaddr_in dst;
5269 struct ifnet *ifp = NULL;
5270 struct pf_addr naddr;
5271 struct pf_src_node *sn = NULL;
5273 uint16_t ip_len, ip_off;
5275 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5276 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5279 if ((pd->pf_mtag == NULL &&
5280 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5281 pd->pf_mtag->routed++ > 3) {
5287 if (r->rt == PF_DUPTO) {
5288 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5294 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5302 ip = mtod(m0, struct ip *);
5304 bzero(&dst, sizeof(dst));
5305 dst.sin_family = AF_INET;
5306 dst.sin_len = sizeof(dst);
5307 dst.sin_addr = ip->ip_dst;
5309 if (r->rt == PF_FASTROUTE) {
5314 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5316 KMOD_IPSTAT_INC(ips_noroute);
5317 error = EHOSTUNREACH;
5322 counter_u64_add(rt->rt_pksent, 1);
5324 if (rt->rt_flags & RTF_GATEWAY)
5325 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5328 if (TAILQ_EMPTY(&r->rpool.list)) {
5329 DPFPRINTF(PF_DEBUG_URGENT,
5330 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5334 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5336 if (!PF_AZERO(&naddr, AF_INET))
5337 dst.sin_addr.s_addr = naddr.v4.s_addr;
5338 ifp = r->rpool.cur->kif ?
5339 r->rpool.cur->kif->pfik_ifp : NULL;
5341 if (!PF_AZERO(&s->rt_addr, AF_INET))
5342 dst.sin_addr.s_addr =
5343 s->rt_addr.v4.s_addr;
5344 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5352 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5354 else if (m0 == NULL)
5356 if (m0->m_len < sizeof(struct ip)) {
5357 DPFPRINTF(PF_DEBUG_URGENT,
5358 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5361 ip = mtod(m0, struct ip *);
5364 if (ifp->if_flags & IFF_LOOPBACK)
5365 m0->m_flags |= M_SKIP_FIREWALL;
5367 ip_len = ntohs(ip->ip_len);
5368 ip_off = ntohs(ip->ip_off);
5370 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5371 m0->m_pkthdr.csum_flags |= CSUM_IP;
5372 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5373 in_delayed_cksum(m0);
5374 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5377 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5378 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5379 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5384 * If small enough for interface, or the interface will take
5385 * care of the fragmentation for us, we can just send directly.
5387 if (ip_len <= ifp->if_mtu ||
5388 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5389 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5391 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5392 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5393 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5395 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5396 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5400 /* Balk when DF bit is set or the interface didn't support TSO. */
5401 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5403 KMOD_IPSTAT_INC(ips_cantfrag);
5404 if (r->rt != PF_DUPTO) {
5405 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5412 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5416 for (; m0; m0 = m1) {
5418 m0->m_nextpkt = NULL;
5420 m_clrprotoflags(m0);
5421 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5427 KMOD_IPSTAT_INC(ips_fragmented);
5430 if (r->rt != PF_DUPTO)
5445 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5446 struct pf_state *s, struct pf_pdesc *pd)
5449 struct sockaddr_in6 dst;
5450 struct ip6_hdr *ip6;
5451 struct ifnet *ifp = NULL;
5452 struct pf_addr naddr;
5453 struct pf_src_node *sn = NULL;
5455 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5456 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5459 if ((pd->pf_mtag == NULL &&
5460 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5461 pd->pf_mtag->routed++ > 3) {
5467 if (r->rt == PF_DUPTO) {
5468 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5474 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5482 ip6 = mtod(m0, struct ip6_hdr *);
5484 bzero(&dst, sizeof(dst));
5485 dst.sin6_family = AF_INET6;
5486 dst.sin6_len = sizeof(dst);
5487 dst.sin6_addr = ip6->ip6_dst;
5489 /* Cheat. XXX why only in the v6 case??? */
5490 if (r->rt == PF_FASTROUTE) {
5493 m0->m_flags |= M_SKIP_FIREWALL;
5494 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5498 if (TAILQ_EMPTY(&r->rpool.list)) {
5499 DPFPRINTF(PF_DEBUG_URGENT,
5500 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5504 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5506 if (!PF_AZERO(&naddr, AF_INET6))
5507 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5509 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5511 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5512 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5513 &s->rt_addr, AF_INET6);
5514 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5524 if (pf_test6(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5526 else if (m0 == NULL)
5528 if (m0->m_len < sizeof(struct ip6_hdr)) {
5529 DPFPRINTF(PF_DEBUG_URGENT,
5530 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5534 ip6 = mtod(m0, struct ip6_hdr *);
5537 if (ifp->if_flags & IFF_LOOPBACK)
5538 m0->m_flags |= M_SKIP_FIREWALL;
5540 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6 &
5541 ~ifp->if_hwassist) {
5542 uint32_t plen = m0->m_pkthdr.len - sizeof(*ip6);
5543 in6_delayed_cksum(m0, plen, sizeof(struct ip6_hdr));
5544 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
5548 * If the packet is too large for the outgoing interface,
5549 * send back an icmp6 error.
5551 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5552 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5553 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5554 nd6_output(ifp, ifp, m0, &dst, NULL);
5556 in6_ifstat_inc(ifp, ifs6_in_toobig);
5557 if (r->rt != PF_DUPTO)
5558 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5564 if (r->rt != PF_DUPTO)
5578 * FreeBSD supports cksum offloads for the following drivers.
5579 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5580 * ti(4), txp(4), xl(4)
5582 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5583 * network driver performed cksum including pseudo header, need to verify
5586 * network driver performed cksum, needs to additional pseudo header
5587 * cksum computation with partial csum_data(i.e. lack of H/W support for
5588 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5590 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5591 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5593 * Also, set csum_data to 0xffff to force cksum validation.
5596 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5602 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5604 if (m->m_pkthdr.len < off + len)
5609 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5610 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5611 sum = m->m_pkthdr.csum_data;
5613 ip = mtod(m, struct ip *);
5614 sum = in_pseudo(ip->ip_src.s_addr,
5615 ip->ip_dst.s_addr, htonl((u_short)len +
5616 m->m_pkthdr.csum_data + IPPROTO_TCP));
5623 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5624 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5625 sum = m->m_pkthdr.csum_data;
5627 ip = mtod(m, struct ip *);
5628 sum = in_pseudo(ip->ip_src.s_addr,
5629 ip->ip_dst.s_addr, htonl((u_short)len +
5630 m->m_pkthdr.csum_data + IPPROTO_UDP));
5638 case IPPROTO_ICMPV6:
5648 if (p == IPPROTO_ICMP) {
5653 sum = in_cksum(m, len);
5657 if (m->m_len < sizeof(struct ip))
5659 sum = in4_cksum(m, p, off, len);
5664 if (m->m_len < sizeof(struct ip6_hdr))
5666 sum = in6_cksum(m, p, off, len);
5677 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5682 KMOD_UDPSTAT_INC(udps_badsum);
5688 KMOD_ICMPSTAT_INC(icps_checksum);
5693 case IPPROTO_ICMPV6:
5695 KMOD_ICMP6STAT_INC(icp6s_checksum);
5702 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5703 m->m_pkthdr.csum_flags |=
5704 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5705 m->m_pkthdr.csum_data = 0xffff;
5714 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5716 struct pfi_kif *kif;
5717 u_short action, reason = 0, log = 0;
5718 struct mbuf *m = *m0;
5719 struct ip *h = NULL;
5720 struct m_tag *ipfwtag;
5721 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5722 struct pf_state *s = NULL;
5723 struct pf_ruleset *ruleset = NULL;
5725 int off, dirndx, pqid = 0;
5729 if (!V_pf_status.running)
5732 memset(&pd, 0, sizeof(pd));
5734 kif = (struct pfi_kif *)ifp->if_pf_kif;
5737 DPFPRINTF(PF_DEBUG_URGENT,
5738 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5741 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5744 if (m->m_flags & M_SKIP_FIREWALL)
5747 pd.pf_mtag = pf_find_mtag(m);
5751 if (ip_divert_ptr != NULL &&
5752 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5753 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5754 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5755 if (pd.pf_mtag == NULL &&
5756 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5760 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5761 m_tag_delete(m, ipfwtag);
5763 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5764 m->m_flags |= M_FASTFWD_OURS;
5765 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5767 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5768 /* We do IP header normalization and packet reassembly here */
5772 m = *m0; /* pf_normalize messes with m0 */
5773 h = mtod(m, struct ip *);
5775 off = h->ip_hl << 2;
5776 if (off < (int)sizeof(struct ip)) {
5778 REASON_SET(&reason, PFRES_SHORT);
5783 pd.src = (struct pf_addr *)&h->ip_src;
5784 pd.dst = (struct pf_addr *)&h->ip_dst;
5785 pd.sport = pd.dport = NULL;
5786 pd.ip_sum = &h->ip_sum;
5787 pd.proto_sum = NULL;
5790 pd.sidx = (dir == PF_IN) ? 0 : 1;
5791 pd.didx = (dir == PF_IN) ? 1 : 0;
5794 pd.tot_len = ntohs(h->ip_len);
5796 /* handle fragments that didn't get reassembled by normalization */
5797 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5798 action = pf_test_fragment(&r, dir, kif, m, h,
5809 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5810 &action, &reason, AF_INET)) {
5811 log = action != PF_PASS;
5814 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5815 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5817 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5818 if (action == PF_DROP)
5820 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5822 if (action == PF_PASS) {
5823 if (pfsync_update_state_ptr != NULL)
5824 pfsync_update_state_ptr(s);
5828 } else if (s == NULL)
5829 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5838 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5839 &action, &reason, AF_INET)) {
5840 log = action != PF_PASS;
5843 if (uh.uh_dport == 0 ||
5844 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5845 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5847 REASON_SET(&reason, PFRES_SHORT);
5850 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5851 if (action == PF_PASS) {
5852 if (pfsync_update_state_ptr != NULL)
5853 pfsync_update_state_ptr(s);
5857 } else if (s == NULL)
5858 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5863 case IPPROTO_ICMP: {
5867 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5868 &action, &reason, AF_INET)) {
5869 log = action != PF_PASS;
5872 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5874 if (action == PF_PASS) {
5875 if (pfsync_update_state_ptr != NULL)
5876 pfsync_update_state_ptr(s);
5880 } else if (s == NULL)
5881 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5887 case IPPROTO_ICMPV6: {
5889 DPFPRINTF(PF_DEBUG_MISC,
5890 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5896 action = pf_test_state_other(&s, dir, kif, m, &pd);
5897 if (action == PF_PASS) {
5898 if (pfsync_update_state_ptr != NULL)
5899 pfsync_update_state_ptr(s);
5903 } else if (s == NULL)
5904 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5911 if (action == PF_PASS && h->ip_hl > 5 &&
5912 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5914 REASON_SET(&reason, PFRES_IPOPTIONS);
5916 DPFPRINTF(PF_DEBUG_MISC,
5917 ("pf: dropping packet with ip options\n"));
5920 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5922 REASON_SET(&reason, PFRES_MEMORY);
5924 if (r->rtableid >= 0)
5925 M_SETFIB(m, r->rtableid);
5928 if (action == PF_PASS && r->qid) {
5929 if (pd.pf_mtag == NULL &&
5930 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5932 REASON_SET(&reason, PFRES_MEMORY);
5934 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5935 pd.pf_mtag->qid = r->pqid;
5937 pd.pf_mtag->qid = r->qid;
5938 /* add hints for ecn */
5939 pd.pf_mtag->hdr = h;
5945 * connections redirected to loopback should not match sockets
5946 * bound specifically to loopback due to security implications,
5947 * see tcp_input() and in_pcblookup_listen().
5949 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5950 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5951 (s->nat_rule.ptr->action == PF_RDR ||
5952 s->nat_rule.ptr->action == PF_BINAT) &&
5953 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5954 m->m_flags |= M_SKIP_FIREWALL;
5956 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5957 !PACKET_LOOPED(&pd)) {
5959 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5960 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5961 if (ipfwtag != NULL) {
5962 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5963 ntohs(r->divert.port);
5964 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5969 m_tag_prepend(m, ipfwtag);
5970 if (m->m_flags & M_FASTFWD_OURS) {
5971 if (pd.pf_mtag == NULL &&
5972 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5974 REASON_SET(&reason, PFRES_MEMORY);
5976 DPFPRINTF(PF_DEBUG_MISC,
5977 ("pf: failed to allocate tag\n"));
5979 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5980 m->m_flags &= ~M_FASTFWD_OURS;
5982 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
5987 /* XXX: ipfw has the same behaviour! */
5989 REASON_SET(&reason, PFRES_MEMORY);
5991 DPFPRINTF(PF_DEBUG_MISC,
5992 ("pf: failed to allocate divert tag\n"));
5999 if (s != NULL && s->nat_rule.ptr != NULL &&
6000 s->nat_rule.ptr->log & PF_LOG_ALL)
6001 lr = s->nat_rule.ptr;
6004 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6008 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6009 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6011 if (action == PF_PASS || r->action == PF_DROP) {
6012 dirndx = (dir == PF_OUT);
6013 r->packets[dirndx]++;
6014 r->bytes[dirndx] += pd.tot_len;
6016 a->packets[dirndx]++;
6017 a->bytes[dirndx] += pd.tot_len;
6020 if (s->nat_rule.ptr != NULL) {
6021 s->nat_rule.ptr->packets[dirndx]++;
6022 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6024 if (s->src_node != NULL) {
6025 s->src_node->packets[dirndx]++;
6026 s->src_node->bytes[dirndx] += pd.tot_len;
6028 if (s->nat_src_node != NULL) {
6029 s->nat_src_node->packets[dirndx]++;
6030 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6032 dirndx = (dir == s->direction) ? 0 : 1;
6033 s->packets[dirndx]++;
6034 s->bytes[dirndx] += pd.tot_len;
6037 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6038 if (nr != NULL && r == &V_pf_default_rule)
6040 if (tr->src.addr.type == PF_ADDR_TABLE)
6041 pfr_update_stats(tr->src.addr.p.tbl,
6042 (s == NULL) ? pd.src :
6043 &s->key[(s->direction == PF_IN)]->
6044 addr[(s->direction == PF_OUT)],
6045 pd.af, pd.tot_len, dir == PF_OUT,
6046 r->action == PF_PASS, tr->src.neg);
6047 if (tr->dst.addr.type == PF_ADDR_TABLE)
6048 pfr_update_stats(tr->dst.addr.p.tbl,
6049 (s == NULL) ? pd.dst :
6050 &s->key[(s->direction == PF_IN)]->
6051 addr[(s->direction == PF_IN)],
6052 pd.af, pd.tot_len, dir == PF_OUT,
6053 r->action == PF_PASS, tr->dst.neg);
6057 case PF_SYNPROXY_DROP:
6068 /* pf_route() returns unlocked. */
6070 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6084 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6086 struct pfi_kif *kif;
6087 u_short action, reason = 0, log = 0;
6088 struct mbuf *m = *m0, *n = NULL;
6089 struct ip6_hdr *h = NULL;
6090 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6091 struct pf_state *s = NULL;
6092 struct pf_ruleset *ruleset = NULL;
6094 int off, terminal = 0, dirndx, rh_cnt = 0;
6098 if (!V_pf_status.running)
6101 memset(&pd, 0, sizeof(pd));
6102 pd.pf_mtag = pf_find_mtag(m);
6104 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6107 kif = (struct pfi_kif *)ifp->if_pf_kif;
6109 DPFPRINTF(PF_DEBUG_URGENT,
6110 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6113 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6116 if (m->m_flags & M_SKIP_FIREWALL)
6121 /* We do IP header normalization and packet reassembly here */
6122 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6126 m = *m0; /* pf_normalize messes with m0 */
6127 h = mtod(m, struct ip6_hdr *);
6131 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6132 * will do something bad, so drop the packet for now.
6134 if (htons(h->ip6_plen) == 0) {
6136 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6141 pd.src = (struct pf_addr *)&h->ip6_src;
6142 pd.dst = (struct pf_addr *)&h->ip6_dst;
6143 pd.sport = pd.dport = NULL;
6145 pd.proto_sum = NULL;
6147 pd.sidx = (dir == PF_IN) ? 0 : 1;
6148 pd.didx = (dir == PF_IN) ? 1 : 0;
6151 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6153 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6154 pd.proto = h->ip6_nxt;
6157 case IPPROTO_FRAGMENT:
6158 action = pf_test_fragment(&r, dir, kif, m, h,
6160 if (action == PF_DROP)
6161 REASON_SET(&reason, PFRES_FRAG);
6163 case IPPROTO_ROUTING: {
6164 struct ip6_rthdr rthdr;
6167 DPFPRINTF(PF_DEBUG_MISC,
6168 ("pf: IPv6 more than one rthdr\n"));
6170 REASON_SET(&reason, PFRES_IPOPTIONS);
6174 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6176 DPFPRINTF(PF_DEBUG_MISC,
6177 ("pf: IPv6 short rthdr\n"));
6179 REASON_SET(&reason, PFRES_SHORT);
6183 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6184 DPFPRINTF(PF_DEBUG_MISC,
6185 ("pf: IPv6 rthdr0\n"));
6187 REASON_SET(&reason, PFRES_IPOPTIONS);
6194 case IPPROTO_HOPOPTS:
6195 case IPPROTO_DSTOPTS: {
6196 /* get next header and header length */
6197 struct ip6_ext opt6;
6199 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6200 NULL, &reason, pd.af)) {
6201 DPFPRINTF(PF_DEBUG_MISC,
6202 ("pf: IPv6 short opt\n"));
6207 if (pd.proto == IPPROTO_AH)
6208 off += (opt6.ip6e_len + 2) * 4;
6210 off += (opt6.ip6e_len + 1) * 8;
6211 pd.proto = opt6.ip6e_nxt;
6212 /* goto the next header */
6219 } while (!terminal);
6221 /* if there's no routing header, use unmodified mbuf for checksumming */
6231 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6232 &action, &reason, AF_INET6)) {
6233 log = action != PF_PASS;
6236 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6237 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6238 if (action == PF_DROP)
6240 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6242 if (action == PF_PASS) {
6243 if (pfsync_update_state_ptr != NULL)
6244 pfsync_update_state_ptr(s);
6248 } else if (s == NULL)
6249 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6258 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6259 &action, &reason, AF_INET6)) {
6260 log = action != PF_PASS;
6263 if (uh.uh_dport == 0 ||
6264 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6265 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6267 REASON_SET(&reason, PFRES_SHORT);
6270 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6271 if (action == PF_PASS) {
6272 if (pfsync_update_state_ptr != NULL)
6273 pfsync_update_state_ptr(s);
6277 } else if (s == NULL)
6278 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6283 case IPPROTO_ICMP: {
6285 DPFPRINTF(PF_DEBUG_MISC,
6286 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6290 case IPPROTO_ICMPV6: {
6291 struct icmp6_hdr ih;
6294 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6295 &action, &reason, AF_INET6)) {
6296 log = action != PF_PASS;
6299 action = pf_test_state_icmp(&s, dir, kif,
6300 m, off, h, &pd, &reason);
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,
6314 action = pf_test_state_other(&s, dir, kif, m, &pd);
6315 if (action == PF_PASS) {
6316 if (pfsync_update_state_ptr != NULL)
6317 pfsync_update_state_ptr(s);
6321 } else if (s == NULL)
6322 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6334 /* handle dangerous IPv6 extension headers. */
6335 if (action == PF_PASS && rh_cnt &&
6336 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6338 REASON_SET(&reason, PFRES_IPOPTIONS);
6340 DPFPRINTF(PF_DEBUG_MISC,
6341 ("pf: dropping packet with dangerous v6 headers\n"));
6344 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6346 REASON_SET(&reason, PFRES_MEMORY);
6348 if (r->rtableid >= 0)
6349 M_SETFIB(m, r->rtableid);
6352 if (action == PF_PASS && r->qid) {
6353 if (pd.pf_mtag == NULL &&
6354 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6356 REASON_SET(&reason, PFRES_MEMORY);
6358 if (pd.tos & IPTOS_LOWDELAY)
6359 pd.pf_mtag->qid = r->pqid;
6361 pd.pf_mtag->qid = r->qid;
6362 /* add hints for ecn */
6363 pd.pf_mtag->hdr = h;
6367 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6368 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6369 (s->nat_rule.ptr->action == PF_RDR ||
6370 s->nat_rule.ptr->action == PF_BINAT) &&
6371 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6372 m->m_flags |= M_SKIP_FIREWALL;
6374 /* XXX: Anybody working on it?! */
6376 printf("pf: divert(9) is not supported for IPv6\n");
6381 if (s != NULL && s->nat_rule.ptr != NULL &&
6382 s->nat_rule.ptr->log & PF_LOG_ALL)
6383 lr = s->nat_rule.ptr;
6386 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6390 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6391 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6393 if (action == PF_PASS || r->action == PF_DROP) {
6394 dirndx = (dir == PF_OUT);
6395 r->packets[dirndx]++;
6396 r->bytes[dirndx] += pd.tot_len;
6398 a->packets[dirndx]++;
6399 a->bytes[dirndx] += pd.tot_len;
6402 if (s->nat_rule.ptr != NULL) {
6403 s->nat_rule.ptr->packets[dirndx]++;
6404 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6406 if (s->src_node != NULL) {
6407 s->src_node->packets[dirndx]++;
6408 s->src_node->bytes[dirndx] += pd.tot_len;
6410 if (s->nat_src_node != NULL) {
6411 s->nat_src_node->packets[dirndx]++;
6412 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6414 dirndx = (dir == s->direction) ? 0 : 1;
6415 s->packets[dirndx]++;
6416 s->bytes[dirndx] += pd.tot_len;
6419 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6420 if (nr != NULL && r == &V_pf_default_rule)
6422 if (tr->src.addr.type == PF_ADDR_TABLE)
6423 pfr_update_stats(tr->src.addr.p.tbl,
6424 (s == NULL) ? pd.src :
6425 &s->key[(s->direction == PF_IN)]->addr[0],
6426 pd.af, pd.tot_len, dir == PF_OUT,
6427 r->action == PF_PASS, tr->src.neg);
6428 if (tr->dst.addr.type == PF_ADDR_TABLE)
6429 pfr_update_stats(tr->dst.addr.p.tbl,
6430 (s == NULL) ? pd.dst :
6431 &s->key[(s->direction == PF_IN)]->addr[1],
6432 pd.af, pd.tot_len, dir == PF_OUT,
6433 r->action == PF_PASS, tr->dst.neg);
6437 case PF_SYNPROXY_DROP:
6448 /* pf_route6() returns unlocked. */
6450 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);