kernel - Allow rn_inithead() to be called early
[dragonfly.git] / sys / net / pf / pf.c
CommitLineData
ed1f0be2 1/* $OpenBSD: pf.c,v 1.614 2008/08/02 12:34:37 henning Exp $ */
02742ec6
JS
2
3/*
4 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 *
6 * Copyright (c) 2001 Daniel Hartmeier
ed1f0be2 7 * Copyright (c) 2002 - 2008 Henning Brauer
02742ec6
JS
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 *
14 * - Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * - Redistributions in binary form must reproduce the above
17 * copyright notice, this list of conditions and the following
18 * disclaimer in the documentation and/or other materials provided
19 * with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 *
34 * Effort sponsored in part by the Defense Advanced Research Projects
35 * Agency (DARPA) and Air Force Research Laboratory, Air Force
36 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
37 *
38 */
39
40#include "opt_inet.h"
41#include "opt_inet6.h"
02742ec6
JS
42
43#include <sys/param.h>
44#include <sys/systm.h>
45#include <sys/malloc.h>
46#include <sys/mbuf.h>
47#include <sys/filio.h>
48#include <sys/socket.h>
49#include <sys/socketvar.h>
50#include <sys/kernel.h>
51#include <sys/time.h>
52#include <sys/sysctl.h>
53#include <sys/endian.h>
54#include <vm/vm_zone.h>
70224baa
JL
55#include <sys/proc.h>
56#include <sys/kthread.h>
02742ec6
JS
57
58#include <machine/inttypes.h>
59
ed1f0be2
JL
60#include <sys/md5.h>
61
02742ec6
JS
62#include <net/if.h>
63#include <net/if_types.h>
64#include <net/bpf.h>
4599cf19 65#include <net/netisr.h>
02742ec6
JS
66#include <net/route.h>
67
68#include <netinet/in.h>
69#include <netinet/in_var.h>
70#include <netinet/in_systm.h>
71#include <netinet/ip.h>
72#include <netinet/ip_var.h>
73#include <netinet/tcp.h>
74#include <netinet/tcp_seq.h>
75#include <netinet/udp.h>
76#include <netinet/ip_icmp.h>
77#include <netinet/in_pcb.h>
78#include <netinet/tcp_timer.h>
79#include <netinet/tcp_var.h>
80#include <netinet/udp_var.h>
81#include <netinet/icmp_var.h>
70224baa 82#include <netinet/if_ether.h>
02742ec6
JS
83
84#include <net/pf/pfvar.h>
85#include <net/pf/if_pflog.h>
86
02742ec6 87#include <net/pf/if_pfsync.h>
02742ec6
JS
88
89#ifdef INET6
90#include <netinet/ip6.h>
91#include <netinet/in_pcb.h>
92#include <netinet/icmp6.h>
93#include <netinet6/nd6.h>
94#include <netinet6/ip6_var.h>
95#include <netinet6/in6_pcb.h>
96#endif /* INET6 */
97
98#include <sys/in_cksum.h>
4599cf19 99#include <sys/ucred.h>
02742ec6
JS
100#include <machine/limits.h>
101#include <sys/msgport2.h>
4599cf19 102#include <net/netmsg2.h>
02742ec6
JS
103
104extern int ip_optcopy(struct ip *, struct ip *);
70224baa 105extern int debug_pfugidhack;
02742ec6 106
a3c18566 107struct lwkt_token pf_token = LWKT_TOKEN_INITIALIZER(pf_token);
2a7a2b1c 108
4b1cf444 109#define DPFPRINTF(n, x) if (pf_status.debug >= (n)) kprintf x
02742ec6
JS
110
111/*
112 * Global variables
113 */
114
b4628cf9
SZ
115/* mask radix tree */
116struct radix_node_head *pf_maskhead;
117
315a7da3 118/* state tables */
ed1f0be2 119struct pf_state_tree pf_statetbl;
315a7da3 120
02742ec6
JS
121struct pf_altqqueue pf_altqs[2];
122struct pf_palist pf_pabuf;
123struct pf_altqqueue *pf_altqs_active;
124struct pf_altqqueue *pf_altqs_inactive;
125struct pf_status pf_status;
126
127u_int32_t ticket_altqs_active;
128u_int32_t ticket_altqs_inactive;
129int altqs_inactive_open;
130u_int32_t ticket_pabuf;
131
ed1f0be2
JL
132MD5_CTX pf_tcp_secret_ctx;
133u_char pf_tcp_secret[16];
134int pf_tcp_secret_init;
135int pf_tcp_iss_off;
136
70224baa
JL
137struct pf_anchor_stackframe {
138 struct pf_ruleset *rs;
139 struct pf_rule *r;
140 struct pf_anchor_node *parent;
141 struct pf_anchor *child;
142} pf_anchor_stack[64];
02742ec6 143
315a7da3 144vm_zone_t pf_src_tree_pl, pf_rule_pl, pf_pooladdr_pl;
ed1f0be2 145vm_zone_t pf_state_pl, pf_state_key_pl, pf_state_item_pl;
315a7da3 146vm_zone_t pf_altq_pl;
02742ec6
JS
147
148void pf_print_host(struct pf_addr *, u_int16_t, u_int8_t);
02742ec6 149
70224baa
JL
150void pf_init_threshold(struct pf_threshold *, u_int32_t,
151 u_int32_t);
152void pf_add_threshold(struct pf_threshold *);
153int pf_check_threshold(struct pf_threshold *);
154
02742ec6
JS
155void pf_change_ap(struct pf_addr *, u_int16_t *,
156 u_int16_t *, u_int16_t *, struct pf_addr *,
157 u_int16_t, u_int8_t, sa_family_t);
70224baa
JL
158int pf_modulate_sack(struct mbuf *, int, struct pf_pdesc *,
159 struct tcphdr *, struct pf_state_peer *);
02742ec6
JS
160#ifdef INET6
161void pf_change_a6(struct pf_addr *, u_int16_t *,
162 struct pf_addr *, u_int8_t);
163#endif /* INET6 */
164void pf_change_icmp(struct pf_addr *, u_int16_t *,
165 struct pf_addr *, struct pf_addr *, u_int16_t,
166 u_int16_t *, u_int16_t *, u_int16_t *,
167 u_int16_t *, u_int8_t, sa_family_t);
168void pf_send_tcp(const struct pf_rule *, sa_family_t,
169 const struct pf_addr *, const struct pf_addr *,
170 u_int16_t, u_int16_t, u_int32_t, u_int32_t,
70224baa
JL
171 u_int8_t, u_int16_t, u_int16_t, u_int8_t, int,
172 u_int16_t, struct ether_header *, struct ifnet *);
02742ec6
JS
173void pf_send_icmp(struct mbuf *, u_int8_t, u_int8_t,
174 sa_family_t, struct pf_rule *);
175struct pf_rule *pf_match_translation(struct pf_pdesc *, struct mbuf *,
176 int, int, struct pfi_kif *,
177 struct pf_addr *, u_int16_t, struct pf_addr *,
178 u_int16_t, int);
179struct pf_rule *pf_get_translation(struct pf_pdesc *, struct mbuf *,
180 int, int, struct pfi_kif *, struct pf_src_node **,
ed1f0be2
JL
181 struct pf_state_key **, struct pf_state_key **,
182 struct pf_state_key **, struct pf_state_key **,
183 struct pf_addr *, struct pf_addr *,
184 u_int16_t, u_int16_t);
185void pf_detach_state(struct pf_state *);
186int pf_state_key_setup(struct pf_pdesc *, struct pf_rule *,
187 struct pf_state_key **, struct pf_state_key **,
188 struct pf_state_key **, struct pf_state_key **,
189 struct pf_addr *, struct pf_addr *,
190 u_int16_t, u_int16_t);
191void pf_state_key_detach(struct pf_state *, int);
192u_int32_t pf_tcp_iss(struct pf_pdesc *);
315a7da3 193int pf_test_rule(struct pf_rule **, struct pf_state **,
02742ec6
JS
194 int, struct pfi_kif *, struct mbuf *, int,
195 void *, struct pf_pdesc *, struct pf_rule **,
70224baa 196 struct pf_ruleset **, struct ifqueue *, struct inpcb *);
ed1f0be2
JL
197static __inline int pf_create_state(struct pf_rule *, struct pf_rule *,
198 struct pf_rule *, struct pf_pdesc *,
199 struct pf_src_node *, struct pf_state_key *,
200 struct pf_state_key *, struct pf_state_key *,
201 struct pf_state_key *, struct mbuf *, int,
202 u_int16_t, u_int16_t, int *, struct pfi_kif *,
203 struct pf_state **, int, u_int16_t, u_int16_t,
204 int);
02742ec6
JS
205int pf_test_fragment(struct pf_rule **, int,
206 struct pfi_kif *, struct mbuf *, void *,
207 struct pf_pdesc *, struct pf_rule **,
208 struct pf_ruleset **);
ed1f0be2
JL
209int pf_tcp_track_full(struct pf_state_peer *,
210 struct pf_state_peer *, struct pf_state **,
211 struct pfi_kif *, struct mbuf *, int,
212 struct pf_pdesc *, u_short *, int *);
213int pf_tcp_track_sloppy(struct pf_state_peer *,
214 struct pf_state_peer *, struct pf_state **,
215 struct pf_pdesc *, u_short *);
02742ec6
JS
216int pf_test_state_tcp(struct pf_state **, int,
217 struct pfi_kif *, struct mbuf *, int,
218 void *, struct pf_pdesc *, u_short *);
219int pf_test_state_udp(struct pf_state **, int,
220 struct pfi_kif *, struct mbuf *, int,
221 void *, struct pf_pdesc *);
222int pf_test_state_icmp(struct pf_state **, int,
223 struct pfi_kif *, struct mbuf *, int,
70224baa 224 void *, struct pf_pdesc *, u_short *);
02742ec6 225int pf_test_state_other(struct pf_state **, int,
ed1f0be2 226 struct pfi_kif *, struct mbuf *, struct pf_pdesc *);
315a7da3 227void pf_step_into_anchor(int *, struct pf_ruleset **, int,
ed1f0be2 228 struct pf_rule **, struct pf_rule **, int *);
70224baa
JL
229int pf_step_out_of_anchor(int *, struct pf_ruleset **,
230 int, struct pf_rule **, struct pf_rule **,
231 int *);
02742ec6
JS
232void pf_hash(struct pf_addr *, struct pf_addr *,
233 struct pf_poolhashkey *, sa_family_t);
234int pf_map_addr(u_int8_t, struct pf_rule *,
235 struct pf_addr *, struct pf_addr *,
236 struct pf_addr *, struct pf_src_node **);
237int pf_get_sport(sa_family_t, u_int8_t, struct pf_rule *,
238 struct pf_addr *, struct pf_addr *, u_int16_t,
239 struct pf_addr *, u_int16_t*, u_int16_t, u_int16_t,
240 struct pf_src_node **);
241void pf_route(struct mbuf **, struct pf_rule *, int,
70224baa
JL
242 struct ifnet *, struct pf_state *,
243 struct pf_pdesc *);
02742ec6 244void pf_route6(struct mbuf **, struct pf_rule *, int,
70224baa
JL
245 struct ifnet *, struct pf_state *,
246 struct pf_pdesc *);
02742ec6
JS
247u_int8_t pf_get_wscale(struct mbuf *, int, u_int16_t,
248 sa_family_t);
249u_int16_t pf_get_mss(struct mbuf *, int, u_int16_t,
250 sa_family_t);
251u_int16_t pf_calc_mss(struct pf_addr *, sa_family_t,
252 u_int16_t);
253void pf_set_rt_ifp(struct pf_state *,
254 struct pf_addr *);
255int pf_check_proto_cksum(struct mbuf *, int, int,
256 u_int8_t, sa_family_t);
ed1f0be2
JL
257struct pf_divert *pf_get_divert(struct mbuf *);
258void pf_print_state_parts(struct pf_state *,
259 struct pf_state_key *, struct pf_state_key *);
02742ec6
JS
260int pf_addr_wrap_neq(struct pf_addr_wrap *,
261 struct pf_addr_wrap *);
315a7da3 262struct pf_state *pf_find_state(struct pfi_kif *,
ed1f0be2 263 struct pf_state_key_cmp *, u_int, struct mbuf *);
70224baa
JL
264int pf_src_connlimit(struct pf_state **);
265int pf_check_congestion(struct ifqueue *);
266
267extern int pf_end_threads;
268
269struct pf_pool_limit pf_pool_limits[PF_LIMIT_MAX] = {
270 { &pf_state_pl, PFSTATE_HIWAT },
271 { &pf_src_tree_pl, PFSNODE_HIWAT },
272 { &pf_frent_pl, PFFRAG_FRENT_HIWAT },
273 { &pfr_ktable_pl, PFR_KTABLE_HIWAT },
274 { &pfr_kentry_pl, PFR_KENTRY_HIWAT }
275};
02742ec6 276
ed1f0be2 277#define STATE_LOOKUP(i, k, d, s, m) \
02742ec6 278 do { \
ed1f0be2
JL
279 s = pf_find_state(i, k, d, m); \
280 if (s == NULL || (s)->timeout == PFTM_PURGE) \
02742ec6 281 return (PF_DROP); \
ed1f0be2
JL
282 if (d == PF_OUT && \
283 (((s)->rule.ptr->rt == PF_ROUTETO && \
284 (s)->rule.ptr->direction == PF_OUT) || \
285 ((s)->rule.ptr->rt == PF_REPLYTO && \
286 (s)->rule.ptr->direction == PF_IN)) && \
287 (s)->rt_kif != NULL && \
288 (s)->rt_kif != i) \
02742ec6
JS
289 return (PF_PASS); \
290 } while (0)
291
70224baa
JL
292#define BOUND_IFACE(r, k) \
293 ((r)->rule_flag & PFRULE_IFBOUND) ? (k) : pfi_all
294
295#define STATE_INC_COUNTERS(s) \
296 do { \
ed1f0be2
JL
297 s->rule.ptr->states_cur++; \
298 s->rule.ptr->states_tot++; \
299 if (s->anchor.ptr != NULL) { \
300 s->anchor.ptr->states_cur++; \
301 s->anchor.ptr->states_tot++; \
302 } \
303 if (s->nat_rule.ptr != NULL) { \
304 s->nat_rule.ptr->states_cur++; \
305 s->nat_rule.ptr->states_tot++; \
306 } \
70224baa
JL
307 } while (0)
308
309#define STATE_DEC_COUNTERS(s) \
310 do { \
311 if (s->nat_rule.ptr != NULL) \
ed1f0be2 312 s->nat_rule.ptr->states_cur--; \
70224baa 313 if (s->anchor.ptr != NULL) \
ed1f0be2
JL
314 s->anchor.ptr->states_cur--; \
315 s->rule.ptr->states_cur--; \
70224baa 316 } while (0)
02742ec6 317
70224baa 318static __inline int pf_src_compare(struct pf_src_node *, struct pf_src_node *);
ed1f0be2 319static __inline int pf_state_compare_key(struct pf_state_key *,
315a7da3 320 struct pf_state_key *);
70224baa 321static __inline int pf_state_compare_id(struct pf_state *,
02742ec6
JS
322 struct pf_state *);
323
324struct pf_src_tree tree_src_tracking;
325
326struct pf_state_tree_id tree_id;
70224baa 327struct pf_state_queue state_list;
02742ec6
JS
328
329RB_GENERATE(pf_src_tree, pf_src_node, entry, pf_src_compare);
ed1f0be2 330RB_GENERATE(pf_state_tree, pf_state_key, entry, pf_state_compare_key);
02742ec6 331RB_GENERATE(pf_state_tree_id, pf_state,
315a7da3
JL
332 entry_id, pf_state_compare_id);
333
70224baa 334static __inline int
02742ec6
JS
335pf_src_compare(struct pf_src_node *a, struct pf_src_node *b)
336{
337 int diff;
338
339 if (a->rule.ptr > b->rule.ptr)
340 return (1);
341 if (a->rule.ptr < b->rule.ptr)
342 return (-1);
343 if ((diff = a->af - b->af) != 0)
344 return (diff);
345 switch (a->af) {
346#ifdef INET
347 case AF_INET:
348 if (a->addr.addr32[0] > b->addr.addr32[0])
349 return (1);
350 if (a->addr.addr32[0] < b->addr.addr32[0])
351 return (-1);
352 break;
353#endif /* INET */
354#ifdef INET6
355 case AF_INET6:
356 if (a->addr.addr32[3] > b->addr.addr32[3])
357 return (1);
358 if (a->addr.addr32[3] < b->addr.addr32[3])
359 return (-1);
360 if (a->addr.addr32[2] > b->addr.addr32[2])
361 return (1);
362 if (a->addr.addr32[2] < b->addr.addr32[2])
363 return (-1);
364 if (a->addr.addr32[1] > b->addr.addr32[1])
365 return (1);
366 if (a->addr.addr32[1] < b->addr.addr32[1])
367 return (-1);
368 if (a->addr.addr32[0] > b->addr.addr32[0])
369 return (1);
370 if (a->addr.addr32[0] < b->addr.addr32[0])
371 return (-1);
372 break;
373#endif /* INET6 */
374 }
375 return (0);
376}
377
a814431a 378u_int32_t
315a7da3 379pf_state_hash(struct pf_state_key *sk)
5950bf01 380{
ed1f0be2 381 u_int32_t hv = (u_int32_t)(((intptr_t)sk >> 6) ^ ((intptr_t)sk >> 15));
a814431a
MD
382 if (hv == 0) /* disallow 0 */
383 hv = 1;
5950bf01
MD
384 return(hv);
385}
386
02742ec6
JS
387#ifdef INET6
388void
389pf_addrcpy(struct pf_addr *dst, struct pf_addr *src, sa_family_t af)
390{
391 switch (af) {
392#ifdef INET
393 case AF_INET:
394 dst->addr32[0] = src->addr32[0];
395 break;
396#endif /* INET */
397 case AF_INET6:
398 dst->addr32[0] = src->addr32[0];
399 dst->addr32[1] = src->addr32[1];
400 dst->addr32[2] = src->addr32[2];
401 dst->addr32[3] = src->addr32[3];
402 break;
403 }
404}
70224baa 405#endif /* INET6 */
02742ec6 406
70224baa
JL
407void
408pf_init_threshold(struct pf_threshold *threshold,
409 u_int32_t limit, u_int32_t seconds)
410{
411 threshold->limit = limit * PF_THRESHOLD_MULT;
412 threshold->seconds = seconds;
413 threshold->count = 0;
414 threshold->last = time_second;
415}
416
417void
418pf_add_threshold(struct pf_threshold *threshold)
419{
420 u_int32_t t = time_second, diff = t - threshold->last;
421
422 if (diff >= threshold->seconds)
423 threshold->count = 0;
424 else
425 threshold->count -= threshold->count * diff /
426 threshold->seconds;
427 threshold->count += PF_THRESHOLD_MULT;
428 threshold->last = t;
429}
430
431int
432pf_check_threshold(struct pf_threshold *threshold)
433{
434 return (threshold->count > threshold->limit);
435}
436
437int
438pf_src_connlimit(struct pf_state **state)
439{
70224baa
JL
440 int bad = 0;
441
442 (*state)->src_node->conn++;
443 (*state)->src.tcp_est = 1;
444 pf_add_threshold(&(*state)->src_node->conn_rate);
445
446 if ((*state)->rule.ptr->max_src_conn &&
447 (*state)->rule.ptr->max_src_conn <
448 (*state)->src_node->conn) {
449 pf_status.lcounters[LCNT_SRCCONN]++;
450 bad++;
451 }
452
453 if ((*state)->rule.ptr->max_src_conn_rate.limit &&
454 pf_check_threshold(&(*state)->src_node->conn_rate)) {
455 pf_status.lcounters[LCNT_SRCCONNRATE]++;
456 bad++;
457 }
458
459 if (!bad)
460 return (0);
461
462 if ((*state)->rule.ptr->overload_tbl) {
463 struct pfr_addr p;
464 u_int32_t killed = 0;
465
466 pf_status.lcounters[LCNT_OVERLOAD_TABLE]++;
467 if (pf_status.debug >= PF_DEBUG_MISC) {
468 kprintf("pf_src_connlimit: blocking address ");
469 pf_print_host(&(*state)->src_node->addr, 0,
ed1f0be2 470 (*state)->key[PF_SK_WIRE]->af);
70224baa
JL
471 }
472
473 bzero(&p, sizeof(p));
ed1f0be2
JL
474 p.pfra_af = (*state)->key[PF_SK_WIRE]->af;
475 switch ((*state)->key[PF_SK_WIRE]->af) {
70224baa
JL
476#ifdef INET
477 case AF_INET:
478 p.pfra_net = 32;
479 p.pfra_ip4addr = (*state)->src_node->addr.v4;
480 break;
481#endif /* INET */
482#ifdef INET6
483 case AF_INET6:
484 p.pfra_net = 128;
485 p.pfra_ip6addr = (*state)->src_node->addr.v6;
486 break;
487#endif /* INET6 */
488 }
489
490 pfr_insert_kentry((*state)->rule.ptr->overload_tbl,
491 &p, time_second);
492
493 /* kill existing states if that's required. */
494 if ((*state)->rule.ptr->flush) {
315a7da3
JL
495 struct pf_state_key *sk;
496 struct pf_state *st;
70224baa 497
315a7da3
JL
498 pf_status.lcounters[LCNT_OVERLOAD_FLUSH]++;
499 RB_FOREACH(st, pf_state_tree_id, &tree_id) {
ed1f0be2 500 sk = st->key[PF_SK_WIRE];
70224baa
JL
501 /*
502 * Kill states from this source. (Only those
503 * from the same rule if PF_FLUSH_GLOBAL is not
504 * set)
505 */
315a7da3 506 if (sk->af ==
ed1f0be2
JL
507 (*state)->key[PF_SK_WIRE]->af &&
508 (((*state)->direction == PF_OUT &&
70224baa 509 PF_AEQ(&(*state)->src_node->addr,
ed1f0be2
JL
510 &sk->addr[0], sk->af)) ||
511 ((*state)->direction == PF_IN &&
70224baa 512 PF_AEQ(&(*state)->src_node->addr,
ed1f0be2 513 &sk->addr[1], sk->af))) &&
70224baa
JL
514 ((*state)->rule.ptr->flush &
515 PF_FLUSH_GLOBAL ||
315a7da3
JL
516 (*state)->rule.ptr == st->rule.ptr)) {
517 st->timeout = PFTM_PURGE;
518 st->src.state = st->dst.state =
70224baa
JL
519 TCPS_CLOSED;
520 killed++;
521 }
522 }
523 if (pf_status.debug >= PF_DEBUG_MISC)
524 kprintf(", %u states killed", killed);
525 }
526 if (pf_status.debug >= PF_DEBUG_MISC)
527 kprintf("\n");
528 }
529
530 /* kill this state */
531 (*state)->timeout = PFTM_PURGE;
532 (*state)->src.state = (*state)->dst.state = TCPS_CLOSED;
533 return (1);
534}
535
02742ec6
JS
536int
537pf_insert_src_node(struct pf_src_node **sn, struct pf_rule *rule,
538 struct pf_addr *src, sa_family_t af)
539{
540 struct pf_src_node k;
541
542 if (*sn == NULL) {
543 k.af = af;
544 PF_ACPY(&k.addr, src, af);
545 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
546 rule->rpool.opts & PF_POOL_STICKYADDR)
547 k.rule.ptr = rule;
548 else
549 k.rule.ptr = NULL;
550 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
551 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
552 }
553 if (*sn == NULL) {
554 if (!rule->max_src_nodes ||
555 rule->src_nodes < rule->max_src_nodes)
ed1f0be2 556 (*sn) = pool_get(&pf_src_tree_pl, PR_NOWAIT | PR_ZERO);
70224baa
JL
557 else
558 pf_status.lcounters[LCNT_SRCNODES]++;
02742ec6
JS
559 if ((*sn) == NULL)
560 return (-1);
70224baa
JL
561
562 pf_init_threshold(&(*sn)->conn_rate,
563 rule->max_src_conn_rate.limit,
564 rule->max_src_conn_rate.seconds);
565
02742ec6
JS
566 (*sn)->af = af;
567 if (rule->rule_flag & PFRULE_RULESRCTRACK ||
568 rule->rpool.opts & PF_POOL_STICKYADDR)
569 (*sn)->rule.ptr = rule;
570 else
571 (*sn)->rule.ptr = NULL;
572 PF_ACPY(&(*sn)->addr, src, af);
573 if (RB_INSERT(pf_src_tree,
574 &tree_src_tracking, *sn) != NULL) {
575 if (pf_status.debug >= PF_DEBUG_MISC) {
4b1cf444 576 kprintf("pf: src_tree insert failed: ");
02742ec6 577 pf_print_host(&(*sn)->addr, 0, af);
4b1cf444 578 kprintf("\n");
02742ec6
JS
579 }
580 pool_put(&pf_src_tree_pl, *sn);
581 return (-1);
582 }
583 (*sn)->creation = time_second;
584 (*sn)->ruletype = rule->action;
585 if ((*sn)->rule.ptr != NULL)
586 (*sn)->rule.ptr->src_nodes++;
587 pf_status.scounters[SCNT_SRC_NODE_INSERT]++;
588 pf_status.src_nodes++;
589 } else {
590 if (rule->max_src_states &&
70224baa
JL
591 (*sn)->states >= rule->max_src_states) {
592 pf_status.lcounters[LCNT_SRCSTATES]++;
02742ec6 593 return (-1);
70224baa 594 }
02742ec6
JS
595 }
596 return (0);
597}
598
ed1f0be2
JL
599/* state table stuff */
600
601static __inline int
602pf_state_compare_key(struct pf_state_key *a, struct pf_state_key *b)
315a7da3 603{
ed1f0be2
JL
604 int diff;
605
606 if ((diff = a->proto - b->proto) != 0)
607 return (diff);
608 if ((diff = a->af - b->af) != 0)
609 return (diff);
610 switch (a->af) {
611#ifdef INET
612 case AF_INET:
613 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
614 return (1);
615 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
616 return (-1);
617 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
618 return (1);
619 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
620 return (-1);
621 break;
622#endif /* INET */
623#ifdef INET6
624 case AF_INET6:
625 if (a->addr[0].addr32[3] > b->addr[0].addr32[3])
626 return (1);
627 if (a->addr[0].addr32[3] < b->addr[0].addr32[3])
628 return (-1);
629 if (a->addr[1].addr32[3] > b->addr[1].addr32[3])
630 return (1);
631 if (a->addr[1].addr32[3] < b->addr[1].addr32[3])
632 return (-1);
633 if (a->addr[0].addr32[2] > b->addr[0].addr32[2])
634 return (1);
635 if (a->addr[0].addr32[2] < b->addr[0].addr32[2])
636 return (-1);
637 if (a->addr[1].addr32[2] > b->addr[1].addr32[2])
638 return (1);
639 if (a->addr[1].addr32[2] < b->addr[1].addr32[2])
640 return (-1);
641 if (a->addr[0].addr32[1] > b->addr[0].addr32[1])
642 return (1);
643 if (a->addr[0].addr32[1] < b->addr[0].addr32[1])
644 return (-1);
645 if (a->addr[1].addr32[1] > b->addr[1].addr32[1])
646 return (1);
647 if (a->addr[1].addr32[1] < b->addr[1].addr32[1])
648 return (-1);
649 if (a->addr[0].addr32[0] > b->addr[0].addr32[0])
650 return (1);
651 if (a->addr[0].addr32[0] < b->addr[0].addr32[0])
652 return (-1);
653 if (a->addr[1].addr32[0] > b->addr[1].addr32[0])
654 return (1);
655 if (a->addr[1].addr32[0] < b->addr[1].addr32[0])
656 return (-1);
657 break;
658#endif /* INET6 */
315a7da3 659 }
ed1f0be2
JL
660
661 if ((diff = a->port[0] - b->port[0]) != 0)
662 return (diff);
663 if ((diff = a->port[1] - b->port[1]) != 0)
664 return (diff);
665
666 return (0);
667}
668
669static __inline int
670pf_state_compare_id(struct pf_state *a, struct pf_state *b)
671{
672 if (a->id > b->id)
673 return (1);
674 if (a->id < b->id)
675 return (-1);
676 if (a->creatorid > b->creatorid)
677 return (1);
678 if (a->creatorid < b->creatorid)
679 return (-1);
680
681 return (0);
315a7da3
JL
682}
683
02742ec6 684int
ed1f0be2 685pf_state_key_attach(struct pf_state_key *sk, struct pf_state *s, int idx)
02742ec6 686{
ed1f0be2
JL
687 struct pf_state_item *si;
688 struct pf_state_key *cur;
315a7da3 689
ed1f0be2 690 KKASSERT(s->key[idx] == NULL); /* XXX handle this? */
315a7da3 691
ed1f0be2 692 if ((cur = RB_INSERT(pf_state_tree, &pf_statetbl, sk)) != NULL) {
315a7da3 693 /* key exists. check for same kif, if none, add to key */
ed1f0be2
JL
694 TAILQ_FOREACH(si, &cur->states, entry)
695 if (si->s->kif == s->kif &&
696 si->s->direction == s->direction) {
697 if (pf_status.debug >= PF_DEBUG_MISC) {
698 kprintf(
699 "pf: %s key attach failed on %s: ",
700 (idx == PF_SK_WIRE) ?
701 "wire" : "stack",
702 s->kif->pfik_name);
703 pf_print_state_parts(s,
704 (idx == PF_SK_WIRE) ? sk : NULL,
705 (idx == PF_SK_STACK) ? sk : NULL);
706 kprintf("\n");
707 }
708 pool_put(&pf_state_key_pl, sk);
709 return (-1); /* collision! */
315a7da3 710 }
ed1f0be2
JL
711 pool_put(&pf_state_key_pl, sk);
712 s->key[idx] = cur;
713 } else
714 s->key[idx] = sk;
02742ec6 715
ed1f0be2
JL
716 if ((si = pool_get(&pf_state_item_pl, PR_NOWAIT)) == NULL) {
717 pf_state_key_detach(s, idx);
02742ec6
JS
718 return (-1);
719 }
ed1f0be2 720 si->s = s;
02742ec6 721
ed1f0be2
JL
722 /* list is sorted, if-bound states before floating */
723 if (s->kif == pfi_all)
724 TAILQ_INSERT_TAIL(&s->key[idx]->states, si, entry);
725 else
726 TAILQ_INSERT_HEAD(&s->key[idx]->states, si, entry);
02742ec6
JS
727 return (0);
728}
729
730void
ed1f0be2 731pf_detach_state(struct pf_state *s)
02742ec6 732{
ed1f0be2
JL
733 if (s->key[PF_SK_WIRE] == s->key[PF_SK_STACK])
734 s->key[PF_SK_WIRE] = NULL;
70224baa 735
ed1f0be2
JL
736 if (s->key[PF_SK_STACK] != NULL)
737 pf_state_key_detach(s, PF_SK_STACK);
738
739 if (s->key[PF_SK_WIRE] != NULL)
740 pf_state_key_detach(s, PF_SK_WIRE);
741}
742
743void
744pf_state_key_detach(struct pf_state *s, int idx)
745{
746 struct pf_state_item *si;
747
748 si = TAILQ_FIRST(&s->key[idx]->states);
749 while (si && si->s != s)
750 si = TAILQ_NEXT(si, entry);
751
752 if (si) {
753 TAILQ_REMOVE(&s->key[idx]->states, si, entry);
754 pool_put(&pf_state_item_pl, si);
755 }
756
757 if (TAILQ_EMPTY(&s->key[idx]->states)) {
758 RB_REMOVE(pf_state_tree, &pf_statetbl, s->key[idx]);
759 if (s->key[idx]->reverse)
760 s->key[idx]->reverse->reverse = NULL;
761 if (s->key[idx]->inp)
762 s->key[idx]->inp->inp_pf_sk = NULL;
763 pool_put(&pf_state_key_pl, s->key[idx]);
764 }
765 s->key[idx] = NULL;
766}
767
768struct pf_state_key *
769pf_alloc_state_key(int pool_flags)
770{
771 struct pf_state_key *sk;
772
773 if ((sk = pool_get(&pf_state_key_pl, pool_flags)) == NULL)
774 return (NULL);
775 TAILQ_INIT(&sk->states);
776
777 return (sk);
778}
779
780int
781pf_state_key_setup(struct pf_pdesc *pd, struct pf_rule *nr,
782 struct pf_state_key **skw, struct pf_state_key **sks,
783 struct pf_state_key **skp, struct pf_state_key **nkp,
784 struct pf_addr *saddr, struct pf_addr *daddr,
785 u_int16_t sport, u_int16_t dport)
786{
787 KKASSERT((*skp == NULL && *nkp == NULL));
788
789 if ((*skp = pf_alloc_state_key(PR_NOWAIT | PR_ZERO)) == NULL)
790 return (ENOMEM);
791
792 PF_ACPY(&(*skp)->addr[pd->sidx], saddr, pd->af);
793 PF_ACPY(&(*skp)->addr[pd->didx], daddr, pd->af);
794 (*skp)->port[pd->sidx] = sport;
795 (*skp)->port[pd->didx] = dport;
796 (*skp)->proto = pd->proto;
797 (*skp)->af = pd->af;
798
799 if (nr != NULL) {
800 if ((*nkp = pf_alloc_state_key(PR_NOWAIT | PR_ZERO)) == NULL)
801 return (ENOMEM); /* caller must handle cleanup */
802
803 /* XXX maybe just bcopy and TAILQ_INIT(&(*nkp)->states) */
804 PF_ACPY(&(*nkp)->addr[0], &(*skp)->addr[0], pd->af);
805 PF_ACPY(&(*nkp)->addr[1], &(*skp)->addr[1], pd->af);
806 (*nkp)->port[0] = (*skp)->port[0];
807 (*nkp)->port[1] = (*skp)->port[1];
808 (*nkp)->proto = pd->proto;
809 (*nkp)->af = pd->af;
810 } else
811 *nkp = *skp;
812
813 if (pd->dir == PF_IN) {
814 *skw = *skp;
815 *sks = *nkp;
816 } else {
817 *sks = *skp;
818 *skw = *nkp;
819 }
820 return (0);
821}
822
823
824int
825pf_state_insert(struct pfi_kif *kif, struct pf_state_key *skw,
826 struct pf_state_key *sks, struct pf_state *s)
827{
828 s->kif = kif;
829
830 if (skw == sks) {
831 if (pf_state_key_attach(skw, s, PF_SK_WIRE))
832 return (-1);
833 s->key[PF_SK_STACK] = s->key[PF_SK_WIRE];
834 } else {
835 if (pf_state_key_attach(skw, s, PF_SK_WIRE)) {
836 pool_put(&pf_state_key_pl, sks);
837 return (-1);
838 }
839 if (pf_state_key_attach(sks, s, PF_SK_STACK)) {
840 pf_state_key_detach(s, PF_SK_WIRE);
841 return (-1);
842 }
843 }
844
845 if (s->id == 0 && s->creatorid == 0) {
846 s->id = htobe64(pf_status.stateid++);
847 s->creatorid = pf_status.hostid;
848 }
849 if (RB_INSERT(pf_state_tree_id, &tree_id, s) != NULL) {
850 if (pf_status.debug >= PF_DEBUG_MISC) {
851 kprintf("pf: state insert failed: "
852 "id: %016jx creatorid: %08x",
853 (uintmax_t)be64toh(s->id), ntohl(s->creatorid));
854 if (s->sync_flags & PFSTATE_FROMSYNC)
855 kprintf(" (from sync)");
856 kprintf("\n");
857 }
858 pf_detach_state(s);
859 return (-1);
860 }
861 TAILQ_INSERT_TAIL(&state_list, s, entry_list);
862 pf_status.fcounters[FCNT_STATE_INSERT]++;
863 pf_status.states++;
864 pfi_kif_ref(kif, PFI_KIF_REF_STATE);
865 pfsync_insert_state(s);
866 return (0);
867}
868
869struct pf_state *
870pf_find_state_byid(struct pf_state_cmp *key)
871{
872 pf_status.fcounters[FCNT_STATE_SEARCH]++;
873
874 return (RB_FIND(pf_state_tree_id, &tree_id, (struct pf_state *)key));
875}
876
877struct pf_state *
878pf_find_state(struct pfi_kif *kif, struct pf_state_key_cmp *key, u_int dir,
879 struct mbuf *m)
880{
881 struct pf_state_key *sk;
882 struct pf_state_item *si;
883
884 pf_status.fcounters[FCNT_STATE_SEARCH]++;
885
886 if (dir == PF_OUT && m->m_pkthdr.pf.statekey &&
887 ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse)
888 sk = ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->reverse;
889 else {
890 if ((sk = RB_FIND(pf_state_tree, &pf_statetbl,
891 (struct pf_state_key *)key)) == NULL)
892 return (NULL);
893 if (dir == PF_OUT && m->m_pkthdr.pf.statekey) {
894 ((struct pf_state_key *)
895 m->m_pkthdr.pf.statekey)->reverse = sk;
896 sk->reverse = m->m_pkthdr.pf.statekey;
897 }
898 }
899
900 if (dir == PF_OUT)
901 m->m_pkthdr.pf.statekey = NULL;
902
903 /* list is sorted, if-bound states before floating ones */
904 TAILQ_FOREACH(si, &sk->states, entry)
905 if ((si->s->kif == pfi_all || si->s->kif == kif) &&
906 sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
907 si->s->key[PF_SK_STACK]))
908 return (si->s);
909
910 return (NULL);
911}
912
913struct pf_state *
914pf_find_state_all(struct pf_state_key_cmp *key, u_int dir, int *more)
915{
916 struct pf_state_key *sk;
917 struct pf_state_item *si, *ret = NULL;
918
919 pf_status.fcounters[FCNT_STATE_SEARCH]++;
920
921 sk = RB_FIND(pf_state_tree, &pf_statetbl, (struct pf_state_key *)key);
922
923 if (sk != NULL) {
924 TAILQ_FOREACH(si, &sk->states, entry)
925 if (dir == PF_INOUT ||
926 (sk == (dir == PF_IN ? si->s->key[PF_SK_WIRE] :
927 si->s->key[PF_SK_STACK]))) {
928 if (more == NULL)
929 return (si->s);
930
931 if (ret)
932 (*more)++;
933 else
934 ret = si;
935 }
936 }
937 return (ret ? ret->s : NULL);
938}
939
940/* END state table stuff */
941
942
943void
944pf_purge_thread(void *v)
945{
946 int nloops = 0;
947 int locked = 0;
948
949 lwkt_gettoken(&pf_token);
950 for (;;) {
951 tsleep(pf_purge_thread, PWAIT, "pftm", 1 * hz);
70224baa
JL
952
953 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
954
955 if (pf_end_threads) {
956 pf_purge_expired_states(pf_status.states, 1);
957 pf_purge_expired_fragments();
958 pf_purge_expired_src_nodes(1);
959 pf_end_threads++;
960
961 lockmgr(&pf_consistency_lock, LK_RELEASE);
962 wakeup(pf_purge_thread);
963 kthread_exit();
964 }
965 crit_enter();
966
967 /* process a fraction of the state table every second */
968 if(!pf_purge_expired_states(1 + (pf_status.states
969 / pf_default_rule.timeout[PFTM_INTERVAL]), 0)) {
02742ec6 970
70224baa
JL
971 pf_purge_expired_states(1 + (pf_status.states
972 / pf_default_rule.timeout[PFTM_INTERVAL]), 1);
973 }
02742ec6 974
70224baa
JL
975 /* purge other expired types every PFTM_INTERVAL seconds */
976 if (++nloops >= pf_default_rule.timeout[PFTM_INTERVAL]) {
977 pf_purge_expired_fragments();
978 if (!pf_purge_expired_src_nodes(locked)) {
979 pf_purge_expired_src_nodes(1);
980 }
981 nloops = 0;
982 }
983 crit_exit();
984 lockmgr(&pf_consistency_lock, LK_RELEASE);
985 }
aa1da187 986 lwkt_reltoken(&pf_token);
02742ec6
JS
987}
988
989u_int32_t
990pf_state_expires(const struct pf_state *state)
991{
992 u_int32_t timeout;
993 u_int32_t start;
994 u_int32_t end;
995 u_int32_t states;
996
997 /* handle all PFTM_* > PFTM_MAX here */
998 if (state->timeout == PFTM_PURGE)
999 return (time_second);
1000 if (state->timeout == PFTM_UNTIL_PACKET)
1001 return (0);
70224baa 1002 KKASSERT(state->timeout != PFTM_UNLINKED);
ed1f0be2 1003 KKASSERT(state->timeout < PFTM_MAX);
02742ec6
JS
1004 timeout = state->rule.ptr->timeout[state->timeout];
1005 if (!timeout)
1006 timeout = pf_default_rule.timeout[state->timeout];
1007 start = state->rule.ptr->timeout[PFTM_ADAPTIVE_START];
1008 if (start) {
1009 end = state->rule.ptr->timeout[PFTM_ADAPTIVE_END];
ed1f0be2 1010 states = state->rule.ptr->states_cur;
02742ec6
JS
1011 } else {
1012 start = pf_default_rule.timeout[PFTM_ADAPTIVE_START];
1013 end = pf_default_rule.timeout[PFTM_ADAPTIVE_END];
1014 states = pf_status.states;
1015 }
1016 if (end && states > start && start < end) {
1017 if (states < end)
1018 return (state->expire + timeout * (end - states) /
1019 (end - start));
1020 else
1021 return (time_second);
1022 }
1023 return (state->expire + timeout);
1024}
1025
70224baa
JL
1026int
1027pf_purge_expired_src_nodes(int waslocked)
02742ec6
JS
1028{
1029 struct pf_src_node *cur, *next;
70224baa 1030 int locked = waslocked;
02742ec6
JS
1031
1032 for (cur = RB_MIN(pf_src_tree, &tree_src_tracking); cur; cur = next) {
1033 next = RB_NEXT(pf_src_tree, &tree_src_tracking, cur);
1034
1035 if (cur->states <= 0 && cur->expire <= time_second) {
70224baa
JL
1036 if (! locked) {
1037 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1038 next = RB_NEXT(pf_src_tree,
1039 &tree_src_tracking, cur);
1040 locked = 1;
1041 }
02742ec6
JS
1042 if (cur->rule.ptr != NULL) {
1043 cur->rule.ptr->src_nodes--;
ed1f0be2 1044 if (cur->rule.ptr->states_cur <= 0 &&
02742ec6
JS
1045 cur->rule.ptr->max_src_nodes <= 0)
1046 pf_rm_rule(NULL, cur->rule.ptr);
1047 }
1048 RB_REMOVE(pf_src_tree, &tree_src_tracking, cur);
1049 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
1050 pf_status.src_nodes--;
1051 pool_put(&pf_src_tree_pl, cur);
1052 }
1053 }
70224baa
JL
1054
1055 if (locked && !waslocked)
1056 lockmgr(&pf_consistency_lock, LK_RELEASE);
1057 return(1);
02742ec6
JS
1058}
1059
1060void
1061pf_src_tree_remove_state(struct pf_state *s)
1062{
1063 u_int32_t timeout;
1064
1065 if (s->src_node != NULL) {
05ac5751
JL
1066 if (s->src.tcp_est)
1067 --s->src_node->conn;
02742ec6
JS
1068 if (--s->src_node->states <= 0) {
1069 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1070 if (!timeout)
1071 timeout =
1072 pf_default_rule.timeout[PFTM_SRC_NODE];
1073 s->src_node->expire = time_second + timeout;
1074 }
1075 }
1076 if (s->nat_src_node != s->src_node && s->nat_src_node != NULL) {
1077 if (--s->nat_src_node->states <= 0) {
1078 timeout = s->rule.ptr->timeout[PFTM_SRC_NODE];
1079 if (!timeout)
1080 timeout =
1081 pf_default_rule.timeout[PFTM_SRC_NODE];
1082 s->nat_src_node->expire = time_second + timeout;
1083 }
1084 }
1085 s->src_node = s->nat_src_node = NULL;
1086}
1087
70224baa
JL
1088/* callers should be at crit_enter() */
1089void
1090pf_unlink_state(struct pf_state *cur)
02742ec6 1091{
70224baa 1092 if (cur->src.state == PF_TCPS_PROXY_DST) {
ed1f0be2
JL
1093 /* XXX wire key the right one? */
1094 pf_send_tcp(cur->rule.ptr, cur->key[PF_SK_WIRE]->af,
1095 &cur->key[PF_SK_WIRE]->addr[1],
1096 &cur->key[PF_SK_WIRE]->addr[0],
1097 cur->key[PF_SK_WIRE]->port[1],
1098 cur->key[PF_SK_WIRE]->port[0],
70224baa
JL
1099 cur->src.seqhi, cur->src.seqlo + 1,
1100 TH_RST|TH_ACK, 0, 0, 0, 1, cur->tag, NULL, NULL);
1101 }
70224baa 1102 RB_REMOVE(pf_state_tree_id, &tree_id, cur);
70224baa 1103 if (cur->creatorid == pf_status.hostid)
f0ea6854 1104 pfsync_delete_state(cur);
70224baa
JL
1105 cur->timeout = PFTM_UNLINKED;
1106 pf_src_tree_remove_state(cur);
ed1f0be2 1107 pf_detach_state(cur);
02742ec6
JS
1108}
1109
aa1da187
MD
1110static struct pf_state *purge_cur;
1111
70224baa
JL
1112/* callers should be at crit_enter() and hold the
1113 * write_lock on pf_consistency_lock */
f0ea6854 1114void
70224baa 1115pf_free_state(struct pf_state *cur)
f0ea6854 1116{
70224baa
JL
1117 if (pfsyncif != NULL &&
1118 (pfsyncif->sc_bulk_send_next == cur ||
1119 pfsyncif->sc_bulk_terminator == cur))
1120 return;
70224baa 1121 KKASSERT(cur->timeout == PFTM_UNLINKED);
ed1f0be2 1122 if (--cur->rule.ptr->states_cur <= 0 &&
70224baa
JL
1123 cur->rule.ptr->src_nodes <= 0)
1124 pf_rm_rule(NULL, cur->rule.ptr);
1125 if (cur->nat_rule.ptr != NULL)
ed1f0be2 1126 if (--cur->nat_rule.ptr->states_cur <= 0 &&
70224baa
JL
1127 cur->nat_rule.ptr->src_nodes <= 0)
1128 pf_rm_rule(NULL, cur->nat_rule.ptr);
1129 if (cur->anchor.ptr != NULL)
ed1f0be2 1130 if (--cur->anchor.ptr->states_cur <= 0)
70224baa
JL
1131 pf_rm_rule(NULL, cur->anchor.ptr);
1132 pf_normalize_tcp_cleanup(cur);
315a7da3 1133 pfi_kif_unref(cur->kif, PFI_KIF_REF_STATE);
aa1da187
MD
1134
1135 /*
1136 * We may be freeing pf_purge_expired_states()'s saved scan entry,
1137 * adjust it if necessary.
1138 */
1139 if (purge_cur == cur) {
1140 kprintf("PURGE CONFLICT\n");
1141 purge_cur = TAILQ_NEXT(purge_cur, entry_list);
1142 }
315a7da3 1143 TAILQ_REMOVE(&state_list, cur, entry_list);
70224baa
JL
1144 if (cur->tag)
1145 pf_tag_unref(cur->tag);
1146 pool_put(&pf_state_pl, cur);
1147 pf_status.fcounters[FCNT_STATE_REMOVALS]++;
1148 pf_status.states--;
f0ea6854
MD
1149}
1150
70224baa
JL
1151int
1152pf_purge_expired_states(u_int32_t maxcheck, int waslocked)
1153{
aa1da187 1154 struct pf_state *cur;
70224baa
JL
1155 int locked = waslocked;
1156
1157 while (maxcheck--) {
aa1da187
MD
1158 /*
1159 * Wrap to start of list when we hit the end
1160 */
1161 cur = purge_cur;
70224baa
JL
1162 if (cur == NULL) {
1163 cur = TAILQ_FIRST(&state_list);
1164 if (cur == NULL)
1165 break; /* list empty */
1166 }
1167
aa1da187
MD
1168 /*
1169 * Setup next (purge_cur) while we process this one. If we block and
1170 * something else deletes purge_cur, pf_free_state() will adjust it further
1171 * ahead.
1172 */
1173 purge_cur = TAILQ_NEXT(cur, entry_list);
70224baa
JL
1174
1175 if (cur->timeout == PFTM_UNLINKED) {
1176 /* free unlinked state */
1177 if (! locked) {
1178 lockmgr(&pf_consistency_lock, LK_EXCLUSIVE);
1179 locked = 1;
1180 }
1181 pf_free_state(cur);
1182 } else if (pf_state_expires(cur) <= time_second) {
1183 /* unlink and free expired state */
1184 pf_unlink_state(cur);
1185 if (! locked) {
1186 if (!lockmgr(&pf_consistency_lock, LK_EXCLUSIVE))
1187 return (0);
1188 locked = 1;
1189 }
1190 pf_free_state(cur);
1191 }
70224baa
JL
1192 }
1193
1194 if (locked)
1195 lockmgr(&pf_consistency_lock, LK_RELEASE);
1196 return (1);
1197}
f0ea6854 1198
02742ec6
JS
1199int
1200pf_tbladdr_setup(struct pf_ruleset *rs, struct pf_addr_wrap *aw)
1201{
1202 if (aw->type != PF_ADDR_TABLE)
1203 return (0);
1204 if ((aw->p.tbl = pfr_attach_table(rs, aw->v.tblname)) == NULL)
1205 return (1);
1206 return (0);
1207}
1208
1209void
1210pf_tbladdr_remove(struct pf_addr_wrap *aw)
1211{
1212 if (aw->type != PF_ADDR_TABLE || aw->p.tbl == NULL)
1213 return;
1214 pfr_detach_table(aw->p.tbl);
1215 aw->p.tbl = NULL;
1216}
1217
1218void
1219pf_tbladdr_copyout(struct pf_addr_wrap *aw)
1220{
1221 struct pfr_ktable *kt = aw->p.tbl;
1222
1223 if (aw->type != PF_ADDR_TABLE || kt == NULL)
1224 return;
1225 if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
1226 kt = kt->pfrkt_root;
1227 aw->p.tbl = NULL;
1228 aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
1229 kt->pfrkt_cnt : -1;
1230}
1231
1232void
1233pf_print_host(struct pf_addr *addr, u_int16_t p, sa_family_t af)
1234{
1235 switch (af) {
1236#ifdef INET
1237 case AF_INET: {
1238 u_int32_t a = ntohl(addr->addr32[0]);
4b1cf444 1239 kprintf("%u.%u.%u.%u", (a>>24)&255, (a>>16)&255,
02742ec6
JS
1240 (a>>8)&255, a&255);
1241 if (p) {
1242 p = ntohs(p);
4b1cf444 1243 kprintf(":%u", p);
02742ec6
JS
1244 }
1245 break;
1246 }
1247#endif /* INET */
1248#ifdef INET6
1249 case AF_INET6: {
1250 u_int16_t b;
1251 u_int8_t i, curstart = 255, curend = 0,
1252 maxstart = 0, maxend = 0;
1253 for (i = 0; i < 8; i++) {
1254 if (!addr->addr16[i]) {
1255 if (curstart == 255)
1256 curstart = i;
1257 else
1258 curend = i;
1259 } else {
1260 if (curstart) {
1261 if ((curend - curstart) >
1262 (maxend - maxstart)) {
1263 maxstart = curstart;
1264 maxend = curend;
1265 curstart = 255;
1266 }
1267 }
1268 }
1269 }
1270 for (i = 0; i < 8; i++) {
1271 if (i >= maxstart && i <= maxend) {
1272 if (maxend != 7) {
1273 if (i == maxstart)
4b1cf444 1274 kprintf(":");
02742ec6
JS
1275 } else {
1276 if (i == maxend)
4b1cf444 1277 kprintf(":");
02742ec6
JS
1278 }
1279 } else {
1280 b = ntohs(addr->addr16[i]);
4b1cf444 1281 kprintf("%x", b);
02742ec6 1282 if (i < 7)
4b1cf444 1283 kprintf(":");
02742ec6
JS
1284 }
1285 }
1286 if (p) {
1287 p = ntohs(p);
4b1cf444 1288 kprintf("[%u]", p);
02742ec6
JS
1289 }
1290 break;
1291 }
1292#endif /* INET6 */
1293 }
1294}
1295
1296void
1297pf_print_state(struct pf_state *s)
1298{
ed1f0be2
JL
1299 pf_print_state_parts(s, NULL, NULL);
1300}
1301
1302void
1303pf_print_state_parts(struct pf_state *s,
1304 struct pf_state_key *skwp, struct pf_state_key *sksp)
1305{
1306 struct pf_state_key *skw, *sks;
1307 u_int8_t proto, dir;
1308
1309 /* Do our best to fill these, but they're skipped if NULL */
1310 skw = skwp ? skwp : (s ? s->key[PF_SK_WIRE] : NULL);
1311 sks = sksp ? sksp : (s ? s->key[PF_SK_STACK] : NULL);
1312 proto = skw ? skw->proto : (sks ? sks->proto : 0);
1313 dir = s ? s->direction : 0;
1314
1315 switch (proto) {
02742ec6 1316 case IPPROTO_TCP:
4b1cf444 1317 kprintf("TCP ");
02742ec6
JS
1318 break;
1319 case IPPROTO_UDP:
4b1cf444 1320 kprintf("UDP ");
02742ec6
JS
1321 break;
1322 case IPPROTO_ICMP:
4b1cf444 1323 kprintf("ICMP ");
02742ec6
JS
1324 break;
1325 case IPPROTO_ICMPV6:
4b1cf444 1326 kprintf("ICMPV6 ");
02742ec6
JS
1327 break;
1328 default:
ed1f0be2
JL
1329 kprintf("%u ", skw->proto);
1330 break;
1331 }
1332 switch (dir) {
1333 case PF_IN:
1334 kprintf(" in");
1335 break;
1336 case PF_OUT:
1337 kprintf(" out");
02742ec6
JS
1338 break;
1339 }
ed1f0be2
JL
1340 if (skw) {
1341 kprintf(" wire: ");
1342 pf_print_host(&skw->addr[0], skw->port[0], skw->af);
1343 kprintf(" ");
1344 pf_print_host(&skw->addr[1], skw->port[1], skw->af);
1345 }
1346 if (sks) {
1347 kprintf(" stack: ");
1348 if (sks != skw) {
1349 pf_print_host(&sks->addr[0], sks->port[0], sks->af);
1350 kprintf(" ");
1351 pf_print_host(&sks->addr[1], sks->port[1], sks->af);
1352 } else
1353 kprintf("-");
1354 }
1355 if (s) {
1356 if (proto == IPPROTO_TCP) {
1357 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1358 s->src.seqlo, s->src.seqhi,
1359 s->src.max_win, s->src.seqdiff);
1360 if (s->src.wscale && s->dst.wscale)
1361 kprintf(" wscale=%u",
1362 s->src.wscale & PF_WSCALE_MASK);
1363 kprintf("]");
1364 kprintf(" [lo=%u high=%u win=%u modulator=%u",
1365 s->dst.seqlo, s->dst.seqhi,
1366 s->dst.max_win, s->dst.seqdiff);
1367 if (s->src.wscale && s->dst.wscale)
1368 kprintf(" wscale=%u",
1369 s->dst.wscale & PF_WSCALE_MASK);
1370 kprintf("]");
1371 }
1372 kprintf(" %u:%u", s->src.state, s->dst.state);
1373 }
02742ec6
JS
1374}
1375
1376void
1377pf_print_flags(u_int8_t f)
1378{
1379 if (f)
4b1cf444 1380 kprintf(" ");
02742ec6 1381 if (f & TH_FIN)
4b1cf444 1382 kprintf("F");
02742ec6 1383 if (f & TH_SYN)
4b1cf444 1384 kprintf("S");
02742ec6 1385 if (f & TH_RST)
4b1cf444 1386 kprintf("R");
02742ec6 1387 if (f & TH_PUSH)
4b1cf444 1388 kprintf("P");
02742ec6 1389 if (f & TH_ACK)
4b1cf444 1390 kprintf("A");
02742ec6 1391 if (f & TH_URG)
4b1cf444 1392 kprintf("U");
02742ec6 1393 if (f & TH_ECE)
4b1cf444 1394 kprintf("E");
02742ec6 1395 if (f & TH_CWR)
4b1cf444 1396 kprintf("W");
02742ec6
JS
1397}
1398
1399#define PF_SET_SKIP_STEPS(i) \
1400 do { \
1401 while (head[i] != cur) { \
1402 head[i]->skip[i].ptr = cur; \
1403 head[i] = TAILQ_NEXT(head[i], entries); \
1404 } \
1405 } while (0)
1406
1407void
1408pf_calc_skip_steps(struct pf_rulequeue *rules)
1409{
1410 struct pf_rule *cur, *prev, *head[PF_SKIP_COUNT];
1411 int i;
1412
1413 cur = TAILQ_FIRST(rules);
1414 prev = cur;
1415 for (i = 0; i < PF_SKIP_COUNT; ++i)
1416 head[i] = cur;
1417 while (cur != NULL) {
1418
1419 if (cur->kif != prev->kif || cur->ifnot != prev->ifnot)
1420 PF_SET_SKIP_STEPS(PF_SKIP_IFP);
1421 if (cur->direction != prev->direction)
1422 PF_SET_SKIP_STEPS(PF_SKIP_DIR);
1423 if (cur->af != prev->af)
1424 PF_SET_SKIP_STEPS(PF_SKIP_AF);
1425 if (cur->proto != prev->proto)
1426 PF_SET_SKIP_STEPS(PF_SKIP_PROTO);
70224baa 1427 if (cur->src.neg != prev->src.neg ||
02742ec6
JS
1428 pf_addr_wrap_neq(&cur->src.addr, &prev->src.addr))
1429 PF_SET_SKIP_STEPS(PF_SKIP_SRC_ADDR);
1430 if (cur->src.port[0] != prev->src.port[0] ||
1431 cur->src.port[1] != prev->src.port[1] ||
1432 cur->src.port_op != prev->src.port_op)
1433 PF_SET_SKIP_STEPS(PF_SKIP_SRC_PORT);
70224baa 1434 if (cur->dst.neg != prev->dst.neg ||
02742ec6
JS
1435 pf_addr_wrap_neq(&cur->dst.addr, &prev->dst.addr))
1436 PF_SET_SKIP_STEPS(PF_SKIP_DST_ADDR);
1437 if (cur->dst.port[0] != prev->dst.port[0] ||
1438 cur->dst.port[1] != prev->dst.port[1] ||
1439 cur->dst.port_op != prev->dst.port_op)
1440 PF_SET_SKIP_STEPS(PF_SKIP_DST_PORT);
1441
1442 prev = cur;
1443 cur = TAILQ_NEXT(cur, entries);
1444 }
1445 for (i = 0; i < PF_SKIP_COUNT; ++i)
1446 PF_SET_SKIP_STEPS(i);
1447}
1448
1449int
1450pf_addr_wrap_neq(struct pf_addr_wrap *aw1, struct pf_addr_wrap *aw2)
1451{
1452 if (aw1->type != aw2->type)
1453 return (1);
1454 switch (aw1->type) {
1455 case PF_ADDR_ADDRMASK:
ed1f0be2 1456 case PF_ADDR_RANGE:
02742ec6
JS
1457 if (PF_ANEQ(&aw1->v.a.addr, &aw2->v.a.addr, 0))
1458 return (1);
1459 if (PF_ANEQ(&aw1->v.a.mask, &aw2->v.a.mask, 0))
1460 return (1);
1461 return (0);
1462 case PF_ADDR_DYNIFTL:
1463 return (aw1->p.dyn->pfid_kt != aw2->p.dyn->pfid_kt);
1464 case PF_ADDR_NOROUTE:
70224baa 1465 case PF_ADDR_URPFFAILED:
02742ec6
JS
1466 return (0);
1467 case PF_ADDR_TABLE:
1468 return (aw1->p.tbl != aw2->p.tbl);
70224baa
JL
1469 case PF_ADDR_RTLABEL:
1470 return (aw1->v.rtlabel != aw2->v.rtlabel);
02742ec6 1471 default:
4b1cf444 1472 kprintf("invalid address type: %d\n", aw1->type);
02742ec6
JS
1473 return (1);
1474 }
1475}
1476
02742ec6
JS
1477u_int16_t
1478pf_cksum_fixup(u_int16_t cksum, u_int16_t old, u_int16_t new, u_int8_t udp)
1479{
1480 u_int32_t l;
1481
1482 if (udp && !cksum)
1483 return (0x0000);
1484 l = cksum + old - new;
1485 l = (l >> 16) + (l & 65535);
1486 l = l & 65535;
1487 if (udp && !l)
1488 return (0xFFFF);
1489 return (l);
1490}
1491
1492void
1493pf_change_ap(struct pf_addr *a, u_int16_t *p, u_int16_t *ic, u_int16_t *pc,
1494 struct pf_addr *an, u_int16_t pn, u_int8_t u, sa_family_t af)
1495{
1496 struct pf_addr ao;
1497 u_int16_t po = *p;
1498
1499 PF_ACPY(&ao, a, af);
1500 PF_ACPY(a, an, af);
1501
1502 *p = pn;
1503
1504 switch (af) {
1505#ifdef INET
1506 case AF_INET:
1507 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1508 ao.addr16[0], an->addr16[0], 0),
1509 ao.addr16[1], an->addr16[1], 0);
1510 *p = pn;
1511 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1512 ao.addr16[0], an->addr16[0], u),
1513 ao.addr16[1], an->addr16[1], u),
1514 po, pn, u);
1515 break;
1516#endif /* INET */
1517#ifdef INET6
1518 case AF_INET6:
1519 *pc = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1520 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1521 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(*pc,
1522 ao.addr16[0], an->addr16[0], u),
1523 ao.addr16[1], an->addr16[1], u),
1524 ao.addr16[2], an->addr16[2], u),
1525 ao.addr16[3], an->addr16[3], u),
1526 ao.addr16[4], an->addr16[4], u),
1527 ao.addr16[5], an->addr16[5], u),
1528 ao.addr16[6], an->addr16[6], u),
1529 ao.addr16[7], an->addr16[7], u),
1530 po, pn, u);
1531 break;
1532#endif /* INET6 */
1533 }
1534}
1535
1536
1537/* Changes a u_int32_t. Uses a void * so there are no align restrictions */
1538void
1539pf_change_a(void *a, u_int16_t *c, u_int32_t an, u_int8_t u)
1540{
1541 u_int32_t ao;
1542
1543 memcpy(&ao, a, sizeof(ao));
1544 memcpy(a, &an, sizeof(u_int32_t));
1545 *c = pf_cksum_fixup(pf_cksum_fixup(*c, ao / 65536, an / 65536, u),
1546 ao % 65536, an % 65536, u);
1547}
1548
1549#ifdef INET6
1550void
1551pf_change_a6(struct pf_addr *a, u_int16_t *c, struct pf_addr *an, u_int8_t u)
1552{
1553 struct pf_addr ao;
1554
1555 PF_ACPY(&ao, a, AF_INET6);
1556 PF_ACPY(a, an, AF_INET6);
1557
1558 *c = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1559 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1560 pf_cksum_fixup(pf_cksum_fixup(*c,
1561 ao.addr16[0], an->addr16[0], u),
1562 ao.addr16[1], an->addr16[1], u),
1563 ao.addr16[2], an->addr16[2], u),
1564 ao.addr16[3], an->addr16[3], u),
1565 ao.addr16[4], an->addr16[4], u),
1566 ao.addr16[5], an->addr16[5], u),
1567 ao.addr16[6], an->addr16[6], u),
1568 ao.addr16[7], an->addr16[7], u);
1569}
1570#endif /* INET6 */
1571
1572void
1573pf_change_icmp(struct pf_addr *ia, u_int16_t *ip, struct pf_addr *oa,
1574 struct pf_addr *na, u_int16_t np, u_int16_t *pc, u_int16_t *h2c,
1575 u_int16_t *ic, u_int16_t *hc, u_int8_t u, sa_family_t af)
1576{
1577 struct pf_addr oia, ooa;
1578
1579 PF_ACPY(&oia, ia, af);
ed1f0be2
JL
1580 if (oa)
1581 PF_ACPY(&ooa, oa, af);
02742ec6
JS
1582
1583 /* Change inner protocol port, fix inner protocol checksum. */
1584 if (ip != NULL) {
1585 u_int16_t oip = *ip;
1586 u_int32_t opc = 0;
1587
1588 if (pc != NULL)
1589 opc = *pc;
1590 *ip = np;
1591 if (pc != NULL)
1592 *pc = pf_cksum_fixup(*pc, oip, *ip, u);
1593 *ic = pf_cksum_fixup(*ic, oip, *ip, 0);
1594 if (pc != NULL)
1595 *ic = pf_cksum_fixup(*ic, opc, *pc, 0);
1596 }
1597 /* Change inner ip address, fix inner ip and icmp checksums. */
1598 PF_ACPY(ia, na, af);
1599 switch (af) {
1600#ifdef INET
1601 case AF_INET: {
1602 u_int32_t oh2c = *h2c;
1603
1604 *h2c = pf_cksum_fixup(pf_cksum_fixup(*h2c,
1605 oia.addr16[0], ia->addr16[0], 0),
1606 oia.addr16[1], ia->addr16[1], 0);
1607 *ic = pf_cksum_fixup(pf_cksum_fixup(*ic,
1608 oia.addr16[0], ia->addr16[0], 0),
1609 oia.addr16[1], ia->addr16[1], 0);
1610 *ic = pf_cksum_fixup(*ic, oh2c, *h2c, 0);
1611 break;
1612 }
1613#endif /* INET */
1614#ifdef INET6
1615 case AF_INET6:
1616 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1617 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1618 pf_cksum_fixup(pf_cksum_fixup(*ic,
1619 oia.addr16[0], ia->addr16[0], u),
1620 oia.addr16[1], ia->addr16[1], u),
1621 oia.addr16[2], ia->addr16[2], u),
1622 oia.addr16[3], ia->addr16[3], u),
1623 oia.addr16[4], ia->addr16[4], u),
1624 oia.addr16[5], ia->addr16[5], u),
1625 oia.addr16[6], ia->addr16[6], u),
1626 oia.addr16[7], ia->addr16[7], u);
1627 break;
1628#endif /* INET6 */
1629 }
ed1f0be2
JL
1630 /* Outer ip address, fix outer ip or icmpv6 checksum, if necessary. */
1631 if (oa) {
1632 PF_ACPY(oa, na, af);
1633 switch (af) {
02742ec6 1634#ifdef INET
ed1f0be2
JL
1635 case AF_INET:
1636 *hc = pf_cksum_fixup(pf_cksum_fixup(*hc,
1637 ooa.addr16[0], oa->addr16[0], 0),
1638 ooa.addr16[1], oa->addr16[1], 0);
1639 break;
02742ec6
JS
1640#endif /* INET */
1641#ifdef INET6
ed1f0be2
JL
1642 case AF_INET6:
1643 *ic = pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1644 pf_cksum_fixup(pf_cksum_fixup(pf_cksum_fixup(
1645 pf_cksum_fixup(pf_cksum_fixup(*ic,
1646 ooa.addr16[0], oa->addr16[0], u),
1647 ooa.addr16[1], oa->addr16[1], u),
1648 ooa.addr16[2], oa->addr16[2], u),
1649 ooa.addr16[3], oa->addr16[3], u),
1650 ooa.addr16[4], oa->addr16[4], u),
1651 ooa.addr16[5], oa->addr16[5], u),
1652 ooa.addr16[6], oa->addr16[6], u),
1653 ooa.addr16[7], oa->addr16[7], u);
1654 break;
02742ec6 1655#endif /* INET6 */
ed1f0be2 1656 }
02742ec6
JS
1657 }
1658}
1659
70224baa
JL
1660
1661/*
1662 * Need to modulate the sequence numbers in the TCP SACK option
1663 * (credits to Krzysztof Pfaff for report and patch)
1664 */
1665int
1666pf_modulate_sack(struct mbuf *m, int off, struct pf_pdesc *pd,
1667 struct tcphdr *th, struct pf_state_peer *dst)
1668{
1669 int hlen = (th->th_off << 2) - sizeof(*th), thoptlen = hlen;
1670 u_int8_t opts[TCP_MAXOLEN], *opt = opts;
1671 int copyback = 0, i, olen;
1672 struct raw_sackblock sack;
1673
1674#define TCPOLEN_SACKLEN (TCPOLEN_SACK + 2)
1675 if (hlen < TCPOLEN_SACKLEN ||
1676 !pf_pull_hdr(m, off + sizeof(*th), opts, hlen, NULL, NULL, pd->af))
1677 return 0;
1678
1679 while (hlen >= TCPOLEN_SACKLEN) {
1680 olen = opt[1];
1681 switch (*opt) {
1682 case TCPOPT_EOL: /* FALLTHROUGH */
1683 case TCPOPT_NOP:
1684 opt++;
1685 hlen--;
1686 break;
1687 case TCPOPT_SACK:
1688 if (olen > hlen)
1689 olen = hlen;
1690 if (olen >= TCPOLEN_SACKLEN) {
1691 for (i = 2; i + TCPOLEN_SACK <= olen;
1692 i += TCPOLEN_SACK) {
1693 memcpy(&sack, &opt[i], sizeof(sack));
1694 pf_change_a(&sack.rblk_start, &th->th_sum,
4fc5aa1c 1695 htonl(ntohl(sack.rblk_start) -
70224baa
JL
1696 dst->seqdiff), 0);
1697 pf_change_a(&sack.rblk_end, &th->th_sum,
4fc5aa1c 1698 htonl(ntohl(sack.rblk_end) -
70224baa
JL
1699 dst->seqdiff), 0);
1700 memcpy(&opt[i], &sack, sizeof(sack));
1701 }
1702 copyback = 1;
1703 }
1704 /* FALLTHROUGH */
1705 default:
1706 if (olen < 2)
1707 olen = 2;
1708 hlen -= olen;
1709 opt += olen;
1710 }
1711 }
1712
1713 if (copyback)
1714 m_copyback(m, off + sizeof(*th), thoptlen, opts);
1715 return (copyback);
1716}
1717
02742ec6
JS
1718void
1719pf_send_tcp(const struct pf_rule *r, sa_family_t af,
1720 const struct pf_addr *saddr, const struct pf_addr *daddr,
1721 u_int16_t sport, u_int16_t dport, u_int32_t seq, u_int32_t ack,
70224baa
JL
1722 u_int8_t flags, u_int16_t win, u_int16_t mss, u_int8_t ttl, int tag,
1723 u_int16_t rtag, struct ether_header *eh, struct ifnet *ifp)
02742ec6
JS
1724{
1725 struct mbuf *m;
1726 int len = 0, tlen;
1727#ifdef INET
1728 struct ip *h = NULL;
1729#endif /* INET */
1730#ifdef INET6
1731 struct ip6_hdr *h6 = NULL;
1732#endif /* INET6 */
1733 struct tcphdr *th = NULL;
70224baa 1734 char *opt;
02742ec6 1735
2a7a2b1c
JL
1736 ASSERT_LWKT_TOKEN_HELD(&pf_token);
1737
02742ec6
JS
1738 /* maximum segment size tcp option */
1739 tlen = sizeof(struct tcphdr);
1740 if (mss)
1741 tlen += 4;
1742
1743 switch (af) {
1744#ifdef INET
1745 case AF_INET:
1746 len = sizeof(struct ip) + tlen;
1747 break;
1748#endif /* INET */
1749#ifdef INET6
1750 case AF_INET6:
1751 len = sizeof(struct ip6_hdr) + tlen;
1752 break;
1753#endif /* INET6 */
1754 }
1755
aa1da187
MD
1756 /*
1757 * Create outgoing mbuf.
1758 *
1759 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1760 * so make sure pf.flags is clear.
1761 */
02742ec6 1762 m = m_gethdr(MB_DONTWAIT, MT_HEADER);
2a7a2b1c 1763 if (m == NULL) {
02742ec6 1764 return;
2a7a2b1c 1765 }
70224baa 1766 if (tag)
aa1da187
MD
1767 m->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1768 m->m_pkthdr.pf.flags = 0;
315a7da3 1769 m->m_pkthdr.pf.tag = rtag;
ed1f0be2
JL
1770 /* XXX Recheck when upgrading to > 4.4 */
1771 m->m_pkthdr.pf.statekey = NULL;
70224baa 1772 if (r != NULL && r->rtableid >= 0)
02dd99a9 1773 m->m_pkthdr.pf.rtableid = r->rtableid;
70224baa 1774
02742ec6
JS
1775#ifdef ALTQ
1776 if (r != NULL && r->qid) {
315a7da3
JL
1777 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1778 m->m_pkthdr.pf.qid = r->qid;
1779 m->m_pkthdr.pf.ecn_af = af;
1780 m->m_pkthdr.pf.hdr = mtod(m, struct ip *);
02742ec6 1781 }
70224baa 1782#endif /* ALTQ */
02742ec6
JS
1783 m->m_data += max_linkhdr;
1784 m->m_pkthdr.len = m->m_len = len;
1785 m->m_pkthdr.rcvif = NULL;
1786 bzero(m->m_data, len);
1787 switch (af) {
1788#ifdef INET
1789 case AF_INET:
1790 h = mtod(m, struct ip *);
1791
1792 /* IP header fields included in the TCP checksum */
1793 h->ip_p = IPPROTO_TCP;
1794 h->ip_len = tlen;
1795 h->ip_src.s_addr = saddr->v4.s_addr;
1796 h->ip_dst.s_addr = daddr->v4.s_addr;
1797
1798 th = (struct tcphdr *)((caddr_t)h + sizeof(struct ip));
1799 break;
1800#endif /* INET */
1801#ifdef INET6
1802 case AF_INET6:
1803 h6 = mtod(m, struct ip6_hdr *);
1804
1805 /* IP header fields included in the TCP checksum */
1806 h6->ip6_nxt = IPPROTO_TCP;
1807 h6->ip6_plen = htons(tlen);
1808 memcpy(&h6->ip6_src, &saddr->v6, sizeof(struct in6_addr));
1809 memcpy(&h6->ip6_dst, &daddr->v6, sizeof(struct in6_addr));
1810
1811 th = (struct tcphdr *)((caddr_t)h6 + sizeof(struct ip6_hdr));
1812 break;
1813#endif /* INET6 */
1814 }
1815
1816 /* TCP header */
1817 th->th_sport = sport;
1818 th->th_dport = dport;
1819 th->th_seq = htonl(seq);
1820 th->th_ack = htonl(ack);
1821 th->th_off = tlen >> 2;
1822 th->th_flags = flags;
1823 th->th_win = htons(win);
1824
1825 if (mss) {
1826 opt = (char *)(th + 1);
1827 opt[0] = TCPOPT_MAXSEG;
1828 opt[1] = 4;
1829 mss = htons(mss);
1830 bcopy((caddr_t)&mss, (caddr_t)(opt + 2), 2);
1831 }
1832
1833 switch (af) {
1834#ifdef INET
1835 case AF_INET:
1836 /* TCP checksum */
1837 th->th_sum = in_cksum(m, len);
1838
1839 /* Finish the IP header */
1840 h->ip_v = 4;
1841 h->ip_hl = sizeof(*h) >> 2;
1842 h->ip_tos = IPTOS_LOWDELAY;
1843 h->ip_len = len;
1844 h->ip_off = path_mtu_discovery ? IP_DF : 0;
1845 h->ip_ttl = ttl ? ttl : ip_defttl;
1846 h->ip_sum = 0;
70224baa 1847 if (eh == NULL) {
2a7a2b1c 1848 lwkt_reltoken(&pf_token);
70224baa 1849 ip_output(m, NULL, NULL, 0, NULL, NULL);
2a7a2b1c 1850 lwkt_gettoken(&pf_token);
70224baa
JL
1851 } else {
1852 struct route ro;
1853 struct rtentry rt;
1854 struct ether_header *e = (void *)ro.ro_dst.sa_data;
1855
1856 if (ifp == NULL) {
1857 m_freem(m);
1858 return;
1859 }
1860 rt.rt_ifp = ifp;
1861 ro.ro_rt = &rt;
1862 ro.ro_dst.sa_len = sizeof(ro.ro_dst);
1863 ro.ro_dst.sa_family = pseudo_AF_HDRCMPLT;
1864 bcopy(eh->ether_dhost, e->ether_shost, ETHER_ADDR_LEN);
1865 bcopy(eh->ether_shost, e->ether_dhost, ETHER_ADDR_LEN);
1866 e->ether_type = eh->ether_type;
1867 /* XXX_IMPORT: later */
2a7a2b1c 1868 lwkt_reltoken(&pf_token);
70224baa
JL
1869 ip_output(m, (void *)NULL, &ro, 0,
1870 (void *)NULL, (void *)NULL);
2a7a2b1c 1871 lwkt_gettoken(&pf_token);
70224baa 1872 }
02742ec6
JS
1873 break;
1874#endif /* INET */
1875#ifdef INET6
1876 case AF_INET6:
1877 /* TCP checksum */
1878 th->th_sum = in6_cksum(m, IPPROTO_TCP,
1879 sizeof(struct ip6_hdr), tlen);
1880
1881 h6->ip6_vfc |= IPV6_VERSION;
1882 h6->ip6_hlim = IPV6_DEFHLIM;
1883
2a7a2b1c 1884 lwkt_reltoken(&pf_token);
02742ec6 1885 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2a7a2b1c 1886 lwkt_gettoken(&pf_token);
02742ec6
JS
1887 break;
1888#endif /* INET6 */
1889 }
1890}
1891
1892void
1893pf_send_icmp(struct mbuf *m, u_int8_t type, u_int8_t code, sa_family_t af,
1894 struct pf_rule *r)
1895{
1896 struct mbuf *m0;
1897
aa1da187
MD
1898 /*
1899 * DragonFly doesn't zero the auxillary pkghdr fields, only fw_flags,
1900 * so make sure pf.flags is clear.
1901 */
ed1f0be2
JL
1902 if ((m0 = m_copy(m, 0, M_COPYALL)) == NULL)
1903 return;
1904
aa1da187
MD
1905 m0->m_pkthdr.fw_flags |= PF_MBUF_TAGGED;
1906 m0->m_pkthdr.pf.flags = 0;
ed1f0be2
JL
1907 /* XXX Re-Check when Upgrading to > 4.4 */
1908 m0->m_pkthdr.pf.statekey = NULL;
70224baa
JL
1909
1910 if (r->rtableid >= 0)
315a7da3 1911 m0->m_pkthdr.pf.rtableid = r->rtableid;
02742ec6
JS
1912
1913#ifdef ALTQ
1914 if (r->qid) {
315a7da3
JL
1915 m->m_pkthdr.fw_flags |= PF_MBUF_STRUCTURE;
1916 m0->m_pkthdr.pf.qid = r->qid;
1917 m0->m_pkthdr.pf.ecn_af = af;
1918 m0->m_pkthdr.pf.hdr = mtod(m0, struct ip *);
02742ec6 1919 }
70224baa 1920#endif /* ALTQ */
02742ec6
JS
1921
1922 switch (af) {
1923#ifdef INET
1924 case AF_INET:
745a4a5d 1925 icmp_error(m0, type, code, 0, 0);
02742ec6
JS
1926 break;
1927#endif /* INET */
1928#ifdef INET6
1929 case AF_INET6:
1930 icmp6_error(m0, type, code, 0);
1931 break;
1932#endif /* INET6 */
1933 }
1934}
1935
1936/*
1937 * Return 1 if the addresses a and b match (with mask m), otherwise return 0.
1938 * If n is 0, they match if they are equal. If n is != 0, they match if they
1939 * are different.
1940 */
1941int
1942pf_match_addr(u_int8_t n, struct pf_addr *a, struct pf_addr *m,
1943 struct pf_addr *b, sa_family_t af)
1944{
1945 int match = 0;
1946
1947 switch (af) {
1948#ifdef INET
1949 case AF_INET:
1950 if ((a->addr32[0] & m->addr32[0]) ==
1951 (b->addr32[0] & m->addr32[0]))
1952 match++;
1953 break;
1954#endif /* INET */
1955#ifdef INET6
1956 case AF_INET6:
1957 if (((a->addr32[0] & m->addr32[0]) ==
1958 (b->addr32[0] & m->addr32[0])) &&
1959 ((a->addr32[1] & m->addr32[1]) ==
1960 (b->addr32[1] & m->addr32[1])) &&
1961 ((a->addr32[2] & m->addr32[2]) ==
1962 (b->addr32[2] & m->addr32[2])) &&
1963 ((a->addr32[3] & m->addr32[3]) ==
1964 (b->addr32[3] & m->addr32[3])))
1965 match++;
1966 break;
1967#endif /* INET6 */
1968 }
1969 if (match) {
1970 if (n)
1971 return (0);
1972 else
1973 return (1);
1974 } else {
1975 if (n)
1976 return (1);
1977 else
1978 return (0);
1979 }
1980}
1981
ed1f0be2
JL
1982/*
1983 * Return 1 if b <= a <= e, otherwise return 0.
1984 */
1985int
1986pf_match_addr_range(struct pf_addr *b, struct pf_addr *e,
1987 struct pf_addr *a, sa_family_t af)
1988{
1989 switch (af) {
1990#ifdef INET
1991 case AF_INET:
1992 if ((a->addr32[0] < b->addr32[0]) ||
1993 (a->addr32[0] > e->addr32[0]))
1994 return (0);
1995 break;
1996#endif /* INET */
1997#ifdef INET6
1998 case AF_INET6: {
1999 int i;
2000
2001 /* check a >= b */
2002 for (i = 0; i < 4; ++i)
2003 if (a->addr32[i] > b->addr32[i])
2004 break;
2005 else if (a->addr32[i] < b->addr32[i])
2006 return (0);
2007 /* check a <= e */
2008 for (i = 0; i < 4; ++i)
2009 if (a->addr32[i] < e->addr32[i])
2010 break;
2011 else if (a->addr32[i] > e->addr32[i])
2012 return (0);
2013 break;
2014 }
2015#endif /* INET6 */
2016 }
2017 return (1);
2018}
2019
02742ec6
JS
2020int
2021pf_match(u_int8_t op, u_int32_t a1, u_int32_t a2, u_int32_t p)
2022{
2023 switch (op) {
2024 case PF_OP_IRG:
2025 return ((p > a1) && (p < a2));
2026 case PF_OP_XRG:
2027 return ((p < a1) || (p > a2));
2028 case PF_OP_RRG:
2029 return ((p >= a1) && (p <= a2));
2030 case PF_OP_EQ:
2031 return (p == a1);
2032 case PF_OP_NE:
2033 return (p != a1);
2034 case PF_OP_LT:
2035 return (p < a1);
2036 case PF_OP_LE:
2037 return (p <= a1);
2038 case PF_OP_GT:
2039 return (p > a1);
2040 case PF_OP_GE:
2041 return (p >= a1);
2042 }
2043 return (0); /* never reached */
2044}
2045
2046int
2047pf_match_port(u_int8_t op, u_int16_t a1, u_int16_t a2, u_int16_t p)
2048{
2049 a1 = ntohs(a1);
2050 a2 = ntohs(a2);
2051 p = ntohs(p);
2052 return (pf_match(op, a1, a2, p));
2053}
2054
2055int
2056pf_match_uid(u_int8_t op, uid_t a1, uid_t a2, uid_t u)
2057{
2058 if (u == UID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2059 return (0);
2060 return (pf_match(op, a1, a2, u));
2061}
2062
2063int
2064pf_match_gid(u_int8_t op, gid_t a1, gid_t a2, gid_t g)
2065{
2066 if (g == GID_MAX && op != PF_OP_EQ && op != PF_OP_NE)
2067 return (0);
2068 return (pf_match(op, a1, a2, g));
2069}
2070
70224baa 2071int
315a7da3 2072pf_match_tag(struct mbuf *m, struct pf_rule *r, int *tag)
70224baa
JL
2073{
2074 if (*tag == -1)
315a7da3 2075 *tag = m->m_pkthdr.pf.tag;
70224baa 2076
02742ec6
JS
2077 return ((!r->match_tag_not && r->match_tag == *tag) ||
2078 (r->match_tag_not && r->match_tag != *tag));
2079}
2080
70224baa 2081int
315a7da3 2082pf_tag_packet(struct mbuf *m, int tag, int rtableid)
02742ec6 2083{
70224baa
JL
2084 if (tag <= 0 && rtableid < 0)
2085 return (0);
2086
70224baa 2087 if (tag > 0)
315a7da3 2088 m->m_pkthdr.pf.tag = tag;
70224baa 2089 if (rtableid >= 0)
315a7da3 2090 m->m_pkthdr.pf.rtableid = rtableid;
02742ec6 2091
70224baa 2092 return (0);
02742ec6
JS
2093}
2094
315a7da3 2095void
70224baa 2096pf_step_into_anchor(int *depth, struct pf_ruleset **rs, int n,
ed1f0be2 2097 struct pf_rule **r, struct pf_rule **a, int *match)
70224baa
JL
2098{
2099 struct pf_anchor_stackframe *f;
2100
2101 (*r)->anchor->match = 0;
2102 if (match)
2103 *match = 0;
2104 if (*depth >= sizeof(pf_anchor_stack) /
2105 sizeof(pf_anchor_stack[0])) {
2106 kprintf("pf_step_into_anchor: stack overflow\n");
2107 *r = TAILQ_NEXT(*r, entries);
2108 return;
2109 } else if (*depth == 0 && a != NULL)
2110 *a = *r;
2111 f = pf_anchor_stack + (*depth)++;
2112 f->rs = *rs;
2113 f->r = *r;
2114 if ((*r)->anchor_wildcard) {
2115 f->parent = &(*r)->anchor->children;
2116 if ((f->child = RB_MIN(pf_anchor_node, f->parent)) ==
2117 NULL) {
2118 *r = NULL;
2119 return;
2120 }
2121 *rs = &f->child->ruleset;
2122 } else {
2123 f->parent = NULL;
2124 f->child = NULL;
2125 *rs = &(*r)->anchor->ruleset;
2126 }
2127 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2128}
02742ec6 2129
70224baa
JL
2130int
2131pf_step_out_of_anchor(int *depth, struct pf_ruleset **rs, int n,
2132 struct pf_rule **r, struct pf_rule **a, int *match)
2133{
2134 struct pf_anchor_stackframe *f;
2135 int quick = 0;
2136
2137 do {
2138 if (*depth <= 0)
2139 break;
2140 f = pf_anchor_stack + *depth - 1;
2141 if (f->parent != NULL && f->child != NULL) {
2142 if (f->child->match ||
2143 (match != NULL && *match)) {
2144 f->r->anchor->match = 1;
2145 *match = 0;
2146 }
2147 f->child = RB_NEXT(pf_anchor_node, f->parent, f->child);
2148 if (f->child != NULL) {
2149 *rs = &f->child->ruleset;
2150 *r = TAILQ_FIRST((*rs)->rules[n].active.ptr);
2151 if (*r == NULL)
2152 continue;
2153 else
2154 break;
2155 }
2156 }
2157 (*depth)--;
2158 if (*depth == 0 && a != NULL)
2159 *a = NULL;
2160 *rs = f->rs;
ed1f0be2 2161 if (f->r->anchor->match || (match != NULL && *match))
70224baa
JL
2162 quick = f->r->quick;
2163 *r = TAILQ_NEXT(f->r, entries);
2164 } while (*r == NULL);
2165
2166 return (quick);
2167}
02742ec6
JS
2168
2169#ifdef INET6
2170void
2171pf_poolmask(struct pf_addr *naddr, struct pf_addr *raddr,
2172 struct pf_addr *rmask, struct pf_addr *saddr, sa_family_t af)
2173{
2174 switch (af) {
2175#ifdef INET
2176 case AF_INET:
2177 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2178 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2179 break;
2180#endif /* INET */
2181 case AF_INET6:
2182 naddr->addr32[0] = (raddr->addr32[0] & rmask->addr32[0]) |
2183 ((rmask->addr32[0] ^ 0xffffffff ) & saddr->addr32[0]);
2184 naddr->addr32[1] = (raddr->addr32[1] & rmask->addr32[1]) |
2185 ((rmask->addr32[1] ^ 0xffffffff ) & saddr->addr32[1]);
2186 naddr->addr32[2] = (raddr->addr32[2] & rmask->addr32[2]) |
2187 ((rmask->addr32[2] ^ 0xffffffff ) & saddr->addr32[2]);
2188 naddr->addr32[3] = (raddr->addr32[3] & rmask->addr32[3]) |
2189 ((rmask->addr32[3] ^ 0xffffffff ) & saddr->addr32[3]);
2190 break;
2191 }
2192}
2193
2194void
2195pf_addr_inc(struct pf_addr *addr, sa_family_t af)
2196{
2197 switch (af) {
2198#ifdef INET
2199 case AF_INET:
2200 addr->addr32[0] = htonl(ntohl(addr->addr32[0]) + 1);
2201 break;
2202#endif /* INET */
2203 case AF_INET6:
2204 if (addr->addr32[3] == 0xffffffff) {
2205 addr->addr32[3] = 0;
2206 if (addr->addr32[2] == 0xffffffff) {
2207 addr->addr32[2] = 0;
2208 if (addr->addr32[1] == 0xffffffff) {
2209 addr->addr32[1] = 0;
2210 addr->addr32[0] =
2211 htonl(ntohl(addr->addr32[0]) + 1);
2212 } else
2213 addr->addr32[1] =
2214 htonl(ntohl(addr->addr32[1]) + 1);
2215 } else
2216 addr->addr32[2] =
2217 htonl(ntohl(addr->addr32[2]) + 1);
2218 } else
2219 addr->addr32[3] =
2220 htonl(ntohl(addr->addr32[3]) + 1);
2221 break;
2222 }
2223}
2224#endif /* INET6 */
2225
2226#define mix(a,b,c) \
2227 do { \
2228 a -= b; a -= c; a ^= (c >> 13); \
2229 b -= c; b -= a; b ^= (a << 8); \
2230 c -= a; c -= b; c ^= (b >> 13); \
2231 a -= b; a -= c; a ^= (c >> 12); \
2232 b -= c; b -= a; b ^= (a << 16); \
2233 c -= a; c -= b; c ^= (b >> 5); \
2234 a -= b; a -= c; a ^= (c >> 3); \
2235 b -= c; b -= a; b ^= (a << 10); \
2236 c -= a; c -= b; c ^= (b >> 15); \
2237 } while (0)
2238
2239/*
2240 * hash function based on bridge_hash in if_bridge.c
2241 */
2242void
2243pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
2244 struct pf_poolhashkey *key, sa_family_t af)
2245{
2246 u_int32_t a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
2247
2248 switch (af) {
2249#ifdef INET
2250 case AF_INET:
2251 a += inaddr->addr32[0];
2252 b += key->key32[1];
2253 mix(a, b, c);
2254 hash->addr32[0] = c + key->key32[2];
2255 break;
2256#endif /* INET */
2257#ifdef INET6
2258 case AF_INET6:
2259 a += inaddr->addr32[0];
2260 b += inaddr->addr32[2];
2261 mix(a, b, c);
2262 hash->addr32[0] = c;
2263 a += inaddr->addr32[1];
2264 b += inaddr->addr32[3];
2265 c += key->key32[1];
2266 mix(a, b, c);
2267 hash->addr32[1] = c;
2268 a += inaddr->addr32[2];
2269 b += inaddr->addr32[1];
2270 c += key->key32[2];
2271 mix(a, b, c);
2272 hash->addr32[2] = c;
2273 a += inaddr->addr32[3];
2274 b += inaddr->addr32[0];
2275 c += key->key32[3];
2276 mix(a, b, c);
2277 hash->addr32[3] = c;
2278 break;
2279#endif /* INET6 */
2280 }
2281}
2282
2283int
2284pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
2285 struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
2286{
2287 unsigned char hash[16];
2288 struct pf_pool *rpool = &r->rpool;
2289 struct pf_addr *raddr = &rpool->cur->addr.v.a.addr;
2290 struct pf_addr *rmask = &rpool->cur->addr.v.a.mask;
2291 struct pf_pooladdr *acur = rpool->cur;
2292 struct pf_src_node k;
2293
2294 if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
2295 (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
2296 k.af = af;
2297 PF_ACPY(&k.addr, saddr, af);
2298 if (r->rule_flag & PFRULE_RULESRCTRACK ||
2299 r->rpool.opts & PF_POOL_STICKYADDR)
2300 k.rule.ptr = r;
2301 else
2302 k.rule.ptr = NULL;
2303 pf_status.scounters[SCNT_SRC_NODE_SEARCH]++;
2304 *sn = RB_FIND(pf_src_tree, &tree_src_tracking, &k);
2305 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
2306 PF_ACPY(naddr, &(*sn)->raddr, af);
2307 if (pf_status.debug >= PF_DEBUG_MISC) {
4b1cf444 2308 kprintf("pf_map_addr: src tracking maps ");
02742ec6 2309 pf_print_host(&k.addr, 0, af);
4b1cf444 2310 kprintf(" to ");
02742ec6 2311 pf_print_host(naddr, 0, af);
4b1cf444 2312 kprintf("\n");
02742ec6
JS
2313 }
2314 return (0);
2315 }
2316 }
2317
2318 if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
2319 return (1);
2320 if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
70224baa
JL
2321 switch (af) {
2322#ifdef INET
2323 case AF_INET:
02742ec6
JS
2324 if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
2325 (rpool->opts & PF_POOL_TYPEMASK) !=
2326 PF_POOL_ROUNDROBIN)
2327 return (1);
2328 raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
2329 rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
70224baa
JL
2330 break;
2331#endif /* INET */
2332#ifdef INET6
2333 case AF_INET6:
02742ec6
JS
2334 if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
2335 (rpool->opts & PF_POOL_TYPEMASK) !=
2336 PF_POOL_ROUNDROBIN)
2337 return (1);
2338 raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
2339 rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
70224baa
JL
2340 break;
2341#endif /* INET6 */
02742ec6
JS
2342 }
2343 } else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2344 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
2345 return (1); /* unsupported */
2346 } else {
2347 raddr = &rpool->cur->addr.v.a.addr;
2348 rmask = &rpool->cur->addr.v.a.mask;
2349 }
2350
2351 switch (rpool->opts & PF_POOL_TYPEMASK) {
2352 case PF_POOL_NONE:
2353 PF_ACPY(naddr, raddr, af);
2354 break;
2355 case PF_POOL_BITMASK:
2356 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
2357 break;
2358 case PF_POOL_RANDOM:
2359 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
2360 switch (af) {
2361#ifdef INET
2362 case AF_INET:
4fc5aa1c 2363 rpool->counter.addr32[0] = htonl(karc4random());
02742ec6
JS
2364 break;
2365#endif /* INET */
2366#ifdef INET6
2367 case AF_INET6:
2368 if (rmask->addr32[3] != 0xffffffff)
70224baa 2369 rpool->counter.addr32[3] =
4fc5aa1c 2370 htonl(karc4random());
02742ec6
JS
2371 else
2372 break;
2373 if (rmask->addr32[2] != 0xffffffff)
70224baa 2374 rpool->counter.addr32[2] =
4fc5aa1c 2375 htonl(karc4random());
02742ec6
JS
2376 else
2377 break;
2378 if (rmask->addr32[1] != 0xffffffff)
70224baa 2379 rpool->counter.addr32[1] =
4fc5aa1c 2380 htonl(karc4random());
02742ec6
JS
2381 else
2382 break;
2383 if (rmask->addr32[0] != 0xffffffff)
70224baa 2384 rpool->counter.addr32[0] =
4fc5aa1c 2385 htonl(karc4random());
02742ec6
JS
2386 break;
2387#endif /* INET6 */
2388 }
2389 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2390 PF_ACPY(init_addr, naddr, af);
2391
2392 } else {
2393 PF_AINC(&rpool->counter, af);
2394 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
2395 }
2396 break;
2397 case PF_POOL_SRCHASH:
2398 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
2399 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
2400 break;
2401 case PF_POOL_ROUNDROBIN:
2402 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2403 if (!pfr_pool_get(rpool->cur->addr.p.tbl,
2404 &rpool->tblidx, &rpool->counter,
2405 &raddr, &rmask, af))
2406 goto get_addr;
2407 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2408 if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2409 &rpool->tblidx, &rpool->counter,
2410 &raddr, &rmask, af))
2411 goto get_addr;
2412 } else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
2413 goto get_addr;
2414
2415 try_next:
2416 if ((rpool->cur = TAILQ_NEXT(rpool->cur, entries)) == NULL)
2417 rpool->cur = TAILQ_FIRST(&rpool->list);
2418 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
2419 rpool->tblidx = -1;
2420 if (pfr_pool_get(rpool->cur->addr.p.tbl,
2421 &rpool->tblidx, &rpool->counter,
2422 &raddr, &rmask, af)) {
2423 /* table contains no address of type 'af' */
2424 if (rpool->cur != acur)
2425 goto try_next;
2426 return (1);
2427 }
2428 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
2429 rpool->tblidx = -1;
2430 if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
2431 &rpool->tblidx, &rpool->counter,
2432 &raddr, &rmask, af)) {
2433 /* table contains no address of type 'af' */
2434 if (rpool->cur != acur)
2435 goto try_next;
2436 return (1);
2437 }
2438 } else {
2439 raddr = &rpool->cur->addr.v.a.addr;
2440 rmask = &rpool->cur->addr.v.a.mask;
2441 PF_ACPY(&rpool->counter, raddr, af);
2442 }
2443
2444 get_addr:
2445 PF_ACPY(naddr, &rpool->counter, af);
70224baa
JL
2446 if (init_addr != NULL && PF_AZERO(init_addr, af))
2447 PF_ACPY(init_addr, naddr, af);
02742ec6
JS
2448 PF_AINC(&rpool->counter, af);
2449 break;
2450 }
2451 if (*sn != NULL)
2452 PF_ACPY(&(*sn)->raddr, naddr, af);
2453
2454 if (pf_status.debug >= PF_DEBUG_MISC &&
2455 (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
4b1cf444 2456 kprintf("pf_map_addr: selected address ");
02742ec6 2457 pf_print_host(naddr, 0, af);
4b1cf444 2458 kprintf("\n");
02742ec6
JS
2459 }
2460
2461 return (0);
2462}
2463
2464int
2465pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
2466 struct pf_addr *saddr, struct pf_addr *daddr, u_int16_t dport,
2467 struct pf_addr *naddr, u_int16_t *nport, u_int16_t low, u_int16_t high,
2468 struct pf_src_node **sn)
2469{
315a7da3 2470 struct pf_state_key_cmp key;
02742ec6
JS
2471 struct pf_addr init_addr;
2472 u_int16_t cut;
2473
2474 bzero(&init_addr, sizeof(init_addr));
2475 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2476 return (1);
2477
70224baa
JL
2478 if (proto == IPPROTO_ICMP) {
2479 low = 1;
2480 high = 65535;
2481 }
2482
02742ec6
JS
2483 do {
2484 key.af = af;
2485 key.proto = proto;
ed1f0be2
JL
2486 PF_ACPY(&key.addr[1], daddr, key.af);
2487 PF_ACPY(&key.addr[0], naddr, key.af);
2488 key.port[1] = dport;
02742ec6
JS
2489
2490 /*
2491 * port search; start random, step;
2492 * similar 2 portloop in in_pcbbind
2493 */
70224baa
JL
2494 if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
2495 proto == IPPROTO_ICMP)) {
ed1f0be2
JL
2496 key.port[0] = dport;
2497 if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
02742ec6
JS
2498 return (0);
2499 } else if (low == 0 && high == 0) {
ed1f0be2
JL
2500 key.port[0] = *nport;
2501 if (pf_find_state_all(&key, PF_IN, NULL) == NULL)
02742ec6
JS
2502 return (0);
2503 } else if (low == high) {
ed1f0be2
JL
2504 key.port[0] = htons(low);
2505 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
02742ec6
JS
2506 *nport = htons(low);
2507 return (0);
2508 }
2509 } else {
2510 u_int16_t tmp;
2511
2512 if (low > high) {
2513 tmp = low;
2514 low = high;
2515 high = tmp;
2516 }
2517 /* low < high */
4fc5aa1c 2518 cut = htonl(karc4random()) % (1 + high - low) + low;
02742ec6
JS
2519 /* low <= cut <= high */
2520 for (tmp = cut; tmp <= high; ++(tmp)) {
ed1f0be2
JL
2521 key.port[0] = htons(tmp);
2522 if (pf_find_state_all(&key, PF_IN, NULL) ==
2523 NULL && !in_baddynamic(tmp, proto)) {
02742ec6
JS
2524 *nport = htons(tmp);
2525 return (0);
2526 }
2527 }
2528 for (tmp = cut - 1; tmp >= low; --(tmp)) {
ed1f0be2
JL
2529 key.port[0] = htons(tmp);
2530 if (pf_find_state_all(&key, PF_IN, NULL) ==
2531 NULL && !in_baddynamic(tmp, proto)) {
02742ec6
JS
2532 *nport = htons(tmp);
2533 return (0);
2534 }
2535 }
2536 }
2537
2538 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
2539 case PF_POOL_RANDOM:
2540 case PF_POOL_ROUNDROBIN:
2541 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
2542 return (1);
2543 break;
2544 case PF_POOL_NONE:
2545 case PF_POOL_SRCHASH:
2546 case PF_POOL_BITMASK:
2547 default:
2548 return (1);
2549 }
2550 } while (! PF_AEQ(&init_addr, naddr, af) );
02742ec6
JS
2551 return (1); /* none available */
2552}
2553
2554struct pf_rule *
2555pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
2556 int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
2557 struct pf_addr *daddr, u_int16_t dport, int rs_num)
2558{
70224baa 2559 struct pf_rule *r, *rm = NULL;
02742ec6 2560 struct pf_ruleset *ruleset = NULL;
70224baa
JL
2561 int tag = -1;
2562 int rtableid = -1;
2563 int asd = 0;
02742ec6
JS
2564
2565 r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
2566 while (r && rm == NULL) {
2567 struct pf_rule_addr *src = NULL, *dst = NULL;
2568 struct pf_addr_wrap *xdst = NULL;
2569
2570 if (r->action == PF_BINAT && direction == PF_IN) {
2571 src = &r->dst;
2572 if (r->rpool.cur != NULL)
2573 xdst = &r->rpool.cur->addr;
2574 } else {
2575 src = &r->src;
2576 dst = &r->dst;
2577 }
2578
2579 r->evaluations++;
70224baa 2580 if (pfi_kif_match(r->kif, kif) == r->ifnot)
02742ec6
JS
2581 r = r->skip[PF_SKIP_IFP].ptr;
2582 else if (r->direction && r->direction != direction)
2583 r = r->skip[PF_SKIP_DIR].ptr;
2584 else if (r->af && r->af != pd->af)
2585 r = r->skip[PF_SKIP_AF].ptr;
2586 else if (r->proto && r->proto != pd->proto)
2587 r = r->skip[PF_SKIP_PROTO].ptr;
70224baa
JL
2588 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
2589 src->neg, kif))
02742ec6
JS
2590 r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
2591 PF_SKIP_DST_ADDR].ptr;
2592 else if (src->port_op && !pf_match_port(src->port_op,
2593 src->port[0], src->port[1], sport))
2594 r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
2595 PF_SKIP_DST_PORT].ptr;
2596 else if (dst != NULL &&
70224baa 2597 PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL))
02742ec6 2598 r = r->skip[PF_SKIP_DST_ADDR].ptr;
70224baa
JL
2599 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
2600 0, NULL))
02742ec6
JS
2601 r = TAILQ_NEXT(r, entries);
2602 else if (dst != NULL && dst->port_op &&
2603 !pf_match_port(dst->port_op, dst->port[0],
2604 dst->port[1], dport))
2605 r = r->skip[PF_SKIP_DST_PORT].ptr;
315a7da3 2606 else if (r->match_tag && !pf_match_tag(m, r, &tag))
70224baa 2607 r = TAILQ_NEXT(r, entries);
02742ec6
JS
2608 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
2609 IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
2610 off, pd->hdr.tcp), r->os_fingerprint)))
2611 r = TAILQ_NEXT(r, entries);
70224baa
JL
2612 else {
2613 if (r->tag)
2614 tag = r->tag;
2615 if (r->rtableid >= 0)
2616 rtableid = r->rtableid;
2617 if (r->anchor == NULL) {
02742ec6 2618 rm = r;
70224baa
JL
2619 } else
2620 pf_step_into_anchor(&asd, &ruleset, rs_num,
2621 &r, NULL, NULL);
2622 }
2623 if (r == NULL)
2624 pf_step_out_of_anchor(&asd, &ruleset, rs_num, &r,
2625 NULL, NULL);
02742ec6 2626 }
315a7da3 2627 if (pf_tag_packet(m, tag, rtableid))
70224baa 2628 return (NULL);
02742ec6
JS
2629 if (rm != NULL && (rm->action == PF_NONAT ||
2630 rm->action == PF_NORDR || rm->action == PF_NOBINAT))
2631 return (NULL);
2632 return (rm);
2633}
2634
2635struct pf_rule *
2636pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
2637 struct pfi_kif *kif, struct pf_src_node **sn,
ed1f0be2
JL
2638 struct pf_state_key **skw, struct pf_state_key **sks,
2639 struct pf_state_key **skp, struct pf_state_key **nkp,
2640 struct pf_addr *saddr, struct pf_addr *daddr,
2641 u_int16_t sport, u_int16_t dport)
02742ec6
JS
2642{
2643 struct pf_rule *r = NULL;
2644
ed1f0be2 2645
02742ec6
JS
2646 if (direction == PF_OUT) {
2647 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2648 sport, daddr, dport, PF_RULESET_BINAT);
2649 if (r == NULL)
2650 r = pf_match_translation(pd, m, off, direction, kif,
2651 saddr, sport, daddr, dport, PF_RULESET_NAT);
2652 } else {
2653 r = pf_match_translation(pd, m, off, direction, kif, saddr,
2654 sport, daddr, dport, PF_RULESET_RDR);
2655 if (r == NULL)
2656 r = pf_match_translation(pd, m, off, direction, kif,
2657 saddr, sport, daddr, dport, PF_RULESET_BINAT);
2658 }
2659
2660 if (r != NULL) {
ed1f0be2
JL
2661 struct pf_addr *naddr;
2662 u_int16_t *nport;
2663
2664 if (pf_state_key_setup(pd, r, skw, sks, skp, nkp,
2665 saddr, daddr, sport, dport))
2666 return r;
2667
2668 /* XXX We only modify one side for now. */
2669 naddr = &(*nkp)->addr[1];
2670 nport = &(*nkp)->port[1];
2671
02742ec6
JS
2672 switch (r->action) {
2673 case PF_NONAT:
2674 case PF_NOBINAT:
2675 case PF_NORDR:
2676 return (NULL);
2677 case PF_NAT:
2678 if (pf_get_sport(pd->af, pd->proto, r, saddr,
2679 daddr, dport, naddr, nport, r->rpool.proxy_port[0],
2680 r->rpool.proxy_port[1], sn)) {
2681 DPFPRINTF(PF_DEBUG_MISC,
2682 ("pf: NAT proxy port allocation "
2683 "(%u-%u) failed\n",
2684 r->rpool.proxy_port[0],
2685 r->rpool.proxy_port[1]));
2686 return (NULL);
2687 }
2688 break;
2689 case PF_BINAT:
2690 switch (direction) {
2691 case PF_OUT:
2692 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
70224baa
JL
2693 switch (pd->af) {
2694#ifdef INET
2695 case AF_INET:
02742ec6
JS
2696 if (r->rpool.cur->addr.p.dyn->
2697 pfid_acnt4 < 1)
2698 return (NULL);
2699 PF_POOLMASK(naddr,
2700 &r->rpool.cur->addr.p.dyn->
2701 pfid_addr4,
2702 &r->rpool.cur->addr.p.dyn->
2703 pfid_mask4,
2704 saddr, AF_INET);
70224baa
JL
2705 break;
2706#endif /* INET */
2707#ifdef INET6
2708 case AF_INET6:
02742ec6
JS
2709 if (r->rpool.cur->addr.p.dyn->
2710 pfid_acnt6 < 1)
2711 return (NULL);
2712 PF_POOLMASK(naddr,
2713 &r->rpool.cur->addr.p.dyn->
2714 pfid_addr6,
2715 &r->rpool.cur->addr.p.dyn->
2716 pfid_mask6,
2717 saddr, AF_INET6);
70224baa
JL
2718 break;
2719#endif /* INET6 */
02742ec6
JS
2720 }
2721 } else
2722 PF_POOLMASK(naddr,
2723 &r->rpool.cur->addr.v.a.addr,
2724 &r->rpool.cur->addr.v.a.mask,
2725 saddr, pd->af);
2726 break;
2727 case PF_IN:
70224baa
JL
2728 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
2729 switch (pd->af) {
2730#ifdef INET
2731 case AF_INET:
02742ec6
JS
2732 if (r->src.addr.p.dyn->
2733 pfid_acnt4 < 1)
2734 return (NULL);
2735 PF_POOLMASK(naddr,
2736 &r->src.addr.p.dyn->
2737 pfid_addr4,
2738 &r->src.addr.p.dyn->
2739 pfid_mask4,
2740 daddr, AF_INET);
70224baa
JL
2741 break;
2742#endif /* INET */
2743#ifdef INET6
2744 case AF_INET6:
02742ec6
JS
2745 if (r->src.addr.p.dyn->
2746 pfid_acnt6 < 1)
2747 return (NULL);
2748 PF_POOLMASK(naddr,
2749 &r->src.addr.p.dyn->
2750 pfid_addr6,
2751 &r->src.addr.p.dyn->
2752 pfid_mask6,
2753 daddr, AF_INET6);
70224baa
JL
2754 break;
2755#endif /* INET6 */
02742ec6
JS
2756 }
2757 } else
2758 PF_POOLMASK(naddr,
2759 &r->src.addr.v.a.addr,
2760 &r->src.addr.v.a.mask, daddr,
2761 pd->af);
2762 break;
2763 }
2764 break;
2765 case PF_RDR: {
70224baa 2766 if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
02742ec6 2767 return (NULL);
70224baa
JL
2768 if ((r->rpool.opts & PF_POOL_TYPEMASK) ==
2769 PF_POOL_BITMASK)
2770 PF_POOLMASK(naddr, naddr,
2771 &r->rpool.cur->addr.v.a.mask, daddr,
2772 pd->af);
315a7da3 2773
02742ec6
JS
2774 if (r->rpool.proxy_port[1]) {
2775 u_int32_t tmp_nport;
2776
2777 tmp_nport = ((ntohs(dport) -
2778 ntohs(r->dst.port[0])) %
2779 (r->rpool.proxy_port[1] -
2780 r->rpool.proxy_port[0] + 1)) +
2781 r->rpool.proxy_port[0];
2782
2783 /* wrap around if necessary */
2784 if (tmp_nport > 65535)
2785 tmp_nport -= 65535;
2786 *nport = htons((u_int16_t)tmp_nport);
2787 } else if (r->rpool.proxy_port[0])
2788 *nport = htons(r->rpool.proxy_port[0]);
2789 break;
2790 }
2791 default:
2792 return (NULL);
2793 }
2794 }
2795
2796 return (r);
2797}
2798
2799#ifdef SMP
2800struct netmsg_hashlookup {
002c1265 2801 struct netmsg_base base;
02742ec6
JS
2802 struct inpcb **nm_pinp;
2803 struct inpcbinfo *nm_pcbinfo;
2804 struct pf_addr *nm_saddr;
2805 struct pf_addr *nm_daddr;
2806 uint16_t nm_sport;
2807 uint16_t nm_dport;
2808 sa_family_t nm_af;
2809};
2810
0379d9fd 2811#ifdef PF_SOCKET_LOOKUP_DOMSG
4599cf19 2812static void
002c1265 2813in_pcblookup_hash_handler(netmsg_t msg)
02742ec6 2814{
002c1265 2815 struct netmsg_hashlookup *rmsg = (struct netmsg_hashlookup *)msg;
02742ec6 2816
002c1265
MD
2817 if (rmsg->nm_af == AF_INET)
2818 *rmsg->nm_pinp = in_pcblookup_hash(rmsg->nm_pcbinfo,
2819 rmsg->nm_saddr->v4, rmsg->nm_sport, rmsg->nm_daddr->v4,
2820 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
02742ec6
JS
2821#ifdef INET6
2822 else
002c1265
MD
2823 *rmsg->nm_pinp = in6_pcblookup_hash(rmsg->nm_pcbinfo,
2824 &rmsg->nm_saddr->v6, rmsg->nm_sport, &rmsg->nm_daddr->v6,
2825 rmsg->nm_dport, INPLOOKUP_WILDCARD, NULL);
02742ec6 2826#endif /* INET6 */
002c1265 2827 lwkt_replymsg(&rmsg->base.lmsg, 0);
02742ec6 2828}
0379d9fd
SZ
2829#endif /* PF_SOCKET_LOOKUP_DOMSG */
2830
02742ec6
JS
2831#endif /* SMP */
2832
2833int
315a7da3 2834pf_socket_lookup(int direction, struct pf_pdesc *pd)
02742ec6
JS
2835{
2836 struct pf_addr *saddr, *daddr;
2837 u_int16_t sport, dport;
2838 struct inpcbinfo *pi;
2839 struct inpcb *inp;
2840#ifdef SMP
2841 struct netmsg_hashlookup *msg = NULL;
0379d9fd 2842#ifdef PF_SOCKET_LOOKUP_DOMSG
d9663f05 2843 struct netmsg_hashlookup msg0;
0379d9fd 2844#endif
02742ec6
JS
2845#endif
2846 int pi_cpu = 0;
2847
70224baa
JL
2848 if (pd == NULL)
2849 return (-1);
2850 pd->lookup.uid = UID_MAX;
2851 pd->lookup.gid = GID_MAX;
2852 pd->lookup.pid = NO_PID;
02742ec6
JS
2853 if (direction == PF_IN) {
2854 saddr = pd->src;
2855 daddr = pd->dst;
2856 } else {
2857 saddr = pd->dst;
2858 daddr = pd->src;
2859 }
2860 switch (pd->proto) {
2861 case IPPROTO_TCP:
315a7da3
JL
2862 if (pd->hdr.tcp == NULL)
2863 return (-1);
02742ec6
JS
2864 sport = pd->hdr.tcp->th_sport;
2865 dport = pd->hdr.tcp->th_dport;
2866
2867 pi_cpu = tcp_addrcpu(saddr->v4.s_addr, sport, daddr->v4.s_addr, dport);
2868 pi = &tcbinfo[pi_cpu];
2869#ifdef SMP
2870 /*
2871 * Our netstack runs lockless on MP systems
2872 * (only for TCP connections at the moment).
2873 *
2874 * As we are not allowed to read another CPU's tcbinfo,
2875 * we have to ask that CPU via remote call to search the
2876 * table for us.
2877 *
2878 * Prepare a msg iff data belongs to another CPU.
2879 */
2880 if (pi_cpu != mycpu->gd_cpuid) {
0379d9fd
SZ
2881#ifdef PF_SOCKET_LOOKUP_DOMSG
2882 /*
2883 * NOTE:
2884 *
2885 * Following lwkt_domsg() is dangerous and could
2886 * lockup the network system, e.g.
2887 *
2888 * On 2 CPU system:
2889 * netisr0 domsg to netisr1 (due to lookup)
2890 * netisr1 domsg to netisr0 (due to lookup)
2891 *
2892 * We simply return -1 here, since we are probably
2893 * called before NAT, so the TCP packet should
2894 * already be on the correct CPU.
2895 */
d9663f05
SZ
2896 msg = &msg0;
2897 netmsg_init(&msg->base, NULL, &curthread->td_msgport,
48e7b118 2898 0, in_pcblookup_hash_handler);
02742ec6
JS
2899 msg->nm_pinp = &inp;
2900 msg->nm_pcbinfo = pi;
2901 msg->nm_saddr = saddr;
2902 msg->nm_sport = sport;
2903 msg->nm_daddr = daddr;
2904 msg->nm_dport = dport;
2905 msg->nm_af = pd->af;
0379d9fd
SZ
2906#else /* !PF_SOCKET_LOOKUP_DOMSG */
2907 kprintf("pf_socket_lookup: tcp packet not on the "
2908 "correct cpu %d, cur cpu %d\n",
2909 pi_cpu, mycpuid);
2910 print_backtrace(-1);
2911 return -1;
2912#endif /* PF_SOCKET_LOOKUP_DOMSG */
02742ec6
JS
2913 }
2914#endif /* SMP */
2915 break;
2916 case IPPROTO_UDP:
315a7da3
JL
2917 if (pd->hdr.udp == NULL)
2918 return (-1);
02742ec6
JS
2919 sport = pd->hdr.udp->uh_sport;
2920 dport = pd->hdr.udp->uh_dport;
2921 pi = &udbinfo;
2922 break;
2923 default:
315a7da3 2924 return (-1);
02742ec6
JS
2925 }
2926 if (direction != PF_IN) {
2927 u_int16_t p;
2928
2929 p = sport;
2930 sport = dport;
2931 dport = p;
2932 }
2933 switch (pd->af) {
2934#ifdef INET6
2935 case AF_INET6:
2936#ifdef SMP
2937 /*
2938 * Query other CPU, second part
2939 *
2940 * msg only gets initialized when:
2941 * 1) packet is TCP
2942 * 2) the info belongs to another CPU
2943 *
2944 * Use some switch/case magic to avoid code duplication.
2945 */
2946 if (msg == NULL)
2947#endif /* SMP */
2948 {
2949 inp = in6_pcblookup_hash(pi, &saddr->v6, sport,
2950 &daddr->v6, dport, INPLOOKUP_WILDCARD, NULL);
2951
2952 if (inp == NULL)
70224baa 2953 return (-1);
02742ec6
JS
2954 break;
2955 }
2956 /* FALLTHROUGH if SMP and on other CPU */
2957#endif /* INET6 */
2958 case AF_INET:
2959#ifdef SMP
2960 if (msg != NULL) {
2a7a2b1c 2961 lwkt_domsg(cpu_portfn(pi_cpu),
002c1265 2962 &msg->base.lmsg, 0);
02742ec6
JS
2963 } else
2964#endif /* SMP */
2965 {
2966 inp = in_pcblookup_hash(pi, saddr->v4, sport, daddr->v4,
2967 dport, INPLOOKUP_WILDCARD, NULL);
2968 }
2969 if (inp == NULL)
315a7da3 2970 return (-1);
02742ec6
JS
2971 break;
2972
2973 default:
70224baa 2974 return (-1);
02742ec6 2975 }
70224baa
JL
2976 pd->lookup.uid = inp->inp_socket->so_cred->cr_uid;
2977 pd->lookup.gid = inp->inp_socket->so_cred->cr_groups[0];
02742ec6
JS
2978 return (1);
2979}
2980
2981u_int8_t
2982pf_get_wscale(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
2983{
2984 int hlen;
2985 u_int8_t hdr[60];
2986 u_int8_t *opt, optlen;
2987 u_int8_t wscale = 0;
2988
2989 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
2990 if (hlen <= sizeof(struct tcphdr))
2991 return (0);
2992 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
2993 return (0);
2994 opt = hdr + sizeof(struct tcphdr);
2995 hlen -= sizeof(struct tcphdr);
2996 while (hlen >= 3) {
2997 switch (*opt) {
2998 case TCPOPT_EOL:
2999 case TCPOPT_NOP:
3000 ++opt;
3001 --hlen;
3002 break;
3003 case TCPOPT_WINDOW:
3004 wscale = opt[2];
3005 if (wscale > TCP_MAX_WINSHIFT)
3006 wscale = TCP_MAX_WINSHIFT;
3007 wscale |= PF_WSCALE_FLAG;
3008 /* FALLTHROUGH */
3009 default:
3010 optlen = opt[1];
3011 if (optlen < 2)
3012 optlen = 2;
3013 hlen -= optlen;
3014 opt += optlen;
3015 break;
3016 }
3017 }
3018 return (wscale);
3019}
3020
3021u_int16_t
3022pf_get_mss(struct mbuf *m, int off, u_int16_t th_off, sa_family_t af)
3023{
3024 int hlen;
3025 u_int8_t hdr[60];
3026 u_int8_t *opt, optlen;
3027 u_int16_t mss = tcp_mssdflt;
3028
3029 hlen = th_off << 2; /* hlen <= sizeof(hdr) */
3030 if (hlen <= sizeof(struct tcphdr))
3031 return (0);
3032 if (!pf_pull_hdr(m, off, hdr, hlen, NULL, NULL, af))
3033 return (0);
3034 opt = hdr + sizeof(struct tcphdr);
3035 hlen -= sizeof(struct tcphdr);
3036 while (hlen >= TCPOLEN_MAXSEG) {
3037 switch (*opt) {
3038 case TCPOPT_EOL:
3039 case TCPOPT_NOP:
3040 ++opt;
3041 --hlen;
3042 break;
3043 case TCPOPT_MAXSEG:
3044 bcopy((caddr_t)(opt + 2), (caddr_t)&mss, 2);
3045 /* FALLTHROUGH */
3046 default:
3047 optlen = opt[1];
3048 if (optlen < 2)
3049 optlen = 2;
3050 hlen -= optlen;
3051 opt += optlen;
3052 break;
3053 }
3054 }
3055 return (mss);
3056}
3057
3058u_int16_t
3059pf_calc_mss(struct pf_addr *addr, sa_family_t af, u_int16_t offer)
3060{
3061#ifdef INET
3062 struct sockaddr_in *dst;
3063 struct route ro;
3064#endif /* INET */
3065#ifdef INET6
3066 struct sockaddr_in6 *dst6;
3067 struct route_in6 ro6;
3068#endif /* INET6 */
3069 struct rtentry *rt = NULL;
3070 int hlen = 0;
3071 u_int16_t mss = tcp_mssdflt;
3072
3073 switch (af) {
3074#ifdef INET
3075 case AF_INET:
3076 hlen = sizeof(struct ip);
3077 bzero(&ro, sizeof(ro));
3078 dst = (struct sockaddr_in *)&ro.ro_dst;
3079 dst->sin_family = AF_INET;
3080 dst->sin_len = sizeof(*dst);
3081 dst->sin_addr = addr->v4;
3082 rtalloc_ign(&ro, (RTF_CLONING | RTF_PRCLONING));
3083 rt = ro.ro_rt;
3084 break;
3085#endif /* INET */
3086#ifdef INET6
3087 case AF_INET6:
3088 hlen = sizeof(struct ip6_hdr);
3089 bzero(&ro6, sizeof(ro6));
3090 dst6 = (struct sockaddr_in6 *)&ro6.ro_dst;
3091 dst6->sin6_family = AF_INET6;
3092 dst6->sin6_len = sizeof(*dst6);
3093 dst6->sin6_addr = addr->v6;
3094 rtalloc_ign((struct route *)&ro6, (RTF_CLONING | RTF_PRCLONING));
3095 rt = ro6.ro_rt;
3096 break;
3097#endif /* INET6 */
3098 }
3099
3100 if (rt && rt->rt_ifp) {
3101 mss = rt->rt_ifp->if_mtu - hlen - sizeof(struct tcphdr);
3102 mss = max(tcp_mssdflt, mss);
3103 RTFREE(rt);
3104 }
3105 mss = min(mss, offer);
3106 mss = max(mss, 64); /* sanity - at least max opt space */
3107 return (mss);
3108}
3109
3110void
3111pf_set_rt_ifp(struct pf_state *s, struct pf_addr *saddr)
3112{
3113 struct pf_rule *r = s->rule.ptr;
3114
3115 s->rt_kif = NULL;
3116 if (!r->rt || r->rt == PF_FASTROUTE)
3117 return;
ed1f0be2 3118 switch (s->key[PF_SK_WIRE]->af) {
02742ec6
JS
3119#ifdef INET
3120 case AF_INET:
3121 pf_map_addr(AF_INET, r, saddr, &s->rt_addr, NULL,
3122 &s->nat_src_node);
3123 s->rt_kif = r->rpool.cur->kif;
3124 break;
3125#endif /* INET */
3126#ifdef INET6
3127 case AF_INET6:
3128 pf_map_addr(AF_INET6, r, saddr, &s->rt_addr, NULL,
3129 &s->nat_src_node);
3130 s->rt_kif = r->rpool.cur->kif;
3131 break;
3132#endif /* INET6 */
3133 }
3134}
3135
ed1f0be2
JL
3136u_int32_t
3137pf_tcp_iss(struct pf_pdesc *pd)
315a7da3 3138{
ed1f0be2
JL
3139 MD5_CTX ctx;
3140 u_int32_t digest[4];
3141
3142 if (pf_tcp_secret_init == 0) {
3143 karc4rand(pf_tcp_secret, sizeof(pf_tcp_secret));
3144 MD5Init(&pf_tcp_secret_ctx);
3145 MD5Update(&pf_tcp_secret_ctx, pf_tcp_secret,
3146 sizeof(pf_tcp_secret));
3147 pf_tcp_secret_init = 1;
3148 }
3149 ctx = pf_tcp_secret_ctx;
3150
3151 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_sport, sizeof(u_short));
3152 MD5Update(&ctx, (char *)&pd->hdr.tcp->th_dport, sizeof(u_short));
3153 if (pd->af == AF_INET6) {
3154 MD5Update(&ctx, (char *)&pd->src->v6, sizeof(struct in6_addr));
3155 MD5Update(&ctx, (char *)&pd->dst->v6, sizeof(struct in6_addr));
3156 } else {
3157 MD5Update(&ctx, (char *)&pd->src->v4, sizeof(struct in_addr));
3158 MD5Update(&ctx, (char *)&pd->dst->v4, sizeof(struct in_addr));
315a7da3 3159 }
ed1f0be2
JL
3160 MD5Final((u_char *)digest, &ctx);
3161 pf_tcp_iss_off += 4096;
3162 return (digest[0] + pd->hdr.tcp->th_seq + pf_tcp_iss_off);
315a7da3
JL
3163}
3164
02742ec6 3165int
315a7da3 3166pf_test_rule(struct pf_rule **rm, struct pf_state **sm, int direction,
02742ec6 3167 struct pfi_kif *kif, struct mbuf *m, int off, void *h,
70224baa
JL
3168 struct pf_pdesc *pd, struct pf_rule **am, struct pf_ruleset **rsm,
3169 struct ifqueue *ifq, struct inpcb *inp)
02742ec6
JS
3170{
3171 struct pf_rule *nr = NULL;
3172 struct pf_addr *saddr = pd->src, *daddr = pd->dst;
02742ec6 3173 sa_family_t af = pd->af;
02742ec6
JS
3174 struct pf_rule *r, *a = NULL;
3175 struct pf_ruleset *ruleset = NULL;
3176 struct pf_src_node *nsn = NULL;
315a7da3 3177 struct tcphdr *th = pd->hdr.tcp;
ed1f0be2
JL
3178 struct pf_state_key *skw = NULL, *sks = NULL;
3179 struct pf_state_key *sk = NULL, *nk = NULL;
02742ec6 3180 u_short reason;
315a7da3 3181 int rewrite = 0, hdrlen = 0;
70224baa 3182 int tag = -1, rtableid = -1;
70224baa
JL
3183 int asd = 0;
3184 int match = 0;
315a7da3 3185 int state_icmp = 0;
ed1f0be2
JL
3186 u_int16_t sport = 0, dport = 0;
3187 u_int16_t nport = 0, bport = 0;
3188 u_int16_t bproto_sum = 0, bip_sum = 0;
315a7da3 3189 u_int8_t icmptype = 0, icmpcode = 0;
70224baa 3190
ed1f0be2 3191
315a7da3 3192 if (direction == PF_IN && pf_check_congestion(ifq)) {
70224baa
JL
3193 REASON_SET(&reason, PFRES_CONGEST);
3194 return (PF_DROP);
3195 }
3196
3197 if (inp != NULL)
315a7da3
JL
3198 pd->lookup.done = pf_socket_lookup(direction, pd);
3199 else if (debug_pfugidhack) {
70224baa 3200 DPFPRINTF(PF_DEBUG_MISC, ("pf: unlocked lookup\n"));
315a7da3 3201 pd->lookup.done = pf_socket_lookup(direction, pd);
70224baa 3202 }
315a7da3 3203
315a7da3
JL
3204 switch (pd->proto) {
3205 case IPPROTO_TCP:
3206 sport = th->th_sport;
3207 dport = th->th_dport;
3208 hdrlen = sizeof(*th);
3209 break;
3210 case IPPROTO_UDP:
3211 sport = pd->hdr.udp->uh_sport;
3212 dport = pd->hdr.udp->uh_dport;
3213 hdrlen = sizeof(*pd->hdr.udp);
3214 break;
3215#ifdef INET
3216 case IPPROTO_ICMP:
3217 if (pd->af != AF_INET)
3218 break;
3219 sport = dport = pd->hdr.icmp->icmp_id;
ed1f0be2 3220 hdrlen = sizeof(*pd->hdr.icmp);
315a7da3
JL
3221 icmptype = pd->hdr.icmp->icmp_type;
3222 icmpcode = pd->hdr.icmp->icmp_code;
3223
3224 if (icmptype == ICMP_UNREACH ||
3225 icmptype == ICMP_SOURCEQUENCH ||
3226 icmptype == ICMP_REDIRECT ||
3227 icmptype == ICMP_TIMXCEED ||
3228 icmptype == ICMP_PARAMPROB)
3229 state_icmp++;
3230 break;
3231#endif /* INET */
3232#ifdef INET6
3233 case IPPROTO_ICMPV6:
ed1f0be2 3234 if (af != AF_INET6)
315a7da3
JL
3235 break;
3236 sport = dport = pd->hdr.icmp6->icmp6_id;
3237 hdrlen = sizeof(*pd->hdr.icmp6);
3238 icmptype = pd->hdr.icmp6->icmp6_type;
3239 icmpcode = pd->hdr.icmp6->icmp6_code;
3240
3241 if (icmptype == ICMP6_DST_UNREACH ||
3242 icmptype == ICMP6_PACKET_TOO_BIG ||
3243 icmptype == ICMP6_TIME_EXCEEDED ||
3244 icmptype == ICMP6_PARAM_PROB)
3245 state_icmp++;
3246 break;
3247#endif /* INET6 */
ed1f0be2
JL
3248 default:
3249 sport = dport = hdrlen = 0;
3250 break;
315a7da3 3251 }
02742ec6
JS
3252
3253 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3254
ed1f0be2
JL
3255 bport = nport = sport;
3256 /* check packet for BINAT/NAT/RDR */
3257 if ((nr = pf_get_translation(pd, m, off, direction, kif, &nsn,
3258 &skw, &sks, &sk, &nk, saddr, daddr, sport, dport)) != NULL) {
3259 if (nk == NULL || sk == NULL) {
3260 REASON_SET(&reason, PFRES_MEMORY);
3261 goto cleanup;
3262 }
3263
3264 if (pd->ip_sum)
3265 bip_sum = *pd->ip_sum;
3266
3267 switch (pd->proto) {
3268 case IPPROTO_TCP:
3269 bproto_sum = th->th_sum;
3270 pd->proto_sum = &th->th_sum;
3271
3272 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3273 nk->port[pd->sidx] != sport) {
315a7da3 3274 pf_change_ap(saddr, &th->th_sport, pd->ip_sum,
ed1f0be2
JL
3275 &th->th_sum, &nk->addr[pd->sidx],
3276 nk->port[pd->sidx], 0, af);
3277 pd->sport = &th->th_sport;
315a7da3 3278 sport = th->th_sport;
ed1f0be2
JL
3279 }
3280
3281 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3282 nk->port[pd->didx] != dport) {
3283 pf_change_ap(daddr, &th->th_dport, pd->ip_sum,
3284 &th->th_sum, &nk->addr[pd->didx],
3285 nk->port[pd->didx], 0, af);
3286 dport = th->th_dport;
3287 pd->dport = &th->th_dport;
3288 }
3289 rewrite++;
3290 break;
3291 case IPPROTO_UDP:
3292 bproto_sum = pd->hdr.udp->uh_sum;
3293 pd->proto_sum = &pd->hdr.udp->uh_sum;
3294
3295 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], af) ||
3296 nk->port[pd->sidx] != sport) {
315a7da3
JL
3297 pf_change_ap(saddr, &pd->hdr.udp->uh_sport,
3298 pd->ip_sum, &pd->hdr.udp->uh_sum,
ed1f0be2
JL
3299 &nk->addr[pd->sidx],
3300 nk->port[pd->sidx], 1, af);
315a7da3 3301 sport = pd->hdr.udp->uh_sport;
ed1f0be2
JL
3302 pd->sport = &pd->hdr.udp->uh_sport;
3303 }
3304
3305 if (PF_ANEQ(daddr, &nk->addr[pd->didx], af) ||
3306 nk->port[pd->didx] != dport) {
3307 pf_change_ap(daddr, &pd->hdr.udp->uh_dport,
3308 pd->ip_sum, &pd->hdr.udp->uh_sum,
3309 &nk->addr[pd->didx],
3310 nk->port[pd->didx], 1, af);
3311 dport = pd->hdr.udp->uh_dport;
3312 pd->dport = &pd->hdr.udp->uh_dport;
3313 }
3314 rewrite++;
3315 break;
315a7da3 3316#ifdef INET
ed1f0be2
JL
3317 case IPPROTO_ICMP:
3318 nk->port[0] = nk->port[1];
3319 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET))
315a7da3 3320 pf_change_a(&saddr->v4.s_addr, pd->ip_sum,
ed1f0be2
JL
3321 nk->addr[pd->sidx].v4.s_addr, 0);
3322
3323 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET))
3324 pf_change_a(&daddr->v4.s_addr, pd->ip_sum,
3325 nk->addr[pd->didx].v4.s_addr, 0);
3326
3327 if (nk->port[1] != pd->hdr.icmp->icmp_id) {
315a7da3 3328 pd->hdr.icmp->icmp_cksum = pf_cksum_fixup(
ed1f0be2
JL
3329 pd->hdr.icmp->icmp_cksum, sport,
3330 nk->port[1], 0);
3331 pd->hdr.icmp->icmp_id = nk->port[1];
3332 pd->sport = &pd->hdr.icmp->icmp_id;
3333 }
3334 m_copyback(m, off, ICMP_MINLEN, (caddr_t)pd->hdr.icmp);
3335 break;
315a7da3
JL
3336#endif /* INET */
3337#ifdef INET6
ed1f0be2
JL
3338 case IPPROTO_ICMPV6:
3339 nk->port[0] = nk->port[1];
3340 if (PF_ANEQ(saddr, &nk->addr[pd->sidx], AF_INET6))
315a7da3 3341 pf_change_a6(saddr, &pd->hdr.icmp6->icmp6_cksum,
ed1f0be2
JL
3342 &nk->addr[pd->sidx], 0);
3343
3344 if (PF_ANEQ(daddr, &nk->addr[pd->didx], AF_INET6))
3345 pf_change_a6(daddr, &pd->hdr.icmp6->icmp6_cksum,
3346 &nk->addr[pd->didx], 0);
3347 rewrite++;
3348 break;
315a7da3 3349#endif /* INET */
ed1f0be2
JL
3350 default:
3351 switch (af) {
315a7da3 3352#ifdef INET
ed1f0be2
JL
3353 case AF_INET:
3354 if (PF_ANEQ(saddr,
3355 &nk->addr[pd->sidx], AF_INET))
315a7da3 3356 pf_change_a(&saddr->v4.s_addr,
ed1f0be2
JL
3357 pd->ip_sum,
3358 nk->addr[pd->sidx].v4.s_addr, 0);
3359
3360 if (PF_ANEQ(daddr,
3361 &nk->addr[pd->didx], AF_INET))
3362 pf_change_a(&daddr->v4.s_addr,
3363 pd->ip_sum,
3364 nk->addr[pd->didx].v4.s_addr, 0);
3365 break;
315a7da3
JL
3366#endif /* INET */
3367#ifdef INET6
ed1f0be2
JL
3368 case AF_INET6:
3369 if (PF_ANEQ(saddr,
3370 &nk->addr[pd->sidx], AF_INET6))
3371 PF_ACPY(saddr, &nk->addr[pd->sidx], af);
315a7da3 3372
ed1f0be2
JL
3373 if (PF_ANEQ(daddr,
3374 &nk->addr[pd->didx], AF_INET6))
3375 PF_ACPY(saddr, &nk->addr[pd->didx], af);
315a7da3 3376 break;
315a7da3 3377#endif /* INET */
315a7da3 3378 }
ed1f0be2 3379 break;
02742ec6 3380 }
ed1f0be2
JL
3381 if (nr->natpass)
3382 r = NULL;
3383 pd->nat_rule = nr;
02742ec6
JS
3384 }
3385
3386 while (r != NULL) {
3387 r->evaluations++;
70224baa 3388 if (pfi_kif_match(r->kif, kif) == r->ifnot)
02742ec6
JS
3389 r = r->skip[PF_SKIP_IFP].ptr;
3390 else if (r->direction && r->direction != direction)
3391 r = r->skip[PF_SKIP_DIR].ptr;
3392 else if (r->af && r->af != af)
3393 r = r->skip[PF_SKIP_AF].ptr;
315a7da3 3394 else if (r->proto && r->proto != pd->proto)
02742ec6 3395 r = r->skip[PF_SKIP_PROTO].ptr;
70224baa
JL
3396 else if (PF_MISMATCHAW(&r->src.addr, saddr, af,
3397 r->src.neg, kif))
02742ec6 3398 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
315a7da3 3399 /* tcp/udp only. port_op always 0 in other cases */
02742ec6 3400 else if (r->src.port_op && !pf_match_port(r->src.port_op,
315a7da3 3401 r->src.port[0], r->src.port[1], sport))
02742ec6 3402 r = r->skip[PF_SKIP_SRC_PORT].ptr;
70224baa
JL
3403 else if (PF_MISMATCHAW(&r->dst.addr, daddr, af,
3404 r->dst.neg, NULL))
02742ec6 3405 r = r->skip[PF_SKIP_DST_ADDR].ptr;
315a7da3 3406 /* tcp/udp only. port_op always 0 in other cases */
02742ec6 3407 else if (r->dst.port_op && !pf_match_port(r->dst.port_op,
315a7da3 3408 r->dst.port[0], r->dst.port[1], dport))
02742ec6 3409 r = r->skip[PF_SKIP_DST_PORT].ptr;
315a7da3
JL
3410 /* icmp only. type always 0 in other cases */
3411 else if (r->type && r->type != icmptype + 1)
3412 r = TAILQ_NEXT(r, entries);
3413 /* icmp only. type always 0 in other cases */
3414 else if (r->code && r->code != icmpcode + 1)
3415 r = TAILQ_NEXT(r, entries);
70224baa 3416 else if (r->tos && !(r->tos == pd->tos))
02742ec6
JS
3417 r = TAILQ_NEXT(r, entries);
3418 else if (r->rule_flag & PFRULE_FRAGMENT)
3419 r = TAILQ_NEXT(r, entries);
315a7da3
JL
3420 else if (pd->proto == IPPROTO_TCP &&
3421 (r->flagset & th->th_flags) != r->flags)
02742ec6 3422 r = TAILQ_NEXT(r, entries);
315a7da3 3423 /* tcp/udp only. uid.op always 0 in other cases */
70224baa 3424 else if (r->uid.op && (pd->lookup.done || (pd->lookup.done =
315a7da3 3425 pf_socket_lookup(direction, pd), 1)) &&
02742ec6 3426 !pf_match_uid(r->uid.op, r->uid.uid[0], r->uid.uid[1],
70224baa 3427 pd->lookup.uid))
02742ec6 3428 r = TAILQ_NEXT(r, entries);
315a7da3 3429 /* tcp/udp only. gid.op always 0 in other cases */
70224baa 3430 else if (r->gid.op && (pd->lookup.done || (pd->lookup.done =
315a7da3 3431 pf_socket_lookup(direction, pd), 1)) &&
02742ec6 3432 !pf_match_gid(r->gid.op, r->gid.gid[0], r->gid.gid[1],
70224baa 3433 pd->lookup.gid))
02742ec6 3434 r = TAILQ_NEXT(r, entries);
ed1f0be2
JL
3435 else if (r->prob &&
3436 r->prob <= karc4random())
75fda04a 3437 r = TAILQ_NEXT(r, entries);
315a7da3 3438 else if (r->match_tag && !pf_match_tag(m, r, &tag))
02742ec6 3439 r = TAILQ_NEXT(r, entries);
315a7da3
JL
3440 else if (r->os_fingerprint != PF_OSFP_ANY &&
3441 (pd->proto != IPPROTO_TCP || !pf_osfp_match(
3442 pf_osfp_fingerprint(pd, m, off, th),
3443 r->os_fingerprint)))
02742ec6
JS
3444 r = TAILQ_NEXT(r, entries);
3445 else {
3446 if (r->tag)
3447 tag = r->tag;
70224baa
JL
3448 if (r->rtableid >= 0)
3449 rtableid = r->rtableid;
02742ec6 3450 if (r->anchor == NULL) {
70224baa 3451 match = 1;
02742ec6
JS
3452 *rm = r;
3453 *am = a;
3454 *rsm = ruleset;
3455 if ((*rm)->quick)
3456 break;
3457 r = TAILQ_NEXT(r, entries);
3458 } else
70224baa
JL
3459 pf_step_into_anchor(&asd, &ruleset,
3460 PF_RULESET_FILTER, &r, &a, &match);
02742ec6 3461 }
70224baa
JL
3462 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3463 PF_RULESET_FILTER, &r, &a, &match))
3464 break;
02742ec6
JS
3465 }
3466 r = *rm;
3467 a = *am;
3468 ruleset = *rsm;
3469
3470 REASON_SET(&reason, PFRES_MATCH);
3471
315a7da3 3472 if (r->log || (nr != NULL && nr->log)) {
02742ec6 3473 if (rewrite)
315a7da3 3474 m_copyback(m, off, hdrlen, pd->hdr.any);
70224baa
JL
3475 PFLOG_PACKET(kif, h, m, af, direction, reason, r->log ? r : nr,
3476 a, ruleset, pd);
02742ec6
JS
3477 }
3478
3479 if ((r->action == PF_DROP) &&
3480 ((r->rule_flag & PFRULE_RETURNRST) ||
3481 (r->rule_flag & PFRULE_RETURNICMP) ||
3482 (r->rule_flag & PFRULE_RETURN))) {
3483 /* undo NAT changes, if they have taken place */
3484 if (nr != NULL) {
ed1f0be2
JL
3485 PF_ACPY(saddr, &sk->addr[pd->sidx], af);
3486 PF_ACPY(daddr, &sk->addr[pd->didx], af);
3487 if (pd->sport)
3488 *pd->sport = sk->port[pd->sidx];
3489 if (pd->dport)
3490 *pd->dport = sk->port[pd->didx];
3491 if (pd->proto_sum)
3492 *pd->proto_sum = bproto_sum;
3493 if (pd->ip_sum)
3494 *pd->ip_sum = bip_sum;
3495 m_copyback(m, off, hdrlen, pd->hdr.any);
02742ec6 3496 }
315a7da3
JL
3497 if (pd->proto == IPPROTO_TCP &&
3498 ((r->rule_flag & PFRULE_RETURNRST) ||
02742ec6
JS
3499 (r->rule_flag & PFRULE_RETURN)) &&
3500 !(th->th_flags & TH_RST)) {
315a7da3 3501 u_int32_t ack = ntohl(th->th_seq) + pd->p_len;
ed1f0be2
JL
3502 int len = 0;
3503 struct ip *h4;
3504 struct ip6_hdr *h6;
3505
3506 switch (af) {
3507 case AF_INET:
3508 h4 = mtod(m, struct ip *);
3509 len = h4->ip_len - off;
3510 break;
2dba2225 3511#ifdef INET6
ed1f0be2
JL
3512 case AF_INET6:
3513 h6 = mtod(m, struct ip6_hdr *);
3514 len = h6->ip6_plen - (off - sizeof(*h6));
3515 break;
2dba2225 3516#endif
ed1f0be2 3517 }
02742ec6 3518
ed1f0be2 3519 if (pf_check_proto_cksum(m, off, len, IPPROTO_TCP, af))
315a7da3
JL
3520 REASON_SET(&reason, PFRES_PROTCKSUM);
3521 else {
3522 if (th->th_flags & TH_SYN)
3523 ack++;
3524 if (th->th_flags & TH_FIN)
3525 ack++;
3526 pf_send_tcp(r, af, pd->dst,
3527 pd->src, th->th_dport, th->th_sport,
3528 ntohl(th->th_ack), ack, TH_RST|TH_ACK, 0, 0,
3529 r->return_ttl, 1, 0, pd->eh, kif->pfik_ifp);
3530 }
ed1f0be2
JL
3531 } else if (pd->proto != IPPROTO_ICMP && af == AF_INET &&
3532 r->return_icmp)
02742ec6
JS
3533 pf_send_icmp(m, r->return_icmp >> 8,
3534 r->return_icmp & 255, af, r);
ed1f0be2
JL
3535 else if (pd->proto != IPPROTO_ICMPV6 && af == AF_INET6 &&
3536 r->return_icmp6)
02742ec6
JS
3537 pf_send_icmp(m, r->return_icmp6 >> 8,
3538 r->return_icmp6 & 255, af, r);
3539 }
3540
315a7da3 3541 if (r->action == PF_DROP)
ed1f0be2 3542 goto cleanup;
02742ec6 3543
315a7da3 3544 if (pf_tag_packet(m, tag, rtableid)) {
70224baa 3545 REASON_SET(&reason, PFRES_MEMORY);
ed1f0be2 3546 goto cleanup;
70224baa 3547 }
02742ec6 3548
315a7da3
JL
3549 if (!state_icmp && (r->keep_state || nr != NULL ||
3550 (pd->flags & PFDESC_TCP_NORM))) {
ed1f0be2
JL
3551 int action;
3552 action = pf_create_state(r, nr, a, pd, nsn, skw, sks, nk, sk, m,
3553 off, sport, dport, &rewrite, kif, sm, tag, bproto_sum,
3554 bip_sum, hdrlen);
3555 if (action != PF_PASS)
3556 return (action);
3557 }
3558
3559 /* copy back packet headers if we performed NAT operations */
3560 if (rewrite)
3561 m_copyback(m, off, hdrlen, pd->hdr.any);
3562
3563 return (PF_PASS);
3564
02742ec6 3565cleanup:
ed1f0be2
JL
3566 if (sk != NULL)
3567 pool_put(&pf_state_key_pl, sk);
3568 if (nk != NULL)
3569 pool_put(&pf_state_key_pl, nk);
3570 return (PF_DROP);
3571}
02742ec6 3572
ed1f0be2
JL
3573static __inline int
3574pf_create_state(struct pf_rule *r, struct pf_rule *nr, struct pf_rule *a,
3575 struct pf_pdesc *pd, struct pf_src_node *nsn, struct pf_state_key *skw,
3576 struct pf_state_key *sks, struct pf_state_key *nk, struct pf_state_key *sk,
3577 struct mbuf *m, int off, u_int16_t sport, u_int16_t dport, int *rewrite,
3578 struct pfi_kif *kif, struct pf_state **sm, int tag, u_int16_t bproto_sum,
3579 u_int16_t bip_sum, int hdrlen)
3580{
3581 struct pf_state *s = NULL;
3582 struct pf_src_node *sn = NULL;
3583 struct tcphdr *th = pd->hdr.tcp;
3584 u_int16_t mss = tcp_mssdflt;
3585 u_short reason;
315a7da3 3586
ed1f0be2
JL
3587 /* check maximums */
3588 if (r->max_states && (r->states_cur >= r->max_states)) {
3589 pf_status.lcounters[LCNT_STATES]++;
3590 REASON_SET(&reason, PFRES_MAXSTATES);
3591 return (PF_DROP);
3592 }
3593 /* src node for filter rule */
3594 if ((r->rule_flag & PFRULE_SRCTRACK ||
3595 r->rpool.opts & PF_POOL_STICKYADDR) &&
3596 pf_insert_src_node(&sn, r, pd->src, pd->af) != 0) {
3597 REASON_SET(&reason, PFRES_SRCLIMIT);
3598 goto csfailed;
3599 }
3600 /* src node for translation rule */
3601 if (nr != NULL && (nr->rpool.opts & PF_POOL_STICKYADDR) &&
3602 pf_insert_src_node(&nsn, nr, &sk->addr[pd->sidx], pd->af)) {
3603 REASON_SET(&reason, PFRES_SRCLIMIT);
3604 goto csfailed;
3605 }
3606 s = pool_get(&pf_state_pl, PR_NOWAIT | PR_ZERO);
3607 if (s == NULL) {
3608 REASON_SET(&reason, PFRES_MEMORY);
3609 goto csfailed;
3610 }
3611 s->id = 0; /* XXX Do we really need that? not in OpenBSD */
3612 s->creatorid = 0;
3613 s->rule.ptr = r;
3614 s->nat_rule.ptr = nr;
3615 s->anchor.ptr = a;
3616 STATE_INC_COUNTERS(s);
3617 if (r->allow_opts)
3618 s->state_flags |= PFSTATE_ALLOWOPTS;
3619 if (r->rule_flag & PFRULE_STATESLOPPY)
3620 s->state_flags |= PFSTATE_SLOPPY;
3621 s->log = r->log & PF_LOG_ALL;
3622 if (nr != NULL)
3623 s->log |= nr->log & PF_LOG_ALL;
3624 switch (pd->proto) {
3625 case IPPROTO_TCP:
3626 s->src.seqlo = ntohl(th->th_seq);
3627 s->src.seqhi = s->src.seqlo + pd->p_len + 1;
3628 if ((th->th_flags & (TH_SYN|TH_ACK)) == TH_SYN &&
3629 r->keep_state == PF_STATE_MODULATE) {
3630 /* Generate sequence number modulator */
3631 if ((s->src.seqdiff = pf_tcp_iss(pd) - s->src.seqlo) ==
3632 0)
3633 s->src.seqdiff = 1;
3634 pf_change_a(&th->th_seq, &th->th_sum,
3635 htonl(s->src.seqlo + s->src.seqdiff), 0);
3636 *rewrite = 1;
3637 } else
3638 s->src.seqdiff = 0;
3639 if (th->th_flags & TH_SYN) {
3640 s->src.seqhi++;
3641 s->src.wscale = pf_get_wscale(m, off,
3642 th->th_off, pd->af);
315a7da3 3643 }
ed1f0be2
JL
3644 s->src.max_win = MAX(ntohs(th->th_win), 1);
3645 if (s->src.wscale & PF_WSCALE_MASK) {
3646 /* Remove scale factor from initial window */
3647 int win = s->src.max_win;
3648 win += 1 << (s->src.wscale & PF_WSCALE_MASK);
3649 s->src.max_win = (win - 1) >>
3650 (s->src.wscale & PF_WSCALE_MASK);
315a7da3 3651 }
ed1f0be2
JL
3652 if (th->th_flags & TH_FIN)
3653 s->src.seqhi++;
3654 s->dst.seqhi = 1;
3655 s->dst.max_win = 1;
3656 s->src.state = TCPS_SYN_SENT;
3657 s->dst.state = TCPS_CLOSED;
3658 s->timeout = PFTM_TCP_FIRST_PACKET;
3659 break;
3660 case IPPROTO_UDP:
3661 s->src.state = PFUDPS_SINGLE;
3662 s->dst.state = PFUDPS_NO_TRAFFIC;
3663 s->timeout = PFTM_UDP_FIRST_PACKET;
3664 break;
3665 case IPPROTO_ICMP:
315a7da3 3666#ifdef INET6
ed1f0be2 3667 case IPPROTO_ICMPV6:
315a7da3 3668#endif
ed1f0be2
JL
3669 s->timeout = PFTM_ICMP_FIRST_PACKET;
3670 break;
3671 default:
3672 s->src.state = PFOTHERS_SINGLE;
3673 s->dst.state = PFOTHERS_NO_TRAFFIC;
3674 s->timeout = PFTM_OTHER_FIRST_PACKET;
3675 }
315a7da3 3676
ed1f0be2
JL
3677 s->creation = time_second;
3678 s->expire = time_second;
315a7da3 3679
ed1f0be2
JL
3680 if (sn != NULL) {
3681 s->src_node = sn;
3682 s->src_node->states++;
3683 }
3684 if (nsn != NULL) {
3685 /* XXX We only modify one side for now. */
3686 PF_ACPY(&nsn->raddr, &nk->addr[1], pd->af);
3687 s->nat_src_node = nsn;
3688 s->nat_src_node->states++;
3689 }
3690 if (pd->proto == IPPROTO_TCP) {
3691 if ((pd->flags & PFDESC_TCP_NORM) && pf_normalize_tcp_init(m,
3692 off, pd, th, &s->src, &s->dst)) {
3693 REASON_SET(&reason, PFRES_MEMORY);
02742ec6 3694 pf_src_tree_remove_state(s);
70224baa 3695 STATE_DEC_COUNTERS(s);
02742ec6
JS
3696 pool_put(&pf_state_pl, s);
3697 return (PF_DROP);
70224baa 3698 }
ed1f0be2
JL
3699 if ((pd->flags & PFDESC_TCP_NORM) && s->src.scrub &&
3700 pf_normalize_tcp_stateful(m, off, pd, &reason, th, s,
3701 &s->src, &s->dst, rewrite)) {
3702 /* This really shouldn't happen!!! */
3703 DPFPRINTF(PF_DEBUG_URGENT,
3704 ("pf_normalize_tcp_stateful failed on first pkt"));
3705 pf_normalize_tcp_cleanup(s);
3706 pf_src_tree_remove_state(s);
3707 STATE_DEC_COUNTERS(s);
3708 pool_put(&pf_state_pl, s);
3709 return (PF_DROP);
315a7da3 3710 }
02742ec6 3711 }
ed1f0be2 3712 s->direction = pd->dir;
02742ec6 3713
ed1f0be2
JL
3714 if (sk == NULL && pf_state_key_setup(pd, nr, &skw, &sks, &sk, &nk,
3715 pd->src, pd->dst, sport, dport))
3716 goto csfailed;
3717
3718 if (pf_state_insert(BOUND_IFACE(r, kif), skw, sks, s)) {
3719 if (pd->proto == IPPROTO_TCP)
3720 pf_normalize_tcp_cleanup(s);
3721 REASON_SET(&reason, PFRES_STATEINS);
3722 pf_src_tree_remove_state(s);
3723 STATE_DEC_COUNTERS(s);
3724 pool_put(&pf_state_pl, s);
3725 return (PF_DROP);
3726 } else
3727 *sm = s;
3728
3729 pf_set_rt_ifp(s, pd->src); /* needs s->state_key set */
3730 if (tag > 0) {
3731 pf_tag_ref(tag);
3732 s->tag = tag;
3733 }
3734 if (pd->proto == IPPROTO_TCP && (th->th_flags & (TH_SYN|TH_ACK)) ==
3735 TH_SYN && r->keep_state == PF_STATE_SYNPROXY) {
3736 s->src.state = PF_TCPS_PROXY_SRC;
3737 /* undo NAT changes, if they have taken place */
3738 if (nr != NULL) {
3739 struct pf_state_key *skt = s->key[PF_SK_WIRE];
3740 if (pd->dir == PF_OUT)
3741 skt = s->key[PF_SK_STACK];
3742 PF_ACPY(pd->src, &skt->addr[pd->sidx], pd->af);
3743 PF_ACPY(pd->dst, &skt->addr[pd->didx], pd->af);
3744 if (pd->sport)
3745 *pd->sport = skt->port[pd->sidx];
3746 if (pd->dport)
3747 *pd->dport = skt->port[pd->didx];
3748 if (pd->proto_sum)
3749 *pd->proto_sum = bproto_sum;
3750 if (pd->ip_sum)
3751 *pd->ip_sum = bip_sum;
3752 m_copyback(m, off, hdrlen, pd->hdr.any);
3753 }
3754 s->src.seqhi = htonl(karc4random());
3755 /* Find mss option */
3756 mss = pf_get_mss(m, off, th->th_off, pd->af);
3757 mss = pf_calc_mss(pd->src, pd->af, mss);
3758 mss = pf_calc_mss(pd->dst, pd->af, mss);
3759 s->src.mss = mss;
3760 pf_send_tcp(r, pd->af, pd->dst, pd->src, th->th_dport,
3761 th->th_sport, s->src.seqhi, ntohl(th->th_seq) + 1,
3762 TH_SYN|TH_ACK, 0, s->src.mss, 0, 1, 0, NULL, NULL);
3763 REASON_SET(&reason, PFRES_SYNPROXY);
3764 return (PF_SYNPROXY_DROP);
3765 }
315a7da3 3766
02742ec6 3767 return (PF_PASS);
ed1f0be2
JL
3768
3769csfailed:
3770 if (sk != NULL)
3771 pool_put(&pf_state_key_pl, sk);
3772 if (nk != NULL)
3773 pool_put(&pf_state_key_pl, nk);
3774
3775 if (sn != NULL && sn->states == 0 && sn->expire == 0) {
3776 RB_REMOVE(pf_src_tree, &tree_src_tracking, sn);
3777 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3778 pf_status.src_nodes--;
3779 pool_put(&pf_src_tree_pl, sn);
3780 }
3781 if (nsn != sn && nsn != NULL && nsn->states == 0 && nsn->expire == 0) {
3782 RB_REMOVE(pf_src_tree, &tree_src_tracking, nsn);
3783 pf_status.scounters[SCNT_SRC_NODE_REMOVALS]++;
3784 pf_status.src_nodes--;
3785 pool_put(&pf_src_tree_pl, nsn);
3786 }
3787 return (PF_DROP);
02742ec6
JS
3788}
3789
3790int
3791pf_test_fragment(struct pf_rule **rm, int direction, struct pfi_kif *kif,
3792 struct mbuf *m, void *h, struct pf_pdesc *pd, struct pf_rule **am,
3793 struct pf_ruleset **rsm)
3794{
3795 struct pf_rule *r, *a = NULL;
3796 struct pf_ruleset *ruleset = NULL;
3797 sa_family_t af = pd->af;
3798 u_short reason;
3799 int tag = -1;
70224baa
JL
3800 int asd = 0;
3801 int match = 0;
02742ec6
JS
3802
3803 r = TAILQ_FIRST(pf_main_ruleset.rules[PF_RULESET_FILTER].active.ptr);
3804 while (r != NULL) {
3805 r->evaluations++;
70224baa 3806 if (pfi_kif_match(r->kif, kif) == r->ifnot)
02742ec6
JS
3807 r = r->skip[PF_SKIP_IFP].ptr;
3808 else if (r->direction && r->direction != direction)
3809 r = r->skip[PF_SKIP_DIR].ptr;
3810 else if (r->af && r->af != af)
3811 r = r->skip[PF_SKIP_AF].ptr;
3812 else if (r->proto && r->proto != pd->proto)
3813 r = r->skip[PF_SKIP_PROTO].ptr;
70224baa
JL
3814 else if (PF_MISMATCHAW(&r->src.addr, pd->src, af,
3815 r->src.neg, kif))
02742ec6 3816 r = r->skip[PF_SKIP_SRC_ADDR].ptr;
70224baa
JL
3817 else if (PF_MISMATCHAW(&r->dst.addr, pd->dst, af,
3818 r->dst.neg, NULL))
02742ec6 3819 r = r->skip[PF_SKIP_DST_ADDR].ptr;
70224baa 3820 else if (r->tos && !(r->tos == pd->tos))
02742ec6 3821 r = TAILQ_NEXT(r, entries);
a814431a
MD
3822 else if (r->os_fingerprint != PF_OSFP_ANY)
3823 r = TAILQ_NEXT(r, entries);
3824 else if (pd->proto == IPPROTO_UDP &&
3825 (r->src.port_op || r->dst.port_op))
3826 r = TAILQ_NEXT(r, entries);
3827 else if (pd->proto == IPPROTO_TCP &&
3828 (r->src.port_op || r->dst.port_op || r->flagset))
3829 r = TAILQ_NEXT(r, entries);
3830 else if ((pd->proto == IPPROTO_ICMP ||
3831 pd->proto == IPPROTO_ICMPV6) &&
3832 (r->type || r->code))
02742ec6 3833 r = TAILQ_NEXT(r, entries);
75fda04a
MD
3834 else if (r->prob && r->prob <= karc4random())
3835 r = TAILQ_NEXT(r, entries);
315a7da3 3836 else if (r->match_tag && !pf_match_tag(m, r, &tag))
02742ec6 3837 r = TAILQ_NEXT(r, entries);
02742ec6
JS
3838 else {
3839 if (r->anchor == NULL) {
70224baa 3840 match = 1;
02742ec6
JS
3841 *rm = r;
3842 *am = a;
3843 *rsm = ruleset;
3844 if ((*rm)->quick)
3845 break;
3846 r = TAILQ_NEXT(r, entries);
3847 } else
70224baa
JL
3848 pf_step_into_anchor(&asd, &ruleset,
3849 PF_RULESET_FILTER, &r, &a, &match);
02742ec6 3850 }
70224baa
JL
3851 if (r == NULL && pf_step_out_of_anchor(&asd, &ruleset,
3852 PF_RULESET_FILTER, &r, &a, &match))
3853 break;
02742ec6
JS
3854 }
3855 r = *rm;
3856 a = *am;
3857 ruleset = *rsm;
3858
3859 REASON_SET(&reason, PFRES_MATCH);
3860
3861 if (r->log)
70224baa
JL
3862 PFLOG_PACKET(kif, h, m, af, direction, reason, r, a, ruleset,
3863 pd);
02742ec6
JS
3864
3865 if (r->action != PF_PASS)
3866 return (PF_DROP);
3867
315a7da3 3868 if (pf_tag_packet(m, tag, -1)) {
70224baa
JL
3869 REASON_SET(&reason, PFRES_MEMORY);
3870 return (PF_DROP);
3871 }
02742ec6
JS
3872
3873 return (PF_PASS);
3874}
3875
3876int
ed1f0be2
JL
3877pf_tcp_track_full(struct pf_state_peer *src, struct pf_state_peer *dst,
3878 struct pf_state **state, struct pfi_kif *kif, struct mbuf *m, int off,
3879 struct pf_pdesc *pd, u_short *reason, int *copyback)
02742ec6 3880{
02742ec6
JS
3881 struct tcphdr *th = pd->hdr.tcp;
3882 u_int16_t win = ntohs(th->th_win);
70224baa 3883 u_int32_t ack, end, seq, orig_seq;
02742ec6
JS
3884 u_int8_t sws, dws;
3885 int ackskew;
02742ec6
JS
3886
3887 if (src->wscale && dst->wscale && !(th->th_flags & TH_SYN)) {
3888 sws = src->wscale & PF_WSCALE_MASK;
3889 dws = dst->wscale & PF_WSCALE_MASK;
3890 } else
3891 sws = dws = 0;
3892
3893 /*
3894 * Sequence tracking algorithm from Guido van Rooij's paper:
3895 * http://www.madison-gurkha.com/publications/tcp_filtering/
3896 * tcp_filtering.ps
<