Home | History | Annotate | Line # | Download | only in npf
npf_nat.c revision 1.49
      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.49 2020/05/23 19:56:00 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 	atomic_store_relaxed(&np->n_refcnt, 1);
    186 	np->n_npfctx = npf;
    187 
    188 	/* The translation type, flags and policy ID. */
    189 	np->n_type = dnvlist_get_number(nat, "type", 0);
    190 	np->n_flags = dnvlist_get_number(nat, "flags", 0) & ~NPF_NAT_PRIVMASK;
    191 	np->n_id = dnvlist_get_number(nat, "nat-policy", 0);
    192 
    193 	/* Should be exclusively either inbound or outbound NAT. */
    194 	if (((np->n_type == NPF_NATIN) ^ (np->n_type == NPF_NATOUT)) == 0) {
    195 		goto err;
    196 	}
    197 	mutex_init(&np->n_lock, MUTEX_DEFAULT, IPL_SOFTNET);
    198 	LIST_INIT(&np->n_nat_list);
    199 
    200 	/*
    201 	 * Translation IP, mask and port (if applicable).  If using the
    202 	 * the table, specified by the ID, then the nat-addr/nat-mask will
    203 	 * be used as a filter for the addresses selected from table.
    204 	 */
    205 	if (nvlist_exists_number(nat, "nat-table-id")) {
    206 		if (np->n_flags & NPF_NAT_STATIC) {
    207 			goto err;
    208 		}
    209 		np->n_tid = nvlist_get_number(nat, "nat-table-id");
    210 		np->n_tmask = NPF_NO_NETMASK;
    211 		np->n_flags |= NPF_NAT_USETABLE;
    212 	} else {
    213 		addr = dnvlist_get_binary(nat, "nat-addr", &len, NULL, 0);
    214 		if (!addr || len == 0 || len > sizeof(npf_addr_t)) {
    215 			goto err;
    216 		}
    217 		memcpy(&np->n_taddr, addr, len);
    218 		np->n_alen = len;
    219 		np->n_tmask = dnvlist_get_number(nat, "nat-mask", NPF_NO_NETMASK);
    220 		if (npf_netmask_check(np->n_alen, np->n_tmask)) {
    221 			goto err;
    222 		}
    223 	}
    224 	np->n_tport = dnvlist_get_number(nat, "nat-port", 0);
    225 
    226 	/*
    227 	 * NAT algorithm.
    228 	 */
    229 	np->n_algo = dnvlist_get_number(nat, "nat-algo", 0);
    230 	switch (np->n_algo) {
    231 	case NPF_ALGO_NPT66:
    232 		np->n_npt66_adj = dnvlist_get_number(nat, "npt66-adj", 0);
    233 		break;
    234 	case NPF_ALGO_NETMAP:
    235 		break;
    236 	case NPF_ALGO_IPHASH:
    237 	case NPF_ALGO_RR:
    238 	default:
    239 		if (np->n_tmask != NPF_NO_NETMASK) {
    240 			goto err;
    241 		}
    242 		break;
    243 	}
    244 	return np;
    245 err:
    246 	mutex_destroy(&np->n_lock);
    247 	kmem_free(np, sizeof(npf_natpolicy_t));
    248 	return NULL;
    249 }
    250 
    251 int
    252 npf_nat_policyexport(const npf_natpolicy_t *np, nvlist_t *nat)
    253 {
    254 	nvlist_add_number(nat, "nat-policy", np->n_id);
    255 	nvlist_add_number(nat, "type", np->n_type);
    256 	nvlist_add_number(nat, "flags", np->n_flags);
    257 
    258 	if (np->n_flags & NPF_NAT_USETABLE) {
    259 		nvlist_add_number(nat, "nat-table-id", np->n_tid);
    260 	} else {
    261 		nvlist_add_binary(nat, "nat-addr", &np->n_taddr, np->n_alen);
    262 		nvlist_add_number(nat, "nat-mask", np->n_tmask);
    263 	}
    264 	nvlist_add_number(nat, "nat-port", np->n_tport);
    265 	nvlist_add_number(nat, "nat-algo", np->n_algo);
    266 
    267 	switch (np->n_algo) {
    268 	case NPF_ALGO_NPT66:
    269 		nvlist_add_number(nat, "npt66-adj", np->n_npt66_adj);
    270 		break;
    271 	}
    272 	return 0;
    273 }
    274 
    275 static void
    276 npf_natpolicy_release(npf_natpolicy_t *np)
    277 {
    278 	KASSERT(atomic_load_relaxed(&np->n_refcnt) > 0);
    279 
    280 	if (atomic_dec_uint_nv(&np->n_refcnt) != 0) {
    281 		return;
    282 	}
    283 	KASSERT(LIST_EMPTY(&np->n_nat_list));
    284 	mutex_destroy(&np->n_lock);
    285 	kmem_free(np, sizeof(npf_natpolicy_t));
    286 }
    287 
    288 /*
    289  * npf_nat_freepolicy: free the NAT policy.
    290  *
    291  * => Called from npf_rule_free() during the reload via npf_ruleset_destroy().
    292  * => At this point, NAT policy cannot acquire new references.
    293  */
    294 void
    295 npf_nat_freepolicy(npf_natpolicy_t *np)
    296 {
    297 	/*
    298 	 * Drain the references.  If there are active NAT connections,
    299 	 * then expire them and kick the worker.
    300 	 */
    301 	if (atomic_load_relaxed(&np->n_refcnt) > 1) {
    302 		npf_nat_t *nt;
    303 
    304 		mutex_enter(&np->n_lock);
    305 		LIST_FOREACH(nt, &np->n_nat_list, nt_entry) {
    306 			npf_conn_t *con = nt->nt_conn;
    307 			KASSERT(con != NULL);
    308 			npf_conn_expire(con);
    309 		}
    310 		mutex_exit(&np->n_lock);
    311 		npf_worker_signal(np->n_npfctx);
    312 	}
    313 	KASSERT(atomic_load_relaxed(&np->n_refcnt) >= 1);
    314 
    315 	/*
    316 	 * Drop the initial reference, but it might not be the last one.
    317 	 * If so, the last reference will be triggered via:
    318 	 *
    319 	 * npf_conn_destroy() -> npf_nat_destroy() -> npf_natpolicy_release()
    320 	 */
    321 	npf_natpolicy_release(np);
    322 }
    323 
    324 void
    325 npf_nat_freealg(npf_natpolicy_t *np, npf_alg_t *alg)
    326 {
    327 	npf_nat_t *nt;
    328 
    329 	mutex_enter(&np->n_lock);
    330 	LIST_FOREACH(nt, &np->n_nat_list, nt_entry) {
    331 		if (nt->nt_alg == alg) {
    332 			nt->nt_alg = NULL;
    333 		}
    334 	}
    335 	mutex_exit(&np->n_lock);
    336 }
    337 
    338 /*
    339  * npf_nat_cmppolicy: compare two NAT policies.
    340  *
    341  * => Return 0 on match, and non-zero otherwise.
    342  */
    343 bool
    344 npf_nat_cmppolicy(npf_natpolicy_t *np, npf_natpolicy_t *mnp)
    345 {
    346 	const void *np_raw, *mnp_raw;
    347 
    348 	/*
    349 	 * Compare the relevant NAT policy information (in raw form),
    350 	 * which is enough for matching criterion.
    351 	 */
    352 	KASSERT(np && mnp && np != mnp);
    353 	np_raw = (const uint8_t *)np + NPF_NP_CMP_START;
    354 	mnp_raw = (const uint8_t *)mnp + NPF_NP_CMP_START;
    355 	return memcmp(np_raw, mnp_raw, NPF_NP_CMP_SIZE) == 0;
    356 }
    357 
    358 void
    359 npf_nat_setid(npf_natpolicy_t *np, uint64_t id)
    360 {
    361 	np->n_id = id;
    362 }
    363 
    364 uint64_t
    365 npf_nat_getid(const npf_natpolicy_t *np)
    366 {
    367 	return np->n_id;
    368 }
    369 
    370 /*
    371  * npf_nat_which: tell which address (source or destination) should be
    372  * rewritten given the combination of the NAT type and flow direction.
    373  */
    374 static inline unsigned
    375 npf_nat_which(const unsigned type, bool forw)
    376 {
    377 	/*
    378 	 * Outbound NAT rewrites:
    379 	 * - Source (NPF_SRC) on "forwards" stream.
    380 	 * - Destination (NPF_DST) on "backwards" stream.
    381 	 * Inbound NAT is other way round.
    382 	 */
    383 	if (type == NPF_NATOUT) {
    384 		forw = !forw;
    385 	} else {
    386 		KASSERT(type == NPF_NATIN);
    387 	}
    388 	CTASSERT(NPF_SRC == 0 && NPF_DST == 1);
    389 	KASSERT(forw == NPF_SRC || forw == NPF_DST);
    390 	return (unsigned)forw;
    391 }
    392 
    393 /*
    394  * npf_nat_inspect: inspect packet against NAT ruleset and return a policy.
    395  *
    396  * => Acquire a reference on the policy, if found.
    397  */
    398 static npf_natpolicy_t *
    399 npf_nat_inspect(npf_cache_t *npc, const int di)
    400 {
    401 	npf_t *npf = npc->npc_ctx;
    402 	int slock = npf_config_read_enter(npf);
    403 	npf_ruleset_t *rlset = npf_config_natset(npf);
    404 	npf_natpolicy_t *np;
    405 	npf_rule_t *rl;
    406 
    407 	rl = npf_ruleset_inspect(npc, rlset, di, NPF_LAYER_3);
    408 	if (rl == NULL) {
    409 		npf_config_read_exit(npf, slock);
    410 		return NULL;
    411 	}
    412 	np = npf_rule_getnat(rl);
    413 	atomic_inc_uint(&np->n_refcnt);
    414 	npf_config_read_exit(npf, slock);
    415 	return np;
    416 }
    417 
    418 static void
    419 npf_nat_algo_netmap(const npf_cache_t *npc, const npf_natpolicy_t *np,
    420     const unsigned which, npf_addr_t *addr)
    421 {
    422 	const npf_addr_t *orig_addr = npc->npc_ips[which];
    423 
    424 	/*
    425 	 * NETMAP:
    426 	 *
    427 	 *	addr = net-addr | (orig-addr & ~mask)
    428 	 */
    429 	npf_addr_mask(&np->n_taddr, np->n_tmask, npc->npc_alen, addr);
    430 	npf_addr_bitor(orig_addr, np->n_tmask, npc->npc_alen, addr);
    431 }
    432 
    433 static inline npf_addr_t *
    434 npf_nat_getaddr(npf_cache_t *npc, npf_natpolicy_t *np, const unsigned alen)
    435 {
    436 	npf_tableset_t *ts = npf_config_tableset(np->n_npfctx);
    437 	npf_table_t *t = npf_tableset_getbyid(ts, np->n_tid);
    438 	unsigned idx;
    439 
    440 	/*
    441 	 * Dynamically select the translation IP address.
    442 	 */
    443 	switch (np->n_algo) {
    444 	case NPF_ALGO_RR:
    445 		idx = atomic_inc_uint_nv(&np->n_rr_idx);
    446 		break;
    447 	case NPF_ALGO_IPHASH:
    448 	default:
    449 		idx = npf_addr_mix(alen,
    450 		    npc->npc_ips[NPF_SRC],
    451 		    npc->npc_ips[NPF_DST]);
    452 		break;
    453 	}
    454 	return npf_table_getsome(t, alen, idx);
    455 }
    456 
    457 /*
    458  * npf_nat_create: create a new NAT translation entry.
    459  */
    460 static npf_nat_t *
    461 npf_nat_create(npf_cache_t *npc, npf_natpolicy_t *np, npf_conn_t *con)
    462 {
    463 	const int proto = npc->npc_proto;
    464 	const unsigned alen = npc->npc_alen;
    465 	npf_t *npf = npc->npc_ctx;
    466 	npf_addr_t *taddr;
    467 	npf_nat_t *nt;
    468 
    469 	KASSERT(npf_iscached(npc, NPC_IP46));
    470 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    471 
    472 	/* Construct a new NAT entry and associate it with the connection. */
    473 	nt = pool_cache_get(nat_cache, PR_NOWAIT);
    474 	if (__predict_false(!nt)) {
    475 		return NULL;
    476 	}
    477 	npf_stats_inc(npf, NPF_STAT_NAT_CREATE);
    478 	nt->nt_natpolicy = np;
    479 	nt->nt_conn = con;
    480 	nt->nt_alg = NULL;
    481 
    482 	/*
    483 	 * Select the translation address.
    484 	 */
    485 	if (np->n_flags & NPF_NAT_USETABLE) {
    486 		int slock = npf_config_read_enter(npf);
    487 		taddr = npf_nat_getaddr(npc, np, alen);
    488 		if (__predict_false(!taddr)) {
    489 			npf_config_read_exit(npf, slock);
    490 			pool_cache_put(nat_cache, nt);
    491 			return NULL;
    492 		}
    493 		memcpy(&nt->nt_taddr, taddr, alen);
    494 		npf_config_read_exit(npf, slock);
    495 
    496 	} else if (np->n_algo == NPF_ALGO_NETMAP) {
    497 		const unsigned which = npf_nat_which(np->n_type, true);
    498 		npf_nat_algo_netmap(npc, np, which, &nt->nt_taddr);
    499 		taddr = &nt->nt_taddr;
    500 	} else {
    501 		/* Static IP address. */
    502 		taddr = &np->n_taddr;
    503 		memcpy(&nt->nt_taddr, taddr, alen);
    504 	}
    505 	nt->nt_alen = alen;
    506 
    507 	/* Save the original address which may be rewritten. */
    508 	if (np->n_type == NPF_NATOUT) {
    509 		/* Outbound NAT: source (think internal) address. */
    510 		memcpy(&nt->nt_oaddr, npc->npc_ips[NPF_SRC], alen);
    511 	} else {
    512 		/* Inbound NAT: destination (think external) address. */
    513 		KASSERT(np->n_type == NPF_NATIN);
    514 		memcpy(&nt->nt_oaddr, npc->npc_ips[NPF_DST], alen);
    515 	}
    516 
    517 	/*
    518 	 * Port translation, if required, and if it is TCP/UDP.
    519 	 */
    520 	if ((np->n_flags & NPF_NAT_PORTS) == 0 ||
    521 	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
    522 		nt->nt_oport = 0;
    523 		nt->nt_tport = 0;
    524 		goto out;
    525 	}
    526 
    527 	/* Save the relevant TCP/UDP port. */
    528 	if (proto == IPPROTO_TCP) {
    529 		const struct tcphdr *th = npc->npc_l4.tcp;
    530 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    531 		    th->th_sport : th->th_dport;
    532 	} else {
    533 		const struct udphdr *uh = npc->npc_l4.udp;
    534 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    535 		    uh->uh_sport : uh->uh_dport;
    536 	}
    537 
    538 	/* Get a new port for translation. */
    539 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0) {
    540 		npf_portmap_t *pm = np->n_npfctx->portmap;
    541 		nt->nt_tport = npf_portmap_get(pm, alen, taddr);
    542 	} else {
    543 		nt->nt_tport = np->n_tport;
    544 	}
    545 out:
    546 	mutex_enter(&np->n_lock);
    547 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    548 	mutex_exit(&np->n_lock);
    549 	return nt;
    550 }
    551 
    552 /*
    553  * npf_nat_translate: perform translation given the state data.
    554  */
    555 static inline int
    556 npf_nat_translate(npf_cache_t *npc, npf_nat_t *nt, bool forw)
    557 {
    558 	const npf_natpolicy_t *np = nt->nt_natpolicy;
    559 	const unsigned which = npf_nat_which(np->n_type, forw);
    560 	const npf_addr_t *addr;
    561 	in_port_t port;
    562 
    563 	KASSERT(npf_iscached(npc, NPC_IP46));
    564 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    565 
    566 	if (forw) {
    567 		/* "Forwards" stream: use translation address/port. */
    568 		addr = &nt->nt_taddr;
    569 		port = nt->nt_tport;
    570 	} else {
    571 		/* "Backwards" stream: use original address/port. */
    572 		addr = &nt->nt_oaddr;
    573 		port = nt->nt_oport;
    574 	}
    575 	KASSERT((np->n_flags & NPF_NAT_PORTS) != 0 || port == 0);
    576 
    577 	/* Execute ALG translation first. */
    578 	if ((npc->npc_info & NPC_ALG_EXEC) == 0) {
    579 		npc->npc_info |= NPC_ALG_EXEC;
    580 		npf_alg_exec(npc, nt, forw);
    581 		npf_recache(npc);
    582 	}
    583 	KASSERT(!nbuf_flag_p(npc->npc_nbuf, NBUF_DATAREF_RESET));
    584 
    585 	/* Finally, perform the translation. */
    586 	return npf_napt_rwr(npc, which, addr, port);
    587 }
    588 
    589 /*
    590  * npf_nat_algo: perform the translation given the algorithm.
    591  */
    592 static inline int
    593 npf_nat_algo(npf_cache_t *npc, const npf_natpolicy_t *np, bool forw)
    594 {
    595 	const unsigned which = npf_nat_which(np->n_type, forw);
    596 	const npf_addr_t *taddr;
    597 	npf_addr_t addr;
    598 
    599 	KASSERT(np->n_flags & NPF_NAT_STATIC);
    600 
    601 	switch (np->n_algo) {
    602 	case NPF_ALGO_NETMAP:
    603 		npf_nat_algo_netmap(npc, np, which, &addr);
    604 		taddr = &addr;
    605 		break;
    606 	case NPF_ALGO_NPT66:
    607 		return npf_npt66_rwr(npc, which, &np->n_taddr,
    608 		    np->n_tmask, np->n_npt66_adj);
    609 	default:
    610 		taddr = &np->n_taddr;
    611 		break;
    612 	}
    613 	return npf_napt_rwr(npc, which, taddr, np->n_tport);
    614 }
    615 
    616 /*
    617  * npf_do_nat:
    618  *
    619  *	- Inspect packet for a NAT policy, unless a connection with a NAT
    620  *	  association already exists.  In such case, determine whether it
    621  *	  is a "forwards" or "backwards" stream.
    622  *	- Perform translation: rewrite source or destination fields,
    623  *	  depending on translation type and direction.
    624  *	- Associate a NAT policy with a connection (may establish a new).
    625  */
    626 int
    627 npf_do_nat(npf_cache_t *npc, npf_conn_t *con, const int di)
    628 {
    629 	nbuf_t *nbuf = npc->npc_nbuf;
    630 	npf_conn_t *ncon = NULL;
    631 	npf_natpolicy_t *np;
    632 	npf_nat_t *nt;
    633 	int error;
    634 	bool forw;
    635 
    636 	/* All relevant data should be already cached. */
    637 	if (!npf_iscached(npc, NPC_IP46) || !npf_iscached(npc, NPC_LAYER4)) {
    638 		return 0;
    639 	}
    640 	KASSERT(!nbuf_flag_p(nbuf, NBUF_DATAREF_RESET));
    641 
    642 	/*
    643 	 * Return the NAT entry associated with the connection, if any.
    644 	 * Determines whether the stream is "forwards" or "backwards".
    645 	 * Note: no need to lock, since reference on connection is held.
    646 	 */
    647 	if (con && (nt = npf_conn_getnat(con, di, &forw)) != NULL) {
    648 		np = nt->nt_natpolicy;
    649 		goto translate;
    650 	}
    651 
    652 	/*
    653 	 * Inspect the packet for a NAT policy, if there is no connection.
    654 	 * Note: acquires a reference if found.
    655 	 */
    656 	np = npf_nat_inspect(npc, di);
    657 	if (np == NULL) {
    658 		/* If packet does not match - done. */
    659 		return 0;
    660 	}
    661 	forw = true;
    662 
    663 	/* Static NAT - just perform the translation. */
    664 	if (np->n_flags & NPF_NAT_STATIC) {
    665 		if (nbuf_cksum_barrier(nbuf, di)) {
    666 			npf_recache(npc);
    667 		}
    668 		error = npf_nat_algo(npc, np, forw);
    669 		npf_natpolicy_release(np);
    670 		return error;
    671 	}
    672 
    673 	/*
    674 	 * If there is no local connection (no "stateful" rule - unusual,
    675 	 * but possible configuration), establish one before translation.
    676 	 * Note that it is not a "pass" connection, therefore passing of
    677 	 * "backwards" stream depends on other, stateless filtering rules.
    678 	 */
    679 	if (con == NULL) {
    680 		ncon = npf_conn_establish(npc, di, true);
    681 		if (ncon == NULL) {
    682 			npf_natpolicy_release(np);
    683 			return ENOMEM;
    684 		}
    685 		con = ncon;
    686 	}
    687 
    688 	/*
    689 	 * Create a new NAT entry and associate with the connection.
    690 	 * We will consume the reference on success (release on error).
    691 	 */
    692 	nt = npf_nat_create(npc, np, con);
    693 	if (nt == NULL) {
    694 		npf_natpolicy_release(np);
    695 		error = ENOMEM;
    696 		goto out;
    697 	}
    698 
    699 	/* Associate the NAT translation entry with the connection. */
    700 	error = npf_conn_setnat(npc, con, nt, np->n_type);
    701 	if (error) {
    702 		/* Will release the reference. */
    703 		npf_nat_destroy(nt);
    704 		goto out;
    705 	}
    706 
    707 	/* Determine whether any ALG matches. */
    708 	if (npf_alg_match(npc, nt, di)) {
    709 		KASSERT(nt->nt_alg != NULL);
    710 	}
    711 
    712 translate:
    713 	/* May need to process the delayed checksums first (XXX: NetBSD). */
    714 	if (nbuf_cksum_barrier(nbuf, di)) {
    715 		npf_recache(npc);
    716 	}
    717 
    718 	/* Perform the translation. */
    719 	error = npf_nat_translate(npc, nt, forw);
    720 out:
    721 	if (__predict_false(ncon)) {
    722 		if (error) {
    723 			/* It created for NAT - just expire. */
    724 			npf_conn_expire(ncon);
    725 		}
    726 		npf_conn_release(ncon);
    727 	}
    728 	return error;
    729 }
    730 
    731 /*
    732  * npf_nat_gettrans: return translation IP address and port.
    733  */
    734 void
    735 npf_nat_gettrans(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    736 {
    737 	*addr = &nt->nt_taddr;
    738 	*port = nt->nt_tport;
    739 }
    740 
    741 /*
    742  * npf_nat_getorig: return original IP address and port from translation entry.
    743  */
    744 void
    745 npf_nat_getorig(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    746 {
    747 	*addr = &nt->nt_oaddr;
    748 	*port = nt->nt_oport;
    749 }
    750 
    751 /*
    752  * npf_nat_setalg: associate an ALG with the NAT entry.
    753  */
    754 void
    755 npf_nat_setalg(npf_nat_t *nt, npf_alg_t *alg, uintptr_t arg)
    756 {
    757 	nt->nt_alg = alg;
    758 	nt->nt_alg_arg = arg;
    759 }
    760 
    761 /*
    762  * npf_nat_destroy: destroy NAT structure (performed on connection expiration).
    763  */
    764 void
    765 npf_nat_destroy(npf_nat_t *nt)
    766 {
    767 	npf_natpolicy_t *np = nt->nt_natpolicy;
    768 	npf_t *npf = np->n_npfctx;
    769 
    770 	/* Return taken port to the portmap. */
    771 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport) {
    772 		npf_portmap_t *pm = npf->portmap;
    773 		npf_portmap_put(pm, nt->nt_alen, &nt->nt_taddr, nt->nt_tport);
    774 	}
    775 	npf_stats_inc(np->n_npfctx, NPF_STAT_NAT_DESTROY);
    776 
    777 	/*
    778 	 * Remove the connection from the list and drop the reference on
    779 	 * the NAT policy.  Note: this might trigger its destruction.
    780 	 */
    781 	mutex_enter(&np->n_lock);
    782 	LIST_REMOVE(nt, nt_entry);
    783 	mutex_exit(&np->n_lock);
    784 	npf_natpolicy_release(np);
    785 
    786 	pool_cache_put(nat_cache, nt);
    787 }
    788 
    789 /*
    790  * npf_nat_export: serialise the NAT entry with a NAT policy ID.
    791  */
    792 void
    793 npf_nat_export(nvlist_t *condict, npf_nat_t *nt)
    794 {
    795 	npf_natpolicy_t *np = nt->nt_natpolicy;
    796 	unsigned alen = nt->nt_alen;
    797 	nvlist_t *nat;
    798 
    799 	nat = nvlist_create(0);
    800 	nvlist_add_number(nat, "alen", alen);
    801 	nvlist_add_binary(nat, "oaddr", &nt->nt_oaddr, sizeof(npf_addr_t));
    802 	nvlist_add_binary(nat, "taddr", &nt->nt_taddr, alen);
    803 	nvlist_add_number(nat, "oport", nt->nt_oport);
    804 	nvlist_add_number(nat, "tport", nt->nt_tport);
    805 	nvlist_add_number(nat, "nat-policy", np->n_id);
    806 	nvlist_move_nvlist(condict, "nat", nat);
    807 }
    808 
    809 /*
    810  * npf_nat_import: find the NAT policy and unserialise the NAT entry.
    811  */
    812 npf_nat_t *
    813 npf_nat_import(npf_t *npf, const nvlist_t *nat,
    814     npf_ruleset_t *natlist, npf_conn_t *con)
    815 {
    816 	npf_natpolicy_t *np;
    817 	npf_nat_t *nt;
    818 	const void *taddr, *oaddr;
    819 	size_t alen, len;
    820 	uint64_t np_id;
    821 
    822 	np_id = dnvlist_get_number(nat, "nat-policy", UINT64_MAX);
    823 	if ((np = npf_ruleset_findnat(natlist, np_id)) == NULL) {
    824 		return NULL;
    825 	}
    826 	nt = pool_cache_get(nat_cache, PR_WAITOK);
    827 	memset(nt, 0, sizeof(npf_nat_t));
    828 
    829 	alen = dnvlist_get_number(nat, "alen", 0);
    830 	if (alen == 0 || alen > sizeof(npf_addr_t)) {
    831 		goto err;
    832 	}
    833 
    834 	taddr = dnvlist_get_binary(nat, "taddr", &len, NULL, 0);
    835 	if (!taddr || len != alen) {
    836 		goto err;
    837 	}
    838 	memcpy(&nt->nt_taddr, taddr, sizeof(npf_addr_t));
    839 
    840 	oaddr = dnvlist_get_binary(nat, "oaddr", &len, NULL, 0);
    841 	if (!oaddr || len != alen) {
    842 		goto err;
    843 	}
    844 	memcpy(&nt->nt_oaddr, oaddr, sizeof(npf_addr_t));
    845 
    846 	nt->nt_oport = dnvlist_get_number(nat, "oport", 0);
    847 	nt->nt_tport = dnvlist_get_number(nat, "tport", 0);
    848 
    849 	/* Take a specific port from port-map. */
    850 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport) {
    851 		npf_portmap_t *pm = npf->portmap;
    852 
    853 		if (!npf_portmap_take(pm, nt->nt_alen,
    854 		    &nt->nt_taddr, nt->nt_tport)) {
    855 			goto err;
    856 		}
    857 	}
    858 	npf_stats_inc(npf, NPF_STAT_NAT_CREATE);
    859 
    860 	/*
    861 	 * Associate, take a reference and insert.  Unlocked since
    862 	 * the policy is not yet visible.
    863 	 */
    864 	nt->nt_natpolicy = np;
    865 	nt->nt_conn = con;
    866 	np->n_refcnt++;
    867 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    868 	return nt;
    869 err:
    870 	pool_cache_put(nat_cache, nt);
    871 	return NULL;
    872 }
    873 
    874 #if defined(DDB) || defined(_NPF_TESTING)
    875 
    876 void
    877 npf_nat_dump(const npf_nat_t *nt)
    878 {
    879 	const npf_natpolicy_t *np;
    880 	struct in_addr ip;
    881 
    882 	np = nt->nt_natpolicy;
    883 	memcpy(&ip, &nt->nt_taddr, sizeof(ip));
    884 	printf("\tNATP(%p): type %u flags 0x%x taddr %s tport %d\n", np,
    885 	    np->n_type, np->n_flags, inet_ntoa(ip), ntohs(np->n_tport));
    886 	memcpy(&ip, &nt->nt_oaddr, sizeof(ip));
    887 	printf("\tNAT: original address %s oport %d tport %d\n",
    888 	    inet_ntoa(ip), ntohs(nt->nt_oport), ntohs(nt->nt_tport));
    889 	if (nt->nt_alg) {
    890 		printf("\tNAT ALG = %p, ARG = %p\n",
    891 		    nt->nt_alg, (void *)nt->nt_alg_arg);
    892 	}
    893 }
    894 
    895 #endif
    896