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