Home | History | Annotate | Line # | Download | only in netinet
ip_nat6.c revision 1.3
      1 /*	$NetBSD: ip_nat6.c,v 1.3 2012/07/22 14:27:51 darrenr Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 2012 by Darren Reed.
      5  *
      6  * See the IPFILTER.LICENCE file for details on licencing.
      7  */
      8 #if defined(KERNEL) || defined(_KERNEL)
      9 # undef KERNEL
     10 # undef 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 	u_32_t flags;
   1145 
   1146 	flags = nat->nat_flags;
   1147 
   1148 	switch (fin->fin_p)
   1149 	{
   1150 	case IPPROTO_ICMPV6 :
   1151 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1152 		sum1 += ntohs(nat->nat_oicmpid);
   1153 		sum2 = LONG_SUM6(&nat->nat_nsrc6);
   1154 		sum2 += ntohs(nat->nat_nicmpid);
   1155 		CALC_SUMD(sum1, sum2, sumd);
   1156 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   1157 
   1158 		sum1 = LONG_SUM6(&nat->nat_odst6);
   1159 		sum2 = LONG_SUM6(&nat->nat_ndst6);
   1160 		CALC_SUMD(sum1, sum2, sumd);
   1161 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   1162 		break;
   1163 
   1164 	case IPPROTO_TCP :
   1165 	case IPPROTO_UDP :
   1166 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1167 		sum1 += ntohs(nat->nat_osport);
   1168 		sum2 = LONG_SUM6(&nat->nat_nsrc6);
   1169 		sum2 += ntohs(nat->nat_nsport);
   1170 		CALC_SUMD(sum1, sum2, sumd);
   1171 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   1172 
   1173 		sum1 = LONG_SUM6(&nat->nat_odst6);
   1174 		sum1 += ntohs(nat->nat_odport);
   1175 		sum2 = LONG_SUM6(&nat->nat_ndst6);
   1176 		sum2 += ntohs(nat->nat_ndport);
   1177 		CALC_SUMD(sum1, sum2, sumd);
   1178 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   1179 		break;
   1180 
   1181 	default :
   1182 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1183 		sum2 = LONG_SUM6(&nat->nat_nsrc6);
   1184 		CALC_SUMD(sum1, sum2, sumd);
   1185 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
   1186 
   1187 		sum1 = LONG_SUM6(&nat->nat_odst6);
   1188 		sum2 = LONG_SUM6(&nat->nat_ndst6);
   1189 		CALC_SUMD(sum1, sum2, sumd);
   1190 		nat->nat_sumd[0] += (sumd & 0xffff) + (sumd >> 16);
   1191 		break;
   1192 	}
   1193 
   1194 	/*
   1195 	 * Compute the partial checksum, just in case.
   1196 	 * This is only ever placed into outbound packets so care needs
   1197 	 * to be taken over which pair of addresses are used.
   1198 	 */
   1199 	if (nat->nat_dir == NAT_OUTBOUND) {
   1200 		sum1 = LONG_SUM6(&nat->nat_nsrc6);
   1201 		sum1 += LONG_SUM6(&nat->nat_ndst6);
   1202 	} else {
   1203 		sum1 = LONG_SUM6(&nat->nat_osrc6);
   1204 		sum1 += LONG_SUM6(&nat->nat_odst6);
   1205 	}
   1206 	sum1 += nat->nat_pr[1];
   1207 	nat->nat_sumd[1] = (sum1 & 0xffff) + (sum1 >> 16);
   1208 
   1209 	if ((nat->nat_flags & SI_CLONE) == 0)
   1210 		nat->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, nat);
   1211 
   1212 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   1213 		nat->nat_mtu[0] = GETIFMTU_6(nat->nat_ifps[0]);
   1214 	}
   1215 
   1216 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   1217 		nat->nat_mtu[1] = GETIFMTU_6(nat->nat_ifps[1]);
   1218 	}
   1219 
   1220 	nat->nat_v[0] = 6;
   1221 	nat->nat_v[1] = 6;
   1222 
   1223 	if (ipf_nat6_insert(softc, softn, nat) == 0) {
   1224 		if (softn->ipf_nat_logging)
   1225 			ipf_nat_log(softc, softn, nat, NL_NEW);
   1226 		fr = nat->nat_fr;
   1227 		if (fr != NULL) {
   1228 			MUTEX_ENTER(&fr->fr_lock);
   1229 			fr->fr_ref++;
   1230 			MUTEX_EXIT(&fr->fr_lock);
   1231 		}
   1232 		return 0;
   1233 	}
   1234 
   1235 	NBUMPSIDE6D(fin->fin_out, ns_unfinalised);
   1236 	/*
   1237 	 * nat6_insert failed, so cleanup time...
   1238 	 */
   1239 	if (nat->nat_sync != NULL)
   1240 		ipf_sync_del_nat(softc->ipf_sync_soft, nat->nat_sync);
   1241 	return -1;
   1242 }
   1243 
   1244 
   1245 /* ------------------------------------------------------------------------ */
   1246 /* Function:    ipf_nat6_insert                                             */
   1247 /* Returns:     int - 0 == sucess, -1 == failure                            */
   1248 /* Parameters:  softc(I) - pointer to soft context main structure           */
   1249 /*              softn(I) - pointer to NAT context structure                 */
   1250 /*              nat(I) - pointer to NAT structure                           */
   1251 /* Write Lock:  ipf_nat                                                     */
   1252 /*                                                                          */
   1253 /* Insert a NAT entry into the hash tables for searching and add it to the  */
   1254 /* list of active NAT entries.  Adjust global counters when complete.       */
   1255 /* ------------------------------------------------------------------------ */
   1256 static int
   1257 ipf_nat6_insert(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, nat_t *nat)
   1258 {
   1259 	u_int hv1, hv2;
   1260 	u_32_t sp, dp;
   1261 	ipnat_t *in;
   1262 
   1263 	/*
   1264 	 * Try and return an error as early as possible, so calculate the hash
   1265 	 * entry numbers first and then proceed.
   1266 	 */
   1267 	if ((nat->nat_flags & (SI_W_SPORT|SI_W_DPORT)) == 0) {
   1268 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1269 			sp = nat->nat_osport;
   1270 			dp = nat->nat_odport;
   1271 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   1272 			sp = 0;
   1273 			dp = nat->nat_oicmpid;
   1274 		} else {
   1275 			sp = 0;
   1276 			dp = 0;
   1277 		}
   1278 		hv1 = NAT_HASH_FN6(&nat->nat_osrc6, sp, 0xffffffff);
   1279 		hv1 = NAT_HASH_FN6(&nat->nat_odst6, hv1 + dp,
   1280 				   softn->ipf_nat_table_sz);
   1281 
   1282 		/*
   1283 		 * TRACE nat6_osrc6, nat6_osport, nat6_odst6,
   1284 		 * nat6_odport, hv1
   1285 		 */
   1286 
   1287 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1288 			sp = nat->nat_nsport;
   1289 			dp = nat->nat_ndport;
   1290 		} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
   1291 			sp = 0;
   1292 			dp = nat->nat_nicmpid;
   1293 		} else {
   1294 			sp = 0;
   1295 			dp = 0;
   1296 		}
   1297 		hv2 = NAT_HASH_FN6(&nat->nat_nsrc6, sp, 0xffffffff);
   1298 		hv2 = NAT_HASH_FN6(&nat->nat_ndst6, hv2 + dp,
   1299 				   softn->ipf_nat_table_sz);
   1300 		/*
   1301 		 * TRACE nat6_nsrcaddr, nat6_nsport, nat6_ndstaddr,
   1302 		 * nat6_ndport, hv1
   1303 		 */
   1304 	} else {
   1305 		hv1 = NAT_HASH_FN6(&nat->nat_osrc6, 0, 0xffffffff);
   1306 		hv1 = NAT_HASH_FN6(&nat->nat_odst6, hv1,
   1307 				   softn->ipf_nat_table_sz);
   1308 		/* TRACE nat6_osrcip6, nat6_odstip6, hv1 */
   1309 
   1310 		hv2 = NAT_HASH_FN6(&nat->nat_nsrc6, 0, 0xffffffff);
   1311 		hv2 = NAT_HASH_FN6(&nat->nat_ndst6, hv2,
   1312 				   softn->ipf_nat_table_sz);
   1313 		/* TRACE nat6_nsrcip6, nat6_ndstip6, hv2 */
   1314 	}
   1315 
   1316 	nat->nat_hv[0] = hv1;
   1317 	nat->nat_hv[1] = hv2;
   1318 
   1319 	MUTEX_INIT(&nat->nat_lock, "nat entry lock");
   1320 
   1321 	in = nat->nat_ptr;
   1322 	nat->nat_ref = nat->nat_me ? 2 : 1;
   1323 
   1324 	nat->nat_ifnames[0][LIFNAMSIZ - 1] = '\0';
   1325 	nat->nat_ifps[0] = ipf_resolvenic(softc, nat->nat_ifnames[0],
   1326 					  nat->nat_v[0]);
   1327 
   1328 	if (nat->nat_ifnames[1][0] != '\0') {
   1329 		nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   1330 		nat->nat_ifps[1] = ipf_resolvenic(softc, nat->nat_ifnames[1],
   1331 						  nat->nat_v[1]);
   1332 	} else if (in->in_ifnames[1] != -1) {
   1333 		char *name;
   1334 
   1335 		name = in->in_names + in->in_ifnames[1];
   1336 		if (name[1] != '\0' && name[0] != '-' && name[0] != '*') {
   1337 			(void) strncpy(nat->nat_ifnames[1],
   1338 				       nat->nat_ifnames[0], LIFNAMSIZ);
   1339 			nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
   1340 			nat->nat_ifps[1] = nat->nat_ifps[0];
   1341 		}
   1342 	}
   1343 	if ((nat->nat_ifps[0] != NULL) && (nat->nat_ifps[0] != (void *)-1)) {
   1344 		nat->nat_mtu[0] = GETIFMTU_6(nat->nat_ifps[0]);
   1345 	}
   1346 	if ((nat->nat_ifps[1] != NULL) && (nat->nat_ifps[1] != (void *)-1)) {
   1347 		nat->nat_mtu[1] = GETIFMTU_6(nat->nat_ifps[1]);
   1348 	}
   1349 
   1350 	return ipf_nat_hashtab_add(softc, softn, nat);
   1351 }
   1352 
   1353 
   1354 /* ------------------------------------------------------------------------ */
   1355 /* Function:    ipf_nat6_icmperrorlookup                                    */
   1356 /* Returns:     nat6_t* - point to matching NAT structure                    */
   1357 /* Parameters:  fin(I) - pointer to packet information                      */
   1358 /*              dir(I) - direction of packet (in/out)                       */
   1359 /*                                                                          */
   1360 /* Check if the ICMP error message is related to an existing TCP, UDP or    */
   1361 /* ICMP query nat entry.  It is assumed that the packet is already of the   */
   1362 /* the required length.                                                     */
   1363 /* ------------------------------------------------------------------------ */
   1364 nat_t *
   1365 ipf_nat6_icmperrorlookup(fr_info_t *fin, int dir)
   1366 {
   1367 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1368 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1369 	struct icmp6_hdr *icmp6, *orgicmp;
   1370 	int flags = 0, type, minlen;
   1371 	nat_stat_side_t *nside;
   1372 	tcphdr_t *tcp = NULL;
   1373 	u_short data[2];
   1374 	ip6_t *oip6;
   1375 	nat_t *nat;
   1376 	u_int p;
   1377 
   1378 	minlen = 40;
   1379 	icmp6 = fin->fin_dp;
   1380 	type = icmp6->icmp6_type;
   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, neg;
   1515 
   1516 	neg = 0;
   1517 	l1 = *ip1;
   1518 	l2 = *ip2;
   1519 	s1 = (u_short *)&l1;
   1520 	s2 = (u_short *)&l2;
   1521 	ds = (u_short *)&d;
   1522 
   1523 	for (i = 7; i > 0; i--) {
   1524 		if (s1[i] > s2[i]) {
   1525 			ds[i] = s2[i] + 0x10000 - s1[i];
   1526 			s2[i - 1] += 0x10000;
   1527 		} else {
   1528 			ds[i] = s2[i] - s1[i];
   1529 		}
   1530 	}
   1531 	if (s2[0] > s1[0]) {
   1532 		ds[0] = s2[0] + 0x10000 - s1[0];
   1533 		neg = 1;
   1534 	} else {
   1535 		ds[0] = s2[0] - s1[0];
   1536 	}
   1537 
   1538 	for (i = 0, r = 0; i < 8; i++) {
   1539 		r += ds[i];
   1540 	}
   1541 
   1542 	return r;
   1543 }
   1544 
   1545 
   1546 /* ------------------------------------------------------------------------ */
   1547 /* Function:    ipf_nat6_icmperror                                          */
   1548 /* Returns:     nat6_t* - point to matching NAT structure                    */
   1549 /* Parameters:  fin(I)    - pointer to packet information                   */
   1550 /*              nflags(I) - NAT flags for this packet                       */
   1551 /*              dir(I)    - direction of packet (in/out)                    */
   1552 /*                                                                          */
   1553 /* Fix up an ICMP packet which is an error message for an existing NAT      */
   1554 /* session.  This will correct both packet header data and checksums.       */
   1555 /*                                                                          */
   1556 /* This should *ONLY* be used for incoming ICMP error packets to make sure  */
   1557 /* a NAT'd ICMP packet gets correctly recognised.                           */
   1558 /* ------------------------------------------------------------------------ */
   1559 nat_t *
   1560 ipf_nat6_icmperror(fr_info_t *fin, u_int *nflags, int dir)
   1561 {
   1562 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1563 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1564 	u_32_t sum1, sum2, sumd, sumd2;
   1565 	i6addr_t a1, a2, a3, a4;
   1566 	struct icmp6_hdr *icmp6;
   1567 	int flags, dlen, odst;
   1568 	u_short *csump;
   1569 	tcphdr_t *tcp;
   1570 	ip6_t *oip6;
   1571 	nat_t *nat;
   1572 	void *dp;
   1573 
   1574 	if ((fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   1575 		NBUMPSIDE6D(fin->fin_out, ns_icmp_short);
   1576 		return NULL;
   1577 	}
   1578 
   1579 	/*
   1580 	 * ipf_nat6_icmperrorlookup() will return NULL for `defective' packets.
   1581 	 */
   1582 	if ((fin->fin_v != 6) || !(nat = ipf_nat6_icmperrorlookup(fin, dir))) {
   1583 		NBUMPSIDE6D(fin->fin_out, ns_icmp_notfound);
   1584 		return NULL;
   1585 	}
   1586 
   1587 	tcp = NULL;
   1588 	csump = NULL;
   1589 	flags = 0;
   1590 	sumd2 = 0;
   1591 	*nflags = IPN_ICMPERR;
   1592 	icmp6 = fin->fin_dp;
   1593 	oip6 = (ip6_t *)((u_char *)icmp6 + sizeof(*icmp6));
   1594 	dp = (u_char *)oip6 + sizeof(*oip6);
   1595 	if (oip6->ip6_nxt == IPPROTO_TCP) {
   1596 		tcp = (tcphdr_t *)dp;
   1597 		csump = (u_short *)&tcp->th_sum;
   1598 		flags = IPN_TCP;
   1599 	} else if (oip6->ip6_nxt == IPPROTO_UDP) {
   1600 		udphdr_t *udp;
   1601 
   1602 		udp = (udphdr_t *)dp;
   1603 		tcp = (tcphdr_t *)dp;
   1604 		csump = (u_short *)&udp->uh_sum;
   1605 		flags = IPN_UDP;
   1606 	} else if (oip6->ip6_nxt == IPPROTO_ICMPV6)
   1607 		flags = IPN_ICMPQUERY;
   1608 	dlen = fin->fin_plen - ((char *)dp - (char *)fin->fin_ip);
   1609 
   1610 	/*
   1611 	 * Need to adjust ICMP header to include the real IP#'s and
   1612 	 * port #'s.  Only apply a checksum change relative to the
   1613 	 * IP address change as it will be modified again in ipf_nat6_checkout
   1614 	 * for both address and port.  Two checksum changes are
   1615 	 * necessary for the two header address changes.  Be careful
   1616 	 * to only modify the checksum once for the port # and twice
   1617 	 * for the IP#.
   1618 	 */
   1619 
   1620 	/*
   1621 	 * Step 1
   1622 	 * Fix the IP addresses in the offending IP packet. You also need
   1623 	 * to adjust the IP header checksum of that offending IP packet.
   1624 	 *
   1625 	 * Normally, you would expect that the ICMP checksum of the
   1626 	 * ICMP error message needs to be adjusted as well for the
   1627 	 * IP address change in oip.
   1628 	 * However, this is a NOP, because the ICMP checksum is
   1629 	 * calculated over the complete ICMP packet, which includes the
   1630 	 * changed oip IP addresses and oip6->ip6_sum. However, these
   1631 	 * two changes cancel each other out (if the delta for
   1632 	 * the IP address is x, then the delta for ip_sum is minus x),
   1633 	 * so no change in the icmp_cksum is necessary.
   1634 	 *
   1635 	 * Inbound ICMP
   1636 	 * ------------
   1637 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   1638 	 * - response to outgoing packet (a,b)=>(c,b) (OIP_SRC=c,OIP_DST=b)
   1639 	 * - OIP_SRC(c)=nat6_newsrcip,          OIP_DST(b)=nat6_newdstip
   1640 	 *=> OIP_SRC(c)=nat6_oldsrcip,          OIP_DST(b)=nat6_olddstip
   1641 	 *
   1642 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   1643 	 * - response to outgoing packet (c,a)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   1644 	 * - OIP_SRC(b)=nat6_olddstip,          OIP_DST(a)=nat6_oldsrcip
   1645 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1646 	 *
   1647 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   1648 	 * - response to outgoing packet (a,b)=>(c,d) (OIP_SRC=c,OIP_DST=d)
   1649 	 * - OIP_SRC(c)=nat6_newsrcip,          OIP_DST(d)=nat6_newdstip
   1650 	 *=> OIP_SRC(c)=nat6_oldsrcip,          OIP_DST(d)=nat6_olddstip
   1651 	 *
   1652 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   1653 	 * - response to outgoing packet (d,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   1654 	 * - OIP_SRC(b)=nat6_olddstip,          OIP_DST(a)=nat6_oldsrcip
   1655 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1656 	 *
   1657 	 * Outbound ICMP
   1658 	 * -------------
   1659 	 * MAP rule, SRC=a,DST=b -> SRC=c,DST=b
   1660 	 * - response to incoming packet (b,c)=>(b,a) (OIP_SRC=b,OIP_DST=a)
   1661 	 * - OIP_SRC(b)=nat6_olddstip,          OIP_DST(a)=nat6_oldsrcip
   1662 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1663 	 *
   1664 	 * RDR rule, SRC=a,DST=b -> SRC=a,DST=c
   1665 	 * - response to incoming packet (a,b)=>(a,c) (OIP_SRC=a,OIP_DST=c)
   1666 	 * - OIP_SRC(a)=nat6_newsrcip,          OIP_DST(c)=nat6_newdstip
   1667 	 *=> OIP_SRC(a)=nat6_oldsrcip,          OIP_DST(c)=nat6_olddstip
   1668 	 *
   1669 	 * REWRITE out rule, SRC=a,DST=b -> SRC=c,DST=d
   1670 	 * - response to incoming packet (d,c)=>(b,a) (OIP_SRC=c,OIP_DST=d)
   1671 	 * - OIP_SRC(c)=nat6_olddstip,          OIP_DST(d)=nat6_oldsrcip
   1672 	 *=> OIP_SRC(b)=nat6_newdstip,          OIP_DST(a)=nat6_newsrcip
   1673 	 *
   1674 	 * REWRITE in rule, SRC=a,DST=b -> SRC=c,DST=d
   1675 	 * - response to incoming packet (a,b)=>(c,d) (OIP_SRC=b,OIP_DST=a)
   1676 	 * - OIP_SRC(b)=nat6_newsrcip,          OIP_DST(a)=nat6_newdstip
   1677 	 *=> OIP_SRC(a)=nat6_oldsrcip,          OIP_DST(c)=nat6_olddstip
   1678 	 */
   1679 
   1680 	if (((fin->fin_out == 0) && ((nat->nat_redir & NAT_MAP) != 0)) ||
   1681 	    ((fin->fin_out == 1) && ((nat->nat_redir & NAT_REDIRECT) != 0))) {
   1682 		a1 = nat->nat_osrc6;
   1683 		a4.in6 = oip6->ip6_src;
   1684 		a3 = nat->nat_odst6;
   1685 		a2.in6 = oip6->ip6_dst;
   1686 		oip6->ip6_src = a1.in6;
   1687 		oip6->ip6_dst = a3.in6;
   1688 		odst = 1;
   1689 	} else {
   1690 		a1 = nat->nat_ndst6;
   1691 		a2.in6 = oip6->ip6_dst;
   1692 		a3 = nat->nat_nsrc6;
   1693 		a4.in6 = oip6->ip6_src;
   1694 		oip6->ip6_dst = a3.in6;
   1695 		oip6->ip6_src = a1.in6;
   1696 		odst = 0;
   1697 	}
   1698 
   1699 	sumd = 0;
   1700 	if (IP6_NEQ(&a3, &a2) || IP6_NEQ(&a1, &a4)) {
   1701 		if (IP6_GT(&a3, &a2)) {
   1702 			sumd = ipf_nat6_ip6subtract(&a2, &a3);
   1703 			sumd--;
   1704 		} else {
   1705 			sumd = ipf_nat6_ip6subtract(&a2, &a3);
   1706 		}
   1707 		if (IP6_GT(&a1, &a4)) {
   1708 			sumd += ipf_nat6_ip6subtract(&a4, &a1);
   1709 			sumd--;
   1710 		} else {
   1711 			sumd += ipf_nat6_ip6subtract(&a4, &a1);
   1712 		}
   1713 		sumd = ~sumd;
   1714 	}
   1715 
   1716 	sumd2 = sumd;
   1717 	sum1 = 0;
   1718 	sum2 = 0;
   1719 
   1720 	/*
   1721 	 * Fix UDP pseudo header checksum to compensate for the
   1722 	 * IP address change.
   1723 	 */
   1724 	if (((flags & IPN_TCPUDP) != 0) && (dlen >= 4)) {
   1725 		u_32_t sum3, sum4;
   1726 		/*
   1727 		 * Step 2 :
   1728 		 * For offending TCP/UDP IP packets, translate the ports as
   1729 		 * well, based on the NAT specification. Of course such
   1730 		 * a change may be reflected in the ICMP checksum as well.
   1731 		 *
   1732 		 * Since the port fields are part of the TCP/UDP checksum
   1733 		 * of the offending IP packet, you need to adjust that checksum
   1734 		 * as well... except that the change in the port numbers should
   1735 		 * be offset by the checksum change.  However, the TCP/UDP
   1736 		 * checksum will also need to change if there has been an
   1737 		 * IP address change.
   1738 		 */
   1739 		if (odst == 1) {
   1740 			sum1 = ntohs(nat->nat_osport);
   1741 			sum4 = ntohs(tcp->th_sport);
   1742 			sum3 = ntohs(nat->nat_odport);
   1743 			sum2 = ntohs(tcp->th_dport);
   1744 
   1745 			tcp->th_sport = htons(sum1);
   1746 			tcp->th_dport = htons(sum3);
   1747 		} else {
   1748 			sum1 = ntohs(nat->nat_ndport);
   1749 			sum2 = ntohs(tcp->th_dport);
   1750 			sum3 = ntohs(nat->nat_nsport);
   1751 			sum4 = ntohs(tcp->th_sport);
   1752 
   1753 			tcp->th_dport = htons(sum3);
   1754 			tcp->th_sport = htons(sum1);
   1755 		}
   1756 		sumd += sum1 - sum4;
   1757 		sumd += sum3 - sum2;
   1758 
   1759 		if (sumd != 0 || sumd2 != 0) {
   1760 			/*
   1761 			 * At this point, sumd is the delta to apply to the
   1762 			 * TCP/UDP header, given the changes in both the IP
   1763 			 * address and the ports and sumd2 is the delta to
   1764 			 * apply to the ICMP header, given the IP address
   1765 			 * change delta that may need to be applied to the
   1766 			 * TCP/UDP checksum instead.
   1767 			 *
   1768 			 * If we will both the IP and TCP/UDP checksums
   1769 			 * then the ICMP checksum changes by the address
   1770 			 * delta applied to the TCP/UDP checksum.  If we
   1771 			 * do not change the TCP/UDP checksum them we
   1772 			 * apply the delta in ports to the ICMP checksum.
   1773 			 */
   1774 			if (oip6->ip6_nxt == IPPROTO_UDP) {
   1775 				if ((dlen >= 8) && (*csump != 0)) {
   1776 					ipf_fix_datacksum(csump, sumd);
   1777 				} else {
   1778 					sumd2 = sum4 - sum1;
   1779 					if (sum1 > sum4)
   1780 						sumd2--;
   1781 					sumd2 += sum2 - sum3;
   1782 					if (sum3 > sum2)
   1783 						sumd2--;
   1784 				}
   1785 			} else if (oip6->ip6_nxt == IPPROTO_TCP) {
   1786 				if (dlen >= 18) {
   1787 					ipf_fix_datacksum(csump, sumd);
   1788 				} else {
   1789 					sumd2 = sum4 - sum1;
   1790 					if (sum1 > sum4)
   1791 						sumd2--;
   1792 					sumd2 += sum2 - sum3;
   1793 					if (sum3 > sum2)
   1794 						sumd2--;
   1795 				}
   1796 			}
   1797 			if (sumd2 != 0) {
   1798 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   1799 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   1800 				sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
   1801 				ipf_fix_incksum(0, &icmp6->icmp6_cksum,
   1802 						sumd2, 0);
   1803 			}
   1804 		}
   1805 	} else if (((flags & IPN_ICMPQUERY) != 0) && (dlen >= 8)) {
   1806 		struct icmp6_hdr *orgicmp;
   1807 
   1808 		/*
   1809 		 * XXX - what if this is bogus hl and we go off the end ?
   1810 		 * In this case, ipf_nat6_icmperrorlookup() will have
   1811 		 * returned NULL.
   1812 		 */
   1813 		orgicmp = (struct icmp6_hdr *)dp;
   1814 
   1815 		if (odst == 1) {
   1816 			if (orgicmp->icmp6_id != nat->nat_osport) {
   1817 
   1818 				/*
   1819 				 * Fix ICMP checksum (of the offening ICMP
   1820 				 * query packet) to compensate the change
   1821 				 * in the ICMP id of the offending ICMP
   1822 				 * packet.
   1823 				 *
   1824 				 * Since you modify orgicmp->icmp6_id with
   1825 				 * a delta (say x) and you compensate that
   1826 				 * in origicmp->icmp6_cksum with a delta
   1827 				 * minus x, you don't have to adjust the
   1828 				 * overall icmp->icmp6_cksum
   1829 				 */
   1830 				sum1 = ntohs(orgicmp->icmp6_id);
   1831 				sum2 = ntohs(nat->nat_osport);
   1832 				CALC_SUMD(sum1, sum2, sumd);
   1833 				orgicmp->icmp6_id = nat->nat_oicmpid;
   1834 				ipf_fix_datacksum(&orgicmp->icmp6_cksum, sumd);
   1835 			}
   1836 		} /* nat6_dir == NAT_INBOUND is impossible for icmp queries */
   1837 	}
   1838 	return nat;
   1839 }
   1840 
   1841 
   1842 /*
   1843  *       MAP-IN    MAP-OUT   RDR-IN   RDR-OUT
   1844  * osrc    X       == src    == src      X
   1845  * odst    X       == dst    == dst      X
   1846  * nsrc  == dst      X         X      == dst
   1847  * ndst  == src      X         X      == src
   1848  * MAP = NAT_OUTBOUND, RDR = NAT_INBOUND
   1849  */
   1850 /*
   1851  * NB: these lookups don't lock access to the list, it assumed that it has
   1852  * already been done!
   1853  */
   1854 /* ------------------------------------------------------------------------ */
   1855 /* Function:    ipf_nat6_inlookup                                           */
   1856 /* Returns:     nat6_t*   - NULL == no match,                               */
   1857 /*                          else pointer to matching NAT entry              */
   1858 /* Parameters:  fin(I)    - pointer to packet information                   */
   1859 /*              flags(I)  - NAT flags for this packet                       */
   1860 /*              p(I)      - protocol for this packet                        */
   1861 /*              src(I)    - source IP address                               */
   1862 /*              mapdst(I) - destination IP address                          */
   1863 /*                                                                          */
   1864 /* Lookup a nat entry based on the mapped destination ip address/port and   */
   1865 /* real source address/port.  We use this lookup when receiving a packet,   */
   1866 /* we're looking for a table entry, based on the destination address.       */
   1867 /*                                                                          */
   1868 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   1869 /*                                                                          */
   1870 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   1871 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   1872 /*                                                                          */
   1873 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   1874 /*            the packet is of said protocol                                */
   1875 /* ------------------------------------------------------------------------ */
   1876 nat_t *
   1877 ipf_nat6_inlookup(fr_info_t *fin, u_int flags, u_int p, struct in6_addr *src,
   1878     struct in6_addr *mapdst)
   1879 {
   1880 	ipf_main_softc_t *softc = fin->fin_main_soft;
   1881 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   1882 	u_short sport, dport;
   1883 	grehdr_t *gre;
   1884 	ipnat_t *ipn;
   1885 	u_int sflags;
   1886 	nat_t *nat;
   1887 	int nflags;
   1888 	i6addr_t dst;
   1889 	void *ifp;
   1890 	u_int hv;
   1891 
   1892 	ifp = fin->fin_ifp;
   1893 	sport = 0;
   1894 	dport = 0;
   1895 	gre = NULL;
   1896 	dst.in6 = *mapdst;
   1897 	sflags = flags & NAT_TCPUDPICMP;
   1898 
   1899 	switch (p)
   1900 	{
   1901 	case IPPROTO_TCP :
   1902 	case IPPROTO_UDP :
   1903 		sport = htons(fin->fin_data[0]);
   1904 		dport = htons(fin->fin_data[1]);
   1905 		break;
   1906 	case IPPROTO_ICMPV6 :
   1907 		if (flags & IPN_ICMPERR)
   1908 			sport = fin->fin_data[1];
   1909 		else
   1910 			dport = fin->fin_data[1];
   1911 		break;
   1912 	default :
   1913 		break;
   1914 	}
   1915 
   1916 
   1917 	if ((flags & SI_WILDP) != 0)
   1918 		goto find_in_wild_ports;
   1919 
   1920 	hv = NAT_HASH_FN6(&dst, dport, 0xffffffff);
   1921 	hv = NAT_HASH_FN6(src, hv + sport, softn->ipf_nat_table_sz);
   1922 	nat = softn->ipf_nat_table[1][hv];
   1923 	/* TRACE dst, dport, src, sport, hv, nat */
   1924 
   1925 	for (; nat; nat = nat->nat_hnext[1]) {
   1926 		if (nat->nat_ifps[0] != NULL) {
   1927 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   1928 				continue;
   1929 		}
   1930 
   1931 		if (nat->nat_pr[0] != p)
   1932 			continue;
   1933 
   1934 		switch (nat->nat_dir)
   1935 		{
   1936 		case NAT_INBOUND :
   1937 			if (nat->nat_v[0] != 6)
   1938 				continue;
   1939 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   1940 			    IP6_NEQ(&nat->nat_odst6, &dst))
   1941 				continue;
   1942 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1943 				if (nat->nat_osport != sport)
   1944 					continue;
   1945 				if (nat->nat_odport != dport)
   1946 					continue;
   1947 
   1948 			} else if (p == IPPROTO_ICMPV6) {
   1949 				if (nat->nat_osport != dport) {
   1950 					continue;
   1951 				}
   1952 			}
   1953 			break;
   1954 		case NAT_OUTBOUND :
   1955 			if (nat->nat_v[1] != 6)
   1956 				continue;
   1957 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   1958 			    IP6_NEQ(&nat->nat_nsrc6, &dst))
   1959 				continue;
   1960 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1961 				if (nat->nat_ndport != sport)
   1962 					continue;
   1963 				if (nat->nat_nsport != dport)
   1964 					continue;
   1965 
   1966 			} else if (p == IPPROTO_ICMPV6) {
   1967 				if (nat->nat_osport != dport) {
   1968 					continue;
   1969 				}
   1970 			}
   1971 			break;
   1972 		}
   1973 
   1974 
   1975 		if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   1976 			ipn = nat->nat_ptr;
   1977 #ifdef IPF_V6_PROXIES
   1978 			if ((ipn != NULL) && (nat->nat_aps != NULL))
   1979 				if (appr_match(fin, nat) != 0)
   1980 					continue;
   1981 #endif
   1982 		}
   1983 		if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   1984 			nat->nat_ifps[0] = ifp;
   1985 			nat->nat_mtu[0] = GETIFMTU_6(ifp);
   1986 		}
   1987 		return nat;
   1988 	}
   1989 
   1990 	/*
   1991 	 * So if we didn't find it but there are wildcard members in the hash
   1992 	 * table, go back and look for them.  We do this search and update here
   1993 	 * because it is modifying the NAT table and we want to do this only
   1994 	 * for the first packet that matches.  The exception, of course, is
   1995 	 * for "dummy" (FI_IGNORE) lookups.
   1996 	 */
   1997 find_in_wild_ports:
   1998 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   1999 		NBUMPSIDE6DX(0, ns_lookup_miss, ns_lookup_miss_1);
   2000 		return NULL;
   2001 	}
   2002 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   2003 		NBUMPSIDE6D(0, ns_lookup_nowild);
   2004 		return NULL;
   2005 	}
   2006 
   2007 	RWLOCK_EXIT(&softc->ipf_nat);
   2008 
   2009 	hv = NAT_HASH_FN6(&dst, 0, 0xffffffff);
   2010 	hv = NAT_HASH_FN6(src, hv, softn->ipf_nat_table_sz);
   2011 	WRITE_ENTER(&softc->ipf_nat);
   2012 
   2013 	nat = softn->ipf_nat_table[1][hv];
   2014 	/* TRACE dst, src, hv, nat */
   2015 	for (; nat; nat = nat->nat_hnext[1]) {
   2016 		if (nat->nat_ifps[0] != NULL) {
   2017 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
   2018 				continue;
   2019 		}
   2020 
   2021 		if (nat->nat_pr[0] != fin->fin_p)
   2022 			continue;
   2023 
   2024 		switch (nat->nat_dir)
   2025 		{
   2026 		case NAT_INBOUND :
   2027 			if (nat->nat_v[0] != 6)
   2028 				continue;
   2029 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   2030 			    IP6_NEQ(&nat->nat_odst6, &dst))
   2031 				continue;
   2032 			break;
   2033 		case NAT_OUTBOUND :
   2034 			if (nat->nat_v[1] != 6)
   2035 				continue;
   2036 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   2037 			    IP6_NEQ(&nat->nat_nsrc6, &dst))
   2038 				continue;
   2039 			break;
   2040 		}
   2041 
   2042 		nflags = nat->nat_flags;
   2043 		if (!(nflags & (NAT_TCPUDP|SI_WILDP)))
   2044 			continue;
   2045 
   2046 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nflags,
   2047 				   NAT_INBOUND) == 1) {
   2048 			if ((fin->fin_flx & FI_IGNORE) != 0)
   2049 				break;
   2050 			if ((nflags & SI_CLONE) != 0) {
   2051 				nat = ipf_nat_clone(fin, nat);
   2052 				if (nat == NULL)
   2053 					break;
   2054 			} else {
   2055 				MUTEX_ENTER(&softn->ipf_nat_new);
   2056 				softn->ipf_nat_stats.ns_wilds--;
   2057 				MUTEX_EXIT(&softn->ipf_nat_new);
   2058 			}
   2059 
   2060 			if (nat->nat_dir == NAT_INBOUND) {
   2061 				if (nat->nat_osport == 0) {
   2062 					nat->nat_osport = sport;
   2063 					nat->nat_nsport = sport;
   2064 				}
   2065 				if (nat->nat_odport == 0) {
   2066 					nat->nat_odport = dport;
   2067 					nat->nat_ndport = dport;
   2068 				}
   2069 			} else {
   2070 				if (nat->nat_osport == 0) {
   2071 					nat->nat_osport = dport;
   2072 					nat->nat_nsport = dport;
   2073 				}
   2074 				if (nat->nat_odport == 0) {
   2075 					nat->nat_odport = sport;
   2076 					nat->nat_ndport = sport;
   2077 				}
   2078 			}
   2079 			if ((nat->nat_ifps[0] == NULL) && (ifp != NULL)) {
   2080 				nat->nat_ifps[0] = ifp;
   2081 				nat->nat_mtu[0] = GETIFMTU_6(ifp);
   2082 			}
   2083 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   2084 			ipf_nat6_tabmove(softn, nat);
   2085 			break;
   2086 		}
   2087 	}
   2088 
   2089 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   2090 
   2091 	if (nat == NULL) {
   2092 		NBUMPSIDE6DX(0, ns_lookup_miss, ns_lookup_miss_2);
   2093 	}
   2094 	return nat;
   2095 }
   2096 
   2097 
   2098 /* ------------------------------------------------------------------------ */
   2099 /* Function:    ipf_nat6_tabmove                                            */
   2100 /* Returns:     Nil                                                         */
   2101 /* Parameters:  nat(I) - pointer to NAT structure                           */
   2102 /* Write Lock:  ipf_nat                                                     */
   2103 /*                                                                          */
   2104 /* This function is only called for TCP/UDP NAT table entries where the     */
   2105 /* original was placed in the table without hashing on the ports and we now */
   2106 /* want to include hashing on port numbers.                                 */
   2107 /* ------------------------------------------------------------------------ */
   2108 static void
   2109 ipf_nat6_tabmove(ipf_nat_softc_t *softn, nat_t *nat)
   2110 {
   2111 	nat_t **natp;
   2112 	u_int hv0, hv1;
   2113 
   2114 	if (nat->nat_flags & SI_CLONE)
   2115 		return;
   2116 
   2117 	/*
   2118 	 * Remove the NAT entry from the old location
   2119 	 */
   2120 	if (nat->nat_hnext[0])
   2121 		nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
   2122 	*nat->nat_phnext[0] = nat->nat_hnext[0];
   2123 	softn->ipf_nat_stats.ns_side[0].ns_bucketlen[nat->nat_hv[0]]--;
   2124 
   2125 	if (nat->nat_hnext[1])
   2126 		nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
   2127 	*nat->nat_phnext[1] = nat->nat_hnext[1];
   2128 	softn->ipf_nat_stats.ns_side[1].ns_bucketlen[nat->nat_hv[1]]--;
   2129 
   2130 	/*
   2131 	 * Add into the NAT table in the new position
   2132 	 */
   2133 	hv0 = NAT_HASH_FN6(&nat->nat_osrc6, nat->nat_osport, 0xffffffff);
   2134 	hv0 = NAT_HASH_FN6(&nat->nat_odst6, hv0 + nat->nat_odport,
   2135 			   softn->ipf_nat_table_sz);
   2136 	hv1 = NAT_HASH_FN6(&nat->nat_nsrc6, nat->nat_nsport, 0xffffffff);
   2137 	hv1 = NAT_HASH_FN6(&nat->nat_ndst6, hv1 + nat->nat_ndport,
   2138 			   softn->ipf_nat_table_sz);
   2139 
   2140 	if (nat->nat_dir == NAT_INBOUND || nat->nat_dir == NAT_DIVERTIN) {
   2141 		u_int swap;
   2142 
   2143 		swap = hv0;
   2144 		hv0 = hv1;
   2145 		hv1 = swap;
   2146 	}
   2147 
   2148 	/* TRACE nat_osrc6, nat_osport, nat_odst6, nat_odport, hv0 */
   2149 	/* TRACE nat_nsrc6, nat_nsport, nat_ndst6, nat_ndport, hv1 */
   2150 
   2151 	nat->nat_hv[0] = hv0;
   2152 	natp = &softn->ipf_nat_table[0][hv0];
   2153 	if (*natp)
   2154 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
   2155 	nat->nat_phnext[0] = natp;
   2156 	nat->nat_hnext[0] = *natp;
   2157 	*natp = nat;
   2158 	softn->ipf_nat_stats.ns_side[0].ns_bucketlen[hv0]++;
   2159 
   2160 	nat->nat_hv[1] = hv1;
   2161 	natp = &softn->ipf_nat_table[1][hv1];
   2162 	if (*natp)
   2163 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
   2164 	nat->nat_phnext[1] = natp;
   2165 	nat->nat_hnext[1] = *natp;
   2166 	*natp = nat;
   2167 	softn->ipf_nat_stats.ns_side[1].ns_bucketlen[hv1]++;
   2168 }
   2169 
   2170 
   2171 /* ------------------------------------------------------------------------ */
   2172 /* Function:    ipf_nat6_outlookup                                          */
   2173 /* Returns:     nat6_t*  - NULL == no match,                                */
   2174 /*                         else pointer to matching NAT entry               */
   2175 /* Parameters:  fin(I)   - pointer to packet information                    */
   2176 /*              flags(I) - NAT flags for this packet                        */
   2177 /*              p(I)     - protocol for this packet                         */
   2178 /*              src(I)   - source IP address                                */
   2179 /*              dst(I)   - destination IP address                           */
   2180 /*              rw(I)    - 1 == write lock on  held, 0 == read lock.        */
   2181 /*                                                                          */
   2182 /* Lookup a nat entry based on the source 'real' ip address/port and        */
   2183 /* destination address/port.  We use this lookup when sending a packet out, */
   2184 /* we're looking for a table entry, based on the source address.            */
   2185 /*                                                                          */
   2186 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
   2187 /*                                                                          */
   2188 /* NOTE: IT IS ASSUMED THAT  IS ONLY HELD WITH A READ LOCK WHEN             */
   2189 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
   2190 /*                                                                          */
   2191 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
   2192 /*            the packet is of said protocol                                */
   2193 /* ------------------------------------------------------------------------ */
   2194 nat_t *
   2195 ipf_nat6_outlookup(fr_info_t *fin, u_int flags, u_int p, struct in6_addr *src,
   2196     struct in6_addr *dst)
   2197 {
   2198 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2199 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2200 	u_short sport, dport;
   2201 	u_int sflags;
   2202 	ipnat_t *ipn;
   2203 	nat_t *nat;
   2204 	void *ifp;
   2205 	u_int hv;
   2206 
   2207 	ifp = fin->fin_ifp;
   2208 	sflags = flags & IPN_TCPUDPICMP;
   2209 	sport = 0;
   2210 	dport = 0;
   2211 
   2212 	switch (p)
   2213 	{
   2214 	case IPPROTO_TCP :
   2215 	case IPPROTO_UDP :
   2216 		sport = htons(fin->fin_data[0]);
   2217 		dport = htons(fin->fin_data[1]);
   2218 		break;
   2219 	case IPPROTO_ICMPV6 :
   2220 		if (flags & IPN_ICMPERR)
   2221 			sport = fin->fin_data[1];
   2222 		else
   2223 			dport = fin->fin_data[1];
   2224 		break;
   2225 	default :
   2226 		break;
   2227 	}
   2228 
   2229 	if ((flags & SI_WILDP) != 0)
   2230 		goto find_out_wild_ports;
   2231 
   2232 	hv = NAT_HASH_FN6(src, sport, 0xffffffff);
   2233 	hv = NAT_HASH_FN6(dst, hv + dport, softn->ipf_nat_table_sz);
   2234 	nat = softn->ipf_nat_table[0][hv];
   2235 
   2236 	/* TRACE src, sport, dst, dport, hv, nat */
   2237 
   2238 	for (; nat; nat = nat->nat_hnext[0]) {
   2239 		if (nat->nat_ifps[1] != NULL) {
   2240 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   2241 				continue;
   2242 		}
   2243 
   2244 		if (nat->nat_pr[1] != p)
   2245 			continue;
   2246 
   2247 		switch (nat->nat_dir)
   2248 		{
   2249 		case NAT_INBOUND :
   2250 			if (nat->nat_v[1] != 6)
   2251 				continue;
   2252 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   2253 			    IP6_NEQ(&nat->nat_nsrc6, dst))
   2254 				continue;
   2255 
   2256 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   2257 				if (nat->nat_ndport != sport)
   2258 					continue;
   2259 				if (nat->nat_nsport != dport)
   2260 					continue;
   2261 
   2262 			} else if (p == IPPROTO_ICMPV6) {
   2263 				if (nat->nat_osport != dport) {
   2264 					continue;
   2265 				}
   2266 			}
   2267 			break;
   2268 		case NAT_OUTBOUND :
   2269 			if (nat->nat_v[0] != 6)
   2270 				continue;
   2271 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   2272 			    IP6_NEQ(&nat->nat_odst6, dst))
   2273 				continue;
   2274 
   2275 			if ((nat->nat_flags & IPN_TCPUDP) != 0) {
   2276 				if (nat->nat_odport != dport)
   2277 					continue;
   2278 				if (nat->nat_osport != sport)
   2279 					continue;
   2280 
   2281 			} else if (p == IPPROTO_ICMPV6) {
   2282 				if (nat->nat_osport != dport) {
   2283 					continue;
   2284 				}
   2285 			}
   2286 			break;
   2287 		}
   2288 
   2289 		ipn = nat->nat_ptr;
   2290 #ifdef IPF_V6_PROXIES
   2291 		if ((ipn != NULL) && (nat->nat_aps != NULL))
   2292 			if (appr_match(fin, nat) != 0)
   2293 				continue;
   2294 #endif
   2295 
   2296 		if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   2297 			nat->nat_ifps[1] = ifp;
   2298 			nat->nat_mtu[1] = GETIFMTU_6(ifp);
   2299 		}
   2300 		return nat;
   2301 	}
   2302 
   2303 	/*
   2304 	 * So if we didn't find it but there are wildcard members in the hash
   2305 	 * table, go back and look for them.  We do this search and update here
   2306 	 * because it is modifying the NAT table and we want to do this only
   2307 	 * for the first packet that matches.  The exception, of course, is
   2308 	 * for "dummy" (FI_IGNORE) lookups.
   2309 	 */
   2310 find_out_wild_ports:
   2311 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH)) {
   2312 		NBUMPSIDE6DX(1, ns_lookup_miss, ns_lookup_miss_3);
   2313 		return NULL;
   2314 	}
   2315 	if (softn->ipf_nat_stats.ns_wilds == 0 || (fin->fin_flx & FI_NOWILD)) {
   2316 		NBUMPSIDE6D(1, ns_lookup_nowild);
   2317 		return NULL;
   2318 	}
   2319 
   2320 	RWLOCK_EXIT(&softc->ipf_nat);
   2321 
   2322 	hv = NAT_HASH_FN6(src, 0, 0xffffffff);
   2323 	hv = NAT_HASH_FN6(dst, hv, softn->ipf_nat_table_sz);
   2324 
   2325 	WRITE_ENTER(&softc->ipf_nat);
   2326 
   2327 	nat = softn->ipf_nat_table[0][hv];
   2328 	for (; nat; nat = nat->nat_hnext[0]) {
   2329 		if (nat->nat_ifps[1] != NULL) {
   2330 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
   2331 				continue;
   2332 		}
   2333 
   2334 		if (nat->nat_pr[1] != fin->fin_p)
   2335 			continue;
   2336 
   2337 		switch (nat->nat_dir)
   2338 		{
   2339 		case NAT_INBOUND :
   2340 			if (nat->nat_v[1] != 6)
   2341 				continue;
   2342 			if (IP6_NEQ(&nat->nat_ndst6, src) ||
   2343 			    IP6_NEQ(&nat->nat_nsrc6, dst))
   2344 				continue;
   2345 			break;
   2346 		case NAT_OUTBOUND :
   2347 			if (nat->nat_v[0] != 6)
   2348 			continue;
   2349 			if (IP6_NEQ(&nat->nat_osrc6, src) ||
   2350 			    IP6_NEQ(&nat->nat_odst6, dst))
   2351 				continue;
   2352 			break;
   2353 		}
   2354 
   2355 		if (!(nat->nat_flags & (NAT_TCPUDP|SI_WILDP)))
   2356 			continue;
   2357 
   2358 		if (ipf_nat_wildok(nat, (int)sport, (int)dport, nat->nat_flags,
   2359 				   NAT_OUTBOUND) == 1) {
   2360 			if ((fin->fin_flx & FI_IGNORE) != 0)
   2361 				break;
   2362 			if ((nat->nat_flags & SI_CLONE) != 0) {
   2363 				nat = ipf_nat_clone(fin, nat);
   2364 				if (nat == NULL)
   2365 					break;
   2366 			} else {
   2367 				MUTEX_ENTER(&softn->ipf_nat_new);
   2368 				softn->ipf_nat_stats.ns_wilds--;
   2369 				MUTEX_EXIT(&softn->ipf_nat_new);
   2370 			}
   2371 
   2372 			if (nat->nat_dir == NAT_OUTBOUND) {
   2373 				if (nat->nat_osport == 0) {
   2374 					nat->nat_osport = sport;
   2375 					nat->nat_nsport = sport;
   2376 				}
   2377 				if (nat->nat_odport == 0) {
   2378 					nat->nat_odport = dport;
   2379 					nat->nat_ndport = dport;
   2380 				}
   2381 			} else {
   2382 				if (nat->nat_osport == 0) {
   2383 					nat->nat_osport = dport;
   2384 					nat->nat_nsport = dport;
   2385 				}
   2386 				if (nat->nat_odport == 0) {
   2387 					nat->nat_odport = sport;
   2388 					nat->nat_ndport = sport;
   2389 				}
   2390 			}
   2391 			if ((nat->nat_ifps[1] == NULL) && (ifp != NULL)) {
   2392 				nat->nat_ifps[1] = ifp;
   2393 				nat->nat_mtu[1] = GETIFMTU_6(ifp);
   2394 			}
   2395 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
   2396 			ipf_nat6_tabmove(softn, nat);
   2397 			break;
   2398 		}
   2399 	}
   2400 
   2401 	MUTEX_DOWNGRADE(&softc->ipf_nat);
   2402 
   2403 	if (nat == NULL) {
   2404 		NBUMPSIDE6DX(1, ns_lookup_miss, ns_lookup_miss_4);
   2405 	}
   2406 	return nat;
   2407 }
   2408 
   2409 
   2410 /* ------------------------------------------------------------------------ */
   2411 /* Function:    ipf_nat6_lookupredir                                        */
   2412 /* Returns:     nat6_t* - NULL == no match,                                 */
   2413 /*                       else pointer to matching NAT entry                 */
   2414 /* Parameters:  np(I) - pointer to description of packet to find NAT table  */
   2415 /*                      entry for.                                          */
   2416 /*                                                                          */
   2417 /* Lookup the NAT tables to search for a matching redirect                  */
   2418 /* The contents of natlookup_t should imitate those found in a packet that  */
   2419 /* would be translated - ie a packet coming in for RDR or going out for MAP.*/
   2420 /* We can do the lookup in one of two ways, imitating an inbound or         */
   2421 /* outbound  packet.  By default we assume outbound, unless IPN_IN is set.  */
   2422 /* For IN, the fields are set as follows:                                   */
   2423 /*     nl_real* = source information                                        */
   2424 /*     nl_out* = destination information (translated)                       */
   2425 /* For an out packet, the fields are set like this:                         */
   2426 /*     nl_in* = source information (untranslated)                           */
   2427 /*     nl_out* = destination information (translated)                       */
   2428 /* ------------------------------------------------------------------------ */
   2429 nat_t *
   2430 ipf_nat6_lookupredir(natlookup_t *np)
   2431 {
   2432 	fr_info_t fi;
   2433 	nat_t *nat;
   2434 
   2435 	bzero((char *)&fi, sizeof(fi));
   2436 	if (np->nl_flags & IPN_IN) {
   2437 		fi.fin_data[0] = ntohs(np->nl_realport);
   2438 		fi.fin_data[1] = ntohs(np->nl_outport);
   2439 	} else {
   2440 		fi.fin_data[0] = ntohs(np->nl_inport);
   2441 		fi.fin_data[1] = ntohs(np->nl_outport);
   2442 	}
   2443 	if (np->nl_flags & IPN_TCP)
   2444 		fi.fin_p = IPPROTO_TCP;
   2445 	else if (np->nl_flags & IPN_UDP)
   2446 		fi.fin_p = IPPROTO_UDP;
   2447 	else if (np->nl_flags & (IPN_ICMPERR|IPN_ICMPQUERY))
   2448 		fi.fin_p = IPPROTO_ICMPV6;
   2449 
   2450 	/*
   2451 	 * We can do two sorts of lookups:
   2452 	 * - IPN_IN: we have the `real' and `out' address, look for `in'.
   2453 	 * - default: we have the `in' and `out' address, look for `real'.
   2454 	 */
   2455 	if (np->nl_flags & IPN_IN) {
   2456 		if ((nat = ipf_nat6_inlookup(&fi, np->nl_flags, fi.fin_p,
   2457 					     &np->nl_realip6,
   2458 					     &np->nl_outip6))) {
   2459 			np->nl_inip6 = nat->nat_odst6.in6;
   2460 			np->nl_inport = nat->nat_odport;
   2461 		}
   2462 	} else {
   2463 		/*
   2464 		 * If nl_inip is non null, this is a lookup based on the real
   2465 		 * ip address. Else, we use the fake.
   2466 		 */
   2467 		if ((nat = ipf_nat6_outlookup(&fi, np->nl_flags, fi.fin_p,
   2468 					      &np->nl_inip6, &np->nl_outip6))) {
   2469 
   2470 			if ((np->nl_flags & IPN_FINDFORWARD) != 0) {
   2471 				fr_info_t fin;
   2472 				bzero((char *)&fin, sizeof(fin));
   2473 				fin.fin_p = nat->nat_pr[0];
   2474 				fin.fin_data[0] = ntohs(nat->nat_ndport);
   2475 				fin.fin_data[1] = ntohs(nat->nat_nsport);
   2476 				if (ipf_nat6_inlookup(&fin, np->nl_flags,
   2477 						     fin.fin_p,
   2478 						     &nat->nat_ndst6.in6,
   2479 						     &nat->nat_nsrc6.in6) !=
   2480 				    NULL) {
   2481 					np->nl_flags &= ~IPN_FINDFORWARD;
   2482 				}
   2483 			}
   2484 
   2485 			np->nl_realip6 = nat->nat_ndst6.in6;
   2486 			np->nl_realport = nat->nat_ndport;
   2487 		}
   2488  	}
   2489 
   2490 	return nat;
   2491 }
   2492 
   2493 
   2494 /* ------------------------------------------------------------------------ */
   2495 /* Function:    ipf_nat6_match                                              */
   2496 /* Returns:     int - 0 == no match, 1 == match                             */
   2497 /* Parameters:  fin(I)   - pointer to packet information                    */
   2498 /*              np(I)    - pointer to NAT rule                              */
   2499 /*                                                                          */
   2500 /* Pull the matching of a packet against a NAT rule out of that complex     */
   2501 /* loop inside ipf_nat6_checkin() and lay it out properly in its own        */
   2502 /* function.                                                                */
   2503 /* ------------------------------------------------------------------------ */
   2504 static int
   2505 ipf_nat6_match(fr_info_t *fin, ipnat_t *np)
   2506 {
   2507 	frtuc_t *ft;
   2508 	int match;
   2509 
   2510 	match = 0;
   2511 	switch (np->in_osrcatype)
   2512 	{
   2513 	case FRI_NORMAL :
   2514 		match = IP6_MASKNEQ(&fin->fin_src6, &np->in_osrcmsk6,
   2515 				    &np->in_osrcip6);
   2516 		break;
   2517 	case FRI_LOOKUP :
   2518 		match = (*np->in_osrcfunc)(fin->fin_main_soft, np->in_osrcptr,
   2519 					   6, &fin->fin_src6, fin->fin_plen);
   2520 		break;
   2521 	}
   2522 	match ^= ((np->in_flags & IPN_NOTSRC) != 0);
   2523 	if (match)
   2524 		return 0;
   2525 
   2526 	match = 0;
   2527 	switch (np->in_odstatype)
   2528 	{
   2529 	case FRI_NORMAL :
   2530 		match = IP6_MASKNEQ(&fin->fin_dst6, &np->in_odstmsk6,
   2531 				    &np->in_odstip6);
   2532 		break;
   2533 	case FRI_LOOKUP :
   2534 		match = (*np->in_odstfunc)(fin->fin_main_soft, np->in_odstptr,
   2535 					   6, &fin->fin_dst6, fin->fin_plen);
   2536 		break;
   2537 	}
   2538 
   2539 	match ^= ((np->in_flags & IPN_NOTDST) != 0);
   2540 	if (match)
   2541 		return 0;
   2542 
   2543 	ft = &np->in_tuc;
   2544 	if (!(fin->fin_flx & FI_TCPUDP) ||
   2545 	    (fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
   2546 		if (ft->ftu_scmp || ft->ftu_dcmp)
   2547 			return 0;
   2548 		return 1;
   2549 	}
   2550 
   2551 	return ipf_tcpudpchk(&fin->fin_fi, ft);
   2552 }
   2553 
   2554 
   2555 /* ------------------------------------------------------------------------ */
   2556 /* Function:    ipf_nat6_checkout                                           */
   2557 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   2558 /*                     0 == no packet translation occurred,                 */
   2559 /*                     1 == packet was successfully translated.             */
   2560 /* Parameters:  fin(I)   - pointer to packet information                    */
   2561 /*              passp(I) - pointer to filtering result flags                */
   2562 /*                                                                          */
   2563 /* Check to see if an outcoming packet should be changed.  ICMP packets are */
   2564 /* first checked to see if they match an existing entry (if an error),      */
   2565 /* otherwise a search of the current NAT table is made.  If neither results */
   2566 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   2567 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   2568 /* packet header(s) as required.                                            */
   2569 /* ------------------------------------------------------------------------ */
   2570 int
   2571 ipf_nat6_checkout(fr_info_t *fin, u_32_t *passp)
   2572 {
   2573 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2574 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2575 	struct icmp6_hdr *icmp6 = NULL;
   2576 	struct ifnet *ifp, *sifp;
   2577 	tcphdr_t *tcp = NULL;
   2578 	int rval, natfailed;
   2579 	ipnat_t *np = NULL;
   2580 	u_int nflags = 0;
   2581 	i6addr_t ipa, iph;
   2582 	int natadd = 1;
   2583 	frentry_t *fr;
   2584 	nat_t *nat;
   2585 
   2586 	if (softn->ipf_nat_stats.ns_rules == 0 || softn->ipf_nat_lock != 0)
   2587 		return 0;
   2588 
   2589 	icmp6 = NULL;
   2590 	natfailed = 0;
   2591 	fr = fin->fin_fr;
   2592 	sifp = fin->fin_ifp;
   2593 	if (fr != NULL) {
   2594 		ifp = fr->fr_tifs[fin->fin_rev].fd_ptr;
   2595 		if ((ifp != NULL) && (ifp != (void *)-1))
   2596 			fin->fin_ifp = ifp;
   2597 	}
   2598 	ifp = fin->fin_ifp;
   2599 
   2600 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   2601 		switch (fin->fin_p)
   2602 		{
   2603 		case IPPROTO_TCP :
   2604 			nflags = IPN_TCP;
   2605 			break;
   2606 		case IPPROTO_UDP :
   2607 			nflags = IPN_UDP;
   2608 			break;
   2609 		case IPPROTO_ICMPV6 :
   2610 			icmp6 = fin->fin_dp;
   2611 
   2612 			/*
   2613 			 * Apart from ECHO request and reply, all other
   2614 			 * informational messages should not be translated
   2615 			 * so as to keep IPv6 working.
   2616 			 */
   2617 			if (icmp6->icmp6_type > ICMP6_ECHO_REPLY)
   2618 				return 0;
   2619 
   2620 			/*
   2621 			 * This is an incoming packet, so the destination is
   2622 			 * the icmp6_id and the source port equals 0
   2623 			 */
   2624 			if ((fin->fin_flx & FI_ICMPQUERY) != 0)
   2625 				nflags = IPN_ICMPQUERY;
   2626 			break;
   2627 		default :
   2628 			break;
   2629 		}
   2630 
   2631 		if ((nflags & IPN_TCPUDP))
   2632 			tcp = fin->fin_dp;
   2633 	}
   2634 
   2635 	ipa = fin->fin_src6;
   2636 
   2637 	READ_ENTER(&softc->ipf_nat);
   2638 
   2639 	if ((fin->fin_p == IPPROTO_ICMPV6) && !(nflags & IPN_ICMPQUERY) &&
   2640 	    (nat = ipf_nat6_icmperror(fin, &nflags, NAT_OUTBOUND)))
   2641 		/*EMPTY*/;
   2642 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   2643 		natadd = 0;
   2644 	else if ((nat = ipf_nat6_outlookup(fin, nflags|NAT_SEARCH,
   2645 					   (u_int)fin->fin_p,
   2646 					   &fin->fin_src6.in6,
   2647 					   &fin->fin_dst6.in6))) {
   2648 		nflags = nat->nat_flags;
   2649 	} else if (fin->fin_off == 0) {
   2650 		u_32_t hv, nmsk = 0;
   2651 		i6addr_t *msk;
   2652 
   2653 		/*
   2654 		 * If there is no current entry in the nat table for this IP#,
   2655 		 * create one for it (if there is a matching rule).
   2656 		 */
   2657 maskloop:
   2658 		msk = &softn->ipf_nat6_map_active_masks[nmsk];
   2659 		IP6_AND(&ipa, msk, &iph);
   2660 		hv = NAT_HASH_FN6(&iph, 0, softn->ipf_nat_maprules_sz);
   2661 		for (np = softn->ipf_nat_map_rules[hv]; np; np = np->in_mnext) {
   2662 			if ((np->in_ifps[1] && (np->in_ifps[1] != ifp)))
   2663 				continue;
   2664 			if (np->in_v[0] != 6)
   2665 				continue;
   2666 			if (np->in_pr[1] && (np->in_pr[1] != fin->fin_p))
   2667 				continue;
   2668 			if ((np->in_flags & IPN_RF) &&
   2669 			    !(np->in_flags & nflags))
   2670 				continue;
   2671 			if (np->in_flags & IPN_FILTER) {
   2672 				switch (ipf_nat6_match(fin, np))
   2673 				{
   2674 				case 0 :
   2675 					continue;
   2676 				case -1 :
   2677 					rval = -1;
   2678 					goto outmatchfail;
   2679 				case 1 :
   2680 				default :
   2681 					break;
   2682 				}
   2683 			} else if (!IP6_MASKEQ(&ipa, &np->in_osrcmsk,
   2684 					       &np->in_osrcip6))
   2685 				continue;
   2686 
   2687 			if ((fr != NULL) &&
   2688 			    !ipf_matchtag(&np->in_tag, &fr->fr_nattag))
   2689 				continue;
   2690 
   2691 #ifdef IPF_V6_PROXIES
   2692 			if (np->in_plabel != -1) {
   2693 				if (((np->in_flags & IPN_FILTER) == 0) &&
   2694 				    (np->in_odport != fin->fin_data[1]))
   2695 					continue;
   2696 				if (appr_ok(fin, tcp, np) == 0)
   2697 					continue;
   2698 			}
   2699 #endif
   2700 
   2701 			if (np->in_flags & IPN_NO) {
   2702 				np->in_hits++;
   2703 				break;
   2704 			}
   2705 
   2706 			MUTEX_ENTER(&softn->ipf_nat_new);
   2707 			nat = ipf_nat6_add(fin, np, NULL, nflags, NAT_OUTBOUND);
   2708 			MUTEX_EXIT(&softn->ipf_nat_new);
   2709 			if (nat != NULL) {
   2710 				np->in_hits++;
   2711 				break;
   2712 			}
   2713 			natfailed = -1;
   2714 		}
   2715 		if ((np == NULL) && (nmsk < softn->ipf_nat6_map_max)) {
   2716 			nmsk++;
   2717 			goto maskloop;
   2718 		}
   2719 	}
   2720 
   2721 	if (nat != NULL) {
   2722 		rval = ipf_nat6_out(fin, nat, natadd, nflags);
   2723 		if (rval == 1) {
   2724 			MUTEX_ENTER(&nat->nat_lock);
   2725 			ipf_nat_update(fin, nat);
   2726 			nat->nat_bytes[1] += fin->fin_plen;
   2727 			nat->nat_pkts[1]++;
   2728 			MUTEX_EXIT(&nat->nat_lock);
   2729 		}
   2730 	} else
   2731 		rval = natfailed;
   2732 outmatchfail:
   2733 	RWLOCK_EXIT(&softc->ipf_nat);
   2734 
   2735 	switch (rval)
   2736 	{
   2737 	case -1 :
   2738 		if (passp != NULL) {
   2739 			NBUMPSIDE6D(1, ns_drop);
   2740 			*passp = FR_BLOCK;
   2741 			fin->fin_reason = FRB_NATV6;
   2742 		}
   2743 		fin->fin_flx |= FI_BADNAT;
   2744 		NBUMPSIDE6D(1, ns_badnat);
   2745 		break;
   2746 	case 0 :
   2747 		NBUMPSIDE6D(1, ns_ignored);
   2748 		break;
   2749 	case 1 :
   2750 		NBUMPSIDE6D(1, ns_translated);
   2751 		break;
   2752 	}
   2753 	fin->fin_ifp = sifp;
   2754 	return rval;
   2755 }
   2756 
   2757 /* ------------------------------------------------------------------------ */
   2758 /* Function:    ipf_nat6_out                                                */
   2759 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   2760 /*                     1 == packet was successfully translated.             */
   2761 /* Parameters:  fin(I)    - pointer to packet information                   */
   2762 /*              nat(I)    - pointer to NAT structure                        */
   2763 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   2764 /*              nflags(I) - NAT flags set for this packet                   */
   2765 /*                                                                          */
   2766 /* Translate a packet coming "out" on an interface.                         */
   2767 /* ------------------------------------------------------------------------ */
   2768 static int
   2769 ipf_nat6_out(fr_info_t *fin, nat_t *nat, int natadd, u_32_t nflags)
   2770 {
   2771 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2772 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2773 	struct icmp6_hdr *icmp6;
   2774 	tcphdr_t *tcp;
   2775 	ipnat_t *np;
   2776 	int skip;
   2777 	int i;
   2778 
   2779 	tcp = NULL;
   2780 	icmp6 = NULL;
   2781 	np = nat->nat_ptr;
   2782 
   2783 	if ((natadd != 0) && (fin->fin_flx & FI_FRAG) && (np != NULL))
   2784 		(void) ipf_frag_natnew(softc, fin, 0, nat);
   2785 
   2786 	/*
   2787 	 * Address assignment is after the checksum modification because
   2788 	 * we are using the address in the packet for determining the
   2789 	 * correct checksum offset (the ICMP error could be coming from
   2790 	 * anyone...)
   2791 	 */
   2792 	switch (nat->nat_dir)
   2793 	{
   2794 	case NAT_OUTBOUND :
   2795 		fin->fin_ip6->ip6_src = nat->nat_nsrc6.in6;
   2796 		fin->fin_src6 = nat->nat_nsrc6;
   2797 		fin->fin_ip6->ip6_dst = nat->nat_ndst6.in6;
   2798 		fin->fin_dst6 = nat->nat_ndst6;
   2799 		break;
   2800 
   2801 	case NAT_INBOUND :
   2802 		fin->fin_ip6->ip6_src = nat->nat_odst6.in6;
   2803 		fin->fin_src6 = nat->nat_ndst6;
   2804 		fin->fin_ip6->ip6_dst = nat->nat_osrc6.in6;
   2805 		fin->fin_dst6 = nat->nat_nsrc6;
   2806 		break;
   2807 
   2808 	case NAT_DIVERTIN :
   2809 	    {
   2810 		mb_t *m;
   2811 
   2812 		skip = ipf_nat6_decap(fin, nat);
   2813 		if (skip <= 0) {
   2814 			NBUMPSIDE6D(1, ns_decap_fail);
   2815 			return -1;
   2816 		}
   2817 
   2818 		m = fin->fin_m;
   2819 
   2820 #if defined(MENTAT) && defined(_KERNEL)
   2821 		m->b_rptr += skip;
   2822 #else
   2823 		m->m_data += skip;
   2824 		m->m_len -= skip;
   2825 
   2826 # ifdef M_PKTHDR
   2827 		if (m->m_flags & M_PKTHDR)
   2828 			m->m_pkthdr.len -= skip;
   2829 # endif
   2830 #endif
   2831 
   2832 		MUTEX_ENTER(&nat->nat_lock);
   2833 		ipf_nat_update(fin, nat);
   2834 		MUTEX_EXIT(&nat->nat_lock);
   2835 		fin->fin_flx |= FI_NATED;
   2836 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   2837 			fin->fin_nattag = &np->in_tag;
   2838 		return 1;
   2839 		/* NOTREACHED */
   2840 	    }
   2841 
   2842 	case NAT_DIVERTOUT :
   2843 	    {
   2844 		udphdr_t *uh;
   2845 		ip6_t *ip6;
   2846 		mb_t *m;
   2847 
   2848 		m = M_DUP(np->in_divmp);
   2849 		if (m == NULL) {
   2850 			NBUMPSIDE6D(1, ns_divert_dup);
   2851 			return -1;
   2852 		}
   2853 
   2854 		ip6 = MTOD(m, ip6_t *);
   2855 
   2856 		ip6->ip6_plen = htons(fin->fin_plen + 8);
   2857 
   2858 		uh = (udphdr_t *)(ip6 + 1);
   2859 		uh->uh_ulen = htons(fin->fin_plen);
   2860 
   2861 		PREP_MB_T(fin, m);
   2862 
   2863 		fin->fin_ip6 = ip6;
   2864 		fin->fin_plen += sizeof(ip6_t) + 8;	/* UDP + new IPv4 hdr */
   2865 		fin->fin_dlen += sizeof(ip6_t) + 8;	/* UDP + old IPv4 hdr */
   2866 
   2867 		nflags &= ~IPN_TCPUDPICMP;
   2868 
   2869 		break;
   2870 	    }
   2871 
   2872 	default :
   2873 		break;
   2874 	}
   2875 
   2876 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   2877 		u_short *csump;
   2878 
   2879 		if ((nat->nat_nsport != 0) && (nflags & IPN_TCPUDP)) {
   2880 			tcp = fin->fin_dp;
   2881 
   2882 			switch (nat->nat_dir)
   2883 			{
   2884 			case NAT_OUTBOUND :
   2885 				tcp->th_sport = nat->nat_nsport;
   2886 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   2887 				tcp->th_dport = nat->nat_ndport;
   2888 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   2889 				break;
   2890 
   2891 			case NAT_INBOUND :
   2892 				tcp->th_sport = nat->nat_odport;
   2893 				fin->fin_data[0] = ntohs(nat->nat_odport);
   2894 				tcp->th_dport = nat->nat_osport;
   2895 				fin->fin_data[1] = ntohs(nat->nat_osport);
   2896 				break;
   2897 			}
   2898 		}
   2899 
   2900 		if ((nat->nat_nsport != 0) && (nflags & IPN_ICMPQUERY)) {
   2901 			icmp6 = fin->fin_dp;
   2902 			icmp6->icmp6_id = nat->nat_nicmpid;
   2903 		}
   2904 
   2905 		csump = ipf_nat_proto(fin, nat, nflags);
   2906 
   2907 		/*
   2908 		 * The above comments do not hold for layer 4 (or higher)
   2909 		 * checksums...
   2910 		 */
   2911 		if (csump != NULL) {
   2912 			if (nat->nat_dir == NAT_OUTBOUND)
   2913 				ipf_fix_outcksum(fin->fin_cksum, csump,
   2914 						 nat->nat_sumd[0],
   2915 						 nat->nat_sumd[1] +
   2916 						 fin->fin_dlen);
   2917 			else
   2918 				ipf_fix_incksum(fin->fin_cksum, csump,
   2919 						nat->nat_sumd[0],
   2920 						nat->nat_sumd[1] +
   2921 						fin->fin_dlen);
   2922 		}
   2923 	}
   2924 
   2925 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   2926 	/* ------------------------------------------------------------- */
   2927 	/* A few quick notes:                                            */
   2928 	/*      Following are test conditions prior to calling the       */
   2929 	/*      ipf_proxy_check routine.                                 */
   2930 	/*                                                               */
   2931 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   2932 	/*      with a redirect rule, we attempt to match the packet's   */
   2933 	/*      source port against in_dport, otherwise we'd compare the */
   2934 	/*      packet's destination.                                    */
   2935 	/* ------------------------------------------------------------- */
   2936 	if ((np != NULL) && (np->in_apr != NULL)) {
   2937 		i = ipf_proxy_check(fin, nat);
   2938 		if (i == 0) {
   2939 			i = 1;
   2940 		} else if (i == -1) {
   2941 			NBUMPSIDE6D(1, ns_ipf_proxy_fail);
   2942 		}
   2943 	} else {
   2944 		i = 1;
   2945 	}
   2946 	fin->fin_flx |= FI_NATED;
   2947 	return i;
   2948 }
   2949 
   2950 
   2951 /* ------------------------------------------------------------------------ */
   2952 /* Function:    ipf_nat6_checkin                                            */
   2953 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   2954 /*                     0 == no packet translation occurred,                 */
   2955 /*                     1 == packet was successfully translated.             */
   2956 /* Parameters:  fin(I)   - pointer to packet information                    */
   2957 /*              passp(I) - pointer to filtering result flags                */
   2958 /*                                                                          */
   2959 /* Check to see if an incoming packet should be changed.  ICMP packets are  */
   2960 /* first checked to see if they match an existing entry (if an error),      */
   2961 /* otherwise a search of the current NAT table is made.  If neither results */
   2962 /* in a match then a search for a matching NAT rule is made.  Create a new  */
   2963 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
   2964 /* packet header(s) as required.                                            */
   2965 /* ------------------------------------------------------------------------ */
   2966 int
   2967 ipf_nat6_checkin(fr_info_t *fin, u_32_t *passp)
   2968 {
   2969 	ipf_main_softc_t *softc = fin->fin_main_soft;
   2970 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   2971 	struct icmp6_hdr *icmp6;
   2972 	u_int nflags, natadd;
   2973 	int rval, natfailed;
   2974 	struct ifnet *ifp;
   2975 	i6addr_t ipa, iph;
   2976 	tcphdr_t *tcp;
   2977 	u_short dport;
   2978 	ipnat_t *np;
   2979 	nat_t *nat;
   2980 
   2981 	if (softn->ipf_nat_stats.ns_rules == 0 || softn->ipf_nat_lock != 0)
   2982 		return 0;
   2983 
   2984 	tcp = NULL;
   2985 	icmp6 = NULL;
   2986 	dport = 0;
   2987 	natadd = 1;
   2988 	nflags = 0;
   2989 	natfailed = 0;
   2990 	ifp = fin->fin_ifp;
   2991 
   2992 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   2993 		switch (fin->fin_p)
   2994 		{
   2995 		case IPPROTO_TCP :
   2996 			nflags = IPN_TCP;
   2997 			break;
   2998 		case IPPROTO_UDP :
   2999 			nflags = IPN_UDP;
   3000 			break;
   3001 		case IPPROTO_ICMPV6 :
   3002 			icmp6 = fin->fin_dp;
   3003 
   3004 			/*
   3005 			 * Apart from ECHO request and reply, all other
   3006 			 * informational messages should not be translated
   3007 			 * so as to keep IPv6 working.
   3008 			 */
   3009 			if (icmp6->icmp6_type > ICMP6_ECHO_REPLY)
   3010 				return 0;
   3011 
   3012 			/*
   3013 			 * This is an incoming packet, so the destination is
   3014 			 * the icmp6_id and the source port equals 0
   3015 			 */
   3016 			if ((fin->fin_flx & FI_ICMPQUERY) != 0) {
   3017 				nflags = IPN_ICMPQUERY;
   3018 				dport = icmp6->icmp6_id;
   3019 			} break;
   3020 		default :
   3021 			break;
   3022 		}
   3023 
   3024 		if ((nflags & IPN_TCPUDP)) {
   3025 			tcp = fin->fin_dp;
   3026 			dport = fin->fin_data[1];
   3027 		}
   3028 	}
   3029 
   3030 	ipa = fin->fin_dst6;
   3031 
   3032 	READ_ENTER(&softc->ipf_nat);
   3033 
   3034 	if ((fin->fin_p == IPPROTO_ICMPV6) && !(nflags & IPN_ICMPQUERY) &&
   3035 	    (nat = ipf_nat6_icmperror(fin, &nflags, NAT_INBOUND)))
   3036 		/*EMPTY*/;
   3037 	else if ((fin->fin_flx & FI_FRAG) && (nat = ipf_frag_natknown(fin)))
   3038 		natadd = 0;
   3039 	else if ((nat = ipf_nat6_inlookup(fin, nflags|NAT_SEARCH,
   3040 					  (u_int)fin->fin_p,
   3041 					  &fin->fin_src6.in6, &ipa.in6))) {
   3042 		nflags = nat->nat_flags;
   3043 	} else if (fin->fin_off == 0) {
   3044 		u_32_t hv, rmsk = 0;
   3045 		i6addr_t *msk;
   3046 
   3047 		/*
   3048 		 * If there is no current entry in the nat table for this IP#,
   3049 		 * create one for it (if there is a matching rule).
   3050 		 */
   3051 maskloop:
   3052 		msk = &softn->ipf_nat6_rdr_active_masks[rmsk];
   3053 		IP6_AND(&ipa, msk, &iph);
   3054 		hv = NAT_HASH_FN6(&iph, 0, softn->ipf_nat_rdrrules_sz);
   3055 		for (np = softn->ipf_nat_rdr_rules[hv]; np; np = np->in_rnext) {
   3056 			if (np->in_ifps[0] && (np->in_ifps[0] != ifp))
   3057 				continue;
   3058 			if (np->in_v[0] != 6)
   3059 				continue;
   3060 			if (np->in_pr[0] && (np->in_pr[0] != fin->fin_p))
   3061 				continue;
   3062 			if ((np->in_flags & IPN_RF) && !(np->in_flags & nflags))
   3063 				continue;
   3064 			if (np->in_flags & IPN_FILTER) {
   3065 				switch (ipf_nat6_match(fin, np))
   3066 				{
   3067 				case 0 :
   3068 					continue;
   3069 				case -1 :
   3070 					rval = -1;
   3071 					goto inmatchfail;
   3072 				case 1 :
   3073 				default :
   3074 					break;
   3075 				}
   3076 			} else {
   3077 				if (!IP6_MASKEQ(&ipa, &np->in_odstmsk6,
   3078 						&np->in_odstip6)) {
   3079 					continue;
   3080 				}
   3081 				if (np->in_odport &&
   3082 				    ((np->in_dtop < dport) ||
   3083 				     (dport < np->in_odport)))
   3084 					continue;
   3085 			}
   3086 
   3087 #ifdef IPF_V6_PROXIES
   3088 			if (np->in_plabel != -1) {
   3089 				if (!appr_ok(fin, tcp, np)) {
   3090 					continue;
   3091 				}
   3092 			}
   3093 #endif
   3094 
   3095 			if (np->in_flags & IPN_NO) {
   3096 				np->in_hits++;
   3097 				break;
   3098 			}
   3099 
   3100 			MUTEX_ENTER(&softn->ipf_nat_new);
   3101 			nat = ipf_nat6_add(fin, np, NULL, nflags, NAT_INBOUND);
   3102 			MUTEX_EXIT(&softn->ipf_nat_new);
   3103 			if (nat != NULL) {
   3104 				np->in_hits++;
   3105 				break;
   3106 			}
   3107 			natfailed = -1;
   3108 		}
   3109 
   3110 		if ((np == NULL) && (rmsk < softn->ipf_nat6_rdr_max)) {
   3111 			rmsk++;
   3112 			goto maskloop;
   3113 		}
   3114 	}
   3115 	if (nat != NULL) {
   3116 		rval = ipf_nat6_in(fin, nat, natadd, nflags);
   3117 		if (rval == 1) {
   3118 			MUTEX_ENTER(&nat->nat_lock);
   3119 			ipf_nat_update(fin, nat);
   3120 			nat->nat_bytes[0] += fin->fin_plen;
   3121 			nat->nat_pkts[0]++;
   3122 			MUTEX_EXIT(&nat->nat_lock);
   3123 		}
   3124 	} else
   3125 		rval = natfailed;
   3126 inmatchfail:
   3127 	RWLOCK_EXIT(&softc->ipf_nat);
   3128 
   3129 	switch (rval)
   3130 	{
   3131 	case -1 :
   3132 		if (passp != NULL) {
   3133 			NBUMPSIDE6D(0, ns_drop);
   3134 			*passp = FR_BLOCK;
   3135 			fin->fin_reason = FRB_NATV6;
   3136 		}
   3137 		fin->fin_flx |= FI_BADNAT;
   3138 		NBUMPSIDE6D(0, ns_badnat);
   3139 		break;
   3140 	case 0 :
   3141 		NBUMPSIDE6D(0, ns_ignored);
   3142 		break;
   3143 	case 1 :
   3144 		NBUMPSIDE6D(0, ns_translated);
   3145 		break;
   3146 	}
   3147 	return rval;
   3148 }
   3149 
   3150 
   3151 /* ------------------------------------------------------------------------ */
   3152 /* Function:    ipf_nat6_in                                                 */
   3153 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
   3154 /*                     1 == packet was successfully translated.             */
   3155 /* Parameters:  fin(I)    - pointer to packet information                   */
   3156 /*              nat(I)    - pointer to NAT structure                        */
   3157 /*              natadd(I) - flag indicating if it is safe to add frag cache */
   3158 /*              nflags(I) - NAT flags set for this packet                   */
   3159 /* Locks Held:   (READ)                                              */
   3160 /*                                                                          */
   3161 /* Translate a packet coming "in" on an interface.                          */
   3162 /* ------------------------------------------------------------------------ */
   3163 static int
   3164 ipf_nat6_in(fr_info_t *fin, nat_t *nat, int natadd, u_32_t nflags)
   3165 {
   3166 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3167 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3168 	struct icmp6_hdr *icmp6;
   3169 	u_short *csump;
   3170 	tcphdr_t *tcp;
   3171 	ipnat_t *np;
   3172 	int skip;
   3173 	int i;
   3174 
   3175 	tcp = NULL;
   3176 	csump = NULL;
   3177 	np = nat->nat_ptr;
   3178 	fin->fin_fr = nat->nat_fr;
   3179 
   3180 	if (np != NULL) {
   3181 		if ((natadd != 0) && (fin->fin_flx & FI_FRAG))
   3182 			(void) ipf_frag_natnew(softc, fin, 0, nat);
   3183 
   3184 	/* ------------------------------------------------------------- */
   3185 	/* A few quick notes:                                            */
   3186 	/*      Following are test conditions prior to calling the       */
   3187 	/*      ipf_proxy_check routine.                                 */
   3188 	/*                                                               */
   3189 	/*      A NULL tcp indicates a non TCP/UDP packet.  When dealing */
   3190 	/*      with a map rule, we attempt to match the packet's        */
   3191 	/*      source port against in_dport, otherwise we'd compare the */
   3192 	/*      packet's destination.                                    */
   3193 	/* ------------------------------------------------------------- */
   3194 		if (np->in_apr != NULL) {
   3195 			i = ipf_proxy_check(fin, nat);
   3196 			if (i == -1) {
   3197 				NBUMPSIDE6D(0, ns_ipf_proxy_fail);
   3198 				return -1;
   3199 			}
   3200 		}
   3201 	}
   3202 
   3203 	ipf_sync_update(softc, SMC_NAT, fin, nat->nat_sync);
   3204 
   3205 	/*
   3206 	 * Fix up checksums, not by recalculating them, but
   3207 	 * simply computing adjustments.
   3208 	 * Why only do this for some platforms on inbound packets ?
   3209 	 * Because for those that it is done, IP processing is yet to happen
   3210 	 * and so the IPv4 header checksum has not yet been evaluated.
   3211 	 * Perhaps it should always be done for the benefit of things like
   3212 	 * fast forwarding (so that it doesn't need to be recomputed) but with
   3213 	 * header checksum offloading, perhaps it is a moot point.
   3214 	 */
   3215 
   3216 	switch (nat->nat_dir)
   3217 	{
   3218 	case NAT_INBOUND :
   3219 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   3220 			fin->fin_ip6->ip6_src = nat->nat_nsrc6.in6;
   3221 			fin->fin_src6 = nat->nat_nsrc6;
   3222 		}
   3223 		fin->fin_ip6->ip6_dst = nat->nat_ndst6.in6;
   3224 		fin->fin_dst6 = nat->nat_ndst6;
   3225 		break;
   3226 
   3227 	case NAT_OUTBOUND :
   3228 		if ((fin->fin_flx & FI_ICMPERR) == 0) {
   3229 			fin->fin_ip6->ip6_src = nat->nat_odst6.in6;
   3230 			fin->fin_src6 = nat->nat_odst6;
   3231 		}
   3232 		fin->fin_ip6->ip6_dst = nat->nat_osrc6.in6;
   3233 		fin->fin_dst6 = nat->nat_osrc6;
   3234 		break;
   3235 
   3236 	case NAT_DIVERTIN :
   3237 	    {
   3238 		udphdr_t *uh;
   3239 		ip6_t *ip6;
   3240 		mb_t *m;
   3241 
   3242 		m = M_DUP(np->in_divmp);
   3243 		if (m == NULL) {
   3244 			NBUMPSIDE6D(0, ns_divert_dup);
   3245 			return -1;
   3246 		}
   3247 
   3248 		ip6 = MTOD(m, ip6_t *);
   3249 		ip6->ip6_plen = htons(fin->fin_plen + sizeof(udphdr_t));
   3250 
   3251 		uh = (udphdr_t *)(ip6 + 1);
   3252 		uh->uh_ulen = ntohs(fin->fin_plen);
   3253 
   3254 		PREP_MB_T(fin, m);
   3255 
   3256 		fin->fin_ip6 = ip6;
   3257 		fin->fin_plen += sizeof(ip6_t) + 8;	/* UDP + new IPv6 hdr */
   3258 		fin->fin_dlen += sizeof(ip6_t) + 8;	/* UDP + old IPv6 hdr */
   3259 
   3260 		nflags &= ~IPN_TCPUDPICMP;
   3261 
   3262 		break;
   3263 	    }
   3264 
   3265 	case NAT_DIVERTOUT :
   3266 	    {
   3267 		mb_t *m;
   3268 
   3269 		skip = ipf_nat6_decap(fin, nat);
   3270 		if (skip <= 0) {
   3271 			NBUMPSIDE6D(0, ns_decap_fail);
   3272 			return -1;
   3273 		}
   3274 
   3275 		m = fin->fin_m;
   3276 
   3277 #if defined(MENTAT) && defined(_KERNEL)
   3278 		m->b_rptr += skip;
   3279 #else
   3280 		m->m_data += skip;
   3281 		m->m_len -= skip;
   3282 
   3283 # ifdef M_PKTHDR
   3284 		if (m->m_flags & M_PKTHDR)
   3285 			m->m_pkthdr.len -= skip;
   3286 # endif
   3287 #endif
   3288 
   3289 		ipf_nat_update(fin, nat);
   3290 		fin->fin_flx |= FI_NATED;
   3291 		if (np != NULL && np->in_tag.ipt_num[0] != 0)
   3292 			fin->fin_nattag = &np->in_tag;
   3293 		return 1;
   3294 		/* NOTREACHED */
   3295 	    }
   3296 	}
   3297 	if (nflags & IPN_TCPUDP)
   3298 		tcp = fin->fin_dp;
   3299 
   3300 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
   3301 		if ((nat->nat_odport != 0) && (nflags & IPN_TCPUDP)) {
   3302 			switch (nat->nat_dir)
   3303 			{
   3304 			case NAT_INBOUND :
   3305 				tcp->th_sport = nat->nat_nsport;
   3306 				fin->fin_data[0] = ntohs(nat->nat_nsport);
   3307 				tcp->th_dport = nat->nat_ndport;
   3308 				fin->fin_data[1] = ntohs(nat->nat_ndport);
   3309 				break;
   3310 
   3311 			case NAT_OUTBOUND :
   3312 				tcp->th_sport = nat->nat_odport;
   3313 				fin->fin_data[0] = ntohs(nat->nat_odport);
   3314 				tcp->th_dport = nat->nat_osport;
   3315 				fin->fin_data[1] = ntohs(nat->nat_osport);
   3316 				break;
   3317 			}
   3318 		}
   3319 
   3320 
   3321 		if ((nat->nat_odport != 0) && (nflags & IPN_ICMPQUERY)) {
   3322 			icmp6 = fin->fin_dp;
   3323 
   3324 			icmp6->icmp6_id = nat->nat_nicmpid;
   3325 		}
   3326 
   3327 		csump = ipf_nat_proto(fin, nat, nflags);
   3328 	}
   3329 
   3330 	/*
   3331 	 * The above comments do not hold for layer 4 (or higher) checksums...
   3332 	 */
   3333 	if (csump != NULL) {
   3334 		if (nat->nat_dir == NAT_OUTBOUND)
   3335 			ipf_fix_incksum(0, csump, nat->nat_sumd[0], 0);
   3336 		else
   3337 			ipf_fix_outcksum(0, csump, nat->nat_sumd[0], 0);
   3338 	}
   3339 	fin->fin_flx |= FI_NATED;
   3340 	if (np != NULL && np->in_tag.ipt_num[0] != 0)
   3341 		fin->fin_nattag = &np->in_tag;
   3342 	return 1;
   3343 }
   3344 
   3345 
   3346 /* ------------------------------------------------------------------------ */
   3347 /* Function:    ipf_nat6_newrewrite                                         */
   3348 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
   3349 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
   3350 /* Parameters:  fin(I) - pointer to packet information                      */
   3351 /*              nat(I) - pointer to NAT entry                               */
   3352 /*              ni(I)  - pointer to structure with misc. information needed */
   3353 /*                       to create new NAT entry.                           */
   3354 /* Write Lock:  ipf_nat                                                     */
   3355 /*                                                                          */
   3356 /* This function is responsible for setting up an active NAT session where  */
   3357 /* we are changing both the source and destination parameters at the same   */
   3358 /* time.  The loop in here works differently to elsewhere - each iteration  */
   3359 /* is responsible for changing a single parameter that can be incremented.  */
   3360 /* So one pass may increase the source IP#, next source port, next dest. IP#*/
   3361 /* and the last destination port for a total of 4 iterations to try each.   */
   3362 /* This is done to try and exhaustively use the translation space available.*/
   3363 /* ------------------------------------------------------------------------ */
   3364 int
   3365 ipf_nat6_newrewrite(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
   3366 {
   3367 	int src_search = 1;
   3368 	int dst_search = 1;
   3369 	fr_info_t frnat;
   3370 	u_32_t flags;
   3371 	u_short swap;
   3372 	ipnat_t *np;
   3373 	nat_t *natl;
   3374 	int l = 0;
   3375 	int changed;
   3376 
   3377 	natl = NULL;
   3378 	changed = -1;
   3379 	np = nai->nai_np;
   3380 	flags = nat->nat_flags;
   3381 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   3382 
   3383 	nat->nat_hm = NULL;
   3384 
   3385 	do {
   3386 		changed = -1;
   3387 		/* TRACE (l, src_search, dst_search, np) */
   3388 
   3389 		if ((src_search == 0) && (np->in_spnext == 0) &&
   3390 		    (dst_search == 0) && (np->in_dpnext == 0)) {
   3391 			if (l > 0)
   3392 				return -1;
   3393 		}
   3394 
   3395 		/*
   3396 		 * Find a new source address
   3397 		 */
   3398 		if (ipf_nat6_nextaddr(fin, &np->in_nsrc, &frnat.fin_src6,
   3399 				 &frnat.fin_src6) == -1) {
   3400 			return -1;
   3401 		}
   3402 
   3403 		if (IP6_ISZERO(&np->in_nsrcip6) &&
   3404 		    IP6_ISONES(&np->in_nsrcmsk6)) {
   3405 			src_search = 0;
   3406 			if (np->in_stepnext == 0)
   3407 				np->in_stepnext = 1;
   3408 
   3409 		} else if (IP6_ISZERO(&np->in_nsrcip6) &&
   3410 			   IP6_ISZERO(&np->in_nsrcmsk6)) {
   3411 			src_search = 0;
   3412 			if (np->in_stepnext == 0)
   3413 				np->in_stepnext = 1;
   3414 
   3415 		} else if (IP6_ISONES(&np->in_nsrcmsk)) {
   3416 			src_search = 0;
   3417 			if (np->in_stepnext == 0)
   3418 				np->in_stepnext = 1;
   3419 
   3420 		} else if (!IP6_ISONES(&np->in_nsrcmsk6)) {
   3421 			if (np->in_stepnext == 0 && changed == -1) {
   3422 				IP6_INC(&np->in_snip);
   3423 				np->in_stepnext++;
   3424 				changed = 0;
   3425 			}
   3426 		}
   3427 
   3428 		if ((flags & IPN_TCPUDPICMP) != 0) {
   3429 			if (np->in_spnext != 0)
   3430 				frnat.fin_data[0] = np->in_spnext;
   3431 
   3432 			/*
   3433 			 * Standard port translation.  Select next port.
   3434 			 */
   3435 			if ((flags & IPN_FIXEDSPORT) != 0) {
   3436 				np->in_stepnext = 2;
   3437 			} else if ((np->in_stepnext == 1) &&
   3438 				   (changed == -1) && (natl != NULL)) {
   3439 				np->in_spnext++;
   3440 				np->in_stepnext++;
   3441 				changed = 1;
   3442 				if (np->in_spnext > np->in_spmax)
   3443 					np->in_spnext = np->in_spmin;
   3444 			}
   3445 		} else {
   3446 			np->in_stepnext = 2;
   3447 		}
   3448 		np->in_stepnext &= 0x3;
   3449 
   3450 		/*
   3451 		 * Find a new destination address
   3452 		 */
   3453 		/* TRACE (fin, np, l, frnat) */
   3454 
   3455 		if (ipf_nat6_nextaddr(fin, &np->in_ndst, &frnat.fin_dst6,
   3456 				      &frnat.fin_dst6) == -1)
   3457 			return -1;
   3458 
   3459 		if (IP6_ISZERO(&np->in_ndstip6) &&
   3460 		    IP6_ISONES(&np->in_ndstmsk6)) {
   3461 			dst_search = 0;
   3462 			if (np->in_stepnext == 2)
   3463 				np->in_stepnext = 3;
   3464 
   3465 		} else if (IP6_ISZERO(&np->in_ndstip6) &&
   3466 			   IP6_ISZERO(&np->in_ndstmsk6)) {
   3467 			dst_search = 0;
   3468 			if (np->in_stepnext == 2)
   3469 				np->in_stepnext = 3;
   3470 
   3471 		} else if (IP6_ISONES(&np->in_ndstmsk6)) {
   3472 			dst_search = 0;
   3473 			if (np->in_stepnext == 2)
   3474 				np->in_stepnext = 3;
   3475 
   3476 		} else if (!IP6_ISONES(&np->in_ndstmsk6)) {
   3477 			if ((np->in_stepnext == 2) && (changed == -1) &&
   3478 			    (natl != NULL)) {
   3479 				changed = 2;
   3480 				np->in_stepnext++;
   3481 				IP6_INC(&np->in_dnip6);
   3482 			}
   3483 		}
   3484 
   3485 		if ((flags & IPN_TCPUDPICMP) != 0) {
   3486 			if (np->in_dpnext != 0)
   3487 				frnat.fin_data[1] = np->in_dpnext;
   3488 
   3489 			/*
   3490 			 * Standard port translation.  Select next port.
   3491 			 */
   3492 			if ((flags & IPN_FIXEDDPORT) != 0) {
   3493 				np->in_stepnext = 0;
   3494 			} else if (np->in_stepnext == 3 && changed == -1) {
   3495 				np->in_dpnext++;
   3496 				np->in_stepnext++;
   3497 				changed = 3;
   3498 				if (np->in_dpnext > np->in_dpmax)
   3499 					np->in_dpnext = np->in_dpmin;
   3500 			}
   3501 		} else {
   3502 			if (np->in_stepnext == 3)
   3503 				np->in_stepnext = 0;
   3504 		}
   3505 
   3506 		/* TRACE (frnat) */
   3507 
   3508 		/*
   3509 		 * Here we do a lookup of the connection as seen from
   3510 		 * the outside.  If an IP# pair already exists, try
   3511 		 * again.  So if you have A->B becomes C->B, you can
   3512 		 * also have D->E become C->E but not D->B causing
   3513 		 * another C->B.  Also take protocol and ports into
   3514 		 * account when determining whether a pre-existing
   3515 		 * NAT setup will cause an external conflict where
   3516 		 * this is appropriate.
   3517 		 *
   3518 		 * fin_data[] is swapped around because we are doing a
   3519 		 * lookup of the packet is if it were moving in the opposite
   3520 		 * direction of the one we are working with now.
   3521 		 */
   3522 		if (flags & IPN_TCPUDP) {
   3523 			swap = frnat.fin_data[0];
   3524 			frnat.fin_data[0] = frnat.fin_data[1];
   3525 			frnat.fin_data[1] = swap;
   3526 		}
   3527 		if (fin->fin_out == 1) {
   3528 			natl = ipf_nat6_inlookup(&frnat,
   3529 					    flags & ~(SI_WILDP|NAT_SEARCH),
   3530 					    (u_int)frnat.fin_p,
   3531 					    &frnat.fin_dst6.in6,
   3532 					    &frnat.fin_src6.in6);
   3533 
   3534 		} else {
   3535 			natl = ipf_nat6_outlookup(&frnat,
   3536 					     flags & ~(SI_WILDP|NAT_SEARCH),
   3537 					     (u_int)frnat.fin_p,
   3538 					     &frnat.fin_dst6.in6,
   3539 					     &frnat.fin_src6.in6);
   3540 		}
   3541 		if (flags & IPN_TCPUDP) {
   3542 			swap = frnat.fin_data[0];
   3543 			frnat.fin_data[0] = frnat.fin_data[1];
   3544 			frnat.fin_data[1] = swap;
   3545 		}
   3546 
   3547 		/* TRACE natl, in_stepnext, l */
   3548 
   3549 		if ((natl != NULL) && (l > 8))	/* XXX 8 is arbitrary */
   3550 			return -1;
   3551 
   3552 		np->in_stepnext &= 0x3;
   3553 
   3554 		l++;
   3555 		changed = -1;
   3556 	} while (natl != NULL);
   3557 	nat->nat_osrc6 = fin->fin_src6;
   3558 	nat->nat_odst6 = fin->fin_dst6;
   3559 	nat->nat_nsrc6 = frnat.fin_src6;
   3560 	nat->nat_ndst6 = frnat.fin_dst6;
   3561 
   3562 	if ((flags & IPN_TCPUDP) != 0) {
   3563 		nat->nat_osport = htons(fin->fin_data[0]);
   3564 		nat->nat_odport = htons(fin->fin_data[1]);
   3565 		nat->nat_nsport = htons(frnat.fin_data[0]);
   3566 		nat->nat_ndport = htons(frnat.fin_data[1]);
   3567 	} else if ((flags & IPN_ICMPQUERY) != 0) {
   3568 		nat->nat_oicmpid = fin->fin_data[1];
   3569 		nat->nat_nicmpid = frnat.fin_data[1];
   3570 	}
   3571 
   3572 	return 0;
   3573 }
   3574 
   3575 
   3576 /* ------------------------------------------------------------------------ */
   3577 /* Function:    ipf_nat6_newdivert                                          */
   3578 /* Returns:     int - -1 == error, 0 == success                             */
   3579 /* Parameters:  fin(I) - pointer to packet information                      */
   3580 /*              nat(I) - pointer to NAT entry                               */
   3581 /*              ni(I)  - pointer to structure with misc. information needed */
   3582 /*                       to create new NAT entry.                           */
   3583 /* Write Lock:  ipf_nat                                                     */
   3584 /*                                                                          */
   3585 /* Create a new NAT divert session as defined by the NAT rule.  This is     */
   3586 /* somewhat different to other NAT session creation routines because we     */
   3587 /* do not iterate through either port numbers or IP addresses, searching    */
   3588 /* for a unique mapping, however, a complimentary duplicate check is made.  */
   3589 /* ------------------------------------------------------------------------ */
   3590 int
   3591 ipf_nat6_newdivert(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
   3592 {
   3593 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3594 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3595 	fr_info_t frnat;
   3596 	ipnat_t *np;
   3597 	nat_t *natl;
   3598 	int p;
   3599 
   3600 	np = nai->nai_np;
   3601 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
   3602 
   3603 	nat->nat_pr[0] = 0;
   3604 	nat->nat_osrc6 = fin->fin_src6;
   3605 	nat->nat_odst6 = fin->fin_dst6;
   3606 	nat->nat_osport = htons(fin->fin_data[0]);
   3607 	nat->nat_odport = htons(fin->fin_data[1]);
   3608 	frnat.fin_src6 = np->in_snip6;
   3609 	frnat.fin_dst6 = np->in_dnip6;
   3610 
   3611 	if (np->in_redir & NAT_DIVERTUDP) {
   3612 		frnat.fin_data[0] = np->in_spnext;
   3613 		frnat.fin_data[1] = np->in_dpnext;
   3614 		frnat.fin_flx |= FI_TCPUDP;
   3615 		p = IPPROTO_UDP;
   3616 	} else {
   3617 		frnat.fin_flx &= ~FI_TCPUDP;
   3618 		p = IPPROTO_IPIP;
   3619 	}
   3620 
   3621 	if (fin->fin_out == 1) {
   3622 		natl = ipf_nat6_inlookup(&frnat, 0, p, &frnat.fin_dst6.in6,
   3623 					 &frnat.fin_src6.in6);
   3624 
   3625 	} else {
   3626 		natl = ipf_nat6_outlookup(&frnat, 0, p, &frnat.fin_dst6.in6,
   3627 					  &frnat.fin_src6.in6);
   3628 	}
   3629 
   3630 	if (natl != NULL) {
   3631 		NBUMPSIDE6D(fin->fin_out, ns_divert_exist);
   3632 		return -1;
   3633 	}
   3634 
   3635 	nat->nat_nsrc6 = frnat.fin_src6;
   3636 	nat->nat_ndst6 = frnat.fin_dst6;
   3637 	if (np->in_redir & NAT_DIVERTUDP) {
   3638 		nat->nat_nsport = htons(frnat.fin_data[0]);
   3639 		nat->nat_ndport = htons(frnat.fin_data[1]);
   3640 	}
   3641 	nat->nat_pr[fin->fin_out] = fin->fin_p;
   3642 	nat->nat_pr[1 - fin->fin_out] = p;
   3643 
   3644 	if (np->in_redir & NAT_REDIRECT)
   3645 		nat->nat_dir = NAT_DIVERTIN;
   3646 	else
   3647 		nat->nat_dir = NAT_DIVERTOUT;
   3648 
   3649 	return 0;
   3650 }
   3651 
   3652 
   3653 /* ------------------------------------------------------------------------ */
   3654 /* Function:    nat6_builddivertmp                                          */
   3655 /* Returns:     int - -1 == error, 0 == success                             */
   3656 /* Parameters:  np(I) - pointer to a NAT rule                               */
   3657 /*                                                                          */
   3658 /* For divert rules, a skeleton packet representing what will be prepended  */
   3659 /* to the real packet is created.  Even though we don't have the full       */
   3660 /* packet here, a checksum is calculated that we update later when we       */
   3661 /* fill in the final details.  At present a 0 checksum for UDP is being set */
   3662 /* here because it is expected that divert will be used for localhost.      */
   3663 /* ------------------------------------------------------------------------ */
   3664 static int
   3665 ipf_nat6_builddivertmp(ipf_nat_softc_t *softn, ipnat_t *np)
   3666 {
   3667 	udphdr_t *uh;
   3668 	size_t len;
   3669 	ip6_t *ip6;
   3670 
   3671 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   3672 		len = sizeof(ip6_t) + sizeof(udphdr_t);
   3673 	else
   3674 		len = sizeof(ip6_t);
   3675 
   3676 	ALLOC_MB_T(np->in_divmp, len);
   3677 	if (np->in_divmp == NULL) {
   3678 		ATOMIC_INCL(softn->ipf_nat_stats.ns_divert_build);
   3679 		return -1;
   3680 	}
   3681 
   3682 	/*
   3683 	 * First, the header to get the packet diverted to the new destination
   3684 	 */
   3685 	ip6 = MTOD(np->in_divmp, ip6_t *);
   3686 	ip6->ip6_vfc = 0x60;
   3687 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
   3688 		ip6->ip6_nxt = IPPROTO_UDP;
   3689 	else
   3690 		ip6->ip6_nxt = IPPROTO_IPIP;
   3691 	ip6->ip6_hlim = 255;
   3692 	ip6->ip6_plen = 0;
   3693 	ip6->ip6_src = np->in_snip6.in6;
   3694 	ip6->ip6_dst = np->in_dnip6.in6;
   3695 
   3696 	if (np->in_redir & NAT_DIVERTUDP) {
   3697 		uh = (udphdr_t *)((u_char *)ip6 + sizeof(*ip6));
   3698 		uh->uh_sum = 0;
   3699 		uh->uh_ulen = 8;
   3700 		uh->uh_sport = htons(np->in_spnext);
   3701 		uh->uh_dport = htons(np->in_dpnext);
   3702 	}
   3703 
   3704 	return 0;
   3705 }
   3706 
   3707 
   3708 #define	MINDECAP	(sizeof(ip6_t) + sizeof(udphdr_t) + sizeof(ip6_t))
   3709 
   3710 /* ------------------------------------------------------------------------ */
   3711 /* Function:    nat6_decap                                                  */
   3712 /* Returns:     int - -1 == error, 0 == success                             */
   3713 /* Parameters:  fin(I) - pointer to packet information                      */
   3714 /*              nat(I) - pointer to current NAT session                     */
   3715 /*                                                                          */
   3716 /* This function is responsible for undoing a packet's encapsulation in the */
   3717 /* reverse of an encap/divert rule.  After removing the outer encapsulation */
   3718 /* it is necessary to call ipf_makefrip() again so that the contents of 'fin'*/
   3719 /* match the "new" packet as it may still be used by IPFilter elsewhere.    */
   3720 /* We use "dir" here as the basis for some of the expectations about the    */
   3721 /* outer header.  If we return an error, the goal is to leave the original  */
   3722 /* packet information undisturbed - this falls short at the end where we'd  */
   3723 /* need to back a backup copy of "fin" - expensive.                         */
   3724 /* ------------------------------------------------------------------------ */
   3725 static int
   3726 ipf_nat6_decap(fr_info_t *fin, nat_t *nat)
   3727 {
   3728 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3729 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3730 	char *hdr;
   3731 	int skip;
   3732 	mb_t *m;
   3733 
   3734 	if ((fin->fin_flx & FI_ICMPERR) != 0) {
   3735 		return 0;
   3736 	}
   3737 
   3738 	m = fin->fin_m;
   3739 	skip = fin->fin_hlen;
   3740 
   3741 	switch (nat->nat_dir)
   3742 	{
   3743 	case NAT_DIVERTIN :
   3744 	case NAT_DIVERTOUT :
   3745 		if (fin->fin_plen < MINDECAP)
   3746 			return -1;
   3747 		skip += sizeof(udphdr_t);
   3748 		break;
   3749 
   3750 	case NAT_ENCAPIN :
   3751 	case NAT_ENCAPOUT :
   3752 		if (fin->fin_plen < (skip + sizeof(ip6_t)))
   3753 			return -1;
   3754 		break;
   3755 	default :
   3756 		return -1;
   3757 		/* NOTREACHED */
   3758 	}
   3759 
   3760 	/*
   3761 	 * The aim here is to keep the original packet details in "fin" for
   3762 	 * as long as possible so that returning with an error is for the
   3763 	 * original packet and there is little undoing work to do.
   3764 	 */
   3765 	if (M_LEN(m) < skip + sizeof(ip6_t)) {
   3766 		if (ipf_pr_pullup(fin, skip + sizeof(ip6_t)) == -1)
   3767 			return -1;
   3768 	}
   3769 
   3770 	hdr = MTOD(fin->fin_m, char *);
   3771 	fin->fin_ip6 = (ip6_t *)(hdr + skip);
   3772 
   3773 	if (ipf_pr_pullup(fin, skip + sizeof(ip6_t)) == -1) {
   3774 		NBUMPSIDE6D(fin->fin_out, ns_decap_pullup);
   3775 		return -1;
   3776 	}
   3777 
   3778 	fin->fin_hlen = sizeof(ip6_t);
   3779 	fin->fin_dlen -= skip;
   3780 	fin->fin_plen -= skip;
   3781 	fin->fin_ipoff += skip;
   3782 
   3783 	if (ipf_makefrip(sizeof(ip6_t), (ip_t *)hdr, fin) == -1) {
   3784 		NBUMPSIDE6D(fin->fin_out, ns_decap_bad);
   3785 		return -1;
   3786 	}
   3787 
   3788 	return skip;
   3789 }
   3790 
   3791 
   3792 /* ------------------------------------------------------------------------ */
   3793 /* Function:    nat6_nextaddr                                               */
   3794 /* Returns:     int - -1 == bad input (no new address),                     */
   3795 /*                     0 == success and dst has new address                 */
   3796 /* Parameters:  fin(I) - pointer to packet information                      */
   3797 /*              na(I)  - how to generate new address                        */
   3798 /*              old(I) - original address being replaced                    */
   3799 /*              dst(O) - where to put the new address                       */
   3800 /* Write Lock:  ipf_nat                                                     */
   3801 /*                                                                          */
   3802 /* This function uses the contents of the "na" structure, in combination    */
   3803 /* with "old" to produce a new address to store in "dst".  Not all of the   */
   3804 /* possible uses of "na" will result in a new address.                      */
   3805 /* ------------------------------------------------------------------------ */
   3806 static int
   3807 ipf_nat6_nextaddr(fr_info_t *fin, nat_addr_t *na, i6addr_t *old, i6addr_t *dst)
   3808 {
   3809 	ipf_main_softc_t *softc = fin->fin_main_soft;
   3810 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
   3811 	i6addr_t newip, new;
   3812 	u_32_t amin, amax;
   3813 	int error;
   3814 
   3815 	new.i6[0] = 0;
   3816 	new.i6[1] = 0;
   3817 	new.i6[2] = 0;
   3818 	new.i6[3] = 0;
   3819 	amin = na->na_addr[0].in4.s_addr;
   3820 
   3821 	switch (na->na_atype)
   3822 	{
   3823 	case FRI_RANGE :
   3824 		amax = na->na_addr[1].in4.s_addr;
   3825 		break;
   3826 
   3827 	case FRI_NETMASKED :
   3828 	case FRI_DYNAMIC :
   3829 	case FRI_NORMAL :
   3830 		/*
   3831 		 * Compute the maximum address by adding the inverse of the
   3832 		 * netmask to the minimum address.
   3833 		 */
   3834 		amax = ~na->na_addr[1].in4.s_addr;
   3835 		amax |= amin;
   3836 		break;
   3837 
   3838 	case FRI_LOOKUP :
   3839 		break;
   3840 
   3841 	case FRI_BROADCAST :
   3842 	case FRI_PEERADDR :
   3843 	case FRI_NETWORK :
   3844 	default :
   3845 		return -1;
   3846 	}
   3847 
   3848 	error = -1;
   3849 	switch (na->na_function)
   3850 	{
   3851 	case IPLT_DSTLIST :
   3852 		error = ipf_dstlist_select_node(fin, na->na_ptr, dst->i6,
   3853 						NULL);
   3854 		break;
   3855 
   3856 	case IPLT_NONE :
   3857 		/*
   3858 		 * 0/0 as the new address means leave it alone.
   3859 		 */
   3860 		if (na->na_addr[0].in4.s_addr == 0 &&
   3861 		    na->na_addr[1].in4.s_addr == 0) {
   3862 			new = *old;
   3863 
   3864 		/*
   3865 		 * 0/32 means get the interface's address
   3866 		 */
   3867 		} else if (IP6_ISZERO(&na->na_addr[0].in6) &&
   3868 			   IP6_ISONES(&na->na_addr[1].in6)) {
   3869 			if (ipf_ifpaddr(softc, 6, na->na_atype,
   3870 				       fin->fin_ifp, &newip, NULL) == -1) {
   3871 				NBUMPSIDE6(fin->fin_out, ns_ifpaddrfail);
   3872 				return -1;
   3873 			}
   3874 			new = newip;
   3875 		} else {
   3876 			new.in6 = na->na_nextip6;
   3877 		}
   3878 		*dst = new;
   3879 		error = 0;
   3880 		break;
   3881 
   3882 	default :
   3883 		NBUMPSIDE6(fin->fin_out, ns_badnextaddr);
   3884 		break;
   3885 	}
   3886 
   3887 	return error;
   3888 }
   3889 
   3890 
   3891 /* ------------------------------------------------------------------------ */
   3892 /* Function:    ipf_nat6_nextaddrinit                                       */
   3893 /* Returns:     int - 0 == success, else error number                       */
   3894 /* Parameters:  na(I)      - NAT address information for generating new addr*/
   3895 /*              base(I)    - start of where to find strings                 */
   3896 /*              initial(I) - flag indicating if it is the first call for    */
   3897 /*                           this "na" structure.                           */
   3898 /*              ifp(I)     - network interface to derive address            */
   3899 /*                           information from.                              */
   3900 /*                                                                          */
   3901 /* This function is expected to be called in two scenarious: when a new NAT */
   3902 /* rule is loaded into the kernel and when the list of NAT rules is sync'd  */
   3903 /* up with the valid network interfaces (possibly due to them changing.)    */
   3904 /* To distinguish between these, the "initial" parameter is used.  If it is */
   3905 /* 1 then this indicates the rule has just been reloaded and 0 for when we  */
   3906 /* are updating information.  This difference is important because in       */
   3907 /* instances where we are not updating address information associated with  */
   3908 /* a network interface, we don't want to disturb what the "next" address to */
   3909 /* come out of ipf_nat6_nextaddr() will be.                                 */
   3910 /* ------------------------------------------------------------------------ */
   3911 static int
   3912 ipf_nat6_nextaddrinit(ipf_main_softc_t *softc, char *base, nat_addr_t *na,
   3913     int initial, void *ifp)
   3914 {
   3915 	switch (na->na_atype)
   3916 	{
   3917 	case FRI_LOOKUP :
   3918 		if (na->na_subtype == 0) {
   3919 			na->na_ptr = ipf_lookup_res_num(softc, IPL_LOGNAT,
   3920 							na->na_type,
   3921 							na->na_num,
   3922 							&na->na_func);
   3923 		} else if (na->na_subtype == 1) {
   3924 			na->na_ptr = ipf_lookup_res_name(softc, IPL_LOGNAT,
   3925 							 na->na_type,
   3926 							 base + na->na_num,
   3927 							 &na->na_func);
   3928 		}
   3929 		if (na->na_func == NULL) {
   3930 			IPFERROR(60072);
   3931 			return ESRCH;
   3932 		}
   3933 		if (na->na_ptr == NULL) {
   3934 			IPFERROR(60073);
   3935 			return ESRCH;
   3936 		}
   3937 		break;
   3938 	case FRI_DYNAMIC :
   3939 	case FRI_BROADCAST :
   3940 	case FRI_NETWORK :
   3941 	case FRI_NETMASKED :
   3942 	case FRI_PEERADDR :
   3943 		if (ifp != NULL)
   3944 			(void )ipf_ifpaddr(softc, 6, na->na_atype, ifp,
   3945 					   &na->na_addr[0],
   3946 					   &na->na_addr[1]);
   3947 		break;
   3948 
   3949 	case FRI_SPLIT :
   3950 	case FRI_RANGE :
   3951 		if (initial)
   3952 			na->na_nextip6 = na->na_addr[0].in6;
   3953 		break;
   3954 
   3955 	case FRI_NONE :
   3956 		IP6_ANDASSIGN(&na->na_addr[0].in6, &na->na_addr[1].in6);
   3957 		return 0;
   3958 
   3959 	case FRI_NORMAL :
   3960 		IP6_ANDASSIGN(&na->na_addr[0].in6, &na->na_addr[1].in6);
   3961 		break;
   3962 
   3963 	default :
   3964 		IPFERROR(60074);
   3965 		return EINVAL;
   3966 	}
   3967 
   3968 	if (initial && (na->na_atype == FRI_NORMAL)) {
   3969 		if (IP6_ISZERO(&na->na_addr[0].in6)) {
   3970 			if (IP6_ISONES(&na->na_addr[1].in6) ||
   3971 			    IP6_ISZERO(&na->na_addr[1].in6)) {
   3972 				return 0;
   3973 			}
   3974 		}
   3975 
   3976 		na->na_nextip6 = na->na_addr[0].in6;
   3977 		if (!IP6_ISONES(&na->na_addr[1].in6)) {
   3978 			IP6_INC(&na->na_nextip6);
   3979 		}
   3980 	}
   3981 
   3982 	return 0;
   3983 }
   3984 
   3985 
   3986 /* ------------------------------------------------------------------------ */
   3987 /* Function:    ipf_nat6_icmpquerytype                                      */
   3988 /* Returns:     int - 1 == success, 0 == failure                            */
   3989 /* Parameters:  icmptype(I) - ICMP type number                              */
   3990 /*                                                                          */
   3991 /* Tests to see if the ICMP type number passed is a query/response type or  */
   3992 /* not.                                                                     */
   3993 /* ------------------------------------------------------------------------ */
   3994 static int
   3995 ipf_nat6_icmpquerytype(int icmptype)
   3996 {
   3997 
   3998 	/*
   3999 	 * For the ICMP query NAT code, it is essential that both the query
   4000 	 * and the reply match on the NAT rule. Because the NAT structure
   4001 	 * does not keep track of the icmptype, and a single NAT structure
   4002 	 * is used for all icmp types with the same src, dest and id, we
   4003 	 * simply define the replies as queries as well. The funny thing is,
   4004 	 * altough it seems silly to call a reply a query, this is exactly
   4005 	 * as it is defined in the IPv4 specification
   4006 	 */
   4007 
   4008 	switch (icmptype)
   4009 	{
   4010 
   4011 	case ICMP6_ECHO_REPLY:
   4012 	case ICMP6_ECHO_REQUEST:
   4013 	/* route aedvertisement/solliciation is currently unsupported: */
   4014 	/* it would require rewriting the ICMP data section            */
   4015 	case ICMP6_MEMBERSHIP_QUERY:
   4016 	case ICMP6_MEMBERSHIP_REPORT:
   4017 	case ICMP6_MEMBERSHIP_REDUCTION:
   4018 	case ICMP6_WRUREQUEST:
   4019 	case ICMP6_WRUREPLY:
   4020 	case MLD6_MTRACE_RESP:
   4021 	case MLD6_MTRACE:
   4022 		return 1;
   4023 	default:
   4024 		return 0;
   4025 	}
   4026 }
   4027 #endif /* USE_INET6 */
   4028