2 * Copyright (c) 2001 Daniel Hartmeier
3 * Copyright (c) 2002 - 2008 Henning Brauer
4 * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
31 * Effort sponsored in part by the Defense Advanced Research Projects
32 * Agency (DARPA) and Air Force Research Laboratory, Air Force
33 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
35 * $OpenBSD: pf.c,v 1.634 2009/02/27 12:37:45 henning Exp $
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
42 #include "opt_inet6.h"
46 #include <sys/param.h>
48 #include <sys/endian.h>
50 #include <sys/interrupt.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
53 #include <sys/limits.h>
56 #include <sys/random.h>
57 #include <sys/refcount.h>
58 #include <sys/socket.h>
59 #include <sys/sysctl.h>
60 #include <sys/taskqueue.h>
61 #include <sys/ucred.h>
64 #include <net/if_types.h>
65 #include <net/route.h>
66 #include <net/radix_mpath.h>
69 #include <net/pfvar.h>
70 #include <net/if_pflog.h>
71 #include <net/if_pfsync.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/in_var.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_fw.h>
77 #include <netinet/ip_icmp.h>
78 #include <netinet/icmp_var.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/tcp.h>
81 #include <netinet/tcp_fsm.h>
82 #include <netinet/tcp_seq.h>
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #include <netinet/udp.h>
86 #include <netinet/udp_var.h>
88 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
91 #include <netinet/ip6.h>
92 #include <netinet/icmp6.h>
93 #include <netinet6/nd6.h>
94 #include <netinet6/ip6_var.h>
95 #include <netinet6/in6_pcb.h>
98 #include <machine/in_cksum.h>
99 #include <security/mac/mac_framework.h>
101 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
108 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
109 VNET_DEFINE(struct pf_palist, pf_pabuf);
110 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
111 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
112 VNET_DEFINE(struct pf_kstatus, pf_status);
114 VNET_DEFINE(u_int32_t, ticket_altqs_active);
115 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
116 VNET_DEFINE(int, altqs_inactive_open);
117 VNET_DEFINE(u_int32_t, ticket_pabuf);
119 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
120 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
121 VNET_DEFINE(u_char, pf_tcp_secret[16]);
122 #define V_pf_tcp_secret VNET(pf_tcp_secret)
123 VNET_DEFINE(int, pf_tcp_secret_init);
124 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
125 VNET_DEFINE(int, pf_tcp_iss_off);
126 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
129 * Queue for pf_intr() sends.
131 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
132 struct pf_send_entry {
133 STAILQ_ENTRY(pf_send_entry) pfse_next;
150 #define pfse_icmp_type u.icmpopts.type
151 #define pfse_icmp_code u.icmpopts.code
152 #define pfse_icmp_mtu u.icmpopts.mtu
155 STAILQ_HEAD(pf_send_head, pf_send_entry);
156 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
157 #define V_pf_sendqueue VNET(pf_sendqueue)
159 static struct mtx pf_sendqueue_mtx;
160 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
161 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
164 * Queue for pf_overload_task() tasks.
166 struct pf_overload_entry {
167 SLIST_ENTRY(pf_overload_entry) next;
171 struct pf_rule *rule;
174 SLIST_HEAD(pf_overload_head, pf_overload_entry);
175 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
176 #define V_pf_overloadqueue VNET(pf_overloadqueue)
177 static VNET_DEFINE(struct task, pf_overloadtask);
178 #define V_pf_overloadtask VNET(pf_overloadtask)
180 static struct mtx pf_overloadqueue_mtx;
181 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
182 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
184 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
185 struct mtx pf_unlnkdrules_mtx;
187 static VNET_DEFINE(uma_zone_t, pf_sources_z);
188 #define V_pf_sources_z VNET(pf_sources_z)
189 uma_zone_t pf_mtag_z;
190 VNET_DEFINE(uma_zone_t, pf_state_z);
191 VNET_DEFINE(uma_zone_t, pf_state_key_z);
193 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
194 #define PFID_CPUBITS 8
195 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
196 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
197 #define PFID_MAXID (~PFID_CPUMASK)
198 CTASSERT((1 << PFID_CPUBITS) > MAXCPU);
200 static void pf_src_tree_remove_state(struct pf_state *);
201 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
203 static void pf_add_threshold(struct pf_threshold *);
204 static int pf_check_threshold(struct pf_threshold *);
206 static void pf_change_ap(struct pf_addr *, u_int16_t *,
207 u_int16_t *, u_int16_t *, struct pf_addr *,
208 u_int16_t, u_int8_t, sa_family_t);
209 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
210 struct tcphdr *, struct pf_state_peer *);
211 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
212 struct pf_addr *, struct pf_addr *, u_int16_t,
213 u_int16_t *, u_int16_t *, u_int16_t *,
214 u_int16_t *, u_int8_t, sa_family_t);
215 static void pf_send_tcp(struct mbuf *,
216 const struct pf_rule *, sa_family_t,
217 const struct pf_addr *, const struct pf_addr *,
218 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
219 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
220 u_int16_t, struct ifnet *);
221 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
222 sa_family_t, struct pf_rule *);
223 static void pf_detach_state(struct pf_state *);
224 static int pf_state_key_attach(struct pf_state_key *,
225 struct pf_state_key *, struct pf_state *);
226 static void pf_state_key_detach(struct pf_state *, int);
227 static int pf_state_key_ctor(void *, int, void *, int);
228 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
229 static int pf_test_rule(struct pf_rule **, struct pf_state **,
230 int, struct pfi_kif *, struct mbuf *, int,
231 struct pf_pdesc *, struct pf_rule **,
232 struct pf_ruleset **, struct inpcb *);
233 static int pf_create_state(struct pf_rule *, struct pf_rule *,
234 struct pf_rule *, struct pf_pdesc *,
235 struct pf_src_node *, struct pf_state_key *,
236 struct pf_state_key *, struct mbuf *, int,
237 u_int16_t, u_int16_t, int *, struct pfi_kif *,
238 struct pf_state **, int, u_int16_t, u_int16_t,
240 static int pf_test_fragment(struct pf_rule **, int,
241 struct pfi_kif *, struct mbuf *, void *,
242 struct pf_pdesc *, struct pf_rule **,
243 struct pf_ruleset **);
244 static int pf_tcp_track_full(struct pf_state_peer *,
245 struct pf_state_peer *, struct pf_state **,
246 struct pfi_kif *, struct mbuf *, int,
247 struct pf_pdesc *, u_short *, int *);
248 static int pf_tcp_track_sloppy(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pf_pdesc *, u_short *);
251 static int pf_test_state_tcp(struct pf_state **, int,
252 struct pfi_kif *, struct mbuf *, int,
253 void *, struct pf_pdesc *, u_short *);
254 static int pf_test_state_udp(struct pf_state **, int,
255 struct pfi_kif *, struct mbuf *, int,
256 void *, struct pf_pdesc *);
257 static int pf_test_state_icmp(struct pf_state **, int,
258 struct pfi_kif *, struct mbuf *, int,
259 void *, struct pf_pdesc *, u_short *);
260 static int pf_test_state_other(struct pf_state **, int,
261 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
262 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
264 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
266 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
268 static int pf_check_proto_cksum(struct mbuf *, int, int,
269 u_int8_t, sa_family_t);
270 static void pf_print_state_parts(struct pf_state *,
271 struct pf_state_key *, struct pf_state_key *);
272 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
273 struct pf_addr_wrap *);
274 static struct pf_state *pf_find_state(struct pfi_kif *,
275 struct pf_state_key_cmp *, u_int);
276 static int pf_src_connlimit(struct pf_state **);
277 static void pf_overload_task(void *v, int pending);
278 static int pf_insert_src_node(struct pf_src_node **,
279 struct pf_rule *, struct pf_addr *, sa_family_t);
280 static u_int pf_purge_expired_states(u_int, int);
281 static void pf_purge_unlinked_rules(void);
282 static int pf_mtag_uminit(void *, int, int);
283 static void pf_mtag_free(struct m_tag *);
285 static void pf_route(struct mbuf **, struct pf_rule *, int,
286 struct ifnet *, struct pf_state *,
290 static void pf_change_a6(struct pf_addr *, u_int16_t *,
291 struct pf_addr *, u_int8_t);
292 static void pf_route6(struct mbuf **, struct pf_rule *, int,
293 struct ifnet *, struct pf_state *,
297 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
299 VNET_DECLARE(int, pf_end_threads);
301 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
303 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
304 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
306 #define STATE_LOOKUP(i, k, d, s, pd) \
308 (s) = pf_find_state((i), (k), (d)); \
311 if (PACKET_LOOPED(pd)) \
313 if ((d) == PF_OUT && \
314 (((s)->rule.ptr->rt == PF_ROUTETO && \
315 (s)->rule.ptr->direction == PF_OUT) || \
316 ((s)->rule.ptr->rt == PF_REPLYTO && \
317 (s)->rule.ptr->direction == PF_IN)) && \
318 (s)->rt_kif != NULL && \
319 (s)->rt_kif != (i)) \
323 #define BOUND_IFACE(r, k) \
324 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
326 #define STATE_INC_COUNTERS(s) \
328 counter_u64_add(s->rule.ptr->states_cur, 1); \
329 counter_u64_add(s->rule.ptr->states_tot, 1); \
330 if (s->anchor.ptr != NULL) { \
331 counter_u64_add(s->anchor.ptr->states_cur, 1); \
332 counter_u64_add(s->anchor.ptr->states_tot, 1); \
334 if (s->nat_rule.ptr != NULL) { \
335 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
336 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
340 #define STATE_DEC_COUNTERS(s) \
342 if (s->nat_rule.ptr != NULL) \
343 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
344 if (s->anchor.ptr != NULL) \
345 counter_u64_add(s->anchor.ptr->states_cur, -1); \
346 counter_u64_add(s->rule.ptr->states_cur, -1); \
349 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
350 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
351 VNET_DEFINE(struct pf_idhash *, pf_idhash);
352 VNET_DEFINE(struct pf_srchash *, pf_srchash);
354 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
357 u_long pf_srchashmask;
358 static u_long pf_hashsize;
359 static u_long pf_srchashsize;
361 SYSCTL_ULONG(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
362 &pf_hashsize, 0, "Size of pf(4) states hashtable");
363 SYSCTL_ULONG(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
364 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
366 VNET_DEFINE(void *, pf_swi_cookie);
368 VNET_DEFINE(uint32_t, pf_hashseed);
369 #define V_pf_hashseed VNET(pf_hashseed)
371 static __inline uint32_t
372 pf_hashkey(struct pf_state_key *sk)
376 h = jenkins_hash32((uint32_t *)sk,
377 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
380 return (h & pf_hashmask);
383 static __inline uint32_t
384 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
390 h = jenkins_hash32((uint32_t *)&addr->v4,
391 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
394 h = jenkins_hash32((uint32_t *)&addr->v6,
395 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
398 panic("%s: unknown address family %u", __func__, af);
401 return (h & pf_srchashmask);
406 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
411 dst->addr32[0] = src->addr32[0];
415 dst->addr32[0] = src->addr32[0];
416 dst->addr32[1] = src->addr32[1];
417 dst->addr32[2] = src->addr32[2];
418 dst->addr32[3] = src->addr32[3];
425 pf_init_threshold(struct pf_threshold *threshold,
426 u_int32_t limit, u_int32_t seconds)
428 threshold->limit = limit * PF_THRESHOLD_MULT;
429 threshold->seconds = seconds;
430 threshold->count = 0;
431 threshold->last = time_uptime;
435 pf_add_threshold(struct pf_threshold *threshold)
437 u_int32_t t = time_uptime, diff = t - threshold->last;
439 if (diff >= threshold->seconds)
440 threshold->count = 0;
442 threshold->count -= threshold->count * diff /
444 threshold->count += PF_THRESHOLD_MULT;
449 pf_check_threshold(struct pf_threshold *threshold)
451 return (threshold->count > threshold->limit);
455 pf_src_connlimit(struct pf_state **state)
457 struct pf_overload_entry *pfoe;
460 PF_STATE_LOCK_ASSERT(*state);
462 (*state)->src_node->conn++;
463 (*state)->src.tcp_est = 1;
464 pf_add_threshold(&(*state)->src_node->conn_rate);
466 if ((*state)->rule.ptr->max_src_conn &&
467 (*state)->rule.ptr->max_src_conn <
468 (*state)->src_node->conn) {
469 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONN], 1);
473 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
474 pf_check_threshold(&(*state)->src_node->conn_rate)) {
475 counter_u64_add(V_pf_status.lcounters[LCNT_SRCCONNRATE], 1);
482 /* Kill this state. */
483 (*state)->timeout = PFTM_PURGE;
484 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
486 if ((*state)->rule.ptr->overload_tbl == NULL)
489 /* Schedule overloading and flushing task. */
490 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
492 return (1); /* too bad :( */
494 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
495 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
496 pfoe->rule = (*state)->rule.ptr;
497 pfoe->dir = (*state)->direction;
499 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
500 PF_OVERLOADQ_UNLOCK();
501 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
507 pf_overload_task(void *v, int pending)
509 struct pf_overload_head queue;
511 struct pf_overload_entry *pfoe, *pfoe1;
514 CURVNET_SET((struct vnet *)v);
517 queue = V_pf_overloadqueue;
518 SLIST_INIT(&V_pf_overloadqueue);
519 PF_OVERLOADQ_UNLOCK();
521 bzero(&p, sizeof(p));
522 SLIST_FOREACH(pfoe, &queue, next) {
523 counter_u64_add(V_pf_status.lcounters[LCNT_OVERLOAD_TABLE], 1);
524 if (V_pf_status.debug >= PF_DEBUG_MISC) {
525 printf("%s: blocking address ", __func__);
526 pf_print_host(&pfoe->addr, 0, pfoe->af);
530 p.pfra_af = pfoe->af;
535 p.pfra_ip4addr = pfoe->addr.v4;
541 p.pfra_ip6addr = pfoe->addr.v6;
547 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
552 * Remove those entries, that don't need flushing.
554 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
555 if (pfoe->rule->flush == 0) {
556 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
557 free(pfoe, M_PFTEMP);
560 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH], 1);
562 /* If nothing to flush, return. */
563 if (SLIST_EMPTY(&queue)) {
568 for (int i = 0; i <= pf_hashmask; i++) {
569 struct pf_idhash *ih = &V_pf_idhash[i];
570 struct pf_state_key *sk;
574 LIST_FOREACH(s, &ih->states, entry) {
575 sk = s->key[PF_SK_WIRE];
576 SLIST_FOREACH(pfoe, &queue, next)
577 if (sk->af == pfoe->af &&
578 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
579 pfoe->rule == s->rule.ptr) &&
580 ((pfoe->dir == PF_OUT &&
581 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
582 (pfoe->dir == PF_IN &&
583 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
584 s->timeout = PFTM_PURGE;
585 s->src.state = s->dst.state = TCPS_CLOSED;
589 PF_HASHROW_UNLOCK(ih);
591 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
592 free(pfoe, M_PFTEMP);
593 if (V_pf_status.debug >= PF_DEBUG_MISC)
594 printf("%s: %u states killed", __func__, killed);
600 * Can return locked on failure, so that we can consistently
601 * allocate and insert a new one.
604 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
607 struct pf_srchash *sh;
608 struct pf_src_node *n;
610 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_SEARCH], 1);
612 sh = &V_pf_srchash[pf_hashsrc(src, af)];
614 LIST_FOREACH(n, &sh->nodes, entry)
615 if (n->rule.ptr == rule && n->af == af &&
616 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
617 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
619 if (n != NULL || returnlocked == 0)
620 PF_HASHROW_UNLOCK(sh);
626 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
627 struct pf_addr *src, sa_family_t af)
630 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
631 rule->rpool.opts & PF_POOL_STICKYADDR),
632 ("%s for non-tracking rule %p", __func__, rule));
635 *sn = pf_find_src_node(src, rule, af, 1);
638 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
640 PF_HASHROW_ASSERT(sh);
642 if (!rule->max_src_nodes ||
643 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
644 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
646 counter_u64_add(V_pf_status.lcounters[LCNT_SRCNODES],
649 PF_HASHROW_UNLOCK(sh);
653 pf_init_threshold(&(*sn)->conn_rate,
654 rule->max_src_conn_rate.limit,
655 rule->max_src_conn_rate.seconds);
658 (*sn)->rule.ptr = rule;
659 PF_ACPY(&(*sn)->addr, src, af);
660 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
661 (*sn)->creation = time_uptime;
662 (*sn)->ruletype = rule->action;
663 if ((*sn)->rule.ptr != NULL)
664 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
665 PF_HASHROW_UNLOCK(sh);
666 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_INSERT], 1);
668 if (rule->max_src_states &&
669 (*sn)->states >= rule->max_src_states) {
670 counter_u64_add(V_pf_status.lcounters[LCNT_SRCSTATES],
679 pf_unlink_src_node_locked(struct pf_src_node *src)
682 struct pf_srchash *sh;
684 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
685 PF_HASHROW_ASSERT(sh);
687 LIST_REMOVE(src, entry);
689 counter_u64_add(src->rule.ptr->src_nodes, -1);
690 counter_u64_add(V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS], 1);
694 pf_unlink_src_node(struct pf_src_node *src)
696 struct pf_srchash *sh;
698 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
700 pf_unlink_src_node_locked(src);
701 PF_HASHROW_UNLOCK(sh);
705 pf_free_src_node(struct pf_src_node *sn)
708 KASSERT(sn->states == 0, ("%s: %p has refs", __func__, sn));
709 uma_zfree(V_pf_sources_z, sn);
713 pf_free_src_nodes(struct pf_src_node_list *head)
715 struct pf_src_node *sn, *tmp;
718 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
719 pf_free_src_node(sn);
730 pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
731 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_uminit, NULL,
735 /* Per-vnet data storage structures initialization. */
739 struct pf_keyhash *kh;
740 struct pf_idhash *ih;
741 struct pf_srchash *sh;
744 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &pf_hashsize);
745 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
746 pf_hashsize = PF_HASHSIZ;
747 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &pf_srchashsize);
748 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
749 pf_srchashsize = PF_HASHSIZ / 4;
751 V_pf_hashseed = arc4random();
753 /* States and state keys storage. */
754 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
755 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
756 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
757 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
758 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
760 V_pf_state_key_z = uma_zcreate("pf state keys",
761 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
763 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
764 M_PFHASH, M_WAITOK | M_ZERO);
765 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
766 M_PFHASH, M_WAITOK | M_ZERO);
767 pf_hashmask = pf_hashsize - 1;
768 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
770 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
771 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
775 V_pf_sources_z = uma_zcreate("pf source nodes",
776 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
778 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
779 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
780 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
781 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
782 M_PFHASH, M_WAITOK|M_ZERO);
783 pf_srchashmask = pf_srchashsize - 1;
784 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
785 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
788 TAILQ_INIT(&V_pf_altqs[0]);
789 TAILQ_INIT(&V_pf_altqs[1]);
790 TAILQ_INIT(&V_pf_pabuf);
791 V_pf_altqs_active = &V_pf_altqs[0];
792 V_pf_altqs_inactive = &V_pf_altqs[1];
795 /* Send & overload+flush queues. */
796 STAILQ_INIT(&V_pf_sendqueue);
797 SLIST_INIT(&V_pf_overloadqueue);
798 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
799 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
800 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
803 /* Unlinked, but may be referenced rules. */
804 TAILQ_INIT(&V_pf_unlinked_rules);
805 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
812 uma_zdestroy(pf_mtag_z);
818 struct pf_keyhash *kh;
819 struct pf_idhash *ih;
820 struct pf_srchash *sh;
821 struct pf_send_entry *pfse, *next;
824 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
826 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
828 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
830 mtx_destroy(&kh->lock);
831 mtx_destroy(&ih->lock);
833 free(V_pf_keyhash, M_PFHASH);
834 free(V_pf_idhash, M_PFHASH);
836 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
837 KASSERT(LIST_EMPTY(&sh->nodes),
838 ("%s: source node hash not empty", __func__));
839 mtx_destroy(&sh->lock);
841 free(V_pf_srchash, M_PFHASH);
843 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
844 m_freem(pfse->pfse_m);
845 free(pfse, M_PFTEMP);
848 mtx_destroy(&pf_sendqueue_mtx);
849 mtx_destroy(&pf_overloadqueue_mtx);
850 mtx_destroy(&pf_unlnkdrules_mtx);
852 uma_zdestroy(V_pf_sources_z);
853 uma_zdestroy(V_pf_state_z);
854 uma_zdestroy(V_pf_state_key_z);
858 pf_mtag_uminit(void *mem, int size, int how)
862 t = (struct m_tag *)mem;
863 t->m_tag_cookie = MTAG_ABI_COMPAT;
864 t->m_tag_id = PACKET_TAG_PF;
865 t->m_tag_len = sizeof(struct pf_mtag);
866 t->m_tag_free = pf_mtag_free;
872 pf_mtag_free(struct m_tag *t)
875 uma_zfree(pf_mtag_z, t);
879 pf_get_mtag(struct mbuf *m)
883 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
884 return ((struct pf_mtag *)(mtag + 1));
886 mtag = uma_zalloc(pf_mtag_z, M_NOWAIT);
889 bzero(mtag + 1, sizeof(struct pf_mtag));
890 m_tag_prepend(m, mtag);
892 return ((struct pf_mtag *)(mtag + 1));
896 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
899 struct pf_keyhash *khs, *khw, *kh;
900 struct pf_state_key *sk, *cur;
901 struct pf_state *si, *olds = NULL;
904 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
905 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
906 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
909 * We need to lock hash slots of both keys. To avoid deadlock
910 * we always lock the slot with lower address first. Unlock order
913 * We also need to lock ID hash slot before dropping key
914 * locks. On success we return with ID hash slot locked.
918 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
919 PF_HASHROW_LOCK(khs);
921 khs = &V_pf_keyhash[pf_hashkey(sks)];
922 khw = &V_pf_keyhash[pf_hashkey(skw)];
924 PF_HASHROW_LOCK(khs);
925 } else if (khs < khw) {
926 PF_HASHROW_LOCK(khs);
927 PF_HASHROW_LOCK(khw);
929 PF_HASHROW_LOCK(khw);
930 PF_HASHROW_LOCK(khs);
934 #define KEYS_UNLOCK() do { \
936 PF_HASHROW_UNLOCK(khs); \
937 PF_HASHROW_UNLOCK(khw); \
939 PF_HASHROW_UNLOCK(khs); \
943 * First run: start with wire key.
950 LIST_FOREACH(cur, &kh->keys, entry)
951 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
955 /* Key exists. Check for same kif, if none, add to key. */
956 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
957 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
960 if (si->kif == s->kif &&
961 si->direction == s->direction) {
962 if (sk->proto == IPPROTO_TCP &&
963 si->src.state >= TCPS_FIN_WAIT_2 &&
964 si->dst.state >= TCPS_FIN_WAIT_2) {
966 * New state matches an old >FIN_WAIT_2
967 * state. We can't drop key hash locks,
968 * thus we can't unlink it properly.
970 * As a workaround we drop it into
971 * TCPS_CLOSED state, schedule purge
972 * ASAP and push it into the very end
973 * of the slot TAILQ, so that it won't
974 * conflict with our new state.
976 si->src.state = si->dst.state =
978 si->timeout = PFTM_PURGE;
981 if (V_pf_status.debug >= PF_DEBUG_MISC) {
982 printf("pf: %s key attach "
984 (idx == PF_SK_WIRE) ?
987 pf_print_state_parts(s,
988 (idx == PF_SK_WIRE) ?
990 (idx == PF_SK_STACK) ?
992 printf(", existing: ");
993 pf_print_state_parts(si,
994 (idx == PF_SK_WIRE) ?
996 (idx == PF_SK_STACK) ?
1000 PF_HASHROW_UNLOCK(ih);
1002 uma_zfree(V_pf_state_key_z, sk);
1003 if (idx == PF_SK_STACK)
1005 return (EEXIST); /* collision! */
1008 PF_HASHROW_UNLOCK(ih);
1010 uma_zfree(V_pf_state_key_z, sk);
1013 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1018 /* List is sorted, if-bound states before floating. */
1019 if (s->kif == V_pfi_all)
1020 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1022 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1025 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1026 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1032 * Attach done. See how should we (or should not?)
1033 * attach a second key.
1036 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1040 } else if (sks != NULL) {
1042 * Continue attaching with stack key.
1054 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1055 ("%s failure", __func__));
1062 pf_detach_state(struct pf_state *s)
1064 struct pf_state_key *sks = s->key[PF_SK_STACK];
1065 struct pf_keyhash *kh;
1068 kh = &V_pf_keyhash[pf_hashkey(sks)];
1069 PF_HASHROW_LOCK(kh);
1070 if (s->key[PF_SK_STACK] != NULL)
1071 pf_state_key_detach(s, PF_SK_STACK);
1073 * If both point to same key, then we are done.
1075 if (sks == s->key[PF_SK_WIRE]) {
1076 pf_state_key_detach(s, PF_SK_WIRE);
1077 PF_HASHROW_UNLOCK(kh);
1080 PF_HASHROW_UNLOCK(kh);
1083 if (s->key[PF_SK_WIRE] != NULL) {
1084 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1085 PF_HASHROW_LOCK(kh);
1086 if (s->key[PF_SK_WIRE] != NULL)
1087 pf_state_key_detach(s, PF_SK_WIRE);
1088 PF_HASHROW_UNLOCK(kh);
1093 pf_state_key_detach(struct pf_state *s, int idx)
1095 struct pf_state_key *sk = s->key[idx];
1097 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1099 PF_HASHROW_ASSERT(kh);
1101 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1104 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1105 LIST_REMOVE(sk, entry);
1106 uma_zfree(V_pf_state_key_z, sk);
1111 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1113 struct pf_state_key *sk = mem;
1115 bzero(sk, sizeof(struct pf_state_key_cmp));
1116 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1117 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1122 struct pf_state_key *
1123 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1124 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1126 struct pf_state_key *sk;
1128 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1132 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1133 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1134 sk->port[pd->sidx] = sport;
1135 sk->port[pd->didx] = dport;
1136 sk->proto = pd->proto;
1142 struct pf_state_key *
1143 pf_state_key_clone(struct pf_state_key *orig)
1145 struct pf_state_key *sk;
1147 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1151 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1157 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1158 struct pf_state_key *sks, struct pf_state *s)
1160 struct pf_idhash *ih;
1161 struct pf_state *cur;
1164 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1165 ("%s: sks not pristine", __func__));
1166 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1167 ("%s: skw not pristine", __func__));
1168 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1172 if (s->id == 0 && s->creatorid == 0) {
1173 /* XXX: should be atomic, but probability of collision low */
1174 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1175 V_pf_stateid[curcpu] = 1;
1176 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1177 s->id = htobe64(s->id);
1178 s->creatorid = V_pf_status.hostid;
1181 /* Returns with ID locked on success. */
1182 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1185 ih = &V_pf_idhash[PF_IDHASH(s)];
1186 PF_HASHROW_ASSERT(ih);
1187 LIST_FOREACH(cur, &ih->states, entry)
1188 if (cur->id == s->id && cur->creatorid == s->creatorid)
1192 PF_HASHROW_UNLOCK(ih);
1193 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1194 printf("pf: state ID collision: "
1195 "id: %016llx creatorid: %08x\n",
1196 (unsigned long long)be64toh(s->id),
1197 ntohl(s->creatorid));
1202 LIST_INSERT_HEAD(&ih->states, s, entry);
1203 /* One for keys, one for ID hash. */
1204 refcount_init(&s->refs, 2);
1206 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_INSERT], 1);
1207 if (pfsync_insert_state_ptr != NULL)
1208 pfsync_insert_state_ptr(s);
1210 /* Returns locked. */
1215 * Find state by ID: returns with locked row on success.
1218 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1220 struct pf_idhash *ih;
1223 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1225 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1227 PF_HASHROW_LOCK(ih);
1228 LIST_FOREACH(s, &ih->states, entry)
1229 if (s->id == id && s->creatorid == creatorid)
1233 PF_HASHROW_UNLOCK(ih);
1239 * Find state by key.
1240 * Returns with ID hash slot locked on success.
1242 static struct pf_state *
1243 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1245 struct pf_keyhash *kh;
1246 struct pf_state_key *sk;
1250 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1252 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1254 PF_HASHROW_LOCK(kh);
1255 LIST_FOREACH(sk, &kh->keys, entry)
1256 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1259 PF_HASHROW_UNLOCK(kh);
1263 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1265 /* List is sorted, if-bound states before floating ones. */
1266 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1267 if (s->kif == V_pfi_all || s->kif == kif) {
1269 PF_HASHROW_UNLOCK(kh);
1270 if (s->timeout >= PFTM_MAX) {
1272 * State is either being processed by
1273 * pf_unlink_state() in an other thread, or
1274 * is scheduled for immediate expiry.
1281 PF_HASHROW_UNLOCK(kh);
1287 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1289 struct pf_keyhash *kh;
1290 struct pf_state_key *sk;
1291 struct pf_state *s, *ret = NULL;
1294 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_SEARCH], 1);
1296 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1298 PF_HASHROW_LOCK(kh);
1299 LIST_FOREACH(sk, &kh->keys, entry)
1300 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1303 PF_HASHROW_UNLOCK(kh);
1318 panic("%s: dir %u", __func__, dir);
1321 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1323 PF_HASHROW_UNLOCK(kh);
1337 PF_HASHROW_UNLOCK(kh);
1342 /* END state table stuff */
1345 pf_send(struct pf_send_entry *pfse)
1349 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1351 swi_sched(V_pf_swi_cookie, 0);
1357 struct pf_send_head queue;
1358 struct pf_send_entry *pfse, *next;
1360 CURVNET_SET((struct vnet *)v);
1363 queue = V_pf_sendqueue;
1364 STAILQ_INIT(&V_pf_sendqueue);
1367 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1368 switch (pfse->pfse_type) {
1371 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1374 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1375 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1380 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1384 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1385 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1389 panic("%s: unknown type", __func__);
1391 free(pfse, M_PFTEMP);
1397 pf_purge_thread(void *v)
1401 CURVNET_SET((struct vnet *)v);
1405 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1407 if (V_pf_end_threads) {
1409 * To cleanse up all kifs and rules we need
1410 * two runs: first one clears reference flags,
1411 * then pf_purge_expired_states() doesn't
1412 * raise them, and then second run frees.
1415 pf_purge_unlinked_rules();
1419 * Now purge everything.
1421 pf_purge_expired_states(0, pf_hashmask);
1422 pf_purge_expired_fragments();
1423 pf_purge_expired_src_nodes();
1426 * Now all kifs & rules should be unreferenced,
1427 * thus should be successfully freed.
1429 pf_purge_unlinked_rules();
1433 * Announce success and exit.
1438 wakeup(pf_purge_thread);
1443 /* Process 1/interval fraction of the state table every run. */
1444 idx = pf_purge_expired_states(idx, pf_hashmask /
1445 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1447 /* Purge other expired types every PFTM_INTERVAL seconds. */
1450 * Order is important:
1451 * - states and src nodes reference rules
1452 * - states and rules reference kifs
1454 pf_purge_expired_fragments();
1455 pf_purge_expired_src_nodes();
1456 pf_purge_unlinked_rules();
1465 pf_state_expires(const struct pf_state *state)
1472 /* handle all PFTM_* > PFTM_MAX here */
1473 if (state->timeout == PFTM_PURGE)
1474 return (time_uptime);
1475 KASSERT(state->timeout != PFTM_UNLINKED,
1476 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1477 KASSERT((state->timeout < PFTM_MAX),
1478 ("pf_state_expires: timeout > PFTM_MAX"));
1479 timeout = state->rule.ptr->timeout[state->timeout];
1481 timeout = V_pf_default_rule.timeout[state->timeout];
1482 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1484 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1485 states = counter_u64_fetch(state->rule.ptr->states_cur);
1487 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1488 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1489 states = V_pf_status.states;
1491 if (end && states > start && start < end) {
1493 return (state->expire + timeout * (end - states) /
1496 return (time_uptime);
1498 return (state->expire + timeout);
1502 pf_purge_expired_src_nodes()
1504 struct pf_src_node_list freelist;
1505 struct pf_srchash *sh;
1506 struct pf_src_node *cur, *next;
1509 LIST_INIT(&freelist);
1510 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1511 PF_HASHROW_LOCK(sh);
1512 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1513 if (cur->states == 0 && cur->expire <= time_uptime) {
1514 pf_unlink_src_node_locked(cur);
1515 LIST_INSERT_HEAD(&freelist, cur, entry);
1516 } else if (cur->rule.ptr != NULL)
1517 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1518 PF_HASHROW_UNLOCK(sh);
1521 pf_free_src_nodes(&freelist);
1523 V_pf_status.src_nodes = uma_zone_get_cur(V_pf_sources_z);
1527 pf_src_tree_remove_state(struct pf_state *s)
1531 if (s->src_node != NULL) {
1533 --s->src_node->conn;
1534 if (--s->src_node->states == 0) {
1535 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1538 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1539 s->src_node->expire = time_uptime + timeout;
1542 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1543 if (--s->nat_src_node->states == 0) {
1544 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1547 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1548 s->nat_src_node->expire = time_uptime + timeout;
1551 s->src_node = s->nat_src_node = NULL;
1555 * Unlink and potentilly free a state. Function may be
1556 * called with ID hash row locked, but always returns
1557 * unlocked, since it needs to go through key hash locking.
1560 pf_unlink_state(struct pf_state *s, u_int flags)
1562 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1564 if ((flags & PF_ENTER_LOCKED) == 0)
1565 PF_HASHROW_LOCK(ih);
1567 PF_HASHROW_ASSERT(ih);
1569 if (s->timeout == PFTM_UNLINKED) {
1571 * State is being processed
1572 * by pf_unlink_state() in
1575 PF_HASHROW_UNLOCK(ih);
1576 return (0); /* XXXGL: undefined actually */
1579 if (s->src.state == PF_TCPS_PROXY_DST) {
1580 /* XXX wire key the right one? */
1581 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1582 &s->key[PF_SK_WIRE]->addr[1],
1583 &s->key[PF_SK_WIRE]->addr[0],
1584 s->key[PF_SK_WIRE]->port[1],
1585 s->key[PF_SK_WIRE]->port[0],
1586 s->src.seqhi, s->src.seqlo + 1,
1587 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1590 LIST_REMOVE(s, entry);
1591 pf_src_tree_remove_state(s);
1593 if (pfsync_delete_state_ptr != NULL)
1594 pfsync_delete_state_ptr(s);
1596 STATE_DEC_COUNTERS(s);
1598 s->timeout = PFTM_UNLINKED;
1600 PF_HASHROW_UNLOCK(ih);
1603 refcount_release(&s->refs);
1605 return (pf_release_state(s));
1609 pf_free_state(struct pf_state *cur)
1612 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1613 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1616 pf_normalize_tcp_cleanup(cur);
1617 uma_zfree(V_pf_state_z, cur);
1618 counter_u64_add(V_pf_status.fcounters[FCNT_STATE_REMOVALS], 1);
1622 * Called only from pf_purge_thread(), thus serialized.
1625 pf_purge_expired_states(u_int i, int maxcheck)
1627 struct pf_idhash *ih;
1630 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1633 * Go through hash and unlink states that expire now.
1635 while (maxcheck > 0) {
1637 ih = &V_pf_idhash[i];
1639 PF_HASHROW_LOCK(ih);
1640 LIST_FOREACH(s, &ih->states, entry) {
1641 if (pf_state_expires(s) <= time_uptime) {
1642 V_pf_status.states -=
1643 pf_unlink_state(s, PF_ENTER_LOCKED);
1646 s->rule.ptr->rule_flag |= PFRULE_REFS;
1647 if (s->nat_rule.ptr != NULL)
1648 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1649 if (s->anchor.ptr != NULL)
1650 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1651 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1653 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1655 PF_HASHROW_UNLOCK(ih);
1657 /* Return when we hit end of hash. */
1658 if (++i > pf_hashmask) {
1659 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1666 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1672 pf_purge_unlinked_rules()
1674 struct pf_rulequeue tmpq;
1675 struct pf_rule *r, *r1;
1678 * If we have overloading task pending, then we'd
1679 * better skip purging this time. There is a tiny
1680 * probability that overloading task references
1681 * an already unlinked rule.
1683 PF_OVERLOADQ_LOCK();
1684 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1685 PF_OVERLOADQ_UNLOCK();
1688 PF_OVERLOADQ_UNLOCK();
1691 * Do naive mark-and-sweep garbage collecting of old rules.
1692 * Reference flag is raised by pf_purge_expired_states()
1693 * and pf_purge_expired_src_nodes().
1695 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1696 * use a temporary queue.
1699 PF_UNLNKDRULES_LOCK();
1700 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1701 if (!(r->rule_flag & PFRULE_REFS)) {
1702 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1703 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1705 r->rule_flag &= ~PFRULE_REFS;
1707 PF_UNLNKDRULES_UNLOCK();
1709 if (!TAILQ_EMPTY(&tmpq)) {
1711 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1712 TAILQ_REMOVE(&tmpq, r, entries);
1720 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1725 u_int32_t a = ntohl(addr->addr32[0]);
1726 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1738 u_int8_t i, curstart, curend, maxstart, maxend;
1739 curstart = curend = maxstart = maxend = 255;
1740 for (i = 0; i < 8; i++) {
1741 if (!addr->addr16[i]) {
1742 if (curstart == 255)
1746 if ((curend - curstart) >
1747 (maxend - maxstart)) {
1748 maxstart = curstart;
1751 curstart = curend = 255;
1754 if ((curend - curstart) >
1755 (maxend - maxstart)) {
1756 maxstart = curstart;
1759 for (i = 0; i < 8; i++) {
1760 if (i >= maxstart && i <= maxend) {
1766 b = ntohs(addr->addr16[i]);
1783 pf_print_state(struct pf_state *s)
1785 pf_print_state_parts(s, NULL, NULL);
1789 pf_print_state_parts(struct pf_state *s,
1790 struct pf_state_key *skwp, struct pf_state_key *sksp)
1792 struct pf_state_key *skw, *sks;
1793 u_int8_t proto, dir;
1795 /* Do our best to fill these, but they're skipped if NULL */
1796 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1797 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1798 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1799 dir = s ? s->direction : 0;
1817 case IPPROTO_ICMPV6:
1821 printf("%u", skw->proto);
1834 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1836 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1841 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1843 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1848 if (proto == IPPROTO_TCP) {
1849 printf(" [lo=%u high=%u win=%u modulator=%u",
1850 s->src.seqlo, s->src.seqhi,
1851 s->src.max_win, s->src.seqdiff);
1852 if (s->src.wscale && s->dst.wscale)
1853 printf(" wscale=%u",
1854 s->src.wscale & PF_WSCALE_MASK);
1856 printf(" [lo=%u high=%u win=%u modulator=%u",
1857 s->dst.seqlo, s->dst.seqhi,
1858 s->dst.max_win, s->dst.seqdiff);
1859 if (s->src.wscale && s->dst.wscale)
1860 printf(" wscale=%u",
1861 s->dst.wscale & PF_WSCALE_MASK);
1864 printf(" %u:%u", s->src.state, s->dst.state);
1869 pf_print_flags(u_int8_t f)
1891 #define PF_SET_SKIP_STEPS(i) \
1893 while (head[i] != cur) { \
1894 head[i]->skip[i].ptr = cur; \
1895 head[i] = TAILQ_NEXT(head[i], entries); \
1900 pf_calc_skip_steps(struct pf_rulequeue *rules)
1902 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1905 cur = TAILQ_FIRST(rules);
1907 for (i = 0; i < PF_SKIP_COUNT; ++i)
1909 while (cur != NULL) {
1911 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1912 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1913 if (cur->direction != prev->direction)
1914 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1915 if (cur->af != prev->af)
1916 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1917 if (cur->proto != prev->proto)
1918 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1919 if (cur->src.neg != prev->src.neg ||
1920 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1921 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1922 if (cur->src.port[0] != prev->src.port[0] ||
1923 cur->src.port[1] != prev->src.port[1] ||
1924 cur->src.port_op != prev->src.port_op)
1925 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1926 if (cur->dst.neg != prev->dst.neg ||
1927 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1928 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1929 if (cur->dst.port[0] != prev->dst.port[0] ||
1930 cur->dst.port[1] != prev->dst.port[1] ||
1931 cur->dst.port_op != prev->dst.port_op)
1932 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1935 cur = TAILQ_NEXT(cur, entries);
1937 for (i = 0; i < PF_SKIP_COUNT; ++i)
1938 PF_SET_SKIP_STEPS(i);
1942 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1944 if (aw1->type != aw2->type)
1946 switch (aw1->type) {
1947 case PF_ADDR_ADDRMASK:
1949 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1951 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1954 case PF_ADDR_DYNIFTL:
1955 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1956 case PF_ADDR_NOROUTE:
1957 case PF_ADDR_URPFFAILED:
1960 return (aw1->p.tbl != aw2->p.tbl);
1962 printf("invalid address type: %d\n", aw1->type);
1968 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1974 l = cksum + old - new;
1975 l = (l >> 16) + (l & 65535);
1983 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1984 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1989 PF_ACPY(&ao, a, af);
1997 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1998 ao.addr16[0], an->addr16[0], 0),
1999 ao.addr16[1], an->addr16[1], 0);
2001 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2002 ao.addr16[0], an->addr16[0], u),
2003 ao.addr16[1], an->addr16[1], u),
2009 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2010 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2011 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2012 ao.addr16[0], an->addr16[0], u),
2013 ao.addr16[1], an->addr16[1], u),
2014 ao.addr16[2], an->addr16[2], u),
2015 ao.addr16[3], an->addr16[3], u),
2016 ao.addr16[4], an->addr16[4], u),
2017 ao.addr16[5], an->addr16[5], u),
2018 ao.addr16[6], an->addr16[6], u),
2019 ao.addr16[7], an->addr16[7], u),
2027 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2029 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2033 memcpy(&ao, a, sizeof(ao));
2034 memcpy(a, &an, sizeof(u_int32_t));
2035 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2036 ao % 65536, an % 65536, u);
2041 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2045 PF_ACPY(&ao, a, AF_INET6);
2046 PF_ACPY(a, an, AF_INET6);
2048 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2049 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2050 pf_cksum_fixup(pf_cksum_fixup(*c,
2051 ao.addr16[0], an->addr16[0], u),
2052 ao.addr16[1], an->addr16[1], u),
2053 ao.addr16[2], an->addr16[2], u),
2054 ao.addr16[3], an->addr16[3], u),
2055 ao.addr16[4], an->addr16[4], u),
2056 ao.addr16[5], an->addr16[5], u),
2057 ao.addr16[6], an->addr16[6], u),
2058 ao.addr16[7], an->addr16[7], u);
2063 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2064 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2065 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2067 struct pf_addr oia, ooa;
2069 PF_ACPY(&oia, ia, af);
2071 PF_ACPY(&ooa, oa, af);
2073 /* Change inner protocol port, fix inner protocol checksum. */
2075 u_int16_t oip = *ip;
2082 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2083 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2085 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2087 /* Change inner ip address, fix inner ip and icmp checksums. */
2088 PF_ACPY(ia, na, af);
2092 u_int32_t oh2c = *h2c;
2094 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2095 oia.addr16[0], ia->addr16[0], 0),
2096 oia.addr16[1], ia->addr16[1], 0);
2097 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2098 oia.addr16[0], ia->addr16[0], 0),
2099 oia.addr16[1], ia->addr16[1], 0);
2100 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2106 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2107 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2108 pf_cksum_fixup(pf_cksum_fixup(*ic,
2109 oia.addr16[0], ia->addr16[0], u),
2110 oia.addr16[1], ia->addr16[1], u),
2111 oia.addr16[2], ia->addr16[2], u),
2112 oia.addr16[3], ia->addr16[3], u),
2113 oia.addr16[4], ia->addr16[4], u),
2114 oia.addr16[5], ia->addr16[5], u),
2115 oia.addr16[6], ia->addr16[6], u),
2116 oia.addr16[7], ia->addr16[7], u);
2120 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2122 PF_ACPY(oa, na, af);
2126 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2127 ooa.addr16[0], oa->addr16[0], 0),
2128 ooa.addr16[1], oa->addr16[1], 0);
2133 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2134 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2135 pf_cksum_fixup(pf_cksum_fixup(*ic,
2136 ooa.addr16[0], oa->addr16[0], u),
2137 ooa.addr16[1], oa->addr16[1], u),
2138 ooa.addr16[2], oa->addr16[2], u),
2139 ooa.addr16[3], oa->addr16[3], u),
2140 ooa.addr16[4], oa->addr16[4], u),
2141 ooa.addr16[5], oa->addr16[5], u),
2142 ooa.addr16[6], oa->addr16[6], u),
2143 ooa.addr16[7], oa->addr16[7], u);
2152 * Need to modulate the sequence numbers in the TCP SACK option
2153 * (credits to Krzysztof Pfaff for report and patch)
2156 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2157 struct tcphdr *th, struct pf_state_peer *dst)
2159 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2160 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2161 int copyback = 0, i, olen;
2162 struct sackblk sack;
2164 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2165 if (hlen < TCPOLEN_SACKLEN ||
2166 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2169 while (hlen >= TCPOLEN_SACKLEN) {
2172 case TCPOPT_EOL: /* FALLTHROUGH */
2180 if (olen >= TCPOLEN_SACKLEN) {
2181 for (i = 2; i + TCPOLEN_SACK <= olen;
2182 i += TCPOLEN_SACK) {
2183 memcpy(&sack, &opt[i], sizeof(sack));
2184 pf_change_a(&sack.start, &th->th_sum,
2185 htonl(ntohl(sack.start) -
2187 pf_change_a(&sack.end, &th->th_sum,
2188 htonl(ntohl(sack.end) -
2190 memcpy(&opt[i], &sack, sizeof(sack));
2204 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2209 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2210 const struct pf_addr *saddr, const struct pf_addr *daddr,
2211 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2212 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2213 u_int16_t rtag, struct ifnet *ifp)
2215 struct pf_send_entry *pfse;
2219 struct ip *h = NULL;
2222 struct ip6_hdr *h6 = NULL;
2226 struct pf_mtag *pf_mtag;
2231 /* maximum segment size tcp option */
2232 tlen = sizeof(struct tcphdr);
2239 len = sizeof(struct ip) + tlen;
2244 len = sizeof(struct ip6_hdr) + tlen;
2248 panic("%s: unsupported af %d", __func__, af);
2251 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2252 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2255 m = m_gethdr(M_NOWAIT, MT_DATA);
2257 free(pfse, M_PFTEMP);
2261 mac_netinet_firewall_send(m);
2263 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2264 free(pfse, M_PFTEMP);
2269 m->m_flags |= M_SKIP_FIREWALL;
2270 pf_mtag->tag = rtag;
2272 if (r != NULL && r->rtableid >= 0)
2273 M_SETFIB(m, r->rtableid);
2276 if (r != NULL && r->qid) {
2277 pf_mtag->qid = r->qid;
2279 /* add hints for ecn */
2280 pf_mtag->hdr = mtod(m, struct ip *);
2283 m->m_data += max_linkhdr;
2284 m->m_pkthdr.len = m->m_len = len;
2285 m->m_pkthdr.rcvif = NULL;
2286 bzero(m->m_data, len);
2290 h = mtod(m, struct ip *);
2292 /* IP header fields included in the TCP checksum */
2293 h->ip_p = IPPROTO_TCP;
2294 h->ip_len = htons(tlen);
2295 h->ip_src.s_addr = saddr->v4.s_addr;
2296 h->ip_dst.s_addr = daddr->v4.s_addr;
2298 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2303 h6 = mtod(m, struct ip6_hdr *);
2305 /* IP header fields included in the TCP checksum */
2306 h6->ip6_nxt = IPPROTO_TCP;
2307 h6->ip6_plen = htons(tlen);
2308 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2309 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2311 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2317 th->th_sport = sport;
2318 th->th_dport = dport;
2319 th->th_seq = htonl(seq);
2320 th->th_ack = htonl(ack);
2321 th->th_off = tlen >> 2;
2322 th->th_flags = flags;
2323 th->th_win = htons(win);
2326 opt = (char *)(th + 1);
2327 opt[0] = TCPOPT_MAXSEG;
2330 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2337 th->th_sum = in_cksum(m, len);
2339 /* Finish the IP header */
2341 h->ip_hl = sizeof(*h) >> 2;
2342 h->ip_tos = IPTOS_LOWDELAY;
2343 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2344 h->ip_len = htons(len);
2345 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2348 pfse->pfse_type = PFSE_IP;
2354 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2355 sizeof(struct ip6_hdr), tlen);
2357 h6->ip6_vfc |= IPV6_VERSION;
2358 h6->ip6_hlim = IPV6_DEFHLIM;
2360 pfse->pfse_type = PFSE_IP6;
2369 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2372 struct pf_send_entry *pfse;
2374 struct pf_mtag *pf_mtag;
2376 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2377 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2381 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2382 free(pfse, M_PFTEMP);
2386 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2387 free(pfse, M_PFTEMP);
2391 m0->m_flags |= M_SKIP_FIREWALL;
2393 if (r->rtableid >= 0)
2394 M_SETFIB(m0, r->rtableid);
2398 pf_mtag->qid = r->qid;
2399 /* add hints for ecn */
2400 pf_mtag->hdr = mtod(m0, struct ip *);
2407 pfse->pfse_type = PFSE_ICMP;
2412 pfse->pfse_type = PFSE_ICMP6;
2417 pfse->pfse_icmp_type = type;
2418 pfse->pfse_icmp_code = code;
2423 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2424 * If n is 0, they match if they are equal. If n is != 0, they match if they
2428 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2429 struct pf_addr *b, sa_family_t af)
2436 if ((a->addr32[0] & m->addr32[0]) ==
2437 (b->addr32[0] & m->addr32[0]))
2443 if (((a->addr32[0] & m->addr32[0]) ==
2444 (b->addr32[0] & m->addr32[0])) &&
2445 ((a->addr32[1] & m->addr32[1]) ==
2446 (b->addr32[1] & m->addr32[1])) &&
2447 ((a->addr32[2] & m->addr32[2]) ==
2448 (b->addr32[2] & m->addr32[2])) &&
2449 ((a->addr32[3] & m->addr32[3]) ==
2450 (b->addr32[3] & m->addr32[3])))
2469 * Return 1 if b <= a <= e, otherwise return 0.
2472 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2473 struct pf_addr *a, sa_family_t af)
2478 if ((a->addr32[0] < b->addr32[0]) ||
2479 (a->addr32[0] > e->addr32[0]))
2488 for (i = 0; i < 4; ++i)
2489 if (a->addr32[i] > b->addr32[i])
2491 else if (a->addr32[i] < b->addr32[i])
2494 for (i = 0; i < 4; ++i)
2495 if (a->addr32[i] < e->addr32[i])
2497 else if (a->addr32[i] > e->addr32[i])
2507 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2511 return ((p > a1) && (p < a2));
2513 return ((p < a1) || (p > a2));
2515 return ((p >= a1) && (p <= a2));
2529 return (0); /* never reached */
2533 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2538 return (pf_match(op, a1, a2, p));
2542 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2544 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2546 return (pf_match(op, a1, a2, u));
2550 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2552 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2554 return (pf_match(op, a1, a2, g));
2558 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2563 return ((!r->match_tag_not && r->match_tag == *tag) ||
2564 (r->match_tag_not && r->match_tag != *tag));
2568 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2571 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2573 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2576 pd->pf_mtag->tag = tag;
2581 #define PF_ANCHOR_STACKSIZE 32
2582 struct pf_anchor_stackframe {
2583 struct pf_ruleset *rs;
2584 struct pf_rule *r; /* XXX: + match bit */
2585 struct pf_anchor *child;
2589 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2591 #define PF_ANCHORSTACK_MATCH 0x00000001
2592 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2594 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2595 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2596 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2597 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2598 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2602 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2603 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2606 struct pf_anchor_stackframe *f;
2612 if (*depth >= PF_ANCHOR_STACKSIZE) {
2613 printf("%s: anchor stack overflow on %s\n",
2614 __func__, (*r)->anchor->name);
2615 *r = TAILQ_NEXT(*r, entries);
2617 } else if (*depth == 0 && a != NULL)
2619 f = stack + (*depth)++;
2622 if ((*r)->anchor_wildcard) {
2623 struct pf_anchor_node *parent = &(*r)->anchor->children;
2625 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2629 *rs = &f->child->ruleset;
2632 *rs = &(*r)->anchor->ruleset;
2634 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2638 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2639 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2642 struct pf_anchor_stackframe *f;
2651 f = stack + *depth - 1;
2652 fr = PF_ANCHOR_RULE(f);
2653 if (f->child != NULL) {
2654 struct pf_anchor_node *parent;
2657 * This block traverses through
2658 * a wildcard anchor.
2660 parent = &fr->anchor->children;
2661 if (match != NULL && *match) {
2663 * If any of "*" matched, then
2664 * "foo/ *" matched, mark frame
2667 PF_ANCHOR_SET_MATCH(f);
2670 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2671 if (f->child != NULL) {
2672 *rs = &f->child->ruleset;
2673 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2681 if (*depth == 0 && a != NULL)
2684 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2686 *r = TAILQ_NEXT(fr, entries);
2687 } while (*r == NULL);
2694 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2695 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2700 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2701 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2705 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2706 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2707 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2708 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2709 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2710 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2711 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2712 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2718 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2723 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2727 if (addr->addr32[3] == 0xffffffff) {
2728 addr->addr32[3] = 0;
2729 if (addr->addr32[2] == 0xffffffff) {
2730 addr->addr32[2] = 0;
2731 if (addr->addr32[1] == 0xffffffff) {
2732 addr->addr32[1] = 0;
2734 htonl(ntohl(addr->addr32[0]) + 1);
2737 htonl(ntohl(addr->addr32[1]) + 1);
2740 htonl(ntohl(addr->addr32[2]) + 1);
2743 htonl(ntohl(addr->addr32[3]) + 1);
2750 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2752 struct pf_addr *saddr, *daddr;
2753 u_int16_t sport, dport;
2754 struct inpcbinfo *pi;
2757 pd->lookup.uid = UID_MAX;
2758 pd->lookup.gid = GID_MAX;
2760 switch (pd->proto) {
2762 if (pd->hdr.tcp == NULL)
2764 sport = pd->hdr.tcp->th_sport;
2765 dport = pd->hdr.tcp->th_dport;
2769 if (pd->hdr.udp == NULL)
2771 sport = pd->hdr.udp->uh_sport;
2772 dport = pd->hdr.udp->uh_dport;
2778 if (direction == PF_IN) {
2793 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2794 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2796 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2797 daddr->v4, dport, INPLOOKUP_WILDCARD |
2798 INPLOOKUP_RLOCKPCB, NULL, m);
2806 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2807 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2809 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2810 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2811 INPLOOKUP_RLOCKPCB, NULL, m);
2821 INP_RLOCK_ASSERT(inp);
2822 pd->lookup.uid = inp->inp_cred->cr_uid;
2823 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2830 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2834 u_int8_t *opt, optlen;
2835 u_int8_t wscale = 0;
2837 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2838 if (hlen <= sizeof(struct tcphdr))
2840 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2842 opt = hdr + sizeof(struct tcphdr);
2843 hlen -= sizeof(struct tcphdr);
2853 if (wscale > TCP_MAX_WINSHIFT)
2854 wscale = TCP_MAX_WINSHIFT;
2855 wscale |= PF_WSCALE_FLAG;
2870 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2874 u_int8_t *opt, optlen;
2875 u_int16_t mss = V_tcp_mssdflt;
2877 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2878 if (hlen <= sizeof(struct tcphdr))
2880 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2882 opt = hdr + sizeof(struct tcphdr);
2883 hlen -= sizeof(struct tcphdr);
2884 while (hlen >= TCPOLEN_MAXSEG) {
2892 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2908 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2911 struct sockaddr_in *dst;
2915 struct sockaddr_in6 *dst6;
2916 struct route_in6 ro6;
2918 struct rtentry *rt = NULL;
2920 u_int16_t mss = V_tcp_mssdflt;
2925 hlen = sizeof(struct ip);
2926 bzero(&ro, sizeof(ro));
2927 dst = (struct sockaddr_in *)&ro.ro_dst;
2928 dst->sin_family = AF_INET;
2929 dst->sin_len = sizeof(*dst);
2930 dst->sin_addr = addr->v4;
2931 in_rtalloc_ign(&ro, 0, rtableid);
2937 hlen = sizeof(struct ip6_hdr);
2938 bzero(&ro6, sizeof(ro6));
2939 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2940 dst6->sin6_family = AF_INET6;
2941 dst6->sin6_len = sizeof(*dst6);
2942 dst6->sin6_addr = addr->v6;
2943 in6_rtalloc_ign(&ro6, 0, rtableid);
2949 if (rt && rt->rt_ifp) {
2950 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2951 mss = max(V_tcp_mssdflt, mss);
2954 mss = min(mss, offer);
2955 mss = max(mss, 64); /* sanity - at least max opt space */
2960 pf_tcp_iss(struct pf_pdesc *pd)
2963 u_int32_t digest[4];
2965 if (V_pf_tcp_secret_init == 0) {
2966 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
2967 MD5Init(&V_pf_tcp_secret_ctx);
2968 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
2969 sizeof(V_pf_tcp_secret));
2970 V_pf_tcp_secret_init = 1;
2973 ctx = V_pf_tcp_secret_ctx;
2975 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
2976 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
2977 if (pd->af == AF_INET6) {
2978 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
2979 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
2981 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
2982 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
2984 MD5Final((u_char *)digest, &ctx);
2985 V_pf_tcp_iss_off += 4096;
2986 #define ISN_RANDOM_INCREMENT (4096 - 1)
2987 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
2989 #undef ISN_RANDOM_INCREMENT
2993 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
2994 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
2995 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
2997 struct pf_rule *nr = NULL;
2998 struct pf_addr * const saddr = pd->src;
2999 struct pf_addr * const daddr = pd->dst;
3000 sa_family_t af = pd->af;
3001 struct pf_rule *r, *a = NULL;
3002 struct pf_ruleset *ruleset = NULL;
3003 struct pf_src_node *nsn = NULL;
3004 struct tcphdr *th = pd->hdr.tcp;
3005 struct pf_state_key *sk = NULL, *nk = NULL;
3007 int rewrite = 0, hdrlen = 0;
3008 int tag = -1, rtableid = -1;
3012 u_int16_t sport = 0, dport = 0;
3013 u_int16_t bproto_sum = 0, bip_sum = 0;
3014 u_int8_t icmptype = 0, icmpcode = 0;
3015 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3020 INP_LOCK_ASSERT(inp);
3021 pd->lookup.uid = inp->inp_cred->cr_uid;
3022 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3023 pd->lookup.done = 1;
3026 switch (pd->proto) {
3028 sport = th->th_sport;
3029 dport = th->th_dport;
3030 hdrlen = sizeof(*th);
3033 sport = pd->hdr.udp->uh_sport;
3034 dport = pd->hdr.udp->uh_dport;
3035 hdrlen = sizeof(*pd->hdr.udp);
3039 if (pd->af != AF_INET)
3041 sport = dport = pd->hdr.icmp->icmp_id;
3042 hdrlen = sizeof(*pd->hdr.icmp);
3043 icmptype = pd->hdr.icmp->icmp_type;
3044 icmpcode = pd->hdr.icmp->icmp_code;
3046 if (icmptype == ICMP_UNREACH ||
3047 icmptype == ICMP_SOURCEQUENCH ||
3048 icmptype == ICMP_REDIRECT ||
3049 icmptype == ICMP_TIMXCEED ||
3050 icmptype == ICMP_PARAMPROB)
3055 case IPPROTO_ICMPV6:
3058 sport = dport = pd->hdr.icmp6->icmp6_id;
3059 hdrlen = sizeof(*pd->hdr.icmp6);
3060 icmptype = pd->hdr.icmp6->icmp6_type;
3061 icmpcode = pd->hdr.icmp6->icmp6_code;
3063 if (icmptype == ICMP6_DST_UNREACH ||
3064 icmptype == ICMP6_PACKET_TOO_BIG ||
3065 icmptype == ICMP6_TIME_EXCEEDED ||
3066 icmptype == ICMP6_PARAM_PROB)
3071 sport = dport = hdrlen = 0;
3075 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3077 /* check packet for BINAT/NAT/RDR */
3078 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3079 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3080 KASSERT(sk != NULL, ("%s: null sk", __func__));
3081 KASSERT(nk != NULL, ("%s: null nk", __func__));
3084 bip_sum = *pd->ip_sum;
3086 switch (pd->proto) {
3088 bproto_sum = th->th_sum;
3089 pd->proto_sum = &th->th_sum;
3091 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3092 nk->port[pd->sidx] != sport) {
3093 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3094 &th->th_sum, &nk->addr[pd->sidx],
3095 nk->port[pd->sidx], 0, af);
3096 pd->sport = &th->th_sport;
3097 sport = th->th_sport;
3100 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3101 nk->port[pd->didx] != dport) {
3102 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3103 &th->th_sum, &nk->addr[pd->didx],
3104 nk->port[pd->didx], 0, af);
3105 dport = th->th_dport;
3106 pd->dport = &th->th_dport;
3111 bproto_sum = pd->hdr.udp->uh_sum;
3112 pd->proto_sum = &pd->hdr.udp->uh_sum;
3114 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3115 nk->port[pd->sidx] != sport) {
3116 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3117 pd->ip_sum, &pd->hdr.udp->uh_sum,
3118 &nk->addr[pd->sidx],
3119 nk->port[pd->sidx], 1, af);
3120 sport = pd->hdr.udp->uh_sport;
3121 pd->sport = &pd->hdr.udp->uh_sport;
3124 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3125 nk->port[pd->didx] != dport) {
3126 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3127 pd->ip_sum, &pd->hdr.udp->uh_sum,
3128 &nk->addr[pd->didx],
3129 nk->port[pd->didx], 1, af);
3130 dport = pd->hdr.udp->uh_dport;
3131 pd->dport = &pd->hdr.udp->uh_dport;
3137 nk->port[0] = nk->port[1];
3138 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3139 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3140 nk->addr[pd->sidx].v4.s_addr, 0);
3142 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3143 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3144 nk->addr[pd->didx].v4.s_addr, 0);
3146 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3147 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3148 pd->hdr.icmp->icmp_cksum, sport,
3150 pd->hdr.icmp->icmp_id = nk->port[1];
3151 pd->sport = &pd->hdr.icmp->icmp_id;
3153 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3157 case IPPROTO_ICMPV6:
3158 nk->port[0] = nk->port[1];
3159 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3160 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3161 &nk->addr[pd->sidx], 0);
3163 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3164 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3165 &nk->addr[pd->didx], 0);
3174 &nk->addr[pd->sidx], AF_INET))
3175 pf_change_a(&saddr->v4.s_addr,
3177 nk->addr[pd->sidx].v4.s_addr, 0);
3180 &nk->addr[pd->didx], AF_INET))
3181 pf_change_a(&daddr->v4.s_addr,
3183 nk->addr[pd->didx].v4.s_addr, 0);
3189 &nk->addr[pd->sidx], AF_INET6))
3190 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3193 &nk->addr[pd->didx], AF_INET6))
3194 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3207 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3208 r = r->skip[PF_SKIP_IFP].ptr;
3209 else if (r->direction && r->direction != direction)
3210 r = r->skip[PF_SKIP_DIR].ptr;
3211 else if (r->af && r->af != af)
3212 r = r->skip[PF_SKIP_AF].ptr;
3213 else if (r->proto && r->proto != pd->proto)
3214 r = r->skip[PF_SKIP_PROTO].ptr;
3215 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3216 r->src.neg, kif, M_GETFIB(m)))
3217 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3218 /* tcp/udp only. port_op always 0 in other cases */
3219 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3220 r->src.port[0], r->src.port[1], sport))
3221 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3222 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3223 r->dst.neg, NULL, M_GETFIB(m)))
3224 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3225 /* tcp/udp only. port_op always 0 in other cases */
3226 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3227 r->dst.port[0], r->dst.port[1], dport))
3228 r = r->skip[PF_SKIP_DST_PORT].ptr;
3229 /* icmp only. type always 0 in other cases */
3230 else if (r->type && r->type != icmptype + 1)
3231 r = TAILQ_NEXT(r, entries);
3232 /* icmp only. type always 0 in other cases */
3233 else if (r->code && r->code != icmpcode + 1)
3234 r = TAILQ_NEXT(r, entries);
3235 else if (r->tos && !(r->tos == pd->tos))
3236 r = TAILQ_NEXT(r, entries);
3237 else if (r->rule_flag & PFRULE_FRAGMENT)
3238 r = TAILQ_NEXT(r, entries);
3239 else if (pd->proto == IPPROTO_TCP &&
3240 (r->flagset & th->th_flags) != r->flags)
3241 r = TAILQ_NEXT(r, entries);
3242 /* tcp/udp only. uid.op always 0 in other cases */
3243 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3244 pf_socket_lookup(direction, pd, m), 1)) &&
3245 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3247 r = TAILQ_NEXT(r, entries);
3248 /* tcp/udp only. gid.op always 0 in other cases */
3249 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3250 pf_socket_lookup(direction, pd, m), 1)) &&
3251 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3253 r = TAILQ_NEXT(r, entries);
3255 r->prob <= arc4random())
3256 r = TAILQ_NEXT(r, entries);
3257 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3258 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3259 r = TAILQ_NEXT(r, entries);
3260 else if (r->os_fingerprint != PF_OSFP_ANY &&
3261 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3262 pf_osfp_fingerprint(pd, m, off, th),
3263 r->os_fingerprint)))
3264 r = TAILQ_NEXT(r, entries);
3268 if (r->rtableid >= 0)
3269 rtableid = r->rtableid;
3270 if (r->anchor == NULL) {
3277 r = TAILQ_NEXT(r, entries);
3279 pf_step_into_anchor(anchor_stack, &asd,
3280 &ruleset, PF_RULESET_FILTER, &r, &a,
3283 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3284 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3291 REASON_SET(&reason, PFRES_MATCH);
3293 if (r->log || (nr != NULL && nr->log)) {
3295 m_copyback(m, off, hdrlen, pd->hdr.any);
3296 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3300 if ((r->action == PF_DROP) &&
3301 ((r->rule_flag & PFRULE_RETURNRST) ||
3302 (r->rule_flag & PFRULE_RETURNICMP) ||
3303 (r->rule_flag & PFRULE_RETURN))) {
3304 /* undo NAT changes, if they have taken place */
3306 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3307 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3309 *pd->sport = sk->port[pd->sidx];
3311 *pd->dport = sk->port[pd->didx];
3313 *pd->proto_sum = bproto_sum;
3315 *pd->ip_sum = bip_sum;
3316 m_copyback(m, off, hdrlen, pd->hdr.any);
3318 if (pd->proto == IPPROTO_TCP &&
3319 ((r->rule_flag & PFRULE_RETURNRST) ||
3320 (r->rule_flag & PFRULE_RETURN)) &&
3321 !(th->th_flags & TH_RST)) {
3322 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3334 h4 = mtod(m, struct ip *);
3335 len = ntohs(h4->ip_len) - off;
3340 h6 = mtod(m, struct ip6_hdr *);
3341 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3346 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3347 REASON_SET(&reason, PFRES_PROTCKSUM);
3349 if (th->th_flags & TH_SYN)
3351 if (th->th_flags & TH_FIN)
3353 pf_send_tcp(m, r, af, pd->dst,
3354 pd->src, th->th_dport, th->th_sport,
3355 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3356 r->return_ttl, 1, 0, kif->pfik_ifp);
3358 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3360 pf_send_icmp(m, r->return_icmp >> 8,
3361 r->return_icmp & 255, af, r);
3362 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3364 pf_send_icmp(m, r->return_icmp6 >> 8,
3365 r->return_icmp6 & 255, af, r);
3368 if (r->action == PF_DROP)
3371 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3372 REASON_SET(&reason, PFRES_MEMORY);
3376 M_SETFIB(m, rtableid);
3378 if (!state_icmp && (r->keep_state || nr != NULL ||
3379 (pd->flags & PFDESC_TCP_NORM))) {
3381 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3382 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3384 if (action != PF_PASS)
3388 uma_zfree(V_pf_state_key_z, sk);
3390 uma_zfree(V_pf_state_key_z, nk);
3393 /* copy back packet headers if we performed NAT operations */
3395 m_copyback(m, off, hdrlen, pd->hdr.any);
3397 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3398 direction == PF_OUT &&
3399 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3401 * We want the state created, but we dont
3402 * want to send this in case a partner
3403 * firewall has to know about it to allow
3404 * replies through it.
3412 uma_zfree(V_pf_state_key_z, sk);
3414 uma_zfree(V_pf_state_key_z, nk);
3419 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3420 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3421 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3422 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3423 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3425 struct pf_state *s = NULL;
3426 struct pf_src_node *sn = NULL;
3427 struct tcphdr *th = pd->hdr.tcp;
3428 u_int16_t mss = V_tcp_mssdflt;
3431 /* check maximums */
3432 if (r->max_states &&
3433 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3434 counter_u64_add(V_pf_status.lcounters[LCNT_STATES], 1);
3435 REASON_SET(&reason, PFRES_MAXSTATES);
3438 /* src node for filter rule */
3439 if ((r->rule_flag & PFRULE_SRCTRACK ||
3440 r->rpool.opts & PF_POOL_STICKYADDR) &&
3441 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3442 REASON_SET(&reason, PFRES_SRCLIMIT);
3445 /* src node for translation rule */
3446 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3447 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3448 REASON_SET(&reason, PFRES_SRCLIMIT);
3451 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3453 REASON_SET(&reason, PFRES_MEMORY);
3457 s->nat_rule.ptr = nr;
3459 STATE_INC_COUNTERS(s);
3461 s->state_flags |= PFSTATE_ALLOWOPTS;
3462 if (r->rule_flag & PFRULE_STATESLOPPY)
3463 s->state_flags |= PFSTATE_SLOPPY;
3464 s->log = r->log & PF_LOG_ALL;
3465 s->sync_state = PFSYNC_S_NONE;
3467 s->log |= nr->log & PF_LOG_ALL;
3468 switch (pd->proto) {
3470 s->src.seqlo = ntohl(th->th_seq);
3471 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3472 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3473 r->keep_state == PF_STATE_MODULATE) {
3474 /* Generate sequence number modulator */
3475 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3478 pf_change_a(&th->th_seq, &th->th_sum,
3479 htonl(s->src.seqlo + s->src.seqdiff), 0);
3483 if (th->th_flags & TH_SYN) {
3485 s->src.wscale = pf_get_wscale(m, off,
3486 th->th_off, pd->af);
3488 s->src.max_win = MAX(ntohs(th->th_win), 1);
3489 if (s->src.wscale & PF_WSCALE_MASK) {
3490 /* Remove scale factor from initial window */
3491 int win = s->src.max_win;
3492 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3493 s->src.max_win = (win - 1) >>
3494 (s->src.wscale & PF_WSCALE_MASK);
3496 if (th->th_flags & TH_FIN)
3500 s->src.state = TCPS_SYN_SENT;
3501 s->dst.state = TCPS_CLOSED;
3502 s->timeout = PFTM_TCP_FIRST_PACKET;
3505 s->src.state = PFUDPS_SINGLE;
3506 s->dst.state = PFUDPS_NO_TRAFFIC;
3507 s->timeout = PFTM_UDP_FIRST_PACKET;
3511 case IPPROTO_ICMPV6:
3513 s->timeout = PFTM_ICMP_FIRST_PACKET;
3516 s->src.state = PFOTHERS_SINGLE;
3517 s->dst.state = PFOTHERS_NO_TRAFFIC;
3518 s->timeout = PFTM_OTHER_FIRST_PACKET;
3521 if (r->rt && r->rt != PF_FASTROUTE) {
3522 if (pf_map_addr(pd->af, r, pd->src, &s->rt_addr, NULL, &sn)) {
3523 REASON_SET(&reason, PFRES_BADSTATE);
3524 pf_src_tree_remove_state(s);
3525 STATE_DEC_COUNTERS(s);
3526 uma_zfree(V_pf_state_z, s);
3529 s->rt_kif = r->rpool.cur->kif;
3532 s->creation = time_uptime;
3533 s->expire = time_uptime;
3537 s->src_node->states++;
3540 /* XXX We only modify one side for now. */
3541 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3542 s->nat_src_node = nsn;
3543 s->nat_src_node->states++;
3545 if (pd->proto == IPPROTO_TCP) {
3546 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3547 off, pd, th, &s->src, &s->dst)) {
3548 REASON_SET(&reason, PFRES_MEMORY);
3549 pf_src_tree_remove_state(s);
3550 STATE_DEC_COUNTERS(s);
3551 uma_zfree(V_pf_state_z, s);
3554 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3555 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3556 &s->src, &s->dst, rewrite)) {
3557 /* This really shouldn't happen!!! */
3558 DPFPRINTF(PF_DEBUG_URGENT,
3559 ("pf_normalize_tcp_stateful failed on first pkt"));
3560 pf_normalize_tcp_cleanup(s);
3561 pf_src_tree_remove_state(s);
3562 STATE_DEC_COUNTERS(s);
3563 uma_zfree(V_pf_state_z, s);
3567 s->direction = pd->dir;
3570 * sk/nk could already been setup by pf_get_translation().
3573 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3574 __func__, nr, sk, nk));
3575 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3580 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3581 __func__, nr, sk, nk));
3583 /* Swap sk/nk for PF_OUT. */
3584 if (pf_state_insert(BOUND_IFACE(r, kif),
3585 (pd->dir == PF_IN) ? sk : nk,
3586 (pd->dir == PF_IN) ? nk : sk, s)) {
3587 if (pd->proto == IPPROTO_TCP)
3588 pf_normalize_tcp_cleanup(s);
3589 REASON_SET(&reason, PFRES_STATEINS);
3590 pf_src_tree_remove_state(s);
3591 STATE_DEC_COUNTERS(s);
3592 uma_zfree(V_pf_state_z, s);
3599 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3600 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3601 s->src.state = PF_TCPS_PROXY_SRC;
3602 /* undo NAT changes, if they have taken place */
3604 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3605 if (pd->dir == PF_OUT)
3606 skt = s->key[PF_SK_STACK];
3607 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3608 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3610 *pd->sport = skt->port[pd->sidx];
3612 *pd->dport = skt->port[pd->didx];
3614 *pd->proto_sum = bproto_sum;
3616 *pd->ip_sum = bip_sum;
3617 m_copyback(m, off, hdrlen, pd->hdr.any);
3619 s->src.seqhi = htonl(arc4random());
3620 /* Find mss option */
3621 int rtid = M_GETFIB(m);
3622 mss = pf_get_mss(m, off, th->th_off, pd->af);
3623 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3624 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3626 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3627 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3628 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3629 REASON_SET(&reason, PFRES_SYNPROXY);
3630 return (PF_SYNPROXY_DROP);
3637 uma_zfree(V_pf_state_key_z, sk);
3639 uma_zfree(V_pf_state_key_z, nk);
3641 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3642 pf_unlink_src_node(sn);
3643 pf_free_src_node(sn);
3646 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3647 pf_unlink_src_node(nsn);
3648 pf_free_src_node(nsn);
3655 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3656 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3657 struct pf_ruleset **rsm)
3659 struct pf_rule *r, *a = NULL;
3660 struct pf_ruleset *ruleset = NULL;
3661 sa_family_t af = pd->af;
3666 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3670 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3673 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3674 r = r->skip[PF_SKIP_IFP].ptr;
3675 else if (r->direction && r->direction != direction)
3676 r = r->skip[PF_SKIP_DIR].ptr;
3677 else if (r->af && r->af != af)
3678 r = r->skip[PF_SKIP_AF].ptr;
3679 else if (r->proto && r->proto != pd->proto)
3680 r = r->skip[PF_SKIP_PROTO].ptr;
3681 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3682 r->src.neg, kif, M_GETFIB(m)))
3683 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3684 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3685 r->dst.neg, NULL, M_GETFIB(m)))
3686 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3687 else if (r->tos && !(r->tos == pd->tos))
3688 r = TAILQ_NEXT(r, entries);
3689 else if (r->os_fingerprint != PF_OSFP_ANY)
3690 r = TAILQ_NEXT(r, entries);
3691 else if (pd->proto == IPPROTO_UDP &&
3692 (r->src.port_op || r->dst.port_op))
3693 r = TAILQ_NEXT(r, entries);
3694 else if (pd->proto == IPPROTO_TCP &&
3695 (r->src.port_op || r->dst.port_op || r->flagset))
3696 r = TAILQ_NEXT(r, entries);
3697 else if ((pd->proto == IPPROTO_ICMP ||
3698 pd->proto == IPPROTO_ICMPV6) &&
3699 (r->type || r->code))
3700 r = TAILQ_NEXT(r, entries);
3701 else if (r->prob && r->prob <=
3702 (arc4random() % (UINT_MAX - 1) + 1))
3703 r = TAILQ_NEXT(r, entries);
3704 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3705 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3706 r = TAILQ_NEXT(r, entries);
3708 if (r->anchor == NULL) {
3715 r = TAILQ_NEXT(r, entries);
3717 pf_step_into_anchor(anchor_stack, &asd,
3718 &ruleset, PF_RULESET_FILTER, &r, &a,
3721 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3722 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3729 REASON_SET(&reason, PFRES_MATCH);
3732 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3735 if (r->action != PF_PASS)
3738 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3739 REASON_SET(&reason, PFRES_MEMORY);
3747 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3748 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3749 struct pf_pdesc *pd, u_short *reason, int *copyback)
3751 struct tcphdr *th = pd->hdr.tcp;
3752 u_int16_t win = ntohs(th->th_win);
3753 u_int32_t ack, end, seq, orig_seq;
3757 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3758 sws = src->wscale & PF_WSCALE_MASK;
3759 dws = dst->wscale & PF_WSCALE_MASK;
3764 * Sequence tracking algorithm from Guido van Rooij's paper:
3765 * http://www.madison-gurkha.com/publications/tcp_filtering/
3769 orig_seq = seq = ntohl(th->th_seq);
3770 if (src->seqlo == 0) {
3771 /* First packet from this end. Set its state */
3773 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3774 src->scrub == NULL) {
3775 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3776 REASON_SET(reason, PFRES_MEMORY);
3781 /* Deferred generation of sequence number modulator */
3782 if (dst->seqdiff && !src->seqdiff) {
3783 /* use random iss for the TCP server */
3784 while ((src->seqdiff = arc4random() - seq) == 0)
3786 ack = ntohl(th->th_ack) - dst->seqdiff;
3787 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3789 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3792 ack = ntohl(th->th_ack);
3795 end = seq + pd->p_len;
3796 if (th->th_flags & TH_SYN) {
3798 if (dst->wscale & PF_WSCALE_FLAG) {
3799 src->wscale = pf_get_wscale(m, off, th->th_off,
3801 if (src->wscale & PF_WSCALE_FLAG) {
3802 /* Remove scale factor from initial
3804 sws = src->wscale & PF_WSCALE_MASK;
3805 win = ((u_int32_t)win + (1 << sws) - 1)
3807 dws = dst->wscale & PF_WSCALE_MASK;
3809 /* fixup other window */
3810 dst->max_win <<= dst->wscale &
3812 /* in case of a retrans SYN|ACK */
3817 if (th->th_flags & TH_FIN)
3821 if (src->state < TCPS_SYN_SENT)
3822 src->state = TCPS_SYN_SENT;
3825 * May need to slide the window (seqhi may have been set by
3826 * the crappy stack check or if we picked up the connection
3827 * after establishment)
3829 if (src->seqhi == 1 ||
3830 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3831 src->seqhi = end + MAX(1, dst->max_win << dws);
3832 if (win > src->max_win)
3836 ack = ntohl(th->th_ack) - dst->seqdiff;
3838 /* Modulate sequence numbers */
3839 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3841 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3844 end = seq + pd->p_len;
3845 if (th->th_flags & TH_SYN)
3847 if (th->th_flags & TH_FIN)
3851 if ((th->th_flags & TH_ACK) == 0) {
3852 /* Let it pass through the ack skew check */
3854 } else if ((ack == 0 &&
3855 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3856 /* broken tcp stacks do not set ack */
3857 (dst->state < TCPS_SYN_SENT)) {
3859 * Many stacks (ours included) will set the ACK number in an
3860 * FIN|ACK if the SYN times out -- no sequence to ACK.
3866 /* Ease sequencing restrictions on no data packets */
3871 ackskew = dst->seqlo - ack;
3875 * Need to demodulate the sequence numbers in any TCP SACK options
3876 * (Selective ACK). We could optionally validate the SACK values
3877 * against the current ACK window, either forwards or backwards, but
3878 * I'm not confident that SACK has been implemented properly
3879 * everywhere. It wouldn't surprise me if several stacks accidently
3880 * SACK too far backwards of previously ACKed data. There really aren't
3881 * any security implications of bad SACKing unless the target stack
3882 * doesn't validate the option length correctly. Someone trying to
3883 * spoof into a TCP connection won't bother blindly sending SACK
3886 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
3887 if (pf_modulate_sack(m, off, pd, th, dst))
3892 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
3893 if (SEQ_GEQ(src->seqhi, end) &&
3894 /* Last octet inside other's window space */
3895 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
3896 /* Retrans: not more than one window back */
3897 (ackskew >= -MAXACKWINDOW) &&
3898 /* Acking not more than one reassembled fragment backwards */
3899 (ackskew <= (MAXACKWINDOW << sws)) &&
3900 /* Acking not more than one window forward */
3901 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
3902 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
3903 (pd->flags & PFDESC_IP_REAS) == 0)) {
3904 /* Require an exact/+1 sequence match on resets when possible */
3906 if (dst->scrub || src->scrub) {
3907 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
3908 *state, src, dst, copyback))
3912 /* update max window */
3913 if (src->max_win < win)
3915 /* synchronize sequencing */
3916 if (SEQ_GT(end, src->seqlo))
3918 /* slide the window of what the other end can send */
3919 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
3920 dst->seqhi = ack + MAX((win << sws), 1);
3924 if (th->th_flags & TH_SYN)
3925 if (src->state < TCPS_SYN_SENT)
3926 src->state = TCPS_SYN_SENT;
3927 if (th->th_flags & TH_FIN)
3928 if (src->state < TCPS_CLOSING)
3929 src->state = TCPS_CLOSING;
3930 if (th->th_flags & TH_ACK) {
3931 if (dst->state == TCPS_SYN_SENT) {
3932 dst->state = TCPS_ESTABLISHED;
3933 if (src->state == TCPS_ESTABLISHED &&
3934 (*state)->src_node != NULL &&
3935 pf_src_connlimit(state)) {
3936 REASON_SET(reason, PFRES_SRCLIMIT);
3939 } else if (dst->state == TCPS_CLOSING)
3940 dst->state = TCPS_FIN_WAIT_2;
3942 if (th->th_flags & TH_RST)
3943 src->state = dst->state = TCPS_TIME_WAIT;
3945 /* update expire time */
3946 (*state)->expire = time_uptime;
3947 if (src->state >= TCPS_FIN_WAIT_2 &&
3948 dst->state >= TCPS_FIN_WAIT_2)
3949 (*state)->timeout = PFTM_TCP_CLOSED;
3950 else if (src->state >= TCPS_CLOSING &&
3951 dst->state >= TCPS_CLOSING)
3952 (*state)->timeout = PFTM_TCP_FIN_WAIT;
3953 else if (src->state < TCPS_ESTABLISHED ||
3954 dst->state < TCPS_ESTABLISHED)
3955 (*state)->timeout = PFTM_TCP_OPENING;
3956 else if (src->state >= TCPS_CLOSING ||
3957 dst->state >= TCPS_CLOSING)
3958 (*state)->timeout = PFTM_TCP_CLOSING;
3960 (*state)->timeout = PFTM_TCP_ESTABLISHED;
3962 /* Fall through to PASS packet */
3964 } else if ((dst->state < TCPS_SYN_SENT ||
3965 dst->state >= TCPS_FIN_WAIT_2 ||
3966 src->state >= TCPS_FIN_WAIT_2) &&
3967 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
3968 /* Within a window forward of the originating packet */
3969 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
3970 /* Within a window backward of the originating packet */
3973 * This currently handles three situations:
3974 * 1) Stupid stacks will shotgun SYNs before their peer
3976 * 2) When PF catches an already established stream (the
3977 * firewall rebooted, the state table was flushed, routes
3979 * 3) Packets get funky immediately after the connection
3980 * closes (this should catch Solaris spurious ACK|FINs
3981 * that web servers like to spew after a close)
3983 * This must be a little more careful than the above code
3984 * since packet floods will also be caught here. We don't
3985 * update the TTL here to mitigate the damage of a packet
3986 * flood and so the same code can handle awkward establishment
3987 * and a loosened connection close.
3988 * In the establishment case, a correct peer response will
3989 * validate the connection, go through the normal state code
3990 * and keep updating the state TTL.
3993 if (V_pf_status.debug >= PF_DEBUG_MISC) {
3994 printf("pf: loose state match: ");
3995 pf_print_state(*state);
3996 pf_print_flags(th->th_flags);
3997 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
3998 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
3999 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4000 (unsigned long long)(*state)->packets[1],
4001 pd->dir == PF_IN ? "in" : "out",
4002 pd->dir == (*state)->direction ? "fwd" : "rev");
4005 if (dst->scrub || src->scrub) {
4006 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4007 *state, src, dst, copyback))
4011 /* update max window */
4012 if (src->max_win < win)
4014 /* synchronize sequencing */
4015 if (SEQ_GT(end, src->seqlo))
4017 /* slide the window of what the other end can send */
4018 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4019 dst->seqhi = ack + MAX((win << sws), 1);
4022 * Cannot set dst->seqhi here since this could be a shotgunned
4023 * SYN and not an already established connection.
4026 if (th->th_flags & TH_FIN)
4027 if (src->state < TCPS_CLOSING)
4028 src->state = TCPS_CLOSING;
4029 if (th->th_flags & TH_RST)
4030 src->state = dst->state = TCPS_TIME_WAIT;
4032 /* Fall through to PASS packet */
4035 if ((*state)->dst.state == TCPS_SYN_SENT &&
4036 (*state)->src.state == TCPS_SYN_SENT) {
4037 /* Send RST for state mismatches during handshake */
4038 if (!(th->th_flags & TH_RST))
4039 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4040 pd->dst, pd->src, th->th_dport,
4041 th->th_sport, ntohl(th->th_ack), 0,
4043 (*state)->rule.ptr->return_ttl, 1, 0,
4048 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4049 printf("pf: BAD state: ");
4050 pf_print_state(*state);
4051 pf_print_flags(th->th_flags);
4052 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4053 "pkts=%llu:%llu dir=%s,%s\n",
4054 seq, orig_seq, ack, pd->p_len, ackskew,
4055 (unsigned long long)(*state)->packets[0],
4056 (unsigned long long)(*state)->packets[1],
4057 pd->dir == PF_IN ? "in" : "out",
4058 pd->dir == (*state)->direction ? "fwd" : "rev");
4059 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4060 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4061 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4063 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4064 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4065 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4066 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4068 REASON_SET(reason, PFRES_BADSTATE);
4076 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4077 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4079 struct tcphdr *th = pd->hdr.tcp;
4081 if (th->th_flags & TH_SYN)
4082 if (src->state < TCPS_SYN_SENT)
4083 src->state = TCPS_SYN_SENT;
4084 if (th->th_flags & TH_FIN)
4085 if (src->state < TCPS_CLOSING)
4086 src->state = TCPS_CLOSING;
4087 if (th->th_flags & TH_ACK) {
4088 if (dst->state == TCPS_SYN_SENT) {
4089 dst->state = TCPS_ESTABLISHED;
4090 if (src->state == TCPS_ESTABLISHED &&
4091 (*state)->src_node != NULL &&
4092 pf_src_connlimit(state)) {
4093 REASON_SET(reason, PFRES_SRCLIMIT);
4096 } else if (dst->state == TCPS_CLOSING) {
4097 dst->state = TCPS_FIN_WAIT_2;
4098 } else if (src->state == TCPS_SYN_SENT &&
4099 dst->state < TCPS_SYN_SENT) {
4101 * Handle a special sloppy case where we only see one
4102 * half of the connection. If there is a ACK after
4103 * the initial SYN without ever seeing a packet from
4104 * the destination, set the connection to established.
4106 dst->state = src->state = TCPS_ESTABLISHED;
4107 if ((*state)->src_node != NULL &&
4108 pf_src_connlimit(state)) {
4109 REASON_SET(reason, PFRES_SRCLIMIT);
4112 } else if (src->state == TCPS_CLOSING &&
4113 dst->state == TCPS_ESTABLISHED &&
4116 * Handle the closing of half connections where we
4117 * don't see the full bidirectional FIN/ACK+ACK
4120 dst->state = TCPS_CLOSING;
4123 if (th->th_flags & TH_RST)
4124 src->state = dst->state = TCPS_TIME_WAIT;
4126 /* update expire time */
4127 (*state)->expire = time_uptime;
4128 if (src->state >= TCPS_FIN_WAIT_2 &&
4129 dst->state >= TCPS_FIN_WAIT_2)
4130 (*state)->timeout = PFTM_TCP_CLOSED;
4131 else if (src->state >= TCPS_CLOSING &&
4132 dst->state >= TCPS_CLOSING)
4133 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4134 else if (src->state < TCPS_ESTABLISHED ||
4135 dst->state < TCPS_ESTABLISHED)
4136 (*state)->timeout = PFTM_TCP_OPENING;
4137 else if (src->state >= TCPS_CLOSING ||
4138 dst->state >= TCPS_CLOSING)
4139 (*state)->timeout = PFTM_TCP_CLOSING;
4141 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4147 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4148 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4151 struct pf_state_key_cmp key;
4152 struct tcphdr *th = pd->hdr.tcp;
4154 struct pf_state_peer *src, *dst;
4155 struct pf_state_key *sk;
4157 bzero(&key, sizeof(key));
4159 key.proto = IPPROTO_TCP;
4160 if (direction == PF_IN) { /* wire side, straight */
4161 PF_ACPY(&key.addr[0], pd->src, key.af);
4162 PF_ACPY(&key.addr[1], pd->dst, key.af);
4163 key.port[0] = th->th_sport;
4164 key.port[1] = th->th_dport;
4165 } else { /* stack side, reverse */
4166 PF_ACPY(&key.addr[1], pd->src, key.af);
4167 PF_ACPY(&key.addr[0], pd->dst, key.af);
4168 key.port[1] = th->th_sport;
4169 key.port[0] = th->th_dport;
4172 STATE_LOOKUP(kif, &key, direction, *state, pd);
4174 if (direction == (*state)->direction) {
4175 src = &(*state)->src;
4176 dst = &(*state)->dst;
4178 src = &(*state)->dst;
4179 dst = &(*state)->src;
4182 sk = (*state)->key[pd->didx];
4184 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4185 if (direction != (*state)->direction) {
4186 REASON_SET(reason, PFRES_SYNPROXY);
4187 return (PF_SYNPROXY_DROP);
4189 if (th->th_flags & TH_SYN) {
4190 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4191 REASON_SET(reason, PFRES_SYNPROXY);
4194 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4195 pd->src, th->th_dport, th->th_sport,
4196 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4197 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4198 REASON_SET(reason, PFRES_SYNPROXY);
4199 return (PF_SYNPROXY_DROP);
4200 } else if (!(th->th_flags & TH_ACK) ||
4201 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4202 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4203 REASON_SET(reason, PFRES_SYNPROXY);
4205 } else if ((*state)->src_node != NULL &&
4206 pf_src_connlimit(state)) {
4207 REASON_SET(reason, PFRES_SRCLIMIT);
4210 (*state)->src.state = PF_TCPS_PROXY_DST;
4212 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4213 if (direction == (*state)->direction) {
4214 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4215 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4216 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4217 REASON_SET(reason, PFRES_SYNPROXY);
4220 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4221 if ((*state)->dst.seqhi == 1)
4222 (*state)->dst.seqhi = htonl(arc4random());
4223 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4224 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4225 sk->port[pd->sidx], sk->port[pd->didx],
4226 (*state)->dst.seqhi, 0, TH_SYN, 0,
4227 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4228 REASON_SET(reason, PFRES_SYNPROXY);
4229 return (PF_SYNPROXY_DROP);
4230 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4232 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4233 REASON_SET(reason, PFRES_SYNPROXY);
4236 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4237 (*state)->dst.seqlo = ntohl(th->th_seq);
4238 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4239 pd->src, th->th_dport, th->th_sport,
4240 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4241 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4242 (*state)->tag, NULL);
4243 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4244 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4245 sk->port[pd->sidx], sk->port[pd->didx],
4246 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4247 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4248 (*state)->src.seqdiff = (*state)->dst.seqhi -
4249 (*state)->src.seqlo;
4250 (*state)->dst.seqdiff = (*state)->src.seqhi -
4251 (*state)->dst.seqlo;
4252 (*state)->src.seqhi = (*state)->src.seqlo +
4253 (*state)->dst.max_win;
4254 (*state)->dst.seqhi = (*state)->dst.seqlo +
4255 (*state)->src.max_win;
4256 (*state)->src.wscale = (*state)->dst.wscale = 0;
4257 (*state)->src.state = (*state)->dst.state =
4259 REASON_SET(reason, PFRES_SYNPROXY);
4260 return (PF_SYNPROXY_DROP);
4264 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4265 dst->state >= TCPS_FIN_WAIT_2 &&
4266 src->state >= TCPS_FIN_WAIT_2) {
4267 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4268 printf("pf: state reuse ");
4269 pf_print_state(*state);
4270 pf_print_flags(th->th_flags);
4273 /* XXX make sure it's the same direction ?? */
4274 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4275 pf_unlink_state(*state, PF_ENTER_LOCKED);
4280 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4281 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4284 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4285 ©back) == PF_DROP)
4289 /* translate source/destination address, if necessary */
4290 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4291 struct pf_state_key *nk = (*state)->key[pd->didx];
4293 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4294 nk->port[pd->sidx] != th->th_sport)
4295 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4296 &th->th_sum, &nk->addr[pd->sidx],
4297 nk->port[pd->sidx], 0, pd->af);
4299 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4300 nk->port[pd->didx] != th->th_dport)
4301 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4302 &th->th_sum, &nk->addr[pd->didx],
4303 nk->port[pd->didx], 0, pd->af);
4307 /* Copyback sequence modulation or stateful scrub changes if needed */
4309 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4315 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4316 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4318 struct pf_state_peer *src, *dst;
4319 struct pf_state_key_cmp key;
4320 struct udphdr *uh = pd->hdr.udp;
4322 bzero(&key, sizeof(key));
4324 key.proto = IPPROTO_UDP;
4325 if (direction == PF_IN) { /* wire side, straight */
4326 PF_ACPY(&key.addr[0], pd->src, key.af);
4327 PF_ACPY(&key.addr[1], pd->dst, key.af);
4328 key.port[0] = uh->uh_sport;
4329 key.port[1] = uh->uh_dport;
4330 } else { /* stack side, reverse */
4331 PF_ACPY(&key.addr[1], pd->src, key.af);
4332 PF_ACPY(&key.addr[0], pd->dst, key.af);
4333 key.port[1] = uh->uh_sport;
4334 key.port[0] = uh->uh_dport;
4337 STATE_LOOKUP(kif, &key, direction, *state, pd);
4339 if (direction == (*state)->direction) {
4340 src = &(*state)->src;
4341 dst = &(*state)->dst;
4343 src = &(*state)->dst;
4344 dst = &(*state)->src;
4348 if (src->state < PFUDPS_SINGLE)
4349 src->state = PFUDPS_SINGLE;
4350 if (dst->state == PFUDPS_SINGLE)
4351 dst->state = PFUDPS_MULTIPLE;
4353 /* update expire time */
4354 (*state)->expire = time_uptime;
4355 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4356 (*state)->timeout = PFTM_UDP_MULTIPLE;
4358 (*state)->timeout = PFTM_UDP_SINGLE;
4360 /* translate source/destination address, if necessary */
4361 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4362 struct pf_state_key *nk = (*state)->key[pd->didx];
4364 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4365 nk->port[pd->sidx] != uh->uh_sport)
4366 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4367 &uh->uh_sum, &nk->addr[pd->sidx],
4368 nk->port[pd->sidx], 1, pd->af);
4370 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4371 nk->port[pd->didx] != uh->uh_dport)
4372 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4373 &uh->uh_sum, &nk->addr[pd->didx],
4374 nk->port[pd->didx], 1, pd->af);
4375 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4382 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4383 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4385 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4386 u_int16_t icmpid = 0, *icmpsum;
4389 struct pf_state_key_cmp key;
4391 bzero(&key, sizeof(key));
4392 switch (pd->proto) {
4395 icmptype = pd->hdr.icmp->icmp_type;
4396 icmpid = pd->hdr.icmp->icmp_id;
4397 icmpsum = &pd->hdr.icmp->icmp_cksum;
4399 if (icmptype == ICMP_UNREACH ||
4400 icmptype == ICMP_SOURCEQUENCH ||
4401 icmptype == ICMP_REDIRECT ||
4402 icmptype == ICMP_TIMXCEED ||
4403 icmptype == ICMP_PARAMPROB)
4408 case IPPROTO_ICMPV6:
4409 icmptype = pd->hdr.icmp6->icmp6_type;
4410 icmpid = pd->hdr.icmp6->icmp6_id;
4411 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4413 if (icmptype == ICMP6_DST_UNREACH ||
4414 icmptype == ICMP6_PACKET_TOO_BIG ||
4415 icmptype == ICMP6_TIME_EXCEEDED ||
4416 icmptype == ICMP6_PARAM_PROB)
4425 * ICMP query/reply message not related to a TCP/UDP packet.
4426 * Search for an ICMP state.
4429 key.proto = pd->proto;
4430 key.port[0] = key.port[1] = icmpid;
4431 if (direction == PF_IN) { /* wire side, straight */
4432 PF_ACPY(&key.addr[0], pd->src, key.af);
4433 PF_ACPY(&key.addr[1], pd->dst, key.af);
4434 } else { /* stack side, reverse */
4435 PF_ACPY(&key.addr[1], pd->src, key.af);
4436 PF_ACPY(&key.addr[0], pd->dst, key.af);
4439 STATE_LOOKUP(kif, &key, direction, *state, pd);
4441 (*state)->expire = time_uptime;
4442 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4444 /* translate source/destination address, if necessary */
4445 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4446 struct pf_state_key *nk = (*state)->key[pd->didx];
4451 if (PF_ANEQ(pd->src,
4452 &nk->addr[pd->sidx], AF_INET))
4453 pf_change_a(&saddr->v4.s_addr,
4455 nk->addr[pd->sidx].v4.s_addr, 0);
4457 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4459 pf_change_a(&daddr->v4.s_addr,
4461 nk->addr[pd->didx].v4.s_addr, 0);
4464 pd->hdr.icmp->icmp_id) {
4465 pd->hdr.icmp->icmp_cksum =
4467 pd->hdr.icmp->icmp_cksum, icmpid,
4468 nk->port[pd->sidx], 0);
4469 pd->hdr.icmp->icmp_id =
4473 m_copyback(m, off, ICMP_MINLEN,
4474 (caddr_t )pd->hdr.icmp);
4479 if (PF_ANEQ(pd->src,
4480 &nk->addr[pd->sidx], AF_INET6))
4482 &pd->hdr.icmp6->icmp6_cksum,
4483 &nk->addr[pd->sidx], 0);
4485 if (PF_ANEQ(pd->dst,
4486 &nk->addr[pd->didx], AF_INET6))
4488 &pd->hdr.icmp6->icmp6_cksum,
4489 &nk->addr[pd->didx], 0);
4491 m_copyback(m, off, sizeof(struct icmp6_hdr),
4492 (caddr_t )pd->hdr.icmp6);
4501 * ICMP error message in response to a TCP/UDP packet.
4502 * Extract the inner TCP/UDP header and search for that state.
4505 struct pf_pdesc pd2;
4506 bzero(&pd2, sizeof pd2);
4511 struct ip6_hdr h2_6;
4518 /* Payload packet is from the opposite direction. */
4519 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4520 pd2.didx = (direction == PF_IN) ? 0 : 1;
4524 /* offset of h2 in mbuf chain */
4525 ipoff2 = off + ICMP_MINLEN;
4527 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4528 NULL, reason, pd2.af)) {
4529 DPFPRINTF(PF_DEBUG_MISC,
4530 ("pf: ICMP error message too short "
4535 * ICMP error messages don't refer to non-first
4538 if (h2.ip_off & htons(IP_OFFMASK)) {
4539 REASON_SET(reason, PFRES_FRAG);
4543 /* offset of protocol header that follows h2 */
4544 off2 = ipoff2 + (h2.ip_hl << 2);
4546 pd2.proto = h2.ip_p;
4547 pd2.src = (struct pf_addr *)&h2.ip_src;
4548 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4549 pd2.ip_sum = &h2.ip_sum;
4554 ipoff2 = off + sizeof(struct icmp6_hdr);
4556 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4557 NULL, reason, pd2.af)) {
4558 DPFPRINTF(PF_DEBUG_MISC,
4559 ("pf: ICMP error message too short "
4563 pd2.proto = h2_6.ip6_nxt;
4564 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4565 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4567 off2 = ipoff2 + sizeof(h2_6);
4569 switch (pd2.proto) {
4570 case IPPROTO_FRAGMENT:
4572 * ICMPv6 error messages for
4573 * non-first fragments
4575 REASON_SET(reason, PFRES_FRAG);
4578 case IPPROTO_HOPOPTS:
4579 case IPPROTO_ROUTING:
4580 case IPPROTO_DSTOPTS: {
4581 /* get next header and header length */
4582 struct ip6_ext opt6;
4584 if (!pf_pull_hdr(m, off2, &opt6,
4585 sizeof(opt6), NULL, reason,
4587 DPFPRINTF(PF_DEBUG_MISC,
4588 ("pf: ICMPv6 short opt\n"));
4591 if (pd2.proto == IPPROTO_AH)
4592 off2 += (opt6.ip6e_len + 2) * 4;
4594 off2 += (opt6.ip6e_len + 1) * 8;
4595 pd2.proto = opt6.ip6e_nxt;
4596 /* goto the next header */
4603 } while (!terminal);
4608 switch (pd2.proto) {
4612 struct pf_state_peer *src, *dst;
4617 * Only the first 8 bytes of the TCP header can be
4618 * expected. Don't access any TCP header fields after
4619 * th_seq, an ackskew test is not possible.
4621 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4623 DPFPRINTF(PF_DEBUG_MISC,
4624 ("pf: ICMP error message too short "
4630 key.proto = IPPROTO_TCP;
4631 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4632 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4633 key.port[pd2.sidx] = th.th_sport;
4634 key.port[pd2.didx] = th.th_dport;
4636 STATE_LOOKUP(kif, &key, direction, *state, pd);
4638 if (direction == (*state)->direction) {
4639 src = &(*state)->dst;
4640 dst = &(*state)->src;
4642 src = &(*state)->src;
4643 dst = &(*state)->dst;
4646 if (src->wscale && dst->wscale)
4647 dws = dst->wscale & PF_WSCALE_MASK;
4651 /* Demodulate sequence number */
4652 seq = ntohl(th.th_seq) - src->seqdiff;
4654 pf_change_a(&th.th_seq, icmpsum,
4659 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4660 (!SEQ_GEQ(src->seqhi, seq) ||
4661 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4662 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4663 printf("pf: BAD ICMP %d:%d ",
4664 icmptype, pd->hdr.icmp->icmp_code);
4665 pf_print_host(pd->src, 0, pd->af);
4667 pf_print_host(pd->dst, 0, pd->af);
4669 pf_print_state(*state);
4670 printf(" seq=%u\n", seq);
4672 REASON_SET(reason, PFRES_BADSTATE);
4675 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4676 printf("pf: OK ICMP %d:%d ",
4677 icmptype, pd->hdr.icmp->icmp_code);
4678 pf_print_host(pd->src, 0, pd->af);
4680 pf_print_host(pd->dst, 0, pd->af);
4682 pf_print_state(*state);
4683 printf(" seq=%u\n", seq);
4687 /* translate source/destination address, if necessary */
4688 if ((*state)->key[PF_SK_WIRE] !=
4689 (*state)->key[PF_SK_STACK]) {
4690 struct pf_state_key *nk =
4691 (*state)->key[pd->didx];
4693 if (PF_ANEQ(pd2.src,
4694 &nk->addr[pd2.sidx], pd2.af) ||
4695 nk->port[pd2.sidx] != th.th_sport)
4696 pf_change_icmp(pd2.src, &th.th_sport,
4697 daddr, &nk->addr[pd2.sidx],
4698 nk->port[pd2.sidx], NULL,
4699 pd2.ip_sum, icmpsum,
4700 pd->ip_sum, 0, pd2.af);
4702 if (PF_ANEQ(pd2.dst,
4703 &nk->addr[pd2.didx], pd2.af) ||
4704 nk->port[pd2.didx] != th.th_dport)
4705 pf_change_icmp(pd2.dst, &th.th_dport,
4706 NULL, /* XXX Inbound NAT? */
4707 &nk->addr[pd2.didx],
4708 nk->port[pd2.didx], NULL,
4709 pd2.ip_sum, icmpsum,
4710 pd->ip_sum, 0, pd2.af);
4718 m_copyback(m, off, ICMP_MINLEN,
4719 (caddr_t )pd->hdr.icmp);
4720 m_copyback(m, ipoff2, sizeof(h2),
4727 sizeof(struct icmp6_hdr),
4728 (caddr_t )pd->hdr.icmp6);
4729 m_copyback(m, ipoff2, sizeof(h2_6),
4734 m_copyback(m, off2, 8, (caddr_t)&th);
4743 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4744 NULL, reason, pd2.af)) {
4745 DPFPRINTF(PF_DEBUG_MISC,
4746 ("pf: ICMP error message too short "
4752 key.proto = IPPROTO_UDP;
4753 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4754 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4755 key.port[pd2.sidx] = uh.uh_sport;
4756 key.port[pd2.didx] = uh.uh_dport;
4758 STATE_LOOKUP(kif, &key, direction, *state, pd);
4760 /* translate source/destination address, if necessary */
4761 if ((*state)->key[PF_SK_WIRE] !=
4762 (*state)->key[PF_SK_STACK]) {
4763 struct pf_state_key *nk =
4764 (*state)->key[pd->didx];
4766 if (PF_ANEQ(pd2.src,
4767 &nk->addr[pd2.sidx], pd2.af) ||
4768 nk->port[pd2.sidx] != uh.uh_sport)
4769 pf_change_icmp(pd2.src, &uh.uh_sport,
4770 daddr, &nk->addr[pd2.sidx],
4771 nk->port[pd2.sidx], &uh.uh_sum,
4772 pd2.ip_sum, icmpsum,
4773 pd->ip_sum, 1, pd2.af);
4775 if (PF_ANEQ(pd2.dst,
4776 &nk->addr[pd2.didx], pd2.af) ||
4777 nk->port[pd2.didx] != uh.uh_dport)
4778 pf_change_icmp(pd2.dst, &uh.uh_dport,
4779 NULL, /* XXX Inbound NAT? */
4780 &nk->addr[pd2.didx],
4781 nk->port[pd2.didx], &uh.uh_sum,
4782 pd2.ip_sum, icmpsum,
4783 pd->ip_sum, 1, pd2.af);
4788 m_copyback(m, off, ICMP_MINLEN,
4789 (caddr_t )pd->hdr.icmp);
4790 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4796 sizeof(struct icmp6_hdr),
4797 (caddr_t )pd->hdr.icmp6);
4798 m_copyback(m, ipoff2, sizeof(h2_6),
4803 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4809 case IPPROTO_ICMP: {
4812 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4813 NULL, reason, pd2.af)) {
4814 DPFPRINTF(PF_DEBUG_MISC,
4815 ("pf: ICMP error message too short i"
4821 key.proto = IPPROTO_ICMP;
4822 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4823 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4824 key.port[0] = key.port[1] = iih.icmp_id;
4826 STATE_LOOKUP(kif, &key, direction, *state, pd);
4828 /* translate source/destination address, if necessary */
4829 if ((*state)->key[PF_SK_WIRE] !=
4830 (*state)->key[PF_SK_STACK]) {
4831 struct pf_state_key *nk =
4832 (*state)->key[pd->didx];
4834 if (PF_ANEQ(pd2.src,
4835 &nk->addr[pd2.sidx], pd2.af) ||
4836 nk->port[pd2.sidx] != iih.icmp_id)
4837 pf_change_icmp(pd2.src, &iih.icmp_id,
4838 daddr, &nk->addr[pd2.sidx],
4839 nk->port[pd2.sidx], NULL,
4840 pd2.ip_sum, icmpsum,
4841 pd->ip_sum, 0, AF_INET);
4843 if (PF_ANEQ(pd2.dst,
4844 &nk->addr[pd2.didx], pd2.af) ||
4845 nk->port[pd2.didx] != iih.icmp_id)
4846 pf_change_icmp(pd2.dst, &iih.icmp_id,
4847 NULL, /* XXX Inbound NAT? */
4848 &nk->addr[pd2.didx],
4849 nk->port[pd2.didx], NULL,
4850 pd2.ip_sum, icmpsum,
4851 pd->ip_sum, 0, AF_INET);
4853 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4854 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4855 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4862 case IPPROTO_ICMPV6: {
4863 struct icmp6_hdr iih;
4865 if (!pf_pull_hdr(m, off2, &iih,
4866 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4867 DPFPRINTF(PF_DEBUG_MISC,
4868 ("pf: ICMP error message too short "
4874 key.proto = IPPROTO_ICMPV6;
4875 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4876 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4877 key.port[0] = key.port[1] = iih.icmp6_id;
4879 STATE_LOOKUP(kif, &key, direction, *state, pd);
4881 /* translate source/destination address, if necessary */
4882 if ((*state)->key[PF_SK_WIRE] !=
4883 (*state)->key[PF_SK_STACK]) {
4884 struct pf_state_key *nk =
4885 (*state)->key[pd->didx];
4887 if (PF_ANEQ(pd2.src,
4888 &nk->addr[pd2.sidx], pd2.af) ||
4889 nk->port[pd2.sidx] != iih.icmp6_id)
4890 pf_change_icmp(pd2.src, &iih.icmp6_id,
4891 daddr, &nk->addr[pd2.sidx],
4892 nk->port[pd2.sidx], NULL,
4893 pd2.ip_sum, icmpsum,
4894 pd->ip_sum, 0, AF_INET6);
4896 if (PF_ANEQ(pd2.dst,
4897 &nk->addr[pd2.didx], pd2.af) ||
4898 nk->port[pd2.didx] != iih.icmp6_id)
4899 pf_change_icmp(pd2.dst, &iih.icmp6_id,
4900 NULL, /* XXX Inbound NAT? */
4901 &nk->addr[pd2.didx],
4902 nk->port[pd2.didx], NULL,
4903 pd2.ip_sum, icmpsum,
4904 pd->ip_sum, 0, AF_INET6);
4906 m_copyback(m, off, sizeof(struct icmp6_hdr),
4907 (caddr_t)pd->hdr.icmp6);
4908 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4909 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4918 key.proto = pd2.proto;
4919 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4920 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4921 key.port[0] = key.port[1] = 0;
4923 STATE_LOOKUP(kif, &key, direction, *state, pd);
4925 /* translate source/destination address, if necessary */
4926 if ((*state)->key[PF_SK_WIRE] !=
4927 (*state)->key[PF_SK_STACK]) {
4928 struct pf_state_key *nk =
4929 (*state)->key[pd->didx];
4931 if (PF_ANEQ(pd2.src,
4932 &nk->addr[pd2.sidx], pd2.af))
4933 pf_change_icmp(pd2.src, NULL, daddr,
4934 &nk->addr[pd2.sidx], 0, NULL,
4935 pd2.ip_sum, icmpsum,
4936 pd->ip_sum, 0, pd2.af);
4938 if (PF_ANEQ(pd2.dst,
4939 &nk->addr[pd2.didx], pd2.af))
4940 pf_change_icmp(pd2.src, NULL,
4941 NULL, /* XXX Inbound NAT? */
4942 &nk->addr[pd2.didx], 0, NULL,
4943 pd2.ip_sum, icmpsum,
4944 pd->ip_sum, 0, pd2.af);
4949 m_copyback(m, off, ICMP_MINLEN,
4950 (caddr_t)pd->hdr.icmp);
4951 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4957 sizeof(struct icmp6_hdr),
4958 (caddr_t )pd->hdr.icmp6);
4959 m_copyback(m, ipoff2, sizeof(h2_6),
4973 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
4974 struct mbuf *m, struct pf_pdesc *pd)
4976 struct pf_state_peer *src, *dst;
4977 struct pf_state_key_cmp key;
4979 bzero(&key, sizeof(key));
4981 key.proto = pd->proto;
4982 if (direction == PF_IN) {
4983 PF_ACPY(&key.addr[0], pd->src, key.af);
4984 PF_ACPY(&key.addr[1], pd->dst, key.af);
4985 key.port[0] = key.port[1] = 0;
4987 PF_ACPY(&key.addr[1], pd->src, key.af);
4988 PF_ACPY(&key.addr[0], pd->dst, key.af);
4989 key.port[1] = key.port[0] = 0;
4992 STATE_LOOKUP(kif, &key, direction, *state, pd);
4994 if (direction == (*state)->direction) {
4995 src = &(*state)->src;
4996 dst = &(*state)->dst;
4998 src = &(*state)->dst;
4999 dst = &(*state)->src;
5003 if (src->state < PFOTHERS_SINGLE)
5004 src->state = PFOTHERS_SINGLE;
5005 if (dst->state == PFOTHERS_SINGLE)
5006 dst->state = PFOTHERS_MULTIPLE;
5008 /* update expire time */
5009 (*state)->expire = time_uptime;
5010 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5011 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5013 (*state)->timeout = PFTM_OTHER_SINGLE;
5015 /* translate source/destination address, if necessary */
5016 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5017 struct pf_state_key *nk = (*state)->key[pd->didx];
5019 KASSERT(nk, ("%s: nk is null", __func__));
5020 KASSERT(pd, ("%s: pd is null", __func__));
5021 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5022 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5026 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5027 pf_change_a(&pd->src->v4.s_addr,
5029 nk->addr[pd->sidx].v4.s_addr,
5033 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5034 pf_change_a(&pd->dst->v4.s_addr,
5036 nk->addr[pd->didx].v4.s_addr,
5043 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5044 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5046 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5047 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5055 * ipoff and off are measured from the start of the mbuf chain.
5056 * h must be at "ipoff" on the mbuf chain.
5059 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5060 u_short *actionp, u_short *reasonp, sa_family_t af)
5065 struct ip *h = mtod(m, struct ip *);
5066 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5070 ACTION_SET(actionp, PF_PASS);
5072 ACTION_SET(actionp, PF_DROP);
5073 REASON_SET(reasonp, PFRES_FRAG);
5077 if (m->m_pkthdr.len < off + len ||
5078 ntohs(h->ip_len) < off + len) {
5079 ACTION_SET(actionp, PF_DROP);
5080 REASON_SET(reasonp, PFRES_SHORT);
5088 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5090 if (m->m_pkthdr.len < off + len ||
5091 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5092 (unsigned)(off + len)) {
5093 ACTION_SET(actionp, PF_DROP);
5094 REASON_SET(reasonp, PFRES_SHORT);
5101 m_copydata(m, off, len, p);
5106 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5110 struct radix_node_head *rnh;
5112 struct sockaddr_in *dst;
5116 struct sockaddr_in6 *dst6;
5117 struct route_in6 ro;
5121 struct radix_node *rn;
5127 /* XXX: stick to table 0 for now */
5128 rnh = rt_tables_get_rnh(0, af);
5129 if (rnh != NULL && rn_mpath_capable(rnh))
5132 bzero(&ro, sizeof(ro));
5135 dst = satosin(&ro.ro_dst);
5136 dst->sin_family = AF_INET;
5137 dst->sin_len = sizeof(*dst);
5138 dst->sin_addr = addr->v4;
5143 * Skip check for addresses with embedded interface scope,
5144 * as they would always match anyway.
5146 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5148 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5149 dst6->sin6_family = AF_INET6;
5150 dst6->sin6_len = sizeof(*dst6);
5151 dst6->sin6_addr = addr->v6;
5158 /* Skip checks for ipsec interfaces */
5159 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5165 in6_rtalloc_ign(&ro, 0, rtableid);
5170 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5174 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5178 if (ro.ro_rt != NULL) {
5179 /* No interface given, this is a no-route check */
5183 if (kif->pfik_ifp == NULL) {
5188 /* Perform uRPF check if passed input interface */
5190 rn = (struct radix_node *)ro.ro_rt;
5192 rt = (struct rtentry *)rn;
5195 if (kif->pfik_ifp == ifp)
5198 rn = rn_mpath_next(rn);
5200 } while (check_mpath == 1 && rn != NULL && ret == 0);
5204 if (ro.ro_rt != NULL)
5211 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5212 struct pf_state *s, struct pf_pdesc *pd)
5214 struct mbuf *m0, *m1;
5215 struct sockaddr_in dst;
5217 struct ifnet *ifp = NULL;
5218 struct pf_addr naddr;
5219 struct pf_src_node *sn = NULL;
5221 uint16_t ip_len, ip_off;
5223 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5224 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5227 if ((pd->pf_mtag == NULL &&
5228 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5229 pd->pf_mtag->routed++ > 3) {
5235 if (r->rt == PF_DUPTO) {
5236 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5242 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5250 ip = mtod(m0, struct ip *);
5252 bzero(&dst, sizeof(dst));
5253 dst.sin_family = AF_INET;
5254 dst.sin_len = sizeof(dst);
5255 dst.sin_addr = ip->ip_dst;
5257 if (r->rt == PF_FASTROUTE) {
5262 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5264 KMOD_IPSTAT_INC(ips_noroute);
5265 error = EHOSTUNREACH;
5270 counter_u64_add(rt->rt_pksent, 1);
5272 if (rt->rt_flags & RTF_GATEWAY)
5273 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5276 if (TAILQ_EMPTY(&r->rpool.list)) {
5277 DPFPRINTF(PF_DEBUG_URGENT,
5278 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5282 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5284 if (!PF_AZERO(&naddr, AF_INET))
5285 dst.sin_addr.s_addr = naddr.v4.s_addr;
5286 ifp = r->rpool.cur->kif ?
5287 r->rpool.cur->kif->pfik_ifp : NULL;
5289 if (!PF_AZERO(&s->rt_addr, AF_INET))
5290 dst.sin_addr.s_addr =
5291 s->rt_addr.v4.s_addr;
5292 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5300 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5302 else if (m0 == NULL)
5304 if (m0->m_len < sizeof(struct ip)) {
5305 DPFPRINTF(PF_DEBUG_URGENT,
5306 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5309 ip = mtod(m0, struct ip *);
5312 if (ifp->if_flags & IFF_LOOPBACK)
5313 m0->m_flags |= M_SKIP_FIREWALL;
5315 ip_len = ntohs(ip->ip_len);
5316 ip_off = ntohs(ip->ip_off);
5318 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5319 m0->m_pkthdr.csum_flags |= CSUM_IP;
5320 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5321 in_delayed_cksum(m0);
5322 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5325 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5326 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5327 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5332 * If small enough for interface, or the interface will take
5333 * care of the fragmentation for us, we can just send directly.
5335 if (ip_len <= ifp->if_mtu ||
5336 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5337 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5339 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5340 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5341 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5343 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5344 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5348 /* Balk when DF bit is set or the interface didn't support TSO. */
5349 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5351 KMOD_IPSTAT_INC(ips_cantfrag);
5352 if (r->rt != PF_DUPTO) {
5353 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5360 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5364 for (; m0; m0 = m1) {
5366 m0->m_nextpkt = NULL;
5368 m_clrprotoflags(m0);
5369 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5375 KMOD_IPSTAT_INC(ips_fragmented);
5378 if (r->rt != PF_DUPTO)
5393 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5394 struct pf_state *s, struct pf_pdesc *pd)
5397 struct sockaddr_in6 dst;
5398 struct ip6_hdr *ip6;
5399 struct ifnet *ifp = NULL;
5400 struct pf_addr naddr;
5401 struct pf_src_node *sn = NULL;
5403 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5404 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5407 if ((pd->pf_mtag == NULL &&
5408 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5409 pd->pf_mtag->routed++ > 3) {
5415 if (r->rt == PF_DUPTO) {
5416 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5422 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5430 ip6 = mtod(m0, struct ip6_hdr *);
5432 bzero(&dst, sizeof(dst));
5433 dst.sin6_family = AF_INET6;
5434 dst.sin6_len = sizeof(dst);
5435 dst.sin6_addr = ip6->ip6_dst;
5437 /* Cheat. XXX why only in the v6 case??? */
5438 if (r->rt == PF_FASTROUTE) {
5441 m0->m_flags |= M_SKIP_FIREWALL;
5442 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5446 if (TAILQ_EMPTY(&r->rpool.list)) {
5447 DPFPRINTF(PF_DEBUG_URGENT,
5448 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5452 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5454 if (!PF_AZERO(&naddr, AF_INET6))
5455 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5457 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5459 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5460 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5461 &s->rt_addr, AF_INET6);
5462 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5472 if (pf_test6(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5474 else if (m0 == NULL)
5476 if (m0->m_len < sizeof(struct ip6_hdr)) {
5477 DPFPRINTF(PF_DEBUG_URGENT,
5478 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5482 ip6 = mtod(m0, struct ip6_hdr *);
5485 if (ifp->if_flags & IFF_LOOPBACK)
5486 m0->m_flags |= M_SKIP_FIREWALL;
5489 * If the packet is too large for the outgoing interface,
5490 * send back an icmp6 error.
5492 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5493 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5494 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5495 nd6_output(ifp, ifp, m0, &dst, NULL);
5497 in6_ifstat_inc(ifp, ifs6_in_toobig);
5498 if (r->rt != PF_DUPTO)
5499 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5505 if (r->rt != PF_DUPTO)
5519 * FreeBSD supports cksum offloads for the following drivers.
5520 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5521 * ti(4), txp(4), xl(4)
5523 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5524 * network driver performed cksum including pseudo header, need to verify
5527 * network driver performed cksum, needs to additional pseudo header
5528 * cksum computation with partial csum_data(i.e. lack of H/W support for
5529 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5531 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5532 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5534 * Also, set csum_data to 0xffff to force cksum validation.
5537 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5543 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5545 if (m->m_pkthdr.len < off + len)
5550 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5551 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5552 sum = m->m_pkthdr.csum_data;
5554 ip = mtod(m, struct ip *);
5555 sum = in_pseudo(ip->ip_src.s_addr,
5556 ip->ip_dst.s_addr, htonl((u_short)len +
5557 m->m_pkthdr.csum_data + IPPROTO_TCP));
5564 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5565 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5566 sum = m->m_pkthdr.csum_data;
5568 ip = mtod(m, struct ip *);
5569 sum = in_pseudo(ip->ip_src.s_addr,
5570 ip->ip_dst.s_addr, htonl((u_short)len +
5571 m->m_pkthdr.csum_data + IPPROTO_UDP));
5579 case IPPROTO_ICMPV6:
5589 if (p == IPPROTO_ICMP) {
5594 sum = in_cksum(m, len);
5598 if (m->m_len < sizeof(struct ip))
5600 sum = in4_cksum(m, p, off, len);
5605 if (m->m_len < sizeof(struct ip6_hdr))
5607 sum = in6_cksum(m, p, off, len);
5618 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5623 KMOD_UDPSTAT_INC(udps_badsum);
5629 KMOD_ICMPSTAT_INC(icps_checksum);
5634 case IPPROTO_ICMPV6:
5636 KMOD_ICMP6STAT_INC(icp6s_checksum);
5643 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5644 m->m_pkthdr.csum_flags |=
5645 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5646 m->m_pkthdr.csum_data = 0xffff;
5655 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5657 struct pfi_kif *kif;
5658 u_short action, reason = 0, log = 0;
5659 struct mbuf *m = *m0;
5660 struct ip *h = NULL;
5661 struct m_tag *ipfwtag;
5662 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5663 struct pf_state *s = NULL;
5664 struct pf_ruleset *ruleset = NULL;
5666 int off, dirndx, pqid = 0;
5670 if (!V_pf_status.running)
5673 memset(&pd, 0, sizeof(pd));
5675 kif = (struct pfi_kif *)ifp->if_pf_kif;
5678 DPFPRINTF(PF_DEBUG_URGENT,
5679 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5682 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5685 if (m->m_flags & M_SKIP_FIREWALL)
5688 pd.pf_mtag = pf_find_mtag(m);
5692 if (ip_divert_ptr != NULL &&
5693 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5694 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5695 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5696 if (pd.pf_mtag == NULL &&
5697 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5701 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5702 m_tag_delete(m, ipfwtag);
5704 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5705 m->m_flags |= M_FASTFWD_OURS;
5706 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5708 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5709 /* We do IP header normalization and packet reassembly here */
5713 m = *m0; /* pf_normalize messes with m0 */
5714 h = mtod(m, struct ip *);
5716 off = h->ip_hl << 2;
5717 if (off < (int)sizeof(struct ip)) {
5719 REASON_SET(&reason, PFRES_SHORT);
5724 pd.src = (struct pf_addr *)&h->ip_src;
5725 pd.dst = (struct pf_addr *)&h->ip_dst;
5726 pd.sport = pd.dport = NULL;
5727 pd.ip_sum = &h->ip_sum;
5728 pd.proto_sum = NULL;
5731 pd.sidx = (dir == PF_IN) ? 0 : 1;
5732 pd.didx = (dir == PF_IN) ? 1 : 0;
5735 pd.tot_len = ntohs(h->ip_len);
5737 /* handle fragments that didn't get reassembled by normalization */
5738 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5739 action = pf_test_fragment(&r, dir, kif, m, h,
5750 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5751 &action, &reason, AF_INET)) {
5752 log = action != PF_PASS;
5755 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5756 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5758 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5759 if (action == PF_DROP)
5761 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5763 if (action == PF_PASS) {
5764 if (pfsync_update_state_ptr != NULL)
5765 pfsync_update_state_ptr(s);
5769 } else if (s == NULL)
5770 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5779 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5780 &action, &reason, AF_INET)) {
5781 log = action != PF_PASS;
5784 if (uh.uh_dport == 0 ||
5785 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5786 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5788 REASON_SET(&reason, PFRES_SHORT);
5791 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5792 if (action == PF_PASS) {
5793 if (pfsync_update_state_ptr != NULL)
5794 pfsync_update_state_ptr(s);
5798 } else if (s == NULL)
5799 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5804 case IPPROTO_ICMP: {
5808 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5809 &action, &reason, AF_INET)) {
5810 log = action != PF_PASS;
5813 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5815 if (action == PF_PASS) {
5816 if (pfsync_update_state_ptr != NULL)
5817 pfsync_update_state_ptr(s);
5821 } else if (s == NULL)
5822 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5828 case IPPROTO_ICMPV6: {
5830 DPFPRINTF(PF_DEBUG_MISC,
5831 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
5837 action = pf_test_state_other(&s, dir, kif, m, &pd);
5838 if (action == PF_PASS) {
5839 if (pfsync_update_state_ptr != NULL)
5840 pfsync_update_state_ptr(s);
5844 } else if (s == NULL)
5845 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
5852 if (action == PF_PASS && h->ip_hl > 5 &&
5853 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
5855 REASON_SET(&reason, PFRES_IPOPTIONS);
5857 DPFPRINTF(PF_DEBUG_MISC,
5858 ("pf: dropping packet with ip options\n"));
5861 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
5863 REASON_SET(&reason, PFRES_MEMORY);
5865 if (r->rtableid >= 0)
5866 M_SETFIB(m, r->rtableid);
5869 if (action == PF_PASS && r->qid) {
5870 if (pd.pf_mtag == NULL &&
5871 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5873 REASON_SET(&reason, PFRES_MEMORY);
5875 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5876 pd.pf_mtag->qid = r->pqid;
5878 pd.pf_mtag->qid = r->qid;
5879 /* add hints for ecn */
5880 pd.pf_mtag->hdr = h;
5886 * connections redirected to loopback should not match sockets
5887 * bound specifically to loopback due to security implications,
5888 * see tcp_input() and in_pcblookup_listen().
5890 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5891 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5892 (s->nat_rule.ptr->action == PF_RDR ||
5893 s->nat_rule.ptr->action == PF_BINAT) &&
5894 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5895 m->m_flags |= M_SKIP_FIREWALL;
5897 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
5898 !PACKET_LOOPED(&pd)) {
5900 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
5901 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
5902 if (ipfwtag != NULL) {
5903 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
5904 ntohs(r->divert.port);
5905 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
5910 m_tag_prepend(m, ipfwtag);
5911 if (m->m_flags & M_FASTFWD_OURS) {
5912 if (pd.pf_mtag == NULL &&
5913 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5915 REASON_SET(&reason, PFRES_MEMORY);
5917 DPFPRINTF(PF_DEBUG_MISC,
5918 ("pf: failed to allocate tag\n"));
5920 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
5921 m->m_flags &= ~M_FASTFWD_OURS;
5923 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
5928 /* XXX: ipfw has the same behaviour! */
5930 REASON_SET(&reason, PFRES_MEMORY);
5932 DPFPRINTF(PF_DEBUG_MISC,
5933 ("pf: failed to allocate divert tag\n"));
5940 if (s != NULL && s->nat_rule.ptr != NULL &&
5941 s->nat_rule.ptr->log & PF_LOG_ALL)
5942 lr = s->nat_rule.ptr;
5945 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
5949 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5950 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5952 if (action == PF_PASS || r->action == PF_DROP) {
5953 dirndx = (dir == PF_OUT);
5954 r->packets[dirndx]++;
5955 r->bytes[dirndx] += pd.tot_len;
5957 a->packets[dirndx]++;
5958 a->bytes[dirndx] += pd.tot_len;
5961 if (s->nat_rule.ptr != NULL) {
5962 s->nat_rule.ptr->packets[dirndx]++;
5963 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
5965 if (s->src_node != NULL) {
5966 s->src_node->packets[dirndx]++;
5967 s->src_node->bytes[dirndx] += pd.tot_len;
5969 if (s->nat_src_node != NULL) {
5970 s->nat_src_node->packets[dirndx]++;
5971 s->nat_src_node->bytes[dirndx] += pd.tot_len;
5973 dirndx = (dir == s->direction) ? 0 : 1;
5974 s->packets[dirndx]++;
5975 s->bytes[dirndx] += pd.tot_len;
5978 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
5979 if (nr != NULL && r == &V_pf_default_rule)
5981 if (tr->src.addr.type == PF_ADDR_TABLE)
5982 pfr_update_stats(tr->src.addr.p.tbl,
5983 (s == NULL) ? pd.src :
5984 &s->key[(s->direction == PF_IN)]->
5985 addr[(s->direction == PF_OUT)],
5986 pd.af, pd.tot_len, dir == PF_OUT,
5987 r->action == PF_PASS, tr->src.neg);
5988 if (tr->dst.addr.type == PF_ADDR_TABLE)
5989 pfr_update_stats(tr->dst.addr.p.tbl,
5990 (s == NULL) ? pd.dst :
5991 &s->key[(s->direction == PF_IN)]->
5992 addr[(s->direction == PF_IN)],
5993 pd.af, pd.tot_len, dir == PF_OUT,
5994 r->action == PF_PASS, tr->dst.neg);
5998 case PF_SYNPROXY_DROP:
6009 /* pf_route() returns unlocked. */
6011 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6025 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6027 struct pfi_kif *kif;
6028 u_short action, reason = 0, log = 0;
6029 struct mbuf *m = *m0, *n = NULL;
6030 struct ip6_hdr *h = NULL;
6031 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6032 struct pf_state *s = NULL;
6033 struct pf_ruleset *ruleset = NULL;
6035 int off, terminal = 0, dirndx, rh_cnt = 0;
6039 if (!V_pf_status.running)
6042 memset(&pd, 0, sizeof(pd));
6043 pd.pf_mtag = pf_find_mtag(m);
6045 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6048 kif = (struct pfi_kif *)ifp->if_pf_kif;
6050 DPFPRINTF(PF_DEBUG_URGENT,
6051 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6054 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6057 if (m->m_flags & M_SKIP_FIREWALL)
6062 /* We do IP header normalization and packet reassembly here */
6063 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6067 m = *m0; /* pf_normalize messes with m0 */
6068 h = mtod(m, struct ip6_hdr *);
6072 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6073 * will do something bad, so drop the packet for now.
6075 if (htons(h->ip6_plen) == 0) {
6077 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6082 pd.src = (struct pf_addr *)&h->ip6_src;
6083 pd.dst = (struct pf_addr *)&h->ip6_dst;
6084 pd.sport = pd.dport = NULL;
6086 pd.proto_sum = NULL;
6088 pd.sidx = (dir == PF_IN) ? 0 : 1;
6089 pd.didx = (dir == PF_IN) ? 1 : 0;
6092 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6094 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6095 pd.proto = h->ip6_nxt;
6098 case IPPROTO_FRAGMENT:
6099 action = pf_test_fragment(&r, dir, kif, m, h,
6101 if (action == PF_DROP)
6102 REASON_SET(&reason, PFRES_FRAG);
6104 case IPPROTO_ROUTING: {
6105 struct ip6_rthdr rthdr;
6108 DPFPRINTF(PF_DEBUG_MISC,
6109 ("pf: IPv6 more than one rthdr\n"));
6111 REASON_SET(&reason, PFRES_IPOPTIONS);
6115 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6117 DPFPRINTF(PF_DEBUG_MISC,
6118 ("pf: IPv6 short rthdr\n"));
6120 REASON_SET(&reason, PFRES_SHORT);
6124 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6125 DPFPRINTF(PF_DEBUG_MISC,
6126 ("pf: IPv6 rthdr0\n"));
6128 REASON_SET(&reason, PFRES_IPOPTIONS);
6135 case IPPROTO_HOPOPTS:
6136 case IPPROTO_DSTOPTS: {
6137 /* get next header and header length */
6138 struct ip6_ext opt6;
6140 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6141 NULL, &reason, pd.af)) {
6142 DPFPRINTF(PF_DEBUG_MISC,
6143 ("pf: IPv6 short opt\n"));
6148 if (pd.proto == IPPROTO_AH)
6149 off += (opt6.ip6e_len + 2) * 4;
6151 off += (opt6.ip6e_len + 1) * 8;
6152 pd.proto = opt6.ip6e_nxt;
6153 /* goto the next header */
6160 } while (!terminal);
6162 /* if there's no routing header, use unmodified mbuf for checksumming */
6172 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6173 &action, &reason, AF_INET6)) {
6174 log = action != PF_PASS;
6177 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6178 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6179 if (action == PF_DROP)
6181 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6183 if (action == PF_PASS) {
6184 if (pfsync_update_state_ptr != NULL)
6185 pfsync_update_state_ptr(s);
6189 } else if (s == NULL)
6190 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6199 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6200 &action, &reason, AF_INET6)) {
6201 log = action != PF_PASS;
6204 if (uh.uh_dport == 0 ||
6205 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6206 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6208 REASON_SET(&reason, PFRES_SHORT);
6211 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6212 if (action == PF_PASS) {
6213 if (pfsync_update_state_ptr != NULL)
6214 pfsync_update_state_ptr(s);
6218 } else if (s == NULL)
6219 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6224 case IPPROTO_ICMP: {
6226 DPFPRINTF(PF_DEBUG_MISC,
6227 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6231 case IPPROTO_ICMPV6: {
6232 struct icmp6_hdr ih;
6235 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6236 &action, &reason, AF_INET6)) {
6237 log = action != PF_PASS;
6240 action = pf_test_state_icmp(&s, dir, kif,
6241 m, off, h, &pd, &reason);
6242 if (action == PF_PASS) {
6243 if (pfsync_update_state_ptr != NULL)
6244 pfsync_update_state_ptr(s);
6248 } else if (s == NULL)
6249 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6255 action = pf_test_state_other(&s, dir, kif, m, &pd);
6256 if (action == PF_PASS) {
6257 if (pfsync_update_state_ptr != NULL)
6258 pfsync_update_state_ptr(s);
6262 } else if (s == NULL)
6263 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6275 /* handle dangerous IPv6 extension headers. */
6276 if (action == PF_PASS && rh_cnt &&
6277 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6279 REASON_SET(&reason, PFRES_IPOPTIONS);
6281 DPFPRINTF(PF_DEBUG_MISC,
6282 ("pf: dropping packet with dangerous v6 headers\n"));
6285 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6287 REASON_SET(&reason, PFRES_MEMORY);
6289 if (r->rtableid >= 0)
6290 M_SETFIB(m, r->rtableid);
6293 if (action == PF_PASS && r->qid) {
6294 if (pd.pf_mtag == NULL &&
6295 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6297 REASON_SET(&reason, PFRES_MEMORY);
6299 if (pd.tos & IPTOS_LOWDELAY)
6300 pd.pf_mtag->qid = r->pqid;
6302 pd.pf_mtag->qid = r->qid;
6303 /* add hints for ecn */
6304 pd.pf_mtag->hdr = h;
6308 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6309 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6310 (s->nat_rule.ptr->action == PF_RDR ||
6311 s->nat_rule.ptr->action == PF_BINAT) &&
6312 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6313 m->m_flags |= M_SKIP_FIREWALL;
6315 /* XXX: Anybody working on it?! */
6317 printf("pf: divert(9) is not supported for IPv6\n");
6322 if (s != NULL && s->nat_rule.ptr != NULL &&
6323 s->nat_rule.ptr->log & PF_LOG_ALL)
6324 lr = s->nat_rule.ptr;
6327 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6331 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6332 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6334 if (action == PF_PASS || r->action == PF_DROP) {
6335 dirndx = (dir == PF_OUT);
6336 r->packets[dirndx]++;
6337 r->bytes[dirndx] += pd.tot_len;
6339 a->packets[dirndx]++;
6340 a->bytes[dirndx] += pd.tot_len;
6343 if (s->nat_rule.ptr != NULL) {
6344 s->nat_rule.ptr->packets[dirndx]++;
6345 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6347 if (s->src_node != NULL) {
6348 s->src_node->packets[dirndx]++;
6349 s->src_node->bytes[dirndx] += pd.tot_len;
6351 if (s->nat_src_node != NULL) {
6352 s->nat_src_node->packets[dirndx]++;
6353 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6355 dirndx = (dir == s->direction) ? 0 : 1;
6356 s->packets[dirndx]++;
6357 s->bytes[dirndx] += pd.tot_len;
6360 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6361 if (nr != NULL && r == &V_pf_default_rule)
6363 if (tr->src.addr.type == PF_ADDR_TABLE)
6364 pfr_update_stats(tr->src.addr.p.tbl,
6365 (s == NULL) ? pd.src :
6366 &s->key[(s->direction == PF_IN)]->addr[0],
6367 pd.af, pd.tot_len, dir == PF_OUT,
6368 r->action == PF_PASS, tr->src.neg);
6369 if (tr->dst.addr.type == PF_ADDR_TABLE)
6370 pfr_update_stats(tr->dst.addr.p.tbl,
6371 (s == NULL) ? pd.dst :
6372 &s->key[(s->direction == PF_IN)]->addr[1],
6373 pd.af, pd.tot_len, dir == PF_OUT,
6374 r->action == PF_PASS, tr->dst.neg);
6378 case PF_SYNPROXY_DROP:
6389 /* pf_route6() returns unlocked. */
6391 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);