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