4 * Copyright (C) 2012 by Darren Reed.
6 * See the IPFILTER.LICENCE file for details on licencing.
8 #if defined(KERNEL) || defined(_KERNEL)
14 #include <sys/errno.h>
15 #include <sys/types.h>
16 #include <sys/param.h>
19 #if defined(_KERNEL) && \
20 (defined(__NetBSD_Version) && (__NetBSD_Version >= 399002000))
21 # include <sys/kauth.h>
34 #if defined(_KERNEL) && \
35 defined(__FreeBSD_version) && (__FreeBSD_version >= 220000)
36 # include <sys/filio.h>
37 # include <sys/fcntl.h>
39 # include <sys/ioctl.h>
42 # include <sys/fcntl.h>
45 # include <sys/protosw.h>
47 #include <sys/socket.h>
49 # include <sys/systm.h>
50 # if !defined(__SVR4) && !defined(__svr4__)
51 # include <sys/mbuf.h>
54 #if defined(__SVR4) || defined(__svr4__)
55 # include <sys/filio.h>
56 # include <sys/byteorder.h>
58 # include <sys/dditypes.h>
60 # include <sys/stream.h>
61 # include <sys/kmem.h>
63 #if __FreeBSD_version >= 300000
64 # include <sys/queue.h>
67 #if __FreeBSD_version >= 300000
68 # include <net/if_var.h>
73 #include <netinet/in.h>
74 #include <netinet/in_systm.h>
75 #include <netinet/ip.h>
79 # include <vpn/ipsec.h>
80 extern struct ifnet vpnif;
84 # include <netinet/ip_var.h>
86 #include <netinet/tcp.h>
87 #include <netinet/udp.h>
88 #include <netinet/ip_icmp.h>
89 #include "netinet/ip_compat.h"
90 #include <netinet/tcpip.h>
91 #include "netinet/ipl.h"
92 #include "netinet/ip_fil.h"
93 #include "netinet/ip_nat.h"
94 #include "netinet/ip_frag.h"
95 #include "netinet/ip_state.h"
96 #include "netinet/ip_proxy.h"
97 #include "netinet/ip_lookup.h"
98 #include "netinet/ip_dstlist.h"
99 #include "netinet/ip_sync.h"
100 #if FREEBSD_GE_REV(300000)
101 # include <sys/malloc.h>
104 # include <sys/md5.h>
108 /* END OF INCLUDES */
111 #define SOCKADDR_IN struct sockaddr_in
114 static const char sccsid[] = "@(#)ip_nat.c 1.11 6/5/96 (C) 1995 Darren Reed";
115 static const char rcsid[] = "@(#)$FreeBSD$";
116 /* static const char rcsid[] = "@(#)$Id: ip_nat.c,v 2.195.2.102 2007/10/16 10:08:10 darrenr Exp $"; */
120 #define NATFSUM(n,v,f) ((v) == 4 ? (n)->f.in4.s_addr : (n)->f.i6[0] + \
121 (n)->f.i6[1] + (n)->f.i6[2] + (n)->f.i6[3])
122 #define NBUMP(x) softn->(x)++
123 #define NBUMPD(x, y) do { \
127 #define NBUMPSIDE(y,x) softn->ipf_nat_stats.ns_side[y].x++
128 #define NBUMPSIDED(y,x) do { softn->ipf_nat_stats.ns_side[y].x++; \
130 #define NBUMPSIDEX(y,x,z) \
131 do { softn->ipf_nat_stats.ns_side[y].x++; \
133 #define NBUMPSIDEDF(y,x)do { softn->ipf_nat_stats.ns_side[y].x++; \
134 DT1(x, fr_info_t *, fin); } while (0)
136 static ipftuneable_t ipf_nat_tuneables[] = {
138 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_lock) },
140 stsizeof(ipf_nat_softc_t, ipf_nat_lock),
141 IPFT_RDONLY, NULL, NULL },
142 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_sz) },
143 "nat_table_size", 1, 0x7fffffff,
144 stsizeof(ipf_nat_softc_t, ipf_nat_table_sz),
145 0, NULL, ipf_nat_rehash },
146 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_max) },
147 "nat_table_max", 1, 0x7fffffff,
148 stsizeof(ipf_nat_softc_t, ipf_nat_table_max),
150 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_maprules_sz) },
151 "nat_rules_size", 1, 0x7fffffff,
152 stsizeof(ipf_nat_softc_t, ipf_nat_maprules_sz),
153 0, NULL, ipf_nat_rehash_rules },
154 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_rdrrules_sz) },
155 "rdr_rules_size", 1, 0x7fffffff,
156 stsizeof(ipf_nat_softc_t, ipf_nat_rdrrules_sz),
157 0, NULL, ipf_nat_rehash_rules },
158 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_hostmap_sz) },
159 "hostmap_size", 1, 0x7fffffff,
160 stsizeof(ipf_nat_softc_t, ipf_nat_hostmap_sz),
161 0, NULL, ipf_nat_hostmap_rehash },
162 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_maxbucket) },
163 "nat_maxbucket",1, 0x7fffffff,
164 stsizeof(ipf_nat_softc_t, ipf_nat_maxbucket),
166 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_logging) },
168 stsizeof(ipf_nat_softc_t, ipf_nat_logging),
170 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_doflush) },
172 stsizeof(ipf_nat_softc_t, ipf_nat_doflush),
174 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_wm_low) },
175 "nat_table_wm_low", 1, 99,
176 stsizeof(ipf_nat_softc_t, ipf_nat_table_wm_low),
178 { { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_wm_high) },
179 "nat_table_wm_high", 2, 100,
180 stsizeof(ipf_nat_softc_t, ipf_nat_table_wm_high),
188 /* ======================================================================== */
189 /* How the NAT is organised and works. */
191 /* Inside (interface y) NAT Outside (interface x) */
192 /* -------------------- -+- ------------------------------------- */
193 /* Packet going | out, processsed by ipf_nat_checkout() for x */
194 /* ------------> | ------------> */
195 /* src=10.1.1.1 | src=192.1.1.1 */
197 /* | in, processed by ipf_nat_checkin() for x */
198 /* <------------ | <------------ */
199 /* dst=10.1.1.1 | dst=192.1.1.1 */
200 /* -------------------- -+- ------------------------------------- */
201 /* ipf_nat_checkout() - changes ip_src and if required, sport */
202 /* - creates a new mapping, if required. */
203 /* ipf_nat_checkin() - changes ip_dst and if required, dport */
205 /* In the NAT table, internal source is recorded as "in" and externally */
207 /* ======================================================================== */
210 #if SOLARIS && !defined(INSTANCES)
211 extern int pfil_delayed_copy;
214 static int ipf_nat_flush_entry __P((ipf_main_softc_t *, void *));
215 static int ipf_nat_getent __P((ipf_main_softc_t *, caddr_t, int));
216 static int ipf_nat_getsz __P((ipf_main_softc_t *, caddr_t, int));
217 static int ipf_nat_putent __P((ipf_main_softc_t *, caddr_t, int));
218 static void ipf_nat_addmap __P((ipf_nat_softc_t *, ipnat_t *));
219 static void ipf_nat_addrdr __P((ipf_nat_softc_t *, ipnat_t *));
220 static int ipf_nat_builddivertmp __P((ipf_nat_softc_t *, ipnat_t *));
221 static int ipf_nat_clearlist __P((ipf_main_softc_t *, ipf_nat_softc_t *));
222 static int ipf_nat_cmp_rules __P((ipnat_t *, ipnat_t *));
223 static int ipf_nat_decap __P((fr_info_t *, nat_t *));
224 static void ipf_nat_delrule __P((ipf_main_softc_t *, ipf_nat_softc_t *,
226 static int ipf_nat_extraflush __P((ipf_main_softc_t *, ipf_nat_softc_t *, int));
227 static int ipf_nat_finalise __P((fr_info_t *, nat_t *));
228 static int ipf_nat_flushtable __P((ipf_main_softc_t *, ipf_nat_softc_t *));
229 static int ipf_nat_getnext __P((ipf_main_softc_t *, ipftoken_t *,
230 ipfgeniter_t *, ipfobj_t *));
231 static int ipf_nat_gettable __P((ipf_main_softc_t *, ipf_nat_softc_t *,
233 static hostmap_t *ipf_nat_hostmap __P((ipf_nat_softc_t *, ipnat_t *,
234 struct in_addr, struct in_addr,
235 struct in_addr, u_32_t));
236 static int ipf_nat_icmpquerytype __P((int));
237 static int ipf_nat_iterator __P((ipf_main_softc_t *, ipftoken_t *,
238 ipfgeniter_t *, ipfobj_t *));
239 static int ipf_nat_match __P((fr_info_t *, ipnat_t *));
240 static int ipf_nat_matcharray __P((nat_t *, int *, u_long));
241 static int ipf_nat_matchflush __P((ipf_main_softc_t *, ipf_nat_softc_t *,
243 static void ipf_nat_mssclamp __P((tcphdr_t *, u_32_t, fr_info_t *,
245 static int ipf_nat_newmap __P((fr_info_t *, nat_t *, natinfo_t *));
246 static int ipf_nat_newdivert __P((fr_info_t *, nat_t *, natinfo_t *));
247 static int ipf_nat_newrdr __P((fr_info_t *, nat_t *, natinfo_t *));
248 static int ipf_nat_newrewrite __P((fr_info_t *, nat_t *, natinfo_t *));
249 static int ipf_nat_nextaddr __P((fr_info_t *, nat_addr_t *, u_32_t *,
251 static int ipf_nat_nextaddrinit __P((ipf_main_softc_t *, char *,
252 nat_addr_t *, int, void *));
253 static int ipf_nat_resolverule __P((ipf_main_softc_t *, ipnat_t *));
254 static int ipf_nat_ruleaddrinit __P((ipf_main_softc_t *,
255 ipf_nat_softc_t *, ipnat_t *));
256 static void ipf_nat_rule_fini __P((ipf_main_softc_t *, ipnat_t *));
257 static int ipf_nat_rule_init __P((ipf_main_softc_t *, ipf_nat_softc_t *,
259 static int ipf_nat_siocaddnat __P((ipf_main_softc_t *, ipf_nat_softc_t *,
261 static void ipf_nat_siocdelnat __P((ipf_main_softc_t *, ipf_nat_softc_t *,
263 static void ipf_nat_tabmove __P((ipf_nat_softc_t *, nat_t *));
265 /* ------------------------------------------------------------------------ */
266 /* Function: ipf_nat_main_load */
267 /* Returns: int - 0 == success, -1 == failure */
268 /* Parameters: Nil */
270 /* The only global NAT structure that needs to be initialised is the filter */
271 /* rule that is used with blocking packets. */
272 /* ------------------------------------------------------------------------ */
281 /* ------------------------------------------------------------------------ */
282 /* Function: ipf_nat_main_unload */
283 /* Returns: int - 0 == success, -1 == failure */
284 /* Parameters: Nil */
286 /* A null-op function that exists as a placeholder so that the flow in */
287 /* other functions is obvious. */
288 /* ------------------------------------------------------------------------ */
290 ipf_nat_main_unload()
296 /* ------------------------------------------------------------------------ */
297 /* Function: ipf_nat_soft_create */
298 /* Returns: void * - NULL = failure, else pointer to NAT context */
299 /* Parameters: softc(I) - pointer to soft context main structure */
301 /* Allocate the initial soft context structure for NAT and populate it with */
302 /* some default values. Creating the tables is left until we call _init so */
303 /* that sizes can be changed before we get under way. */
304 /* ------------------------------------------------------------------------ */
306 ipf_nat_soft_create(softc)
307 ipf_main_softc_t *softc;
309 ipf_nat_softc_t *softn;
311 KMALLOC(softn, ipf_nat_softc_t *);
315 bzero((char *)softn, sizeof(*softn));
317 softn->ipf_nat_tune = ipf_tune_array_copy(softn,
318 sizeof(ipf_nat_tuneables),
320 if (softn->ipf_nat_tune == NULL) {
321 ipf_nat_soft_destroy(softc, softn);
324 if (ipf_tune_array_link(softc, softn->ipf_nat_tune) == -1) {
325 ipf_nat_soft_destroy(softc, softn);
329 softn->ipf_nat_list_tail = &softn->ipf_nat_list;
331 softn->ipf_nat_table_max = NAT_TABLE_MAX;
332 softn->ipf_nat_table_sz = NAT_TABLE_SZ;
333 softn->ipf_nat_maprules_sz = NAT_SIZE;
334 softn->ipf_nat_rdrrules_sz = RDR_SIZE;
335 softn->ipf_nat_hostmap_sz = HOSTMAP_SIZE;
336 softn->ipf_nat_doflush = 0;
338 softn->ipf_nat_logging = 1;
340 softn->ipf_nat_logging = 0;
343 softn->ipf_nat_defage = DEF_NAT_AGE;
344 softn->ipf_nat_defipage = IPF_TTLVAL(60);
345 softn->ipf_nat_deficmpage = IPF_TTLVAL(3);
346 softn->ipf_nat_table_wm_high = 99;
347 softn->ipf_nat_table_wm_low = 90;
352 /* ------------------------------------------------------------------------ */
353 /* Function: ipf_nat_soft_destroy */
355 /* Parameters: softc(I) - pointer to soft context main structure */
357 /* ------------------------------------------------------------------------ */
359 ipf_nat_soft_destroy(softc, arg)
360 ipf_main_softc_t *softc;
363 ipf_nat_softc_t *softn = arg;
365 if (softn->ipf_nat_tune != NULL) {
366 ipf_tune_array_unlink(softc, softn->ipf_nat_tune);
367 KFREES(softn->ipf_nat_tune, sizeof(ipf_nat_tuneables));
368 softn->ipf_nat_tune = NULL;
375 /* ------------------------------------------------------------------------ */
376 /* Function: ipf_nat_init */
377 /* Returns: int - 0 == success, -1 == failure */
378 /* Parameters: softc(I) - pointer to soft context main structure */
380 /* Initialise all of the NAT locks, tables and other structures. */
381 /* ------------------------------------------------------------------------ */
383 ipf_nat_soft_init(softc, arg)
384 ipf_main_softc_t *softc;
387 ipf_nat_softc_t *softn = arg;
391 KMALLOCS(softn->ipf_nat_table[0], nat_t **, \
392 sizeof(nat_t *) * softn->ipf_nat_table_sz);
394 if (softn->ipf_nat_table[0] != NULL) {
395 bzero((char *)softn->ipf_nat_table[0],
396 softn->ipf_nat_table_sz * sizeof(nat_t *));
401 KMALLOCS(softn->ipf_nat_table[1], nat_t **, \
402 sizeof(nat_t *) * softn->ipf_nat_table_sz);
404 if (softn->ipf_nat_table[1] != NULL) {
405 bzero((char *)softn->ipf_nat_table[1],
406 softn->ipf_nat_table_sz * sizeof(nat_t *));
411 KMALLOCS(softn->ipf_nat_map_rules, ipnat_t **, \
412 sizeof(ipnat_t *) * softn->ipf_nat_maprules_sz);
414 if (softn->ipf_nat_map_rules != NULL) {
415 bzero((char *)softn->ipf_nat_map_rules,
416 softn->ipf_nat_maprules_sz * sizeof(ipnat_t *));
421 KMALLOCS(softn->ipf_nat_rdr_rules, ipnat_t **, \
422 sizeof(ipnat_t *) * softn->ipf_nat_rdrrules_sz);
424 if (softn->ipf_nat_rdr_rules != NULL) {
425 bzero((char *)softn->ipf_nat_rdr_rules,
426 softn->ipf_nat_rdrrules_sz * sizeof(ipnat_t *));
431 KMALLOCS(softn->ipf_hm_maptable, hostmap_t **, \
432 sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
434 if (softn->ipf_hm_maptable != NULL) {
435 bzero((char *)softn->ipf_hm_maptable,
436 sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
440 softn->ipf_hm_maplist = NULL;
442 KMALLOCS(softn->ipf_nat_stats.ns_side[0].ns_bucketlen, u_int *,
443 softn->ipf_nat_table_sz * sizeof(u_int));
445 if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen == NULL) {
448 bzero((char *)softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
449 softn->ipf_nat_table_sz * sizeof(u_int));
451 KMALLOCS(softn->ipf_nat_stats.ns_side[1].ns_bucketlen, u_int *,
452 softn->ipf_nat_table_sz * sizeof(u_int));
454 if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen == NULL) {
458 bzero((char *)softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
459 softn->ipf_nat_table_sz * sizeof(u_int));
461 if (softn->ipf_nat_maxbucket == 0) {
462 for (i = softn->ipf_nat_table_sz; i > 0; i >>= 1)
463 softn->ipf_nat_maxbucket++;
464 softn->ipf_nat_maxbucket *= 2;
467 ipf_sttab_init(softc, softn->ipf_nat_tcptq);
469 * Increase this because we may have "keep state" following this too
470 * and packet storms can occur if this is removed too quickly.
472 softn->ipf_nat_tcptq[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcplastack;
473 softn->ipf_nat_tcptq[IPF_TCP_NSTATES - 1].ifq_next =
474 &softn->ipf_nat_udptq;
476 IPFTQ_INIT(&softn->ipf_nat_udptq, softn->ipf_nat_defage,
477 "nat ipftq udp tab");
478 softn->ipf_nat_udptq.ifq_next = &softn->ipf_nat_udpacktq;
480 IPFTQ_INIT(&softn->ipf_nat_udpacktq, softn->ipf_nat_defage,
481 "nat ipftq udpack tab");
482 softn->ipf_nat_udpacktq.ifq_next = &softn->ipf_nat_icmptq;
484 IPFTQ_INIT(&softn->ipf_nat_icmptq, softn->ipf_nat_deficmpage,
485 "nat icmp ipftq tab");
486 softn->ipf_nat_icmptq.ifq_next = &softn->ipf_nat_icmpacktq;
488 IPFTQ_INIT(&softn->ipf_nat_icmpacktq, softn->ipf_nat_defage,
489 "nat icmpack ipftq tab");
490 softn->ipf_nat_icmpacktq.ifq_next = &softn->ipf_nat_iptq;
492 IPFTQ_INIT(&softn->ipf_nat_iptq, softn->ipf_nat_defipage,
494 softn->ipf_nat_iptq.ifq_next = &softn->ipf_nat_pending;
496 IPFTQ_INIT(&softn->ipf_nat_pending, 1, "nat pending ipftq tab");
497 softn->ipf_nat_pending.ifq_next = NULL;
499 for (i = 0, tq = softn->ipf_nat_tcptq; i < IPF_TCP_NSTATES; i++, tq++) {
500 if (tq->ifq_ttl < softn->ipf_nat_deficmpage)
501 tq->ifq_ttl = softn->ipf_nat_deficmpage;
503 else if (tq->ifq_ttl > softn->ipf_nat_defage)
504 tq->ifq_ttl = softn->ipf_nat_defage;
509 * Increase this because we may have "keep state" following
510 * this too and packet storms can occur if this is removed
513 softn->ipf_nat_tcptq[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcplastack;
515 MUTEX_INIT(&softn->ipf_nat_new, "ipf nat new mutex");
516 MUTEX_INIT(&softn->ipf_nat_io, "ipf nat io mutex");
518 softn->ipf_nat_inited = 1;
524 /* ------------------------------------------------------------------------ */
525 /* Function: ipf_nat_soft_fini */
527 /* Parameters: softc(I) - pointer to soft context main structure */
529 /* Free all memory used by NAT structures allocated at runtime. */
530 /* ------------------------------------------------------------------------ */
532 ipf_nat_soft_fini(softc, arg)
533 ipf_main_softc_t *softc;
536 ipf_nat_softc_t *softn = arg;
537 ipftq_t *ifq, *ifqnext;
539 (void) ipf_nat_clearlist(softc, softn);
540 (void) ipf_nat_flushtable(softc, softn);
543 * Proxy timeout queues are not cleaned here because although they
544 * exist on the NAT list, ipf_proxy_unload is called after unload
545 * and the proxies actually are responsible for them being created.
546 * Should the proxy timeouts have their own list? There's no real
547 * justification as this is the only complication.
549 for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifqnext) {
550 ifqnext = ifq->ifq_next;
551 if (ipf_deletetimeoutqueue(ifq) == 0)
552 ipf_freetimeoutqueue(softc, ifq);
555 if (softn->ipf_nat_table[0] != NULL) {
556 KFREES(softn->ipf_nat_table[0],
557 sizeof(nat_t *) * softn->ipf_nat_table_sz);
558 softn->ipf_nat_table[0] = NULL;
560 if (softn->ipf_nat_table[1] != NULL) {
561 KFREES(softn->ipf_nat_table[1],
562 sizeof(nat_t *) * softn->ipf_nat_table_sz);
563 softn->ipf_nat_table[1] = NULL;
565 if (softn->ipf_nat_map_rules != NULL) {
566 KFREES(softn->ipf_nat_map_rules,
567 sizeof(ipnat_t *) * softn->ipf_nat_maprules_sz);
568 softn->ipf_nat_map_rules = NULL;
570 if (softn->ipf_nat_rdr_rules != NULL) {
571 KFREES(softn->ipf_nat_rdr_rules,
572 sizeof(ipnat_t *) * softn->ipf_nat_rdrrules_sz);
573 softn->ipf_nat_rdr_rules = NULL;
575 if (softn->ipf_hm_maptable != NULL) {
576 KFREES(softn->ipf_hm_maptable,
577 sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
578 softn->ipf_hm_maptable = NULL;
580 if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen != NULL) {
581 KFREES(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
582 sizeof(u_int) * softn->ipf_nat_table_sz);
583 softn->ipf_nat_stats.ns_side[0].ns_bucketlen = NULL;
585 if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen != NULL) {
586 KFREES(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
587 sizeof(u_int) * softn->ipf_nat_table_sz);
588 softn->ipf_nat_stats.ns_side[1].ns_bucketlen = NULL;
591 if (softn->ipf_nat_inited == 1) {
592 softn->ipf_nat_inited = 0;
593 ipf_sttab_destroy(softn->ipf_nat_tcptq);
595 MUTEX_DESTROY(&softn->ipf_nat_new);
596 MUTEX_DESTROY(&softn->ipf_nat_io);
598 MUTEX_DESTROY(&softn->ipf_nat_udptq.ifq_lock);
599 MUTEX_DESTROY(&softn->ipf_nat_udpacktq.ifq_lock);
600 MUTEX_DESTROY(&softn->ipf_nat_icmptq.ifq_lock);
601 MUTEX_DESTROY(&softn->ipf_nat_icmpacktq.ifq_lock);
602 MUTEX_DESTROY(&softn->ipf_nat_iptq.ifq_lock);
603 MUTEX_DESTROY(&softn->ipf_nat_pending.ifq_lock);
610 /* ------------------------------------------------------------------------ */
611 /* Function: ipf_nat_setlock */
613 /* Parameters: arg(I) - pointer to soft state information */
614 /* tmp(I) - new lock value */
616 /* Set the "lock status" of NAT to the value in tmp. */
617 /* ------------------------------------------------------------------------ */
619 ipf_nat_setlock(arg, tmp)
623 ipf_nat_softc_t *softn = arg;
625 softn->ipf_nat_lock = tmp;
629 /* ------------------------------------------------------------------------ */
630 /* Function: ipf_nat_addrdr */
632 /* Parameters: n(I) - pointer to NAT rule to add */
634 /* Adds a redirect rule to the hash table of redirect rules and the list of */
635 /* loaded NAT rules. Updates the bitmask indicating which netmasks are in */
636 /* use by redirect rules. */
637 /* ------------------------------------------------------------------------ */
639 ipf_nat_addrdr(softn, n)
640 ipf_nat_softc_t *softn;
649 if (n->in_odstatype == FRI_NORMAL) {
650 k = count4bits(n->in_odstmsk);
651 ipf_inet_mask_add(k, &softn->ipf_nat_rdr_mask);
652 j = (n->in_odstaddr & n->in_odstmsk);
653 rhv = NAT_HASH_FN(j, 0, 0xffffffff);
655 ipf_inet_mask_add(0, &softn->ipf_nat_rdr_mask);
659 hv = rhv % softn->ipf_nat_rdrrules_sz;
660 np = softn->ipf_nat_rdr_rules + hv;
662 np = &(*np)->in_rnext;
671 /* ------------------------------------------------------------------------ */
672 /* Function: ipf_nat_addmap */
674 /* Parameters: n(I) - pointer to NAT rule to add */
676 /* Adds a NAT map rule to the hash table of rules and the list of loaded */
677 /* NAT rules. Updates the bitmask indicating which netmasks are in use by */
678 /* redirect rules. */
679 /* ------------------------------------------------------------------------ */
681 ipf_nat_addmap(softn, n)
682 ipf_nat_softc_t *softn;
691 if (n->in_osrcatype == FRI_NORMAL) {
692 k = count4bits(n->in_osrcmsk);
693 ipf_inet_mask_add(k, &softn->ipf_nat_map_mask);
694 j = (n->in_osrcaddr & n->in_osrcmsk);
695 rhv = NAT_HASH_FN(j, 0, 0xffffffff);
697 ipf_inet_mask_add(0, &softn->ipf_nat_map_mask);
701 hv = rhv % softn->ipf_nat_maprules_sz;
702 np = softn->ipf_nat_map_rules + hv;
704 np = &(*np)->in_mnext;
713 /* ------------------------------------------------------------------------ */
714 /* Function: ipf_nat_delrdr */
716 /* Parameters: n(I) - pointer to NAT rule to delete */
718 /* Removes a redirect rule from the hash table of redirect rules. */
719 /* ------------------------------------------------------------------------ */
721 ipf_nat_delrdr(softn, n)
722 ipf_nat_softc_t *softn;
725 if (n->in_odstatype == FRI_NORMAL) {
726 int k = count4bits(n->in_odstmsk);
727 ipf_inet_mask_del(k, &softn->ipf_nat_rdr_mask);
729 ipf_inet_mask_del(0, &softn->ipf_nat_rdr_mask);
732 n->in_rnext->in_prnext = n->in_prnext;
733 *n->in_prnext = n->in_rnext;
738 /* ------------------------------------------------------------------------ */
739 /* Function: ipf_nat_delmap */
741 /* Parameters: n(I) - pointer to NAT rule to delete */
743 /* Removes a NAT map rule from the hash table of NAT map rules. */
744 /* ------------------------------------------------------------------------ */
746 ipf_nat_delmap(softn, n)
747 ipf_nat_softc_t *softn;
750 if (n->in_osrcatype == FRI_NORMAL) {
751 int k = count4bits(n->in_osrcmsk);
752 ipf_inet_mask_del(k, &softn->ipf_nat_map_mask);
754 ipf_inet_mask_del(0, &softn->ipf_nat_map_mask);
756 if (n->in_mnext != NULL)
757 n->in_mnext->in_pmnext = n->in_pmnext;
758 *n->in_pmnext = n->in_mnext;
763 /* ------------------------------------------------------------------------ */
764 /* Function: ipf_nat_hostmap */
765 /* Returns: struct hostmap* - NULL if no hostmap could be created, */
766 /* else a pointer to the hostmapping to use */
767 /* Parameters: np(I) - pointer to NAT rule */
768 /* real(I) - real IP address */
769 /* map(I) - mapped IP address */
770 /* port(I) - destination port number */
771 /* Write Locks: ipf_nat */
773 /* Check if an ip address has already been allocated for a given mapping */
774 /* that is not doing port based translation. If is not yet allocated, then */
775 /* create a new entry if a non-NULL NAT rule pointer has been supplied. */
776 /* ------------------------------------------------------------------------ */
777 static struct hostmap *
778 ipf_nat_hostmap(softn, np, src, dst, map, port)
779 ipf_nat_softc_t *softn;
789 hv = (src.s_addr ^ dst.s_addr);
793 hv %= softn->ipf_nat_hostmap_sz;
794 for (hm = softn->ipf_hm_maptable[hv]; hm; hm = hm->hm_hnext)
795 if ((hm->hm_osrcip.s_addr == src.s_addr) &&
796 (hm->hm_odstip.s_addr == dst.s_addr) &&
797 ((np == NULL) || (np == hm->hm_ipnat)) &&
798 ((port == 0) || (port == hm->hm_port))) {
799 softn->ipf_nat_stats.ns_hm_addref++;
805 softn->ipf_nat_stats.ns_hm_nullnp++;
809 KMALLOC(hm, hostmap_t *);
811 hm->hm_next = softn->ipf_hm_maplist;
812 hm->hm_pnext = &softn->ipf_hm_maplist;
813 if (softn->ipf_hm_maplist != NULL)
814 softn->ipf_hm_maplist->hm_pnext = &hm->hm_next;
815 softn->ipf_hm_maplist = hm;
816 hm->hm_hnext = softn->ipf_hm_maptable[hv];
817 hm->hm_phnext = softn->ipf_hm_maptable + hv;
818 if (softn->ipf_hm_maptable[hv] != NULL)
819 softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
820 softn->ipf_hm_maptable[hv] = hm;
826 hm->hm_ndstip.s_addr = 0;
831 softn->ipf_nat_stats.ns_hm_new++;
833 softn->ipf_nat_stats.ns_hm_newfail++;
839 /* ------------------------------------------------------------------------ */
840 /* Function: ipf_nat_hostmapdel */
842 /* Parameters: hmp(I) - pointer to hostmap structure pointer */
843 /* Write Locks: ipf_nat */
845 /* Decrement the references to this hostmap structure by one. If this */
846 /* reaches zero then remove it and free it. */
847 /* ------------------------------------------------------------------------ */
849 ipf_nat_hostmapdel(softc, hmp)
850 ipf_main_softc_t *softc;
851 struct hostmap **hmp;
859 if (hm->hm_ref == 0) {
860 ipf_nat_rule_deref(softc, &hm->hm_ipnat);
862 hm->hm_hnext->hm_phnext = hm->hm_phnext;
863 *hm->hm_phnext = hm->hm_hnext;
865 hm->hm_next->hm_pnext = hm->hm_pnext;
866 *hm->hm_pnext = hm->hm_next;
872 /* ------------------------------------------------------------------------ */
873 /* Function: ipf_fix_outcksum */
875 /* Parameters: fin(I) - pointer to packet information */
876 /* sp(I) - location of 16bit checksum to update */
877 /* n((I) - amount to adjust checksum by */
879 /* Adjusts the 16bit checksum by "n" for packets going out. */
880 /* ------------------------------------------------------------------------ */
882 ipf_fix_outcksum(cksum, sp, n, partial)
899 sum1 = (sum1 & 0xffff) + (sum1 >> 16);
903 sum1 = (~ntohs(*sp)) & 0xffff;
905 sum1 = (sum1 >> 16) + (sum1 & 0xffff);
907 sum1 = (sum1 >> 16) + (sum1 & 0xffff);
908 sumshort = ~(u_short)sum1;
909 *(sp) = htons(sumshort);
913 /* ------------------------------------------------------------------------ */
914 /* Function: ipf_fix_incksum */
916 /* Parameters: fin(I) - pointer to packet information */
917 /* sp(I) - location of 16bit checksum to update */
918 /* n((I) - amount to adjust checksum by */
920 /* Adjusts the 16bit checksum by "n" for packets going in. */
921 /* ------------------------------------------------------------------------ */
923 ipf_fix_incksum(cksum, sp, n, partial)
940 sum1 = (sum1 & 0xffff) + (sum1 >> 16);
945 sum1 = (~ntohs(*sp)) & 0xffff;
946 sum1 += ~(n) & 0xffff;
947 sum1 = (sum1 >> 16) + (sum1 & 0xffff);
949 sum1 = (sum1 >> 16) + (sum1 & 0xffff);
950 sumshort = ~(u_short)sum1;
951 *(sp) = htons(sumshort);
955 /* ------------------------------------------------------------------------ */
956 /* Function: ipf_fix_datacksum */
958 /* Parameters: sp(I) - location of 16bit checksum to update */
959 /* n((I) - amount to adjust checksum by */
961 /* Fix_datacksum is used *only* for the adjustments of checksums in the */
962 /* data section of an IP packet. */
964 /* The only situation in which you need to do this is when NAT'ing an */
965 /* ICMP error message. Such a message, contains in its body the IP header */
966 /* of the original IP packet, that causes the error. */
968 /* You can't use fix_incksum or fix_outcksum in that case, because for the */
969 /* kernel the data section of the ICMP error is just data, and no special */
970 /* processing like hardware cksum or ntohs processing have been done by the */
971 /* kernel on the data section. */
972 /* ------------------------------------------------------------------------ */
974 ipf_fix_datacksum(sp, n)
984 sum1 = (~ntohs(*sp)) & 0xffff;
986 sum1 = (sum1 >> 16) + (sum1 & 0xffff);
988 sum1 = (sum1 >> 16) + (sum1 & 0xffff);
989 sumshort = ~(u_short)sum1;
990 *(sp) = htons(sumshort);
994 /* ------------------------------------------------------------------------ */
995 /* Function: ipf_nat_ioctl */
996 /* Returns: int - 0 == success, != 0 == failure */
997 /* Parameters: softc(I) - pointer to soft context main structure */
998 /* data(I) - pointer to ioctl data */
999 /* cmd(I) - ioctl command integer */
1000 /* mode(I) - file mode bits used with open */
1001 /* uid(I) - uid of calling process */
1002 /* ctx(I) - pointer used as key for finding context */
1004 /* Processes an ioctl call made to operate on the IP Filter NAT device. */
1005 /* ------------------------------------------------------------------------ */
1007 ipf_nat_ioctl(softc, data, cmd, mode, uid, ctx)
1008 ipf_main_softc_t *softc;
1014 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
1015 int error = 0, ret, arg, getlock;
1016 ipnat_t *nat, *nt, *n;
1020 #if BSD_GE_YEAR(199306) && defined(_KERNEL)
1021 # if NETBSD_GE_REV(399002000)
1022 if ((mode & FWRITE) &&
1023 kauth_authorize_network(curlwp->l_cred, KAUTH_NETWORK_FIREWALL,
1024 KAUTH_REQ_NETWORK_FIREWALL_FW,
1027 # if defined(__FreeBSD_version) && (__FreeBSD_version >= 500034)
1028 if (securelevel_ge(curthread->td_ucred, 3) && (mode & FWRITE))
1030 if ((securelevel >= 3) && (mode & FWRITE))
1039 #if defined(__osf__) && defined(_KERNEL)
1042 getlock = (mode & NAT_LOCKHELD) ? 0 : 1;
1049 if ((cmd == (ioctlcmd_t)SIOCADNAT) || (cmd == (ioctlcmd_t)SIOCRMNAT) ||
1050 (cmd == (ioctlcmd_t)SIOCPURGENAT)) {
1051 if (mode & NAT_SYSSPACE) {
1052 bcopy(data, (char *)&natd, sizeof(natd));
1056 bzero(&natd, sizeof(natd));
1057 error = ipf_inobj(softc, data, NULL, &natd,
1062 if (natd.in_size < sizeof(ipnat_t)) {
1066 KMALLOCS(nt, ipnat_t *, natd.in_size);
1072 bzero(nt, natd.in_size);
1073 error = ipf_inobjsz(softc, data, nt, IPFOBJ_IPNAT,
1081 * For add/delete, look to see if the NAT entry is
1084 nat->in_flags &= IPN_USERFLAGS;
1085 if ((nat->in_redir & NAT_MAPBLK) == 0) {
1086 if (nat->in_osrcatype == FRI_NORMAL ||
1087 nat->in_osrcatype == FRI_NONE)
1088 nat->in_osrcaddr &= nat->in_osrcmsk;
1089 if (nat->in_odstatype == FRI_NORMAL ||
1090 nat->in_odstatype == FRI_NONE)
1091 nat->in_odstaddr &= nat->in_odstmsk;
1092 if ((nat->in_flags & (IPN_SPLIT|IPN_SIPRANGE)) == 0) {
1093 if (nat->in_nsrcatype == FRI_NORMAL)
1094 nat->in_nsrcaddr &= nat->in_nsrcmsk;
1095 if (nat->in_ndstatype == FRI_NORMAL)
1096 nat->in_ndstaddr &= nat->in_ndstmsk;
1100 error = ipf_nat_rule_init(softc, softn, nat);
1104 MUTEX_ENTER(&softn->ipf_nat_io);
1105 for (n = softn->ipf_nat_list; n != NULL; n = n->in_next)
1106 if (ipf_nat_cmp_rules(nat, n) == 0)
1117 if (!(mode & FWRITE)) {
1121 tmp = ipf_log_clear(softc, IPL_LOGNAT);
1122 error = BCOPYOUT(&tmp, data, sizeof(tmp));
1132 if (!(mode & FWRITE)) {
1136 error = BCOPYIN(data, &softn->ipf_nat_logging,
1137 sizeof(softn->ipf_nat_logging));
1144 error = BCOPYOUT(&softn->ipf_nat_logging, data,
1145 sizeof(softn->ipf_nat_logging));
1153 arg = ipf_log_bytesused(softc, IPL_LOGNAT);
1154 error = BCOPYOUT(&arg, data, sizeof(arg));
1162 if (!(mode & FWRITE)) {
1165 } else if (n != NULL) {
1166 natd.in_flineno = n->in_flineno;
1167 (void) ipf_outobj(softc, data, &natd, IPFOBJ_IPNAT);
1170 } else if (nt == NULL) {
1175 MUTEX_EXIT(&softn->ipf_nat_io);
1179 bcopy((char *)nat, (char *)nt, sizeof(*n));
1180 error = ipf_nat_siocaddnat(softc, softn, nt, getlock);
1181 MUTEX_EXIT(&softn->ipf_nat_io);
1190 if (!(mode & FWRITE)) {
1194 } else if (n == NULL) {
1200 MUTEX_EXIT(&softn->ipf_nat_io);
1203 if (cmd == (ioctlcmd_t)SIOCPURGENAT) {
1204 error = ipf_outobjsz(softc, data, n, IPFOBJ_IPNAT,
1207 MUTEX_EXIT(&softn->ipf_nat_io);
1210 n->in_flags |= IPN_PURGE;
1212 ipf_nat_siocdelnat(softc, softn, n, getlock);
1214 MUTEX_EXIT(&softn->ipf_nat_io);
1220 natstat_t *nsp = &softn->ipf_nat_stats;
1222 nsp->ns_side[0].ns_table = softn->ipf_nat_table[0];
1223 nsp->ns_side[1].ns_table = softn->ipf_nat_table[1];
1224 nsp->ns_list = softn->ipf_nat_list;
1225 nsp->ns_maptable = softn->ipf_hm_maptable;
1226 nsp->ns_maplist = softn->ipf_hm_maplist;
1227 nsp->ns_nattab_sz = softn->ipf_nat_table_sz;
1228 nsp->ns_nattab_max = softn->ipf_nat_table_max;
1229 nsp->ns_rultab_sz = softn->ipf_nat_maprules_sz;
1230 nsp->ns_rdrtab_sz = softn->ipf_nat_rdrrules_sz;
1231 nsp->ns_hostmap_sz = softn->ipf_nat_hostmap_sz;
1232 nsp->ns_instances = softn->ipf_nat_instances;
1233 nsp->ns_ticks = softc->ipf_ticks;
1234 #ifdef IPFILTER_LOGGING
1235 nsp->ns_log_ok = ipf_log_logok(softc, IPF_LOGNAT);
1236 nsp->ns_log_fail = ipf_log_failures(softc, IPF_LOGNAT);
1239 nsp->ns_log_fail = 0;
1241 error = ipf_outobj(softc, data, nsp, IPFOBJ_NATSTAT);
1249 error = ipf_inobj(softc, data, NULL, &nl, IPFOBJ_NATLOOKUP);
1254 READ_ENTER(&softc->ipf_nat);
1260 ptr = ipf_nat_lookupredir(&nl);
1264 ptr = ipf_nat6_lookupredir(&nl);
1273 RWLOCK_EXIT(&softc->ipf_nat);
1276 error = ipf_outobj(softc, data, &nl,
1286 case SIOCIPFFL : /* old SIOCFLNAT & SIOCCNATL */
1287 if (!(mode & FWRITE)) {
1293 WRITE_ENTER(&softc->ipf_nat);
1296 error = BCOPYIN(data, &arg, sizeof(arg));
1302 ret = ipf_nat_flushtable(softc, softn);
1304 ret = ipf_nat_clearlist(softc, softn);
1306 ret = ipf_nat_extraflush(softc, softn, arg);
1307 ipf_proxy_flush(softc->ipf_proxy_soft, arg);
1311 RWLOCK_EXIT(&softc->ipf_nat);
1314 error = BCOPYOUT(&ret, data, sizeof(ret));
1318 case SIOCMATCHFLUSH :
1319 if (!(mode & FWRITE)) {
1325 WRITE_ENTER(&softc->ipf_nat);
1328 error = ipf_nat_matchflush(softc, softn, data);
1331 RWLOCK_EXIT(&softc->ipf_nat);
1336 error = ipf_proxy_ioctl(softc, data, cmd, mode, ctx);
1340 if (!(mode & FWRITE)) {
1344 error = ipf_lock(data, &softn->ipf_nat_lock);
1349 if ((mode & FWRITE) != 0) {
1350 error = ipf_nat_putent(softc, data, getlock);
1358 if (softn->ipf_nat_lock) {
1359 error = ipf_nat_getsz(softc, data, getlock);
1367 if (softn->ipf_nat_lock) {
1368 error = ipf_nat_getent(softc, data, getlock);
1381 error = ipf_inobj(softc, data, &obj, &iter, IPFOBJ_GENITER);
1386 token = ipf_token_find(softc, iter.igi_type, uid, ctx);
1387 if (token != NULL) {
1388 error = ipf_nat_iterator(softc, token, &iter, &obj);
1389 WRITE_ENTER(&softc->ipf_tokens);
1390 ipf_token_deref(softc, token);
1391 RWLOCK_EXIT(&softc->ipf_tokens);
1397 case SIOCIPFDELTOK :
1398 error = BCOPYIN(data, &arg, sizeof(arg));
1401 error = ipf_token_del(softc, arg, uid, ctx);
1410 error = ipf_outobj(softc, data, softn->ipf_nat_tcptq,
1415 error = ipf_nat_gettable(softc, softn, data);
1425 ipf_nat_rule_fini(softc, nat);
1427 KFREES(nt, nt->in_size);
1432 /* ------------------------------------------------------------------------ */
1433 /* Function: ipf_nat_siocaddnat */
1434 /* Returns: int - 0 == success, != 0 == failure */
1435 /* Parameters: softc(I) - pointer to soft context main structure */
1436 /* softn(I) - pointer to NAT context structure */
1437 /* n(I) - pointer to new NAT rule */
1438 /* np(I) - pointer to where to insert new NAT rule */
1439 /* getlock(I) - flag indicating if lock on is held */
1440 /* Mutex Locks: ipf_nat_io */
1442 /* Handle SIOCADNAT. Resolve and calculate details inside the NAT rule */
1443 /* from information passed to the kernel, then add it to the appropriate */
1444 /* NAT rule table(s). */
1445 /* ------------------------------------------------------------------------ */
1447 ipf_nat_siocaddnat(softc, softn, n, getlock)
1448 ipf_main_softc_t *softc;
1449 ipf_nat_softc_t *softn;
1455 if (ipf_nat_resolverule(softc, n) != 0) {
1460 if ((n->in_age[0] == 0) && (n->in_age[1] != 0)) {
1465 if (n->in_redir == (NAT_DIVERTUDP|NAT_MAP)) {
1467 * Prerecord whether or not the destination of the divert
1468 * is local or not to the interface the packet is going
1471 n->in_dlocal = ipf_deliverlocal(softc, n->in_v[1],
1472 n->in_ifps[1], &n->in_ndstip6);
1476 WRITE_ENTER(&softc->ipf_nat);
1479 n->in_pnext = softn->ipf_nat_list_tail;
1481 softn->ipf_nat_list_tail = &n->in_next;
1484 if (n->in_redir & NAT_REDIRECT) {
1485 n->in_flags &= ~IPN_NOTDST;
1489 ipf_nat_addrdr(softn, n);
1493 ipf_nat6_addrdr(softn, n);
1499 ATOMIC_INC32(softn->ipf_nat_stats.ns_rules_rdr);
1502 if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
1503 n->in_flags &= ~IPN_NOTSRC;
1507 ipf_nat_addmap(softn, n);
1511 ipf_nat6_addmap(softn, n);
1517 ATOMIC_INC32(softn->ipf_nat_stats.ns_rules_map);
1520 if (n->in_age[0] != 0)
1521 n->in_tqehead[0] = ipf_addtimeoutqueue(softc,
1522 &softn->ipf_nat_utqe,
1525 if (n->in_age[1] != 0)
1526 n->in_tqehead[1] = ipf_addtimeoutqueue(softc,
1527 &softn->ipf_nat_utqe,
1530 MUTEX_INIT(&n->in_lock, "ipnat rule lock");
1533 ATOMIC_INC32(softn->ipf_nat_stats.ns_rules);
1534 #if SOLARIS && !defined(INSTANCES)
1535 pfil_delayed_copy = 0;
1538 RWLOCK_EXIT(&softc->ipf_nat); /* WRITE */
1545 /* ------------------------------------------------------------------------ */
1546 /* Function: ipf_nat_ruleaddrinit */
1547 /* Parameters: softc(I) - pointer to soft context main structure */
1548 /* softn(I) - pointer to NAT context structure */
1549 /* n(I) - pointer to NAT rule */
1551 /* Initialise all of the NAT address structures in a NAT rule. */
1552 /* ------------------------------------------------------------------------ */
1554 ipf_nat_ruleaddrinit(softc, softn, n)
1555 ipf_main_softc_t *softc;
1556 ipf_nat_softc_t *softn;
1561 if ((n->in_ndst.na_atype == FRI_LOOKUP) &&
1562 (n->in_ndst.na_type != IPLT_DSTLIST)) {
1566 if ((n->in_nsrc.na_atype == FRI_LOOKUP) &&
1567 (n->in_nsrc.na_type != IPLT_DSTLIST)) {
1572 if (n->in_redir == NAT_BIMAP) {
1573 n->in_ndstaddr = n->in_osrcaddr;
1574 n->in_ndstmsk = n->in_osrcmsk;
1575 n->in_odstaddr = n->in_nsrcaddr;
1576 n->in_odstmsk = n->in_nsrcmsk;
1580 if (n->in_redir & NAT_REDIRECT)
1585 * Initialise all of the address fields.
1587 error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_osrc, 1,
1592 error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_odst, 1,
1597 error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_nsrc, 1,
1602 error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_ndst, 1,
1607 if (n->in_redir & NAT_DIVERTUDP)
1608 ipf_nat_builddivertmp(softn, n);
1614 /* ------------------------------------------------------------------------ */
1615 /* Function: ipf_nat_resolvrule */
1617 /* Parameters: softc(I) - pointer to soft context main structure */
1618 /* n(I) - pointer to NAT rule */
1620 /* Handle SIOCADNAT. Resolve and calculate details inside the NAT rule */
1621 /* from information passed to the kernel, then add it to the appropriate */
1622 /* NAT rule table(s). */
1623 /* ------------------------------------------------------------------------ */
1625 ipf_nat_resolverule(softc, n)
1626 ipf_main_softc_t *softc;
1633 n->in_ifps[0] = ipf_resolvenic(softc, base + n->in_ifnames[0],
1636 if (n->in_ifnames[1] == -1) {
1637 n->in_ifnames[1] = n->in_ifnames[0];
1638 n->in_ifps[1] = n->in_ifps[0];
1640 n->in_ifps[1] = ipf_resolvenic(softc, base + n->in_ifnames[1],
1644 if (n->in_plabel != -1) {
1645 if (n->in_redir & NAT_REDIRECT)
1646 n->in_apr = ipf_proxy_lookup(softc->ipf_proxy_soft,
1648 base + n->in_plabel);
1650 n->in_apr = ipf_proxy_lookup(softc->ipf_proxy_soft,
1652 base + n->in_plabel);
1653 if (n->in_apr == NULL)
1660 /* ------------------------------------------------------------------------ */
1661 /* Function: ipf_nat_siocdelnat */
1662 /* Returns: int - 0 == success, != 0 == failure */
1663 /* Parameters: softc(I) - pointer to soft context main structure */
1664 /* softn(I) - pointer to NAT context structure */
1665 /* n(I) - pointer to new NAT rule */
1666 /* getlock(I) - flag indicating if lock on is held */
1667 /* Mutex Locks: ipf_nat_io */
1669 /* Handle SIOCADNAT. Resolve and calculate details inside the NAT rule */
1670 /* from information passed to the kernel, then add it to the appropriate */
1671 /* NAT rule table(s). */
1672 /* ------------------------------------------------------------------------ */
1674 ipf_nat_siocdelnat(softc, softn, n, getlock)
1675 ipf_main_softc_t *softc;
1676 ipf_nat_softc_t *softn;
1681 WRITE_ENTER(&softc->ipf_nat);
1684 ipf_nat_delrule(softc, softn, n, 1);
1687 RWLOCK_EXIT(&softc->ipf_nat); /* READ/WRITE */
1692 /* ------------------------------------------------------------------------ */
1693 /* Function: ipf_nat_getsz */
1694 /* Returns: int - 0 == success, != 0 is the error value. */
1695 /* Parameters: softc(I) - pointer to soft context main structure */
1696 /* data(I) - pointer to natget structure with kernel */
1697 /* pointer get the size of. */
1698 /* getlock(I) - flag indicating whether or not the caller */
1699 /* holds a lock on ipf_nat */
1701 /* Handle SIOCSTGSZ. */
1702 /* Return the size of the nat list entry to be copied back to user space. */
1703 /* The size of the entry is stored in the ng_sz field and the enture natget */
1704 /* structure is copied back to the user. */
1705 /* ------------------------------------------------------------------------ */
1707 ipf_nat_getsz(softc, data, getlock)
1708 ipf_main_softc_t *softc;
1712 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
1718 error = BCOPYIN(data, &ng, sizeof(ng));
1725 READ_ENTER(&softc->ipf_nat);
1730 nat = softn->ipf_nat_instances;
1733 * Empty list so the size returned is 0. Simple.
1737 RWLOCK_EXIT(&softc->ipf_nat);
1739 error = BCOPYOUT(&ng, data, sizeof(ng));
1748 * Make sure the pointer we're copying from exists in the
1749 * current list of entries. Security precaution to prevent
1750 * copying of random kernel data.
1752 for (n = softn->ipf_nat_instances; n; n = n->nat_next)
1757 RWLOCK_EXIT(&softc->ipf_nat);
1765 * Incluse any space required for proxy data structures.
1767 ng.ng_sz = sizeof(nat_save_t);
1770 ng.ng_sz += sizeof(ap_session_t) - 4;
1771 if (aps->aps_data != 0)
1772 ng.ng_sz += aps->aps_psiz;
1775 RWLOCK_EXIT(&softc->ipf_nat);
1778 error = BCOPYOUT(&ng, data, sizeof(ng));
1787 /* ------------------------------------------------------------------------ */
1788 /* Function: ipf_nat_getent */
1789 /* Returns: int - 0 == success, != 0 is the error value. */
1790 /* Parameters: softc(I) - pointer to soft context main structure */
1791 /* data(I) - pointer to natget structure with kernel pointer*/
1792 /* to NAT structure to copy out. */
1793 /* getlock(I) - flag indicating whether or not the caller */
1794 /* holds a lock on ipf_nat */
1796 /* Handle SIOCSTGET. */
1797 /* Copies out NAT entry to user space. Any additional data held for a */
1798 /* proxy is also copied, as to is the NAT rule which was responsible for it */
1799 /* ------------------------------------------------------------------------ */
1801 ipf_nat_getent(softc, data, getlock)
1802 ipf_main_softc_t *softc;
1806 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
1809 nat_save_t *ipn, ipns;
1812 error = ipf_inobj(softc, data, NULL, &ipns, IPFOBJ_NATSAVE);
1816 if ((ipns.ipn_dsize < sizeof(ipns)) || (ipns.ipn_dsize > 81920)) {
1821 KMALLOCS(ipn, nat_save_t *, ipns.ipn_dsize);
1828 READ_ENTER(&softc->ipf_nat);
1831 ipn->ipn_dsize = ipns.ipn_dsize;
1832 nat = ipns.ipn_next;
1834 nat = softn->ipf_nat_instances;
1836 if (softn->ipf_nat_instances == NULL) {
1844 * Make sure the pointer we're copying from exists in the
1845 * current list of entries. Security precaution to prevent
1846 * copying of random kernel data.
1848 for (n = softn->ipf_nat_instances; n; n = n->nat_next)
1857 ipn->ipn_next = nat->nat_next;
1860 * Copy the NAT structure.
1862 bcopy((char *)nat, &ipn->ipn_nat, sizeof(*nat));
1865 * If we have a pointer to the NAT rule it belongs to, save that too.
1867 if (nat->nat_ptr != NULL)
1868 bcopy((char *)nat->nat_ptr, (char *)&ipn->ipn_ipnat,
1869 ipn->ipn_ipnat.in_size);
1872 * If we also know the NAT entry has an associated filter rule,
1875 if (nat->nat_fr != NULL)
1876 bcopy((char *)nat->nat_fr, (char *)&ipn->ipn_fr,
1877 sizeof(ipn->ipn_fr));
1880 * Last but not least, if there is an application proxy session set
1881 * up for this NAT entry, then copy that out too, including any
1882 * private data saved along side it by the proxy.
1885 outsize = ipn->ipn_dsize - sizeof(*ipn) + sizeof(ipn->ipn_data);
1889 if (outsize < sizeof(*aps)) {
1896 bcopy((char *)aps, s, sizeof(*aps));
1898 outsize -= sizeof(*aps);
1899 if ((aps->aps_data != NULL) && (outsize >= aps->aps_psiz))
1900 bcopy(aps->aps_data, s, aps->aps_psiz);
1908 READ_ENTER(&softc->ipf_nat);
1911 error = ipf_outobjsz(softc, data, ipn, IPFOBJ_NATSAVE,
1917 READ_ENTER(&softc->ipf_nat);
1920 KFREES(ipn, ipns.ipn_dsize);
1926 /* ------------------------------------------------------------------------ */
1927 /* Function: ipf_nat_putent */
1928 /* Returns: int - 0 == success, != 0 is the error value. */
1929 /* Parameters: softc(I) - pointer to soft context main structure */
1930 /* data(I) - pointer to natget structure with NAT */
1931 /* structure information to load into the kernel */
1932 /* getlock(I) - flag indicating whether or not a write lock */
1933 /* on is already held. */
1935 /* Handle SIOCSTPUT. */
1936 /* Loads a NAT table entry from user space, including a NAT rule, proxy and */
1937 /* firewall rule data structures, if pointers to them indicate so. */
1938 /* ------------------------------------------------------------------------ */
1940 ipf_nat_putent(softc, data, getlock)
1941 ipf_main_softc_t *softc;
1945 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
1946 nat_save_t ipn, *ipnn;
1954 error = ipf_inobj(softc, data, NULL, &ipn, IPFOBJ_NATSAVE);
1959 * Initialise early because of code at junkput label.
1969 * New entry, copy in the rest of the NAT entry if it's size is more
1970 * than just the nat_t structure.
1972 if (ipn.ipn_dsize > sizeof(ipn)) {
1973 if (ipn.ipn_dsize > 81920) {
1979 KMALLOCS(ipnn, nat_save_t *, ipn.ipn_dsize);
1985 bzero(ipnn, ipn.ipn_dsize);
1986 error = ipf_inobjsz(softc, data, ipnn, IPFOBJ_NATSAVE,
1994 KMALLOC(nat, nat_t *);
2001 bcopy((char *)&ipnn->ipn_nat, (char *)nat, sizeof(*nat));
2003 switch (nat->nat_v[0])
2012 error = EPROTONOSUPPORT;
2018 * Initialize all these so that ipf_nat_delete() doesn't cause a crash.
2020 bzero((char *)nat, offsetof(struct nat, nat_tqe));
2021 nat->nat_tqe.tqe_pnext = NULL;
2022 nat->nat_tqe.tqe_next = NULL;
2023 nat->nat_tqe.tqe_ifq = NULL;
2024 nat->nat_tqe.tqe_parent = nat;
2027 * Restore the rule associated with this nat session
2029 in = ipnn->ipn_nat.nat_ptr;
2031 KMALLOCS(in, ipnat_t *, ipnn->ipn_ipnat.in_size);
2038 bcopy((char *)&ipnn->ipn_ipnat, (char *)in,
2039 ipnn->ipn_ipnat.in_size);
2041 in->in_flags |= IPN_DELETE;
2043 ATOMIC_INC32(softn->ipf_nat_stats.ns_rules);
2045 if (ipf_nat_resolverule(softc, in) != 0) {
2053 * Check that the NAT entry doesn't already exist in the kernel.
2055 * For NAT_OUTBOUND, we're lookup for a duplicate MAP entry. To do
2056 * this, we check to see if the inbound combination of addresses and
2057 * ports is already known. Similar logic is applied for NAT_INBOUND.
2060 bzero((char *)&fin, sizeof(fin));
2061 fin.fin_v = nat->nat_v[0];
2062 fin.fin_p = nat->nat_pr[0];
2063 fin.fin_rev = nat->nat_rev;
2064 fin.fin_ifp = nat->nat_ifps[0];
2065 fin.fin_data[0] = ntohs(nat->nat_ndport);
2066 fin.fin_data[1] = ntohs(nat->nat_nsport);
2068 switch (nat->nat_dir)
2071 case NAT_DIVERTOUT :
2073 READ_ENTER(&softc->ipf_nat);
2076 fin.fin_v = nat->nat_v[1];
2077 if (nat->nat_v[1] == 4) {
2078 n = ipf_nat_inlookup(&fin, nat->nat_flags, fin.fin_p,
2079 nat->nat_ndstip, nat->nat_nsrcip);
2081 } else if (nat->nat_v[1] == 6) {
2082 n = ipf_nat6_inlookup(&fin, nat->nat_flags, fin.fin_p,
2083 &nat->nat_ndst6.in6,
2084 &nat->nat_nsrc6.in6);
2089 RWLOCK_EXIT(&softc->ipf_nat);
2101 READ_ENTER(&softc->ipf_nat);
2104 if (fin.fin_v == 4) {
2105 n = ipf_nat_outlookup(&fin, nat->nat_flags, fin.fin_p,
2109 } else if (fin.fin_v == 6) {
2110 n = ipf_nat6_outlookup(&fin, nat->nat_flags, fin.fin_p,
2111 &nat->nat_ndst6.in6,
2112 &nat->nat_nsrc6.in6);
2117 RWLOCK_EXIT(&softc->ipf_nat);
2133 * Restore ap_session_t structure. Include the private data allocated
2138 KMALLOC(aps, ap_session_t *);
2145 bcopy(ipnn->ipn_data, (char *)aps, sizeof(*aps));
2147 aps->aps_apr = in->in_apr;
2149 aps->aps_apr = NULL;
2150 if (aps->aps_psiz != 0) {
2151 if (aps->aps_psiz > 81920) {
2156 KMALLOCS(aps->aps_data, void *, aps->aps_psiz);
2157 if (aps->aps_data == NULL) {
2162 bcopy(ipnn->ipn_data + sizeof(*aps), aps->aps_data,
2166 aps->aps_data = NULL;
2171 * If there was a filtering rule associated with this entry then
2172 * build up a new one.
2176 if ((nat->nat_flags & SI_NEWFR) != 0) {
2177 KMALLOC(fr, frentry_t *);
2184 ipnn->ipn_nat.nat_fr = fr;
2186 (void) ipf_outobj(softc, data, ipnn, IPFOBJ_NATSAVE);
2187 bcopy((char *)&ipnn->ipn_fr, (char *)fr, sizeof(*fr));
2192 fr->fr_type = FR_T_NONE;
2194 MUTEX_NUKE(&fr->fr_lock);
2195 MUTEX_INIT(&fr->fr_lock, "nat-filter rule lock");
2198 READ_ENTER(&softc->ipf_nat);
2200 for (n = softn->ipf_nat_instances; n; n = n->nat_next)
2201 if (n->nat_fr == fr)
2205 MUTEX_ENTER(&fr->fr_lock);
2207 MUTEX_EXIT(&fr->fr_lock);
2210 RWLOCK_EXIT(&softc->ipf_nat);
2222 KFREES(ipnn, ipn.ipn_dsize);
2227 WRITE_ENTER(&softc->ipf_nat);
2231 error = ipf_nat_finalise(&fin, nat);
2234 error = ipf_nat6_finalise(&fin, nat);
2238 RWLOCK_EXIT(&softc->ipf_nat);
2249 (void) ipf_derefrule(softc, &fr);
2252 if ((ipnn != NULL) && (ipnn != &ipn)) {
2253 KFREES(ipnn, ipn.ipn_dsize);
2257 if (aps->aps_data != NULL) {
2258 KFREES(aps->aps_data, aps->aps_psiz);
2264 ipf_proxy_deref(in->in_apr);
2265 KFREES(in, in->in_size);
2273 /* ------------------------------------------------------------------------ */
2274 /* Function: ipf_nat_delete */
2276 /* Parameters: softc(I) - pointer to soft context main structure */
2277 /* nat(I) - pointer to NAT structure to delete */
2278 /* logtype(I) - type of LOG record to create before deleting */
2279 /* Write Lock: ipf_nat */
2281 /* Delete a nat entry from the various lists and table. If NAT logging is */
2282 /* enabled then generate a NAT log record for this event. */
2283 /* ------------------------------------------------------------------------ */
2285 ipf_nat_delete(softc, nat, logtype)
2286 ipf_main_softc_t *softc;
2290 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
2291 int madeorphan = 0, bkt, removed = 0;
2292 nat_stat_side_t *nss;
2295 if (logtype != 0 && softn->ipf_nat_logging != 0)
2296 ipf_nat_log(softc, softn, nat, logtype);
2299 * Take it as a general indication that all the pointers are set if
2302 if (nat->nat_pnext != NULL) {
2305 bkt = nat->nat_hv[0] % softn->ipf_nat_table_sz;
2306 nss = &softn->ipf_nat_stats.ns_side[0];
2307 nss->ns_bucketlen[bkt]--;
2308 if (nss->ns_bucketlen[bkt] == 0) {
2312 bkt = nat->nat_hv[1] % softn->ipf_nat_table_sz;
2313 nss = &softn->ipf_nat_stats.ns_side[1];
2314 nss->ns_bucketlen[bkt]--;
2315 if (nss->ns_bucketlen[bkt] == 0) {
2319 *nat->nat_pnext = nat->nat_next;
2320 if (nat->nat_next != NULL) {
2321 nat->nat_next->nat_pnext = nat->nat_pnext;
2322 nat->nat_next = NULL;
2324 nat->nat_pnext = NULL;
2326 *nat->nat_phnext[0] = nat->nat_hnext[0];
2327 if (nat->nat_hnext[0] != NULL) {
2328 nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
2329 nat->nat_hnext[0] = NULL;
2331 nat->nat_phnext[0] = NULL;
2333 *nat->nat_phnext[1] = nat->nat_hnext[1];
2334 if (nat->nat_hnext[1] != NULL) {
2335 nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
2336 nat->nat_hnext[1] = NULL;
2338 nat->nat_phnext[1] = NULL;
2340 if ((nat->nat_flags & SI_WILDP) != 0) {
2341 ATOMIC_DEC32(softn->ipf_nat_stats.ns_wilds);
2346 if (nat->nat_me != NULL) {
2347 *nat->nat_me = NULL;
2350 ASSERT(nat->nat_ref >= 0);
2353 if (nat->nat_tqe.tqe_ifq != NULL) {
2355 * No call to ipf_freetimeoutqueue() is made here, they are
2356 * garbage collected in ipf_nat_expire().
2358 (void) ipf_deletequeueentry(&nat->nat_tqe);
2361 if (nat->nat_sync) {
2362 ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
2363 nat->nat_sync = NULL;
2366 if (logtype == NL_EXPIRE)
2367 softn->ipf_nat_stats.ns_expire++;
2369 MUTEX_ENTER(&nat->nat_lock);
2371 * NL_DESTROY should only be passed in when we've got nat_ref >= 2.
2372 * This happens when a nat'd packet is blocked and we want to throw
2373 * away the NAT session.
2375 if (logtype == NL_DESTROY) {
2376 if (nat->nat_ref > 2) {
2378 MUTEX_EXIT(&nat->nat_lock);
2380 softn->ipf_nat_stats.ns_orphans++;
2383 } else if (nat->nat_ref > 1) {
2385 MUTEX_EXIT(&nat->nat_lock);
2386 if (madeorphan == 1)
2387 softn->ipf_nat_stats.ns_orphans++;
2390 ASSERT(nat->nat_ref >= 0);
2391 MUTEX_EXIT(&nat->nat_lock);
2395 if (madeorphan == 0)
2396 softn->ipf_nat_stats.ns_orphans--;
2399 * At this point, nat_ref can be either 0 or -1
2401 softn->ipf_nat_stats.ns_proto[nat->nat_pr[0]]--;
2403 if (nat->nat_fr != NULL) {
2404 (void) ipf_derefrule(softc, &nat->nat_fr);
2407 if (nat->nat_hm != NULL) {
2408 ipf_nat_hostmapdel(softc, &nat->nat_hm);
2412 * If there is an active reference from the nat entry to its parent
2413 * rule, decrement the rule's reference count and free it too if no
2414 * longer being used.
2417 nat->nat_ptr = NULL;
2421 ipf_nat_rule_deref(softc, &ipn);
2424 if (nat->nat_aps != NULL) {
2425 ipf_proxy_free(softc, nat->nat_aps);
2426 nat->nat_aps = NULL;
2429 MUTEX_DESTROY(&nat->nat_lock);
2431 softn->ipf_nat_stats.ns_active--;
2434 * If there's a fragment table entry too for this nat entry, then
2435 * dereference that as well. This is after nat_lock is released
2438 ipf_frag_natforget(softc, (void *)nat);
2444 /* ------------------------------------------------------------------------ */
2445 /* Function: ipf_nat_flushtable */
2446 /* Returns: int - number of NAT rules deleted */
2447 /* Parameters: softc(I) - pointer to soft context main structure */
2448 /* softn(I) - pointer to NAT context structure */
2449 /* Write Lock: ipf_nat */
2451 /* Deletes all currently active NAT sessions. In deleting each NAT entry a */
2452 /* log record should be emitted in ipf_nat_delete() if NAT logging is */
2454 /* ------------------------------------------------------------------------ */
2456 * nat_flushtable - clear the NAT table of all mapping entries.
2459 ipf_nat_flushtable(softc, softn)
2460 ipf_main_softc_t *softc;
2461 ipf_nat_softc_t *softn;
2467 * ALL NAT mappings deleted, so lets just make the deletions
2470 if (softn->ipf_nat_table[0] != NULL)
2471 bzero((char *)softn->ipf_nat_table[0],
2472 sizeof(softn->ipf_nat_table[0]) *
2473 softn->ipf_nat_table_sz);
2474 if (softn->ipf_nat_table[1] != NULL)
2475 bzero((char *)softn->ipf_nat_table[1],
2476 sizeof(softn->ipf_nat_table[1]) *
2477 softn->ipf_nat_table_sz);
2479 while ((nat = softn->ipf_nat_instances) != NULL) {
2480 ipf_nat_delete(softc, nat, NL_FLUSH);
2488 /* ------------------------------------------------------------------------ */
2489 /* Function: ipf_nat_clearlist */
2490 /* Returns: int - number of NAT/RDR rules deleted */
2491 /* Parameters: softc(I) - pointer to soft context main structure */
2492 /* softn(I) - pointer to NAT context structure */
2494 /* Delete all rules in the current list of rules. There is nothing elegant */
2495 /* about this cleanup: simply free all entries on the list of rules and */
2496 /* clear out the tables used for hashed NAT rule lookups. */
2497 /* ------------------------------------------------------------------------ */
2499 ipf_nat_clearlist(softc, softn)
2500 ipf_main_softc_t *softc;
2501 ipf_nat_softc_t *softn;
2506 if (softn->ipf_nat_map_rules != NULL) {
2507 bzero((char *)softn->ipf_nat_map_rules,
2508 sizeof(*softn->ipf_nat_map_rules) *
2509 softn->ipf_nat_maprules_sz);
2511 if (softn->ipf_nat_rdr_rules != NULL) {
2512 bzero((char *)softn->ipf_nat_rdr_rules,
2513 sizeof(*softn->ipf_nat_rdr_rules) *
2514 softn->ipf_nat_rdrrules_sz);
2517 while ((n = softn->ipf_nat_list) != NULL) {
2518 ipf_nat_delrule(softc, softn, n, 0);
2521 #if SOLARIS && !defined(INSTANCES)
2522 pfil_delayed_copy = 1;
2528 /* ------------------------------------------------------------------------ */
2529 /* Function: ipf_nat_delrule */
2531 /* Parameters: softc(I) - pointer to soft context main structure */
2532 /* softn(I) - pointer to NAT context structure */
2533 /* np(I) - pointer to NAT rule to delete */
2534 /* purge(I) - 1 == allow purge, 0 == prevent purge */
2535 /* Locks: WRITE(ipf_nat) */
2537 /* Preventing "purge" from occuring is allowed because when all of the NAT */
2538 /* rules are being removed, allowing the "purge" to walk through the list */
2539 /* of NAT sessions, possibly multiple times, would be a large performance */
2540 /* hit, on the order of O(N^2). */
2541 /* ------------------------------------------------------------------------ */
2543 ipf_nat_delrule(softc, softn, np, purge)
2544 ipf_main_softc_t *softc;
2545 ipf_nat_softc_t *softn;
2550 if (np->in_pnext != NULL) {
2551 *np->in_pnext = np->in_next;
2552 if (np->in_next != NULL)
2553 np->in_next->in_pnext = np->in_pnext;
2554 if (softn->ipf_nat_list_tail == &np->in_next)
2555 softn->ipf_nat_list_tail = np->in_pnext;
2558 if ((purge == 1) && ((np->in_flags & IPN_PURGE) != 0)) {
2562 for (next = softn->ipf_nat_instances; (nat = next) != NULL;) {
2563 next = nat->nat_next;
2564 if (nat->nat_ptr == np)
2565 ipf_nat_delete(softc, nat, NL_PURGE);
2569 if ((np->in_flags & IPN_DELETE) == 0) {
2570 if (np->in_redir & NAT_REDIRECT) {
2571 switch (np->in_v[0])
2574 ipf_nat_delrdr(softn, np);
2578 ipf_nat6_delrdr(softn, np);
2583 if (np->in_redir & (NAT_MAPBLK|NAT_MAP)) {
2584 switch (np->in_v[0])
2587 ipf_nat_delmap(softn, np);
2591 ipf_nat6_delmap(softn, np);
2598 np->in_flags |= IPN_DELETE;
2599 ipf_nat_rule_deref(softc, &np);
2603 /* ------------------------------------------------------------------------ */
2604 /* Function: ipf_nat_newmap */
2605 /* Returns: int - -1 == error, 0 == success */
2606 /* Parameters: fin(I) - pointer to packet information */
2607 /* nat(I) - pointer to NAT entry */
2608 /* ni(I) - pointer to structure with misc. information needed */
2609 /* to create new NAT entry. */
2611 /* Given an empty NAT structure, populate it with new information about a */
2612 /* new NAT session, as defined by the matching NAT rule. */
2613 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
2614 /* to the new IP address for the translation. */
2615 /* ------------------------------------------------------------------------ */
2617 ipf_nat_newmap(fin, nat, ni)
2622 ipf_main_softc_t *softc = fin->fin_main_soft;
2623 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
2624 u_short st_port, dport, sport, port, sp, dp;
2625 struct in_addr in, inb;
2634 * If it's an outbound packet which doesn't match any existing
2635 * record, then create a new port
2640 st_ip = np->in_snip;
2641 st_port = np->in_spnext;
2642 flags = nat->nat_flags;
2644 if (flags & IPN_ICMPQUERY) {
2645 sport = fin->fin_data[1];
2648 sport = htons(fin->fin_data[0]);
2649 dport = htons(fin->fin_data[1]);
2653 * Do a loop until we either run out of entries to try or we find
2654 * a NAT mapping that isn't currently being used. This is done
2655 * because the change to the source is not (usually) being fixed.
2659 in.s_addr = htonl(np->in_snip);
2662 * Check to see if there is an existing NAT
2663 * setup for this IP address pair.
2665 hm = ipf_nat_hostmap(softn, np, fin->fin_src,
2666 fin->fin_dst, in, 0);
2668 in.s_addr = hm->hm_nsrcip.s_addr;
2669 } else if ((l == 1) && (hm != NULL)) {
2670 ipf_nat_hostmapdel(softc, &hm);
2672 in.s_addr = ntohl(in.s_addr);
2676 if ((np->in_nsrcmsk == 0xffffffff) && (np->in_spnext == 0)) {
2678 NBUMPSIDEX(1, ns_exhausted, ns_exhausted_1);
2683 if (np->in_redir == NAT_BIMAP &&
2684 np->in_osrcmsk == np->in_nsrcmsk) {
2686 * map the address block in a 1:1 fashion
2688 in.s_addr = np->in_nsrcaddr;
2689 in.s_addr |= fin->fin_saddr & ~np->in_osrcmsk;
2690 in.s_addr = ntohl(in.s_addr);
2692 } else if (np->in_redir & NAT_MAPBLK) {
2693 if ((l >= np->in_ppip) || ((l > 0) &&
2694 !(flags & IPN_TCPUDP))) {
2695 NBUMPSIDEX(1, ns_exhausted, ns_exhausted_2);
2699 * map-block - Calculate destination address.
2701 in.s_addr = ntohl(fin->fin_saddr);
2702 in.s_addr &= ntohl(~np->in_osrcmsk);
2703 inb.s_addr = in.s_addr;
2704 in.s_addr /= np->in_ippip;
2705 in.s_addr &= ntohl(~np->in_nsrcmsk);
2706 in.s_addr += ntohl(np->in_nsrcaddr);
2708 * Calculate destination port.
2710 if ((flags & IPN_TCPUDP) &&
2711 (np->in_ppip != 0)) {
2712 port = ntohs(sport) + l;
2713 port %= np->in_ppip;
2714 port += np->in_ppip *
2715 (inb.s_addr % np->in_ippip);
2716 port += MAPBLK_MINPORT;
2720 } else if ((np->in_nsrcaddr == 0) &&
2721 (np->in_nsrcmsk == 0xffffffff)) {
2725 * 0/32 - use the interface's IP address.
2728 ipf_ifpaddr(softc, 4, FRI_NORMAL, fin->fin_ifp,
2729 &in6, NULL) == -1) {
2730 NBUMPSIDEX(1, ns_new_ifpaddr, ns_new_ifpaddr_1);
2733 in.s_addr = ntohl(in6.in4.s_addr);
2735 } else if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0)) {
2737 * 0/0 - use the original source address/port.
2740 NBUMPSIDEX(1, ns_exhausted, ns_exhausted_3);
2743 in.s_addr = ntohl(fin->fin_saddr);
2745 } else if ((np->in_nsrcmsk != 0xffffffff) &&
2746 (np->in_spnext == 0) && ((l > 0) || (hm == NULL)))
2751 if ((flags & IPN_TCPUDP) &&
2752 ((np->in_redir & NAT_MAPBLK) == 0) &&
2753 (np->in_flags & IPN_AUTOPORTMAP)) {
2755 * "ports auto" (without map-block)
2757 if ((l > 0) && (l % np->in_ppip == 0)) {
2758 if ((l > np->in_ppip) &&
2759 np->in_nsrcmsk != 0xffffffff)
2762 if (np->in_ppip != 0) {
2763 port = ntohs(sport);
2764 port += (l % np->in_ppip);
2765 port %= np->in_ppip;
2766 port += np->in_ppip *
2767 (ntohl(fin->fin_saddr) %
2769 port += MAPBLK_MINPORT;
2773 } else if (((np->in_redir & NAT_MAPBLK) == 0) &&
2774 (flags & IPN_TCPUDPICMP) && (np->in_spnext != 0)) {
2776 * Standard port translation. Select next port.
2778 if (np->in_flags & IPN_SEQUENTIAL) {
2779 port = np->in_spnext;
2781 port = ipf_random() % (np->in_spmax -
2783 port += np->in_spmin;
2788 if (np->in_spnext > np->in_spmax) {
2789 np->in_spnext = np->in_spmin;
2790 if (np->in_nsrcmsk != 0xffffffff)
2795 if (np->in_flags & IPN_SIPRANGE) {
2796 if (np->in_snip > ntohl(np->in_nsrcmsk))
2797 np->in_snip = ntohl(np->in_nsrcaddr);
2799 if ((np->in_nsrcmsk != 0xffffffff) &&
2800 ((np->in_snip + 1) & ntohl(np->in_nsrcmsk)) >
2801 ntohl(np->in_nsrcaddr))
2802 np->in_snip = ntohl(np->in_nsrcaddr) + 1;
2805 if ((port == 0) && (flags & (IPN_TCPUDPICMP|IPN_ICMPQUERY)))
2809 * Here we do a lookup of the connection as seen from
2810 * the outside. If an IP# pair already exists, try
2811 * again. So if you have A->B becomes C->B, you can
2812 * also have D->E become C->E but not D->B causing
2813 * another C->B. Also take protocol and ports into
2814 * account when determining whether a pre-existing
2815 * NAT setup will cause an external conflict where
2816 * this is appropriate.
2818 inb.s_addr = htonl(in.s_addr);
2819 sp = fin->fin_data[0];
2820 dp = fin->fin_data[1];
2821 fin->fin_data[0] = fin->fin_data[1];
2822 fin->fin_data[1] = ntohs(port);
2823 natl = ipf_nat_inlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
2824 (u_int)fin->fin_p, fin->fin_dst, inb);
2825 fin->fin_data[0] = sp;
2826 fin->fin_data[1] = dp;
2829 * Has the search wrapped around and come back to the
2832 if ((natl != NULL) &&
2833 (np->in_spnext != 0) && (st_port == np->in_spnext) &&
2834 (np->in_snip != 0) && (st_ip == np->in_snip)) {
2835 NBUMPSIDED(1, ns_wrap);
2839 } while (natl != NULL);
2841 /* Setup the NAT table */
2842 nat->nat_osrcip = fin->fin_src;
2843 nat->nat_nsrcaddr = htonl(in.s_addr);
2844 nat->nat_odstip = fin->fin_dst;
2845 nat->nat_ndstip = fin->fin_dst;
2846 if (nat->nat_hm == NULL)
2847 nat->nat_hm = ipf_nat_hostmap(softn, np, fin->fin_src,
2848 fin->fin_dst, nat->nat_nsrcip,
2851 if (flags & IPN_TCPUDP) {
2852 nat->nat_osport = sport;
2853 nat->nat_nsport = port; /* sport */
2854 nat->nat_odport = dport;
2855 nat->nat_ndport = dport;
2856 ((tcphdr_t *)fin->fin_dp)->th_sport = port;
2857 } else if (flags & IPN_ICMPQUERY) {
2858 nat->nat_oicmpid = fin->fin_data[1];
2859 ((icmphdr_t *)fin->fin_dp)->icmp_id = port;
2860 nat->nat_nicmpid = port;
2866 /* ------------------------------------------------------------------------ */
2867 /* Function: ipf_nat_newrdr */
2868 /* Returns: int - -1 == error, 0 == success (no move), 1 == success and */
2869 /* allow rule to be moved if IPN_ROUNDR is set. */
2870 /* Parameters: fin(I) - pointer to packet information */
2871 /* nat(I) - pointer to NAT entry */
2872 /* ni(I) - pointer to structure with misc. information needed */
2873 /* to create new NAT entry. */
2875 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
2876 /* to the new IP address for the translation. */
2877 /* ------------------------------------------------------------------------ */
2879 ipf_nat_newrdr(fin, nat, ni)
2884 ipf_main_softc_t *softc = fin->fin_main_soft;
2885 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
2886 u_short nport, dport, sport;
2887 struct in_addr in, inb;
2899 flags = nat->nat_flags;
2901 if (flags & IPN_ICMPQUERY) {
2902 dport = fin->fin_data[1];
2905 sport = htons(fin->fin_data[0]);
2906 dport = htons(fin->fin_data[1]);
2909 /* TRACE sport, dport */
2913 * If the matching rule has IPN_STICKY set, then we want to have the
2914 * same rule kick in as before. Why would this happen? If you have
2915 * a collection of rdr rules with "round-robin sticky", the current
2916 * packet might match a different one to the previous connection but
2917 * we want the same destination to be used.
2919 if (((np->in_flags & (IPN_ROUNDR|IPN_SPLIT)) != 0) &&
2920 ((np->in_flags & IPN_STICKY) != 0)) {
2921 hm = ipf_nat_hostmap(softn, NULL, fin->fin_src, fin->fin_dst,
2924 in.s_addr = ntohl(hm->hm_ndstip.s_addr);
2928 ipf_nat_hostmapdel(softc, &hm);
2933 * Otherwise, it's an inbound packet. Most likely, we don't
2934 * want to rewrite source ports and source addresses. Instead,
2935 * we want to rewrite to a fixed internal address and fixed
2938 if (np->in_flags & IPN_SPLIT) {
2939 in.s_addr = np->in_dnip;
2940 inb.s_addr = htonl(in.s_addr);
2942 if ((np->in_flags & (IPN_ROUNDR|IPN_STICKY)) == IPN_STICKY) {
2943 hm = ipf_nat_hostmap(softn, NULL, fin->fin_src,
2944 fin->fin_dst, inb, (u_32_t)dport);
2946 in.s_addr = hm->hm_ndstip.s_addr;
2951 if (hm == NULL || hm->hm_ref == 1) {
2952 if (np->in_ndstaddr == htonl(in.s_addr)) {
2953 np->in_dnip = ntohl(np->in_ndstmsk);
2956 np->in_dnip = ntohl(np->in_ndstaddr);
2960 ipf_nat_hostmapdel(softc, &hm);
2962 } else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0xffffffff)) {
2966 * 0/32 - use the interface's IP address.
2968 if (ipf_ifpaddr(softc, 4, FRI_NORMAL, fin->fin_ifp,
2969 &in6, NULL) == -1) {
2970 NBUMPSIDEX(0, ns_new_ifpaddr, ns_new_ifpaddr_2);
2973 in.s_addr = ntohl(in6.in4.s_addr);
2975 } else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk== 0)) {
2977 * 0/0 - use the original destination address/port.
2979 in.s_addr = ntohl(fin->fin_daddr);
2981 } else if (np->in_redir == NAT_BIMAP &&
2982 np->in_ndstmsk == np->in_odstmsk) {
2984 * map the address block in a 1:1 fashion
2986 in.s_addr = np->in_ndstaddr;
2987 in.s_addr |= fin->fin_daddr & ~np->in_ndstmsk;
2988 in.s_addr = ntohl(in.s_addr);
2990 in.s_addr = ntohl(np->in_ndstaddr);
2993 if ((np->in_dpnext == 0) || ((flags & NAT_NOTRULEPORT) != 0))
2997 * Whilst not optimized for the case where
2998 * pmin == pmax, the gain is not significant.
3000 if (((np->in_flags & IPN_FIXEDDPORT) == 0) &&
3001 (np->in_odport != np->in_dtop)) {
3002 nport = ntohs(dport) - np->in_odport + np->in_dpmax;
3003 nport = htons(nport);
3005 nport = htons(np->in_dpnext);
3007 if (np->in_dpnext > np->in_dpmax)
3008 np->in_dpnext = np->in_dpmin;
3013 * When the redirect-to address is set to 0.0.0.0, just
3014 * assume a blank `forwarding' of the packet. We don't
3015 * setup any translation for this either.
3017 if (in.s_addr == 0) {
3018 if (nport == dport) {
3019 NBUMPSIDED(0, ns_xlate_null);
3022 in.s_addr = ntohl(fin->fin_daddr);
3026 * Check to see if this redirect mapping already exists and if
3027 * it does, return "failure" (allowing it to be created will just
3028 * cause one or both of these "connections" to stop working.)
3030 inb.s_addr = htonl(in.s_addr);
3031 sp = fin->fin_data[0];
3032 dp = fin->fin_data[1];
3033 fin->fin_data[1] = fin->fin_data[0];
3034 fin->fin_data[0] = ntohs(nport);
3035 natl = ipf_nat_outlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
3036 (u_int)fin->fin_p, inb, fin->fin_src);
3037 fin->fin_data[0] = sp;
3038 fin->fin_data[1] = dp;
3040 DT2(ns_new_xlate_exists, fr_info_t *, fin, nat_t *, natl);
3041 NBUMPSIDE(0, ns_xlate_exists);
3045 inb.s_addr = htonl(in.s_addr);
3046 nat->nat_ndstaddr = htonl(in.s_addr);
3047 nat->nat_odstip = fin->fin_dst;
3048 nat->nat_nsrcip = fin->fin_src;
3049 nat->nat_osrcip = fin->fin_src;
3050 if ((nat->nat_hm == NULL) && ((np->in_flags & IPN_STICKY) != 0))
3051 nat->nat_hm = ipf_nat_hostmap(softn, np, fin->fin_src,
3052 fin->fin_dst, inb, (u_32_t)dport);
3054 if (flags & IPN_TCPUDP) {
3055 nat->nat_odport = dport;
3056 nat->nat_ndport = nport;
3057 nat->nat_osport = sport;
3058 nat->nat_nsport = sport;
3059 ((tcphdr_t *)fin->fin_dp)->th_dport = nport;
3060 } else if (flags & IPN_ICMPQUERY) {
3061 nat->nat_oicmpid = fin->fin_data[1];
3062 ((icmphdr_t *)fin->fin_dp)->icmp_id = nport;
3063 nat->nat_nicmpid = nport;
3069 /* ------------------------------------------------------------------------ */
3070 /* Function: ipf_nat_add */
3071 /* Returns: nat_t* - NULL == failure to create new NAT structure, */
3072 /* else pointer to new NAT structure */
3073 /* Parameters: fin(I) - pointer to packet information */
3074 /* np(I) - pointer to NAT rule */
3075 /* natsave(I) - pointer to where to store NAT struct pointer */
3076 /* flags(I) - flags describing the current packet */
3077 /* direction(I) - direction of packet (in/out) */
3078 /* Write Lock: ipf_nat */
3080 /* Attempts to create a new NAT entry. Does not actually change the packet */
3083 /* This fucntion is in three main parts: (1) deal with creating a new NAT */
3084 /* structure for a "MAP" rule (outgoing NAT translation); (2) deal with */
3085 /* creating a new NAT structure for a "RDR" rule (incoming NAT translation) */
3086 /* and (3) building that structure and putting it into the NAT table(s). */
3088 /* NOTE: natsave should NOT be used top point back to an ipstate_t struct */
3089 /* as it can result in memory being corrupted. */
3090 /* ------------------------------------------------------------------------ */
3092 ipf_nat_add(fin, np, natsave, flags, direction)
3099 ipf_main_softc_t *softc = fin->fin_main_soft;
3100 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
3101 hostmap_t *hm = NULL;
3108 nsp = &softn->ipf_nat_stats;
3110 if ((nsp->ns_active * 100 / softn->ipf_nat_table_max) >
3111 softn->ipf_nat_table_wm_high) {
3112 softn->ipf_nat_doflush = 1;
3115 if (nsp->ns_active >= softn->ipf_nat_table_max) {
3116 NBUMPSIDED(fin->fin_out, ns_table_max);
3121 nflags = np->in_flags & flags;
3122 nflags &= NAT_FROMRULE;
3128 /* Give me a new nat */
3129 KMALLOC(nat, nat_t *);
3131 NBUMPSIDED(fin->fin_out, ns_memfail);
3133 * Try to automatically tune the max # of entries in the
3134 * table allowed to be less than what will cause kmem_alloc()
3135 * to fail and try to eliminate panics due to out of memory
3136 * conditions arising.
3138 if ((softn->ipf_nat_table_max > softn->ipf_nat_table_sz) &&
3139 (nsp->ns_active > 100)) {
3140 softn->ipf_nat_table_max = nsp->ns_active - 100;
3141 printf("table_max reduced to %d\n",
3142 softn->ipf_nat_table_max);
3147 if (flags & IPN_ICMPQUERY) {
3149 * In the ICMP query NAT code, we translate the ICMP id fields
3150 * to make them unique. This is indepedent of the ICMP type
3151 * (e.g. in the unlikely event that a host sends an echo and
3152 * an tstamp request with the same id, both packets will have
3153 * their ip address/id field changed in the same way).
3155 /* The icmp_id field is used by the sender to identify the
3156 * process making the icmp request. (the receiver justs
3157 * copies it back in its response). So, it closely matches
3158 * the concept of source port. We overlay sport, so we can
3159 * maximally reuse the existing code.
3161 ni.nai_sport = fin->fin_data[1];
3165 bzero((char *)nat, sizeof(*nat));
3166 nat->nat_flags = flags;
3167 nat->nat_redir = np->in_redir;
3168 nat->nat_dir = direction;
3169 nat->nat_pr[0] = fin->fin_p;
3170 nat->nat_pr[1] = fin->fin_p;
3173 * Search the current table for a match and create a new mapping
3174 * if there is none found.
3176 if (np->in_redir & NAT_DIVERTUDP) {
3177 move = ipf_nat_newdivert(fin, nat, &ni);
3179 } else if (np->in_redir & NAT_REWRITE) {
3180 move = ipf_nat_newrewrite(fin, nat, &ni);
3182 } else if (direction == NAT_OUTBOUND) {
3184 * We can now arrange to call this for the same connection
3185 * because ipf_nat_new doesn't protect the code path into
3188 natl = ipf_nat_outlookup(fin, nflags, (u_int)fin->fin_p,
3189 fin->fin_src, fin->fin_dst);
3196 move = ipf_nat_newmap(fin, nat, &ni);
3199 * NAT_INBOUND is used for redirects rules
3201 natl = ipf_nat_inlookup(fin, nflags, (u_int)fin->fin_p,
3202 fin->fin_src, fin->fin_dst);
3209 move = ipf_nat_newrdr(fin, nat, &ni);
3216 nat->nat_mssclamp = np->in_mssclamp;
3217 nat->nat_me = natsave;
3218 nat->nat_fr = fin->fin_fr;
3219 nat->nat_rev = fin->fin_rev;
3221 nat->nat_dlocal = np->in_dlocal;
3223 if ((np->in_apr != NULL) && ((nat->nat_flags & NAT_SLAVE) == 0)) {
3224 if (ipf_proxy_new(fin, nat) == -1) {
3225 NBUMPSIDED(fin->fin_out, ns_appr_fail);
3230 nat->nat_ifps[0] = np->in_ifps[0];
3231 if (np->in_ifps[0] != NULL) {
3232 COPYIFNAME(np->in_v[0], np->in_ifps[0], nat->nat_ifnames[0]);
3235 nat->nat_ifps[1] = np->in_ifps[1];
3236 if (np->in_ifps[1] != NULL) {
3237 COPYIFNAME(np->in_v[1], np->in_ifps[1], nat->nat_ifnames[1]);
3240 if (ipf_nat_finalise(fin, nat) == -1) {
3246 if ((move == 1) && (np->in_flags & IPN_ROUNDR)) {
3247 if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_REDIRECT) {
3248 ipf_nat_delrdr(softn, np);
3249 ipf_nat_addrdr(softn, np);
3250 } else if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_MAP) {
3251 ipf_nat_delmap(softn, np);
3252 ipf_nat_addmap(softn, np);
3256 if (flags & SI_WILDP)
3258 nsp->ns_proto[nat->nat_pr[0]]++;
3262 DT2(ns_badnatnew, fr_info_t *, fin, nat_t *, nat);
3263 NBUMPSIDE(fin->fin_out, ns_badnatnew);
3264 if ((hm = nat->nat_hm) != NULL)
3265 ipf_nat_hostmapdel(softc, &hm);
3269 if (nat != NULL && np != NULL)
3271 if (natsave != NULL)
3277 /* ------------------------------------------------------------------------ */
3278 /* Function: ipf_nat_finalise */
3279 /* Returns: int - 0 == sucess, -1 == failure */
3280 /* Parameters: fin(I) - pointer to packet information */
3281 /* nat(I) - pointer to NAT entry */
3282 /* Write Lock: ipf_nat */
3284 /* This is the tail end of constructing a new NAT entry and is the same */
3285 /* for both IPv4 and IPv6. */
3286 /* ------------------------------------------------------------------------ */
3289 ipf_nat_finalise(fin, nat)
3293 ipf_main_softc_t *softc = fin->fin_main_soft;
3294 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
3295 u_32_t sum1, sum2, sumd;
3298 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6) && defined(ICK_M_CTL_MAGIC)
3299 qpktinfo_t *qpi = fin->fin_qpi;
3302 flags = nat->nat_flags;
3304 switch (nat->nat_pr[0])
3307 sum1 = LONG_SUM(ntohs(nat->nat_oicmpid));
3308 sum2 = LONG_SUM(ntohs(nat->nat_nicmpid));
3309 CALC_SUMD(sum1, sum2, sumd);
3310 nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
3315 sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr) + \
3316 ntohs(nat->nat_osport));
3317 sum2 = LONG_SUM(ntohl(nat->nat_nsrcaddr) + \
3318 ntohs(nat->nat_nsport));
3319 CALC_SUMD(sum1, sum2, sumd);
3320 nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
3322 sum1 = LONG_SUM(ntohl(nat->nat_odstaddr) + \
3323 ntohs(nat->nat_odport));
3324 sum2 = LONG_SUM(ntohl(nat->nat_ndstaddr) + \
3325 ntohs(nat->nat_ndport));
3326 CALC_SUMD(sum1, sum2, sumd);
3327 nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
3332 * Compute the partial checksum, just in case.
3333 * This is only ever placed into outbound packets so care needs
3334 * to be taken over which pair of addresses are used.
3336 if (nat->nat_dir == NAT_OUTBOUND) {
3337 sum1 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
3338 sum1 += LONG_SUM(ntohl(nat->nat_ndstaddr));
3340 sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr));
3341 sum1 += LONG_SUM(ntohl(nat->nat_odstaddr));
3343 sum1 += nat->nat_pr[1];
3344 nat->nat_sumd[1] = (sum1 & 0xffff) + (sum1 >> 16);
3346 sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr));
3347 sum2 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
3348 CALC_SUMD(sum1, sum2, sumd);
3349 nat->nat_ipsumd = (sumd & 0xffff) + (sumd >> 16);
3351 sum1 = LONG_SUM(ntohl(nat->nat_odstaddr));
3352 sum2 = LONG_SUM(ntohl(nat->nat_ndstaddr));
3353 CALC_SUMD(sum1, sum2, sumd);
3354 nat->nat_ipsumd += (sumd & 0xffff) + (sumd >> 16);
3359 if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
3360 nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
3363 if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
3364 nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
3367 if ((nat->nat_flags & SI_CLONE) == 0)
3368 nat->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, nat);
3370 if (ipf_nat_insert(softc, softn, nat) == 0) {
3371 if (softn->ipf_nat_logging)
3372 ipf_nat_log(softc, softn, nat, NL_NEW);
3375 MUTEX_ENTER(&fr->fr_lock);
3377 MUTEX_EXIT(&fr->fr_lock);
3382 NBUMPSIDED(fin->fin_out, ns_unfinalised);
3384 * nat_insert failed, so cleanup time...
3386 if (nat->nat_sync != NULL)
3387 ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
3392 /* ------------------------------------------------------------------------ */
3393 /* Function: ipf_nat_insert */
3394 /* Returns: int - 0 == sucess, -1 == failure */
3395 /* Parameters: softc(I) - pointer to soft context main structure */
3396 /* softn(I) - pointer to NAT context structure */
3397 /* nat(I) - pointer to NAT structure */
3398 /* Write Lock: ipf_nat */
3400 /* Insert a NAT entry into the hash tables for searching and add it to the */
3401 /* list of active NAT entries. Adjust global counters when complete. */
3402 /* ------------------------------------------------------------------------ */
3404 ipf_nat_insert(softc, softn, nat)
3405 ipf_main_softc_t *softc;
3406 ipf_nat_softc_t *softn;
3414 * Try and return an error as early as possible, so calculate the hash
3415 * entry numbers first and then proceed.
3417 if ((nat->nat_flags & (SI_W_SPORT|SI_W_DPORT)) == 0) {
3418 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
3419 sp = nat->nat_osport;
3420 dp = nat->nat_odport;
3421 } else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
3423 dp = nat->nat_oicmpid;
3428 hv0 = NAT_HASH_FN(nat->nat_osrcaddr, sp, 0xffffffff);
3429 hv0 = NAT_HASH_FN(nat->nat_odstaddr, hv0 + dp, 0xffffffff);
3431 * TRACE nat_osrcaddr, nat_osport, nat_odstaddr,
3435 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
3436 sp = nat->nat_nsport;
3437 dp = nat->nat_ndport;
3438 } else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
3440 dp = nat->nat_nicmpid;
3445 hv1 = NAT_HASH_FN(nat->nat_nsrcaddr, sp, 0xffffffff);
3446 hv1 = NAT_HASH_FN(nat->nat_ndstaddr, hv1 + dp, 0xffffffff);
3448 * TRACE nat_nsrcaddr, nat_nsport, nat_ndstaddr,
3452 hv0 = NAT_HASH_FN(nat->nat_osrcaddr, 0, 0xffffffff);
3453 hv0 = NAT_HASH_FN(nat->nat_odstaddr, hv0, 0xffffffff);
3454 /* TRACE nat_osrcaddr, nat_odstaddr, hv0 */
3456 hv1 = NAT_HASH_FN(nat->nat_nsrcaddr, 0, 0xffffffff);
3457 hv1 = NAT_HASH_FN(nat->nat_ndstaddr, hv1, 0xffffffff);
3458 /* TRACE nat_nsrcaddr, nat_ndstaddr, hv1 */
3461 nat->nat_hv[0] = hv0;
3462 nat->nat_hv[1] = hv1;
3464 MUTEX_INIT(&nat->nat_lock, "nat entry lock");
3467 nat->nat_ref = nat->nat_me ? 2 : 1;
3469 nat->nat_ifnames[0][LIFNAMSIZ - 1] = '\0';
3470 nat->nat_ifps[0] = ipf_resolvenic(softc, nat->nat_ifnames[0], 4);
3472 if (nat->nat_ifnames[1][0] != '\0') {
3473 nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
3474 nat->nat_ifps[1] = ipf_resolvenic(softc,
3475 nat->nat_ifnames[1], 4);
3476 } else if (in->in_ifnames[1] != -1) {
3479 name = in->in_names + in->in_ifnames[1];
3480 if (name[1] != '\0' && name[0] != '-' && name[0] != '*') {
3481 (void) strncpy(nat->nat_ifnames[1],
3482 nat->nat_ifnames[0], LIFNAMSIZ);
3483 nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
3484 nat->nat_ifps[1] = nat->nat_ifps[0];
3487 if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
3488 nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
3490 if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
3491 nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
3494 return ipf_nat_hashtab_add(softc, softn, nat);
3498 /* ------------------------------------------------------------------------ */
3499 /* Function: ipf_nat_hashtab_add */
3500 /* Parameters: softc(I) - pointer to soft context main structure */
3501 /* softn(I) - pointer to NAT context structure */
3502 /* nat(I) - pointer to NAT structure */
3504 /* Handle the insertion of a NAT entry into the table/list. */
3505 /* ------------------------------------------------------------------------ */
3507 ipf_nat_hashtab_add(softc, softn, nat)
3508 ipf_main_softc_t *softc;
3509 ipf_nat_softc_t *softn;
3516 hv0 = nat->nat_hv[0] % softn->ipf_nat_table_sz;
3517 hv1 = nat->nat_hv[1] % softn->ipf_nat_table_sz;
3519 if (nat->nat_dir == NAT_INBOUND || nat->nat_dir == NAT_DIVERTIN) {
3527 if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0] >=
3528 softn->ipf_nat_maxbucket) {
3529 DT1(ns_bucket_max_0, int,
3530 softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0]);
3531 NBUMPSIDE(0, ns_bucket_max);
3535 if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1] >=
3536 softn->ipf_nat_maxbucket) {
3537 DT1(ns_bucket_max_1, int,
3538 softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1]);
3539 NBUMPSIDE(1, ns_bucket_max);
3544 * The ordering of operations in the list and hash table insertion
3545 * is very important. The last operation for each task should be
3546 * to update the top of the list, after all the "nexts" have been
3547 * done so that walking the list while it is being done does not
3548 * find strange pointers.
3550 * Global list of NAT instances
3552 nat->nat_next = softn->ipf_nat_instances;
3553 nat->nat_pnext = &softn->ipf_nat_instances;
3554 if (softn->ipf_nat_instances)
3555 softn->ipf_nat_instances->nat_pnext = &nat->nat_next;
3556 softn->ipf_nat_instances = nat;
3559 * Inbound hash table.
3561 natp = &softn->ipf_nat_table[0][hv0];
3562 nat->nat_phnext[0] = natp;
3563 nat->nat_hnext[0] = *natp;
3565 (*natp)->nat_phnext[0] = &nat->nat_hnext[0];
3567 NBUMPSIDE(0, ns_inuse);
3570 NBUMPSIDE(0, ns_bucketlen[hv0]);
3573 * Outbound hash table.
3575 natp = &softn->ipf_nat_table[1][hv1];
3576 nat->nat_phnext[1] = natp;
3577 nat->nat_hnext[1] = *natp;
3579 (*natp)->nat_phnext[1] = &nat->nat_hnext[1];
3581 NBUMPSIDE(1, ns_inuse);
3584 NBUMPSIDE(1, ns_bucketlen[hv1]);
3586 ipf_nat_setqueue(softc, softn, nat);
3588 if (nat->nat_dir & NAT_OUTBOUND) {
3589 NBUMPSIDE(1, ns_added);
3591 NBUMPSIDE(0, ns_added);
3593 softn->ipf_nat_stats.ns_active++;
3598 /* ------------------------------------------------------------------------ */
3599 /* Function: ipf_nat_icmperrorlookup */
3600 /* Returns: nat_t* - point to matching NAT structure */
3601 /* Parameters: fin(I) - pointer to packet information */
3602 /* dir(I) - direction of packet (in/out) */
3604 /* Check if the ICMP error message is related to an existing TCP, UDP or */
3605 /* ICMP query nat entry. It is assumed that the packet is already of the */
3606 /* the required length. */
3607 /* ------------------------------------------------------------------------ */
3609 ipf_nat_icmperrorlookup(fin, dir)
3613 ipf_main_softc_t *softc = fin->fin_main_soft;
3614 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
3615 int flags = 0, type, minlen;
3616 icmphdr_t *icmp, *orgicmp;
3617 nat_stat_side_t *nside;
3618 tcphdr_t *tcp = NULL;
3625 type = icmp->icmp_type;
3626 nside = &softn->ipf_nat_stats.ns_side[fin->fin_out];
3628 * Does it at least have the return (basic) IP header ?
3629 * Only a basic IP header (no options) should be with an ICMP error
3630 * header. Also, if it's not an error type, then return.
3632 if ((fin->fin_hlen != sizeof(ip_t)) || !(fin->fin_flx & FI_ICMPERR)) {
3633 ATOMIC_INCL(nside->ns_icmp_basic);
3640 oip = (ip_t *)((char *)fin->fin_dp + 8);
3641 minlen = IP_HL(oip) << 2;
3642 if ((minlen < sizeof(ip_t)) ||
3643 (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen)) {
3644 ATOMIC_INCL(nside->ns_icmp_size);
3649 * Is the buffer big enough for all of it ? It's the size of the IP
3650 * header claimed in the encapsulated part which is of concern. It
3651 * may be too big to be in this buffer but not so big that it's
3652 * outside the ICMP packet, leading to TCP deref's causing problems.
3653 * This is possible because we don't know how big oip_hl is when we
3654 * do the pullup early in ipf_check() and thus can't gaurantee it is
3657 #ifdef ipf_nat_KERNEL
3662 # if defined(MENTAT)
3663 if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN >
3664 (char *)m->b_wptr) {
3665 ATOMIC_INCL(nside->ns_icmp_mbuf);
3669 if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN >
3670 (char *)fin->fin_ip + M_LEN(m)) {
3671 ATOMIC_INCL(nside->ns_icmp_mbuf);
3678 if (fin->fin_daddr != oip->ip_src.s_addr) {
3679 ATOMIC_INCL(nside->ns_icmp_address);
3684 if (p == IPPROTO_TCP)
3686 else if (p == IPPROTO_UDP)
3688 else if (p == IPPROTO_ICMP) {
3689 orgicmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
3691 /* see if this is related to an ICMP query */
3692 if (ipf_nat_icmpquerytype(orgicmp->icmp_type)) {
3693 data[0] = fin->fin_data[0];
3694 data[1] = fin->fin_data[1];
3695 fin->fin_data[0] = 0;
3696 fin->fin_data[1] = orgicmp->icmp_id;
3698 flags = IPN_ICMPERR|IPN_ICMPQUERY;
3700 * NOTE : dir refers to the direction of the original
3701 * ip packet. By definition the icmp error
3702 * message flows in the opposite direction.
3704 if (dir == NAT_INBOUND)
3705 nat = ipf_nat_inlookup(fin, flags, p,
3709 nat = ipf_nat_outlookup(fin, flags, p,
3712 fin->fin_data[0] = data[0];
3713 fin->fin_data[1] = data[1];
3718 if (flags & IPN_TCPUDP) {
3719 minlen += 8; /* + 64bits of data to get ports */
3720 /* TRACE (fin,minlen) */
3721 if (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen) {
3722 ATOMIC_INCL(nside->ns_icmp_short);
3726 data[0] = fin->fin_data[0];
3727 data[1] = fin->fin_data[1];
3728 tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
3729 fin->fin_data[0] = ntohs(tcp->th_dport);
3730 fin->fin_data[1] = ntohs(tcp->th_sport);
3732 if (dir == NAT_INBOUND) {
3733 nat = ipf_nat_inlookup(fin, flags, p, oip->ip_dst,
3736 nat = ipf_nat_outlookup(fin, flags, p, oip->ip_dst,
3739 fin->fin_data[0] = data[0];
3740 fin->fin_data[1] = data[1];
3743 if (dir == NAT_INBOUND)
3744 nat = ipf_nat_inlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
3746 nat = ipf_nat_outlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
3752 /* ------------------------------------------------------------------------ */
3753 /* Function: ipf_nat_icmperror */
3754 /* Returns: nat_t* - point to matching NAT structure */
3755 /* Parameters: fin(I) - pointer to packet information */
3756 /* nflags(I) - NAT flags for this packet */
3757 /* dir(I) - direction of packet (in/out) */
3759 /* Fix up an ICMP packet which is an error message for an existing NAT */
3760 /* session. This will correct both packet header data and checksums. */
3762 /* This should *ONLY* be used for incoming ICMP error packets to make sure */
3763 /* a NAT'd ICMP packet gets correctly recognised. */
3764 /* ------------------------------------------------------------------------ */
3766 ipf_nat_icmperror(fin, nflags, dir)
3771 ipf_main_softc_t *softc = fin->fin_main_soft;
3772 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
3773 u_32_t sum1, sum2, sumd, sumd2;
3774 struct in_addr a1, a2, a3, a4;
3775 int flags, dlen, odst;
3783 if ((fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
3784 NBUMPSIDED(fin->fin_out, ns_icmp_short);
3789 * ipf_nat_icmperrorlookup() will return NULL for `defective' packets.
3791 if ((fin->fin_v != 4) || !(nat = ipf_nat_icmperrorlookup(fin, dir))) {
3792 NBUMPSIDED(fin->fin_out, ns_icmp_notfound);
3800 *nflags = IPN_ICMPERR;
3802 oip = (ip_t *)&icmp->icmp_ip;
3803 dp = (((char *)oip) + (IP_HL(oip) << 2));
3804 if (oip->ip_p == IPPROTO_TCP) {
3805 tcp = (tcphdr_t *)dp;
3806 csump = (u_short *)&tcp->th_sum;
3808 } else if (oip->ip_p == IPPROTO_UDP) {
3811 udp = (udphdr_t *)dp;
3812 tcp = (tcphdr_t *)dp;
3813 csump = (u_short *)&udp->uh_sum;
3815 } else if (oip->ip_p == IPPROTO_ICMP)
3816 flags = IPN_ICMPQUERY;
3817 dlen = fin->fin_plen - ((char *)dp - (char *)fin->fin_ip);
3820 * Need to adjust ICMP header to include the real IP#'s and
3821 * port #'s. Only apply a checksum change relative to the
3822 * IP address change as it will be modified again in ipf_nat_checkout
3823 * for both address and port. Two checksum changes are
3824 * necessary for the two header address changes. Be careful
3825 * to only modify the checksum once for the port # and twice
3831 * Fix the IP addresses in the offending IP packet. You also need
3832 * to adjust the IP header checksum of that offending IP packet.
3834 * Normally, you would expect that the ICMP checksum of the
3835 * ICMP error message needs to be adjusted as well for the
3836 * IP address change in oip.
3837 * However, this is a NOP, because the ICMP checksum is
3838 * calculated over the complete ICMP packet, which includes the
3839 * changed oip IP addresses and oip->ip_sum. However, these
3840 * two changes cancel each other out (if the delta for
3841 * the IP address is x, then the delta for ip_sum is minus x),
3842 * so no change in the icmp_cksum is necessary.
3846 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
3847 * - response to outgoing packet (a,b)=>(c,b) (OIP_SRC=c,OIP_DST=b)
3848 * - OIP_SRC(c)=nat_newsrcip, OIP_DST(b)=nat_newdstip
3849 *=> OIP_SRC(c)=nat_oldsrcip, OIP_DST(b)=nat_olddstip
3851 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
3852 * - response to outgoing packet (c,a)=>(b,a) (OIP_SRC=b,OIP_DST=a)
3853 * - OIP_SRC(b)=nat_olddstip, OIP_DST(a)=nat_oldsrcip
3854 *=> OIP_SRC(b)=nat_newdstip, OIP_DST(a)=nat_newsrcip
3856 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
3857 * - response to outgoing packet (a,b)=>(c,d) (OIP_SRC=c,OIP_DST=d)
3858 * - OIP_SRC(c)=nat_newsrcip, OIP_DST(d)=nat_newdstip
3859 *=> OIP_SRC(c)=nat_oldsrcip, OIP_DST(d)=nat_olddstip
3861 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
3862 * - response to outgoing packet (d,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
3863 * - OIP_SRC(b)=nat_olddstip, OIP_DST(a)=nat_oldsrcip
3864 *=> OIP_SRC(b)=nat_newdstip, OIP_DST(a)=nat_newsrcip
3868 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
3869 * - response to incoming packet (b,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
3870 * - OIP_SRC(b)=nat_olddstip, OIP_DST(a)=nat_oldsrcip
3871 *=> OIP_SRC(b)=nat_newdstip, OIP_DST(a)=nat_newsrcip
3873 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
3874 * - response to incoming packet (a,b)=>(a,c) (OIP_SRC=a,OIP_DST=c)
3875 * - OIP_SRC(a)=nat_newsrcip, OIP_DST(c)=nat_newdstip
3876 *=> OIP_SRC(a)=nat_oldsrcip, OIP_DST(c)=nat_olddstip
3878 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
3879 * - response to incoming packet (d,c)=>(b,a) (OIP_SRC=c,OIP_DST=d)
3880 * - OIP_SRC(c)=nat_olddstip, OIP_DST(d)=nat_oldsrcip
3881 *=> OIP_SRC(b)=nat_newdstip, OIP_DST(a)=nat_newsrcip
3883 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
3884 * - response to incoming packet (a,b)=>(c,d) (OIP_SRC=b,OIP_DST=a)
3885 * - OIP_SRC(b)=nat_newsrcip, OIP_DST(a)=nat_newdstip
3886 *=> OIP_SRC(a)=nat_oldsrcip, OIP_DST(c)=nat_olddstip
3889 if (((fin->fin_out == 0) && ((nat->nat_redir & NAT_MAP) != 0)) ||
3890 ((fin->fin_out == 1) && ((nat->nat_redir & NAT_REDIRECT) != 0))) {
3891 a1.s_addr = ntohl(nat->nat_osrcaddr);
3892 a4.s_addr = ntohl(oip->ip_src.s_addr);
3893 a3.s_addr = ntohl(nat->nat_odstaddr);
3894 a2.s_addr = ntohl(oip->ip_dst.s_addr);
3895 oip->ip_src.s_addr = htonl(a1.s_addr);
3896 oip->ip_dst.s_addr = htonl(a3.s_addr);
3899 a1.s_addr = ntohl(nat->nat_ndstaddr);
3900 a2.s_addr = ntohl(oip->ip_dst.s_addr);
3901 a3.s_addr = ntohl(nat->nat_nsrcaddr);
3902 a4.s_addr = ntohl(oip->ip_src.s_addr);
3903 oip->ip_dst.s_addr = htonl(a3.s_addr);
3904 oip->ip_src.s_addr = htonl(a1.s_addr);
3910 CALC_SUMD(a2.s_addr, a3.s_addr, sum1);
3911 CALC_SUMD(a4.s_addr, a1.s_addr, sum2);
3914 ipf_fix_datacksum(&oip->ip_sum, sumd);
3921 * Fix UDP pseudo header checksum to compensate for the
3922 * IP address change.
3924 if (((flags & IPN_TCPUDP) != 0) && (dlen >= 4)) {
3925 u_32_t sum3, sum4, sumt;
3929 * For offending TCP/UDP IP packets, translate the ports as
3930 * well, based on the NAT specification. Of course such
3931 * a change may be reflected in the ICMP checksum as well.
3933 * Since the port fields are part of the TCP/UDP checksum
3934 * of the offending IP packet, you need to adjust that checksum
3935 * as well... except that the change in the port numbers should
3936 * be offset by the checksum change. However, the TCP/UDP
3937 * checksum will also need to change if there has been an
3938 * IP address change.
3941 sum1 = ntohs(nat->nat_osport);
3942 sum4 = ntohs(tcp->th_sport);
3943 sum3 = ntohs(nat->nat_odport);
3944 sum2 = ntohs(tcp->th_dport);
3946 tcp->th_sport = htons(sum1);
3947 tcp->th_dport = htons(sum3);
3949 sum1 = ntohs(nat->nat_ndport);
3950 sum2 = ntohs(tcp->th_dport);
3951 sum3 = ntohs(nat->nat_nsport);
3952 sum4 = ntohs(tcp->th_sport);
3954 tcp->th_dport = htons(sum3);
3955 tcp->th_sport = htons(sum1);
3957 CALC_SUMD(sum4, sum1, sumt);
3959 CALC_SUMD(sum2, sum3, sumt);
3962 if (sumd != 0 || sumd2 != 0) {
3964 * At this point, sumd is the delta to apply to the
3965 * TCP/UDP header, given the changes in both the IP
3966 * address and the ports and sumd2 is the delta to
3967 * apply to the ICMP header, given the IP address
3968 * change delta that may need to be applied to the
3969 * TCP/UDP checksum instead.
3971 * If we will both the IP and TCP/UDP checksums
3972 * then the ICMP checksum changes by the address
3973 * delta applied to the TCP/UDP checksum. If we
3974 * do not change the TCP/UDP checksum them we
3975 * apply the delta in ports to the ICMP checksum.
3977 if (oip->ip_p == IPPROTO_UDP) {
3978 if ((dlen >= 8) && (*csump != 0)) {
3979 ipf_fix_datacksum(csump, sumd);
3981 CALC_SUMD(sum1, sum4, sumd2);
3982 CALC_SUMD(sum3, sum2, sumt);
3985 } else if (oip->ip_p == IPPROTO_TCP) {
3987 ipf_fix_datacksum(csump, sumd);
3989 CALC_SUMD(sum1, sum4, sumd2);
3990 CALC_SUMD(sum3, sum2, sumt);
3995 sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
3996 sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
3997 sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
3998 ipf_fix_incksum(0, &icmp->icmp_cksum, sumd2, 0);
4001 } else if (((flags & IPN_ICMPQUERY) != 0) && (dlen >= 8)) {
4005 * XXX - what if this is bogus hl and we go off the end ?
4006 * In this case, ipf_nat_icmperrorlookup() will have
4009 orgicmp = (icmphdr_t *)dp;
4012 if (orgicmp->icmp_id != nat->nat_osport) {
4015 * Fix ICMP checksum (of the offening ICMP
4016 * query packet) to compensate the change
4017 * in the ICMP id of the offending ICMP
4020 * Since you modify orgicmp->icmp_id with
4021 * a delta (say x) and you compensate that
4022 * in origicmp->icmp_cksum with a delta
4023 * minus x, you don't have to adjust the
4024 * overall icmp->icmp_cksum
4026 sum1 = ntohs(orgicmp->icmp_id);
4027 sum2 = ntohs(nat->nat_oicmpid);
4028 CALC_SUMD(sum1, sum2, sumd);
4029 orgicmp->icmp_id = nat->nat_oicmpid;
4030 ipf_fix_datacksum(&orgicmp->icmp_cksum, sumd);
4032 } /* nat_dir == NAT_INBOUND is impossible for icmp queries */
4039 * MAP-IN MAP-OUT RDR-IN RDR-OUT
4040 * osrc X == src == src X
4041 * odst X == dst == dst X
4042 * nsrc == dst X X == dst
4043 * ndst == src X X == src
4044 * MAP = NAT_OUTBOUND, RDR = NAT_INBOUND
4047 * NB: these lookups don't lock access to the list, it assumed that it has
4048 * already been done!
4050 /* ------------------------------------------------------------------------ */
4051 /* Function: ipf_nat_inlookup */
4052 /* Returns: nat_t* - NULL == no match, */
4053 /* else pointer to matching NAT entry */
4054 /* Parameters: fin(I) - pointer to packet information */
4055 /* flags(I) - NAT flags for this packet */
4056 /* p(I) - protocol for this packet */
4057 /* src(I) - source IP address */
4058 /* mapdst(I) - destination IP address */
4060 /* Lookup a nat entry based on the mapped destination ip address/port and */
4061 /* real source address/port. We use this lookup when receiving a packet, */
4062 /* we're looking for a table entry, based on the destination address. */
4064 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY. */
4066 /* NOTE: IT IS ASSUMED THAT IS ONLY HELD WITH A READ LOCK WHEN */
4067 /* THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags. */
4069 /* flags -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if */
4070 /* the packet is of said protocol */
4071 /* ------------------------------------------------------------------------ */
4073 ipf_nat_inlookup(fin, flags, p, src, mapdst)
4076 struct in_addr src , mapdst;
4078 ipf_main_softc_t *softc = fin->fin_main_soft;
4079 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
4080 u_short sport, dport;
4092 dst = mapdst.s_addr;
4093 sflags = flags & NAT_TCPUDPICMP;
4099 sport = htons(fin->fin_data[0]);
4100 dport = htons(fin->fin_data[1]);
4104 dport = fin->fin_data[1];
4113 if ((flags & SI_WILDP) != 0)
4114 goto find_in_wild_ports;
4116 rhv = NAT_HASH_FN(dst, dport, 0xffffffff);
4117 rhv = NAT_HASH_FN(src.s_addr, rhv + sport, 0xffffffff);
4118 hv = rhv % softn->ipf_nat_table_sz;
4119 nat = softn->ipf_nat_table[1][hv];
4120 /* TRACE dst, dport, src, sport, hv, nat */
4122 for (; nat; nat = nat->nat_hnext[1]) {
4123 if (nat->nat_ifps[0] != NULL) {
4124 if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
4128 if (nat->nat_pr[0] != p)
4131 switch (nat->nat_dir)
4135 if (nat->nat_v[0] != 4)
4137 if (nat->nat_osrcaddr != src.s_addr ||
4138 nat->nat_odstaddr != dst)
4140 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
4141 if (nat->nat_osport != sport)
4143 if (nat->nat_odport != dport)
4146 } else if (p == IPPROTO_ICMP) {
4147 if (nat->nat_osport != dport) {
4152 case NAT_DIVERTOUT :
4153 if (nat->nat_dlocal)
4156 if (nat->nat_v[1] != 4)
4158 if (nat->nat_dlocal)
4160 if (nat->nat_dlocal)
4162 if (nat->nat_ndstaddr != src.s_addr ||
4163 nat->nat_nsrcaddr != dst)
4165 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
4166 if (nat->nat_ndport != sport)
4168 if (nat->nat_nsport != dport)
4171 } else if (p == IPPROTO_ICMP) {
4172 if (nat->nat_osport != dport) {
4180 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
4182 if ((ipn != NULL) && (nat->nat_aps != NULL))
4183 if (ipf_proxy_match(fin, nat) != 0)
4186 if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
4187 nat->nat_ifps[0] = ifp;
4188 nat->nat_mtu[0] = GETIFMTU_4(ifp);
4194 * So if we didn't find it but there are wildcard members in the hash
4195 * table, go back and look for them. We do this search and update here
4196 * because it is modifying the NAT table and we want to do this only
4197 * for the first packet that matches. The exception, of course, is
4198 * for "dummy" (FI_IGNORE) lookups.
4201 if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
4202 NBUMPSIDEX(0, ns_lookup_miss, ns_lookup_miss_0);
4205 if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
4206 NBUMPSIDEX(0, ns_lookup_nowild, ns_lookup_nowild_0);
4210 RWLOCK_EXIT(&softc->ipf_nat);
4212 hv = NAT_HASH_FN(dst, 0, 0xffffffff);
4213 hv = NAT_HASH_FN(src.s_addr, hv, softn->ipf_nat_table_sz);
4214 WRITE_ENTER(&softc->ipf_nat);
4216 nat = softn->ipf_nat_table[1][hv];
4217 /* TRACE dst, src, hv, nat */
4218 for (; nat; nat = nat->nat_hnext[1]) {
4219 if (nat->nat_ifps[0] != NULL) {
4220 if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
4224 if (nat->nat_pr[0] != fin->fin_p)
4227 switch (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND))
4230 if (nat->nat_v[0] != 4)
4232 if (nat->nat_osrcaddr != src.s_addr ||
4233 nat->nat_odstaddr != dst)
4237 if (nat->nat_v[1] != 4)
4239 if (nat->nat_ndstaddr != src.s_addr ||
4240 nat->nat_nsrcaddr != dst)
4245 nflags = nat->nat_flags;
4246 if (!(nflags & (NAT_TCPUDP|SI_WILDP)))
4249 if (ipf_nat_wildok(nat, (int)sport, (int)dport, nflags,
4250 NAT_INBOUND) == 1) {
4251 if ((fin->fin_flx & FI_IGNORE) != 0)
4253 if ((nflags & SI_CLONE) != 0) {
4254 nat = ipf_nat_clone(fin, nat);
4258 MUTEX_ENTER(&softn->ipf_nat_new);
4259 softn->ipf_nat_stats.ns_wilds--;
4260 MUTEX_EXIT(&softn->ipf_nat_new);
4263 if (nat->nat_dir == NAT_INBOUND) {
4264 if (nat->nat_osport == 0) {
4265 nat->nat_osport = sport;
4266 nat->nat_nsport = sport;
4268 if (nat->nat_odport == 0) {
4269 nat->nat_odport = dport;
4270 nat->nat_ndport = dport;
4272 } else if (nat->nat_dir == NAT_OUTBOUND) {
4273 if (nat->nat_osport == 0) {
4274 nat->nat_osport = dport;
4275 nat->nat_nsport = dport;
4277 if (nat->nat_odport == 0) {
4278 nat->nat_odport = sport;
4279 nat->nat_ndport = sport;
4282 if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
4283 nat->nat_ifps[0] = ifp;
4284 nat->nat_mtu[0] = GETIFMTU_4(ifp);
4286 nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
4287 ipf_nat_tabmove(softn, nat);
4292 MUTEX_DOWNGRADE(&softc->ipf_nat);
4295 NBUMPSIDE(0, ns_lookup_miss);
4301 /* ------------------------------------------------------------------------ */
4302 /* Function: ipf_nat_tabmove */
4304 /* Parameters: softn(I) - pointer to NAT context structure */
4305 /* nat(I) - pointer to NAT structure */
4306 /* Write Lock: ipf_nat */
4308 /* This function is only called for TCP/UDP NAT table entries where the */
4309 /* original was placed in the table without hashing on the ports and we now */
4310 /* want to include hashing on port numbers. */
4311 /* ------------------------------------------------------------------------ */
4313 ipf_nat_tabmove(softn, nat)
4314 ipf_nat_softc_t *softn;
4317 u_int hv0, hv1, rhv0, rhv1;
4321 if (nat->nat_flags & SI_CLONE)
4324 nsp = &softn->ipf_nat_stats;
4326 * Remove the NAT entry from the old location
4328 if (nat->nat_hnext[0])
4329 nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
4330 *nat->nat_phnext[0] = nat->nat_hnext[0];
4331 nsp->ns_side[0].ns_bucketlen[nat->nat_hv[0] %
4332 softn->ipf_nat_table_sz]--;
4334 if (nat->nat_hnext[1])
4335 nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
4336 *nat->nat_phnext[1] = nat->nat_hnext[1];
4337 nsp->ns_side[1].ns_bucketlen[nat->nat_hv[1] %
4338 softn->ipf_nat_table_sz]--;
4341 * Add into the NAT table in the new position
4343 rhv0 = NAT_HASH_FN(nat->nat_osrcaddr, nat->nat_osport, 0xffffffff);
4344 rhv0 = NAT_HASH_FN(nat->nat_odstaddr, rhv0 + nat->nat_odport,
4346 rhv1 = NAT_HASH_FN(nat->nat_nsrcaddr, nat->nat_nsport, 0xffffffff);
4347 rhv1 = NAT_HASH_FN(nat->nat_ndstaddr, rhv1 + nat->nat_ndport,
4350 hv0 = rhv0 % softn->ipf_nat_table_sz;
4351 hv1 = rhv1 % softn->ipf_nat_table_sz;
4353 if (nat->nat_dir == NAT_INBOUND || nat->nat_dir == NAT_DIVERTIN) {
4361 /* TRACE nat_osrcaddr, nat_osport, nat_odstaddr, nat_odport, hv0 */
4362 /* TRACE nat_nsrcaddr, nat_nsport, nat_ndstaddr, nat_ndport, hv1 */
4364 nat->nat_hv[0] = rhv0;
4365 natp = &softn->ipf_nat_table[0][hv0];
4367 (*natp)->nat_phnext[0] = &nat->nat_hnext[0];
4368 nat->nat_phnext[0] = natp;
4369 nat->nat_hnext[0] = *natp;
4371 nsp->ns_side[0].ns_bucketlen[hv0]++;
4373 nat->nat_hv[1] = rhv1;
4374 natp = &softn->ipf_nat_table[1][hv1];
4376 (*natp)->nat_phnext[1] = &nat->nat_hnext[1];
4377 nat->nat_phnext[1] = natp;
4378 nat->nat_hnext[1] = *natp;
4380 nsp->ns_side[1].ns_bucketlen[hv1]++;
4384 /* ------------------------------------------------------------------------ */
4385 /* Function: ipf_nat_outlookup */
4386 /* Returns: nat_t* - NULL == no match, */
4387 /* else pointer to matching NAT entry */
4388 /* Parameters: fin(I) - pointer to packet information */
4389 /* flags(I) - NAT flags for this packet */
4390 /* p(I) - protocol for this packet */
4391 /* src(I) - source IP address */
4392 /* dst(I) - destination IP address */
4393 /* rw(I) - 1 == write lock on held, 0 == read lock. */
4395 /* Lookup a nat entry based on the source 'real' ip address/port and */
4396 /* destination address/port. We use this lookup when sending a packet out, */
4397 /* we're looking for a table entry, based on the source address. */
4399 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY. */
4401 /* NOTE: IT IS ASSUMED THAT IS ONLY HELD WITH A READ LOCK WHEN */
4402 /* THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags. */
4404 /* flags -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if */
4405 /* the packet is of said protocol */
4406 /* ------------------------------------------------------------------------ */
4408 ipf_nat_outlookup(fin, flags, p, src, dst)
4411 struct in_addr src , dst;
4413 ipf_main_softc_t *softc = fin->fin_main_soft;
4414 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
4415 u_short sport, dport;
4423 sflags = flags & IPN_TCPUDPICMP;
4429 sport = htons(fin->fin_data[0]);
4430 dport = htons(fin->fin_data[1]);
4434 dport = fin->fin_data[1];
4442 if ((flags & SI_WILDP) != 0)
4443 goto find_out_wild_ports;
4445 hv = NAT_HASH_FN(src.s_addr, sport, 0xffffffff);
4446 hv = NAT_HASH_FN(dst.s_addr, hv + dport, softn->ipf_nat_table_sz);
4447 nat = softn->ipf_nat_table[0][hv];
4449 /* TRACE src, sport, dst, dport, hv, nat */
4451 for (; nat; nat = nat->nat_hnext[0]) {
4452 if (nat->nat_ifps[1] != NULL) {
4453 if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
4457 if (nat->nat_pr[1] != p)
4460 switch (nat->nat_dir)
4464 if (nat->nat_v[1] != 4)
4466 if (nat->nat_ndstaddr != src.s_addr ||
4467 nat->nat_nsrcaddr != dst.s_addr)
4470 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
4471 if (nat->nat_ndport != sport)
4473 if (nat->nat_nsport != dport)
4476 } else if (p == IPPROTO_ICMP) {
4477 if (nat->nat_osport != dport) {
4483 case NAT_DIVERTOUT :
4484 if (nat->nat_v[0] != 4)
4486 if (nat->nat_osrcaddr != src.s_addr ||
4487 nat->nat_odstaddr != dst.s_addr)
4490 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
4491 if (nat->nat_odport != dport)
4493 if (nat->nat_osport != sport)
4496 } else if (p == IPPROTO_ICMP) {
4497 if (nat->nat_osport != dport) {
4505 if ((ipn != NULL) && (nat->nat_aps != NULL))
4506 if (ipf_proxy_match(fin, nat) != 0)
4509 if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
4510 nat->nat_ifps[1] = ifp;
4511 nat->nat_mtu[1] = GETIFMTU_4(ifp);
4517 * So if we didn't find it but there are wildcard members in the hash
4518 * table, go back and look for them. We do this search and update here
4519 * because it is modifying the NAT table and we want to do this only
4520 * for the first packet that matches. The exception, of course, is
4521 * for "dummy" (FI_IGNORE) lookups.
4523 find_out_wild_ports:
4524 if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
4525 NBUMPSIDEX(1, ns_lookup_miss, ns_lookup_miss_1);
4528 if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
4529 NBUMPSIDEX(1, ns_lookup_nowild, ns_lookup_nowild_1);
4533 RWLOCK_EXIT(&softc->ipf_nat);
4535 hv = NAT_HASH_FN(src.s_addr, 0, 0xffffffff);
4536 hv = NAT_HASH_FN(dst.s_addr, hv, softn->ipf_nat_table_sz);
4538 WRITE_ENTER(&softc->ipf_nat);
4540 nat = softn->ipf_nat_table[0][hv];
4541 for (; nat; nat = nat->nat_hnext[0]) {
4542 if (nat->nat_ifps[1] != NULL) {
4543 if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
4547 if (nat->nat_pr[1] != fin->fin_p)
4550 switch (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND))
4553 if (nat->nat_v[1] != 4)
4555 if (nat->nat_ndstaddr != src.s_addr ||
4556 nat->nat_nsrcaddr != dst.s_addr)
4560 if (nat->nat_v[0] != 4)
4562 if (nat->nat_osrcaddr != src.s_addr ||
4563 nat->nat_odstaddr != dst.s_addr)
4568 if (!(nat->nat_flags & (NAT_TCPUDP|SI_WILDP)))
4571 if (ipf_nat_wildok(nat, (int)sport, (int)dport, nat->nat_flags,
4572 NAT_OUTBOUND) == 1) {
4573 if ((fin->fin_flx & FI_IGNORE) != 0)
4575 if ((nat->nat_flags & SI_CLONE) != 0) {
4576 nat = ipf_nat_clone(fin, nat);
4580 MUTEX_ENTER(&softn->ipf_nat_new);
4581 softn->ipf_nat_stats.ns_wilds--;
4582 MUTEX_EXIT(&softn->ipf_nat_new);
4585 if (nat->nat_dir == NAT_OUTBOUND) {
4586 if (nat->nat_osport == 0) {
4587 nat->nat_osport = sport;
4588 nat->nat_nsport = sport;
4590 if (nat->nat_odport == 0) {
4591 nat->nat_odport = dport;
4592 nat->nat_ndport = dport;
4594 } else if (nat->nat_dir == NAT_INBOUND) {
4595 if (nat->nat_osport == 0) {
4596 nat->nat_osport = dport;
4597 nat->nat_nsport = dport;
4599 if (nat->nat_odport == 0) {
4600 nat->nat_odport = sport;
4601 nat->nat_ndport = sport;
4604 if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
4605 nat->nat_ifps[1] = ifp;
4606 nat->nat_mtu[1] = GETIFMTU_4(ifp);
4608 nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
4609 ipf_nat_tabmove(softn, nat);
4614 MUTEX_DOWNGRADE(&softc->ipf_nat);
4617 NBUMPSIDE(1, ns_lookup_miss);
4623 /* ------------------------------------------------------------------------ */
4624 /* Function: ipf_nat_lookupredir */
4625 /* Returns: nat_t* - NULL == no match, */
4626 /* else pointer to matching NAT entry */
4627 /* Parameters: np(I) - pointer to description of packet to find NAT table */
4630 /* Lookup the NAT tables to search for a matching redirect */
4631 /* The contents of natlookup_t should imitate those found in a packet that */
4632 /* would be translated - ie a packet coming in for RDR or going out for MAP.*/
4633 /* We can do the lookup in one of two ways, imitating an inbound or */
4634 /* outbound packet. By default we assume outbound, unless IPN_IN is set. */
4635 /* For IN, the fields are set as follows: */
4636 /* nl_real* = source information */
4637 /* nl_out* = destination information (translated) */
4638 /* For an out packet, the fields are set like this: */
4639 /* nl_in* = source information (untranslated) */
4640 /* nl_out* = destination information (translated) */
4641 /* ------------------------------------------------------------------------ */
4643 ipf_nat_lookupredir(np)
4649 bzero((char *)&fi, sizeof(fi));
4650 if (np->nl_flags & IPN_IN) {
4651 fi.fin_data[0] = ntohs(np->nl_realport);
4652 fi.fin_data[1] = ntohs(np->nl_outport);
4654 fi.fin_data[0] = ntohs(np->nl_inport);
4655 fi.fin_data[1] = ntohs(np->nl_outport);
4657 if (np->nl_flags & IPN_TCP)
4658 fi.fin_p = IPPROTO_TCP;
4659 else if (np->nl_flags & IPN_UDP)
4660 fi.fin_p = IPPROTO_UDP;
4661 else if (np->nl_flags & (IPN_ICMPERR|IPN_ICMPQUERY))
4662 fi.fin_p = IPPROTO_ICMP;
4665 * We can do two sorts of lookups:
4666 * - IPN_IN: we have the `real' and `out' address, look for `in'.
4667 * - default: we have the `in' and `out' address, look for `real'.
4669 if (np->nl_flags & IPN_IN) {
4670 if ((nat = ipf_nat_inlookup(&fi, np->nl_flags, fi.fin_p,
4671 np->nl_realip, np->nl_outip))) {
4672 np->nl_inip = nat->nat_odstip;
4673 np->nl_inport = nat->nat_odport;
4677 * If nl_inip is non null, this is a lookup based on the real
4678 * ip address. Else, we use the fake.
4680 if ((nat = ipf_nat_outlookup(&fi, np->nl_flags, fi.fin_p,
4681 np->nl_inip, np->nl_outip))) {
4683 if ((np->nl_flags & IPN_FINDFORWARD) != 0) {
4685 bzero((char *)&fin, sizeof(fin));
4686 fin.fin_p = nat->nat_pr[0];
4687 fin.fin_data[0] = ntohs(nat->nat_ndport);
4688 fin.fin_data[1] = ntohs(nat->nat_nsport);
4689 if (ipf_nat_inlookup(&fin, np->nl_flags,
4690 fin.fin_p, nat->nat_ndstip,
4691 nat->nat_nsrcip) != NULL) {
4692 np->nl_flags &= ~IPN_FINDFORWARD;
4696 np->nl_realip = nat->nat_odstip;
4697 np->nl_realport = nat->nat_odport;
4705 /* ------------------------------------------------------------------------ */
4706 /* Function: ipf_nat_match */
4707 /* Returns: int - 0 == no match, 1 == match */
4708 /* Parameters: fin(I) - pointer to packet information */
4709 /* np(I) - pointer to NAT rule */
4711 /* Pull the matching of a packet against a NAT rule out of that complex */
4712 /* loop inside ipf_nat_checkin() and lay it out properly in its own function. */
4713 /* ------------------------------------------------------------------------ */
4715 ipf_nat_match(fin, np)
4719 ipf_main_softc_t *softc = fin->fin_main_soft;
4724 switch (np->in_osrcatype)
4727 match = ((fin->fin_saddr & np->in_osrcmsk) != np->in_osrcaddr);
4730 match = (*np->in_osrcfunc)(softc, np->in_osrcptr,
4731 4, &fin->fin_saddr, fin->fin_plen);
4734 match ^= ((np->in_flags & IPN_NOTSRC) != 0);
4739 switch (np->in_odstatype)
4742 match = ((fin->fin_daddr & np->in_odstmsk) != np->in_odstaddr);
4745 match = (*np->in_odstfunc)(softc, np->in_odstptr,
4746 4, &fin->fin_daddr, fin->fin_plen);
4750 match ^= ((np->in_flags & IPN_NOTDST) != 0);
4755 if (!(fin->fin_flx & FI_TCPUDP) ||
4756 (fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
4757 if (ft->ftu_scmp || ft->ftu_dcmp)
4762 return ipf_tcpudpchk(&fin->fin_fi, ft);
4766 /* ------------------------------------------------------------------------ */
4767 /* Function: ipf_nat_update */
4769 /* Parameters: fin(I) - pointer to packet information */
4770 /* nat(I) - pointer to NAT structure */
4772 /* Updates the lifetime of a NAT table entry for non-TCP packets. Must be */
4773 /* called with fin_rev updated - i.e. after calling ipf_nat_proto(). */
4775 /* This *MUST* be called after ipf_nat_proto() as it expects fin_rev to */
4776 /* already be set. */
4777 /* ------------------------------------------------------------------------ */
4779 ipf_nat_update(fin, nat)
4783 ipf_main_softc_t *softc = fin->fin_main_soft;
4784 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
4785 ipftq_t *ifq, *ifq2;
4787 ipnat_t *np = nat->nat_ptr;
4789 tqe = &nat->nat_tqe;
4793 * We allow over-riding of NAT timeouts from NAT rules, even for
4794 * TCP, however, if it is TCP and there is no rule timeout set,
4795 * then do not update the timeout here.
4798 np->in_bytes[fin->fin_rev] += fin->fin_plen;
4799 ifq2 = np->in_tqehead[fin->fin_rev];
4804 if (nat->nat_pr[0] == IPPROTO_TCP && ifq2 == NULL) {
4805 (void) ipf_tcp_age(&nat->nat_tqe, fin, softn->ipf_nat_tcptq,
4809 if (nat->nat_pr[0] == IPPROTO_UDP)
4810 ifq2 = fin->fin_rev ? &softn->ipf_nat_udpacktq :
4811 &softn->ipf_nat_udptq;
4812 else if (nat->nat_pr[0] == IPPROTO_ICMP ||
4813 nat->nat_pr[0] == IPPROTO_ICMPV6)
4814 ifq2 = fin->fin_rev ? &softn->ipf_nat_icmpacktq:
4815 &softn->ipf_nat_icmptq;
4817 ifq2 = &softn->ipf_nat_iptq;
4820 ipf_movequeue(softc->ipf_ticks, tqe, ifq, ifq2);
4825 /* ------------------------------------------------------------------------ */
4826 /* Function: ipf_nat_checkout */
4827 /* Returns: int - -1 == packet failed NAT checks so block it, */
4828 /* 0 == no packet translation occurred, */
4829 /* 1 == packet was successfully translated. */
4830 /* Parameters: fin(I) - pointer to packet information */
4831 /* passp(I) - pointer to filtering result flags */
4833 /* Check to see if an outcoming packet should be changed. ICMP packets are */
4834 /* first checked to see if they match an existing entry (if an error), */
4835 /* otherwise a search of the current NAT table is made. If neither results */
4836 /* in a match then a search for a matching NAT rule is made. Create a new */
4837 /* NAT entry if a we matched a NAT rule. Lastly, actually change the */
4838 /* packet header(s) as required. */
4839 /* ------------------------------------------------------------------------ */
4841 ipf_nat_checkout(fin, passp)
4845 ipnat_t *np = NULL, *npnext;
4846 struct ifnet *ifp, *sifp;
4847 ipf_main_softc_t *softc;
4848 ipf_nat_softc_t *softn;
4849 icmphdr_t *icmp = NULL;
4850 tcphdr_t *tcp = NULL;
4851 int rval, natfailed;
4858 if (fin->fin_v == 6) {
4860 return ipf_nat6_checkout(fin, passp);
4866 softc = fin->fin_main_soft;
4867 softn = softc->ipf_nat_soft;
4869 if (softn->ipf_nat_lock != 0)
4871 if (softn->ipf_nat_stats.ns_rules == 0 &&
4872 softn->ipf_nat_instances == NULL)
4877 sifp = fin->fin_ifp;
4879 ifp = fr->fr_tifs[fin->fin_rev].fd_ptr;
4880 if ((ifp != NULL) && (ifp != (void *)-1))
4885 if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
4898 * This is an incoming packet, so the destination is
4899 * the icmp_id and the source port equals 0
4901 if ((fin->fin_flx & FI_ICMPQUERY) != 0)
4902 nflags = IPN_ICMPQUERY;
4908 if ((nflags & IPN_TCPUDP))
4912 ipa = fin->fin_saddr;
4914 READ_ENTER(&softc->ipf_nat);
4916 if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
4917 (nat = ipf_nat_icmperror(fin, &nflags, NAT_OUTBOUND)))
4919 else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
4921 else if ((nat = ipf_nat_outlookup(fin, nflags|NAT_SEARCH,
4922 (u_int)fin->fin_p, fin->fin_src,
4924 nflags = nat->nat_flags;
4925 } else if (fin->fin_off == 0) {
4926 u_32_t hv, msk, nmsk = 0;
4929 * If there is no current entry in the nat table for this IP#,
4930 * create one for it (if there is a matching rule).
4933 msk = softn->ipf_nat_map_active_masks[nmsk];
4935 hv = NAT_HASH_FN(iph, 0, softn->ipf_nat_maprules_sz);
4937 for (np = softn->ipf_nat_map_rules[hv]; np; np = npnext) {
4938 npnext = np->in_mnext;
4939 if ((np->in_ifps[1] && (np->in_ifps[1] != ifp)))
4941 if (np->in_v[0] != 4)
4943 if (np->in_pr[1] && (np->in_pr[1] != fin->fin_p))
4945 if ((np->in_flags & IPN_RF) &&
4946 !(np->in_flags & nflags))
4948 if (np->in_flags & IPN_FILTER) {
4949 switch (ipf_nat_match(fin, np))
4960 } else if ((ipa & np->in_osrcmsk) != np->in_osrcaddr)
4964 !ipf_matchtag(&np->in_tag, &fr->fr_nattag))
4967 if (np->in_plabel != -1) {
4968 if (((np->in_flags & IPN_FILTER) == 0) &&
4969 (np->in_odport != fin->fin_data[1]))
4971 if (ipf_proxy_ok(fin, tcp, np) == 0)
4975 if (np->in_flags & IPN_NO) {
4979 MUTEX_ENTER(&softn->ipf_nat_new);
4981 * If we've matched a round-robin rule but it has
4982 * moved in the list since we got it, start over as
4983 * this is now no longer correct.
4985 if (npnext != np->in_mnext) {
4986 if ((np->in_flags & IPN_ROUNDR) != 0) {
4987 MUTEX_EXIT(&softn->ipf_nat_new);
4988 goto retry_roundrobin;
4990 npnext = np->in_mnext;
4993 nat = ipf_nat_add(fin, np, NULL, nflags, NAT_OUTBOUND);
4994 MUTEX_EXIT(&softn->ipf_nat_new);
5001 if ((np == NULL) && (nmsk < softn->ipf_nat_map_max)) {
5008 rval = ipf_nat_out(fin, nat, natadd, nflags);
5010 MUTEX_ENTER(&nat->nat_lock);
5011 ipf_nat_update(fin, nat);
5012 nat->nat_bytes[1] += fin->fin_plen;
5014 fin->fin_pktnum = nat->nat_pkts[1];
5015 MUTEX_EXIT(&nat->nat_lock);
5020 RWLOCK_EXIT(&softc->ipf_nat);
5025 if (passp != NULL) {
5026 DT1(frb_natv4out, fr_info_t *, fin);
5027 NBUMPSIDED(1, ns_drop);
5029 fin->fin_reason = FRB_NATV4;
5031 fin->fin_flx |= FI_BADNAT;
5032 NBUMPSIDED(1, ns_badnat);
5035 NBUMPSIDE(1, ns_ignored);
5038 NBUMPSIDE(1, ns_translated);
5041 fin->fin_ifp = sifp;
5045 /* ------------------------------------------------------------------------ */
5046 /* Function: ipf_nat_out */
5047 /* Returns: int - -1 == packet failed NAT checks so block it, */
5048 /* 1 == packet was successfully translated. */
5049 /* Parameters: fin(I) - pointer to packet information */
5050 /* nat(I) - pointer to NAT structure */
5051 /* natadd(I) - flag indicating if it is safe to add frag cache */
5052 /* nflags(I) - NAT flags set for this packet */
5054 /* Translate a packet coming "out" on an interface. */
5055 /* ------------------------------------------------------------------------ */
5057 ipf_nat_out(fin, nat, natadd, nflags)
5063 ipf_main_softc_t *softc = fin->fin_main_soft;
5064 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
5075 if ((natadd != 0) && (fin->fin_flx & FI_FRAG) && (np != NULL))
5076 (void) ipf_frag_natnew(softc, fin, 0, nat);
5079 * Fix up checksums, not by recalculating them, but
5080 * simply computing adjustments.
5081 * This is only done for STREAMS based IP implementations where the
5082 * checksum has already been calculated by IP. In all other cases,
5083 * IPFilter is called before the checksum needs calculating so there
5084 * is no call to modify whatever is in the header now.
5086 if (nflags == IPN_ICMPERR) {
5087 u_32_t s1, s2, sumd, msumd;
5089 s1 = LONG_SUM(ntohl(fin->fin_saddr));
5090 if (nat->nat_dir == NAT_OUTBOUND) {
5091 s2 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
5093 s2 = LONG_SUM(ntohl(nat->nat_odstaddr));
5095 CALC_SUMD(s1, s2, sumd);
5098 s1 = LONG_SUM(ntohl(fin->fin_daddr));
5099 if (nat->nat_dir == NAT_OUTBOUND) {
5100 s2 = LONG_SUM(ntohl(nat->nat_ndstaddr));
5102 s2 = LONG_SUM(ntohl(nat->nat_osrcaddr));
5104 CALC_SUMD(s1, s2, sumd);
5107 ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, msumd, 0);
5109 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
5110 defined(linux) || defined(BRIDGE_IPF) || defined(__FreeBSD__)
5113 * Strictly speaking, this isn't necessary on BSD
5114 * kernels because they do checksum calculation after
5115 * this code has run BUT if ipfilter is being used
5116 * to do NAT as a bridge, that code doesn't exist.
5118 switch (nat->nat_dir)
5121 ipf_fix_outcksum(fin->fin_cksum & FI_CK_L4PART,
5122 &fin->fin_ip->ip_sum,
5123 nat->nat_ipsumd, 0);
5127 ipf_fix_incksum(fin->fin_cksum & FI_CK_L4PART,
5128 &fin->fin_ip->ip_sum,
5129 nat->nat_ipsumd, 0);
5139 * Address assignment is after the checksum modification because
5140 * we are using the address in the packet for determining the
5141 * correct checksum offset (the ICMP error could be coming from
5144 switch (nat->nat_dir)
5147 fin->fin_ip->ip_src = nat->nat_nsrcip;
5148 fin->fin_saddr = nat->nat_nsrcaddr;
5149 fin->fin_ip->ip_dst = nat->nat_ndstip;
5150 fin->fin_daddr = nat->nat_ndstaddr;
5154 fin->fin_ip->ip_src = nat->nat_odstip;
5155 fin->fin_saddr = nat->nat_ndstaddr;
5156 fin->fin_ip->ip_dst = nat->nat_osrcip;
5157 fin->fin_daddr = nat->nat_nsrcaddr;
5164 skip = ipf_nat_decap(fin, nat);
5166 NBUMPSIDED(1, ns_decap_fail);
5172 #if defined(MENTAT) && defined(_KERNEL)
5179 if (m->m_flags & M_PKTHDR)
5180 m->m_pkthdr.len -= skip;
5184 MUTEX_ENTER(&nat->nat_lock);
5185 ipf_nat_update(fin, nat);
5186 MUTEX_EXIT(&nat->nat_lock);
5187 fin->fin_flx |= FI_NATED;
5188 if (np != NULL && np->in_tag.ipt_num[0] != 0)
5189 fin->fin_nattag = &np->in_tag;
5194 case NAT_DIVERTOUT :
5196 u_32_t s1, s2, sumd;
5201 m = M_DUP(np->in_divmp);
5203 NBUMPSIDED(1, ns_divert_dup);
5207 ip = MTOD(m, ip_t *);
5209 s2 = ntohs(ip->ip_id);
5212 ip->ip_len = ntohs(ip->ip_len);
5213 ip->ip_len += fin->fin_plen;
5214 ip->ip_len = htons(ip->ip_len);
5215 s2 += ntohs(ip->ip_len);
5216 CALC_SUMD(s1, s2, sumd);
5218 uh = (udphdr_t *)(ip + 1);
5219 uh->uh_ulen += fin->fin_plen;
5220 uh->uh_ulen = htons(uh->uh_ulen);
5221 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
5222 defined(linux) || defined(BRIDGE_IPF) || defined(__FreeBSD__)
5223 ipf_fix_outcksum(0, &ip->ip_sum, sumd, 0);
5228 fin->fin_src = ip->ip_src;
5229 fin->fin_dst = ip->ip_dst;
5231 fin->fin_plen += sizeof(ip_t) + 8; /* UDP + IPv4 hdr */
5232 fin->fin_dlen += sizeof(ip_t) + 8; /* UDP + IPv4 hdr */
5234 nflags &= ~IPN_TCPUDPICMP;
5243 if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
5246 if ((nat->nat_nsport != 0) && (nflags & IPN_TCPUDP)) {
5249 switch (nat->nat_dir)
5252 tcp->th_sport = nat->nat_nsport;
5253 fin->fin_data[0] = ntohs(nat->nat_nsport);
5254 tcp->th_dport = nat->nat_ndport;
5255 fin->fin_data[1] = ntohs(nat->nat_ndport);
5259 tcp->th_sport = nat->nat_odport;
5260 fin->fin_data[0] = ntohs(nat->nat_odport);
5261 tcp->th_dport = nat->nat_osport;
5262 fin->fin_data[1] = ntohs(nat->nat_osport);
5267 if ((nat->nat_nsport != 0) && (nflags & IPN_ICMPQUERY)) {
5269 icmp->icmp_id = nat->nat_nicmpid;
5272 csump = ipf_nat_proto(fin, nat, nflags);
5275 * The above comments do not hold for layer 4 (or higher)
5278 if (csump != NULL) {
5279 if (nat->nat_dir == NAT_OUTBOUND)
5280 ipf_fix_outcksum(fin->fin_cksum, csump,
5285 ipf_fix_incksum(fin->fin_cksum, csump,
5292 ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
5293 /* ------------------------------------------------------------- */
5294 /* A few quick notes: */
5295 /* Following are test conditions prior to calling the */
5296 /* ipf_proxy_check routine. */
5298 /* A NULL tcp indicates a non TCP/UDP packet. When dealing */
5299 /* with a redirect rule, we attempt to match the packet's */
5300 /* source port against in_dport, otherwise we'd compare the */
5301 /* packet's destination. */
5302 /* ------------------------------------------------------------- */
5303 if ((np != NULL) && (np->in_apr != NULL)) {
5304 i = ipf_proxy_check(fin, nat);
5307 } else if (i == -1) {
5308 NBUMPSIDED(1, ns_ipf_proxy_fail);
5313 fin->fin_flx |= FI_NATED;
5318 /* ------------------------------------------------------------------------ */
5319 /* Function: ipf_nat_checkin */
5320 /* Returns: int - -1 == packet failed NAT checks so block it, */
5321 /* 0 == no packet translation occurred, */
5322 /* 1 == packet was successfully translated. */
5323 /* Parameters: fin(I) - pointer to packet information */
5324 /* passp(I) - pointer to filtering result flags */
5326 /* Check to see if an incoming packet should be changed. ICMP packets are */
5327 /* first checked to see if they match an existing entry (if an error), */
5328 /* otherwise a search of the current NAT table is made. If neither results */
5329 /* in a match then a search for a matching NAT rule is made. Create a new */
5330 /* NAT entry if a we matched a NAT rule. Lastly, actually change the */
5331 /* packet header(s) as required. */
5332 /* ------------------------------------------------------------------------ */
5334 ipf_nat_checkin(fin, passp)
5338 ipf_main_softc_t *softc;
5339 ipf_nat_softc_t *softn;
5340 u_int nflags, natadd;
5341 ipnat_t *np, *npnext;
5342 int rval, natfailed;
5351 softc = fin->fin_main_soft;
5352 softn = softc->ipf_nat_soft;
5354 if (softn->ipf_nat_lock != 0)
5356 if (softn->ipf_nat_stats.ns_rules == 0 &&
5357 softn->ipf_nat_instances == NULL)
5368 if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
5381 * This is an incoming packet, so the destination is
5382 * the icmp_id and the source port equals 0
5384 if ((fin->fin_flx & FI_ICMPQUERY) != 0) {
5385 nflags = IPN_ICMPQUERY;
5386 dport = icmp->icmp_id;
5392 if ((nflags & IPN_TCPUDP)) {
5394 dport = fin->fin_data[1];
5400 READ_ENTER(&softc->ipf_nat);
5402 if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
5403 (nat = ipf_nat_icmperror(fin, &nflags, NAT_INBOUND)))
5405 else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
5407 else if ((nat = ipf_nat_inlookup(fin, nflags|NAT_SEARCH,
5409 fin->fin_src, in))) {
5410 nflags = nat->nat_flags;
5411 } else if (fin->fin_off == 0) {
5412 u_32_t hv, msk, rmsk = 0;
5415 * If there is no current entry in the nat table for this IP#,
5416 * create one for it (if there is a matching rule).
5419 msk = softn->ipf_nat_rdr_active_masks[rmsk];
5420 iph = in.s_addr & msk;
5421 hv = NAT_HASH_FN(iph, 0, softn->ipf_nat_rdrrules_sz);
5423 /* TRACE (iph,msk,rmsk,hv,softn->ipf_nat_rdrrules_sz) */
5424 for (np = softn->ipf_nat_rdr_rules[hv]; np; np = npnext) {
5425 npnext = np->in_rnext;
5426 if (np->in_ifps[0] && (np->in_ifps[0] != ifp))
5428 if (np->in_v[0] != 4)
5430 if (np->in_pr[0] && (np->in_pr[0] != fin->fin_p))
5432 if ((np->in_flags & IPN_RF) && !(np->in_flags & nflags))
5434 if (np->in_flags & IPN_FILTER) {
5435 switch (ipf_nat_match(fin, np))
5447 if ((in.s_addr & np->in_odstmsk) !=
5450 if (np->in_odport &&
5451 ((np->in_dtop < dport) ||
5452 (dport < np->in_odport)))
5456 if (np->in_plabel != -1) {
5457 if (!ipf_proxy_ok(fin, tcp, np)) {
5462 if (np->in_flags & IPN_NO) {
5467 MUTEX_ENTER(&softn->ipf_nat_new);
5469 * If we've matched a round-robin rule but it has
5470 * moved in the list since we got it, start over as
5471 * this is now no longer correct.
5473 if (npnext != np->in_rnext) {
5474 if ((np->in_flags & IPN_ROUNDR) != 0) {
5475 MUTEX_EXIT(&softn->ipf_nat_new);
5476 goto retry_roundrobin;
5478 npnext = np->in_rnext;
5481 nat = ipf_nat_add(fin, np, NULL, nflags, NAT_INBOUND);
5482 MUTEX_EXIT(&softn->ipf_nat_new);
5489 if ((np == NULL) && (rmsk < softn->ipf_nat_rdr_max)) {
5496 rval = ipf_nat_in(fin, nat, natadd, nflags);
5498 MUTEX_ENTER(&nat->nat_lock);
5499 ipf_nat_update(fin, nat);
5500 nat->nat_bytes[0] += fin->fin_plen;
5502 fin->fin_pktnum = nat->nat_pkts[0];
5503 MUTEX_EXIT(&nat->nat_lock);
5508 RWLOCK_EXIT(&softc->ipf_nat);
5513 if (passp != NULL) {
5514 DT1(frb_natv4in, fr_info_t *, fin);
5515 NBUMPSIDED(0, ns_drop);
5517 fin->fin_reason = FRB_NATV4;
5519 fin->fin_flx |= FI_BADNAT;
5520 NBUMPSIDED(0, ns_badnat);
5523 NBUMPSIDE(0, ns_ignored);
5526 NBUMPSIDE(0, ns_translated);
5533 /* ------------------------------------------------------------------------ */
5534 /* Function: ipf_nat_in */
5535 /* Returns: int - -1 == packet failed NAT checks so block it, */
5536 /* 1 == packet was successfully translated. */
5537 /* Parameters: fin(I) - pointer to packet information */
5538 /* nat(I) - pointer to NAT structure */
5539 /* natadd(I) - flag indicating if it is safe to add frag cache */
5540 /* nflags(I) - NAT flags set for this packet */
5541 /* Locks Held: ipf_nat(READ) */
5543 /* Translate a packet coming "in" on an interface. */
5544 /* ------------------------------------------------------------------------ */
5546 ipf_nat_in(fin, nat, natadd, nflags)
5552 ipf_main_softc_t *softc = fin->fin_main_soft;
5553 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
5554 u_32_t sumd, ipsumd, sum1, sum2;
5563 fin->fin_fr = nat->nat_fr;
5566 if ((natadd != 0) && (fin->fin_flx & FI_FRAG))
5567 (void) ipf_frag_natnew(softc, fin, 0, nat);
5569 /* ------------------------------------------------------------- */
5570 /* A few quick notes: */
5571 /* Following are test conditions prior to calling the */
5572 /* ipf_proxy_check routine. */
5574 /* A NULL tcp indicates a non TCP/UDP packet. When dealing */
5575 /* with a map rule, we attempt to match the packet's */
5576 /* source port against in_dport, otherwise we'd compare the */
5577 /* packet's destination. */
5578 /* ------------------------------------------------------------- */
5579 if (np->in_apr != NULL) {
5580 i = ipf_proxy_check(fin, nat);
5582 NBUMPSIDED(0, ns_ipf_proxy_fail);
5588 ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
5590 ipsumd = nat->nat_ipsumd;
5592 * Fix up checksums, not by recalculating them, but
5593 * simply computing adjustments.
5594 * Why only do this for some platforms on inbound packets ?
5595 * Because for those that it is done, IP processing is yet to happen
5596 * and so the IPv4 header checksum has not yet been evaluated.
5597 * Perhaps it should always be done for the benefit of things like
5598 * fast forwarding (so that it doesn't need to be recomputed) but with
5599 * header checksum offloading, perhaps it is a moot point.
5602 switch (nat->nat_dir)
5605 if ((fin->fin_flx & FI_ICMPERR) == 0) {
5606 fin->fin_ip->ip_src = nat->nat_nsrcip;
5607 fin->fin_saddr = nat->nat_nsrcaddr;
5609 sum1 = nat->nat_osrcaddr;
5610 sum2 = nat->nat_nsrcaddr;
5611 CALC_SUMD(sum1, sum2, sumd);
5614 fin->fin_ip->ip_dst = nat->nat_ndstip;
5615 fin->fin_daddr = nat->nat_ndstaddr;
5616 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
5617 defined(__osf__) || defined(linux)
5618 ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, ipsumd, 0);
5623 if ((fin->fin_flx & FI_ICMPERR) == 0) {
5624 fin->fin_ip->ip_src = nat->nat_odstip;
5625 fin->fin_saddr = nat->nat_odstaddr;
5627 sum1 = nat->nat_odstaddr;
5628 sum2 = nat->nat_ndstaddr;
5629 CALC_SUMD(sum1, sum2, sumd);
5632 fin->fin_ip->ip_dst = nat->nat_osrcip;
5633 fin->fin_daddr = nat->nat_osrcaddr;
5634 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
5635 defined(__osf__) || defined(linux)
5636 ipf_fix_incksum(0, &fin->fin_ip->ip_sum, ipsumd, 0);
5646 m = M_DUP(np->in_divmp);
5648 NBUMPSIDED(0, ns_divert_dup);
5652 ip = MTOD(m, ip_t *);
5654 sum1 = ntohs(ip->ip_len);
5655 ip->ip_len = ntohs(ip->ip_len);
5656 ip->ip_len += fin->fin_plen;
5657 ip->ip_len = htons(ip->ip_len);
5659 uh = (udphdr_t *)(ip + 1);
5660 uh->uh_ulen += fin->fin_plen;
5661 uh->uh_ulen = htons(uh->uh_ulen);
5663 sum2 = ntohs(ip->ip_id) + ntohs(ip->ip_len);
5664 sum2 += ntohs(ip->ip_off) & IP_DF;
5665 CALC_SUMD(sum1, sum2, sumd);
5667 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
5668 defined(__osf__) || defined(linux)
5669 ipf_fix_outcksum(0, &ip->ip_sum, sumd, 0);
5674 fin->fin_plen += sizeof(ip_t) + 8; /* UDP + new IPv4 hdr */
5675 fin->fin_dlen += sizeof(ip_t) + 8; /* UDP + old IPv4 hdr */
5677 nflags &= ~IPN_TCPUDPICMP;
5682 case NAT_DIVERTOUT :
5686 skip = ipf_nat_decap(fin, nat);
5688 NBUMPSIDED(0, ns_decap_fail);
5694 #if defined(MENTAT) && defined(_KERNEL)
5701 if (m->m_flags & M_PKTHDR)
5702 m->m_pkthdr.len -= skip;
5706 ipf_nat_update(fin, nat);
5707 nflags &= ~IPN_TCPUDPICMP;
5708 fin->fin_flx |= FI_NATED;
5709 if (np != NULL && np->in_tag.ipt_num[0] != 0)
5710 fin->fin_nattag = &np->in_tag;
5715 if (nflags & IPN_TCPUDP)
5718 if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
5721 if ((nat->nat_odport != 0) && (nflags & IPN_TCPUDP)) {
5722 switch (nat->nat_dir)
5725 tcp->th_sport = nat->nat_nsport;
5726 fin->fin_data[0] = ntohs(nat->nat_nsport);
5727 tcp->th_dport = nat->nat_ndport;
5728 fin->fin_data[1] = ntohs(nat->nat_ndport);
5732 tcp->th_sport = nat->nat_odport;
5733 fin->fin_data[0] = ntohs(nat->nat_odport);
5734 tcp->th_dport = nat->nat_osport;
5735 fin->fin_data[1] = ntohs(nat->nat_osport);
5741 if ((nat->nat_odport != 0) && (nflags & IPN_ICMPQUERY)) {
5744 icmp->icmp_id = nat->nat_nicmpid;
5747 csump = ipf_nat_proto(fin, nat, nflags);
5750 * The above comments do not hold for layer 4 (or higher)
5753 if (csump != NULL) {
5754 if (nat->nat_dir == NAT_OUTBOUND)
5755 ipf_fix_incksum(0, csump, nat->nat_sumd[0], 0);
5757 ipf_fix_outcksum(0, csump, nat->nat_sumd[0], 0);
5761 fin->fin_flx |= FI_NATED;
5762 if (np != NULL && np->in_tag.ipt_num[0] != 0)
5763 fin->fin_nattag = &np->in_tag;
5768 /* ------------------------------------------------------------------------ */
5769 /* Function: ipf_nat_proto */
5770 /* Returns: u_short* - pointer to transport header checksum to update, */
5771 /* NULL if the transport protocol is not recognised */
5772 /* as needing a checksum update. */
5773 /* Parameters: fin(I) - pointer to packet information */
5774 /* nat(I) - pointer to NAT structure */
5775 /* nflags(I) - NAT flags set for this packet */
5777 /* Return the pointer to the checksum field for each protocol so understood.*/
5778 /* If support for making other changes to a protocol header is required, */
5779 /* that is not strictly 'address' translation, such as clamping the MSS in */
5780 /* TCP down to a specific value, then do it from here. */
5781 /* ------------------------------------------------------------------------ */
5783 ipf_nat_proto(fin, nat, nflags)
5794 if (fin->fin_out == 0) {
5795 fin->fin_rev = (nat->nat_dir & NAT_OUTBOUND);
5797 fin->fin_rev = ((nat->nat_dir & NAT_OUTBOUND) == 0);
5805 if ((nflags & IPN_TCP) != 0)
5806 csump = &tcp->th_sum;
5809 * Do a MSS CLAMPING on a SYN packet,
5810 * only deal IPv4 for now.
5812 if ((nat->nat_mssclamp != 0) && (tcp->th_flags & TH_SYN) != 0)
5813 ipf_nat_mssclamp(tcp, nat->nat_mssclamp, fin, csump);
5820 if ((nflags & IPN_UDP) != 0) {
5821 if (udp->uh_sum != 0)
5822 csump = &udp->uh_sum;
5829 if ((nflags & IPN_ICMPQUERY) != 0) {
5830 if (icmp->icmp_cksum != 0)
5831 csump = &icmp->icmp_cksum;
5836 case IPPROTO_ICMPV6 :
5838 struct icmp6_hdr *icmp6 = (struct icmp6_hdr *)fin->fin_dp;
5840 icmp6 = fin->fin_dp;
5842 if ((nflags & IPN_ICMPQUERY) != 0) {
5843 if (icmp6->icmp6_cksum != 0)
5844 csump = &icmp6->icmp6_cksum;
5854 /* ------------------------------------------------------------------------ */
5855 /* Function: ipf_nat_expire */
5857 /* Parameters: softc(I) - pointer to soft context main structure */
5859 /* Check all of the timeout queues for entries at the top which need to be */
5861 /* ------------------------------------------------------------------------ */
5863 ipf_nat_expire(softc)
5864 ipf_main_softc_t *softc;
5866 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
5867 ipftq_t *ifq, *ifqnext;
5868 ipftqent_t *tqe, *tqn;
5873 WRITE_ENTER(&softc->ipf_nat);
5874 for (ifq = softn->ipf_nat_tcptq, i = 0; ifq != NULL;
5875 ifq = ifq->ifq_next) {
5876 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
5877 if (tqe->tqe_die > softc->ipf_ticks)
5879 tqn = tqe->tqe_next;
5880 ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
5884 for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifq->ifq_next) {
5885 for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
5886 if (tqe->tqe_die > softc->ipf_ticks)
5888 tqn = tqe->tqe_next;
5889 ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
5893 for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifqnext) {
5894 ifqnext = ifq->ifq_next;
5896 if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
5897 (ifq->ifq_ref == 0)) {
5898 ipf_freetimeoutqueue(softc, ifq);
5902 if (softn->ipf_nat_doflush != 0) {
5903 ipf_nat_extraflush(softc, softn, 2);
5904 softn->ipf_nat_doflush = 0;
5907 RWLOCK_EXIT(&softc->ipf_nat);
5912 /* ------------------------------------------------------------------------ */
5913 /* Function: ipf_nat_sync */
5915 /* Parameters: softc(I) - pointer to soft context main structure */
5916 /* ifp(I) - pointer to network interface */
5918 /* Walk through all of the currently active NAT sessions, looking for those */
5919 /* which need to have their translated address updated. */
5920 /* ------------------------------------------------------------------------ */
5922 ipf_nat_sync(softc, ifp)
5923 ipf_main_softc_t *softc;
5926 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
5927 u_32_t sum1, sum2, sumd;
5935 if (softc->ipf_running <= 0)
5939 * Change IP addresses for NAT sessions for any protocol except TCP
5940 * since it will break the TCP connection anyway. The only rules
5941 * which will get changed are those which are "map ... -> 0/32",
5942 * where the rule specifies the address is taken from the interface.
5945 WRITE_ENTER(&softc->ipf_nat);
5947 if (softc->ipf_running <= 0) {
5948 RWLOCK_EXIT(&softc->ipf_nat);
5952 for (nat = softn->ipf_nat_instances; nat; nat = nat->nat_next) {
5953 if ((nat->nat_flags & IPN_TCP) != 0)
5958 if (n->in_v[1] == 4) {
5959 if (n->in_redir & NAT_MAP) {
5960 if ((n->in_nsrcaddr != 0) ||
5961 (n->in_nsrcmsk != 0xffffffff))
5963 } else if (n->in_redir & NAT_REDIRECT) {
5964 if ((n->in_ndstaddr != 0) ||
5965 (n->in_ndstmsk != 0xffffffff))
5970 if (n->in_v[1] == 4) {
5971 if (n->in_redir & NAT_MAP) {
5972 if (!IP6_ISZERO(&n->in_nsrcaddr) ||
5973 !IP6_ISONES(&n->in_nsrcmsk))
5975 } else if (n->in_redir & NAT_REDIRECT) {
5976 if (!IP6_ISZERO(&n->in_ndstaddr) ||
5977 !IP6_ISONES(&n->in_ndstmsk))
5984 if (((ifp == NULL) || (ifp == nat->nat_ifps[0]) ||
5985 (ifp == nat->nat_ifps[1]))) {
5986 nat->nat_ifps[0] = GETIFP(nat->nat_ifnames[0],
5988 if ((nat->nat_ifps[0] != NULL) &&
5989 (nat->nat_ifps[0] != (void *)-1)) {
5990 nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
5992 if (nat->nat_ifnames[1][0] != '\0') {
5993 nat->nat_ifps[1] = GETIFP(nat->nat_ifnames[1],
5996 nat->nat_ifps[1] = nat->nat_ifps[0];
5998 if ((nat->nat_ifps[1] != NULL) &&
5999 (nat->nat_ifps[1] != (void *)-1)) {
6000 nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
6002 ifp2 = nat->nat_ifps[0];
6007 * Change the map-to address to be the same as the
6010 sum1 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
6011 if (ipf_ifpaddr(softc, nat->nat_v[0], FRI_NORMAL, ifp2,
6013 if (nat->nat_v[0] == 4)
6014 nat->nat_nsrcip = in.in4;
6016 sum2 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
6021 * Readjust the checksum adjustment to take into
6022 * account the new IP#.
6024 CALC_SUMD(sum1, sum2, sumd);
6025 /* XXX - dont change for TCP when solaris does
6026 * hardware checksumming.
6028 sumd += nat->nat_sumd[0];
6029 nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
6030 nat->nat_sumd[1] = nat->nat_sumd[0];
6034 for (n = softn->ipf_nat_list; (n != NULL); n = n->in_next) {
6035 char *base = n->in_names;
6037 if ((ifp == NULL) || (n->in_ifps[0] == ifp))
6038 n->in_ifps[0] = ipf_resolvenic(softc,
6039 base + n->in_ifnames[0],
6041 if ((ifp == NULL) || (n->in_ifps[1] == ifp))
6042 n->in_ifps[1] = ipf_resolvenic(softc,
6043 base + n->in_ifnames[1],
6046 if (n->in_redir & NAT_REDIRECT)
6051 if (((ifp == NULL) || (n->in_ifps[idx] == ifp)) &&
6052 (n->in_ifps[idx] != NULL &&
6053 n->in_ifps[idx] != (void *)-1)) {
6055 ipf_nat_nextaddrinit(softc, n->in_names, &n->in_osrc,
6056 0, n->in_ifps[idx]);
6057 ipf_nat_nextaddrinit(softc, n->in_names, &n->in_odst,
6058 0, n->in_ifps[idx]);
6059 ipf_nat_nextaddrinit(softc, n->in_names, &n->in_nsrc,
6060 0, n->in_ifps[idx]);
6061 ipf_nat_nextaddrinit(softc, n->in_names, &n->in_ndst,
6062 0, n->in_ifps[idx]);
6065 RWLOCK_EXIT(&softc->ipf_nat);
6070 /* ------------------------------------------------------------------------ */
6071 /* Function: ipf_nat_icmpquerytype */
6072 /* Returns: int - 1 == success, 0 == failure */
6073 /* Parameters: icmptype(I) - ICMP type number */
6075 /* Tests to see if the ICMP type number passed is a query/response type or */
6077 /* ------------------------------------------------------------------------ */
6079 ipf_nat_icmpquerytype(icmptype)
6084 * For the ICMP query NAT code, it is essential that both the query
6085 * and the reply match on the NAT rule. Because the NAT structure
6086 * does not keep track of the icmptype, and a single NAT structure
6087 * is used for all icmp types with the same src, dest and id, we
6088 * simply define the replies as queries as well. The funny thing is,
6089 * altough it seems silly to call a reply a query, this is exactly
6090 * as it is defined in the IPv4 specification
6094 case ICMP_ECHOREPLY:
6096 /* route advertisement/solicitation is currently unsupported: */
6097 /* it would require rewriting the ICMP data section */
6099 case ICMP_TSTAMPREPLY:
6101 case ICMP_IREQREPLY:
6103 case ICMP_MASKREPLY:
6111 /* ------------------------------------------------------------------------ */
6112 /* Function: nat_log */
6114 /* Parameters: softc(I) - pointer to soft context main structure */
6115 /* softn(I) - pointer to NAT context structure */
6116 /* nat(I) - pointer to NAT structure */
6117 /* action(I) - action related to NAT structure being performed */
6119 /* Creates a NAT log entry. */
6120 /* ------------------------------------------------------------------------ */
6122 ipf_nat_log(softc, softn, nat, action)
6123 ipf_main_softc_t *softc;
6124 ipf_nat_softc_t *softn;
6138 bcopy((char *)&nat->nat_osrc6, (char *)&natl.nl_osrcip,
6139 sizeof(natl.nl_osrcip));
6140 bcopy((char *)&nat->nat_nsrc6, (char *)&natl.nl_nsrcip,
6141 sizeof(natl.nl_nsrcip));
6142 bcopy((char *)&nat->nat_odst6, (char *)&natl.nl_odstip,
6143 sizeof(natl.nl_odstip));
6144 bcopy((char *)&nat->nat_ndst6, (char *)&natl.nl_ndstip,
6145 sizeof(natl.nl_ndstip));
6147 natl.nl_bytes[0] = nat->nat_bytes[0];
6148 natl.nl_bytes[1] = nat->nat_bytes[1];
6149 natl.nl_pkts[0] = nat->nat_pkts[0];
6150 natl.nl_pkts[1] = nat->nat_pkts[1];
6151 natl.nl_odstport = nat->nat_odport;
6152 natl.nl_osrcport = nat->nat_osport;
6153 natl.nl_nsrcport = nat->nat_nsport;
6154 natl.nl_ndstport = nat->nat_ndport;
6155 natl.nl_p[0] = nat->nat_pr[0];
6156 natl.nl_p[1] = nat->nat_pr[1];
6157 natl.nl_v[0] = nat->nat_v[0];
6158 natl.nl_v[1] = nat->nat_v[1];
6159 natl.nl_type = nat->nat_redir;
6160 natl.nl_action = action;
6163 bcopy(nat->nat_ifnames[0], natl.nl_ifnames[0],
6164 sizeof(nat->nat_ifnames[0]));
6165 bcopy(nat->nat_ifnames[1], natl.nl_ifnames[1],
6166 sizeof(nat->nat_ifnames[1]));
6169 if (nat->nat_ptr != NULL) {
6170 for (rulen = 0, np = softn->ipf_nat_list; np != NULL;
6171 np = np->in_next, rulen++)
6172 if (np == nat->nat_ptr) {
6173 natl.nl_rule = rulen;
6179 sizes[0] = sizeof(natl);
6182 (void) ipf_log_items(softc, IPL_LOGNAT, NULL, items, sizes, types, 1);
6187 #if defined(__OpenBSD__)
6188 /* ------------------------------------------------------------------------ */
6189 /* Function: ipf_nat_ifdetach */
6191 /* Parameters: ifp(I) - pointer to network interface */
6193 /* Compatibility interface for OpenBSD to trigger the correct updating of */
6194 /* interface references within IPFilter. */
6195 /* ------------------------------------------------------------------------ */
6197 ipf_nat_ifdetach(ifp)
6200 ipf_main_softc_t *softc;
6202 softc = ipf_get_softc(0);
6210 /* ------------------------------------------------------------------------ */
6211 /* Function: ipf_nat_rule_deref */
6213 /* Parameters: softc(I) - pointer to soft context main structure */
6214 /* inp(I) - pointer to pointer to NAT rule */
6215 /* Write Locks: ipf_nat */
6217 /* Dropping the refernce count for a rule means that whatever held the */
6218 /* pointer to this rule (*inp) is no longer interested in it and when the */
6219 /* reference count drops to zero, any resources allocated for the rule can */
6220 /* be released and the rule itself free'd. */
6221 /* ------------------------------------------------------------------------ */
6223 ipf_nat_rule_deref(softc, inp)
6224 ipf_main_softc_t *softc;
6227 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6236 if (n->in_apr != NULL)
6237 ipf_proxy_deref(n->in_apr);
6239 ipf_nat_rule_fini(softc, n);
6241 if (n->in_redir & NAT_REDIRECT) {
6242 if ((n->in_flags & IPN_PROXYRULE) == 0) {
6243 ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_rdr);
6246 if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
6247 if ((n->in_flags & IPN_PROXYRULE) == 0) {
6248 ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_map);
6252 if (n->in_tqehead[0] != NULL) {
6253 if (ipf_deletetimeoutqueue(n->in_tqehead[0]) == 0) {
6254 ipf_freetimeoutqueue(softc, n->in_tqehead[1]);
6258 if (n->in_tqehead[1] != NULL) {
6259 if (ipf_deletetimeoutqueue(n->in_tqehead[1]) == 0) {
6260 ipf_freetimeoutqueue(softc, n->in_tqehead[1]);
6264 if ((n->in_flags & IPN_PROXYRULE) == 0) {
6265 ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules);
6268 MUTEX_DESTROY(&n->in_lock);
6270 KFREES(n, n->in_size);
6272 #if SOLARIS && !defined(INSTANCES)
6273 if (softn->ipf_nat_stats.ns_rules == 0)
6274 pfil_delayed_copy = 1;
6279 /* ------------------------------------------------------------------------ */
6280 /* Function: ipf_nat_deref */
6282 /* Parameters: softc(I) - pointer to soft context main structure */
6283 /* natp(I) - pointer to pointer to NAT table entry */
6285 /* Decrement the reference counter for this NAT table entry and free it if */
6286 /* there are no more things using it. */
6288 /* IF nat_ref == 1 when this function is called, then we have an orphan nat */
6289 /* structure *because* it only gets called on paths _after_ nat_ref has been*/
6290 /* incremented. If nat_ref == 1 then we shouldn't decrement it here */
6291 /* because nat_delete() will do that and send nat_ref to -1. */
6293 /* Holding the lock on nat_lock is required to serialise nat_delete() being */
6294 /* called from a NAT flush ioctl with a deref happening because of a packet.*/
6295 /* ------------------------------------------------------------------------ */
6297 ipf_nat_deref(softc, natp)
6298 ipf_main_softc_t *softc;
6306 MUTEX_ENTER(&nat->nat_lock);
6307 if (nat->nat_ref > 1) {
6309 ASSERT(nat->nat_ref >= 0);
6310 MUTEX_EXIT(&nat->nat_lock);
6313 MUTEX_EXIT(&nat->nat_lock);
6315 WRITE_ENTER(&softc->ipf_nat);
6316 ipf_nat_delete(softc, nat, NL_EXPIRE);
6317 RWLOCK_EXIT(&softc->ipf_nat);
6321 /* ------------------------------------------------------------------------ */
6322 /* Function: ipf_nat_clone */
6323 /* Returns: ipstate_t* - NULL == cloning failed, */
6324 /* else pointer to new state structure */
6325 /* Parameters: fin(I) - pointer to packet information */
6326 /* is(I) - pointer to master state structure */
6327 /* Write Lock: ipf_nat */
6329 /* Create a "duplcate" state table entry from the master. */
6330 /* ------------------------------------------------------------------------ */
6332 ipf_nat_clone(fin, nat)
6336 ipf_main_softc_t *softc = fin->fin_main_soft;
6337 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6342 KMALLOC(clone, nat_t *);
6343 if (clone == NULL) {
6344 NBUMPSIDED(fin->fin_out, ns_clone_nomem);
6347 bcopy((char *)nat, (char *)clone, sizeof(*clone));
6349 MUTEX_NUKE(&clone->nat_lock);
6351 clone->nat_rev = fin->fin_rev;
6352 clone->nat_aps = NULL;
6354 * Initialize all these so that ipf_nat_delete() doesn't cause a crash.
6356 clone->nat_tqe.tqe_pnext = NULL;
6357 clone->nat_tqe.tqe_next = NULL;
6358 clone->nat_tqe.tqe_ifq = NULL;
6359 clone->nat_tqe.tqe_parent = clone;
6361 clone->nat_flags &= ~SI_CLONE;
6362 clone->nat_flags |= SI_CLONED;
6365 clone->nat_hm->hm_ref++;
6367 if (ipf_nat_insert(softc, softn, clone) == -1) {
6369 NBUMPSIDED(fin->fin_out, ns_insert_fail);
6373 np = clone->nat_ptr;
6375 if (softn->ipf_nat_logging)
6376 ipf_nat_log(softc, softn, clone, NL_CLONE);
6381 MUTEX_ENTER(&fr->fr_lock);
6383 MUTEX_EXIT(&fr->fr_lock);
6388 * Because the clone is created outside the normal loop of things and
6389 * TCP has special needs in terms of state, initialise the timeout
6390 * state of the new NAT from here.
6392 if (clone->nat_pr[0] == IPPROTO_TCP) {
6393 (void) ipf_tcp_age(&clone->nat_tqe, fin, softn->ipf_nat_tcptq,
6394 clone->nat_flags, 2);
6396 clone->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, clone);
6397 if (softn->ipf_nat_logging)
6398 ipf_nat_log(softc, softn, clone, NL_CLONE);
6403 /* ------------------------------------------------------------------------ */
6404 /* Function: ipf_nat_wildok */
6405 /* Returns: int - 1 == packet's ports match wildcards */
6406 /* 0 == packet's ports don't match wildcards */
6407 /* Parameters: nat(I) - NAT entry */
6408 /* sport(I) - source port */
6409 /* dport(I) - destination port */
6410 /* flags(I) - wildcard flags */
6411 /* dir(I) - packet direction */
6413 /* Use NAT entry and packet direction to determine which combination of */
6414 /* wildcard flags should be used. */
6415 /* ------------------------------------------------------------------------ */
6417 ipf_nat_wildok(nat, sport, dport, flags, dir)
6419 int sport, dport, flags, dir;
6422 * When called by dir is set to
6423 * nat_inlookup NAT_INBOUND (0)
6424 * nat_outlookup NAT_OUTBOUND (1)
6426 * We simply combine the packet's direction in dir with the original
6427 * "intended" direction of that NAT entry in nat->nat_dir to decide
6428 * which combination of wildcard flags to allow.
6430 switch ((dir << 1) | (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND)))
6432 case 3: /* outbound packet / outbound entry */
6433 if (((nat->nat_osport == sport) ||
6434 (flags & SI_W_SPORT)) &&
6435 ((nat->nat_odport == dport) ||
6436 (flags & SI_W_DPORT)))
6439 case 2: /* outbound packet / inbound entry */
6440 if (((nat->nat_osport == dport) ||
6441 (flags & SI_W_SPORT)) &&
6442 ((nat->nat_odport == sport) ||
6443 (flags & SI_W_DPORT)))
6446 case 1: /* inbound packet / outbound entry */
6447 if (((nat->nat_osport == dport) ||
6448 (flags & SI_W_SPORT)) &&
6449 ((nat->nat_odport == sport) ||
6450 (flags & SI_W_DPORT)))
6453 case 0: /* inbound packet / inbound entry */
6454 if (((nat->nat_osport == sport) ||
6455 (flags & SI_W_SPORT)) &&
6456 ((nat->nat_odport == dport) ||
6457 (flags & SI_W_DPORT)))
6468 /* ------------------------------------------------------------------------ */
6469 /* Function: nat_mssclamp */
6471 /* Parameters: tcp(I) - pointer to TCP header */
6472 /* maxmss(I) - value to clamp the TCP MSS to */
6473 /* fin(I) - pointer to packet information */
6474 /* csump(I) - pointer to TCP checksum */
6476 /* Check for MSS option and clamp it if necessary. If found and changed, */
6477 /* then the TCP header checksum will be updated to reflect the change in */
6479 /* ------------------------------------------------------------------------ */
6481 ipf_nat_mssclamp(tcp, maxmss, fin, csump)
6487 u_char *cp, *ep, opt;
6491 hlen = TCP_OFF(tcp) << 2;
6492 if (hlen > sizeof(*tcp)) {
6493 cp = (u_char *)tcp + sizeof(*tcp);
6494 ep = (u_char *)tcp + hlen;
6498 if (opt == TCPOPT_EOL)
6500 else if (opt == TCPOPT_NOP) {
6508 if ((cp + advance > ep) || (advance <= 0))
6515 mss = cp[2] * 256 + cp[3];
6517 cp[2] = maxmss / 256;
6518 cp[3] = maxmss & 0xff;
6519 CALC_SUMD(mss, maxmss, sumd);
6520 ipf_fix_outcksum(0, csump, sumd, 0);
6524 /* ignore unknown options */
6534 /* ------------------------------------------------------------------------ */
6535 /* Function: ipf_nat_setqueue */
6537 /* Parameters: softc(I) - pointer to soft context main structure */
6538 /* softn(I) - pointer to NAT context structure */
6539 /* nat(I)- pointer to NAT structure */
6540 /* Locks: ipf_nat (read or write) */
6542 /* Put the NAT entry on its default queue entry, using rev as a helped in */
6543 /* determining which queue it should be placed on. */
6544 /* ------------------------------------------------------------------------ */
6546 ipf_nat_setqueue(softc, softn, nat)
6547 ipf_main_softc_t *softc;
6548 ipf_nat_softc_t *softn;
6551 ipftq_t *oifq, *nifq;
6552 int rev = nat->nat_rev;
6554 if (nat->nat_ptr != NULL)
6555 nifq = nat->nat_ptr->in_tqehead[rev];
6560 switch (nat->nat_pr[0])
6563 nifq = &softn->ipf_nat_udptq;
6566 nifq = &softn->ipf_nat_icmptq;
6569 nifq = softn->ipf_nat_tcptq +
6570 nat->nat_tqe.tqe_state[rev];
6573 nifq = &softn->ipf_nat_iptq;
6578 oifq = nat->nat_tqe.tqe_ifq;
6580 * If it's currently on a timeout queue, move it from one queue to
6581 * another, else put it on the end of the newly determined queue.
6584 ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq, nifq);
6586 ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe, nifq, nat);
6591 /* ------------------------------------------------------------------------ */
6592 /* Function: nat_getnext */
6593 /* Returns: int - 0 == ok, else error */
6594 /* Parameters: softc(I) - pointer to soft context main structure */
6595 /* t(I) - pointer to ipftoken structure */
6596 /* itp(I) - pointer to ipfgeniter_t structure */
6598 /* Fetch the next nat/ipnat structure pointer from the linked list and */
6599 /* copy it out to the storage space pointed to by itp_data. The next item */
6600 /* in the list to look at is put back in the ipftoken struture. */
6601 /* ------------------------------------------------------------------------ */
6603 ipf_nat_getnext(softc, t, itp, objp)
6604 ipf_main_softc_t *softc;
6609 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6610 hostmap_t *hm, *nexthm = NULL, zerohm;
6611 ipnat_t *ipn, *nextipnat = NULL, zeroipn;
6612 nat_t *nat, *nextnat = NULL, zeronat;
6616 if (itp->igi_nitems != 1) {
6621 READ_ENTER(&softc->ipf_nat);
6623 switch (itp->igi_type)
6625 case IPFGENITER_HOSTMAP :
6628 nexthm = softn->ipf_hm_maplist;
6630 nexthm = hm->hm_next;
6632 if (nexthm != NULL) {
6633 ATOMIC_INC32(nexthm->hm_ref);
6634 t->ipt_data = nexthm;
6636 bzero(&zerohm, sizeof(zerohm));
6640 nnext = nexthm->hm_next;
6643 case IPFGENITER_IPNAT :
6646 nextipnat = softn->ipf_nat_list;
6648 nextipnat = ipn->in_next;
6650 if (nextipnat != NULL) {
6651 ATOMIC_INC32(nextipnat->in_use);
6652 t->ipt_data = nextipnat;
6654 bzero(&zeroipn, sizeof(zeroipn));
6655 nextipnat = &zeroipn;
6658 nnext = nextipnat->in_next;
6661 case IPFGENITER_NAT :
6664 nextnat = softn->ipf_nat_instances;
6666 nextnat = nat->nat_next;
6668 if (nextnat != NULL) {
6669 MUTEX_ENTER(&nextnat->nat_lock);
6671 MUTEX_EXIT(&nextnat->nat_lock);
6672 t->ipt_data = nextnat;
6674 bzero(&zeronat, sizeof(zeronat));
6678 nnext = nextnat->nat_next;
6682 RWLOCK_EXIT(&softc->ipf_nat);
6687 RWLOCK_EXIT(&softc->ipf_nat);
6689 objp->ipfo_ptr = itp->igi_data;
6691 switch (itp->igi_type)
6693 case IPFGENITER_HOSTMAP :
6694 error = COPYOUT(nexthm, objp->ipfo_ptr, sizeof(*nexthm));
6700 WRITE_ENTER(&softc->ipf_nat);
6701 ipf_nat_hostmapdel(softc, &hm);
6702 RWLOCK_EXIT(&softc->ipf_nat);
6706 case IPFGENITER_IPNAT :
6707 objp->ipfo_size = nextipnat->in_size;
6708 objp->ipfo_type = IPFOBJ_IPNAT;
6709 error = ipf_outobjk(softc, objp, nextipnat);
6711 WRITE_ENTER(&softc->ipf_nat);
6712 ipf_nat_rule_deref(softc, &ipn);
6713 RWLOCK_EXIT(&softc->ipf_nat);
6717 case IPFGENITER_NAT :
6718 objp->ipfo_size = sizeof(nat_t);
6719 objp->ipfo_type = IPFOBJ_NAT;
6720 error = ipf_outobjk(softc, objp, nextnat);
6722 ipf_nat_deref(softc, &nat);
6728 ipf_token_mark_complete(t);
6734 /* ------------------------------------------------------------------------ */
6735 /* Function: nat_extraflush */
6736 /* Returns: int - 0 == success, -1 == failure */
6737 /* Parameters: softc(I) - pointer to soft context main structure */
6738 /* softn(I) - pointer to NAT context structure */
6739 /* which(I) - how to flush the active NAT table */
6740 /* Write Locks: ipf_nat */
6742 /* Flush nat tables. Three actions currently defined: */
6743 /* which == 0 : flush all nat table entries */
6744 /* which == 1 : flush TCP connections which have started to close but are */
6745 /* stuck for some reason. */
6746 /* which == 2 : flush TCP connections which have been idle for a long time, */
6747 /* starting at > 4 days idle and working back in successive half-*/
6748 /* days to at most 12 hours old. If this fails to free enough */
6749 /* slots then work backwards in half hour slots to 30 minutes. */
6750 /* If that too fails, then work backwards in 30 second intervals */
6751 /* for the last 30 minutes to at worst 30 seconds idle. */
6752 /* ------------------------------------------------------------------------ */
6754 ipf_nat_extraflush(softc, softn, which)
6755 ipf_main_softc_t *softc;
6756 ipf_nat_softc_t *softn;
6771 softn->ipf_nat_stats.ns_flush_all++;
6773 * Style 0 flush removes everything...
6775 for (natp = &softn->ipf_nat_instances;
6776 ((nat = *natp) != NULL); ) {
6777 ipf_nat_delete(softc, nat, NL_FLUSH);
6783 softn->ipf_nat_stats.ns_flush_closing++;
6785 * Since we're only interested in things that are closing,
6786 * we can start with the appropriate timeout queue.
6788 for (ifq = softn->ipf_nat_tcptq + IPF_TCPS_CLOSE_WAIT;
6789 ifq != NULL; ifq = ifq->ifq_next) {
6791 for (tqn = ifq->ifq_head; tqn != NULL; ) {
6792 nat = tqn->tqe_parent;
6793 tqn = tqn->tqe_next;
6794 if (nat->nat_pr[0] != IPPROTO_TCP ||
6795 nat->nat_pr[1] != IPPROTO_TCP)
6797 ipf_nat_delete(softc, nat, NL_EXPIRE);
6803 * Also need to look through the user defined queues.
6805 for (ifq = softn->ipf_nat_utqe; ifq != NULL;
6806 ifq = ifq->ifq_next) {
6807 for (tqn = ifq->ifq_head; tqn != NULL; ) {
6808 nat = tqn->tqe_parent;
6809 tqn = tqn->tqe_next;
6810 if (nat->nat_pr[0] != IPPROTO_TCP ||
6811 nat->nat_pr[1] != IPPROTO_TCP)
6814 if ((nat->nat_tcpstate[0] >
6815 IPF_TCPS_ESTABLISHED) &&
6816 (nat->nat_tcpstate[1] >
6817 IPF_TCPS_ESTABLISHED)) {
6818 ipf_nat_delete(softc, nat, NL_EXPIRE);
6826 * Args 5-11 correspond to flushing those particular states
6827 * for TCP connections.
6829 case IPF_TCPS_CLOSE_WAIT :
6830 case IPF_TCPS_FIN_WAIT_1 :
6831 case IPF_TCPS_CLOSING :
6832 case IPF_TCPS_LAST_ACK :
6833 case IPF_TCPS_FIN_WAIT_2 :
6834 case IPF_TCPS_TIME_WAIT :
6835 case IPF_TCPS_CLOSED :
6836 softn->ipf_nat_stats.ns_flush_state++;
6837 tqn = softn->ipf_nat_tcptq[which].ifq_head;
6838 while (tqn != NULL) {
6839 nat = tqn->tqe_parent;
6840 tqn = tqn->tqe_next;
6841 ipf_nat_delete(softc, nat, NL_FLUSH);
6850 softn->ipf_nat_stats.ns_flush_timeout++;
6852 * Take a large arbitrary number to mean the number of seconds
6853 * for which which consider to be the maximum value we'll allow
6854 * the expiration to be.
6856 which = IPF_TTLVAL(which);
6857 for (natp = &softn->ipf_nat_instances;
6858 ((nat = *natp) != NULL); ) {
6859 if (softc->ipf_ticks - nat->nat_touched > which) {
6860 ipf_nat_delete(softc, nat, NL_FLUSH);
6863 natp = &nat->nat_next;
6873 softn->ipf_nat_stats.ns_flush_queue++;
6876 * Asked to remove inactive entries because the table is full, try
6877 * again, 3 times, if first attempt failed with a different criteria
6878 * each time. The order tried in must be in decreasing age.
6879 * Another alternative is to implement random drop and drop N entries
6880 * at random until N have been freed up.
6882 if (softc->ipf_ticks - softn->ipf_nat_last_force_flush >
6884 softn->ipf_nat_last_force_flush = softc->ipf_ticks;
6886 removed = ipf_queueflush(softc, ipf_nat_flush_entry,
6887 softn->ipf_nat_tcptq,
6888 softn->ipf_nat_utqe,
6889 &softn->ipf_nat_stats.ns_active,
6890 softn->ipf_nat_table_sz,
6891 softn->ipf_nat_table_wm_low);
6899 /* ------------------------------------------------------------------------ */
6900 /* Function: ipf_nat_flush_entry */
6901 /* Returns: 0 - always succeeds */
6902 /* Parameters: softc(I) - pointer to soft context main structure */
6903 /* entry(I) - pointer to NAT entry */
6904 /* Write Locks: ipf_nat */
6906 /* This function is a stepping stone between ipf_queueflush() and */
6907 /* nat_dlete(). It is used so we can provide a uniform interface via the */
6908 /* ipf_queueflush() function. Since the nat_delete() function returns void */
6909 /* we translate that to mean it always succeeds in deleting something. */
6910 /* ------------------------------------------------------------------------ */
6912 ipf_nat_flush_entry(softc, entry)
6913 ipf_main_softc_t *softc;
6916 ipf_nat_delete(softc, entry, NL_FLUSH);
6921 /* ------------------------------------------------------------------------ */
6922 /* Function: ipf_nat_iterator */
6923 /* Returns: int - 0 == ok, else error */
6924 /* Parameters: softc(I) - pointer to soft context main structure */
6925 /* token(I) - pointer to ipftoken structure */
6926 /* itp(I) - pointer to ipfgeniter_t structure */
6927 /* obj(I) - pointer to data description structure */
6929 /* This function acts as a handler for the SIOCGENITER ioctls that use a */
6930 /* generic structure to iterate through a list. There are three different */
6931 /* linked lists of NAT related information to go through: NAT rules, active */
6932 /* NAT mappings and the NAT fragment cache. */
6933 /* ------------------------------------------------------------------------ */
6935 ipf_nat_iterator(softc, token, itp, obj)
6936 ipf_main_softc_t *softc;
6943 if (itp->igi_data == NULL) {
6948 switch (itp->igi_type)
6950 case IPFGENITER_HOSTMAP :
6951 case IPFGENITER_IPNAT :
6952 case IPFGENITER_NAT :
6953 error = ipf_nat_getnext(softc, token, itp, obj);
6956 case IPFGENITER_NATFRAG :
6957 error = ipf_frag_nat_next(softc, token, itp);
6969 /* ------------------------------------------------------------------------ */
6970 /* Function: ipf_nat_setpending */
6972 /* Parameters: softc(I) - pointer to soft context main structure */
6973 /* nat(I) - pointer to NAT structure */
6974 /* Locks: ipf_nat (read or write) */
6976 /* Put the NAT entry on to the pending queue - this queue has a very short */
6977 /* lifetime where items are put that can't be deleted straight away because */
6978 /* of locking issues but we want to delete them ASAP, anyway. In calling */
6979 /* this function, it is assumed that the owner (if there is one, as shown */
6980 /* by nat_me) is no longer interested in it. */
6981 /* ------------------------------------------------------------------------ */
6983 ipf_nat_setpending(softc, nat)
6984 ipf_main_softc_t *softc;
6987 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6990 oifq = nat->nat_tqe.tqe_ifq;
6992 ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq,
6993 &softn->ipf_nat_pending);
6995 ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe,
6996 &softn->ipf_nat_pending, nat);
6998 if (nat->nat_me != NULL) {
6999 *nat->nat_me = NULL;
7002 ASSERT(nat->nat_ref >= 0);
7007 /* ------------------------------------------------------------------------ */
7008 /* Function: nat_newrewrite */
7009 /* Returns: int - -1 == error, 0 == success (no move), 1 == success and */
7010 /* allow rule to be moved if IPN_ROUNDR is set. */
7011 /* Parameters: fin(I) - pointer to packet information */
7012 /* nat(I) - pointer to NAT entry */
7013 /* ni(I) - pointer to structure with misc. information needed */
7014 /* to create new NAT entry. */
7015 /* Write Lock: ipf_nat */
7017 /* This function is responsible for setting up an active NAT session where */
7018 /* we are changing both the source and destination parameters at the same */
7019 /* time. The loop in here works differently to elsewhere - each iteration */
7020 /* is responsible for changing a single parameter that can be incremented. */
7021 /* So one pass may increase the source IP#, next source port, next dest. IP#*/
7022 /* and the last destination port for a total of 4 iterations to try each. */
7023 /* This is done to try and exhaustively use the translation space available.*/
7024 /* ------------------------------------------------------------------------ */
7026 ipf_nat_newrewrite(fin, nat, nai)
7044 flags = nat->nat_flags;
7045 bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
7051 /* TRACE (l, src_search, dst_search, np) */
7053 if ((src_search == 0) && (np->in_spnext == 0) &&
7054 (dst_search == 0) && (np->in_dpnext == 0)) {
7060 * Find a new source address
7062 if (ipf_nat_nextaddr(fin, &np->in_nsrc, &frnat.fin_saddr,
7063 &frnat.fin_saddr) == -1) {
7067 if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0xffffffff)) {
7069 if (np->in_stepnext == 0)
7070 np->in_stepnext = 1;
7072 } else if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0)) {
7074 if (np->in_stepnext == 0)
7075 np->in_stepnext = 1;
7077 } else if (np->in_nsrcmsk == 0xffffffff) {
7079 if (np->in_stepnext == 0)
7080 np->in_stepnext = 1;
7082 } else if (np->in_nsrcmsk != 0xffffffff) {
7083 if (np->in_stepnext == 0 && changed == -1) {
7090 if ((flags & IPN_TCPUDPICMP) != 0) {
7091 if (np->in_spnext != 0)
7092 frnat.fin_data[0] = np->in_spnext;
7095 * Standard port translation. Select next port.
7097 if ((flags & IPN_FIXEDSPORT) != 0) {
7098 np->in_stepnext = 2;
7099 } else if ((np->in_stepnext == 1) &&
7100 (changed == -1) && (natl != NULL)) {
7104 if (np->in_spnext > np->in_spmax)
7105 np->in_spnext = np->in_spmin;
7108 np->in_stepnext = 2;
7110 np->in_stepnext &= 0x3;
7113 * Find a new destination address
7115 /* TRACE (fin, np, l, frnat) */
7117 if (ipf_nat_nextaddr(fin, &np->in_ndst, &frnat.fin_daddr,
7118 &frnat.fin_daddr) == -1)
7120 if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0xffffffff)) {
7122 if (np->in_stepnext == 2)
7123 np->in_stepnext = 3;
7125 } else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0)) {
7127 if (np->in_stepnext == 2)
7128 np->in_stepnext = 3;
7130 } else if (np->in_ndstmsk == 0xffffffff) {
7132 if (np->in_stepnext == 2)
7133 np->in_stepnext = 3;
7135 } else if (np->in_ndstmsk != 0xffffffff) {
7136 if ((np->in_stepnext == 2) && (changed == -1) &&
7144 if ((flags & IPN_TCPUDPICMP) != 0) {
7145 if (np->in_dpnext != 0)
7146 frnat.fin_data[1] = np->in_dpnext;
7149 * Standard port translation. Select next port.
7151 if ((flags & IPN_FIXEDDPORT) != 0) {
7152 np->in_stepnext = 0;
7153 } else if (np->in_stepnext == 3 && changed == -1) {
7157 if (np->in_dpnext > np->in_dpmax)
7158 np->in_dpnext = np->in_dpmin;
7161 if (np->in_stepnext == 3)
7162 np->in_stepnext = 0;
7168 * Here we do a lookup of the connection as seen from
7169 * the outside. If an IP# pair already exists, try
7170 * again. So if you have A->B becomes C->B, you can
7171 * also have D->E become C->E but not D->B causing
7172 * another C->B. Also take protocol and ports into
7173 * account when determining whether a pre-existing
7174 * NAT setup will cause an external conflict where
7175 * this is appropriate.
7177 * fin_data[] is swapped around because we are doing a
7178 * lookup of the packet is if it were moving in the opposite
7179 * direction of the one we are working with now.
7181 if (flags & IPN_TCPUDP) {
7182 swap = frnat.fin_data[0];
7183 frnat.fin_data[0] = frnat.fin_data[1];
7184 frnat.fin_data[1] = swap;
7186 if (fin->fin_out == 1) {
7187 natl = ipf_nat_inlookup(&frnat,
7188 flags & ~(SI_WILDP|NAT_SEARCH),
7190 frnat.fin_dst, frnat.fin_src);
7193 natl = ipf_nat_outlookup(&frnat,
7194 flags & ~(SI_WILDP|NAT_SEARCH),
7196 frnat.fin_dst, frnat.fin_src);
7198 if (flags & IPN_TCPUDP) {
7199 swap = frnat.fin_data[0];
7200 frnat.fin_data[0] = frnat.fin_data[1];
7201 frnat.fin_data[1] = swap;
7204 /* TRACE natl, in_stepnext, l */
7206 if ((natl != NULL) && (l > 8)) /* XXX 8 is arbitrary */
7209 np->in_stepnext &= 0x3;
7213 } while (natl != NULL);
7215 nat->nat_osrcip = fin->fin_src;
7216 nat->nat_odstip = fin->fin_dst;
7217 nat->nat_nsrcip = frnat.fin_src;
7218 nat->nat_ndstip = frnat.fin_dst;
7220 if ((flags & IPN_TCPUDP) != 0) {
7221 nat->nat_osport = htons(fin->fin_data[0]);
7222 nat->nat_odport = htons(fin->fin_data[1]);
7223 nat->nat_nsport = htons(frnat.fin_data[0]);
7224 nat->nat_ndport = htons(frnat.fin_data[1]);
7225 } else if ((flags & IPN_ICMPQUERY) != 0) {
7226 nat->nat_oicmpid = fin->fin_data[1];
7227 nat->nat_nicmpid = frnat.fin_data[1];
7234 /* ------------------------------------------------------------------------ */
7235 /* Function: nat_newdivert */
7236 /* Returns: int - -1 == error, 0 == success */
7237 /* Parameters: fin(I) - pointer to packet information */
7238 /* nat(I) - pointer to NAT entry */
7239 /* ni(I) - pointer to structure with misc. information needed */
7240 /* to create new NAT entry. */
7241 /* Write Lock: ipf_nat */
7243 /* Create a new NAT divert session as defined by the NAT rule. This is */
7244 /* somewhat different to other NAT session creation routines because we */
7245 /* do not iterate through either port numbers or IP addresses, searching */
7246 /* for a unique mapping, however, a complimentary duplicate check is made. */
7247 /* ------------------------------------------------------------------------ */
7249 ipf_nat_newdivert(fin, nat, nai)
7254 ipf_main_softc_t *softc = fin->fin_main_soft;
7255 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7262 bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
7265 nat->nat_osrcaddr = fin->fin_saddr;
7266 nat->nat_odstaddr = fin->fin_daddr;
7267 frnat.fin_saddr = htonl(np->in_snip);
7268 frnat.fin_daddr = htonl(np->in_dnip);
7269 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
7270 nat->nat_osport = htons(fin->fin_data[0]);
7271 nat->nat_odport = htons(fin->fin_data[1]);
7272 } else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
7273 nat->nat_oicmpid = fin->fin_data[1];
7276 if (np->in_redir & NAT_DIVERTUDP) {
7277 frnat.fin_data[0] = np->in_spnext;
7278 frnat.fin_data[1] = np->in_dpnext;
7279 frnat.fin_flx |= FI_TCPUDP;
7282 frnat.fin_flx &= ~FI_TCPUDP;
7286 if (fin->fin_out == 1) {
7287 natl = ipf_nat_inlookup(&frnat, 0, p,
7288 frnat.fin_dst, frnat.fin_src);
7291 natl = ipf_nat_outlookup(&frnat, 0, p,
7292 frnat.fin_dst, frnat.fin_src);
7296 NBUMPSIDED(fin->fin_out, ns_divert_exist);
7300 nat->nat_nsrcaddr = frnat.fin_saddr;
7301 nat->nat_ndstaddr = frnat.fin_daddr;
7302 if ((nat->nat_flags & IPN_TCPUDP) != 0) {
7303 nat->nat_nsport = htons(frnat.fin_data[0]);
7304 nat->nat_ndport = htons(frnat.fin_data[1]);
7305 } else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
7306 nat->nat_nicmpid = frnat.fin_data[1];
7309 nat->nat_pr[fin->fin_out] = fin->fin_p;
7310 nat->nat_pr[1 - fin->fin_out] = p;
7312 if (np->in_redir & NAT_REDIRECT)
7313 nat->nat_dir = NAT_DIVERTIN;
7315 nat->nat_dir = NAT_DIVERTOUT;
7321 /* ------------------------------------------------------------------------ */
7322 /* Function: nat_builddivertmp */
7323 /* Returns: int - -1 == error, 0 == success */
7324 /* Parameters: softn(I) - pointer to NAT context structure */
7325 /* np(I) - pointer to a NAT rule */
7327 /* For divert rules, a skeleton packet representing what will be prepended */
7328 /* to the real packet is created. Even though we don't have the full */
7329 /* packet here, a checksum is calculated that we update later when we */
7330 /* fill in the final details. At present a 0 checksum for UDP is being set */
7331 /* here because it is expected that divert will be used for localhost. */
7332 /* ------------------------------------------------------------------------ */
7334 ipf_nat_builddivertmp(softn, np)
7335 ipf_nat_softc_t *softn;
7342 if ((np->in_redir & NAT_DIVERTUDP) != 0)
7343 len = sizeof(ip_t) + sizeof(udphdr_t);
7347 ALLOC_MB_T(np->in_divmp, len);
7348 if (np->in_divmp == NULL) {
7349 NBUMPD(ipf_nat_stats, ns_divert_build);
7354 * First, the header to get the packet diverted to the new destination
7356 ip = MTOD(np->in_divmp, ip_t *);
7360 if ((np->in_redir & NAT_DIVERTUDP) != 0)
7361 ip->ip_p = IPPROTO_UDP;
7363 ip->ip_p = IPPROTO_IPIP;
7367 ip->ip_len = htons(len);
7369 ip->ip_src.s_addr = htonl(np->in_snip);
7370 ip->ip_dst.s_addr = htonl(np->in_dnip);
7371 ip->ip_sum = ipf_cksum((u_short *)ip, sizeof(*ip));
7373 if (np->in_redir & NAT_DIVERTUDP) {
7374 uh = (udphdr_t *)(ip + 1);
7377 uh->uh_sport = htons(np->in_spnext);
7378 uh->uh_dport = htons(np->in_dpnext);
7385 #define MINDECAP (sizeof(ip_t) + sizeof(udphdr_t) + sizeof(ip_t))
7387 /* ------------------------------------------------------------------------ */
7388 /* Function: nat_decap */
7389 /* Returns: int - -1 == error, 0 == success */
7390 /* Parameters: fin(I) - pointer to packet information */
7391 /* nat(I) - pointer to current NAT session */
7393 /* This function is responsible for undoing a packet's encapsulation in the */
7394 /* reverse of an encap/divert rule. After removing the outer encapsulation */
7395 /* it is necessary to call ipf_makefrip() again so that the contents of 'fin'*/
7396 /* match the "new" packet as it may still be used by IPFilter elsewhere. */
7397 /* We use "dir" here as the basis for some of the expectations about the */
7398 /* outer header. If we return an error, the goal is to leave the original */
7399 /* packet information undisturbed - this falls short at the end where we'd */
7400 /* need to back a backup copy of "fin" - expensive. */
7401 /* ------------------------------------------------------------------------ */
7403 ipf_nat_decap(fin, nat)
7407 ipf_main_softc_t *softc = fin->fin_main_soft;
7408 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7414 if ((fin->fin_flx & FI_ICMPERR) != 0) {
7416 * ICMP packets don't get decapsulated, instead what we need
7417 * to do is change the ICMP reply from including (in the data
7418 * portion for errors) the encapsulated packet that we sent
7419 * out to something that resembles the original packet prior
7420 * to encapsulation. This isn't done here - all we're doing
7421 * here is changing the outer address to ensure that it gets
7422 * targetted back to the correct system.
7425 if (nat->nat_dir & NAT_OUTBOUND) {
7426 u_32_t sum1, sum2, sumd;
7428 sum1 = ntohl(fin->fin_daddr);
7429 sum2 = ntohl(nat->nat_osrcaddr);
7430 CALC_SUMD(sum1, sum2, sumd);
7431 fin->fin_ip->ip_dst = nat->nat_osrcip;
7432 fin->fin_daddr = nat->nat_osrcaddr;
7433 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
7434 defined(__osf__) || defined(linux)
7435 ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, sumd, 0);
7442 skip = fin->fin_hlen;
7444 switch (nat->nat_dir)
7447 case NAT_DIVERTOUT :
7448 if (fin->fin_plen < MINDECAP)
7450 skip += sizeof(udphdr_t);
7455 if (fin->fin_plen < (skip + sizeof(ip_t)))
7464 * The aim here is to keep the original packet details in "fin" for
7465 * as long as possible so that returning with an error is for the
7466 * original packet and there is little undoing work to do.
7468 if (M_LEN(m) < skip + sizeof(ip_t)) {
7469 if (ipf_pr_pullup(fin, skip + sizeof(ip_t)) == -1)
7473 hdr = MTOD(fin->fin_m, char *);
7474 fin->fin_ip = (ip_t *)(hdr + skip);
7475 hlen = IP_HL(fin->fin_ip) << 2;
7477 if (ipf_pr_pullup(fin, skip + hlen) == -1) {
7478 NBUMPSIDED(fin->fin_out, ns_decap_pullup);
7482 fin->fin_hlen = hlen;
7483 fin->fin_dlen -= skip;
7484 fin->fin_plen -= skip;
7485 fin->fin_ipoff += skip;
7487 if (ipf_makefrip(hlen, (ip_t *)hdr, fin) == -1) {
7488 NBUMPSIDED(fin->fin_out, ns_decap_bad);
7496 /* ------------------------------------------------------------------------ */
7497 /* Function: nat_nextaddr */
7498 /* Returns: int - -1 == bad input (no new address), */
7499 /* 0 == success and dst has new address */
7500 /* Parameters: fin(I) - pointer to packet information */
7501 /* na(I) - how to generate new address */
7502 /* old(I) - original address being replaced */
7503 /* dst(O) - where to put the new address */
7504 /* Write Lock: ipf_nat */
7506 /* This function uses the contents of the "na" structure, in combination */
7507 /* with "old" to produce a new address to store in "dst". Not all of the */
7508 /* possible uses of "na" will result in a new address. */
7509 /* ------------------------------------------------------------------------ */
7511 ipf_nat_nextaddr(fin, na, old, dst)
7516 ipf_main_softc_t *softc = fin->fin_main_soft;
7517 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7518 u_32_t amin, amax, new;
7523 amin = na->na_addr[0].in4.s_addr;
7525 switch (na->na_atype)
7528 amax = na->na_addr[1].in4.s_addr;
7531 case FRI_NETMASKED :
7535 * Compute the maximum address by adding the inverse of the
7536 * netmask to the minimum address.
7538 amax = ~na->na_addr[1].in4.s_addr;
7545 case FRI_BROADCAST :
7554 if (na->na_atype == FRI_LOOKUP) {
7555 if (na->na_type == IPLT_DSTLIST) {
7556 error = ipf_dstlist_select_node(fin, na->na_ptr, dst,
7559 NBUMPSIDE(fin->fin_out, ns_badnextaddr);
7562 } else if (na->na_atype == IPLT_NONE) {
7564 * 0/0 as the new address means leave it alone.
7566 if (na->na_addr[0].in4.s_addr == 0 &&
7567 na->na_addr[1].in4.s_addr == 0) {
7571 * 0/32 means get the interface's address
7573 } else if (na->na_addr[0].in4.s_addr == 0 &&
7574 na->na_addr[1].in4.s_addr == 0xffffffff) {
7575 if (ipf_ifpaddr(softc, 4, na->na_atype,
7576 fin->fin_ifp, &newip, NULL) == -1) {
7577 NBUMPSIDED(fin->fin_out, ns_ifpaddrfail);
7580 new = newip.in4.s_addr;
7582 new = htonl(na->na_nextip);
7588 NBUMPSIDE(fin->fin_out, ns_badnextaddr);
7595 /* ------------------------------------------------------------------------ */
7596 /* Function: nat_nextaddrinit */
7597 /* Returns: int - 0 == success, else error number */
7598 /* Parameters: softc(I) - pointer to soft context main structure */
7599 /* na(I) - NAT address information for generating new addr*/
7600 /* initial(I) - flag indicating if it is the first call for */
7601 /* this "na" structure. */
7602 /* ifp(I) - network interface to derive address */
7603 /* information from. */
7605 /* This function is expected to be called in two scenarious: when a new NAT */
7606 /* rule is loaded into the kernel and when the list of NAT rules is sync'd */
7607 /* up with the valid network interfaces (possibly due to them changing.) */
7608 /* To distinguish between these, the "initial" parameter is used. If it is */
7609 /* 1 then this indicates the rule has just been reloaded and 0 for when we */
7610 /* are updating information. This difference is important because in */
7611 /* instances where we are not updating address information associated with */
7612 /* a network interface, we don't want to disturb what the "next" address to */
7613 /* come out of ipf_nat_nextaddr() will be. */
7614 /* ------------------------------------------------------------------------ */
7616 ipf_nat_nextaddrinit(softc, base, na, initial, ifp)
7617 ipf_main_softc_t *softc;
7624 switch (na->na_atype)
7627 if (na->na_subtype == 0) {
7628 na->na_ptr = ipf_lookup_res_num(softc, IPL_LOGNAT,
7632 } else if (na->na_subtype == 1) {
7633 na->na_ptr = ipf_lookup_res_name(softc, IPL_LOGNAT,
7638 if (na->na_func == NULL) {
7642 if (na->na_ptr == NULL) {
7649 case FRI_BROADCAST :
7651 case FRI_NETMASKED :
7654 (void )ipf_ifpaddr(softc, 4, na->na_atype, ifp,
7655 &na->na_addr[0], &na->na_addr[1]);
7661 na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
7665 na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
7669 na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
7677 if (initial && (na->na_atype == FRI_NORMAL)) {
7678 if (na->na_addr[0].in4.s_addr == 0) {
7679 if ((na->na_addr[1].in4.s_addr == 0xffffffff) ||
7680 (na->na_addr[1].in4.s_addr == 0)) {
7685 if (na->na_addr[1].in4.s_addr == 0xffffffff) {
7686 na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
7688 na->na_nextip = ntohl(na->na_addr[0].in4.s_addr) + 1;
7696 /* ------------------------------------------------------------------------ */
7697 /* Function: ipf_nat_matchflush */
7698 /* Returns: int - -1 == error, 0 == success */
7699 /* Parameters: softc(I) - pointer to soft context main structure */
7700 /* softn(I) - pointer to NAT context structure */
7701 /* nat(I) - pointer to current NAT session */
7703 /* ------------------------------------------------------------------------ */
7705 ipf_nat_matchflush(softc, softn, data)
7706 ipf_main_softc_t *softc;
7707 ipf_nat_softc_t *softn;
7710 int *array, flushed, error;
7711 nat_t *nat, *natnext;
7714 error = ipf_matcharray_load(softc, data, &obj, &array);
7720 for (nat = softn->ipf_nat_instances; nat != NULL; nat = natnext) {
7721 natnext = nat->nat_next;
7722 if (ipf_nat_matcharray(nat, array, softc->ipf_ticks) == 0) {
7723 ipf_nat_delete(softc, nat, NL_FLUSH);
7728 obj.ipfo_retval = flushed;
7729 error = BCOPYOUT(&obj, data, sizeof(obj));
7731 KFREES(array, array[0] * sizeof(*array));
7737 /* ------------------------------------------------------------------------ */
7738 /* Function: ipf_nat_matcharray */
7739 /* Returns: int - -1 == error, 0 == success */
7740 /* Parameters: fin(I) - pointer to packet information */
7741 /* nat(I) - pointer to current NAT session */
7743 /* ------------------------------------------------------------------------ */
7745 ipf_nat_matcharray(nat, array, ticks)
7756 for (; n > 0; x += 3 + x[2]) {
7757 if (x[0] == IPF_EXP_END)
7766 if (p != 0 && p != nat->nat_pr[1])
7771 case IPF_EXP_IP_PR :
7772 for (i = 0; !e && i < x[2]; i++) {
7773 e |= (nat->nat_pr[1] == x[i + 3]);
7777 case IPF_EXP_IP_SRCADDR :
7778 if (nat->nat_v[0] == 4) {
7779 for (i = 0; !e && i < x[2]; i++) {
7780 e |= ((nat->nat_osrcaddr & x[i + 4]) ==
7784 if (nat->nat_v[1] == 4) {
7785 for (i = 0; !e && i < x[2]; i++) {
7786 e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
7792 case IPF_EXP_IP_DSTADDR :
7793 if (nat->nat_v[0] == 4) {
7794 for (i = 0; !e && i < x[2]; i++) {
7795 e |= ((nat->nat_odstaddr & x[i + 4]) ==
7799 if (nat->nat_v[1] == 4) {
7800 for (i = 0; !e && i < x[2]; i++) {
7801 e |= ((nat->nat_ndstaddr & x[i + 4]) ==
7807 case IPF_EXP_IP_ADDR :
7808 for (i = 0; !e && i < x[2]; i++) {
7809 if (nat->nat_v[0] == 4) {
7810 e |= ((nat->nat_osrcaddr & x[i + 4]) ==
7813 if (nat->nat_v[1] == 4) {
7814 e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
7817 if (nat->nat_v[0] == 4) {
7818 e |= ((nat->nat_odstaddr & x[i + 4]) ==
7821 if (nat->nat_v[1] == 4) {
7822 e |= ((nat->nat_ndstaddr & x[i + 4]) ==
7829 case IPF_EXP_IP6_SRCADDR :
7830 if (nat->nat_v[0] == 6) {
7831 for (i = 0; !e && i < x[3]; i++) {
7832 e |= IP6_MASKEQ(&nat->nat_osrc6,
7833 x + i + 7, x + i + 3);
7836 if (nat->nat_v[1] == 6) {
7837 for (i = 0; !e && i < x[3]; i++) {
7838 e |= IP6_MASKEQ(&nat->nat_nsrc6,
7839 x + i + 7, x + i + 3);
7844 case IPF_EXP_IP6_DSTADDR :
7845 if (nat->nat_v[0] == 6) {
7846 for (i = 0; !e && i < x[3]; i++) {
7847 e |= IP6_MASKEQ(&nat->nat_odst6,
7852 if (nat->nat_v[1] == 6) {
7853 for (i = 0; !e && i < x[3]; i++) {
7854 e |= IP6_MASKEQ(&nat->nat_ndst6,
7861 case IPF_EXP_IP6_ADDR :
7862 for (i = 0; !e && i < x[3]; i++) {
7863 if (nat->nat_v[0] == 6) {
7864 e |= IP6_MASKEQ(&nat->nat_osrc6,
7868 if (nat->nat_v[0] == 6) {
7869 e |= IP6_MASKEQ(&nat->nat_odst6,
7873 if (nat->nat_v[1] == 6) {
7874 e |= IP6_MASKEQ(&nat->nat_nsrc6,
7878 if (nat->nat_v[1] == 6) {
7879 e |= IP6_MASKEQ(&nat->nat_ndst6,
7887 case IPF_EXP_UDP_PORT :
7888 case IPF_EXP_TCP_PORT :
7889 for (i = 0; !e && i < x[2]; i++) {
7890 e |= (nat->nat_nsport == x[i + 3]) ||
7891 (nat->nat_ndport == x[i + 3]);
7895 case IPF_EXP_UDP_SPORT :
7896 case IPF_EXP_TCP_SPORT :
7897 for (i = 0; !e && i < x[2]; i++) {
7898 e |= (nat->nat_nsport == x[i + 3]);
7902 case IPF_EXP_UDP_DPORT :
7903 case IPF_EXP_TCP_DPORT :
7904 for (i = 0; !e && i < x[2]; i++) {
7905 e |= (nat->nat_ndport == x[i + 3]);
7909 case IPF_EXP_TCP_STATE :
7910 for (i = 0; !e && i < x[2]; i++) {
7911 e |= (nat->nat_tcpstate[0] == x[i + 3]) ||
7912 (nat->nat_tcpstate[1] == x[i + 3]);
7916 case IPF_EXP_IDLE_GT :
7917 e |= (ticks - nat->nat_touched > x[3]);
7930 /* ------------------------------------------------------------------------ */
7931 /* Function: ipf_nat_gettable */
7932 /* Returns: int - 0 = success, else error */
7933 /* Parameters: softc(I) - pointer to soft context main structure */
7934 /* softn(I) - pointer to NAT context structure */
7935 /* data(I) - pointer to ioctl data */
7937 /* This function handles ioctl requests for tables of nat information. */
7938 /* At present the only table it deals with is the hash bucket statistics. */
7939 /* ------------------------------------------------------------------------ */
7941 ipf_nat_gettable(softc, softn, data)
7942 ipf_main_softc_t *softc;
7943 ipf_nat_softc_t *softn;
7949 error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
7953 switch (table.ita_type)
7955 case IPFTABLE_BUCKETS_NATIN :
7956 error = COPYOUT(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
7958 softn->ipf_nat_table_sz * sizeof(u_int));
7961 case IPFTABLE_BUCKETS_NATOUT :
7962 error = COPYOUT(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
7964 softn->ipf_nat_table_sz * sizeof(u_int));
7980 /* ------------------------------------------------------------------------ */
7981 /* Function: ipf_nat_settimeout */
7982 /* Returns: int - 0 = success, else failure */
7983 /* Parameters: softc(I) - pointer to soft context main structure */
7984 /* t(I) - pointer to tunable */
7985 /* p(I) - pointer to new tuning data */
7987 /* Apply the timeout change to the NAT timeout queues. */
7988 /* ------------------------------------------------------------------------ */
7990 ipf_nat_settimeout(softc, t, p)
7991 struct ipf_main_softc_s *softc;
7995 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7997 if (!strncmp(t->ipft_name, "tcp_", 4))
7998 return ipf_settimeout_tcp(t, p, softn->ipf_nat_tcptq);
8000 if (!strcmp(t->ipft_name, "udp_timeout")) {
8001 ipf_apply_timeout(&softn->ipf_nat_udptq, p->ipftu_int);
8002 } else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
8003 ipf_apply_timeout(&softn->ipf_nat_udpacktq, p->ipftu_int);
8004 } else if (!strcmp(t->ipft_name, "icmp_timeout")) {
8005 ipf_apply_timeout(&softn->ipf_nat_icmptq, p->ipftu_int);
8006 } else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
8007 ipf_apply_timeout(&softn->ipf_nat_icmpacktq, p->ipftu_int);
8008 } else if (!strcmp(t->ipft_name, "ip_timeout")) {
8009 ipf_apply_timeout(&softn->ipf_nat_iptq, p->ipftu_int);
8018 /* ------------------------------------------------------------------------ */
8019 /* Function: ipf_nat_rehash */
8020 /* Returns: int - 0 = success, else failure */
8021 /* Parameters: softc(I) - pointer to soft context main structure */
8022 /* t(I) - pointer to tunable */
8023 /* p(I) - pointer to new tuning data */
8025 /* To change the size of the basic NAT table, we need to first allocate the */
8026 /* new tables (lest it fails and we've got nowhere to store all of the NAT */
8027 /* sessions currently active) and then walk through the entire list and */
8028 /* insert them into the table. There are two tables here: an inbound one */
8029 /* and an outbound one. Each NAT entry goes into each table once. */
8030 /* ------------------------------------------------------------------------ */
8032 ipf_nat_rehash(softc, t, p)
8033 ipf_main_softc_t *softc;
8037 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
8038 nat_t **newtab[2], *nat, **natp;
8039 u_int *bucketlens[2];
8046 newsize = p->ipftu_int;
8048 * In case there is nothing to do...
8050 if (newsize == softn->ipf_nat_table_sz)
8055 bucketlens[0] = NULL;
8056 bucketlens[1] = NULL;
8058 * 4 tables depend on the NAT table size: the inbound looking table,
8059 * the outbound lookup table and the hash chain length for each.
8061 KMALLOCS(newtab[0], nat_t **, newsize * sizeof(nat_t *));
8062 if (newtab[0] == NULL) {
8067 KMALLOCS(newtab[1], nat_t **, newsize * sizeof(nat_t *));
8068 if (newtab[1] == NULL) {
8073 KMALLOCS(bucketlens[0], u_int *, newsize * sizeof(u_int));
8074 if (bucketlens[0] == NULL) {
8079 KMALLOCS(bucketlens[1], u_int *, newsize * sizeof(u_int));
8080 if (bucketlens[1] == NULL) {
8086 * Recalculate the maximum length based on the new size.
8088 for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
8092 bzero((char *)newtab[0], newsize * sizeof(nat_t *));
8093 bzero((char *)newtab[1], newsize * sizeof(nat_t *));
8094 bzero((char *)bucketlens[0], newsize * sizeof(u_int));
8095 bzero((char *)bucketlens[1], newsize * sizeof(u_int));
8097 WRITE_ENTER(&softc->ipf_nat);
8099 if (softn->ipf_nat_table[0] != NULL) {
8100 KFREES(softn->ipf_nat_table[0],
8101 softn->ipf_nat_table_sz *
8102 sizeof(*softn->ipf_nat_table[0]));
8104 softn->ipf_nat_table[0] = newtab[0];
8106 if (softn->ipf_nat_table[1] != NULL) {
8107 KFREES(softn->ipf_nat_table[1],
8108 softn->ipf_nat_table_sz *
8109 sizeof(*softn->ipf_nat_table[1]));
8111 softn->ipf_nat_table[1] = newtab[1];
8113 if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen != NULL) {
8114 KFREES(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
8115 softn->ipf_nat_table_sz * sizeof(u_int));
8117 softn->ipf_nat_stats.ns_side[0].ns_bucketlen = bucketlens[0];
8119 if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen != NULL) {
8120 KFREES(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
8121 softn->ipf_nat_table_sz * sizeof(u_int));
8123 softn->ipf_nat_stats.ns_side[1].ns_bucketlen = bucketlens[1];
8126 if (softn->ipf_nat_stats.ns_side6[0].ns_bucketlen != NULL) {
8127 KFREES(softn->ipf_nat_stats.ns_side6[0].ns_bucketlen,
8128 softn->ipf_nat_table_sz * sizeof(u_int));
8130 softn->ipf_nat_stats.ns_side6[0].ns_bucketlen = bucketlens[0];
8132 if (softn->ipf_nat_stats.ns_side6[1].ns_bucketlen != NULL) {
8133 KFREES(softn->ipf_nat_stats.ns_side6[1].ns_bucketlen,
8134 softn->ipf_nat_table_sz * sizeof(u_int));
8136 softn->ipf_nat_stats.ns_side6[1].ns_bucketlen = bucketlens[1];
8139 softn->ipf_nat_maxbucket = maxbucket;
8140 softn->ipf_nat_table_sz = newsize;
8142 * Walk through the entire list of NAT table entries and put them
8143 * in the new NAT table, somewhere. Because we have a new table,
8144 * we need to restart the counter of how many chains are in use.
8146 softn->ipf_nat_stats.ns_side[0].ns_inuse = 0;
8147 softn->ipf_nat_stats.ns_side[1].ns_inuse = 0;
8149 softn->ipf_nat_stats.ns_side6[0].ns_inuse = 0;
8150 softn->ipf_nat_stats.ns_side6[1].ns_inuse = 0;
8153 for (nat = softn->ipf_nat_instances; nat != NULL; nat = nat->nat_next) {
8154 nat->nat_hnext[0] = NULL;
8155 nat->nat_phnext[0] = NULL;
8156 hv = nat->nat_hv[0] % softn->ipf_nat_table_sz;
8158 natp = &softn->ipf_nat_table[0][hv];
8160 (*natp)->nat_phnext[0] = &nat->nat_hnext[0];
8162 NBUMPSIDE(0, ns_inuse);
8164 nat->nat_phnext[0] = natp;
8165 nat->nat_hnext[0] = *natp;
8167 NBUMPSIDE(0, ns_bucketlen[hv]);
8169 nat->nat_hnext[1] = NULL;
8170 nat->nat_phnext[1] = NULL;
8171 hv = nat->nat_hv[1] % softn->ipf_nat_table_sz;
8173 natp = &softn->ipf_nat_table[1][hv];
8175 (*natp)->nat_phnext[1] = &nat->nat_hnext[1];
8177 NBUMPSIDE(1, ns_inuse);
8179 nat->nat_phnext[1] = natp;
8180 nat->nat_hnext[1] = *natp;
8182 NBUMPSIDE(1, ns_bucketlen[hv]);
8184 RWLOCK_EXIT(&softc->ipf_nat);
8189 if (bucketlens[1] != NULL) {
8190 KFREES(bucketlens[0], newsize * sizeof(u_int));
8192 if (bucketlens[0] != NULL) {
8193 KFREES(bucketlens[0], newsize * sizeof(u_int));
8195 if (newtab[0] != NULL) {
8196 KFREES(newtab[0], newsize * sizeof(nat_t *));
8198 if (newtab[1] != NULL) {
8199 KFREES(newtab[1], newsize * sizeof(nat_t *));
8206 /* ------------------------------------------------------------------------ */
8207 /* Function: ipf_nat_rehash_rules */
8208 /* Returns: int - 0 = success, else failure */
8209 /* Parameters: softc(I) - pointer to soft context main structure */
8210 /* t(I) - pointer to tunable */
8211 /* p(I) - pointer to new tuning data */
8213 /* All of the NAT rules hang off of a hash table that is searched with a */
8214 /* hash on address after the netmask is applied. There is a different table*/
8215 /* for both inbound rules (rdr) and outbound (map.) The resizing will only */
8216 /* affect one of these two tables. */
8217 /* ------------------------------------------------------------------------ */
8219 ipf_nat_rehash_rules(softc, t, p)
8220 ipf_main_softc_t *softc;
8224 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
8225 ipnat_t **newtab, *np, ***old, **npp;
8230 newsize = p->ipftu_int;
8232 * In case there is nothing to do...
8234 if (newsize == *t->ipft_pint)
8238 * All inbound rules have the NAT_REDIRECT bit set in in_redir and
8239 * all outbound rules have either NAT_MAP or MAT_MAPBLK set.
8240 * This if statement allows for some more generic code to be below,
8241 * rather than two huge gobs of code that almost do the same thing.
8243 if (t->ipft_pint == &softn->ipf_nat_rdrrules_sz) {
8244 old = &softn->ipf_nat_rdr_rules;
8245 mask = NAT_REDIRECT;
8247 old = &softn->ipf_nat_map_rules;
8248 mask = NAT_MAP|NAT_MAPBLK;
8251 KMALLOCS(newtab, ipnat_t **, newsize * sizeof(ipnat_t *));
8252 if (newtab == NULL) {
8257 bzero((char *)newtab, newsize * sizeof(ipnat_t *));
8259 WRITE_ENTER(&softc->ipf_nat);
8262 KFREES(*old, *t->ipft_pint * sizeof(ipnat_t **));
8265 *t->ipft_pint = newsize;
8267 for (np = softn->ipf_nat_list; np != NULL; np = np->in_next) {
8268 if ((np->in_redir & mask) == 0)
8271 if (np->in_redir & NAT_REDIRECT) {
8272 np->in_rnext = NULL;
8273 hv = np->in_hv[0] % newsize;
8274 for (npp = newtab + hv; *npp != NULL; )
8275 npp = &(*npp)->in_rnext;
8276 np->in_prnext = npp;
8279 if (np->in_redir & NAT_MAP) {
8280 np->in_mnext = NULL;
8281 hv = np->in_hv[1] % newsize;
8282 for (npp = newtab + hv; *npp != NULL; )
8283 npp = &(*npp)->in_mnext;
8284 np->in_pmnext = npp;
8289 RWLOCK_EXIT(&softc->ipf_nat);
8295 /* ------------------------------------------------------------------------ */
8296 /* Function: ipf_nat_hostmap_rehash */
8297 /* Returns: int - 0 = success, else failure */
8298 /* Parameters: softc(I) - pointer to soft context main structure */
8299 /* t(I) - pointer to tunable */
8300 /* p(I) - pointer to new tuning data */
8302 /* Allocate and populate a new hash table that will contain a reference to */
8303 /* all of the active IP# translations currently in place. */
8304 /* ------------------------------------------------------------------------ */
8306 ipf_nat_hostmap_rehash(softc, t, p)
8307 ipf_main_softc_t *softc;
8311 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
8312 hostmap_t *hm, **newtab;
8316 newsize = p->ipftu_int;
8318 * In case there is nothing to do...
8320 if (newsize == *t->ipft_pint)
8323 KMALLOCS(newtab, hostmap_t **, newsize * sizeof(hostmap_t *));
8324 if (newtab == NULL) {
8329 bzero((char *)newtab, newsize * sizeof(hostmap_t *));
8331 WRITE_ENTER(&softc->ipf_nat);
8332 if (softn->ipf_hm_maptable != NULL) {
8333 KFREES(softn->ipf_hm_maptable,
8334 softn->ipf_nat_hostmap_sz * sizeof(hostmap_t *));
8336 softn->ipf_hm_maptable = newtab;
8337 softn->ipf_nat_hostmap_sz = newsize;
8339 for (hm = softn->ipf_hm_maplist; hm != NULL; hm = hm->hm_next) {
8340 hv = hm->hm_hv % softn->ipf_nat_hostmap_sz;
8341 hm->hm_hnext = softn->ipf_hm_maptable[hv];
8342 hm->hm_phnext = softn->ipf_hm_maptable + hv;
8343 if (softn->ipf_hm_maptable[hv] != NULL)
8344 softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
8345 softn->ipf_hm_maptable[hv] = hm;
8347 RWLOCK_EXIT(&softc->ipf_nat);
8353 /* ------------------------------------------------------------------------ */
8354 /* Function: ipf_nat_add_tq */
8355 /* Parameters: softc(I) - pointer to soft context main structure */
8357 /* ------------------------------------------------------------------------ */
8359 ipf_nat_add_tq(softc, ttl)
8360 ipf_main_softc_t *softc;
8363 ipf_nat_softc_t *softs = softc->ipf_nat_soft;
8365 return ipf_addtimeoutqueue(softc, &softs->ipf_nat_utqe, ttl);
8368 /* ------------------------------------------------------------------------ */
8369 /* Function: ipf_nat_uncreate */
8371 /* Parameters: fin(I) - pointer to packet information */
8373 /* This function is used to remove a NAT entry from the NAT table when we */
8374 /* decide that the create was actually in error. It is thus assumed that */
8375 /* fin_flx will have both FI_NATED and FI_NATNEW set. Because we're dealing */
8376 /* with the translated packet (not the original), we have to reverse the */
8377 /* lookup. Although doing the lookup is expensive (relatively speaking), it */
8378 /* is not anticipated that this will be a frequent occurance for normal */
8379 /* traffic patterns. */
8380 /* ------------------------------------------------------------------------ */
8382 ipf_nat_uncreate(fin)
8385 ipf_main_softc_t *softc = fin->fin_main_soft;
8386 ipf_nat_softc_t *softn = softc->ipf_nat_soft;
8403 WRITE_ENTER(&softc->ipf_nat);
8405 if (fin->fin_out == 0) {
8406 nat = ipf_nat_outlookup(fin, nflags, (u_int)fin->fin_p,
8407 fin->fin_dst, fin->fin_src);
8409 nat = ipf_nat_inlookup(fin, nflags, (u_int)fin->fin_p,
8410 fin->fin_src, fin->fin_dst);
8414 NBUMPSIDE(fin->fin_out, ns_uncreate[0]);
8415 ipf_nat_delete(softc, nat, NL_DESTROY);
8417 NBUMPSIDE(fin->fin_out, ns_uncreate[1]);
8420 RWLOCK_EXIT(&softc->ipf_nat);
8424 /* ------------------------------------------------------------------------ */
8425 /* Function: ipf_nat_cmp_rules */
8426 /* Returns: int - 0 == success, else rules do not match. */
8427 /* Parameters: n1(I) - first rule to compare */
8428 /* n2(I) - first rule to compare */
8430 /* Compare two rules using pointers to each rule. A straight bcmp will not */
8431 /* work as some fields (such as in_dst, in_pkts) actually do change once */
8432 /* the rule has been loaded into the kernel. Whilst this function returns */
8433 /* various non-zero returns, they're strictly to aid in debugging. Use of */
8434 /* this function should simply care if the result is zero or not. */
8435 /* ------------------------------------------------------------------------ */
8437 ipf_nat_cmp_rules(n1, n2)
8440 if (n1->in_size != n2->in_size)
8443 if (bcmp((char *)&n1->in_v, (char *)&n2->in_v,
8444 offsetof(ipnat_t, in_ndst) - offsetof(ipnat_t, in_v)) != 0)
8447 if (bcmp((char *)&n1->in_tuc, (char *)&n2->in_tuc,
8448 n1->in_size - offsetof(ipnat_t, in_tuc)) != 0)
8450 if (n1->in_ndst.na_atype != n2->in_ndst.na_atype)
8452 if (n1->in_ndst.na_function != n2->in_ndst.na_function)
8454 if (bcmp((char *)&n1->in_ndst.na_addr, (char *)&n2->in_ndst.na_addr,
8455 sizeof(n1->in_ndst.na_addr)))
8457 if (n1->in_nsrc.na_atype != n2->in_nsrc.na_atype)
8459 if (n1->in_nsrc.na_function != n2->in_nsrc.na_function)
8461 if (bcmp((char *)&n1->in_nsrc.na_addr, (char *)&n2->in_nsrc.na_addr,
8462 sizeof(n1->in_nsrc.na_addr)))
8464 if (n1->in_odst.na_atype != n2->in_odst.na_atype)
8466 if (n1->in_odst.na_function != n2->in_odst.na_function)
8468 if (bcmp((char *)&n1->in_odst.na_addr, (char *)&n2->in_odst.na_addr,
8469 sizeof(n1->in_odst.na_addr)))
8471 if (n1->in_osrc.na_atype != n2->in_osrc.na_atype)
8473 if (n1->in_osrc.na_function != n2->in_osrc.na_function)
8475 if (bcmp((char *)&n1->in_osrc.na_addr, (char *)&n2->in_osrc.na_addr,
8476 sizeof(n1->in_osrc.na_addr)))
8482 /* ------------------------------------------------------------------------ */
8483 /* Function: ipf_nat_rule_init */
8484 /* Returns: int - 0 == success, else rules do not match. */
8485 /* Parameters: softc(I) - pointer to soft context main structure */
8486 /* softn(I) - pointer to NAT context structure */
8487 /* n(I) - first rule to compare */
8489 /* ------------------------------------------------------------------------ */
8491 ipf_nat_rule_init(softc, softn, n)
8492 ipf_main_softc_t *softc;
8493 ipf_nat_softc_t *softn;
8498 if ((n->in_flags & IPN_SIPRANGE) != 0)
8499 n->in_nsrcatype = FRI_RANGE;
8501 if ((n->in_flags & IPN_DIPRANGE) != 0)
8502 n->in_ndstatype = FRI_RANGE;
8504 if ((n->in_flags & IPN_SPLIT) != 0)
8505 n->in_ndstatype = FRI_SPLIT;
8507 if ((n->in_redir & (NAT_MAP|NAT_REWRITE|NAT_DIVERTUDP)) != 0)
8508 n->in_spnext = n->in_spmin;
8510 if ((n->in_redir & (NAT_REWRITE|NAT_DIVERTUDP)) != 0) {
8511 n->in_dpnext = n->in_dpmin;
8512 } else if (n->in_redir == NAT_REDIRECT) {
8513 n->in_dpnext = n->in_dpmin;
8521 error = ipf_nat_ruleaddrinit(softc, softn, n);
8527 error = ipf_nat6_ruleaddrinit(softc, softn, n);
8536 if (n->in_redir == (NAT_DIVERTUDP|NAT_MAP)) {
8538 * Prerecord whether or not the destination of the divert
8539 * is local or not to the interface the packet is going
8542 n->in_dlocal = ipf_deliverlocal(softc, n->in_v[1],
8543 n->in_ifps[1], &n->in_ndstip6);
8550 /* ------------------------------------------------------------------------ */
8551 /* Function: ipf_nat_rule_fini */
8552 /* Returns: int - 0 == success, else rules do not match. */
8553 /* Parameters: softc(I) - pointer to soft context main structure */
8554 /* n(I) - rule to work on */
8556 /* This function is used to release any objects that were referenced during */
8557 /* the rule initialisation. This is useful both when free'ing the rule and */
8558 /* when handling ioctls that need to initialise these fields but not */
8559 /* actually use them after the ioctl processing has finished. */
8560 /* ------------------------------------------------------------------------ */
8562 ipf_nat_rule_fini(softc, n)
8563 ipf_main_softc_t *softc;
8566 if (n->in_odst.na_atype == FRI_LOOKUP && n->in_odst.na_ptr != NULL)
8567 ipf_lookup_deref(softc, n->in_odst.na_type, n->in_odst.na_ptr);
8569 if (n->in_osrc.na_atype == FRI_LOOKUP && n->in_osrc.na_ptr != NULL)
8570 ipf_lookup_deref(softc, n->in_osrc.na_type, n->in_osrc.na_ptr);
8572 if (n->in_ndst.na_atype == FRI_LOOKUP && n->in_ndst.na_ptr != NULL)
8573 ipf_lookup_deref(softc, n->in_ndst.na_type, n->in_ndst.na_ptr);
8575 if (n->in_nsrc.na_atype == FRI_LOOKUP && n->in_nsrc.na_ptr != NULL)
8576 ipf_lookup_deref(softc, n->in_nsrc.na_type, n->in_nsrc.na_ptr);
8578 if (n->in_divmp != NULL)
8579 FREE_MB_T(n->in_divmp);