1 /* $OpenBSD: pf.c,v 1.614 2008/08/02 12:34:37 henning Exp $ */
4 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
6 * Copyright (c) 2001 Daniel Hartmeier
7 * Copyright (c) 2002 - 2008 Henning Brauer
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
14 * - Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * - Redistributions in binary form must reproduce the above
17 * copyright notice, this list of conditions and the following
18 * disclaimer in the documentation and/or other materials provided
19 * with the distribution.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
34 * Effort sponsored in part by the Defense Advanced Research Projects
35 * Agency (DARPA) and Air Force Research Laboratory, Air Force
36 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
41 #include "opt_inet6.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
47 #include <sys/filio.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/kernel.h>
52 #include <sys/sysctl.h>
53 #include <sys/endian.h>
55 #include <sys/kthread.h>
56 #include <sys/spinlock.h>
58 #include <machine/inttypes.h>
63 #include <net/if_types.h>
65 #include <net/netisr2.h>
66 #include <net/route.h>
68 #include <netinet/in.h>
69 #include <netinet/in_var.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/ip.h>
72 #include <netinet/ip_var.h>
73 #include <netinet/tcp.h>
74 #include <netinet/tcp_seq.h>
75 #include <netinet/udp.h>
76 #include <netinet/ip_icmp.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/tcp_timer.h>
79 #include <netinet/tcp_var.h>
80 #include <netinet/udp_var.h>
81 #include <netinet/icmp_var.h>
82 #include <netinet/if_ether.h>
84 #include <net/pf/pfvar.h>
85 #include <net/pf/if_pflog.h>
87 #include <net/pf/if_pfsync.h>
90 #include <netinet/ip6.h>
91 #include <netinet/icmp6.h>
92 #include <netinet6/nd6.h>
93 #include <netinet6/ip6_var.h>
94 #include <netinet6/in6_pcb.h>
97 #include <sys/in_cksum.h>
98 #include <sys/ucred.h>
99 #include <machine/limits.h>
100 #include <sys/msgport2.h>
101 #include <sys/spinlock2.h>
102 #include <net/netmsg2.h>
103 #include <net/toeplitz2.h>
105 extern int ip_optcopy(struct ip *, struct ip *);
106 extern int debug_pfugidhack;
109 * pf_token - shared lock for cpu-localized operations,
110 * exclusive lock otherwise.
112 * pf_gtoken- exclusive lock used for initialization.
114 * pf_spin - only used to atomically fetch and increment stateid
117 struct lwkt_token pf_token = LWKT_TOKEN_INITIALIZER(pf_token);
118 struct lwkt_token pf_gtoken = LWKT_TOKEN_INITIALIZER(pf_gtoken);
119 #if __SIZEOF_LONG__ != 8
120 struct spinlock pf_spin = SPINLOCK_INITIALIZER(pf_spin);
123 #define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
125 #define FAIL(code) { error = (code); goto done; }
131 /* mask radix tree */
132 struct radix_node_head *pf_maskhead;
135 struct pf_state_tree pf_statetbl[MAXCPU+1]; /* incls one global table */
137 struct pf_altqqueue pf_altqs[2];
138 struct pf_palist pf_pabuf;
139 struct pf_altqqueue *pf_altqs_active;
140 struct pf_altqqueue *pf_altqs_inactive;
141 struct pf_status pf_status;
143 u_int32_t ticket_altqs_active;
144 u_int32_t ticket_altqs_inactive;
145 int altqs_inactive_open;
146 u_int32_t ticket_pabuf;
148 MD5_CTX pf_tcp_secret_ctx;
149 u_char pf_tcp_secret[16];
150 int pf_tcp_secret_init;
153 struct pf_anchor_stackframe {
154 struct pf_ruleset *rs;
156 struct pf_anchor_node *parent;
157 struct pf_anchor *child;
158 } pf_anchor_stack[64];
160 struct malloc_type *pf_src_tree_pl, *pf_rule_pl, *pf_pooladdr_pl;
161 struct malloc_type *pf_state_pl, *pf_state_key_pl, *pf_state_item_pl;
162 struct malloc_type *pf_altq_pl;
164 void pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
166 void pf_init_threshold(struct pf_threshold *, u_int32_t,
168 void pf_add_threshold(struct pf_threshold *);
169 int pf_check_threshold(struct pf_threshold *);
171 void pf_change_ap(struct pf_addr *, u_int16_t *,
172 u_int16_t *, u_int16_t *, struct pf_addr *,
173 u_int16_t, u_int8_t, sa_family_t);
174 int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
175 struct tcphdr *, struct pf_state_peer *);
177 void pf_change_a6(struct pf_addr *, u_int16_t *,
178 struct pf_addr *, u_int8_t);
180 void pf_change_icmp(struct pf_addr *, u_int16_t *,
181 struct pf_addr *, struct pf_addr *, u_int16_t,
182 u_int16_t *, u_int16_t *, u_int16_t *,
183 u_int16_t *, u_int8_t, sa_family_t);
184 void pf_send_tcp(const struct pf_rule *, sa_family_t,
185 const struct pf_addr *, const struct pf_addr *,
186 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
187 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
188 u_int16_t, struct ether_header *, struct ifnet *);
189 void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
190 sa_family_t, struct pf_rule *);
191 struct pf_rule *pf_match_translation(struct pf_pdesc *, struct mbuf *,
192 int, int, struct pfi_kif *,
193 struct pf_addr *, u_int16_t, struct pf_addr *,
195 struct pf_rule *pf_get_translation(struct pf_pdesc *, struct mbuf *,
196 int, int, struct pfi_kif *, struct pf_src_node **,
197 struct pf_state_key **, struct pf_state_key **,
198 struct pf_state_key **, struct pf_state_key **,
199 struct pf_addr *, struct pf_addr *,
200 u_int16_t, u_int16_t);
201 void pf_detach_state(struct pf_state *);
202 int pf_state_key_setup(struct pf_pdesc *, struct pf_rule *,
203 struct pf_state_key **, struct pf_state_key **,
204 struct pf_state_key **, struct pf_state_key **,
205 struct pf_addr *, struct pf_addr *,
206 u_int16_t, u_int16_t);
207 void pf_state_key_detach(struct pf_state *, int);
208 u_int32_t pf_tcp_iss(struct pf_pdesc *);
209 int pf_test_rule(struct pf_rule **, struct pf_state **,
210 int, struct pfi_kif *, struct mbuf *, int,
211 void *, struct pf_pdesc *, struct pf_rule **,
212 struct pf_ruleset **, struct ifqueue *, struct inpcb *);
213 static __inline int pf_create_state(struct pf_rule *, struct pf_rule *,
214 struct pf_rule *, struct pf_pdesc *,
215 struct pf_src_node *, struct pf_state_key *,
216 struct pf_state_key *, struct pf_state_key *,
217 struct pf_state_key *, struct mbuf *, int,
218 u_int16_t, u_int16_t, int *, struct pfi_kif *,
219 struct pf_state **, int, u_int16_t, u_int16_t,
221 int pf_test_fragment(struct pf_rule **, int,
222 struct pfi_kif *, struct mbuf *, void *,
223 struct pf_pdesc *, struct pf_rule **,
224 struct pf_ruleset **);
225 int pf_tcp_track_full(struct pf_state_peer *,
226 struct pf_state_peer *, struct pf_state **,
227 struct pfi_kif *, struct mbuf *, int,
228 struct pf_pdesc *, u_short *, int *);
229 int pf_tcp_track_sloppy(struct pf_state_peer *,
230 struct pf_state_peer *, struct pf_state **,
231 struct pf_pdesc *, u_short *);
232 int pf_test_state_tcp(struct pf_state **, int,
233 struct pfi_kif *, struct mbuf *, int,
234 void *, struct pf_pdesc *, u_short *);
235 int pf_test_state_udp(struct pf_state **, int,
236 struct pfi_kif *, struct mbuf *, int,
237 void *, struct pf_pdesc *);
238 int pf_test_state_icmp(struct pf_state **, int,
239 struct pfi_kif *, struct mbuf *, int,
240 void *, struct pf_pdesc *, u_short *);
241 int pf_test_state_other(struct pf_state **, int,
242 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
243 void pf_step_into_anchor(int *, struct pf_ruleset **, int,
244 struct pf_rule **, struct pf_rule **, int *);
245 int pf_step_out_of_anchor(int *, struct pf_ruleset **,
246 int, struct pf_rule **, struct pf_rule **,
248 void pf_hash(struct pf_addr *, struct pf_addr *,
249 struct pf_poolhashkey *, sa_family_t);
250 int pf_map_addr(u_int8_t, struct pf_rule *,
251 struct pf_addr *, struct pf_addr *,
252 struct pf_addr *, struct pf_src_node **);
253 int pf_get_sport(struct pf_pdesc *,
254 sa_family_t, u_int8_t, struct pf_rule *,
255 struct pf_addr *, struct pf_addr *,
256 u_int16_t, u_int16_t,
257 struct pf_addr *, u_int16_t *,
258 u_int16_t, u_int16_t,
259 struct pf_src_node **);
260 void pf_route(struct mbuf **, struct pf_rule *, int,
261 struct ifnet *, struct pf_state *,
263 void pf_route6(struct mbuf **, struct pf_rule *, int,
264 struct ifnet *, struct pf_state *,
266 u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
268 u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
270 u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
272 void pf_set_rt_ifp(struct pf_state *,
274 int pf_check_proto_cksum(struct mbuf *, int, int,
275 u_int8_t, sa_family_t);
276 struct pf_divert *pf_get_divert(struct mbuf *);
277 void pf_print_state_parts(struct pf_state *,
278 struct pf_state_key *, struct pf_state_key *);
279 int pf_addr_wrap_neq(struct pf_addr_wrap *,
280 struct pf_addr_wrap *);
281 struct pf_state *pf_find_state(struct pfi_kif *,
282 struct pf_state_key_cmp *, u_int, struct mbuf *);
283 int pf_src_connlimit(struct pf_state *);
284 int pf_check_congestion(struct ifqueue *);
286 extern int pf_end_threads;
288 struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
289 { &pf_state_pl, PFSTATE_HIWAT },
290 { &pf_src_tree_pl, PFSNODE_HIWAT },
291 { &pf_frent_pl, PFFRAG_FRENT_HIWAT },
292 { &pfr_ktable_pl, PFR_KTABLE_HIWAT },
293 { &pfr_kentry_pl, PFR_KENTRY_HIWAT }
296 #define STATE_LOOKUP(i, k, d, s, m) \
298 s = pf_find_state(i, k, d, m); \
299 if (s == NULL || (s)->timeout == PFTM_PURGE) \
302 (((s)->rule.ptr->rt == PF_ROUTETO && \
303 (s)->rule.ptr->direction == PF_OUT) || \
304 ((s)->rule.ptr->rt == PF_REPLYTO && \
305 (s)->rule.ptr->direction == PF_IN)) && \
306 (s)->rt_kif != NULL && \
311 #define BOUND_IFACE(r, k) \
312 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
314 #define STATE_INC_COUNTERS(s) \
316 atomic_add_int(&s->rule.ptr->states_cur, 1); \
317 s->rule.ptr->states_tot++; \
318 if (s->anchor.ptr != NULL) { \
319 atomic_add_int(&s->anchor.ptr->states_cur, 1); \
320 s->anchor.ptr->states_tot++; \
322 if (s->nat_rule.ptr != NULL) { \
323 atomic_add_int(&s->nat_rule.ptr->states_cur, 1); \
324 s->nat_rule.ptr->states_tot++; \
328 #define STATE_DEC_COUNTERS(s) \
330 if (s->nat_rule.ptr != NULL) \
331 atomic_add_int(&s->nat_rule.ptr->states_cur, -1); \
332 if (s->anchor.ptr != NULL) \
333 atomic_add_int(&s->anchor.ptr->states_cur, -1); \
334 atomic_add_int(&s->rule.ptr->states_cur, -1); \
337 static MALLOC_DEFINE(M_PFSTATEPL, "pfstatepl", "pf state pool list");
338 static MALLOC_DEFINE(M_PFSRCTREEPL, "pfsrctpl", "pf source tree pool list");
339 static MALLOC_DEFINE(M_PFSTATEKEYPL, "pfstatekeypl", "pf state key pool list");
340 static MALLOC_DEFINE(M_PFSTATEITEMPL, "pfstateitempl", "pf state item pool list");
342 static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
343 static __inline int pf_state_compare_key(struct pf_state_key *,
344 struct pf_state_key *);
345 static __inline int pf_state_compare_id(struct pf_state *,
348 struct pf_src_tree tree_src_tracking[MAXCPU];
349 struct pf_state_tree_id tree_id[MAXCPU];
350 struct pf_state_queue state_list[MAXCPU];
352 RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
353 RB_GENERATE(pf_state_tree, pf_state_key, entry, pf_state_compare_key);
354 RB_GENERATE(pf_state_tree_id, pf_state,
355 entry_id, pf_state_compare_id);
358 pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
362 if (a->rule.ptr > b->rule.ptr)
364 if (a->rule.ptr < b->rule.ptr)
366 if ((diff = a->af - b->af) != 0)
371 if (a->addr.addr32[0] > b->addr.addr32[0])
373 if (a->addr.addr32[0] < b->addr.addr32[0])
379 if (a->addr.addr32[3] > b->addr.addr32[3])
381 if (a->addr.addr32[3] < b->addr.addr32[3])
383 if (a->addr.addr32[2] > b->addr.addr32[2])
385 if (a->addr.addr32[2] < b->addr.addr32[2])
387 if (a->addr.addr32[1] > b->addr.addr32[1])
389 if (a->addr.addr32[1] < b->addr.addr32[1])
391 if (a->addr.addr32[0] > b->addr.addr32[0])
393 if (a->addr.addr32[0] < b->addr.addr32[0])
402 pf_state_hash(struct pf_state_key *sk)
404 u_int32_t hv = (u_int32_t)(((intptr_t)sk >> 6) ^ ((intptr_t)sk >> 15));
405 if (hv == 0) /* disallow 0 */
412 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
417 dst->addr32[0] = src->addr32[0];
421 dst->addr32[0] = src->addr32[0];
422 dst->addr32[1] = src->addr32[1];
423 dst->addr32[2] = src->addr32[2];
424 dst->addr32[3] = src->addr32[3];
431 pf_init_threshold(struct pf_threshold *threshold,
432 u_int32_t limit, u_int32_t seconds)
434 threshold->limit = limit * PF_THRESHOLD_MULT;
435 threshold->seconds = seconds;
436 threshold->count = 0;
437 threshold->last = time_second;
441 pf_add_threshold(struct pf_threshold *threshold)
443 u_int32_t t = time_second, diff = t - threshold->last;
445 if (diff >= threshold->seconds)
446 threshold->count = 0;
448 threshold->count -= threshold->count * diff /
450 threshold->count += PF_THRESHOLD_MULT;
455 pf_check_threshold(struct pf_threshold *threshold)
457 return (threshold->count > threshold->limit);
461 pf_src_connlimit(struct pf_state *state)
464 int cpu = mycpu->gd_cpuid;
466 state->src_node->conn++;
467 state->src.tcp_est = 1;
468 pf_add_threshold(&state->src_node->conn_rate);
470 if (state->rule.ptr->max_src_conn &&
471 state->rule.ptr->max_src_conn <
472 state->src_node->conn) {
473 pf_status.lcounters[LCNT_SRCCONN]++;
477 if (state->rule.ptr->max_src_conn_rate.limit &&
478 pf_check_threshold(&state->src_node->conn_rate)) {
479 pf_status.lcounters[LCNT_SRCCONNRATE]++;
486 if (state->rule.ptr->overload_tbl) {
488 u_int32_t killed = 0;
490 pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
491 if (pf_status.debug >= PF_DEBUG_MISC) {
492 kprintf("pf_src_connlimit: blocking address ");
493 pf_print_host(&state->src_node->addr, 0,
494 state->key[PF_SK_WIRE]->af);
497 bzero(&p, sizeof(p));
498 p.pfra_af = state->key[PF_SK_WIRE]->af;
499 switch (state->key[PF_SK_WIRE]->af) {
503 p.pfra_ip4addr = state->src_node->addr.v4;
509 p.pfra_ip6addr = state->src_node->addr.v6;
514 pfr_insert_kentry(state->rule.ptr->overload_tbl,
517 /* kill existing states if that's required. */
518 if (state->rule.ptr->flush) {
519 struct pf_state_key *sk;
522 pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
523 RB_FOREACH(st, pf_state_tree_id, &tree_id[cpu]) {
524 sk = st->key[PF_SK_WIRE];
526 * Kill states from this source. (Only those
527 * from the same rule if PF_FLUSH_GLOBAL is not
528 * set). (Only on current cpu).
531 state->key[PF_SK_WIRE]->af &&
532 ((state->direction == PF_OUT &&
533 PF_AEQ(&state->src_node->addr,
534 &sk->addr[0], sk->af)) ||
535 (state->direction == PF_IN &&
536 PF_AEQ(&state->src_node->addr,
537 &sk->addr[1], sk->af))) &&
538 (state->rule.ptr->flush &
540 state->rule.ptr == st->rule.ptr)) {
541 st->timeout = PFTM_PURGE;
542 st->src.state = st->dst.state =
547 if (pf_status.debug >= PF_DEBUG_MISC)
548 kprintf(", %u states killed", killed);
550 if (pf_status.debug >= PF_DEBUG_MISC)
554 /* kill this state */
555 state->timeout = PFTM_PURGE;
556 state->src.state = state->dst.state = TCPS_CLOSED;
562 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
563 struct pf_addr *src, sa_family_t af)
565 struct pf_src_node k;
566 int cpu = mycpu->gd_cpuid;
570 PF_ACPY(&k.addr, src, af);
571 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
572 rule->rpool.opts & PF_POOL_STICKYADDR)
576 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
577 *sn = RB_FIND(pf_src_tree, &tree_src_tracking[cpu], &k);
580 if (!rule->max_src_nodes ||
581 rule->src_nodes < rule->max_src_nodes)
582 (*sn) = kmalloc(sizeof(struct pf_src_node),
583 M_PFSRCTREEPL, M_NOWAIT|M_ZERO);
585 pf_status.lcounters[LCNT_SRCNODES]++;
589 pf_init_threshold(&(*sn)->conn_rate,
590 rule->max_src_conn_rate.limit,
591 rule->max_src_conn_rate.seconds);
594 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
595 rule->rpool.opts & PF_POOL_STICKYADDR)
596 (*sn)->rule.ptr = rule;
598 (*sn)->rule.ptr = NULL;
599 PF_ACPY(&(*sn)->addr, src, af);
600 if (RB_INSERT(pf_src_tree,
601 &tree_src_tracking[cpu], *sn) != NULL) {
602 if (pf_status.debug >= PF_DEBUG_MISC) {
603 kprintf("pf: src_tree insert failed: ");
604 pf_print_host(&(*sn)->addr, 0, af);
607 kfree(*sn, M_PFSRCTREEPL);
612 * Atomic op required to increment src_nodes in the rule
613 * because we hold a shared token here (decrements will use
614 * an exclusive token).
616 (*sn)->creation = time_second;
617 (*sn)->ruletype = rule->action;
618 if ((*sn)->rule.ptr != NULL)
619 atomic_add_int(&(*sn)->rule.ptr->src_nodes, 1);
620 pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
621 atomic_add_int(&pf_status.src_nodes, 1);
623 if (rule->max_src_states &&
624 (*sn)->states >= rule->max_src_states) {
625 pf_status.lcounters[LCNT_SRCSTATES]++;
632 /* state table stuff */
635 pf_state_compare_key(struct pf_state_key *a, struct pf_state_key *b)
639 if ((diff = a->proto - b->proto) != 0)
641 if ((diff = a->af - b->af) != 0)
646 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
648 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
650 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
652 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
658 if (a->addr[0].addr32[3] > b->addr[0].addr32[3])
660 if (a->addr[0].addr32[3] < b->addr[0].addr32[3])
662 if (a->addr[1].addr32[3] > b->addr[1].addr32[3])
664 if (a->addr[1].addr32[3] < b->addr[1].addr32[3])
666 if (a->addr[0].addr32[2] > b->addr[0].addr32[2])
668 if (a->addr[0].addr32[2] < b->addr[0].addr32[2])
670 if (a->addr[1].addr32[2] > b->addr[1].addr32[2])
672 if (a->addr[1].addr32[2] < b->addr[1].addr32[2])
674 if (a->addr[0].addr32[1] > b->addr[0].addr32[1])
676 if (a->addr[0].addr32[1] < b->addr[0].addr32[1])
678 if (a->addr[1].addr32[1] > b->addr[1].addr32[1])
680 if (a->addr[1].addr32[1] < b->addr[1].addr32[1])
682 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
684 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
686 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
688 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
694 if ((diff = a->port[0] - b->port[0]) != 0)
696 if ((diff = a->port[1] - b->port[1]) != 0)
703 pf_state_compare_id(struct pf_state *a, struct pf_state *b)
709 if (a->creatorid > b->creatorid)
711 if (a->creatorid < b->creatorid)
718 pf_state_key_attach(struct pf_state_key *sk, struct pf_state *s, int idx)
720 struct pf_state_item *si;
721 struct pf_state_key *cur;
726 * PFSTATE_STACK_GLOBAL is set for translations when the translated
727 * address/port is not localized to the same cpu that the untranslated
728 * address/port is on. The wire pf_state_key is managed on the global
729 * statetbl tree for this case.
731 if ((s->state_flags & PFSTATE_STACK_GLOBAL) && idx == PF_SK_WIRE) {
733 lockmgr(&pf_global_statetbl_lock, LK_EXCLUSIVE);
735 cpu = mycpu->gd_cpuid;
738 KKASSERT(s->key[idx] == NULL); /* XXX handle this? */
740 if ((cur = RB_INSERT(pf_state_tree, &pf_statetbl[cpu], sk)) != NULL) {
741 /* key exists. check for same kif, if none, add to key */
742 TAILQ_FOREACH(si, &cur->states, entry)
743 if (si->s->kif == s->kif &&
744 si->s->direction == s->direction) {
745 if (pf_status.debug >= PF_DEBUG_MISC) {
747 "pf: %s key attach failed on %s: ",
748 (idx == PF_SK_WIRE) ?
751 pf_print_state_parts(s,
752 (idx == PF_SK_WIRE) ? sk : NULL,
753 (idx == PF_SK_STACK) ? sk : NULL);
756 kfree(sk, M_PFSTATEKEYPL);
758 goto failed; /* collision! */
760 kfree(sk, M_PFSTATEKEYPL);
767 if ((si = kmalloc(sizeof(struct pf_state_item),
768 M_PFSTATEITEMPL, M_NOWAIT)) == NULL) {
769 pf_state_key_detach(s, idx);
771 goto failed; /* collision! */
775 /* list is sorted, if-bound states before floating */
776 if (s->kif == pfi_all)
777 TAILQ_INSERT_TAIL(&s->key[idx]->states, si, entry);
779 TAILQ_INSERT_HEAD(&s->key[idx]->states, si, entry);
783 if ((s->state_flags & PFSTATE_STACK_GLOBAL) && idx == PF_SK_WIRE)
784 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
789 * NOTE: Can only be called indirectly via the purge thread with pf_token
790 * exclusively locked.
793 pf_detach_state(struct pf_state *s)
795 if (s->key[PF_SK_WIRE] == s->key[PF_SK_STACK])
796 s->key[PF_SK_WIRE] = NULL;
798 if (s->key[PF_SK_STACK] != NULL)
799 pf_state_key_detach(s, PF_SK_STACK);
801 if (s->key[PF_SK_WIRE] != NULL)
802 pf_state_key_detach(s, PF_SK_WIRE);
806 * NOTE: Can only be called indirectly via the purge thread with pf_token
807 * exclusively locked.
810 pf_state_key_detach(struct pf_state *s, int idx)
812 struct pf_state_item *si;
816 * PFSTATE_STACK_GLOBAL is set for translations when the translated
817 * address/port is not localized to the same cpu that the untranslated
818 * address/port is on. The wire pf_state_key is managed on the global
819 * statetbl tree for this case.
821 if ((s->state_flags & PFSTATE_STACK_GLOBAL) && idx == PF_SK_WIRE) {
823 lockmgr(&pf_global_statetbl_lock, LK_EXCLUSIVE);
825 cpu = mycpu->gd_cpuid;
828 si = TAILQ_FIRST(&s->key[idx]->states);
829 while (si && si->s != s)
830 si = TAILQ_NEXT(si, entry);
833 TAILQ_REMOVE(&s->key[idx]->states, si, entry);
834 kfree(si, M_PFSTATEITEMPL);
837 if (TAILQ_EMPTY(&s->key[idx]->states)) {
838 RB_REMOVE(pf_state_tree, &pf_statetbl[cpu], s->key[idx]);
839 if (s->key[idx]->reverse)
840 s->key[idx]->reverse->reverse = NULL;
841 if (s->key[idx]->inp)
842 s->key[idx]->inp->inp_pf_sk = NULL;
843 kfree(s->key[idx], M_PFSTATEKEYPL);
847 if ((s->state_flags & PFSTATE_STACK_GLOBAL) && idx == PF_SK_WIRE)
848 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
851 struct pf_state_key *
852 pf_alloc_state_key(int pool_flags)
854 struct pf_state_key *sk;
856 sk = kmalloc(sizeof(struct pf_state_key), M_PFSTATEKEYPL, pool_flags);
858 TAILQ_INIT(&sk->states);
864 pf_state_key_setup(struct pf_pdesc *pd, struct pf_rule *nr,
865 struct pf_state_key **skw, struct pf_state_key **sks,
866 struct pf_state_key **skp, struct pf_state_key **nkp,
867 struct pf_addr *saddr, struct pf_addr *daddr,
868 u_int16_t sport, u_int16_t dport)
870 KKASSERT((*skp == NULL && *nkp == NULL));
872 if ((*skp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
875 PF_ACPY(&(*skp)->addr[pd->sidx], saddr, pd->af);
876 PF_ACPY(&(*skp)->addr[pd->didx], daddr, pd->af);
877 (*skp)->port[pd->sidx] = sport;
878 (*skp)->port[pd->didx] = dport;
879 (*skp)->proto = pd->proto;
883 if ((*nkp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
884 return (ENOMEM); /* caller must handle cleanup */
886 /* XXX maybe just bcopy and TAILQ_INIT(&(*nkp)->states) */
887 PF_ACPY(&(*nkp)->addr[0], &(*skp)->addr[0], pd->af);
888 PF_ACPY(&(*nkp)->addr[1], &(*skp)->addr[1], pd->af);
889 (*nkp)->port[0] = (*skp)->port[0];
890 (*nkp)->port[1] = (*skp)->port[1];
891 (*nkp)->proto = pd->proto;
896 if (pd->dir == PF_IN) {
907 * Insert pf_state with one or two state keys (allowing a reverse path lookup
908 * which is used by NAT). In the NAT case skw is the initiator (?) and
912 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
913 struct pf_state_key *sks, struct pf_state *s)
915 int cpu = mycpu->gd_cpuid;
921 if (pf_state_key_attach(skw, s, PF_SK_WIRE))
923 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
925 if (pf_state_key_attach(skw, s, PF_SK_WIRE)) {
926 kfree(sks, M_PFSTATEKEYPL);
929 if (pf_state_key_attach(sks, s, PF_SK_STACK)) {
930 pf_state_key_detach(s, PF_SK_WIRE);
935 if (s->id == 0 && s->creatorid == 0) {
938 #if __SIZEOF_LONG__ == 8
939 sid = atomic_fetchadd_long(&pf_status.stateid, 1);
942 sid = pf_status.stateid++;
943 spin_unlock(&pf_spin);
945 s->id = htobe64(sid);
946 s->creatorid = pf_status.hostid;
950 * Calculate hash code for altq
952 s->hash = crc32(s->key[PF_SK_WIRE], sizeof(*sks));
954 if (RB_INSERT(pf_state_tree_id, &tree_id[cpu], s) != NULL) {
955 if (pf_status.debug >= PF_DEBUG_MISC) {
956 kprintf("pf: state insert failed: "
957 "id: %016jx creatorid: %08x",
958 (uintmax_t)be64toh(s->id), ntohl(s->creatorid));
959 if (s->sync_flags & PFSTATE_FROMSYNC)
960 kprintf(" (from sync)");
966 TAILQ_INSERT_TAIL(&state_list[cpu], s, entry_list);
967 pf_status.fcounters[FCNT_STATE_INSERT]++;
968 atomic_add_int(&pf_status.states, 1);
969 pfi_kif_ref(kif, PFI_KIF_REF_STATE);
970 pfsync_insert_state(s);
975 pf_find_state_byid(struct pf_state_cmp *key)
977 int cpu = mycpu->gd_cpuid;
979 pf_status.fcounters[FCNT_STATE_SEARCH]++;
981 return (RB_FIND(pf_state_tree_id, &tree_id[cpu],
982 (struct pf_state *)key));
986 * WARNING! May return a state structure that was localized to another cpu,
987 * destruction is typically protected by the callers pf_token.
988 * The element can only be destroyed
991 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir,
994 struct pf_state_key *skey = (void *)key;
995 struct pf_state_key *sk;
996 struct pf_state_item *si;
998 int cpu = mycpu->gd_cpuid;
1001 pf_status.fcounters[FCNT_STATE_SEARCH]++;
1003 if (dir == PF_OUT && m->m_pkthdr.pf.statekey &&
1004 ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse) {
1005 sk = ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse;
1007 sk = RB_FIND(pf_state_tree, &pf_statetbl[cpu], skey);
1009 lockmgr(&pf_global_statetbl_lock, LK_SHARED);
1010 sk = RB_FIND(pf_state_tree, &pf_statetbl[MAXCPU], skey);
1012 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
1017 if (dir == PF_OUT && m->m_pkthdr.pf.statekey) {
1018 ((struct pf_state_key *)
1019 m->m_pkthdr.pf.statekey)->reverse = sk;
1020 sk->reverse = m->m_pkthdr.pf.statekey;
1024 m->m_pkthdr.pf.statekey = NULL;
1026 /* list is sorted, if-bound states before floating ones */
1027 TAILQ_FOREACH(si, &sk->states, entry) {
1028 if ((si->s->kif == pfi_all || si->s->kif == kif) &&
1029 sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
1030 si->s->key[PF_SK_STACK])) {
1036 * Extract state before potentially releasing the global statetbl
1037 * lock. Ignore the state if the create is still in-progress as
1038 * it can be deleted out from under us by the owning localized cpu.
1039 * However, if CREATEINPROG is not set, state can only be deleted
1040 * by the purge thread which we are protected from via our shared
1045 if (s && (s->state_flags & PFSTATE_CREATEINPROG))
1051 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
1056 * WARNING! May return a state structure that was localized to another cpu,
1057 * destruction is typically protected by the callers pf_token.
1060 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1062 struct pf_state_key *skey = (void *)key;
1063 struct pf_state_key *sk;
1064 struct pf_state_item *si, *ret = NULL;
1066 int cpu = mycpu->gd_cpuid;
1069 pf_status.fcounters[FCNT_STATE_SEARCH]++;
1071 sk = RB_FIND(pf_state_tree, &pf_statetbl[cpu], skey);
1073 lockmgr(&pf_global_statetbl_lock, LK_SHARED);
1074 sk = RB_FIND(pf_state_tree, &pf_statetbl[MAXCPU], skey);
1078 TAILQ_FOREACH(si, &sk->states, entry)
1079 if (dir == PF_INOUT ||
1080 (sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
1081 si->s->key[PF_SK_STACK]))) {
1094 * Extract state before potentially releasing the global statetbl
1095 * lock. Ignore the state if the create is still in-progress as
1096 * it can be deleted out from under us by the owning localized cpu.
1097 * However, if CREATEINPROG is not set, state can only be deleted
1098 * by the purge thread which we are protected from via our shared
1103 if (s && (s->state_flags & PFSTATE_CREATEINPROG))
1109 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
1113 /* END state table stuff */
1116 pf_purge_thread(void *v)
1118 globaldata_t save_gd = mycpu;
1125 tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
1127 endingit = pf_end_threads;
1129 for (nn = 0; nn < ncpus; ++nn) {
1130 lwkt_setcpu_self(globaldata_find(nn));
1132 lwkt_gettoken(&pf_token);
1133 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1137 * process a fraction of the state table every second
1139 if(!pf_purge_expired_states(
1140 1 + (pf_status.states /
1141 pf_default_rule.timeout[
1142 PFTM_INTERVAL]), 0)) {
1143 pf_purge_expired_states(
1144 1 + (pf_status.states /
1145 pf_default_rule.timeout[
1146 PFTM_INTERVAL]), 1);
1150 * purge other expired types every PFTM_INTERVAL
1154 pf_default_rule.timeout[PFTM_INTERVAL]) {
1155 pf_purge_expired_fragments();
1156 if (!pf_purge_expired_src_nodes(locked)) {
1157 pf_purge_expired_src_nodes(1);
1163 * If terminating the thread, clean everything out
1167 pf_purge_expired_states(pf_status.states, 0);
1168 pf_purge_expired_fragments();
1169 pf_purge_expired_src_nodes(1);
1173 lockmgr(&pf_consistency_lock, LK_RELEASE);
1174 lwkt_reltoken(&pf_token);
1176 lwkt_setcpu_self(save_gd);
1182 * Thread termination
1185 wakeup(pf_purge_thread);
1190 pf_state_expires(const struct pf_state *state)
1197 /* handle all PFTM_* > PFTM_MAX here */
1198 if (state->timeout == PFTM_PURGE)
1199 return (time_second);
1200 if (state->timeout == PFTM_UNTIL_PACKET)
1202 KKASSERT(state->timeout != PFTM_UNLINKED);
1203 KKASSERT(state->timeout < PFTM_MAX);
1204 timeout = state->rule.ptr->timeout[state->timeout];
1206 timeout = pf_default_rule.timeout[state->timeout];
1207 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1209 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1210 states = state->rule.ptr->states_cur;
1212 start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1213 end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1214 states = pf_status.states;
1216 if (end && states > start && start < end) {
1218 return (state->expire + timeout * (end - states) /
1221 return (time_second);
1223 return (state->expire + timeout);
1227 * (called with exclusive pf_token)
1230 pf_purge_expired_src_nodes(int waslocked)
1232 struct pf_src_node *cur, *next;
1233 int locked = waslocked;
1234 int cpu = mycpu->gd_cpuid;
1236 for (cur = RB_MIN(pf_src_tree, &tree_src_tracking[cpu]);
1239 next = RB_NEXT(pf_src_tree, &tree_src_tracking[cpu], cur);
1241 if (cur->states <= 0 && cur->expire <= time_second) {
1243 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1244 next = RB_NEXT(pf_src_tree,
1245 &tree_src_tracking[cpu], cur);
1248 if (cur->rule.ptr != NULL) {
1249 cur->rule.ptr->src_nodes--;
1250 if (cur->rule.ptr->states_cur <= 0 &&
1251 cur->rule.ptr->max_src_nodes <= 0)
1252 pf_rm_rule(NULL, cur->rule.ptr);
1254 RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], cur);
1255 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1256 atomic_add_int(&pf_status.src_nodes, -1);
1257 kfree(cur, M_PFSRCTREEPL);
1260 if (locked && !waslocked)
1261 lockmgr(&pf_consistency_lock, LK_RELEASE);
1266 pf_src_tree_remove_state(struct pf_state *s)
1270 if (s->src_node != NULL) {
1272 --s->src_node->conn;
1273 if (--s->src_node->states <= 0) {
1274 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1277 pf_default_rule.timeout[PFTM_SRC_NODE];
1279 s->src_node->expire = time_second + timeout;
1282 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1283 if (--s->nat_src_node->states <= 0) {
1284 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1287 pf_default_rule.timeout[PFTM_SRC_NODE];
1288 s->nat_src_node->expire = time_second + timeout;
1291 s->src_node = s->nat_src_node = NULL;
1294 /* callers should be at crit_enter() */
1296 pf_unlink_state(struct pf_state *cur)
1298 int cpu = mycpu->gd_cpuid;
1300 if (cur->src.state == PF_TCPS_PROXY_DST) {
1301 /* XXX wire key the right one? */
1302 pf_send_tcp(cur->rule.ptr, cur->key[PF_SK_WIRE]->af,
1303 &cur->key[PF_SK_WIRE]->addr[1],
1304 &cur->key[PF_SK_WIRE]->addr[0],
1305 cur->key[PF_SK_WIRE]->port[1],
1306 cur->key[PF_SK_WIRE]->port[0],
1307 cur->src.seqhi, cur->src.seqlo + 1,
1308 TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1310 RB_REMOVE(pf_state_tree_id, &tree_id[cpu], cur);
1311 if (cur->creatorid == pf_status.hostid)
1312 pfsync_delete_state(cur);
1313 cur->timeout = PFTM_UNLINKED;
1314 pf_src_tree_remove_state(cur);
1315 pf_detach_state(cur);
1318 static struct pf_state *purge_cur[MAXCPU];
1321 * callers should be at crit_enter() and hold pf_consistency_lock exclusively.
1322 * pf_token must also be held exclusively.
1325 pf_free_state(struct pf_state *cur)
1327 int cpu = mycpu->gd_cpuid;
1329 KKASSERT(cur->cpuid == cpu);
1331 if (pfsyncif != NULL &&
1332 (pfsyncif->sc_bulk_send_next == cur ||
1333 pfsyncif->sc_bulk_terminator == cur))
1335 KKASSERT(cur->timeout == PFTM_UNLINKED);
1336 if (--cur->rule.ptr->states_cur <= 0 &&
1337 cur->rule.ptr->src_nodes <= 0)
1338 pf_rm_rule(NULL, cur->rule.ptr);
1339 if (cur->nat_rule.ptr != NULL) {
1340 if (--cur->nat_rule.ptr->states_cur <= 0 &&
1341 cur->nat_rule.ptr->src_nodes <= 0) {
1342 pf_rm_rule(NULL, cur->nat_rule.ptr);
1345 if (cur->anchor.ptr != NULL) {
1346 if (--cur->anchor.ptr->states_cur <= 0)
1347 pf_rm_rule(NULL, cur->anchor.ptr);
1349 pf_normalize_tcp_cleanup(cur);
1350 pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1353 * We may be freeing pf_purge_expired_states()'s saved scan entry,
1354 * adjust it if necessary.
1356 if (purge_cur[cpu] == cur) {
1357 kprintf("PURGE CONFLICT\n");
1358 purge_cur[cpu] = TAILQ_NEXT(purge_cur[cpu], entry_list);
1360 TAILQ_REMOVE(&state_list[cpu], cur, entry_list);
1362 pf_tag_unref(cur->tag);
1363 kfree(cur, M_PFSTATEPL);
1364 pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1365 atomic_add_int(&pf_status.states, -1);
1369 pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1371 struct pf_state *cur;
1372 int locked = waslocked;
1373 int cpu = mycpu->gd_cpuid;
1375 while (maxcheck--) {
1377 * Wrap to start of list when we hit the end
1379 cur = purge_cur[cpu];
1381 cur = TAILQ_FIRST(&state_list[cpu]);
1383 break; /* list empty */
1387 * Setup next (purge_cur) while we process this one. If
1388 * we block and something else deletes purge_cur,
1389 * pf_free_state() will adjust it further ahead.
1391 purge_cur[cpu] = TAILQ_NEXT(cur, entry_list);
1393 if (cur->timeout == PFTM_UNLINKED) {
1394 /* free unlinked state */
1396 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1400 } else if (pf_state_expires(cur) <= time_second) {
1401 /* unlink and free expired state */
1402 pf_unlink_state(cur);
1404 if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1413 lockmgr(&pf_consistency_lock, LK_RELEASE);
1418 pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1420 if (aw->type != PF_ADDR_TABLE)
1422 if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1428 pf_tbladdr_remove(struct pf_addr_wrap *aw)
1430 if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1432 pfr_detach_table(aw->p.tbl);
1437 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1439 struct pfr_ktable *kt = aw->p.tbl;
1441 if (aw->type != PF_ADDR_TABLE || kt == NULL)
1443 if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1444 kt = kt->pfrkt_root;
1446 aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1451 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1456 u_int32_t a = ntohl(addr->addr32[0]);
1457 kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1469 u_int8_t i, curstart = 255, curend = 0,
1470 maxstart = 0, maxend = 0;
1471 for (i = 0; i < 8; i++) {
1472 if (!addr->addr16[i]) {
1473 if (curstart == 255)
1479 if ((curend - curstart) >
1480 (maxend - maxstart)) {
1481 maxstart = curstart;
1488 for (i = 0; i < 8; i++) {
1489 if (i >= maxstart && i <= maxend) {
1498 b = ntohs(addr->addr16[i]);
1515 pf_print_state(struct pf_state *s)
1517 pf_print_state_parts(s, NULL, NULL);
1521 pf_print_state_parts(struct pf_state *s,
1522 struct pf_state_key *skwp, struct pf_state_key *sksp)
1524 struct pf_state_key *skw, *sks;
1525 u_int8_t proto, dir;
1527 /* Do our best to fill these, but they're skipped if NULL */
1528 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1529 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1530 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1531 dir = s ? s->direction : 0;
1543 case IPPROTO_ICMPV6:
1547 kprintf("%u ", skw->proto);
1560 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1562 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1565 kprintf(" stack: ");
1567 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1569 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1574 if (proto == IPPROTO_TCP) {
1575 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1576 s->src.seqlo, s->src.seqhi,
1577 s->src.max_win, s->src.seqdiff);
1578 if (s->src.wscale && s->dst.wscale)
1579 kprintf(" wscale=%u",
1580 s->src.wscale & PF_WSCALE_MASK);
1582 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1583 s->dst.seqlo, s->dst.seqhi,
1584 s->dst.max_win, s->dst.seqdiff);
1585 if (s->src.wscale && s->dst.wscale)
1586 kprintf(" wscale=%u",
1587 s->dst.wscale & PF_WSCALE_MASK);
1590 kprintf(" %u:%u", s->src.state, s->dst.state);
1595 pf_print_flags(u_int8_t f)
1617 #define PF_SET_SKIP_STEPS(i) \
1619 while (head[i] != cur) { \
1620 head[i]->skip[i].ptr = cur; \
1621 head[i] = TAILQ_NEXT(head[i], entries); \
1626 pf_calc_skip_steps(struct pf_rulequeue *rules)
1628 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1631 cur = TAILQ_FIRST(rules);
1633 for (i = 0; i < PF_SKIP_COUNT; ++i)
1635 while (cur != NULL) {
1637 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1638 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1639 if (cur->direction != prev->direction)
1640 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1641 if (cur->af != prev->af)
1642 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1643 if (cur->proto != prev->proto)
1644 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1645 if (cur->src.neg != prev->src.neg ||
1646 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1647 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1648 if (cur->src.port[0] != prev->src.port[0] ||
1649 cur->src.port[1] != prev->src.port[1] ||
1650 cur->src.port_op != prev->src.port_op)
1651 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1652 if (cur->dst.neg != prev->dst.neg ||
1653 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1654 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1655 if (cur->dst.port[0] != prev->dst.port[0] ||
1656 cur->dst.port[1] != prev->dst.port[1] ||
1657 cur->dst.port_op != prev->dst.port_op)
1658 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1661 cur = TAILQ_NEXT(cur, entries);
1663 for (i = 0; i < PF_SKIP_COUNT; ++i)
1664 PF_SET_SKIP_STEPS(i);
1668 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1670 if (aw1->type != aw2->type)
1672 switch (aw1->type) {
1673 case PF_ADDR_ADDRMASK:
1675 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1677 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1680 case PF_ADDR_DYNIFTL:
1681 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1682 case PF_ADDR_NOROUTE:
1683 case PF_ADDR_URPFFAILED:
1686 return (aw1->p.tbl != aw2->p.tbl);
1687 case PF_ADDR_RTLABEL:
1688 return (aw1->v.rtlabel != aw2->v.rtlabel);
1690 kprintf("invalid address type: %d\n", aw1->type);
1696 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1702 l = cksum + old - new;
1703 l = (l >> 16) + (l & 65535);
1711 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1712 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1717 PF_ACPY(&ao, a, af);
1725 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1726 ao.addr16[0], an->addr16[0], 0),
1727 ao.addr16[1], an->addr16[1], 0);
1729 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1730 ao.addr16[0], an->addr16[0], u),
1731 ao.addr16[1], an->addr16[1], u),
1737 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1738 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1739 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1740 ao.addr16[0], an->addr16[0], u),
1741 ao.addr16[1], an->addr16[1], u),
1742 ao.addr16[2], an->addr16[2], u),
1743 ao.addr16[3], an->addr16[3], u),
1744 ao.addr16[4], an->addr16[4], u),
1745 ao.addr16[5], an->addr16[5], u),
1746 ao.addr16[6], an->addr16[6], u),
1747 ao.addr16[7], an->addr16[7], u),
1755 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
1757 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1761 memcpy(&ao, a, sizeof(ao));
1762 memcpy(a, &an, sizeof(u_int32_t));
1763 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1764 ao % 65536, an % 65536, u);
1769 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1773 PF_ACPY(&ao, a, AF_INET6);
1774 PF_ACPY(a, an, AF_INET6);
1776 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1777 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1778 pf_cksum_fixup(pf_cksum_fixup(*c,
1779 ao.addr16[0], an->addr16[0], u),
1780 ao.addr16[1], an->addr16[1], u),
1781 ao.addr16[2], an->addr16[2], u),
1782 ao.addr16[3], an->addr16[3], u),
1783 ao.addr16[4], an->addr16[4], u),
1784 ao.addr16[5], an->addr16[5], u),
1785 ao.addr16[6], an->addr16[6], u),
1786 ao.addr16[7], an->addr16[7], u);
1791 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1792 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1793 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1795 struct pf_addr oia, ooa;
1797 PF_ACPY(&oia, ia, af);
1799 PF_ACPY(&ooa, oa, af);
1801 /* Change inner protocol port, fix inner protocol checksum. */
1803 u_int16_t oip = *ip;
1810 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
1811 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1813 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1815 /* Change inner ip address, fix inner ip and icmp checksums. */
1816 PF_ACPY(ia, na, af);
1820 u_int32_t oh2c = *h2c;
1822 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1823 oia.addr16[0], ia->addr16[0], 0),
1824 oia.addr16[1], ia->addr16[1], 0);
1825 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1826 oia.addr16[0], ia->addr16[0], 0),
1827 oia.addr16[1], ia->addr16[1], 0);
1828 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1834 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1835 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1836 pf_cksum_fixup(pf_cksum_fixup(*ic,
1837 oia.addr16[0], ia->addr16[0], u),
1838 oia.addr16[1], ia->addr16[1], u),
1839 oia.addr16[2], ia->addr16[2], u),
1840 oia.addr16[3], ia->addr16[3], u),
1841 oia.addr16[4], ia->addr16[4], u),
1842 oia.addr16[5], ia->addr16[5], u),
1843 oia.addr16[6], ia->addr16[6], u),
1844 oia.addr16[7], ia->addr16[7], u);
1848 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
1850 PF_ACPY(oa, na, af);
1854 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
1855 ooa.addr16[0], oa->addr16[0], 0),
1856 ooa.addr16[1], oa->addr16[1], 0);
1861 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1862 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1863 pf_cksum_fixup(pf_cksum_fixup(*ic,
1864 ooa.addr16[0], oa->addr16[0], u),
1865 ooa.addr16[1], oa->addr16[1], u),
1866 ooa.addr16[2], oa->addr16[2], u),
1867 ooa.addr16[3], oa->addr16[3], u),
1868 ooa.addr16[4], oa->addr16[4], u),
1869 ooa.addr16[5], oa->addr16[5], u),
1870 ooa.addr16[6], oa->addr16[6], u),
1871 ooa.addr16[7], oa->addr16[7], u);
1880 * Need to modulate the sequence numbers in the TCP SACK option
1881 * (credits to Krzysztof Pfaff for report and patch)
1884 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
1885 struct tcphdr *th, struct pf_state_peer *dst)
1887 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
1888 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
1889 int copyback = 0, i, olen;
1890 struct raw_sackblock sack;
1892 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
1893 if (hlen < TCPOLEN_SACKLEN ||
1894 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
1897 while (hlen >= TCPOLEN_SACKLEN) {
1900 case TCPOPT_EOL: /* FALLTHROUGH */
1908 if (olen >= TCPOLEN_SACKLEN) {
1909 for (i = 2; i + TCPOLEN_SACK <= olen;
1910 i += TCPOLEN_SACK) {
1911 memcpy(&sack, &opt[i], sizeof(sack));
1912 pf_change_a(&sack.rblk_start, &th->th_sum,
1913 htonl(ntohl(sack.rblk_start) -
1915 pf_change_a(&sack.rblk_end, &th->th_sum,
1916 htonl(ntohl(sack.rblk_end) -
1918 memcpy(&opt[i], &sack, sizeof(sack));
1932 m_copyback(m, off + sizeof(*th), thoptlen, opts);
1937 pf_send_tcp(const struct pf_rule *r, sa_family_t af,
1938 const struct pf_addr *saddr, const struct pf_addr *daddr,
1939 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
1940 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
1941 u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
1946 struct ip *h = NULL;
1949 struct ip6_hdr *h6 = NULL;
1951 struct tcphdr *th = NULL;
1954 ASSERT_LWKT_TOKEN_HELD(&pf_token);
1956 /* maximum segment size tcp option */
1957 tlen = sizeof(struct tcphdr);
1964 len = sizeof(struct ip) + tlen;
1969 len = sizeof(struct ip6_hdr) + tlen;
1975 * Create outgoing mbuf.
1977 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1978 * so make sure pf.flags is clear.
1980 m = m_gethdr(MB_DONTWAIT, MT_HEADER);
1985 m->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1986 m->m_pkthdr.pf.flags = 0;
1987 m->m_pkthdr.pf.tag = rtag;
1988 /* XXX Recheck when upgrading to > 4.4 */
1989 m->m_pkthdr.pf.statekey = NULL;
1990 if (r != NULL && r->rtableid >= 0)
1991 m->m_pkthdr.pf.rtableid = r->rtableid;
1994 if (r != NULL && r->qid) {
1995 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1996 m->m_pkthdr.pf.qid = r->qid;
1997 m->m_pkthdr.pf.ecn_af = af;
1998 m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
2001 m->m_data += max_linkhdr;
2002 m->m_pkthdr.len = m->m_len = len;
2003 m->m_pkthdr.rcvif = NULL;
2004 bzero(m->m_data, len);
2008 h = mtod(m, struct ip *);
2010 /* IP header fields included in the TCP checksum */
2011 h->ip_p = IPPROTO_TCP;
2013 h->ip_src.s_addr = saddr->v4.s_addr;
2014 h->ip_dst.s_addr = daddr->v4.s_addr;
2016 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2021 h6 = mtod(m, struct ip6_hdr *);
2023 /* IP header fields included in the TCP checksum */
2024 h6->ip6_nxt = IPPROTO_TCP;
2025 h6->ip6_plen = htons(tlen);
2026 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2027 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2029 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2035 th->th_sport = sport;
2036 th->th_dport = dport;
2037 th->th_seq = htonl(seq);
2038 th->th_ack = htonl(ack);
2039 th->th_off = tlen >> 2;
2040 th->th_flags = flags;
2041 th->th_win = htons(win);
2044 opt = (char *)(th + 1);
2045 opt[0] = TCPOPT_MAXSEG;
2048 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2055 th->th_sum = in_cksum(m, len);
2057 /* Finish the IP header */
2059 h->ip_hl = sizeof(*h) >> 2;
2060 h->ip_tos = IPTOS_LOWDELAY;
2062 h->ip_off = path_mtu_discovery ? IP_DF : 0;
2063 h->ip_ttl = ttl ? ttl : ip_defttl;
2066 lwkt_reltoken(&pf_token);
2067 ip_output(m, NULL, NULL, 0, NULL, NULL);
2068 lwkt_gettoken(&pf_token);
2072 struct ether_header *e = (void *)ro.ro_dst.sa_data;
2080 ro.ro_dst.sa_len = sizeof(ro.ro_dst);
2081 ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
2082 bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
2083 bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
2084 e->ether_type = eh->ether_type;
2085 /* XXX_IMPORT: later */
2086 lwkt_reltoken(&pf_token);
2087 ip_output(m, NULL, &ro, 0, NULL, NULL);
2088 lwkt_gettoken(&pf_token);
2095 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2096 sizeof(struct ip6_hdr), tlen);
2098 h6->ip6_vfc |= IPV6_VERSION;
2099 h6->ip6_hlim = IPV6_DEFHLIM;
2101 lwkt_reltoken(&pf_token);
2102 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2103 lwkt_gettoken(&pf_token);
2110 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2116 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
2117 * so make sure pf.flags is clear.
2119 if ((m0 = m_copy(m, 0, M_COPYALL)) == NULL)
2122 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
2123 m0->m_pkthdr.pf.flags = 0;
2124 /* XXX Re-Check when Upgrading to > 4.4 */
2125 m0->m_pkthdr.pf.statekey = NULL;
2127 if (r->rtableid >= 0)
2128 m0->m_pkthdr.pf.rtableid = r->rtableid;
2132 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
2133 m0->m_pkthdr.pf.qid = r->qid;
2134 m0->m_pkthdr.pf.ecn_af = af;
2135 m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
2142 icmp_error(m0, type, code, 0, 0);
2147 icmp6_error(m0, type, code, 0);
2154 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2155 * If n is 0, they match if they are equal. If n is != 0, they match if they
2159 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2160 struct pf_addr *b, sa_family_t af)
2167 if ((a->addr32[0] & m->addr32[0]) ==
2168 (b->addr32[0] & m->addr32[0]))
2174 if (((a->addr32[0] & m->addr32[0]) ==
2175 (b->addr32[0] & m->addr32[0])) &&
2176 ((a->addr32[1] & m->addr32[1]) ==
2177 (b->addr32[1] & m->addr32[1])) &&
2178 ((a->addr32[2] & m->addr32[2]) ==
2179 (b->addr32[2] & m->addr32[2])) &&
2180 ((a->addr32[3] & m->addr32[3]) ==
2181 (b->addr32[3] & m->addr32[3])))
2200 * Return 1 if b <= a <= e, otherwise return 0.
2203 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2204 struct pf_addr *a, sa_family_t af)
2209 if ((a->addr32[0] < b->addr32[0]) ||
2210 (a->addr32[0] > e->addr32[0]))
2219 for (i = 0; i < 4; ++i)
2220 if (a->addr32[i] > b->addr32[i])
2222 else if (a->addr32[i] < b->addr32[i])
2225 for (i = 0; i < 4; ++i)
2226 if (a->addr32[i] < e->addr32[i])
2228 else if (a->addr32[i] > e->addr32[i])
2238 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2242 return ((p > a1) && (p < a2));
2244 return ((p < a1) || (p > a2));
2246 return ((p >= a1) && (p <= a2));
2260 return (0); /* never reached */
2264 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2269 return (pf_match(op, a1, a2, p));
2273 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2275 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2277 return (pf_match(op, a1, a2, u));
2281 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2283 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2285 return (pf_match(op, a1, a2, g));
2289 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
2292 *tag = m->m_pkthdr.pf.tag;
2294 return ((!r->match_tag_not && r->match_tag == *tag) ||
2295 (r->match_tag_not && r->match_tag != *tag));
2299 pf_tag_packet(struct mbuf *m, int tag, int rtableid)
2301 if (tag <= 0 && rtableid < 0)
2305 m->m_pkthdr.pf.tag = tag;
2307 m->m_pkthdr.pf.rtableid = rtableid;
2313 pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
2314 struct pf_rule **r, struct pf_rule **a, int *match)
2316 struct pf_anchor_stackframe *f;
2318 (*r)->anchor->match = 0;
2321 if (*depth >= NELEM(pf_anchor_stack)) {
2322 kprintf("pf_step_into_anchor: stack overflow\n");
2323 *r = TAILQ_NEXT(*r, entries);
2325 } else if (*depth == 0 && a != NULL)
2327 f = pf_anchor_stack + (*depth)++;
2330 if ((*r)->anchor_wildcard) {
2331 f->parent = &(*r)->anchor->children;
2332 if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
2337 *rs = &f->child->ruleset;
2341 *rs = &(*r)->anchor->ruleset;
2343 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2347 pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
2348 struct pf_rule **r, struct pf_rule **a, int *match)
2350 struct pf_anchor_stackframe *f;
2356 f = pf_anchor_stack + *depth - 1;
2357 if (f->parent != NULL && f->child != NULL) {
2358 if (f->child->match ||
2359 (match != NULL && *match)) {
2360 f->r->anchor->match = 1;
2363 f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
2364 if (f->child != NULL) {
2365 *rs = &f->child->ruleset;
2366 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2374 if (*depth == 0 && a != NULL)
2377 if (f->r->anchor->match || (match != NULL && *match))
2378 quick = f->r->quick;
2379 *r = TAILQ_NEXT(f->r, entries);
2380 } while (*r == NULL);
2387 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2388 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2393 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2394 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2398 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2399 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2400 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2401 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2402 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2403 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2404 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2405 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2411 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2416 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2420 if (addr->addr32[3] == 0xffffffff) {
2421 addr->addr32[3] = 0;
2422 if (addr->addr32[2] == 0xffffffff) {
2423 addr->addr32[2] = 0;
2424 if (addr->addr32[1] == 0xffffffff) {
2425 addr->addr32[1] = 0;
2427 htonl(ntohl(addr->addr32[0]) + 1);
2430 htonl(ntohl(addr->addr32[1]) + 1);
2433 htonl(ntohl(addr->addr32[2]) + 1);
2436 htonl(ntohl(addr->addr32[3]) + 1);
2442 #define mix(a,b,c) \
2444 a -= b; a -= c; a ^= (c >> 13); \
2445 b -= c; b -= a; b ^= (a << 8); \
2446 c -= a; c -= b; c ^= (b >> 13); \
2447 a -= b; a -= c; a ^= (c >> 12); \
2448 b -= c; b -= a; b ^= (a << 16); \
2449 c -= a; c -= b; c ^= (b >> 5); \
2450 a -= b; a -= c; a ^= (c >> 3); \
2451 b -= c; b -= a; b ^= (a << 10); \
2452 c -= a; c -= b; c ^= (b >> 15); \
2456 * hash function based on bridge_hash in if_bridge.c
2459 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2460 struct pf_poolhashkey *key, sa_family_t af)
2462 u_int32_t a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2467 a += inaddr->addr32[0];
2470 hash->addr32[0] = c + key->key32[2];
2475 a += inaddr->addr32[0];
2476 b += inaddr->addr32[2];
2478 hash->addr32[0] = c;
2479 a += inaddr->addr32[1];
2480 b += inaddr->addr32[3];
2483 hash->addr32[1] = c;
2484 a += inaddr->addr32[2];
2485 b += inaddr->addr32[1];
2488 hash->addr32[2] = c;
2489 a += inaddr->addr32[3];
2490 b += inaddr->addr32[0];
2493 hash->addr32[3] = c;
2500 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2501 struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2503 unsigned char hash[16];
2504 struct pf_pool *rpool = &r->rpool;
2505 struct pf_pooladdr *acur = rpool->cur;
2506 struct pf_pooladdr *cur;
2507 struct pf_addr *raddr;
2508 struct pf_addr *rmask;
2509 struct pf_addr counter;
2510 struct pf_src_node k;
2511 int cpu = mycpu->gd_cpuid;
2515 * NOTE! rpool->cur and rpool->tblidx can be iterators and thus
2516 * may represent a SMP race due to the shared nature of the
2517 * rpool structure. We allow the race and ensure that updates
2518 * do not create a fatal condition.
2522 raddr = &cur->addr.v.a.addr;
2523 rmask = &cur->addr.v.a.mask;
2525 if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2526 (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2528 PF_ACPY(&k.addr, saddr, af);
2529 if (r->rule_flag & PFRULE_RULESRCTRACK ||
2530 r->rpool.opts & PF_POOL_STICKYADDR)
2534 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2535 *sn = RB_FIND(pf_src_tree, &tree_src_tracking[cpu], &k);
2536 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2537 PF_ACPY(naddr, &(*sn)->raddr, af);
2538 if (pf_status.debug >= PF_DEBUG_MISC) {
2539 kprintf("pf_map_addr: src tracking maps ");
2540 pf_print_host(&k.addr, 0, af);
2542 pf_print_host(naddr, 0, af);
2549 if (cur->addr.type == PF_ADDR_NOROUTE)
2551 if (cur->addr.type == PF_ADDR_DYNIFTL) {
2555 if (cur->addr.p.dyn->pfid_acnt4 < 1 &&
2556 (rpool->opts & PF_POOL_TYPEMASK) !=
2559 raddr = &cur->addr.p.dyn->pfid_addr4;
2560 rmask = &cur->addr.p.dyn->pfid_mask4;
2565 if (cur->addr.p.dyn->pfid_acnt6 < 1 &&
2566 (rpool->opts & PF_POOL_TYPEMASK) !=
2569 raddr = &cur->addr.p.dyn->pfid_addr6;
2570 rmask = &cur->addr.p.dyn->pfid_mask6;
2574 } else if (cur->addr.type == PF_ADDR_TABLE) {
2575 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2576 return (1); /* unsupported */
2578 raddr = &cur->addr.v.a.addr;
2579 rmask = &cur->addr.v.a.mask;
2582 switch (rpool->opts & PF_POOL_TYPEMASK) {
2584 PF_ACPY(naddr, raddr, af);
2586 case PF_POOL_BITMASK:
2587 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2589 case PF_POOL_RANDOM:
2590 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2594 counter.addr32[0] = htonl(karc4random());
2599 if (rmask->addr32[3] != 0xffffffff)
2601 htonl(karc4random());
2604 if (rmask->addr32[2] != 0xffffffff)
2606 htonl(karc4random());
2609 if (rmask->addr32[1] != 0xffffffff)
2611 htonl(karc4random());
2614 if (rmask->addr32[0] != 0xffffffff)
2616 htonl(karc4random());
2620 PF_POOLMASK(naddr, raddr, rmask, &counter, af);
2621 PF_ACPY(init_addr, naddr, af);
2624 counter = rpool->counter;
2626 PF_AINC(&counter, af);
2627 PF_POOLMASK(naddr, raddr, rmask, &counter, af);
2628 rpool->counter = counter;
2631 case PF_POOL_SRCHASH:
2632 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2633 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2635 case PF_POOL_ROUNDROBIN:
2636 tblidx = rpool->tblidx;
2637 counter = rpool->counter;
2638 if (cur->addr.type == PF_ADDR_TABLE) {
2639 if (!pfr_pool_get(cur->addr.p.tbl,
2641 &raddr, &rmask, af)) {
2644 } else if (cur->addr.type == PF_ADDR_DYNIFTL) {
2645 if (!pfr_pool_get(cur->addr.p.dyn->pfid_kt,
2647 &raddr, &rmask, af)) {
2650 } else if (pf_match_addr(0, raddr, rmask,
2656 if ((cur = TAILQ_NEXT(cur, entries)) == NULL)
2657 cur = TAILQ_FIRST(&rpool->list);
2658 if (cur->addr.type == PF_ADDR_TABLE) {
2660 if (pfr_pool_get(cur->addr.p.tbl,
2662 &raddr, &rmask, af)) {
2663 /* table contains no address of type 'af' */
2668 } else if (cur->addr.type == PF_ADDR_DYNIFTL) {
2670 if (pfr_pool_get(cur->addr.p.dyn->pfid_kt,
2672 &raddr, &rmask, af)) {
2673 /* table contains no address of type 'af' */
2679 raddr = &cur->addr.v.a.addr;
2680 rmask = &cur->addr.v.a.mask;
2681 PF_ACPY(&counter, raddr, af);
2686 rpool->tblidx = tblidx;
2687 PF_ACPY(naddr, &counter, af);
2688 if (init_addr != NULL && PF_AZERO(init_addr, af))
2689 PF_ACPY(init_addr, naddr, af);
2690 PF_AINC(&counter, af);
2691 rpool->counter = counter;
2695 PF_ACPY(&(*sn)->raddr, naddr, af);
2697 if (pf_status.debug >= PF_DEBUG_MISC &&
2698 (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2699 kprintf("pf_map_addr: selected address ");
2700 pf_print_host(naddr, 0, af);
2708 pf_get_sport(struct pf_pdesc *pd, sa_family_t af,
2709 u_int8_t proto, struct pf_rule *r,
2710 struct pf_addr *saddr, struct pf_addr *daddr,
2711 u_int16_t sport, u_int16_t dport,
2712 struct pf_addr *naddr, u_int16_t *nport,
2713 u_int16_t low, u_int16_t high, struct pf_src_node **sn)
2715 struct pf_state_key_cmp key;
2716 struct pf_addr init_addr;
2718 u_int32_t toeplitz_sport;
2720 bzero(&init_addr, sizeof(init_addr));
2721 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2724 if (proto == IPPROTO_ICMP) {
2729 bzero(&key, sizeof(key));
2732 key.port[0] = dport;
2733 PF_ACPY(&key.addr[0], daddr, key.af);
2736 PF_ACPY(&key.addr[1], naddr, key.af);
2739 * We want to select a port that calculates to a toeplitz hash
2740 * that masks to the same cpu, otherwise the response may
2741 * not see the new state.
2743 * We can still do this even if the kernel is disregarding
2744 * the hash and vectoring the packets to a specific cpu,
2745 * but it will reduce the number of ports we can use.
2750 toeplitz_piecemeal_port(sport) ^
2751 toeplitz_piecemeal_addr(saddr->v4.s_addr) ^
2752 toeplitz_piecemeal_addr(naddr->v4.s_addr);
2763 * port search; start random, step;
2764 * similar 2 portloop in in_pcbbind
2766 * WARNING! We try to match such that the kernel will
2767 * dispatch the translated host/port to the same
2768 * cpu, but this might not be possible.
2770 * In the case where the port is fixed, or for the
2771 * UDP case (whos toeplitz does not incorporate the
2772 * port), we set not_cpu_localized which ultimately
2773 * causes the pf_state_tree element
2775 * XXX fixed ports present a problem for cpu localization.
2777 if (!(proto == IPPROTO_TCP ||
2778 proto == IPPROTO_UDP ||
2779 proto == IPPROTO_ICMP)) {
2781 * non-specific protocol, leave port intact.
2783 key.port[1] = sport;
2784 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2786 pd->not_cpu_localized = 1;
2789 } else if (low == 0 && high == 0) {
2791 * static-port same as originator.
2793 key.port[1] = sport;
2794 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2796 pd->not_cpu_localized = 1;
2799 } else if (low == high) {
2801 * specific port as specified.
2803 key.port[1] = htons(low);
2804 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2805 *nport = htons(low);
2806 pd->not_cpu_localized = 1;
2811 * normal dynamic port
2821 cut = htonl(karc4random()) % (1 + high - low) + low;
2822 /* low <= cut <= high */
2823 for (tmp = cut; tmp <= high; ++(tmp)) {
2824 key.port[1] = htons(tmp);
2825 if ((toeplitz_piecemeal_port(key.port[1]) ^
2826 toeplitz_sport) & ncpus2_mask) {
2829 if (pf_find_state_all(&key, PF_IN, NULL) ==
2830 NULL && !in_baddynamic(tmp, proto)) {
2831 if (proto == IPPROTO_UDP)
2832 pd->not_cpu_localized = 1;
2833 *nport = htons(tmp);
2837 for (tmp = cut - 1; tmp >= low; --(tmp)) {
2838 key.port[1] = htons(tmp);
2839 if ((toeplitz_piecemeal_port(key.port[1]) ^
2840 toeplitz_sport) & ncpus2_mask) {
2843 if (pf_find_state_all(&key, PF_IN, NULL) ==
2844 NULL && !in_baddynamic(tmp, proto)) {
2845 if (proto == IPPROTO_UDP)
2846 pd->not_cpu_localized = 1;
2847 *nport = htons(tmp);
2856 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
2857 case PF_POOL_RANDOM:
2858 case PF_POOL_ROUNDROBIN:
2859 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2863 case PF_POOL_SRCHASH:
2864 case PF_POOL_BITMASK:
2868 } while (! PF_AEQ(&init_addr, naddr, af) );
2869 return (1); /* none available */
2873 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
2874 int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
2875 struct pf_addr *daddr, u_int16_t dport, int rs_num)
2877 struct pf_rule *r, *rm = NULL;
2878 struct pf_ruleset *ruleset = NULL;
2883 r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
2884 while (r && rm == NULL) {
2885 struct pf_rule_addr *src = NULL, *dst = NULL;
2886 struct pf_addr_wrap *xdst = NULL;
2887 struct pf_pooladdr *cur;
2889 if (r->action == PF_BINAT && direction == PF_IN) {
2891 cur = r->rpool.cur; /* SMP race possible */
2901 if (pfi_kif_match(r->kif, kif) == r->ifnot)
2902 r = r->skip[PF_SKIP_IFP].ptr;
2903 else if (r->direction && r->direction != direction)
2904 r = r->skip[PF_SKIP_DIR].ptr;
2905 else if (r->af && r->af != pd->af)
2906 r = r->skip[PF_SKIP_AF].ptr;
2907 else if (r->proto && r->proto != pd->proto)
2908 r = r->skip[PF_SKIP_PROTO].ptr;
2909 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
2911 r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
2912 PF_SKIP_DST_ADDR].ptr;
2913 else if (src->port_op && !pf_match_port(src->port_op,
2914 src->port[0], src->port[1], sport))
2915 r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
2916 PF_SKIP_DST_PORT].ptr;
2917 else if (dst != NULL &&
2918 PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
2919 r = r->skip[PF_SKIP_DST_ADDR].ptr;
2920 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
2922 r = TAILQ_NEXT(r, entries);
2923 else if (dst != NULL && dst->port_op &&
2924 !pf_match_port(dst->port_op, dst->port[0],
2925 dst->port[1], dport))
2926 r = r->skip[PF_SKIP_DST_PORT].ptr;
2927 else if (r->match_tag && !pf_match_tag(m, r, &tag))
2928 r = TAILQ_NEXT(r, entries);
2929 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
2930 IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
2931 off, pd->hdr.tcp), r->os_fingerprint)))
2932 r = TAILQ_NEXT(r, entries);
2936 if (r->rtableid >= 0)
2937 rtableid = r->rtableid;
2938 if (r->anchor == NULL) {
2941 pf_step_into_anchor(&asd, &ruleset, rs_num,
2945 pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
2948 if (pf_tag_packet(m, tag, rtableid))
2950 if (rm != NULL && (rm->action == PF_NONAT ||
2951 rm->action == PF_NORDR || rm->action == PF_NOBINAT))
2957 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
2958 struct pfi_kif *kif, struct pf_src_node **sn,
2959 struct pf_state_key **skw, struct pf_state_key **sks,
2960 struct pf_state_key **skp, struct pf_state_key **nkp,
2961 struct pf_addr *saddr, struct pf_addr *daddr,
2962 u_int16_t sport, u_int16_t dport)
2964 struct pf_rule *r = NULL;
2966 if (direction == PF_OUT) {
2967 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2968 sport, daddr, dport, PF_RULESET_BINAT);
2970 r = pf_match_translation(pd, m, off, direction, kif,
2971 saddr, sport, daddr, dport, PF_RULESET_NAT);
2973 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2974 sport, daddr, dport, PF_RULESET_RDR);
2976 r = pf_match_translation(pd, m, off, direction, kif,
2977 saddr, sport, daddr, dport, PF_RULESET_BINAT);
2981 struct pf_addr *naddr;
2984 if (pf_state_key_setup(pd, r, skw, sks, skp, nkp,
2985 saddr, daddr, sport, dport))
2988 /* XXX We only modify one side for now. */
2989 naddr = &(*nkp)->addr[1];
2990 nport = &(*nkp)->port[1];
2993 * NOTE: Currently all translations will clear
2994 * BRIDGE_MBUF_TAGGED, telling the bridge to
2995 * ignore the original input encapsulation.
2997 switch (r->action) {
3003 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3004 if (pf_get_sport(pd, pd->af, pd->proto, r,
3005 saddr, daddr, sport, dport,
3006 naddr, nport, r->rpool.proxy_port[0],
3007 r->rpool.proxy_port[1], sn)) {
3008 DPFPRINTF(PF_DEBUG_MISC,
3009 ("pf: NAT proxy port allocation "
3011 r->rpool.proxy_port[0],
3012 r->rpool.proxy_port[1]));
3017 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3018 switch (direction) {
3020 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
3024 if (r->rpool.cur->addr.p.dyn->
3028 &r->rpool.cur->addr.p.dyn->
3030 &r->rpool.cur->addr.p.dyn->
3037 if (r->rpool.cur->addr.p.dyn->
3041 &r->rpool.cur->addr.p.dyn->
3043 &r->rpool.cur->addr.p.dyn->
3051 &r->rpool.cur->addr.v.a.addr,
3052 &r->rpool.cur->addr.v.a.mask,
3056 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
3060 if (r->src.addr.p.dyn->
3064 &r->src.addr.p.dyn->
3066 &r->src.addr.p.dyn->
3073 if (r->src.addr.p.dyn->
3077 &r->src.addr.p.dyn->
3079 &r->src.addr.p.dyn->
3087 &r->src.addr.v.a.addr,
3088 &r->src.addr.v.a.mask, daddr,
3094 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3095 if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
3097 if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
3099 PF_POOLMASK(naddr, naddr,
3100 &r->rpool.cur->addr.v.a.mask, daddr,
3103 if (r->rpool.proxy_port[1]) {
3104 u_int32_t tmp_nport;
3106 tmp_nport = ((ntohs(dport) -
3107 ntohs(r->dst.port[0])) %
3108 (r->rpool.proxy_port[1] -
3109 r->rpool.proxy_port[0] + 1)) +
3110 r->rpool.proxy_port[0];
3112 /* wrap around if necessary */
3113 if (tmp_nport > 65535)
3115 *nport = htons((u_int16_t)tmp_nport);
3116 } else if (r->rpool.proxy_port[0])
3117 *nport = htons(r->rpool.proxy_port[0]);
3128 struct netmsg_hashlookup {
3129 struct netmsg_base base;
3130 struct inpcb **nm_pinp;
3131 struct inpcbinfo *nm_pcbinfo;
3132 struct pf_addr *nm_saddr;
3133 struct pf_addr *nm_daddr;
3139 #ifdef PF_SOCKET_LOOKUP_DOMSG
3141 in_pcblookup_hash_handler(netmsg_t msg)
3143 struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
3145 if (rmsg->nm_af == AF_INET)
3146 *rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
3147 rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
3148 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
3151 *rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
3152 &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
3153 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
3155 lwkt_replymsg(&rmsg->base.lmsg, 0);
3157 #endif /* PF_SOCKET_LOOKUP_DOMSG */
3160 pf_socket_lookup(int direction, struct pf_pdesc *pd)
3162 struct pf_addr *saddr, *daddr;
3163 u_int16_t sport, dport;
3164 struct inpcbinfo *pi;
3166 struct netmsg_hashlookup *msg = NULL;
3167 #ifdef PF_SOCKET_LOOKUP_DOMSG
3168 struct netmsg_hashlookup msg0;
3174 pd->lookup.uid = UID_MAX;
3175 pd->lookup.gid = GID_MAX;
3176 pd->lookup.pid = NO_PID;
3177 if (direction == PF_IN) {
3184 switch (pd->proto) {
3186 if (pd->hdr.tcp == NULL)
3188 sport = pd->hdr.tcp->th_sport;
3189 dport = pd->hdr.tcp->th_dport;
3191 pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
3192 pi = &tcbinfo[pi_cpu];
3194 * Our netstack runs lockless on MP systems
3195 * (only for TCP connections at the moment).
3197 * As we are not allowed to read another CPU's tcbinfo,
3198 * we have to ask that CPU via remote call to search the
3201 * Prepare a msg iff data belongs to another CPU.
3203 if (pi_cpu != mycpu->gd_cpuid) {
3204 #ifdef PF_SOCKET_LOOKUP_DOMSG
3208 * Following lwkt_domsg() is dangerous and could
3209 * lockup the network system, e.g.
3212 * netisr0 domsg to netisr1 (due to lookup)
3213 * netisr1 domsg to netisr0 (due to lookup)
3215 * We simply return -1 here, since we are probably
3216 * called before NAT, so the TCP packet should
3217 * already be on the correct CPU.
3220 netmsg_init(&msg->base, NULL, &curthread->td_msgport,
3221 0, in_pcblookup_hash_handler);
3222 msg->nm_pinp = &inp;
3223 msg->nm_pcbinfo = pi;
3224 msg->nm_saddr = saddr;
3225 msg->nm_sport = sport;
3226 msg->nm_daddr = daddr;
3227 msg->nm_dport = dport;
3228 msg->nm_af = pd->af;
3229 #else /* !PF_SOCKET_LOOKUP_DOMSG */
3230 kprintf("pf_socket_lookup: tcp packet not on the "
3231 "correct cpu %d, cur cpu %d\n",
3233 print_backtrace(-1);
3235 #endif /* PF_SOCKET_LOOKUP_DOMSG */
3239 if (pd->hdr.udp == NULL)
3241 sport = pd->hdr.udp->uh_sport;
3242 dport = pd->hdr.udp->uh_dport;
3248 if (direction != PF_IN) {
3259 * Query other CPU, second part
3261 * msg only gets initialized when:
3263 * 2) the info belongs to another CPU
3265 * Use some switch/case magic to avoid code duplication.
3268 inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
3269 &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
3275 /* FALLTHROUGH if SMP and on other CPU */
3279 lwkt_domsg(netisr_cpuport(pi_cpu),
3280 &msg->base.lmsg, 0);
3283 inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
3284 dport, INPLOOKUP_WILDCARD, NULL);
3293 pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
3294 pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
3299 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3303 u_int8_t *opt, optlen;
3304 u_int8_t wscale = 0;
3306 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3307 if (hlen <= sizeof(struct tcphdr))
3309 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3311 opt = hdr + sizeof(struct tcphdr);
3312 hlen -= sizeof(struct tcphdr);
3322 if (wscale > TCP_MAX_WINSHIFT)
3323 wscale = TCP_MAX_WINSHIFT;
3324 wscale |= PF_WSCALE_FLAG;
3339 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3343 u_int8_t *opt, optlen;
3344 u_int16_t mss = tcp_mssdflt;
3346 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3347 if (hlen <= sizeof(struct tcphdr))
3349 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3351 opt = hdr + sizeof(struct tcphdr);
3352 hlen -= sizeof(struct tcphdr);
3353 while (hlen >= TCPOLEN_MAXSEG) {
3361 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3376 pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
3379 struct sockaddr_in *dst;
3383 struct sockaddr_in6 *dst6;
3384 struct route_in6 ro6;
3386 struct rtentry *rt = NULL;
3388 u_int16_t mss = tcp_mssdflt;
3393 hlen = sizeof(struct ip);
3394 bzero(&ro, sizeof(ro));
3395 dst = (struct sockaddr_in *)&ro.ro_dst;
3396 dst->sin_family = AF_INET;
3397 dst->sin_len = sizeof(*dst);
3398 dst->sin_addr = addr->v4;
3399 rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
3405 hlen = sizeof(struct ip6_hdr);
3406 bzero(&ro6, sizeof(ro6));
3407 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3408 dst6->sin6_family = AF_INET6;
3409 dst6->sin6_len = sizeof(*dst6);
3410 dst6->sin6_addr = addr->v6;
3411 rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
3417 if (rt && rt->rt_ifp) {
3418 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3419 mss = max(tcp_mssdflt, mss);
3422 mss = min(mss, offer);
3423 mss = max(mss, 64); /* sanity - at least max opt space */
3428 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3430 struct pf_rule *r = s->rule.ptr;
3433 if (!r->rt || r->rt == PF_FASTROUTE)
3435 switch (s->key[PF_SK_WIRE]->af) {
3438 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
3440 s->rt_kif = r->rpool.cur->kif;
3445 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
3447 s->rt_kif = r->rpool.cur->kif;
3454 pf_tcp_iss(struct pf_pdesc *pd)
3457 u_int32_t digest[4];
3459 if (pf_tcp_secret_init == 0) {
3460 lwkt_gettoken(&pf_gtoken);
3461 if (pf_tcp_secret_init == 0) {
3462 karc4rand(pf_tcp_secret, sizeof(pf_tcp_secret));
3463 MD5Init(&pf_tcp_secret_ctx);
3464 MD5Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3465 sizeof(pf_tcp_secret));
3466 pf_tcp_secret_init = 1;
3468 lwkt_reltoken(&pf_gtoken);
3470 ctx = pf_tcp_secret_ctx;
3472 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3473 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3474 if (pd->af == AF_INET6) {
3475 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3476 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3478 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3479 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3481 MD5Final((u_char *)digest, &ctx);
3482 pf_tcp_iss_off += 4096;
3484 return (digest[0] + pd->hdr.tcp->th_seq + pf_tcp_iss_off);
3488 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3489 struct pfi_kif *kif, struct mbuf *m, int off, void *h,
3490 struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
3491 struct ifqueue *ifq, struct inpcb *inp)
3493 struct pf_rule *nr = NULL;
3494 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
3495 sa_family_t af = pd->af;
3496 struct pf_rule *r, *a = NULL;
3497 struct pf_ruleset *ruleset = NULL;
3498 struct pf_src_node *nsn = NULL;
3499 struct tcphdr *th = pd->hdr.tcp;
3500 struct pf_state_key *skw = NULL, *sks = NULL;
3501 struct pf_state_key *sk = NULL, *nk = NULL;
3503 int rewrite = 0, hdrlen = 0;
3504 int tag = -1, rtableid = -1;
3508 u_int16_t sport = 0, dport = 0;
3509 u_int16_t bproto_sum = 0, bip_sum = 0;
3510 u_int8_t icmptype = 0, icmpcode = 0;
3513 if (direction == PF_IN && pf_check_congestion(ifq)) {
3514 REASON_SET(&reason, PFRES_CONGEST);
3519 pd->lookup.done = pf_socket_lookup(direction, pd);
3520 else if (debug_pfugidhack) {
3521 DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
3522 pd->lookup.done = pf_socket_lookup(direction, pd);
3525 switch (pd->proto) {
3527 sport = th->th_sport;
3528 dport = th->th_dport;
3529 hdrlen = sizeof(*th);
3532 sport = pd->hdr.udp->uh_sport;
3533 dport = pd->hdr.udp->uh_dport;
3534 hdrlen = sizeof(*pd->hdr.udp);
3538 if (pd->af != AF_INET)
3540 sport = dport = pd->hdr.icmp->icmp_id;
3541 hdrlen = sizeof(*pd->hdr.icmp);
3542 icmptype = pd->hdr.icmp->icmp_type;
3543 icmpcode = pd->hdr.icmp->icmp_code;
3545 if (icmptype == ICMP_UNREACH ||
3546 icmptype == ICMP_SOURCEQUENCH ||
3547 icmptype == ICMP_REDIRECT ||
3548 icmptype == ICMP_TIMXCEED ||
3549 icmptype == ICMP_PARAMPROB)
3554 case IPPROTO_ICMPV6:
3557 sport = dport = pd->hdr.icmp6->icmp6_id;
3558 hdrlen = sizeof(*pd->hdr.icmp6);
3559 icmptype = pd->hdr.icmp6->icmp6_type;
3560 icmpcode = pd->hdr.icmp6->icmp6_code;
3562 if (icmptype == ICMP6_DST_UNREACH ||
3563 icmptype == ICMP6_PACKET_TOO_BIG ||
3564 icmptype == ICMP6_TIME_EXCEEDED ||
3565 icmptype == ICMP6_PARAM_PROB)
3570 sport = dport = hdrlen = 0;
3574 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3576 /* check packet for BINAT/NAT/RDR */
3577 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn,
3578 &skw, &sks, &sk, &nk, saddr, daddr, sport, dport)) != NULL) {
3579 if (nk == NULL || sk == NULL) {
3580 REASON_SET(&reason, PFRES_MEMORY);
3585 bip_sum = *pd->ip_sum;
3587 m->m_flags &= ~M_HASH;
3588 switch (pd->proto) {
3590 bproto_sum = th->th_sum;
3591 pd->proto_sum = &th->th_sum;
3593 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3594 nk->port[pd->sidx] != sport) {
3595 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3596 &th->th_sum, &nk->addr[pd->sidx],
3597 nk->port[pd->sidx], 0, af);
3598 pd->sport = &th->th_sport;
3599 sport = th->th_sport;
3602 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3603 nk->port[pd->didx] != dport) {
3604 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3605 &th->th_sum, &nk->addr[pd->didx],
3606 nk->port[pd->didx], 0, af);
3607 dport = th->th_dport;
3608 pd->dport = &th->th_dport;
3613 bproto_sum = pd->hdr.udp->uh_sum;
3614 pd->proto_sum = &pd->hdr.udp->uh_sum;
3616 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3617 nk->port[pd->sidx] != sport) {
3618 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3619 pd->ip_sum, &pd->hdr.udp->uh_sum,
3620 &nk->addr[pd->sidx],
3621 nk->port[pd->sidx], 1, af);
3622 sport = pd->hdr.udp->uh_sport;
3623 pd->sport = &pd->hdr.udp->uh_sport;
3626 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3627 nk->port[pd->didx] != dport) {
3628 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3629 pd->ip_sum, &pd->hdr.udp->uh_sum,
3630 &nk->addr[pd->didx],
3631 nk->port[pd->didx], 1, af);
3632 dport = pd->hdr.udp->uh_dport;
3633 pd->dport = &pd->hdr.udp->uh_dport;
3639 nk->port[0] = nk->port[1];
3640 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3641 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3642 nk->addr[pd->sidx].v4.s_addr, 0);
3644 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3645 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3646 nk->addr[pd->didx].v4.s_addr, 0);
3648 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3649 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3650 pd->hdr.icmp->icmp_cksum, sport,
3652 pd->hdr.icmp->icmp_id = nk->port[1];
3653 pd->sport = &pd->hdr.icmp->icmp_id;
3655 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3659 case IPPROTO_ICMPV6:
3660 nk->port[0] = nk->port[1];
3661 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3662 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3663 &nk->addr[pd->sidx], 0);
3665 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3666 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3667 &nk->addr[pd->didx], 0);
3676 &nk->addr[pd->sidx], AF_INET))
3677 pf_change_a(&saddr->v4.s_addr,
3679 nk->addr[pd->sidx].v4.s_addr, 0);
3682 &nk->addr[pd->didx], AF_INET))
3683 pf_change_a(&daddr->v4.s_addr,
3685 nk->addr[pd->didx].v4.s_addr, 0);
3691 &nk->addr[pd->sidx], AF_INET6))
3692 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3695 &nk->addr[pd->didx], AF_INET6))
3696 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3709 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3710 r = r->skip[PF_SKIP_IFP].ptr;
3711 else if (r->direction && r->direction != direction)
3712 r = r->skip[PF_SKIP_DIR].ptr;
3713 else if (r->af && r->af != af)
3714 r = r->skip[PF_SKIP_AF].ptr;
3715 else if (r->proto && r->proto != pd->proto)
3716 r = r->skip[PF_SKIP_PROTO].ptr;
3717 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3719 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3720 /* tcp/udp only. port_op always 0 in other cases */
3721 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3722 r->src.port[0], r->src.port[1], sport))
3723 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3724 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3726 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3727 /* tcp/udp only. port_op always 0 in other cases */
3728 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3729 r->dst.port[0], r->dst.port[1], dport))
3730 r = r->skip[PF_SKIP_DST_PORT].ptr;
3731 /* icmp only. type always 0 in other cases */
3732 else if (r->type && r->type != icmptype + 1)
3733 r = TAILQ_NEXT(r, entries);
3734 /* icmp only. type always 0 in other cases */
3735 else if (r->code && r->code != icmpcode + 1)
3736 r = TAILQ_NEXT(r, entries);
3737 else if (r->tos && !(r->tos == pd->tos))
3738 r = TAILQ_NEXT(r, entries);
3739 else if (r->rule_flag & PFRULE_FRAGMENT)
3740 r = TAILQ_NEXT(r, entries);
3741 else if (pd->proto == IPPROTO_TCP &&
3742 (r->flagset & th->th_flags) != r->flags)
3743 r = TAILQ_NEXT(r, entries);
3744 /* tcp/udp only. uid.op always 0 in other cases */
3745 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3746 pf_socket_lookup(direction, pd), 1)) &&
3747 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3749 r = TAILQ_NEXT(r, entries);
3750 /* tcp/udp only. gid.op always 0 in other cases */
3751 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3752 pf_socket_lookup(direction, pd), 1)) &&
3753 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3755 r = TAILQ_NEXT(r, entries);
3757 r->prob <= karc4random())
3758 r = TAILQ_NEXT(r, entries);
3759 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3760 r = TAILQ_NEXT(r, entries);
3761 else if (r->os_fingerprint != PF_OSFP_ANY &&
3762 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3763 pf_osfp_fingerprint(pd, m, off, th),
3764 r->os_fingerprint)))
3765 r = TAILQ_NEXT(r, entries);
3769 if (r->rtableid >= 0)
3770 rtableid = r->rtableid;
3771 if (r->anchor == NULL) {
3778 r = TAILQ_NEXT(r, entries);
3780 pf_step_into_anchor(&asd, &ruleset,
3781 PF_RULESET_FILTER, &r, &a, &match);
3783 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3784 PF_RULESET_FILTER, &r, &a, &match))
3791 REASON_SET(&reason, PFRES_MATCH);
3793 if (r->log || (nr != NULL && nr->log)) {
3795 m_copyback(m, off, hdrlen, pd->hdr.any);
3796 PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3800 if ((r->action == PF_DROP) &&
3801 ((r->rule_flag & PFRULE_RETURNRST) ||
3802 (r->rule_flag & PFRULE_RETURNICMP) ||
3803 (r->rule_flag & PFRULE_RETURN))) {
3804 /* undo NAT changes, if they have taken place */
3806 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3807 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3809 *pd->sport = sk->port[pd->sidx];
3811 *pd->dport = sk->port[pd->didx];
3813 *pd->proto_sum = bproto_sum;
3815 *pd->ip_sum = bip_sum;
3816 m_copyback(m, off, hdrlen, pd->hdr.any);
3818 if (pd->proto == IPPROTO_TCP &&
3819 ((r->rule_flag & PFRULE_RETURNRST) ||
3820 (r->rule_flag & PFRULE_RETURN)) &&
3821 !(th->th_flags & TH_RST)) {
3822 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3830 h4 = mtod(m, struct ip *);
3831 len = h4->ip_len - off;
3835 h6 = mtod(m, struct ip6_hdr *);
3836 len = h6->ip6_plen - (off - sizeof(*h6));
3841 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3842 REASON_SET(&reason, PFRES_PROTCKSUM);
3844 if (th->th_flags & TH_SYN)
3846 if (th->th_flags & TH_FIN)
3848 pf_send_tcp(r, af, pd->dst,
3849 pd->src, th->th_dport, th->th_sport,
3850 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3851 r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
3853 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3855 pf_send_icmp(m, r->return_icmp >> 8,
3856 r->return_icmp & 255, af, r);
3857 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3859 pf_send_icmp(m, r->return_icmp6 >> 8,
3860 r->return_icmp6 & 255, af, r);
3863 if (r->action == PF_DROP)
3866 if (pf_tag_packet(m, tag, rtableid)) {
3867 REASON_SET(&reason, PFRES_MEMORY);
3871 if (!state_icmp && (r->keep_state || nr != NULL ||
3872 (pd->flags & PFDESC_TCP_NORM))) {
3874 action = pf_create_state(r, nr, a, pd, nsn, skw, sks, nk, sk, m,
3875 off, sport, dport, &rewrite, kif, sm, tag, bproto_sum,
3877 if (action != PF_PASS)
3881 /* copy back packet headers if we performed NAT operations */
3883 m_copyback(m, off, hdrlen, pd->hdr.any);
3889 kfree(sk, M_PFSTATEKEYPL);
3891 kfree(nk, M_PFSTATEKEYPL);
3896 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3897 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *skw,
3898 struct pf_state_key *sks, struct pf_state_key *nk, struct pf_state_key *sk,
3899 struct mbuf *m, int off, u_int16_t sport, u_int16_t dport, int *rewrite,
3900 struct pfi_kif *kif, struct pf_state **sm, int tag, u_int16_t bproto_sum,
3901 u_int16_t bip_sum, int hdrlen)
3903 struct pf_state *s = NULL;
3904 struct pf_src_node *sn = NULL;
3905 struct tcphdr *th = pd->hdr.tcp;
3906 u_int16_t mss = tcp_mssdflt;
3908 int cpu = mycpu->gd_cpuid;
3910 /* check maximums */
3911 if (r->max_states && (r->states_cur >= r->max_states)) {
3912 pf_status.lcounters[LCNT_STATES]++;
3913 REASON_SET(&reason, PFRES_MAXSTATES);
3916 /* src node for filter rule */
3917 if ((r->rule_flag & PFRULE_SRCTRACK ||
3918 r->rpool.opts & PF_POOL_STICKYADDR) &&
3919 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3920 REASON_SET(&reason, PFRES_SRCLIMIT);
3923 /* src node for translation rule */
3924 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3925 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3926 REASON_SET(&reason, PFRES_SRCLIMIT);
3929 s = kmalloc(sizeof(struct pf_state), M_PFSTATEPL, M_NOWAIT|M_ZERO);
3931 REASON_SET(&reason, PFRES_MEMORY);
3934 lockinit(&s->lk, "pfstlk", 0, 0);
3935 s->id = 0; /* XXX Do we really need that? not in OpenBSD */
3938 s->nat_rule.ptr = nr;
3940 s->state_flags = PFSTATE_CREATEINPROG;
3941 STATE_INC_COUNTERS(s);
3943 s->state_flags |= PFSTATE_ALLOWOPTS;
3944 if (r->rule_flag & PFRULE_STATESLOPPY)
3945 s->state_flags |= PFSTATE_SLOPPY;
3946 if (pd->not_cpu_localized)
3947 s->state_flags |= PFSTATE_STACK_GLOBAL;
3949 s->log = r->log & PF_LOG_ALL;
3951 s->log |= nr->log & PF_LOG_ALL;
3952 switch (pd->proto) {
3954 s->src.seqlo = ntohl(th->th_seq);
3955 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3956 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3957 r->keep_state == PF_STATE_MODULATE) {
3958 /* Generate sequence number modulator */
3959 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3962 pf_change_a(&th->th_seq, &th->th_sum,
3963 htonl(s->src.seqlo + s->src.seqdiff), 0);
3967 if (th->th_flags & TH_SYN) {
3969 s->src.wscale = pf_get_wscale(m, off,
3970 th->th_off, pd->af);
3972 s->src.max_win = MAX(ntohs(th->th_win), 1);
3973 if (s->src.wscale & PF_WSCALE_MASK) {
3974 /* Remove scale factor from initial window */
3975 int win = s->src.max_win;
3976 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3977 s->src.max_win = (win - 1) >>
3978 (s->src.wscale & PF_WSCALE_MASK);
3980 if (th->th_flags & TH_FIN)
3984 s->src.state = TCPS_SYN_SENT;
3985 s->dst.state = TCPS_CLOSED;
3986 s->timeout = PFTM_TCP_FIRST_PACKET;
3989 s->src.state = PFUDPS_SINGLE;
3990 s->dst.state = PFUDPS_NO_TRAFFIC;
3991 s->timeout = PFTM_UDP_FIRST_PACKET;
3995 case IPPROTO_ICMPV6:
3997 s->timeout = PFTM_ICMP_FIRST_PACKET;
4000 s->src.state = PFOTHERS_SINGLE;
4001 s->dst.state = PFOTHERS_NO_TRAFFIC;
4002 s->timeout = PFTM_OTHER_FIRST_PACKET;
4005 s->creation = time_second;
4006 s->expire = time_second;
4010 s->src_node->states++;
4013 /* XXX We only modify one side for now. */
4014 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
4015 s->nat_src_node = nsn;
4016 s->nat_src_node->states++;
4018 if (pd->proto == IPPROTO_TCP) {
4019 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
4020 off, pd, th, &s->src, &s->dst)) {
4021 REASON_SET(&reason, PFRES_MEMORY);
4022 pf_src_tree_remove_state(s);
4023 STATE_DEC_COUNTERS(s);
4024 kfree(s, M_PFSTATEPL);
4027 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
4028 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
4029 &s->src, &s->dst, rewrite)) {
4030 /* This really shouldn't happen!!! */
4031 DPFPRINTF(PF_DEBUG_URGENT,
4032 ("pf_normalize_tcp_stateful failed on first pkt"));
4033 pf_normalize_tcp_cleanup(s);
4034 pf_src_tree_remove_state(s);
4035 STATE_DEC_COUNTERS(s);
4036 kfree(s, M_PFSTATEPL);
4040 s->direction = pd->dir;
4042 if (sk == NULL && pf_state_key_setup(pd, nr, &skw, &sks, &sk, &nk,
4043 pd->src, pd->dst, sport, dport)) {
4044 REASON_SET(&reason, PFRES_MEMORY);
4048 if (pf_state_insert(BOUND_IFACE(r, kif), skw, sks, s)) {
4049 if (pd->proto == IPPROTO_TCP)
4050 pf_normalize_tcp_cleanup(s);
4051 REASON_SET(&reason, PFRES_STATEINS);
4052 pf_src_tree_remove_state(s);
4053 STATE_DEC_COUNTERS(s);
4054 kfree(s, M_PFSTATEPL);
4059 pf_set_rt_ifp(s, pd->src); /* needs s->state_key set */
4064 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
4065 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
4066 s->src.state = PF_TCPS_PROXY_SRC;
4067 /* undo NAT changes, if they have taken place */
4069 struct pf_state_key *skt = s->key[PF_SK_WIRE];
4070 if (pd->dir == PF_OUT)
4071 skt = s->key[PF_SK_STACK];
4072 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
4073 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
4075 *pd->sport = skt->port[pd->sidx];
4077 *pd->dport = skt->port[pd->didx];
4079 *pd->proto_sum = bproto_sum;
4081 *pd->ip_sum = bip_sum;
4082 m_copyback(m, off, hdrlen, pd->hdr.any);
4084 s->src.seqhi = htonl(karc4random());
4085 /* Find mss option */
4086 mss = pf_get_mss(m, off, th->th_off, pd->af);
4087 mss = pf_calc_mss(pd->src, pd->af, mss);
4088 mss = pf_calc_mss(pd->dst, pd->af, mss);
4090 s->state_flags &= ~PFSTATE_CREATEINPROG;
4091 pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
4092 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
4093 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
4094 REASON_SET(&reason, PFRES_SYNPROXY);
4095 return (PF_SYNPROXY_DROP);
4098 s->state_flags &= ~PFSTATE_CREATEINPROG;
4103 kfree(sk, M_PFSTATEKEYPL);
4105 kfree(nk, M_PFSTATEKEYPL);
4107 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
4108 RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], sn);
4109 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
4110 atomic_add_int(&pf_status.src_nodes, -1);
4111 kfree(sn, M_PFSRCTREEPL);
4113 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
4114 RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], nsn);
4115 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
4116 atomic_add_int(&pf_status.src_nodes, -1);
4117 kfree(nsn, M_PFSRCTREEPL);
4120 pf_src_tree_remove_state(s);
4121 STATE_DEC_COUNTERS(s);
4122 kfree(s, M_PFSTATEPL);
4129 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
4130 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
4131 struct pf_ruleset **rsm)
4133 struct pf_rule *r, *a = NULL;
4134 struct pf_ruleset *ruleset = NULL;
4135 sa_family_t af = pd->af;
4141 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4144 if (pfi_kif_match(r->kif, kif) == r->ifnot)
4145 r = r->skip[PF_SKIP_IFP].ptr;
4146 else if (r->direction && r->direction != direction)
4147 r = r->skip[PF_SKIP_DIR].ptr;
4148 else if (r->af && r->af != af)
4149 r = r->skip[PF_SKIP_AF].ptr;
4150 else if (r->proto && r->proto != pd->proto)
4151 r = r->skip[PF_SKIP_PROTO].ptr;
4152 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
4154 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4155 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
4157 r = r->skip[PF_SKIP_DST_ADDR].ptr;
4158 else if (r->tos && !(r->tos == pd->tos))
4159 r = TAILQ_NEXT(r, entries);
4160 else if (r->os_fingerprint != PF_OSFP_ANY)
4161 r = TAILQ_NEXT(r, entries);
4162 else if (pd->proto == IPPROTO_UDP &&
4163 (r->src.port_op || r->dst.port_op))
4164 r = TAILQ_NEXT(r, entries);
4165 else if (pd->proto == IPPROTO_TCP &&
4166 (r->src.port_op || r->dst.port_op || r->flagset))
4167 r = TAILQ_NEXT(r, entries);
4168 else if ((pd->proto == IPPROTO_ICMP ||
4169 pd->proto == IPPROTO_ICMPV6) &&
4170 (r->type || r->code))
4171 r = TAILQ_NEXT(r, entries);
4172 else if (r->prob && r->prob <= karc4random())
4173 r = TAILQ_NEXT(r, entries);
4174 else if (r->match_tag && !pf_match_tag(m, r, &tag))
4175 r = TAILQ_NEXT(r, entries);
4177 if (r->anchor == NULL) {
4184 r = TAILQ_NEXT(r, entries);
4186 pf_step_into_anchor(&asd, &ruleset,
4187 PF_RULESET_FILTER, &r, &a, &match);
4189 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
4190 PF_RULESET_FILTER, &r, &a, &match))
4197 REASON_SET(&reason, PFRES_MATCH);
4200 PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
4203 if (r->action != PF_PASS)
4206 if (pf_tag_packet(m, tag, -1)) {
4207 REASON_SET(&reason, PFRES_MEMORY);
4215 * Called with state locked
4218 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
4219 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
4220 struct pf_pdesc *pd, u_short *reason, int *copyback)
4222 struct tcphdr *th = pd->hdr.tcp;
4223 u_int16_t win = ntohs(th->th_win);
4224 u_int32_t ack, end, seq, orig_seq;
4228 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
4229 sws = src->wscale & PF_WSCALE_MASK;
4230 dws = dst->wscale & PF_WSCALE_MASK;
4235 * Sequence tracking algorithm from Guido van Rooij's paper:
4236 * http://www.madison-gurkha.com/publications/tcp_filtering/
4240 orig_seq = seq = ntohl(th->th_seq);
4241 if (src->seqlo == 0) {
4242 /* First packet from this end. Set its state */
4244 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
4245 src->scrub == NULL) {
4246 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
4247 REASON_SET(reason, PFRES_MEMORY);
4252 /* Deferred generation of sequence number modulator */
4253 if (dst->seqdiff && !src->seqdiff) {
4254 /* use random iss for the TCP server */
4255 while ((src->seqdiff = karc4random() - seq) == 0)
4257 ack = ntohl(th->th_ack) - dst->seqdiff;
4258 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
4260 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
4263 ack = ntohl(th->th_ack);
4266 end = seq + pd->p_len;
4267 if (th->th_flags & TH_SYN) {
4269 (*state)->sync_flags |= PFSTATE_GOT_SYN2;
4270 if (dst->wscale & PF_WSCALE_FLAG) {
4271 src->wscale = pf_get_wscale(m, off, th->th_off,
4273 if (src->wscale & PF_WSCALE_FLAG) {
4274 /* Remove scale factor from initial
4276 sws = src->wscale & PF_WSCALE_MASK;
4277 win = ((u_int32_t)win + (1 << sws) - 1)
4279 dws = dst->wscale & PF_WSCALE_MASK;
4281 /* fixup other window */
4282 dst->max_win <<= dst->wscale &
4284 /* in case of a retrans SYN|ACK */
4289 if (th->th_flags & TH_FIN)
4293 if (src->state < TCPS_SYN_SENT)
4294 src->state = TCPS_SYN_SENT;
4297 * May need to slide the window (seqhi may have been set by
4298 * the crappy stack check or if we picked up the connection
4299 * after establishment)
4301 if (src->seqhi == 1 ||
4302 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4303 src->seqhi = end + MAX(1, dst->max_win << dws);
4304 if (win > src->max_win)
4308 ack = ntohl(th->th_ack) - dst->seqdiff;
4310 /* Modulate sequence numbers */
4311 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
4313 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
4316 end = seq + pd->p_len;
4317 if (th->th_flags & TH_SYN)
4319 if (th->th_flags & TH_FIN)
4323 if ((th->th_flags & TH_ACK) == 0) {
4324 /* Let it pass through the ack skew check */
4326 } else if ((ack == 0 &&
4327 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4328 /* broken tcp stacks do not set ack */
4329 (dst->state < TCPS_SYN_SENT)) {
4331 * Many stacks (ours included) will set the ACK number in an
4332 * FIN|ACK if the SYN times out -- no sequence to ACK.
4338 /* Ease sequencing restrictions on no data packets */
4343 ackskew = dst->seqlo - ack;
4347 * Need to demodulate the sequence numbers in any TCP SACK options
4348 * (Selective ACK). We could optionally validate the SACK values
4349 * against the current ACK window, either forwards or backwards, but
4350 * I'm not confident that SACK has been implemented properly
4351 * everywhere. It wouldn't surprise me if several stacks accidently
4352 * SACK too far backwards of previously ACKed data. There really aren't
4353 * any security implications of bad SACKing unless the target stack
4354 * doesn't validate the option length correctly. Someone trying to
4355 * spoof into a TCP connection won't bother blindly sending SACK
4358 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4359 if (pf_modulate_sack(m, off, pd, th, dst))
4364 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4365 if (SEQ_GEQ(src->seqhi, end) &&
4366 /* Last octet inside other's window space */
4367 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4368 /* Retrans: not more than one window back */
4369 (ackskew >= -MAXACKWINDOW) &&
4370 /* Acking not more than one reassembled fragment backwards */
4371 (ackskew <= (MAXACKWINDOW << sws)) &&
4372 /* Acking not more than one window forward */
4373 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4374 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4375 (pd->flags & PFDESC_IP_REAS) == 0)) {
4376 /* Require an exact/+1 sequence match on resets when possible */
4378 if (dst->scrub || src->scrub) {
4379 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4380 *state, src, dst, copyback))
4384 /* update max window */
4385 if (src->max_win < win)
4387 /* synchronize sequencing */
4388 if (SEQ_GT(end, src->seqlo))
4390 /* slide the window of what the other end can send */
4391 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4392 dst->seqhi = ack + MAX((win << sws), 1);
4396 if (th->th_flags & TH_SYN)
4397 if (src->state < TCPS_SYN_SENT)
4398 src->state = TCPS_SYN_SENT;
4399 if (th->th_flags & TH_FIN)
4400 if (src->state < TCPS_CLOSING)
4401 src->state = TCPS_CLOSING;
4402 if (th->th_flags & TH_ACK) {
4403 if (dst->state == TCPS_SYN_SENT) {
4404 dst->state = TCPS_ESTABLISHED;
4405 if (src->state == TCPS_ESTABLISHED &&
4406 (*state)->src_node != NULL &&
4407 pf_src_connlimit(*state)) {
4408 REASON_SET(reason, PFRES_SRCLIMIT);
4411 } else if (dst->state == TCPS_CLOSING)
4412 dst->state = TCPS_FIN_WAIT_2;
4414 if (th->th_flags & TH_RST)
4415 src->state = dst->state = TCPS_TIME_WAIT;
4417 /* update expire time */
4418 (*state)->expire = time_second;
4419 if (src->state >= TCPS_FIN_WAIT_2 &&
4420 dst->state >= TCPS_FIN_WAIT_2)
4421 (*state)->timeout = PFTM_TCP_CLOSED;
4422 else if (src->state >= TCPS_CLOSING &&
4423 dst->state >= TCPS_CLOSING)
4424 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4425 else if (src->state < TCPS_ESTABLISHED ||
4426 dst->state < TCPS_ESTABLISHED)
4427 (*state)->timeout = PFTM_TCP_OPENING;
4428 else if (src->state >= TCPS_CLOSING ||
4429 dst->state >= TCPS_CLOSING)
4430 (*state)->timeout = PFTM_TCP_CLOSING;
4432 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4434 /* Fall through to PASS packet */
4436 } else if ((dst->state < TCPS_SYN_SENT ||
4437 dst->state >= TCPS_FIN_WAIT_2 ||
4438 src->state >= TCPS_FIN_WAIT_2) &&
4439 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4440 /* Within a window forward of the originating packet */
4441 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4442 /* Within a window backward of the originating packet */
4445 * This currently handles three situations:
4446 * 1) Stupid stacks will shotgun SYNs before their peer
4448 * 2) When PF catches an already established stream (the
4449 * firewall rebooted, the state table was flushed, routes
4451 * 3) Packets get funky immediately after the connection
4452 * closes (this should catch Solaris spurious ACK|FINs
4453 * that web servers like to spew after a close)
4455 * This must be a little more careful than the above code
4456 * since packet floods will also be caught here. We don't
4457 * update the TTL here to mitigate the damage of a packet
4458 * flood and so the same code can handle awkward establishment
4459 * and a loosened connection close.
4460 * In the establishment case, a correct peer response will
4461 * validate the connection, go through the normal state code
4462 * and keep updating the state TTL.
4465 if (pf_status.debug >= PF_DEBUG_MISC) {
4466 kprintf("pf: loose state match: ");
4467 pf_print_state(*state);
4468 pf_print_flags(th->th_flags);
4469 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4470 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack, pd->p_len,
4471 ackskew, (unsigned long long)(*state)->packets[0],
4472 (unsigned long long)(*state)->packets[1],
4473 pd->dir == PF_IN ? "in" : "out",
4474 pd->dir == (*state)->direction ? "fwd" : "rev");
4477 if (dst->scrub || src->scrub) {
4478 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4479 *state, src, dst, copyback))
4483 /* update max window */
4484 if (src->max_win < win)
4486 /* synchronize sequencing */
4487 if (SEQ_GT(end, src->seqlo))
4489 /* slide the window of what the other end can send */
4490 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4491 dst->seqhi = ack + MAX((win << sws), 1);
4494 * Cannot set dst->seqhi here since this could be a shotgunned
4495 * SYN and not an already established connection.
4498 if (th->th_flags & TH_FIN)
4499 if (src->state < TCPS_CLOSING)
4500 src->state = TCPS_CLOSING;
4501 if (th->th_flags & TH_RST)
4502 src->state = dst->state = TCPS_TIME_WAIT;
4504 /* Fall through to PASS packet */
4506 } else if ((*state)->pickup_mode == PF_PICKUPS_HASHONLY ||
4507 ((*state)->pickup_mode == PF_PICKUPS_ENABLED &&
4508 ((*state)->sync_flags & PFSTATE_GOT_SYN_MASK) !=
4509 PFSTATE_GOT_SYN_MASK)) {
4511 * If pickup mode is hash only, do not fail on sequence checks.
4513 * If pickup mode is enabled and we did not see the SYN in
4514 * both direction, do not fail on sequence checks because
4515 * we do not have complete information on window scale.
4517 * Adjust expiration and fall through to PASS packet.
4518 * XXX Add a FIN check to reduce timeout?
4520 (*state)->expire = time_second;
4523 * Failure processing
4525 if ((*state)->dst.state == TCPS_SYN_SENT &&
4526 (*state)->src.state == TCPS_SYN_SENT) {
4527 /* Send RST for state mismatches during handshake */
4528 if (!(th->th_flags & TH_RST))
4529 pf_send_tcp((*state)->rule.ptr, pd->af,
4530 pd->dst, pd->src, th->th_dport,
4531 th->th_sport, ntohl(th->th_ack), 0,
4533 (*state)->rule.ptr->return_ttl, 1, 0,
4534 pd->eh, kif->pfik_ifp);
4538 } else if (pf_status.debug >= PF_DEBUG_MISC) {
4539 kprintf("pf: BAD state: ");
4540 pf_print_state(*state);
4541 pf_print_flags(th->th_flags);
4542 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4543 "pkts=%llu:%llu dir=%s,%s\n",
4544 seq, orig_seq, ack, pd->p_len, ackskew,
4545 (unsigned long long)(*state)->packets[0],
4546 (unsigned long long)(*state)->packets[1],
4547 pd->dir == PF_IN ? "in" : "out",
4548 pd->dir == (*state)->direction ? "fwd" : "rev");
4549 kprintf("pf: State failure on: %c %c %c %c | %c %c\n",
4550 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4551 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4553 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4554 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4555 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4556 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4558 REASON_SET(reason, PFRES_BADSTATE);
4566 * Called with state locked
4569 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4570 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4572 struct tcphdr *th = pd->hdr.tcp;
4574 if (th->th_flags & TH_SYN)
4575 if (src->state < TCPS_SYN_SENT)
4576 src->state = TCPS_SYN_SENT;
4577 if (th->th_flags & TH_FIN)
4578 if (src->state < TCPS_CLOSING)
4579 src->state = TCPS_CLOSING;
4580 if (th->th_flags & TH_ACK) {
4581 if (dst->state == TCPS_SYN_SENT) {
4582 dst->state = TCPS_ESTABLISHED;
4583 if (src->state == TCPS_ESTABLISHED &&
4584 (*state)->src_node != NULL &&
4585 pf_src_connlimit(*state)) {
4586 REASON_SET(reason, PFRES_SRCLIMIT);
4589 } else if (dst->state == TCPS_CLOSING) {
4590 dst->state = TCPS_FIN_WAIT_2;
4591 } else if (src->state == TCPS_SYN_SENT &&
4592 dst->state < TCPS_SYN_SENT) {
4594 * Handle a special sloppy case where we only see one
4595 * half of the connection. If there is a ACK after
4596 * the initial SYN without ever seeing a packet from
4597 * the destination, set the connection to established.
4599 dst->state = src->state = TCPS_ESTABLISHED;
4600 if ((*state)->src_node != NULL &&
4601 pf_src_connlimit(*state)) {
4602 REASON_SET(reason, PFRES_SRCLIMIT);
4605 } else if (src->state == TCPS_CLOSING &&
4606 dst->state == TCPS_ESTABLISHED &&
4609 * Handle the closing of half connections where we
4610 * don't see the full bidirectional FIN/ACK+ACK
4613 dst->state = TCPS_CLOSING;
4616 if (th->th_flags & TH_RST)
4617 src->state = dst->state = TCPS_TIME_WAIT;
4619 /* update expire time */
4620 (*state)->expire = time_second;
4621 if (src->state >= TCPS_FIN_WAIT_2 &&
4622 dst->state >= TCPS_FIN_WAIT_2)
4623 (*state)->timeout = PFTM_TCP_CLOSED;
4624 else if (src->state >= TCPS_CLOSING &&
4625 dst->state >= TCPS_CLOSING)
4626 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4627 else if (src->state < TCPS_ESTABLISHED ||
4628 dst->state < TCPS_ESTABLISHED)
4629 (*state)->timeout = PFTM_TCP_OPENING;
4630 else if (src->state >= TCPS_CLOSING ||
4631 dst->state >= TCPS_CLOSING)
4632 (*state)->timeout = PFTM_TCP_CLOSING;
4634 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4640 * Test TCP connection state. Caller must hold the state locked.
4643 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4644 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4647 struct pf_state_key_cmp key;
4648 struct tcphdr *th = pd->hdr.tcp;
4651 struct pf_state_peer *src, *dst;
4652 struct pf_state_key *sk;
4655 key.proto = IPPROTO_TCP;
4656 if (direction == PF_IN) { /* wire side, straight */
4657 PF_ACPY(&key.addr[0], pd->src, key.af);
4658 PF_ACPY(&key.addr[1], pd->dst, key.af);
4659 key.port[0] = th->th_sport;
4660 key.port[1] = th->th_dport;
4661 } else { /* stack side, reverse */
4662 PF_ACPY(&key.addr[1], pd->src, key.af);
4663 PF_ACPY(&key.addr[0], pd->dst, key.af);
4664 key.port[1] = th->th_sport;
4665 key.port[0] = th->th_dport;
4668 STATE_LOOKUP(kif, &key, direction, *state, m);
4669 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
4671 if (direction == (*state)->direction) {
4672 src = &(*state)->src;
4673 dst = &(*state)->dst;
4675 src = &(*state)->dst;
4676 dst = &(*state)->src;
4679 sk = (*state)->key[pd->didx];
4681 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4682 if (direction != (*state)->direction) {
4683 REASON_SET(reason, PFRES_SYNPROXY);
4684 FAIL (PF_SYNPROXY_DROP);
4686 if (th->th_flags & TH_SYN) {
4687 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4688 REASON_SET(reason, PFRES_SYNPROXY);
4691 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4692 pd->src, th->th_dport, th->th_sport,
4693 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4694 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
4696 REASON_SET(reason, PFRES_SYNPROXY);
4697 FAIL (PF_SYNPROXY_DROP);
4698 } else if (!(th->th_flags & TH_ACK) ||
4699 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4700 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4701 REASON_SET(reason, PFRES_SYNPROXY);
4703 } else if ((*state)->src_node != NULL &&
4704 pf_src_connlimit(*state)) {
4705 REASON_SET(reason, PFRES_SRCLIMIT);
4708 (*state)->src.state = PF_TCPS_PROXY_DST;
4710 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4711 if (direction == (*state)->direction) {
4712 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4713 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4714 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4715 REASON_SET(reason, PFRES_SYNPROXY);
4718 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4719 if ((*state)->dst.seqhi == 1)
4720 (*state)->dst.seqhi = htonl(karc4random());
4721 pf_send_tcp((*state)->rule.ptr, pd->af,
4722 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4723 sk->port[pd->sidx], sk->port[pd->didx],
4724 (*state)->dst.seqhi, 0, TH_SYN, 0,
4725 (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
4726 REASON_SET(reason, PFRES_SYNPROXY);
4727 FAIL (PF_SYNPROXY_DROP);
4728 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4730 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4731 REASON_SET(reason, PFRES_SYNPROXY);
4734 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4735 (*state)->dst.seqlo = ntohl(th->th_seq);
4736 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4737 pd->src, th->th_dport, th->th_sport,
4738 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4739 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4740 (*state)->tag, NULL, NULL);
4741 pf_send_tcp((*state)->rule.ptr, pd->af,
4742 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4743 sk->port[pd->sidx], sk->port[pd->didx],
4744 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4745 TH_ACK, (*state)->dst.max_win, 0, 0, 1,
4747 (*state)->src.seqdiff = (*state)->dst.seqhi -
4748 (*state)->src.seqlo;
4749 (*state)->dst.seqdiff = (*state)->src.seqhi -
4750 (*state)->dst.seqlo;
4751 (*state)->src.seqhi = (*state)->src.seqlo +
4752 (*state)->dst.max_win;
4753 (*state)->dst.seqhi = (*state)->dst.seqlo +
4754 (*state)->src.max_win;
4755 (*state)->src.wscale = (*state)->dst.wscale = 0;
4756 (*state)->src.state = (*state)->dst.state =
4758 REASON_SET(reason, PFRES_SYNPROXY);
4759 FAIL (PF_SYNPROXY_DROP);
4764 * Check for connection (addr+port pair) reuse. We can't actually
4765 * unlink the state if we don't own it.
4767 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4768 dst->state >= TCPS_FIN_WAIT_2 &&
4769 src->state >= TCPS_FIN_WAIT_2) {
4770 if (pf_status.debug >= PF_DEBUG_MISC) {
4771 kprintf("pf: state reuse ");
4772 pf_print_state(*state);
4773 pf_print_flags(th->th_flags);
4776 /* XXX make sure it's the same direction ?? */
4777 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4778 if ((*state)->cpuid == mycpu->gd_cpuid) {
4779 pf_unlink_state(*state);
4782 (*state)->timeout = PFTM_PURGE;
4787 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4788 if (pf_tcp_track_sloppy(src, dst, state, pd,
4789 reason) == PF_DROP) {
4793 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd,
4794 reason, ©back) == PF_DROP) {
4799 /* translate source/destination address, if necessary */
4800 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4801 struct pf_state_key *nk = (*state)->key[pd->didx];
4803 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4804 nk->port[pd->sidx] != th->th_sport) {
4806 * The translated source address may be completely
4807 * unrelated to the saved link header, make sure
4808 * a bridge doesn't try to use it.
4810 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4811 m->m_flags &= ~M_HASH;
4812 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4813 &th->th_sum, &nk->addr[pd->sidx],
4814 nk->port[pd->sidx], 0, pd->af);
4817 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4818 nk->port[pd->didx] != th->th_dport) {
4820 * If we don't redispatch the packet will go into
4821 * the protocol stack on the wrong cpu for the
4822 * post-translated address.
4824 m->m_flags &= ~M_HASH;
4825 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4826 &th->th_sum, &nk->addr[pd->didx],
4827 nk->port[pd->didx], 0, pd->af);
4832 /* Copyback sequence modulation or stateful scrub changes if needed */
4834 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4836 pfsync_update_state(*state);
4840 lockmgr(&(*state)->lk, LK_RELEASE);
4845 * Test UDP connection state. Caller must hold the state locked.
4848 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4849 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4851 struct pf_state_peer *src, *dst;
4852 struct pf_state_key_cmp key;
4853 struct udphdr *uh = pd->hdr.udp;
4856 key.proto = IPPROTO_UDP;
4857 if (direction == PF_IN) { /* wire side, straight */
4858 PF_ACPY(&key.addr[0], pd->src, key.af);
4859 PF_ACPY(&key.addr[1], pd->dst, key.af);
4860 key.port[0] = uh->uh_sport;
4861 key.port[1] = uh->uh_dport;
4862 } else { /* stack side, reverse */
4863 PF_ACPY(&key.addr[1], pd->src, key.af);
4864 PF_ACPY(&key.addr[0], pd->dst, key.af);
4865 key.port[1] = uh->uh_sport;
4866 key.port[0] = uh->uh_dport;
4869 STATE_LOOKUP(kif, &key, direction, *state, m);
4870 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
4872 if (direction == (*state)->direction) {
4873 src = &(*state)->src;
4874 dst = &(*state)->dst;
4876 src = &(*state)->dst;
4877 dst = &(*state)->src;
4881 if (src->state < PFUDPS_SINGLE)
4882 src->state = PFUDPS_SINGLE;
4883 if (dst->state == PFUDPS_SINGLE)
4884 dst->state = PFUDPS_MULTIPLE;
4886 /* update expire time */
4887 (*state)->expire = time_second;
4888 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4889 (*state)->timeout = PFTM_UDP_MULTIPLE;
4891 (*state)->timeout = PFTM_UDP_SINGLE;
4893 /* translate source/destination address, if necessary */
4894 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4895 struct pf_state_key *nk = (*state)->key[pd->didx];
4897 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4898 nk->port[pd->sidx] != uh->uh_sport) {
4900 * The translated source address may be completely
4901 * unrelated to the saved link header, make sure
4902 * a bridge doesn't try to use it.
4904 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4905 m->m_flags &= ~M_HASH;
4906 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4907 &uh->uh_sum, &nk->addr[pd->sidx],
4908 nk->port[pd->sidx], 1, pd->af);
4911 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4912 nk->port[pd->didx] != uh->uh_dport) {
4914 * If we don't redispatch the packet will go into
4915 * the protocol stack on the wrong cpu for the
4916 * post-translated address.
4918 m->m_flags &= ~M_HASH;
4919 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4920 &uh->uh_sum, &nk->addr[pd->didx],
4921 nk->port[pd->didx], 1, pd->af);
4923 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4926 pfsync_update_state(*state);
4927 lockmgr(&(*state)->lk, LK_RELEASE);
4932 * Test ICMP connection state. Caller must hold the state locked.
4935 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4936 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4939 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4940 u_int16_t icmpid = 0, *icmpsum;
4944 struct pf_state_key_cmp key;
4946 switch (pd->proto) {
4949 icmptype = pd->hdr.icmp->icmp_type;
4950 icmpid = pd->hdr.icmp->icmp_id;
4951 icmpsum = &pd->hdr.icmp->icmp_cksum;
4953 if (icmptype == ICMP_UNREACH ||
4954 icmptype == ICMP_SOURCEQUENCH ||
4955 icmptype == ICMP_REDIRECT ||
4956 icmptype == ICMP_TIMXCEED ||
4957 icmptype == ICMP_PARAMPROB)
4962 case IPPROTO_ICMPV6:
4963 icmptype = pd->hdr.icmp6->icmp6_type;
4964 icmpid = pd->hdr.icmp6->icmp6_id;
4965 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4967 if (icmptype == ICMP6_DST_UNREACH ||
4968 icmptype == ICMP6_PACKET_TOO_BIG ||
4969 icmptype == ICMP6_TIME_EXCEEDED ||
4970 icmptype == ICMP6_PARAM_PROB)
4979 * ICMP query/reply message not related to a TCP/UDP packet.
4980 * Search for an ICMP state.
4983 key.proto = pd->proto;
4984 key.port[0] = key.port[1] = icmpid;
4985 if (direction == PF_IN) { /* wire side, straight */
4986 PF_ACPY(&key.addr[0], pd->src, key.af);
4987 PF_ACPY(&key.addr[1], pd->dst, key.af);
4988 } else { /* stack side, reverse */
4989 PF_ACPY(&key.addr[1], pd->src, key.af);
4990 PF_ACPY(&key.addr[0], pd->dst, key.af);
4993 STATE_LOOKUP(kif, &key, direction, *state, m);
4994 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
4996 (*state)->expire = time_second;
4997 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4999 /* translate source/destination address, if necessary */
5000 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5001 struct pf_state_key *nk = (*state)->key[pd->didx];
5006 if (PF_ANEQ(pd->src,
5007 &nk->addr[pd->sidx], AF_INET))
5008 pf_change_a(&saddr->v4.s_addr,
5010 nk->addr[pd->sidx].v4.s_addr, 0);
5012 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
5014 pf_change_a(&daddr->v4.s_addr,
5016 nk->addr[pd->didx].v4.s_addr, 0);
5019 pd->hdr.icmp->icmp_id) {
5020 pd->hdr.icmp->icmp_cksum =
5022 pd->hdr.icmp->icmp_cksum, icmpid,
5023 nk->port[pd->sidx], 0);
5024 pd->hdr.icmp->icmp_id =
5028 m_copyback(m, off, ICMP_MINLEN,
5029 (caddr_t)pd->hdr.icmp);
5034 if (PF_ANEQ(pd->src,
5035 &nk->addr[pd->sidx], AF_INET6))
5037 &pd->hdr.icmp6->icmp6_cksum,
5038 &nk->addr[pd->sidx], 0);
5040 if (PF_ANEQ(pd->dst,
5041 &nk->addr[pd->didx], AF_INET6))
5043 &pd->hdr.icmp6->icmp6_cksum,
5044 &nk->addr[pd->didx], 0);
5047 sizeof(struct icmp6_hdr),
5048 (caddr_t)pd->hdr.icmp6);
5055 * ICMP error message in response to a TCP/UDP packet.
5056 * Extract the inner TCP/UDP header and search for that state.
5059 struct pf_pdesc pd2;
5064 struct ip6_hdr h2_6;
5070 pd2.not_cpu_localized = 1;
5072 /* Payload packet is from the opposite direction. */
5073 pd2.sidx = (direction == PF_IN) ? 1 : 0;
5074 pd2.didx = (direction == PF_IN) ? 0 : 1;
5078 /* offset of h2 in mbuf chain */
5079 ipoff2 = off + ICMP_MINLEN;
5081 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
5082 NULL, reason, pd2.af)) {
5083 DPFPRINTF(PF_DEBUG_MISC,
5084 ("pf: ICMP error message too short "
5089 * ICMP error messages don't refer to non-first
5092 if (h2.ip_off & htons(IP_OFFMASK)) {
5093 REASON_SET(reason, PFRES_FRAG);
5097 /* offset of protocol header that follows h2 */
5098 off2 = ipoff2 + (h2.ip_hl << 2);
5100 pd2.proto = h2.ip_p;
5101 pd2.src = (struct pf_addr *)&h2.ip_src;
5102 pd2.dst = (struct pf_addr *)&h2.ip_dst;
5103 pd2.ip_sum = &h2.ip_sum;
5108 ipoff2 = off + sizeof(struct icmp6_hdr);
5110 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
5111 NULL, reason, pd2.af)) {
5112 DPFPRINTF(PF_DEBUG_MISC,
5113 ("pf: ICMP error message too short "
5117 pd2.proto = h2_6.ip6_nxt;
5118 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
5119 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
5121 off2 = ipoff2 + sizeof(h2_6);
5123 switch (pd2.proto) {
5124 case IPPROTO_FRAGMENT:
5126 * ICMPv6 error messages for
5127 * non-first fragments
5129 REASON_SET(reason, PFRES_FRAG);
5132 case IPPROTO_HOPOPTS:
5133 case IPPROTO_ROUTING:
5134 case IPPROTO_DSTOPTS: {
5135 /* get next header and header length */
5136 struct ip6_ext opt6;
5138 if (!pf_pull_hdr(m, off2, &opt6,
5139 sizeof(opt6), NULL, reason,
5141 DPFPRINTF(PF_DEBUG_MISC,
5142 ("pf: ICMPv6 short opt\n"));
5145 if (pd2.proto == IPPROTO_AH)
5146 off2 += (opt6.ip6e_len + 2) * 4;
5148 off2 += (opt6.ip6e_len + 1) * 8;
5149 pd2.proto = opt6.ip6e_nxt;
5150 /* goto the next header */
5157 } while (!terminal);
5161 DPFPRINTF(PF_DEBUG_MISC,
5162 ("pf: ICMP AF %d unknown (ip6)\n", pd->af));
5167 switch (pd2.proto) {
5171 struct pf_state_peer *src, *dst;
5176 * Only the first 8 bytes of the TCP header can be
5177 * expected. Don't access any TCP header fields after
5178 * th_seq, an ackskew test is not possible.
5180 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
5182 DPFPRINTF(PF_DEBUG_MISC,
5183 ("pf: ICMP error message too short "
5189 key.proto = IPPROTO_TCP;
5190 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5191 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5192 key.port[pd2.sidx] = th.th_sport;
5193 key.port[pd2.didx] = th.th_dport;
5195 STATE_LOOKUP(kif, &key, direction, *state, m);
5196 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5198 if (direction == (*state)->direction) {
5199 src = &(*state)->dst;
5200 dst = &(*state)->src;
5202 src = &(*state)->src;
5203 dst = &(*state)->dst;
5206 if (src->wscale && dst->wscale)
5207 dws = dst->wscale & PF_WSCALE_MASK;
5211 /* Demodulate sequence number */
5212 seq = ntohl(th.th_seq) - src->seqdiff;
5214 pf_change_a(&th.th_seq, icmpsum,
5219 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
5220 (!SEQ_GEQ(src->seqhi, seq) ||
5221 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
5222 if (pf_status.debug >= PF_DEBUG_MISC) {
5223 kprintf("pf: BAD ICMP %d:%d ",
5224 icmptype, pd->hdr.icmp->icmp_code);
5225 pf_print_host(pd->src, 0, pd->af);
5227 pf_print_host(pd->dst, 0, pd->af);
5228 kprintf(" state: ");
5229 pf_print_state(*state);
5230 kprintf(" seq=%u\n", seq);
5232 REASON_SET(reason, PFRES_BADSTATE);
5235 if (pf_status.debug >= PF_DEBUG_MISC) {
5236 kprintf("pf: OK ICMP %d:%d ",
5237 icmptype, pd->hdr.icmp->icmp_code);
5238 pf_print_host(pd->src, 0, pd->af);
5240 pf_print_host(pd->dst, 0, pd->af);
5241 kprintf(" state: ");
5242 pf_print_state(*state);
5243 kprintf(" seq=%u\n", seq);
5247 /* translate source/destination address, if necessary */
5248 if ((*state)->key[PF_SK_WIRE] !=
5249 (*state)->key[PF_SK_STACK]) {
5250 struct pf_state_key *nk =
5251 (*state)->key[pd->didx];
5253 if (PF_ANEQ(pd2.src,
5254 &nk->addr[pd2.sidx], pd2.af) ||
5255 nk->port[pd2.sidx] != th.th_sport)
5256 pf_change_icmp(pd2.src, &th.th_sport,
5257 daddr, &nk->addr[pd2.sidx],
5258 nk->port[pd2.sidx], NULL,
5259 pd2.ip_sum, icmpsum,
5260 pd->ip_sum, 0, pd2.af);
5262 if (PF_ANEQ(pd2.dst,
5263 &nk->addr[pd2.didx], pd2.af) ||
5264 nk->port[pd2.didx] != th.th_dport)
5265 pf_change_icmp(pd2.dst, &th.th_dport,
5266 NULL, /* XXX Inbound NAT? */
5267 &nk->addr[pd2.didx],
5268 nk->port[pd2.didx], NULL,
5269 pd2.ip_sum, icmpsum,
5270 pd->ip_sum, 0, pd2.af);
5278 m_copyback(m, off, ICMP_MINLEN,
5279 (caddr_t)pd->hdr.icmp);
5280 m_copyback(m, ipoff2, sizeof(h2),
5287 sizeof(struct icmp6_hdr),
5288 (caddr_t)pd->hdr.icmp6);
5289 m_copyback(m, ipoff2, sizeof(h2_6),
5294 m_copyback(m, off2, 8, (caddr_t)&th);
5301 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
5302 NULL, reason, pd2.af)) {
5303 DPFPRINTF(PF_DEBUG_MISC,
5304 ("pf: ICMP error message too short "
5310 key.proto = IPPROTO_UDP;
5311 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5312 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5313 key.port[pd2.sidx] = uh.uh_sport;
5314 key.port[pd2.didx] = uh.uh_dport;
5316 STATE_LOOKUP(kif, &key, direction, *state, m);
5317 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5319 /* translate source/destination address, if necessary */
5320 if ((*state)->key[PF_SK_WIRE] !=
5321 (*state)->key[PF_SK_STACK]) {
5322 struct pf_state_key *nk =
5323 (*state)->key[pd->didx];
5325 if (PF_ANEQ(pd2.src,
5326 &nk->addr[pd2.sidx], pd2.af) ||
5327 nk->port[pd2.sidx] != uh.uh_sport)
5328 pf_change_icmp(pd2.src, &uh.uh_sport,
5329 daddr, &nk->addr[pd2.sidx],
5330 nk->port[pd2.sidx], &uh.uh_sum,
5331 pd2.ip_sum, icmpsum,
5332 pd->ip_sum, 1, pd2.af);
5334 if (PF_ANEQ(pd2.dst,
5335 &nk->addr[pd2.didx], pd2.af) ||
5336 nk->port[pd2.didx] != uh.uh_dport)
5337 pf_change_icmp(pd2.dst, &uh.uh_dport,
5338 NULL, /* XXX Inbound NAT? */
5339 &nk->addr[pd2.didx],
5340 nk->port[pd2.didx], &uh.uh_sum,
5341 pd2.ip_sum, icmpsum,
5342 pd->ip_sum, 1, pd2.af);
5347 m_copyback(m, off, ICMP_MINLEN,
5348 (caddr_t)pd->hdr.icmp);
5349 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5355 sizeof(struct icmp6_hdr),
5356 (caddr_t)pd->hdr.icmp6);
5357 m_copyback(m, ipoff2, sizeof(h2_6),
5362 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5367 case IPPROTO_ICMP: {
5370 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5371 NULL, reason, pd2.af)) {
5372 DPFPRINTF(PF_DEBUG_MISC,
5373 ("pf: ICMP error message too short i"
5379 key.proto = IPPROTO_ICMP;
5380 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5381 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5382 key.port[0] = key.port[1] = iih.icmp_id;
5384 STATE_LOOKUP(kif, &key, direction, *state, m);
5385 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5387 /* translate source/destination address, if necessary */
5388 if ((*state)->key[PF_SK_WIRE] !=
5389 (*state)->key[PF_SK_STACK]) {
5390 struct pf_state_key *nk =
5391 (*state)->key[pd->didx];
5393 if (PF_ANEQ(pd2.src,
5394 &nk->addr[pd2.sidx], pd2.af) ||
5395 nk->port[pd2.sidx] != iih.icmp_id)
5396 pf_change_icmp(pd2.src, &iih.icmp_id,
5397 daddr, &nk->addr[pd2.sidx],
5398 nk->port[pd2.sidx], NULL,
5399 pd2.ip_sum, icmpsum,
5400 pd->ip_sum, 0, AF_INET);
5402 if (PF_ANEQ(pd2.dst,
5403 &nk->addr[pd2.didx], pd2.af) ||
5404 nk->port[pd2.didx] != iih.icmp_id)
5405 pf_change_icmp(pd2.dst, &iih.icmp_id,
5406 NULL, /* XXX Inbound NAT? */
5407 &nk->addr[pd2.didx],
5408 nk->port[pd2.didx], NULL,
5409 pd2.ip_sum, icmpsum,
5410 pd->ip_sum, 0, AF_INET);
5412 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5413 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5414 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5420 case IPPROTO_ICMPV6: {
5421 struct icmp6_hdr iih;
5423 if (!pf_pull_hdr(m, off2, &iih,
5424 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5425 DPFPRINTF(PF_DEBUG_MISC,
5426 ("pf: ICMP error message too short "
5432 key.proto = IPPROTO_ICMPV6;
5433 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5434 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5435 key.port[0] = key.port[1] = iih.icmp6_id;
5437 STATE_LOOKUP(kif, &key, direction, *state, m);
5438 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5440 /* translate source/destination address, if necessary */
5441 if ((*state)->key[PF_SK_WIRE] !=
5442 (*state)->key[PF_SK_STACK]) {
5443 struct pf_state_key *nk =
5444 (*state)->key[pd->didx];
5446 if (PF_ANEQ(pd2.src,
5447 &nk->addr[pd2.sidx], pd2.af) ||
5448 nk->port[pd2.sidx] != iih.icmp6_id)
5449 pf_change_icmp(pd2.src, &iih.icmp6_id,
5450 daddr, &nk->addr[pd2.sidx],
5451 nk->port[pd2.sidx], NULL,
5452 pd2.ip_sum, icmpsum,
5453 pd->ip_sum, 0, AF_INET6);
5455 if (PF_ANEQ(pd2.dst,
5456 &nk->addr[pd2.didx], pd2.af) ||
5457 nk->port[pd2.didx] != iih.icmp6_id)
5458 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5459 NULL, /* XXX Inbound NAT? */
5460 &nk->addr[pd2.didx],
5461 nk->port[pd2.didx], NULL,
5462 pd2.ip_sum, icmpsum,
5463 pd->ip_sum, 0, AF_INET6);
5465 m_copyback(m, off, sizeof(struct icmp6_hdr),
5466 (caddr_t)pd->hdr.icmp6);
5467 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5468 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5476 key.proto = pd2.proto;
5477 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5478 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5479 key.port[0] = key.port[1] = 0;
5481 STATE_LOOKUP(kif, &key, direction, *state, m);
5482 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5484 /* translate source/destination address, if necessary */
5485 if ((*state)->key[PF_SK_WIRE] !=
5486 (*state)->key[PF_SK_STACK]) {
5487 struct pf_state_key *nk =
5488 (*state)->key[pd->didx];
5490 if (PF_ANEQ(pd2.src,
5491 &nk->addr[pd2.sidx], pd2.af))
5492 pf_change_icmp(pd2.src, NULL, daddr,
5493 &nk->addr[pd2.sidx], 0, NULL,
5494 pd2.ip_sum, icmpsum,
5495 pd->ip_sum, 0, pd2.af);
5497 if (PF_ANEQ(pd2.dst,
5498 &nk->addr[pd2.didx], pd2.af))
5499 pf_change_icmp(pd2.src, NULL,
5500 NULL, /* XXX Inbound NAT? */
5501 &nk->addr[pd2.didx], 0, NULL,
5502 pd2.ip_sum, icmpsum,
5503 pd->ip_sum, 0, pd2.af);
5508 m_copyback(m, off, ICMP_MINLEN,
5509 (caddr_t)pd->hdr.icmp);
5510 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5516 sizeof(struct icmp6_hdr),
5517 (caddr_t)pd->hdr.icmp6);
5518 m_copyback(m, ipoff2, sizeof(h2_6),
5529 pfsync_update_state(*state);
5533 lockmgr(&(*state)->lk, LK_RELEASE);
5538 * Test other connection state. Caller must hold the state locked.
5541 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5542 struct mbuf *m, struct pf_pdesc *pd)
5544 struct pf_state_peer *src, *dst;
5545 struct pf_state_key_cmp key;
5548 key.proto = pd->proto;
5549 if (direction == PF_IN) {
5550 PF_ACPY(&key.addr[0], pd->src, key.af);
5551 PF_ACPY(&key.addr[1], pd->dst, key.af);
5552 key.port[0] = key.port[1] = 0;
5554 PF_ACPY(&key.addr[1], pd->src, key.af);
5555 PF_ACPY(&key.addr[0], pd->dst, key.af);
5556 key.port[1] = key.port[0] = 0;
5559 STATE_LOOKUP(kif, &key, direction, *state, m);
5560 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5562 if (direction == (*state)->direction) {
5563 src = &(*state)->src;
5564 dst = &(*state)->dst;
5566 src = &(*state)->dst;
5567 dst = &(*state)->src;
5571 if (src->state < PFOTHERS_SINGLE)
5572 src->state = PFOTHERS_SINGLE;
5573 if (dst->state == PFOTHERS_SINGLE)
5574 dst->state = PFOTHERS_MULTIPLE;
5576 /* update expire time */
5577 (*state)->expire = time_second;
5578 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5579 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5581 (*state)->timeout = PFTM_OTHER_SINGLE;
5583 /* translate source/destination address, if necessary */
5584 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5585 struct pf_state_key *nk = (*state)->key[pd->didx];
5594 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5595 pf_change_a(&pd->src->v4.s_addr,
5597 nk->addr[pd->sidx].v4.s_addr,
5601 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5602 pf_change_a(&pd->dst->v4.s_addr,
5604 nk->addr[pd->didx].v4.s_addr,
5611 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5612 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5614 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5615 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5620 pfsync_update_state(*state);
5621 lockmgr(&(*state)->lk, LK_RELEASE);
5626 * ipoff and off are measured from the start of the mbuf chain.
5627 * h must be at "ipoff" on the mbuf chain.
5630 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5631 u_short *actionp, u_short *reasonp, sa_family_t af)
5636 struct ip *h = mtod(m, struct ip *);
5637 u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;
5641 ACTION_SET(actionp, PF_PASS);
5643 ACTION_SET(actionp, PF_DROP);
5644 REASON_SET(reasonp, PFRES_FRAG);
5648 if (m->m_pkthdr.len < off + len ||
5649 h->ip_len < off + len) {
5650 ACTION_SET(actionp, PF_DROP);
5651 REASON_SET(reasonp, PFRES_SHORT);
5659 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5661 if (m->m_pkthdr.len < off + len ||
5662 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5663 (unsigned)(off + len)) {
5664 ACTION_SET(actionp, PF_DROP);
5665 REASON_SET(reasonp, PFRES_SHORT);
5672 m_copydata(m, off, len, p);
5677 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif)
5679 struct sockaddr_in *dst;
5683 struct sockaddr_in6 *dst6;
5684 struct route_in6 ro;
5688 struct radix_node *rn;
5693 bzero(&ro, sizeof(ro));
5696 dst = satosin(&ro.ro_dst);
5697 dst->sin_family = AF_INET;
5698 dst->sin_len = sizeof(*dst);
5699 dst->sin_addr = addr->v4;
5703 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5704 dst6->sin6_family = AF_INET6;
5705 dst6->sin6_len = sizeof(*dst6);
5706 dst6->sin6_addr = addr->v6;
5713 /* Skip checks for ipsec interfaces */
5714 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5717 rtalloc_ign((struct route *)&ro, 0);
5719 if (ro.ro_rt != NULL) {
5720 /* No interface given, this is a no-route check */
5724 if (kif->pfik_ifp == NULL) {
5729 /* Perform uRPF check if passed input interface */
5731 rn = (struct radix_node *)ro.ro_rt;
5733 rt = (struct rtentry *)rn;
5736 if (kif->pfik_ifp == ifp)
5739 } while (check_mpath == 1 && rn != NULL && ret == 0);
5743 if (ro.ro_rt != NULL)
5749 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw)
5751 struct sockaddr_in *dst;
5753 struct sockaddr_in6 *dst6;
5754 struct route_in6 ro;
5760 ASSERT_LWKT_TOKEN_HELD(&pf_token);
5762 bzero(&ro, sizeof(ro));
5765 dst = satosin(&ro.ro_dst);
5766 dst->sin_family = AF_INET;
5767 dst->sin_len = sizeof(*dst);
5768 dst->sin_addr = addr->v4;
5772 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5773 dst6->sin6_family = AF_INET6;
5774 dst6->sin6_len = sizeof(*dst6);
5775 dst6->sin6_addr = addr->v6;
5782 rtalloc_ign((struct route *)&ro, (RTF_CLONING | RTF_PRCLONING));
5784 if (ro.ro_rt != NULL) {
5793 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5794 struct pf_state *s, struct pf_pdesc *pd)
5796 struct mbuf *m0, *m1;
5797 struct route iproute;
5798 struct route *ro = NULL;
5799 struct sockaddr_in *dst;
5801 struct ifnet *ifp = NULL;
5802 struct pf_addr naddr;
5803 struct pf_src_node *sn = NULL;
5810 ASSERT_LWKT_TOKEN_HELD(&pf_token);
5812 if (m == NULL || *m == NULL || r == NULL ||
5813 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5814 panic("pf_route: invalid parameters");
5816 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5817 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5818 (*m)->m_pkthdr.pf.routed = 1;
5820 if ((*m)->m_pkthdr.pf.routed++ > 3) {
5827 if (r->rt == PF_DUPTO) {
5828 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL) {
5832 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5838 if (m0->m_len < sizeof(struct ip)) {
5839 DPFPRINTF(PF_DEBUG_URGENT,
5840 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5844 ip = mtod(m0, struct ip *);
5847 bzero((caddr_t)ro, sizeof(*ro));
5848 dst = satosin(&ro->ro_dst);
5849 dst->sin_family = AF_INET;
5850 dst->sin_len = sizeof(*dst);
5851 dst->sin_addr = ip->ip_dst;
5853 if (r->rt == PF_FASTROUTE) {
5855 if (ro->ro_rt == 0) {
5856 ipstat.ips_noroute++;
5860 ifp = ro->ro_rt->rt_ifp;
5861 ro->ro_rt->rt_use++;
5863 if (ro->ro_rt->rt_flags & RTF_GATEWAY)
5864 dst = satosin(ro->ro_rt->rt_gateway);
5866 if (TAILQ_EMPTY(&r->rpool.list)) {
5867 DPFPRINTF(PF_DEBUG_URGENT,
5868 ("pf_route: TAILQ_EMPTY(&r->rpool.list)\n"));
5872 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5874 if (!PF_AZERO(&naddr, AF_INET))
5875 dst->sin_addr.s_addr = naddr.v4.s_addr;
5876 ifp = r->rpool.cur->kif ?
5877 r->rpool.cur->kif->pfik_ifp : NULL;
5879 if (!PF_AZERO(&s->rt_addr, AF_INET))
5880 dst->sin_addr.s_addr =
5881 s->rt_addr.v4.s_addr;
5882 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5889 if (pf_test(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5891 } else if (m0 == NULL) {
5894 if (m0->m_len < sizeof(struct ip)) {
5895 DPFPRINTF(PF_DEBUG_URGENT,
5896 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5899 ip = mtod(m0, struct ip *);
5902 /* Copied from FreeBSD 5.1-CURRENT ip_output. */
5903 m0->m_pkthdr.csum_flags |= CSUM_IP;
5904 sw_csum = m0->m_pkthdr.csum_flags & ~ifp->if_hwassist;
5905 if (sw_csum & CSUM_DELAY_DATA) {
5906 in_delayed_cksum(m0);
5907 sw_csum &= ~CSUM_DELAY_DATA;
5909 m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
5910 m0->m_pkthdr.csum_iphlen = (ip->ip_hl << 2);
5913 * WARNING! We cannot fragment if the packet was modified from an
5914 * original which expected to be using TSO. In this
5915 * situation we pray that the target interface is
5916 * compatible with the originating interface.
5918 if (ip->ip_len <= ifp->if_mtu ||
5919 (m0->m_pkthdr.csum_flags & CSUM_TSO) ||
5920 ((ifp->if_hwassist & CSUM_FRAGMENT) &&
5921 (ip->ip_off & IP_DF) == 0)) {
5922 ip->ip_len = htons(ip->ip_len);
5923 ip->ip_off = htons(ip->ip_off);
5925 if (sw_csum & CSUM_DELAY_IP) {
5927 if (ip->ip_v == IPVERSION &&
5928 (ip->ip_hl << 2) == sizeof(*ip)) {
5929 ip->ip_sum = in_cksum_hdr(ip);
5931 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5934 lwkt_reltoken(&pf_token);
5935 error = ifp->if_output(ifp, m0, sintosa(dst), ro->ro_rt);
5936 lwkt_gettoken(&pf_token);
5941 * Too large for interface; fragment if possible.
5942 * Must be able to put at least 8 bytes per fragment.
5944 if (ip->ip_off & IP_DF) {
5945 ipstat.ips_cantfrag++;
5946 if (r->rt != PF_DUPTO) {
5947 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5955 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist, sw_csum);
5960 for (m0 = m1; m0; m0 = m1) {
5964 lwkt_reltoken(&pf_token);
5965 error = (*ifp->if_output)(ifp, m0, sintosa(dst),
5967 lwkt_gettoken(&pf_token);
5973 ipstat.ips_fragmented++;
5976 if (r->rt != PF_DUPTO)
5978 if (ro == &iproute && ro->ro_rt)
5990 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5991 struct pf_state *s, struct pf_pdesc *pd)
5994 struct route_in6 ip6route;
5995 struct route_in6 *ro;
5996 struct sockaddr_in6 *dst;
5997 struct ip6_hdr *ip6;
5998 struct ifnet *ifp = NULL;
5999 struct pf_addr naddr;
6000 struct pf_src_node *sn = NULL;
6002 if (m == NULL || *m == NULL || r == NULL ||
6003 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
6004 panic("pf_route6: invalid parameters");
6006 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
6007 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
6008 (*m)->m_pkthdr.pf.routed = 1;
6010 if ((*m)->m_pkthdr.pf.routed++ > 3) {
6017 if (r->rt == PF_DUPTO) {
6018 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL)
6021 if ((r->rt == PF_REPLYTO) == (r->direction == dir))
6026 if (m0->m_len < sizeof(struct ip6_hdr)) {
6027 DPFPRINTF(PF_DEBUG_URGENT,
6028 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
6031 ip6 = mtod(m0, struct ip6_hdr *);
6034 bzero((caddr_t)ro, sizeof(*ro));
6035 dst = (struct sockaddr_in6 *)&ro->ro_dst;
6036 dst->sin6_family = AF_INET6;
6037 dst->sin6_len = sizeof(*dst);
6038 dst->sin6_addr = ip6->ip6_dst;
6041 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6042 * so make sure pf.flags is clear.
6044 * Cheat. XXX why only in the v6 case???
6046 if (r->rt == PF_FASTROUTE) {
6047 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
6048 m0->m_pkthdr.pf.flags = 0;
6049 /* XXX Re-Check when Upgrading to > 4.4 */
6050 m0->m_pkthdr.pf.statekey = NULL;
6051 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
6055 if (TAILQ_EMPTY(&r->rpool.list)) {
6056 DPFPRINTF(PF_DEBUG_URGENT,
6057 ("pf_route6: TAILQ_EMPTY(&r->rpool.list)\n"));
6061 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
6063 if (!PF_AZERO(&naddr, AF_INET6))
6064 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
6066 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6068 if (!PF_AZERO(&s->rt_addr, AF_INET6))
6069 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
6070 &s->rt_addr, AF_INET6);
6071 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6077 if (pf_test6(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
6079 } else if (m0 == NULL) {
6082 if (m0->m_len < sizeof(struct ip6_hdr)) {
6083 DPFPRINTF(PF_DEBUG_URGENT,
6084 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
6087 ip6 = mtod(m0, struct ip6_hdr *);
6091 * If the packet is too large for the outgoing interface,
6092 * send back an icmp6 error.
6094 if (IN6_IS_ADDR_LINKLOCAL(&dst->sin6_addr))
6095 dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
6096 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
6097 nd6_output(ifp, ifp, m0, dst, NULL);
6099 in6_ifstat_inc(ifp, ifs6_in_toobig);
6100 if (r->rt != PF_DUPTO)
6101 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
6107 if (r->rt != PF_DUPTO)
6119 * check protocol (tcp/udp/icmp/icmp6) checksum and set mbuf flag
6120 * off is the offset where the protocol header starts
6121 * len is the total length of protocol header plus payload
6122 * returns 0 when the checksum is valid, otherwise returns 1.
6126 * FreeBSD supports cksum offload for the following drivers.
6127 * em(4), gx(4), lge(4), nge(4), ti(4), xl(4)
6128 * If we can make full use of it we would outperform ipfw/ipfilter in
6129 * very heavy traffic.
6130 * I have not tested 'cause I don't have NICs that supports cksum offload.
6131 * (There might be problems. Typical phenomena would be
6132 * 1. No route message for UDP packet.
6133 * 2. No connection acceptance from external hosts regardless of rule set.)
6136 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p,
6143 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
6145 if (m->m_pkthdr.len < off + len)
6151 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6152 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6153 sum = m->m_pkthdr.csum_data;
6155 ip = mtod(m, struct ip *);
6156 sum = in_pseudo(ip->ip_src.s_addr,
6157 ip->ip_dst.s_addr, htonl((u_short)len +
6158 m->m_pkthdr.csum_data + p));
6166 case IPPROTO_ICMPV6:
6176 if (p == IPPROTO_ICMP) {
6181 sum = in_cksum(m, len);
6185 if (m->m_len < sizeof(struct ip))
6187 sum = in_cksum_range(m, p, off, len);
6189 m->m_pkthdr.csum_flags |=
6192 m->m_pkthdr.csum_data = 0xffff;
6198 if (m->m_len < sizeof(struct ip6_hdr))
6200 sum = in6_cksum(m, p, off, len);
6203 * IPv6 H/W cksum off-load not supported yet!
6206 * m->m_pkthdr.csum_flags |=
6207 * (CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
6208 * m->m_pkthdr.csum_data = 0xffff;
6220 tcpstat.tcps_rcvbadsum++;
6223 udp_stat.udps_badsum++;
6226 icmpstat.icps_checksum++;
6229 case IPPROTO_ICMPV6:
6230 icmp6stat.icp6s_checksum++;
6240 pf_find_divert(struct mbuf *m)
6244 if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL)
6247 return ((struct pf_divert *)(mtag + 1));
6251 pf_get_divert(struct mbuf *m)
6255 if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL) {
6256 mtag = m_tag_get(PACKET_TAG_PF_DIVERT, sizeof(struct pf_divert),
6260 bzero(mtag + 1, sizeof(struct pf_divert));
6261 m_tag_prepend(m, mtag);
6264 return ((struct pf_divert *)(mtag + 1));
6270 * WARNING: pf_token held shared on entry, THIS IS CPU LOCALIZED CODE
6273 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0,
6274 struct ether_header *eh, struct inpcb *inp)
6276 struct pfi_kif *kif;
6277 u_short action, reason = 0, log = 0;
6278 struct mbuf *m = *m0;
6279 struct ip *h = NULL;
6280 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
6281 struct pf_state *s = NULL;
6282 struct pf_ruleset *ruleset = NULL;
6289 if (!pf_status.running)
6292 memset(&pd, 0, sizeof(pd));
6294 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6295 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6298 kif = (struct pfi_kif *)ifp->if_pf_kif;
6301 DPFPRINTF(PF_DEBUG_URGENT,
6302 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
6305 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6309 if ((m->m_flags & M_PKTHDR) == 0)
6310 panic("non-M_PKTHDR is passed to pf_test");
6311 #endif /* DIAGNOSTIC */
6313 if (m->m_pkthdr.len < (int)sizeof(*h)) {
6315 REASON_SET(&reason, PFRES_SHORT);
6321 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6322 * so make sure pf.flags is clear.
6324 if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6326 m->m_pkthdr.pf.flags = 0;
6327 /* Re-Check when updating to > 4.4 */
6328 m->m_pkthdr.pf.statekey = NULL;
6330 /* We do IP header normalization and packet reassembly here */
6331 if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
6335 m = *m0; /* pf_normalize messes with m0 */
6336 h = mtod(m, struct ip *);
6338 off = h->ip_hl << 2;
6339 if (off < (int)sizeof(*h)) {
6341 REASON_SET(&reason, PFRES_SHORT);
6346 pd.src = (struct pf_addr *)&h->ip_src;
6347 pd.dst = (struct pf_addr *)&h->ip_dst;
6348 pd.sport = pd.dport = NULL;
6349 pd.ip_sum = &h->ip_sum;
6350 pd.proto_sum = NULL;
6353 pd.sidx = (dir == PF_IN) ? 0 : 1;
6354 pd.didx = (dir == PF_IN) ? 1 : 0;
6357 pd.tot_len = h->ip_len;
6360 /* handle fragments that didn't get reassembled by normalization */
6361 if (h->ip_off & (IP_MF | IP_OFFMASK)) {
6362 action = pf_test_fragment(&r, dir, kif, m, h,
6373 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6374 &action, &reason, AF_INET)) {
6375 log = action != PF_PASS;
6378 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6380 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6383 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6384 if (action == PF_DROP)
6386 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6388 if (action == PF_PASS) {
6392 } else if (s == NULL) {
6393 action = pf_test_rule(&r, &s, dir, kif,
6395 &ruleset, NULL, inp);
6404 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6405 &action, &reason, AF_INET)) {
6406 log = action != PF_PASS;
6409 if (uh.uh_dport == 0 ||
6410 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6411 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6413 REASON_SET(&reason, PFRES_SHORT);
6416 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6417 if (action == PF_PASS) {
6421 } else if (s == NULL) {
6422 action = pf_test_rule(&r, &s, dir, kif,
6424 &ruleset, NULL, inp);
6429 case IPPROTO_ICMP: {
6433 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6434 &action, &reason, AF_INET)) {
6435 log = action != PF_PASS;
6438 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6440 if (action == PF_PASS) {
6444 } else if (s == NULL) {
6445 action = pf_test_rule(&r, &s, dir, kif,
6447 &ruleset, NULL, inp);
6453 action = pf_test_state_other(&s, dir, kif, m, &pd);
6454 if (action == PF_PASS) {
6458 } else if (s == NULL) {
6459 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6460 &pd, &a, &ruleset, NULL, inp);
6466 if (action == PF_PASS && h->ip_hl > 5 &&
6467 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6469 REASON_SET(&reason, PFRES_IPOPTIONS);
6471 DPFPRINTF(PF_DEBUG_MISC,
6472 ("pf: dropping packet with ip options\n"));
6475 if ((s && s->tag) || r->rtableid)
6476 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6479 if (dir == PF_IN && s && s->key[PF_SK_STACK])
6480 m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6484 if (action == PF_PASS && r->qid) {
6485 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6486 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6487 m->m_pkthdr.pf.qid = r->pqid;
6489 m->m_pkthdr.pf.qid = r->qid;
6490 m->m_pkthdr.pf.ecn_af = AF_INET;
6491 m->m_pkthdr.pf.hdr = h;
6492 /* add connection hash for fairq */
6495 m->m_pkthdr.pf.state_hash = s->hash;
6496 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6502 * connections redirected to loopback should not match sockets
6503 * bound specifically to loopback due to security implications,
6504 * see tcp_input() and in_pcblookup_listen().
6506 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6507 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6508 (s->nat_rule.ptr->action == PF_RDR ||
6509 s->nat_rule.ptr->action == PF_BINAT) &&
6510 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6511 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6513 if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6514 struct pf_divert *divert;
6516 if ((divert = pf_get_divert(m))) {
6517 m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6518 divert->port = r->divert.port;
6519 divert->addr.ipv4 = r->divert.addr.v4;
6526 if (s != NULL && s->nat_rule.ptr != NULL &&
6527 s->nat_rule.ptr->log & PF_LOG_ALL)
6528 lr = s->nat_rule.ptr;
6531 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, lr, a, ruleset,
6535 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6536 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6538 if (action == PF_PASS || r->action == PF_DROP) {
6539 dirndx = (dir == PF_OUT);
6540 r->packets[dirndx]++;
6541 r->bytes[dirndx] += pd.tot_len;
6543 a->packets[dirndx]++;
6544 a->bytes[dirndx] += pd.tot_len;
6547 if (s->nat_rule.ptr != NULL) {
6548 s->nat_rule.ptr->packets[dirndx]++;
6549 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6551 if (s->src_node != NULL) {
6552 s->src_node->packets[dirndx]++;
6553 s->src_node->bytes[dirndx] += pd.tot_len;
6555 if (s->nat_src_node != NULL) {
6556 s->nat_src_node->packets[dirndx]++;
6557 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6559 dirndx = (dir == s->direction) ? 0 : 1;
6560 s->packets[dirndx]++;
6561 s->bytes[dirndx] += pd.tot_len;
6564 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6565 if (nr != NULL && r == &pf_default_rule)
6567 if (tr->src.addr.type == PF_ADDR_TABLE)
6568 pfr_update_stats(tr->src.addr.p.tbl,
6569 (s == NULL) ? pd.src :
6570 &s->key[(s->direction == PF_IN)]->
6571 addr[(s->direction == PF_OUT)],
6572 pd.af, pd.tot_len, dir == PF_OUT,
6573 r->action == PF_PASS, tr->src.neg);
6574 if (tr->dst.addr.type == PF_ADDR_TABLE)
6575 pfr_update_stats(tr->dst.addr.p.tbl,
6576 (s == NULL) ? pd.dst :
6577 &s->key[(s->direction == PF_IN)]->
6578 addr[(s->direction == PF_IN)],
6579 pd.af, pd.tot_len, dir == PF_OUT,
6580 r->action == PF_PASS, tr->dst.neg);
6584 if (action == PF_SYNPROXY_DROP) {
6589 /* pf_route can free the mbuf causing *m0 to become NULL */
6590 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6599 * WARNING: pf_token held shared on entry, THIS IS CPU LOCALIZED CODE
6602 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0,
6603 struct ether_header *eh, struct inpcb *inp)
6605 struct pfi_kif *kif;
6606 u_short action, reason = 0, log = 0;
6607 struct mbuf *m = *m0, *n = NULL;
6608 struct ip6_hdr *h = NULL;
6609 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
6610 struct pf_state *s = NULL;
6611 struct pf_ruleset *ruleset = NULL;
6613 int off, terminal = 0, dirndx, rh_cnt = 0;
6615 if (!pf_status.running)
6618 memset(&pd, 0, sizeof(pd));
6620 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6621 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6624 kif = (struct pfi_kif *)ifp->if_pf_kif;
6627 DPFPRINTF(PF_DEBUG_URGENT,
6628 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6631 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6635 if ((m->m_flags & M_PKTHDR) == 0)
6636 panic("non-M_PKTHDR is passed to pf_test6");
6637 #endif /* DIAGNOSTIC */
6639 if (m->m_pkthdr.len < (int)sizeof(*h)) {
6641 REASON_SET(&reason, PFRES_SHORT);
6647 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6648 * so make sure pf.flags is clear.
6650 if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6652 m->m_pkthdr.pf.flags = 0;
6653 /* Re-Check when updating to > 4.4 */
6654 m->m_pkthdr.pf.statekey = NULL;
6656 /* We do IP header normalization and packet reassembly here */
6657 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6661 m = *m0; /* pf_normalize messes with m0 */
6662 h = mtod(m, struct ip6_hdr *);
6666 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6667 * will do something bad, so drop the packet for now.
6669 if (htons(h->ip6_plen) == 0) {
6671 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6676 pd.src = (struct pf_addr *)&h->ip6_src;
6677 pd.dst = (struct pf_addr *)&h->ip6_dst;
6678 pd.sport = pd.dport = NULL;
6680 pd.proto_sum = NULL;
6682 pd.sidx = (dir == PF_IN) ? 0 : 1;
6683 pd.didx = (dir == PF_IN) ? 1 : 0;
6686 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6689 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6690 pd.proto = h->ip6_nxt;
6693 case IPPROTO_FRAGMENT:
6694 action = pf_test_fragment(&r, dir, kif, m, h,
6696 if (action == PF_DROP)
6697 REASON_SET(&reason, PFRES_FRAG);
6699 case IPPROTO_ROUTING: {
6700 struct ip6_rthdr rthdr;
6703 DPFPRINTF(PF_DEBUG_MISC,
6704 ("pf: IPv6 more than one rthdr\n"));
6706 REASON_SET(&reason, PFRES_IPOPTIONS);
6710 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6712 DPFPRINTF(PF_DEBUG_MISC,
6713 ("pf: IPv6 short rthdr\n"));
6715 REASON_SET(&reason, PFRES_SHORT);
6719 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6720 DPFPRINTF(PF_DEBUG_MISC,
6721 ("pf: IPv6 rthdr0\n"));
6723 REASON_SET(&reason, PFRES_IPOPTIONS);
6730 case IPPROTO_HOPOPTS:
6731 case IPPROTO_DSTOPTS: {
6732 /* get next header and header length */
6733 struct ip6_ext opt6;
6735 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6736 NULL, &reason, pd.af)) {
6737 DPFPRINTF(PF_DEBUG_MISC,
6738 ("pf: IPv6 short opt\n"));
6743 if (pd.proto == IPPROTO_AH)
6744 off += (opt6.ip6e_len + 2) * 4;
6746 off += (opt6.ip6e_len + 1) * 8;
6747 pd.proto = opt6.ip6e_nxt;
6748 /* goto the next header */
6755 } while (!terminal);
6757 /* if there's no routing header, use unmodified mbuf for checksumming */
6767 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6768 &action, &reason, AF_INET6)) {
6769 log = action != PF_PASS;
6772 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6773 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6774 if (action == PF_DROP)
6776 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6778 if (action == PF_PASS) {
6782 } else if (s == NULL) {
6783 action = pf_test_rule(&r, &s, dir, kif,
6785 &ruleset, NULL, inp);
6794 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6795 &action, &reason, AF_INET6)) {
6796 log = action != PF_PASS;
6799 if (uh.uh_dport == 0 ||
6800 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6801 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6803 REASON_SET(&reason, PFRES_SHORT);
6806 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6807 if (action == PF_PASS) {
6811 } else if (s == NULL) {
6812 action = pf_test_rule(&r, &s, dir, kif,
6814 &ruleset, NULL, inp);
6819 case IPPROTO_ICMPV6: {
6820 struct icmp6_hdr ih;
6823 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6824 &action, &reason, AF_INET6)) {
6825 log = action != PF_PASS;
6828 action = pf_test_state_icmp(&s, dir, kif,
6829 m, off, h, &pd, &reason);
6830 if (action == PF_PASS) {
6834 } else if (s == NULL) {
6835 action = pf_test_rule(&r, &s, dir, kif,
6837 &ruleset, NULL, inp);
6843 action = pf_test_state_other(&s, dir, kif, m, &pd);
6844 if (action == PF_PASS) {
6848 } else if (s == NULL) {
6849 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6850 &pd, &a, &ruleset, NULL, inp);
6861 /* handle dangerous IPv6 extension headers. */
6862 if (action == PF_PASS && rh_cnt &&
6863 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6865 REASON_SET(&reason, PFRES_IPOPTIONS);
6867 DPFPRINTF(PF_DEBUG_MISC,
6868 ("pf: dropping packet with dangerous v6 headers\n"));
6871 if ((s && s->tag) || r->rtableid)
6872 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6875 if (dir == PF_IN && s && s->key[PF_SK_STACK])
6876 m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6880 if (action == PF_PASS && r->qid) {
6881 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6882 if (pd.tos & IPTOS_LOWDELAY)
6883 m->m_pkthdr.pf.qid = r->pqid;
6885 m->m_pkthdr.pf.qid = r->qid;
6886 m->m_pkthdr.pf.ecn_af = AF_INET6;
6887 m->m_pkthdr.pf.hdr = h;
6890 m->m_pkthdr.pf.state_hash = s->hash;
6891 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6896 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6897 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6898 (s->nat_rule.ptr->action == PF_RDR ||
6899 s->nat_rule.ptr->action == PF_BINAT) &&
6900 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6901 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6903 if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6904 struct pf_divert *divert;
6906 if ((divert = pf_get_divert(m))) {
6907 m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6908 divert->port = r->divert.port;
6909 divert->addr.ipv6 = r->divert.addr.v6;
6916 if (s != NULL && s->nat_rule.ptr != NULL &&
6917 s->nat_rule.ptr->log & PF_LOG_ALL)
6918 lr = s->nat_rule.ptr;
6921 PFLOG_PACKET(kif, h, m, AF_INET6, dir, reason, lr, a, ruleset,
6925 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6926 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6928 if (action == PF_PASS || r->action == PF_DROP) {
6929 dirndx = (dir == PF_OUT);
6930 r->packets[dirndx]++;
6931 r->bytes[dirndx] += pd.tot_len;
6933 a->packets[dirndx]++;
6934 a->bytes[dirndx] += pd.tot_len;
6937 if (s->nat_rule.ptr != NULL) {
6938 s->nat_rule.ptr->packets[dirndx]++;
6939 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6941 if (s->src_node != NULL) {
6942 s->src_node->packets[dirndx]++;
6943 s->src_node->bytes[dirndx] += pd.tot_len;
6945 if (s->nat_src_node != NULL) {
6946 s->nat_src_node->packets[dirndx]++;
6947 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6949 dirndx = (dir == s->direction) ? 0 : 1;
6950 s->packets[dirndx]++;
6951 s->bytes[dirndx] += pd.tot_len;
6954 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6955 if (nr != NULL && r == &pf_default_rule)
6957 if (tr->src.addr.type == PF_ADDR_TABLE)
6958 pfr_update_stats(tr->src.addr.p.tbl,
6959 (s == NULL) ? pd.src :
6960 &s->key[(s->direction == PF_IN)]->addr[0],
6961 pd.af, pd.tot_len, dir == PF_OUT,
6962 r->action == PF_PASS, tr->src.neg);
6963 if (tr->dst.addr.type == PF_ADDR_TABLE)
6964 pfr_update_stats(tr->dst.addr.p.tbl,
6965 (s == NULL) ? pd.dst :
6966 &s->key[(s->direction == PF_IN)]->addr[1],
6967 pd.af, pd.tot_len, dir == PF_OUT,
6968 r->action == PF_PASS, tr->dst.neg);
6972 if (action == PF_SYNPROXY_DROP) {
6977 /* pf_route6 can free the mbuf causing *m0 to become NULL */
6978 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6985 pf_check_congestion(struct ifqueue *ifq)