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