Home | History | Annotate | Line # | Download | only in npf
npf_nat.c revision 1.47
      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.47 2019/08/11 20:26:34 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 		npf_portmap_t *pm = np->n_npfctx->portmap;
    518 		nt->nt_tport = npf_portmap_get(pm, alen, taddr);
    519 	} else {
    520 		nt->nt_tport = np->n_tport;
    521 	}
    522 out:
    523 	mutex_enter(&np->n_lock);
    524 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    525 	mutex_exit(&np->n_lock);
    526 	return nt;
    527 }
    528 
    529 /*
    530  * npf_nat_translate: perform translation given the state data.
    531  */
    532 static inline int
    533 npf_nat_translate(npf_cache_t *npc, npf_nat_t *nt, bool forw)
    534 {
    535 	const npf_natpolicy_t *np = nt->nt_natpolicy;
    536 	const unsigned which = npf_nat_which(np->n_type, forw);
    537 	const npf_addr_t *addr;
    538 	in_port_t port;
    539 
    540 	KASSERT(npf_iscached(npc, NPC_IP46));
    541 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    542 
    543 	if (forw) {
    544 		/* "Forwards" stream: use translation address/port. */
    545 		addr = &nt->nt_taddr;
    546 		port = nt->nt_tport;
    547 	} else {
    548 		/* "Backwards" stream: use original address/port. */
    549 		addr = &nt->nt_oaddr;
    550 		port = nt->nt_oport;
    551 	}
    552 	KASSERT((np->n_flags & NPF_NAT_PORTS) != 0 || port == 0);
    553 
    554 	/* Execute ALG translation first. */
    555 	if ((npc->npc_info & NPC_ALG_EXEC) == 0) {
    556 		npc->npc_info |= NPC_ALG_EXEC;
    557 		npf_alg_exec(npc, nt, forw);
    558 		npf_recache(npc);
    559 	}
    560 	KASSERT(!nbuf_flag_p(npc->npc_nbuf, NBUF_DATAREF_RESET));
    561 
    562 	/* Finally, perform the translation. */
    563 	return npf_napt_rwr(npc, which, addr, port);
    564 }
    565 
    566 /*
    567  * npf_nat_algo: perform the translation given the algorithm.
    568  */
    569 static inline int
    570 npf_nat_algo(npf_cache_t *npc, const npf_natpolicy_t *np, bool forw)
    571 {
    572 	const unsigned which = npf_nat_which(np->n_type, forw);
    573 	const npf_addr_t *taddr;
    574 	npf_addr_t addr;
    575 
    576 	KASSERT(np->n_flags & NPF_NAT_STATIC);
    577 
    578 	switch (np->n_algo) {
    579 	case NPF_ALGO_NETMAP:
    580 		npf_nat_algo_netmap(npc, np, which, &addr);
    581 		taddr = &addr;
    582 		break;
    583 	case NPF_ALGO_NPT66:
    584 		return npf_npt66_rwr(npc, which, &np->n_taddr,
    585 		    np->n_tmask, np->n_npt66_adj);
    586 	default:
    587 		taddr = &np->n_taddr;
    588 		break;
    589 	}
    590 	return npf_napt_rwr(npc, which, taddr, np->n_tport);
    591 }
    592 
    593 /*
    594  * npf_do_nat:
    595  *
    596  *	- Inspect packet for a NAT policy, unless a connection with a NAT
    597  *	  association already exists.  In such case, determine whether it
    598  *	  is a "forwards" or "backwards" stream.
    599  *	- Perform translation: rewrite source or destination fields,
    600  *	  depending on translation type and direction.
    601  *	- Associate a NAT policy with a connection (may establish a new).
    602  */
    603 int
    604 npf_do_nat(npf_cache_t *npc, npf_conn_t *con, const int di)
    605 {
    606 	nbuf_t *nbuf = npc->npc_nbuf;
    607 	npf_conn_t *ncon = NULL;
    608 	npf_natpolicy_t *np;
    609 	npf_nat_t *nt;
    610 	int error;
    611 	bool forw;
    612 
    613 	/* All relevant data should be already cached. */
    614 	if (!npf_iscached(npc, NPC_IP46) || !npf_iscached(npc, NPC_LAYER4)) {
    615 		return 0;
    616 	}
    617 	KASSERT(!nbuf_flag_p(nbuf, NBUF_DATAREF_RESET));
    618 
    619 	/*
    620 	 * Return the NAT entry associated with the connection, if any.
    621 	 * Determines whether the stream is "forwards" or "backwards".
    622 	 * Note: no need to lock, since reference on connection is held.
    623 	 */
    624 	if (con && (nt = npf_conn_getnat(con, di, &forw)) != NULL) {
    625 		np = nt->nt_natpolicy;
    626 		goto translate;
    627 	}
    628 
    629 	/*
    630 	 * Inspect the packet for a NAT policy, if there is no connection.
    631 	 * Note: acquires a reference if found.
    632 	 */
    633 	np = npf_nat_inspect(npc, di);
    634 	if (np == NULL) {
    635 		/* If packet does not match - done. */
    636 		return 0;
    637 	}
    638 	forw = true;
    639 
    640 	/* Static NAT - just perform the translation. */
    641 	if (np->n_flags & NPF_NAT_STATIC) {
    642 		if (nbuf_cksum_barrier(nbuf, di)) {
    643 			npf_recache(npc);
    644 		}
    645 		error = npf_nat_algo(npc, np, forw);
    646 		atomic_dec_uint(&np->n_refcnt);
    647 		return error;
    648 	}
    649 
    650 	/*
    651 	 * If there is no local connection (no "stateful" rule - unusual,
    652 	 * but possible configuration), establish one before translation.
    653 	 * Note that it is not a "pass" connection, therefore passing of
    654 	 * "backwards" stream depends on other, stateless filtering rules.
    655 	 */
    656 	if (con == NULL) {
    657 		ncon = npf_conn_establish(npc, di, true);
    658 		if (ncon == NULL) {
    659 			atomic_dec_uint(&np->n_refcnt);
    660 			return ENOMEM;
    661 		}
    662 		con = ncon;
    663 	}
    664 
    665 	/*
    666 	 * Create a new NAT entry and associate with the connection.
    667 	 * We will consume the reference on success (release on error).
    668 	 */
    669 	nt = npf_nat_create(npc, np, con);
    670 	if (nt == NULL) {
    671 		atomic_dec_uint(&np->n_refcnt);
    672 		error = ENOMEM;
    673 		goto out;
    674 	}
    675 
    676 	/* Associate the NAT translation entry with the connection. */
    677 	error = npf_conn_setnat(npc, con, nt, np->n_type);
    678 	if (error) {
    679 		/* Will release the reference. */
    680 		npf_nat_destroy(nt);
    681 		goto out;
    682 	}
    683 
    684 	/* Determine whether any ALG matches. */
    685 	if (npf_alg_match(npc, nt, di)) {
    686 		KASSERT(nt->nt_alg != NULL);
    687 	}
    688 
    689 translate:
    690 	/* May need to process the delayed checksums first (XXX: NetBSD). */
    691 	if (nbuf_cksum_barrier(nbuf, di)) {
    692 		npf_recache(npc);
    693 	}
    694 
    695 	/* Perform the translation. */
    696 	error = npf_nat_translate(npc, nt, forw);
    697 out:
    698 	if (__predict_false(ncon)) {
    699 		if (error) {
    700 			/* It created for NAT - just expire. */
    701 			npf_conn_expire(ncon);
    702 		}
    703 		npf_conn_release(ncon);
    704 	}
    705 	return error;
    706 }
    707 
    708 /*
    709  * npf_nat_gettrans: return translation IP address and port.
    710  */
    711 void
    712 npf_nat_gettrans(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    713 {
    714 	*addr = &nt->nt_taddr;
    715 	*port = nt->nt_tport;
    716 }
    717 
    718 /*
    719  * npf_nat_getorig: return original IP address and port from translation entry.
    720  */
    721 void
    722 npf_nat_getorig(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    723 {
    724 	*addr = &nt->nt_oaddr;
    725 	*port = nt->nt_oport;
    726 }
    727 
    728 /*
    729  * npf_nat_setalg: associate an ALG with the NAT entry.
    730  */
    731 void
    732 npf_nat_setalg(npf_nat_t *nt, npf_alg_t *alg, uintptr_t arg)
    733 {
    734 	nt->nt_alg = alg;
    735 	nt->nt_alg_arg = arg;
    736 }
    737 
    738 /*
    739  * npf_nat_destroy: destroy NAT structure (performed on connection expiration).
    740  */
    741 void
    742 npf_nat_destroy(npf_nat_t *nt)
    743 {
    744 	npf_natpolicy_t *np = nt->nt_natpolicy;
    745 	npf_t *npf = np->n_npfctx;
    746 
    747 	/* Return taken port to the portmap. */
    748 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport) {
    749 		npf_portmap_t *pm = npf->portmap;
    750 		npf_portmap_put(pm, nt->nt_alen, &nt->nt_taddr, nt->nt_tport);
    751 	}
    752 	npf_stats_inc(np->n_npfctx, NPF_STAT_NAT_DESTROY);
    753 
    754 	mutex_enter(&np->n_lock);
    755 	LIST_REMOVE(nt, nt_entry);
    756 	KASSERT(np->n_refcnt > 0);
    757 	atomic_dec_uint(&np->n_refcnt);
    758 	mutex_exit(&np->n_lock);
    759 	pool_cache_put(nat_cache, nt);
    760 }
    761 
    762 /*
    763  * npf_nat_export: serialise the NAT entry with a NAT policy ID.
    764  */
    765 void
    766 npf_nat_export(nvlist_t *condict, npf_nat_t *nt)
    767 {
    768 	npf_natpolicy_t *np = nt->nt_natpolicy;
    769 	nvlist_t *nat;
    770 
    771 	nat = nvlist_create(0);
    772 	nvlist_add_binary(nat, "oaddr", &nt->nt_oaddr, sizeof(npf_addr_t));
    773 	nvlist_add_number(nat, "oport", nt->nt_oport);
    774 	nvlist_add_number(nat, "tport", nt->nt_tport);
    775 	nvlist_add_number(nat, "nat-policy", np->n_id);
    776 	nvlist_move_nvlist(condict, "nat", nat);
    777 }
    778 
    779 /*
    780  * npf_nat_import: find the NAT policy and unserialise the NAT entry.
    781  */
    782 npf_nat_t *
    783 npf_nat_import(npf_t *npf, const nvlist_t *nat,
    784     npf_ruleset_t *natlist, npf_conn_t *con)
    785 {
    786 	npf_natpolicy_t *np;
    787 	npf_nat_t *nt;
    788 	const void *oaddr;
    789 	uint64_t np_id;
    790 	size_t len;
    791 
    792 	np_id = dnvlist_get_number(nat, "nat-policy", UINT64_MAX);
    793 	if ((np = npf_ruleset_findnat(natlist, np_id)) == NULL) {
    794 		return NULL;
    795 	}
    796 	nt = pool_cache_get(nat_cache, PR_WAITOK);
    797 	memset(nt, 0, sizeof(npf_nat_t));
    798 
    799 	oaddr = dnvlist_get_binary(nat, "oaddr", &len, NULL, 0);
    800 	if (!oaddr || len != sizeof(npf_addr_t)) {
    801 		pool_cache_put(nat_cache, nt);
    802 		return NULL;
    803 	}
    804 	memcpy(&nt->nt_oaddr, oaddr, sizeof(npf_addr_t));
    805 	nt->nt_oport = dnvlist_get_number(nat, "oport", 0);
    806 	nt->nt_tport = dnvlist_get_number(nat, "tport", 0);
    807 
    808 	/* Take a specific port from port-map. */
    809 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport) {
    810 		npf_portmap_t *pm = npf->portmap;
    811 
    812 		if (!npf_portmap_take(pm, nt->nt_alen,
    813 		    &nt->nt_taddr, nt->nt_tport)) {
    814 			pool_cache_put(nat_cache, nt);
    815 			return NULL;
    816 		}
    817 	}
    818 	npf_stats_inc(npf, NPF_STAT_NAT_CREATE);
    819 
    820 	/*
    821 	 * Associate, take a reference and insert.  Unlocked since
    822 	 * the policy is not yet visible.
    823 	 */
    824 	nt->nt_natpolicy = np;
    825 	nt->nt_conn = con;
    826 	np->n_refcnt++;
    827 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    828 	return nt;
    829 }
    830 
    831 #if defined(DDB) || defined(_NPF_TESTING)
    832 
    833 void
    834 npf_nat_dump(const npf_nat_t *nt)
    835 {
    836 	const npf_natpolicy_t *np;
    837 	struct in_addr ip;
    838 
    839 	np = nt->nt_natpolicy;
    840 	memcpy(&ip, &nt->nt_taddr, sizeof(ip));
    841 	printf("\tNATP(%p): type %u flags 0x%x taddr %s tport %d\n", np,
    842 	    np->n_type, np->n_flags, inet_ntoa(ip), ntohs(np->n_tport));
    843 	memcpy(&ip, &nt->nt_oaddr, sizeof(ip));
    844 	printf("\tNAT: original address %s oport %d tport %d\n",
    845 	    inet_ntoa(ip), ntohs(nt->nt_oport), ntohs(nt->nt_tport));
    846 	if (nt->nt_alg) {
    847 		printf("\tNAT ALG = %p, ARG = %p\n",
    848 		    nt->nt_alg, (void *)nt->nt_alg_arg);
    849 	}
    850 }
    851 
    852 #endif
    853