Home | History | Annotate | Line # | Download | only in npf
npf_nat.c revision 1.46
      1 /*-
      2  * Copyright (c) 2014-2019 Mindaugas Rasiukevicius <rmind at netbsd org>
      3  * Copyright (c) 2010-2013 The NetBSD Foundation, Inc.
      4  * All rights reserved.
      5  *
      6  * This material is based upon work partially supported by The
      7  * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     20  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     21  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     22  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     28  * POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 
     31 /*
     32  * NPF network address port translation (NAPT) and other forms of NAT.
     33  * Described in RFC 2663, RFC 3022, etc.
     34  *
     35  * Overview
     36  *
     37  *	There are a few mechanisms: NAT policy, port map and translation.
     38  *	The NAT module has a separate ruleset where rules always have an
     39  *	associated NAT policy.
     40  *
     41  * Translation types
     42  *
     43  *	There are two types of translation: outbound (NPF_NATOUT) and
     44  *	inbound (NPF_NATIN).  It should not be confused with connection
     45  *	direction.  See npf_nat_which() for the description of how the
     46  *	addresses are rewritten.  The bi-directional NAT is a combined
     47  *	outbound and inbound translation, therefore is constructed as
     48  *	two policies.
     49  *
     50  * NAT policies and port maps
     51  *
     52  *	The NAT (translation) policy is applied when packet matches the
     53  *	rule.  Apart from the filter criteria, the NAT policy always has
     54  *	a translation IP address or a table.  If port translation is set,
     55  *	then NAT mechanism relies on port map mechanism.
     56  *
     57  * Connections, translation entries and their life-cycle
     58  *
     59  *	NAT relies on the connection tracking module.  Each translated
     60  *	connection has an associated translation entry (npf_nat_t) which
     61  *	contains information used for backwards stream translation, i.e.
     62  *	the original IP address with port and translation port, allocated
     63  *	from the port map.  Each NAT entry is associated with the policy,
     64  *	which contains translation IP address.  Allocated port is returned
     65  *	to the port map and NAT entry is destroyed when connection expires.
     66  */
     67 
     68 #ifdef _KERNEL
     69 #include <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: npf_nat.c,v 1.46 2019/07/23 00:52:01 rmind Exp $");
     71 
     72 #include <sys/param.h>
     73 #include <sys/types.h>
     74 
     75 #include <sys/atomic.h>
     76 #include <sys/condvar.h>
     77 #include <sys/kmem.h>
     78 #include <sys/mutex.h>
     79 #include <sys/pool.h>
     80 #include <sys/proc.h>
     81 #endif
     82 
     83 #include "npf_impl.h"
     84 #include "npf_conn.h"
     85 
     86 /*
     87  * NAT policy structure.
     88  */
     89 struct npf_natpolicy {
     90 	npf_t *			n_npfctx;
     91 	kmutex_t		n_lock;
     92 	LIST_HEAD(, npf_nat)	n_nat_list;
     93 	volatile unsigned	n_refcnt;
     94 	uint64_t		n_id;
     95 
     96 	/*
     97 	 * Translation type, flags, address or table and the port.
     98 	 * Additionally, there may be translation algorithm and any
     99 	 * auxiliary data, e.g. NPTv6 adjustment value.
    100 	 *
    101 	 * NPF_NP_CMP_START mark starts here.
    102 	 */
    103 	unsigned		n_type;
    104 	unsigned		n_flags;
    105 	unsigned		n_alen;
    106 
    107 	npf_addr_t		n_taddr;
    108 	npf_netmask_t		n_tmask;
    109 	in_port_t		n_tport;
    110 	unsigned		n_tid;
    111 
    112 	unsigned		n_algo;
    113 	union {
    114 		unsigned	n_rr_idx;
    115 		uint16_t	n_npt66_adj;
    116 	};
    117 };
    118 
    119 /*
    120  * Private flags - must be in the NPF_NAT_PRIVMASK range.
    121  */
    122 #define	NPF_NAT_USETABLE	(0x01000000 & NPF_NAT_PRIVMASK)
    123 
    124 #define	NPF_NP_CMP_START	offsetof(npf_natpolicy_t, n_type)
    125 #define	NPF_NP_CMP_SIZE		(sizeof(npf_natpolicy_t) - NPF_NP_CMP_START)
    126 
    127 /*
    128  * NAT translation entry for a connection.
    129  */
    130 struct npf_nat {
    131 	/* Associated NAT policy. */
    132 	npf_natpolicy_t *	nt_natpolicy;
    133 
    134 	/*
    135 	 * Translation address as well as the original address which is
    136 	 * used for backwards translation.  The same for ports.
    137 	 */
    138 	npf_addr_t		nt_taddr;
    139 	npf_addr_t		nt_oaddr;
    140 
    141 	unsigned		nt_alen;
    142 	in_port_t		nt_oport;
    143 	in_port_t		nt_tport;
    144 
    145 	/* ALG (if any) associated with this NAT entry. */
    146 	npf_alg_t *		nt_alg;
    147 	uintptr_t		nt_alg_arg;
    148 
    149 	LIST_ENTRY(npf_nat)	nt_entry;
    150 	npf_conn_t *		nt_conn;
    151 };
    152 
    153 static pool_cache_t		nat_cache	__read_mostly;
    154 
    155 /*
    156  * npf_nat_sys{init,fini}: initialise/destroy NAT subsystem structures.
    157  */
    158 
    159 void
    160 npf_nat_sysinit(void)
    161 {
    162 	nat_cache = pool_cache_init(sizeof(npf_nat_t), 0,
    163 	    0, 0, "npfnatpl", NULL, IPL_NET, NULL, NULL, NULL);
    164 	KASSERT(nat_cache != NULL);
    165 }
    166 
    167 void
    168 npf_nat_sysfini(void)
    169 {
    170 	/* All NAT policies should already be destroyed. */
    171 	pool_cache_destroy(nat_cache);
    172 }
    173 
    174 /*
    175  * npf_nat_newpolicy: create a new NAT policy.
    176  */
    177 npf_natpolicy_t *
    178 npf_nat_newpolicy(npf_t *npf, const nvlist_t *nat, npf_ruleset_t *rset)
    179 {
    180 	npf_natpolicy_t *np;
    181 	const void *addr;
    182 	size_t len;
    183 
    184 	np = kmem_zalloc(sizeof(npf_natpolicy_t), KM_SLEEP);
    185 	np->n_npfctx = npf;
    186 
    187 	/* The translation type, flags and policy ID. */
    188 	np->n_type = dnvlist_get_number(nat, "type", 0);
    189 	np->n_flags = dnvlist_get_number(nat, "flags", 0) & ~NPF_NAT_PRIVMASK;
    190 	np->n_id = dnvlist_get_number(nat, "nat-policy", 0);
    191 
    192 	/* Should be exclusively either inbound or outbound NAT. */
    193 	if (((np->n_type == NPF_NATIN) ^ (np->n_type == NPF_NATOUT)) == 0) {
    194 		goto err;
    195 	}
    196 	mutex_init(&np->n_lock, MUTEX_DEFAULT, IPL_SOFTNET);
    197 	LIST_INIT(&np->n_nat_list);
    198 
    199 	/*
    200 	 * Translation IP, mask and port (if applicable).  If using the
    201 	 * the table, specified by the ID, then the nat-addr/nat-mask will
    202 	 * be used as a filter for the addresses selected from table.
    203 	 */
    204 	if (nvlist_exists_number(nat, "nat-table-id")) {
    205 		if (np->n_flags & NPF_NAT_STATIC) {
    206 			goto err;
    207 		}
    208 		np->n_tid = nvlist_get_number(nat, "nat-table-id");
    209 		np->n_tmask = NPF_NO_NETMASK;
    210 		np->n_flags |= NPF_NAT_USETABLE;
    211 	} else {
    212 		addr = dnvlist_get_binary(nat, "nat-addr", &len, NULL, 0);
    213 		if (!addr || len == 0 || len > sizeof(npf_addr_t)) {
    214 			goto err;
    215 		}
    216 		memcpy(&np->n_taddr, addr, len);
    217 		np->n_alen = len;
    218 		np->n_tmask = dnvlist_get_number(nat, "nat-mask", NPF_NO_NETMASK);
    219 		if (npf_netmask_check(np->n_alen, np->n_tmask)) {
    220 			goto err;
    221 		}
    222 	}
    223 	np->n_tport = dnvlist_get_number(nat, "nat-port", 0);
    224 
    225 	/*
    226 	 * NAT algorithm.
    227 	 */
    228 	np->n_algo = dnvlist_get_number(nat, "nat-algo", 0);
    229 	switch (np->n_algo) {
    230 	case NPF_ALGO_NPT66:
    231 		np->n_npt66_adj = dnvlist_get_number(nat, "npt66-adj", 0);
    232 		break;
    233 	case NPF_ALGO_NETMAP:
    234 		break;
    235 	case NPF_ALGO_IPHASH:
    236 	case NPF_ALGO_RR:
    237 	default:
    238 		if (np->n_tmask != NPF_NO_NETMASK) {
    239 			goto err;
    240 		}
    241 		break;
    242 	}
    243 	return np;
    244 err:
    245 	mutex_destroy(&np->n_lock);
    246 	kmem_free(np, sizeof(npf_natpolicy_t));
    247 	return NULL;
    248 }
    249 
    250 int
    251 npf_nat_policyexport(const npf_natpolicy_t *np, nvlist_t *nat)
    252 {
    253 	nvlist_add_number(nat, "nat-policy", np->n_id);
    254 	nvlist_add_number(nat, "type", np->n_type);
    255 	nvlist_add_number(nat, "flags", np->n_flags);
    256 
    257 	if (np->n_flags & NPF_NAT_USETABLE) {
    258 		nvlist_add_number(nat, "nat-table-id", np->n_tid);
    259 	} else {
    260 		nvlist_add_binary(nat, "nat-addr", &np->n_taddr, np->n_alen);
    261 		nvlist_add_number(nat, "nat-mask", np->n_tmask);
    262 	}
    263 	nvlist_add_number(nat, "nat-port", np->n_tport);
    264 	nvlist_add_number(nat, "nat-algo", np->n_algo);
    265 
    266 	switch (np->n_algo) {
    267 	case NPF_ALGO_NPT66:
    268 		nvlist_add_number(nat, "npt66-adj", np->n_npt66_adj);
    269 		break;
    270 	}
    271 	return 0;
    272 }
    273 
    274 /*
    275  * npf_nat_freepolicy: free the NAT policy.
    276  *
    277  * => Called from npf_rule_free() during the reload via npf_ruleset_destroy().
    278  */
    279 void
    280 npf_nat_freepolicy(npf_natpolicy_t *np)
    281 {
    282 	npf_conn_t *con;
    283 	npf_nat_t *nt;
    284 
    285 	/*
    286 	 * Disassociate all entries from the policy.  At this point,
    287 	 * new entries can no longer be created for this policy.
    288 	 */
    289 	while (np->n_refcnt) {
    290 		mutex_enter(&np->n_lock);
    291 		LIST_FOREACH(nt, &np->n_nat_list, nt_entry) {
    292 			con = nt->nt_conn;
    293 			KASSERT(con != NULL);
    294 			npf_conn_expire(con);
    295 		}
    296 		mutex_exit(&np->n_lock);
    297 
    298 		/* Kick the worker - all references should be going away. */
    299 		npf_worker_signal(np->n_npfctx);
    300 		kpause("npfgcnat", false, 1, NULL);
    301 	}
    302 	KASSERT(LIST_EMPTY(&np->n_nat_list));
    303 	mutex_destroy(&np->n_lock);
    304 	kmem_free(np, sizeof(npf_natpolicy_t));
    305 }
    306 
    307 void
    308 npf_nat_freealg(npf_natpolicy_t *np, npf_alg_t *alg)
    309 {
    310 	npf_nat_t *nt;
    311 
    312 	mutex_enter(&np->n_lock);
    313 	LIST_FOREACH(nt, &np->n_nat_list, nt_entry) {
    314 		if (nt->nt_alg == alg) {
    315 			nt->nt_alg = NULL;
    316 		}
    317 	}
    318 	mutex_exit(&np->n_lock);
    319 }
    320 
    321 /*
    322  * npf_nat_cmppolicy: compare two NAT policies.
    323  *
    324  * => Return 0 on match, and non-zero otherwise.
    325  */
    326 bool
    327 npf_nat_cmppolicy(npf_natpolicy_t *np, npf_natpolicy_t *mnp)
    328 {
    329 	const void *np_raw, *mnp_raw;
    330 
    331 	/*
    332 	 * Compare the relevant NAT policy information (in raw form),
    333 	 * which is enough for matching criterion.
    334 	 */
    335 	KASSERT(np && mnp && np != mnp);
    336 	np_raw = (const uint8_t *)np + NPF_NP_CMP_START;
    337 	mnp_raw = (const uint8_t *)mnp + NPF_NP_CMP_START;
    338 	return memcmp(np_raw, mnp_raw, NPF_NP_CMP_SIZE) == 0;
    339 }
    340 
    341 void
    342 npf_nat_setid(npf_natpolicy_t *np, uint64_t id)
    343 {
    344 	np->n_id = id;
    345 }
    346 
    347 uint64_t
    348 npf_nat_getid(const npf_natpolicy_t *np)
    349 {
    350 	return np->n_id;
    351 }
    352 
    353 /*
    354  * npf_nat_which: tell which address (source or destination) should be
    355  * rewritten given the combination of the NAT type and flow direction.
    356  */
    357 static inline unsigned
    358 npf_nat_which(const unsigned type, bool forw)
    359 {
    360 	/*
    361 	 * Outbound NAT rewrites:
    362 	 * - Source (NPF_SRC) on "forwards" stream.
    363 	 * - Destination (NPF_DST) on "backwards" stream.
    364 	 * Inbound NAT is other way round.
    365 	 */
    366 	if (type == NPF_NATOUT) {
    367 		forw = !forw;
    368 	} else {
    369 		KASSERT(type == NPF_NATIN);
    370 	}
    371 	CTASSERT(NPF_SRC == 0 && NPF_DST == 1);
    372 	KASSERT(forw == NPF_SRC || forw == NPF_DST);
    373 	return (unsigned)forw;
    374 }
    375 
    376 /*
    377  * npf_nat_inspect: inspect packet against NAT ruleset and return a policy.
    378  *
    379  * => Acquire a reference on the policy, if found.
    380  */
    381 static npf_natpolicy_t *
    382 npf_nat_inspect(npf_cache_t *npc, const int di)
    383 {
    384 	int slock = npf_config_read_enter();
    385 	npf_ruleset_t *rlset = npf_config_natset(npc->npc_ctx);
    386 	npf_natpolicy_t *np;
    387 	npf_rule_t *rl;
    388 
    389 	rl = npf_ruleset_inspect(npc, rlset, di, NPF_LAYER_3);
    390 	if (rl == NULL) {
    391 		npf_config_read_exit(slock);
    392 		return NULL;
    393 	}
    394 	np = npf_rule_getnat(rl);
    395 	atomic_inc_uint(&np->n_refcnt);
    396 	npf_config_read_exit(slock);
    397 	return np;
    398 }
    399 
    400 static void
    401 npf_nat_algo_netmap(const npf_cache_t *npc, const npf_natpolicy_t *np,
    402     const unsigned which, npf_addr_t *addr)
    403 {
    404 	const npf_addr_t *orig_addr = npc->npc_ips[which];
    405 
    406 	/*
    407 	 * NETMAP:
    408 	 *
    409 	 *	addr = net-addr | (orig-addr & ~mask)
    410 	 */
    411 	npf_addr_mask(&np->n_taddr, np->n_tmask, npc->npc_alen, addr);
    412 	npf_addr_bitor(orig_addr, np->n_tmask, npc->npc_alen, addr);
    413 }
    414 
    415 static inline npf_addr_t *
    416 npf_nat_getaddr(npf_cache_t *npc, npf_natpolicy_t *np, const unsigned alen)
    417 {
    418 	npf_tableset_t *ts = npf_config_tableset(np->n_npfctx);
    419 	npf_table_t *t = npf_tableset_getbyid(ts, np->n_tid);
    420 	unsigned idx;
    421 
    422 	/*
    423 	 * Dynamically select the translation IP address.
    424 	 */
    425 	switch (np->n_algo) {
    426 	case NPF_ALGO_RR:
    427 		idx = atomic_inc_uint_nv(&np->n_rr_idx);
    428 		break;
    429 	case NPF_ALGO_IPHASH:
    430 	default:
    431 		idx = npf_addr_mix(alen,
    432 		    npc->npc_ips[NPF_SRC],
    433 		    npc->npc_ips[NPF_DST]);
    434 		break;
    435 	}
    436 	return npf_table_getsome(t, alen, idx);
    437 }
    438 
    439 /*
    440  * npf_nat_create: create a new NAT translation entry.
    441  */
    442 static npf_nat_t *
    443 npf_nat_create(npf_cache_t *npc, npf_natpolicy_t *np, npf_conn_t *con)
    444 {
    445 	const int proto = npc->npc_proto;
    446 	const unsigned alen = npc->npc_alen;
    447 	npf_addr_t *taddr;
    448 	npf_nat_t *nt;
    449 
    450 	KASSERT(npf_iscached(npc, NPC_IP46));
    451 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    452 
    453 	/* Construct a new NAT entry and associate it with the connection. */
    454 	nt = pool_cache_get(nat_cache, PR_NOWAIT);
    455 	if (__predict_false(!nt)) {
    456 		return NULL;
    457 	}
    458 	npf_stats_inc(npc->npc_ctx, NPF_STAT_NAT_CREATE);
    459 	nt->nt_natpolicy = np;
    460 	nt->nt_conn = con;
    461 	nt->nt_alg = NULL;
    462 
    463 	/*
    464 	 * Select the translation address.
    465 	 */
    466 	if (np->n_flags & NPF_NAT_USETABLE) {
    467 		taddr = npf_nat_getaddr(npc, np, alen);
    468 		if (__predict_false(!taddr)) {
    469 			pool_cache_put(nat_cache, nt);
    470 			return NULL;
    471 		}
    472 		memcpy(&nt->nt_taddr, taddr, alen);
    473 	} else if (np->n_algo == NPF_ALGO_NETMAP) {
    474 		const unsigned which = npf_nat_which(np->n_type, true);
    475 		npf_nat_algo_netmap(npc, np, which, &nt->nt_taddr);
    476 		taddr = &nt->nt_taddr;
    477 	} else {
    478 		/* Static IP address. */
    479 		taddr = &np->n_taddr;
    480 		memcpy(&nt->nt_taddr, taddr, alen);
    481 	}
    482 	nt->nt_alen = alen;
    483 
    484 	/* Save the original address which may be rewritten. */
    485 	if (np->n_type == NPF_NATOUT) {
    486 		/* Outbound NAT: source (think internal) address. */
    487 		memcpy(&nt->nt_oaddr, npc->npc_ips[NPF_SRC], alen);
    488 	} else {
    489 		/* Inbound NAT: destination (think external) address. */
    490 		KASSERT(np->n_type == NPF_NATIN);
    491 		memcpy(&nt->nt_oaddr, npc->npc_ips[NPF_DST], alen);
    492 	}
    493 
    494 	/*
    495 	 * Port translation, if required, and if it is TCP/UDP.
    496 	 */
    497 	if ((np->n_flags & NPF_NAT_PORTS) == 0 ||
    498 	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
    499 		nt->nt_oport = 0;
    500 		nt->nt_tport = 0;
    501 		goto out;
    502 	}
    503 
    504 	/* Save the relevant TCP/UDP port. */
    505 	if (proto == IPPROTO_TCP) {
    506 		const struct tcphdr *th = npc->npc_l4.tcp;
    507 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    508 		    th->th_sport : th->th_dport;
    509 	} else {
    510 		const struct udphdr *uh = npc->npc_l4.udp;
    511 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    512 		    uh->uh_sport : uh->uh_dport;
    513 	}
    514 
    515 	/* Get a new port for translation. */
    516 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0) {
    517 		nt->nt_tport = npf_portmap_get(np->n_npfctx, alen, taddr);
    518 	} else {
    519 		nt->nt_tport = np->n_tport;
    520 	}
    521 out:
    522 	mutex_enter(&np->n_lock);
    523 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    524 	mutex_exit(&np->n_lock);
    525 	return nt;
    526 }
    527 
    528 /*
    529  * npf_nat_translate: perform translation given the state data.
    530  */
    531 static inline int
    532 npf_nat_translate(npf_cache_t *npc, npf_nat_t *nt, bool forw)
    533 {
    534 	const npf_natpolicy_t *np = nt->nt_natpolicy;
    535 	const unsigned which = npf_nat_which(np->n_type, forw);
    536 	const npf_addr_t *addr;
    537 	in_port_t port;
    538 
    539 	KASSERT(npf_iscached(npc, NPC_IP46));
    540 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    541 
    542 	if (forw) {
    543 		/* "Forwards" stream: use translation address/port. */
    544 		addr = &nt->nt_taddr;
    545 		port = nt->nt_tport;
    546 	} else {
    547 		/* "Backwards" stream: use original address/port. */
    548 		addr = &nt->nt_oaddr;
    549 		port = nt->nt_oport;
    550 	}
    551 	KASSERT((np->n_flags & NPF_NAT_PORTS) != 0 || port == 0);
    552 
    553 	/* Execute ALG translation first. */
    554 	if ((npc->npc_info & NPC_ALG_EXEC) == 0) {
    555 		npc->npc_info |= NPC_ALG_EXEC;
    556 		npf_alg_exec(npc, nt, forw);
    557 		npf_recache(npc);
    558 	}
    559 	KASSERT(!nbuf_flag_p(npc->npc_nbuf, NBUF_DATAREF_RESET));
    560 
    561 	/* Finally, perform the translation. */
    562 	return npf_napt_rwr(npc, which, addr, port);
    563 }
    564 
    565 /*
    566  * npf_nat_algo: perform the translation given the algorithm.
    567  */
    568 static inline int
    569 npf_nat_algo(npf_cache_t *npc, const npf_natpolicy_t *np, bool forw)
    570 {
    571 	const unsigned which = npf_nat_which(np->n_type, forw);
    572 	const npf_addr_t *taddr;
    573 	npf_addr_t addr;
    574 
    575 	KASSERT(np->n_flags & NPF_NAT_STATIC);
    576 
    577 	switch (np->n_algo) {
    578 	case NPF_ALGO_NETMAP:
    579 		npf_nat_algo_netmap(npc, np, which, &addr);
    580 		taddr = &addr;
    581 		break;
    582 	case NPF_ALGO_NPT66:
    583 		return npf_npt66_rwr(npc, which, &np->n_taddr,
    584 		    np->n_tmask, np->n_npt66_adj);
    585 	default:
    586 		taddr = &np->n_taddr;
    587 		break;
    588 	}
    589 	return npf_napt_rwr(npc, which, taddr, np->n_tport);
    590 }
    591 
    592 /*
    593  * npf_do_nat:
    594  *
    595  *	- Inspect packet for a NAT policy, unless a connection with a NAT
    596  *	  association already exists.  In such case, determine whether it
    597  *	  is a "forwards" or "backwards" stream.
    598  *	- Perform translation: rewrite source or destination fields,
    599  *	  depending on translation type and direction.
    600  *	- Associate a NAT policy with a connection (may establish a new).
    601  */
    602 int
    603 npf_do_nat(npf_cache_t *npc, npf_conn_t *con, const int di)
    604 {
    605 	nbuf_t *nbuf = npc->npc_nbuf;
    606 	npf_conn_t *ncon = NULL;
    607 	npf_natpolicy_t *np;
    608 	npf_nat_t *nt;
    609 	int error;
    610 	bool forw;
    611 
    612 	/* All relevant data should be already cached. */
    613 	if (!npf_iscached(npc, NPC_IP46) || !npf_iscached(npc, NPC_LAYER4)) {
    614 		return 0;
    615 	}
    616 	KASSERT(!nbuf_flag_p(nbuf, NBUF_DATAREF_RESET));
    617 
    618 	/*
    619 	 * Return the NAT entry associated with the connection, if any.
    620 	 * Determines whether the stream is "forwards" or "backwards".
    621 	 * Note: no need to lock, since reference on connection is held.
    622 	 */
    623 	if (con && (nt = npf_conn_getnat(con, di, &forw)) != NULL) {
    624 		np = nt->nt_natpolicy;
    625 		goto translate;
    626 	}
    627 
    628 	/*
    629 	 * Inspect the packet for a NAT policy, if there is no connection.
    630 	 * Note: acquires a reference if found.
    631 	 */
    632 	np = npf_nat_inspect(npc, di);
    633 	if (np == NULL) {
    634 		/* If packet does not match - done. */
    635 		return 0;
    636 	}
    637 	forw = true;
    638 
    639 	/* Static NAT - just perform the translation. */
    640 	if (np->n_flags & NPF_NAT_STATIC) {
    641 		if (nbuf_cksum_barrier(nbuf, di)) {
    642 			npf_recache(npc);
    643 		}
    644 		error = npf_nat_algo(npc, np, forw);
    645 		atomic_dec_uint(&np->n_refcnt);
    646 		return error;
    647 	}
    648 
    649 	/*
    650 	 * If there is no local connection (no "stateful" rule - unusual,
    651 	 * but possible configuration), establish one before translation.
    652 	 * Note that it is not a "pass" connection, therefore passing of
    653 	 * "backwards" stream depends on other, stateless filtering rules.
    654 	 */
    655 	if (con == NULL) {
    656 		ncon = npf_conn_establish(npc, di, true);
    657 		if (ncon == NULL) {
    658 			atomic_dec_uint(&np->n_refcnt);
    659 			return ENOMEM;
    660 		}
    661 		con = ncon;
    662 	}
    663 
    664 	/*
    665 	 * Create a new NAT entry and associate with the connection.
    666 	 * We will consume the reference on success (release on error).
    667 	 */
    668 	nt = npf_nat_create(npc, np, con);
    669 	if (nt == NULL) {
    670 		atomic_dec_uint(&np->n_refcnt);
    671 		error = ENOMEM;
    672 		goto out;
    673 	}
    674 
    675 	/* Associate the NAT translation entry with the connection. */
    676 	error = npf_conn_setnat(npc, con, nt, np->n_type);
    677 	if (error) {
    678 		/* Will release the reference. */
    679 		npf_nat_destroy(nt);
    680 		goto out;
    681 	}
    682 
    683 	/* Determine whether any ALG matches. */
    684 	if (npf_alg_match(npc, nt, di)) {
    685 		KASSERT(nt->nt_alg != NULL);
    686 	}
    687 
    688 translate:
    689 	/* May need to process the delayed checksums first (XXX: NetBSD). */
    690 	if (nbuf_cksum_barrier(nbuf, di)) {
    691 		npf_recache(npc);
    692 	}
    693 
    694 	/* Perform the translation. */
    695 	error = npf_nat_translate(npc, nt, forw);
    696 out:
    697 	if (__predict_false(ncon)) {
    698 		if (error) {
    699 			/* It created for NAT - just expire. */
    700 			npf_conn_expire(ncon);
    701 		}
    702 		npf_conn_release(ncon);
    703 	}
    704 	return error;
    705 }
    706 
    707 /*
    708  * npf_nat_gettrans: return translation IP address and port.
    709  */
    710 void
    711 npf_nat_gettrans(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    712 {
    713 	*addr = &nt->nt_taddr;
    714 	*port = nt->nt_tport;
    715 }
    716 
    717 /*
    718  * npf_nat_getorig: return original IP address and port from translation entry.
    719  */
    720 void
    721 npf_nat_getorig(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    722 {
    723 	*addr = &nt->nt_oaddr;
    724 	*port = nt->nt_oport;
    725 }
    726 
    727 /*
    728  * npf_nat_setalg: associate an ALG with the NAT entry.
    729  */
    730 void
    731 npf_nat_setalg(npf_nat_t *nt, npf_alg_t *alg, uintptr_t arg)
    732 {
    733 	nt->nt_alg = alg;
    734 	nt->nt_alg_arg = arg;
    735 }
    736 
    737 /*
    738  * npf_nat_destroy: destroy NAT structure (performed on connection expiration).
    739  */
    740 void
    741 npf_nat_destroy(npf_nat_t *nt)
    742 {
    743 	npf_natpolicy_t *np = nt->nt_natpolicy;
    744 	npf_t *npf = np->n_npfctx;
    745 
    746 	/* Return taken port to the portmap. */
    747 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport) {
    748 		npf_portmap_put(npf, nt->nt_alen, &nt->nt_taddr, nt->nt_tport);
    749 	}
    750 	npf_stats_inc(np->n_npfctx, NPF_STAT_NAT_DESTROY);
    751 
    752 	mutex_enter(&np->n_lock);
    753 	LIST_REMOVE(nt, nt_entry);
    754 	KASSERT(np->n_refcnt > 0);
    755 	atomic_dec_uint(&np->n_refcnt);
    756 	mutex_exit(&np->n_lock);
    757 	pool_cache_put(nat_cache, nt);
    758 }
    759 
    760 /*
    761  * npf_nat_export: serialise the NAT entry with a NAT policy ID.
    762  */
    763 void
    764 npf_nat_export(nvlist_t *condict, npf_nat_t *nt)
    765 {
    766 	npf_natpolicy_t *np = nt->nt_natpolicy;
    767 	nvlist_t *nat;
    768 
    769 	nat = nvlist_create(0);
    770 	nvlist_add_binary(nat, "oaddr", &nt->nt_oaddr, sizeof(npf_addr_t));
    771 	nvlist_add_number(nat, "oport", nt->nt_oport);
    772 	nvlist_add_number(nat, "tport", nt->nt_tport);
    773 	nvlist_add_number(nat, "nat-policy", np->n_id);
    774 	nvlist_move_nvlist(condict, "nat", nat);
    775 }
    776 
    777 /*
    778  * npf_nat_import: find the NAT policy and unserialise the NAT entry.
    779  */
    780 npf_nat_t *
    781 npf_nat_import(npf_t *npf, const nvlist_t *nat,
    782     npf_ruleset_t *natlist, npf_conn_t *con)
    783 {
    784 	npf_natpolicy_t *np;
    785 	npf_nat_t *nt;
    786 	const void *oaddr;
    787 	uint64_t np_id;
    788 	size_t len;
    789 
    790 	np_id = dnvlist_get_number(nat, "nat-policy", UINT64_MAX);
    791 	if ((np = npf_ruleset_findnat(natlist, np_id)) == NULL) {
    792 		return NULL;
    793 	}
    794 	nt = pool_cache_get(nat_cache, PR_WAITOK);
    795 	memset(nt, 0, sizeof(npf_nat_t));
    796 
    797 	oaddr = dnvlist_get_binary(nat, "oaddr", &len, NULL, 0);
    798 	if (!oaddr || len != sizeof(npf_addr_t)) {
    799 		pool_cache_put(nat_cache, nt);
    800 		return NULL;
    801 	}
    802 	memcpy(&nt->nt_oaddr, oaddr, sizeof(npf_addr_t));
    803 	nt->nt_oport = dnvlist_get_number(nat, "oport", 0);
    804 	nt->nt_tport = dnvlist_get_number(nat, "tport", 0);
    805 
    806 	/* Take a specific port from port-map. */
    807 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport &&
    808 	    !npf_portmap_take(npf, nt->nt_alen, &nt->nt_taddr, nt->nt_tport)) {
    809 		pool_cache_put(nat_cache, nt);
    810 		return NULL;
    811 	}
    812 	npf_stats_inc(npf, NPF_STAT_NAT_CREATE);
    813 
    814 	/*
    815 	 * Associate, take a reference and insert.  Unlocked since
    816 	 * the policy is not yet visible.
    817 	 */
    818 	nt->nt_natpolicy = np;
    819 	nt->nt_conn = con;
    820 	np->n_refcnt++;
    821 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    822 	return nt;
    823 }
    824 
    825 #if defined(DDB) || defined(_NPF_TESTING)
    826 
    827 void
    828 npf_nat_dump(const npf_nat_t *nt)
    829 {
    830 	const npf_natpolicy_t *np;
    831 	struct in_addr ip;
    832 
    833 	np = nt->nt_natpolicy;
    834 	memcpy(&ip, &nt->nt_taddr, sizeof(ip));
    835 	printf("\tNATP(%p): type %u flags 0x%x taddr %s tport %d\n", np,
    836 	    np->n_type, np->n_flags, inet_ntoa(ip), ntohs(np->n_tport));
    837 	memcpy(&ip, &nt->nt_oaddr, sizeof(ip));
    838 	printf("\tNAT: original address %s oport %d tport %d\n",
    839 	    inet_ntoa(ip), ntohs(nt->nt_oport), ntohs(nt->nt_tport));
    840 	if (nt->nt_alg) {
    841 		printf("\tNAT ALG = %p, ARG = %p\n",
    842 		    nt->nt_alg, (void *)nt->nt_alg_arg);
    843 	}
    844 }
    845 
    846 #endif
    847