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