Home | History | Annotate | Line # | Download | only in netinet
ip_nat6.c revision 1.5
      1 /*	$NetBSD: ip_nat6.c,v 1.5 2013/09/14 12:03:10 martin 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 ipf_nat6_KERNEL
     11 # define        KERNEL	1
     12 # define        ipf_nat6_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) && defined(__NetBSD_Version__) && \
     20     (__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 ipf_nat6_KERNEL
     28 # ifdef ipf_nat6__OpenBSD__
     29 struct file;
     30 # endif
     31 # include <sys/uio.h>
     32 # undef ipf_nat6_KERNEL
     33 #endif
     34 #if defined(_KERNEL) && (__FreeBSD_version >= 220000)
     35 # include <sys/filio.h>
     36 # include <sys/fcntl.h>
     37 #else
     38 # include <sys/ioctl.h>
     39 #endif
     40 #if !defined(AIX)
     41 # include <sys/fcntl.h>
     42 #endif
     43 #if !defined(linux)
     44 # include <sys/protosw.h>
     45 #endif
     46 #include <sys/socket.h>
     47 #if defined(_KERNEL)
     48 # include <sys/systm.h>
     49 # if !defined(__SVR4) && !defined(__svr4__)
     50 #  include <sys/mbuf.h>
     51 # endif
     52 #endif
     53 #if defined(__SVR4) || defined(__svr4__)
     54 # include <sys/filio.h>
     55 # include <sys/byteorder.h>
     56 # ifdef ipf_nat6_KERNEL
     57 #  include <sys/dditypes.h>
     58 # endif
     59 # include <sys/stream.h>
     60 # include <sys/kmem.h>
     61 #endif
     62 #if ipf_nat6__FreeBSD_version >= 300000
     63 # include <sys/queue.h>
     64 #endif
     65 #include <net/if.h>
     66 #if ipf_nat6__FreeBSD_version >= 300000
     67 # include <net/if_var.h>
     68 #endif
     69 #ifdef sun
     70 # include <net/af.h>
     71 #endif
     72 #include <net/route.h>
     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/ip_fil.h"
     92 #include "netinet/ip_nat.h"
     93 #include "netinet/ip_frag.h"
     94 #include "netinet/ip_state.h"
     95 #include "netinet/ip_proxy.h"
     96 #include "netinet/ip_lookup.h"
     97 #include "netinet/ip_dstlist.h"
     98 #include "netinet/ip_sync.h"
     99 #if (__FreeBSD_version >= 300000)
    100 # include <sys/malloc.h>
    101 #endif
    102 #ifdef HAS_SYS_MD5_H
    103 # include <sys/md5.h>
    104 #else
    105 # include "md5.h"
    106 #endif
    107 /* END OF INCLUDES */
    108 
    109 #undef	SOCKADDR_IN
    110 #define	SOCKADDR_IN	struct sockaddr_in
    111 
    112 #if !defined(lint)
    113 static const char rcsid[] = "@(#)Id: ip_nat6.c,v 1.1.1.2 2012/07/22 13:45:29 darrenr Exp";
    114 #endif
    115 
    116 #ifdef USE_INET6
    117 static struct hostmap *ipf_nat6_hostmap(ipf_nat_softc_t *, ipnat_t *,
    118 					     i6addr_t *, i6addr_t *,
    119 					     i6addr_t *, u_32_t);
    120 static int ipf_nat6_match(fr_info_t *, ipnat_t *);
    121 static void ipf_nat6_tabmove(ipf_nat_softc_t *, nat_t *);
    122 static int ipf_nat6_decap(fr_info_t *, nat_t *);
    123 static int ipf_nat6_nextaddr(fr_info_t *, nat_addr_t *, i6addr_t *,
    124 				  i6addr_t *);
    125 static int ipf_nat6_icmpquerytype(int);
    126 static int ipf_nat6_out(fr_info_t *, nat_t *, int, u_32_t);
    127 static int ipf_nat6_in(fr_info_t *, nat_t *, int, u_32_t);
    128 static int ipf_nat6_builddivertmp(ipf_nat_softc_t *, ipnat_t *);
    129 static int ipf_nat6_nextaddrinit(ipf_main_softc_t *, char *,
    130 				      nat_addr_t *, int, void *);
    131 static int ipf_nat6_insert(ipf_main_softc_t *, ipf_nat_softc_t *,
    132 				nat_t *);
    133 
    134 
    135 #define	NINCLSIDE6(y,x)	ATOMIC_INCL(softn->ipf_nat_stats.ns_side6[y].x)
    136 #define	NBUMPSIDE(y,x)	softn->ipf_nat_stats.ns_side[y].x++
    137 #define	NBUMPSIDE6(y,x)	softn->ipf_nat_stats.ns_side6[y].x++
    138 #define	NBUMPSIDE6D(y,x) \
    139 			do { \
    140 				softn->ipf_nat_stats.ns_side6[y].x++; \
    141 				DT(x); \
    142 			} while (0)
    143 #define	NBUMPSIDE6DX(y,x,z) \
    144 			do { \
    145 				softn->ipf_nat_stats.ns_side6[y].x++; \
    146 				DT(z); \
    147 			} while (0)
    148 
    149 
    150 /* ------------------------------------------------------------------------ */
    151 /* Function:    ipf_nat6_ruleaddrinit                                       */
    152 /* Returns:     int   - 0 == success, else failure                          */
    153 /* Parameters:  in(I) - NAT rule that requires address fields to be init'd  */
    154 /*                                                                          */
    155 /* For each of the source/destination address fields in a NAT rule, call    */
    156 /* ipf_nat6_nextaddrinit() to prepare the structure for active duty.  Other */
    157 /* IPv6 specific actions can also be taken care of here.                    */
    158 /* ------------------------------------------------------------------------ */
    159 int
    160 ipf_nat6_ruleaddrinit(ipf_main_softc_t *softc, ipf_nat_softc_t *softn,
    161     ipnat_t *n)
    162 {
    163 	int idx, error;
    164 
    165 	if (n->in_redir == NAT_BIMAP) {
    166 		n->in_ndstip6 = n->in_osrcip6;
    167 		n->in_ndstmsk6 = n->in_osrcmsk6;
    168 		n->in_odstip6 = n->in_nsrcip6;
    169 		n->in_odstmsk6 = n->in_nsrcmsk6;
    170 
    171 	}
    172 
    173 	if (n->in_redir & NAT_REDIRECT)
    174 		idx = 1;
    175 	else
    176 		idx = 0;
    177 	/*
    178 	 * Initialise all of the address fields.
    179 	 */
    180 	error = ipf_nat6_nextaddrinit(softc, n->in_names, &n->in_osrc, 1,
    181 				      n->in_ifps[idx]);
    182 	if (error != 0)
    183 		return error;
    184 
    185 	error = ipf_nat6_nextaddrinit(softc, n->in_names, &n->in_odst, 1,
    186 				      n->in_ifps[idx]);
    187 	if (error != 0)
    188 		return error;
    189 
    190 	error = ipf_nat6_nextaddrinit(softc, n->in_names, &n->in_nsrc, 1,
    191 				      n->in_ifps[idx]);
    192 	if (error != 0)
    193 		return error;
    194 
    195 	error = ipf_nat6_nextaddrinit(softc, n->in_names, &n->in_ndst, 1,
    196 				      n->in_ifps[idx]);
    197 	if (error != 0)
    198 		return error;
    199 
    200 	if (n->in_redir & NAT_DIVERTUDP)
    201 		ipf_nat6_builddivertmp(softn, n);
    202 	return 0;
    203 }
    204 
    205 
    206 /* ------------------------------------------------------------------------ */
    207 /* Function:    ipf_nat6_addrdr                                             */
    208 /* Returns:     Nil                                                         */
    209 /* Parameters:  n(I) - pointer to NAT rule to add                           */
    210 /*                                                                          */
    211 /* Adds a redirect rule to the hash table of redirect rules and the list of */
    212 /* loaded NAT rules.  Updates the bitmask indicating which netmasks are in  */
    213 /* use by redirect rules.                                                   */
    214 /* ------------------------------------------------------------------------ */
    215 void
    216 ipf_nat6_addrdr(ipf_nat_softc_t *softn, ipnat_t *n)
    217 {
    218 	i6addr_t *mask;
    219 	ipnat_t **np;
    220 	i6addr_t j;
    221 	u_int hv;
    222 	int k;
    223 
    224 	if ((n->in_redir & NAT_BIMAP) == NAT_BIMAP) {
    225 		k = count6bits(n->in_nsrcmsk6.i6);
    226 		mask = &n->in_nsrcmsk6;
    227 		IP6_AND(&n->in_odstip6, &n->in_odstmsk6, &j);
    228 		hv = NAT_HASH_FN6(&j, 0, softn->ipf_nat_rdrrules_sz);
    229 
    230 	} else if (n->in_odstatype == FRI_NORMAL) {
    231 		k = count6bits(n->in_odstmsk6.i6);
    232 		mask = &n->in_odstmsk6;
    233 		IP6_AND(&n->in_odstip6, &n->in_odstmsk6, &j);
    234 		hv = NAT_HASH_FN6(&j, 0, softn->ipf_nat_rdrrules_sz);
    235 	} else {
    236 		k = 0;
    237 		hv = 0;
    238 		mask = NULL;
    239 	}
    240 	ipf_inet6_mask_add(k, mask, &softn->ipf_nat6_rdr_mask);
    241 
    242 	np = softn->ipf_nat_rdr_rules + hv;
    243 	while (*np != NULL)
    244 		np = &(*np)->in_rnext;
    245 	n->in_rnext = NULL;
    246 	n->in_prnext = np;
    247 	n->in_hv[0] = hv;
    248 	n->in_use++;
    249 	*np = n;
    250 }
    251 
    252 
    253 /* ------------------------------------------------------------------------ */
    254 /* Function:    ipf_nat6_addmap                                             */
    255 /* Returns:     Nil                                                         */
    256 /* Parameters:  n(I) - pointer to NAT rule to add                           */
    257 /*                                                                          */
    258 /* Adds a NAT map rule to the hash table of rules and the list of  loaded   */
    259 /* NAT rules.  Updates the bitmask indicating which netmasks are in use by  */
    260 /* redirect rules.                                                          */
    261 /* ------------------------------------------------------------------------ */
    262 void
    263 ipf_nat6_addmap(ipf_nat_softc_t *softn, ipnat_t *n)
    264 {
    265 	i6addr_t *mask;
    266 	ipnat_t **np;
    267 	i6addr_t j;
    268 	u_int hv;
    269 	int k;
    270 
    271 	if (n->in_osrcatype == FRI_NORMAL) {
    272 		k = count6bits(n->in_osrcmsk6.i6);
    273 		mask = &n->in_osrcmsk6;
    274 		IP6_AND(&n->in_osrcip6, &n->in_osrcmsk6, &j);
    275 		hv = NAT_HASH_FN6(&j, 0, softn->ipf_nat_maprules_sz);
    276 	} else {
    277 		k = 0;
    278 		hv = 0;
    279 		mask = NULL;
    280 	}
    281 	ipf_inet6_mask_add(k, mask, &softn->ipf_nat6_map_mask);
    282 
    283 	np = softn->ipf_nat_map_rules + hv;
    284 	while (*np != NULL)
    285 		np = &(*np)->in_mnext;
    286 	n->in_mnext = NULL;
    287 	n->in_pmnext = np;
    288 	n->in_hv[1] = hv;
    289 	n->in_use++;
    290 	*np = n;
    291 }
    292 
    293 
    294 /* ------------------------------------------------------------------------ */
    295 /* Function:    ipf_nat6_del_rdr                                             */
    296 /* Returns:     Nil                                                         */
    297 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
    298 /*                                                                          */
    299 /* Removes a NAT rdr rule from the hash table of NAT rdr rules.             */
    300 /* ------------------------------------------------------------------------ */
    301 void
    302 ipf_nat6_delrdr(ipf_nat_softc_t *softn, ipnat_t *n)
    303 {
    304 	i6addr_t *mask;
    305 	int k;
    306 
    307 	if ((n->in_redir & NAT_BIMAP) == NAT_BIMAP) {
    308 		k = count6bits(n->in_nsrcmsk6.i6);
    309 		mask = &n->in_nsrcmsk6;
    310 	} else if (n->in_odstatype == FRI_NORMAL) {
    311 		k = count6bits(n->in_odstmsk6.i6);
    312 		mask = &n->in_odstmsk6;
    313 	} else {
    314 		k = 0;
    315 		mask = NULL;
    316 	}
    317 	ipf_inet6_mask_del(k, mask, &softn->ipf_nat6_rdr_mask);
    318 
    319 	if (n->in_rnext != NULL)
    320 		n->in_rnext->in_prnext = n->in_prnext;
    321 	*n->in_prnext = n->in_rnext;
    322 	n->in_use--;
    323 }
    324 
    325 
    326 /* ------------------------------------------------------------------------ */
    327 /* Function:    ipf_nat6_delmap                                             */
    328 /* Returns:     Nil                                                         */
    329 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
    330 /*                                                                          */
    331 /* Removes a NAT map rule from the hash table of NAT map rules.             */
    332 /* ------------------------------------------------------------------------ */
    333 void
    334 ipf_nat6_delmap(ipf_nat_softc_t *softn, ipnat_t *n)
    335 {
    336 	i6addr_t *mask;
    337 	int k;
    338 
    339 	if (n->in_osrcatype == FRI_NORMAL) {
    340 		k = count6bits(n->in_osrcmsk6.i6);
    341 		mask = &n->in_osrcmsk6;
    342 	} else {
    343 		k = 0;
    344 		mask = NULL;
    345 	}
    346 	ipf_inet6_mask_del(k, mask, &softn->ipf_nat6_map_mask);
    347 
    348 	if (n->in_mnext != NULL)
    349 		n->in_mnext->in_pmnext = n->in_pmnext;
    350 	*n->in_pmnext = n->in_mnext;
    351 	n->in_use--;
    352 }
    353 
    354 
    355 /* ------------------------------------------------------------------------ */
    356 /* Function:    ipf_nat6_hostmap                                            */
    357 /* Returns:     struct hostmap* - NULL if no hostmap could be created,      */
    358 /*                                else a pointer to the hostmapping to use  */
    359 /* Parameters:  np(I)   - pointer to NAT rule                               */
    360 /*              real(I) - real IP address                                   */
    361 /*              map(I)  - mapped IP address                                 */
    362 /*              port(I) - destination port number                           */
    363 /* Write Locks: ipf_nat                                                     */
    364 /*                                                                          */
    365 /* Check if an ip address has already been allocated for a given mapping    */
    366 /* that is not doing port based translation.  If is not yet allocated, then */
    367 /* create a new entry if a non-NULL NAT rule pointer has been supplied.     */
    368 /* ------------------------------------------------------------------------ */
    369 static struct hostmap *
    370 ipf_nat6_hostmap(ipf_nat_softc_t *softn, ipnat_t *np, i6addr_t *src,
    371     i6addr_t *dst, i6addr_t *map, u_32_t port)
    372 {
    373 	hostmap_t *hm;
    374 	u_int hv;
    375 
    376 	hv = (src->i6[3] ^ dst->i6[3]);
    377 	hv += (src->i6[2] ^ dst->i6[2]);
    378 	hv += (src->i6[1] ^ dst->i6[1]);
    379 	hv += (src->i6[0] ^ dst->i6[0]);
    380 	hv += src->i6[3];
    381 	hv += src->i6[2];
    382 	hv += src->i6[1];
    383 	hv += src->i6[0];
    384 	hv += dst->i6[3];
    385 	hv += dst->i6[2];
    386 	hv += dst->i6[1];
    387 	hv += dst->i6[0];
    388 	hv %= HOSTMAP_SIZE;
    389 	for (hm = softn->ipf_hm_maptable[hv]; hm; hm = hm->hm_next)
    390 		if (IP6_EQ(&hm->hm_osrc6, src) &&
    391 		    IP6_EQ(&hm->hm_odst6, dst) &&
    392 		    ((np == NULL) || (np == hm->hm_ipnat)) &&
    393 		    ((port == 0) || (port == hm->hm_port))) {
    394 			softn->ipf_nat_stats.ns_hm_addref++;
    395 			hm->hm_ref++;
    396 			return hm;
    397 		}
    398 
    399 	if (np == NULL) {
    400 		softn->ipf_nat_stats.ns_hm_nullnp++;
    401 		return NULL;
    402 	}
    403 
    404 	KMALLOC(hm, hostmap_t *);
    405 	if (hm) {
    406 		hm->hm_next = softn->ipf_hm_maplist;
    407 		hm->hm_pnext = &softn->ipf_hm_maplist;
    408 		if (softn->ipf_hm_maplist != NULL)
    409 			softn->ipf_hm_maplist->hm_pnext = &hm->hm_next;
    410 		softn->ipf_hm_maplist = hm;
    411 		hm->hm_hnext = softn->ipf_hm_maptable[hv];
    412 		hm->hm_phnext = softn->ipf_hm_maptable + hv;
    413 		if (softn->ipf_hm_maptable[hv] != NULL)
    414 			softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
    415 		softn->ipf_hm_maptable[hv] = hm;
    416 		hm->hm_ipnat = np;
    417 		np->in_use++;
    418 		hm->hm_osrcip6 = *src;
    419 		hm->hm_odstip6 = *dst;
    420 		hm->hm_nsrcip6 = *map;
    421 		hm->hm_ndstip6.i6[0] = 0;
    422 		hm->hm_ndstip6.i6[1] = 0;
    423 		hm->hm_ndstip6.i6[2] = 0;
    424 		hm->hm_ndstip6.i6[3] = 0;
    425 		hm->hm_ref = 1;
    426 		hm->hm_port = port;
    427 		hm->hm_hv = hv;
    428 		hm->hm_v = 6;
    429 		softn->ipf_nat_stats.ns_hm_new++;
    430 	} else {
    431 		softn->ipf_nat_stats.ns_hm_newfail++;
    432 	}
    433 	return hm;
    434 }
    435 
    436 
    437 /* ------------------------------------------------------------------------ */
    438 /* Function:    ipf_nat6_newmap                                             */
    439 /* Returns:     int - -1 == error, 0 == success                             */
    440 /* Parameters:  fin(I) - pointer to packet information                      */
    441 /*              nat(I) - pointer to NAT entry                               */
    442 /*              ni(I)  - pointer to structure with misc. information needed */
    443 /*                       to create new NAT entry.                           */
    444 /*                                                                          */
    445 /* Given an empty NAT structure, populate it with new information about a   */
    446 /* new NAT session, as defined by the matching NAT rule.                    */
    447 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
    448 /* to the new IP address for the translation.                               */
    449 /* ------------------------------------------------------------------------ */
    450 int
    451 ipf_nat6_newmap(fr_info_t *fin, nat_t *nat, natinfo_t *ni)
    452 {
    453 	ipf_main_softc_t *softc = fin->fin_main_soft;
    454 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
    455 	u_short st_port, dport, sport, port, sp, dp;
    456 	i6addr_t in, st_ip;
    457 	hostmap_t *hm;
    458 	u_32_t flags;
    459 	ipnat_t *np;
    460 	nat_t *natl;
    461 	int l;
    462 
    463 	/*
    464 	 * If it's an outbound packet which doesn't match any existing
    465 	 * record, then create a new port
    466 	 */
    467 	l = 0;
    468 	hm = NULL;
    469 	np = ni->nai_np;
    470 	st_ip = np->in_snip6;
    471 	st_port = np->in_spnext;
    472 	flags = nat->nat_flags;
    473 
    474 	if (flags & IPN_ICMPQUERY) {
    475 		sport = fin->fin_data[1];
    476 		dport = 0;
    477 	} else {
    478 		sport = htons(fin->fin_data[0]);
    479 		dport = htons(fin->fin_data[1]);
    480 	}
    481 
    482 	/*
    483 	 * Do a loop until we either run out of entries to try or we find
    484 	 * a NAT mapping that isn't currently being used.  This is done
    485 	 * because the change to the source is not (usually) being fixed.
    486 	 */
    487 	do {
    488 		port = 0;
    489 		in = np->in_nsrc.na_nextaddr;
    490 		if (l == 0) {
    491 			/*
    492 			 * Check to see if there is an existing NAT
    493 			 * setup for this IP address pair.
    494 			 */
    495 			hm = ipf_nat6_hostmap(softn, np, &fin->fin_src6,
    496 					      &fin->fin_dst6, &in, 0);
    497 			if (hm != NULL)
    498 				in = hm->hm_nsrcip6;
    499 		} else if ((l == 1) && (hm != NULL)) {
    500 			ipf_nat_hostmapdel(softc, &hm);
    501 		}
    502 
    503 		nat->nat_hm = hm;
    504 
    505 		if (IP6_ISONES(&np->in_nsrcmsk6) && (np->in_spnext == 0)) {
    506 			if (l > 0) {
    507 				NBUMPSIDE6DX(1, ns_exhausted, ns_exhausted_1);
    508 				return -1;
    509 			}
    510 		}
    511 
    512 		if ((np->in_redir == NAT_BIMAP) &&
    513 		    IP6_EQ(&np->in_osrcmsk6, &np->in_nsrcmsk6)) {
    514 			i6addr_t temp;
    515 			/*
    516 			 * map the address block in a 1:1 fashion
    517 			 */
    518 			temp.i6[0] = fin->fin_src6.i6[0] &
    519 				     ~np->in_osrcmsk6.i6[0];
    520 			temp.i6[1] = fin->fin_src6.i6[1] &
    521 				     ~np->in_osrcmsk6.i6[1];
    522 			temp.i6[2] = fin->fin_src6.i6[2] &
    523 				     ~np->in_osrcmsk6.i6[0];
    524 			temp.i6[3] = fin->fin_src6.i6[3] &
    525 				     ~np->in_osrcmsk6.i6[3];
    526 			in = np->in_nsrcip6;
    527 			IP6_MERGE(&in, &temp, &np->in_osrc);
    528 
    529 #ifdef NEED_128BIT_MATH
    530 		} else if (np->in_redir & NAT_MAPBLK) {
    531 			if ((l >= np->in_ppip) || ((l > 0) &&
    532 			     !(flags & IPN_TCPUDP))) {
    533 				NBUMPSIDE6DX(1, ns_exhausted, ns_exhausted_2);
    534 				return -1;
    535 			}
    536 			/*
    537 			 * map-block - Calculate destination address.
    538 			 */
    539 			IP6_MASK(&in, &fin->fin_src6, &np->in_osrcmsk6);
    540 			in = ntohl(in);
    541 			inb = in;
    542 			in.s_addr /= np->in_ippip;
    543 			in.s_addr &= ntohl(~np->in_nsrcmsk6);
    544 			in.s_addr += ntohl(np->in_nsrcaddr6);
    545 			/*
    546 			 * Calculate destination port.
    547 			 */
    548 			if ((flags & IPN_TCPUDP) &&
    549 			    (np->in_ppip != 0)) {
    550 				port = ntohs(sport) + l;
    551 				port %= np->in_ppip;
    552 				port += np->in_ppip *
    553 					(inb.s_addr % np->in_ippip);
    554 				port += MAPBLK_MINPORT;
    555 				port = htons(port);
    556 			}
    557 #endif
    558 
    559 		} else if (IP6_ISZERO(&np->in_nsrcaddr) &&
    560 			   IP6_ISONES(&np->in_nsrcmsk)) {
    561 			/*
    562 			 * 0/32 - use the interface's IP address.
    563 			 */
    564 			if ((l > 0) ||
    565 			    ipf_ifpaddr(softc, 6, FRI_NORMAL, fin->fin_ifp,
    566 				       &in, NULL) == -1) {
    567 				NBUMPSIDE6DX(1, ns_new_ifpaddr,
    568 					     ns_new_ifpaddr_1);
    569 				return -1;
    570 			}
    571 
    572 		} else if (IP6_ISZERO(&np->in_nsrcip6) &&
    573 			   IP6_ISZERO(&np->in_nsrcmsk6)) {
    574 			/*
    575 			 * 0/0 - use the original source address/port.
    576 			 */
    577 			if (l > 0) {
    578 				NBUMPSIDE6DX(1, ns_exhausted, ns_exhausted_3);
    579 				return -1;
    580 			}
    581 			in = fin->fin_src6;
    582 
    583 		} else if (!IP6_ISONES(&np->in_nsrcmsk6) &&
    584 			   (np->in_spnext == 0) && ((l > 0) || (hm == NULL))) {
    585 			IP6_INC(&np->in_snip6);
    586 		}
    587 
    588 		natl = NULL;
    589 
    590 		if ((flags & IPN_TCPUDP) &&
    591 		    ((np->in_redir & NAT_MAPBLK) == 0) &&
    592 		    (np->in_flags & IPN_AUTOPORTMAP)) {
    593 #ifdef NEED_128BIT_MATH
    594 			/*
    595 			 * "ports auto" (without map-block)
    596 			 */
    597 			if ((l > 0) && (l % np->in_ppip == 0)) {
    598 				if ((l > np->in_ppip) &&
    599 				    !IP6_ISONES(&np->in_nsrcmsk)) {
    600 					IP6_INC(&np->in_snip6)
    601 				}
    602 			}
    603 			if (np->in_ppip != 0) {
    604 				port = ntohs(sport);
    605 				port += (l % np->in_ppip);
    606 				port %= np->in_ppip;
    607 				port += np->in_ppip *
    608 					(ntohl(fin->fin_src6) %
    609 					 np->in_ippip);
    610 				port += MAPBLK_MINPORT;
    611 				port = htons(port);
    612 			}
    613 #endif
    614 
    615 		} else if (((np->in_redir & NAT_MAPBLK) == 0) &&
    616 			   (flags & IPN_TCPUDPICMP) && (np->in_spnext != 0)) {
    617                         /*
    618                          * Standard port translation.  Select next port.
    619                          */
    620                         if (np->in_flags & IPN_SEQUENTIAL) {
    621                                 port = np->in_spnext;
    622                         } else {
    623 				port = ipf_random() % (np->in_spmax -
    624 						       np->in_spmin + 1);
    625                                 port += np->in_spmin;
    626                         }
    627                         port = htons(port);
    628                         np->in_spnext++;
    629 
    630 			if (np->in_spnext > np->in_spmax) {
    631 				np->in_spnext = np->in_spmin;
    632 				if (!IP6_ISONES(&np->in_nsrcmsk6)) {
    633 					IP6_INC(&np->in_snip6);
    634 				}
    635 			}
    636 		}
    637 
    638 		if (np->in_flags & IPN_SIPRANGE) {
    639 			if (IP6_GT(&np->in_snip, &np->in_nsrcmsk))
    640 				np->in_snip6 = np->in_nsrcip6;
    641 		} else {
    642 			i6addr_t a1, a2;
    643 
    644 			a1 = np->in_snip6;
    645 			IP6_INC(&a1);
    646 			IP6_AND(&a1, &np->in_nsrcmsk6, &a2);
    647 
    648 			if (!IP6_ISONES(&np->in_nsrcmsk6) &&
    649 			    IP6_GT(&a2, &np->in_nsrcip6)) {
    650 				IP6_ADD(&np->in_nsrcip6, 1, &np->in_snip6);
    651 			}
    652 		}
    653 
    654 		if ((port == 0) && (flags & (IPN_TCPUDPICMP|IPN_ICMPQUERY)))
    655 			port = sport;
    656 
    657 		/*
    658 		 * Here we do a lookup of the connection as seen from
    659 		 * the outside.  If an IP# pair already exists, try
    660 		 * again.  So if you have A->B becomes C->B, you can
    661 		 * also have D->E become C->E but not D->B causing
    662 		 * another C->B.  Also take protocol and ports into
    663 		 * account when determining whether a pre-existing
    664 		 * NAT setup will cause an external conflict where
    665 		 * this is appropriate.
    666 		 */
    667 		sp = fin->fin_data[0];
    668 		dp = fin->fin_data[1];
    669 		fin->fin_data[0] = fin->fin_data[1];
    670 		fin->fin_data[1] = ntohs(port);
    671 		natl = ipf_nat6_inlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
    672 					 (u_int)fin->fin_p, &fin->fin_dst6.in6,
    673 					 &in.in6);
    674 		fin->fin_data[0] = sp;
    675 		fin->fin_data[1] = dp;
    676 
    677 		/*
    678 		 * Has the search wrapped around and come back to the
    679 		 * start ?
    680 		 */
    681 		if ((natl != NULL) &&
    682 		    (np->in_spnext != 0) && (st_port == np->in_spnext) &&
    683 		    (!IP6_ISZERO(&np->in_snip6) &&
    684 		     IP6_EQ(&st_ip, &np->in_snip6))) {
    685 			NBUMPSIDE6D(1, ns_wrap);
    686 			return -1;
    687 		}
    688 		l++;
    689 	} while (natl != NULL);
    690 
    691 	/* Setup the NAT table */
    692 	nat->nat_osrc6 = fin->fin_src6;
    693 	nat->nat_nsrc6 = in;
    694 	nat->nat_odst6 = fin->fin_dst6;
    695 	nat->nat_ndst6 = fin->fin_dst6;
    696 	if (nat->nat_hm == NULL)
    697 		nat->nat_hm = ipf_nat6_hostmap(softn, np, &fin->fin_src6,
    698 					       &fin->fin_dst6,
    699 					       &nat->nat_nsrc6, 0);
    700 
    701 	if (flags & IPN_TCPUDP) {
    702 		nat->nat_osport = sport;
    703 		nat->nat_nsport = port;	/* sport */
    704 		nat->nat_odport = dport;
    705 		nat->nat_ndport = dport;
    706 		((tcphdr_t *)fin->fin_dp)->th_sport = port;
    707 	} else if (flags & IPN_ICMPQUERY) {
    708 		nat->nat_oicmpid = fin->fin_data[1];
    709 		((struct icmp6_hdr *)fin->fin_dp)->icmp6_id = port;
    710 		nat->nat_nicmpid = port;
    711 	}
    712 	return 0;
    713 }
    714 
    715 
    716 /* ------------------------------------------------------------------------ */
    717 /* Function:    ipf_nat6_newrdr                                             */
    718 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
    719 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
    720 /* Parameters:  fin(I) - pointer to packet information                      */
    721 /*              nat(I) - pointer to NAT entry                               */
    722 /*              ni(I)  - pointer to structure with misc. information needed */
    723 /*                       to create new NAT entry.                           */
    724 /*                                                                          */
    725 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
    726 /* to the new IP address for the translation.                               */
    727 /* ------------------------------------------------------------------------ */
    728 int
    729 ipf_nat6_newrdr(fr_info_t *fin, nat_t *nat, natinfo_t *ni)
    730 {
    731 	ipf_main_softc_t *softc = fin->fin_main_soft;
    732 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
    733 	u_short nport, dport, sport;
    734 	u_short sp, dp;
    735 	hostmap_t *hm;
    736 	u_32_t flags;
    737 	i6addr_t in;
    738 	ipnat_t *np;
    739 	nat_t *natl;
    740 	int move;
    741 
    742 	move = 1;
    743 	hm = NULL;
    744 	in.i6[0] = 0;
    745 	in.i6[1] = 0;
    746 	in.i6[2] = 0;
    747 	in.i6[3] = 0;
    748 	np = ni->nai_np;
    749 	flags = nat->nat_flags;
    750 
    751 	if (flags & IPN_ICMPQUERY) {
    752 		dport = fin->fin_data[1];
    753 		sport = 0;
    754 	} else {
    755 		sport = htons(fin->fin_data[0]);
    756 		dport = htons(fin->fin_data[1]);
    757 	}
    758 
    759 	/* TRACE sport, dport */
    760 
    761 
    762 	/*
    763 	 * If the matching rule has IPN_STICKY set, then we want to have the
    764 	 * same rule kick in as before.  Why would this happen?  If you have
    765 	 * a collection of rdr rules with "round-robin sticky", the current
    766 	 * packet might match a different one to the previous connection but
    767 	 * we want the same destination to be used.
    768 	 */
    769 	if (((np->in_flags & (IPN_ROUNDR|IPN_SPLIT)) != 0) &&
    770 	    ((np->in_flags & IPN_STICKY) != 0)) {
    771 		hm = ipf_nat6_hostmap(softn, NULL, &fin->fin_src6,
    772 				      &fin->fin_dst6, &in, (u_32_t)dport);
    773 		if (hm != NULL) {
    774 			in = hm->hm_ndstip6;
    775 			np = hm->hm_ipnat;
    776 			ni->nai_np = np;
    777 			move = 0;
    778 		}
    779 	}
    780 
    781 	/*
    782 	 * Otherwise, it's an inbound packet. Most likely, we don't
    783 	 * want to rewrite source ports and source addresses. Instead,
    784 	 * we want to rewrite to a fixed internal address and fixed
    785 	 * internal port.
    786 	 */
    787 	if (np->in_flags & IPN_SPLIT) {
    788 		in = np->in_dnip6;
    789 
    790 		if ((np->in_flags & (IPN_ROUNDR|IPN_STICKY)) == IPN_STICKY) {
    791 			hm = ipf_nat6_hostmap(softn, NULL, &fin->fin_src6,
    792 					      &fin->fin_dst6, &in,
    793 					      (u_32_t)dport);
    794 			if (hm != NULL) {
    795 				in = hm->hm_ndstip6;
    796 				move = 0;
    797 			}
    798 		}
    799 
    800 		if (hm == NULL || hm->hm_ref == 1) {
    801 			if (IP6_EQ(&np->in_ndstip6, &in)) {
    802 				np->in_dnip6 = np->in_ndstmsk6;
    803 				move = 0;
    804 			} else {
    805 				np->in_dnip6 = np->in_ndstip6;
    806 			}
    807 		}
    808 
    809 	} else if (IP6_ISZERO(&np->in_ndstaddr) &&
    810 		   IP6_ISONES(&np->in_ndstmsk)) {
    811 		/*
    812 		 * 0/32 - use the interface's IP address.
    813 		 */
    814 		if (ipf_ifpaddr(softc, 6, FRI_NORMAL, fin->fin_ifp,
    815 			       &in, NULL) == -1) {
    816 			NBUMPSIDE6DX(0, ns_new_ifpaddr, ns_new_ifpaddr_2);
    817 			return -1;
    818 		}
    819 
    820 	} else if (IP6_ISZERO(&np->in_ndstip6) &&
    821 		   IP6_ISZERO(&np->in_ndstmsk6)) {
    822 		/*
    823 		 * 0/0 - use the original destination address/port.
    824 		 */
    825 		in = fin->fin_dst6;
    826 
    827 	} else if (np->in_redir == NAT_BIMAP &&
    828 		   IP6_EQ(&np->in_ndstmsk6, &np->in_odstmsk6)) {
    829 		i6addr_t temp;
    830 		/*
    831 		 * map the address block in a 1:1 fashion
    832 		 */
    833 		temp.i6[0] = fin->fin_dst6.i6[0] & ~np->in_osrcmsk6.i6[0];
    834 		temp.i6[1] = fin->fin_dst6.i6[1] & ~np->in_osrcmsk6.i6[1];
    835 		temp.i6[2] = fin->fin_dst6.i6[2] & ~np->in_osrcmsk6.i6[0];
    836 		temp.i6[3] = fin->fin_dst6.i6[3] & ~np->in_osrcmsk6.i6[3];
    837 		in = np->in_ndstip6;
    838 		IP6_MERGE(&in, &temp, &np->in_ndstmsk6);
    839 	} else {
    840 		in = np->in_ndstip6;
    841 	}
    842 
    843 	if ((np->in_dpnext == 0) || ((flags & NAT_NOTRULEPORT) != 0))
    844 		nport = dport;
    845 	else {
    846 		/*
    847 		 * Whilst not optimized for the case where
    848 		 * pmin == pmax, the gain is not significant.
    849 		 */
    850 		if (((np->in_flags & IPN_FIXEDDPORT) == 0) &&
    851 		    (np->in_odport != np->in_dtop)) {
    852 			nport = ntohs(dport) - np->in_odport + np->in_dpmax;
    853 			nport = htons(nport);
    854 		} else {
    855 			nport = htons(np->in_dpnext);
    856 			np->in_dpnext++;
    857 			if (np->in_dpnext > np->in_dpmax)
    858 				np->in_dpnext = np->in_dpmin;
    859 		}
    860 	}
    861 
    862 	/*
    863 	 * When the redirect-to address is set to 0.0.0.0, just
    864 	 * assume a blank `forwarding' of the packet.  We don't
    865 	 * setup any translation for this either.
    866 	 */
    867 	if (IP6_ISZERO(&in)) {
    868 		if (nport == dport) {
    869 			NBUMPSIDE6D(0, ns_xlate_null);
    870 			return -1;
    871 		}
    872 		in = fin->fin_dst6;
    873 	}
    874 
    875 	/*
    876 	 * Check to see if this redirect mapping already exists and if
    877 	 * it does, return "failure" (allowing it to be created will just
    878 	 * cause one or both of these "connections" to stop working.)
    879 	 */
    880 	sp = fin->fin_data[0];
    881 	dp = fin->fin_data[1];
    882 	fin->fin_data[1] = fin->fin_data[0];
    883 	fin->fin_data[0] = ntohs(nport);
    884 	natl = ipf_nat6_outlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
    885 				  (u_int)fin->fin_p, &in.in6,
    886 				  &fin->fin_src6.in6);
    887 	fin->fin_data[0] = sp;
    888 	fin->fin_data[1] = dp;
    889 	if (natl != NULL) {
    890 		NBUMPSIDE6D(0, ns_xlate_exists);
    891 		return -1;
    892 	}
    893 
    894 	nat->nat_ndst6 = in;
    895 	nat->nat_odst6 = fin->fin_dst6;
    896 	nat->nat_nsrc6 = fin->fin_src6;
    897 	nat->nat_osrc6 = fin->fin_src6;
    898 	if ((nat->nat_hm == NULL) && ((np->in_flags & IPN_STICKY) != 0))
    899 		nat->nat_hm = ipf_nat6_hostmap(softn, np, &fin->fin_src6,
    900 					       &fin->fin_dst6, &in,
    901 					       (u_32_t)dport);
    902 
    903 	if (flags & IPN_TCPUDP) {
    904 		nat->nat_odport = dport;
    905 		nat->nat_ndport = nport;
    906 		nat->nat_osport = sport;
    907 		nat->nat_nsport = sport;
    908 		((tcphdr_t *)fin->fin_dp)->th_dport = nport;
    909 	} else if (flags & IPN_ICMPQUERY) {
    910 		nat->nat_oicmpid = fin->fin_data[1];
    911 		((struct icmp6_hdr *)fin->fin_dp)->icmp6_id = nport;
    912 		nat->nat_nicmpid = nport;
    913 	}
    914 
    915 	return move;
    916 }
    917 
    918 /* ------------------------------------------------------------------------ */
    919 /* Function:    ipf_nat6_add                                                */
    920 /* Returns:     nat6_t*      - NULL == failure to create new NAT structure, */
    921 /*                             else pointer to new NAT structure            */
    922 /* Parameters:  fin(I)       - pointer to packet information                */
    923 /*              np(I)        - pointer to NAT rule                          */
    924 /*              natsave(I)   - pointer to where to store NAT struct pointer */
    925 /*              flags(I)     - flags describing the current packet          */
    926 /*              direction(I) - direction of packet (in/out)                 */
    927 /* Write Lock:  ipf_nat                                                     */
    928 /*                                                                          */
    929 /* Attempts to create a new NAT entry.  Does not actually change the packet */
    930 /* in any way.                                                              */
    931 /*                                                                          */
    932 /* This fucntion is in three main parts: (1) deal with creating a new NAT   */
    933 /* structure for a "MAP" rule (outgoing NAT translation); (2) deal with     */
    934 /* creating a new NAT structure for a "RDR" rule (incoming NAT translation) */
    935 /* and (3) building that structure and putting it into the NAT table(s).    */
    936 /*                                                                          */
    937 /* NOTE: natsave should NOT be used top point back to an ipstate_t struct   */
    938 /*       as it can result in memory being corrupted.                        */
    939 /* ------------------------------------------------------------------------ */
    940 nat_t *
    941 ipf_nat6_add(fr_info_t *fin, ipnat_t *np, nat_t **natsave, u_int flags,
    942     int direction)
    943 {
    944 	ipf_main_softc_t *softc = fin->fin_main_soft;
    945 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
    946 	hostmap_t *hm = NULL;
    947 	nat_t *nat, *natl;
    948 	natstat_t *nsp;
    949 	u_int nflags;
    950 	natinfo_t ni;
    951 	int move;
    952 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6) && defined(ICK_M_CTL_MAGIC)
    953 	qpktinfo_t *qpi = fin->fin_qpi;
    954 #endif
    955 
    956 	nsp = &softn->ipf_nat_stats;
    957 
    958 	if ((nsp->ns_active * 100 / softn->ipf_nat_table_max) >
    959 	    softn->ipf_nat_table_wm_high) {
    960 		softn->ipf_nat_doflush = 1;
    961 	}
    962 
    963 	if (nsp->ns_active >= softn->ipf_nat_table_max) {
    964 		NBUMPSIDE6(fin->fin_out, ns_table_max);
    965 		return NULL;
    966 	}
    967 
    968 	move = 1;
    969 	nflags = np->in_flags & flags;
    970 	nflags &= NAT_FROMRULE;
    971 
    972 	ni.nai_np = np;
    973 	ni.nai_dport = 0;
    974 	ni.nai_sport = 0;
    975 
    976 	/* Give me a new nat */
    977 	KMALLOC(nat, nat_t *);
    978 	if (nat == NULL) {
    979 		NBUMPSIDE6(fin->fin_out, ns_memfail);
    980 		/*
    981 		 * Try to automatically tune the max # of entries in the
    982 		 * table allowed to be less than what will cause kmem_alloc()
    983 		 * to fail and try to eliminate panics due to out of memory
    984 		 * conditions arising.
    985 		 */
    986 		if ((softn->ipf_nat_table_max > softn->ipf_nat_table_sz) &&
    987 		    (nsp->ns_active > 100)) {
    988 			softn->ipf_nat_table_max = nsp->ns_active - 100;
    989 			printf("table_max reduced to %d\n",
    990 				softn->ipf_nat_table_max);
    991 		}
    992 		return NULL;
    993 	}
    994 
    995 	if (flags & IPN_ICMPQUERY) {
    996 		/*
    997 		 * In the ICMP query NAT code, we translate the ICMP id fields
    998 		 * to make them unique. This is indepedent of the ICMP type
    999 		 * (e.g. in the unlikely event that a host sends an echo and
   1000 		 * an tstamp request with the same id, both packets will have
   1001 		 * their ip address/id field changed in the same way).
   1002 		 */
   1003 		/* The icmp6_id field is used by the sender to identify the
   1004 		 * process making the icmp request. (the receiver justs
   1005 		 * copies it back in its response). So, it closely matches
   1006 		 * the concept of source port. We overlay sport, so we can
   1007 		 * maximally reuse the existing code.
   1008 		 */
   1009 		ni.nai_sport = fin->fin_data[1];
   1010 		ni.nai_dport = 0;
   1011 	}
   1012 
   1013 	bzero((char *)nat, sizeof(*nat));
   1014 	nat->nat_flags = flags;
   1015 	nat->nat_redir = np->in_redir;
   1016 	nat->nat_dir = direction;
   1017 	nat->nat_pr[0] = fin->fin_p;
   1018 	nat->nat_pr[1] = fin->fin_p;
   1019 
   1020 	/*
   1021 	 * Search the current table for a match and create a new mapping
   1022 	 * if there is none found.
   1023 	 */
   1024 	if (np->in_redir & NAT_DIVERTUDP) {
   1025 		move = ipf_nat6_newdivert(fin, nat, &ni);
   1026 
   1027 	} else if (np->in_redir & NAT_REWRITE) {
   1028 		move = ipf_nat6_newrewrite(fin, nat, &ni);
   1029 
   1030 	} else if (direction == NAT_OUTBOUND) {
   1031 		/*
   1032 		 * We can now arrange to call this for the same connection
   1033 		 * because ipf_nat6_new doesn't protect the code path into
   1034 		 * this function.
   1035 		 */
   1036 		natl = ipf_nat6_outlookup(fin, nflags, (u_int)fin->fin_p,
   1037 					  &fin->fin_src6.in6,
   1038 					  &fin->fin_dst6.in6);
   1039 		if (natl != NULL) {
   1040 			KFREE(nat);
   1041 			nat = natl;
   1042 			goto done;
   1043 		}
   1044 
   1045 		move = ipf_nat6_newmap(fin, nat, &ni);
   1046 	} else {
   1047 		/*
   1048 		 * NAT_INBOUND is used for redirects rules
   1049 		 */
   1050 		natl = ipf_nat6_inlookup(fin, nflags, (u_int)fin->fin_p,
   1051 					 &fin->fin_src6.in6,
   1052 					 &fin->fin_dst6.in6);
   1053 		if (natl != NULL) {
   1054 			KFREE(nat);
   1055 			nat = natl;
   1056 			goto done;
   1057 		}
   1058 
   1059 		move = ipf_nat6_newrdr(fin, nat, &ni);
   1060 	}
   1061 	if (move == -1)
   1062 		goto badnat;
   1063 
   1064 	np = ni.nai_np;
   1065 
   1066 	nat->nat_mssclamp = np->in_mssclamp;
   1067 	nat->nat_me = natsave;
   1068 	nat->nat_fr = fin->fin_fr;
   1069 	nat->nat_rev = fin->fin_rev;
   1070 	nat->nat_ptr = np;
   1071 	nat->nat_dlocal = np->in_dlocal;
   1072 
   1073 	if ((np->in_apr != NULL) && ((nat->nat_flags & NAT_SLAVE) == 0)) {
   1074 		if (ipf_proxy_new(fin, nat) == -1) {
   1075 			NBUMPSIDE6D(fin->fin_out, ns_appr_fail);
   1076 			goto badnat;
   1077 		}
   1078 	}
   1079 
   1080 	nat->nat_ifps[0] = np->in_ifps[0];
   1081 	if (np->in_ifps[0] != NULL) {
   1082 		COPYIFNAME(np->in_v[0], np->in_ifps[0], nat->nat_ifnames[0]);
   1083 	}
   1084 
   1085 	nat->nat_ifps[1] = np->in_ifps[1];
   1086 	if (np->in_ifps[1] != NULL) {
   1087 		COPYIFNAME(np->in_v[1], np->in_ifps[1], nat->nat_ifnames[1]);
   1088 	}
   1089 
   1090 	if (ipf_nat6_finalise(fin, nat) == -1) {
   1091 		goto badnat;
   1092 	}
   1093 
   1094 	np->in_use++;
   1095 
   1096 	if ((move == 1) && (np->in_flags & IPN_ROUNDR)) {
   1097 		if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_REDIRECT) {
   1098 			ipf_nat6_delrdr(softn, np);
   1099 			ipf_nat6_addrdr(softn, np);
   1100 		} else if ((np->in_redir & (NAT_REDIRECT|NAT_MAP)) == NAT_MAP) {
   1101 			ipf_nat6_delmap(softn, np);
   1102 			ipf_nat6_addmap(softn, np);
   1103 		}
   1104 	}
   1105 
   1106 	if (flags & SI_WILDP)
   1107 		nsp->ns_wilds++;
   1108 	softn->ipf_nat_stats.ns_proto[nat->nat_pr[0]]++;
   1109 
   1110 	goto done;
   1111 badnat:
   1112 	NBUMPSIDE6(fin->fin_out, ns_badnatnew);
   1113 	if ((hm = nat->nat_hm) != NULL)
   1114 		ipf_nat_hostmapdel(softc, &hm);
   1115 	KFREE(nat);
   1116 	nat = NULL;
   1117 done:
   1118 	if (nat != NULL && np != NULL)
   1119 		np->in_hits++;
   1120 	if (natsave != NULL)
   1121 		*natsave = nat;
   1122 	return nat;
   1123 }
   1124 
   1125 
   1126 /* ------------------------------------------------------------------------ */
   1127 /* Function:    ipf_nat6_finalise                                           */
   1128 /* Returns:     int - 0 == sucess, -1 == failure                            */
   1129 /* Parameters:  fin(I) - pointer to packet information                      */
   1130 /*              nat(I) - pointer to NAT entry                               */
   1131 /* Write Lock:  ipf_nat                                                     */
   1132 /*                                                                          */
   1133 /* This is the tail end of constructing a new NAT entry and is the same     */
   1134 /* for both IPv4 and IPv6.                                                  */
   1135 /* ------------------------------------------------------------------------ */
   1136 /*ARGSUSED*/
   1137 int
   1138 ipf_nat6_finalise(fr_info_t *fin, nat_t *nat)
   1139 {
   1140 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1141 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1142 	u_32_t sum1, sum2, sumd;
   1143 	frentry_t *fr;
   1144 
   1145 	switch (fin->fin_p)
   1146 	{
   1147 	case IPPROTO_ICMPV6 :
   1148 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1149 		sum1 += ntohs(nat->nat_oicmpid);
   1150 		sum2 = LONG_SUM6(&nat->nat_nsrc6);
   1151 		sum2 += ntohs(nat->nat_nicmpid);
   1152 		CALC_SUMD(sum1, sum2, sumd);
   1153 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   1154 
   1155 		sum1 = LONG_SUM6(&nat->nat_odst6);
   1156 		sum2 = LONG_SUM6(&nat->nat_ndst6);
   1157 		CALC_SUMD(sum1, sum2, sumd);
   1158 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   1159 		break;
   1160 
   1161 	case IPPROTO_TCP :
   1162 	case IPPROTO_UDP :
   1163 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1164 		sum1 += ntohs(nat->nat_osport);
   1165 		sum2 = LONG_SUM6(&nat->nat_nsrc6);
   1166 		sum2 += ntohs(nat->nat_nsport);
   1167 		CALC_SUMD(sum1, sum2, sumd);
   1168 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   1169 
   1170 		sum1 = LONG_SUM6(&nat->nat_odst6);
   1171 		sum1 += ntohs(nat->nat_odport);
   1172 		sum2 = LONG_SUM6(&nat->nat_ndst6);
   1173 		sum2 += ntohs(nat->nat_ndport);
   1174 		CALC_SUMD(sum1, sum2, sumd);
   1175 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   1176 		break;
   1177 
   1178 	default :
   1179 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1180 		sum2 = LONG_SUM6(&nat->nat_nsrc6);
   1181 		CALC_SUMD(sum1, sum2, sumd);
   1182 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   1183 
   1184 		sum1 = LONG_SUM6(&nat->nat_odst6);
   1185 		sum2 = LONG_SUM6(&nat->nat_ndst6);
   1186 		CALC_SUMD(sum1, sum2, sumd);
   1187 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   1188 		break;
   1189 	}
   1190 
   1191 	/*
   1192 	 * Compute the partial checksum, just in case.
   1193 	 * This is only ever placed into outbound packets so care needs
   1194 	 * to be taken over which pair of addresses are used.
   1195 	 */
   1196 	if (nat->nat_dir == NAT_OUTBOUND) {
   1197 		sum1 = LONG_SUM6(&nat->nat_nsrc6);
   1198 		sum1 += LONG_SUM6(&nat->nat_ndst6);
   1199 	} else {
   1200 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1201 		sum1 += LONG_SUM6(&nat->nat_odst6);
   1202 	}
   1203 	sum1 += nat->nat_pr[1];
   1204 	nat->nat_sumd[1] = (sum1 & 0xffff) + (sum1 >> 16);
   1205 
   1206 	if ((nat->nat_flags & SI_CLONE) == 0)
   1207 		nat->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, nat);
   1208 
   1209 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   1210 		nat->nat_mtu[0] = GETIFMTU_6(nat->nat_ifps[0]);
   1211 	}
   1212 
   1213 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   1214 		nat->nat_mtu[1] = GETIFMTU_6(nat->nat_ifps[1]);
   1215 	}
   1216 
   1217 	nat->nat_v[0] = 6;
   1218 	nat->nat_v[1] = 6;
   1219 
   1220 	if (ipf_nat6_insert(softc, softn, nat) == 0) {
   1221 		if (softn->ipf_nat_logging)
   1222 			ipf_nat_log(softc, softn, nat, NL_NEW);
   1223 		fr = nat->nat_fr;
   1224 		if (fr != NULL) {
   1225 			MUTEX_ENTER(&fr->fr_lock);
   1226 			fr->fr_ref++;
   1227 			MUTEX_EXIT(&fr->fr_lock);
   1228 		}
   1229 		return 0;
   1230 	}
   1231 
   1232 	NBUMPSIDE6D(fin->fin_out, ns_unfinalised);
   1233 	/*
   1234 	 * nat6_insert failed, so cleanup time...
   1235 	 */
   1236 	if (nat->nat_sync != NULL)
   1237 		ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
   1238 	return -1;
   1239 }
   1240 
   1241 
   1242 /* ------------------------------------------------------------------------ */
   1243 /* Function:    ipf_nat6_insert                                             */
   1244 /* Returns:     int - 0 == sucess, -1 == failure                            */
   1245 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1246 /*              softn(I) - pointer to NAT context structure                 */
   1247 /*              nat(I) - pointer to NAT structure                           */
   1248 /* Write Lock:  ipf_nat                                                     */
   1249 /*                                                                          */
   1250 /* Insert a NAT entry into the hash tables for searching and add it to the  */
   1251 /* list of active NAT entries.  Adjust global counters when complete.       */
   1252 /* ------------------------------------------------------------------------ */
   1253 static int
   1254 ipf_nat6_insert(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, nat_t *nat)
   1255 {
   1256 	u_int hv0, hv1;
   1257 	u_32_t sp, dp;
   1258 	ipnat_t *in;
   1259 
   1260 	/*
   1261 	 * Try and return an error as early as possible, so calculate the hash
   1262 	 * entry numbers first and then proceed.
   1263 	 */
   1264 	if ((nat->nat_flags & (SI_W_SPORT|SI_W_DPORT)) == 0) {
   1265 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1266 			sp = nat->nat_osport;
   1267 			dp = nat->nat_odport;
   1268 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   1269 			sp = 0;
   1270 			dp = nat->nat_oicmpid;
   1271 		} else {
   1272 			sp = 0;
   1273 			dp = 0;
   1274 		}
   1275 		hv0 = NAT_HASH_FN6(&nat->nat_osrc6, sp, 0xffffffff);
   1276 		hv0 = NAT_HASH_FN6(&nat->nat_odst6, hv0 + dp,
   1277 				   softn->ipf_nat_table_sz);
   1278 
   1279 		/*
   1280 		 * TRACE nat6_osrc6, nat6_osport, nat6_odst6,
   1281 		 * nat6_odport, hv0
   1282 		 */
   1283 
   1284 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1285 			sp = nat->nat_nsport;
   1286 			dp = nat->nat_ndport;
   1287 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   1288 			sp = 0;
   1289 			dp = nat->nat_nicmpid;
   1290 		} else {
   1291 			sp = 0;
   1292 			dp = 0;
   1293 		}
   1294 		hv1 = NAT_HASH_FN6(&nat->nat_nsrc6, sp, 0xffffffff);
   1295 		hv1 = NAT_HASH_FN6(&nat->nat_ndst6, hv1 + dp,
   1296 				   softn->ipf_nat_table_sz);
   1297 		/*
   1298 		 * TRACE nat6_nsrcaddr, nat6_nsport, nat6_ndstaddr,
   1299 		 * nat6_ndport, hv0
   1300 		 */
   1301 	} else {
   1302 		hv0 = NAT_HASH_FN6(&nat->nat_osrc6, 0, 0xffffffff);
   1303 		hv0 = NAT_HASH_FN6(&nat->nat_odst6, hv0,
   1304 				   softn->ipf_nat_table_sz);
   1305 		/* TRACE nat6_osrcip6, nat6_odstip6, hv0 */
   1306 
   1307 		hv1 = NAT_HASH_FN6(&nat->nat_nsrc6, 0, 0xffffffff);
   1308 		hv1 = NAT_HASH_FN6(&nat->nat_ndst6, hv1,
   1309 				   softn->ipf_nat_table_sz);
   1310 		/* TRACE nat6_nsrcip6, nat6_ndstip6, hv1 */
   1311 	}
   1312 
   1313 	if ((nat->nat_dir & NAT_OUTBOUND) == NAT_OUTBOUND) {
   1314 		nat->nat_hv[0] = hv0;
   1315 		nat->nat_hv[1] = hv1;
   1316 	} else {
   1317 		nat->nat_hv[0] = hv1;
   1318 		nat->nat_hv[1] = hv0;
   1319 	}
   1320 
   1321 	MUTEX_INIT(&nat->nat_lock, "nat entry lock");
   1322 
   1323 	in = nat->nat_ptr;
   1324 	nat->nat_ref = nat->nat_me ? 2 : 1;
   1325 
   1326 	nat->nat_ifnames[0][LIFNAMSIZ - 1] = '\0';
   1327 	nat->nat_ifps[0] = ipf_resolvenic(softc, nat->nat_ifnames[0],
   1328 					  nat->nat_v[0]);
   1329 
   1330 	if (nat->nat_ifnames[1][0] != '\0') {
   1331 		nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   1332 		nat->nat_ifps[1] = ipf_resolvenic(softc, nat->nat_ifnames[1],
   1333 						  nat->nat_v[1]);
   1334 	} else if (in->in_ifnames[1] != -1) {
   1335 		char *name;
   1336 
   1337 		name = in->in_names + in->in_ifnames[1];
   1338 		if (name[1] != '\0' && name[0] != '-' && name[0] != '*') {
   1339 			(void) strncpy(nat->nat_ifnames[1],
   1340 				       nat->nat_ifnames[0], LIFNAMSIZ);
   1341 			nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   1342 			nat->nat_ifps[1] = nat->nat_ifps[0];
   1343 		}
   1344 	}
   1345 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   1346 		nat->nat_mtu[0] = GETIFMTU_6(nat->nat_ifps[0]);
   1347 	}
   1348 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   1349 		nat->nat_mtu[1] = GETIFMTU_6(nat->nat_ifps[1]);
   1350 	}
   1351 
   1352 	return ipf_nat_hashtab_add(softc, softn, nat);
   1353 }
   1354 
   1355 
   1356 /* ------------------------------------------------------------------------ */
   1357 /* Function:    ipf_nat6_icmperrorlookup                                    */
   1358 /* Returns:     nat6_t* - point to matching NAT structure                    */
   1359 /* Parameters:  fin(I) - pointer to packet information                      */
   1360 /*              dir(I) - direction of packet (in/out)                       */
   1361 /*                                                                          */
   1362 /* Check if the ICMP error message is related to an existing TCP, UDP or    */
   1363 /* ICMP query nat entry.  It is assumed that the packet is already of the   */
   1364 /* the required length.                                                     */
   1365 /* ------------------------------------------------------------------------ */
   1366 nat_t *
   1367 ipf_nat6_icmperrorlookup(fr_info_t *fin, int dir)
   1368 {
   1369 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1370 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1371 	struct icmp6_hdr *orgicmp;
   1372 	int flags = 0, minlen;
   1373 	nat_stat_side_t *nside;
   1374 	tcphdr_t *tcp = NULL;
   1375 	u_short data[2];
   1376 	ip6_t *oip6;
   1377 	nat_t *nat;
   1378 	u_int p;
   1379 
   1380 	minlen = 40;
   1381 	nside = &softn->ipf_nat_stats.ns_side6[fin->fin_out];
   1382 	/*
   1383 	 * Does it at least have the return (basic) IP header ?
   1384 	 * Only a basic IP header (no options) should be with an ICMP error
   1385 	 * header.  Also, if it's not an error type, then return.
   1386 	 */
   1387 	if (!(fin->fin_flx & FI_ICMPERR)) {
   1388 		ATOMIC_INCL(nside->ns_icmp_basic);
   1389 		return NULL;
   1390 	}
   1391 
   1392 	/*
   1393 	 * Check packet size
   1394 	 */
   1395 	if (fin->fin_plen < ICMP6ERR_IPICMPHLEN) {
   1396 		ATOMIC_INCL(nside->ns_icmp_size);
   1397 		return NULL;
   1398 	}
   1399 	oip6 = (ip6_t *)((char *)fin->fin_dp + 8);
   1400 
   1401 	/*
   1402 	 * Is the buffer big enough for all of it ?  It's the size of the IP
   1403 	 * header claimed in the encapsulated part which is of concern.  It
   1404 	 * may be too big to be in this buffer but not so big that it's
   1405 	 * outside the ICMP packet, leading to TCP deref's causing problems.
   1406 	 * This is possible because we don't know how big oip_hl is when we
   1407 	 * do the pullup early in ipf_check() and thus can't gaurantee it is
   1408 	 * all here now.
   1409 	 */
   1410 #ifdef  ipf_nat6_KERNEL
   1411 	{
   1412 	mb_t *m;
   1413 
   1414 	m = fin->fin_m;
   1415 # if defined(MENTAT)
   1416 	if ((char *)oip6 + fin->fin_dlen - ICMPERR_ICMPHLEN >
   1417 	    (char *)m->b_wptr) {
   1418 		ATOMIC_INCL(nside->ns_icmp_mbuf);
   1419 		return NULL;
   1420 	}
   1421 # else
   1422 	if ((char *)oip6 + fin->fin_dlen - ICMPERR_ICMPHLEN >
   1423 	    (char *)fin->fin_ip + M_LEN(m)) {
   1424 		ATOMIC_INCL(nside->ns_icmp_mbuf);
   1425 		return NULL;
   1426 	}
   1427 # endif
   1428 	}
   1429 #endif
   1430 
   1431 	if (IP6_NEQ(&fin->fin_dst6, &oip6->ip6_src)) {
   1432 		ATOMIC_INCL(nside->ns_icmp_address);
   1433 		return NULL;
   1434 	}
   1435 
   1436 	p = oip6->ip6_nxt;
   1437 	if (p == IPPROTO_TCP)
   1438 		flags = IPN_TCP;
   1439 	else if (p == IPPROTO_UDP)
   1440 		flags = IPN_UDP;
   1441 	else if (p == IPPROTO_ICMPV6) {
   1442 		orgicmp = (struct icmp6_hdr *)(oip6 + 1);
   1443 
   1444 		/* see if this is related to an ICMP query */
   1445 		if (ipf_nat6_icmpquerytype(orgicmp->icmp6_type)) {
   1446 			data[0] = fin->fin_data[0];
   1447 			data[1] = fin->fin_data[1];
   1448 			fin->fin_data[0] = 0;
   1449 			fin->fin_data[1] = orgicmp->icmp6_id;
   1450 
   1451 			flags = IPN_ICMPERR|IPN_ICMPQUERY;
   1452 			/*
   1453 			 * NOTE : dir refers to the direction of the original
   1454 			 *        ip packet. By definition the icmp error
   1455 			 *        message flows in the opposite direction.
   1456 			 */
   1457 			if (dir == NAT_INBOUND)
   1458 				nat = ipf_nat6_inlookup(fin, flags, p,
   1459 						        &oip6->ip6_dst,
   1460 						        &oip6->ip6_src);
   1461 			else
   1462 				nat = ipf_nat6_outlookup(fin, flags, p,
   1463 							 &oip6->ip6_dst,
   1464 							 &oip6->ip6_src);
   1465 			fin->fin_data[0] = data[0];
   1466 			fin->fin_data[1] = data[1];
   1467 			return nat;
   1468 		}
   1469 	}
   1470 
   1471 	if (flags & IPN_TCPUDP) {
   1472 		minlen += 8;		/* + 64bits of data to get ports */
   1473 		/* TRACE (fin,minlen) */
   1474 		if (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen) {
   1475 			ATOMIC_INCL(nside->ns_icmp_short);
   1476 			return NULL;
   1477 		}
   1478 
   1479 		data[0] = fin->fin_data[0];
   1480 		data[1] = fin->fin_data[1];
   1481 		tcp = (tcphdr_t *)(oip6 + 1);
   1482 		fin->fin_data[0] = ntohs(tcp->th_dport);
   1483 		fin->fin_data[1] = ntohs(tcp->th_sport);
   1484 
   1485 		if (dir == NAT_INBOUND) {
   1486 			nat = ipf_nat6_inlookup(fin, flags, p, &oip6->ip6_dst,
   1487 						&oip6->ip6_src);
   1488 		} else {
   1489 			nat = ipf_nat6_outlookup(fin, flags, p, &oip6->ip6_dst,
   1490 						 &oip6->ip6_src);
   1491 		}
   1492 		fin->fin_data[0] = data[0];
   1493 		fin->fin_data[1] = data[1];
   1494 		return nat;
   1495 	}
   1496 	if (dir == NAT_INBOUND)
   1497 		nat = ipf_nat6_inlookup(fin, 0, p, &oip6->ip6_dst,
   1498 					&oip6->ip6_src);
   1499 	else
   1500 		nat = ipf_nat6_outlookup(fin, 0, p, &oip6->ip6_dst,
   1501 					 &oip6->ip6_src);
   1502 
   1503 	return nat;
   1504 }
   1505 
   1506 
   1507 /* result = ip1 - ip2 */
   1508 u_32_t
   1509 ipf_nat6_ip6subtract(i6addr_t *ip1, i6addr_t *ip2)
   1510 {
   1511 	i6addr_t l1, l2, d;
   1512 	u_short *s1, *s2, *ds;
   1513 	u_32_t r;
   1514 	int i;
   1515 
   1516 	l1 = *ip1;
   1517 	l2 = *ip2;
   1518 	s1 = (u_short *)&l1;
   1519 	s2 = (u_short *)&l2;
   1520 	ds = (u_short *)&d;
   1521 
   1522 	for (i = 7; i > 0; i--) {
   1523 		if (s1[i] > s2[i]) {
   1524 			ds[i] = s2[i] + 0x10000 - s1[i];
   1525 			s2[i - 1] += 0x10000;
   1526 		} else {
   1527 			ds[i] = s2[i] - s1[i];
   1528 		}
   1529 	}
   1530 	if (s2[0] > s1[0]) {
   1531 		ds[0] = s2[0] + 0x10000 - s1[0];
   1532 	} else {
   1533 		ds[0] = s2[0] - s1[0];
   1534 	}
   1535 
   1536 	for (i = 0, r = 0; i < 8; i++) {
   1537 		r += ds[i];
   1538 	}
   1539 
   1540 	return r;
   1541 }
   1542 
   1543 
   1544 /* ------------------------------------------------------------------------ */
   1545 /* Function:    ipf_nat6_icmperror                                          */
   1546 /* Returns:     nat6_t* - point to matching NAT structure                    */
   1547 /* Parameters:  fin(I)    - pointer to packet information                   */
   1548 /*              nflags(I) - NAT flags for this packet                       */
   1549 /*              dir(I)    - direction of packet (in/out)                    */
   1550 /*                                                                          */
   1551 /* Fix up an ICMP packet which is an error message for an existing NAT      */
   1552 /* session.  This will correct both packet header data and checksums.       */
   1553 /*                                                                          */
   1554 /* This should *ONLY* be used for incoming ICMP error packets to make sure  */
   1555 /* a NAT'd ICMP packet gets correctly recognised.                           */
   1556 /* ------------------------------------------------------------------------ */
   1557 nat_t *
   1558 ipf_nat6_icmperror(fr_info_t *fin, u_int *nflags, int dir)
   1559 {
   1560 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1561 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1562 	u_32_t sum1, sum2, sumd, sumd2;
   1563 	i6addr_t a1, a2, a3, a4;
   1564 	struct icmp6_hdr *icmp6;
   1565 	int flags, dlen, odst;
   1566 	u_short *csump;
   1567 	tcphdr_t *tcp;
   1568 	ip6_t *oip6;
   1569 	nat_t *nat;
   1570 	void *dp;
   1571 
   1572 	if ((fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   1573 		NBUMPSIDE6D(fin->fin_out, ns_icmp_short);
   1574 		return NULL;
   1575 	}
   1576 
   1577 	/*
   1578 	 * ipf_nat6_icmperrorlookup() will return NULL for `defective' packets.
   1579 	 */
   1580 	if ((fin->fin_v != 6) || !(nat = ipf_nat6_icmperrorlookup(fin, dir))) {
   1581 		NBUMPSIDE6D(fin->fin_out, ns_icmp_notfound);
   1582 		return NULL;
   1583 	}
   1584 
   1585 	tcp = NULL;
   1586 	csump = NULL;
   1587 	flags = 0;
   1588 	sumd2 = 0;
   1589 	*nflags = IPN_ICMPERR;
   1590 	icmp6 = fin->fin_dp;
   1591 	oip6 = (ip6_t *)((u_char *)icmp6 + sizeof(*icmp6));
   1592 	dp = (u_char *)oip6 + sizeof(*oip6);
   1593 	if (oip6->ip6_nxt == IPPROTO_TCP) {
   1594 		tcp = (tcphdr_t *)dp;
   1595 		csump = (u_short *)&tcp->th_sum;
   1596 		flags = IPN_TCP;
   1597 	} else if (oip6->ip6_nxt == IPPROTO_UDP) {
   1598 		udphdr_t *udp;
   1599 
   1600 		udp = (udphdr_t *)dp;
   1601 		tcp = (tcphdr_t *)dp;
   1602 		csump = (u_short *)&udp->uh_sum;
   1603 		flags = IPN_UDP;
   1604 	} else if (oip6->ip6_nxt == IPPROTO_ICMPV6)
   1605 		flags = IPN_ICMPQUERY;
   1606 	dlen = fin->fin_plen - ((char *)dp - (char *)fin->fin_ip);
   1607 
   1608 	/*
   1609 	 * Need to adjust ICMP header to include the real IP#'s and
   1610 	 * port #'s.  Only apply a checksum change relative to the
   1611 	 * IP address change as it will be modified again in ipf_nat6_checkout
   1612 	 * for both address and port.  Two checksum changes are
   1613 	 * necessary for the two header address changes.  Be careful
   1614 	 * to only modify the checksum once for the port # and twice
   1615 	 * for the IP#.
   1616 	 */
   1617 
   1618 	/*
   1619 	 * Step 1
   1620 	 * Fix the IP addresses in the offending IP packet. You also need
   1621 	 * to adjust the IP header checksum of that offending IP packet.
   1622 	 *
   1623 	 * Normally, you would expect that the ICMP checksum of the
   1624 	 * ICMP error message needs to be adjusted as well for the
   1625 	 * IP address change in oip.
   1626 	 * However, this is a NOP, because the ICMP checksum is
   1627 	 * calculated over the complete ICMP packet, which includes the
   1628 	 * changed oip IP addresses and oip6->ip6_sum. However, these
   1629 	 * two changes cancel each other out (if the delta for
   1630 	 * the IP address is x, then the delta for ip_sum is minus x),
   1631 	 * so no change in the icmp_cksum is necessary.
   1632 	 *
   1633 	 * Inbound ICMP
   1634 	 * ------------
   1635 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   1636 	 * - response to outgoing packet (a,b)=>(c,b) (OIP_SRC=c,OIP_DST=b)
   1637 	 * - OIP_SRC(c)=nat6_newsrcip,          OIP_DST(b)=nat6_newdstip
   1638 	 *=> OIP_SRC(c)=nat6_oldsrcip,          OIP_DST(b)=nat6_olddstip
   1639 	 *
   1640 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   1641 	 * - response to outgoing packet (c,a)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   1642 	 * - OIP_SRC(b)=nat6_olddstip,          OIP_DST(a)=nat6_oldsrcip
   1643 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1644 	 *
   1645 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   1646 	 * - response to outgoing packet (a,b)=>(c,d) (OIP_SRC=c,OIP_DST=d)
   1647 	 * - OIP_SRC(c)=nat6_newsrcip,          OIP_DST(d)=nat6_newdstip
   1648 	 *=> OIP_SRC(c)=nat6_oldsrcip,          OIP_DST(d)=nat6_olddstip
   1649 	 *
   1650 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   1651 	 * - response to outgoing packet (d,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   1652 	 * - OIP_SRC(b)=nat6_olddstip,          OIP_DST(a)=nat6_oldsrcip
   1653 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1654 	 *
   1655 	 * Outbound ICMP
   1656 	 * -------------
   1657 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   1658 	 * - response to incoming packet (b,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   1659 	 * - OIP_SRC(b)=nat6_olddstip,          OIP_DST(a)=nat6_oldsrcip
   1660 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1661 	 *
   1662 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   1663 	 * - response to incoming packet (a,b)=>(a,c) (OIP_SRC=a,OIP_DST=c)
   1664 	 * - OIP_SRC(a)=nat6_newsrcip,          OIP_DST(c)=nat6_newdstip
   1665 	 *=> OIP_SRC(a)=nat6_oldsrcip,          OIP_DST(c)=nat6_olddstip
   1666 	 *
   1667 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   1668 	 * - response to incoming packet (d,c)=>(b,a) (OIP_SRC=c,OIP_DST=d)
   1669 	 * - OIP_SRC(c)=nat6_olddstip,          OIP_DST(d)=nat6_oldsrcip
   1670 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1671 	 *
   1672 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   1673 	 * - response to incoming packet (a,b)=>(c,d) (OIP_SRC=b,OIP_DST=a)
   1674 	 * - OIP_SRC(b)=nat6_newsrcip,          OIP_DST(a)=nat6_newdstip
   1675 	 *=> OIP_SRC(a)=nat6_oldsrcip,          OIP_DST(c)=nat6_olddstip
   1676 	 */
   1677 
   1678 	if (((fin->fin_out == 0) && ((nat->nat_redir & NAT_MAP) != 0)) ||
   1679 	    ((fin->fin_out == 1) && ((nat->nat_redir & NAT_REDIRECT) != 0))) {
   1680 		a1 = nat->nat_osrc6;
   1681 		a4.in6 = oip6->ip6_src;
   1682 		a3 = nat->nat_odst6;
   1683 		a2.in6 = oip6->ip6_dst;
   1684 		oip6->ip6_src = a1.in6;
   1685 		oip6->ip6_dst = a3.in6;
   1686 		odst = 1;
   1687 	} else {
   1688 		a1 = nat->nat_ndst6;
   1689 		a2.in6 = oip6->ip6_dst;
   1690 		a3 = nat->nat_nsrc6;
   1691 		a4.in6 = oip6->ip6_src;
   1692 		oip6->ip6_dst = a3.in6;
   1693 		oip6->ip6_src = a1.in6;
   1694 		odst = 0;
   1695 	}
   1696 
   1697 	sumd = 0;
   1698 	if (IP6_NEQ(&a3, &a2) || IP6_NEQ(&a1, &a4)) {
   1699 		if (IP6_GT(&a3, &a2)) {
   1700 			sumd = ipf_nat6_ip6subtract(&a2, &a3);
   1701 			sumd--;
   1702 		} else {
   1703 			sumd = ipf_nat6_ip6subtract(&a2, &a3);
   1704 		}
   1705 		if (IP6_GT(&a1, &a4)) {
   1706 			sumd += ipf_nat6_ip6subtract(&a4, &a1);
   1707 			sumd--;
   1708 		} else {
   1709 			sumd += ipf_nat6_ip6subtract(&a4, &a1);
   1710 		}
   1711 		sumd = ~sumd;
   1712 	}
   1713 
   1714 	sumd2 = sumd;
   1715 	sum1 = 0;
   1716 	sum2 = 0;
   1717 
   1718 	/*
   1719 	 * Fix UDP pseudo header checksum to compensate for the
   1720 	 * IP address change.
   1721 	 */
   1722 	if (((flags & IPN_TCPUDP) != 0) && (dlen >= 4)) {
   1723 		u_32_t sum3, sum4;
   1724 		/*
   1725 		 * Step 2 :
   1726 		 * For offending TCP/UDP IP packets, translate the ports as
   1727 		 * well, based on the NAT specification. Of course such
   1728 		 * a change may be reflected in the ICMP checksum as well.
   1729 		 *
   1730 		 * Since the port fields are part of the TCP/UDP checksum
   1731 		 * of the offending IP packet, you need to adjust that checksum
   1732 		 * as well... except that the change in the port numbers should
   1733 		 * be offset by the checksum change.  However, the TCP/UDP
   1734 		 * checksum will also need to change if there has been an
   1735 		 * IP address change.
   1736 		 */
   1737 		if (odst == 1) {
   1738 			sum1 = ntohs(nat->nat_osport);
   1739 			sum4 = ntohs(tcp->th_sport);
   1740 			sum3 = ntohs(nat->nat_odport);
   1741 			sum2 = ntohs(tcp->th_dport);
   1742 
   1743 			tcp->th_sport = htons(sum1);
   1744 			tcp->th_dport = htons(sum3);
   1745 		} else {
   1746 			sum1 = ntohs(nat->nat_ndport);
   1747 			sum2 = ntohs(tcp->th_dport);
   1748 			sum3 = ntohs(nat->nat_nsport);
   1749 			sum4 = ntohs(tcp->th_sport);
   1750 
   1751 			tcp->th_dport = htons(sum3);
   1752 			tcp->th_sport = htons(sum1);
   1753 		}
   1754 		sumd += sum1 - sum4;
   1755 		sumd += sum3 - sum2;
   1756 
   1757 		if (sumd != 0 || sumd2 != 0) {
   1758 			/*
   1759 			 * At this point, sumd is the delta to apply to the
   1760 			 * TCP/UDP header, given the changes in both the IP
   1761 			 * address and the ports and sumd2 is the delta to
   1762 			 * apply to the ICMP header, given the IP address
   1763 			 * change delta that may need to be applied to the
   1764 			 * TCP/UDP checksum instead.
   1765 			 *
   1766 			 * If we will both the IP and TCP/UDP checksums
   1767 			 * then the ICMP checksum changes by the address
   1768 			 * delta applied to the TCP/UDP checksum.  If we
   1769 			 * do not change the TCP/UDP checksum them we
   1770 			 * apply the delta in ports to the ICMP checksum.
   1771 			 */
   1772 			if (oip6->ip6_nxt == IPPROTO_UDP) {
   1773 				if ((dlen >= 8) && (*csump != 0)) {
   1774 					ipf_fix_datacksum(csump, sumd);
   1775 				} else {
   1776 					sumd2 = sum4 - sum1;
   1777 					if (sum1 > sum4)
   1778 						sumd2--;
   1779 					sumd2 += sum2 - sum3;
   1780 					if (sum3 > sum2)
   1781 						sumd2--;
   1782 				}
   1783 			} else if (oip6->ip6_nxt == IPPROTO_TCP) {
   1784 				if (dlen >= 18) {
   1785 					ipf_fix_datacksum(csump, sumd);
   1786 				} else {
   1787 					sumd2 = sum4 - sum1;
   1788 					if (sum1 > sum4)
   1789 						sumd2--;
   1790 					sumd2 += sum2 - sum3;
   1791 					if (sum3 > sum2)
   1792 						sumd2--;
   1793 				}
   1794 			}
   1795 			if (sumd2 != 0) {
   1796 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   1797 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   1798 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   1799 				ipf_fix_incksum(0, &icmp6->icmp6_cksum,
   1800 						sumd2, 0);
   1801 			}
   1802 		}
   1803 	} else if (((flags & IPN_ICMPQUERY) != 0) && (dlen >= 8)) {
   1804 		struct icmp6_hdr *orgicmp;
   1805 
   1806 		/*
   1807 		 * XXX - what if this is bogus hl and we go off the end ?
   1808 		 * In this case, ipf_nat6_icmperrorlookup() will have
   1809 		 * returned NULL.
   1810 		 */
   1811 		orgicmp = (struct icmp6_hdr *)dp;
   1812 
   1813 		if (odst == 1) {
   1814 			if (orgicmp->icmp6_id != nat->nat_osport) {
   1815 
   1816 				/*
   1817 				 * Fix ICMP checksum (of the offening ICMP
   1818 				 * query packet) to compensate the change
   1819 				 * in the ICMP id of the offending ICMP
   1820 				 * packet.
   1821 				 *
   1822 				 * Since you modify orgicmp->icmp6_id with
   1823 				 * a delta (say x) and you compensate that
   1824 				 * in origicmp->icmp6_cksum with a delta
   1825 				 * minus x, you don't have to adjust the
   1826 				 * overall icmp->icmp6_cksum
   1827 				 */
   1828 				sum1 = ntohs(orgicmp->icmp6_id);
   1829 				sum2 = ntohs(nat->nat_osport);
   1830 				CALC_SUMD(sum1, sum2, sumd);
   1831 				orgicmp->icmp6_id = nat->nat_oicmpid;
   1832 				ipf_fix_datacksum(&orgicmp->icmp6_cksum, sumd);
   1833 			}
   1834 		} /* nat6_dir == NAT_INBOUND is impossible for icmp queries */
   1835 	}
   1836 	return nat;
   1837 }
   1838 
   1839 
   1840 /*
   1841  *       MAP-IN    MAP-OUT   RDR-IN   RDR-OUT
   1842  * osrc    X       == src    == src      X
   1843  * odst    X       == dst    == dst      X
   1844  * nsrc  == dst      X         X      == dst
   1845  * ndst  == src      X         X      == src
   1846  * MAP = NAT_OUTBOUND, RDR = NAT_INBOUND
   1847  */
   1848 /*
   1849  * NB: these lookups don't lock access to the list, it assumed that it has
   1850  * already been done!
   1851  */
   1852 /* ------------------------------------------------------------------------ */
   1853 /* Function:    ipf_nat6_inlookup                                           */
   1854 /* Returns:     nat6_t*   - NULL == no match,                               */
   1855 /*                          else pointer to matching NAT entry              */
   1856 /* Parameters:  fin(I)    - pointer to packet information                   */
   1857 /*              flags(I)  - NAT flags for this packet                       */
   1858 /*              p(I)      - protocol for this packet                        */
   1859 /*              src(I)    - source IP address                               */
   1860 /*              mapdst(I) - destination IP address                          */
   1861 /*                                                                          */
   1862 /* Lookup a nat entry based on the mapped destination ip address/port and   */
   1863 /* real source address/port.  We use this lookup when receiving a packet,   */
   1864 /* we're looking for a table entry, based on the destination address.       */
   1865 /*                                                                          */
   1866 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   1867 /*                                                                          */
   1868 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   1869 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   1870 /*                                                                          */
   1871 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   1872 /*            the packet is of said protocol                                */
   1873 /* ------------------------------------------------------------------------ */
   1874 nat_t *
   1875 ipf_nat6_inlookup(fr_info_t *fin, u_int flags, u_int p, struct in6_addr *src,
   1876     struct in6_addr *mapdst)
   1877 {
   1878 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1879 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1880 	u_short sport, dport;
   1881 	nat_t *nat;
   1882 	int nflags;
   1883 	i6addr_t dst;
   1884 	void *ifp;
   1885 	u_int hv;
   1886 
   1887 	ifp = fin->fin_ifp;
   1888 	sport = 0;
   1889 	dport = 0;
   1890 	dst.in6 = *mapdst;
   1891 
   1892 	switch (p)
   1893 	{
   1894 	case IPPROTO_TCP :
   1895 	case IPPROTO_UDP :
   1896 		sport = htons(fin->fin_data[0]);
   1897 		dport = htons(fin->fin_data[1]);
   1898 		break;
   1899 	case IPPROTO_ICMPV6 :
   1900 		if (flags & IPN_ICMPERR)
   1901 			sport = fin->fin_data[1];
   1902 		else
   1903 			dport = fin->fin_data[1];
   1904 		break;
   1905 	default :
   1906 		break;
   1907 	}
   1908 
   1909 
   1910 	if ((flags & SI_WILDP) != 0)
   1911 		goto find_in_wild_ports;
   1912 
   1913 	hv = NAT_HASH_FN6(&dst, dport, 0xffffffff);
   1914 	hv = NAT_HASH_FN6(src, hv + sport, softn->ipf_nat_table_sz);
   1915 	nat = softn->ipf_nat_table[1][hv];
   1916 	/* TRACE dst, dport, src, sport, hv, nat */
   1917 
   1918 	for (; nat; nat = nat->nat_hnext[1]) {
   1919 		if (nat->nat_ifps[0] != NULL) {
   1920 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   1921 				continue;
   1922 		}
   1923 
   1924 		if (nat->nat_pr[0] != p)
   1925 			continue;
   1926 
   1927 		switch (nat->nat_dir)
   1928 		{
   1929 		case NAT_INBOUND :
   1930 			if (nat->nat_v[0] != 6)
   1931 				continue;
   1932 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   1933 			    IP6_NEQ(&nat->nat_odst6, &dst))
   1934 				continue;
   1935 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1936 				if (nat->nat_osport != sport)
   1937 					continue;
   1938 				if (nat->nat_odport != dport)
   1939 					continue;
   1940 
   1941 			} else if (p == IPPROTO_ICMPV6) {
   1942 				if (nat->nat_osport != dport) {
   1943 					continue;
   1944 				}
   1945 			}
   1946 			break;
   1947 		case NAT_OUTBOUND :
   1948 			if (nat->nat_v[1] != 6)
   1949 				continue;
   1950 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   1951 			    IP6_NEQ(&nat->nat_nsrc6, &dst))
   1952 				continue;
   1953 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1954 				if (nat->nat_ndport != sport)
   1955 					continue;
   1956 				if (nat->nat_nsport != dport)
   1957 					continue;
   1958 
   1959 			} else if (p == IPPROTO_ICMPV6) {
   1960 				if (nat->nat_osport != dport) {
   1961 					continue;
   1962 				}
   1963 			}
   1964 			break;
   1965 		}
   1966 
   1967 
   1968 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1969 #ifdef IPF_V6_PROXIES
   1970 			if ((nat->nat_ptr != NULL) && (nat->nat_aps != NULL))
   1971 				if (appr_match(fin, nat) != 0)
   1972 					continue;
   1973 #endif
   1974 		}
   1975 		if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   1976 			nat->nat_ifps[0] = ifp;
   1977 			nat->nat_mtu[0] = GETIFMTU_6(ifp);
   1978 		}
   1979 		return nat;
   1980 	}
   1981 
   1982 	/*
   1983 	 * So if we didn't find it but there are wildcard members in the hash
   1984 	 * table, go back and look for them.  We do this search and update here
   1985 	 * because it is modifying the NAT table and we want to do this only
   1986 	 * for the first packet that matches.  The exception, of course, is
   1987 	 * for "dummy" (FI_IGNORE) lookups.
   1988 	 */
   1989 find_in_wild_ports:
   1990 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   1991 		NBUMPSIDE6DX(0, ns_lookup_miss, ns_lookup_miss_1);
   1992 		return NULL;
   1993 	}
   1994 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   1995 		NBUMPSIDE6D(0, ns_lookup_nowild);
   1996 		return NULL;
   1997 	}
   1998 
   1999 	RWLOCK_EXIT(&softc->ipf_nat);
   2000 
   2001 	hv = NAT_HASH_FN6(&dst, 0, 0xffffffff);
   2002 	hv = NAT_HASH_FN6(src, hv, softn->ipf_nat_table_sz);
   2003 	WRITE_ENTER(&softc->ipf_nat);
   2004 
   2005 	nat = softn->ipf_nat_table[1][hv];
   2006 	/* TRACE dst, src, hv, nat */
   2007 	for (; nat; nat = nat->nat_hnext[1]) {
   2008 		if (nat->nat_ifps[0] != NULL) {
   2009 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   2010 				continue;
   2011 		}
   2012 
   2013 		if (nat->nat_pr[0] != fin->fin_p)
   2014 			continue;
   2015 
   2016 		switch (nat->nat_dir)
   2017 		{
   2018 		case NAT_INBOUND :
   2019 			if (nat->nat_v[0] != 6)
   2020 				continue;
   2021 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   2022 			    IP6_NEQ(&nat->nat_odst6, &dst))
   2023 				continue;
   2024 			break;
   2025 		case NAT_OUTBOUND :
   2026 			if (nat->nat_v[1] != 6)
   2027 				continue;
   2028 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   2029 			    IP6_NEQ(&nat->nat_nsrc6, &dst))
   2030 				continue;
   2031 			break;
   2032 		}
   2033 
   2034 		nflags = nat->nat_flags;
   2035 		if (!(nflags & (NAT_TCPUDP|SI_WILDP)))
   2036 			continue;
   2037 
   2038 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nflags,
   2039 				   NAT_INBOUND) == 1) {
   2040 			if ((fin->fin_flx & FI_IGNORE) != 0)
   2041 				break;
   2042 			if ((nflags & SI_CLONE) != 0) {
   2043 				nat = ipf_nat_clone(fin, nat);
   2044 				if (nat == NULL)
   2045 					break;
   2046 			} else {
   2047 				MUTEX_ENTER(&softn->ipf_nat_new);
   2048 				softn->ipf_nat_stats.ns_wilds--;
   2049 				MUTEX_EXIT(&softn->ipf_nat_new);
   2050 			}
   2051 
   2052 			if (nat->nat_dir == NAT_INBOUND) {
   2053 				if (nat->nat_osport == 0) {
   2054 					nat->nat_osport = sport;
   2055 					nat->nat_nsport = sport;
   2056 				}
   2057 				if (nat->nat_odport == 0) {
   2058 					nat->nat_odport = dport;
   2059 					nat->nat_ndport = dport;
   2060 				}
   2061 			} else {
   2062 				if (nat->nat_osport == 0) {
   2063 					nat->nat_osport = dport;
   2064 					nat->nat_nsport = dport;
   2065 				}
   2066 				if (nat->nat_odport == 0) {
   2067 					nat->nat_odport = sport;
   2068 					nat->nat_ndport = sport;
   2069 				}
   2070 			}
   2071 			if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   2072 				nat->nat_ifps[0] = ifp;
   2073 				nat->nat_mtu[0] = GETIFMTU_6(ifp);
   2074 			}
   2075 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   2076 			ipf_nat6_tabmove(softn, nat);
   2077 			break;
   2078 		}
   2079 	}
   2080 
   2081 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   2082 
   2083 	if (nat == NULL) {
   2084 		NBUMPSIDE6DX(0, ns_lookup_miss, ns_lookup_miss_2);
   2085 	}
   2086 	return nat;
   2087 }
   2088 
   2089 
   2090 /* ------------------------------------------------------------------------ */
   2091 /* Function:    ipf_nat6_tabmove                                            */
   2092 /* Returns:     Nil                                                         */
   2093 /* Parameters:  nat(I) - pointer to NAT structure                           */
   2094 /* Write Lock:  ipf_nat                                                     */
   2095 /*                                                                          */
   2096 /* This function is only called for TCP/UDP NAT table entries where the     */
   2097 /* original was placed in the table without hashing on the ports and we now */
   2098 /* want to include hashing on port numbers.                                 */
   2099 /* ------------------------------------------------------------------------ */
   2100 static void
   2101 ipf_nat6_tabmove(ipf_nat_softc_t *softn, nat_t *nat)
   2102 {
   2103 	u_int rhv0, rhv1, hv0, hv1;
   2104 	nat_t **natp;
   2105 
   2106 	if (nat->nat_flags & SI_CLONE)
   2107 		return;
   2108 
   2109 	/*
   2110 	 * Remove the NAT entry from the old location
   2111 	 */
   2112 	if (nat->nat_hnext[0])
   2113 		nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
   2114 	*nat->nat_phnext[0] = nat->nat_hnext[0];
   2115 	softn->ipf_nat_stats.ns_side[0].ns_bucketlen[nat->nat_hv[0]]--;
   2116 
   2117 	if (nat->nat_hnext[1])
   2118 		nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
   2119 	*nat->nat_phnext[1] = nat->nat_hnext[1];
   2120 	softn->ipf_nat_stats.ns_side[1].ns_bucketlen[nat->nat_hv[1]]--;
   2121 
   2122 	/*
   2123 	 * Add into the NAT table in the new position
   2124 	 */
   2125 	rhv0 = NAT_HASH_FN6(&nat->nat_osrc6, nat->nat_osport, 0xffffffff);
   2126 	rhv0 = NAT_HASH_FN6(&nat->nat_odst6, rhv0 + nat->nat_odport,
   2127 			    softn->ipf_nat_table_sz);
   2128 	rhv1 = NAT_HASH_FN6(&nat->nat_nsrc6, nat->nat_nsport, 0xffffffff);
   2129 	rhv1 = NAT_HASH_FN6(&nat->nat_ndst6, rhv1 + nat->nat_ndport,
   2130 			    softn->ipf_nat_table_sz);
   2131 
   2132 	if ((nat->nat_dir & NAT_OUTBOUND) == NAT_OUTBOUND) {
   2133 		nat->nat_hv[0] = rhv0;
   2134 		nat->nat_hv[1] = rhv1;
   2135 	} else {
   2136 		nat->nat_hv[0] = rhv1;
   2137 		nat->nat_hv[1] = rhv0;
   2138 	}
   2139 
   2140 	hv0 = nat->nat_hv[0] % softn->ipf_nat_table_sz;
   2141         hv1 = nat->nat_hv[1] % softn->ipf_nat_table_sz;
   2142 
   2143 	/* TRACE nat_osrc6, nat_osport, nat_odst6, nat_odport, hv0 */
   2144 	/* TRACE nat_nsrc6, nat_nsport, nat_ndst6, nat_ndport, hv1 */
   2145 
   2146 	natp = &softn->ipf_nat_table[0][hv0];
   2147 	if (*natp)
   2148 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   2149 	nat->nat_phnext[0] = natp;
   2150 	nat->nat_hnext[0] = *natp;
   2151 	*natp = nat;
   2152 	softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0]++;
   2153 
   2154 	natp = &softn->ipf_nat_table[1][hv1];
   2155 	if (*natp)
   2156 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   2157 	nat->nat_phnext[1] = natp;
   2158 	nat->nat_hnext[1] = *natp;
   2159 	*natp = nat;
   2160 	softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1]++;
   2161 }
   2162 
   2163 
   2164 /* ------------------------------------------------------------------------ */
   2165 /* Function:    ipf_nat6_outlookup                                          */
   2166 /* Returns:     nat6_t*  - NULL == no match,                                */
   2167 /*                         else pointer to matching NAT entry               */
   2168 /* Parameters:  fin(I)   - pointer to packet information                    */
   2169 /*              flags(I) - NAT flags for this packet                        */
   2170 /*              p(I)     - protocol for this packet                         */
   2171 /*              src(I)   - source IP address                                */
   2172 /*              dst(I)   - destination IP address                           */
   2173 /*              rw(I)    - 1 == write lock on  held, 0 == read lock.        */
   2174 /*                                                                          */
   2175 /* Lookup a nat entry based on the source 'real' ip address/port and        */
   2176 /* destination address/port.  We use this lookup when sending a packet out, */
   2177 /* we're looking for a table entry, based on the source address.            */
   2178 /*                                                                          */
   2179 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   2180 /*                                                                          */
   2181 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   2182 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   2183 /*                                                                          */
   2184 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   2185 /*            the packet is of said protocol                                */
   2186 /* ------------------------------------------------------------------------ */
   2187 nat_t *
   2188 ipf_nat6_outlookup(fr_info_t *fin, u_int flags, u_int p, struct in6_addr *src,
   2189     struct in6_addr *dst)
   2190 {
   2191 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2192 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2193 	u_short sport, dport;
   2194 	nat_t *nat;
   2195 	void *ifp;
   2196 	u_int hv;
   2197 
   2198 	ifp = fin->fin_ifp;
   2199 	sport = 0;
   2200 	dport = 0;
   2201 
   2202 	switch (p)
   2203 	{
   2204 	case IPPROTO_TCP :
   2205 	case IPPROTO_UDP :
   2206 		sport = htons(fin->fin_data[0]);
   2207 		dport = htons(fin->fin_data[1]);
   2208 		break;
   2209 	case IPPROTO_ICMPV6 :
   2210 		if (flags & IPN_ICMPERR)
   2211 			sport = fin->fin_data[1];
   2212 		else
   2213 			dport = fin->fin_data[1];
   2214 		break;
   2215 	default :
   2216 		break;
   2217 	}
   2218 
   2219 	if ((flags & SI_WILDP) != 0)
   2220 		goto find_out_wild_ports;
   2221 
   2222 	hv = NAT_HASH_FN6(src, sport, 0xffffffff);
   2223 	hv = NAT_HASH_FN6(dst, hv + dport, softn->ipf_nat_table_sz);
   2224 	nat = softn->ipf_nat_table[0][hv];
   2225 
   2226 	/* TRACE src, sport, dst, dport, hv, nat */
   2227 
   2228 	for (; nat; nat = nat->nat_hnext[0]) {
   2229 		if (nat->nat_ifps[1] != NULL) {
   2230 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   2231 				continue;
   2232 		}
   2233 
   2234 		if (nat->nat_pr[1] != p)
   2235 			continue;
   2236 
   2237 		switch (nat->nat_dir)
   2238 		{
   2239 		case NAT_INBOUND :
   2240 			if (nat->nat_v[1] != 6)
   2241 				continue;
   2242 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   2243 			    IP6_NEQ(&nat->nat_nsrc6, dst))
   2244 				continue;
   2245 
   2246 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   2247 				if (nat->nat_ndport != sport)
   2248 					continue;
   2249 				if (nat->nat_nsport != dport)
   2250 					continue;
   2251 
   2252 			} else if (p == IPPROTO_ICMPV6) {
   2253 				if (nat->nat_osport != dport) {
   2254 					continue;
   2255 				}
   2256 			}
   2257 			break;
   2258 		case NAT_OUTBOUND :
   2259 			if (nat->nat_v[0] != 6)
   2260 				continue;
   2261 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   2262 			    IP6_NEQ(&nat->nat_odst6, dst))
   2263 				continue;
   2264 
   2265 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   2266 				if (nat->nat_odport != dport)
   2267 					continue;
   2268 				if (nat->nat_osport != sport)
   2269 					continue;
   2270 
   2271 			} else if (p == IPPROTO_ICMPV6) {
   2272 				if (nat->nat_osport != dport) {
   2273 					continue;
   2274 				}
   2275 			}
   2276 			break;
   2277 		}
   2278 
   2279 #ifdef IPF_V6_PROXIES
   2280 		if ((nat->nat_ptr != NULL) && (nat->nat_aps != NULL))
   2281 			if (appr_match(fin, nat) != 0)
   2282 				continue;
   2283 #endif
   2284 
   2285 		if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   2286 			nat->nat_ifps[1] = ifp;
   2287 			nat->nat_mtu[1] = GETIFMTU_6(ifp);
   2288 		}
   2289 		return nat;
   2290 	}
   2291 
   2292 	/*
   2293 	 * So if we didn't find it but there are wildcard members in the hash
   2294 	 * table, go back and look for them.  We do this search and update here
   2295 	 * because it is modifying the NAT table and we want to do this only
   2296 	 * for the first packet that matches.  The exception, of course, is
   2297 	 * for "dummy" (FI_IGNORE) lookups.
   2298 	 */
   2299 find_out_wild_ports:
   2300 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   2301 		NBUMPSIDE6DX(1, ns_lookup_miss, ns_lookup_miss_3);
   2302 		return NULL;
   2303 	}
   2304 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   2305 		NBUMPSIDE6D(1, ns_lookup_nowild);
   2306 		return NULL;
   2307 	}
   2308 
   2309 	RWLOCK_EXIT(&softc->ipf_nat);
   2310 
   2311 	hv = NAT_HASH_FN6(src, 0, 0xffffffff);
   2312 	hv = NAT_HASH_FN6(dst, hv, softn->ipf_nat_table_sz);
   2313 
   2314 	WRITE_ENTER(&softc->ipf_nat);
   2315 
   2316 	nat = softn->ipf_nat_table[0][hv];
   2317 	for (; nat; nat = nat->nat_hnext[0]) {
   2318 		if (nat->nat_ifps[1] != NULL) {
   2319 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   2320 				continue;
   2321 		}
   2322 
   2323 		if (nat->nat_pr[1] != fin->fin_p)
   2324 			continue;
   2325 
   2326 		switch (nat->nat_dir)
   2327 		{
   2328 		case NAT_INBOUND :
   2329 			if (nat->nat_v[1] != 6)
   2330 				continue;
   2331 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   2332 			    IP6_NEQ(&nat->nat_nsrc6, dst))
   2333 				continue;
   2334 			break;
   2335 		case NAT_OUTBOUND :
   2336 			if (nat->nat_v[0] != 6)
   2337 			continue;
   2338 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   2339 			    IP6_NEQ(&nat->nat_odst6, dst))
   2340 				continue;
   2341 			break;
   2342 		}
   2343 
   2344 		if (!(nat->nat_flags & (NAT_TCPUDP|SI_WILDP)))
   2345 			continue;
   2346 
   2347 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nat->nat_flags,
   2348 				   NAT_OUTBOUND) == 1) {
   2349 			if ((fin->fin_flx & FI_IGNORE) != 0)
   2350 				break;
   2351 			if ((nat->nat_flags & SI_CLONE) != 0) {
   2352 				nat = ipf_nat_clone(fin, nat);
   2353 				if (nat == NULL)
   2354 					break;
   2355 			} else {
   2356 				MUTEX_ENTER(&softn->ipf_nat_new);
   2357 				softn->ipf_nat_stats.ns_wilds--;
   2358 				MUTEX_EXIT(&softn->ipf_nat_new);
   2359 			}
   2360 
   2361 			if (nat->nat_dir == NAT_OUTBOUND) {
   2362 				if (nat->nat_osport == 0) {
   2363 					nat->nat_osport = sport;
   2364 					nat->nat_nsport = sport;
   2365 				}
   2366 				if (nat->nat_odport == 0) {
   2367 					nat->nat_odport = dport;
   2368 					nat->nat_ndport = dport;
   2369 				}
   2370 			} else {
   2371 				if (nat->nat_osport == 0) {
   2372 					nat->nat_osport = dport;
   2373 					nat->nat_nsport = dport;
   2374 				}
   2375 				if (nat->nat_odport == 0) {
   2376 					nat->nat_odport = sport;
   2377 					nat->nat_ndport = sport;
   2378 				}
   2379 			}
   2380 			if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   2381 				nat->nat_ifps[1] = ifp;
   2382 				nat->nat_mtu[1] = GETIFMTU_6(ifp);
   2383 			}
   2384 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   2385 			ipf_nat6_tabmove(softn, nat);
   2386 			break;
   2387 		}
   2388 	}
   2389 
   2390 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   2391 
   2392 	if (nat == NULL) {
   2393 		NBUMPSIDE6DX(1, ns_lookup_miss, ns_lookup_miss_4);
   2394 	}
   2395 	return nat;
   2396 }
   2397 
   2398 
   2399 /* ------------------------------------------------------------------------ */
   2400 /* Function:    ipf_nat6_lookupredir                                        */
   2401 /* Returns:     nat6_t* - NULL == no match,                                 */
   2402 /*                       else pointer to matching NAT entry                 */
   2403 /* Parameters:  np(I) - pointer to description of packet to find NAT table  */
   2404 /*                      entry for.                                          */
   2405 /*                                                                          */
   2406 /* Lookup the NAT tables to search for a matching redirect                  */
   2407 /* The contents of natlookup_t should imitate those found in a packet that  */
   2408 /* would be translated - ie a packet coming in for RDR or going out for MAP.*/
   2409 /* We can do the lookup in one of two ways, imitating an inbound or         */
   2410 /* outbound  packet.  By default we assume outbound, unless IPN_IN is set.  */
   2411 /* For IN, the fields are set as follows:                                   */
   2412 /*     nl_real* = source information                                        */
   2413 /*     nl_out* = destination information (translated)                       */
   2414 /* For an out packet, the fields are set like this:                         */
   2415 /*     nl_in* = source information (untranslated)                           */
   2416 /*     nl_out* = destination information (translated)                       */
   2417 /* ------------------------------------------------------------------------ */
   2418 nat_t *
   2419 ipf_nat6_lookupredir(natlookup_t *np)
   2420 {
   2421 	fr_info_t fi;
   2422 	nat_t *nat;
   2423 
   2424 	bzero((char *)&fi, sizeof(fi));
   2425 	if (np->nl_flags & IPN_IN) {
   2426 		fi.fin_data[0] = ntohs(np->nl_realport);
   2427 		fi.fin_data[1] = ntohs(np->nl_outport);
   2428 	} else {
   2429 		fi.fin_data[0] = ntohs(np->nl_inport);
   2430 		fi.fin_data[1] = ntohs(np->nl_outport);
   2431 	}
   2432 	if (np->nl_flags & IPN_TCP)
   2433 		fi.fin_p = IPPROTO_TCP;
   2434 	else if (np->nl_flags & IPN_UDP)
   2435 		fi.fin_p = IPPROTO_UDP;
   2436 	else if (np->nl_flags & (IPN_ICMPERR|IPN_ICMPQUERY))
   2437 		fi.fin_p = IPPROTO_ICMPV6;
   2438 
   2439 	/*
   2440 	 * We can do two sorts of lookups:
   2441 	 * - IPN_IN: we have the `real' and `out' address, look for `in'.
   2442 	 * - default: we have the `in' and `out' address, look for `real'.
   2443 	 */
   2444 	if (np->nl_flags & IPN_IN) {
   2445 		if ((nat = ipf_nat6_inlookup(&fi, np->nl_flags, fi.fin_p,
   2446 					     &np->nl_realip6,
   2447 					     &np->nl_outip6))) {
   2448 			np->nl_inip6 = nat->nat_odst6.in6;
   2449 			np->nl_inport = nat->nat_odport;
   2450 		}
   2451 	} else {
   2452 		/*
   2453 		 * If nl_inip is non null, this is a lookup based on the real
   2454 		 * ip address. Else, we use the fake.
   2455 		 */
   2456 		if ((nat = ipf_nat6_outlookup(&fi, np->nl_flags, fi.fin_p,
   2457 					      &np->nl_inip6, &np->nl_outip6))) {
   2458 
   2459 			if ((np->nl_flags & IPN_FINDFORWARD) != 0) {
   2460 				fr_info_t fin;
   2461 				bzero((char *)&fin, sizeof(fin));
   2462 				fin.fin_p = nat->nat_pr[0];
   2463 				fin.fin_data[0] = ntohs(nat->nat_ndport);
   2464 				fin.fin_data[1] = ntohs(nat->nat_nsport);
   2465 				if (ipf_nat6_inlookup(&fin, np->nl_flags,
   2466 						     fin.fin_p,
   2467 						     &nat->nat_ndst6.in6,
   2468 						     &nat->nat_nsrc6.in6) !=
   2469 				    NULL) {
   2470 					np->nl_flags &= ~IPN_FINDFORWARD;
   2471 				}
   2472 			}
   2473 
   2474 			np->nl_realip6 = nat->nat_ndst6.in6;
   2475 			np->nl_realport = nat->nat_ndport;
   2476 		}
   2477  	}
   2478 
   2479 	return nat;
   2480 }
   2481 
   2482 
   2483 /* ------------------------------------------------------------------------ */
   2484 /* Function:    ipf_nat6_match                                              */
   2485 /* Returns:     int - 0 == no match, 1 == match                             */
   2486 /* Parameters:  fin(I)   - pointer to packet information                    */
   2487 /*              np(I)    - pointer to NAT rule                              */
   2488 /*                                                                          */
   2489 /* Pull the matching of a packet against a NAT rule out of that complex     */
   2490 /* loop inside ipf_nat6_checkin() and lay it out properly in its own        */
   2491 /* function.                                                                */
   2492 /* ------------------------------------------------------------------------ */
   2493 static int
   2494 ipf_nat6_match(fr_info_t *fin, ipnat_t *np)
   2495 {
   2496 	frtuc_t *ft;
   2497 	int match;
   2498 
   2499 	match = 0;
   2500 	switch (np->in_osrcatype)
   2501 	{
   2502 	case FRI_NORMAL :
   2503 		match = IP6_MASKNEQ(&fin->fin_src6, &np->in_osrcmsk6,
   2504 				    &np->in_osrcip6);
   2505 		break;
   2506 	case FRI_LOOKUP :
   2507 		match = (*np->in_osrcfunc)(fin->fin_main_soft, np->in_osrcptr,
   2508 					   6, &fin->fin_src6, fin->fin_plen);
   2509 		break;
   2510 	}
   2511 	match ^= ((np->in_flags & IPN_NOTSRC) != 0);
   2512 	if (match)
   2513 		return 0;
   2514 
   2515 	match = 0;
   2516 	switch (np->in_odstatype)
   2517 	{
   2518 	case FRI_NORMAL :
   2519 		match = IP6_MASKNEQ(&fin->fin_dst6, &np->in_odstmsk6,
   2520 				    &np->in_odstip6);
   2521 		break;
   2522 	case FRI_LOOKUP :
   2523 		match = (*np->in_odstfunc)(fin->fin_main_soft, np->in_odstptr,
   2524 					   6, &fin->fin_dst6, fin->fin_plen);
   2525 		break;
   2526 	}
   2527 
   2528 	match ^= ((np->in_flags & IPN_NOTDST) != 0);
   2529 	if (match)
   2530 		return 0;
   2531 
   2532 	ft = &np->in_tuc;
   2533 	if (!(fin->fin_flx & FI_TCPUDP) ||
   2534 	    (fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   2535 		if (ft->ftu_scmp || ft->ftu_dcmp)
   2536 			return 0;
   2537 		return 1;
   2538 	}
   2539 
   2540 	return ipf_tcpudpchk(&fin->fin_fi, ft);
   2541 }
   2542 
   2543 
   2544 /* ------------------------------------------------------------------------ */
   2545 /* Function:    ipf_nat6_checkout                                           */
   2546 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   2547 /*                     0 == no packet translation occurred,                 */
   2548 /*                     1 == packet was successfully translated.             */
   2549 /* Parameters:  fin(I)   - pointer to packet information                    */
   2550 /*              passp(I) - pointer to filtering result flags                */
   2551 /*                                                                          */
   2552 /* Check to see if an outcoming packet should be changed.  ICMP packets are */
   2553 /* first checked to see if they match an existing entry (if an error),      */
   2554 /* otherwise a search of the current NAT table is made.  If neither results */
   2555 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   2556 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   2557 /* packet header(s) as required.                                            */
   2558 /* ------------------------------------------------------------------------ */
   2559 int
   2560 ipf_nat6_checkout(fr_info_t *fin, u_32_t *passp)
   2561 {
   2562 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2563 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2564 	struct icmp6_hdr *icmp6 = NULL;
   2565 	struct ifnet *ifp, *sifp;
   2566 #ifdef IPF_V6_PROXIES
   2567 	tcphdr_t *tcp = NULL;
   2568 #endif
   2569 	int rval, natfailed;
   2570 	ipnat_t *np = NULL;
   2571 	u_int nflags = 0;
   2572 	i6addr_t ipa, iph;
   2573 	int natadd = 1;
   2574 	frentry_t *fr;
   2575 	nat_t *nat;
   2576 
   2577 	if (softn->ipf_nat_stats.ns_rules == 0 || softn->ipf_nat_lock != 0)
   2578 		return 0;
   2579 
   2580 	icmp6 = NULL;
   2581 	natfailed = 0;
   2582 	fr = fin->fin_fr;
   2583 	sifp = fin->fin_ifp;
   2584 	if (fr != NULL) {
   2585 		ifp = fr->fr_tifs[fin->fin_rev].fd_ptr;
   2586 		if ((ifp != NULL) && (ifp != (void *)-1))
   2587 			fin->fin_ifp = ifp;
   2588 	}
   2589 	ifp = fin->fin_ifp;
   2590 
   2591 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   2592 		switch (fin->fin_p)
   2593 		{
   2594 		case IPPROTO_TCP :
   2595 			nflags = IPN_TCP;
   2596 			break;
   2597 		case IPPROTO_UDP :
   2598 			nflags = IPN_UDP;
   2599 			break;
   2600 		case IPPROTO_ICMPV6 :
   2601 			icmp6 = fin->fin_dp;
   2602 
   2603 			/*
   2604 			 * Apart from ECHO request and reply, all other
   2605 			 * informational messages should not be translated
   2606 			 * so as to keep IPv6 working.
   2607 			 */
   2608 			if (icmp6->icmp6_type > ICMP6_ECHO_REPLY)
   2609 				return 0;
   2610 
   2611 			/*
   2612 			 * This is an incoming packet, so the destination is
   2613 			 * the icmp6_id and the source port equals 0
   2614 			 */
   2615 			if ((fin->fin_flx & FI_ICMPQUERY) != 0)
   2616 				nflags = IPN_ICMPQUERY;
   2617 			break;
   2618 		default :
   2619 			break;
   2620 		}
   2621 
   2622 #ifdef IPF_V6_PROXIES
   2623 		if ((nflags & IPN_TCPUDP))
   2624 			tcp = fin->fin_dp;
   2625 #endif
   2626 	}
   2627 
   2628 	ipa = fin->fin_src6;
   2629 
   2630 	READ_ENTER(&softc->ipf_nat);
   2631 
   2632 	if ((fin->fin_p == IPPROTO_ICMPV6) && !(nflags & IPN_ICMPQUERY) &&
   2633 	    (nat = ipf_nat6_icmperror(fin, &nflags, NAT_OUTBOUND)))
   2634 		/*EMPTY*/;
   2635 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   2636 		natadd = 0;
   2637 	else if ((nat = ipf_nat6_outlookup(fin, nflags|NAT_SEARCH,
   2638 					   (u_int)fin->fin_p,
   2639 					   &fin->fin_src6.in6,
   2640 					   &fin->fin_dst6.in6))) {
   2641 		nflags = nat->nat_flags;
   2642 	} else if (fin->fin_off == 0) {
   2643 		u_32_t hv, nmsk = 0;
   2644 		i6addr_t *msk;
   2645 
   2646 		/*
   2647 		 * If there is no current entry in the nat table for this IP#,
   2648 		 * create one for it (if there is a matching rule).
   2649 		 */
   2650 maskloop:
   2651 		msk = &softn->ipf_nat6_map_active_masks[nmsk];
   2652 		IP6_AND(&ipa, msk, &iph);
   2653 		hv = NAT_HASH_FN6(&iph, 0, softn->ipf_nat_maprules_sz);
   2654 		for (np = softn->ipf_nat_map_rules[hv]; np; np = np->in_mnext) {
   2655 			if ((np->in_ifps[1] && (np->in_ifps[1] != ifp)))
   2656 				continue;
   2657 			if (np->in_v[0] != 6)
   2658 				continue;
   2659 			if (np->in_pr[1] && (np->in_pr[1] != fin->fin_p))
   2660 				continue;
   2661 			if ((np->in_flags & IPN_RF) &&
   2662 			    !(np->in_flags & nflags))
   2663 				continue;
   2664 			if (np->in_flags & IPN_FILTER) {
   2665 				switch (ipf_nat6_match(fin, np))
   2666 				{
   2667 				case 0 :
   2668 					continue;
   2669 				case -1 :
   2670 					rval = -1;
   2671 					goto outmatchfail;
   2672 				case 1 :
   2673 				default :
   2674 					break;
   2675 				}
   2676 			} else if (!IP6_MASKEQ(&ipa, &np->in_osrcmsk,
   2677 					       &np->in_osrcip6))
   2678 				continue;
   2679 
   2680 			if ((fr != NULL) &&
   2681 			    !ipf_matchtag(&np->in_tag, &fr->fr_nattag))
   2682 				continue;
   2683 
   2684 #ifdef IPF_V6_PROXIES
   2685 			if (np->in_plabel != -1) {
   2686 				if (((np->in_flags & IPN_FILTER) == 0) &&
   2687 				    (np->in_odport != fin->fin_data[1]))
   2688 					continue;
   2689 				if (appr_ok(fin, tcp, np) == 0)
   2690 					continue;
   2691 			}
   2692 #endif
   2693 
   2694 			if (np->in_flags & IPN_NO) {
   2695 				np->in_hits++;
   2696 				break;
   2697 			}
   2698 
   2699 			MUTEX_ENTER(&softn->ipf_nat_new);
   2700 			nat = ipf_nat6_add(fin, np, NULL, nflags, NAT_OUTBOUND);
   2701 			MUTEX_EXIT(&softn->ipf_nat_new);
   2702 			if (nat != NULL) {
   2703 				np->in_hits++;
   2704 				break;
   2705 			}
   2706 			natfailed = -1;
   2707 		}
   2708 		if ((np == NULL) && (nmsk < softn->ipf_nat6_map_max)) {
   2709 			nmsk++;
   2710 			goto maskloop;
   2711 		}
   2712 	}
   2713 
   2714 	if (nat != NULL) {
   2715 		rval = ipf_nat6_out(fin, nat, natadd, nflags);
   2716 		if (rval == 1) {
   2717 			MUTEX_ENTER(&nat->nat_lock);
   2718 			ipf_nat_update(fin, nat);
   2719 			nat->nat_bytes[1] += fin->fin_plen;
   2720 			nat->nat_pkts[1]++;
   2721 			MUTEX_EXIT(&nat->nat_lock);
   2722 		}
   2723 	} else
   2724 		rval = natfailed;
   2725 outmatchfail:
   2726 	RWLOCK_EXIT(&softc->ipf_nat);
   2727 
   2728 	switch (rval)
   2729 	{
   2730 	case -1 :
   2731 		if (passp != NULL) {
   2732 			NBUMPSIDE6D(1, ns_drop);
   2733 			*passp = FR_BLOCK;
   2734 			fin->fin_reason = FRB_NATV6;
   2735 		}
   2736 		fin->fin_flx |= FI_BADNAT;
   2737 		NBUMPSIDE6D(1, ns_badnat);
   2738 		break;
   2739 	case 0 :
   2740 		NBUMPSIDE6D(1, ns_ignored);
   2741 		break;
   2742 	case 1 :
   2743 		NBUMPSIDE6D(1, ns_translated);
   2744 		break;
   2745 	}
   2746 	fin->fin_ifp = sifp;
   2747 	return rval;
   2748 }
   2749 
   2750 /* ------------------------------------------------------------------------ */
   2751 /* Function:    ipf_nat6_out                                                */
   2752 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   2753 /*                     1 == packet was successfully translated.             */
   2754 /* Parameters:  fin(I)    - pointer to packet information                   */
   2755 /*              nat(I)    - pointer to NAT structure                        */
   2756 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   2757 /*              nflags(I) - NAT flags set for this packet                   */
   2758 /*                                                                          */
   2759 /* Translate a packet coming "out" on an interface.                         */
   2760 /* ------------------------------------------------------------------------ */
   2761 static int
   2762 ipf_nat6_out(fr_info_t *fin, nat_t *nat, int natadd, u_32_t nflags)
   2763 {
   2764 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2765 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2766 	struct icmp6_hdr *icmp6;
   2767 	tcphdr_t *tcp;
   2768 	ipnat_t *np;
   2769 	int skip;
   2770 	int i;
   2771 
   2772 	tcp = NULL;
   2773 	icmp6 = NULL;
   2774 	np = nat->nat_ptr;
   2775 
   2776 	if ((natadd != 0) && (fin->fin_flx & FI_FRAG) && (np != NULL))
   2777 		(void) ipf_frag_natnew(softc, fin, 0, nat);
   2778 
   2779 	/*
   2780 	 * Address assignment is after the checksum modification because
   2781 	 * we are using the address in the packet for determining the
   2782 	 * correct checksum offset (the ICMP error could be coming from
   2783 	 * anyone...)
   2784 	 */
   2785 	switch (nat->nat_dir)
   2786 	{
   2787 	case NAT_OUTBOUND :
   2788 		fin->fin_ip6->ip6_src = nat->nat_nsrc6.in6;
   2789 		fin->fin_src6 = nat->nat_nsrc6;
   2790 		fin->fin_ip6->ip6_dst = nat->nat_ndst6.in6;
   2791 		fin->fin_dst6 = nat->nat_ndst6;
   2792 		break;
   2793 
   2794 	case NAT_INBOUND :
   2795 		fin->fin_ip6->ip6_src = nat->nat_odst6.in6;
   2796 		fin->fin_src6 = nat->nat_ndst6;
   2797 		fin->fin_ip6->ip6_dst = nat->nat_osrc6.in6;
   2798 		fin->fin_dst6 = nat->nat_nsrc6;
   2799 		break;
   2800 
   2801 	case NAT_DIVERTIN :
   2802 	    {
   2803 		mb_t *m;
   2804 
   2805 		skip = ipf_nat6_decap(fin, nat);
   2806 		if (skip <= 0) {
   2807 			NBUMPSIDE6D(1, ns_decap_fail);
   2808 			return -1;
   2809 		}
   2810 
   2811 		m = fin->fin_m;
   2812 
   2813 #if defined(MENTAT) && defined(_KERNEL)
   2814 		m->b_rptr += skip;
   2815 #else
   2816 		m->m_data += skip;
   2817 		m->m_len -= skip;
   2818 
   2819 # ifdef M_PKTHDR
   2820 		if (m->m_flags & M_PKTHDR)
   2821 			m->m_pkthdr.len -= skip;
   2822 # endif
   2823 #endif
   2824 
   2825 		MUTEX_ENTER(&nat->nat_lock);
   2826 		ipf_nat_update(fin, nat);
   2827 		MUTEX_EXIT(&nat->nat_lock);
   2828 		fin->fin_flx |= FI_NATED;
   2829 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   2830 			fin->fin_nattag = &np->in_tag;
   2831 		return 1;
   2832 		/* NOTREACHED */
   2833 	    }
   2834 
   2835 	case NAT_DIVERTOUT :
   2836 	    {
   2837 		udphdr_t *uh;
   2838 		ip6_t *ip6;
   2839 		mb_t *m;
   2840 
   2841 		m = M_DUP(np->in_divmp);
   2842 		if (m == NULL) {
   2843 			NBUMPSIDE6D(1, ns_divert_dup);
   2844 			return -1;
   2845 		}
   2846 
   2847 		ip6 = MTOD(m, ip6_t *);
   2848 
   2849 		ip6->ip6_plen = htons(fin->fin_plen + 8);
   2850 
   2851 		uh = (udphdr_t *)(ip6 + 1);
   2852 		uh->uh_ulen = htons(fin->fin_plen);
   2853 
   2854 		PREP_MB_T(fin, m);
   2855 
   2856 		fin->fin_ip6 = ip6;
   2857 		fin->fin_plen += sizeof(ip6_t) + 8;	/* UDP + new IPv4 hdr */
   2858 		fin->fin_dlen += sizeof(ip6_t) + 8;	/* UDP + old IPv4 hdr */
   2859 
   2860 		nflags &= ~IPN_TCPUDPICMP;
   2861 
   2862 		break;
   2863 	    }
   2864 
   2865 	default :
   2866 		break;
   2867 	}
   2868 
   2869 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   2870 		u_short *csump;
   2871 
   2872 		if ((nat->nat_nsport != 0) && (nflags & IPN_TCPUDP)) {
   2873 			tcp = fin->fin_dp;
   2874 
   2875 			switch (nat->nat_dir)
   2876 			{
   2877 			case NAT_OUTBOUND :
   2878 				tcp->th_sport = nat->nat_nsport;
   2879 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   2880 				tcp->th_dport = nat->nat_ndport;
   2881 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   2882 				break;
   2883 
   2884 			case NAT_INBOUND :
   2885 				tcp->th_sport = nat->nat_odport;
   2886 				fin->fin_data[0] = ntohs(nat->nat_odport);
   2887 				tcp->th_dport = nat->nat_osport;
   2888 				fin->fin_data[1] = ntohs(nat->nat_osport);
   2889 				break;
   2890 			}
   2891 		}
   2892 
   2893 		if ((nat->nat_nsport != 0) && (nflags & IPN_ICMPQUERY)) {
   2894 			icmp6 = fin->fin_dp;
   2895 			icmp6->icmp6_id = nat->nat_nicmpid;
   2896 		}
   2897 
   2898 		csump = ipf_nat_proto(fin, nat, nflags);
   2899 
   2900 		/*
   2901 		 * The above comments do not hold for layer 4 (or higher)
   2902 		 * checksums...
   2903 		 */
   2904 		if (csump != NULL) {
   2905 			if (nat->nat_dir == NAT_OUTBOUND)
   2906 				ipf_fix_outcksum(fin->fin_cksum, csump,
   2907 						 nat->nat_sumd[0],
   2908 						 nat->nat_sumd[1] +
   2909 						 fin->fin_dlen);
   2910 			else
   2911 				ipf_fix_incksum(fin->fin_cksum, csump,
   2912 						nat->nat_sumd[0],
   2913 						nat->nat_sumd[1] +
   2914 						fin->fin_dlen);
   2915 		}
   2916 	}
   2917 
   2918 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   2919 	/* ------------------------------------------------------------- */
   2920 	/* A few quick notes:                                            */
   2921 	/*      Following are test conditions prior to calling the       */
   2922 	/*      ipf_proxy_check routine.                                 */
   2923 	/*                                                               */
   2924 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   2925 	/*      with a redirect rule, we attempt to match the packet's   */
   2926 	/*      source port against in_dport, otherwise we'd compare the */
   2927 	/*      packet's destination.                                    */
   2928 	/* ------------------------------------------------------------- */
   2929 	if ((np != NULL) && (np->in_apr != NULL)) {
   2930 		i = ipf_proxy_check(fin, nat);
   2931 		if (i == 0) {
   2932 			i = 1;
   2933 		} else if (i == -1) {
   2934 			NBUMPSIDE6D(1, ns_ipf_proxy_fail);
   2935 		}
   2936 	} else {
   2937 		i = 1;
   2938 	}
   2939 	fin->fin_flx |= FI_NATED;
   2940 	return i;
   2941 }
   2942 
   2943 
   2944 /* ------------------------------------------------------------------------ */
   2945 /* Function:    ipf_nat6_checkin                                            */
   2946 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   2947 /*                     0 == no packet translation occurred,                 */
   2948 /*                     1 == packet was successfully translated.             */
   2949 /* Parameters:  fin(I)   - pointer to packet information                    */
   2950 /*              passp(I) - pointer to filtering result flags                */
   2951 /*                                                                          */
   2952 /* Check to see if an incoming packet should be changed.  ICMP packets are  */
   2953 /* first checked to see if they match an existing entry (if an error),      */
   2954 /* otherwise a search of the current NAT table is made.  If neither results */
   2955 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   2956 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   2957 /* packet header(s) as required.                                            */
   2958 /* ------------------------------------------------------------------------ */
   2959 int
   2960 ipf_nat6_checkin(fr_info_t *fin, u_32_t *passp)
   2961 {
   2962 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2963 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2964 	struct icmp6_hdr *icmp6;
   2965 	u_int nflags, natadd;
   2966 	int rval, natfailed;
   2967 	struct ifnet *ifp;
   2968 	i6addr_t ipa, iph;
   2969 #ifdef IPF_V6_PROXIES
   2970 	tcphdr_t *tcp;
   2971 #endif
   2972 	u_short dport;
   2973 	ipnat_t *np;
   2974 	nat_t *nat;
   2975 
   2976 	if (softn->ipf_nat_stats.ns_rules == 0 || softn->ipf_nat_lock != 0)
   2977 		return 0;
   2978 
   2979 #ifdef IPF_V6_PROXIES
   2980 	tcp = NULL;
   2981 #endif
   2982 	icmp6 = NULL;
   2983 	dport = 0;
   2984 	natadd = 1;
   2985 	nflags = 0;
   2986 	natfailed = 0;
   2987 	ifp = fin->fin_ifp;
   2988 
   2989 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   2990 		switch (fin->fin_p)
   2991 		{
   2992 		case IPPROTO_TCP :
   2993 			nflags = IPN_TCP;
   2994 			break;
   2995 		case IPPROTO_UDP :
   2996 			nflags = IPN_UDP;
   2997 			break;
   2998 		case IPPROTO_ICMPV6 :
   2999 			icmp6 = fin->fin_dp;
   3000 
   3001 			/*
   3002 			 * Apart from ECHO request and reply, all other
   3003 			 * informational messages should not be translated
   3004 			 * so as to keep IPv6 working.
   3005 			 */
   3006 			if (icmp6->icmp6_type > ICMP6_ECHO_REPLY)
   3007 				return 0;
   3008 
   3009 			/*
   3010 			 * This is an incoming packet, so the destination is
   3011 			 * the icmp6_id and the source port equals 0
   3012 			 */
   3013 			if ((fin->fin_flx & FI_ICMPQUERY) != 0) {
   3014 				nflags = IPN_ICMPQUERY;
   3015 				dport = icmp6->icmp6_id;
   3016 			} break;
   3017 		default :
   3018 			break;
   3019 		}
   3020 
   3021 		if ((nflags & IPN_TCPUDP)) {
   3022 #ifdef IPF_V6_PROXIES
   3023 			tcp = fin->fin_dp;
   3024 #endif
   3025 			dport = fin->fin_data[1];
   3026 		}
   3027 	}
   3028 
   3029 	ipa = fin->fin_dst6;
   3030 
   3031 	READ_ENTER(&softc->ipf_nat);
   3032 
   3033 	if ((fin->fin_p == IPPROTO_ICMPV6) && !(nflags & IPN_ICMPQUERY) &&
   3034 	    (nat = ipf_nat6_icmperror(fin, &nflags, NAT_INBOUND)))
   3035 		/*EMPTY*/;
   3036 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   3037 		natadd = 0;
   3038 	else if ((nat = ipf_nat6_inlookup(fin, nflags|NAT_SEARCH,
   3039 					  (u_int)fin->fin_p,
   3040 					  &fin->fin_src6.in6, &ipa.in6))) {
   3041 		nflags = nat->nat_flags;
   3042 	} else if (fin->fin_off == 0) {
   3043 		u_32_t hv, rmsk = 0;
   3044 		i6addr_t *msk;
   3045 
   3046 		/*
   3047 		 * If there is no current entry in the nat table for this IP#,
   3048 		 * create one for it (if there is a matching rule).
   3049 		 */
   3050 maskloop:
   3051 		msk = &softn->ipf_nat6_rdr_active_masks[rmsk];
   3052 		IP6_AND(&ipa, msk, &iph);
   3053 		hv = NAT_HASH_FN6(&iph, 0, softn->ipf_nat_rdrrules_sz);
   3054 		for (np = softn->ipf_nat_rdr_rules[hv]; np; np = np->in_rnext) {
   3055 			if (np->in_ifps[0] && (np->in_ifps[0] != ifp))
   3056 				continue;
   3057 			if (np->in_v[0] != 6)
   3058 				continue;
   3059 			if (np->in_pr[0] && (np->in_pr[0] != fin->fin_p))
   3060 				continue;
   3061 			if ((np->in_flags & IPN_RF) && !(np->in_flags & nflags))
   3062 				continue;
   3063 			if (np->in_flags & IPN_FILTER) {
   3064 				switch (ipf_nat6_match(fin, np))
   3065 				{
   3066 				case 0 :
   3067 					continue;
   3068 				case -1 :
   3069 					rval = -1;
   3070 					goto inmatchfail;
   3071 				case 1 :
   3072 				default :
   3073 					break;
   3074 				}
   3075 			} else {
   3076 				if (!IP6_MASKEQ(&ipa, &np->in_odstmsk6,
   3077 						&np->in_odstip6)) {
   3078 					continue;
   3079 				}
   3080 				if (np->in_odport &&
   3081 				    ((np->in_dtop < dport) ||
   3082 				     (dport < np->in_odport)))
   3083 					continue;
   3084 			}
   3085 
   3086 #ifdef IPF_V6_PROXIES
   3087 			if (np->in_plabel != -1) {
   3088 				if (!appr_ok(fin, tcp, np)) {
   3089 					continue;
   3090 				}
   3091 			}
   3092 #endif
   3093 
   3094 			if (np->in_flags & IPN_NO) {
   3095 				np->in_hits++;
   3096 				break;
   3097 			}
   3098 
   3099 			MUTEX_ENTER(&softn->ipf_nat_new);
   3100 			nat = ipf_nat6_add(fin, np, NULL, nflags, NAT_INBOUND);
   3101 			MUTEX_EXIT(&softn->ipf_nat_new);
   3102 			if (nat != NULL) {
   3103 				np->in_hits++;
   3104 				break;
   3105 			}
   3106 			natfailed = -1;
   3107 		}
   3108 
   3109 		if ((np == NULL) && (rmsk < softn->ipf_nat6_rdr_max)) {
   3110 			rmsk++;
   3111 			goto maskloop;
   3112 		}
   3113 	}
   3114 	if (nat != NULL) {
   3115 		rval = ipf_nat6_in(fin, nat, natadd, nflags);
   3116 		if (rval == 1) {
   3117 			MUTEX_ENTER(&nat->nat_lock);
   3118 			ipf_nat_update(fin, nat);
   3119 			nat->nat_bytes[0] += fin->fin_plen;
   3120 			nat->nat_pkts[0]++;
   3121 			MUTEX_EXIT(&nat->nat_lock);
   3122 		}
   3123 	} else
   3124 		rval = natfailed;
   3125 inmatchfail:
   3126 	RWLOCK_EXIT(&softc->ipf_nat);
   3127 
   3128 	switch (rval)
   3129 	{
   3130 	case -1 :
   3131 		if (passp != NULL) {
   3132 			NBUMPSIDE6D(0, ns_drop);
   3133 			*passp = FR_BLOCK;
   3134 			fin->fin_reason = FRB_NATV6;
   3135 		}
   3136 		fin->fin_flx |= FI_BADNAT;
   3137 		NBUMPSIDE6D(0, ns_badnat);
   3138 		break;
   3139 	case 0 :
   3140 		NBUMPSIDE6D(0, ns_ignored);
   3141 		break;
   3142 	case 1 :
   3143 		NBUMPSIDE6D(0, ns_translated);
   3144 		break;
   3145 	}
   3146 	return rval;
   3147 }
   3148 
   3149 
   3150 /* ------------------------------------------------------------------------ */
   3151 /* Function:    ipf_nat6_in                                                 */
   3152 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   3153 /*                     1 == packet was successfully translated.             */
   3154 /* Parameters:  fin(I)    - pointer to packet information                   */
   3155 /*              nat(I)    - pointer to NAT structure                        */
   3156 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   3157 /*              nflags(I) - NAT flags set for this packet                   */
   3158 /* Locks Held:   (READ)                                              */
   3159 /*                                                                          */
   3160 /* Translate a packet coming "in" on an interface.                          */
   3161 /* ------------------------------------------------------------------------ */
   3162 static int
   3163 ipf_nat6_in(fr_info_t *fin, nat_t *nat, int natadd, u_32_t nflags)
   3164 {
   3165 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3166 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3167 	struct icmp6_hdr *icmp6;
   3168 	u_short *csump;
   3169 	tcphdr_t *tcp;
   3170 	ipnat_t *np;
   3171 	int skip;
   3172 	int i;
   3173 
   3174 	tcp = NULL;
   3175 	csump = NULL;
   3176 	np = nat->nat_ptr;
   3177 	fin->fin_fr = nat->nat_fr;
   3178 
   3179 	if (np != NULL) {
   3180 		if ((natadd != 0) && (fin->fin_flx & FI_FRAG))
   3181 			(void) ipf_frag_natnew(softc, fin, 0, nat);
   3182 
   3183 	/* ------------------------------------------------------------- */
   3184 	/* A few quick notes:                                            */
   3185 	/*      Following are test conditions prior to calling the       */
   3186 	/*      ipf_proxy_check routine.                                 */
   3187 	/*                                                               */
   3188 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   3189 	/*      with a map rule, we attempt to match the packet's        */
   3190 	/*      source port against in_dport, otherwise we'd compare the */
   3191 	/*      packet's destination.                                    */
   3192 	/* ------------------------------------------------------------- */
   3193 		if (np->in_apr != NULL) {
   3194 			i = ipf_proxy_check(fin, nat);
   3195 			if (i == -1) {
   3196 				NBUMPSIDE6D(0, ns_ipf_proxy_fail);
   3197 				return -1;
   3198 			}
   3199 		}
   3200 	}
   3201 
   3202 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   3203 
   3204 	/*
   3205 	 * Fix up checksums, not by recalculating them, but
   3206 	 * simply computing adjustments.
   3207 	 * Why only do this for some platforms on inbound packets ?
   3208 	 * Because for those that it is done, IP processing is yet to happen
   3209 	 * and so the IPv4 header checksum has not yet been evaluated.
   3210 	 * Perhaps it should always be done for the benefit of things like
   3211 	 * fast forwarding (so that it doesn't need to be recomputed) but with
   3212 	 * header checksum offloading, perhaps it is a moot point.
   3213 	 */
   3214 
   3215 	switch (nat->nat_dir)
   3216 	{
   3217 	case NAT_INBOUND :
   3218 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   3219 			fin->fin_ip6->ip6_src = nat->nat_nsrc6.in6;
   3220 			fin->fin_src6 = nat->nat_nsrc6;
   3221 		}
   3222 		fin->fin_ip6->ip6_dst = nat->nat_ndst6.in6;
   3223 		fin->fin_dst6 = nat->nat_ndst6;
   3224 		break;
   3225 
   3226 	case NAT_OUTBOUND :
   3227 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   3228 			fin->fin_ip6->ip6_src = nat->nat_odst6.in6;
   3229 			fin->fin_src6 = nat->nat_odst6;
   3230 		}
   3231 		fin->fin_ip6->ip6_dst = nat->nat_osrc6.in6;
   3232 		fin->fin_dst6 = nat->nat_osrc6;
   3233 		break;
   3234 
   3235 	case NAT_DIVERTIN :
   3236 	    {
   3237 		udphdr_t *uh;
   3238 		ip6_t *ip6;
   3239 		mb_t *m;
   3240 
   3241 		m = M_DUP(np->in_divmp);
   3242 		if (m == NULL) {
   3243 			NBUMPSIDE6D(0, ns_divert_dup);
   3244 			return -1;
   3245 		}
   3246 
   3247 		ip6 = MTOD(m, ip6_t *);
   3248 		ip6->ip6_plen = htons(fin->fin_plen + sizeof(udphdr_t));
   3249 
   3250 		uh = (udphdr_t *)(ip6 + 1);
   3251 		uh->uh_ulen = ntohs(fin->fin_plen);
   3252 
   3253 		PREP_MB_T(fin, m);
   3254 
   3255 		fin->fin_ip6 = ip6;
   3256 		fin->fin_plen += sizeof(ip6_t) + 8;	/* UDP + new IPv6 hdr */
   3257 		fin->fin_dlen += sizeof(ip6_t) + 8;	/* UDP + old IPv6 hdr */
   3258 
   3259 		nflags &= ~IPN_TCPUDPICMP;
   3260 
   3261 		break;
   3262 	    }
   3263 
   3264 	case NAT_DIVERTOUT :
   3265 	    {
   3266 		mb_t *m;
   3267 
   3268 		skip = ipf_nat6_decap(fin, nat);
   3269 		if (skip <= 0) {
   3270 			NBUMPSIDE6D(0, ns_decap_fail);
   3271 			return -1;
   3272 		}
   3273 
   3274 		m = fin->fin_m;
   3275 
   3276 #if defined(MENTAT) && defined(_KERNEL)
   3277 		m->b_rptr += skip;
   3278 #else
   3279 		m->m_data += skip;
   3280 		m->m_len -= skip;
   3281 
   3282 # ifdef M_PKTHDR
   3283 		if (m->m_flags & M_PKTHDR)
   3284 			m->m_pkthdr.len -= skip;
   3285 # endif
   3286 #endif
   3287 
   3288 		ipf_nat_update(fin, nat);
   3289 		fin->fin_flx |= FI_NATED;
   3290 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   3291 			fin->fin_nattag = &np->in_tag;
   3292 		return 1;
   3293 		/* NOTREACHED */
   3294 	    }
   3295 	}
   3296 	if (nflags & IPN_TCPUDP)
   3297 		tcp = fin->fin_dp;
   3298 
   3299 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   3300 		if ((nat->nat_odport != 0) && (nflags & IPN_TCPUDP)) {
   3301 			switch (nat->nat_dir)
   3302 			{
   3303 			case NAT_INBOUND :
   3304 				tcp->th_sport = nat->nat_nsport;
   3305 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   3306 				tcp->th_dport = nat->nat_ndport;
   3307 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   3308 				break;
   3309 
   3310 			case NAT_OUTBOUND :
   3311 				tcp->th_sport = nat->nat_odport;
   3312 				fin->fin_data[0] = ntohs(nat->nat_odport);
   3313 				tcp->th_dport = nat->nat_osport;
   3314 				fin->fin_data[1] = ntohs(nat->nat_osport);
   3315 				break;
   3316 			}
   3317 		}
   3318 
   3319 
   3320 		if ((nat->nat_odport != 0) && (nflags & IPN_ICMPQUERY)) {
   3321 			icmp6 = fin->fin_dp;
   3322 
   3323 			icmp6->icmp6_id = nat->nat_nicmpid;
   3324 		}
   3325 
   3326 		csump = ipf_nat_proto(fin, nat, nflags);
   3327 	}
   3328 
   3329 	/*
   3330 	 * The above comments do not hold for layer 4 (or higher) checksums...
   3331 	 */
   3332 	if (csump != NULL) {
   3333 		if (nat->nat_dir == NAT_OUTBOUND)
   3334 			ipf_fix_incksum(0, csump, nat->nat_sumd[0], 0);
   3335 		else
   3336 			ipf_fix_outcksum(0, csump, nat->nat_sumd[0], 0);
   3337 	}
   3338 	fin->fin_flx |= FI_NATED;
   3339 	if (np != NULL && np->in_tag.ipt_num[0] != 0)
   3340 		fin->fin_nattag = &np->in_tag;
   3341 	return 1;
   3342 }
   3343 
   3344 
   3345 /* ------------------------------------------------------------------------ */
   3346 /* Function:    ipf_nat6_newrewrite                                         */
   3347 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
   3348 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
   3349 /* Parameters:  fin(I) - pointer to packet information                      */
   3350 /*              nat(I) - pointer to NAT entry                               */
   3351 /*              ni(I)  - pointer to structure with misc. information needed */
   3352 /*                       to create new NAT entry.                           */
   3353 /* Write Lock:  ipf_nat                                                     */
   3354 /*                                                                          */
   3355 /* This function is responsible for setting up an active NAT session where  */
   3356 /* we are changing both the source and destination parameters at the same   */
   3357 /* time.  The loop in here works differently to elsewhere - each iteration  */
   3358 /* is responsible for changing a single parameter that can be incremented.  */
   3359 /* So one pass may increase the source IP#, next source port, next dest. IP#*/
   3360 /* and the last destination port for a total of 4 iterations to try each.   */
   3361 /* This is done to try and exhaustively use the translation space available.*/
   3362 /* ------------------------------------------------------------------------ */
   3363 int
   3364 ipf_nat6_newrewrite(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
   3365 {
   3366 	int src_search = 1;
   3367 	int dst_search = 1;
   3368 	fr_info_t frnat;
   3369 	u_32_t flags;
   3370 	u_short swap;
   3371 	ipnat_t *np;
   3372 	nat_t *natl;
   3373 	int l = 0;
   3374 	int changed;
   3375 
   3376 	natl = NULL;
   3377 	changed = -1;
   3378 	np = nai->nai_np;
   3379 	flags = nat->nat_flags;
   3380 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   3381 
   3382 	nat->nat_hm = NULL;
   3383 
   3384 	do {
   3385 		changed = -1;
   3386 		/* TRACE (l, src_search, dst_search, np) */
   3387 
   3388 		if ((src_search == 0) && (np->in_spnext == 0) &&
   3389 		    (dst_search == 0) && (np->in_dpnext == 0)) {
   3390 			if (l > 0)
   3391 				return -1;
   3392 		}
   3393 
   3394 		/*
   3395 		 * Find a new source address
   3396 		 */
   3397 		if (ipf_nat6_nextaddr(fin, &np->in_nsrc, &frnat.fin_src6,
   3398 				 &frnat.fin_src6) == -1) {
   3399 			return -1;
   3400 		}
   3401 
   3402 		if (IP6_ISZERO(&np->in_nsrcip6) &&
   3403 		    IP6_ISONES(&np->in_nsrcmsk6)) {
   3404 			src_search = 0;
   3405 			if (np->in_stepnext == 0)
   3406 				np->in_stepnext = 1;
   3407 
   3408 		} else if (IP6_ISZERO(&np->in_nsrcip6) &&
   3409 			   IP6_ISZERO(&np->in_nsrcmsk6)) {
   3410 			src_search = 0;
   3411 			if (np->in_stepnext == 0)
   3412 				np->in_stepnext = 1;
   3413 
   3414 		} else if (IP6_ISONES(&np->in_nsrcmsk)) {
   3415 			src_search = 0;
   3416 			if (np->in_stepnext == 0)
   3417 				np->in_stepnext = 1;
   3418 
   3419 		} else if (!IP6_ISONES(&np->in_nsrcmsk6)) {
   3420 			if (np->in_stepnext == 0 && changed == -1) {
   3421 				IP6_INC(&np->in_snip);
   3422 				np->in_stepnext++;
   3423 				changed = 0;
   3424 			}
   3425 		}
   3426 
   3427 		if ((flags & IPN_TCPUDPICMP) != 0) {
   3428 			if (np->in_spnext != 0)
   3429 				frnat.fin_data[0] = np->in_spnext;
   3430 
   3431 			/*
   3432 			 * Standard port translation.  Select next port.
   3433 			 */
   3434 			if ((flags & IPN_FIXEDSPORT) != 0) {
   3435 				np->in_stepnext = 2;
   3436 			} else if ((np->in_stepnext == 1) &&
   3437 				   (changed == -1) && (natl != NULL)) {
   3438 				np->in_spnext++;
   3439 				np->in_stepnext++;
   3440 				changed = 1;
   3441 				if (np->in_spnext > np->in_spmax)
   3442 					np->in_spnext = np->in_spmin;
   3443 			}
   3444 		} else {
   3445 			np->in_stepnext = 2;
   3446 		}
   3447 		np->in_stepnext &= 0x3;
   3448 
   3449 		/*
   3450 		 * Find a new destination address
   3451 		 */
   3452 		/* TRACE (fin, np, l, frnat) */
   3453 
   3454 		if (ipf_nat6_nextaddr(fin, &np->in_ndst, &frnat.fin_dst6,
   3455 				      &frnat.fin_dst6) == -1)
   3456 			return -1;
   3457 
   3458 		if (IP6_ISZERO(&np->in_ndstip6) &&
   3459 		    IP6_ISONES(&np->in_ndstmsk6)) {
   3460 			dst_search = 0;
   3461 			if (np->in_stepnext == 2)
   3462 				np->in_stepnext = 3;
   3463 
   3464 		} else if (IP6_ISZERO(&np->in_ndstip6) &&
   3465 			   IP6_ISZERO(&np->in_ndstmsk6)) {
   3466 			dst_search = 0;
   3467 			if (np->in_stepnext == 2)
   3468 				np->in_stepnext = 3;
   3469 
   3470 		} else if (IP6_ISONES(&np->in_ndstmsk6)) {
   3471 			dst_search = 0;
   3472 			if (np->in_stepnext == 2)
   3473 				np->in_stepnext = 3;
   3474 
   3475 		} else if (!IP6_ISONES(&np->in_ndstmsk6)) {
   3476 			if ((np->in_stepnext == 2) && (changed == -1) &&
   3477 			    (natl != NULL)) {
   3478 				changed = 2;
   3479 				np->in_stepnext++;
   3480 				IP6_INC(&np->in_dnip6);
   3481 			}
   3482 		}
   3483 
   3484 		if ((flags & IPN_TCPUDPICMP) != 0) {
   3485 			if (np->in_dpnext != 0)
   3486 				frnat.fin_data[1] = np->in_dpnext;
   3487 
   3488 			/*
   3489 			 * Standard port translation.  Select next port.
   3490 			 */
   3491 			if ((flags & IPN_FIXEDDPORT) != 0) {
   3492 				np->in_stepnext = 0;
   3493 			} else if (np->in_stepnext == 3 && changed == -1) {
   3494 				np->in_dpnext++;
   3495 				np->in_stepnext++;
   3496 				changed = 3;
   3497 				if (np->in_dpnext > np->in_dpmax)
   3498 					np->in_dpnext = np->in_dpmin;
   3499 			}
   3500 		} else {
   3501 			if (np->in_stepnext == 3)
   3502 				np->in_stepnext = 0;
   3503 		}
   3504 
   3505 		/* TRACE (frnat) */
   3506 
   3507 		/*
   3508 		 * Here we do a lookup of the connection as seen from
   3509 		 * the outside.  If an IP# pair already exists, try
   3510 		 * again.  So if you have A->B becomes C->B, you can
   3511 		 * also have D->E become C->E but not D->B causing
   3512 		 * another C->B.  Also take protocol and ports into
   3513 		 * account when determining whether a pre-existing
   3514 		 * NAT setup will cause an external conflict where
   3515 		 * this is appropriate.
   3516 		 *
   3517 		 * fin_data[] is swapped around because we are doing a
   3518 		 * lookup of the packet is if it were moving in the opposite
   3519 		 * direction of the one we are working with now.
   3520 		 */
   3521 		if (flags & IPN_TCPUDP) {
   3522 			swap = frnat.fin_data[0];
   3523 			frnat.fin_data[0] = frnat.fin_data[1];
   3524 			frnat.fin_data[1] = swap;
   3525 		}
   3526 		if (fin->fin_out == 1) {
   3527 			natl = ipf_nat6_inlookup(&frnat,
   3528 					    flags & ~(SI_WILDP|NAT_SEARCH),
   3529 					    (u_int)frnat.fin_p,
   3530 					    &frnat.fin_dst6.in6,
   3531 					    &frnat.fin_src6.in6);
   3532 
   3533 		} else {
   3534 			natl = ipf_nat6_outlookup(&frnat,
   3535 					     flags & ~(SI_WILDP|NAT_SEARCH),
   3536 					     (u_int)frnat.fin_p,
   3537 					     &frnat.fin_dst6.in6,
   3538 					     &frnat.fin_src6.in6);
   3539 		}
   3540 		if (flags & IPN_TCPUDP) {
   3541 			swap = frnat.fin_data[0];
   3542 			frnat.fin_data[0] = frnat.fin_data[1];
   3543 			frnat.fin_data[1] = swap;
   3544 		}
   3545 
   3546 		/* TRACE natl, in_stepnext, l */
   3547 
   3548 		if ((natl != NULL) && (l > 8))	/* XXX 8 is arbitrary */
   3549 			return -1;
   3550 
   3551 		np->in_stepnext &= 0x3;
   3552 
   3553 		l++;
   3554 		changed = -1;
   3555 	} while (natl != NULL);
   3556 	nat->nat_osrc6 = fin->fin_src6;
   3557 	nat->nat_odst6 = fin->fin_dst6;
   3558 	nat->nat_nsrc6 = frnat.fin_src6;
   3559 	nat->nat_ndst6 = frnat.fin_dst6;
   3560 
   3561 	if ((flags & IPN_TCPUDP) != 0) {
   3562 		nat->nat_osport = htons(fin->fin_data[0]);
   3563 		nat->nat_odport = htons(fin->fin_data[1]);
   3564 		nat->nat_nsport = htons(frnat.fin_data[0]);
   3565 		nat->nat_ndport = htons(frnat.fin_data[1]);
   3566 	} else if ((flags & IPN_ICMPQUERY) != 0) {
   3567 		nat->nat_oicmpid = fin->fin_data[1];
   3568 		nat->nat_nicmpid = frnat.fin_data[1];
   3569 	}
   3570 
   3571 	return 0;
   3572 }
   3573 
   3574 
   3575 /* ------------------------------------------------------------------------ */
   3576 /* Function:    ipf_nat6_newdivert                                          */
   3577 /* Returns:     int - -1 == error, 0 == success                             */
   3578 /* Parameters:  fin(I) - pointer to packet information                      */
   3579 /*              nat(I) - pointer to NAT entry                               */
   3580 /*              ni(I)  - pointer to structure with misc. information needed */
   3581 /*                       to create new NAT entry.                           */
   3582 /* Write Lock:  ipf_nat                                                     */
   3583 /*                                                                          */
   3584 /* Create a new NAT divert session as defined by the NAT rule.  This is     */
   3585 /* somewhat different to other NAT session creation routines because we     */
   3586 /* do not iterate through either port numbers or IP addresses, searching    */
   3587 /* for a unique mapping, however, a complimentary duplicate check is made.  */
   3588 /* ------------------------------------------------------------------------ */
   3589 int
   3590 ipf_nat6_newdivert(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
   3591 {
   3592 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3593 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3594 	fr_info_t frnat;
   3595 	ipnat_t *np;
   3596 	nat_t *natl;
   3597 	int p;
   3598 
   3599 	np = nai->nai_np;
   3600 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   3601 
   3602 	nat->nat_pr[0] = 0;
   3603 	nat->nat_osrc6 = fin->fin_src6;
   3604 	nat->nat_odst6 = fin->fin_dst6;
   3605 	nat->nat_osport = htons(fin->fin_data[0]);
   3606 	nat->nat_odport = htons(fin->fin_data[1]);
   3607 	frnat.fin_src6 = np->in_snip6;
   3608 	frnat.fin_dst6 = np->in_dnip6;
   3609 
   3610 	if (np->in_redir & NAT_DIVERTUDP) {
   3611 		frnat.fin_data[0] = np->in_spnext;
   3612 		frnat.fin_data[1] = np->in_dpnext;
   3613 		frnat.fin_flx |= FI_TCPUDP;
   3614 		p = IPPROTO_UDP;
   3615 	} else {
   3616 		frnat.fin_flx &= ~FI_TCPUDP;
   3617 		p = IPPROTO_IPIP;
   3618 	}
   3619 
   3620 	if (fin->fin_out == 1) {
   3621 		natl = ipf_nat6_inlookup(&frnat, 0, p, &frnat.fin_dst6.in6,
   3622 					 &frnat.fin_src6.in6);
   3623 
   3624 	} else {
   3625 		natl = ipf_nat6_outlookup(&frnat, 0, p, &frnat.fin_dst6.in6,
   3626 					  &frnat.fin_src6.in6);
   3627 	}
   3628 
   3629 	if (natl != NULL) {
   3630 		NBUMPSIDE6D(fin->fin_out, ns_divert_exist);
   3631 		return -1;
   3632 	}
   3633 
   3634 	nat->nat_nsrc6 = frnat.fin_src6;
   3635 	nat->nat_ndst6 = frnat.fin_dst6;
   3636 	if (np->in_redir & NAT_DIVERTUDP) {
   3637 		nat->nat_nsport = htons(frnat.fin_data[0]);
   3638 		nat->nat_ndport = htons(frnat.fin_data[1]);
   3639 	}
   3640 	nat->nat_pr[fin->fin_out] = fin->fin_p;
   3641 	nat->nat_pr[1 - fin->fin_out] = p;
   3642 
   3643 	if (np->in_redir & NAT_REDIRECT)
   3644 		nat->nat_dir = NAT_DIVERTIN;
   3645 	else
   3646 		nat->nat_dir = NAT_DIVERTOUT;
   3647 
   3648 	return 0;
   3649 }
   3650 
   3651 
   3652 /* ------------------------------------------------------------------------ */
   3653 /* Function:    nat6_builddivertmp                                          */
   3654 /* Returns:     int - -1 == error, 0 == success                             */
   3655 /* Parameters:  np(I) - pointer to a NAT rule                               */
   3656 /*                                                                          */
   3657 /* For divert rules, a skeleton packet representing what will be prepended  */
   3658 /* to the real packet is created.  Even though we don't have the full       */
   3659 /* packet here, a checksum is calculated that we update later when we       */
   3660 /* fill in the final details.  At present a 0 checksum for UDP is being set */
   3661 /* here because it is expected that divert will be used for localhost.      */
   3662 /* ------------------------------------------------------------------------ */
   3663 static int
   3664 ipf_nat6_builddivertmp(ipf_nat_softc_t *softn, ipnat_t *np)
   3665 {
   3666 	udphdr_t *uh;
   3667 	size_t len;
   3668 	ip6_t *ip6;
   3669 
   3670 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   3671 		len = sizeof(ip6_t) + sizeof(udphdr_t);
   3672 	else
   3673 		len = sizeof(ip6_t);
   3674 
   3675 	ALLOC_MB_T(np->in_divmp, len);
   3676 	if (np->in_divmp == NULL) {
   3677 		ATOMIC_INCL(softn->ipf_nat_stats.ns_divert_build);
   3678 		return -1;
   3679 	}
   3680 
   3681 	/*
   3682 	 * First, the header to get the packet diverted to the new destination
   3683 	 */
   3684 	ip6 = MTOD(np->in_divmp, ip6_t *);
   3685 	ip6->ip6_vfc = 0x60;
   3686 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   3687 		ip6->ip6_nxt = IPPROTO_UDP;
   3688 	else
   3689 		ip6->ip6_nxt = IPPROTO_IPIP;
   3690 	ip6->ip6_hlim = 255;
   3691 	ip6->ip6_plen = 0;
   3692 	ip6->ip6_src = np->in_snip6.in6;
   3693 	ip6->ip6_dst = np->in_dnip6.in6;
   3694 
   3695 	if (np->in_redir & NAT_DIVERTUDP) {
   3696 		uh = (udphdr_t *)((u_char *)ip6 + sizeof(*ip6));
   3697 		uh->uh_sum = 0;
   3698 		uh->uh_ulen = 8;
   3699 		uh->uh_sport = htons(np->in_spnext);
   3700 		uh->uh_dport = htons(np->in_dpnext);
   3701 	}
   3702 
   3703 	return 0;
   3704 }
   3705 
   3706 
   3707 #define	MINDECAP	(sizeof(ip6_t) + sizeof(udphdr_t) + sizeof(ip6_t))
   3708 
   3709 /* ------------------------------------------------------------------------ */
   3710 /* Function:    nat6_decap                                                  */
   3711 /* Returns:     int - -1 == error, 0 == success                             */
   3712 /* Parameters:  fin(I) - pointer to packet information                      */
   3713 /*              nat(I) - pointer to current NAT session                     */
   3714 /*                                                                          */
   3715 /* This function is responsible for undoing a packet's encapsulation in the */
   3716 /* reverse of an encap/divert rule.  After removing the outer encapsulation */
   3717 /* it is necessary to call ipf_makefrip() again so that the contents of 'fin'*/
   3718 /* match the "new" packet as it may still be used by IPFilter elsewhere.    */
   3719 /* We use "dir" here as the basis for some of the expectations about the    */
   3720 /* outer header.  If we return an error, the goal is to leave the original  */
   3721 /* packet information undisturbed - this falls short at the end where we'd  */
   3722 /* need to back a backup copy of "fin" - expensive.                         */
   3723 /* ------------------------------------------------------------------------ */
   3724 static int
   3725 ipf_nat6_decap(fr_info_t *fin, nat_t *nat)
   3726 {
   3727 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3728 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3729 	char *hdr;
   3730 	int skip;
   3731 	mb_t *m;
   3732 
   3733 	if ((fin->fin_flx & FI_ICMPERR) != 0) {
   3734 		return 0;
   3735 	}
   3736 
   3737 	m = fin->fin_m;
   3738 	skip = fin->fin_hlen;
   3739 
   3740 	switch (nat->nat_dir)
   3741 	{
   3742 	case NAT_DIVERTIN :
   3743 	case NAT_DIVERTOUT :
   3744 		if (fin->fin_plen < MINDECAP)
   3745 			return -1;
   3746 		skip += sizeof(udphdr_t);
   3747 		break;
   3748 
   3749 	case NAT_ENCAPIN :
   3750 	case NAT_ENCAPOUT :
   3751 		if (fin->fin_plen < (skip + sizeof(ip6_t)))
   3752 			return -1;
   3753 		break;
   3754 	default :
   3755 		return -1;
   3756 		/* NOTREACHED */
   3757 	}
   3758 
   3759 	/*
   3760 	 * The aim here is to keep the original packet details in "fin" for
   3761 	 * as long as possible so that returning with an error is for the
   3762 	 * original packet and there is little undoing work to do.
   3763 	 */
   3764 	if (M_LEN(m) < skip + sizeof(ip6_t)) {
   3765 		if (ipf_pr_pullup(fin, skip + sizeof(ip6_t)) == -1)
   3766 			return -1;
   3767 	}
   3768 
   3769 	hdr = MTOD(fin->fin_m, char *);
   3770 	fin->fin_ip6 = (ip6_t *)(hdr + skip);
   3771 
   3772 	if (ipf_pr_pullup(fin, skip + sizeof(ip6_t)) == -1) {
   3773 		NBUMPSIDE6D(fin->fin_out, ns_decap_pullup);
   3774 		return -1;
   3775 	}
   3776 
   3777 	fin->fin_hlen = sizeof(ip6_t);
   3778 	fin->fin_dlen -= skip;
   3779 	fin->fin_plen -= skip;
   3780 	fin->fin_ipoff += skip;
   3781 
   3782 	if (ipf_makefrip(sizeof(ip6_t), (ip_t *)hdr, fin) == -1) {
   3783 		NBUMPSIDE6D(fin->fin_out, ns_decap_bad);
   3784 		return -1;
   3785 	}
   3786 
   3787 	return skip;
   3788 }
   3789 
   3790 
   3791 /* ------------------------------------------------------------------------ */
   3792 /* Function:    nat6_nextaddr                                               */
   3793 /* Returns:     int - -1 == bad input (no new address),                     */
   3794 /*                     0 == success and dst has new address                 */
   3795 /* Parameters:  fin(I) - pointer to packet information                      */
   3796 /*              na(I)  - how to generate new address                        */
   3797 /*              old(I) - original address being replaced                    */
   3798 /*              dst(O) - where to put the new address                       */
   3799 /* Write Lock:  ipf_nat                                                     */
   3800 /*                                                                          */
   3801 /* This function uses the contents of the "na" structure, in combination    */
   3802 /* with "old" to produce a new address to store in "dst".  Not all of the   */
   3803 /* possible uses of "na" will result in a new address.                      */
   3804 /* ------------------------------------------------------------------------ */
   3805 static int
   3806 ipf_nat6_nextaddr(fr_info_t *fin, nat_addr_t *na, i6addr_t *old, i6addr_t *dst)
   3807 {
   3808 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3809 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3810 	i6addr_t newip, new;
   3811 	u_32_t amin, amax;
   3812 	int error;
   3813 
   3814 	new.i6[0] = 0;
   3815 	new.i6[1] = 0;
   3816 	new.i6[2] = 0;
   3817 	new.i6[3] = 0;
   3818 	amin = na->na_addr[0].in4.s_addr;
   3819 
   3820 	switch (na->na_atype)
   3821 	{
   3822 	case FRI_RANGE :
   3823 		amax = na->na_addr[1].in4.s_addr;
   3824 		break;
   3825 
   3826 	case FRI_NETMASKED :
   3827 	case FRI_DYNAMIC :
   3828 	case FRI_NORMAL :
   3829 		/*
   3830 		 * Compute the maximum address by adding the inverse of the
   3831 		 * netmask to the minimum address.
   3832 		 */
   3833 		amax = ~na->na_addr[1].in4.s_addr;
   3834 		amax |= amin;
   3835 		break;
   3836 
   3837 	case FRI_LOOKUP :
   3838 		break;
   3839 
   3840 	case FRI_BROADCAST :
   3841 	case FRI_PEERADDR :
   3842 	case FRI_NETWORK :
   3843 	default :
   3844 		return -1;
   3845 	}
   3846 
   3847 	error = -1;
   3848 	switch (na->na_function)
   3849 	{
   3850 	case IPLT_DSTLIST :
   3851 		error = ipf_dstlist_select_node(fin, na->na_ptr, dst->i6,
   3852 						NULL);
   3853 		break;
   3854 
   3855 	case IPLT_NONE :
   3856 		/*
   3857 		 * 0/0 as the new address means leave it alone.
   3858 		 */
   3859 		if (na->na_addr[0].in4.s_addr == 0 &&
   3860 		    na->na_addr[1].in4.s_addr == 0) {
   3861 			new = *old;
   3862 
   3863 		/*
   3864 		 * 0/32 means get the interface's address
   3865 		 */
   3866 		} else if (IP6_ISZERO(&na->na_addr[0].in6) &&
   3867 			   IP6_ISONES(&na->na_addr[1].in6)) {
   3868 			if (ipf_ifpaddr(softc, 6, na->na_atype,
   3869 				       fin->fin_ifp, &newip, NULL) == -1) {
   3870 				NBUMPSIDE6(fin->fin_out, ns_ifpaddrfail);
   3871 				return -1;
   3872 			}
   3873 			new = newip;
   3874 		} else {
   3875 			new.in6 = na->na_nextip6;
   3876 		}
   3877 		*dst = new;
   3878 		error = 0;
   3879 		break;
   3880 
   3881 	default :
   3882 		NBUMPSIDE6(fin->fin_out, ns_badnextaddr);
   3883 		break;
   3884 	}
   3885 
   3886 	return error;
   3887 }
   3888 
   3889 
   3890 /* ------------------------------------------------------------------------ */
   3891 /* Function:    ipf_nat6_nextaddrinit                                       */
   3892 /* Returns:     int - 0 == success, else error number                       */
   3893 /* Parameters:  na(I)      - NAT address information for generating new addr*/
   3894 /*              base(I)    - start of where to find strings                 */
   3895 /*              initial(I) - flag indicating if it is the first call for    */
   3896 /*                           this "na" structure.                           */
   3897 /*              ifp(I)     - network interface to derive address            */
   3898 /*                           information from.                              */
   3899 /*                                                                          */
   3900 /* This function is expected to be called in two scenarious: when a new NAT */
   3901 /* rule is loaded into the kernel and when the list of NAT rules is sync'd  */
   3902 /* up with the valid network interfaces (possibly due to them changing.)    */
   3903 /* To distinguish between these, the "initial" parameter is used.  If it is */
   3904 /* 1 then this indicates the rule has just been reloaded and 0 for when we  */
   3905 /* are updating information.  This difference is important because in       */
   3906 /* instances where we are not updating address information associated with  */
   3907 /* a network interface, we don't want to disturb what the "next" address to */
   3908 /* come out of ipf_nat6_nextaddr() will be.                                 */
   3909 /* ------------------------------------------------------------------------ */
   3910 static int
   3911 ipf_nat6_nextaddrinit(ipf_main_softc_t *softc, char *base, nat_addr_t *na,
   3912     int initial, void *ifp)
   3913 {
   3914 	switch (na->na_atype)
   3915 	{
   3916 	case FRI_LOOKUP :
   3917 		if (na->na_subtype == 0) {
   3918 			na->na_ptr = ipf_lookup_res_num(softc, IPL_LOGNAT,
   3919 							na->na_type,
   3920 							na->na_num,
   3921 							&na->na_func);
   3922 		} else if (na->na_subtype == 1) {
   3923 			na->na_ptr = ipf_lookup_res_name(softc, IPL_LOGNAT,
   3924 							 na->na_type,
   3925 							 base + na->na_num,
   3926 							 &na->na_func);
   3927 		}
   3928 		if (na->na_func == NULL) {
   3929 			IPFERROR(60072);
   3930 			return ESRCH;
   3931 		}
   3932 		if (na->na_ptr == NULL) {
   3933 			IPFERROR(60073);
   3934 			return ESRCH;
   3935 		}
   3936 		break;
   3937 	case FRI_DYNAMIC :
   3938 	case FRI_BROADCAST :
   3939 	case FRI_NETWORK :
   3940 	case FRI_NETMASKED :
   3941 	case FRI_PEERADDR :
   3942 		if (ifp != NULL)
   3943 			(void )ipf_ifpaddr(softc, 6, na->na_atype, ifp,
   3944 					   &na->na_addr[0],
   3945 					   &na->na_addr[1]);
   3946 		break;
   3947 
   3948 	case FRI_SPLIT :
   3949 	case FRI_RANGE :
   3950 		if (initial)
   3951 			na->na_nextip6 = na->na_addr[0].in6;
   3952 		break;
   3953 
   3954 	case FRI_NONE :
   3955 		IP6_ANDASSIGN(&na->na_addr[0].in6, &na->na_addr[1].in6);
   3956 		return 0;
   3957 
   3958 	case FRI_NORMAL :
   3959 		IP6_ANDASSIGN(&na->na_addr[0].in6, &na->na_addr[1].in6);
   3960 		break;
   3961 
   3962 	default :
   3963 		IPFERROR(60074);
   3964 		return EINVAL;
   3965 	}
   3966 
   3967 	if (initial && (na->na_atype == FRI_NORMAL)) {
   3968 		if (IP6_ISZERO(&na->na_addr[0].in6)) {
   3969 			if (IP6_ISONES(&na->na_addr[1].in6) ||
   3970 			    IP6_ISZERO(&na->na_addr[1].in6)) {
   3971 				return 0;
   3972 			}
   3973 		}
   3974 
   3975 		na->na_nextip6 = na->na_addr[0].in6;
   3976 		if (!IP6_ISONES(&na->na_addr[1].in6)) {
   3977 			IP6_INC(&na->na_nextip6);
   3978 		}
   3979 	}
   3980 
   3981 	return 0;
   3982 }
   3983 
   3984 
   3985 /* ------------------------------------------------------------------------ */
   3986 /* Function:    ipf_nat6_icmpquerytype                                      */
   3987 /* Returns:     int - 1 == success, 0 == failure                            */
   3988 /* Parameters:  icmptype(I) - ICMP type number                              */
   3989 /*                                                                          */
   3990 /* Tests to see if the ICMP type number passed is a query/response type or  */
   3991 /* not.                                                                     */
   3992 /* ------------------------------------------------------------------------ */
   3993 static int
   3994 ipf_nat6_icmpquerytype(int icmptype)
   3995 {
   3996 
   3997 	/*
   3998 	 * For the ICMP query NAT code, it is essential that both the query
   3999 	 * and the reply match on the NAT rule. Because the NAT structure
   4000 	 * does not keep track of the icmptype, and a single NAT structure
   4001 	 * is used for all icmp types with the same src, dest and id, we
   4002 	 * simply define the replies as queries as well. The funny thing is,
   4003 	 * altough it seems silly to call a reply a query, this is exactly
   4004 	 * as it is defined in the IPv4 specification
   4005 	 */
   4006 
   4007 	switch (icmptype)
   4008 	{
   4009 
   4010 	case ICMP6_ECHO_REPLY:
   4011 	case ICMP6_ECHO_REQUEST:
   4012 	/* route aedvertisement/solliciation is currently unsupported: */
   4013 	/* it would require rewriting the ICMP data section            */
   4014 	case ICMP6_MEMBERSHIP_QUERY:
   4015 	case ICMP6_MEMBERSHIP_REPORT:
   4016 	case ICMP6_MEMBERSHIP_REDUCTION:
   4017 	case ICMP6_WRUREQUEST:
   4018 	case ICMP6_WRUREPLY:
   4019 	case MLD6_MTRACE_RESP:
   4020 	case MLD6_MTRACE:
   4021 		return 1;
   4022 	default:
   4023 		return 0;
   4024 	}
   4025 }
   4026 #endif /* USE_INET6 */
   4027