xref: /freebsd-12.1/sys/netpfil/pf/pf_lb.c (revision 2ea0396c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002 - 2008 Henning Brauer
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
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.
18  *
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.
31  *
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.
35  *
36  *	$OpenBSD: pf_lb.c,v 1.2 2009/02/12 02:13:15 sthen Exp $
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_pf.h"
43 #include "opt_inet.h"
44 #include "opt_inet6.h"
45 
46 #include <sys/param.h>
47 #include <sys/lock.h>
48 #include <sys/mbuf.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 
52 #include <net/if.h>
53 #include <net/vnet.h>
54 #include <net/pfvar.h>
55 #include <net/if_pflog.h>
56 
57 #define DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
58 
59 static void		 pf_hash(struct pf_addr *, struct pf_addr *,
60 			    struct pf_poolhashkey *, sa_family_t);
61 static struct pf_rule	*pf_match_translation(struct pf_pdesc *, struct mbuf *,
62 			    int, int, struct pfi_kif *,
63 			    struct pf_addr *, u_int16_t, struct pf_addr *,
64 			    uint16_t, int, struct pf_anchor_stackframe *);
65 static int pf_get_sport(sa_family_t, uint8_t, struct pf_rule *,
66     struct pf_addr *, uint16_t, struct pf_addr *, uint16_t, struct pf_addr *,
67     uint16_t *, uint16_t, uint16_t, struct pf_src_node **);
68 
69 #define mix(a,b,c) \
70 	do {					\
71 		a -= b; a -= c; a ^= (c >> 13);	\
72 		b -= c; b -= a; b ^= (a << 8);	\
73 		c -= a; c -= b; c ^= (b >> 13);	\
74 		a -= b; a -= c; a ^= (c >> 12);	\
75 		b -= c; b -= a; b ^= (a << 16);	\
76 		c -= a; c -= b; c ^= (b >> 5);	\
77 		a -= b; a -= c; a ^= (c >> 3);	\
78 		b -= c; b -= a; b ^= (a << 10);	\
79 		c -= a; c -= b; c ^= (b >> 15);	\
80 	} while (0)
81 
82 /*
83  * hash function based on bridge_hash in if_bridge.c
84  */
85 static void
pf_hash(struct pf_addr * inaddr,struct pf_addr * hash,struct pf_poolhashkey * key,sa_family_t af)86 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
87     struct pf_poolhashkey *key, sa_family_t af)
88 {
89 	u_int32_t	a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
90 
91 	switch (af) {
92 #ifdef INET
93 	case AF_INET:
94 		a += inaddr->addr32[0];
95 		b += key->key32[1];
96 		mix(a, b, c);
97 		hash->addr32[0] = c + key->key32[2];
98 		break;
99 #endif /* INET */
100 #ifdef INET6
101 	case AF_INET6:
102 		a += inaddr->addr32[0];
103 		b += inaddr->addr32[2];
104 		mix(a, b, c);
105 		hash->addr32[0] = c;
106 		a += inaddr->addr32[1];
107 		b += inaddr->addr32[3];
108 		c += key->key32[1];
109 		mix(a, b, c);
110 		hash->addr32[1] = c;
111 		a += inaddr->addr32[2];
112 		b += inaddr->addr32[1];
113 		c += key->key32[2];
114 		mix(a, b, c);
115 		hash->addr32[2] = c;
116 		a += inaddr->addr32[3];
117 		b += inaddr->addr32[0];
118 		c += key->key32[3];
119 		mix(a, b, c);
120 		hash->addr32[3] = c;
121 		break;
122 #endif /* INET6 */
123 	}
124 }
125 
126 static struct pf_rule *
pf_match_translation(struct pf_pdesc * pd,struct mbuf * m,int off,int direction,struct pfi_kif * kif,struct pf_addr * saddr,u_int16_t sport,struct pf_addr * daddr,uint16_t dport,int rs_num,struct pf_anchor_stackframe * anchor_stack)127 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
128     int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
129     struct pf_addr *daddr, uint16_t dport, int rs_num,
130     struct pf_anchor_stackframe *anchor_stack)
131 {
132 	struct pf_rule		*r, *rm = NULL;
133 	struct pf_ruleset	*ruleset = NULL;
134 	int			 tag = -1;
135 	int			 rtableid = -1;
136 	int			 asd = 0;
137 
138 	r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
139 	while (r && rm == NULL) {
140 		struct pf_rule_addr	*src = NULL, *dst = NULL;
141 		struct pf_addr_wrap	*xdst = NULL;
142 
143 		if (r->action == PF_BINAT && direction == PF_IN) {
144 			src = &r->dst;
145 			if (r->rpool.cur != NULL)
146 				xdst = &r->rpool.cur->addr;
147 		} else {
148 			src = &r->src;
149 			dst = &r->dst;
150 		}
151 
152 		r->evaluations++;
153 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
154 			r = r->skip[PF_SKIP_IFP].ptr;
155 		else if (r->direction && r->direction != direction)
156 			r = r->skip[PF_SKIP_DIR].ptr;
157 		else if (r->af && r->af != pd->af)
158 			r = r->skip[PF_SKIP_AF].ptr;
159 		else if (r->proto && r->proto != pd->proto)
160 			r = r->skip[PF_SKIP_PROTO].ptr;
161 		else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
162 		    src->neg, kif, M_GETFIB(m)))
163 			r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
164 			    PF_SKIP_DST_ADDR].ptr;
165 		else if (src->port_op && !pf_match_port(src->port_op,
166 		    src->port[0], src->port[1], sport))
167 			r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
168 			    PF_SKIP_DST_PORT].ptr;
169 		else if (dst != NULL &&
170 		    PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL,
171 		    M_GETFIB(m)))
172 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
173 		else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
174 		    0, NULL, M_GETFIB(m)))
175 			r = TAILQ_NEXT(r, entries);
176 		else if (dst != NULL && dst->port_op &&
177 		    !pf_match_port(dst->port_op, dst->port[0],
178 		    dst->port[1], dport))
179 			r = r->skip[PF_SKIP_DST_PORT].ptr;
180 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
181 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
182 			r = TAILQ_NEXT(r, entries);
183 		else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
184 		    IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
185 		    off, pd->hdr.tcp), r->os_fingerprint)))
186 			r = TAILQ_NEXT(r, entries);
187 		else {
188 			if (r->tag)
189 				tag = r->tag;
190 			if (r->rtableid >= 0)
191 				rtableid = r->rtableid;
192 			if (r->anchor == NULL) {
193 				rm = r;
194 			} else
195 				pf_step_into_anchor(anchor_stack, &asd,
196 				    &ruleset, rs_num, &r, NULL, NULL);
197 		}
198 		if (r == NULL)
199 			pf_step_out_of_anchor(anchor_stack, &asd, &ruleset,
200 			    rs_num, &r, NULL, NULL);
201 	}
202 
203 	if (tag > 0 && pf_tag_packet(m, pd, tag))
204 		return (NULL);
205 	if (rtableid >= 0)
206 		M_SETFIB(m, rtableid);
207 
208 	if (rm != NULL && (rm->action == PF_NONAT ||
209 	    rm->action == PF_NORDR || rm->action == PF_NOBINAT))
210 		return (NULL);
211 	return (rm);
212 }
213 
214 static int
pf_get_sport(sa_family_t af,u_int8_t proto,struct pf_rule * r,struct pf_addr * saddr,uint16_t sport,struct pf_addr * daddr,uint16_t dport,struct pf_addr * naddr,uint16_t * nport,uint16_t low,uint16_t high,struct pf_src_node ** sn)215 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
216     struct pf_addr *saddr, uint16_t sport, struct pf_addr *daddr,
217     uint16_t dport, struct pf_addr *naddr, uint16_t *nport, uint16_t low,
218     uint16_t high, struct pf_src_node **sn)
219 {
220 	struct pf_state_key_cmp	key;
221 	struct pf_addr		init_addr;
222 
223 	bzero(&init_addr, sizeof(init_addr));
224 	if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
225 		return (1);
226 
227 	if (proto == IPPROTO_ICMP) {
228 		low = 1;
229 		high = 65535;
230 	}
231 
232 	bzero(&key, sizeof(key));
233 	key.af = af;
234 	key.proto = proto;
235 	key.port[0] = dport;
236 	PF_ACPY(&key.addr[0], daddr, key.af);
237 
238 	do {
239 		PF_ACPY(&key.addr[1], naddr, key.af);
240 
241 		/*
242 		 * port search; start random, step;
243 		 * similar 2 portloop in in_pcbbind
244 		 */
245 		if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
246 		    proto == IPPROTO_ICMP) || (low == 0 && high == 0)) {
247 			/*
248 			 * XXX bug: icmp states don't use the id on both sides.
249 			 * (traceroute -I through nat)
250 			 */
251 			key.port[1] = sport;
252 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
253 				*nport = sport;
254 				return (0);
255 			}
256 		} else if (low == high) {
257 			key.port[1] = htons(low);
258 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
259 				*nport = htons(low);
260 				return (0);
261 			}
262 		} else {
263 			uint32_t tmp;
264 			uint16_t cut;
265 
266 			if (low > high) {
267 				tmp = low;
268 				low = high;
269 				high = tmp;
270 			}
271 			/* low < high */
272 			cut = arc4random() % (1 + high - low) + low;
273 			/* low <= cut <= high */
274 			for (tmp = cut; tmp <= high && tmp <= 0xffff; ++tmp) {
275 				key.port[1] = htons(tmp);
276 				if (pf_find_state_all(&key, PF_IN, NULL) ==
277 				    NULL) {
278 					*nport = htons(tmp);
279 					return (0);
280 				}
281 			}
282 			tmp = cut;
283 			for (tmp -= 1; tmp >= low && tmp <= 0xffff; --tmp) {
284 				key.port[1] = htons(tmp);
285 				if (pf_find_state_all(&key, PF_IN, NULL) ==
286 				    NULL) {
287 					*nport = htons(tmp);
288 					return (0);
289 				}
290 			}
291 		}
292 
293 		switch (r->rpool.opts & PF_POOL_TYPEMASK) {
294 		case PF_POOL_RANDOM:
295 		case PF_POOL_ROUNDROBIN:
296 			if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
297 				return (1);
298 			break;
299 		case PF_POOL_NONE:
300 		case PF_POOL_SRCHASH:
301 		case PF_POOL_BITMASK:
302 		default:
303 			return (1);
304 		}
305 	} while (! PF_AEQ(&init_addr, naddr, af) );
306 	return (1);					/* none available */
307 }
308 
309 int
pf_map_addr(sa_family_t af,struct pf_rule * r,struct pf_addr * saddr,struct pf_addr * naddr,struct pf_addr * init_addr,struct pf_src_node ** sn)310 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
311     struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
312 {
313 	struct pf_pool		*rpool = &r->rpool;
314 	struct pf_addr		*raddr = NULL, *rmask = NULL;
315 
316 	/* Try to find a src_node if none was given and this
317 	   is a sticky-address rule. */
318 	if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
319 	    (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE)
320 		*sn = pf_find_src_node(saddr, r, af, 0);
321 
322 	/* If a src_node was found or explicitly given and it has a non-zero
323 	   route address, use this address. A zeroed address is found if the
324 	   src node was created just a moment ago in pf_create_state and it
325 	   needs to be filled in with routing decision calculated here. */
326 	if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
327 		/* If the supplied address is the same as the current one we've
328 		 * been asked before, so tell the caller that there's no other
329 		 * address to be had. */
330 		if (PF_AEQ(naddr, &(*sn)->raddr, af))
331 			return (1);
332 
333 		PF_ACPY(naddr, &(*sn)->raddr, af);
334 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
335 			printf("pf_map_addr: src tracking maps ");
336 			pf_print_host(saddr, 0, af);
337 			printf(" to ");
338 			pf_print_host(naddr, 0, af);
339 			printf("\n");
340 		}
341 		return (0);
342 	}
343 
344 	/* Find the route using chosen algorithm. Store the found route
345 	   in src_node if it was given or found. */
346 	if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
347 		return (1);
348 	if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
349 		switch (af) {
350 #ifdef INET
351 		case AF_INET:
352 			if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
353 			    (rpool->opts & PF_POOL_TYPEMASK) !=
354 			    PF_POOL_ROUNDROBIN)
355 				return (1);
356 			 raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
357 			 rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
358 			break;
359 #endif /* INET */
360 #ifdef INET6
361 		case AF_INET6:
362 			if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
363 			    (rpool->opts & PF_POOL_TYPEMASK) !=
364 			    PF_POOL_ROUNDROBIN)
365 				return (1);
366 			raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
367 			rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
368 			break;
369 #endif /* INET6 */
370 		}
371 	} else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
372 		if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
373 			return (1); /* unsupported */
374 	} else {
375 		raddr = &rpool->cur->addr.v.a.addr;
376 		rmask = &rpool->cur->addr.v.a.mask;
377 	}
378 
379 	switch (rpool->opts & PF_POOL_TYPEMASK) {
380 	case PF_POOL_NONE:
381 		PF_ACPY(naddr, raddr, af);
382 		break;
383 	case PF_POOL_BITMASK:
384 		PF_POOLMASK(naddr, raddr, rmask, saddr, af);
385 		break;
386 	case PF_POOL_RANDOM:
387 		if (init_addr != NULL && PF_AZERO(init_addr, af)) {
388 			switch (af) {
389 #ifdef INET
390 			case AF_INET:
391 				rpool->counter.addr32[0] = htonl(arc4random());
392 				break;
393 #endif /* INET */
394 #ifdef INET6
395 			case AF_INET6:
396 				if (rmask->addr32[3] != 0xffffffff)
397 					rpool->counter.addr32[3] =
398 					    htonl(arc4random());
399 				else
400 					break;
401 				if (rmask->addr32[2] != 0xffffffff)
402 					rpool->counter.addr32[2] =
403 					    htonl(arc4random());
404 				else
405 					break;
406 				if (rmask->addr32[1] != 0xffffffff)
407 					rpool->counter.addr32[1] =
408 					    htonl(arc4random());
409 				else
410 					break;
411 				if (rmask->addr32[0] != 0xffffffff)
412 					rpool->counter.addr32[0] =
413 					    htonl(arc4random());
414 				break;
415 #endif /* INET6 */
416 			}
417 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
418 			PF_ACPY(init_addr, naddr, af);
419 
420 		} else {
421 			PF_AINC(&rpool->counter, af);
422 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
423 		}
424 		break;
425 	case PF_POOL_SRCHASH:
426 	    {
427 		unsigned char hash[16];
428 
429 		pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
430 		PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
431 		break;
432 	    }
433 	case PF_POOL_ROUNDROBIN:
434 	    {
435 		struct pf_pooladdr *acur = rpool->cur;
436 
437 		/*
438 		 * XXXGL: in the round-robin case we need to store
439 		 * the round-robin machine state in the rule, thus
440 		 * forwarding thread needs to modify rule.
441 		 *
442 		 * This is done w/o locking, because performance is assumed
443 		 * more important than round-robin precision.
444 		 *
445 		 * In the simpliest case we just update the "rpool->cur"
446 		 * pointer. However, if pool contains tables or dynamic
447 		 * addresses, then "tblidx" is also used to store machine
448 		 * state. Since "tblidx" is int, concurrent access to it can't
449 		 * lead to inconsistence, only to lost of precision.
450 		 *
451 		 * Things get worse, if table contains not hosts, but
452 		 * prefixes. In this case counter also stores machine state,
453 		 * and for IPv6 address, counter can't be updated atomically.
454 		 * Probably, using round-robin on a table containing IPv6
455 		 * prefixes (or even IPv4) would cause a panic.
456 		 */
457 
458 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
459 			if (!pfr_pool_get(rpool->cur->addr.p.tbl,
460 			    &rpool->tblidx, &rpool->counter, af))
461 				goto get_addr;
462 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
463 			if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
464 			    &rpool->tblidx, &rpool->counter, af))
465 				goto get_addr;
466 		} else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
467 			goto get_addr;
468 
469 	try_next:
470 		if (TAILQ_NEXT(rpool->cur, entries) == NULL)
471 			rpool->cur = TAILQ_FIRST(&rpool->list);
472 		else
473 			rpool->cur = TAILQ_NEXT(rpool->cur, entries);
474 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
475 			rpool->tblidx = -1;
476 			if (pfr_pool_get(rpool->cur->addr.p.tbl,
477 			    &rpool->tblidx, &rpool->counter, af)) {
478 				/* table contains no address of type 'af' */
479 				if (rpool->cur != acur)
480 					goto try_next;
481 				return (1);
482 			}
483 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
484 			rpool->tblidx = -1;
485 			if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
486 			    &rpool->tblidx, &rpool->counter, af)) {
487 				/* table contains no address of type 'af' */
488 				if (rpool->cur != acur)
489 					goto try_next;
490 				return (1);
491 			}
492 		} else {
493 			raddr = &rpool->cur->addr.v.a.addr;
494 			rmask = &rpool->cur->addr.v.a.mask;
495 			PF_ACPY(&rpool->counter, raddr, af);
496 		}
497 
498 	get_addr:
499 		PF_ACPY(naddr, &rpool->counter, af);
500 		if (init_addr != NULL && PF_AZERO(init_addr, af))
501 			PF_ACPY(init_addr, naddr, af);
502 		PF_AINC(&rpool->counter, af);
503 		break;
504 	    }
505 	}
506 	if (*sn != NULL)
507 		PF_ACPY(&(*sn)->raddr, naddr, af);
508 
509 	if (V_pf_status.debug >= PF_DEBUG_MISC &&
510 	    (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
511 		printf("pf_map_addr: selected address ");
512 		pf_print_host(naddr, 0, af);
513 		printf("\n");
514 	}
515 
516 	return (0);
517 }
518 
519 struct pf_rule *
pf_get_translation(struct pf_pdesc * pd,struct mbuf * m,int off,int direction,struct pfi_kif * kif,struct pf_src_node ** sn,struct pf_state_key ** skp,struct pf_state_key ** nkp,struct pf_addr * saddr,struct pf_addr * daddr,uint16_t sport,uint16_t dport,struct pf_anchor_stackframe * anchor_stack)520 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
521     struct pfi_kif *kif, struct pf_src_node **sn,
522     struct pf_state_key **skp, struct pf_state_key **nkp,
523     struct pf_addr *saddr, struct pf_addr *daddr,
524     uint16_t sport, uint16_t dport, struct pf_anchor_stackframe *anchor_stack)
525 {
526 	struct pf_rule	*r = NULL;
527 	struct pf_addr	*naddr;
528 	uint16_t	*nport;
529 
530 	PF_RULES_RASSERT();
531 	KASSERT(*skp == NULL, ("*skp not NULL"));
532 	KASSERT(*nkp == NULL, ("*nkp not NULL"));
533 
534 	if (direction == PF_OUT) {
535 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
536 		    sport, daddr, dport, PF_RULESET_BINAT, anchor_stack);
537 		if (r == NULL)
538 			r = pf_match_translation(pd, m, off, direction, kif,
539 			    saddr, sport, daddr, dport, PF_RULESET_NAT,
540 			    anchor_stack);
541 	} else {
542 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
543 		    sport, daddr, dport, PF_RULESET_RDR, anchor_stack);
544 		if (r == NULL)
545 			r = pf_match_translation(pd, m, off, direction, kif,
546 			    saddr, sport, daddr, dport, PF_RULESET_BINAT,
547 			    anchor_stack);
548 	}
549 
550 	if (r == NULL)
551 		return (NULL);
552 
553 	switch (r->action) {
554 	case PF_NONAT:
555 	case PF_NOBINAT:
556 	case PF_NORDR:
557 		return (NULL);
558 	}
559 
560 	*skp = pf_state_key_setup(pd, saddr, daddr, sport, dport);
561 	if (*skp == NULL)
562 		return (NULL);
563 	*nkp = pf_state_key_clone(*skp);
564 	if (*nkp == NULL) {
565 		uma_zfree(V_pf_state_key_z, *skp);
566 		*skp = NULL;
567 		return (NULL);
568 	}
569 
570 	/* XXX We only modify one side for now. */
571 	naddr = &(*nkp)->addr[1];
572 	nport = &(*nkp)->port[1];
573 
574 	switch (r->action) {
575 	case PF_NAT:
576 		if (pf_get_sport(pd->af, pd->proto, r, saddr, sport, daddr,
577 		    dport, naddr, nport, r->rpool.proxy_port[0],
578 		    r->rpool.proxy_port[1], sn)) {
579 			DPFPRINTF(PF_DEBUG_MISC,
580 			    ("pf: NAT proxy port allocation (%u-%u) failed\n",
581 			    r->rpool.proxy_port[0], r->rpool.proxy_port[1]));
582 			goto notrans;
583 		}
584 		break;
585 	case PF_BINAT:
586 		switch (direction) {
587 		case PF_OUT:
588 			if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
589 				switch (pd->af) {
590 #ifdef INET
591 				case AF_INET:
592 					if (r->rpool.cur->addr.p.dyn->
593 					    pfid_acnt4 < 1)
594 						goto notrans;
595 					PF_POOLMASK(naddr,
596 					    &r->rpool.cur->addr.p.dyn->
597 					    pfid_addr4,
598 					    &r->rpool.cur->addr.p.dyn->
599 					    pfid_mask4, saddr, AF_INET);
600 					break;
601 #endif /* INET */
602 #ifdef INET6
603 				case AF_INET6:
604 					if (r->rpool.cur->addr.p.dyn->
605 					    pfid_acnt6 < 1)
606 						goto notrans;
607 					PF_POOLMASK(naddr,
608 					    &r->rpool.cur->addr.p.dyn->
609 					    pfid_addr6,
610 					    &r->rpool.cur->addr.p.dyn->
611 					    pfid_mask6, saddr, AF_INET6);
612 					break;
613 #endif /* INET6 */
614 				}
615 			} else
616 				PF_POOLMASK(naddr,
617 				    &r->rpool.cur->addr.v.a.addr,
618 				    &r->rpool.cur->addr.v.a.mask, saddr,
619 				    pd->af);
620 			break;
621 		case PF_IN:
622 			if (r->src.addr.type == PF_ADDR_DYNIFTL) {
623 				switch (pd->af) {
624 #ifdef INET
625 				case AF_INET:
626 					if (r->src.addr.p.dyn-> pfid_acnt4 < 1)
627 						goto notrans;
628 					PF_POOLMASK(naddr,
629 					    &r->src.addr.p.dyn->pfid_addr4,
630 					    &r->src.addr.p.dyn->pfid_mask4,
631 					    daddr, AF_INET);
632 					break;
633 #endif /* INET */
634 #ifdef INET6
635 				case AF_INET6:
636 					if (r->src.addr.p.dyn->pfid_acnt6 < 1)
637 						goto notrans;
638 					PF_POOLMASK(naddr,
639 					    &r->src.addr.p.dyn->pfid_addr6,
640 					    &r->src.addr.p.dyn->pfid_mask6,
641 					    daddr, AF_INET6);
642 					break;
643 #endif /* INET6 */
644 				}
645 			} else
646 				PF_POOLMASK(naddr, &r->src.addr.v.a.addr,
647 				    &r->src.addr.v.a.mask, daddr, pd->af);
648 			break;
649 		}
650 		break;
651 	case PF_RDR: {
652 		if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
653 			goto notrans;
654 		if ((r->rpool.opts & PF_POOL_TYPEMASK) == PF_POOL_BITMASK)
655 			PF_POOLMASK(naddr, naddr, &r->rpool.cur->addr.v.a.mask,
656 			    daddr, pd->af);
657 
658 		if (r->rpool.proxy_port[1]) {
659 			uint32_t	tmp_nport;
660 
661 			tmp_nport = ((ntohs(dport) - ntohs(r->dst.port[0])) %
662 			    (r->rpool.proxy_port[1] - r->rpool.proxy_port[0] +
663 			    1)) + r->rpool.proxy_port[0];
664 
665 			/* Wrap around if necessary. */
666 			if (tmp_nport > 65535)
667 				tmp_nport -= 65535;
668 			*nport = htons((uint16_t)tmp_nport);
669 		} else if (r->rpool.proxy_port[0])
670 			*nport = htons(r->rpool.proxy_port[0]);
671 		break;
672 	}
673 	default:
674 		panic("%s: unknown action %u", __func__, r->action);
675 	}
676 
677 	/* Return success only if translation really happened. */
678 	if (bcmp(*skp, *nkp, sizeof(struct pf_state_key_cmp)))
679 		return (r);
680 
681 notrans:
682 	uma_zfree(V_pf_state_key_z, *nkp);
683 	uma_zfree(V_pf_state_key_z, *skp);
684 	*skp = *nkp = NULL;
685 	*sn = NULL;
686 
687 	return (NULL);
688 }
689