1 /*-
2  * Copyright (c) 2001 Daniel Hartmeier
3  * Copyright (c) 2002 - 2008 Henning Brauer
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  *    - Redistributions of source code must retain the above copyright
11  *      notice, this list of conditions and the following disclaimer.
12  *    - Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials provided
15  *      with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Effort sponsored in part by the Defense Advanced Research Projects
31  * Agency (DARPA) and Air Force Research Laboratory, Air Force
32  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
33  *
34  *	$OpenBSD: pf_lb.c,v 1.2 2009/02/12 02:13:15 sthen Exp $
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD: stable/10/sys/netpfil/pf/pf_lb.c 314940 2017-03-09 03:20:20Z kp $");
39 
40 #include "opt_pf.h"
41 #include "opt_inet.h"
42 #include "opt_inet6.h"
43 
44 #include <sys/param.h>
45 #include <sys/socket.h>
46 #include <sys/sysctl.h>
47 
48 #include <net/if.h>
49 #include <net/pfvar.h>
50 #include <net/if_pflog.h>
51 
52 #define DPFPRINTF(n, x)	if (V_pf_status.debug >= (n)) printf x
53 
54 static void		 pf_hash(struct pf_addr *, struct pf_addr *,
55 			    struct pf_poolhashkey *, sa_family_t);
56 static struct pf_rule	*pf_match_translation(struct pf_pdesc *, struct mbuf *,
57 			    int, int, struct pfi_kif *,
58 			    struct pf_addr *, u_int16_t, struct pf_addr *,
59 			    uint16_t, int, struct pf_anchor_stackframe *);
60 static int pf_get_sport(sa_family_t, uint8_t, struct pf_rule *,
61     struct pf_addr *, uint16_t, struct pf_addr *, uint16_t, struct pf_addr *,
62     uint16_t *, uint16_t, uint16_t, struct pf_src_node **);
63 
64 #define mix(a,b,c) \
65 	do {					\
66 		a -= b; a -= c; a ^= (c >> 13);	\
67 		b -= c; b -= a; b ^= (a << 8);	\
68 		c -= a; c -= b; c ^= (b >> 13);	\
69 		a -= b; a -= c; a ^= (c >> 12);	\
70 		b -= c; b -= a; b ^= (a << 16);	\
71 		c -= a; c -= b; c ^= (b >> 5);	\
72 		a -= b; a -= c; a ^= (c >> 3);	\
73 		b -= c; b -= a; b ^= (a << 10);	\
74 		c -= a; c -= b; c ^= (b >> 15);	\
75 	} while (0)
76 
77 /*
78  * hash function based on bridge_hash in if_bridge.c
79  */
80 static void
pf_hash(struct pf_addr * inaddr,struct pf_addr * hash,struct pf_poolhashkey * key,sa_family_t af)81 pf_hash(struct pf_addr *inaddr, struct pf_addr *hash,
82     struct pf_poolhashkey *key, sa_family_t af)
83 {
84 	u_int32_t	a = 0x9e3779b9, b = 0x9e3779b9, c = key->key32[0];
85 
86 	switch (af) {
87 #ifdef INET
88 	case AF_INET:
89 		a += inaddr->addr32[0];
90 		b += key->key32[1];
91 		mix(a, b, c);
92 		hash->addr32[0] = c + key->key32[2];
93 		break;
94 #endif /* INET */
95 #ifdef INET6
96 	case AF_INET6:
97 		a += inaddr->addr32[0];
98 		b += inaddr->addr32[2];
99 		mix(a, b, c);
100 		hash->addr32[0] = c;
101 		a += inaddr->addr32[1];
102 		b += inaddr->addr32[3];
103 		c += key->key32[1];
104 		mix(a, b, c);
105 		hash->addr32[1] = c;
106 		a += inaddr->addr32[2];
107 		b += inaddr->addr32[1];
108 		c += key->key32[2];
109 		mix(a, b, c);
110 		hash->addr32[2] = c;
111 		a += inaddr->addr32[3];
112 		b += inaddr->addr32[0];
113 		c += key->key32[3];
114 		mix(a, b, c);
115 		hash->addr32[3] = c;
116 		break;
117 #endif /* INET6 */
118 	}
119 }
120 
121 static struct pf_rule *
pf_match_translation(struct pf_pdesc * pd,struct mbuf * m,int off,int direction,struct pfi_kif * kif,struct pf_addr * saddr,u_int16_t sport,struct pf_addr * daddr,uint16_t dport,int rs_num,struct pf_anchor_stackframe * anchor_stack)122 pf_match_translation(struct pf_pdesc *pd, struct mbuf *m, int off,
123     int direction, struct pfi_kif *kif, struct pf_addr *saddr, u_int16_t sport,
124     struct pf_addr *daddr, uint16_t dport, int rs_num,
125     struct pf_anchor_stackframe *anchor_stack)
126 {
127 	struct pf_rule		*r, *rm = NULL;
128 	struct pf_ruleset	*ruleset = NULL;
129 	int			 tag = -1;
130 	int			 rtableid = -1;
131 	int			 asd = 0;
132 
133 	r = TAILQ_FIRST(pf_main_ruleset.rules[rs_num].active.ptr);
134 	while (r && rm == NULL) {
135 		struct pf_rule_addr	*src = NULL, *dst = NULL;
136 		struct pf_addr_wrap	*xdst = NULL;
137 
138 		if (r->action == PF_BINAT && direction == PF_IN) {
139 			src = &r->dst;
140 			if (r->rpool.cur != NULL)
141 				xdst = &r->rpool.cur->addr;
142 		} else {
143 			src = &r->src;
144 			dst = &r->dst;
145 		}
146 
147 		r->evaluations++;
148 		if (pfi_kif_match(r->kif, kif) == r->ifnot)
149 			r = r->skip[PF_SKIP_IFP].ptr;
150 		else if (r->direction && r->direction != direction)
151 			r = r->skip[PF_SKIP_DIR].ptr;
152 		else if (r->af && r->af != pd->af)
153 			r = r->skip[PF_SKIP_AF].ptr;
154 		else if (r->proto && r->proto != pd->proto)
155 			r = r->skip[PF_SKIP_PROTO].ptr;
156 		else if (PF_MISMATCHAW(&src->addr, saddr, pd->af,
157 		    src->neg, kif, M_GETFIB(m)))
158 			r = r->skip[src == &r->src ? PF_SKIP_SRC_ADDR :
159 			    PF_SKIP_DST_ADDR].ptr;
160 		else if (src->port_op && !pf_match_port(src->port_op,
161 		    src->port[0], src->port[1], sport))
162 			r = r->skip[src == &r->src ? PF_SKIP_SRC_PORT :
163 			    PF_SKIP_DST_PORT].ptr;
164 		else if (dst != NULL &&
165 		    PF_MISMATCHAW(&dst->addr, daddr, pd->af, dst->neg, NULL,
166 		    M_GETFIB(m)))
167 			r = r->skip[PF_SKIP_DST_ADDR].ptr;
168 		else if (xdst != NULL && PF_MISMATCHAW(xdst, daddr, pd->af,
169 		    0, NULL, M_GETFIB(m)))
170 			r = TAILQ_NEXT(r, entries);
171 		else if (dst != NULL && dst->port_op &&
172 		    !pf_match_port(dst->port_op, dst->port[0],
173 		    dst->port[1], dport))
174 			r = r->skip[PF_SKIP_DST_PORT].ptr;
175 		else if (r->match_tag && !pf_match_tag(m, r, &tag,
176 		    pd->pf_mtag ? pd->pf_mtag->tag : 0))
177 			r = TAILQ_NEXT(r, entries);
178 		else if (r->os_fingerprint != PF_OSFP_ANY && (pd->proto !=
179 		    IPPROTO_TCP || !pf_osfp_match(pf_osfp_fingerprint(pd, m,
180 		    off, pd->hdr.tcp), r->os_fingerprint)))
181 			r = TAILQ_NEXT(r, entries);
182 		else {
183 			if (r->tag)
184 				tag = r->tag;
185 			if (r->rtableid >= 0)
186 				rtableid = r->rtableid;
187 			if (r->anchor == NULL) {
188 				rm = r;
189 			} else
190 				pf_step_into_anchor(anchor_stack, &asd,
191 				    &ruleset, rs_num, &r, NULL, NULL);
192 		}
193 		if (r == NULL)
194 			pf_step_out_of_anchor(anchor_stack, &asd, &ruleset,
195 			    rs_num, &r, NULL, NULL);
196 	}
197 
198 	if (tag > 0 && pf_tag_packet(m, pd, tag))
199 		return (NULL);
200 	if (rtableid >= 0)
201 		M_SETFIB(m, rtableid);
202 
203 	if (rm != NULL && (rm->action == PF_NONAT ||
204 	    rm->action == PF_NORDR || rm->action == PF_NOBINAT))
205 		return (NULL);
206 	return (rm);
207 }
208 
209 static int
pf_get_sport(sa_family_t af,u_int8_t proto,struct pf_rule * r,struct pf_addr * saddr,uint16_t sport,struct pf_addr * daddr,uint16_t dport,struct pf_addr * naddr,uint16_t * nport,uint16_t low,uint16_t high,struct pf_src_node ** sn)210 pf_get_sport(sa_family_t af, u_int8_t proto, struct pf_rule *r,
211     struct pf_addr *saddr, uint16_t sport, struct pf_addr *daddr,
212     uint16_t dport, struct pf_addr *naddr, uint16_t *nport, uint16_t low,
213     uint16_t high, struct pf_src_node **sn)
214 {
215 	struct pf_state_key_cmp	key;
216 	struct pf_addr		init_addr;
217 	uint16_t		cut;
218 
219 	bzero(&init_addr, sizeof(init_addr));
220 	if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
221 		return (1);
222 
223 	if (proto == IPPROTO_ICMP) {
224 		low = 1;
225 		high = 65535;
226 	}
227 
228 	bzero(&key, sizeof(key));
229 	key.af = af;
230 	key.proto = proto;
231 	key.port[0] = dport;
232 	PF_ACPY(&key.addr[0], daddr, key.af);
233 
234 	do {
235 		PF_ACPY(&key.addr[1], naddr, key.af);
236 
237 		/*
238 		 * port search; start random, step;
239 		 * similar 2 portloop in in_pcbbind
240 		 */
241 		if (!(proto == IPPROTO_TCP || proto == IPPROTO_UDP ||
242 		    proto == IPPROTO_ICMP) || (low == 0 && high == 0)) {
243 			/*
244 			 * XXX bug: icmp states don't use the id on both sides.
245 			 * (traceroute -I through nat)
246 			 */
247 			key.port[1] = sport;
248 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
249 				*nport = sport;
250 				return (0);
251 			}
252 		} else if (low == high) {
253 			key.port[1] = htons(low);
254 			if (pf_find_state_all(&key, PF_IN, NULL) == NULL) {
255 				*nport = htons(low);
256 				return (0);
257 			}
258 		} else {
259 			uint16_t tmp;
260 
261 			if (low > high) {
262 				tmp = low;
263 				low = high;
264 				high = tmp;
265 			}
266 			/* low < high */
267 			cut = htonl(arc4random()) % (1 + high - low) + low;
268 			/* low <= cut <= high */
269 			for (tmp = cut; tmp <= high; ++(tmp)) {
270 				key.port[1] = htons(tmp);
271 				if (pf_find_state_all(&key, PF_IN, NULL) ==
272 				    NULL) {
273 					*nport = htons(tmp);
274 					return (0);
275 				}
276 			}
277 			for (tmp = cut - 1; tmp >= low; --(tmp)) {
278 				key.port[1] = htons(tmp);
279 				if (pf_find_state_all(&key, PF_IN, NULL) ==
280 				    NULL) {
281 					*nport = htons(tmp);
282 					return (0);
283 				}
284 			}
285 		}
286 
287 		switch (r->rpool.opts & PF_POOL_TYPEMASK) {
288 		case PF_POOL_RANDOM:
289 		case PF_POOL_ROUNDROBIN:
290 			if (pf_map_addr(af, r, saddr, naddr, &init_addr, sn))
291 				return (1);
292 			break;
293 		case PF_POOL_NONE:
294 		case PF_POOL_SRCHASH:
295 		case PF_POOL_BITMASK:
296 		default:
297 			return (1);
298 		}
299 	} while (! PF_AEQ(&init_addr, naddr, af) );
300 	return (1);					/* none available */
301 }
302 
303 int
pf_map_addr(sa_family_t af,struct pf_rule * r,struct pf_addr * saddr,struct pf_addr * naddr,struct pf_addr * init_addr,struct pf_src_node ** sn)304 pf_map_addr(sa_family_t af, struct pf_rule *r, struct pf_addr *saddr,
305     struct pf_addr *naddr, struct pf_addr *init_addr, struct pf_src_node **sn)
306 {
307 	struct pf_pool		*rpool = &r->rpool;
308 	struct pf_addr		*raddr = NULL, *rmask = NULL;
309 
310 	/* Try to find a src_node if none was given and this
311 	   is a sticky-address rule. */
312 	if (*sn == NULL && r->rpool.opts & PF_POOL_STICKYADDR &&
313 	    (r->rpool.opts & PF_POOL_TYPEMASK) != PF_POOL_NONE)
314 		*sn = pf_find_src_node(saddr, r, af, 0);
315 
316 	/* If a src_node was found or explicitly given and it has a non-zero
317 	   route address, use this address. A zeroed address is found if the
318 	   src node was created just a moment ago in pf_create_state and it
319 	   needs to be filled in with routing decision calculated here. */
320 	if (*sn != NULL && !PF_AZERO(&(*sn)->raddr, af)) {
321 		PF_ACPY(naddr, &(*sn)->raddr, af);
322 		if (V_pf_status.debug >= PF_DEBUG_MISC) {
323 			printf("pf_map_addr: src tracking maps ");
324 			pf_print_host(saddr, 0, af);
325 			printf(" to ");
326 			pf_print_host(naddr, 0, af);
327 			printf("\n");
328 		}
329 		return (0);
330 	}
331 
332 	/* Find the route using chosen algorithm. Store the found route
333 	   in src_node if it was given or found. */
334 	if (rpool->cur->addr.type == PF_ADDR_NOROUTE)
335 		return (1);
336 	if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
337 		switch (af) {
338 #ifdef INET
339 		case AF_INET:
340 			if (rpool->cur->addr.p.dyn->pfid_acnt4 < 1 &&
341 			    (rpool->opts & PF_POOL_TYPEMASK) !=
342 			    PF_POOL_ROUNDROBIN)
343 				return (1);
344 			 raddr = &rpool->cur->addr.p.dyn->pfid_addr4;
345 			 rmask = &rpool->cur->addr.p.dyn->pfid_mask4;
346 			break;
347 #endif /* INET */
348 #ifdef INET6
349 		case AF_INET6:
350 			if (rpool->cur->addr.p.dyn->pfid_acnt6 < 1 &&
351 			    (rpool->opts & PF_POOL_TYPEMASK) !=
352 			    PF_POOL_ROUNDROBIN)
353 				return (1);
354 			raddr = &rpool->cur->addr.p.dyn->pfid_addr6;
355 			rmask = &rpool->cur->addr.p.dyn->pfid_mask6;
356 			break;
357 #endif /* INET6 */
358 		}
359 	} else if (rpool->cur->addr.type == PF_ADDR_TABLE) {
360 		if ((rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_ROUNDROBIN)
361 			return (1); /* unsupported */
362 	} else {
363 		raddr = &rpool->cur->addr.v.a.addr;
364 		rmask = &rpool->cur->addr.v.a.mask;
365 	}
366 
367 	switch (rpool->opts & PF_POOL_TYPEMASK) {
368 	case PF_POOL_NONE:
369 		PF_ACPY(naddr, raddr, af);
370 		break;
371 	case PF_POOL_BITMASK:
372 		PF_POOLMASK(naddr, raddr, rmask, saddr, af);
373 		break;
374 	case PF_POOL_RANDOM:
375 		if (init_addr != NULL && PF_AZERO(init_addr, af)) {
376 			switch (af) {
377 #ifdef INET
378 			case AF_INET:
379 				rpool->counter.addr32[0] = htonl(arc4random());
380 				break;
381 #endif /* INET */
382 #ifdef INET6
383 			case AF_INET6:
384 				if (rmask->addr32[3] != 0xffffffff)
385 					rpool->counter.addr32[3] =
386 					    htonl(arc4random());
387 				else
388 					break;
389 				if (rmask->addr32[2] != 0xffffffff)
390 					rpool->counter.addr32[2] =
391 					    htonl(arc4random());
392 				else
393 					break;
394 				if (rmask->addr32[1] != 0xffffffff)
395 					rpool->counter.addr32[1] =
396 					    htonl(arc4random());
397 				else
398 					break;
399 				if (rmask->addr32[0] != 0xffffffff)
400 					rpool->counter.addr32[0] =
401 					    htonl(arc4random());
402 				break;
403 #endif /* INET6 */
404 			}
405 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
406 			PF_ACPY(init_addr, naddr, af);
407 
408 		} else {
409 			PF_AINC(&rpool->counter, af);
410 			PF_POOLMASK(naddr, raddr, rmask, &rpool->counter, af);
411 		}
412 		break;
413 	case PF_POOL_SRCHASH:
414 	    {
415 		unsigned char hash[16];
416 
417 		pf_hash(saddr, (struct pf_addr *)&hash, &rpool->key, af);
418 		PF_POOLMASK(naddr, raddr, rmask, (struct pf_addr *)&hash, af);
419 		break;
420 	    }
421 	case PF_POOL_ROUNDROBIN:
422 	    {
423 		struct pf_pooladdr *acur = rpool->cur;
424 
425 		/*
426 		 * XXXGL: in the round-robin case we need to store
427 		 * the round-robin machine state in the rule, thus
428 		 * forwarding thread needs to modify rule.
429 		 *
430 		 * This is done w/o locking, because performance is assumed
431 		 * more important than round-robin precision.
432 		 *
433 		 * In the simpliest case we just update the "rpool->cur"
434 		 * pointer. However, if pool contains tables or dynamic
435 		 * addresses, then "tblidx" is also used to store machine
436 		 * state. Since "tblidx" is int, concurrent access to it can't
437 		 * lead to inconsistence, only to lost of precision.
438 		 *
439 		 * Things get worse, if table contains not hosts, but
440 		 * prefixes. In this case counter also stores machine state,
441 		 * and for IPv6 address, counter can't be updated atomically.
442 		 * Probably, using round-robin on a table containing IPv6
443 		 * prefixes (or even IPv4) would cause a panic.
444 		 */
445 
446 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
447 			if (!pfr_pool_get(rpool->cur->addr.p.tbl,
448 			    &rpool->tblidx, &rpool->counter, af))
449 				goto get_addr;
450 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
451 			if (!pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
452 			    &rpool->tblidx, &rpool->counter, af))
453 				goto get_addr;
454 		} else if (pf_match_addr(0, raddr, rmask, &rpool->counter, af))
455 			goto get_addr;
456 
457 	try_next:
458 		if (TAILQ_NEXT(rpool->cur, entries) == NULL)
459 			rpool->cur = TAILQ_FIRST(&rpool->list);
460 		else
461 			rpool->cur = TAILQ_NEXT(rpool->cur, entries);
462 		if (rpool->cur->addr.type == PF_ADDR_TABLE) {
463 			rpool->tblidx = -1;
464 			if (pfr_pool_get(rpool->cur->addr.p.tbl,
465 			    &rpool->tblidx, &rpool->counter, af)) {
466 				/* table contains no address of type 'af' */
467 				if (rpool->cur != acur)
468 					goto try_next;
469 				return (1);
470 			}
471 		} else if (rpool->cur->addr.type == PF_ADDR_DYNIFTL) {
472 			rpool->tblidx = -1;
473 			if (pfr_pool_get(rpool->cur->addr.p.dyn->pfid_kt,
474 			    &rpool->tblidx, &rpool->counter, af)) {
475 				/* table contains no address of type 'af' */
476 				if (rpool->cur != acur)
477 					goto try_next;
478 				return (1);
479 			}
480 		} else {
481 			raddr = &rpool->cur->addr.v.a.addr;
482 			rmask = &rpool->cur->addr.v.a.mask;
483 			PF_ACPY(&rpool->counter, raddr, af);
484 		}
485 
486 	get_addr:
487 		PF_ACPY(naddr, &rpool->counter, af);
488 		if (init_addr != NULL && PF_AZERO(init_addr, af))
489 			PF_ACPY(init_addr, naddr, af);
490 		PF_AINC(&rpool->counter, af);
491 		break;
492 	    }
493 	}
494 	if (*sn != NULL)
495 		PF_ACPY(&(*sn)->raddr, naddr, af);
496 
497 	if (V_pf_status.debug >= PF_DEBUG_MISC &&
498 	    (rpool->opts & PF_POOL_TYPEMASK) != PF_POOL_NONE) {
499 		printf("pf_map_addr: selected address ");
500 		pf_print_host(naddr, 0, af);
501 		printf("\n");
502 	}
503 
504 	return (0);
505 }
506 
507 struct pf_rule *
pf_get_translation(struct pf_pdesc * pd,struct mbuf * m,int off,int direction,struct pfi_kif * kif,struct pf_src_node ** sn,struct pf_state_key ** skp,struct pf_state_key ** nkp,struct pf_addr * saddr,struct pf_addr * daddr,uint16_t sport,uint16_t dport,struct pf_anchor_stackframe * anchor_stack)508 pf_get_translation(struct pf_pdesc *pd, struct mbuf *m, int off, int direction,
509     struct pfi_kif *kif, struct pf_src_node **sn,
510     struct pf_state_key **skp, struct pf_state_key **nkp,
511     struct pf_addr *saddr, struct pf_addr *daddr,
512     uint16_t sport, uint16_t dport, struct pf_anchor_stackframe *anchor_stack)
513 {
514 	struct pf_rule	*r = NULL;
515 	struct pf_addr	*naddr;
516 	uint16_t	*nport;
517 
518 	PF_RULES_RASSERT();
519 	KASSERT(*skp == NULL, ("*skp not NULL"));
520 	KASSERT(*nkp == NULL, ("*nkp not NULL"));
521 
522 	if (direction == PF_OUT) {
523 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
524 		    sport, daddr, dport, PF_RULESET_BINAT, anchor_stack);
525 		if (r == NULL)
526 			r = pf_match_translation(pd, m, off, direction, kif,
527 			    saddr, sport, daddr, dport, PF_RULESET_NAT,
528 			    anchor_stack);
529 	} else {
530 		r = pf_match_translation(pd, m, off, direction, kif, saddr,
531 		    sport, daddr, dport, PF_RULESET_RDR, anchor_stack);
532 		if (r == NULL)
533 			r = pf_match_translation(pd, m, off, direction, kif,
534 			    saddr, sport, daddr, dport, PF_RULESET_BINAT,
535 			    anchor_stack);
536 	}
537 
538 	if (r == NULL)
539 		return (NULL);
540 
541 	switch (r->action) {
542 	case PF_NONAT:
543 	case PF_NOBINAT:
544 	case PF_NORDR:
545 		return (NULL);
546 	}
547 
548 	*skp = pf_state_key_setup(pd, saddr, daddr, sport, dport);
549 	if (*skp == NULL)
550 		return (NULL);
551 	*nkp = pf_state_key_clone(*skp);
552 	if (*nkp == NULL) {
553 		uma_zfree(V_pf_state_key_z, *skp);
554 		*skp = NULL;
555 		return (NULL);
556 	}
557 
558 	/* XXX We only modify one side for now. */
559 	naddr = &(*nkp)->addr[1];
560 	nport = &(*nkp)->port[1];
561 
562 	switch (r->action) {
563 	case PF_NAT:
564 		if (pf_get_sport(pd->af, pd->proto, r, saddr, sport, daddr,
565 		    dport, naddr, nport, r->rpool.proxy_port[0],
566 		    r->rpool.proxy_port[1], sn)) {
567 			DPFPRINTF(PF_DEBUG_MISC,
568 			    ("pf: NAT proxy port allocation (%u-%u) failed\n",
569 			    r->rpool.proxy_port[0], r->rpool.proxy_port[1]));
570 			goto notrans;
571 		}
572 		break;
573 	case PF_BINAT:
574 		switch (direction) {
575 		case PF_OUT:
576 			if (r->rpool.cur->addr.type == PF_ADDR_DYNIFTL){
577 				switch (pd->af) {
578 #ifdef INET
579 				case AF_INET:
580 					if (r->rpool.cur->addr.p.dyn->
581 					    pfid_acnt4 < 1)
582 						goto notrans;
583 					PF_POOLMASK(naddr,
584 					    &r->rpool.cur->addr.p.dyn->
585 					    pfid_addr4,
586 					    &r->rpool.cur->addr.p.dyn->
587 					    pfid_mask4, saddr, AF_INET);
588 					break;
589 #endif /* INET */
590 #ifdef INET6
591 				case AF_INET6:
592 					if (r->rpool.cur->addr.p.dyn->
593 					    pfid_acnt6 < 1)
594 						goto notrans;
595 					PF_POOLMASK(naddr,
596 					    &r->rpool.cur->addr.p.dyn->
597 					    pfid_addr6,
598 					    &r->rpool.cur->addr.p.dyn->
599 					    pfid_mask6, saddr, AF_INET6);
600 					break;
601 #endif /* INET6 */
602 				}
603 			} else
604 				PF_POOLMASK(naddr,
605 				    &r->rpool.cur->addr.v.a.addr,
606 				    &r->rpool.cur->addr.v.a.mask, saddr,
607 				    pd->af);
608 			break;
609 		case PF_IN:
610 			if (r->src.addr.type == PF_ADDR_DYNIFTL) {
611 				switch (pd->af) {
612 #ifdef INET
613 				case AF_INET:
614 					if (r->src.addr.p.dyn-> pfid_acnt4 < 1)
615 						goto notrans;
616 					PF_POOLMASK(naddr,
617 					    &r->src.addr.p.dyn->pfid_addr4,
618 					    &r->src.addr.p.dyn->pfid_mask4,
619 					    daddr, AF_INET);
620 					break;
621 #endif /* INET */
622 #ifdef INET6
623 				case AF_INET6:
624 					if (r->src.addr.p.dyn->pfid_acnt6 < 1)
625 						goto notrans;
626 					PF_POOLMASK(naddr,
627 					    &r->src.addr.p.dyn->pfid_addr6,
628 					    &r->src.addr.p.dyn->pfid_mask6,
629 					    daddr, AF_INET6);
630 					break;
631 #endif /* INET6 */
632 				}
633 			} else
634 				PF_POOLMASK(naddr, &r->src.addr.v.a.addr,
635 				    &r->src.addr.v.a.mask, daddr, pd->af);
636 			break;
637 		}
638 		break;
639 	case PF_RDR: {
640 		if (pf_map_addr(pd->af, r, saddr, naddr, NULL, sn))
641 			goto notrans;
642 		if ((r->rpool.opts & PF_POOL_TYPEMASK) == PF_POOL_BITMASK)
643 			PF_POOLMASK(naddr, naddr, &r->rpool.cur->addr.v.a.mask,
644 			    daddr, pd->af);
645 
646 		if (r->rpool.proxy_port[1]) {
647 			uint32_t	tmp_nport;
648 
649 			tmp_nport = ((ntohs(dport) - ntohs(r->dst.port[0])) %
650 			    (r->rpool.proxy_port[1] - r->rpool.proxy_port[0] +
651 			    1)) + r->rpool.proxy_port[0];
652 
653 			/* Wrap around if necessary. */
654 			if (tmp_nport > 65535)
655 				tmp_nport -= 65535;
656 			*nport = htons((uint16_t)tmp_nport);
657 		} else if (r->rpool.proxy_port[0])
658 			*nport = htons(r->rpool.proxy_port[0]);
659 		break;
660 	}
661 	default:
662 		panic("%s: unknown action %u", __func__, r->action);
663 	}
664 
665 	/* Return success only if translation really happened. */
666 	if (bcmp(*skp, *nkp, sizeof(struct pf_state_key_cmp)))
667 		return (r);
668 
669 notrans:
670 	uma_zfree(V_pf_state_key_z, *nkp);
671 	uma_zfree(V_pf_state_key_z, *skp);
672 	*skp = *nkp = NULL;
673 	*sn = NULL;
674 
675 	return (NULL);
676 }
677