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