xref: /freebsd/sys/netpfil/pf/pf_lb.c (revision d411c1d6)
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_krule	*pf_match_translation(struct pf_pdesc *, struct mbuf *,
62 			    int, int, struct pfi_kkif *,
63 			    struct pf_addr *, u_int16_t, struct pf_addr *,
64 			    uint16_t, int, struct pf_kanchor_stackframe *);
65 static int pf_get_sport(sa_family_t, uint8_t, struct pf_krule *,
66     struct pf_addr *, uint16_t, struct pf_addr *, uint16_t, struct pf_addr *,
67     uint16_t *, uint16_t, uint16_t, struct pf_ksrc_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
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_krule *
127 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
128     int direction, struct pfi_kkif *kif, struct pf_addr *saddr, u_int16_t sport,
129     struct pf_addr *daddr, uint16_t dport, int rs_num,
130     struct pf_kanchor_stackframe *anchor_stack)
131 {
132 	struct pf_krule		*r, *rm = NULL;
133 	struct pf_kruleset	*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 != 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 		pf_counter_u64_add(&r->evaluations, 1);
153 		if (pfi_kkif_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 				if (rm->action == PF_NONAT ||
195 				    rm->action == PF_NORDR ||
196 				    rm->action == PF_NOBINAT) {
197 					rm = NULL;
198 				}
199 				break;
200 			} else
201 				pf_step_into_anchor(anchor_stack, &asd,
202 				    &ruleset, rs_num, &r, NULL, NULL);
203 		}
204 		if (r == NULL)
205 			pf_step_out_of_anchor(anchor_stack, &asd, &ruleset,
206 			    rs_num, &r, NULL, NULL);
207 	}
208 
209 	if (tag > 0 && pf_tag_packet(m, pd, tag))
210 		return (NULL);
211 	if (rtableid >= 0)
212 		M_SETFIB(m, rtableid);
213 
214 	return (rm);
215 }
216 
217 static int
218 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_krule *r,
219     struct pf_addr *saddr, uint16_t sport, struct pf_addr *daddr,
220     uint16_t dport, struct pf_addr *naddr, uint16_t *nport, uint16_t low,
221     uint16_t high, struct pf_ksrc_node **sn)
222 {
223 	struct pf_state_key_cmp	key;
224 	struct pf_addr		init_addr;
225 
226 	bzero(&init_addr, sizeof(init_addr));
227 	if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
228 		return (1);
229 
230 	bzero(&key, sizeof(key));
231 	key.af = af;
232 	key.proto = proto;
233 	key.port[0] = dport;
234 	PF_ACPY(&key.addr[0], daddr, key.af);
235 
236 	do {
237 		PF_ACPY(&key.addr[1], naddr, key.af);
238 
239 		/*
240 		 * port search; start random, step;
241 		 * similar 2 portloop in in_pcbbind
242 		 */
243 		if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
244 		    proto == IPPROTO_ICMP) || (low == 0 && high == 0)) {
245 			/*
246 			 * XXX bug: icmp states don't use the id on both sides.
247 			 * (traceroute -I through nat)
248 			 */
249 			key.port[1] = sport;
250 			if (!pf_find_state_all_exists(&key, PF_IN)) {
251 				*nport = sport;
252 				return (0);
253 			}
254 		} else if (low == high) {
255 			key.port[1] = htons(low);
256 			if (!pf_find_state_all_exists(&key, PF_IN)) {
257 				*nport = htons(low);
258 				return (0);
259 			}
260 		} else {
261 			uint32_t tmp;
262 			uint16_t cut;
263 
264 			if (low > high) {
265 				tmp = low;
266 				low = high;
267 				high = tmp;
268 			}
269 			/* low < high */
270 			cut = arc4random() % (1 + high - low) + low;
271 			/* low <= cut <= high */
272 			for (tmp = cut; tmp <= high && tmp <= 0xffff; ++tmp) {
273 				key.port[1] = htons(tmp);
274 				if (!pf_find_state_all_exists(&key, PF_IN)) {
275 					*nport = htons(tmp);
276 					return (0);
277 				}
278 			}
279 			tmp = cut;
280 			for (tmp -= 1; tmp >= low && tmp <= 0xffff; --tmp) {
281 				key.port[1] = htons(tmp);
282 				if (!pf_find_state_all_exists(&key, PF_IN)) {
283 					*nport = htons(tmp);
284 					return (0);
285 				}
286 			}
287 		}
288 
289 		switch (r->rpool.opts & PF_POOL_TYPEMASK) {
290 		case PF_POOL_RANDOM:
291 		case PF_POOL_ROUNDROBIN:
292 			/*
293 			 * pick a different source address since we're out
294 			 * of free port choices for the current one.
295 			 */
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 static int
310 pf_get_mape_sport(sa_family_t af, u_int8_t proto, struct pf_krule *r,
311     struct pf_addr *saddr, uint16_t sport, struct pf_addr *daddr,
312     uint16_t dport, struct pf_addr *naddr, uint16_t *nport,
313     struct pf_ksrc_node **sn)
314 {
315 	uint16_t psmask, low, highmask;
316 	uint16_t i, ahigh, cut;
317 	int ashift, psidshift;
318 
319 	ashift = 16 - r->rpool.mape.offset;
320 	psidshift = ashift - r->rpool.mape.psidlen;
321 	psmask = r->rpool.mape.psid & ((1U << r->rpool.mape.psidlen) - 1);
322 	psmask = psmask << psidshift;
323 	highmask = (1U << psidshift) - 1;
324 
325 	ahigh = (1U << r->rpool.mape.offset) - 1;
326 	cut = arc4random() & ahigh;
327 	if (cut == 0)
328 		cut = 1;
329 
330 	for (i = cut; i <= ahigh; i++) {
331 		low = (i << ashift) | psmask;
332 		if (!pf_get_sport(af, proto, r, saddr, sport, daddr, dport,
333 		    naddr, nport, low, low | highmask, sn))
334 			return (0);
335 	}
336 	for (i = cut - 1; i > 0; i--) {
337 		low = (i << ashift) | psmask;
338 		if (!pf_get_sport(af, proto, r, saddr, sport, daddr, dport,
339 		    naddr, nport, low, low | highmask, sn))
340 			return (0);
341 	}
342 	return (1);
343 }
344 
345 u_short
346 pf_map_addr(sa_family_t af, struct pf_krule *r, struct pf_addr *saddr,
347     struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_ksrc_node **sn)
348 {
349 	u_short			 reason = 0;
350 	struct pf_kpool		*rpool = &r->rpool;
351 	struct pf_addr		*raddr = NULL, *rmask = NULL;
352 	struct pf_srchash	*sh = NULL;
353 
354 	/* Try to find a src_node if none was given and this
355 	   is a sticky-address rule. */
356 	if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
357 	    (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE)
358 		*sn = pf_find_src_node(saddr, r, af, &sh, false);
359 
360 	/* If a src_node was found or explicitly given and it has a non-zero
361 	   route address, use this address. A zeroed address is found if the
362 	   src node was created just a moment ago in pf_create_state and it
363 	   needs to be filled in with routing decision calculated here. */
364 	if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
365 		/* If the supplied address is the same as the current one we've
366 		 * been asked before, so tell the caller that there's no other
367 		 * address to be had. */
368 		if (PF_AEQ(naddr, &(*sn)->raddr, af)) {
369 			reason = PFRES_MAPFAILED;
370 			goto done;
371 		}
372 
373 		PF_ACPY(naddr, &(*sn)->raddr, af);
374 		if (V_pf_status.debug >= PF_DEBUG_NOISY) {
375 			printf("pf_map_addr: src tracking maps ");
376 			pf_print_host(saddr, 0, af);
377 			printf(" to ");
378 			pf_print_host(naddr, 0, af);
379 			printf("\n");
380 		}
381 		goto done;
382 	}
383 
384 	mtx_lock(&rpool->mtx);
385 	/* Find the route using chosen algorithm. Store the found route
386 	   in src_node if it was given or found. */
387 	if (rpool->cur->addr.type == PF_ADDR_NOROUTE) {
388 		reason = PFRES_MAPFAILED;
389 		goto done_pool_mtx;
390 	}
391 	if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
392 		switch (af) {
393 #ifdef INET
394 		case AF_INET:
395 			if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
396 			    (rpool->opts & PF_POOL_TYPEMASK) !=
397 			    PF_POOL_ROUNDROBIN) {
398 				reason = PFRES_MAPFAILED;
399 				goto done_pool_mtx;
400 			}
401 			raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
402 			rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
403 			break;
404 #endif /* INET */
405 #ifdef INET6
406 		case AF_INET6:
407 			if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
408 			    (rpool->opts & PF_POOL_TYPEMASK) !=
409 			    PF_POOL_ROUNDROBIN) {
410 				reason = PFRES_MAPFAILED;
411 				goto done_pool_mtx;
412 			}
413 			raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
414 			rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
415 			break;
416 #endif /* INET6 */
417 		}
418 	} else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
419 		if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN) {
420 			reason = PFRES_MAPFAILED;
421 			goto done_pool_mtx; /* unsupported */
422 		}
423 	} else {
424 		raddr = &rpool->cur->addr.v.a.addr;
425 		rmask = &rpool->cur->addr.v.a.mask;
426 	}
427 
428 	switch (rpool->opts & PF_POOL_TYPEMASK) {
429 	case PF_POOL_NONE:
430 		PF_ACPY(naddr, raddr, af);
431 		break;
432 	case PF_POOL_BITMASK:
433 		PF_POOLMASK(naddr, raddr, rmask, saddr, af);
434 		break;
435 	case PF_POOL_RANDOM:
436 		if (init_addr != NULL && PF_AZERO(init_addr, af)) {
437 			switch (af) {
438 #ifdef INET
439 			case AF_INET:
440 				rpool->counter.addr32[0] = htonl(arc4random());
441 				break;
442 #endif /* INET */
443 #ifdef INET6
444 			case AF_INET6:
445 				if (rmask->addr32[3] != 0xffffffff)
446 					rpool->counter.addr32[3] =
447 					    htonl(arc4random());
448 				else
449 					break;
450 				if (rmask->addr32[2] != 0xffffffff)
451 					rpool->counter.addr32[2] =
452 					    htonl(arc4random());
453 				else
454 					break;
455 				if (rmask->addr32[1] != 0xffffffff)
456 					rpool->counter.addr32[1] =
457 					    htonl(arc4random());
458 				else
459 					break;
460 				if (rmask->addr32[0] != 0xffffffff)
461 					rpool->counter.addr32[0] =
462 					    htonl(arc4random());
463 				break;
464 #endif /* INET6 */
465 			}
466 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
467 			PF_ACPY(init_addr, naddr, af);
468 
469 		} else {
470 			PF_AINC(&rpool->counter, af);
471 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
472 		}
473 		break;
474 	case PF_POOL_SRCHASH:
475 	    {
476 		unsigned char hash[16];
477 
478 		pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
479 		PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
480 		break;
481 	    }
482 	case PF_POOL_ROUNDROBIN:
483 	    {
484 		struct pf_kpooladdr *acur = rpool->cur;
485 
486 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
487 			if (!pfr_pool_get(rpool->cur->addr.p.tbl,
488 			    &rpool->tblidx, &rpool->counter, af))
489 				goto get_addr;
490 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
491 			if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
492 			    &rpool->tblidx, &rpool->counter, af))
493 				goto get_addr;
494 		} else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
495 			goto get_addr;
496 
497 	try_next:
498 		if (TAILQ_NEXT(rpool->cur, entries) == NULL)
499 			rpool->cur = TAILQ_FIRST(&rpool->list);
500 		else
501 			rpool->cur = TAILQ_NEXT(rpool->cur, entries);
502 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
503 			rpool->tblidx = -1;
504 			if (pfr_pool_get(rpool->cur->addr.p.tbl,
505 			    &rpool->tblidx, &rpool->counter, af)) {
506 				/* table contains no address of type 'af' */
507 				if (rpool->cur != acur)
508 					goto try_next;
509 				reason = PFRES_MAPFAILED;
510 				goto done_pool_mtx;
511 			}
512 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
513 			rpool->tblidx = -1;
514 			if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
515 			    &rpool->tblidx, &rpool->counter, af)) {
516 				/* table contains no address of type 'af' */
517 				if (rpool->cur != acur)
518 					goto try_next;
519 				reason = PFRES_MAPFAILED;
520 				goto done_pool_mtx;
521 			}
522 		} else {
523 			raddr = &rpool->cur->addr.v.a.addr;
524 			rmask = &rpool->cur->addr.v.a.mask;
525 			PF_ACPY(&rpool->counter, raddr, af);
526 		}
527 
528 	get_addr:
529 		PF_ACPY(naddr, &rpool->counter, af);
530 		if (init_addr != NULL && PF_AZERO(init_addr, af))
531 			PF_ACPY(init_addr, naddr, af);
532 		PF_AINC(&rpool->counter, af);
533 		break;
534 	    }
535 	}
536 	if (*sn != NULL)
537 		PF_ACPY(&(*sn)->raddr, naddr, af);
538 
539 	if (V_pf_status.debug >= PF_DEBUG_NOISY &&
540 	    (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
541 		printf("pf_map_addr: selected address ");
542 		pf_print_host(naddr, 0, af);
543 		printf("\n");
544 	}
545 
546 done_pool_mtx:
547 	mtx_unlock(&rpool->mtx);
548 
549 done:
550 	if (reason) {
551 		counter_u64_add(V_pf_status.counters[reason], 1);
552 	}
553 
554 	return (reason);
555 }
556 
557 struct pf_krule *
558 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
559     struct pfi_kkif *kif, struct pf_ksrc_node **sn,
560     struct pf_state_key **skp, struct pf_state_key **nkp,
561     struct pf_addr *saddr, struct pf_addr *daddr,
562     uint16_t sport, uint16_t dport, struct pf_kanchor_stackframe *anchor_stack)
563 {
564 	struct pf_krule	*r = NULL;
565 	struct pf_addr	*naddr;
566 	uint16_t	*nport;
567 	uint16_t	 low, high;
568 
569 	PF_RULES_RASSERT();
570 	KASSERT(*skp == NULL, ("*skp not NULL"));
571 	KASSERT(*nkp == NULL, ("*nkp not NULL"));
572 
573 	if (direction == PF_OUT) {
574 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
575 		    sport, daddr, dport, PF_RULESET_BINAT, anchor_stack);
576 		if (r == NULL)
577 			r = pf_match_translation(pd, m, off, direction, kif,
578 			    saddr, sport, daddr, dport, PF_RULESET_NAT,
579 			    anchor_stack);
580 	} else {
581 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
582 		    sport, daddr, dport, PF_RULESET_RDR, anchor_stack);
583 		if (r == NULL)
584 			r = pf_match_translation(pd, m, off, direction, kif,
585 			    saddr, sport, daddr, dport, PF_RULESET_BINAT,
586 			    anchor_stack);
587 	}
588 
589 	if (r == NULL)
590 		return (NULL);
591 
592 	switch (r->action) {
593 	case PF_NONAT:
594 	case PF_NOBINAT:
595 	case PF_NORDR:
596 		return (NULL);
597 	}
598 
599 	*skp = pf_state_key_setup(pd, saddr, daddr, sport, dport);
600 	if (*skp == NULL)
601 		return (NULL);
602 	*nkp = pf_state_key_clone(*skp);
603 	if (*nkp == NULL) {
604 		uma_zfree(V_pf_state_key_z, *skp);
605 		*skp = NULL;
606 		return (NULL);
607 	}
608 
609 	/* XXX We only modify one side for now. */
610 	naddr = &(*nkp)->addr[1];
611 	nport = &(*nkp)->port[1];
612 
613 	switch (r->action) {
614 	case PF_NAT:
615 		if (pd->proto == IPPROTO_ICMP) {
616 			low  = 1;
617 			high = 65535;
618 		} else {
619 			low  = r->rpool.proxy_port[0];
620 			high = r->rpool.proxy_port[1];
621 		}
622 		if (r->rpool.mape.offset > 0) {
623 			if (pf_get_mape_sport(pd->af, pd->proto, r, saddr,
624 			    sport, daddr, dport, naddr, nport, sn)) {
625 				DPFPRINTF(PF_DEBUG_MISC,
626 				    ("pf: MAP-E port allocation (%u/%u/%u)"
627 				    " failed\n",
628 				    r->rpool.mape.offset,
629 				    r->rpool.mape.psidlen,
630 				    r->rpool.mape.psid));
631 				goto notrans;
632 			}
633 		} else if (pf_get_sport(pd->af, pd->proto, r, saddr, sport,
634 		    daddr, dport, naddr, nport, low, high, sn)) {
635 			DPFPRINTF(PF_DEBUG_MISC,
636 			    ("pf: NAT proxy port allocation (%u-%u) failed\n",
637 			    r->rpool.proxy_port[0], r->rpool.proxy_port[1]));
638 			goto notrans;
639 		}
640 		break;
641 	case PF_BINAT:
642 		switch (direction) {
643 		case PF_OUT:
644 			if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
645 				switch (pd->af) {
646 #ifdef INET
647 				case AF_INET:
648 					if (r->rpool.cur->addr.p.dyn->
649 					    pfid_acnt4 < 1)
650 						goto notrans;
651 					PF_POOLMASK(naddr,
652 					    &r->rpool.cur->addr.p.dyn->
653 					    pfid_addr4,
654 					    &r->rpool.cur->addr.p.dyn->
655 					    pfid_mask4, saddr, AF_INET);
656 					break;
657 #endif /* INET */
658 #ifdef INET6
659 				case AF_INET6:
660 					if (r->rpool.cur->addr.p.dyn->
661 					    pfid_acnt6 < 1)
662 						goto notrans;
663 					PF_POOLMASK(naddr,
664 					    &r->rpool.cur->addr.p.dyn->
665 					    pfid_addr6,
666 					    &r->rpool.cur->addr.p.dyn->
667 					    pfid_mask6, saddr, AF_INET6);
668 					break;
669 #endif /* INET6 */
670 				}
671 			} else
672 				PF_POOLMASK(naddr,
673 				    &r->rpool.cur->addr.v.a.addr,
674 				    &r->rpool.cur->addr.v.a.mask, saddr,
675 				    pd->af);
676 			break;
677 		case PF_IN:
678 			if (r->src.addr.type == PF_ADDR_DYNIFTL) {
679 				switch (pd->af) {
680 #ifdef INET
681 				case AF_INET:
682 					if (r->src.addr.p.dyn-> pfid_acnt4 < 1)
683 						goto notrans;
684 					PF_POOLMASK(naddr,
685 					    &r->src.addr.p.dyn->pfid_addr4,
686 					    &r->src.addr.p.dyn->pfid_mask4,
687 					    daddr, AF_INET);
688 					break;
689 #endif /* INET */
690 #ifdef INET6
691 				case AF_INET6:
692 					if (r->src.addr.p.dyn->pfid_acnt6 < 1)
693 						goto notrans;
694 					PF_POOLMASK(naddr,
695 					    &r->src.addr.p.dyn->pfid_addr6,
696 					    &r->src.addr.p.dyn->pfid_mask6,
697 					    daddr, AF_INET6);
698 					break;
699 #endif /* INET6 */
700 				}
701 			} else
702 				PF_POOLMASK(naddr, &r->src.addr.v.a.addr,
703 				    &r->src.addr.v.a.mask, daddr, pd->af);
704 			break;
705 		}
706 		break;
707 	case PF_RDR: {
708 		if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
709 			goto notrans;
710 		if ((r->rpool.opts & PF_POOL_TYPEMASK) == PF_POOL_BITMASK)
711 			PF_POOLMASK(naddr, naddr, &r->rpool.cur->addr.v.a.mask,
712 			    daddr, pd->af);
713 
714 		if (r->rpool.proxy_port[1]) {
715 			uint32_t	tmp_nport;
716 
717 			tmp_nport = ((ntohs(dport) - ntohs(r->dst.port[0])) %
718 			    (r->rpool.proxy_port[1] - r->rpool.proxy_port[0] +
719 			    1)) + r->rpool.proxy_port[0];
720 
721 			/* Wrap around if necessary. */
722 			if (tmp_nport > 65535)
723 				tmp_nport -= 65535;
724 			*nport = htons((uint16_t)tmp_nport);
725 		} else if (r->rpool.proxy_port[0])
726 			*nport = htons(r->rpool.proxy_port[0]);
727 		break;
728 	}
729 	default:
730 		panic("%s: unknown action %u", __func__, r->action);
731 	}
732 
733 	/* Return success only if translation really happened. */
734 	if (bcmp(*skp, *nkp, sizeof(struct pf_state_key_cmp)))
735 		return (r);
736 
737 notrans:
738 	uma_zfree(V_pf_state_key_z, *nkp);
739 	uma_zfree(V_pf_state_key_z, *skp);
740 	*skp = *nkp = NULL;
741 	*sn = NULL;
742 
743 	return (NULL);
744 }
745