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_status, 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 static VNET_DEFINE(uma_zone_t, pf_mtag_z);
190 #define V_pf_mtag_z VNET(pf_mtag_z)
191 VNET_DEFINE(uma_zone_t, pf_state_z);
192 VNET_DEFINE(uma_zone_t, pf_state_key_z);
194 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
195 #define PFID_CPUBITS 8
196 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
197 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
198 #define PFID_MAXID (~PFID_CPUMASK)
199 CTASSERT((1 << PFID_CPUBITS) > MAXCPU);
201 static void pf_src_tree_remove_state(struct pf_state *);
202 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
204 static void pf_add_threshold(struct pf_threshold *);
205 static int pf_check_threshold(struct pf_threshold *);
207 static void pf_change_ap(struct pf_addr *, u_int16_t *,
208 u_int16_t *, u_int16_t *, struct pf_addr *,
209 u_int16_t, u_int8_t, sa_family_t);
210 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
211 struct tcphdr *, struct pf_state_peer *);
212 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
213 struct pf_addr *, struct pf_addr *, u_int16_t,
214 u_int16_t *, u_int16_t *, u_int16_t *,
215 u_int16_t *, u_int8_t, sa_family_t);
216 static void pf_send_tcp(struct mbuf *,
217 const struct pf_rule *, sa_family_t,
218 const struct pf_addr *, const struct pf_addr *,
219 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
220 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
221 u_int16_t, struct ifnet *);
222 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
223 sa_family_t, struct pf_rule *);
224 static void pf_detach_state(struct pf_state *);
225 static int pf_state_key_attach(struct pf_state_key *,
226 struct pf_state_key *, struct pf_state *);
227 static void pf_state_key_detach(struct pf_state *, int);
228 static int pf_state_key_ctor(void *, int, void *, int);
229 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
230 static int pf_test_rule(struct pf_rule **, struct pf_state **,
231 int, struct pfi_kif *, struct mbuf *, int,
232 struct pf_pdesc *, struct pf_rule **,
233 struct pf_ruleset **, struct inpcb *);
234 static int pf_create_state(struct pf_rule *, struct pf_rule *,
235 struct pf_rule *, struct pf_pdesc *,
236 struct pf_src_node *, struct pf_state_key *,
237 struct pf_state_key *, struct mbuf *, int,
238 u_int16_t, u_int16_t, int *, struct pfi_kif *,
239 struct pf_state **, int, u_int16_t, u_int16_t,
241 static int pf_test_fragment(struct pf_rule **, int,
242 struct pfi_kif *, struct mbuf *, void *,
243 struct pf_pdesc *, struct pf_rule **,
244 struct pf_ruleset **);
245 static int pf_tcp_track_full(struct pf_state_peer *,
246 struct pf_state_peer *, struct pf_state **,
247 struct pfi_kif *, struct mbuf *, int,
248 struct pf_pdesc *, u_short *, int *);
249 static int pf_tcp_track_sloppy(struct pf_state_peer *,
250 struct pf_state_peer *, struct pf_state **,
251 struct pf_pdesc *, u_short *);
252 static int pf_test_state_tcp(struct pf_state **, int,
253 struct pfi_kif *, struct mbuf *, int,
254 void *, struct pf_pdesc *, u_short *);
255 static int pf_test_state_udp(struct pf_state **, int,
256 struct pfi_kif *, struct mbuf *, int,
257 void *, struct pf_pdesc *);
258 static int pf_test_state_icmp(struct pf_state **, int,
259 struct pfi_kif *, struct mbuf *, int,
260 void *, struct pf_pdesc *, u_short *);
261 static int pf_test_state_other(struct pf_state **, int,
262 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
263 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
265 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
267 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
269 static void pf_set_rt_ifp(struct pf_state *,
271 static int pf_check_proto_cksum(struct mbuf *, int, int,
272 u_int8_t, sa_family_t);
273 static void pf_print_state_parts(struct pf_state *,
274 struct pf_state_key *, struct pf_state_key *);
275 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
276 struct pf_addr_wrap *);
277 static struct pf_state *pf_find_state(struct pfi_kif *,
278 struct pf_state_key_cmp *, u_int);
279 static int pf_src_connlimit(struct pf_state **);
280 static void pf_overload_task(void *c, int pending);
281 static int pf_insert_src_node(struct pf_src_node **,
282 struct pf_rule *, struct pf_addr *, sa_family_t);
283 static u_int pf_purge_expired_states(u_int, int);
284 static void pf_purge_unlinked_rules(void);
285 static int pf_mtag_init(void *, int, int);
286 static void pf_mtag_free(struct m_tag *);
288 static void pf_route(struct mbuf **, struct pf_rule *, int,
289 struct ifnet *, struct pf_state *,
293 static void pf_change_a6(struct pf_addr *, u_int16_t *,
294 struct pf_addr *, u_int8_t);
295 static void pf_route6(struct mbuf **, struct pf_rule *, int,
296 struct ifnet *, struct pf_state *,
300 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
302 VNET_DECLARE(int, pf_end_threads);
304 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
306 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
307 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
309 #define STATE_LOOKUP(i, k, d, s, pd) \
311 (s) = pf_find_state((i), (k), (d)); \
314 if (PACKET_LOOPED(pd)) \
316 if ((d) == PF_OUT && \
317 (((s)->rule.ptr->rt == PF_ROUTETO && \
318 (s)->rule.ptr->direction == PF_OUT) || \
319 ((s)->rule.ptr->rt == PF_REPLYTO && \
320 (s)->rule.ptr->direction == PF_IN)) && \
321 (s)->rt_kif != NULL && \
322 (s)->rt_kif != (i)) \
326 #define BOUND_IFACE(r, k) \
327 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
329 #define STATE_INC_COUNTERS(s) \
331 counter_u64_add(s->rule.ptr->states_cur, 1); \
332 counter_u64_add(s->rule.ptr->states_tot, 1); \
333 if (s->anchor.ptr != NULL) { \
334 counter_u64_add(s->anchor.ptr->states_cur, 1); \
335 counter_u64_add(s->anchor.ptr->states_tot, 1); \
337 if (s->nat_rule.ptr != NULL) { \
338 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
339 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
343 #define STATE_DEC_COUNTERS(s) \
345 if (s->nat_rule.ptr != NULL) \
346 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
347 if (s->anchor.ptr != NULL) \
348 counter_u64_add(s->anchor.ptr->states_cur, -1); \
349 counter_u64_add(s->rule.ptr->states_cur, -1); \
352 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
353 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
354 VNET_DEFINE(struct pf_idhash *, pf_idhash);
355 VNET_DEFINE(u_long, pf_hashmask);
356 VNET_DEFINE(struct pf_srchash *, pf_srchash);
357 VNET_DEFINE(u_long, pf_srchashmask);
359 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
361 VNET_DEFINE(u_long, pf_hashsize);
362 #define V_pf_hashsize VNET(pf_hashsize)
363 SYSCTL_VNET_UINT(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
364 &VNET_NAME(pf_hashsize), 0, "Size of pf(4) states hashtable");
366 VNET_DEFINE(u_long, pf_srchashsize);
367 #define V_pf_srchashsize VNET(pf_srchashsize)
368 SYSCTL_VNET_UINT(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
369 &VNET_NAME(pf_srchashsize), 0, "Size of pf(4) source nodes hashtable");
371 VNET_DEFINE(void *, pf_swi_cookie);
373 VNET_DEFINE(uint32_t, pf_hashseed);
374 #define V_pf_hashseed VNET(pf_hashseed)
376 static __inline uint32_t
377 pf_hashkey(struct pf_state_key *sk)
381 h = jenkins_hash32((uint32_t *)sk,
382 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
385 return (h & V_pf_hashmask);
388 static __inline uint32_t
389 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
395 h = jenkins_hash32((uint32_t *)&addr->v4,
396 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
399 h = jenkins_hash32((uint32_t *)&addr->v6,
400 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
403 panic("%s: unknown address family %u", __func__, af);
406 return (h & V_pf_srchashmask);
411 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
416 dst->addr32[0] = src->addr32[0];
420 dst->addr32[0] = src->addr32[0];
421 dst->addr32[1] = src->addr32[1];
422 dst->addr32[2] = src->addr32[2];
423 dst->addr32[3] = src->addr32[3];
430 pf_init_threshold(struct pf_threshold *threshold,
431 u_int32_t limit, u_int32_t seconds)
433 threshold->limit = limit * PF_THRESHOLD_MULT;
434 threshold->seconds = seconds;
435 threshold->count = 0;
436 threshold->last = time_uptime;
440 pf_add_threshold(struct pf_threshold *threshold)
442 u_int32_t t = time_uptime, diff = t - threshold->last;
444 if (diff >= threshold->seconds)
445 threshold->count = 0;
447 threshold->count -= threshold->count * diff /
449 threshold->count += PF_THRESHOLD_MULT;
454 pf_check_threshold(struct pf_threshold *threshold)
456 return (threshold->count > threshold->limit);
460 pf_src_connlimit(struct pf_state **state)
462 struct pf_overload_entry *pfoe;
465 PF_STATE_LOCK_ASSERT(*state);
467 (*state)->src_node->conn++;
468 (*state)->src.tcp_est = 1;
469 pf_add_threshold(&(*state)->src_node->conn_rate);
471 if ((*state)->rule.ptr->max_src_conn &&
472 (*state)->rule.ptr->max_src_conn <
473 (*state)->src_node->conn) {
474 V_pf_status.lcounters[LCNT_SRCCONN]++;
478 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
479 pf_check_threshold(&(*state)->src_node->conn_rate)) {
480 V_pf_status.lcounters[LCNT_SRCCONNRATE]++;
487 /* Kill this state. */
488 (*state)->timeout = PFTM_PURGE;
489 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
491 if ((*state)->rule.ptr->overload_tbl == NULL)
494 /* Schedule overloading and flushing task. */
495 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
497 return (1); /* too bad :( */
499 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
500 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
501 pfoe->rule = (*state)->rule.ptr;
502 pfoe->dir = (*state)->direction;
504 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
505 PF_OVERLOADQ_UNLOCK();
506 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
512 pf_overload_task(void *c, int pending)
514 struct pf_overload_head queue;
516 struct pf_overload_entry *pfoe, *pfoe1;
520 queue = *(struct pf_overload_head *)c;
521 SLIST_INIT((struct pf_overload_head *)c);
522 PF_OVERLOADQ_UNLOCK();
524 bzero(&p, sizeof(p));
525 SLIST_FOREACH(pfoe, &queue, next) {
526 V_pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
527 if (V_pf_status.debug >= PF_DEBUG_MISC) {
528 printf("%s: blocking address ", __func__);
529 pf_print_host(&pfoe->addr, 0, pfoe->af);
533 p.pfra_af = pfoe->af;
538 p.pfra_ip4addr = pfoe->addr.v4;
544 p.pfra_ip6addr = pfoe->addr.v6;
550 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
555 * Remove those entries, that don't need flushing.
557 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
558 if (pfoe->rule->flush == 0) {
559 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
560 free(pfoe, M_PFTEMP);
562 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
564 /* If nothing to flush, return. */
565 if (SLIST_EMPTY(&queue))
568 for (int i = 0; i <= V_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);
598 * Can return locked on failure, so that we can consistently
599 * allocate and insert a new one.
602 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
605 struct pf_srchash *sh;
606 struct pf_src_node *n;
608 V_pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
610 sh = &V_pf_srchash[pf_hashsrc(src, af)];
612 LIST_FOREACH(n, &sh->nodes, entry)
613 if (n->rule.ptr == rule && n->af == af &&
614 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
615 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
617 if (n != NULL || returnlocked == 0)
618 PF_HASHROW_UNLOCK(sh);
624 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
625 struct pf_addr *src, sa_family_t af)
628 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
629 rule->rpool.opts & PF_POOL_STICKYADDR),
630 ("%s for non-tracking rule %p", __func__, rule));
633 *sn = pf_find_src_node(src, rule, af, 1);
636 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
638 PF_HASHROW_ASSERT(sh);
640 if (!rule->max_src_nodes ||
641 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
642 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
644 V_pf_status.lcounters[LCNT_SRCNODES]++;
646 PF_HASHROW_UNLOCK(sh);
650 pf_init_threshold(&(*sn)->conn_rate,
651 rule->max_src_conn_rate.limit,
652 rule->max_src_conn_rate.seconds);
655 (*sn)->rule.ptr = rule;
656 PF_ACPY(&(*sn)->addr, src, af);
657 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
658 (*sn)->creation = time_uptime;
659 (*sn)->ruletype = rule->action;
660 if ((*sn)->rule.ptr != NULL)
661 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
662 PF_HASHROW_UNLOCK(sh);
663 V_pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
664 V_pf_status.src_nodes++;
666 if (rule->max_src_states &&
667 (*sn)->states >= rule->max_src_states) {
668 V_pf_status.lcounters[LCNT_SRCSTATES]++;
676 pf_unlink_src_node_locked(struct pf_src_node *src)
679 struct pf_srchash *sh;
681 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
682 PF_HASHROW_ASSERT(sh);
684 LIST_REMOVE(src, entry);
686 counter_u64_add(src->rule.ptr->src_nodes, -1);
687 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
688 V_pf_status.src_nodes--;
692 pf_unlink_src_node(struct pf_src_node *src)
694 struct pf_srchash *sh;
696 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
698 pf_unlink_src_node_locked(src);
699 PF_HASHROW_UNLOCK(sh);
703 pf_free_src_node(struct pf_src_node *sn)
706 KASSERT(sn->states == 0, ("%s: %p has refs", __func__, sn));
707 uma_zfree(V_pf_sources_z, sn);
711 pf_free_src_nodes(struct pf_src_node_list *head)
713 struct pf_src_node *sn, *tmp;
716 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
717 pf_free_src_node(sn);
724 /* Data storage structures initialization. */
728 struct pf_keyhash *kh;
729 struct pf_idhash *ih;
730 struct pf_srchash *sh;
733 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &V_pf_hashsize);
734 if (V_pf_hashsize == 0 || !powerof2(V_pf_hashsize))
735 V_pf_hashsize = PF_HASHSIZ;
736 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &V_pf_srchashsize);
737 if (V_pf_srchashsize == 0 || !powerof2(V_pf_srchashsize))
738 V_pf_srchashsize = PF_HASHSIZ / 4;
740 V_pf_hashseed = arc4random();
742 /* States and state keys storage. */
743 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
744 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
745 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
746 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
747 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
749 V_pf_state_key_z = uma_zcreate("pf state keys",
750 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
752 V_pf_keyhash = malloc(V_pf_hashsize * sizeof(struct pf_keyhash),
753 M_PFHASH, M_WAITOK | M_ZERO);
754 V_pf_idhash = malloc(V_pf_hashsize * sizeof(struct pf_idhash),
755 M_PFHASH, M_WAITOK | M_ZERO);
756 V_pf_hashmask = V_pf_hashsize - 1;
757 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
759 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
760 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
764 V_pf_sources_z = uma_zcreate("pf source nodes",
765 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
767 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
768 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
769 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
770 V_pf_srchash = malloc(V_pf_srchashsize * sizeof(struct pf_srchash),
771 M_PFHASH, M_WAITOK|M_ZERO);
772 V_pf_srchashmask = V_pf_srchashsize - 1;
773 for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++)
774 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
777 TAILQ_INIT(&V_pf_altqs[0]);
778 TAILQ_INIT(&V_pf_altqs[1]);
779 TAILQ_INIT(&V_pf_pabuf);
780 V_pf_altqs_active = &V_pf_altqs[0];
781 V_pf_altqs_inactive = &V_pf_altqs[1];
784 V_pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
785 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_init, NULL,
788 /* Send & overload+flush queues. */
789 STAILQ_INIT(&V_pf_sendqueue);
790 SLIST_INIT(&V_pf_overloadqueue);
791 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, &V_pf_overloadqueue);
792 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
793 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
796 /* Unlinked, but may be referenced rules. */
797 TAILQ_INIT(&V_pf_unlinked_rules);
798 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
804 struct pf_keyhash *kh;
805 struct pf_idhash *ih;
806 struct pf_srchash *sh;
807 struct pf_send_entry *pfse, *next;
810 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= V_pf_hashmask;
812 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
814 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
816 mtx_destroy(&kh->lock);
817 mtx_destroy(&ih->lock);
819 free(V_pf_keyhash, M_PFHASH);
820 free(V_pf_idhash, M_PFHASH);
822 for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
823 KASSERT(LIST_EMPTY(&sh->nodes),
824 ("%s: source node hash not empty", __func__));
825 mtx_destroy(&sh->lock);
827 free(V_pf_srchash, M_PFHASH);
829 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
830 m_freem(pfse->pfse_m);
831 free(pfse, M_PFTEMP);
834 mtx_destroy(&pf_sendqueue_mtx);
835 mtx_destroy(&pf_overloadqueue_mtx);
836 mtx_destroy(&pf_unlnkdrules_mtx);
838 uma_zdestroy(V_pf_mtag_z);
839 uma_zdestroy(V_pf_sources_z);
840 uma_zdestroy(V_pf_state_z);
841 uma_zdestroy(V_pf_state_key_z);
845 pf_mtag_init(void *mem, int size, int how)
849 t = (struct m_tag *)mem;
850 t->m_tag_cookie = MTAG_ABI_COMPAT;
851 t->m_tag_id = PACKET_TAG_PF;
852 t->m_tag_len = sizeof(struct pf_mtag);
853 t->m_tag_free = pf_mtag_free;
859 pf_mtag_free(struct m_tag *t)
862 uma_zfree(V_pf_mtag_z, t);
866 pf_get_mtag(struct mbuf *m)
870 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
871 return ((struct pf_mtag *)(mtag + 1));
873 mtag = uma_zalloc(V_pf_mtag_z, M_NOWAIT);
876 bzero(mtag + 1, sizeof(struct pf_mtag));
877 m_tag_prepend(m, mtag);
879 return ((struct pf_mtag *)(mtag + 1));
883 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
886 struct pf_keyhash *khs, *khw, *kh;
887 struct pf_state_key *sk, *cur;
888 struct pf_state *si, *olds = NULL;
891 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
892 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
893 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
896 * We need to lock hash slots of both keys. To avoid deadlock
897 * we always lock the slot with lower address first. Unlock order
900 * We also need to lock ID hash slot before dropping key
901 * locks. On success we return with ID hash slot locked.
905 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
906 PF_HASHROW_LOCK(khs);
908 khs = &V_pf_keyhash[pf_hashkey(sks)];
909 khw = &V_pf_keyhash[pf_hashkey(skw)];
911 PF_HASHROW_LOCK(khs);
912 } else if (khs < khw) {
913 PF_HASHROW_LOCK(khs);
914 PF_HASHROW_LOCK(khw);
916 PF_HASHROW_LOCK(khw);
917 PF_HASHROW_LOCK(khs);
921 #define KEYS_UNLOCK() do { \
923 PF_HASHROW_UNLOCK(khs); \
924 PF_HASHROW_UNLOCK(khw); \
926 PF_HASHROW_UNLOCK(khs); \
930 * First run: start with wire key.
937 LIST_FOREACH(cur, &kh->keys, entry)
938 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
942 /* Key exists. Check for same kif, if none, add to key. */
943 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
944 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
947 if (si->kif == s->kif &&
948 si->direction == s->direction) {
949 if (sk->proto == IPPROTO_TCP &&
950 si->src.state >= TCPS_FIN_WAIT_2 &&
951 si->dst.state >= TCPS_FIN_WAIT_2) {
953 * New state matches an old >FIN_WAIT_2
954 * state. We can't drop key hash locks,
955 * thus we can't unlink it properly.
957 * As a workaround we drop it into
958 * TCPS_CLOSED state, schedule purge
959 * ASAP and push it into the very end
960 * of the slot TAILQ, so that it won't
961 * conflict with our new state.
963 si->src.state = si->dst.state =
965 si->timeout = PFTM_PURGE;
968 if (V_pf_status.debug >= PF_DEBUG_MISC) {
969 printf("pf: %s key attach "
971 (idx == PF_SK_WIRE) ?
974 pf_print_state_parts(s,
975 (idx == PF_SK_WIRE) ?
977 (idx == PF_SK_STACK) ?
979 printf(", existing: ");
980 pf_print_state_parts(si,
981 (idx == PF_SK_WIRE) ?
983 (idx == PF_SK_STACK) ?
987 PF_HASHROW_UNLOCK(ih);
989 uma_zfree(V_pf_state_key_z, sk);
990 if (idx == PF_SK_STACK)
992 return (EEXIST); /* collision! */
995 PF_HASHROW_UNLOCK(ih);
997 uma_zfree(V_pf_state_key_z, sk);
1000 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1005 /* List is sorted, if-bound states before floating. */
1006 if (s->kif == V_pfi_all)
1007 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1009 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1012 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1013 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1019 * Attach done. See how should we (or should not?)
1020 * attach a second key.
1023 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1027 } else if (sks != NULL) {
1029 * Continue attaching with stack key.
1041 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1042 ("%s failure", __func__));
1049 pf_detach_state(struct pf_state *s)
1051 struct pf_state_key *sks = s->key[PF_SK_STACK];
1052 struct pf_keyhash *kh;
1055 kh = &V_pf_keyhash[pf_hashkey(sks)];
1056 PF_HASHROW_LOCK(kh);
1057 if (s->key[PF_SK_STACK] != NULL)
1058 pf_state_key_detach(s, PF_SK_STACK);
1060 * If both point to same key, then we are done.
1062 if (sks == s->key[PF_SK_WIRE]) {
1063 pf_state_key_detach(s, PF_SK_WIRE);
1064 PF_HASHROW_UNLOCK(kh);
1067 PF_HASHROW_UNLOCK(kh);
1070 if (s->key[PF_SK_WIRE] != NULL) {
1071 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1072 PF_HASHROW_LOCK(kh);
1073 if (s->key[PF_SK_WIRE] != NULL)
1074 pf_state_key_detach(s, PF_SK_WIRE);
1075 PF_HASHROW_UNLOCK(kh);
1080 pf_state_key_detach(struct pf_state *s, int idx)
1082 struct pf_state_key *sk = s->key[idx];
1084 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1086 PF_HASHROW_ASSERT(kh);
1088 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1091 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1092 LIST_REMOVE(sk, entry);
1093 uma_zfree(V_pf_state_key_z, sk);
1098 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1100 struct pf_state_key *sk = mem;
1102 bzero(sk, sizeof(struct pf_state_key_cmp));
1103 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1104 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1109 struct pf_state_key *
1110 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1111 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1113 struct pf_state_key *sk;
1115 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1119 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1120 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1121 sk->port[pd->sidx] = sport;
1122 sk->port[pd->didx] = dport;
1123 sk->proto = pd->proto;
1129 struct pf_state_key *
1130 pf_state_key_clone(struct pf_state_key *orig)
1132 struct pf_state_key *sk;
1134 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1138 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1144 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1145 struct pf_state_key *sks, struct pf_state *s)
1147 struct pf_idhash *ih;
1148 struct pf_state *cur;
1151 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1152 ("%s: sks not pristine", __func__));
1153 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1154 ("%s: skw not pristine", __func__));
1155 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1159 if (s->id == 0 && s->creatorid == 0) {
1160 /* XXX: should be atomic, but probability of collision low */
1161 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1162 V_pf_stateid[curcpu] = 1;
1163 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1164 s->id = htobe64(s->id);
1165 s->creatorid = V_pf_status.hostid;
1168 /* Returns with ID locked on success. */
1169 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1172 ih = &V_pf_idhash[PF_IDHASH(s)];
1173 PF_HASHROW_ASSERT(ih);
1174 LIST_FOREACH(cur, &ih->states, entry)
1175 if (cur->id == s->id && cur->creatorid == s->creatorid)
1179 PF_HASHROW_UNLOCK(ih);
1180 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1181 printf("pf: state ID collision: "
1182 "id: %016llx creatorid: %08x\n",
1183 (unsigned long long)be64toh(s->id),
1184 ntohl(s->creatorid));
1189 LIST_INSERT_HEAD(&ih->states, s, entry);
1190 /* One for keys, one for ID hash. */
1191 refcount_init(&s->refs, 2);
1193 V_pf_status.fcounters[FCNT_STATE_INSERT]++;
1194 if (pfsync_insert_state_ptr != NULL)
1195 pfsync_insert_state_ptr(s);
1197 /* Returns locked. */
1202 * Find state by ID: returns with locked row on success.
1205 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1207 struct pf_idhash *ih;
1210 V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1212 ih = &V_pf_idhash[(be64toh(id) % (V_pf_hashmask + 1))];
1214 PF_HASHROW_LOCK(ih);
1215 LIST_FOREACH(s, &ih->states, entry)
1216 if (s->id == id && s->creatorid == creatorid)
1220 PF_HASHROW_UNLOCK(ih);
1226 * Find state by key.
1227 * Returns with ID hash slot locked on success.
1229 static struct pf_state *
1230 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1232 struct pf_keyhash *kh;
1233 struct pf_state_key *sk;
1237 V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1239 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1241 PF_HASHROW_LOCK(kh);
1242 LIST_FOREACH(sk, &kh->keys, entry)
1243 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1246 PF_HASHROW_UNLOCK(kh);
1250 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1252 /* List is sorted, if-bound states before floating ones. */
1253 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1254 if (s->kif == V_pfi_all || s->kif == kif) {
1256 PF_HASHROW_UNLOCK(kh);
1257 if (s->timeout >= PFTM_MAX) {
1259 * State is either being processed by
1260 * pf_unlink_state() in an other thread, or
1261 * is scheduled for immediate expiry.
1268 PF_HASHROW_UNLOCK(kh);
1274 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1276 struct pf_keyhash *kh;
1277 struct pf_state_key *sk;
1278 struct pf_state *s, *ret = NULL;
1281 V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1283 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1285 PF_HASHROW_LOCK(kh);
1286 LIST_FOREACH(sk, &kh->keys, entry)
1287 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1290 PF_HASHROW_UNLOCK(kh);
1305 panic("%s: dir %u", __func__, dir);
1308 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1310 PF_HASHROW_UNLOCK(kh);
1324 PF_HASHROW_UNLOCK(kh);
1329 /* END state table stuff */
1332 pf_send(struct pf_send_entry *pfse)
1336 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1338 swi_sched(V_pf_swi_cookie, 0);
1344 struct pf_send_head queue;
1345 struct pf_send_entry *pfse, *next;
1347 CURVNET_SET((struct vnet *)v);
1350 queue = V_pf_sendqueue;
1351 STAILQ_INIT(&V_pf_sendqueue);
1354 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1355 switch (pfse->pfse_type) {
1358 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1361 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1362 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1367 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1371 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1372 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1376 panic("%s: unknown type", __func__);
1378 free(pfse, M_PFTEMP);
1384 pf_purge_thread(void *v)
1388 CURVNET_SET((struct vnet *)v);
1392 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1394 if (V_pf_end_threads) {
1396 * To cleanse up all kifs and rules we need
1397 * two runs: first one clears reference flags,
1398 * then pf_purge_expired_states() doesn't
1399 * raise them, and then second run frees.
1402 pf_purge_unlinked_rules();
1406 * Now purge everything.
1408 pf_purge_expired_states(0, V_pf_hashmask);
1409 pf_purge_expired_fragments();
1410 pf_purge_expired_src_nodes();
1413 * Now all kifs & rules should be unreferenced,
1414 * thus should be successfully freed.
1416 pf_purge_unlinked_rules();
1420 * Announce success and exit.
1425 wakeup(pf_purge_thread);
1430 /* Process 1/interval fraction of the state table every run. */
1431 idx = pf_purge_expired_states(idx, V_pf_hashmask /
1432 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1434 /* Purge other expired types every PFTM_INTERVAL seconds. */
1437 * Order is important:
1438 * - states and src nodes reference rules
1439 * - states and rules reference kifs
1441 pf_purge_expired_fragments();
1442 pf_purge_expired_src_nodes();
1443 pf_purge_unlinked_rules();
1452 pf_state_expires(const struct pf_state *state)
1459 /* handle all PFTM_* > PFTM_MAX here */
1460 if (state->timeout == PFTM_PURGE)
1461 return (time_uptime);
1462 KASSERT(state->timeout != PFTM_UNLINKED,
1463 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1464 KASSERT((state->timeout < PFTM_MAX),
1465 ("pf_state_expires: timeout > PFTM_MAX"));
1466 timeout = state->rule.ptr->timeout[state->timeout];
1468 timeout = V_pf_default_rule.timeout[state->timeout];
1469 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1471 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1472 states = counter_u64_fetch(state->rule.ptr->states_cur);
1474 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1475 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1476 states = V_pf_status.states;
1478 if (end && states > start && start < end) {
1480 return (state->expire + timeout * (end - states) /
1483 return (time_uptime);
1485 return (state->expire + timeout);
1489 pf_purge_expired_src_nodes()
1491 struct pf_src_node_list freelist;
1492 struct pf_srchash *sh;
1493 struct pf_src_node *cur, *next;
1496 LIST_INIT(&freelist);
1497 for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask; i++, sh++) {
1498 PF_HASHROW_LOCK(sh);
1499 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1500 if (cur->states == 0 && cur->expire <= time_uptime) {
1501 pf_unlink_src_node_locked(cur);
1502 LIST_INSERT_HEAD(&freelist, cur, entry);
1503 } else if (cur->rule.ptr != NULL)
1504 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1505 PF_HASHROW_UNLOCK(sh);
1508 pf_free_src_nodes(&freelist);
1512 pf_src_tree_remove_state(struct pf_state *s)
1516 if (s->src_node != NULL) {
1518 --s->src_node->conn;
1519 if (--s->src_node->states == 0) {
1520 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1523 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1524 s->src_node->expire = time_uptime + timeout;
1527 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1528 if (--s->nat_src_node->states == 0) {
1529 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1532 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1533 s->nat_src_node->expire = time_uptime + timeout;
1536 s->src_node = s->nat_src_node = NULL;
1540 * Unlink and potentilly free a state. Function may be
1541 * called with ID hash row locked, but always returns
1542 * unlocked, since it needs to go through key hash locking.
1545 pf_unlink_state(struct pf_state *s, u_int flags)
1547 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1549 if ((flags & PF_ENTER_LOCKED) == 0)
1550 PF_HASHROW_LOCK(ih);
1552 PF_HASHROW_ASSERT(ih);
1554 if (s->timeout == PFTM_UNLINKED) {
1556 * State is being processed
1557 * by pf_unlink_state() in
1560 PF_HASHROW_UNLOCK(ih);
1561 return (0); /* XXXGL: undefined actually */
1564 if (s->src.state == PF_TCPS_PROXY_DST) {
1565 /* XXX wire key the right one? */
1566 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1567 &s->key[PF_SK_WIRE]->addr[1],
1568 &s->key[PF_SK_WIRE]->addr[0],
1569 s->key[PF_SK_WIRE]->port[1],
1570 s->key[PF_SK_WIRE]->port[0],
1571 s->src.seqhi, s->src.seqlo + 1,
1572 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1575 LIST_REMOVE(s, entry);
1576 pf_src_tree_remove_state(s);
1578 if (pfsync_delete_state_ptr != NULL)
1579 pfsync_delete_state_ptr(s);
1581 STATE_DEC_COUNTERS(s);
1583 s->timeout = PFTM_UNLINKED;
1585 PF_HASHROW_UNLOCK(ih);
1588 refcount_release(&s->refs);
1590 return (pf_release_state(s));
1594 pf_free_state(struct pf_state *cur)
1597 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1598 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1601 pf_normalize_tcp_cleanup(cur);
1602 uma_zfree(V_pf_state_z, cur);
1603 V_pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1607 * Called only from pf_purge_thread(), thus serialized.
1610 pf_purge_expired_states(u_int i, int maxcheck)
1612 struct pf_idhash *ih;
1615 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1618 * Go through hash and unlink states that expire now.
1620 while (maxcheck > 0) {
1622 ih = &V_pf_idhash[i];
1624 PF_HASHROW_LOCK(ih);
1625 LIST_FOREACH(s, &ih->states, entry) {
1626 if (pf_state_expires(s) <= time_uptime) {
1627 V_pf_status.states -=
1628 pf_unlink_state(s, PF_ENTER_LOCKED);
1631 s->rule.ptr->rule_flag |= PFRULE_REFS;
1632 if (s->nat_rule.ptr != NULL)
1633 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1634 if (s->anchor.ptr != NULL)
1635 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1636 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1638 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1640 PF_HASHROW_UNLOCK(ih);
1642 /* Return when we hit end of hash. */
1643 if (++i > V_pf_hashmask) {
1644 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1651 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1657 pf_purge_unlinked_rules()
1659 struct pf_rulequeue tmpq;
1660 struct pf_rule *r, *r1;
1663 * If we have overloading task pending, then we'd
1664 * better skip purging this time. There is a tiny
1665 * probability that overloading task references
1666 * an already unlinked rule.
1668 PF_OVERLOADQ_LOCK();
1669 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1670 PF_OVERLOADQ_UNLOCK();
1673 PF_OVERLOADQ_UNLOCK();
1676 * Do naive mark-and-sweep garbage collecting of old rules.
1677 * Reference flag is raised by pf_purge_expired_states()
1678 * and pf_purge_expired_src_nodes().
1680 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1681 * use a temporary queue.
1684 PF_UNLNKDRULES_LOCK();
1685 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1686 if (!(r->rule_flag & PFRULE_REFS)) {
1687 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1688 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1690 r->rule_flag &= ~PFRULE_REFS;
1692 PF_UNLNKDRULES_UNLOCK();
1694 if (!TAILQ_EMPTY(&tmpq)) {
1696 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1697 TAILQ_REMOVE(&tmpq, r, entries);
1705 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1710 u_int32_t a = ntohl(addr->addr32[0]);
1711 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1723 u_int8_t i, curstart, curend, maxstart, maxend;
1724 curstart = curend = maxstart = maxend = 255;
1725 for (i = 0; i < 8; i++) {
1726 if (!addr->addr16[i]) {
1727 if (curstart == 255)
1731 if ((curend - curstart) >
1732 (maxend - maxstart)) {
1733 maxstart = curstart;
1736 curstart = curend = 255;
1739 if ((curend - curstart) >
1740 (maxend - maxstart)) {
1741 maxstart = curstart;
1744 for (i = 0; i < 8; i++) {
1745 if (i >= maxstart && i <= maxend) {
1751 b = ntohs(addr->addr16[i]);
1768 pf_print_state(struct pf_state *s)
1770 pf_print_state_parts(s, NULL, NULL);
1774 pf_print_state_parts(struct pf_state *s,
1775 struct pf_state_key *skwp, struct pf_state_key *sksp)
1777 struct pf_state_key *skw, *sks;
1778 u_int8_t proto, dir;
1780 /* Do our best to fill these, but they're skipped if NULL */
1781 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1782 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1783 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1784 dir = s ? s->direction : 0;
1802 case IPPROTO_ICMPV6:
1806 printf("%u", skw->proto);
1819 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1821 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1826 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1828 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1833 if (proto == IPPROTO_TCP) {
1834 printf(" [lo=%u high=%u win=%u modulator=%u",
1835 s->src.seqlo, s->src.seqhi,
1836 s->src.max_win, s->src.seqdiff);
1837 if (s->src.wscale && s->dst.wscale)
1838 printf(" wscale=%u",
1839 s->src.wscale & PF_WSCALE_MASK);
1841 printf(" [lo=%u high=%u win=%u modulator=%u",
1842 s->dst.seqlo, s->dst.seqhi,
1843 s->dst.max_win, s->dst.seqdiff);
1844 if (s->src.wscale && s->dst.wscale)
1845 printf(" wscale=%u",
1846 s->dst.wscale & PF_WSCALE_MASK);
1849 printf(" %u:%u", s->src.state, s->dst.state);
1854 pf_print_flags(u_int8_t f)
1876 #define PF_SET_SKIP_STEPS(i) \
1878 while (head[i] != cur) { \
1879 head[i]->skip[i].ptr = cur; \
1880 head[i] = TAILQ_NEXT(head[i], entries); \
1885 pf_calc_skip_steps(struct pf_rulequeue *rules)
1887 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1890 cur = TAILQ_FIRST(rules);
1892 for (i = 0; i < PF_SKIP_COUNT; ++i)
1894 while (cur != NULL) {
1896 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1897 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1898 if (cur->direction != prev->direction)
1899 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1900 if (cur->af != prev->af)
1901 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1902 if (cur->proto != prev->proto)
1903 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1904 if (cur->src.neg != prev->src.neg ||
1905 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1906 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1907 if (cur->src.port[0] != prev->src.port[0] ||
1908 cur->src.port[1] != prev->src.port[1] ||
1909 cur->src.port_op != prev->src.port_op)
1910 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1911 if (cur->dst.neg != prev->dst.neg ||
1912 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1913 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1914 if (cur->dst.port[0] != prev->dst.port[0] ||
1915 cur->dst.port[1] != prev->dst.port[1] ||
1916 cur->dst.port_op != prev->dst.port_op)
1917 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1920 cur = TAILQ_NEXT(cur, entries);
1922 for (i = 0; i < PF_SKIP_COUNT; ++i)
1923 PF_SET_SKIP_STEPS(i);
1927 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1929 if (aw1->type != aw2->type)
1931 switch (aw1->type) {
1932 case PF_ADDR_ADDRMASK:
1934 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1936 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1939 case PF_ADDR_DYNIFTL:
1940 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1941 case PF_ADDR_NOROUTE:
1942 case PF_ADDR_URPFFAILED:
1945 return (aw1->p.tbl != aw2->p.tbl);
1947 printf("invalid address type: %d\n", aw1->type);
1953 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1959 l = cksum + old - new;
1960 l = (l >> 16) + (l & 65535);
1968 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1969 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1974 PF_ACPY(&ao, a, af);
1982 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1983 ao.addr16[0], an->addr16[0], 0),
1984 ao.addr16[1], an->addr16[1], 0);
1986 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1987 ao.addr16[0], an->addr16[0], u),
1988 ao.addr16[1], an->addr16[1], u),
1994 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1995 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1996 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1997 ao.addr16[0], an->addr16[0], u),
1998 ao.addr16[1], an->addr16[1], u),
1999 ao.addr16[2], an->addr16[2], u),
2000 ao.addr16[3], an->addr16[3], u),
2001 ao.addr16[4], an->addr16[4], u),
2002 ao.addr16[5], an->addr16[5], u),
2003 ao.addr16[6], an->addr16[6], u),
2004 ao.addr16[7], an->addr16[7], u),
2012 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2014 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2018 memcpy(&ao, a, sizeof(ao));
2019 memcpy(a, &an, sizeof(u_int32_t));
2020 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2021 ao % 65536, an % 65536, u);
2026 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2030 PF_ACPY(&ao, a, AF_INET6);
2031 PF_ACPY(a, an, AF_INET6);
2033 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2034 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2035 pf_cksum_fixup(pf_cksum_fixup(*c,
2036 ao.addr16[0], an->addr16[0], u),
2037 ao.addr16[1], an->addr16[1], u),
2038 ao.addr16[2], an->addr16[2], u),
2039 ao.addr16[3], an->addr16[3], u),
2040 ao.addr16[4], an->addr16[4], u),
2041 ao.addr16[5], an->addr16[5], u),
2042 ao.addr16[6], an->addr16[6], u),
2043 ao.addr16[7], an->addr16[7], u);
2048 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2049 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2050 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2052 struct pf_addr oia, ooa;
2054 PF_ACPY(&oia, ia, af);
2056 PF_ACPY(&ooa, oa, af);
2058 /* Change inner protocol port, fix inner protocol checksum. */
2060 u_int16_t oip = *ip;
2067 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2068 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2070 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2072 /* Change inner ip address, fix inner ip and icmp checksums. */
2073 PF_ACPY(ia, na, af);
2077 u_int32_t oh2c = *h2c;
2079 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2080 oia.addr16[0], ia->addr16[0], 0),
2081 oia.addr16[1], ia->addr16[1], 0);
2082 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2083 oia.addr16[0], ia->addr16[0], 0),
2084 oia.addr16[1], ia->addr16[1], 0);
2085 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2091 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2092 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2093 pf_cksum_fixup(pf_cksum_fixup(*ic,
2094 oia.addr16[0], ia->addr16[0], u),
2095 oia.addr16[1], ia->addr16[1], u),
2096 oia.addr16[2], ia->addr16[2], u),
2097 oia.addr16[3], ia->addr16[3], u),
2098 oia.addr16[4], ia->addr16[4], u),
2099 oia.addr16[5], ia->addr16[5], u),
2100 oia.addr16[6], ia->addr16[6], u),
2101 oia.addr16[7], ia->addr16[7], u);
2105 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2107 PF_ACPY(oa, na, af);
2111 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2112 ooa.addr16[0], oa->addr16[0], 0),
2113 ooa.addr16[1], oa->addr16[1], 0);
2118 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2119 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2120 pf_cksum_fixup(pf_cksum_fixup(*ic,
2121 ooa.addr16[0], oa->addr16[0], u),
2122 ooa.addr16[1], oa->addr16[1], u),
2123 ooa.addr16[2], oa->addr16[2], u),
2124 ooa.addr16[3], oa->addr16[3], u),
2125 ooa.addr16[4], oa->addr16[4], u),
2126 ooa.addr16[5], oa->addr16[5], u),
2127 ooa.addr16[6], oa->addr16[6], u),
2128 ooa.addr16[7], oa->addr16[7], u);
2137 * Need to modulate the sequence numbers in the TCP SACK option
2138 * (credits to Krzysztof Pfaff for report and patch)
2141 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2142 struct tcphdr *th, struct pf_state_peer *dst)
2144 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2145 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2146 int copyback = 0, i, olen;
2147 struct sackblk sack;
2149 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2150 if (hlen < TCPOLEN_SACKLEN ||
2151 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2154 while (hlen >= TCPOLEN_SACKLEN) {
2157 case TCPOPT_EOL: /* FALLTHROUGH */
2165 if (olen >= TCPOLEN_SACKLEN) {
2166 for (i = 2; i + TCPOLEN_SACK <= olen;
2167 i += TCPOLEN_SACK) {
2168 memcpy(&sack, &opt[i], sizeof(sack));
2169 pf_change_a(&sack.start, &th->th_sum,
2170 htonl(ntohl(sack.start) -
2172 pf_change_a(&sack.end, &th->th_sum,
2173 htonl(ntohl(sack.end) -
2175 memcpy(&opt[i], &sack, sizeof(sack));
2189 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2194 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2195 const struct pf_addr *saddr, const struct pf_addr *daddr,
2196 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2197 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2198 u_int16_t rtag, struct ifnet *ifp)
2200 struct pf_send_entry *pfse;
2204 struct ip *h = NULL;
2207 struct ip6_hdr *h6 = NULL;
2211 struct pf_mtag *pf_mtag;
2216 /* maximum segment size tcp option */
2217 tlen = sizeof(struct tcphdr);
2224 len = sizeof(struct ip) + tlen;
2229 len = sizeof(struct ip6_hdr) + tlen;
2233 panic("%s: unsupported af %d", __func__, af);
2236 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2237 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2240 m = m_gethdr(M_NOWAIT, MT_DATA);
2242 free(pfse, M_PFTEMP);
2246 mac_netinet_firewall_send(m);
2248 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2249 free(pfse, M_PFTEMP);
2254 m->m_flags |= M_SKIP_FIREWALL;
2255 pf_mtag->tag = rtag;
2257 if (r != NULL && r->rtableid >= 0)
2258 M_SETFIB(m, r->rtableid);
2261 if (r != NULL && r->qid) {
2262 pf_mtag->qid = r->qid;
2264 /* add hints for ecn */
2265 pf_mtag->hdr = mtod(m, struct ip *);
2268 m->m_data += max_linkhdr;
2269 m->m_pkthdr.len = m->m_len = len;
2270 m->m_pkthdr.rcvif = NULL;
2271 bzero(m->m_data, len);
2275 h = mtod(m, struct ip *);
2277 /* IP header fields included in the TCP checksum */
2278 h->ip_p = IPPROTO_TCP;
2279 h->ip_len = htons(tlen);
2280 h->ip_src.s_addr = saddr->v4.s_addr;
2281 h->ip_dst.s_addr = daddr->v4.s_addr;
2283 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2288 h6 = mtod(m, struct ip6_hdr *);
2290 /* IP header fields included in the TCP checksum */
2291 h6->ip6_nxt = IPPROTO_TCP;
2292 h6->ip6_plen = htons(tlen);
2293 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2294 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2296 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2302 th->th_sport = sport;
2303 th->th_dport = dport;
2304 th->th_seq = htonl(seq);
2305 th->th_ack = htonl(ack);
2306 th->th_off = tlen >> 2;
2307 th->th_flags = flags;
2308 th->th_win = htons(win);
2311 opt = (char *)(th + 1);
2312 opt[0] = TCPOPT_MAXSEG;
2315 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2322 th->th_sum = in_cksum(m, len);
2324 /* Finish the IP header */
2326 h->ip_hl = sizeof(*h) >> 2;
2327 h->ip_tos = IPTOS_LOWDELAY;
2328 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2329 h->ip_len = htons(len);
2330 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2333 pfse->pfse_type = PFSE_IP;
2339 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2340 sizeof(struct ip6_hdr), tlen);
2342 h6->ip6_vfc |= IPV6_VERSION;
2343 h6->ip6_hlim = IPV6_DEFHLIM;
2345 pfse->pfse_type = PFSE_IP6;
2354 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2357 struct pf_send_entry *pfse;
2359 struct pf_mtag *pf_mtag;
2361 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2362 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2366 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2367 free(pfse, M_PFTEMP);
2371 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2372 free(pfse, M_PFTEMP);
2376 m0->m_flags |= M_SKIP_FIREWALL;
2378 if (r->rtableid >= 0)
2379 M_SETFIB(m0, r->rtableid);
2383 pf_mtag->qid = r->qid;
2384 /* add hints for ecn */
2385 pf_mtag->hdr = mtod(m0, struct ip *);
2392 pfse->pfse_type = PFSE_ICMP;
2397 pfse->pfse_type = PFSE_ICMP6;
2402 pfse->pfse_icmp_type = type;
2403 pfse->pfse_icmp_code = code;
2408 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2409 * If n is 0, they match if they are equal. If n is != 0, they match if they
2413 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2414 struct pf_addr *b, sa_family_t af)
2421 if ((a->addr32[0] & m->addr32[0]) ==
2422 (b->addr32[0] & m->addr32[0]))
2428 if (((a->addr32[0] & m->addr32[0]) ==
2429 (b->addr32[0] & m->addr32[0])) &&
2430 ((a->addr32[1] & m->addr32[1]) ==
2431 (b->addr32[1] & m->addr32[1])) &&
2432 ((a->addr32[2] & m->addr32[2]) ==
2433 (b->addr32[2] & m->addr32[2])) &&
2434 ((a->addr32[3] & m->addr32[3]) ==
2435 (b->addr32[3] & m->addr32[3])))
2454 * Return 1 if b <= a <= e, otherwise return 0.
2457 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2458 struct pf_addr *a, sa_family_t af)
2463 if ((a->addr32[0] < b->addr32[0]) ||
2464 (a->addr32[0] > e->addr32[0]))
2473 for (i = 0; i < 4; ++i)
2474 if (a->addr32[i] > b->addr32[i])
2476 else if (a->addr32[i] < b->addr32[i])
2479 for (i = 0; i < 4; ++i)
2480 if (a->addr32[i] < e->addr32[i])
2482 else if (a->addr32[i] > e->addr32[i])
2492 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2496 return ((p > a1) && (p < a2));
2498 return ((p < a1) || (p > a2));
2500 return ((p >= a1) && (p <= a2));
2514 return (0); /* never reached */
2518 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2523 return (pf_match(op, a1, a2, p));
2527 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2529 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2531 return (pf_match(op, a1, a2, u));
2535 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2537 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2539 return (pf_match(op, a1, a2, g));
2543 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2548 return ((!r->match_tag_not && r->match_tag == *tag) ||
2549 (r->match_tag_not && r->match_tag != *tag));
2553 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2556 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2558 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2561 pd->pf_mtag->tag = tag;
2566 #define PF_ANCHOR_STACKSIZE 32
2567 struct pf_anchor_stackframe {
2568 struct pf_ruleset *rs;
2569 struct pf_rule *r; /* XXX: + match bit */
2570 struct pf_anchor *child;
2574 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2576 #define PF_ANCHORSTACK_MATCH 0x00000001
2577 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2579 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2580 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2581 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2582 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2583 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2587 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2588 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2591 struct pf_anchor_stackframe *f;
2597 if (*depth >= PF_ANCHOR_STACKSIZE) {
2598 printf("%s: anchor stack overflow on %s\n",
2599 __func__, (*r)->anchor->name);
2600 *r = TAILQ_NEXT(*r, entries);
2602 } else if (*depth == 0 && a != NULL)
2604 f = stack + (*depth)++;
2607 if ((*r)->anchor_wildcard) {
2608 struct pf_anchor_node *parent = &(*r)->anchor->children;
2610 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2614 *rs = &f->child->ruleset;
2617 *rs = &(*r)->anchor->ruleset;
2619 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2623 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2624 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2627 struct pf_anchor_stackframe *f;
2636 f = stack + *depth - 1;
2637 fr = PF_ANCHOR_RULE(f);
2638 if (f->child != NULL) {
2639 struct pf_anchor_node *parent;
2642 * This block traverses through
2643 * a wildcard anchor.
2645 parent = &fr->anchor->children;
2646 if (match != NULL && *match) {
2648 * If any of "*" matched, then
2649 * "foo/ *" matched, mark frame
2652 PF_ANCHOR_SET_MATCH(f);
2655 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2656 if (f->child != NULL) {
2657 *rs = &f->child->ruleset;
2658 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2666 if (*depth == 0 && a != NULL)
2669 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2671 *r = TAILQ_NEXT(fr, entries);
2672 } while (*r == NULL);
2679 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2680 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2685 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2686 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2690 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2691 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2692 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2693 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2694 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2695 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2696 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2697 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2703 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2708 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2712 if (addr->addr32[3] == 0xffffffff) {
2713 addr->addr32[3] = 0;
2714 if (addr->addr32[2] == 0xffffffff) {
2715 addr->addr32[2] = 0;
2716 if (addr->addr32[1] == 0xffffffff) {
2717 addr->addr32[1] = 0;
2719 htonl(ntohl(addr->addr32[0]) + 1);
2722 htonl(ntohl(addr->addr32[1]) + 1);
2725 htonl(ntohl(addr->addr32[2]) + 1);
2728 htonl(ntohl(addr->addr32[3]) + 1);
2735 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2737 struct pf_addr *saddr, *daddr;
2738 u_int16_t sport, dport;
2739 struct inpcbinfo *pi;
2742 pd->lookup.uid = UID_MAX;
2743 pd->lookup.gid = GID_MAX;
2745 switch (pd->proto) {
2747 if (pd->hdr.tcp == NULL)
2749 sport = pd->hdr.tcp->th_sport;
2750 dport = pd->hdr.tcp->th_dport;
2754 if (pd->hdr.udp == NULL)
2756 sport = pd->hdr.udp->uh_sport;
2757 dport = pd->hdr.udp->uh_dport;
2763 if (direction == PF_IN) {
2778 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2779 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2781 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2782 daddr->v4, dport, INPLOOKUP_WILDCARD |
2783 INPLOOKUP_RLOCKPCB, NULL, m);
2791 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2792 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2794 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2795 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2796 INPLOOKUP_RLOCKPCB, NULL, m);
2806 INP_RLOCK_ASSERT(inp);
2807 pd->lookup.uid = inp->inp_cred->cr_uid;
2808 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2815 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2819 u_int8_t *opt, optlen;
2820 u_int8_t wscale = 0;
2822 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2823 if (hlen <= sizeof(struct tcphdr))
2825 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2827 opt = hdr + sizeof(struct tcphdr);
2828 hlen -= sizeof(struct tcphdr);
2838 if (wscale > TCP_MAX_WINSHIFT)
2839 wscale = TCP_MAX_WINSHIFT;
2840 wscale |= PF_WSCALE_FLAG;
2855 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2859 u_int8_t *opt, optlen;
2860 u_int16_t mss = V_tcp_mssdflt;
2862 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2863 if (hlen <= sizeof(struct tcphdr))
2865 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2867 opt = hdr + sizeof(struct tcphdr);
2868 hlen -= sizeof(struct tcphdr);
2869 while (hlen >= TCPOLEN_MAXSEG) {
2877 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2893 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
2896 struct sockaddr_in *dst;
2900 struct sockaddr_in6 *dst6;
2901 struct route_in6 ro6;
2903 struct rtentry *rt = NULL;
2905 u_int16_t mss = V_tcp_mssdflt;
2910 hlen = sizeof(struct ip);
2911 bzero(&ro, sizeof(ro));
2912 dst = (struct sockaddr_in *)&ro.ro_dst;
2913 dst->sin_family = AF_INET;
2914 dst->sin_len = sizeof(*dst);
2915 dst->sin_addr = addr->v4;
2916 in_rtalloc_ign(&ro, 0, rtableid);
2922 hlen = sizeof(struct ip6_hdr);
2923 bzero(&ro6, sizeof(ro6));
2924 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2925 dst6->sin6_family = AF_INET6;
2926 dst6->sin6_len = sizeof(*dst6);
2927 dst6->sin6_addr = addr->v6;
2928 in6_rtalloc_ign(&ro6, 0, rtableid);
2934 if (rt && rt->rt_ifp) {
2935 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2936 mss = max(V_tcp_mssdflt, mss);
2939 mss = min(mss, offer);
2940 mss = max(mss, 64); /* sanity - at least max opt space */
2945 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
2947 struct pf_rule *r = s->rule.ptr;
2948 struct pf_src_node *sn = NULL;
2951 if (!r->rt || r->rt == PF_FASTROUTE)
2953 switch (s->key[PF_SK_WIRE]->af) {
2956 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL, &sn);
2957 s->rt_kif = r->rpool.cur->kif;
2962 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL, &sn);
2963 s->rt_kif = r->rpool.cur->kif;
2970 pf_tcp_iss(struct pf_pdesc *pd)
2973 u_int32_t digest[4];
2975 if (V_pf_tcp_secret_init == 0) {
2976 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
2977 MD5Init(&V_pf_tcp_secret_ctx);
2978 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
2979 sizeof(V_pf_tcp_secret));
2980 V_pf_tcp_secret_init = 1;
2983 ctx = V_pf_tcp_secret_ctx;
2985 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
2986 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
2987 if (pd->af == AF_INET6) {
2988 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
2989 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
2991 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
2992 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
2994 MD5Final((u_char *)digest, &ctx);
2995 V_pf_tcp_iss_off += 4096;
2996 #define ISN_RANDOM_INCREMENT (4096 - 1)
2997 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
2999 #undef ISN_RANDOM_INCREMENT
3003 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3004 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3005 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3007 struct pf_rule *nr = NULL;
3008 struct pf_addr * const saddr = pd->src;
3009 struct pf_addr * const daddr = pd->dst;
3010 sa_family_t af = pd->af;
3011 struct pf_rule *r, *a = NULL;
3012 struct pf_ruleset *ruleset = NULL;
3013 struct pf_src_node *nsn = NULL;
3014 struct tcphdr *th = pd->hdr.tcp;
3015 struct pf_state_key *sk = NULL, *nk = NULL;
3017 int rewrite = 0, hdrlen = 0;
3018 int tag = -1, rtableid = -1;
3022 u_int16_t sport = 0, dport = 0;
3023 u_int16_t bproto_sum = 0, bip_sum = 0;
3024 u_int8_t icmptype = 0, icmpcode = 0;
3025 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3030 INP_LOCK_ASSERT(inp);
3031 pd->lookup.uid = inp->inp_cred->cr_uid;
3032 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3033 pd->lookup.done = 1;
3036 switch (pd->proto) {
3038 sport = th->th_sport;
3039 dport = th->th_dport;
3040 hdrlen = sizeof(*th);
3043 sport = pd->hdr.udp->uh_sport;
3044 dport = pd->hdr.udp->uh_dport;
3045 hdrlen = sizeof(*pd->hdr.udp);
3049 if (pd->af != AF_INET)
3051 sport = dport = pd->hdr.icmp->icmp_id;
3052 hdrlen = sizeof(*pd->hdr.icmp);
3053 icmptype = pd->hdr.icmp->icmp_type;
3054 icmpcode = pd->hdr.icmp->icmp_code;
3056 if (icmptype == ICMP_UNREACH ||
3057 icmptype == ICMP_SOURCEQUENCH ||
3058 icmptype == ICMP_REDIRECT ||
3059 icmptype == ICMP_TIMXCEED ||
3060 icmptype == ICMP_PARAMPROB)
3065 case IPPROTO_ICMPV6:
3068 sport = dport = pd->hdr.icmp6->icmp6_id;
3069 hdrlen = sizeof(*pd->hdr.icmp6);
3070 icmptype = pd->hdr.icmp6->icmp6_type;
3071 icmpcode = pd->hdr.icmp6->icmp6_code;
3073 if (icmptype == ICMP6_DST_UNREACH ||
3074 icmptype == ICMP6_PACKET_TOO_BIG ||
3075 icmptype == ICMP6_TIME_EXCEEDED ||
3076 icmptype == ICMP6_PARAM_PROB)
3081 sport = dport = hdrlen = 0;
3085 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3087 /* check packet for BINAT/NAT/RDR */
3088 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3089 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3090 KASSERT(sk != NULL, ("%s: null sk", __func__));
3091 KASSERT(nk != NULL, ("%s: null nk", __func__));
3094 bip_sum = *pd->ip_sum;
3096 switch (pd->proto) {
3098 bproto_sum = th->th_sum;
3099 pd->proto_sum = &th->th_sum;
3101 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3102 nk->port[pd->sidx] != sport) {
3103 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3104 &th->th_sum, &nk->addr[pd->sidx],
3105 nk->port[pd->sidx], 0, af);
3106 pd->sport = &th->th_sport;
3107 sport = th->th_sport;
3110 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3111 nk->port[pd->didx] != dport) {
3112 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3113 &th->th_sum, &nk->addr[pd->didx],
3114 nk->port[pd->didx], 0, af);
3115 dport = th->th_dport;
3116 pd->dport = &th->th_dport;
3121 bproto_sum = pd->hdr.udp->uh_sum;
3122 pd->proto_sum = &pd->hdr.udp->uh_sum;
3124 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3125 nk->port[pd->sidx] != sport) {
3126 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3127 pd->ip_sum, &pd->hdr.udp->uh_sum,
3128 &nk->addr[pd->sidx],
3129 nk->port[pd->sidx], 1, af);
3130 sport = pd->hdr.udp->uh_sport;
3131 pd->sport = &pd->hdr.udp->uh_sport;
3134 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3135 nk->port[pd->didx] != dport) {
3136 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3137 pd->ip_sum, &pd->hdr.udp->uh_sum,
3138 &nk->addr[pd->didx],
3139 nk->port[pd->didx], 1, af);
3140 dport = pd->hdr.udp->uh_dport;
3141 pd->dport = &pd->hdr.udp->uh_dport;
3147 nk->port[0] = nk->port[1];
3148 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3149 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3150 nk->addr[pd->sidx].v4.s_addr, 0);
3152 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3153 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3154 nk->addr[pd->didx].v4.s_addr, 0);
3156 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3157 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3158 pd->hdr.icmp->icmp_cksum, sport,
3160 pd->hdr.icmp->icmp_id = nk->port[1];
3161 pd->sport = &pd->hdr.icmp->icmp_id;
3163 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3167 case IPPROTO_ICMPV6:
3168 nk->port[0] = nk->port[1];
3169 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3170 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3171 &nk->addr[pd->sidx], 0);
3173 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3174 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3175 &nk->addr[pd->didx], 0);
3184 &nk->addr[pd->sidx], AF_INET))
3185 pf_change_a(&saddr->v4.s_addr,
3187 nk->addr[pd->sidx].v4.s_addr, 0);
3190 &nk->addr[pd->didx], AF_INET))
3191 pf_change_a(&daddr->v4.s_addr,
3193 nk->addr[pd->didx].v4.s_addr, 0);
3199 &nk->addr[pd->sidx], AF_INET6))
3200 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3203 &nk->addr[pd->didx], AF_INET6))
3204 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3217 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3218 r = r->skip[PF_SKIP_IFP].ptr;
3219 else if (r->direction && r->direction != direction)
3220 r = r->skip[PF_SKIP_DIR].ptr;
3221 else if (r->af && r->af != af)
3222 r = r->skip[PF_SKIP_AF].ptr;
3223 else if (r->proto && r->proto != pd->proto)
3224 r = r->skip[PF_SKIP_PROTO].ptr;
3225 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3226 r->src.neg, kif, M_GETFIB(m)))
3227 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3228 /* tcp/udp only. port_op always 0 in other cases */
3229 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3230 r->src.port[0], r->src.port[1], sport))
3231 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3232 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3233 r->dst.neg, NULL, M_GETFIB(m)))
3234 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3235 /* tcp/udp only. port_op always 0 in other cases */
3236 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3237 r->dst.port[0], r->dst.port[1], dport))
3238 r = r->skip[PF_SKIP_DST_PORT].ptr;
3239 /* icmp only. type always 0 in other cases */
3240 else if (r->type && r->type != icmptype + 1)
3241 r = TAILQ_NEXT(r, entries);
3242 /* icmp only. type always 0 in other cases */
3243 else if (r->code && r->code != icmpcode + 1)
3244 r = TAILQ_NEXT(r, entries);
3245 else if (r->tos && !(r->tos == pd->tos))
3246 r = TAILQ_NEXT(r, entries);
3247 else if (r->rule_flag & PFRULE_FRAGMENT)
3248 r = TAILQ_NEXT(r, entries);
3249 else if (pd->proto == IPPROTO_TCP &&
3250 (r->flagset & th->th_flags) != r->flags)
3251 r = TAILQ_NEXT(r, entries);
3252 /* tcp/udp only. uid.op always 0 in other cases */
3253 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3254 pf_socket_lookup(direction, pd, m), 1)) &&
3255 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3257 r = TAILQ_NEXT(r, entries);
3258 /* tcp/udp only. gid.op always 0 in other cases */
3259 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3260 pf_socket_lookup(direction, pd, m), 1)) &&
3261 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3263 r = TAILQ_NEXT(r, entries);
3265 r->prob <= arc4random())
3266 r = TAILQ_NEXT(r, entries);
3267 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3268 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3269 r = TAILQ_NEXT(r, entries);
3270 else if (r->os_fingerprint != PF_OSFP_ANY &&
3271 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3272 pf_osfp_fingerprint(pd, m, off, th),
3273 r->os_fingerprint)))
3274 r = TAILQ_NEXT(r, entries);
3278 if (r->rtableid >= 0)
3279 rtableid = r->rtableid;
3280 if (r->anchor == NULL) {
3287 r = TAILQ_NEXT(r, entries);
3289 pf_step_into_anchor(anchor_stack, &asd,
3290 &ruleset, PF_RULESET_FILTER, &r, &a,
3293 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3294 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3301 REASON_SET(&reason, PFRES_MATCH);
3303 if (r->log || (nr != NULL && nr->log)) {
3305 m_copyback(m, off, hdrlen, pd->hdr.any);
3306 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3310 if ((r->action == PF_DROP) &&
3311 ((r->rule_flag & PFRULE_RETURNRST) ||
3312 (r->rule_flag & PFRULE_RETURNICMP) ||
3313 (r->rule_flag & PFRULE_RETURN))) {
3314 /* undo NAT changes, if they have taken place */
3316 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3317 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3319 *pd->sport = sk->port[pd->sidx];
3321 *pd->dport = sk->port[pd->didx];
3323 *pd->proto_sum = bproto_sum;
3325 *pd->ip_sum = bip_sum;
3326 m_copyback(m, off, hdrlen, pd->hdr.any);
3328 if (pd->proto == IPPROTO_TCP &&
3329 ((r->rule_flag & PFRULE_RETURNRST) ||
3330 (r->rule_flag & PFRULE_RETURN)) &&
3331 !(th->th_flags & TH_RST)) {
3332 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3344 h4 = mtod(m, struct ip *);
3345 len = ntohs(h4->ip_len) - off;
3350 h6 = mtod(m, struct ip6_hdr *);
3351 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3356 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3357 REASON_SET(&reason, PFRES_PROTCKSUM);
3359 if (th->th_flags & TH_SYN)
3361 if (th->th_flags & TH_FIN)
3363 pf_send_tcp(m, r, af, pd->dst,
3364 pd->src, th->th_dport, th->th_sport,
3365 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3366 r->return_ttl, 1, 0, kif->pfik_ifp);
3368 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3370 pf_send_icmp(m, r->return_icmp >> 8,
3371 r->return_icmp & 255, af, r);
3372 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3374 pf_send_icmp(m, r->return_icmp6 >> 8,
3375 r->return_icmp6 & 255, af, r);
3378 if (r->action == PF_DROP)
3381 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3382 REASON_SET(&reason, PFRES_MEMORY);
3386 M_SETFIB(m, rtableid);
3388 if (!state_icmp && (r->keep_state || nr != NULL ||
3389 (pd->flags & PFDESC_TCP_NORM))) {
3391 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3392 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3394 if (action != PF_PASS)
3398 uma_zfree(V_pf_state_key_z, sk);
3400 uma_zfree(V_pf_state_key_z, nk);
3403 /* copy back packet headers if we performed NAT operations */
3405 m_copyback(m, off, hdrlen, pd->hdr.any);
3407 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3408 direction == PF_OUT &&
3409 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3411 * We want the state created, but we dont
3412 * want to send this in case a partner
3413 * firewall has to know about it to allow
3414 * replies through it.
3422 uma_zfree(V_pf_state_key_z, sk);
3424 uma_zfree(V_pf_state_key_z, nk);
3429 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3430 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3431 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3432 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3433 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3435 struct pf_state *s = NULL;
3436 struct pf_src_node *sn = NULL;
3437 struct tcphdr *th = pd->hdr.tcp;
3438 u_int16_t mss = V_tcp_mssdflt;
3441 /* check maximums */
3442 if (r->max_states &&
3443 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3444 V_pf_status.lcounters[LCNT_STATES]++;
3445 REASON_SET(&reason, PFRES_MAXSTATES);
3448 /* src node for filter rule */
3449 if ((r->rule_flag & PFRULE_SRCTRACK ||
3450 r->rpool.opts & PF_POOL_STICKYADDR) &&
3451 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3452 REASON_SET(&reason, PFRES_SRCLIMIT);
3455 /* src node for translation rule */
3456 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3457 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3458 REASON_SET(&reason, PFRES_SRCLIMIT);
3461 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3463 REASON_SET(&reason, PFRES_MEMORY);
3467 s->nat_rule.ptr = nr;
3469 STATE_INC_COUNTERS(s);
3471 s->state_flags |= PFSTATE_ALLOWOPTS;
3472 if (r->rule_flag & PFRULE_STATESLOPPY)
3473 s->state_flags |= PFSTATE_SLOPPY;
3474 s->log = r->log & PF_LOG_ALL;
3475 s->sync_state = PFSYNC_S_NONE;
3477 s->log |= nr->log & PF_LOG_ALL;
3478 switch (pd->proto) {
3480 s->src.seqlo = ntohl(th->th_seq);
3481 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3482 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3483 r->keep_state == PF_STATE_MODULATE) {
3484 /* Generate sequence number modulator */
3485 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3488 pf_change_a(&th->th_seq, &th->th_sum,
3489 htonl(s->src.seqlo + s->src.seqdiff), 0);
3493 if (th->th_flags & TH_SYN) {
3495 s->src.wscale = pf_get_wscale(m, off,
3496 th->th_off, pd->af);
3498 s->src.max_win = MAX(ntohs(th->th_win), 1);
3499 if (s->src.wscale & PF_WSCALE_MASK) {
3500 /* Remove scale factor from initial window */
3501 int win = s->src.max_win;
3502 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3503 s->src.max_win = (win - 1) >>
3504 (s->src.wscale & PF_WSCALE_MASK);
3506 if (th->th_flags & TH_FIN)
3510 s->src.state = TCPS_SYN_SENT;
3511 s->dst.state = TCPS_CLOSED;
3512 s->timeout = PFTM_TCP_FIRST_PACKET;
3515 s->src.state = PFUDPS_SINGLE;
3516 s->dst.state = PFUDPS_NO_TRAFFIC;
3517 s->timeout = PFTM_UDP_FIRST_PACKET;
3521 case IPPROTO_ICMPV6:
3523 s->timeout = PFTM_ICMP_FIRST_PACKET;
3526 s->src.state = PFOTHERS_SINGLE;
3527 s->dst.state = PFOTHERS_NO_TRAFFIC;
3528 s->timeout = PFTM_OTHER_FIRST_PACKET;
3531 s->creation = time_uptime;
3532 s->expire = time_uptime;
3536 s->src_node->states++;
3539 /* XXX We only modify one side for now. */
3540 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3541 s->nat_src_node = nsn;
3542 s->nat_src_node->states++;
3544 if (pd->proto == IPPROTO_TCP) {
3545 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3546 off, pd, th, &s->src, &s->dst)) {
3547 REASON_SET(&reason, PFRES_MEMORY);
3548 pf_src_tree_remove_state(s);
3549 STATE_DEC_COUNTERS(s);
3550 uma_zfree(V_pf_state_z, s);
3553 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3554 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3555 &s->src, &s->dst, rewrite)) {
3556 /* This really shouldn't happen!!! */
3557 DPFPRINTF(PF_DEBUG_URGENT,
3558 ("pf_normalize_tcp_stateful failed on first pkt"));
3559 pf_normalize_tcp_cleanup(s);
3560 pf_src_tree_remove_state(s);
3561 STATE_DEC_COUNTERS(s);
3562 uma_zfree(V_pf_state_z, s);
3566 s->direction = pd->dir;
3569 * sk/nk could already been setup by pf_get_translation().
3572 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3573 __func__, nr, sk, nk));
3574 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3579 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3580 __func__, nr, sk, nk));
3582 /* Swap sk/nk for PF_OUT. */
3583 if (pf_state_insert(BOUND_IFACE(r, kif),
3584 (pd->dir == PF_IN) ? sk : nk,
3585 (pd->dir == PF_IN) ? nk : sk, s)) {
3586 if (pd->proto == IPPROTO_TCP)
3587 pf_normalize_tcp_cleanup(s);
3588 REASON_SET(&reason, PFRES_STATEINS);
3589 pf_src_tree_remove_state(s);
3590 STATE_DEC_COUNTERS(s);
3591 uma_zfree(V_pf_state_z, s);
3596 pf_set_rt_ifp(s, pd->src); /* needs s->state_key set */
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 rt->rt_rmx.rmx_pksent++;
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:
6005 /* pf_route() returns unlocked. */
6007 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6021 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6023 struct pfi_kif *kif;
6024 u_short action, reason = 0, log = 0;
6025 struct mbuf *m = *m0, *n = NULL;
6026 struct ip6_hdr *h = NULL;
6027 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6028 struct pf_state *s = NULL;
6029 struct pf_ruleset *ruleset = NULL;
6031 int off, terminal = 0, dirndx, rh_cnt = 0;
6035 if (!V_pf_status.running)
6038 memset(&pd, 0, sizeof(pd));
6039 pd.pf_mtag = pf_find_mtag(m);
6041 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6044 kif = (struct pfi_kif *)ifp->if_pf_kif;
6046 DPFPRINTF(PF_DEBUG_URGENT,
6047 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6050 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6055 /* We do IP header normalization and packet reassembly here */
6056 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6060 m = *m0; /* pf_normalize messes with m0 */
6061 h = mtod(m, struct ip6_hdr *);
6065 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6066 * will do something bad, so drop the packet for now.
6068 if (htons(h->ip6_plen) == 0) {
6070 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6075 pd.src = (struct pf_addr *)&h->ip6_src;
6076 pd.dst = (struct pf_addr *)&h->ip6_dst;
6077 pd.sport = pd.dport = NULL;
6079 pd.proto_sum = NULL;
6081 pd.sidx = (dir == PF_IN) ? 0 : 1;
6082 pd.didx = (dir == PF_IN) ? 1 : 0;
6085 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6087 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6088 pd.proto = h->ip6_nxt;
6091 case IPPROTO_FRAGMENT:
6092 action = pf_test_fragment(&r, dir, kif, m, h,
6094 if (action == PF_DROP)
6095 REASON_SET(&reason, PFRES_FRAG);
6097 case IPPROTO_ROUTING: {
6098 struct ip6_rthdr rthdr;
6101 DPFPRINTF(PF_DEBUG_MISC,
6102 ("pf: IPv6 more than one rthdr\n"));
6104 REASON_SET(&reason, PFRES_IPOPTIONS);
6108 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6110 DPFPRINTF(PF_DEBUG_MISC,
6111 ("pf: IPv6 short rthdr\n"));
6113 REASON_SET(&reason, PFRES_SHORT);
6117 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6118 DPFPRINTF(PF_DEBUG_MISC,
6119 ("pf: IPv6 rthdr0\n"));
6121 REASON_SET(&reason, PFRES_IPOPTIONS);
6128 case IPPROTO_HOPOPTS:
6129 case IPPROTO_DSTOPTS: {
6130 /* get next header and header length */
6131 struct ip6_ext opt6;
6133 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6134 NULL, &reason, pd.af)) {
6135 DPFPRINTF(PF_DEBUG_MISC,
6136 ("pf: IPv6 short opt\n"));
6141 if (pd.proto == IPPROTO_AH)
6142 off += (opt6.ip6e_len + 2) * 4;
6144 off += (opt6.ip6e_len + 1) * 8;
6145 pd.proto = opt6.ip6e_nxt;
6146 /* goto the next header */
6153 } while (!terminal);
6155 /* if there's no routing header, use unmodified mbuf for checksumming */
6165 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6166 &action, &reason, AF_INET6)) {
6167 log = action != PF_PASS;
6170 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6171 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6172 if (action == PF_DROP)
6174 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6176 if (action == PF_PASS) {
6177 if (pfsync_update_state_ptr != NULL)
6178 pfsync_update_state_ptr(s);
6182 } else if (s == NULL)
6183 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6192 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6193 &action, &reason, AF_INET6)) {
6194 log = action != PF_PASS;
6197 if (uh.uh_dport == 0 ||
6198 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6199 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6201 REASON_SET(&reason, PFRES_SHORT);
6204 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6205 if (action == PF_PASS) {
6206 if (pfsync_update_state_ptr != NULL)
6207 pfsync_update_state_ptr(s);
6211 } else if (s == NULL)
6212 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6217 case IPPROTO_ICMP: {
6219 DPFPRINTF(PF_DEBUG_MISC,
6220 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6224 case IPPROTO_ICMPV6: {
6225 struct icmp6_hdr ih;
6228 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6229 &action, &reason, AF_INET6)) {
6230 log = action != PF_PASS;
6233 action = pf_test_state_icmp(&s, dir, kif,
6234 m, off, h, &pd, &reason);
6235 if (action == PF_PASS) {
6236 if (pfsync_update_state_ptr != NULL)
6237 pfsync_update_state_ptr(s);
6241 } else if (s == NULL)
6242 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6248 action = pf_test_state_other(&s, dir, kif, m, &pd);
6249 if (action == PF_PASS) {
6250 if (pfsync_update_state_ptr != NULL)
6251 pfsync_update_state_ptr(s);
6255 } else if (s == NULL)
6256 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6268 /* handle dangerous IPv6 extension headers. */
6269 if (action == PF_PASS && rh_cnt &&
6270 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6272 REASON_SET(&reason, PFRES_IPOPTIONS);
6274 DPFPRINTF(PF_DEBUG_MISC,
6275 ("pf: dropping packet with dangerous v6 headers\n"));
6278 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6280 REASON_SET(&reason, PFRES_MEMORY);
6282 if (r->rtableid >= 0)
6283 M_SETFIB(m, r->rtableid);
6286 if (action == PF_PASS && r->qid) {
6287 if (pd.pf_mtag == NULL &&
6288 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6290 REASON_SET(&reason, PFRES_MEMORY);
6292 if (pd.tos & IPTOS_LOWDELAY)
6293 pd.pf_mtag->qid = r->pqid;
6295 pd.pf_mtag->qid = r->qid;
6296 /* add hints for ecn */
6297 pd.pf_mtag->hdr = h;
6301 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6302 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6303 (s->nat_rule.ptr->action == PF_RDR ||
6304 s->nat_rule.ptr->action == PF_BINAT) &&
6305 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6306 m->m_flags |= M_SKIP_FIREWALL;
6308 /* XXX: Anybody working on it?! */
6310 printf("pf: divert(9) is not supported for IPv6\n");
6315 if (s != NULL && s->nat_rule.ptr != NULL &&
6316 s->nat_rule.ptr->log & PF_LOG_ALL)
6317 lr = s->nat_rule.ptr;
6320 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6324 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6325 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6327 if (action == PF_PASS || r->action == PF_DROP) {
6328 dirndx = (dir == PF_OUT);
6329 r->packets[dirndx]++;
6330 r->bytes[dirndx] += pd.tot_len;
6332 a->packets[dirndx]++;
6333 a->bytes[dirndx] += pd.tot_len;
6336 if (s->nat_rule.ptr != NULL) {
6337 s->nat_rule.ptr->packets[dirndx]++;
6338 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6340 if (s->src_node != NULL) {
6341 s->src_node->packets[dirndx]++;
6342 s->src_node->bytes[dirndx] += pd.tot_len;
6344 if (s->nat_src_node != NULL) {
6345 s->nat_src_node->packets[dirndx]++;
6346 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6348 dirndx = (dir == s->direction) ? 0 : 1;
6349 s->packets[dirndx]++;
6350 s->bytes[dirndx] += pd.tot_len;
6353 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6354 if (nr != NULL && r == &V_pf_default_rule)
6356 if (tr->src.addr.type == PF_ADDR_TABLE)
6357 pfr_update_stats(tr->src.addr.p.tbl,
6358 (s == NULL) ? pd.src :
6359 &s->key[(s->direction == PF_IN)]->addr[0],
6360 pd.af, pd.tot_len, dir == PF_OUT,
6361 r->action == PF_PASS, tr->src.neg);
6362 if (tr->dst.addr.type == PF_ADDR_TABLE)
6363 pfr_update_stats(tr->dst.addr.p.tbl,
6364 (s == NULL) ? pd.dst :
6365 &s->key[(s->direction == PF_IN)]->addr[1],
6366 pd.af, pd.tot_len, dir == PF_OUT,
6367 r->action == PF_PASS, tr->dst.neg);
6371 case PF_SYNPROXY_DROP:
6378 /* pf_route6() returns unlocked. */
6380 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);