1 /* $NetBSD: npf_nat.c,v 1.27 2014/03/14 11:29:44 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 * Sessions, translation entries and their life-cycle 63 * 64 * NAT module relies on session management module. Each translated 65 * session 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 session expires. 71 */ 72 73 #include <sys/cdefs.h> 74 __KERNEL_RCSID(0, "$NetBSD: npf_nat.c,v 1.27 2014/03/14 11:29:44 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 93 /* 94 * NPF portmap structure. 95 */ 96 typedef struct { 97 u_int p_refcnt; 98 uint32_t p_bitmap[0]; 99 } npf_portmap_t; 100 101 /* Portmap range: [ 1024 .. 65535 ] */ 102 #define PORTMAP_FIRST (1024) 103 #define PORTMAP_SIZE ((65536 - PORTMAP_FIRST) / 32) 104 #define PORTMAP_FILLED ((uint32_t)~0U) 105 #define PORTMAP_MASK (31) 106 #define PORTMAP_SHIFT (5) 107 108 #define PORTMAP_MEM_SIZE \ 109 (sizeof(npf_portmap_t) + (PORTMAP_SIZE * sizeof(uint32_t))) 110 111 /* 112 * NAT policy structure. 113 */ 114 struct npf_natpolicy { 115 LIST_HEAD(, npf_nat) n_nat_list; 116 volatile u_int n_refcnt; 117 kmutex_t n_lock; 118 kcondvar_t n_cv; 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 session. 138 */ 139 struct npf_nat { 140 /* Association (list entry and a link pointer) with NAT policy. */ 141 LIST_ENTRY(npf_nat) nt_entry; 142 npf_natpolicy_t * nt_natpolicy; 143 npf_session_t * nt_session; 144 /* Original address and port (for backwards translation). */ 145 npf_addr_t nt_oaddr; 146 in_port_t nt_oport; 147 /* Translation port (for redirects). */ 148 in_port_t nt_tport; 149 /* ALG (if any) associated with this NAT entry. */ 150 npf_alg_t * nt_alg; 151 uintptr_t nt_alg_arg; 152 }; 153 154 static pool_cache_t nat_cache __read_mostly; 155 156 /* 157 * npf_nat_sys{init,fini}: initialise/destroy NAT subsystem structures. 158 */ 159 160 void 161 npf_nat_sysinit(void) 162 { 163 nat_cache = pool_cache_init(sizeof(npf_nat_t), coherency_unit, 164 0, 0, "npfnatpl", NULL, IPL_NET, NULL, NULL, NULL); 165 KASSERT(nat_cache != NULL); 166 } 167 168 void 169 npf_nat_sysfini(void) 170 { 171 /* All NAT policies should already be destroyed. */ 172 pool_cache_destroy(nat_cache); 173 } 174 175 /* 176 * npf_nat_newpolicy: create a new NAT policy. 177 * 178 * => Shares portmap if policy is on existing translation address. 179 */ 180 npf_natpolicy_t * 181 npf_nat_newpolicy(prop_dictionary_t natdict, npf_ruleset_t *nrlset) 182 { 183 npf_natpolicy_t *np; 184 prop_object_t obj; 185 npf_portmap_t *pm; 186 187 np = kmem_zalloc(sizeof(npf_natpolicy_t), KM_SLEEP); 188 189 /* Translation type and flags. */ 190 prop_dictionary_get_int32(natdict, "type", &np->n_type); 191 prop_dictionary_get_uint32(natdict, "flags", &np->n_flags); 192 193 /* Should be exclusively either inbound or outbound NAT. */ 194 if (((np->n_type == NPF_NATIN) ^ (np->n_type == NPF_NATOUT)) == 0) { 195 goto err; 196 } 197 mutex_init(&np->n_lock, MUTEX_DEFAULT, IPL_SOFTNET); 198 cv_init(&np->n_cv, "npfnatcv"); 199 LIST_INIT(&np->n_nat_list); 200 201 /* Translation IP, mask and port (if applicable). */ 202 obj = prop_dictionary_get(natdict, "translation-ip"); 203 np->n_addr_sz = prop_data_size(obj); 204 if (np->n_addr_sz == 0 || np->n_addr_sz > sizeof(npf_addr_t)) { 205 goto err; 206 } 207 memcpy(&np->n_taddr, prop_data_data_nocopy(obj), np->n_addr_sz); 208 prop_dictionary_get_uint8(natdict, "translation-mask", &np->n_tmask); 209 prop_dictionary_get_uint16(natdict, "translation-port", &np->n_tport); 210 211 prop_dictionary_get_uint32(natdict, "translation-algo", &np->n_algo); 212 switch (np->n_algo) { 213 case NPF_ALGO_NPT66: 214 prop_dictionary_get_uint16(natdict, "npt66-adjustment", 215 &np->n_npt66_adj); 216 break; 217 default: 218 if (np->n_tmask != NPF_NO_NETMASK) 219 goto err; 220 break; 221 } 222 223 /* Determine if port map is needed. */ 224 np->n_portmap = NULL; 225 if ((np->n_flags & NPF_NAT_PORTMAP) == 0) { 226 /* No port map. */ 227 return np; 228 } 229 230 /* 231 * Inspect NAT policies in the ruleset for port map sharing. 232 * Note that npf_ruleset_sharepm() will increase the reference count. 233 */ 234 if (!npf_ruleset_sharepm(nrlset, np)) { 235 /* Allocate a new port map for the NAT policy. */ 236 pm = kmem_zalloc(PORTMAP_MEM_SIZE, KM_SLEEP); 237 pm->p_refcnt = 1; 238 KASSERT((uintptr_t)pm->p_bitmap == (uintptr_t)pm + sizeof(*pm)); 239 np->n_portmap = pm; 240 } else { 241 KASSERT(np->n_portmap != NULL); 242 } 243 return np; 244 err: 245 kmem_free(np, sizeof(npf_natpolicy_t)); 246 return NULL; 247 } 248 249 /* 250 * npf_nat_freepolicy: free NAT policy and, on last reference, free portmap. 251 * 252 * => Called from npf_rule_free() during the reload via npf_ruleset_destroy(). 253 */ 254 void 255 npf_nat_freepolicy(npf_natpolicy_t *np) 256 { 257 npf_portmap_t *pm = np->n_portmap; 258 npf_session_t *se; 259 npf_nat_t *nt; 260 261 /* 262 * Disassociate all entries from the policy. At this point, 263 * new entries can no longer be created for this policy. 264 */ 265 mutex_enter(&np->n_lock); 266 LIST_FOREACH(nt, &np->n_nat_list, nt_entry) { 267 se = nt->nt_session; 268 KASSERT(se != NULL); 269 npf_session_expire(se); 270 } 271 while (!LIST_EMPTY(&np->n_nat_list)) { 272 cv_wait(&np->n_cv, &np->n_lock); 273 } 274 mutex_exit(&np->n_lock); 275 276 /* Kick the worker - all references should be going away. */ 277 npf_worker_signal(); 278 while (np->n_refcnt) { 279 kpause("npfgcnat", false, 1, NULL); 280 } 281 KASSERT(LIST_EMPTY(&np->n_nat_list)); 282 283 /* Destroy the port map, on last reference. */ 284 if (pm && --pm->p_refcnt == 0) { 285 KASSERT((np->n_flags & NPF_NAT_PORTMAP) != 0); 286 kmem_free(pm, PORTMAP_MEM_SIZE); 287 } 288 cv_destroy(&np->n_cv); 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_session_t *se) 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 session. */ 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_session = se; 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 session 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 session (may establish a new). 618 */ 619 int 620 npf_do_nat(npf_cache_t *npc, npf_session_t *se, nbuf_t *nbuf, const int di) 621 { 622 npf_session_t *nse = 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 session, if any. 636 * Determines whether the stream is "forwards" or "backwards". 637 * Note: no need to lock, since reference on session is held. 638 */ 639 if (se && (nt = npf_session_retnat(se, 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 session. 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 session (no "stateful" rule - unusual, but 667 * possible configuration), establish one before translation. Note 668 * that it is not a "pass" session, therefore passing of "backwards" 669 * stream depends on other, stateless filtering rules. 670 */ 671 if (se == NULL) { 672 nse = npf_session_establish(npc, nbuf, di, true); 673 if (nse == NULL) { 674 atomic_dec_uint(&np->n_refcnt); 675 return ENOMEM; 676 } 677 se = nse; 678 } 679 680 /* 681 * Create a new NAT entry and associate with the session. 682 * We will consume the reference on success (release on error). 683 */ 684 nt = npf_nat_create(npc, np, se); 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 session. */ 692 error = npf_session_setnat(se, 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(nse)) { 714 if (error) { 715 /* It created for NAT - just expire. */ 716 npf_session_expire(nse); 717 } 718 npf_session_release(nse); 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 session 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 if (LIST_EMPTY(&np->n_nat_list)) { 771 /* Notify any waiters if empty. */ 772 cv_broadcast(&np->n_cv); 773 } 774 atomic_dec_uint(&np->n_refcnt); 775 mutex_exit(&np->n_lock); 776 777 pool_cache_put(nat_cache, nt); 778 npf_stats_inc(NPF_STAT_NAT_DESTROY); 779 } 780 781 /* 782 * npf_nat_save: construct NAT entry and reference to the NAT policy. 783 */ 784 int 785 npf_nat_save(prop_dictionary_t sedict, prop_array_t natlist, npf_nat_t *nt) 786 { 787 npf_natpolicy_t *np = nt->nt_natpolicy; 788 prop_object_iterator_t it; 789 prop_dictionary_t npdict; 790 prop_data_t nd, npd; 791 uint64_t itnp; 792 793 /* Set NAT entry data. */ 794 nd = prop_data_create_data(nt, sizeof(npf_nat_t)); 795 prop_dictionary_set(sedict, "nat-data", nd); 796 prop_object_release(nd); 797 798 /* Find or create a NAT policy. */ 799 it = prop_array_iterator(natlist); 800 while ((npdict = prop_object_iterator_next(it)) != NULL) { 801 CTASSERT(sizeof(uintptr_t) <= sizeof(uint64_t)); 802 prop_dictionary_get_uint64(npdict, "id-ptr", &itnp); 803 if ((uintptr_t)itnp == (uintptr_t)np) { 804 break; 805 } 806 } 807 if (npdict == NULL) { 808 /* Create NAT policy dictionary and copy the data. */ 809 npdict = prop_dictionary_create(); 810 npd = prop_data_create_data(np, sizeof(npf_natpolicy_t)); 811 prop_dictionary_set(npdict, "nat-policy-data", npd); 812 prop_object_release(npd); 813 814 CTASSERT(sizeof(uintptr_t) <= sizeof(uint64_t)); 815 prop_dictionary_set_uint64(npdict, "id-ptr", (uintptr_t)np); 816 prop_array_add(natlist, npdict); 817 prop_object_release(npdict); 818 } 819 prop_dictionary_set(sedict, "nat-policy", npdict); 820 prop_object_release(npdict); 821 return 0; 822 } 823 824 /* 825 * npf_nat_restore: find a matching NAT policy and restore NAT entry. 826 * 827 * => Caller should lock the active NAT ruleset. 828 */ 829 npf_nat_t * 830 npf_nat_restore(prop_dictionary_t sedict, npf_session_t *se) 831 { 832 const npf_natpolicy_t *onp; 833 const npf_nat_t *ntraw; 834 prop_object_t obj; 835 npf_natpolicy_t *np; 836 npf_rule_t *rl; 837 npf_nat_t *nt; 838 839 /* Get raw NAT entry. */ 840 obj = prop_dictionary_get(sedict, "nat-data"); 841 ntraw = prop_data_data_nocopy(obj); 842 if (ntraw == NULL || prop_data_size(obj) != sizeof(npf_nat_t)) { 843 return NULL; 844 } 845 846 /* Find a stored NAT policy information. */ 847 obj = prop_dictionary_get( 848 prop_dictionary_get(sedict, "nat-policy"), "nat-policy-data"); 849 onp = prop_data_data_nocopy(obj); 850 if (onp == NULL || prop_data_size(obj) != sizeof(npf_natpolicy_t)) { 851 return NULL; 852 } 853 854 /* 855 * Match if there is an existing NAT policy. Will acquire the 856 * reference on it if further operations are successful. 857 */ 858 KASSERT(npf_config_locked_p()); 859 rl = npf_ruleset_matchnat(npf_config_natset(), __UNCONST(onp)); 860 if (rl == NULL) { 861 return NULL; 862 } 863 np = npf_rule_getnat(rl); 864 KASSERT(np != NULL); 865 866 /* Take a specific port from port-map. */ 867 if (!npf_nat_takeport(np, ntraw->nt_tport)) { 868 return NULL; 869 } 870 atomic_inc_uint(&np->n_refcnt); 871 872 /* Create and return NAT entry for association. */ 873 nt = pool_cache_get(nat_cache, PR_WAITOK); 874 memcpy(nt, ntraw, sizeof(npf_nat_t)); 875 LIST_INSERT_HEAD(&np->n_nat_list, nt, nt_entry); 876 nt->nt_natpolicy = np; 877 nt->nt_session = se; 878 nt->nt_alg = NULL; 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