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