2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2001 Daniel Hartmeier
5 * Copyright (c) 2002 - 2008 Henning Brauer
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * - Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * - Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
32 * Effort sponsored in part by the Defense Advanced Research Projects
33 * Agency (DARPA) and Air Force Research Laboratory, Air Force
34 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
36 * $OpenBSD: pf_lb.c,v 1.2 2009/02/12 02:13:15 sthen Exp $
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
44 #include "opt_inet6.h"
46 #include <sys/param.h>
49 #include <sys/rwlock.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
55 #include <net/pfvar.h>
56 #include <net/if_pflog.h>
58 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
60 static void pf_hash(struct pf_addr *, struct pf_addr *,
61 struct pf_poolhashkey *, sa_family_t);
62 static struct pf_rule *pf_match_translation(struct pf_pdesc *, struct mbuf *,
63 int, int, struct pfi_kif *,
64 struct pf_addr *, u_int16_t, struct pf_addr *,
65 uint16_t, int, struct pf_anchor_stackframe *);
66 static int pf_get_sport(sa_family_t, uint8_t, struct pf_rule *,
67 struct pf_addr *, uint16_t, struct pf_addr *, uint16_t, struct pf_addr *,
68 uint16_t *, uint16_t, uint16_t, struct pf_src_node **);
72 a -= b; a -= c; a ^= (c >> 13); \
73 b -= c; b -= a; b ^= (a << 8); \
74 c -= a; c -= b; c ^= (b >> 13); \
75 a -= b; a -= c; a ^= (c >> 12); \
76 b -= c; b -= a; b ^= (a << 16); \
77 c -= a; c -= b; c ^= (b >> 5); \
78 a -= b; a -= c; a ^= (c >> 3); \
79 b -= c; b -= a; b ^= (a << 10); \
80 c -= a; c -= b; c ^= (b >> 15); \
84 * hash function based on bridge_hash in if_bridge.c
87 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
88 struct pf_poolhashkey *key, sa_family_t af)
90 u_int32_t a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
95 a += inaddr->addr32[0];
98 hash->addr32[0] = c + key->key32[2];
103 a += inaddr->addr32[0];
104 b += inaddr->addr32[2];
107 a += inaddr->addr32[1];
108 b += inaddr->addr32[3];
112 a += inaddr->addr32[2];
113 b += inaddr->addr32[1];
117 a += inaddr->addr32[3];
118 b += inaddr->addr32[0];
127 static struct pf_rule *
128 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
129 int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
130 struct pf_addr *daddr, uint16_t dport, int rs_num,
131 struct pf_anchor_stackframe *anchor_stack)
133 struct pf_rule *r, *rm = NULL;
134 struct pf_ruleset *ruleset = NULL;
139 r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
140 while (r && rm == NULL) {
141 struct pf_rule_addr *src = NULL, *dst = NULL;
142 struct pf_addr_wrap *xdst = NULL;
144 if (r->action == PF_BINAT && direction == PF_IN) {
146 if (r->rpool.cur != NULL)
147 xdst = &r->rpool.cur->addr;
154 if (pfi_kif_match(r->kif, kif) == r->ifnot)
155 r = r->skip[PF_SKIP_IFP].ptr;
156 else if (r->direction && r->direction != direction)
157 r = r->skip[PF_SKIP_DIR].ptr;
158 else if (r->af && r->af != pd->af)
159 r = r->skip[PF_SKIP_AF].ptr;
160 else if (r->proto && r->proto != pd->proto)
161 r = r->skip[PF_SKIP_PROTO].ptr;
162 else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
163 src->neg, kif, M_GETFIB(m)))
164 r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
165 PF_SKIP_DST_ADDR].ptr;
166 else if (src->port_op && !pf_match_port(src->port_op,
167 src->port[0], src->port[1], sport))
168 r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
169 PF_SKIP_DST_PORT].ptr;
170 else if (dst != NULL &&
171 PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL,
173 r = r->skip[PF_SKIP_DST_ADDR].ptr;
174 else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
175 0, NULL, M_GETFIB(m)))
176 r = TAILQ_NEXT(r, entries);
177 else if (dst != NULL && dst->port_op &&
178 !pf_match_port(dst->port_op, dst->port[0],
179 dst->port[1], dport))
180 r = r->skip[PF_SKIP_DST_PORT].ptr;
181 else if (r->match_tag && !pf_match_tag(m, r, &tag,
182 pd->pf_mtag ? pd->pf_mtag->tag : 0))
183 r = TAILQ_NEXT(r, entries);
184 else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
185 IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
186 off, pd->hdr.tcp), r->os_fingerprint)))
187 r = TAILQ_NEXT(r, entries);
191 if (r->rtableid >= 0)
192 rtableid = r->rtableid;
193 if (r->anchor == NULL) {
196 pf_step_into_anchor(anchor_stack, &asd,
197 &ruleset, rs_num, &r, NULL, NULL);
200 pf_step_out_of_anchor(anchor_stack, &asd, &ruleset,
201 rs_num, &r, NULL, NULL);
204 if (tag > 0 && pf_tag_packet(m, pd, tag))
207 M_SETFIB(m, rtableid);
209 if (rm != NULL && (rm->action == PF_NONAT ||
210 rm->action == PF_NORDR || rm->action == PF_NOBINAT))
216 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
217 struct pf_addr *saddr, uint16_t sport, struct pf_addr *daddr,
218 uint16_t dport, struct pf_addr *naddr, uint16_t *nport, uint16_t low,
219 uint16_t high, struct pf_src_node **sn)
221 struct pf_state_key_cmp key;
222 struct pf_addr init_addr;
224 bzero(&init_addr, sizeof(init_addr));
225 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
228 if (proto == IPPROTO_ICMP) {
233 bzero(&key, sizeof(key));
237 PF_ACPY(&key.addr[0], daddr, key.af);
240 PF_ACPY(&key.addr[1], naddr, key.af);
243 * port search; start random, step;
244 * similar 2 portloop in in_pcbbind
246 if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
247 proto == IPPROTO_ICMP) || (low == 0 && high == 0)) {
249 * XXX bug: icmp states don't use the id on both sides.
250 * (traceroute -I through nat)
253 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
257 } else if (low == high) {
258 key.port[1] = htons(low);
259 if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
273 cut = arc4random() % (1 + high - low) + low;
274 /* low <= cut <= high */
275 for (tmp = cut; tmp <= high && tmp <= 0xffff; ++tmp) {
276 key.port[1] = htons(tmp);
277 if (pf_find_state_all(&key, PF_IN, NULL) ==
284 for (tmp -= 1; tmp >= low && tmp <= 0xffff; --tmp) {
285 key.port[1] = htons(tmp);
286 if (pf_find_state_all(&key, PF_IN, NULL) ==
294 switch (r->rpool.opts & PF_POOL_TYPEMASK) {
296 case PF_POOL_ROUNDROBIN:
297 if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
301 case PF_POOL_SRCHASH:
302 case PF_POOL_BITMASK:
306 } while (! PF_AEQ(&init_addr, naddr, af) );
307 return (1); /* none available */
311 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
312 struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
314 struct pf_pool *rpool = &r->rpool;
315 struct pf_addr *raddr = NULL, *rmask = NULL;
317 /* Try to find a src_node if none was given and this
318 is a sticky-address rule. */
319 if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
320 (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE)
321 *sn = pf_find_src_node(saddr, r, af, 0);
323 /* If a src_node was found or explicitly given and it has a non-zero
324 route address, use this address. A zeroed address is found if the
325 src node was created just a moment ago in pf_create_state and it
326 needs to be filled in with routing decision calculated here. */
327 if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
328 PF_ACPY(naddr, &(*sn)->raddr, af);
329 if (V_pf_status.debug >= PF_DEBUG_MISC) {
330 printf("pf_map_addr: src tracking maps ");
331 pf_print_host(saddr, 0, af);
333 pf_print_host(naddr, 0, af);
339 /* Find the route using chosen algorithm. Store the found route
340 in src_node if it was given or found. */
341 if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
343 if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
347 if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
348 (rpool->opts & PF_POOL_TYPEMASK) !=
351 raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
352 rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
357 if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
358 (rpool->opts & PF_POOL_TYPEMASK) !=
361 raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
362 rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
366 } else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
367 if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
368 return (1); /* unsupported */
370 raddr = &rpool->cur->addr.v.a.addr;
371 rmask = &rpool->cur->addr.v.a.mask;
374 switch (rpool->opts & PF_POOL_TYPEMASK) {
376 PF_ACPY(naddr, raddr, af);
378 case PF_POOL_BITMASK:
379 PF_POOLMASK(naddr, raddr, rmask, saddr, af);
382 if (init_addr != NULL && PF_AZERO(init_addr, af)) {
386 rpool->counter.addr32[0] = htonl(arc4random());
391 if (rmask->addr32[3] != 0xffffffff)
392 rpool->counter.addr32[3] =
396 if (rmask->addr32[2] != 0xffffffff)
397 rpool->counter.addr32[2] =
401 if (rmask->addr32[1] != 0xffffffff)
402 rpool->counter.addr32[1] =
406 if (rmask->addr32[0] != 0xffffffff)
407 rpool->counter.addr32[0] =
412 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
413 PF_ACPY(init_addr, naddr, af);
416 PF_AINC(&rpool->counter, af);
417 PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
420 case PF_POOL_SRCHASH:
422 unsigned char hash[16];
424 pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
425 PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
428 case PF_POOL_ROUNDROBIN:
430 struct pf_pooladdr *acur = rpool->cur;
433 * XXXGL: in the round-robin case we need to store
434 * the round-robin machine state in the rule, thus
435 * forwarding thread needs to modify rule.
437 * This is done w/o locking, because performance is assumed
438 * more important than round-robin precision.
440 * In the simpliest case we just update the "rpool->cur"
441 * pointer. However, if pool contains tables or dynamic
442 * addresses, then "tblidx" is also used to store machine
443 * state. Since "tblidx" is int, concurrent access to it can't
444 * lead to inconsistence, only to lost of precision.
446 * Things get worse, if table contains not hosts, but
447 * prefixes. In this case counter also stores machine state,
448 * and for IPv6 address, counter can't be updated atomically.
449 * Probably, using round-robin on a table containing IPv6
450 * prefixes (or even IPv4) would cause a panic.
453 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
454 if (!pfr_pool_get(rpool->cur->addr.p.tbl,
455 &rpool->tblidx, &rpool->counter, af))
457 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
458 if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
459 &rpool->tblidx, &rpool->counter, af))
461 } else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
465 if (TAILQ_NEXT(rpool->cur, entries) == NULL)
466 rpool->cur = TAILQ_FIRST(&rpool->list);
468 rpool->cur = TAILQ_NEXT(rpool->cur, entries);
469 if (rpool->cur->addr.type == PF_ADDR_TABLE) {
471 if (pfr_pool_get(rpool->cur->addr.p.tbl,
472 &rpool->tblidx, &rpool->counter, af)) {
473 /* table contains no address of type 'af' */
474 if (rpool->cur != acur)
478 } else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
480 if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
481 &rpool->tblidx, &rpool->counter, af)) {
482 /* table contains no address of type 'af' */
483 if (rpool->cur != acur)
488 raddr = &rpool->cur->addr.v.a.addr;
489 rmask = &rpool->cur->addr.v.a.mask;
490 PF_ACPY(&rpool->counter, raddr, af);
494 PF_ACPY(naddr, &rpool->counter, af);
495 if (init_addr != NULL && PF_AZERO(init_addr, af))
496 PF_ACPY(init_addr, naddr, af);
497 PF_AINC(&rpool->counter, af);
502 PF_ACPY(&(*sn)->raddr, naddr, af);
504 if (V_pf_status.debug >= PF_DEBUG_MISC &&
505 (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
506 printf("pf_map_addr: selected address ");
507 pf_print_host(naddr, 0, af);
515 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
516 struct pfi_kif *kif, struct pf_src_node **sn,
517 struct pf_state_key **skp, struct pf_state_key **nkp,
518 struct pf_addr *saddr, struct pf_addr *daddr,
519 uint16_t sport, uint16_t dport, struct pf_anchor_stackframe *anchor_stack)
521 struct pf_rule *r = NULL;
522 struct pf_addr *naddr;
526 KASSERT(*skp == NULL, ("*skp not NULL"));
527 KASSERT(*nkp == NULL, ("*nkp not NULL"));
529 if (direction == PF_OUT) {
530 r = pf_match_translation(pd, m, off, direction, kif, saddr,
531 sport, daddr, dport, PF_RULESET_BINAT, anchor_stack);
533 r = pf_match_translation(pd, m, off, direction, kif,
534 saddr, sport, daddr, dport, PF_RULESET_NAT,
537 r = pf_match_translation(pd, m, off, direction, kif, saddr,
538 sport, daddr, dport, PF_RULESET_RDR, anchor_stack);
540 r = pf_match_translation(pd, m, off, direction, kif,
541 saddr, sport, daddr, dport, PF_RULESET_BINAT,
555 *skp = pf_state_key_setup(pd, saddr, daddr, sport, dport);
558 *nkp = pf_state_key_clone(*skp);
560 uma_zfree(V_pf_state_key_z, *skp);
565 /* XXX We only modify one side for now. */
566 naddr = &(*nkp)->addr[1];
567 nport = &(*nkp)->port[1];
571 if (pf_get_sport(pd->af, pd->proto, r, saddr, sport, daddr,
572 dport, naddr, nport, r->rpool.proxy_port[0],
573 r->rpool.proxy_port[1], sn)) {
574 DPFPRINTF(PF_DEBUG_MISC,
575 ("pf: NAT proxy port allocation (%u-%u) failed\n",
576 r->rpool.proxy_port[0], r->rpool.proxy_port[1]));
583 if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
587 if (r->rpool.cur->addr.p.dyn->
591 &r->rpool.cur->addr.p.dyn->
593 &r->rpool.cur->addr.p.dyn->
594 pfid_mask4, saddr, AF_INET);
599 if (r->rpool.cur->addr.p.dyn->
603 &r->rpool.cur->addr.p.dyn->
605 &r->rpool.cur->addr.p.dyn->
606 pfid_mask6, saddr, AF_INET6);
612 &r->rpool.cur->addr.v.a.addr,
613 &r->rpool.cur->addr.v.a.mask, saddr,
617 if (r->src.addr.type == PF_ADDR_DYNIFTL) {
621 if (r->src.addr.p.dyn-> pfid_acnt4 < 1)
624 &r->src.addr.p.dyn->pfid_addr4,
625 &r->src.addr.p.dyn->pfid_mask4,
631 if (r->src.addr.p.dyn->pfid_acnt6 < 1)
634 &r->src.addr.p.dyn->pfid_addr6,
635 &r->src.addr.p.dyn->pfid_mask6,
641 PF_POOLMASK(naddr, &r->src.addr.v.a.addr,
642 &r->src.addr.v.a.mask, daddr, pd->af);
647 if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
649 if ((r->rpool.opts & PF_POOL_TYPEMASK) == PF_POOL_BITMASK)
650 PF_POOLMASK(naddr, naddr, &r->rpool.cur->addr.v.a.mask,
653 if (r->rpool.proxy_port[1]) {
656 tmp_nport = ((ntohs(dport) - ntohs(r->dst.port[0])) %
657 (r->rpool.proxy_port[1] - r->rpool.proxy_port[0] +
658 1)) + r->rpool.proxy_port[0];
660 /* Wrap around if necessary. */
661 if (tmp_nport > 65535)
663 *nport = htons((uint16_t)tmp_nport);
664 } else if (r->rpool.proxy_port[0])
665 *nport = htons(r->rpool.proxy_port[0]);
669 panic("%s: unknown action %u", __func__, r->action);
672 /* Return success only if translation really happened. */
673 if (bcmp(*skp, *nkp, sizeof(struct pf_state_key_cmp)))
677 uma_zfree(V_pf_state_key_z, *nkp);
678 uma_zfree(V_pf_state_key_z, *skp);