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