Home | History | Annotate | Line # | Download | only in npf
npf_nat.c revision 1.35
      1 /*	$NetBSD: npf_nat.c,v 1.35 2014/11/26 21:25:35 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.35 2014/11/26 21:25:35 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 	}
    256 	return np;
    257 err:
    258 	kmem_free(np, sizeof(npf_natpolicy_t));
    259 	return NULL;
    260 }
    261 
    262 int
    263 npf_nat_policyexport(const npf_natpolicy_t *np, prop_dictionary_t natdict)
    264 {
    265 	prop_data_t d;
    266 
    267 	prop_dictionary_set_int32(natdict, "type", np->n_type);
    268 	prop_dictionary_set_uint32(natdict, "flags", np->n_flags);
    269 
    270 	d = prop_data_create_data(&np->n_taddr, np->n_alen);
    271 	prop_dictionary_set_and_rel(natdict, "nat-ip", d);
    272 
    273 	prop_dictionary_set_uint8(natdict, "nat-mask", np->n_tmask);
    274 	prop_dictionary_set_uint16(natdict, "nat-port", np->n_tport);
    275 	prop_dictionary_set_uint32(natdict, "nat-algo", np->n_algo);
    276 
    277 	switch (np->n_algo) {
    278 	case NPF_ALGO_NPT66:
    279 		prop_dictionary_set_uint16(natdict, "npt66-adj", np->n_npt66_adj);
    280 		break;
    281 	}
    282 	prop_dictionary_set_uint64(natdict, "nat-policy", np->n_id);
    283 	return 0;
    284 }
    285 
    286 /*
    287  * npf_nat_freepolicy: free NAT policy and, on last reference, free portmap.
    288  *
    289  * => Called from npf_rule_free() during the reload via npf_ruleset_destroy().
    290  */
    291 void
    292 npf_nat_freepolicy(npf_natpolicy_t *np)
    293 {
    294 	npf_portmap_t *pm = np->n_portmap;
    295 	npf_conn_t *con;
    296 	npf_nat_t *nt;
    297 
    298 	/*
    299 	 * Disassociate all entries from the policy.  At this point,
    300 	 * new entries can no longer be created for this policy.
    301 	 */
    302 	while (np->n_refcnt) {
    303 		mutex_enter(&np->n_lock);
    304 		LIST_FOREACH(nt, &np->n_nat_list, nt_entry) {
    305 			con = nt->nt_conn;
    306 			KASSERT(con != NULL);
    307 			npf_conn_expire(con);
    308 		}
    309 		mutex_exit(&np->n_lock);
    310 
    311 		/* Kick the worker - all references should be going away. */
    312 		npf_worker_signal();
    313 		kpause("npfgcnat", false, 1, NULL);
    314 	}
    315 	KASSERT(LIST_EMPTY(&np->n_nat_list));
    316 	KASSERT(pm == NULL || pm->p_refcnt > 0);
    317 
    318 	/* Destroy the port map, on last reference. */
    319 	if (pm && atomic_dec_uint_nv(&pm->p_refcnt) == 0) {
    320 		KASSERT((np->n_flags & NPF_NAT_PORTMAP) != 0);
    321 		kmem_free(pm, PORTMAP_MEM_SIZE);
    322 	}
    323 	mutex_destroy(&np->n_lock);
    324 	kmem_free(np, sizeof(npf_natpolicy_t));
    325 }
    326 
    327 void
    328 npf_nat_freealg(npf_natpolicy_t *np, npf_alg_t *alg)
    329 {
    330 	npf_nat_t *nt;
    331 
    332 	mutex_enter(&np->n_lock);
    333 	LIST_FOREACH(nt, &np->n_nat_list, nt_entry) {
    334 		if (nt->nt_alg == alg)
    335 			nt->nt_alg = NULL;
    336 	}
    337 	mutex_exit(&np->n_lock);
    338 }
    339 
    340 /*
    341  * npf_nat_cmppolicy: compare two NAT policies.
    342  *
    343  * => Return 0 on match, and non-zero otherwise.
    344  */
    345 bool
    346 npf_nat_cmppolicy(npf_natpolicy_t *np, npf_natpolicy_t *mnp)
    347 {
    348 	const void *np_raw, *mnp_raw;
    349 
    350 	/*
    351 	 * Compare the relevant NAT policy information (in raw form),
    352 	 * which is enough for matching criterion.
    353 	 */
    354 	KASSERT(np && mnp && np != mnp);
    355 	np_raw = (const uint8_t *)np + NPF_NP_CMP_START;
    356 	mnp_raw = (const uint8_t *)mnp + NPF_NP_CMP_START;
    357 	return memcmp(np_raw, mnp_raw, NPF_NP_CMP_SIZE) == 0;
    358 }
    359 
    360 bool
    361 npf_nat_sharepm(npf_natpolicy_t *np, npf_natpolicy_t *mnp)
    362 {
    363 	npf_portmap_t *pm, *mpm;
    364 
    365 	KASSERT(np && mnp && np != mnp);
    366 
    367 	/* Using port map and having equal translation address? */
    368 	if ((np->n_flags & mnp->n_flags & NPF_NAT_PORTMAP) == 0) {
    369 		return false;
    370 	}
    371 	if (np->n_alen != mnp->n_alen) {
    372 		return false;
    373 	}
    374 	if (memcmp(&np->n_taddr, &mnp->n_taddr, np->n_alen) != 0) {
    375 		return false;
    376 	}
    377 	mpm = mnp->n_portmap;
    378 	KASSERT(mpm == NULL || mpm->p_refcnt > 0);
    379 
    380 	/*
    381 	 * If NAT policy has an old port map - drop the reference
    382 	 * and destroy the port map if it was the last.
    383 	 */
    384 	if (mpm && atomic_dec_uint_nv(&mpm->p_refcnt) == 0) {
    385 		kmem_free(mpm, PORTMAP_MEM_SIZE);
    386 	}
    387 
    388 	/* Share the port map. */
    389 	pm = np->n_portmap;
    390 	atomic_inc_uint(&pm->p_refcnt);
    391 	mnp->n_portmap = pm;
    392 	return true;
    393 }
    394 
    395 void
    396 npf_nat_setid(npf_natpolicy_t *np, uint64_t id)
    397 {
    398 	np->n_id = id;
    399 }
    400 
    401 uint64_t
    402 npf_nat_getid(const npf_natpolicy_t *np)
    403 {
    404 	return np->n_id;
    405 }
    406 
    407 /*
    408  * npf_nat_getport: allocate and return a port in the NAT policy portmap.
    409  *
    410  * => Returns in network byte-order.
    411  * => Zero indicates failure.
    412  */
    413 static in_port_t
    414 npf_nat_getport(npf_natpolicy_t *np)
    415 {
    416 	npf_portmap_t *pm = np->n_portmap;
    417 	u_int n = PORTMAP_SIZE, idx, bit;
    418 	uint32_t map, nmap;
    419 
    420 	idx = cprng_fast32() % PORTMAP_SIZE;
    421 	for (;;) {
    422 		KASSERT(idx < PORTMAP_SIZE);
    423 		map = pm->p_bitmap[idx];
    424 		if (__predict_false(map == PORTMAP_FILLED)) {
    425 			if (n-- == 0) {
    426 				/* No space. */
    427 				return 0;
    428 			}
    429 			/* This bitmap is filled, next. */
    430 			idx = (idx ? idx : PORTMAP_SIZE) - 1;
    431 			continue;
    432 		}
    433 		bit = ffs32(~map) - 1;
    434 		nmap = map | (1 << bit);
    435 		if (atomic_cas_32(&pm->p_bitmap[idx], map, nmap) == map) {
    436 			/* Success. */
    437 			break;
    438 		}
    439 	}
    440 	return htons(PORTMAP_FIRST + (idx << PORTMAP_SHIFT) + bit);
    441 }
    442 
    443 /*
    444  * npf_nat_takeport: allocate specific port in the NAT policy portmap.
    445  */
    446 static bool
    447 npf_nat_takeport(npf_natpolicy_t *np, in_port_t port)
    448 {
    449 	npf_portmap_t *pm = np->n_portmap;
    450 	uint32_t map, nmap;
    451 	u_int idx, bit;
    452 
    453 	port = ntohs(port) - PORTMAP_FIRST;
    454 	idx = port >> PORTMAP_SHIFT;
    455 	bit = port & PORTMAP_MASK;
    456 	map = pm->p_bitmap[idx];
    457 	nmap = map | (1 << bit);
    458 	if (map == nmap) {
    459 		/* Already taken. */
    460 		return false;
    461 	}
    462 	return atomic_cas_32(&pm->p_bitmap[idx], map, nmap) == map;
    463 }
    464 
    465 /*
    466  * npf_nat_putport: return port as available in the NAT policy portmap.
    467  *
    468  * => Port should be in network byte-order.
    469  */
    470 static void
    471 npf_nat_putport(npf_natpolicy_t *np, in_port_t port)
    472 {
    473 	npf_portmap_t *pm = np->n_portmap;
    474 	uint32_t map, nmap;
    475 	u_int idx, bit;
    476 
    477 	port = ntohs(port) - PORTMAP_FIRST;
    478 	idx = port >> PORTMAP_SHIFT;
    479 	bit = port & PORTMAP_MASK;
    480 	do {
    481 		map = pm->p_bitmap[idx];
    482 		KASSERT(map | (1 << bit));
    483 		nmap = map & ~(1 << bit);
    484 	} while (atomic_cas_32(&pm->p_bitmap[idx], map, nmap) != map);
    485 }
    486 
    487 /*
    488  * npf_nat_which: tell which address (source or destination) should be
    489  * rewritten given the combination of the NAT type and flow direction.
    490  */
    491 static inline u_int
    492 npf_nat_which(const int type, bool forw)
    493 {
    494 	/*
    495 	 * Outbound NAT rewrites:
    496 	 * - Source (NPF_SRC) on "forwards" stream.
    497 	 * - Destination (NPF_DST) on "backwards" stream.
    498 	 * Inbound NAT is other way round.
    499 	 */
    500 	if (type == NPF_NATOUT) {
    501 		forw = !forw;
    502 	} else {
    503 		KASSERT(type == NPF_NATIN);
    504 	}
    505 	CTASSERT(NPF_SRC == 0 && NPF_DST == 1);
    506 	KASSERT(forw == NPF_SRC || forw == NPF_DST);
    507 	return (u_int)forw;
    508 }
    509 
    510 /*
    511  * npf_nat_inspect: inspect packet against NAT ruleset and return a policy.
    512  *
    513  * => Acquire a reference on the policy, if found.
    514  */
    515 static npf_natpolicy_t *
    516 npf_nat_inspect(npf_cache_t *npc, const int di)
    517 {
    518 	int slock = npf_config_read_enter();
    519 	npf_ruleset_t *rlset = npf_config_natset();
    520 	npf_natpolicy_t *np;
    521 	npf_rule_t *rl;
    522 
    523 	rl = npf_ruleset_inspect(npc, rlset, di, NPF_LAYER_3);
    524 	if (rl == NULL) {
    525 		npf_config_read_exit(slock);
    526 		return NULL;
    527 	}
    528 	np = npf_rule_getnat(rl);
    529 	atomic_inc_uint(&np->n_refcnt);
    530 	npf_config_read_exit(slock);
    531 	return np;
    532 }
    533 
    534 /*
    535  * npf_nat_create: create a new NAT translation entry.
    536  */
    537 static npf_nat_t *
    538 npf_nat_create(npf_cache_t *npc, npf_natpolicy_t *np, npf_conn_t *con)
    539 {
    540 	const int proto = npc->npc_proto;
    541 	npf_nat_t *nt;
    542 
    543 	KASSERT(npf_iscached(npc, NPC_IP46));
    544 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    545 
    546 	/* Construct a new NAT entry and associate it with the connection. */
    547 	nt = pool_cache_get(nat_cache, PR_NOWAIT);
    548 	if (nt == NULL){
    549 		return NULL;
    550 	}
    551 	npf_stats_inc(NPF_STAT_NAT_CREATE);
    552 	nt->nt_natpolicy = np;
    553 	nt->nt_conn = con;
    554 	nt->nt_alg = NULL;
    555 
    556 	/* Save the original address which may be rewritten. */
    557 	if (np->n_type == NPF_NATOUT) {
    558 		/* Outbound NAT: source (think internal) address. */
    559 		memcpy(&nt->nt_oaddr, npc->npc_ips[NPF_SRC], npc->npc_alen);
    560 	} else {
    561 		/* Inbound NAT: destination (think external) address. */
    562 		KASSERT(np->n_type == NPF_NATIN);
    563 		memcpy(&nt->nt_oaddr, npc->npc_ips[NPF_DST], npc->npc_alen);
    564 	}
    565 
    566 	/*
    567 	 * Port translation, if required, and if it is TCP/UDP.
    568 	 */
    569 	if ((np->n_flags & NPF_NAT_PORTS) == 0 ||
    570 	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
    571 		nt->nt_oport = 0;
    572 		nt->nt_tport = 0;
    573 		goto out;
    574 	}
    575 
    576 	/* Save the relevant TCP/UDP port. */
    577 	if (proto == IPPROTO_TCP) {
    578 		const struct tcphdr *th = npc->npc_l4.tcp;
    579 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    580 		    th->th_sport : th->th_dport;
    581 	} else {
    582 		const struct udphdr *uh = npc->npc_l4.udp;
    583 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    584 		    uh->uh_sport : uh->uh_dport;
    585 	}
    586 
    587 	/* Get a new port for translation. */
    588 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0) {
    589 		nt->nt_tport = npf_nat_getport(np);
    590 	} else {
    591 		nt->nt_tport = np->n_tport;
    592 	}
    593 out:
    594 	mutex_enter(&np->n_lock);
    595 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    596 	mutex_exit(&np->n_lock);
    597 	return nt;
    598 }
    599 
    600 /*
    601  * npf_nat_translate: perform translation given the state data.
    602  */
    603 static inline int
    604 npf_nat_translate(npf_cache_t *npc, npf_nat_t *nt, bool forw)
    605 {
    606 	const npf_natpolicy_t *np = nt->nt_natpolicy;
    607 	const u_int which = npf_nat_which(np->n_type, forw);
    608 	const npf_addr_t *addr;
    609 	in_port_t port;
    610 
    611 	KASSERT(npf_iscached(npc, NPC_IP46));
    612 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    613 
    614 	if (forw) {
    615 		/* "Forwards" stream: use translation address/port. */
    616 		addr = &np->n_taddr;
    617 		port = nt->nt_tport;
    618 	} else {
    619 		/* "Backwards" stream: use original address/port. */
    620 		addr = &nt->nt_oaddr;
    621 		port = nt->nt_oport;
    622 	}
    623 	KASSERT((np->n_flags & NPF_NAT_PORTS) != 0 || port == 0);
    624 
    625 	/* Execute ALG translation first. */
    626 	if ((npc->npc_info & NPC_ALG_EXEC) == 0) {
    627 		npc->npc_info |= NPC_ALG_EXEC;
    628 		npf_alg_exec(npc, nt, forw);
    629 		npf_recache(npc);
    630 	}
    631 	KASSERT(!nbuf_flag_p(npc->npc_nbuf, NBUF_DATAREF_RESET));
    632 
    633 	/* Finally, perform the translation. */
    634 	return npf_napt_rwr(npc, which, addr, port);
    635 }
    636 
    637 /*
    638  * npf_nat_algo: perform the translation given the algorithm.
    639  */
    640 static inline int
    641 npf_nat_algo(npf_cache_t *npc, const npf_natpolicy_t *np, bool forw)
    642 {
    643 	const u_int which = npf_nat_which(np->n_type, forw);
    644 	int error;
    645 
    646 	switch (np->n_algo) {
    647 	case NPF_ALGO_NPT66:
    648 		error = npf_npt66_rwr(npc, which, &np->n_taddr,
    649 		    np->n_tmask, np->n_npt66_adj);
    650 		break;
    651 	default:
    652 		error = npf_napt_rwr(npc, which, &np->n_taddr, np->n_tport);
    653 		break;
    654 	}
    655 
    656 	return error;
    657 }
    658 
    659 /*
    660  * npf_do_nat:
    661  *	- Inspect packet for a NAT policy, unless a connection with a NAT
    662  *	  association already exists.  In such case, determine whether it
    663  *	  is a "forwards" or "backwards" stream.
    664  *	- Perform translation: rewrite source or destination fields,
    665  *	  depending on translation type and direction.
    666  *	- Associate a NAT policy with a connection (may establish a new).
    667  */
    668 int
    669 npf_do_nat(npf_cache_t *npc, npf_conn_t *con, const int di)
    670 {
    671 	nbuf_t *nbuf = npc->npc_nbuf;
    672 	npf_conn_t *ncon = NULL;
    673 	npf_natpolicy_t *np;
    674 	npf_nat_t *nt;
    675 	int error;
    676 	bool forw;
    677 
    678 	/* All relevant IPv4 data should be already cached. */
    679 	if (!npf_iscached(npc, NPC_IP46) || !npf_iscached(npc, NPC_LAYER4)) {
    680 		return 0;
    681 	}
    682 	KASSERT(!nbuf_flag_p(nbuf, NBUF_DATAREF_RESET));
    683 
    684 	/*
    685 	 * Return the NAT entry associated with the connection, if any.
    686 	 * Determines whether the stream is "forwards" or "backwards".
    687 	 * Note: no need to lock, since reference on connection is held.
    688 	 */
    689 	if (con && (nt = npf_conn_retnat(con, di, &forw)) != NULL) {
    690 		np = nt->nt_natpolicy;
    691 		goto translate;
    692 	}
    693 
    694 	/*
    695 	 * Inspect the packet for a NAT policy, if there is no connection.
    696 	 * Note: acquires a reference if found.
    697 	 */
    698 	np = npf_nat_inspect(npc, di);
    699 	if (np == NULL) {
    700 		/* If packet does not match - done. */
    701 		return 0;
    702 	}
    703 	forw = true;
    704 
    705 	/* Static NAT - just perform the translation. */
    706 	if (np->n_flags & NPF_NAT_STATIC) {
    707 		if (nbuf_cksum_barrier(nbuf, di)) {
    708 			npf_recache(npc);
    709 		}
    710 		error = npf_nat_algo(npc, np, forw);
    711 		atomic_dec_uint(&np->n_refcnt);
    712 		return error;
    713 	}
    714 
    715 	/*
    716 	 * If there is no local connection (no "stateful" rule - unusual,
    717 	 * but possible configuration), establish one before translation.
    718 	 * Note that it is not a "pass" connection, therefore passing of
    719 	 * "backwards" stream depends on other, stateless filtering rules.
    720 	 */
    721 	if (con == NULL) {
    722 		ncon = npf_conn_establish(npc, di, true);
    723 		if (ncon == NULL) {
    724 			atomic_dec_uint(&np->n_refcnt);
    725 			return ENOMEM;
    726 		}
    727 		con = ncon;
    728 	}
    729 
    730 	/*
    731 	 * Create a new NAT entry and associate with the connection.
    732 	 * We will consume the reference on success (release on error).
    733 	 */
    734 	nt = npf_nat_create(npc, np, con);
    735 	if (nt == NULL) {
    736 		atomic_dec_uint(&np->n_refcnt);
    737 		error = ENOMEM;
    738 		goto out;
    739 	}
    740 
    741 	/* Associate the NAT translation entry with the connection. */
    742 	error = npf_conn_setnat(npc, con, nt, np->n_type);
    743 	if (error) {
    744 		/* Will release the reference. */
    745 		npf_nat_destroy(nt);
    746 		goto out;
    747 	}
    748 
    749 	/* Determine whether any ALG matches. */
    750 	if (npf_alg_match(npc, nt, di)) {
    751 		KASSERT(nt->nt_alg != NULL);
    752 	}
    753 
    754 translate:
    755 	/* May need to process the delayed checksums first (XXX: NetBSD). */
    756 	if (nbuf_cksum_barrier(nbuf, di)) {
    757 		npf_recache(npc);
    758 	}
    759 
    760 	/* Perform the translation. */
    761 	error = npf_nat_translate(npc, nt, forw);
    762 out:
    763 	if (__predict_false(ncon)) {
    764 		if (error) {
    765 			/* It created for NAT - just expire. */
    766 			npf_conn_expire(ncon);
    767 		}
    768 		npf_conn_release(ncon);
    769 	}
    770 	return error;
    771 }
    772 
    773 /*
    774  * npf_nat_gettrans: return translation IP address and port.
    775  */
    776 void
    777 npf_nat_gettrans(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    778 {
    779 	npf_natpolicy_t *np = nt->nt_natpolicy;
    780 
    781 	*addr = &np->n_taddr;
    782 	*port = nt->nt_tport;
    783 }
    784 
    785 /*
    786  * npf_nat_getorig: return original IP address and port from translation entry.
    787  */
    788 void
    789 npf_nat_getorig(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    790 {
    791 	*addr = &nt->nt_oaddr;
    792 	*port = nt->nt_oport;
    793 }
    794 
    795 /*
    796  * npf_nat_setalg: associate an ALG with the NAT entry.
    797  */
    798 void
    799 npf_nat_setalg(npf_nat_t *nt, npf_alg_t *alg, uintptr_t arg)
    800 {
    801 	nt->nt_alg = alg;
    802 	nt->nt_alg_arg = arg;
    803 }
    804 
    805 /*
    806  * npf_nat_destroy: destroy NAT structure (performed on connection expiration).
    807  */
    808 void
    809 npf_nat_destroy(npf_nat_t *nt)
    810 {
    811 	npf_natpolicy_t *np = nt->nt_natpolicy;
    812 
    813 	/* Return any taken port to the portmap. */
    814 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport) {
    815 		npf_nat_putport(np, nt->nt_tport);
    816 	}
    817 
    818 	mutex_enter(&np->n_lock);
    819 	LIST_REMOVE(nt, nt_entry);
    820 	KASSERT(np->n_refcnt > 0);
    821 	atomic_dec_uint(&np->n_refcnt);
    822 	mutex_exit(&np->n_lock);
    823 
    824 	pool_cache_put(nat_cache, nt);
    825 	npf_stats_inc(NPF_STAT_NAT_DESTROY);
    826 }
    827 
    828 /*
    829  * npf_nat_export: serialise the NAT entry with a NAT policy ID.
    830  */
    831 void
    832 npf_nat_export(prop_dictionary_t condict, npf_nat_t *nt)
    833 {
    834 	npf_natpolicy_t *np = nt->nt_natpolicy;
    835 	prop_dictionary_t natdict;
    836 	prop_data_t d;
    837 
    838 	natdict = prop_dictionary_create();
    839 	d = prop_data_create_data(&nt->nt_oaddr, sizeof(npf_addr_t));
    840 	prop_dictionary_set_and_rel(natdict, "oaddr", d);
    841 	prop_dictionary_set_uint16(natdict, "oport", nt->nt_oport);
    842 	prop_dictionary_set_uint16(natdict, "tport", nt->nt_tport);
    843 	prop_dictionary_set_uint64(natdict, "nat-policy", np->n_id);
    844 	prop_dictionary_set_and_rel(condict, "nat", natdict);
    845 }
    846 
    847 /*
    848  * npf_nat_import: find the NAT policy and unserialise the NAT entry.
    849  */
    850 npf_nat_t *
    851 npf_nat_import(prop_dictionary_t natdict, npf_ruleset_t *natlist,
    852     npf_conn_t *con)
    853 {
    854 	npf_natpolicy_t *np;
    855 	npf_nat_t *nt;
    856 	uint64_t np_id;
    857 	const void *d;
    858 
    859 	prop_dictionary_get_uint64(natdict, "nat-policy", &np_id);
    860 	if ((np = npf_ruleset_findnat(natlist, np_id)) == NULL) {
    861 		return NULL;
    862 	}
    863 	nt = pool_cache_get(nat_cache, PR_WAITOK);
    864 	memset(nt, 0, sizeof(npf_nat_t));
    865 
    866 	prop_object_t obj = prop_dictionary_get(natdict, "oaddr");
    867 	if ((d = prop_data_data_nocopy(obj)) == NULL ||
    868 	    prop_data_size(obj) != sizeof(npf_addr_t)) {
    869 		pool_cache_put(nat_cache, nt);
    870 		return NULL;
    871 	}
    872 	memcpy(&nt->nt_oaddr, d, sizeof(npf_addr_t));
    873 	prop_dictionary_get_uint16(natdict, "oport", &nt->nt_oport);
    874 	prop_dictionary_get_uint16(natdict, "tport", &nt->nt_tport);
    875 
    876 	/* Take a specific port from port-map. */
    877 	if (!npf_nat_takeport(np, nt->nt_tport)) {
    878 		pool_cache_put(nat_cache, nt);
    879 		return NULL;
    880 	}
    881 
    882 	/*
    883 	 * Associate, take a reference and insert.  Unlocked since
    884 	 * the policy is not yet visible.
    885 	 */
    886 	nt->nt_natpolicy = np;
    887 	nt->nt_conn = con;
    888 	np->n_refcnt++;
    889 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    890 	return nt;
    891 }
    892 
    893 #if defined(DDB) || defined(_NPF_TESTING)
    894 
    895 void
    896 npf_nat_dump(const npf_nat_t *nt)
    897 {
    898 	const npf_natpolicy_t *np;
    899 	struct in_addr ip;
    900 
    901 	np = nt->nt_natpolicy;
    902 	memcpy(&ip, &np->n_taddr, sizeof(ip));
    903 	printf("\tNATP(%p): type %d flags 0x%x taddr %s tport %d\n",
    904 	    np, np->n_type, np->n_flags, inet_ntoa(ip), np->n_tport);
    905 	memcpy(&ip, &nt->nt_oaddr, sizeof(ip));
    906 	printf("\tNAT: original address %s oport %d tport %d\n",
    907 	    inet_ntoa(ip), ntohs(nt->nt_oport), ntohs(nt->nt_tport));
    908 	if (nt->nt_alg) {
    909 		printf("\tNAT ALG = %p, ARG = %p\n",
    910 		    nt->nt_alg, (void *)nt->nt_alg_arg);
    911 	}
    912 }
    913 
    914 #endif
    915