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