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