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>
57 #include <machine/inttypes.h>
62 #include <net/if_types.h>
64 #include <net/netisr.h>
65 #include <net/route.h>
67 #include <netinet/in.h>
68 #include <netinet/in_var.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip_var.h>
72 #include <netinet/tcp.h>
73 #include <netinet/tcp_seq.h>
74 #include <netinet/udp.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/in_pcb.h>
77 #include <netinet/tcp_timer.h>
78 #include <netinet/tcp_var.h>
79 #include <netinet/udp_var.h>
80 #include <netinet/icmp_var.h>
81 #include <netinet/if_ether.h>
83 #include <net/pf/pfvar.h>
84 #include <net/pf/if_pflog.h>
86 #include <net/pf/if_pfsync.h>
89 #include <netinet/ip6.h>
90 #include <netinet/in_pcb.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 <net/netmsg2.h>
103 extern int ip_optcopy(struct ip *, struct ip *);
104 extern int debug_pfugidhack;
106 struct lwkt_token pf_token = LWKT_TOKEN_INITIALIZER(pf_token);
108 #define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
114 /* mask radix tree */
115 struct radix_node_head *pf_maskhead;
118 struct pf_state_tree pf_statetbl;
120 struct pf_altqqueue pf_altqs[2];
121 struct pf_palist pf_pabuf;
122 struct pf_altqqueue *pf_altqs_active;
123 struct pf_altqqueue *pf_altqs_inactive;
124 struct pf_status pf_status;
126 u_int32_t ticket_altqs_active;
127 u_int32_t ticket_altqs_inactive;
128 int altqs_inactive_open;
129 u_int32_t ticket_pabuf;
131 MD5_CTX pf_tcp_secret_ctx;
132 u_char pf_tcp_secret[16];
133 int pf_tcp_secret_init;
136 struct pf_anchor_stackframe {
137 struct pf_ruleset *rs;
139 struct pf_anchor_node *parent;
140 struct pf_anchor *child;
141 } pf_anchor_stack[64];
143 struct malloc_type *pf_src_tree_pl, *pf_rule_pl, *pf_pooladdr_pl;
144 struct malloc_type *pf_state_pl, *pf_state_key_pl, *pf_state_item_pl;
145 struct malloc_type *pf_altq_pl;
147 void pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
149 void pf_init_threshold(struct pf_threshold *, u_int32_t,
151 void pf_add_threshold(struct pf_threshold *);
152 int pf_check_threshold(struct pf_threshold *);
154 void pf_change_ap(struct pf_addr *, u_int16_t *,
155 u_int16_t *, u_int16_t *, struct pf_addr *,
156 u_int16_t, u_int8_t, sa_family_t);
157 int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
158 struct tcphdr *, struct pf_state_peer *);
160 void pf_change_a6(struct pf_addr *, u_int16_t *,
161 struct pf_addr *, u_int8_t);
163 void pf_change_icmp(struct pf_addr *, u_int16_t *,
164 struct pf_addr *, struct pf_addr *, u_int16_t,
165 u_int16_t *, u_int16_t *, u_int16_t *,
166 u_int16_t *, u_int8_t, sa_family_t);
167 void pf_send_tcp(const struct pf_rule *, sa_family_t,
168 const struct pf_addr *, const struct pf_addr *,
169 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
170 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
171 u_int16_t, struct ether_header *, struct ifnet *);
172 void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
173 sa_family_t, struct pf_rule *);
174 struct pf_rule *pf_match_translation(struct pf_pdesc *, struct mbuf *,
175 int, int, struct pfi_kif *,
176 struct pf_addr *, u_int16_t, struct pf_addr *,
178 struct pf_rule *pf_get_translation(struct pf_pdesc *, struct mbuf *,
179 int, int, struct pfi_kif *, struct pf_src_node **,
180 struct pf_state_key **, struct pf_state_key **,
181 struct pf_state_key **, struct pf_state_key **,
182 struct pf_addr *, struct pf_addr *,
183 u_int16_t, u_int16_t);
184 void pf_detach_state(struct pf_state *);
185 int pf_state_key_setup(struct pf_pdesc *, struct pf_rule *,
186 struct pf_state_key **, struct pf_state_key **,
187 struct pf_state_key **, struct pf_state_key **,
188 struct pf_addr *, struct pf_addr *,
189 u_int16_t, u_int16_t);
190 void pf_state_key_detach(struct pf_state *, int);
191 u_int32_t pf_tcp_iss(struct pf_pdesc *);
192 int pf_test_rule(struct pf_rule **, struct pf_state **,
193 int, struct pfi_kif *, struct mbuf *, int,
194 void *, struct pf_pdesc *, struct pf_rule **,
195 struct pf_ruleset **, struct ifqueue *, struct inpcb *);
196 static __inline int pf_create_state(struct pf_rule *, struct pf_rule *,
197 struct pf_rule *, struct pf_pdesc *,
198 struct pf_src_node *, struct pf_state_key *,
199 struct pf_state_key *, struct pf_state_key *,
200 struct pf_state_key *, struct mbuf *, int,
201 u_int16_t, u_int16_t, int *, struct pfi_kif *,
202 struct pf_state **, int, u_int16_t, u_int16_t,
204 int pf_test_fragment(struct pf_rule **, int,
205 struct pfi_kif *, struct mbuf *, void *,
206 struct pf_pdesc *, struct pf_rule **,
207 struct pf_ruleset **);
208 int pf_tcp_track_full(struct pf_state_peer *,
209 struct pf_state_peer *, struct pf_state **,
210 struct pfi_kif *, struct mbuf *, int,
211 struct pf_pdesc *, u_short *, int *);
212 int pf_tcp_track_sloppy(struct pf_state_peer *,
213 struct pf_state_peer *, struct pf_state **,
214 struct pf_pdesc *, u_short *);
215 int pf_test_state_tcp(struct pf_state **, int,
216 struct pfi_kif *, struct mbuf *, int,
217 void *, struct pf_pdesc *, u_short *);
218 int pf_test_state_udp(struct pf_state **, int,
219 struct pfi_kif *, struct mbuf *, int,
220 void *, struct pf_pdesc *);
221 int pf_test_state_icmp(struct pf_state **, int,
222 struct pfi_kif *, struct mbuf *, int,
223 void *, struct pf_pdesc *, u_short *);
224 int pf_test_state_other(struct pf_state **, int,
225 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
226 void pf_step_into_anchor(int *, struct pf_ruleset **, int,
227 struct pf_rule **, struct pf_rule **, int *);
228 int pf_step_out_of_anchor(int *, struct pf_ruleset **,
229 int, struct pf_rule **, struct pf_rule **,
231 void pf_hash(struct pf_addr *, struct pf_addr *,
232 struct pf_poolhashkey *, sa_family_t);
233 int pf_map_addr(u_int8_t, struct pf_rule *,
234 struct pf_addr *, struct pf_addr *,
235 struct pf_addr *, struct pf_src_node **);
236 int pf_get_sport(sa_family_t, u_int8_t, struct pf_rule *,
237 struct pf_addr *, struct pf_addr *, u_int16_t,
238 struct pf_addr *, u_int16_t*, u_int16_t, u_int16_t,
239 struct pf_src_node **);
240 void pf_route(struct mbuf **, struct pf_rule *, int,
241 struct ifnet *, struct pf_state *,
243 void pf_route6(struct mbuf **, struct pf_rule *, int,
244 struct ifnet *, struct pf_state *,
246 u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
248 u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
250 u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
252 void pf_set_rt_ifp(struct pf_state *,
254 int pf_check_proto_cksum(struct mbuf *, int, int,
255 u_int8_t, sa_family_t);
256 struct pf_divert *pf_get_divert(struct mbuf *);
257 void pf_print_state_parts(struct pf_state *,
258 struct pf_state_key *, struct pf_state_key *);
259 int pf_addr_wrap_neq(struct pf_addr_wrap *,
260 struct pf_addr_wrap *);
261 struct pf_state *pf_find_state(struct pfi_kif *,
262 struct pf_state_key_cmp *, u_int, struct mbuf *);
263 int pf_src_connlimit(struct pf_state **);
264 int pf_check_congestion(struct ifqueue *);
266 extern int pf_end_threads;
268 struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
269 { &pf_state_pl, PFSTATE_HIWAT },
270 { &pf_src_tree_pl, PFSNODE_HIWAT },
271 { &pf_frent_pl, PFFRAG_FRENT_HIWAT },
272 { &pfr_ktable_pl, PFR_KTABLE_HIWAT },
273 { &pfr_kentry_pl, PFR_KENTRY_HIWAT }
276 #define STATE_LOOKUP(i, k, d, s, m) \
278 s = pf_find_state(i, k, d, m); \
279 if (s == NULL || (s)->timeout == PFTM_PURGE) \
282 (((s)->rule.ptr->rt == PF_ROUTETO && \
283 (s)->rule.ptr->direction == PF_OUT) || \
284 ((s)->rule.ptr->rt == PF_REPLYTO && \
285 (s)->rule.ptr->direction == PF_IN)) && \
286 (s)->rt_kif != NULL && \
291 #define BOUND_IFACE(r, k) \
292 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
294 #define STATE_INC_COUNTERS(s) \
296 s->rule.ptr->states_cur++; \
297 s->rule.ptr->states_tot++; \
298 if (s->anchor.ptr != NULL) { \
299 s->anchor.ptr->states_cur++; \
300 s->anchor.ptr->states_tot++; \
302 if (s->nat_rule.ptr != NULL) { \
303 s->nat_rule.ptr->states_cur++; \
304 s->nat_rule.ptr->states_tot++; \
308 #define STATE_DEC_COUNTERS(s) \
310 if (s->nat_rule.ptr != NULL) \
311 s->nat_rule.ptr->states_cur--; \
312 if (s->anchor.ptr != NULL) \
313 s->anchor.ptr->states_cur--; \
314 s->rule.ptr->states_cur--; \
317 static MALLOC_DEFINE(M_PFSTATEPL, "pfstatepl", "pf state pool list");
318 static MALLOC_DEFINE(M_PFSRCTREEPL, "pfsrctpl", "pf source tree pool list");
319 static MALLOC_DEFINE(M_PFSTATEKEYPL, "pfstatekeypl", "pf state key pool list");
320 static MALLOC_DEFINE(M_PFSTATEITEMPL, "pfstateitempl", "pf state item pool list");
322 static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
323 static __inline int pf_state_compare_key(struct pf_state_key *,
324 struct pf_state_key *);
325 static __inline int pf_state_compare_id(struct pf_state *,
328 struct pf_src_tree tree_src_tracking;
330 struct pf_state_tree_id tree_id;
331 struct pf_state_queue state_list;
333 RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
334 RB_GENERATE(pf_state_tree, pf_state_key, entry, pf_state_compare_key);
335 RB_GENERATE(pf_state_tree_id, pf_state,
336 entry_id, pf_state_compare_id);
339 pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
343 if (a->rule.ptr > b->rule.ptr)
345 if (a->rule.ptr < b->rule.ptr)
347 if ((diff = a->af - b->af) != 0)
352 if (a->addr.addr32[0] > b->addr.addr32[0])
354 if (a->addr.addr32[0] < b->addr.addr32[0])
360 if (a->addr.addr32[3] > b->addr.addr32[3])
362 if (a->addr.addr32[3] < b->addr.addr32[3])
364 if (a->addr.addr32[2] > b->addr.addr32[2])
366 if (a->addr.addr32[2] < b->addr.addr32[2])
368 if (a->addr.addr32[1] > b->addr.addr32[1])
370 if (a->addr.addr32[1] < b->addr.addr32[1])
372 if (a->addr.addr32[0] > b->addr.addr32[0])
374 if (a->addr.addr32[0] < b->addr.addr32[0])
383 pf_state_hash(struct pf_state_key *sk)
385 u_int32_t hv = (u_int32_t)(((intptr_t)sk >> 6) ^ ((intptr_t)sk >> 15));
386 if (hv == 0) /* disallow 0 */
393 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
398 dst->addr32[0] = src->addr32[0];
402 dst->addr32[0] = src->addr32[0];
403 dst->addr32[1] = src->addr32[1];
404 dst->addr32[2] = src->addr32[2];
405 dst->addr32[3] = src->addr32[3];
412 pf_init_threshold(struct pf_threshold *threshold,
413 u_int32_t limit, u_int32_t seconds)
415 threshold->limit = limit * PF_THRESHOLD_MULT;
416 threshold->seconds = seconds;
417 threshold->count = 0;
418 threshold->last = time_second;
422 pf_add_threshold(struct pf_threshold *threshold)
424 u_int32_t t = time_second, diff = t - threshold->last;
426 if (diff >= threshold->seconds)
427 threshold->count = 0;
429 threshold->count -= threshold->count * diff /
431 threshold->count += PF_THRESHOLD_MULT;
436 pf_check_threshold(struct pf_threshold *threshold)
438 return (threshold->count > threshold->limit);
442 pf_src_connlimit(struct pf_state **state)
446 (*state)->src_node->conn++;
447 (*state)->src.tcp_est = 1;
448 pf_add_threshold(&(*state)->src_node->conn_rate);
450 if ((*state)->rule.ptr->max_src_conn &&
451 (*state)->rule.ptr->max_src_conn <
452 (*state)->src_node->conn) {
453 pf_status.lcounters[LCNT_SRCCONN]++;
457 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
458 pf_check_threshold(&(*state)->src_node->conn_rate)) {
459 pf_status.lcounters[LCNT_SRCCONNRATE]++;
466 if ((*state)->rule.ptr->overload_tbl) {
468 u_int32_t killed = 0;
470 pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
471 if (pf_status.debug >= PF_DEBUG_MISC) {
472 kprintf("pf_src_connlimit: blocking address ");
473 pf_print_host(&(*state)->src_node->addr, 0,
474 (*state)->key[PF_SK_WIRE]->af);
477 bzero(&p, sizeof(p));
478 p.pfra_af = (*state)->key[PF_SK_WIRE]->af;
479 switch ((*state)->key[PF_SK_WIRE]->af) {
483 p.pfra_ip4addr = (*state)->src_node->addr.v4;
489 p.pfra_ip6addr = (*state)->src_node->addr.v6;
494 pfr_insert_kentry((*state)->rule.ptr->overload_tbl,
497 /* kill existing states if that's required. */
498 if ((*state)->rule.ptr->flush) {
499 struct pf_state_key *sk;
502 pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
503 RB_FOREACH(st, pf_state_tree_id, &tree_id) {
504 sk = st->key[PF_SK_WIRE];
506 * Kill states from this source. (Only those
507 * from the same rule if PF_FLUSH_GLOBAL is not
511 (*state)->key[PF_SK_WIRE]->af &&
512 (((*state)->direction == PF_OUT &&
513 PF_AEQ(&(*state)->src_node->addr,
514 &sk->addr[0], sk->af)) ||
515 ((*state)->direction == PF_IN &&
516 PF_AEQ(&(*state)->src_node->addr,
517 &sk->addr[1], sk->af))) &&
518 ((*state)->rule.ptr->flush &
520 (*state)->rule.ptr == st->rule.ptr)) {
521 st->timeout = PFTM_PURGE;
522 st->src.state = st->dst.state =
527 if (pf_status.debug >= PF_DEBUG_MISC)
528 kprintf(", %u states killed", killed);
530 if (pf_status.debug >= PF_DEBUG_MISC)
534 /* kill this state */
535 (*state)->timeout = PFTM_PURGE;
536 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
541 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
542 struct pf_addr *src, sa_family_t af)
544 struct pf_src_node k;
548 PF_ACPY(&k.addr, src, af);
549 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
550 rule->rpool.opts & PF_POOL_STICKYADDR)
554 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
555 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
558 if (!rule->max_src_nodes ||
559 rule->src_nodes < rule->max_src_nodes)
560 (*sn) = kmalloc(sizeof(struct pf_src_node), M_PFSRCTREEPL, M_NOWAIT|M_ZERO);
562 pf_status.lcounters[LCNT_SRCNODES]++;
566 pf_init_threshold(&(*sn)->conn_rate,
567 rule->max_src_conn_rate.limit,
568 rule->max_src_conn_rate.seconds);
571 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
572 rule->rpool.opts & PF_POOL_STICKYADDR)
573 (*sn)->rule.ptr = rule;
575 (*sn)->rule.ptr = NULL;
576 PF_ACPY(&(*sn)->addr, src, af);
577 if (RB_INSERT(pf_src_tree,
578 &tree_src_tracking, *sn) != NULL) {
579 if (pf_status.debug >= PF_DEBUG_MISC) {
580 kprintf("pf: src_tree insert failed: ");
581 pf_print_host(&(*sn)->addr, 0, af);
584 kfree(*sn, M_PFSRCTREEPL);
587 (*sn)->creation = time_second;
588 (*sn)->ruletype = rule->action;
589 if ((*sn)->rule.ptr != NULL)
590 (*sn)->rule.ptr->src_nodes++;
591 pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
592 pf_status.src_nodes++;
594 if (rule->max_src_states &&
595 (*sn)->states >= rule->max_src_states) {
596 pf_status.lcounters[LCNT_SRCSTATES]++;
603 /* state table stuff */
606 pf_state_compare_key(struct pf_state_key *a, struct pf_state_key *b)
610 if ((diff = a->proto - b->proto) != 0)
612 if ((diff = a->af - b->af) != 0)
617 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
619 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
621 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
623 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
629 if (a->addr[0].addr32[3] > b->addr[0].addr32[3])
631 if (a->addr[0].addr32[3] < b->addr[0].addr32[3])
633 if (a->addr[1].addr32[3] > b->addr[1].addr32[3])
635 if (a->addr[1].addr32[3] < b->addr[1].addr32[3])
637 if (a->addr[0].addr32[2] > b->addr[0].addr32[2])
639 if (a->addr[0].addr32[2] < b->addr[0].addr32[2])
641 if (a->addr[1].addr32[2] > b->addr[1].addr32[2])
643 if (a->addr[1].addr32[2] < b->addr[1].addr32[2])
645 if (a->addr[0].addr32[1] > b->addr[0].addr32[1])
647 if (a->addr[0].addr32[1] < b->addr[0].addr32[1])
649 if (a->addr[1].addr32[1] > b->addr[1].addr32[1])
651 if (a->addr[1].addr32[1] < b->addr[1].addr32[1])
653 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
655 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
657 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
659 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
665 if ((diff = a->port[0] - b->port[0]) != 0)
667 if ((diff = a->port[1] - b->port[1]) != 0)
674 pf_state_compare_id(struct pf_state *a, struct pf_state *b)
680 if (a->creatorid > b->creatorid)
682 if (a->creatorid < b->creatorid)
689 pf_state_key_attach(struct pf_state_key *sk, struct pf_state *s, int idx)
691 struct pf_state_item *si;
692 struct pf_state_key *cur;
694 KKASSERT(s->key[idx] == NULL); /* XXX handle this? */
696 if ((cur = RB_INSERT(pf_state_tree, &pf_statetbl, sk)) != NULL) {
697 /* key exists. check for same kif, if none, add to key */
698 TAILQ_FOREACH(si, &cur->states, entry)
699 if (si->s->kif == s->kif &&
700 si->s->direction == s->direction) {
701 if (pf_status.debug >= PF_DEBUG_MISC) {
703 "pf: %s key attach failed on %s: ",
704 (idx == PF_SK_WIRE) ?
707 pf_print_state_parts(s,
708 (idx == PF_SK_WIRE) ? sk : NULL,
709 (idx == PF_SK_STACK) ? sk : NULL);
712 kfree(sk, M_PFSTATEKEYPL);
713 return (-1); /* collision! */
715 kfree(sk, M_PFSTATEKEYPL);
721 if ((si = kmalloc(sizeof(struct pf_state_item), M_PFSTATEITEMPL, M_NOWAIT)) == NULL) {
722 pf_state_key_detach(s, idx);
727 /* list is sorted, if-bound states before floating */
728 if (s->kif == pfi_all)
729 TAILQ_INSERT_TAIL(&s->key[idx]->states, si, entry);
731 TAILQ_INSERT_HEAD(&s->key[idx]->states, si, entry);
736 pf_detach_state(struct pf_state *s)
738 if (s->key[PF_SK_WIRE] == s->key[PF_SK_STACK])
739 s->key[PF_SK_WIRE] = NULL;
741 if (s->key[PF_SK_STACK] != NULL)
742 pf_state_key_detach(s, PF_SK_STACK);
744 if (s->key[PF_SK_WIRE] != NULL)
745 pf_state_key_detach(s, PF_SK_WIRE);
749 pf_state_key_detach(struct pf_state *s, int idx)
751 struct pf_state_item *si;
752 si = TAILQ_FIRST(&s->key[idx]->states);
753 while (si && si->s != s)
754 si = TAILQ_NEXT(si, entry);
757 TAILQ_REMOVE(&s->key[idx]->states, si, entry);
758 kfree(si, M_PFSTATEITEMPL);
761 if (TAILQ_EMPTY(&s->key[idx]->states)) {
762 RB_REMOVE(pf_state_tree, &pf_statetbl, s->key[idx]);
763 if (s->key[idx]->reverse)
764 s->key[idx]->reverse->reverse = NULL;
765 if (s->key[idx]->inp)
766 s->key[idx]->inp->inp_pf_sk = NULL;
767 kfree(s->key[idx], M_PFSTATEKEYPL);
772 struct pf_state_key *
773 pf_alloc_state_key(int pool_flags)
775 struct pf_state_key *sk;
777 if ((sk = kmalloc(sizeof(struct pf_state_key), M_PFSTATEKEYPL, pool_flags)) == NULL)
779 TAILQ_INIT(&sk->states);
785 pf_state_key_setup(struct pf_pdesc *pd, struct pf_rule *nr,
786 struct pf_state_key **skw, struct pf_state_key **sks,
787 struct pf_state_key **skp, struct pf_state_key **nkp,
788 struct pf_addr *saddr, struct pf_addr *daddr,
789 u_int16_t sport, u_int16_t dport)
791 KKASSERT((*skp == NULL && *nkp == NULL));
793 if ((*skp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
796 PF_ACPY(&(*skp)->addr[pd->sidx], saddr, pd->af);
797 PF_ACPY(&(*skp)->addr[pd->didx], daddr, pd->af);
798 (*skp)->port[pd->sidx] = sport;
799 (*skp)->port[pd->didx] = dport;
800 (*skp)->proto = pd->proto;
804 if ((*nkp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
805 return (ENOMEM); /* caller must handle cleanup */
807 /* XXX maybe just bcopy and TAILQ_INIT(&(*nkp)->states) */
808 PF_ACPY(&(*nkp)->addr[0], &(*skp)->addr[0], pd->af);
809 PF_ACPY(&(*nkp)->addr[1], &(*skp)->addr[1], pd->af);
810 (*nkp)->port[0] = (*skp)->port[0];
811 (*nkp)->port[1] = (*skp)->port[1];
812 (*nkp)->proto = pd->proto;
817 if (pd->dir == PF_IN) {
829 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
830 struct pf_state_key *sks, struct pf_state *s)
835 if (pf_state_key_attach(skw, s, PF_SK_WIRE))
837 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
839 if (pf_state_key_attach(skw, s, PF_SK_WIRE)) {
840 kfree(sks, M_PFSTATEKEYPL);
843 if (pf_state_key_attach(sks, s, PF_SK_STACK)) {
844 pf_state_key_detach(s, PF_SK_WIRE);
849 if (s->id == 0 && s->creatorid == 0) {
850 s->id = htobe64(pf_status.stateid++);
851 s->creatorid = pf_status.hostid;
855 * Calculate hash code for altq
857 s->hash = crc32(s->key[PF_SK_WIRE], sizeof(*sks));
859 if (RB_INSERT(pf_state_tree_id, &tree_id, s) != NULL) {
860 if (pf_status.debug >= PF_DEBUG_MISC) {
861 kprintf("pf: state insert failed: "
862 "id: %016jx creatorid: %08x",
863 (uintmax_t)be64toh(s->id), ntohl(s->creatorid));
864 if (s->sync_flags & PFSTATE_FROMSYNC)
865 kprintf(" (from sync)");
871 TAILQ_INSERT_TAIL(&state_list, s, entry_list);
872 pf_status.fcounters[FCNT_STATE_INSERT]++;
874 pfi_kif_ref(kif, PFI_KIF_REF_STATE);
875 pfsync_insert_state(s);
880 pf_find_state_byid(struct pf_state_cmp *key)
882 pf_status.fcounters[FCNT_STATE_SEARCH]++;
884 return (RB_FIND(pf_state_tree_id, &tree_id, (struct pf_state *)key));
888 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir,
891 struct pf_state_key *sk;
892 struct pf_state_item *si;
894 pf_status.fcounters[FCNT_STATE_SEARCH]++;
896 if (dir == PF_OUT && m->m_pkthdr.pf.statekey &&
897 ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse)
898 sk = ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse;
900 if ((sk = RB_FIND(pf_state_tree, &pf_statetbl,
901 (struct pf_state_key *)key)) == NULL)
903 if (dir == PF_OUT && m->m_pkthdr.pf.statekey) {
904 ((struct pf_state_key *)
905 m->m_pkthdr.pf.statekey)->reverse = sk;
906 sk->reverse = m->m_pkthdr.pf.statekey;
911 m->m_pkthdr.pf.statekey = NULL;
913 /* list is sorted, if-bound states before floating ones */
914 TAILQ_FOREACH(si, &sk->states, entry)
915 if ((si->s->kif == pfi_all || si->s->kif == kif) &&
916 sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
917 si->s->key[PF_SK_STACK]))
924 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
926 struct pf_state_key *sk;
927 struct pf_state_item *si, *ret = NULL;
929 pf_status.fcounters[FCNT_STATE_SEARCH]++;
931 sk = RB_FIND(pf_state_tree, &pf_statetbl, (struct pf_state_key *)key);
934 TAILQ_FOREACH(si, &sk->states, entry)
935 if (dir == PF_INOUT ||
936 (sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
937 si->s->key[PF_SK_STACK]))) {
947 return (ret ? ret->s : NULL);
950 /* END state table stuff */
954 pf_purge_thread(void *v)
959 lwkt_gettoken(&pf_token);
961 tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
963 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
965 if (pf_end_threads) {
966 pf_purge_expired_states(pf_status.states, 0);
967 pf_purge_expired_fragments();
968 pf_purge_expired_src_nodes(1);
971 lockmgr(&pf_consistency_lock, LK_RELEASE);
972 wakeup(pf_purge_thread);
977 /* process a fraction of the state table every second */
978 if(!pf_purge_expired_states(1 + (pf_status.states
979 / pf_default_rule.timeout[PFTM_INTERVAL]), 0)) {
981 pf_purge_expired_states(1 + (pf_status.states
982 / pf_default_rule.timeout[PFTM_INTERVAL]), 1);
985 /* purge other expired types every PFTM_INTERVAL seconds */
986 if (++nloops >= pf_default_rule.timeout[PFTM_INTERVAL]) {
987 pf_purge_expired_fragments();
988 if (!pf_purge_expired_src_nodes(locked)) {
989 pf_purge_expired_src_nodes(1);
994 lockmgr(&pf_consistency_lock, LK_RELEASE);
996 lwkt_reltoken(&pf_token);
1000 pf_state_expires(const struct pf_state *state)
1007 /* handle all PFTM_* > PFTM_MAX here */
1008 if (state->timeout == PFTM_PURGE)
1009 return (time_second);
1010 if (state->timeout == PFTM_UNTIL_PACKET)
1012 KKASSERT(state->timeout != PFTM_UNLINKED);
1013 KKASSERT(state->timeout < PFTM_MAX);
1014 timeout = state->rule.ptr->timeout[state->timeout];
1016 timeout = pf_default_rule.timeout[state->timeout];
1017 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1019 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1020 states = state->rule.ptr->states_cur;
1022 start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1023 end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1024 states = pf_status.states;
1026 if (end && states > start && start < end) {
1028 return (state->expire + timeout * (end - states) /
1031 return (time_second);
1033 return (state->expire + timeout);
1037 pf_purge_expired_src_nodes(int waslocked)
1039 struct pf_src_node *cur, *next;
1040 int locked = waslocked;
1042 for (cur = RB_MIN(pf_src_tree, &tree_src_tracking); cur; cur = next) {
1043 next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
1045 if (cur->states <= 0 && cur->expire <= time_second) {
1047 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1048 next = RB_NEXT(pf_src_tree,
1049 &tree_src_tracking, cur);
1052 if (cur->rule.ptr != NULL) {
1053 cur->rule.ptr->src_nodes--;
1054 if (cur->rule.ptr->states_cur <= 0 &&
1055 cur->rule.ptr->max_src_nodes <= 0)
1056 pf_rm_rule(NULL, cur->rule.ptr);
1058 RB_REMOVE(pf_src_tree, &tree_src_tracking, cur);
1059 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1060 pf_status.src_nodes--;
1061 kfree(cur, M_PFSRCTREEPL);
1065 if (locked && !waslocked)
1066 lockmgr(&pf_consistency_lock, LK_RELEASE);
1071 pf_src_tree_remove_state(struct pf_state *s)
1075 if (s->src_node != NULL) {
1077 --s->src_node->conn;
1078 if (--s->src_node->states <= 0) {
1079 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1082 pf_default_rule.timeout[PFTM_SRC_NODE];
1083 s->src_node->expire = time_second + timeout;
1086 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1087 if (--s->nat_src_node->states <= 0) {
1088 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1091 pf_default_rule.timeout[PFTM_SRC_NODE];
1092 s->nat_src_node->expire = time_second + timeout;
1095 s->src_node = s->nat_src_node = NULL;
1098 /* callers should be at crit_enter() */
1100 pf_unlink_state(struct pf_state *cur)
1102 if (cur->src.state == PF_TCPS_PROXY_DST) {
1103 /* XXX wire key the right one? */
1104 pf_send_tcp(cur->rule.ptr, cur->key[PF_SK_WIRE]->af,
1105 &cur->key[PF_SK_WIRE]->addr[1],
1106 &cur->key[PF_SK_WIRE]->addr[0],
1107 cur->key[PF_SK_WIRE]->port[1],
1108 cur->key[PF_SK_WIRE]->port[0],
1109 cur->src.seqhi, cur->src.seqlo + 1,
1110 TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1112 RB_REMOVE(pf_state_tree_id, &tree_id, cur);
1113 if (cur->creatorid == pf_status.hostid)
1114 pfsync_delete_state(cur);
1115 cur->timeout = PFTM_UNLINKED;
1116 pf_src_tree_remove_state(cur);
1117 pf_detach_state(cur);
1120 static struct pf_state *purge_cur;
1122 /* callers should be at crit_enter() and hold the
1123 * write_lock on pf_consistency_lock */
1125 pf_free_state(struct pf_state *cur)
1127 if (pfsyncif != NULL &&
1128 (pfsyncif->sc_bulk_send_next == cur ||
1129 pfsyncif->sc_bulk_terminator == cur))
1131 KKASSERT(cur->timeout == PFTM_UNLINKED);
1132 if (--cur->rule.ptr->states_cur <= 0 &&
1133 cur->rule.ptr->src_nodes <= 0)
1134 pf_rm_rule(NULL, cur->rule.ptr);
1135 if (cur->nat_rule.ptr != NULL)
1136 if (--cur->nat_rule.ptr->states_cur <= 0 &&
1137 cur->nat_rule.ptr->src_nodes <= 0)
1138 pf_rm_rule(NULL, cur->nat_rule.ptr);
1139 if (cur->anchor.ptr != NULL)
1140 if (--cur->anchor.ptr->states_cur <= 0)
1141 pf_rm_rule(NULL, cur->anchor.ptr);
1142 pf_normalize_tcp_cleanup(cur);
1143 pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1146 * We may be freeing pf_purge_expired_states()'s saved scan entry,
1147 * adjust it if necessary.
1149 if (purge_cur == cur) {
1150 kprintf("PURGE CONFLICT\n");
1151 purge_cur = TAILQ_NEXT(purge_cur, entry_list);
1153 TAILQ_REMOVE(&state_list, cur, entry_list);
1155 pf_tag_unref(cur->tag);
1156 kfree(cur, M_PFSTATEPL);
1157 pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1162 pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1164 struct pf_state *cur;
1165 int locked = waslocked;
1167 while (maxcheck--) {
1169 * Wrap to start of list when we hit the end
1173 cur = TAILQ_FIRST(&state_list);
1175 break; /* list empty */
1179 * Setup next (purge_cur) while we process this one. If we block and
1180 * something else deletes purge_cur, pf_free_state() will adjust it further
1183 purge_cur = TAILQ_NEXT(cur, entry_list);
1185 if (cur->timeout == PFTM_UNLINKED) {
1186 /* free unlinked state */
1188 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1192 } else if (pf_state_expires(cur) <= time_second) {
1193 /* unlink and free expired state */
1194 pf_unlink_state(cur);
1196 if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1205 lockmgr(&pf_consistency_lock, LK_RELEASE);
1210 pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1212 if (aw->type != PF_ADDR_TABLE)
1214 if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1220 pf_tbladdr_remove(struct pf_addr_wrap *aw)
1222 if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1224 pfr_detach_table(aw->p.tbl);
1229 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1231 struct pfr_ktable *kt = aw->p.tbl;
1233 if (aw->type != PF_ADDR_TABLE || kt == NULL)
1235 if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1236 kt = kt->pfrkt_root;
1238 aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1243 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1248 u_int32_t a = ntohl(addr->addr32[0]);
1249 kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1261 u_int8_t i, curstart = 255, curend = 0,
1262 maxstart = 0, maxend = 0;
1263 for (i = 0; i < 8; i++) {
1264 if (!addr->addr16[i]) {
1265 if (curstart == 255)
1271 if ((curend - curstart) >
1272 (maxend - maxstart)) {
1273 maxstart = curstart;
1280 for (i = 0; i < 8; i++) {
1281 if (i >= maxstart && i <= maxend) {
1290 b = ntohs(addr->addr16[i]);
1307 pf_print_state(struct pf_state *s)
1309 pf_print_state_parts(s, NULL, NULL);
1313 pf_print_state_parts(struct pf_state *s,
1314 struct pf_state_key *skwp, struct pf_state_key *sksp)
1316 struct pf_state_key *skw, *sks;
1317 u_int8_t proto, dir;
1319 /* Do our best to fill these, but they're skipped if NULL */
1320 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1321 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1322 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1323 dir = s ? s->direction : 0;
1335 case IPPROTO_ICMPV6:
1339 kprintf("%u ", skw->proto);
1352 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1354 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1357 kprintf(" stack: ");
1359 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1361 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1366 if (proto == IPPROTO_TCP) {
1367 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1368 s->src.seqlo, s->src.seqhi,
1369 s->src.max_win, s->src.seqdiff);
1370 if (s->src.wscale && s->dst.wscale)
1371 kprintf(" wscale=%u",
1372 s->src.wscale & PF_WSCALE_MASK);
1374 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1375 s->dst.seqlo, s->dst.seqhi,
1376 s->dst.max_win, s->dst.seqdiff);
1377 if (s->src.wscale && s->dst.wscale)
1378 kprintf(" wscale=%u",
1379 s->dst.wscale & PF_WSCALE_MASK);
1382 kprintf(" %u:%u", s->src.state, s->dst.state);
1387 pf_print_flags(u_int8_t f)
1409 #define PF_SET_SKIP_STEPS(i) \
1411 while (head[i] != cur) { \
1412 head[i]->skip[i].ptr = cur; \
1413 head[i] = TAILQ_NEXT(head[i], entries); \
1418 pf_calc_skip_steps(struct pf_rulequeue *rules)
1420 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1423 cur = TAILQ_FIRST(rules);
1425 for (i = 0; i < PF_SKIP_COUNT; ++i)
1427 while (cur != NULL) {
1429 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1430 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1431 if (cur->direction != prev->direction)
1432 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1433 if (cur->af != prev->af)
1434 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1435 if (cur->proto != prev->proto)
1436 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1437 if (cur->src.neg != prev->src.neg ||
1438 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1439 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1440 if (cur->src.port[0] != prev->src.port[0] ||
1441 cur->src.port[1] != prev->src.port[1] ||
1442 cur->src.port_op != prev->src.port_op)
1443 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1444 if (cur->dst.neg != prev->dst.neg ||
1445 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1446 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1447 if (cur->dst.port[0] != prev->dst.port[0] ||
1448 cur->dst.port[1] != prev->dst.port[1] ||
1449 cur->dst.port_op != prev->dst.port_op)
1450 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1453 cur = TAILQ_NEXT(cur, entries);
1455 for (i = 0; i < PF_SKIP_COUNT; ++i)
1456 PF_SET_SKIP_STEPS(i);
1460 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1462 if (aw1->type != aw2->type)
1464 switch (aw1->type) {
1465 case PF_ADDR_ADDRMASK:
1467 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1469 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1472 case PF_ADDR_DYNIFTL:
1473 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1474 case PF_ADDR_NOROUTE:
1475 case PF_ADDR_URPFFAILED:
1478 return (aw1->p.tbl != aw2->p.tbl);
1479 case PF_ADDR_RTLABEL:
1480 return (aw1->v.rtlabel != aw2->v.rtlabel);
1482 kprintf("invalid address type: %d\n", aw1->type);
1488 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1494 l = cksum + old - new;
1495 l = (l >> 16) + (l & 65535);
1503 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1504 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1509 PF_ACPY(&ao, a, af);
1517 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1518 ao.addr16[0], an->addr16[0], 0),
1519 ao.addr16[1], an->addr16[1], 0);
1521 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1522 ao.addr16[0], an->addr16[0], u),
1523 ao.addr16[1], an->addr16[1], u),
1529 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1530 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1531 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1532 ao.addr16[0], an->addr16[0], u),
1533 ao.addr16[1], an->addr16[1], u),
1534 ao.addr16[2], an->addr16[2], u),
1535 ao.addr16[3], an->addr16[3], u),
1536 ao.addr16[4], an->addr16[4], u),
1537 ao.addr16[5], an->addr16[5], u),
1538 ao.addr16[6], an->addr16[6], u),
1539 ao.addr16[7], an->addr16[7], u),
1547 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
1549 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1553 memcpy(&ao, a, sizeof(ao));
1554 memcpy(a, &an, sizeof(u_int32_t));
1555 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1556 ao % 65536, an % 65536, u);
1561 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1565 PF_ACPY(&ao, a, AF_INET6);
1566 PF_ACPY(a, an, AF_INET6);
1568 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1569 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1570 pf_cksum_fixup(pf_cksum_fixup(*c,
1571 ao.addr16[0], an->addr16[0], u),
1572 ao.addr16[1], an->addr16[1], u),
1573 ao.addr16[2], an->addr16[2], u),
1574 ao.addr16[3], an->addr16[3], u),
1575 ao.addr16[4], an->addr16[4], u),
1576 ao.addr16[5], an->addr16[5], u),
1577 ao.addr16[6], an->addr16[6], u),
1578 ao.addr16[7], an->addr16[7], u);
1583 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1584 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1585 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1587 struct pf_addr oia, ooa;
1589 PF_ACPY(&oia, ia, af);
1591 PF_ACPY(&ooa, oa, af);
1593 /* Change inner protocol port, fix inner protocol checksum. */
1595 u_int16_t oip = *ip;
1602 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
1603 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1605 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1607 /* Change inner ip address, fix inner ip and icmp checksums. */
1608 PF_ACPY(ia, na, af);
1612 u_int32_t oh2c = *h2c;
1614 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1615 oia.addr16[0], ia->addr16[0], 0),
1616 oia.addr16[1], ia->addr16[1], 0);
1617 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1618 oia.addr16[0], ia->addr16[0], 0),
1619 oia.addr16[1], ia->addr16[1], 0);
1620 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1626 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1627 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1628 pf_cksum_fixup(pf_cksum_fixup(*ic,
1629 oia.addr16[0], ia->addr16[0], u),
1630 oia.addr16[1], ia->addr16[1], u),
1631 oia.addr16[2], ia->addr16[2], u),
1632 oia.addr16[3], ia->addr16[3], u),
1633 oia.addr16[4], ia->addr16[4], u),
1634 oia.addr16[5], ia->addr16[5], u),
1635 oia.addr16[6], ia->addr16[6], u),
1636 oia.addr16[7], ia->addr16[7], u);
1640 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
1642 PF_ACPY(oa, na, af);
1646 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
1647 ooa.addr16[0], oa->addr16[0], 0),
1648 ooa.addr16[1], oa->addr16[1], 0);
1653 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1654 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1655 pf_cksum_fixup(pf_cksum_fixup(*ic,
1656 ooa.addr16[0], oa->addr16[0], u),
1657 ooa.addr16[1], oa->addr16[1], u),
1658 ooa.addr16[2], oa->addr16[2], u),
1659 ooa.addr16[3], oa->addr16[3], u),
1660 ooa.addr16[4], oa->addr16[4], u),
1661 ooa.addr16[5], oa->addr16[5], u),
1662 ooa.addr16[6], oa->addr16[6], u),
1663 ooa.addr16[7], oa->addr16[7], u);
1672 * Need to modulate the sequence numbers in the TCP SACK option
1673 * (credits to Krzysztof Pfaff for report and patch)
1676 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
1677 struct tcphdr *th, struct pf_state_peer *dst)
1679 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
1680 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
1681 int copyback = 0, i, olen;
1682 struct raw_sackblock sack;
1684 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
1685 if (hlen < TCPOLEN_SACKLEN ||
1686 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
1689 while (hlen >= TCPOLEN_SACKLEN) {
1692 case TCPOPT_EOL: /* FALLTHROUGH */
1700 if (olen >= TCPOLEN_SACKLEN) {
1701 for (i = 2; i + TCPOLEN_SACK <= olen;
1702 i += TCPOLEN_SACK) {
1703 memcpy(&sack, &opt[i], sizeof(sack));
1704 pf_change_a(&sack.rblk_start, &th->th_sum,
1705 htonl(ntohl(sack.rblk_start) -
1707 pf_change_a(&sack.rblk_end, &th->th_sum,
1708 htonl(ntohl(sack.rblk_end) -
1710 memcpy(&opt[i], &sack, sizeof(sack));
1724 m_copyback(m, off + sizeof(*th), thoptlen, opts);
1729 pf_send_tcp(const struct pf_rule *r, sa_family_t af,
1730 const struct pf_addr *saddr, const struct pf_addr *daddr,
1731 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
1732 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
1733 u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
1738 struct ip *h = NULL;
1741 struct ip6_hdr *h6 = NULL;
1743 struct tcphdr *th = NULL;
1746 ASSERT_LWKT_TOKEN_HELD(&pf_token);
1748 /* maximum segment size tcp option */
1749 tlen = sizeof(struct tcphdr);
1756 len = sizeof(struct ip) + tlen;
1761 len = sizeof(struct ip6_hdr) + tlen;
1767 * Create outgoing mbuf.
1769 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1770 * so make sure pf.flags is clear.
1772 m = m_gethdr(MB_DONTWAIT, MT_HEADER);
1777 m->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1778 m->m_pkthdr.pf.flags = 0;
1779 m->m_pkthdr.pf.tag = rtag;
1780 /* XXX Recheck when upgrading to > 4.4 */
1781 m->m_pkthdr.pf.statekey = NULL;
1782 if (r != NULL && r->rtableid >= 0)
1783 m->m_pkthdr.pf.rtableid = r->rtableid;
1786 if (r != NULL && r->qid) {
1787 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1788 m->m_pkthdr.pf.qid = r->qid;
1789 m->m_pkthdr.pf.ecn_af = af;
1790 m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
1793 m->m_data += max_linkhdr;
1794 m->m_pkthdr.len = m->m_len = len;
1795 m->m_pkthdr.rcvif = NULL;
1796 bzero(m->m_data, len);
1800 h = mtod(m, struct ip *);
1802 /* IP header fields included in the TCP checksum */
1803 h->ip_p = IPPROTO_TCP;
1805 h->ip_src.s_addr = saddr->v4.s_addr;
1806 h->ip_dst.s_addr = daddr->v4.s_addr;
1808 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
1813 h6 = mtod(m, struct ip6_hdr *);
1815 /* IP header fields included in the TCP checksum */
1816 h6->ip6_nxt = IPPROTO_TCP;
1817 h6->ip6_plen = htons(tlen);
1818 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
1819 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
1821 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
1827 th->th_sport = sport;
1828 th->th_dport = dport;
1829 th->th_seq = htonl(seq);
1830 th->th_ack = htonl(ack);
1831 th->th_off = tlen >> 2;
1832 th->th_flags = flags;
1833 th->th_win = htons(win);
1836 opt = (char *)(th + 1);
1837 opt[0] = TCPOPT_MAXSEG;
1840 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
1847 th->th_sum = in_cksum(m, len);
1849 /* Finish the IP header */
1851 h->ip_hl = sizeof(*h) >> 2;
1852 h->ip_tos = IPTOS_LOWDELAY;
1854 h->ip_off = path_mtu_discovery ? IP_DF : 0;
1855 h->ip_ttl = ttl ? ttl : ip_defttl;
1858 lwkt_reltoken(&pf_token);
1859 ip_output(m, NULL, NULL, 0, NULL, NULL);
1860 lwkt_gettoken(&pf_token);
1864 struct ether_header *e = (void *)ro.ro_dst.sa_data;
1872 ro.ro_dst.sa_len = sizeof(ro.ro_dst);
1873 ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
1874 bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
1875 bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
1876 e->ether_type = eh->ether_type;
1877 /* XXX_IMPORT: later */
1878 lwkt_reltoken(&pf_token);
1879 ip_output(m, NULL, &ro, 0, NULL, NULL);
1880 lwkt_gettoken(&pf_token);
1887 th->th_sum = in6_cksum(m, IPPROTO_TCP,
1888 sizeof(struct ip6_hdr), tlen);
1890 h6->ip6_vfc |= IPV6_VERSION;
1891 h6->ip6_hlim = IPV6_DEFHLIM;
1893 lwkt_reltoken(&pf_token);
1894 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1895 lwkt_gettoken(&pf_token);
1902 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
1908 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1909 * so make sure pf.flags is clear.
1911 if ((m0 = m_copy(m, 0, M_COPYALL)) == NULL)
1914 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1915 m0->m_pkthdr.pf.flags = 0;
1916 /* XXX Re-Check when Upgrading to > 4.4 */
1917 m0->m_pkthdr.pf.statekey = NULL;
1919 if (r->rtableid >= 0)
1920 m0->m_pkthdr.pf.rtableid = r->rtableid;
1924 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1925 m0->m_pkthdr.pf.qid = r->qid;
1926 m0->m_pkthdr.pf.ecn_af = af;
1927 m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
1934 icmp_error(m0, type, code, 0, 0);
1939 icmp6_error(m0, type, code, 0);
1946 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
1947 * If n is 0, they match if they are equal. If n is != 0, they match if they
1951 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
1952 struct pf_addr *b, sa_family_t af)
1959 if ((a->addr32[0] & m->addr32[0]) ==
1960 (b->addr32[0] & m->addr32[0]))
1966 if (((a->addr32[0] & m->addr32[0]) ==
1967 (b->addr32[0] & m->addr32[0])) &&
1968 ((a->addr32[1] & m->addr32[1]) ==
1969 (b->addr32[1] & m->addr32[1])) &&
1970 ((a->addr32[2] & m->addr32[2]) ==
1971 (b->addr32[2] & m->addr32[2])) &&
1972 ((a->addr32[3] & m->addr32[3]) ==
1973 (b->addr32[3] & m->addr32[3])))
1992 * Return 1 if b <= a <= e, otherwise return 0.
1995 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
1996 struct pf_addr *a, sa_family_t af)
2001 if ((a->addr32[0] < b->addr32[0]) ||
2002 (a->addr32[0] > e->addr32[0]))
2011 for (i = 0; i < 4; ++i)
2012 if (a->addr32[i] > b->addr32[i])
2014 else if (a->addr32[i] < b->addr32[i])
2017 for (i = 0; i < 4; ++i)
2018 if (a->addr32[i] < e->addr32[i])
2020 else if (a->addr32[i] > e->addr32[i])
2030 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2034 return ((p > a1) && (p < a2));
2036 return ((p < a1) || (p > a2));
2038 return ((p >= a1) && (p <= a2));
2052 return (0); /* never reached */
2056 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2061 return (pf_match(op, a1, a2, p));
2065 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2067 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2069 return (pf_match(op, a1, a2, u));
2073 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2075 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2077 return (pf_match(op, a1, a2, g));
2081 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
2084 *tag = m->m_pkthdr.pf.tag;
2086 return ((!r->match_tag_not && r->match_tag == *tag) ||
2087 (r->match_tag_not && r->match_tag != *tag));
2091 pf_tag_packet(struct mbuf *m, int tag, int rtableid)
2093 if (tag <= 0 && rtableid < 0)
2097 m->m_pkthdr.pf.tag = tag;
2099 m->m_pkthdr.pf.rtableid = rtableid;
2105 pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
2106 struct pf_rule **r, struct pf_rule **a, int *match)
2108 struct pf_anchor_stackframe *f;
2110 (*r)->anchor->match = 0;
2113 if (*depth >= NELEM(pf_anchor_stack)) {
2114 kprintf("pf_step_into_anchor: stack overflow\n");
2115 *r = TAILQ_NEXT(*r, entries);
2117 } else if (*depth == 0 && a != NULL)
2119 f = pf_anchor_stack + (*depth)++;
2122 if ((*r)->anchor_wildcard) {
2123 f->parent = &(*r)->anchor->children;
2124 if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
2129 *rs = &f->child->ruleset;
2133 *rs = &(*r)->anchor->ruleset;
2135 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2139 pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
2140 struct pf_rule **r, struct pf_rule **a, int *match)
2142 struct pf_anchor_stackframe *f;
2148 f = pf_anchor_stack + *depth - 1;
2149 if (f->parent != NULL && f->child != NULL) {
2150 if (f->child->match ||
2151 (match != NULL && *match)) {
2152 f->r->anchor->match = 1;
2155 f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
2156 if (f->child != NULL) {
2157 *rs = &f->child->ruleset;
2158 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2166 if (*depth == 0 && a != NULL)
2169 if (f->r->anchor->match || (match != NULL && *match))
2170 quick = f->r->quick;
2171 *r = TAILQ_NEXT(f->r, entries);
2172 } while (*r == NULL);
2179 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2180 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2185 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2186 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2190 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2191 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2192 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2193 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2194 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2195 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2196 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2197 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2203 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2208 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2212 if (addr->addr32[3] == 0xffffffff) {
2213 addr->addr32[3] = 0;
2214 if (addr->addr32[2] == 0xffffffff) {
2215 addr->addr32[2] = 0;
2216 if (addr->addr32[1] == 0xffffffff) {
2217 addr->addr32[1] = 0;
2219 htonl(ntohl(addr->addr32[0]) + 1);
2222 htonl(ntohl(addr->addr32[1]) + 1);
2225 htonl(ntohl(addr->addr32[2]) + 1);
2228 htonl(ntohl(addr->addr32[3]) + 1);
2234 #define mix(a,b,c) \
2236 a -= b; a -= c; a ^= (c >> 13); \
2237 b -= c; b -= a; b ^= (a << 8); \
2238 c -= a; c -= b; c ^= (b >> 13); \
2239 a -= b; a -= c; a ^= (c >> 12); \
2240 b -= c; b -= a; b ^= (a << 16); \
2241 c -= a; c -= b; c ^= (b >> 5); \
2242 a -= b; a -= c; a ^= (c >> 3); \
2243 b -= c; b -= a; b ^= (a << 10); \
2244 c -= a; c -= b; c ^= (b >> 15); \
2248 * hash function based on bridge_hash in if_bridge.c
2251 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2252 struct pf_poolhashkey *key, sa_family_t af)
2254 u_int32_t a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2259 a += inaddr->addr32[0];
2262 hash->addr32[0] = c + key->key32[2];
2267 a += inaddr->addr32[0];
2268 b += inaddr->addr32[2];
2270 hash->addr32[0] = c;
2271 a += inaddr->addr32[1];
2272 b += inaddr->addr32[3];
2275 hash->addr32[1] = c;
2276 a += inaddr->addr32[2];
2277 b += inaddr->addr32[1];
2280 hash->addr32[2] = c;
2281 a += inaddr->addr32[3];
2282 b += inaddr->addr32[0];
2285 hash->addr32[3] = c;
2292 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2293 struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2295 unsigned char hash[16];
2296 struct pf_pool *rpool = &r->rpool;
2297 struct pf_addr *raddr = &rpool->cur->addr.v.a.addr;
2298 struct pf_addr *rmask = &rpool->cur->addr.v.a.mask;
2299 struct pf_pooladdr *acur = rpool->cur;
2300 struct pf_src_node k;
2302 if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2303 (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2305 PF_ACPY(&k.addr, saddr, af);
2306 if (r->rule_flag & PFRULE_RULESRCTRACK ||
2307 r->rpool.opts & PF_POOL_STICKYADDR)
2311 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2312 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
2313 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2314 PF_ACPY(naddr, &(*sn)->raddr, af);
2315 if (pf_status.debug >= PF_DEBUG_MISC) {
2316 kprintf("pf_map_addr: src tracking maps ");
2317 pf_print_host(&k.addr, 0, af);
2319 pf_print_host(naddr, 0, af);
2326 if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
2328 if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2332 if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
2333 (rpool->opts & PF_POOL_TYPEMASK) !=
2336 raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
2337 rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
2342 if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
2343 (rpool->opts & PF_POOL_TYPEMASK) !=
2346 raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
2347 rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
2351 } else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2352 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2353 return (1); /* unsupported */
2355 raddr = &rpool->cur->addr.v.a.addr;
2356 rmask = &rpool->cur->addr.v.a.mask;
2359 switch (rpool->opts & PF_POOL_TYPEMASK) {
2361 PF_ACPY(naddr, raddr, af);
2363 case PF_POOL_BITMASK:
2364 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2366 case PF_POOL_RANDOM:
2367 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2371 rpool->counter.addr32[0] = htonl(karc4random());
2376 if (rmask->addr32[3] != 0xffffffff)
2377 rpool->counter.addr32[3] =
2378 htonl(karc4random());
2381 if (rmask->addr32[2] != 0xffffffff)
2382 rpool->counter.addr32[2] =
2383 htonl(karc4random());
2386 if (rmask->addr32[1] != 0xffffffff)
2387 rpool->counter.addr32[1] =
2388 htonl(karc4random());
2391 if (rmask->addr32[0] != 0xffffffff)
2392 rpool->counter.addr32[0] =
2393 htonl(karc4random());
2397 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2398 PF_ACPY(init_addr, naddr, af);
2401 PF_AINC(&rpool->counter, af);
2402 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2405 case PF_POOL_SRCHASH:
2406 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2407 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2409 case PF_POOL_ROUNDROBIN:
2410 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2411 if (!pfr_pool_get(rpool->cur->addr.p.tbl,
2412 &rpool->tblidx, &rpool->counter,
2413 &raddr, &rmask, af))
2415 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2416 if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2417 &rpool->tblidx, &rpool->counter,
2418 &raddr, &rmask, af))
2420 } else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
2424 if ((rpool->cur = TAILQ_NEXT(rpool->cur, entries)) == NULL)
2425 rpool->cur = TAILQ_FIRST(&rpool->list);
2426 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2428 if (pfr_pool_get(rpool->cur->addr.p.tbl,
2429 &rpool->tblidx, &rpool->counter,
2430 &raddr, &rmask, af)) {
2431 /* table contains no address of type 'af' */
2432 if (rpool->cur != acur)
2436 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2438 if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2439 &rpool->tblidx, &rpool->counter,
2440 &raddr, &rmask, af)) {
2441 /* table contains no address of type 'af' */
2442 if (rpool->cur != acur)
2447 raddr = &rpool->cur->addr.v.a.addr;
2448 rmask = &rpool->cur->addr.v.a.mask;
2449 PF_ACPY(&rpool->counter, raddr, af);
2453 PF_ACPY(naddr, &rpool->counter, af);
2454 if (init_addr != NULL && PF_AZERO(init_addr, af))
2455 PF_ACPY(init_addr, naddr, af);
2456 PF_AINC(&rpool->counter, af);
2460 PF_ACPY(&(*sn)->raddr, naddr, af);
2462 if (pf_status.debug >= PF_DEBUG_MISC &&
2463 (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2464 kprintf("pf_map_addr: selected address ");
2465 pf_print_host(naddr, 0, af);
2473 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
2474 struct pf_addr *saddr, struct pf_addr *daddr, u_int16_t dport,
2475 struct pf_addr *naddr, u_int16_t *nport, u_int16_t low, u_int16_t high,
2476 struct pf_src_node **sn)
2478 struct pf_state_key_cmp key;
2479 struct pf_addr init_addr;
2482 bzero(&init_addr, sizeof(init_addr));
2483 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2486 if (proto == IPPROTO_ICMP) {
2494 PF_ACPY(&key.addr[1], daddr, key.af);
2495 PF_ACPY(&key.addr[0], naddr, key.af);
2496 key.port[1] = dport;
2499 * port search; start random, step;
2500 * similar 2 portloop in in_pcbbind
2502 if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
2503 proto == IPPROTO_ICMP)) {
2504 key.port[0] = dport;
2505 if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
2507 } else if (low == 0 && high == 0) {
2508 key.port[0] = *nport;
2509 if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
2511 } else if (low == high) {
2512 key.port[0] = htons(low);
2513 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2514 *nport = htons(low);
2526 cut = htonl(karc4random()) % (1 + high - low) + low;
2527 /* low <= cut <= high */
2528 for (tmp = cut; tmp <= high; ++(tmp)) {
2529 key.port[0] = htons(tmp);
2530 if (pf_find_state_all(&key, PF_IN, NULL) ==
2531 NULL && !in_baddynamic(tmp, proto)) {
2532 *nport = htons(tmp);
2536 for (tmp = cut - 1; tmp >= low; --(tmp)) {
2537 key.port[0] = htons(tmp);
2538 if (pf_find_state_all(&key, PF_IN, NULL) ==
2539 NULL && !in_baddynamic(tmp, proto)) {
2540 *nport = htons(tmp);
2546 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
2547 case PF_POOL_RANDOM:
2548 case PF_POOL_ROUNDROBIN:
2549 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2553 case PF_POOL_SRCHASH:
2554 case PF_POOL_BITMASK:
2558 } while (! PF_AEQ(&init_addr, naddr, af) );
2559 return (1); /* none available */
2563 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
2564 int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
2565 struct pf_addr *daddr, u_int16_t dport, int rs_num)
2567 struct pf_rule *r, *rm = NULL;
2568 struct pf_ruleset *ruleset = NULL;
2573 r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
2574 while (r && rm == NULL) {
2575 struct pf_rule_addr *src = NULL, *dst = NULL;
2576 struct pf_addr_wrap *xdst = NULL;
2578 if (r->action == PF_BINAT && direction == PF_IN) {
2580 if (r->rpool.cur != NULL)
2581 xdst = &r->rpool.cur->addr;
2588 if (pfi_kif_match(r->kif, kif) == r->ifnot)
2589 r = r->skip[PF_SKIP_IFP].ptr;
2590 else if (r->direction && r->direction != direction)
2591 r = r->skip[PF_SKIP_DIR].ptr;
2592 else if (r->af && r->af != pd->af)
2593 r = r->skip[PF_SKIP_AF].ptr;
2594 else if (r->proto && r->proto != pd->proto)
2595 r = r->skip[PF_SKIP_PROTO].ptr;
2596 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
2598 r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
2599 PF_SKIP_DST_ADDR].ptr;
2600 else if (src->port_op && !pf_match_port(src->port_op,
2601 src->port[0], src->port[1], sport))
2602 r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
2603 PF_SKIP_DST_PORT].ptr;
2604 else if (dst != NULL &&
2605 PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
2606 r = r->skip[PF_SKIP_DST_ADDR].ptr;
2607 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
2609 r = TAILQ_NEXT(r, entries);
2610 else if (dst != NULL && dst->port_op &&
2611 !pf_match_port(dst->port_op, dst->port[0],
2612 dst->port[1], dport))
2613 r = r->skip[PF_SKIP_DST_PORT].ptr;
2614 else if (r->match_tag && !pf_match_tag(m, r, &tag))
2615 r = TAILQ_NEXT(r, entries);
2616 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
2617 IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
2618 off, pd->hdr.tcp), r->os_fingerprint)))
2619 r = TAILQ_NEXT(r, entries);
2623 if (r->rtableid >= 0)
2624 rtableid = r->rtableid;
2625 if (r->anchor == NULL) {
2628 pf_step_into_anchor(&asd, &ruleset, rs_num,
2632 pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
2635 if (pf_tag_packet(m, tag, rtableid))
2637 if (rm != NULL && (rm->action == PF_NONAT ||
2638 rm->action == PF_NORDR || rm->action == PF_NOBINAT))
2644 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
2645 struct pfi_kif *kif, struct pf_src_node **sn,
2646 struct pf_state_key **skw, struct pf_state_key **sks,
2647 struct pf_state_key **skp, struct pf_state_key **nkp,
2648 struct pf_addr *saddr, struct pf_addr *daddr,
2649 u_int16_t sport, u_int16_t dport)
2651 struct pf_rule *r = NULL;
2654 if (direction == PF_OUT) {
2655 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2656 sport, daddr, dport, PF_RULESET_BINAT);
2658 r = pf_match_translation(pd, m, off, direction, kif,
2659 saddr, sport, daddr, dport, PF_RULESET_NAT);
2661 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2662 sport, daddr, dport, PF_RULESET_RDR);
2664 r = pf_match_translation(pd, m, off, direction, kif,
2665 saddr, sport, daddr, dport, PF_RULESET_BINAT);
2669 struct pf_addr *naddr;
2672 if (pf_state_key_setup(pd, r, skw, sks, skp, nkp,
2673 saddr, daddr, sport, dport))
2676 /* XXX We only modify one side for now. */
2677 naddr = &(*nkp)->addr[1];
2678 nport = &(*nkp)->port[1];
2681 * NOTE: Currently all translations will clear
2682 * BRIDGE_MBUF_TAGGED, telling the bridge to
2683 * ignore the original input encapsulation.
2685 switch (r->action) {
2691 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
2692 if (pf_get_sport(pd->af, pd->proto, r, saddr,
2693 daddr, dport, naddr, nport, r->rpool.proxy_port[0],
2694 r->rpool.proxy_port[1], sn)) {
2695 DPFPRINTF(PF_DEBUG_MISC,
2696 ("pf: NAT proxy port allocation "
2698 r->rpool.proxy_port[0],
2699 r->rpool.proxy_port[1]));
2704 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
2705 switch (direction) {
2707 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
2711 if (r->rpool.cur->addr.p.dyn->
2715 &r->rpool.cur->addr.p.dyn->
2717 &r->rpool.cur->addr.p.dyn->
2724 if (r->rpool.cur->addr.p.dyn->
2728 &r->rpool.cur->addr.p.dyn->
2730 &r->rpool.cur->addr.p.dyn->
2738 &r->rpool.cur->addr.v.a.addr,
2739 &r->rpool.cur->addr.v.a.mask,
2743 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
2747 if (r->src.addr.p.dyn->
2751 &r->src.addr.p.dyn->
2753 &r->src.addr.p.dyn->
2760 if (r->src.addr.p.dyn->
2764 &r->src.addr.p.dyn->
2766 &r->src.addr.p.dyn->
2774 &r->src.addr.v.a.addr,
2775 &r->src.addr.v.a.mask, daddr,
2781 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
2782 if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
2784 if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
2786 PF_POOLMASK(naddr, naddr,
2787 &r->rpool.cur->addr.v.a.mask, daddr,
2790 if (r->rpool.proxy_port[1]) {
2791 u_int32_t tmp_nport;
2793 tmp_nport = ((ntohs(dport) -
2794 ntohs(r->dst.port[0])) %
2795 (r->rpool.proxy_port[1] -
2796 r->rpool.proxy_port[0] + 1)) +
2797 r->rpool.proxy_port[0];
2799 /* wrap around if necessary */
2800 if (tmp_nport > 65535)
2802 *nport = htons((u_int16_t)tmp_nport);
2803 } else if (r->rpool.proxy_port[0])
2804 *nport = htons(r->rpool.proxy_port[0]);
2816 struct netmsg_hashlookup {
2817 struct netmsg_base base;
2818 struct inpcb **nm_pinp;
2819 struct inpcbinfo *nm_pcbinfo;
2820 struct pf_addr *nm_saddr;
2821 struct pf_addr *nm_daddr;
2827 #ifdef PF_SOCKET_LOOKUP_DOMSG
2829 in_pcblookup_hash_handler(netmsg_t msg)
2831 struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
2833 if (rmsg->nm_af == AF_INET)
2834 *rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
2835 rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
2836 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2839 *rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
2840 &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
2841 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2843 lwkt_replymsg(&rmsg->base.lmsg, 0);
2845 #endif /* PF_SOCKET_LOOKUP_DOMSG */
2850 pf_socket_lookup(int direction, struct pf_pdesc *pd)
2852 struct pf_addr *saddr, *daddr;
2853 u_int16_t sport, dport;
2854 struct inpcbinfo *pi;
2857 struct netmsg_hashlookup *msg = NULL;
2858 #ifdef PF_SOCKET_LOOKUP_DOMSG
2859 struct netmsg_hashlookup msg0;
2866 pd->lookup.uid = UID_MAX;
2867 pd->lookup.gid = GID_MAX;
2868 pd->lookup.pid = NO_PID;
2869 if (direction == PF_IN) {
2876 switch (pd->proto) {
2878 if (pd->hdr.tcp == NULL)
2880 sport = pd->hdr.tcp->th_sport;
2881 dport = pd->hdr.tcp->th_dport;
2883 pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
2884 pi = &tcbinfo[pi_cpu];
2887 * Our netstack runs lockless on MP systems
2888 * (only for TCP connections at the moment).
2890 * As we are not allowed to read another CPU's tcbinfo,
2891 * we have to ask that CPU via remote call to search the
2894 * Prepare a msg iff data belongs to another CPU.
2896 if (pi_cpu != mycpu->gd_cpuid) {
2897 #ifdef PF_SOCKET_LOOKUP_DOMSG
2901 * Following lwkt_domsg() is dangerous and could
2902 * lockup the network system, e.g.
2905 * netisr0 domsg to netisr1 (due to lookup)
2906 * netisr1 domsg to netisr0 (due to lookup)
2908 * We simply return -1 here, since we are probably
2909 * called before NAT, so the TCP packet should
2910 * already be on the correct CPU.
2913 netmsg_init(&msg->base, NULL, &curthread->td_msgport,
2914 0, in_pcblookup_hash_handler);
2915 msg->nm_pinp = &inp;
2916 msg->nm_pcbinfo = pi;
2917 msg->nm_saddr = saddr;
2918 msg->nm_sport = sport;
2919 msg->nm_daddr = daddr;
2920 msg->nm_dport = dport;
2921 msg->nm_af = pd->af;
2922 #else /* !PF_SOCKET_LOOKUP_DOMSG */
2923 kprintf("pf_socket_lookup: tcp packet not on the "
2924 "correct cpu %d, cur cpu %d\n",
2926 print_backtrace(-1);
2928 #endif /* PF_SOCKET_LOOKUP_DOMSG */
2933 if (pd->hdr.udp == NULL)
2935 sport = pd->hdr.udp->uh_sport;
2936 dport = pd->hdr.udp->uh_dport;
2942 if (direction != PF_IN) {
2954 * Query other CPU, second part
2956 * msg only gets initialized when:
2958 * 2) the info belongs to another CPU
2960 * Use some switch/case magic to avoid code duplication.
2965 inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
2966 &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
2972 /* FALLTHROUGH if SMP and on other CPU */
2977 lwkt_domsg(cpu_portfn(pi_cpu),
2978 &msg->base.lmsg, 0);
2982 inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
2983 dport, INPLOOKUP_WILDCARD, NULL);
2992 pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
2993 pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
2998 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3002 u_int8_t *opt, optlen;
3003 u_int8_t wscale = 0;
3005 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3006 if (hlen <= sizeof(struct tcphdr))
3008 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3010 opt = hdr + sizeof(struct tcphdr);
3011 hlen -= sizeof(struct tcphdr);
3021 if (wscale > TCP_MAX_WINSHIFT)
3022 wscale = TCP_MAX_WINSHIFT;
3023 wscale |= PF_WSCALE_FLAG;
3038 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3042 u_int8_t *opt, optlen;
3043 u_int16_t mss = tcp_mssdflt;
3045 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3046 if (hlen <= sizeof(struct tcphdr))
3048 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3050 opt = hdr + sizeof(struct tcphdr);
3051 hlen -= sizeof(struct tcphdr);
3052 while (hlen >= TCPOLEN_MAXSEG) {
3060 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3075 pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
3078 struct sockaddr_in *dst;
3082 struct sockaddr_in6 *dst6;
3083 struct route_in6 ro6;
3085 struct rtentry *rt = NULL;
3087 u_int16_t mss = tcp_mssdflt;
3092 hlen = sizeof(struct ip);
3093 bzero(&ro, sizeof(ro));
3094 dst = (struct sockaddr_in *)&ro.ro_dst;
3095 dst->sin_family = AF_INET;
3096 dst->sin_len = sizeof(*dst);
3097 dst->sin_addr = addr->v4;
3098 rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
3104 hlen = sizeof(struct ip6_hdr);
3105 bzero(&ro6, sizeof(ro6));
3106 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3107 dst6->sin6_family = AF_INET6;
3108 dst6->sin6_len = sizeof(*dst6);
3109 dst6->sin6_addr = addr->v6;
3110 rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
3116 if (rt && rt->rt_ifp) {
3117 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3118 mss = max(tcp_mssdflt, mss);
3121 mss = min(mss, offer);
3122 mss = max(mss, 64); /* sanity - at least max opt space */
3127 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3129 struct pf_rule *r = s->rule.ptr;
3132 if (!r->rt || r->rt == PF_FASTROUTE)
3134 switch (s->key[PF_SK_WIRE]->af) {
3137 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
3139 s->rt_kif = r->rpool.cur->kif;
3144 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
3146 s->rt_kif = r->rpool.cur->kif;
3153 pf_tcp_iss(struct pf_pdesc *pd)
3156 u_int32_t digest[4];
3158 if (pf_tcp_secret_init == 0) {
3159 karc4rand(pf_tcp_secret, sizeof(pf_tcp_secret));
3160 MD5Init(&pf_tcp_secret_ctx);
3161 MD5Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3162 sizeof(pf_tcp_secret));
3163 pf_tcp_secret_init = 1;
3165 ctx = pf_tcp_secret_ctx;
3167 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3168 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3169 if (pd->af == AF_INET6) {
3170 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3171 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3173 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3174 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3176 MD5Final((u_char *)digest, &ctx);
3177 pf_tcp_iss_off += 4096;
3178 return (digest[0] + pd->hdr.tcp->th_seq + pf_tcp_iss_off);
3182 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3183 struct pfi_kif *kif, struct mbuf *m, int off, void *h,
3184 struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
3185 struct ifqueue *ifq, struct inpcb *inp)
3187 struct pf_rule *nr = NULL;
3188 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
3189 sa_family_t af = pd->af;
3190 struct pf_rule *r, *a = NULL;
3191 struct pf_ruleset *ruleset = NULL;
3192 struct pf_src_node *nsn = NULL;
3193 struct tcphdr *th = pd->hdr.tcp;
3194 struct pf_state_key *skw = NULL, *sks = NULL;
3195 struct pf_state_key *sk = NULL, *nk = NULL;
3197 int rewrite = 0, hdrlen = 0;
3198 int tag = -1, rtableid = -1;
3202 u_int16_t sport = 0, dport = 0;
3203 u_int16_t nport = 0, bport = 0;
3204 u_int16_t bproto_sum = 0, bip_sum = 0;
3205 u_int8_t icmptype = 0, icmpcode = 0;
3208 if (direction == PF_IN && pf_check_congestion(ifq)) {
3209 REASON_SET(&reason, PFRES_CONGEST);
3214 pd->lookup.done = pf_socket_lookup(direction, pd);
3215 else if (debug_pfugidhack) {
3216 DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
3217 pd->lookup.done = pf_socket_lookup(direction, pd);
3220 switch (pd->proto) {
3222 sport = th->th_sport;
3223 dport = th->th_dport;
3224 hdrlen = sizeof(*th);
3227 sport = pd->hdr.udp->uh_sport;
3228 dport = pd->hdr.udp->uh_dport;
3229 hdrlen = sizeof(*pd->hdr.udp);
3233 if (pd->af != AF_INET)
3235 sport = dport = pd->hdr.icmp->icmp_id;
3236 hdrlen = sizeof(*pd->hdr.icmp);
3237 icmptype = pd->hdr.icmp->icmp_type;
3238 icmpcode = pd->hdr.icmp->icmp_code;
3240 if (icmptype == ICMP_UNREACH ||
3241 icmptype == ICMP_SOURCEQUENCH ||
3242 icmptype == ICMP_REDIRECT ||
3243 icmptype == ICMP_TIMXCEED ||
3244 icmptype == ICMP_PARAMPROB)
3249 case IPPROTO_ICMPV6:
3252 sport = dport = pd->hdr.icmp6->icmp6_id;
3253 hdrlen = sizeof(*pd->hdr.icmp6);
3254 icmptype = pd->hdr.icmp6->icmp6_type;
3255 icmpcode = pd->hdr.icmp6->icmp6_code;
3257 if (icmptype == ICMP6_DST_UNREACH ||
3258 icmptype == ICMP6_PACKET_TOO_BIG ||
3259 icmptype == ICMP6_TIME_EXCEEDED ||
3260 icmptype == ICMP6_PARAM_PROB)
3265 sport = dport = hdrlen = 0;
3269 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3271 bport = nport = sport;
3272 /* check packet for BINAT/NAT/RDR */
3273 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn,
3274 &skw, &sks, &sk, &nk, saddr, daddr, sport, dport)) != NULL) {
3275 if (nk == NULL || sk == NULL) {
3276 REASON_SET(&reason, PFRES_MEMORY);
3281 bip_sum = *pd->ip_sum;
3283 switch (pd->proto) {
3285 bproto_sum = th->th_sum;
3286 pd->proto_sum = &th->th_sum;
3288 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3289 nk->port[pd->sidx] != sport) {
3290 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3291 &th->th_sum, &nk->addr[pd->sidx],
3292 nk->port[pd->sidx], 0, af);
3293 pd->sport = &th->th_sport;
3294 sport = th->th_sport;
3297 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3298 nk->port[pd->didx] != dport) {
3299 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3300 &th->th_sum, &nk->addr[pd->didx],
3301 nk->port[pd->didx], 0, af);
3302 dport = th->th_dport;
3303 pd->dport = &th->th_dport;
3308 bproto_sum = pd->hdr.udp->uh_sum;
3309 pd->proto_sum = &pd->hdr.udp->uh_sum;
3311 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3312 nk->port[pd->sidx] != sport) {
3313 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3314 pd->ip_sum, &pd->hdr.udp->uh_sum,
3315 &nk->addr[pd->sidx],
3316 nk->port[pd->sidx], 1, af);
3317 sport = pd->hdr.udp->uh_sport;
3318 pd->sport = &pd->hdr.udp->uh_sport;
3321 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3322 nk->port[pd->didx] != dport) {
3323 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3324 pd->ip_sum, &pd->hdr.udp->uh_sum,
3325 &nk->addr[pd->didx],
3326 nk->port[pd->didx], 1, af);
3327 dport = pd->hdr.udp->uh_dport;
3328 pd->dport = &pd->hdr.udp->uh_dport;
3334 nk->port[0] = nk->port[1];
3335 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3336 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3337 nk->addr[pd->sidx].v4.s_addr, 0);
3339 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3340 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3341 nk->addr[pd->didx].v4.s_addr, 0);
3343 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3344 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3345 pd->hdr.icmp->icmp_cksum, sport,
3347 pd->hdr.icmp->icmp_id = nk->port[1];
3348 pd->sport = &pd->hdr.icmp->icmp_id;
3350 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3354 case IPPROTO_ICMPV6:
3355 nk->port[0] = nk->port[1];
3356 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3357 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3358 &nk->addr[pd->sidx], 0);
3360 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3361 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3362 &nk->addr[pd->didx], 0);
3371 &nk->addr[pd->sidx], AF_INET))
3372 pf_change_a(&saddr->v4.s_addr,
3374 nk->addr[pd->sidx].v4.s_addr, 0);
3377 &nk->addr[pd->didx], AF_INET))
3378 pf_change_a(&daddr->v4.s_addr,
3380 nk->addr[pd->didx].v4.s_addr, 0);
3386 &nk->addr[pd->sidx], AF_INET6))
3387 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3390 &nk->addr[pd->didx], AF_INET6))
3391 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3404 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3405 r = r->skip[PF_SKIP_IFP].ptr;
3406 else if (r->direction && r->direction != direction)
3407 r = r->skip[PF_SKIP_DIR].ptr;
3408 else if (r->af && r->af != af)
3409 r = r->skip[PF_SKIP_AF].ptr;
3410 else if (r->proto && r->proto != pd->proto)
3411 r = r->skip[PF_SKIP_PROTO].ptr;
3412 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3414 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3415 /* tcp/udp only. port_op always 0 in other cases */
3416 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3417 r->src.port[0], r->src.port[1], sport))
3418 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3419 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3421 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3422 /* tcp/udp only. port_op always 0 in other cases */
3423 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3424 r->dst.port[0], r->dst.port[1], dport))
3425 r = r->skip[PF_SKIP_DST_PORT].ptr;
3426 /* icmp only. type always 0 in other cases */
3427 else if (r->type && r->type != icmptype + 1)
3428 r = TAILQ_NEXT(r, entries);
3429 /* icmp only. type always 0 in other cases */
3430 else if (r->code && r->code != icmpcode + 1)
3431 r = TAILQ_NEXT(r, entries);
3432 else if (r->tos && !(r->tos == pd->tos))
3433 r = TAILQ_NEXT(r, entries);
3434 else if (r->rule_flag & PFRULE_FRAGMENT)
3435 r = TAILQ_NEXT(r, entries);
3436 else if (pd->proto == IPPROTO_TCP &&
3437 (r->flagset & th->th_flags) != r->flags)
3438 r = TAILQ_NEXT(r, entries);
3439 /* tcp/udp only. uid.op always 0 in other cases */
3440 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3441 pf_socket_lookup(direction, pd), 1)) &&
3442 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3444 r = TAILQ_NEXT(r, entries);
3445 /* tcp/udp only. gid.op always 0 in other cases */
3446 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3447 pf_socket_lookup(direction, pd), 1)) &&
3448 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3450 r = TAILQ_NEXT(r, entries);
3452 r->prob <= karc4random())
3453 r = TAILQ_NEXT(r, entries);
3454 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3455 r = TAILQ_NEXT(r, entries);
3456 else if (r->os_fingerprint != PF_OSFP_ANY &&
3457 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3458 pf_osfp_fingerprint(pd, m, off, th),
3459 r->os_fingerprint)))
3460 r = TAILQ_NEXT(r, entries);
3464 if (r->rtableid >= 0)
3465 rtableid = r->rtableid;
3466 if (r->anchor == NULL) {
3473 r = TAILQ_NEXT(r, entries);
3475 pf_step_into_anchor(&asd, &ruleset,
3476 PF_RULESET_FILTER, &r, &a, &match);
3478 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3479 PF_RULESET_FILTER, &r, &a, &match))
3486 REASON_SET(&reason, PFRES_MATCH);
3488 if (r->log || (nr != NULL && nr->log)) {
3490 m_copyback(m, off, hdrlen, pd->hdr.any);
3491 PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3495 if ((r->action == PF_DROP) &&
3496 ((r->rule_flag & PFRULE_RETURNRST) ||
3497 (r->rule_flag & PFRULE_RETURNICMP) ||
3498 (r->rule_flag & PFRULE_RETURN))) {
3499 /* undo NAT changes, if they have taken place */
3501 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3502 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3504 *pd->sport = sk->port[pd->sidx];
3506 *pd->dport = sk->port[pd->didx];
3508 *pd->proto_sum = bproto_sum;
3510 *pd->ip_sum = bip_sum;
3511 m_copyback(m, off, hdrlen, pd->hdr.any);
3513 if (pd->proto == IPPROTO_TCP &&
3514 ((r->rule_flag & PFRULE_RETURNRST) ||
3515 (r->rule_flag & PFRULE_RETURN)) &&
3516 !(th->th_flags & TH_RST)) {
3517 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3525 h4 = mtod(m, struct ip *);
3526 len = h4->ip_len - off;
3530 h6 = mtod(m, struct ip6_hdr *);
3531 len = h6->ip6_plen - (off - sizeof(*h6));
3536 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
3537 REASON_SET(&reason, PFRES_PROTCKSUM);
3539 if (th->th_flags & TH_SYN)
3541 if (th->th_flags & TH_FIN)
3543 pf_send_tcp(r, af, pd->dst,
3544 pd->src, th->th_dport, th->th_sport,
3545 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3546 r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
3548 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3550 pf_send_icmp(m, r->return_icmp >> 8,
3551 r->return_icmp & 255, af, r);
3552 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3554 pf_send_icmp(m, r->return_icmp6 >> 8,
3555 r->return_icmp6 & 255, af, r);
3558 if (r->action == PF_DROP)
3561 if (pf_tag_packet(m, tag, rtableid)) {
3562 REASON_SET(&reason, PFRES_MEMORY);
3566 if (!state_icmp && (r->keep_state || nr != NULL ||
3567 (pd->flags & PFDESC_TCP_NORM))) {
3569 action = pf_create_state(r, nr, a, pd, nsn, skw, sks, nk, sk, m,
3570 off, sport, dport, &rewrite, kif, sm, tag, bproto_sum,
3572 if (action != PF_PASS)
3576 /* copy back packet headers if we performed NAT operations */
3578 m_copyback(m, off, hdrlen, pd->hdr.any);
3584 kfree(sk, M_PFSTATEKEYPL);
3586 kfree(nk, M_PFSTATEKEYPL);
3591 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3592 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *skw,
3593 struct pf_state_key *sks, struct pf_state_key *nk, struct pf_state_key *sk,
3594 struct mbuf *m, int off, u_int16_t sport, u_int16_t dport, int *rewrite,
3595 struct pfi_kif *kif, struct pf_state **sm, int tag, u_int16_t bproto_sum,
3596 u_int16_t bip_sum, int hdrlen)
3598 struct pf_state *s = NULL;
3599 struct pf_src_node *sn = NULL;
3600 struct tcphdr *th = pd->hdr.tcp;
3601 u_int16_t mss = tcp_mssdflt;
3604 /* check maximums */
3605 if (r->max_states && (r->states_cur >= r->max_states)) {
3606 pf_status.lcounters[LCNT_STATES]++;
3607 REASON_SET(&reason, PFRES_MAXSTATES);
3610 /* src node for filter rule */
3611 if ((r->rule_flag & PFRULE_SRCTRACK ||
3612 r->rpool.opts & PF_POOL_STICKYADDR) &&
3613 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3614 REASON_SET(&reason, PFRES_SRCLIMIT);
3617 /* src node for translation rule */
3618 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3619 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3620 REASON_SET(&reason, PFRES_SRCLIMIT);
3623 s = kmalloc(sizeof(struct pf_state), M_PFSTATEPL, M_NOWAIT|M_ZERO);
3625 REASON_SET(&reason, PFRES_MEMORY);
3628 s->id = 0; /* XXX Do we really need that? not in OpenBSD */
3631 s->nat_rule.ptr = nr;
3633 STATE_INC_COUNTERS(s);
3635 s->state_flags |= PFSTATE_ALLOWOPTS;
3636 if (r->rule_flag & PFRULE_STATESLOPPY)
3637 s->state_flags |= PFSTATE_SLOPPY;
3638 s->log = r->log & PF_LOG_ALL;
3640 s->log |= nr->log & PF_LOG_ALL;
3641 switch (pd->proto) {
3643 s->src.seqlo = ntohl(th->th_seq);
3644 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3645 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3646 r->keep_state == PF_STATE_MODULATE) {
3647 /* Generate sequence number modulator */
3648 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3651 pf_change_a(&th->th_seq, &th->th_sum,
3652 htonl(s->src.seqlo + s->src.seqdiff), 0);
3656 if (th->th_flags & TH_SYN) {
3658 s->src.wscale = pf_get_wscale(m, off,
3659 th->th_off, pd->af);
3661 s->src.max_win = MAX(ntohs(th->th_win), 1);
3662 if (s->src.wscale & PF_WSCALE_MASK) {
3663 /* Remove scale factor from initial window */
3664 int win = s->src.max_win;
3665 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3666 s->src.max_win = (win - 1) >>
3667 (s->src.wscale & PF_WSCALE_MASK);
3669 if (th->th_flags & TH_FIN)
3673 s->src.state = TCPS_SYN_SENT;
3674 s->dst.state = TCPS_CLOSED;
3675 s->timeout = PFTM_TCP_FIRST_PACKET;
3678 s->src.state = PFUDPS_SINGLE;
3679 s->dst.state = PFUDPS_NO_TRAFFIC;
3680 s->timeout = PFTM_UDP_FIRST_PACKET;
3684 case IPPROTO_ICMPV6:
3686 s->timeout = PFTM_ICMP_FIRST_PACKET;
3689 s->src.state = PFOTHERS_SINGLE;
3690 s->dst.state = PFOTHERS_NO_TRAFFIC;
3691 s->timeout = PFTM_OTHER_FIRST_PACKET;
3694 s->creation = time_second;
3695 s->expire = time_second;
3699 s->src_node->states++;
3702 /* XXX We only modify one side for now. */
3703 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3704 s->nat_src_node = nsn;
3705 s->nat_src_node->states++;
3707 if (pd->proto == IPPROTO_TCP) {
3708 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3709 off, pd, th, &s->src, &s->dst)) {
3710 REASON_SET(&reason, PFRES_MEMORY);
3711 pf_src_tree_remove_state(s);
3712 STATE_DEC_COUNTERS(s);
3713 kfree(s, M_PFSTATEPL);
3716 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3717 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3718 &s->src, &s->dst, rewrite)) {
3719 /* This really shouldn't happen!!! */
3720 DPFPRINTF(PF_DEBUG_URGENT,
3721 ("pf_normalize_tcp_stateful failed on first pkt"));
3722 pf_normalize_tcp_cleanup(s);
3723 pf_src_tree_remove_state(s);
3724 STATE_DEC_COUNTERS(s);
3725 kfree(s, M_PFSTATEPL);
3729 s->direction = pd->dir;
3731 if (sk == NULL && pf_state_key_setup(pd, nr, &skw, &sks, &sk, &nk,
3732 pd->src, pd->dst, sport, dport))
3735 if (pf_state_insert(BOUND_IFACE(r, kif), skw, sks, s)) {
3736 if (pd->proto == IPPROTO_TCP)
3737 pf_normalize_tcp_cleanup(s);
3738 REASON_SET(&reason, PFRES_STATEINS);
3739 pf_src_tree_remove_state(s);
3740 STATE_DEC_COUNTERS(s);
3741 kfree(s, M_PFSTATEPL);
3746 pf_set_rt_ifp(s, pd->src); /* needs s->state_key set */
3751 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3752 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3753 s->src.state = PF_TCPS_PROXY_SRC;
3754 /* undo NAT changes, if they have taken place */
3756 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3757 if (pd->dir == PF_OUT)
3758 skt = s->key[PF_SK_STACK];
3759 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3760 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3762 *pd->sport = skt->port[pd->sidx];
3764 *pd->dport = skt->port[pd->didx];
3766 *pd->proto_sum = bproto_sum;
3768 *pd->ip_sum = bip_sum;
3769 m_copyback(m, off, hdrlen, pd->hdr.any);
3771 s->src.seqhi = htonl(karc4random());
3772 /* Find mss option */
3773 mss = pf_get_mss(m, off, th->th_off, pd->af);
3774 mss = pf_calc_mss(pd->src, pd->af, mss);
3775 mss = pf_calc_mss(pd->dst, pd->af, mss);
3777 pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
3778 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3779 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
3780 REASON_SET(&reason, PFRES_SYNPROXY);
3781 return (PF_SYNPROXY_DROP);
3788 kfree(sk, M_PFSTATEKEYPL);
3790 kfree(nk, M_PFSTATEKEYPL);
3792 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3793 RB_REMOVE(pf_src_tree, &tree_src_tracking, sn);
3794 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3795 pf_status.src_nodes--;
3796 kfree(sn, M_PFSRCTREEPL);
3798 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3799 RB_REMOVE(pf_src_tree, &tree_src_tracking, nsn);
3800 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3801 pf_status.src_nodes--;
3802 kfree(nsn, M_PFSRCTREEPL);
3808 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3809 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3810 struct pf_ruleset **rsm)
3812 struct pf_rule *r, *a = NULL;
3813 struct pf_ruleset *ruleset = NULL;
3814 sa_family_t af = pd->af;
3820 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3823 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3824 r = r->skip[PF_SKIP_IFP].ptr;
3825 else if (r->direction && r->direction != direction)
3826 r = r->skip[PF_SKIP_DIR].ptr;
3827 else if (r->af && r->af != af)
3828 r = r->skip[PF_SKIP_AF].ptr;
3829 else if (r->proto && r->proto != pd->proto)
3830 r = r->skip[PF_SKIP_PROTO].ptr;
3831 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3833 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3834 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3836 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3837 else if (r->tos && !(r->tos == pd->tos))
3838 r = TAILQ_NEXT(r, entries);
3839 else if (r->os_fingerprint != PF_OSFP_ANY)
3840 r = TAILQ_NEXT(r, entries);
3841 else if (pd->proto == IPPROTO_UDP &&
3842 (r->src.port_op || r->dst.port_op))
3843 r = TAILQ_NEXT(r, entries);
3844 else if (pd->proto == IPPROTO_TCP &&
3845 (r->src.port_op || r->dst.port_op || r->flagset))
3846 r = TAILQ_NEXT(r, entries);
3847 else if ((pd->proto == IPPROTO_ICMP ||
3848 pd->proto == IPPROTO_ICMPV6) &&
3849 (r->type || r->code))
3850 r = TAILQ_NEXT(r, entries);
3851 else if (r->prob && r->prob <= karc4random())
3852 r = TAILQ_NEXT(r, entries);
3853 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3854 r = TAILQ_NEXT(r, entries);
3856 if (r->anchor == NULL) {
3863 r = TAILQ_NEXT(r, entries);
3865 pf_step_into_anchor(&asd, &ruleset,
3866 PF_RULESET_FILTER, &r, &a, &match);
3868 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3869 PF_RULESET_FILTER, &r, &a, &match))
3876 REASON_SET(&reason, PFRES_MATCH);
3879 PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
3882 if (r->action != PF_PASS)
3885 if (pf_tag_packet(m, tag, -1)) {
3886 REASON_SET(&reason, PFRES_MEMORY);
3894 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3895 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3896 struct pf_pdesc *pd, u_short *reason, int *copyback)
3898 struct tcphdr *th = pd->hdr.tcp;
3899 u_int16_t win = ntohs(th->th_win);
3900 u_int32_t ack, end, seq, orig_seq;
3904 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3905 sws = src->wscale & PF_WSCALE_MASK;
3906 dws = dst->wscale & PF_WSCALE_MASK;
3911 * Sequence tracking algorithm from Guido van Rooij's paper:
3912 * http://www.madison-gurkha.com/publications/tcp_filtering/
3916 orig_seq = seq = ntohl(th->th_seq);
3917 if (src->seqlo == 0) {
3918 /* First packet from this end. Set its state */
3920 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3921 src->scrub == NULL) {
3922 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3923 REASON_SET(reason, PFRES_MEMORY);
3928 /* Deferred generation of sequence number modulator */
3929 if (dst->seqdiff && !src->seqdiff) {
3930 /* use random iss for the TCP server */
3931 while ((src->seqdiff = karc4random() - seq) == 0)
3933 ack = ntohl(th->th_ack) - dst->seqdiff;
3934 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3936 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3939 ack = ntohl(th->th_ack);
3942 end = seq + pd->p_len;
3943 if (th->th_flags & TH_SYN) {
3945 (*state)->sync_flags |= PFSTATE_GOT_SYN2;
3946 if (dst->wscale & PF_WSCALE_FLAG) {
3947 src->wscale = pf_get_wscale(m, off, th->th_off,
3949 if (src->wscale & PF_WSCALE_FLAG) {
3950 /* Remove scale factor from initial
3952 sws = src->wscale & PF_WSCALE_MASK;
3953 win = ((u_int32_t)win + (1 << sws) - 1)
3955 dws = dst->wscale & PF_WSCALE_MASK;
3957 /* fixup other window */
3958 dst->max_win <<= dst->wscale &
3960 /* in case of a retrans SYN|ACK */
3965 if (th->th_flags & TH_FIN)
3969 if (src->state < TCPS_SYN_SENT)
3970 src->state = TCPS_SYN_SENT;
3973 * May need to slide the window (seqhi may have been set by
3974 * the crappy stack check or if we picked up the connection
3975 * after establishment)
3977 if (src->seqhi == 1 ||
3978 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3979 src->seqhi = end + MAX(1, dst->max_win << dws);
3980 if (win > src->max_win)
3984 ack = ntohl(th->th_ack) - dst->seqdiff;
3986 /* Modulate sequence numbers */
3987 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3989 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3992 end = seq + pd->p_len;
3993 if (th->th_flags & TH_SYN)
3995 if (th->th_flags & TH_FIN)
3999 if ((th->th_flags & TH_ACK) == 0) {
4000 /* Let it pass through the ack skew check */
4002 } else if ((ack == 0 &&
4003 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4004 /* broken tcp stacks do not set ack */
4005 (dst->state < TCPS_SYN_SENT)) {
4007 * Many stacks (ours included) will set the ACK number in an
4008 * FIN|ACK if the SYN times out -- no sequence to ACK.
4014 /* Ease sequencing restrictions on no data packets */
4019 ackskew = dst->seqlo - ack;
4023 * Need to demodulate the sequence numbers in any TCP SACK options
4024 * (Selective ACK). We could optionally validate the SACK values
4025 * against the current ACK window, either forwards or backwards, but
4026 * I'm not confident that SACK has been implemented properly
4027 * everywhere. It wouldn't surprise me if several stacks accidently
4028 * SACK too far backwards of previously ACKed data. There really aren't
4029 * any security implications of bad SACKing unless the target stack
4030 * doesn't validate the option length correctly. Someone trying to
4031 * spoof into a TCP connection won't bother blindly sending SACK
4034 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4035 if (pf_modulate_sack(m, off, pd, th, dst))
4040 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4041 if (SEQ_GEQ(src->seqhi, end) &&
4042 /* Last octet inside other's window space */
4043 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4044 /* Retrans: not more than one window back */
4045 (ackskew >= -MAXACKWINDOW) &&
4046 /* Acking not more than one reassembled fragment backwards */
4047 (ackskew <= (MAXACKWINDOW << sws)) &&
4048 /* Acking not more than one window forward */
4049 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4050 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4051 (pd->flags & PFDESC_IP_REAS) == 0)) {
4052 /* Require an exact/+1 sequence match on resets when possible */
4054 if (dst->scrub || src->scrub) {
4055 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4056 *state, src, dst, copyback))
4060 /* update max window */
4061 if (src->max_win < win)
4063 /* synchronize sequencing */
4064 if (SEQ_GT(end, src->seqlo))
4066 /* slide the window of what the other end can send */
4067 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4068 dst->seqhi = ack + MAX((win << sws), 1);
4072 if (th->th_flags & TH_SYN)
4073 if (src->state < TCPS_SYN_SENT)
4074 src->state = TCPS_SYN_SENT;
4075 if (th->th_flags & TH_FIN)
4076 if (src->state < TCPS_CLOSING)
4077 src->state = TCPS_CLOSING;
4078 if (th->th_flags & TH_ACK) {
4079 if (dst->state == TCPS_SYN_SENT) {
4080 dst->state = TCPS_ESTABLISHED;
4081 if (src->state == TCPS_ESTABLISHED &&
4082 (*state)->src_node != NULL &&
4083 pf_src_connlimit(state)) {
4084 REASON_SET(reason, PFRES_SRCLIMIT);
4087 } else if (dst->state == TCPS_CLOSING)
4088 dst->state = TCPS_FIN_WAIT_2;
4090 if (th->th_flags & TH_RST)
4091 src->state = dst->state = TCPS_TIME_WAIT;
4093 /* update expire time */
4094 (*state)->expire = time_second;
4095 if (src->state >= TCPS_FIN_WAIT_2 &&
4096 dst->state >= TCPS_FIN_WAIT_2)
4097 (*state)->timeout = PFTM_TCP_CLOSED;
4098 else if (src->state >= TCPS_CLOSING &&
4099 dst->state >= TCPS_CLOSING)
4100 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4101 else if (src->state < TCPS_ESTABLISHED ||
4102 dst->state < TCPS_ESTABLISHED)
4103 (*state)->timeout = PFTM_TCP_OPENING;
4104 else if (src->state >= TCPS_CLOSING ||
4105 dst->state >= TCPS_CLOSING)
4106 (*state)->timeout = PFTM_TCP_CLOSING;
4108 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4110 /* Fall through to PASS packet */
4112 } else if ((dst->state < TCPS_SYN_SENT ||
4113 dst->state >= TCPS_FIN_WAIT_2 ||
4114 src->state >= TCPS_FIN_WAIT_2) &&
4115 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4116 /* Within a window forward of the originating packet */
4117 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4118 /* Within a window backward of the originating packet */
4121 * This currently handles three situations:
4122 * 1) Stupid stacks will shotgun SYNs before their peer
4124 * 2) When PF catches an already established stream (the
4125 * firewall rebooted, the state table was flushed, routes
4127 * 3) Packets get funky immediately after the connection
4128 * closes (this should catch Solaris spurious ACK|FINs
4129 * that web servers like to spew after a close)
4131 * This must be a little more careful than the above code
4132 * since packet floods will also be caught here. We don't
4133 * update the TTL here to mitigate the damage of a packet
4134 * flood and so the same code can handle awkward establishment
4135 * and a loosened connection close.
4136 * In the establishment case, a correct peer response will
4137 * validate the connection, go through the normal state code
4138 * and keep updating the state TTL.
4141 if (pf_status.debug >= PF_DEBUG_MISC) {
4142 kprintf("pf: loose state match: ");
4143 pf_print_state(*state);
4144 pf_print_flags(th->th_flags);
4145 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4146 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack, pd->p_len,
4147 ackskew, (unsigned long long)(*state)->packets[0],
4148 (unsigned long long)(*state)->packets[1],
4149 pd->dir == PF_IN ? "in" : "out",
4150 pd->dir == (*state)->direction ? "fwd" : "rev");
4153 if (dst->scrub || src->scrub) {
4154 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4155 *state, src, dst, copyback))
4159 /* update max window */
4160 if (src->max_win < win)
4162 /* synchronize sequencing */
4163 if (SEQ_GT(end, src->seqlo))
4165 /* slide the window of what the other end can send */
4166 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4167 dst->seqhi = ack + MAX((win << sws), 1);
4170 * Cannot set dst->seqhi here since this could be a shotgunned
4171 * SYN and not an already established connection.
4174 if (th->th_flags & TH_FIN)
4175 if (src->state < TCPS_CLOSING)
4176 src->state = TCPS_CLOSING;
4177 if (th->th_flags & TH_RST)
4178 src->state = dst->state = TCPS_TIME_WAIT;
4180 /* Fall through to PASS packet */
4182 } else if ((*state)->pickup_mode == PF_PICKUPS_HASHONLY ||
4183 ((*state)->pickup_mode == PF_PICKUPS_ENABLED &&
4184 ((*state)->sync_flags & PFSTATE_GOT_SYN_MASK) !=
4185 PFSTATE_GOT_SYN_MASK)) {
4187 * If pickup mode is hash only, do not fail on sequence checks.
4189 * If pickup mode is enabled and we did not see the SYN in
4190 * both direction, do not fail on sequence checks because
4191 * we do not have complete information on window scale.
4193 * Adjust expiration and fall through to PASS packet.
4194 * XXX Add a FIN check to reduce timeout?
4196 (*state)->expire = time_second;
4199 * Failure processing
4201 if ((*state)->dst.state == TCPS_SYN_SENT &&
4202 (*state)->src.state == TCPS_SYN_SENT) {
4203 /* Send RST for state mismatches during handshake */
4204 if (!(th->th_flags & TH_RST))
4205 pf_send_tcp((*state)->rule.ptr, pd->af,
4206 pd->dst, pd->src, th->th_dport,
4207 th->th_sport, ntohl(th->th_ack), 0,
4209 (*state)->rule.ptr->return_ttl, 1, 0,
4210 pd->eh, kif->pfik_ifp);
4214 } else if (pf_status.debug >= PF_DEBUG_MISC) {
4215 kprintf("pf: BAD state: ");
4216 pf_print_state(*state);
4217 pf_print_flags(th->th_flags);
4218 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4219 "pkts=%llu:%llu dir=%s,%s\n",
4220 seq, orig_seq, ack, pd->p_len, ackskew,
4221 (unsigned long long)(*state)->packets[0],
4222 (unsigned long long)(*state)->packets[1],
4223 pd->dir == PF_IN ? "in" : "out",
4224 pd->dir == (*state)->direction ? "fwd" : "rev");
4225 kprintf("pf: State failure on: %c %c %c %c | %c %c\n",
4226 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4227 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4229 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4230 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4231 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4232 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4234 REASON_SET(reason, PFRES_BADSTATE);
4242 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4243 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4245 struct tcphdr *th = pd->hdr.tcp;
4247 if (th->th_flags & TH_SYN)
4248 if (src->state < TCPS_SYN_SENT)
4249 src->state = TCPS_SYN_SENT;
4250 if (th->th_flags & TH_FIN)
4251 if (src->state < TCPS_CLOSING)
4252 src->state = TCPS_CLOSING;
4253 if (th->th_flags & TH_ACK) {
4254 if (dst->state == TCPS_SYN_SENT) {
4255 dst->state = TCPS_ESTABLISHED;
4256 if (src->state == TCPS_ESTABLISHED &&
4257 (*state)->src_node != NULL &&
4258 pf_src_connlimit(state)) {
4259 REASON_SET(reason, PFRES_SRCLIMIT);
4262 } else if (dst->state == TCPS_CLOSING) {
4263 dst->state = TCPS_FIN_WAIT_2;
4264 } else if (src->state == TCPS_SYN_SENT &&
4265 dst->state < TCPS_SYN_SENT) {
4267 * Handle a special sloppy case where we only see one
4268 * half of the connection. If there is a ACK after
4269 * the initial SYN without ever seeing a packet from
4270 * the destination, set the connection to established.
4272 dst->state = src->state = TCPS_ESTABLISHED;
4273 if ((*state)->src_node != NULL &&
4274 pf_src_connlimit(state)) {
4275 REASON_SET(reason, PFRES_SRCLIMIT);
4278 } else if (src->state == TCPS_CLOSING &&
4279 dst->state == TCPS_ESTABLISHED &&
4282 * Handle the closing of half connections where we
4283 * don't see the full bidirectional FIN/ACK+ACK
4286 dst->state = TCPS_CLOSING;
4289 if (th->th_flags & TH_RST)
4290 src->state = dst->state = TCPS_TIME_WAIT;
4292 /* update expire time */
4293 (*state)->expire = time_second;
4294 if (src->state >= TCPS_FIN_WAIT_2 &&
4295 dst->state >= TCPS_FIN_WAIT_2)
4296 (*state)->timeout = PFTM_TCP_CLOSED;
4297 else if (src->state >= TCPS_CLOSING &&
4298 dst->state >= TCPS_CLOSING)
4299 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4300 else if (src->state < TCPS_ESTABLISHED ||
4301 dst->state < TCPS_ESTABLISHED)
4302 (*state)->timeout = PFTM_TCP_OPENING;
4303 else if (src->state >= TCPS_CLOSING ||
4304 dst->state >= TCPS_CLOSING)
4305 (*state)->timeout = PFTM_TCP_CLOSING;
4307 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4313 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4314 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4317 struct pf_state_key_cmp key;
4318 struct tcphdr *th = pd->hdr.tcp;
4320 struct pf_state_peer *src, *dst;
4321 struct pf_state_key *sk;
4324 key.proto = IPPROTO_TCP;
4325 if (direction == PF_IN) { /* wire side, straight */
4326 PF_ACPY(&key.addr[0], pd->src, key.af);
4327 PF_ACPY(&key.addr[1], pd->dst, key.af);
4328 key.port[0] = th->th_sport;
4329 key.port[1] = th->th_dport;
4330 } else { /* stack side, reverse */
4331 PF_ACPY(&key.addr[1], pd->src, key.af);
4332 PF_ACPY(&key.addr[0], pd->dst, key.af);
4333 key.port[1] = th->th_sport;
4334 key.port[0] = th->th_dport;
4337 STATE_LOOKUP(kif, &key, direction, *state, m);
4339 if (direction == (*state)->direction) {
4340 src = &(*state)->src;
4341 dst = &(*state)->dst;
4343 src = &(*state)->dst;
4344 dst = &(*state)->src;
4347 sk = (*state)->key[pd->didx];
4349 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4350 if (direction != (*state)->direction) {
4351 REASON_SET(reason, PFRES_SYNPROXY);
4352 return (PF_SYNPROXY_DROP);
4354 if (th->th_flags & TH_SYN) {
4355 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4356 REASON_SET(reason, PFRES_SYNPROXY);
4359 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4360 pd->src, th->th_dport, th->th_sport,
4361 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4362 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
4364 REASON_SET(reason, PFRES_SYNPROXY);
4365 return (PF_SYNPROXY_DROP);
4366 } else if (!(th->th_flags & TH_ACK) ||
4367 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4368 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4369 REASON_SET(reason, PFRES_SYNPROXY);
4371 } else if ((*state)->src_node != NULL &&
4372 pf_src_connlimit(state)) {
4373 REASON_SET(reason, PFRES_SRCLIMIT);
4376 (*state)->src.state = PF_TCPS_PROXY_DST;
4378 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4379 if (direction == (*state)->direction) {
4380 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4381 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4382 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4383 REASON_SET(reason, PFRES_SYNPROXY);
4386 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4387 if ((*state)->dst.seqhi == 1)
4388 (*state)->dst.seqhi = htonl(karc4random());
4389 pf_send_tcp((*state)->rule.ptr, pd->af,
4390 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4391 sk->port[pd->sidx], sk->port[pd->didx],
4392 (*state)->dst.seqhi, 0, TH_SYN, 0,
4393 (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
4394 REASON_SET(reason, PFRES_SYNPROXY);
4395 return (PF_SYNPROXY_DROP);
4396 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4398 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4399 REASON_SET(reason, PFRES_SYNPROXY);
4402 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4403 (*state)->dst.seqlo = ntohl(th->th_seq);
4404 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4405 pd->src, th->th_dport, th->th_sport,
4406 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4407 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4408 (*state)->tag, NULL, NULL);
4409 pf_send_tcp((*state)->rule.ptr, pd->af,
4410 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4411 sk->port[pd->sidx], sk->port[pd->didx],
4412 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4413 TH_ACK, (*state)->dst.max_win, 0, 0, 1,
4415 (*state)->src.seqdiff = (*state)->dst.seqhi -
4416 (*state)->src.seqlo;
4417 (*state)->dst.seqdiff = (*state)->src.seqhi -
4418 (*state)->dst.seqlo;
4419 (*state)->src.seqhi = (*state)->src.seqlo +
4420 (*state)->dst.max_win;
4421 (*state)->dst.seqhi = (*state)->dst.seqlo +
4422 (*state)->src.max_win;
4423 (*state)->src.wscale = (*state)->dst.wscale = 0;
4424 (*state)->src.state = (*state)->dst.state =
4426 REASON_SET(reason, PFRES_SYNPROXY);
4427 return (PF_SYNPROXY_DROP);
4431 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4432 dst->state >= TCPS_FIN_WAIT_2 &&
4433 src->state >= TCPS_FIN_WAIT_2) {
4434 if (pf_status.debug >= PF_DEBUG_MISC) {
4435 kprintf("pf: state reuse ");
4436 pf_print_state(*state);
4437 pf_print_flags(th->th_flags);
4440 /* XXX make sure it's the same direction ?? */
4441 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4442 pf_unlink_state(*state);
4447 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4448 if (pf_tcp_track_sloppy(src, dst, state, pd, reason) == PF_DROP)
4451 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd, reason,
4452 ©back) == PF_DROP)
4456 /* translate source/destination address, if necessary */
4457 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4458 struct pf_state_key *nk = (*state)->key[pd->didx];
4460 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4461 nk->port[pd->sidx] != th->th_sport) {
4463 * The translated source address may be completely
4464 * unrelated to the saved link header, make sure
4465 * a bridge doesn't try to use it.
4467 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4468 m->m_flags &= ~M_HASH;
4469 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4470 &th->th_sum, &nk->addr[pd->sidx],
4471 nk->port[pd->sidx], 0, pd->af);
4474 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4475 nk->port[pd->didx] != th->th_dport) {
4477 * If we don't redispatch the packet will go into
4478 * the protocol stack on the wrong cpu for the
4479 * post-translated address.
4481 m->m_flags &= ~M_HASH;
4482 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4483 &th->th_sum, &nk->addr[pd->didx],
4484 nk->port[pd->didx], 0, pd->af);
4489 /* Copyback sequence modulation or stateful scrub changes if needed */
4491 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4497 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4498 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4500 struct pf_state_peer *src, *dst;
4501 struct pf_state_key_cmp key;
4502 struct udphdr *uh = pd->hdr.udp;
4505 key.proto = IPPROTO_UDP;
4506 if (direction == PF_IN) { /* wire side, straight */
4507 PF_ACPY(&key.addr[0], pd->src, key.af);
4508 PF_ACPY(&key.addr[1], pd->dst, key.af);
4509 key.port[0] = uh->uh_sport;
4510 key.port[1] = uh->uh_dport;
4511 } else { /* stack side, reverse */
4512 PF_ACPY(&key.addr[1], pd->src, key.af);
4513 PF_ACPY(&key.addr[0], pd->dst, key.af);
4514 key.port[1] = uh->uh_sport;
4515 key.port[0] = uh->uh_dport;
4518 STATE_LOOKUP(kif, &key, direction, *state, m);
4520 if (direction == (*state)->direction) {
4521 src = &(*state)->src;
4522 dst = &(*state)->dst;
4524 src = &(*state)->dst;
4525 dst = &(*state)->src;
4529 if (src->state < PFUDPS_SINGLE)
4530 src->state = PFUDPS_SINGLE;
4531 if (dst->state == PFUDPS_SINGLE)
4532 dst->state = PFUDPS_MULTIPLE;
4534 /* update expire time */
4535 (*state)->expire = time_second;
4536 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4537 (*state)->timeout = PFTM_UDP_MULTIPLE;
4539 (*state)->timeout = PFTM_UDP_SINGLE;
4541 /* translate source/destination address, if necessary */
4542 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4543 struct pf_state_key *nk = (*state)->key[pd->didx];
4545 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
4546 nk->port[pd->sidx] != uh->uh_sport) {
4548 * The translated source address may be completely
4549 * unrelated to the saved link header, make sure
4550 * a bridge doesn't try to use it.
4552 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
4553 m->m_flags &= ~M_HASH;
4554 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4555 &uh->uh_sum, &nk->addr[pd->sidx],
4556 nk->port[pd->sidx], 1, pd->af);
4559 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
4560 nk->port[pd->didx] != uh->uh_dport) {
4562 * If we don't redispatch the packet will go into
4563 * the protocol stack on the wrong cpu for the
4564 * post-translated address.
4566 m->m_flags &= ~M_HASH;
4567 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4568 &uh->uh_sum, &nk->addr[pd->didx],
4569 nk->port[pd->didx], 1, pd->af);
4571 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4578 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4579 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4581 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4582 u_int16_t icmpid = 0, *icmpsum;
4585 struct pf_state_key_cmp key;
4587 switch (pd->proto) {
4590 icmptype = pd->hdr.icmp->icmp_type;
4591 icmpid = pd->hdr.icmp->icmp_id;
4592 icmpsum = &pd->hdr.icmp->icmp_cksum;
4594 if (icmptype == ICMP_UNREACH ||
4595 icmptype == ICMP_SOURCEQUENCH ||
4596 icmptype == ICMP_REDIRECT ||
4597 icmptype == ICMP_TIMXCEED ||
4598 icmptype == ICMP_PARAMPROB)
4603 case IPPROTO_ICMPV6:
4604 icmptype = pd->hdr.icmp6->icmp6_type;
4605 icmpid = pd->hdr.icmp6->icmp6_id;
4606 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4608 if (icmptype == ICMP6_DST_UNREACH ||
4609 icmptype == ICMP6_PACKET_TOO_BIG ||
4610 icmptype == ICMP6_TIME_EXCEEDED ||
4611 icmptype == ICMP6_PARAM_PROB)
4620 * ICMP query/reply message not related to a TCP/UDP packet.
4621 * Search for an ICMP state.
4624 key.proto = pd->proto;
4625 key.port[0] = key.port[1] = icmpid;
4626 if (direction == PF_IN) { /* wire side, straight */
4627 PF_ACPY(&key.addr[0], pd->src, key.af);
4628 PF_ACPY(&key.addr[1], pd->dst, key.af);
4629 } else { /* stack side, reverse */
4630 PF_ACPY(&key.addr[1], pd->src, key.af);
4631 PF_ACPY(&key.addr[0], pd->dst, key.af);
4634 STATE_LOOKUP(kif, &key, direction, *state, m);
4636 (*state)->expire = time_second;
4637 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4639 /* translate source/destination address, if necessary */
4640 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4641 struct pf_state_key *nk = (*state)->key[pd->didx];
4646 if (PF_ANEQ(pd->src,
4647 &nk->addr[pd->sidx], AF_INET))
4648 pf_change_a(&saddr->v4.s_addr,
4650 nk->addr[pd->sidx].v4.s_addr, 0);
4652 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
4654 pf_change_a(&daddr->v4.s_addr,
4656 nk->addr[pd->didx].v4.s_addr, 0);
4659 pd->hdr.icmp->icmp_id) {
4660 pd->hdr.icmp->icmp_cksum =
4662 pd->hdr.icmp->icmp_cksum, icmpid,
4663 nk->port[pd->sidx], 0);
4664 pd->hdr.icmp->icmp_id =
4668 m_copyback(m, off, ICMP_MINLEN,
4669 (caddr_t)pd->hdr.icmp);
4674 if (PF_ANEQ(pd->src,
4675 &nk->addr[pd->sidx], AF_INET6))
4677 &pd->hdr.icmp6->icmp6_cksum,
4678 &nk->addr[pd->sidx], 0);
4680 if (PF_ANEQ(pd->dst,
4681 &nk->addr[pd->didx], AF_INET6))
4683 &pd->hdr.icmp6->icmp6_cksum,
4684 &nk->addr[pd->didx], 0);
4687 sizeof(struct icmp6_hdr),
4688 (caddr_t)pd->hdr.icmp6);
4697 * ICMP error message in response to a TCP/UDP packet.
4698 * Extract the inner TCP/UDP header and search for that state.
4701 struct pf_pdesc pd2;
4706 struct ip6_hdr h2_6;
4713 /* Payload packet is from the opposite direction. */
4714 pd2.sidx = (direction == PF_IN) ? 1 : 0;
4715 pd2.didx = (direction == PF_IN) ? 0 : 1;
4719 /* offset of h2 in mbuf chain */
4720 ipoff2 = off + ICMP_MINLEN;
4722 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4723 NULL, reason, pd2.af)) {
4724 DPFPRINTF(PF_DEBUG_MISC,
4725 ("pf: ICMP error message too short "
4730 * ICMP error messages don't refer to non-first
4733 if (h2.ip_off & htons(IP_OFFMASK)) {
4734 REASON_SET(reason, PFRES_FRAG);
4738 /* offset of protocol header that follows h2 */
4739 off2 = ipoff2 + (h2.ip_hl << 2);
4741 pd2.proto = h2.ip_p;
4742 pd2.src = (struct pf_addr *)&h2.ip_src;
4743 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4744 pd2.ip_sum = &h2.ip_sum;
4749 ipoff2 = off + sizeof(struct icmp6_hdr);
4751 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4752 NULL, reason, pd2.af)) {
4753 DPFPRINTF(PF_DEBUG_MISC,
4754 ("pf: ICMP error message too short "
4758 pd2.proto = h2_6.ip6_nxt;
4759 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4760 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4762 off2 = ipoff2 + sizeof(h2_6);
4764 switch (pd2.proto) {
4765 case IPPROTO_FRAGMENT:
4767 * ICMPv6 error messages for
4768 * non-first fragments
4770 REASON_SET(reason, PFRES_FRAG);
4773 case IPPROTO_HOPOPTS:
4774 case IPPROTO_ROUTING:
4775 case IPPROTO_DSTOPTS: {
4776 /* get next header and header length */
4777 struct ip6_ext opt6;
4779 if (!pf_pull_hdr(m, off2, &opt6,
4780 sizeof(opt6), NULL, reason,
4782 DPFPRINTF(PF_DEBUG_MISC,
4783 ("pf: ICMPv6 short opt\n"));
4786 if (pd2.proto == IPPROTO_AH)
4787 off2 += (opt6.ip6e_len + 2) * 4;
4789 off2 += (opt6.ip6e_len + 1) * 8;
4790 pd2.proto = opt6.ip6e_nxt;
4791 /* goto the next header */
4798 } while (!terminal);
4802 DPFPRINTF(PF_DEBUG_MISC,
4803 ("pf: ICMP AF %d unknown (ip6)\n", pd->af));
4808 switch (pd2.proto) {
4812 struct pf_state_peer *src, *dst;
4817 * Only the first 8 bytes of the TCP header can be
4818 * expected. Don't access any TCP header fields after
4819 * th_seq, an ackskew test is not possible.
4821 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4823 DPFPRINTF(PF_DEBUG_MISC,
4824 ("pf: ICMP error message too short "
4830 key.proto = IPPROTO_TCP;
4831 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4832 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4833 key.port[pd2.sidx] = th.th_sport;
4834 key.port[pd2.didx] = th.th_dport;
4836 STATE_LOOKUP(kif, &key, direction, *state, m);
4838 if (direction == (*state)->direction) {
4839 src = &(*state)->dst;
4840 dst = &(*state)->src;
4842 src = &(*state)->src;
4843 dst = &(*state)->dst;
4846 if (src->wscale && dst->wscale)
4847 dws = dst->wscale & PF_WSCALE_MASK;
4851 /* Demodulate sequence number */
4852 seq = ntohl(th.th_seq) - src->seqdiff;
4854 pf_change_a(&th.th_seq, icmpsum,
4859 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
4860 (!SEQ_GEQ(src->seqhi, seq) ||
4861 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
4862 if (pf_status.debug >= PF_DEBUG_MISC) {
4863 kprintf("pf: BAD ICMP %d:%d ",
4864 icmptype, pd->hdr.icmp->icmp_code);
4865 pf_print_host(pd->src, 0, pd->af);
4867 pf_print_host(pd->dst, 0, pd->af);
4868 kprintf(" state: ");
4869 pf_print_state(*state);
4870 kprintf(" seq=%u\n", seq);
4872 REASON_SET(reason, PFRES_BADSTATE);
4875 if (pf_status.debug >= PF_DEBUG_MISC) {
4876 kprintf("pf: OK ICMP %d:%d ",
4877 icmptype, pd->hdr.icmp->icmp_code);
4878 pf_print_host(pd->src, 0, pd->af);
4880 pf_print_host(pd->dst, 0, pd->af);
4881 kprintf(" state: ");
4882 pf_print_state(*state);
4883 kprintf(" seq=%u\n", seq);
4887 /* translate source/destination address, if necessary */
4888 if ((*state)->key[PF_SK_WIRE] !=
4889 (*state)->key[PF_SK_STACK]) {
4890 struct pf_state_key *nk =
4891 (*state)->key[pd->didx];
4893 if (PF_ANEQ(pd2.src,
4894 &nk->addr[pd2.sidx], pd2.af) ||
4895 nk->port[pd2.sidx] != th.th_sport)
4896 pf_change_icmp(pd2.src, &th.th_sport,
4897 daddr, &nk->addr[pd2.sidx],
4898 nk->port[pd2.sidx], NULL,
4899 pd2.ip_sum, icmpsum,
4900 pd->ip_sum, 0, pd2.af);
4902 if (PF_ANEQ(pd2.dst,
4903 &nk->addr[pd2.didx], pd2.af) ||
4904 nk->port[pd2.didx] != th.th_dport)
4905 pf_change_icmp(pd2.dst, &th.th_dport,
4906 NULL, /* XXX Inbound NAT? */
4907 &nk->addr[pd2.didx],
4908 nk->port[pd2.didx], NULL,
4909 pd2.ip_sum, icmpsum,
4910 pd->ip_sum, 0, pd2.af);
4918 m_copyback(m, off, ICMP_MINLEN,
4919 (caddr_t)pd->hdr.icmp);
4920 m_copyback(m, ipoff2, sizeof(h2),
4927 sizeof(struct icmp6_hdr),
4928 (caddr_t)pd->hdr.icmp6);
4929 m_copyback(m, ipoff2, sizeof(h2_6),
4934 m_copyback(m, off2, 8, (caddr_t)&th);
4943 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4944 NULL, reason, pd2.af)) {
4945 DPFPRINTF(PF_DEBUG_MISC,
4946 ("pf: ICMP error message too short "
4952 key.proto = IPPROTO_UDP;
4953 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
4954 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
4955 key.port[pd2.sidx] = uh.uh_sport;
4956 key.port[pd2.didx] = uh.uh_dport;
4958 STATE_LOOKUP(kif, &key, direction, *state, m);
4960 /* translate source/destination address, if necessary */
4961 if ((*state)->key[PF_SK_WIRE] !=
4962 (*state)->key[PF_SK_STACK]) {
4963 struct pf_state_key *nk =
4964 (*state)->key[pd->didx];
4966 if (PF_ANEQ(pd2.src,
4967 &nk->addr[pd2.sidx], pd2.af) ||
4968 nk->port[pd2.sidx] != uh.uh_sport)
4969 pf_change_icmp(pd2.src, &uh.uh_sport,
4970 daddr, &nk->addr[pd2.sidx],
4971 nk->port[pd2.sidx], &uh.uh_sum,
4972 pd2.ip_sum, icmpsum,
4973 pd->ip_sum, 1, pd2.af);
4975 if (PF_ANEQ(pd2.dst,
4976 &nk->addr[pd2.didx], pd2.af) ||
4977 nk->port[pd2.didx] != uh.uh_dport)
4978 pf_change_icmp(pd2.dst, &uh.uh_dport,
4979 NULL, /* XXX Inbound NAT? */
4980 &nk->addr[pd2.didx],
4981 nk->port[pd2.didx], &uh.uh_sum,
4982 pd2.ip_sum, icmpsum,
4983 pd->ip_sum, 1, pd2.af);
4988 m_copyback(m, off, ICMP_MINLEN,
4989 (caddr_t)pd->hdr.icmp);
4990 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4996 sizeof(struct icmp6_hdr),
4997 (caddr_t)pd->hdr.icmp6);
4998 m_copyback(m, ipoff2, sizeof(h2_6),
5003 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5010 case IPPROTO_ICMP: {
5013 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5014 NULL, reason, pd2.af)) {
5015 DPFPRINTF(PF_DEBUG_MISC,
5016 ("pf: ICMP error message too short i"
5022 key.proto = IPPROTO_ICMP;
5023 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5024 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5025 key.port[0] = key.port[1] = iih.icmp_id;
5027 STATE_LOOKUP(kif, &key, direction, *state, m);
5029 /* translate source/destination address, if necessary */
5030 if ((*state)->key[PF_SK_WIRE] !=
5031 (*state)->key[PF_SK_STACK]) {
5032 struct pf_state_key *nk =
5033 (*state)->key[pd->didx];
5035 if (PF_ANEQ(pd2.src,
5036 &nk->addr[pd2.sidx], pd2.af) ||
5037 nk->port[pd2.sidx] != iih.icmp_id)
5038 pf_change_icmp(pd2.src, &iih.icmp_id,
5039 daddr, &nk->addr[pd2.sidx],
5040 nk->port[pd2.sidx], NULL,
5041 pd2.ip_sum, icmpsum,
5042 pd->ip_sum, 0, AF_INET);
5044 if (PF_ANEQ(pd2.dst,
5045 &nk->addr[pd2.didx], pd2.af) ||
5046 nk->port[pd2.didx] != iih.icmp_id)
5047 pf_change_icmp(pd2.dst, &iih.icmp_id,
5048 NULL, /* XXX Inbound NAT? */
5049 &nk->addr[pd2.didx],
5050 nk->port[pd2.didx], NULL,
5051 pd2.ip_sum, icmpsum,
5052 pd->ip_sum, 0, AF_INET);
5054 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5055 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5056 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5063 case IPPROTO_ICMPV6: {
5064 struct icmp6_hdr iih;
5066 if (!pf_pull_hdr(m, off2, &iih,
5067 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5068 DPFPRINTF(PF_DEBUG_MISC,
5069 ("pf: ICMP error message too short "
5075 key.proto = IPPROTO_ICMPV6;
5076 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5077 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5078 key.port[0] = key.port[1] = iih.icmp6_id;
5080 STATE_LOOKUP(kif, &key, direction, *state, m);
5082 /* translate source/destination address, if necessary */
5083 if ((*state)->key[PF_SK_WIRE] !=
5084 (*state)->key[PF_SK_STACK]) {
5085 struct pf_state_key *nk =
5086 (*state)->key[pd->didx];
5088 if (PF_ANEQ(pd2.src,
5089 &nk->addr[pd2.sidx], pd2.af) ||
5090 nk->port[pd2.sidx] != iih.icmp6_id)
5091 pf_change_icmp(pd2.src, &iih.icmp6_id,
5092 daddr, &nk->addr[pd2.sidx],
5093 nk->port[pd2.sidx], NULL,
5094 pd2.ip_sum, icmpsum,
5095 pd->ip_sum, 0, AF_INET6);
5097 if (PF_ANEQ(pd2.dst,
5098 &nk->addr[pd2.didx], pd2.af) ||
5099 nk->port[pd2.didx] != iih.icmp6_id)
5100 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5101 NULL, /* XXX Inbound NAT? */
5102 &nk->addr[pd2.didx],
5103 nk->port[pd2.didx], NULL,
5104 pd2.ip_sum, icmpsum,
5105 pd->ip_sum, 0, AF_INET6);
5107 m_copyback(m, off, sizeof(struct icmp6_hdr),
5108 (caddr_t)pd->hdr.icmp6);
5109 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5110 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5120 key.proto = pd2.proto;
5121 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5122 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5123 key.port[0] = key.port[1] = 0;
5125 STATE_LOOKUP(kif, &key, direction, *state, m);
5127 /* translate source/destination address, if necessary */
5128 if ((*state)->key[PF_SK_WIRE] !=
5129 (*state)->key[PF_SK_STACK]) {
5130 struct pf_state_key *nk =
5131 (*state)->key[pd->didx];
5133 if (PF_ANEQ(pd2.src,
5134 &nk->addr[pd2.sidx], pd2.af))
5135 pf_change_icmp(pd2.src, NULL, daddr,
5136 &nk->addr[pd2.sidx], 0, NULL,
5137 pd2.ip_sum, icmpsum,
5138 pd->ip_sum, 0, pd2.af);
5140 if (PF_ANEQ(pd2.dst,
5141 &nk->addr[pd2.didx], pd2.af))
5142 pf_change_icmp(pd2.src, NULL,
5143 NULL, /* XXX Inbound NAT? */
5144 &nk->addr[pd2.didx], 0, NULL,
5145 pd2.ip_sum, icmpsum,
5146 pd->ip_sum, 0, pd2.af);
5151 m_copyback(m, off, ICMP_MINLEN,
5152 (caddr_t)pd->hdr.icmp);
5153 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5159 sizeof(struct icmp6_hdr),
5160 (caddr_t)pd->hdr.icmp6);
5161 m_copyback(m, ipoff2, sizeof(h2_6),
5175 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5176 struct mbuf *m, struct pf_pdesc *pd)
5178 struct pf_state_peer *src, *dst;
5179 struct pf_state_key_cmp key;
5182 key.proto = pd->proto;
5183 if (direction == PF_IN) {
5184 PF_ACPY(&key.addr[0], pd->src, key.af);
5185 PF_ACPY(&key.addr[1], pd->dst, key.af);
5186 key.port[0] = key.port[1] = 0;
5188 PF_ACPY(&key.addr[1], pd->src, key.af);
5189 PF_ACPY(&key.addr[0], pd->dst, key.af);
5190 key.port[1] = key.port[0] = 0;
5193 STATE_LOOKUP(kif, &key, direction, *state, m);
5195 if (direction == (*state)->direction) {
5196 src = &(*state)->src;
5197 dst = &(*state)->dst;
5199 src = &(*state)->dst;
5200 dst = &(*state)->src;
5204 if (src->state < PFOTHERS_SINGLE)
5205 src->state = PFOTHERS_SINGLE;
5206 if (dst->state == PFOTHERS_SINGLE)
5207 dst->state = PFOTHERS_MULTIPLE;
5209 /* update expire time */
5210 (*state)->expire = time_second;
5211 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5212 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5214 (*state)->timeout = PFTM_OTHER_SINGLE;
5216 /* translate source/destination address, if necessary */
5217 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5218 struct pf_state_key *nk = (*state)->key[pd->didx];
5227 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5228 pf_change_a(&pd->src->v4.s_addr,
5230 nk->addr[pd->sidx].v4.s_addr,
5234 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5235 pf_change_a(&pd->dst->v4.s_addr,
5237 nk->addr[pd->didx].v4.s_addr,
5244 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5245 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5247 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5248 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5256 * ipoff and off are measured from the start of the mbuf chain.
5257 * h must be at "ipoff" on the mbuf chain.
5260 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5261 u_short *actionp, u_short *reasonp, sa_family_t af)
5266 struct ip *h = mtod(m, struct ip *);
5267 u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;
5271 ACTION_SET(actionp, PF_PASS);
5273 ACTION_SET(actionp, PF_DROP);
5274 REASON_SET(reasonp, PFRES_FRAG);
5278 if (m->m_pkthdr.len < off + len ||
5279 h->ip_len < off + len) {
5280 ACTION_SET(actionp, PF_DROP);
5281 REASON_SET(reasonp, PFRES_SHORT);
5289 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5291 if (m->m_pkthdr.len < off + len ||
5292 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5293 (unsigned)(off + len)) {
5294 ACTION_SET(actionp, PF_DROP);
5295 REASON_SET(reasonp, PFRES_SHORT);
5302 m_copydata(m, off, len, p);
5307 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif)
5309 struct sockaddr_in *dst;
5313 struct sockaddr_in6 *dst6;
5314 struct route_in6 ro;
5318 struct radix_node *rn;
5323 bzero(&ro, sizeof(ro));
5326 dst = satosin(&ro.ro_dst);
5327 dst->sin_family = AF_INET;
5328 dst->sin_len = sizeof(*dst);
5329 dst->sin_addr = addr->v4;
5333 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5334 dst6->sin6_family = AF_INET6;
5335 dst6->sin6_len = sizeof(*dst6);
5336 dst6->sin6_addr = addr->v6;
5343 /* Skip checks for ipsec interfaces */
5344 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5347 rtalloc_ign((struct route *)&ro, 0);
5349 if (ro.ro_rt != NULL) {
5350 /* No interface given, this is a no-route check */
5354 if (kif->pfik_ifp == NULL) {
5359 /* Perform uRPF check if passed input interface */
5361 rn = (struct radix_node *)ro.ro_rt;
5363 rt = (struct rtentry *)rn;
5366 if (kif->pfik_ifp == ifp)
5369 } while (check_mpath == 1 && rn != NULL && ret == 0);
5373 if (ro.ro_rt != NULL)
5379 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw)
5381 struct sockaddr_in *dst;
5383 struct sockaddr_in6 *dst6;
5384 struct route_in6 ro;
5390 ASSERT_LWKT_TOKEN_HELD(&pf_token);
5392 bzero(&ro, sizeof(ro));
5395 dst = satosin(&ro.ro_dst);
5396 dst->sin_family = AF_INET;
5397 dst->sin_len = sizeof(*dst);
5398 dst->sin_addr = addr->v4;
5402 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5403 dst6->sin6_family = AF_INET6;
5404 dst6->sin6_len = sizeof(*dst6);
5405 dst6->sin6_addr = addr->v6;
5412 rtalloc_ign((struct route *)&ro, (RTF_CLONING | RTF_PRCLONING));
5414 if (ro.ro_rt != NULL) {
5423 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5424 struct pf_state *s, struct pf_pdesc *pd)
5426 struct mbuf *m0, *m1;
5427 struct route iproute;
5428 struct route *ro = NULL;
5429 struct sockaddr_in *dst;
5431 struct ifnet *ifp = NULL;
5432 struct pf_addr naddr;
5433 struct pf_src_node *sn = NULL;
5440 ASSERT_LWKT_TOKEN_HELD(&pf_token);
5442 if (m == NULL || *m == NULL || r == NULL ||
5443 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5444 panic("pf_route: invalid parameters");
5446 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5447 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5448 (*m)->m_pkthdr.pf.routed = 1;
5450 if ((*m)->m_pkthdr.pf.routed++ > 3) {
5457 if (r->rt == PF_DUPTO) {
5458 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL) {
5462 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5468 if (m0->m_len < sizeof(struct ip)) {
5469 DPFPRINTF(PF_DEBUG_URGENT,
5470 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5474 ip = mtod(m0, struct ip *);
5477 bzero((caddr_t)ro, sizeof(*ro));
5478 dst = satosin(&ro->ro_dst);
5479 dst->sin_family = AF_INET;
5480 dst->sin_len = sizeof(*dst);
5481 dst->sin_addr = ip->ip_dst;
5483 if (r->rt == PF_FASTROUTE) {
5485 if (ro->ro_rt == 0) {
5486 ipstat.ips_noroute++;
5490 ifp = ro->ro_rt->rt_ifp;
5491 ro->ro_rt->rt_use++;
5493 if (ro->ro_rt->rt_flags & RTF_GATEWAY)
5494 dst = satosin(ro->ro_rt->rt_gateway);
5496 if (TAILQ_EMPTY(&r->rpool.list)) {
5497 DPFPRINTF(PF_DEBUG_URGENT,
5498 ("pf_route: TAILQ_EMPTY(&r->rpool.list)\n"));
5502 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5504 if (!PF_AZERO(&naddr, AF_INET))
5505 dst->sin_addr.s_addr = naddr.v4.s_addr;
5506 ifp = r->rpool.cur->kif ?
5507 r->rpool.cur->kif->pfik_ifp : NULL;
5509 if (!PF_AZERO(&s->rt_addr, AF_INET))
5510 dst->sin_addr.s_addr =
5511 s->rt_addr.v4.s_addr;
5512 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5519 if (pf_test(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5521 } else if (m0 == NULL) {
5524 if (m0->m_len < sizeof(struct ip)) {
5525 DPFPRINTF(PF_DEBUG_URGENT,
5526 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5529 ip = mtod(m0, struct ip *);
5532 /* Copied from FreeBSD 5.1-CURRENT ip_output. */
5533 m0->m_pkthdr.csum_flags |= CSUM_IP;
5534 sw_csum = m0->m_pkthdr.csum_flags & ~ifp->if_hwassist;
5535 if (sw_csum & CSUM_DELAY_DATA) {
5536 in_delayed_cksum(m0);
5537 sw_csum &= ~CSUM_DELAY_DATA;
5539 m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
5541 if (ip->ip_len <= ifp->if_mtu ||
5542 (ifp->if_hwassist & CSUM_FRAGMENT &&
5543 (ip->ip_off & IP_DF) == 0)) {
5544 ip->ip_len = htons(ip->ip_len);
5545 ip->ip_off = htons(ip->ip_off);
5547 if (sw_csum & CSUM_DELAY_IP) {
5549 if (ip->ip_v == IPVERSION &&
5550 (ip->ip_hl << 2) == sizeof(*ip)) {
5551 ip->ip_sum = in_cksum_hdr(ip);
5553 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5556 lwkt_reltoken(&pf_token);
5557 error = ifp->if_output(ifp, m0, sintosa(dst), ro->ro_rt);
5558 lwkt_gettoken(&pf_token);
5563 * Too large for interface; fragment if possible.
5564 * Must be able to put at least 8 bytes per fragment.
5566 if (ip->ip_off & IP_DF) {
5567 ipstat.ips_cantfrag++;
5568 if (r->rt != PF_DUPTO) {
5569 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5577 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist, sw_csum);
5582 for (m0 = m1; m0; m0 = m1) {
5586 lwkt_reltoken(&pf_token);
5587 error = (*ifp->if_output)(ifp, m0, sintosa(dst),
5589 lwkt_gettoken(&pf_token);
5595 ipstat.ips_fragmented++;
5598 if (r->rt != PF_DUPTO)
5600 if (ro == &iproute && ro->ro_rt)
5612 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5613 struct pf_state *s, struct pf_pdesc *pd)
5616 struct route_in6 ip6route;
5617 struct route_in6 *ro;
5618 struct sockaddr_in6 *dst;
5619 struct ip6_hdr *ip6;
5620 struct ifnet *ifp = NULL;
5621 struct pf_addr naddr;
5622 struct pf_src_node *sn = NULL;
5625 if (m == NULL || *m == NULL || r == NULL ||
5626 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5627 panic("pf_route6: invalid parameters");
5629 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5630 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5631 (*m)->m_pkthdr.pf.routed = 1;
5633 if ((*m)->m_pkthdr.pf.routed++ > 3) {
5640 if (r->rt == PF_DUPTO) {
5641 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL)
5644 if ((r->rt == PF_REPLYTO) == (r->direction == dir))
5649 if (m0->m_len < sizeof(struct ip6_hdr)) {
5650 DPFPRINTF(PF_DEBUG_URGENT,
5651 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5654 ip6 = mtod(m0, struct ip6_hdr *);
5657 bzero((caddr_t)ro, sizeof(*ro));
5658 dst = (struct sockaddr_in6 *)&ro->ro_dst;
5659 dst->sin6_family = AF_INET6;
5660 dst->sin6_len = sizeof(*dst);
5661 dst->sin6_addr = ip6->ip6_dst;
5664 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
5665 * so make sure pf.flags is clear.
5667 * Cheat. XXX why only in the v6 case???
5669 if (r->rt == PF_FASTROUTE) {
5670 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
5671 m0->m_pkthdr.pf.flags = 0;
5672 /* XXX Re-Check when Upgrading to > 4.4 */
5673 m0->m_pkthdr.pf.statekey = NULL;
5674 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5678 if (TAILQ_EMPTY(&r->rpool.list)) {
5679 DPFPRINTF(PF_DEBUG_URGENT,
5680 ("pf_route6: TAILQ_EMPTY(&r->rpool.list)\n"));
5684 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5686 if (!PF_AZERO(&naddr, AF_INET6))
5687 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5689 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5691 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5692 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5693 &s->rt_addr, AF_INET6);
5694 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5700 if (pf_test6(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5702 } else if (m0 == NULL) {
5705 if (m0->m_len < sizeof(struct ip6_hdr)) {
5706 DPFPRINTF(PF_DEBUG_URGENT,
5707 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5710 ip6 = mtod(m0, struct ip6_hdr *);
5714 * If the packet is too large for the outgoing interface,
5715 * send back an icmp6 error.
5717 if (IN6_IS_ADDR_LINKLOCAL(&dst->sin6_addr))
5718 dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5719 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
5720 error = nd6_output(ifp, ifp, m0, dst, NULL);
5722 in6_ifstat_inc(ifp, ifs6_in_toobig);
5723 if (r->rt != PF_DUPTO)
5724 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5730 if (r->rt != PF_DUPTO)
5742 * check protocol (tcp/udp/icmp/icmp6) checksum and set mbuf flag
5743 * off is the offset where the protocol header starts
5744 * len is the total length of protocol header plus payload
5745 * returns 0 when the checksum is valid, otherwise returns 1.
5749 * FreeBSD supports cksum offload for the following drivers.
5750 * em(4), gx(4), lge(4), nge(4), ti(4), xl(4)
5751 * If we can make full use of it we would outperform ipfw/ipfilter in
5752 * very heavy traffic.
5753 * I have not tested 'cause I don't have NICs that supports cksum offload.
5754 * (There might be problems. Typical phenomena would be
5755 * 1. No route message for UDP packet.
5756 * 2. No connection acceptance from external hosts regardless of rule set.)
5759 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p,
5766 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5768 if (m->m_pkthdr.len < off + len)
5774 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5775 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5776 sum = m->m_pkthdr.csum_data;
5778 ip = mtod(m, struct ip *);
5779 sum = in_pseudo(ip->ip_src.s_addr,
5780 ip->ip_dst.s_addr, htonl((u_short)len +
5781 m->m_pkthdr.csum_data + p));
5789 case IPPROTO_ICMPV6:
5799 if (p == IPPROTO_ICMP) {
5804 sum = in_cksum(m, len);
5808 if (m->m_len < sizeof(struct ip))
5810 sum = in_cksum_range(m, p, off, len);
5812 m->m_pkthdr.csum_flags |=
5815 m->m_pkthdr.csum_data = 0xffff;
5821 if (m->m_len < sizeof(struct ip6_hdr))
5823 sum = in6_cksum(m, p, off, len);
5826 * IPv6 H/W cksum off-load not supported yet!
5829 * m->m_pkthdr.csum_flags |=
5830 * (CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
5831 * m->m_pkthdr.csum_data = 0xffff;
5843 tcpstat.tcps_rcvbadsum++;
5846 udpstat.udps_badsum++;
5849 icmpstat.icps_checksum++;
5852 case IPPROTO_ICMPV6:
5853 icmp6stat.icp6s_checksum++;
5863 pf_find_divert(struct mbuf *m)
5867 if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL)
5870 return ((struct pf_divert *)(mtag + 1));
5874 pf_get_divert(struct mbuf *m)
5878 if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL) {
5879 mtag = m_tag_get(PACKET_TAG_PF_DIVERT, sizeof(struct pf_divert),
5883 bzero(mtag + 1, sizeof(struct pf_divert));
5884 m_tag_prepend(m, mtag);
5887 return ((struct pf_divert *)(mtag + 1));
5892 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0,
5893 struct ether_header *eh, struct inpcb *inp)
5895 struct pfi_kif *kif;
5896 u_short action, reason = 0, log = 0;
5897 struct mbuf *m = *m0;
5898 struct ip *h = NULL;
5899 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
5900 struct pf_state *s = NULL;
5901 struct pf_ruleset *ruleset = NULL;
5903 int off, dirndx, pqid = 0;
5905 if (!pf_status.running)
5908 memset(&pd, 0, sizeof(pd));
5910 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
5911 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
5914 kif = (struct pfi_kif *)ifp->if_pf_kif;
5917 DPFPRINTF(PF_DEBUG_URGENT,
5918 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5921 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5925 if ((m->m_flags & M_PKTHDR) == 0)
5926 panic("non-M_PKTHDR is passed to pf_test");
5927 #endif /* DIAGNOSTIC */
5929 if (m->m_pkthdr.len < (int)sizeof(*h)) {
5931 REASON_SET(&reason, PFRES_SHORT);
5937 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
5938 * so make sure pf.flags is clear.
5940 if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
5942 m->m_pkthdr.pf.flags = 0;
5943 /* Re-Check when updating to > 4.4 */
5944 m->m_pkthdr.pf.statekey = NULL;
5946 /* We do IP header normalization and packet reassembly here */
5947 if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5951 m = *m0; /* pf_normalize messes with m0 */
5952 h = mtod(m, struct ip *);
5954 off = h->ip_hl << 2;
5955 if (off < (int)sizeof(*h)) {
5957 REASON_SET(&reason, PFRES_SHORT);
5962 pd.src = (struct pf_addr *)&h->ip_src;
5963 pd.dst = (struct pf_addr *)&h->ip_dst;
5964 pd.sport = pd.dport = NULL;
5965 pd.ip_sum = &h->ip_sum;
5966 pd.proto_sum = NULL;
5969 pd.sidx = (dir == PF_IN) ? 0 : 1;
5970 pd.didx = (dir == PF_IN) ? 1 : 0;
5973 pd.tot_len = h->ip_len;
5976 /* handle fragments that didn't get reassembled by normalization */
5977 if (h->ip_off & (IP_MF | IP_OFFMASK)) {
5978 action = pf_test_fragment(&r, dir, kif, m, h,
5989 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5990 &action, &reason, AF_INET)) {
5991 log = action != PF_PASS;
5994 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5995 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5997 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5998 if (action == PF_DROP)
6000 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6002 if (action == PF_PASS) {
6003 pfsync_update_state(s);
6007 } else if (s == NULL)
6008 action = pf_test_rule(&r, &s, dir, kif,
6009 m, off, h, &pd, &a, &ruleset, NULL, inp);
6017 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6018 &action, &reason, AF_INET)) {
6019 log = action != PF_PASS;
6022 if (uh.uh_dport == 0 ||
6023 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6024 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6026 REASON_SET(&reason, PFRES_SHORT);
6029 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6030 if (action == PF_PASS) {
6031 pfsync_update_state(s);
6035 } else if (s == NULL)
6036 action = pf_test_rule(&r, &s, dir, kif,
6037 m, off, h, &pd, &a, &ruleset, NULL, inp);
6041 case IPPROTO_ICMP: {
6045 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6046 &action, &reason, AF_INET)) {
6047 log = action != PF_PASS;
6050 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6052 if (action == PF_PASS) {
6053 pfsync_update_state(s);
6057 } else if (s == NULL)
6058 action = pf_test_rule(&r, &s, dir, kif,
6059 m, off, h, &pd, &a, &ruleset, NULL, inp);
6064 action = pf_test_state_other(&s, dir, kif, m, &pd);
6065 if (action == PF_PASS) {
6066 pfsync_update_state(s);
6070 } else if (s == NULL)
6071 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6072 &pd, &a, &ruleset, NULL, inp);
6077 if (action == PF_PASS && h->ip_hl > 5 &&
6078 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6080 REASON_SET(&reason, PFRES_IPOPTIONS);
6082 DPFPRINTF(PF_DEBUG_MISC,
6083 ("pf: dropping packet with ip options\n"));
6086 if ((s && s->tag) || r->rtableid)
6087 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6090 if (dir == PF_IN && s && s->key[PF_SK_STACK])
6091 m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6095 if (action == PF_PASS && r->qid) {
6096 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6097 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6098 m->m_pkthdr.pf.qid = r->pqid;
6100 m->m_pkthdr.pf.qid = r->qid;
6101 m->m_pkthdr.pf.ecn_af = AF_INET;
6102 m->m_pkthdr.pf.hdr = h;
6103 /* add connection hash for fairq */
6106 m->m_pkthdr.pf.state_hash = s->hash;
6107 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6113 * connections redirected to loopback should not match sockets
6114 * bound specifically to loopback due to security implications,
6115 * see tcp_input() and in_pcblookup_listen().
6117 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6118 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6119 (s->nat_rule.ptr->action == PF_RDR ||
6120 s->nat_rule.ptr->action == PF_BINAT) &&
6121 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6122 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6124 if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6125 struct pf_divert *divert;
6127 if ((divert = pf_get_divert(m))) {
6128 m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6129 divert->port = r->divert.port;
6130 divert->addr.ipv4 = r->divert.addr.v4;
6137 if (s != NULL && s->nat_rule.ptr != NULL &&
6138 s->nat_rule.ptr->log & PF_LOG_ALL)
6139 lr = s->nat_rule.ptr;
6142 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, lr, a, ruleset,
6146 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6147 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6149 if (action == PF_PASS || r->action == PF_DROP) {
6150 dirndx = (dir == PF_OUT);
6151 r->packets[dirndx]++;
6152 r->bytes[dirndx] += pd.tot_len;
6154 a->packets[dirndx]++;
6155 a->bytes[dirndx] += pd.tot_len;
6158 if (s->nat_rule.ptr != NULL) {
6159 s->nat_rule.ptr->packets[dirndx]++;
6160 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6162 if (s->src_node != NULL) {
6163 s->src_node->packets[dirndx]++;
6164 s->src_node->bytes[dirndx] += pd.tot_len;
6166 if (s->nat_src_node != NULL) {
6167 s->nat_src_node->packets[dirndx]++;
6168 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6170 dirndx = (dir == s->direction) ? 0 : 1;
6171 s->packets[dirndx]++;
6172 s->bytes[dirndx] += pd.tot_len;
6175 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6176 if (nr != NULL && r == &pf_default_rule)
6178 if (tr->src.addr.type == PF_ADDR_TABLE)
6179 pfr_update_stats(tr->src.addr.p.tbl,
6180 (s == NULL) ? pd.src :
6181 &s->key[(s->direction == PF_IN)]->
6182 addr[(s->direction == PF_OUT)],
6183 pd.af, pd.tot_len, dir == PF_OUT,
6184 r->action == PF_PASS, tr->src.neg);
6185 if (tr->dst.addr.type == PF_ADDR_TABLE)
6186 pfr_update_stats(tr->dst.addr.p.tbl,
6187 (s == NULL) ? pd.dst :
6188 &s->key[(s->direction == PF_IN)]->
6189 addr[(s->direction == PF_IN)],
6190 pd.af, pd.tot_len, dir == PF_OUT,
6191 r->action == PF_PASS, tr->dst.neg);
6195 if (action == PF_SYNPROXY_DROP) {
6200 /* pf_route can free the mbuf causing *m0 to become NULL */
6201 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6209 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0,
6210 struct ether_header *eh, struct inpcb *inp)
6212 struct pfi_kif *kif;
6213 u_short action, reason = 0, log = 0;
6214 struct mbuf *m = *m0, *n = NULL;
6215 struct ip6_hdr *h = NULL;
6216 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
6217 struct pf_state *s = NULL;
6218 struct pf_ruleset *ruleset = NULL;
6220 int off, terminal = 0, dirndx, rh_cnt = 0;
6222 if (!pf_status.running)
6225 memset(&pd, 0, sizeof(pd));
6227 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6228 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6231 kif = (struct pfi_kif *)ifp->if_pf_kif;
6234 DPFPRINTF(PF_DEBUG_URGENT,
6235 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6238 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6242 if ((m->m_flags & M_PKTHDR) == 0)
6243 panic("non-M_PKTHDR is passed to pf_test6");
6244 #endif /* DIAGNOSTIC */
6246 if (m->m_pkthdr.len < (int)sizeof(*h)) {
6248 REASON_SET(&reason, PFRES_SHORT);
6254 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6255 * so make sure pf.flags is clear.
6257 if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6259 m->m_pkthdr.pf.flags = 0;
6260 /* Re-Check when updating to > 4.4 */
6261 m->m_pkthdr.pf.statekey = NULL;
6263 /* We do IP header normalization and packet reassembly here */
6264 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6268 m = *m0; /* pf_normalize messes with m0 */
6269 h = mtod(m, struct ip6_hdr *);
6273 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6274 * will do something bad, so drop the packet for now.
6276 if (htons(h->ip6_plen) == 0) {
6278 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6283 pd.src = (struct pf_addr *)&h->ip6_src;
6284 pd.dst = (struct pf_addr *)&h->ip6_dst;
6285 pd.sport = pd.dport = NULL;
6287 pd.proto_sum = NULL;
6289 pd.sidx = (dir == PF_IN) ? 0 : 1;
6290 pd.didx = (dir == PF_IN) ? 1 : 0;
6293 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6296 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6297 pd.proto = h->ip6_nxt;
6300 case IPPROTO_FRAGMENT:
6301 action = pf_test_fragment(&r, dir, kif, m, h,
6303 if (action == PF_DROP)
6304 REASON_SET(&reason, PFRES_FRAG);
6306 case IPPROTO_ROUTING: {
6307 struct ip6_rthdr rthdr;
6310 DPFPRINTF(PF_DEBUG_MISC,
6311 ("pf: IPv6 more than one rthdr\n"));
6313 REASON_SET(&reason, PFRES_IPOPTIONS);
6317 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6319 DPFPRINTF(PF_DEBUG_MISC,
6320 ("pf: IPv6 short rthdr\n"));
6322 REASON_SET(&reason, PFRES_SHORT);
6326 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6327 DPFPRINTF(PF_DEBUG_MISC,
6328 ("pf: IPv6 rthdr0\n"));
6330 REASON_SET(&reason, PFRES_IPOPTIONS);
6337 case IPPROTO_HOPOPTS:
6338 case IPPROTO_DSTOPTS: {
6339 /* get next header and header length */
6340 struct ip6_ext opt6;
6342 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6343 NULL, &reason, pd.af)) {
6344 DPFPRINTF(PF_DEBUG_MISC,
6345 ("pf: IPv6 short opt\n"));
6350 if (pd.proto == IPPROTO_AH)
6351 off += (opt6.ip6e_len + 2) * 4;
6353 off += (opt6.ip6e_len + 1) * 8;
6354 pd.proto = opt6.ip6e_nxt;
6355 /* goto the next header */
6362 } while (!terminal);
6364 /* if there's no routing header, use unmodified mbuf for checksumming */
6374 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6375 &action, &reason, AF_INET6)) {
6376 log = action != PF_PASS;
6379 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6380 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6381 if (action == PF_DROP)
6383 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6385 if (action == PF_PASS) {
6386 pfsync_update_state(s);
6390 } else if (s == NULL)
6391 action = pf_test_rule(&r, &s, dir, kif,
6392 m, off, h, &pd, &a, &ruleset, NULL, inp);
6400 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6401 &action, &reason, AF_INET6)) {
6402 log = action != PF_PASS;
6405 if (uh.uh_dport == 0 ||
6406 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6407 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6409 REASON_SET(&reason, PFRES_SHORT);
6412 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6413 if (action == PF_PASS) {
6414 pfsync_update_state(s);
6418 } else if (s == NULL)
6419 action = pf_test_rule(&r, &s, dir, kif,
6420 m, off, h, &pd, &a, &ruleset, NULL, inp);
6424 case IPPROTO_ICMPV6: {
6425 struct icmp6_hdr ih;
6428 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6429 &action, &reason, AF_INET6)) {
6430 log = action != PF_PASS;
6433 action = pf_test_state_icmp(&s, dir, kif,
6434 m, off, h, &pd, &reason);
6435 if (action == PF_PASS) {
6436 pfsync_update_state(s);
6440 } else if (s == NULL)
6441 action = pf_test_rule(&r, &s, dir, kif,
6442 m, off, h, &pd, &a, &ruleset, NULL, inp);
6447 action = pf_test_state_other(&s, dir, kif, m, &pd);
6448 if (action == PF_PASS) {
6449 pfsync_update_state(s);
6453 } else if (s == NULL)
6454 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6455 &pd, &a, &ruleset, NULL, inp);
6465 /* handle dangerous IPv6 extension headers. */
6466 if (action == PF_PASS && rh_cnt &&
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 dangerous v6 headers\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 (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_INET6;
6491 m->m_pkthdr.pf.hdr = h;
6494 m->m_pkthdr.pf.state_hash = s->hash;
6495 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6500 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6501 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6502 (s->nat_rule.ptr->action == PF_RDR ||
6503 s->nat_rule.ptr->action == PF_BINAT) &&
6504 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6505 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6507 if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6508 struct pf_divert *divert;
6510 if ((divert = pf_get_divert(m))) {
6511 m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6512 divert->port = r->divert.port;
6513 divert->addr.ipv6 = r->divert.addr.v6;
6520 if (s != NULL && s->nat_rule.ptr != NULL &&
6521 s->nat_rule.ptr->log & PF_LOG_ALL)
6522 lr = s->nat_rule.ptr;
6525 PFLOG_PACKET(kif, h, m, AF_INET6, dir, reason, lr, a, ruleset,
6529 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6530 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6532 if (action == PF_PASS || r->action == PF_DROP) {
6533 dirndx = (dir == PF_OUT);
6534 r->packets[dirndx]++;
6535 r->bytes[dirndx] += pd.tot_len;
6537 a->packets[dirndx]++;
6538 a->bytes[dirndx] += pd.tot_len;
6541 if (s->nat_rule.ptr != NULL) {
6542 s->nat_rule.ptr->packets[dirndx]++;
6543 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6545 if (s->src_node != NULL) {
6546 s->src_node->packets[dirndx]++;
6547 s->src_node->bytes[dirndx] += pd.tot_len;
6549 if (s->nat_src_node != NULL) {
6550 s->nat_src_node->packets[dirndx]++;
6551 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6553 dirndx = (dir == s->direction) ? 0 : 1;
6554 s->packets[dirndx]++;
6555 s->bytes[dirndx] += pd.tot_len;
6558 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6559 if (nr != NULL && r == &pf_default_rule)
6561 if (tr->src.addr.type == PF_ADDR_TABLE)
6562 pfr_update_stats(tr->src.addr.p.tbl,
6563 (s == NULL) ? pd.src :
6564 &s->key[(s->direction == PF_IN)]->addr[0],
6565 pd.af, pd.tot_len, dir == PF_OUT,
6566 r->action == PF_PASS, tr->src.neg);
6567 if (tr->dst.addr.type == PF_ADDR_TABLE)
6568 pfr_update_stats(tr->dst.addr.p.tbl,
6569 (s == NULL) ? pd.dst :
6570 &s->key[(s->direction == PF_IN)]->addr[1],
6571 pd.af, pd.tot_len, dir == PF_OUT,
6572 r->action == PF_PASS, tr->dst.neg);
6576 if (action == PF_SYNPROXY_DROP) {
6581 /* pf_route6 can free the mbuf causing *m0 to become NULL */
6582 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6589 pf_check_congestion(struct ifqueue *ifq)