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