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