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