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