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