Home | History | Annotate | Line # | Download | only in netinet
ip_nat.c revision 1.3
      1 /*	$NetBSD: ip_nat.c,v 1.3 2012/07/22 14:27:51 darrenr Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 2012 by Darren Reed.
      5  *
      6  * See the IPFILTER.LICENCE file for details on licencing.
      7  */
      8 #if defined(KERNEL) || defined(_KERNEL)
      9 # undef KERNEL
     10 # undef KERNEL
     11 # define        KERNEL	1
     12 # define        KERNEL	1
     13 #endif
     14 #include <sys/errno.h>
     15 #include <sys/types.h>
     16 #include <sys/param.h>
     17 #include <sys/time.h>
     18 #include <sys/file.h>
     19 #if defined(_KERNEL) && \
     20     (defined(__NetBSD_Version) && (__NetBSD_Version >= 399002000))
     21 # include <sys/kauth.h>
     22 #endif
     23 #if !defined(_KERNEL)
     24 # include <stdio.h>
     25 # include <string.h>
     26 # include <stdlib.h>
     27 # define KERNEL
     28 # ifdef _OpenBSD__
     29 struct file;
     30 # endif
     31 # include <sys/uio.h>
     32 # undef KERNEL
     33 #endif
     34 #if defined(_KERNEL) && \
     35     defined(__FreeBSD_version) && (__FreeBSD_version >= 220000)
     36 # include <sys/filio.h>
     37 # include <sys/fcntl.h>
     38 #else
     39 # include <sys/ioctl.h>
     40 #endif
     41 #if !defined(AIX)
     42 # include <sys/fcntl.h>
     43 #endif
     44 #if !defined(linux)
     45 # include <sys/protosw.h>
     46 #endif
     47 #include <sys/socket.h>
     48 #if defined(_KERNEL)
     49 # include <sys/systm.h>
     50 # if !defined(__SVR4) && !defined(__svr4__)
     51 #  include <sys/mbuf.h>
     52 # endif
     53 #endif
     54 #if defined(__SVR4) || defined(__svr4__)
     55 # include <sys/filio.h>
     56 # include <sys/byteorder.h>
     57 # ifdef KERNEL
     58 #  include <sys/dditypes.h>
     59 # endif
     60 # include <sys/stream.h>
     61 # include <sys/kmem.h>
     62 #endif
     63 #if _FreeBSD_version >= 300000
     64 # include <sys/queue.h>
     65 #endif
     66 #include <net/if.h>
     67 #if _FreeBSD_version >= 300000
     68 # include <net/if_var.h>
     69 #endif
     70 #ifdef sun
     71 # include <net/af.h>
     72 #endif
     73 #include <netinet/in.h>
     74 #include <netinet/in_systm.h>
     75 #include <netinet/ip.h>
     76 
     77 #ifdef RFC1825
     78 # include <vpn/md5.h>
     79 # include <vpn/ipsec.h>
     80 extern struct ifnet vpnif;
     81 #endif
     82 
     83 #if !defined(linux)
     84 # include <netinet/ip_var.h>
     85 #endif
     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>
    102 #endif
    103 #ifdef HAS_SYS_MD5_H
    104 # include <sys/md5.h>
    105 #else
    106 # include "md5.h"
    107 #endif
    108 /* END OF INCLUDES */
    109 
    110 #undef	SOCKADDR_IN
    111 #define	SOCKADDR_IN	struct sockaddr_in
    112 
    113 #if !defined(lint)
    114 #if defined(__NetBSD__)
    115 #include <sys/cdefs.h>
    116 __KERNEL_RCSID(0, "$NetBSD: ip_nat.c,v 1.3 2012/07/22 14:27:51 darrenr Exp $");
    117 #else
    118 static const char sccsid[] = "@(#)ip_nat.c	1.11 6/5/96 (C) 1995 Darren Reed";
    119 static const char rcsid[] = "@(#)Id: ip_nat.c,v 1.1.1.2 2012/07/22 13:45:27 darrenr Exp";
    120 #endif
    121 #endif
    122 
    123 
    124 #define	NATFSUM(n,v,f)	((v) == 4 ? (n)->f.in4.s_addr : (n)->f.i6[0] + \
    125 			 (n)->f.i6[1] + (n)->f.i6[2] + (n)->f.i6[3])
    126 #define	NBUMP(x)	softn->(x)++
    127 #define	NBUMPD(x, y)	do { \
    128 				softn->x.y++; \
    129 				DT(y); \
    130 			} while (0)
    131 #define	NBUMPSIDE(y,x)	softn->ipf_nat_stats.ns_side[y].x++
    132 #define	NBUMPSIDED(y,x)	do { softn->ipf_nat_stats.ns_side[y].x++; \
    133 			     DT(x); } while (0)
    134 #define	NBUMPSIDEX(y,x,z) \
    135 			do { softn->ipf_nat_stats.ns_side[y].x++; \
    136 			     DT(z); } while (0)
    137 #define	NBUMPSIDEDF(y,x)do { softn->ipf_nat_stats.ns_side[y].x++; \
    138 			     DT1(x, fr_info_t *, fin); } while (0)
    139 
    140 frentry_t	ipfnatblock;
    141 
    142 static ipftuneable_t ipf_nat_tuneables[] = {
    143 	/* nat */
    144 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_lock) },
    145 		"nat_lock",	0,	1,
    146 		stsizeof(ipf_nat_softc_t, ipf_nat_lock),
    147 		IPFT_RDONLY,		NULL,	NULL },
    148 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_sz) },
    149 		"nat_table_size", 1,	0x7fffffff,
    150 		stsizeof(ipf_nat_softc_t, ipf_nat_table_sz),
    151 		0,			NULL,	ipf_nat_rehash },
    152 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_max) },
    153 		"nat_table_max", 1,	0x7fffffff,
    154 		stsizeof(ipf_nat_softc_t, ipf_nat_table_max),
    155 		0,			NULL,	NULL },
    156 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_maprules_sz) },
    157 		"nat_rules_size", 1,	0x7fffffff,
    158 		stsizeof(ipf_nat_softc_t, ipf_nat_maprules_sz),
    159 		0,			NULL,	ipf_nat_rehash_rules },
    160 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_rdrrules_sz) },
    161 		"rdr_rules_size", 1,	0x7fffffff,
    162 		stsizeof(ipf_nat_softc_t, ipf_nat_rdrrules_sz),
    163 		0,			NULL,	ipf_nat_rehash_rules },
    164 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_hostmap_sz) },
    165 		"hostmap_size",	1,	0x7fffffff,
    166 		stsizeof(ipf_nat_softc_t, ipf_nat_hostmap_sz),
    167 		0,			NULL,	ipf_nat_hostmap_rehash },
    168 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_maxbucket) },
    169 		"nat_maxbucket",1,	0x7fffffff,
    170 		stsizeof(ipf_nat_softc_t, ipf_nat_maxbucket),
    171 		0,			NULL,	NULL },
    172 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_logging) },
    173 		"nat_logging",	0,	1,
    174 		stsizeof(ipf_nat_softc_t, ipf_nat_logging),
    175 		0,			NULL,	NULL },
    176 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_doflush) },
    177 		"nat_doflush",	0,	1,
    178 		stsizeof(ipf_nat_softc_t, ipf_nat_doflush),
    179 		0,			NULL,	NULL },
    180 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_wm_low) },
    181 		"nat_table_wm_low",	1,	99,
    182 		stsizeof(ipf_nat_softc_t, ipf_nat_table_wm_low),
    183 		0,			NULL,	NULL },
    184 	{ { (void *)offsetof(ipf_nat_softc_t, ipf_nat_table_wm_high) },
    185 		"nat_table_wm_high",	2,	100,
    186 		stsizeof(ipf_nat_softc_t, ipf_nat_table_wm_high),
    187 		0,			NULL,	NULL },
    188 	{ { 0 },
    189 		NULL,			0,	0,
    190 		0,
    191 		0,			NULL,	NULL }
    192 };
    193 
    194 /* ======================================================================== */
    195 /* How the NAT is organised and works.                                      */
    196 /*                                                                          */
    197 /* Inside (interface y) NAT       Outside (interface x)                     */
    198 /* -------------------- -+- -------------------------------------           */
    199 /* Packet going          |   out, processsed by ipf_nat_checkout() for x    */
    200 /* ------------>         |   ------------>                                  */
    201 /* src=10.1.1.1          |   src=192.1.1.1                                  */
    202 /*                       |                                                  */
    203 /*                       |   in, processed by ipf_nat_checkin() for x       */
    204 /* <------------         |   <------------                                  */
    205 /* dst=10.1.1.1          |   dst=192.1.1.1                                  */
    206 /* -------------------- -+- -------------------------------------           */
    207 /* ipf_nat_checkout() - changes ip_src and if required, sport               */
    208 /*             - creates a new mapping, if required.                        */
    209 /* ipf_nat_checkin()  - changes ip_dst and if required, dport               */
    210 /*                                                                          */
    211 /* In the NAT table, internal source is recorded as "in" and externally     */
    212 /* seen as "out".                                                           */
    213 /* ======================================================================== */
    214 
    215 
    216 #if SOLARIS && !defined(INSTANCES)
    217 extern	int		pfil_delayed_copy;
    218 #endif
    219 
    220 static	int	ipf_nat_flush_entry(ipf_main_softc_t *, void *);
    221 static	int	ipf_nat_getent(ipf_main_softc_t *, void *, int);
    222 static	int	ipf_nat_getsz(ipf_main_softc_t *, void *, int);
    223 static	int	ipf_nat_putent(ipf_main_softc_t *, void *, int);
    224 static	void	ipf_nat_addmap(ipf_nat_softc_t *, ipnat_t *);
    225 static	void	ipf_nat_addrdr(ipf_nat_softc_t *, ipnat_t *);
    226 static	int	ipf_nat_builddivertmp(ipf_nat_softc_t *, ipnat_t *);
    227 static	int	ipf_nat_clearlist(ipf_main_softc_t *, ipf_nat_softc_t *);
    228 static	int	ipf_nat_cmp_rules(ipnat_t *, ipnat_t *);
    229 static	int	ipf_nat_decap(fr_info_t *, nat_t *);
    230 static	void	ipf_nat_delrule(ipf_main_softc_t *, ipf_nat_softc_t *,
    231 				     ipnat_t *, int);
    232 static	int	ipf_nat_extraflush(ipf_main_softc_t *, ipf_nat_softc_t *, int);
    233 static	int	ipf_nat_finalise(fr_info_t *, nat_t *);
    234 static	int	ipf_nat_flushtable(ipf_main_softc_t *, ipf_nat_softc_t *);
    235 static	int	ipf_nat_getnext(ipf_main_softc_t *, ipftoken_t *,
    236 				ipfgeniter_t *, ipfobj_t *);
    237 static	int	ipf_nat_gettable(ipf_main_softc_t *, ipf_nat_softc_t *, char *);
    238 static	hostmap_t *ipf_nat_hostmap(ipf_nat_softc_t *, ipnat_t *,
    239 				   struct in_addr, struct in_addr,
    240 				   struct in_addr, u_32_t);
    241 static	int	ipf_nat_icmpquerytype(int);
    242 static	int	ipf_nat_iterator(ipf_main_softc_t *, ipftoken_t *,
    243 				 ipfgeniter_t *, ipfobj_t *);
    244 static	int	ipf_nat_match(fr_info_t *, ipnat_t *);
    245 static	int	ipf_nat_matcharray(nat_t *, int *, u_long);
    246 static	int	ipf_nat_matchflush(ipf_main_softc_t *, ipf_nat_softc_t *,
    247 				   void *);
    248 static	void	ipf_nat_mssclamp(tcphdr_t *, u_32_t, fr_info_t *, u_short *);
    249 static	int	ipf_nat_newmap(fr_info_t *, nat_t *, natinfo_t *);
    250 static	int	ipf_nat_newdivert(fr_info_t *, nat_t *, natinfo_t *);
    251 static	int	ipf_nat_newrdr(fr_info_t *, nat_t *, natinfo_t *);
    252 static	int	ipf_nat_newrewrite(fr_info_t *, nat_t *, natinfo_t *);
    253 static	int	ipf_nat_nextaddr(fr_info_t *, nat_addr_t *, u_32_t *, u_32_t *);
    254 static	int	ipf_nat_nextaddrinit(ipf_main_softc_t *, char *,
    255 				     nat_addr_t *, int, void *);
    256 static	int	ipf_nat_resolverule(ipf_main_softc_t *, ipnat_t *);
    257 static	int	ipf_nat_ruleaddrinit(ipf_main_softc_t *,
    258 				     ipf_nat_softc_t *, ipnat_t *);
    259 static	void	ipf_nat_rule_fini(ipf_main_softc_t *, ipnat_t *);
    260 static	int	ipf_nat_rule_init(ipf_main_softc_t *, ipf_nat_softc_t *,
    261 				       ipnat_t *);
    262 static	int	ipf_nat_siocaddnat(ipf_main_softc_t *, ipf_nat_softc_t *,
    263 					ipnat_t *, int);
    264 static	void	ipf_nat_siocdelnat(ipf_main_softc_t *, ipf_nat_softc_t *,
    265 					ipnat_t *, int);
    266 static	void	ipf_nat_tabmove(ipf_nat_softc_t *, nat_t *);
    267 
    268 /* ------------------------------------------------------------------------ */
    269 /* Function:    ipf_nat_main_load                                           */
    270 /* Returns:     int - 0 == success, -1 == failure                           */
    271 /* Parameters:  Nil                                                         */
    272 /*                                                                          */
    273 /* The only global NAT structure that needs to be initialised is the filter */
    274 /* rule that is used with blocking packets.                                 */
    275 /* ------------------------------------------------------------------------ */
    276 int
    277 ipf_nat_main_load(void)
    278 {
    279 	bzero((char *)&ipfnatblock, sizeof(ipfnatblock));
    280 	ipfnatblock.fr_flags = FR_BLOCK|FR_QUICK;
    281 	ipfnatblock.fr_ref = 1;
    282 
    283 	return 0;
    284 }
    285 
    286 
    287 /* ------------------------------------------------------------------------ */
    288 /* Function:    ipf_nat_main_unload                                         */
    289 /* Returns:     int - 0 == success, -1 == failure                           */
    290 /* Parameters:  Nil                                                         */
    291 /*                                                                          */
    292 /* A null-op function that exists as a placeholder so that the flow in      */
    293 /* other functions is obvious.                                              */
    294 /* ------------------------------------------------------------------------ */
    295 int
    296 ipf_nat_main_unload(void)
    297 {
    298 	return 0;
    299 }
    300 
    301 
    302 /* ------------------------------------------------------------------------ */
    303 /* Function:    ipf_nat_soft_create                                         */
    304 /* Returns:     void * - NULL = failure, else pointer to NAT context        */
    305 /* Parameters:  softc(I) - pointer to soft context main structure           */
    306 /*                                                                          */
    307 /* Allocate the initial soft context structure for NAT and populate it with */
    308 /* some default values. Creating the tables is left until we call _init so  */
    309 /* that sizes can be changed before we get under way.                       */
    310 /* ------------------------------------------------------------------------ */
    311 void *
    312 ipf_nat_soft_create(ipf_main_softc_t *softc)
    313 {
    314 	ipf_nat_softc_t *softn;
    315 
    316 	KMALLOC(softn, ipf_nat_softc_t *);
    317 	if (softn == NULL)
    318 		return NULL;
    319 
    320 	bzero((char *)softn, sizeof(*softn));
    321 
    322 	softn->ipf_nat_tune = ipf_tune_array_copy(softn,
    323 						  sizeof(ipf_nat_tuneables),
    324 						  ipf_nat_tuneables);
    325 	if (softn->ipf_nat_tune == NULL) {
    326 		ipf_nat_soft_destroy(softc, softn);
    327 		return NULL;
    328 	}
    329 	if (ipf_tune_array_link(softc, softn->ipf_nat_tune) == -1) {
    330 		ipf_nat_soft_destroy(softc, softn);
    331 		return NULL;
    332 	}
    333 
    334 	softn->ipf_nat_list_tail = &softn->ipf_nat_list;
    335 
    336 	softn->ipf_nat_table_max = NAT_TABLE_MAX;
    337 	softn->ipf_nat_table_sz = NAT_TABLE_SZ;
    338 	softn->ipf_nat_maprules_sz = NAT_SIZE;
    339 	softn->ipf_nat_rdrrules_sz = RDR_SIZE;
    340 	softn->ipf_nat_hostmap_sz = HOSTMAP_SIZE;
    341 	softn->ipf_nat_doflush = 0;
    342 #ifdef  IPFILTER_LOG
    343 	softn->ipf_nat_logging = 1;
    344 #else
    345 	softn->ipf_nat_logging = 0;
    346 #endif
    347 
    348 	softn->ipf_nat_defage = DEF_NAT_AGE;
    349 	softn->ipf_nat_defipage = IPF_TTLVAL(60);
    350 	softn->ipf_nat_deficmpage = IPF_TTLVAL(3);
    351 	softn->ipf_nat_table_wm_high = 99;
    352 	softn->ipf_nat_table_wm_low = 90;
    353 
    354 	return softn;
    355 }
    356 
    357 /* ------------------------------------------------------------------------ */
    358 /* Function:    ipf_nat_soft_destroy                                        */
    359 /* Returns:     Nil                                                         */
    360 /* Parameters:  softc(I) - pointer to soft context main structure           */
    361 /*                                                                          */
    362 /* ------------------------------------------------------------------------ */
    363 void
    364 ipf_nat_soft_destroy(ipf_main_softc_t *softc, void *arg)
    365 {
    366 	ipf_nat_softc_t *softn = arg;
    367 
    368 	if (softn->ipf_nat_tune != NULL) {
    369 		ipf_tune_array_unlink(softc, softn->ipf_nat_tune);
    370 		KFREES(softn->ipf_nat_tune, sizeof(ipf_nat_tuneables));
    371 		softn->ipf_nat_tune = NULL;
    372 	}
    373 
    374 	KFREE(softn);
    375 }
    376 
    377 
    378 /* ------------------------------------------------------------------------ */
    379 /* Function:    ipf_nat_init                                                */
    380 /* Returns:     int - 0 == success, -1 == failure                           */
    381 /* Parameters:  softc(I) - pointer to soft context main structure           */
    382 /*                                                                          */
    383 /* Initialise all of the NAT locks, tables and other structures.            */
    384 /* ------------------------------------------------------------------------ */
    385 int
    386 ipf_nat_soft_init(ipf_main_softc_t *softc, void *arg)
    387 {
    388 	ipf_nat_softc_t *softn = arg;
    389 	ipftq_t *tq;
    390 	int i;
    391 
    392 	KMALLOCS(softn->ipf_nat_table[0], nat_t **, \
    393 		 sizeof(nat_t *) * softn->ipf_nat_table_sz);
    394 
    395 	if (softn->ipf_nat_table[0] != NULL) {
    396 		bzero((char *)softn->ipf_nat_table[0],
    397 		      softn->ipf_nat_table_sz * sizeof(nat_t *));
    398 	} else {
    399 		return -1;
    400 	}
    401 
    402 	KMALLOCS(softn->ipf_nat_table[1], nat_t **, \
    403 		 sizeof(nat_t *) * softn->ipf_nat_table_sz);
    404 
    405 	if (softn->ipf_nat_table[1] != NULL) {
    406 		bzero((char *)softn->ipf_nat_table[1],
    407 		      softn->ipf_nat_table_sz * sizeof(nat_t *));
    408 	} else {
    409 		return -2;
    410 	}
    411 
    412 	KMALLOCS(softn->ipf_nat_map_rules, ipnat_t **, \
    413 		 sizeof(ipnat_t *) * softn->ipf_nat_maprules_sz);
    414 
    415 	if (softn->ipf_nat_map_rules != NULL) {
    416 		bzero((char *)softn->ipf_nat_map_rules,
    417 		      softn->ipf_nat_maprules_sz * sizeof(ipnat_t *));
    418 	} else {
    419 		return -3;
    420 	}
    421 
    422 	KMALLOCS(softn->ipf_nat_rdr_rules, ipnat_t **, \
    423 		 sizeof(ipnat_t *) * softn->ipf_nat_rdrrules_sz);
    424 
    425 	if (softn->ipf_nat_rdr_rules != NULL) {
    426 		bzero((char *)softn->ipf_nat_rdr_rules,
    427 		      softn->ipf_nat_rdrrules_sz * sizeof(ipnat_t *));
    428 	} else {
    429 		return -4;
    430 	}
    431 
    432 	KMALLOCS(softn->ipf_hm_maptable, hostmap_t **, \
    433 		 sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
    434 
    435 	if (softn->ipf_hm_maptable != NULL) {
    436 		bzero((char *)softn->ipf_hm_maptable,
    437 		      sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
    438 	} else {
    439 		return -5;
    440 	}
    441 	softn->ipf_hm_maplist = NULL;
    442 
    443 	KMALLOCS(softn->ipf_nat_stats.ns_side[0].ns_bucketlen, u_int *,
    444 		 softn->ipf_nat_table_sz * sizeof(u_int));
    445 
    446 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen == NULL) {
    447 		return -6;
    448 	}
    449 	bzero((char *)softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
    450 	      softn->ipf_nat_table_sz * sizeof(u_int));
    451 
    452 	KMALLOCS(softn->ipf_nat_stats.ns_side[1].ns_bucketlen, u_int *,
    453 		 softn->ipf_nat_table_sz * sizeof(u_int));
    454 
    455 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen == NULL) {
    456 		return -7;
    457 	}
    458 
    459 	bzero((char *)softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
    460 	      softn->ipf_nat_table_sz * sizeof(u_int));
    461 
    462 	if (softn->ipf_nat_maxbucket == 0) {
    463 		for (i = softn->ipf_nat_table_sz; i > 0; i >>= 1)
    464 			softn->ipf_nat_maxbucket++;
    465 		softn->ipf_nat_maxbucket *= 2;
    466 	}
    467 
    468 	ipf_sttab_init(softc, softn->ipf_nat_tcptq);
    469 	/*
    470 	 * Increase this because we may have "keep state" following this too
    471 	 * and packet storms can occur if this is removed too quickly.
    472 	 */
    473 	softn->ipf_nat_tcptq[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcplastack;
    474 	softn->ipf_nat_tcptq[IPF_TCP_NSTATES - 1].ifq_next =
    475 							&softn->ipf_nat_udptq;
    476 
    477 	IPFTQ_INIT(&softn->ipf_nat_udptq, softn->ipf_nat_defage,
    478 		   "nat ipftq udp tab");
    479 	softn->ipf_nat_udptq.ifq_next = &softn->ipf_nat_udpacktq;
    480 
    481 	IPFTQ_INIT(&softn->ipf_nat_udpacktq, softn->ipf_nat_defage,
    482 		   "nat ipftq udpack tab");
    483 	softn->ipf_nat_udpacktq.ifq_next = &softn->ipf_nat_icmptq;
    484 
    485 	IPFTQ_INIT(&softn->ipf_nat_icmptq, softn->ipf_nat_deficmpage,
    486 		   "nat icmp ipftq tab");
    487 	softn->ipf_nat_icmptq.ifq_next = &softn->ipf_nat_icmpacktq;
    488 
    489 	IPFTQ_INIT(&softn->ipf_nat_icmpacktq, softn->ipf_nat_defage,
    490 		   "nat icmpack ipftq tab");
    491 	softn->ipf_nat_icmpacktq.ifq_next = &softn->ipf_nat_iptq;
    492 
    493 	IPFTQ_INIT(&softn->ipf_nat_iptq, softn->ipf_nat_defipage,
    494 		   "nat ip ipftq tab");
    495 	softn->ipf_nat_iptq.ifq_next = &softn->ipf_nat_pending;
    496 
    497 	IPFTQ_INIT(&softn->ipf_nat_pending, 1, "nat pending ipftq tab");
    498 	softn->ipf_nat_pending.ifq_next = NULL;
    499 
    500 	for (i = 0, tq = softn->ipf_nat_tcptq; i < IPF_TCP_NSTATES; i++, tq++) {
    501 		if (tq->ifq_ttl < softn->ipf_nat_deficmpage)
    502 			tq->ifq_ttl = softn->ipf_nat_deficmpage;
    503 #ifdef LARGE_NAT
    504 		else if (tq->ifq_ttl > softn->ipf_nat_defage)
    505 			tq->ifq_ttl = softn->ipf_nat_defage;
    506 #endif
    507 	}
    508 
    509 	/*
    510 	 * Increase this because we may have "keep state" following
    511 	 * this too and packet storms can occur if this is removed
    512 	 * too quickly.
    513 	 */
    514 	softn->ipf_nat_tcptq[IPF_TCPS_CLOSED].ifq_ttl = softc->ipf_tcplastack;
    515 
    516 	MUTEX_INIT(&softn->ipf_nat_new, "ipf nat new mutex");
    517 	MUTEX_INIT(&softn->ipf_nat_io, "ipf nat io mutex");
    518 
    519 	softn->ipf_nat_inited = 1;
    520 
    521 	return 0;
    522 }
    523 
    524 
    525 /* ------------------------------------------------------------------------ */
    526 /* Function:    ipf_nat_soft_fini                                           */
    527 /* Returns:     Nil                                                         */
    528 /* Parameters:  softc(I) - pointer to soft context main structure           */
    529 /*                                                                          */
    530 /* Free all memory used by NAT structures allocated at runtime.             */
    531 /* ------------------------------------------------------------------------ */
    532 int
    533 ipf_nat_soft_fini(ipf_main_softc_t *softc, void *arg)
    534 {
    535 	ipf_nat_softc_t *softn = arg;
    536 	ipftq_t *ifq, *ifqnext;
    537 
    538 	(void) ipf_nat_clearlist(softc, softn);
    539 	(void) ipf_nat_flushtable(softc, softn);
    540 
    541 	/*
    542 	 * Proxy timeout queues are not cleaned here because although they
    543 	 * exist on the NAT list, ipf_proxy_unload is called after unload
    544 	 * and the proxies actually are responsible for them being created.
    545 	 * Should the proxy timeouts have their own list?  There's no real
    546 	 * justification as this is the only complication.
    547 	 */
    548 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifqnext) {
    549 		ifqnext = ifq->ifq_next;
    550 		if (ipf_deletetimeoutqueue(ifq) == 0)
    551 			ipf_freetimeoutqueue(softc, ifq);
    552 	}
    553 
    554 	if (softn->ipf_nat_table[0] != NULL) {
    555 		KFREES(softn->ipf_nat_table[0],
    556 		       sizeof(nat_t *) * softn->ipf_nat_table_sz);
    557 		softn->ipf_nat_table[0] = NULL;
    558 	}
    559 	if (softn->ipf_nat_table[1] != NULL) {
    560 		KFREES(softn->ipf_nat_table[1],
    561 		       sizeof(nat_t *) * softn->ipf_nat_table_sz);
    562 		softn->ipf_nat_table[1] = NULL;
    563 	}
    564 	if (softn->ipf_nat_map_rules != NULL) {
    565 		KFREES(softn->ipf_nat_map_rules,
    566 		       sizeof(ipnat_t *) * softn->ipf_nat_maprules_sz);
    567 		softn->ipf_nat_map_rules = NULL;
    568 	}
    569 	if (softn->ipf_nat_rdr_rules != NULL) {
    570 		KFREES(softn->ipf_nat_rdr_rules,
    571 		       sizeof(ipnat_t *) * softn->ipf_nat_rdrrules_sz);
    572 		softn->ipf_nat_rdr_rules = NULL;
    573 	}
    574 	if (softn->ipf_hm_maptable != NULL) {
    575 		KFREES(softn->ipf_hm_maptable,
    576 		       sizeof(hostmap_t *) * softn->ipf_nat_hostmap_sz);
    577 		softn->ipf_hm_maptable = NULL;
    578 	}
    579 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen != NULL) {
    580 		KFREES(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
    581 		       sizeof(u_int) * softn->ipf_nat_table_sz);
    582 		softn->ipf_nat_stats.ns_side[0].ns_bucketlen = NULL;
    583 	}
    584 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen != NULL) {
    585 		KFREES(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
    586 		       sizeof(u_int) * softn->ipf_nat_table_sz);
    587 		softn->ipf_nat_stats.ns_side[1].ns_bucketlen = NULL;
    588 	}
    589 
    590 	if (softn->ipf_nat_inited == 1) {
    591 		softn->ipf_nat_inited = 0;
    592 		ipf_sttab_destroy(softn->ipf_nat_tcptq);
    593 
    594 		MUTEX_DESTROY(&softn->ipf_nat_new);
    595 		MUTEX_DESTROY(&softn->ipf_nat_io);
    596 
    597 		MUTEX_DESTROY(&softn->ipf_nat_udptq.ifq_lock);
    598 		MUTEX_DESTROY(&softn->ipf_nat_udpacktq.ifq_lock);
    599 		MUTEX_DESTROY(&softn->ipf_nat_icmptq.ifq_lock);
    600 		MUTEX_DESTROY(&softn->ipf_nat_icmpacktq.ifq_lock);
    601 		MUTEX_DESTROY(&softn->ipf_nat_iptq.ifq_lock);
    602 		MUTEX_DESTROY(&softn->ipf_nat_pending.ifq_lock);
    603 	}
    604 
    605 	return 0;
    606 }
    607 
    608 
    609 /* ------------------------------------------------------------------------ */
    610 /* Function:    ipf_nat_setlock                                             */
    611 /* Returns:     Nil                                                         */
    612 /* Parameters:  arg(I) - pointer to soft state information                  */
    613 /*              tmp(I) - new lock value                                     */
    614 /*                                                                          */
    615 /* Set the "lock status" of NAT to the value in tmp.                        */
    616 /* ------------------------------------------------------------------------ */
    617 void
    618 ipf_nat_setlock(void *arg, int tmp)
    619 {
    620 	ipf_nat_softc_t *softn = arg;
    621 
    622 	softn->ipf_nat_lock = tmp;
    623 }
    624 
    625 
    626 /* ------------------------------------------------------------------------ */
    627 /* Function:    ipf_nat_addrdr                                              */
    628 /* Returns:     Nil                                                         */
    629 /* Parameters:  n(I) - pointer to NAT rule to add                           */
    630 /*                                                                          */
    631 /* Adds a redirect rule to the hash table of redirect rules and the list of */
    632 /* loaded NAT rules.  Updates the bitmask indicating which netmasks are in  */
    633 /* use by redirect rules.                                                   */
    634 /* ------------------------------------------------------------------------ */
    635 static void
    636 ipf_nat_addrdr(ipf_nat_softc_t *softn, ipnat_t *n)
    637 {
    638 	ipnat_t **np;
    639 	u_32_t j;
    640 	u_int hv;
    641 	u_int rhv;
    642 	int k;
    643 
    644 	if (n->in_odstatype == FRI_NORMAL) {
    645 		k = count4bits(n->in_odstmsk);
    646 		ipf_inet_mask_add(k, &softn->ipf_nat_rdr_mask);
    647 		j = (n->in_odstaddr & n->in_odstmsk);
    648 		rhv = NAT_HASH_FN(j, 0, 0xffffffff);
    649 	} else {
    650 		ipf_inet_mask_add(0, &softn->ipf_nat_rdr_mask);
    651 		j = 0;
    652 		rhv = 0;
    653 	}
    654 	hv = rhv % softn->ipf_nat_rdrrules_sz;
    655 	np = softn->ipf_nat_rdr_rules + hv;
    656 	while (*np != NULL)
    657 		np = &(*np)->in_rnext;
    658 	n->in_rnext = NULL;
    659 	n->in_prnext = np;
    660 	n->in_hv[0] = hv;
    661 	n->in_use++;
    662 	*np = n;
    663 }
    664 
    665 
    666 /* ------------------------------------------------------------------------ */
    667 /* Function:    ipf_nat_addmap                                              */
    668 /* Returns:     Nil                                                         */
    669 /* Parameters:  n(I) - pointer to NAT rule to add                           */
    670 /*                                                                          */
    671 /* Adds a NAT map rule to the hash table of rules and the list of  loaded   */
    672 /* NAT rules.  Updates the bitmask indicating which netmasks are in use by  */
    673 /* redirect rules.                                                          */
    674 /* ------------------------------------------------------------------------ */
    675 static void
    676 ipf_nat_addmap(ipf_nat_softc_t *softn, ipnat_t *n)
    677 {
    678 	ipnat_t **np;
    679 	u_32_t j;
    680 	u_int hv;
    681 	u_int rhv;
    682 	int k;
    683 
    684 	if (n->in_osrcatype == FRI_NORMAL) {
    685 		k = count4bits(n->in_osrcmsk);
    686 		ipf_inet_mask_add(k, &softn->ipf_nat_map_mask);
    687 		j = (n->in_osrcaddr & n->in_osrcmsk);
    688 		rhv = NAT_HASH_FN(j, 0, 0xffffffff);
    689 	} else {
    690 		ipf_inet_mask_add(0, &softn->ipf_nat_map_mask);
    691 		j = 0;
    692 		rhv = 0;
    693 	}
    694 	hv = rhv % softn->ipf_nat_maprules_sz;
    695 	np = softn->ipf_nat_map_rules + hv;
    696 	while (*np != NULL)
    697 		np = &(*np)->in_mnext;
    698 	n->in_mnext = NULL;
    699 	n->in_pmnext = np;
    700 	n->in_hv[1] = rhv;
    701 	n->in_use++;
    702 	*np = n;
    703 }
    704 
    705 
    706 /* ------------------------------------------------------------------------ */
    707 /* Function:    ipf_nat_delrdr                                              */
    708 /* Returns:     Nil                                                         */
    709 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
    710 /*                                                                          */
    711 /* Removes a redirect rule from the hash table of redirect rules.           */
    712 /* ------------------------------------------------------------------------ */
    713 void
    714 ipf_nat_delrdr(ipf_nat_softc_t *softn, ipnat_t *n)
    715 {
    716 	if (n->in_odstatype == FRI_NORMAL) {
    717 		int k = count4bits(n->in_odstmsk);
    718 		ipf_inet_mask_del(k, &softn->ipf_nat_rdr_mask);
    719 	} else {
    720 		ipf_inet_mask_del(0, &softn->ipf_nat_rdr_mask);
    721 	}
    722 	if (n->in_rnext)
    723 		n->in_rnext->in_prnext = n->in_prnext;
    724 	*n->in_prnext = n->in_rnext;
    725 	n->in_use--;
    726 }
    727 
    728 
    729 /* ------------------------------------------------------------------------ */
    730 /* Function:    ipf_nat_delmap                                              */
    731 /* Returns:     Nil                                                         */
    732 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
    733 /*                                                                          */
    734 /* Removes a NAT map rule from the hash table of NAT map rules.             */
    735 /* ------------------------------------------------------------------------ */
    736 void
    737 ipf_nat_delmap(ipf_nat_softc_t *softn, ipnat_t *n)
    738 {
    739 	if (n->in_osrcatype == FRI_NORMAL) {
    740 		int k = count4bits(n->in_osrcmsk);
    741 		ipf_inet_mask_del(k, &softn->ipf_nat_map_mask);
    742 	} else {
    743 		ipf_inet_mask_del(0, &softn->ipf_nat_map_mask);
    744 	}
    745 	if (n->in_mnext != NULL)
    746 		n->in_mnext->in_pmnext = n->in_pmnext;
    747 	*n->in_pmnext = n->in_mnext;
    748 	n->in_use--;
    749 }
    750 
    751 
    752 /* ------------------------------------------------------------------------ */
    753 /* Function:    ipf_nat_hostmap                                             */
    754 /* Returns:     struct hostmap* - NULL if no hostmap could be created,      */
    755 /*                                else a pointer to the hostmapping to use  */
    756 /* Parameters:  np(I)   - pointer to NAT rule                               */
    757 /*              real(I) - real IP address                                   */
    758 /*              map(I)  - mapped IP address                                 */
    759 /*              port(I) - destination port number                           */
    760 /* Write Locks: ipf_nat                                                     */
    761 /*                                                                          */
    762 /* Check if an ip address has already been allocated for a given mapping    */
    763 /* that is not doing port based translation.  If is not yet allocated, then */
    764 /* create a new entry if a non-NULL NAT rule pointer has been supplied.     */
    765 /* ------------------------------------------------------------------------ */
    766 static struct hostmap *
    767 ipf_nat_hostmap(ipf_nat_softc_t *softn, ipnat_t *np, struct in_addr src,
    768     struct in_addr dst, struct in_addr map, u_32_t port)
    769 {
    770 	hostmap_t *hm;
    771 	u_int hv, rhv;
    772 
    773 	hv = (src.s_addr ^ dst.s_addr);
    774 	hv += src.s_addr;
    775 	hv += dst.s_addr;
    776 	rhv = hv;
    777 	hv %= softn->ipf_nat_hostmap_sz;
    778 	for (hm = softn->ipf_hm_maptable[hv]; hm; hm = hm->hm_hnext)
    779 		if ((hm->hm_osrcip.s_addr == src.s_addr) &&
    780 		    (hm->hm_odstip.s_addr == dst.s_addr) &&
    781 		    ((np == NULL) || (np == hm->hm_ipnat)) &&
    782 		    ((port == 0) || (port == hm->hm_port))) {
    783 			softn->ipf_nat_stats.ns_hm_addref++;
    784 			hm->hm_ref++;
    785 			return hm;
    786 		}
    787 
    788 	if (np == NULL) {
    789 		softn->ipf_nat_stats.ns_hm_nullnp++;
    790 		return NULL;
    791 	}
    792 
    793 	KMALLOC(hm, hostmap_t *);
    794 	if (hm) {
    795 		hm->hm_next = softn->ipf_hm_maplist;
    796 		hm->hm_pnext = &softn->ipf_hm_maplist;
    797 		if (softn->ipf_hm_maplist != NULL)
    798 			softn->ipf_hm_maplist->hm_pnext = &hm->hm_next;
    799 		softn->ipf_hm_maplist = hm;
    800 		hm->hm_hnext = softn->ipf_hm_maptable[hv];
    801 		hm->hm_phnext = softn->ipf_hm_maptable + hv;
    802 		if (softn->ipf_hm_maptable[hv] != NULL)
    803 			softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
    804 		softn->ipf_hm_maptable[hv] = hm;
    805 		hm->hm_ipnat = np;
    806 		np->in_use++;
    807 		hm->hm_osrcip = src;
    808 		hm->hm_odstip = dst;
    809 		hm->hm_nsrcip = map;
    810 		hm->hm_ndstip.s_addr = 0;
    811 		hm->hm_ref = 1;
    812 		hm->hm_port = port;
    813 		hm->hm_hv = rhv;
    814 		hm->hm_v = 4;
    815 		softn->ipf_nat_stats.ns_hm_new++;
    816 	} else {
    817 		softn->ipf_nat_stats.ns_hm_newfail++;
    818 	}
    819 	return hm;
    820 }
    821 
    822 
    823 /* ------------------------------------------------------------------------ */
    824 /* Function:    ipf_nat_hostmapdel                                          */
    825 /* Returns:     Nil                                                         */
    826 /* Parameters:  hmp(I) - pointer to hostmap structure pointer               */
    827 /* Write Locks: ipf_nat                                                     */
    828 /*                                                                          */
    829 /* Decrement the references to this hostmap structure by one.  If this      */
    830 /* reaches zero then remove it and free it.                                 */
    831 /* ------------------------------------------------------------------------ */
    832 void
    833 ipf_nat_hostmapdel(ipf_main_softc_t *softc, struct hostmap **hmp)
    834 {
    835 	struct hostmap *hm;
    836 
    837 	hm = *hmp;
    838 	*hmp = NULL;
    839 
    840 	hm->hm_ref--;
    841 	if (hm->hm_ref == 0) {
    842 		ipf_nat_rule_deref(softc, &hm->hm_ipnat);
    843 		if (hm->hm_hnext)
    844 			hm->hm_hnext->hm_phnext = hm->hm_phnext;
    845 		*hm->hm_phnext = hm->hm_hnext;
    846 		if (hm->hm_next)
    847 			hm->hm_next->hm_pnext = hm->hm_pnext;
    848 		*hm->hm_pnext = hm->hm_next;
    849 		KFREE(hm);
    850 	}
    851 }
    852 
    853 
    854 /* ------------------------------------------------------------------------ */
    855 /* Function:    ipf_fix_outcksum                                            */
    856 /* Returns:     Nil                                                         */
    857 /* Parameters:  fin(I) - pointer to packet information                      */
    858 /*              sp(I)  - location of 16bit checksum to update               */
    859 /*              n((I)  - amount to adjust checksum by                       */
    860 /*                                                                          */
    861 /* Adjusts the 16bit checksum by "n" for packets going out.                 */
    862 /* ------------------------------------------------------------------------ */
    863 void
    864 ipf_fix_outcksum(int cksum, u_short *sp, u_32_t n, u_32_t partial)
    865 {
    866 	u_short sumshort;
    867 	u_32_t sum1;
    868 
    869 	if (n == 0)
    870 		return;
    871 
    872 	if (cksum == 4) {
    873 		*sp = 0;
    874 		return;
    875 	}
    876 	if (cksum == 2) {
    877 		sum1 = partial;
    878 		sum1 = (sum1 & 0xffff) + (sum1 >> 16);
    879 		*sp = htons(sum1);
    880 		return;
    881 	}
    882 	sum1 = (~ntohs(*sp)) & 0xffff;
    883 	sum1 += (n);
    884 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    885 	/* Again */
    886 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    887 	sumshort = ~(u_short)sum1;
    888 	*(sp) = htons(sumshort);
    889 }
    890 
    891 
    892 /* ------------------------------------------------------------------------ */
    893 /* Function:    ipf_fix_incksum                                             */
    894 /* Returns:     Nil                                                         */
    895 /* Parameters:  fin(I) - pointer to packet information                      */
    896 /*              sp(I)  - location of 16bit checksum to update               */
    897 /*              n((I)  - amount to adjust checksum by                       */
    898 /*                                                                          */
    899 /* Adjusts the 16bit checksum by "n" for packets going in.                  */
    900 /* ------------------------------------------------------------------------ */
    901 void
    902 ipf_fix_incksum(int cksum, u_short *sp, u_32_t n, u_32_t partial)
    903 {
    904 	u_short sumshort;
    905 	u_32_t sum1;
    906 
    907 	if (n == 0)
    908 		return;
    909 
    910 	if (cksum == 4) {
    911 		*sp = 0;
    912 		return;
    913 	}
    914 	if (cksum == 2) {
    915 		sum1 = partial;
    916 		sum1 = (sum1 & 0xffff) + (sum1 >> 16);
    917 		*sp = htons(sum1);
    918 		return;
    919 	}
    920 
    921 	sum1 = (~ntohs(*sp)) & 0xffff;
    922 	sum1 += ~(n) & 0xffff;
    923 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    924 	/* Again */
    925 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    926 	sumshort = ~(u_short)sum1;
    927 	*(sp) = htons(sumshort);
    928 }
    929 
    930 
    931 /* ------------------------------------------------------------------------ */
    932 /* Function:    ipf_fix_datacksum                                           */
    933 /* Returns:     Nil                                                         */
    934 /* Parameters:  sp(I)  - location of 16bit checksum to update               */
    935 /*              n((I)  - amount to adjust checksum by                       */
    936 /*                                                                          */
    937 /* Fix_datacksum is used *only* for the adjustments of checksums in the     */
    938 /* data section of an IP packet.                                            */
    939 /*                                                                          */
    940 /* The only situation in which you need to do this is when NAT'ing an       */
    941 /* ICMP error message. Such a message, contains in its body the IP header   */
    942 /* of the original IP packet, that causes the error.                        */
    943 /*                                                                          */
    944 /* You can't use fix_incksum or fix_outcksum in that case, because for the  */
    945 /* kernel the data section of the ICMP error is just data, and no special   */
    946 /* processing like hardware cksum or ntohs processing have been done by the */
    947 /* kernel on the data section.                                              */
    948 /* ------------------------------------------------------------------------ */
    949 void
    950 ipf_fix_datacksum(u_short *sp, u_32_t n)
    951 {
    952 	u_short sumshort;
    953 	u_32_t sum1;
    954 
    955 	if (n == 0)
    956 		return;
    957 
    958 	sum1 = (~ntohs(*sp)) & 0xffff;
    959 	sum1 += (n);
    960 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    961 	/* Again */
    962 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
    963 	sumshort = ~(u_short)sum1;
    964 	*(sp) = htons(sumshort);
    965 }
    966 
    967 
    968 /* ------------------------------------------------------------------------ */
    969 /* Function:    ipf_nat_ioctl                                               */
    970 /* Returns:     int - 0 == success, != 0 == failure                         */
    971 /* Parameters:  softc(I) - pointer to soft context main structure           */
    972 /*              data(I)  - pointer to ioctl data                            */
    973 /*              cmd(I)   - ioctl command integer                            */
    974 /*              mode(I)  - file mode bits used with open                    */
    975 /*              uid(I)   - uid of calling process                           */
    976 /*              ctx(I)   - pointer used as key for finding context          */
    977 /*                                                                          */
    978 /* Processes an ioctl call made to operate on the IP Filter NAT device.     */
    979 /* ------------------------------------------------------------------------ */
    980 int
    981 ipf_nat_ioctl(ipf_main_softc_t *softc, void *data, ioctlcmd_t cmd, int mode,
    982    int uid, void *ctx)
    983 {
    984 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
    985 	int error = 0, ret, arg, getlock;
    986 	ipnat_t *nat, *nt, *n;
    987 	ipnat_t natd;
    988 	SPL_INT(s);
    989 
    990 #if BSD_GE_YEAR(199306) && defined(_KERNEL)
    991 # if NETBSD_GE_REV(399002000)
    992 	if ((mode & FWRITE) &&
    993 	     kauth_authorize_network(curlwp->l_cred, KAUTH_NETWORK_FIREWALL,
    994 				     KAUTH_REQ_NETWORK_FIREWALL_FW,
    995 				     NULL, NULL, NULL))
    996 # else
    997 #  if defined(__FreeBSD_version) && (__FreeBSD_version >= 500034)
    998 	if (securelevel_ge(curthread->td_ucred, 3) && (mode & FWRITE))
    999 #  else
   1000 	if ((securelevel >= 3) && (mode & FWRITE))
   1001 #  endif
   1002 # endif
   1003 	{
   1004 		IPFERROR(60001);
   1005 		return EPERM;
   1006 	}
   1007 #endif
   1008 
   1009 #if defined(__osf__) && defined(_KERNEL)
   1010 	getlock = 0;
   1011 #else
   1012 	getlock = (mode & NAT_LOCKHELD) ? 0 : 1;
   1013 #endif
   1014 
   1015 	n = NULL;
   1016 	nt = NULL;
   1017 	nat = NULL;
   1018 
   1019 	if ((cmd == (ioctlcmd_t)SIOCADNAT) || (cmd == (ioctlcmd_t)SIOCRMNAT) ||
   1020 	    (cmd == (ioctlcmd_t)SIOCPURGENAT)) {
   1021 		if (mode & NAT_SYSSPACE) {
   1022 			bcopy(data, (char *)&natd, sizeof(natd));
   1023 			nat = &natd;
   1024 			error = 0;
   1025 		} else {
   1026 			bzero(&natd, sizeof(natd));
   1027 			error = ipf_inobj(softc, data, NULL, &natd,
   1028 					  IPFOBJ_IPNAT);
   1029 			if (error != 0)
   1030 				goto done;
   1031 
   1032 			if (natd.in_size < sizeof(ipnat_t)) {
   1033 				error = EINVAL;
   1034 				goto done;
   1035 			}
   1036 			KMALLOCS(nt, ipnat_t *, natd.in_size);
   1037 			if (nt == NULL) {
   1038 				IPFERROR(60070);
   1039 				error = ENOMEM;
   1040 				goto done;
   1041 			}
   1042 			bzero(nt, natd.in_size);
   1043 			error = ipf_inobjsz(softc, data, nt, IPFOBJ_IPNAT,
   1044 					    natd.in_size);
   1045 			if (error)
   1046 				goto done;
   1047 			nat = nt;
   1048 		}
   1049 
   1050 		/*
   1051 		 * For add/delete, look to see if the NAT entry is
   1052 		 * already present
   1053 		 */
   1054 		nat->in_flags &= IPN_USERFLAGS;
   1055 		if ((nat->in_redir & NAT_MAPBLK) == 0) {
   1056 			if (nat->in_osrcatype == FRI_NORMAL ||
   1057 			    nat->in_osrcatype == FRI_NONE)
   1058 				nat->in_osrcaddr &= nat->in_osrcmsk;
   1059 			if (nat->in_odstatype == FRI_NORMAL ||
   1060 			    nat->in_odstatype == FRI_NONE)
   1061 				nat->in_odstaddr &= nat->in_odstmsk;
   1062 			if ((nat->in_flags & (IPN_SPLIT|IPN_SIPRANGE)) == 0) {
   1063 				if (nat->in_nsrcatype == FRI_NORMAL)
   1064 					nat->in_nsrcaddr &= nat->in_nsrcmsk;
   1065 				if (nat->in_ndstatype == FRI_NORMAL)
   1066 					nat->in_ndstaddr &= nat->in_ndstmsk;
   1067 			}
   1068 		}
   1069 
   1070 		error = ipf_nat_rule_init(softc, softn, nat);
   1071 		if (error != 0)
   1072 			goto done;
   1073 
   1074 		MUTEX_ENTER(&softn->ipf_nat_io);
   1075 		for (n = softn->ipf_nat_list; n != NULL; n = n->in_next)
   1076 			if (ipf_nat_cmp_rules(nat, n) == 0)
   1077 				break;
   1078 	}
   1079 
   1080 	switch (cmd)
   1081 	{
   1082 #ifdef  IPFILTER_LOG
   1083 	case SIOCIPFFB :
   1084 	{
   1085 		int tmp;
   1086 
   1087 		if (!(mode & FWRITE)) {
   1088 			IPFERROR(60002);
   1089 			error = EPERM;
   1090 		} else {
   1091 			tmp = ipf_log_clear(softc, IPL_LOGNAT);
   1092 			error = BCOPYOUT(&tmp, data, sizeof(tmp));
   1093 			if (error != 0) {
   1094 				IPFERROR(60057);
   1095 				error = EFAULT;
   1096 			}
   1097 		}
   1098 		break;
   1099 	}
   1100 
   1101 	case SIOCSETLG :
   1102 		if (!(mode & FWRITE)) {
   1103 			IPFERROR(60003);
   1104 			error = EPERM;
   1105 		} else {
   1106 			error = BCOPYIN(data, &softn->ipf_nat_logging,
   1107 					sizeof(softn->ipf_nat_logging));
   1108 			if (error != 0)
   1109 				error = EFAULT;
   1110 		}
   1111 		break;
   1112 
   1113 	case SIOCGETLG :
   1114 		error = BCOPYOUT(&softn->ipf_nat_logging, data,
   1115 				 sizeof(softn->ipf_nat_logging));
   1116 		if (error != 0) {
   1117 			IPFERROR(60004);
   1118 			error = EFAULT;
   1119 		}
   1120 		break;
   1121 
   1122 	case FIONREAD :
   1123 		arg = ipf_log_bytesused(softc, IPL_LOGNAT);
   1124 		error = BCOPYOUT(&arg, data, sizeof(arg));
   1125 		if (error != 0) {
   1126 			IPFERROR(60005);
   1127 			error = EFAULT;
   1128 		}
   1129 		break;
   1130 #endif
   1131 	case SIOCADNAT :
   1132 		if (!(mode & FWRITE)) {
   1133 			IPFERROR(60006);
   1134 			error = EPERM;
   1135 		} else if (n != NULL) {
   1136 			natd.in_flineno = n->in_flineno;
   1137 			(void) ipf_outobj(softc, data, &natd, IPFOBJ_IPNAT);
   1138 			IPFERROR(60007);
   1139 			error = EEXIST;
   1140 		} else if (nt == NULL) {
   1141 			IPFERROR(60008);
   1142 			error = ENOMEM;
   1143 		}
   1144 		if (error != 0) {
   1145 			MUTEX_EXIT(&softn->ipf_nat_io);
   1146 			break;
   1147 		}
   1148 		if (nat != nt)
   1149 			bcopy((char *)nat, (char *)nt, sizeof(*n));
   1150 		error = ipf_nat_siocaddnat(softc, softn, nt, getlock);
   1151 		MUTEX_EXIT(&softn->ipf_nat_io);
   1152 		if (error == 0) {
   1153 			nat = NULL;
   1154 			nt = NULL;
   1155 		}
   1156 		break;
   1157 
   1158 	case SIOCRMNAT :
   1159 	case SIOCPURGENAT :
   1160 		if (!(mode & FWRITE)) {
   1161 			IPFERROR(60009);
   1162 			error = EPERM;
   1163 			n = NULL;
   1164 		} else if (n == NULL) {
   1165 			IPFERROR(60010);
   1166 			error = ESRCH;
   1167 		}
   1168 
   1169 		if (error != 0) {
   1170 			MUTEX_EXIT(&softn->ipf_nat_io);
   1171 			break;
   1172 		}
   1173 		if (cmd == (ioctlcmd_t)SIOCPURGENAT) {
   1174 			error = ipf_outobjsz(softc, data, n, IPFOBJ_IPNAT,
   1175 					     n->in_size);
   1176 			if (error) {
   1177 				MUTEX_EXIT(&softn->ipf_nat_io);
   1178 				goto done;
   1179 			}
   1180 			n->in_flags |= IPN_PURGE;
   1181 		}
   1182 		ipf_nat_siocdelnat(softc, softn, n, getlock);
   1183 
   1184 		MUTEX_EXIT(&softn->ipf_nat_io);
   1185 		n = NULL;
   1186 		break;
   1187 
   1188 	case SIOCGNATS :
   1189 	    {
   1190 		natstat_t *nsp = &softn->ipf_nat_stats;
   1191 
   1192 		nsp->ns_side[0].ns_table = softn->ipf_nat_table[0];
   1193 		nsp->ns_side[1].ns_table = softn->ipf_nat_table[1];
   1194 		nsp->ns_list = softn->ipf_nat_list;
   1195 		nsp->ns_maptable = softn->ipf_hm_maptable;
   1196 		nsp->ns_maplist = softn->ipf_hm_maplist;
   1197 		nsp->ns_nattab_sz = softn->ipf_nat_table_sz;
   1198 		nsp->ns_nattab_max = softn->ipf_nat_table_max;
   1199 		nsp->ns_rultab_sz = softn->ipf_nat_maprules_sz;
   1200 		nsp->ns_rdrtab_sz = softn->ipf_nat_rdrrules_sz;
   1201 		nsp->ns_hostmap_sz = softn->ipf_nat_hostmap_sz;
   1202 		nsp->ns_instances = softn->ipf_nat_instances;
   1203 		nsp->ns_ticks = softc->ipf_ticks;
   1204 #ifdef IPFILTER_LOGGING
   1205 		nsp->ns_log_ok = ipf_log_logok(softc, IPF_LOGNAT);
   1206 		nsp->ns_log_fail = ipf_log_failures(softc, IPF_LOGNAT);
   1207 #else
   1208 		nsp->ns_log_ok = 0;
   1209 		nsp->ns_log_fail = 0;
   1210 #endif
   1211 		error = ipf_outobj(softc, data, nsp, IPFOBJ_NATSTAT);
   1212 		break;
   1213 	    }
   1214 
   1215 	case SIOCGNATL :
   1216 	    {
   1217 		natlookup_t nl;
   1218 
   1219 		error = ipf_inobj(softc, data, NULL, &nl, IPFOBJ_NATLOOKUP);
   1220 		if (error == 0) {
   1221 			void *ptr;
   1222 
   1223 			if (getlock) {
   1224 				READ_ENTER(&softc->ipf_nat);
   1225 			}
   1226 
   1227 			switch (nl.nl_v)
   1228 			{
   1229 			case 4 :
   1230 				ptr = ipf_nat_lookupredir(&nl);
   1231 				break;
   1232 #ifdef USE_INET6
   1233 			case 6 :
   1234 				ptr = ipf_nat6_lookupredir(&nl);
   1235 				break;
   1236 #endif
   1237 			default:
   1238 				ptr = NULL;
   1239 				break;
   1240 			}
   1241 
   1242 			if (getlock) {
   1243 				RWLOCK_EXIT(&softc->ipf_nat);
   1244 			}
   1245 			if (ptr != NULL) {
   1246 				error = ipf_outobj(softc, data, &nl,
   1247 						   IPFOBJ_NATLOOKUP);
   1248 			} else {
   1249 				IPFERROR(60011);
   1250 				error = ESRCH;
   1251 			}
   1252 		}
   1253 		break;
   1254 	    }
   1255 
   1256 	case SIOCIPFFL :	/* old SIOCFLNAT & SIOCCNATL */
   1257 		if (!(mode & FWRITE)) {
   1258 			IPFERROR(60012);
   1259 			error = EPERM;
   1260 			break;
   1261 		}
   1262 		if (getlock) {
   1263 			WRITE_ENTER(&softc->ipf_nat);
   1264 		}
   1265 
   1266 		error = BCOPYIN(data, &arg, sizeof(arg));
   1267 		if (error != 0) {
   1268 			IPFERROR(60013);
   1269 			error = EFAULT;
   1270 		} else {
   1271 			if (arg == 0)
   1272 				ret = ipf_nat_flushtable(softc, softn);
   1273 			else if (arg == 1)
   1274 				ret = ipf_nat_clearlist(softc, softn);
   1275 			else
   1276 				ret = ipf_nat_extraflush(softc, softn, arg);
   1277 			ipf_proxy_flush(softc->ipf_proxy_soft, arg);
   1278 		}
   1279 
   1280 		if (getlock) {
   1281 			RWLOCK_EXIT(&softc->ipf_nat);
   1282 		}
   1283 		if (error == 0) {
   1284 			error = BCOPYOUT(&ret, data, sizeof(ret));
   1285 		}
   1286 		break;
   1287 
   1288 	case SIOCMATCHFLUSH :
   1289 		if (!(mode & FWRITE)) {
   1290 			IPFERROR(60014);
   1291 			error = EPERM;
   1292 			break;
   1293 		}
   1294 		if (getlock) {
   1295 			WRITE_ENTER(&softc->ipf_nat);
   1296 		}
   1297 
   1298 		error = ipf_nat_matchflush(softc, softn, data);
   1299 
   1300 		if (getlock) {
   1301 			RWLOCK_EXIT(&softc->ipf_nat);
   1302 		}
   1303 		break;
   1304 
   1305 	case SIOCPROXY :
   1306 		error = ipf_proxy_ioctl(softc, data, cmd, mode, ctx);
   1307 		break;
   1308 
   1309 	case SIOCSTLCK :
   1310 		if (!(mode & FWRITE)) {
   1311 			IPFERROR(60015);
   1312 			error = EPERM;
   1313 		} else {
   1314 			error = ipf_lock(data, &softn->ipf_nat_lock);
   1315 		}
   1316 		break;
   1317 
   1318 	case SIOCSTPUT :
   1319 		if ((mode & FWRITE) != 0) {
   1320 			error = ipf_nat_putent(softc, data, getlock);
   1321 		} else {
   1322 			IPFERROR(60016);
   1323 			error = EACCES;
   1324 		}
   1325 		break;
   1326 
   1327 	case SIOCSTGSZ :
   1328 		if (softn->ipf_nat_lock) {
   1329 			error = ipf_nat_getsz(softc, data, getlock);
   1330 		} else {
   1331 			IPFERROR(60017);
   1332 			error = EACCES;
   1333 		}
   1334 		break;
   1335 
   1336 	case SIOCSTGET :
   1337 		if (softn->ipf_nat_lock) {
   1338 			error = ipf_nat_getent(softc, data, getlock);
   1339 		} else {
   1340 			IPFERROR(60018);
   1341 			error = EACCES;
   1342 		}
   1343 		break;
   1344 
   1345 	case SIOCGENITER :
   1346 	    {
   1347 		ipfgeniter_t iter;
   1348 		ipftoken_t *token;
   1349 		ipfobj_t obj;
   1350 
   1351 		error = ipf_inobj(softc, data, &obj, &iter, IPFOBJ_GENITER);
   1352 		if (error != 0)
   1353 			break;
   1354 
   1355 		SPL_SCHED(s);
   1356 		token = ipf_token_find(softc, iter.igi_type, uid, ctx);
   1357 		if (token != NULL) {
   1358 			error  = ipf_nat_iterator(softc, token, &iter, &obj);
   1359 			WRITE_ENTER(&softc->ipf_tokens);
   1360 			ipf_token_deref(softc, token);
   1361 			RWLOCK_EXIT(&softc->ipf_tokens);
   1362 		}
   1363 		SPL_X(s);
   1364 		break;
   1365 	    }
   1366 
   1367 	case SIOCIPFDELTOK :
   1368 		error = BCOPYIN(data, &arg, sizeof(arg));
   1369 		if (error == 0) {
   1370 			SPL_SCHED(s);
   1371 			error = ipf_token_del(softc, arg, uid, ctx);
   1372 			SPL_X(s);
   1373 		} else {
   1374 			IPFERROR(60019);
   1375 			error = EFAULT;
   1376 		}
   1377 		break;
   1378 
   1379 	case SIOCGTQTAB :
   1380 		error = ipf_outobj(softc, data, softn->ipf_nat_tcptq,
   1381 				   IPFOBJ_STATETQTAB);
   1382 		break;
   1383 
   1384 	case SIOCGTABL :
   1385 		error = ipf_nat_gettable(softc, softn, data);
   1386 		break;
   1387 
   1388 	default :
   1389 		IPFERROR(60020);
   1390 		error = EINVAL;
   1391 		break;
   1392 	}
   1393 done:
   1394 	if (nat != NULL)
   1395 		ipf_nat_rule_fini(softc, nat);
   1396 	if (nt != NULL)
   1397 		KFREES(nt, nt->in_size);
   1398 	return error;
   1399 }
   1400 
   1401 
   1402 /* ------------------------------------------------------------------------ */
   1403 /* Function:    ipf_nat_siocaddnat                                          */
   1404 /* Returns:     int - 0 == success, != 0 == failure                         */
   1405 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1406 /*              softn(I) - pointer to NAT context structure                 */
   1407 /*              n(I)       - pointer to new NAT rule                        */
   1408 /*              np(I)      - pointer to where to insert new NAT rule        */
   1409 /*              getlock(I) - flag indicating if lock on  is held            */
   1410 /* Mutex Locks: ipf_nat_io                                                  */
   1411 /*                                                                          */
   1412 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
   1413 /* from information passed to the kernel, then add it  to the appropriate   */
   1414 /* NAT rule table(s).                                                       */
   1415 /* ------------------------------------------------------------------------ */
   1416 static int
   1417 ipf_nat_siocaddnat(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, ipnat_t *n,
   1418 	int getlock)
   1419 {
   1420 	int error = 0;
   1421 
   1422 	if (ipf_nat_resolverule(softc, n) != 0) {
   1423 		IPFERROR(60022);
   1424 		return ENOENT;
   1425 	}
   1426 
   1427 	if ((n->in_age[0] == 0) && (n->in_age[1] != 0)) {
   1428 		IPFERROR(60023);
   1429 		return EINVAL;
   1430 	}
   1431 
   1432 	if (n->in_redir == (NAT_DIVERTUDP|NAT_MAP)) {
   1433 		/*
   1434 		 * Prerecord whether or not the destination of the divert
   1435 		 * is local or not to the interface the packet is going
   1436 		 * to be sent out.
   1437 		 */
   1438 		n->in_dlocal = ipf_deliverlocal(softc, n->in_v[1],
   1439 						n->in_ifps[1], &n->in_ndstip6);
   1440 	}
   1441 
   1442 	if (getlock) {
   1443 		WRITE_ENTER(&softc->ipf_nat);
   1444 	}
   1445 	n->in_next = NULL;
   1446 	n->in_pnext = softn->ipf_nat_list_tail;
   1447 	*n->in_pnext = n;
   1448 	softn->ipf_nat_list_tail = &n->in_next;
   1449 	n->in_use++;
   1450 
   1451 	if (n->in_redir & NAT_REDIRECT) {
   1452 		n->in_flags &= ~IPN_NOTDST;
   1453 		switch (n->in_v[0])
   1454 		{
   1455 		case 4 :
   1456 			ipf_nat_addrdr(softn, n);
   1457 			break;
   1458 #ifdef USE_INET6
   1459 		case 6 :
   1460 			ipf_nat6_addrdr(softn, n);
   1461 			break;
   1462 #endif
   1463 		default :
   1464 			break;
   1465 		}
   1466 		ATOMIC_INC32(softn->ipf_nat_stats.ns_rules_rdr);
   1467 	}
   1468 
   1469 	if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
   1470 		n->in_flags &= ~IPN_NOTSRC;
   1471 		switch (n->in_v[0])
   1472 		{
   1473 		case 4 :
   1474 			ipf_nat_addmap(softn, n);
   1475 			break;
   1476 #ifdef USE_INET6
   1477 		case 6 :
   1478 			ipf_nat6_addmap(softn, n);
   1479 			break;
   1480 #endif
   1481 		default :
   1482 			break;
   1483 		}
   1484 		ATOMIC_INC32(softn->ipf_nat_stats.ns_rules_map);
   1485 	}
   1486 
   1487 	if (n->in_age[0] != 0)
   1488 		n->in_tqehead[0] = ipf_addtimeoutqueue(softc,
   1489 						       &softn->ipf_nat_utqe,
   1490 						       n->in_age[0]);
   1491 
   1492 	if (n->in_age[1] != 0)
   1493 		n->in_tqehead[1] = ipf_addtimeoutqueue(softc,
   1494 						       &softn->ipf_nat_utqe,
   1495 						       n->in_age[1]);
   1496 
   1497 	MUTEX_INIT(&n->in_lock, "ipnat rule lock");
   1498 
   1499 	n = NULL;
   1500 	ATOMIC_INC32(softn->ipf_nat_stats.ns_rules);
   1501 #if SOLARIS && !defined(INSTANCES)
   1502 	pfil_delayed_copy = 0;
   1503 #endif
   1504 	if (getlock) {
   1505 		RWLOCK_EXIT(&softc->ipf_nat);			/* WRITE */
   1506 	}
   1507 
   1508 	return error;
   1509 }
   1510 
   1511 
   1512 /* ------------------------------------------------------------------------ */
   1513 /* Function:    ipf_nat_ruleaddrinit                                        */
   1514 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1515 /*              softn(I) - pointer to NAT context structure                 */
   1516 /*              n(I)     - pointer to NAT rule                              */
   1517 /*                                                                          */
   1518 /* Initialise all of the NAT address structures in a NAT rule.              */
   1519 /* ------------------------------------------------------------------------ */
   1520 static int
   1521 ipf_nat_ruleaddrinit(ipf_main_softc_t *softc, ipf_nat_softc_t *softn,
   1522     ipnat_t *n)
   1523 {
   1524 	int idx, error;
   1525 
   1526 	if ((n->in_ndst.na_atype == FRI_LOOKUP) &&
   1527 	    (n->in_ndst.na_type != IPLT_DSTLIST)) {
   1528 		IPFERROR(60071);
   1529 		return EINVAL;
   1530 	}
   1531 	if ((n->in_nsrc.na_atype == FRI_LOOKUP) &&
   1532 	    (n->in_nsrc.na_type != IPLT_DSTLIST)) {
   1533 		IPFERROR(60069);
   1534 		return EINVAL;
   1535 	}
   1536 
   1537 	if (n->in_redir == NAT_BIMAP) {
   1538 		n->in_ndstaddr = n->in_osrcaddr;
   1539 		n->in_ndstmsk = n->in_osrcmsk;
   1540 		n->in_odstaddr = n->in_nsrcaddr;
   1541 		n->in_odstmsk = n->in_nsrcmsk;
   1542 
   1543 	}
   1544 
   1545 	if (n->in_redir & NAT_REDIRECT)
   1546 		idx = 1;
   1547 	else
   1548 		idx = 0;
   1549 	/*
   1550 	 * Initialise all of the address fields.
   1551 	 */
   1552 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_osrc, 1,
   1553 				     n->in_ifps[idx]);
   1554 	if (error != 0)
   1555 		return error;
   1556 
   1557 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_odst, 1,
   1558 				     n->in_ifps[idx]);
   1559 	if (error != 0)
   1560 		return error;
   1561 
   1562 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_nsrc, 1,
   1563 				     n->in_ifps[idx]);
   1564 	if (error != 0)
   1565 		return error;
   1566 
   1567 	error = ipf_nat_nextaddrinit(softc, n->in_names, &n->in_ndst, 1,
   1568 				     n->in_ifps[idx]);
   1569 	if (error != 0)
   1570 		return error;
   1571 
   1572 	if (n->in_redir & NAT_DIVERTUDP)
   1573 		ipf_nat_builddivertmp(softn, n);
   1574 
   1575 	return 0;
   1576 }
   1577 
   1578 
   1579 /* ------------------------------------------------------------------------ */
   1580 /* Function:    ipf_nat_resolvrule                                          */
   1581 /* Returns:     Nil                                                         */
   1582 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1583 /*              n(I)     - pointer to NAT rule                              */
   1584 /*                                                                          */
   1585 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
   1586 /* from information passed to the kernel, then add it  to the appropriate   */
   1587 /* NAT rule table(s).                                                       */
   1588 /* ------------------------------------------------------------------------ */
   1589 static int
   1590 ipf_nat_resolverule(ipf_main_softc_t *softc, ipnat_t *n)
   1591 {
   1592 	char *base;
   1593 
   1594 	base = n->in_names;
   1595 
   1596 	n->in_ifps[0] = ipf_resolvenic(softc, base + n->in_ifnames[0],
   1597 				       n->in_v[0]);
   1598 
   1599 	if (n->in_ifnames[1] == -1) {
   1600 		n->in_ifnames[1] = n->in_ifnames[0];
   1601 		n->in_ifps[1] = n->in_ifps[0];
   1602 	} else {
   1603 		n->in_ifps[1] = ipf_resolvenic(softc, base + n->in_ifnames[1],
   1604 					       n->in_v[1]);
   1605 	}
   1606 
   1607 	if (n->in_plabel != -1) {
   1608 		if (n->in_redir & NAT_REDIRECT)
   1609 			n->in_apr = ipf_proxy_lookup(softc->ipf_proxy_soft,
   1610 						     n->in_pr[0],
   1611 						     base + n->in_plabel);
   1612 		else
   1613 			n->in_apr = ipf_proxy_lookup(softc->ipf_proxy_soft,
   1614 						     n->in_pr[1],
   1615 						     base + n->in_plabel);
   1616 		if (n->in_apr == NULL)
   1617 			return -1;
   1618 	}
   1619 	return 0;
   1620 }
   1621 
   1622 
   1623 /* ------------------------------------------------------------------------ */
   1624 /* Function:    ipf_nat_siocdelnat                                          */
   1625 /* Returns:     int - 0 == success, != 0 == failure                         */
   1626 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1627 /*              softn(I)   - pointer to NAT context structure               */
   1628 /*              n(I)       - pointer to new NAT rule                        */
   1629 /*              getlock(I) - flag indicating if lock on  is held            */
   1630 /* Mutex Locks: ipf_nat_io                                                  */
   1631 /*                                                                          */
   1632 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
   1633 /* from information passed to the kernel, then add it  to the appropriate   */
   1634 /* NAT rule table(s).                                                       */
   1635 /* ------------------------------------------------------------------------ */
   1636 static void
   1637 ipf_nat_siocdelnat(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, ipnat_t *n,
   1638 	int getlock)
   1639 {
   1640 #ifdef IPF_NAT6
   1641 	int i;
   1642 #endif
   1643 
   1644 	if (getlock) {
   1645 		WRITE_ENTER(&softc->ipf_nat);
   1646 	}
   1647 
   1648 	ipf_nat_delrule(softc, softn, n, 1);
   1649 
   1650 	if (getlock) {
   1651 		RWLOCK_EXIT(&softc->ipf_nat);			/* READ/WRITE */
   1652 	}
   1653 }
   1654 
   1655 
   1656 /* ------------------------------------------------------------------------ */
   1657 /* Function:    ipf_nat_getsz                                               */
   1658 /* Returns:     int - 0 == success, != 0 is the error value.                */
   1659 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1660 /*              data(I)    - pointer to natget structure with kernel        */
   1661 /*                           pointer get the size of.                       */
   1662 /*              getlock(I) - flag indicating whether or not the caller      */
   1663 /*                           holds a lock on ipf_nat                        */
   1664 /*                                                                          */
   1665 /* Handle SIOCSTGSZ.                                                        */
   1666 /* Return the size of the nat list entry to be copied back to user space.   */
   1667 /* The size of the entry is stored in the ng_sz field and the enture natget */
   1668 /* structure is copied back to the user.                                    */
   1669 /* ------------------------------------------------------------------------ */
   1670 static int
   1671 ipf_nat_getsz(ipf_main_softc_t *softc, void *data, int getlock)
   1672 {
   1673 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1674 	ap_session_t *aps;
   1675 	nat_t *nat, *n;
   1676 	natget_t ng;
   1677 	int error;
   1678 
   1679 	error = BCOPYIN(data, &ng, sizeof(ng));
   1680 	if (error != 0) {
   1681 		IPFERROR(60024);
   1682 		return EFAULT;
   1683 	}
   1684 
   1685 	if (getlock) {
   1686 		READ_ENTER(&softc->ipf_nat);
   1687 	}
   1688 
   1689 	nat = ng.ng_ptr;
   1690 	if (!nat) {
   1691 		nat = softn->ipf_nat_instances;
   1692 		ng.ng_sz = 0;
   1693 		/*
   1694 		 * Empty list so the size returned is 0.  Simple.
   1695 		 */
   1696 		if (nat == NULL) {
   1697 			if (getlock) {
   1698 				RWLOCK_EXIT(&softc->ipf_nat);
   1699 			}
   1700 			error = BCOPYOUT(&ng, data, sizeof(ng));
   1701 			if (error != 0) {
   1702 				IPFERROR(60025);
   1703 				return EFAULT;
   1704 			}
   1705 			return 0;
   1706 		}
   1707 	} else {
   1708 		/*
   1709 		 * Make sure the pointer we're copying from exists in the
   1710 		 * current list of entries.  Security precaution to prevent
   1711 		 * copying of random kernel data.
   1712 		 */
   1713 		for (n = softn->ipf_nat_instances; n; n = n->nat_next)
   1714 			if (n == nat)
   1715 				break;
   1716 		if (n == NULL) {
   1717 			if (getlock) {
   1718 				RWLOCK_EXIT(&softc->ipf_nat);
   1719 			}
   1720 			IPFERROR(60026);
   1721 			return ESRCH;
   1722 		}
   1723 	}
   1724 
   1725 	/*
   1726 	 * Incluse any space required for proxy data structures.
   1727 	 */
   1728 	ng.ng_sz = sizeof(nat_save_t);
   1729 	aps = nat->nat_aps;
   1730 	if (aps != NULL) {
   1731 		ng.ng_sz += sizeof(ap_session_t) - 4;
   1732 		if (aps->aps_data != 0)
   1733 			ng.ng_sz += aps->aps_psiz;
   1734 	}
   1735 	if (getlock) {
   1736 		RWLOCK_EXIT(&softc->ipf_nat);
   1737 	}
   1738 
   1739 	error = BCOPYOUT(&ng, data, sizeof(ng));
   1740 	if (error != 0) {
   1741 		IPFERROR(60027);
   1742 		return EFAULT;
   1743 	}
   1744 	return 0;
   1745 }
   1746 
   1747 
   1748 /* ------------------------------------------------------------------------ */
   1749 /* Function:    ipf_nat_getent                                              */
   1750 /* Returns:     int - 0 == success, != 0 is the error value.                */
   1751 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1752 /*              data(I)    - pointer to natget structure with kernel pointer*/
   1753 /*                           to NAT structure to copy out.                  */
   1754 /*              getlock(I) - flag indicating whether or not the caller      */
   1755 /*                           holds a lock on ipf_nat                        */
   1756 /*                                                                          */
   1757 /* Handle SIOCSTGET.                                                        */
   1758 /* Copies out NAT entry to user space.  Any additional data held for a      */
   1759 /* proxy is also copied, as to is the NAT rule which was responsible for it */
   1760 /* ------------------------------------------------------------------------ */
   1761 static int
   1762 ipf_nat_getent(ipf_main_softc_t *softc, void *data, int getlock)
   1763 {
   1764 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1765 	int error, outsize;
   1766 	ap_session_t *aps;
   1767 	nat_save_t *ipn, ipns;
   1768 	nat_t *n, *nat;
   1769 
   1770 	error = ipf_inobj(softc, data, NULL, &ipns, IPFOBJ_NATSAVE);
   1771 	if (error != 0)
   1772 		return error;
   1773 
   1774 	if ((ipns.ipn_dsize < sizeof(ipns)) || (ipns.ipn_dsize > 81920)) {
   1775 		IPFERROR(60028);
   1776 		return EINVAL;
   1777 	}
   1778 
   1779 	KMALLOCS(ipn, nat_save_t *, ipns.ipn_dsize);
   1780 	if (ipn == NULL) {
   1781 		IPFERROR(60029);
   1782 		return ENOMEM;
   1783 	}
   1784 
   1785 	if (getlock) {
   1786 		READ_ENTER(&softc->ipf_nat);
   1787 	}
   1788 
   1789 	ipn->ipn_dsize = ipns.ipn_dsize;
   1790 	nat = ipns.ipn_next;
   1791 	if (nat == NULL) {
   1792 		nat = softn->ipf_nat_instances;
   1793 		if (nat == NULL) {
   1794 			if (softn->ipf_nat_instances == NULL) {
   1795 				IPFERROR(60030);
   1796 				error = ENOENT;
   1797 			}
   1798 			goto finished;
   1799 		}
   1800 	} else {
   1801 		/*
   1802 		 * Make sure the pointer we're copying from exists in the
   1803 		 * current list of entries.  Security precaution to prevent
   1804 		 * copying of random kernel data.
   1805 		 */
   1806 		for (n = softn->ipf_nat_instances; n; n = n->nat_next)
   1807 			if (n == nat)
   1808 				break;
   1809 		if (n == NULL) {
   1810 			IPFERROR(60031);
   1811 			error = ESRCH;
   1812 			goto finished;
   1813 		}
   1814 	}
   1815 	ipn->ipn_next = nat->nat_next;
   1816 
   1817 	/*
   1818 	 * Copy the NAT structure.
   1819 	 */
   1820 	bcopy((char *)nat, &ipn->ipn_nat, sizeof(*nat));
   1821 
   1822 	/*
   1823 	 * If we have a pointer to the NAT rule it belongs to, save that too.
   1824 	 */
   1825 	if (nat->nat_ptr != NULL)
   1826 		bcopy((char *)nat->nat_ptr, (char *)&ipn->ipn_ipnat,
   1827 		      ipn->ipn_ipnat.in_size);
   1828 
   1829 	/*
   1830 	 * If we also know the NAT entry has an associated filter rule,
   1831 	 * save that too.
   1832 	 */
   1833 	if (nat->nat_fr != NULL)
   1834 		bcopy((char *)nat->nat_fr, (char *)&ipn->ipn_fr,
   1835 		      sizeof(ipn->ipn_fr));
   1836 
   1837 	/*
   1838 	 * Last but not least, if there is an application proxy session set
   1839 	 * up for this NAT entry, then copy that out too, including any
   1840 	 * private data saved along side it by the proxy.
   1841 	 */
   1842 	aps = nat->nat_aps;
   1843 	outsize = ipn->ipn_dsize - sizeof(*ipn) + sizeof(ipn->ipn_data);
   1844 	if (aps != NULL) {
   1845 		char *s;
   1846 
   1847 		if (outsize < sizeof(*aps)) {
   1848 			IPFERROR(60032);
   1849 			error = ENOBUFS;
   1850 			goto finished;
   1851 		}
   1852 
   1853 		s = ipn->ipn_data;
   1854 		bcopy((char *)aps, s, sizeof(*aps));
   1855 		s += sizeof(*aps);
   1856 		outsize -= sizeof(*aps);
   1857 		if ((aps->aps_data != NULL) && (outsize >= aps->aps_psiz))
   1858 			bcopy(aps->aps_data, s, aps->aps_psiz);
   1859 		else {
   1860 			IPFERROR(60033);
   1861 			error = ENOBUFS;
   1862 		}
   1863 	}
   1864 	if (error == 0) {
   1865 		if (getlock) {
   1866 			READ_ENTER(&softc->ipf_nat);
   1867 			getlock = 0;
   1868 		}
   1869 		error = ipf_outobjsz(softc, data, ipn, IPFOBJ_NATSAVE,
   1870 				     ipns.ipn_dsize);
   1871 	}
   1872 
   1873 finished:
   1874 	if (getlock) {
   1875 		READ_ENTER(&softc->ipf_nat);
   1876 	}
   1877 	if (ipn != NULL) {
   1878 		KFREES(ipn, ipns.ipn_dsize);
   1879 	}
   1880 	return error;
   1881 }
   1882 
   1883 
   1884 /* ------------------------------------------------------------------------ */
   1885 /* Function:    ipf_nat_putent                                              */
   1886 /* Returns:     int - 0 == success, != 0 is the error value.                */
   1887 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   1888 /*              data(I)    - pointer to natget structure with NAT           */
   1889 /*                           structure information to load into the kernel  */
   1890 /*              getlock(I) - flag indicating whether or not a write lock    */
   1891 /*                           on is already held.                            */
   1892 /*                                                                          */
   1893 /* Handle SIOCSTPUT.                                                        */
   1894 /* Loads a NAT table entry from user space, including a NAT rule, proxy and */
   1895 /* firewall rule data structures, if pointers to them indicate so.          */
   1896 /* ------------------------------------------------------------------------ */
   1897 static int
   1898 ipf_nat_putent(ipf_main_softc_t *softc, void *data, int getlock)
   1899 {
   1900 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1901 	nat_save_t *ipn, *ipnn;
   1902 	ap_session_t *aps;
   1903 	nat_t *n, *nat;
   1904 	frentry_t *fr;
   1905 	fr_info_t *fin;
   1906 	ipnat_t *in;
   1907 	int error;
   1908 
   1909 	KMALLOC(ipn, nat_save_t *);
   1910 	if (ipn == NULL)
   1911 		return ENOMEM;
   1912 	error = ipf_inobj(softc, data, NULL, ipn, IPFOBJ_NATSAVE);
   1913 	if (error != 0)
   1914 		return error;
   1915 
   1916 	/*
   1917 	 * Initialise early because of code at junkput label.
   1918 	 */
   1919 	n = NULL;
   1920 	in = NULL;
   1921 	aps = NULL;
   1922 	nat = NULL;
   1923 	ipnn = NULL;
   1924 	fin = NULL;
   1925 	fr = NULL;
   1926 
   1927 	/*
   1928 	 * New entry, copy in the rest of the NAT entry if it's size is more
   1929 	 * than just the nat_t structure.
   1930 	 */
   1931 	if (ipn->ipn_dsize > sizeof(*ipn)) {
   1932 		if (ipn->ipn_dsize > 81920) {
   1933 			IPFERROR(60034);
   1934 			error = ENOMEM;
   1935 			goto junkput;
   1936 		}
   1937 
   1938 		KMALLOCS(ipnn, nat_save_t *, ipn->ipn_dsize);
   1939 		if (ipnn == NULL) {
   1940 			IPFERROR(60035);
   1941 			return ENOMEM;
   1942 		}
   1943 
   1944 		bzero(ipnn, ipn->ipn_dsize);
   1945 		error = ipf_inobjsz(softc, data, ipnn, IPFOBJ_NATSAVE,
   1946 				    ipn->ipn_dsize);
   1947 		if (error != 0) {
   1948 			goto junkput;
   1949 		}
   1950 	} else
   1951 		ipnn = ipn;
   1952 
   1953 	KMALLOC(nat, nat_t *);
   1954 	if (nat == NULL) {
   1955 		IPFERROR(60037);
   1956 		error = ENOMEM;
   1957 		goto junkput;
   1958 	}
   1959 
   1960 	bcopy((char *)&ipnn->ipn_nat, (char *)nat, sizeof(*nat));
   1961 
   1962 	switch (nat->nat_v[0])
   1963 	{
   1964 	case 4:
   1965 #ifdef USE_IENT6
   1966 	case 6 :
   1967 #endif
   1968 		break;
   1969 	default :
   1970 		IPFERROR(60061);
   1971 		error = EPROTONOSUPPORT;
   1972 		goto junkput;
   1973 		/*NOTREACHED*/
   1974 	}
   1975 
   1976 	/*
   1977 	 * Initialize all these so that ipf_nat_delete() doesn't cause a crash.
   1978 	 */
   1979 	bzero((char *)nat, offsetof(struct nat, nat_tqe));
   1980 	nat->nat_tqe.tqe_pnext = NULL;
   1981 	nat->nat_tqe.tqe_next = NULL;
   1982 	nat->nat_tqe.tqe_ifq = NULL;
   1983 	nat->nat_tqe.tqe_parent = nat;
   1984 
   1985 	/*
   1986 	 * Restore the rule associated with this nat session
   1987 	 */
   1988 	in = ipnn->ipn_nat.nat_ptr;
   1989 	if (in != NULL) {
   1990 		KMALLOCS(in, ipnat_t *, ipnn->ipn_ipnat.in_size);
   1991 		nat->nat_ptr = in;
   1992 		if (in == NULL) {
   1993 			IPFERROR(60038);
   1994 			error = ENOMEM;
   1995 			goto junkput;
   1996 		}
   1997 		bcopy((char *)&ipnn->ipn_ipnat, (char *)in,
   1998 		      ipnn->ipn_ipnat.in_size);
   1999 		in->in_use = 1;
   2000 		in->in_flags |= IPN_DELETE;
   2001 
   2002 		ATOMIC_INC32(softn->ipf_nat_stats.ns_rules);
   2003 
   2004 		if (ipf_nat_resolverule(softc, in) != 0) {
   2005 			IPFERROR(60039);
   2006 			error = ESRCH;
   2007 			goto junkput;
   2008 		}
   2009 	}
   2010 
   2011 	/*
   2012 	 * Check that the NAT entry doesn't already exist in the kernel.
   2013 	 *
   2014 	 * For NAT_OUTBOUND, we're lookup for a duplicate MAP entry.  To do
   2015 	 * this, we check to see if the inbound combination of addresses and
   2016 	 * ports is already known.  Similar logic is applied for NAT_INBOUND.
   2017 	 *
   2018 	 */
   2019 	KMALLOC(fin, fr_info_t *);
   2020 	if (fin == NULL) {
   2021 		error = ENOMEM;
   2022 		goto junkput;
   2023 	}
   2024 	bzero(fin, sizeof(*fin));
   2025 	fin->fin_v = nat->nat_v[0];
   2026 	fin->fin_p = nat->nat_pr[0];
   2027 	fin->fin_rev = nat->nat_rev;
   2028 	fin->fin_ifp = nat->nat_ifps[0];
   2029 	fin->fin_data[0] = ntohs(nat->nat_ndport);
   2030 	fin->fin_data[1] = ntohs(nat->nat_nsport);
   2031 
   2032 	switch (nat->nat_dir)
   2033 	{
   2034 	case NAT_OUTBOUND :
   2035 	case NAT_DIVERTOUT :
   2036 		if (getlock) {
   2037 			READ_ENTER(&softc->ipf_nat);
   2038 		}
   2039 
   2040 		fin->fin_v = nat->nat_v[1];
   2041 		if (nat->nat_v[1] == 4) {
   2042 			n = ipf_nat_inlookup(fin, nat->nat_flags, fin->fin_p,
   2043 					     nat->nat_ndstip, nat->nat_nsrcip);
   2044 #ifdef USE_INET6
   2045 		} else if (nat->nat_v[1] == 6) {
   2046 			n = ipf_nat6_inlookup(fin, nat->nat_flags, fin->fin_p,
   2047 					      &nat->nat_ndst6.in6,
   2048 					      &nat->nat_nsrc6.in6);
   2049 #endif
   2050 		}
   2051 
   2052 		if (getlock) {
   2053 			RWLOCK_EXIT(&softc->ipf_nat);
   2054 		}
   2055 		if (n != NULL) {
   2056 			IPFERROR(60040);
   2057 			error = EEXIST;
   2058 			goto junkput;
   2059 		}
   2060 		break;
   2061 
   2062 	case NAT_INBOUND :
   2063 	case NAT_DIVERTIN :
   2064 		if (getlock) {
   2065 			READ_ENTER(&softc->ipf_nat);
   2066 		}
   2067 
   2068 		if (fin->fin_v == 4) {
   2069 			n = ipf_nat_outlookup(fin, nat->nat_flags, fin->fin_p,
   2070 					      nat->nat_ndstip,
   2071 					      nat->nat_nsrcip);
   2072 #ifdef USE_INET6
   2073 		} else if (fin->fin_v == 6) {
   2074 			n = ipf_nat6_outlookup(fin, nat->nat_flags, fin->fin_p,
   2075 					       &nat->nat_ndst6.in6,
   2076 					       &nat->nat_nsrc6.in6);
   2077 #endif
   2078 		}
   2079 
   2080 		if (getlock) {
   2081 			RWLOCK_EXIT(&softc->ipf_nat);
   2082 		}
   2083 		if (n != NULL) {
   2084 			IPFERROR(60041);
   2085 			error = EEXIST;
   2086 			goto junkput;
   2087 		}
   2088 		break;
   2089 
   2090 	default :
   2091 		IPFERROR(60042);
   2092 		error = EINVAL;
   2093 		goto junkput;
   2094 	}
   2095 
   2096 	/*
   2097 	 * Restore ap_session_t structure.  Include the private data allocated
   2098 	 * if it was there.
   2099 	 */
   2100 	aps = nat->nat_aps;
   2101 	if (aps != NULL) {
   2102 		KMALLOC(aps, ap_session_t *);
   2103 		nat->nat_aps = aps;
   2104 		if (aps == NULL) {
   2105 			IPFERROR(60043);
   2106 			error = ENOMEM;
   2107 			goto junkput;
   2108 		}
   2109 		bcopy(ipnn->ipn_data, (char *)aps, sizeof(*aps));
   2110 		if (in != NULL)
   2111 			aps->aps_apr = in->in_apr;
   2112 		else
   2113 			aps->aps_apr = NULL;
   2114 		if (aps->aps_psiz != 0) {
   2115 			if (aps->aps_psiz > 81920) {
   2116 				IPFERROR(60044);
   2117 				error = ENOMEM;
   2118 				goto junkput;
   2119 			}
   2120 			KMALLOCS(aps->aps_data, void *, aps->aps_psiz);
   2121 			if (aps->aps_data == NULL) {
   2122 				IPFERROR(60045);
   2123 				error = ENOMEM;
   2124 				goto junkput;
   2125 			}
   2126 			bcopy(ipnn->ipn_data + sizeof(*aps), aps->aps_data,
   2127 			      aps->aps_psiz);
   2128 		} else {
   2129 			aps->aps_psiz = 0;
   2130 			aps->aps_data = NULL;
   2131 		}
   2132 	}
   2133 
   2134 	/*
   2135 	 * If there was a filtering rule associated with this entry then
   2136 	 * build up a new one.
   2137 	 */
   2138 	fr = nat->nat_fr;
   2139 	if (fr != NULL) {
   2140 		if ((nat->nat_flags & SI_NEWFR) != 0) {
   2141 			KMALLOC(fr, frentry_t *);
   2142 			nat->nat_fr = fr;
   2143 			if (fr == NULL) {
   2144 				IPFERROR(60046);
   2145 				error = ENOMEM;
   2146 				goto junkput;
   2147 			}
   2148 			ipnn->ipn_nat.nat_fr = fr;
   2149 			fr->fr_ref = 1;
   2150 			(void) ipf_outobj(softc, data, ipnn, IPFOBJ_NATSAVE);
   2151 			bcopy((char *)&ipnn->ipn_fr, (char *)fr, sizeof(*fr));
   2152 
   2153 			fr->fr_ref = 1;
   2154 			fr->fr_dsize = 0;
   2155 			fr->fr_data = NULL;
   2156 			fr->fr_type = FR_T_NONE;
   2157 
   2158 			MUTEX_NUKE(&fr->fr_lock);
   2159 			MUTEX_INIT(&fr->fr_lock, "nat-filter rule lock");
   2160 		} else {
   2161 			if (getlock) {
   2162 				READ_ENTER(&softc->ipf_nat);
   2163 			}
   2164 			for (n = softn->ipf_nat_instances; n; n = n->nat_next)
   2165 				if (n->nat_fr == fr)
   2166 					break;
   2167 
   2168 			if (n != NULL) {
   2169 				MUTEX_ENTER(&fr->fr_lock);
   2170 				fr->fr_ref++;
   2171 				MUTEX_EXIT(&fr->fr_lock);
   2172 			}
   2173 			if (getlock) {
   2174 				RWLOCK_EXIT(&softc->ipf_nat);
   2175 			}
   2176 
   2177 			if (n == NULL) {
   2178 				IPFERROR(60047);
   2179 				error = ESRCH;
   2180 				goto junkput;
   2181 			}
   2182 		}
   2183 	}
   2184 
   2185 	if (ipnn != ipn) {
   2186 		KFREES(ipnn, ipn->ipn_dsize);
   2187 		ipnn = NULL;
   2188 	}
   2189 
   2190 	if (getlock) {
   2191 		WRITE_ENTER(&softc->ipf_nat);
   2192 	}
   2193 
   2194 	if (fin->fin_v == 4)
   2195 		error = ipf_nat_finalise(fin, nat);
   2196 #ifdef USE_INET6
   2197 	else
   2198 		error = ipf_nat6_finalise(fin, nat);
   2199 #endif
   2200 
   2201 	if (getlock) {
   2202 		RWLOCK_EXIT(&softc->ipf_nat);
   2203 	}
   2204 
   2205 	if (error == 0)
   2206 		return 0;
   2207 
   2208 	IPFERROR(60048);
   2209 	error = ENOMEM;
   2210 
   2211 junkput:
   2212 	if (fin != NULL)
   2213 		KFREE(fin);
   2214 	if (fr != NULL) {
   2215 		(void) ipf_derefrule(softc, &fr);
   2216 	}
   2217 
   2218 	if ((ipnn != NULL) && (ipnn != ipn)) {
   2219 		KFREES(ipnn, ipn->ipn_dsize);
   2220 	}
   2221 	if (ipn != NULL)
   2222 		KFREE(ipn);
   2223 	if (nat != NULL) {
   2224 		if (aps != NULL) {
   2225 			if (aps->aps_data != NULL) {
   2226 				KFREES(aps->aps_data, aps->aps_psiz);
   2227 			}
   2228 			KFREE(aps);
   2229 		}
   2230 		if (in != NULL) {
   2231 			if (in->in_apr)
   2232 				ipf_proxy_deref(in->in_apr);
   2233 			KFREES(in, in->in_size);
   2234 		}
   2235 		KFREE(nat);
   2236 	}
   2237 	return error;
   2238 }
   2239 
   2240 
   2241 /* ------------------------------------------------------------------------ */
   2242 /* Function:    ipf_nat_delete                                              */
   2243 /* Returns:     Nil                                                         */
   2244 /* Parameters:  softc(I)   - pointer to soft context main structure         */
   2245 /*              nat(I)     - pointer to NAT structure to delete             */
   2246 /*              logtype(I) - type of LOG record to create before deleting   */
   2247 /* Write Lock:  ipf_nat                                                     */
   2248 /*                                                                          */
   2249 /* Delete a nat entry from the various lists and table.  If NAT logging is  */
   2250 /* enabled then generate a NAT log record for this event.                   */
   2251 /* ------------------------------------------------------------------------ */
   2252 void
   2253 ipf_nat_delete(ipf_main_softc_t *softc, struct nat *nat, int logtype)
   2254 {
   2255 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2256 	int madeorphan = 0, bkt, removed = 0;
   2257 	nat_stat_side_t *nss;
   2258 	struct ipnat *ipn;
   2259 
   2260 	if (logtype != 0 && softn->ipf_nat_logging != 0)
   2261 		ipf_nat_log(softc, softn, nat, logtype);
   2262 
   2263 	/*
   2264 	 * Take it as a general indication that all the pointers are set if
   2265 	 * nat_pnext is set.
   2266 	 */
   2267 	if (nat->nat_pnext != NULL) {
   2268 		removed = 1;
   2269 
   2270 		bkt = nat->nat_hv[0] % softn->ipf_nat_table_sz;
   2271 		nss = &softn->ipf_nat_stats.ns_side[0];
   2272 		nss->ns_bucketlen[bkt]--;
   2273 		if (nss->ns_bucketlen[bkt] == 0) {
   2274 			nss->ns_inuse--;
   2275 		}
   2276 
   2277 		bkt = nat->nat_hv[1] % softn->ipf_nat_table_sz;
   2278 		nss = &softn->ipf_nat_stats.ns_side[1];
   2279 		nss->ns_bucketlen[bkt]--;
   2280 		if (nss->ns_bucketlen[bkt] == 0) {
   2281 			nss->ns_inuse--;
   2282 		}
   2283 
   2284 		*nat->nat_pnext = nat->nat_next;
   2285 		if (nat->nat_next != NULL) {
   2286 			nat->nat_next->nat_pnext = nat->nat_pnext;
   2287 			nat->nat_next = NULL;
   2288 		}
   2289 		nat->nat_pnext = NULL;
   2290 
   2291 		*nat->nat_phnext[0] = nat->nat_hnext[0];
   2292 		if (nat->nat_hnext[0] != NULL) {
   2293 			nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
   2294 			nat->nat_hnext[0] = NULL;
   2295 		}
   2296 		nat->nat_phnext[0] = NULL;
   2297 
   2298 		*nat->nat_phnext[1] = nat->nat_hnext[1];
   2299 		if (nat->nat_hnext[1] != NULL) {
   2300 			nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
   2301 			nat->nat_hnext[1] = NULL;
   2302 		}
   2303 		nat->nat_phnext[1] = NULL;
   2304 
   2305 		if ((nat->nat_flags & SI_WILDP) != 0) {
   2306 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_wilds);
   2307 		}
   2308 		madeorphan = 1;
   2309 	}
   2310 
   2311 	if (nat->nat_me != NULL) {
   2312 		*nat->nat_me = NULL;
   2313 		nat->nat_me = NULL;
   2314 		nat->nat_ref--;
   2315 		ASSERT(nat->nat_ref >= 0);
   2316 	}
   2317 
   2318 	if (nat->nat_tqe.tqe_ifq != NULL) {
   2319 		/*
   2320 		 * No call to ipf_freetimeoutqueue() is made here, they are
   2321 		 * garbage collected in ipf_nat_expire().
   2322 		 */
   2323 		(void) ipf_deletequeueentry(&nat->nat_tqe);
   2324 	}
   2325 
   2326 	if (nat->nat_sync) {
   2327 		ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
   2328 		nat->nat_sync = NULL;
   2329 	}
   2330 
   2331 	if (logtype == NL_EXPIRE)
   2332 		softn->ipf_nat_stats.ns_expire++;
   2333 
   2334 	MUTEX_ENTER(&nat->nat_lock);
   2335 	/*
   2336 	 * NL_DESTROY should only be passed in when we've got nat_ref >= 2.
   2337 	 * This happens when a nat'd packet is blocked and we want to throw
   2338 	 * away the NAT session.
   2339 	 */
   2340 	if (logtype == NL_DESTROY) {
   2341 		if (nat->nat_ref > 2) {
   2342 			nat->nat_ref -= 2;
   2343 			MUTEX_EXIT(&nat->nat_lock);
   2344 			if (removed)
   2345 				softn->ipf_nat_stats.ns_orphans++;
   2346 			return;
   2347 		}
   2348 	} else if (nat->nat_ref > 1) {
   2349 		nat->nat_ref--;
   2350 		MUTEX_EXIT(&nat->nat_lock);
   2351 		if (madeorphan == 1)
   2352 			softn->ipf_nat_stats.ns_orphans++;
   2353 		return;
   2354 	}
   2355 	ASSERT(nat->nat_ref >= 0);
   2356 	MUTEX_EXIT(&nat->nat_lock);
   2357 
   2358 	nat->nat_ref = 0;
   2359 
   2360 	if (madeorphan == 0)
   2361 		softn->ipf_nat_stats.ns_orphans--;
   2362 
   2363 	/*
   2364 	 * At this point, nat_ref can be either 0 or -1
   2365 	 */
   2366 	softn->ipf_nat_stats.ns_proto[nat->nat_pr[0]]--;
   2367 
   2368 	if (nat->nat_fr != NULL) {
   2369 		(void) ipf_derefrule(softc, &nat->nat_fr);
   2370 	}
   2371 
   2372 	if (nat->nat_hm != NULL) {
   2373 		ipf_nat_hostmapdel(softc, &nat->nat_hm);
   2374 	}
   2375 
   2376 	/*
   2377 	 * If there is an active reference from the nat entry to its parent
   2378 	 * rule, decrement the rule's reference count and free it too if no
   2379 	 * longer being used.
   2380 	 */
   2381 	ipn = nat->nat_ptr;
   2382 	nat->nat_ptr = NULL;
   2383 
   2384 	if (ipn != NULL) {
   2385 		ipn->in_space++;
   2386 		ipf_nat_rule_deref(softc, &ipn);
   2387 	}
   2388 
   2389 	if (nat->nat_aps != NULL) {
   2390 		ipf_proxy_free(softc, nat->nat_aps);
   2391 		nat->nat_aps = NULL;
   2392 	}
   2393 
   2394 	MUTEX_DESTROY(&nat->nat_lock);
   2395 
   2396 	softn->ipf_nat_stats.ns_active--;
   2397 
   2398 	/*
   2399 	 * If there's a fragment table entry too for this nat entry, then
   2400 	 * dereference that as well.  This is after nat_lock is released
   2401 	 * because of Tru64.
   2402 	 */
   2403 	ipf_frag_natforget(softc, (void *)nat);
   2404 
   2405 	KFREE(nat);
   2406 }
   2407 
   2408 
   2409 /* ------------------------------------------------------------------------ */
   2410 /* Function:    ipf_nat_flushtable                                          */
   2411 /* Returns:     int - number of NAT rules deleted                           */
   2412 /* Parameters:  softc(I) - pointer to soft context main structure           */
   2413 /*              softn(I) - pointer to NAT context structure                 */
   2414 /* Write Lock:  ipf_nat                                                     */
   2415 /*                                                                          */
   2416 /* Deletes all currently active NAT sessions.  In deleting each NAT entry a */
   2417 /* log record should be emitted in ipf_nat_delete() if NAT logging is       */
   2418 /* enabled.                                                                 */
   2419 /* ------------------------------------------------------------------------ */
   2420 /*
   2421  * nat_flushtable - clear the NAT table of all mapping entries.
   2422  */
   2423 static int
   2424 ipf_nat_flushtable(ipf_main_softc_t *softc, ipf_nat_softc_t *softn)
   2425 {
   2426 	nat_t *nat;
   2427 	int j = 0;
   2428 
   2429 	/*
   2430 	 * ALL NAT mappings deleted, so lets just make the deletions
   2431 	 * quicker.
   2432 	 */
   2433 	if (softn->ipf_nat_table[0] != NULL)
   2434 		bzero((char *)softn->ipf_nat_table[0],
   2435 		      sizeof(softn->ipf_nat_table[0]) *
   2436 		      softn->ipf_nat_table_sz);
   2437 	if (softn->ipf_nat_table[1] != NULL)
   2438 		bzero((char *)softn->ipf_nat_table[1],
   2439 		      sizeof(softn->ipf_nat_table[1]) *
   2440 		      softn->ipf_nat_table_sz);
   2441 
   2442 	while ((nat = softn->ipf_nat_instances) != NULL) {
   2443 		ipf_nat_delete(softc, nat, NL_FLUSH);
   2444 		j++;
   2445 	}
   2446 
   2447 	return j;
   2448 }
   2449 
   2450 
   2451 /* ------------------------------------------------------------------------ */
   2452 /* Function:    ipf_nat_clearlist                                           */
   2453 /* Returns:     int - number of NAT/RDR rules deleted                       */
   2454 /* Parameters:  softc(I) - pointer to soft context main structure           */
   2455 /*              softn(I) - pointer to NAT context structure                 */
   2456 /*                                                                          */
   2457 /* Delete all rules in the current list of rules.  There is nothing elegant */
   2458 /* about this cleanup: simply free all entries on the list of rules and     */
   2459 /* clear out the tables used for hashed NAT rule lookups.                   */
   2460 /* ------------------------------------------------------------------------ */
   2461 static int
   2462 ipf_nat_clearlist(ipf_main_softc_t *softc, ipf_nat_softc_t *softn)
   2463 {
   2464 	ipnat_t *n;
   2465 	int i = 0;
   2466 
   2467 	if (softn->ipf_nat_map_rules != NULL) {
   2468 		bzero((char *)softn->ipf_nat_map_rules,
   2469 		      sizeof(*softn->ipf_nat_map_rules) *
   2470 		      softn->ipf_nat_maprules_sz);
   2471 	}
   2472 	if (softn->ipf_nat_rdr_rules != NULL) {
   2473 		bzero((char *)softn->ipf_nat_rdr_rules,
   2474 		      sizeof(*softn->ipf_nat_rdr_rules) *
   2475 		      softn->ipf_nat_rdrrules_sz);
   2476 	}
   2477 
   2478 	while ((n = softn->ipf_nat_list) != NULL) {
   2479 		ipf_nat_delrule(softc, softn, n, 0);
   2480 		i++;
   2481 	}
   2482 #if SOLARIS && !defined(INSTANCES)
   2483 	pfil_delayed_copy = 1;
   2484 #endif
   2485 	return i;
   2486 }
   2487 
   2488 
   2489 /* ------------------------------------------------------------------------ */
   2490 /* Function:    ipf_nat_delrule                                             */
   2491 /* Returns:     Nil                                                         */
   2492 /* Parameters:  softc(I) - pointer to soft context main structure           */
   2493 /*              softn(I) - pointer to NAT context structure                 */
   2494 /*              np(I)    - pointer to NAT rule to delete                    */
   2495 /*              purge(I) - 1 == allow purge, 0 == prevent purge             */
   2496 /* Locks:       WRITE(ipf_nat)                                              */
   2497 /*                                                                          */
   2498 /* Preventing "purge" from occuring is allowed because when all of the NAT  */
   2499 /* rules are being removed, allowing the "purge" to walk through the list   */
   2500 /* of NAT sessions, possibly multiple times, would be a large performance   */
   2501 /* hit, on the order of O(N^2).                                             */
   2502 /* ------------------------------------------------------------------------ */
   2503 static void
   2504 ipf_nat_delrule(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, ipnat_t *np,
   2505 	int purge)
   2506 {
   2507 
   2508 	if (np->in_pnext != NULL) {
   2509 		*np->in_pnext = np->in_next;
   2510 		if (np->in_next != NULL)
   2511 			np->in_next->in_pnext = np->in_pnext;
   2512 		if (softn->ipf_nat_list_tail == &np->in_next)
   2513 			softn->ipf_nat_list_tail = np->in_pnext;
   2514 	}
   2515 
   2516 	if ((purge == 1) && ((np->in_flags & IPN_PURGE) != 0)) {
   2517 		nat_t *next;
   2518 		nat_t *nat;
   2519 
   2520 		for (next = softn->ipf_nat_instances; (nat = next) != NULL;) {
   2521 			next = nat->nat_next;
   2522 			if (nat->nat_ptr == np)
   2523 				ipf_nat_delete(softc, nat, NL_PURGE);
   2524 		}
   2525 	}
   2526 
   2527 	if ((np->in_flags & IPN_DELETE) == 0) {
   2528 		if (np->in_redir & NAT_REDIRECT) {
   2529 			switch (np->in_v[0])
   2530 			{
   2531 			case 4 :
   2532 				ipf_nat_delrdr(softn, np);
   2533 				break;
   2534 			case 6 :
   2535 				ipf_nat6_delrdr(softn, np);
   2536 				break;
   2537 			}
   2538 		}
   2539 		if (np->in_redir & (NAT_MAPBLK|NAT_MAP)) {
   2540 			switch (np->in_v[0])
   2541 			{
   2542 			case 4 :
   2543 				ipf_nat_delmap(softn, np);
   2544 				break;
   2545 			case 6 :
   2546 				ipf_nat6_delmap(softn, np);
   2547 				break;
   2548 			}
   2549 		}
   2550 	}
   2551 
   2552 	np->in_flags |= IPN_DELETE;
   2553 	ipf_nat_rule_deref(softc, &np);
   2554 }
   2555 
   2556 
   2557 /* ------------------------------------------------------------------------ */
   2558 /* Function:    ipf_nat_newmap                                              */
   2559 /* Returns:     int - -1 == error, 0 == success                             */
   2560 /* Parameters:  fin(I) - pointer to packet information                      */
   2561 /*              nat(I) - pointer to NAT entry                               */
   2562 /*              ni(I)  - pointer to structure with misc. information needed */
   2563 /*                       to create new NAT entry.                           */
   2564 /*                                                                          */
   2565 /* Given an empty NAT structure, populate it with new information about a   */
   2566 /* new NAT session, as defined by the matching NAT rule.                    */
   2567 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
   2568 /* to the new IP address for the translation.                               */
   2569 /* ------------------------------------------------------------------------ */
   2570 static int
   2571 ipf_nat_newmap(fr_info_t *fin, nat_t *nat, natinfo_t *ni)
   2572 {
   2573 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2574 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2575 	u_short st_port, dport, sport, port, sp, dp;
   2576 	struct in_addr in, inb;
   2577 	hostmap_t *hm;
   2578 	u_32_t flags;
   2579 	u_32_t st_ip;
   2580 	ipnat_t *np;
   2581 	nat_t *natl;
   2582 	int l;
   2583 
   2584 	/*
   2585 	 * If it's an outbound packet which doesn't match any existing
   2586 	 * record, then create a new port
   2587 	 */
   2588 	l = 0;
   2589 	hm = NULL;
   2590 	np = ni->nai_np;
   2591 	st_ip = np->in_snip;
   2592 	st_port = np->in_spnext;
   2593 	flags = nat->nat_flags;
   2594 
   2595 	if (flags & IPN_ICMPQUERY) {
   2596 		sport = fin->fin_data[1];
   2597 		dport = 0;
   2598 	} else {
   2599 		sport = htons(fin->fin_data[0]);
   2600 		dport = htons(fin->fin_data[1]);
   2601 	}
   2602 
   2603 	/*
   2604 	 * Do a loop until we either run out of entries to try or we find
   2605 	 * a NAT mapping that isn't currently being used.  This is done
   2606 	 * because the change to the source is not (usually) being fixed.
   2607 	 */
   2608 	do {
   2609 		port = 0;
   2610 		in.s_addr = htonl(np->in_snip);
   2611 		if (l == 0) {
   2612 			/*
   2613 			 * Check to see if there is an existing NAT
   2614 			 * setup for this IP address pair.
   2615 			 */
   2616 			hm = ipf_nat_hostmap(softn, np, fin->fin_src,
   2617 					     fin->fin_dst, in, 0);
   2618 			if (hm != NULL)
   2619 				in.s_addr = hm->hm_nsrcip.s_addr;
   2620 		} else if ((l == 1) && (hm != NULL)) {
   2621 			ipf_nat_hostmapdel(softc, &hm);
   2622 		}
   2623 		in.s_addr = ntohl(in.s_addr);
   2624 
   2625 		nat->nat_hm = hm;
   2626 
   2627 		if ((np->in_nsrcmsk == 0xffffffff) && (np->in_spnext == 0)) {
   2628 			if (l > 0) {
   2629 				NBUMPSIDEX(1, ns_exhausted, ns_exhausted_1);
   2630 				return -1;
   2631 			}
   2632 		}
   2633 
   2634 		if (np->in_redir == NAT_BIMAP &&
   2635 		    np->in_osrcmsk == np->in_nsrcmsk) {
   2636 			/*
   2637 			 * map the address block in a 1:1 fashion
   2638 			 */
   2639 			in.s_addr = np->in_nsrcaddr;
   2640 			in.s_addr |= fin->fin_saddr & ~np->in_osrcmsk;
   2641 			in.s_addr = ntohl(in.s_addr);
   2642 
   2643 		} else if (np->in_redir & NAT_MAPBLK) {
   2644 			if ((l >= np->in_ppip) || ((l > 0) &&
   2645 			     !(flags & IPN_TCPUDP))) {
   2646 				NBUMPSIDEX(1, ns_exhausted, ns_exhausted_2);
   2647 				return -1;
   2648 			}
   2649 			/*
   2650 			 * map-block - Calculate destination address.
   2651 			 */
   2652 			in.s_addr = ntohl(fin->fin_saddr);
   2653 			in.s_addr &= ntohl(~np->in_osrcmsk);
   2654 			inb.s_addr = in.s_addr;
   2655 			in.s_addr /= np->in_ippip;
   2656 			in.s_addr &= ntohl(~np->in_nsrcmsk);
   2657 			in.s_addr += ntohl(np->in_nsrcaddr);
   2658 			/*
   2659 			 * Calculate destination port.
   2660 			 */
   2661 			if ((flags & IPN_TCPUDP) &&
   2662 			    (np->in_ppip != 0)) {
   2663 				port = ntohs(sport) + l;
   2664 				port %= np->in_ppip;
   2665 				port += np->in_ppip *
   2666 					(inb.s_addr % np->in_ippip);
   2667 				port += MAPBLK_MINPORT;
   2668 				port = htons(port);
   2669 			}
   2670 
   2671 		} else if ((np->in_nsrcaddr == 0) &&
   2672 			   (np->in_nsrcmsk == 0xffffffff)) {
   2673 			i6addr_t in6;
   2674 
   2675 			/*
   2676 			 * 0/32 - use the interface's IP address.
   2677 			 */
   2678 			if ((l > 0) ||
   2679 			    ipf_ifpaddr(softc, 4, FRI_NORMAL, fin->fin_ifp,
   2680 				       &in6, NULL) == -1) {
   2681 				NBUMPSIDEX(1, ns_new_ifpaddr, ns_new_ifpaddr_1);
   2682 				return -1;
   2683 			}
   2684 			in.s_addr = ntohl(in6.in4.s_addr);
   2685 
   2686 		} else if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0)) {
   2687 			/*
   2688 			 * 0/0 - use the original source address/port.
   2689 			 */
   2690 			if (l > 0) {
   2691 				NBUMPSIDEX(1, ns_exhausted, ns_exhausted_3);
   2692 				return -1;
   2693 			}
   2694 			in.s_addr = ntohl(fin->fin_saddr);
   2695 
   2696 		} else if ((np->in_nsrcmsk != 0xffffffff) &&
   2697 			   (np->in_spnext == 0) && ((l > 0) || (hm == NULL)))
   2698 			np->in_snip++;
   2699 
   2700 		natl = NULL;
   2701 
   2702 		if ((flags & IPN_TCPUDP) &&
   2703 		    ((np->in_redir & NAT_MAPBLK) == 0) &&
   2704 		    (np->in_flags & IPN_AUTOPORTMAP)) {
   2705 			/*
   2706 			 * "ports auto" (without map-block)
   2707 			 */
   2708 			if ((l > 0) && np->in_ppip && (l % np->in_ppip == 0)) {
   2709 				if (l > np->in_space) {
   2710 					return -1;
   2711 				} else if ((l > np->in_ppip) &&
   2712 					   np->in_nsrcmsk != 0xffffffff)
   2713 					np->in_snip++;
   2714 			}
   2715 			if (np->in_ppip != 0) {
   2716 				port = ntohs(sport);
   2717 				port += (l % np->in_ppip);
   2718 				port %= np->in_ppip;
   2719 				port += np->in_ppip *
   2720 					(ntohl(fin->fin_saddr) %
   2721 					 np->in_ippip);
   2722 				port += MAPBLK_MINPORT;
   2723 				port = htons(port);
   2724 			}
   2725 
   2726 		} else if (((np->in_redir & NAT_MAPBLK) == 0) &&
   2727 			   (flags & IPN_TCPUDPICMP) && (np->in_spnext != 0)) {
   2728 			/*
   2729 			 * Standard port translation.  Select next port.
   2730 			 */
   2731 			if (np->in_flags & IPN_SEQUENTIAL) {
   2732 				port = np->in_spnext;
   2733 			} else {
   2734 				port = ipf_random() % (np->in_spmax -
   2735 						       np->in_spmin + 1);
   2736 				port += np->in_spmin;
   2737 			}
   2738 			port = htons(port);
   2739 			np->in_spnext++;
   2740 
   2741 			if (np->in_spnext > np->in_spmax) {
   2742 				np->in_spnext = np->in_spmin;
   2743 				if (np->in_nsrcmsk != 0xffffffff)
   2744 					np->in_snip++;
   2745 			}
   2746 		}
   2747 
   2748 		if (np->in_flags & IPN_SIPRANGE) {
   2749 			if (np->in_snip > ntohl(np->in_nsrcmsk))
   2750 				np->in_snip = ntohl(np->in_nsrcaddr);
   2751 		} else {
   2752 			if ((np->in_nsrcmsk != 0xffffffff) &&
   2753 			    ((np->in_snip + 1) & ntohl(np->in_nsrcmsk)) >
   2754 			    ntohl(np->in_nsrcaddr))
   2755 				np->in_snip = ntohl(np->in_nsrcaddr) + 1;
   2756 		}
   2757 
   2758 		if ((port == 0) && (flags & (IPN_TCPUDPICMP|IPN_ICMPQUERY)))
   2759 			port = sport;
   2760 
   2761 		/*
   2762 		 * Here we do a lookup of the connection as seen from
   2763 		 * the outside.  If an IP# pair already exists, try
   2764 		 * again.  So if you have A->B becomes C->B, you can
   2765 		 * also have D->E become C->E but not D->B causing
   2766 		 * another C->B.  Also take protocol and ports into
   2767 		 * account when determining whether a pre-existing
   2768 		 * NAT setup will cause an external conflict where
   2769 		 * this is appropriate.
   2770 		 */
   2771 		inb.s_addr = htonl(in.s_addr);
   2772 		sp = fin->fin_data[0];
   2773 		dp = fin->fin_data[1];
   2774 		fin->fin_data[0] = fin->fin_data[1];
   2775 		fin->fin_data[1] = ntohs(port);
   2776 		natl = ipf_nat_inlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
   2777 					(u_int)fin->fin_p, fin->fin_dst, inb);
   2778 		fin->fin_data[0] = sp;
   2779 		fin->fin_data[1] = dp;
   2780 
   2781 		/*
   2782 		 * Has the search wrapped around and come back to the
   2783 		 * start ?
   2784 		 */
   2785 		if ((natl != NULL) &&
   2786 		    (np->in_spnext != 0) && (st_port == np->in_spnext) &&
   2787 		    (np->in_snip != 0) && (st_ip == np->in_snip)) {
   2788 			NBUMPSIDED(1, ns_wrap);
   2789 			return -1;
   2790 		}
   2791 		l++;
   2792 	} while (natl != NULL);
   2793 
   2794 	/* Setup the NAT table */
   2795 	nat->nat_osrcip = fin->fin_src;
   2796 	nat->nat_nsrcaddr = htonl(in.s_addr);
   2797 	nat->nat_odstip = fin->fin_dst;
   2798 	nat->nat_ndstip = fin->fin_dst;
   2799 	if (nat->nat_hm == NULL)
   2800 		nat->nat_hm = ipf_nat_hostmap(softn, np, fin->fin_src,
   2801 					      fin->fin_dst, nat->nat_nsrcip,
   2802 					      0);
   2803 
   2804 	if (flags & IPN_TCPUDP) {
   2805 		nat->nat_osport = sport;
   2806 		nat->nat_nsport = port;	/* sport */
   2807 		nat->nat_odport = dport;
   2808 		nat->nat_ndport = dport;
   2809 		((tcphdr_t *)fin->fin_dp)->th_sport = port;
   2810 	} else if (flags & IPN_ICMPQUERY) {
   2811 		nat->nat_oicmpid = fin->fin_data[1];
   2812 		((icmphdr_t *)fin->fin_dp)->icmp_id = port;
   2813 		nat->nat_nicmpid = port;
   2814 	}
   2815 	return 0;
   2816 }
   2817 
   2818 
   2819 /* ------------------------------------------------------------------------ */
   2820 /* Function:    ipf_nat_newrdr                                              */
   2821 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
   2822 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
   2823 /* Parameters:  fin(I) - pointer to packet information                      */
   2824 /*              nat(I) - pointer to NAT entry                               */
   2825 /*              ni(I)  - pointer to structure with misc. information needed */
   2826 /*                       to create new NAT entry.                           */
   2827 /*                                                                          */
   2828 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
   2829 /* to the new IP address for the translation.                               */
   2830 /* ------------------------------------------------------------------------ */
   2831 static int
   2832 ipf_nat_newrdr(fr_info_t *fin, nat_t *nat, natinfo_t *ni)
   2833 {
   2834 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2835 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2836 	u_short nport, dport, sport;
   2837 	struct in_addr in, inb;
   2838 	u_short sp, dp;
   2839 	hostmap_t *hm;
   2840 	u_32_t flags;
   2841 	ipnat_t *np;
   2842 	nat_t *natl;
   2843 	int move;
   2844 
   2845 	move = 1;
   2846 	hm = NULL;
   2847 	in.s_addr = 0;
   2848 	np = ni->nai_np;
   2849 	flags = nat->nat_flags;
   2850 
   2851 	if (flags & IPN_ICMPQUERY) {
   2852 		dport = fin->fin_data[1];
   2853 		sport = 0;
   2854 	} else {
   2855 		sport = htons(fin->fin_data[0]);
   2856 		dport = htons(fin->fin_data[1]);
   2857 	}
   2858 
   2859 	/* TRACE sport, dport */
   2860 
   2861 
   2862 	/*
   2863 	 * If the matching rule has IPN_STICKY set, then we want to have the
   2864 	 * same rule kick in as before.  Why would this happen?  If you have
   2865 	 * a collection of rdr rules with "round-robin sticky", the current
   2866 	 * packet might match a different one to the previous connection but
   2867 	 * we want the same destination to be used.
   2868 	 */
   2869 	if (((np->in_flags & (IPN_ROUNDR|IPN_SPLIT)) != 0) &&
   2870 	    ((np->in_flags & IPN_STICKY) != 0)) {
   2871 		hm = ipf_nat_hostmap(softn, NULL, fin->fin_src, fin->fin_dst,
   2872 				     in, (u_32_t)dport);
   2873 		if (hm != NULL) {
   2874 			in.s_addr = ntohl(hm->hm_ndstip.s_addr);
   2875 			np = hm->hm_ipnat;
   2876 			ni->nai_np = np;
   2877 			move = 0;
   2878 			ipf_nat_hostmapdel(softc, &hm);
   2879 		}
   2880 	}
   2881 
   2882 	/*
   2883 	 * Otherwise, it's an inbound packet. Most likely, we don't
   2884 	 * want to rewrite source ports and source addresses. Instead,
   2885 	 * we want to rewrite to a fixed internal address and fixed
   2886 	 * internal port.
   2887 	 */
   2888 	if (np->in_flags & IPN_SPLIT) {
   2889 		in.s_addr = np->in_dnip;
   2890 
   2891 		if ((np->in_flags & (IPN_ROUNDR|IPN_STICKY)) == IPN_STICKY) {
   2892 			hm = ipf_nat_hostmap(softn, NULL, fin->fin_src,
   2893 					     fin->fin_dst, in, (u_32_t)dport);
   2894 			if (hm != NULL) {
   2895 				in.s_addr = hm->hm_ndstip.s_addr;
   2896 				move = 0;
   2897 			}
   2898 		}
   2899 
   2900 		if (hm == NULL || hm->hm_ref == 1) {
   2901 			if (np->in_ndstaddr == htonl(in.s_addr)) {
   2902 				np->in_dnip = ntohl(np->in_ndstmsk);
   2903 				move = 0;
   2904 			} else {
   2905 				np->in_dnip = ntohl(np->in_ndstaddr);
   2906 			}
   2907 		}
   2908 		if (hm != NULL)
   2909 			ipf_nat_hostmapdel(softc, &hm);
   2910 
   2911 	} else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0xffffffff)) {
   2912 		i6addr_t in6;
   2913 
   2914 		/*
   2915 		 * 0/32 - use the interface's IP address.
   2916 		 */
   2917 		if (ipf_ifpaddr(softc, 4, FRI_NORMAL, fin->fin_ifp,
   2918 			       &in6, NULL) == -1) {
   2919 			NBUMPSIDEX(0, ns_new_ifpaddr, ns_new_ifpaddr_2);
   2920 			return -1;
   2921 		}
   2922 		in.s_addr = ntohl(in6.in4.s_addr);
   2923 
   2924 	} else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk== 0)) {
   2925 		/*
   2926 		 * 0/0 - use the original destination address/port.
   2927 		 */
   2928 		in.s_addr = ntohl(fin->fin_daddr);
   2929 
   2930 	} else if (np->in_redir == NAT_BIMAP &&
   2931 		   np->in_ndstmsk == np->in_odstmsk) {
   2932 		/*
   2933 		 * map the address block in a 1:1 fashion
   2934 		 */
   2935 		in.s_addr = np->in_ndstaddr;
   2936 		in.s_addr |= fin->fin_daddr & ~np->in_ndstmsk;
   2937 		in.s_addr = ntohl(in.s_addr);
   2938 	} else {
   2939 		in.s_addr = ntohl(np->in_ndstaddr);
   2940 	}
   2941 
   2942 	if ((np->in_dpnext == 0) || ((flags & NAT_NOTRULEPORT) != 0))
   2943 		nport = dport;
   2944 	else {
   2945 		/*
   2946 		 * Whilst not optimized for the case where
   2947 		 * pmin == pmax, the gain is not significant.
   2948 		 */
   2949 		if (((np->in_flags & IPN_FIXEDDPORT) == 0) &&
   2950 		    (np->in_odport != np->in_dtop)) {
   2951 			nport = ntohs(dport) - np->in_odport + np->in_dpmax;
   2952 			nport = htons(nport);
   2953 		} else {
   2954 			nport = htons(np->in_dpnext);
   2955 			np->in_dpnext++;
   2956 			if (np->in_dpnext > np->in_dpmax)
   2957 				np->in_dpnext = np->in_dpmin;
   2958 		}
   2959 	}
   2960 
   2961 	/*
   2962 	 * When the redirect-to address is set to 0.0.0.0, just
   2963 	 * assume a blank `forwarding' of the packet.  We don't
   2964 	 * setup any translation for this either.
   2965 	 */
   2966 	if (in.s_addr == 0) {
   2967 		if (nport == dport) {
   2968 			NBUMPSIDED(0, ns_xlate_null);
   2969 			return -1;
   2970 		}
   2971 		in.s_addr = ntohl(fin->fin_daddr);
   2972 	}
   2973 
   2974 	/*
   2975 	 * Check to see if this redirect mapping already exists and if
   2976 	 * it does, return "failure" (allowing it to be created will just
   2977 	 * cause one or both of these "connections" to stop working.)
   2978 	 */
   2979 	inb.s_addr = htonl(in.s_addr);
   2980 	sp = fin->fin_data[0];
   2981 	dp = fin->fin_data[1];
   2982 	fin->fin_data[1] = fin->fin_data[0];
   2983 	fin->fin_data[0] = ntohs(nport);
   2984 	natl = ipf_nat_outlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
   2985 			     (u_int)fin->fin_p, inb, fin->fin_src);
   2986 	fin->fin_data[0] = sp;
   2987 	fin->fin_data[1] = dp;
   2988 	if (natl != NULL) {
   2989 		DT2(ns_new_xlate_exists, fr_info_t *, fin, nat_t *, natl);
   2990 		NBUMPSIDE(0, ns_xlate_exists);
   2991 		return -1;
   2992 	}
   2993 
   2994 	nat->nat_ndstaddr = htonl(in.s_addr);
   2995 	nat->nat_odstip = fin->fin_dst;
   2996 	nat->nat_nsrcip = fin->fin_src;
   2997 	nat->nat_osrcip = fin->fin_src;
   2998 	if ((nat->nat_hm == NULL) && ((np->in_flags & IPN_STICKY) != 0))
   2999 		nat->nat_hm = ipf_nat_hostmap(softn, np, fin->fin_src,
   3000 					      fin->fin_dst, in, (u_32_t)dport);
   3001 
   3002 	if (flags & IPN_TCPUDP) {
   3003 		nat->nat_odport = dport;
   3004 		nat->nat_ndport = nport;
   3005 		nat->nat_osport = sport;
   3006 		nat->nat_nsport = sport;
   3007 		((tcphdr_t *)fin->fin_dp)->th_dport = nport;
   3008 	} else if (flags & IPN_ICMPQUERY) {
   3009 		nat->nat_oicmpid = fin->fin_data[1];
   3010 		((icmphdr_t *)fin->fin_dp)->icmp_id = nport;
   3011 		nat->nat_nicmpid = nport;
   3012 	}
   3013 
   3014 	return move;
   3015 }
   3016 
   3017 /* ------------------------------------------------------------------------ */
   3018 /* Function:    ipf_nat_add                                                 */
   3019 /* Returns:     nat_t* - NULL == failure to create new NAT structure,       */
   3020 /*                       else pointer to new NAT structure                  */
   3021 /* Parameters:  fin(I)       - pointer to packet information                */
   3022 /*              np(I)        - pointer to NAT rule                          */
   3023 /*              natsave(I)   - pointer to where to store NAT struct pointer */
   3024 /*              flags(I)     - flags describing the current packet          */
   3025 /*              direction(I) - direction of packet (in/out)                 */
   3026 /* Write Lock:  ipf_nat                                                     */
   3027 /*                                                                          */
   3028 /* Attempts to create a new NAT entry.  Does not actually change the packet */
   3029 /* in any way.                                                              */
   3030 /*                                                                          */
   3031 /* This fucntion is in three main parts: (1) deal with creating a new NAT   */
   3032 /* structure for a "MAP" rule (outgoing NAT translation); (2) deal with     */
   3033 /* creating a new NAT structure for a "RDR" rule (incoming NAT translation) */
   3034 /* and (3) building that structure and putting it into the NAT table(s).    */
   3035 /*                                                                          */
   3036 /* NOTE: natsave should NOT be used top point back to an ipstate_t struct   */
   3037 /*       as it can result in memory being corrupted.                        */
   3038 /* ------------------------------------------------------------------------ */
   3039 nat_t *
   3040 ipf_nat_add(fr_info_t *fin, ipnat_t *np, nat_t **natsave, u_int flags,
   3041     int direction)
   3042 {
   3043 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3044 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3045 	hostmap_t *hm = NULL;
   3046 	nat_t *nat, *natl;
   3047 	natstat_t *nsp;
   3048 	u_int nflags;
   3049 	natinfo_t ni;
   3050 	int move;
   3051 
   3052 	memset(&ni, 0, sizeof ni);	/* XXX gcc */
   3053 	nsp = &softn->ipf_nat_stats;
   3054 
   3055 	if ((nsp->ns_active * 100 / softn->ipf_nat_table_max) >
   3056 	    softn->ipf_nat_table_wm_high) {
   3057 		softn->ipf_nat_doflush = 1;
   3058 	}
   3059 
   3060 	if (nsp->ns_active >= softn->ipf_nat_table_max) {
   3061 		NBUMPSIDED(fin->fin_out, ns_table_max);
   3062 		return NULL;
   3063 	}
   3064 
   3065 	move = 1;
   3066 	nflags = np->in_flags & flags;
   3067 	nflags &= NAT_FROMRULE;
   3068 
   3069 	ni.nai_np = np;
   3070 	ni.nai_dport = 0;
   3071 	ni.nai_sport = 0;
   3072 
   3073 	/* Give me a new nat */
   3074 	KMALLOC(nat, nat_t *);
   3075 	if (nat == NULL) {
   3076 		NBUMPSIDED(fin->fin_out, ns_memfail);
   3077 		/*
   3078 		 * Try to automatically tune the max # of entries in the
   3079 		 * table allowed to be less than what will cause kmem_alloc()
   3080 		 * to fail and try to eliminate panics due to out of memory
   3081 		 * conditions arising.
   3082 		 */
   3083 		if ((softn->ipf_nat_table_max > softn->ipf_nat_table_sz) &&
   3084 		    (nsp->ns_active > 100)) {
   3085 			softn->ipf_nat_table_max = nsp->ns_active - 100;
   3086 			printf("table_max reduced to %d\n",
   3087 				softn->ipf_nat_table_max);
   3088 		}
   3089 		return NULL;
   3090 	}
   3091 
   3092 	if (flags & IPN_ICMPQUERY) {
   3093 		/*
   3094 		 * In the ICMP query NAT code, we translate the ICMP id fields
   3095 		 * to make them unique. This is indepedent of the ICMP type
   3096 		 * (e.g. in the unlikely event that a host sends an echo and
   3097 		 * an tstamp request with the same id, both packets will have
   3098 		 * their ip address/id field changed in the same way).
   3099 		 */
   3100 		/* The icmp_id field is used by the sender to identify the
   3101 		 * process making the icmp request. (the receiver justs
   3102 		 * copies it back in its response). So, it closely matches
   3103 		 * the concept of source port. We overlay sport, so we can
   3104 		 * maximally reuse the existing code.
   3105 		 */
   3106 		ni.nai_sport = fin->fin_data[1];
   3107 		ni.nai_dport = 0;
   3108 	}
   3109 
   3110 	bzero((char *)nat, sizeof(*nat));
   3111 	nat->nat_flags = flags;
   3112 	nat->nat_redir = np->in_redir;
   3113 	nat->nat_dir = direction;
   3114 	nat->nat_pr[0] = fin->fin_p;
   3115 	nat->nat_pr[1] = fin->fin_p;
   3116 
   3117 	/*
   3118 	 * Search the current table for a match and create a new mapping
   3119 	 * if there is none found.
   3120 	 */
   3121 	if (np->in_redir & NAT_DIVERTUDP) {
   3122 		move = ipf_nat_newdivert(fin, nat, &ni);
   3123 
   3124 	} else if (np->in_redir & NAT_REWRITE) {
   3125 		move = ipf_nat_newrewrite(fin, nat, &ni);
   3126 
   3127 	} else if (direction == NAT_OUTBOUND) {
   3128 		/*
   3129 		 * We can now arrange to call this for the same connection
   3130 		 * because ipf_nat_new doesn't protect the code path into
   3131 		 * this function.
   3132 		 */
   3133 		natl = ipf_nat_outlookup(fin, nflags, (u_int)fin->fin_p,
   3134 				     fin->fin_src, fin->fin_dst);
   3135 		if (natl != NULL) {
   3136 			KFREE(nat);
   3137 			nat = natl;
   3138 			goto done;
   3139 		}
   3140 
   3141 		move = ipf_nat_newmap(fin, nat, &ni);
   3142 	} else {
   3143 		/*
   3144 		 * NAT_INBOUND is used for redirects rules
   3145 		 */
   3146 		natl = ipf_nat_inlookup(fin, nflags, (u_int)fin->fin_p,
   3147 					fin->fin_src, fin->fin_dst);
   3148 		if (natl != NULL) {
   3149 			KFREE(nat);
   3150 			nat = natl;
   3151 			goto done;
   3152 		}
   3153 
   3154 		move = ipf_nat_newrdr(fin, nat, &ni);
   3155 	}
   3156 	if (move == -1)
   3157 		goto badnat;
   3158 
   3159 	np = ni.nai_np;
   3160 
   3161 	nat->nat_mssclamp = np->in_mssclamp;
   3162 	nat->nat_me = natsave;
   3163 	nat->nat_fr = fin->fin_fr;
   3164 	nat->nat_rev = fin->fin_rev;
   3165 	nat->nat_ptr = np;
   3166 	nat->nat_dlocal = np->in_dlocal;
   3167 
   3168 	if ((np->in_apr != NULL) && ((nat->nat_flags & NAT_SLAVE) == 0)) {
   3169 		if (ipf_proxy_new(fin, nat) == -1) {
   3170 			NBUMPSIDED(fin->fin_out, ns_appr_fail);
   3171 			goto badnat;
   3172 		}
   3173 	}
   3174 
   3175 	nat->nat_ifps[0] = np->in_ifps[0];
   3176 	if (np->in_ifps[0] != NULL) {
   3177 		COPYIFNAME(np->in_v[0], np->in_ifps[0], nat->nat_ifnames[0]);
   3178 	}
   3179 
   3180 	nat->nat_ifps[1] = np->in_ifps[1];
   3181 	if (np->in_ifps[1] != NULL) {
   3182 		COPYIFNAME(np->in_v[1], np->in_ifps[1], nat->nat_ifnames[1]);
   3183 	}
   3184 
   3185 	if (ipf_nat_finalise(fin, nat) == -1) {
   3186 		goto badnat;
   3187 	}
   3188 
   3189 	np->in_use++;
   3190 
   3191 	if ((move == 1) && (np->in_flags & IPN_ROUNDR)) {
   3192 		if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_REDIRECT) {
   3193 			ipf_nat_delrdr(softn, np);
   3194 			ipf_nat_addrdr(softn, np);
   3195 		} else if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_MAP) {
   3196 			ipf_nat_delmap(softn, np);
   3197 			ipf_nat_addmap(softn, np);
   3198 		}
   3199 	}
   3200 
   3201 	if (flags & SI_WILDP)
   3202 		nsp->ns_wilds++;
   3203 	nsp->ns_proto[nat->nat_pr[0]]++;
   3204 
   3205 	goto done;
   3206 badnat:
   3207 	DT2(ns_badnatnew, fr_info_t *, fin, nat_t *, nat);
   3208 	NBUMPSIDE(fin->fin_out, ns_badnatnew);
   3209 	if ((hm = nat->nat_hm) != NULL)
   3210 		ipf_nat_hostmapdel(softc, &hm);
   3211 	KFREE(nat);
   3212 	nat = NULL;
   3213 done:
   3214 	if (nat != NULL && np != NULL)
   3215 		np->in_hits++;
   3216 	if (natsave != NULL)
   3217 		*natsave = nat;
   3218 	return nat;
   3219 }
   3220 
   3221 
   3222 /* ------------------------------------------------------------------------ */
   3223 /* Function:    ipf_nat_finalise                                            */
   3224 /* Returns:     int - 0 == sucess, -1 == failure                            */
   3225 /* Parameters:  fin(I) - pointer to packet information                      */
   3226 /*              nat(I) - pointer to NAT entry                               */
   3227 /* Write Lock:  ipf_nat                                                     */
   3228 /*                                                                          */
   3229 /* This is the tail end of constructing a new NAT entry and is the same     */
   3230 /* for both IPv4 and IPv6.                                                  */
   3231 /* ------------------------------------------------------------------------ */
   3232 /*ARGSUSED*/
   3233 static int
   3234 ipf_nat_finalise(fr_info_t *fin, nat_t *nat)
   3235 {
   3236 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3237 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3238 	u_32_t sum1, sum2, sumd;
   3239 	frentry_t *fr;
   3240 	u_32_t flags;
   3241 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6) && defined(ICK_M_CTL_MAGIC)
   3242 	qpktinfo_t *qpi = fin->fin_qpi;
   3243 #endif
   3244 
   3245 	flags = nat->nat_flags;
   3246 
   3247 	switch (nat->nat_pr[0])
   3248 	{
   3249 	case IPPROTO_ICMP :
   3250 		sum1 = LONG_SUM(ntohs(nat->nat_oicmpid));
   3251 		sum2 = LONG_SUM(ntohs(nat->nat_nicmpid));
   3252 		CALC_SUMD(sum1, sum2, sumd);
   3253 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   3254 
   3255 		break;
   3256 
   3257 	default :
   3258 		sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr) + \
   3259 				ntohs(nat->nat_osport));
   3260 		sum2 = LONG_SUM(ntohl(nat->nat_nsrcaddr) + \
   3261 				ntohs(nat->nat_nsport));
   3262 		CALC_SUMD(sum1, sum2, sumd);
   3263 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   3264 
   3265 		sum1 = LONG_SUM(ntohl(nat->nat_odstaddr) + \
   3266 				ntohs(nat->nat_odport));
   3267 		sum2 = LONG_SUM(ntohl(nat->nat_ndstaddr) + \
   3268 				ntohs(nat->nat_ndport));
   3269 		CALC_SUMD(sum1, sum2, sumd);
   3270 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   3271 		break;
   3272 	}
   3273 
   3274 	/*
   3275 	 * Compute the partial checksum, just in case.
   3276 	 * This is only ever placed into outbound packets so care needs
   3277 	 * to be taken over which pair of addresses are used.
   3278 	 */
   3279 	if (nat->nat_dir == NAT_OUTBOUND) {
   3280 		sum1 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
   3281 		sum1 += LONG_SUM(ntohl(nat->nat_ndstaddr));
   3282 	} else {
   3283 		sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr));
   3284 		sum1 += LONG_SUM(ntohl(nat->nat_odstaddr));
   3285 	}
   3286 	sum1 += nat->nat_pr[1];
   3287 	nat->nat_sumd[1] = (sum1 & 0xffff) + (sum1 >> 16);
   3288 
   3289 	sum1 = LONG_SUM(ntohl(nat->nat_osrcaddr));
   3290 	sum2 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
   3291 	CALC_SUMD(sum1, sum2, sumd);
   3292 	nat->nat_ipsumd = (sumd & 0xffff) + (sumd >> 16);
   3293 
   3294 	sum1 = LONG_SUM(ntohl(nat->nat_odstaddr));
   3295 	sum2 = LONG_SUM(ntohl(nat->nat_ndstaddr));
   3296 	CALC_SUMD(sum1, sum2, sumd);
   3297 	nat->nat_ipsumd += (sumd & 0xffff) + (sumd >> 16);
   3298 
   3299 	nat->nat_v[0] = 4;
   3300 	nat->nat_v[1] = 4;
   3301 
   3302 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   3303 		nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
   3304 	}
   3305 
   3306 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   3307 		nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
   3308 	}
   3309 
   3310 	if ((nat->nat_flags & SI_CLONE) == 0)
   3311 		nat->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, nat);
   3312 
   3313 	if (ipf_nat_insert(softc, softn, nat) == 0) {
   3314 		if (softn->ipf_nat_logging)
   3315 			ipf_nat_log(softc, softn, nat, NL_NEW);
   3316 		fr = nat->nat_fr;
   3317 		if (fr != NULL) {
   3318 			MUTEX_ENTER(&fr->fr_lock);
   3319 			fr->fr_ref++;
   3320 			MUTEX_EXIT(&fr->fr_lock);
   3321 		}
   3322 		return 0;
   3323 	}
   3324 
   3325 	NBUMPSIDED(fin->fin_out, ns_unfinalised);
   3326 	/*
   3327 	 * nat_insert failed, so cleanup time...
   3328 	 */
   3329 	if (nat->nat_sync != NULL)
   3330 		ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
   3331 	return -1;
   3332 }
   3333 
   3334 
   3335 /* ------------------------------------------------------------------------ */
   3336 /* Function:    ipf_nat_insert                                              */
   3337 /* Returns:     int - 0 == sucess, -1 == failure                            */
   3338 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3339 /*              softn(I) - pointer to NAT context structure                 */
   3340 /*              nat(I) - pointer to NAT structure                           */
   3341 /* Write Lock:  ipf_nat                                                     */
   3342 /*                                                                          */
   3343 /* Insert a NAT entry into the hash tables for searching and add it to the  */
   3344 /* list of active NAT entries.  Adjust global counters when complete.       */
   3345 /* ------------------------------------------------------------------------ */
   3346 int
   3347 ipf_nat_insert(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, nat_t *nat)
   3348 {
   3349 	u_int hv0, hv1;
   3350 	u_int sp, dp;
   3351 	ipnat_t *in;
   3352 
   3353 	/*
   3354 	 * Try and return an error as early as possible, so calculate the hash
   3355 	 * entry numbers first and then proceed.
   3356 	 */
   3357 	if ((nat->nat_flags & (SI_W_SPORT|SI_W_DPORT)) == 0) {
   3358 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   3359 			sp = nat->nat_osport;
   3360 			dp = nat->nat_odport;
   3361 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   3362 			sp = 0;
   3363 			dp = nat->nat_oicmpid;
   3364 		} else {
   3365 			sp = 0;
   3366 			dp = 0;
   3367 		}
   3368 		hv0 = NAT_HASH_FN(nat->nat_osrcaddr, sp, 0xffffffff);
   3369 		hv0 = NAT_HASH_FN(nat->nat_odstaddr, hv0 + dp, 0xffffffff);
   3370 		/*
   3371 		 * TRACE nat_osrcaddr, nat_osport, nat_odstaddr,
   3372 		 * nat_odport, hv0
   3373 		 */
   3374 
   3375 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   3376 			sp = nat->nat_nsport;
   3377 			dp = nat->nat_ndport;
   3378 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   3379 			sp = 0;
   3380 			dp = nat->nat_nicmpid;
   3381 		} else {
   3382 			sp = 0;
   3383 			dp = 0;
   3384 		}
   3385 		hv1 = NAT_HASH_FN(nat->nat_nsrcaddr, sp, 0xffffffff);
   3386 		hv1 = NAT_HASH_FN(nat->nat_ndstaddr, hv1 + dp, 0xffffffff);
   3387 		/*
   3388 		 * TRACE nat_nsrcaddr, nat_nsport, nat_ndstaddr,
   3389 		 * nat_ndport, hv1
   3390 		 */
   3391 	} else {
   3392 		hv0 = NAT_HASH_FN(nat->nat_osrcaddr, 0, 0xffffffff);
   3393 		hv0 = NAT_HASH_FN(nat->nat_odstaddr, hv0, 0xffffffff);
   3394 		/* TRACE nat_osrcaddr, nat_odstaddr, hv0 */
   3395 
   3396 		hv1 = NAT_HASH_FN(nat->nat_nsrcaddr, 0, 0xffffffff);
   3397 		hv1 = NAT_HASH_FN(nat->nat_ndstaddr, hv1, 0xffffffff);
   3398 		/* TRACE nat_nsrcaddr, nat_ndstaddr, hv1 */
   3399 	}
   3400 
   3401 	nat->nat_hv[0] = hv0;
   3402 	nat->nat_hv[1] = hv1;
   3403 
   3404 	MUTEX_INIT(&nat->nat_lock, "nat entry lock");
   3405 
   3406 	in = nat->nat_ptr;
   3407 	nat->nat_ref = nat->nat_me ? 2 : 1;
   3408 
   3409 	nat->nat_ifnames[0][LIFNAMSIZ - 1] = '\0';
   3410 	nat->nat_ifps[0] = ipf_resolvenic(softc, nat->nat_ifnames[0], 4);
   3411 
   3412 	if (nat->nat_ifnames[1][0] != '\0') {
   3413 		nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   3414 		nat->nat_ifps[1] = ipf_resolvenic(softc,
   3415 						  nat->nat_ifnames[1], 4);
   3416 	} else if (in->in_ifnames[1] != -1) {
   3417 		char *name;
   3418 
   3419 		name = in->in_names + in->in_ifnames[1];
   3420 		if (name[1] != '\0' && name[0] != '-' && name[0] != '*') {
   3421 			(void) strncpy(nat->nat_ifnames[1],
   3422 				       nat->nat_ifnames[0], LIFNAMSIZ);
   3423 			nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   3424 			nat->nat_ifps[1] = nat->nat_ifps[0];
   3425 		}
   3426 	}
   3427 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   3428 		nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
   3429 	}
   3430 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   3431 		nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
   3432 	}
   3433 
   3434 	return ipf_nat_hashtab_add(softc, softn, nat);
   3435 }
   3436 
   3437 
   3438 /* ------------------------------------------------------------------------ */
   3439 /* Function:    ipf_nat_hashtab_add                                         */
   3440 /* Parameters:  softc(I) - pointer to soft context main structure           */
   3441 /*              softn(I) - pointer to NAT context structure                 */
   3442 /*              nat(I) - pointer to NAT structure                           */
   3443 /*                                                                          */
   3444 /* Handle the insertion of a NAT entry into the table/list.                 */
   3445 /* ------------------------------------------------------------------------ */
   3446 int
   3447 ipf_nat_hashtab_add(softc, softn, nat)
   3448 	ipf_main_softc_t *softc;
   3449 	ipf_nat_softc_t *softn;
   3450 	nat_t *nat;
   3451 {
   3452 	nat_t **natp;
   3453 	u_int hv0;
   3454 	u_int hv1;
   3455 
   3456 	hv0 = nat->nat_hv[0] % softn->ipf_nat_table_sz;
   3457 	hv1 = nat->nat_hv[1] % softn->ipf_nat_table_sz;
   3458 
   3459 	if (nat->nat_dir == NAT_INBOUND || nat->nat_dir == NAT_DIVERTIN) {
   3460 		u_int swap;
   3461 
   3462 		swap = hv0;
   3463 		hv0 = hv1;
   3464 		hv1 = swap;
   3465 	}
   3466 
   3467 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0] >=
   3468 	    softn->ipf_nat_maxbucket) {
   3469 		DT1(ns_bucket_max_0, int,
   3470 		    softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0]);
   3471 		NBUMPSIDE(0, ns_bucket_max);
   3472 		return -1;
   3473 	}
   3474 
   3475 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1] >=
   3476 	    softn->ipf_nat_maxbucket) {
   3477 		DT1(ns_bucket_max_1, int,
   3478 		    softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1]);
   3479 		NBUMPSIDE(1, ns_bucket_max);
   3480 		return -1;
   3481 	}
   3482 
   3483 	/*
   3484 	 * The ordering of operations in the list and hash table insertion
   3485 	 * is very important.  The last operation for each task should be
   3486 	 * to update the top of the list, after all the "nexts" have been
   3487 	 * done so that walking the list while it is being done does not
   3488 	 * find strange pointers.
   3489 	 *
   3490 	 * Global list of NAT instances
   3491 	 */
   3492 	nat->nat_next = softn->ipf_nat_instances;
   3493 	nat->nat_pnext = &softn->ipf_nat_instances;
   3494 	if (softn->ipf_nat_instances)
   3495 		softn->ipf_nat_instances->nat_pnext = &nat->nat_next;
   3496 	softn->ipf_nat_instances = nat;
   3497 
   3498 	/*
   3499 	 * Inbound hash table.
   3500 	 */
   3501 	natp = &softn->ipf_nat_table[0][hv0];
   3502 	nat->nat_phnext[0] = natp;
   3503 	nat->nat_hnext[0] = *natp;
   3504 	if (*natp) {
   3505 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   3506 	} else {
   3507 		NBUMPSIDE(0, ns_inuse);
   3508 	}
   3509 	*natp = nat;
   3510 	NBUMPSIDE(0, ns_bucketlen[hv0]);
   3511 
   3512 	/*
   3513 	 * Outbound hash table.
   3514 	 */
   3515 	natp = &softn->ipf_nat_table[1][hv1];
   3516 	nat->nat_phnext[1] = natp;
   3517 	nat->nat_hnext[1] = *natp;
   3518 	if (*natp)
   3519 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   3520 	else {
   3521 		NBUMPSIDE(1, ns_inuse);
   3522 	}
   3523 	*natp = nat;
   3524 	NBUMPSIDE(1, ns_bucketlen[hv1]);
   3525 
   3526 	ipf_nat_setqueue(softc, softn, nat);
   3527 
   3528 	if (nat->nat_dir & NAT_OUTBOUND) {
   3529 		NBUMPSIDE(1, ns_added);
   3530 	} else {
   3531 		NBUMPSIDE(0, ns_added);
   3532 	}
   3533 	softn->ipf_nat_stats.ns_active++;
   3534 	return 0;
   3535 }
   3536 
   3537 
   3538 /* ------------------------------------------------------------------------ */
   3539 /* Function:    ipf_nat_icmperrorlookup                                     */
   3540 /* Returns:     nat_t* - point to matching NAT structure                    */
   3541 /* Parameters:  fin(I) - pointer to packet information                      */
   3542 /*              dir(I) - direction of packet (in/out)                       */
   3543 /*                                                                          */
   3544 /* Check if the ICMP error message is related to an existing TCP, UDP or    */
   3545 /* ICMP query nat entry.  It is assumed that the packet is already of the   */
   3546 /* the required length.                                                     */
   3547 /* ------------------------------------------------------------------------ */
   3548 nat_t *
   3549 ipf_nat_icmperrorlookup(fr_info_t *fin, int dir)
   3550 {
   3551 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3552 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3553 	int flags = 0, type, minlen;
   3554 	icmphdr_t *icmp, *orgicmp;
   3555 	nat_stat_side_t *nside;
   3556 	tcphdr_t *tcp = NULL;
   3557 	u_short data[2];
   3558 	nat_t *nat;
   3559 	ip_t *oip;
   3560 	u_int p;
   3561 
   3562 	icmp = fin->fin_dp;
   3563 	type = icmp->icmp_type;
   3564 	nside = &softn->ipf_nat_stats.ns_side[fin->fin_out];
   3565 	/*
   3566 	 * Does it at least have the return (basic) IP header ?
   3567 	 * Only a basic IP header (no options) should be with an ICMP error
   3568 	 * header.  Also, if it's not an error type, then return.
   3569 	 */
   3570 	if ((fin->fin_hlen != sizeof(ip_t)) || !(fin->fin_flx & FI_ICMPERR)) {
   3571 		ATOMIC_INCL(nside->ns_icmp_basic);
   3572 		return NULL;
   3573 	}
   3574 
   3575 	/*
   3576 	 * Check packet size
   3577 	 */
   3578 	oip = (ip_t *)((char *)fin->fin_dp + 8);
   3579 	minlen = IP_HL(oip) << 2;
   3580 	if ((minlen < sizeof(ip_t)) ||
   3581 	    (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen)) {
   3582 		ATOMIC_INCL(nside->ns_icmp_size);
   3583 		return NULL;
   3584 	}
   3585 
   3586 	/*
   3587 	 * Is the buffer big enough for all of it ?  It's the size of the IP
   3588 	 * header claimed in the encapsulated part which is of concern.  It
   3589 	 * may be too big to be in this buffer but not so big that it's
   3590 	 * outside the ICMP packet, leading to TCP deref's causing problems.
   3591 	 * This is possible because we don't know how big oip_hl is when we
   3592 	 * do the pullup early in ipf_check() and thus can't gaurantee it is
   3593 	 * all here now.
   3594 	 */
   3595 #ifdef  ipf_nat_KERNEL
   3596 	{
   3597 	mb_t *m;
   3598 
   3599 	m = fin->fin_m;
   3600 # if defined(MENTAT)
   3601 	if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN >
   3602 	    (char *)m->b_wptr) {
   3603 		ATOMIC_INCL(nside->ns_icmp_mbuf);
   3604 		return NULL;
   3605 	}
   3606 # else
   3607 	if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN >
   3608 	    (char *)fin->fin_ip + M_LEN(m)) {
   3609 		ATOMIC_INCL(nside->ns_icmp_mbuf);
   3610 		return NULL;
   3611 	}
   3612 # endif
   3613 	}
   3614 #endif
   3615 
   3616 	if (fin->fin_daddr != oip->ip_src.s_addr) {
   3617 		ATOMIC_INCL(nside->ns_icmp_address);
   3618 		return NULL;
   3619 	}
   3620 
   3621 	p = oip->ip_p;
   3622 	if (p == IPPROTO_TCP)
   3623 		flags = IPN_TCP;
   3624 	else if (p == IPPROTO_UDP)
   3625 		flags = IPN_UDP;
   3626 	else if (p == IPPROTO_ICMP) {
   3627 		orgicmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
   3628 
   3629 		/* see if this is related to an ICMP query */
   3630 		if (ipf_nat_icmpquerytype(orgicmp->icmp_type)) {
   3631 			data[0] = fin->fin_data[0];
   3632 			data[1] = fin->fin_data[1];
   3633 			fin->fin_data[0] = 0;
   3634 			fin->fin_data[1] = orgicmp->icmp_id;
   3635 
   3636 			flags = IPN_ICMPERR|IPN_ICMPQUERY;
   3637 			/*
   3638 			 * NOTE : dir refers to the direction of the original
   3639 			 *        ip packet. By definition the icmp error
   3640 			 *        message flows in the opposite direction.
   3641 			 */
   3642 			if (dir == NAT_INBOUND)
   3643 				nat = ipf_nat_inlookup(fin, flags, p,
   3644 						       oip->ip_dst,
   3645 						       oip->ip_src);
   3646 			else
   3647 				nat = ipf_nat_outlookup(fin, flags, p,
   3648 							oip->ip_dst,
   3649 							oip->ip_src);
   3650 			fin->fin_data[0] = data[0];
   3651 			fin->fin_data[1] = data[1];
   3652 			return nat;
   3653 		}
   3654 	}
   3655 
   3656 	if (flags & IPN_TCPUDP) {
   3657 		minlen += 8;		/* + 64bits of data to get ports */
   3658 		/* TRACE (fin,minlen) */
   3659 		if (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen) {
   3660 			ATOMIC_INCL(nside->ns_icmp_short);
   3661 			return NULL;
   3662 		}
   3663 
   3664 		data[0] = fin->fin_data[0];
   3665 		data[1] = fin->fin_data[1];
   3666 		tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
   3667 		fin->fin_data[0] = ntohs(tcp->th_dport);
   3668 		fin->fin_data[1] = ntohs(tcp->th_sport);
   3669 
   3670 		if (dir == NAT_INBOUND) {
   3671 			nat = ipf_nat_inlookup(fin, flags, p, oip->ip_dst,
   3672 					       oip->ip_src);
   3673 		} else {
   3674 			nat = ipf_nat_outlookup(fin, flags, p, oip->ip_dst,
   3675 					    oip->ip_src);
   3676 		}
   3677 		fin->fin_data[0] = data[0];
   3678 		fin->fin_data[1] = data[1];
   3679 		return nat;
   3680 	}
   3681 	if (dir == NAT_INBOUND)
   3682 		nat = ipf_nat_inlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
   3683 	else
   3684 		nat = ipf_nat_outlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
   3685 
   3686 	return nat;
   3687 }
   3688 
   3689 
   3690 /* ------------------------------------------------------------------------ */
   3691 /* Function:    ipf_nat_icmperror                                           */
   3692 /* Returns:     nat_t* - point to matching NAT structure                    */
   3693 /* Parameters:  fin(I)    - pointer to packet information                   */
   3694 /*              nflags(I) - NAT flags for this packet                       */
   3695 /*              dir(I)    - direction of packet (in/out)                    */
   3696 /*                                                                          */
   3697 /* Fix up an ICMP packet which is an error message for an existing NAT      */
   3698 /* session.  This will correct both packet header data and checksums.       */
   3699 /*                                                                          */
   3700 /* This should *ONLY* be used for incoming ICMP error packets to make sure  */
   3701 /* a NAT'd ICMP packet gets correctly recognised.                           */
   3702 /* ------------------------------------------------------------------------ */
   3703 nat_t *
   3704 ipf_nat_icmperror(fr_info_t *fin, u_int *nflags, int dir)
   3705 {
   3706 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3707 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3708 	u_32_t sum1, sum2, sumd, sumd2;
   3709 	struct in_addr a1, a2, a3, a4;
   3710 	int flags, dlen, odst;
   3711 	icmphdr_t *icmp;
   3712 	u_short *csump;
   3713 	tcphdr_t *tcp;
   3714 	nat_t *nat;
   3715 	ip_t *oip;
   3716 	void *dp;
   3717 
   3718 	if ((fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   3719 		NBUMPSIDED(fin->fin_out, ns_icmp_short);
   3720 		return NULL;
   3721 	}
   3722 
   3723 	/*
   3724 	 * ipf_nat_icmperrorlookup() will return NULL for `defective' packets.
   3725 	 */
   3726 	if ((fin->fin_v != 4) || !(nat = ipf_nat_icmperrorlookup(fin, dir))) {
   3727 		NBUMPSIDED(fin->fin_out, ns_icmp_notfound);
   3728 		return NULL;
   3729 	}
   3730 
   3731 	tcp = NULL;
   3732 	csump = NULL;
   3733 	flags = 0;
   3734 	sumd2 = 0;
   3735 	*nflags = IPN_ICMPERR;
   3736 	icmp = fin->fin_dp;
   3737 	oip = (ip_t *)&icmp->icmp_ip;
   3738 	dp = (((char *)oip) + (IP_HL(oip) << 2));
   3739 	if (oip->ip_p == IPPROTO_TCP) {
   3740 		tcp = (tcphdr_t *)dp;
   3741 		csump = (u_short *)&tcp->th_sum;
   3742 		flags = IPN_TCP;
   3743 	} else if (oip->ip_p == IPPROTO_UDP) {
   3744 		udphdr_t *udp;
   3745 
   3746 		udp = (udphdr_t *)dp;
   3747 		tcp = (tcphdr_t *)dp;
   3748 		csump = (u_short *)&udp->uh_sum;
   3749 		flags = IPN_UDP;
   3750 	} else if (oip->ip_p == IPPROTO_ICMP)
   3751 		flags = IPN_ICMPQUERY;
   3752 	dlen = fin->fin_plen - ((char *)dp - (char *)fin->fin_ip);
   3753 
   3754 	/*
   3755 	 * Need to adjust ICMP header to include the real IP#'s and
   3756 	 * port #'s.  Only apply a checksum change relative to the
   3757 	 * IP address change as it will be modified again in ipf_nat_checkout
   3758 	 * for both address and port.  Two checksum changes are
   3759 	 * necessary for the two header address changes.  Be careful
   3760 	 * to only modify the checksum once for the port # and twice
   3761 	 * for the IP#.
   3762 	 */
   3763 
   3764 	/*
   3765 	 * Step 1
   3766 	 * Fix the IP addresses in the offending IP packet. You also need
   3767 	 * to adjust the IP header checksum of that offending IP packet.
   3768 	 *
   3769 	 * Normally, you would expect that the ICMP checksum of the
   3770 	 * ICMP error message needs to be adjusted as well for the
   3771 	 * IP address change in oip.
   3772 	 * However, this is a NOP, because the ICMP checksum is
   3773 	 * calculated over the complete ICMP packet, which includes the
   3774 	 * changed oip IP addresses and oip->ip_sum. However, these
   3775 	 * two changes cancel each other out (if the delta for
   3776 	 * the IP address is x, then the delta for ip_sum is minus x),
   3777 	 * so no change in the icmp_cksum is necessary.
   3778 	 *
   3779 	 * Inbound ICMP
   3780 	 * ------------
   3781 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   3782 	 * - response to outgoing packet (a,b)=>(c,b) (OIP_SRC=c,OIP_DST=b)
   3783 	 * - OIP_SRC(c)=nat_newsrcip,          OIP_DST(b)=nat_newdstip
   3784 	 *=> OIP_SRC(c)=nat_oldsrcip,          OIP_DST(b)=nat_olddstip
   3785 	 *
   3786 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   3787 	 * - response to outgoing packet (c,a)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   3788 	 * - OIP_SRC(b)=nat_olddstip,          OIP_DST(a)=nat_oldsrcip
   3789 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3790 	 *
   3791 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   3792 	 * - response to outgoing packet (a,b)=>(c,d) (OIP_SRC=c,OIP_DST=d)
   3793 	 * - OIP_SRC(c)=nat_newsrcip,          OIP_DST(d)=nat_newdstip
   3794 	 *=> OIP_SRC(c)=nat_oldsrcip,          OIP_DST(d)=nat_olddstip
   3795 	 *
   3796 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   3797 	 * - response to outgoing packet (d,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   3798 	 * - OIP_SRC(b)=nat_olddstip,          OIP_DST(a)=nat_oldsrcip
   3799 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3800 	 *
   3801 	 * Outbound ICMP
   3802 	 * -------------
   3803 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   3804 	 * - response to incoming packet (b,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   3805 	 * - OIP_SRC(b)=nat_olddstip,          OIP_DST(a)=nat_oldsrcip
   3806 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3807 	 *
   3808 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   3809 	 * - response to incoming packet (a,b)=>(a,c) (OIP_SRC=a,OIP_DST=c)
   3810 	 * - OIP_SRC(a)=nat_newsrcip,          OIP_DST(c)=nat_newdstip
   3811 	 *=> OIP_SRC(a)=nat_oldsrcip,          OIP_DST(c)=nat_olddstip
   3812 	 *
   3813 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   3814 	 * - response to incoming packet (d,c)=>(b,a) (OIP_SRC=c,OIP_DST=d)
   3815 	 * - OIP_SRC(c)=nat_olddstip,          OIP_DST(d)=nat_oldsrcip
   3816 	 *=> OIP_SRC(b)=nat_newdstip,          OIP_DST(a)=nat_newsrcip
   3817 	 *
   3818 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   3819 	 * - response to incoming packet (a,b)=>(c,d) (OIP_SRC=b,OIP_DST=a)
   3820 	 * - OIP_SRC(b)=nat_newsrcip,          OIP_DST(a)=nat_newdstip
   3821 	 *=> OIP_SRC(a)=nat_oldsrcip,          OIP_DST(c)=nat_olddstip
   3822 	 */
   3823 
   3824 	if (((fin->fin_out == 0) && ((nat->nat_redir & NAT_MAP) != 0)) ||
   3825 	    ((fin->fin_out == 1) && ((nat->nat_redir & NAT_REDIRECT) != 0))) {
   3826 		a1.s_addr = ntohl(nat->nat_osrcaddr);
   3827 		a4.s_addr = ntohl(oip->ip_src.s_addr);
   3828 		a3.s_addr = ntohl(nat->nat_odstaddr);
   3829 		a2.s_addr = ntohl(oip->ip_dst.s_addr);
   3830 		oip->ip_src.s_addr = htonl(a1.s_addr);
   3831 		oip->ip_dst.s_addr = htonl(a3.s_addr);
   3832 		odst = 1;
   3833 	} else {
   3834 		a1.s_addr = ntohl(nat->nat_ndstaddr);
   3835 		a2.s_addr = ntohl(oip->ip_dst.s_addr);
   3836 		a3.s_addr = ntohl(nat->nat_nsrcaddr);
   3837 		a4.s_addr = ntohl(oip->ip_src.s_addr);
   3838 		oip->ip_dst.s_addr = htonl(a3.s_addr);
   3839 		oip->ip_src.s_addr = htonl(a1.s_addr);
   3840 		odst = 0;
   3841 	}
   3842 	sum1 = 0;
   3843 	sum2 = 0;
   3844 	sumd = 0;
   3845 	CALC_SUMD(a2.s_addr, a3.s_addr, sum1);
   3846 	CALC_SUMD(a4.s_addr, a1.s_addr, sum2);
   3847 	sumd = sum2 + sum1;
   3848 	if (sumd != 0)
   3849 		ipf_fix_datacksum(&oip->ip_sum, sumd);
   3850 
   3851 	sumd2 = sumd;
   3852 	sum1 = 0;
   3853 	sum2 = 0;
   3854 
   3855 	/*
   3856 	 * Fix UDP pseudo header checksum to compensate for the
   3857 	 * IP address change.
   3858 	 */
   3859 	if (((flags & IPN_TCPUDP) != 0) && (dlen >= 4)) {
   3860 		u_32_t sum3, sum4, sumt;
   3861 
   3862 		/*
   3863 		 * Step 2 :
   3864 		 * For offending TCP/UDP IP packets, translate the ports as
   3865 		 * well, based on the NAT specification. Of course such
   3866 		 * a change may be reflected in the ICMP checksum as well.
   3867 		 *
   3868 		 * Since the port fields are part of the TCP/UDP checksum
   3869 		 * of the offending IP packet, you need to adjust that checksum
   3870 		 * as well... except that the change in the port numbers should
   3871 		 * be offset by the checksum change.  However, the TCP/UDP
   3872 		 * checksum will also need to change if there has been an
   3873 		 * IP address change.
   3874 		 */
   3875 		if (odst == 1) {
   3876 			sum1 = ntohs(nat->nat_osport);
   3877 			sum4 = ntohs(tcp->th_sport);
   3878 			sum3 = ntohs(nat->nat_odport);
   3879 			sum2 = ntohs(tcp->th_dport);
   3880 
   3881 			tcp->th_sport = htons(sum1);
   3882 			tcp->th_dport = htons(sum3);
   3883 		} else {
   3884 			sum1 = ntohs(nat->nat_ndport);
   3885 			sum2 = ntohs(tcp->th_dport);
   3886 			sum3 = ntohs(nat->nat_nsport);
   3887 			sum4 = ntohs(tcp->th_sport);
   3888 
   3889 			tcp->th_dport = htons(sum3);
   3890 			tcp->th_sport = htons(sum1);
   3891 		}
   3892 		CALC_SUMD(sum4, sum1, sumt);
   3893 		sumd += sumt;
   3894 		CALC_SUMD(sum2, sum3, sumt);
   3895 		sumd += sumt;
   3896 
   3897 		if (sumd != 0 || sumd2 != 0) {
   3898 			/*
   3899 			 * At this point, sumd is the delta to apply to the
   3900 			 * TCP/UDP header, given the changes in both the IP
   3901 			 * address and the ports and sumd2 is the delta to
   3902 			 * apply to the ICMP header, given the IP address
   3903 			 * change delta that may need to be applied to the
   3904 			 * TCP/UDP checksum instead.
   3905 			 *
   3906 			 * If we will both the IP and TCP/UDP checksums
   3907 			 * then the ICMP checksum changes by the address
   3908 			 * delta applied to the TCP/UDP checksum.  If we
   3909 			 * do not change the TCP/UDP checksum them we
   3910 			 * apply the delta in ports to the ICMP checksum.
   3911 			 */
   3912 			if (oip->ip_p == IPPROTO_UDP) {
   3913 				if ((dlen >= 8) && (*csump != 0)) {
   3914 					ipf_fix_datacksum(csump, sumd);
   3915 				} else {
   3916 					CALC_SUMD(sum1, sum4, sumd2);
   3917 					CALC_SUMD(sum3, sum2, sumt);
   3918 					sumd2 += sumt;
   3919 				}
   3920 			} else if (oip->ip_p == IPPROTO_TCP) {
   3921 				if (dlen >= 18) {
   3922 					ipf_fix_datacksum(csump, sumd);
   3923 				} else {
   3924 					CALC_SUMD(sum1, sum4, sumd2);
   3925 					CALC_SUMD(sum3, sum2, sumt);
   3926 					sumd2 += sumt;
   3927 				}
   3928 			}
   3929 			if (sumd2 != 0) {
   3930 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   3931 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   3932 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   3933 				ipf_fix_incksum(0, &icmp->icmp_cksum, sumd2, 0);
   3934 			}
   3935 		}
   3936 	} else if (((flags & IPN_ICMPQUERY) != 0) && (dlen >= 8)) {
   3937 		icmphdr_t *orgicmp;
   3938 
   3939 		/*
   3940 		 * XXX - what if this is bogus hl and we go off the end ?
   3941 		 * In this case, ipf_nat_icmperrorlookup() will have
   3942 		 * returned NULL.
   3943 		 */
   3944 		orgicmp = (icmphdr_t *)dp;
   3945 
   3946 		if (odst == 1) {
   3947 			if (orgicmp->icmp_id != nat->nat_osport) {
   3948 
   3949 				/*
   3950 				 * Fix ICMP checksum (of the offening ICMP
   3951 				 * query packet) to compensate the change
   3952 				 * in the ICMP id of the offending ICMP
   3953 				 * packet.
   3954 				 *
   3955 				 * Since you modify orgicmp->icmp_id with
   3956 				 * a delta (say x) and you compensate that
   3957 				 * in origicmp->icmp_cksum with a delta
   3958 				 * minus x, you don't have to adjust the
   3959 				 * overall icmp->icmp_cksum
   3960 				 */
   3961 				sum1 = ntohs(orgicmp->icmp_id);
   3962 				sum2 = ntohs(nat->nat_oicmpid);
   3963 				CALC_SUMD(sum1, sum2, sumd);
   3964 				orgicmp->icmp_id = nat->nat_oicmpid;
   3965 				ipf_fix_datacksum(&orgicmp->icmp_cksum, sumd);
   3966 			}
   3967 		} /* nat_dir == NAT_INBOUND is impossible for icmp queries */
   3968 	}
   3969 	return nat;
   3970 }
   3971 
   3972 
   3973 /*
   3974  *       MAP-IN    MAP-OUT   RDR-IN   RDR-OUT
   3975  * osrc    X       == src    == src      X
   3976  * odst    X       == dst    == dst      X
   3977  * nsrc  == dst      X         X      == dst
   3978  * ndst  == src      X         X      == src
   3979  * MAP = NAT_OUTBOUND, RDR = NAT_INBOUND
   3980  */
   3981 /*
   3982  * NB: these lookups don't lock access to the list, it assumed that it has
   3983  * already been done!
   3984  */
   3985 /* ------------------------------------------------------------------------ */
   3986 /* Function:    ipf_nat_inlookup                                            */
   3987 /* Returns:     nat_t* - NULL == no match,                                  */
   3988 /*                       else pointer to matching NAT entry                 */
   3989 /* Parameters:  fin(I)    - pointer to packet information                   */
   3990 /*              flags(I)  - NAT flags for this packet                       */
   3991 /*              p(I)      - protocol for this packet                        */
   3992 /*              src(I)    - source IP address                               */
   3993 /*              mapdst(I) - destination IP address                          */
   3994 /*                                                                          */
   3995 /* Lookup a nat entry based on the mapped destination ip address/port and   */
   3996 /* real source address/port.  We use this lookup when receiving a packet,   */
   3997 /* we're looking for a table entry, based on the destination address.       */
   3998 /*                                                                          */
   3999 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   4000 /*                                                                          */
   4001 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   4002 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   4003 /*                                                                          */
   4004 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   4005 /*            the packet is of said protocol                                */
   4006 /* ------------------------------------------------------------------------ */
   4007 nat_t *
   4008 ipf_nat_inlookup(fr_info_t *fin, u_int flags, u_int p, struct in_addr src,
   4009     struct in_addr mapdst)
   4010 {
   4011 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4012 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   4013 	u_short sport, dport;
   4014 	grehdr_t *gre;
   4015 	ipnat_t *ipn;
   4016 	u_int sflags;
   4017 	nat_t *nat;
   4018 	int nflags;
   4019 	u_32_t dst;
   4020 	void *ifp;
   4021 	u_int hv, rhv;
   4022 
   4023 	ifp = fin->fin_ifp;
   4024 	gre = NULL;
   4025 	dst = mapdst.s_addr;
   4026 	sflags = flags & NAT_TCPUDPICMP;
   4027 
   4028 	switch (p)
   4029 	{
   4030 	case IPPROTO_TCP :
   4031 	case IPPROTO_UDP :
   4032 		sport = htons(fin->fin_data[0]);
   4033 		dport = htons(fin->fin_data[1]);
   4034 		break;
   4035 	case IPPROTO_ICMP :
   4036 		if (flags & IPN_ICMPERR) {
   4037 			sport = fin->fin_data[1];
   4038 			dport = 0;
   4039 		} else {
   4040 			dport = fin->fin_data[1];
   4041 			sport = 0;
   4042 		}
   4043 		break;
   4044 	default :
   4045 		sport = 0;
   4046 		dport = 0;
   4047 		break;
   4048 	}
   4049 
   4050 
   4051 	if ((flags & SI_WILDP) != 0)
   4052 		goto find_in_wild_ports;
   4053 
   4054 	rhv = NAT_HASH_FN(dst, dport, 0xffffffff);
   4055 	rhv = NAT_HASH_FN(src.s_addr, rhv + sport, 0xffffffff);
   4056 	hv = rhv % softn->ipf_nat_table_sz;
   4057 	nat = softn->ipf_nat_table[1][hv];
   4058 	/* TRACE dst, dport, src, sport, hv, nat */
   4059 
   4060 	for (; nat; nat = nat->nat_hnext[1]) {
   4061 		if (nat->nat_ifps[0] != NULL) {
   4062 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   4063 				continue;
   4064 		}
   4065 
   4066 		if (nat->nat_pr[0] != p)
   4067 			continue;
   4068 
   4069 		switch (nat->nat_dir)
   4070 		{
   4071 		case NAT_INBOUND :
   4072 		case NAT_DIVERTIN :
   4073 			if (nat->nat_v[0] != 4)
   4074 				continue;
   4075 			if (nat->nat_osrcaddr != src.s_addr ||
   4076 			    nat->nat_odstaddr != dst)
   4077 				continue;
   4078 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4079 				if (nat->nat_osport != sport)
   4080 					continue;
   4081 				if (nat->nat_odport != dport)
   4082 					continue;
   4083 
   4084 			} else if (p == IPPROTO_ICMP) {
   4085 				if (nat->nat_osport != dport) {
   4086 					continue;
   4087 				}
   4088 			}
   4089 			break;
   4090 		case NAT_DIVERTOUT :
   4091 			if (nat->nat_dlocal)
   4092 				continue;
   4093 		case NAT_OUTBOUND :
   4094 			if (nat->nat_v[1] != 4)
   4095 				continue;
   4096 			if (nat->nat_dlocal)
   4097 				continue;
   4098 			if (nat->nat_dlocal)
   4099 				continue;
   4100 			if (nat->nat_ndstaddr != src.s_addr ||
   4101 			    nat->nat_nsrcaddr != dst)
   4102 				continue;
   4103 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4104 				if (nat->nat_ndport != sport)
   4105 					continue;
   4106 				if (nat->nat_nsport != dport)
   4107 					continue;
   4108 
   4109 			} else if (p == IPPROTO_ICMP) {
   4110 				if (nat->nat_osport != dport) {
   4111 					continue;
   4112 				}
   4113 			}
   4114 			break;
   4115 		}
   4116 
   4117 
   4118 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4119 			ipn = nat->nat_ptr;
   4120 			if ((ipn != NULL) && (nat->nat_aps != NULL))
   4121 				if (ipf_proxy_match(fin, nat) != 0)
   4122 					continue;
   4123 		}
   4124 		if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   4125 			nat->nat_ifps[0] = ifp;
   4126 			nat->nat_mtu[0] = GETIFMTU_4(ifp);
   4127 		}
   4128 		return nat;
   4129 	}
   4130 
   4131 	/*
   4132 	 * So if we didn't find it but there are wildcard members in the hash
   4133 	 * table, go back and look for them.  We do this search and update here
   4134 	 * because it is modifying the NAT table and we want to do this only
   4135 	 * for the first packet that matches.  The exception, of course, is
   4136 	 * for "dummy" (FI_IGNORE) lookups.
   4137 	 */
   4138 find_in_wild_ports:
   4139 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   4140 		NBUMPSIDEX(0, ns_lookup_miss, ns_lookup_miss_0);
   4141 		return NULL;
   4142 	}
   4143 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   4144 		NBUMPSIDEX(0, ns_lookup_nowild, ns_lookup_nowild_0);
   4145 		return NULL;
   4146 	}
   4147 
   4148 	RWLOCK_EXIT(&softc->ipf_nat);
   4149 
   4150 	hv = NAT_HASH_FN(dst, 0, 0xffffffff);
   4151 	hv = NAT_HASH_FN(src.s_addr, hv, softn->ipf_nat_table_sz);
   4152 	WRITE_ENTER(&softc->ipf_nat);
   4153 
   4154 	nat = softn->ipf_nat_table[1][hv];
   4155 	/* TRACE dst, src, hv, nat */
   4156 	for (; nat; nat = nat->nat_hnext[1]) {
   4157 		if (nat->nat_ifps[0] != NULL) {
   4158 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   4159 				continue;
   4160 		}
   4161 
   4162 		if (nat->nat_pr[0] != fin->fin_p)
   4163 			continue;
   4164 
   4165 		switch (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND))
   4166 		{
   4167 		case NAT_INBOUND :
   4168 			if (nat->nat_v[0] != 4)
   4169 				continue;
   4170 			if (nat->nat_osrcaddr != src.s_addr ||
   4171 			    nat->nat_odstaddr != dst)
   4172 				continue;
   4173 			break;
   4174 		case NAT_OUTBOUND :
   4175 			if (nat->nat_v[1] != 4)
   4176 				continue;
   4177 			if (nat->nat_ndstaddr != src.s_addr ||
   4178 			    nat->nat_nsrcaddr != dst)
   4179 				continue;
   4180 			break;
   4181 		}
   4182 
   4183 		nflags = nat->nat_flags;
   4184 		if (!(nflags & (NAT_TCPUDP|SI_WILDP)))
   4185 			continue;
   4186 
   4187 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nflags,
   4188 				   NAT_INBOUND) == 1) {
   4189 			if ((fin->fin_flx & FI_IGNORE) != 0)
   4190 				break;
   4191 			if ((nflags & SI_CLONE) != 0) {
   4192 				nat = ipf_nat_clone(fin, nat);
   4193 				if (nat == NULL)
   4194 					break;
   4195 			} else {
   4196 				MUTEX_ENTER(&softn->ipf_nat_new);
   4197 				softn->ipf_nat_stats.ns_wilds--;
   4198 				MUTEX_EXIT(&softn->ipf_nat_new);
   4199 			}
   4200 
   4201 			if (nat->nat_dir == NAT_INBOUND) {
   4202 				if (nat->nat_osport == 0) {
   4203 					nat->nat_osport = sport;
   4204 					nat->nat_nsport = sport;
   4205 				}
   4206 				if (nat->nat_odport == 0) {
   4207 					nat->nat_odport = dport;
   4208 					nat->nat_ndport = dport;
   4209 				}
   4210 			} else if (nat->nat_dir == NAT_OUTBOUND) {
   4211 				if (nat->nat_osport == 0) {
   4212 					nat->nat_osport = dport;
   4213 					nat->nat_nsport = dport;
   4214 				}
   4215 				if (nat->nat_odport == 0) {
   4216 					nat->nat_odport = sport;
   4217 					nat->nat_ndport = sport;
   4218 				}
   4219 			}
   4220 			if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   4221 				nat->nat_ifps[0] = ifp;
   4222 				nat->nat_mtu[0] = GETIFMTU_4(ifp);
   4223 			}
   4224 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   4225 			ipf_nat_tabmove(softn, nat);
   4226 			break;
   4227 		}
   4228 	}
   4229 
   4230 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   4231 
   4232 	if (nat == NULL) {
   4233 		NBUMPSIDE(0, ns_lookup_miss);
   4234 	}
   4235 	return nat;
   4236 }
   4237 
   4238 
   4239 /* ------------------------------------------------------------------------ */
   4240 /* Function:    ipf_nat_tabmove                                             */
   4241 /* Returns:     Nil                                                         */
   4242 /* Parameters:  softn(I) - pointer to NAT context structure                 */
   4243 /*              nat(I)   - pointer to NAT structure                         */
   4244 /* Write Lock:  ipf_nat                                                     */
   4245 /*                                                                          */
   4246 /* This function is only called for TCP/UDP NAT table entries where the     */
   4247 /* original was placed in the table without hashing on the ports and we now */
   4248 /* want to include hashing on port numbers.                                 */
   4249 /* ------------------------------------------------------------------------ */
   4250 static void
   4251 ipf_nat_tabmove(ipf_nat_softc_t *softn, nat_t *nat)
   4252 {
   4253 	u_int hv0, hv1, rhv0, rhv1;
   4254 	natstat_t *nsp;
   4255 	nat_t **natp;
   4256 
   4257 	if (nat->nat_flags & SI_CLONE)
   4258 		return;
   4259 
   4260 	nsp = &softn->ipf_nat_stats;
   4261 	/*
   4262 	 * Remove the NAT entry from the old location
   4263 	 */
   4264 	if (nat->nat_hnext[0])
   4265 		nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
   4266 	*nat->nat_phnext[0] = nat->nat_hnext[0];
   4267 	nsp->ns_side[0].ns_bucketlen[nat->nat_hv[0] %
   4268 				     softn->ipf_nat_table_sz]--;
   4269 
   4270 	if (nat->nat_hnext[1])
   4271 		nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
   4272 	*nat->nat_phnext[1] = nat->nat_hnext[1];
   4273 	nsp->ns_side[1].ns_bucketlen[nat->nat_hv[1] %
   4274 				     softn->ipf_nat_table_sz]--;
   4275 
   4276 	/*
   4277 	 * Add into the NAT table in the new position
   4278 	 */
   4279 	rhv0 = NAT_HASH_FN(nat->nat_osrcaddr, nat->nat_osport, 0xffffffff);
   4280 	rhv0 = NAT_HASH_FN(nat->nat_odstaddr, rhv0 + nat->nat_odport,
   4281 			   0xffffffff);
   4282 	rhv1 = NAT_HASH_FN(nat->nat_nsrcaddr, nat->nat_nsport, 0xffffffff);
   4283 	rhv1 = NAT_HASH_FN(nat->nat_ndstaddr, rhv1 + nat->nat_ndport,
   4284 			   0xffffffff);
   4285 
   4286 	hv0 = rhv0 % softn->ipf_nat_table_sz;
   4287 	hv1 = rhv1 % softn->ipf_nat_table_sz;
   4288 
   4289 	if (nat->nat_dir == NAT_INBOUND || nat->nat_dir == NAT_DIVERTIN) {
   4290 		u_int swap;
   4291 
   4292 		swap = hv0;
   4293 		hv0 = hv1;
   4294 		hv1 = swap;
   4295 	}
   4296 
   4297 	/* TRACE nat_osrcaddr, nat_osport, nat_odstaddr, nat_odport, hv0 */
   4298 	/* TRACE nat_nsrcaddr, nat_nsport, nat_ndstaddr, nat_ndport, hv1 */
   4299 
   4300 	nat->nat_hv[0] = rhv0;
   4301 	natp = &softn->ipf_nat_table[0][hv0];
   4302 	if (*natp)
   4303 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   4304 	nat->nat_phnext[0] = natp;
   4305 	nat->nat_hnext[0] = *natp;
   4306 	*natp = nat;
   4307 	nsp->ns_side[0].ns_bucketlen[hv0]++;
   4308 
   4309 	nat->nat_hv[1] = rhv1;
   4310 	natp = &softn->ipf_nat_table[1][hv1];
   4311 	if (*natp)
   4312 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   4313 	nat->nat_phnext[1] = natp;
   4314 	nat->nat_hnext[1] = *natp;
   4315 	*natp = nat;
   4316 	nsp->ns_side[1].ns_bucketlen[hv1]++;
   4317 }
   4318 
   4319 
   4320 /* ------------------------------------------------------------------------ */
   4321 /* Function:    ipf_nat_outlookup                                           */
   4322 /* Returns:     nat_t* - NULL == no match,                                  */
   4323 /*                       else pointer to matching NAT entry                 */
   4324 /* Parameters:  fin(I)   - pointer to packet information                    */
   4325 /*              flags(I) - NAT flags for this packet                        */
   4326 /*              p(I)     - protocol for this packet                         */
   4327 /*              src(I)   - source IP address                                */
   4328 /*              dst(I)   - destination IP address                           */
   4329 /*              rw(I)    - 1 == write lock on  held, 0 == read lock.        */
   4330 /*                                                                          */
   4331 /* Lookup a nat entry based on the source 'real' ip address/port and        */
   4332 /* destination address/port.  We use this lookup when sending a packet out, */
   4333 /* we're looking for a table entry, based on the source address.            */
   4334 /*                                                                          */
   4335 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   4336 /*                                                                          */
   4337 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   4338 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   4339 /*                                                                          */
   4340 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   4341 /*            the packet is of said protocol                                */
   4342 /* ------------------------------------------------------------------------ */
   4343 nat_t *
   4344 ipf_nat_outlookup(fr_info_t *fin, u_int flags, u_int p, struct in_addr src,
   4345    struct in_addr dst)
   4346 {
   4347 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4348 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   4349 	u_short sport, dport;
   4350 	u_int sflags;
   4351 	ipnat_t *ipn;
   4352 	nat_t *nat;
   4353 	void *ifp;
   4354 	u_int hv;
   4355 
   4356 	ifp = fin->fin_ifp;
   4357 	sflags = flags & IPN_TCPUDPICMP;
   4358 	sport = 0;
   4359 	dport = 0;
   4360 
   4361 	switch (p)
   4362 	{
   4363 	case IPPROTO_TCP :
   4364 	case IPPROTO_UDP :
   4365 		sport = htons(fin->fin_data[0]);
   4366 		dport = htons(fin->fin_data[1]);
   4367 		break;
   4368 	case IPPROTO_ICMP :
   4369 		if (flags & IPN_ICMPERR)
   4370 			sport = fin->fin_data[1];
   4371 		else
   4372 			dport = fin->fin_data[1];
   4373 		break;
   4374 	default :
   4375 		break;
   4376 	}
   4377 
   4378 	if ((flags & SI_WILDP) != 0)
   4379 		goto find_out_wild_ports;
   4380 
   4381 	hv = NAT_HASH_FN(src.s_addr, sport, 0xffffffff);
   4382 	hv = NAT_HASH_FN(dst.s_addr, hv + dport, softn->ipf_nat_table_sz);
   4383 	nat = softn->ipf_nat_table[0][hv];
   4384 
   4385 	/* TRACE src, sport, dst, dport, hv, nat */
   4386 
   4387 	for (; nat; nat = nat->nat_hnext[0]) {
   4388 		if (nat->nat_ifps[1] != NULL) {
   4389 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   4390 				continue;
   4391 		}
   4392 
   4393 		if (nat->nat_pr[1] != p)
   4394 			continue;
   4395 
   4396 		switch (nat->nat_dir)
   4397 		{
   4398 		case NAT_INBOUND :
   4399 		case NAT_DIVERTIN :
   4400 			if (nat->nat_v[1] != 4)
   4401 				continue;
   4402 			if (nat->nat_ndstaddr != src.s_addr ||
   4403 			    nat->nat_nsrcaddr != dst.s_addr)
   4404 				continue;
   4405 
   4406 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4407 				if (nat->nat_ndport != sport)
   4408 					continue;
   4409 				if (nat->nat_nsport != dport)
   4410 					continue;
   4411 
   4412 			} else if (p == IPPROTO_ICMP) {
   4413 				if (nat->nat_osport != dport) {
   4414 					continue;
   4415 				}
   4416 			}
   4417 			break;
   4418 		case NAT_OUTBOUND :
   4419 		case NAT_DIVERTOUT :
   4420 			if (nat->nat_v[0] != 4)
   4421 				continue;
   4422 			if (nat->nat_osrcaddr != src.s_addr ||
   4423 			    nat->nat_odstaddr != dst.s_addr)
   4424 				continue;
   4425 
   4426 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   4427 				if (nat->nat_odport != dport)
   4428 					continue;
   4429 				if (nat->nat_osport != sport)
   4430 					continue;
   4431 
   4432 			} else if (p == IPPROTO_ICMP) {
   4433 				if (nat->nat_osport != dport) {
   4434 					continue;
   4435 				}
   4436 			}
   4437 			break;
   4438 		}
   4439 
   4440 		ipn = nat->nat_ptr;
   4441 		if ((ipn != NULL) && (nat->nat_aps != NULL))
   4442 			if (ipf_proxy_match(fin, nat) != 0)
   4443 				continue;
   4444 
   4445 		if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   4446 			nat->nat_ifps[1] = ifp;
   4447 			nat->nat_mtu[1] = GETIFMTU_4(ifp);
   4448 		}
   4449 		return nat;
   4450 	}
   4451 
   4452 	/*
   4453 	 * So if we didn't find it but there are wildcard members in the hash
   4454 	 * table, go back and look for them.  We do this search and update here
   4455 	 * because it is modifying the NAT table and we want to do this only
   4456 	 * for the first packet that matches.  The exception, of course, is
   4457 	 * for "dummy" (FI_IGNORE) lookups.
   4458 	 */
   4459 find_out_wild_ports:
   4460 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   4461 		NBUMPSIDEX(1, ns_lookup_miss, ns_lookup_miss_1);
   4462 		return NULL;
   4463 	}
   4464 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   4465 		NBUMPSIDEX(1, ns_lookup_nowild, ns_lookup_nowild_1);
   4466 		return NULL;
   4467 	}
   4468 
   4469 	RWLOCK_EXIT(&softc->ipf_nat);
   4470 
   4471 	hv = NAT_HASH_FN(src.s_addr, 0, 0xffffffff);
   4472 	hv = NAT_HASH_FN(dst.s_addr, hv, softn->ipf_nat_table_sz);
   4473 
   4474 	WRITE_ENTER(&softc->ipf_nat);
   4475 
   4476 	nat = softn->ipf_nat_table[0][hv];
   4477 	for (; nat; nat = nat->nat_hnext[0]) {
   4478 		if (nat->nat_ifps[1] != NULL) {
   4479 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   4480 				continue;
   4481 		}
   4482 
   4483 		if (nat->nat_pr[1] != fin->fin_p)
   4484 			continue;
   4485 
   4486 		switch (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND))
   4487 		{
   4488 		case NAT_INBOUND :
   4489 			if (nat->nat_v[1] != 4)
   4490 				continue;
   4491 			if (nat->nat_ndstaddr != src.s_addr ||
   4492 			    nat->nat_nsrcaddr != dst.s_addr)
   4493 				continue;
   4494 			break;
   4495 		case NAT_OUTBOUND :
   4496 			if (nat->nat_v[0] != 4)
   4497 				continue;
   4498 			if (nat->nat_osrcaddr != src.s_addr ||
   4499 			    nat->nat_odstaddr != dst.s_addr)
   4500 				continue;
   4501 			break;
   4502 		}
   4503 
   4504 		if (!(nat->nat_flags & (NAT_TCPUDP|SI_WILDP)))
   4505 			continue;
   4506 
   4507 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nat->nat_flags,
   4508 				   NAT_OUTBOUND) == 1) {
   4509 			if ((fin->fin_flx & FI_IGNORE) != 0)
   4510 				break;
   4511 			if ((nat->nat_flags & SI_CLONE) != 0) {
   4512 				nat = ipf_nat_clone(fin, nat);
   4513 				if (nat == NULL)
   4514 					break;
   4515 			} else {
   4516 				MUTEX_ENTER(&softn->ipf_nat_new);
   4517 				softn->ipf_nat_stats.ns_wilds--;
   4518 				MUTEX_EXIT(&softn->ipf_nat_new);
   4519 			}
   4520 
   4521 			if (nat->nat_dir == NAT_OUTBOUND) {
   4522 				if (nat->nat_osport == 0) {
   4523 					nat->nat_osport = sport;
   4524 					nat->nat_nsport = sport;
   4525 				}
   4526 				if (nat->nat_odport == 0) {
   4527 					nat->nat_odport = dport;
   4528 					nat->nat_ndport = dport;
   4529 				}
   4530 			} else if (nat->nat_dir == NAT_INBOUND) {
   4531 				if (nat->nat_osport == 0) {
   4532 					nat->nat_osport = dport;
   4533 					nat->nat_nsport = dport;
   4534 				}
   4535 				if (nat->nat_odport == 0) {
   4536 					nat->nat_odport = sport;
   4537 					nat->nat_ndport = sport;
   4538 				}
   4539 			}
   4540 			if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   4541 				nat->nat_ifps[1] = ifp;
   4542 				nat->nat_mtu[1] = GETIFMTU_4(ifp);
   4543 			}
   4544 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   4545 			ipf_nat_tabmove(softn, nat);
   4546 			break;
   4547 		}
   4548 	}
   4549 
   4550 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   4551 
   4552 	if (nat == NULL) {
   4553 		NBUMPSIDE(1, ns_lookup_miss);
   4554 	}
   4555 	return nat;
   4556 }
   4557 
   4558 
   4559 /* ------------------------------------------------------------------------ */
   4560 /* Function:    ipf_nat_lookupredir                                         */
   4561 /* Returns:     nat_t* - NULL == no match,                                  */
   4562 /*                       else pointer to matching NAT entry                 */
   4563 /* Parameters:  np(I) - pointer to description of packet to find NAT table  */
   4564 /*                      entry for.                                          */
   4565 /*                                                                          */
   4566 /* Lookup the NAT tables to search for a matching redirect                  */
   4567 /* The contents of natlookup_t should imitate those found in a packet that  */
   4568 /* would be translated - ie a packet coming in for RDR or going out for MAP.*/
   4569 /* We can do the lookup in one of two ways, imitating an inbound or         */
   4570 /* outbound  packet.  By default we assume outbound, unless IPN_IN is set.  */
   4571 /* For IN, the fields are set as follows:                                   */
   4572 /*     nl_real* = source information                                        */
   4573 /*     nl_out* = destination information (translated)                       */
   4574 /* For an out packet, the fields are set like this:                         */
   4575 /*     nl_in* = source information (untranslated)                           */
   4576 /*     nl_out* = destination information (translated)                       */
   4577 /* ------------------------------------------------------------------------ */
   4578 nat_t *
   4579 ipf_nat_lookupredir(natlookup_t *np)
   4580 {
   4581 	fr_info_t fi;
   4582 	nat_t *nat;
   4583 
   4584 	bzero((char *)&fi, sizeof(fi));
   4585 	if (np->nl_flags & IPN_IN) {
   4586 		fi.fin_data[0] = ntohs(np->nl_realport);
   4587 		fi.fin_data[1] = ntohs(np->nl_outport);
   4588 	} else {
   4589 		fi.fin_data[0] = ntohs(np->nl_inport);
   4590 		fi.fin_data[1] = ntohs(np->nl_outport);
   4591 	}
   4592 	if (np->nl_flags & IPN_TCP)
   4593 		fi.fin_p = IPPROTO_TCP;
   4594 	else if (np->nl_flags & IPN_UDP)
   4595 		fi.fin_p = IPPROTO_UDP;
   4596 	else if (np->nl_flags & (IPN_ICMPERR|IPN_ICMPQUERY))
   4597 		fi.fin_p = IPPROTO_ICMP;
   4598 
   4599 	/*
   4600 	 * We can do two sorts of lookups:
   4601 	 * - IPN_IN: we have the `real' and `out' address, look for `in'.
   4602 	 * - default: we have the `in' and `out' address, look for `real'.
   4603 	 */
   4604 	if (np->nl_flags & IPN_IN) {
   4605 		if ((nat = ipf_nat_inlookup(&fi, np->nl_flags, fi.fin_p,
   4606 					    np->nl_realip, np->nl_outip))) {
   4607 			np->nl_inip = nat->nat_odstip;
   4608 			np->nl_inport = nat->nat_odport;
   4609 		}
   4610 	} else {
   4611 		/*
   4612 		 * If nl_inip is non null, this is a lookup based on the real
   4613 		 * ip address. Else, we use the fake.
   4614 		 */
   4615 		if ((nat = ipf_nat_outlookup(&fi, np->nl_flags, fi.fin_p,
   4616 					 np->nl_inip, np->nl_outip))) {
   4617 
   4618 			if ((np->nl_flags & IPN_FINDFORWARD) != 0) {
   4619 				fr_info_t fin;
   4620 				bzero((char *)&fin, sizeof(fin));
   4621 				fin.fin_p = nat->nat_pr[0];
   4622 				fin.fin_data[0] = ntohs(nat->nat_ndport);
   4623 				fin.fin_data[1] = ntohs(nat->nat_nsport);
   4624 				if (ipf_nat_inlookup(&fin, np->nl_flags,
   4625 						     fin.fin_p, nat->nat_ndstip,
   4626 						     nat->nat_nsrcip) != NULL) {
   4627 					np->nl_flags &= ~IPN_FINDFORWARD;
   4628 				}
   4629 			}
   4630 
   4631 			np->nl_realip = nat->nat_ndstip;
   4632 			np->nl_realport = nat->nat_ndport;
   4633 		}
   4634  	}
   4635 
   4636 	return nat;
   4637 }
   4638 
   4639 
   4640 /* ------------------------------------------------------------------------ */
   4641 /* Function:    ipf_nat_match                                               */
   4642 /* Returns:     int - 0 == no match, 1 == match                             */
   4643 /* Parameters:  fin(I)   - pointer to packet information                    */
   4644 /*              np(I)    - pointer to NAT rule                              */
   4645 /*                                                                          */
   4646 /* Pull the matching of a packet against a NAT rule out of that complex     */
   4647 /* loop inside ipf_nat_checkin() and lay it out properly in its own function. */
   4648 /* ------------------------------------------------------------------------ */
   4649 static int
   4650 ipf_nat_match(fr_info_t *fin, ipnat_t *np)
   4651 {
   4652 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4653 	frtuc_t *ft;
   4654 	int match;
   4655 
   4656 	match = 0;
   4657 	switch (np->in_osrcatype)
   4658 	{
   4659 	case FRI_NORMAL :
   4660 		match = ((fin->fin_saddr & np->in_osrcmsk) != np->in_osrcaddr);
   4661 		break;
   4662 	case FRI_LOOKUP :
   4663 		match = (*np->in_osrcfunc)(softc, np->in_osrcptr,
   4664 					   4, &fin->fin_saddr, fin->fin_plen);
   4665 		break;
   4666 	}
   4667 	match ^= ((np->in_flags & IPN_NOTSRC) != 0);
   4668 	if (match)
   4669 		return 0;
   4670 
   4671 	match = 0;
   4672 	switch (np->in_odstatype)
   4673 	{
   4674 	case FRI_NORMAL :
   4675 		match = ((fin->fin_daddr & np->in_odstmsk) != np->in_odstaddr);
   4676 		break;
   4677 	case FRI_LOOKUP :
   4678 		match = (*np->in_odstfunc)(softc, np->in_odstptr,
   4679 					   4, &fin->fin_daddr, fin->fin_plen);
   4680 		break;
   4681 	}
   4682 
   4683 	match ^= ((np->in_flags & IPN_NOTDST) != 0);
   4684 	if (match)
   4685 		return 0;
   4686 
   4687 	ft = &np->in_tuc;
   4688 	if (!(fin->fin_flx & FI_TCPUDP) ||
   4689 	    (fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   4690 		if (ft->ftu_scmp || ft->ftu_dcmp)
   4691 			return 0;
   4692 		return 1;
   4693 	}
   4694 
   4695 	return ipf_tcpudpchk(&fin->fin_fi, ft);
   4696 }
   4697 
   4698 
   4699 /* ------------------------------------------------------------------------ */
   4700 /* Function:    ipf_nat_update                                              */
   4701 /* Returns:     Nil                                                         */
   4702 /* Parameters:  fin(I) - pointer to packet information                      */
   4703 /*              nat(I) - pointer to NAT structure                           */
   4704 /*                                                                          */
   4705 /* Updates the lifetime of a NAT table entry for non-TCP packets.  Must be  */
   4706 /* called with fin_rev updated - i.e. after calling ipf_nat_proto().        */
   4707 /*                                                                          */
   4708 /* This *MUST* be called after ipf_nat_proto() as it expects fin_rev to     */
   4709 /* already be set.                                                          */
   4710 /* ------------------------------------------------------------------------ */
   4711 void
   4712 ipf_nat_update(fr_info_t *fin, nat_t *nat)
   4713 {
   4714 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4715 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   4716 	ipftq_t *ifq, *ifq2;
   4717 	ipftqent_t *tqe;
   4718 	ipnat_t *np = nat->nat_ptr;
   4719 
   4720 	tqe = &nat->nat_tqe;
   4721 	ifq = tqe->tqe_ifq;
   4722 
   4723 	/*
   4724 	 * We allow over-riding of NAT timeouts from NAT rules, even for
   4725 	 * TCP, however, if it is TCP and there is no rule timeout set,
   4726 	 * then do not update the timeout here.
   4727 	 */
   4728 	if (np != NULL) {
   4729 		np->in_bytes[fin->fin_rev] += fin->fin_plen;
   4730 		ifq2 = np->in_tqehead[fin->fin_rev];
   4731 	} else {
   4732 		ifq2 = NULL;
   4733 	}
   4734 
   4735 	if (nat->nat_pr[0] == IPPROTO_TCP && ifq2 == NULL) {
   4736 		(void) ipf_tcp_age(&nat->nat_tqe, fin, softn->ipf_nat_tcptq,
   4737 				   0, 2);
   4738 	} else {
   4739 		if (ifq2 == NULL) {
   4740 			if (nat->nat_pr[0] == IPPROTO_UDP)
   4741 				ifq2 = fin->fin_rev ? &softn->ipf_nat_udpacktq :
   4742 						      &softn->ipf_nat_udptq;
   4743 			else if (nat->nat_pr[0] == IPPROTO_ICMP ||
   4744 				 nat->nat_pr[0] == IPPROTO_ICMPV6)
   4745 				ifq2 = fin->fin_rev ? &softn->ipf_nat_icmpacktq:
   4746 						      &softn->ipf_nat_icmptq;
   4747 			else
   4748 				ifq2 = &softn->ipf_nat_iptq;
   4749 		}
   4750 
   4751 		ipf_movequeue(softc->ipf_ticks, tqe, ifq, ifq2);
   4752 	}
   4753 }
   4754 
   4755 
   4756 /* ------------------------------------------------------------------------ */
   4757 /* Function:    ipf_nat_checkout                                            */
   4758 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   4759 /*                     0 == no packet translation occurred,                 */
   4760 /*                     1 == packet was successfully translated.             */
   4761 /* Parameters:  fin(I)   - pointer to packet information                    */
   4762 /*              passp(I) - pointer to filtering result flags                */
   4763 /*                                                                          */
   4764 /* Check to see if an outcoming packet should be changed.  ICMP packets are */
   4765 /* first checked to see if they match an existing entry (if an error),      */
   4766 /* otherwise a search of the current NAT table is made.  If neither results */
   4767 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   4768 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   4769 /* packet header(s) as required.                                            */
   4770 /* ------------------------------------------------------------------------ */
   4771 int
   4772 ipf_nat_checkout(fr_info_t *fin, u_32_t *passp)
   4773 {
   4774 	ipnat_t *np = NULL, *npnext;
   4775 	struct ifnet *ifp, *sifp;
   4776 	ipf_main_softc_t *softc;
   4777 	ipf_nat_softc_t *softn;
   4778 	icmphdr_t *icmp = NULL;
   4779 	tcphdr_t *tcp = NULL;
   4780 	int rval, natfailed;
   4781 	u_int nflags = 0;
   4782 	u_32_t ipa, iph;
   4783 	int natadd = 1;
   4784 	frentry_t *fr;
   4785 	nat_t *nat;
   4786 
   4787 	if (fin->fin_v == 6) {
   4788 #ifdef USE_INET6
   4789 		return ipf_nat6_checkout(fin, passp);
   4790 #else
   4791 		return 0;
   4792 #endif
   4793 	}
   4794 
   4795 	softc = fin->fin_main_soft;
   4796 	softn = softc->ipf_nat_soft;
   4797 
   4798 	if (softn->ipf_nat_lock != 0)
   4799 		return 0;
   4800 	if (softn->ipf_nat_stats.ns_rules == 0 &&
   4801 	    softn->ipf_nat_instances == NULL)
   4802 		return 0;
   4803 
   4804 	natfailed = 0;
   4805 	fr = fin->fin_fr;
   4806 	sifp = fin->fin_ifp;
   4807 	if (fr != NULL) {
   4808 		ifp = fr->fr_tifs[fin->fin_rev].fd_ptr;
   4809 		if ((ifp != NULL) && (ifp != (void *)-1))
   4810 			fin->fin_ifp = ifp;
   4811 	}
   4812 	ifp = fin->fin_ifp;
   4813 
   4814 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   4815 		switch (fin->fin_p)
   4816 		{
   4817 		case IPPROTO_TCP :
   4818 			nflags = IPN_TCP;
   4819 			break;
   4820 		case IPPROTO_UDP :
   4821 			nflags = IPN_UDP;
   4822 			break;
   4823 		case IPPROTO_ICMP :
   4824 			icmp = fin->fin_dp;
   4825 
   4826 			/*
   4827 			 * This is an incoming packet, so the destination is
   4828 			 * the icmp_id and the source port equals 0
   4829 			 */
   4830 			if ((fin->fin_flx & FI_ICMPQUERY) != 0)
   4831 				nflags = IPN_ICMPQUERY;
   4832 			break;
   4833 		default :
   4834 			break;
   4835 		}
   4836 
   4837 		if ((nflags & IPN_TCPUDP))
   4838 			tcp = fin->fin_dp;
   4839 	}
   4840 
   4841 	ipa = fin->fin_saddr;
   4842 
   4843 	READ_ENTER(&softc->ipf_nat);
   4844 
   4845 	if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
   4846 	    (nat = ipf_nat_icmperror(fin, &nflags, NAT_OUTBOUND)))
   4847 		/*EMPTY*/;
   4848 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   4849 		natadd = 0;
   4850 	else if ((nat = ipf_nat_outlookup(fin, nflags|NAT_SEARCH,
   4851 				      (u_int)fin->fin_p, fin->fin_src,
   4852 				      fin->fin_dst))) {
   4853 		nflags = nat->nat_flags;
   4854 	} else if (fin->fin_off == 0) {
   4855 		u_32_t hv, msk, nmsk = 0;
   4856 
   4857 		/*
   4858 		 * If there is no current entry in the nat table for this IP#,
   4859 		 * create one for it (if there is a matching rule).
   4860 		 */
   4861 maskloop:
   4862 		msk = softn->ipf_nat_map_active_masks[nmsk];
   4863 		iph = ipa & msk;
   4864 		hv = NAT_HASH_FN(iph, 0, softn->ipf_nat_maprules_sz);
   4865 retry_roundrobin:
   4866 		for (np = softn->ipf_nat_map_rules[hv]; np; np = npnext) {
   4867 			npnext = np->in_mnext;
   4868 			if ((np->in_ifps[1] && (np->in_ifps[1] != ifp)))
   4869 				continue;
   4870 			if (np->in_v[0] != 4)
   4871 				continue;
   4872 			if (np->in_pr[1] && (np->in_pr[1] != fin->fin_p))
   4873 				continue;
   4874 			if ((np->in_flags & IPN_RF) &&
   4875 			    !(np->in_flags & nflags))
   4876 				continue;
   4877 			if (np->in_flags & IPN_FILTER) {
   4878 				switch (ipf_nat_match(fin, np))
   4879 				{
   4880 				case 0 :
   4881 					continue;
   4882 				case -1 :
   4883 					rval = -1;
   4884 					goto outmatchfail;
   4885 				case 1 :
   4886 				default :
   4887 					break;
   4888 				}
   4889 			} else if ((ipa & np->in_osrcmsk) != np->in_osrcaddr)
   4890 				continue;
   4891 
   4892 			if ((fr != NULL) &&
   4893 			    !ipf_matchtag(&np->in_tag, &fr->fr_nattag))
   4894 				continue;
   4895 
   4896 			if (np->in_plabel != -1) {
   4897 				if (((np->in_flags & IPN_FILTER) == 0) &&
   4898 				    (np->in_odport != fin->fin_data[1]))
   4899 					continue;
   4900 				if (ipf_proxy_ok(fin, tcp, np) == 0)
   4901 					continue;
   4902 			}
   4903 
   4904 			if (np->in_flags & IPN_NO) {
   4905 				np->in_hits++;
   4906 				break;
   4907 			}
   4908 			MUTEX_ENTER(&softn->ipf_nat_new);
   4909 			/*
   4910 			 * If we've matched a round-robin rule but it has
   4911 			 * moved in the list since we got it, start over as
   4912 			 * this is now no longer correct.
   4913 			 */
   4914 			if (npnext != np->in_mnext) {
   4915 				if ((np->in_flags & IPN_ROUNDR) != 0) {
   4916 					MUTEX_EXIT(&softn->ipf_nat_new);
   4917 					goto retry_roundrobin;
   4918 				}
   4919 				npnext = np->in_mnext;
   4920 			}
   4921 
   4922 			nat = ipf_nat_add(fin, np, NULL, nflags, NAT_OUTBOUND);
   4923 			MUTEX_EXIT(&softn->ipf_nat_new);
   4924 			if (nat != NULL) {
   4925 				natfailed = 0;
   4926 				break;
   4927 			}
   4928 			natfailed = -1;
   4929 		}
   4930 		if ((np == NULL) && (nmsk < softn->ipf_nat_map_max)) {
   4931 			nmsk++;
   4932 			goto maskloop;
   4933 		}
   4934 	}
   4935 
   4936 	if (nat != NULL) {
   4937 		rval = ipf_nat_out(fin, nat, natadd, nflags);
   4938 		if (rval == 1) {
   4939 			MUTEX_ENTER(&nat->nat_lock);
   4940 			ipf_nat_update(fin, nat);
   4941 			nat->nat_bytes[1] += fin->fin_plen;
   4942 			nat->nat_pkts[1]++;
   4943 			fin->fin_pktnum = nat->nat_pkts[1];
   4944 			MUTEX_EXIT(&nat->nat_lock);
   4945 		}
   4946 	} else
   4947 		rval = natfailed;
   4948 outmatchfail:
   4949 	RWLOCK_EXIT(&softc->ipf_nat);
   4950 
   4951 	switch (rval)
   4952 	{
   4953 	case -1 :
   4954 		if (passp != NULL) {
   4955 			DT1(frb_natv4out, fr_info_t *, fin);
   4956 			NBUMPSIDED(1, ns_drop);
   4957 			*passp = FR_BLOCK;
   4958 			fin->fin_reason = FRB_NATV4;
   4959 		}
   4960 		fin->fin_flx |= FI_BADNAT;
   4961 		NBUMPSIDED(1, ns_badnat);
   4962 		break;
   4963 	case 0 :
   4964 		NBUMPSIDE(1, ns_ignored);
   4965 		break;
   4966 	case 1 :
   4967 		NBUMPSIDE(1, ns_translated);
   4968 		break;
   4969 	}
   4970 	fin->fin_ifp = sifp;
   4971 	return rval;
   4972 }
   4973 
   4974 /* ------------------------------------------------------------------------ */
   4975 /* Function:    ipf_nat_out                                                 */
   4976 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   4977 /*                     1 == packet was successfully translated.             */
   4978 /* Parameters:  fin(I)    - pointer to packet information                   */
   4979 /*              nat(I)    - pointer to NAT structure                        */
   4980 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   4981 /*              nflags(I) - NAT flags set for this packet                   */
   4982 /*                                                                          */
   4983 /* Translate a packet coming "out" on an interface.                         */
   4984 /* ------------------------------------------------------------------------ */
   4985 int
   4986 ipf_nat_out(fr_info_t *fin, nat_t *nat, int natadd, u_32_t nflags)
   4987 {
   4988 	ipf_main_softc_t *softc = fin->fin_main_soft;
   4989 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   4990 	icmphdr_t *icmp;
   4991 	tcphdr_t *tcp;
   4992 	ipnat_t *np;
   4993 	int skip;
   4994 	int i;
   4995 
   4996 	tcp = NULL;
   4997 	icmp = NULL;
   4998 	np = nat->nat_ptr;
   4999 
   5000 	if ((natadd != 0) && (fin->fin_flx & FI_FRAG) && (np != NULL))
   5001 		(void) ipf_frag_natnew(softc, fin, 0, nat);
   5002 
   5003 	/*
   5004 	 * Fix up checksums, not by recalculating them, but
   5005 	 * simply computing adjustments.
   5006 	 * This is only done for STREAMS based IP implementations where the
   5007 	 * checksum has already been calculated by IP.  In all other cases,
   5008 	 * IPFilter is called before the checksum needs calculating so there
   5009 	 * is no call to modify whatever is in the header now.
   5010 	 */
   5011 	if (nflags == IPN_ICMPERR) {
   5012 		u_32_t s1, s2, sumd, msumd;
   5013 
   5014 		s1 = LONG_SUM(ntohl(fin->fin_saddr));
   5015 		if (nat->nat_dir == NAT_OUTBOUND) {
   5016 			s2 = LONG_SUM(ntohl(nat->nat_nsrcaddr));
   5017 		} else {
   5018 			s2 = LONG_SUM(ntohl(nat->nat_odstaddr));
   5019 		}
   5020 		CALC_SUMD(s1, s2, sumd);
   5021 		msumd = sumd;
   5022 
   5023 		s1 = LONG_SUM(ntohl(fin->fin_daddr));
   5024 		if (nat->nat_dir == NAT_OUTBOUND) {
   5025 			s2 = LONG_SUM(ntohl(nat->nat_ndstaddr));
   5026 		} else {
   5027 			s2 = LONG_SUM(ntohl(nat->nat_osrcaddr));
   5028 		}
   5029 		CALC_SUMD(s1, s2, sumd);
   5030 		msumd += sumd;
   5031 
   5032 		ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, msumd, 0);
   5033 	}
   5034 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5035     defined(linux) || defined(BRIDGE_IPF)
   5036 	else {
   5037 		/*
   5038 		 * Strictly speaking, this isn't necessary on BSD
   5039 		 * kernels because they do checksum calculation after
   5040 		 * this code has run BUT if ipfilter is being used
   5041 		 * to do NAT as a bridge, that code doesn't exist.
   5042 		 */
   5043 		switch (nat->nat_dir)
   5044 		{
   5045 		case NAT_OUTBOUND :
   5046 			ipf_fix_outcksum(fin->fin_cksum & FI_CK_L4PART,
   5047 					 &fin->fin_ip->ip_sum,
   5048 					 nat->nat_ipsumd, 0);
   5049 			break;
   5050 
   5051 		case NAT_INBOUND :
   5052 			ipf_fix_incksum(fin->fin_cksum & FI_CK_L4PART,
   5053 					&fin->fin_ip->ip_sum,
   5054 					nat->nat_ipsumd, 0);
   5055 			break;
   5056 
   5057 		default :
   5058 			break;
   5059 		}
   5060 	}
   5061 #endif
   5062 
   5063 	/*
   5064 	 * Address assignment is after the checksum modification because
   5065 	 * we are using the address in the packet for determining the
   5066 	 * correct checksum offset (the ICMP error could be coming from
   5067 	 * anyone...)
   5068 	 */
   5069 	switch (nat->nat_dir)
   5070 	{
   5071 	case NAT_OUTBOUND :
   5072 		fin->fin_ip->ip_src = nat->nat_nsrcip;
   5073 		fin->fin_saddr = nat->nat_nsrcaddr;
   5074 		fin->fin_ip->ip_dst = nat->nat_ndstip;
   5075 		fin->fin_daddr = nat->nat_ndstaddr;
   5076 		break;
   5077 
   5078 	case NAT_INBOUND :
   5079 		fin->fin_ip->ip_src = nat->nat_odstip;
   5080 		fin->fin_saddr = nat->nat_ndstaddr;
   5081 		fin->fin_ip->ip_dst = nat->nat_osrcip;
   5082 		fin->fin_daddr = nat->nat_nsrcaddr;
   5083 		break;
   5084 
   5085 	case NAT_DIVERTIN :
   5086 	    {
   5087 		mb_t *m;
   5088 
   5089 		skip = ipf_nat_decap(fin, nat);
   5090 		if (skip <= 0) {
   5091 			NBUMPSIDED(1, ns_decap_fail);
   5092 			return -1;
   5093 		}
   5094 
   5095 		m = fin->fin_m;
   5096 
   5097 #if defined(MENTAT) && defined(_KERNEL)
   5098 		m->b_rptr += skip;
   5099 #else
   5100 		m->m_data += skip;
   5101 		m->m_len -= skip;
   5102 
   5103 # ifdef M_PKTHDR
   5104 		if (m->m_flags & M_PKTHDR)
   5105 			m->m_pkthdr.len -= skip;
   5106 # endif
   5107 #endif
   5108 
   5109 		MUTEX_ENTER(&nat->nat_lock);
   5110 		ipf_nat_update(fin, nat);
   5111 		MUTEX_EXIT(&nat->nat_lock);
   5112 		fin->fin_flx |= FI_NATED;
   5113 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   5114 			fin->fin_nattag = &np->in_tag;
   5115 		return 1;
   5116 		/* NOTREACHED */
   5117 	    }
   5118 
   5119 	case NAT_DIVERTOUT :
   5120 	    {
   5121 		u_32_t s1, s2, sumd;
   5122 		udphdr_t *uh;
   5123 		ip_t *ip;
   5124 		mb_t *m;
   5125 
   5126 		m = M_DUP(np->in_divmp);
   5127 		if (m == NULL) {
   5128 			NBUMPSIDED(1, ns_divert_dup);
   5129 			return -1;
   5130 		}
   5131 
   5132 		ip = MTOD(m, ip_t *);
   5133 		ip->ip_id = htons(ipf_nextipid(fin));
   5134 		s2 = ntohs(ip->ip_id);
   5135 
   5136 		s1 = ip->ip_len;
   5137 		ip->ip_len = ntohs(ip->ip_len);
   5138 		ip->ip_len += fin->fin_plen;
   5139 		ip->ip_len = htons(ip->ip_len);
   5140 		s2 += ntohs(ip->ip_len);
   5141 		CALC_SUMD(s1, s2, sumd);
   5142 
   5143 		uh = (udphdr_t *)(ip + 1);
   5144 		uh->uh_ulen += fin->fin_plen;
   5145 		uh->uh_ulen = htons(uh->uh_ulen);
   5146 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5147     defined(linux) || defined(BRIDGE_IPF)
   5148 		ipf_fix_outcksum(0, &ip->ip_sum, sumd, 0);
   5149 #endif
   5150 
   5151 		PREP_MB_T(fin, m);
   5152 
   5153 		fin->fin_src = ip->ip_src;
   5154 		fin->fin_dst = ip->ip_dst;
   5155 		fin->fin_ip = ip;
   5156 		fin->fin_plen += sizeof(ip_t) + 8;	/* UDP + IPv4 hdr */
   5157 		fin->fin_dlen += sizeof(ip_t) + 8;	/* UDP + IPv4 hdr */
   5158 
   5159 		nflags &= ~IPN_TCPUDPICMP;
   5160 
   5161 		break;
   5162 	    }
   5163 
   5164 	default :
   5165 		break;
   5166 	}
   5167 
   5168 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   5169 		u_short *csump;
   5170 
   5171 		if ((nat->nat_nsport != 0) && (nflags & IPN_TCPUDP)) {
   5172 			tcp = fin->fin_dp;
   5173 
   5174 			switch (nat->nat_dir)
   5175 			{
   5176 			case NAT_OUTBOUND :
   5177 				tcp->th_sport = nat->nat_nsport;
   5178 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   5179 				tcp->th_dport = nat->nat_ndport;
   5180 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   5181 				break;
   5182 
   5183 			case NAT_INBOUND :
   5184 				tcp->th_sport = nat->nat_odport;
   5185 				fin->fin_data[0] = ntohs(nat->nat_odport);
   5186 				tcp->th_dport = nat->nat_osport;
   5187 				fin->fin_data[1] = ntohs(nat->nat_osport);
   5188 				break;
   5189 			}
   5190 		}
   5191 
   5192 		if ((nat->nat_nsport != 0) && (nflags & IPN_ICMPQUERY)) {
   5193 			icmp = fin->fin_dp;
   5194 			icmp->icmp_id = nat->nat_nicmpid;
   5195 		}
   5196 
   5197 		csump = ipf_nat_proto(fin, nat, nflags);
   5198 
   5199 		/*
   5200 		 * The above comments do not hold for layer 4 (or higher)
   5201 		 * checksums...
   5202 		 */
   5203 		if (csump != NULL) {
   5204 			if (nat->nat_dir == NAT_OUTBOUND)
   5205 				ipf_fix_outcksum(fin->fin_cksum, csump,
   5206 						 nat->nat_sumd[0],
   5207 						 nat->nat_sumd[1] +
   5208 						 fin->fin_dlen);
   5209 			else
   5210 				ipf_fix_incksum(fin->fin_cksum, csump,
   5211 						nat->nat_sumd[0],
   5212 						nat->nat_sumd[1] +
   5213 						fin->fin_dlen);
   5214 		}
   5215 	}
   5216 
   5217 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   5218 	/* ------------------------------------------------------------- */
   5219 	/* A few quick notes:                                            */
   5220 	/*      Following are test conditions prior to calling the       */
   5221 	/*      ipf_proxy_check routine.                                 */
   5222 	/*                                                               */
   5223 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   5224 	/*      with a redirect rule, we attempt to match the packet's   */
   5225 	/*      source port against in_dport, otherwise we'd compare the */
   5226 	/*      packet's destination.                                    */
   5227 	/* ------------------------------------------------------------- */
   5228 	if ((np != NULL) && (np->in_apr != NULL)) {
   5229 		i = ipf_proxy_check(fin, nat);
   5230 		if (i == 0) {
   5231 			i = 1;
   5232 		} else if (i == -1) {
   5233 			NBUMPSIDED(1, ns_ipf_proxy_fail);
   5234 		}
   5235 	} else {
   5236 		i = 1;
   5237 	}
   5238 	fin->fin_flx |= FI_NATED;
   5239 	return i;
   5240 }
   5241 
   5242 
   5243 /* ------------------------------------------------------------------------ */
   5244 /* Function:    ipf_nat_checkin                                             */
   5245 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   5246 /*                     0 == no packet translation occurred,                 */
   5247 /*                     1 == packet was successfully translated.             */
   5248 /* Parameters:  fin(I)   - pointer to packet information                    */
   5249 /*              passp(I) - pointer to filtering result flags                */
   5250 /*                                                                          */
   5251 /* Check to see if an incoming packet should be changed.  ICMP packets are  */
   5252 /* first checked to see if they match an existing entry (if an error),      */
   5253 /* otherwise a search of the current NAT table is made.  If neither results */
   5254 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   5255 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   5256 /* packet header(s) as required.                                            */
   5257 /* ------------------------------------------------------------------------ */
   5258 int
   5259 ipf_nat_checkin(fr_info_t *fin, u_32_t *passp)
   5260 {
   5261 	ipf_main_softc_t *softc;
   5262 	ipf_nat_softc_t *softn;
   5263 	u_int nflags, natadd;
   5264 	ipnat_t *np, *npnext;
   5265 	int rval, natfailed;
   5266 	struct ifnet *ifp;
   5267 	struct in_addr in;
   5268 	icmphdr_t *icmp;
   5269 	tcphdr_t *tcp;
   5270 	u_short dport;
   5271 	nat_t *nat;
   5272 	u_32_t iph;
   5273 
   5274 	softc = fin->fin_main_soft;
   5275 	softn = softc->ipf_nat_soft;
   5276 
   5277 	if (softn->ipf_nat_lock != 0)
   5278 		return 0;
   5279 	if (softn->ipf_nat_stats.ns_rules == 0 &&
   5280 	    softn->ipf_nat_instances == NULL)
   5281 		return 0;
   5282 
   5283 	tcp = NULL;
   5284 	icmp = NULL;
   5285 	dport = 0;
   5286 	natadd = 1;
   5287 	nflags = 0;
   5288 	natfailed = 0;
   5289 	ifp = fin->fin_ifp;
   5290 
   5291 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   5292 		switch (fin->fin_p)
   5293 		{
   5294 		case IPPROTO_TCP :
   5295 			nflags = IPN_TCP;
   5296 			break;
   5297 		case IPPROTO_UDP :
   5298 			nflags = IPN_UDP;
   5299 			break;
   5300 		case IPPROTO_ICMP :
   5301 			icmp = fin->fin_dp;
   5302 
   5303 			/*
   5304 			 * This is an incoming packet, so the destination is
   5305 			 * the icmp_id and the source port equals 0
   5306 			 */
   5307 			if ((fin->fin_flx & FI_ICMPQUERY) != 0) {
   5308 				nflags = IPN_ICMPQUERY;
   5309 				dport = icmp->icmp_id;
   5310 			} break;
   5311 		default :
   5312 			break;
   5313 		}
   5314 
   5315 		if ((nflags & IPN_TCPUDP)) {
   5316 			tcp = fin->fin_dp;
   5317 			dport = fin->fin_data[1];
   5318 		}
   5319 	}
   5320 
   5321 	in = fin->fin_dst;
   5322 
   5323 	READ_ENTER(&softc->ipf_nat);
   5324 
   5325 	if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
   5326 	    (nat = ipf_nat_icmperror(fin, &nflags, NAT_INBOUND)))
   5327 		/*EMPTY*/;
   5328 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   5329 		natadd = 0;
   5330 	else if ((nat = ipf_nat_inlookup(fin, nflags|NAT_SEARCH,
   5331 					 (u_int)fin->fin_p,
   5332 					 fin->fin_src, in))) {
   5333 		nflags = nat->nat_flags;
   5334 	} else if (fin->fin_off == 0) {
   5335 		u_32_t hv, msk, rmsk = 0;
   5336 
   5337 		/*
   5338 		 * If there is no current entry in the nat table for this IP#,
   5339 		 * create one for it (if there is a matching rule).
   5340 		 */
   5341 maskloop:
   5342 		msk = softn->ipf_nat_rdr_active_masks[rmsk];
   5343 		iph = in.s_addr & msk;
   5344 		hv = NAT_HASH_FN(iph, 0, softn->ipf_nat_rdrrules_sz);
   5345 retry_roundrobin:
   5346 		/* TRACE (iph,msk,rmsk,hv,softn->ipf_nat_rdrrules_sz) */
   5347 		for (np = softn->ipf_nat_rdr_rules[hv]; np; np = npnext) {
   5348 			npnext = np->in_rnext;
   5349 			if (np->in_ifps[0] && (np->in_ifps[0] != ifp))
   5350 				continue;
   5351 			if (np->in_v[0] != 4)
   5352 				continue;
   5353 			if (np->in_pr[0] && (np->in_pr[0] != fin->fin_p))
   5354 				continue;
   5355 			if ((np->in_flags & IPN_RF) && !(np->in_flags & nflags))
   5356 				continue;
   5357 			if (np->in_flags & IPN_FILTER) {
   5358 				switch (ipf_nat_match(fin, np))
   5359 				{
   5360 				case 0 :
   5361 					continue;
   5362 				case -1 :
   5363 					rval = -1;
   5364 					goto inmatchfail;
   5365 				case 1 :
   5366 				default :
   5367 					break;
   5368 				}
   5369 			} else {
   5370 				if ((in.s_addr & np->in_odstmsk) !=
   5371 				    np->in_odstaddr)
   5372 					continue;
   5373 				if (np->in_odport &&
   5374 				    ((np->in_dtop < dport) ||
   5375 				     (dport < np->in_odport)))
   5376 					continue;
   5377 			}
   5378 
   5379 			if (np->in_plabel != -1) {
   5380 				if (!ipf_proxy_ok(fin, tcp, np)) {
   5381 					continue;
   5382 				}
   5383 			}
   5384 
   5385 			if (np->in_flags & IPN_NO) {
   5386 				np->in_hits++;
   5387 				break;
   5388 			}
   5389 
   5390 			MUTEX_ENTER(&softn->ipf_nat_new);
   5391 			/*
   5392 			 * If we've matched a round-robin rule but it has
   5393 			 * moved in the list since we got it, start over as
   5394 			 * this is now no longer correct.
   5395 			 */
   5396 			if (npnext != np->in_rnext) {
   5397 				if ((np->in_flags & IPN_ROUNDR) != 0) {
   5398 					MUTEX_EXIT(&softn->ipf_nat_new);
   5399 					goto retry_roundrobin;
   5400 				}
   5401 				npnext = np->in_rnext;
   5402 			}
   5403 
   5404 			nat = ipf_nat_add(fin, np, NULL, nflags, NAT_INBOUND);
   5405 			MUTEX_EXIT(&softn->ipf_nat_new);
   5406 			if (nat != NULL) {
   5407 				natfailed = 0;
   5408 				break;
   5409 			}
   5410 			natfailed = -1;
   5411 		}
   5412 		if ((np == NULL) && (rmsk < softn->ipf_nat_rdr_max)) {
   5413 			rmsk++;
   5414 			goto maskloop;
   5415 		}
   5416 	}
   5417 
   5418 	if (nat != NULL) {
   5419 		rval = ipf_nat_in(fin, nat, natadd, nflags);
   5420 		if (rval == 1) {
   5421 			MUTEX_ENTER(&nat->nat_lock);
   5422 			ipf_nat_update(fin, nat);
   5423 			nat->nat_bytes[0] += fin->fin_plen;
   5424 			nat->nat_pkts[0]++;
   5425 			fin->fin_pktnum = nat->nat_pkts[0];
   5426 			MUTEX_EXIT(&nat->nat_lock);
   5427 		}
   5428 	} else
   5429 		rval = natfailed;
   5430 inmatchfail:
   5431 	RWLOCK_EXIT(&softc->ipf_nat);
   5432 
   5433 	switch (rval)
   5434 	{
   5435 	case -1 :
   5436 		if (passp != NULL) {
   5437 			DT1(frb_natv4in, fr_info_t *, fin);
   5438 			NBUMPSIDED(0, ns_drop);
   5439 			*passp = FR_BLOCK;
   5440 			fin->fin_reason = FRB_NATV4;
   5441 		}
   5442 		fin->fin_flx |= FI_BADNAT;
   5443 		NBUMPSIDED(0, ns_badnat);
   5444 		break;
   5445 	case 0 :
   5446 		NBUMPSIDE(0, ns_ignored);
   5447 		break;
   5448 	case 1 :
   5449 		NBUMPSIDE(0, ns_translated);
   5450 		break;
   5451 	}
   5452 	return rval;
   5453 }
   5454 
   5455 
   5456 /* ------------------------------------------------------------------------ */
   5457 /* Function:    ipf_nat_in                                                  */
   5458 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   5459 /*                     1 == packet was successfully translated.             */
   5460 /* Parameters:  fin(I)    - pointer to packet information                   */
   5461 /*              nat(I)    - pointer to NAT structure                        */
   5462 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   5463 /*              nflags(I) - NAT flags set for this packet                   */
   5464 /* Locks Held:  ipf_nat(READ)                                               */
   5465 /*                                                                          */
   5466 /* Translate a packet coming "in" on an interface.                          */
   5467 /* ------------------------------------------------------------------------ */
   5468 int
   5469 ipf_nat_in(fr_info_t *fin, nat_t *nat, int natadd, u_32_t nflags)
   5470 {
   5471 	ipf_main_softc_t *softc = fin->fin_main_soft;
   5472 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   5473 	u_32_t sumd, ipsumd, sum1, sum2;
   5474 	icmphdr_t *icmp;
   5475 	tcphdr_t *tcp;
   5476 	ipnat_t *np;
   5477 	int skip;
   5478 	int i;
   5479 
   5480 	tcp = NULL;
   5481 	np = nat->nat_ptr;
   5482 	fin->fin_fr = nat->nat_fr;
   5483 
   5484 	if (np != NULL) {
   5485 		if ((natadd != 0) && (fin->fin_flx & FI_FRAG))
   5486 			(void) ipf_frag_natnew(softc, fin, 0, nat);
   5487 
   5488 	/* ------------------------------------------------------------- */
   5489 	/* A few quick notes:                                            */
   5490 	/*      Following are test conditions prior to calling the       */
   5491 	/*      ipf_proxy_check routine.                                 */
   5492 	/*                                                               */
   5493 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   5494 	/*      with a map rule, we attempt to match the packet's        */
   5495 	/*      source port against in_dport, otherwise we'd compare the */
   5496 	/*      packet's destination.                                    */
   5497 	/* ------------------------------------------------------------- */
   5498 		if (np->in_apr != NULL) {
   5499 			i = ipf_proxy_check(fin, nat);
   5500 			if (i == -1) {
   5501 				NBUMPSIDED(0, ns_ipf_proxy_fail);
   5502 				return -1;
   5503 			}
   5504 		}
   5505 	}
   5506 
   5507 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   5508 
   5509 	ipsumd = nat->nat_ipsumd;
   5510 	/*
   5511 	 * Fix up checksums, not by recalculating them, but
   5512 	 * simply computing adjustments.
   5513 	 * Why only do this for some platforms on inbound packets ?
   5514 	 * Because for those that it is done, IP processing is yet to happen
   5515 	 * and so the IPv4 header checksum has not yet been evaluated.
   5516 	 * Perhaps it should always be done for the benefit of things like
   5517 	 * fast forwarding (so that it doesn't need to be recomputed) but with
   5518 	 * header checksum offloading, perhaps it is a moot point.
   5519 	 */
   5520 
   5521 	switch (nat->nat_dir)
   5522 	{
   5523 	case NAT_INBOUND :
   5524 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   5525 			fin->fin_ip->ip_src = nat->nat_nsrcip;
   5526 			fin->fin_saddr = nat->nat_nsrcaddr;
   5527 		} else {
   5528 			sum1 = nat->nat_osrcaddr;
   5529 			sum2 = nat->nat_nsrcaddr;
   5530 			CALC_SUMD(sum1, sum2, sumd);
   5531 			ipsumd -= sumd;
   5532 		}
   5533 		fin->fin_ip->ip_dst = nat->nat_ndstip;
   5534 		fin->fin_daddr = nat->nat_ndstaddr;
   5535 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5536      defined(__osf__) || defined(linux)
   5537 		ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, ipsumd, 0);
   5538 #endif
   5539 		break;
   5540 
   5541 	case NAT_OUTBOUND :
   5542 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   5543 			fin->fin_ip->ip_src = nat->nat_odstip;
   5544 			fin->fin_saddr = nat->nat_odstaddr;
   5545 		} else {
   5546 			sum1 = nat->nat_odstaddr;
   5547 			sum2 = nat->nat_ndstaddr;
   5548 			CALC_SUMD(sum1, sum2, sumd);
   5549 			ipsumd -= sumd;
   5550 		}
   5551 		fin->fin_ip->ip_dst = nat->nat_osrcip;
   5552 		fin->fin_daddr = nat->nat_osrcaddr;
   5553 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5554      defined(__osf__) || defined(linux)
   5555 		ipf_fix_incksum(0, &fin->fin_ip->ip_sum, ipsumd, 0);
   5556 #endif
   5557 		break;
   5558 
   5559 	case NAT_DIVERTIN :
   5560 	    {
   5561 		udphdr_t *uh;
   5562 		ip_t *ip;
   5563 		mb_t *m;
   5564 
   5565 		m = M_DUP(np->in_divmp);
   5566 		if (m == NULL) {
   5567 			NBUMPSIDED(0, ns_divert_dup);
   5568 			return -1;
   5569 		}
   5570 
   5571 		ip = MTOD(m, ip_t *);
   5572 		ip->ip_id = htons(ipf_nextipid(fin));
   5573 		sum1 = ntohs(ip->ip_len);
   5574 		ip->ip_len = ntohs(ip->ip_len);
   5575 		ip->ip_len += fin->fin_plen;
   5576 		ip->ip_len = htons(ip->ip_len);
   5577 
   5578 		uh = (udphdr_t *)(ip + 1);
   5579 		uh->uh_ulen += fin->fin_plen;
   5580 		uh->uh_ulen = htons(uh->uh_ulen);
   5581 
   5582 		sum2 = ntohs(ip->ip_id) + ntohs(ip->ip_len);
   5583 		sum2 += ntohs(ip->ip_off) & IP_DF;
   5584 		CALC_SUMD(sum1, sum2, sumd);
   5585 
   5586 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   5587      defined(__osf__) || defined(linux)
   5588 		ipf_fix_outcksum(0, &ip->ip_sum, sumd, 0);
   5589 #endif
   5590 		PREP_MB_T(fin, m);
   5591 
   5592 		fin->fin_ip = ip;
   5593 		fin->fin_plen += sizeof(ip_t) + 8;	/* UDP + new IPv4 hdr */
   5594 		fin->fin_dlen += sizeof(ip_t) + 8;	/* UDP + old IPv4 hdr */
   5595 
   5596 		nflags &= ~IPN_TCPUDPICMP;
   5597 
   5598 		break;
   5599 	    }
   5600 
   5601 	case NAT_DIVERTOUT :
   5602 	    {
   5603 		mb_t *m;
   5604 
   5605 		skip = ipf_nat_decap(fin, nat);
   5606 		if (skip <= 0) {
   5607 			NBUMPSIDED(0, ns_decap_fail);
   5608 			return -1;
   5609 		}
   5610 
   5611 		m = fin->fin_m;
   5612 
   5613 #if defined(MENTAT) && defined(_KERNEL)
   5614 		m->b_rptr += skip;
   5615 #else
   5616 		m->m_data += skip;
   5617 		m->m_len -= skip;
   5618 
   5619 # ifdef M_PKTHDR
   5620 		if (m->m_flags & M_PKTHDR)
   5621 			m->m_pkthdr.len -= skip;
   5622 # endif
   5623 #endif
   5624 
   5625 		ipf_nat_update(fin, nat);
   5626 		nflags &= ~IPN_TCPUDPICMP;
   5627 		fin->fin_flx |= FI_NATED;
   5628 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   5629 			fin->fin_nattag = &np->in_tag;
   5630 		return 1;
   5631 		/* NOTREACHED */
   5632 	    }
   5633 	}
   5634 	if (nflags & IPN_TCPUDP)
   5635 		tcp = fin->fin_dp;
   5636 
   5637 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   5638 		u_short *csump;
   5639 
   5640 		if ((nat->nat_odport != 0) && (nflags & IPN_TCPUDP)) {
   5641 			switch (nat->nat_dir)
   5642 			{
   5643 			case NAT_INBOUND :
   5644 				tcp->th_sport = nat->nat_nsport;
   5645 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   5646 				tcp->th_dport = nat->nat_ndport;
   5647 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   5648 				break;
   5649 
   5650 			case NAT_OUTBOUND :
   5651 				tcp->th_sport = nat->nat_odport;
   5652 				fin->fin_data[0] = ntohs(nat->nat_odport);
   5653 				tcp->th_dport = nat->nat_osport;
   5654 				fin->fin_data[1] = ntohs(nat->nat_osport);
   5655 				break;
   5656 			}
   5657 		}
   5658 
   5659 
   5660 		if ((nat->nat_odport != 0) && (nflags & IPN_ICMPQUERY)) {
   5661 			icmp = fin->fin_dp;
   5662 
   5663 			icmp->icmp_id = nat->nat_nicmpid;
   5664 		}
   5665 
   5666 		csump = ipf_nat_proto(fin, nat, nflags);
   5667 
   5668 		/*
   5669 		 * The above comments do not hold for layer 4 (or higher)
   5670 		 * checksums...
   5671 		 */
   5672 		if (csump != NULL) {
   5673 			if (nat->nat_dir == NAT_OUTBOUND)
   5674 				ipf_fix_incksum(0, csump, nat->nat_sumd[0], 0);
   5675 			else
   5676 				ipf_fix_outcksum(0, csump, nat->nat_sumd[0], 0);
   5677 		}
   5678 	}
   5679 
   5680 	fin->fin_flx |= FI_NATED;
   5681 	if (np != NULL && np->in_tag.ipt_num[0] != 0)
   5682 		fin->fin_nattag = &np->in_tag;
   5683 	return 1;
   5684 }
   5685 
   5686 
   5687 /* ------------------------------------------------------------------------ */
   5688 /* Function:    ipf_nat_proto                                               */
   5689 /* Returns:     u_short* - pointer to transport header checksum to update,  */
   5690 /*                         NULL if the transport protocol is not recognised */
   5691 /*                         as needing a checksum update.                    */
   5692 /* Parameters:  fin(I)    - pointer to packet information                   */
   5693 /*              nat(I)    - pointer to NAT structure                        */
   5694 /*              nflags(I) - NAT flags set for this packet                   */
   5695 /*                                                                          */
   5696 /* Return the pointer to the checksum field for each protocol so understood.*/
   5697 /* If support for making other changes to a protocol header is required,    */
   5698 /* that is not strictly 'address' translation, such as clamping the MSS in  */
   5699 /* TCP down to a specific value, then do it from here.                      */
   5700 /* ------------------------------------------------------------------------ */
   5701 u_short *
   5702 ipf_nat_proto(fr_info_t *fin, nat_t *nat, u_int nflags)
   5703 {
   5704 	icmphdr_t *icmp;
   5705 	u_short *csump;
   5706 	tcphdr_t *tcp;
   5707 	udphdr_t *udp;
   5708 
   5709 	csump = NULL;
   5710 	if (fin->fin_out == 0) {
   5711 		fin->fin_rev = (nat->nat_dir & NAT_OUTBOUND);
   5712 	} else {
   5713 		fin->fin_rev = ((nat->nat_dir & NAT_OUTBOUND) == 0);
   5714 	}
   5715 
   5716 	switch (fin->fin_p)
   5717 	{
   5718 	case IPPROTO_TCP :
   5719 		tcp = fin->fin_dp;
   5720 
   5721 		if ((nflags & IPN_TCP) != 0)
   5722 			csump = &tcp->th_sum;
   5723 
   5724 		/*
   5725 		 * Do a MSS CLAMPING on a SYN packet,
   5726 		 * only deal IPv4 for now.
   5727 		 */
   5728 		if ((nat->nat_mssclamp != 0) && (tcp->th_flags & TH_SYN) != 0)
   5729 			ipf_nat_mssclamp(tcp, nat->nat_mssclamp, fin, csump);
   5730 
   5731 		break;
   5732 
   5733 	case IPPROTO_UDP :
   5734 		udp = fin->fin_dp;
   5735 
   5736 		if ((nflags & IPN_UDP) != 0) {
   5737 			if (udp->uh_sum != 0)
   5738 				csump = &udp->uh_sum;
   5739 		}
   5740 		break;
   5741 
   5742 	case IPPROTO_ICMP :
   5743 		icmp = fin->fin_dp;
   5744 
   5745 		if ((nflags & IPN_ICMPQUERY) != 0) {
   5746 			if (icmp->icmp_cksum != 0)
   5747 				csump = &icmp->icmp_cksum;
   5748 		}
   5749 		break;
   5750 
   5751 #ifdef USE_INET6
   5752 	case IPPROTO_ICMPV6 :
   5753 	    {
   5754 		struct icmp6_hdr *icmp6 = (struct icmp6_hdr *)fin->fin_dp;
   5755 
   5756 		icmp6 = fin->fin_dp;
   5757 
   5758 		if ((nflags & IPN_ICMPQUERY) != 0) {
   5759 			if (icmp6->icmp6_cksum != 0)
   5760 				csump = &icmp6->icmp6_cksum;
   5761 		}
   5762 		break;
   5763 	    }
   5764 #endif
   5765 	}
   5766 	return csump;
   5767 }
   5768 
   5769 
   5770 /* ------------------------------------------------------------------------ */
   5771 /* Function:    ipf_nat_expire                                              */
   5772 /* Returns:     Nil                                                         */
   5773 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5774 /*                                                                          */
   5775 /* Check all of the timeout queues for entries at the top which need to be  */
   5776 /* expired.                                                                 */
   5777 /* ------------------------------------------------------------------------ */
   5778 void
   5779 ipf_nat_expire(ipf_main_softc_t *softc)
   5780 {
   5781 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   5782 	ipftq_t *ifq, *ifqnext;
   5783 	ipftqent_t *tqe, *tqn;
   5784 	int i;
   5785 	SPL_INT(s);
   5786 
   5787 	SPL_NET(s);
   5788 	WRITE_ENTER(&softc->ipf_nat);
   5789 	for (ifq = softn->ipf_nat_tcptq, i = 0; ifq != NULL;
   5790 	     ifq = ifq->ifq_next) {
   5791 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
   5792 			if (tqe->tqe_die > softc->ipf_ticks)
   5793 				break;
   5794 			tqn = tqe->tqe_next;
   5795 			ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
   5796 		}
   5797 	}
   5798 
   5799 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifq->ifq_next) {
   5800 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
   5801 			if (tqe->tqe_die > softc->ipf_ticks)
   5802 				break;
   5803 			tqn = tqe->tqe_next;
   5804 			ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
   5805 		}
   5806 	}
   5807 
   5808 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifqnext) {
   5809 		ifqnext = ifq->ifq_next;
   5810 
   5811 		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
   5812 		    (ifq->ifq_ref == 0)) {
   5813 			ipf_freetimeoutqueue(softc, ifq);
   5814 		}
   5815 	}
   5816 
   5817 	if (softn->ipf_nat_doflush != 0) {
   5818 		ipf_nat_extraflush(softc, softn, 2);
   5819 		softn->ipf_nat_doflush = 0;
   5820 	}
   5821 
   5822 	RWLOCK_EXIT(&softc->ipf_nat);
   5823 	SPL_X(s);
   5824 }
   5825 
   5826 
   5827 /* ------------------------------------------------------------------------ */
   5828 /* Function:    ipf_nat_sync                                                */
   5829 /* Returns:     Nil                                                         */
   5830 /* Parameters:  softc(I) - pointer to soft context main structure           */
   5831 /*              ifp(I) - pointer to network interface                       */
   5832 /*                                                                          */
   5833 /* Walk through all of the currently active NAT sessions, looking for those */
   5834 /* which need to have their translated address updated.                     */
   5835 /* ------------------------------------------------------------------------ */
   5836 void
   5837 ipf_nat_sync(ipf_main_softc_t *softc, void *ifp)
   5838 {
   5839 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   5840 	u_32_t sum1, sum2, sumd;
   5841 	i6addr_t in;
   5842 	ipnat_t *n;
   5843 	nat_t *nat;
   5844 	void *ifp2;
   5845 	int idx;
   5846 	SPL_INT(s);
   5847 
   5848 	if (softc->ipf_running <= 0)
   5849 		return;
   5850 
   5851 	/*
   5852 	 * Change IP addresses for NAT sessions for any protocol except TCP
   5853 	 * since it will break the TCP connection anyway.  The only rules
   5854 	 * which will get changed are those which are "map ... -> 0/32",
   5855 	 * where the rule specifies the address is taken from the interface.
   5856 	 */
   5857 	SPL_NET(s);
   5858 	WRITE_ENTER(&softc->ipf_nat);
   5859 
   5860 	if (softc->ipf_running <= 0) {
   5861 		RWLOCK_EXIT(&softc->ipf_nat);
   5862 		return;
   5863 	}
   5864 
   5865 	for (nat = softn->ipf_nat_instances; nat; nat = nat->nat_next) {
   5866 		if ((nat->nat_flags & IPN_TCP) != 0)
   5867 			continue;
   5868 
   5869 		n = nat->nat_ptr;
   5870 		if (n != NULL) {
   5871 			if (n->in_v[1] == 4) {
   5872 				if (n->in_redir & NAT_MAP) {
   5873 					if ((n->in_nsrcaddr != 0) ||
   5874 					    (n->in_nsrcmsk != 0xffffffff))
   5875 						continue;
   5876 				} else if (n->in_redir & NAT_REDIRECT) {
   5877 					if ((n->in_ndstaddr != 0) ||
   5878 					    (n->in_ndstmsk != 0xffffffff))
   5879 						continue;
   5880 				}
   5881 			}
   5882 #ifdef USE_INET6
   5883 			if (n->in_v[1] == 4) {
   5884 				if (n->in_redir & NAT_MAP) {
   5885 					if (!IP6_ISZERO(&n->in_nsrcaddr) ||
   5886 					    !IP6_ISONES(&n->in_nsrcmsk))
   5887 						continue;
   5888 				} else if (n->in_redir & NAT_REDIRECT) {
   5889 					if (!IP6_ISZERO(&n->in_ndstaddr) ||
   5890 					    !IP6_ISONES(&n->in_ndstmsk))
   5891 						continue;
   5892 				}
   5893 			}
   5894 #endif
   5895 		}
   5896 
   5897 		if (((ifp == NULL) || (ifp == nat->nat_ifps[0]) ||
   5898 		     (ifp == nat->nat_ifps[1]))) {
   5899 			nat->nat_ifps[0] = GETIFP(nat->nat_ifnames[0],
   5900 						  nat->nat_v[0]);
   5901 			if ((nat->nat_ifps[0] != NULL) &&
   5902 			    (nat->nat_ifps[0] != (void *)-1)) {
   5903 				nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
   5904 			}
   5905 			if (nat->nat_ifnames[1][0] != '\0') {
   5906 				nat->nat_ifps[1] = GETIFP(nat->nat_ifnames[1],
   5907 							  nat->nat_v[1]);
   5908 			} else {
   5909 				nat->nat_ifps[1] = nat->nat_ifps[0];
   5910 			}
   5911 			if ((nat->nat_ifps[1] != NULL) &&
   5912 			    (nat->nat_ifps[1] != (void *)-1)) {
   5913 				nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
   5914 			}
   5915 			ifp2 = nat->nat_ifps[0];
   5916 			if (ifp2 == NULL)
   5917 				continue;
   5918 
   5919 			/*
   5920 			 * Change the map-to address to be the same as the
   5921 			 * new one.
   5922 			 */
   5923 			sum1 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
   5924 			if (ipf_ifpaddr(softc, nat->nat_v[0], FRI_NORMAL, ifp2,
   5925 				       &in, NULL) != -1) {
   5926 				if (nat->nat_v[0] == 4)
   5927 					nat->nat_nsrcip = in.in4;
   5928 			}
   5929 			sum2 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
   5930 
   5931 			if (sum1 == sum2)
   5932 				continue;
   5933 			/*
   5934 			 * Readjust the checksum adjustment to take into
   5935 			 * account the new IP#.
   5936 			 */
   5937 			CALC_SUMD(sum1, sum2, sumd);
   5938 			/* XXX - dont change for TCP when solaris does
   5939 			 * hardware checksumming.
   5940 			 */
   5941 			sumd += nat->nat_sumd[0];
   5942 			nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   5943 			nat->nat_sumd[1] = nat->nat_sumd[0];
   5944 		}
   5945 	}
   5946 
   5947 	for (n = softn->ipf_nat_list; (n != NULL); n = n->in_next) {
   5948 		char *base = n->in_names;
   5949 
   5950 		if ((ifp == NULL) || (n->in_ifps[0] == ifp))
   5951 			n->in_ifps[0] = ipf_resolvenic(softc,
   5952 						       base + n->in_ifnames[0],
   5953 						       n->in_v[0]);
   5954 		if ((ifp == NULL) || (n->in_ifps[1] == ifp))
   5955 			n->in_ifps[1] = ipf_resolvenic(softc,
   5956 						       base + n->in_ifnames[1],
   5957 						       n->in_v[1]);
   5958 
   5959 		if (n->in_redir & NAT_REDIRECT)
   5960 			idx = 1;
   5961 		else
   5962 			idx = 0;
   5963 
   5964 		if (((ifp == NULL) || (n->in_ifps[idx] == ifp)) &&
   5965 		    (n->in_ifps[idx] != NULL &&
   5966 		     n->in_ifps[idx] != (void *)-1)) {
   5967 
   5968 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_osrc,
   5969 					     0, n->in_ifps[idx]);
   5970 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_odst,
   5971 					     0, n->in_ifps[idx]);
   5972 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_nsrc,
   5973 					     0, n->in_ifps[idx]);
   5974 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_ndst,
   5975 					     0, n->in_ifps[idx]);
   5976 		}
   5977 	}
   5978 	RWLOCK_EXIT(&softc->ipf_nat);
   5979 	SPL_X(s);
   5980 }
   5981 
   5982 
   5983 /* ------------------------------------------------------------------------ */
   5984 /* Function:    ipf_nat_icmpquerytype                                       */
   5985 /* Returns:     int - 1 == success, 0 == failure                            */
   5986 /* Parameters:  icmptype(I) - ICMP type number                              */
   5987 /*                                                                          */
   5988 /* Tests to see if the ICMP type number passed is a query/response type or  */
   5989 /* not.                                                                     */
   5990 /* ------------------------------------------------------------------------ */
   5991 static int
   5992 ipf_nat_icmpquerytype(int icmptype)
   5993 {
   5994 
   5995 	/*
   5996 	 * For the ICMP query NAT code, it is essential that both the query
   5997 	 * and the reply match on the NAT rule. Because the NAT structure
   5998 	 * does not keep track of the icmptype, and a single NAT structure
   5999 	 * is used for all icmp types with the same src, dest and id, we
   6000 	 * simply define the replies as queries as well. The funny thing is,
   6001 	 * although it seems silly to call a reply a query, this is exactly
   6002 	 * as it is defined in the IPv4 specification
   6003 	 */
   6004 	switch (icmptype)
   6005 	{
   6006 	case ICMP_ECHOREPLY:
   6007 	case ICMP_ECHO:
   6008 	/* route aedvertisement/solliciation is currently unsupported: */
   6009 	/* it would require rewriting the ICMP data section            */
   6010 	case ICMP_TSTAMP:
   6011 	case ICMP_TSTAMPREPLY:
   6012 	case ICMP_IREQ:
   6013 	case ICMP_IREQREPLY:
   6014 	case ICMP_MASKREQ:
   6015 	case ICMP_MASKREPLY:
   6016 		return 1;
   6017 	default:
   6018 		return 0;
   6019 	}
   6020 }
   6021 
   6022 
   6023 /* ------------------------------------------------------------------------ */
   6024 /* Function:    nat_log                                                     */
   6025 /* Returns:     Nil                                                         */
   6026 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6027 /*              softn(I) - pointer to NAT context structure                 */
   6028 /*              nat(I)    - pointer to NAT structure                        */
   6029 /*              action(I) - action related to NAT structure being performed */
   6030 /*                                                                          */
   6031 /* Creates a NAT log entry.                                                 */
   6032 /* ------------------------------------------------------------------------ */
   6033 void
   6034 ipf_nat_log(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, struct nat *nat,
   6035     u_int action)
   6036 {
   6037 #ifdef	IPFILTER_LOG
   6038 # ifndef LARGE_NAT
   6039 	struct ipnat *np;
   6040 	int rulen;
   6041 # endif
   6042 	struct natlog natl;
   6043 	void *items[1];
   6044 	size_t sizes[1];
   6045 	int types[1];
   6046 
   6047 	bcopy((char *)&nat->nat_osrc6, (char *)&natl.nl_osrcip,
   6048 	      sizeof(natl.nl_osrcip));
   6049 	bcopy((char *)&nat->nat_nsrc6, (char *)&natl.nl_nsrcip,
   6050 	      sizeof(natl.nl_nsrcip));
   6051 	bcopy((char *)&nat->nat_odst6, (char *)&natl.nl_odstip,
   6052 	      sizeof(natl.nl_odstip));
   6053 	bcopy((char *)&nat->nat_ndst6, (char *)&natl.nl_ndstip,
   6054 	      sizeof(natl.nl_ndstip));
   6055 
   6056 	natl.nl_bytes[0] = nat->nat_bytes[0];
   6057 	natl.nl_bytes[1] = nat->nat_bytes[1];
   6058 	natl.nl_pkts[0] = nat->nat_pkts[0];
   6059 	natl.nl_pkts[1] = nat->nat_pkts[1];
   6060 	natl.nl_odstport = nat->nat_odport;
   6061 	natl.nl_osrcport = nat->nat_osport;
   6062 	natl.nl_nsrcport = nat->nat_nsport;
   6063 	natl.nl_ndstport = nat->nat_ndport;
   6064 	natl.nl_p[0] = nat->nat_pr[0];
   6065 	natl.nl_p[1] = nat->nat_pr[1];
   6066 	natl.nl_v[0] = nat->nat_v[0];
   6067 	natl.nl_v[1] = nat->nat_v[1];
   6068 	natl.nl_type = nat->nat_redir;
   6069 	natl.nl_action = action;
   6070 	natl.nl_rule = -1;
   6071 
   6072 	bcopy(nat->nat_ifnames[0], natl.nl_ifnames[0],
   6073 	      sizeof(nat->nat_ifnames[0]));
   6074 	bcopy(nat->nat_ifnames[1], natl.nl_ifnames[1],
   6075 	      sizeof(nat->nat_ifnames[1]));
   6076 
   6077 # ifndef LARGE_NAT
   6078 	if (nat->nat_ptr != NULL) {
   6079 		for (rulen = 0, np = softn->ipf_nat_list; np != NULL;
   6080 		     np = np->in_next, rulen++)
   6081 			if (np == nat->nat_ptr) {
   6082 				natl.nl_rule = rulen;
   6083 				break;
   6084 			}
   6085 	}
   6086 # endif
   6087 	items[0] = &natl;
   6088 	sizes[0] = sizeof(natl);
   6089 	types[0] = 0;
   6090 
   6091 	(void) ipf_log_items(softc, IPL_LOGNAT, NULL, items, sizes, types, 1);
   6092 #endif
   6093 }
   6094 
   6095 
   6096 #if defined(__OpenBSD__)
   6097 /* ------------------------------------------------------------------------ */
   6098 /* Function:    ipf_nat_ifdetach                                            */
   6099 /* Returns:     Nil                                                         */
   6100 /* Parameters:  ifp(I) - pointer to network interface                       */
   6101 /*                                                                          */
   6102 /* Compatibility interface for OpenBSD to trigger the correct updating of   */
   6103 /* interface references within IPFilter.                                    */
   6104 /* ------------------------------------------------------------------------ */
   6105 void
   6106 ipf_nat_ifdetach(ifp)
   6107 	void *ifp;
   6108 {
   6109 	ipf_main_softc_t *softc;
   6110 
   6111 	softc = ipf_get_softc(0);
   6112 
   6113 	ipf_sync(ifp);
   6114 	return;
   6115 }
   6116 #endif
   6117 
   6118 
   6119 /* ------------------------------------------------------------------------ */
   6120 /* Function:    ipf_nat_rule_deref                                          */
   6121 /* Returns:     Nil                                                         */
   6122 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6123 /*              inp(I)   - pointer to pointer to NAT rule                   */
   6124 /* Write Locks: ipf_nat                                                     */
   6125 /*                                                                          */
   6126 /* Dropping the refernce count for a rule means that whatever held the      */
   6127 /* pointer to this rule (*inp) is no longer interested in it and when the   */
   6128 /* reference count drops to zero, any resources allocated for the rule can  */
   6129 /* be released and the rule itself free'd.                                  */
   6130 /* ------------------------------------------------------------------------ */
   6131 void
   6132 ipf_nat_rule_deref(ipf_main_softc_t *softc, ipnat_t **inp)
   6133 {
   6134 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6135 	ipnat_t *n;
   6136 
   6137 	n = *inp;
   6138 	*inp = NULL;
   6139 	n->in_use--;
   6140 	if (n->in_use > 0)
   6141 		return;
   6142 
   6143 	if (n->in_apr != NULL)
   6144 		ipf_proxy_deref(n->in_apr);
   6145 
   6146 	ipf_nat_rule_fini(softc, n);
   6147 
   6148 	if (n->in_redir & NAT_REDIRECT) {
   6149 		if ((n->in_flags & IPN_PROXYRULE) == 0) {
   6150 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_rdr);
   6151 		}
   6152 	}
   6153 	if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
   6154 		if ((n->in_flags & IPN_PROXYRULE) == 0) {
   6155 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_map);
   6156 		}
   6157 	}
   6158 
   6159 	if (n->in_tqehead[0] != NULL) {
   6160 		if (ipf_deletetimeoutqueue(n->in_tqehead[0]) == 0) {
   6161 			ipf_freetimeoutqueue(softc, n->in_tqehead[1]);
   6162 		}
   6163 	}
   6164 
   6165 	if (n->in_tqehead[1] != NULL) {
   6166 		if (ipf_deletetimeoutqueue(n->in_tqehead[1]) == 0) {
   6167 			ipf_freetimeoutqueue(softc, n->in_tqehead[1]);
   6168 		}
   6169 	}
   6170 
   6171 	if ((n->in_flags & IPN_PROXYRULE) == 0) {
   6172 		ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules);
   6173 	}
   6174 
   6175 	MUTEX_DESTROY(&n->in_lock);
   6176 
   6177 	KFREES(n, n->in_size);
   6178 
   6179 #if SOLARIS && !defined(INSTANCES)
   6180 	if (softn->ipf_nat_stats.ns_rules == 0)
   6181 		pfil_delayed_copy = 1;
   6182 #endif
   6183 }
   6184 
   6185 
   6186 /* ------------------------------------------------------------------------ */
   6187 /* Function:    ipf_nat_deref                                               */
   6188 /* Returns:     Nil                                                         */
   6189 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6190 /*              natp(I)  - pointer to pointer to NAT table entry            */
   6191 /*                                                                          */
   6192 /* Decrement the reference counter for this NAT table entry and free it if  */
   6193 /* there are no more things using it.                                       */
   6194 /*                                                                          */
   6195 /* IF nat_ref == 1 when this function is called, then we have an orphan nat */
   6196 /* structure *because* it only gets called on paths _after_ nat_ref has been*/
   6197 /* incremented.  If nat_ref == 1 then we shouldn't decrement it here        */
   6198 /* because nat_delete() will do that and send nat_ref to -1.                */
   6199 /*                                                                          */
   6200 /* Holding the lock on nat_lock is required to serialise nat_delete() being */
   6201 /* called from a NAT flush ioctl with a deref happening because of a packet.*/
   6202 /* ------------------------------------------------------------------------ */
   6203 void
   6204 ipf_nat_deref(ipf_main_softc_t *softc, nat_t **natp)
   6205 {
   6206 	nat_t *nat;
   6207 
   6208 	nat = *natp;
   6209 	*natp = NULL;
   6210 
   6211 	MUTEX_ENTER(&nat->nat_lock);
   6212 	if (nat->nat_ref > 1) {
   6213 		nat->nat_ref--;
   6214 		ASSERT(nat->nat_ref >= 0);
   6215 		MUTEX_EXIT(&nat->nat_lock);
   6216 		return;
   6217 	}
   6218 	MUTEX_EXIT(&nat->nat_lock);
   6219 
   6220 	WRITE_ENTER(&softc->ipf_nat);
   6221 	ipf_nat_delete(softc, nat, NL_EXPIRE);
   6222 	RWLOCK_EXIT(&softc->ipf_nat);
   6223 }
   6224 
   6225 
   6226 /* ------------------------------------------------------------------------ */
   6227 /* Function:    ipf_nat_clone                                               */
   6228 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
   6229 /*                           else pointer to new state structure            */
   6230 /* Parameters:  fin(I) - pointer to packet information                      */
   6231 /*              is(I)  - pointer to master state structure                  */
   6232 /* Write Lock:  ipf_nat                                                     */
   6233 /*                                                                          */
   6234 /* Create a "duplcate" state table entry from the master.                   */
   6235 /* ------------------------------------------------------------------------ */
   6236 nat_t *
   6237 ipf_nat_clone(fr_info_t *fin, nat_t *nat)
   6238 {
   6239 	ipf_main_softc_t *softc = fin->fin_main_soft;
   6240 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6241 	frentry_t *fr;
   6242 	nat_t *clone;
   6243 	ipnat_t *np;
   6244 
   6245 	KMALLOC(clone, nat_t *);
   6246 	if (clone == NULL) {
   6247 		NBUMPSIDED(fin->fin_out, ns_clone_nomem);
   6248 		return NULL;
   6249 	}
   6250 	bcopy((char *)nat, (char *)clone, sizeof(*clone));
   6251 
   6252 	MUTEX_NUKE(&clone->nat_lock);
   6253 
   6254 	clone->nat_rev = fin->fin_rev;
   6255 	clone->nat_aps = NULL;
   6256 	/*
   6257 	 * Initialize all these so that ipf_nat_delete() doesn't cause a crash.
   6258 	 */
   6259 	clone->nat_tqe.tqe_pnext = NULL;
   6260 	clone->nat_tqe.tqe_next = NULL;
   6261 	clone->nat_tqe.tqe_ifq = NULL;
   6262 	clone->nat_tqe.tqe_parent = clone;
   6263 
   6264 	clone->nat_flags &= ~SI_CLONE;
   6265 	clone->nat_flags |= SI_CLONED;
   6266 
   6267 	if (clone->nat_hm)
   6268 		clone->nat_hm->hm_ref++;
   6269 
   6270 	if (ipf_nat_insert(softc, softn, clone) == -1) {
   6271 		KFREE(clone);
   6272 		NBUMPSIDED(fin->fin_out, ns_insert_fail);
   6273 		return NULL;
   6274 	}
   6275 
   6276 	np = clone->nat_ptr;
   6277 	if (np != NULL) {
   6278 		if (softn->ipf_nat_logging)
   6279 			ipf_nat_log(softc, softn, clone, NL_CLONE);
   6280 		np->in_use++;
   6281 	}
   6282 	fr = clone->nat_fr;
   6283 	if (fr != NULL) {
   6284 		MUTEX_ENTER(&fr->fr_lock);
   6285 		fr->fr_ref++;
   6286 		MUTEX_EXIT(&fr->fr_lock);
   6287 	}
   6288 
   6289 
   6290 	/*
   6291 	 * Because the clone is created outside the normal loop of things and
   6292 	 * TCP has special needs in terms of state, initialise the timeout
   6293 	 * state of the new NAT from here.
   6294 	 */
   6295 	if (clone->nat_pr[0] == IPPROTO_TCP) {
   6296 		(void) ipf_tcp_age(&clone->nat_tqe, fin, softn->ipf_nat_tcptq,
   6297 				   clone->nat_flags, 2);
   6298 	}
   6299 	clone->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, clone);
   6300 	if (softn->ipf_nat_logging)
   6301 		ipf_nat_log(softc, softn, clone, NL_CLONE);
   6302 	return clone;
   6303 }
   6304 
   6305 
   6306 /* ------------------------------------------------------------------------ */
   6307 /* Function:   ipf_nat_wildok                                               */
   6308 /* Returns:    int - 1 == packet's ports match wildcards                    */
   6309 /*                   0 == packet's ports don't match wildcards              */
   6310 /* Parameters: nat(I)   - NAT entry                                         */
   6311 /*             sport(I) - source port                                       */
   6312 /*             dport(I) - destination port                                  */
   6313 /*             flags(I) - wildcard flags                                    */
   6314 /*             dir(I)   - packet direction                                  */
   6315 /*                                                                          */
   6316 /* Use NAT entry and packet direction to determine which combination of     */
   6317 /* wildcard flags should be used.                                           */
   6318 /* ------------------------------------------------------------------------ */
   6319 int
   6320 ipf_nat_wildok(nat_t *nat, int sport, int dport, int flags, int dir)
   6321 {
   6322 	/*
   6323 	 * When called by       dir is set to
   6324 	 * nat_inlookup         NAT_INBOUND (0)
   6325 	 * nat_outlookup        NAT_OUTBOUND (1)
   6326 	 *
   6327 	 * We simply combine the packet's direction in dir with the original
   6328 	 * "intended" direction of that NAT entry in nat->nat_dir to decide
   6329 	 * which combination of wildcard flags to allow.
   6330 	 */
   6331 	switch ((dir << 1) | (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND)))
   6332 	{
   6333 	case 3: /* outbound packet / outbound entry */
   6334 		if (((nat->nat_osport == sport) ||
   6335 		    (flags & SI_W_SPORT)) &&
   6336 		    ((nat->nat_odport == dport) ||
   6337 		    (flags & SI_W_DPORT)))
   6338 			return 1;
   6339 		break;
   6340 	case 2: /* outbound packet / inbound entry */
   6341 		if (((nat->nat_osport == dport) ||
   6342 		    (flags & SI_W_SPORT)) &&
   6343 		    ((nat->nat_odport == sport) ||
   6344 		    (flags & SI_W_DPORT)))
   6345 			return 1;
   6346 		break;
   6347 	case 1: /* inbound packet / outbound entry */
   6348 		if (((nat->nat_osport == dport) ||
   6349 		    (flags & SI_W_SPORT)) &&
   6350 		    ((nat->nat_odport == sport) ||
   6351 		    (flags & SI_W_DPORT)))
   6352 			return 1;
   6353 		break;
   6354 	case 0: /* inbound packet / inbound entry */
   6355 		if (((nat->nat_osport == sport) ||
   6356 		    (flags & SI_W_SPORT)) &&
   6357 		    ((nat->nat_odport == dport) ||
   6358 		    (flags & SI_W_DPORT)))
   6359 			return 1;
   6360 		break;
   6361 	default:
   6362 		break;
   6363 	}
   6364 
   6365 	return(0);
   6366 }
   6367 
   6368 
   6369 /* ------------------------------------------------------------------------ */
   6370 /* Function:    nat_mssclamp                                                */
   6371 /* Returns:     Nil                                                         */
   6372 /* Parameters:  tcp(I)    - pointer to TCP header                           */
   6373 /*              maxmss(I) - value to clamp the TCP MSS to                   */
   6374 /*              fin(I)    - pointer to packet information                   */
   6375 /*              csump(I)  - pointer to TCP checksum                         */
   6376 /*                                                                          */
   6377 /* Check for MSS option and clamp it if necessary.  If found and changed,   */
   6378 /* then the TCP header checksum will be updated to reflect the change in    */
   6379 /* the MSS.                                                                 */
   6380 /* ------------------------------------------------------------------------ */
   6381 static void
   6382 ipf_nat_mssclamp(tcphdr_t *tcp, u_32_t maxmss, fr_info_t *fin, u_short *csump)
   6383 {
   6384 	u_char *cp, *ep, opt;
   6385 	int hlen, advance;
   6386 	u_32_t mss, sumd;
   6387 
   6388 	hlen = TCP_OFF(tcp) << 2;
   6389 	if (hlen > sizeof(*tcp)) {
   6390 		cp = (u_char *)tcp + sizeof(*tcp);
   6391 		ep = (u_char *)tcp + hlen;
   6392 
   6393 		while (cp < ep) {
   6394 			opt = cp[0];
   6395 			if (opt == TCPOPT_EOL)
   6396 				break;
   6397 			else if (opt == TCPOPT_NOP) {
   6398 				cp++;
   6399 				continue;
   6400 			}
   6401 
   6402 			if (cp + 1 >= ep)
   6403 				break;
   6404 			advance = cp[1];
   6405 			if ((cp + advance > ep) || (advance <= 0))
   6406 				break;
   6407 			switch (opt)
   6408 			{
   6409 			case TCPOPT_MAXSEG:
   6410 				if (advance != 4)
   6411 					break;
   6412 				mss = cp[2] * 256 + cp[3];
   6413 				if (mss > maxmss) {
   6414 					cp[2] = maxmss / 256;
   6415 					cp[3] = maxmss & 0xff;
   6416 					CALC_SUMD(mss, maxmss, sumd);
   6417 					ipf_fix_outcksum(0, csump, sumd, 0);
   6418 				}
   6419 				break;
   6420 			default:
   6421 				/* ignore unknown options */
   6422 				break;
   6423 			}
   6424 
   6425 			cp += advance;
   6426 		}
   6427 	}
   6428 }
   6429 
   6430 
   6431 /* ------------------------------------------------------------------------ */
   6432 /* Function:    ipf_nat_setqueue                                            */
   6433 /* Returns:     Nil                                                         */
   6434 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6435 /*              softn(I) - pointer to NAT context structure                 */
   6436 /*              nat(I)- pointer to NAT structure                            */
   6437 /* Locks:       ipf_nat (read or write)                                     */
   6438 /*                                                                          */
   6439 /* Put the NAT entry on its default queue entry, using rev as a helped in   */
   6440 /* determining which queue it should be placed on.                          */
   6441 /* ------------------------------------------------------------------------ */
   6442 void
   6443 ipf_nat_setqueue(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, nat_t *nat)
   6444 {
   6445 	ipftq_t *oifq, *nifq;
   6446 	int rev = nat->nat_rev;
   6447 
   6448 	if (nat->nat_ptr != NULL)
   6449 		nifq = nat->nat_ptr->in_tqehead[rev];
   6450 	else
   6451 		nifq = NULL;
   6452 
   6453 	if (nifq == NULL) {
   6454 		switch (nat->nat_pr[0])
   6455 		{
   6456 		case IPPROTO_UDP :
   6457 			nifq = &softn->ipf_nat_udptq;
   6458 			break;
   6459 		case IPPROTO_ICMP :
   6460 			nifq = &softn->ipf_nat_icmptq;
   6461 			break;
   6462 		case IPPROTO_TCP :
   6463 			nifq = softn->ipf_nat_tcptq +
   6464 			       nat->nat_tqe.tqe_state[rev];
   6465 			break;
   6466 		default :
   6467 			nifq = &softn->ipf_nat_iptq;
   6468 			break;
   6469 		}
   6470 	}
   6471 
   6472 	oifq = nat->nat_tqe.tqe_ifq;
   6473 	/*
   6474 	 * If it's currently on a timeout queue, move it from one queue to
   6475 	 * another, else put it on the end of the newly determined queue.
   6476 	 */
   6477 	if (oifq != NULL)
   6478 		ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq, nifq);
   6479 	else
   6480 		ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe, nifq, nat);
   6481 	return;
   6482 }
   6483 
   6484 
   6485 /* ------------------------------------------------------------------------ */
   6486 /* Function:    nat_getnext                                                 */
   6487 /* Returns:     int - 0 == ok, else error                                   */
   6488 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6489 /*              t(I)   - pointer to ipftoken structure                      */
   6490 /*              itp(I) - pointer to ipfgeniter_t structure                  */
   6491 /*                                                                          */
   6492 /* Fetch the next nat/ipnat structure pointer from the linked list and      */
   6493 /* copy it out to the storage space pointed to by itp_data.  The next item  */
   6494 /* in the list to look at is put back in the ipftoken struture.             */
   6495 /* ------------------------------------------------------------------------ */
   6496 static int
   6497 ipf_nat_getnext(ipf_main_softc_t *softc, ipftoken_t *t, ipfgeniter_t *itp,
   6498     ipfobj_t *objp)
   6499 {
   6500 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6501 	hostmap_t *hm, *nexthm = NULL, zerohm;
   6502 	ipnat_t *ipn, *nextipnat = NULL, zeroipn;
   6503 	nat_t *nat, *nextnat = NULL, zeronat;
   6504 	int error = 0;
   6505 	void *nnext;
   6506 
   6507 	if (itp->igi_nitems != 1) {
   6508 		IPFERROR(60075);
   6509 		return ENOSPC;
   6510 	}
   6511 
   6512 	READ_ENTER(&softc->ipf_nat);
   6513 
   6514 	switch (itp->igi_type)
   6515 	{
   6516 	case IPFGENITER_HOSTMAP :
   6517 		hm = t->ipt_data;
   6518 		if (hm == NULL) {
   6519 			nexthm = softn->ipf_hm_maplist;
   6520 		} else {
   6521 			nexthm = hm->hm_next;
   6522 		}
   6523 		if (nexthm != NULL) {
   6524 			ATOMIC_INC32(nexthm->hm_ref);
   6525 			t->ipt_data = nexthm;
   6526 		} else {
   6527 			bzero(&zerohm, sizeof(zerohm));
   6528 			nexthm = &zerohm;
   6529 			t->ipt_data = NULL;
   6530 		}
   6531 		nnext = nexthm->hm_next;
   6532 		break;
   6533 
   6534 	case IPFGENITER_IPNAT :
   6535 		ipn = t->ipt_data;
   6536 		if (ipn == NULL) {
   6537 			nextipnat = softn->ipf_nat_list;
   6538 		} else {
   6539 			nextipnat = ipn->in_next;
   6540 		}
   6541 		if (nextipnat != NULL) {
   6542 			ATOMIC_INC32(nextipnat->in_use);
   6543 			t->ipt_data = nextipnat;
   6544 		} else {
   6545 			bzero(&zeroipn, sizeof(zeroipn));
   6546 			nextipnat = &zeroipn;
   6547 			t->ipt_data = NULL;
   6548 		}
   6549 		nnext = nextipnat->in_next;
   6550 		break;
   6551 
   6552 	case IPFGENITER_NAT :
   6553 		nat = t->ipt_data;
   6554 		if (nat == NULL) {
   6555 			nextnat = softn->ipf_nat_instances;
   6556 		} else {
   6557 			nextnat = nat->nat_next;
   6558 		}
   6559 		if (nextnat != NULL) {
   6560 			MUTEX_ENTER(&nextnat->nat_lock);
   6561 			nextnat->nat_ref++;
   6562 			MUTEX_EXIT(&nextnat->nat_lock);
   6563 			t->ipt_data = nextnat;
   6564 		} else {
   6565 			bzero(&zeronat, sizeof(zeronat));
   6566 			nextnat = &zeronat;
   6567 			t->ipt_data = NULL;
   6568 		}
   6569 		nnext = nextnat->nat_next;
   6570 		break;
   6571 
   6572 	default :
   6573 		RWLOCK_EXIT(&softc->ipf_nat);
   6574 		IPFERROR(60055);
   6575 		return EINVAL;
   6576 	}
   6577 
   6578 	RWLOCK_EXIT(&softc->ipf_nat);
   6579 
   6580 	objp->ipfo_ptr = itp->igi_data;
   6581 
   6582 	switch (itp->igi_type)
   6583 	{
   6584 	case IPFGENITER_HOSTMAP :
   6585 		error = COPYOUT(nexthm, objp->ipfo_ptr, sizeof(*nexthm));
   6586 		if (error != 0) {
   6587 			IPFERROR(60049);
   6588 			error = EFAULT;
   6589 		}
   6590 		if (hm != NULL) {
   6591 			WRITE_ENTER(&softc->ipf_nat);
   6592 			ipf_nat_hostmapdel(softc, &hm);
   6593 			RWLOCK_EXIT(&softc->ipf_nat);
   6594 		}
   6595 		break;
   6596 
   6597 	case IPFGENITER_IPNAT :
   6598 		objp->ipfo_size = nextipnat->in_size;
   6599 		objp->ipfo_type = IPFOBJ_IPNAT;
   6600 		error = ipf_outobjk(softc, objp, nextipnat);
   6601 		if (ipn != NULL) {
   6602 			WRITE_ENTER(&softc->ipf_nat);
   6603 			ipf_nat_rule_deref(softc, &ipn);
   6604 			RWLOCK_EXIT(&softc->ipf_nat);
   6605 		}
   6606 		break;
   6607 
   6608 	case IPFGENITER_NAT :
   6609 		objp->ipfo_size = sizeof(nat_t);
   6610 		objp->ipfo_type = IPFOBJ_NAT;
   6611 		error = ipf_outobjk(softc, objp, nextnat);
   6612 		if (nat != NULL)
   6613 			ipf_nat_deref(softc, &nat);
   6614 
   6615 		break;
   6616 	}
   6617 
   6618 	if (nnext == NULL)
   6619 		ipf_token_mark_complete(t);
   6620 
   6621 	return error;
   6622 }
   6623 
   6624 
   6625 /* ------------------------------------------------------------------------ */
   6626 /* Function:    nat_extraflush                                              */
   6627 /* Returns:     int - 0 == success, -1 == failure                           */
   6628 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6629 /*              softn(I) - pointer to NAT context structure                 */
   6630 /*              which(I) - how to flush the active NAT table                */
   6631 /* Write Locks: ipf_nat                                                     */
   6632 /*                                                                          */
   6633 /* Flush nat tables.  Three actions currently defined:                      */
   6634 /* which == 0 : flush all nat table entries                                 */
   6635 /* which == 1 : flush TCP connections which have started to close but are   */
   6636 /*	      stuck for some reason.                                        */
   6637 /* which == 2 : flush TCP connections which have been idle for a long time, */
   6638 /*	      starting at > 4 days idle and working back in successive half-*/
   6639 /*	      days to at most 12 hours old.  If this fails to free enough   */
   6640 /*            slots then work backwards in half hour slots to 30 minutes.   */
   6641 /*            If that too fails, then work backwards in 30 second intervals */
   6642 /*            for the last 30 minutes to at worst 30 seconds idle.          */
   6643 /* ------------------------------------------------------------------------ */
   6644 static int
   6645 ipf_nat_extraflush(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, int which)
   6646 {
   6647 	nat_t *nat, **natp;
   6648 	ipftqent_t *tqn;
   6649 	ipftq_t *ifq;
   6650 	int removed;
   6651 	SPL_INT(s);
   6652 
   6653 	removed = 0;
   6654 
   6655 	SPL_NET(s);
   6656 	switch (which)
   6657 	{
   6658 	case 0 :
   6659 		softn->ipf_nat_stats.ns_flush_all++;
   6660 		/*
   6661 		 * Style 0 flush removes everything...
   6662 		 */
   6663 		for (natp = &softn->ipf_nat_instances;
   6664 		     ((nat = *natp) != NULL); ) {
   6665 			ipf_nat_delete(softc, nat, NL_FLUSH);
   6666 			removed++;
   6667 		}
   6668 		break;
   6669 
   6670 	case 1 :
   6671 		softn->ipf_nat_stats.ns_flush_closing++;
   6672 		/*
   6673 		 * Since we're only interested in things that are closing,
   6674 		 * we can start with the appropriate timeout queue.
   6675 		 */
   6676 		for (ifq = softn->ipf_nat_tcptq + IPF_TCPS_CLOSE_WAIT;
   6677 		     ifq != NULL; ifq = ifq->ifq_next) {
   6678 
   6679 			for (tqn = ifq->ifq_head; tqn != NULL; ) {
   6680 				nat = tqn->tqe_parent;
   6681 				tqn = tqn->tqe_next;
   6682 				if (nat->nat_pr[0] != IPPROTO_TCP ||
   6683 				    nat->nat_pr[1] != IPPROTO_TCP)
   6684 					break;
   6685 				ipf_nat_delete(softc, nat, NL_EXPIRE);
   6686 				removed++;
   6687 			}
   6688 		}
   6689 
   6690 		/*
   6691 		 * Also need to look through the user defined queues.
   6692 		 */
   6693 		for (ifq = softn->ipf_nat_utqe; ifq != NULL;
   6694 		     ifq = ifq->ifq_next) {
   6695 			for (tqn = ifq->ifq_head; tqn != NULL; ) {
   6696 				nat = tqn->tqe_parent;
   6697 				tqn = tqn->tqe_next;
   6698 				if (nat->nat_pr[0] != IPPROTO_TCP ||
   6699 				    nat->nat_pr[1] != IPPROTO_TCP)
   6700 					continue;
   6701 
   6702 				if ((nat->nat_tcpstate[0] >
   6703 				     IPF_TCPS_ESTABLISHED) &&
   6704 				    (nat->nat_tcpstate[1] >
   6705 				     IPF_TCPS_ESTABLISHED)) {
   6706 					ipf_nat_delete(softc, nat, NL_EXPIRE);
   6707 					removed++;
   6708 				}
   6709 			}
   6710 		}
   6711 		break;
   6712 
   6713 		/*
   6714 		 * Args 5-11 correspond to flushing those particular states
   6715 		 * for TCP connections.
   6716 		 */
   6717 	case IPF_TCPS_CLOSE_WAIT :
   6718 	case IPF_TCPS_FIN_WAIT_1 :
   6719 	case IPF_TCPS_CLOSING :
   6720 	case IPF_TCPS_LAST_ACK :
   6721 	case IPF_TCPS_FIN_WAIT_2 :
   6722 	case IPF_TCPS_TIME_WAIT :
   6723 	case IPF_TCPS_CLOSED :
   6724 		softn->ipf_nat_stats.ns_flush_state++;
   6725 		tqn = softn->ipf_nat_tcptq[which].ifq_head;
   6726 		while (tqn != NULL) {
   6727 			nat = tqn->tqe_parent;
   6728 			tqn = tqn->tqe_next;
   6729 			ipf_nat_delete(softc, nat, NL_FLUSH);
   6730 			removed++;
   6731 		}
   6732 		break;
   6733 
   6734 	default :
   6735 		if (which < 30)
   6736 			break;
   6737 
   6738 		softn->ipf_nat_stats.ns_flush_timeout++;
   6739 		/*
   6740 		 * Take a large arbitrary number to mean the number of seconds
   6741 		 * for which which consider to be the maximum value we'll allow
   6742 		 * the expiration to be.
   6743 		 */
   6744 		which = IPF_TTLVAL(which);
   6745 		for (natp = &softn->ipf_nat_instances;
   6746 		     ((nat = *natp) != NULL); ) {
   6747 			if (softc->ipf_ticks - nat->nat_touched > which) {
   6748 				ipf_nat_delete(softc, nat, NL_FLUSH);
   6749 				removed++;
   6750 			} else
   6751 				natp = &nat->nat_next;
   6752 		}
   6753 		break;
   6754 	}
   6755 
   6756 	if (which != 2) {
   6757 		SPL_X(s);
   6758 		return removed;
   6759 	}
   6760 
   6761 	softn->ipf_nat_stats.ns_flush_queue++;
   6762 
   6763 	/*
   6764 	 * Asked to remove inactive entries because the table is full, try
   6765 	 * again, 3 times, if first attempt failed with a different criteria
   6766 	 * each time.  The order tried in must be in decreasing age.
   6767 	 * Another alternative is to implement random drop and drop N entries
   6768 	 * at random until N have been freed up.
   6769 	 */
   6770 	if (softc->ipf_ticks - softn->ipf_nat_last_force_flush >
   6771 	    IPF_TTLVAL(5)) {
   6772 		softn->ipf_nat_last_force_flush = softc->ipf_ticks;
   6773 
   6774 		removed = ipf_queueflush(softc, ipf_nat_flush_entry,
   6775 					 softn->ipf_nat_tcptq,
   6776 					 softn->ipf_nat_utqe,
   6777 					 &softn->ipf_nat_stats.ns_active,
   6778 					 softn->ipf_nat_table_sz,
   6779 					 softn->ipf_nat_table_wm_low);
   6780 	}
   6781 
   6782 	SPL_X(s);
   6783 	return removed;
   6784 }
   6785 
   6786 
   6787 /* ------------------------------------------------------------------------ */
   6788 /* Function:    ipf_nat_flush_entry                                         */
   6789 /* Returns:     0 - always succeeds                                         */
   6790 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6791 /*              entry(I) - pointer to NAT entry                             */
   6792 /* Write Locks: ipf_nat                                                     */
   6793 /*                                                                          */
   6794 /* This function is a stepping stone between ipf_queueflush() and           */
   6795 /* nat_dlete().  It is used so we can provide a uniform interface via the   */
   6796 /* ipf_queueflush() function.  Since the nat_delete() function returns void */
   6797 /* we translate that to mean it always succeeds in deleting something.      */
   6798 /* ------------------------------------------------------------------------ */
   6799 static int
   6800 ipf_nat_flush_entry(ipf_main_softc_t *softc, void *entry)
   6801 {
   6802 	ipf_nat_delete(softc, entry, NL_FLUSH);
   6803 	return 0;
   6804 }
   6805 
   6806 
   6807 /* ------------------------------------------------------------------------ */
   6808 /* Function:    ipf_nat_iterator                                            */
   6809 /* Returns:     int - 0 == ok, else error                                   */
   6810 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6811 /*              token(I) - pointer to ipftoken structure                    */
   6812 /*              itp(I)   - pointer to ipfgeniter_t structure                */
   6813 /*              obj(I)   - pointer to data description structure            */
   6814 /*                                                                          */
   6815 /* This function acts as a handler for the SIOCGENITER ioctls that use a    */
   6816 /* generic structure to iterate through a list.  There are three different  */
   6817 /* linked lists of NAT related information to go through: NAT rules, active */
   6818 /* NAT mappings and the NAT fragment cache.                                 */
   6819 /* ------------------------------------------------------------------------ */
   6820 static int
   6821 ipf_nat_iterator(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp,
   6822     ipfobj_t *obj)
   6823 {
   6824 	int error;
   6825 
   6826 	if (itp->igi_data == NULL) {
   6827 		IPFERROR(60052);
   6828 		return EFAULT;
   6829 	}
   6830 
   6831 	switch (itp->igi_type)
   6832 	{
   6833 	case IPFGENITER_HOSTMAP :
   6834 	case IPFGENITER_IPNAT :
   6835 	case IPFGENITER_NAT :
   6836 		error = ipf_nat_getnext(softc, token, itp, obj);
   6837 		break;
   6838 
   6839 	case IPFGENITER_NATFRAG :
   6840 		error = ipf_frag_nat_next(softc, token, itp);
   6841 		break;
   6842 	default :
   6843 		IPFERROR(60053);
   6844 		error = EINVAL;
   6845 		break;
   6846 	}
   6847 
   6848 	return error;
   6849 }
   6850 
   6851 
   6852 /* ------------------------------------------------------------------------ */
   6853 /* Function:    ipf_nat_setpending                                          */
   6854 /* Returns:     Nil                                                         */
   6855 /* Parameters:  softc(I) - pointer to soft context main structure           */
   6856 /*              nat(I)   - pointer to NAT structure                         */
   6857 /* Locks:       ipf_nat (read or write)                                     */
   6858 /*                                                                          */
   6859 /* Put the NAT entry on to the pending queue - this queue has a very short  */
   6860 /* lifetime where items are put that can't be deleted straight away because */
   6861 /* of locking issues but we want to delete them ASAP, anyway.  In calling   */
   6862 /* this function, it is assumed that the owner (if there is one, as shown   */
   6863 /* by nat_me) is no longer interested in it.                                */
   6864 /* ------------------------------------------------------------------------ */
   6865 void
   6866 ipf_nat_setpending(ipf_main_softc_t *softc, nat_t *nat)
   6867 {
   6868 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   6869 	ipftq_t *oifq;
   6870 
   6871 	oifq = nat->nat_tqe.tqe_ifq;
   6872 	if (oifq != NULL)
   6873 		ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq,
   6874 			      &softn->ipf_nat_pending);
   6875 	else
   6876 		ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe,
   6877 				&softn->ipf_nat_pending, nat);
   6878 
   6879 	if (nat->nat_me != NULL) {
   6880 		*nat->nat_me = NULL;
   6881 		nat->nat_me = NULL;
   6882 		nat->nat_ref--;
   6883 		ASSERT(nat->nat_ref >= 0);
   6884 	}
   6885 }
   6886 
   6887 
   6888 /* ------------------------------------------------------------------------ */
   6889 /* Function:    nat_newrewrite                                              */
   6890 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
   6891 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
   6892 /* Parameters:  fin(I) - pointer to packet information                      */
   6893 /*              nat(I) - pointer to NAT entry                               */
   6894 /*              ni(I)  - pointer to structure with misc. information needed */
   6895 /*                       to create new NAT entry.                           */
   6896 /* Write Lock:  ipf_nat                                                     */
   6897 /*                                                                          */
   6898 /* This function is responsible for setting up an active NAT session where  */
   6899 /* we are changing both the source and destination parameters at the same   */
   6900 /* time.  The loop in here works differently to elsewhere - each iteration  */
   6901 /* is responsible for changing a single parameter that can be incremented.  */
   6902 /* So one pass may increase the source IP#, next source port, next dest. IP#*/
   6903 /* and the last destination port for a total of 4 iterations to try each.   */
   6904 /* This is done to try and exhaustively use the translation space available.*/
   6905 /* ------------------------------------------------------------------------ */
   6906 static int
   6907 ipf_nat_newrewrite(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
   6908 {
   6909 	int src_search = 1;
   6910 	int dst_search = 1;
   6911 	fr_info_t frnat;
   6912 	u_32_t flags;
   6913 	u_short swap;
   6914 	ipnat_t *np;
   6915 	nat_t *natl;
   6916 	int l = 0;
   6917 	int changed;
   6918 
   6919 	natl = NULL;
   6920 	changed = -1;
   6921 	np = nai->nai_np;
   6922 	flags = nat->nat_flags;
   6923 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   6924 
   6925 	nat->nat_hm = NULL;
   6926 
   6927 	do {
   6928 		changed = -1;
   6929 		/* TRACE (l, src_search, dst_search, np) */
   6930 
   6931 		if ((src_search == 0) && (np->in_spnext == 0) &&
   6932 		    (dst_search == 0) && (np->in_dpnext == 0)) {
   6933 			if (l > 0)
   6934 				return -1;
   6935 		}
   6936 
   6937 		/*
   6938 		 * Find a new source address
   6939 		 */
   6940 		if (ipf_nat_nextaddr(fin, &np->in_nsrc, &frnat.fin_saddr,
   6941 				     &frnat.fin_saddr) == -1) {
   6942 			return -1;
   6943 		}
   6944 
   6945 		if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0xffffffff)) {
   6946 			src_search = 0;
   6947 			if (np->in_stepnext == 0)
   6948 				np->in_stepnext = 1;
   6949 
   6950 		} else if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0)) {
   6951 			src_search = 0;
   6952 			if (np->in_stepnext == 0)
   6953 				np->in_stepnext = 1;
   6954 
   6955 		} else if (np->in_nsrcmsk == 0xffffffff) {
   6956 			src_search = 0;
   6957 			if (np->in_stepnext == 0)
   6958 				np->in_stepnext = 1;
   6959 
   6960 		} else if (np->in_nsrcmsk != 0xffffffff) {
   6961 			if (np->in_stepnext == 0 && changed == -1) {
   6962 				np->in_snip++;
   6963 				np->in_stepnext++;
   6964 				changed = 0;
   6965 			}
   6966 		}
   6967 
   6968 		if ((flags & IPN_TCPUDPICMP) != 0) {
   6969 			if (np->in_spnext != 0)
   6970 				frnat.fin_data[0] = np->in_spnext;
   6971 
   6972 			/*
   6973 			 * Standard port translation.  Select next port.
   6974 			 */
   6975 			if ((flags & IPN_FIXEDSPORT) != 0) {
   6976 				np->in_stepnext = 2;
   6977 			} else if ((np->in_stepnext == 1) &&
   6978 				   (changed == -1) && (natl != NULL)) {
   6979 				np->in_spnext++;
   6980 				np->in_stepnext++;
   6981 				changed = 1;
   6982 				if (np->in_spnext > np->in_spmax)
   6983 					np->in_spnext = np->in_spmin;
   6984 			}
   6985 		} else {
   6986 			np->in_stepnext = 2;
   6987 		}
   6988 		np->in_stepnext &= 0x3;
   6989 
   6990 		/*
   6991 		 * Find a new destination address
   6992 		 */
   6993 		/* TRACE (fin, np, l, frnat) */
   6994 
   6995 		if (ipf_nat_nextaddr(fin, &np->in_ndst, &frnat.fin_daddr,
   6996 				     &frnat.fin_daddr) == -1)
   6997 			return -1;
   6998 		if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0xffffffff)) {
   6999 			dst_search = 0;
   7000 			if (np->in_stepnext == 2)
   7001 				np->in_stepnext = 3;
   7002 
   7003 		} else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0)) {
   7004 			dst_search = 0;
   7005 			if (np->in_stepnext == 2)
   7006 				np->in_stepnext = 3;
   7007 
   7008 		} else if (np->in_ndstmsk == 0xffffffff) {
   7009 			dst_search = 0;
   7010 			if (np->in_stepnext == 2)
   7011 				np->in_stepnext = 3;
   7012 
   7013 		} else if (np->in_ndstmsk != 0xffffffff) {
   7014 			if ((np->in_stepnext == 2) && (changed == -1) &&
   7015 			    (natl != NULL)) {
   7016 				changed = 2;
   7017 				np->in_stepnext++;
   7018 				np->in_dnip++;
   7019 			}
   7020 		}
   7021 
   7022 		if ((flags & IPN_TCPUDPICMP) != 0) {
   7023 			if (np->in_dpnext != 0)
   7024 				frnat.fin_data[1] = np->in_dpnext;
   7025 
   7026 			/*
   7027 			 * Standard port translation.  Select next port.
   7028 			 */
   7029 			if ((flags & IPN_FIXEDDPORT) != 0) {
   7030 				np->in_stepnext = 0;
   7031 			} else if (np->in_stepnext == 3 && changed == -1) {
   7032 				np->in_dpnext++;
   7033 				np->in_stepnext++;
   7034 				changed = 3;
   7035 				if (np->in_dpnext > np->in_dpmax)
   7036 					np->in_dpnext = np->in_dpmin;
   7037 			}
   7038 		} else {
   7039 			if (np->in_stepnext == 3)
   7040 				np->in_stepnext = 0;
   7041 		}
   7042 
   7043 		/* TRACE (frnat) */
   7044 
   7045 		/*
   7046 		 * Here we do a lookup of the connection as seen from
   7047 		 * the outside.  If an IP# pair already exists, try
   7048 		 * again.  So if you have A->B becomes C->B, you can
   7049 		 * also have D->E become C->E but not D->B causing
   7050 		 * another C->B.  Also take protocol and ports into
   7051 		 * account when determining whether a pre-existing
   7052 		 * NAT setup will cause an external conflict where
   7053 		 * this is appropriate.
   7054 		 *
   7055 		 * fin_data[] is swapped around because we are doing a
   7056 		 * lookup of the packet is if it were moving in the opposite
   7057 		 * direction of the one we are working with now.
   7058 		 */
   7059 		if (flags & IPN_TCPUDP) {
   7060 			swap = frnat.fin_data[0];
   7061 			frnat.fin_data[0] = frnat.fin_data[1];
   7062 			frnat.fin_data[1] = swap;
   7063 		}
   7064 		if (fin->fin_out == 1) {
   7065 			natl = ipf_nat_inlookup(&frnat,
   7066 						flags & ~(SI_WILDP|NAT_SEARCH),
   7067 						(u_int)frnat.fin_p,
   7068 						frnat.fin_dst, frnat.fin_src);
   7069 
   7070 		} else {
   7071 			natl = ipf_nat_outlookup(&frnat,
   7072 						 flags & ~(SI_WILDP|NAT_SEARCH),
   7073 						 (u_int)frnat.fin_p,
   7074 						 frnat.fin_dst, frnat.fin_src);
   7075 		}
   7076 		if (flags & IPN_TCPUDP) {
   7077 			swap = frnat.fin_data[0];
   7078 			frnat.fin_data[0] = frnat.fin_data[1];
   7079 			frnat.fin_data[1] = swap;
   7080 		}
   7081 
   7082 		/* TRACE natl, in_stepnext, l */
   7083 
   7084 		if ((natl != NULL) && (l > 8))	/* XXX 8 is arbitrary */
   7085 			return -1;
   7086 
   7087 		np->in_stepnext &= 0x3;
   7088 
   7089 		l++;
   7090 		changed = -1;
   7091 	} while (natl != NULL);
   7092 
   7093 	nat->nat_osrcip = fin->fin_src;
   7094 	nat->nat_odstip = fin->fin_dst;
   7095 	nat->nat_nsrcip = frnat.fin_src;
   7096 	nat->nat_ndstip = frnat.fin_dst;
   7097 
   7098 	if ((flags & IPN_TCPUDP) != 0) {
   7099 		nat->nat_osport = htons(fin->fin_data[0]);
   7100 		nat->nat_odport = htons(fin->fin_data[1]);
   7101 		nat->nat_nsport = htons(frnat.fin_data[0]);
   7102 		nat->nat_ndport = htons(frnat.fin_data[1]);
   7103 	} else if ((flags & IPN_ICMPQUERY) != 0) {
   7104 		nat->nat_oicmpid = fin->fin_data[1];
   7105 		nat->nat_nicmpid = frnat.fin_data[1];
   7106 	}
   7107 
   7108 	return 0;
   7109 }
   7110 
   7111 
   7112 /* ------------------------------------------------------------------------ */
   7113 /* Function:    nat_newdivert                                               */
   7114 /* Returns:     int - -1 == error, 0 == success                             */
   7115 /* Parameters:  fin(I) - pointer to packet information                      */
   7116 /*              nat(I) - pointer to NAT entry                               */
   7117 /*              ni(I)  - pointer to structure with misc. information needed */
   7118 /*                       to create new NAT entry.                           */
   7119 /* Write Lock:  ipf_nat                                                     */
   7120 /*                                                                          */
   7121 /* Create a new NAT  divert session as defined by the NAT rule.  This is    */
   7122 /* somewhat different to other NAT session creation routines because we     */
   7123 /* do not iterate through either port numbers or IP addresses, searching    */
   7124 /* for a unique mapping, however, a complimentary duplicate check is made.  */
   7125 /* ------------------------------------------------------------------------ */
   7126 static int
   7127 ipf_nat_newdivert(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
   7128 {
   7129 	ipf_main_softc_t *softc = fin->fin_main_soft;
   7130 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7131 	fr_info_t frnat;
   7132 	ipnat_t *np;
   7133 	nat_t *natl;
   7134 	int p;
   7135 
   7136 	np = nai->nai_np;
   7137 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   7138 
   7139 	nat->nat_pr[0] = 0;
   7140 	nat->nat_osrcaddr = fin->fin_saddr;
   7141 	nat->nat_odstaddr = fin->fin_daddr;
   7142 	frnat.fin_saddr = htonl(np->in_snip);
   7143 	frnat.fin_daddr = htonl(np->in_dnip);
   7144 	if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   7145 		nat->nat_osport = htons(fin->fin_data[0]);
   7146 		nat->nat_odport = htons(fin->fin_data[1]);
   7147 	} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   7148 		nat->nat_oicmpid = fin->fin_data[1];
   7149 	}
   7150 
   7151 	if (np->in_redir & NAT_DIVERTUDP) {
   7152 		frnat.fin_data[0] = np->in_spnext;
   7153 		frnat.fin_data[1] = np->in_dpnext;
   7154 		frnat.fin_flx |= FI_TCPUDP;
   7155 		p = IPPROTO_UDP;
   7156 	} else {
   7157 		frnat.fin_flx &= ~FI_TCPUDP;
   7158 		p = IPPROTO_IPIP;
   7159 	}
   7160 
   7161 	if (fin->fin_out == 1) {
   7162 		natl = ipf_nat_inlookup(&frnat, 0, p,
   7163 					frnat.fin_dst, frnat.fin_src);
   7164 
   7165 	} else {
   7166 		natl = ipf_nat_outlookup(&frnat, 0, p,
   7167 					 frnat.fin_dst, frnat.fin_src);
   7168 	}
   7169 
   7170 	if (natl != NULL) {
   7171 		NBUMPSIDED(fin->fin_out, ns_divert_exist);
   7172 		return -1;
   7173 	}
   7174 
   7175 	nat->nat_nsrcaddr = frnat.fin_saddr;
   7176 	nat->nat_ndstaddr = frnat.fin_daddr;
   7177 	if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   7178 		nat->nat_nsport = htons(frnat.fin_data[0]);
   7179 		nat->nat_ndport = htons(frnat.fin_data[1]);
   7180 	} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   7181 		nat->nat_nicmpid = frnat.fin_data[1];
   7182 	}
   7183 
   7184 	nat->nat_pr[fin->fin_out] = fin->fin_p;
   7185 	nat->nat_pr[1 - fin->fin_out] = p;
   7186 
   7187 	if (np->in_redir & NAT_REDIRECT)
   7188 		nat->nat_dir = NAT_DIVERTIN;
   7189 	else
   7190 		nat->nat_dir = NAT_DIVERTOUT;
   7191 
   7192 	return 0;
   7193 }
   7194 
   7195 
   7196 /* ------------------------------------------------------------------------ */
   7197 /* Function:    nat_builddivertmp                                           */
   7198 /* Returns:     int - -1 == error, 0 == success                             */
   7199 /* Parameters:  softn(I) - pointer to NAT context structure                 */
   7200 /*              np(I)    - pointer to a NAT rule                            */
   7201 /*                                                                          */
   7202 /* For divert rules, a skeleton packet representing what will be prepended  */
   7203 /* to the real packet is created.  Even though we don't have the full       */
   7204 /* packet here, a checksum is calculated that we update later when we       */
   7205 /* fill in the final details.  At present a 0 checksum for UDP is being set */
   7206 /* here because it is expected that divert will be used for localhost.      */
   7207 /* ------------------------------------------------------------------------ */
   7208 static int
   7209 ipf_nat_builddivertmp(ipf_nat_softc_t *softn, ipnat_t *np)
   7210 {
   7211 	udphdr_t *uh;
   7212 	size_t len;
   7213 	ip_t *ip;
   7214 
   7215 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   7216 		len = sizeof(ip_t) + sizeof(udphdr_t);
   7217 	else
   7218 		len = sizeof(ip_t);
   7219 
   7220 	ALLOC_MB_T(np->in_divmp, len);
   7221 	if (np->in_divmp == NULL) {
   7222 		NBUMPD(ipf_nat_stats, ns_divert_build);
   7223 		return -1;
   7224 	}
   7225 
   7226 	/*
   7227 	 * First, the header to get the packet diverted to the new destination
   7228 	 */
   7229 	ip = MTOD(np->in_divmp, ip_t *);
   7230 	IP_V_A(ip, 4);
   7231 	IP_HL_A(ip, 5);
   7232 	ip->ip_tos = 0;
   7233 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   7234 		ip->ip_p = IPPROTO_UDP;
   7235 	else
   7236 		ip->ip_p = IPPROTO_IPIP;
   7237 	ip->ip_ttl = 255;
   7238 	ip->ip_off = 0;
   7239 	ip->ip_sum = 0;
   7240 	ip->ip_len = htons(len);
   7241 	ip->ip_id = 0;
   7242 	ip->ip_src.s_addr = htonl(np->in_snip);
   7243 	ip->ip_dst.s_addr = htonl(np->in_dnip);
   7244 	ip->ip_sum = ipf_cksum((u_short *)ip, sizeof(*ip));
   7245 
   7246 	if (np->in_redir & NAT_DIVERTUDP) {
   7247 		uh = (udphdr_t *)(ip + 1);
   7248 		uh->uh_sum = 0;
   7249 		uh->uh_ulen = 8;
   7250 		uh->uh_sport = htons(np->in_spnext);
   7251 		uh->uh_dport = htons(np->in_dpnext);
   7252 	}
   7253 
   7254 	return 0;
   7255 }
   7256 
   7257 
   7258 #define	MINDECAP	(sizeof(ip_t) + sizeof(udphdr_t) + sizeof(ip_t))
   7259 
   7260 /* ------------------------------------------------------------------------ */
   7261 /* Function:    nat_decap                                                   */
   7262 /* Returns:     int - -1 == error, 0 == success                             */
   7263 /* Parameters:  fin(I) - pointer to packet information                      */
   7264 /*              nat(I) - pointer to current NAT session                     */
   7265 /*                                                                          */
   7266 /* This function is responsible for undoing a packet's encapsulation in the */
   7267 /* reverse of an encap/divert rule.  After removing the outer encapsulation */
   7268 /* it is necessary to call ipf_makefrip() again so that the contents of 'fin'*/
   7269 /* match the "new" packet as it may still be used by IPFilter elsewhere.    */
   7270 /* We use "dir" here as the basis for some of the expectations about the    */
   7271 /* outer header.  If we return an error, the goal is to leave the original  */
   7272 /* packet information undisturbed - this falls short at the end where we'd  */
   7273 /* need to back a backup copy of "fin" - expensive.                         */
   7274 /* ------------------------------------------------------------------------ */
   7275 static int
   7276 ipf_nat_decap(fr_info_t *fin, nat_t *nat)
   7277 {
   7278 	ipf_main_softc_t *softc = fin->fin_main_soft;
   7279 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7280 	char *hdr;
   7281 	int hlen;
   7282 	int skip;
   7283 	mb_t *m;
   7284 
   7285 	if ((fin->fin_flx & FI_ICMPERR) != 0) {
   7286 		/*
   7287 		 * ICMP packets don't get decapsulated, instead what we need
   7288 		 * to do is change the ICMP reply from including (in the data
   7289 		 * portion for errors) the encapsulated packet that we sent
   7290 		 * out to something that resembles the original packet prior
   7291 		 * to encapsulation.  This isn't done here - all we're doing
   7292 		 * here is changing the outer address to ensure that it gets
   7293 		 * targetted back to the correct system.
   7294 		 */
   7295 
   7296 		if (nat->nat_dir & NAT_OUTBOUND) {
   7297 			u_32_t sum1, sum2, sumd;
   7298 
   7299 			sum1 = ntohl(fin->fin_daddr);
   7300 			sum2 = ntohl(nat->nat_osrcaddr);
   7301 			CALC_SUMD(sum1, sum2, sumd);
   7302 			fin->fin_ip->ip_dst = nat->nat_osrcip;
   7303 			fin->fin_daddr = nat->nat_osrcaddr;
   7304 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
   7305      defined(__osf__) || defined(linux)
   7306 			ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, sumd, 0);
   7307 #endif
   7308 		}
   7309 		return 0;
   7310 	}
   7311 
   7312 	m = fin->fin_m;
   7313 	skip = fin->fin_hlen;
   7314 
   7315 	switch (nat->nat_dir)
   7316 	{
   7317 	case NAT_DIVERTIN :
   7318 	case NAT_DIVERTOUT :
   7319 		if (fin->fin_plen < MINDECAP)
   7320 			return -1;
   7321 		skip += sizeof(udphdr_t);
   7322 		break;
   7323 
   7324 	case NAT_ENCAPIN :
   7325 	case NAT_ENCAPOUT :
   7326 		if (fin->fin_plen < (skip + sizeof(ip_t)))
   7327 			return -1;
   7328 		break;
   7329 	default :
   7330 		return -1;
   7331 		/* NOTREACHED */
   7332 	}
   7333 
   7334 	/*
   7335 	 * The aim here is to keep the original packet details in "fin" for
   7336 	 * as long as possible so that returning with an error is for the
   7337 	 * original packet and there is little undoing work to do.
   7338 	 */
   7339 	if (M_LEN(m) < skip + sizeof(ip_t)) {
   7340 		if (ipf_pr_pullup(fin, skip + sizeof(ip_t)) == -1)
   7341 			return -1;
   7342 	}
   7343 
   7344 	hdr = MTOD(fin->fin_m, char *);
   7345 	fin->fin_ip = (ip_t *)(hdr + skip);
   7346 	hlen = IP_HL(fin->fin_ip) << 2;
   7347 
   7348 	if (ipf_pr_pullup(fin, skip + hlen) == -1) {
   7349 		NBUMPSIDED(fin->fin_out, ns_decap_pullup);
   7350 		return -1;
   7351 	}
   7352 
   7353 	fin->fin_hlen = hlen;
   7354 	fin->fin_dlen -= skip;
   7355 	fin->fin_plen -= skip;
   7356 	fin->fin_ipoff += skip;
   7357 
   7358 	if (ipf_makefrip(hlen, (ip_t *)hdr, fin) == -1) {
   7359 		NBUMPSIDED(fin->fin_out, ns_decap_bad);
   7360 		return -1;
   7361 	}
   7362 
   7363 	return skip;
   7364 }
   7365 
   7366 
   7367 /* ------------------------------------------------------------------------ */
   7368 /* Function:    nat_nextaddr                                                */
   7369 /* Returns:     int - -1 == bad input (no new address),                     */
   7370 /*                     0 == success and dst has new address                 */
   7371 /* Parameters:  fin(I) - pointer to packet information                      */
   7372 /*              na(I)  - how to generate new address                        */
   7373 /*              old(I) - original address being replaced                    */
   7374 /*              dst(O) - where to put the new address                       */
   7375 /* Write Lock:  ipf_nat                                                     */
   7376 /*                                                                          */
   7377 /* This function uses the contents of the "na" structure, in combination    */
   7378 /* with "old" to produce a new address to store in "dst".  Not all of the   */
   7379 /* possible uses of "na" will result in a new address.                      */
   7380 /* ------------------------------------------------------------------------ */
   7381 static int
   7382 ipf_nat_nextaddr(fr_info_t *fin, nat_addr_t *na, u_32_t *old, u_32_t *dst)
   7383 {
   7384 	ipf_main_softc_t *softc = fin->fin_main_soft;
   7385 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7386 	u_32_t amin, amax, new;
   7387 	i6addr_t newip;
   7388 	int error;
   7389 
   7390 	new = 0;
   7391 	amin = na->na_addr[0].in4.s_addr;
   7392 
   7393 	switch (na->na_atype)
   7394 	{
   7395 	case FRI_RANGE :
   7396 		amax = na->na_addr[1].in4.s_addr;
   7397 		break;
   7398 
   7399 	case FRI_NETMASKED :
   7400 	case FRI_DYNAMIC :
   7401 	case FRI_NORMAL :
   7402 		/*
   7403 		 * Compute the maximum address by adding the inverse of the
   7404 		 * netmask to the minimum address.
   7405 		 */
   7406 		amax = ~na->na_addr[1].in4.s_addr;
   7407 		amax |= amin;
   7408 		break;
   7409 
   7410 	case FRI_LOOKUP :
   7411 		break;
   7412 
   7413 	case FRI_BROADCAST :
   7414 	case FRI_PEERADDR :
   7415 	case FRI_NETWORK :
   7416 	default :
   7417 		return -1;
   7418 	}
   7419 
   7420 	error = -1;
   7421 
   7422 	if (na->na_atype == FRI_LOOKUP) {
   7423 		if (na->na_type == IPLT_DSTLIST) {
   7424 			error = ipf_dstlist_select_node(fin, na->na_ptr, dst,
   7425 							NULL);
   7426 		} else {
   7427 			NBUMPSIDE(fin->fin_out, ns_badnextaddr);
   7428 		}
   7429 
   7430 	} else if (na->na_atype == IPLT_NONE) {
   7431 		/*
   7432 		 * 0/0 as the new address means leave it alone.
   7433 		 */
   7434 		if (na->na_addr[0].in4.s_addr == 0 &&
   7435 		    na->na_addr[1].in4.s_addr == 0) {
   7436 			new = *old;
   7437 
   7438 		/*
   7439 		 * 0/32 means get the interface's address
   7440 		 */
   7441 		} else if (na->na_addr[0].in4.s_addr == 0 &&
   7442 			   na->na_addr[1].in4.s_addr == 0xffffffff) {
   7443 			if (ipf_ifpaddr(softc, 4, na->na_atype,
   7444 					fin->fin_ifp, &newip, NULL) == -1) {
   7445 				NBUMPSIDED(fin->fin_out, ns_ifpaddrfail);
   7446 				return -1;
   7447 			}
   7448 			new = newip.in4.s_addr;
   7449 		} else {
   7450 			new = htonl(na->na_nextip);
   7451 		}
   7452 		*dst = new;
   7453 		error = 0;
   7454 
   7455 	} else {
   7456 		NBUMPSIDE(fin->fin_out, ns_badnextaddr);
   7457 	}
   7458 
   7459 	return error;
   7460 }
   7461 
   7462 
   7463 /* ------------------------------------------------------------------------ */
   7464 /* Function:    nat_nextaddrinit                                            */
   7465 /* Returns:     int - 0 == success, else error number                       */
   7466 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7467 /*              na(I)      - NAT address information for generating new addr*/
   7468 /*              initial(I) - flag indicating if it is the first call for    */
   7469 /*                           this "na" structure.                           */
   7470 /*              ifp(I)     - network interface to derive address            */
   7471 /*                           information from.                              */
   7472 /*                                                                          */
   7473 /* This function is expected to be called in two scenarious: when a new NAT */
   7474 /* rule is loaded into the kernel and when the list of NAT rules is sync'd  */
   7475 /* up with the valid network interfaces (possibly due to them changing.)    */
   7476 /* To distinguish between these, the "initial" parameter is used.  If it is */
   7477 /* 1 then this indicates the rule has just been reloaded and 0 for when we  */
   7478 /* are updating information.  This difference is important because in       */
   7479 /* instances where we are not updating address information associated with  */
   7480 /* a network interface, we don't want to disturb what the "next" address to */
   7481 /* come out of ipf_nat_nextaddr() will be.                                  */
   7482 /* ------------------------------------------------------------------------ */
   7483 static int
   7484 ipf_nat_nextaddrinit(ipf_main_softc_t *softc, char *base, nat_addr_t *na,
   7485     int initial, void *ifp)
   7486 {
   7487 
   7488 	switch (na->na_atype)
   7489 	{
   7490 	case FRI_LOOKUP :
   7491 		if (na->na_subtype == 0) {
   7492 			na->na_ptr = ipf_lookup_res_num(softc, IPL_LOGNAT,
   7493 							na->na_type,
   7494 							na->na_num,
   7495 							&na->na_func);
   7496 		} else if (na->na_subtype == 1) {
   7497 			na->na_ptr = ipf_lookup_res_name(softc, IPL_LOGNAT,
   7498 							 na->na_type,
   7499 							 base + na->na_num,
   7500 							 &na->na_func);
   7501 		}
   7502 		if (na->na_func == NULL) {
   7503 			IPFERROR(60060);
   7504 			return ESRCH;
   7505 		}
   7506 		if (na->na_ptr == NULL) {
   7507 			IPFERROR(60056);
   7508 			return ESRCH;
   7509 		}
   7510 		break;
   7511 
   7512 	case FRI_DYNAMIC :
   7513 	case FRI_BROADCAST :
   7514 	case FRI_NETWORK :
   7515 	case FRI_NETMASKED :
   7516 	case FRI_PEERADDR :
   7517 		if (ifp != NULL)
   7518 			(void )ipf_ifpaddr(softc, 4, na->na_atype, ifp,
   7519 					   &na->na_addr[0], &na->na_addr[1]);
   7520 		break;
   7521 
   7522 	case FRI_SPLIT :
   7523 	case FRI_RANGE :
   7524 		if (initial)
   7525 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
   7526 		break;
   7527 
   7528 	case FRI_NONE :
   7529 		na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
   7530 		return 0;
   7531 
   7532 	case FRI_NORMAL :
   7533 		na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
   7534 		break;
   7535 
   7536 	default :
   7537 		IPFERROR(60054);
   7538 		return EINVAL;
   7539 	}
   7540 
   7541 	if (initial && (na->na_atype == FRI_NORMAL)) {
   7542 		if (na->na_addr[0].in4.s_addr == 0) {
   7543 			if ((na->na_addr[1].in4.s_addr == 0xffffffff) ||
   7544 			    (na->na_addr[1].in4.s_addr == 0)) {
   7545 				return 0;
   7546 			}
   7547 		}
   7548 
   7549 		if (na->na_addr[1].in4.s_addr == 0xffffffff) {
   7550 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
   7551 		} else {
   7552 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr) + 1;
   7553 		}
   7554 	}
   7555 
   7556 	return 0;
   7557 }
   7558 
   7559 
   7560 /* ------------------------------------------------------------------------ */
   7561 /* Function:    ipf_nat_matchflush                                          */
   7562 /* Returns:     int - -1 == error, 0 == success                             */
   7563 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7564 /*              softn(I) - pointer to NAT context structure                 */
   7565 /*              nat(I)   - pointer to current NAT session                   */
   7566 /*                                                                          */
   7567 /* ------------------------------------------------------------------------ */
   7568 static int
   7569 ipf_nat_matchflush(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, void *data)
   7570 {
   7571 	int *array, flushed, error;
   7572 	nat_t *nat, *natnext;
   7573 	ipfobj_t obj;
   7574 
   7575 	error = ipf_matcharray_load(softc, data, &obj, &array);
   7576 	if (error != 0)
   7577 		return error;
   7578 
   7579 	flushed = 0;
   7580 
   7581 	for (nat = softn->ipf_nat_instances; nat != NULL; nat = natnext) {
   7582 		natnext = nat->nat_next;
   7583 		if (ipf_nat_matcharray(nat, array, softc->ipf_ticks) == 0) {
   7584 			ipf_nat_delete(softc, nat, NL_FLUSH);
   7585 			flushed++;
   7586 		}
   7587 	}
   7588 
   7589 	obj.ipfo_retval = flushed;
   7590 	error = BCOPYOUT(&obj, data, sizeof(obj));
   7591 
   7592 	KFREES(array, array[0] * sizeof(*array));
   7593 
   7594 	return error;
   7595 }
   7596 
   7597 
   7598 /* ------------------------------------------------------------------------ */
   7599 /* Function:    ipf_nat_matcharray                                          */
   7600 /* Returns:     int - -1 == error, 0 == success                             */
   7601 /* Parameters:  fin(I) - pointer to packet information                      */
   7602 /*              nat(I) - pointer to current NAT session                     */
   7603 /*                                                                          */
   7604 /* ------------------------------------------------------------------------ */
   7605 static int
   7606 ipf_nat_matcharray(nat_t *nat, int *array, u_long ticks)
   7607 {
   7608 	int i, n, *x, e, p;
   7609 
   7610 	e = 0;
   7611 	n = array[0];
   7612 	x = array + 1;
   7613 
   7614 	for (; n > 0; x += 3 + x[2]) {
   7615 		if (x[0] == IPF_EXP_END)
   7616 			break;
   7617 		e = 0;
   7618 
   7619 		n -= x[2] + 3;
   7620 		if (n < 0)
   7621 			break;
   7622 
   7623 		p = x[0] >> 16;
   7624 		if (p != 0 && p != nat->nat_pr[1])
   7625 			break;
   7626 
   7627 		switch (x[0])
   7628 		{
   7629 		case IPF_EXP_IP_PR :
   7630 			for (i = 0; !e && i < x[2]; i++) {
   7631 				e |= (nat->nat_pr[1] == x[i + 3]);
   7632 			}
   7633 			break;
   7634 
   7635 		case IPF_EXP_IP_SRCADDR :
   7636 			if (nat->nat_v[0] == 4) {
   7637 				for (i = 0; !e && i < x[2]; i++) {
   7638 					e |= ((nat->nat_osrcaddr & x[i + 4]) ==
   7639 					      x[i + 3]);
   7640 				}
   7641 			}
   7642 			if (nat->nat_v[1] == 4) {
   7643 				for (i = 0; !e && i < x[2]; i++) {
   7644 					e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
   7645 					      x[i + 3]);
   7646 				}
   7647 			}
   7648 			break;
   7649 
   7650 		case IPF_EXP_IP_DSTADDR :
   7651 			if (nat->nat_v[0] == 4) {
   7652 				for (i = 0; !e && i < x[2]; i++) {
   7653 					e |= ((nat->nat_odstaddr & x[i + 4]) ==
   7654 					      x[i + 3]);
   7655 				}
   7656 			}
   7657 			if (nat->nat_v[1] == 4) {
   7658 				for (i = 0; !e && i < x[2]; i++) {
   7659 					e |= ((nat->nat_ndstaddr & x[i + 4]) ==
   7660 					      x[i + 3]);
   7661 				}
   7662 			}
   7663 			break;
   7664 
   7665 		case IPF_EXP_IP_ADDR :
   7666 			for (i = 0; !e && i < x[2]; i++) {
   7667 				if (nat->nat_v[0] == 4) {
   7668 					e |= ((nat->nat_osrcaddr & x[i + 4]) ==
   7669 					      x[i + 3]);
   7670 				}
   7671 				if (nat->nat_v[1] == 4) {
   7672 					e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
   7673 					      x[i + 3]);
   7674 				}
   7675 				if (nat->nat_v[0] == 4) {
   7676 					e |= ((nat->nat_odstaddr & x[i + 4]) ==
   7677 					      x[i + 3]);
   7678 				}
   7679 				if (nat->nat_v[1] == 4) {
   7680 					e |= ((nat->nat_ndstaddr & x[i + 4]) ==
   7681 					      x[i + 3]);
   7682 				}
   7683 			}
   7684 			break;
   7685 
   7686 #ifdef USE_INET6
   7687 		case IPF_EXP_IP6_SRCADDR :
   7688 			if (nat->nat_v[0] == 6) {
   7689 				for (i = 0; !e && i < x[3]; i++) {
   7690 					e |= IP6_MASKEQ(&nat->nat_osrc6,
   7691 							x + i + 7, x + i + 3);
   7692 				}
   7693 			}
   7694 			if (nat->nat_v[1] == 6) {
   7695 				for (i = 0; !e && i < x[3]; i++) {
   7696 					e |= IP6_MASKEQ(&nat->nat_nsrc6,
   7697 							x + i + 7, x + i + 3);
   7698 				}
   7699 			}
   7700 			break;
   7701 
   7702 		case IPF_EXP_IP6_DSTADDR :
   7703 			if (nat->nat_v[0] == 6) {
   7704 				for (i = 0; !e && i < x[3]; i++) {
   7705 					e |= IP6_MASKEQ(&nat->nat_odst6,
   7706 							x + i + 7,
   7707 							x + i + 3);
   7708 				}
   7709 			}
   7710 			if (nat->nat_v[1] == 6) {
   7711 				for (i = 0; !e && i < x[3]; i++) {
   7712 					e |= IP6_MASKEQ(&nat->nat_ndst6,
   7713 							x + i + 7,
   7714 							x + i + 3);
   7715 				}
   7716 			}
   7717 			break;
   7718 
   7719 		case IPF_EXP_IP6_ADDR :
   7720 			for (i = 0; !e && i < x[3]; i++) {
   7721 				if (nat->nat_v[0] == 6) {
   7722 					e |= IP6_MASKEQ(&nat->nat_osrc6,
   7723 							x + i + 7,
   7724 							x + i + 3);
   7725 				}
   7726 				if (nat->nat_v[0] == 6) {
   7727 					e |= IP6_MASKEQ(&nat->nat_odst6,
   7728 							x + i + 7,
   7729 							x + i + 3);
   7730 				}
   7731 				if (nat->nat_v[1] == 6) {
   7732 					e |= IP6_MASKEQ(&nat->nat_nsrc6,
   7733 							x + i + 7,
   7734 							x + i + 3);
   7735 				}
   7736 				if (nat->nat_v[1] == 6) {
   7737 					e |= IP6_MASKEQ(&nat->nat_ndst6,
   7738 							x + i + 7,
   7739 							x + i + 3);
   7740 				}
   7741 			}
   7742 			break;
   7743 #endif
   7744 
   7745 		case IPF_EXP_UDP_PORT :
   7746 		case IPF_EXP_TCP_PORT :
   7747 			for (i = 0; !e && i < x[2]; i++) {
   7748 				e |= (nat->nat_nsport == x[i + 3]) ||
   7749 				     (nat->nat_ndport == x[i + 3]);
   7750 			}
   7751 			break;
   7752 
   7753 		case IPF_EXP_UDP_SPORT :
   7754 		case IPF_EXP_TCP_SPORT :
   7755 			for (i = 0; !e && i < x[2]; i++) {
   7756 				e |= (nat->nat_nsport == x[i + 3]);
   7757 			}
   7758 			break;
   7759 
   7760 		case IPF_EXP_UDP_DPORT :
   7761 		case IPF_EXP_TCP_DPORT :
   7762 			for (i = 0; !e && i < x[2]; i++) {
   7763 				e |= (nat->nat_ndport == x[i + 3]);
   7764 			}
   7765 			break;
   7766 
   7767 		case IPF_EXP_TCP_STATE :
   7768 			for (i = 0; !e && i < x[2]; i++) {
   7769 				e |= (nat->nat_tcpstate[0] == x[i + 3]) ||
   7770 				     (nat->nat_tcpstate[1] == x[i + 3]);
   7771 			}
   7772 			break;
   7773 
   7774 		case IPF_EXP_IDLE_GT :
   7775 			e |= (ticks - nat->nat_touched > x[3]);
   7776 			break;
   7777 		}
   7778 		e ^= x[1];
   7779 
   7780 		if (!e)
   7781 			break;
   7782 	}
   7783 
   7784 	return e;
   7785 }
   7786 
   7787 
   7788 /* ------------------------------------------------------------------------ */
   7789 /* Function:    ipf_nat_gettable                                            */
   7790 /* Returns:     int     - 0 = success, else error                           */
   7791 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7792 /*              softn(I) - pointer to NAT context structure                 */
   7793 /*              data(I)  - pointer to ioctl data                            */
   7794 /*                                                                          */
   7795 /* This function handles ioctl requests for tables of nat information.      */
   7796 /* At present the only table it deals with is the hash bucket statistics.   */
   7797 /* ------------------------------------------------------------------------ */
   7798 static int
   7799 ipf_nat_gettable(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, char *data)
   7800 {
   7801 	ipftable_t table;
   7802 	int error;
   7803 
   7804 	error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
   7805 	if (error != 0)
   7806 		return error;
   7807 
   7808 	switch (table.ita_type)
   7809 	{
   7810 	case IPFTABLE_BUCKETS_NATIN :
   7811 		error = COPYOUT(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
   7812 				table.ita_table,
   7813 				softn->ipf_nat_table_sz * sizeof(u_int));
   7814 		break;
   7815 
   7816 	case IPFTABLE_BUCKETS_NATOUT :
   7817 		error = COPYOUT(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
   7818 				table.ita_table,
   7819 				softn->ipf_nat_table_sz * sizeof(u_int));
   7820 		break;
   7821 
   7822 	default :
   7823 		IPFERROR(60058);
   7824 		return EINVAL;
   7825 	}
   7826 
   7827 	if (error != 0) {
   7828 		IPFERROR(60059);
   7829 		error = EFAULT;
   7830 	}
   7831 	return error;
   7832 }
   7833 
   7834 
   7835 /* ------------------------------------------------------------------------ */
   7836 /* Function:    ipf_nat_settimeout                                          */
   7837 /* Returns:     int  - 0 = success, else failure			    */
   7838 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7839 /*              t(I) - pointer to tunable                                   */
   7840 /*              p(I) - pointer to new tuning data                           */
   7841 /*                                                                          */
   7842 /* Apply the timeout change to the NAT timeout queues.                      */
   7843 /* ------------------------------------------------------------------------ */
   7844 int
   7845 ipf_nat_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
   7846     ipftuneval_t *p)
   7847 {
   7848 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7849 
   7850 	if (!strncmp(t->ipft_name, "tcp_", 4))
   7851 		return ipf_settimeout_tcp(t, p, softn->ipf_nat_tcptq);
   7852 
   7853 	if (!strcmp(t->ipft_name, "udp_timeout")) {
   7854 		ipf_apply_timeout(&softn->ipf_nat_udptq, p->ipftu_int);
   7855 	} else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
   7856 		ipf_apply_timeout(&softn->ipf_nat_udpacktq, p->ipftu_int);
   7857 	} else if (!strcmp(t->ipft_name, "icmp_timeout")) {
   7858 		ipf_apply_timeout(&softn->ipf_nat_icmptq, p->ipftu_int);
   7859 	} else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
   7860 		ipf_apply_timeout(&softn->ipf_nat_icmpacktq, p->ipftu_int);
   7861 	} else if (!strcmp(t->ipft_name, "ip_timeout")) {
   7862 		ipf_apply_timeout(&softn->ipf_nat_iptq, p->ipftu_int);
   7863 	} else {
   7864 		IPFERROR(60062);
   7865 		return ESRCH;
   7866 	}
   7867 	return 0;
   7868 }
   7869 
   7870 
   7871 /* ------------------------------------------------------------------------ */
   7872 /* Function:    ipf_nat_rehash                                              */
   7873 /* Returns:     int  - 0 = success, else failure			    */
   7874 /* Parameters:  softc(I) - pointer to soft context main structure           */
   7875 /*              t(I) - pointer to tunable                                   */
   7876 /*              p(I) - pointer to new tuning data                           */
   7877 /*                                                                          */
   7878 /* To change the size of the basic NAT table, we need to first allocate the */
   7879 /* new tables (lest it fails and we've got nowhere to store all of the NAT  */
   7880 /* sessions currently active) and then walk through the entire list and     */
   7881 /* insert them into the table.  There are two tables here: an inbound one   */
   7882 /* and an outbound one.  Each NAT entry goes into each table once.          */
   7883 /* ------------------------------------------------------------------------ */
   7884 int
   7885 ipf_nat_rehash(ipf_main_softc_t *softc, ipftuneable_t *t, ipftuneval_t *p)
   7886 {
   7887 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   7888 	nat_t **newtab[2], *nat, **natp;
   7889 	u_int *bucketlens[2];
   7890 	u_int maxbucket;
   7891 	u_int newsize;
   7892 	int error;
   7893 	u_int hv;
   7894 	int i;
   7895 
   7896 	newsize = p->ipftu_int;
   7897 	/*
   7898 	 * In case there is nothing to do...
   7899 	 */
   7900 	if (newsize == softn->ipf_nat_table_sz)
   7901 		return 0;
   7902 
   7903 	newtab[0] = NULL;
   7904 	newtab[1] = NULL;
   7905 	bucketlens[0] = NULL;
   7906 	bucketlens[1] = NULL;
   7907 	/*
   7908 	 * 4 tables depend on the NAT table size: the inbound looking table,
   7909 	 * the outbound lookup table and the hash chain length for each.
   7910 	 */
   7911 	KMALLOCS(newtab[0], nat_t **, newsize * sizeof(nat_t *));
   7912 	if (newtab == NULL) {
   7913 		error = 60063;
   7914 		goto badrehash;
   7915 	}
   7916 
   7917 	KMALLOCS(newtab[1], nat_t **, newsize * sizeof(nat_t *));
   7918 	if (newtab == NULL) {
   7919 		error = 60064;
   7920 		goto badrehash;
   7921 	}
   7922 
   7923 	KMALLOCS(bucketlens[0], u_int *, newsize * sizeof(u_int));
   7924 	if (bucketlens[0] == NULL) {
   7925 		error = 60065;
   7926 		goto badrehash;
   7927 	}
   7928 
   7929 	KMALLOCS(bucketlens[1], u_int *, newsize * sizeof(u_int));
   7930 	if (bucketlens[1] == NULL) {
   7931 		error = 60066;
   7932 		goto badrehash;
   7933 	}
   7934 
   7935 	/*
   7936 	 * Recalculate the maximum length based on the new size.
   7937 	 */
   7938 	for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
   7939 		maxbucket++;
   7940 	maxbucket *= 2;
   7941 
   7942 	bzero((char *)newtab[0], newsize * sizeof(nat_t *));
   7943 	bzero((char *)newtab[1], newsize * sizeof(nat_t *));
   7944 	bzero((char *)bucketlens[0], newsize * sizeof(u_int));
   7945 	bzero((char *)bucketlens[1], newsize * sizeof(u_int));
   7946 
   7947 	WRITE_ENTER(&softc->ipf_nat);
   7948 
   7949 	if (softn->ipf_nat_table[0] != NULL) {
   7950 		KFREES(softn->ipf_nat_table[0],
   7951 		       softn->ipf_nat_table_sz *
   7952 		       sizeof(*softn->ipf_nat_table[0]));
   7953 	}
   7954 	softn->ipf_nat_table[0] = newtab[0];
   7955 
   7956 	if (softn->ipf_nat_table[1] != NULL) {
   7957 		KFREES(softn->ipf_nat_table[1],
   7958 		       softn->ipf_nat_table_sz *
   7959 		       sizeof(*softn->ipf_nat_table[1]));
   7960 	}
   7961 	softn->ipf_nat_table[1] = newtab[1];
   7962 
   7963 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen != NULL) {
   7964 		KFREES(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
   7965 		       softn->ipf_nat_table_sz * sizeof(u_int));
   7966 	}
   7967 	softn->ipf_nat_stats.ns_side[0].ns_bucketlen = bucketlens[0];
   7968 
   7969 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen != NULL) {
   7970 		KFREES(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
   7971 		       softn->ipf_nat_table_sz * sizeof(u_int));
   7972 	}
   7973 	softn->ipf_nat_stats.ns_side[1].ns_bucketlen = bucketlens[1];
   7974 
   7975 	if (softn->ipf_nat_stats.ns_side6[0].ns_bucketlen != NULL) {
   7976 		KFREES(softn->ipf_nat_stats.ns_side6[0].ns_bucketlen,
   7977 		       softn->ipf_nat_table_sz * sizeof(u_int));
   7978 	}
   7979 	softn->ipf_nat_stats.ns_side6[0].ns_bucketlen = bucketlens[0];
   7980 
   7981 	if (softn->ipf_nat_stats.ns_side6[1].ns_bucketlen != NULL) {
   7982 		KFREES(softn->ipf_nat_stats.ns_side6[1].ns_bucketlen,
   7983 		       softn->ipf_nat_table_sz * sizeof(u_int));
   7984 	}
   7985 	softn->ipf_nat_stats.ns_side6[1].ns_bucketlen = bucketlens[1];
   7986 
   7987 	softn->ipf_nat_maxbucket = maxbucket;
   7988 	softn->ipf_nat_table_sz = newsize;
   7989 	/*
   7990 	 * Walk through the entire list of NAT table entries and put them
   7991 	 * in the new NAT table, somewhere.  Because we have a new table,
   7992 	 * we need to restart the counter of how many chains are in use.
   7993 	 */
   7994 	softn->ipf_nat_stats.ns_side[0].ns_inuse = 0;
   7995 	softn->ipf_nat_stats.ns_side[1].ns_inuse = 0;
   7996 	softn->ipf_nat_stats.ns_side6[0].ns_inuse = 0;
   7997 	softn->ipf_nat_stats.ns_side6[1].ns_inuse = 0;
   7998 
   7999 	for (nat = softn->ipf_nat_instances; nat != NULL; nat = nat->nat_next) {
   8000 		nat->nat_hnext[0] = NULL;
   8001 		nat->nat_phnext[0] = NULL;
   8002 		hv = nat->nat_hv[0] % softn->ipf_nat_table_sz;
   8003 
   8004 		natp = &softn->ipf_nat_table[0][hv];
   8005 		if (*natp) {
   8006 			(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   8007 		} else {
   8008 			NBUMPSIDE(0, ns_inuse);
   8009 		}
   8010 		nat->nat_phnext[0] = natp;
   8011 		nat->nat_hnext[0] = *natp;
   8012 		*natp = nat;
   8013 		NBUMPSIDE(0, ns_bucketlen[hv]);
   8014 
   8015 		nat->nat_hnext[1] = NULL;
   8016 		nat->nat_phnext[1] = NULL;
   8017 		hv = nat->nat_hv[1] % softn->ipf_nat_table_sz;
   8018 
   8019 		natp = &softn->ipf_nat_table[1][hv];
   8020 		if (*natp) {
   8021 			(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   8022 		} else {
   8023 			NBUMPSIDE(1, ns_inuse);
   8024 		}
   8025 		nat->nat_phnext[1] = natp;
   8026 		nat->nat_hnext[1] = *natp;
   8027 		*natp = nat;
   8028 		NBUMPSIDE(1, ns_bucketlen[hv]);
   8029 	}
   8030 	RWLOCK_EXIT(&softc->ipf_nat);
   8031 
   8032 	return 0;
   8033 
   8034 badrehash:
   8035 	if (bucketlens[1] != NULL) {
   8036 		KFREES(bucketlens[0], newsize * sizeof(u_int));
   8037 	}
   8038 	if (bucketlens[0] != NULL) {
   8039 		KFREES(bucketlens[0], newsize * sizeof(u_int));
   8040 	}
   8041 	if (newtab[0] != NULL) {
   8042 		KFREES(newtab[0], newsize * sizeof(nat_t *));
   8043 	}
   8044 	if (newtab[1] != NULL) {
   8045 		KFREES(newtab[1], newsize * sizeof(nat_t *));
   8046 	}
   8047 	IPFERROR(error);
   8048 	return ENOMEM;
   8049 }
   8050 
   8051 
   8052 /* ------------------------------------------------------------------------ */
   8053 /* Function:    ipf_nat_rehash_rules                                        */
   8054 /* Returns:     int  - 0 = success, else failure			    */
   8055 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8056 /*              t(I) - pointer to tunable                                   */
   8057 /*              p(I) - pointer to new tuning data                           */
   8058 /*                                                                          */
   8059 /* All of the NAT rules hang off of a hash table that is searched with a    */
   8060 /* hash on address after the netmask is applied.  There is a different table*/
   8061 /* for both inbound rules (rdr) and outbound (map.)  The resizing will only */
   8062 /* affect one of these two tables.                                          */
   8063 /* ------------------------------------------------------------------------ */
   8064 int
   8065 ipf_nat_rehash_rules(ipf_main_softc_t *softc, ipftuneable_t *t, ipftuneval_t *p)
   8066 {
   8067 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8068 	ipnat_t **newtab, *np, ***old, **npp;
   8069 	u_int newsize;
   8070 	u_int mask;
   8071 	u_int hv;
   8072 
   8073 	newsize = p->ipftu_int;
   8074 	/*
   8075 	 * In case there is nothing to do...
   8076 	 */
   8077 	if (newsize == *t->ipft_pint)
   8078 		return 0;
   8079 
   8080 	/*
   8081 	 * All inbound rules have the NAT_REDIRECT bit set in in_redir and
   8082 	 * all outbound rules have either NAT_MAP or MAT_MAPBLK set.
   8083 	 * This if statement allows for some more generic code to be below,
   8084 	 * rather than two huge gobs of code that almost do the same thing.
   8085 	 */
   8086 	if (t->ipft_pint == &softn->ipf_nat_rdrrules_sz) {
   8087 		old = &softn->ipf_nat_rdr_rules;
   8088 		mask = NAT_REDIRECT;
   8089 	} else {
   8090 		old = &softn->ipf_nat_map_rules;
   8091 		mask = NAT_MAP|NAT_MAPBLK;
   8092 	}
   8093 
   8094 	KMALLOCS(newtab, ipnat_t **, newsize * sizeof(ipnat_t *));
   8095 	if (newtab == NULL) {
   8096 		IPFERROR(60067);
   8097 		return ENOMEM;
   8098 	}
   8099 
   8100 	bzero((char *)newtab, newsize * sizeof(ipnat_t *));
   8101 
   8102 	WRITE_ENTER(&softc->ipf_nat);
   8103 
   8104 	if (*old != NULL) {
   8105 		KFREES(*old, *t->ipft_pint * sizeof(ipnat_t **));
   8106 	}
   8107 	*old = newtab;
   8108 	*t->ipft_pint = newsize;
   8109 
   8110 	for (np = softn->ipf_nat_list; np != NULL; np = np->in_next) {
   8111 		if ((np->in_redir & mask) == 0)
   8112 			continue;
   8113 
   8114 		if (np->in_redir & NAT_REDIRECT) {
   8115 			np->in_rnext = NULL;
   8116 			hv = np->in_hv[0] % newsize;
   8117 			for (npp = newtab + hv; *npp != NULL; )
   8118 				npp = &(*npp)->in_rnext;
   8119 			np->in_prnext = npp;
   8120 			*npp = np;
   8121 		}
   8122 		if (np->in_redir & NAT_MAP) {
   8123 			np->in_mnext = NULL;
   8124 			hv = np->in_hv[1] % newsize;
   8125 			for (npp = newtab + hv; *npp != NULL; )
   8126 				npp = &(*npp)->in_mnext;
   8127 			np->in_pmnext = npp;
   8128 			*npp = np;
   8129 		}
   8130 
   8131 	}
   8132 	RWLOCK_EXIT(&softc->ipf_nat);
   8133 
   8134 	return 0;
   8135 }
   8136 
   8137 
   8138 /* ------------------------------------------------------------------------ */
   8139 /* Function:    ipf_nat_hostmap_rehash                                      */
   8140 /* Returns:     int  - 0 = success, else failure			    */
   8141 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8142 /*              t(I) - pointer to tunable                                   */
   8143 /*              p(I) - pointer to new tuning data                           */
   8144 /*                                                                          */
   8145 /* Allocate and populate a new hash table that will contain a reference to  */
   8146 /* all of the active IP# translations currently in place.                   */
   8147 /* ------------------------------------------------------------------------ */
   8148 int
   8149 ipf_nat_hostmap_rehash(ipf_main_softc_t *softc, ipftuneable_t *t,
   8150     ipftuneval_t *p)
   8151 {
   8152 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8153 	hostmap_t *hm, **newtab;
   8154 	u_int newsize;
   8155 	u_int hv;
   8156 
   8157 	newsize = p->ipftu_int;
   8158 	/*
   8159 	 * In case there is nothing to do...
   8160 	 */
   8161 	if (newsize == *t->ipft_pint)
   8162 		return 0;
   8163 
   8164 	KMALLOCS(newtab, hostmap_t **, newsize * sizeof(hostmap_t *));
   8165 	if (newtab == NULL) {
   8166 		IPFERROR(60068);
   8167 		return ENOMEM;
   8168 	}
   8169 
   8170 	bzero((char *)newtab, newsize * sizeof(hostmap_t *));
   8171 
   8172 	WRITE_ENTER(&softc->ipf_nat);
   8173 	if (softn->ipf_hm_maptable != NULL) {
   8174 		KFREES(softn->ipf_hm_maptable,
   8175 		       softn->ipf_nat_hostmap_sz * sizeof(hostmap_t *));
   8176 	}
   8177 	softn->ipf_hm_maptable = newtab;
   8178 	softn->ipf_nat_hostmap_sz = newsize;
   8179 
   8180 	for (hm = softn->ipf_hm_maplist; hm != NULL; hm = hm->hm_next) {
   8181 		hv = hm->hm_hv % softn->ipf_nat_hostmap_sz;
   8182 		hm->hm_hnext = softn->ipf_hm_maptable[hv];
   8183 		hm->hm_phnext = softn->ipf_hm_maptable + hv;
   8184 		if (softn->ipf_hm_maptable[hv] != NULL)
   8185 			softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
   8186 		softn->ipf_hm_maptable[hv] = hm;
   8187 	}
   8188 	RWLOCK_EXIT(&softc->ipf_nat);
   8189 
   8190 	return 0;
   8191 }
   8192 
   8193 
   8194 /* ------------------------------------------------------------------------ */
   8195 /* Function:    ipf_nat_add_tq                                              */
   8196 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8197 /*                                                                          */
   8198 /* ------------------------------------------------------------------------ */
   8199 ipftq_t *
   8200 ipf_nat_add_tq(ipf_main_softc_t *softc, int ttl)
   8201 {
   8202 	ipf_nat_softc_t *softs = softc->ipf_nat_soft;
   8203 
   8204 	return ipf_addtimeoutqueue(softc, &softs->ipf_nat_utqe, ttl);
   8205 }
   8206 
   8207 /* ------------------------------------------------------------------------ */
   8208 /* Function:    ipf_nat_uncreate                                            */
   8209 /* Returns:     Nil                                                         */
   8210 /* Parameters:  fin(I) - pointer to packet information                      */
   8211 /*                                                                          */
   8212 /* This function is used to remove a NAT entry from the NAT table when we   */
   8213 /* decide that the create was actually in error. It is thus assumed that    */
   8214 /* fin_flx will have both FI_NATED and FI_NATNEW set. Because we're dealing */
   8215 /* with the translated packet (not the original), we have to reverse the    */
   8216 /* lookup. Although doing the lookup is expensive (relatively speaking), it */
   8217 /* is not anticipated that this will be a frequent occurance for normal     */
   8218 /* traffic patterns.                                                        */
   8219 /* ------------------------------------------------------------------------ */
   8220 void
   8221 ipf_nat_uncreate(fr_info_t *fin)
   8222 {
   8223 	ipf_main_softc_t *softc = fin->fin_main_soft;
   8224 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   8225 	int nflags;
   8226 	nat_t *nat;
   8227 
   8228 	switch (fin->fin_p)
   8229 	{
   8230 	case IPPROTO_TCP :
   8231 		nflags = IPN_TCP;
   8232 		break;
   8233 	case IPPROTO_UDP :
   8234 		nflags = IPN_UDP;
   8235 		break;
   8236 	default :
   8237 		nflags = 0;
   8238 		break;
   8239 	}
   8240 
   8241 	WRITE_ENTER(&softc->ipf_nat);
   8242 
   8243 	if (fin->fin_out == 0) {
   8244 		nat = ipf_nat_outlookup(fin, nflags, (u_int)fin->fin_p,
   8245 					fin->fin_dst, fin->fin_src);
   8246 	} else {
   8247 		nat = ipf_nat_inlookup(fin, nflags, (u_int)fin->fin_p,
   8248 				       fin->fin_src, fin->fin_dst);
   8249 	}
   8250 
   8251 	if (nat != NULL) {
   8252 		NBUMPSIDE(fin->fin_out, ns_uncreate[0]);
   8253 		ipf_nat_delete(softc, nat, NL_DESTROY);
   8254 	} else {
   8255 		NBUMPSIDE(fin->fin_out, ns_uncreate[1]);
   8256 	}
   8257 
   8258 	RWLOCK_EXIT(&softc->ipf_nat);
   8259 }
   8260 
   8261 
   8262 /* ------------------------------------------------------------------------ */
   8263 /* Function:    ipf_nat_cmp_rules                                           */
   8264 /* Returns:     int   - 0 == success, else rules do not match.              */
   8265 /* Parameters:  n1(I) - first rule to compare                               */
   8266 /*              n2(I) - first rule to compare                               */
   8267 /*                                                                          */
   8268 /* Compare two rules using pointers to each rule. A straight bcmp will not  */
   8269 /* work as some fields (such as in_dst, in_pkts) actually do change once    */
   8270 /* the rule has been loaded into the kernel. Whilst this function returns   */
   8271 /* various non-zero returns, they're strictly to aid in debugging. Use of   */
   8272 /* this function should simply care if the result is zero or not.           */
   8273 /* ------------------------------------------------------------------------ */
   8274 static int
   8275 ipf_nat_cmp_rules(n1, n2)
   8276 	ipnat_t *n1, *n2;
   8277 {
   8278 	if (n1->in_size != n2->in_size)
   8279 		return 1;
   8280 
   8281 	if (bcmp((char *)&n1->in_v, (char *)&n2->in_v,
   8282 		 offsetof(ipnat_t, in_ndst) - offsetof(ipnat_t, in_v)) != 0)
   8283 		return 2;
   8284 
   8285 	if (bcmp((char *)&n1->in_tuc, (char *)&n2->in_tuc,
   8286 		 n1->in_size - offsetof(ipnat_t, in_tuc)) != 0)
   8287 		return 3;
   8288 	if (n1->in_ndst.na_atype != n2->in_ndst.na_atype)
   8289 		return 5;
   8290 	if (n1->in_ndst.na_function != n2->in_ndst.na_function)
   8291 		return 6;
   8292 	if (bcmp((char *)&n1->in_ndst.na_addr, (char *)&n2->in_ndst.na_addr,
   8293 		 sizeof(n1->in_ndst.na_addr)))
   8294 		return 7;
   8295 	if (n1->in_nsrc.na_atype != n2->in_nsrc.na_atype)
   8296 		return 8;
   8297 	if (n1->in_nsrc.na_function != n2->in_nsrc.na_function)
   8298 		return 9;
   8299 	if (bcmp((char *)&n1->in_nsrc.na_addr, (char *)&n2->in_nsrc.na_addr,
   8300 		 sizeof(n1->in_nsrc.na_addr)))
   8301 		return 10;
   8302 	if (n1->in_odst.na_atype != n2->in_odst.na_atype)
   8303 		return 11;
   8304 	if (n1->in_odst.na_function != n2->in_odst.na_function)
   8305 		return 12;
   8306 	if (bcmp((char *)&n1->in_odst.na_addr, (char *)&n2->in_odst.na_addr,
   8307 		 sizeof(n1->in_odst.na_addr)))
   8308 		return 13;
   8309 	if (n1->in_osrc.na_atype != n2->in_osrc.na_atype)
   8310 		return 14;
   8311 	if (n1->in_osrc.na_function != n2->in_osrc.na_function)
   8312 		return 15;
   8313 	if (bcmp((char *)&n1->in_osrc.na_addr, (char *)&n2->in_osrc.na_addr,
   8314 		 sizeof(n1->in_osrc.na_addr)))
   8315 		return 16;
   8316 	return 0;
   8317 }
   8318 
   8319 
   8320 /* ------------------------------------------------------------------------ */
   8321 /* Function:    ipf_nat_rule_init                                           */
   8322 /* Returns:     int   - 0 == success, else rules do not match.              */
   8323 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8324 /*              softn(I) - pointer to NAT context structure                 */
   8325 /*              n(I)     - first rule to compare                            */
   8326 /*                                                                          */
   8327 /* ------------------------------------------------------------------------ */
   8328 static int
   8329 ipf_nat_rule_init(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, ipnat_t *n)
   8330 {
   8331 	int error = 0;
   8332 
   8333 	if ((n->in_flags & IPN_SIPRANGE) != 0)
   8334 		n->in_nsrcatype = FRI_RANGE;
   8335 
   8336 	if ((n->in_flags & IPN_DIPRANGE) != 0)
   8337 		n->in_ndstatype = FRI_RANGE;
   8338 
   8339 	if ((n->in_flags & IPN_SPLIT) != 0)
   8340 		n->in_ndstatype = FRI_SPLIT;
   8341 
   8342 	if ((n->in_redir & (NAT_MAP|NAT_REWRITE|NAT_DIVERTUDP)) != 0)
   8343 		n->in_spnext = n->in_spmin;
   8344 
   8345 	if ((n->in_redir & (NAT_REWRITE|NAT_DIVERTUDP)) != 0) {
   8346 		n->in_dpnext = n->in_dpmin;
   8347 	} else if (n->in_redir == NAT_REDIRECT) {
   8348 		n->in_dpnext = n->in_dpmin;
   8349 	}
   8350 
   8351 	n->in_stepnext = 0;
   8352 
   8353 	switch (n->in_v[0])
   8354 	{
   8355 	case 4 :
   8356 		error = ipf_nat_ruleaddrinit(softc, softn, n);
   8357 		if (error != 0)
   8358 			return error;
   8359 		break;
   8360 #ifdef USE_INET6
   8361 	case 6 :
   8362 		error = ipf_nat6_ruleaddrinit(softc, softn, n);
   8363 		if (error != 0)
   8364 			return error;
   8365 		break;
   8366 #endif
   8367 	default :
   8368 		break;
   8369 	}
   8370 
   8371 	if (n->in_redir == (NAT_DIVERTUDP|NAT_MAP)) {
   8372 		/*
   8373 		 * Prerecord whether or not the destination of the divert
   8374 		 * is local or not to the interface the packet is going
   8375 		 * to be sent out.
   8376 		 */
   8377 		n->in_dlocal = ipf_deliverlocal(softc, n->in_v[1],
   8378 						n->in_ifps[1], &n->in_ndstip6);
   8379 	}
   8380 
   8381 	return error;
   8382 }
   8383 
   8384 
   8385 /* ------------------------------------------------------------------------ */
   8386 /* Function:    ipf_nat_rule_fini                                           */
   8387 /* Returns:     int   - 0 == success, else rules do not match.              */
   8388 /* Parameters:  softc(I) - pointer to soft context main structure           */
   8389 /*              n(I)     - rule to work on                                  */
   8390 /*                                                                          */
   8391 /* This function is used to release any objects that were referenced during */
   8392 /* the rule initialisation. This is useful both when free'ing the rule and  */
   8393 /* when handling ioctls that need to initialise these fields but not        */
   8394 /* actually use them after the ioctl processing has finished.               */
   8395 /* ------------------------------------------------------------------------ */
   8396 static void
   8397 ipf_nat_rule_fini(ipf_main_softc_t *softc, ipnat_t *n)
   8398 {
   8399 	if (n->in_odst.na_atype == FRI_LOOKUP && n->in_odst.na_ptr != NULL)
   8400 		ipf_lookup_deref(softc, n->in_odst.na_type, n->in_odst.na_ptr);
   8401 
   8402 	if (n->in_osrc.na_atype == FRI_LOOKUP && n->in_osrc.na_ptr != NULL)
   8403 		ipf_lookup_deref(softc, n->in_osrc.na_type, n->in_osrc.na_ptr);
   8404 
   8405 	if (n->in_ndst.na_atype == FRI_LOOKUP && n->in_ndst.na_ptr != NULL)
   8406 		ipf_lookup_deref(softc, n->in_ndst.na_type, n->in_ndst.na_ptr);
   8407 
   8408 	if (n->in_nsrc.na_atype == FRI_LOOKUP && n->in_nsrc.na_ptr != NULL)
   8409 		ipf_lookup_deref(softc, n->in_nsrc.na_type, n->in_nsrc.na_ptr);
   8410 
   8411 	if (n->in_divmp != NULL)
   8412 		FREE_MB_T(n->in_divmp);
   8413 }
   8414