xref: /illumos-gate/usr/src/uts/common/inet/ipf/ip_nat.c (revision a763904894d1c7d4593dc27d5f0c8e03c6c1936f)
1 /*
2  * Copyright (C) 1995-2003 by Darren Reed.
3  *
4  * See the IPFILTER.LICENCE file for details on licencing.
5  *
6  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
7  * Use is subject to license terms.
8  */
9 
10 #pragma ident	"%Z%%M%	%I%	%E% SMI"$
11 
12 #if defined(KERNEL) || defined(_KERNEL)
13 # undef KERNEL
14 # undef _KERNEL
15 # define        KERNEL	1
16 # define        _KERNEL	1
17 #endif
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/time.h>
22 #include <sys/file.h>
23 #if defined(__NetBSD__) && (NetBSD >= 199905) && !defined(IPFILTER_LKM) && \
24     defined(_KERNEL)
25 # include "opt_ipfilter_log.h"
26 #endif
27 #if !defined(_KERNEL)
28 # include <stdio.h>
29 # include <string.h>
30 # include <stdlib.h>
31 # define _KERNEL
32 # ifdef __OpenBSD__
33 struct file;
34 # endif
35 # include <sys/uio.h>
36 # undef _KERNEL
37 #endif
38 #if defined(_KERNEL) && (__FreeBSD_version >= 220000)
39 # include <sys/filio.h>
40 # include <sys/fcntl.h>
41 #else
42 # include <sys/ioctl.h>
43 #endif
44 #if !defined(AIX)
45 # include <sys/fcntl.h>
46 #endif
47 #if !defined(linux)
48 # include <sys/protosw.h>
49 #endif
50 #include <sys/socket.h>
51 #if defined(_KERNEL)
52 # include <sys/systm.h>
53 # if !defined(__SVR4) && !defined(__svr4__)
54 #  include <sys/mbuf.h>
55 # endif
56 #endif
57 #if defined(__SVR4) || defined(__svr4__)
58 # include <sys/filio.h>
59 # include <sys/byteorder.h>
60 # ifdef _KERNEL
61 #  include <sys/dditypes.h>
62 # endif
63 # include <sys/stream.h>
64 # include <sys/kmem.h>
65 #endif
66 #if __FreeBSD_version >= 300000
67 # include <sys/queue.h>
68 #endif
69 #include <net/if.h>
70 #if __FreeBSD_version >= 300000
71 # include <net/if_var.h>
72 # if defined(_KERNEL) && !defined(IPFILTER_LKM)
73 #  include "opt_ipfilter.h"
74 # endif
75 #endif
76 #ifdef sun
77 # include <net/af.h>
78 #endif
79 #include <net/route.h>
80 #include <netinet/in.h>
81 #include <netinet/in_systm.h>
82 #include <netinet/ip.h>
83 
84 #ifdef RFC1825
85 # include <vpn/md5.h>
86 # include <vpn/ipsec.h>
87 extern struct ifnet vpnif;
88 #endif
89 
90 #if !defined(linux)
91 # include <netinet/ip_var.h>
92 #endif
93 #include <netinet/tcp.h>
94 #include <netinet/udp.h>
95 #include <netinet/ip_icmp.h>
96 #include "netinet/ip_compat.h"
97 #include <netinet/tcpip.h>
98 #include "netinet/ip_fil.h"
99 #include "netinet/ip_nat.h"
100 #include "netinet/ip_frag.h"
101 #include "netinet/ip_state.h"
102 #include "netinet/ip_proxy.h"
103 #include "netinet/ipf_stack.h"
104 #ifdef	IPFILTER_SYNC
105 #include "netinet/ip_sync.h"
106 #endif
107 #if (__FreeBSD_version >= 300000)
108 # include <sys/malloc.h>
109 #endif
110 /* END OF INCLUDES */
111 
112 #undef	SOCKADDR_IN
113 #define	SOCKADDR_IN	struct sockaddr_in
114 
115 #if !defined(lint)
116 static const char sccsid[] = "@(#)ip_nat.c	1.11 6/5/96 (C) 1995 Darren Reed";
117 static const char rcsid[] = "@(#)$Id: ip_nat.c,v 2.195.2.42 2005/08/11 19:51:36 darrenr Exp $";
118 #endif
119 
120 
121 /* ======================================================================== */
122 /* How the NAT is organised and works.                                      */
123 /*                                                                          */
124 /* Inside (interface y) NAT       Outside (interface x)                     */
125 /* -------------------- -+- -------------------------------------           */
126 /* Packet going          |   out, processsed by fr_checknatout() for x      */
127 /* ------------>         |   ------------>                                  */
128 /* src=10.1.1.1          |   src=192.1.1.1                                  */
129 /*                       |                                                  */
130 /*                       |   in, processed by fr_checknatin() for x         */
131 /* <------------         |   <------------                                  */
132 /* dst=10.1.1.1          |   dst=192.1.1.1                                  */
133 /* -------------------- -+- -------------------------------------           */
134 /* fr_checknatout() - changes ip_src and if required, sport                 */
135 /*             - creates a new mapping, if required.                        */
136 /* fr_checknatin()  - changes ip_dst and if required, dport                 */
137 /*                                                                          */
138 /* In the NAT table, internal source is recorded as "in" and externally     */
139 /* seen as "out".                                                           */
140 /* ======================================================================== */
141 
142 
143 static	int	nat_flushtable __P((ipf_stack_t *));
144 static	int	nat_clearlist __P((ipf_stack_t *));
145 static	void	nat_addnat __P((struct ipnat *, ipf_stack_t *));
146 static	void	nat_addrdr __P((struct ipnat *, ipf_stack_t *));
147 static	void	nat_delete __P((struct nat *, int, ipf_stack_t *));
148 static	void	nat_delrdr __P((struct ipnat *));
149 static	void	nat_delnat __P((struct ipnat *));
150 static	int	fr_natgetent __P((caddr_t, ipf_stack_t *));
151 static	int	fr_natgetsz __P((caddr_t, ipf_stack_t *));
152 static	int	fr_natputent __P((caddr_t, int, ipf_stack_t *));
153 static	void	nat_tabmove __P((nat_t *, ipf_stack_t *));
154 static	int	nat_match __P((fr_info_t *, ipnat_t *));
155 static	INLINE	int nat_newmap __P((fr_info_t *, nat_t *, natinfo_t *));
156 static	INLINE	int nat_newrdr __P((fr_info_t *, nat_t *, natinfo_t *));
157 static	hostmap_t *nat_hostmap __P((ipnat_t *, struct in_addr,
158 				    struct in_addr, struct in_addr, u_32_t,
159 				    ipf_stack_t *));
160 static	void	nat_hostmapdel __P((struct hostmap *));
161 static	INLINE	int nat_icmpquerytype4 __P((int));
162 static	int	nat_siocaddnat __P((ipnat_t *, ipnat_t **, int,
163 				    ipf_stack_t *));
164 static	void	nat_siocdelnat __P((ipnat_t *, ipnat_t **, int,
165 				    ipf_stack_t *));
166 static	INLINE	int nat_icmperrortype4 __P((int));
167 static	INLINE	int nat_finalise __P((fr_info_t *, nat_t *, natinfo_t *,
168 				      tcphdr_t *, nat_t **, int));
169 static	INLINE	int nat_resolverule __P((ipnat_t *, ipf_stack_t *));
170 static	nat_t	*fr_natclone __P((fr_info_t *, nat_t *));
171 static	void	nat_mssclamp __P((tcphdr_t *, u_32_t, u_short *));
172 static	INLINE	int nat_wildok __P((nat_t *, int, int, int, int));
173 static	int	nat_getnext __P((ipftoken_t *, ipfgeniter_t *, ipf_stack_t *));
174 static	int	nat_iterator __P((ipftoken_t *, ipfgeniter_t *, ipf_stack_t *));
175 static	int	nat_extraflush __P((int, ipf_stack_t *));
176 static	int	nat_earlydrop __P((ipftq_t *, int, ipf_stack_t *));
177 static	int	nat_flushclosing __P((int, ipf_stack_t *));
178 
179 
180 /*
181  * Below we declare a list of constants used only in the nat_extraflush()
182  * routine.  We are placing it here, instead of in nat_extraflush() itself,
183  * because we want to make it visible to tools such as mdb, nm etc., so the
184  * values can easily be altered during debugging.
185  */
186 static	const int	idletime_tab[] = {
187 	IPF_TTLVAL(30),		/* 30 seconds */
188 	IPF_TTLVAL(1800),	/* 30 minutes */
189 	IPF_TTLVAL(43200),	/* 12 hours */
190 	IPF_TTLVAL(345600),	/* 4 days */
191 };
192 
193 
194 /* ------------------------------------------------------------------------ */
195 /* Function:    fr_natinit                                                  */
196 /* Returns:     int - 0 == success, -1 == failure                           */
197 /* Parameters:  Nil                                                         */
198 /*                                                                          */
199 /* Initialise all of the NAT locks, tables and other structures.            */
200 /* ------------------------------------------------------------------------ */
201 int fr_natinit(ifs)
202 ipf_stack_t *ifs;
203 {
204 	int i;
205 
206 	KMALLOCS(ifs->ifs_nat_table[0], nat_t **,
207 		 sizeof(nat_t *) * ifs->ifs_ipf_nattable_sz);
208 	if (ifs->ifs_nat_table[0] != NULL)
209 		bzero((char *)ifs->ifs_nat_table[0],
210 		      ifs->ifs_ipf_nattable_sz * sizeof(nat_t *));
211 	else
212 		return -1;
213 
214 	KMALLOCS(ifs->ifs_nat_table[1], nat_t **,
215 		 sizeof(nat_t *) * ifs->ifs_ipf_nattable_sz);
216 	if (ifs->ifs_nat_table[1] != NULL)
217 		bzero((char *)ifs->ifs_nat_table[1],
218 		      ifs->ifs_ipf_nattable_sz * sizeof(nat_t *));
219 	else
220 		return -2;
221 
222 	KMALLOCS(ifs->ifs_nat_rules, ipnat_t **,
223 		 sizeof(ipnat_t *) * ifs->ifs_ipf_natrules_sz);
224 	if (ifs->ifs_nat_rules != NULL)
225 		bzero((char *)ifs->ifs_nat_rules,
226 		      ifs->ifs_ipf_natrules_sz * sizeof(ipnat_t *));
227 	else
228 		return -3;
229 
230 	KMALLOCS(ifs->ifs_rdr_rules, ipnat_t **,
231 		 sizeof(ipnat_t *) * ifs->ifs_ipf_rdrrules_sz);
232 	if (ifs->ifs_rdr_rules != NULL)
233 		bzero((char *)ifs->ifs_rdr_rules,
234 		      ifs->ifs_ipf_rdrrules_sz * sizeof(ipnat_t *));
235 	else
236 		return -4;
237 
238 	KMALLOCS(ifs->ifs_maptable, hostmap_t **,
239 		 sizeof(hostmap_t *) * ifs->ifs_ipf_hostmap_sz);
240 	if (ifs->ifs_maptable != NULL)
241 		bzero((char *)ifs->ifs_maptable,
242 		      sizeof(hostmap_t *) * ifs->ifs_ipf_hostmap_sz);
243 	else
244 		return -5;
245 
246 	ifs->ifs_ipf_hm_maplist = NULL;
247 
248 	KMALLOCS(ifs->ifs_nat_stats.ns_bucketlen[0], u_long *,
249 		 ifs->ifs_ipf_nattable_sz * sizeof(u_long));
250 	if (ifs->ifs_nat_stats.ns_bucketlen[0] == NULL)
251 		return -1;
252 	bzero((char *)ifs->ifs_nat_stats.ns_bucketlen[0],
253 	      ifs->ifs_ipf_nattable_sz * sizeof(u_long));
254 
255 	KMALLOCS(ifs->ifs_nat_stats.ns_bucketlen[1], u_long *,
256 		 ifs->ifs_ipf_nattable_sz * sizeof(u_long));
257 	if (ifs->ifs_nat_stats.ns_bucketlen[1] == NULL)
258 		return -1;
259 	bzero((char *)ifs->ifs_nat_stats.ns_bucketlen[1],
260 	      ifs->ifs_ipf_nattable_sz * sizeof(u_long));
261 
262 	if (ifs->ifs_fr_nat_maxbucket == 0) {
263 		for (i = ifs->ifs_ipf_nattable_sz; i > 0; i >>= 1)
264 			ifs->ifs_fr_nat_maxbucket++;
265 		ifs->ifs_fr_nat_maxbucket *= 2;
266 	}
267 
268 	fr_sttab_init(ifs->ifs_nat_tqb, ifs);
269 	/*
270 	 * Increase this because we may have "keep state" following this too
271 	 * and packet storms can occur if this is removed too quickly.
272 	 */
273 	ifs->ifs_nat_tqb[IPF_TCPS_CLOSED].ifq_ttl = ifs->ifs_fr_tcplastack;
274 	ifs->ifs_nat_tqb[IPF_TCP_NSTATES - 1].ifq_next = &ifs->ifs_nat_udptq;
275 	ifs->ifs_nat_udptq.ifq_ttl = ifs->ifs_fr_defnatage;
276 	ifs->ifs_nat_udptq.ifq_ref = 1;
277 	ifs->ifs_nat_udptq.ifq_head = NULL;
278 	ifs->ifs_nat_udptq.ifq_tail = &ifs->ifs_nat_udptq.ifq_head;
279 	MUTEX_INIT(&ifs->ifs_nat_udptq.ifq_lock, "nat ipftq udp tab");
280 	ifs->ifs_nat_udptq.ifq_next = &ifs->ifs_nat_icmptq;
281 	ifs->ifs_nat_icmptq.ifq_ttl = ifs->ifs_fr_defnaticmpage;
282 	ifs->ifs_nat_icmptq.ifq_ref = 1;
283 	ifs->ifs_nat_icmptq.ifq_head = NULL;
284 	ifs->ifs_nat_icmptq.ifq_tail = &ifs->ifs_nat_icmptq.ifq_head;
285 	MUTEX_INIT(&ifs->ifs_nat_icmptq.ifq_lock, "nat icmp ipftq tab");
286 	ifs->ifs_nat_icmptq.ifq_next = &ifs->ifs_nat_iptq;
287 	ifs->ifs_nat_iptq.ifq_ttl = ifs->ifs_fr_defnatipage;
288 	ifs->ifs_nat_iptq.ifq_ref = 1;
289 	ifs->ifs_nat_iptq.ifq_head = NULL;
290 	ifs->ifs_nat_iptq.ifq_tail = &ifs->ifs_nat_iptq.ifq_head;
291 	MUTEX_INIT(&ifs->ifs_nat_iptq.ifq_lock, "nat ip ipftq tab");
292 	ifs->ifs_nat_iptq.ifq_next = NULL;
293 
294 	for (i = 0; i < IPF_TCP_NSTATES; i++) {
295 		if (ifs->ifs_nat_tqb[i].ifq_ttl < ifs->ifs_fr_defnaticmpage)
296 			ifs->ifs_nat_tqb[i].ifq_ttl = ifs->ifs_fr_defnaticmpage;
297 #ifdef LARGE_NAT
298 		else if (ifs->ifs_nat_tqb[i].ifq_ttl > ifs->ifs_fr_defnatage)
299 			ifs->ifs_nat_tqb[i].ifq_ttl = ifs->ifs_fr_defnatage;
300 #endif
301 	}
302 
303 	/*
304 	 * Increase this because we may have "keep state" following
305 	 * this too and packet storms can occur if this is removed
306 	 * too quickly.
307 	 */
308 	ifs->ifs_nat_tqb[IPF_TCPS_CLOSED].ifq_ttl =
309 	    ifs->ifs_nat_tqb[IPF_TCPS_LAST_ACK].ifq_ttl;
310 
311 	RWLOCK_INIT(&ifs->ifs_ipf_nat, "ipf IP NAT rwlock");
312 	RWLOCK_INIT(&ifs->ifs_ipf_natfrag, "ipf IP NAT-Frag rwlock");
313 	MUTEX_INIT(&ifs->ifs_ipf_nat_new, "ipf nat new mutex");
314 	MUTEX_INIT(&ifs->ifs_ipf_natio, "ipf nat io mutex");
315 
316 	ifs->ifs_fr_nat_init = 1;
317 
318 	return 0;
319 }
320 
321 
322 /* ------------------------------------------------------------------------ */
323 /* Function:    nat_addrdr                                                  */
324 /* Returns:     Nil                                                         */
325 /* Parameters:  n(I) - pointer to NAT rule to add                           */
326 /*                                                                          */
327 /* Adds a redirect rule to the hash table of redirect rules and the list of */
328 /* loaded NAT rules.  Updates the bitmask indicating which netmasks are in  */
329 /* use by redirect rules.                                                   */
330 /* ------------------------------------------------------------------------ */
331 static void nat_addrdr(n, ifs)
332 ipnat_t *n;
333 ipf_stack_t *ifs;
334 {
335 	ipnat_t **np;
336 	u_32_t j;
337 	u_int hv;
338 	int k;
339 
340 	k = count4bits(n->in_outmsk);
341 	if ((k >= 0) && (k != 32))
342 		ifs->ifs_rdr_masks |= 1 << k;
343 	j = (n->in_outip & n->in_outmsk);
344 	hv = NAT_HASH_FN(j, 0, ifs->ifs_ipf_rdrrules_sz);
345 	np = ifs->ifs_rdr_rules + hv;
346 	while (*np != NULL)
347 		np = &(*np)->in_rnext;
348 	n->in_rnext = NULL;
349 	n->in_prnext = np;
350 	n->in_hv = hv;
351 	*np = n;
352 }
353 
354 
355 /* ------------------------------------------------------------------------ */
356 /* Function:    nat_addnat                                                  */
357 /* Returns:     Nil                                                         */
358 /* Parameters:  n(I) - pointer to NAT rule to add                           */
359 /*                                                                          */
360 /* Adds a NAT map rule to the hash table of rules and the list of  loaded   */
361 /* NAT rules.  Updates the bitmask indicating which netmasks are in use by  */
362 /* redirect rules.                                                          */
363 /* ------------------------------------------------------------------------ */
364 static void nat_addnat(n, ifs)
365 ipnat_t *n;
366 ipf_stack_t *ifs;
367 {
368 	ipnat_t **np;
369 	u_32_t j;
370 	u_int hv;
371 	int k;
372 
373 	k = count4bits(n->in_inmsk);
374 	if ((k >= 0) && (k != 32))
375 		ifs->ifs_nat_masks |= 1 << k;
376 	j = (n->in_inip & n->in_inmsk);
377 	hv = NAT_HASH_FN(j, 0, ifs->ifs_ipf_natrules_sz);
378 	np = ifs->ifs_nat_rules + hv;
379 	while (*np != NULL)
380 		np = &(*np)->in_mnext;
381 	n->in_mnext = NULL;
382 	n->in_pmnext = np;
383 	n->in_hv = hv;
384 	*np = n;
385 }
386 
387 
388 /* ------------------------------------------------------------------------ */
389 /* Function:    nat_delrdr                                                  */
390 /* Returns:     Nil                                                         */
391 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
392 /*                                                                          */
393 /* Removes a redirect rule from the hash table of redirect rules.           */
394 /* ------------------------------------------------------------------------ */
395 static void nat_delrdr(n)
396 ipnat_t *n;
397 {
398 	if (n->in_rnext)
399 		n->in_rnext->in_prnext = n->in_prnext;
400 	*n->in_prnext = n->in_rnext;
401 }
402 
403 
404 /* ------------------------------------------------------------------------ */
405 /* Function:    nat_delnat                                                  */
406 /* Returns:     Nil                                                         */
407 /* Parameters:  n(I) - pointer to NAT rule to delete                        */
408 /*                                                                          */
409 /* Removes a NAT map rule from the hash table of NAT map rules.             */
410 /* ------------------------------------------------------------------------ */
411 static void nat_delnat(n)
412 ipnat_t *n;
413 {
414 	if (n->in_mnext != NULL)
415 		n->in_mnext->in_pmnext = n->in_pmnext;
416 	*n->in_pmnext = n->in_mnext;
417 }
418 
419 
420 /* ------------------------------------------------------------------------ */
421 /* Function:    nat_hostmap                                                 */
422 /* Returns:     struct hostmap* - NULL if no hostmap could be created,      */
423 /*                                else a pointer to the hostmapping to use  */
424 /* Parameters:  np(I)   - pointer to NAT rule                               */
425 /*              real(I) - real IP address                                   */
426 /*              map(I)  - mapped IP address                                 */
427 /*              port(I) - destination port number                           */
428 /* Write Locks: ipf_nat                                                     */
429 /*                                                                          */
430 /* Check if an ip address has already been allocated for a given mapping    */
431 /* that is not doing port based translation.  If is not yet allocated, then */
432 /* create a new entry if a non-NULL NAT rule pointer has been supplied.     */
433 /* ------------------------------------------------------------------------ */
434 static struct hostmap *nat_hostmap(np, src, dst, map, port, ifs)
435 ipnat_t *np;
436 struct in_addr src;
437 struct in_addr dst;
438 struct in_addr map;
439 u_32_t port;
440 ipf_stack_t *ifs;
441 {
442 	hostmap_t *hm;
443 	u_int hv;
444 
445 	hv = (src.s_addr ^ dst.s_addr);
446 	hv += src.s_addr;
447 	hv += dst.s_addr;
448 	hv %= HOSTMAP_SIZE;
449 	for (hm = ifs->ifs_maptable[hv]; hm; hm = hm->hm_next)
450 		if ((hm->hm_srcip.s_addr == src.s_addr) &&
451 		    (hm->hm_dstip.s_addr == dst.s_addr) &&
452 		    ((np == NULL) || (np == hm->hm_ipnat)) &&
453 		    ((port == 0) || (port == hm->hm_port))) {
454 			hm->hm_ref++;
455 			return hm;
456 		}
457 
458 	if (np == NULL)
459 		return NULL;
460 
461 	KMALLOC(hm, hostmap_t *);
462 	if (hm) {
463 		hm->hm_hnext = ifs->ifs_ipf_hm_maplist;
464 		hm->hm_phnext = &ifs->ifs_ipf_hm_maplist;
465 		if (ifs->ifs_ipf_hm_maplist != NULL)
466 			ifs->ifs_ipf_hm_maplist->hm_phnext = &hm->hm_hnext;
467 		ifs->ifs_ipf_hm_maplist = hm;
468 
469 		hm->hm_next = ifs->ifs_maptable[hv];
470 		hm->hm_pnext = ifs->ifs_maptable + hv;
471 		if (ifs->ifs_maptable[hv] != NULL)
472 			ifs->ifs_maptable[hv]->hm_pnext = &hm->hm_next;
473 		ifs->ifs_maptable[hv] = hm;
474 		hm->hm_ipnat = np;
475 		hm->hm_srcip = src;
476 		hm->hm_dstip = dst;
477 		hm->hm_mapip = map;
478 		hm->hm_ref = 1;
479 		hm->hm_port = port;
480 	}
481 	return hm;
482 }
483 
484 
485 /* ------------------------------------------------------------------------ */
486 /* Function:    nat_hostmapdel                                              */
487 /* Returns:     Nil                                                         */
488 /* Parameters:  hm(I) - pointer to hostmap structure                        */
489 /* Write Locks: ipf_nat                                                     */
490 /*                                                                          */
491 /* Decrement the references to this hostmap structure by one.  If this      */
492 /* reaches zero then remove it and free it.                                 */
493 /* ------------------------------------------------------------------------ */
494 static void nat_hostmapdel(hm)
495 struct hostmap *hm;
496 {
497 	hm->hm_ref--;
498 	if (hm->hm_ref == 0) {
499 		if (hm->hm_next)
500 			hm->hm_next->hm_pnext = hm->hm_pnext;
501 		*hm->hm_pnext = hm->hm_next;
502 		if (hm->hm_hnext)
503 			hm->hm_hnext->hm_phnext = hm->hm_phnext;
504 		*hm->hm_phnext = hm->hm_hnext;
505 		KFREE(hm);
506 	}
507 }
508 
509 void fr_hostmapderef(hmp)
510 struct hostmap **hmp;
511 {
512 	struct hostmap *hm;
513 
514 	hm = *hmp;
515 	*hmp = NULL;
516 	hm->hm_ref--;
517 	if (hm->hm_ref == 0)
518 		nat_hostmapdel(hm);
519 }
520 
521 
522 /* ------------------------------------------------------------------------ */
523 /* Function:    fix_outcksum                                                */
524 /* Returns:     Nil                                                         */
525 /* Parameters:  sp(I)  - location of 16bit checksum to update               */
526 /*              n((I)  - amount to adjust checksum by                       */
527 /*                                                                          */
528 /* Adjusts the 16bit checksum by "n" for packets going out.                 */
529 /* ------------------------------------------------------------------------ */
530 void fix_outcksum(sp, n)
531 u_short *sp;
532 u_32_t n;
533 {
534 	u_short sumshort;
535 	u_32_t sum1;
536 
537 	if (n == 0)
538 		return;
539 
540 	sum1 = (~ntohs(*sp)) & 0xffff;
541 	sum1 += (n);
542 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
543 	/* Again */
544 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
545 	sumshort = ~(u_short)sum1;
546 	*(sp) = htons(sumshort);
547 }
548 
549 
550 /* ------------------------------------------------------------------------ */
551 /* Function:    fix_incksum                                                 */
552 /* Returns:     Nil                                                         */
553 /* Parameters:  sp(I)  - location of 16bit checksum to update               */
554 /*              n((I)  - amount to adjust checksum by                       */
555 /*                                                                          */
556 /* Adjusts the 16bit checksum by "n" for packets going in.                  */
557 /* ------------------------------------------------------------------------ */
558 void fix_incksum(sp, n)
559 u_short *sp;
560 u_32_t n;
561 {
562 	u_short sumshort;
563 	u_32_t sum1;
564 
565 	if (n == 0)
566 		return;
567 
568 	sum1 = (~ntohs(*sp)) & 0xffff;
569 	sum1 += ~(n) & 0xffff;
570 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
571 	/* Again */
572 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
573 	sumshort = ~(u_short)sum1;
574 	*(sp) = htons(sumshort);
575 }
576 
577 
578 /* ------------------------------------------------------------------------ */
579 /* Function:    fix_datacksum                                               */
580 /* Returns:     Nil                                                         */
581 /* Parameters:  sp(I)  - location of 16bit checksum to update               */
582 /*              n((I)  - amount to adjust checksum by                       */
583 /*                                                                          */
584 /* Fix_datacksum is used *only* for the adjustments of checksums in the     */
585 /* data section of an IP packet.                                            */
586 /*                                                                          */
587 /* The only situation in which you need to do this is when NAT'ing an       */
588 /* ICMP error message. Such a message, contains in its body the IP header   */
589 /* of the original IP packet, that causes the error.                        */
590 /*                                                                          */
591 /* You can't use fix_incksum or fix_outcksum in that case, because for the  */
592 /* kernel the data section of the ICMP error is just data, and no special   */
593 /* processing like hardware cksum or ntohs processing have been done by the */
594 /* kernel on the data section.                                              */
595 /* ------------------------------------------------------------------------ */
596 void fix_datacksum(sp, n)
597 u_short *sp;
598 u_32_t n;
599 {
600 	u_short sumshort;
601 	u_32_t sum1;
602 
603 	if (n == 0)
604 		return;
605 
606 	sum1 = (~ntohs(*sp)) & 0xffff;
607 	sum1 += (n);
608 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
609 	/* Again */
610 	sum1 = (sum1 >> 16) + (sum1 & 0xffff);
611 	sumshort = ~(u_short)sum1;
612 	*(sp) = htons(sumshort);
613 }
614 
615 
616 /* ------------------------------------------------------------------------ */
617 /* Function:    fr_nat_ioctl                                                */
618 /* Returns:     int - 0 == success, != 0 == failure                         */
619 /* Parameters:  data(I) - pointer to ioctl data                             */
620 /*              cmd(I)  - ioctl command integer                             */
621 /*              mode(I) - file mode bits used with open                     */
622 /*                                                                          */
623 /* Processes an ioctl call made to operate on the IP Filter NAT device.     */
624 /* ------------------------------------------------------------------------ */
625 int fr_nat_ioctl(data, cmd, mode, uid, ctx, ifs)
626 ioctlcmd_t cmd;
627 caddr_t data;
628 int mode, uid;
629 void *ctx;
630 ipf_stack_t *ifs;
631 {
632 	ipnat_t *nat, *nt, *n = NULL, **np = NULL;
633 	int error = 0, ret, arg, getlock;
634 	ipnat_t natd;
635 
636 #if (BSD >= 199306) && defined(_KERNEL)
637 	if ((securelevel >= 2) && (mode & FWRITE))
638 		return EPERM;
639 #endif
640 
641 #if defined(__osf__) && defined(_KERNEL)
642 	getlock = 0;
643 #else
644 	getlock = (mode & NAT_LOCKHELD) ? 0 : 1;
645 #endif
646 
647 	nat = NULL;     /* XXX gcc -Wuninitialized */
648 	if (cmd == (ioctlcmd_t)SIOCADNAT) {
649 		KMALLOC(nt, ipnat_t *);
650 	} else {
651 		nt = NULL;
652 	}
653 
654 	if ((cmd == (ioctlcmd_t)SIOCADNAT) || (cmd == (ioctlcmd_t)SIOCRMNAT)) {
655 		if (mode & NAT_SYSSPACE) {
656 			bcopy(data, (char *)&natd, sizeof(natd));
657 			error = 0;
658 		} else {
659 			error = fr_inobj(data, &natd, IPFOBJ_IPNAT);
660 		}
661 
662 	} else if (cmd == (ioctlcmd_t)SIOCIPFFL) { /* SIOCFLNAT & SIOCCNATL */
663 		BCOPYIN(data, &arg, sizeof(arg));
664 	}
665 
666 	if (error != 0)
667 		goto done;
668 
669 	/*
670 	 * For add/delete, look to see if the NAT entry is already present
671 	 */
672 	if ((cmd == (ioctlcmd_t)SIOCADNAT) || (cmd == (ioctlcmd_t)SIOCRMNAT)) {
673 		nat = &natd;
674 		if (nat->in_v == 0)	/* For backward compat. */
675 			nat->in_v = 4;
676 		nat->in_flags &= IPN_USERFLAGS;
677 		if ((nat->in_redir & NAT_MAPBLK) == 0) {
678 			if ((nat->in_flags & IPN_SPLIT) == 0)
679 				nat->in_inip &= nat->in_inmsk;
680 			if ((nat->in_flags & IPN_IPRANGE) == 0)
681 				nat->in_outip &= nat->in_outmsk;
682 		}
683 		MUTEX_ENTER(&ifs->ifs_ipf_natio);
684 		for (np = &ifs->ifs_nat_list; ((n = *np) != NULL);
685 		     np = &n->in_next)
686 			if (!bcmp((char *)&nat->in_flags, (char *)&n->in_flags,
687 					IPN_CMPSIZ))
688 				break;
689 	}
690 
691 	switch (cmd)
692 	{
693 	case SIOCGENITER :
694 	    {
695 		ipfgeniter_t iter;
696 		ipftoken_t *token;
697 
698 		error = fr_inobj(data, &iter, IPFOBJ_GENITER);
699 		if (error != 0)
700 			break;
701 
702 		token = ipf_findtoken(iter.igi_type, uid, ctx, ifs);
703 		if (token != NULL)
704 			error  = nat_iterator(token, &iter, ifs);
705 		else
706 			error = ESRCH;
707 		RWLOCK_EXIT(&ifs->ifs_ipf_tokens);
708 		break;
709 	    }
710 #ifdef  IPFILTER_LOG
711 	case SIOCIPFFB :
712 	{
713 		int tmp;
714 
715 		if (!(mode & FWRITE))
716 			error = EPERM;
717 		else {
718 			tmp = ipflog_clear(IPL_LOGNAT, ifs);
719 			BCOPYOUT((char *)&tmp, (char *)data, sizeof(tmp));
720 		}
721 		break;
722 	}
723 	case SIOCSETLG :
724 		if (!(mode & FWRITE))
725 			error = EPERM;
726 		else {
727 			BCOPYIN((char *)data,
728 				       (char *)&ifs->ifs_nat_logging,
729 				sizeof(ifs->ifs_nat_logging));
730 		}
731 		break;
732 	case SIOCGETLG :
733 		BCOPYOUT((char *)&ifs->ifs_nat_logging, (char *)data,
734 			sizeof(ifs->ifs_nat_logging));
735 		break;
736 	case FIONREAD :
737 		arg = ifs->ifs_iplused[IPL_LOGNAT];
738 		BCOPYOUT(&arg, data, sizeof(arg));
739 		break;
740 #endif
741 	case SIOCADNAT :
742 		if (!(mode & FWRITE)) {
743 			error = EPERM;
744 		} else if (n != NULL) {
745 			error = EEXIST;
746 		} else if (nt == NULL) {
747 			error = ENOMEM;
748 		}
749 		if (error != 0) {
750 			MUTEX_EXIT(&ifs->ifs_ipf_natio);
751 			break;
752 		}
753 		bcopy((char *)nat, (char *)nt, sizeof(*n));
754 		error = nat_siocaddnat(nt, np, getlock, ifs);
755 		MUTEX_EXIT(&ifs->ifs_ipf_natio);
756 		if (error == 0)
757 			nt = NULL;
758 		break;
759 	case SIOCRMNAT :
760 		if (!(mode & FWRITE)) {
761 			error = EPERM;
762 			n = NULL;
763 		} else if (n == NULL) {
764 			error = ESRCH;
765 		}
766 
767 		if (error != 0) {
768 			MUTEX_EXIT(&ifs->ifs_ipf_natio);
769 			break;
770 		}
771 		nat_siocdelnat(n, np, getlock, ifs);
772 
773 		MUTEX_EXIT(&ifs->ifs_ipf_natio);
774 		n = NULL;
775 		break;
776 	case SIOCGNATS :
777 		ifs->ifs_nat_stats.ns_table[0] = ifs->ifs_nat_table[0];
778 		ifs->ifs_nat_stats.ns_table[1] = ifs->ifs_nat_table[1];
779 		ifs->ifs_nat_stats.ns_list = ifs->ifs_nat_list;
780 		ifs->ifs_nat_stats.ns_maptable = ifs->ifs_maptable;
781 		ifs->ifs_nat_stats.ns_maplist = ifs->ifs_ipf_hm_maplist;
782 		ifs->ifs_nat_stats.ns_nattab_max = ifs->ifs_ipf_nattable_max;
783 		ifs->ifs_nat_stats.ns_nattab_sz = ifs->ifs_ipf_nattable_sz;
784 		ifs->ifs_nat_stats.ns_rultab_sz = ifs->ifs_ipf_natrules_sz;
785 		ifs->ifs_nat_stats.ns_rdrtab_sz = ifs->ifs_ipf_rdrrules_sz;
786 		ifs->ifs_nat_stats.ns_hostmap_sz = ifs->ifs_ipf_hostmap_sz;
787 		ifs->ifs_nat_stats.ns_instances = ifs->ifs_nat_instances;
788 		ifs->ifs_nat_stats.ns_apslist = ifs->ifs_ap_sess_list;
789 		error = fr_outobj(data, &ifs->ifs_nat_stats, IPFOBJ_NATSTAT);
790 		break;
791 	case SIOCGNATL :
792 	    {
793 		natlookup_t nl;
794 
795 		if (getlock) {
796 			READ_ENTER(&ifs->ifs_ipf_nat);
797 		}
798 		error = fr_inobj(data, &nl, IPFOBJ_NATLOOKUP);
799 		if (error == 0) {
800 			if (nat_lookupredir(&nl, ifs) != NULL) {
801 				error = fr_outobj(data, &nl, IPFOBJ_NATLOOKUP);
802 			} else {
803 				error = ESRCH;
804 			}
805 		}
806 		if (getlock) {
807 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
808 		}
809 		break;
810 	    }
811 	case SIOCIPFFL :	/* old SIOCFLNAT & SIOCCNATL */
812 		if (!(mode & FWRITE)) {
813 			error = EPERM;
814 			break;
815 		}
816 		if (getlock) {
817 			WRITE_ENTER(&ifs->ifs_ipf_nat);
818 		}
819 		error = 0;
820 		if (arg == 0)
821 			ret = nat_flushtable(ifs);
822 		else if (arg == 1)
823 			ret = nat_clearlist(ifs);
824 		else if (arg >= 2 && arg <= 4)
825 			ret = nat_extraflush(arg - 2, ifs);
826 		else
827 			error = EINVAL;
828 		if (getlock) {
829 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
830 		}
831 		if (error == 0) {
832 			BCOPYOUT(&ret, data, sizeof(ret));
833 		}
834 		break;
835 	case SIOCPROXY :
836 		error = appr_ioctl(data, cmd, mode, ifs);
837 		break;
838 	case SIOCSTLCK :
839 		if (!(mode & FWRITE)) {
840 			error = EPERM;
841 		} else {
842 			fr_lock(data, &ifs->ifs_fr_nat_lock);
843 		}
844 		break;
845 	case SIOCSTPUT :
846 		if ((mode & FWRITE) != 0) {
847 			error = fr_natputent(data, getlock, ifs);
848 		} else {
849 			error = EACCES;
850 		}
851 		break;
852 	case SIOCSTGSZ :
853 		if (ifs->ifs_fr_nat_lock) {
854 			if (getlock) {
855 				READ_ENTER(&ifs->ifs_ipf_nat);
856 			}
857 			error = fr_natgetsz(data, ifs);
858 			if (getlock) {
859 				RWLOCK_EXIT(&ifs->ifs_ipf_nat);
860 			}
861 		} else
862 			error = EACCES;
863 		break;
864 	case SIOCSTGET :
865 		if (ifs->ifs_fr_nat_lock) {
866 			if (getlock) {
867 				READ_ENTER(&ifs->ifs_ipf_nat);
868 			}
869 			error = fr_natgetent(data, ifs);
870 			if (getlock) {
871 				RWLOCK_EXIT(&ifs->ifs_ipf_nat);
872 			}
873 		} else
874 			error = EACCES;
875 		break;
876 	case SIOCIPFDELTOK :
877 		(void) BCOPYIN((caddr_t)data, (caddr_t)&arg, sizeof(arg));
878 		error = ipf_deltoken(arg, uid, ctx, ifs);
879 		break;
880 	default :
881 		error = EINVAL;
882 		break;
883 	}
884 done:
885 	if (nt)
886 		KFREE(nt);
887 	return error;
888 }
889 
890 
891 /* ------------------------------------------------------------------------ */
892 /* Function:    nat_siocaddnat                                              */
893 /* Returns:     int - 0 == success, != 0 == failure                         */
894 /* Parameters:  n(I)       - pointer to new NAT rule                        */
895 /*              np(I)      - pointer to where to insert new NAT rule        */
896 /*              getlock(I) - flag indicating if lock on ipf_nat is held     */
897 /* Mutex Locks: ipf_natio                                                   */
898 /*                                                                          */
899 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
900 /* from information passed to the kernel, then add it  to the appropriate   */
901 /* NAT rule table(s).                                                       */
902 /* ------------------------------------------------------------------------ */
903 static int nat_siocaddnat(n, np, getlock, ifs)
904 ipnat_t *n, **np;
905 int getlock;
906 ipf_stack_t *ifs;
907 {
908 	int error = 0, i, j;
909 
910 	if (nat_resolverule(n, ifs) != 0)
911 		return ENOENT;
912 
913 	if ((n->in_age[0] == 0) && (n->in_age[1] != 0))
914 		return EINVAL;
915 
916 	n->in_use = 0;
917 	if (n->in_redir & NAT_MAPBLK)
918 		n->in_space = USABLE_PORTS * ~ntohl(n->in_outmsk);
919 	else if (n->in_flags & IPN_AUTOPORTMAP)
920 		n->in_space = USABLE_PORTS * ~ntohl(n->in_inmsk);
921 	else if (n->in_flags & IPN_IPRANGE)
922 		n->in_space = ntohl(n->in_outmsk) - ntohl(n->in_outip);
923 	else if (n->in_flags & IPN_SPLIT)
924 		n->in_space = 2;
925 	else if (n->in_outmsk != 0)
926 		n->in_space = ~ntohl(n->in_outmsk);
927 	else
928 		n->in_space = 1;
929 
930 	/*
931 	 * Calculate the number of valid IP addresses in the output
932 	 * mapping range.  In all cases, the range is inclusive of
933 	 * the start and ending IP addresses.
934 	 * If to a CIDR address, lose 2: broadcast + network address
935 	 *                               (so subtract 1)
936 	 * If to a range, add one.
937 	 * If to a single IP address, set to 1.
938 	 */
939 	if (n->in_space) {
940 		if ((n->in_flags & IPN_IPRANGE) != 0)
941 			n->in_space += 1;
942 		else
943 			n->in_space -= 1;
944 	} else
945 		n->in_space = 1;
946 
947 	if ((n->in_outmsk != 0xffffffff) && (n->in_outmsk != 0) &&
948 	    ((n->in_flags & (IPN_IPRANGE|IPN_SPLIT)) == 0))
949 		n->in_nip = ntohl(n->in_outip) + 1;
950 	else if ((n->in_flags & IPN_SPLIT) &&
951 		 (n->in_redir & NAT_REDIRECT))
952 		n->in_nip = ntohl(n->in_inip);
953 	else
954 		n->in_nip = ntohl(n->in_outip);
955 	if (n->in_redir & NAT_MAP) {
956 		n->in_pnext = ntohs(n->in_pmin);
957 		/*
958 		 * Multiply by the number of ports made available.
959 		 */
960 		if (ntohs(n->in_pmax) >= ntohs(n->in_pmin)) {
961 			n->in_space *= (ntohs(n->in_pmax) -
962 					ntohs(n->in_pmin) + 1);
963 			/*
964 			 * Because two different sources can map to
965 			 * different destinations but use the same
966 			 * local IP#/port #.
967 			 * If the result is smaller than in_space, then
968 			 * we may have wrapped around 32bits.
969 			 */
970 			i = n->in_inmsk;
971 			if ((i != 0) && (i != 0xffffffff)) {
972 				j = n->in_space * (~ntohl(i) + 1);
973 				if (j >= n->in_space)
974 					n->in_space = j;
975 				else
976 					n->in_space = 0xffffffff;
977 			}
978 		}
979 		/*
980 		 * If no protocol is specified, multiple by 256 to allow for
981 		 * at least one IP:IP mapping per protocol.
982 		 */
983 		if ((n->in_flags & IPN_TCPUDPICMP) == 0) {
984 				j = n->in_space * 256;
985 				if (j >= n->in_space)
986 					n->in_space = j;
987 				else
988 					n->in_space = 0xffffffff;
989 		}
990 	}
991 
992 	/* Otherwise, these fields are preset */
993 
994 	if (getlock) {
995 		WRITE_ENTER(&ifs->ifs_ipf_nat);
996 	}
997 	n->in_next = NULL;
998 	*np = n;
999 
1000 	if (n->in_age[0] != 0)
1001 	    n->in_tqehead[0] = fr_addtimeoutqueue(&ifs->ifs_nat_utqe,
1002 						  n->in_age[0], ifs);
1003 
1004 	if (n->in_age[1] != 0)
1005 	    n->in_tqehead[1] = fr_addtimeoutqueue(&ifs->ifs_nat_utqe,
1006 						  n->in_age[1], ifs);
1007 
1008 	if (n->in_redir & NAT_REDIRECT) {
1009 		n->in_flags &= ~IPN_NOTDST;
1010 		nat_addrdr(n, ifs);
1011 	}
1012 	if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
1013 		n->in_flags &= ~IPN_NOTSRC;
1014 		nat_addnat(n, ifs);
1015 	}
1016 	n = NULL;
1017 	ifs->ifs_nat_stats.ns_rules++;
1018 	if (getlock) {
1019 		RWLOCK_EXIT(&ifs->ifs_ipf_nat);			/* WRITE */
1020 	}
1021 
1022 	return error;
1023 }
1024 
1025 
1026 /* ------------------------------------------------------------------------ */
1027 /* Function:    nat_resolvrule                                              */
1028 /* Returns:     int - 0 == success, -1 == failure                           */
1029 /* Parameters:  n(I)  - pointer to NAT rule                                 */
1030 /*                                                                          */
1031 /* Resolve some of the details inside the NAT rule.  Includes resolving	    */
1032 /* any specified interfaces and proxy labels, and determines whether or not */
1033 /* all proxy labels are correctly specified.				    */
1034 /*									    */
1035 /* Called by nat_siocaddnat() (SIOCADNAT) and fr_natputent (SIOCSTPUT).     */
1036 /* ------------------------------------------------------------------------ */
1037 static int nat_resolverule(n, ifs)
1038 ipnat_t *n;
1039 ipf_stack_t *ifs;
1040 {
1041 	n->in_ifnames[0][LIFNAMSIZ - 1] = '\0';
1042 	n->in_ifps[0] = fr_resolvenic(n->in_ifnames[0], 4, ifs);
1043 
1044 	n->in_ifnames[1][LIFNAMSIZ - 1] = '\0';
1045 	if (n->in_ifnames[1][0] == '\0') {
1046 		(void) strncpy(n->in_ifnames[1], n->in_ifnames[0], LIFNAMSIZ);
1047 		n->in_ifps[1] = n->in_ifps[0];
1048 	} else {
1049 		n->in_ifps[1] = fr_resolvenic(n->in_ifnames[1], 4, ifs);
1050 	}
1051 
1052 	if (n->in_plabel[0] != '\0') {
1053 		n->in_apr = appr_lookup(n->in_p, n->in_plabel, ifs);
1054 		if (n->in_apr == NULL)
1055 			return -1;
1056 	}
1057 	return 0;
1058 }
1059 
1060 
1061 /* ------------------------------------------------------------------------ */
1062 /* Function:    nat_siocdelnat                                              */
1063 /* Returns:     int - 0 == success, != 0 == failure                         */
1064 /* Parameters:  n(I)       - pointer to new NAT rule                        */
1065 /*              np(I)      - pointer to where to insert new NAT rule        */
1066 /*              getlock(I) - flag indicating if lock on ipf_nat is held     */
1067 /* Mutex Locks: ipf_natio                                                   */
1068 /*                                                                          */
1069 /* Handle SIOCADNAT.  Resolve and calculate details inside the NAT rule     */
1070 /* from information passed to the kernel, then add it  to the appropriate   */
1071 /* NAT rule table(s).                                                       */
1072 /* ------------------------------------------------------------------------ */
1073 static void nat_siocdelnat(n, np, getlock, ifs)
1074 ipnat_t *n, **np;
1075 int getlock;
1076 ipf_stack_t *ifs;
1077 {
1078 	if (getlock) {
1079 		WRITE_ENTER(&ifs->ifs_ipf_nat);
1080 	}
1081 	if (n->in_redir & NAT_REDIRECT)
1082 		nat_delrdr(n);
1083 	if (n->in_redir & (NAT_MAPBLK|NAT_MAP))
1084 		nat_delnat(n);
1085 	if (ifs->ifs_nat_list == NULL) {
1086 		ifs->ifs_nat_masks = 0;
1087 		ifs->ifs_rdr_masks = 0;
1088 	}
1089 
1090 	if (n->in_tqehead[0] != NULL) {
1091 		if (fr_deletetimeoutqueue(n->in_tqehead[0]) == 0) {
1092 			fr_freetimeoutqueue(n->in_tqehead[0], ifs);
1093 		}
1094 	}
1095 
1096 	if (n->in_tqehead[1] != NULL) {
1097 		if (fr_deletetimeoutqueue(n->in_tqehead[1]) == 0) {
1098 			fr_freetimeoutqueue(n->in_tqehead[1], ifs);
1099 		}
1100 	}
1101 
1102 	*np = n->in_next;
1103 
1104 	if (n->in_use == 0) {
1105 		if (n->in_apr)
1106 			appr_free(n->in_apr);
1107 		KFREE(n);
1108 		ifs->ifs_nat_stats.ns_rules--;
1109 	} else {
1110 		n->in_flags |= IPN_DELETE;
1111 		n->in_next = NULL;
1112 	}
1113 	if (getlock) {
1114 		RWLOCK_EXIT(&ifs->ifs_ipf_nat);			/* READ/WRITE */
1115 	}
1116 }
1117 
1118 
1119 /* ------------------------------------------------------------------------ */
1120 /* Function:    fr_natgetsz                                                 */
1121 /* Returns:     int - 0 == success, != 0 is the error value.                */
1122 /* Parameters:  data(I) - pointer to natget structure with kernel pointer   */
1123 /*                        get the size of.                                  */
1124 /*                                                                          */
1125 /* Handle SIOCSTGSZ.                                                        */
1126 /* Return the size of the nat list entry to be copied back to user space.   */
1127 /* The size of the entry is stored in the ng_sz field and the enture natget */
1128 /* structure is copied back to the user.                                    */
1129 /* ------------------------------------------------------------------------ */
1130 static int fr_natgetsz(data, ifs)
1131 caddr_t data;
1132 ipf_stack_t *ifs;
1133 {
1134 	ap_session_t *aps;
1135 	nat_t *nat, *n;
1136 	natget_t ng;
1137 
1138 	BCOPYIN(data, &ng, sizeof(ng));
1139 
1140 	nat = ng.ng_ptr;
1141 	if (!nat) {
1142 		nat = ifs->ifs_nat_instances;
1143 		ng.ng_sz = 0;
1144 		/*
1145 		 * Empty list so the size returned is 0.  Simple.
1146 		 */
1147 		if (nat == NULL) {
1148 			BCOPYOUT(&ng, data, sizeof(ng));
1149 			return 0;
1150 		}
1151 	} else {
1152 		/*
1153 		 * Make sure the pointer we're copying from exists in the
1154 		 * current list of entries.  Security precaution to prevent
1155 		 * copying of random kernel data.
1156 		 */
1157 		for (n = ifs->ifs_nat_instances; n; n = n->nat_next)
1158 			if (n == nat)
1159 				break;
1160 		if (!n)
1161 			return ESRCH;
1162 	}
1163 
1164 	/*
1165 	 * Incluse any space required for proxy data structures.
1166 	 */
1167 	ng.ng_sz = sizeof(nat_save_t);
1168 	aps = nat->nat_aps;
1169 	if (aps != NULL) {
1170 		ng.ng_sz += sizeof(ap_session_t) - 4;
1171 		if (aps->aps_data != 0)
1172 			ng.ng_sz += aps->aps_psiz;
1173 	}
1174 
1175 	BCOPYOUT(&ng, data, sizeof(ng));
1176 	return 0;
1177 }
1178 
1179 
1180 /* ------------------------------------------------------------------------ */
1181 /* Function:    fr_natgetent                                                */
1182 /* Returns:     int - 0 == success, != 0 is the error value.                */
1183 /* Parameters:  data(I) - pointer to natget structure with kernel pointer   */
1184 /*                        to NAT structure to copy out.                     */
1185 /*                                                                          */
1186 /* Handle SIOCSTGET.                                                        */
1187 /* Copies out NAT entry to user space.  Any additional data held for a      */
1188 /* proxy is also copied, as to is the NAT rule which was responsible for it */
1189 /* ------------------------------------------------------------------------ */
1190 static int fr_natgetent(data, ifs)
1191 caddr_t data;
1192 ipf_stack_t *ifs;
1193 {
1194 	int error, outsize;
1195 	ap_session_t *aps;
1196 	nat_save_t *ipn, ipns;
1197 	nat_t *n, *nat;
1198 
1199 	error = fr_inobj(data, &ipns, IPFOBJ_NATSAVE);
1200 	if (error != 0)
1201 		return error;
1202 
1203 	if ((ipns.ipn_dsize < sizeof(ipns)) || (ipns.ipn_dsize > 81920))
1204 		return EINVAL;
1205 
1206 	KMALLOCS(ipn, nat_save_t *, ipns.ipn_dsize);
1207 	if (ipn == NULL)
1208 		return ENOMEM;
1209 
1210 	ipn->ipn_dsize = ipns.ipn_dsize;
1211 	nat = ipns.ipn_next;
1212 	if (nat == NULL) {
1213 		nat = ifs->ifs_nat_instances;
1214 		if (nat == NULL) {
1215 			if (ifs->ifs_nat_instances == NULL)
1216 				error = ENOENT;
1217 			goto finished;
1218 		}
1219 	} else {
1220 		/*
1221 		 * Make sure the pointer we're copying from exists in the
1222 		 * current list of entries.  Security precaution to prevent
1223 		 * copying of random kernel data.
1224 		 */
1225 		for (n = ifs->ifs_nat_instances; n; n = n->nat_next)
1226 			if (n == nat)
1227 				break;
1228 		if (n == NULL) {
1229 			error = ESRCH;
1230 			goto finished;
1231 		}
1232 	}
1233 	ipn->ipn_next = nat->nat_next;
1234 
1235 	/*
1236 	 * Copy the NAT structure.
1237 	 */
1238 	bcopy((char *)nat, &ipn->ipn_nat, sizeof(*nat));
1239 
1240 	/*
1241 	 * If we have a pointer to the NAT rule it belongs to, save that too.
1242 	 */
1243 	if (nat->nat_ptr != NULL)
1244 		bcopy((char *)nat->nat_ptr, (char *)&ipn->ipn_ipnat,
1245 		      sizeof(ipn->ipn_ipnat));
1246 
1247 	/*
1248 	 * If we also know the NAT entry has an associated filter rule,
1249 	 * save that too.
1250 	 */
1251 	if (nat->nat_fr != NULL)
1252 		bcopy((char *)nat->nat_fr, (char *)&ipn->ipn_fr,
1253 		      sizeof(ipn->ipn_fr));
1254 
1255 	/*
1256 	 * Last but not least, if there is an application proxy session set
1257 	 * up for this NAT entry, then copy that out too, including any
1258 	 * private data saved along side it by the proxy.
1259 	 */
1260 	aps = nat->nat_aps;
1261 	outsize = ipn->ipn_dsize - sizeof(*ipn) + sizeof(ipn->ipn_data);
1262 	if (aps != NULL) {
1263 		char *s;
1264 
1265 		if (outsize < sizeof(*aps)) {
1266 			error = ENOBUFS;
1267 			goto finished;
1268 		}
1269 
1270 		s = ipn->ipn_data;
1271 		bcopy((char *)aps, s, sizeof(*aps));
1272 		s += sizeof(*aps);
1273 		outsize -= sizeof(*aps);
1274 		if ((aps->aps_data != NULL) && (outsize >= aps->aps_psiz))
1275 			bcopy(aps->aps_data, s, aps->aps_psiz);
1276 		else
1277 			error = ENOBUFS;
1278 	}
1279 	if (error == 0) {
1280 		error = fr_outobjsz(data, ipn, IPFOBJ_NATSAVE, ipns.ipn_dsize);
1281 	}
1282 
1283 finished:
1284 	if (ipn != NULL) {
1285 		KFREES(ipn, ipns.ipn_dsize);
1286 	}
1287 	return error;
1288 }
1289 
1290 
1291 /* ------------------------------------------------------------------------ */
1292 /* Function:    fr_natputent                                                */
1293 /* Returns:     int - 0 == success, != 0 is the error value.                */
1294 /* Parameters:  data(I) -     pointer to natget structure with NAT          */
1295 /*                            structure information to load into the kernel */
1296 /*              getlock(I) - flag indicating whether or not a write lock    */
1297 /*                           on ipf_nat is already held.                    */
1298 /*                                                                          */
1299 /* Handle SIOCSTPUT.                                                        */
1300 /* Loads a NAT table entry from user space, including a NAT rule, proxy and */
1301 /* firewall rule data structures, if pointers to them indicate so.          */
1302 /* ------------------------------------------------------------------------ */
1303 static int fr_natputent(data, getlock, ifs)
1304 caddr_t data;
1305 int getlock;
1306 ipf_stack_t *ifs;
1307 {
1308 	nat_save_t ipn, *ipnn;
1309 	ap_session_t *aps;
1310 	nat_t *n, *nat;
1311 	frentry_t *fr;
1312 	fr_info_t fin;
1313 	ipnat_t *in;
1314 	int error;
1315 
1316 	error = fr_inobj(data, &ipn, IPFOBJ_NATSAVE);
1317 	if (error != 0)
1318 		return error;
1319 
1320 	/*
1321 	 * Trigger automatic call to nat_extraflush() if the
1322 	 * table has reached capcity specified by hi watermark.
1323 	 */
1324 	if (NAT_TAB_WATER_LEVEL(ifs) > ifs->ifs_nat_flush_lvl_hi)
1325 		ifs->ifs_nat_doflush = 1;
1326 
1327 	/*
1328 	 * Initialise early because of code at junkput label.
1329 	 */
1330 	in = NULL;
1331 	aps = NULL;
1332 	nat = NULL;
1333 	ipnn = NULL;
1334 
1335 	/*
1336 	 * New entry, copy in the rest of the NAT entry if it's size is more
1337 	 * than just the nat_t structure.
1338 	 */
1339 	fr = NULL;
1340 	if (ipn.ipn_dsize > sizeof(ipn)) {
1341 		if (ipn.ipn_dsize > 81920) {
1342 			error = ENOMEM;
1343 			goto junkput;
1344 		}
1345 
1346 		KMALLOCS(ipnn, nat_save_t *, ipn.ipn_dsize);
1347 		if (ipnn == NULL)
1348 			return ENOMEM;
1349 
1350 		error = fr_inobjsz(data, ipnn, IPFOBJ_NATSAVE, ipn.ipn_dsize);
1351 		if (error != 0) {
1352 			error = EFAULT;
1353 			goto junkput;
1354 		}
1355 	} else
1356 		ipnn = &ipn;
1357 
1358 	KMALLOC(nat, nat_t *);
1359 	if (nat == NULL) {
1360 		error = ENOMEM;
1361 		goto junkput;
1362 	}
1363 
1364 	bcopy((char *)&ipnn->ipn_nat, (char *)nat, sizeof(*nat));
1365 	/*
1366 	 * Initialize all these so that nat_delete() doesn't cause a crash.
1367 	 */
1368 	bzero((char *)nat, offsetof(struct nat, nat_tqe));
1369 	nat->nat_tqe.tqe_pnext = NULL;
1370 	nat->nat_tqe.tqe_next = NULL;
1371 	nat->nat_tqe.tqe_ifq = NULL;
1372 	nat->nat_tqe.tqe_parent = nat;
1373 
1374 	/*
1375 	 * Restore the rule associated with this nat session
1376 	 */
1377 	in = ipnn->ipn_nat.nat_ptr;
1378 	if (in != NULL) {
1379 		KMALLOC(in, ipnat_t *);
1380 		nat->nat_ptr = in;
1381 		if (in == NULL) {
1382 			error = ENOMEM;
1383 			goto junkput;
1384 		}
1385 		bzero((char *)in, offsetof(struct ipnat, in_next6));
1386 		bcopy((char *)&ipnn->ipn_ipnat, (char *)in, sizeof(*in));
1387 		in->in_use = 1;
1388 		in->in_flags |= IPN_DELETE;
1389 
1390 		ATOMIC_INC(ifs->ifs_nat_stats.ns_rules);
1391 
1392 		if (nat_resolverule(in, ifs) != 0) {
1393 			error = ESRCH;
1394 			goto junkput;
1395 		}
1396 	}
1397 
1398 	/*
1399 	 * Check that the NAT entry doesn't already exist in the kernel.
1400 	 */
1401 	bzero((char *)&fin, sizeof(fin));
1402 	fin.fin_p = nat->nat_p;
1403 	fin.fin_ifs = ifs;
1404 	if (nat->nat_dir == NAT_OUTBOUND) {
1405 		fin.fin_data[0] = ntohs(nat->nat_oport);
1406 		fin.fin_data[1] = ntohs(nat->nat_outport);
1407 		fin.fin_ifp = nat->nat_ifps[0];
1408 		if (getlock) {
1409 			READ_ENTER(&ifs->ifs_ipf_nat);
1410 		}
1411 		n = nat_inlookup(&fin, nat->nat_flags, fin.fin_p,
1412 			nat->nat_oip, nat->nat_outip);
1413 		if (getlock) {
1414 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
1415 		}
1416 		if (n != NULL) {
1417 			error = EEXIST;
1418 			goto junkput;
1419 		}
1420 	} else if (nat->nat_dir == NAT_INBOUND) {
1421 		fin.fin_data[0] = ntohs(nat->nat_inport);
1422 		fin.fin_data[1] = ntohs(nat->nat_oport);
1423 		fin.fin_ifp = nat->nat_ifps[1];
1424 		if (getlock) {
1425 			READ_ENTER(&ifs->ifs_ipf_nat);
1426 		}
1427 		n = nat_outlookup(&fin, nat->nat_flags, fin.fin_p,
1428 			nat->nat_inip, nat->nat_oip);
1429 		if (getlock) {
1430 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
1431 		}
1432 		if (n != NULL) {
1433 			error = EEXIST;
1434 			goto junkput;
1435 		}
1436 	} else {
1437 		error = EINVAL;
1438 		goto junkput;
1439 	}
1440 
1441 	/*
1442 	 * Restore ap_session_t structure.  Include the private data allocated
1443 	 * if it was there.
1444 	 */
1445 	aps = nat->nat_aps;
1446 	if (aps != NULL) {
1447 		KMALLOC(aps, ap_session_t *);
1448 		nat->nat_aps = aps;
1449 		if (aps == NULL) {
1450 			error = ENOMEM;
1451 			goto junkput;
1452 		}
1453 		bcopy(ipnn->ipn_data, (char *)aps, sizeof(*aps));
1454 		if (in != NULL)
1455 			aps->aps_apr = in->in_apr;
1456 		else
1457 			aps->aps_apr = NULL;
1458 		if (aps->aps_psiz != 0) {
1459 			if (aps->aps_psiz > 81920) {
1460 				error = ENOMEM;
1461 				goto junkput;
1462 			}
1463 			KMALLOCS(aps->aps_data, void *, aps->aps_psiz);
1464 			if (aps->aps_data == NULL) {
1465 				error = ENOMEM;
1466 				goto junkput;
1467 			}
1468 			bcopy(ipnn->ipn_data + sizeof(*aps), aps->aps_data,
1469 			      aps->aps_psiz);
1470 		} else {
1471 			aps->aps_psiz = 0;
1472 			aps->aps_data = NULL;
1473 		}
1474 	}
1475 
1476 	/*
1477 	 * If there was a filtering rule associated with this entry then
1478 	 * build up a new one.
1479 	 */
1480 	fr = nat->nat_fr;
1481 	if (fr != NULL) {
1482 		if ((nat->nat_flags & SI_NEWFR) != 0) {
1483 			KMALLOC(fr, frentry_t *);
1484 			nat->nat_fr = fr;
1485 			if (fr == NULL) {
1486 				error = ENOMEM;
1487 				goto junkput;
1488 			}
1489 			ipnn->ipn_nat.nat_fr = fr;
1490 			(void) fr_outobj(data, ipnn, IPFOBJ_NATSAVE);
1491 			bcopy((char *)&ipnn->ipn_fr, (char *)fr, sizeof(*fr));
1492 
1493 			fr->fr_ref = 1;
1494 			fr->fr_dsize = 0;
1495 			fr->fr_data = NULL;
1496 			fr->fr_type = FR_T_NONE;
1497 
1498 			MUTEX_NUKE(&fr->fr_lock);
1499 			MUTEX_INIT(&fr->fr_lock, "nat-filter rule lock");
1500 		} else {
1501 			if (getlock) {
1502 				READ_ENTER(&ifs->ifs_ipf_nat);
1503 			}
1504 			for (n = ifs->ifs_nat_instances; n; n = n->nat_next)
1505 				if (n->nat_fr == fr)
1506 					break;
1507 
1508 			if (n != NULL) {
1509 				MUTEX_ENTER(&fr->fr_lock);
1510 				fr->fr_ref++;
1511 				MUTEX_EXIT(&fr->fr_lock);
1512 			}
1513 			if (getlock) {
1514 				RWLOCK_EXIT(&ifs->ifs_ipf_nat);
1515 			}
1516 			if (!n) {
1517 				error = ESRCH;
1518 				goto junkput;
1519 			}
1520 		}
1521 	}
1522 
1523 	if (ipnn != &ipn) {
1524 		KFREES(ipnn, ipn.ipn_dsize);
1525 		ipnn = NULL;
1526 	}
1527 
1528 	if (getlock) {
1529 		WRITE_ENTER(&ifs->ifs_ipf_nat);
1530 	}
1531 	error = nat_insert(nat, nat->nat_rev, ifs);
1532 	if ((error == 0) && (aps != NULL)) {
1533 		aps->aps_next = ifs->ifs_ap_sess_list;
1534 		ifs->ifs_ap_sess_list = aps;
1535 	}
1536 	if (getlock) {
1537 		RWLOCK_EXIT(&ifs->ifs_ipf_nat);
1538 	}
1539 
1540 	if (error == 0)
1541 		return 0;
1542 
1543 	error = ENOMEM;
1544 
1545 junkput:
1546 	if (fr != NULL)
1547 		(void) fr_derefrule(&fr, ifs);
1548 
1549 	if ((ipnn != NULL) && (ipnn != &ipn)) {
1550 		KFREES(ipnn, ipn.ipn_dsize);
1551 	}
1552 	if (nat != NULL) {
1553 		if (aps != NULL) {
1554 			if (aps->aps_data != NULL) {
1555 				KFREES(aps->aps_data, aps->aps_psiz);
1556 			}
1557 			KFREE(aps);
1558 		}
1559 		if (in != NULL) {
1560 			if (in->in_apr)
1561 				appr_free(in->in_apr);
1562 			KFREE(in);
1563 		}
1564 		KFREE(nat);
1565 	}
1566 	return error;
1567 }
1568 
1569 
1570 /* ------------------------------------------------------------------------ */
1571 /* Function:    nat_delete                                                  */
1572 /* Returns:     Nil                                                         */
1573 /* Parameters:  natd(I)    - pointer to NAT structure to delete             */
1574 /*              logtype(I) - type of LOG record to create before deleting   */
1575 /* Write Lock:  ipf_nat                                                     */
1576 /*                                                                          */
1577 /* Delete a nat entry from the various lists and table.  If NAT logging is  */
1578 /* enabled then generate a NAT log record for this event.                   */
1579 /* ------------------------------------------------------------------------ */
1580 static void nat_delete(nat, logtype, ifs)
1581 struct nat *nat;
1582 int logtype;
1583 ipf_stack_t *ifs;
1584 {
1585 	struct ipnat *ipn;
1586 
1587 	if (logtype != 0 && ifs->ifs_nat_logging != 0)
1588 		nat_log(nat, logtype, ifs);
1589 
1590 	MUTEX_ENTER(&ifs->ifs_ipf_nat_new);
1591 
1592 	/*
1593 	 * Take it as a general indication that all the pointers are set if
1594 	 * nat_pnext is set.
1595 	 */
1596 	if (nat->nat_pnext != NULL) {
1597 		ifs->ifs_nat_stats.ns_bucketlen[0][nat->nat_hv[0]]--;
1598 		ifs->ifs_nat_stats.ns_bucketlen[1][nat->nat_hv[1]]--;
1599 
1600 		*nat->nat_pnext = nat->nat_next;
1601 		if (nat->nat_next != NULL) {
1602 			nat->nat_next->nat_pnext = nat->nat_pnext;
1603 			nat->nat_next = NULL;
1604 		}
1605 		nat->nat_pnext = NULL;
1606 
1607 		*nat->nat_phnext[0] = nat->nat_hnext[0];
1608 		if (nat->nat_hnext[0] != NULL) {
1609 			nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
1610 			nat->nat_hnext[0] = NULL;
1611 		}
1612 		nat->nat_phnext[0] = NULL;
1613 
1614 		*nat->nat_phnext[1] = nat->nat_hnext[1];
1615 		if (nat->nat_hnext[1] != NULL) {
1616 			nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
1617 			nat->nat_hnext[1] = NULL;
1618 		}
1619 		nat->nat_phnext[1] = NULL;
1620 
1621 		if ((nat->nat_flags & SI_WILDP) != 0)
1622 			ifs->ifs_nat_stats.ns_wilds--;
1623 	}
1624 
1625 	if (nat->nat_me != NULL) {
1626 		*nat->nat_me = NULL;
1627 		nat->nat_me = NULL;
1628 	}
1629 
1630 	fr_deletequeueentry(&nat->nat_tqe);
1631 
1632 	nat->nat_ref--;
1633 	if (nat->nat_ref > 0) {
1634 		MUTEX_EXIT(&ifs->ifs_ipf_nat_new);
1635 		return;
1636 	}
1637 
1638 #ifdef	IPFILTER_SYNC
1639 	if (nat->nat_sync)
1640 		ipfsync_del(nat->nat_sync);
1641 #endif
1642 
1643 	if (nat->nat_fr != NULL)
1644 		(void)fr_derefrule(&nat->nat_fr, ifs);
1645 
1646 	if (nat->nat_hm != NULL)
1647 		nat_hostmapdel(nat->nat_hm);
1648 
1649 	/*
1650 	 * If there is an active reference from the nat entry to its parent
1651 	 * rule, decrement the rule's reference count and free it too if no
1652 	 * longer being used.
1653 	 */
1654 	ipn = nat->nat_ptr;
1655 	if (ipn != NULL) {
1656 		ipn->in_space++;
1657 		ipn->in_use--;
1658 		if (ipn->in_use == 0 && (ipn->in_flags & IPN_DELETE)) {
1659 			if (ipn->in_apr)
1660 				appr_free(ipn->in_apr);
1661 			KFREE(ipn);
1662 			ifs->ifs_nat_stats.ns_rules--;
1663 		}
1664 	}
1665 
1666 	MUTEX_DESTROY(&nat->nat_lock);
1667 
1668 	aps_free(nat->nat_aps, ifs);
1669 	ifs->ifs_nat_stats.ns_inuse--;
1670 	MUTEX_EXIT(&ifs->ifs_ipf_nat_new);
1671 
1672 	/*
1673 	 * If there's a fragment table entry too for this nat entry, then
1674 	 * dereference that as well.  This is after nat_lock is released
1675 	 * because of Tru64.
1676 	 */
1677 	fr_forgetnat((void *)nat, ifs);
1678 
1679 	KFREE(nat);
1680 }
1681 
1682 
1683 /* ------------------------------------------------------------------------ */
1684 /* Function:    nat_flushtable                                              */
1685 /* Returns:     int - number of NAT rules deleted                           */
1686 /* Parameters:  Nil                                                         */
1687 /*                                                                          */
1688 /* Deletes all currently active NAT sessions.  In deleting each NAT entry a */
1689 /* log record should be emitted in nat_delete() if NAT logging is enabled.  */
1690 /* ------------------------------------------------------------------------ */
1691 /*
1692  * nat_flushtable - clear the NAT table of all mapping entries.
1693  */
1694 static int nat_flushtable(ifs)
1695 ipf_stack_t *ifs;
1696 {
1697 	nat_t *nat;
1698 	int j = 0;
1699 
1700 	/*
1701 	 * ALL NAT mappings deleted, so lets just make the deletions
1702 	 * quicker.
1703 	 */
1704 	if (ifs->ifs_nat_table[0] != NULL)
1705 		bzero((char *)ifs->ifs_nat_table[0],
1706 		      sizeof(ifs->ifs_nat_table[0]) * ifs->ifs_ipf_nattable_sz);
1707 	if (ifs->ifs_nat_table[1] != NULL)
1708 		bzero((char *)ifs->ifs_nat_table[1],
1709 		      sizeof(ifs->ifs_nat_table[1]) * ifs->ifs_ipf_nattable_sz);
1710 
1711 	while ((nat = ifs->ifs_nat_instances) != NULL) {
1712 		nat_delete(nat, NL_FLUSH, ifs);
1713 		j++;
1714 	}
1715 
1716 	ifs->ifs_nat_stats.ns_inuse = 0;
1717 	return j;
1718 }
1719 
1720 
1721 /* ------------------------------------------------------------------------ */
1722 /* Function:    nat_clearlist                                               */
1723 /* Returns:     int - number of NAT/RDR rules deleted                       */
1724 /* Parameters:  Nil                                                         */
1725 /*                                                                          */
1726 /* Delete all rules in the current list of rules.  There is nothing elegant */
1727 /* about this cleanup: simply free all entries on the list of rules and     */
1728 /* clear out the tables used for hashed NAT rule lookups.                   */
1729 /* ------------------------------------------------------------------------ */
1730 static int nat_clearlist(ifs)
1731 ipf_stack_t *ifs;
1732 {
1733 	ipnat_t *n, **np = &ifs->ifs_nat_list;
1734 	int i = 0;
1735 
1736 	if (ifs->ifs_nat_rules != NULL)
1737 		bzero((char *)ifs->ifs_nat_rules,
1738 		      sizeof(*ifs->ifs_nat_rules) * ifs->ifs_ipf_natrules_sz);
1739 	if (ifs->ifs_rdr_rules != NULL)
1740 		bzero((char *)ifs->ifs_rdr_rules,
1741 		      sizeof(*ifs->ifs_rdr_rules) * ifs->ifs_ipf_rdrrules_sz);
1742 
1743 	while ((n = *np) != NULL) {
1744 		*np = n->in_next;
1745 		if (n->in_use == 0) {
1746 			if (n->in_apr != NULL)
1747 				appr_free(n->in_apr);
1748 			KFREE(n);
1749 			ifs->ifs_nat_stats.ns_rules--;
1750 		} else {
1751 			n->in_flags |= IPN_DELETE;
1752 			n->in_next = NULL;
1753 		}
1754 		i++;
1755 	}
1756 	ifs->ifs_nat_masks = 0;
1757 	ifs->ifs_rdr_masks = 0;
1758 	return i;
1759 }
1760 
1761 
1762 /* ------------------------------------------------------------------------ */
1763 /* Function:    nat_newmap                                                  */
1764 /* Returns:     int - -1 == error, 0 == success                             */
1765 /* Parameters:  fin(I) - pointer to packet information                      */
1766 /*              nat(I) - pointer to NAT entry                               */
1767 /*              ni(I)  - pointer to structure with misc. information needed */
1768 /*                       to create new NAT entry.                           */
1769 /*                                                                          */
1770 /* Given an empty NAT structure, populate it with new information about a   */
1771 /* new NAT session, as defined by the matching NAT rule.                    */
1772 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
1773 /* to the new IP address for the translation.                               */
1774 /* ------------------------------------------------------------------------ */
1775 static INLINE int nat_newmap(fin, nat, ni)
1776 fr_info_t *fin;
1777 nat_t *nat;
1778 natinfo_t *ni;
1779 {
1780 	u_short st_port, dport, sport, port, sp, dp;
1781 	struct in_addr in, inb;
1782 	hostmap_t *hm;
1783 	u_32_t flags;
1784 	u_32_t st_ip;
1785 	ipnat_t *np;
1786 	nat_t *natl;
1787 	int l;
1788 	ipf_stack_t *ifs = fin->fin_ifs;
1789 
1790 	/*
1791 	 * If it's an outbound packet which doesn't match any existing
1792 	 * record, then create a new port
1793 	 */
1794 	l = 0;
1795 	hm = NULL;
1796 	np = ni->nai_np;
1797 	st_ip = np->in_nip;
1798 	st_port = np->in_pnext;
1799 	flags = ni->nai_flags;
1800 	sport = ni->nai_sport;
1801 	dport = ni->nai_dport;
1802 
1803 	/*
1804 	 * Do a loop until we either run out of entries to try or we find
1805 	 * a NAT mapping that isn't currently being used.  This is done
1806 	 * because the change to the source is not (usually) being fixed.
1807 	 */
1808 	do {
1809 		port = 0;
1810 		in.s_addr = htonl(np->in_nip);
1811 		if (l == 0) {
1812 			/*
1813 			 * Check to see if there is an existing NAT
1814 			 * setup for this IP address pair.
1815 			 */
1816 			hm = nat_hostmap(np, fin->fin_src, fin->fin_dst,
1817 					 in, 0, ifs);
1818 			if (hm != NULL)
1819 				in.s_addr = hm->hm_mapip.s_addr;
1820 		} else if ((l == 1) && (hm != NULL)) {
1821 			nat_hostmapdel(hm);
1822 			hm = NULL;
1823 		}
1824 		in.s_addr = ntohl(in.s_addr);
1825 
1826 		nat->nat_hm = hm;
1827 
1828 		if ((np->in_outmsk == 0xffffffff) && (np->in_pnext == 0)) {
1829 			if (l > 0)
1830 				return -1;
1831 		}
1832 
1833 		if (np->in_redir == NAT_BIMAP &&
1834 		    np->in_inmsk == np->in_outmsk) {
1835 			/*
1836 			 * map the address block in a 1:1 fashion
1837 			 */
1838 			in.s_addr = np->in_outip;
1839 			in.s_addr |= fin->fin_saddr & ~np->in_inmsk;
1840 			in.s_addr = ntohl(in.s_addr);
1841 
1842 		} else if (np->in_redir & NAT_MAPBLK) {
1843 			if ((l >= np->in_ppip) || ((l > 0) &&
1844 			     !(flags & IPN_TCPUDP)))
1845 				return -1;
1846 			/*
1847 			 * map-block - Calculate destination address.
1848 			 */
1849 			in.s_addr = ntohl(fin->fin_saddr);
1850 			in.s_addr &= ntohl(~np->in_inmsk);
1851 			inb.s_addr = in.s_addr;
1852 			in.s_addr /= np->in_ippip;
1853 			in.s_addr &= ntohl(~np->in_outmsk);
1854 			in.s_addr += ntohl(np->in_outip);
1855 			/*
1856 			 * Calculate destination port.
1857 			 */
1858 			if ((flags & IPN_TCPUDP) &&
1859 			    (np->in_ppip != 0)) {
1860 				port = ntohs(sport) + l;
1861 				port %= np->in_ppip;
1862 				port += np->in_ppip *
1863 					(inb.s_addr % np->in_ippip);
1864 				port += MAPBLK_MINPORT;
1865 				port = htons(port);
1866 			}
1867 
1868 		} else if ((np->in_outip == 0) &&
1869 			   (np->in_outmsk == 0xffffffff)) {
1870 			/*
1871 			 * 0/32 - use the interface's IP address.
1872 			 */
1873 			if ((l > 0) ||
1874 			    fr_ifpaddr(4, FRI_NORMAL, fin->fin_ifp,
1875 				       &in, NULL, fin->fin_ifs) == -1)
1876 				return -1;
1877 			in.s_addr = ntohl(in.s_addr);
1878 
1879 		} else if ((np->in_outip == 0) && (np->in_outmsk == 0)) {
1880 			/*
1881 			 * 0/0 - use the original source address/port.
1882 			 */
1883 			if (l > 0)
1884 				return -1;
1885 			in.s_addr = ntohl(fin->fin_saddr);
1886 
1887 		} else if ((np->in_outmsk != 0xffffffff) &&
1888 			   (np->in_pnext == 0) && ((l > 0) || (hm == NULL)))
1889 			np->in_nip++;
1890 
1891 		natl = NULL;
1892 
1893 		if ((flags & IPN_TCPUDP) &&
1894 		    ((np->in_redir & NAT_MAPBLK) == 0) &&
1895 		    (np->in_flags & IPN_AUTOPORTMAP)) {
1896 			/*
1897 			 * "ports auto" (without map-block)
1898 			 */
1899 			if ((l > 0) && (l % np->in_ppip == 0)) {
1900 				if (l > np->in_space) {
1901 					return -1;
1902 				} else if ((l > np->in_ppip) &&
1903 					   np->in_outmsk != 0xffffffff)
1904 					np->in_nip++;
1905 			}
1906 			if (np->in_ppip != 0) {
1907 				port = ntohs(sport);
1908 				port += (l % np->in_ppip);
1909 				port %= np->in_ppip;
1910 				port += np->in_ppip *
1911 					(ntohl(fin->fin_saddr) %
1912 					 np->in_ippip);
1913 				port += MAPBLK_MINPORT;
1914 				port = htons(port);
1915 			}
1916 
1917 		} else if (((np->in_redir & NAT_MAPBLK) == 0) &&
1918 			   (flags & IPN_TCPUDPICMP) && (np->in_pnext != 0)) {
1919 			/*
1920 			 * Standard port translation.  Select next port.
1921 			 */
1922 			port = htons(np->in_pnext++);
1923 
1924 			if (np->in_pnext > ntohs(np->in_pmax)) {
1925 				np->in_pnext = ntohs(np->in_pmin);
1926 				if (np->in_outmsk != 0xffffffff)
1927 					np->in_nip++;
1928 			}
1929 		}
1930 
1931 		if (np->in_flags & IPN_IPRANGE) {
1932 			if (np->in_nip > ntohl(np->in_outmsk))
1933 				np->in_nip = ntohl(np->in_outip);
1934 		} else {
1935 			if ((np->in_outmsk != 0xffffffff) &&
1936 			    ((np->in_nip + 1) & ntohl(np->in_outmsk)) >
1937 			    ntohl(np->in_outip))
1938 				np->in_nip = ntohl(np->in_outip) + 1;
1939 		}
1940 
1941 		if ((port == 0) && (flags & (IPN_TCPUDPICMP|IPN_ICMPQUERY)))
1942 			port = sport;
1943 
1944 		/*
1945 		 * Here we do a lookup of the connection as seen from
1946 		 * the outside.  If an IP# pair already exists, try
1947 		 * again.  So if you have A->B becomes C->B, you can
1948 		 * also have D->E become C->E but not D->B causing
1949 		 * another C->B.  Also take protocol and ports into
1950 		 * account when determining whether a pre-existing
1951 		 * NAT setup will cause an external conflict where
1952 		 * this is appropriate.
1953 		 */
1954 		inb.s_addr = htonl(in.s_addr);
1955 		sp = fin->fin_data[0];
1956 		dp = fin->fin_data[1];
1957 		fin->fin_data[0] = fin->fin_data[1];
1958 		fin->fin_data[1] = htons(port);
1959 		natl = nat_inlookup(fin, flags & ~(SI_WILDP|NAT_SEARCH),
1960 				    (u_int)fin->fin_p, fin->fin_dst, inb);
1961 		fin->fin_data[0] = sp;
1962 		fin->fin_data[1] = dp;
1963 
1964 		/*
1965 		 * Has the search wrapped around and come back to the
1966 		 * start ?
1967 		 */
1968 		if ((natl != NULL) &&
1969 		    (np->in_pnext != 0) && (st_port == np->in_pnext) &&
1970 		    (np->in_nip != 0) && (st_ip == np->in_nip))
1971 			return -1;
1972 		l++;
1973 	} while (natl != NULL);
1974 
1975 	if (np->in_space > 0)
1976 		np->in_space--;
1977 
1978 	/* Setup the NAT table */
1979 	nat->nat_inip = fin->fin_src;
1980 	nat->nat_outip.s_addr = htonl(in.s_addr);
1981 	nat->nat_oip = fin->fin_dst;
1982 	if (nat->nat_hm == NULL)
1983 		nat->nat_hm = nat_hostmap(np, fin->fin_src, fin->fin_dst,
1984 					  nat->nat_outip, 0, ifs);
1985 
1986 	/*
1987 	 * The ICMP checksum does not have a pseudo header containing
1988 	 * the IP addresses
1989 	 */
1990 	ni->nai_sum1 = LONG_SUM(ntohl(fin->fin_saddr));
1991 	ni->nai_sum2 = LONG_SUM(in.s_addr);
1992 	if ((flags & IPN_TCPUDP)) {
1993 		ni->nai_sum1 += ntohs(sport);
1994 		ni->nai_sum2 += ntohs(port);
1995 	}
1996 
1997 	if (flags & IPN_TCPUDP) {
1998 		nat->nat_inport = sport;
1999 		nat->nat_outport = port;	/* sport */
2000 		nat->nat_oport = dport;
2001 		((tcphdr_t *)fin->fin_dp)->th_sport = port;
2002 	} else if (flags & IPN_ICMPQUERY) {
2003 		((icmphdr_t *)fin->fin_dp)->icmp_id = port;
2004 		nat->nat_inport = port;
2005 		nat->nat_outport = port;
2006 	}
2007 
2008 	ni->nai_ip.s_addr = in.s_addr;
2009 	ni->nai_port = port;
2010 	ni->nai_nport = dport;
2011 	return 0;
2012 }
2013 
2014 
2015 /* ------------------------------------------------------------------------ */
2016 /* Function:    nat_newrdr                                                  */
2017 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
2018 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
2019 /* Parameters:  fin(I) - pointer to packet information                      */
2020 /*              nat(I) - pointer to NAT entry                               */
2021 /*              ni(I)  - pointer to structure with misc. information needed */
2022 /*                       to create new NAT entry.                           */
2023 /*                                                                          */
2024 /* ni.nai_ip is passed in uninitialised and must be set, in host byte order,*/
2025 /* to the new IP address for the translation.                               */
2026 /* ------------------------------------------------------------------------ */
2027 static INLINE int nat_newrdr(fin, nat, ni)
2028 fr_info_t *fin;
2029 nat_t *nat;
2030 natinfo_t *ni;
2031 {
2032 	u_short nport, dport, sport;
2033 	struct in_addr in;
2034 	hostmap_t *hm;
2035 	u_32_t flags;
2036 	ipnat_t *np;
2037 	int move;
2038 	ipf_stack_t *ifs = fin->fin_ifs;
2039 
2040 	move = 1;
2041 	hm = NULL;
2042 	in.s_addr = 0;
2043 	np = ni->nai_np;
2044 	flags = ni->nai_flags;
2045 	sport = ni->nai_sport;
2046 	dport = ni->nai_dport;
2047 
2048 	/*
2049 	 * If the matching rule has IPN_STICKY set, then we want to have the
2050 	 * same rule kick in as before.  Why would this happen?  If you have
2051 	 * a collection of rdr rules with "round-robin sticky", the current
2052 	 * packet might match a different one to the previous connection but
2053 	 * we want the same destination to be used.
2054 	 */
2055 	if ((np->in_flags & (IPN_ROUNDR|IPN_STICKY)) ==
2056 	    (IPN_ROUNDR|IPN_STICKY)) {
2057 		hm = nat_hostmap(NULL, fin->fin_src, fin->fin_dst, in,
2058 				 (u_32_t)dport, ifs);
2059 		if (hm != NULL) {
2060 			in.s_addr = ntohl(hm->hm_mapip.s_addr);
2061 			np = hm->hm_ipnat;
2062 			ni->nai_np = np;
2063 			move = 0;
2064 		}
2065 	}
2066 
2067 	/*
2068 	 * Otherwise, it's an inbound packet. Most likely, we don't
2069 	 * want to rewrite source ports and source addresses. Instead,
2070 	 * we want to rewrite to a fixed internal address and fixed
2071 	 * internal port.
2072 	 */
2073 	if (np->in_flags & IPN_SPLIT) {
2074 		in.s_addr = np->in_nip;
2075 
2076 		if ((np->in_flags & (IPN_ROUNDR|IPN_STICKY)) == IPN_STICKY) {
2077 			hm = nat_hostmap(np, fin->fin_src, fin->fin_dst,
2078 					 in, (u_32_t)dport, ifs);
2079 			if (hm != NULL) {
2080 				in.s_addr = hm->hm_mapip.s_addr;
2081 				move = 0;
2082 			}
2083 		}
2084 
2085 		if (hm == NULL || hm->hm_ref == 1) {
2086 			if (np->in_inip == htonl(in.s_addr)) {
2087 				np->in_nip = ntohl(np->in_inmsk);
2088 				move = 0;
2089 			} else {
2090 				np->in_nip = ntohl(np->in_inip);
2091 			}
2092 		}
2093 
2094 	} else if ((np->in_inip == 0) && (np->in_inmsk == 0xffffffff)) {
2095 		/*
2096 		 * 0/32 - use the interface's IP address.
2097 		 */
2098 		if (fr_ifpaddr(4, FRI_NORMAL, fin->fin_ifp, &in, NULL,
2099 			   fin->fin_ifs) == -1)
2100 			return -1;
2101 		in.s_addr = ntohl(in.s_addr);
2102 
2103 	} else if ((np->in_inip == 0) && (np->in_inmsk== 0)) {
2104 		/*
2105 		 * 0/0 - use the original destination address/port.
2106 		 */
2107 		in.s_addr = ntohl(fin->fin_daddr);
2108 
2109 	} else if (np->in_redir == NAT_BIMAP &&
2110 		   np->in_inmsk == np->in_outmsk) {
2111 		/*
2112 		 * map the address block in a 1:1 fashion
2113 		 */
2114 		in.s_addr = np->in_inip;
2115 		in.s_addr |= fin->fin_daddr & ~np->in_inmsk;
2116 		in.s_addr = ntohl(in.s_addr);
2117 	} else {
2118 		in.s_addr = ntohl(np->in_inip);
2119 	}
2120 
2121 	if ((np->in_pnext == 0) || ((flags & NAT_NOTRULEPORT) != 0))
2122 		nport = dport;
2123 	else {
2124 		/*
2125 		 * Whilst not optimized for the case where
2126 		 * pmin == pmax, the gain is not significant.
2127 		 */
2128 		if (((np->in_flags & IPN_FIXEDDPORT) == 0) &&
2129 		    (np->in_pmin != np->in_pmax)) {
2130 			nport = ntohs(dport) - ntohs(np->in_pmin) +
2131 				ntohs(np->in_pnext);
2132 			nport = htons(nport);
2133 		} else
2134 			nport = np->in_pnext;
2135 	}
2136 
2137 	/*
2138 	 * When the redirect-to address is set to 0.0.0.0, just
2139 	 * assume a blank `forwarding' of the packet.  We don't
2140 	 * setup any translation for this either.
2141 	 */
2142 	if (in.s_addr == 0) {
2143 		if (nport == dport)
2144 			return -1;
2145 		in.s_addr = ntohl(fin->fin_daddr);
2146 	}
2147 
2148 	nat->nat_inip.s_addr = htonl(in.s_addr);
2149 	nat->nat_outip = fin->fin_dst;
2150 	nat->nat_oip = fin->fin_src;
2151 
2152 	ni->nai_sum1 = LONG_SUM(ntohl(fin->fin_daddr)) + ntohs(dport);
2153 	ni->nai_sum2 = LONG_SUM(in.s_addr) + ntohs(nport);
2154 
2155 	ni->nai_ip.s_addr = in.s_addr;
2156 	ni->nai_nport = nport;
2157 	ni->nai_port = sport;
2158 
2159 	if (flags & IPN_TCPUDP) {
2160 		nat->nat_inport = nport;
2161 		nat->nat_outport = dport;
2162 		nat->nat_oport = sport;
2163 		((tcphdr_t *)fin->fin_dp)->th_dport = nport;
2164 	} else if (flags & IPN_ICMPQUERY) {
2165 		((icmphdr_t *)fin->fin_dp)->icmp_id = nport;
2166 		nat->nat_inport = nport;
2167 		nat->nat_outport = nport;
2168 	}
2169 
2170 	return move;
2171 }
2172 
2173 /* ------------------------------------------------------------------------ */
2174 /* Function:    nat_new                                                     */
2175 /* Returns:     nat_t* - NULL == failure to create new NAT structure,       */
2176 /*                       else pointer to new NAT structure                  */
2177 /* Parameters:  fin(I)       - pointer to packet information                */
2178 /*              np(I)        - pointer to NAT rule                          */
2179 /*              natsave(I)   - pointer to where to store NAT struct pointer */
2180 /*              flags(I)     - flags describing the current packet          */
2181 /*              direction(I) - direction of packet (in/out)                 */
2182 /* Write Lock:  ipf_nat                                                     */
2183 /*                                                                          */
2184 /* Attempts to create a new NAT entry.  Does not actually change the packet */
2185 /* in any way.                                                              */
2186 /*                                                                          */
2187 /* This fucntion is in three main parts: (1) deal with creating a new NAT   */
2188 /* structure for a "MAP" rule (outgoing NAT translation); (2) deal with     */
2189 /* creating a new NAT structure for a "RDR" rule (incoming NAT translation) */
2190 /* and (3) building that structure and putting it into the NAT table(s).    */
2191 /* ------------------------------------------------------------------------ */
2192 nat_t *nat_new(fin, np, natsave, flags, direction)
2193 fr_info_t *fin;
2194 ipnat_t *np;
2195 nat_t **natsave;
2196 u_int flags;
2197 int direction;
2198 {
2199 	u_short port = 0, sport = 0, dport = 0, nport = 0;
2200 	tcphdr_t *tcp = NULL;
2201 	hostmap_t *hm = NULL;
2202 	struct in_addr in;
2203 	nat_t *nat, *natl;
2204 	u_int nflags;
2205 	natinfo_t ni;
2206 	u_32_t sumd;
2207 	int move;
2208 	ipf_stack_t *ifs = fin->fin_ifs;
2209 
2210 	/*
2211 	 * Trigger automatic call to nat_extraflush() if the
2212 	 * table has reached capcity specified by hi watermark.
2213 	 */
2214 	if (NAT_TAB_WATER_LEVEL(ifs) > ifs->ifs_nat_flush_lvl_hi)
2215 		ifs->ifs_nat_doflush = 1;
2216 
2217 	if (ifs->ifs_nat_stats.ns_inuse >= ifs->ifs_ipf_nattable_max) {
2218 		ifs->ifs_nat_stats.ns_memfail++;
2219 		return NULL;
2220 	}
2221 
2222 	move = 1;
2223 	nflags = np->in_flags & flags;
2224 	nflags &= NAT_FROMRULE;
2225 
2226 	ni.nai_np = np;
2227 	ni.nai_nflags = nflags;
2228 	ni.nai_flags = flags;
2229 
2230 	/* Give me a new nat */
2231 	KMALLOC(nat, nat_t *);
2232 	if (nat == NULL) {
2233 		ifs->ifs_nat_stats.ns_memfail++;
2234 		/*
2235 		 * Try to automatically tune the max # of entries in the
2236 		 * table allowed to be less than what will cause kmem_alloc()
2237 		 * to fail and try to eliminate panics due to out of memory
2238 		 * conditions arising.
2239 		 */
2240 		if (ifs->ifs_ipf_nattable_max > ifs->ifs_ipf_nattable_sz) {
2241 			ifs->ifs_ipf_nattable_max = ifs->ifs_nat_stats.ns_inuse - 100;
2242 			printf("ipf_nattable_max reduced to %d\n",
2243 				ifs->ifs_ipf_nattable_max);
2244 		}
2245 		return NULL;
2246 	}
2247 
2248 	if (flags & IPN_TCPUDP) {
2249 		tcp = fin->fin_dp;
2250 		ni.nai_sport = htons(fin->fin_sport);
2251 		ni.nai_dport = htons(fin->fin_dport);
2252 	} else if (flags & IPN_ICMPQUERY) {
2253 		/*
2254 		 * In the ICMP query NAT code, we translate the ICMP id fields
2255 		 * to make them unique. This is indepedent of the ICMP type
2256 		 * (e.g. in the unlikely event that a host sends an echo and
2257 		 * an tstamp request with the same id, both packets will have
2258 		 * their ip address/id field changed in the same way).
2259 		 */
2260 		/* The icmp_id field is used by the sender to identify the
2261 		 * process making the icmp request. (the receiver justs
2262 		 * copies it back in its response). So, it closely matches
2263 		 * the concept of source port. We overlay sport, so we can
2264 		 * maximally reuse the existing code.
2265 		 */
2266 		ni.nai_sport = ((icmphdr_t *)fin->fin_dp)->icmp_id;
2267 		ni.nai_dport = ni.nai_sport;
2268 	}
2269 
2270 	bzero((char *)nat, sizeof(*nat));
2271 	nat->nat_flags = flags;
2272 	nat->nat_redir = np->in_redir;
2273 
2274 	if ((flags & NAT_SLAVE) == 0) {
2275 		MUTEX_ENTER(&ifs->ifs_ipf_nat_new);
2276 	}
2277 
2278 	/*
2279 	 * Search the current table for a match.
2280 	 */
2281 	if (direction == NAT_OUTBOUND) {
2282 		/*
2283 		 * We can now arrange to call this for the same connection
2284 		 * because ipf_nat_new doesn't protect the code path into
2285 		 * this function.
2286 		 */
2287 		natl = nat_outlookup(fin, nflags, (u_int)fin->fin_p,
2288 				     fin->fin_src, fin->fin_dst);
2289 		if (natl != NULL) {
2290 			KFREE(nat);
2291 			nat = natl;
2292 			goto done;
2293 		}
2294 
2295 		move = nat_newmap(fin, nat, &ni);
2296 		if (move == -1)
2297 			goto badnat;
2298 
2299 		np = ni.nai_np;
2300 		in = ni.nai_ip;
2301 	} else {
2302 		/*
2303 		 * NAT_INBOUND is used only for redirects rules
2304 		 */
2305 		natl = nat_inlookup(fin, nflags, (u_int)fin->fin_p,
2306 				    fin->fin_src, fin->fin_dst);
2307 		if (natl != NULL) {
2308 			KFREE(nat);
2309 			nat = natl;
2310 			goto done;
2311 		}
2312 
2313 		move = nat_newrdr(fin, nat, &ni);
2314 		if (move == -1)
2315 			goto badnat;
2316 
2317 		np = ni.nai_np;
2318 		in = ni.nai_ip;
2319 	}
2320 	port = ni.nai_port;
2321 	nport = ni.nai_nport;
2322 
2323 	if ((move == 1) && (np->in_flags & IPN_ROUNDR)) {
2324 		if (np->in_redir == NAT_REDIRECT) {
2325 			nat_delrdr(np);
2326 			nat_addrdr(np, ifs);
2327 		} else if (np->in_redir == NAT_MAP) {
2328 			nat_delnat(np);
2329 			nat_addnat(np, ifs);
2330 		}
2331 	}
2332 
2333 	if (flags & IPN_TCPUDP) {
2334 		sport = ni.nai_sport;
2335 		dport = ni.nai_dport;
2336 	} else if (flags & IPN_ICMPQUERY) {
2337 		sport = ni.nai_sport;
2338 		dport = 0;
2339 	}
2340 
2341 	/*
2342 	 * nat_sumd[0] stores adjustment value including both IP address and
2343 	 * port number changes. nat_sumd[1] stores adjustment value only for
2344 	 * IP address changes, to be used for pseudo header adjustment, in
2345 	 * case hardware partial checksum offload is offered.
2346 	 */
2347 	CALC_SUMD(ni.nai_sum1, ni.nai_sum2, sumd);
2348 	nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
2349 #if SOLARIS && defined(_KERNEL) && (SOLARIS2 >= 6)
2350 	if (flags & IPN_TCPUDP) {
2351 		ni.nai_sum1 = LONG_SUM(in.s_addr);
2352 		if (direction == NAT_OUTBOUND)
2353 			ni.nai_sum2 = LONG_SUM(ntohl(fin->fin_saddr));
2354 		else
2355 			ni.nai_sum2 = LONG_SUM(ntohl(fin->fin_daddr));
2356 
2357 		CALC_SUMD(ni.nai_sum1, ni.nai_sum2, sumd);
2358 		nat->nat_sumd[1] = (sumd & 0xffff) + (sumd >> 16);
2359 	} else
2360 #endif
2361 		nat->nat_sumd[1] = nat->nat_sumd[0];
2362 
2363 	if ((flags & IPN_TCPUDPICMP) && ((sport != port) || (dport != nport))) {
2364 		if (direction == NAT_OUTBOUND)
2365 			ni.nai_sum1 = LONG_SUM(ntohl(fin->fin_saddr));
2366 		else
2367 			ni.nai_sum1 = LONG_SUM(ntohl(fin->fin_daddr));
2368 
2369 		ni.nai_sum2 = LONG_SUM(in.s_addr);
2370 
2371 		CALC_SUMD(ni.nai_sum1, ni.nai_sum2, sumd);
2372 		nat->nat_ipsumd = (sumd & 0xffff) + (sumd >> 16);
2373 	} else {
2374 		nat->nat_ipsumd = nat->nat_sumd[0];
2375 		if (!(flags & IPN_TCPUDPICMP)) {
2376 			nat->nat_sumd[0] = 0;
2377 			nat->nat_sumd[1] = 0;
2378 		}
2379 	}
2380 
2381 	if (nat_finalise(fin, nat, &ni, tcp, natsave, direction) == -1) {
2382 		goto badnat;
2383 	}
2384 	if (flags & SI_WILDP)
2385 		ifs->ifs_nat_stats.ns_wilds++;
2386 	goto done;
2387 badnat:
2388 	ifs->ifs_nat_stats.ns_badnat++;
2389 	if ((hm = nat->nat_hm) != NULL)
2390 		nat_hostmapdel(hm);
2391 	KFREE(nat);
2392 	nat = NULL;
2393 done:
2394 	if ((flags & NAT_SLAVE) == 0) {
2395 		MUTEX_EXIT(&ifs->ifs_ipf_nat_new);
2396 	}
2397 	return nat;
2398 }
2399 
2400 
2401 /* ------------------------------------------------------------------------ */
2402 /* Function:    nat_finalise                                                */
2403 /* Returns:     int - 0 == sucess, -1 == failure                            */
2404 /* Parameters:  fin(I) - pointer to packet information                      */
2405 /*              nat(I) - pointer to NAT entry                               */
2406 /*              ni(I)  - pointer to structure with misc. information needed */
2407 /*                       to create new NAT entry.                           */
2408 /* Write Lock:  ipf_nat                                                     */
2409 /*                                                                          */
2410 /* This is the tail end of constructing a new NAT entry and is the same     */
2411 /* for both IPv4 and IPv6.                                                  */
2412 /* ------------------------------------------------------------------------ */
2413 /*ARGSUSED*/
2414 static INLINE int nat_finalise(fin, nat, ni, tcp, natsave, direction)
2415 fr_info_t *fin;
2416 nat_t *nat;
2417 natinfo_t *ni;
2418 tcphdr_t *tcp;
2419 nat_t **natsave;
2420 int direction;
2421 {
2422 	frentry_t *fr;
2423 	ipnat_t *np;
2424 	ipf_stack_t *ifs = fin->fin_ifs;
2425 
2426 	np = ni->nai_np;
2427 
2428 	COPYIFNAME(fin->fin_ifp, nat->nat_ifnames[0], fin->fin_v);
2429 
2430 #ifdef	IPFILTER_SYNC
2431 	if ((nat->nat_flags & SI_CLONE) == 0)
2432 		nat->nat_sync = ipfsync_new(SMC_NAT, fin, nat);
2433 #endif
2434 
2435 	nat->nat_me = natsave;
2436 	nat->nat_dir = direction;
2437 	nat->nat_ifps[0] = np->in_ifps[0];
2438 	nat->nat_ifps[1] = np->in_ifps[1];
2439 	nat->nat_ptr = np;
2440 	nat->nat_p = fin->fin_p;
2441 	nat->nat_mssclamp = np->in_mssclamp;
2442 	fr = fin->fin_fr;
2443 	nat->nat_fr = fr;
2444 
2445 	if ((np->in_apr != NULL) && ((ni->nai_flags & NAT_SLAVE) == 0))
2446 		if (appr_new(fin, nat) == -1)
2447 			return -1;
2448 
2449 	if (nat_insert(nat, fin->fin_rev, ifs) == 0) {
2450 		if (ifs->ifs_nat_logging)
2451 			nat_log(nat, (u_int)np->in_redir, ifs);
2452 		np->in_use++;
2453 		if (fr != NULL) {
2454 			MUTEX_ENTER(&fr->fr_lock);
2455 			fr->fr_ref++;
2456 			MUTEX_EXIT(&fr->fr_lock);
2457 		}
2458 		return 0;
2459 	}
2460 
2461 	/*
2462 	 * nat_insert failed, so cleanup time...
2463 	 */
2464 	return -1;
2465 }
2466 
2467 
2468 /* ------------------------------------------------------------------------ */
2469 /* Function:   nat_insert                                                   */
2470 /* Returns:    int - 0 == sucess, -1 == failure                             */
2471 /* Parameters: nat(I) - pointer to NAT structure                            */
2472 /*             rev(I) - flag indicating forward/reverse direction of packet */
2473 /* Write Lock: ipf_nat                                                      */
2474 /*                                                                          */
2475 /* Insert a NAT entry into the hash tables for searching and add it to the  */
2476 /* list of active NAT entries.  Adjust global counters when complete.       */
2477 /* ------------------------------------------------------------------------ */
2478 int	nat_insert(nat, rev, ifs)
2479 nat_t	*nat;
2480 int	rev;
2481 ipf_stack_t *ifs;
2482 {
2483 	u_int hv1, hv2;
2484 	nat_t **natp;
2485 
2486 	/*
2487 	 * Try and return an error as early as possible, so calculate the hash
2488 	 * entry numbers first and then proceed.
2489 	 */
2490 	if ((nat->nat_flags & (SI_W_SPORT|SI_W_DPORT)) == 0) {
2491 		hv1 = NAT_HASH_FN(nat->nat_inip.s_addr, nat->nat_inport,
2492 				  0xffffffff);
2493 		hv1 = NAT_HASH_FN(nat->nat_oip.s_addr, hv1 + nat->nat_oport,
2494 				  ifs->ifs_ipf_nattable_sz);
2495 		hv2 = NAT_HASH_FN(nat->nat_outip.s_addr, nat->nat_outport,
2496 				  0xffffffff);
2497 		hv2 = NAT_HASH_FN(nat->nat_oip.s_addr, hv2 + nat->nat_oport,
2498 				  ifs->ifs_ipf_nattable_sz);
2499 	} else {
2500 		hv1 = NAT_HASH_FN(nat->nat_inip.s_addr, 0, 0xffffffff);
2501 		hv1 = NAT_HASH_FN(nat->nat_oip.s_addr, hv1,
2502 				  ifs->ifs_ipf_nattable_sz);
2503 		hv2 = NAT_HASH_FN(nat->nat_outip.s_addr, 0, 0xffffffff);
2504 		hv2 = NAT_HASH_FN(nat->nat_oip.s_addr, hv2,
2505 				  ifs->ifs_ipf_nattable_sz);
2506 	}
2507 
2508 	if (ifs->ifs_nat_stats.ns_bucketlen[0][hv1] >= ifs->ifs_fr_nat_maxbucket ||
2509 	    ifs->ifs_nat_stats.ns_bucketlen[1][hv2] >= ifs->ifs_fr_nat_maxbucket) {
2510 		return -1;
2511 	}
2512 
2513 	nat->nat_hv[0] = hv1;
2514 	nat->nat_hv[1] = hv2;
2515 
2516 	MUTEX_INIT(&nat->nat_lock, "nat entry lock");
2517 
2518 	nat->nat_rev = rev;
2519 	nat->nat_ref = 1;
2520 	nat->nat_bytes[0] = 0;
2521 	nat->nat_pkts[0] = 0;
2522 	nat->nat_bytes[1] = 0;
2523 	nat->nat_pkts[1] = 0;
2524 
2525 	nat->nat_ifnames[0][LIFNAMSIZ - 1] = '\0';
2526 	nat->nat_ifps[0] = fr_resolvenic(nat->nat_ifnames[0], 4, ifs);
2527 
2528 	if (nat->nat_ifnames[1][0] !='\0') {
2529 		nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
2530 		nat->nat_ifps[1] = fr_resolvenic(nat->nat_ifnames[1], 4, ifs);
2531 	} else {
2532 		(void) strncpy(nat->nat_ifnames[1], nat->nat_ifnames[0],
2533 			       LIFNAMSIZ);
2534 		nat->nat_ifnames[1][LIFNAMSIZ - 1] = '\0';
2535 		nat->nat_ifps[1] = nat->nat_ifps[0];
2536 	}
2537 
2538 	nat->nat_next = ifs->ifs_nat_instances;
2539 	nat->nat_pnext = &ifs->ifs_nat_instances;
2540 	if (ifs->ifs_nat_instances)
2541 		ifs->ifs_nat_instances->nat_pnext = &nat->nat_next;
2542 	ifs->ifs_nat_instances = nat;
2543 
2544 	natp = &ifs->ifs_nat_table[0][hv1];
2545 	if (*natp)
2546 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
2547 	nat->nat_phnext[0] = natp;
2548 	nat->nat_hnext[0] = *natp;
2549 	*natp = nat;
2550 	ifs->ifs_nat_stats.ns_bucketlen[0][hv1]++;
2551 
2552 	natp = &ifs->ifs_nat_table[1][hv2];
2553 	if (*natp)
2554 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
2555 	nat->nat_phnext[1] = natp;
2556 	nat->nat_hnext[1] = *natp;
2557 	*natp = nat;
2558 	ifs->ifs_nat_stats.ns_bucketlen[1][hv2]++;
2559 
2560 	fr_setnatqueue(nat, rev, ifs);
2561 
2562 	ifs->ifs_nat_stats.ns_added++;
2563 	ifs->ifs_nat_stats.ns_inuse++;
2564 	return 0;
2565 }
2566 
2567 
2568 /* ------------------------------------------------------------------------ */
2569 /* Function:    nat_icmperrorlookup                                         */
2570 /* Returns:     nat_t* - point to matching NAT structure                    */
2571 /* Parameters:  fin(I) - pointer to packet information                      */
2572 /*              dir(I) - direction of packet (in/out)                       */
2573 /*                                                                          */
2574 /* Check if the ICMP error message is related to an existing TCP, UDP or    */
2575 /* ICMP query nat entry.  It is assumed that the packet is already of the   */
2576 /* the required length.                                                     */
2577 /* ------------------------------------------------------------------------ */
2578 nat_t *nat_icmperrorlookup(fin, dir)
2579 fr_info_t *fin;
2580 int dir;
2581 {
2582 	int flags = 0, minlen;
2583 	icmphdr_t *orgicmp;
2584 	tcphdr_t *tcp = NULL;
2585 	u_short data[2];
2586 	nat_t *nat;
2587 	ip_t *oip;
2588 	u_int p;
2589 
2590 	/*
2591 	 * Does it at least have the return (basic) IP header ?
2592 	 * Only a basic IP header (no options) should be with an ICMP error
2593 	 * header.  Also, if it's not an error type, then return.
2594 	 */
2595 	if ((fin->fin_hlen != sizeof(ip_t)) || !(fin->fin_flx & FI_ICMPERR))
2596 		return NULL;
2597 
2598 	/*
2599 	 * Check packet size
2600 	 */
2601 	oip = (ip_t *)((char *)fin->fin_dp + 8);
2602 	minlen = IP_HL(oip) << 2;
2603 	if ((minlen < sizeof(ip_t)) ||
2604 	    (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen))
2605 		return NULL;
2606 	/*
2607 	 * Is the buffer big enough for all of it ?  It's the size of the IP
2608 	 * header claimed in the encapsulated part which is of concern.  It
2609 	 * may be too big to be in this buffer but not so big that it's
2610 	 * outside the ICMP packet, leading to TCP deref's causing problems.
2611 	 * This is possible because we don't know how big oip_hl is when we
2612 	 * do the pullup early in fr_check() and thus can't gaurantee it is
2613 	 * all here now.
2614 	 */
2615 #ifdef  _KERNEL
2616 	{
2617 	mb_t *m;
2618 
2619 	m = fin->fin_m;
2620 # if defined(MENTAT)
2621 	if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN > (char *)m->b_wptr)
2622 		return NULL;
2623 # else
2624 	if ((char *)oip + fin->fin_dlen - ICMPERR_ICMPHLEN >
2625 	    (char *)fin->fin_ip + M_LEN(m))
2626 		return NULL;
2627 # endif
2628 	}
2629 #endif
2630 
2631 	if (fin->fin_daddr != oip->ip_src.s_addr)
2632 		return NULL;
2633 
2634 	p = oip->ip_p;
2635 	if (p == IPPROTO_TCP)
2636 		flags = IPN_TCP;
2637 	else if (p == IPPROTO_UDP)
2638 		flags = IPN_UDP;
2639 	else if (p == IPPROTO_ICMP) {
2640 		orgicmp = (icmphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2641 
2642 		/* see if this is related to an ICMP query */
2643 		if (nat_icmpquerytype4(orgicmp->icmp_type)) {
2644 			data[0] = fin->fin_data[0];
2645 			data[1] = fin->fin_data[1];
2646 			fin->fin_data[0] = 0;
2647 			fin->fin_data[1] = orgicmp->icmp_id;
2648 
2649 			flags = IPN_ICMPERR|IPN_ICMPQUERY;
2650 			/*
2651 			 * NOTE : dir refers to the direction of the original
2652 			 *        ip packet. By definition the icmp error
2653 			 *        message flows in the opposite direction.
2654 			 */
2655 			if (dir == NAT_INBOUND)
2656 				nat = nat_inlookup(fin, flags, p, oip->ip_dst,
2657 						   oip->ip_src);
2658 			else
2659 				nat = nat_outlookup(fin, flags, p, oip->ip_dst,
2660 						    oip->ip_src);
2661 			fin->fin_data[0] = data[0];
2662 			fin->fin_data[1] = data[1];
2663 			return nat;
2664 		}
2665 	}
2666 
2667 	if (flags & IPN_TCPUDP) {
2668 		minlen += 8;		/* + 64bits of data to get ports */
2669 		if (fin->fin_plen < ICMPERR_IPICMPHLEN + minlen)
2670 			return NULL;
2671 
2672 		data[0] = fin->fin_data[0];
2673 		data[1] = fin->fin_data[1];
2674 		tcp = (tcphdr_t *)((char *)oip + (IP_HL(oip) << 2));
2675 		fin->fin_data[0] = ntohs(tcp->th_dport);
2676 		fin->fin_data[1] = ntohs(tcp->th_sport);
2677 
2678 		if (dir == NAT_INBOUND) {
2679 			nat = nat_inlookup(fin, flags, p, oip->ip_dst,
2680 					   oip->ip_src);
2681 		} else {
2682 			nat = nat_outlookup(fin, flags, p, oip->ip_dst,
2683 					    oip->ip_src);
2684 		}
2685 		fin->fin_data[0] = data[0];
2686 		fin->fin_data[1] = data[1];
2687 		return nat;
2688 	}
2689 	if (dir == NAT_INBOUND)
2690 		return nat_inlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
2691 	else
2692 		return nat_outlookup(fin, 0, p, oip->ip_dst, oip->ip_src);
2693 }
2694 
2695 
2696 /* ------------------------------------------------------------------------ */
2697 /* Function:    nat_icmperror                                               */
2698 /* Returns:     nat_t* - point to matching NAT structure                    */
2699 /* Parameters:  fin(I)    - pointer to packet information                   */
2700 /*              nflags(I) - NAT flags for this packet                       */
2701 /*              dir(I)    - direction of packet (in/out)                    */
2702 /*                                                                          */
2703 /* Fix up an ICMP packet which is an error message for an existing NAT      */
2704 /* session.  This will correct both packet header data and checksums.       */
2705 /*                                                                          */
2706 /* This should *ONLY* be used for incoming ICMP error packets to make sure  */
2707 /* a NAT'd ICMP packet gets correctly recognised.                           */
2708 /* ------------------------------------------------------------------------ */
2709 nat_t *nat_icmperror(fin, nflags, dir)
2710 fr_info_t *fin;
2711 u_int *nflags;
2712 int dir;
2713 {
2714 	u_32_t sum1, sum2, sumd, psum1, psum2, psumd, sumd2;
2715 	struct in_addr in;
2716 	icmphdr_t *icmp, *orgicmp;
2717 	int dlen;
2718 	udphdr_t *udp;
2719 	tcphdr_t *tcp;
2720 	nat_t *nat;
2721 	ip_t *oip;
2722 	if ((fin->fin_flx & (FI_SHORT|FI_FRAGBODY)))
2723 		return NULL;
2724 
2725 	/*
2726 	 * nat_icmperrorlookup() looks up nat entry associated with the
2727 	 * offending IP packet and returns pointer to the entry, or NULL
2728 	 * if packet wasn't natted or for `defective' packets.
2729 	 */
2730 
2731 	if ((fin->fin_v != 4) || !(nat = nat_icmperrorlookup(fin, dir)))
2732 		return NULL;
2733 
2734 	sumd2 = 0;
2735 	*nflags = IPN_ICMPERR;
2736 	icmp = fin->fin_dp;
2737 	oip = (ip_t *)&icmp->icmp_ip;
2738 	udp = (udphdr_t *)((((char *)oip) + (IP_HL(oip) << 2)));
2739 	tcp = (tcphdr_t *)udp;
2740 	dlen = fin->fin_plen - ((char *)udp - (char *)fin->fin_ip);
2741 
2742 	/*
2743 	 * Need to adjust ICMP header to include the real IP#'s and
2744 	 * port #'s.  There are three steps required.
2745 	 *
2746 	 * Step 1
2747 	 * Fix the IP addresses in the offending IP packet and update
2748 	 * ip header checksum to compensate for the change.
2749 	 *
2750 	 * No update needed here for icmp_cksum because the ICMP checksum
2751 	 * is calculated over the complete ICMP packet, which includes the
2752 	 * changed oip IP addresses and oip->ip_sum.  These two changes
2753 	 * cancel each other out (if the delta for the IP address is x,
2754 	 * then the delta for ip_sum is minus x).
2755 	 */
2756 
2757 	if (oip->ip_dst.s_addr == nat->nat_oip.s_addr) {
2758 		sum1 = LONG_SUM(ntohl(oip->ip_src.s_addr));
2759 		in = nat->nat_inip;
2760 		oip->ip_src = in;
2761 	} else {
2762 		sum1 = LONG_SUM(ntohl(oip->ip_dst.s_addr));
2763 		in = nat->nat_outip;
2764 		oip->ip_dst = in;
2765 	}
2766 
2767 	sum2 = LONG_SUM(ntohl(in.s_addr));
2768 	CALC_SUMD(sum1, sum2, sumd);
2769 	fix_datacksum(&oip->ip_sum, sumd);
2770 
2771 	/*
2772 	 * Step 2
2773 	 * Perform other adjustments based on protocol of offending packet.
2774 	 */
2775 
2776 	switch (oip->ip_p) {
2777 		case IPPROTO_TCP :
2778 		case IPPROTO_UDP :
2779 
2780 			/*
2781 			* For offending TCP/UDP IP packets, translate the ports
2782 			* based on the NAT specification.
2783 			*
2784 			* Advance notice : Now it becomes complicated :-)
2785 			*
2786 			* Since the port and IP addresse fields are both part
2787 			* of the TCP/UDP checksum of the offending IP packet,
2788 			* we need to adjust that checksum as well.
2789 			*
2790 			* To further complicate things, the TCP/UDP checksum
2791 			* may not be present.  We must check to see if the
2792 			* length of the data portion is big enough to hold
2793 			* the checksum.  In the UDP case, a test to determine
2794 			* if the checksum is even set is also required.
2795 			*
2796 			* Any changes to an IP address, port or checksum within
2797 			* the ICMP packet requires a change to icmp_cksum.
2798 			*
2799 			* Be extremely careful here ... The change is dependent
2800 			* upon whether or not the TCP/UPD checksum is present.
2801 			*
2802 			* If TCP/UPD checksum is present, the icmp_cksum must
2803 			* compensate for checksum modification resulting from
2804 			* IP address change only.  Port change and resulting
2805 			* data checksum adjustments cancel each other out.
2806 			*
2807 			* If TCP/UDP checksum is not present, icmp_cksum must
2808 			* compensate for port change only.  The IP address
2809 			* change does not modify anything else in this case.
2810 			*/
2811 
2812 			psum1 = 0;
2813 			psum2 = 0;
2814 			psumd = 0;
2815 
2816 			if ((tcp->th_dport == nat->nat_oport) &&
2817 			    (tcp->th_sport != nat->nat_inport)) {
2818 
2819 				/*
2820 				 * Translate the source port.
2821 				 */
2822 
2823 				psum1 = ntohs(tcp->th_sport);
2824 				psum2 = ntohs(nat->nat_inport);
2825 				tcp->th_sport = nat->nat_inport;
2826 
2827 			} else if ((tcp->th_sport == nat->nat_oport) &&
2828 				    (tcp->th_dport != nat->nat_outport)) {
2829 
2830 				/*
2831 				 * Translate the destination port.
2832 				 */
2833 
2834 				psum1 = ntohs(tcp->th_dport);
2835 				psum2 = ntohs(nat->nat_outport);
2836 				tcp->th_dport = nat->nat_outport;
2837 			}
2838 
2839 			if ((oip->ip_p == IPPROTO_TCP) && (dlen >= 18)) {
2840 
2841 				/*
2842 				 * TCP checksum present.
2843 				 *
2844 				 * Adjust data checksum and icmp checksum to
2845 				 * compensate for any IP address change.
2846 				 */
2847 
2848 				sum1 = ntohs(tcp->th_sum);
2849 				fix_datacksum(&tcp->th_sum, sumd);
2850 				sum2 = ntohs(tcp->th_sum);
2851 				sumd2 = sumd << 1;
2852 				CALC_SUMD(sum1, sum2, sumd);
2853 				sumd2 += sumd;
2854 
2855 				/*
2856 				 * Also make data checksum adjustment to
2857 				 * compensate for any port change.
2858 				 */
2859 
2860 				if (psum1 != psum2) {
2861 					CALC_SUMD(psum1, psum2, psumd);
2862 					fix_datacksum(&tcp->th_sum, psumd);
2863 				}
2864 
2865 			} else if ((oip->ip_p == IPPROTO_UDP) &&
2866 				   (dlen >= 8) && (udp->uh_sum != 0)) {
2867 
2868 				/*
2869 				 * The UDP checksum is present and set.
2870 				 *
2871 				 * Adjust data checksum and icmp checksum to
2872 				 * compensate for any IP address change.
2873 				 */
2874 
2875 				sum1 = ntohs(udp->uh_sum);
2876 				fix_datacksum(&udp->uh_sum, sumd);
2877 				sum2 = ntohs(udp->uh_sum);
2878 				sumd2 = sumd << 1;
2879 				CALC_SUMD(sum1, sum2, sumd);
2880 				sumd2 += sumd;
2881 
2882 				/*
2883 				 * Also make data checksum adjustment to
2884 				 * compensate for any port change.
2885 				 */
2886 
2887 				if (psum1 != psum2) {
2888 					CALC_SUMD(psum1, psum2, psumd);
2889 					fix_datacksum(&udp->uh_sum, psumd);
2890 				}
2891 
2892 			} else {
2893 
2894 				/*
2895 				 * Data checksum was not present.
2896 				 *
2897 				 * Compensate for any port change.
2898 				 */
2899 
2900 				CALC_SUMD(psum2, psum1, psumd);
2901 				sumd2 += psumd;
2902 			}
2903 			break;
2904 
2905 		case IPPROTO_ICMP :
2906 
2907 			orgicmp = (icmphdr_t *)udp;
2908 
2909 			if ((nat->nat_dir == NAT_OUTBOUND) &&
2910 			    (orgicmp->icmp_id != nat->nat_inport) &&
2911 			    (dlen >= 8)) {
2912 
2913 				/*
2914 				 * Fix ICMP checksum (of the offening ICMP
2915 				 * query packet) to compensate the change
2916 				 * in the ICMP id of the offending ICMP
2917 				 * packet.
2918 				 *
2919 				 * Since you modify orgicmp->icmp_id with
2920 				 * a delta (say x) and you compensate that
2921 				 * in origicmp->icmp_cksum with a delta
2922 				 * minus x, you don't have to adjust the
2923 				 * overall icmp->icmp_cksum
2924 				 */
2925 
2926 				sum1 = ntohs(orgicmp->icmp_id);
2927 				sum2 = ntohs(nat->nat_inport);
2928 				CALC_SUMD(sum1, sum2, sumd);
2929 				orgicmp->icmp_id = nat->nat_inport;
2930 				fix_datacksum(&orgicmp->icmp_cksum, sumd);
2931 
2932 			} /* nat_dir can't be NAT_INBOUND for icmp queries */
2933 
2934 			break;
2935 
2936 		default :
2937 
2938 			break;
2939 
2940 	} /* switch (oip->ip_p) */
2941 
2942 	/*
2943 	 * Step 3
2944 	 * Make the adjustments to icmp checksum.
2945 	 */
2946 
2947 	if (sumd2 != 0) {
2948 		sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
2949 		sumd2 = (sumd2 & 0xffff) + (sumd2 >> 16);
2950 		fix_incksum(&icmp->icmp_cksum, sumd2);
2951 	}
2952 	return nat;
2953 }
2954 
2955 
2956 /*
2957  * NB: these lookups don't lock access to the list, it assumed that it has
2958  * already been done!
2959  */
2960 
2961 /* ------------------------------------------------------------------------ */
2962 /* Function:    nat_inlookup                                                */
2963 /* Returns:     nat_t* - NULL == no match,                                  */
2964 /*                       else pointer to matching NAT entry                 */
2965 /* Parameters:  fin(I)    - pointer to packet information                   */
2966 /*              flags(I)  - NAT flags for this packet                       */
2967 /*              p(I)      - protocol for this packet                        */
2968 /*              src(I)    - source IP address                               */
2969 /*              mapdst(I) - destination IP address                          */
2970 /*                                                                          */
2971 /* Lookup a nat entry based on the mapped destination ip address/port and   */
2972 /* real source address/port.  We use this lookup when receiving a packet,   */
2973 /* we're looking for a table entry, based on the destination address.       */
2974 /*                                                                          */
2975 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
2976 /*                                                                          */
2977 /* NOTE: IT IS ASSUMED THAT ipf_nat IS ONLY HELD WITH A READ LOCK WHEN      */
2978 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
2979 /*                                                                          */
2980 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
2981 /*            the packet is of said protocol                                */
2982 /* ------------------------------------------------------------------------ */
2983 nat_t *nat_inlookup(fin, flags, p, src, mapdst)
2984 fr_info_t *fin;
2985 u_int flags, p;
2986 struct in_addr src , mapdst;
2987 {
2988 	u_short sport, dport;
2989 	ipnat_t *ipn;
2990 	u_int sflags;
2991 	nat_t *nat;
2992 	int nflags;
2993 	u_32_t dst;
2994 	void *ifp;
2995 	u_int hv;
2996 	ipf_stack_t *ifs = fin->fin_ifs;
2997 
2998 	if (fin != NULL)
2999 		ifp = fin->fin_ifp;
3000 	else
3001 		ifp = NULL;
3002 	sport = 0;
3003 	dport = 0;
3004 	dst = mapdst.s_addr;
3005 	sflags = flags & NAT_TCPUDPICMP;
3006 
3007 	switch (p)
3008 	{
3009 	case IPPROTO_TCP :
3010 	case IPPROTO_UDP :
3011 		sport = htons(fin->fin_data[0]);
3012 		dport = htons(fin->fin_data[1]);
3013 		break;
3014 	case IPPROTO_ICMP :
3015 		if (flags & IPN_ICMPERR)
3016 			sport = fin->fin_data[1];
3017 		else
3018 			dport = fin->fin_data[1];
3019 		break;
3020 	default :
3021 		break;
3022 	}
3023 
3024 
3025 	if ((flags & SI_WILDP) != 0)
3026 		goto find_in_wild_ports;
3027 
3028 	hv = NAT_HASH_FN(dst, dport, 0xffffffff);
3029 	hv = NAT_HASH_FN(src.s_addr, hv + sport, ifs->ifs_ipf_nattable_sz);
3030 	nat = ifs->ifs_nat_table[1][hv];
3031 	for (; nat; nat = nat->nat_hnext[1]) {
3032 		if (nat->nat_ifps[0] != NULL) {
3033 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
3034 				continue;
3035 		} else if (ifp != NULL)
3036 			nat->nat_ifps[0] = ifp;
3037 
3038 		nflags = nat->nat_flags;
3039 
3040 		if (nat->nat_oip.s_addr == src.s_addr &&
3041 		    nat->nat_outip.s_addr == dst &&
3042 		    (((p == 0) &&
3043 		      (sflags == (nat->nat_flags & IPN_TCPUDPICMP)))
3044 		     || (p == nat->nat_p))) {
3045 			switch (p)
3046 			{
3047 #if 0
3048 			case IPPROTO_GRE :
3049 				if (nat->nat_call[1] != fin->fin_data[0])
3050 					continue;
3051 				break;
3052 #endif
3053 			case IPPROTO_ICMP :
3054 				if ((flags & IPN_ICMPERR) != 0) {
3055 					if (nat->nat_outport != sport)
3056 						continue;
3057 				} else {
3058 					if (nat->nat_outport != dport)
3059 						continue;
3060 				}
3061 				break;
3062 			case IPPROTO_TCP :
3063 			case IPPROTO_UDP :
3064 				if (nat->nat_oport != sport)
3065 					continue;
3066 				if (nat->nat_outport != dport)
3067 					continue;
3068 				break;
3069 			default :
3070 				break;
3071 			}
3072 
3073 			ipn = nat->nat_ptr;
3074 			if ((ipn != NULL) && (nat->nat_aps != NULL))
3075 				if (appr_match(fin, nat) != 0)
3076 					continue;
3077 			return nat;
3078 		}
3079 	}
3080 
3081 	/*
3082 	 * So if we didn't find it but there are wildcard members in the hash
3083 	 * table, go back and look for them.  We do this search and update here
3084 	 * because it is modifying the NAT table and we want to do this only
3085 	 * for the first packet that matches.  The exception, of course, is
3086 	 * for "dummy" (FI_IGNORE) lookups.
3087 	 */
3088 find_in_wild_ports:
3089 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH))
3090 		return NULL;
3091 	if (ifs->ifs_nat_stats.ns_wilds == 0)
3092 		return NULL;
3093 
3094 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
3095 
3096 	hv = NAT_HASH_FN(dst, 0, 0xffffffff);
3097 	hv = NAT_HASH_FN(src.s_addr, hv, ifs->ifs_ipf_nattable_sz);
3098 
3099 	WRITE_ENTER(&ifs->ifs_ipf_nat);
3100 
3101 	nat = ifs->ifs_nat_table[1][hv];
3102 	for (; nat; nat = nat->nat_hnext[1]) {
3103 		if (nat->nat_ifps[0] != NULL) {
3104 			if ((ifp != NULL) && (ifp != nat->nat_ifps[0]))
3105 				continue;
3106 		} else if (ifp != NULL)
3107 			nat->nat_ifps[0] = ifp;
3108 
3109 		if (nat->nat_p != fin->fin_p)
3110 			continue;
3111 		if (nat->nat_oip.s_addr != src.s_addr ||
3112 		    nat->nat_outip.s_addr != dst)
3113 			continue;
3114 
3115 		nflags = nat->nat_flags;
3116 		if (!(nflags & (NAT_TCPUDP|SI_WILDP)))
3117 			continue;
3118 
3119 		if (nat_wildok(nat, (int)sport, (int)dport, nflags,
3120 			       NAT_INBOUND) == 1) {
3121 			if ((fin->fin_flx & FI_IGNORE) != 0)
3122 				break;
3123 			if ((nflags & SI_CLONE) != 0) {
3124 				nat = fr_natclone(fin, nat);
3125 				if (nat == NULL)
3126 					break;
3127 			} else {
3128 				MUTEX_ENTER(&ifs->ifs_ipf_nat_new);
3129 				ifs->ifs_nat_stats.ns_wilds--;
3130 				MUTEX_EXIT(&ifs->ifs_ipf_nat_new);
3131 			}
3132 			nat->nat_oport = sport;
3133 			nat->nat_outport = dport;
3134 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
3135 			nat_tabmove(nat, ifs);
3136 			break;
3137 		}
3138 	}
3139 
3140 	MUTEX_DOWNGRADE(&ifs->ifs_ipf_nat);
3141 
3142 	return nat;
3143 }
3144 
3145 
3146 /* ------------------------------------------------------------------------ */
3147 /* Function:    nat_tabmove                                                 */
3148 /* Returns:     Nil                                                         */
3149 /* Parameters:  nat(I) - pointer to NAT structure                           */
3150 /* Write Lock:  ipf_nat                                                     */
3151 /*                                                                          */
3152 /* This function is only called for TCP/UDP NAT table entries where the     */
3153 /* original was placed in the table without hashing on the ports and we now */
3154 /* want to include hashing on port numbers.                                 */
3155 /* ------------------------------------------------------------------------ */
3156 static void nat_tabmove(nat, ifs)
3157 nat_t *nat;
3158 ipf_stack_t *ifs;
3159 {
3160 	nat_t **natp;
3161 	u_int hv;
3162 
3163 	if (nat->nat_flags & SI_CLONE)
3164 		return;
3165 
3166 	/*
3167 	 * Remove the NAT entry from the old location
3168 	 */
3169 	if (nat->nat_hnext[0])
3170 		nat->nat_hnext[0]->nat_phnext[0] = nat->nat_phnext[0];
3171 	*nat->nat_phnext[0] = nat->nat_hnext[0];
3172 	ifs->ifs_nat_stats.ns_bucketlen[0][nat->nat_hv[0]]--;
3173 
3174 	if (nat->nat_hnext[1])
3175 		nat->nat_hnext[1]->nat_phnext[1] = nat->nat_phnext[1];
3176 	*nat->nat_phnext[1] = nat->nat_hnext[1];
3177 	ifs->ifs_nat_stats.ns_bucketlen[1][nat->nat_hv[1]]--;
3178 
3179 	/*
3180 	 * Add into the NAT table in the new position
3181 	 */
3182 	hv = NAT_HASH_FN(nat->nat_inip.s_addr, nat->nat_inport, 0xffffffff);
3183 	hv = NAT_HASH_FN(nat->nat_oip.s_addr, hv + nat->nat_oport,
3184 			 ifs->ifs_ipf_nattable_sz);
3185 	nat->nat_hv[0] = hv;
3186 	natp = &ifs->ifs_nat_table[0][hv];
3187 	if (*natp)
3188 		(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
3189 	nat->nat_phnext[0] = natp;
3190 	nat->nat_hnext[0] = *natp;
3191 	*natp = nat;
3192 	ifs->ifs_nat_stats.ns_bucketlen[0][hv]++;
3193 
3194 	hv = NAT_HASH_FN(nat->nat_outip.s_addr, nat->nat_outport, 0xffffffff);
3195 	hv = NAT_HASH_FN(nat->nat_oip.s_addr, hv + nat->nat_oport,
3196 			 ifs->ifs_ipf_nattable_sz);
3197 	nat->nat_hv[1] = hv;
3198 	natp = &ifs->ifs_nat_table[1][hv];
3199 	if (*natp)
3200 		(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
3201 	nat->nat_phnext[1] = natp;
3202 	nat->nat_hnext[1] = *natp;
3203 	*natp = nat;
3204 	ifs->ifs_nat_stats.ns_bucketlen[1][hv]++;
3205 }
3206 
3207 
3208 /* ------------------------------------------------------------------------ */
3209 /* Function:    nat_outlookup                                               */
3210 /* Returns:     nat_t* - NULL == no match,                                  */
3211 /*                       else pointer to matching NAT entry                 */
3212 /* Parameters:  fin(I)   - pointer to packet information                    */
3213 /*              flags(I) - NAT flags for this packet                        */
3214 /*              p(I)     - protocol for this packet                         */
3215 /*              src(I)   - source IP address                                */
3216 /*              dst(I)   - destination IP address                           */
3217 /*              rw(I)    - 1 == write lock on ipf_nat held, 0 == read lock. */
3218 /*                                                                          */
3219 /* Lookup a nat entry based on the source 'real' ip address/port and        */
3220 /* destination address/port.  We use this lookup when sending a packet out, */
3221 /* we're looking for a table entry, based on the source address.            */
3222 /*                                                                          */
3223 /* NOTE: THE PACKET BEING CHECKED (IF FOUND) HAS A MAPPING ALREADY.         */
3224 /*                                                                          */
3225 /* NOTE: IT IS ASSUMED THAT ipf_nat IS ONLY HELD WITH A READ LOCK WHEN      */
3226 /*       THIS FUNCTION IS CALLED WITH NAT_SEARCH SET IN nflags.             */
3227 /*                                                                          */
3228 /* flags   -> relevant are IPN_UDP/IPN_TCP/IPN_ICMPQUERY that indicate if   */
3229 /*            the packet is of said protocol                                */
3230 /* ------------------------------------------------------------------------ */
3231 nat_t *nat_outlookup(fin, flags, p, src, dst)
3232 fr_info_t *fin;
3233 u_int flags, p;
3234 struct in_addr src , dst;
3235 {
3236 	u_short sport, dport;
3237 	u_int sflags;
3238 	ipnat_t *ipn;
3239 	u_32_t srcip;
3240 	nat_t *nat;
3241 	int nflags;
3242 	void *ifp;
3243 	u_int hv;
3244 	ipf_stack_t *ifs = fin->fin_ifs;
3245 
3246 	ifp = fin->fin_ifp;
3247 
3248 	srcip = src.s_addr;
3249 	sflags = flags & IPN_TCPUDPICMP;
3250 	sport = 0;
3251 	dport = 0;
3252 
3253 	switch (p)
3254 	{
3255 	case IPPROTO_TCP :
3256 	case IPPROTO_UDP :
3257 		sport = htons(fin->fin_data[0]);
3258 		dport = htons(fin->fin_data[1]);
3259 		break;
3260 	case IPPROTO_ICMP :
3261 		if (flags & IPN_ICMPERR)
3262 			sport = fin->fin_data[1];
3263 		else
3264 			dport = fin->fin_data[1];
3265 		break;
3266 	default :
3267 		break;
3268 	}
3269 
3270 	if ((flags & SI_WILDP) != 0)
3271 		goto find_out_wild_ports;
3272 
3273 	hv = NAT_HASH_FN(srcip, sport, 0xffffffff);
3274 	hv = NAT_HASH_FN(dst.s_addr, hv + dport, ifs->ifs_ipf_nattable_sz);
3275 	nat = ifs->ifs_nat_table[0][hv];
3276 	for (; nat; nat = nat->nat_hnext[0]) {
3277 		if (nat->nat_ifps[1] != NULL) {
3278 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
3279 				continue;
3280 		} else if (ifp != NULL)
3281 			nat->nat_ifps[1] = ifp;
3282 
3283 		nflags = nat->nat_flags;
3284 
3285 		if (nat->nat_inip.s_addr == srcip &&
3286 		    nat->nat_oip.s_addr == dst.s_addr &&
3287 		    (((p == 0) && (sflags == (nflags & NAT_TCPUDPICMP)))
3288 		     || (p == nat->nat_p))) {
3289 			switch (p)
3290 			{
3291 #if 0
3292 			case IPPROTO_GRE :
3293 				if (nat->nat_call[1] != fin->fin_data[0])
3294 					continue;
3295 				break;
3296 #endif
3297 			case IPPROTO_TCP :
3298 			case IPPROTO_UDP :
3299 				if (nat->nat_oport != dport)
3300 					continue;
3301 				if (nat->nat_inport != sport)
3302 					continue;
3303 				break;
3304 			default :
3305 				break;
3306 			}
3307 
3308 			ipn = nat->nat_ptr;
3309 			if ((ipn != NULL) && (nat->nat_aps != NULL))
3310 				if (appr_match(fin, nat) != 0)
3311 					continue;
3312 			return nat;
3313 		}
3314 	}
3315 
3316 	/*
3317 	 * So if we didn't find it but there are wildcard members in the hash
3318 	 * table, go back and look for them.  We do this search and update here
3319 	 * because it is modifying the NAT table and we want to do this only
3320 	 * for the first packet that matches.  The exception, of course, is
3321 	 * for "dummy" (FI_IGNORE) lookups.
3322 	 */
3323 find_out_wild_ports:
3324 	if (!(flags & NAT_TCPUDP) || !(flags & NAT_SEARCH))
3325 		return NULL;
3326 	if (ifs->ifs_nat_stats.ns_wilds == 0)
3327 		return NULL;
3328 
3329 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
3330 
3331 	hv = NAT_HASH_FN(srcip, 0, 0xffffffff);
3332 	hv = NAT_HASH_FN(dst.s_addr, hv, ifs->ifs_ipf_nattable_sz);
3333 
3334 	WRITE_ENTER(&ifs->ifs_ipf_nat);
3335 
3336 	nat = ifs->ifs_nat_table[0][hv];
3337 	for (; nat; nat = nat->nat_hnext[0]) {
3338 		if (nat->nat_ifps[1] != NULL) {
3339 			if ((ifp != NULL) && (ifp != nat->nat_ifps[1]))
3340 				continue;
3341 		} else if (ifp != NULL)
3342 			nat->nat_ifps[1] = ifp;
3343 
3344 		if (nat->nat_p != fin->fin_p)
3345 			continue;
3346 		if ((nat->nat_inip.s_addr != srcip) ||
3347 		    (nat->nat_oip.s_addr != dst.s_addr))
3348 			continue;
3349 
3350 		nflags = nat->nat_flags;
3351 		if (!(nflags & (NAT_TCPUDP|SI_WILDP)))
3352 			continue;
3353 
3354 		if (nat_wildok(nat, (int)sport, (int)dport, nflags,
3355 			       NAT_OUTBOUND) == 1) {
3356 			if ((fin->fin_flx & FI_IGNORE) != 0)
3357 				break;
3358 			if ((nflags & SI_CLONE) != 0) {
3359 				nat = fr_natclone(fin, nat);
3360 				if (nat == NULL)
3361 					break;
3362 			} else {
3363 				MUTEX_ENTER(&ifs->ifs_ipf_nat_new);
3364 				ifs->ifs_nat_stats.ns_wilds--;
3365 				MUTEX_EXIT(&ifs->ifs_ipf_nat_new);
3366 			}
3367 			nat->nat_inport = sport;
3368 			nat->nat_oport = dport;
3369 			if (nat->nat_outport == 0)
3370 				nat->nat_outport = sport;
3371 			nat->nat_flags &= ~(SI_W_DPORT|SI_W_SPORT);
3372 			nat_tabmove(nat, ifs);
3373 			break;
3374 		}
3375 	}
3376 
3377 	MUTEX_DOWNGRADE(&ifs->ifs_ipf_nat);
3378 
3379 	return nat;
3380 }
3381 
3382 
3383 /* ------------------------------------------------------------------------ */
3384 /* Function:    nat_lookupredir                                             */
3385 /* Returns:     nat_t* - NULL == no match,                                  */
3386 /*                       else pointer to matching NAT entry                 */
3387 /* Parameters:  np(I) - pointer to description of packet to find NAT table  */
3388 /*                      entry for.                                          */
3389 /*                                                                          */
3390 /* Lookup the NAT tables to search for a matching redirect                  */
3391 /* ------------------------------------------------------------------------ */
3392 nat_t *nat_lookupredir(np, ifs)
3393 natlookup_t *np;
3394 ipf_stack_t *ifs;
3395 {
3396 	fr_info_t fi;
3397 	nat_t *nat;
3398 
3399 	bzero((char *)&fi, sizeof(fi));
3400 	if (np->nl_flags & IPN_IN) {
3401 		fi.fin_data[0] = ntohs(np->nl_realport);
3402 		fi.fin_data[1] = ntohs(np->nl_outport);
3403 	} else {
3404 		fi.fin_data[0] = ntohs(np->nl_inport);
3405 		fi.fin_data[1] = ntohs(np->nl_outport);
3406 	}
3407 	if (np->nl_flags & IPN_TCP)
3408 		fi.fin_p = IPPROTO_TCP;
3409 	else if (np->nl_flags & IPN_UDP)
3410 		fi.fin_p = IPPROTO_UDP;
3411 	else if (np->nl_flags & (IPN_ICMPERR|IPN_ICMPQUERY))
3412 		fi.fin_p = IPPROTO_ICMP;
3413 
3414 	fi.fin_ifs = ifs;
3415 	/*
3416 	 * We can do two sorts of lookups:
3417 	 * - IPN_IN: we have the `real' and `out' address, look for `in'.
3418 	 * - default: we have the `in' and `out' address, look for `real'.
3419 	 */
3420 	if (np->nl_flags & IPN_IN) {
3421 		if ((nat = nat_inlookup(&fi, np->nl_flags, fi.fin_p,
3422 					np->nl_realip, np->nl_outip))) {
3423 			np->nl_inip = nat->nat_inip;
3424 			np->nl_inport = nat->nat_inport;
3425 		}
3426 	} else {
3427 		/*
3428 		 * If nl_inip is non null, this is a lookup based on the real
3429 		 * ip address. Else, we use the fake.
3430 		 */
3431 		if ((nat = nat_outlookup(&fi, np->nl_flags, fi.fin_p,
3432 					 np->nl_inip, np->nl_outip))) {
3433 
3434 			if ((np->nl_flags & IPN_FINDFORWARD) != 0) {
3435 				fr_info_t fin;
3436 				bzero((char *)&fin, sizeof(fin));
3437 				fin.fin_p = nat->nat_p;
3438 				fin.fin_data[0] = ntohs(nat->nat_outport);
3439 				fin.fin_data[1] = ntohs(nat->nat_oport);
3440 				fin.fin_ifs = ifs;
3441 				if (nat_inlookup(&fin, np->nl_flags, fin.fin_p,
3442 						 nat->nat_outip,
3443 						 nat->nat_oip) != NULL) {
3444 					np->nl_flags &= ~IPN_FINDFORWARD;
3445 				}
3446 			}
3447 
3448 			np->nl_realip = nat->nat_outip;
3449 			np->nl_realport = nat->nat_outport;
3450 		}
3451  	}
3452 
3453 	return nat;
3454 }
3455 
3456 
3457 /* ------------------------------------------------------------------------ */
3458 /* Function:    nat_match                                                   */
3459 /* Returns:     int - 0 == no match, 1 == match                             */
3460 /* Parameters:  fin(I)   - pointer to packet information                    */
3461 /*              np(I)    - pointer to NAT rule                              */
3462 /*                                                                          */
3463 /* Pull the matching of a packet against a NAT rule out of that complex     */
3464 /* loop inside fr_checknatin() and lay it out properly in its own function. */
3465 /* ------------------------------------------------------------------------ */
3466 static int nat_match(fin, np)
3467 fr_info_t *fin;
3468 ipnat_t *np;
3469 {
3470 	frtuc_t *ft;
3471 
3472 	if (fin->fin_v != 4)
3473 		return 0;
3474 
3475 	if (np->in_p && fin->fin_p != np->in_p)
3476 		return 0;
3477 
3478 	if (fin->fin_out) {
3479 		if (!(np->in_redir & (NAT_MAP|NAT_MAPBLK)))
3480 			return 0;
3481 		if (((fin->fin_fi.fi_saddr & np->in_inmsk) != np->in_inip)
3482 		    ^ ((np->in_flags & IPN_NOTSRC) != 0))
3483 			return 0;
3484 		if (((fin->fin_fi.fi_daddr & np->in_srcmsk) != np->in_srcip)
3485 		    ^ ((np->in_flags & IPN_NOTDST) != 0))
3486 			return 0;
3487 	} else {
3488 		if (!(np->in_redir & NAT_REDIRECT))
3489 			return 0;
3490 		if (((fin->fin_fi.fi_saddr & np->in_srcmsk) != np->in_srcip)
3491 		    ^ ((np->in_flags & IPN_NOTSRC) != 0))
3492 			return 0;
3493 		if (((fin->fin_fi.fi_daddr & np->in_outmsk) != np->in_outip)
3494 		    ^ ((np->in_flags & IPN_NOTDST) != 0))
3495 			return 0;
3496 	}
3497 
3498 	ft = &np->in_tuc;
3499 	if (!(fin->fin_flx & FI_TCPUDP) ||
3500 	    (fin->fin_flx & (FI_SHORT|FI_FRAGBODY))) {
3501 		if (ft->ftu_scmp || ft->ftu_dcmp)
3502 			return 0;
3503 		return 1;
3504 	}
3505 
3506 	return fr_tcpudpchk(fin, ft);
3507 }
3508 
3509 
3510 /* ------------------------------------------------------------------------ */
3511 /* Function:    nat_update                                                  */
3512 /* Returns:     Nil                                                         */
3513 /* Parameters:  nat(I)    - pointer to NAT structure                        */
3514 /*              np(I)     - pointer to NAT rule                             */
3515 /*                                                                          */
3516 /* Updates the lifetime of a NAT table entry for non-TCP packets.  Must be  */
3517 /* called with fin_rev updated - i.e. after calling nat_proto().            */
3518 /* ------------------------------------------------------------------------ */
3519 void nat_update(fin, nat, np)
3520 fr_info_t *fin;
3521 nat_t *nat;
3522 ipnat_t *np;
3523 {
3524 	ipftq_t *ifq, *ifq2;
3525 	ipftqent_t *tqe;
3526 	ipf_stack_t *ifs = fin->fin_ifs;
3527 
3528 	MUTEX_ENTER(&nat->nat_lock);
3529 	tqe = &nat->nat_tqe;
3530 	ifq = tqe->tqe_ifq;
3531 
3532 	/*
3533 	 * We allow over-riding of NAT timeouts from NAT rules, even for
3534 	 * TCP, however, if it is TCP and there is no rule timeout set,
3535 	 * then do not update the timeout here.
3536 	 */
3537 	if (np != NULL)
3538 		ifq2 = np->in_tqehead[fin->fin_rev];
3539 	else
3540 		ifq2 = NULL;
3541 
3542 	if (nat->nat_p == IPPROTO_TCP && ifq2 == NULL) {
3543 		(void) fr_tcp_age(&nat->nat_tqe, fin, ifs->ifs_nat_tqb, 0);
3544 	} else {
3545 		if (ifq2 == NULL) {
3546 			if (nat->nat_p == IPPROTO_UDP)
3547 				ifq2 = &ifs->ifs_nat_udptq;
3548 			else if (nat->nat_p == IPPROTO_ICMP)
3549 				ifq2 = &ifs->ifs_nat_icmptq;
3550 			else
3551 				ifq2 = &ifs->ifs_nat_iptq;
3552 		}
3553 
3554 		fr_movequeue(tqe, ifq, ifq2, ifs);
3555 	}
3556 	MUTEX_EXIT(&nat->nat_lock);
3557 }
3558 
3559 
3560 /* ------------------------------------------------------------------------ */
3561 /* Function:    fr_checknatout                                              */
3562 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
3563 /*                     0 == no packet translation occurred,                 */
3564 /*                     1 == packet was successfully translated.             */
3565 /* Parameters:  fin(I)   - pointer to packet information                    */
3566 /*              passp(I) - pointer to filtering result flags                */
3567 /*                                                                          */
3568 /* Check to see if an outcoming packet should be changed.  ICMP packets are */
3569 /* first checked to see if they match an existing entry (if an error),      */
3570 /* otherwise a search of the current NAT table is made.  If neither results */
3571 /* in a match then a search for a matching NAT rule is made.  Create a new  */
3572 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
3573 /* packet header(s) as required.                                            */
3574 /* ------------------------------------------------------------------------ */
3575 int fr_checknatout(fin, passp)
3576 fr_info_t *fin;
3577 u_32_t *passp;
3578 {
3579 	struct ifnet *ifp, *sifp;
3580 	icmphdr_t *icmp = NULL;
3581 	tcphdr_t *tcp = NULL;
3582 	int rval, natfailed;
3583 	ipnat_t *np = NULL;
3584 	u_int nflags = 0;
3585 	u_32_t ipa, iph;
3586 	int natadd = 1;
3587 	frentry_t *fr;
3588 	nat_t *nat;
3589 	ipf_stack_t *ifs = fin->fin_ifs;
3590 
3591 	if (ifs->ifs_nat_stats.ns_rules == 0 || ifs->ifs_fr_nat_lock != 0)
3592 		return 0;
3593 
3594 	natfailed = 0;
3595 	fr = fin->fin_fr;
3596 	sifp = fin->fin_ifp;
3597 	if ((fr != NULL) && !(fr->fr_flags & FR_DUP) &&
3598 	    fr->fr_tifs[fin->fin_rev].fd_ifp &&
3599 	    fr->fr_tifs[fin->fin_rev].fd_ifp != (void *)-1)
3600 		fin->fin_ifp = fr->fr_tifs[fin->fin_rev].fd_ifp;
3601 	ifp = fin->fin_ifp;
3602 
3603 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
3604 		switch (fin->fin_p)
3605 		{
3606 		case IPPROTO_TCP :
3607 			nflags = IPN_TCP;
3608 			break;
3609 		case IPPROTO_UDP :
3610 			nflags = IPN_UDP;
3611 			break;
3612 		case IPPROTO_ICMP :
3613 			icmp = fin->fin_dp;
3614 
3615 			/*
3616 			 * This is an incoming packet, so the destination is
3617 			 * the icmp_id and the source port equals 0
3618 			 */
3619 			if (nat_icmpquerytype4(icmp->icmp_type))
3620 				nflags = IPN_ICMPQUERY;
3621 			break;
3622 		default :
3623 			break;
3624 		}
3625 
3626 		if ((nflags & IPN_TCPUDP))
3627 			tcp = fin->fin_dp;
3628 	}
3629 
3630 	ipa = fin->fin_saddr;
3631 
3632 	READ_ENTER(&ifs->ifs_ipf_nat);
3633 
3634 	if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
3635 	    (nat = nat_icmperror(fin, &nflags, NAT_OUTBOUND)))
3636 		/*EMPTY*/;
3637 	else if ((fin->fin_flx & FI_FRAG) && (nat = fr_nat_knownfrag(fin)))
3638 		natadd = 0;
3639 	else if ((nat = nat_outlookup(fin, nflags|NAT_SEARCH, (u_int)fin->fin_p,
3640 				      fin->fin_src, fin->fin_dst))) {
3641 		nflags = nat->nat_flags;
3642 	} else {
3643 		u_32_t hv, msk, nmsk;
3644 
3645 		/*
3646 		 * If there is no current entry in the nat table for this IP#,
3647 		 * create one for it (if there is a matching rule).
3648 		 */
3649 		RWLOCK_EXIT(&ifs->ifs_ipf_nat);
3650 		msk = 0xffffffff;
3651 		nmsk = ifs->ifs_nat_masks;
3652 		WRITE_ENTER(&ifs->ifs_ipf_nat);
3653 maskloop:
3654 		iph = ipa & htonl(msk);
3655 		hv = NAT_HASH_FN(iph, 0, ifs->ifs_ipf_natrules_sz);
3656 		for (np = ifs->ifs_nat_rules[hv]; np; np = np->in_mnext)
3657 		{
3658 			if ((np->in_ifps[1] && (np->in_ifps[1] != ifp)))
3659 				continue;
3660 			if (np->in_v != fin->fin_v)
3661 				continue;
3662 			if (np->in_p && (np->in_p != fin->fin_p))
3663 				continue;
3664 			if ((np->in_flags & IPN_RF) && !(np->in_flags & nflags))
3665 				continue;
3666 			if (np->in_flags & IPN_FILTER) {
3667 				if (!nat_match(fin, np))
3668 					continue;
3669 			} else if ((ipa & np->in_inmsk) != np->in_inip)
3670 				continue;
3671 
3672 			if ((fr != NULL) &&
3673 			    !fr_matchtag(&np->in_tag, &fr->fr_nattag))
3674 				continue;
3675 
3676 			if (*np->in_plabel != '\0') {
3677 				if (((np->in_flags & IPN_FILTER) == 0) &&
3678 				    (np->in_dport != tcp->th_dport))
3679 					continue;
3680 				if (appr_ok(fin, tcp, np) == 0)
3681 					continue;
3682 			}
3683 
3684 			if ((nat = nat_new(fin, np, NULL, nflags,
3685 					   NAT_OUTBOUND))) {
3686 				np->in_hits++;
3687 				break;
3688 			} else
3689 				natfailed = -1;
3690 		}
3691 		if ((np == NULL) && (nmsk != 0)) {
3692 			while (nmsk) {
3693 				msk <<= 1;
3694 				if (nmsk & 0x80000000)
3695 					break;
3696 				nmsk <<= 1;
3697 			}
3698 			if (nmsk != 0) {
3699 				nmsk <<= 1;
3700 				goto maskloop;
3701 			}
3702 		}
3703 		MUTEX_DOWNGRADE(&ifs->ifs_ipf_nat);
3704 	}
3705 
3706 	if (nat != NULL) {
3707 		rval = fr_natout(fin, nat, natadd, nflags);
3708 		if (rval == 1) {
3709 			MUTEX_ENTER(&nat->nat_lock);
3710 			nat->nat_ref++;
3711 			MUTEX_EXIT(&nat->nat_lock);
3712 			nat->nat_touched = ifs->ifs_fr_ticks;
3713 			fin->fin_nat = nat;
3714 		}
3715 	} else
3716 		rval = natfailed;
3717 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
3718 
3719 	if (rval == -1) {
3720 		if (passp != NULL)
3721 			*passp = FR_BLOCK;
3722 		fin->fin_flx |= FI_BADNAT;
3723 	}
3724 	fin->fin_ifp = sifp;
3725 	return rval;
3726 }
3727 
3728 /* ------------------------------------------------------------------------ */
3729 /* Function:    fr_natout                                                   */
3730 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
3731 /*                     1 == packet was successfully translated.             */
3732 /* Parameters:  fin(I)    - pointer to packet information                   */
3733 /*              nat(I)    - pointer to NAT structure                        */
3734 /*              natadd(I) - flag indicating if it is safe to add frag cache */
3735 /*              nflags(I) - NAT flags set for this packet                   */
3736 /*                                                                          */
3737 /* Translate a packet coming "out" on an interface.                         */
3738 /* ------------------------------------------------------------------------ */
3739 int fr_natout(fin, nat, natadd, nflags)
3740 fr_info_t *fin;
3741 nat_t *nat;
3742 int natadd;
3743 u_32_t nflags;
3744 {
3745 	icmphdr_t *icmp;
3746 	u_short *csump;
3747 	u_32_t sumd;
3748 	tcphdr_t *tcp;
3749 	ipnat_t *np;
3750 	int i;
3751 	ipf_stack_t *ifs = fin->fin_ifs;
3752 
3753 #if SOLARIS && defined(_KERNEL)
3754 	net_data_t net_data_p;
3755 	if (fin->fin_v == 4)
3756 		net_data_p = ifs->ifs_ipf_ipv4;
3757 	else
3758 		net_data_p = ifs->ifs_ipf_ipv6;
3759 #endif
3760 
3761 	tcp = NULL;
3762 	icmp = NULL;
3763 	csump = NULL;
3764 	np = nat->nat_ptr;
3765 
3766 	if ((natadd != 0) && (fin->fin_flx & FI_FRAG))
3767 		(void) fr_nat_newfrag(fin, 0, nat);
3768 
3769 	MUTEX_ENTER(&nat->nat_lock);
3770 	nat->nat_bytes[1] += fin->fin_plen;
3771 	nat->nat_pkts[1]++;
3772 	MUTEX_EXIT(&nat->nat_lock);
3773 
3774 	/*
3775 	 * Fix up checksums, not by recalculating them, but
3776 	 * simply computing adjustments.
3777 	 * This is only done for STREAMS based IP implementations where the
3778 	 * checksum has already been calculated by IP.  In all other cases,
3779 	 * IPFilter is called before the checksum needs calculating so there
3780 	 * is no call to modify whatever is in the header now.
3781 	 */
3782 	ASSERT(fin->fin_m != NULL);
3783 	if (fin->fin_v == 4 && !NET_IS_HCK_L3_FULL(net_data_p, fin->fin_m)) {
3784 		if (nflags == IPN_ICMPERR) {
3785 			u_32_t s1, s2;
3786 
3787 			s1 = LONG_SUM(ntohl(fin->fin_saddr));
3788 			s2 = LONG_SUM(ntohl(nat->nat_outip.s_addr));
3789 			CALC_SUMD(s1, s2, sumd);
3790 
3791 			fix_outcksum(&fin->fin_ip->ip_sum, sumd);
3792 		}
3793 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
3794     defined(linux) || defined(BRIDGE_IPF)
3795 		else {
3796 			/*
3797 			 * Strictly speaking, this isn't necessary on BSD
3798 			 * kernels because they do checksum calculation after
3799 			 * this code has run BUT if ipfilter is being used
3800 			 * to do NAT as a bridge, that code doesn't exist.
3801 			 */
3802 			if (nat->nat_dir == NAT_OUTBOUND)
3803 				fix_outcksum(&fin->fin_ip->ip_sum,
3804 					    nat->nat_ipsumd);
3805 			else
3806 				fix_incksum(&fin->fin_ip->ip_sum,
3807 				 	   nat->nat_ipsumd);
3808 		}
3809 #endif
3810 	}
3811 
3812 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
3813 		if ((nat->nat_outport != 0) && (nflags & IPN_TCPUDP)) {
3814 			tcp = fin->fin_dp;
3815 
3816 			tcp->th_sport = nat->nat_outport;
3817 			fin->fin_data[0] = ntohs(nat->nat_outport);
3818 		}
3819 
3820 		if ((nat->nat_outport != 0) && (nflags & IPN_ICMPQUERY)) {
3821 			icmp = fin->fin_dp;
3822 			icmp->icmp_id = nat->nat_outport;
3823 		}
3824 
3825 		csump = nat_proto(fin, nat, nflags);
3826 	}
3827 
3828 	fin->fin_ip->ip_src = nat->nat_outip;
3829 
3830 	nat_update(fin, nat, np);
3831 
3832 	/*
3833 	 * The above comments do not hold for layer 4 (or higher) checksums...
3834 	 */
3835 	if (csump != NULL && !NET_IS_HCK_L4_FULL(net_data_p, fin->fin_m)) {
3836 		if (nflags & IPN_TCPUDP &&
3837 	   	    NET_IS_HCK_L4_PART(net_data_p, fin->fin_m))
3838 			sumd = nat->nat_sumd[1];
3839 		else
3840 			sumd = nat->nat_sumd[0];
3841 
3842 		if (nat->nat_dir == NAT_OUTBOUND)
3843 			fix_outcksum(csump, sumd);
3844 		else
3845 			fix_incksum(csump, sumd);
3846 	}
3847 #ifdef	IPFILTER_SYNC
3848 	ipfsync_update(SMC_NAT, fin, nat->nat_sync);
3849 #endif
3850 	/* ------------------------------------------------------------- */
3851 	/* A few quick notes:						 */
3852 	/*	Following are test conditions prior to calling the 	 */
3853 	/*	appr_check routine.					 */
3854 	/*								 */
3855 	/* 	A NULL tcp indicates a non TCP/UDP packet.  When dealing */
3856 	/*	with a redirect rule, we attempt to match the packet's	 */
3857 	/*	source port against in_dport, otherwise	we'd compare the */
3858 	/*	packet's destination.			 		 */
3859 	/* ------------------------------------------------------------- */
3860 	if ((np != NULL) && (np->in_apr != NULL)) {
3861 		i = appr_check(fin, nat);
3862 		if (i == 0)
3863 			i = 1;
3864 	} else
3865 		i = 1;
3866 	ATOMIC_INCL(ifs->ifs_nat_stats.ns_mapped[1]);
3867 	fin->fin_flx |= FI_NATED;
3868 	return i;
3869 }
3870 
3871 
3872 /* ------------------------------------------------------------------------ */
3873 /* Function:    fr_checknatin                                               */
3874 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
3875 /*                     0 == no packet translation occurred,                 */
3876 /*                     1 == packet was successfully translated.             */
3877 /* Parameters:  fin(I)   - pointer to packet information                    */
3878 /*              passp(I) - pointer to filtering result flags                */
3879 /*                                                                          */
3880 /* Check to see if an incoming packet should be changed.  ICMP packets are  */
3881 /* first checked to see if they match an existing entry (if an error),      */
3882 /* otherwise a search of the current NAT table is made.  If neither results */
3883 /* in a match then a search for a matching NAT rule is made.  Create a new  */
3884 /* NAT entry if a we matched a NAT rule.  Lastly, actually change the       */
3885 /* packet header(s) as required.                                            */
3886 /* ------------------------------------------------------------------------ */
3887 int fr_checknatin(fin, passp)
3888 fr_info_t *fin;
3889 u_32_t *passp;
3890 {
3891 	u_int nflags, natadd;
3892 	int rval, natfailed;
3893 	struct ifnet *ifp;
3894 	struct in_addr in;
3895 	icmphdr_t *icmp;
3896 	tcphdr_t *tcp;
3897 	u_short dport;
3898 	ipnat_t *np;
3899 	nat_t *nat;
3900 	u_32_t iph;
3901 	ipf_stack_t *ifs = fin->fin_ifs;
3902 
3903 	if (ifs->ifs_nat_stats.ns_rules == 0 || ifs->ifs_fr_nat_lock != 0)
3904 		return 0;
3905 
3906 	tcp = NULL;
3907 	icmp = NULL;
3908 	dport = 0;
3909 	natadd = 1;
3910 	nflags = 0;
3911 	natfailed = 0;
3912 	ifp = fin->fin_ifp;
3913 
3914 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
3915 		switch (fin->fin_p)
3916 		{
3917 		case IPPROTO_TCP :
3918 			nflags = IPN_TCP;
3919 			break;
3920 		case IPPROTO_UDP :
3921 			nflags = IPN_UDP;
3922 			break;
3923 		case IPPROTO_ICMP :
3924 			icmp = fin->fin_dp;
3925 
3926 			/*
3927 			 * This is an incoming packet, so the destination is
3928 			 * the icmp_id and the source port equals 0
3929 			 */
3930 			if (nat_icmpquerytype4(icmp->icmp_type)) {
3931 				nflags = IPN_ICMPQUERY;
3932 				dport = icmp->icmp_id;
3933 			} break;
3934 		default :
3935 			break;
3936 		}
3937 
3938 		if ((nflags & IPN_TCPUDP)) {
3939 			tcp = fin->fin_dp;
3940 			dport = tcp->th_dport;
3941 		}
3942 	}
3943 
3944 	in = fin->fin_dst;
3945 
3946 	READ_ENTER(&ifs->ifs_ipf_nat);
3947 
3948 	if ((fin->fin_p == IPPROTO_ICMP) && !(nflags & IPN_ICMPQUERY) &&
3949 	    (nat = nat_icmperror(fin, &nflags, NAT_INBOUND)))
3950 		/*EMPTY*/;
3951 	else if ((fin->fin_flx & FI_FRAG) && (nat = fr_nat_knownfrag(fin)))
3952 		natadd = 0;
3953 	else if ((nat = nat_inlookup(fin, nflags|NAT_SEARCH, (u_int)fin->fin_p,
3954 				     fin->fin_src, in))) {
3955 		nflags = nat->nat_flags;
3956 	} else {
3957 		u_32_t hv, msk, rmsk;
3958 
3959 		RWLOCK_EXIT(&ifs->ifs_ipf_nat);
3960 		rmsk = ifs->ifs_rdr_masks;
3961 		msk = 0xffffffff;
3962 		WRITE_ENTER(&ifs->ifs_ipf_nat);
3963 		/*
3964 		 * If there is no current entry in the nat table for this IP#,
3965 		 * create one for it (if there is a matching rule).
3966 		 */
3967 maskloop:
3968 		iph = in.s_addr & htonl(msk);
3969 		hv = NAT_HASH_FN(iph, 0, ifs->ifs_ipf_rdrrules_sz);
3970 		for (np = ifs->ifs_rdr_rules[hv]; np; np = np->in_rnext) {
3971 			if (np->in_ifps[0] && (np->in_ifps[0] != ifp))
3972 				continue;
3973 			if (np->in_v != fin->fin_v)
3974 				continue;
3975 			if (np->in_p && (np->in_p != fin->fin_p))
3976 				continue;
3977 			if ((np->in_flags & IPN_RF) && !(np->in_flags & nflags))
3978 				continue;
3979 			if (np->in_flags & IPN_FILTER) {
3980 				if (!nat_match(fin, np))
3981 					continue;
3982 			} else {
3983 				if ((in.s_addr & np->in_outmsk) != np->in_outip)
3984 					continue;
3985 				if (np->in_pmin &&
3986 				    ((ntohs(np->in_pmax) < ntohs(dport)) ||
3987 				     (ntohs(dport) < ntohs(np->in_pmin))))
3988 					continue;
3989 			}
3990 
3991 			if (*np->in_plabel != '\0') {
3992 				if (!appr_ok(fin, tcp, np)) {
3993 					continue;
3994 				}
3995 			}
3996 
3997 			nat = nat_new(fin, np, NULL, nflags, NAT_INBOUND);
3998 			if (nat != NULL) {
3999 				np->in_hits++;
4000 				break;
4001 			} else
4002 				natfailed = -1;
4003 		}
4004 
4005 		if ((np == NULL) && (rmsk != 0)) {
4006 			while (rmsk) {
4007 				msk <<= 1;
4008 				if (rmsk & 0x80000000)
4009 					break;
4010 				rmsk <<= 1;
4011 			}
4012 			if (rmsk != 0) {
4013 				rmsk <<= 1;
4014 				goto maskloop;
4015 			}
4016 		}
4017 		MUTEX_DOWNGRADE(&ifs->ifs_ipf_nat);
4018 	}
4019 	if (nat != NULL) {
4020 		rval = fr_natin(fin, nat, natadd, nflags);
4021 		if (rval == 1) {
4022 			MUTEX_ENTER(&nat->nat_lock);
4023 			nat->nat_ref++;
4024 			MUTEX_EXIT(&nat->nat_lock);
4025 			nat->nat_touched = ifs->ifs_fr_ticks;
4026 			fin->fin_nat = nat;
4027 			fin->fin_state = nat->nat_state;
4028 		}
4029 	} else
4030 		rval = natfailed;
4031 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
4032 
4033 	if (rval == -1) {
4034 		if (passp != NULL)
4035 			*passp = FR_BLOCK;
4036 		fin->fin_flx |= FI_BADNAT;
4037 	}
4038 	return rval;
4039 }
4040 
4041 
4042 /* ------------------------------------------------------------------------ */
4043 /* Function:    fr_natin                                                    */
4044 /* Returns:     int - -1 == packet failed NAT checks so block it,           */
4045 /*                     1 == packet was successfully translated.             */
4046 /* Parameters:  fin(I)    - pointer to packet information                   */
4047 /*              nat(I)    - pointer to NAT structure                        */
4048 /*              natadd(I) - flag indicating if it is safe to add frag cache */
4049 /*              nflags(I) - NAT flags set for this packet                   */
4050 /* Locks Held:  ipf_nat (READ)                                              */
4051 /*                                                                          */
4052 /* Translate a packet coming "in" on an interface.                          */
4053 /* ------------------------------------------------------------------------ */
4054 int fr_natin(fin, nat, natadd, nflags)
4055 fr_info_t *fin;
4056 nat_t *nat;
4057 int natadd;
4058 u_32_t nflags;
4059 {
4060 	icmphdr_t *icmp;
4061 	u_short *csump, *csump1;
4062 	u_32_t sumd;
4063 	tcphdr_t *tcp;
4064 	ipnat_t *np;
4065 	int i;
4066 	ipf_stack_t *ifs = fin->fin_ifs;
4067 
4068 #if SOLARIS && defined(_KERNEL)
4069 	net_data_t net_data_p;
4070 	if (fin->fin_v == 4)
4071 		net_data_p = ifs->ifs_ipf_ipv4;
4072 	else
4073 		net_data_p = ifs->ifs_ipf_ipv6;
4074 #endif
4075 
4076 	tcp = NULL;
4077 	csump = NULL;
4078 	np = nat->nat_ptr;
4079 	fin->fin_fr = nat->nat_fr;
4080 
4081 	if ((natadd != 0) && (fin->fin_flx & FI_FRAG))
4082 		(void) fr_nat_newfrag(fin, 0, nat);
4083 
4084 	if (np != NULL) {
4085 
4086 	/* ------------------------------------------------------------- */
4087 	/* A few quick notes:						 */
4088 	/*	Following are test conditions prior to calling the 	 */
4089 	/*	appr_check routine.					 */
4090 	/*								 */
4091 	/* 	A NULL tcp indicates a non TCP/UDP packet.  When dealing */
4092 	/*	with a map rule, we attempt to match the packet's	 */
4093 	/*	source port against in_dport, otherwise	we'd compare the */
4094 	/*	packet's destination.			 		 */
4095 	/* ------------------------------------------------------------- */
4096 		if (np->in_apr != NULL) {
4097 			i = appr_check(fin, nat);
4098 			if (i == -1) {
4099 				return -1;
4100 			}
4101 		}
4102 	}
4103 
4104 #ifdef	IPFILTER_SYNC
4105 	ipfsync_update(SMC_NAT, fin, nat->nat_sync);
4106 #endif
4107 
4108 	MUTEX_ENTER(&nat->nat_lock);
4109 	nat->nat_bytes[0] += fin->fin_plen;
4110 	nat->nat_pkts[0]++;
4111 	MUTEX_EXIT(&nat->nat_lock);
4112 
4113 	fin->fin_ip->ip_dst = nat->nat_inip;
4114 	fin->fin_fi.fi_daddr = nat->nat_inip.s_addr;
4115 	if (nflags & IPN_TCPUDP)
4116 		tcp = fin->fin_dp;
4117 
4118 	/*
4119 	 * Fix up checksums, not by recalculating them, but
4120 	 * simply computing adjustments.
4121 	 * Why only do this for some platforms on inbound packets ?
4122 	 * Because for those that it is done, IP processing is yet to happen
4123 	 * and so the IPv4 header checksum has not yet been evaluated.
4124 	 * Perhaps it should always be done for the benefit of things like
4125 	 * fast forwarding (so that it doesn't need to be recomputed) but with
4126 	 * header checksum offloading, perhaps it is a moot point.
4127 	 */
4128 #if !defined(_KERNEL) || defined(MENTAT) || defined(__sgi) || \
4129      defined(__osf__) || defined(linux)
4130 	if (nat->nat_dir == NAT_OUTBOUND)
4131 		fix_incksum(&fin->fin_ip->ip_sum, nat->nat_ipsumd);
4132 	else
4133 		fix_outcksum(&fin->fin_ip->ip_sum, nat->nat_ipsumd);
4134 #endif
4135 
4136 	if (!(fin->fin_flx & FI_SHORT) && (fin->fin_off == 0)) {
4137 		if ((nat->nat_inport != 0) && (nflags & IPN_TCPUDP)) {
4138 			tcp->th_dport = nat->nat_inport;
4139 			fin->fin_data[1] = ntohs(nat->nat_inport);
4140 		}
4141 
4142 
4143 		if ((nat->nat_inport != 0) && (nflags & IPN_ICMPQUERY)) {
4144 			icmp = fin->fin_dp;
4145 
4146 			icmp->icmp_id = nat->nat_inport;
4147 		}
4148 
4149 		csump = nat_proto(fin, nat, nflags);
4150 	}
4151 
4152 	nat_update(fin, nat, np);
4153 
4154 #if SOLARIS && defined(_KERNEL)
4155 	if (nflags & IPN_TCPUDP &&
4156 	    NET_IS_HCK_L4_PART(net_data_p, fin->fin_m)) {
4157 		sumd = nat->nat_sumd[1];
4158 		csump1 = &(fin->fin_m->b_datap->db_struioun.cksum.cksum_val.u16);
4159 		if (csump1 != NULL) {
4160 			if (nat->nat_dir == NAT_OUTBOUND)
4161 				fix_incksum(csump1, sumd);
4162 			else
4163 				fix_outcksum(csump1, sumd);
4164 		}
4165 	} else
4166 #endif
4167 		sumd = nat->nat_sumd[0];
4168 
4169 	/*
4170 	 * Inbound packets always need to have their address adjusted in case
4171 	 * code following this validates it.
4172 	 */
4173 	if (csump != NULL) {
4174 		if (nat->nat_dir == NAT_OUTBOUND)
4175 			fix_incksum(csump, sumd);
4176 		else
4177 			fix_outcksum(csump, sumd);
4178 	}
4179 	ATOMIC_INCL(ifs->ifs_nat_stats.ns_mapped[0]);
4180 	fin->fin_flx |= FI_NATED;
4181 	if (np != NULL && np->in_tag.ipt_num[0] != 0)
4182 		fin->fin_nattag = &np->in_tag;
4183 	return 1;
4184 }
4185 
4186 
4187 /* ------------------------------------------------------------------------ */
4188 /* Function:    nat_proto                                                   */
4189 /* Returns:     u_short* - pointer to transport header checksum to update,  */
4190 /*                         NULL if the transport protocol is not recognised */
4191 /*                         as needing a checksum update.                    */
4192 /* Parameters:  fin(I)    - pointer to packet information                   */
4193 /*              nat(I)    - pointer to NAT structure                        */
4194 /*              nflags(I) - NAT flags set for this packet                   */
4195 /*                                                                          */
4196 /* Return the pointer to the checksum field for each protocol so understood.*/
4197 /* If support for making other changes to a protocol header is required,    */
4198 /* that is not strictly 'address' translation, such as clamping the MSS in  */
4199 /* TCP down to a specific value, then do it from here.                      */
4200 /* ------------------------------------------------------------------------ */
4201 u_short *nat_proto(fin, nat, nflags)
4202 fr_info_t *fin;
4203 nat_t *nat;
4204 u_int nflags;
4205 {
4206 	icmphdr_t *icmp;
4207 	u_short *csump;
4208 	tcphdr_t *tcp;
4209 	udphdr_t *udp;
4210 
4211 	csump = NULL;
4212 	if (fin->fin_out == 0) {
4213 		fin->fin_rev = (nat->nat_dir == NAT_OUTBOUND);
4214 	} else {
4215 		fin->fin_rev = (nat->nat_dir == NAT_INBOUND);
4216 	}
4217 
4218 	switch (fin->fin_p)
4219 	{
4220 	case IPPROTO_TCP :
4221 		tcp = fin->fin_dp;
4222 
4223 		csump = &tcp->th_sum;
4224 
4225 		/*
4226 		 * Do a MSS CLAMPING on a SYN packet,
4227 		 * only deal IPv4 for now.
4228 		 */
4229 		if ((nat->nat_mssclamp != 0) && (tcp->th_flags & TH_SYN) != 0)
4230 			nat_mssclamp(tcp, nat->nat_mssclamp, csump);
4231 
4232 		break;
4233 
4234 	case IPPROTO_UDP :
4235 		udp = fin->fin_dp;
4236 
4237 		if (udp->uh_sum)
4238 			csump = &udp->uh_sum;
4239 		break;
4240 
4241 	case IPPROTO_ICMP :
4242 		icmp = fin->fin_dp;
4243 
4244 		if ((nflags & IPN_ICMPQUERY) != 0) {
4245 			if (icmp->icmp_cksum != 0)
4246 				csump = &icmp->icmp_cksum;
4247 		}
4248 		break;
4249 	}
4250 	return csump;
4251 }
4252 
4253 
4254 /* ------------------------------------------------------------------------ */
4255 /* Function:    fr_natunload                                                */
4256 /* Returns:     Nil                                                         */
4257 /* Parameters:  Nil                                                         */
4258 /*                                                                          */
4259 /* Free all memory used by NAT structures allocated at runtime.             */
4260 /* ------------------------------------------------------------------------ */
4261 void fr_natunload(ifs)
4262 ipf_stack_t *ifs;
4263 {
4264 	ipftq_t *ifq, *ifqnext;
4265 
4266 	(void) nat_clearlist(ifs);
4267 	(void) nat_flushtable(ifs);
4268 
4269 	/*
4270 	 * Proxy timeout queues are not cleaned here because although they
4271 	 * exist on the NAT list, appr_unload is called after fr_natunload
4272 	 * and the proxies actually are responsible for them being created.
4273 	 * Should the proxy timeouts have their own list?  There's no real
4274 	 * justification as this is the only complication.
4275 	 */
4276 	for (ifq = ifs->ifs_nat_utqe; ifq != NULL; ifq = ifqnext) {
4277 		ifqnext = ifq->ifq_next;
4278 		if (((ifq->ifq_flags & IFQF_PROXY) == 0) &&
4279 		    (fr_deletetimeoutqueue(ifq) == 0))
4280 			fr_freetimeoutqueue(ifq, ifs);
4281 	}
4282 
4283 	if (ifs->ifs_nat_table[0] != NULL) {
4284 		KFREES(ifs->ifs_nat_table[0],
4285 		       sizeof(nat_t *) * ifs->ifs_ipf_nattable_sz);
4286 		ifs->ifs_nat_table[0] = NULL;
4287 	}
4288 	if (ifs->ifs_nat_table[1] != NULL) {
4289 		KFREES(ifs->ifs_nat_table[1],
4290 		       sizeof(nat_t *) * ifs->ifs_ipf_nattable_sz);
4291 		ifs->ifs_nat_table[1] = NULL;
4292 	}
4293 	if (ifs->ifs_nat_rules != NULL) {
4294 		KFREES(ifs->ifs_nat_rules,
4295 		       sizeof(ipnat_t *) * ifs->ifs_ipf_natrules_sz);
4296 		ifs->ifs_nat_rules = NULL;
4297 	}
4298 	if (ifs->ifs_rdr_rules != NULL) {
4299 		KFREES(ifs->ifs_rdr_rules,
4300 		       sizeof(ipnat_t *) * ifs->ifs_ipf_rdrrules_sz);
4301 		ifs->ifs_rdr_rules = NULL;
4302 	}
4303 	if (ifs->ifs_maptable != NULL) {
4304 		KFREES(ifs->ifs_maptable,
4305 		       sizeof(hostmap_t *) * ifs->ifs_ipf_hostmap_sz);
4306 		ifs->ifs_maptable = NULL;
4307 	}
4308 	if (ifs->ifs_nat_stats.ns_bucketlen[0] != NULL) {
4309 		KFREES(ifs->ifs_nat_stats.ns_bucketlen[0],
4310 		       sizeof(u_long *) * ifs->ifs_ipf_nattable_sz);
4311 		ifs->ifs_nat_stats.ns_bucketlen[0] = NULL;
4312 	}
4313 	if (ifs->ifs_nat_stats.ns_bucketlen[1] != NULL) {
4314 		KFREES(ifs->ifs_nat_stats.ns_bucketlen[1],
4315 		       sizeof(u_long *) * ifs->ifs_ipf_nattable_sz);
4316 		ifs->ifs_nat_stats.ns_bucketlen[1] = NULL;
4317 	}
4318 
4319 	if (ifs->ifs_fr_nat_maxbucket_reset == 1)
4320 		ifs->ifs_fr_nat_maxbucket = 0;
4321 
4322 	if (ifs->ifs_fr_nat_init == 1) {
4323 		ifs->ifs_fr_nat_init = 0;
4324 		fr_sttab_destroy(ifs->ifs_nat_tqb);
4325 
4326 		RW_DESTROY(&ifs->ifs_ipf_natfrag);
4327 		RW_DESTROY(&ifs->ifs_ipf_nat);
4328 
4329 		MUTEX_DESTROY(&ifs->ifs_ipf_nat_new);
4330 		MUTEX_DESTROY(&ifs->ifs_ipf_natio);
4331 
4332 		MUTEX_DESTROY(&ifs->ifs_nat_udptq.ifq_lock);
4333 		MUTEX_DESTROY(&ifs->ifs_nat_icmptq.ifq_lock);
4334 		MUTEX_DESTROY(&ifs->ifs_nat_iptq.ifq_lock);
4335 	}
4336 }
4337 
4338 
4339 /* ------------------------------------------------------------------------ */
4340 /* Function:    fr_natexpire                                                */
4341 /* Returns:     Nil                                                         */
4342 /* Parameters:  Nil                                                         */
4343 /*                                                                          */
4344 /* Check all of the timeout queues for entries at the top which need to be  */
4345 /* expired.                                                                 */
4346 /* ------------------------------------------------------------------------ */
4347 void fr_natexpire(ifs)
4348 ipf_stack_t *ifs;
4349 {
4350 	ipftq_t *ifq, *ifqnext;
4351 	ipftqent_t *tqe, *tqn;
4352 	int i;
4353 	SPL_INT(s);
4354 
4355 	SPL_NET(s);
4356 	WRITE_ENTER(&ifs->ifs_ipf_nat);
4357 	for (ifq = ifs->ifs_nat_tqb, i = 0; ifq != NULL; ifq = ifq->ifq_next) {
4358 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
4359 			if (tqe->tqe_die > ifs->ifs_fr_ticks)
4360 				break;
4361 			tqn = tqe->tqe_next;
4362 			nat_delete(tqe->tqe_parent, NL_EXPIRE, ifs);
4363 		}
4364 	}
4365 
4366 	for (ifq = ifs->ifs_nat_utqe; ifq != NULL; ifq = ifqnext) {
4367 		ifqnext = ifq->ifq_next;
4368 
4369 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
4370 			if (tqe->tqe_die > ifs->ifs_fr_ticks)
4371 				break;
4372 			tqn = tqe->tqe_next;
4373 			nat_delete(tqe->tqe_parent, NL_EXPIRE, ifs);
4374 		}
4375 	}
4376 
4377 	for (ifq = ifs->ifs_nat_utqe; ifq != NULL; ifq = ifqnext) {
4378 		ifqnext = ifq->ifq_next;
4379 
4380 		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
4381 		    (ifq->ifq_ref == 0)) {
4382 			fr_freetimeoutqueue(ifq, ifs);
4383 		}
4384 	}
4385 
4386 	if (ifs->ifs_nat_doflush != 0) {
4387 		(void) nat_extraflush(2, ifs);
4388 		ifs->ifs_nat_doflush = 0;
4389 	}
4390 
4391 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
4392 	SPL_X(s);
4393 }
4394 
4395 
4396 /* ------------------------------------------------------------------------ */
4397 /* Function:    fr_nataddrsync                                              */
4398 /* Returns:     Nil                                                         */
4399 /* Parameters:  ifp(I) -  pointer to network interface                      */
4400 /*              addr(I) - pointer to new network address                    */
4401 /*                                                                          */
4402 /* Walk through all of the currently active NAT sessions, looking for those */
4403 /* which need to have their translated address updated (where the interface */
4404 /* matches the one passed in) and change it, recalculating the checksum sum */
4405 /* difference too.                                                          */
4406 /* ------------------------------------------------------------------------ */
4407 void fr_nataddrsync(ifp, addr, ifs)
4408 void *ifp;
4409 struct in_addr *addr;
4410 ipf_stack_t *ifs;
4411 {
4412 	u_32_t sum1, sum2, sumd;
4413 	nat_t *nat;
4414 	ipnat_t *np;
4415 	SPL_INT(s);
4416 
4417 	if (ifs->ifs_fr_running <= 0)
4418 		return;
4419 
4420 	SPL_NET(s);
4421 	WRITE_ENTER(&ifs->ifs_ipf_nat);
4422 
4423 	if (ifs->ifs_fr_running <= 0) {
4424 		RWLOCK_EXIT(&ifs->ifs_ipf_nat);
4425 		return;
4426 	}
4427 
4428 	/*
4429 	 * Change IP addresses for NAT sessions for any protocol except TCP
4430 	 * since it will break the TCP connection anyway.  The only rules
4431 	 * which will get changed are those which are "map ... -> 0/32",
4432 	 * where the rule specifies the address is taken from the interface.
4433 	 */
4434 	for (nat = ifs->ifs_nat_instances; nat; nat = nat->nat_next) {
4435 		if (addr != NULL) {
4436 			if (((ifp != NULL) && ifp != (nat->nat_ifps[0])) ||
4437 			    ((nat->nat_flags & IPN_TCP) != 0))
4438 				continue;
4439 			if (((np = nat->nat_ptr) == NULL) ||
4440 			    (np->in_nip || (np->in_outmsk != 0xffffffff)))
4441 				continue;
4442 
4443 			/*
4444 			 * Change the map-to address to be the same as the
4445 			 * new one.
4446 			 */
4447 			sum1 = nat->nat_outip.s_addr;
4448 			nat->nat_outip = *addr;
4449 			sum2 = nat->nat_outip.s_addr;
4450 
4451 		} else if (((ifp == NULL) || (ifp == nat->nat_ifps[0])) &&
4452 		    !(nat->nat_flags & IPN_TCP) && (np = nat->nat_ptr) &&
4453 		    (np->in_outmsk == 0xffffffff) && !np->in_nip) {
4454 			struct in_addr in;
4455 
4456 			/*
4457 			 * Change the map-to address to be the same as the
4458 			 * new one.
4459 			 */
4460 			sum1 = nat->nat_outip.s_addr;
4461 			if (fr_ifpaddr(4, FRI_NORMAL, nat->nat_ifps[0],
4462 				       &in, NULL, ifs) != -1)
4463 				nat->nat_outip = in;
4464 			sum2 = nat->nat_outip.s_addr;
4465 		} else {
4466 			continue;
4467 		}
4468 
4469 		if (sum1 == sum2)
4470 			continue;
4471 		/*
4472 		 * Readjust the checksum adjustment to take into
4473 		 * account the new IP#.
4474 		 */
4475 		CALC_SUMD(sum1, sum2, sumd);
4476 		/* XXX - dont change for TCP when solaris does
4477 		 * hardware checksumming.
4478 		 */
4479 		sumd += nat->nat_sumd[0];
4480 		nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
4481 		nat->nat_sumd[1] = nat->nat_sumd[0];
4482 	}
4483 
4484 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
4485 	SPL_X(s);
4486 }
4487 
4488 
4489 /* ------------------------------------------------------------------------ */
4490 /* Function:    fr_natifpsync                                               */
4491 /* Returns:     Nil                                                         */
4492 /* Parameters:  action(I) - how we are syncing                              */
4493 /*              ifp(I)    - pointer to network interface                    */
4494 /*              name(I)   - name of interface to sync to                    */
4495 /*                                                                          */
4496 /* This function is used to resync the mapping of interface names and their */
4497 /* respective 'pointers'.  For "action == IPFSYNC_RESYNC", resync all       */
4498 /* interfaces by doing a new lookup of name to 'pointer'.  For "action ==   */
4499 /* IPFSYNC_NEWIFP", treat ifp as the new pointer value associated with      */
4500 /* "name" and for "action == IPFSYNC_OLDIFP", ifp is a pointer for which    */
4501 /* there is no longer any interface associated with it.                     */
4502 /* ------------------------------------------------------------------------ */
4503 void fr_natifpsync(action, ifp, name, ifs)
4504 int action;
4505 void *ifp;
4506 char *name;
4507 ipf_stack_t *ifs;
4508 {
4509 #if defined(_KERNEL) && !defined(MENTAT) && defined(USE_SPL)
4510 	int s;
4511 #endif
4512 	nat_t *nat;
4513 	ipnat_t *n;
4514 
4515 	if (ifs->ifs_fr_running <= 0)
4516 		return;
4517 
4518 	SPL_NET(s);
4519 	WRITE_ENTER(&ifs->ifs_ipf_nat);
4520 
4521 	if (ifs->ifs_fr_running <= 0) {
4522 		RWLOCK_EXIT(&ifs->ifs_ipf_nat);
4523 		return;
4524 	}
4525 
4526 	switch (action)
4527 	{
4528 	case IPFSYNC_RESYNC :
4529 		for (nat = ifs->ifs_nat_instances; nat; nat = nat->nat_next) {
4530 			if ((ifp == nat->nat_ifps[0]) ||
4531 			    (nat->nat_ifps[0] == (void *)-1)) {
4532 				nat->nat_ifps[0] =
4533 				    fr_resolvenic(nat->nat_ifnames[0], 4, ifs);
4534 			}
4535 
4536 			if ((ifp == nat->nat_ifps[1]) ||
4537 			    (nat->nat_ifps[1] == (void *)-1)) {
4538 				nat->nat_ifps[1] =
4539 				    fr_resolvenic(nat->nat_ifnames[1], 4, ifs);
4540 			}
4541 		}
4542 
4543 		for (n = ifs->ifs_nat_list; (n != NULL); n = n->in_next) {
4544 			if (n->in_ifps[0] == ifp ||
4545 			    n->in_ifps[0] == (void *)-1) {
4546 				n->in_ifps[0] =
4547 				    fr_resolvenic(n->in_ifnames[0], 4, ifs);
4548 			}
4549 			if (n->in_ifps[1] == ifp ||
4550 			    n->in_ifps[1] == (void *)-1) {
4551 				n->in_ifps[1] =
4552 				    fr_resolvenic(n->in_ifnames[1], 4, ifs);
4553 			}
4554 		}
4555 		break;
4556 	case IPFSYNC_NEWIFP :
4557 		for (nat = ifs->ifs_nat_instances; nat; nat = nat->nat_next) {
4558 			if (!strncmp(name, nat->nat_ifnames[0],
4559 				     sizeof(nat->nat_ifnames[0])))
4560 				nat->nat_ifps[0] = ifp;
4561 			if (!strncmp(name, nat->nat_ifnames[1],
4562 				     sizeof(nat->nat_ifnames[1])))
4563 				nat->nat_ifps[1] = ifp;
4564 		}
4565 		for (n = ifs->ifs_nat_list; (n != NULL); n = n->in_next) {
4566 			if (!strncmp(name, n->in_ifnames[0],
4567 				     sizeof(n->in_ifnames[0])))
4568 				n->in_ifps[0] = ifp;
4569 			if (!strncmp(name, n->in_ifnames[1],
4570 				     sizeof(n->in_ifnames[1])))
4571 				n->in_ifps[1] = ifp;
4572 		}
4573 		break;
4574 	case IPFSYNC_OLDIFP :
4575 		for (nat = ifs->ifs_nat_instances; nat; nat = nat->nat_next) {
4576 			if (ifp == nat->nat_ifps[0])
4577 				nat->nat_ifps[0] = (void *)-1;
4578 			if (ifp == nat->nat_ifps[1])
4579 				nat->nat_ifps[1] = (void *)-1;
4580 		}
4581 		for (n = ifs->ifs_nat_list; (n != NULL); n = n->in_next) {
4582 			if (n->in_ifps[0] == ifp)
4583 				n->in_ifps[0] = (void *)-1;
4584 			if (n->in_ifps[1] == ifp)
4585 				n->in_ifps[1] = (void *)-1;
4586 		}
4587 		break;
4588 	}
4589 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
4590 	SPL_X(s);
4591 }
4592 
4593 
4594 /* ------------------------------------------------------------------------ */
4595 /* Function:    nat_icmpquerytype4                                          */
4596 /* Returns:     int - 1 == success, 0 == failure                            */
4597 /* Parameters:  icmptype(I) - ICMP type number                              */
4598 /*                                                                          */
4599 /* Tests to see if the ICMP type number passed is a query/response type or  */
4600 /* not.                                                                     */
4601 /* ------------------------------------------------------------------------ */
4602 static INLINE int nat_icmpquerytype4(icmptype)
4603 int icmptype;
4604 {
4605 
4606 	/*
4607 	 * For the ICMP query NAT code, it is essential that both the query
4608 	 * and the reply match on the NAT rule. Because the NAT structure
4609 	 * does not keep track of the icmptype, and a single NAT structure
4610 	 * is used for all icmp types with the same src, dest and id, we
4611 	 * simply define the replies as queries as well. The funny thing is,
4612 	 * altough it seems silly to call a reply a query, this is exactly
4613 	 * as it is defined in the IPv4 specification
4614 	 */
4615 
4616 	switch (icmptype)
4617 	{
4618 
4619 	case ICMP_ECHOREPLY:
4620 	case ICMP_ECHO:
4621 	/* route aedvertisement/solliciation is currently unsupported: */
4622 	/* it would require rewriting the ICMP data section            */
4623 	case ICMP_TSTAMP:
4624 	case ICMP_TSTAMPREPLY:
4625 	case ICMP_IREQ:
4626 	case ICMP_IREQREPLY:
4627 	case ICMP_MASKREQ:
4628 	case ICMP_MASKREPLY:
4629 		return 1;
4630 	default:
4631 		return 0;
4632 	}
4633 }
4634 
4635 
4636 /* ------------------------------------------------------------------------ */
4637 /* Function:    nat_log                                                     */
4638 /* Returns:     Nil                                                         */
4639 /* Parameters:  nat(I)  - pointer to NAT structure                          */
4640 /*              type(I) - type of log entry to create                       */
4641 /*                                                                          */
4642 /* Creates a NAT log entry.                                                 */
4643 /* ------------------------------------------------------------------------ */
4644 void nat_log(nat, type, ifs)
4645 struct nat *nat;
4646 u_int type;
4647 ipf_stack_t *ifs;
4648 {
4649 #ifdef	IPFILTER_LOG
4650 # ifndef LARGE_NAT
4651 	struct ipnat *np;
4652 	int rulen;
4653 # endif
4654 	struct natlog natl;
4655 	void *items[1];
4656 	size_t sizes[1];
4657 	int types[1];
4658 
4659 	natl.nl_inip = nat->nat_inip;
4660 	natl.nl_outip = nat->nat_outip;
4661 	natl.nl_origip = nat->nat_oip;
4662 	natl.nl_bytes[0] = nat->nat_bytes[0];
4663 	natl.nl_bytes[1] = nat->nat_bytes[1];
4664 	natl.nl_pkts[0] = nat->nat_pkts[0];
4665 	natl.nl_pkts[1] = nat->nat_pkts[1];
4666 	natl.nl_origport = nat->nat_oport;
4667 	natl.nl_inport = nat->nat_inport;
4668 	natl.nl_outport = nat->nat_outport;
4669 	natl.nl_p = nat->nat_p;
4670 	natl.nl_type = type;
4671 	natl.nl_rule = -1;
4672 # ifndef LARGE_NAT
4673 	if (nat->nat_ptr != NULL) {
4674 		for (rulen = 0, np = ifs->ifs_nat_list; np;
4675 		     np = np->in_next, rulen++)
4676 			if (np == nat->nat_ptr) {
4677 				natl.nl_rule = rulen;
4678 				break;
4679 			}
4680 	}
4681 # endif
4682 	items[0] = &natl;
4683 	sizes[0] = sizeof(natl);
4684 	types[0] = 0;
4685 
4686 	(void) ipllog(IPL_LOGNAT, NULL, items, sizes, types, 1, ifs);
4687 #endif
4688 }
4689 
4690 
4691 #if defined(__OpenBSD__)
4692 /* ------------------------------------------------------------------------ */
4693 /* Function:    nat_ifdetach                                                */
4694 /* Returns:     Nil                                                         */
4695 /* Parameters:  ifp(I) - pointer to network interface                       */
4696 /*                                                                          */
4697 /* Compatibility interface for OpenBSD to trigger the correct updating of   */
4698 /* interface references within IPFilter.                                    */
4699 /* ------------------------------------------------------------------------ */
4700 void nat_ifdetach(ifp, ifs)
4701 void *ifp;
4702 ipf_stack_t *ifs;
4703 {
4704 	frsync(ifp, ifs);
4705 	return;
4706 }
4707 #endif
4708 
4709 
4710 /* ------------------------------------------------------------------------ */
4711 /* Function:    fr_ipnatderef                                               */
4712 /* Returns:     Nil                                                         */
4713 /* Parameters:  isp(I) - pointer to pointer to NAT rule                     */
4714 /* Write Locks: ipf_nat                                                     */
4715 /*                                                                          */
4716 /* ------------------------------------------------------------------------ */
4717 void fr_ipnatderef(inp, ifs)
4718 ipnat_t **inp;
4719 ipf_stack_t *ifs;
4720 {
4721 	ipnat_t *in;
4722 
4723 	in = *inp;
4724 	*inp = NULL;
4725 	in->in_space++;
4726 	in->in_use--;
4727 	if (in->in_use == 0 && (in->in_flags & IPN_DELETE)) {
4728 		if (in->in_apr)
4729 			appr_free(in->in_apr);
4730 		KFREE(in);
4731 		ifs->ifs_nat_stats.ns_rules--;
4732 #ifdef notdef
4733 #if SOLARIS
4734 		if (ifs->ifs_nat_stats.ns_rules == 0)
4735 			ifs->ifs_pfil_delayed_copy = 1;
4736 #endif
4737 #endif
4738 	}
4739 }
4740 
4741 
4742 /* ------------------------------------------------------------------------ */
4743 /* Function:    fr_natderef                                                 */
4744 /* Returns:     Nil                                                         */
4745 /* Parameters:  isp(I) - pointer to pointer to NAT table entry              */
4746 /*                                                                          */
4747 /* Decrement the reference counter for this NAT table entry and free it if  */
4748 /* there are no more things using it.                                       */
4749 /* ------------------------------------------------------------------------ */
4750 void fr_natderef(natp, ifs)
4751 nat_t **natp;
4752 ipf_stack_t *ifs;
4753 {
4754 	nat_t *nat;
4755 
4756 	nat = *natp;
4757 	*natp = NULL;
4758 	WRITE_ENTER(&ifs->ifs_ipf_nat);
4759 	nat->nat_ref--;
4760 	if (nat->nat_ref == 0)
4761 	    nat_delete(nat, NL_EXPIRE, ifs);
4762 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
4763 }
4764 
4765 
4766 /* ------------------------------------------------------------------------ */
4767 /* Function:    fr_natclone                                                 */
4768 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
4769 /*                           else pointer to new state structure            */
4770 /* Parameters:  fin(I) - pointer to packet information                      */
4771 /*              is(I)  - pointer to master state structure                  */
4772 /* Write Lock:  ipf_nat                                                     */
4773 /*                                                                          */
4774 /* Create a "duplcate" state table entry from the master.                   */
4775 /* ------------------------------------------------------------------------ */
4776 static nat_t *fr_natclone(fin, nat)
4777 fr_info_t *fin;
4778 nat_t *nat;
4779 {
4780 	frentry_t *fr;
4781 	nat_t *clone;
4782 	ipnat_t *np;
4783 	ipf_stack_t *ifs = fin->fin_ifs;
4784 
4785 	KMALLOC(clone, nat_t *);
4786 	if (clone == NULL)
4787 		return NULL;
4788 	bcopy((char *)nat, (char *)clone, sizeof(*clone));
4789 
4790 	MUTEX_NUKE(&clone->nat_lock);
4791 
4792 	clone->nat_aps = NULL;
4793 	/*
4794 	 * Initialize all these so that nat_delete() doesn't cause a crash.
4795 	 */
4796 	clone->nat_tqe.tqe_pnext = NULL;
4797 	clone->nat_tqe.tqe_next = NULL;
4798 	clone->nat_tqe.tqe_ifq = NULL;
4799 	clone->nat_tqe.tqe_parent = clone;
4800 
4801 	clone->nat_flags &= ~SI_CLONE;
4802 	clone->nat_flags |= SI_CLONED;
4803 
4804 	if (clone->nat_hm)
4805 		clone->nat_hm->hm_ref++;
4806 
4807 	if (nat_insert(clone, fin->fin_rev, ifs) == -1) {
4808 		KFREE(clone);
4809 		return NULL;
4810 	}
4811 	np = clone->nat_ptr;
4812 	if (np != NULL) {
4813 		if (ifs->ifs_nat_logging)
4814 			nat_log(clone, (u_int)np->in_redir, ifs);
4815 		np->in_use++;
4816 	}
4817 	fr = clone->nat_fr;
4818 	if (fr != NULL) {
4819 		MUTEX_ENTER(&fr->fr_lock);
4820 		fr->fr_ref++;
4821 		MUTEX_EXIT(&fr->fr_lock);
4822 	}
4823 
4824 	/*
4825 	 * Because the clone is created outside the normal loop of things and
4826 	 * TCP has special needs in terms of state, initialise the timeout
4827 	 * state of the new NAT from here.
4828 	 */
4829 	if (clone->nat_p == IPPROTO_TCP) {
4830 		(void) fr_tcp_age(&clone->nat_tqe, fin, ifs->ifs_nat_tqb,
4831 				  clone->nat_flags);
4832 	}
4833 #ifdef	IPFILTER_SYNC
4834 	clone->nat_sync = ipfsync_new(SMC_NAT, fin, clone);
4835 #endif
4836 	if (ifs->ifs_nat_logging)
4837 		nat_log(clone, NL_CLONE, ifs);
4838 	return clone;
4839 }
4840 
4841 
4842 /* ------------------------------------------------------------------------ */
4843 /* Function:   nat_wildok                                                   */
4844 /* Returns:    int - 1 == packet's ports match wildcards                    */
4845 /*                   0 == packet's ports don't match wildcards              */
4846 /* Parameters: nat(I)   - NAT entry                                         */
4847 /*             sport(I) - source port                                       */
4848 /*             dport(I) - destination port                                  */
4849 /*             flags(I) - wildcard flags                                    */
4850 /*             dir(I)   - packet direction                                  */
4851 /*                                                                          */
4852 /* Use NAT entry and packet direction to determine which combination of     */
4853 /* wildcard flags should be used.                                           */
4854 /* ------------------------------------------------------------------------ */
4855 static INLINE int nat_wildok(nat, sport, dport, flags, dir)
4856 nat_t *nat;
4857 int sport;
4858 int dport;
4859 int flags;
4860 int dir;
4861 {
4862 	/*
4863 	 * When called by       dir is set to
4864 	 * nat_inlookup         NAT_INBOUND (0)
4865 	 * nat_outlookup        NAT_OUTBOUND (1)
4866 	 *
4867 	 * We simply combine the packet's direction in dir with the original
4868 	 * "intended" direction of that NAT entry in nat->nat_dir to decide
4869 	 * which combination of wildcard flags to allow.
4870 	 */
4871 
4872 	switch ((dir << 1) | nat->nat_dir)
4873 	{
4874 	case 3: /* outbound packet / outbound entry */
4875 		if (((nat->nat_inport == sport) ||
4876 		    (flags & SI_W_SPORT)) &&
4877 		    ((nat->nat_oport == dport) ||
4878 		    (flags & SI_W_DPORT)))
4879 			return 1;
4880 		break;
4881 	case 2: /* outbound packet / inbound entry */
4882 		if (((nat->nat_outport == sport) ||
4883 		    (flags & SI_W_DPORT)) &&
4884 		    ((nat->nat_oport == dport) ||
4885 		    (flags & SI_W_SPORT)))
4886 			return 1;
4887 		break;
4888 	case 1: /* inbound packet / outbound entry */
4889 		if (((nat->nat_oport == sport) ||
4890 		    (flags & SI_W_DPORT)) &&
4891 		    ((nat->nat_outport == dport) ||
4892 		    (flags & SI_W_SPORT)))
4893 			return 1;
4894 		break;
4895 	case 0: /* inbound packet / inbound entry */
4896 		if (((nat->nat_oport == sport) ||
4897 		    (flags & SI_W_SPORT)) &&
4898 		    ((nat->nat_outport == dport) ||
4899 		    (flags & SI_W_DPORT)))
4900 			return 1;
4901 		break;
4902 	default:
4903 		break;
4904 	}
4905 
4906 	return(0);
4907 }
4908 
4909 
4910 /* ------------------------------------------------------------------------ */
4911 /* Function:    nat_mssclamp                                                */
4912 /* Returns:     Nil                                                         */
4913 /* Parameters:  tcp(I)    - pointer to TCP header                           */
4914 /*              maxmss(I) - value to clamp the TCP MSS to                   */
4915 /*              csump(I)  - pointer to TCP checksum                         */
4916 /*                                                                          */
4917 /* Check for MSS option and clamp it if necessary.  If found and changed,   */
4918 /* then the TCP header checksum will be updated to reflect the change in    */
4919 /* the MSS.                                                                 */
4920 /* ------------------------------------------------------------------------ */
4921 static void nat_mssclamp(tcp, maxmss, csump)
4922 tcphdr_t *tcp;
4923 u_32_t maxmss;
4924 u_short *csump;
4925 {
4926 	u_char *cp, *ep, opt;
4927 	int hlen, advance;
4928 	u_32_t mss, sumd;
4929 
4930 	hlen = TCP_OFF(tcp) << 2;
4931 	if (hlen > sizeof(*tcp)) {
4932 		cp = (u_char *)tcp + sizeof(*tcp);
4933 		ep = (u_char *)tcp + hlen;
4934 
4935 		while (cp < ep) {
4936 			opt = cp[0];
4937 			if (opt == TCPOPT_EOL)
4938 				break;
4939 			else if (opt == TCPOPT_NOP) {
4940 				cp++;
4941 				continue;
4942 			}
4943 
4944 			if (cp + 1 >= ep)
4945 				break;
4946 			advance = cp[1];
4947 			if ((cp + advance > ep) || (advance <= 0))
4948 				break;
4949 			switch (opt)
4950 			{
4951 			case TCPOPT_MAXSEG:
4952 				if (advance != 4)
4953 					break;
4954 				mss = cp[2] * 256 + cp[3];
4955 				if (mss > maxmss) {
4956 					cp[2] = maxmss / 256;
4957 					cp[3] = maxmss & 0xff;
4958 					CALC_SUMD(mss, maxmss, sumd);
4959 					fix_outcksum(csump, sumd);
4960 				}
4961 				break;
4962 			default:
4963 				/* ignore unknown options */
4964 				break;
4965 			}
4966 
4967 			cp += advance;
4968 		}
4969 	}
4970 }
4971 
4972 
4973 /* ------------------------------------------------------------------------ */
4974 /* Function:    fr_setnatqueue                                              */
4975 /* Returns:     Nil                                                         */
4976 /* Parameters:  nat(I)- pointer to NAT structure                            */
4977 /*              rev(I) - forward(0) or reverse(1) direction                 */
4978 /* Locks:       ipf_nat (read or write)                                     */
4979 /*                                                                          */
4980 /* Put the NAT entry on its default queue entry, using rev as a helped in   */
4981 /* determining which queue it should be placed on.                          */
4982 /* ------------------------------------------------------------------------ */
4983 void fr_setnatqueue(nat, rev, ifs)
4984 nat_t *nat;
4985 int rev;
4986 ipf_stack_t *ifs;
4987 {
4988 	ipftq_t *oifq, *nifq;
4989 
4990 	if (nat->nat_ptr != NULL)
4991 		nifq = nat->nat_ptr->in_tqehead[rev];
4992 	else
4993 		nifq = NULL;
4994 
4995 	if (nifq == NULL) {
4996 		switch (nat->nat_p)
4997 		{
4998 		case IPPROTO_UDP :
4999 			nifq = &ifs->ifs_nat_udptq;
5000 			break;
5001 		case IPPROTO_ICMP :
5002 			nifq = &ifs->ifs_nat_icmptq;
5003 			break;
5004 		case IPPROTO_TCP :
5005 			nifq = ifs->ifs_nat_tqb + nat->nat_tqe.tqe_state[rev];
5006 			break;
5007 		default :
5008 			nifq = &ifs->ifs_nat_iptq;
5009 			break;
5010 		}
5011 	}
5012 
5013 	oifq = nat->nat_tqe.tqe_ifq;
5014 	/*
5015 	 * If it's currently on a timeout queue, move it from one queue to
5016 	 * another, else put it on the end of the newly determined queue.
5017 	 */
5018 	if (oifq != NULL)
5019 		fr_movequeue(&nat->nat_tqe, oifq, nifq, ifs);
5020 	else
5021 		fr_queueappend(&nat->nat_tqe, nifq, nat, ifs);
5022 	return;
5023 }
5024 
5025 /* Function:    nat_getnext                                                 */
5026 /* Returns:     int - 0 == ok, else error                                   */
5027 /* Parameters:  t(I)   - pointer to ipftoken structure                      */
5028 /*              itp(I) - pointer to ipfgeniter_t structure                  */
5029 /*                                                                          */
5030 /* Fetch the next nat/ipnat structure pointer from the linked list and      */
5031 /* copy it out to the storage space pointed to by itp_data.  The next item  */
5032 /* in the list to look at is put back in the ipftoken struture.             */
5033 /* If we call ipf_freetoken, the accompanying pointer is set to NULL because*/
5034 /* ipf_freetoken will call a deref function for us and we dont want to call */
5035 /* that twice (second time would be in the second switch statement below.   */
5036 /* ------------------------------------------------------------------------ */
5037 static int nat_getnext(t, itp, ifs)
5038 ipftoken_t *t;
5039 ipfgeniter_t *itp;
5040 ipf_stack_t *ifs;
5041 {
5042 	hostmap_t *hm, *nexthm = NULL, zerohm;
5043 	ipnat_t *ipn, *nextipnat = NULL, zeroipn;
5044 	nat_t *nat, *nextnat = NULL, zeronat;
5045 	int error = 0;
5046 
5047 	READ_ENTER(&ifs->ifs_ipf_nat);
5048 	switch (itp->igi_type)
5049 	{
5050 	case IPFGENITER_HOSTMAP :
5051 		hm = t->ipt_data;
5052 		if (hm == NULL) {
5053 			nexthm = ifs->ifs_ipf_hm_maplist;
5054 		} else {
5055 			nexthm = hm->hm_hnext;
5056 		}
5057 		if (nexthm != NULL) {
5058 			if (nexthm->hm_hnext == NULL) {
5059 				t->ipt_alive = 0;
5060 				ipf_unlinktoken(t, ifs);
5061 				KFREE(t);
5062 			} else {
5063 				/*MUTEX_ENTER(&nexthm->hm_lock);*/
5064 				nexthm->hm_ref++;
5065 				/*MUTEX_EXIT(&nextipnat->hm_lock);*/
5066 			}
5067 
5068 		} else {
5069 			bzero(&zerohm, sizeof(zerohm));
5070 			nexthm = &zerohm;
5071 			ipf_freetoken(t, ifs);
5072 		}
5073 		break;
5074 
5075 	case IPFGENITER_IPNAT :
5076 		ipn = t->ipt_data;
5077 		if (ipn == NULL) {
5078 			nextipnat = ifs->ifs_nat_list;
5079 		} else {
5080 			nextipnat = ipn->in_next;
5081 		}
5082 		if (nextipnat != NULL) {
5083 			if (nextipnat->in_next == NULL) {
5084 				t->ipt_alive = 0;
5085 				ipf_unlinktoken(t, ifs);
5086 				KFREE(t);
5087 			} else {
5088 				/* MUTEX_ENTER(&nextipnat->in_lock); */
5089 				nextipnat->in_use++;
5090 				/* MUTEX_EXIT(&nextipnat->in_lock); */
5091 			}
5092 		} else {
5093 			bzero(&zeroipn, sizeof(zeroipn));
5094 			nextipnat = &zeroipn;
5095 			ipf_freetoken(t, ifs);
5096 		}
5097 		break;
5098 
5099 	case IPFGENITER_NAT :
5100 		nat = t->ipt_data;
5101 		if (nat == NULL) {
5102 			nextnat = ifs->ifs_nat_instances;
5103 		} else {
5104 			nextnat = nat->nat_next;
5105 		}
5106 		if (nextnat != NULL) {
5107 			if (nextnat->nat_next == NULL) {
5108 				t->ipt_alive = 0;
5109 				ipf_unlinktoken(t, ifs);
5110 				KFREE(t);
5111 			} else {
5112 				MUTEX_ENTER(&nextnat->nat_lock);
5113 				nextnat->nat_ref++;
5114 				MUTEX_EXIT(&nextnat->nat_lock);
5115 			}
5116 		} else {
5117 			bzero(&zeronat, sizeof(zeronat));
5118 			nextnat = &zeronat;
5119 			ipf_freetoken(t, ifs);
5120 		}
5121 		break;
5122 	}
5123 
5124 	RWLOCK_EXIT(&ifs->ifs_ipf_nat);
5125 
5126 	switch (itp->igi_type)
5127 	{
5128 	case IPFGENITER_HOSTMAP :
5129 		if (hm != NULL) {
5130 			WRITE_ENTER(&ifs->ifs_ipf_nat);
5131 			fr_hostmapderef(&hm);
5132 			RWLOCK_EXIT(&ifs->ifs_ipf_nat);
5133 		}
5134 		if (nexthm->hm_hnext != NULL)
5135 			t->ipt_data = nexthm;
5136 		error = COPYOUT(nexthm, itp->igi_data, sizeof(*nexthm));
5137 		if (error != 0)
5138 			error = EFAULT;
5139 		break;
5140 
5141 	case IPFGENITER_IPNAT :
5142 		if (ipn != NULL)
5143 			fr_ipnatderef(&ipn, ifs);
5144 		if (nextipnat->in_next != NULL)
5145 			t->ipt_data = nextipnat;
5146 		error = COPYOUT(nextipnat, itp->igi_data, sizeof(*nextipnat));
5147 		if (error != 0)
5148 			error = EFAULT;
5149 		break;
5150 
5151 	case IPFGENITER_NAT :
5152 		if (nat != NULL)
5153 			fr_natderef(&nat, ifs);
5154 		if (nextnat->nat_next != NULL)
5155 			t->ipt_data = nextnat;
5156 		error = COPYOUT(nextnat, itp->igi_data, sizeof(*nextnat));
5157 		if (error != 0)
5158 			error = EFAULT;
5159 		break;
5160 	}
5161 
5162 	return error;
5163 }
5164 
5165 
5166 /* ------------------------------------------------------------------------ */
5167 /* Function:    nat_iterator                                                */
5168 /* Returns:     int - 0 == ok, else error                                   */
5169 /* Parameters:  token(I) - pointer to ipftoken structure                    */
5170 /*              itp(I) - pointer to ipfgeniter_t structure                  */
5171 /*                                                                          */
5172 /* This function acts as a handler for the SIOCGENITER ioctls that use a    */
5173 /* generic structure to iterate through a list.  There are three different  */
5174 /* linked lists of NAT related information to go through: NAT rules, active */
5175 /* NAT mappings and the NAT fragment cache.                                 */
5176 /* ------------------------------------------------------------------------ */
5177 static int nat_iterator(token, itp, ifs)
5178 ipftoken_t *token;
5179 ipfgeniter_t *itp;
5180 ipf_stack_t *ifs;
5181 {
5182 	int error;
5183 
5184 	if (itp->igi_data == NULL)
5185 		return EFAULT;
5186 
5187 	token->ipt_subtype = itp->igi_type;
5188 
5189 	switch (itp->igi_type)
5190 	{
5191 	case IPFGENITER_HOSTMAP :
5192 	case IPFGENITER_IPNAT :
5193 	case IPFGENITER_NAT :
5194 		error = nat_getnext(token, itp, ifs);
5195 		break;
5196 	case IPFGENITER_NATFRAG :
5197 		error = fr_nextfrag(token, itp, &ifs->ifs_ipfr_natlist,
5198 				    &ifs->ifs_ipfr_nattail,
5199 				    &ifs->ifs_ipf_natfrag, ifs);
5200 		break;
5201 	default :
5202 		error = EINVAL;
5203 		break;
5204 	}
5205 
5206 	return error;
5207 }
5208 
5209 
5210 /* -------------------------------------------------------------------- */
5211 /* Function:	nat_earlydrop						*/
5212 /* Returns:	number of dropped/removed entries from the queue	*/
5213 /* Parameters:	ifq - pointer to queue with entries to be processed	*/
5214 /*		maxidle - entry must be idle this long to be dropped	*/
5215 /*		ifs - ipf stack instance				*/
5216 /*									*/
5217 /* Function is invoked from nat_extraflush() only.  Removes entries	*/
5218 /* form specified timeout queue, based on how long they've sat idle,	*/
5219 /* without waiting for it to happen on its own.				*/
5220 /* -------------------------------------------------------------------- */
5221 static int nat_earlydrop(ifq, maxidle, ifs)
5222 ipftq_t *ifq;
5223 int maxidle;
5224 ipf_stack_t *ifs;
5225 {
5226 	ipftqent_t *tqe, *tqn;
5227 	nat_t *nat;
5228 	unsigned int dropped;
5229 	int droptick;
5230 
5231 	if (ifq == NULL)
5232 		return (0);
5233 
5234 	dropped = 0;
5235 
5236 	/*
5237 	 * Determine the tick representing the idle time we're interested
5238 	 * in.  If an entry exists in the queue, and it was touched before
5239 	 * that tick, then it's been idle longer than maxidle ... remove it.
5240 	 */
5241 	droptick = ifs->ifs_fr_ticks - maxidle;
5242 	tqn = ifq->ifq_head;
5243 	while ((tqe = tqn) != NULL && tqe->tqe_touched < droptick) {
5244 		tqn = tqe->tqe_next;
5245 		nat = tqe->tqe_parent;
5246 		nat_delete(nat, ISL_EXPIRE, ifs);
5247 		dropped++;
5248 	}
5249 	return (dropped);
5250 }
5251 
5252 
5253 /* --------------------------------------------------------------------- */
5254 /* Function:	nat_flushclosing					 */
5255 /* Returns:	int - number of NAT entries deleted			 */
5256 /* Parameters:	stateval(I) - State at which to start removing entries	 */
5257 /*		ifs - ipf stack instance				 */
5258 /*									 */
5259 /* Remove nat table entries for TCP connections which are in the process */
5260 /* of closing, and are in (or "beyond") state specified by 'stateval'.	 */
5261 /* --------------------------------------------------------------------- */
5262 static int nat_flushclosing(stateval, ifs)
5263 int stateval;
5264 ipf_stack_t *ifs;
5265 {
5266 	ipftq_t *ifq, *ifqn;
5267 	ipftqent_t *tqe, *tqn;
5268 	nat_t *nat;
5269 	int dropped;
5270 
5271 	dropped = 0;
5272 
5273 	/*
5274 	 * Start by deleting any entries in specific timeout queues.
5275 	 */
5276 	ifqn = &ifs->ifs_nat_tqb[stateval];
5277 	while ((ifq = ifqn) != NULL) {
5278 		ifqn = ifq->ifq_next;
5279 		dropped += nat_earlydrop(ifq, (int)0, ifs);
5280 	}
5281 
5282 	/*
5283 	 * Next, look through user defined queues for closing entries.
5284 	 */
5285 	ifqn = ifs->ifs_nat_utqe;
5286 	while ((ifq = ifqn) != NULL) {
5287 		ifqn = ifq->ifq_next;
5288 		tqn = ifq->ifq_head;
5289 		while ((tqe = tqn) != NULL) {
5290 			tqn = tqe->tqe_next;
5291 			nat = tqe->tqe_parent;
5292 			if (nat->nat_p != IPPROTO_TCP)
5293 				continue;
5294 			if ((nat->nat_tcpstate[0] >= stateval) &&
5295 			    (nat->nat_tcpstate[1] >= stateval)) {
5296 				nat_delete(nat, NL_EXPIRE, ifs);
5297 				dropped++;
5298 			}
5299 		}
5300 	}
5301 	return (dropped);
5302 }
5303 
5304 
5305 /* --------------------------------------------------------------------- */
5306 /* Function:	nat_extraflush						 */
5307 /* Returns:	int - number of NAT entries deleted			 */
5308 /* Parameters:	which(I) - how to flush the active NAT table		 */
5309 /*		ifs - ipf stack instance				 */
5310 /* Write Locks:	ipf_nat							 */
5311 /*									 */
5312 /* Flush nat tables.  Three actions currently defined:			 */
5313 /*									 */
5314 /* which == 0 :	Flush all nat table entries.				 */
5315 /*									 */
5316 /* which == 1 :	Flush entries with TCP connections which have started	 */
5317 /*		to close on both ends.					 */
5318 /*									 */
5319 /* which == 2 :	First, flush entries which are "almost" closed.  If that */
5320 /*		does not take us below specified threshold in the table, */
5321 /*		we want to flush entries with TCP connections which have */
5322 /*		been idle for a long time.  Start with connections idle	 */
5323 /*		over 12 hours,  and then work backwards in half hour	 */
5324 /*		increments to at most 30 minutes idle, and finally work	 */
5325 /*		back in 30 second increments to at most 30 seconds.	 */
5326 /* --------------------------------------------------------------------- */
5327 static int nat_extraflush(which, ifs)
5328 int which;
5329 ipf_stack_t *ifs;
5330 {
5331 	ipftq_t *ifq, *ifqn;
5332 	nat_t *nat, **natp;
5333 	int idletime, removed, idle_idx;
5334 	SPL_INT(s);
5335 
5336 	removed = 0;
5337 
5338 	SPL_NET(s);
5339 	switch (which)
5340 	{
5341 	case 0:
5342 		natp = &ifs->ifs_nat_instances;
5343 		while ((nat = *natp) != NULL) {
5344 			natp = &nat->nat_next;
5345 			nat_delete(nat, ISL_FLUSH, ifs);
5346 			removed++;
5347 		}
5348 		break;
5349 
5350 	case 1:
5351 		removed = nat_flushclosing(IPF_TCPS_CLOSE_WAIT, ifs);
5352 		break;
5353 
5354 	case 2:
5355 		removed = nat_flushclosing(IPF_TCPS_FIN_WAIT_2, ifs);
5356 
5357 		/*
5358 		 * Be sure we haven't done this in the last 10 seconds.
5359 		 */
5360 		if (ifs->ifs_fr_ticks - ifs->ifs_nat_last_force_flush <
5361 		    IPF_TTLVAL(10))
5362 			break;
5363 		ifs->ifs_nat_last_force_flush = ifs->ifs_fr_ticks;
5364 
5365 		/*
5366 		 * Determine initial threshold for minimum idle time based on
5367 		 * how long ipfilter has been running.  Ipfilter needs to have
5368 		 * been up as long as the smallest interval to continue on.
5369 		 *
5370 		 * Minimum idle times stored in idletime_tab and indexed by
5371 		 * idle_idx.  Start at upper end of array and work backwards.
5372 		 *
5373 		 * Once the index is found, set the initial idle time to the
5374 		 * first interval before the current ipfilter run time.
5375 		 */
5376 		if (ifs->ifs_fr_ticks < idletime_tab[0])
5377 			break;  /* switch */
5378 		idle_idx = (sizeof (idletime_tab) / sizeof (int)) - 1;
5379 		if (ifs->ifs_fr_ticks > idletime_tab[idle_idx]) {
5380 			idletime = idletime_tab[idle_idx];
5381 		} else {
5382 			while ((idle_idx > 0) &&
5383 			    (ifs->ifs_fr_ticks < idletime_tab[idle_idx]))
5384 				idle_idx--;
5385 			idletime = (ifs->ifs_fr_ticks /
5386 				    idletime_tab[idle_idx]) *
5387 				    idletime_tab[idle_idx];
5388 		}
5389 
5390 		while ((idle_idx >= 0) &&
5391 		    (NAT_TAB_WATER_LEVEL(ifs) > ifs->ifs_nat_flush_lvl_lo)) {
5392 			/*
5393 			 * Start with appropriate timeout queue.
5394 			 */
5395 			removed += nat_earlydrop(
5396 					&ifs->ifs_nat_tqb[IPF_TCPS_ESTABLISHED],
5397 					idletime, ifs);
5398 
5399 			/*
5400 			 * Make sure we haven't already deleted enough
5401 			 * entries before checking the user defined queues.
5402 			 */
5403 			if (NAT_TAB_WATER_LEVEL(ifs) <=
5404 			    ifs->ifs_nat_flush_lvl_lo)
5405 				break;
5406 
5407 			/*
5408 			 * Next, look through the user defined queues.
5409 			 */
5410 			ifqn = ifs->ifs_nat_utqe;
5411 			while ((ifq = ifqn) != NULL) {
5412 				ifqn = ifq->ifq_next;
5413 				removed += nat_earlydrop(ifq, idletime, ifs);
5414 			}
5415 
5416 			/*
5417 			 * Adjust the granularity of idle time.
5418 			 *
5419 			 * If we reach an interval boundary, we need to
5420 			 * either adjust the idle time accordingly or exit
5421 			 * the loop altogether (if this is very last check).
5422 			 */
5423 			idletime -= idletime_tab[idle_idx];
5424 			if (idletime < idletime_tab[idle_idx]) {
5425 				if (idle_idx != 0) {
5426 					idletime = idletime_tab[idle_idx] -
5427 					    idletime_tab[idle_idx - 1];
5428 					idle_idx--;
5429 				} else {
5430 					break;  /* while */
5431 				}
5432 			}
5433 		}
5434 		break;
5435 	default:
5436 		break;
5437 	}
5438 
5439 	SPL_X(s);
5440 	return (removed);
5441 }
5442