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