xref: /freebsd/sys/netpfil/pf/pf_lb.c (revision dedb4d3597e548bf72c380c850b061a8f5bec729)
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 <crypto/siphash/siphash.h>
51 
52 #include <net/if.h>
53 #include <net/if_var.h>
54 #include <net/vnet.h>
55 #include <net/pfvar.h>
56 #include <net/if_pflog.h>
57 
58 #ifdef INET
59 #include <netinet/in_var.h>
60 #endif /* INET */
61 
62 #ifdef INET6
63 #include <netinet6/in6_var.h>
64 #endif /* INET6 */
65 
66 
67 /*
68  * Limit the amount of work we do to find a free source port for redirects that
69  * introduce a state conflict.
70  */
71 #define	V_pf_rdr_srcport_rewrite_tries	VNET(pf_rdr_srcport_rewrite_tries)
72 VNET_DEFINE_STATIC(int, pf_rdr_srcport_rewrite_tries) = 16;
73 
74 #define DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
75 
76 static uint64_t		 pf_hash(struct pf_addr *, struct pf_addr *,
77 			    struct pf_poolhashkey *, sa_family_t);
78 struct pf_krule		*pf_match_translation(int, struct pf_test_ctx *);
79 static enum pf_test_status pf_step_into_translation_anchor(int, struct pf_test_ctx *,
80 			    struct pf_krule *);
81 static int		 pf_get_sport(struct pf_pdesc *, struct pf_krule *,
82 			    struct pf_addr *, uint16_t *, uint16_t, uint16_t,
83 			    struct pf_kpool *, struct pf_udp_mapping **,
84 			    pf_sn_types_t);
85 static bool		 pf_islinklocal(const sa_family_t, const struct pf_addr *);
86 
87 static uint64_t
pf_hash(struct pf_addr * inaddr,struct pf_addr * hash,struct pf_poolhashkey * key,sa_family_t af)88 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
89     struct pf_poolhashkey *key, sa_family_t af)
90 {
91 	SIPHASH_CTX	 ctx;
92 #ifdef INET6
93 	union {
94 		uint64_t hash64;
95 		uint32_t hash32[2];
96 	} h;
97 #endif /* INET6 */
98 	uint64_t	 res = 0;
99 
100 	_Static_assert(sizeof(*key) >= SIPHASH_KEY_LENGTH, "");
101 
102 	switch (af) {
103 #ifdef INET
104 	case AF_INET:
105 		res = SipHash24(&ctx, (const uint8_t *)key,
106 		    &inaddr->addr32[0], sizeof(inaddr->addr32[0]));
107 		hash->addr32[0] = res;
108 		break;
109 #endif /* INET */
110 #ifdef INET6
111 	case AF_INET6:
112 		res = SipHash24(&ctx, (const uint8_t *)key,
113 		    &inaddr->addr32[0], 4 * sizeof(inaddr->addr32[0]));
114 		h.hash64 = res;
115 		hash->addr32[0] = h.hash32[0];
116 		hash->addr32[1] = h.hash32[1];
117 		/*
118 		 * siphash isn't big enough, but flipping it around is
119 		 * good enough here.
120 		 */
121 		hash->addr32[2] = ~h.hash32[1];
122 		hash->addr32[3] = ~h.hash32[0];
123 		break;
124 #endif /* INET6 */
125 	default:
126 		unhandled_af(af);
127 	}
128 	return (res);
129 }
130 
131 #define PF_TEST_ATTRIB(t, a)		\
132 	if (t) {			\
133 		r = a;			\
134 		continue;		\
135 	} else do {			\
136 	} while (0)
137 
138 static enum pf_test_status
pf_match_translation_rule(int rs_num,struct pf_test_ctx * ctx,struct pf_kruleset * ruleset)139 pf_match_translation_rule(int rs_num, struct pf_test_ctx *ctx, struct pf_kruleset *ruleset)
140 {
141 	struct pf_krule		*r;
142 	struct pf_pdesc		*pd = ctx->pd;
143 	int			 rtableid = -1;
144 
145 	r = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
146 	while (r != NULL) {
147 		struct pf_rule_addr	*src = NULL, *dst = NULL;
148 		struct pf_addr_wrap	*xdst = NULL;
149 
150 		if (r->action == PF_BINAT && pd->dir == PF_IN) {
151 			src = &r->dst;
152 			if (r->rdr.cur != NULL)
153 				xdst = &r->rdr.cur->addr;
154 		} else {
155 			src = &r->src;
156 			dst = &r->dst;
157 		}
158 
159 		pf_counter_u64_add(&r->evaluations, 1);
160 		PF_TEST_ATTRIB(pfi_kkif_match(r->kif, pd->kif) == r->ifnot,
161 			r->skip[PF_SKIP_IFP]);
162 		PF_TEST_ATTRIB(r->direction && r->direction != pd->dir,
163 			r->skip[PF_SKIP_DIR]);
164 		PF_TEST_ATTRIB(r->af && r->af != pd->af,
165 			r->skip[PF_SKIP_AF]);
166 		PF_TEST_ATTRIB(r->proto && r->proto != pd->proto,
167 			r->skip[PF_SKIP_PROTO]);
168 		PF_TEST_ATTRIB(PF_MISMATCHAW(&src->addr, &pd->nsaddr, pd->af,
169 		    src->neg, pd->kif, M_GETFIB(pd->m)),
170 			r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
171 			    PF_SKIP_DST_ADDR]);
172 		PF_TEST_ATTRIB(src->port_op && !pf_match_port(src->port_op,
173 		    src->port[0], src->port[1], pd->nsport),
174 			r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
175 			    PF_SKIP_DST_PORT]);
176 		PF_TEST_ATTRIB(dst != NULL &&
177 		    PF_MISMATCHAW(&dst->addr, &pd->ndaddr, pd->af, dst->neg, NULL,
178 		    M_GETFIB(pd->m)),
179 			r->skip[PF_SKIP_DST_ADDR]);
180 		PF_TEST_ATTRIB(xdst != NULL && PF_MISMATCHAW(xdst, &pd->ndaddr, pd->af,
181 		    0, NULL, M_GETFIB(pd->m)),
182 			TAILQ_NEXT(r, entries));
183 		PF_TEST_ATTRIB(dst != NULL && dst->port_op &&
184 		    !pf_match_port(dst->port_op, dst->port[0],
185 		    dst->port[1], pd->ndport),
186 			r->skip[PF_SKIP_DST_PORT]);
187 		PF_TEST_ATTRIB(r->match_tag && !pf_match_tag(pd->m, r, &ctx->tag,
188 		    pd->pf_mtag ? pd->pf_mtag->tag : 0),
189 			TAILQ_NEXT(r, entries));
190 		PF_TEST_ATTRIB(r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
191 		    IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd,
192 		    &pd->hdr.tcp), r->os_fingerprint)),
193 			TAILQ_NEXT(r, entries));
194 		if (r->tag)
195 			ctx->tag = r->tag;
196 		if (r->rtableid >= 0)
197 			rtableid = r->rtableid;
198 		if (r->anchor == NULL) {
199 			if (r->action == PF_NONAT ||
200 			    r->action == PF_NORDR ||
201 			    r->action == PF_NOBINAT) {
202 				*ctx->rm = NULL;
203 			} else {
204 				/*
205 				 * found matching r
206 				 */
207 				ctx->tr = r;
208 				/*
209 				 * anchor, with ruleset, where r belongs to
210 				 */
211 				*ctx->am = ctx->a;
212 				/*
213 				 * ruleset where r belongs to
214 				 */
215 				*ctx->rsm = ruleset;
216 				/*
217 				 * ruleset, where anchor belongs to.
218 				 */
219 				ctx->arsm = ctx->aruleset;
220 			}
221 		} else {
222 			ctx->a = r;			/* remember anchor */
223 			ctx->aruleset = ruleset;	/* and its ruleset */
224 			if (pf_step_into_translation_anchor(rs_num, ctx,
225 			    r) != PF_TEST_OK) {
226 				break;
227 			}
228 		}
229 		r = TAILQ_NEXT(r, entries);
230 	}
231 
232 	if (ctx->tag > 0 && pf_tag_packet(pd, ctx->tag))
233 		return (PF_TEST_FAIL);
234 	if (rtableid >= 0)
235 		M_SETFIB(pd->m, rtableid);
236 
237 	return (PF_TEST_OK);
238 }
239 
240 static enum pf_test_status
pf_step_into_translation_anchor(int rs_num,struct pf_test_ctx * ctx,struct pf_krule * r)241 pf_step_into_translation_anchor(int rs_num, struct pf_test_ctx *ctx, struct pf_krule *r)
242 {
243 	enum pf_test_status	rv;
244 
245 	PF_RULES_RASSERT();
246 
247 	if (ctx->depth >= PF_ANCHOR_STACK_MAX) {
248 		printf("%s: anchor stack overflow on %s\n",
249 		    __func__, r->anchor->name);
250 		return (PF_TEST_FAIL);
251 	}
252 
253 	ctx->depth++;
254 
255 	if (r->anchor_wildcard) {
256 		struct pf_kanchor *child;
257 		rv = PF_TEST_OK;
258 		RB_FOREACH(child, pf_kanchor_node, &r->anchor->children) {
259 			rv = pf_match_translation_rule(rs_num, ctx, &child->ruleset);
260 			if ((rv == PF_TEST_QUICK) || (rv == PF_TEST_FAIL)) {
261 				/*
262 				 * we either hit a rule qith quick action
263 				 * (more likely), or hit some runtime
264 				 * error (e.g. pool_get() faillure).
265 				 */
266 				break;
267 			}
268 		}
269 	} else {
270 		rv = pf_match_translation_rule(rs_num, ctx, &r->anchor->ruleset);
271 	}
272 
273 	ctx->depth--;
274 
275 	return (rv);
276 }
277 
278 struct pf_krule *
pf_match_translation(int rs_num,struct pf_test_ctx * ctx)279 pf_match_translation(int rs_num, struct pf_test_ctx *ctx)
280 {
281 	enum pf_test_status rv;
282 
283 	MPASS(ctx->depth == 0);
284 	rv = pf_match_translation_rule(rs_num, ctx, &pf_main_ruleset);
285 	MPASS(ctx->depth == 0);
286 	if (rv != PF_TEST_OK)
287 		return (NULL);
288 
289 	return (ctx->tr);
290 }
291 
292 static int
pf_get_sport(struct pf_pdesc * pd,struct pf_krule * r,struct pf_addr * naddr,uint16_t * nport,uint16_t low,uint16_t high,struct pf_kpool * rpool,struct pf_udp_mapping ** udp_mapping,pf_sn_types_t sn_type)293 pf_get_sport(struct pf_pdesc *pd, struct pf_krule *r, struct pf_addr *naddr,
294     uint16_t *nport, uint16_t low, uint16_t high, struct pf_kpool *rpool,
295     struct pf_udp_mapping **udp_mapping, pf_sn_types_t sn_type)
296 {
297 	struct pf_state_key_cmp	key;
298 	struct pf_addr		init_addr;
299 	int			dir = (pd->dir == PF_IN) ? PF_OUT : PF_IN;
300 	int			sidx = pd->sidx;
301 	int			didx = pd->didx;
302 
303 	bzero(&init_addr, sizeof(init_addr));
304 
305 	if (udp_mapping) {
306 		MPASS(*udp_mapping == NULL);
307 	}
308 
309 	/*
310 	 * If we are UDP and have an existing mapping we can get source port
311 	 * from the mapping. In this case we have to look up the src_node as
312 	 * pf_map_addr would.
313 	 */
314 	if (pd->proto == IPPROTO_UDP && (rpool->opts & PF_POOL_ENDPI)) {
315 		struct pf_udp_endpoint_cmp udp_source;
316 
317 		bzero(&udp_source, sizeof(udp_source));
318 		udp_source.af = pd->af;
319 		pf_addrcpy(&udp_source.addr, &pd->nsaddr, pd->af);
320 		udp_source.port = pd->nsport;
321 		if (udp_mapping) {
322 			struct pf_ksrc_node	*sn = NULL;
323 			struct pf_srchash	*sh = NULL;
324 			*udp_mapping = pf_udp_mapping_find(&udp_source);
325 			if (*udp_mapping) {
326 				pf_addrcpy(naddr,
327 				    &(*udp_mapping)->endpoints[1].addr,
328 				    pd->af);
329 				*nport = (*udp_mapping)->endpoints[1].port;
330 				/*
331 				 * Try to find a src_node as per pf_map_addr().
332 				 * XXX: Why? This code seems to do nothing.
333 				 */
334 				if (rpool->opts & PF_POOL_STICKYADDR &&
335 				    (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE)
336 					sn = pf_find_src_node(&pd->nsaddr, r,
337 					    pd->af, &sh, sn_type, false);
338 				if (sn != NULL)
339 					PF_SRC_NODE_UNLOCK(sn);
340 				return (0);
341 			} else {
342 				*udp_mapping = pf_udp_mapping_create(pd->af, &pd->nsaddr,
343 				    pd->nsport, &init_addr, 0);
344 				if (*udp_mapping == NULL)
345 					return (1);
346 			}
347 		}
348 	}
349 
350 	if (pf_map_addr_sn(pd->naf, r, &pd->nsaddr, naddr, NULL, &init_addr,
351 	    rpool, sn_type))
352 		goto failed;
353 
354 	if (pd->proto == IPPROTO_ICMP) {
355 		if (pd->ndport == htons(ICMP_ECHO)) {
356 			low = 1;
357 			high = 65535;
358 		} else
359 			return (0);	/* Don't try to modify non-echo ICMP */
360 	}
361 #ifdef INET6
362 	if (pd->proto == IPPROTO_ICMPV6) {
363 		if (pd->ndport == htons(ICMP6_ECHO_REQUEST)) {
364 			low = 1;
365 			high = 65535;
366 		} else
367 			return (0);	/* Don't try to modify non-echo ICMP */
368 	}
369 #endif /* INET6 */
370 
371 	bzero(&key, sizeof(key));
372 	key.af = pd->naf;
373 	key.proto = pd->proto;
374 
375 	do {
376 		pf_addrcpy(&key.addr[didx], &pd->ndaddr, key.af);
377 		pf_addrcpy(&key.addr[sidx], naddr, key.af);
378 		key.port[didx] = pd->ndport;
379 
380 		if (udp_mapping && *udp_mapping)
381 			pf_addrcpy(&(*udp_mapping)->endpoints[1].addr, naddr,
382 			    pd->af);
383 
384 		/*
385 		 * port search; start random, step;
386 		 * similar 2 portloop in in_pcbbind
387 		 */
388 		if (pd->proto == IPPROTO_SCTP) {
389 			key.port[sidx] = pd->nsport;
390 			if (!pf_find_state_all_exists(&key, dir)) {
391 				*nport = pd->nsport;
392 				return (0);
393 			} else {
394 				return (1); /* Fail mapping. */
395 			}
396 		} else if (!(pd->proto == IPPROTO_TCP || pd->proto == IPPROTO_UDP ||
397 		    pd->proto == IPPROTO_ICMP) || (low == 0 && high == 0)) {
398 			/*
399 			 * XXX bug: icmp states don't use the id on both sides.
400 			 * (traceroute -I through nat)
401 			 */
402 			key.port[sidx] = pd->nsport;
403 			if (!pf_find_state_all_exists(&key, dir)) {
404 				*nport = pd->nsport;
405 				return (0);
406 			}
407 		} else if (low == high) {
408 			key.port[sidx] = htons(low);
409 			if (!pf_find_state_all_exists(&key, dir)) {
410 				if (udp_mapping && *udp_mapping != NULL) {
411 					(*udp_mapping)->endpoints[1].port = htons(low);
412 					if (pf_udp_mapping_insert(*udp_mapping) == 0) {
413 						*nport = htons(low);
414 						return (0);
415 					}
416 				} else {
417 					*nport = htons(low);
418 					return (0);
419 				}
420 			}
421 		} else {
422 			uint32_t tmp;
423 			uint16_t cut;
424 
425 			if (low > high) {
426 				tmp = low;
427 				low = high;
428 				high = tmp;
429 			}
430 			/* low < high */
431 			cut = arc4random() % (1 + high - low) + low;
432 			/* low <= cut <= high */
433 			for (tmp = cut; tmp <= high && tmp <= 0xffff; ++tmp) {
434 				if (udp_mapping && *udp_mapping != NULL) {
435 					(*udp_mapping)->endpoints[sidx].port = htons(tmp);
436 					if (pf_udp_mapping_insert(*udp_mapping) == 0) {
437 						*nport = htons(tmp);
438 						return (0);
439 					}
440 				} else {
441 					key.port[sidx] = htons(tmp);
442 					if (!pf_find_state_all_exists(&key, dir)) {
443 						*nport = htons(tmp);
444 						return (0);
445 					}
446 				}
447 			}
448 			tmp = cut;
449 			for (tmp -= 1; tmp >= low && tmp <= 0xffff; --tmp) {
450 				if (pd->proto == IPPROTO_UDP &&
451 				    (rpool->opts & PF_POOL_ENDPI &&
452 				    udp_mapping != NULL)) {
453 					(*udp_mapping)->endpoints[1].port = htons(tmp);
454 					if (pf_udp_mapping_insert(*udp_mapping) == 0) {
455 						*nport = htons(tmp);
456 						return (0);
457 					}
458 				} else {
459 					key.port[sidx] = htons(tmp);
460 					if (!pf_find_state_all_exists(&key, dir)) {
461 						*nport = htons(tmp);
462 						return (0);
463 					}
464 				}
465 			}
466 		}
467 
468 		switch (rpool->opts & PF_POOL_TYPEMASK) {
469 		case PF_POOL_RANDOM:
470 		case PF_POOL_ROUNDROBIN:
471 			/*
472 			 * pick a different source address since we're out
473 			 * of free port choices for the current one.
474 			 */
475 			if (pf_map_addr_sn(pd->naf, r, &pd->nsaddr, naddr, NULL,
476 			    &init_addr, rpool, sn_type))
477 				return (1);
478 			break;
479 		case PF_POOL_NONE:
480 		case PF_POOL_SRCHASH:
481 		case PF_POOL_BITMASK:
482 		default:
483 			return (1);
484 		}
485 	} while (! PF_AEQ(&init_addr, naddr, pd->naf) );
486 
487 failed:
488 	if (udp_mapping) {
489 		uma_zfree(V_pf_udp_mapping_z, *udp_mapping);
490 		*udp_mapping = NULL;
491 	}
492 
493 	return (1);					/* none available */
494 }
495 
496 static bool
pf_islinklocal(const sa_family_t af,const struct pf_addr * addr)497 pf_islinklocal(const sa_family_t af, const struct pf_addr *addr)
498 {
499 	if (af == AF_INET6 && IN6_IS_ADDR_LINKLOCAL(&addr->v6))
500 		return (true);
501 	return (false);
502 }
503 
504 static int
pf_get_mape_sport(struct pf_pdesc * pd,struct pf_krule * r,struct pf_addr * naddr,uint16_t * nport,struct pf_udp_mapping ** udp_mapping,struct pf_kpool * rpool)505 pf_get_mape_sport(struct pf_pdesc *pd, struct pf_krule *r,
506     struct pf_addr *naddr, uint16_t *nport,
507     struct pf_udp_mapping **udp_mapping, struct pf_kpool *rpool)
508 {
509 	uint16_t psmask, low, highmask;
510 	uint16_t i, ahigh, cut;
511 	int ashift, psidshift;
512 
513 	ashift = 16 - rpool->mape.offset;
514 	psidshift = ashift - rpool->mape.psidlen;
515 	psmask = rpool->mape.psid & ((1U << rpool->mape.psidlen) - 1);
516 	psmask = psmask << psidshift;
517 	highmask = (1U << psidshift) - 1;
518 
519 	ahigh = (1U << rpool->mape.offset) - 1;
520 	cut = arc4random() & ahigh;
521 	if (cut == 0)
522 		cut = 1;
523 
524 	for (i = cut; i <= ahigh; i++) {
525 		low = (i << ashift) | psmask;
526 		if (!pf_get_sport(pd, r, naddr, nport, low, low | highmask,
527 		    rpool, udp_mapping, PF_SN_NAT))
528 			return (0);
529 	}
530 	for (i = cut - 1; i > 0; i--) {
531 		low = (i << ashift) | psmask;
532 		if (!pf_get_sport(pd, r, naddr, nport, low, low | highmask,
533 		    rpool, udp_mapping, PF_SN_NAT))
534 			return (0);
535 	}
536 	return (1);
537 }
538 
539 u_short
pf_map_addr(sa_family_t af,struct pf_krule * r,struct pf_addr * saddr,struct pf_addr * naddr,struct pfi_kkif ** nkif,struct pf_addr * init_addr,struct pf_kpool * rpool)540 pf_map_addr(sa_family_t af, struct pf_krule *r, struct pf_addr *saddr,
541     struct pf_addr *naddr, struct pfi_kkif **nkif, struct pf_addr *init_addr,
542     struct pf_kpool *rpool)
543 {
544 	u_short			 reason = PFRES_MATCH;
545 	struct pf_addr		*raddr = NULL, *rmask = NULL;
546 	struct pfr_ktable	*kt;
547 	uint64_t		 hashidx;
548 	int			 cnt;
549 
550 	mtx_lock(&rpool->mtx);
551 	/* Find the route using chosen algorithm. Store the found route
552 	   in src_node if it was given or found. */
553 	if (rpool->cur->addr.type == PF_ADDR_NOROUTE) {
554 		reason = PFRES_MAPFAILED;
555 		goto done_pool_mtx;
556 	}
557 	if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
558 		switch (af) {
559 #ifdef INET
560 		case AF_INET:
561 			if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
562 			    !PF_POOL_DYNTYPE(rpool->opts)) {
563 				reason = PFRES_MAPFAILED;
564 				goto done_pool_mtx;
565 			}
566 			raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
567 			rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
568 			break;
569 #endif /* INET */
570 #ifdef INET6
571 		case AF_INET6:
572 			if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
573 			    !PF_POOL_DYNTYPE(rpool->opts)) {
574 				reason = PFRES_MAPFAILED;
575 				goto done_pool_mtx;
576 			}
577 			raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
578 			rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
579 			break;
580 #endif /* INET6 */
581 		default:
582 			unhandled_af(af);
583 		}
584 	} else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
585 		if (!PF_POOL_DYNTYPE(rpool->opts)) {
586 			reason = PFRES_MAPFAILED;
587 			goto done_pool_mtx; /* unsupported */
588 		}
589 	} else {
590 		raddr = &rpool->cur->addr.v.a.addr;
591 		rmask = &rpool->cur->addr.v.a.mask;
592 	}
593 
594 	switch (rpool->opts & PF_POOL_TYPEMASK) {
595 	case PF_POOL_NONE:
596 		pf_addrcpy(naddr, raddr, af);
597 		break;
598 	case PF_POOL_BITMASK:
599 		pf_poolmask(naddr, raddr, rmask, saddr, af);
600 		break;
601 	case PF_POOL_RANDOM:
602 		if (rpool->cur->addr.type == PF_ADDR_TABLE ||
603 		    rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
604 			if (rpool->cur->addr.type == PF_ADDR_TABLE)
605 				kt = rpool->cur->addr.p.tbl;
606 			else
607 				kt = rpool->cur->addr.p.dyn->pfid_kt;
608 			kt = pfr_ktable_select_active(kt);
609 			if (kt == NULL) {
610 				reason = PFRES_MAPFAILED;
611 				goto done_pool_mtx; /* unsupported */
612 			}
613 			cnt = kt->pfrkt_cnt;
614 			if (cnt == 0)
615 				rpool->tblidx = 0;
616 			else
617 				rpool->tblidx = (int)arc4random_uniform(cnt);
618 			memset(&rpool->counter, 0, sizeof(rpool->counter));
619 			if (pfr_pool_get(kt, &rpool->tblidx, &rpool->counter,
620 			    af, pf_islinklocal)) {
621 				reason = PFRES_MAPFAILED;
622 				goto done_pool_mtx; /* unsupported */
623 			}
624 			pf_addrcpy(naddr, &rpool->counter, af);
625 		} else if (init_addr != NULL && PF_AZERO(init_addr, af)) {
626 			switch (af) {
627 #ifdef INET
628 			case AF_INET:
629 				rpool->counter.addr32[0] = arc4random();
630 				break;
631 #endif /* INET */
632 #ifdef INET6
633 			case AF_INET6:
634 				if (rmask->addr32[3] != 0xffffffff)
635 					rpool->counter.addr32[3] =
636 					    arc4random();
637 				else
638 					break;
639 				if (rmask->addr32[2] != 0xffffffff)
640 					rpool->counter.addr32[2] =
641 					    arc4random();
642 				else
643 					break;
644 				if (rmask->addr32[1] != 0xffffffff)
645 					rpool->counter.addr32[1] =
646 					    arc4random();
647 				else
648 					break;
649 				if (rmask->addr32[0] != 0xffffffff)
650 					rpool->counter.addr32[0] =
651 					    arc4random();
652 				break;
653 #endif /* INET6 */
654 			}
655 			pf_poolmask(naddr, raddr, rmask, &rpool->counter, af);
656 			pf_addrcpy(init_addr, naddr, af);
657 
658 		} else {
659 			pf_addr_inc(&rpool->counter, af);
660 			pf_poolmask(naddr, raddr, rmask, &rpool->counter, af);
661 		}
662 		break;
663 	case PF_POOL_SRCHASH:
664 	    {
665 		unsigned char hash[16];
666 
667 		hashidx =
668 		    pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
669 		if (rpool->cur->addr.type == PF_ADDR_TABLE ||
670 		    rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
671 			if (rpool->cur->addr.type == PF_ADDR_TABLE)
672 				kt = rpool->cur->addr.p.tbl;
673 			else
674 				kt = rpool->cur->addr.p.dyn->pfid_kt;
675 			kt = pfr_ktable_select_active(kt);
676 			if (kt == NULL) {
677 				reason = PFRES_MAPFAILED;
678 				goto done_pool_mtx; /* unsupported */
679 			}
680 			cnt = kt->pfrkt_cnt;
681 			if (cnt == 0)
682 				rpool->tblidx = 0;
683 			else
684 				rpool->tblidx = (int)(hashidx % cnt);
685 			memset(&rpool->counter, 0, sizeof(rpool->counter));
686 			if (pfr_pool_get(kt, &rpool->tblidx, &rpool->counter,
687 			    af, pf_islinklocal)) {
688 				reason = PFRES_MAPFAILED;
689 				goto done_pool_mtx; /* unsupported */
690 			}
691 			pf_addrcpy(naddr, &rpool->counter, af);
692 		} else {
693 			pf_poolmask(naddr, raddr, rmask,
694 			    (struct pf_addr *)&hash, af);
695 		}
696 		break;
697 	    }
698 	case PF_POOL_ROUNDROBIN:
699 	    {
700 		struct pf_kpooladdr *acur = rpool->cur;
701 
702 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
703 			if (!pfr_pool_get(rpool->cur->addr.p.tbl,
704 			    &rpool->tblidx, &rpool->counter, af, NULL))
705 				goto get_addr;
706 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
707 			if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
708 			    &rpool->tblidx, &rpool->counter, af, pf_islinklocal))
709 				goto get_addr;
710 		} else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
711 			goto get_addr;
712 
713 	try_next:
714 		if (TAILQ_NEXT(rpool->cur, entries) == NULL)
715 			rpool->cur = TAILQ_FIRST(&rpool->list);
716 		else
717 			rpool->cur = TAILQ_NEXT(rpool->cur, entries);
718 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
719 			if (pfr_pool_get(rpool->cur->addr.p.tbl,
720 			    &rpool->tblidx, &rpool->counter, af, NULL)) {
721 				/* table contains no address of type 'af' */
722 				if (rpool->cur != acur)
723 					goto try_next;
724 				reason = PFRES_MAPFAILED;
725 				goto done_pool_mtx;
726 			}
727 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
728 			rpool->tblidx = -1;
729 			if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
730 			    &rpool->tblidx, &rpool->counter, af, pf_islinklocal)) {
731 				/* table contains no address of type 'af' */
732 				if (rpool->cur != acur)
733 					goto try_next;
734 				reason = PFRES_MAPFAILED;
735 				goto done_pool_mtx;
736 			}
737 		} else {
738 			raddr = &rpool->cur->addr.v.a.addr;
739 			rmask = &rpool->cur->addr.v.a.mask;
740 			pf_addrcpy(&rpool->counter, raddr, af);
741 		}
742 
743 	get_addr:
744 		pf_addrcpy(naddr, &rpool->counter, af);
745 		if (init_addr != NULL && PF_AZERO(init_addr, af))
746 			pf_addrcpy(init_addr, naddr, af);
747 		pf_addr_inc(&rpool->counter, af);
748 		break;
749 	    }
750 	}
751 
752 	if (nkif)
753 		*nkif = rpool->cur->kif;
754 
755 done_pool_mtx:
756 	mtx_unlock(&rpool->mtx);
757 
758 	if (reason) {
759 		counter_u64_add(V_pf_status.counters[reason], 1);
760 	}
761 
762 	return (reason);
763 }
764 
765 u_short
pf_map_addr_sn(sa_family_t af,struct pf_krule * r,struct pf_addr * saddr,struct pf_addr * naddr,struct pfi_kkif ** nkif,struct pf_addr * init_addr,struct pf_kpool * rpool,pf_sn_types_t sn_type)766 pf_map_addr_sn(sa_family_t af, struct pf_krule *r, struct pf_addr *saddr,
767     struct pf_addr *naddr, struct pfi_kkif **nkif, struct pf_addr *init_addr,
768     struct pf_kpool *rpool, pf_sn_types_t sn_type)
769 {
770 	struct pf_ksrc_node	*sn = NULL;
771 	struct pf_srchash	*sh = NULL;
772 	u_short			 reason = 0;
773 
774 	/*
775 	 * If this is a sticky-address rule, try to find an existing src_node.
776 	 */
777 	if (rpool->opts & PF_POOL_STICKYADDR &&
778 	    (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE)
779 		sn = pf_find_src_node(saddr, r, af, &sh, sn_type, false);
780 
781 	if (sn != NULL) {
782 		PF_SRC_NODE_LOCK_ASSERT(sn);
783 
784 		/* If the supplied address is the same as the current one we've
785 		 * been asked before, so tell the caller that there's no other
786 		 * address to be had. */
787 		if (PF_AEQ(naddr, &(sn->raddr), af)) {
788 			reason = PFRES_MAPFAILED;
789 			goto done;
790 		}
791 
792 		pf_addrcpy(naddr, &(sn->raddr), af);
793 		if (nkif)
794 			*nkif = sn->rkif;
795 		if (V_pf_status.debug >= PF_DEBUG_NOISY) {
796 			printf("pf_map_addr: src tracking maps ");
797 			pf_print_host(saddr, 0, af);
798 			printf(" to ");
799 			pf_print_host(naddr, 0, af);
800 			if (nkif)
801 				printf("@%s", (*nkif)->pfik_name);
802 			printf("\n");
803 		}
804 		goto done;
805 	}
806 
807 	/*
808 	 * Source node has not been found. Find a new address and store it
809 	 * in variables given by the caller.
810 	 */
811 	if (pf_map_addr(af, r, saddr, naddr, nkif, init_addr, rpool) != 0) {
812 		/* pf_map_addr() sets reason counters on its own */
813 		goto done;
814 	}
815 
816 	if (V_pf_status.debug >= PF_DEBUG_NOISY &&
817 	    (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
818 		printf("pf_map_addr: selected address ");
819 		pf_print_host(naddr, 0, af);
820 		if (nkif)
821 			printf("@%s", (*nkif)->pfik_name);
822 		printf("\n");
823 	}
824 
825 done:
826 	if (sn != NULL)
827 		PF_SRC_NODE_UNLOCK(sn);
828 
829 	if (reason) {
830 		counter_u64_add(V_pf_status.counters[reason], 1);
831 	}
832 
833 	return (reason);
834 }
835 
836 u_short
pf_get_translation(struct pf_test_ctx * ctx)837 pf_get_translation(struct pf_test_ctx *ctx)
838 {
839 	struct pf_krule	*r = NULL;
840 	u_short		 transerror;
841 
842 	PF_RULES_RASSERT();
843 	KASSERT(ctx->sk == NULL, ("*skp not NULL"));
844 	KASSERT(ctx->nk == NULL, ("*nkp not NULL"));
845 
846 	ctx->nr = NULL;
847 
848 	if (ctx->pd->dir == PF_OUT) {
849 		r = pf_match_translation(PF_RULESET_BINAT, ctx);
850 		if (r == NULL)
851 			r = pf_match_translation(PF_RULESET_NAT, ctx);
852 	} else {
853 		r = pf_match_translation(PF_RULESET_RDR, ctx);
854 		if (r == NULL)
855 			r = pf_match_translation(PF_RULESET_BINAT, ctx);
856 	}
857 
858 	if (r == NULL)
859 		return (PFRES_MAX);
860 
861 	switch (r->action) {
862 	case PF_NONAT:
863 	case PF_NOBINAT:
864 	case PF_NORDR:
865 		return (PFRES_MAX);
866 	}
867 
868 	transerror = pf_get_transaddr(ctx, r, r->action, &(r->rdr));
869 	if (transerror == PFRES_MATCH)
870 		ctx->nr = r;
871 
872 	return (transerror);
873 }
874 
875 u_short
pf_get_transaddr(struct pf_test_ctx * ctx,struct pf_krule * r,uint8_t nat_action,struct pf_kpool * rpool)876 pf_get_transaddr(struct pf_test_ctx *ctx, struct pf_krule *r,
877     uint8_t nat_action, struct pf_kpool *rpool)
878 {
879 	struct pf_pdesc	*pd = ctx->pd;
880 	struct pf_addr	*naddr;
881 	uint16_t	*nportp;
882 	uint16_t	 low, high;
883 	u_short		 reason;
884 
885 	PF_RULES_RASSERT();
886 	KASSERT(r != NULL, ("r is NULL"));
887 	KASSERT(!(r->rule_flag & PFRULE_AFTO), ("AFTO rule"));
888 
889 	if (ctx->sk == NULL && ctx->nk == NULL) {
890 		if (pf_state_key_setup(pd, pd->nsport, pd->ndport, &ctx->sk,
891 		    &ctx->nk))
892 			return (PFRES_MEMORY);
893 	}
894 
895 	naddr = &ctx->nk->addr[1];
896 	nportp = &ctx->nk->port[1];
897 
898 	switch (nat_action) {
899 	case PF_NAT:
900 		if (pd->proto == IPPROTO_ICMP) {
901 			low = 1;
902 			high = 65535;
903 		} else {
904 			low  = rpool->proxy_port[0];
905 			high = rpool->proxy_port[1];
906 		}
907 		if (rpool->mape.offset > 0) {
908 			if (pf_get_mape_sport(pd, r, naddr, nportp,
909 			    &ctx->udp_mapping, rpool)) {
910 				DPFPRINTF(PF_DEBUG_MISC,
911 				    ("pf: MAP-E port allocation (%u/%u/%u)"
912 				    " failed\n",
913 				    rpool->mape.offset,
914 				    rpool->mape.psidlen,
915 				    rpool->mape.psid));
916 				reason = PFRES_MAPFAILED;
917 				goto notrans;
918 			}
919 		} else if (pf_get_sport(pd, r, naddr, nportp, low, high,
920 		    rpool, &ctx->udp_mapping, PF_SN_NAT)) {
921 			DPFPRINTF(PF_DEBUG_MISC,
922 			    ("pf: NAT proxy port allocation (%u-%u) failed\n",
923 			    rpool->proxy_port[0], rpool->proxy_port[1]));
924 			reason = PFRES_MAPFAILED;
925 			goto notrans;
926 		}
927 		break;
928 	case PF_BINAT:
929 		switch (pd->dir) {
930 		case PF_OUT:
931 			if (rpool->cur->addr.type == PF_ADDR_DYNIFTL){
932 				switch (pd->af) {
933 #ifdef INET
934 				case AF_INET:
935 					if (rpool->cur->addr.p.dyn->
936 					    pfid_acnt4 < 1) {
937 						reason = PFRES_MAPFAILED;
938 						goto notrans;
939 					}
940 					pf_poolmask(naddr,
941 					    &rpool->cur->addr.p.dyn->pfid_addr4,
942 					    &rpool->cur->addr.p.dyn->pfid_mask4,
943 					    &pd->nsaddr, AF_INET);
944 					break;
945 #endif /* INET */
946 #ifdef INET6
947 				case AF_INET6:
948 					if (rpool->cur->addr.p.dyn->
949 					    pfid_acnt6 < 1) {
950 						reason = PFRES_MAPFAILED;
951 						goto notrans;
952 					}
953 					pf_poolmask(naddr,
954 					    &rpool->cur->addr.p.dyn->pfid_addr6,
955 					    &rpool->cur->addr.p.dyn->pfid_mask6,
956 					    &pd->nsaddr, AF_INET6);
957 					break;
958 #endif /* INET6 */
959 				}
960 			} else
961 				pf_poolmask(naddr,
962 				    &rpool->cur->addr.v.a.addr,
963 				    &rpool->cur->addr.v.a.mask, &pd->nsaddr,
964 				    pd->af);
965 			break;
966 		case PF_IN:
967 			if (r->src.addr.type == PF_ADDR_DYNIFTL) {
968 				switch (pd->af) {
969 #ifdef INET
970 				case AF_INET:
971 					if (r->src.addr.p.dyn->pfid_acnt4 < 1) {
972 						reason = PFRES_MAPFAILED;
973 						goto notrans;
974 					}
975 					pf_poolmask(naddr,
976 					    &r->src.addr.p.dyn->pfid_addr4,
977 					    &r->src.addr.p.dyn->pfid_mask4,
978 					    &pd->ndaddr, AF_INET);
979 					break;
980 #endif /* INET */
981 #ifdef INET6
982 				case AF_INET6:
983 					if (r->src.addr.p.dyn->pfid_acnt6 < 1) {
984 						reason = PFRES_MAPFAILED;
985 						goto notrans;
986 					}
987 					pf_poolmask(naddr,
988 					    &r->src.addr.p.dyn->pfid_addr6,
989 					    &r->src.addr.p.dyn->pfid_mask6,
990 					    &pd->ndaddr, AF_INET6);
991 					break;
992 #endif /* INET6 */
993 				}
994 			} else
995 				pf_poolmask(naddr, &r->src.addr.v.a.addr,
996 				    &r->src.addr.v.a.mask, &pd->ndaddr, pd->af);
997 			break;
998 		}
999 		break;
1000 	case PF_RDR: {
1001 		struct pf_state_key_cmp key;
1002 		int tries;
1003 		uint16_t cut, low, high, nport;
1004 
1005 		reason = pf_map_addr_sn(pd->af, r, &pd->nsaddr, naddr, NULL,
1006 		    NULL, rpool, PF_SN_NAT);
1007 		if (reason != 0)
1008 			goto notrans;
1009 		if ((rpool->opts & PF_POOL_TYPEMASK) == PF_POOL_BITMASK)
1010 			pf_poolmask(naddr, naddr, &rpool->cur->addr.v.a.mask,
1011 			    &pd->ndaddr, pd->af);
1012 
1013 		/* Do not change SCTP ports. */
1014 		if (pd->proto == IPPROTO_SCTP)
1015 			break;
1016 
1017 		if (rpool->proxy_port[1]) {
1018 			uint32_t	tmp_nport;
1019 
1020 			tmp_nport = ((ntohs(pd->ndport) - ntohs(r->dst.port[0])) %
1021 			    (rpool->proxy_port[1] - rpool->proxy_port[0] +
1022 			    1)) + rpool->proxy_port[0];
1023 
1024 			/* Wrap around if necessary. */
1025 			if (tmp_nport > 65535)
1026 				tmp_nport -= 65535;
1027 			nport = htons((uint16_t)tmp_nport);
1028 		} else if (rpool->proxy_port[0])
1029 			nport = htons(rpool->proxy_port[0]);
1030 		else
1031 			nport = pd->ndport;
1032 
1033 		/*
1034 		 * Update the destination port.
1035 		 */
1036 		*nportp = nport;
1037 
1038 		/*
1039 		 * Do we have a source port conflict in the stack state?  Try to
1040 		 * modulate the source port if so.  Note that this is racy since
1041 		 * the state lookup may not find any matches here but will once
1042 		 * pf_create_state() actually instantiates the state.
1043 		 */
1044 		bzero(&key, sizeof(key));
1045 		key.af = pd->af;
1046 		key.proto = pd->proto;
1047 		key.port[0] = pd->nsport;
1048 		pf_addrcpy(&key.addr[0], &pd->nsaddr, key.af);
1049 		key.port[1] = nport;
1050 		pf_addrcpy(&key.addr[1], naddr, key.af);
1051 
1052 		if (!pf_find_state_all_exists(&key, PF_OUT))
1053 			break;
1054 
1055 		tries = 0;
1056 
1057 		low = 50001;	/* XXX-MJ PF_NAT_PROXY_PORT_LOW/HIGH */
1058 		high = 65535;
1059 		cut = arc4random() % (1 + high - low) + low;
1060 		for (uint32_t tmp = cut;
1061 		    tmp <= high && tmp <= UINT16_MAX &&
1062 		    tries < V_pf_rdr_srcport_rewrite_tries;
1063 		    tmp++, tries++) {
1064 			key.port[0] = htons(tmp);
1065 			if (!pf_find_state_all_exists(&key, PF_OUT)) {
1066 				/* Update the source port. */
1067 				ctx->nk->port[0] = htons(tmp);
1068 				goto out;
1069 			}
1070 		}
1071 		for (uint32_t tmp = cut - 1;
1072 		    tmp >= low && tries < V_pf_rdr_srcport_rewrite_tries;
1073 		    tmp--, tries++) {
1074 			key.port[0] = htons(tmp);
1075 			if (!pf_find_state_all_exists(&key, PF_OUT)) {
1076 				/* Update the source port. */
1077 				ctx->nk->port[0] = htons(tmp);
1078 				goto out;
1079 			}
1080 		}
1081 
1082 		/*
1083 		 * We failed to find a match.  Push on ahead anyway, let
1084 		 * pf_state_insert() be the arbiter of whether the state
1085 		 * conflict is tolerable.  In particular, with TCP connections
1086 		 * the state may be reused if the TCP state is terminal.
1087 		 */
1088 		DPFPRINTF(PF_DEBUG_MISC,
1089 		    ("pf: RDR source port allocation failed\n"));
1090 		break;
1091 
1092 out:
1093 		DPFPRINTF(PF_DEBUG_MISC,
1094 		    ("pf: RDR source port allocation %u->%u\n",
1095 		    ntohs(pd->nsport), ntohs(ctx->nk->port[0])));
1096 		break;
1097 	}
1098 	default:
1099 		panic("%s: unknown action %u", __func__, r->action);
1100 	}
1101 
1102 	/* Return success only if translation really happened. */
1103 	if (bcmp(ctx->sk, ctx->nk, sizeof(struct pf_state_key_cmp))) {
1104 		return (PFRES_MATCH);
1105 	}
1106 
1107 	reason = PFRES_MAX;
1108 notrans:
1109 	uma_zfree(V_pf_state_key_z, ctx->nk);
1110 	uma_zfree(V_pf_state_key_z, ctx->sk);
1111 	ctx->sk = ctx->nk = NULL;
1112 
1113 	return (reason);
1114 }
1115 
1116 int
pf_get_transaddr_af(struct pf_krule * r,struct pf_pdesc * pd)1117 pf_get_transaddr_af(struct pf_krule *r, struct pf_pdesc *pd)
1118 {
1119 #if defined(INET) && defined(INET6)
1120 	struct pf_addr	 ndaddr, nsaddr, naddr;
1121 	u_int16_t	 nport = 0;
1122 	int		 prefixlen = 96;
1123 
1124 	bzero(&nsaddr, sizeof(nsaddr));
1125 	bzero(&ndaddr, sizeof(ndaddr));
1126 
1127 	if (V_pf_status.debug >= PF_DEBUG_MISC) {
1128 		printf("pf: af-to %s %s, ",
1129 		    pd->naf == AF_INET ? "inet" : "inet6",
1130 		    TAILQ_EMPTY(&r->rdr.list) ? "nat" : "rdr");
1131 		pf_print_host(&pd->nsaddr, pd->nsport, pd->af);
1132 		printf(" -> ");
1133 		pf_print_host(&pd->ndaddr, pd->ndport, pd->af);
1134 		printf("\n");
1135 	}
1136 
1137 	if (TAILQ_EMPTY(&r->nat.list))
1138 		panic("pf_get_transaddr_af: no nat pool for source address");
1139 
1140 	/* get source address and port */
1141 	if (pf_get_sport(pd, r, &nsaddr, &nport, r->nat.proxy_port[0],
1142 	    r->nat.proxy_port[1], &r->nat, NULL, PF_SN_NAT)) {
1143 		DPFPRINTF(PF_DEBUG_MISC,
1144 		    ("pf: af-to NAT proxy port allocation (%u-%u) failed",
1145 		    r->nat.proxy_port[0], r->nat.proxy_port[1]));
1146 		return (-1);
1147 	}
1148 
1149 	if (pd->proto == IPPROTO_ICMPV6 && pd->naf == AF_INET) {
1150 		pd->ndport = ntohs(pd->ndport);
1151 		if (pd->ndport == ICMP6_ECHO_REQUEST)
1152 			pd->ndport = ICMP_ECHO;
1153 		else if (pd->ndport == ICMP6_ECHO_REPLY)
1154 			pd->ndport = ICMP_ECHOREPLY;
1155 		pd->ndport = htons(pd->ndport);
1156 	} else if (pd->proto == IPPROTO_ICMP && pd->naf == AF_INET6) {
1157 		pd->nsport = ntohs(pd->nsport);
1158 		if (pd->ndport == ICMP_ECHO)
1159 			pd->ndport = ICMP6_ECHO_REQUEST;
1160 		else if (pd->ndport == ICMP_ECHOREPLY)
1161 			pd->ndport = ICMP6_ECHO_REPLY;
1162 		pd->nsport = htons(pd->nsport);
1163 	}
1164 
1165 	/* get the destination address and port */
1166 	if (! TAILQ_EMPTY(&r->rdr.list)) {
1167 		if (pf_map_addr_sn(pd->naf, r, &nsaddr, &naddr, NULL, NULL,
1168 		    &r->rdr, PF_SN_NAT))
1169 			return (-1);
1170 		if (r->rdr.proxy_port[0])
1171 			pd->ndport = htons(r->rdr.proxy_port[0]);
1172 
1173 		if (pd->naf == AF_INET) {
1174 			/* The prefix is the IPv4 rdr address */
1175 			prefixlen = in_mask2len(
1176 			    (struct in_addr *)&r->rdr.cur->addr.v.a.mask);
1177 			inet_nat46(pd->naf, &pd->ndaddr, &ndaddr, &naddr,
1178 			    prefixlen);
1179 		} else {
1180 			/* The prefix is the IPv6 rdr address */
1181 			prefixlen = in6_mask2len(
1182 			    (struct in6_addr *)&r->rdr.cur->addr.v.a.mask, NULL);
1183 			inet_nat64(pd->naf, &pd->ndaddr, &ndaddr, &naddr,
1184 			    prefixlen);
1185 		}
1186 	} else {
1187 		if (pd->naf == AF_INET) {
1188 			/* The prefix is the IPv6 dst address */
1189 			prefixlen = in6_mask2len(
1190 			    (struct in6_addr *)&r->dst.addr.v.a.mask, NULL);
1191 			if (prefixlen < 32)
1192 				prefixlen = 96;
1193 			inet_nat64(pd->naf, &pd->ndaddr, &ndaddr, &pd->ndaddr,
1194 			    prefixlen);
1195 		} else {
1196 			/*
1197 			 * The prefix is the IPv6 nat address
1198 			 * (that was stored in pd->nsaddr)
1199 			 */
1200 			prefixlen = in6_mask2len(
1201 			    (struct in6_addr *)&r->nat.cur->addr.v.a.mask, NULL);
1202 			if (prefixlen > 96)
1203 				prefixlen = 96;
1204 			inet_nat64(pd->naf, &pd->ndaddr, &ndaddr, &nsaddr,
1205 			    prefixlen);
1206 		}
1207 	}
1208 
1209 	pf_addrcpy(&pd->nsaddr, &nsaddr, pd->naf);
1210 	pf_addrcpy(&pd->ndaddr, &ndaddr, pd->naf);
1211 
1212 	if (V_pf_status.debug >= PF_DEBUG_MISC) {
1213 		printf("pf: af-to %s done, prefixlen %d, ",
1214 		    pd->naf == AF_INET ? "inet" : "inet6",
1215 		    prefixlen);
1216 		pf_print_host(&pd->nsaddr, pd->nsport, pd->naf);
1217 		printf(" -> ");
1218 		pf_print_host(&pd->ndaddr, pd->ndport, pd->naf);
1219 		printf("\n");
1220 	}
1221 
1222 	return (0);
1223 #else
1224 	return (-1);
1225 #endif
1226 }
1227