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