route: Delete ortentry, SIOC{ADD,DEL}RT and RTM_OLD{ADD,DEL}
[dragonfly.git] / sys / net / pf / pf.c
blobd9920b4c321feeb7fdd0264c9a06c5312852d1f3
1 /*
2 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
4 * Copyright (c) 2001 Daniel Hartmeier
5 * Copyright (c) 2002 - 2008 Henning Brauer
6 * All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
12 * - Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
32 * Effort sponsored in part by the Defense Advanced Research Projects
33 * Agency (DARPA) and Air Force Research Laboratory, Air Force
34 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/filio.h>
46 #include <sys/socket.h>
47 #include <sys/socketvar.h>
48 #include <sys/kernel.h>
49 #include <sys/time.h>
50 #include <sys/sysctl.h>
51 #include <sys/endian.h>
52 #include <sys/proc.h>
53 #include <sys/kthread.h>
54 #include <sys/spinlock.h>
56 #include <machine/inttypes.h>
58 #include <sys/md5.h>
60 #include <net/if.h>
61 #include <net/if_types.h>
62 #include <net/bpf.h>
63 #include <net/netisr2.h>
64 #include <net/route.h>
66 #include <netinet/in.h>
67 #include <netinet/in_var.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/tcp.h>
72 #include <netinet/tcp_seq.h>
73 #include <netinet/udp.h>
74 #include <netinet/ip_icmp.h>
75 #include <netinet/in_pcb.h>
76 #include <netinet/tcp_timer.h>
77 #include <netinet/tcp_var.h>
78 #include <netinet/udp_var.h>
79 #include <netinet/icmp_var.h>
80 #include <netinet/if_ether.h>
82 #include <net/pf/pfvar.h>
83 #include <net/pf/if_pflog.h>
85 #include <net/pf/if_pfsync.h>
87 #ifdef INET6
88 #include <netinet/ip6.h>
89 #include <netinet/icmp6.h>
90 #include <netinet6/nd6.h>
91 #include <netinet6/ip6_var.h>
92 #include <netinet6/in6_pcb.h>
93 #endif /* INET6 */
95 #include <sys/in_cksum.h>
96 #include <sys/ucred.h>
97 #include <machine/limits.h>
98 #include <sys/msgport2.h>
99 #include <sys/spinlock2.h>
100 #include <net/netmsg2.h>
101 #include <net/toeplitz2.h>
103 extern int ip_optcopy(struct ip *, struct ip *);
104 extern int debug_pfugidhack;
107 * pf_token - shared lock for cpu-localized operations,
108 * exclusive lock otherwise.
110 * pf_gtoken- exclusive lock used for initialization.
112 * pf_spin - only used to atomically fetch and increment stateid
113 * on 32-bit systems.
115 struct lwkt_token pf_token = LWKT_TOKEN_INITIALIZER(pf_token);
116 struct lwkt_token pf_gtoken = LWKT_TOKEN_INITIALIZER(pf_gtoken);
117 #if __SIZEOF_LONG__ != 8
118 struct spinlock pf_spin = SPINLOCK_INITIALIZER(pf_spin, "pf_spin");
119 #endif
121 #define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
123 #define FAIL(code) { error = (code); goto done; }
126 * Global variables
129 /* mask radix tree */
130 struct radix_node_head *pf_maskhead;
132 /* state tables */
133 struct pf_state_tree pf_statetbl[MAXCPU+1]; /* incls one global table */
135 struct pf_altqqueue pf_altqs[2];
136 struct pf_palist pf_pabuf;
137 struct pf_altqqueue *pf_altqs_active;
138 struct pf_altqqueue *pf_altqs_inactive;
139 struct pf_status pf_status;
141 u_int32_t ticket_altqs_active;
142 u_int32_t ticket_altqs_inactive;
143 int altqs_inactive_open;
144 u_int32_t ticket_pabuf;
146 MD5_CTX pf_tcp_secret_ctx;
147 u_char pf_tcp_secret[16];
148 int pf_tcp_secret_init;
149 int pf_tcp_iss_off;
151 struct pf_anchor_stackframe {
152 struct pf_ruleset *rs;
153 struct pf_rule *r;
154 struct pf_anchor_node *parent;
155 struct pf_anchor *child;
156 } pf_anchor_stack[64];
158 struct malloc_type *pf_src_tree_pl, *pf_rule_pl, *pf_pooladdr_pl;
159 struct malloc_type *pf_state_pl, *pf_state_key_pl, *pf_state_item_pl;
160 struct malloc_type *pf_altq_pl;
162 void pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
164 void pf_init_threshold(struct pf_threshold *, u_int32_t,
165 u_int32_t);
166 void pf_add_threshold(struct pf_threshold *);
167 int pf_check_threshold(struct pf_threshold *);
169 void pf_change_ap(struct pf_addr *, u_int16_t *,
170 u_int16_t *, u_int16_t *, struct pf_addr *,
171 u_int16_t, u_int8_t, sa_family_t);
172 int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
173 struct tcphdr *, struct pf_state_peer *);
174 #ifdef INET6
175 void pf_change_a6(struct pf_addr *, u_int16_t *,
176 struct pf_addr *, u_int8_t);
177 #endif /* INET6 */
178 void pf_change_icmp(struct pf_addr *, u_int16_t *,
179 struct pf_addr *, struct pf_addr *, u_int16_t,
180 u_int16_t *, u_int16_t *, u_int16_t *,
181 u_int16_t *, u_int8_t, sa_family_t);
182 void pf_send_tcp(const struct pf_rule *, sa_family_t,
183 const struct pf_addr *, const struct pf_addr *,
184 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
185 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
186 u_int16_t, struct ether_header *, struct ifnet *);
187 void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
188 sa_family_t, struct pf_rule *);
189 struct pf_rule *pf_match_translation(struct pf_pdesc *, struct mbuf *,
190 int, int, struct pfi_kif *,
191 struct pf_addr *, u_int16_t, struct pf_addr *,
192 u_int16_t, int);
193 struct pf_rule *pf_get_translation(struct pf_pdesc *, struct mbuf *,
194 int, int, struct pfi_kif *, struct pf_src_node **,
195 struct pf_state_key **, struct pf_state_key **,
196 struct pf_state_key **, struct pf_state_key **,
197 struct pf_addr *, struct pf_addr *,
198 u_int16_t, u_int16_t);
199 void pf_detach_state(struct pf_state *);
200 int pf_state_key_setup(struct pf_pdesc *, struct pf_rule *,
201 struct pf_state_key **, struct pf_state_key **,
202 struct pf_state_key **, struct pf_state_key **,
203 struct pf_addr *, struct pf_addr *,
204 u_int16_t, u_int16_t);
205 void pf_state_key_detach(struct pf_state *, int);
206 u_int32_t pf_tcp_iss(struct pf_pdesc *);
207 int pf_test_rule(struct pf_rule **, struct pf_state **,
208 int, struct pfi_kif *, struct mbuf *, int,
209 void *, struct pf_pdesc *, struct pf_rule **,
210 struct pf_ruleset **, struct ifqueue *, struct inpcb *);
211 static __inline int pf_create_state(struct pf_rule *, struct pf_rule *,
212 struct pf_rule *, struct pf_pdesc *,
213 struct pf_src_node *, struct pf_state_key *,
214 struct pf_state_key *, struct pf_state_key *,
215 struct pf_state_key *, struct mbuf *, int,
216 u_int16_t, u_int16_t, int *, struct pfi_kif *,
217 struct pf_state **, int, u_int16_t, u_int16_t,
218 int);
219 int pf_test_fragment(struct pf_rule **, int,
220 struct pfi_kif *, struct mbuf *, void *,
221 struct pf_pdesc *, struct pf_rule **,
222 struct pf_ruleset **);
223 int pf_tcp_track_full(struct pf_state_peer *,
224 struct pf_state_peer *, struct pf_state **,
225 struct pfi_kif *, struct mbuf *, int,
226 struct pf_pdesc *, u_short *, int *);
227 int pf_tcp_track_sloppy(struct pf_state_peer *,
228 struct pf_state_peer *, struct pf_state **,
229 struct pf_pdesc *, u_short *);
230 int pf_test_state_tcp(struct pf_state **, int,
231 struct pfi_kif *, struct mbuf *, int,
232 void *, struct pf_pdesc *, u_short *);
233 int pf_test_state_udp(struct pf_state **, int,
234 struct pfi_kif *, struct mbuf *, int,
235 void *, struct pf_pdesc *);
236 int pf_test_state_icmp(struct pf_state **, int,
237 struct pfi_kif *, struct mbuf *, int,
238 void *, struct pf_pdesc *, u_short *);
239 int pf_test_state_other(struct pf_state **, int,
240 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
241 void pf_step_into_anchor(int *, struct pf_ruleset **, int,
242 struct pf_rule **, struct pf_rule **, int *);
243 int pf_step_out_of_anchor(int *, struct pf_ruleset **,
244 int, struct pf_rule **, struct pf_rule **,
245 int *);
246 void pf_hash(struct pf_addr *, struct pf_addr *,
247 struct pf_poolhashkey *, sa_family_t);
248 int pf_map_addr(u_int8_t, struct pf_rule *,
249 struct pf_addr *, struct pf_addr *,
250 struct pf_addr *, struct pf_src_node **);
251 int pf_get_sport(struct pf_pdesc *,
252 sa_family_t, u_int8_t, struct pf_rule *,
253 struct pf_addr *, struct pf_addr *,
254 u_int16_t, u_int16_t,
255 struct pf_addr *, u_int16_t *,
256 u_int16_t, u_int16_t,
257 struct pf_src_node **);
258 void pf_route(struct mbuf **, struct pf_rule *, int,
259 struct ifnet *, struct pf_state *,
260 struct pf_pdesc *);
261 void pf_route6(struct mbuf **, struct pf_rule *, int,
262 struct ifnet *, struct pf_state *,
263 struct pf_pdesc *);
264 u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
265 sa_family_t);
266 u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
267 sa_family_t);
268 u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
269 u_int16_t);
270 void pf_set_rt_ifp(struct pf_state *,
271 struct pf_addr *);
272 int pf_check_proto_cksum(struct mbuf *, int, int,
273 u_int8_t, sa_family_t);
274 struct pf_divert *pf_get_divert(struct mbuf *);
275 void pf_print_state_parts(struct pf_state *,
276 struct pf_state_key *, struct pf_state_key *);
277 int pf_addr_wrap_neq(struct pf_addr_wrap *,
278 struct pf_addr_wrap *);
279 struct pf_state *pf_find_state(struct pfi_kif *,
280 struct pf_state_key_cmp *, u_int, struct mbuf *);
281 int pf_src_connlimit(struct pf_state *);
282 int pf_check_congestion(struct ifqueue *);
284 extern int pf_end_threads;
286 struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
287 { &pf_state_pl, PFSTATE_HIWAT },
288 { &pf_src_tree_pl, PFSNODE_HIWAT },
289 { &pf_frent_pl, PFFRAG_FRENT_HIWAT },
290 { &pfr_ktable_pl, PFR_KTABLE_HIWAT },
291 { &pfr_kentry_pl, PFR_KENTRY_HIWAT }
295 * If route-to and direction is out we match with no further processing
296 * (rt_kif must be assigned and not equal to the out interface)
297 * If reply-to and direction is in we match with no further processing
298 * (rt_kif must be assigned and not equal to the in interface)
300 #define STATE_LOOKUP(i, k, d, s, m) \
301 do { \
302 s = pf_find_state(i, k, d, m); \
303 if (s == NULL || (s)->timeout == PFTM_PURGE) \
304 return (PF_DROP); \
305 if (d == PF_OUT && \
306 (((s)->rule.ptr->rt == PF_ROUTETO && \
307 (s)->rule.ptr->direction == PF_OUT) || \
308 ((s)->rule.ptr->rt == PF_REPLYTO && \
309 (s)->rule.ptr->direction == PF_IN)) && \
310 (s)->rt_kif != NULL && \
311 (s)->rt_kif != i) \
312 return (PF_PASS); \
313 } while (0)
315 #define BOUND_IFACE(r, k) \
316 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
318 #define STATE_INC_COUNTERS(s) \
319 do { \
320 atomic_add_int(&s->rule.ptr->states_cur, 1); \
321 s->rule.ptr->states_tot++; \
322 if (s->anchor.ptr != NULL) { \
323 atomic_add_int(&s->anchor.ptr->states_cur, 1); \
324 s->anchor.ptr->states_tot++; \
326 if (s->nat_rule.ptr != NULL) { \
327 atomic_add_int(&s->nat_rule.ptr->states_cur, 1); \
328 s->nat_rule.ptr->states_tot++; \
330 } while (0)
332 #define STATE_DEC_COUNTERS(s) \
333 do { \
334 if (s->nat_rule.ptr != NULL) \
335 atomic_add_int(&s->nat_rule.ptr->states_cur, -1); \
336 if (s->anchor.ptr != NULL) \
337 atomic_add_int(&s->anchor.ptr->states_cur, -1); \
338 atomic_add_int(&s->rule.ptr->states_cur, -1); \
339 } while (0)
341 static MALLOC_DEFINE(M_PFSTATEPL, "pfstatepl", "pf state pool list");
342 static MALLOC_DEFINE(M_PFSRCTREEPL, "pfsrctpl", "pf source tree pool list");
343 static MALLOC_DEFINE(M_PFSTATEKEYPL, "pfstatekeypl", "pf state key pool list");
344 static MALLOC_DEFINE(M_PFSTATEITEMPL, "pfstateitempl", "pf state item pool list");
346 static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
347 static __inline int pf_state_compare_key(struct pf_state_key *,
348 struct pf_state_key *);
349 static __inline int pf_state_compare_rkey(struct pf_state_key *,
350 struct pf_state_key *);
351 static __inline int pf_state_compare_id(struct pf_state *,
352 struct pf_state *);
354 struct pf_src_tree tree_src_tracking[MAXCPU];
355 struct pf_state_tree_id tree_id[MAXCPU];
356 struct pf_state_queue state_list[MAXCPU];
358 RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
359 RB_GENERATE(pf_state_tree, pf_state_key, entry, pf_state_compare_key);
360 RB_GENERATE(pf_state_rtree, pf_state_key, entry, pf_state_compare_rkey);
361 RB_GENERATE(pf_state_tree_id, pf_state, entry_id, pf_state_compare_id);
363 static __inline int
364 pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
366 int diff;
368 if (a->rule.ptr > b->rule.ptr)
369 return (1);
370 if (a->rule.ptr < b->rule.ptr)
371 return (-1);
372 if ((diff = a->af - b->af) != 0)
373 return (diff);
374 switch (a->af) {
375 #ifdef INET
376 case AF_INET:
377 if (a->addr.addr32[0] > b->addr.addr32[0])
378 return (1);
379 if (a->addr.addr32[0] < b->addr.addr32[0])
380 return (-1);
381 break;
382 #endif /* INET */
383 #ifdef INET6
384 case AF_INET6:
385 if (a->addr.addr32[3] > b->addr.addr32[3])
386 return (1);
387 if (a->addr.addr32[3] < b->addr.addr32[3])
388 return (-1);
389 if (a->addr.addr32[2] > b->addr.addr32[2])
390 return (1);
391 if (a->addr.addr32[2] < b->addr.addr32[2])
392 return (-1);
393 if (a->addr.addr32[1] > b->addr.addr32[1])
394 return (1);
395 if (a->addr.addr32[1] < b->addr.addr32[1])
396 return (-1);
397 if (a->addr.addr32[0] > b->addr.addr32[0])
398 return (1);
399 if (a->addr.addr32[0] < b->addr.addr32[0])
400 return (-1);
401 break;
402 #endif /* INET6 */
404 return (0);
407 u_int32_t
408 pf_state_hash(struct pf_state_key *sk)
410 u_int32_t hv = (u_int32_t)(((intptr_t)sk >> 6) ^ ((intptr_t)sk >> 15));
411 if (hv == 0) /* disallow 0 */
412 hv = 1;
413 return(hv);
416 #ifdef INET6
417 void
418 pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
420 switch (af) {
421 #ifdef INET
422 case AF_INET:
423 dst->addr32[0] = src->addr32[0];
424 break;
425 #endif /* INET */
426 case AF_INET6:
427 dst->addr32[0] = src->addr32[0];
428 dst->addr32[1] = src->addr32[1];
429 dst->addr32[2] = src->addr32[2];
430 dst->addr32[3] = src->addr32[3];
431 break;
434 #endif /* INET6 */
436 void
437 pf_init_threshold(struct pf_threshold *threshold,
438 u_int32_t limit, u_int32_t seconds)
440 threshold->limit = limit * PF_THRESHOLD_MULT;
441 threshold->seconds = seconds;
442 threshold->count = 0;
443 threshold->last = time_second;
446 void
447 pf_add_threshold(struct pf_threshold *threshold)
449 u_int32_t t = time_second, diff = t - threshold->last;
451 if (diff >= threshold->seconds)
452 threshold->count = 0;
453 else
454 threshold->count -= threshold->count * diff /
455 threshold->seconds;
456 threshold->count += PF_THRESHOLD_MULT;
457 threshold->last = t;
461 pf_check_threshold(struct pf_threshold *threshold)
463 return (threshold->count > threshold->limit);
467 pf_src_connlimit(struct pf_state *state)
469 int bad = 0;
470 int cpu = mycpu->gd_cpuid;
472 state->src_node->conn++;
473 state->src.tcp_est = 1;
474 pf_add_threshold(&state->src_node->conn_rate);
476 if (state->rule.ptr->max_src_conn &&
477 state->rule.ptr->max_src_conn <
478 state->src_node->conn) {
479 pf_status.lcounters[LCNT_SRCCONN]++;
480 bad++;
483 if (state->rule.ptr->max_src_conn_rate.limit &&
484 pf_check_threshold(&state->src_node->conn_rate)) {
485 pf_status.lcounters[LCNT_SRCCONNRATE]++;
486 bad++;
489 if (!bad)
490 return 0;
492 if (state->rule.ptr->overload_tbl) {
493 struct pfr_addr p;
494 u_int32_t killed = 0;
496 pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
497 if (pf_status.debug >= PF_DEBUG_MISC) {
498 kprintf("pf_src_connlimit: blocking address ");
499 pf_print_host(&state->src_node->addr, 0,
500 state->key[PF_SK_WIRE]->af);
503 bzero(&p, sizeof(p));
504 p.pfra_af = state->key[PF_SK_WIRE]->af;
505 switch (state->key[PF_SK_WIRE]->af) {
506 #ifdef INET
507 case AF_INET:
508 p.pfra_net = 32;
509 p.pfra_ip4addr = state->src_node->addr.v4;
510 break;
511 #endif /* INET */
512 #ifdef INET6
513 case AF_INET6:
514 p.pfra_net = 128;
515 p.pfra_ip6addr = state->src_node->addr.v6;
516 break;
517 #endif /* INET6 */
520 pfr_insert_kentry(state->rule.ptr->overload_tbl,
521 &p, time_second);
523 /* kill existing states if that's required. */
524 if (state->rule.ptr->flush) {
525 struct pf_state_key *sk;
526 struct pf_state *st;
528 pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
529 RB_FOREACH(st, pf_state_tree_id, &tree_id[cpu]) {
530 sk = st->key[PF_SK_WIRE];
532 * Kill states from this source. (Only those
533 * from the same rule if PF_FLUSH_GLOBAL is not
534 * set). (Only on current cpu).
536 if (sk->af ==
537 state->key[PF_SK_WIRE]->af &&
538 ((state->direction == PF_OUT &&
539 PF_AEQ(&state->src_node->addr,
540 &sk->addr[0], sk->af)) ||
541 (state->direction == PF_IN &&
542 PF_AEQ(&state->src_node->addr,
543 &sk->addr[1], sk->af))) &&
544 (state->rule.ptr->flush &
545 PF_FLUSH_GLOBAL ||
546 state->rule.ptr == st->rule.ptr)) {
547 st->timeout = PFTM_PURGE;
548 st->src.state = st->dst.state =
549 TCPS_CLOSED;
550 killed++;
553 if (pf_status.debug >= PF_DEBUG_MISC)
554 kprintf(", %u states killed", killed);
556 if (pf_status.debug >= PF_DEBUG_MISC)
557 kprintf("\n");
560 /* kill this state */
561 state->timeout = PFTM_PURGE;
562 state->src.state = state->dst.state = TCPS_CLOSED;
564 return 1;
568 pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
569 struct pf_addr *src, sa_family_t af)
571 struct pf_src_node k;
572 int cpu = mycpu->gd_cpuid;
574 bzero(&k, sizeof(k)); /* avoid gcc warnings */
575 if (*sn == NULL) {
576 k.af = af;
577 PF_ACPY(&k.addr, src, af);
578 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
579 rule->rpool.opts & PF_POOL_STICKYADDR)
580 k.rule.ptr = rule;
581 else
582 k.rule.ptr = NULL;
583 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
584 *sn = RB_FIND(pf_src_tree, &tree_src_tracking[cpu], &k);
586 if (*sn == NULL) {
587 if (!rule->max_src_nodes ||
588 rule->src_nodes < rule->max_src_nodes)
589 (*sn) = kmalloc(sizeof(struct pf_src_node),
590 M_PFSRCTREEPL, M_NOWAIT|M_ZERO);
591 else
592 pf_status.lcounters[LCNT_SRCNODES]++;
593 if ((*sn) == NULL)
594 return (-1);
596 pf_init_threshold(&(*sn)->conn_rate,
597 rule->max_src_conn_rate.limit,
598 rule->max_src_conn_rate.seconds);
600 (*sn)->af = af;
601 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
602 rule->rpool.opts & PF_POOL_STICKYADDR)
603 (*sn)->rule.ptr = rule;
604 else
605 (*sn)->rule.ptr = NULL;
606 PF_ACPY(&(*sn)->addr, src, af);
607 if (RB_INSERT(pf_src_tree,
608 &tree_src_tracking[cpu], *sn) != NULL) {
609 if (pf_status.debug >= PF_DEBUG_MISC) {
610 kprintf("pf: src_tree insert failed: ");
611 pf_print_host(&(*sn)->addr, 0, af);
612 kprintf("\n");
614 kfree(*sn, M_PFSRCTREEPL);
615 return (-1);
619 * Atomic op required to increment src_nodes in the rule
620 * because we hold a shared token here (decrements will use
621 * an exclusive token).
623 (*sn)->creation = time_second;
624 (*sn)->ruletype = rule->action;
625 if ((*sn)->rule.ptr != NULL)
626 atomic_add_int(&(*sn)->rule.ptr->src_nodes, 1);
627 pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
628 atomic_add_int(&pf_status.src_nodes, 1);
629 } else {
630 if (rule->max_src_states &&
631 (*sn)->states >= rule->max_src_states) {
632 pf_status.lcounters[LCNT_SRCSTATES]++;
633 return (-1);
636 return (0);
640 * state table (indexed by the pf_state_key structure), normal RBTREE
641 * comparison.
643 static __inline int
644 pf_state_compare_key(struct pf_state_key *a, struct pf_state_key *b)
646 int diff;
648 if ((diff = a->proto - b->proto) != 0)
649 return (diff);
650 if ((diff = a->af - b->af) != 0)
651 return (diff);
652 switch (a->af) {
653 #ifdef INET
654 case AF_INET:
655 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
656 return (1);
657 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
658 return (-1);
659 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
660 return (1);
661 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
662 return (-1);
663 break;
664 #endif /* INET */
665 #ifdef INET6
666 case AF_INET6:
667 if (a->addr[0].addr32[3] > b->addr[0].addr32[3])
668 return (1);
669 if (a->addr[0].addr32[3] < b->addr[0].addr32[3])
670 return (-1);
671 if (a->addr[1].addr32[3] > b->addr[1].addr32[3])
672 return (1);
673 if (a->addr[1].addr32[3] < b->addr[1].addr32[3])
674 return (-1);
675 if (a->addr[0].addr32[2] > b->addr[0].addr32[2])
676 return (1);
677 if (a->addr[0].addr32[2] < b->addr[0].addr32[2])
678 return (-1);
679 if (a->addr[1].addr32[2] > b->addr[1].addr32[2])
680 return (1);
681 if (a->addr[1].addr32[2] < b->addr[1].addr32[2])
682 return (-1);
683 if (a->addr[0].addr32[1] > b->addr[0].addr32[1])
684 return (1);
685 if (a->addr[0].addr32[1] < b->addr[0].addr32[1])
686 return (-1);
687 if (a->addr[1].addr32[1] > b->addr[1].addr32[1])
688 return (1);
689 if (a->addr[1].addr32[1] < b->addr[1].addr32[1])
690 return (-1);
691 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
692 return (1);
693 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
694 return (-1);
695 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
696 return (1);
697 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
698 return (-1);
699 break;
700 #endif /* INET6 */
703 if ((diff = a->port[0] - b->port[0]) != 0)
704 return (diff);
705 if ((diff = a->port[1] - b->port[1]) != 0)
706 return (diff);
708 return (0);
712 * Used for RB_FIND only, compare in the reverse direction. The
713 * element to be reversed is always (a), since we obviously can't
714 * reverse the state tree depicted by (b).
716 static __inline int
717 pf_state_compare_rkey(struct pf_state_key *a, struct pf_state_key *b)
719 int diff;
721 if ((diff = a->proto - b->proto) != 0)
722 return (diff);
723 if ((diff = a->af - b->af) != 0)
724 return (diff);
725 switch (a->af) {
726 #ifdef INET
727 case AF_INET:
728 if (a->addr[1].addr32[0] > b->addr[0].addr32[0])
729 return (1);
730 if (a->addr[1].addr32[0] < b->addr[0].addr32[0])
731 return (-1);
732 if (a->addr[0].addr32[0] > b->addr[1].addr32[0])
733 return (1);
734 if (a->addr[0].addr32[0] < b->addr[1].addr32[0])
735 return (-1);
736 break;
737 #endif /* INET */
738 #ifdef INET6
739 case AF_INET6:
740 if (a->addr[1].addr32[3] > b->addr[0].addr32[3])
741 return (1);
742 if (a->addr[1].addr32[3] < b->addr[0].addr32[3])
743 return (-1);
744 if (a->addr[0].addr32[3] > b->addr[1].addr32[3])
745 return (1);
746 if (a->addr[0].addr32[3] < b->addr[1].addr32[3])
747 return (-1);
748 if (a->addr[1].addr32[2] > b->addr[0].addr32[2])
749 return (1);
750 if (a->addr[1].addr32[2] < b->addr[0].addr32[2])
751 return (-1);
752 if (a->addr[0].addr32[2] > b->addr[1].addr32[2])
753 return (1);
754 if (a->addr[0].addr32[2] < b->addr[1].addr32[2])
755 return (-1);
756 if (a->addr[1].addr32[1] > b->addr[0].addr32[1])
757 return (1);
758 if (a->addr[1].addr32[1] < b->addr[0].addr32[1])
759 return (-1);
760 if (a->addr[0].addr32[1] > b->addr[1].addr32[1])
761 return (1);
762 if (a->addr[0].addr32[1] < b->addr[1].addr32[1])
763 return (-1);
764 if (a->addr[1].addr32[0] > b->addr[0].addr32[0])
765 return (1);
766 if (a->addr[1].addr32[0] < b->addr[0].addr32[0])
767 return (-1);
768 if (a->addr[0].addr32[0] > b->addr[1].addr32[0])
769 return (1);
770 if (a->addr[0].addr32[0] < b->addr[1].addr32[0])
771 return (-1);
772 break;
773 #endif /* INET6 */
776 if ((diff = a->port[1] - b->port[0]) != 0)
777 return (diff);
778 if ((diff = a->port[0] - b->port[1]) != 0)
779 return (diff);
781 return (0);
784 static __inline int
785 pf_state_compare_id(struct pf_state *a, struct pf_state *b)
787 if (a->id > b->id)
788 return (1);
789 if (a->id < b->id)
790 return (-1);
791 if (a->creatorid > b->creatorid)
792 return (1);
793 if (a->creatorid < b->creatorid)
794 return (-1);
796 return (0);
800 pf_state_key_attach(struct pf_state_key *sk, struct pf_state *s, int idx)
802 struct pf_state_item *si;
803 struct pf_state_key *cur;
804 int cpu;
805 int error;
808 * PFSTATE_STACK_GLOBAL is set when the state might not hash to the
809 * current cpu. The keys are managed on the global statetbl tree
810 * for this case. Only translations (RDR, NAT) can cause this.
812 * When this flag is not set we must still check the global statetbl
813 * for a collision, and if we find one we set the HALF_DUPLEX flag
814 * in the state.
816 if (s->state_flags & PFSTATE_STACK_GLOBAL) {
817 cpu = MAXCPU;
818 lockmgr(&pf_global_statetbl_lock, LK_EXCLUSIVE);
819 } else {
820 cpu = mycpu->gd_cpuid;
821 lockmgr(&pf_global_statetbl_lock, LK_SHARED);
823 KKASSERT(s->key[idx] == NULL); /* XXX handle this? */
825 if (pf_status.debug >= PF_DEBUG_MISC) {
826 kprintf("state_key attach cpu %d (%08x:%d) %s (%08x:%d)\n",
827 cpu,
828 ntohl(sk->addr[0].addr32[0]), ntohs(sk->port[0]),
829 (idx == PF_SK_WIRE ? "->" : "<-"),
830 ntohl(sk->addr[1].addr32[0]), ntohs(sk->port[1]));
834 * Check whether (e.g.) a PASS rule being put on a per-cpu tree
835 * collides with a translation rule on the global tree. This is
836 * NOT an error. We *WANT* to establish state for this case so the
837 * packet path is short-cutted and doesn't need to scan the ruleset
838 * on every packet. But the established state will only see one
839 * side of a two-way packet conversation. To prevent this from
840 * causing problems (e.g. generating a RST), we force PFSTATE_SLOPPY
841 * to be set on the established state.
843 * A collision against RDR state can only occur with a PASS IN in the
844 * opposite direction or a PASS OUT in the forwards direction. This
845 * is because RDRs are processed on the input side.
847 * A collision against NAT state can only occur with a PASS IN in the
848 * forwards direction or a PASS OUT in the opposite direction. This
849 * is because NATs are processed on the output side.
851 * In both situations we need to do a reverse addr/port test because
852 * the PASS IN or PASS OUT only establishes if it doesn't match the
853 * established RDR state in the forwards direction. The direction
854 * flag has to be ignored (it will be one way for a PASS IN and the
855 * other way for a PASS OUT).
857 * pf_global_statetbl_lock will be locked shared when testing and
858 * not entering into the global state table.
860 if (cpu != MAXCPU &&
861 (cur = RB_FIND(pf_state_rtree,
862 (struct pf_state_rtree *)&pf_statetbl[MAXCPU],
863 sk)) != NULL) {
864 TAILQ_FOREACH(si, &cur->states, entry) {
866 * NOTE: We must ignore direction mismatches.
868 if (si->s->kif == s->kif) {
869 s->state_flags |= PFSTATE_HALF_DUPLEX |
870 PFSTATE_SLOPPY;
871 if (pf_status.debug >= PF_DEBUG_MISC) {
872 kprintf(
873 "pf: %s key attach collision "
874 "on %s: ",
875 (idx == PF_SK_WIRE) ?
876 "wire" : "stack",
877 s->kif->pfik_name);
878 pf_print_state_parts(s,
879 (idx == PF_SK_WIRE) ? sk : NULL,
880 (idx == PF_SK_STACK) ? sk : NULL);
881 kprintf("\n");
883 break;
889 * Enter into either the per-cpu or the global state table.
891 * pf_global_statetbl_lock will be locked exclusively when entering
892 * into the global state table.
894 if ((cur = RB_INSERT(pf_state_tree, &pf_statetbl[cpu], sk)) != NULL) {
895 /* key exists. check for same kif, if none, add to key */
896 TAILQ_FOREACH(si, &cur->states, entry) {
897 if (si->s->kif == s->kif &&
898 si->s->direction == s->direction) {
899 if (pf_status.debug >= PF_DEBUG_MISC) {
900 kprintf(
901 "pf: %s key attach failed on %s: ",
902 (idx == PF_SK_WIRE) ?
903 "wire" : "stack",
904 s->kif->pfik_name);
905 pf_print_state_parts(s,
906 (idx == PF_SK_WIRE) ? sk : NULL,
907 (idx == PF_SK_STACK) ? sk : NULL);
908 kprintf("\n");
910 kfree(sk, M_PFSTATEKEYPL);
911 error = -1;
912 goto failed; /* collision! */
915 kfree(sk, M_PFSTATEKEYPL);
917 s->key[idx] = cur;
918 } else {
919 s->key[idx] = sk;
922 if ((si = kmalloc(sizeof(struct pf_state_item),
923 M_PFSTATEITEMPL, M_NOWAIT)) == NULL) {
924 pf_state_key_detach(s, idx);
925 error = -1;
926 goto failed; /* collision! */
928 si->s = s;
930 /* list is sorted, if-bound states before floating */
931 if (s->kif == pfi_all)
932 TAILQ_INSERT_TAIL(&s->key[idx]->states, si, entry);
933 else
934 TAILQ_INSERT_HEAD(&s->key[idx]->states, si, entry);
936 error = 0;
937 failed:
938 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
939 return error;
943 * NOTE: Can only be called indirectly via the purge thread with pf_token
944 * exclusively locked.
946 void
947 pf_detach_state(struct pf_state *s)
949 if (s->key[PF_SK_WIRE] == s->key[PF_SK_STACK])
950 s->key[PF_SK_WIRE] = NULL;
952 if (s->key[PF_SK_STACK] != NULL)
953 pf_state_key_detach(s, PF_SK_STACK);
955 if (s->key[PF_SK_WIRE] != NULL)
956 pf_state_key_detach(s, PF_SK_WIRE);
960 * NOTE: Can only be called indirectly via the purge thread with pf_token
961 * exclusively locked.
963 void
964 pf_state_key_detach(struct pf_state *s, int idx)
966 struct pf_state_item *si;
967 int cpu;
970 * PFSTATE_STACK_GLOBAL is set for translations when the translated
971 * address/port is not localized to the same cpu that the untranslated
972 * address/port is on. The wire pf_state_key is managed on the global
973 * statetbl tree for this case.
975 if (s->state_flags & PFSTATE_STACK_GLOBAL) {
976 cpu = MAXCPU;
977 lockmgr(&pf_global_statetbl_lock, LK_EXCLUSIVE);
978 } else {
979 cpu = mycpu->gd_cpuid;
982 si = TAILQ_FIRST(&s->key[idx]->states);
983 while (si && si->s != s)
984 si = TAILQ_NEXT(si, entry);
986 if (si) {
987 TAILQ_REMOVE(&s->key[idx]->states, si, entry);
988 kfree(si, M_PFSTATEITEMPL);
991 if (TAILQ_EMPTY(&s->key[idx]->states)) {
992 RB_REMOVE(pf_state_tree, &pf_statetbl[cpu], s->key[idx]);
993 if (s->key[idx]->reverse)
994 s->key[idx]->reverse->reverse = NULL;
995 if (s->key[idx]->inp)
996 s->key[idx]->inp->inp_pf_sk = NULL;
997 kfree(s->key[idx], M_PFSTATEKEYPL);
999 s->key[idx] = NULL;
1001 if (s->state_flags & PFSTATE_STACK_GLOBAL)
1002 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
1005 struct pf_state_key *
1006 pf_alloc_state_key(int pool_flags)
1008 struct pf_state_key *sk;
1010 sk = kmalloc(sizeof(struct pf_state_key), M_PFSTATEKEYPL, pool_flags);
1011 if (sk) {
1012 TAILQ_INIT(&sk->states);
1014 return (sk);
1018 pf_state_key_setup(struct pf_pdesc *pd, struct pf_rule *nr,
1019 struct pf_state_key **skw, struct pf_state_key **sks,
1020 struct pf_state_key **skp, struct pf_state_key **nkp,
1021 struct pf_addr *saddr, struct pf_addr *daddr,
1022 u_int16_t sport, u_int16_t dport)
1024 KKASSERT((*skp == NULL && *nkp == NULL));
1026 if ((*skp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
1027 return (ENOMEM);
1029 PF_ACPY(&(*skp)->addr[pd->sidx], saddr, pd->af);
1030 PF_ACPY(&(*skp)->addr[pd->didx], daddr, pd->af);
1031 (*skp)->port[pd->sidx] = sport;
1032 (*skp)->port[pd->didx] = dport;
1033 (*skp)->proto = pd->proto;
1034 (*skp)->af = pd->af;
1036 if (nr != NULL) {
1037 if ((*nkp = pf_alloc_state_key(M_NOWAIT | M_ZERO)) == NULL)
1038 return (ENOMEM); /* caller must handle cleanup */
1040 /* XXX maybe just bcopy and TAILQ_INIT(&(*nkp)->states) */
1041 PF_ACPY(&(*nkp)->addr[0], &(*skp)->addr[0], pd->af);
1042 PF_ACPY(&(*nkp)->addr[1], &(*skp)->addr[1], pd->af);
1043 (*nkp)->port[0] = (*skp)->port[0];
1044 (*nkp)->port[1] = (*skp)->port[1];
1045 (*nkp)->proto = pd->proto;
1046 (*nkp)->af = pd->af;
1047 } else {
1048 *nkp = *skp;
1051 if (pd->dir == PF_IN) {
1052 *skw = *skp;
1053 *sks = *nkp;
1054 } else {
1055 *sks = *skp;
1056 *skw = *nkp;
1058 return (0);
1062 * Insert pf_state with one or two state keys (allowing a reverse path lookup
1063 * which is used by NAT). In the NAT case skw is the initiator (?) and
1064 * sks is the target.
1067 pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
1068 struct pf_state_key *sks, struct pf_state *s)
1070 int cpu = mycpu->gd_cpuid;
1072 s->kif = kif;
1073 s->cpuid = cpu;
1075 if (skw == sks) {
1076 if (pf_state_key_attach(skw, s, PF_SK_WIRE))
1077 return (-1);
1078 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
1079 } else {
1081 skw->reverse = sks;
1082 sks->reverse = skw;
1084 if (pf_state_key_attach(skw, s, PF_SK_WIRE)) {
1085 kfree(sks, M_PFSTATEKEYPL);
1086 return (-1);
1088 if (pf_state_key_attach(sks, s, PF_SK_STACK)) {
1089 pf_state_key_detach(s, PF_SK_WIRE);
1090 return (-1);
1094 if (s->id == 0 && s->creatorid == 0) {
1095 u_int64_t sid;
1097 #if __SIZEOF_LONG__ == 8
1098 sid = atomic_fetchadd_long(&pf_status.stateid, 1);
1099 #else
1100 spin_lock(&pf_spin);
1101 sid = pf_status.stateid++;
1102 spin_unlock(&pf_spin);
1103 #endif
1104 s->id = htobe64(sid);
1105 s->creatorid = pf_status.hostid;
1109 * Calculate hash code for altq
1111 s->hash = crc32(s->key[PF_SK_WIRE], PF_STATE_KEY_HASH_LENGTH);
1113 if (RB_INSERT(pf_state_tree_id, &tree_id[cpu], s) != NULL) {
1114 if (pf_status.debug >= PF_DEBUG_MISC) {
1115 kprintf("pf: state insert failed: "
1116 "id: %016jx creatorid: %08x",
1117 (uintmax_t)be64toh(s->id), ntohl(s->creatorid));
1118 if (s->sync_flags & PFSTATE_FROMSYNC)
1119 kprintf(" (from sync)");
1120 kprintf("\n");
1122 pf_detach_state(s);
1123 return (-1);
1125 TAILQ_INSERT_TAIL(&state_list[cpu], s, entry_list);
1126 pf_status.fcounters[FCNT_STATE_INSERT]++;
1127 atomic_add_int(&pf_status.states, 1);
1128 pfi_kif_ref(kif, PFI_KIF_REF_STATE);
1129 pfsync_insert_state(s);
1130 return (0);
1133 struct pf_state *
1134 pf_find_state_byid(struct pf_state_cmp *key)
1136 int cpu = mycpu->gd_cpuid;
1138 pf_status.fcounters[FCNT_STATE_SEARCH]++;
1140 return (RB_FIND(pf_state_tree_id, &tree_id[cpu],
1141 (struct pf_state *)key));
1145 * WARNING! May return a state structure that was localized to another cpu,
1146 * destruction is typically protected by the callers pf_token.
1147 * The element can only be destroyed
1149 struct pf_state *
1150 pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir,
1151 struct mbuf *m)
1153 struct pf_state_key *skey = (void *)key;
1154 struct pf_state_key *sk;
1155 struct pf_state_item *si;
1156 struct pf_state *s;
1157 int cpu = mycpu->gd_cpuid;
1158 int globalstl = 0;
1160 pf_status.fcounters[FCNT_STATE_SEARCH]++;
1162 if (dir == PF_OUT && m->m_pkthdr.pf.statekey &&
1163 ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse) {
1164 sk = ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse;
1165 } else {
1166 sk = RB_FIND(pf_state_tree, &pf_statetbl[cpu], skey);
1167 if (sk == NULL) {
1168 lockmgr(&pf_global_statetbl_lock, LK_SHARED);
1169 sk = RB_FIND(pf_state_tree, &pf_statetbl[MAXCPU], skey);
1170 if (sk == NULL) {
1171 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
1172 return (NULL);
1174 globalstl = 1;
1176 if (dir == PF_OUT && m->m_pkthdr.pf.statekey) {
1177 ((struct pf_state_key *)
1178 m->m_pkthdr.pf.statekey)->reverse = sk;
1179 sk->reverse = m->m_pkthdr.pf.statekey;
1182 if (dir == PF_OUT)
1183 m->m_pkthdr.pf.statekey = NULL;
1185 /* list is sorted, if-bound states before floating ones */
1186 TAILQ_FOREACH(si, &sk->states, entry) {
1187 if ((si->s->kif == pfi_all || si->s->kif == kif) &&
1188 sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
1189 si->s->key[PF_SK_STACK])) {
1190 break;
1195 * Extract state before potentially releasing the global statetbl
1196 * lock. Ignore the state if the create is still in-progress as
1197 * it can be deleted out from under us by the owning localized cpu.
1198 * However, if CREATEINPROG is not set, state can only be deleted
1199 * by the purge thread which we are protected from via our shared
1200 * pf_token.
1202 if (si) {
1203 s = si->s;
1204 if (s && (s->state_flags & PFSTATE_CREATEINPROG))
1205 s = NULL;
1206 } else {
1207 s = NULL;
1209 if (globalstl)
1210 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
1211 return s;
1215 * WARNING! May return a state structure that was localized to another cpu,
1216 * destruction is typically protected by the callers pf_token.
1218 struct pf_state *
1219 pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
1221 struct pf_state_key *skey = (void *)key;
1222 struct pf_state_key *sk;
1223 struct pf_state_item *si, *ret = NULL;
1224 struct pf_state *s;
1225 int cpu = mycpu->gd_cpuid;
1226 int globalstl = 0;
1228 pf_status.fcounters[FCNT_STATE_SEARCH]++;
1230 sk = RB_FIND(pf_state_tree, &pf_statetbl[cpu], skey);
1231 if (sk == NULL) {
1232 lockmgr(&pf_global_statetbl_lock, LK_SHARED);
1233 sk = RB_FIND(pf_state_tree, &pf_statetbl[MAXCPU], skey);
1234 globalstl = 1;
1236 if (sk != NULL) {
1237 TAILQ_FOREACH(si, &sk->states, entry)
1238 if (dir == PF_INOUT ||
1239 (sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
1240 si->s->key[PF_SK_STACK]))) {
1241 if (more == NULL) {
1242 ret = si;
1243 break;
1245 if (ret)
1246 (*more)++;
1247 else
1248 ret = si;
1253 * Extract state before potentially releasing the global statetbl
1254 * lock. Ignore the state if the create is still in-progress as
1255 * it can be deleted out from under us by the owning localized cpu.
1256 * However, if CREATEINPROG is not set, state can only be deleted
1257 * by the purge thread which we are protected from via our shared
1258 * pf_token.
1260 if (ret) {
1261 s = ret->s;
1262 if (s && (s->state_flags & PFSTATE_CREATEINPROG))
1263 s = NULL;
1264 } else {
1265 s = NULL;
1267 if (globalstl)
1268 lockmgr(&pf_global_statetbl_lock, LK_RELEASE);
1269 return s;
1272 /* END state table stuff */
1274 void
1275 pf_purge_thread(void *v)
1277 globaldata_t save_gd = mycpu;
1278 int nloops = 0;
1279 int locked = 0;
1280 int nn;
1281 int endingit;
1283 for (;;) {
1284 tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
1286 endingit = pf_end_threads;
1288 for (nn = 0; nn < ncpus; ++nn) {
1289 lwkt_setcpu_self(globaldata_find(nn));
1291 lwkt_gettoken(&pf_token);
1292 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1293 crit_enter();
1296 * process a fraction of the state table every second
1298 if(!pf_purge_expired_states(
1299 1 + (pf_status.states /
1300 pf_default_rule.timeout[
1301 PFTM_INTERVAL]), 0)) {
1302 pf_purge_expired_states(
1303 1 + (pf_status.states /
1304 pf_default_rule.timeout[
1305 PFTM_INTERVAL]), 1);
1309 * purge other expired types every PFTM_INTERVAL
1310 * seconds
1312 if (++nloops >=
1313 pf_default_rule.timeout[PFTM_INTERVAL]) {
1314 pf_purge_expired_fragments();
1315 if (!pf_purge_expired_src_nodes(locked)) {
1316 pf_purge_expired_src_nodes(1);
1318 nloops = 0;
1322 * If terminating the thread, clean everything out
1323 * (on all cpus).
1325 if (endingit) {
1326 pf_purge_expired_states(pf_status.states, 0);
1327 pf_purge_expired_fragments();
1328 pf_purge_expired_src_nodes(1);
1331 crit_exit();
1332 lockmgr(&pf_consistency_lock, LK_RELEASE);
1333 lwkt_reltoken(&pf_token);
1335 lwkt_setcpu_self(save_gd);
1336 if (endingit)
1337 break;
1341 * Thread termination
1343 pf_end_threads++;
1344 wakeup(pf_purge_thread);
1345 kthread_exit();
1348 u_int32_t
1349 pf_state_expires(const struct pf_state *state)
1351 u_int32_t timeout;
1352 u_int32_t start;
1353 u_int32_t end;
1354 u_int32_t states;
1356 /* handle all PFTM_* > PFTM_MAX here */
1357 if (state->timeout == PFTM_PURGE)
1358 return (time_second);
1359 if (state->timeout == PFTM_UNTIL_PACKET)
1360 return (0);
1361 KKASSERT(state->timeout != PFTM_UNLINKED);
1362 KKASSERT(state->timeout < PFTM_MAX);
1363 timeout = state->rule.ptr->timeout[state->timeout];
1364 if (!timeout)
1365 timeout = pf_default_rule.timeout[state->timeout];
1366 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1367 if (start) {
1368 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
1369 states = state->rule.ptr->states_cur;
1370 } else {
1371 start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1372 end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1373 states = pf_status.states;
1375 if (end && states > start && start < end) {
1376 if (states < end)
1377 return (state->expire + timeout * (end - states) /
1378 (end - start));
1379 else
1380 return (time_second);
1382 return (state->expire + timeout);
1386 * (called with exclusive pf_token)
1389 pf_purge_expired_src_nodes(int waslocked)
1391 struct pf_src_node *cur, *next;
1392 int locked = waslocked;
1393 int cpu = mycpu->gd_cpuid;
1395 for (cur = RB_MIN(pf_src_tree, &tree_src_tracking[cpu]);
1396 cur;
1397 cur = next) {
1398 next = RB_NEXT(pf_src_tree, &tree_src_tracking[cpu], cur);
1400 if (cur->states <= 0 && cur->expire <= time_second) {
1401 if (!locked) {
1402 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1403 next = RB_NEXT(pf_src_tree,
1404 &tree_src_tracking[cpu], cur);
1405 locked = 1;
1407 if (cur->rule.ptr != NULL) {
1409 * decrements in rule should be ok, token is
1410 * held exclusively in this code path.
1412 cur->rule.ptr->src_nodes--;
1413 if (cur->rule.ptr->states_cur <= 0 &&
1414 cur->rule.ptr->max_src_nodes <= 0)
1415 pf_rm_rule(NULL, cur->rule.ptr);
1417 RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], cur);
1418 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1419 atomic_add_int(&pf_status.src_nodes, -1);
1420 kfree(cur, M_PFSRCTREEPL);
1423 if (locked && !waslocked)
1424 lockmgr(&pf_consistency_lock, LK_RELEASE);
1425 return(1);
1428 void
1429 pf_src_tree_remove_state(struct pf_state *s)
1431 u_int32_t timeout;
1433 if (s->src_node != NULL) {
1434 if (s->src.tcp_est)
1435 --s->src_node->conn;
1436 if (--s->src_node->states <= 0) {
1437 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1438 if (!timeout) {
1439 timeout =
1440 pf_default_rule.timeout[PFTM_SRC_NODE];
1442 s->src_node->expire = time_second + timeout;
1445 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1446 if (--s->nat_src_node->states <= 0) {
1447 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1448 if (!timeout)
1449 timeout =
1450 pf_default_rule.timeout[PFTM_SRC_NODE];
1451 s->nat_src_node->expire = time_second + timeout;
1454 s->src_node = s->nat_src_node = NULL;
1457 /* callers should be at crit_enter() */
1458 void
1459 pf_unlink_state(struct pf_state *cur)
1461 int cpu = mycpu->gd_cpuid;
1463 if (cur->src.state == PF_TCPS_PROXY_DST) {
1464 /* XXX wire key the right one? */
1465 pf_send_tcp(cur->rule.ptr, cur->key[PF_SK_WIRE]->af,
1466 &cur->key[PF_SK_WIRE]->addr[1],
1467 &cur->key[PF_SK_WIRE]->addr[0],
1468 cur->key[PF_SK_WIRE]->port[1],
1469 cur->key[PF_SK_WIRE]->port[0],
1470 cur->src.seqhi, cur->src.seqlo + 1,
1471 TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1473 RB_REMOVE(pf_state_tree_id, &tree_id[cpu], cur);
1474 if (cur->creatorid == pf_status.hostid)
1475 pfsync_delete_state(cur);
1476 cur->timeout = PFTM_UNLINKED;
1477 pf_src_tree_remove_state(cur);
1478 pf_detach_state(cur);
1481 static struct pf_state *purge_cur[MAXCPU];
1484 * callers should be at crit_enter() and hold pf_consistency_lock exclusively.
1485 * pf_token must also be held exclusively.
1487 void
1488 pf_free_state(struct pf_state *cur)
1490 int cpu = mycpu->gd_cpuid;
1492 KKASSERT(cur->cpuid == cpu);
1494 if (pfsyncif != NULL &&
1495 (pfsyncif->sc_bulk_send_next == cur ||
1496 pfsyncif->sc_bulk_terminator == cur))
1497 return;
1498 KKASSERT(cur->timeout == PFTM_UNLINKED);
1500 * decrements in rule should be ok, token is
1501 * held exclusively in this code path.
1503 if (--cur->rule.ptr->states_cur <= 0 &&
1504 cur->rule.ptr->src_nodes <= 0)
1505 pf_rm_rule(NULL, cur->rule.ptr);
1506 if (cur->nat_rule.ptr != NULL) {
1507 if (--cur->nat_rule.ptr->states_cur <= 0 &&
1508 cur->nat_rule.ptr->src_nodes <= 0) {
1509 pf_rm_rule(NULL, cur->nat_rule.ptr);
1512 if (cur->anchor.ptr != NULL) {
1513 if (--cur->anchor.ptr->states_cur <= 0)
1514 pf_rm_rule(NULL, cur->anchor.ptr);
1516 pf_normalize_tcp_cleanup(cur);
1517 pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
1520 * We may be freeing pf_purge_expired_states()'s saved scan entry,
1521 * adjust it if necessary.
1523 if (purge_cur[cpu] == cur) {
1524 kprintf("PURGE CONFLICT\n");
1525 purge_cur[cpu] = TAILQ_NEXT(purge_cur[cpu], entry_list);
1527 TAILQ_REMOVE(&state_list[cpu], cur, entry_list);
1528 if (cur->tag)
1529 pf_tag_unref(cur->tag);
1530 kfree(cur, M_PFSTATEPL);
1531 pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1532 atomic_add_int(&pf_status.states, -1);
1536 pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1538 struct pf_state *cur;
1539 int locked = waslocked;
1540 int cpu = mycpu->gd_cpuid;
1542 while (maxcheck--) {
1544 * Wrap to start of list when we hit the end
1546 cur = purge_cur[cpu];
1547 if (cur == NULL) {
1548 cur = TAILQ_FIRST(&state_list[cpu]);
1549 if (cur == NULL)
1550 break; /* list empty */
1554 * Setup next (purge_cur) while we process this one. If
1555 * we block and something else deletes purge_cur,
1556 * pf_free_state() will adjust it further ahead.
1558 purge_cur[cpu] = TAILQ_NEXT(cur, entry_list);
1560 if (cur->timeout == PFTM_UNLINKED) {
1561 /* free unlinked state */
1562 if (! locked) {
1563 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1564 locked = 1;
1566 pf_free_state(cur);
1567 } else if (pf_state_expires(cur) <= time_second) {
1568 /* unlink and free expired state */
1569 pf_unlink_state(cur);
1570 if (! locked) {
1571 if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1572 return (0);
1573 locked = 1;
1575 pf_free_state(cur);
1579 if (locked)
1580 lockmgr(&pf_consistency_lock, LK_RELEASE);
1581 return (1);
1585 pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1587 if (aw->type != PF_ADDR_TABLE)
1588 return (0);
1589 if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1590 return (1);
1591 return (0);
1594 void
1595 pf_tbladdr_remove(struct pf_addr_wrap *aw)
1597 if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1598 return;
1599 pfr_detach_table(aw->p.tbl);
1600 aw->p.tbl = NULL;
1603 void
1604 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1606 struct pfr_ktable *kt = aw->p.tbl;
1608 if (aw->type != PF_ADDR_TABLE || kt == NULL)
1609 return;
1610 if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1611 kt = kt->pfrkt_root;
1612 aw->p.tbl = NULL;
1613 aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1614 kt->pfrkt_cnt : -1;
1617 void
1618 pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1620 switch (af) {
1621 #ifdef INET
1622 case AF_INET: {
1623 u_int32_t a = ntohl(addr->addr32[0]);
1624 kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
1625 (a>>8)&255, a&255);
1626 if (p) {
1627 p = ntohs(p);
1628 kprintf(":%u", p);
1630 break;
1632 #endif /* INET */
1633 #ifdef INET6
1634 case AF_INET6: {
1635 u_int16_t b;
1636 u_int8_t i, curstart = 255, curend = 0,
1637 maxstart = 0, maxend = 0;
1638 for (i = 0; i < 8; i++) {
1639 if (!addr->addr16[i]) {
1640 if (curstart == 255)
1641 curstart = i;
1642 else
1643 curend = i;
1644 } else {
1645 if (curstart) {
1646 if ((curend - curstart) >
1647 (maxend - maxstart)) {
1648 maxstart = curstart;
1649 maxend = curend;
1650 curstart = 255;
1655 for (i = 0; i < 8; i++) {
1656 if (i >= maxstart && i <= maxend) {
1657 if (maxend != 7) {
1658 if (i == maxstart)
1659 kprintf(":");
1660 } else {
1661 if (i == maxend)
1662 kprintf(":");
1664 } else {
1665 b = ntohs(addr->addr16[i]);
1666 kprintf("%x", b);
1667 if (i < 7)
1668 kprintf(":");
1671 if (p) {
1672 p = ntohs(p);
1673 kprintf("[%u]", p);
1675 break;
1677 #endif /* INET6 */
1681 void
1682 pf_print_state(struct pf_state *s)
1684 pf_print_state_parts(s, NULL, NULL);
1687 void
1688 pf_print_state_parts(struct pf_state *s,
1689 struct pf_state_key *skwp, struct pf_state_key *sksp)
1691 struct pf_state_key *skw, *sks;
1692 u_int8_t proto, dir;
1694 /* Do our best to fill these, but they're skipped if NULL */
1695 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1696 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1697 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1698 dir = s ? s->direction : 0;
1700 switch (proto) {
1701 case IPPROTO_TCP:
1702 kprintf("TCP ");
1703 break;
1704 case IPPROTO_UDP:
1705 kprintf("UDP ");
1706 break;
1707 case IPPROTO_ICMP:
1708 kprintf("ICMP ");
1709 break;
1710 case IPPROTO_ICMPV6:
1711 kprintf("ICMPV6 ");
1712 break;
1713 default:
1714 kprintf("%u ", skw->proto);
1715 break;
1717 switch (dir) {
1718 case PF_IN:
1719 kprintf(" in");
1720 break;
1721 case PF_OUT:
1722 kprintf(" out");
1723 break;
1725 if (skw) {
1726 kprintf(" wire: ");
1727 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1728 kprintf(" ");
1729 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1731 if (sks) {
1732 kprintf(" stack: ");
1733 if (sks != skw) {
1734 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1735 kprintf(" ");
1736 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1737 } else
1738 kprintf("-");
1740 if (s) {
1741 if (proto == IPPROTO_TCP) {
1742 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1743 s->src.seqlo, s->src.seqhi,
1744 s->src.max_win, s->src.seqdiff);
1745 if (s->src.wscale && s->dst.wscale)
1746 kprintf(" wscale=%u",
1747 s->src.wscale & PF_WSCALE_MASK);
1748 kprintf("]");
1749 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1750 s->dst.seqlo, s->dst.seqhi,
1751 s->dst.max_win, s->dst.seqdiff);
1752 if (s->src.wscale && s->dst.wscale)
1753 kprintf(" wscale=%u",
1754 s->dst.wscale & PF_WSCALE_MASK);
1755 kprintf("]");
1757 kprintf(" %u:%u", s->src.state, s->dst.state);
1761 void
1762 pf_print_flags(u_int8_t f)
1764 if (f)
1765 kprintf(" ");
1766 if (f & TH_FIN)
1767 kprintf("F");
1768 if (f & TH_SYN)
1769 kprintf("S");
1770 if (f & TH_RST)
1771 kprintf("R");
1772 if (f & TH_PUSH)
1773 kprintf("P");
1774 if (f & TH_ACK)
1775 kprintf("A");
1776 if (f & TH_URG)
1777 kprintf("U");
1778 if (f & TH_ECE)
1779 kprintf("E");
1780 if (f & TH_CWR)
1781 kprintf("W");
1784 #define PF_SET_SKIP_STEPS(i) \
1785 do { \
1786 while (head[i] != cur) { \
1787 head[i]->skip[i].ptr = cur; \
1788 head[i] = TAILQ_NEXT(head[i], entries); \
1790 } while (0)
1792 void
1793 pf_calc_skip_steps(struct pf_rulequeue *rules)
1795 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1796 int i;
1798 cur = TAILQ_FIRST(rules);
1799 prev = cur;
1800 for (i = 0; i < PF_SKIP_COUNT; ++i)
1801 head[i] = cur;
1802 while (cur != NULL) {
1804 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1805 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1806 if (cur->direction != prev->direction)
1807 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1808 if (cur->af != prev->af)
1809 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1810 if (cur->proto != prev->proto)
1811 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
1812 if (cur->src.neg != prev->src.neg ||
1813 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1814 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1815 if (cur->src.port[0] != prev->src.port[0] ||
1816 cur->src.port[1] != prev->src.port[1] ||
1817 cur->src.port_op != prev->src.port_op)
1818 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
1819 if (cur->dst.neg != prev->dst.neg ||
1820 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1821 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1822 if (cur->dst.port[0] != prev->dst.port[0] ||
1823 cur->dst.port[1] != prev->dst.port[1] ||
1824 cur->dst.port_op != prev->dst.port_op)
1825 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1827 prev = cur;
1828 cur = TAILQ_NEXT(cur, entries);
1830 for (i = 0; i < PF_SKIP_COUNT; ++i)
1831 PF_SET_SKIP_STEPS(i);
1835 pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1837 if (aw1->type != aw2->type)
1838 return (1);
1839 switch (aw1->type) {
1840 case PF_ADDR_ADDRMASK:
1841 case PF_ADDR_RANGE:
1842 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1843 return (1);
1844 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1845 return (1);
1846 return (0);
1847 case PF_ADDR_DYNIFTL:
1848 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1849 case PF_ADDR_NOROUTE:
1850 case PF_ADDR_URPFFAILED:
1851 return (0);
1852 case PF_ADDR_TABLE:
1853 return (aw1->p.tbl != aw2->p.tbl);
1854 case PF_ADDR_RTLABEL:
1855 return (aw1->v.rtlabel != aw2->v.rtlabel);
1856 default:
1857 kprintf("invalid address type: %d\n", aw1->type);
1858 return (1);
1862 u_int16_t
1863 pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1865 u_int32_t l;
1867 if (udp && !cksum)
1868 return (0x0000);
1869 l = cksum + old - new;
1870 l = (l >> 16) + (l & 65535);
1871 l = l & 65535;
1872 if (udp && !l)
1873 return (0xFFFF);
1874 return (l);
1877 void
1878 pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1879 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1881 struct pf_addr ao;
1882 u_int16_t po = *p;
1884 PF_ACPY(&ao, a, af);
1885 PF_ACPY(a, an, af);
1887 *p = pn;
1889 switch (af) {
1890 #ifdef INET
1891 case AF_INET:
1892 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1893 ao.addr16[0], an->addr16[0], 0),
1894 ao.addr16[1], an->addr16[1], 0);
1895 *p = pn;
1896 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1897 ao.addr16[0], an->addr16[0], u),
1898 ao.addr16[1], an->addr16[1], u),
1899 po, pn, u);
1900 break;
1901 #endif /* INET */
1902 #ifdef INET6
1903 case AF_INET6:
1904 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1905 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1906 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1907 ao.addr16[0], an->addr16[0], u),
1908 ao.addr16[1], an->addr16[1], u),
1909 ao.addr16[2], an->addr16[2], u),
1910 ao.addr16[3], an->addr16[3], u),
1911 ao.addr16[4], an->addr16[4], u),
1912 ao.addr16[5], an->addr16[5], u),
1913 ao.addr16[6], an->addr16[6], u),
1914 ao.addr16[7], an->addr16[7], u),
1915 po, pn, u);
1916 break;
1917 #endif /* INET6 */
1922 /* Changes a u_int32_t. Uses a void * so there are no align restrictions */
1923 void
1924 pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1926 u_int32_t ao;
1928 memcpy(&ao, a, sizeof(ao));
1929 memcpy(a, &an, sizeof(u_int32_t));
1930 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1931 ao % 65536, an % 65536, u);
1934 #ifdef INET6
1935 void
1936 pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1938 struct pf_addr ao;
1940 PF_ACPY(&ao, a, AF_INET6);
1941 PF_ACPY(a, an, AF_INET6);
1943 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1944 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1945 pf_cksum_fixup(pf_cksum_fixup(*c,
1946 ao.addr16[0], an->addr16[0], u),
1947 ao.addr16[1], an->addr16[1], u),
1948 ao.addr16[2], an->addr16[2], u),
1949 ao.addr16[3], an->addr16[3], u),
1950 ao.addr16[4], an->addr16[4], u),
1951 ao.addr16[5], an->addr16[5], u),
1952 ao.addr16[6], an->addr16[6], u),
1953 ao.addr16[7], an->addr16[7], u);
1955 #endif /* INET6 */
1957 void
1958 pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1959 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1960 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1962 struct pf_addr oia, ooa;
1964 PF_ACPY(&oia, ia, af);
1965 if (oa)
1966 PF_ACPY(&ooa, oa, af);
1968 /* Change inner protocol port, fix inner protocol checksum. */
1969 if (ip != NULL) {
1970 u_int16_t oip = *ip;
1971 u_int32_t opc = 0;
1973 if (pc != NULL)
1974 opc = *pc;
1975 *ip = np;
1976 if (pc != NULL)
1977 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
1978 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1979 if (pc != NULL)
1980 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1982 /* Change inner ip address, fix inner ip and icmp checksums. */
1983 PF_ACPY(ia, na, af);
1984 switch (af) {
1985 #ifdef INET
1986 case AF_INET: {
1987 u_int32_t oh2c = *h2c;
1989 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1990 oia.addr16[0], ia->addr16[0], 0),
1991 oia.addr16[1], ia->addr16[1], 0);
1992 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1993 oia.addr16[0], ia->addr16[0], 0),
1994 oia.addr16[1], ia->addr16[1], 0);
1995 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1996 break;
1998 #endif /* INET */
1999 #ifdef INET6
2000 case AF_INET6:
2001 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2002 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2003 pf_cksum_fixup(pf_cksum_fixup(*ic,
2004 oia.addr16[0], ia->addr16[0], u),
2005 oia.addr16[1], ia->addr16[1], u),
2006 oia.addr16[2], ia->addr16[2], u),
2007 oia.addr16[3], ia->addr16[3], u),
2008 oia.addr16[4], ia->addr16[4], u),
2009 oia.addr16[5], ia->addr16[5], u),
2010 oia.addr16[6], ia->addr16[6], u),
2011 oia.addr16[7], ia->addr16[7], u);
2012 break;
2013 #endif /* INET6 */
2015 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
2016 if (oa) {
2017 PF_ACPY(oa, na, af);
2018 switch (af) {
2019 #ifdef INET
2020 case AF_INET:
2021 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
2022 ooa.addr16[0], oa->addr16[0], 0),
2023 ooa.addr16[1], oa->addr16[1], 0);
2024 break;
2025 #endif /* INET */
2026 #ifdef INET6
2027 case AF_INET6:
2028 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2029 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
2030 pf_cksum_fixup(pf_cksum_fixup(*ic,
2031 ooa.addr16[0], oa->addr16[0], u),
2032 ooa.addr16[1], oa->addr16[1], u),
2033 ooa.addr16[2], oa->addr16[2], u),
2034 ooa.addr16[3], oa->addr16[3], u),
2035 ooa.addr16[4], oa->addr16[4], u),
2036 ooa.addr16[5], oa->addr16[5], u),
2037 ooa.addr16[6], oa->addr16[6], u),
2038 ooa.addr16[7], oa->addr16[7], u);
2039 break;
2040 #endif /* INET6 */
2047 * Need to modulate the sequence numbers in the TCP SACK option
2048 * (credits to Krzysztof Pfaff for report and patch)
2051 pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
2052 struct tcphdr *th, struct pf_state_peer *dst)
2054 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
2055 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
2056 int copyback = 0, i, olen;
2057 struct raw_sackblock sack;
2059 #define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
2060 if (hlen < TCPOLEN_SACKLEN ||
2061 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
2062 return 0;
2064 while (hlen >= TCPOLEN_SACKLEN) {
2065 olen = opt[1];
2066 switch (*opt) {
2067 case TCPOPT_EOL: /* FALLTHROUGH */
2068 case TCPOPT_NOP:
2069 opt++;
2070 hlen--;
2071 break;
2072 case TCPOPT_SACK:
2073 if (olen > hlen)
2074 olen = hlen;
2075 if (olen >= TCPOLEN_SACKLEN) {
2076 for (i = 2; i + TCPOLEN_SACK <= olen;
2077 i += TCPOLEN_SACK) {
2078 memcpy(&sack, &opt[i], sizeof(sack));
2079 pf_change_a(&sack.rblk_start, &th->th_sum,
2080 htonl(ntohl(sack.rblk_start) -
2081 dst->seqdiff), 0);
2082 pf_change_a(&sack.rblk_end, &th->th_sum,
2083 htonl(ntohl(sack.rblk_end) -
2084 dst->seqdiff), 0);
2085 memcpy(&opt[i], &sack, sizeof(sack));
2087 copyback = 1;
2089 /* FALLTHROUGH */
2090 default:
2091 if (olen < 2)
2092 olen = 2;
2093 hlen -= olen;
2094 opt += olen;
2098 if (copyback)
2099 m_copyback(m, off + sizeof(*th), thoptlen, opts);
2100 return (copyback);
2103 void
2104 pf_send_tcp(const struct pf_rule *r, sa_family_t af,
2105 const struct pf_addr *saddr, const struct pf_addr *daddr,
2106 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
2107 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
2108 u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
2110 struct mbuf *m;
2111 int len = 0, tlen;
2112 #ifdef INET
2113 struct ip *h = NULL;
2114 #endif /* INET */
2115 #ifdef INET6
2116 struct ip6_hdr *h6 = NULL;
2117 #endif /* INET6 */
2118 struct tcphdr *th = NULL;
2119 char *opt;
2121 ASSERT_LWKT_TOKEN_HELD(&pf_token);
2123 /* maximum segment size tcp option */
2124 tlen = sizeof(struct tcphdr);
2125 if (mss)
2126 tlen += 4;
2128 switch (af) {
2129 #ifdef INET
2130 case AF_INET:
2131 len = sizeof(struct ip) + tlen;
2132 break;
2133 #endif /* INET */
2134 #ifdef INET6
2135 case AF_INET6:
2136 len = sizeof(struct ip6_hdr) + tlen;
2137 break;
2138 #endif /* INET6 */
2142 * Create outgoing mbuf.
2144 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
2145 * so make sure pf.flags is clear.
2147 m = m_gethdr(M_NOWAIT, MT_HEADER);
2148 if (m == NULL) {
2149 return;
2151 if (tag)
2152 m->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
2153 m->m_pkthdr.pf.flags = 0;
2154 m->m_pkthdr.pf.tag = rtag;
2155 /* XXX Recheck when upgrading to > 4.4 */
2156 m->m_pkthdr.pf.statekey = NULL;
2157 if (r != NULL && r->rtableid >= 0)
2158 m->m_pkthdr.pf.rtableid = r->rtableid;
2160 #ifdef ALTQ
2161 if (r != NULL && r->qid) {
2162 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
2163 m->m_pkthdr.pf.qid = r->qid;
2164 m->m_pkthdr.pf.ecn_af = af;
2165 m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
2167 #endif /* ALTQ */
2168 m->m_data += max_linkhdr;
2169 m->m_pkthdr.len = m->m_len = len;
2170 m->m_pkthdr.rcvif = NULL;
2171 bzero(m->m_data, len);
2172 switch (af) {
2173 #ifdef INET
2174 case AF_INET:
2175 h = mtod(m, struct ip *);
2177 /* IP header fields included in the TCP checksum */
2178 h->ip_p = IPPROTO_TCP;
2179 h->ip_len = tlen;
2180 h->ip_src.s_addr = saddr->v4.s_addr;
2181 h->ip_dst.s_addr = daddr->v4.s_addr;
2183 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
2184 break;
2185 #endif /* INET */
2186 #ifdef INET6
2187 case AF_INET6:
2188 h6 = mtod(m, struct ip6_hdr *);
2190 /* IP header fields included in the TCP checksum */
2191 h6->ip6_nxt = IPPROTO_TCP;
2192 h6->ip6_plen = htons(tlen);
2193 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
2194 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
2196 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
2197 break;
2198 #endif /* INET6 */
2201 /* TCP header */
2202 th->th_sport = sport;
2203 th->th_dport = dport;
2204 th->th_seq = htonl(seq);
2205 th->th_ack = htonl(ack);
2206 th->th_off = tlen >> 2;
2207 th->th_flags = flags;
2208 th->th_win = htons(win);
2210 if (mss) {
2211 opt = (char *)(th + 1);
2212 opt[0] = TCPOPT_MAXSEG;
2213 opt[1] = 4;
2214 mss = htons(mss);
2215 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
2218 switch (af) {
2219 #ifdef INET
2220 case AF_INET:
2221 /* TCP checksum */
2222 th->th_sum = in_cksum(m, len);
2224 /* Finish the IP header */
2225 h->ip_v = 4;
2226 h->ip_hl = sizeof(*h) >> 2;
2227 h->ip_tos = IPTOS_LOWDELAY;
2228 h->ip_len = len;
2229 h->ip_off = path_mtu_discovery ? IP_DF : 0;
2230 h->ip_ttl = ttl ? ttl : ip_defttl;
2231 h->ip_sum = 0;
2232 if (eh == NULL) {
2233 lwkt_reltoken(&pf_token);
2234 ip_output(m, NULL, NULL, 0, NULL, NULL);
2235 lwkt_gettoken(&pf_token);
2236 } else {
2237 struct route ro;
2238 struct rtentry rt;
2239 struct ether_header *e = (void *)ro.ro_dst.sa_data;
2241 if (ifp == NULL) {
2242 m_freem(m);
2243 return;
2245 rt.rt_ifp = ifp;
2246 ro.ro_rt = &rt;
2247 ro.ro_dst.sa_len = sizeof(ro.ro_dst);
2248 ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
2249 bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
2250 bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
2251 e->ether_type = eh->ether_type;
2252 /* XXX_IMPORT: later */
2253 lwkt_reltoken(&pf_token);
2254 ip_output(m, NULL, &ro, 0, NULL, NULL);
2255 lwkt_gettoken(&pf_token);
2257 break;
2258 #endif /* INET */
2259 #ifdef INET6
2260 case AF_INET6:
2261 /* TCP checksum */
2262 th->th_sum = in6_cksum(m, IPPROTO_TCP,
2263 sizeof(struct ip6_hdr), tlen);
2265 h6->ip6_vfc |= IPV6_VERSION;
2266 h6->ip6_hlim = IPV6_DEFHLIM;
2268 lwkt_reltoken(&pf_token);
2269 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2270 lwkt_gettoken(&pf_token);
2271 break;
2272 #endif /* INET6 */
2276 void
2277 pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
2278 struct pf_rule *r)
2280 struct mbuf *m0;
2283 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
2284 * so make sure pf.flags is clear.
2286 if ((m0 = m_copy(m, 0, M_COPYALL)) == NULL)
2287 return;
2289 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
2290 m0->m_pkthdr.pf.flags = 0;
2291 /* XXX Re-Check when Upgrading to > 4.4 */
2292 m0->m_pkthdr.pf.statekey = NULL;
2294 if (r->rtableid >= 0)
2295 m0->m_pkthdr.pf.rtableid = r->rtableid;
2297 #ifdef ALTQ
2298 if (r->qid) {
2299 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
2300 m0->m_pkthdr.pf.qid = r->qid;
2301 m0->m_pkthdr.pf.ecn_af = af;
2302 m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
2304 #endif /* ALTQ */
2306 switch (af) {
2307 #ifdef INET
2308 case AF_INET:
2309 icmp_error(m0, type, code, 0, 0);
2310 break;
2311 #endif /* INET */
2312 #ifdef INET6
2313 case AF_INET6:
2314 icmp6_error(m0, type, code, 0);
2315 break;
2316 #endif /* INET6 */
2321 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
2322 * If n is 0, they match if they are equal. If n is != 0, they match if they
2323 * are different.
2326 pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
2327 struct pf_addr *b, sa_family_t af)
2329 int match = 0;
2331 switch (af) {
2332 #ifdef INET
2333 case AF_INET:
2334 if ((a->addr32[0] & m->addr32[0]) ==
2335 (b->addr32[0] & m->addr32[0]))
2336 match++;
2337 break;
2338 #endif /* INET */
2339 #ifdef INET6
2340 case AF_INET6:
2341 if (((a->addr32[0] & m->addr32[0]) ==
2342 (b->addr32[0] & m->addr32[0])) &&
2343 ((a->addr32[1] & m->addr32[1]) ==
2344 (b->addr32[1] & m->addr32[1])) &&
2345 ((a->addr32[2] & m->addr32[2]) ==
2346 (b->addr32[2] & m->addr32[2])) &&
2347 ((a->addr32[3] & m->addr32[3]) ==
2348 (b->addr32[3] & m->addr32[3])))
2349 match++;
2350 break;
2351 #endif /* INET6 */
2353 if (match) {
2354 if (n)
2355 return (0);
2356 else
2357 return (1);
2358 } else {
2359 if (n)
2360 return (1);
2361 else
2362 return (0);
2367 * Return 1 if b <= a <= e, otherwise return 0.
2370 pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
2371 struct pf_addr *a, sa_family_t af)
2373 switch (af) {
2374 #ifdef INET
2375 case AF_INET:
2376 if ((a->addr32[0] < b->addr32[0]) ||
2377 (a->addr32[0] > e->addr32[0]))
2378 return (0);
2379 break;
2380 #endif /* INET */
2381 #ifdef INET6
2382 case AF_INET6: {
2383 int i;
2385 /* check a >= b */
2386 for (i = 0; i < 4; ++i)
2387 if (a->addr32[i] > b->addr32[i])
2388 break;
2389 else if (a->addr32[i] < b->addr32[i])
2390 return (0);
2391 /* check a <= e */
2392 for (i = 0; i < 4; ++i)
2393 if (a->addr32[i] < e->addr32[i])
2394 break;
2395 else if (a->addr32[i] > e->addr32[i])
2396 return (0);
2397 break;
2399 #endif /* INET6 */
2401 return (1);
2405 pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2407 switch (op) {
2408 case PF_OP_IRG:
2409 return ((p > a1) && (p < a2));
2410 case PF_OP_XRG:
2411 return ((p < a1) || (p > a2));
2412 case PF_OP_RRG:
2413 return ((p >= a1) && (p <= a2));
2414 case PF_OP_EQ:
2415 return (p == a1);
2416 case PF_OP_NE:
2417 return (p != a1);
2418 case PF_OP_LT:
2419 return (p < a1);
2420 case PF_OP_LE:
2421 return (p <= a1);
2422 case PF_OP_GT:
2423 return (p > a1);
2424 case PF_OP_GE:
2425 return (p >= a1);
2427 return (0); /* never reached */
2431 pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2433 a1 = ntohs(a1);
2434 a2 = ntohs(a2);
2435 p = ntohs(p);
2436 return (pf_match(op, a1, a2, p));
2440 pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2442 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2443 return (0);
2444 return (pf_match(op, a1, a2, u));
2448 pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2450 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2451 return (0);
2452 return (pf_match(op, a1, a2, g));
2456 pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
2458 if (*tag == -1)
2459 *tag = m->m_pkthdr.pf.tag;
2461 return ((!r->match_tag_not && r->match_tag == *tag) ||
2462 (r->match_tag_not && r->match_tag != *tag));
2466 pf_tag_packet(struct mbuf *m, int tag, int rtableid)
2468 if (tag <= 0 && rtableid < 0)
2469 return (0);
2471 if (tag > 0)
2472 m->m_pkthdr.pf.tag = tag;
2473 if (rtableid >= 0)
2474 m->m_pkthdr.pf.rtableid = rtableid;
2476 return (0);
2479 void
2480 pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
2481 struct pf_rule **r, struct pf_rule **a, int *match)
2483 struct pf_anchor_stackframe *f;
2485 (*r)->anchor->match = 0;
2486 if (match)
2487 *match = 0;
2488 if (*depth >= NELEM(pf_anchor_stack)) {
2489 kprintf("pf_step_into_anchor: stack overflow\n");
2490 *r = TAILQ_NEXT(*r, entries);
2491 return;
2492 } else if (*depth == 0 && a != NULL)
2493 *a = *r;
2494 f = pf_anchor_stack + (*depth)++;
2495 f->rs = *rs;
2496 f->r = *r;
2497 if ((*r)->anchor_wildcard) {
2498 f->parent = &(*r)->anchor->children;
2499 if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
2500 NULL) {
2501 *r = NULL;
2502 return;
2504 *rs = &f->child->ruleset;
2505 } else {
2506 f->parent = NULL;
2507 f->child = NULL;
2508 *rs = &(*r)->anchor->ruleset;
2510 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2514 pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
2515 struct pf_rule **r, struct pf_rule **a, int *match)
2517 struct pf_anchor_stackframe *f;
2518 int quick = 0;
2520 do {
2521 if (*depth <= 0)
2522 break;
2523 f = pf_anchor_stack + *depth - 1;
2524 if (f->parent != NULL && f->child != NULL) {
2525 if (f->child->match ||
2526 (match != NULL && *match)) {
2527 f->r->anchor->match = 1;
2528 *match = 0;
2530 f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
2531 if (f->child != NULL) {
2532 *rs = &f->child->ruleset;
2533 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2534 if (*r == NULL)
2535 continue;
2536 else
2537 break;
2540 (*depth)--;
2541 if (*depth == 0 && a != NULL)
2542 *a = NULL;
2543 *rs = f->rs;
2544 if (f->r->anchor->match || (match != NULL && *match))
2545 quick = f->r->quick;
2546 *r = TAILQ_NEXT(f->r, entries);
2547 } while (*r == NULL);
2549 return (quick);
2552 #ifdef INET6
2553 void
2554 pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2555 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2557 switch (af) {
2558 #ifdef INET
2559 case AF_INET:
2560 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2561 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2562 break;
2563 #endif /* INET */
2564 case AF_INET6:
2565 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2566 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2567 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2568 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2569 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2570 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2571 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2572 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2573 break;
2577 void
2578 pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2580 switch (af) {
2581 #ifdef INET
2582 case AF_INET:
2583 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2584 break;
2585 #endif /* INET */
2586 case AF_INET6:
2587 if (addr->addr32[3] == 0xffffffff) {
2588 addr->addr32[3] = 0;
2589 if (addr->addr32[2] == 0xffffffff) {
2590 addr->addr32[2] = 0;
2591 if (addr->addr32[1] == 0xffffffff) {
2592 addr->addr32[1] = 0;
2593 addr->addr32[0] =
2594 htonl(ntohl(addr->addr32[0]) + 1);
2595 } else
2596 addr->addr32[1] =
2597 htonl(ntohl(addr->addr32[1]) + 1);
2598 } else
2599 addr->addr32[2] =
2600 htonl(ntohl(addr->addr32[2]) + 1);
2601 } else
2602 addr->addr32[3] =
2603 htonl(ntohl(addr->addr32[3]) + 1);
2604 break;
2607 #endif /* INET6 */
2609 #define mix(a,b,c) \
2610 do { \
2611 a -= b; a -= c; a ^= (c >> 13); \
2612 b -= c; b -= a; b ^= (a << 8); \
2613 c -= a; c -= b; c ^= (b >> 13); \
2614 a -= b; a -= c; a ^= (c >> 12); \
2615 b -= c; b -= a; b ^= (a << 16); \
2616 c -= a; c -= b; c ^= (b >> 5); \
2617 a -= b; a -= c; a ^= (c >> 3); \
2618 b -= c; b -= a; b ^= (a << 10); \
2619 c -= a; c -= b; c ^= (b >> 15); \
2620 } while (0)
2623 * hash function based on bridge_hash in if_bridge.c
2625 void
2626 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2627 struct pf_poolhashkey *key, sa_family_t af)
2629 u_int32_t a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2631 switch (af) {
2632 #ifdef INET
2633 case AF_INET:
2634 a += inaddr->addr32[0];
2635 b += key->key32[1];
2636 mix(a, b, c);
2637 hash->addr32[0] = c + key->key32[2];
2638 break;
2639 #endif /* INET */
2640 #ifdef INET6
2641 case AF_INET6:
2642 a += inaddr->addr32[0];
2643 b += inaddr->addr32[2];
2644 mix(a, b, c);
2645 hash->addr32[0] = c;
2646 a += inaddr->addr32[1];
2647 b += inaddr->addr32[3];
2648 c += key->key32[1];
2649 mix(a, b, c);
2650 hash->addr32[1] = c;
2651 a += inaddr->addr32[2];
2652 b += inaddr->addr32[1];
2653 c += key->key32[2];
2654 mix(a, b, c);
2655 hash->addr32[2] = c;
2656 a += inaddr->addr32[3];
2657 b += inaddr->addr32[0];
2658 c += key->key32[3];
2659 mix(a, b, c);
2660 hash->addr32[3] = c;
2661 break;
2662 #endif /* INET6 */
2667 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2668 struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2670 unsigned char hash[16];
2671 struct pf_pool *rpool = &r->rpool;
2672 struct pf_pooladdr *acur = rpool->cur;
2673 struct pf_pooladdr *cur;
2674 struct pf_addr *raddr;
2675 struct pf_addr *rmask;
2676 struct pf_addr counter;
2677 struct pf_src_node k;
2678 int cpu = mycpu->gd_cpuid;
2679 int tblidx;
2681 bzero(hash, sizeof(hash)); /* avoid gcc warnings */
2684 * NOTE! rpool->cur and rpool->tblidx can be iterators and thus
2685 * may represent a SMP race due to the shared nature of the
2686 * rpool structure. We allow the race and ensure that updates
2687 * do not create a fatal condition.
2689 cpu_ccfence();
2690 cur = acur;
2691 raddr = &cur->addr.v.a.addr;
2692 rmask = &cur->addr.v.a.mask;
2694 if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2695 (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2696 k.af = af;
2697 PF_ACPY(&k.addr, saddr, af);
2698 if (r->rule_flag & PFRULE_RULESRCTRACK ||
2699 r->rpool.opts & PF_POOL_STICKYADDR)
2700 k.rule.ptr = r;
2701 else
2702 k.rule.ptr = NULL;
2703 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2704 *sn = RB_FIND(pf_src_tree, &tree_src_tracking[cpu], &k);
2705 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2706 PF_ACPY(naddr, &(*sn)->raddr, af);
2707 if (pf_status.debug >= PF_DEBUG_MISC) {
2708 kprintf("pf_map_addr: src tracking maps ");
2709 pf_print_host(&k.addr, 0, af);
2710 kprintf(" to ");
2711 pf_print_host(naddr, 0, af);
2712 kprintf("\n");
2714 return (0);
2718 if (cur->addr.type == PF_ADDR_NOROUTE)
2719 return (1);
2720 if (cur->addr.type == PF_ADDR_DYNIFTL) {
2721 switch (af) {
2722 #ifdef INET
2723 case AF_INET:
2724 if (cur->addr.p.dyn->pfid_acnt4 < 1 &&
2725 (rpool->opts & PF_POOL_TYPEMASK) !=
2726 PF_POOL_ROUNDROBIN)
2727 return (1);
2728 raddr = &cur->addr.p.dyn->pfid_addr4;
2729 rmask = &cur->addr.p.dyn->pfid_mask4;
2730 break;
2731 #endif /* INET */
2732 #ifdef INET6
2733 case AF_INET6:
2734 if (cur->addr.p.dyn->pfid_acnt6 < 1 &&
2735 (rpool->opts & PF_POOL_TYPEMASK) !=
2736 PF_POOL_ROUNDROBIN)
2737 return (1);
2738 raddr = &cur->addr.p.dyn->pfid_addr6;
2739 rmask = &cur->addr.p.dyn->pfid_mask6;
2740 break;
2741 #endif /* INET6 */
2743 } else if (cur->addr.type == PF_ADDR_TABLE) {
2744 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2745 return (1); /* unsupported */
2746 } else {
2747 raddr = &cur->addr.v.a.addr;
2748 rmask = &cur->addr.v.a.mask;
2751 switch (rpool->opts & PF_POOL_TYPEMASK) {
2752 case PF_POOL_NONE:
2753 PF_ACPY(naddr, raddr, af);
2754 break;
2755 case PF_POOL_BITMASK:
2756 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2757 break;
2758 case PF_POOL_RANDOM:
2759 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2760 switch (af) {
2761 #ifdef INET
2762 case AF_INET:
2763 counter.addr32[0] = htonl(karc4random());
2764 break;
2765 #endif /* INET */
2766 #ifdef INET6
2767 case AF_INET6:
2768 if (rmask->addr32[3] != 0xffffffff)
2769 counter.addr32[3] =
2770 htonl(karc4random());
2771 else
2772 break;
2773 if (rmask->addr32[2] != 0xffffffff)
2774 counter.addr32[2] =
2775 htonl(karc4random());
2776 else
2777 break;
2778 if (rmask->addr32[1] != 0xffffffff)
2779 counter.addr32[1] =
2780 htonl(karc4random());
2781 else
2782 break;
2783 if (rmask->addr32[0] != 0xffffffff)
2784 counter.addr32[0] =
2785 htonl(karc4random());
2786 break;
2787 #endif /* INET6 */
2789 PF_POOLMASK(naddr, raddr, rmask, &counter, af);
2790 PF_ACPY(init_addr, naddr, af);
2792 } else {
2793 counter = rpool->counter;
2794 cpu_ccfence();
2795 PF_AINC(&counter, af);
2796 PF_POOLMASK(naddr, raddr, rmask, &counter, af);
2797 rpool->counter = counter;
2799 break;
2800 case PF_POOL_SRCHASH:
2801 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2802 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2803 break;
2804 case PF_POOL_ROUNDROBIN:
2805 tblidx = rpool->tblidx;
2806 counter = rpool->counter;
2807 if (cur->addr.type == PF_ADDR_TABLE) {
2808 if (!pfr_pool_get(cur->addr.p.tbl,
2809 &tblidx, &counter,
2810 &raddr, &rmask, af)) {
2811 goto get_addr;
2813 } else if (cur->addr.type == PF_ADDR_DYNIFTL) {
2814 if (!pfr_pool_get(cur->addr.p.dyn->pfid_kt,
2815 &tblidx, &counter,
2816 &raddr, &rmask, af)) {
2817 goto get_addr;
2819 } else if (pf_match_addr(0, raddr, rmask,
2820 &counter, af)) {
2821 goto get_addr;
2824 try_next:
2825 if ((cur = TAILQ_NEXT(cur, entries)) == NULL)
2826 cur = TAILQ_FIRST(&rpool->list);
2827 if (cur->addr.type == PF_ADDR_TABLE) {
2828 tblidx = -1;
2829 if (pfr_pool_get(cur->addr.p.tbl,
2830 &tblidx, &counter,
2831 &raddr, &rmask, af)) {
2832 /* table contains no address of type 'af' */
2833 if (cur != acur)
2834 goto try_next;
2835 return (1);
2837 } else if (cur->addr.type == PF_ADDR_DYNIFTL) {
2838 tblidx = -1;
2839 if (pfr_pool_get(cur->addr.p.dyn->pfid_kt,
2840 &tblidx, &counter,
2841 &raddr, &rmask, af)) {
2842 /* table contains no address of type 'af' */
2843 if (cur != acur)
2844 goto try_next;
2845 return (1);
2847 } else {
2848 raddr = &cur->addr.v.a.addr;
2849 rmask = &cur->addr.v.a.mask;
2850 PF_ACPY(&counter, raddr, af);
2853 get_addr:
2854 rpool->cur = cur;
2855 rpool->tblidx = tblidx;
2856 PF_ACPY(naddr, &counter, af);
2857 if (init_addr != NULL && PF_AZERO(init_addr, af))
2858 PF_ACPY(init_addr, naddr, af);
2859 PF_AINC(&counter, af);
2860 rpool->counter = counter;
2861 break;
2863 if (*sn != NULL)
2864 PF_ACPY(&(*sn)->raddr, naddr, af);
2866 if (pf_status.debug >= PF_DEBUG_MISC &&
2867 (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2868 kprintf("pf_map_addr: selected address ");
2869 pf_print_host(naddr, 0, af);
2870 kprintf("\n");
2873 return (0);
2877 pf_get_sport(struct pf_pdesc *pd, sa_family_t af,
2878 u_int8_t proto, struct pf_rule *r,
2879 struct pf_addr *saddr, struct pf_addr *daddr,
2880 u_int16_t sport, u_int16_t dport,
2881 struct pf_addr *naddr, u_int16_t *nport,
2882 u_int16_t low, u_int16_t high, struct pf_src_node **sn)
2884 struct pf_state_key_cmp key;
2885 struct pf_addr init_addr;
2886 u_int16_t cut;
2887 u_int32_t hash_base = 0;
2888 int do_hash = 0;
2890 bzero(&init_addr, sizeof(init_addr));
2891 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2892 return (1);
2894 if (proto == IPPROTO_ICMP) {
2895 low = 1;
2896 high = 65535;
2899 bzero(&key, sizeof(key));
2900 key.af = af;
2901 key.proto = proto;
2902 key.port[0] = dport;
2903 PF_ACPY(&key.addr[0], daddr, key.af);
2905 do {
2906 PF_ACPY(&key.addr[1], naddr, key.af);
2909 * We want to select a port that calculates to a toeplitz hash
2910 * that masks to the same cpu, otherwise the response may
2911 * not see the new state.
2913 * We can still do this even if the kernel is disregarding
2914 * the hash and vectoring the packets to a specific cpu,
2915 * but it will reduce the number of ports we can use.
2917 switch(af) {
2918 case AF_INET:
2919 if (proto == IPPROTO_TCP) {
2920 do_hash = 1;
2921 hash_base = toeplitz_piecemeal_port(dport) ^
2922 toeplitz_piecemeal_addr(daddr->v4.s_addr) ^
2923 toeplitz_piecemeal_addr(naddr->v4.s_addr);
2925 break;
2926 case AF_INET6:
2927 /* XXX TODO XXX */
2928 default:
2929 /* XXX TODO XXX */
2930 break;
2934 * port search; start random, step;
2935 * similar 2 portloop in in_pcbbind
2937 * WARNING! We try to match such that the kernel will
2938 * dispatch the translated host/port to the same
2939 * cpu, but this might not be possible.
2941 * In the case where the port is fixed, or for the
2942 * UDP case (whos toeplitz does not incorporate the
2943 * port), we set not_cpu_localized which ultimately
2944 * causes the pf_state_tree element
2946 * XXX fixed ports present a problem for cpu localization.
2948 if (!(proto == IPPROTO_TCP ||
2949 proto == IPPROTO_UDP ||
2950 proto == IPPROTO_ICMP)) {
2952 * non-specific protocol, leave port intact.
2954 key.port[1] = sport;
2955 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2956 *nport = sport;
2957 pd->not_cpu_localized = 1;
2958 return (0);
2960 } else if (low == 0 && high == 0) {
2962 * static-port same as originator.
2964 key.port[1] = sport;
2965 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2966 *nport = sport;
2967 pd->not_cpu_localized = 1;
2968 return (0);
2970 } else if (low == high) {
2972 * specific port as specified.
2974 key.port[1] = htons(low);
2975 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
2976 *nport = htons(low);
2977 pd->not_cpu_localized = 1;
2978 return (0);
2980 } else {
2982 * normal dynamic port
2984 u_int16_t tmp;
2986 if (low > high) {
2987 tmp = low;
2988 low = high;
2989 high = tmp;
2991 /* low < high */
2992 cut = htonl(karc4random()) % (1 + high - low) + low;
2993 /* low <= cut <= high */
2994 for (tmp = cut; tmp <= high; ++(tmp)) {
2995 key.port[1] = htons(tmp);
2996 if (do_hash) {
2997 uint32_t hash;
2999 hash = hash_base ^
3000 toeplitz_piecemeal_port(key.port[1]);
3001 if (netisr_hashcpu(hash) != mycpuid)
3002 continue;
3004 if (pf_find_state_all(&key, PF_IN, NULL) ==
3005 NULL && !in_baddynamic(tmp, proto)) {
3006 if (proto == IPPROTO_UDP)
3007 pd->not_cpu_localized = 1;
3008 *nport = htons(tmp);
3009 return (0);
3012 for (tmp = cut - 1; tmp >= low; --(tmp)) {
3013 key.port[1] = htons(tmp);
3014 if (do_hash) {
3015 uint32_t hash;
3017 hash = hash_base ^
3018 toeplitz_piecemeal_port(key.port[1]);
3019 if (netisr_hashcpu(hash) != mycpuid)
3020 continue;
3022 if (pf_find_state_all(&key, PF_IN, NULL) ==
3023 NULL && !in_baddynamic(tmp, proto)) {
3024 if (proto == IPPROTO_UDP)
3025 pd->not_cpu_localized = 1;
3026 *nport = htons(tmp);
3027 return (0);
3033 * Next address
3035 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
3036 case PF_POOL_RANDOM:
3037 case PF_POOL_ROUNDROBIN:
3038 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
3039 return (1);
3040 break;
3041 case PF_POOL_NONE:
3042 case PF_POOL_SRCHASH:
3043 case PF_POOL_BITMASK:
3044 default:
3045 return (1);
3047 } while (! PF_AEQ(&init_addr, naddr, af) );
3048 return (1); /* none available */
3051 struct pf_rule *
3052 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
3053 int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
3054 struct pf_addr *daddr, u_int16_t dport, int rs_num)
3056 struct pf_rule *r, *rm = NULL;
3057 struct pf_ruleset *ruleset = NULL;
3058 int tag = -1;
3059 int rtableid = -1;
3060 int asd = 0;
3062 r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
3063 while (r && rm == NULL) {
3064 struct pf_rule_addr *src = NULL, *dst = NULL;
3065 struct pf_addr_wrap *xdst = NULL;
3066 struct pf_pooladdr *cur;
3068 if (r->action == PF_BINAT && direction == PF_IN) {
3069 src = &r->dst;
3070 cur = r->rpool.cur; /* SMP race possible */
3071 cpu_ccfence();
3072 if (cur)
3073 xdst = &cur->addr;
3074 } else {
3075 src = &r->src;
3076 dst = &r->dst;
3079 r->evaluations++;
3080 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3081 r = r->skip[PF_SKIP_IFP].ptr;
3082 else if (r->direction && r->direction != direction)
3083 r = r->skip[PF_SKIP_DIR].ptr;
3084 else if (r->af && r->af != pd->af)
3085 r = r->skip[PF_SKIP_AF].ptr;
3086 else if (r->proto && r->proto != pd->proto)
3087 r = r->skip[PF_SKIP_PROTO].ptr;
3088 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
3089 src->neg, kif))
3090 r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
3091 PF_SKIP_DST_ADDR].ptr;
3092 else if (src->port_op && !pf_match_port(src->port_op,
3093 src->port[0], src->port[1], sport))
3094 r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
3095 PF_SKIP_DST_PORT].ptr;
3096 else if (dst != NULL &&
3097 PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
3098 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3099 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
3100 0, NULL))
3101 r = TAILQ_NEXT(r, entries);
3102 else if (dst != NULL && dst->port_op &&
3103 !pf_match_port(dst->port_op, dst->port[0],
3104 dst->port[1], dport))
3105 r = r->skip[PF_SKIP_DST_PORT].ptr;
3106 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3107 r = TAILQ_NEXT(r, entries);
3108 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
3109 IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
3110 off, pd->hdr.tcp), r->os_fingerprint)))
3111 r = TAILQ_NEXT(r, entries);
3112 else {
3113 if (r->tag)
3114 tag = r->tag;
3115 if (r->rtableid >= 0)
3116 rtableid = r->rtableid;
3117 if (r->anchor == NULL) {
3118 rm = r;
3119 } else
3120 pf_step_into_anchor(&asd, &ruleset, rs_num,
3121 &r, NULL, NULL);
3123 if (r == NULL)
3124 pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
3125 NULL, NULL);
3127 if (pf_tag_packet(m, tag, rtableid))
3128 return (NULL);
3129 if (rm != NULL && (rm->action == PF_NONAT ||
3130 rm->action == PF_NORDR || rm->action == PF_NOBINAT))
3131 return (NULL);
3132 return (rm);
3135 struct pf_rule *
3136 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
3137 struct pfi_kif *kif, struct pf_src_node **sn,
3138 struct pf_state_key **skw, struct pf_state_key **sks,
3139 struct pf_state_key **skp, struct pf_state_key **nkp,
3140 struct pf_addr *saddr, struct pf_addr *daddr,
3141 u_int16_t sport, u_int16_t dport)
3143 struct pf_rule *r = NULL;
3145 if (direction == PF_OUT) {
3146 r = pf_match_translation(pd, m, off, direction, kif, saddr,
3147 sport, daddr, dport, PF_RULESET_BINAT);
3148 if (r == NULL)
3149 r = pf_match_translation(pd, m, off, direction, kif,
3150 saddr, sport, daddr, dport, PF_RULESET_NAT);
3151 } else {
3152 r = pf_match_translation(pd, m, off, direction, kif, saddr,
3153 sport, daddr, dport, PF_RULESET_RDR);
3154 if (r == NULL)
3155 r = pf_match_translation(pd, m, off, direction, kif,
3156 saddr, sport, daddr, dport, PF_RULESET_BINAT);
3159 if (r != NULL) {
3160 struct pf_addr *naddr;
3161 u_int16_t *nport;
3163 if (pf_state_key_setup(pd, r, skw, sks, skp, nkp,
3164 saddr, daddr, sport, dport))
3165 return r;
3167 /* XXX We only modify one side for now. */
3168 naddr = &(*nkp)->addr[1];
3169 nport = &(*nkp)->port[1];
3172 * NOTE: Currently all translations will clear
3173 * BRIDGE_MBUF_TAGGED, telling the bridge to
3174 * ignore the original input encapsulation.
3176 switch (r->action) {
3177 case PF_NONAT:
3178 case PF_NOBINAT:
3179 case PF_NORDR:
3180 return (NULL);
3181 case PF_NAT:
3182 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3183 if (pf_get_sport(pd, pd->af, pd->proto, r,
3184 saddr, daddr, sport, dport,
3185 naddr, nport, r->rpool.proxy_port[0],
3186 r->rpool.proxy_port[1], sn)) {
3187 DPFPRINTF(PF_DEBUG_MISC,
3188 ("pf: NAT proxy port allocation "
3189 "(%u-%u) failed\n",
3190 r->rpool.proxy_port[0],
3191 r->rpool.proxy_port[1]));
3192 return (NULL);
3194 break;
3195 case PF_BINAT:
3196 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3197 switch (direction) {
3198 case PF_OUT:
3199 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
3200 switch (pd->af) {
3201 #ifdef INET
3202 case AF_INET:
3203 if (r->rpool.cur->addr.p.dyn->
3204 pfid_acnt4 < 1)
3205 return (NULL);
3206 PF_POOLMASK(naddr,
3207 &r->rpool.cur->addr.p.dyn->
3208 pfid_addr4,
3209 &r->rpool.cur->addr.p.dyn->
3210 pfid_mask4,
3211 saddr, AF_INET);
3212 break;
3213 #endif /* INET */
3214 #ifdef INET6
3215 case AF_INET6:
3216 if (r->rpool.cur->addr.p.dyn->
3217 pfid_acnt6 < 1)
3218 return (NULL);
3219 PF_POOLMASK(naddr,
3220 &r->rpool.cur->addr.p.dyn->
3221 pfid_addr6,
3222 &r->rpool.cur->addr.p.dyn->
3223 pfid_mask6,
3224 saddr, AF_INET6);
3225 break;
3226 #endif /* INET6 */
3228 } else
3229 PF_POOLMASK(naddr,
3230 &r->rpool.cur->addr.v.a.addr,
3231 &r->rpool.cur->addr.v.a.mask,
3232 saddr, pd->af);
3233 break;
3234 case PF_IN:
3235 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
3236 switch (pd->af) {
3237 #ifdef INET
3238 case AF_INET:
3239 if (r->src.addr.p.dyn->
3240 pfid_acnt4 < 1)
3241 return (NULL);
3242 PF_POOLMASK(naddr,
3243 &r->src.addr.p.dyn->
3244 pfid_addr4,
3245 &r->src.addr.p.dyn->
3246 pfid_mask4,
3247 daddr, AF_INET);
3248 break;
3249 #endif /* INET */
3250 #ifdef INET6
3251 case AF_INET6:
3252 if (r->src.addr.p.dyn->
3253 pfid_acnt6 < 1)
3254 return (NULL);
3255 PF_POOLMASK(naddr,
3256 &r->src.addr.p.dyn->
3257 pfid_addr6,
3258 &r->src.addr.p.dyn->
3259 pfid_mask6,
3260 daddr, AF_INET6);
3261 break;
3262 #endif /* INET6 */
3264 } else
3265 PF_POOLMASK(naddr,
3266 &r->src.addr.v.a.addr,
3267 &r->src.addr.v.a.mask, daddr,
3268 pd->af);
3269 break;
3271 break;
3272 case PF_RDR: {
3273 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
3274 if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
3275 return (NULL);
3276 if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
3277 PF_POOL_BITMASK)
3278 PF_POOLMASK(naddr, naddr,
3279 &r->rpool.cur->addr.v.a.mask, daddr,
3280 pd->af);
3282 if (r->rpool.proxy_port[1]) {
3283 u_int32_t tmp_nport;
3285 tmp_nport = ((ntohs(dport) -
3286 ntohs(r->dst.port[0])) %
3287 (r->rpool.proxy_port[1] -
3288 r->rpool.proxy_port[0] + 1)) +
3289 r->rpool.proxy_port[0];
3291 /* wrap around if necessary */
3292 if (tmp_nport > 65535)
3293 tmp_nport -= 65535;
3294 *nport = htons((u_int16_t)tmp_nport);
3295 } else if (r->rpool.proxy_port[0]) {
3296 *nport = htons(r->rpool.proxy_port[0]);
3298 pd->not_cpu_localized = 1;
3299 break;
3301 default:
3302 return (NULL);
3306 return (r);
3309 struct netmsg_hashlookup {
3310 struct netmsg_base base;
3311 struct inpcb **nm_pinp;
3312 struct inpcbinfo *nm_pcbinfo;
3313 struct pf_addr *nm_saddr;
3314 struct pf_addr *nm_daddr;
3315 uint16_t nm_sport;
3316 uint16_t nm_dport;
3317 sa_family_t nm_af;
3320 #ifdef PF_SOCKET_LOOKUP_DOMSG
3321 static void
3322 in_pcblookup_hash_handler(netmsg_t msg)
3324 struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
3326 if (rmsg->nm_af == AF_INET)
3327 *rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
3328 rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
3329 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
3330 #ifdef INET6
3331 else
3332 *rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
3333 &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
3334 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
3335 #endif /* INET6 */
3336 lwkt_replymsg(&rmsg->base.lmsg, 0);
3338 #endif /* PF_SOCKET_LOOKUP_DOMSG */
3341 pf_socket_lookup(int direction, struct pf_pdesc *pd)
3343 struct pf_addr *saddr, *daddr;
3344 u_int16_t sport, dport;
3345 struct inpcbinfo *pi;
3346 struct inpcb *inp;
3347 struct netmsg_hashlookup *msg = NULL;
3348 #ifdef PF_SOCKET_LOOKUP_DOMSG
3349 struct netmsg_hashlookup msg0;
3350 #endif
3351 int pi_cpu = 0;
3353 if (pd == NULL)
3354 return (-1);
3355 pd->lookup.uid = UID_MAX;
3356 pd->lookup.gid = GID_MAX;
3357 pd->lookup.pid = NO_PID;
3358 if (direction == PF_IN) {
3359 saddr = pd->src;
3360 daddr = pd->dst;
3361 } else {
3362 saddr = pd->dst;
3363 daddr = pd->src;
3365 switch (pd->proto) {
3366 case IPPROTO_TCP:
3367 if (pd->hdr.tcp == NULL)
3368 return (-1);
3369 sport = pd->hdr.tcp->th_sport;
3370 dport = pd->hdr.tcp->th_dport;
3372 pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
3373 pi = &tcbinfo[pi_cpu];
3375 * Our netstack runs lockless on MP systems
3376 * (only for TCP connections at the moment).
3378 * As we are not allowed to read another CPU's tcbinfo,
3379 * we have to ask that CPU via remote call to search the
3380 * table for us.
3382 * Prepare a msg iff data belongs to another CPU.
3384 if (pi_cpu != mycpu->gd_cpuid) {
3385 #ifdef PF_SOCKET_LOOKUP_DOMSG
3387 * NOTE:
3389 * Following lwkt_domsg() is dangerous and could
3390 * lockup the network system, e.g.
3392 * On 2 CPU system:
3393 * netisr0 domsg to netisr1 (due to lookup)
3394 * netisr1 domsg to netisr0 (due to lookup)
3396 * We simply return -1 here, since we are probably
3397 * called before NAT, so the TCP packet should
3398 * already be on the correct CPU.
3400 msg = &msg0;
3401 netmsg_init(&msg->base, NULL, &curthread->td_msgport,
3402 0, in_pcblookup_hash_handler);
3403 msg->nm_pinp = &inp;
3404 msg->nm_pcbinfo = pi;
3405 msg->nm_saddr = saddr;
3406 msg->nm_sport = sport;
3407 msg->nm_daddr = daddr;
3408 msg->nm_dport = dport;
3409 msg->nm_af = pd->af;
3410 #else /* !PF_SOCKET_LOOKUP_DOMSG */
3411 kprintf("pf_socket_lookup: tcp packet not on the "
3412 "correct cpu %d, cur cpu %d\n",
3413 pi_cpu, mycpuid);
3414 print_backtrace(-1);
3415 return -1;
3416 #endif /* PF_SOCKET_LOOKUP_DOMSG */
3418 break;
3419 case IPPROTO_UDP:
3420 if (pd->hdr.udp == NULL)
3421 return (-1);
3422 sport = pd->hdr.udp->uh_sport;
3423 dport = pd->hdr.udp->uh_dport;
3424 pi = &udbinfo[mycpuid];
3425 break;
3426 default:
3427 return (-1);
3429 if (direction != PF_IN) {
3430 u_int16_t p;
3432 p = sport;
3433 sport = dport;
3434 dport = p;
3436 switch (pd->af) {
3437 #ifdef INET6
3438 case AF_INET6:
3440 * Query other CPU, second part
3442 * msg only gets initialized when:
3443 * 1) packet is TCP
3444 * 2) the info belongs to another CPU
3446 * Use some switch/case magic to avoid code duplication.
3448 if (msg == NULL) {
3449 inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
3450 &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
3452 if (inp == NULL)
3453 return (-1);
3454 break;
3456 /* FALLTHROUGH if SMP and on other CPU */
3457 #endif /* INET6 */
3458 case AF_INET:
3459 if (msg != NULL) {
3460 lwkt_domsg(netisr_cpuport(pi_cpu),
3461 &msg->base.lmsg, 0);
3462 } else
3464 inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
3465 dport, INPLOOKUP_WILDCARD, NULL);
3467 if (inp == NULL)
3468 return (-1);
3469 break;
3471 default:
3472 return (-1);
3474 pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
3475 pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
3476 return (1);
3479 u_int8_t
3480 pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3482 int hlen;
3483 u_int8_t hdr[60];
3484 u_int8_t *opt, optlen;
3485 u_int8_t wscale = 0;
3487 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3488 if (hlen <= sizeof(struct tcphdr))
3489 return (0);
3490 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3491 return (0);
3492 opt = hdr + sizeof(struct tcphdr);
3493 hlen -= sizeof(struct tcphdr);
3494 while (hlen >= 3) {
3495 switch (*opt) {
3496 case TCPOPT_EOL:
3497 case TCPOPT_NOP:
3498 ++opt;
3499 --hlen;
3500 break;
3501 case TCPOPT_WINDOW:
3502 wscale = opt[2];
3503 if (wscale > TCP_MAX_WINSHIFT)
3504 wscale = TCP_MAX_WINSHIFT;
3505 wscale |= PF_WSCALE_FLAG;
3506 /* FALLTHROUGH */
3507 default:
3508 optlen = opt[1];
3509 if (optlen < 2)
3510 optlen = 2;
3511 hlen -= optlen;
3512 opt += optlen;
3513 break;
3516 return (wscale);
3519 u_int16_t
3520 pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3522 int hlen;
3523 u_int8_t hdr[60];
3524 u_int8_t *opt, optlen;
3525 u_int16_t mss = tcp_mssdflt;
3527 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3528 if (hlen <= sizeof(struct tcphdr))
3529 return (0);
3530 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3531 return (0);
3532 opt = hdr + sizeof(struct tcphdr);
3533 hlen -= sizeof(struct tcphdr);
3534 while (hlen >= TCPOLEN_MAXSEG) {
3535 switch (*opt) {
3536 case TCPOPT_EOL:
3537 case TCPOPT_NOP:
3538 ++opt;
3539 --hlen;
3540 break;
3541 case TCPOPT_MAXSEG:
3542 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3543 /* FALLTHROUGH */
3544 default:
3545 optlen = opt[1];
3546 if (optlen < 2)
3547 optlen = 2;
3548 hlen -= optlen;
3549 opt += optlen;
3550 break;
3553 return (mss);
3556 u_int16_t
3557 pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
3559 #ifdef INET
3560 struct sockaddr_in *dst;
3561 struct route ro;
3562 #endif /* INET */
3563 #ifdef INET6
3564 struct sockaddr_in6 *dst6;
3565 struct route_in6 ro6;
3566 #endif /* INET6 */
3567 struct rtentry *rt = NULL;
3568 int hlen = 0;
3569 u_int16_t mss = tcp_mssdflt;
3571 switch (af) {
3572 #ifdef INET
3573 case AF_INET:
3574 hlen = sizeof(struct ip);
3575 bzero(&ro, sizeof(ro));
3576 dst = (struct sockaddr_in *)&ro.ro_dst;
3577 dst->sin_family = AF_INET;
3578 dst->sin_len = sizeof(*dst);
3579 dst->sin_addr = addr->v4;
3580 rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
3581 rt = ro.ro_rt;
3582 break;
3583 #endif /* INET */
3584 #ifdef INET6
3585 case AF_INET6:
3586 hlen = sizeof(struct ip6_hdr);
3587 bzero(&ro6, sizeof(ro6));
3588 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3589 dst6->sin6_family = AF_INET6;
3590 dst6->sin6_len = sizeof(*dst6);
3591 dst6->sin6_addr = addr->v6;
3592 rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
3593 rt = ro6.ro_rt;
3594 break;
3595 #endif /* INET6 */
3598 if (rt && rt->rt_ifp) {
3599 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3600 mss = max(tcp_mssdflt, mss);
3601 RTFREE(rt);
3603 mss = min(mss, offer);
3604 mss = max(mss, 64); /* sanity - at least max opt space */
3605 return (mss);
3608 void
3609 pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3611 struct pf_rule *r = s->rule.ptr;
3613 s->rt_kif = NULL;
3614 if (!r->rt || r->rt == PF_FASTROUTE)
3615 return;
3616 switch (s->key[PF_SK_WIRE]->af) {
3617 #ifdef INET
3618 case AF_INET:
3619 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
3620 &s->nat_src_node);
3621 s->rt_kif = r->rpool.cur->kif;
3622 break;
3623 #endif /* INET */
3624 #ifdef INET6
3625 case AF_INET6:
3626 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
3627 &s->nat_src_node);
3628 s->rt_kif = r->rpool.cur->kif;
3629 break;
3630 #endif /* INET6 */
3634 u_int32_t
3635 pf_tcp_iss(struct pf_pdesc *pd)
3637 MD5_CTX ctx;
3638 u_int32_t digest[4];
3640 if (pf_tcp_secret_init == 0) {
3641 lwkt_gettoken(&pf_gtoken);
3642 if (pf_tcp_secret_init == 0) {
3643 karc4rand(pf_tcp_secret, sizeof(pf_tcp_secret));
3644 MD5Init(&pf_tcp_secret_ctx);
3645 MD5Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3646 sizeof(pf_tcp_secret));
3647 pf_tcp_secret_init = 1;
3649 lwkt_reltoken(&pf_gtoken);
3651 ctx = pf_tcp_secret_ctx;
3653 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3654 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3655 if (pd->af == AF_INET6) {
3656 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3657 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3658 } else {
3659 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3660 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
3662 MD5Final((u_char *)digest, &ctx);
3663 pf_tcp_iss_off += 4096;
3665 return (digest[0] + pd->hdr.tcp->th_seq + pf_tcp_iss_off);
3669 pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
3670 struct pfi_kif *kif, struct mbuf *m, int off, void *h,
3671 struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
3672 struct ifqueue *ifq, struct inpcb *inp)
3674 struct pf_rule *nr = NULL;
3675 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
3676 sa_family_t af = pd->af;
3677 struct pf_rule *r, *a = NULL;
3678 struct pf_ruleset *ruleset = NULL;
3679 struct pf_src_node *nsn = NULL;
3680 struct tcphdr *th = pd->hdr.tcp;
3681 struct pf_state_key *skw = NULL, *sks = NULL;
3682 struct pf_state_key *sk = NULL, *nk = NULL;
3683 u_short reason;
3684 int rewrite = 0, hdrlen = 0;
3685 int tag = -1, rtableid = -1;
3686 int asd = 0;
3687 int match = 0;
3688 int state_icmp = 0;
3689 u_int16_t sport = 0, dport = 0;
3690 u_int16_t bproto_sum = 0, bip_sum = 0;
3691 u_int8_t icmptype = 0, icmpcode = 0;
3694 if (direction == PF_IN && pf_check_congestion(ifq)) {
3695 REASON_SET(&reason, PFRES_CONGEST);
3696 return (PF_DROP);
3699 if (inp != NULL)
3700 pd->lookup.done = pf_socket_lookup(direction, pd);
3701 else if (debug_pfugidhack) {
3702 DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
3703 pd->lookup.done = pf_socket_lookup(direction, pd);
3706 switch (pd->proto) {
3707 case IPPROTO_TCP:
3708 sport = th->th_sport;
3709 dport = th->th_dport;
3710 hdrlen = sizeof(*th);
3711 break;
3712 case IPPROTO_UDP:
3713 sport = pd->hdr.udp->uh_sport;
3714 dport = pd->hdr.udp->uh_dport;
3715 hdrlen = sizeof(*pd->hdr.udp);
3716 break;
3717 #ifdef INET
3718 case IPPROTO_ICMP:
3719 if (pd->af != AF_INET)
3720 break;
3721 sport = dport = pd->hdr.icmp->icmp_id;
3722 hdrlen = sizeof(*pd->hdr.icmp);
3723 icmptype = pd->hdr.icmp->icmp_type;
3724 icmpcode = pd->hdr.icmp->icmp_code;
3726 if (icmptype == ICMP_UNREACH ||
3727 icmptype == ICMP_SOURCEQUENCH ||
3728 icmptype == ICMP_REDIRECT ||
3729 icmptype == ICMP_TIMXCEED ||
3730 icmptype == ICMP_PARAMPROB)
3731 state_icmp++;
3732 break;
3733 #endif /* INET */
3734 #ifdef INET6
3735 case IPPROTO_ICMPV6:
3736 if (af != AF_INET6)
3737 break;
3738 sport = dport = pd->hdr.icmp6->icmp6_id;
3739 hdrlen = sizeof(*pd->hdr.icmp6);
3740 icmptype = pd->hdr.icmp6->icmp6_type;
3741 icmpcode = pd->hdr.icmp6->icmp6_code;
3743 if (icmptype == ICMP6_DST_UNREACH ||
3744 icmptype == ICMP6_PACKET_TOO_BIG ||
3745 icmptype == ICMP6_TIME_EXCEEDED ||
3746 icmptype == ICMP6_PARAM_PROB)
3747 state_icmp++;
3748 break;
3749 #endif /* INET6 */
3750 default:
3751 sport = dport = hdrlen = 0;
3752 break;
3755 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3757 /* check packet for BINAT/NAT/RDR */
3758 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn,
3759 &skw, &sks, &sk, &nk, saddr, daddr, sport, dport)) != NULL) {
3760 if (nk == NULL || sk == NULL) {
3761 REASON_SET(&reason, PFRES_MEMORY);
3762 goto cleanup;
3765 if (pd->ip_sum)
3766 bip_sum = *pd->ip_sum;
3768 m->m_flags &= ~M_HASH;
3769 switch (pd->proto) {
3770 case IPPROTO_TCP:
3771 bproto_sum = th->th_sum;
3772 pd->proto_sum = &th->th_sum;
3774 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3775 nk->port[pd->sidx] != sport) {
3776 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
3777 &th->th_sum, &nk->addr[pd->sidx],
3778 nk->port[pd->sidx], 0, af);
3779 pd->sport = &th->th_sport;
3780 sport = th->th_sport;
3783 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3784 nk->port[pd->didx] != dport) {
3785 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3786 &th->th_sum, &nk->addr[pd->didx],
3787 nk->port[pd->didx], 0, af);
3788 dport = th->th_dport;
3789 pd->dport = &th->th_dport;
3791 rewrite++;
3792 break;
3793 case IPPROTO_UDP:
3794 bproto_sum = pd->hdr.udp->uh_sum;
3795 pd->proto_sum = &pd->hdr.udp->uh_sum;
3797 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3798 nk->port[pd->sidx] != sport) {
3799 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3800 pd->ip_sum, &pd->hdr.udp->uh_sum,
3801 &nk->addr[pd->sidx],
3802 nk->port[pd->sidx], 1, af);
3803 sport = pd->hdr.udp->uh_sport;
3804 pd->sport = &pd->hdr.udp->uh_sport;
3807 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3808 nk->port[pd->didx] != dport) {
3809 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3810 pd->ip_sum, &pd->hdr.udp->uh_sum,
3811 &nk->addr[pd->didx],
3812 nk->port[pd->didx], 1, af);
3813 dport = pd->hdr.udp->uh_dport;
3814 pd->dport = &pd->hdr.udp->uh_dport;
3816 rewrite++;
3817 break;
3818 #ifdef INET
3819 case IPPROTO_ICMP:
3820 nk->port[0] = nk->port[1];
3821 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
3822 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
3823 nk->addr[pd->sidx].v4.s_addr, 0);
3825 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3826 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3827 nk->addr[pd->didx].v4.s_addr, 0);
3829 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
3830 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
3831 pd->hdr.icmp->icmp_cksum, sport,
3832 nk->port[1], 0);
3833 pd->hdr.icmp->icmp_id = nk->port[1];
3834 pd->sport = &pd->hdr.icmp->icmp_id;
3836 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3837 break;
3838 #endif /* INET */
3839 #ifdef INET6
3840 case IPPROTO_ICMPV6:
3841 nk->port[0] = nk->port[1];
3842 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
3843 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
3844 &nk->addr[pd->sidx], 0);
3846 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3847 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3848 &nk->addr[pd->didx], 0);
3849 rewrite++;
3850 break;
3851 #endif /* INET */
3852 default:
3853 switch (af) {
3854 #ifdef INET
3855 case AF_INET:
3856 if (PF_ANEQ(saddr,
3857 &nk->addr[pd->sidx], AF_INET))
3858 pf_change_a(&saddr->v4.s_addr,
3859 pd->ip_sum,
3860 nk->addr[pd->sidx].v4.s_addr, 0);
3862 if (PF_ANEQ(daddr,
3863 &nk->addr[pd->didx], AF_INET))
3864 pf_change_a(&daddr->v4.s_addr,
3865 pd->ip_sum,
3866 nk->addr[pd->didx].v4.s_addr, 0);
3867 break;
3868 #endif /* INET */
3869 #ifdef INET6
3870 case AF_INET6:
3871 if (PF_ANEQ(saddr,
3872 &nk->addr[pd->sidx], AF_INET6))
3873 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
3875 if (PF_ANEQ(daddr,
3876 &nk->addr[pd->didx], AF_INET6))
3877 PF_ACPY(saddr, &nk->addr[pd->didx], af);
3878 break;
3879 #endif /* INET */
3881 break;
3883 if (nr->natpass)
3884 r = NULL;
3885 pd->nat_rule = nr;
3888 while (r != NULL) {
3889 r->evaluations++;
3890 if (pfi_kif_match(r->kif, kif) == r->ifnot)
3891 r = r->skip[PF_SKIP_IFP].ptr;
3892 else if (r->direction && r->direction != direction)
3893 r = r->skip[PF_SKIP_DIR].ptr;
3894 else if (r->af && r->af != af)
3895 r = r->skip[PF_SKIP_AF].ptr;
3896 else if (r->proto && r->proto != pd->proto)
3897 r = r->skip[PF_SKIP_PROTO].ptr;
3898 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3899 r->src.neg, kif))
3900 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
3901 /* tcp/udp only. port_op always 0 in other cases */
3902 else if (r->src.port_op && !pf_match_port(r->src.port_op,
3903 r->src.port[0], r->src.port[1], sport))
3904 r = r->skip[PF_SKIP_SRC_PORT].ptr;
3905 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3906 r->dst.neg, NULL))
3907 r = r->skip[PF_SKIP_DST_ADDR].ptr;
3908 /* tcp/udp only. port_op always 0 in other cases */
3909 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
3910 r->dst.port[0], r->dst.port[1], dport))
3911 r = r->skip[PF_SKIP_DST_PORT].ptr;
3912 /* icmp only. type always 0 in other cases */
3913 else if (r->type && r->type != icmptype + 1)
3914 r = TAILQ_NEXT(r, entries);
3915 /* icmp only. type always 0 in other cases */
3916 else if (r->code && r->code != icmpcode + 1)
3917 r = TAILQ_NEXT(r, entries);
3918 else if (r->tos && !(r->tos == pd->tos))
3919 r = TAILQ_NEXT(r, entries);
3920 else if (r->rule_flag & PFRULE_FRAGMENT)
3921 r = TAILQ_NEXT(r, entries);
3922 else if (pd->proto == IPPROTO_TCP &&
3923 (r->flagset & th->th_flags) != r->flags)
3924 r = TAILQ_NEXT(r, entries);
3925 /* tcp/udp only. uid.op always 0 in other cases */
3926 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
3927 pf_socket_lookup(direction, pd), 1)) &&
3928 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
3929 pd->lookup.uid))
3930 r = TAILQ_NEXT(r, entries);
3931 /* tcp/udp only. gid.op always 0 in other cases */
3932 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
3933 pf_socket_lookup(direction, pd), 1)) &&
3934 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
3935 pd->lookup.gid))
3936 r = TAILQ_NEXT(r, entries);
3937 else if (r->prob &&
3938 r->prob <= karc4random())
3939 r = TAILQ_NEXT(r, entries);
3940 else if (r->match_tag && !pf_match_tag(m, r, &tag))
3941 r = TAILQ_NEXT(r, entries);
3942 else if (r->os_fingerprint != PF_OSFP_ANY &&
3943 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3944 pf_osfp_fingerprint(pd, m, off, th),
3945 r->os_fingerprint)))
3946 r = TAILQ_NEXT(r, entries);
3947 else {
3948 if (r->tag)
3949 tag = r->tag;
3950 if (r->rtableid >= 0)
3951 rtableid = r->rtableid;
3952 if (r->anchor == NULL) {
3953 match = 1;
3954 *rm = r;
3955 *am = a;
3956 *rsm = ruleset;
3957 if ((*rm)->quick)
3958 break;
3959 r = TAILQ_NEXT(r, entries);
3960 } else
3961 pf_step_into_anchor(&asd, &ruleset,
3962 PF_RULESET_FILTER, &r, &a, &match);
3964 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3965 PF_RULESET_FILTER, &r, &a, &match))
3966 break;
3968 r = *rm;
3969 a = *am;
3970 ruleset = *rsm;
3972 REASON_SET(&reason, PFRES_MATCH);
3974 if (r->log || (nr != NULL && nr->log)) {
3975 if (rewrite)
3976 m_copyback(m, off, hdrlen, pd->hdr.any);
3977 PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3978 a, ruleset, pd);
3981 if ((r->action == PF_DROP) &&
3982 ((r->rule_flag & PFRULE_RETURNRST) ||
3983 (r->rule_flag & PFRULE_RETURNICMP) ||
3984 (r->rule_flag & PFRULE_RETURN))) {
3985 /* undo NAT changes, if they have taken place */
3986 if (nr != NULL) {
3987 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3988 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3989 if (pd->sport)
3990 *pd->sport = sk->port[pd->sidx];
3991 if (pd->dport)
3992 *pd->dport = sk->port[pd->didx];
3993 if (pd->proto_sum)
3994 *pd->proto_sum = bproto_sum;
3995 if (pd->ip_sum)
3996 *pd->ip_sum = bip_sum;
3997 m_copyback(m, off, hdrlen, pd->hdr.any);
3999 if (pd->proto == IPPROTO_TCP &&
4000 ((r->rule_flag & PFRULE_RETURNRST) ||
4001 (r->rule_flag & PFRULE_RETURN)) &&
4002 !(th->th_flags & TH_RST)) {
4003 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
4004 int len = 0;
4005 struct ip *h4;
4006 #ifdef INET6
4007 struct ip6_hdr *h6;
4008 #endif
4009 switch (af) {
4010 case AF_INET:
4011 h4 = mtod(m, struct ip *);
4012 len = h4->ip_len - off;
4013 break;
4014 #ifdef INET6
4015 case AF_INET6:
4016 h6 = mtod(m, struct ip6_hdr *);
4017 len = h6->ip6_plen - (off - sizeof(*h6));
4018 break;
4019 #endif
4022 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
4023 REASON_SET(&reason, PFRES_PROTCKSUM);
4024 else {
4025 if (th->th_flags & TH_SYN)
4026 ack++;
4027 if (th->th_flags & TH_FIN)
4028 ack++;
4029 pf_send_tcp(r, af, pd->dst,
4030 pd->src, th->th_dport, th->th_sport,
4031 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
4032 r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
4034 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
4035 r->return_icmp)
4036 pf_send_icmp(m, r->return_icmp >> 8,
4037 r->return_icmp & 255, af, r);
4038 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
4039 r->return_icmp6)
4040 pf_send_icmp(m, r->return_icmp6 >> 8,
4041 r->return_icmp6 & 255, af, r);
4044 if (r->action == PF_DROP)
4045 goto cleanup;
4047 if (pf_tag_packet(m, tag, rtableid)) {
4048 REASON_SET(&reason, PFRES_MEMORY);
4049 goto cleanup;
4052 if (!state_icmp && (r->keep_state || nr != NULL ||
4053 (pd->flags & PFDESC_TCP_NORM))) {
4054 int action;
4055 action = pf_create_state(r, nr, a, pd, nsn, skw, sks, nk, sk, m,
4056 off, sport, dport, &rewrite, kif, sm, tag, bproto_sum,
4057 bip_sum, hdrlen);
4058 if (action != PF_PASS)
4059 return (action);
4062 /* copy back packet headers if we performed NAT operations */
4063 if (rewrite)
4064 m_copyback(m, off, hdrlen, pd->hdr.any);
4066 return (PF_PASS);
4068 cleanup:
4069 if (sk != NULL)
4070 kfree(sk, M_PFSTATEKEYPL);
4071 if (nk != NULL)
4072 kfree(nk, M_PFSTATEKEYPL);
4073 return (PF_DROP);
4076 static __inline int
4077 pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
4078 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *skw,
4079 struct pf_state_key *sks, struct pf_state_key *nk, struct pf_state_key *sk,
4080 struct mbuf *m, int off, u_int16_t sport, u_int16_t dport, int *rewrite,
4081 struct pfi_kif *kif, struct pf_state **sm, int tag, u_int16_t bproto_sum,
4082 u_int16_t bip_sum, int hdrlen)
4084 struct pf_state *s = NULL;
4085 struct pf_src_node *sn = NULL;
4086 struct tcphdr *th = pd->hdr.tcp;
4087 u_int16_t mss = tcp_mssdflt;
4088 u_short reason;
4089 int cpu = mycpu->gd_cpuid;
4091 /* check maximums */
4092 if (r->max_states && (r->states_cur >= r->max_states)) {
4093 pf_status.lcounters[LCNT_STATES]++;
4094 REASON_SET(&reason, PFRES_MAXSTATES);
4095 return (PF_DROP);
4097 /* src node for filter rule */
4098 if ((r->rule_flag & PFRULE_SRCTRACK ||
4099 r->rpool.opts & PF_POOL_STICKYADDR) &&
4100 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
4101 REASON_SET(&reason, PFRES_SRCLIMIT);
4102 goto csfailed;
4104 /* src node for translation rule */
4105 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
4106 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
4107 REASON_SET(&reason, PFRES_SRCLIMIT);
4108 goto csfailed;
4110 s = kmalloc(sizeof(struct pf_state), M_PFSTATEPL, M_NOWAIT|M_ZERO);
4111 if (s == NULL) {
4112 REASON_SET(&reason, PFRES_MEMORY);
4113 goto csfailed;
4115 lockinit(&s->lk, "pfstlk", 0, 0);
4116 s->id = 0; /* XXX Do we really need that? not in OpenBSD */
4117 s->creatorid = 0;
4118 s->rule.ptr = r;
4119 s->nat_rule.ptr = nr;
4120 s->anchor.ptr = a;
4121 s->state_flags = PFSTATE_CREATEINPROG;
4122 STATE_INC_COUNTERS(s);
4123 if (r->allow_opts)
4124 s->state_flags |= PFSTATE_ALLOWOPTS;
4125 if (r->rule_flag & PFRULE_STATESLOPPY)
4126 s->state_flags |= PFSTATE_SLOPPY;
4127 if (pd->not_cpu_localized)
4128 s->state_flags |= PFSTATE_STACK_GLOBAL;
4130 s->log = r->log & PF_LOG_ALL;
4131 if (nr != NULL)
4132 s->log |= nr->log & PF_LOG_ALL;
4133 switch (pd->proto) {
4134 case IPPROTO_TCP:
4135 s->src.seqlo = ntohl(th->th_seq);
4136 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
4137 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
4138 r->keep_state == PF_STATE_MODULATE) {
4139 /* Generate sequence number modulator */
4140 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
4142 s->src.seqdiff = 1;
4143 pf_change_a(&th->th_seq, &th->th_sum,
4144 htonl(s->src.seqlo + s->src.seqdiff), 0);
4145 *rewrite = 1;
4146 } else
4147 s->src.seqdiff = 0;
4148 if (th->th_flags & TH_SYN) {
4149 s->src.seqhi++;
4150 s->src.wscale = pf_get_wscale(m, off,
4151 th->th_off, pd->af);
4153 s->src.max_win = MAX(ntohs(th->th_win), 1);
4154 if (s->src.wscale & PF_WSCALE_MASK) {
4155 /* Remove scale factor from initial window */
4156 int win = s->src.max_win;
4157 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
4158 s->src.max_win = (win - 1) >>
4159 (s->src.wscale & PF_WSCALE_MASK);
4161 if (th->th_flags & TH_FIN)
4162 s->src.seqhi++;
4163 s->dst.seqhi = 1;
4164 s->dst.max_win = 1;
4165 s->src.state = TCPS_SYN_SENT;
4166 s->dst.state = TCPS_CLOSED;
4167 s->timeout = PFTM_TCP_FIRST_PACKET;
4168 break;
4169 case IPPROTO_UDP:
4170 s->src.state = PFUDPS_SINGLE;
4171 s->dst.state = PFUDPS_NO_TRAFFIC;
4172 s->timeout = PFTM_UDP_FIRST_PACKET;
4173 break;
4174 case IPPROTO_ICMP:
4175 #ifdef INET6
4176 case IPPROTO_ICMPV6:
4177 #endif
4178 s->timeout = PFTM_ICMP_FIRST_PACKET;
4179 break;
4180 default:
4181 s->src.state = PFOTHERS_SINGLE;
4182 s->dst.state = PFOTHERS_NO_TRAFFIC;
4183 s->timeout = PFTM_OTHER_FIRST_PACKET;
4186 s->creation = time_second;
4187 s->expire = time_second;
4189 if (sn != NULL) {
4190 s->src_node = sn;
4191 s->src_node->states++;
4193 if (nsn != NULL) {
4194 /* XXX We only modify one side for now. */
4195 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
4196 s->nat_src_node = nsn;
4197 s->nat_src_node->states++;
4199 if (pd->proto == IPPROTO_TCP) {
4200 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
4201 off, pd, th, &s->src, &s->dst)) {
4202 REASON_SET(&reason, PFRES_MEMORY);
4203 pf_src_tree_remove_state(s);
4204 STATE_DEC_COUNTERS(s);
4205 kfree(s, M_PFSTATEPL);
4206 return (PF_DROP);
4208 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
4209 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
4210 &s->src, &s->dst, rewrite)) {
4211 /* This really shouldn't happen!!! */
4212 DPFPRINTF(PF_DEBUG_URGENT,
4213 ("pf_normalize_tcp_stateful failed on first pkt"));
4214 pf_normalize_tcp_cleanup(s);
4215 pf_src_tree_remove_state(s);
4216 STATE_DEC_COUNTERS(s);
4217 kfree(s, M_PFSTATEPL);
4218 return (PF_DROP);
4221 s->direction = pd->dir;
4223 if (sk == NULL && pf_state_key_setup(pd, nr, &skw, &sks, &sk, &nk,
4224 pd->src, pd->dst, sport, dport)) {
4225 REASON_SET(&reason, PFRES_MEMORY);
4226 goto csfailed;
4229 if (pf_state_insert(BOUND_IFACE(r, kif), skw, sks, s)) {
4230 if (pd->proto == IPPROTO_TCP)
4231 pf_normalize_tcp_cleanup(s);
4232 REASON_SET(&reason, PFRES_STATEINS);
4233 pf_src_tree_remove_state(s);
4234 STATE_DEC_COUNTERS(s);
4235 kfree(s, M_PFSTATEPL);
4236 return (PF_DROP);
4237 } else
4238 *sm = s;
4240 pf_set_rt_ifp(s, pd->src); /* needs s->state_key set */
4241 if (tag > 0) {
4242 pf_tag_ref(tag);
4243 s->tag = tag;
4245 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
4246 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
4247 s->src.state = PF_TCPS_PROXY_SRC;
4248 /* undo NAT changes, if they have taken place */
4249 if (nr != NULL) {
4250 struct pf_state_key *skt = s->key[PF_SK_WIRE];
4251 if (pd->dir == PF_OUT)
4252 skt = s->key[PF_SK_STACK];
4253 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
4254 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
4255 if (pd->sport)
4256 *pd->sport = skt->port[pd->sidx];
4257 if (pd->dport)
4258 *pd->dport = skt->port[pd->didx];
4259 if (pd->proto_sum)
4260 *pd->proto_sum = bproto_sum;
4261 if (pd->ip_sum)
4262 *pd->ip_sum = bip_sum;
4263 m->m_flags &= ~M_HASH;
4264 m_copyback(m, off, hdrlen, pd->hdr.any);
4266 s->src.seqhi = htonl(karc4random());
4267 /* Find mss option */
4268 mss = pf_get_mss(m, off, th->th_off, pd->af);
4269 mss = pf_calc_mss(pd->src, pd->af, mss);
4270 mss = pf_calc_mss(pd->dst, pd->af, mss);
4271 s->src.mss = mss;
4272 s->state_flags &= ~PFSTATE_CREATEINPROG;
4273 pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
4274 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
4275 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
4276 REASON_SET(&reason, PFRES_SYNPROXY);
4277 return (PF_SYNPROXY_DROP);
4280 s->state_flags &= ~PFSTATE_CREATEINPROG;
4281 return (PF_PASS);
4283 csfailed:
4284 if (sk != NULL)
4285 kfree(sk, M_PFSTATEKEYPL);
4286 if (nk != NULL)
4287 kfree(nk, M_PFSTATEKEYPL);
4289 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
4290 RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], sn);
4291 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
4292 atomic_add_int(&pf_status.src_nodes, -1);
4293 kfree(sn, M_PFSRCTREEPL);
4295 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
4296 RB_REMOVE(pf_src_tree, &tree_src_tracking[cpu], nsn);
4297 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
4298 atomic_add_int(&pf_status.src_nodes, -1);
4299 kfree(nsn, M_PFSRCTREEPL);
4301 if (s) {
4302 pf_src_tree_remove_state(s);
4303 STATE_DEC_COUNTERS(s);
4304 kfree(s, M_PFSTATEPL);
4307 return (PF_DROP);
4311 pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
4312 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
4313 struct pf_ruleset **rsm)
4315 struct pf_rule *r, *a = NULL;
4316 struct pf_ruleset *ruleset = NULL;
4317 sa_family_t af = pd->af;
4318 u_short reason;
4319 int tag = -1;
4320 int asd = 0;
4321 int match = 0;
4323 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
4324 while (r != NULL) {
4325 r->evaluations++;
4326 if (pfi_kif_match(r->kif, kif) == r->ifnot)
4327 r = r->skip[PF_SKIP_IFP].ptr;
4328 else if (r->direction && r->direction != direction)
4329 r = r->skip[PF_SKIP_DIR].ptr;
4330 else if (r->af && r->af != af)
4331 r = r->skip[PF_SKIP_AF].ptr;
4332 else if (r->proto && r->proto != pd->proto)
4333 r = r->skip[PF_SKIP_PROTO].ptr;
4334 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
4335 r->src.neg, kif))
4336 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
4337 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
4338 r->dst.neg, NULL))
4339 r = r->skip[PF_SKIP_DST_ADDR].ptr;
4340 else if (r->tos && !(r->tos == pd->tos))
4341 r = TAILQ_NEXT(r, entries);
4342 else if (r->os_fingerprint != PF_OSFP_ANY)
4343 r = TAILQ_NEXT(r, entries);
4344 else if (pd->proto == IPPROTO_UDP &&
4345 (r->src.port_op || r->dst.port_op))
4346 r = TAILQ_NEXT(r, entries);
4347 else if (pd->proto == IPPROTO_TCP &&
4348 (r->src.port_op || r->dst.port_op || r->flagset))
4349 r = TAILQ_NEXT(r, entries);
4350 else if ((pd->proto == IPPROTO_ICMP ||
4351 pd->proto == IPPROTO_ICMPV6) &&
4352 (r->type || r->code))
4353 r = TAILQ_NEXT(r, entries);
4354 else if (r->prob && r->prob <= karc4random())
4355 r = TAILQ_NEXT(r, entries);
4356 else if (r->match_tag && !pf_match_tag(m, r, &tag))
4357 r = TAILQ_NEXT(r, entries);
4358 else {
4359 if (r->anchor == NULL) {
4360 match = 1;
4361 *rm = r;
4362 *am = a;
4363 *rsm = ruleset;
4364 if ((*rm)->quick)
4365 break;
4366 r = TAILQ_NEXT(r, entries);
4367 } else
4368 pf_step_into_anchor(&asd, &ruleset,
4369 PF_RULESET_FILTER, &r, &a, &match);
4371 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
4372 PF_RULESET_FILTER, &r, &a, &match))
4373 break;
4375 r = *rm;
4376 a = *am;
4377 ruleset = *rsm;
4379 REASON_SET(&reason, PFRES_MATCH);
4381 if (r->log)
4382 PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
4383 pd);
4385 if (r->action != PF_PASS)
4386 return (PF_DROP);
4388 if (pf_tag_packet(m, tag, -1)) {
4389 REASON_SET(&reason, PFRES_MEMORY);
4390 return (PF_DROP);
4393 return (PF_PASS);
4397 * Called with state locked
4400 pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
4401 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
4402 struct pf_pdesc *pd, u_short *reason, int *copyback)
4404 struct tcphdr *th = pd->hdr.tcp;
4405 u_int16_t win = ntohs(th->th_win);
4406 u_int32_t ack, end, seq, orig_seq;
4407 u_int8_t sws, dws;
4408 int ackskew;
4410 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
4411 sws = src->wscale & PF_WSCALE_MASK;
4412 dws = dst->wscale & PF_WSCALE_MASK;
4413 } else {
4414 sws = dws = 0;
4418 * Sequence tracking algorithm from Guido van Rooij's paper:
4419 * http://www.madison-gurkha.com/publications/tcp_filtering/
4420 * tcp_filtering.ps
4423 orig_seq = seq = ntohl(th->th_seq);
4424 if (src->seqlo == 0) {
4425 /* First packet from this end. Set its state */
4427 if ((pd->flags & PFDESC_TCP_NORM || dst->scrub) &&
4428 src->scrub == NULL) {
4429 if (pf_normalize_tcp_init(m, off, pd, th, src, dst)) {
4430 REASON_SET(reason, PFRES_MEMORY);
4431 return (PF_DROP);
4435 /* Deferred generation of sequence number modulator */
4436 if (dst->seqdiff && !src->seqdiff) {
4437 /* use random iss for the TCP server */
4438 while ((src->seqdiff = karc4random() - seq) == 0)
4440 ack = ntohl(th->th_ack) - dst->seqdiff;
4441 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
4442 src->seqdiff), 0);
4443 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
4444 *copyback = 1;
4445 } else {
4446 ack = ntohl(th->th_ack);
4449 end = seq + pd->p_len;
4450 if (th->th_flags & TH_SYN) {
4451 end++;
4452 (*state)->sync_flags |= PFSTATE_GOT_SYN2;
4453 if (dst->wscale & PF_WSCALE_FLAG) {
4454 src->wscale = pf_get_wscale(m, off, th->th_off,
4455 pd->af);
4456 if (src->wscale & PF_WSCALE_FLAG) {
4457 /* Remove scale factor from initial
4458 * window */
4459 sws = src->wscale & PF_WSCALE_MASK;
4460 win = ((u_int32_t)win + (1 << sws) - 1)
4461 >> sws;
4462 dws = dst->wscale & PF_WSCALE_MASK;
4463 } else {
4464 /* fixup other window */
4465 dst->max_win <<= dst->wscale &
4466 PF_WSCALE_MASK;
4467 /* in case of a retrans SYN|ACK */
4468 dst->wscale = 0;
4472 if (th->th_flags & TH_FIN)
4473 end++;
4475 src->seqlo = seq;
4476 if (src->state < TCPS_SYN_SENT)
4477 src->state = TCPS_SYN_SENT;
4480 * May need to slide the window (seqhi may have been set by
4481 * the crappy stack check or if we picked up the connection
4482 * after establishment)
4484 if (src->seqhi == 1 ||
4485 SEQ_GEQ(end + MAX(1, dst->max_win << dws), src->seqhi))
4486 src->seqhi = end + MAX(1, dst->max_win << dws);
4487 if (win > src->max_win)
4488 src->max_win = win;
4490 } else {
4491 ack = ntohl(th->th_ack) - dst->seqdiff;
4492 if (src->seqdiff) {
4493 /* Modulate sequence numbers */
4494 pf_change_a(&th->th_seq, &th->th_sum, htonl(seq +
4495 src->seqdiff), 0);
4496 pf_change_a(&th->th_ack, &th->th_sum, htonl(ack), 0);
4497 *copyback = 1;
4499 end = seq + pd->p_len;
4500 if (th->th_flags & TH_SYN)
4501 end++;
4502 if (th->th_flags & TH_FIN)
4503 end++;
4506 if ((th->th_flags & TH_ACK) == 0) {
4507 /* Let it pass through the ack skew check */
4508 ack = dst->seqlo;
4509 } else if ((ack == 0 &&
4510 (th->th_flags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) ||
4511 /* broken tcp stacks do not set ack */
4512 (dst->state < TCPS_SYN_SENT)) {
4514 * Many stacks (ours included) will set the ACK number in an
4515 * FIN|ACK if the SYN times out -- no sequence to ACK.
4517 ack = dst->seqlo;
4520 if (seq == end) {
4521 /* Ease sequencing restrictions on no data packets */
4522 seq = src->seqlo;
4523 end = seq;
4526 ackskew = dst->seqlo - ack;
4530 * Need to demodulate the sequence numbers in any TCP SACK options
4531 * (Selective ACK). We could optionally validate the SACK values
4532 * against the current ACK window, either forwards or backwards, but
4533 * I'm not confident that SACK has been implemented properly
4534 * everywhere. It wouldn't surprise me if several stacks accidently
4535 * SACK too far backwards of previously ACKed data. There really aren't
4536 * any security implications of bad SACKing unless the target stack
4537 * doesn't validate the option length correctly. Someone trying to
4538 * spoof into a TCP connection won't bother blindly sending SACK
4539 * options anyway.
4541 if (dst->seqdiff && (th->th_off << 2) > sizeof(struct tcphdr)) {
4542 if (pf_modulate_sack(m, off, pd, th, dst))
4543 *copyback = 1;
4547 #define MAXACKWINDOW (0xffff + 1500) /* 1500 is an arbitrary fudge factor */
4548 if (SEQ_GEQ(src->seqhi, end) &&
4549 /* Last octet inside other's window space */
4550 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) &&
4551 /* Retrans: not more than one window back */
4552 (ackskew >= -MAXACKWINDOW) &&
4553 /* Acking not more than one reassembled fragment backwards */
4554 (ackskew <= (MAXACKWINDOW << sws)) &&
4555 /* Acking not more than one window forward */
4556 ((th->th_flags & TH_RST) == 0 || orig_seq == src->seqlo ||
4557 (orig_seq == src->seqlo + 1) || (orig_seq + 1 == src->seqlo) ||
4558 (pd->flags & PFDESC_IP_REAS) == 0)) {
4559 /* Require an exact/+1 sequence match on resets when possible */
4561 if (dst->scrub || src->scrub) {
4562 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4563 *state, src, dst, copyback))
4564 return (PF_DROP);
4567 /* update max window */
4568 if (src->max_win < win)
4569 src->max_win = win;
4570 /* synchronize sequencing */
4571 if (SEQ_GT(end, src->seqlo))
4572 src->seqlo = end;
4573 /* slide the window of what the other end can send */
4574 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4575 dst->seqhi = ack + MAX((win << sws), 1);
4578 /* update states */
4579 if (th->th_flags & TH_SYN)
4580 if (src->state < TCPS_SYN_SENT)
4581 src->state = TCPS_SYN_SENT;
4582 if (th->th_flags & TH_FIN)
4583 if (src->state < TCPS_CLOSING)
4584 src->state = TCPS_CLOSING;
4585 if (th->th_flags & TH_ACK) {
4586 if (dst->state == TCPS_SYN_SENT) {
4587 dst->state = TCPS_ESTABLISHED;
4588 if (src->state == TCPS_ESTABLISHED &&
4589 (*state)->src_node != NULL &&
4590 pf_src_connlimit(*state)) {
4591 REASON_SET(reason, PFRES_SRCLIMIT);
4592 return (PF_DROP);
4594 } else if (dst->state == TCPS_CLOSING)
4595 dst->state = TCPS_FIN_WAIT_2;
4597 if (th->th_flags & TH_RST)
4598 src->state = dst->state = TCPS_TIME_WAIT;
4600 /* update expire time */
4601 (*state)->expire = time_second;
4602 if (src->state >= TCPS_FIN_WAIT_2 &&
4603 dst->state >= TCPS_FIN_WAIT_2)
4604 (*state)->timeout = PFTM_TCP_CLOSED;
4605 else if (src->state >= TCPS_CLOSING &&
4606 dst->state >= TCPS_CLOSING)
4607 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4608 else if (src->state < TCPS_ESTABLISHED ||
4609 dst->state < TCPS_ESTABLISHED)
4610 (*state)->timeout = PFTM_TCP_OPENING;
4611 else if (src->state >= TCPS_CLOSING ||
4612 dst->state >= TCPS_CLOSING)
4613 (*state)->timeout = PFTM_TCP_CLOSING;
4614 else
4615 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4617 /* Fall through to PASS packet */
4619 } else if ((dst->state < TCPS_SYN_SENT ||
4620 dst->state >= TCPS_FIN_WAIT_2 ||
4621 src->state >= TCPS_FIN_WAIT_2) &&
4622 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) &&
4623 /* Within a window forward of the originating packet */
4624 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW)) {
4625 /* Within a window backward of the originating packet */
4628 * This currently handles three situations:
4629 * 1) Stupid stacks will shotgun SYNs before their peer
4630 * replies.
4631 * 2) When PF catches an already established stream (the
4632 * firewall rebooted, the state table was flushed, routes
4633 * changed...)
4634 * 3) Packets get funky immediately after the connection
4635 * closes (this should catch Solaris spurious ACK|FINs
4636 * that web servers like to spew after a close)
4638 * This must be a little more careful than the above code
4639 * since packet floods will also be caught here. We don't
4640 * update the TTL here to mitigate the damage of a packet
4641 * flood and so the same code can handle awkward establishment
4642 * and a loosened connection close.
4643 * In the establishment case, a correct peer response will
4644 * validate the connection, go through the normal state code
4645 * and keep updating the state TTL.
4648 if (pf_status.debug >= PF_DEBUG_MISC) {
4649 kprintf("pf: loose state match: ");
4650 pf_print_state(*state);
4651 pf_print_flags(th->th_flags);
4652 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4653 "pkts=%llu:%llu dir=%s,%s\n", seq, orig_seq, ack, pd->p_len,
4654 ackskew, (unsigned long long)(*state)->packets[0],
4655 (unsigned long long)(*state)->packets[1],
4656 pd->dir == PF_IN ? "in" : "out",
4657 pd->dir == (*state)->direction ? "fwd" : "rev");
4660 if (dst->scrub || src->scrub) {
4661 if (pf_normalize_tcp_stateful(m, off, pd, reason, th,
4662 *state, src, dst, copyback))
4663 return (PF_DROP);
4666 /* update max window */
4667 if (src->max_win < win)
4668 src->max_win = win;
4669 /* synchronize sequencing */
4670 if (SEQ_GT(end, src->seqlo))
4671 src->seqlo = end;
4672 /* slide the window of what the other end can send */
4673 if (SEQ_GEQ(ack + (win << sws), dst->seqhi))
4674 dst->seqhi = ack + MAX((win << sws), 1);
4677 * Cannot set dst->seqhi here since this could be a shotgunned
4678 * SYN and not an already established connection.
4681 if (th->th_flags & TH_FIN)
4682 if (src->state < TCPS_CLOSING)
4683 src->state = TCPS_CLOSING;
4684 if (th->th_flags & TH_RST)
4685 src->state = dst->state = TCPS_TIME_WAIT;
4687 /* Fall through to PASS packet */
4689 } else if ((*state)->pickup_mode == PF_PICKUPS_HASHONLY ||
4690 ((*state)->pickup_mode == PF_PICKUPS_ENABLED &&
4691 ((*state)->sync_flags & PFSTATE_GOT_SYN_MASK) !=
4692 PFSTATE_GOT_SYN_MASK)) {
4694 * If pickup mode is hash only, do not fail on sequence checks.
4696 * If pickup mode is enabled and we did not see the SYN in
4697 * both direction, do not fail on sequence checks because
4698 * we do not have complete information on window scale.
4700 * Adjust expiration and fall through to PASS packet.
4701 * XXX Add a FIN check to reduce timeout?
4703 (*state)->expire = time_second;
4704 } else {
4706 * Failure processing
4708 if ((*state)->dst.state == TCPS_SYN_SENT &&
4709 (*state)->src.state == TCPS_SYN_SENT) {
4710 /* Send RST for state mismatches during handshake */
4711 if (!(th->th_flags & TH_RST))
4712 pf_send_tcp((*state)->rule.ptr, pd->af,
4713 pd->dst, pd->src, th->th_dport,
4714 th->th_sport, ntohl(th->th_ack), 0,
4715 TH_RST, 0, 0,
4716 (*state)->rule.ptr->return_ttl, 1, 0,
4717 pd->eh, kif->pfik_ifp);
4718 src->seqlo = 0;
4719 src->seqhi = 1;
4720 src->max_win = 1;
4721 } else if (pf_status.debug >= PF_DEBUG_MISC) {
4722 kprintf("pf: BAD state: ");
4723 pf_print_state(*state);
4724 pf_print_flags(th->th_flags);
4725 kprintf(" seq=%u (%u) ack=%u len=%u ackskew=%d "
4726 "pkts=%llu:%llu dir=%s,%s\n",
4727 seq, orig_seq, ack, pd->p_len, ackskew,
4728 (unsigned long long)(*state)->packets[0],
4729 (unsigned long long)(*state)->packets[1],
4730 pd->dir == PF_IN ? "in" : "out",
4731 pd->dir == (*state)->direction ? "fwd" : "rev");
4732 kprintf("pf: State failure on: %c %c %c %c | %c %c\n",
4733 SEQ_GEQ(src->seqhi, end) ? ' ' : '1',
4734 SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)) ?
4735 ' ': '2',
4736 (ackskew >= -MAXACKWINDOW) ? ' ' : '3',
4737 (ackskew <= (MAXACKWINDOW << sws)) ? ' ' : '4',
4738 SEQ_GEQ(src->seqhi + MAXACKWINDOW, end) ?' ' :'5',
4739 SEQ_GEQ(seq, src->seqlo - MAXACKWINDOW) ?' ' :'6');
4741 REASON_SET(reason, PFRES_BADSTATE);
4742 return (PF_DROP);
4745 return (PF_PASS);
4749 * Called with state locked
4752 pf_tcp_track_sloppy(struct pf_state_peer *src, struct pf_state_peer *dst,
4753 struct pf_state **state, struct pf_pdesc *pd, u_short *reason)
4755 struct tcphdr *th = pd->hdr.tcp;
4757 if (th->th_flags & TH_SYN)
4758 if (src->state < TCPS_SYN_SENT)
4759 src->state = TCPS_SYN_SENT;
4760 if (th->th_flags & TH_FIN)
4761 if (src->state < TCPS_CLOSING)
4762 src->state = TCPS_CLOSING;
4763 if (th->th_flags & TH_ACK) {
4764 if (dst->state == TCPS_SYN_SENT) {
4765 dst->state = TCPS_ESTABLISHED;
4766 if (src->state == TCPS_ESTABLISHED &&
4767 (*state)->src_node != NULL &&
4768 pf_src_connlimit(*state)) {
4769 REASON_SET(reason, PFRES_SRCLIMIT);
4770 return (PF_DROP);
4772 } else if (dst->state == TCPS_CLOSING) {
4773 dst->state = TCPS_FIN_WAIT_2;
4774 } else if (src->state == TCPS_SYN_SENT &&
4775 dst->state < TCPS_SYN_SENT) {
4777 * Handle a special sloppy case where we only see one
4778 * half of the connection. If there is a ACK after
4779 * the initial SYN without ever seeing a packet from
4780 * the destination, set the connection to established.
4782 dst->state = src->state = TCPS_ESTABLISHED;
4783 if ((*state)->src_node != NULL &&
4784 pf_src_connlimit(*state)) {
4785 REASON_SET(reason, PFRES_SRCLIMIT);
4786 return (PF_DROP);
4788 } else if (src->state == TCPS_CLOSING &&
4789 dst->state == TCPS_ESTABLISHED &&
4790 dst->seqlo == 0) {
4792 * Handle the closing of half connections where we
4793 * don't see the full bidirectional FIN/ACK+ACK
4794 * handshake.
4796 dst->state = TCPS_CLOSING;
4799 if (th->th_flags & TH_RST)
4800 src->state = dst->state = TCPS_TIME_WAIT;
4802 /* update expire time */
4803 (*state)->expire = time_second;
4804 if (src->state >= TCPS_FIN_WAIT_2 &&
4805 dst->state >= TCPS_FIN_WAIT_2)
4806 (*state)->timeout = PFTM_TCP_CLOSED;
4807 else if (src->state >= TCPS_CLOSING &&
4808 dst->state >= TCPS_CLOSING)
4809 (*state)->timeout = PFTM_TCP_FIN_WAIT;
4810 else if (src->state < TCPS_ESTABLISHED ||
4811 dst->state < TCPS_ESTABLISHED)
4812 (*state)->timeout = PFTM_TCP_OPENING;
4813 else if (src->state >= TCPS_CLOSING ||
4814 dst->state >= TCPS_CLOSING)
4815 (*state)->timeout = PFTM_TCP_CLOSING;
4816 else
4817 (*state)->timeout = PFTM_TCP_ESTABLISHED;
4819 return (PF_PASS);
4823 * Test TCP connection state. Caller must hold the state locked.
4826 pf_test_state_tcp(struct pf_state **state, int direction, struct pfi_kif *kif,
4827 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
4828 u_short *reason)
4830 struct pf_state_key_cmp key;
4831 struct tcphdr *th = pd->hdr.tcp;
4832 int copyback = 0;
4833 int error;
4834 struct pf_state_peer *src, *dst;
4835 struct pf_state_key *sk;
4837 bzero(&key, sizeof(key));
4838 key.af = pd->af;
4839 key.proto = IPPROTO_TCP;
4840 if (direction == PF_IN) { /* wire side, straight */
4841 PF_ACPY(&key.addr[0], pd->src, key.af);
4842 PF_ACPY(&key.addr[1], pd->dst, key.af);
4843 key.port[0] = th->th_sport;
4844 key.port[1] = th->th_dport;
4845 if (pf_status.debug >= PF_DEBUG_MISC) {
4846 kprintf("test-tcp IN (%08x:%d) -> (%08x:%d)\n",
4847 ntohl(key.addr[0].addr32[0]),
4848 ntohs(key.port[0]),
4849 ntohl(key.addr[1].addr32[0]),
4850 ntohs(key.port[1]));
4852 } else { /* stack side, reverse */
4853 PF_ACPY(&key.addr[1], pd->src, key.af);
4854 PF_ACPY(&key.addr[0], pd->dst, key.af);
4855 key.port[1] = th->th_sport;
4856 key.port[0] = th->th_dport;
4857 if (pf_status.debug >= PF_DEBUG_MISC) {
4858 kprintf("test-tcp OUT (%08x:%d) <- (%08x:%d)\n",
4859 ntohl(key.addr[0].addr32[0]),
4860 ntohs(key.port[0]),
4861 ntohl(key.addr[1].addr32[0]),
4862 ntohs(key.port[1]));
4866 STATE_LOOKUP(kif, &key, direction, *state, m);
4867 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
4869 if (direction == (*state)->direction) {
4870 src = &(*state)->src;
4871 dst = &(*state)->dst;
4872 } else {
4873 src = &(*state)->dst;
4874 dst = &(*state)->src;
4877 sk = (*state)->key[pd->didx];
4879 if ((*state)->src.state == PF_TCPS_PROXY_SRC) {
4880 if (direction != (*state)->direction) {
4881 REASON_SET(reason, PFRES_SYNPROXY);
4882 FAIL (PF_SYNPROXY_DROP);
4884 if (th->th_flags & TH_SYN) {
4885 if (ntohl(th->th_seq) != (*state)->src.seqlo) {
4886 REASON_SET(reason, PFRES_SYNPROXY);
4887 FAIL (PF_DROP);
4889 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4890 pd->src, th->th_dport, th->th_sport,
4891 (*state)->src.seqhi, ntohl(th->th_seq) + 1,
4892 TH_SYN|TH_ACK, 0, (*state)->src.mss, 0, 1,
4893 0, NULL, NULL);
4894 REASON_SET(reason, PFRES_SYNPROXY);
4895 FAIL (PF_SYNPROXY_DROP);
4896 } else if (!(th->th_flags & TH_ACK) ||
4897 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4898 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4899 REASON_SET(reason, PFRES_SYNPROXY);
4900 FAIL (PF_DROP);
4901 } else if ((*state)->src_node != NULL &&
4902 pf_src_connlimit(*state)) {
4903 REASON_SET(reason, PFRES_SRCLIMIT);
4904 FAIL (PF_DROP);
4905 } else
4906 (*state)->src.state = PF_TCPS_PROXY_DST;
4908 if ((*state)->src.state == PF_TCPS_PROXY_DST) {
4909 if (direction == (*state)->direction) {
4910 if (((th->th_flags & (TH_SYN|TH_ACK)) != TH_ACK) ||
4911 (ntohl(th->th_ack) != (*state)->src.seqhi + 1) ||
4912 (ntohl(th->th_seq) != (*state)->src.seqlo + 1)) {
4913 REASON_SET(reason, PFRES_SYNPROXY);
4914 FAIL (PF_DROP);
4916 (*state)->src.max_win = MAX(ntohs(th->th_win), 1);
4917 if ((*state)->dst.seqhi == 1)
4918 (*state)->dst.seqhi = htonl(karc4random());
4919 pf_send_tcp((*state)->rule.ptr, pd->af,
4920 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4921 sk->port[pd->sidx], sk->port[pd->didx],
4922 (*state)->dst.seqhi, 0, TH_SYN, 0,
4923 (*state)->src.mss, 0, 0, (*state)->tag, NULL, NULL);
4924 REASON_SET(reason, PFRES_SYNPROXY);
4925 FAIL (PF_SYNPROXY_DROP);
4926 } else if (((th->th_flags & (TH_SYN|TH_ACK)) !=
4927 (TH_SYN|TH_ACK)) ||
4928 (ntohl(th->th_ack) != (*state)->dst.seqhi + 1)) {
4929 REASON_SET(reason, PFRES_SYNPROXY);
4930 FAIL (PF_DROP);
4931 } else {
4932 (*state)->dst.max_win = MAX(ntohs(th->th_win), 1);
4933 (*state)->dst.seqlo = ntohl(th->th_seq);
4934 pf_send_tcp((*state)->rule.ptr, pd->af, pd->dst,
4935 pd->src, th->th_dport, th->th_sport,
4936 ntohl(th->th_ack), ntohl(th->th_seq) + 1,
4937 TH_ACK, (*state)->src.max_win, 0, 0, 0,
4938 (*state)->tag, NULL, NULL);
4939 pf_send_tcp((*state)->rule.ptr, pd->af,
4940 &sk->addr[pd->sidx], &sk->addr[pd->didx],
4941 sk->port[pd->sidx], sk->port[pd->didx],
4942 (*state)->src.seqhi + 1, (*state)->src.seqlo + 1,
4943 TH_ACK, (*state)->dst.max_win, 0, 0, 1,
4944 0, NULL, NULL);
4945 (*state)->src.seqdiff = (*state)->dst.seqhi -
4946 (*state)->src.seqlo;
4947 (*state)->dst.seqdiff = (*state)->src.seqhi -
4948 (*state)->dst.seqlo;
4949 (*state)->src.seqhi = (*state)->src.seqlo +
4950 (*state)->dst.max_win;
4951 (*state)->dst.seqhi = (*state)->dst.seqlo +
4952 (*state)->src.max_win;
4953 (*state)->src.wscale = (*state)->dst.wscale = 0;
4954 (*state)->src.state = (*state)->dst.state =
4955 TCPS_ESTABLISHED;
4956 REASON_SET(reason, PFRES_SYNPROXY);
4957 FAIL (PF_SYNPROXY_DROP);
4962 * Check for connection (addr+port pair) reuse. We can't actually
4963 * unlink the state if we don't own it.
4965 if (((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN) &&
4966 dst->state >= TCPS_FIN_WAIT_2 &&
4967 src->state >= TCPS_FIN_WAIT_2) {
4968 if (pf_status.debug >= PF_DEBUG_MISC) {
4969 kprintf("pf: state reuse ");
4970 pf_print_state(*state);
4971 pf_print_flags(th->th_flags);
4972 kprintf("\n");
4974 /* XXX make sure it's the same direction ?? */
4975 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
4976 if ((*state)->cpuid == mycpu->gd_cpuid) {
4977 pf_unlink_state(*state);
4978 *state = NULL;
4979 } else {
4980 (*state)->timeout = PFTM_PURGE;
4982 FAIL (PF_DROP);
4985 if ((*state)->state_flags & PFSTATE_SLOPPY) {
4986 if (pf_tcp_track_sloppy(src, dst, state, pd,
4987 reason) == PF_DROP) {
4988 FAIL (PF_DROP);
4990 } else {
4991 if (pf_tcp_track_full(src, dst, state, kif, m, off, pd,
4992 reason, &copyback) == PF_DROP) {
4993 FAIL (PF_DROP);
4997 /* translate source/destination address, if necessary */
4998 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
4999 struct pf_state_key *nk = (*state)->key[pd->didx];
5001 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5002 nk->port[pd->sidx] != th->th_sport) {
5004 * The translated source address may be completely
5005 * unrelated to the saved link header, make sure
5006 * a bridge doesn't try to use it.
5008 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
5009 pf_change_ap(pd->src, &th->th_sport, pd->ip_sum,
5010 &th->th_sum, &nk->addr[pd->sidx],
5011 nk->port[pd->sidx], 0, pd->af);
5014 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5015 nk->port[pd->didx] != th->th_dport) {
5017 * If we don't redispatch the packet will go into
5018 * the protocol stack on the wrong cpu for the
5019 * post-translated address.
5021 pf_change_ap(pd->dst, &th->th_dport, pd->ip_sum,
5022 &th->th_sum, &nk->addr[pd->didx],
5023 nk->port[pd->didx], 0, pd->af);
5025 copyback = 1;
5028 /* Copyback sequence modulation or stateful scrub changes if needed */
5029 if (copyback) {
5030 m->m_flags &= ~M_HASH;
5031 m_copyback(m, off, sizeof(*th), (caddr_t)th);
5034 pfsync_update_state(*state);
5035 error = PF_PASS;
5036 done:
5037 if (*state)
5038 lockmgr(&(*state)->lk, LK_RELEASE);
5039 return (error);
5043 * Test UDP connection state. Caller must hold the state locked.
5046 pf_test_state_udp(struct pf_state **state, int direction, struct pfi_kif *kif,
5047 struct mbuf *m, int off, void *h, struct pf_pdesc *pd)
5049 struct pf_state_peer *src, *dst;
5050 struct pf_state_key_cmp key;
5051 struct udphdr *uh = pd->hdr.udp;
5053 bzero(&key, sizeof(key));
5054 key.af = pd->af;
5055 key.proto = IPPROTO_UDP;
5056 if (direction == PF_IN) { /* wire side, straight */
5057 PF_ACPY(&key.addr[0], pd->src, key.af);
5058 PF_ACPY(&key.addr[1], pd->dst, key.af);
5059 key.port[0] = uh->uh_sport;
5060 key.port[1] = uh->uh_dport;
5061 } else { /* stack side, reverse */
5062 PF_ACPY(&key.addr[1], pd->src, key.af);
5063 PF_ACPY(&key.addr[0], pd->dst, key.af);
5064 key.port[1] = uh->uh_sport;
5065 key.port[0] = uh->uh_dport;
5068 STATE_LOOKUP(kif, &key, direction, *state, m);
5069 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5071 if (direction == (*state)->direction) {
5072 src = &(*state)->src;
5073 dst = &(*state)->dst;
5074 } else {
5075 src = &(*state)->dst;
5076 dst = &(*state)->src;
5079 /* update states */
5080 if (src->state < PFUDPS_SINGLE)
5081 src->state = PFUDPS_SINGLE;
5082 if (dst->state == PFUDPS_SINGLE)
5083 dst->state = PFUDPS_MULTIPLE;
5085 /* update expire time */
5086 (*state)->expire = time_second;
5087 if (src->state == PFUDPS_MULTIPLE && dst->state == PFUDPS_MULTIPLE)
5088 (*state)->timeout = PFTM_UDP_MULTIPLE;
5089 else
5090 (*state)->timeout = PFTM_UDP_SINGLE;
5092 /* translate source/destination address, if necessary */
5093 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5094 struct pf_state_key *nk = (*state)->key[pd->didx];
5096 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], pd->af) ||
5097 nk->port[pd->sidx] != uh->uh_sport) {
5099 * The translated source address may be completely
5100 * unrelated to the saved link header, make sure
5101 * a bridge doesn't try to use it.
5103 m->m_pkthdr.fw_flags &= ~BRIDGE_MBUF_TAGGED;
5104 m->m_flags &= ~M_HASH;
5105 pf_change_ap(pd->src, &uh->uh_sport, pd->ip_sum,
5106 &uh->uh_sum, &nk->addr[pd->sidx],
5107 nk->port[pd->sidx], 1, pd->af);
5110 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], pd->af) ||
5111 nk->port[pd->didx] != uh->uh_dport) {
5113 * If we don't redispatch the packet will go into
5114 * the protocol stack on the wrong cpu for the
5115 * post-translated address.
5117 m->m_flags &= ~M_HASH;
5118 pf_change_ap(pd->dst, &uh->uh_dport, pd->ip_sum,
5119 &uh->uh_sum, &nk->addr[pd->didx],
5120 nk->port[pd->didx], 1, pd->af);
5122 m_copyback(m, off, sizeof(*uh), (caddr_t)uh);
5125 pfsync_update_state(*state);
5126 lockmgr(&(*state)->lk, LK_RELEASE);
5127 return (PF_PASS);
5131 * Test ICMP connection state. Caller must hold the state locked.
5134 pf_test_state_icmp(struct pf_state **state, int direction, struct pfi_kif *kif,
5135 struct mbuf *m, int off, void *h, struct pf_pdesc *pd,
5136 u_short *reason)
5138 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
5139 u_int16_t icmpid = 0, *icmpsum = NULL;
5140 u_int8_t icmptype = 0;
5141 int state_icmp = 0;
5142 int error;
5143 struct pf_state_key_cmp key;
5145 bzero(&key, sizeof(key));
5147 switch (pd->proto) {
5148 #ifdef INET
5149 case IPPROTO_ICMP:
5150 icmptype = pd->hdr.icmp->icmp_type;
5151 icmpid = pd->hdr.icmp->icmp_id;
5152 icmpsum = &pd->hdr.icmp->icmp_cksum;
5154 if (icmptype == ICMP_UNREACH ||
5155 icmptype == ICMP_SOURCEQUENCH ||
5156 icmptype == ICMP_REDIRECT ||
5157 icmptype == ICMP_TIMXCEED ||
5158 icmptype == ICMP_PARAMPROB)
5159 state_icmp++;
5160 break;
5161 #endif /* INET */
5162 #ifdef INET6
5163 case IPPROTO_ICMPV6:
5164 icmptype = pd->hdr.icmp6->icmp6_type;
5165 icmpid = pd->hdr.icmp6->icmp6_id;
5166 icmpsum = &pd->hdr.icmp6->icmp6_cksum;
5168 if (icmptype == ICMP6_DST_UNREACH ||
5169 icmptype == ICMP6_PACKET_TOO_BIG ||
5170 icmptype == ICMP6_TIME_EXCEEDED ||
5171 icmptype == ICMP6_PARAM_PROB)
5172 state_icmp++;
5173 break;
5174 #endif /* INET6 */
5177 if (!state_icmp) {
5180 * ICMP query/reply message not related to a TCP/UDP packet.
5181 * Search for an ICMP state.
5183 key.af = pd->af;
5184 key.proto = pd->proto;
5185 key.port[0] = key.port[1] = icmpid;
5186 if (direction == PF_IN) { /* wire side, straight */
5187 PF_ACPY(&key.addr[0], pd->src, key.af);
5188 PF_ACPY(&key.addr[1], pd->dst, key.af);
5189 } else { /* stack side, reverse */
5190 PF_ACPY(&key.addr[1], pd->src, key.af);
5191 PF_ACPY(&key.addr[0], pd->dst, key.af);
5194 STATE_LOOKUP(kif, &key, direction, *state, m);
5195 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5197 (*state)->expire = time_second;
5198 (*state)->timeout = PFTM_ICMP_ERROR_REPLY;
5200 /* translate source/destination address, if necessary */
5201 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5202 struct pf_state_key *nk = (*state)->key[pd->didx];
5204 switch (pd->af) {
5205 #ifdef INET
5206 case AF_INET:
5207 if (PF_ANEQ(pd->src,
5208 &nk->addr[pd->sidx], AF_INET))
5209 pf_change_a(&saddr->v4.s_addr,
5210 pd->ip_sum,
5211 nk->addr[pd->sidx].v4.s_addr, 0);
5213 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx],
5214 AF_INET))
5215 pf_change_a(&daddr->v4.s_addr,
5216 pd->ip_sum,
5217 nk->addr[pd->didx].v4.s_addr, 0);
5219 if (nk->port[0] !=
5220 pd->hdr.icmp->icmp_id) {
5221 pd->hdr.icmp->icmp_cksum =
5222 pf_cksum_fixup(
5223 pd->hdr.icmp->icmp_cksum, icmpid,
5224 nk->port[pd->sidx], 0);
5225 pd->hdr.icmp->icmp_id =
5226 nk->port[pd->sidx];
5229 m->m_flags &= ~M_HASH;
5230 m_copyback(m, off, ICMP_MINLEN,
5231 (caddr_t)pd->hdr.icmp);
5232 break;
5233 #endif /* INET */
5234 #ifdef INET6
5235 case AF_INET6:
5236 if (PF_ANEQ(pd->src,
5237 &nk->addr[pd->sidx], AF_INET6))
5238 pf_change_a6(saddr,
5239 &pd->hdr.icmp6->icmp6_cksum,
5240 &nk->addr[pd->sidx], 0);
5242 if (PF_ANEQ(pd->dst,
5243 &nk->addr[pd->didx], AF_INET6))
5244 pf_change_a6(daddr,
5245 &pd->hdr.icmp6->icmp6_cksum,
5246 &nk->addr[pd->didx], 0);
5248 m->m_flags &= ~M_HASH;
5249 m_copyback(m, off,
5250 sizeof(struct icmp6_hdr),
5251 (caddr_t)pd->hdr.icmp6);
5252 break;
5253 #endif /* INET6 */
5256 } else {
5258 * ICMP error message in response to a TCP/UDP packet.
5259 * Extract the inner TCP/UDP header and search for that state.
5262 struct pf_pdesc pd2;
5263 #ifdef INET
5264 struct ip h2;
5265 #endif /* INET */
5266 #ifdef INET6
5267 struct ip6_hdr h2_6;
5268 int terminal = 0;
5269 #endif /* INET6 */
5270 int ipoff2;
5271 int off2;
5273 pd2.not_cpu_localized = 1;
5274 pd2.af = pd->af;
5275 /* Payload packet is from the opposite direction. */
5276 pd2.sidx = (direction == PF_IN) ? 1 : 0;
5277 pd2.didx = (direction == PF_IN) ? 0 : 1;
5278 switch (pd->af) {
5279 #ifdef INET
5280 case AF_INET:
5281 /* offset of h2 in mbuf chain */
5282 ipoff2 = off + ICMP_MINLEN;
5284 if (!pf_pull_hdr(m, ipoff2, &h2, sizeof(h2),
5285 NULL, reason, pd2.af)) {
5286 DPFPRINTF(PF_DEBUG_MISC,
5287 ("pf: ICMP error message too short "
5288 "(ip)\n"));
5289 FAIL (PF_DROP);
5292 * ICMP error messages don't refer to non-first
5293 * fragments
5295 if (h2.ip_off & htons(IP_OFFMASK)) {
5296 REASON_SET(reason, PFRES_FRAG);
5297 FAIL (PF_DROP);
5300 /* offset of protocol header that follows h2 */
5301 off2 = ipoff2 + (h2.ip_hl << 2);
5303 pd2.proto = h2.ip_p;
5304 pd2.src = (struct pf_addr *)&h2.ip_src;
5305 pd2.dst = (struct pf_addr *)&h2.ip_dst;
5306 pd2.ip_sum = &h2.ip_sum;
5307 break;
5308 #endif /* INET */
5309 #ifdef INET6
5310 case AF_INET6:
5311 ipoff2 = off + sizeof(struct icmp6_hdr);
5313 if (!pf_pull_hdr(m, ipoff2, &h2_6, sizeof(h2_6),
5314 NULL, reason, pd2.af)) {
5315 DPFPRINTF(PF_DEBUG_MISC,
5316 ("pf: ICMP error message too short "
5317 "(ip6)\n"));
5318 FAIL (PF_DROP);
5320 pd2.proto = h2_6.ip6_nxt;
5321 pd2.src = (struct pf_addr *)&h2_6.ip6_src;
5322 pd2.dst = (struct pf_addr *)&h2_6.ip6_dst;
5323 pd2.ip_sum = NULL;
5324 off2 = ipoff2 + sizeof(h2_6);
5325 do {
5326 switch (pd2.proto) {
5327 case IPPROTO_FRAGMENT:
5329 * ICMPv6 error messages for
5330 * non-first fragments
5332 REASON_SET(reason, PFRES_FRAG);
5333 FAIL (PF_DROP);
5334 case IPPROTO_AH:
5335 case IPPROTO_HOPOPTS:
5336 case IPPROTO_ROUTING:
5337 case IPPROTO_DSTOPTS: {
5338 /* get next header and header length */
5339 struct ip6_ext opt6;
5341 if (!pf_pull_hdr(m, off2, &opt6,
5342 sizeof(opt6), NULL, reason,
5343 pd2.af)) {
5344 DPFPRINTF(PF_DEBUG_MISC,
5345 ("pf: ICMPv6 short opt\n"));
5346 FAIL (PF_DROP);
5348 if (pd2.proto == IPPROTO_AH)
5349 off2 += (opt6.ip6e_len + 2) * 4;
5350 else
5351 off2 += (opt6.ip6e_len + 1) * 8;
5352 pd2.proto = opt6.ip6e_nxt;
5353 /* goto the next header */
5354 break;
5356 default:
5357 terminal++;
5358 break;
5360 } while (!terminal);
5361 break;
5362 #endif /* INET6 */
5363 default:
5364 DPFPRINTF(PF_DEBUG_MISC,
5365 ("pf: ICMP AF %d unknown (ip6)\n", pd->af));
5366 FAIL (PF_DROP);
5367 break;
5370 switch (pd2.proto) {
5371 case IPPROTO_TCP: {
5372 struct tcphdr th;
5373 u_int32_t seq;
5374 struct pf_state_peer *src, *dst;
5375 u_int8_t dws;
5376 int copyback = 0;
5379 * Only the first 8 bytes of the TCP header can be
5380 * expected. Don't access any TCP header fields after
5381 * th_seq, an ackskew test is not possible.
5383 if (!pf_pull_hdr(m, off2, &th, 8, NULL, reason,
5384 pd2.af)) {
5385 DPFPRINTF(PF_DEBUG_MISC,
5386 ("pf: ICMP error message too short "
5387 "(tcp)\n"));
5388 FAIL (PF_DROP);
5391 key.af = pd2.af;
5392 key.proto = IPPROTO_TCP;
5393 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5394 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5395 key.port[pd2.sidx] = th.th_sport;
5396 key.port[pd2.didx] = th.th_dport;
5398 STATE_LOOKUP(kif, &key, direction, *state, m);
5399 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5401 if (direction == (*state)->direction) {
5402 src = &(*state)->dst;
5403 dst = &(*state)->src;
5404 } else {
5405 src = &(*state)->src;
5406 dst = &(*state)->dst;
5409 if (src->wscale && dst->wscale)
5410 dws = dst->wscale & PF_WSCALE_MASK;
5411 else
5412 dws = 0;
5414 /* Demodulate sequence number */
5415 seq = ntohl(th.th_seq) - src->seqdiff;
5416 if (src->seqdiff) {
5417 pf_change_a(&th.th_seq, icmpsum,
5418 htonl(seq), 0);
5419 copyback = 1;
5422 if (!((*state)->state_flags & PFSTATE_SLOPPY) &&
5423 (!SEQ_GEQ(src->seqhi, seq) ||
5424 !SEQ_GEQ(seq, src->seqlo - (dst->max_win << dws)))) {
5425 if (pf_status.debug >= PF_DEBUG_MISC) {
5426 kprintf("pf: BAD ICMP %d:%d ",
5427 icmptype, pd->hdr.icmp->icmp_code);
5428 pf_print_host(pd->src, 0, pd->af);
5429 kprintf(" -> ");
5430 pf_print_host(pd->dst, 0, pd->af);
5431 kprintf(" state: ");
5432 pf_print_state(*state);
5433 kprintf(" seq=%u\n", seq);
5435 REASON_SET(reason, PFRES_BADSTATE);
5436 FAIL (PF_DROP);
5437 } else {
5438 if (pf_status.debug >= PF_DEBUG_MISC) {
5439 kprintf("pf: OK ICMP %d:%d ",
5440 icmptype, pd->hdr.icmp->icmp_code);
5441 pf_print_host(pd->src, 0, pd->af);
5442 kprintf(" -> ");
5443 pf_print_host(pd->dst, 0, pd->af);
5444 kprintf(" state: ");
5445 pf_print_state(*state);
5446 kprintf(" seq=%u\n", seq);
5450 /* translate source/destination address, if necessary */
5451 if ((*state)->key[PF_SK_WIRE] !=
5452 (*state)->key[PF_SK_STACK]) {
5453 struct pf_state_key *nk =
5454 (*state)->key[pd->didx];
5456 if (PF_ANEQ(pd2.src,
5457 &nk->addr[pd2.sidx], pd2.af) ||
5458 nk->port[pd2.sidx] != th.th_sport)
5459 pf_change_icmp(pd2.src, &th.th_sport,
5460 daddr, &nk->addr[pd2.sidx],
5461 nk->port[pd2.sidx], NULL,
5462 pd2.ip_sum, icmpsum,
5463 pd->ip_sum, 0, pd2.af);
5465 if (PF_ANEQ(pd2.dst,
5466 &nk->addr[pd2.didx], pd2.af) ||
5467 nk->port[pd2.didx] != th.th_dport)
5468 pf_change_icmp(pd2.dst, &th.th_dport,
5469 NULL, /* XXX Inbound NAT? */
5470 &nk->addr[pd2.didx],
5471 nk->port[pd2.didx], NULL,
5472 pd2.ip_sum, icmpsum,
5473 pd->ip_sum, 0, pd2.af);
5474 copyback = 1;
5477 if (copyback) {
5478 switch (pd2.af) {
5479 #ifdef INET
5480 case AF_INET:
5481 m_copyback(m, off, ICMP_MINLEN,
5482 (caddr_t)pd->hdr.icmp);
5483 m_copyback(m, ipoff2, sizeof(h2),
5484 (caddr_t)&h2);
5485 break;
5486 #endif /* INET */
5487 #ifdef INET6
5488 case AF_INET6:
5489 m_copyback(m, off,
5490 sizeof(struct icmp6_hdr),
5491 (caddr_t)pd->hdr.icmp6);
5492 m_copyback(m, ipoff2, sizeof(h2_6),
5493 (caddr_t)&h2_6);
5494 break;
5495 #endif /* INET6 */
5497 m->m_flags &= ~M_HASH;
5498 m_copyback(m, off2, 8, (caddr_t)&th);
5500 break;
5502 case IPPROTO_UDP: {
5503 struct udphdr uh;
5505 if (!pf_pull_hdr(m, off2, &uh, sizeof(uh),
5506 NULL, reason, pd2.af)) {
5507 DPFPRINTF(PF_DEBUG_MISC,
5508 ("pf: ICMP error message too short "
5509 "(udp)\n"));
5510 return (PF_DROP);
5513 key.af = pd2.af;
5514 key.proto = IPPROTO_UDP;
5515 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5516 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5517 key.port[pd2.sidx] = uh.uh_sport;
5518 key.port[pd2.didx] = uh.uh_dport;
5520 STATE_LOOKUP(kif, &key, direction, *state, m);
5521 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5523 /* translate source/destination address, if necessary */
5524 if ((*state)->key[PF_SK_WIRE] !=
5525 (*state)->key[PF_SK_STACK]) {
5526 struct pf_state_key *nk =
5527 (*state)->key[pd->didx];
5529 if (PF_ANEQ(pd2.src,
5530 &nk->addr[pd2.sidx], pd2.af) ||
5531 nk->port[pd2.sidx] != uh.uh_sport)
5532 pf_change_icmp(pd2.src, &uh.uh_sport,
5533 daddr, &nk->addr[pd2.sidx],
5534 nk->port[pd2.sidx], &uh.uh_sum,
5535 pd2.ip_sum, icmpsum,
5536 pd->ip_sum, 1, pd2.af);
5538 if (PF_ANEQ(pd2.dst,
5539 &nk->addr[pd2.didx], pd2.af) ||
5540 nk->port[pd2.didx] != uh.uh_dport)
5541 pf_change_icmp(pd2.dst, &uh.uh_dport,
5542 NULL, /* XXX Inbound NAT? */
5543 &nk->addr[pd2.didx],
5544 nk->port[pd2.didx], &uh.uh_sum,
5545 pd2.ip_sum, icmpsum,
5546 pd->ip_sum, 1, pd2.af);
5548 switch (pd2.af) {
5549 #ifdef INET
5550 case AF_INET:
5551 m_copyback(m, off, ICMP_MINLEN,
5552 (caddr_t)pd->hdr.icmp);
5553 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5554 break;
5555 #endif /* INET */
5556 #ifdef INET6
5557 case AF_INET6:
5558 m_copyback(m, off,
5559 sizeof(struct icmp6_hdr),
5560 (caddr_t)pd->hdr.icmp6);
5561 m_copyback(m, ipoff2, sizeof(h2_6),
5562 (caddr_t)&h2_6);
5563 break;
5564 #endif /* INET6 */
5566 m->m_flags &= ~M_HASH;
5567 m_copyback(m, off2, sizeof(uh), (caddr_t)&uh);
5569 break;
5571 #ifdef INET
5572 case IPPROTO_ICMP: {
5573 struct icmp iih;
5575 if (!pf_pull_hdr(m, off2, &iih, ICMP_MINLEN,
5576 NULL, reason, pd2.af)) {
5577 DPFPRINTF(PF_DEBUG_MISC,
5578 ("pf: ICMP error message too short i"
5579 "(icmp)\n"));
5580 return (PF_DROP);
5583 key.af = pd2.af;
5584 key.proto = IPPROTO_ICMP;
5585 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5586 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5587 key.port[0] = key.port[1] = iih.icmp_id;
5589 STATE_LOOKUP(kif, &key, direction, *state, m);
5590 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5592 /* translate source/destination address, if necessary */
5593 if ((*state)->key[PF_SK_WIRE] !=
5594 (*state)->key[PF_SK_STACK]) {
5595 struct pf_state_key *nk =
5596 (*state)->key[pd->didx];
5598 if (PF_ANEQ(pd2.src,
5599 &nk->addr[pd2.sidx], pd2.af) ||
5600 nk->port[pd2.sidx] != iih.icmp_id)
5601 pf_change_icmp(pd2.src, &iih.icmp_id,
5602 daddr, &nk->addr[pd2.sidx],
5603 nk->port[pd2.sidx], NULL,
5604 pd2.ip_sum, icmpsum,
5605 pd->ip_sum, 0, AF_INET);
5607 if (PF_ANEQ(pd2.dst,
5608 &nk->addr[pd2.didx], pd2.af) ||
5609 nk->port[pd2.didx] != iih.icmp_id)
5610 pf_change_icmp(pd2.dst, &iih.icmp_id,
5611 NULL, /* XXX Inbound NAT? */
5612 &nk->addr[pd2.didx],
5613 nk->port[pd2.didx], NULL,
5614 pd2.ip_sum, icmpsum,
5615 pd->ip_sum, 0, AF_INET);
5617 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
5618 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5619 m_copyback(m, off2, ICMP_MINLEN, (caddr_t)&iih);
5620 m->m_flags &= ~M_HASH;
5622 break;
5624 #endif /* INET */
5625 #ifdef INET6
5626 case IPPROTO_ICMPV6: {
5627 struct icmp6_hdr iih;
5629 if (!pf_pull_hdr(m, off2, &iih,
5630 sizeof(struct icmp6_hdr), NULL, reason, pd2.af)) {
5631 DPFPRINTF(PF_DEBUG_MISC,
5632 ("pf: ICMP error message too short "
5633 "(icmp6)\n"));
5634 FAIL (PF_DROP);
5637 key.af = pd2.af;
5638 key.proto = IPPROTO_ICMPV6;
5639 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5640 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5641 key.port[0] = key.port[1] = iih.icmp6_id;
5643 STATE_LOOKUP(kif, &key, direction, *state, m);
5644 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5646 /* translate source/destination address, if necessary */
5647 if ((*state)->key[PF_SK_WIRE] !=
5648 (*state)->key[PF_SK_STACK]) {
5649 struct pf_state_key *nk =
5650 (*state)->key[pd->didx];
5652 if (PF_ANEQ(pd2.src,
5653 &nk->addr[pd2.sidx], pd2.af) ||
5654 nk->port[pd2.sidx] != iih.icmp6_id)
5655 pf_change_icmp(pd2.src, &iih.icmp6_id,
5656 daddr, &nk->addr[pd2.sidx],
5657 nk->port[pd2.sidx], NULL,
5658 pd2.ip_sum, icmpsum,
5659 pd->ip_sum, 0, AF_INET6);
5661 if (PF_ANEQ(pd2.dst,
5662 &nk->addr[pd2.didx], pd2.af) ||
5663 nk->port[pd2.didx] != iih.icmp6_id)
5664 pf_change_icmp(pd2.dst, &iih.icmp6_id,
5665 NULL, /* XXX Inbound NAT? */
5666 &nk->addr[pd2.didx],
5667 nk->port[pd2.didx], NULL,
5668 pd2.ip_sum, icmpsum,
5669 pd->ip_sum, 0, AF_INET6);
5671 m_copyback(m, off, sizeof(struct icmp6_hdr),
5672 (caddr_t)pd->hdr.icmp6);
5673 m_copyback(m, ipoff2, sizeof(h2_6), (caddr_t)&h2_6);
5674 m_copyback(m, off2, sizeof(struct icmp6_hdr),
5675 (caddr_t)&iih);
5676 m->m_flags &= ~M_HASH;
5678 break;
5680 #endif /* INET6 */
5681 default: {
5682 key.af = pd2.af;
5683 key.proto = pd2.proto;
5684 PF_ACPY(&key.addr[pd2.sidx], pd2.src, key.af);
5685 PF_ACPY(&key.addr[pd2.didx], pd2.dst, key.af);
5686 key.port[0] = key.port[1] = 0;
5688 STATE_LOOKUP(kif, &key, direction, *state, m);
5689 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5691 /* translate source/destination address, if necessary */
5692 if ((*state)->key[PF_SK_WIRE] !=
5693 (*state)->key[PF_SK_STACK]) {
5694 struct pf_state_key *nk =
5695 (*state)->key[pd->didx];
5697 if (PF_ANEQ(pd2.src,
5698 &nk->addr[pd2.sidx], pd2.af))
5699 pf_change_icmp(pd2.src, NULL, daddr,
5700 &nk->addr[pd2.sidx], 0, NULL,
5701 pd2.ip_sum, icmpsum,
5702 pd->ip_sum, 0, pd2.af);
5704 if (PF_ANEQ(pd2.dst,
5705 &nk->addr[pd2.didx], pd2.af))
5706 pf_change_icmp(pd2.src, NULL,
5707 NULL, /* XXX Inbound NAT? */
5708 &nk->addr[pd2.didx], 0, NULL,
5709 pd2.ip_sum, icmpsum,
5710 pd->ip_sum, 0, pd2.af);
5712 switch (pd2.af) {
5713 #ifdef INET
5714 case AF_INET:
5715 m_copyback(m, off, ICMP_MINLEN,
5716 (caddr_t)pd->hdr.icmp);
5717 m_copyback(m, ipoff2, sizeof(h2), (caddr_t)&h2);
5718 m->m_flags &= ~M_HASH;
5719 break;
5720 #endif /* INET */
5721 #ifdef INET6
5722 case AF_INET6:
5723 m_copyback(m, off,
5724 sizeof(struct icmp6_hdr),
5725 (caddr_t)pd->hdr.icmp6);
5726 m_copyback(m, ipoff2, sizeof(h2_6),
5727 (caddr_t)&h2_6);
5728 m->m_flags &= ~M_HASH;
5729 break;
5730 #endif /* INET6 */
5733 break;
5738 pfsync_update_state(*state);
5739 error = PF_PASS;
5740 done:
5741 if (*state)
5742 lockmgr(&(*state)->lk, LK_RELEASE);
5743 return (error);
5747 * Test other connection state. Caller must hold the state locked.
5750 pf_test_state_other(struct pf_state **state, int direction, struct pfi_kif *kif,
5751 struct mbuf *m, struct pf_pdesc *pd)
5753 struct pf_state_peer *src, *dst;
5754 struct pf_state_key_cmp key;
5756 bzero(&key, sizeof(key));
5757 key.af = pd->af;
5758 key.proto = pd->proto;
5759 if (direction == PF_IN) {
5760 PF_ACPY(&key.addr[0], pd->src, key.af);
5761 PF_ACPY(&key.addr[1], pd->dst, key.af);
5762 key.port[0] = key.port[1] = 0;
5763 } else {
5764 PF_ACPY(&key.addr[1], pd->src, key.af);
5765 PF_ACPY(&key.addr[0], pd->dst, key.af);
5766 key.port[1] = key.port[0] = 0;
5769 STATE_LOOKUP(kif, &key, direction, *state, m);
5770 lockmgr(&(*state)->lk, LK_EXCLUSIVE);
5772 if (direction == (*state)->direction) {
5773 src = &(*state)->src;
5774 dst = &(*state)->dst;
5775 } else {
5776 src = &(*state)->dst;
5777 dst = &(*state)->src;
5780 /* update states */
5781 if (src->state < PFOTHERS_SINGLE)
5782 src->state = PFOTHERS_SINGLE;
5783 if (dst->state == PFOTHERS_SINGLE)
5784 dst->state = PFOTHERS_MULTIPLE;
5786 /* update expire time */
5787 (*state)->expire = time_second;
5788 if (src->state == PFOTHERS_MULTIPLE && dst->state == PFOTHERS_MULTIPLE)
5789 (*state)->timeout = PFTM_OTHER_MULTIPLE;
5790 else
5791 (*state)->timeout = PFTM_OTHER_SINGLE;
5793 /* translate source/destination address, if necessary */
5794 if ((*state)->key[PF_SK_WIRE] != (*state)->key[PF_SK_STACK]) {
5795 struct pf_state_key *nk = (*state)->key[pd->didx];
5797 KKASSERT(nk);
5798 KKASSERT(pd);
5799 KKASSERT(pd->src);
5800 KKASSERT(pd->dst);
5801 switch (pd->af) {
5802 #ifdef INET
5803 case AF_INET:
5804 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5805 pf_change_a(&pd->src->v4.s_addr,
5806 pd->ip_sum,
5807 nk->addr[pd->sidx].v4.s_addr,
5811 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5812 pf_change_a(&pd->dst->v4.s_addr,
5813 pd->ip_sum,
5814 nk->addr[pd->didx].v4.s_addr,
5817 break;
5818 #endif /* INET */
5819 #ifdef INET6
5820 case AF_INET6:
5821 if (PF_ANEQ(pd->src, &nk->addr[pd->sidx], AF_INET))
5822 PF_ACPY(pd->src, &nk->addr[pd->sidx], pd->af);
5824 if (PF_ANEQ(pd->dst, &nk->addr[pd->didx], AF_INET))
5825 PF_ACPY(pd->dst, &nk->addr[pd->didx], pd->af);
5826 #endif /* INET6 */
5830 pfsync_update_state(*state);
5831 lockmgr(&(*state)->lk, LK_RELEASE);
5832 return (PF_PASS);
5836 * ipoff and off are measured from the start of the mbuf chain.
5837 * h must be at "ipoff" on the mbuf chain.
5839 void *
5840 pf_pull_hdr(struct mbuf *m, int off, void *p, int len,
5841 u_short *actionp, u_short *reasonp, sa_family_t af)
5843 switch (af) {
5844 #ifdef INET
5845 case AF_INET: {
5846 struct ip *h = mtod(m, struct ip *);
5847 u_int16_t fragoff = (h->ip_off & IP_OFFMASK) << 3;
5849 if (fragoff) {
5850 if (fragoff >= len)
5851 ACTION_SET(actionp, PF_PASS);
5852 else {
5853 ACTION_SET(actionp, PF_DROP);
5854 REASON_SET(reasonp, PFRES_FRAG);
5856 return (NULL);
5858 if (m->m_pkthdr.len < off + len ||
5859 h->ip_len < off + len) {
5860 ACTION_SET(actionp, PF_DROP);
5861 REASON_SET(reasonp, PFRES_SHORT);
5862 return (NULL);
5864 break;
5866 #endif /* INET */
5867 #ifdef INET6
5868 case AF_INET6: {
5869 struct ip6_hdr *h = mtod(m, struct ip6_hdr *);
5871 if (m->m_pkthdr.len < off + len ||
5872 (ntohs(h->ip6_plen) + sizeof(struct ip6_hdr)) <
5873 (unsigned)(off + len)) {
5874 ACTION_SET(actionp, PF_DROP);
5875 REASON_SET(reasonp, PFRES_SHORT);
5876 return (NULL);
5878 break;
5880 #endif /* INET6 */
5882 m_copydata(m, off, len, p);
5883 return (p);
5887 pf_routable(struct pf_addr *addr, sa_family_t af, struct pfi_kif *kif)
5889 struct sockaddr_in *dst;
5890 int ret = 1;
5891 int check_mpath;
5892 #ifdef INET6
5893 struct sockaddr_in6 *dst6;
5894 struct route_in6 ro;
5895 #else
5896 struct route ro;
5897 #endif
5898 struct radix_node *rn;
5899 struct rtentry *rt;
5900 struct ifnet *ifp;
5902 check_mpath = 0;
5903 bzero(&ro, sizeof(ro));
5904 switch (af) {
5905 case AF_INET:
5906 dst = satosin(&ro.ro_dst);
5907 dst->sin_family = AF_INET;
5908 dst->sin_len = sizeof(*dst);
5909 dst->sin_addr = addr->v4;
5910 break;
5911 #ifdef INET6
5912 case AF_INET6:
5913 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5914 dst6->sin6_family = AF_INET6;
5915 dst6->sin6_len = sizeof(*dst6);
5916 dst6->sin6_addr = addr->v6;
5917 break;
5918 #endif /* INET6 */
5919 default:
5920 return (0);
5923 /* Skip checks for ipsec interfaces */
5924 if (kif != NULL && kif->pfik_ifp->if_type == IFT_ENC)
5925 goto out;
5927 rtalloc_ign((struct route *)&ro, 0);
5929 if (ro.ro_rt != NULL) {
5930 /* No interface given, this is a no-route check */
5931 if (kif == NULL)
5932 goto out;
5934 if (kif->pfik_ifp == NULL) {
5935 ret = 0;
5936 goto out;
5939 /* Perform uRPF check if passed input interface */
5940 ret = 0;
5941 rn = (struct radix_node *)ro.ro_rt;
5942 do {
5943 rt = (struct rtentry *)rn;
5944 ifp = rt->rt_ifp;
5946 if (kif->pfik_ifp == ifp)
5947 ret = 1;
5948 rn = NULL;
5949 } while (check_mpath == 1 && rn != NULL && ret == 0);
5950 } else
5951 ret = 0;
5952 out:
5953 if (ro.ro_rt != NULL)
5954 RTFREE(ro.ro_rt);
5955 return (ret);
5959 pf_rtlabel_match(struct pf_addr *addr, sa_family_t af, struct pf_addr_wrap *aw)
5961 struct sockaddr_in *dst;
5962 #ifdef INET6
5963 struct sockaddr_in6 *dst6;
5964 struct route_in6 ro;
5965 #else
5966 struct route ro;
5967 #endif
5968 int ret = 0;
5970 ASSERT_LWKT_TOKEN_HELD(&pf_token);
5972 bzero(&ro, sizeof(ro));
5973 switch (af) {
5974 case AF_INET:
5975 dst = satosin(&ro.ro_dst);
5976 dst->sin_family = AF_INET;
5977 dst->sin_len = sizeof(*dst);
5978 dst->sin_addr = addr->v4;
5979 break;
5980 #ifdef INET6
5981 case AF_INET6:
5982 dst6 = (struct sockaddr_in6 *)&ro.ro_dst;
5983 dst6->sin6_family = AF_INET6;
5984 dst6->sin6_len = sizeof(*dst6);
5985 dst6->sin6_addr = addr->v6;
5986 break;
5987 #endif /* INET6 */
5988 default:
5989 return (0);
5992 rtalloc_ign((struct route *)&ro, (RTF_CLONING | RTF_PRCLONING));
5994 if (ro.ro_rt != NULL) {
5995 RTFREE(ro.ro_rt);
5998 return (ret);
6001 #ifdef INET
6002 void
6003 pf_route(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
6004 struct pf_state *s, struct pf_pdesc *pd)
6006 struct mbuf *m0, *m1;
6007 struct route iproute;
6008 struct route *ro = NULL;
6009 struct sockaddr_in *dst;
6010 struct ip *ip;
6011 struct ifnet *ifp = NULL;
6012 struct pf_addr naddr;
6013 struct pf_src_node *sn = NULL;
6014 int error = 0;
6015 int sw_csum;
6016 #ifdef IPSEC
6017 struct m_tag *mtag;
6018 #endif /* IPSEC */
6020 ASSERT_LWKT_TOKEN_HELD(&pf_token);
6022 if (m == NULL || *m == NULL || r == NULL ||
6023 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
6024 panic("pf_route: invalid parameters");
6026 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
6027 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
6028 (*m)->m_pkthdr.pf.routed = 1;
6029 } else {
6030 if ((*m)->m_pkthdr.pf.routed++ > 3) {
6031 m0 = *m;
6032 *m = NULL;
6033 goto bad;
6037 if (r->rt == PF_DUPTO) {
6038 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL) {
6039 return;
6041 } else {
6042 if ((r->rt == PF_REPLYTO) == (r->direction == dir)) {
6043 return;
6045 m0 = *m;
6048 if (m0->m_len < sizeof(struct ip)) {
6049 DPFPRINTF(PF_DEBUG_URGENT,
6050 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
6051 goto bad;
6054 ip = mtod(m0, struct ip *);
6056 ro = &iproute;
6057 bzero((caddr_t)ro, sizeof(*ro));
6058 dst = satosin(&ro->ro_dst);
6059 dst->sin_family = AF_INET;
6060 dst->sin_len = sizeof(*dst);
6061 dst->sin_addr = ip->ip_dst;
6063 if (r->rt == PF_FASTROUTE) {
6064 rtalloc(ro);
6065 if (ro->ro_rt == 0) {
6066 ipstat.ips_noroute++;
6067 goto bad;
6070 ifp = ro->ro_rt->rt_ifp;
6071 ro->ro_rt->rt_use++;
6073 if (ro->ro_rt->rt_flags & RTF_GATEWAY)
6074 dst = satosin(ro->ro_rt->rt_gateway);
6075 } else {
6076 if (TAILQ_EMPTY(&r->rpool.list)) {
6077 DPFPRINTF(PF_DEBUG_URGENT,
6078 ("pf_route: TAILQ_EMPTY(&r->rpool.list)\n"));
6079 goto bad;
6081 if (s == NULL) {
6082 pf_map_addr(AF_INET, r, (struct pf_addr *)&ip->ip_src,
6083 &naddr, NULL, &sn);
6084 if (!PF_AZERO(&naddr, AF_INET))
6085 dst->sin_addr.s_addr = naddr.v4.s_addr;
6086 ifp = r->rpool.cur->kif ?
6087 r->rpool.cur->kif->pfik_ifp : NULL;
6088 } else {
6089 if (!PF_AZERO(&s->rt_addr, AF_INET))
6090 dst->sin_addr.s_addr =
6091 s->rt_addr.v4.s_addr;
6092 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6095 if (ifp == NULL)
6096 goto bad;
6098 if (oifp != ifp) {
6099 if (pf_test(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
6100 goto bad;
6101 } else if (m0 == NULL) {
6102 goto done;
6104 if (m0->m_len < sizeof(struct ip)) {
6105 DPFPRINTF(PF_DEBUG_URGENT,
6106 ("pf_route: m0->m_len < sizeof(struct ip)\n"));
6107 goto bad;
6109 ip = mtod(m0, struct ip *);
6112 /* Copied from FreeBSD 5.1-CURRENT ip_output. */
6113 m0->m_pkthdr.csum_flags |= CSUM_IP;
6114 sw_csum = m0->m_pkthdr.csum_flags & ~ifp->if_hwassist;
6115 if (sw_csum & CSUM_DELAY_DATA) {
6116 in_delayed_cksum(m0);
6117 sw_csum &= ~CSUM_DELAY_DATA;
6119 m0->m_pkthdr.csum_flags &= ifp->if_hwassist;
6120 m0->m_pkthdr.csum_iphlen = (ip->ip_hl << 2);
6123 * WARNING! We cannot fragment if the packet was modified from an
6124 * original which expected to be using TSO. In this
6125 * situation we pray that the target interface is
6126 * compatible with the originating interface.
6128 if (ip->ip_len <= ifp->if_mtu ||
6129 (m0->m_pkthdr.csum_flags & CSUM_TSO) ||
6130 ((ifp->if_hwassist & CSUM_FRAGMENT) &&
6131 (ip->ip_off & IP_DF) == 0)) {
6132 ip->ip_len = htons(ip->ip_len);
6133 ip->ip_off = htons(ip->ip_off);
6134 ip->ip_sum = 0;
6135 if (sw_csum & CSUM_DELAY_IP) {
6136 /* From KAME */
6137 if (ip->ip_v == IPVERSION &&
6138 (ip->ip_hl << 2) == sizeof(*ip)) {
6139 ip->ip_sum = in_cksum_hdr(ip);
6140 } else {
6141 ip->ip_sum = in_cksum(m0, ip->ip_hl << 2);
6144 lwkt_reltoken(&pf_token);
6145 error = ifp->if_output(ifp, m0, sintosa(dst), ro->ro_rt);
6146 lwkt_gettoken(&pf_token);
6147 goto done;
6151 * Too large for interface; fragment if possible.
6152 * Must be able to put at least 8 bytes per fragment.
6154 if (ip->ip_off & IP_DF) {
6155 ipstat.ips_cantfrag++;
6156 if (r->rt != PF_DUPTO) {
6157 icmp_error(m0, ICMP_UNREACH, ICMP_UNREACH_NEEDFRAG, 0,
6158 ifp->if_mtu);
6159 goto done;
6160 } else
6161 goto bad;
6164 m1 = m0;
6165 error = ip_fragment(ip, &m0, ifp->if_mtu, ifp->if_hwassist, sw_csum);
6166 if (error) {
6167 goto bad;
6170 for (m0 = m1; m0; m0 = m1) {
6171 m1 = m0->m_nextpkt;
6172 m0->m_nextpkt = 0;
6173 if (error == 0) {
6174 lwkt_reltoken(&pf_token);
6175 error = (*ifp->if_output)(ifp, m0, sintosa(dst),
6176 NULL);
6177 lwkt_gettoken(&pf_token);
6178 } else
6179 m_freem(m0);
6182 if (error == 0)
6183 ipstat.ips_fragmented++;
6185 done:
6186 if (r->rt != PF_DUPTO)
6187 *m = NULL;
6188 if (ro == &iproute && ro->ro_rt)
6189 RTFREE(ro->ro_rt);
6190 return;
6192 bad:
6193 m_freem(m0);
6194 goto done;
6196 #endif /* INET */
6198 #ifdef INET6
6199 void
6200 pf_route6(struct mbuf **m, struct pf_rule *r, int dir, struct ifnet *oifp,
6201 struct pf_state *s, struct pf_pdesc *pd)
6203 struct mbuf *m0;
6204 struct route_in6 ip6route;
6205 struct route_in6 *ro;
6206 struct sockaddr_in6 *dst;
6207 struct ip6_hdr *ip6;
6208 struct ifnet *ifp = NULL;
6209 struct pf_addr naddr;
6210 struct pf_src_node *sn = NULL;
6212 if (m == NULL || *m == NULL || r == NULL ||
6213 (dir != PF_IN && dir != PF_OUT) || oifp == NULL)
6214 panic("pf_route6: invalid parameters");
6216 if (((*m)->m_pkthdr.fw_flags & PF_MBUF_ROUTED) == 0) {
6217 (*m)->m_pkthdr.fw_flags |= PF_MBUF_ROUTED;
6218 (*m)->m_pkthdr.pf.routed = 1;
6219 } else {
6220 if ((*m)->m_pkthdr.pf.routed++ > 3) {
6221 m0 = *m;
6222 *m = NULL;
6223 goto bad;
6227 if (r->rt == PF_DUPTO) {
6228 if ((m0 = m_dup(*m, M_NOWAIT)) == NULL)
6229 return;
6230 } else {
6231 if ((r->rt == PF_REPLYTO) == (r->direction == dir))
6232 return;
6233 m0 = *m;
6236 if (m0->m_len < sizeof(struct ip6_hdr)) {
6237 DPFPRINTF(PF_DEBUG_URGENT,
6238 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
6239 goto bad;
6241 ip6 = mtod(m0, struct ip6_hdr *);
6243 ro = &ip6route;
6244 bzero((caddr_t)ro, sizeof(*ro));
6245 dst = (struct sockaddr_in6 *)&ro->ro_dst;
6246 dst->sin6_family = AF_INET6;
6247 dst->sin6_len = sizeof(*dst);
6248 dst->sin6_addr = ip6->ip6_dst;
6251 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6252 * so make sure pf.flags is clear.
6254 * Cheat. XXX why only in the v6 case???
6256 if (r->rt == PF_FASTROUTE) {
6257 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
6258 m0->m_pkthdr.pf.flags = 0;
6259 /* XXX Re-Check when Upgrading to > 4.4 */
6260 m0->m_pkthdr.pf.statekey = NULL;
6261 ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
6262 return;
6265 if (TAILQ_EMPTY(&r->rpool.list)) {
6266 DPFPRINTF(PF_DEBUG_URGENT,
6267 ("pf_route6: TAILQ_EMPTY(&r->rpool.list)\n"));
6268 goto bad;
6270 if (s == NULL) {
6271 pf_map_addr(AF_INET6, r, (struct pf_addr *)&ip6->ip6_src,
6272 &naddr, NULL, &sn);
6273 if (!PF_AZERO(&naddr, AF_INET6))
6274 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
6275 &naddr, AF_INET6);
6276 ifp = r->rpool.cur->kif ? r->rpool.cur->kif->pfik_ifp : NULL;
6277 } else {
6278 if (!PF_AZERO(&s->rt_addr, AF_INET6))
6279 PF_ACPY((struct pf_addr *)&dst->sin6_addr,
6280 &s->rt_addr, AF_INET6);
6281 ifp = s->rt_kif ? s->rt_kif->pfik_ifp : NULL;
6283 if (ifp == NULL)
6284 goto bad;
6286 if (oifp != ifp) {
6287 if (pf_test6(PF_OUT, ifp, &m0, NULL, NULL) != PF_PASS) {
6288 goto bad;
6289 } else if (m0 == NULL) {
6290 goto done;
6292 if (m0->m_len < sizeof(struct ip6_hdr)) {
6293 DPFPRINTF(PF_DEBUG_URGENT,
6294 ("pf_route6: m0->m_len < sizeof(struct ip6_hdr)\n"));
6295 goto bad;
6297 ip6 = mtod(m0, struct ip6_hdr *);
6301 * If the packet is too large for the outgoing interface,
6302 * send back an icmp6 error.
6304 if (IN6_IS_ADDR_LINKLOCAL(&dst->sin6_addr))
6305 dst->sin6_addr.s6_addr16[1] = htons(ifp->if_index);
6306 if ((u_long)m0->m_pkthdr.len <= ifp->if_mtu) {
6307 nd6_output(ifp, ifp, m0, dst, NULL);
6308 } else {
6309 in6_ifstat_inc(ifp, ifs6_in_toobig);
6310 if (r->rt != PF_DUPTO)
6311 icmp6_error(m0, ICMP6_PACKET_TOO_BIG, 0, ifp->if_mtu);
6312 else
6313 goto bad;
6316 done:
6317 if (r->rt != PF_DUPTO)
6318 *m = NULL;
6319 return;
6321 bad:
6322 m_freem(m0);
6323 goto done;
6325 #endif /* INET6 */
6329 * check protocol (tcp/udp/icmp/icmp6) checksum and set mbuf flag
6330 * off is the offset where the protocol header starts
6331 * len is the total length of protocol header plus payload
6332 * returns 0 when the checksum is valid, otherwise returns 1.
6335 * XXX
6336 * FreeBSD supports cksum offload for the following drivers.
6337 * em(4), gx(4), lge(4), nge(4), ti(4), xl(4)
6338 * If we can make full use of it we would outperform ipfw/ipfilter in
6339 * very heavy traffic.
6340 * I have not tested 'cause I don't have NICs that supports cksum offload.
6341 * (There might be problems. Typical phenomena would be
6342 * 1. No route message for UDP packet.
6343 * 2. No connection acceptance from external hosts regardless of rule set.)
6346 pf_check_proto_cksum(struct mbuf *m, int off, int len, u_int8_t p,
6347 sa_family_t af)
6349 u_int16_t sum = 0;
6350 int hw_assist = 0;
6351 struct ip *ip;
6353 if (off < sizeof(struct ip) || len < sizeof(struct udphdr))
6354 return (1);
6355 if (m->m_pkthdr.len < off + len)
6356 return (1);
6358 switch (p) {
6359 case IPPROTO_TCP:
6360 case IPPROTO_UDP:
6361 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
6362 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6363 sum = m->m_pkthdr.csum_data;
6364 } else {
6365 ip = mtod(m, struct ip *);
6366 sum = in_pseudo(ip->ip_src.s_addr,
6367 ip->ip_dst.s_addr, htonl((u_short)len +
6368 m->m_pkthdr.csum_data + p));
6370 sum ^= 0xffff;
6371 ++hw_assist;
6373 break;
6374 case IPPROTO_ICMP:
6375 #ifdef INET6
6376 case IPPROTO_ICMPV6:
6377 #endif /* INET6 */
6378 break;
6379 default:
6380 return (1);
6383 if (!hw_assist) {
6384 switch (af) {
6385 case AF_INET:
6386 if (p == IPPROTO_ICMP) {
6387 if (m->m_len < off)
6388 return (1);
6389 m->m_data += off;
6390 m->m_len -= off;
6391 sum = in_cksum(m, len);
6392 m->m_data -= off;
6393 m->m_len += off;
6394 } else {
6395 if (m->m_len < sizeof(struct ip))
6396 return (1);
6397 sum = in_cksum_range(m, p, off, len);
6398 if (sum == 0) {
6399 m->m_pkthdr.csum_flags |=
6400 (CSUM_DATA_VALID |
6401 CSUM_PSEUDO_HDR);
6402 m->m_pkthdr.csum_data = 0xffff;
6405 break;
6406 #ifdef INET6
6407 case AF_INET6:
6408 if (m->m_len < sizeof(struct ip6_hdr))
6409 return (1);
6410 sum = in6_cksum(m, p, off, len);
6412 * XXX
6413 * IPv6 H/W cksum off-load not supported yet!
6415 * if (sum == 0) {
6416 * m->m_pkthdr.csum_flags |=
6417 * (CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
6418 * m->m_pkthdr.csum_data = 0xffff;
6421 break;
6422 #endif /* INET6 */
6423 default:
6424 return (1);
6427 if (sum) {
6428 switch (p) {
6429 case IPPROTO_TCP:
6430 tcpstat.tcps_rcvbadsum++;
6431 break;
6432 case IPPROTO_UDP:
6433 udp_stat.udps_badsum++;
6434 break;
6435 case IPPROTO_ICMP:
6436 icmpstat.icps_checksum++;
6437 break;
6438 #ifdef INET6
6439 case IPPROTO_ICMPV6:
6440 icmp6stat.icp6s_checksum++;
6441 break;
6442 #endif /* INET6 */
6444 return (1);
6446 return (0);
6449 struct pf_divert *
6450 pf_find_divert(struct mbuf *m)
6452 struct m_tag *mtag;
6454 if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL)
6455 return (NULL);
6457 return ((struct pf_divert *)(mtag + 1));
6460 struct pf_divert *
6461 pf_get_divert(struct mbuf *m)
6463 struct m_tag *mtag;
6465 if ((mtag = m_tag_find(m, PACKET_TAG_PF_DIVERT, NULL)) == NULL) {
6466 mtag = m_tag_get(PACKET_TAG_PF_DIVERT, sizeof(struct pf_divert),
6467 M_NOWAIT);
6468 if (mtag == NULL)
6469 return (NULL);
6470 bzero(mtag + 1, sizeof(struct pf_divert));
6471 m_tag_prepend(m, mtag);
6474 return ((struct pf_divert *)(mtag + 1));
6477 #ifdef INET
6480 * WARNING: pf_token held shared on entry, THIS IS CPU LOCALIZED CODE
6483 pf_test(int dir, struct ifnet *ifp, struct mbuf **m0,
6484 struct ether_header *eh, struct inpcb *inp)
6486 struct pfi_kif *kif;
6487 u_short action, reason = 0, log = 0;
6488 struct mbuf *m = *m0;
6489 struct ip *h = NULL;
6490 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
6491 struct pf_state *s = NULL;
6492 struct pf_ruleset *ruleset = NULL;
6493 struct pf_pdesc pd;
6494 int off, dirndx;
6495 #ifdef ALTQ
6496 int pqid = 0;
6497 #endif
6499 if (!pf_status.running)
6500 return (PF_PASS);
6502 memset(&pd, 0, sizeof(pd));
6503 #ifdef foo
6504 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6505 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6506 else
6507 #endif
6508 kif = (struct pfi_kif *)ifp->if_pf_kif;
6510 if (kif == NULL) {
6511 DPFPRINTF(PF_DEBUG_URGENT,
6512 ("pf_test: kif == NULL, if_xname %s\n", ifp->if_xname));
6513 return (PF_DROP);
6515 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6516 return (PF_PASS);
6518 #ifdef DIAGNOSTIC
6519 if ((m->m_flags & M_PKTHDR) == 0)
6520 panic("non-M_PKTHDR is passed to pf_test");
6521 #endif /* DIAGNOSTIC */
6523 if (m->m_pkthdr.len < (int)sizeof(*h)) {
6524 action = PF_DROP;
6525 REASON_SET(&reason, PFRES_SHORT);
6526 log = 1;
6527 goto done;
6531 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6532 * so make sure pf.flags is clear.
6534 if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6535 return (PF_PASS);
6536 m->m_pkthdr.pf.flags = 0;
6537 /* Re-Check when updating to > 4.4 */
6538 m->m_pkthdr.pf.statekey = NULL;
6540 /* We do IP header normalization and packet reassembly here */
6541 if (pf_normalize_ip(m0, dir, kif, &reason, &pd) != PF_PASS) {
6542 action = PF_DROP;
6543 goto done;
6545 m = *m0; /* pf_normalize messes with m0 */
6546 h = mtod(m, struct ip *);
6548 off = h->ip_hl << 2;
6549 if (off < (int)sizeof(*h)) {
6550 action = PF_DROP;
6551 REASON_SET(&reason, PFRES_SHORT);
6552 log = 1;
6553 goto done;
6556 pd.src = (struct pf_addr *)&h->ip_src;
6557 pd.dst = (struct pf_addr *)&h->ip_dst;
6558 pd.sport = pd.dport = NULL;
6559 pd.ip_sum = &h->ip_sum;
6560 pd.proto_sum = NULL;
6561 pd.proto = h->ip_p;
6562 pd.dir = dir;
6563 pd.sidx = (dir == PF_IN) ? 0 : 1;
6564 pd.didx = (dir == PF_IN) ? 1 : 0;
6565 pd.af = AF_INET;
6566 pd.tos = h->ip_tos;
6567 pd.tot_len = h->ip_len;
6568 pd.eh = eh;
6570 /* handle fragments that didn't get reassembled by normalization */
6571 if (h->ip_off & (IP_MF | IP_OFFMASK)) {
6572 action = pf_test_fragment(&r, dir, kif, m, h,
6573 &pd, &a, &ruleset);
6574 goto done;
6577 switch (h->ip_p) {
6579 case IPPROTO_TCP: {
6580 struct tcphdr th;
6582 pd.hdr.tcp = &th;
6583 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6584 &action, &reason, AF_INET)) {
6585 log = action != PF_PASS;
6586 goto done;
6588 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6589 #ifdef ALTQ
6590 if ((th.th_flags & TH_ACK) && pd.p_len == 0)
6591 pqid = 1;
6592 #endif
6593 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6594 if (action == PF_DROP)
6595 goto done;
6596 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6597 &reason);
6598 if (action == PF_PASS) {
6599 r = s->rule.ptr;
6600 a = s->anchor.ptr;
6601 log = s->log;
6602 } else if (s == NULL) {
6603 action = pf_test_rule(&r, &s, dir, kif,
6604 m, off, h, &pd, &a,
6605 &ruleset, NULL, inp);
6607 break;
6610 case IPPROTO_UDP: {
6611 struct udphdr uh;
6613 pd.hdr.udp = &uh;
6614 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
6615 &action, &reason, AF_INET)) {
6616 log = action != PF_PASS;
6617 goto done;
6619 if (uh.uh_dport == 0 ||
6620 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
6621 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
6622 action = PF_DROP;
6623 REASON_SET(&reason, PFRES_SHORT);
6624 goto done;
6626 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
6627 if (action == PF_PASS) {
6628 r = s->rule.ptr;
6629 a = s->anchor.ptr;
6630 log = s->log;
6631 } else if (s == NULL) {
6632 action = pf_test_rule(&r, &s, dir, kif,
6633 m, off, h, &pd, &a,
6634 &ruleset, NULL, inp);
6636 break;
6639 case IPPROTO_ICMP: {
6640 struct icmp ih;
6642 pd.hdr.icmp = &ih;
6643 if (!pf_pull_hdr(m, off, &ih, ICMP_MINLEN,
6644 &action, &reason, AF_INET)) {
6645 log = action != PF_PASS;
6646 goto done;
6648 action = pf_test_state_icmp(&s, dir, kif, m, off, h, &pd,
6649 &reason);
6650 if (action == PF_PASS) {
6651 r = s->rule.ptr;
6652 a = s->anchor.ptr;
6653 log = s->log;
6654 } else if (s == NULL) {
6655 action = pf_test_rule(&r, &s, dir, kif,
6656 m, off, h, &pd, &a,
6657 &ruleset, NULL, inp);
6659 break;
6662 default:
6663 action = pf_test_state_other(&s, dir, kif, m, &pd);
6664 if (action == PF_PASS) {
6665 r = s->rule.ptr;
6666 a = s->anchor.ptr;
6667 log = s->log;
6668 } else if (s == NULL) {
6669 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
6670 &pd, &a, &ruleset, NULL, inp);
6672 break;
6675 done:
6676 if (action == PF_PASS && h->ip_hl > 5 &&
6677 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
6678 action = PF_DROP;
6679 REASON_SET(&reason, PFRES_IPOPTIONS);
6680 log = 1;
6681 DPFPRINTF(PF_DEBUG_MISC,
6682 ("pf: dropping packet with ip options\n"));
6685 if ((s && s->tag) || r->rtableid)
6686 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
6688 #if 0
6689 if (dir == PF_IN && s && s->key[PF_SK_STACK])
6690 m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
6691 #endif
6693 #ifdef ALTQ
6695 * Generate a hash code and qid request for ALTQ. A qid of 0
6696 * is allowed and will cause altq to select the default queue.
6698 if (action == PF_PASS) {
6699 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
6700 if (pqid || (pd.tos & IPTOS_LOWDELAY))
6701 m->m_pkthdr.pf.qid = r->pqid;
6702 else
6703 m->m_pkthdr.pf.qid = r->qid;
6704 m->m_pkthdr.pf.ecn_af = AF_INET;
6705 m->m_pkthdr.pf.hdr = h;
6706 /* add connection hash for fairq */
6707 if (s) {
6708 /* for fairq */
6709 m->m_pkthdr.pf.state_hash = s->hash;
6710 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
6713 #endif /* ALTQ */
6716 * connections redirected to loopback should not match sockets
6717 * bound specifically to loopback due to security implications,
6718 * see tcp_input() and in_pcblookup_listen().
6720 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
6721 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
6722 (s->nat_rule.ptr->action == PF_RDR ||
6723 s->nat_rule.ptr->action == PF_BINAT) &&
6724 (ntohl(pd.dst->v4.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
6725 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
6727 if (dir == PF_IN && action == PF_PASS && r->divert.port) {
6728 struct pf_divert *divert;
6730 if ((divert = pf_get_divert(m))) {
6731 m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
6732 divert->port = r->divert.port;
6733 divert->addr.ipv4 = r->divert.addr.v4;
6737 if (log) {
6738 struct pf_rule *lr;
6740 if (s != NULL && s->nat_rule.ptr != NULL &&
6741 s->nat_rule.ptr->log & PF_LOG_ALL)
6742 lr = s->nat_rule.ptr;
6743 else
6744 lr = r;
6745 PFLOG_PACKET(kif, h, m, AF_INET, dir, reason, lr, a, ruleset,
6746 &pd);
6749 kif->pfik_bytes[0][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
6750 kif->pfik_packets[0][dir == PF_OUT][action != PF_PASS]++;
6752 if (action == PF_PASS || r->action == PF_DROP) {
6753 dirndx = (dir == PF_OUT);
6754 r->packets[dirndx]++;
6755 r->bytes[dirndx] += pd.tot_len;
6756 if (a != NULL) {
6757 a->packets[dirndx]++;
6758 a->bytes[dirndx] += pd.tot_len;
6760 if (s != NULL) {
6761 if (s->nat_rule.ptr != NULL) {
6762 s->nat_rule.ptr->packets[dirndx]++;
6763 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
6765 if (s->src_node != NULL) {
6766 s->src_node->packets[dirndx]++;
6767 s->src_node->bytes[dirndx] += pd.tot_len;
6769 if (s->nat_src_node != NULL) {
6770 s->nat_src_node->packets[dirndx]++;
6771 s->nat_src_node->bytes[dirndx] += pd.tot_len;
6773 dirndx = (dir == s->direction) ? 0 : 1;
6774 s->packets[dirndx]++;
6775 s->bytes[dirndx] += pd.tot_len;
6777 tr = r;
6778 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
6779 if (nr != NULL && r == &pf_default_rule)
6780 tr = nr;
6781 if (tr->src.addr.type == PF_ADDR_TABLE)
6782 pfr_update_stats(tr->src.addr.p.tbl,
6783 (s == NULL) ? pd.src :
6784 &s->key[(s->direction == PF_IN)]->
6785 addr[(s->direction == PF_OUT)],
6786 pd.af, pd.tot_len, dir == PF_OUT,
6787 r->action == PF_PASS, tr->src.neg);
6788 if (tr->dst.addr.type == PF_ADDR_TABLE)
6789 pfr_update_stats(tr->dst.addr.p.tbl,
6790 (s == NULL) ? pd.dst :
6791 &s->key[(s->direction == PF_IN)]->
6792 addr[(s->direction == PF_IN)],
6793 pd.af, pd.tot_len, dir == PF_OUT,
6794 r->action == PF_PASS, tr->dst.neg);
6798 if (action == PF_SYNPROXY_DROP) {
6799 m_freem(*m0);
6800 *m0 = NULL;
6801 action = PF_PASS;
6802 } else if (r->rt) {
6803 /* pf_route can free the mbuf causing *m0 to become NULL */
6804 pf_route(m0, r, dir, kif->pfik_ifp, s, &pd);
6807 return (action);
6809 #endif /* INET */
6811 #ifdef INET6
6814 * WARNING: pf_token held shared on entry, THIS IS CPU LOCALIZED CODE
6817 pf_test6(int dir, struct ifnet *ifp, struct mbuf **m0,
6818 struct ether_header *eh, struct inpcb *inp)
6820 struct pfi_kif *kif;
6821 u_short action, reason = 0, log = 0;
6822 struct mbuf *m = *m0, *n = NULL;
6823 struct ip6_hdr *h = NULL;
6824 struct pf_rule *a = NULL, *r = &pf_default_rule, *tr, *nr;
6825 struct pf_state *s = NULL;
6826 struct pf_ruleset *ruleset = NULL;
6827 struct pf_pdesc pd;
6828 int off, terminal = 0, dirndx, rh_cnt = 0;
6830 if (!pf_status.running)
6831 return (PF_PASS);
6833 memset(&pd, 0, sizeof(pd));
6834 #ifdef foo
6835 if (ifp->if_type == IFT_CARP && ifp->if_carpdev)
6836 kif = (struct pfi_kif *)ifp->if_carpdev->if_pf_kif;
6837 else
6838 #endif
6839 kif = (struct pfi_kif *)ifp->if_pf_kif;
6841 if (kif == NULL) {
6842 DPFPRINTF(PF_DEBUG_URGENT,
6843 ("pf_test6: kif == NULL, if_xname %s\n", ifp->if_xname));
6844 return (PF_DROP);
6846 if (kif->pfik_flags & PFI_IFLAG_SKIP)
6847 return (PF_PASS);
6849 #ifdef DIAGNOSTIC
6850 if ((m->m_flags & M_PKTHDR) == 0)
6851 panic("non-M_PKTHDR is passed to pf_test6");
6852 #endif /* DIAGNOSTIC */
6854 if (m->m_pkthdr.len < (int)sizeof(*h)) {
6855 action = PF_DROP;
6856 REASON_SET(&reason, PFRES_SHORT);
6857 log = 1;
6858 goto done;
6862 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
6863 * so make sure pf.flags is clear.
6865 if (m->m_pkthdr.fw_flags & PF_MBUF_TAGGED)
6866 return (PF_PASS);
6867 m->m_pkthdr.pf.flags = 0;
6868 /* Re-Check when updating to > 4.4 */
6869 m->m_pkthdr.pf.statekey = NULL;
6871 /* We do IP header normalization and packet reassembly here */
6872 if (pf_normalize_ip6(m0, dir, kif, &reason, &pd) != PF_PASS) {
6873 action = PF_DROP;
6874 goto done;
6876 m = *m0; /* pf_normalize messes with m0 */
6877 h = mtod(m, struct ip6_hdr *);
6879 #if 1
6881 * we do not support jumbogram yet. if we keep going, zero ip6_plen
6882 * will do something bad, so drop the packet for now.
6884 if (htons(h->ip6_plen) == 0) {
6885 action = PF_DROP;
6886 REASON_SET(&reason, PFRES_NORM); /*XXX*/
6887 goto done;
6889 #endif
6891 pd.src = (struct pf_addr *)&h->ip6_src;
6892 pd.dst = (struct pf_addr *)&h->ip6_dst;
6893 pd.sport = pd.dport = NULL;
6894 pd.ip_sum = NULL;
6895 pd.proto_sum = NULL;
6896 pd.dir = dir;
6897 pd.sidx = (dir == PF_IN) ? 0 : 1;
6898 pd.didx = (dir == PF_IN) ? 1 : 0;
6899 pd.af = AF_INET6;
6900 pd.tos = 0;
6901 pd.tot_len = ntohs(h->ip6_plen) + sizeof(struct ip6_hdr);
6902 pd.eh = eh;
6904 off = ((caddr_t)h - m->m_data) + sizeof(struct ip6_hdr);
6905 pd.proto = h->ip6_nxt;
6906 do {
6907 switch (pd.proto) {
6908 case IPPROTO_FRAGMENT:
6909 action = pf_test_fragment(&r, dir, kif, m, h,
6910 &pd, &a, &ruleset);
6911 if (action == PF_DROP)
6912 REASON_SET(&reason, PFRES_FRAG);
6913 goto done;
6914 case IPPROTO_ROUTING: {
6915 struct ip6_rthdr rthdr;
6917 if (rh_cnt++) {
6918 DPFPRINTF(PF_DEBUG_MISC,
6919 ("pf: IPv6 more than one rthdr\n"));
6920 action = PF_DROP;
6921 REASON_SET(&reason, PFRES_IPOPTIONS);
6922 log = 1;
6923 goto done;
6925 if (!pf_pull_hdr(m, off, &rthdr, sizeof(rthdr), NULL,
6926 &reason, pd.af)) {
6927 DPFPRINTF(PF_DEBUG_MISC,
6928 ("pf: IPv6 short rthdr\n"));
6929 action = PF_DROP;
6930 REASON_SET(&reason, PFRES_SHORT);
6931 log = 1;
6932 goto done;
6934 if (rthdr.ip6r_type == IPV6_RTHDR_TYPE_0) {
6935 DPFPRINTF(PF_DEBUG_MISC,
6936 ("pf: IPv6 rthdr0\n"));
6937 action = PF_DROP;
6938 REASON_SET(&reason, PFRES_IPOPTIONS);
6939 log = 1;
6940 goto done;
6942 /* FALLTHROUGH */
6944 case IPPROTO_AH:
6945 case IPPROTO_HOPOPTS:
6946 case IPPROTO_DSTOPTS: {
6947 /* get next header and header length */
6948 struct ip6_ext opt6;
6950 if (!pf_pull_hdr(m, off, &opt6, sizeof(opt6),
6951 NULL, &reason, pd.af)) {
6952 DPFPRINTF(PF_DEBUG_MISC,
6953 ("pf: IPv6 short opt\n"));
6954 action = PF_DROP;
6955 log = 1;
6956 goto done;
6958 if (pd.proto == IPPROTO_AH)
6959 off += (opt6.ip6e_len + 2) * 4;
6960 else
6961 off += (opt6.ip6e_len + 1) * 8;
6962 pd.proto = opt6.ip6e_nxt;
6963 /* goto the next header */
6964 break;
6966 default:
6967 terminal++;
6968 break;
6970 } while (!terminal);
6972 /* if there's no routing header, use unmodified mbuf for checksumming */
6973 if (!n)
6974 n = m;
6976 switch (pd.proto) {
6978 case IPPROTO_TCP: {
6979 struct tcphdr th;
6981 pd.hdr.tcp = &th;
6982 if (!pf_pull_hdr(m, off, &th, sizeof(th),
6983 &action, &reason, AF_INET6)) {
6984 log = action != PF_PASS;
6985 goto done;
6987 pd.p_len = pd.tot_len - off - (th.th_off << 2);
6988 action = pf_normalize_tcp(dir, kif, m, 0, off, h, &pd);
6989 if (action == PF_DROP)
6990 goto done;
6991 action = pf_test_state_tcp(&s, dir, kif, m, off, h, &pd,
6992 &reason);
6993 if (action == PF_PASS) {
6994 r = s->rule.ptr;
6995 a = s->anchor.ptr;
6996 log = s->log;
6997 } else if (s == NULL) {
6998 action = pf_test_rule(&r, &s, dir, kif,
6999 m, off, h, &pd, &a,
7000 &ruleset, NULL, inp);
7002 break;
7005 case IPPROTO_UDP: {
7006 struct udphdr uh;
7008 pd.hdr.udp = &uh;
7009 if (!pf_pull_hdr(m, off, &uh, sizeof(uh),
7010 &action, &reason, AF_INET6)) {
7011 log = action != PF_PASS;
7012 goto done;
7014 if (uh.uh_dport == 0 ||
7015 ntohs(uh.uh_ulen) > m->m_pkthdr.len - off ||
7016 ntohs(uh.uh_ulen) < sizeof(struct udphdr)) {
7017 action = PF_DROP;
7018 REASON_SET(&reason, PFRES_SHORT);
7019 goto done;
7021 action = pf_test_state_udp(&s, dir, kif, m, off, h, &pd);
7022 if (action == PF_PASS) {
7023 r = s->rule.ptr;
7024 a = s->anchor.ptr;
7025 log = s->log;
7026 } else if (s == NULL) {
7027 action = pf_test_rule(&r, &s, dir, kif,
7028 m, off, h, &pd, &a,
7029 &ruleset, NULL, inp);
7031 break;
7034 case IPPROTO_ICMPV6: {
7035 struct icmp6_hdr ih;
7037 pd.hdr.icmp6 = &ih;
7038 if (!pf_pull_hdr(m, off, &ih, sizeof(ih),
7039 &action, &reason, AF_INET6)) {
7040 log = action != PF_PASS;
7041 goto done;
7043 action = pf_test_state_icmp(&s, dir, kif,
7044 m, off, h, &pd, &reason);
7045 if (action == PF_PASS) {
7046 r = s->rule.ptr;
7047 a = s->anchor.ptr;
7048 log = s->log;
7049 } else if (s == NULL) {
7050 action = pf_test_rule(&r, &s, dir, kif,
7051 m, off, h, &pd, &a,
7052 &ruleset, NULL, inp);
7054 break;
7057 default:
7058 action = pf_test_state_other(&s, dir, kif, m, &pd);
7059 if (action == PF_PASS) {
7060 r = s->rule.ptr;
7061 a = s->anchor.ptr;
7062 log = s->log;
7063 } else if (s == NULL) {
7064 action = pf_test_rule(&r, &s, dir, kif, m, off, h,
7065 &pd, &a, &ruleset, NULL, inp);
7067 break;
7070 done:
7071 if (n != m) {
7072 m_freem(n);
7073 n = NULL;
7076 /* handle dangerous IPv6 extension headers. */
7077 if (action == PF_PASS && rh_cnt &&
7078 !((s && s->state_flags & PFSTATE_ALLOWOPTS) || r->allow_opts)) {
7079 action = PF_DROP;
7080 REASON_SET(&reason, PFRES_IPOPTIONS);
7081 log = 1;
7082 DPFPRINTF(PF_DEBUG_MISC,
7083 ("pf: dropping packet with dangerous v6 headers\n"));
7086 if ((s && s->tag) || r->rtableid)
7087 pf_tag_packet(m, s ? s->tag : 0, r->rtableid);
7089 #if 0
7090 if (dir == PF_IN && s && s->key[PF_SK_STACK])
7091 m->m_pkthdr.pf.statekey = s->key[PF_SK_STACK];
7092 #endif
7094 #ifdef ALTQ
7096 * Generate a hash code and qid request for ALTQ. A qid of 0
7097 * is allowed and will cause altq to select the default queue.
7099 if (action == PF_PASS) {
7100 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
7101 if (pd.tos & IPTOS_LOWDELAY)
7102 m->m_pkthdr.pf.qid = r->pqid;
7103 else
7104 m->m_pkthdr.pf.qid = r->qid;
7105 m->m_pkthdr.pf.ecn_af = AF_INET6;
7106 m->m_pkthdr.pf.hdr = h;
7107 if (s) {
7108 /* for fairq */
7109 m->m_pkthdr.pf.state_hash = s->hash;
7110 m->m_pkthdr.pf.flags |= PF_TAG_STATE_HASHED;
7113 #endif /* ALTQ */
7115 if (dir == PF_IN && action == PF_PASS && (pd.proto == IPPROTO_TCP ||
7116 pd.proto == IPPROTO_UDP) && s != NULL && s->nat_rule.ptr != NULL &&
7117 (s->nat_rule.ptr->action == PF_RDR ||
7118 s->nat_rule.ptr->action == PF_BINAT) &&
7119 IN6_IS_ADDR_LOOPBACK(&pd.dst->v6))
7120 m->m_pkthdr.pf.flags |= PF_TAG_TRANSLATE_LOCALHOST;
7122 if (dir == PF_IN && action == PF_PASS && r->divert.port) {
7123 struct pf_divert *divert;
7125 if ((divert = pf_get_divert(m))) {
7126 m->m_pkthdr.pf.flags |= PF_TAG_DIVERTED;
7127 divert->port = r->divert.port;
7128 divert->addr.ipv6 = r->divert.addr.v6;
7132 if (log) {
7133 struct pf_rule *lr;
7135 if (s != NULL && s->nat_rule.ptr != NULL &&
7136 s->nat_rule.ptr->log & PF_LOG_ALL)
7137 lr = s->nat_rule.ptr;
7138 else
7139 lr = r;
7140 PFLOG_PACKET(kif, h, m, AF_INET6, dir, reason, lr, a, ruleset,
7141 &pd);
7144 kif->pfik_bytes[1][dir == PF_OUT][action != PF_PASS] += pd.tot_len;
7145 kif->pfik_packets[1][dir == PF_OUT][action != PF_PASS]++;
7147 if (action == PF_PASS || r->action == PF_DROP) {
7148 dirndx = (dir == PF_OUT);
7149 r->packets[dirndx]++;
7150 r->bytes[dirndx] += pd.tot_len;
7151 if (a != NULL) {
7152 a->packets[dirndx]++;
7153 a->bytes[dirndx] += pd.tot_len;
7155 if (s != NULL) {
7156 if (s->nat_rule.ptr != NULL) {
7157 s->nat_rule.ptr->packets[dirndx]++;
7158 s->nat_rule.ptr->bytes[dirndx] += pd.tot_len;
7160 if (s->src_node != NULL) {
7161 s->src_node->packets[dirndx]++;
7162 s->src_node->bytes[dirndx] += pd.tot_len;
7164 if (s->nat_src_node != NULL) {
7165 s->nat_src_node->packets[dirndx]++;
7166 s->nat_src_node->bytes[dirndx] += pd.tot_len;
7168 dirndx = (dir == s->direction) ? 0 : 1;
7169 s->packets[dirndx]++;
7170 s->bytes[dirndx] += pd.tot_len;
7172 tr = r;
7173 nr = (s != NULL) ? s->nat_rule.ptr : pd.nat_rule;
7174 if (nr != NULL && r == &pf_default_rule)
7175 tr = nr;
7176 if (tr->src.addr.type == PF_ADDR_TABLE)
7177 pfr_update_stats(tr->src.addr.p.tbl,
7178 (s == NULL) ? pd.src :
7179 &s->key[(s->direction == PF_IN)]->addr[0],
7180 pd.af, pd.tot_len, dir == PF_OUT,
7181 r->action == PF_PASS, tr->src.neg);
7182 if (tr->dst.addr.type == PF_ADDR_TABLE)
7183 pfr_update_stats(tr->dst.addr.p.tbl,
7184 (s == NULL) ? pd.dst :
7185 &s->key[(s->direction == PF_IN)]->addr[1],
7186 pd.af, pd.tot_len, dir == PF_OUT,
7187 r->action == PF_PASS, tr->dst.neg);
7191 if (action == PF_SYNPROXY_DROP) {
7192 m_freem(*m0);
7193 *m0 = NULL;
7194 action = PF_PASS;
7195 } else if (r->rt)
7196 /* pf_route6 can free the mbuf causing *m0 to become NULL */
7197 pf_route6(m0, r, dir, kif->pfik_ifp, s, &pd);
7199 return (action);
7201 #endif /* INET6 */
7204 pf_check_congestion(struct ifqueue *ifq)
7206 return (0);