Home | History | Annotate | Line # | Download | only in npf
npf_nat.c revision 1.8
      1 /*	$NetBSD: npf_nat.c,v 1.8 2011/11/19 22:51:25 tls 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.8 2011/11/19 22:51:25 tls 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 	mutex_init(&np->n_lock, MUTEX_DEFAULT, IPL_SOFTNET);
    185 	cv_init(&np->n_cv, "npfnatcv");
    186 	LIST_INIT(&np->n_nat_list);
    187 
    188 	/* Translation type and flags. */
    189 	prop_dictionary_get_int32(natdict, "type", &np->n_type);
    190 	prop_dictionary_get_uint32(natdict, "flags", &np->n_flags);
    191 	KASSERT(np->n_type == NPF_NATIN || np->n_type == NPF_NATOUT);
    192 
    193 	/* Translation IP. */
    194 	obj = prop_dictionary_get(natdict, "translation-ip");
    195 	np->n_addr_sz = prop_data_size(obj);
    196 	KASSERT(np->n_addr_sz > 0 && np->n_addr_sz <= sizeof(npf_addr_t));
    197 	memcpy(&np->n_taddr, prop_data_data_nocopy(obj), np->n_addr_sz);
    198 
    199 	/* Translation port (for redirect case). */
    200 	prop_dictionary_get_uint16(natdict, "translation-port", &np->n_tport);
    201 
    202 	/* Determine if port map is needed. */
    203 	np->n_portmap = NULL;
    204 	if ((np->n_flags & NPF_NAT_PORTMAP) == 0) {
    205 		/* No port map. */
    206 		return np;
    207 	}
    208 
    209 	/*
    210 	 * Inspect NAT policies in the ruleset for port map sharing.
    211 	 * Note that npf_ruleset_sharepm() will increase the reference count.
    212 	 */
    213 	if (!npf_ruleset_sharepm(nrlset, np)) {
    214 		/* Allocate a new port map for the NAT policy. */
    215 		pm = kmem_zalloc(PORTMAP_MEM_SIZE, KM_SLEEP);
    216 		pm->p_refcnt = 1;
    217 		KASSERT((uintptr_t)pm->p_bitmap == (uintptr_t)pm + sizeof(*pm));
    218 		np->n_portmap = pm;
    219 	} else {
    220 		KASSERT(np->n_portmap != NULL);
    221 	}
    222 	return np;
    223 }
    224 
    225 /*
    226  * npf_nat_freepolicy: free NAT policy and, on last reference, free portmap.
    227  *
    228  * => Called from npf_rule_free() during the reload via npf_ruleset_destroy().
    229  */
    230 void
    231 npf_nat_freepolicy(npf_natpolicy_t *np)
    232 {
    233 	npf_portmap_t *pm = np->n_portmap;
    234 	npf_session_t *se;
    235 	npf_nat_t *nt;
    236 
    237 	/* De-associate all entries from the policy. */
    238 	mutex_enter(&np->n_lock);
    239 	LIST_FOREACH(nt, &np->n_nat_list, nt_entry) {
    240 		se = nt->nt_session; /* XXXSMP */
    241 		if (se == NULL) {
    242 			continue;
    243 		}
    244 		npf_session_expire(se);
    245 	}
    246 	while (!LIST_EMPTY(&np->n_nat_list)) {
    247 		cv_wait(&np->n_cv, &np->n_lock);
    248 	}
    249 	mutex_exit(&np->n_lock);
    250 
    251 	/* Destroy the port map, on last reference. */
    252 	if (pm && --pm->p_refcnt == 0) {
    253 		KASSERT((np->n_flags & NPF_NAT_PORTMAP) != 0);
    254 		kmem_free(pm, PORTMAP_MEM_SIZE);
    255 	}
    256 	cv_destroy(&np->n_cv);
    257 	mutex_destroy(&np->n_lock);
    258 	kmem_free(np, sizeof(npf_natpolicy_t));
    259 }
    260 
    261 /*
    262  * npf_nat_matchpolicy: compare two NAT policies.
    263  *
    264  * => Return 0 on match, and non-zero otherwise.
    265  */
    266 bool
    267 npf_nat_matchpolicy(npf_natpolicy_t *np, npf_natpolicy_t *mnp)
    268 {
    269 	void *np_raw, *mnp_raw;
    270 	/*
    271 	 * Compare the relevant NAT policy information (in raw form),
    272 	 * which is enough for matching criterion.
    273 	 */
    274 	KASSERT(np && mnp && np != mnp);
    275 	np_raw = (uint8_t *)np + NPF_NP_CMP_START;
    276 	mnp_raw = (uint8_t *)mnp + NPF_NP_CMP_START;
    277 	return (memcmp(np_raw, mnp_raw, NPF_NP_CMP_SIZE) == 0);
    278 }
    279 
    280 bool
    281 npf_nat_sharepm(npf_natpolicy_t *np, npf_natpolicy_t *mnp)
    282 {
    283 	npf_portmap_t *pm, *mpm;
    284 
    285 	KASSERT(np && mnp && np != mnp);
    286 
    287 	/* Using port map and having equal translation address? */
    288 	if ((np->n_flags & mnp->n_flags & NPF_NAT_PORTMAP) == 0) {
    289 		return false;
    290 	}
    291 	if (np->n_addr_sz != mnp->n_addr_sz) {
    292 		return false;
    293 	}
    294 	if (memcmp(&np->n_taddr, &mnp->n_taddr, np->n_addr_sz) != 0) {
    295 		return false;
    296 	}
    297 	/* If NAT policy has an old port map - drop the reference. */
    298 	mpm = mnp->n_portmap;
    299 	if (mpm) {
    300 		/* Note: in such case, we must not be a last reference. */
    301 		KASSERT(mpm->p_refcnt > 1);
    302 		mpm->p_refcnt--;
    303 	}
    304 	/* Share the port map. */
    305 	pm = np->n_portmap;
    306 	mnp->n_portmap = pm;
    307 	pm->p_refcnt++;
    308 	return true;
    309 }
    310 
    311 /*
    312  * npf_nat_getport: allocate and return a port in the NAT policy portmap.
    313  *
    314  * => Returns in network byte-order.
    315  * => Zero indicates failure.
    316  */
    317 static in_port_t
    318 npf_nat_getport(npf_natpolicy_t *np)
    319 {
    320 	npf_portmap_t *pm = np->n_portmap;
    321 	u_int n = PORTMAP_SIZE, idx, bit;
    322 	uint32_t map, nmap;
    323 
    324 	idx = cprng_fast32() % PORTMAP_SIZE;
    325 	for (;;) {
    326 		KASSERT(idx < PORTMAP_SIZE);
    327 		map = pm->p_bitmap[idx];
    328 		if (__predict_false(map == PORTMAP_FILLED)) {
    329 			if (n-- == 0) {
    330 				/* No space. */
    331 				return 0;
    332 			}
    333 			/* This bitmap is filled, next. */
    334 			idx = (idx ? idx : PORTMAP_SIZE) - 1;
    335 			continue;
    336 		}
    337 		bit = ffs32(~map) - 1;
    338 		nmap = map | (1 << bit);
    339 		if (atomic_cas_32(&pm->p_bitmap[idx], map, nmap) == map) {
    340 			/* Success. */
    341 			break;
    342 		}
    343 	}
    344 	return htons(PORTMAP_FIRST + (idx << PORTMAP_SHIFT) + bit);
    345 }
    346 
    347 /*
    348  * npf_nat_takeport: allocate specific port in the NAT policy portmap.
    349  */
    350 static bool
    351 npf_nat_takeport(npf_natpolicy_t *np, in_port_t port)
    352 {
    353 	npf_portmap_t *pm = np->n_portmap;
    354 	uint32_t map, nmap;
    355 	u_int idx, bit;
    356 
    357 	port = ntohs(port) - PORTMAP_FIRST;
    358 	idx = port >> PORTMAP_SHIFT;
    359 	bit = port & PORTMAP_MASK;
    360 	map = pm->p_bitmap[idx];
    361 	nmap = map | (1 << bit);
    362 	if (map == nmap) {
    363 		/* Already taken. */
    364 		return false;
    365 	}
    366 	return atomic_cas_32(&pm->p_bitmap[idx], map, nmap) == map;
    367 }
    368 
    369 /*
    370  * npf_nat_putport: return port as available in the NAT policy portmap.
    371  *
    372  * => Port should be in network byte-order.
    373  */
    374 static void
    375 npf_nat_putport(npf_natpolicy_t *np, in_port_t port)
    376 {
    377 	npf_portmap_t *pm = np->n_portmap;
    378 	uint32_t map, nmap;
    379 	u_int idx, bit;
    380 
    381 	port = ntohs(port) - PORTMAP_FIRST;
    382 	idx = port >> PORTMAP_SHIFT;
    383 	bit = port & PORTMAP_MASK;
    384 	do {
    385 		map = pm->p_bitmap[idx];
    386 		KASSERT(map | (1 << bit));
    387 		nmap = map & ~(1 << bit);
    388 	} while (atomic_cas_32(&pm->p_bitmap[idx], map, nmap) != map);
    389 }
    390 
    391 /*
    392  * npf_nat_inspect: inspect packet against NAT ruleset and return a policy.
    393  */
    394 static npf_natpolicy_t *
    395 npf_nat_inspect(npf_cache_t *npc, nbuf_t *nbuf, ifnet_t *ifp, const int di)
    396 {
    397 	npf_ruleset_t *rlset;
    398 	npf_natpolicy_t *np;
    399 	npf_rule_t *rl;
    400 
    401 	npf_core_enter();
    402 	rlset = npf_core_natset();
    403 	rl = npf_ruleset_inspect(npc, nbuf, rlset, ifp, di, NPF_LAYER_3);
    404 	if (rl == NULL) {
    405 		return NULL;
    406 	}
    407 	np = npf_rule_getnat(rl);
    408 	if (np == NULL) {
    409 		npf_core_exit();
    410 		return NULL;
    411 	}
    412 	return np;
    413 }
    414 
    415 /*
    416  * npf_nat_create: create a new NAT translation entry.
    417  */
    418 static npf_nat_t *
    419 npf_nat_create(npf_cache_t *npc, npf_natpolicy_t *np)
    420 {
    421 	const int proto = npf_cache_ipproto(npc);
    422 	npf_nat_t *nt;
    423 
    424 	KASSERT(npf_iscached(npc, NPC_IP46));
    425 	KASSERT(npf_iscached(npc, NPC_LAYER4));
    426 
    427 	/* New NAT association. */
    428 	nt = pool_cache_get(nat_cache, PR_NOWAIT);
    429 	if (nt == NULL){
    430 		return NULL;
    431 	}
    432 	npf_stats_inc(NPF_STAT_NAT_CREATE);
    433 	nt->nt_natpolicy = np;
    434 	nt->nt_session = NULL;
    435 	nt->nt_alg = NULL;
    436 
    437 	mutex_enter(&np->n_lock);
    438 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    439 	mutex_exit(&np->n_lock);
    440 
    441 	/* Save the original address which may be rewritten. */
    442 	if (np->n_type == NPF_NATOUT) {
    443 		/* Source (local) for Outbound NAT. */
    444 		memcpy(&nt->nt_oaddr, npc->npc_srcip, npc->npc_ipsz);
    445 	} else {
    446 		/* Destination (external) for Inbound NAT. */
    447 		KASSERT(np->n_type == NPF_NATIN);
    448 		memcpy(&nt->nt_oaddr, npc->npc_dstip, npc->npc_ipsz);
    449 	}
    450 
    451 	/*
    452 	 * Port translation, if required, and if it is TCP/UDP.
    453 	 */
    454 	if ((np->n_flags & NPF_NAT_PORTS) == 0 ||
    455 	    (proto != IPPROTO_TCP && proto != IPPROTO_UDP)) {
    456 		nt->nt_oport = 0;
    457 		nt->nt_tport = 0;
    458 		return nt;
    459 	}
    460 	/* Save the relevant TCP/UDP port. */
    461 	if (proto == IPPROTO_TCP) {
    462 		struct tcphdr *th = &npc->npc_l4.tcp;
    463 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    464 		    th->th_sport : th->th_dport;
    465 	} else {
    466 		struct udphdr *uh = &npc->npc_l4.udp;
    467 		nt->nt_oport = (np->n_type == NPF_NATOUT) ?
    468 		    uh->uh_sport : uh->uh_dport;
    469 	}
    470 
    471 	/* Get a new port for translation. */
    472 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0) {
    473 		nt->nt_tport = npf_nat_getport(np);
    474 	} else {
    475 		nt->nt_tport = np->n_tport;
    476 	}
    477 	return nt;
    478 }
    479 
    480 /*
    481  * npf_nat_translate: perform address and/or port translation.
    482  */
    483 static int
    484 npf_nat_translate(npf_cache_t *npc, nbuf_t *nbuf, npf_nat_t *nt,
    485     const bool forw, const int di)
    486 {
    487 	void *n_ptr = nbuf_dataptr(nbuf);
    488 	npf_natpolicy_t *np = nt->nt_natpolicy;
    489 	npf_addr_t *addr;
    490 	in_port_t port;
    491 
    492 	KASSERT(npf_iscached(npc, NPC_IP46));
    493 
    494 	if (forw) {
    495 		/* "Forwards" stream: use translation address/port. */
    496 		KASSERT(
    497 		    (np->n_type == NPF_NATIN && di == PFIL_IN) ^
    498 		    (np->n_type == NPF_NATOUT && di == PFIL_OUT)
    499 		);
    500 		addr = &np->n_taddr;
    501 		port = nt->nt_tport;
    502 	} else {
    503 		/* "Backwards" stream: use original address/port. */
    504 		KASSERT(
    505 		    (np->n_type == NPF_NATIN && di == PFIL_OUT) ^
    506 		    (np->n_type == NPF_NATOUT && di == PFIL_IN)
    507 		);
    508 		addr = &nt->nt_oaddr;
    509 		port = nt->nt_oport;
    510 	}
    511 	KASSERT((np->n_flags & NPF_NAT_PORTS) != 0 || port == 0);
    512 
    513 	/* Execute ALG hook first. */
    514 	npf_alg_exec(npc, nbuf, nt, di);
    515 
    516 	/*
    517 	 * Rewrite IP and/or TCP/UDP checksums first, since it will use
    518 	 * the cache containing original values for checksum calculation.
    519 	 */
    520 	if (!npf_rwrcksum(npc, nbuf, n_ptr, di, addr, port)) {
    521 		return EINVAL;
    522 	}
    523 	/*
    524 	 * Address translation: rewrite source/destination address, depending
    525 	 * on direction (PFIL_OUT - for source, PFIL_IN - for destination).
    526 	 */
    527 	if (!npf_rwrip(npc, nbuf, n_ptr, di, addr)) {
    528 		return EINVAL;
    529 	}
    530 	if ((np->n_flags & NPF_NAT_PORTS) == 0) {
    531 		/* Done. */
    532 		return 0;
    533 	}
    534 	switch (npf_cache_ipproto(npc)) {
    535 	case IPPROTO_TCP:
    536 	case IPPROTO_UDP:
    537 		KASSERT(npf_iscached(npc, NPC_TCP) || npf_iscached(npc, NPC_UDP));
    538 		/* Rewrite source/destination port. */
    539 		if (!npf_rwrport(npc, nbuf, n_ptr, di, port)) {
    540 			return EINVAL;
    541 		}
    542 		break;
    543 	case IPPROTO_ICMP:
    544 		KASSERT(npf_iscached(npc, NPC_ICMP));
    545 		/* Nothing. */
    546 		break;
    547 	default:
    548 		return ENOTSUP;
    549 	}
    550 	return 0;
    551 }
    552 
    553 /*
    554  * npf_do_nat:
    555  *	- Inspect packet for a NAT policy, unless a session with a NAT
    556  *	  association already exists.  In such case, determine whether it
    557  *	  is a "forwards" or "backwards" stream.
    558  *	- Perform translation: rewrite source or destination fields,
    559  *	  depending on translation type and direction.
    560  *	- Associate a NAT policy with a session (may establish a new).
    561  */
    562 int
    563 npf_do_nat(npf_cache_t *npc, npf_session_t *se, nbuf_t *nbuf,
    564     ifnet_t *ifp, const int di)
    565 {
    566 	npf_session_t *nse = NULL;
    567 	npf_natpolicy_t *np;
    568 	npf_nat_t *nt;
    569 	int error;
    570 	bool forw, new;
    571 
    572 	/* All relevant IPv4 data should be already cached. */
    573 	if (!npf_iscached(npc, NPC_IP46) || !npf_iscached(npc, NPC_LAYER4)) {
    574 		return 0;
    575 	}
    576 
    577 	/*
    578 	 * Return the NAT entry associated with the session, if any.
    579 	 * Determines whether the stream is "forwards" or "backwards".
    580 	 * Note: no need to lock, since reference on session is held.
    581 	 */
    582 	if (se && (nt = npf_session_retnat(se, di, &forw)) != NULL) {
    583 		np = nt->nt_natpolicy;
    584 		new = false;
    585 		goto translate;
    586 	}
    587 
    588 	/*
    589 	 * Inspect the packet for a NAT policy, if there is no session.
    590 	 * Note: acquires the lock (releases, if not found).
    591 	 */
    592 	np = npf_nat_inspect(npc, nbuf, ifp, di);
    593 	if (np == NULL) {
    594 		/* If packet does not match - done. */
    595 		return 0;
    596 	}
    597 	forw = true;
    598 
    599 	/*
    600 	 * Create a new NAT entry.  Note: it is safe to unlock, since the
    601 	 * NAT policy wont be desotroyed while there are list entries, which
    602 	 * are removed only on session expiration.  Currently, NAT entry is
    603 	 * not yet associated with any session.
    604 	 */
    605 	nt = npf_nat_create(npc, np);
    606 	if (nt == NULL) {
    607 		npf_core_exit();
    608 		return ENOMEM;
    609 	}
    610 	npf_core_exit();
    611 	new = true;
    612 
    613 	/* Determine whether any ALG matches. */
    614 	if (npf_alg_match(npc, nbuf, nt)) {
    615 		KASSERT(nt->nt_alg != NULL);
    616 	}
    617 
    618 	/*
    619 	 * If there is no local session (no "keep state" rule - unusual, but
    620 	 * possible configuration), establish one before translation.  Note
    621 	 * that it is not a "pass" session, therefore passing of "backwards"
    622 	 * stream depends on other, stateless filtering rules.
    623 	 */
    624 	if (se == NULL) {
    625 		nse = npf_session_establish(npc, nbuf, di);
    626 		if (nse == NULL) {
    627 			error = ENOMEM;
    628 			goto out;
    629 		}
    630 		se = nse;
    631 	}
    632 translate:
    633 	/* Perform the translation. */
    634 	error = npf_nat_translate(npc, nbuf, nt, forw, di);
    635 	if (error) {
    636 		goto out;
    637 	}
    638 
    639 	if (__predict_false(new)) {
    640 		/*
    641 		 * Associate NAT translation entry with the session.
    642 		 * Note: packet now has a translated address in the cache.
    643 		 */
    644 		nt->nt_session = se;
    645 		error = npf_session_setnat(se, nt, di);
    646 out:
    647 		if (error) {
    648 			/* If session was for NAT only - expire it. */
    649 			if (nse) {
    650 				npf_session_expire(nse);
    651 			}
    652 			/* Will free the structure and return the port. */
    653 			npf_nat_expire(nt);
    654 		}
    655 		if (nse != NULL) {
    656 			npf_session_release(nse);
    657 		}
    658 	}
    659 	return error;
    660 }
    661 
    662 /*
    663  * npf_nat_gettrans: return translation IP address and port.
    664  */
    665 void
    666 npf_nat_gettrans(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    667 {
    668 	npf_natpolicy_t *np = nt->nt_natpolicy;
    669 
    670 	*addr = &np->n_taddr;
    671 	*port = nt->nt_tport;
    672 }
    673 
    674 /*
    675  * npf_nat_getorig: return original IP address and port from translation entry.
    676  */
    677 void
    678 npf_nat_getorig(npf_nat_t *nt, npf_addr_t **addr, in_port_t *port)
    679 {
    680 
    681 	*addr = &nt->nt_oaddr;
    682 	*port = nt->nt_oport;
    683 }
    684 
    685 /*
    686  * npf_nat_setalg: associate an ALG with the NAT entry.
    687  */
    688 void
    689 npf_nat_setalg(npf_nat_t *nt, npf_alg_t *alg, uintptr_t arg)
    690 {
    691 
    692 	nt->nt_alg = alg;
    693 	nt->nt_alg_arg = arg;
    694 }
    695 
    696 /*
    697  * npf_nat_expire: free NAT-related data structures on session expiration.
    698  */
    699 void
    700 npf_nat_expire(npf_nat_t *nt)
    701 {
    702 	npf_natpolicy_t *np = nt->nt_natpolicy;
    703 
    704 	/* Return any taken port to the portmap. */
    705 	if ((np->n_flags & NPF_NAT_PORTMAP) != 0 && nt->nt_tport) {
    706 		npf_nat_putport(np, nt->nt_tport);
    707 	}
    708 
    709 	/* Remove NAT entry from the list, notify any waiters if last entry. */
    710 	mutex_enter(&np->n_lock);
    711 	LIST_REMOVE(nt, nt_entry);
    712 	if (LIST_EMPTY(&np->n_nat_list)) {
    713 		cv_broadcast(&np->n_cv);
    714 	}
    715 	mutex_exit(&np->n_lock);
    716 
    717 	/* Free structure, increase the counter. */
    718 	pool_cache_put(nat_cache, nt);
    719 	npf_stats_inc(NPF_STAT_NAT_DESTROY);
    720 }
    721 
    722 /*
    723  * npf_nat_save: construct NAT entry and reference to the NAT policy.
    724  */
    725 int
    726 npf_nat_save(prop_dictionary_t sedict, prop_array_t natlist, npf_nat_t *nt)
    727 {
    728 	npf_natpolicy_t *np = nt->nt_natpolicy;
    729 	prop_object_iterator_t it;
    730 	prop_dictionary_t npdict;
    731 	prop_data_t nd, npd;
    732 	uintptr_t itnp;
    733 
    734 	/* Set NAT entry data. */
    735 	nd = prop_data_create_data(nt, sizeof(npf_nat_t));
    736 	prop_dictionary_set(sedict, "nat-data", nd);
    737 	prop_object_release(nd);
    738 
    739 	/* Find or create a NAT policy. */
    740 	it = prop_array_iterator(natlist);
    741 	while ((npdict = prop_object_iterator_next(it)) != NULL) {
    742 		CTASSERT(sizeof(uintptr_t) <= sizeof(uint64_t));
    743 		prop_dictionary_get_uint64(npdict, "id-ptr", (uint64_t *)&itnp);
    744 		if (itnp == (uintptr_t)np) {
    745 			break;
    746 		}
    747 	}
    748 	if (npdict == NULL) {
    749 		/* Create NAT policy dictionary and copy the data. */
    750 		npdict = prop_dictionary_create();
    751 		npd = prop_data_create_data(np, sizeof(npf_natpolicy_t));
    752 		prop_dictionary_set(npdict, "nat-policy-data", npd);
    753 		prop_object_release(npd);
    754 
    755 		CTASSERT(sizeof(uintptr_t) <= sizeof(uint64_t));
    756 		prop_dictionary_set_uint64(npdict, "id-ptr", (uintptr_t)np);
    757 		prop_array_add(natlist, npdict);
    758 		prop_object_release(npdict);
    759 	}
    760 	prop_dictionary_set(sedict, "nat-policy", npdict);
    761 	prop_object_release(npdict);
    762 	return 0;
    763 }
    764 
    765 /*
    766  * npf_nat_restore: find a matching NAT policy and restore NAT entry.
    767  *
    768  * => Caller should lock the active NAT ruleset.
    769  */
    770 npf_nat_t *
    771 npf_nat_restore(prop_dictionary_t sedict, npf_session_t *se)
    772 {
    773 	const npf_natpolicy_t *onp;
    774 	const npf_nat_t *ntraw;
    775 	prop_object_t obj;
    776 	npf_natpolicy_t *np;
    777 	npf_rule_t *rl;
    778 	npf_nat_t *nt;
    779 
    780 	/* Get raw NAT entry. */
    781 	obj = prop_dictionary_get(sedict, "nat-data");
    782 	ntraw = prop_data_data_nocopy(obj);
    783 	if (ntraw == NULL || prop_data_size(obj) != sizeof(npf_nat_t)) {
    784 		return NULL;
    785 	}
    786 
    787 	/* Find a stored NAT policy information. */
    788 	obj = prop_dictionary_get(
    789 	    prop_dictionary_get(sedict, "nat-policy"), "nat-policy-data");
    790 	onp = prop_data_data_nocopy(obj);
    791 	if (onp == NULL || prop_data_size(obj) != sizeof(npf_natpolicy_t)) {
    792 		return NULL;
    793 	}
    794 
    795 	/* Match if there is an existing NAT policy. */
    796 	rl = npf_ruleset_matchnat(npf_core_natset(), __UNCONST(onp));
    797 	if (rl == NULL) {
    798 		return NULL;
    799 	}
    800 	np = npf_rule_getnat(rl);
    801 	KASSERT(np != NULL);
    802 
    803 	/* Take a specific port from port-map. */
    804 	if (!npf_nat_takeport(np, ntraw->nt_tport)) {
    805 		return NULL;
    806 	}
    807 
    808 	/* Create and return NAT entry for association. */
    809 	nt = pool_cache_get(nat_cache, PR_WAITOK);
    810 	memcpy(nt, ntraw, sizeof(npf_nat_t));
    811 	LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry);
    812 	nt->nt_natpolicy = np;
    813 	nt->nt_session = se;
    814 	nt->nt_alg = NULL;
    815 	return nt;
    816 }
    817 
    818 #if defined(DDB) || defined(_NPF_TESTING)
    819 
    820 void
    821 npf_nat_dump(npf_nat_t *nt)
    822 {
    823 	npf_natpolicy_t *np;
    824 	struct in_addr ip;
    825 
    826 	np = nt->nt_natpolicy;
    827 	memcpy(&ip, &np->n_taddr, sizeof(ip));
    828 	printf("\tNATP(%p): type %d flags 0x%x taddr %s tport %d\n",
    829 	    np, np->n_type, np->n_flags, inet_ntoa(ip), np->n_tport);
    830 	memcpy(&ip, &nt->nt_oaddr, sizeof(ip));
    831 	printf("\tNAT: original address %s oport %d tport %d\n",
    832 	    inet_ntoa(ip), ntohs(nt->nt_oport), ntohs(nt->nt_tport));
    833 	if (nt->nt_alg) {
    834 		printf("\tNAT ALG = %p, ARG = %p\n",
    835 		    nt->nt_alg, (void *)nt->nt_alg_arg);
    836 	}
    837 }
    838 
    839 #endif
    840