2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
35 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 #include "opt_inet6.h"
46 #include <sys/param.h>
48 #include <sys/endian.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/limits.h>
56 #include <sys/random.h>
57 #include <sys/refcount.h>
58 #include <sys/socket.h>
59 #include <sys/sysctl.h>
60 #include <sys/taskqueue.h>
61 #include <sys/ucred.h>
64 #include <net/if_types.h>
65 #include <net/route.h>
66 #include <net/radix_mpath.h>
69 #include <net/pfvar.h>
70 #include <net/if_pflog.h>
71 #include <net/if_pfsync.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/in_var.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/icmp_var.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/tcp.h>
81 #include <netinet/tcp_fsm.h>
82 #include <netinet/tcp_seq.h>
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #include <netinet/udp.h>
86 #include <netinet/udp_var.h>
88 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
91 #include <netinet/ip6.h>
92 #include <netinet/icmp6.h>
93 #include <netinet6/nd6.h>
94 #include <netinet6/ip6_var.h>
95 #include <netinet6/in6_pcb.h>
98 #include <machine/in_cksum.h>
99 #include <security/mac/mac_framework.h>
101 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
108 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
109 VNET_DEFINE(struct pf_palist, pf_pabuf);
110 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
111 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
112 VNET_DEFINE(struct pf_kstatus, pf_status);
114 VNET_DEFINE(u_int32_t, ticket_altqs_active);
115 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
116 VNET_DEFINE(int, altqs_inactive_open);
117 VNET_DEFINE(u_int32_t, ticket_pabuf);
119 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
120 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
121 VNET_DEFINE(u_char, pf_tcp_secret[16]);
122 #define V_pf_tcp_secret VNET(pf_tcp_secret)
123 VNET_DEFINE(int, pf_tcp_secret_init);
124 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
125 VNET_DEFINE(int, pf_tcp_iss_off);
126 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
129 * Queue for pf_intr() sends.
131 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
132 struct pf_send_entry {
133 STAILQ_ENTRY(pf_send_entry) pfse_next;
150 #define pfse_icmp_type u.icmpopts.type
151 #define pfse_icmp_code u.icmpopts.code
152 #define pfse_icmp_mtu u.icmpopts.mtu
155 STAILQ_HEAD(pf_send_head, pf_send_entry);
156 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157 #define V_pf_sendqueue VNET(pf_sendqueue)
159 static struct mtx pf_sendqueue_mtx;
160 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
161 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
164 * Queue for pf_overload_task() tasks.
166 struct pf_overload_entry {
167 SLIST_ENTRY(pf_overload_entry) next;
171 struct pf_rule *rule;
174 SLIST_HEAD(pf_overload_head, pf_overload_entry);
175 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
176 #define V_pf_overloadqueue VNET(pf_overloadqueue)
177 static VNET_DEFINE(struct task, pf_overloadtask);
178 #define V_pf_overloadtask VNET(pf_overloadtask)
180 static struct mtx pf_overloadqueue_mtx;
181 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
182 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
184 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
185 struct mtx pf_unlnkdrules_mtx;
187 static VNET_DEFINE(uma_zone_t, pf_sources_z);
188 #define V_pf_sources_z VNET(pf_sources_z)
189 uma_zone_t pf_mtag_z;
190 VNET_DEFINE(uma_zone_t, pf_state_z);
191 VNET_DEFINE(uma_zone_t, pf_state_key_z);
193 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
194 #define PFID_CPUBITS 8
195 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
196 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
197 #define PFID_MAXID (~PFID_CPUMASK)
198 CTASSERT((1 << PFID_CPUBITS) > MAXCPU);
200 static void pf_src_tree_remove_state(struct pf_state *);
201 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
203 static void pf_add_threshold(struct pf_threshold *);
204 static int pf_check_threshold(struct pf_threshold *);
206 static void pf_change_ap(struct pf_addr *, u_int16_t *,
207 u_int16_t *, u_int16_t *, struct pf_addr *,
208 u_int16_t, u_int8_t, sa_family_t);
209 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
210 struct tcphdr *, struct pf_state_peer *);
211 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
212 struct pf_addr *, struct pf_addr *, u_int16_t,
213 u_int16_t *, u_int16_t *, u_int16_t *,
214 u_int16_t *, u_int8_t, sa_family_t);
215 static void pf_send_tcp(struct mbuf *,
216 const struct pf_rule *, sa_family_t,
217 const struct pf_addr *, const struct pf_addr *,
218 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
219 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
220 u_int16_t, struct ifnet *);
221 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
222 sa_family_t, struct pf_rule *);
223 static void pf_detach_state(struct pf_state *);
224 static int pf_state_key_attach(struct pf_state_key *,
225 struct pf_state_key *, struct pf_state *);
226 static void pf_state_key_detach(struct pf_state *, int);
227 static int pf_state_key_ctor(void *, int, void *, int);
228 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
229 static int pf_test_rule(struct pf_rule **, struct pf_state **,
230 int, struct pfi_kif *, struct mbuf *, int,
231 struct pf_pdesc *, struct pf_rule **,
232 struct pf_ruleset **, struct inpcb *);
233 static int pf_create_state(struct pf_rule *, struct pf_rule *,
234 struct pf_rule *, struct pf_pdesc *,
235 struct pf_src_node *, struct pf_state_key *,
236 struct pf_state_key *, struct mbuf *, int,
237 u_int16_t, u_int16_t, int *, struct pfi_kif *,
238 struct pf_state **, int, u_int16_t, u_int16_t,
240 static int pf_test_fragment(struct pf_rule **, int,
241 struct pfi_kif *, struct mbuf *, void *,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **);
244 static int pf_tcp_track_full(struct pf_state_peer *,
245 struct pf_state_peer *, struct pf_state **,
246 struct pfi_kif *, struct mbuf *, int,
247 struct pf_pdesc *, u_short *, int *);
248 static int pf_tcp_track_sloppy(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pf_pdesc *, u_short *);
251 static int pf_test_state_tcp(struct pf_state **, int,
252 struct pfi_kif *, struct mbuf *, int,
253 void *, struct pf_pdesc *, u_short *);
254 static int pf_test_state_udp(struct pf_state **, int,
255 struct pfi_kif *, struct mbuf *, int,
256 void *, struct pf_pdesc *);
257 static int pf_test_state_icmp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260 static int pf_test_state_other(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
262 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
264 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
266 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
268 static int pf_check_proto_cksum(struct mbuf *, int, int,
269 u_int8_t, sa_family_t);
270 static void pf_print_state_parts(struct pf_state *,
271 struct pf_state_key *, struct pf_state_key *);
272 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
273 struct pf_addr_wrap *);
274 static struct pf_state *pf_find_state(struct pfi_kif *,
275 struct pf_state_key_cmp *, u_int);
276 static int pf_src_connlimit(struct pf_state **);
277 static void pf_overload_task(void *v, int pending);
278 static int pf_insert_src_node(struct pf_src_node **,
279 struct pf_rule *, struct pf_addr *, sa_family_t);
280 static u_int pf_purge_expired_states(u_int, int);
281 static void pf_purge_unlinked_rules(void);
282 static int pf_mtag_uminit(void *, int, int);
283 static void pf_mtag_free(struct m_tag *);
285 static void pf_route(struct mbuf **, struct pf_rule *, int,
286 struct ifnet *, struct pf_state *,
290 static void pf_change_a6(struct pf_addr *, u_int16_t *,
291 struct pf_addr *, u_int8_t);
292 static void pf_route6(struct mbuf **, struct pf_rule *, int,
293 struct ifnet *, struct pf_state *,
297 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
299 VNET_DECLARE(int, pf_end_threads);
301 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
303 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
304 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
306 #define STATE_LOOKUP(i, k, d, s, pd) \
308 (s) = pf_find_state((i), (k), (d)); \
311 if (PACKET_LOOPED(pd)) \
313 if ((d) == PF_OUT && \
314 (((s)->rule.ptr->rt == PF_ROUTETO && \
315 (s)->rule.ptr->direction == PF_OUT) || \
316 ((s)->rule.ptr->rt == PF_REPLYTO && \
317 (s)->rule.ptr->direction == PF_IN)) && \
318 (s)->rt_kif != NULL && \
319 (s)->rt_kif != (i)) \
323 #define BOUND_IFACE(r, k) \
324 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
326 #define STATE_INC_COUNTERS(s) \
328 counter_u64_add(s->rule.ptr->states_cur, 1); \
329 counter_u64_add(s->rule.ptr->states_tot, 1); \
330 if (s->anchor.ptr != NULL) { \
331 counter_u64_add(s->anchor.ptr->states_cur, 1); \
332 counter_u64_add(s->anchor.ptr->states_tot, 1); \
334 if (s->nat_rule.ptr != NULL) { \
335 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
336 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
340 #define STATE_DEC_COUNTERS(s) \
342 if (s->nat_rule.ptr != NULL) \
343 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
344 if (s->anchor.ptr != NULL) \
345 counter_u64_add(s->anchor.ptr->states_cur, -1); \
346 counter_u64_add(s->rule.ptr->states_cur, -1); \
349 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
350 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
351 VNET_DEFINE(struct pf_idhash *, pf_idhash);
352 VNET_DEFINE(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 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1976 l = cksum + old - new;
1977 l = (l >> 16) + (l & 65535);
1985 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1986 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1991 PF_ACPY(&ao, a, af);
1999 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2000 ao.addr16[0], an->addr16[0], 0),
2001 ao.addr16[1], an->addr16[1], 0);
2003 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2004 ao.addr16[0], an->addr16[0], u),
2005 ao.addr16[1], an->addr16[1], u),
2011 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2012 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2013 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2014 ao.addr16[0], an->addr16[0], u),
2015 ao.addr16[1], an->addr16[1], u),
2016 ao.addr16[2], an->addr16[2], u),
2017 ao.addr16[3], an->addr16[3], u),
2018 ao.addr16[4], an->addr16[4], u),
2019 ao.addr16[5], an->addr16[5], u),
2020 ao.addr16[6], an->addr16[6], u),
2021 ao.addr16[7], an->addr16[7], u),
2029 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2031 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2035 memcpy(&ao, a, sizeof(ao));
2036 memcpy(a, &an, sizeof(u_int32_t));
2037 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2038 ao % 65536, an % 65536, u);
2043 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2047 PF_ACPY(&ao, a, AF_INET6);
2048 PF_ACPY(a, an, AF_INET6);
2050 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2051 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2052 pf_cksum_fixup(pf_cksum_fixup(*c,
2053 ao.addr16[0], an->addr16[0], u),
2054 ao.addr16[1], an->addr16[1], u),
2055 ao.addr16[2], an->addr16[2], u),
2056 ao.addr16[3], an->addr16[3], u),
2057 ao.addr16[4], an->addr16[4], u),
2058 ao.addr16[5], an->addr16[5], u),
2059 ao.addr16[6], an->addr16[6], u),
2060 ao.addr16[7], an->addr16[7], u);
2065 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2066 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2067 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2069 struct pf_addr oia, ooa;
2071 PF_ACPY(&oia, ia, af);
2073 PF_ACPY(&ooa, oa, af);
2075 /* Change inner protocol port, fix inner protocol checksum. */
2077 u_int16_t oip = *ip;
2084 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2085 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2087 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2089 /* Change inner ip address, fix inner ip and icmp checksums. */
2090 PF_ACPY(ia, na, af);
2094 u_int32_t oh2c = *h2c;
2096 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2097 oia.addr16[0], ia->addr16[0], 0),
2098 oia.addr16[1], ia->addr16[1], 0);
2099 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2100 oia.addr16[0], ia->addr16[0], 0),
2101 oia.addr16[1], ia->addr16[1], 0);
2102 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2108 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2109 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2110 pf_cksum_fixup(pf_cksum_fixup(*ic,
2111 oia.addr16[0], ia->addr16[0], u),
2112 oia.addr16[1], ia->addr16[1], u),
2113 oia.addr16[2], ia->addr16[2], u),
2114 oia.addr16[3], ia->addr16[3], u),
2115 oia.addr16[4], ia->addr16[4], u),
2116 oia.addr16[5], ia->addr16[5], u),
2117 oia.addr16[6], ia->addr16[6], u),
2118 oia.addr16[7], ia->addr16[7], u);
2122 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2124 PF_ACPY(oa, na, af);
2128 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2129 ooa.addr16[0], oa->addr16[0], 0),
2130 ooa.addr16[1], oa->addr16[1], 0);
2135 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2136 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2137 pf_cksum_fixup(pf_cksum_fixup(*ic,
2138 ooa.addr16[0], oa->addr16[0], u),
2139 ooa.addr16[1], oa->addr16[1], u),
2140 ooa.addr16[2], oa->addr16[2], u),
2141 ooa.addr16[3], oa->addr16[3], u),
2142 ooa.addr16[4], oa->addr16[4], u),
2143 ooa.addr16[5], oa->addr16[5], u),
2144 ooa.addr16[6], oa->addr16[6], u),
2145 ooa.addr16[7], oa->addr16[7], u);
2154 * Need to modulate the sequence numbers in the TCP SACK option
2155 * (credits to Krzysztof Pfaff for report and patch)
2158 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2159 struct tcphdr *th, struct pf_state_peer *dst)
2161 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2162 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2163 int copyback = 0, i, olen;
2164 struct sackblk sack;
2166 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2167 if (hlen < TCPOLEN_SACKLEN ||
2168 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2171 while (hlen >= TCPOLEN_SACKLEN) {
2174 case TCPOPT_EOL: /* FALLTHROUGH */
2182 if (olen >= TCPOLEN_SACKLEN) {
2183 for (i = 2; i + TCPOLEN_SACK <= olen;
2184 i += TCPOLEN_SACK) {
2185 memcpy(&sack, &opt[i], sizeof(sack));
2186 pf_change_a(&sack.start, &th->th_sum,
2187 htonl(ntohl(sack.start) -
2189 pf_change_a(&sack.end, &th->th_sum,
2190 htonl(ntohl(sack.end) -
2192 memcpy(&opt[i], &sack, sizeof(sack));
2206 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2211 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2212 const struct pf_addr *saddr, const struct pf_addr *daddr,
2213 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2214 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2215 u_int16_t rtag, struct ifnet *ifp)
2217 struct pf_send_entry *pfse;
2221 struct ip *h = NULL;
2224 struct ip6_hdr *h6 = NULL;
2228 struct pf_mtag *pf_mtag;
2233 /* maximum segment size tcp option */
2234 tlen = sizeof(struct tcphdr);
2241 len = sizeof(struct ip) + tlen;
2246 len = sizeof(struct ip6_hdr) + tlen;
2250 panic("%s: unsupported af %d", __func__, af);
2253 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2254 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2257 m = m_gethdr(M_NOWAIT, MT_DATA);
2259 free(pfse, M_PFTEMP);
2263 mac_netinet_firewall_send(m);
2265 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2266 free(pfse, M_PFTEMP);
2271 m->m_flags |= M_SKIP_FIREWALL;
2272 pf_mtag->tag = rtag;
2274 if (r != NULL && r->rtableid >= 0)
2275 M_SETFIB(m, r->rtableid);
2278 if (r != NULL && r->qid) {
2279 pf_mtag->qid = r->qid;
2281 /* add hints for ecn */
2282 pf_mtag->hdr = mtod(m, struct ip *);
2285 m->m_data += max_linkhdr;
2286 m->m_pkthdr.len = m->m_len = len;
2287 m->m_pkthdr.rcvif = NULL;
2288 bzero(m->m_data, len);
2292 h = mtod(m, struct ip *);
2294 /* IP header fields included in the TCP checksum */
2295 h->ip_p = IPPROTO_TCP;
2296 h->ip_len = htons(tlen);
2297 h->ip_src.s_addr = saddr->v4.s_addr;
2298 h->ip_dst.s_addr = daddr->v4.s_addr;
2300 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2305 h6 = mtod(m, struct ip6_hdr *);
2307 /* IP header fields included in the TCP checksum */
2308 h6->ip6_nxt = IPPROTO_TCP;
2309 h6->ip6_plen = htons(tlen);
2310 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2311 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2313 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2319 th->th_sport = sport;
2320 th->th_dport = dport;
2321 th->th_seq = htonl(seq);
2322 th->th_ack = htonl(ack);
2323 th->th_off = tlen >> 2;
2324 th->th_flags = flags;
2325 th->th_win = htons(win);
2328 opt = (char *)(th + 1);
2329 opt[0] = TCPOPT_MAXSEG;
2332 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2339 th->th_sum = in_cksum(m, len);
2341 /* Finish the IP header */
2343 h->ip_hl = sizeof(*h) >> 2;
2344 h->ip_tos = IPTOS_LOWDELAY;
2345 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2346 h->ip_len = htons(len);
2347 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2350 pfse->pfse_type = PFSE_IP;
2356 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2357 sizeof(struct ip6_hdr), tlen);
2359 h6->ip6_vfc |= IPV6_VERSION;
2360 h6->ip6_hlim = IPV6_DEFHLIM;
2362 pfse->pfse_type = PFSE_IP6;
2371 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2374 struct pf_send_entry *pfse;
2376 struct pf_mtag *pf_mtag;
2378 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2379 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2383 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2384 free(pfse, M_PFTEMP);
2388 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2389 free(pfse, M_PFTEMP);
2393 m0->m_flags |= M_SKIP_FIREWALL;
2395 if (r->rtableid >= 0)
2396 M_SETFIB(m0, r->rtableid);
2400 pf_mtag->qid = r->qid;
2401 /* add hints for ecn */
2402 pf_mtag->hdr = mtod(m0, struct ip *);
2409 pfse->pfse_type = PFSE_ICMP;
2414 pfse->pfse_type = PFSE_ICMP6;
2419 pfse->pfse_icmp_type = type;
2420 pfse->pfse_icmp_code = code;
2425 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2426 * If n is 0, they match if they are equal. If n is != 0, they match if they
2430 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2431 struct pf_addr *b, sa_family_t af)
2438 if ((a->addr32[0] & m->addr32[0]) ==
2439 (b->addr32[0] & m->addr32[0]))
2445 if (((a->addr32[0] & m->addr32[0]) ==
2446 (b->addr32[0] & m->addr32[0])) &&
2447 ((a->addr32[1] & m->addr32[1]) ==
2448 (b->addr32[1] & m->addr32[1])) &&
2449 ((a->addr32[2] & m->addr32[2]) ==
2450 (b->addr32[2] & m->addr32[2])) &&
2451 ((a->addr32[3] & m->addr32[3]) ==
2452 (b->addr32[3] & m->addr32[3])))
2471 * Return 1 if b <= a <= e, otherwise return 0.
2474 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2475 struct pf_addr *a, sa_family_t af)
2480 if ((a->addr32[0] < b->addr32[0]) ||
2481 (a->addr32[0] > e->addr32[0]))
2490 for (i = 0; i < 4; ++i)
2491 if (a->addr32[i] > b->addr32[i])
2493 else if (a->addr32[i] < b->addr32[i])
2496 for (i = 0; i < 4; ++i)
2497 if (a->addr32[i] < e->addr32[i])
2499 else if (a->addr32[i] > e->addr32[i])
2509 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2513 return ((p > a1) && (p < a2));
2515 return ((p < a1) || (p > a2));
2517 return ((p >= a1) && (p <= a2));
2531 return (0); /* never reached */
2535 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2540 return (pf_match(op, a1, a2, p));
2544 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2546 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2548 return (pf_match(op, a1, a2, u));
2552 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2554 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2556 return (pf_match(op, a1, a2, g));
2560 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2565 return ((!r->match_tag_not && r->match_tag == *tag) ||
2566 (r->match_tag_not && r->match_tag != *tag));
2570 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2573 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2575 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2578 pd->pf_mtag->tag = tag;
2583 #define PF_ANCHOR_STACKSIZE 32
2584 struct pf_anchor_stackframe {
2585 struct pf_ruleset *rs;
2586 struct pf_rule *r; /* XXX: + match bit */
2587 struct pf_anchor *child;
2591 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2593 #define PF_ANCHORSTACK_MATCH 0x00000001
2594 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2596 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2597 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2598 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2599 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2600 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2604 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2605 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2608 struct pf_anchor_stackframe *f;
2614 if (*depth >= PF_ANCHOR_STACKSIZE) {
2615 printf("%s: anchor stack overflow on %s\n",
2616 __func__, (*r)->anchor->name);
2617 *r = TAILQ_NEXT(*r, entries);
2619 } else if (*depth == 0 && a != NULL)
2621 f = stack + (*depth)++;
2624 if ((*r)->anchor_wildcard) {
2625 struct pf_anchor_node *parent = &(*r)->anchor->children;
2627 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2631 *rs = &f->child->ruleset;
2634 *rs = &(*r)->anchor->ruleset;
2636 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2640 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2641 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2644 struct pf_anchor_stackframe *f;
2653 f = stack + *depth - 1;
2654 fr = PF_ANCHOR_RULE(f);
2655 if (f->child != NULL) {
2656 struct pf_anchor_node *parent;
2659 * This block traverses through
2660 * a wildcard anchor.
2662 parent = &fr->anchor->children;
2663 if (match != NULL && *match) {
2665 * If any of "*" matched, then
2666 * "foo/ *" matched, mark frame
2669 PF_ANCHOR_SET_MATCH(f);
2672 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2673 if (f->child != NULL) {
2674 *rs = &f->child->ruleset;
2675 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2683 if (*depth == 0 && a != NULL)
2686 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2688 *r = TAILQ_NEXT(fr, entries);
2689 } while (*r == NULL);
2696 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2697 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2702 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2703 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2707 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2708 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2709 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2710 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2711 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2712 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2713 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2714 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2720 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2725 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2729 if (addr->addr32[3] == 0xffffffff) {
2730 addr->addr32[3] = 0;
2731 if (addr->addr32[2] == 0xffffffff) {
2732 addr->addr32[2] = 0;
2733 if (addr->addr32[1] == 0xffffffff) {
2734 addr->addr32[1] = 0;
2736 htonl(ntohl(addr->addr32[0]) + 1);
2739 htonl(ntohl(addr->addr32[1]) + 1);
2742 htonl(ntohl(addr->addr32[2]) + 1);
2745 htonl(ntohl(addr->addr32[3]) + 1);
2752 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2754 struct pf_addr *saddr, *daddr;
2755 u_int16_t sport, dport;
2756 struct inpcbinfo *pi;
2759 pd->lookup.uid = UID_MAX;
2760 pd->lookup.gid = GID_MAX;
2762 switch (pd->proto) {
2764 if (pd->hdr.tcp == NULL)
2766 sport = pd->hdr.tcp->th_sport;
2767 dport = pd->hdr.tcp->th_dport;
2771 if (pd->hdr.udp == NULL)
2773 sport = pd->hdr.udp->uh_sport;
2774 dport = pd->hdr.udp->uh_dport;
2780 if (direction == PF_IN) {
2795 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2796 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2798 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2799 daddr->v4, dport, INPLOOKUP_WILDCARD |
2800 INPLOOKUP_RLOCKPCB, NULL, m);
2808 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2809 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2811 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2812 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2813 INPLOOKUP_RLOCKPCB, NULL, m);
2823 INP_RLOCK_ASSERT(inp);
2824 pd->lookup.uid = inp->inp_cred->cr_uid;
2825 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2832 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2836 u_int8_t *opt, optlen;
2837 u_int8_t wscale = 0;
2839 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2840 if (hlen <= sizeof(struct tcphdr))
2842 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2844 opt = hdr + sizeof(struct tcphdr);
2845 hlen -= sizeof(struct tcphdr);
2855 if (wscale > TCP_MAX_WINSHIFT)
2856 wscale = TCP_MAX_WINSHIFT;
2857 wscale |= PF_WSCALE_FLAG;
2872 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2876 u_int8_t *opt, optlen;
2877 u_int16_t mss = V_tcp_mssdflt;
2879 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2880 if (hlen <= sizeof(struct tcphdr))
2882 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2884 opt = hdr + sizeof(struct tcphdr);
2885 hlen -= sizeof(struct tcphdr);
2886 while (hlen >= TCPOLEN_MAXSEG) {
2894 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2910 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2913 struct sockaddr_in *dst;
2917 struct sockaddr_in6 *dst6;
2918 struct route_in6 ro6;
2920 struct rtentry *rt = NULL;
2922 u_int16_t mss = V_tcp_mssdflt;
2927 hlen = sizeof(struct ip);
2928 bzero(&ro, sizeof(ro));
2929 dst = (struct sockaddr_in *)&ro.ro_dst;
2930 dst->sin_family = AF_INET;
2931 dst->sin_len = sizeof(*dst);
2932 dst->sin_addr = addr->v4;
2933 in_rtalloc_ign(&ro, 0, rtableid);
2939 hlen = sizeof(struct ip6_hdr);
2940 bzero(&ro6, sizeof(ro6));
2941 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2942 dst6->sin6_family = AF_INET6;
2943 dst6->sin6_len = sizeof(*dst6);
2944 dst6->sin6_addr = addr->v6;
2945 in6_rtalloc_ign(&ro6, 0, rtableid);
2951 if (rt && rt->rt_ifp) {
2952 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2953 mss = max(V_tcp_mssdflt, mss);
2956 mss = min(mss, offer);
2957 mss = max(mss, 64); /* sanity - at least max opt space */
2962 pf_tcp_iss(struct pf_pdesc *pd)
2965 u_int32_t digest[4];
2967 if (V_pf_tcp_secret_init == 0) {
2968 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
2969 MD5Init(&V_pf_tcp_secret_ctx);
2970 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
2971 sizeof(V_pf_tcp_secret));
2972 V_pf_tcp_secret_init = 1;
2975 ctx = V_pf_tcp_secret_ctx;
2977 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
2978 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
2979 if (pd->af == AF_INET6) {
2980 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
2981 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
2983 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
2984 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
2986 MD5Final((u_char *)digest, &ctx);
2987 V_pf_tcp_iss_off += 4096;
2988 #define ISN_RANDOM_INCREMENT (4096 - 1)
2989 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
2991 #undef ISN_RANDOM_INCREMENT
2995 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
2996 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
2997 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
2999 struct pf_rule *nr = NULL;
3000 struct pf_addr * const saddr = pd->src;
3001 struct pf_addr * const daddr = pd->dst;
3002 sa_family_t af = pd->af;
3003 struct pf_rule *r, *a = NULL;
3004 struct pf_ruleset *ruleset = NULL;
3005 struct pf_src_node *nsn = NULL;
3006 struct tcphdr *th = pd->hdr.tcp;
3007 struct pf_state_key *sk = NULL, *nk = NULL;
3009 int rewrite = 0, hdrlen = 0;
3010 int tag = -1, rtableid = -1;
3014 u_int16_t sport = 0, dport = 0;
3015 u_int16_t bproto_sum = 0, bip_sum = 0;
3016 u_int8_t icmptype = 0, icmpcode = 0;
3017 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3022 INP_LOCK_ASSERT(inp);
3023 pd->lookup.uid = inp->inp_cred->cr_uid;
3024 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3025 pd->lookup.done = 1;
3028 switch (pd->proto) {
3030 sport = th->th_sport;
3031 dport = th->th_dport;
3032 hdrlen = sizeof(*th);
3035 sport = pd->hdr.udp->uh_sport;
3036 dport = pd->hdr.udp->uh_dport;
3037 hdrlen = sizeof(*pd->hdr.udp);
3041 if (pd->af != AF_INET)
3043 sport = dport = pd->hdr.icmp->icmp_id;
3044 hdrlen = sizeof(*pd->hdr.icmp);
3045 icmptype = pd->hdr.icmp->icmp_type;
3046 icmpcode = pd->hdr.icmp->icmp_code;
3048 if (icmptype == ICMP_UNREACH ||
3049 icmptype == ICMP_SOURCEQUENCH ||
3050 icmptype == ICMP_REDIRECT ||
3051 icmptype == ICMP_TIMXCEED ||
3052 icmptype == ICMP_PARAMPROB)
3057 case IPPROTO_ICMPV6:
3060 sport = dport = pd->hdr.icmp6->icmp6_id;
3061 hdrlen = sizeof(*pd->hdr.icmp6);
3062 icmptype = pd->hdr.icmp6->icmp6_type;
3063 icmpcode = pd->hdr.icmp6->icmp6_code;
3065 if (icmptype == ICMP6_DST_UNREACH ||
3066 icmptype == ICMP6_PACKET_TOO_BIG ||
3067 icmptype == ICMP6_TIME_EXCEEDED ||
3068 icmptype == ICMP6_PARAM_PROB)
3073 sport = dport = hdrlen = 0;
3077 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3079 /* check packet for BINAT/NAT/RDR */
3080 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3081 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3082 KASSERT(sk != NULL, ("%s: null sk", __func__));
3083 KASSERT(nk != NULL, ("%s: null nk", __func__));
3086 bip_sum = *pd->ip_sum;
3088 switch (pd->proto) {
3090 bproto_sum = th->th_sum;
3091 pd->proto_sum = &th->th_sum;
3093 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3094 nk->port[pd->sidx] != sport) {
3095 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3096 &th->th_sum, &nk->addr[pd->sidx],
3097 nk->port[pd->sidx], 0, af);
3098 pd->sport = &th->th_sport;
3099 sport = th->th_sport;
3102 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3103 nk->port[pd->didx] != dport) {
3104 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3105 &th->th_sum, &nk->addr[pd->didx],
3106 nk->port[pd->didx], 0, af);
3107 dport = th->th_dport;
3108 pd->dport = &th->th_dport;
3113 bproto_sum = pd->hdr.udp->uh_sum;
3114 pd->proto_sum = &pd->hdr.udp->uh_sum;
3116 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3117 nk->port[pd->sidx] != sport) {
3118 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3119 pd->ip_sum, &pd->hdr.udp->uh_sum,
3120 &nk->addr[pd->sidx],
3121 nk->port[pd->sidx], 1, af);
3122 sport = pd->hdr.udp->uh_sport;
3123 pd->sport = &pd->hdr.udp->uh_sport;
3126 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3127 nk->port[pd->didx] != dport) {
3128 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3129 pd->ip_sum, &pd->hdr.udp->uh_sum,
3130 &nk->addr[pd->didx],
3131 nk->port[pd->didx], 1, af);
3132 dport = pd->hdr.udp->uh_dport;
3133 pd->dport = &pd->hdr.udp->uh_dport;
3139 nk->port[0] = nk->port[1];
3140 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3141 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3142 nk->addr[pd->sidx].v4.s_addr, 0);
3144 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3145 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3146 nk->addr[pd->didx].v4.s_addr, 0);
3148 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3149 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3150 pd->hdr.icmp->icmp_cksum, sport,
3152 pd->hdr.icmp->icmp_id = nk->port[1];
3153 pd->sport = &pd->hdr.icmp->icmp_id;
3155 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3159 case IPPROTO_ICMPV6:
3160 nk->port[0] = nk->port[1];
3161 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3162 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3163 &nk->addr[pd->sidx], 0);
3165 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3166 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3167 &nk->addr[pd->didx], 0);
3176 &nk->addr[pd->sidx], AF_INET))
3177 pf_change_a(&saddr->v4.s_addr,
3179 nk->addr[pd->sidx].v4.s_addr, 0);
3182 &nk->addr[pd->didx], AF_INET))
3183 pf_change_a(&daddr->v4.s_addr,
3185 nk->addr[pd->didx].v4.s_addr, 0);
3191 &nk->addr[pd->sidx], AF_INET6))
3192 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3195 &nk->addr[pd->didx], AF_INET6))
3196 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3209 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3210 r = r->skip[PF_SKIP_IFP].ptr;
3211 else if (r->direction && r->direction != direction)
3212 r = r->skip[PF_SKIP_DIR].ptr;
3213 else if (r->af && r->af != af)
3214 r = r->skip[PF_SKIP_AF].ptr;
3215 else if (r->proto && r->proto != pd->proto)
3216 r = r->skip[PF_SKIP_PROTO].ptr;
3217 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3218 r->src.neg, kif, M_GETFIB(m)))
3219 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3220 /* tcp/udp only. port_op always 0 in other cases */
3221 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3222 r->src.port[0], r->src.port[1], sport))
3223 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3224 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3225 r->dst.neg, NULL, M_GETFIB(m)))
3226 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3227 /* tcp/udp only. port_op always 0 in other cases */
3228 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3229 r->dst.port[0], r->dst.port[1], dport))
3230 r = r->skip[PF_SKIP_DST_PORT].ptr;
3231 /* icmp only. type always 0 in other cases */
3232 else if (r->type && r->type != icmptype + 1)
3233 r = TAILQ_NEXT(r, entries);
3234 /* icmp only. type always 0 in other cases */
3235 else if (r->code && r->code != icmpcode + 1)
3236 r = TAILQ_NEXT(r, entries);
3237 else if (r->tos && !(r->tos == pd->tos))
3238 r = TAILQ_NEXT(r, entries);
3239 else if (r->rule_flag & PFRULE_FRAGMENT)
3240 r = TAILQ_NEXT(r, entries);
3241 else if (pd->proto == IPPROTO_TCP &&
3242 (r->flagset & th->th_flags) != r->flags)
3243 r = TAILQ_NEXT(r, entries);
3244 /* tcp/udp only. uid.op always 0 in other cases */
3245 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3246 pf_socket_lookup(direction, pd, m), 1)) &&
3247 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3249 r = TAILQ_NEXT(r, entries);
3250 /* tcp/udp only. gid.op always 0 in other cases */
3251 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3252 pf_socket_lookup(direction, pd, m), 1)) &&
3253 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3255 r = TAILQ_NEXT(r, entries);
3257 r->prob <= arc4random())
3258 r = TAILQ_NEXT(r, entries);
3259 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3260 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3261 r = TAILQ_NEXT(r, entries);
3262 else if (r->os_fingerprint != PF_OSFP_ANY &&
3263 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3264 pf_osfp_fingerprint(pd, m, off, th),
3265 r->os_fingerprint)))
3266 r = TAILQ_NEXT(r, entries);
3270 if (r->rtableid >= 0)
3271 rtableid = r->rtableid;
3272 if (r->anchor == NULL) {
3279 r = TAILQ_NEXT(r, entries);
3281 pf_step_into_anchor(anchor_stack, &asd,
3282 &ruleset, PF_RULESET_FILTER, &r, &a,
3285 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3286 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3293 REASON_SET(&reason, PFRES_MATCH);
3295 if (r->log || (nr != NULL && nr->log)) {
3297 m_copyback(m, off, hdrlen, pd->hdr.any);
3298 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3302 if ((r->action == PF_DROP) &&
3303 ((r->rule_flag & PFRULE_RETURNRST) ||
3304 (r->rule_flag & PFRULE_RETURNICMP) ||
3305 (r->rule_flag & PFRULE_RETURN))) {
3306 /* undo NAT changes, if they have taken place */
3308 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3309 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3311 *pd->sport = sk->port[pd->sidx];
3313 *pd->dport = sk->port[pd->didx];
3315 *pd->proto_sum = bproto_sum;
3317 *pd->ip_sum = bip_sum;
3318 m_copyback(m, off, hdrlen, pd->hdr.any);
3320 if (pd->proto == IPPROTO_TCP &&
3321 ((r->rule_flag & PFRULE_RETURNRST) ||
3322 (r->rule_flag & PFRULE_RETURN)) &&
3323 !(th->th_flags & TH_RST)) {
3324 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3336 h4 = mtod(m, struct ip *);
3337 len = ntohs(h4->ip_len) - off;
3342 h6 = mtod(m, struct ip6_hdr *);
3343 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3348 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3349 REASON_SET(&reason, PFRES_PROTCKSUM);
3351 if (th->th_flags & TH_SYN)
3353 if (th->th_flags & TH_FIN)
3355 pf_send_tcp(m, r, af, pd->dst,
3356 pd->src, th->th_dport, th->th_sport,
3357 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3358 r->return_ttl, 1, 0, kif->pfik_ifp);
3360 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3362 pf_send_icmp(m, r->return_icmp >> 8,
3363 r->return_icmp & 255, af, r);
3364 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3366 pf_send_icmp(m, r->return_icmp6 >> 8,
3367 r->return_icmp6 & 255, af, r);
3370 if (r->action == PF_DROP)
3373 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3374 REASON_SET(&reason, PFRES_MEMORY);
3378 M_SETFIB(m, rtableid);
3380 if (!state_icmp && (r->keep_state || nr != NULL ||
3381 (pd->flags & PFDESC_TCP_NORM))) {
3383 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3384 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3386 if (action != PF_PASS)
3390 uma_zfree(V_pf_state_key_z, sk);
3392 uma_zfree(V_pf_state_key_z, nk);
3395 /* copy back packet headers if we performed NAT operations */
3397 m_copyback(m, off, hdrlen, pd->hdr.any);
3399 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3400 direction == PF_OUT &&
3401 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3403 * We want the state created, but we dont
3404 * want to send this in case a partner
3405 * firewall has to know about it to allow
3406 * replies through it.
3414 uma_zfree(V_pf_state_key_z, sk);
3416 uma_zfree(V_pf_state_key_z, nk);
3421 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3422 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3423 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3424 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3425 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3427 struct pf_state *s = NULL;
3428 struct pf_src_node *sn = NULL;
3429 struct tcphdr *th = pd->hdr.tcp;
3430 u_int16_t mss = V_tcp_mssdflt;
3433 /* check maximums */
3434 if (r->max_states &&
3435 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3436 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3437 REASON_SET(&reason, PFRES_MAXSTATES);
3440 /* src node for filter rule */
3441 if ((r->rule_flag & PFRULE_SRCTRACK ||
3442 r->rpool.opts & PF_POOL_STICKYADDR) &&
3443 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3444 REASON_SET(&reason, PFRES_SRCLIMIT);
3447 /* src node for translation rule */
3448 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3449 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3450 REASON_SET(&reason, PFRES_SRCLIMIT);
3453 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3455 REASON_SET(&reason, PFRES_MEMORY);
3459 s->nat_rule.ptr = nr;
3461 STATE_INC_COUNTERS(s);
3463 s->state_flags |= PFSTATE_ALLOWOPTS;
3464 if (r->rule_flag & PFRULE_STATESLOPPY)
3465 s->state_flags |= PFSTATE_SLOPPY;
3466 s->log = r->log & PF_LOG_ALL;
3467 s->sync_state = PFSYNC_S_NONE;
3469 s->log |= nr->log & PF_LOG_ALL;
3470 switch (pd->proto) {
3472 s->src.seqlo = ntohl(th->th_seq);
3473 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3474 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3475 r->keep_state == PF_STATE_MODULATE) {
3476 /* Generate sequence number modulator */
3477 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3480 pf_change_a(&th->th_seq, &th->th_sum,
3481 htonl(s->src.seqlo + s->src.seqdiff), 0);
3485 if (th->th_flags & TH_SYN) {
3487 s->src.wscale = pf_get_wscale(m, off,
3488 th->th_off, pd->af);
3490 s->src.max_win = MAX(ntohs(th->th_win), 1);
3491 if (s->src.wscale & PF_WSCALE_MASK) {
3492 /* Remove scale factor from initial window */
3493 int win = s->src.max_win;
3494 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3495 s->src.max_win = (win - 1) >>
3496 (s->src.wscale & PF_WSCALE_MASK);
3498 if (th->th_flags & TH_FIN)
3502 s->src.state = TCPS_SYN_SENT;
3503 s->dst.state = TCPS_CLOSED;
3504 s->timeout = PFTM_TCP_FIRST_PACKET;
3507 s->src.state = PFUDPS_SINGLE;
3508 s->dst.state = PFUDPS_NO_TRAFFIC;
3509 s->timeout = PFTM_UDP_FIRST_PACKET;
3513 case IPPROTO_ICMPV6:
3515 s->timeout = PFTM_ICMP_FIRST_PACKET;
3518 s->src.state = PFOTHERS_SINGLE;
3519 s->dst.state = PFOTHERS_NO_TRAFFIC;
3520 s->timeout = PFTM_OTHER_FIRST_PACKET;
3523 if (r->rt && r->rt != PF_FASTROUTE) {
3524 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3525 REASON_SET(&reason, PFRES_MAPFAILED);
3526 pf_src_tree_remove_state(s);
3527 STATE_DEC_COUNTERS(s);
3528 uma_zfree(V_pf_state_z, s);
3531 s->rt_kif = r->rpool.cur->kif;
3534 s->creation = time_uptime;
3535 s->expire = time_uptime;
3539 s->src_node->states++;
3542 /* XXX We only modify one side for now. */
3543 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3544 s->nat_src_node = nsn;
3545 s->nat_src_node->states++;
3547 if (pd->proto == IPPROTO_TCP) {
3548 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3549 off, pd, th, &s->src, &s->dst)) {
3550 REASON_SET(&reason, PFRES_MEMORY);
3551 pf_src_tree_remove_state(s);
3552 STATE_DEC_COUNTERS(s);
3553 uma_zfree(V_pf_state_z, s);
3556 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3557 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3558 &s->src, &s->dst, rewrite)) {
3559 /* This really shouldn't happen!!! */
3560 DPFPRINTF(PF_DEBUG_URGENT,
3561 ("pf_normalize_tcp_stateful failed on first pkt"));
3562 pf_normalize_tcp_cleanup(s);
3563 pf_src_tree_remove_state(s);
3564 STATE_DEC_COUNTERS(s);
3565 uma_zfree(V_pf_state_z, s);
3569 s->direction = pd->dir;
3572 * sk/nk could already been setup by pf_get_translation().
3575 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3576 __func__, nr, sk, nk));
3577 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3582 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3583 __func__, nr, sk, nk));
3585 /* Swap sk/nk for PF_OUT. */
3586 if (pf_state_insert(BOUND_IFACE(r, kif),
3587 (pd->dir == PF_IN) ? sk : nk,
3588 (pd->dir == PF_IN) ? nk : sk, s)) {
3589 if (pd->proto == IPPROTO_TCP)
3590 pf_normalize_tcp_cleanup(s);
3591 REASON_SET(&reason, PFRES_STATEINS);
3592 pf_src_tree_remove_state(s);
3593 STATE_DEC_COUNTERS(s);
3594 uma_zfree(V_pf_state_z, s);
3601 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3602 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3603 s->src.state = PF_TCPS_PROXY_SRC;
3604 /* undo NAT changes, if they have taken place */
3606 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3607 if (pd->dir == PF_OUT)
3608 skt = s->key[PF_SK_STACK];
3609 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3610 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3612 *pd->sport = skt->port[pd->sidx];
3614 *pd->dport = skt->port[pd->didx];
3616 *pd->proto_sum = bproto_sum;
3618 *pd->ip_sum = bip_sum;
3619 m_copyback(m, off, hdrlen, pd->hdr.any);
3621 s->src.seqhi = htonl(arc4random());
3622 /* Find mss option */
3623 int rtid = M_GETFIB(m);
3624 mss = pf_get_mss(m, off, th->th_off, pd->af);
3625 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3626 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3628 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3629 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3630 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3631 REASON_SET(&reason, PFRES_SYNPROXY);
3632 return (PF_SYNPROXY_DROP);
3639 uma_zfree(V_pf_state_key_z, sk);
3641 uma_zfree(V_pf_state_key_z, nk);
3643 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3644 pf_unlink_src_node(sn);
3645 pf_free_src_node(sn);
3648 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3649 pf_unlink_src_node(nsn);
3650 pf_free_src_node(nsn);
3657 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3658 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3659 struct pf_ruleset **rsm)
3661 struct pf_rule *r, *a = NULL;
3662 struct pf_ruleset *ruleset = NULL;
3663 sa_family_t af = pd->af;
3668 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3672 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3675 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3676 r = r->skip[PF_SKIP_IFP].ptr;
3677 else if (r->direction && r->direction != direction)
3678 r = r->skip[PF_SKIP_DIR].ptr;
3679 else if (r->af && r->af != af)
3680 r = r->skip[PF_SKIP_AF].ptr;
3681 else if (r->proto && r->proto != pd->proto)
3682 r = r->skip[PF_SKIP_PROTO].ptr;
3683 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3684 r->src.neg, kif, M_GETFIB(m)))
3685 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3686 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3687 r->dst.neg, NULL, M_GETFIB(m)))
3688 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3689 else if (r->tos && !(r->tos == pd->tos))
3690 r = TAILQ_NEXT(r, entries);
3691 else if (r->os_fingerprint != PF_OSFP_ANY)
3692 r = TAILQ_NEXT(r, entries);
3693 else if (pd->proto == IPPROTO_UDP &&
3694 (r->src.port_op || r->dst.port_op))
3695 r = TAILQ_NEXT(r, entries);
3696 else if (pd->proto == IPPROTO_TCP &&
3697 (r->src.port_op || r->dst.port_op || r->flagset))
3698 r = TAILQ_NEXT(r, entries);
3699 else if ((pd->proto == IPPROTO_ICMP ||
3700 pd->proto == IPPROTO_ICMPV6) &&
3701 (r->type || r->code))
3702 r = TAILQ_NEXT(r, entries);
3703 else if (r->prob && r->prob <=
3704 (arc4random() % (UINT_MAX - 1) + 1))
3705 r = TAILQ_NEXT(r, entries);
3706 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3707 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3708 r = TAILQ_NEXT(r, entries);
3710 if (r->anchor == NULL) {
3717 r = TAILQ_NEXT(r, entries);
3719 pf_step_into_anchor(anchor_stack, &asd,
3720 &ruleset, PF_RULESET_FILTER, &r, &a,
3723 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3724 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3731 REASON_SET(&reason, PFRES_MATCH);
3734 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3737 if (r->action != PF_PASS)
3740 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3741 REASON_SET(&reason, PFRES_MEMORY);
3749 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3750 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3751 struct pf_pdesc *pd, u_short *reason, int *copyback)
3753 struct tcphdr *th = pd->hdr.tcp;
3754 u_int16_t win = ntohs(th->th_win);
3755 u_int32_t ack, end, seq, orig_seq;
3759 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3760 sws = src->wscale & PF_WSCALE_MASK;
3761 dws = dst->wscale & PF_WSCALE_MASK;
3766 * Sequence tracking algorithm from Guido van Rooij's paper:
3767 * http://www.madison-gurkha.com/publications/tcp_filtering/
3771 orig_seq = seq = ntohl(th->th_seq);
3772 if (src->seqlo == 0) {
3773 /* First packet from this end. Set its state */
3775 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3776 src->scrub == NULL) {
3777 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3778 REASON_SET(reason, PFRES_MEMORY);
3783 /* Deferred generation of sequence number modulator */
3784 if (dst->seqdiff && !src->seqdiff) {
3785 /* use random iss for the TCP server */
3786 while ((src->seqdiff = arc4random() - seq) == 0)
3788 ack = ntohl(th->th_ack) - dst->seqdiff;
3789 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3791 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3794 ack = ntohl(th->th_ack);
3797 end = seq + pd->p_len;
3798 if (th->th_flags & TH_SYN) {
3800 if (dst->wscale & PF_WSCALE_FLAG) {
3801 src->wscale = pf_get_wscale(m, off, th->th_off,
3803 if (src->wscale & PF_WSCALE_FLAG) {
3804 /* Remove scale factor from initial
3806 sws = src->wscale & PF_WSCALE_MASK;
3807 win = ((u_int32_t)win + (1 << sws) - 1)
3809 dws = dst->wscale & PF_WSCALE_MASK;
3811 /* fixup other window */
3812 dst->max_win <<= dst->wscale &
3814 /* in case of a retrans SYN|ACK */
3819 if (th->th_flags & TH_FIN)
3823 if (src->state < TCPS_SYN_SENT)
3824 src->state = TCPS_SYN_SENT;
3827 * May need to slide the window (seqhi may have been set by
3828 * the crappy stack check or if we picked up the connection
3829 * after establishment)
3831 if (src->seqhi == 1 ||
3832 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3833 src->seqhi = end + MAX(1, dst->max_win << dws);
3834 if (win > src->max_win)
3838 ack = ntohl(th->th_ack) - dst->seqdiff;
3840 /* Modulate sequence numbers */
3841 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3843 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3846 end = seq + pd->p_len;
3847 if (th->th_flags & TH_SYN)
3849 if (th->th_flags & TH_FIN)
3853 if ((th->th_flags & TH_ACK) == 0) {
3854 /* Let it pass through the ack skew check */
3856 } else if ((ack == 0 &&
3857 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3858 /* broken tcp stacks do not set ack */
3859 (dst->state < TCPS_SYN_SENT)) {
3861 * Many stacks (ours included) will set the ACK number in an
3862 * FIN|ACK if the SYN times out -- no sequence to ACK.
3868 /* Ease sequencing restrictions on no data packets */
3873 ackskew = dst->seqlo - ack;
3877 * Need to demodulate the sequence numbers in any TCP SACK options
3878 * (Selective ACK). We could optionally validate the SACK values
3879 * against the current ACK window, either forwards or backwards, but
3880 * I'm not confident that SACK has been implemented properly
3881 * everywhere. It wouldn't surprise me if several stacks accidently
3882 * SACK too far backwards of previously ACKed data. There really aren't
3883 * any security implications of bad SACKing unless the target stack
3884 * doesn't validate the option length correctly. Someone trying to
3885 * spoof into a TCP connection won't bother blindly sending SACK
3888 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3889 if (pf_modulate_sack(m, off, pd, th, dst))
3894 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
3895 if (SEQ_GEQ(src->seqhi, end) &&
3896 /* Last octet inside other's window space */
3897 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3898 /* Retrans: not more than one window back */
3899 (ackskew >= -MAXACKWINDOW) &&
3900 /* Acking not more than one reassembled fragment backwards */
3901 (ackskew <= (MAXACKWINDOW << sws)) &&
3902 /* Acking not more than one window forward */
3903 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3904 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3905 (pd->flags & PFDESC_IP_REAS) == 0)) {
3906 /* Require an exact/+1 sequence match on resets when possible */
3908 if (dst->scrub || src->scrub) {
3909 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3910 *state, src, dst, copyback))
3914 /* update max window */
3915 if (src->max_win < win)
3917 /* synchronize sequencing */
3918 if (SEQ_GT(end, src->seqlo))
3920 /* slide the window of what the other end can send */
3921 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3922 dst->seqhi = ack + MAX((win << sws), 1);
3926 if (th->th_flags & TH_SYN)
3927 if (src->state < TCPS_SYN_SENT)
3928 src->state = TCPS_SYN_SENT;
3929 if (th->th_flags & TH_FIN)
3930 if (src->state < TCPS_CLOSING)
3931 src->state = TCPS_CLOSING;
3932 if (th->th_flags & TH_ACK) {
3933 if (dst->state == TCPS_SYN_SENT) {
3934 dst->state = TCPS_ESTABLISHED;
3935 if (src->state == TCPS_ESTABLISHED &&
3936 (*state)->src_node != NULL &&
3937 pf_src_connlimit(state)) {
3938 REASON_SET(reason, PFRES_SRCLIMIT);
3941 } else if (dst->state == TCPS_CLOSING)
3942 dst->state = TCPS_FIN_WAIT_2;
3944 if (th->th_flags & TH_RST)
3945 src->state = dst->state = TCPS_TIME_WAIT;
3947 /* update expire time */
3948 (*state)->expire = time_uptime;
3949 if (src->state >= TCPS_FIN_WAIT_2 &&
3950 dst->state >= TCPS_FIN_WAIT_2)
3951 (*state)->timeout = PFTM_TCP_CLOSED;
3952 else if (src->state >= TCPS_CLOSING &&
3953 dst->state >= TCPS_CLOSING)
3954 (*state)->timeout = PFTM_TCP_FIN_WAIT;
3955 else if (src->state < TCPS_ESTABLISHED ||
3956 dst->state < TCPS_ESTABLISHED)
3957 (*state)->timeout = PFTM_TCP_OPENING;
3958 else if (src->state >= TCPS_CLOSING ||
3959 dst->state >= TCPS_CLOSING)
3960 (*state)->timeout = PFTM_TCP_CLOSING;
3962 (*state)->timeout = PFTM_TCP_ESTABLISHED;
3964 /* Fall through to PASS packet */
3966 } else if ((dst->state < TCPS_SYN_SENT ||
3967 dst->state >= TCPS_FIN_WAIT_2 ||
3968 src->state >= TCPS_FIN_WAIT_2) &&
3969 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
3970 /* Within a window forward of the originating packet */
3971 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
3972 /* Within a window backward of the originating packet */
3975 * This currently handles three situations:
3976 * 1) Stupid stacks will shotgun SYNs before their peer
3978 * 2) When PF catches an already established stream (the
3979 * firewall rebooted, the state table was flushed, routes
3981 * 3) Packets get funky immediately after the connection
3982 * closes (this should catch Solaris spurious ACK|FINs
3983 * that web servers like to spew after a close)
3985 * This must be a little more careful than the above code
3986 * since packet floods will also be caught here. We don't
3987 * update the TTL here to mitigate the damage of a packet
3988 * flood and so the same code can handle awkward establishment
3989 * and a loosened connection close.
3990 * In the establishment case, a correct peer response will
3991 * validate the connection, go through the normal state code
3992 * and keep updating the state TTL.
3995 if (V_pf_status.debug >= PF_DEBUG_MISC) {
3996 printf("pf: loose state match: ");
3997 pf_print_state(*state);
3998 pf_print_flags(th->th_flags);
3999 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4000 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4001 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4002 (unsigned long long)(*state)->packets[1],
4003 pd->dir == PF_IN ? "in" : "out",
4004 pd->dir == (*state)->direction ? "fwd" : "rev");
4007 if (dst->scrub || src->scrub) {
4008 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4009 *state, src, dst, copyback))
4013 /* update max window */
4014 if (src->max_win < win)
4016 /* synchronize sequencing */
4017 if (SEQ_GT(end, src->seqlo))
4019 /* slide the window of what the other end can send */
4020 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4021 dst->seqhi = ack + MAX((win << sws), 1);
4024 * Cannot set dst->seqhi here since this could be a shotgunned
4025 * SYN and not an already established connection.
4028 if (th->th_flags & TH_FIN)
4029 if (src->state < TCPS_CLOSING)
4030 src->state = TCPS_CLOSING;
4031 if (th->th_flags & TH_RST)
4032 src->state = dst->state = TCPS_TIME_WAIT;
4034 /* Fall through to PASS packet */
4037 if ((*state)->dst.state == TCPS_SYN_SENT &&
4038 (*state)->src.state == TCPS_SYN_SENT) {
4039 /* Send RST for state mismatches during handshake */
4040 if (!(th->th_flags & TH_RST))
4041 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4042 pd->dst, pd->src, th->th_dport,
4043 th->th_sport, ntohl(th->th_ack), 0,
4045 (*state)->rule.ptr->return_ttl, 1, 0,
4050 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4051 printf("pf: BAD state: ");
4052 pf_print_state(*state);
4053 pf_print_flags(th->th_flags);
4054 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4055 "pkts=%llu:%llu dir=%s,%s\n",
4056 seq, orig_seq, ack, pd->p_len, ackskew,
4057 (unsigned long long)(*state)->packets[0],
4058 (unsigned long long)(*state)->packets[1],
4059 pd->dir == PF_IN ? "in" : "out",
4060 pd->dir == (*state)->direction ? "fwd" : "rev");
4061 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4062 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4063 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4065 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4066 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4067 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4068 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4070 REASON_SET(reason, PFRES_BADSTATE);
4078 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4079 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4081 struct tcphdr *th = pd->hdr.tcp;
4083 if (th->th_flags & TH_SYN)
4084 if (src->state < TCPS_SYN_SENT)
4085 src->state = TCPS_SYN_SENT;
4086 if (th->th_flags & TH_FIN)
4087 if (src->state < TCPS_CLOSING)
4088 src->state = TCPS_CLOSING;
4089 if (th->th_flags & TH_ACK) {
4090 if (dst->state == TCPS_SYN_SENT) {
4091 dst->state = TCPS_ESTABLISHED;
4092 if (src->state == TCPS_ESTABLISHED &&
4093 (*state)->src_node != NULL &&
4094 pf_src_connlimit(state)) {
4095 REASON_SET(reason, PFRES_SRCLIMIT);
4098 } else if (dst->state == TCPS_CLOSING) {
4099 dst->state = TCPS_FIN_WAIT_2;
4100 } else if (src->state == TCPS_SYN_SENT &&
4101 dst->state < TCPS_SYN_SENT) {
4103 * Handle a special sloppy case where we only see one
4104 * half of the connection. If there is a ACK after
4105 * the initial SYN without ever seeing a packet from
4106 * the destination, set the connection to established.
4108 dst->state = src->state = TCPS_ESTABLISHED;
4109 if ((*state)->src_node != NULL &&
4110 pf_src_connlimit(state)) {
4111 REASON_SET(reason, PFRES_SRCLIMIT);
4114 } else if (src->state == TCPS_CLOSING &&
4115 dst->state == TCPS_ESTABLISHED &&
4118 * Handle the closing of half connections where we
4119 * don't see the full bidirectional FIN/ACK+ACK
4122 dst->state = TCPS_CLOSING;
4125 if (th->th_flags & TH_RST)
4126 src->state = dst->state = TCPS_TIME_WAIT;
4128 /* update expire time */
4129 (*state)->expire = time_uptime;
4130 if (src->state >= TCPS_FIN_WAIT_2 &&
4131 dst->state >= TCPS_FIN_WAIT_2)
4132 (*state)->timeout = PFTM_TCP_CLOSED;
4133 else if (src->state >= TCPS_CLOSING &&
4134 dst->state >= TCPS_CLOSING)
4135 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4136 else if (src->state < TCPS_ESTABLISHED ||
4137 dst->state < TCPS_ESTABLISHED)
4138 (*state)->timeout = PFTM_TCP_OPENING;
4139 else if (src->state >= TCPS_CLOSING ||
4140 dst->state >= TCPS_CLOSING)
4141 (*state)->timeout = PFTM_TCP_CLOSING;
4143 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4149 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4150 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4153 struct pf_state_key_cmp key;
4154 struct tcphdr *th = pd->hdr.tcp;
4156 struct pf_state_peer *src, *dst;
4157 struct pf_state_key *sk;
4159 bzero(&key, sizeof(key));
4161 key.proto = IPPROTO_TCP;
4162 if (direction == PF_IN) { /* wire side, straight */
4163 PF_ACPY(&key.addr[0], pd->src, key.af);
4164 PF_ACPY(&key.addr[1], pd->dst, key.af);
4165 key.port[0] = th->th_sport;
4166 key.port[1] = th->th_dport;
4167 } else { /* stack side, reverse */
4168 PF_ACPY(&key.addr[1], pd->src, key.af);
4169 PF_ACPY(&key.addr[0], pd->dst, key.af);
4170 key.port[1] = th->th_sport;
4171 key.port[0] = th->th_dport;
4174 STATE_LOOKUP(kif, &key, direction, *state, pd);
4176 if (direction == (*state)->direction) {
4177 src = &(*state)->src;
4178 dst = &(*state)->dst;
4180 src = &(*state)->dst;
4181 dst = &(*state)->src;
4184 sk = (*state)->key[pd->didx];
4186 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4187 if (direction != (*state)->direction) {
4188 REASON_SET(reason, PFRES_SYNPROXY);
4189 return (PF_SYNPROXY_DROP);
4191 if (th->th_flags & TH_SYN) {
4192 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4193 REASON_SET(reason, PFRES_SYNPROXY);
4196 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4197 pd->src, th->th_dport, th->th_sport,
4198 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4199 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4200 REASON_SET(reason, PFRES_SYNPROXY);
4201 return (PF_SYNPROXY_DROP);
4202 } else if (!(th->th_flags & TH_ACK) ||
4203 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4204 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4205 REASON_SET(reason, PFRES_SYNPROXY);
4207 } else if ((*state)->src_node != NULL &&
4208 pf_src_connlimit(state)) {
4209 REASON_SET(reason, PFRES_SRCLIMIT);
4212 (*state)->src.state = PF_TCPS_PROXY_DST;
4214 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4215 if (direction == (*state)->direction) {
4216 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4217 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4218 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4219 REASON_SET(reason, PFRES_SYNPROXY);
4222 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4223 if ((*state)->dst.seqhi == 1)
4224 (*state)->dst.seqhi = htonl(arc4random());
4225 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4226 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4227 sk->port[pd->sidx], sk->port[pd->didx],
4228 (*state)->dst.seqhi, 0, TH_SYN, 0,
4229 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4230 REASON_SET(reason, PFRES_SYNPROXY);
4231 return (PF_SYNPROXY_DROP);
4232 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4234 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4235 REASON_SET(reason, PFRES_SYNPROXY);
4238 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4239 (*state)->dst.seqlo = ntohl(th->th_seq);
4240 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4241 pd->src, th->th_dport, th->th_sport,
4242 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4243 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4244 (*state)->tag, NULL);
4245 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4246 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4247 sk->port[pd->sidx], sk->port[pd->didx],
4248 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4249 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4250 (*state)->src.seqdiff = (*state)->dst.seqhi -
4251 (*state)->src.seqlo;
4252 (*state)->dst.seqdiff = (*state)->src.seqhi -
4253 (*state)->dst.seqlo;
4254 (*state)->src.seqhi = (*state)->src.seqlo +
4255 (*state)->dst.max_win;
4256 (*state)->dst.seqhi = (*state)->dst.seqlo +
4257 (*state)->src.max_win;
4258 (*state)->src.wscale = (*state)->dst.wscale = 0;
4259 (*state)->src.state = (*state)->dst.state =
4261 REASON_SET(reason, PFRES_SYNPROXY);
4262 return (PF_SYNPROXY_DROP);
4266 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4267 dst->state >= TCPS_FIN_WAIT_2 &&
4268 src->state >= TCPS_FIN_WAIT_2) {
4269 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4270 printf("pf: state reuse ");
4271 pf_print_state(*state);
4272 pf_print_flags(th->th_flags);
4275 /* XXX make sure it's the same direction ?? */
4276 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4277 pf_unlink_state(*state, PF_ENTER_LOCKED);
4282 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4283 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4286 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4287 ©back) == PF_DROP)
4291 /* translate source/destination address, if necessary */
4292 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4293 struct pf_state_key *nk = (*state)->key[pd->didx];
4295 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4296 nk->port[pd->sidx] != th->th_sport)
4297 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4298 &th->th_sum, &nk->addr[pd->sidx],
4299 nk->port[pd->sidx], 0, pd->af);
4301 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4302 nk->port[pd->didx] != th->th_dport)
4303 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4304 &th->th_sum, &nk->addr[pd->didx],
4305 nk->port[pd->didx], 0, pd->af);
4309 /* Copyback sequence modulation or stateful scrub changes if needed */
4311 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4317 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4318 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4320 struct pf_state_peer *src, *dst;
4321 struct pf_state_key_cmp key;
4322 struct udphdr *uh = pd->hdr.udp;
4324 bzero(&key, sizeof(key));
4326 key.proto = IPPROTO_UDP;
4327 if (direction == PF_IN) { /* wire side, straight */
4328 PF_ACPY(&key.addr[0], pd->src, key.af);
4329 PF_ACPY(&key.addr[1], pd->dst, key.af);
4330 key.port[0] = uh->uh_sport;
4331 key.port[1] = uh->uh_dport;
4332 } else { /* stack side, reverse */
4333 PF_ACPY(&key.addr[1], pd->src, key.af);
4334 PF_ACPY(&key.addr[0], pd->dst, key.af);
4335 key.port[1] = uh->uh_sport;
4336 key.port[0] = uh->uh_dport;
4339 STATE_LOOKUP(kif, &key, direction, *state, pd);
4341 if (direction == (*state)->direction) {
4342 src = &(*state)->src;
4343 dst = &(*state)->dst;
4345 src = &(*state)->dst;
4346 dst = &(*state)->src;
4350 if (src->state < PFUDPS_SINGLE)
4351 src->state = PFUDPS_SINGLE;
4352 if (dst->state == PFUDPS_SINGLE)
4353 dst->state = PFUDPS_MULTIPLE;
4355 /* update expire time */
4356 (*state)->expire = time_uptime;
4357 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4358 (*state)->timeout = PFTM_UDP_MULTIPLE;
4360 (*state)->timeout = PFTM_UDP_SINGLE;
4362 /* translate source/destination address, if necessary */
4363 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4364 struct pf_state_key *nk = (*state)->key[pd->didx];
4366 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4367 nk->port[pd->sidx] != uh->uh_sport)
4368 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4369 &uh->uh_sum, &nk->addr[pd->sidx],
4370 nk->port[pd->sidx], 1, pd->af);
4372 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4373 nk->port[pd->didx] != uh->uh_dport)
4374 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4375 &uh->uh_sum, &nk->addr[pd->didx],
4376 nk->port[pd->didx], 1, pd->af);
4377 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4384 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4385 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4387 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4388 u_int16_t icmpid = 0, *icmpsum;
4391 struct pf_state_key_cmp key;
4393 bzero(&key, sizeof(key));
4394 switch (pd->proto) {
4397 icmptype = pd->hdr.icmp->icmp_type;
4398 icmpid = pd->hdr.icmp->icmp_id;
4399 icmpsum = &pd->hdr.icmp->icmp_cksum;
4401 if (icmptype == ICMP_UNREACH ||
4402 icmptype == ICMP_SOURCEQUENCH ||
4403 icmptype == ICMP_REDIRECT ||
4404 icmptype == ICMP_TIMXCEED ||
4405 icmptype == ICMP_PARAMPROB)
4410 case IPPROTO_ICMPV6:
4411 icmptype = pd->hdr.icmp6->icmp6_type;
4412 icmpid = pd->hdr.icmp6->icmp6_id;
4413 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4415 if (icmptype == ICMP6_DST_UNREACH ||
4416 icmptype == ICMP6_PACKET_TOO_BIG ||
4417 icmptype == ICMP6_TIME_EXCEEDED ||
4418 icmptype == ICMP6_PARAM_PROB)
4427 * ICMP query/reply message not related to a TCP/UDP packet.
4428 * Search for an ICMP state.
4431 key.proto = pd->proto;
4432 key.port[0] = key.port[1] = icmpid;
4433 if (direction == PF_IN) { /* wire side, straight */
4434 PF_ACPY(&key.addr[0], pd->src, key.af);
4435 PF_ACPY(&key.addr[1], pd->dst, key.af);
4436 } else { /* stack side, reverse */
4437 PF_ACPY(&key.addr[1], pd->src, key.af);
4438 PF_ACPY(&key.addr[0], pd->dst, key.af);
4441 STATE_LOOKUP(kif, &key, direction, *state, pd);
4443 (*state)->expire = time_uptime;
4444 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4446 /* translate source/destination address, if necessary */
4447 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4448 struct pf_state_key *nk = (*state)->key[pd->didx];
4453 if (PF_ANEQ(pd->src,
4454 &nk->addr[pd->sidx], AF_INET))
4455 pf_change_a(&saddr->v4.s_addr,
4457 nk->addr[pd->sidx].v4.s_addr, 0);
4459 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4461 pf_change_a(&daddr->v4.s_addr,
4463 nk->addr[pd->didx].v4.s_addr, 0);
4466 pd->hdr.icmp->icmp_id) {
4467 pd->hdr.icmp->icmp_cksum =
4469 pd->hdr.icmp->icmp_cksum, icmpid,
4470 nk->port[pd->sidx], 0);
4471 pd->hdr.icmp->icmp_id =
4475 m_copyback(m, off, ICMP_MINLEN,
4476 (caddr_t )pd->hdr.icmp);
4481 if (PF_ANEQ(pd->src,
4482 &nk->addr[pd->sidx], AF_INET6))
4484 &pd->hdr.icmp6->icmp6_cksum,
4485 &nk->addr[pd->sidx], 0);
4487 if (PF_ANEQ(pd->dst,
4488 &nk->addr[pd->didx], AF_INET6))
4490 &pd->hdr.icmp6->icmp6_cksum,
4491 &nk->addr[pd->didx], 0);
4493 m_copyback(m, off, sizeof(struct icmp6_hdr),
4494 (caddr_t )pd->hdr.icmp6);
4503 * ICMP error message in response to a TCP/UDP packet.
4504 * Extract the inner TCP/UDP header and search for that state.
4507 struct pf_pdesc pd2;
4508 bzero(&pd2, sizeof pd2);
4513 struct ip6_hdr h2_6;
4520 /* Payload packet is from the opposite direction. */
4521 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4522 pd2.didx = (direction == PF_IN) ? 0 : 1;
4526 /* offset of h2 in mbuf chain */
4527 ipoff2 = off + ICMP_MINLEN;
4529 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4530 NULL, reason, pd2.af)) {
4531 DPFPRINTF(PF_DEBUG_MISC,
4532 ("pf: ICMP error message too short "
4537 * ICMP error messages don't refer to non-first
4540 if (h2.ip_off & htons(IP_OFFMASK)) {
4541 REASON_SET(reason, PFRES_FRAG);
4545 /* offset of protocol header that follows h2 */
4546 off2 = ipoff2 + (h2.ip_hl << 2);
4548 pd2.proto = h2.ip_p;
4549 pd2.src = (struct pf_addr *)&h2.ip_src;
4550 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4551 pd2.ip_sum = &h2.ip_sum;
4556 ipoff2 = off + sizeof(struct icmp6_hdr);
4558 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4559 NULL, reason, pd2.af)) {
4560 DPFPRINTF(PF_DEBUG_MISC,
4561 ("pf: ICMP error message too short "
4565 pd2.proto = h2_6.ip6_nxt;
4566 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4567 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4569 off2 = ipoff2 + sizeof(h2_6);
4571 switch (pd2.proto) {
4572 case IPPROTO_FRAGMENT:
4574 * ICMPv6 error messages for
4575 * non-first fragments
4577 REASON_SET(reason, PFRES_FRAG);
4580 case IPPROTO_HOPOPTS:
4581 case IPPROTO_ROUTING:
4582 case IPPROTO_DSTOPTS: {
4583 /* get next header and header length */
4584 struct ip6_ext opt6;
4586 if (!pf_pull_hdr(m, off2, &opt6,
4587 sizeof(opt6), NULL, reason,
4589 DPFPRINTF(PF_DEBUG_MISC,
4590 ("pf: ICMPv6 short opt\n"));
4593 if (pd2.proto == IPPROTO_AH)
4594 off2 += (opt6.ip6e_len + 2) * 4;
4596 off2 += (opt6.ip6e_len + 1) * 8;
4597 pd2.proto = opt6.ip6e_nxt;
4598 /* goto the next header */
4605 } while (!terminal);
4610 switch (pd2.proto) {
4614 struct pf_state_peer *src, *dst;
4619 * Only the first 8 bytes of the TCP header can be
4620 * expected. Don't access any TCP header fields after
4621 * th_seq, an ackskew test is not possible.
4623 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4625 DPFPRINTF(PF_DEBUG_MISC,
4626 ("pf: ICMP error message too short "
4632 key.proto = IPPROTO_TCP;
4633 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4634 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4635 key.port[pd2.sidx] = th.th_sport;
4636 key.port[pd2.didx] = th.th_dport;
4638 STATE_LOOKUP(kif, &key, direction, *state, pd);
4640 if (direction == (*state)->direction) {
4641 src = &(*state)->dst;
4642 dst = &(*state)->src;
4644 src = &(*state)->src;
4645 dst = &(*state)->dst;
4648 if (src->wscale && dst->wscale)
4649 dws = dst->wscale & PF_WSCALE_MASK;
4653 /* Demodulate sequence number */
4654 seq = ntohl(th.th_seq) - src->seqdiff;
4656 pf_change_a(&th.th_seq, icmpsum,
4661 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4662 (!SEQ_GEQ(src->seqhi, seq) ||
4663 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4664 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4665 printf("pf: BAD ICMP %d:%d ",
4666 icmptype, pd->hdr.icmp->icmp_code);
4667 pf_print_host(pd->src, 0, pd->af);
4669 pf_print_host(pd->dst, 0, pd->af);
4671 pf_print_state(*state);
4672 printf(" seq=%u\n", seq);
4674 REASON_SET(reason, PFRES_BADSTATE);
4677 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4678 printf("pf: OK ICMP %d:%d ",
4679 icmptype, pd->hdr.icmp->icmp_code);
4680 pf_print_host(pd->src, 0, pd->af);
4682 pf_print_host(pd->dst, 0, pd->af);
4684 pf_print_state(*state);
4685 printf(" seq=%u\n", seq);
4689 /* translate source/destination address, if necessary */
4690 if ((*state)->key[PF_SK_WIRE] !=
4691 (*state)->key[PF_SK_STACK]) {
4692 struct pf_state_key *nk =
4693 (*state)->key[pd->didx];
4695 if (PF_ANEQ(pd2.src,
4696 &nk->addr[pd2.sidx], pd2.af) ||
4697 nk->port[pd2.sidx] != th.th_sport)
4698 pf_change_icmp(pd2.src, &th.th_sport,
4699 daddr, &nk->addr[pd2.sidx],
4700 nk->port[pd2.sidx], NULL,
4701 pd2.ip_sum, icmpsum,
4702 pd->ip_sum, 0, pd2.af);
4704 if (PF_ANEQ(pd2.dst,
4705 &nk->addr[pd2.didx], pd2.af) ||
4706 nk->port[pd2.didx] != th.th_dport)
4707 pf_change_icmp(pd2.dst, &th.th_dport,
4708 NULL, /* XXX Inbound NAT? */
4709 &nk->addr[pd2.didx],
4710 nk->port[pd2.didx], NULL,
4711 pd2.ip_sum, icmpsum,
4712 pd->ip_sum, 0, pd2.af);
4720 m_copyback(m, off, ICMP_MINLEN,
4721 (caddr_t )pd->hdr.icmp);
4722 m_copyback(m, ipoff2, sizeof(h2),
4729 sizeof(struct icmp6_hdr),
4730 (caddr_t )pd->hdr.icmp6);
4731 m_copyback(m, ipoff2, sizeof(h2_6),
4736 m_copyback(m, off2, 8, (caddr_t)&th);
4745 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4746 NULL, reason, pd2.af)) {
4747 DPFPRINTF(PF_DEBUG_MISC,
4748 ("pf: ICMP error message too short "
4754 key.proto = IPPROTO_UDP;
4755 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4756 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4757 key.port[pd2.sidx] = uh.uh_sport;
4758 key.port[pd2.didx] = uh.uh_dport;
4760 STATE_LOOKUP(kif, &key, direction, *state, pd);
4762 /* translate source/destination address, if necessary */
4763 if ((*state)->key[PF_SK_WIRE] !=
4764 (*state)->key[PF_SK_STACK]) {
4765 struct pf_state_key *nk =
4766 (*state)->key[pd->didx];
4768 if (PF_ANEQ(pd2.src,
4769 &nk->addr[pd2.sidx], pd2.af) ||
4770 nk->port[pd2.sidx] != uh.uh_sport)
4771 pf_change_icmp(pd2.src, &uh.uh_sport,
4772 daddr, &nk->addr[pd2.sidx],
4773 nk->port[pd2.sidx], &uh.uh_sum,
4774 pd2.ip_sum, icmpsum,
4775 pd->ip_sum, 1, pd2.af);
4777 if (PF_ANEQ(pd2.dst,
4778 &nk->addr[pd2.didx], pd2.af) ||
4779 nk->port[pd2.didx] != uh.uh_dport)
4780 pf_change_icmp(pd2.dst, &uh.uh_dport,
4781 NULL, /* XXX Inbound NAT? */
4782 &nk->addr[pd2.didx],
4783 nk->port[pd2.didx], &uh.uh_sum,
4784 pd2.ip_sum, icmpsum,
4785 pd->ip_sum, 1, pd2.af);
4790 m_copyback(m, off, ICMP_MINLEN,
4791 (caddr_t )pd->hdr.icmp);
4792 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4798 sizeof(struct icmp6_hdr),
4799 (caddr_t )pd->hdr.icmp6);
4800 m_copyback(m, ipoff2, sizeof(h2_6),
4805 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4811 case IPPROTO_ICMP: {
4814 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4815 NULL, reason, pd2.af)) {
4816 DPFPRINTF(PF_DEBUG_MISC,
4817 ("pf: ICMP error message too short i"
4823 key.proto = IPPROTO_ICMP;
4824 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4825 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4826 key.port[0] = key.port[1] = iih.icmp_id;
4828 STATE_LOOKUP(kif, &key, direction, *state, pd);
4830 /* translate source/destination address, if necessary */
4831 if ((*state)->key[PF_SK_WIRE] !=
4832 (*state)->key[PF_SK_STACK]) {
4833 struct pf_state_key *nk =
4834 (*state)->key[pd->didx];
4836 if (PF_ANEQ(pd2.src,
4837 &nk->addr[pd2.sidx], pd2.af) ||
4838 nk->port[pd2.sidx] != iih.icmp_id)
4839 pf_change_icmp(pd2.src, &iih.icmp_id,
4840 daddr, &nk->addr[pd2.sidx],
4841 nk->port[pd2.sidx], NULL,
4842 pd2.ip_sum, icmpsum,
4843 pd->ip_sum, 0, AF_INET);
4845 if (PF_ANEQ(pd2.dst,
4846 &nk->addr[pd2.didx], pd2.af) ||
4847 nk->port[pd2.didx] != iih.icmp_id)
4848 pf_change_icmp(pd2.dst, &iih.icmp_id,
4849 NULL, /* XXX Inbound NAT? */
4850 &nk->addr[pd2.didx],
4851 nk->port[pd2.didx], NULL,
4852 pd2.ip_sum, icmpsum,
4853 pd->ip_sum, 0, AF_INET);
4855 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4856 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4857 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4864 case IPPROTO_ICMPV6: {
4865 struct icmp6_hdr iih;
4867 if (!pf_pull_hdr(m, off2, &iih,
4868 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4869 DPFPRINTF(PF_DEBUG_MISC,
4870 ("pf: ICMP error message too short "
4876 key.proto = IPPROTO_ICMPV6;
4877 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4878 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4879 key.port[0] = key.port[1] = iih.icmp6_id;
4881 STATE_LOOKUP(kif, &key, direction, *state, pd);
4883 /* translate source/destination address, if necessary */
4884 if ((*state)->key[PF_SK_WIRE] !=
4885 (*state)->key[PF_SK_STACK]) {
4886 struct pf_state_key *nk =
4887 (*state)->key[pd->didx];
4889 if (PF_ANEQ(pd2.src,
4890 &nk->addr[pd2.sidx], pd2.af) ||
4891 nk->port[pd2.sidx] != iih.icmp6_id)
4892 pf_change_icmp(pd2.src, &iih.icmp6_id,
4893 daddr, &nk->addr[pd2.sidx],
4894 nk->port[pd2.sidx], NULL,
4895 pd2.ip_sum, icmpsum,
4896 pd->ip_sum, 0, AF_INET6);
4898 if (PF_ANEQ(pd2.dst,
4899 &nk->addr[pd2.didx], pd2.af) ||
4900 nk->port[pd2.didx] != iih.icmp6_id)
4901 pf_change_icmp(pd2.dst, &iih.icmp6_id,
4902 NULL, /* XXX Inbound NAT? */
4903 &nk->addr[pd2.didx],
4904 nk->port[pd2.didx], NULL,
4905 pd2.ip_sum, icmpsum,
4906 pd->ip_sum, 0, AF_INET6);
4908 m_copyback(m, off, sizeof(struct icmp6_hdr),
4909 (caddr_t)pd->hdr.icmp6);
4910 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4911 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4920 key.proto = pd2.proto;
4921 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4922 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4923 key.port[0] = key.port[1] = 0;
4925 STATE_LOOKUP(kif, &key, direction, *state, pd);
4927 /* translate source/destination address, if necessary */
4928 if ((*state)->key[PF_SK_WIRE] !=
4929 (*state)->key[PF_SK_STACK]) {
4930 struct pf_state_key *nk =
4931 (*state)->key[pd->didx];
4933 if (PF_ANEQ(pd2.src,
4934 &nk->addr[pd2.sidx], pd2.af))
4935 pf_change_icmp(pd2.src, NULL, daddr,
4936 &nk->addr[pd2.sidx], 0, NULL,
4937 pd2.ip_sum, icmpsum,
4938 pd->ip_sum, 0, pd2.af);
4940 if (PF_ANEQ(pd2.dst,
4941 &nk->addr[pd2.didx], pd2.af))
4942 pf_change_icmp(pd2.src, NULL,
4943 NULL, /* XXX Inbound NAT? */
4944 &nk->addr[pd2.didx], 0, NULL,
4945 pd2.ip_sum, icmpsum,
4946 pd->ip_sum, 0, pd2.af);
4951 m_copyback(m, off, ICMP_MINLEN,
4952 (caddr_t)pd->hdr.icmp);
4953 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4959 sizeof(struct icmp6_hdr),
4960 (caddr_t )pd->hdr.icmp6);
4961 m_copyback(m, ipoff2, sizeof(h2_6),
4975 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
4976 struct mbuf *m, struct pf_pdesc *pd)
4978 struct pf_state_peer *src, *dst;
4979 struct pf_state_key_cmp key;
4981 bzero(&key, sizeof(key));
4983 key.proto = pd->proto;
4984 if (direction == PF_IN) {
4985 PF_ACPY(&key.addr[0], pd->src, key.af);
4986 PF_ACPY(&key.addr[1], pd->dst, key.af);
4987 key.port[0] = key.port[1] = 0;
4989 PF_ACPY(&key.addr[1], pd->src, key.af);
4990 PF_ACPY(&key.addr[0], pd->dst, key.af);
4991 key.port[1] = key.port[0] = 0;
4994 STATE_LOOKUP(kif, &key, direction, *state, pd);
4996 if (direction == (*state)->direction) {
4997 src = &(*state)->src;
4998 dst = &(*state)->dst;
5000 src = &(*state)->dst;
5001 dst = &(*state)->src;
5005 if (src->state < PFOTHERS_SINGLE)
5006 src->state = PFOTHERS_SINGLE;
5007 if (dst->state == PFOTHERS_SINGLE)
5008 dst->state = PFOTHERS_MULTIPLE;
5010 /* update expire time */
5011 (*state)->expire = time_uptime;
5012 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5013 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5015 (*state)->timeout = PFTM_OTHER_SINGLE;
5017 /* translate source/destination address, if necessary */
5018 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5019 struct pf_state_key *nk = (*state)->key[pd->didx];
5021 KASSERT(nk, ("%s: nk is null", __func__));
5022 KASSERT(pd, ("%s: pd is null", __func__));
5023 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5024 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5028 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5029 pf_change_a(&pd->src->v4.s_addr,
5031 nk->addr[pd->sidx].v4.s_addr,
5035 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5036 pf_change_a(&pd->dst->v4.s_addr,
5038 nk->addr[pd->didx].v4.s_addr,
5045 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5046 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5048 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5049 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5057 * ipoff and off are measured from the start of the mbuf chain.
5058 * h must be at "ipoff" on the mbuf chain.
5061 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5062 u_short *actionp, u_short *reasonp, sa_family_t af)
5067 struct ip *h = mtod(m, struct ip *);
5068 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5072 ACTION_SET(actionp, PF_PASS);
5074 ACTION_SET(actionp, PF_DROP);
5075 REASON_SET(reasonp, PFRES_FRAG);
5079 if (m->m_pkthdr.len < off + len ||
5080 ntohs(h->ip_len) < off + len) {
5081 ACTION_SET(actionp, PF_DROP);
5082 REASON_SET(reasonp, PFRES_SHORT);
5090 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5092 if (m->m_pkthdr.len < off + len ||
5093 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5094 (unsigned)(off + len)) {
5095 ACTION_SET(actionp, PF_DROP);
5096 REASON_SET(reasonp, PFRES_SHORT);
5103 m_copydata(m, off, len, p);
5108 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5112 struct radix_node_head *rnh;
5114 struct sockaddr_in *dst;
5118 struct sockaddr_in6 *dst6;
5119 struct route_in6 ro;
5123 struct radix_node *rn;
5129 /* XXX: stick to table 0 for now */
5130 rnh = rt_tables_get_rnh(0, af);
5131 if (rnh != NULL && rn_mpath_capable(rnh))
5134 bzero(&ro, sizeof(ro));
5137 dst = satosin(&ro.ro_dst);
5138 dst->sin_family = AF_INET;
5139 dst->sin_len = sizeof(*dst);
5140 dst->sin_addr = addr->v4;
5145 * Skip check for addresses with embedded interface scope,
5146 * as they would always match anyway.
5148 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5150 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5151 dst6->sin6_family = AF_INET6;
5152 dst6->sin6_len = sizeof(*dst6);
5153 dst6->sin6_addr = addr->v6;
5160 /* Skip checks for ipsec interfaces */
5161 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5167 in6_rtalloc_ign(&ro, 0, rtableid);
5172 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5176 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5180 if (ro.ro_rt != NULL) {
5181 /* No interface given, this is a no-route check */
5185 if (kif->pfik_ifp == NULL) {
5190 /* Perform uRPF check if passed input interface */
5192 rn = (struct radix_node *)ro.ro_rt;
5194 rt = (struct rtentry *)rn;
5197 if (kif->pfik_ifp == ifp)
5200 rn = rn_mpath_next(rn);
5202 } while (check_mpath == 1 && rn != NULL && ret == 0);
5206 if (ro.ro_rt != NULL)
5213 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5214 struct pf_state *s, struct pf_pdesc *pd)
5216 struct mbuf *m0, *m1;
5217 struct sockaddr_in dst;
5219 struct ifnet *ifp = NULL;
5220 struct pf_addr naddr;
5221 struct pf_src_node *sn = NULL;
5223 uint16_t ip_len, ip_off;
5225 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5226 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5229 if ((pd->pf_mtag == NULL &&
5230 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5231 pd->pf_mtag->routed++ > 3) {
5237 if (r->rt == PF_DUPTO) {
5238 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5244 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5252 ip = mtod(m0, struct ip *);
5254 bzero(&dst, sizeof(dst));
5255 dst.sin_family = AF_INET;
5256 dst.sin_len = sizeof(dst);
5257 dst.sin_addr = ip->ip_dst;
5259 if (r->rt == PF_FASTROUTE) {
5264 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5266 KMOD_IPSTAT_INC(ips_noroute);
5267 error = EHOSTUNREACH;
5272 counter_u64_add(rt->rt_pksent, 1);
5274 if (rt->rt_flags & RTF_GATEWAY)
5275 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5278 if (TAILQ_EMPTY(&r->rpool.list)) {
5279 DPFPRINTF(PF_DEBUG_URGENT,
5280 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5284 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5286 if (!PF_AZERO(&naddr, AF_INET))
5287 dst.sin_addr.s_addr = naddr.v4.s_addr;
5288 ifp = r->rpool.cur->kif ?
5289 r->rpool.cur->kif->pfik_ifp : NULL;
5291 if (!PF_AZERO(&s->rt_addr, AF_INET))
5292 dst.sin_addr.s_addr =
5293 s->rt_addr.v4.s_addr;
5294 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5302 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5304 else if (m0 == NULL)
5306 if (m0->m_len < sizeof(struct ip)) {
5307 DPFPRINTF(PF_DEBUG_URGENT,
5308 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5311 ip = mtod(m0, struct ip *);
5314 if (ifp->if_flags & IFF_LOOPBACK)
5315 m0->m_flags |= M_SKIP_FIREWALL;
5317 ip_len = ntohs(ip->ip_len);
5318 ip_off = ntohs(ip->ip_off);
5320 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5321 m0->m_pkthdr.csum_flags |= CSUM_IP;
5322 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5323 in_delayed_cksum(m0);
5324 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5327 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5328 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5329 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5334 * If small enough for interface, or the interface will take
5335 * care of the fragmentation for us, we can just send directly.
5337 if (ip_len <= ifp->if_mtu ||
5338 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5339 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5341 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5342 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5343 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5345 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5346 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5350 /* Balk when DF bit is set or the interface didn't support TSO. */
5351 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5353 KMOD_IPSTAT_INC(ips_cantfrag);
5354 if (r->rt != PF_DUPTO) {
5355 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5362 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5366 for (; m0; m0 = m1) {
5368 m0->m_nextpkt = NULL;
5370 m_clrprotoflags(m0);
5371 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5377 KMOD_IPSTAT_INC(ips_fragmented);
5380 if (r->rt != PF_DUPTO)
5395 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5396 struct pf_state *s, struct pf_pdesc *pd)
5399 struct sockaddr_in6 dst;
5400 struct ip6_hdr *ip6;
5401 struct ifnet *ifp = NULL;
5402 struct pf_addr naddr;
5403 struct pf_src_node *sn = NULL;
5405 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5406 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5409 if ((pd->pf_mtag == NULL &&
5410 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5411 pd->pf_mtag->routed++ > 3) {
5417 if (r->rt == PF_DUPTO) {
5418 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5424 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5432 ip6 = mtod(m0, struct ip6_hdr *);
5434 bzero(&dst, sizeof(dst));
5435 dst.sin6_family = AF_INET6;
5436 dst.sin6_len = sizeof(dst);
5437 dst.sin6_addr = ip6->ip6_dst;
5439 /* Cheat. XXX why only in the v6 case??? */
5440 if (r->rt == PF_FASTROUTE) {
5443 m0->m_flags |= M_SKIP_FIREWALL;
5444 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5448 if (TAILQ_EMPTY(&r->rpool.list)) {
5449 DPFPRINTF(PF_DEBUG_URGENT,
5450 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5454 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5456 if (!PF_AZERO(&naddr, AF_INET6))
5457 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5459 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5461 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5462 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5463 &s->rt_addr, AF_INET6);
5464 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5474 if (pf_test6(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5476 else if (m0 == NULL)
5478 if (m0->m_len < sizeof(struct ip6_hdr)) {
5479 DPFPRINTF(PF_DEBUG_URGENT,
5480 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5484 ip6 = mtod(m0, struct ip6_hdr *);
5487 if (ifp->if_flags & IFF_LOOPBACK)
5488 m0->m_flags |= M_SKIP_FIREWALL;
5491 * If the packet is too large for the outgoing interface,
5492 * send back an icmp6 error.
5494 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5495 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5496 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5497 nd6_output(ifp, ifp, m0, &dst, NULL);
5499 in6_ifstat_inc(ifp, ifs6_in_toobig);
5500 if (r->rt != PF_DUPTO)
5501 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5507 if (r->rt != PF_DUPTO)
5521 * FreeBSD supports cksum offloads for the following drivers.
5522 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5523 * ti(4), txp(4), xl(4)
5525 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5526 * network driver performed cksum including pseudo header, need to verify
5529 * network driver performed cksum, needs to additional pseudo header
5530 * cksum computation with partial csum_data(i.e. lack of H/W support for
5531 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5533 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5534 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5536 * Also, set csum_data to 0xffff to force cksum validation.
5539 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5545 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5547 if (m->m_pkthdr.len < off + len)
5552 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5553 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5554 sum = m->m_pkthdr.csum_data;
5556 ip = mtod(m, struct ip *);
5557 sum = in_pseudo(ip->ip_src.s_addr,
5558 ip->ip_dst.s_addr, htonl((u_short)len +
5559 m->m_pkthdr.csum_data + IPPROTO_TCP));
5566 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5567 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5568 sum = m->m_pkthdr.csum_data;
5570 ip = mtod(m, struct ip *);
5571 sum = in_pseudo(ip->ip_src.s_addr,
5572 ip->ip_dst.s_addr, htonl((u_short)len +
5573 m->m_pkthdr.csum_data + IPPROTO_UDP));
5581 case IPPROTO_ICMPV6:
5591 if (p == IPPROTO_ICMP) {
5596 sum = in_cksum(m, len);
5600 if (m->m_len < sizeof(struct ip))
5602 sum = in4_cksum(m, p, off, len);
5607 if (m->m_len < sizeof(struct ip6_hdr))
5609 sum = in6_cksum(m, p, off, len);
5620 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5625 KMOD_UDPSTAT_INC(udps_badsum);
5631 KMOD_ICMPSTAT_INC(icps_checksum);
5636 case IPPROTO_ICMPV6:
5638 KMOD_ICMP6STAT_INC(icp6s_checksum);
5645 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5646 m->m_pkthdr.csum_flags |=
5647 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5648 m->m_pkthdr.csum_data = 0xffff;
5657 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5659 struct pfi_kif *kif;
5660 u_short action, reason = 0, log = 0;
5661 struct mbuf *m = *m0;
5662 struct ip *h = NULL;
5663 struct m_tag *ipfwtag;
5664 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5665 struct pf_state *s = NULL;
5666 struct pf_ruleset *ruleset = NULL;
5668 int off, dirndx, pqid = 0;
5672 if (!V_pf_status.running)
5675 memset(&pd, 0, sizeof(pd));
5677 kif = (struct pfi_kif *)ifp->if_pf_kif;
5680 DPFPRINTF(PF_DEBUG_URGENT,
5681 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5684 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5687 if (m->m_flags & M_SKIP_FIREWALL)
5690 pd.pf_mtag = pf_find_mtag(m);
5694 if (ip_divert_ptr != NULL &&
5695 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5696 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5697 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5698 if (pd.pf_mtag == NULL &&
5699 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5703 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5704 m_tag_delete(m, ipfwtag);
5706 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5707 m->m_flags |= M_FASTFWD_OURS;
5708 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5710 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5711 /* We do IP header normalization and packet reassembly here */
5715 m = *m0; /* pf_normalize messes with m0 */
5716 h = mtod(m, struct ip *);
5718 off = h->ip_hl << 2;
5719 if (off < (int)sizeof(struct ip)) {
5721 REASON_SET(&reason, PFRES_SHORT);
5726 pd.src = (struct pf_addr *)&h->ip_src;
5727 pd.dst = (struct pf_addr *)&h->ip_dst;
5728 pd.sport = pd.dport = NULL;
5729 pd.ip_sum = &h->ip_sum;
5730 pd.proto_sum = NULL;
5733 pd.sidx = (dir == PF_IN) ? 0 : 1;
5734 pd.didx = (dir == PF_IN) ? 1 : 0;
5737 pd.tot_len = ntohs(h->ip_len);
5739 /* handle fragments that didn't get reassembled by normalization */
5740 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5741 action = pf_test_fragment(&r, dir, kif, m, h,
5752 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5753 &action, &reason, AF_INET)) {
5754 log = action != PF_PASS;
5757 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5758 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5760 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5761 if (action == PF_DROP)
5763 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5765 if (action == PF_PASS) {
5766 if (pfsync_update_state_ptr != NULL)
5767 pfsync_update_state_ptr(s);
5771 } else if (s == NULL)
5772 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5781 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5782 &action, &reason, AF_INET)) {
5783 log = action != PF_PASS;
5786 if (uh.uh_dport == 0 ||
5787 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5788 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5790 REASON_SET(&reason, PFRES_SHORT);
5793 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5794 if (action == PF_PASS) {
5795 if (pfsync_update_state_ptr != NULL)
5796 pfsync_update_state_ptr(s);
5800 } else if (s == NULL)
5801 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5806 case IPPROTO_ICMP: {
5810 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5811 &action, &reason, AF_INET)) {
5812 log = action != PF_PASS;
5815 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5817 if (action == PF_PASS) {
5818 if (pfsync_update_state_ptr != NULL)
5819 pfsync_update_state_ptr(s);
5823 } else if (s == NULL)
5824 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5830 case IPPROTO_ICMPV6: {
5832 DPFPRINTF(PF_DEBUG_MISC,
5833 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5839 action = pf_test_state_other(&s, dir, kif, m, &pd);
5840 if (action == PF_PASS) {
5841 if (pfsync_update_state_ptr != NULL)
5842 pfsync_update_state_ptr(s);
5846 } else if (s == NULL)
5847 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5854 if (action == PF_PASS && h->ip_hl > 5 &&
5855 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5857 REASON_SET(&reason, PFRES_IPOPTIONS);
5859 DPFPRINTF(PF_DEBUG_MISC,
5860 ("pf: dropping packet with ip options\n"));
5863 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5865 REASON_SET(&reason, PFRES_MEMORY);
5867 if (r->rtableid >= 0)
5868 M_SETFIB(m, r->rtableid);
5871 if (action == PF_PASS && r->qid) {
5872 if (pd.pf_mtag == NULL &&
5873 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5875 REASON_SET(&reason, PFRES_MEMORY);
5877 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5878 pd.pf_mtag->qid = r->pqid;
5880 pd.pf_mtag->qid = r->qid;
5881 /* add hints for ecn */
5882 pd.pf_mtag->hdr = h;
5888 * connections redirected to loopback should not match sockets
5889 * bound specifically to loopback due to security implications,
5890 * see tcp_input() and in_pcblookup_listen().
5892 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5893 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5894 (s->nat_rule.ptr->action == PF_RDR ||
5895 s->nat_rule.ptr->action == PF_BINAT) &&
5896 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5897 m->m_flags |= M_SKIP_FIREWALL;
5899 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5900 !PACKET_LOOPED(&pd)) {
5902 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5903 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5904 if (ipfwtag != NULL) {
5905 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5906 ntohs(r->divert.port);
5907 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5912 m_tag_prepend(m, ipfwtag);
5913 if (m->m_flags & M_FASTFWD_OURS) {
5914 if (pd.pf_mtag == NULL &&
5915 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5917 REASON_SET(&reason, PFRES_MEMORY);
5919 DPFPRINTF(PF_DEBUG_MISC,
5920 ("pf: failed to allocate tag\n"));
5922 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5923 m->m_flags &= ~M_FASTFWD_OURS;
5925 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
5930 /* XXX: ipfw has the same behaviour! */
5932 REASON_SET(&reason, PFRES_MEMORY);
5934 DPFPRINTF(PF_DEBUG_MISC,
5935 ("pf: failed to allocate divert tag\n"));
5942 if (s != NULL && s->nat_rule.ptr != NULL &&
5943 s->nat_rule.ptr->log & PF_LOG_ALL)
5944 lr = s->nat_rule.ptr;
5947 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5951 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5952 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5954 if (action == PF_PASS || r->action == PF_DROP) {
5955 dirndx = (dir == PF_OUT);
5956 r->packets[dirndx]++;
5957 r->bytes[dirndx] += pd.tot_len;
5959 a->packets[dirndx]++;
5960 a->bytes[dirndx] += pd.tot_len;
5963 if (s->nat_rule.ptr != NULL) {
5964 s->nat_rule.ptr->packets[dirndx]++;
5965 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
5967 if (s->src_node != NULL) {
5968 s->src_node->packets[dirndx]++;
5969 s->src_node->bytes[dirndx] += pd.tot_len;
5971 if (s->nat_src_node != NULL) {
5972 s->nat_src_node->packets[dirndx]++;
5973 s->nat_src_node->bytes[dirndx] += pd.tot_len;
5975 dirndx = (dir == s->direction) ? 0 : 1;
5976 s->packets[dirndx]++;
5977 s->bytes[dirndx] += pd.tot_len;
5980 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
5981 if (nr != NULL && r == &V_pf_default_rule)
5983 if (tr->src.addr.type == PF_ADDR_TABLE)
5984 pfr_update_stats(tr->src.addr.p.tbl,
5985 (s == NULL) ? pd.src :
5986 &s->key[(s->direction == PF_IN)]->
5987 addr[(s->direction == PF_OUT)],
5988 pd.af, pd.tot_len, dir == PF_OUT,
5989 r->action == PF_PASS, tr->src.neg);
5990 if (tr->dst.addr.type == PF_ADDR_TABLE)
5991 pfr_update_stats(tr->dst.addr.p.tbl,
5992 (s == NULL) ? pd.dst :
5993 &s->key[(s->direction == PF_IN)]->
5994 addr[(s->direction == PF_IN)],
5995 pd.af, pd.tot_len, dir == PF_OUT,
5996 r->action == PF_PASS, tr->dst.neg);
6000 case PF_SYNPROXY_DROP:
6007 /* pf_route() returns unlocked. */
6009 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6023 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6025 struct pfi_kif *kif;
6026 u_short action, reason = 0, log = 0;
6027 struct mbuf *m = *m0, *n = NULL;
6028 struct ip6_hdr *h = NULL;
6029 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6030 struct pf_state *s = NULL;
6031 struct pf_ruleset *ruleset = NULL;
6033 int off, terminal = 0, dirndx, rh_cnt = 0;
6037 if (!V_pf_status.running)
6040 memset(&pd, 0, sizeof(pd));
6041 pd.pf_mtag = pf_find_mtag(m);
6043 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6046 kif = (struct pfi_kif *)ifp->if_pf_kif;
6048 DPFPRINTF(PF_DEBUG_URGENT,
6049 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6052 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6055 if (m->m_flags & M_SKIP_FIREWALL)
6060 /* We do IP header normalization and packet reassembly here */
6061 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6065 m = *m0; /* pf_normalize messes with m0 */
6066 h = mtod(m, struct ip6_hdr *);
6070 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6071 * will do something bad, so drop the packet for now.
6073 if (htons(h->ip6_plen) == 0) {
6075 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6080 pd.src = (struct pf_addr *)&h->ip6_src;
6081 pd.dst = (struct pf_addr *)&h->ip6_dst;
6082 pd.sport = pd.dport = NULL;
6084 pd.proto_sum = NULL;
6086 pd.sidx = (dir == PF_IN) ? 0 : 1;
6087 pd.didx = (dir == PF_IN) ? 1 : 0;
6090 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6092 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6093 pd.proto = h->ip6_nxt;
6096 case IPPROTO_FRAGMENT:
6097 action = pf_test_fragment(&r, dir, kif, m, h,
6099 if (action == PF_DROP)
6100 REASON_SET(&reason, PFRES_FRAG);
6102 case IPPROTO_ROUTING: {
6103 struct ip6_rthdr rthdr;
6106 DPFPRINTF(PF_DEBUG_MISC,
6107 ("pf: IPv6 more than one rthdr\n"));
6109 REASON_SET(&reason, PFRES_IPOPTIONS);
6113 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6115 DPFPRINTF(PF_DEBUG_MISC,
6116 ("pf: IPv6 short rthdr\n"));
6118 REASON_SET(&reason, PFRES_SHORT);
6122 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6123 DPFPRINTF(PF_DEBUG_MISC,
6124 ("pf: IPv6 rthdr0\n"));
6126 REASON_SET(&reason, PFRES_IPOPTIONS);
6133 case IPPROTO_HOPOPTS:
6134 case IPPROTO_DSTOPTS: {
6135 /* get next header and header length */
6136 struct ip6_ext opt6;
6138 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6139 NULL, &reason, pd.af)) {
6140 DPFPRINTF(PF_DEBUG_MISC,
6141 ("pf: IPv6 short opt\n"));
6146 if (pd.proto == IPPROTO_AH)
6147 off += (opt6.ip6e_len + 2) * 4;
6149 off += (opt6.ip6e_len + 1) * 8;
6150 pd.proto = opt6.ip6e_nxt;
6151 /* goto the next header */
6158 } while (!terminal);
6160 /* if there's no routing header, use unmodified mbuf for checksumming */
6170 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6171 &action, &reason, AF_INET6)) {
6172 log = action != PF_PASS;
6175 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6176 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6177 if (action == PF_DROP)
6179 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6181 if (action == PF_PASS) {
6182 if (pfsync_update_state_ptr != NULL)
6183 pfsync_update_state_ptr(s);
6187 } else if (s == NULL)
6188 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6197 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6198 &action, &reason, AF_INET6)) {
6199 log = action != PF_PASS;
6202 if (uh.uh_dport == 0 ||
6203 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6204 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6206 REASON_SET(&reason, PFRES_SHORT);
6209 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6210 if (action == PF_PASS) {
6211 if (pfsync_update_state_ptr != NULL)
6212 pfsync_update_state_ptr(s);
6216 } else if (s == NULL)
6217 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6222 case IPPROTO_ICMP: {
6224 DPFPRINTF(PF_DEBUG_MISC,
6225 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6229 case IPPROTO_ICMPV6: {
6230 struct icmp6_hdr ih;
6233 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6234 &action, &reason, AF_INET6)) {
6235 log = action != PF_PASS;
6238 action = pf_test_state_icmp(&s, dir, kif,
6239 m, off, h, &pd, &reason);
6240 if (action == PF_PASS) {
6241 if (pfsync_update_state_ptr != NULL)
6242 pfsync_update_state_ptr(s);
6246 } else if (s == NULL)
6247 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6253 action = pf_test_state_other(&s, dir, kif, m, &pd);
6254 if (action == PF_PASS) {
6255 if (pfsync_update_state_ptr != NULL)
6256 pfsync_update_state_ptr(s);
6260 } else if (s == NULL)
6261 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6273 /* handle dangerous IPv6 extension headers. */
6274 if (action == PF_PASS && rh_cnt &&
6275 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6277 REASON_SET(&reason, PFRES_IPOPTIONS);
6279 DPFPRINTF(PF_DEBUG_MISC,
6280 ("pf: dropping packet with dangerous v6 headers\n"));
6283 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6285 REASON_SET(&reason, PFRES_MEMORY);
6287 if (r->rtableid >= 0)
6288 M_SETFIB(m, r->rtableid);
6291 if (action == PF_PASS && r->qid) {
6292 if (pd.pf_mtag == NULL &&
6293 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6295 REASON_SET(&reason, PFRES_MEMORY);
6297 if (pd.tos & IPTOS_LOWDELAY)
6298 pd.pf_mtag->qid = r->pqid;
6300 pd.pf_mtag->qid = r->qid;
6301 /* add hints for ecn */
6302 pd.pf_mtag->hdr = h;
6306 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6307 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6308 (s->nat_rule.ptr->action == PF_RDR ||
6309 s->nat_rule.ptr->action == PF_BINAT) &&
6310 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6311 m->m_flags |= M_SKIP_FIREWALL;
6313 /* XXX: Anybody working on it?! */
6315 printf("pf: divert(9) is not supported for IPv6\n");
6320 if (s != NULL && s->nat_rule.ptr != NULL &&
6321 s->nat_rule.ptr->log & PF_LOG_ALL)
6322 lr = s->nat_rule.ptr;
6325 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6329 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6330 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6332 if (action == PF_PASS || r->action == PF_DROP) {
6333 dirndx = (dir == PF_OUT);
6334 r->packets[dirndx]++;
6335 r->bytes[dirndx] += pd.tot_len;
6337 a->packets[dirndx]++;
6338 a->bytes[dirndx] += pd.tot_len;
6341 if (s->nat_rule.ptr != NULL) {
6342 s->nat_rule.ptr->packets[dirndx]++;
6343 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6345 if (s->src_node != NULL) {
6346 s->src_node->packets[dirndx]++;
6347 s->src_node->bytes[dirndx] += pd.tot_len;
6349 if (s->nat_src_node != NULL) {
6350 s->nat_src_node->packets[dirndx]++;
6351 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6353 dirndx = (dir == s->direction) ? 0 : 1;
6354 s->packets[dirndx]++;
6355 s->bytes[dirndx] += pd.tot_len;
6358 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6359 if (nr != NULL && r == &V_pf_default_rule)
6361 if (tr->src.addr.type == PF_ADDR_TABLE)
6362 pfr_update_stats(tr->src.addr.p.tbl,
6363 (s == NULL) ? pd.src :
6364 &s->key[(s->direction == PF_IN)]->addr[0],
6365 pd.af, pd.tot_len, dir == PF_OUT,
6366 r->action == PF_PASS, tr->src.neg);
6367 if (tr->dst.addr.type == PF_ADDR_TABLE)
6368 pfr_update_stats(tr->dst.addr.p.tbl,
6369 (s == NULL) ? pd.dst :
6370 &s->key[(s->direction == PF_IN)]->addr[1],
6371 pd.af, pd.tot_len, dir == PF_OUT,
6372 r->action == PF_PASS, tr->dst.neg);
6376 case PF_SYNPROXY_DROP:
6383 /* pf_route6() returns unlocked. */
6385 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);