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_var.h>
65 #include <net/if_types.h>
66 #include <net/route.h>
67 #include <net/radix_mpath.h>
70 #include <net/pfvar.h>
71 #include <net/if_pflog.h>
72 #include <net/if_pfsync.h>
74 #include <netinet/in_pcb.h>
75 #include <netinet/in_var.h>
76 #include <netinet/ip.h>
77 #include <netinet/ip_fw.h>
78 #include <netinet/ip_icmp.h>
79 #include <netinet/icmp_var.h>
80 #include <netinet/ip_var.h>
81 #include <netinet/tcp.h>
82 #include <netinet/tcp_fsm.h>
83 #include <netinet/tcp_seq.h>
84 #include <netinet/tcp_timer.h>
85 #include <netinet/tcp_var.h>
86 #include <netinet/udp.h>
87 #include <netinet/udp_var.h>
89 #include <netpfil/ipfw/ip_fw_private.h> /* XXX: only for DIR_IN/DIR_OUT */
92 #include <netinet/ip6.h>
93 #include <netinet/icmp6.h>
94 #include <netinet6/nd6.h>
95 #include <netinet6/ip6_var.h>
96 #include <netinet6/in6_pcb.h>
99 #include <machine/in_cksum.h>
100 #include <security/mac/mac_framework.h>
102 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
109 VNET_DEFINE(struct pf_altqqueue, pf_altqs[2]);
110 VNET_DEFINE(struct pf_palist, pf_pabuf);
111 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_active);
112 VNET_DEFINE(struct pf_altqqueue *, pf_altqs_inactive);
113 VNET_DEFINE(struct pf_status, pf_status);
115 VNET_DEFINE(u_int32_t, ticket_altqs_active);
116 VNET_DEFINE(u_int32_t, ticket_altqs_inactive);
117 VNET_DEFINE(int, altqs_inactive_open);
118 VNET_DEFINE(u_int32_t, ticket_pabuf);
120 VNET_DEFINE(MD5_CTX, pf_tcp_secret_ctx);
121 #define V_pf_tcp_secret_ctx VNET(pf_tcp_secret_ctx)
122 VNET_DEFINE(u_char, pf_tcp_secret[16]);
123 #define V_pf_tcp_secret VNET(pf_tcp_secret)
124 VNET_DEFINE(int, pf_tcp_secret_init);
125 #define V_pf_tcp_secret_init VNET(pf_tcp_secret_init)
126 VNET_DEFINE(int, pf_tcp_iss_off);
127 #define V_pf_tcp_iss_off VNET(pf_tcp_iss_off)
130 * Queue for pf_intr() sends.
132 static MALLOC_DEFINE(M_PFTEMP, "pf_temp", "pf(4) temporary allocations");
133 struct pf_send_entry {
134 STAILQ_ENTRY(pf_send_entry) pfse_next;
151 #define pfse_icmp_type u.icmpopts.type
152 #define pfse_icmp_code u.icmpopts.code
153 #define pfse_icmp_mtu u.icmpopts.mtu
156 STAILQ_HEAD(pf_send_head, pf_send_entry);
157 static VNET_DEFINE(struct pf_send_head, pf_sendqueue);
158 #define V_pf_sendqueue VNET(pf_sendqueue)
160 static struct mtx pf_sendqueue_mtx;
161 #define PF_SENDQ_LOCK() mtx_lock(&pf_sendqueue_mtx)
162 #define PF_SENDQ_UNLOCK() mtx_unlock(&pf_sendqueue_mtx)
165 * Queue for pf_overload_task() tasks.
167 struct pf_overload_entry {
168 SLIST_ENTRY(pf_overload_entry) next;
172 struct pf_rule *rule;
175 SLIST_HEAD(pf_overload_head, pf_overload_entry);
176 static VNET_DEFINE(struct pf_overload_head, pf_overloadqueue);
177 #define V_pf_overloadqueue VNET(pf_overloadqueue)
178 static VNET_DEFINE(struct task, pf_overloadtask);
179 #define V_pf_overloadtask VNET(pf_overloadtask)
181 static struct mtx pf_overloadqueue_mtx;
182 #define PF_OVERLOADQ_LOCK() mtx_lock(&pf_overloadqueue_mtx)
183 #define PF_OVERLOADQ_UNLOCK() mtx_unlock(&pf_overloadqueue_mtx)
185 VNET_DEFINE(struct pf_rulequeue, pf_unlinked_rules);
186 struct mtx pf_unlnkdrules_mtx;
188 static VNET_DEFINE(uma_zone_t, pf_sources_z);
189 #define V_pf_sources_z VNET(pf_sources_z)
190 static VNET_DEFINE(uma_zone_t, pf_mtag_z);
191 #define V_pf_mtag_z VNET(pf_mtag_z)
192 VNET_DEFINE(uma_zone_t, pf_state_z);
193 VNET_DEFINE(uma_zone_t, pf_state_key_z);
195 VNET_DEFINE(uint64_t, pf_stateid[MAXCPU]);
196 #define PFID_CPUBITS 8
197 #define PFID_CPUSHIFT (sizeof(uint64_t) * NBBY - PFID_CPUBITS)
198 #define PFID_CPUMASK ((uint64_t)((1 << PFID_CPUBITS) - 1) << PFID_CPUSHIFT)
199 #define PFID_MAXID (~PFID_CPUMASK)
200 CTASSERT((1 << PFID_CPUBITS) > MAXCPU);
202 static void pf_src_tree_remove_state(struct pf_state *);
203 static void pf_init_threshold(struct pf_threshold *, u_int32_t,
205 static void pf_add_threshold(struct pf_threshold *);
206 static int pf_check_threshold(struct pf_threshold *);
208 static void pf_change_ap(struct pf_addr *, u_int16_t *,
209 u_int16_t *, u_int16_t *, struct pf_addr *,
210 u_int16_t, u_int8_t, sa_family_t);
211 static int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
212 struct tcphdr *, struct pf_state_peer *);
213 static int pf_icmp_mapping(struct pf_pdesc *, uint8_t, int *,
214 int *, uint16_t *, uint16_t *);
215 static void pf_change_icmp(struct pf_addr *, u_int16_t *,
216 struct pf_addr *, struct pf_addr *, u_int16_t,
217 u_int16_t *, u_int16_t *, u_int16_t *,
218 u_int16_t *, u_int8_t, sa_family_t);
219 static void pf_send_tcp(struct mbuf *,
220 const struct pf_rule *, sa_family_t,
221 const struct pf_addr *, const struct pf_addr *,
222 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
223 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
224 u_int16_t, struct ifnet *);
225 static void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
226 sa_family_t, struct pf_rule *);
227 static void pf_detach_state(struct pf_state *);
228 static int pf_state_key_attach(struct pf_state_key *,
229 struct pf_state_key *, struct pf_state *);
230 static void pf_state_key_detach(struct pf_state *, int);
231 static int pf_state_key_ctor(void *, int, void *, int);
232 static u_int32_t pf_tcp_iss(struct pf_pdesc *);
233 static int pf_test_rule(struct pf_rule **, struct pf_state **,
234 int, struct pfi_kif *, struct mbuf *, int,
235 struct pf_pdesc *, struct pf_rule **,
236 struct pf_ruleset **, struct inpcb *);
237 static int pf_create_state(struct pf_rule *, struct pf_rule *,
238 struct pf_rule *, struct pf_pdesc *,
239 struct pf_src_node *, struct pf_state_key *,
240 struct pf_state_key *, struct mbuf *, int,
241 u_int16_t, u_int16_t, int *, struct pfi_kif *,
242 struct pf_state **, int, u_int16_t, u_int16_t,
244 static int pf_test_fragment(struct pf_rule **, int,
245 struct pfi_kif *, struct mbuf *, void *,
246 struct pf_pdesc *, struct pf_rule **,
247 struct pf_ruleset **);
248 static int pf_tcp_track_full(struct pf_state_peer *,
249 struct pf_state_peer *, struct pf_state **,
250 struct pfi_kif *, struct mbuf *, int,
251 struct pf_pdesc *, u_short *, int *);
252 static int pf_tcp_track_sloppy(struct pf_state_peer *,
253 struct pf_state_peer *, struct pf_state **,
254 struct pf_pdesc *, u_short *);
255 static int pf_test_state_tcp(struct pf_state **, int,
256 struct pfi_kif *, struct mbuf *, int,
257 void *, struct pf_pdesc *, u_short *);
258 static int pf_test_state_udp(struct pf_state **, int,
259 struct pfi_kif *, struct mbuf *, int,
260 void *, struct pf_pdesc *);
261 static int pf_icmp_state_lookup(struct pf_state_key_cmp *,
262 struct pf_pdesc *, struct pf_state **, struct mbuf *,
263 int, struct pfi_kif *, uint16_t, uint16_t,
265 static int pf_test_state_icmp(struct pf_state **, int,
266 struct pfi_kif *, struct mbuf *, int,
267 void *, struct pf_pdesc *, u_short *);
268 static int pf_test_state_other(struct pf_state **, int,
269 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
270 static u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
272 static u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
274 static u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
276 static void pf_set_rt_ifp(struct pf_state *,
278 static int pf_check_proto_cksum(struct mbuf *, int, int,
279 u_int8_t, sa_family_t);
280 static void pf_print_state_parts(struct pf_state *,
281 struct pf_state_key *, struct pf_state_key *);
282 static int pf_addr_wrap_neq(struct pf_addr_wrap *,
283 struct pf_addr_wrap *);
284 static struct pf_state *pf_find_state(struct pfi_kif *,
285 struct pf_state_key_cmp *, u_int);
286 static int pf_src_connlimit(struct pf_state **);
287 static void pf_overload_task(void *v, int pending);
288 static int pf_insert_src_node(struct pf_src_node **,
289 struct pf_rule *, struct pf_addr *, sa_family_t);
290 static u_int pf_purge_expired_states(u_int, int);
291 static void pf_purge_unlinked_rules(void);
292 static int pf_mtag_init(void *, int, int);
293 static void pf_mtag_free(struct m_tag *);
295 static void pf_route(struct mbuf **, struct pf_rule *, int,
296 struct ifnet *, struct pf_state *,
300 static void pf_change_a6(struct pf_addr *, u_int16_t *,
301 struct pf_addr *, u_int8_t);
302 static void pf_route6(struct mbuf **, struct pf_rule *, int,
303 struct ifnet *, struct pf_state *,
307 int in4_cksum(struct mbuf *m, u_int8_t nxt, int off, int len);
309 VNET_DECLARE(int, pf_end_threads);
311 VNET_DEFINE(struct pf_limit, pf_limits[PF_LIMIT_MAX]);
313 enum { PF_ICMP_MULTI_NONE, PF_ICMP_MULTI_SOLICITED, PF_ICMP_MULTI_LINK };
315 #define PACKET_LOOPED(pd) ((pd)->pf_mtag && \
316 (pd)->pf_mtag->flags & PF_PACKET_LOOPED)
318 #define STATE_LOOKUP(i, k, d, s, pd) \
320 (s) = pf_find_state((i), (k), (d)); \
323 if (PACKET_LOOPED(pd)) \
325 if ((d) == PF_OUT && \
326 (((s)->rule.ptr->rt == PF_ROUTETO && \
327 (s)->rule.ptr->direction == PF_OUT) || \
328 ((s)->rule.ptr->rt == PF_REPLYTO && \
329 (s)->rule.ptr->direction == PF_IN)) && \
330 (s)->rt_kif != NULL && \
331 (s)->rt_kif != (i)) \
335 #define BOUND_IFACE(r, k) \
336 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : V_pfi_all
338 #define STATE_INC_COUNTERS(s) \
340 counter_u64_add(s->rule.ptr->states_cur, 1); \
341 counter_u64_add(s->rule.ptr->states_tot, 1); \
342 if (s->anchor.ptr != NULL) { \
343 counter_u64_add(s->anchor.ptr->states_cur, 1); \
344 counter_u64_add(s->anchor.ptr->states_tot, 1); \
346 if (s->nat_rule.ptr != NULL) { \
347 counter_u64_add(s->nat_rule.ptr->states_cur, 1);\
348 counter_u64_add(s->nat_rule.ptr->states_tot, 1);\
352 #define STATE_DEC_COUNTERS(s) \
354 if (s->nat_rule.ptr != NULL) \
355 counter_u64_add(s->nat_rule.ptr->states_cur, -1);\
356 if (s->anchor.ptr != NULL) \
357 counter_u64_add(s->anchor.ptr->states_cur, -1); \
358 counter_u64_add(s->rule.ptr->states_cur, -1); \
361 static MALLOC_DEFINE(M_PFHASH, "pf_hash", "pf(4) hash header structures");
362 VNET_DEFINE(struct pf_keyhash *, pf_keyhash);
363 VNET_DEFINE(struct pf_idhash *, pf_idhash);
364 VNET_DEFINE(struct pf_srchash *, pf_srchash);
366 SYSCTL_NODE(_net, OID_AUTO, pf, CTLFLAG_RW, 0, "pf(4)");
369 u_long pf_srchashmask;
370 static u_long pf_hashsize;
371 static u_long pf_srchashsize;
373 SYSCTL_UINT(_net_pf, OID_AUTO, states_hashsize, CTLFLAG_RDTUN,
374 &pf_hashsize, 0, "Size of pf(4) states hashtable");
375 SYSCTL_UINT(_net_pf, OID_AUTO, source_nodes_hashsize, CTLFLAG_RDTUN,
376 &pf_srchashsize, 0, "Size of pf(4) source nodes hashtable");
378 VNET_DEFINE(void *, pf_swi_cookie);
380 VNET_DEFINE(uint32_t, pf_hashseed);
381 #define V_pf_hashseed VNET(pf_hashseed)
383 static __inline uint32_t
384 pf_hashkey(struct pf_state_key *sk)
388 h = jenkins_hash32((uint32_t *)sk,
389 sizeof(struct pf_state_key_cmp)/sizeof(uint32_t),
392 return (h & pf_hashmask);
395 static __inline uint32_t
396 pf_hashsrc(struct pf_addr *addr, sa_family_t af)
402 h = jenkins_hash32((uint32_t *)&addr->v4,
403 sizeof(addr->v4)/sizeof(uint32_t), V_pf_hashseed);
406 h = jenkins_hash32((uint32_t *)&addr->v6,
407 sizeof(addr->v6)/sizeof(uint32_t), V_pf_hashseed);
410 panic("%s: unknown address family %u", __func__, af);
413 return (h & pf_srchashmask);
418 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
423 dst->addr32[0] = src->addr32[0];
427 dst->addr32[0] = src->addr32[0];
428 dst->addr32[1] = src->addr32[1];
429 dst->addr32[2] = src->addr32[2];
430 dst->addr32[3] = src->addr32[3];
437 pf_init_threshold(struct pf_threshold *threshold,
438 u_int32_t limit, u_int32_t seconds)
440 threshold->limit = limit * PF_THRESHOLD_MULT;
441 threshold->seconds = seconds;
442 threshold->count = 0;
443 threshold->last = time_uptime;
447 pf_add_threshold(struct pf_threshold *threshold)
449 u_int32_t t = time_uptime, diff = t - threshold->last;
451 if (diff >= threshold->seconds)
452 threshold->count = 0;
454 threshold->count -= threshold->count * diff /
456 threshold->count += PF_THRESHOLD_MULT;
461 pf_check_threshold(struct pf_threshold *threshold)
463 return (threshold->count > threshold->limit);
467 pf_src_connlimit(struct pf_state **state)
469 struct pf_overload_entry *pfoe;
472 PF_STATE_LOCK_ASSERT(*state);
474 (*state)->src_node->conn++;
475 (*state)->src.tcp_est = 1;
476 pf_add_threshold(&(*state)->src_node->conn_rate);
478 if ((*state)->rule.ptr->max_src_conn &&
479 (*state)->rule.ptr->max_src_conn <
480 (*state)->src_node->conn) {
481 V_pf_status.lcounters[LCNT_SRCCONN]++;
485 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
486 pf_check_threshold(&(*state)->src_node->conn_rate)) {
487 V_pf_status.lcounters[LCNT_SRCCONNRATE]++;
494 /* Kill this state. */
495 (*state)->timeout = PFTM_PURGE;
496 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
498 if ((*state)->rule.ptr->overload_tbl == NULL)
501 /* Schedule overloading and flushing task. */
502 pfoe = malloc(sizeof(*pfoe), M_PFTEMP, M_NOWAIT);
504 return (1); /* too bad :( */
506 bcopy(&(*state)->src_node->addr, &pfoe->addr, sizeof(pfoe->addr));
507 pfoe->af = (*state)->key[PF_SK_WIRE]->af;
508 pfoe->rule = (*state)->rule.ptr;
509 pfoe->dir = (*state)->direction;
511 SLIST_INSERT_HEAD(&V_pf_overloadqueue, pfoe, next);
512 PF_OVERLOADQ_UNLOCK();
513 taskqueue_enqueue(taskqueue_swi, &V_pf_overloadtask);
519 pf_overload_task(void *v, int pending)
521 struct pf_overload_head queue;
523 struct pf_overload_entry *pfoe, *pfoe1;
526 CURVNET_SET((struct vnet *)v);
529 queue = V_pf_overloadqueue;
530 SLIST_INIT(&V_pf_overloadqueue);
531 PF_OVERLOADQ_UNLOCK();
533 bzero(&p, sizeof(p));
534 SLIST_FOREACH(pfoe, &queue, next) {
535 V_pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
536 if (V_pf_status.debug >= PF_DEBUG_MISC) {
537 printf("%s: blocking address ", __func__);
538 pf_print_host(&pfoe->addr, 0, pfoe->af);
542 p.pfra_af = pfoe->af;
547 p.pfra_ip4addr = pfoe->addr.v4;
553 p.pfra_ip6addr = pfoe->addr.v6;
559 pfr_insert_kentry(pfoe->rule->overload_tbl, &p, time_second);
564 * Remove those entries, that don't need flushing.
566 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
567 if (pfoe->rule->flush == 0) {
568 SLIST_REMOVE(&queue, pfoe, pf_overload_entry, next);
569 free(pfoe, M_PFTEMP);
571 V_pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
573 /* If nothing to flush, return. */
574 if (SLIST_EMPTY(&queue)) {
579 for (int i = 0; i <= pf_hashmask; i++) {
580 struct pf_idhash *ih = &V_pf_idhash[i];
581 struct pf_state_key *sk;
585 LIST_FOREACH(s, &ih->states, entry) {
586 sk = s->key[PF_SK_WIRE];
587 SLIST_FOREACH(pfoe, &queue, next)
588 if (sk->af == pfoe->af &&
589 ((pfoe->rule->flush & PF_FLUSH_GLOBAL) ||
590 pfoe->rule == s->rule.ptr) &&
591 ((pfoe->dir == PF_OUT &&
592 PF_AEQ(&pfoe->addr, &sk->addr[1], sk->af)) ||
593 (pfoe->dir == PF_IN &&
594 PF_AEQ(&pfoe->addr, &sk->addr[0], sk->af)))) {
595 s->timeout = PFTM_PURGE;
596 s->src.state = s->dst.state = TCPS_CLOSED;
600 PF_HASHROW_UNLOCK(ih);
602 SLIST_FOREACH_SAFE(pfoe, &queue, next, pfoe1)
603 free(pfoe, M_PFTEMP);
604 if (V_pf_status.debug >= PF_DEBUG_MISC)
605 printf("%s: %u states killed", __func__, killed);
611 * Can return locked on failure, so that we can consistently
612 * allocate and insert a new one.
615 pf_find_src_node(struct pf_addr *src, struct pf_rule *rule, sa_family_t af,
618 struct pf_srchash *sh;
619 struct pf_src_node *n;
621 V_pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
623 sh = &V_pf_srchash[pf_hashsrc(src, af)];
625 LIST_FOREACH(n, &sh->nodes, entry)
626 if (n->rule.ptr == rule && n->af == af &&
627 ((af == AF_INET && n->addr.v4.s_addr == src->v4.s_addr) ||
628 (af == AF_INET6 && bcmp(&n->addr, src, sizeof(*src)) == 0)))
630 if (n != NULL || returnlocked == 0)
631 PF_HASHROW_UNLOCK(sh);
637 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
638 struct pf_addr *src, sa_family_t af)
641 KASSERT((rule->rule_flag & PFRULE_RULESRCTRACK ||
642 rule->rpool.opts & PF_POOL_STICKYADDR),
643 ("%s for non-tracking rule %p", __func__, rule));
646 *sn = pf_find_src_node(src, rule, af, 1);
649 struct pf_srchash *sh = &V_pf_srchash[pf_hashsrc(src, af)];
651 PF_HASHROW_ASSERT(sh);
653 if (!rule->max_src_nodes ||
654 counter_u64_fetch(rule->src_nodes) < rule->max_src_nodes)
655 (*sn) = uma_zalloc(V_pf_sources_z, M_NOWAIT | M_ZERO);
657 V_pf_status.lcounters[LCNT_SRCNODES]++;
659 PF_HASHROW_UNLOCK(sh);
663 pf_init_threshold(&(*sn)->conn_rate,
664 rule->max_src_conn_rate.limit,
665 rule->max_src_conn_rate.seconds);
668 (*sn)->rule.ptr = rule;
669 PF_ACPY(&(*sn)->addr, src, af);
670 LIST_INSERT_HEAD(&sh->nodes, *sn, entry);
671 (*sn)->creation = time_uptime;
672 (*sn)->ruletype = rule->action;
673 if ((*sn)->rule.ptr != NULL)
674 counter_u64_add((*sn)->rule.ptr->src_nodes, 1);
675 PF_HASHROW_UNLOCK(sh);
676 V_pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
677 V_pf_status.src_nodes++;
679 if (rule->max_src_states &&
680 (*sn)->states >= rule->max_src_states) {
681 V_pf_status.lcounters[LCNT_SRCSTATES]++;
689 pf_unlink_src_node_locked(struct pf_src_node *src)
692 struct pf_srchash *sh;
694 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
695 PF_HASHROW_ASSERT(sh);
697 LIST_REMOVE(src, entry);
699 counter_u64_add(src->rule.ptr->src_nodes, -1);
700 V_pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
701 V_pf_status.src_nodes--;
705 pf_unlink_src_node(struct pf_src_node *src)
707 struct pf_srchash *sh;
709 sh = &V_pf_srchash[pf_hashsrc(&src->addr, src->af)];
711 pf_unlink_src_node_locked(src);
712 PF_HASHROW_UNLOCK(sh);
716 pf_free_src_node(struct pf_src_node *sn)
719 KASSERT(sn->states == 0, ("%s: %p has refs", __func__, sn));
720 uma_zfree(V_pf_sources_z, sn);
724 pf_free_src_nodes(struct pf_src_node_list *head)
726 struct pf_src_node *sn, *tmp;
729 LIST_FOREACH_SAFE(sn, head, entry, tmp) {
730 pf_free_src_node(sn);
737 /* Data storage structures initialization. */
741 struct pf_keyhash *kh;
742 struct pf_idhash *ih;
743 struct pf_srchash *sh;
746 TUNABLE_ULONG_FETCH("net.pf.states_hashsize", &pf_hashsize);
747 if (pf_hashsize == 0 || !powerof2(pf_hashsize))
748 pf_hashsize = PF_HASHSIZ;
749 TUNABLE_ULONG_FETCH("net.pf.source_nodes_hashsize", &pf_srchashsize);
750 if (pf_srchashsize == 0 || !powerof2(pf_srchashsize))
751 pf_srchashsize = PF_HASHSIZ / 4;
753 V_pf_hashseed = arc4random();
755 /* States and state keys storage. */
756 V_pf_state_z = uma_zcreate("pf states", sizeof(struct pf_state),
757 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
758 V_pf_limits[PF_LIMIT_STATES].zone = V_pf_state_z;
759 uma_zone_set_max(V_pf_state_z, PFSTATE_HIWAT);
760 uma_zone_set_warning(V_pf_state_z, "PF states limit reached");
762 V_pf_state_key_z = uma_zcreate("pf state keys",
763 sizeof(struct pf_state_key), pf_state_key_ctor, NULL, NULL, NULL,
765 V_pf_keyhash = malloc(pf_hashsize * sizeof(struct pf_keyhash),
766 M_PFHASH, M_WAITOK | M_ZERO);
767 V_pf_idhash = malloc(pf_hashsize * sizeof(struct pf_idhash),
768 M_PFHASH, M_WAITOK | M_ZERO);
769 pf_hashmask = pf_hashsize - 1;
770 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
772 mtx_init(&kh->lock, "pf_keyhash", NULL, MTX_DEF | MTX_DUPOK);
773 mtx_init(&ih->lock, "pf_idhash", NULL, MTX_DEF);
777 V_pf_sources_z = uma_zcreate("pf source nodes",
778 sizeof(struct pf_src_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
780 V_pf_limits[PF_LIMIT_SRC_NODES].zone = V_pf_sources_z;
781 uma_zone_set_max(V_pf_sources_z, PFSNODE_HIWAT);
782 uma_zone_set_warning(V_pf_sources_z, "PF source nodes limit reached");
783 V_pf_srchash = malloc(pf_srchashsize * sizeof(struct pf_srchash),
784 M_PFHASH, M_WAITOK|M_ZERO);
785 pf_srchashmask = pf_srchashsize - 1;
786 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++)
787 mtx_init(&sh->lock, "pf_srchash", NULL, MTX_DEF);
790 TAILQ_INIT(&V_pf_altqs[0]);
791 TAILQ_INIT(&V_pf_altqs[1]);
792 TAILQ_INIT(&V_pf_pabuf);
793 V_pf_altqs_active = &V_pf_altqs[0];
794 V_pf_altqs_inactive = &V_pf_altqs[1];
797 V_pf_mtag_z = uma_zcreate("pf mtags", sizeof(struct m_tag) +
798 sizeof(struct pf_mtag), NULL, NULL, pf_mtag_init, NULL,
801 /* Send & overload+flush queues. */
802 STAILQ_INIT(&V_pf_sendqueue);
803 SLIST_INIT(&V_pf_overloadqueue);
804 TASK_INIT(&V_pf_overloadtask, 0, pf_overload_task, curvnet);
805 mtx_init(&pf_sendqueue_mtx, "pf send queue", NULL, MTX_DEF);
806 mtx_init(&pf_overloadqueue_mtx, "pf overload/flush queue", NULL,
809 /* Unlinked, but may be referenced rules. */
810 TAILQ_INIT(&V_pf_unlinked_rules);
811 mtx_init(&pf_unlnkdrules_mtx, "pf unlinked rules", NULL, MTX_DEF);
817 struct pf_keyhash *kh;
818 struct pf_idhash *ih;
819 struct pf_srchash *sh;
820 struct pf_send_entry *pfse, *next;
823 for (i = 0, kh = V_pf_keyhash, ih = V_pf_idhash; i <= pf_hashmask;
825 KASSERT(LIST_EMPTY(&kh->keys), ("%s: key hash not empty",
827 KASSERT(LIST_EMPTY(&ih->states), ("%s: id hash not empty",
829 mtx_destroy(&kh->lock);
830 mtx_destroy(&ih->lock);
832 free(V_pf_keyhash, M_PFHASH);
833 free(V_pf_idhash, M_PFHASH);
835 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
836 KASSERT(LIST_EMPTY(&sh->nodes),
837 ("%s: source node hash not empty", __func__));
838 mtx_destroy(&sh->lock);
840 free(V_pf_srchash, M_PFHASH);
842 STAILQ_FOREACH_SAFE(pfse, &V_pf_sendqueue, pfse_next, next) {
843 m_freem(pfse->pfse_m);
844 free(pfse, M_PFTEMP);
847 mtx_destroy(&pf_sendqueue_mtx);
848 mtx_destroy(&pf_overloadqueue_mtx);
849 mtx_destroy(&pf_unlnkdrules_mtx);
851 uma_zdestroy(V_pf_mtag_z);
852 uma_zdestroy(V_pf_sources_z);
853 uma_zdestroy(V_pf_state_z);
854 uma_zdestroy(V_pf_state_key_z);
858 pf_mtag_init(void *mem, int size, int how)
862 t = (struct m_tag *)mem;
863 t->m_tag_cookie = MTAG_ABI_COMPAT;
864 t->m_tag_id = PACKET_TAG_PF;
865 t->m_tag_len = sizeof(struct pf_mtag);
866 t->m_tag_free = pf_mtag_free;
872 pf_mtag_free(struct m_tag *t)
875 uma_zfree(V_pf_mtag_z, t);
879 pf_get_mtag(struct mbuf *m)
883 if ((mtag = m_tag_find(m, PACKET_TAG_PF, NULL)) != NULL)
884 return ((struct pf_mtag *)(mtag + 1));
886 mtag = uma_zalloc(V_pf_mtag_z, M_NOWAIT);
889 bzero(mtag + 1, sizeof(struct pf_mtag));
890 m_tag_prepend(m, mtag);
892 return ((struct pf_mtag *)(mtag + 1));
896 pf_state_key_attach(struct pf_state_key *skw, struct pf_state_key *sks,
899 struct pf_keyhash *khs, *khw, *kh;
900 struct pf_state_key *sk, *cur;
901 struct pf_state *si, *olds = NULL;
904 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
905 KASSERT(s->key[PF_SK_WIRE] == NULL, ("%s: state has key", __func__));
906 KASSERT(s->key[PF_SK_STACK] == NULL, ("%s: state has key", __func__));
909 * We need to lock hash slots of both keys. To avoid deadlock
910 * we always lock the slot with lower address first. Unlock order
913 * We also need to lock ID hash slot before dropping key
914 * locks. On success we return with ID hash slot locked.
918 khs = khw = &V_pf_keyhash[pf_hashkey(skw)];
919 PF_HASHROW_LOCK(khs);
921 khs = &V_pf_keyhash[pf_hashkey(sks)];
922 khw = &V_pf_keyhash[pf_hashkey(skw)];
924 PF_HASHROW_LOCK(khs);
925 } else if (khs < khw) {
926 PF_HASHROW_LOCK(khs);
927 PF_HASHROW_LOCK(khw);
929 PF_HASHROW_LOCK(khw);
930 PF_HASHROW_LOCK(khs);
934 #define KEYS_UNLOCK() do { \
936 PF_HASHROW_UNLOCK(khs); \
937 PF_HASHROW_UNLOCK(khw); \
939 PF_HASHROW_UNLOCK(khs); \
943 * First run: start with wire key.
950 LIST_FOREACH(cur, &kh->keys, entry)
951 if (bcmp(cur, sk, sizeof(struct pf_state_key_cmp)) == 0)
955 /* Key exists. Check for same kif, if none, add to key. */
956 TAILQ_FOREACH(si, &cur->states[idx], key_list[idx]) {
957 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(si)];
960 if (si->kif == s->kif &&
961 si->direction == s->direction) {
962 if (sk->proto == IPPROTO_TCP &&
963 si->src.state >= TCPS_FIN_WAIT_2 &&
964 si->dst.state >= TCPS_FIN_WAIT_2) {
966 * New state matches an old >FIN_WAIT_2
967 * state. We can't drop key hash locks,
968 * thus we can't unlink it properly.
970 * As a workaround we drop it into
971 * TCPS_CLOSED state, schedule purge
972 * ASAP and push it into the very end
973 * of the slot TAILQ, so that it won't
974 * conflict with our new state.
976 si->src.state = si->dst.state =
978 si->timeout = PFTM_PURGE;
981 if (V_pf_status.debug >= PF_DEBUG_MISC) {
982 printf("pf: %s key attach "
984 (idx == PF_SK_WIRE) ?
987 pf_print_state_parts(s,
988 (idx == PF_SK_WIRE) ?
990 (idx == PF_SK_STACK) ?
992 printf(", existing: ");
993 pf_print_state_parts(si,
994 (idx == PF_SK_WIRE) ?
996 (idx == PF_SK_STACK) ?
1000 PF_HASHROW_UNLOCK(ih);
1002 uma_zfree(V_pf_state_key_z, sk);
1003 if (idx == PF_SK_STACK)
1005 return (EEXIST); /* collision! */
1008 PF_HASHROW_UNLOCK(ih);
1010 uma_zfree(V_pf_state_key_z, sk);
1013 LIST_INSERT_HEAD(&kh->keys, sk, entry);
1018 /* List is sorted, if-bound states before floating. */
1019 if (s->kif == V_pfi_all)
1020 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], s, key_list[idx]);
1022 TAILQ_INSERT_HEAD(&s->key[idx]->states[idx], s, key_list[idx]);
1025 TAILQ_REMOVE(&s->key[idx]->states[idx], olds, key_list[idx]);
1026 TAILQ_INSERT_TAIL(&s->key[idx]->states[idx], olds,
1032 * Attach done. See how should we (or should not?)
1033 * attach a second key.
1036 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1040 } else if (sks != NULL) {
1042 * Continue attaching with stack key.
1054 KASSERT(s->key[PF_SK_WIRE] != NULL && s->key[PF_SK_STACK] != NULL,
1055 ("%s failure", __func__));
1062 pf_detach_state(struct pf_state *s)
1064 struct pf_state_key *sks = s->key[PF_SK_STACK];
1065 struct pf_keyhash *kh;
1068 kh = &V_pf_keyhash[pf_hashkey(sks)];
1069 PF_HASHROW_LOCK(kh);
1070 if (s->key[PF_SK_STACK] != NULL)
1071 pf_state_key_detach(s, PF_SK_STACK);
1073 * If both point to same key, then we are done.
1075 if (sks == s->key[PF_SK_WIRE]) {
1076 pf_state_key_detach(s, PF_SK_WIRE);
1077 PF_HASHROW_UNLOCK(kh);
1080 PF_HASHROW_UNLOCK(kh);
1083 if (s->key[PF_SK_WIRE] != NULL) {
1084 kh = &V_pf_keyhash[pf_hashkey(s->key[PF_SK_WIRE])];
1085 PF_HASHROW_LOCK(kh);
1086 if (s->key[PF_SK_WIRE] != NULL)
1087 pf_state_key_detach(s, PF_SK_WIRE);
1088 PF_HASHROW_UNLOCK(kh);
1093 pf_state_key_detach(struct pf_state *s, int idx)
1095 struct pf_state_key *sk = s->key[idx];
1097 struct pf_keyhash *kh = &V_pf_keyhash[pf_hashkey(sk)];
1099 PF_HASHROW_ASSERT(kh);
1101 TAILQ_REMOVE(&sk->states[idx], s, key_list[idx]);
1104 if (TAILQ_EMPTY(&sk->states[0]) && TAILQ_EMPTY(&sk->states[1])) {
1105 LIST_REMOVE(sk, entry);
1106 uma_zfree(V_pf_state_key_z, sk);
1111 pf_state_key_ctor(void *mem, int size, void *arg, int flags)
1113 struct pf_state_key *sk = mem;
1115 bzero(sk, sizeof(struct pf_state_key_cmp));
1116 TAILQ_INIT(&sk->states[PF_SK_WIRE]);
1117 TAILQ_INIT(&sk->states[PF_SK_STACK]);
1122 struct pf_state_key *
1123 pf_state_key_setup(struct pf_pdesc *pd, struct pf_addr *saddr,
1124 struct pf_addr *daddr, u_int16_t sport, u_int16_t dport)
1126 struct pf_state_key *sk;
1128 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1132 PF_ACPY(&sk->addr[pd->sidx], saddr, pd->af);
1133 PF_ACPY(&sk->addr[pd->didx], daddr, pd->af);
1134 sk->port[pd->sidx] = sport;
1135 sk->port[pd->didx] = dport;
1136 sk->proto = pd->proto;
1142 struct pf_state_key *
1143 pf_state_key_clone(struct pf_state_key *orig)
1145 struct pf_state_key *sk;
1147 sk = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
1151 bcopy(orig, sk, sizeof(struct pf_state_key_cmp));
1157 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1158 struct pf_state_key *sks, struct pf_state *s)
1160 struct pf_idhash *ih;
1161 struct pf_state *cur;
1164 KASSERT(TAILQ_EMPTY(&sks->states[0]) && TAILQ_EMPTY(&sks->states[1]),
1165 ("%s: sks not pristine", __func__));
1166 KASSERT(TAILQ_EMPTY(&skw->states[0]) && TAILQ_EMPTY(&skw->states[1]),
1167 ("%s: skw not pristine", __func__));
1168 KASSERT(s->refs == 0, ("%s: state not pristine", __func__));
1172 if (s->id == 0 && s->creatorid == 0) {
1173 /* XXX: should be atomic, but probability of collision low */
1174 if ((s->id = V_pf_stateid[curcpu]++) == PFID_MAXID)
1175 V_pf_stateid[curcpu] = 1;
1176 s->id |= (uint64_t )curcpu << PFID_CPUSHIFT;
1177 s->id = htobe64(s->id);
1178 s->creatorid = V_pf_status.hostid;
1181 /* Returns with ID locked on success. */
1182 if ((error = pf_state_key_attach(skw, sks, s)) != 0)
1185 ih = &V_pf_idhash[PF_IDHASH(s)];
1186 PF_HASHROW_ASSERT(ih);
1187 LIST_FOREACH(cur, &ih->states, entry)
1188 if (cur->id == s->id && cur->creatorid == s->creatorid)
1192 PF_HASHROW_UNLOCK(ih);
1193 if (V_pf_status.debug >= PF_DEBUG_MISC) {
1194 printf("pf: state ID collision: "
1195 "id: %016llx creatorid: %08x\n",
1196 (unsigned long long)be64toh(s->id),
1197 ntohl(s->creatorid));
1202 LIST_INSERT_HEAD(&ih->states, s, entry);
1203 /* One for keys, one for ID hash. */
1204 refcount_init(&s->refs, 2);
1206 V_pf_status.fcounters[FCNT_STATE_INSERT]++;
1207 if (pfsync_insert_state_ptr != NULL)
1208 pfsync_insert_state_ptr(s);
1210 /* Returns locked. */
1215 * Find state by ID: returns with locked row on success.
1218 pf_find_state_byid(uint64_t id, uint32_t creatorid)
1220 struct pf_idhash *ih;
1223 V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1225 ih = &V_pf_idhash[(be64toh(id) % (pf_hashmask + 1))];
1227 PF_HASHROW_LOCK(ih);
1228 LIST_FOREACH(s, &ih->states, entry)
1229 if (s->id == id && s->creatorid == creatorid)
1233 PF_HASHROW_UNLOCK(ih);
1239 * Find state by key.
1240 * Returns with ID hash slot locked on success.
1242 static struct pf_state *
1243 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir)
1245 struct pf_keyhash *kh;
1246 struct pf_state_key *sk;
1250 V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1252 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1254 PF_HASHROW_LOCK(kh);
1255 LIST_FOREACH(sk, &kh->keys, entry)
1256 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1259 PF_HASHROW_UNLOCK(kh);
1263 idx = (dir == PF_IN ? PF_SK_WIRE : PF_SK_STACK);
1265 /* List is sorted, if-bound states before floating ones. */
1266 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx])
1267 if (s->kif == V_pfi_all || s->kif == kif) {
1269 PF_HASHROW_UNLOCK(kh);
1270 if (s->timeout >= PFTM_MAX) {
1272 * State is either being processed by
1273 * pf_unlink_state() in an other thread, or
1274 * is scheduled for immediate expiry.
1281 PF_HASHROW_UNLOCK(kh);
1287 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1289 struct pf_keyhash *kh;
1290 struct pf_state_key *sk;
1291 struct pf_state *s, *ret = NULL;
1294 V_pf_status.fcounters[FCNT_STATE_SEARCH]++;
1296 kh = &V_pf_keyhash[pf_hashkey((struct pf_state_key *)key)];
1298 PF_HASHROW_LOCK(kh);
1299 LIST_FOREACH(sk, &kh->keys, entry)
1300 if (bcmp(sk, key, sizeof(struct pf_state_key_cmp)) == 0)
1303 PF_HASHROW_UNLOCK(kh);
1318 panic("%s: dir %u", __func__, dir);
1321 TAILQ_FOREACH(s, &sk->states[idx], key_list[idx]) {
1323 PF_HASHROW_UNLOCK(kh);
1337 PF_HASHROW_UNLOCK(kh);
1342 /* END state table stuff */
1345 pf_send(struct pf_send_entry *pfse)
1349 STAILQ_INSERT_TAIL(&V_pf_sendqueue, pfse, pfse_next);
1351 swi_sched(V_pf_swi_cookie, 0);
1357 struct pf_send_head queue;
1358 struct pf_send_entry *pfse, *next;
1360 CURVNET_SET((struct vnet *)v);
1363 queue = V_pf_sendqueue;
1364 STAILQ_INIT(&V_pf_sendqueue);
1367 STAILQ_FOREACH_SAFE(pfse, &queue, pfse_next, next) {
1368 switch (pfse->pfse_type) {
1371 ip_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL);
1374 icmp_error(pfse->pfse_m, pfse->pfse_icmp_type,
1375 pfse->pfse_icmp_code, 0, pfse->pfse_icmp_mtu);
1380 ip6_output(pfse->pfse_m, NULL, NULL, 0, NULL, NULL,
1384 icmp6_error(pfse->pfse_m, pfse->pfse_icmp_type,
1385 pfse->pfse_icmp_code, pfse->pfse_icmp_mtu);
1389 panic("%s: unknown type", __func__);
1391 free(pfse, M_PFTEMP);
1397 pf_purge_thread(void *v)
1401 CURVNET_SET((struct vnet *)v);
1405 rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftm", hz / 10);
1407 if (V_pf_end_threads) {
1409 * To cleanse up all kifs and rules we need
1410 * two runs: first one clears reference flags,
1411 * then pf_purge_expired_states() doesn't
1412 * raise them, and then second run frees.
1415 pf_purge_unlinked_rules();
1419 * Now purge everything.
1421 pf_purge_expired_states(0, pf_hashmask);
1422 pf_purge_expired_fragments();
1423 pf_purge_expired_src_nodes();
1426 * Now all kifs & rules should be unreferenced,
1427 * thus should be successfully freed.
1429 pf_purge_unlinked_rules();
1433 * Announce success and exit.
1438 wakeup(pf_purge_thread);
1443 /* Process 1/interval fraction of the state table every run. */
1444 idx = pf_purge_expired_states(idx, pf_hashmask /
1445 (V_pf_default_rule.timeout[PFTM_INTERVAL] * 10));
1447 /* Purge other expired types every PFTM_INTERVAL seconds. */
1450 * Order is important:
1451 * - states and src nodes reference rules
1452 * - states and rules reference kifs
1454 pf_purge_expired_fragments();
1455 pf_purge_expired_src_nodes();
1456 pf_purge_unlinked_rules();
1465 pf_state_expires(const struct pf_state *state)
1472 /* handle all PFTM_* > PFTM_MAX here */
1473 if (state->timeout == PFTM_PURGE)
1474 return (time_uptime);
1475 KASSERT(state->timeout != PFTM_UNLINKED,
1476 ("pf_state_expires: timeout == PFTM_UNLINKED"));
1477 KASSERT((state->timeout < PFTM_MAX),
1478 ("pf_state_expires: timeout > PFTM_MAX"));
1479 timeout = state->rule.ptr->timeout[state->timeout];
1481 timeout = V_pf_default_rule.timeout[state->timeout];
1482 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1484 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1485 states = counter_u64_fetch(state->rule.ptr->states_cur);
1487 start = V_pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1488 end = V_pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1489 states = V_pf_status.states;
1491 if (end && states > start && start < end) {
1493 return (state->expire + timeout * (end - states) /
1496 return (time_uptime);
1498 return (state->expire + timeout);
1502 pf_purge_expired_src_nodes()
1504 struct pf_src_node_list freelist;
1505 struct pf_srchash *sh;
1506 struct pf_src_node *cur, *next;
1509 LIST_INIT(&freelist);
1510 for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask; i++, sh++) {
1511 PF_HASHROW_LOCK(sh);
1512 LIST_FOREACH_SAFE(cur, &sh->nodes, entry, next)
1513 if (cur->states == 0 && cur->expire <= time_uptime) {
1514 pf_unlink_src_node_locked(cur);
1515 LIST_INSERT_HEAD(&freelist, cur, entry);
1516 } else if (cur->rule.ptr != NULL)
1517 cur->rule.ptr->rule_flag |= PFRULE_REFS;
1518 PF_HASHROW_UNLOCK(sh);
1521 pf_free_src_nodes(&freelist);
1525 pf_src_tree_remove_state(struct pf_state *s)
1529 if (s->src_node != NULL) {
1531 --s->src_node->conn;
1532 if (--s->src_node->states == 0) {
1533 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1536 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1537 s->src_node->expire = time_uptime + timeout;
1540 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1541 if (--s->nat_src_node->states == 0) {
1542 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1545 V_pf_default_rule.timeout[PFTM_SRC_NODE];
1546 s->nat_src_node->expire = time_uptime + timeout;
1549 s->src_node = s->nat_src_node = NULL;
1553 * Unlink and potentilly free a state. Function may be
1554 * called with ID hash row locked, but always returns
1555 * unlocked, since it needs to go through key hash locking.
1558 pf_unlink_state(struct pf_state *s, u_int flags)
1560 struct pf_idhash *ih = &V_pf_idhash[PF_IDHASH(s)];
1562 if ((flags & PF_ENTER_LOCKED) == 0)
1563 PF_HASHROW_LOCK(ih);
1565 PF_HASHROW_ASSERT(ih);
1567 if (s->timeout == PFTM_UNLINKED) {
1569 * State is being processed
1570 * by pf_unlink_state() in
1573 PF_HASHROW_UNLOCK(ih);
1574 return (0); /* XXXGL: undefined actually */
1577 if (s->src.state == PF_TCPS_PROXY_DST) {
1578 /* XXX wire key the right one? */
1579 pf_send_tcp(NULL, s->rule.ptr, s->key[PF_SK_WIRE]->af,
1580 &s->key[PF_SK_WIRE]->addr[1],
1581 &s->key[PF_SK_WIRE]->addr[0],
1582 s->key[PF_SK_WIRE]->port[1],
1583 s->key[PF_SK_WIRE]->port[0],
1584 s->src.seqhi, s->src.seqlo + 1,
1585 TH_RST|TH_ACK, 0, 0, 0, 1, s->tag, NULL);
1588 LIST_REMOVE(s, entry);
1589 pf_src_tree_remove_state(s);
1591 if (pfsync_delete_state_ptr != NULL)
1592 pfsync_delete_state_ptr(s);
1594 STATE_DEC_COUNTERS(s);
1596 s->timeout = PFTM_UNLINKED;
1598 PF_HASHROW_UNLOCK(ih);
1601 refcount_release(&s->refs);
1603 return (pf_release_state(s));
1607 pf_free_state(struct pf_state *cur)
1610 KASSERT(cur->refs == 0, ("%s: %p has refs", __func__, cur));
1611 KASSERT(cur->timeout == PFTM_UNLINKED, ("%s: timeout %u", __func__,
1614 pf_normalize_tcp_cleanup(cur);
1615 uma_zfree(V_pf_state_z, cur);
1616 V_pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1620 * Called only from pf_purge_thread(), thus serialized.
1623 pf_purge_expired_states(u_int i, int maxcheck)
1625 struct pf_idhash *ih;
1628 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1631 * Go through hash and unlink states that expire now.
1633 while (maxcheck > 0) {
1635 ih = &V_pf_idhash[i];
1637 PF_HASHROW_LOCK(ih);
1638 LIST_FOREACH(s, &ih->states, entry) {
1639 if (pf_state_expires(s) <= time_uptime) {
1640 V_pf_status.states -=
1641 pf_unlink_state(s, PF_ENTER_LOCKED);
1644 s->rule.ptr->rule_flag |= PFRULE_REFS;
1645 if (s->nat_rule.ptr != NULL)
1646 s->nat_rule.ptr->rule_flag |= PFRULE_REFS;
1647 if (s->anchor.ptr != NULL)
1648 s->anchor.ptr->rule_flag |= PFRULE_REFS;
1649 s->kif->pfik_flags |= PFI_IFLAG_REFS;
1651 s->rt_kif->pfik_flags |= PFI_IFLAG_REFS;
1653 PF_HASHROW_UNLOCK(ih);
1655 /* Return when we hit end of hash. */
1656 if (++i > pf_hashmask) {
1657 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1664 V_pf_status.states = uma_zone_get_cur(V_pf_state_z);
1670 pf_purge_unlinked_rules()
1672 struct pf_rulequeue tmpq;
1673 struct pf_rule *r, *r1;
1676 * If we have overloading task pending, then we'd
1677 * better skip purging this time. There is a tiny
1678 * probability that overloading task references
1679 * an already unlinked rule.
1681 PF_OVERLOADQ_LOCK();
1682 if (!SLIST_EMPTY(&V_pf_overloadqueue)) {
1683 PF_OVERLOADQ_UNLOCK();
1686 PF_OVERLOADQ_UNLOCK();
1689 * Do naive mark-and-sweep garbage collecting of old rules.
1690 * Reference flag is raised by pf_purge_expired_states()
1691 * and pf_purge_expired_src_nodes().
1693 * To avoid LOR between PF_UNLNKDRULES_LOCK/PF_RULES_WLOCK,
1694 * use a temporary queue.
1697 PF_UNLNKDRULES_LOCK();
1698 TAILQ_FOREACH_SAFE(r, &V_pf_unlinked_rules, entries, r1) {
1699 if (!(r->rule_flag & PFRULE_REFS)) {
1700 TAILQ_REMOVE(&V_pf_unlinked_rules, r, entries);
1701 TAILQ_INSERT_TAIL(&tmpq, r, entries);
1703 r->rule_flag &= ~PFRULE_REFS;
1705 PF_UNLNKDRULES_UNLOCK();
1707 if (!TAILQ_EMPTY(&tmpq)) {
1709 TAILQ_FOREACH_SAFE(r, &tmpq, entries, r1) {
1710 TAILQ_REMOVE(&tmpq, r, entries);
1718 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1723 u_int32_t a = ntohl(addr->addr32[0]);
1724 printf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1736 u_int8_t i, curstart, curend, maxstart, maxend;
1737 curstart = curend = maxstart = maxend = 255;
1738 for (i = 0; i < 8; i++) {
1739 if (!addr->addr16[i]) {
1740 if (curstart == 255)
1744 if ((curend - curstart) >
1745 (maxend - maxstart)) {
1746 maxstart = curstart;
1749 curstart = curend = 255;
1752 if ((curend - curstart) >
1753 (maxend - maxstart)) {
1754 maxstart = curstart;
1757 for (i = 0; i < 8; i++) {
1758 if (i >= maxstart && i <= maxend) {
1764 b = ntohs(addr->addr16[i]);
1781 pf_print_state(struct pf_state *s)
1783 pf_print_state_parts(s, NULL, NULL);
1787 pf_print_state_parts(struct pf_state *s,
1788 struct pf_state_key *skwp, struct pf_state_key *sksp)
1790 struct pf_state_key *skw, *sks;
1791 u_int8_t proto, dir;
1793 /* Do our best to fill these, but they're skipped if NULL */
1794 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1795 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1796 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1797 dir = s ? s->direction : 0;
1815 case IPPROTO_ICMPV6:
1819 printf("%u", skw->proto);
1832 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1834 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1839 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1841 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1846 if (proto == IPPROTO_TCP) {
1847 printf(" [lo=%u high=%u win=%u modulator=%u",
1848 s->src.seqlo, s->src.seqhi,
1849 s->src.max_win, s->src.seqdiff);
1850 if (s->src.wscale && s->dst.wscale)
1851 printf(" wscale=%u",
1852 s->src.wscale & PF_WSCALE_MASK);
1854 printf(" [lo=%u high=%u win=%u modulator=%u",
1855 s->dst.seqlo, s->dst.seqhi,
1856 s->dst.max_win, s->dst.seqdiff);
1857 if (s->src.wscale && s->dst.wscale)
1858 printf(" wscale=%u",
1859 s->dst.wscale & PF_WSCALE_MASK);
1862 printf(" %u:%u", s->src.state, s->dst.state);
1867 pf_print_flags(u_int8_t f)
1889 #define PF_SET_SKIP_STEPS(i) \
1891 while (head[i] != cur) { \
1892 head[i]->skip[i].ptr = cur; \
1893 head[i] = TAILQ_NEXT(head[i], entries); \
1898 pf_calc_skip_steps(struct pf_rulequeue *rules)
1900 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1903 cur = TAILQ_FIRST(rules);
1905 for (i = 0; i < PF_SKIP_COUNT; ++i)
1907 while (cur != NULL) {
1909 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1910 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1911 if (cur->direction != prev->direction)
1912 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1913 if (cur->af != prev->af)
1914 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1915 if (cur->proto != prev->proto)
1916 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1917 if (cur->src.neg != prev->src.neg ||
1918 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1919 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1920 if (cur->src.port[0] != prev->src.port[0] ||
1921 cur->src.port[1] != prev->src.port[1] ||
1922 cur->src.port_op != prev->src.port_op)
1923 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1924 if (cur->dst.neg != prev->dst.neg ||
1925 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1926 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1927 if (cur->dst.port[0] != prev->dst.port[0] ||
1928 cur->dst.port[1] != prev->dst.port[1] ||
1929 cur->dst.port_op != prev->dst.port_op)
1930 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1933 cur = TAILQ_NEXT(cur, entries);
1935 for (i = 0; i < PF_SKIP_COUNT; ++i)
1936 PF_SET_SKIP_STEPS(i);
1940 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1942 if (aw1->type != aw2->type)
1944 switch (aw1->type) {
1945 case PF_ADDR_ADDRMASK:
1947 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1949 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1952 case PF_ADDR_DYNIFTL:
1953 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1954 case PF_ADDR_NOROUTE:
1955 case PF_ADDR_URPFFAILED:
1958 return (aw1->p.tbl != aw2->p.tbl);
1960 printf("invalid address type: %d\n", aw1->type);
1966 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1972 l = cksum + old - new;
1973 l = (l >> 16) + (l & 65535);
1981 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1982 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1987 PF_ACPY(&ao, a, af);
1995 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1996 ao.addr16[0], an->addr16[0], 0),
1997 ao.addr16[1], an->addr16[1], 0);
1999 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2000 ao.addr16[0], an->addr16[0], u),
2001 ao.addr16[1], an->addr16[1], u),
2007 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2008 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2009 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
2010 ao.addr16[0], an->addr16[0], u),
2011 ao.addr16[1], an->addr16[1], u),
2012 ao.addr16[2], an->addr16[2], u),
2013 ao.addr16[3], an->addr16[3], u),
2014 ao.addr16[4], an->addr16[4], u),
2015 ao.addr16[5], an->addr16[5], u),
2016 ao.addr16[6], an->addr16[6], u),
2017 ao.addr16[7], an->addr16[7], u),
2025 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
2027 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
2031 memcpy(&ao, a, sizeof(ao));
2032 memcpy(a, &an, sizeof(u_int32_t));
2033 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
2034 ao % 65536, an % 65536, u);
2039 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
2043 PF_ACPY(&ao, a, AF_INET6);
2044 PF_ACPY(a, an, AF_INET6);
2046 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2047 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2048 pf_cksum_fixup(pf_cksum_fixup(*c,
2049 ao.addr16[0], an->addr16[0], u),
2050 ao.addr16[1], an->addr16[1], u),
2051 ao.addr16[2], an->addr16[2], u),
2052 ao.addr16[3], an->addr16[3], u),
2053 ao.addr16[4], an->addr16[4], u),
2054 ao.addr16[5], an->addr16[5], u),
2055 ao.addr16[6], an->addr16[6], u),
2056 ao.addr16[7], an->addr16[7], u);
2061 pf_icmp_mapping(struct pf_pdesc *pd, uint8_t type,
2062 int *icmp_dir, int *multi, uint16_t *icmpid, uint16_t *icmptype)
2065 * ICMP types marked with PF_OUT are typically responses to
2066 * PF_IN, and will match states in the opposite direction.
2067 * PF_IN ICMP types need to match a state with that type.
2070 *multi = PF_ICMP_MULTI_LINK;
2071 /* Queries (and responses) */
2075 case ICMP_ECHOREPLY:
2076 *icmptype = ICMP_ECHO;
2077 *icmpid = pd->hdr.icmp->icmp_id;
2082 case ICMP_TSTAMPREPLY:
2083 *icmptype = ICMP_TSTAMP;
2084 *icmpid = pd->hdr.icmp->icmp_id;
2089 case ICMP_IREQREPLY:
2090 *icmptype = ICMP_IREQ;
2091 *icmpid = pd->hdr.icmp->icmp_id;
2096 case ICMP_MASKREPLY:
2097 *icmptype = ICMP_MASKREQ;
2098 *icmpid = pd->hdr.icmp->icmp_id;
2101 case ICMP_IPV6_WHEREAREYOU:
2103 case ICMP_IPV6_IAMHERE:
2104 *icmptype = ICMP_IPV6_WHEREAREYOU;
2105 *icmpid = 0; /* Nothing sane to match on! */
2108 case ICMP_MOBILE_REGREQUEST:
2110 case ICMP_MOBILE_REGREPLY:
2111 *icmptype = ICMP_MOBILE_REGREQUEST;
2112 *icmpid = 0; /* Nothing sane to match on! */
2115 case ICMP_ROUTERSOLICIT:
2117 case ICMP_ROUTERADVERT:
2118 *icmptype = ICMP_MOBILE_REGREQUEST;
2119 *icmpid = 0; /* Nothing sane to match on! */
2123 case ICMP6_ECHO_REQUEST:
2125 case ICMP6_ECHO_REPLY:
2126 *icmptype = ICMP6_ECHO_REPLY;
2127 *icmpid = 0; /* Nothing sane to match on! */
2130 case MLD_LISTENER_QUERY:
2132 case MLD_LISTENER_REPORT: {
2133 struct mld_hdr *mld = (void *)pd->hdr.icmp6;
2135 *icmptype = MLD_LISTENER_QUERY;
2136 /* generate fake id for these messages */
2137 *icmpid = (mld->mld_addr.s6_addr32[0] ^
2138 mld->mld_addr.s6_addr32[1] ^
2139 mld->mld_addr.s6_addr32[2] ^
2140 mld->mld_addr.s6_addr32[3]) & 0xffff;
2144 /* ICMP6_FQDN and ICMP6_NI query/reply are the same type as ICMP6_WRU */
2145 case ICMP6_WRUREQUEST:
2147 case ICMP6_WRUREPLY:
2148 *icmptype = ICMP6_WRUREQUEST;
2149 *icmpid = 0; /* Nothing sane to match on! */
2154 case MLD_MTRACE_RESP:
2155 *icmptype = MLD_MTRACE;
2156 *icmpid = 0; /* Nothing sane to match on! */
2159 case ND_NEIGHBOR_SOLICIT:
2161 case ND_NEIGHBOR_ADVERT: {
2162 struct nd_neighbor_solicit *nd = (void *)pd->hdr.icmp6;
2164 *icmptype = ND_NEIGHBOR_SOLICIT;
2165 *multi = PF_ICMP_MULTI_SOLICITED;
2166 /* generate fake id for these messages */
2167 *icmpid = (nd->nd_ns_target.s6_addr32[0] ^
2168 nd->nd_ns_target.s6_addr32[1] ^
2169 nd->nd_ns_target.s6_addr32[2] ^
2170 nd->nd_ns_target.s6_addr32[3]) & 0xffff;
2175 /* These ICMP types map to other connections */
2177 case ICMP_SOURCEQUENCH:
2180 case ICMP_PARAMPROB:
2183 * ICMP6_TIME_EXCEEDED is the same type as ICMP_UNREACH
2184 * ND_REDIRECT can't be in this list because the triggering packet
2185 * header is optional.
2187 case ICMP6_PACKET_TOO_BIG:
2189 /* These will not be used, but set them anyways */
2191 *icmptype = htons(type);
2193 return (1); /* These types are matched to other state */
2195 * All remaining ICMP types get their own states,
2196 * and will only match in one direction.
2204 *icmptype = htons(*icmptype);
2210 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
2211 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
2212 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
2214 struct pf_addr oia, ooa;
2216 PF_ACPY(&oia, ia, af);
2218 PF_ACPY(&ooa, oa, af);
2220 /* Change inner protocol port, fix inner protocol checksum. */
2222 u_int16_t oip = *ip;
2229 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
2230 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
2232 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
2234 /* Change inner ip address, fix inner ip and icmp checksums. */
2235 PF_ACPY(ia, na, af);
2239 u_int32_t oh2c = *h2c;
2241 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
2242 oia.addr16[0], ia->addr16[0], 0),
2243 oia.addr16[1], ia->addr16[1], 0);
2244 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
2245 oia.addr16[0], ia->addr16[0], 0),
2246 oia.addr16[1], ia->addr16[1], 0);
2247 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
2253 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2254 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2255 pf_cksum_fixup(pf_cksum_fixup(*ic,
2256 oia.addr16[0], ia->addr16[0], u),
2257 oia.addr16[1], ia->addr16[1], u),
2258 oia.addr16[2], ia->addr16[2], u),
2259 oia.addr16[3], ia->addr16[3], u),
2260 oia.addr16[4], ia->addr16[4], u),
2261 oia.addr16[5], ia->addr16[5], u),
2262 oia.addr16[6], ia->addr16[6], u),
2263 oia.addr16[7], ia->addr16[7], u);
2267 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2269 PF_ACPY(oa, na, af);
2273 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2274 ooa.addr16[0], oa->addr16[0], 0),
2275 ooa.addr16[1], oa->addr16[1], 0);
2280 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2281 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2282 pf_cksum_fixup(pf_cksum_fixup(*ic,
2283 ooa.addr16[0], oa->addr16[0], u),
2284 ooa.addr16[1], oa->addr16[1], u),
2285 ooa.addr16[2], oa->addr16[2], u),
2286 ooa.addr16[3], oa->addr16[3], u),
2287 ooa.addr16[4], oa->addr16[4], u),
2288 ooa.addr16[5], oa->addr16[5], u),
2289 ooa.addr16[6], oa->addr16[6], u),
2290 ooa.addr16[7], oa->addr16[7], u);
2299 * Need to modulate the sequence numbers in the TCP SACK option
2300 * (credits to Krzysztof Pfaff for report and patch)
2303 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2304 struct tcphdr *th, struct pf_state_peer *dst)
2306 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2307 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2308 int copyback = 0, i, olen;
2309 struct sackblk sack;
2311 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2312 if (hlen < TCPOLEN_SACKLEN ||
2313 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2316 while (hlen >= TCPOLEN_SACKLEN) {
2319 case TCPOPT_EOL: /* FALLTHROUGH */
2327 if (olen >= TCPOLEN_SACKLEN) {
2328 for (i = 2; i + TCPOLEN_SACK <= olen;
2329 i += TCPOLEN_SACK) {
2330 memcpy(&sack, &opt[i], sizeof(sack));
2331 pf_change_a(&sack.start, &th->th_sum,
2332 htonl(ntohl(sack.start) -
2334 pf_change_a(&sack.end, &th->th_sum,
2335 htonl(ntohl(sack.end) -
2337 memcpy(&opt[i], &sack, sizeof(sack));
2351 m_copyback(m, off + sizeof(*th), thoptlen, (caddr_t)opts);
2356 pf_send_tcp(struct mbuf *replyto, const struct pf_rule *r, sa_family_t af,
2357 const struct pf_addr *saddr, const struct pf_addr *daddr,
2358 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2359 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2360 u_int16_t rtag, struct ifnet *ifp)
2362 struct pf_send_entry *pfse;
2366 struct ip *h = NULL;
2369 struct ip6_hdr *h6 = NULL;
2373 struct pf_mtag *pf_mtag;
2378 /* maximum segment size tcp option */
2379 tlen = sizeof(struct tcphdr);
2386 len = sizeof(struct ip) + tlen;
2391 len = sizeof(struct ip6_hdr) + tlen;
2395 panic("%s: unsupported af %d", __func__, af);
2398 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2399 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2402 m = m_gethdr(M_NOWAIT, MT_DATA);
2404 free(pfse, M_PFTEMP);
2408 mac_netinet_firewall_send(m);
2410 if ((pf_mtag = pf_get_mtag(m)) == NULL) {
2411 free(pfse, M_PFTEMP);
2416 m->m_flags |= M_SKIP_FIREWALL;
2417 pf_mtag->tag = rtag;
2419 if (r != NULL && r->rtableid >= 0)
2420 M_SETFIB(m, r->rtableid);
2423 if (r != NULL && r->qid) {
2424 pf_mtag->qid = r->qid;
2426 /* add hints for ecn */
2427 pf_mtag->hdr = mtod(m, struct ip *);
2430 m->m_data += max_linkhdr;
2431 m->m_pkthdr.len = m->m_len = len;
2432 m->m_pkthdr.rcvif = NULL;
2433 bzero(m->m_data, len);
2437 h = mtod(m, struct ip *);
2439 /* IP header fields included in the TCP checksum */
2440 h->ip_p = IPPROTO_TCP;
2441 h->ip_len = htons(tlen);
2442 h->ip_src.s_addr = saddr->v4.s_addr;
2443 h->ip_dst.s_addr = daddr->v4.s_addr;
2445 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2450 h6 = mtod(m, struct ip6_hdr *);
2452 /* IP header fields included in the TCP checksum */
2453 h6->ip6_nxt = IPPROTO_TCP;
2454 h6->ip6_plen = htons(tlen);
2455 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2456 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2458 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2464 th->th_sport = sport;
2465 th->th_dport = dport;
2466 th->th_seq = htonl(seq);
2467 th->th_ack = htonl(ack);
2468 th->th_off = tlen >> 2;
2469 th->th_flags = flags;
2470 th->th_win = htons(win);
2473 opt = (char *)(th + 1);
2474 opt[0] = TCPOPT_MAXSEG;
2477 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2484 th->th_sum = in_cksum(m, len);
2486 /* Finish the IP header */
2488 h->ip_hl = sizeof(*h) >> 2;
2489 h->ip_tos = IPTOS_LOWDELAY;
2490 h->ip_off = htons(V_path_mtu_discovery ? IP_DF : 0);
2491 h->ip_len = htons(len);
2492 h->ip_ttl = ttl ? ttl : V_ip_defttl;
2495 pfse->pfse_type = PFSE_IP;
2501 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2502 sizeof(struct ip6_hdr), tlen);
2504 h6->ip6_vfc |= IPV6_VERSION;
2505 h6->ip6_hlim = IPV6_DEFHLIM;
2507 pfse->pfse_type = PFSE_IP6;
2516 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2519 struct pf_send_entry *pfse;
2521 struct pf_mtag *pf_mtag;
2523 /* Allocate outgoing queue entry, mbuf and mbuf tag. */
2524 pfse = malloc(sizeof(*pfse), M_PFTEMP, M_NOWAIT);
2528 if ((m0 = m_copypacket(m, M_NOWAIT)) == NULL) {
2529 free(pfse, M_PFTEMP);
2533 if ((pf_mtag = pf_get_mtag(m0)) == NULL) {
2534 free(pfse, M_PFTEMP);
2538 m0->m_flags |= M_SKIP_FIREWALL;
2540 if (r->rtableid >= 0)
2541 M_SETFIB(m0, r->rtableid);
2545 pf_mtag->qid = r->qid;
2546 /* add hints for ecn */
2547 pf_mtag->hdr = mtod(m0, struct ip *);
2554 pfse->pfse_type = PFSE_ICMP;
2559 pfse->pfse_type = PFSE_ICMP6;
2564 pfse->pfse_icmp_type = type;
2565 pfse->pfse_icmp_code = code;
2570 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2571 * If n is 0, they match if they are equal. If n is != 0, they match if they
2575 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2576 struct pf_addr *b, sa_family_t af)
2583 if ((a->addr32[0] & m->addr32[0]) ==
2584 (b->addr32[0] & m->addr32[0]))
2590 if (((a->addr32[0] & m->addr32[0]) ==
2591 (b->addr32[0] & m->addr32[0])) &&
2592 ((a->addr32[1] & m->addr32[1]) ==
2593 (b->addr32[1] & m->addr32[1])) &&
2594 ((a->addr32[2] & m->addr32[2]) ==
2595 (b->addr32[2] & m->addr32[2])) &&
2596 ((a->addr32[3] & m->addr32[3]) ==
2597 (b->addr32[3] & m->addr32[3])))
2616 * Return 1 if b <= a <= e, otherwise return 0.
2619 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2620 struct pf_addr *a, sa_family_t af)
2625 if ((a->addr32[0] < b->addr32[0]) ||
2626 (a->addr32[0] > e->addr32[0]))
2635 for (i = 0; i < 4; ++i)
2636 if (a->addr32[i] > b->addr32[i])
2638 else if (a->addr32[i] < b->addr32[i])
2641 for (i = 0; i < 4; ++i)
2642 if (a->addr32[i] < e->addr32[i])
2644 else if (a->addr32[i] > e->addr32[i])
2654 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2658 return ((p > a1) && (p < a2));
2660 return ((p < a1) || (p > a2));
2662 return ((p >= a1) && (p <= a2));
2676 return (0); /* never reached */
2680 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2685 return (pf_match(op, a1, a2, p));
2689 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2691 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2693 return (pf_match(op, a1, a2, u));
2697 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2699 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2701 return (pf_match(op, a1, a2, g));
2705 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag, int mtag)
2710 return ((!r->match_tag_not && r->match_tag == *tag) ||
2711 (r->match_tag_not && r->match_tag != *tag));
2715 pf_tag_packet(struct mbuf *m, struct pf_pdesc *pd, int tag)
2718 KASSERT(tag > 0, ("%s: tag %d", __func__, tag));
2720 if (pd->pf_mtag == NULL && ((pd->pf_mtag = pf_get_mtag(m)) == NULL))
2723 pd->pf_mtag->tag = tag;
2728 #define PF_ANCHOR_STACKSIZE 32
2729 struct pf_anchor_stackframe {
2730 struct pf_ruleset *rs;
2731 struct pf_rule *r; /* XXX: + match bit */
2732 struct pf_anchor *child;
2736 * XXX: We rely on malloc(9) returning pointer aligned addresses.
2738 #define PF_ANCHORSTACK_MATCH 0x00000001
2739 #define PF_ANCHORSTACK_MASK (PF_ANCHORSTACK_MATCH)
2741 #define PF_ANCHOR_MATCH(f) ((uintptr_t)(f)->r & PF_ANCHORSTACK_MATCH)
2742 #define PF_ANCHOR_RULE(f) (struct pf_rule *) \
2743 ((uintptr_t)(f)->r & ~PF_ANCHORSTACK_MASK)
2744 #define PF_ANCHOR_SET_MATCH(f) do { (f)->r = (void *) \
2745 ((uintptr_t)(f)->r | PF_ANCHORSTACK_MATCH); \
2749 pf_step_into_anchor(struct pf_anchor_stackframe *stack, int *depth,
2750 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2753 struct pf_anchor_stackframe *f;
2759 if (*depth >= PF_ANCHOR_STACKSIZE) {
2760 printf("%s: anchor stack overflow on %s\n",
2761 __func__, (*r)->anchor->name);
2762 *r = TAILQ_NEXT(*r, entries);
2764 } else if (*depth == 0 && a != NULL)
2766 f = stack + (*depth)++;
2769 if ((*r)->anchor_wildcard) {
2770 struct pf_anchor_node *parent = &(*r)->anchor->children;
2772 if ((f->child = RB_MIN(pf_anchor_node, parent)) == NULL) {
2776 *rs = &f->child->ruleset;
2779 *rs = &(*r)->anchor->ruleset;
2781 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2785 pf_step_out_of_anchor(struct pf_anchor_stackframe *stack, int *depth,
2786 struct pf_ruleset **rs, int n, struct pf_rule **r, struct pf_rule **a,
2789 struct pf_anchor_stackframe *f;
2798 f = stack + *depth - 1;
2799 fr = PF_ANCHOR_RULE(f);
2800 if (f->child != NULL) {
2801 struct pf_anchor_node *parent;
2804 * This block traverses through
2805 * a wildcard anchor.
2807 parent = &fr->anchor->children;
2808 if (match != NULL && *match) {
2810 * If any of "*" matched, then
2811 * "foo/ *" matched, mark frame
2814 PF_ANCHOR_SET_MATCH(f);
2817 f->child = RB_NEXT(pf_anchor_node, parent, f->child);
2818 if (f->child != NULL) {
2819 *rs = &f->child->ruleset;
2820 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2828 if (*depth == 0 && a != NULL)
2831 if (PF_ANCHOR_MATCH(f) || (match != NULL && *match))
2833 *r = TAILQ_NEXT(fr, entries);
2834 } while (*r == NULL);
2841 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2842 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2847 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2848 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2852 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2853 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2854 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2855 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2856 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2857 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2858 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2859 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2865 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2870 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2874 if (addr->addr32[3] == 0xffffffff) {
2875 addr->addr32[3] = 0;
2876 if (addr->addr32[2] == 0xffffffff) {
2877 addr->addr32[2] = 0;
2878 if (addr->addr32[1] == 0xffffffff) {
2879 addr->addr32[1] = 0;
2881 htonl(ntohl(addr->addr32[0]) + 1);
2884 htonl(ntohl(addr->addr32[1]) + 1);
2887 htonl(ntohl(addr->addr32[2]) + 1);
2890 htonl(ntohl(addr->addr32[3]) + 1);
2897 pf_socket_lookup(int direction, struct pf_pdesc *pd, struct mbuf *m)
2899 struct pf_addr *saddr, *daddr;
2900 u_int16_t sport, dport;
2901 struct inpcbinfo *pi;
2904 pd->lookup.uid = UID_MAX;
2905 pd->lookup.gid = GID_MAX;
2907 switch (pd->proto) {
2909 if (pd->hdr.tcp == NULL)
2911 sport = pd->hdr.tcp->th_sport;
2912 dport = pd->hdr.tcp->th_dport;
2916 if (pd->hdr.udp == NULL)
2918 sport = pd->hdr.udp->uh_sport;
2919 dport = pd->hdr.udp->uh_dport;
2925 if (direction == PF_IN) {
2940 inp = in_pcblookup_mbuf(pi, saddr->v4, sport, daddr->v4,
2941 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2943 inp = in_pcblookup_mbuf(pi, saddr->v4, sport,
2944 daddr->v4, dport, INPLOOKUP_WILDCARD |
2945 INPLOOKUP_RLOCKPCB, NULL, m);
2953 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport, &daddr->v6,
2954 dport, INPLOOKUP_RLOCKPCB, NULL, m);
2956 inp = in6_pcblookup_mbuf(pi, &saddr->v6, sport,
2957 &daddr->v6, dport, INPLOOKUP_WILDCARD |
2958 INPLOOKUP_RLOCKPCB, NULL, m);
2968 INP_RLOCK_ASSERT(inp);
2969 pd->lookup.uid = inp->inp_cred->cr_uid;
2970 pd->lookup.gid = inp->inp_cred->cr_groups[0];
2977 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2981 u_int8_t *opt, optlen;
2982 u_int8_t wscale = 0;
2984 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2985 if (hlen <= sizeof(struct tcphdr))
2987 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2989 opt = hdr + sizeof(struct tcphdr);
2990 hlen -= sizeof(struct tcphdr);
3000 if (wscale > TCP_MAX_WINSHIFT)
3001 wscale = TCP_MAX_WINSHIFT;
3002 wscale |= PF_WSCALE_FLAG;
3017 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3021 u_int8_t *opt, optlen;
3022 u_int16_t mss = V_tcp_mssdflt;
3024 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3025 if (hlen <= sizeof(struct tcphdr))
3027 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3029 opt = hdr + sizeof(struct tcphdr);
3030 hlen -= sizeof(struct tcphdr);
3031 while (hlen >= TCPOLEN_MAXSEG) {
3039 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3055 pf_calc_mss(struct pf_addr *addr, sa_family_t af, int rtableid, u_int16_t offer)
3058 struct sockaddr_in *dst;
3062 struct sockaddr_in6 *dst6;
3063 struct route_in6 ro6;
3065 struct rtentry *rt = NULL;
3067 u_int16_t mss = V_tcp_mssdflt;
3072 hlen = sizeof(struct ip);
3073 bzero(&ro, sizeof(ro));
3074 dst = (struct sockaddr_in *)&ro.ro_dst;
3075 dst->sin_family = AF_INET;
3076 dst->sin_len = sizeof(*dst);
3077 dst->sin_addr = addr->v4;
3078 in_rtalloc_ign(&ro, 0, rtableid);
3084 hlen = sizeof(struct ip6_hdr);
3085 bzero(&ro6, sizeof(ro6));
3086 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3087 dst6->sin6_family = AF_INET6;
3088 dst6->sin6_len = sizeof(*dst6);
3089 dst6->sin6_addr = addr->v6;
3090 in6_rtalloc_ign(&ro6, 0, rtableid);
3096 if (rt && rt->rt_ifp) {
3097 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3098 mss = max(V_tcp_mssdflt, mss);
3101 mss = min(mss, offer);
3102 mss = max(mss, 64); /* sanity - at least max opt space */
3107 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3109 struct pf_rule *r = s->rule.ptr;
3110 struct pf_src_node *sn = NULL;
3113 if (!r->rt || r->rt == PF_FASTROUTE)
3115 switch (s->key[PF_SK_WIRE]->af) {
3118 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL, &sn);
3119 s->rt_kif = r->rpool.cur->kif;
3124 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL, &sn);
3125 s->rt_kif = r->rpool.cur->kif;
3132 pf_tcp_iss(struct pf_pdesc *pd)
3135 u_int32_t digest[4];
3137 if (V_pf_tcp_secret_init == 0) {
3138 read_random(&V_pf_tcp_secret, sizeof(V_pf_tcp_secret));
3139 MD5Init(&V_pf_tcp_secret_ctx);
3140 MD5Update(&V_pf_tcp_secret_ctx, V_pf_tcp_secret,
3141 sizeof(V_pf_tcp_secret));
3142 V_pf_tcp_secret_init = 1;
3145 ctx = V_pf_tcp_secret_ctx;
3147 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3148 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3149 if (pd->af == AF_INET6) {
3150 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3151 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3153 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3154 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3156 MD5Final((u_char *)digest, &ctx);
3157 V_pf_tcp_iss_off += 4096;
3158 #define ISN_RANDOM_INCREMENT (4096 - 1)
3159 return (digest[0] + (arc4random() & ISN_RANDOM_INCREMENT) +
3161 #undef ISN_RANDOM_INCREMENT
3165 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3166 struct pfi_kif *kif, struct mbuf *m, int off, struct pf_pdesc *pd,
3167 struct pf_rule **am, struct pf_ruleset **rsm, struct inpcb *inp)
3169 struct pf_rule *nr = NULL;
3170 struct pf_addr * const saddr = pd->src;
3171 struct pf_addr * const daddr = pd->dst;
3172 sa_family_t af = pd->af;
3173 struct pf_rule *r, *a = NULL;
3174 struct pf_ruleset *ruleset = NULL;
3175 struct pf_src_node *nsn = NULL;
3176 struct tcphdr *th = pd->hdr.tcp;
3177 struct pf_state_key *sk = NULL, *nk = NULL;
3179 int rewrite = 0, hdrlen = 0;
3180 int tag = -1, rtableid = -1;
3183 int state_icmp = 0, icmp_dir, multi;
3184 uint16_t sport = 0 , dport = 0, virtual_type = 0, virtual_id = 0;
3185 u_int16_t bproto_sum = 0, bip_sum = 0;
3186 u_int8_t icmptype = 0, icmpcode = 0;
3187 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3192 INP_LOCK_ASSERT(inp);
3193 pd->lookup.uid = inp->inp_cred->cr_uid;
3194 pd->lookup.gid = inp->inp_cred->cr_groups[0];
3195 pd->lookup.done = 1;
3198 switch (pd->proto) {
3200 sport = th->th_sport;
3201 dport = th->th_dport;
3202 hdrlen = sizeof(*th);
3205 sport = pd->hdr.udp->uh_sport;
3206 dport = pd->hdr.udp->uh_dport;
3207 hdrlen = sizeof(*pd->hdr.udp);
3211 if (pd->af != AF_INET)
3213 hdrlen = sizeof(*pd->hdr.icmp);
3214 icmptype = pd->hdr.icmp->icmp_type;
3215 icmpcode = pd->hdr.icmp->icmp_code;
3217 state_icmp = pf_icmp_mapping(pd, icmptype,
3218 &icmp_dir, &multi, &virtual_id, &virtual_type);
3219 if (icmp_dir == PF_IN) {
3221 dport = virtual_type;
3223 sport = virtual_type;
3229 case IPPROTO_ICMPV6:
3232 hdrlen = sizeof(*pd->hdr.icmp6);
3233 icmptype = pd->hdr.icmp6->icmp6_type;
3234 icmpcode = pd->hdr.icmp6->icmp6_code;
3236 state_icmp = pf_icmp_mapping(pd, icmptype,
3237 &icmp_dir, &multi, &virtual_id, &virtual_type);
3238 if (icmp_dir == PF_IN) {
3240 dport = virtual_type;
3242 sport = virtual_type;
3248 sport = dport = hdrlen = 0;
3252 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3254 /* check packet for BINAT/NAT/RDR */
3255 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn, &sk,
3256 &nk, saddr, daddr, sport, dport, anchor_stack)) != NULL) {
3257 KASSERT(sk != NULL, ("%s: null sk", __func__));
3258 KASSERT(nk != NULL, ("%s: null nk", __func__));
3261 bip_sum = *pd->ip_sum;
3263 switch (pd->proto) {
3265 bproto_sum = th->th_sum;
3266 pd->proto_sum = &th->th_sum;
3268 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3269 nk->port[pd->sidx] != sport) {
3270 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3271 &th->th_sum, &nk->addr[pd->sidx],
3272 nk->port[pd->sidx], 0, af);
3273 pd->sport = &th->th_sport;
3274 sport = th->th_sport;
3277 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3278 nk->port[pd->didx] != dport) {
3279 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3280 &th->th_sum, &nk->addr[pd->didx],
3281 nk->port[pd->didx], 0, af);
3282 dport = th->th_dport;
3283 pd->dport = &th->th_dport;
3288 bproto_sum = pd->hdr.udp->uh_sum;
3289 pd->proto_sum = &pd->hdr.udp->uh_sum;
3291 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3292 nk->port[pd->sidx] != sport) {
3293 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3294 pd->ip_sum, &pd->hdr.udp->uh_sum,
3295 &nk->addr[pd->sidx],
3296 nk->port[pd->sidx], 1, af);
3297 sport = pd->hdr.udp->uh_sport;
3298 pd->sport = &pd->hdr.udp->uh_sport;
3301 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3302 nk->port[pd->didx] != dport) {
3303 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3304 pd->ip_sum, &pd->hdr.udp->uh_sum,
3305 &nk->addr[pd->didx],
3306 nk->port[pd->didx], 1, af);
3307 dport = pd->hdr.udp->uh_dport;
3308 pd->dport = &pd->hdr.udp->uh_dport;
3314 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3315 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3316 nk->addr[pd->sidx].v4.s_addr, 0);
3318 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3319 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3320 nk->addr[pd->didx].v4.s_addr, 0);
3322 if (virtual_type == ICMP_ECHO &&
3323 nk->port[pd->sidx] != pd->hdr.icmp->icmp_id) {
3324 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3325 pd->hdr.icmp->icmp_cksum, sport,
3326 nk->port[pd->sidx], 0);
3327 pd->hdr.icmp->icmp_id = nk->port[pd->sidx];
3328 pd->sport = &pd->hdr.icmp->icmp_id;
3330 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3334 case IPPROTO_ICMPV6:
3335 nk->port[0] = nk->port[1];
3336 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3337 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3338 &nk->addr[pd->sidx], 0);
3340 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3341 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3342 &nk->addr[pd->didx], 0);
3351 &nk->addr[pd->sidx], AF_INET))
3352 pf_change_a(&saddr->v4.s_addr,
3354 nk->addr[pd->sidx].v4.s_addr, 0);
3357 &nk->addr[pd->didx], AF_INET))
3358 pf_change_a(&daddr->v4.s_addr,
3360 nk->addr[pd->didx].v4.s_addr, 0);
3366 &nk->addr[pd->sidx], AF_INET6))
3367 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3370 &nk->addr[pd->didx], AF_INET6))
3371 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3384 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3385 r = r->skip[PF_SKIP_IFP].ptr;
3386 else if (r->direction && r->direction != direction)
3387 r = r->skip[PF_SKIP_DIR].ptr;
3388 else if (r->af && r->af != af)
3389 r = r->skip[PF_SKIP_AF].ptr;
3390 else if (r->proto && r->proto != pd->proto)
3391 r = r->skip[PF_SKIP_PROTO].ptr;
3392 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3393 r->src.neg, kif, M_GETFIB(m)))
3394 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3395 /* tcp/udp only. port_op always 0 in other cases */
3396 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3397 r->src.port[0], r->src.port[1], sport))
3398 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3399 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3400 r->dst.neg, NULL, M_GETFIB(m)))
3401 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3402 /* tcp/udp only. port_op always 0 in other cases */
3403 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3404 r->dst.port[0], r->dst.port[1], dport))
3405 r = r->skip[PF_SKIP_DST_PORT].ptr;
3406 /* icmp only. type always 0 in other cases */
3407 else if (r->type && r->type != icmptype + 1)
3408 r = TAILQ_NEXT(r, entries);
3409 /* icmp only. type always 0 in other cases */
3410 else if (r->code && r->code != icmpcode + 1)
3411 r = TAILQ_NEXT(r, entries);
3412 else if (r->tos && !(r->tos == pd->tos))
3413 r = TAILQ_NEXT(r, entries);
3414 else if (r->rule_flag & PFRULE_FRAGMENT)
3415 r = TAILQ_NEXT(r, entries);
3416 else if (pd->proto == IPPROTO_TCP &&
3417 (r->flagset & th->th_flags) != r->flags)
3418 r = TAILQ_NEXT(r, entries);
3419 /* tcp/udp only. uid.op always 0 in other cases */
3420 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3421 pf_socket_lookup(direction, pd, m), 1)) &&
3422 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3424 r = TAILQ_NEXT(r, entries);
3425 /* tcp/udp only. gid.op always 0 in other cases */
3426 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3427 pf_socket_lookup(direction, pd, m), 1)) &&
3428 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3430 r = TAILQ_NEXT(r, entries);
3432 r->prob <= arc4random())
3433 r = TAILQ_NEXT(r, entries);
3434 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3435 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3436 r = TAILQ_NEXT(r, entries);
3437 else if (r->os_fingerprint != PF_OSFP_ANY &&
3438 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3439 pf_osfp_fingerprint(pd, m, off, th),
3440 r->os_fingerprint)))
3441 r = TAILQ_NEXT(r, entries);
3445 if (r->rtableid >= 0)
3446 rtableid = r->rtableid;
3447 if (r->anchor == NULL) {
3454 r = TAILQ_NEXT(r, entries);
3456 pf_step_into_anchor(anchor_stack, &asd,
3457 &ruleset, PF_RULESET_FILTER, &r, &a,
3460 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3461 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3468 REASON_SET(&reason, PFRES_MATCH);
3470 if (r->log || (nr != NULL && nr->log)) {
3472 m_copyback(m, off, hdrlen, pd->hdr.any);
3473 PFLOG_PACKET(kif, m, af, direction, reason, r->log ? r : nr, a,
3477 if ((r->action == PF_DROP) &&
3478 ((r->rule_flag & PFRULE_RETURNRST) ||
3479 (r->rule_flag & PFRULE_RETURNICMP) ||
3480 (r->rule_flag & PFRULE_RETURN))) {
3481 /* undo NAT changes, if they have taken place */
3483 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3484 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3486 *pd->sport = sk->port[pd->sidx];
3488 *pd->dport = sk->port[pd->didx];
3490 *pd->proto_sum = bproto_sum;
3492 *pd->ip_sum = bip_sum;
3493 m_copyback(m, off, hdrlen, pd->hdr.any);
3495 if (pd->proto == IPPROTO_TCP &&
3496 ((r->rule_flag & PFRULE_RETURNRST) ||
3497 (r->rule_flag & PFRULE_RETURN)) &&
3498 !(th->th_flags & TH_RST)) {
3499 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3511 h4 = mtod(m, struct ip *);
3512 len = ntohs(h4->ip_len) - off;
3517 h6 = mtod(m, struct ip6_hdr *);
3518 len = ntohs(h6->ip6_plen) - (off - sizeof(*h6));
3523 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3524 REASON_SET(&reason, PFRES_PROTCKSUM);
3526 if (th->th_flags & TH_SYN)
3528 if (th->th_flags & TH_FIN)
3530 pf_send_tcp(m, r, af, pd->dst,
3531 pd->src, th->th_dport, th->th_sport,
3532 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3533 r->return_ttl, 1, 0, kif->pfik_ifp);
3535 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3537 pf_send_icmp(m, r->return_icmp >> 8,
3538 r->return_icmp & 255, af, r);
3539 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3541 pf_send_icmp(m, r->return_icmp6 >> 8,
3542 r->return_icmp6 & 255, af, r);
3545 if (r->action == PF_DROP)
3548 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3549 REASON_SET(&reason, PFRES_MEMORY);
3553 M_SETFIB(m, rtableid);
3555 if (!state_icmp && (r->keep_state || nr != NULL ||
3556 (pd->flags & PFDESC_TCP_NORM))) {
3558 action = pf_create_state(r, nr, a, pd, nsn, nk, sk, m, off,
3559 sport, dport, &rewrite, kif, sm, tag, bproto_sum, bip_sum,
3561 if (action != PF_PASS)
3565 uma_zfree(V_pf_state_key_z, sk);
3567 uma_zfree(V_pf_state_key_z, nk);
3570 /* copy back packet headers if we performed NAT operations */
3572 m_copyback(m, off, hdrlen, pd->hdr.any);
3574 if (*sm != NULL && !((*sm)->state_flags & PFSTATE_NOSYNC) &&
3575 direction == PF_OUT &&
3576 pfsync_defer_ptr != NULL && pfsync_defer_ptr(*sm, m))
3578 * We want the state created, but we dont
3579 * want to send this in case a partner
3580 * firewall has to know about it to allow
3581 * replies through it.
3589 uma_zfree(V_pf_state_key_z, sk);
3591 uma_zfree(V_pf_state_key_z, nk);
3596 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3597 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *nk,
3598 struct pf_state_key *sk, struct mbuf *m, int off, u_int16_t sport,
3599 u_int16_t dport, int *rewrite, struct pfi_kif *kif, struct pf_state **sm,
3600 int tag, u_int16_t bproto_sum, u_int16_t bip_sum, int hdrlen)
3602 struct pf_state *s = NULL;
3603 struct pf_src_node *sn = NULL;
3604 struct tcphdr *th = pd->hdr.tcp;
3605 u_int16_t mss = V_tcp_mssdflt;
3608 /* check maximums */
3609 if (r->max_states &&
3610 (counter_u64_fetch(r->states_cur) >= r->max_states)) {
3611 V_pf_status.lcounters[LCNT_STATES]++;
3612 REASON_SET(&reason, PFRES_MAXSTATES);
3615 /* src node for filter rule */
3616 if ((r->rule_flag & PFRULE_SRCTRACK ||
3617 r->rpool.opts & PF_POOL_STICKYADDR) &&
3618 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3619 REASON_SET(&reason, PFRES_SRCLIMIT);
3622 /* src node for translation rule */
3623 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3624 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3625 REASON_SET(&reason, PFRES_SRCLIMIT);
3628 s = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO);
3630 REASON_SET(&reason, PFRES_MEMORY);
3634 s->nat_rule.ptr = nr;
3636 STATE_INC_COUNTERS(s);
3638 s->state_flags |= PFSTATE_ALLOWOPTS;
3639 if (r->rule_flag & PFRULE_STATESLOPPY)
3640 s->state_flags |= PFSTATE_SLOPPY;
3641 s->log = r->log & PF_LOG_ALL;
3642 s->sync_state = PFSYNC_S_NONE;
3644 s->log |= nr->log & PF_LOG_ALL;
3645 switch (pd->proto) {
3647 s->src.seqlo = ntohl(th->th_seq);
3648 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3649 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3650 r->keep_state == PF_STATE_MODULATE) {
3651 /* Generate sequence number modulator */
3652 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3655 pf_change_a(&th->th_seq, &th->th_sum,
3656 htonl(s->src.seqlo + s->src.seqdiff), 0);
3660 if (th->th_flags & TH_SYN) {
3662 s->src.wscale = pf_get_wscale(m, off,
3663 th->th_off, pd->af);
3665 s->src.max_win = MAX(ntohs(th->th_win), 1);
3666 if (s->src.wscale & PF_WSCALE_MASK) {
3667 /* Remove scale factor from initial window */
3668 int win = s->src.max_win;
3669 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3670 s->src.max_win = (win - 1) >>
3671 (s->src.wscale & PF_WSCALE_MASK);
3673 if (th->th_flags & TH_FIN)
3677 s->src.state = TCPS_SYN_SENT;
3678 s->dst.state = TCPS_CLOSED;
3679 s->timeout = PFTM_TCP_FIRST_PACKET;
3682 s->src.state = PFUDPS_SINGLE;
3683 s->dst.state = PFUDPS_NO_TRAFFIC;
3684 s->timeout = PFTM_UDP_FIRST_PACKET;
3688 case IPPROTO_ICMPV6:
3690 s->timeout = PFTM_ICMP_FIRST_PACKET;
3693 s->src.state = PFOTHERS_SINGLE;
3694 s->dst.state = PFOTHERS_NO_TRAFFIC;
3695 s->timeout = PFTM_OTHER_FIRST_PACKET;
3698 s->creation = time_uptime;
3699 s->expire = time_uptime;
3703 s->src_node->states++;
3706 /* XXX We only modify one side for now. */
3707 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3708 s->nat_src_node = nsn;
3709 s->nat_src_node->states++;
3711 if (pd->proto == IPPROTO_TCP) {
3712 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3713 off, pd, th, &s->src, &s->dst)) {
3714 REASON_SET(&reason, PFRES_MEMORY);
3715 pf_src_tree_remove_state(s);
3716 STATE_DEC_COUNTERS(s);
3717 uma_zfree(V_pf_state_z, s);
3720 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3721 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3722 &s->src, &s->dst, rewrite)) {
3723 /* This really shouldn't happen!!! */
3724 DPFPRINTF(PF_DEBUG_URGENT,
3725 ("pf_normalize_tcp_stateful failed on first pkt"));
3726 pf_normalize_tcp_cleanup(s);
3727 pf_src_tree_remove_state(s);
3728 STATE_DEC_COUNTERS(s);
3729 uma_zfree(V_pf_state_z, s);
3733 s->direction = pd->dir;
3736 * sk/nk could already been setup by pf_get_translation().
3739 KASSERT((sk == NULL && nk == NULL), ("%s: nr %p sk %p, nk %p",
3740 __func__, nr, sk, nk));
3741 sk = pf_state_key_setup(pd, pd->src, pd->dst, sport, dport);
3746 KASSERT((sk != NULL && nk != NULL), ("%s: nr %p sk %p, nk %p",
3747 __func__, nr, sk, nk));
3749 /* Swap sk/nk for PF_OUT. */
3750 if (pf_state_insert(BOUND_IFACE(r, kif),
3751 (pd->dir == PF_IN) ? sk : nk,
3752 (pd->dir == PF_IN) ? nk : sk, s)) {
3753 if (pd->proto == IPPROTO_TCP)
3754 pf_normalize_tcp_cleanup(s);
3755 REASON_SET(&reason, PFRES_STATEINS);
3756 pf_src_tree_remove_state(s);
3757 STATE_DEC_COUNTERS(s);
3758 uma_zfree(V_pf_state_z, s);
3763 pf_set_rt_ifp(s, pd->src); /* needs s->state_key set */
3766 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3767 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3768 s->src.state = PF_TCPS_PROXY_SRC;
3769 /* undo NAT changes, if they have taken place */
3771 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3772 if (pd->dir == PF_OUT)
3773 skt = s->key[PF_SK_STACK];
3774 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3775 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3777 *pd->sport = skt->port[pd->sidx];
3779 *pd->dport = skt->port[pd->didx];
3781 *pd->proto_sum = bproto_sum;
3783 *pd->ip_sum = bip_sum;
3784 m_copyback(m, off, hdrlen, pd->hdr.any);
3786 s->src.seqhi = htonl(arc4random());
3787 /* Find mss option */
3788 int rtid = M_GETFIB(m);
3789 mss = pf_get_mss(m, off, th->th_off, pd->af);
3790 mss = pf_calc_mss(pd->src, pd->af, rtid, mss);
3791 mss = pf_calc_mss(pd->dst, pd->af, rtid, mss);
3793 pf_send_tcp(NULL, r, pd->af, pd->dst, pd->src, th->th_dport,
3794 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3795 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL);
3796 REASON_SET(&reason, PFRES_SYNPROXY);
3797 return (PF_SYNPROXY_DROP);
3804 uma_zfree(V_pf_state_key_z, sk);
3806 uma_zfree(V_pf_state_key_z, nk);
3808 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3809 pf_unlink_src_node(sn);
3810 pf_free_src_node(sn);
3813 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3814 pf_unlink_src_node(nsn);
3815 pf_free_src_node(nsn);
3822 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3823 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3824 struct pf_ruleset **rsm)
3826 struct pf_rule *r, *a = NULL;
3827 struct pf_ruleset *ruleset = NULL;
3828 sa_family_t af = pd->af;
3833 struct pf_anchor_stackframe anchor_stack[PF_ANCHOR_STACKSIZE];
3837 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3840 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3841 r = r->skip[PF_SKIP_IFP].ptr;
3842 else if (r->direction && r->direction != direction)
3843 r = r->skip[PF_SKIP_DIR].ptr;
3844 else if (r->af && r->af != af)
3845 r = r->skip[PF_SKIP_AF].ptr;
3846 else if (r->proto && r->proto != pd->proto)
3847 r = r->skip[PF_SKIP_PROTO].ptr;
3848 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3849 r->src.neg, kif, M_GETFIB(m)))
3850 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3851 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3852 r->dst.neg, NULL, M_GETFIB(m)))
3853 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3854 else if (r->tos && !(r->tos == pd->tos))
3855 r = TAILQ_NEXT(r, entries);
3856 else if (r->os_fingerprint != PF_OSFP_ANY)
3857 r = TAILQ_NEXT(r, entries);
3858 else if (pd->proto == IPPROTO_UDP &&
3859 (r->src.port_op || r->dst.port_op))
3860 r = TAILQ_NEXT(r, entries);
3861 else if (pd->proto == IPPROTO_TCP &&
3862 (r->src.port_op || r->dst.port_op || r->flagset))
3863 r = TAILQ_NEXT(r, entries);
3864 else if ((pd->proto == IPPROTO_ICMP ||
3865 pd->proto == IPPROTO_ICMPV6) &&
3866 (r->type || r->code))
3867 r = TAILQ_NEXT(r, entries);
3868 else if (r->prob && r->prob <=
3869 (arc4random() % (UINT_MAX - 1) + 1))
3870 r = TAILQ_NEXT(r, entries);
3871 else if (r->match_tag && !pf_match_tag(m, r, &tag,
3872 pd->pf_mtag ? pd->pf_mtag->tag : 0))
3873 r = TAILQ_NEXT(r, entries);
3875 if (r->anchor == NULL) {
3882 r = TAILQ_NEXT(r, entries);
3884 pf_step_into_anchor(anchor_stack, &asd,
3885 &ruleset, PF_RULESET_FILTER, &r, &a,
3888 if (r == NULL && pf_step_out_of_anchor(anchor_stack, &asd,
3889 &ruleset, PF_RULESET_FILTER, &r, &a, &match))
3896 REASON_SET(&reason, PFRES_MATCH);
3899 PFLOG_PACKET(kif, m, af, direction, reason, r, a, ruleset, pd,
3902 if (r->action != PF_PASS)
3905 if (tag > 0 && pf_tag_packet(m, pd, tag)) {
3906 REASON_SET(&reason, PFRES_MEMORY);
3914 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3915 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3916 struct pf_pdesc *pd, u_short *reason, int *copyback)
3918 struct tcphdr *th = pd->hdr.tcp;
3919 u_int16_t win = ntohs(th->th_win);
3920 u_int32_t ack, end, seq, orig_seq;
3924 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3925 sws = src->wscale & PF_WSCALE_MASK;
3926 dws = dst->wscale & PF_WSCALE_MASK;
3931 * Sequence tracking algorithm from Guido van Rooij's paper:
3932 * http://www.madison-gurkha.com/publications/tcp_filtering/
3936 orig_seq = seq = ntohl(th->th_seq);
3937 if (src->seqlo == 0) {
3938 /* First packet from this end. Set its state */
3940 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3941 src->scrub == NULL) {
3942 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3943 REASON_SET(reason, PFRES_MEMORY);
3948 /* Deferred generation of sequence number modulator */
3949 if (dst->seqdiff && !src->seqdiff) {
3950 /* use random iss for the TCP server */
3951 while ((src->seqdiff = arc4random() - seq) == 0)
3953 ack = ntohl(th->th_ack) - dst->seqdiff;
3954 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3956 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3959 ack = ntohl(th->th_ack);
3962 end = seq + pd->p_len;
3963 if (th->th_flags & TH_SYN) {
3965 if (dst->wscale & PF_WSCALE_FLAG) {
3966 src->wscale = pf_get_wscale(m, off, th->th_off,
3968 if (src->wscale & PF_WSCALE_FLAG) {
3969 /* Remove scale factor from initial
3971 sws = src->wscale & PF_WSCALE_MASK;
3972 win = ((u_int32_t)win + (1 << sws) - 1)
3974 dws = dst->wscale & PF_WSCALE_MASK;
3976 /* fixup other window */
3977 dst->max_win <<= dst->wscale &
3979 /* in case of a retrans SYN|ACK */
3984 if (th->th_flags & TH_FIN)
3988 if (src->state < TCPS_SYN_SENT)
3989 src->state = TCPS_SYN_SENT;
3992 * May need to slide the window (seqhi may have been set by
3993 * the crappy stack check or if we picked up the connection
3994 * after establishment)
3996 if (src->seqhi == 1 ||
3997 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3998 src->seqhi = end + MAX(1, dst->max_win << dws);
3999 if (win > src->max_win)
4003 ack = ntohl(th->th_ack) - dst->seqdiff;
4005 /* Modulate sequence numbers */
4006 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
4008 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
4011 end = seq + pd->p_len;
4012 if (th->th_flags & TH_SYN)
4014 if (th->th_flags & TH_FIN)
4018 if ((th->th_flags & TH_ACK) == 0) {
4019 /* Let it pass through the ack skew check */
4021 } else if ((ack == 0 &&
4022 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4023 /* broken tcp stacks do not set ack */
4024 (dst->state < TCPS_SYN_SENT)) {
4026 * Many stacks (ours included) will set the ACK number in an
4027 * FIN|ACK if the SYN times out -- no sequence to ACK.
4033 /* Ease sequencing restrictions on no data packets */
4038 ackskew = dst->seqlo - ack;
4042 * Need to demodulate the sequence numbers in any TCP SACK options
4043 * (Selective ACK). We could optionally validate the SACK values
4044 * against the current ACK window, either forwards or backwards, but
4045 * I'm not confident that SACK has been implemented properly
4046 * everywhere. It wouldn't surprise me if several stacks accidently
4047 * SACK too far backwards of previously ACKed data. There really aren't
4048 * any security implications of bad SACKing unless the target stack
4049 * doesn't validate the option length correctly. Someone trying to
4050 * spoof into a TCP connection won't bother blindly sending SACK
4053 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4054 if (pf_modulate_sack(m, off, pd, th, dst))
4059 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4060 if (SEQ_GEQ(src->seqhi, end) &&
4061 /* Last octet inside other's window space */
4062 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4063 /* Retrans: not more than one window back */
4064 (ackskew >= -MAXACKWINDOW) &&
4065 /* Acking not more than one reassembled fragment backwards */
4066 (ackskew <= (MAXACKWINDOW << sws)) &&
4067 /* Acking not more than one window forward */
4068 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4069 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4070 (pd->flags & PFDESC_IP_REAS) == 0)) {
4071 /* Require an exact/+1 sequence match on resets when possible */
4073 if (dst->scrub || src->scrub) {
4074 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4075 *state, src, dst, copyback))
4079 /* update max window */
4080 if (src->max_win < win)
4082 /* synchronize sequencing */
4083 if (SEQ_GT(end, src->seqlo))
4085 /* slide the window of what the other end can send */
4086 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4087 dst->seqhi = ack + MAX((win << sws), 1);
4091 if (th->th_flags & TH_SYN)
4092 if (src->state < TCPS_SYN_SENT)
4093 src->state = TCPS_SYN_SENT;
4094 if (th->th_flags & TH_FIN)
4095 if (src->state < TCPS_CLOSING)
4096 src->state = TCPS_CLOSING;
4097 if (th->th_flags & TH_ACK) {
4098 if (dst->state == TCPS_SYN_SENT) {
4099 dst->state = TCPS_ESTABLISHED;
4100 if (src->state == TCPS_ESTABLISHED &&
4101 (*state)->src_node != NULL &&
4102 pf_src_connlimit(state)) {
4103 REASON_SET(reason, PFRES_SRCLIMIT);
4106 } else if (dst->state == TCPS_CLOSING)
4107 dst->state = TCPS_FIN_WAIT_2;
4109 if (th->th_flags & TH_RST)
4110 src->state = dst->state = TCPS_TIME_WAIT;
4112 /* update expire time */
4113 (*state)->expire = time_uptime;
4114 if (src->state >= TCPS_FIN_WAIT_2 &&
4115 dst->state >= TCPS_FIN_WAIT_2)
4116 (*state)->timeout = PFTM_TCP_CLOSED;
4117 else if (src->state >= TCPS_CLOSING &&
4118 dst->state >= TCPS_CLOSING)
4119 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4120 else if (src->state < TCPS_ESTABLISHED ||
4121 dst->state < TCPS_ESTABLISHED)
4122 (*state)->timeout = PFTM_TCP_OPENING;
4123 else if (src->state >= TCPS_CLOSING ||
4124 dst->state >= TCPS_CLOSING)
4125 (*state)->timeout = PFTM_TCP_CLOSING;
4127 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4129 /* Fall through to PASS packet */
4131 } else if ((dst->state < TCPS_SYN_SENT ||
4132 dst->state >= TCPS_FIN_WAIT_2 ||
4133 src->state >= TCPS_FIN_WAIT_2) &&
4134 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4135 /* Within a window forward of the originating packet */
4136 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4137 /* Within a window backward of the originating packet */
4140 * This currently handles three situations:
4141 * 1) Stupid stacks will shotgun SYNs before their peer
4143 * 2) When PF catches an already established stream (the
4144 * firewall rebooted, the state table was flushed, routes
4146 * 3) Packets get funky immediately after the connection
4147 * closes (this should catch Solaris spurious ACK|FINs
4148 * that web servers like to spew after a close)
4150 * This must be a little more careful than the above code
4151 * since packet floods will also be caught here. We don't
4152 * update the TTL here to mitigate the damage of a packet
4153 * flood and so the same code can handle awkward establishment
4154 * and a loosened connection close.
4155 * In the establishment case, a correct peer response will
4156 * validate the connection, go through the normal state code
4157 * and keep updating the state TTL.
4160 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4161 printf("pf: loose state match: ");
4162 pf_print_state(*state);
4163 pf_print_flags(th->th_flags);
4164 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4165 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack,
4166 pd->p_len, ackskew, (unsigned long long)(*state)->packets[0],
4167 (unsigned long long)(*state)->packets[1],
4168 pd->dir == PF_IN ? "in" : "out",
4169 pd->dir == (*state)->direction ? "fwd" : "rev");
4172 if (dst->scrub || src->scrub) {
4173 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4174 *state, src, dst, copyback))
4178 /* update max window */
4179 if (src->max_win < win)
4181 /* synchronize sequencing */
4182 if (SEQ_GT(end, src->seqlo))
4184 /* slide the window of what the other end can send */
4185 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4186 dst->seqhi = ack + MAX((win << sws), 1);
4189 * Cannot set dst->seqhi here since this could be a shotgunned
4190 * SYN and not an already established connection.
4193 if (th->th_flags & TH_FIN)
4194 if (src->state < TCPS_CLOSING)
4195 src->state = TCPS_CLOSING;
4196 if (th->th_flags & TH_RST)
4197 src->state = dst->state = TCPS_TIME_WAIT;
4199 /* Fall through to PASS packet */
4202 if ((*state)->dst.state == TCPS_SYN_SENT &&
4203 (*state)->src.state == TCPS_SYN_SENT) {
4204 /* Send RST for state mismatches during handshake */
4205 if (!(th->th_flags & TH_RST))
4206 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4207 pd->dst, pd->src, th->th_dport,
4208 th->th_sport, ntohl(th->th_ack), 0,
4210 (*state)->rule.ptr->return_ttl, 1, 0,
4215 } else if (V_pf_status.debug >= PF_DEBUG_MISC) {
4216 printf("pf: BAD state: ");
4217 pf_print_state(*state);
4218 pf_print_flags(th->th_flags);
4219 printf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4220 "pkts=%llu:%llu dir=%s,%s\n",
4221 seq, orig_seq, ack, pd->p_len, ackskew,
4222 (unsigned long long)(*state)->packets[0],
4223 (unsigned long long)(*state)->packets[1],
4224 pd->dir == PF_IN ? "in" : "out",
4225 pd->dir == (*state)->direction ? "fwd" : "rev");
4226 printf("pf: State failure on: %c %c %c %c | %c %c\n",
4227 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4228 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4230 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4231 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4232 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4233 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4235 REASON_SET(reason, PFRES_BADSTATE);
4243 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4244 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4246 struct tcphdr *th = pd->hdr.tcp;
4248 if (th->th_flags & TH_SYN)
4249 if (src->state < TCPS_SYN_SENT)
4250 src->state = TCPS_SYN_SENT;
4251 if (th->th_flags & TH_FIN)
4252 if (src->state < TCPS_CLOSING)
4253 src->state = TCPS_CLOSING;
4254 if (th->th_flags & TH_ACK) {
4255 if (dst->state == TCPS_SYN_SENT) {
4256 dst->state = TCPS_ESTABLISHED;
4257 if (src->state == TCPS_ESTABLISHED &&
4258 (*state)->src_node != NULL &&
4259 pf_src_connlimit(state)) {
4260 REASON_SET(reason, PFRES_SRCLIMIT);
4263 } else if (dst->state == TCPS_CLOSING) {
4264 dst->state = TCPS_FIN_WAIT_2;
4265 } else if (src->state == TCPS_SYN_SENT &&
4266 dst->state < TCPS_SYN_SENT) {
4268 * Handle a special sloppy case where we only see one
4269 * half of the connection. If there is a ACK after
4270 * the initial SYN without ever seeing a packet from
4271 * the destination, set the connection to established.
4273 dst->state = src->state = TCPS_ESTABLISHED;
4274 if ((*state)->src_node != NULL &&
4275 pf_src_connlimit(state)) {
4276 REASON_SET(reason, PFRES_SRCLIMIT);
4279 } else if (src->state == TCPS_CLOSING &&
4280 dst->state == TCPS_ESTABLISHED &&
4283 * Handle the closing of half connections where we
4284 * don't see the full bidirectional FIN/ACK+ACK
4287 dst->state = TCPS_CLOSING;
4290 if (th->th_flags & TH_RST)
4291 src->state = dst->state = TCPS_TIME_WAIT;
4293 /* update expire time */
4294 (*state)->expire = time_uptime;
4295 if (src->state >= TCPS_FIN_WAIT_2 &&
4296 dst->state >= TCPS_FIN_WAIT_2)
4297 (*state)->timeout = PFTM_TCP_CLOSED;
4298 else if (src->state >= TCPS_CLOSING &&
4299 dst->state >= TCPS_CLOSING)
4300 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4301 else if (src->state < TCPS_ESTABLISHED ||
4302 dst->state < TCPS_ESTABLISHED)
4303 (*state)->timeout = PFTM_TCP_OPENING;
4304 else if (src->state >= TCPS_CLOSING ||
4305 dst->state >= TCPS_CLOSING)
4306 (*state)->timeout = PFTM_TCP_CLOSING;
4308 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4314 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4315 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4318 struct pf_state_key_cmp key;
4319 struct tcphdr *th = pd->hdr.tcp;
4321 struct pf_state_peer *src, *dst;
4322 struct pf_state_key *sk;
4324 bzero(&key, sizeof(key));
4326 key.proto = IPPROTO_TCP;
4327 if (direction == PF_IN) { /* wire side, straight */
4328 PF_ACPY(&key.addr[0], pd->src, key.af);
4329 PF_ACPY(&key.addr[1], pd->dst, key.af);
4330 key.port[0] = th->th_sport;
4331 key.port[1] = th->th_dport;
4332 } else { /* stack side, reverse */
4333 PF_ACPY(&key.addr[1], pd->src, key.af);
4334 PF_ACPY(&key.addr[0], pd->dst, key.af);
4335 key.port[1] = th->th_sport;
4336 key.port[0] = th->th_dport;
4339 STATE_LOOKUP(kif, &key, direction, *state, pd);
4341 if (direction == (*state)->direction) {
4342 src = &(*state)->src;
4343 dst = &(*state)->dst;
4345 src = &(*state)->dst;
4346 dst = &(*state)->src;
4349 sk = (*state)->key[pd->didx];
4351 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4352 if (direction != (*state)->direction) {
4353 REASON_SET(reason, PFRES_SYNPROXY);
4354 return (PF_SYNPROXY_DROP);
4356 if (th->th_flags & TH_SYN) {
4357 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4358 REASON_SET(reason, PFRES_SYNPROXY);
4361 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4362 pd->src, th->th_dport, th->th_sport,
4363 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4364 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1, 0, NULL);
4365 REASON_SET(reason, PFRES_SYNPROXY);
4366 return (PF_SYNPROXY_DROP);
4367 } else if (!(th->th_flags & TH_ACK) ||
4368 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4369 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4370 REASON_SET(reason, PFRES_SYNPROXY);
4372 } else if ((*state)->src_node != NULL &&
4373 pf_src_connlimit(state)) {
4374 REASON_SET(reason, PFRES_SRCLIMIT);
4377 (*state)->src.state = PF_TCPS_PROXY_DST;
4379 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4380 if (direction == (*state)->direction) {
4381 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4382 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4383 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4384 REASON_SET(reason, PFRES_SYNPROXY);
4387 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4388 if ((*state)->dst.seqhi == 1)
4389 (*state)->dst.seqhi = htonl(arc4random());
4390 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4391 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4392 sk->port[pd->sidx], sk->port[pd->didx],
4393 (*state)->dst.seqhi, 0, TH_SYN, 0,
4394 (*state)->src.mss, 0, 0, (*state)->tag, NULL);
4395 REASON_SET(reason, PFRES_SYNPROXY);
4396 return (PF_SYNPROXY_DROP);
4397 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4399 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4400 REASON_SET(reason, PFRES_SYNPROXY);
4403 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4404 (*state)->dst.seqlo = ntohl(th->th_seq);
4405 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af, pd->dst,
4406 pd->src, th->th_dport, th->th_sport,
4407 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4408 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4409 (*state)->tag, NULL);
4410 pf_send_tcp(NULL, (*state)->rule.ptr, pd->af,
4411 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4412 sk->port[pd->sidx], sk->port[pd->didx],
4413 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4414 TH_ACK, (*state)->dst.max_win, 0, 0, 1, 0, NULL);
4415 (*state)->src.seqdiff = (*state)->dst.seqhi -
4416 (*state)->src.seqlo;
4417 (*state)->dst.seqdiff = (*state)->src.seqhi -
4418 (*state)->dst.seqlo;
4419 (*state)->src.seqhi = (*state)->src.seqlo +
4420 (*state)->dst.max_win;
4421 (*state)->dst.seqhi = (*state)->dst.seqlo +
4422 (*state)->src.max_win;
4423 (*state)->src.wscale = (*state)->dst.wscale = 0;
4424 (*state)->src.state = (*state)->dst.state =
4426 REASON_SET(reason, PFRES_SYNPROXY);
4427 return (PF_SYNPROXY_DROP);
4431 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4432 dst->state >= TCPS_FIN_WAIT_2 &&
4433 src->state >= TCPS_FIN_WAIT_2) {
4434 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4435 printf("pf: state reuse ");
4436 pf_print_state(*state);
4437 pf_print_flags(th->th_flags);
4440 /* XXX make sure it's the same direction ?? */
4441 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4442 pf_unlink_state(*state, PF_ENTER_LOCKED);
4447 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4448 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4451 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4452 ©back) == PF_DROP)
4456 /* translate source/destination address, if necessary */
4457 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4458 struct pf_state_key *nk = (*state)->key[pd->didx];
4460 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4461 nk->port[pd->sidx] != th->th_sport)
4462 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4463 &th->th_sum, &nk->addr[pd->sidx],
4464 nk->port[pd->sidx], 0, pd->af);
4466 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4467 nk->port[pd->didx] != th->th_dport)
4468 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4469 &th->th_sum, &nk->addr[pd->didx],
4470 nk->port[pd->didx], 0, pd->af);
4474 /* Copyback sequence modulation or stateful scrub changes if needed */
4476 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4482 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4483 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4485 struct pf_state_peer *src, *dst;
4486 struct pf_state_key_cmp key;
4487 struct udphdr *uh = pd->hdr.udp;
4489 bzero(&key, sizeof(key));
4491 key.proto = IPPROTO_UDP;
4492 if (direction == PF_IN) { /* wire side, straight */
4493 PF_ACPY(&key.addr[0], pd->src, key.af);
4494 PF_ACPY(&key.addr[1], pd->dst, key.af);
4495 key.port[0] = uh->uh_sport;
4496 key.port[1] = uh->uh_dport;
4497 } else { /* stack side, reverse */
4498 PF_ACPY(&key.addr[1], pd->src, key.af);
4499 PF_ACPY(&key.addr[0], pd->dst, key.af);
4500 key.port[1] = uh->uh_sport;
4501 key.port[0] = uh->uh_dport;
4504 STATE_LOOKUP(kif, &key, direction, *state, pd);
4506 if (direction == (*state)->direction) {
4507 src = &(*state)->src;
4508 dst = &(*state)->dst;
4510 src = &(*state)->dst;
4511 dst = &(*state)->src;
4515 if (src->state < PFUDPS_SINGLE)
4516 src->state = PFUDPS_SINGLE;
4517 if (dst->state == PFUDPS_SINGLE)
4518 dst->state = PFUDPS_MULTIPLE;
4520 /* update expire time */
4521 (*state)->expire = time_uptime;
4522 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4523 (*state)->timeout = PFTM_UDP_MULTIPLE;
4525 (*state)->timeout = PFTM_UDP_SINGLE;
4527 /* translate source/destination address, if necessary */
4528 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4529 struct pf_state_key *nk = (*state)->key[pd->didx];
4531 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4532 nk->port[pd->sidx] != uh->uh_sport)
4533 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4534 &uh->uh_sum, &nk->addr[pd->sidx],
4535 nk->port[pd->sidx], 1, pd->af);
4537 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4538 nk->port[pd->didx] != uh->uh_dport)
4539 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4540 &uh->uh_sum, &nk->addr[pd->didx],
4541 nk->port[pd->didx], 1, pd->af);
4542 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4549 pf_icmp_state_lookup(struct pf_state_key_cmp *key, struct pf_pdesc *pd,
4550 struct pf_state **state, struct mbuf *m, int direction, struct pfi_kif *kif,
4551 uint16_t icmpid, uint16_t type, int icmp_dir, int *iidx, int multi)
4555 key->proto = pd->proto;
4556 if (icmp_dir == PF_IN) {
4558 key->port[pd->sidx] = icmpid;
4559 key->port[pd->didx] = type;
4562 key->port[pd->sidx] = type;
4563 key->port[pd->didx] = icmpid;
4566 if (pd->af == AF_INET6 && multi != PF_ICMP_MULTI_NONE) {
4568 case PF_ICMP_MULTI_SOLICITED:
4569 key->addr[pd->sidx].addr32[0] = IPV6_ADDR_INT32_MLL;
4570 key->addr[pd->sidx].addr32[1] = 0;
4571 key->addr[pd->sidx].addr32[2] = IPV6_ADDR_INT32_ONE;
4572 key->addr[pd->sidx].addr32[3] = pd->src->addr32[3];
4573 key->addr[pd->sidx].addr8[12] = 0xff;
4575 case PF_ICMP_MULTI_LINK:
4576 key->addr[pd->sidx].addr32[0] = IPV6_ADDR_INT32_MLL;
4577 key->addr[pd->sidx].addr32[1] = 0;
4578 key->addr[pd->sidx].addr32[2] = 0;
4579 key->addr[pd->sidx].addr32[3] = IPV6_ADDR_INT32_ONE;
4584 PF_ACPY(&key->addr[pd->sidx], pd->src, key->af);
4585 PF_ACPY(&key->addr[pd->didx], pd->dst, key->af);
4587 STATE_LOOKUP(kif, key, direction, *state, pd);
4589 /* Is this ICMP message flowing in right direction? */
4590 if ((*state)->rule.ptr->type &&
4591 (((*state)->direction == direction) ?
4592 PF_IN : PF_OUT) != icmp_dir) {
4593 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4594 printf("pf: icmp type %d in wrong direction (%d): ",
4595 icmp_dir, direction);
4596 pf_print_state(*state);
4605 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4606 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4608 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4609 u_int16_t icmpid = 0, *icmpsum, virtual_id, virtual_type;
4611 int icmp_dir, iidx, ret, multi;
4612 struct pf_state_key_cmp key;
4614 bzero(&key, sizeof(key));
4615 switch (pd->proto) {
4618 icmptype = pd->hdr.icmp->icmp_type;
4619 icmpid = pd->hdr.icmp->icmp_id;
4620 icmpsum = &pd->hdr.icmp->icmp_cksum;
4625 case IPPROTO_ICMPV6:
4626 icmptype = pd->hdr.icmp6->icmp6_type;
4627 icmpid = pd->hdr.icmp6->icmp6_id;
4628 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4633 panic("%s: proto %d\n", __func__, pd->proto);
4636 if (pf_icmp_mapping(pd, icmptype, &icmp_dir, &multi,
4637 &virtual_id, &virtual_type) == 0) {
4639 * ICMP query/reply message not related to a TCP/UDP packet.
4640 * Search for an ICMP state.
4642 ret = pf_icmp_state_lookup(&key, pd, state, m, direction,
4643 kif, virtual_id, virtual_type, icmp_dir, &iidx,
4644 PF_ICMP_MULTI_NONE);
4646 if (ret == PF_DROP && pd->af == AF_INET6 &&
4647 icmp_dir == PF_OUT) {
4649 PF_STATE_UNLOCK(*state);
4650 ret = pf_icmp_state_lookup(&key, pd, state, m,
4651 direction, kif, virtual_id, virtual_type,
4652 icmp_dir, &iidx, multi);
4659 (*state)->expire = time_uptime;
4660 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4662 /* translate source/destination address, if necessary */
4663 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4664 struct pf_state_key *nk = (*state)->key[pd->didx];
4669 if (PF_ANEQ(pd->src,
4670 &nk->addr[pd->sidx], AF_INET))
4671 pf_change_a(&saddr->v4.s_addr,
4673 nk->addr[pd->sidx].v4.s_addr, 0);
4675 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4677 pf_change_a(&daddr->v4.s_addr,
4679 nk->addr[pd->didx].v4.s_addr, 0);
4681 if (nk->port[iidx] !=
4682 pd->hdr.icmp->icmp_id) {
4683 pd->hdr.icmp->icmp_cksum =
4685 pd->hdr.icmp->icmp_cksum, icmpid,
4687 pd->hdr.icmp->icmp_id = nk->port[iidx];
4690 m_copyback(m, off, ICMP_MINLEN,
4691 (caddr_t )pd->hdr.icmp);
4696 if (PF_ANEQ(pd->src,
4697 &nk->addr[pd->sidx], AF_INET6))
4699 &pd->hdr.icmp6->icmp6_cksum,
4700 &nk->addr[pd->sidx], 0);
4702 if (PF_ANEQ(pd->dst,
4703 &nk->addr[pd->didx], AF_INET6))
4705 &pd->hdr.icmp6->icmp6_cksum,
4706 &nk->addr[pd->didx], 0);
4708 m_copyback(m, off, sizeof(struct icmp6_hdr),
4709 (caddr_t )pd->hdr.icmp6);
4718 * ICMP error message in response to a TCP/UDP packet.
4719 * Extract the inner TCP/UDP header and search for that state.
4722 struct pf_pdesc pd2;
4723 bzero(&pd2, sizeof pd2);
4728 struct ip6_hdr h2_6;
4735 /* Payload packet is from the opposite direction. */
4736 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4737 pd2.didx = (direction == PF_IN) ? 0 : 1;
4741 /* offset of h2 in mbuf chain */
4742 ipoff2 = off + ICMP_MINLEN;
4744 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4745 NULL, reason, pd2.af)) {
4746 DPFPRINTF(PF_DEBUG_MISC,
4747 ("pf: ICMP error message too short "
4752 * ICMP error messages don't refer to non-first
4755 if (h2.ip_off & htons(IP_OFFMASK)) {
4756 REASON_SET(reason, PFRES_FRAG);
4760 /* offset of protocol header that follows h2 */
4761 off2 = ipoff2 + (h2.ip_hl << 2);
4763 pd2.proto = h2.ip_p;
4764 pd2.src = (struct pf_addr *)&h2.ip_src;
4765 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4766 pd2.ip_sum = &h2.ip_sum;
4771 ipoff2 = off + sizeof(struct icmp6_hdr);
4773 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4774 NULL, reason, pd2.af)) {
4775 DPFPRINTF(PF_DEBUG_MISC,
4776 ("pf: ICMP error message too short "
4780 pd2.proto = h2_6.ip6_nxt;
4781 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4782 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4784 off2 = ipoff2 + sizeof(h2_6);
4786 switch (pd2.proto) {
4787 case IPPROTO_FRAGMENT:
4789 * ICMPv6 error messages for
4790 * non-first fragments
4792 REASON_SET(reason, PFRES_FRAG);
4795 case IPPROTO_HOPOPTS:
4796 case IPPROTO_ROUTING:
4797 case IPPROTO_DSTOPTS: {
4798 /* get next header and header length */
4799 struct ip6_ext opt6;
4801 if (!pf_pull_hdr(m, off2, &opt6,
4802 sizeof(opt6), NULL, reason,
4804 DPFPRINTF(PF_DEBUG_MISC,
4805 ("pf: ICMPv6 short opt\n"));
4808 if (pd2.proto == IPPROTO_AH)
4809 off2 += (opt6.ip6e_len + 2) * 4;
4811 off2 += (opt6.ip6e_len + 1) * 8;
4812 pd2.proto = opt6.ip6e_nxt;
4813 /* goto the next header */
4820 } while (!terminal);
4825 switch (pd2.proto) {
4829 struct pf_state_peer *src, *dst;
4834 * Only the first 8 bytes of the TCP header can be
4835 * expected. Don't access any TCP header fields after
4836 * th_seq, an ackskew test is not possible.
4838 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4840 DPFPRINTF(PF_DEBUG_MISC,
4841 ("pf: ICMP error message too short "
4847 key.proto = IPPROTO_TCP;
4848 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4849 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4850 key.port[pd2.sidx] = th.th_sport;
4851 key.port[pd2.didx] = th.th_dport;
4853 STATE_LOOKUP(kif, &key, direction, *state, pd);
4855 if (direction == (*state)->direction) {
4856 src = &(*state)->dst;
4857 dst = &(*state)->src;
4859 src = &(*state)->src;
4860 dst = &(*state)->dst;
4863 if (src->wscale && dst->wscale)
4864 dws = dst->wscale & PF_WSCALE_MASK;
4868 /* Demodulate sequence number */
4869 seq = ntohl(th.th_seq) - src->seqdiff;
4871 pf_change_a(&th.th_seq, icmpsum,
4876 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4877 (!SEQ_GEQ(src->seqhi, seq) ||
4878 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4879 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4880 printf("pf: BAD ICMP %d:%d ",
4881 icmptype, pd->hdr.icmp->icmp_code);
4882 pf_print_host(pd->src, 0, pd->af);
4884 pf_print_host(pd->dst, 0, pd->af);
4886 pf_print_state(*state);
4887 printf(" seq=%u\n", seq);
4889 REASON_SET(reason, PFRES_BADSTATE);
4892 if (V_pf_status.debug >= PF_DEBUG_MISC) {
4893 printf("pf: OK ICMP %d:%d ",
4894 icmptype, pd->hdr.icmp->icmp_code);
4895 pf_print_host(pd->src, 0, pd->af);
4897 pf_print_host(pd->dst, 0, pd->af);
4899 pf_print_state(*state);
4900 printf(" seq=%u\n", seq);
4904 /* translate source/destination address, if necessary */
4905 if ((*state)->key[PF_SK_WIRE] !=
4906 (*state)->key[PF_SK_STACK]) {
4907 struct pf_state_key *nk =
4908 (*state)->key[pd->didx];
4910 if (PF_ANEQ(pd2.src,
4911 &nk->addr[pd2.sidx], pd2.af) ||
4912 nk->port[pd2.sidx] != th.th_sport)
4913 pf_change_icmp(pd2.src, &th.th_sport,
4914 daddr, &nk->addr[pd2.sidx],
4915 nk->port[pd2.sidx], NULL,
4916 pd2.ip_sum, icmpsum,
4917 pd->ip_sum, 0, pd2.af);
4919 if (PF_ANEQ(pd2.dst,
4920 &nk->addr[pd2.didx], pd2.af) ||
4921 nk->port[pd2.didx] != th.th_dport)
4922 pf_change_icmp(pd2.dst, &th.th_dport,
4923 NULL, /* XXX Inbound NAT? */
4924 &nk->addr[pd2.didx],
4925 nk->port[pd2.didx], NULL,
4926 pd2.ip_sum, icmpsum,
4927 pd->ip_sum, 0, pd2.af);
4935 m_copyback(m, off, ICMP_MINLEN,
4936 (caddr_t )pd->hdr.icmp);
4937 m_copyback(m, ipoff2, sizeof(h2),
4944 sizeof(struct icmp6_hdr),
4945 (caddr_t )pd->hdr.icmp6);
4946 m_copyback(m, ipoff2, sizeof(h2_6),
4951 m_copyback(m, off2, 8, (caddr_t)&th);
4960 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4961 NULL, reason, pd2.af)) {
4962 DPFPRINTF(PF_DEBUG_MISC,
4963 ("pf: ICMP error message too short "
4969 key.proto = IPPROTO_UDP;
4970 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4971 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4972 key.port[pd2.sidx] = uh.uh_sport;
4973 key.port[pd2.didx] = uh.uh_dport;
4975 STATE_LOOKUP(kif, &key, direction, *state, pd);
4977 /* translate source/destination address, if necessary */
4978 if ((*state)->key[PF_SK_WIRE] !=
4979 (*state)->key[PF_SK_STACK]) {
4980 struct pf_state_key *nk =
4981 (*state)->key[pd->didx];
4983 if (PF_ANEQ(pd2.src,
4984 &nk->addr[pd2.sidx], pd2.af) ||
4985 nk->port[pd2.sidx] != uh.uh_sport)
4986 pf_change_icmp(pd2.src, &uh.uh_sport,
4987 daddr, &nk->addr[pd2.sidx],
4988 nk->port[pd2.sidx], &uh.uh_sum,
4989 pd2.ip_sum, icmpsum,
4990 pd->ip_sum, 1, pd2.af);
4992 if (PF_ANEQ(pd2.dst,
4993 &nk->addr[pd2.didx], pd2.af) ||
4994 nk->port[pd2.didx] != uh.uh_dport)
4995 pf_change_icmp(pd2.dst, &uh.uh_dport,
4996 NULL, /* XXX Inbound NAT? */
4997 &nk->addr[pd2.didx],
4998 nk->port[pd2.didx], &uh.uh_sum,
4999 pd2.ip_sum, icmpsum,
5000 pd->ip_sum, 1, pd2.af);
5005 m_copyback(m, off, ICMP_MINLEN,
5006 (caddr_t )pd->hdr.icmp);
5007 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5013 sizeof(struct icmp6_hdr),
5014 (caddr_t )pd->hdr.icmp6);
5015 m_copyback(m, ipoff2, sizeof(h2_6),
5020 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5026 case IPPROTO_ICMP: {
5029 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5030 NULL, reason, pd2.af)) {
5031 DPFPRINTF(PF_DEBUG_MISC,
5032 ("pf: ICMP error message too short i"
5037 pd2.hdr.icmp = &iih;
5038 pf_icmp_mapping(&pd2, iih.icmp_type,
5039 &icmp_dir, &multi, &virtual_id, &virtual_type);
5041 ret = pf_icmp_state_lookup(&key, &pd2, state, m,
5042 direction, kif, virtual_id, virtual_type,
5043 icmp_dir, &iidx, PF_ICMP_MULTI_NONE);
5047 /* translate source/destination address, if necessary */
5048 if ((*state)->key[PF_SK_WIRE] !=
5049 (*state)->key[PF_SK_STACK]) {
5050 struct pf_state_key *nk =
5051 (*state)->key[pd->didx];
5053 if (PF_ANEQ(pd2.src,
5054 &nk->addr[pd2.sidx], pd2.af) ||
5055 (virtual_type == ICMP_ECHO &&
5056 nk->port[iidx] != iih.icmp_id))
5057 pf_change_icmp(pd2.src,
5058 (virtual_type == ICMP_ECHO) ?
5059 &iih.icmp_id : NULL,
5060 daddr, &nk->addr[pd2.sidx],
5061 nk->port[pd2.sidx], NULL,
5062 pd2.ip_sum, icmpsum,
5063 pd->ip_sum, 0, AF_INET);
5065 if (PF_ANEQ(pd2.dst,
5066 &nk->addr[pd2.didx], pd2.af))
5067 pf_change_icmp(pd2.dst, NULL, NULL,
5068 &nk->addr[pd2.didx], 0, NULL,
5069 pd2.ip_sum, icmpsum,
5070 pd->ip_sum, 0, AF_INET);
5072 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5073 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5074 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5081 case IPPROTO_ICMPV6: {
5082 struct icmp6_hdr iih;
5084 if (!pf_pull_hdr(m, off2, &iih,
5085 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5086 DPFPRINTF(PF_DEBUG_MISC,
5087 ("pf: ICMP error message too short "
5092 pd2.hdr.icmp6 = &iih;
5093 pf_icmp_mapping(&pd2, iih.icmp6_type,
5094 &icmp_dir, &multi, &virtual_id, &virtual_type);
5095 ret = pf_icmp_state_lookup(&key, &pd2, state, m,
5096 direction, kif, virtual_id, virtual_type,
5097 icmp_dir, &iidx, PF_ICMP_MULTI_NONE);
5099 if (ret == PF_DROP && pd->af == AF_INET6 &&
5100 icmp_dir == PF_OUT) {
5102 PF_STATE_UNLOCK(*state);
5103 ret = pf_icmp_state_lookup(&key, pd,
5104 state, m, direction, kif,
5105 virtual_id, virtual_type,
5106 icmp_dir, &iidx, multi);
5113 /* translate source/destination address, if necessary */
5114 if ((*state)->key[PF_SK_WIRE] !=
5115 (*state)->key[PF_SK_STACK]) {
5116 struct pf_state_key *nk =
5117 (*state)->key[pd->didx];
5119 if (PF_ANEQ(pd2.src,
5120 &nk->addr[pd2.sidx], pd2.af) ||
5121 ((virtual_type == ICMP6_ECHO_REQUEST) &&
5122 nk->port[pd2.sidx] != iih.icmp6_id))
5123 pf_change_icmp(pd2.src,
5124 (virtual_type == ICMP6_ECHO_REQUEST)
5125 ? &iih.icmp6_id : NULL,
5126 daddr, &nk->addr[pd2.sidx],
5127 (virtual_type == ICMP6_ECHO_REQUEST)
5128 ? nk->port[iidx] : 0, NULL,
5129 pd2.ip_sum, icmpsum,
5130 pd->ip_sum, 0, AF_INET6);
5132 if (PF_ANEQ(pd2.dst,
5133 &nk->addr[pd2.didx], pd2.af))
5134 pf_change_icmp(pd2.dst, NULL, NULL,
5135 &nk->addr[pd2.didx], 0, NULL,
5136 pd2.ip_sum, icmpsum,
5137 pd->ip_sum, 0, AF_INET6);
5139 m_copyback(m, off, sizeof(struct icmp6_hdr),
5140 (caddr_t)pd->hdr.icmp6);
5141 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5142 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5151 key.proto = pd2.proto;
5152 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5153 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5154 key.port[0] = key.port[1] = 0;
5156 STATE_LOOKUP(kif, &key, direction, *state, pd);
5158 /* translate source/destination address, if necessary */
5159 if ((*state)->key[PF_SK_WIRE] !=
5160 (*state)->key[PF_SK_STACK]) {
5161 struct pf_state_key *nk =
5162 (*state)->key[pd->didx];
5164 if (PF_ANEQ(pd2.src,
5165 &nk->addr[pd2.sidx], pd2.af))
5166 pf_change_icmp(pd2.src, NULL, daddr,
5167 &nk->addr[pd2.sidx], 0, NULL,
5168 pd2.ip_sum, icmpsum,
5169 pd->ip_sum, 0, pd2.af);
5171 if (PF_ANEQ(pd2.dst,
5172 &nk->addr[pd2.didx], pd2.af))
5173 pf_change_icmp(pd2.src, NULL,
5174 NULL, /* XXX Inbound NAT? */
5175 &nk->addr[pd2.didx], 0, NULL,
5176 pd2.ip_sum, icmpsum,
5177 pd->ip_sum, 0, pd2.af);
5182 m_copyback(m, off, ICMP_MINLEN,
5183 (caddr_t)pd->hdr.icmp);
5184 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5190 sizeof(struct icmp6_hdr),
5191 (caddr_t )pd->hdr.icmp6);
5192 m_copyback(m, ipoff2, sizeof(h2_6),
5206 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5207 struct mbuf *m, struct pf_pdesc *pd)
5209 struct pf_state_peer *src, *dst;
5210 struct pf_state_key_cmp key;
5212 bzero(&key, sizeof(key));
5214 key.proto = pd->proto;
5215 if (direction == PF_IN) {
5216 PF_ACPY(&key.addr[0], pd->src, key.af);
5217 PF_ACPY(&key.addr[1], pd->dst, key.af);
5218 key.port[0] = key.port[1] = 0;
5220 PF_ACPY(&key.addr[1], pd->src, key.af);
5221 PF_ACPY(&key.addr[0], pd->dst, key.af);
5222 key.port[1] = key.port[0] = 0;
5225 STATE_LOOKUP(kif, &key, direction, *state, pd);
5227 if (direction == (*state)->direction) {
5228 src = &(*state)->src;
5229 dst = &(*state)->dst;
5231 src = &(*state)->dst;
5232 dst = &(*state)->src;
5236 if (src->state < PFOTHERS_SINGLE)
5237 src->state = PFOTHERS_SINGLE;
5238 if (dst->state == PFOTHERS_SINGLE)
5239 dst->state = PFOTHERS_MULTIPLE;
5241 /* update expire time */
5242 (*state)->expire = time_uptime;
5243 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5244 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5246 (*state)->timeout = PFTM_OTHER_SINGLE;
5248 /* translate source/destination address, if necessary */
5249 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5250 struct pf_state_key *nk = (*state)->key[pd->didx];
5252 KASSERT(nk, ("%s: nk is null", __func__));
5253 KASSERT(pd, ("%s: pd is null", __func__));
5254 KASSERT(pd->src, ("%s: pd->src is null", __func__));
5255 KASSERT(pd->dst, ("%s: pd->dst is null", __func__));
5259 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5260 pf_change_a(&pd->src->v4.s_addr,
5262 nk->addr[pd->sidx].v4.s_addr,
5266 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5267 pf_change_a(&pd->dst->v4.s_addr,
5269 nk->addr[pd->didx].v4.s_addr,
5276 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5277 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5279 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5280 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5288 * ipoff and off are measured from the start of the mbuf chain.
5289 * h must be at "ipoff" on the mbuf chain.
5292 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5293 u_short *actionp, u_short *reasonp, sa_family_t af)
5298 struct ip *h = mtod(m, struct ip *);
5299 u_int16_t fragoff = (ntohs(h->ip_off) & IP_OFFMASK) << 3;
5303 ACTION_SET(actionp, PF_PASS);
5305 ACTION_SET(actionp, PF_DROP);
5306 REASON_SET(reasonp, PFRES_FRAG);
5310 if (m->m_pkthdr.len < off + len ||
5311 ntohs(h->ip_len) < off + len) {
5312 ACTION_SET(actionp, PF_DROP);
5313 REASON_SET(reasonp, PFRES_SHORT);
5321 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5323 if (m->m_pkthdr.len < off + len ||
5324 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5325 (unsigned)(off + len)) {
5326 ACTION_SET(actionp, PF_DROP);
5327 REASON_SET(reasonp, PFRES_SHORT);
5334 m_copydata(m, off, len, p);
5339 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif,
5343 struct radix_node_head *rnh;
5345 struct sockaddr_in *dst;
5349 struct sockaddr_in6 *dst6;
5350 struct route_in6 ro;
5354 struct radix_node *rn;
5360 /* XXX: stick to table 0 for now */
5361 rnh = rt_tables_get_rnh(0, af);
5362 if (rnh != NULL && rn_mpath_capable(rnh))
5365 bzero(&ro, sizeof(ro));
5368 dst = satosin(&ro.ro_dst);
5369 dst->sin_family = AF_INET;
5370 dst->sin_len = sizeof(*dst);
5371 dst->sin_addr = addr->v4;
5376 * Skip check for addresses with embedded interface scope,
5377 * as they would always match anyway.
5379 if (IN6_IS_SCOPE_EMBED(&addr->v6))
5381 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5382 dst6->sin6_family = AF_INET6;
5383 dst6->sin6_len = sizeof(*dst6);
5384 dst6->sin6_addr = addr->v6;
5391 /* Skip checks for ipsec interfaces */
5392 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5398 in6_rtalloc_ign(&ro, 0, rtableid);
5403 in_rtalloc_ign((struct route *)&ro, 0, rtableid);
5407 rtalloc_ign((struct route *)&ro, 0); /* No/default FIB. */
5411 if (ro.ro_rt != NULL) {
5412 /* No interface given, this is a no-route check */
5416 if (kif->pfik_ifp == NULL) {
5421 /* Perform uRPF check if passed input interface */
5423 rn = (struct radix_node *)ro.ro_rt;
5425 rt = (struct rtentry *)rn;
5428 if (kif->pfik_ifp == ifp)
5431 rn = rn_mpath_next(rn);
5433 } while (check_mpath == 1 && rn != NULL && ret == 0);
5437 if (ro.ro_rt != NULL)
5444 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5445 struct pf_state *s, struct pf_pdesc *pd)
5447 struct mbuf *m0, *m1;
5448 struct sockaddr_in dst;
5450 struct ifnet *ifp = NULL;
5451 struct pf_addr naddr;
5452 struct pf_src_node *sn = NULL;
5454 uint16_t ip_len, ip_off;
5456 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5457 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5460 if ((pd->pf_mtag == NULL &&
5461 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5462 pd->pf_mtag->routed++ > 3) {
5468 if (r->rt == PF_DUPTO) {
5469 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5475 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5483 ip = mtod(m0, struct ip *);
5485 bzero(&dst, sizeof(dst));
5486 dst.sin_family = AF_INET;
5487 dst.sin_len = sizeof(dst);
5488 dst.sin_addr = ip->ip_dst;
5490 if (r->rt == PF_FASTROUTE) {
5495 rt = rtalloc1_fib(sintosa(&dst), 0, 0, M_GETFIB(m0));
5497 KMOD_IPSTAT_INC(ips_noroute);
5498 error = EHOSTUNREACH;
5503 counter_u64_add(rt->rt_pksent, 1);
5505 if (rt->rt_flags & RTF_GATEWAY)
5506 bcopy(satosin(rt->rt_gateway), &dst, sizeof(dst));
5509 if (TAILQ_EMPTY(&r->rpool.list)) {
5510 DPFPRINTF(PF_DEBUG_URGENT,
5511 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5515 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5517 if (!PF_AZERO(&naddr, AF_INET))
5518 dst.sin_addr.s_addr = naddr.v4.s_addr;
5519 ifp = r->rpool.cur->kif ?
5520 r->rpool.cur->kif->pfik_ifp : NULL;
5522 if (!PF_AZERO(&s->rt_addr, AF_INET))
5523 dst.sin_addr.s_addr =
5524 s->rt_addr.v4.s_addr;
5525 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5533 if (pf_test(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5535 else if (m0 == NULL)
5537 if (m0->m_len < sizeof(struct ip)) {
5538 DPFPRINTF(PF_DEBUG_URGENT,
5539 ("%s: m0->m_len < sizeof(struct ip)\n", __func__));
5542 ip = mtod(m0, struct ip *);
5545 if (ifp->if_flags & IFF_LOOPBACK)
5546 m0->m_flags |= M_SKIP_FIREWALL;
5548 ip_len = ntohs(ip->ip_len);
5549 ip_off = ntohs(ip->ip_off);
5551 /* Copied from FreeBSD 10.0-CURRENT ip_output. */
5552 m0->m_pkthdr.csum_flags |= CSUM_IP;
5553 if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
5554 in_delayed_cksum(m0);
5555 m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
5558 if (m0->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
5559 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
5560 m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
5565 * If small enough for interface, or the interface will take
5566 * care of the fragmentation for us, we can just send directly.
5568 if (ip_len <= ifp->if_mtu ||
5569 (m0->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
5570 ((ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
5572 if (m0->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
5573 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5574 m0->m_pkthdr.csum_flags &= ~CSUM_IP;
5576 m_clrprotoflags(m0); /* Avoid confusing lower layers. */
5577 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5581 /* Balk when DF bit is set or the interface didn't support TSO. */
5582 if ((ip_off & IP_DF) || (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5584 KMOD_IPSTAT_INC(ips_cantfrag);
5585 if (r->rt != PF_DUPTO) {
5586 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5593 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist);
5597 for (; m0; m0 = m1) {
5599 m0->m_nextpkt = NULL;
5601 m_clrprotoflags(m0);
5602 error = (*ifp->if_output)(ifp, m0, sintosa(&dst), NULL);
5608 KMOD_IPSTAT_INC(ips_fragmented);
5611 if (r->rt != PF_DUPTO)
5626 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5627 struct pf_state *s, struct pf_pdesc *pd)
5630 struct sockaddr_in6 dst;
5631 struct ip6_hdr *ip6;
5632 struct ifnet *ifp = NULL;
5633 struct pf_addr naddr;
5634 struct pf_src_node *sn = NULL;
5636 KASSERT(m && *m && r && oifp, ("%s: invalid parameters", __func__));
5637 KASSERT(dir == PF_IN || dir == PF_OUT, ("%s: invalid direction",
5640 if ((pd->pf_mtag == NULL &&
5641 ((pd->pf_mtag = pf_get_mtag(*m)) == NULL)) ||
5642 pd->pf_mtag->routed++ > 3) {
5648 if (r->rt == PF_DUPTO) {
5649 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
5655 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5663 ip6 = mtod(m0, struct ip6_hdr *);
5665 bzero(&dst, sizeof(dst));
5666 dst.sin6_family = AF_INET6;
5667 dst.sin6_len = sizeof(dst);
5668 dst.sin6_addr = ip6->ip6_dst;
5670 /* Cheat. XXX why only in the v6 case??? */
5671 if (r->rt == PF_FASTROUTE) {
5674 m0->m_flags |= M_SKIP_FIREWALL;
5675 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5679 if (TAILQ_EMPTY(&r->rpool.list)) {
5680 DPFPRINTF(PF_DEBUG_URGENT,
5681 ("%s: TAILQ_EMPTY(&r->rpool.list)\n", __func__));
5685 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5687 if (!PF_AZERO(&naddr, AF_INET6))
5688 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5690 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5692 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5693 PF_ACPY((struct pf_addr *)&dst.sin6_addr,
5694 &s->rt_addr, AF_INET6);
5695 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5705 if (pf_test6(PF_OUT, ifp, &m0, NULL) != PF_PASS)
5707 else if (m0 == NULL)
5709 if (m0->m_len < sizeof(struct ip6_hdr)) {
5710 DPFPRINTF(PF_DEBUG_URGENT,
5711 ("%s: m0->m_len < sizeof(struct ip6_hdr)\n",
5715 ip6 = mtod(m0, struct ip6_hdr *);
5718 if (ifp->if_flags & IFF_LOOPBACK)
5719 m0->m_flags |= M_SKIP_FIREWALL;
5722 * If the packet is too large for the outgoing interface,
5723 * send back an icmp6 error.
5725 if (IN6_IS_SCOPE_EMBED(&dst.sin6_addr))
5726 dst.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5727 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu)
5728 nd6_output(ifp, ifp, m0, &dst, NULL);
5730 in6_ifstat_inc(ifp, ifs6_in_toobig);
5731 if (r->rt != PF_DUPTO)
5732 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5738 if (r->rt != PF_DUPTO)
5752 * FreeBSD supports cksum offloads for the following drivers.
5753 * em(4), fxp(4), ixgb(4), lge(4), ndis(4), nge(4), re(4),
5754 * ti(4), txp(4), xl(4)
5756 * CSUM_DATA_VALID | CSUM_PSEUDO_HDR :
5757 * network driver performed cksum including pseudo header, need to verify
5760 * network driver performed cksum, needs to additional pseudo header
5761 * cksum computation with partial csum_data(i.e. lack of H/W support for
5762 * pseudo header, for instance hme(4), sk(4) and possibly gem(4))
5764 * After validating the cksum of packet, set both flag CSUM_DATA_VALID and
5765 * CSUM_PSEUDO_HDR in order to avoid recomputation of the cksum in upper
5767 * Also, set csum_data to 0xffff to force cksum validation.
5770 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p, sa_family_t af)
5776 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5778 if (m->m_pkthdr.len < off + len)
5783 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5784 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5785 sum = m->m_pkthdr.csum_data;
5787 ip = mtod(m, struct ip *);
5788 sum = in_pseudo(ip->ip_src.s_addr,
5789 ip->ip_dst.s_addr, htonl((u_short)len +
5790 m->m_pkthdr.csum_data + IPPROTO_TCP));
5797 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5798 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5799 sum = m->m_pkthdr.csum_data;
5801 ip = mtod(m, struct ip *);
5802 sum = in_pseudo(ip->ip_src.s_addr,
5803 ip->ip_dst.s_addr, htonl((u_short)len +
5804 m->m_pkthdr.csum_data + IPPROTO_UDP));
5812 case IPPROTO_ICMPV6:
5822 if (p == IPPROTO_ICMP) {
5827 sum = in_cksum(m, len);
5831 if (m->m_len < sizeof(struct ip))
5833 sum = in4_cksum(m, p, off, len);
5838 if (m->m_len < sizeof(struct ip6_hdr))
5840 sum = in6_cksum(m, p, off, len);
5851 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
5856 KMOD_UDPSTAT_INC(udps_badsum);
5862 KMOD_ICMPSTAT_INC(icps_checksum);
5867 case IPPROTO_ICMPV6:
5869 KMOD_ICMP6STAT_INC(icp6s_checksum);
5876 if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
5877 m->m_pkthdr.csum_flags |=
5878 (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
5879 m->m_pkthdr.csum_data = 0xffff;
5888 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
5890 struct pfi_kif *kif;
5891 u_short action, reason = 0, log = 0;
5892 struct mbuf *m = *m0;
5893 struct ip *h = NULL;
5894 struct m_tag *ipfwtag;
5895 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
5896 struct pf_state *s = NULL;
5897 struct pf_ruleset *ruleset = NULL;
5899 int off, dirndx, pqid = 0;
5903 if (!V_pf_status.running)
5906 memset(&pd, 0, sizeof(pd));
5908 kif = (struct pfi_kif *)ifp->if_pf_kif;
5911 DPFPRINTF(PF_DEBUG_URGENT,
5912 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5915 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5918 if (m->m_flags & M_SKIP_FIREWALL)
5921 pd.pf_mtag = pf_find_mtag(m);
5925 if (ip_divert_ptr != NULL &&
5926 ((ipfwtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL)) != NULL)) {
5927 struct ipfw_rule_ref *rr = (struct ipfw_rule_ref *)(ipfwtag+1);
5928 if (rr->info & IPFW_IS_DIVERT && rr->rulenum == 0) {
5929 if (pd.pf_mtag == NULL &&
5930 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
5934 pd.pf_mtag->flags |= PF_PACKET_LOOPED;
5935 m_tag_delete(m, ipfwtag);
5937 if (pd.pf_mtag && pd.pf_mtag->flags & PF_FASTFWD_OURS_PRESENT) {
5938 m->m_flags |= M_FASTFWD_OURS;
5939 pd.pf_mtag->flags &= ~PF_FASTFWD_OURS_PRESENT;
5941 } else if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5942 /* We do IP header normalization and packet reassembly here */
5946 m = *m0; /* pf_normalize messes with m0 */
5947 h = mtod(m, struct ip *);
5949 off = h->ip_hl << 2;
5950 if (off < (int)sizeof(struct ip)) {
5952 REASON_SET(&reason, PFRES_SHORT);
5957 pd.src = (struct pf_addr *)&h->ip_src;
5958 pd.dst = (struct pf_addr *)&h->ip_dst;
5959 pd.sport = pd.dport = NULL;
5960 pd.ip_sum = &h->ip_sum;
5961 pd.proto_sum = NULL;
5964 pd.sidx = (dir == PF_IN) ? 0 : 1;
5965 pd.didx = (dir == PF_IN) ? 1 : 0;
5968 pd.tot_len = ntohs(h->ip_len);
5970 /* handle fragments that didn't get reassembled by normalization */
5971 if (h->ip_off & htons(IP_MF | IP_OFFMASK)) {
5972 action = pf_test_fragment(&r, dir, kif, m, h,
5983 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5984 &action, &reason, AF_INET)) {
5985 log = action != PF_PASS;
5988 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5989 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5991 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5992 if (action == PF_DROP)
5994 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5996 if (action == PF_PASS) {
5997 if (pfsync_update_state_ptr != NULL)
5998 pfsync_update_state_ptr(s);
6002 } else if (s == NULL)
6003 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6012 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6013 &action, &reason, AF_INET)) {
6014 log = action != PF_PASS;
6017 if (uh.uh_dport == 0 ||
6018 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6019 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6021 REASON_SET(&reason, PFRES_SHORT);
6024 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6025 if (action == PF_PASS) {
6026 if (pfsync_update_state_ptr != NULL)
6027 pfsync_update_state_ptr(s);
6031 } else if (s == NULL)
6032 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6037 case IPPROTO_ICMP: {
6041 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6042 &action, &reason, AF_INET)) {
6043 log = action != PF_PASS;
6046 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6048 if (action == PF_PASS) {
6049 if (pfsync_update_state_ptr != NULL)
6050 pfsync_update_state_ptr(s);
6054 } else if (s == NULL)
6055 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6061 case IPPROTO_ICMPV6: {
6063 DPFPRINTF(PF_DEBUG_MISC,
6064 ("pf: dropping IPv4 packet with ICMPv6 payload\n"));
6070 action = pf_test_state_other(&s, dir, kif, m, &pd);
6071 if (action == PF_PASS) {
6072 if (pfsync_update_state_ptr != NULL)
6073 pfsync_update_state_ptr(s);
6077 } else if (s == NULL)
6078 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6085 if (action == PF_PASS && h->ip_hl > 5 &&
6086 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6088 REASON_SET(&reason, PFRES_IPOPTIONS);
6090 DPFPRINTF(PF_DEBUG_MISC,
6091 ("pf: dropping packet with ip options\n"));
6094 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6096 REASON_SET(&reason, PFRES_MEMORY);
6098 if (r->rtableid >= 0)
6099 M_SETFIB(m, r->rtableid);
6102 if (action == PF_PASS && r->qid) {
6103 if (pd.pf_mtag == NULL &&
6104 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6106 REASON_SET(&reason, PFRES_MEMORY);
6108 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6109 pd.pf_mtag->qid = r->pqid;
6111 pd.pf_mtag->qid = r->qid;
6112 /* add hints for ecn */
6113 pd.pf_mtag->hdr = h;
6119 * connections redirected to loopback should not match sockets
6120 * bound specifically to loopback due to security implications,
6121 * see tcp_input() and in_pcblookup_listen().
6123 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6124 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6125 (s->nat_rule.ptr->action == PF_RDR ||
6126 s->nat_rule.ptr->action == PF_BINAT) &&
6127 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6128 m->m_flags |= M_SKIP_FIREWALL;
6130 if (action == PF_PASS && r->divert.port && ip_divert_ptr != NULL &&
6131 !PACKET_LOOPED(&pd)) {
6133 ipfwtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
6134 sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
6135 if (ipfwtag != NULL) {
6136 ((struct ipfw_rule_ref *)(ipfwtag+1))->info =
6137 ntohs(r->divert.port);
6138 ((struct ipfw_rule_ref *)(ipfwtag+1))->rulenum = dir;
6143 m_tag_prepend(m, ipfwtag);
6144 if (m->m_flags & M_FASTFWD_OURS) {
6145 if (pd.pf_mtag == NULL &&
6146 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6148 REASON_SET(&reason, PFRES_MEMORY);
6150 DPFPRINTF(PF_DEBUG_MISC,
6151 ("pf: failed to allocate tag\n"));
6153 pd.pf_mtag->flags |= PF_FASTFWD_OURS_PRESENT;
6154 m->m_flags &= ~M_FASTFWD_OURS;
6156 ip_divert_ptr(*m0, dir == PF_IN ? DIR_IN : DIR_OUT);
6161 /* XXX: ipfw has the same behaviour! */
6163 REASON_SET(&reason, PFRES_MEMORY);
6165 DPFPRINTF(PF_DEBUG_MISC,
6166 ("pf: failed to allocate divert tag\n"));
6173 if (s != NULL && s->nat_rule.ptr != NULL &&
6174 s->nat_rule.ptr->log & PF_LOG_ALL)
6175 lr = s->nat_rule.ptr;
6178 PFLOG_PACKET(kif, m, AF_INET, dir, reason, lr, a, ruleset, &pd,
6182 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6183 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6185 if (action == PF_PASS || r->action == PF_DROP) {
6186 dirndx = (dir == PF_OUT);
6187 r->packets[dirndx]++;
6188 r->bytes[dirndx] += pd.tot_len;
6190 a->packets[dirndx]++;
6191 a->bytes[dirndx] += pd.tot_len;
6194 if (s->nat_rule.ptr != NULL) {
6195 s->nat_rule.ptr->packets[dirndx]++;
6196 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6198 if (s->src_node != NULL) {
6199 s->src_node->packets[dirndx]++;
6200 s->src_node->bytes[dirndx] += pd.tot_len;
6202 if (s->nat_src_node != NULL) {
6203 s->nat_src_node->packets[dirndx]++;
6204 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6206 dirndx = (dir == s->direction) ? 0 : 1;
6207 s->packets[dirndx]++;
6208 s->bytes[dirndx] += pd.tot_len;
6211 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6212 if (nr != NULL && r == &V_pf_default_rule)
6214 if (tr->src.addr.type == PF_ADDR_TABLE)
6215 pfr_update_stats(tr->src.addr.p.tbl,
6216 (s == NULL) ? pd.src :
6217 &s->key[(s->direction == PF_IN)]->
6218 addr[(s->direction == PF_OUT)],
6219 pd.af, pd.tot_len, dir == PF_OUT,
6220 r->action == PF_PASS, tr->src.neg);
6221 if (tr->dst.addr.type == PF_ADDR_TABLE)
6222 pfr_update_stats(tr->dst.addr.p.tbl,
6223 (s == NULL) ? pd.dst :
6224 &s->key[(s->direction == PF_IN)]->
6225 addr[(s->direction == PF_IN)],
6226 pd.af, pd.tot_len, dir == PF_OUT,
6227 r->action == PF_PASS, tr->dst.neg);
6231 case PF_SYNPROXY_DROP:
6238 /* pf_route() returns unlocked. */
6240 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6254 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0, struct inpcb *inp)
6256 struct pfi_kif *kif;
6257 u_short action, reason = 0, log = 0;
6258 struct mbuf *m = *m0, *n = NULL;
6259 struct ip6_hdr *h = NULL;
6260 struct pf_rule *a = NULL, *r = &V_pf_default_rule, *tr, *nr;
6261 struct pf_state *s = NULL;
6262 struct pf_ruleset *ruleset = NULL;
6264 int off, terminal = 0, dirndx, rh_cnt = 0;
6268 if (!V_pf_status.running)
6271 memset(&pd, 0, sizeof(pd));
6272 pd.pf_mtag = pf_find_mtag(m);
6274 if (pd.pf_mtag && pd.pf_mtag->flags & PF_TAG_GENERATED)
6277 kif = (struct pfi_kif *)ifp->if_pf_kif;
6279 DPFPRINTF(PF_DEBUG_URGENT,
6280 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6283 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6288 /* We do IP header normalization and packet reassembly here */
6289 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6293 m = *m0; /* pf_normalize messes with m0 */
6294 h = mtod(m, struct ip6_hdr *);
6298 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6299 * will do something bad, so drop the packet for now.
6301 if (htons(h->ip6_plen) == 0) {
6303 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6308 pd.src = (struct pf_addr *)&h->ip6_src;
6309 pd.dst = (struct pf_addr *)&h->ip6_dst;
6310 pd.sport = pd.dport = NULL;
6312 pd.proto_sum = NULL;
6314 pd.sidx = (dir == PF_IN) ? 0 : 1;
6315 pd.didx = (dir == PF_IN) ? 1 : 0;
6318 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6320 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6321 pd.proto = h->ip6_nxt;
6324 case IPPROTO_FRAGMENT:
6325 action = pf_test_fragment(&r, dir, kif, m, h,
6327 if (action == PF_DROP)
6328 REASON_SET(&reason, PFRES_FRAG);
6330 case IPPROTO_ROUTING: {
6331 struct ip6_rthdr rthdr;
6334 DPFPRINTF(PF_DEBUG_MISC,
6335 ("pf: IPv6 more than one rthdr\n"));
6337 REASON_SET(&reason, PFRES_IPOPTIONS);
6341 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6343 DPFPRINTF(PF_DEBUG_MISC,
6344 ("pf: IPv6 short rthdr\n"));
6346 REASON_SET(&reason, PFRES_SHORT);
6350 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6351 DPFPRINTF(PF_DEBUG_MISC,
6352 ("pf: IPv6 rthdr0\n"));
6354 REASON_SET(&reason, PFRES_IPOPTIONS);
6361 case IPPROTO_HOPOPTS:
6362 case IPPROTO_DSTOPTS: {
6363 /* get next header and header length */
6364 struct ip6_ext opt6;
6366 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6367 NULL, &reason, pd.af)) {
6368 DPFPRINTF(PF_DEBUG_MISC,
6369 ("pf: IPv6 short opt\n"));
6374 if (pd.proto == IPPROTO_AH)
6375 off += (opt6.ip6e_len + 2) * 4;
6377 off += (opt6.ip6e_len + 1) * 8;
6378 pd.proto = opt6.ip6e_nxt;
6379 /* goto the next header */
6386 } while (!terminal);
6388 /* if there's no routing header, use unmodified mbuf for checksumming */
6398 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6399 &action, &reason, AF_INET6)) {
6400 log = action != PF_PASS;
6403 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6404 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6405 if (action == PF_DROP)
6407 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6409 if (action == PF_PASS) {
6410 if (pfsync_update_state_ptr != NULL)
6411 pfsync_update_state_ptr(s);
6415 } else if (s == NULL)
6416 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6425 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6426 &action, &reason, AF_INET6)) {
6427 log = action != PF_PASS;
6430 if (uh.uh_dport == 0 ||
6431 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6432 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6434 REASON_SET(&reason, PFRES_SHORT);
6437 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6438 if (action == PF_PASS) {
6439 if (pfsync_update_state_ptr != NULL)
6440 pfsync_update_state_ptr(s);
6444 } else if (s == NULL)
6445 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6450 case IPPROTO_ICMP: {
6452 DPFPRINTF(PF_DEBUG_MISC,
6453 ("pf: dropping IPv6 packet with ICMPv4 payload\n"));
6457 case IPPROTO_ICMPV6: {
6459 struct icmp6_hdr icmp6;
6461 struct nd_neighbor_solicit nd;
6463 size_t icmp_hlen = sizeof(struct icmp6_hdr);
6465 pd.hdr.icmp6 = &ih.icmp6;
6466 if (!pf_pull_hdr(m, off, &ih, icmp_hlen,
6467 &action, &reason, AF_INET6)) {
6468 log = action != PF_PASS;
6471 /* ICMP headers we look further into to match state */
6472 switch (ih.icmp6.icmp6_type) {
6473 case MLD_LISTENER_QUERY:
6474 case MLD_LISTENER_REPORT:
6475 icmp_hlen = sizeof(struct mld_hdr);
6477 case ND_NEIGHBOR_SOLICIT:
6478 case ND_NEIGHBOR_ADVERT:
6479 icmp_hlen = sizeof(struct nd_neighbor_solicit);
6482 if (icmp_hlen > sizeof(struct icmp6_hdr) &&
6483 !pf_pull_hdr(m, off, &ih, icmp_hlen,
6484 &action, &reason, AF_INET6)) {
6485 log = action != PF_PASS;
6488 action = pf_test_state_icmp(&s, dir, kif,
6489 m, off, h, &pd, &reason);
6490 if (action == PF_PASS) {
6491 if (pfsync_update_state_ptr != NULL)
6492 pfsync_update_state_ptr(s);
6496 } else if (s == NULL)
6497 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6503 action = pf_test_state_other(&s, dir, kif, m, &pd);
6504 if (action == PF_PASS) {
6505 if (pfsync_update_state_ptr != NULL)
6506 pfsync_update_state_ptr(s);
6510 } else if (s == NULL)
6511 action = pf_test_rule(&r, &s, dir, kif, m, off, &pd,
6523 /* handle dangerous IPv6 extension headers. */
6524 if (action == PF_PASS && rh_cnt &&
6525 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6527 REASON_SET(&reason, PFRES_IPOPTIONS);
6529 DPFPRINTF(PF_DEBUG_MISC,
6530 ("pf: dropping packet with dangerous v6 headers\n"));
6533 if (s && s->tag > 0 && pf_tag_packet(m, &pd, s->tag)) {
6535 REASON_SET(&reason, PFRES_MEMORY);
6537 if (r->rtableid >= 0)
6538 M_SETFIB(m, r->rtableid);
6541 if (action == PF_PASS && r->qid) {
6542 if (pd.pf_mtag == NULL &&
6543 ((pd.pf_mtag = pf_get_mtag(m)) == NULL)) {
6545 REASON_SET(&reason, PFRES_MEMORY);
6547 if (pd.tos & IPTOS_LOWDELAY)
6548 pd.pf_mtag->qid = r->pqid;
6550 pd.pf_mtag->qid = r->qid;
6551 /* add hints for ecn */
6552 pd.pf_mtag->hdr = h;
6556 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6557 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6558 (s->nat_rule.ptr->action == PF_RDR ||
6559 s->nat_rule.ptr->action == PF_BINAT) &&
6560 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6561 m->m_flags |= M_SKIP_FIREWALL;
6563 /* XXX: Anybody working on it?! */
6565 printf("pf: divert(9) is not supported for IPv6\n");
6570 if (s != NULL && s->nat_rule.ptr != NULL &&
6571 s->nat_rule.ptr->log & PF_LOG_ALL)
6572 lr = s->nat_rule.ptr;
6575 PFLOG_PACKET(kif, m, AF_INET6, dir, reason, lr, a, ruleset,
6579 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6580 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6582 if (action == PF_PASS || r->action == PF_DROP) {
6583 dirndx = (dir == PF_OUT);
6584 r->packets[dirndx]++;
6585 r->bytes[dirndx] += pd.tot_len;
6587 a->packets[dirndx]++;
6588 a->bytes[dirndx] += pd.tot_len;
6591 if (s->nat_rule.ptr != NULL) {
6592 s->nat_rule.ptr->packets[dirndx]++;
6593 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6595 if (s->src_node != NULL) {
6596 s->src_node->packets[dirndx]++;
6597 s->src_node->bytes[dirndx] += pd.tot_len;
6599 if (s->nat_src_node != NULL) {
6600 s->nat_src_node->packets[dirndx]++;
6601 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6603 dirndx = (dir == s->direction) ? 0 : 1;
6604 s->packets[dirndx]++;
6605 s->bytes[dirndx] += pd.tot_len;
6608 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6609 if (nr != NULL && r == &V_pf_default_rule)
6611 if (tr->src.addr.type == PF_ADDR_TABLE)
6612 pfr_update_stats(tr->src.addr.p.tbl,
6613 (s == NULL) ? pd.src :
6614 &s->key[(s->direction == PF_IN)]->addr[0],
6615 pd.af, pd.tot_len, dir == PF_OUT,
6616 r->action == PF_PASS, tr->src.neg);
6617 if (tr->dst.addr.type == PF_ADDR_TABLE)
6618 pfr_update_stats(tr->dst.addr.p.tbl,
6619 (s == NULL) ? pd.dst :
6620 &s->key[(s->direction == PF_IN)]->addr[1],
6621 pd.af, pd.tot_len, dir == PF_OUT,
6622 r->action == PF_PASS, tr->dst.neg);
6626 case PF_SYNPROXY_DROP:
6633 /* pf_route6() returns unlocked. */
6635 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);