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