1 /* $OpenBSD: pf.c,v 1.552.2.1 2007/11/27 16:37:57 henning Exp $ */
2 /* add $OpenBSD: pf.c,v 1.553 2007/08/23 11:15:49 dhartmei Exp $ */
3 /* add $OpenBSD: pf.c,v 1.554 2007/08/28 16:09:12 henning Exp $ */
7 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
9 * Copyright (c) 2001 Daniel Hartmeier
10 * Copyright (c) 2002,2003 Henning Brauer
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
17 * - Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * - Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials provided
22 * with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 * POSSIBILITY OF SUCH DAMAGE.
37 * Effort sponsored in part by the Defense Advanced Research Projects
38 * Agency (DARPA) and Air Force Research Laboratory, Air Force
39 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
44 #include "opt_inet6.h"
45 #include "use_pfsync.h"
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/malloc.h>
51 #include <sys/filio.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/kernel.h>
56 #include <sys/sysctl.h>
57 #include <sys/endian.h>
58 #include <vm/vm_zone.h>
60 #include <sys/kthread.h>
62 #include <sys/mplock2.h>
64 #include <machine/inttypes.h>
67 #include <net/if_types.h>
69 #include <net/netisr.h>
70 #include <net/route.h>
72 #include <netinet/in.h>
73 #include <netinet/in_var.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/tcp.h>
78 #include <netinet/tcp_seq.h>
79 #include <netinet/udp.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/tcp_timer.h>
83 #include <netinet/tcp_var.h>
84 #include <netinet/udp_var.h>
85 #include <netinet/icmp_var.h>
86 #include <netinet/if_ether.h>
88 #include <net/pf/pfvar.h>
89 #include <net/pf/if_pflog.h>
92 #include <net/pf/if_pfsync.h>
93 #endif /* NPFSYNC > 0 */
96 #include <netinet/ip6.h>
97 #include <netinet/in_pcb.h>
98 #include <netinet/icmp6.h>
99 #include <netinet6/nd6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/in6_pcb.h>
104 #include <sys/in_cksum.h>
105 #include <sys/ucred.h>
106 #include <machine/limits.h>
107 #include <sys/msgport2.h>
108 #include <net/netmsg2.h>
110 extern int ip_optcopy(struct ip *, struct ip *);
111 extern int debug_pfugidhack;
113 struct lwkt_token pf_token = LWKT_TOKEN_MP_INITIALIZER(pf_token);
115 #define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
122 struct pf_state_tree_lan_ext pf_statetbl_lan_ext;
123 struct pf_state_tree_ext_gwy pf_statetbl_ext_gwy;
125 struct pf_altqqueue pf_altqs[2];
126 struct pf_palist pf_pabuf;
127 struct pf_altqqueue *pf_altqs_active;
128 struct pf_altqqueue *pf_altqs_inactive;
129 struct pf_status pf_status;
131 u_int32_t ticket_altqs_active;
132 u_int32_t ticket_altqs_inactive;
133 int altqs_inactive_open;
134 u_int32_t ticket_pabuf;
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 vm_zone_t pf_src_tree_pl, pf_rule_pl, pf_pooladdr_pl;
144 vm_zone_t pf_state_pl, pf_state_key_pl;
145 vm_zone_t 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_addr *, u_int16_t,
181 struct pf_addr *, u_int16_t,
182 struct pf_addr *, u_int16_t *);
183 void pf_attach_state(struct pf_state_key *,
184 struct pf_state *, int);
185 void pf_detach_state(struct pf_state *, int);
186 int pf_test_rule(struct pf_rule **, struct pf_state **,
187 int, struct pfi_kif *, struct mbuf *, int,
188 void *, struct pf_pdesc *, struct pf_rule **,
189 struct pf_ruleset **, struct ifqueue *, struct inpcb *);
190 int pf_test_fragment(struct pf_rule **, int,
191 struct pfi_kif *, struct mbuf *, void *,
192 struct pf_pdesc *, struct pf_rule **,
193 struct pf_ruleset **);
194 int pf_test_state_tcp(struct pf_state **, int,
195 struct pfi_kif *, struct mbuf *, int,
196 void *, struct pf_pdesc *, u_short *);
197 int pf_test_state_udp(struct pf_state **, int,
198 struct pfi_kif *, struct mbuf *, int,
199 void *, struct pf_pdesc *);
200 int pf_test_state_icmp(struct pf_state **, int,
201 struct pfi_kif *, struct mbuf *, int,
202 void *, struct pf_pdesc *, u_short *);
203 int pf_test_state_other(struct pf_state **, int,
204 struct pfi_kif *, struct pf_pdesc *);
205 int pf_match_tag(struct mbuf *, struct pf_rule *, int *);
206 void pf_step_into_anchor(int *, struct pf_ruleset **, int,
207 struct pf_rule **, struct pf_rule **, int *);
208 int pf_step_out_of_anchor(int *, struct pf_ruleset **,
209 int, struct pf_rule **, struct pf_rule **,
211 void pf_hash(struct pf_addr *, struct pf_addr *,
212 struct pf_poolhashkey *, sa_family_t);
213 int pf_map_addr(u_int8_t, struct pf_rule *,
214 struct pf_addr *, struct pf_addr *,
215 struct pf_addr *, struct pf_src_node **);
216 int pf_get_sport(sa_family_t, u_int8_t, struct pf_rule *,
217 struct pf_addr *, struct pf_addr *, u_int16_t,
218 struct pf_addr *, u_int16_t*, u_int16_t, u_int16_t,
219 struct pf_src_node **);
220 void pf_route(struct mbuf **, struct pf_rule *, int,
221 struct ifnet *, struct pf_state *,
223 void pf_route6(struct mbuf **, struct pf_rule *, int,
224 struct ifnet *, struct pf_state *,
226 u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
228 u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
230 u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
232 void pf_set_rt_ifp(struct pf_state *,
234 int pf_check_proto_cksum(struct mbuf *, int, int,
235 u_int8_t, sa_family_t);
236 int pf_addr_wrap_neq(struct pf_addr_wrap *,
237 struct pf_addr_wrap *);
238 struct pf_state *pf_find_state(struct pfi_kif *,
239 struct pf_state_key_cmp *, u_int8_t);
240 int pf_src_connlimit(struct pf_state **);
241 void pf_stateins_err(const char *, struct pf_state *,
243 int pf_check_congestion(struct ifqueue *);
245 extern int pf_end_threads;
247 struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
248 { &pf_state_pl, PFSTATE_HIWAT },
249 { &pf_src_tree_pl, PFSNODE_HIWAT },
250 { &pf_frent_pl, PFFRAG_FRENT_HIWAT },
251 { &pfr_ktable_pl, PFR_KTABLE_HIWAT },
252 { &pfr_kentry_pl, PFR_KENTRY_HIWAT }
255 #define STATE_LOOKUP() \
257 if (direction == PF_IN) \
258 *state = pf_find_state(kif, &key, PF_EXT_GWY); \
260 *state = pf_find_state(kif, &key, PF_LAN_EXT); \
261 if (*state == NULL || (*state)->timeout == PFTM_PURGE) \
263 if (direction == PF_OUT && \
264 (((*state)->rule.ptr->rt == PF_ROUTETO && \
265 (*state)->rule.ptr->direction == PF_OUT) || \
266 ((*state)->rule.ptr->rt == PF_REPLYTO && \
267 (*state)->rule.ptr->direction == PF_IN)) && \
268 (*state)->rt_kif != NULL && \
269 (*state)->rt_kif != kif) \
273 #define STATE_TRANSLATE(sk) \
274 (sk)->lan.addr.addr32[0] != (sk)->gwy.addr.addr32[0] || \
275 ((sk)->af == AF_INET6 && \
276 ((sk)->lan.addr.addr32[1] != (sk)->gwy.addr.addr32[1] || \
277 (sk)->lan.addr.addr32[2] != (sk)->gwy.addr.addr32[2] || \
278 (sk)->lan.addr.addr32[3] != (sk)->gwy.addr.addr32[3])) || \
279 (sk)->lan.port != (sk)->gwy.port
281 #define BOUND_IFACE(r, k) \
282 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
284 #define STATE_INC_COUNTERS(s) \
286 s->rule.ptr->states++; \
287 if (s->anchor.ptr != NULL) \
288 s->anchor.ptr->states++; \
289 if (s->nat_rule.ptr != NULL) \
290 s->nat_rule.ptr->states++; \
293 #define STATE_DEC_COUNTERS(s) \
295 if (s->nat_rule.ptr != NULL) \
296 s->nat_rule.ptr->states--; \
297 if (s->anchor.ptr != NULL) \
298 s->anchor.ptr->states--; \
299 s->rule.ptr->states--; \
302 static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
303 static __inline int pf_state_compare_lan_ext(struct pf_state_key *,
304 struct pf_state_key *);
305 static __inline int pf_state_compare_ext_gwy(struct pf_state_key *,
306 struct pf_state_key *);
307 static __inline int pf_state_compare_id(struct pf_state *,
310 struct pf_src_tree tree_src_tracking;
312 struct pf_state_tree_id tree_id;
313 struct pf_state_queue state_list;
315 RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
316 RB_GENERATE(pf_state_tree_lan_ext, pf_state_key,
317 entry_lan_ext, pf_state_compare_lan_ext);
318 RB_GENERATE(pf_state_tree_ext_gwy, pf_state_key,
319 entry_ext_gwy, pf_state_compare_ext_gwy);
320 RB_GENERATE(pf_state_tree_id, pf_state,
321 entry_id, pf_state_compare_id);
323 #define PF_DT_SKIP_LANEXT 0x01
324 #define PF_DT_SKIP_EXTGWY 0x02
327 pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
331 if (a->rule.ptr > b->rule.ptr)
333 if (a->rule.ptr < b->rule.ptr)
335 if ((diff = a->af - b->af) != 0)
340 if (a->addr.addr32[0] > b->addr.addr32[0])
342 if (a->addr.addr32[0] < b->addr.addr32[0])
348 if (a->addr.addr32[3] > b->addr.addr32[3])
350 if (a->addr.addr32[3] < b->addr.addr32[3])
352 if (a->addr.addr32[2] > b->addr.addr32[2])
354 if (a->addr.addr32[2] < b->addr.addr32[2])
356 if (a->addr.addr32[1] > b->addr.addr32[1])
358 if (a->addr.addr32[1] < b->addr.addr32[1])
360 if (a->addr.addr32[0] > b->addr.addr32[0])
362 if (a->addr.addr32[0] < b->addr.addr32[0])
371 pf_state_hash(struct pf_state_key *sk)
373 u_int32_t hv = (intptr_t)sk / sizeof(*sk);
375 hv ^= crc32(&sk->lan, sizeof(sk->lan));
376 hv ^= crc32(&sk->gwy, sizeof(sk->gwy));
377 hv ^= crc32(&sk->ext, sizeof(sk->ext));
378 if (hv == 0) /* disallow 0 */
384 pf_state_compare_lan_ext(struct pf_state_key *a, struct pf_state_key *b)
388 if ((diff = a->proto - b->proto) != 0)
390 if ((diff = a->af - b->af) != 0)
395 if (a->lan.addr.addr32[0] > b->lan.addr.addr32[0])
397 if (a->lan.addr.addr32[0] < b->lan.addr.addr32[0])
399 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
401 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
407 if (a->lan.addr.addr32[3] > b->lan.addr.addr32[3])
409 if (a->lan.addr.addr32[3] < b->lan.addr.addr32[3])
411 if (a->ext.addr.addr32[3] > b->ext.addr.addr32[3])
413 if (a->ext.addr.addr32[3] < b->ext.addr.addr32[3])
415 if (a->lan.addr.addr32[2] > b->lan.addr.addr32[2])
417 if (a->lan.addr.addr32[2] < b->lan.addr.addr32[2])
419 if (a->ext.addr.addr32[2] > b->ext.addr.addr32[2])
421 if (a->ext.addr.addr32[2] < b->ext.addr.addr32[2])
423 if (a->lan.addr.addr32[1] > b->lan.addr.addr32[1])
425 if (a->lan.addr.addr32[1] < b->lan.addr.addr32[1])
427 if (a->ext.addr.addr32[1] > b->ext.addr.addr32[1])
429 if (a->ext.addr.addr32[1] < b->ext.addr.addr32[1])
431 if (a->lan.addr.addr32[0] > b->lan.addr.addr32[0])
433 if (a->lan.addr.addr32[0] < b->lan.addr.addr32[0])
435 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
437 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
443 if ((diff = a->lan.port - b->lan.port) != 0)
445 if ((diff = a->ext.port - b->ext.port) != 0)
452 pf_state_compare_ext_gwy(struct pf_state_key *a, struct pf_state_key *b)
456 if ((diff = a->proto - b->proto) != 0)
458 if ((diff = a->af - b->af) != 0)
463 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
465 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
467 if (a->gwy.addr.addr32[0] > b->gwy.addr.addr32[0])
469 if (a->gwy.addr.addr32[0] < b->gwy.addr.addr32[0])
475 if (a->ext.addr.addr32[3] > b->ext.addr.addr32[3])
477 if (a->ext.addr.addr32[3] < b->ext.addr.addr32[3])
479 if (a->gwy.addr.addr32[3] > b->gwy.addr.addr32[3])
481 if (a->gwy.addr.addr32[3] < b->gwy.addr.addr32[3])
483 if (a->ext.addr.addr32[2] > b->ext.addr.addr32[2])
485 if (a->ext.addr.addr32[2] < b->ext.addr.addr32[2])
487 if (a->gwy.addr.addr32[2] > b->gwy.addr.addr32[2])
489 if (a->gwy.addr.addr32[2] < b->gwy.addr.addr32[2])
491 if (a->ext.addr.addr32[1] > b->ext.addr.addr32[1])
493 if (a->ext.addr.addr32[1] < b->ext.addr.addr32[1])
495 if (a->gwy.addr.addr32[1] > b->gwy.addr.addr32[1])
497 if (a->gwy.addr.addr32[1] < b->gwy.addr.addr32[1])
499 if (a->ext.addr.addr32[0] > b->ext.addr.addr32[0])
501 if (a->ext.addr.addr32[0] < b->ext.addr.addr32[0])
503 if (a->gwy.addr.addr32[0] > b->gwy.addr.addr32[0])
505 if (a->gwy.addr.addr32[0] < b->gwy.addr.addr32[0])
511 if ((diff = a->ext.port - b->ext.port) != 0)
513 if ((diff = a->gwy.port - b->gwy.port) != 0)
520 pf_state_compare_id(struct pf_state *a, struct pf_state *b)
526 if (a->creatorid > b->creatorid)
528 if (a->creatorid < b->creatorid)
536 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
541 dst->addr32[0] = src->addr32[0];
545 dst->addr32[0] = src->addr32[0];
546 dst->addr32[1] = src->addr32[1];
547 dst->addr32[2] = src->addr32[2];
548 dst->addr32[3] = src->addr32[3];
555 pf_find_state_byid(struct pf_state_cmp *key)
557 pf_status.fcounters[FCNT_STATE_SEARCH]++;
559 return (RB_FIND(pf_state_tree_id, &tree_id, (struct pf_state *)key));
563 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int8_t tree)
565 struct pf_state_key *sk;
568 pf_status.fcounters[FCNT_STATE_SEARCH]++;
572 sk = RB_FIND(pf_state_tree_lan_ext, &pf_statetbl_lan_ext,
573 (struct pf_state_key *)key);
576 sk = RB_FIND(pf_state_tree_ext_gwy, &pf_statetbl_ext_gwy,
577 (struct pf_state_key *)key);
580 panic("pf_find_state");
583 /* list is sorted, if-bound states before floating ones */
585 TAILQ_FOREACH(s, &sk->states, next)
586 if (s->kif == pfi_all || s->kif == kif)
593 pf_find_state_all(struct pf_state_key_cmp *key, u_int8_t tree, int *more)
595 struct pf_state_key *sk;
596 struct pf_state *s, *ret = NULL;
598 pf_status.fcounters[FCNT_STATE_SEARCH]++;
602 sk = RB_FIND(pf_state_tree_lan_ext,
603 &pf_statetbl_lan_ext, (struct pf_state_key *)key);
606 sk = RB_FIND(pf_state_tree_ext_gwy,
607 &pf_statetbl_ext_gwy, (struct pf_state_key *)key);
610 panic("pf_find_state_all");
614 ret = TAILQ_FIRST(&sk->states);
618 TAILQ_FOREACH(s, &sk->states, next)
626 pf_init_threshold(struct pf_threshold *threshold,
627 u_int32_t limit, u_int32_t seconds)
629 threshold->limit = limit * PF_THRESHOLD_MULT;
630 threshold->seconds = seconds;
631 threshold->count = 0;
632 threshold->last = time_second;
636 pf_add_threshold(struct pf_threshold *threshold)
638 u_int32_t t = time_second, diff = t - threshold->last;
640 if (diff >= threshold->seconds)
641 threshold->count = 0;
643 threshold->count -= threshold->count * diff /
645 threshold->count += PF_THRESHOLD_MULT;
650 pf_check_threshold(struct pf_threshold *threshold)
652 return (threshold->count > threshold->limit);
656 pf_src_connlimit(struct pf_state **state)
660 (*state)->src_node->conn++;
661 (*state)->src.tcp_est = 1;
662 pf_add_threshold(&(*state)->src_node->conn_rate);
664 if ((*state)->rule.ptr->max_src_conn &&
665 (*state)->rule.ptr->max_src_conn <
666 (*state)->src_node->conn) {
667 pf_status.lcounters[LCNT_SRCCONN]++;
671 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
672 pf_check_threshold(&(*state)->src_node->conn_rate)) {
673 pf_status.lcounters[LCNT_SRCCONNRATE]++;
680 if ((*state)->rule.ptr->overload_tbl) {
682 u_int32_t killed = 0;
684 pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
685 if (pf_status.debug >= PF_DEBUG_MISC) {
686 kprintf("pf_src_connlimit: blocking address ");
687 pf_print_host(&(*state)->src_node->addr, 0,
688 (*state)->state_key->af);
691 bzero(&p, sizeof(p));
692 p.pfra_af = (*state)->state_key->af;
693 switch ((*state)->state_key->af) {
697 p.pfra_ip4addr = (*state)->src_node->addr.v4;
703 p.pfra_ip6addr = (*state)->src_node->addr.v6;
708 pfr_insert_kentry((*state)->rule.ptr->overload_tbl,
711 /* kill existing states if that's required. */
712 if ((*state)->rule.ptr->flush) {
713 struct pf_state_key *sk;
716 pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
717 RB_FOREACH(st, pf_state_tree_id, &tree_id) {
720 * Kill states from this source. (Only those
721 * from the same rule if PF_FLUSH_GLOBAL is not
725 (*state)->state_key->af &&
726 (((*state)->state_key->direction ==
728 PF_AEQ(&(*state)->src_node->addr,
729 &sk->lan.addr, sk->af)) ||
730 ((*state)->state_key->direction == PF_IN &&
731 PF_AEQ(&(*state)->src_node->addr,
732 &sk->ext.addr, sk->af))) &&
733 ((*state)->rule.ptr->flush &
735 (*state)->rule.ptr == st->rule.ptr)) {
736 st->timeout = PFTM_PURGE;
737 st->src.state = st->dst.state =
742 if (pf_status.debug >= PF_DEBUG_MISC)
743 kprintf(", %u states killed", killed);
745 if (pf_status.debug >= PF_DEBUG_MISC)
749 /* kill this state */
750 (*state)->timeout = PFTM_PURGE;
751 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
756 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
757 struct pf_addr *src, sa_family_t af)
759 struct pf_src_node k;
763 PF_ACPY(&k.addr, src, af);
764 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
765 rule->rpool.opts & PF_POOL_STICKYADDR)
769 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
770 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
773 if (!rule->max_src_nodes ||
774 rule->src_nodes < rule->max_src_nodes)
775 (*sn) = pool_get(&pf_src_tree_pl, PR_NOWAIT);
777 pf_status.lcounters[LCNT_SRCNODES]++;
780 bzero(*sn, sizeof(struct pf_src_node));
782 pf_init_threshold(&(*sn)->conn_rate,
783 rule->max_src_conn_rate.limit,
784 rule->max_src_conn_rate.seconds);
787 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
788 rule->rpool.opts & PF_POOL_STICKYADDR)
789 (*sn)->rule.ptr = rule;
791 (*sn)->rule.ptr = NULL;
792 PF_ACPY(&(*sn)->addr, src, af);
793 if (RB_INSERT(pf_src_tree,
794 &tree_src_tracking, *sn) != NULL) {
795 if (pf_status.debug >= PF_DEBUG_MISC) {
796 kprintf("pf: src_tree insert failed: ");
797 pf_print_host(&(*sn)->addr, 0, af);
800 pool_put(&pf_src_tree_pl, *sn);
803 (*sn)->creation = time_second;
804 (*sn)->ruletype = rule->action;
805 if ((*sn)->rule.ptr != NULL)
806 (*sn)->rule.ptr->src_nodes++;
807 pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
808 pf_status.src_nodes++;
810 if (rule->max_src_states &&
811 (*sn)->states >= rule->max_src_states) {
812 pf_status.lcounters[LCNT_SRCSTATES]++;
820 pf_stateins_err(const char *tree, struct pf_state *s, struct pfi_kif *kif)
822 struct pf_state_key *sk = s->state_key;
824 if (pf_status.debug >= PF_DEBUG_MISC) {
825 kprintf("pf: state insert failed: %s %s", tree, kif->pfik_name);
827 pf_print_host(&sk->lan.addr, sk->lan.port,
830 pf_print_host(&sk->gwy.addr, sk->gwy.port,
833 pf_print_host(&sk->ext.addr, sk->ext.port,
835 if (s->sync_flags & PFSTATE_FROMSYNC)
836 kprintf(" (from sync)");
842 pf_insert_state(struct pfi_kif *kif, struct pf_state *s)
844 struct pf_state_key *cur;
847 KKASSERT(s->state_key != NULL);
850 if ((cur = RB_INSERT(pf_state_tree_lan_ext, &pf_statetbl_lan_ext,
851 s->state_key)) != NULL) {
852 /* key exists. check for same kif, if none, add to key */
853 TAILQ_FOREACH(sp, &cur->states, next)
854 if (sp->kif == kif) { /* collision! */
855 pf_stateins_err("tree_lan_ext", s, kif);
857 PF_DT_SKIP_LANEXT|PF_DT_SKIP_EXTGWY);
860 pf_detach_state(s, PF_DT_SKIP_LANEXT|PF_DT_SKIP_EXTGWY);
861 pf_attach_state(cur, s, kif == pfi_all ? 1 : 0);
864 /* if cur != NULL, we already found a state key and attached to it */
865 if (cur == NULL && (cur = RB_INSERT(pf_state_tree_ext_gwy,
866 &pf_statetbl_ext_gwy, s->state_key)) != NULL) {
867 /* must not happen. we must have found the sk above! */
868 pf_stateins_err("tree_ext_gwy", s, kif);
869 pf_detach_state(s, PF_DT_SKIP_EXTGWY);
873 if (s->id == 0 && s->creatorid == 0) {
874 s->id = htobe64(pf_status.stateid++);
875 s->creatorid = pf_status.hostid;
877 if (RB_INSERT(pf_state_tree_id, &tree_id, s) != NULL) {
878 if (pf_status.debug >= PF_DEBUG_MISC) {
879 kprintf("pf: state insert failed: "
880 "id: %016llx creatorid: %08x",
881 be64toh(s->id), ntohl(s->creatorid));
882 if (s->sync_flags & PFSTATE_FROMSYNC)
883 kprintf(" (from sync)");
886 pf_detach_state(s, 0);
889 TAILQ_INSERT_TAIL(&state_list, s, entry_list);
890 pf_status.fcounters[FCNT_STATE_INSERT]++;
892 pfi_kif_ref(kif, PFI_KIF_REF_STATE);
894 pfsync_insert_state(s);
900 pf_purge_thread(void *v)
907 tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
909 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
911 if (pf_end_threads) {
912 pf_purge_expired_states(pf_status.states, 1);
913 pf_purge_expired_fragments();
914 pf_purge_expired_src_nodes(1);
917 lockmgr(&pf_consistency_lock, LK_RELEASE);
918 wakeup(pf_purge_thread);
923 /* process a fraction of the state table every second */
924 if(!pf_purge_expired_states(1 + (pf_status.states
925 / pf_default_rule.timeout[PFTM_INTERVAL]), 0)) {
927 pf_purge_expired_states(1 + (pf_status.states
928 / pf_default_rule.timeout[PFTM_INTERVAL]), 1);
931 /* purge other expired types every PFTM_INTERVAL seconds */
932 if (++nloops >= pf_default_rule.timeout[PFTM_INTERVAL]) {
933 pf_purge_expired_fragments();
934 if (!pf_purge_expired_src_nodes(locked)) {
935 pf_purge_expired_src_nodes(1);
940 lockmgr(&pf_consistency_lock, LK_RELEASE);
946 pf_state_expires(const struct pf_state *state)
953 /* handle all PFTM_* > PFTM_MAX here */
954 if (state->timeout == PFTM_PURGE)
955 return (time_second);
956 if (state->timeout == PFTM_UNTIL_PACKET)
958 KKASSERT(state->timeout != PFTM_UNLINKED);
959 KASSERT((state->timeout < PFTM_MAX),
960 ("pf_state_expires: timeout > PFTM_MAX"));
961 timeout = state->rule.ptr->timeout[state->timeout];
963 timeout = pf_default_rule.timeout[state->timeout];
964 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
966 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
967 states = state->rule.ptr->states;
969 start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
970 end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
971 states = pf_status.states;
973 if (end && states > start && start < end) {
975 return (state->expire + timeout * (end - states) /
978 return (time_second);
980 return (state->expire + timeout);
984 pf_purge_expired_src_nodes(int waslocked)
986 struct pf_src_node *cur, *next;
987 int locked = waslocked;
989 for (cur = RB_MIN(pf_src_tree, &tree_src_tracking); cur; cur = next) {
990 next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
992 if (cur->states <= 0 && cur->expire <= time_second) {
994 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
995 next = RB_NEXT(pf_src_tree,
996 &tree_src_tracking, cur);
999 if (cur->rule.ptr != NULL) {
1000 cur->rule.ptr->src_nodes--;
1001 if (cur->rule.ptr->states <= 0 &&
1002 cur->rule.ptr->max_src_nodes <= 0)
1003 pf_rm_rule(NULL, cur->rule.ptr);
1005 RB_REMOVE(pf_src_tree, &tree_src_tracking, cur);
1006 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1007 pf_status.src_nodes--;
1008 pool_put(&pf_src_tree_pl, cur);
1012 if (locked && !waslocked)
1013 lockmgr(&pf_consistency_lock, LK_RELEASE);
1018 pf_src_tree_remove_state(struct pf_state *s)
1022 if (s->src_node != NULL) {
1024 --s->src_node->conn;
1025 if (--s->src_node->states <= 0) {
1026 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1029 pf_default_rule.timeout[PFTM_SRC_NODE];
1030 s->src_node->expire = time_second + timeout;
1033 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1034 if (--s->nat_src_node->states <= 0) {
1035 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1038 pf_default_rule.timeout[PFTM_SRC_NODE];
1039 s->nat_src_node->expire = time_second + timeout;
1042 s->src_node = s->nat_src_node = NULL;
1045 /* callers should be at crit_enter() */
1047 pf_unlink_state(struct pf_state *cur)
1049 if (cur->src.state == PF_TCPS_PROXY_DST) {
1050 lwkt_reltoken(&pf_token);
1051 pf_send_tcp(cur->rule.ptr, cur->state_key->af,
1052 &cur->state_key->ext.addr, &cur->state_key->lan.addr,
1053 cur->state_key->ext.port, cur->state_key->lan.port,
1054 cur->src.seqhi, cur->src.seqlo + 1,
1055 TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1056 lwkt_gettoken(&pf_token);
1058 RB_REMOVE(pf_state_tree_id, &tree_id, cur);
1060 if (cur->creatorid == pf_status.hostid)
1061 pfsync_delete_state(cur);
1063 cur->timeout = PFTM_UNLINKED;
1064 pf_src_tree_remove_state(cur);
1065 pf_detach_state(cur, 0);
1068 /* callers should be at crit_enter() and hold the
1069 * write_lock on pf_consistency_lock */
1071 pf_free_state(struct pf_state *cur)
1074 if (pfsyncif != NULL &&
1075 (pfsyncif->sc_bulk_send_next == cur ||
1076 pfsyncif->sc_bulk_terminator == cur))
1079 KKASSERT(cur->timeout == PFTM_UNLINKED);
1080 if (--cur->rule.ptr->states <= 0 &&
1081 cur->rule.ptr->src_nodes <= 0)
1082 pf_rm_rule(NULL, cur->rule.ptr);
1083 if (cur->nat_rule.ptr != NULL)
1084 if (--cur->nat_rule.ptr->states <= 0 &&
1085 cur->nat_rule.ptr->src_nodes <= 0)
1086 pf_rm_rule(NULL, cur->nat_rule.ptr);
1087 if (cur->anchor.ptr != NULL)
1088 if (--cur->anchor.ptr->states <= 0)
1089 pf_rm_rule(NULL, cur->anchor.ptr);
1090 pf_normalize_tcp_cleanup(cur);
1091 pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1092 TAILQ_REMOVE(&state_list, cur, entry_list);
1094 pf_tag_unref(cur->tag);
1095 pool_put(&pf_state_pl, cur);
1096 pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1101 pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1103 static struct pf_state *cur = NULL;
1104 struct pf_state *next;
1105 int locked = waslocked;
1107 while (maxcheck--) {
1108 /* wrap to start of list when we hit the end */
1110 cur = TAILQ_FIRST(&state_list);
1112 break; /* list empty */
1115 /* get next state, as cur may get deleted */
1116 next = TAILQ_NEXT(cur, entry_list);
1118 if (cur->timeout == PFTM_UNLINKED) {
1119 /* free unlinked state */
1121 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1125 } else if (pf_state_expires(cur) <= time_second) {
1126 /* unlink and free expired state */
1127 pf_unlink_state(cur);
1129 if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1139 lockmgr(&pf_consistency_lock, LK_RELEASE);
1144 pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1146 if (aw->type != PF_ADDR_TABLE)
1148 if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1154 pf_tbladdr_remove(struct pf_addr_wrap *aw)
1156 if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1158 pfr_detach_table(aw->p.tbl);
1163 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1165 struct pfr_ktable *kt = aw->p.tbl;
1167 if (aw->type != PF_ADDR_TABLE || kt == NULL)
1169 if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1170 kt = kt->pfrkt_root;
1172 aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1177 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1182 u_int32_t a = ntohl(addr->addr32[0]);
1183 kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1195 u_int8_t i, curstart = 255, curend = 0,
1196 maxstart = 0, maxend = 0;
1197 for (i = 0; i < 8; i++) {
1198 if (!addr->addr16[i]) {
1199 if (curstart == 255)
1205 if ((curend - curstart) >
1206 (maxend - maxstart)) {
1207 maxstart = curstart;
1214 for (i = 0; i < 8; i++) {
1215 if (i >= maxstart && i <= maxend) {
1224 b = ntohs(addr->addr16[i]);
1241 pf_print_state(struct pf_state *s)
1243 struct pf_state_key *sk = s->state_key;
1244 switch (sk->proto) {
1254 case IPPROTO_ICMPV6:
1258 kprintf("%u ", sk->proto);
1261 pf_print_host(&sk->lan.addr, sk->lan.port, sk->af);
1263 pf_print_host(&sk->gwy.addr, sk->gwy.port, sk->af);
1265 pf_print_host(&sk->ext.addr, sk->ext.port, sk->af);
1266 kprintf(" [lo=%u high=%u win=%u modulator=%u", s->src.seqlo,
1267 s->src.seqhi, s->src.max_win, s->src.seqdiff);
1268 if (s->src.wscale && s->dst.wscale)
1269 kprintf(" wscale=%u", s->src.wscale & PF_WSCALE_MASK);
1271 kprintf(" [lo=%u high=%u win=%u modulator=%u", s->dst.seqlo,
1272 s->dst.seqhi, s->dst.max_win, s->dst.seqdiff);
1273 if (s->src.wscale && s->dst.wscale)
1274 kprintf(" wscale=%u", s->dst.wscale & PF_WSCALE_MASK);
1276 kprintf(" %u:%u", s->src.state, s->dst.state);
1280 pf_print_flags(u_int8_t f)
1302 #define PF_SET_SKIP_STEPS(i) \
1304 while (head[i] != cur) { \
1305 head[i]->skip[i].ptr = cur; \
1306 head[i] = TAILQ_NEXT(head[i], entries); \
1311 pf_calc_skip_steps(struct pf_rulequeue *rules)
1313 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1316 cur = TAILQ_FIRST(rules);
1318 for (i = 0; i < PF_SKIP_COUNT; ++i)
1320 while (cur != NULL) {
1322 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1323 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1324 if (cur->direction != prev->direction)
1325 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1326 if (cur->af != prev->af)
1327 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1328 if (cur->proto != prev->proto)
1329 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1330 if (cur->src.neg != prev->src.neg ||
1331 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1332 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1333 if (cur->src.port[0] != prev->src.port[0] ||
1334 cur->src.port[1] != prev->src.port[1] ||
1335 cur->src.port_op != prev->src.port_op)
1336 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1337 if (cur->dst.neg != prev->dst.neg ||
1338 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1339 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1340 if (cur->dst.port[0] != prev->dst.port[0] ||
1341 cur->dst.port[1] != prev->dst.port[1] ||
1342 cur->dst.port_op != prev->dst.port_op)
1343 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1346 cur = TAILQ_NEXT(cur, entries);
1348 for (i = 0; i < PF_SKIP_COUNT; ++i)
1349 PF_SET_SKIP_STEPS(i);
1353 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1355 if (aw1->type != aw2->type)
1357 switch (aw1->type) {
1358 case PF_ADDR_ADDRMASK:
1359 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1361 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1364 case PF_ADDR_DYNIFTL:
1365 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1366 case PF_ADDR_NOROUTE:
1367 case PF_ADDR_URPFFAILED:
1370 return (aw1->p.tbl != aw2->p.tbl);
1371 case PF_ADDR_RTLABEL:
1372 return (aw1->v.rtlabel != aw2->v.rtlabel);
1374 kprintf("invalid address type: %d\n", aw1->type);
1380 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1386 l = cksum + old - new;
1387 l = (l >> 16) + (l & 65535);
1395 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1396 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1401 PF_ACPY(&ao, a, af);
1409 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1410 ao.addr16[0], an->addr16[0], 0),
1411 ao.addr16[1], an->addr16[1], 0);
1413 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1414 ao.addr16[0], an->addr16[0], u),
1415 ao.addr16[1], an->addr16[1], u),
1421 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1422 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1423 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1424 ao.addr16[0], an->addr16[0], u),
1425 ao.addr16[1], an->addr16[1], u),
1426 ao.addr16[2], an->addr16[2], u),
1427 ao.addr16[3], an->addr16[3], u),
1428 ao.addr16[4], an->addr16[4], u),
1429 ao.addr16[5], an->addr16[5], u),
1430 ao.addr16[6], an->addr16[6], u),
1431 ao.addr16[7], an->addr16[7], u),
1439 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
1441 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1445 memcpy(&ao, a, sizeof(ao));
1446 memcpy(a, &an, sizeof(u_int32_t));
1447 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1448 ao % 65536, an % 65536, u);
1453 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1457 PF_ACPY(&ao, a, AF_INET6);
1458 PF_ACPY(a, an, AF_INET6);
1460 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1461 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1462 pf_cksum_fixup(pf_cksum_fixup(*c,
1463 ao.addr16[0], an->addr16[0], u),
1464 ao.addr16[1], an->addr16[1], u),
1465 ao.addr16[2], an->addr16[2], u),
1466 ao.addr16[3], an->addr16[3], u),
1467 ao.addr16[4], an->addr16[4], u),
1468 ao.addr16[5], an->addr16[5], u),
1469 ao.addr16[6], an->addr16[6], u),
1470 ao.addr16[7], an->addr16[7], u);
1475 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1476 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1477 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1479 struct pf_addr oia, ooa;
1481 PF_ACPY(&oia, ia, af);
1482 PF_ACPY(&ooa, oa, af);
1484 /* Change inner protocol port, fix inner protocol checksum. */
1486 u_int16_t oip = *ip;
1493 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
1494 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1496 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1498 /* Change inner ip address, fix inner ip and icmp checksums. */
1499 PF_ACPY(ia, na, af);
1503 u_int32_t oh2c = *h2c;
1505 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1506 oia.addr16[0], ia->addr16[0], 0),
1507 oia.addr16[1], ia->addr16[1], 0);
1508 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1509 oia.addr16[0], ia->addr16[0], 0),
1510 oia.addr16[1], ia->addr16[1], 0);
1511 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1517 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1518 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1519 pf_cksum_fixup(pf_cksum_fixup(*ic,
1520 oia.addr16[0], ia->addr16[0], u),
1521 oia.addr16[1], ia->addr16[1], u),
1522 oia.addr16[2], ia->addr16[2], u),
1523 oia.addr16[3], ia->addr16[3], u),
1524 oia.addr16[4], ia->addr16[4], u),
1525 oia.addr16[5], ia->addr16[5], u),
1526 oia.addr16[6], ia->addr16[6], u),
1527 oia.addr16[7], ia->addr16[7], u);
1531 /* Change outer ip address, fix outer ip or icmpv6 checksum. */
1532 PF_ACPY(oa, na, af);
1536 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
1537 ooa.addr16[0], oa->addr16[0], 0),
1538 ooa.addr16[1], oa->addr16[1], 0);
1543 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1544 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1545 pf_cksum_fixup(pf_cksum_fixup(*ic,
1546 ooa.addr16[0], oa->addr16[0], u),
1547 ooa.addr16[1], oa->addr16[1], u),
1548 ooa.addr16[2], oa->addr16[2], u),
1549 ooa.addr16[3], oa->addr16[3], u),
1550 ooa.addr16[4], oa->addr16[4], u),
1551 ooa.addr16[5], oa->addr16[5], u),
1552 ooa.addr16[6], oa->addr16[6], u),
1553 ooa.addr16[7], oa->addr16[7], u);
1561 * Need to modulate the sequence numbers in the TCP SACK option
1562 * (credits to Krzysztof Pfaff for report and patch)
1565 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
1566 struct tcphdr *th, struct pf_state_peer *dst)
1568 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
1569 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
1570 int copyback = 0, i, olen;
1571 struct raw_sackblock sack;
1573 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
1574 if (hlen < TCPOLEN_SACKLEN ||
1575 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
1578 while (hlen >= TCPOLEN_SACKLEN) {
1581 case TCPOPT_EOL: /* FALLTHROUGH */
1589 if (olen >= TCPOLEN_SACKLEN) {
1590 for (i = 2; i + TCPOLEN_SACK <= olen;
1591 i += TCPOLEN_SACK) {
1592 memcpy(&sack, &opt[i], sizeof(sack));
1593 pf_change_a(&sack.rblk_start, &th->th_sum,
1594 htonl(ntohl(sack.rblk_start) -
1596 pf_change_a(&sack.rblk_end, &th->th_sum,
1597 htonl(ntohl(sack.rblk_end) -
1599 memcpy(&opt[i], &sack, sizeof(sack));
1613 m_copyback(m, off + sizeof(*th), thoptlen, opts);
1618 pf_send_tcp(const struct pf_rule *r, sa_family_t af,
1619 const struct pf_addr *saddr, const struct pf_addr *daddr,
1620 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
1621 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
1622 u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
1627 struct ip *h = NULL;
1630 struct ip6_hdr *h6 = NULL;
1632 struct tcphdr *th = NULL;
1635 lwkt_gettoken(&pf_token);
1637 /* maximum segment size tcp option */
1638 tlen = sizeof(struct tcphdr);
1645 len = sizeof(struct ip) + tlen;
1650 len = sizeof(struct ip6_hdr) + tlen;
1655 /* create outgoing mbuf */
1656 m = m_gethdr(MB_DONTWAIT, MT_HEADER);
1658 lwkt_reltoken(&pf_token);
1662 m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
1663 m->m_pkthdr.pf.tag = rtag;
1665 if (r != NULL && r->rtableid >= 0)
1666 m->m_pkthdr.pf.rtableid = r->rtableid;
1669 if (r != NULL && r->qid) {
1670 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1671 m->m_pkthdr.pf.qid = r->qid;
1672 m->m_pkthdr.pf.ecn_af = af;
1673 m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
1676 m->m_data += max_linkhdr;
1677 m->m_pkthdr.len = m->m_len = len;
1678 m->m_pkthdr.rcvif = NULL;
1679 bzero(m->m_data, len);
1683 h = mtod(m, struct ip *);
1685 /* IP header fields included in the TCP checksum */
1686 h->ip_p = IPPROTO_TCP;
1688 h->ip_src.s_addr = saddr->v4.s_addr;
1689 h->ip_dst.s_addr = daddr->v4.s_addr;
1691 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
1696 h6 = mtod(m, struct ip6_hdr *);
1698 /* IP header fields included in the TCP checksum */
1699 h6->ip6_nxt = IPPROTO_TCP;
1700 h6->ip6_plen = htons(tlen);
1701 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
1702 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
1704 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
1710 th->th_sport = sport;
1711 th->th_dport = dport;
1712 th->th_seq = htonl(seq);
1713 th->th_ack = htonl(ack);
1714 th->th_off = tlen >> 2;
1715 th->th_flags = flags;
1716 th->th_win = htons(win);
1719 opt = (char *)(th + 1);
1720 opt[0] = TCPOPT_MAXSEG;
1723 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
1730 th->th_sum = in_cksum(m, len);
1732 /* Finish the IP header */
1734 h->ip_hl = sizeof(*h) >> 2;
1735 h->ip_tos = IPTOS_LOWDELAY;
1737 h->ip_off = path_mtu_discovery ? IP_DF : 0;
1738 h->ip_ttl = ttl ? ttl : ip_defttl;
1741 lwkt_reltoken(&pf_token);
1742 ip_output(m, NULL, NULL, 0, NULL, NULL);
1743 lwkt_gettoken(&pf_token);
1747 struct ether_header *e = (void *)ro.ro_dst.sa_data;
1751 lwkt_reltoken(&pf_token);
1756 ro.ro_dst.sa_len = sizeof(ro.ro_dst);
1757 ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
1758 bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
1759 bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
1760 e->ether_type = eh->ether_type;
1761 /* XXX_IMPORT: later */
1762 lwkt_reltoken(&pf_token);
1763 ip_output(m, (void *)NULL, &ro, 0,
1764 (void *)NULL, (void *)NULL);
1765 lwkt_gettoken(&pf_token);
1772 th->th_sum = in6_cksum(m, IPPROTO_TCP,
1773 sizeof(struct ip6_hdr), tlen);
1775 h6->ip6_vfc |= IPV6_VERSION;
1776 h6->ip6_hlim = IPV6_DEFHLIM;
1778 lwkt_reltoken(&pf_token);
1779 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1780 lwkt_gettoken(&pf_token);
1784 lwkt_reltoken(&pf_token);
1788 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
1793 m0 = m_copy(m, 0, M_COPYALL);
1794 m0->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
1796 if (r->rtableid >= 0)
1797 m0->m_pkthdr.pf.rtableid = r->rtableid;
1801 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1802 m0->m_pkthdr.pf.qid = r->qid;
1803 m0->m_pkthdr.pf.ecn_af = af;
1804 m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
1811 icmp_error(m0, type, code, 0, 0);
1816 icmp6_error(m0, type, code, 0);
1823 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
1824 * If n is 0, they match if they are equal. If n is != 0, they match if they
1828 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
1829 struct pf_addr *b, sa_family_t af)
1836 if ((a->addr32[0] & m->addr32[0]) ==
1837 (b->addr32[0] & m->addr32[0]))
1843 if (((a->addr32[0] & m->addr32[0]) ==
1844 (b->addr32[0] & m->addr32[0])) &&
1845 ((a->addr32[1] & m->addr32[1]) ==
1846 (b->addr32[1] & m->addr32[1])) &&
1847 ((a->addr32[2] & m->addr32[2]) ==
1848 (b->addr32[2] & m->addr32[2])) &&
1849 ((a->addr32[3] & m->addr32[3]) ==
1850 (b->addr32[3] & m->addr32[3])))
1869 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
1873 return ((p > a1) && (p < a2));
1875 return ((p < a1) || (p > a2));
1877 return ((p >= a1) && (p <= a2));
1891 return (0); /* never reached */
1895 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
1900 return (pf_match(op, a1, a2, p));
1904 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
1906 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
1908 return (pf_match(op, a1, a2, u));
1912 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
1914 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
1916 return (pf_match(op, a1, a2, g));
1920 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
1923 *tag = m->m_pkthdr.pf.tag;
1925 return ((!r->match_tag_not && r->match_tag == *tag) ||
1926 (r->match_tag_not && r->match_tag != *tag));
1930 pf_tag_packet(struct mbuf *m, int tag, int rtableid)
1932 if (tag <= 0 && rtableid < 0)
1936 m->m_pkthdr.pf.tag = tag;
1938 m->m_pkthdr.pf.rtableid = rtableid;
1944 pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
1945 struct pf_rule **r, struct pf_rule **a, int *match)
1947 struct pf_anchor_stackframe *f;
1949 (*r)->anchor->match = 0;
1952 if (*depth >= sizeof(pf_anchor_stack) /
1953 sizeof(pf_anchor_stack[0])) {
1954 kprintf("pf_step_into_anchor: stack overflow\n");
1955 *r = TAILQ_NEXT(*r, entries);
1957 } else if (*depth == 0 && a != NULL)
1959 f = pf_anchor_stack + (*depth)++;
1962 if ((*r)->anchor_wildcard) {
1963 f->parent = &(*r)->anchor->children;
1964 if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
1969 *rs = &f->child->ruleset;
1973 *rs = &(*r)->anchor->ruleset;
1975 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
1979 pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
1980 struct pf_rule **r, struct pf_rule **a, int *match)
1982 struct pf_anchor_stackframe *f;
1988 f = pf_anchor_stack + *depth - 1;
1989 if (f->parent != NULL && f->child != NULL) {
1990 if (f->child->match ||
1991 (match != NULL && *match)) {
1992 f->r->anchor->match = 1;
1995 f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
1996 if (f->child != NULL) {
1997 *rs = &f->child->ruleset;
1998 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2006 if (*depth == 0 && a != NULL)
2009 if (f->r->anchor->match || (match != NULL && *match))
2010 quick = f->r->quick;
2011 *r = TAILQ_NEXT(f->r, entries);
2012 } while (*r == NULL);
2019 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2020 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2025 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2026 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2030 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2031 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2032 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2033 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2034 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2035 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2036 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2037 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2043 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2048 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2052 if (addr->addr32[3] == 0xffffffff) {
2053 addr->addr32[3] = 0;
2054 if (addr->addr32[2] == 0xffffffff) {
2055 addr->addr32[2] = 0;
2056 if (addr->addr32[1] == 0xffffffff) {
2057 addr->addr32[1] = 0;
2059 htonl(ntohl(addr->addr32[0]) + 1);
2062 htonl(ntohl(addr->addr32[1]) + 1);
2065 htonl(ntohl(addr->addr32[2]) + 1);
2068 htonl(ntohl(addr->addr32[3]) + 1);
2074 #define mix(a,b,c) \
2076 a -= b; a -= c; a ^= (c >> 13); \
2077 b -= c; b -= a; b ^= (a << 8); \
2078 c -= a; c -= b; c ^= (b >> 13); \
2079 a -= b; a -= c; a ^= (c >> 12); \
2080 b -= c; b -= a; b ^= (a << 16); \
2081 c -= a; c -= b; c ^= (b >> 5); \
2082 a -= b; a -= c; a ^= (c >> 3); \
2083 b -= c; b -= a; b ^= (a << 10); \
2084 c -= a; c -= b; c ^= (b >> 15); \
2088 * hash function based on bridge_hash in if_bridge.c
2091 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2092 struct pf_poolhashkey *key, sa_family_t af)
2094 u_int32_t a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2099 a += inaddr->addr32[0];
2102 hash->addr32[0] = c + key->key32[2];
2107 a += inaddr->addr32[0];
2108 b += inaddr->addr32[2];
2110 hash->addr32[0] = c;
2111 a += inaddr->addr32[1];
2112 b += inaddr->addr32[3];
2115 hash->addr32[1] = c;
2116 a += inaddr->addr32[2];
2117 b += inaddr->addr32[1];
2120 hash->addr32[2] = c;
2121 a += inaddr->addr32[3];
2122 b += inaddr->addr32[0];
2125 hash->addr32[3] = c;
2132 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2133 struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2135 unsigned char hash[16];
2136 struct pf_pool *rpool = &r->rpool;
2137 struct pf_addr *raddr = &rpool->cur->addr.v.a.addr;
2138 struct pf_addr *rmask = &rpool->cur->addr.v.a.mask;
2139 struct pf_pooladdr *acur = rpool->cur;
2140 struct pf_src_node k;
2142 if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2143 (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2145 PF_ACPY(&k.addr, saddr, af);
2146 if (r->rule_flag & PFRULE_RULESRCTRACK ||
2147 r->rpool.opts & PF_POOL_STICKYADDR)
2151 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2152 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
2153 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2154 PF_ACPY(naddr, &(*sn)->raddr, af);
2155 if (pf_status.debug >= PF_DEBUG_MISC) {
2156 kprintf("pf_map_addr: src tracking maps ");
2157 pf_print_host(&k.addr, 0, af);
2159 pf_print_host(naddr, 0, af);
2166 if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
2168 if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2172 if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
2173 (rpool->opts & PF_POOL_TYPEMASK) !=
2176 raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
2177 rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
2182 if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
2183 (rpool->opts & PF_POOL_TYPEMASK) !=
2186 raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
2187 rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
2191 } else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2192 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2193 return (1); /* unsupported */
2195 raddr = &rpool->cur->addr.v.a.addr;
2196 rmask = &rpool->cur->addr.v.a.mask;
2199 switch (rpool->opts & PF_POOL_TYPEMASK) {
2201 PF_ACPY(naddr, raddr, af);
2203 case PF_POOL_BITMASK:
2204 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2206 case PF_POOL_RANDOM:
2207 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2211 rpool->counter.addr32[0] = htonl(karc4random());
2216 if (rmask->addr32[3] != 0xffffffff)
2217 rpool->counter.addr32[3] =
2218 htonl(karc4random());
2221 if (rmask->addr32[2] != 0xffffffff)
2222 rpool->counter.addr32[2] =
2223 htonl(karc4random());
2226 if (rmask->addr32[1] != 0xffffffff)
2227 rpool->counter.addr32[1] =
2228 htonl(karc4random());
2231 if (rmask->addr32[0] != 0xffffffff)
2232 rpool->counter.addr32[0] =
2233 htonl(karc4random());
2237 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2238 PF_ACPY(init_addr, naddr, af);
2241 PF_AINC(&rpool->counter, af);
2242 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2245 case PF_POOL_SRCHASH:
2246 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2247 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2249 case PF_POOL_ROUNDROBIN:
2250 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2251 if (!pfr_pool_get(rpool->cur->addr.p.tbl,
2252 &rpool->tblidx, &rpool->counter,
2253 &raddr, &rmask, af))
2255 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2256 if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2257 &rpool->tblidx, &rpool->counter,
2258 &raddr, &rmask, af))
2260 } else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
2264 if ((rpool->cur = TAILQ_NEXT(rpool->cur, entries)) == NULL)
2265 rpool->cur = TAILQ_FIRST(&rpool->list);
2266 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2268 if (pfr_pool_get(rpool->cur->addr.p.tbl,
2269 &rpool->tblidx, &rpool->counter,
2270 &raddr, &rmask, af)) {
2271 /* table contains no address of type 'af' */
2272 if (rpool->cur != acur)
2276 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2278 if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2279 &rpool->tblidx, &rpool->counter,
2280 &raddr, &rmask, af)) {
2281 /* table contains no address of type 'af' */
2282 if (rpool->cur != acur)
2287 raddr = &rpool->cur->addr.v.a.addr;
2288 rmask = &rpool->cur->addr.v.a.mask;
2289 PF_ACPY(&rpool->counter, raddr, af);
2293 PF_ACPY(naddr, &rpool->counter, af);
2294 if (init_addr != NULL && PF_AZERO(init_addr, af))
2295 PF_ACPY(init_addr, naddr, af);
2296 PF_AINC(&rpool->counter, af);
2300 PF_ACPY(&(*sn)->raddr, naddr, af);
2302 if (pf_status.debug >= PF_DEBUG_MISC &&
2303 (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2304 kprintf("pf_map_addr: selected address ");
2305 pf_print_host(naddr, 0, af);
2313 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
2314 struct pf_addr *saddr, struct pf_addr *daddr, u_int16_t dport,
2315 struct pf_addr *naddr, u_int16_t *nport, u_int16_t low, u_int16_t high,
2316 struct pf_src_node **sn)
2318 struct pf_state_key_cmp key;
2319 struct pf_addr init_addr;
2322 bzero(&init_addr, sizeof(init_addr));
2323 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2326 if (proto == IPPROTO_ICMP) {
2334 PF_ACPY(&key.ext.addr, daddr, key.af);
2335 PF_ACPY(&key.gwy.addr, naddr, key.af);
2336 key.ext.port = dport;
2339 * port search; start random, step;
2340 * similar 2 portloop in in_pcbbind
2342 if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
2343 proto == IPPROTO_ICMP)) {
2344 key.gwy.port = dport;
2345 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) == NULL)
2347 } else if (low == 0 && high == 0) {
2348 key.gwy.port = *nport;
2349 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) == NULL)
2351 } else if (low == high) {
2352 key.gwy.port = htons(low);
2353 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) == NULL) {
2354 *nport = htons(low);
2366 cut = htonl(karc4random()) % (1 + high - low) + low;
2367 /* low <= cut <= high */
2368 for (tmp = cut; tmp <= high; ++(tmp)) {
2369 key.gwy.port = htons(tmp);
2370 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) ==
2372 *nport = htons(tmp);
2376 for (tmp = cut - 1; tmp >= low; --(tmp)) {
2377 key.gwy.port = htons(tmp);
2378 if (pf_find_state_all(&key, PF_EXT_GWY, NULL) ==
2380 *nport = htons(tmp);
2386 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
2387 case PF_POOL_RANDOM:
2388 case PF_POOL_ROUNDROBIN:
2389 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2393 case PF_POOL_SRCHASH:
2394 case PF_POOL_BITMASK:
2398 } while (! PF_AEQ(&init_addr, naddr, af) );
2400 return (1); /* none available */
2404 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
2405 int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
2406 struct pf_addr *daddr, u_int16_t dport, int rs_num)
2408 struct pf_rule *r, *rm = NULL;
2409 struct pf_ruleset *ruleset = NULL;
2414 r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
2415 while (r && rm == NULL) {
2416 struct pf_rule_addr *src = NULL, *dst = NULL;
2417 struct pf_addr_wrap *xdst = NULL;
2419 if (r->action == PF_BINAT && direction == PF_IN) {
2421 if (r->rpool.cur != NULL)
2422 xdst = &r->rpool.cur->addr;
2429 if (pfi_kif_match(r->kif, kif) == r->ifnot)
2430 r = r->skip[PF_SKIP_IFP].ptr;
2431 else if (r->direction && r->direction != direction)
2432 r = r->skip[PF_SKIP_DIR].ptr;
2433 else if (r->af && r->af != pd->af)
2434 r = r->skip[PF_SKIP_AF].ptr;
2435 else if (r->proto && r->proto != pd->proto)
2436 r = r->skip[PF_SKIP_PROTO].ptr;
2437 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
2439 r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
2440 PF_SKIP_DST_ADDR].ptr;
2441 else if (src->port_op && !pf_match_port(src->port_op,
2442 src->port[0], src->port[1], sport))
2443 r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
2444 PF_SKIP_DST_PORT].ptr;
2445 else if (dst != NULL &&
2446 PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
2447 r = r->skip[PF_SKIP_DST_ADDR].ptr;
2448 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
2450 r = TAILQ_NEXT(r, entries);
2451 else if (dst != NULL && dst->port_op &&
2452 !pf_match_port(dst->port_op, dst->port[0],
2453 dst->port[1], dport))
2454 r = r->skip[PF_SKIP_DST_PORT].ptr;
2455 else if (r->match_tag && !pf_match_tag(m, r, &tag))
2456 r = TAILQ_NEXT(r, entries);
2457 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
2458 IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
2459 off, pd->hdr.tcp), r->os_fingerprint)))
2460 r = TAILQ_NEXT(r, entries);
2464 if (r->rtableid >= 0)
2465 rtableid = r->rtableid;
2466 if (r->anchor == NULL) {
2469 pf_step_into_anchor(&asd, &ruleset, rs_num,
2473 pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
2476 if (pf_tag_packet(m, tag, rtableid))
2478 if (rm != NULL && (rm->action == PF_NONAT ||
2479 rm->action == PF_NORDR || rm->action == PF_NOBINAT))
2485 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
2486 struct pfi_kif *kif, struct pf_src_node **sn,
2487 struct pf_addr *saddr, u_int16_t sport,
2488 struct pf_addr *daddr, u_int16_t dport,
2489 struct pf_addr *naddr, u_int16_t *nport)
2491 struct pf_rule *r = NULL;
2493 if (direction == PF_OUT) {
2494 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2495 sport, daddr, dport, PF_RULESET_BINAT);
2497 r = pf_match_translation(pd, m, off, direction, kif,
2498 saddr, sport, daddr, dport, PF_RULESET_NAT);
2500 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2501 sport, daddr, dport, PF_RULESET_RDR);
2503 r = pf_match_translation(pd, m, off, direction, kif,
2504 saddr, sport, daddr, dport, PF_RULESET_BINAT);
2508 switch (r->action) {
2514 if (pf_get_sport(pd->af, pd->proto, r, saddr,
2515 daddr, dport, naddr, nport, r->rpool.proxy_port[0],
2516 r->rpool.proxy_port[1], sn)) {
2517 DPFPRINTF(PF_DEBUG_MISC,
2518 ("pf: NAT proxy port allocation "
2520 r->rpool.proxy_port[0],
2521 r->rpool.proxy_port[1]));
2526 switch (direction) {
2528 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
2532 if (r->rpool.cur->addr.p.dyn->
2536 &r->rpool.cur->addr.p.dyn->
2538 &r->rpool.cur->addr.p.dyn->
2545 if (r->rpool.cur->addr.p.dyn->
2549 &r->rpool.cur->addr.p.dyn->
2551 &r->rpool.cur->addr.p.dyn->
2559 &r->rpool.cur->addr.v.a.addr,
2560 &r->rpool.cur->addr.v.a.mask,
2564 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
2568 if (r->src.addr.p.dyn->
2572 &r->src.addr.p.dyn->
2574 &r->src.addr.p.dyn->
2581 if (r->src.addr.p.dyn->
2585 &r->src.addr.p.dyn->
2587 &r->src.addr.p.dyn->
2595 &r->src.addr.v.a.addr,
2596 &r->src.addr.v.a.mask, daddr,
2602 if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
2604 if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
2606 PF_POOLMASK(naddr, naddr,
2607 &r->rpool.cur->addr.v.a.mask, daddr,
2610 if (r->rpool.proxy_port[1]) {
2611 u_int32_t tmp_nport;
2613 tmp_nport = ((ntohs(dport) -
2614 ntohs(r->dst.port[0])) %
2615 (r->rpool.proxy_port[1] -
2616 r->rpool.proxy_port[0] + 1)) +
2617 r->rpool.proxy_port[0];
2619 /* wrap around if necessary */
2620 if (tmp_nport > 65535)
2622 *nport = htons((u_int16_t)tmp_nport);
2623 } else if (r->rpool.proxy_port[0])
2624 *nport = htons(r->rpool.proxy_port[0]);
2636 struct netmsg_hashlookup {
2637 struct netmsg nm_netmsg;
2638 struct inpcb **nm_pinp;
2639 struct inpcbinfo *nm_pcbinfo;
2640 struct pf_addr *nm_saddr;
2641 struct pf_addr *nm_daddr;
2648 in_pcblookup_hash_handler(struct netmsg *msg0)
2650 struct netmsg_hashlookup *msg = (struct netmsg_hashlookup *)msg0;
2652 if (msg->nm_af == AF_INET)
2653 *msg->nm_pinp = in_pcblookup_hash(msg->nm_pcbinfo,
2654 msg->nm_saddr->v4, msg->nm_sport, msg->nm_daddr->v4,
2655 msg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2658 *msg->nm_pinp = in6_pcblookup_hash(msg->nm_pcbinfo,
2659 &msg->nm_saddr->v6, msg->nm_sport, &msg->nm_daddr->v6,
2660 msg->nm_dport, INPLOOKUP_WILDCARD, NULL);
2662 lwkt_replymsg(&msg->nm_netmsg.nm_lmsg, 0);
2667 pf_socket_lookup(int direction, struct pf_pdesc *pd)
2669 struct pf_addr *saddr, *daddr;
2670 u_int16_t sport, dport;
2671 struct inpcbinfo *pi;
2674 struct netmsg_hashlookup *msg = NULL;
2680 pd->lookup.uid = UID_MAX;
2681 pd->lookup.gid = GID_MAX;
2682 pd->lookup.pid = NO_PID;
2683 if (direction == PF_IN) {
2690 switch (pd->proto) {
2692 if (pd->hdr.tcp == NULL)
2694 sport = pd->hdr.tcp->th_sport;
2695 dport = pd->hdr.tcp->th_dport;
2697 pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
2698 pi = &tcbinfo[pi_cpu];
2701 * Our netstack runs lockless on MP systems
2702 * (only for TCP connections at the moment).
2704 * As we are not allowed to read another CPU's tcbinfo,
2705 * we have to ask that CPU via remote call to search the
2708 * Prepare a msg iff data belongs to another CPU.
2710 if (pi_cpu != mycpu->gd_cpuid) {
2711 msg = kmalloc(sizeof(*msg), M_LWKTMSG, M_INTWAIT);
2712 netmsg_init(&msg->nm_netmsg, NULL, &netisr_afree_rport,
2713 0, in_pcblookup_hash_handler);
2714 msg->nm_pinp = &inp;
2715 msg->nm_pcbinfo = pi;
2716 msg->nm_saddr = saddr;
2717 msg->nm_sport = sport;
2718 msg->nm_daddr = daddr;
2719 msg->nm_dport = dport;
2720 msg->nm_af = pd->af;
2725 if (pd->hdr.udp == NULL)
2727 sport = pd->hdr.udp->uh_sport;
2728 dport = pd->hdr.udp->uh_dport;
2734 if (direction != PF_IN) {
2746 * Query other CPU, second part
2748 * msg only gets initialized when:
2750 * 2) the info belongs to another CPU
2752 * Use some switch/case magic to avoid code duplication.
2757 inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
2758 &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
2764 /* FALLTHROUGH if SMP and on other CPU */
2769 lwkt_sendmsg(cpu_portfn(pi_cpu),
2770 &msg->nm_netmsg.nm_lmsg);
2774 inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
2775 dport, INPLOOKUP_WILDCARD, NULL);
2784 pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
2785 pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
2790 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2794 u_int8_t *opt, optlen;
2795 u_int8_t wscale = 0;
2797 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2798 if (hlen <= sizeof(struct tcphdr))
2800 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2802 opt = hdr + sizeof(struct tcphdr);
2803 hlen -= sizeof(struct tcphdr);
2813 if (wscale > TCP_MAX_WINSHIFT)
2814 wscale = TCP_MAX_WINSHIFT;
2815 wscale |= PF_WSCALE_FLAG;
2830 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2834 u_int8_t *opt, optlen;
2835 u_int16_t mss = tcp_mssdflt;
2837 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2838 if (hlen <= sizeof(struct tcphdr))
2840 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2842 opt = hdr + sizeof(struct tcphdr);
2843 hlen -= sizeof(struct tcphdr);
2844 while (hlen >= TCPOLEN_MAXSEG) {
2852 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
2867 pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
2870 struct sockaddr_in *dst;
2874 struct sockaddr_in6 *dst6;
2875 struct route_in6 ro6;
2877 struct rtentry *rt = NULL;
2879 u_int16_t mss = tcp_mssdflt;
2884 hlen = sizeof(struct ip);
2885 bzero(&ro, sizeof(ro));
2886 dst = (struct sockaddr_in *)&ro.ro_dst;
2887 dst->sin_family = AF_INET;
2888 dst->sin_len = sizeof(*dst);
2889 dst->sin_addr = addr->v4;
2890 rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
2896 hlen = sizeof(struct ip6_hdr);
2897 bzero(&ro6, sizeof(ro6));
2898 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
2899 dst6->sin6_family = AF_INET6;
2900 dst6->sin6_len = sizeof(*dst6);
2901 dst6->sin6_addr = addr->v6;
2902 rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
2908 if (rt && rt->rt_ifp) {
2909 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
2910 mss = max(tcp_mssdflt, mss);
2913 mss = min(mss, offer);
2914 mss = max(mss, 64); /* sanity - at least max opt space */
2919 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
2921 struct pf_rule *r = s->rule.ptr;
2924 if (!r->rt || r->rt == PF_FASTROUTE)
2926 switch (s->state_key->af) {
2929 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
2931 s->rt_kif = r->rpool.cur->kif;
2936 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
2938 s->rt_kif = r->rpool.cur->kif;
2945 pf_attach_state(struct pf_state_key *sk, struct pf_state *s, int tail)
2950 /* list is sorted, if-bound states before floating */
2952 TAILQ_INSERT_TAIL(&sk->states, s, next);
2954 TAILQ_INSERT_HEAD(&sk->states, s, next);
2958 pf_detach_state(struct pf_state *s, int flags)
2960 struct pf_state_key *sk = s->state_key;
2965 s->state_key = NULL;
2966 TAILQ_REMOVE(&sk->states, s, next);
2967 if (--sk->refcnt == 0) {
2968 if (!(flags & PF_DT_SKIP_EXTGWY))
2969 RB_REMOVE(pf_state_tree_ext_gwy,
2970 &pf_statetbl_ext_gwy, sk);
2971 if (!(flags & PF_DT_SKIP_LANEXT))
2972 RB_REMOVE(pf_state_tree_lan_ext,
2973 &pf_statetbl_lan_ext, sk);
2974 pool_put(&pf_state_key_pl, sk);
2978 struct pf_state_key *
2979 pf_alloc_state_key(struct pf_state *s)
2981 struct pf_state_key *sk;
2983 if ((sk = pool_get(&pf_state_key_pl, PR_NOWAIT)) == NULL)
2985 bzero(sk, sizeof(*sk));
2986 TAILQ_INIT(&sk->states);
2987 pf_attach_state(sk, s, 0);
2993 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
2994 struct pfi_kif *kif, struct mbuf *m, int off, void *h,
2995 struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
2996 struct ifqueue *ifq, struct inpcb *inp)
2998 struct pf_rule *nr = NULL;
2999 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
3000 u_int16_t bport, nport = 0;
3001 sa_family_t af = pd->af;
3002 struct pf_rule *r, *a = NULL;
3003 struct pf_ruleset *ruleset = NULL;
3004 struct pf_src_node *nsn = NULL;
3005 struct tcphdr *th = pd->hdr.tcp;
3007 int rewrite = 0, hdrlen = 0;
3008 int tag = -1, rtableid = -1;
3012 u_int16_t mss = tcp_mssdflt;
3013 u_int16_t sport, dport;
3014 u_int8_t icmptype = 0, icmpcode = 0;
3016 if (direction == PF_IN && pf_check_congestion(ifq)) {
3017 REASON_SET(&reason, PFRES_CONGEST);
3022 pd->lookup.done = pf_socket_lookup(direction, pd);
3023 else if (debug_pfugidhack) {
3025 DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
3026 pd->lookup.done = pf_socket_lookup(direction, pd);
3030 sport = dport = hdrlen = 0;
3032 switch (pd->proto) {
3034 sport = th->th_sport;
3035 dport = th->th_dport;
3036 hdrlen = sizeof(*th);
3039 sport = pd->hdr.udp->uh_sport;
3040 dport = pd->hdr.udp->uh_dport;
3041 hdrlen = sizeof(*pd->hdr.udp);
3045 if (pd->af != AF_INET)
3047 sport = dport = pd->hdr.icmp->icmp_id;
3048 icmptype = pd->hdr.icmp->icmp_type;
3049 icmpcode = pd->hdr.icmp->icmp_code;
3051 if (icmptype == ICMP_UNREACH ||
3052 icmptype == ICMP_SOURCEQUENCH ||
3053 icmptype == ICMP_REDIRECT ||
3054 icmptype == ICMP_TIMXCEED ||
3055 icmptype == ICMP_PARAMPROB)
3060 case IPPROTO_ICMPV6:
3061 if (pd->af != AF_INET6)
3063 sport = dport = pd->hdr.icmp6->icmp6_id;
3064 hdrlen = sizeof(*pd->hdr.icmp6);
3065 icmptype = pd->hdr.icmp6->icmp6_type;
3066 icmpcode = pd->hdr.icmp6->icmp6_code;
3068 if (icmptype == ICMP6_DST_UNREACH ||
3069 icmptype == ICMP6_PACKET_TOO_BIG ||
3070 icmptype == ICMP6_TIME_EXCEEDED ||
3071 icmptype == ICMP6_PARAM_PROB)
3077 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3079 if (direction == PF_OUT) {
3080 bport = nport = sport;
3081 /* check outgoing packet for BINAT/NAT */
3082 if ((nr = pf_get_translation(pd, m, off, PF_OUT, kif, &nsn,
3083 saddr, sport, daddr, dport, &pd->naddr, &nport)) != NULL) {
3084 PF_ACPY(&pd->baddr, saddr, af);
3085 switch (pd->proto) {
3087 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3088 &th->th_sum, &pd->naddr, nport, 0, af);
3089 sport = th->th_sport;
3093 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3094 pd->ip_sum, &pd->hdr.udp->uh_sum,
3095 &pd->naddr, nport, 1, af);
3096 sport = pd->hdr.udp->uh_sport;
3101 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3102 pd->naddr.v4.s_addr, 0);
3103 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3104 pd->hdr.icmp->icmp_cksum, sport, nport, 0);
3105 pd->hdr.icmp->icmp_id = nport;
3106 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3110 case IPPROTO_ICMPV6:
3111 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3120 pf_change_a(&saddr->v4.s_addr,
3121 pd->ip_sum, pd->naddr.v4.s_addr, 0);
3126 PF_ACPY(saddr, &pd->naddr, af);
3138 bport = nport = dport;
3139 /* check incoming packet for BINAT/RDR */
3140 if ((nr = pf_get_translation(pd, m, off, PF_IN, kif, &nsn,
3141 saddr, sport, daddr, dport, &pd->naddr, &nport)) != NULL) {
3142 PF_ACPY(&pd->baddr, daddr, af);
3143 switch (pd->proto) {
3145 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3146 &th->th_sum, &pd->naddr, nport, 0, af);
3147 dport = th->th_dport;
3151 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3152 pd->ip_sum, &pd->hdr.udp->uh_sum,
3153 &pd->naddr, nport, 1, af);
3154 dport = pd->hdr.udp->uh_dport;
3159 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3160 pd->naddr.v4.s_addr, 0);
3164 case IPPROTO_ICMPV6:
3165 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3174 pf_change_a(&daddr->v4.s_addr,
3175 pd->ip_sum, pd->naddr.v4.s_addr, 0);
3180 PF_ACPY(daddr, &pd->naddr, af);
3195 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3196 r = r->skip[PF_SKIP_IFP].ptr;
3197 else if (r->direction && r->direction != direction)
3198 r = r->skip[PF_SKIP_DIR].ptr;
3199 else if (r->af && r->af != af)
3200 r = r->skip[PF_SKIP_AF].ptr;
3201 else if (r->proto && r->proto != pd->proto)
3202 r = r->skip[PF_SKIP_PROTO].ptr;
3203 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3205 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3206 /* tcp/udp only. port_op always 0 in other cases */
3207 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3208 r->src.port[0], r->src.port[1], sport))
3209 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3210 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3212 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3213 /* tcp/udp only. port_op always 0 in other cases */
3214 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3215 r->dst.port[0], r->dst.port[1], dport))
3216 r = r->skip[PF_SKIP_DST_PORT].ptr;
3217 /* icmp only. type always 0 in other cases */
3218 else if (r->type && r->type != icmptype + 1)
3219 r = TAILQ_NEXT(r, entries);
3220 /* icmp only. type always 0 in other cases */
3221 else if (r->code && r->code != icmpcode + 1)
3222 r = TAILQ_NEXT(r, entries);
3223 else if (r->tos && !(r->tos == pd->tos))
3224 r = TAILQ_NEXT(r, entries);
3225 else if (r->rule_flag & PFRULE_FRAGMENT)
3226 r = TAILQ_NEXT(r, entries);
3227 else if (pd->proto == IPPROTO_TCP &&
3228 (r->flagset & th->th_flags) != r->flags)
3229 r = TAILQ_NEXT(r, entries);
3230 /* tcp/udp only. uid.op always 0 in other cases */
3231 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3232 pf_socket_lookup(direction, pd), 1)) &&
3233 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3235 r = TAILQ_NEXT(r, entries);
3236 /* tcp/udp only. gid.op always 0 in other cases */
3237 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3238 pf_socket_lookup(direction, pd), 1)) &&
3239 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3241 r = TAILQ_NEXT(r, entries);
3242 else if (r->prob && r->prob <= karc4random())
3243 r = TAILQ_NEXT(r, entries);
3244 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3245 r = TAILQ_NEXT(r, entries);
3246 else if (r->os_fingerprint != PF_OSFP_ANY &&
3247 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3248 pf_osfp_fingerprint(pd, m, off, th),
3249 r->os_fingerprint)))
3250 r = TAILQ_NEXT(r, entries);
3254 if (r->rtableid >= 0)
3255 rtableid = r->rtableid;
3256 if (r->anchor == NULL) {
3263 r = TAILQ_NEXT(r, entries);
3265 pf_step_into_anchor(&asd, &ruleset,
3266 PF_RULESET_FILTER, &r, &a, &match);
3268 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3269 PF_RULESET_FILTER, &r, &a, &match))
3276 REASON_SET(&reason, PFRES_MATCH);
3278 if (r->log || (nr != NULL && nr->log)) {
3280 m_copyback(m, off, hdrlen, pd->hdr.any);
3281 PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3285 if ((r->action == PF_DROP) &&
3286 ((r->rule_flag & PFRULE_RETURNRST) ||
3287 (r->rule_flag & PFRULE_RETURNICMP) ||
3288 (r->rule_flag & PFRULE_RETURN))) {
3289 /* undo NAT changes, if they have taken place */
3291 if (direction == PF_OUT) {
3292 switch (pd->proto) {
3294 pf_change_ap(saddr, &th->th_sport,
3295 pd->ip_sum, &th->th_sum,
3296 &pd->baddr, bport, 0, af);
3297 sport = th->th_sport;
3302 &pd->hdr.udp->uh_sport, pd->ip_sum,
3303 &pd->hdr.udp->uh_sum, &pd->baddr,
3305 sport = pd->hdr.udp->uh_sport;
3310 case IPPROTO_ICMPV6:
3317 pf_change_a(&saddr->v4.s_addr,
3319 pd->baddr.v4.s_addr, 0);
3322 PF_ACPY(saddr, &pd->baddr, af);
3327 switch (pd->proto) {
3329 pf_change_ap(daddr, &th->th_dport,
3330 pd->ip_sum, &th->th_sum,
3331 &pd->baddr, bport, 0, af);
3332 dport = th->th_dport;
3337 &pd->hdr.udp->uh_dport, pd->ip_sum,
3338 &pd->hdr.udp->uh_sum, &pd->baddr,
3340 dport = pd->hdr.udp->uh_dport;
3345 case IPPROTO_ICMPV6:
3352 pf_change_a(&daddr->v4.s_addr,
3354 pd->baddr.v4.s_addr, 0);
3357 PF_ACPY(daddr, &pd->baddr, af);
3363 if (pd->proto == IPPROTO_TCP &&
3364 ((r->rule_flag & PFRULE_RETURNRST) ||
3365 (r->rule_flag & PFRULE_RETURN)) &&
3366 !(th->th_flags & TH_RST)) {
3367 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
3368 struct ip *h = mtod(m, struct ip *);
3370 if (pf_check_proto_cksum(m, off,
3371 h->ip_len - off, IPPROTO_TCP, AF_INET))
3372 REASON_SET(&reason, PFRES_PROTCKSUM);
3374 if (th->th_flags & TH_SYN)
3376 if (th->th_flags & TH_FIN)
3378 lwkt_reltoken(&pf_token);
3379 pf_send_tcp(r, af, pd->dst,
3380 pd->src, th->th_dport, th->th_sport,
3381 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3382 r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
3383 lwkt_gettoken(&pf_token);
3385 } else if ((af == AF_INET) && r->return_icmp)
3386 pf_send_icmp(m, r->return_icmp >> 8,
3387 r->return_icmp & 255, af, r);
3388 else if ((af == AF_INET6) && r->return_icmp6)
3389 pf_send_icmp(m, r->return_icmp6 >> 8,
3390 r->return_icmp6 & 255, af, r);
3393 if (r->action == PF_DROP)
3396 if (pf_tag_packet(m, tag, rtableid)) {
3397 REASON_SET(&reason, PFRES_MEMORY);
3401 if (!state_icmp && (r->keep_state || nr != NULL ||
3402 (pd->flags & PFDESC_TCP_NORM))) {
3403 /* create new state */
3405 struct pf_state *s = NULL;
3406 struct pf_state_key *sk = NULL;
3407 struct pf_src_node *sn = NULL;
3409 /* check maximums */
3410 if (r->max_states && (r->states >= r->max_states)) {
3411 pf_status.lcounters[LCNT_STATES]++;
3412 REASON_SET(&reason, PFRES_MAXSTATES);
3415 /* src node for filter rule */
3416 if ((r->rule_flag & PFRULE_SRCTRACK ||
3417 r->rpool.opts & PF_POOL_STICKYADDR) &&
3418 pf_insert_src_node(&sn, r, saddr, af) != 0) {
3419 REASON_SET(&reason, PFRES_SRCLIMIT);
3422 /* src node for translation rule */
3423 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3424 ((direction == PF_OUT &&
3425 pf_insert_src_node(&nsn, nr, &pd->baddr, af) != 0) ||
3426 (pf_insert_src_node(&nsn, nr, saddr, af) != 0))) {
3427 REASON_SET(&reason, PFRES_SRCLIMIT);
3430 s = pool_get(&pf_state_pl, PR_NOWAIT);
3432 REASON_SET(&reason, PFRES_MEMORY);
3434 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3435 RB_REMOVE(pf_src_tree, &tree_src_tracking, sn);
3436 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3437 pf_status.src_nodes--;
3438 pool_put(&pf_src_tree_pl, sn);
3440 if (nsn != sn && nsn != NULL && nsn->states == 0 &&
3442 RB_REMOVE(pf_src_tree, &tree_src_tracking, nsn);
3443 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3444 pf_status.src_nodes--;
3445 pool_put(&pf_src_tree_pl, nsn);
3448 pool_put(&pf_state_key_pl, sk);
3452 bzero(s, sizeof(*s));
3454 s->nat_rule.ptr = nr;
3456 STATE_INC_COUNTERS(s);
3457 s->allow_opts = r->allow_opts;
3458 s->log = r->log & PF_LOG_ALL;
3460 s->log |= nr->log & PF_LOG_ALL;
3461 switch (pd->proto) {
3463 len = pd->tot_len - off - (th->th_off << 2);
3464 s->src.seqlo = ntohl(th->th_seq);
3465 s->src.seqhi = s->src.seqlo + len + 1;
3466 if ((th->th_flags & (TH_SYN|TH_ACK)) ==
3467 TH_SYN && r->keep_state == PF_STATE_MODULATE) {
3468 /* Generate sequence number modulator */
3469 while ((s->src.seqdiff =
3470 pf_new_isn(sk) - s->src.seqlo) == 0)
3472 pf_change_a(&th->th_seq, &th->th_sum,
3473 htonl(s->src.seqlo + s->src.seqdiff), 0);
3477 if (th->th_flags & TH_SYN) {
3479 s->src.wscale = pf_get_wscale(m, off,
3482 s->src.max_win = MAX(ntohs(th->th_win), 1);
3483 if (s->src.wscale & PF_WSCALE_MASK) {
3484 /* Remove scale factor from initial window */
3485 int win = s->src.max_win;
3486 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3487 s->src.max_win = (win - 1) >>
3488 (s->src.wscale & PF_WSCALE_MASK);
3490 if (th->th_flags & TH_FIN)
3494 s->src.state = TCPS_SYN_SENT;
3495 s->dst.state = TCPS_CLOSED;
3496 s->timeout = PFTM_TCP_FIRST_PACKET;
3499 s->src.state = PFUDPS_SINGLE;
3500 s->dst.state = PFUDPS_NO_TRAFFIC;
3501 s->timeout = PFTM_UDP_FIRST_PACKET;
3505 case IPPROTO_ICMPV6:
3507 s->timeout = PFTM_ICMP_FIRST_PACKET;
3510 s->src.state = PFOTHERS_SINGLE;
3511 s->dst.state = PFOTHERS_NO_TRAFFIC;
3512 s->timeout = PFTM_OTHER_FIRST_PACKET;
3515 s->creation = time_second;
3516 s->expire = time_second;
3520 s->src_node->states++;
3523 PF_ACPY(&nsn->raddr, &pd->naddr, af);
3524 s->nat_src_node = nsn;
3525 s->nat_src_node->states++;
3527 if (pd->proto == IPPROTO_TCP) {
3528 if ((pd->flags & PFDESC_TCP_NORM) &&
3529 pf_normalize_tcp_init(m, off, pd, th, &s->src,
3531 REASON_SET(&reason, PFRES_MEMORY);
3532 pf_src_tree_remove_state(s);
3533 STATE_DEC_COUNTERS(s);
3534 pool_put(&pf_state_pl, s);
3537 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3538 pf_normalize_tcp_stateful(m, off, pd, &reason,
3539 th, s, &s->src, &s->dst, &rewrite)) {
3540 /* This really shouldn't happen!!! */
3541 DPFPRINTF(PF_DEBUG_URGENT,
3542 ("pf_normalize_tcp_stateful failed on "
3544 pf_normalize_tcp_cleanup(s);
3545 pf_src_tree_remove_state(s);
3546 STATE_DEC_COUNTERS(s);
3547 pool_put(&pf_state_pl, s);
3552 if ((sk = pf_alloc_state_key(s)) == NULL) {
3553 REASON_SET(&reason, PFRES_MEMORY);
3557 sk->proto = pd->proto;
3558 sk->direction = direction;
3560 if (direction == PF_OUT) {
3561 PF_ACPY(&sk->gwy.addr, saddr, af);
3562 PF_ACPY(&sk->ext.addr, daddr, af);
3563 switch (pd->proto) {
3566 case IPPROTO_ICMPV6:
3568 sk->gwy.port = nport;
3572 sk->gwy.port = sport;
3573 sk->ext.port = dport;
3576 PF_ACPY(&sk->lan.addr, &pd->baddr, af);
3577 sk->lan.port = bport;
3579 PF_ACPY(&sk->lan.addr, &sk->gwy.addr, af);
3580 sk->lan.port = sk->gwy.port;
3583 PF_ACPY(&sk->lan.addr, daddr, af);
3584 PF_ACPY(&sk->ext.addr, saddr, af);
3585 switch (pd->proto) {
3588 case IPPROTO_ICMPV6:
3590 sk->lan.port = nport;
3594 sk->lan.port = dport;
3595 sk->ext.port = sport;
3598 PF_ACPY(&sk->gwy.addr, &pd->baddr, af);
3599 sk->gwy.port = bport;
3601 PF_ACPY(&sk->gwy.addr, &sk->lan.addr, af);
3602 sk->gwy.port = sk->lan.port;
3606 s->hash = pf_state_hash(sk);
3607 s->pickup_mode = r->pickup_mode;
3609 pf_set_rt_ifp(s, saddr); /* needs s->state_key set */
3611 if (pf_insert_state(BOUND_IFACE(r, kif), s)) {
3612 if (pd->proto == IPPROTO_TCP)
3613 pf_normalize_tcp_cleanup(s);
3614 REASON_SET(&reason, PFRES_STATEINS);
3615 pf_src_tree_remove_state(s);
3616 STATE_DEC_COUNTERS(s);
3617 pool_put(&pf_state_pl, s);
3625 if (pd->proto == IPPROTO_TCP &&
3626 (th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3627 r->keep_state == PF_STATE_SYNPROXY) {
3628 s->src.state = PF_TCPS_PROXY_SRC;
3630 if (direction == PF_OUT) {
3631 pf_change_ap(saddr, &th->th_sport,
3632 pd->ip_sum, &th->th_sum, &pd->baddr,
3634 sport = th->th_sport;
3636 pf_change_ap(daddr, &th->th_dport,
3637 pd->ip_sum, &th->th_sum, &pd->baddr,
3639 sport = th->th_dport;
3642 s->src.seqhi = htonl(karc4random());
3643 /* Find mss option */
3644 mss = pf_get_mss(m, off, th->th_off, af);
3645 mss = pf_calc_mss(saddr, af, mss);
3646 mss = pf_calc_mss(daddr, af, mss);
3648 lwkt_reltoken(&pf_token);
3649 pf_send_tcp(r, af, daddr, saddr, th->th_dport,
3650 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3651 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
3652 lwkt_gettoken(&pf_token);
3653 REASON_SET(&reason, PFRES_SYNPROXY);
3654 return (PF_SYNPROXY_DROP);
3658 /* copy back packet headers if we performed NAT operations */
3660 m_copyback(m, off, hdrlen, pd->hdr.any);
3666 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3667 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3668 struct pf_ruleset **rsm)
3670 struct pf_rule *r, *a = NULL;
3671 struct pf_ruleset *ruleset = NULL;
3672 sa_family_t af = pd->af;
3678 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3681 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3682 r = r->skip[PF_SKIP_IFP].ptr;
3683 else if (r->direction && r->direction != direction)
3684 r = r->skip[PF_SKIP_DIR].ptr;
3685 else if (r->af && r->af != af)
3686 r = r->skip[PF_SKIP_AF].ptr;
3687 else if (r->proto && r->proto != pd->proto)
3688 r = r->skip[PF_SKIP_PROTO].ptr;
3689 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3691 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3692 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3694 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3695 else if (r->tos && !(r->tos == pd->tos))
3696 r = TAILQ_NEXT(r, entries);
3697 else if (r->os_fingerprint != PF_OSFP_ANY)
3698 r = TAILQ_NEXT(r, entries);
3699 else if (pd->proto == IPPROTO_UDP &&
3700 (r->src.port_op || r->dst.port_op))
3701 r = TAILQ_NEXT(r, entries);
3702 else if (pd->proto == IPPROTO_TCP &&
3703 (r->src.port_op || r->dst.port_op || r->flagset))
3704 r = TAILQ_NEXT(r, entries);
3705 else if ((pd->proto == IPPROTO_ICMP ||
3706 pd->proto == IPPROTO_ICMPV6) &&
3707 (r->type || r->code))
3708 r = TAILQ_NEXT(r, entries);
3709 else if (r->prob && r->prob <= karc4random())
3710 r = TAILQ_NEXT(r, entries);
3711 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3712 r = TAILQ_NEXT(r, entries);
3714 if (r->anchor == NULL) {
3721 r = TAILQ_NEXT(r, entries);
3723 pf_step_into_anchor(&asd, &ruleset,
3724 PF_RULESET_FILTER, &r, &a, &match);
3726 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3727 PF_RULESET_FILTER, &r, &a, &match))
3734 REASON_SET(&reason, PFRES_MATCH);
3737 PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
3740 if (r->action != PF_PASS)
3743 if (pf_tag_packet(m, tag, -1)) {
3744 REASON_SET(&reason, PFRES_MEMORY);
3752 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
3753 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
3756 struct pf_state_key_cmp key;
3757 struct tcphdr *th = pd->hdr.tcp;
3758 u_int16_t win = ntohs(th->th_win);
3759 u_int32_t ack, end, seq, orig_seq;
3763 struct pf_state_peer *src, *dst;
3766 key.proto = IPPROTO_TCP;
3767 if (direction == PF_IN) {
3768 PF_ACPY(&key.ext.addr, pd->src, key.af);
3769 PF_ACPY(&key.gwy.addr, pd->dst, key.af);
3770 key.ext.port = th->th_sport;
3771 key.gwy.port = th->th_dport;
3773 PF_ACPY(&key.lan.addr, pd->src, key.af);
3774 PF_ACPY(&key.ext.addr, pd->dst, key.af);
3775 key.lan.port = th->th_sport;
3776 key.ext.port = th->th_dport;
3781 if (direction == (*state)->state_key->direction) {
3782 src = &(*state)->src;
3783 dst = &(*state)->dst;
3785 src = &(*state)->dst;
3786 dst = &(*state)->src;
3789 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
3790 if (direction != (*state)->state_key->direction) {
3791 REASON_SET(reason, PFRES_SYNPROXY);
3792 return (PF_SYNPROXY_DROP);
3794 if (th->th_flags & TH_SYN) {
3795 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
3796 REASON_SET(reason, PFRES_SYNPROXY);
3799 lwkt_reltoken(&pf_token);
3800 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
3801 pd->src, th->th_dport, th->th_sport,
3802 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
3803 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
3805 lwkt_gettoken(&pf_token);
3806 REASON_SET(reason, PFRES_SYNPROXY);
3807 return (PF_SYNPROXY_DROP);
3808 } else if (!(th->th_flags & TH_ACK) ||
3809 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
3810 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
3811 REASON_SET(reason, PFRES_SYNPROXY);
3813 } else if ((*state)->src_node != NULL &&
3814 pf_src_connlimit(state)) {
3815 REASON_SET(reason, PFRES_SRCLIMIT);
3818 (*state)->src.state = PF_TCPS_PROXY_DST;
3820 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
3821 struct pf_state_host *src, *dst;
3823 if (direction == PF_OUT) {
3824 src = &(*state)->state_key->gwy;
3825 dst = &(*state)->state_key->ext;
3827 src = &(*state)->state_key->ext;
3828 dst = &(*state)->state_key->lan;
3830 if (direction == (*state)->state_key->direction) {
3831 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
3832 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
3833 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
3834 REASON_SET(reason, PFRES_SYNPROXY);
3837 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
3838 if ((*state)->dst.seqhi == 1)
3839 (*state)->dst.seqhi = htonl(karc4random());
3840 lwkt_reltoken(&pf_token);
3841 pf_send_tcp((*state)->rule.ptr, pd->af, &src->addr,
3842 &dst->addr, src->port, dst->port,
3843 (*state)->dst.seqhi, 0, TH_SYN, 0,
3844 (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
3845 lwkt_gettoken(&pf_token);
3846 REASON_SET(reason, PFRES_SYNPROXY);
3847 return (PF_SYNPROXY_DROP);
3848 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
3850 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
3851 REASON_SET(reason, PFRES_SYNPROXY);
3854 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
3855 (*state)->dst.seqlo = ntohl(th->th_seq);
3856 lwkt_reltoken(&pf_token);
3857 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
3858 pd->src, th->th_dport, th->th_sport,
3859 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
3860 TH_ACK, (*state)->src.max_win, 0, 0, 0,
3861 (*state)->tag, NULL, NULL);
3862 pf_send_tcp((*state)->rule.ptr, pd->af, &src->addr,
3863 &dst->addr, src->port, dst->port,
3864 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
3865 TH_ACK, (*state)->dst.max_win, 0, 0, 1,
3867 lwkt_gettoken(&pf_token);
3868 (*state)->src.seqdiff = (*state)->dst.seqhi -
3869 (*state)->src.seqlo;
3870 (*state)->dst.seqdiff = (*state)->src.seqhi -
3871 (*state)->dst.seqlo;
3872 (*state)->src.seqhi = (*state)->src.seqlo +
3873 (*state)->dst.max_win;
3874 (*state)->dst.seqhi = (*state)->dst.seqlo +
3875 (*state)->src.max_win;
3876 (*state)->src.wscale = (*state)->dst.wscale = 0;
3877 (*state)->src.state = (*state)->dst.state =
3879 REASON_SET(reason, PFRES_SYNPROXY);
3880 return (PF_SYNPROXY_DROP);
3884 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3885 sws = src->wscale & PF_WSCALE_MASK;
3886 dws = dst->wscale & PF_WSCALE_MASK;
3891 * Sequence tracking algorithm from Guido van Rooij's paper:
3892 * http://www.madison-gurkha.com/publications/tcp_filtering/
3896 orig_seq = seq = ntohl(th->th_seq);
3897 if (src->seqlo == 0) {
3898 /* First packet from this end. Set its state */
3900 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
3901 src->scrub == NULL) {
3902 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
3903 REASON_SET(reason, PFRES_MEMORY);
3908 /* Deferred generation of sequence number modulator */
3909 if (dst->seqdiff && !src->seqdiff) {
3911 while ((src->seqdiff = pf_new_isn((struct pf_state_key *)&key) - seq) == 0)
3913 ack = ntohl(th->th_ack) - dst->seqdiff;
3914 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3916 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3919 ack = ntohl(th->th_ack);
3922 end = seq + pd->p_len;
3923 if (th->th_flags & TH_SYN) {
3925 (*state)->sync_flags |= PFSTATE_GOT_SYN2;
3926 if (dst->wscale & PF_WSCALE_FLAG) {
3927 src->wscale = pf_get_wscale(m, off, th->th_off,
3929 if (src->wscale & PF_WSCALE_FLAG) {
3930 /* Remove scale factor from initial
3932 sws = src->wscale & PF_WSCALE_MASK;
3933 win = ((u_int32_t)win + (1 << sws) - 1)
3935 dws = dst->wscale & PF_WSCALE_MASK;
3937 /* fixup other window */
3938 dst->max_win <<= dst->wscale &
3940 /* in case of a retrans SYN|ACK */
3945 if (th->th_flags & TH_FIN)
3949 if (src->state < TCPS_SYN_SENT)
3950 src->state = TCPS_SYN_SENT;
3953 * May need to slide the window (seqhi may have been set by
3954 * the crappy stack check or if we picked up the connection
3955 * after establishment)
3957 if (src->seqhi == 1 ||
3958 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
3959 src->seqhi = end + MAX(1, dst->max_win << dws);
3960 if (win > src->max_win)
3964 ack = ntohl(th->th_ack) - dst->seqdiff;
3966 /* Modulate sequence numbers */
3967 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
3969 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
3972 end = seq + pd->p_len;
3973 if (th->th_flags & TH_SYN)
3975 if (th->th_flags & TH_FIN)
3979 if ((th->th_flags & TH_ACK) == 0) {
3980 /* Let it pass through the ack skew check */
3982 } else if ((ack == 0 &&
3983 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
3984 /* broken tcp stacks do not set ack */
3985 (dst->state < TCPS_SYN_SENT)) {
3987 * Many stacks (ours included) will set the ACK number in an
3988 * FIN|ACK if the SYN times out -- no sequence to ACK.
3994 /* Ease sequencing restrictions on no data packets */
3999 ackskew = dst->seqlo - ack;
4003 * Need to demodulate the sequence numbers in any TCP SACK options
4004 * (Selective ACK). We could optionally validate the SACK values
4005 * against the current ACK window, either forwards or backwards, but
4006 * I'm not confident that SACK has been implemented properly
4007 * everywhere. It wouldn't surprise me if several stacks accidently
4008 * SACK too far backwards of previously ACKed data. There really aren't
4009 * any security implications of bad SACKing unless the target stack
4010 * doesn't validate the option length correctly. Someone trying to
4011 * spoof into a TCP connection won't bother blindly sending SACK
4014 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4015 if (pf_modulate_sack(m, off, pd, th, dst))
4020 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4021 if (SEQ_GEQ(src->seqhi, end) &&
4022 /* Last octet inside other's window space */
4023 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4024 /* Retrans: not more than one window back */
4025 (ackskew >= -MAXACKWINDOW) &&
4026 /* Acking not more than one reassembled fragment backwards */
4027 (ackskew <= (MAXACKWINDOW << sws)) &&
4028 /* Acking not more than one window forward */
4029 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4030 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4031 (pd->flags & PFDESC_IP_REAS) == 0)) {
4032 /* Require an exact/+1 sequence match on resets when possible */
4034 if (dst->scrub || src->scrub) {
4035 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4036 *state, src, dst, ©back))
4040 /* update max window */
4041 if (src->max_win < win)
4043 /* synchronize sequencing */
4044 if (SEQ_GT(end, src->seqlo))
4046 /* slide the window of what the other end can send */
4047 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4048 dst->seqhi = ack + MAX((win << sws), 1);
4052 if (th->th_flags & TH_SYN)
4053 if (src->state < TCPS_SYN_SENT)
4054 src->state = TCPS_SYN_SENT;
4055 if (th->th_flags & TH_FIN)
4056 if (src->state < TCPS_CLOSING)
4057 src->state = TCPS_CLOSING;
4058 if (th->th_flags & TH_ACK) {
4059 if (dst->state == TCPS_SYN_SENT) {
4060 dst->state = TCPS_ESTABLISHED;
4061 if (src->state == TCPS_ESTABLISHED &&
4062 (*state)->src_node != NULL &&
4063 pf_src_connlimit(state)) {
4064 REASON_SET(reason, PFRES_SRCLIMIT);
4067 } else if (dst->state == TCPS_CLOSING)
4068 dst->state = TCPS_FIN_WAIT_2;
4070 if (th->th_flags & TH_RST)
4071 src->state = dst->state = TCPS_TIME_WAIT;
4073 /* update expire time */
4074 (*state)->expire = time_second;
4075 if (src->state >= TCPS_FIN_WAIT_2 &&
4076 dst->state >= TCPS_FIN_WAIT_2)
4077 (*state)->timeout = PFTM_TCP_CLOSED;
4078 else if (src->state >= TCPS_CLOSING &&
4079 dst->state >= TCPS_CLOSING)
4080 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4081 else if (src->state < TCPS_ESTABLISHED ||
4082 dst->state < TCPS_ESTABLISHED)
4083 (*state)->timeout = PFTM_TCP_OPENING;
4084 else if (src->state >= TCPS_CLOSING ||
4085 dst->state >= TCPS_CLOSING)
4086 (*state)->timeout = PFTM_TCP_CLOSING;
4088 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4090 /* Fall through to PASS packet */
4092 } else if ((dst->state < TCPS_SYN_SENT ||
4093 dst->state >= TCPS_FIN_WAIT_2 ||
4094 src->state >= TCPS_FIN_WAIT_2) &&
4095 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4096 /* Within a window forward of the originating packet */
4097 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4098 /* Within a window backward of the originating packet */
4101 * This currently handles three situations:
4102 * 1) Stupid stacks will shotgun SYNs before their peer
4104 * 2) When PF catches an already established stream (the
4105 * firewall rebooted, the state table was flushed, routes
4107 * 3) Packets get funky immediately after the connection
4108 * closes (this should catch Solaris spurious ACK|FINs
4109 * that web servers like to spew after a close)
4111 * This must be a little more careful than the above code
4112 * since packet floods will also be caught here. We don't
4113 * update the TTL here to mitigate the damage of a packet
4114 * flood and so the same code can handle awkward establishment
4115 * and a loosened connection close.
4116 * In the establishment case, a correct peer response will
4117 * validate the connection, go through the normal state code
4118 * and keep updating the state TTL.
4121 if (pf_status.debug >= PF_DEBUG_MISC) {
4122 kprintf("pf: loose state match: ");
4123 pf_print_state(*state);
4124 pf_print_flags(th->th_flags);
4125 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4126 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack, pd->p_len,
4127 ackskew, (unsigned long long)(*state)->packets[0],
4128 (unsigned long long)(*state)->packets[1],
4129 direction == PF_IN ? "in" : "out",
4130 direction == (*state)->state_key->direction ?
4134 if (dst->scrub || src->scrub) {
4135 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4136 *state, src, dst, ©back))
4140 /* update max window */
4141 if (src->max_win < win)
4143 /* synchronize sequencing */
4144 if (SEQ_GT(end, src->seqlo))
4146 /* slide the window of what the other end can send */
4147 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4148 dst->seqhi = ack + MAX((win << sws), 1);
4151 * Cannot set dst->seqhi here since this could be a shotgunned
4152 * SYN and not an already established connection.
4155 if (th->th_flags & TH_FIN)
4156 if (src->state < TCPS_CLOSING)
4157 src->state = TCPS_CLOSING;
4158 if (th->th_flags & TH_RST)
4159 src->state = dst->state = TCPS_TIME_WAIT;
4161 /* Fall through to PASS packet */
4163 } else if ((*state)->pickup_mode == PF_PICKUPS_HASHONLY ||
4164 ((*state)->pickup_mode == PF_PICKUPS_ENABLED &&
4165 ((*state)->sync_flags & PFSTATE_GOT_SYN_MASK) !=
4166 PFSTATE_GOT_SYN_MASK)) {
4168 * If pickup mode is hash only, do not fail on sequence checks.
4170 * If pickup mode is enabled and we did not see the SYN in
4171 * both direction, do not fail on sequence checks because
4172 * we do not have complete information on window scale.
4174 * Adjust expiration and fall through to PASS packet.
4175 * XXX Add a FIN check to reduce timeout?
4177 (*state)->expire = time_second;
4180 * Failure processing
4182 if ((*state)->dst.state == TCPS_SYN_SENT &&
4183 (*state)->src.state == TCPS_SYN_SENT) {
4184 /* Send RST for state mismatches during handshake */
4185 if (!(th->th_flags & TH_RST))
4186 lwkt_reltoken(&pf_token);
4187 pf_send_tcp((*state)->rule.ptr, pd->af,
4188 pd->dst, pd->src, th->th_dport,
4189 th->th_sport, ntohl(th->th_ack), 0,
4191 (*state)->rule.ptr->return_ttl, 1, 0,
4192 pd->eh, kif->pfik_ifp);
4193 lwkt_gettoken(&pf_token);
4197 } else if (pf_status.debug >= PF_DEBUG_MISC) {
4198 kprintf("pf: BAD state: ");
4199 pf_print_state(*state);
4200 pf_print_flags(th->th_flags);
4201 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4202 "pkts=%llu:%llu dir=%s,%s\n",
4203 seq, orig_seq, ack, pd->p_len, ackskew,
4204 (unsigned long long)(*state)->packets[0],
4205 (unsigned long long)(*state)->packets[1],
4206 direction == PF_IN ? "in" : "out",
4207 direction == (*state)->state_key->direction ?
4209 kprintf("pf: State failure on: %c %c %c %c | %c %c\n",
4210 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4211 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4213 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4214 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4215 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4216 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4218 REASON_SET(reason, PFRES_BADSTATE);
4222 /* Any packets which have gotten here are to be passed */
4224 /* translate source/destination address, if necessary */
4225 if (STATE_TRANSLATE((*state)->state_key)) {
4226 if (direction == PF_OUT) {
4227 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
4228 &th->th_sum, &(*state)->state_key->gwy.addr,
4229 (*state)->state_key->gwy.port, 0, pd->af);
4232 * If we don't redispatch the packet will go into
4233 * the protocol stack on the wrong cpu for the
4234 * post-translated address.
4236 /* m->m_pkthdr.fw_flags |= FW_MBUF_REDISPATCH; */
4237 m->m_flags &= ~M_HASH;
4238 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
4239 &th->th_sum, &(*state)->state_key->lan.addr,
4240 (*state)->state_key->lan.port, 0, pd->af);
4242 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4243 } else if (copyback) {
4244 /* Copyback sequence modulation or stateful scrub changes */
4245 m_copyback(m, off, sizeof(*th), (caddr_t)th);
4252 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
4253 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
4255 struct pf_state_peer *src, *dst;
4256 struct pf_state_key_cmp key;
4257 struct udphdr *uh = pd->hdr.udp;
4260 key.proto = IPPROTO_UDP;
4261 if (direction == PF_IN) {
4262 PF_ACPY(&key.ext.addr, pd->src, key.af);
4263 PF_ACPY(&key.gwy.addr, pd->dst, key.af);
4264 key.ext.port = uh->uh_sport;
4265 key.gwy.port = uh->uh_dport;
4267 PF_ACPY(&key.lan.addr, pd->src, key.af);
4268 PF_ACPY(&key.ext.addr, pd->dst, key.af);
4269 key.lan.port = uh->uh_sport;
4270 key.ext.port = uh->uh_dport;
4275 if (direction == (*state)->state_key->direction) {
4276 src = &(*state)->src;
4277 dst = &(*state)->dst;
4279 src = &(*state)->dst;
4280 dst = &(*state)->src;
4284 if (src->state < PFUDPS_SINGLE)
4285 src->state = PFUDPS_SINGLE;
4286 if (dst->state == PFUDPS_SINGLE)
4287 dst->state = PFUDPS_MULTIPLE;
4289 /* update expire time */
4290 (*state)->expire = time_second;
4291 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
4292 (*state)->timeout = PFTM_UDP_MULTIPLE;
4294 (*state)->timeout = PFTM_UDP_SINGLE;
4296 /* translate source/destination address, if necessary */
4297 if (STATE_TRANSLATE((*state)->state_key)) {
4298 if (direction == PF_OUT) {
4299 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
4300 &uh->uh_sum, &(*state)->state_key->gwy.addr,
4301 (*state)->state_key->gwy.port, 1, pd->af);
4304 * If we don't redispatch the packet will go into
4305 * the protocol stack on the wrong cpu for the
4306 * post-translated address.
4308 /* m->m_pkthdr.fw_flags |= FW_MBUF_REDISPATCH; */
4309 m->m_flags &= ~M_HASH;
4310 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
4311 &uh->uh_sum, &(*state)->state_key->lan.addr,
4312 (*state)->state_key->lan.port, 1, pd->af);
4314 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
4321 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
4322 struct mbuf *m, int off, void *h, struct pf_pdesc *pd, u_short *reason)
4324 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
4325 u_int16_t icmpid = 0, *icmpsum;
4328 struct pf_state_key_cmp key;
4330 switch (pd->proto) {
4333 icmptype = pd->hdr.icmp->icmp_type;
4334 icmpid = pd->hdr.icmp->icmp_id;
4335 icmpsum = &pd->hdr.icmp->icmp_cksum;
4337 if (icmptype == ICMP_UNREACH ||
4338 icmptype == ICMP_SOURCEQUENCH ||
4339 icmptype == ICMP_REDIRECT ||
4340 icmptype == ICMP_TIMXCEED ||
4341 icmptype == ICMP_PARAMPROB)
4346 case IPPROTO_ICMPV6:
4347 icmptype = pd->hdr.icmp6->icmp6_type;
4348 icmpid = pd->hdr.icmp6->icmp6_id;
4349 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
4351 if (icmptype == ICMP6_DST_UNREACH ||
4352 icmptype == ICMP6_PACKET_TOO_BIG ||
4353 icmptype == ICMP6_TIME_EXCEEDED ||
4354 icmptype == ICMP6_PARAM_PROB)
4363 * ICMP query/reply message not related to a TCP/UDP packet.
4364 * Search for an ICMP state.
4367 key.proto = pd->proto;
4368 if (direction == PF_IN) {
4369 PF_ACPY(&key.ext.addr, pd->src, key.af);
4370 PF_ACPY(&key.gwy.addr, pd->dst, key.af);
4372 key.gwy.port = icmpid;
4374 PF_ACPY(&key.lan.addr, pd->src, key.af);
4375 PF_ACPY(&key.ext.addr, pd->dst, key.af);
4376 key.lan.port = icmpid;
4382 (*state)->expire = time_second;
4383 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
4385 /* translate source/destination address, if necessary */
4386 if (STATE_TRANSLATE((*state)->state_key)) {
4387 if (direction == PF_OUT) {
4391 pf_change_a(&saddr->v4.s_addr,
4393 (*state)->state_key->gwy.addr.v4.s_addr, 0);
4394 pd->hdr.icmp->icmp_cksum =
4396 pd->hdr.icmp->icmp_cksum, icmpid,
4397 (*state)->state_key->gwy.port, 0);
4398 pd->hdr.icmp->icmp_id =
4399 (*state)->state_key->gwy.port;
4400 m_copyback(m, off, ICMP_MINLEN,
4401 (caddr_t)pd->hdr.icmp);
4407 &pd->hdr.icmp6->icmp6_cksum,
4408 &(*state)->state_key->gwy.addr, 0);
4410 sizeof(struct icmp6_hdr),
4411 (caddr_t)pd->hdr.icmp6);
4419 pf_change_a(&daddr->v4.s_addr,
4421 (*state)->state_key->lan.addr.v4.s_addr, 0);
4422 pd->hdr.icmp->icmp_cksum =
4424 pd->hdr.icmp->icmp_cksum, icmpid,
4425 (*state)->state_key->lan.port, 0);
4426 pd->hdr.icmp->icmp_id =
4427 (*state)->state_key->lan.port;
4428 m_copyback(m, off, ICMP_MINLEN,
4429 (caddr_t)pd->hdr.icmp);
4435 &pd->hdr.icmp6->icmp6_cksum,
4436 &(*state)->state_key->lan.addr, 0);
4438 sizeof(struct icmp6_hdr),
4439 (caddr_t)pd->hdr.icmp6);
4450 * ICMP error message in response to a TCP/UDP packet.
4451 * Extract the inner TCP/UDP header and search for that state.
4454 struct pf_pdesc pd2;
4459 struct ip6_hdr h2_6;
4469 /* offset of h2 in mbuf chain */
4470 ipoff2 = off + ICMP_MINLEN;
4472 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
4473 NULL, reason, pd2.af)) {
4474 DPFPRINTF(PF_DEBUG_MISC,
4475 ("pf: ICMP error message too short "
4480 * ICMP error messages don't refer to non-first
4483 if (h2.ip_off & htons(IP_OFFMASK)) {
4484 REASON_SET(reason, PFRES_FRAG);
4488 /* offset of protocol header that follows h2 */
4489 off2 = ipoff2 + (h2.ip_hl << 2);
4491 pd2.proto = h2.ip_p;
4492 pd2.src = (struct pf_addr *)&h2.ip_src;
4493 pd2.dst = (struct pf_addr *)&h2.ip_dst;
4494 pd2.ip_sum = &h2.ip_sum;
4499 ipoff2 = off + sizeof(struct icmp6_hdr);
4501 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
4502 NULL, reason, pd2.af)) {
4503 DPFPRINTF(PF_DEBUG_MISC,
4504 ("pf: ICMP error message too short "
4508 pd2.proto = h2_6.ip6_nxt;
4509 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
4510 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
4512 off2 = ipoff2 + sizeof(h2_6);
4514 switch (pd2.proto) {
4515 case IPPROTO_FRAGMENT:
4517 * ICMPv6 error messages for
4518 * non-first fragments
4520 REASON_SET(reason, PFRES_FRAG);
4523 case IPPROTO_HOPOPTS:
4524 case IPPROTO_ROUTING:
4525 case IPPROTO_DSTOPTS: {
4526 /* get next header and header length */
4527 struct ip6_ext opt6;
4529 if (!pf_pull_hdr(m, off2, &opt6,
4530 sizeof(opt6), NULL, reason,
4532 DPFPRINTF(PF_DEBUG_MISC,
4533 ("pf: ICMPv6 short opt\n"));
4536 if (pd2.proto == IPPROTO_AH)
4537 off2 += (opt6.ip6e_len + 2) * 4;
4539 off2 += (opt6.ip6e_len + 1) * 8;
4540 pd2.proto = opt6.ip6e_nxt;
4541 /* goto the next header */
4548 } while (!terminal);
4552 DPFPRINTF(PF_DEBUG_MISC,
4553 ("pf: ICMP AF %d unknown (ip6)\n", pd->af));
4558 switch (pd2.proto) {
4562 struct pf_state_peer *src, *dst;
4567 * Only the first 8 bytes of the TCP header can be
4568 * expected. Don't access any TCP header fields after
4569 * th_seq, an ackskew test is not possible.
4571 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
4573 DPFPRINTF(PF_DEBUG_MISC,
4574 ("pf: ICMP error message too short "
4580 key.proto = IPPROTO_TCP;
4581 if (direction == PF_IN) {
4582 PF_ACPY(&key.ext.addr, pd2.dst, key.af);
4583 PF_ACPY(&key.gwy.addr, pd2.src, key.af);
4584 key.ext.port = th.th_dport;
4585 key.gwy.port = th.th_sport;
4587 PF_ACPY(&key.lan.addr, pd2.dst, key.af);
4588 PF_ACPY(&key.ext.addr, pd2.src, key.af);
4589 key.lan.port = th.th_dport;
4590 key.ext.port = th.th_sport;
4595 if (direction == (*state)->state_key->direction) {
4596 src = &(*state)->dst;
4597 dst = &(*state)->src;
4599 src = &(*state)->src;
4600 dst = &(*state)->dst;
4603 if (src->wscale && dst->wscale)
4604 dws = dst->wscale & PF_WSCALE_MASK;
4608 /* Demodulate sequence number */
4609 seq = ntohl(th.th_seq) - src->seqdiff;
4611 pf_change_a(&th.th_seq, icmpsum,
4616 if (!SEQ_GEQ(src->seqhi, seq) ||
4617 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws))) {
4618 if (pf_status.debug >= PF_DEBUG_MISC) {
4619 kprintf("pf: BAD ICMP %d:%d ",
4620 icmptype, pd->hdr.icmp->icmp_code);
4621 pf_print_host(pd->src, 0, pd->af);
4623 pf_print_host(pd->dst, 0, pd->af);
4624 kprintf(" state: ");
4625 pf_print_state(*state);
4626 kprintf(" seq=%u\n", seq);
4628 REASON_SET(reason, PFRES_BADSTATE);
4632 if (STATE_TRANSLATE((*state)->state_key)) {
4633 if (direction == PF_IN) {
4634 pf_change_icmp(pd2.src, &th.th_sport,
4635 daddr, &(*state)->state_key->lan.addr,
4636 (*state)->state_key->lan.port, NULL,
4637 pd2.ip_sum, icmpsum,
4638 pd->ip_sum, 0, pd2.af);
4640 pf_change_icmp(pd2.dst, &th.th_dport,
4641 saddr, &(*state)->state_key->gwy.addr,
4642 (*state)->state_key->gwy.port, NULL,
4643 pd2.ip_sum, icmpsum,
4644 pd->ip_sum, 0, pd2.af);
4653 m_copyback(m, off, ICMP_MINLEN,
4654 (caddr_t)pd->hdr.icmp);
4655 m_copyback(m, ipoff2, sizeof(h2),
4662 sizeof(struct icmp6_hdr),
4663 (caddr_t)pd->hdr.icmp6);
4664 m_copyback(m, ipoff2, sizeof(h2_6),
4669 m_copyback(m, off2, 8, (caddr_t)&th);
4678 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
4679 NULL, reason, pd2.af)) {
4680 DPFPRINTF(PF_DEBUG_MISC,
4681 ("pf: ICMP error message too short "
4687 key.proto = IPPROTO_UDP;
4688 if (direction == PF_IN) {
4689 PF_ACPY(&key.ext.addr, pd2.dst, key.af);
4690 PF_ACPY(&key.gwy.addr, pd2.src, key.af);
4691 key.ext.port = uh.uh_dport;
4692 key.gwy.port = uh.uh_sport;
4694 PF_ACPY(&key.lan.addr, pd2.dst, key.af);
4695 PF_ACPY(&key.ext.addr, pd2.src, key.af);
4696 key.lan.port = uh.uh_dport;
4697 key.ext.port = uh.uh_sport;
4702 if (STATE_TRANSLATE((*state)->state_key)) {
4703 if (direction == PF_IN) {
4704 pf_change_icmp(pd2.src, &uh.uh_sport,
4706 &(*state)->state_key->lan.addr,
4707 (*state)->state_key->lan.port,
4709 pd2.ip_sum, icmpsum,
4710 pd->ip_sum, 1, pd2.af);
4712 pf_change_icmp(pd2.dst, &uh.uh_dport,
4714 &(*state)->state_key->gwy.addr,
4715 (*state)->state_key->gwy.port, &uh.uh_sum,
4716 pd2.ip_sum, icmpsum,
4717 pd->ip_sum, 1, pd2.af);
4722 m_copyback(m, off, ICMP_MINLEN,
4723 (caddr_t)pd->hdr.icmp);
4724 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4730 sizeof(struct icmp6_hdr),
4731 (caddr_t)pd->hdr.icmp6);
4732 m_copyback(m, ipoff2, sizeof(h2_6),
4737 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
4744 case IPPROTO_ICMP: {
4747 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
4748 NULL, reason, pd2.af)) {
4749 DPFPRINTF(PF_DEBUG_MISC,
4750 ("pf: ICMP error message too short i"
4756 key.proto = IPPROTO_ICMP;
4757 if (direction == PF_IN) {
4758 PF_ACPY(&key.ext.addr, pd2.dst, key.af);
4759 PF_ACPY(&key.gwy.addr, pd2.src, key.af);
4761 key.gwy.port = iih.icmp_id;
4763 PF_ACPY(&key.lan.addr, pd2.dst, key.af);
4764 PF_ACPY(&key.ext.addr, pd2.src, key.af);
4765 key.lan.port = iih.icmp_id;
4771 if (STATE_TRANSLATE((*state)->state_key)) {
4772 if (direction == PF_IN) {
4773 pf_change_icmp(pd2.src, &iih.icmp_id,
4775 &(*state)->state_key->lan.addr,
4776 (*state)->state_key->lan.port, NULL,
4777 pd2.ip_sum, icmpsum,
4778 pd->ip_sum, 0, AF_INET);
4780 pf_change_icmp(pd2.dst, &iih.icmp_id,
4782 &(*state)->state_key->gwy.addr,
4783 (*state)->state_key->gwy.port, NULL,
4784 pd2.ip_sum, icmpsum,
4785 pd->ip_sum, 0, AF_INET);
4787 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
4788 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4789 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
4797 case IPPROTO_ICMPV6: {
4798 struct icmp6_hdr iih;
4800 if (!pf_pull_hdr(m, off2, &iih,
4801 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
4802 DPFPRINTF(PF_DEBUG_MISC,
4803 ("pf: ICMP error message too short "
4809 key.proto = IPPROTO_ICMPV6;
4810 if (direction == PF_IN) {
4811 PF_ACPY(&key.ext.addr, pd2.dst, key.af);
4812 PF_ACPY(&key.gwy.addr, pd2.src, key.af);
4814 key.gwy.port = iih.icmp6_id;
4816 PF_ACPY(&key.lan.addr, pd2.dst, key.af);
4817 PF_ACPY(&key.ext.addr, pd2.src, key.af);
4818 key.lan.port = iih.icmp6_id;
4824 if (STATE_TRANSLATE((*state)->state_key)) {
4825 if (direction == PF_IN) {
4826 pf_change_icmp(pd2.src, &iih.icmp6_id,
4828 &(*state)->state_key->lan.addr,
4829 (*state)->state_key->lan.port, NULL,
4830 pd2.ip_sum, icmpsum,
4831 pd->ip_sum, 0, AF_INET6);
4833 pf_change_icmp(pd2.dst, &iih.icmp6_id,
4834 saddr, &(*state)->state_key->gwy.addr,
4835 (*state)->state_key->gwy.port, NULL,
4836 pd2.ip_sum, icmpsum,
4837 pd->ip_sum, 0, AF_INET6);
4839 m_copyback(m, off, sizeof(struct icmp6_hdr),
4840 (caddr_t)pd->hdr.icmp6);
4841 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
4842 m_copyback(m, off2, sizeof(struct icmp6_hdr),
4852 key.proto = pd2.proto;
4853 if (direction == PF_IN) {
4854 PF_ACPY(&key.ext.addr, pd2.dst, key.af);
4855 PF_ACPY(&key.gwy.addr, pd2.src, key.af);
4859 PF_ACPY(&key.lan.addr, pd2.dst, key.af);
4860 PF_ACPY(&key.ext.addr, pd2.src, key.af);
4867 if (STATE_TRANSLATE((*state)->state_key)) {
4868 if (direction == PF_IN) {
4869 pf_change_icmp(pd2.src, NULL,
4871 &(*state)->state_key->lan.addr,
4873 pd2.ip_sum, icmpsum,
4874 pd->ip_sum, 0, pd2.af);
4876 pf_change_icmp(pd2.dst, NULL,
4878 &(*state)->state_key->gwy.addr,
4880 pd2.ip_sum, icmpsum,
4881 pd->ip_sum, 0, pd2.af);
4886 m_copyback(m, off, ICMP_MINLEN,
4887 (caddr_t)pd->hdr.icmp);
4888 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
4894 sizeof(struct icmp6_hdr),
4895 (caddr_t)pd->hdr.icmp6);
4896 m_copyback(m, ipoff2, sizeof(h2_6),
4911 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
4912 struct pf_pdesc *pd)
4914 struct pf_state_peer *src, *dst;
4915 struct pf_state_key_cmp key;
4918 key.proto = pd->proto;
4919 if (direction == PF_IN) {
4920 PF_ACPY(&key.ext.addr, pd->src, key.af);
4921 PF_ACPY(&key.gwy.addr, pd->dst, key.af);
4925 PF_ACPY(&key.lan.addr, pd->src, key.af);
4926 PF_ACPY(&key.ext.addr, pd->dst, key.af);
4933 if (direction == (*state)->state_key->direction) {
4934 src = &(*state)->src;
4935 dst = &(*state)->dst;
4937 src = &(*state)->dst;
4938 dst = &(*state)->src;
4942 if (src->state < PFOTHERS_SINGLE)
4943 src->state = PFOTHERS_SINGLE;
4944 if (dst->state == PFOTHERS_SINGLE)
4945 dst->state = PFOTHERS_MULTIPLE;
4947 /* update expire time */
4948 (*state)->expire = time_second;
4949 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
4950 (*state)->timeout = PFTM_OTHER_MULTIPLE;
4952 (*state)->timeout = PFTM_OTHER_SINGLE;
4954 /* translate source/destination address, if necessary */
4955 if (STATE_TRANSLATE((*state)->state_key)) {
4956 if (direction == PF_OUT)
4960 pf_change_a(&pd->src->v4.s_addr,
4962 (*state)->state_key->gwy.addr.v4.s_addr,
4969 &(*state)->state_key->gwy.addr, pd->af);
4977 pf_change_a(&pd->dst->v4.s_addr,
4979 (*state)->state_key->lan.addr.v4.s_addr,
4986 &(*state)->state_key->lan.addr, pd->af);
4996 * ipoff and off are measured from the start of the mbuf chain.
4997 * h must be at "ipoff" on the mbuf chain.
5000 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5001 u_short *actionp, u_short *reasonp, sa_family_t af)
5006 struct ip *h = mtod(m, struct ip *);
5007 u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;
5011 ACTION_SET(actionp, PF_PASS);
5013 ACTION_SET(actionp, PF_DROP);
5014 REASON_SET(reasonp, PFRES_FRAG);
5018 if (m->m_pkthdr.len < off + len ||
5019 h->ip_len < off + len) {
5020 ACTION_SET(actionp, PF_DROP);
5021 REASON_SET(reasonp, PFRES_SHORT);
5029 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5031 if (m->m_pkthdr.len < off + len ||
5032 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5033 (unsigned)(off + len)) {
5034 ACTION_SET(actionp, PF_DROP);
5035 REASON_SET(reasonp, PFRES_SHORT);
5042 m_copydata(m, off, len, p);
5047 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif)
5049 struct sockaddr_in *dst;
5053 struct sockaddr_in6 *dst6;
5054 struct route_in6 ro;
5058 struct radix_node *rn;
5063 bzero(&ro, sizeof(ro));
5066 dst = satosin(&ro.ro_dst);
5067 dst->sin_family = AF_INET;
5068 dst->sin_len = sizeof(*dst);
5069 dst->sin_addr = addr->v4;
5073 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5074 dst6->sin6_family = AF_INET6;
5075 dst6->sin6_len = sizeof(*dst6);
5076 dst6->sin6_addr = addr->v6;
5083 /* Skip checks for ipsec interfaces */
5084 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5087 rtalloc_ign((struct route *)&ro, 0);
5089 if (ro.ro_rt != NULL) {
5090 /* No interface given, this is a no-route check */
5094 if (kif->pfik_ifp == NULL) {
5099 /* Perform uRPF check if passed input interface */
5101 rn = (struct radix_node *)ro.ro_rt;
5103 rt = (struct rtentry *)rn;
5106 if (kif->pfik_ifp == ifp)
5109 } while (check_mpath == 1 && rn != NULL && ret == 0);
5113 if (ro.ro_rt != NULL)
5119 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw)
5121 struct sockaddr_in *dst;
5123 struct sockaddr_in6 *dst6;
5124 struct route_in6 ro;
5130 lwkt_gettoken(&pf_token);
5132 bzero(&ro, sizeof(ro));
5135 dst = satosin(&ro.ro_dst);
5136 dst->sin_family = AF_INET;
5137 dst->sin_len = sizeof(*dst);
5138 dst->sin_addr = addr->v4;
5142 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5143 dst6->sin6_family = AF_INET6;
5144 dst6->sin6_len = sizeof(*dst6);
5145 dst6->sin6_addr = addr->v6;
5149 lwkt_reltoken(&pf_token);
5153 rtalloc_ign((struct route *)&ro, (RTF_CLONING | RTF_PRCLONING));
5155 if (ro.ro_rt != NULL) {
5159 lwkt_reltoken(&pf_token);
5165 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5166 struct pf_state *s, struct pf_pdesc *pd)
5168 struct mbuf *m0, *m1;
5169 struct route iproute;
5170 struct route *ro = NULL;
5171 struct sockaddr_in *dst;
5173 struct ifnet *ifp = NULL;
5174 struct pf_addr naddr;
5175 struct pf_src_node *sn = NULL;
5182 lwkt_gettoken(&pf_token);
5184 if (m == NULL || *m == NULL || r == NULL ||
5185 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5186 panic("pf_route: invalid parameters");
5188 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5189 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5190 (*m)->m_pkthdr.pf.routed = 1;
5192 if ((*m)->m_pkthdr.pf.routed++ > 3) {
5199 if (r->rt == PF_DUPTO) {
5200 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL) {
5201 lwkt_reltoken(&pf_token);
5205 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
5206 lwkt_reltoken(&pf_token);
5212 if (m0->m_len < sizeof(struct ip)) {
5213 DPFPRINTF(PF_DEBUG_URGENT,
5214 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5218 ip = mtod(m0, struct ip *);
5221 bzero((caddr_t)ro, sizeof(*ro));
5222 dst = satosin(&ro->ro_dst);
5223 dst->sin_family = AF_INET;
5224 dst->sin_len = sizeof(*dst);
5225 dst->sin_addr = ip->ip_dst;
5227 if (r->rt == PF_FASTROUTE) {
5229 if (ro->ro_rt == 0) {
5230 ipstat.ips_noroute++;
5234 ifp = ro->ro_rt->rt_ifp;
5235 ro->ro_rt->rt_use++;
5237 if (ro->ro_rt->rt_flags & RTF_GATEWAY)
5238 dst = satosin(ro->ro_rt->rt_gateway);
5240 if (TAILQ_EMPTY(&r->rpool.list)) {
5241 DPFPRINTF(PF_DEBUG_URGENT,
5242 ("pf_route: TAILQ_EMPTY(&r->rpool.list)\n"));
5246 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
5248 if (!PF_AZERO(&naddr, AF_INET))
5249 dst->sin_addr.s_addr = naddr.v4.s_addr;
5250 ifp = r->rpool.cur->kif ?
5251 r->rpool.cur->kif->pfik_ifp : NULL;
5253 if (!PF_AZERO(&s->rt_addr, AF_INET))
5254 dst->sin_addr.s_addr =
5255 s->rt_addr.v4.s_addr;
5256 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5264 if (pf_test(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5267 } else if (m0 == NULL) {
5272 if (m0->m_len < sizeof(struct ip)) {
5273 DPFPRINTF(PF_DEBUG_URGENT,
5274 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
5277 ip = mtod(m0, struct ip *);
5280 /* Copied from FreeBSD 5.1-CURRENT ip_output. */
5281 m0->m_pkthdr.csum_flags |= CSUM_IP;
5282 sw_csum = m0->m_pkthdr.csum_flags & ~ifp->if_hwassist;
5283 if (sw_csum & CSUM_DELAY_DATA) {
5284 in_delayed_cksum(m0);
5285 sw_csum &= ~CSUM_DELAY_DATA;
5287 m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
5289 if (ip->ip_len <= ifp->if_mtu ||
5290 (ifp->if_hwassist & CSUM_FRAGMENT &&
5291 (ip->ip_off & IP_DF) == 0)) {
5292 ip->ip_len = htons(ip->ip_len);
5293 ip->ip_off = htons(ip->ip_off);
5295 if (sw_csum & CSUM_DELAY_IP) {
5297 if (ip->ip_v == IPVERSION &&
5298 (ip->ip_hl << 2) == sizeof(*ip)) {
5299 ip->ip_sum = in_cksum_hdr(ip);
5301 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
5304 lwkt_reltoken(&pf_token);
5306 error = ifp->if_output(ifp, m0, sintosa(dst), ro->ro_rt);
5308 lwkt_gettoken(&pf_token);
5313 * Too large for interface; fragment if possible.
5314 * Must be able to put at least 8 bytes per fragment.
5316 if (ip->ip_off & IP_DF) {
5317 ipstat.ips_cantfrag++;
5318 if (r->rt != PF_DUPTO) {
5320 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
5329 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist, sw_csum);
5334 for (m0 = m1; m0; m0 = m1) {
5338 lwkt_reltoken(&pf_token);
5340 error = (*ifp->if_output)(ifp, m0, sintosa(dst),
5343 lwkt_gettoken(&pf_token);
5349 ipstat.ips_fragmented++;
5352 if (r->rt != PF_DUPTO)
5354 if (ro == &iproute && ro->ro_rt)
5356 lwkt_reltoken(&pf_token);
5367 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
5368 struct pf_state *s, struct pf_pdesc *pd)
5371 struct route_in6 ip6route;
5372 struct route_in6 *ro;
5373 struct sockaddr_in6 *dst;
5374 struct ip6_hdr *ip6;
5375 struct ifnet *ifp = NULL;
5376 struct pf_addr naddr;
5377 struct pf_src_node *sn = NULL;
5380 if (m == NULL || *m == NULL || r == NULL ||
5381 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
5382 panic("pf_route6: invalid parameters");
5384 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
5385 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
5386 (*m)->m_pkthdr.pf.routed = 1;
5388 if ((*m)->m_pkthdr.pf.routed++ > 3) {
5395 if (r->rt == PF_DUPTO) {
5396 if ((m0 = m_dup(*m, MB_DONTWAIT)) == NULL)
5399 if ((r->rt == PF_REPLYTO) == (r->direction == dir))
5404 if (m0->m_len < sizeof(struct ip6_hdr)) {
5405 DPFPRINTF(PF_DEBUG_URGENT,
5406 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5409 ip6 = mtod(m0, struct ip6_hdr *);
5412 bzero((caddr_t)ro, sizeof(*ro));
5413 dst = (struct sockaddr_in6 *)&ro->ro_dst;
5414 dst->sin6_family = AF_INET6;
5415 dst->sin6_len = sizeof(*dst);
5416 dst->sin6_addr = ip6->ip6_dst;
5418 /* Cheat. XXX why only in the v6 case??? */
5419 if (r->rt == PF_FASTROUTE) {
5420 m0->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
5421 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
5426 if (TAILQ_EMPTY(&r->rpool.list)) {
5427 DPFPRINTF(PF_DEBUG_URGENT,
5428 ("pf_route6: TAILQ_EMPTY(&r->rpool.list)\n"));
5432 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
5434 if (!PF_AZERO(&naddr, AF_INET6))
5435 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5437 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
5439 if (!PF_AZERO(&s->rt_addr, AF_INET6))
5440 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
5441 &s->rt_addr, AF_INET6);
5442 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
5449 if (pf_test6(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
5452 } else if (m0 == NULL) {
5457 if (m0->m_len < sizeof(struct ip6_hdr)) {
5458 DPFPRINTF(PF_DEBUG_URGENT,
5459 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
5462 ip6 = mtod(m0, struct ip6_hdr *);
5466 * If the packet is too large for the outgoing interface,
5467 * send back an icmp6 error.
5469 if (IN6_IS_ADDR_LINKLOCAL(&dst->sin6_addr))
5470 dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
5471 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
5473 error = nd6_output(ifp, ifp, m0, dst, NULL);
5476 in6_ifstat_inc(ifp, ifs6_in_toobig);
5477 if (r->rt != PF_DUPTO) {
5479 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
5486 if (r->rt != PF_DUPTO)
5499 * check protocol (tcp/udp/icmp/icmp6) checksum and set mbuf flag
5500 * off is the offset where the protocol header starts
5501 * len is the total length of protocol header plus payload
5502 * returns 0 when the checksum is valid, otherwise returns 1.
5506 * FreeBSD supports cksum offload for the following drivers.
5507 * em(4), gx(4), lge(4), nge(4), ti(4), xl(4)
5508 * If we can make full use of it we would outperform ipfw/ipfilter in
5509 * very heavy traffic.
5510 * I have not tested 'cause I don't have NICs that supports cksum offload.
5511 * (There might be problems. Typical phenomena would be
5512 * 1. No route message for UDP packet.
5513 * 2. No connection acceptance from external hosts regardless of rule set.)
5516 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p,
5523 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
5525 if (m->m_pkthdr.len < off + len)
5531 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
5532 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
5533 sum = m->m_pkthdr.csum_data;
5535 ip = mtod(m, struct ip *);
5536 sum = in_pseudo(ip->ip_src.s_addr,
5537 ip->ip_dst.s_addr, htonl((u_short)len +
5538 m->m_pkthdr.csum_data + p));
5546 case IPPROTO_ICMPV6:
5556 if (p == IPPROTO_ICMP) {
5561 sum = in_cksum(m, len);
5565 if (m->m_len < sizeof(struct ip))
5567 sum = in_cksum_range(m, p, off, len);
5569 m->m_pkthdr.csum_flags |=
5572 m->m_pkthdr.csum_data = 0xffff;
5578 if (m->m_len < sizeof(struct ip6_hdr))
5580 sum = in6_cksum(m, p, off, len);
5583 * IPv6 H/W cksum off-load not supported yet!
5586 * m->m_pkthdr.csum_flags |=
5587 * (CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
5588 * m->m_pkthdr.csum_data = 0xffff;
5600 tcpstat.tcps_rcvbadsum++;
5603 udpstat.udps_badsum++;
5606 icmpstat.icps_checksum++;
5609 case IPPROTO_ICMPV6:
5610 icmp6stat.icp6s_checksum++;
5621 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0,
5622 struct ether_header *eh, struct inpcb *inp)
5624 struct pfi_kif *kif;
5625 u_short action, reason = 0, log = 0;
5626 struct mbuf *m = *m0;
5627 struct ip *h = NULL;
5628 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
5629 struct pf_state *s = NULL;
5630 struct pf_state_key *sk = NULL;
5631 struct pf_ruleset *ruleset = NULL;
5633 int off, dirndx, pqid = 0;
5635 if (!pf_status.running)
5638 memset(&pd, 0, sizeof(pd));
5639 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
5640 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
5642 kif = (struct pfi_kif *)ifp->if_pf_kif;
5645 DPFPRINTF(PF_DEBUG_URGENT,
5646 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
5649 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5653 if ((m->m_flags & M_PKTHDR) == 0)
5654 panic("non-M_PKTHDR is passed to pf_test");
5655 #endif /* DIAGNOSTIC */
5657 if (m->m_pkthdr.len < (int)sizeof(*h)) {
5659 REASON_SET(&reason, PFRES_SHORT);
5664 if (m->m_pkthdr.pf.flags & PF_TAG_GENERATED)
5667 /* We do IP header normalization and packet reassembly here */
5668 if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
5672 m = *m0; /* pf_normalize messes with m0 */
5673 h = mtod(m, struct ip *);
5675 off = h->ip_hl << 2;
5676 if (off < (int)sizeof(*h)) {
5678 REASON_SET(&reason, PFRES_SHORT);
5683 pd.src = (struct pf_addr *)&h->ip_src;
5684 pd.dst = (struct pf_addr *)&h->ip_dst;
5685 PF_ACPY(&pd.baddr, dir == PF_OUT ? pd.src : pd.dst, AF_INET);
5686 pd.ip_sum = &h->ip_sum;
5690 pd.tot_len = h->ip_len;
5693 /* handle fragments that didn't get reassembled by normalization */
5694 if (h->ip_off & (IP_MF | IP_OFFMASK)) {
5695 action = pf_test_fragment(&r, dir, kif, m, h,
5706 if (!pf_pull_hdr(m, off, &th, sizeof(th),
5707 &action, &reason, AF_INET)) {
5708 log = action != PF_PASS;
5711 pd.p_len = pd.tot_len - off - (th.th_off << 2);
5712 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
5714 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
5715 if (action == PF_DROP)
5717 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
5719 if (action == PF_PASS) {
5721 pfsync_update_state(s);
5722 #endif /* NPFSYNC */
5726 } else if (s == NULL)
5727 action = pf_test_rule(&r, &s, dir, kif,
5728 m, off, h, &pd, &a, &ruleset, NULL, inp);
5736 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
5737 &action, &reason, AF_INET)) {
5738 log = action != PF_PASS;
5741 if (uh.uh_dport == 0 ||
5742 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
5743 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
5745 REASON_SET(&reason, PFRES_SHORT);
5748 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
5749 if (action == PF_PASS) {
5751 pfsync_update_state(s);
5752 #endif /* NPFSYNC */
5756 } else if (s == NULL)
5757 action = pf_test_rule(&r, &s, dir, kif,
5758 m, off, h, &pd, &a, &ruleset, NULL, inp);
5762 case IPPROTO_ICMP: {
5766 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
5767 &action, &reason, AF_INET)) {
5768 log = action != PF_PASS;
5771 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
5773 if (action == PF_PASS) {
5775 pfsync_update_state(s);
5776 #endif /* NPFSYNC */
5780 } else if (s == NULL)
5781 action = pf_test_rule(&r, &s, dir, kif,
5782 m, off, h, &pd, &a, &ruleset, NULL, inp);
5787 action = pf_test_state_other(&s, dir, kif, &pd);
5788 if (action == PF_PASS) {
5790 pfsync_update_state(s);
5791 #endif /* NPFSYNC */
5795 } else if (s == NULL)
5796 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
5797 &pd, &a, &ruleset, NULL, inp);
5802 if (action == PF_PASS && h->ip_hl > 5 &&
5803 !((s && s->allow_opts) || r->allow_opts)) {
5805 REASON_SET(&reason, PFRES_IPOPTIONS);
5807 DPFPRINTF(PF_DEBUG_MISC,
5808 ("pf: dropping packet with ip options\n"));
5811 if ((s && s->tag) || r->rtableid)
5812 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
5815 if (action == PF_PASS && r->qid) {
5816 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
5817 if (pqid || (pd.tos & IPTOS_LOWDELAY))
5818 m->m_pkthdr.pf.qid = r->pqid;
5820 m->m_pkthdr.pf.qid = r->qid;
5821 m->m_pkthdr.pf.ecn_af = AF_INET;
5822 m->m_pkthdr.pf.hdr = h;
5823 /* add connection hash for fairq */
5826 m->m_pkthdr.pf.state_hash = s->hash;
5827 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
5833 * connections redirected to loopback should not match sockets
5834 * bound specifically to loopback due to security implications,
5835 * see tcp_input() and in_pcblookup_listen().
5837 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
5838 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
5839 (s->nat_rule.ptr->action == PF_RDR ||
5840 s->nat_rule.ptr->action == PF_BINAT) &&
5841 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
5842 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
5847 if (s != NULL && s->nat_rule.ptr != NULL &&
5848 s->nat_rule.ptr->log & PF_LOG_ALL)
5849 lr = s->nat_rule.ptr;
5852 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, lr, a, ruleset,
5856 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
5857 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
5859 if (action == PF_PASS || r->action == PF_DROP) {
5860 dirndx = (dir == PF_OUT);
5861 r->packets[dirndx]++;
5862 r->bytes[dirndx] += pd.tot_len;
5864 a->packets[dirndx]++;
5865 a->bytes[dirndx] += pd.tot_len;
5869 if (s->nat_rule.ptr != NULL) {
5870 s->nat_rule.ptr->packets[dirndx]++;
5871 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
5873 if (s->src_node != NULL) {
5874 s->src_node->packets[dirndx]++;
5875 s->src_node->bytes[dirndx] += pd.tot_len;
5877 if (s->nat_src_node != NULL) {
5878 s->nat_src_node->packets[dirndx]++;
5879 s->nat_src_node->bytes[dirndx] += pd.tot_len;
5881 dirndx = (dir == sk->direction) ? 0 : 1;
5882 s->packets[dirndx]++;
5883 s->bytes[dirndx] += pd.tot_len;
5886 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
5890 * XXX: we need to make sure that the addresses
5891 * passed to pfr_update_stats() are the same than
5892 * the addresses used during matching (pfr_match)
5894 if (r == &pf_default_rule) {
5896 x = (sk == NULL || sk->direction == dir) ?
5897 &pd.baddr : &pd.naddr;
5899 x = (sk == NULL || sk->direction == dir) ?
5900 &pd.naddr : &pd.baddr;
5901 if (x == &pd.baddr || s == NULL) {
5902 /* we need to change the address */
5909 if (tr->src.addr.type == PF_ADDR_TABLE)
5910 pfr_update_stats(tr->src.addr.p.tbl, (sk == NULL ||
5911 sk->direction == dir) ?
5912 pd.src : pd.dst, pd.af,
5913 pd.tot_len, dir == PF_OUT, r->action == PF_PASS,
5915 if (tr->dst.addr.type == PF_ADDR_TABLE)
5916 pfr_update_stats(tr->dst.addr.p.tbl, (sk == NULL ||
5917 sk->direction == dir) ? pd.dst : pd.src, pd.af,
5918 pd.tot_len, dir == PF_OUT, r->action == PF_PASS,
5923 if (action == PF_SYNPROXY_DROP) {
5928 /* pf_route can free the mbuf causing *m0 to become NULL */
5929 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
5937 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0,
5938 struct ether_header *eh, struct inpcb *inp)
5940 struct pfi_kif *kif;
5941 u_short action, reason = 0, log = 0;
5942 struct mbuf *m = *m0, *n = NULL;
5943 struct ip6_hdr *h = NULL;
5944 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
5945 struct pf_state *s = NULL;
5946 struct pf_state_key *sk = NULL;
5947 struct pf_ruleset *ruleset = NULL;
5949 int off, terminal = 0, dirndx, rh_cnt = 0;
5951 if (!pf_status.running)
5954 memset(&pd, 0, sizeof(pd));
5955 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
5956 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
5958 kif = (struct pfi_kif *)ifp->if_pf_kif;
5961 DPFPRINTF(PF_DEBUG_URGENT,
5962 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
5965 if (kif->pfik_flags & PFI_IFLAG_SKIP)
5969 if ((m->m_flags & M_PKTHDR) == 0)
5970 panic("non-M_PKTHDR is passed to pf_test6");
5971 #endif /* DIAGNOSTIC */
5973 if (m->m_pkthdr.len < (int)sizeof(*h)) {
5975 REASON_SET(&reason, PFRES_SHORT);
5980 if (m->m_pkthdr.pf.flags & PF_TAG_GENERATED)
5983 /* We do IP header normalization and packet reassembly here */
5984 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
5988 m = *m0; /* pf_normalize messes with m0 */
5989 h = mtod(m, struct ip6_hdr *);
5993 * we do not support jumbogram yet. if we keep going, zero ip6_plen
5994 * will do something bad, so drop the packet for now.
5996 if (htons(h->ip6_plen) == 0) {
5998 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6003 pd.src = (struct pf_addr *)&h->ip6_src;
6004 pd.dst = (struct pf_addr *)&h->ip6_dst;
6005 PF_ACPY(&pd.baddr, dir == PF_OUT ? pd.src : pd.dst, AF_INET6);
6009 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6012 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6013 pd.proto = h->ip6_nxt;
6016 case IPPROTO_FRAGMENT:
6017 action = pf_test_fragment(&r, dir, kif, m, h,
6019 if (action == PF_DROP)
6020 REASON_SET(&reason, PFRES_FRAG);
6022 case IPPROTO_ROUTING: {
6023 struct ip6_rthdr rthdr;
6026 DPFPRINTF(PF_DEBUG_MISC,
6027 ("pf: IPv6 more than one rthdr\n"));
6029 REASON_SET(&reason, PFRES_IPOPTIONS);
6033 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6035 DPFPRINTF(PF_DEBUG_MISC,
6036 ("pf: IPv6 short rthdr\n"));
6038 REASON_SET(&reason, PFRES_SHORT);
6042 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6043 DPFPRINTF(PF_DEBUG_MISC,
6044 ("pf: IPv6 rthdr0\n"));
6046 REASON_SET(&reason, PFRES_IPOPTIONS);
6053 case IPPROTO_HOPOPTS:
6054 case IPPROTO_DSTOPTS: {
6055 /* get next header and header length */
6056 struct ip6_ext opt6;
6058 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6059 NULL, &reason, pd.af)) {
6060 DPFPRINTF(PF_DEBUG_MISC,
6061 ("pf: IPv6 short opt\n"));
6066 if (pd.proto == IPPROTO_AH)
6067 off += (opt6.ip6e_len + 2) * 4;
6069 off += (opt6.ip6e_len + 1) * 8;
6070 pd.proto = opt6.ip6e_nxt;
6071 /* goto the next header */
6078 } while (!terminal);
6080 /* if there's no routing header, use unmodified mbuf for checksumming */
6090 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6091 &action, &reason, AF_INET6)) {
6092 log = action != PF_PASS;
6095 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6096 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6097 if (action == PF_DROP)
6099 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6101 if (action == PF_PASS) {
6103 pfsync_update_state(s);
6104 #endif /* NPFSYNC */
6108 } else if (s == NULL)
6109 action = pf_test_rule(&r, &s, dir, kif,
6110 m, off, h, &pd, &a, &ruleset, NULL, inp);
6118 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6119 &action, &reason, AF_INET6)) {
6120 log = action != PF_PASS;
6123 if (uh.uh_dport == 0 ||
6124 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6125 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6127 REASON_SET(&reason, PFRES_SHORT);
6130 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6131 if (action == PF_PASS) {
6133 pfsync_update_state(s);
6134 #endif /* NPFSYNC */
6138 } else if (s == NULL)
6139 action = pf_test_rule(&r, &s, dir, kif,
6140 m, off, h, &pd, &a, &ruleset, NULL, inp);
6144 case IPPROTO_ICMPV6: {
6145 struct icmp6_hdr ih;
6148 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
6149 &action, &reason, AF_INET6)) {
6150 log = action != PF_PASS;
6153 action = pf_test_state_icmp(&s, dir, kif,
6154 m, off, h, &pd, &reason);
6155 if (action == PF_PASS) {
6157 pfsync_update_state(s);
6158 #endif /* NPFSYNC */
6162 } else if (s == NULL)
6163 action = pf_test_rule(&r, &s, dir, kif,
6164 m, off, h, &pd, &a, &ruleset, NULL, inp);
6169 action = pf_test_state_other(&s, dir, kif, &pd);
6170 if (action == PF_PASS) {
6172 pfsync_update_state(s);
6173 #endif /* NPFSYNC */
6177 } else if (s == NULL)
6178 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6179 &pd, &a, &ruleset, NULL, inp);
6189 /* handle dangerous IPv6 extension headers. */
6190 if (action == PF_PASS && rh_cnt &&
6191 !((s && s->allow_opts) || r->allow_opts)) {
6193 REASON_SET(&reason, PFRES_IPOPTIONS);
6195 DPFPRINTF(PF_DEBUG_MISC,
6196 ("pf: dropping packet with dangerous v6 headers\n"));
6199 if ((s && s->tag) || r->rtableid)
6200 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6203 if (action == PF_PASS && r->qid) {
6204 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6205 if (pd.tos & IPTOS_LOWDELAY)
6206 m->m_pkthdr.pf.qid = r->pqid;
6208 m->m_pkthdr.pf.qid = r->qid;
6209 m->m_pkthdr.pf.ecn_af = AF_INET6;
6210 m->m_pkthdr.pf.hdr = h;
6213 m->m_pkthdr.pf.state_hash = s->hash;
6214 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6219 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6220 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6221 (s->nat_rule.ptr->action == PF_RDR ||
6222 s->nat_rule.ptr->action == PF_BINAT) &&
6223 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
6224 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6229 if (s != NULL && s->nat_rule.ptr != NULL &&
6230 s->nat_rule.ptr->log & PF_LOG_ALL)
6231 lr = s->nat_rule.ptr;
6234 PFLOG_PACKET(kif, h, m, AF_INET6, dir, reason, lr, a, ruleset,
6238 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6239 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
6241 if (action == PF_PASS || r->action == PF_DROP) {
6242 dirndx = (dir == PF_OUT);
6243 r->packets[dirndx]++;
6244 r->bytes[dirndx] += pd.tot_len;
6246 a->packets[dirndx]++;
6247 a->bytes[dirndx] += pd.tot_len;
6251 if (s->nat_rule.ptr != NULL) {
6252 s->nat_rule.ptr->packets[dirndx]++;
6253 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6255 if (s->src_node != NULL) {
6256 s->src_node->packets[dirndx]++;
6257 s->src_node->bytes[dirndx] += pd.tot_len;
6259 if (s->nat_src_node != NULL) {
6260 s->nat_src_node->packets[dirndx]++;
6261 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6263 dirndx = (dir == sk->direction) ? 0 : 1;
6264 s->packets[dirndx]++;
6265 s->bytes[dirndx] += pd.tot_len;
6268 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6272 * XXX: we need to make sure that the addresses
6273 * passed to pfr_update_stats() are the same than
6274 * the addresses used during matching (pfr_match)
6276 if (r == &pf_default_rule) {
6278 x = (s == NULL || sk->direction == dir) ?
6279 &pd.baddr : &pd.naddr;
6281 x = (s == NULL || sk->direction == dir) ?
6282 &pd.naddr : &pd.baddr;
6284 if (x == &pd.baddr || s == NULL) {
6291 if (tr->src.addr.type == PF_ADDR_TABLE)
6292 pfr_update_stats(tr->src.addr.p.tbl, (sk == NULL ||
6293 sk->direction == dir) ? pd.src : pd.dst, pd.af,
6294 pd.tot_len, dir == PF_OUT, r->action == PF_PASS,
6296 if (tr->dst.addr.type == PF_ADDR_TABLE)
6297 pfr_update_stats(tr->dst.addr.p.tbl, (sk == NULL ||
6298 sk->direction == dir) ? pd.dst : pd.src, pd.af,
6299 pd.tot_len, dir == PF_OUT, r->action == PF_PASS,
6304 if (action == PF_SYNPROXY_DROP) {
6309 /* pf_route6 can free the mbuf causing *m0 to become NULL */
6310 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
6317 pf_check_congestion(struct ifqueue *ifq)