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