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