xref: /freebsd/sys/netpfil/ipfilter/netinet/ip_nat.c (revision 0ff0c19e7f70bc4d3f98196a8ad43de635cf13e5)
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 = 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 	int i;
5811 	SPL_INT(s);
5812 
5813 	SPL_NET(s);
5814 	WRITE_ENTER(&softc->ipf_nat);
5815 	for (ifq = softn->ipf_nat_tcptq, i = 0; ifq != NULL;
5816 	     ifq = ifq->ifq_next) {
5817 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
5818 			if (tqe->tqe_die > softc->ipf_ticks)
5819 				break;
5820 			tqn = tqe->tqe_next;
5821 			ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
5822 		}
5823 	}
5824 
5825 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifq->ifq_next) {
5826 		for (tqn = ifq->ifq_head; ((tqe = tqn) != NULL); i++) {
5827 			if (tqe->tqe_die > softc->ipf_ticks)
5828 				break;
5829 			tqn = tqe->tqe_next;
5830 			ipf_nat_delete(softc, tqe->tqe_parent, NL_EXPIRE);
5831 		}
5832 	}
5833 
5834 	for (ifq = softn->ipf_nat_utqe; ifq != NULL; ifq = ifqnext) {
5835 		ifqnext = ifq->ifq_next;
5836 
5837 		if (((ifq->ifq_flags & IFQF_DELETE) != 0) &&
5838 		    (ifq->ifq_ref == 0)) {
5839 			ipf_freetimeoutqueue(softc, ifq);
5840 		}
5841 	}
5842 
5843 	if (softn->ipf_nat_doflush != 0) {
5844 		ipf_nat_extraflush(softc, softn, 2);
5845 		softn->ipf_nat_doflush = 0;
5846 	}
5847 
5848 	RWLOCK_EXIT(&softc->ipf_nat);
5849 	SPL_X(s);
5850 }
5851 
5852 
5853 /* ------------------------------------------------------------------------ */
5854 /* Function:    ipf_nat_sync                                                */
5855 /* Returns:     Nil                                                         */
5856 /* Parameters:  softc(I) - pointer to soft context main structure           */
5857 /*              ifp(I) - pointer to network interface                       */
5858 /*                                                                          */
5859 /* Walk through all of the currently active NAT sessions, looking for those */
5860 /* which need to have their translated address updated.                     */
5861 /* ------------------------------------------------------------------------ */
5862 void
ipf_nat_sync(ipf_main_softc_t * softc,void * ifp)5863 ipf_nat_sync(ipf_main_softc_t *softc, void *ifp)
5864 {
5865 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
5866 	u_32_t sum1, sum2, sumd;
5867 	i6addr_t in;
5868 	ipnat_t *n;
5869 	nat_t *nat;
5870 	void *ifp2;
5871 	int idx;
5872 	SPL_INT(s);
5873 
5874 	if (softc->ipf_running <= 0)
5875 		return;
5876 
5877 	/*
5878 	 * Change IP addresses for NAT sessions for any protocol except TCP
5879 	 * since it will break the TCP connection anyway.  The only rules
5880 	 * which will get changed are those which are "map ... -> 0/32",
5881 	 * where the rule specifies the address is taken from the interface.
5882 	 */
5883 	SPL_NET(s);
5884 	WRITE_ENTER(&softc->ipf_nat);
5885 
5886 	if (softc->ipf_running <= 0) {
5887 		RWLOCK_EXIT(&softc->ipf_nat);
5888 		return;
5889 	}
5890 
5891 	for (nat = softn->ipf_nat_instances; nat; nat = nat->nat_next) {
5892 		if ((nat->nat_flags & IPN_TCP) != 0)
5893 			continue;
5894 
5895 		n = nat->nat_ptr;
5896 		if (n != NULL) {
5897 			if (n->in_v[1] == 4) {
5898 				if (n->in_redir & NAT_MAP) {
5899 					if ((n->in_nsrcaddr != 0) ||
5900 					    (n->in_nsrcmsk != 0xffffffff))
5901 						continue;
5902 				} else if (n->in_redir & NAT_REDIRECT) {
5903 					if ((n->in_ndstaddr != 0) ||
5904 					    (n->in_ndstmsk != 0xffffffff))
5905 						continue;
5906 				}
5907 			}
5908 #ifdef USE_INET6
5909 			if (n->in_v[1] == 4) {
5910 				if (n->in_redir & NAT_MAP) {
5911 					if (!IP6_ISZERO(&n->in_nsrcaddr) ||
5912 					    !IP6_ISONES(&n->in_nsrcmsk))
5913 						continue;
5914 				} else if (n->in_redir & NAT_REDIRECT) {
5915 					if (!IP6_ISZERO(&n->in_ndstaddr) ||
5916 					    !IP6_ISONES(&n->in_ndstmsk))
5917 						continue;
5918 				}
5919 			}
5920 #endif
5921 		}
5922 
5923 		if (((ifp == NULL) || (ifp == nat->nat_ifps[0]) ||
5924 		     (ifp == nat->nat_ifps[1]))) {
5925 			nat->nat_ifps[0] = GETIFP(nat->nat_ifnames[0],
5926 						  nat->nat_v[0]);
5927 			if ((nat->nat_ifps[0] != NULL) &&
5928 			    (nat->nat_ifps[0] != (void *)-1)) {
5929 				nat->nat_mtu[0] = GETIFMTU_4(nat->nat_ifps[0]);
5930 			}
5931 			if (nat->nat_ifnames[1][0] != '\0') {
5932 				nat->nat_ifps[1] = GETIFP(nat->nat_ifnames[1],
5933 							  nat->nat_v[1]);
5934 			} else {
5935 				nat->nat_ifps[1] = nat->nat_ifps[0];
5936 			}
5937 			if ((nat->nat_ifps[1] != NULL) &&
5938 			    (nat->nat_ifps[1] != (void *)-1)) {
5939 				nat->nat_mtu[1] = GETIFMTU_4(nat->nat_ifps[1]);
5940 			}
5941 			ifp2 = nat->nat_ifps[0];
5942 			if (ifp2 == NULL)
5943 				continue;
5944 
5945 			/*
5946 			 * Change the map-to address to be the same as the
5947 			 * new one.
5948 			 */
5949 			sum1 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
5950 			if (ipf_ifpaddr(softc, nat->nat_v[0], FRI_NORMAL, ifp2,
5951 				       &in, NULL) != -1) {
5952 				if (nat->nat_v[0] == 4)
5953 					nat->nat_nsrcip = in.in4;
5954 			}
5955 			sum2 = NATFSUM(nat, nat->nat_v[1], nat_nsrc6);
5956 
5957 			if (sum1 == sum2)
5958 				continue;
5959 			/*
5960 			 * Readjust the checksum adjustment to take into
5961 			 * account the new IP#.
5962 			 */
5963 			CALC_SUMD(sum1, sum2, sumd);
5964 			/* XXX - dont change for TCP when solaris does
5965 			 * hardware checksumming.
5966 			 */
5967 			sumd += nat->nat_sumd[0];
5968 			nat->nat_sumd[0] = (sumd & 0xffff) + (sumd >> 16);
5969 			nat->nat_sumd[1] = nat->nat_sumd[0];
5970 		}
5971 	}
5972 
5973 	for (n = softn->ipf_nat_list; (n != NULL); n = n->in_next) {
5974 		char *base = n->in_names;
5975 
5976 		if ((ifp == NULL) || (n->in_ifps[0] == ifp))
5977 			n->in_ifps[0] = ipf_resolvenic(softc,
5978 						       base + n->in_ifnames[0],
5979 						       n->in_v[0]);
5980 		if ((ifp == NULL) || (n->in_ifps[1] == ifp))
5981 			n->in_ifps[1] = ipf_resolvenic(softc,
5982 						       base + n->in_ifnames[1],
5983 						       n->in_v[1]);
5984 
5985 		if (n->in_redir & NAT_REDIRECT)
5986 			idx = 1;
5987 		else
5988 			idx = 0;
5989 
5990 		if (((ifp == NULL) || (n->in_ifps[idx] == ifp)) &&
5991 		    (n->in_ifps[idx] != NULL &&
5992 		     n->in_ifps[idx] != (void *)-1)) {
5993 
5994 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_osrc,
5995 					     0, n->in_ifps[idx]);
5996 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_odst,
5997 					     0, n->in_ifps[idx]);
5998 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_nsrc,
5999 					     0, n->in_ifps[idx]);
6000 			ipf_nat_nextaddrinit(softc, n->in_names, &n->in_ndst,
6001 					     0, n->in_ifps[idx]);
6002 		}
6003 	}
6004 	RWLOCK_EXIT(&softc->ipf_nat);
6005 	SPL_X(s);
6006 }
6007 
6008 
6009 /* ------------------------------------------------------------------------ */
6010 /* Function:    ipf_nat_icmpquerytype                                       */
6011 /* Returns:     int - 1 == success, 0 == failure                            */
6012 /* Parameters:  icmptype(I) - ICMP type number                              */
6013 /*                                                                          */
6014 /* Tests to see if the ICMP type number passed is a query/response type or  */
6015 /* not.                                                                     */
6016 /* ------------------------------------------------------------------------ */
6017 static int
ipf_nat_icmpquerytype(int icmptype)6018 ipf_nat_icmpquerytype(int icmptype)
6019 {
6020 
6021 	/*
6022 	 * For the ICMP query NAT code, it is essential that both the query
6023 	 * and the reply match on the NAT rule. Because the NAT structure
6024 	 * does not keep track of the icmptype, and a single NAT structure
6025 	 * is used for all icmp types with the same src, dest and id, we
6026 	 * simply define the replies as queries as well. The funny thing is,
6027 	 * altough it seems silly to call a reply a query, this is exactly
6028 	 * as it is defined in the IPv4 specification
6029 	 */
6030 	switch (icmptype)
6031 	{
6032 	case ICMP_ECHOREPLY:
6033 	case ICMP_ECHO:
6034 	/* route advertisement/solicitation is currently unsupported: */
6035 	/* it would require rewriting the ICMP data section          */
6036 	case ICMP_TSTAMP:
6037 	case ICMP_TSTAMPREPLY:
6038 	case ICMP_IREQ:
6039 	case ICMP_IREQREPLY:
6040 	case ICMP_MASKREQ:
6041 	case ICMP_MASKREPLY:
6042 		return (1);
6043 	default:
6044 		return (0);
6045 	}
6046 }
6047 
6048 
6049 /* ------------------------------------------------------------------------ */
6050 /* Function:    nat_log                                                     */
6051 /* Returns:     Nil                                                         */
6052 /* Parameters:  softc(I) - pointer to soft context main structure           */
6053 /*              softn(I) - pointer to NAT context structure                 */
6054 /*              nat(I)    - pointer to NAT structure                        */
6055 /*              action(I) - action related to NAT structure being performed */
6056 /*                                                                          */
6057 /* Creates a NAT log entry.                                                 */
6058 /* ------------------------------------------------------------------------ */
6059 void
ipf_nat_log(ipf_main_softc_t * softc,ipf_nat_softc_t * softn,struct nat * nat,u_int action)6060 ipf_nat_log(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, struct nat *nat,
6061 	u_int action)
6062 {
6063 #ifdef	IPFILTER_LOG
6064 	struct ipnat *np;
6065 	int rulen;
6066 	struct natlog natl;
6067 	void *items[1];
6068 	size_t sizes[1];
6069 	int types[1];
6070 
6071 	bcopy((char *)&nat->nat_osrc6, (char *)&natl.nl_osrcip,
6072 	      sizeof(natl.nl_osrcip));
6073 	bcopy((char *)&nat->nat_nsrc6, (char *)&natl.nl_nsrcip,
6074 	      sizeof(natl.nl_nsrcip));
6075 	bcopy((char *)&nat->nat_odst6, (char *)&natl.nl_odstip,
6076 	      sizeof(natl.nl_odstip));
6077 	bcopy((char *)&nat->nat_ndst6, (char *)&natl.nl_ndstip,
6078 	      sizeof(natl.nl_ndstip));
6079 
6080 	natl.nl_bytes[0] = nat->nat_bytes[0];
6081 	natl.nl_bytes[1] = nat->nat_bytes[1];
6082 	natl.nl_pkts[0] = nat->nat_pkts[0];
6083 	natl.nl_pkts[1] = nat->nat_pkts[1];
6084 	natl.nl_odstport = nat->nat_odport;
6085 	natl.nl_osrcport = nat->nat_osport;
6086 	natl.nl_nsrcport = nat->nat_nsport;
6087 	natl.nl_ndstport = nat->nat_ndport;
6088 	natl.nl_p[0] = nat->nat_pr[0];
6089 	natl.nl_p[1] = nat->nat_pr[1];
6090 	natl.nl_v[0] = nat->nat_v[0];
6091 	natl.nl_v[1] = nat->nat_v[1];
6092 	natl.nl_type = nat->nat_redir;
6093 	natl.nl_action = action;
6094 	natl.nl_rule = -1;
6095 
6096 	bcopy(nat->nat_ifnames[0], natl.nl_ifnames[0],
6097 	      sizeof(nat->nat_ifnames[0]));
6098 	bcopy(nat->nat_ifnames[1], natl.nl_ifnames[1],
6099 	      sizeof(nat->nat_ifnames[1]));
6100 
6101 	if (softc->ipf_large_nat && nat->nat_ptr != NULL) {
6102 		for (rulen = 0, np = softn->ipf_nat_list; np != NULL;
6103 		     np = np->in_next, rulen++)
6104 			if (np == nat->nat_ptr) {
6105 				natl.nl_rule = rulen;
6106 				break;
6107 			}
6108 	}
6109 	items[0] = &natl;
6110 	sizes[0] = sizeof(natl);
6111 	types[0] = 0;
6112 
6113 	(void) ipf_log_items(softc, IPL_LOGNAT, NULL, items, sizes, types, 1);
6114 #endif
6115 }
6116 
6117 
6118 
6119 
6120 /* ------------------------------------------------------------------------ */
6121 /* Function:    ipf_nat_rule_deref                                          */
6122 /* Returns:     Nil                                                         */
6123 /* Parameters:  softc(I) - pointer to soft context main structure           */
6124 /*              inp(I)   - pointer to pointer to NAT rule                   */
6125 /* Write Locks: ipf_nat                                                     */
6126 /*                                                                          */
6127 /* Dropping the refernce count for a rule means that whatever held the      */
6128 /* pointer to this rule (*inp) is no longer interested in it and when the   */
6129 /* reference count drops to zero, any resources allocated for the rule can  */
6130 /* be released and the rule itself free'd.                                  */
6131 /* ------------------------------------------------------------------------ */
6132 void
ipf_nat_rule_deref(ipf_main_softc_t * softc,ipnat_t ** inp)6133 ipf_nat_rule_deref(ipf_main_softc_t *softc, ipnat_t **inp)
6134 {
6135 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6136 	ipnat_t *n;
6137 
6138 	n = *inp;
6139 	*inp = NULL;
6140 	n->in_use--;
6141 	if (n->in_use > 0)
6142 		return;
6143 
6144 	if (n->in_apr != NULL)
6145 		ipf_proxy_deref(n->in_apr);
6146 
6147 	ipf_nat_rule_fini(softc, n);
6148 
6149 	if (n->in_redir & NAT_REDIRECT) {
6150 		if ((n->in_flags & IPN_PROXYRULE) == 0) {
6151 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_rdr);
6152 		}
6153 	}
6154 	if (n->in_redir & (NAT_MAP|NAT_MAPBLK)) {
6155 		if ((n->in_flags & IPN_PROXYRULE) == 0) {
6156 			ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules_map);
6157 		}
6158 	}
6159 
6160 	if (n->in_tqehead[0] != NULL) {
6161 		if (ipf_deletetimeoutqueue(n->in_tqehead[0]) == 0) {
6162 			ipf_freetimeoutqueue(softc, n->in_tqehead[0]);
6163 		}
6164 	}
6165 
6166 	if (n->in_tqehead[1] != NULL) {
6167 		if (ipf_deletetimeoutqueue(n->in_tqehead[1]) == 0) {
6168 			ipf_freetimeoutqueue(softc, n->in_tqehead[1]);
6169 		}
6170 	}
6171 
6172 	if ((n->in_flags & IPN_PROXYRULE) == 0) {
6173 		ATOMIC_DEC32(softn->ipf_nat_stats.ns_rules);
6174 	}
6175 
6176 	MUTEX_DESTROY(&n->in_lock);
6177 
6178 	KFREES(n, n->in_size);
6179 
6180 #if SOLARIS && !defined(INSTANCES)
6181 	if (softn->ipf_nat_stats.ns_rules == 0)
6182 		pfil_delayed_copy = 1;
6183 #endif
6184 }
6185 
6186 
6187 /* ------------------------------------------------------------------------ */
6188 /* Function:    ipf_nat_deref                                               */
6189 /* Returns:     Nil                                                         */
6190 /* Parameters:  softc(I) - pointer to soft context main structure           */
6191 /*              natp(I)  - pointer to pointer to NAT table entry            */
6192 /*                                                                          */
6193 /* Decrement the reference counter for this NAT table entry and free it if  */
6194 /* there are no more things using it.                                       */
6195 /*                                                                          */
6196 /* IF nat_ref == 1 when this function is called, then we have an orphan nat */
6197 /* structure *because* it only gets called on paths _after_ nat_ref has been*/
6198 /* incremented.  If nat_ref == 1 then we shouldn't decrement it here        */
6199 /* because nat_delete() will do that and send nat_ref to -1.                */
6200 /*                                                                          */
6201 /* Holding the lock on nat_lock is required to serialise nat_delete() being */
6202 /* called from a NAT flush ioctl with a deref happening because of a packet.*/
6203 /* ------------------------------------------------------------------------ */
6204 void
ipf_nat_deref(ipf_main_softc_t * softc,nat_t ** natp)6205 ipf_nat_deref(ipf_main_softc_t *softc, nat_t **natp)
6206 {
6207 	nat_t *nat;
6208 
6209 	nat = *natp;
6210 	*natp = NULL;
6211 
6212 	MUTEX_ENTER(&nat->nat_lock);
6213 	if (nat->nat_ref > 1) {
6214 		nat->nat_ref--;
6215 		ASSERT(nat->nat_ref >= 0);
6216 		MUTEX_EXIT(&nat->nat_lock);
6217 		return;
6218 	}
6219 	MUTEX_EXIT(&nat->nat_lock);
6220 
6221 	WRITE_ENTER(&softc->ipf_nat);
6222 	ipf_nat_delete(softc, nat, NL_EXPIRE);
6223 	RWLOCK_EXIT(&softc->ipf_nat);
6224 }
6225 
6226 
6227 /* ------------------------------------------------------------------------ */
6228 /* Function:    ipf_nat_clone                                               */
6229 /* Returns:     ipstate_t* - NULL == cloning failed,                        */
6230 /*                           else pointer to new state structure            */
6231 /* Parameters:  fin(I) - pointer to packet information                      */
6232 /*              is(I)  - pointer to master state structure                  */
6233 /* Write Lock:  ipf_nat                                                     */
6234 /*                                                                          */
6235 /* Create a "duplcate" state table entry from the master.                   */
6236 /* ------------------------------------------------------------------------ */
6237 nat_t *
ipf_nat_clone(fr_info_t * fin,nat_t * nat)6238 ipf_nat_clone(fr_info_t *fin, nat_t *nat)
6239 {
6240 	ipf_main_softc_t *softc = fin->fin_main_soft;
6241 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6242 	frentry_t *fr;
6243 	nat_t *clone;
6244 	ipnat_t *np;
6245 
6246 	KMALLOC(clone, nat_t *);
6247 	if (clone == NULL) {
6248 		NBUMPSIDED(fin->fin_out, ns_clone_nomem);
6249 		return (NULL);
6250 	}
6251 	bcopy((char *)nat, (char *)clone, sizeof(*clone));
6252 
6253 	MUTEX_NUKE(&clone->nat_lock);
6254 
6255 	clone->nat_rev = fin->fin_rev;
6256 	clone->nat_aps = NULL;
6257 	/*
6258 	 * Initialize all these so that ipf_nat_delete() doesn't cause a crash.
6259 	 */
6260 	clone->nat_tqe.tqe_pnext = NULL;
6261 	clone->nat_tqe.tqe_next = NULL;
6262 	clone->nat_tqe.tqe_ifq = NULL;
6263 	clone->nat_tqe.tqe_parent = clone;
6264 
6265 	clone->nat_flags &= ~SI_CLONE;
6266 	clone->nat_flags |= SI_CLONED;
6267 
6268 	if (clone->nat_hm)
6269 		clone->nat_hm->hm_ref++;
6270 
6271 	if (ipf_nat_insert(softc, softn, clone) == -1) {
6272 		KFREE(clone);
6273 		NBUMPSIDED(fin->fin_out, ns_insert_fail);
6274 		return (NULL);
6275 	}
6276 
6277 	np = clone->nat_ptr;
6278 	if (np != NULL) {
6279 		if (softn->ipf_nat_logging)
6280 			ipf_nat_log(softc, softn, clone, NL_CLONE);
6281 		np->in_use++;
6282 	}
6283 	fr = clone->nat_fr;
6284 	if (fr != NULL) {
6285 		MUTEX_ENTER(&fr->fr_lock);
6286 		fr->fr_ref++;
6287 		MUTEX_EXIT(&fr->fr_lock);
6288 	}
6289 
6290 
6291 	/*
6292 	 * Because the clone is created outside the normal loop of things and
6293 	 * TCP has special needs in terms of state, initialise the timeout
6294 	 * state of the new NAT from here.
6295 	 */
6296 	if (clone->nat_pr[0] == IPPROTO_TCP) {
6297 		(void) ipf_tcp_age(&clone->nat_tqe, fin, softn->ipf_nat_tcptq,
6298 				   clone->nat_flags, 2);
6299 	}
6300 	clone->nat_sync = ipf_sync_new(softc, SMC_NAT, fin, clone);
6301 	if (softn->ipf_nat_logging)
6302 		ipf_nat_log(softc, softn, clone, NL_CLONE);
6303 	return (clone);
6304 }
6305 
6306 
6307 /* ------------------------------------------------------------------------ */
6308 /* Function:   ipf_nat_wildok                                               */
6309 /* Returns:    int - 1 == packet's ports match wildcards                    */
6310 /*                   0 == packet's ports don't match wildcards              */
6311 /* Parameters: nat(I)   - NAT entry                                         */
6312 /*             sport(I) - source port                                       */
6313 /*             dport(I) - destination port                                  */
6314 /*             flags(I) - wildcard flags                                    */
6315 /*             dir(I)   - packet direction                                  */
6316 /*                                                                          */
6317 /* Use NAT entry and packet direction to determine which combination of     */
6318 /* wildcard flags should be used.                                           */
6319 /* ------------------------------------------------------------------------ */
6320 int
ipf_nat_wildok(nat_t * nat,int sport,int dport,int flags,int dir)6321 ipf_nat_wildok(nat_t *nat, int sport, int dport, int flags, int dir)
6322 {
6323 	/*
6324 	 * When called by       dir is set to
6325 	 * nat_inlookup         NAT_INBOUND (0)
6326 	 * nat_outlookup        NAT_OUTBOUND (1)
6327 	 *
6328 	 * We simply combine the packet's direction in dir with the original
6329 	 * "intended" direction of that NAT entry in nat->nat_dir to decide
6330 	 * which combination of wildcard flags to allow.
6331 	 */
6332 	switch ((dir << 1) | (nat->nat_dir & (NAT_INBOUND|NAT_OUTBOUND)))
6333 	{
6334 	case 3: /* outbound packet / outbound entry */
6335 		if (((nat->nat_osport == sport) ||
6336 		    (flags & SI_W_SPORT)) &&
6337 		    ((nat->nat_odport == dport) ||
6338 		    (flags & SI_W_DPORT)))
6339 			return (1);
6340 		break;
6341 	case 2: /* outbound packet / inbound entry */
6342 		if (((nat->nat_osport == dport) ||
6343 		    (flags & SI_W_SPORT)) &&
6344 		    ((nat->nat_odport == sport) ||
6345 		    (flags & SI_W_DPORT)))
6346 			return (1);
6347 		break;
6348 	case 1: /* inbound packet / outbound entry */
6349 		if (((nat->nat_osport == dport) ||
6350 		    (flags & SI_W_SPORT)) &&
6351 		    ((nat->nat_odport == sport) ||
6352 		    (flags & SI_W_DPORT)))
6353 			return (1);
6354 		break;
6355 	case 0: /* inbound packet / inbound entry */
6356 		if (((nat->nat_osport == sport) ||
6357 		    (flags & SI_W_SPORT)) &&
6358 		    ((nat->nat_odport == dport) ||
6359 		    (flags & SI_W_DPORT)))
6360 			return (1);
6361 		break;
6362 	default:
6363 		break;
6364 	}
6365 
6366 	return (0);
6367 }
6368 
6369 
6370 /* ------------------------------------------------------------------------ */
6371 /* Function:    nat_mssclamp                                                */
6372 /* Returns:     Nil                                                         */
6373 /* Parameters:  tcp(I)    - pointer to TCP header                           */
6374 /*              maxmss(I) - value to clamp the TCP MSS to                   */
6375 /*              fin(I)    - pointer to packet information                   */
6376 /*              csump(I)  - pointer to TCP checksum                         */
6377 /*                                                                          */
6378 /* Check for MSS option and clamp it if necessary.  If found and changed,   */
6379 /* then the TCP header checksum will be updated to reflect the change in    */
6380 /* the MSS.                                                                 */
6381 /* ------------------------------------------------------------------------ */
6382 static void
ipf_nat_mssclamp(tcphdr_t * tcp,u_32_t maxmss,fr_info_t * fin,u_short * csump)6383 ipf_nat_mssclamp(tcphdr_t *tcp, u_32_t maxmss, fr_info_t *fin, u_short *csump)
6384 {
6385 	u_char *cp, *ep, opt;
6386 	int hlen, advance;
6387 	u_32_t mss, sumd;
6388 
6389 	hlen = TCP_OFF(tcp) << 2;
6390 	if (hlen > sizeof(*tcp)) {
6391 		cp = (u_char *)tcp + sizeof(*tcp);
6392 		ep = (u_char *)tcp + hlen;
6393 
6394 		while (cp < ep) {
6395 			opt = cp[0];
6396 			if (opt == TCPOPT_EOL)
6397 				break;
6398 			else if (opt == TCPOPT_NOP) {
6399 				cp++;
6400 				continue;
6401 			}
6402 
6403 			if (cp + 1 >= ep)
6404 				break;
6405 			advance = cp[1];
6406 			if ((cp + advance > ep) || (advance <= 0))
6407 				break;
6408 			switch (opt)
6409 			{
6410 			case TCPOPT_MAXSEG:
6411 				if (advance != 4)
6412 					break;
6413 				mss = cp[2] * 256 + cp[3];
6414 				if (mss > maxmss) {
6415 					cp[2] = maxmss / 256;
6416 					cp[3] = maxmss & 0xff;
6417 					CALC_SUMD(mss, maxmss, sumd);
6418 					ipf_fix_outcksum(0, csump, sumd, 0);
6419 				}
6420 				break;
6421 			default:
6422 				/* ignore unknown options */
6423 				break;
6424 			}
6425 
6426 			cp += advance;
6427 		}
6428 	}
6429 }
6430 
6431 
6432 /* ------------------------------------------------------------------------ */
6433 /* Function:    ipf_nat_setqueue                                            */
6434 /* Returns:     Nil                                                         */
6435 /* Parameters:  softc(I) - pointer to soft context main structure           */
6436 /*              softn(I) - pointer to NAT context structure                 */
6437 /*              nat(I)- pointer to NAT structure                            */
6438 /* Locks:       ipf_nat (read or write)                                     */
6439 /*                                                                          */
6440 /* Put the NAT entry on its default queue entry, using rev as a helped in   */
6441 /* determining which queue it should be placed on.                          */
6442 /* ------------------------------------------------------------------------ */
6443 void
ipf_nat_setqueue(ipf_main_softc_t * softc,ipf_nat_softc_t * softn,nat_t * nat)6444 ipf_nat_setqueue(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, nat_t *nat)
6445 {
6446 	ipftq_t *oifq, *nifq;
6447 	int rev = nat->nat_rev;
6448 
6449 	if (nat->nat_ptr != NULL)
6450 		nifq = nat->nat_ptr->in_tqehead[rev];
6451 	else
6452 		nifq = NULL;
6453 
6454 	if (nifq == NULL) {
6455 		switch (nat->nat_pr[0])
6456 		{
6457 		case IPPROTO_UDP :
6458 			nifq = &softn->ipf_nat_udptq;
6459 			break;
6460 		case IPPROTO_ICMP :
6461 			nifq = &softn->ipf_nat_icmptq;
6462 			break;
6463 		case IPPROTO_TCP :
6464 			nifq = softn->ipf_nat_tcptq +
6465 			       nat->nat_tqe.tqe_state[rev];
6466 			break;
6467 		default :
6468 			nifq = &softn->ipf_nat_iptq;
6469 			break;
6470 		}
6471 	}
6472 
6473 	oifq = nat->nat_tqe.tqe_ifq;
6474 	/*
6475 	 * If it's currently on a timeout queue, move it from one queue to
6476 	 * another, else put it on the end of the newly determined queue.
6477 	 */
6478 	if (oifq != NULL)
6479 		ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq, nifq);
6480 	else
6481 		ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe, nifq, nat);
6482 	return;
6483 }
6484 
6485 
6486 /* ------------------------------------------------------------------------ */
6487 /* Function:    nat_getnext                                                 */
6488 /* Returns:     int - 0 == ok, else error                                   */
6489 /* Parameters:  softc(I) - pointer to soft context main structure           */
6490 /*              t(I)   - pointer to ipftoken structure                      */
6491 /*              itp(I) - pointer to ipfgeniter_t structure                  */
6492 /*                                                                          */
6493 /* Fetch the next nat/ipnat structure pointer from the linked list and      */
6494 /* copy it out to the storage space pointed to by itp_data.  The next item  */
6495 /* in the list to look at is put back in the ipftoken struture.             */
6496 /* ------------------------------------------------------------------------ */
6497 static int
ipf_nat_getnext(ipf_main_softc_t * softc,ipftoken_t * t,ipfgeniter_t * itp,ipfobj_t * objp)6498 ipf_nat_getnext(ipf_main_softc_t *softc, ipftoken_t *t, ipfgeniter_t *itp,
6499 	ipfobj_t *objp)
6500 {
6501 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6502 	hostmap_t *hm, *nexthm = NULL, zerohm;
6503 	ipnat_t *ipn, *nextipnat = NULL, zeroipn;
6504 	nat_t *nat, *nextnat = NULL, zeronat;
6505 	int error = 0;
6506 	void *nnext;
6507 
6508 	if (itp->igi_nitems != 1) {
6509 		IPFERROR(60075);
6510 		return (ENOSPC);
6511 	}
6512 
6513 	READ_ENTER(&softc->ipf_nat);
6514 
6515 	switch (itp->igi_type)
6516 	{
6517 	case IPFGENITER_HOSTMAP :
6518 		hm = t->ipt_data;
6519 		if (hm == NULL) {
6520 			nexthm = softn->ipf_hm_maplist;
6521 		} else {
6522 			nexthm = hm->hm_next;
6523 		}
6524 		if (nexthm != NULL) {
6525 			ATOMIC_INC32(nexthm->hm_ref);
6526 			t->ipt_data = nexthm;
6527 		} else {
6528 			bzero(&zerohm, sizeof(zerohm));
6529 			nexthm = &zerohm;
6530 			t->ipt_data = NULL;
6531 		}
6532 		nnext = nexthm->hm_next;
6533 		break;
6534 
6535 	case IPFGENITER_IPNAT :
6536 		ipn = t->ipt_data;
6537 		if (ipn == NULL) {
6538 			nextipnat = softn->ipf_nat_list;
6539 		} else {
6540 			nextipnat = ipn->in_next;
6541 		}
6542 		if (nextipnat != NULL) {
6543 			ATOMIC_INC32(nextipnat->in_use);
6544 			t->ipt_data = nextipnat;
6545 		} else {
6546 			bzero(&zeroipn, sizeof(zeroipn));
6547 			nextipnat = &zeroipn;
6548 			t->ipt_data = NULL;
6549 		}
6550 		nnext = nextipnat->in_next;
6551 		break;
6552 
6553 	case IPFGENITER_NAT :
6554 		nat = t->ipt_data;
6555 		if (nat == NULL) {
6556 			nextnat = softn->ipf_nat_instances;
6557 		} else {
6558 			nextnat = nat->nat_next;
6559 		}
6560 		if (nextnat != NULL) {
6561 			MUTEX_ENTER(&nextnat->nat_lock);
6562 			nextnat->nat_ref++;
6563 			MUTEX_EXIT(&nextnat->nat_lock);
6564 			t->ipt_data = nextnat;
6565 		} else {
6566 			bzero(&zeronat, sizeof(zeronat));
6567 			nextnat = &zeronat;
6568 			t->ipt_data = NULL;
6569 		}
6570 		nnext = nextnat->nat_next;
6571 		break;
6572 
6573 	default :
6574 		RWLOCK_EXIT(&softc->ipf_nat);
6575 		IPFERROR(60055);
6576 		return (EINVAL);
6577 	}
6578 
6579 	RWLOCK_EXIT(&softc->ipf_nat);
6580 
6581 	objp->ipfo_ptr = itp->igi_data;
6582 
6583 	switch (itp->igi_type)
6584 	{
6585 	case IPFGENITER_HOSTMAP :
6586 		error = COPYOUT(nexthm, objp->ipfo_ptr, sizeof(*nexthm));
6587 		if (error != 0) {
6588 			IPFERROR(60049);
6589 			error = EFAULT;
6590 		}
6591 		if (hm != NULL) {
6592 			WRITE_ENTER(&softc->ipf_nat);
6593 			ipf_nat_hostmapdel(softc, &hm);
6594 			RWLOCK_EXIT(&softc->ipf_nat);
6595 		}
6596 		break;
6597 
6598 	case IPFGENITER_IPNAT :
6599 		objp->ipfo_size = nextipnat->in_size;
6600 		objp->ipfo_type = IPFOBJ_IPNAT;
6601 		error = ipf_outobjk(softc, objp, nextipnat);
6602 		if (ipn != NULL) {
6603 			WRITE_ENTER(&softc->ipf_nat);
6604 			ipf_nat_rule_deref(softc, &ipn);
6605 			RWLOCK_EXIT(&softc->ipf_nat);
6606 		}
6607 		break;
6608 
6609 	case IPFGENITER_NAT :
6610 		objp->ipfo_size = sizeof(nat_t);
6611 		objp->ipfo_type = IPFOBJ_NAT;
6612 		error = ipf_outobjk(softc, objp, nextnat);
6613 		if (nat != NULL)
6614 			ipf_nat_deref(softc, &nat);
6615 
6616 		break;
6617 	}
6618 
6619 	if (nnext == NULL)
6620 		ipf_token_mark_complete(t);
6621 
6622 	return (error);
6623 }
6624 
6625 
6626 /* ------------------------------------------------------------------------ */
6627 /* Function:    nat_extraflush                                              */
6628 /* Returns:     int - 0 == success, -1 == failure                           */
6629 /* Parameters:  softc(I) - pointer to soft context main structure           */
6630 /*              softn(I) - pointer to NAT context structure                 */
6631 /*              which(I) - how to flush the active NAT table                */
6632 /* Write Locks: ipf_nat                                                     */
6633 /*                                                                          */
6634 /* Flush nat tables.  Three actions currently defined:                      */
6635 /* which == 0 : flush all nat table entries                                 */
6636 /* which == 1 : flush TCP connections which have started to close but are   */
6637 /*	      stuck for some reason.                                        */
6638 /* which == 2 : flush TCP connections which have been idle for a long time, */
6639 /*	      starting at > 4 days idle and working back in successive half-*/
6640 /*	      days to at most 12 hours old.  If this fails to free enough   */
6641 /*            slots then work backwards in half hour slots to 30 minutes.   */
6642 /*            If that too fails, then work backwards in 30 second intervals */
6643 /*            for the last 30 minutes to at worst 30 seconds idle.          */
6644 /* ------------------------------------------------------------------------ */
6645 static int
ipf_nat_extraflush(ipf_main_softc_t * softc,ipf_nat_softc_t * softn,int which)6646 ipf_nat_extraflush(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, int which)
6647 {
6648 	nat_t *nat, **natp;
6649 	ipftqent_t *tqn;
6650 	ipftq_t *ifq;
6651 	int removed;
6652 	SPL_INT(s);
6653 
6654 	removed = 0;
6655 
6656 	SPL_NET(s);
6657 	switch (which)
6658 	{
6659 	case 0 :
6660 		softn->ipf_nat_stats.ns_flush_all++;
6661 		/*
6662 		 * Style 0 flush removes everything...
6663 		 */
6664 		for (natp = &softn->ipf_nat_instances;
6665 		     ((nat = *natp) != NULL); ) {
6666 			ipf_nat_delete(softc, nat, NL_FLUSH);
6667 			removed++;
6668 		}
6669 		break;
6670 
6671 	case 1 :
6672 		softn->ipf_nat_stats.ns_flush_closing++;
6673 		/*
6674 		 * Since we're only interested in things that are closing,
6675 		 * we can start with the appropriate timeout queue.
6676 		 */
6677 		for (ifq = softn->ipf_nat_tcptq + IPF_TCPS_CLOSE_WAIT;
6678 		     ifq != NULL; ifq = ifq->ifq_next) {
6679 
6680 			for (tqn = ifq->ifq_head; tqn != NULL; ) {
6681 				nat = tqn->tqe_parent;
6682 				tqn = tqn->tqe_next;
6683 				if (nat->nat_pr[0] != IPPROTO_TCP ||
6684 				    nat->nat_pr[1] != IPPROTO_TCP)
6685 					break;
6686 				ipf_nat_delete(softc, nat, NL_EXPIRE);
6687 				removed++;
6688 			}
6689 		}
6690 
6691 		/*
6692 		 * Also need to look through the user defined queues.
6693 		 */
6694 		for (ifq = softn->ipf_nat_utqe; ifq != NULL;
6695 		     ifq = ifq->ifq_next) {
6696 			for (tqn = ifq->ifq_head; tqn != NULL; ) {
6697 				nat = tqn->tqe_parent;
6698 				tqn = tqn->tqe_next;
6699 				if (nat->nat_pr[0] != IPPROTO_TCP ||
6700 				    nat->nat_pr[1] != IPPROTO_TCP)
6701 					continue;
6702 
6703 				if ((nat->nat_tcpstate[0] >
6704 				     IPF_TCPS_ESTABLISHED) &&
6705 				    (nat->nat_tcpstate[1] >
6706 				     IPF_TCPS_ESTABLISHED)) {
6707 					ipf_nat_delete(softc, nat, NL_EXPIRE);
6708 					removed++;
6709 				}
6710 			}
6711 		}
6712 		break;
6713 
6714 		/*
6715 		 * Args 5-11 correspond to flushing those particular states
6716 		 * for TCP connections.
6717 		 */
6718 	case IPF_TCPS_CLOSE_WAIT :
6719 	case IPF_TCPS_FIN_WAIT_1 :
6720 	case IPF_TCPS_CLOSING :
6721 	case IPF_TCPS_LAST_ACK :
6722 	case IPF_TCPS_FIN_WAIT_2 :
6723 	case IPF_TCPS_TIME_WAIT :
6724 	case IPF_TCPS_CLOSED :
6725 		softn->ipf_nat_stats.ns_flush_state++;
6726 		tqn = softn->ipf_nat_tcptq[which].ifq_head;
6727 		while (tqn != NULL) {
6728 			nat = tqn->tqe_parent;
6729 			tqn = tqn->tqe_next;
6730 			ipf_nat_delete(softc, nat, NL_FLUSH);
6731 			removed++;
6732 		}
6733 		break;
6734 
6735 	default :
6736 		if (which < 30)
6737 			break;
6738 
6739 		softn->ipf_nat_stats.ns_flush_timeout++;
6740 		/*
6741 		 * Take a large arbitrary number to mean the number of seconds
6742 		 * for which which consider to be the maximum value we'll allow
6743 		 * the expiration to be.
6744 		 */
6745 		which = IPF_TTLVAL(which);
6746 		for (natp = &softn->ipf_nat_instances;
6747 		     ((nat = *natp) != NULL); ) {
6748 			if (softc->ipf_ticks - nat->nat_touched > which) {
6749 				ipf_nat_delete(softc, nat, NL_FLUSH);
6750 				removed++;
6751 			} else
6752 				natp = &nat->nat_next;
6753 		}
6754 		break;
6755 	}
6756 
6757 	if (which != 2) {
6758 		SPL_X(s);
6759 		return (removed);
6760 	}
6761 
6762 	softn->ipf_nat_stats.ns_flush_queue++;
6763 
6764 	/*
6765 	 * Asked to remove inactive entries because the table is full, try
6766 	 * again, 3 times, if first attempt failed with a different criteria
6767 	 * each time.  The order tried in must be in decreasing age.
6768 	 * Another alternative is to implement random drop and drop N entries
6769 	 * at random until N have been freed up.
6770 	 */
6771 	if (softc->ipf_ticks - softn->ipf_nat_last_force_flush >
6772 	    IPF_TTLVAL(5)) {
6773 		softn->ipf_nat_last_force_flush = softc->ipf_ticks;
6774 
6775 		removed = ipf_queueflush(softc, ipf_nat_flush_entry,
6776 					 softn->ipf_nat_tcptq,
6777 					 softn->ipf_nat_utqe,
6778 					 &softn->ipf_nat_stats.ns_active,
6779 					 softn->ipf_nat_table_sz,
6780 					 softn->ipf_nat_table_wm_low);
6781 	}
6782 
6783 	SPL_X(s);
6784 	return (removed);
6785 }
6786 
6787 
6788 /* ------------------------------------------------------------------------ */
6789 /* Function:    ipf_nat_flush_entry                                         */
6790 /* Returns:     0 - always succeeds                                         */
6791 /* Parameters:  softc(I) - pointer to soft context main structure           */
6792 /*              entry(I) - pointer to NAT entry                             */
6793 /* Write Locks: ipf_nat                                                     */
6794 /*                                                                          */
6795 /* This function is a stepping stone between ipf_queueflush() and           */
6796 /* nat_dlete().  It is used so we can provide a uniform interface via the   */
6797 /* ipf_queueflush() function.  Since the nat_delete() function returns void */
6798 /* we translate that to mean it always succeeds in deleting something.      */
6799 /* ------------------------------------------------------------------------ */
6800 static int
ipf_nat_flush_entry(ipf_main_softc_t * softc,void * entry)6801 ipf_nat_flush_entry(ipf_main_softc_t *softc, void *entry)
6802 {
6803 	ipf_nat_delete(softc, entry, NL_FLUSH);
6804 	return (0);
6805 }
6806 
6807 
6808 /* ------------------------------------------------------------------------ */
6809 /* Function:    ipf_nat_iterator                                            */
6810 /* Returns:     int - 0 == ok, else error                                   */
6811 /* Parameters:  softc(I) - pointer to soft context main structure           */
6812 /*              token(I) - pointer to ipftoken structure                    */
6813 /*              itp(I)   - pointer to ipfgeniter_t structure                */
6814 /*              obj(I)   - pointer to data description structure            */
6815 /*                                                                          */
6816 /* This function acts as a handler for the SIOCGENITER ioctls that use a    */
6817 /* generic structure to iterate through a list.  There are three different  */
6818 /* linked lists of NAT related information to go through: NAT rules, active */
6819 /* NAT mappings and the NAT fragment cache.                                 */
6820 /* ------------------------------------------------------------------------ */
6821 static int
ipf_nat_iterator(ipf_main_softc_t * softc,ipftoken_t * token,ipfgeniter_t * itp,ipfobj_t * obj)6822 ipf_nat_iterator(ipf_main_softc_t *softc, ipftoken_t *token, ipfgeniter_t *itp,
6823 	ipfobj_t *obj)
6824 {
6825 	int error;
6826 
6827 	if (itp->igi_data == NULL) {
6828 		IPFERROR(60052);
6829 		return (EFAULT);
6830 	}
6831 
6832 	switch (itp->igi_type)
6833 	{
6834 	case IPFGENITER_HOSTMAP :
6835 	case IPFGENITER_IPNAT :
6836 	case IPFGENITER_NAT :
6837 		error = ipf_nat_getnext(softc, token, itp, obj);
6838 		break;
6839 
6840 	case IPFGENITER_NATFRAG :
6841 		error = ipf_frag_nat_next(softc, token, itp);
6842 		break;
6843 	default :
6844 		IPFERROR(60053);
6845 		error = EINVAL;
6846 		break;
6847 	}
6848 
6849 	return (error);
6850 }
6851 
6852 
6853 /* ------------------------------------------------------------------------ */
6854 /* Function:    ipf_nat_setpending                                          */
6855 /* Returns:     Nil                                                         */
6856 /* Parameters:  softc(I) - pointer to soft context main structure           */
6857 /*              nat(I)   - pointer to NAT structure                         */
6858 /* Locks:       ipf_nat (read or write)                                     */
6859 /*                                                                          */
6860 /* Put the NAT entry on to the pending queue - this queue has a very short  */
6861 /* lifetime where items are put that can't be deleted straight away because */
6862 /* of locking issues but we want to delete them ASAP, anyway.  In calling   */
6863 /* this function, it is assumed that the owner (if there is one, as shown   */
6864 /* by nat_me) is no longer interested in it.                                */
6865 /* ------------------------------------------------------------------------ */
6866 void
ipf_nat_setpending(ipf_main_softc_t * softc,nat_t * nat)6867 ipf_nat_setpending(ipf_main_softc_t *softc, nat_t *nat)
6868 {
6869 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
6870 	ipftq_t *oifq;
6871 
6872 	oifq = nat->nat_tqe.tqe_ifq;
6873 	if (oifq != NULL)
6874 		ipf_movequeue(softc->ipf_ticks, &nat->nat_tqe, oifq,
6875 			      &softn->ipf_nat_pending);
6876 	else
6877 		ipf_queueappend(softc->ipf_ticks, &nat->nat_tqe,
6878 				&softn->ipf_nat_pending, nat);
6879 
6880 	if (nat->nat_me != NULL) {
6881 		*nat->nat_me = NULL;
6882 		nat->nat_me = NULL;
6883 		nat->nat_ref--;
6884 		ASSERT(nat->nat_ref >= 0);
6885 	}
6886 }
6887 
6888 
6889 /* ------------------------------------------------------------------------ */
6890 /* Function:    nat_newrewrite                                              */
6891 /* Returns:     int - -1 == error, 0 == success (no move), 1 == success and */
6892 /*                    allow rule to be moved if IPN_ROUNDR is set.          */
6893 /* Parameters:  fin(I) - pointer to packet information                      */
6894 /*              nat(I) - pointer to NAT entry                               */
6895 /*              ni(I)  - pointer to structure with misc. information needed */
6896 /*                       to create new NAT entry.                           */
6897 /* Write Lock:  ipf_nat                                                     */
6898 /*                                                                          */
6899 /* This function is responsible for setting up an active NAT session where  */
6900 /* we are changing both the source and destination parameters at the same   */
6901 /* time.  The loop in here works differently to elsewhere - each iteration  */
6902 /* is responsible for changing a single parameter that can be incremented.  */
6903 /* So one pass may increase the source IP#, next source port, next dest. IP#*/
6904 /* and the last destination port for a total of 4 iterations to try each.   */
6905 /* This is done to try and exhaustively use the translation space available.*/
6906 /* ------------------------------------------------------------------------ */
6907 static int
ipf_nat_newrewrite(fr_info_t * fin,nat_t * nat,natinfo_t * nai)6908 ipf_nat_newrewrite(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
6909 {
6910 	int src_search = 1;
6911 	int dst_search = 1;
6912 	fr_info_t frnat;
6913 	u_32_t flags;
6914 	u_short swap;
6915 	ipnat_t *np;
6916 	nat_t *natl;
6917 	int l = 0;
6918 	int changed;
6919 
6920 	natl = NULL;
6921 	changed = -1;
6922 	np = nai->nai_np;
6923 	flags = nat->nat_flags;
6924 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
6925 
6926 	nat->nat_hm = NULL;
6927 
6928 	do {
6929 		changed = -1;
6930 		/* TRACE (l, src_search, dst_search, np) */
6931 		DT4(ipf_nat_rewrite_1, int, l, int, src_search, int, dst_search, ipnat_t *, np);
6932 
6933 		if ((src_search == 0) && (np->in_spnext == 0) &&
6934 		    (dst_search == 0) && (np->in_dpnext == 0)) {
6935 			if (l > 0)
6936 				return (-1);
6937 		}
6938 
6939 		/*
6940 		 * Find a new source address
6941 		 */
6942 		if (ipf_nat_nextaddr(fin, &np->in_nsrc, &frnat.fin_saddr,
6943 				     &frnat.fin_saddr) == -1) {
6944 			return (-1);
6945 		}
6946 
6947 		if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0xffffffff)) {
6948 			src_search = 0;
6949 			if (np->in_stepnext == 0)
6950 				np->in_stepnext = 1;
6951 
6952 		} else if ((np->in_nsrcaddr == 0) && (np->in_nsrcmsk == 0)) {
6953 			src_search = 0;
6954 			if (np->in_stepnext == 0)
6955 				np->in_stepnext = 1;
6956 
6957 		} else if (np->in_nsrcmsk == 0xffffffff) {
6958 			src_search = 0;
6959 			if (np->in_stepnext == 0)
6960 				np->in_stepnext = 1;
6961 
6962 		} else if (np->in_nsrcmsk != 0xffffffff) {
6963 			if (np->in_stepnext == 0 && changed == -1) {
6964 				np->in_snip++;
6965 				np->in_stepnext++;
6966 				changed = 0;
6967 			}
6968 		}
6969 
6970 		if ((flags & IPN_TCPUDPICMP) != 0) {
6971 			if (np->in_spnext != 0)
6972 				frnat.fin_data[0] = np->in_spnext;
6973 
6974 			/*
6975 			 * Standard port translation.  Select next port.
6976 			 */
6977 			if ((flags & IPN_FIXEDSPORT) != 0) {
6978 				np->in_stepnext = 2;
6979 			} else if ((np->in_stepnext == 1) &&
6980 				   (changed == -1) && (natl != NULL)) {
6981 				np->in_spnext++;
6982 				np->in_stepnext++;
6983 				changed = 1;
6984 				if (np->in_spnext > np->in_spmax)
6985 					np->in_spnext = np->in_spmin;
6986 			}
6987 		} else {
6988 			np->in_stepnext = 2;
6989 		}
6990 		np->in_stepnext &= 0x3;
6991 
6992 		/*
6993 		 * Find a new destination address
6994 		 */
6995 		/* TRACE (fin, np, l, frnat) */
6996 		DT4(ipf_nat_rewrite_2, frinfo_t *, fin, ipnat_t *, np, int, l, frinfo_t *, &frnat);
6997 
6998 		if (ipf_nat_nextaddr(fin, &np->in_ndst, &frnat.fin_daddr,
6999 				     &frnat.fin_daddr) == -1)
7000 			return (-1);
7001 		if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0xffffffff)) {
7002 			dst_search = 0;
7003 			if (np->in_stepnext == 2)
7004 				np->in_stepnext = 3;
7005 
7006 		} else if ((np->in_ndstaddr == 0) && (np->in_ndstmsk == 0)) {
7007 			dst_search = 0;
7008 			if (np->in_stepnext == 2)
7009 				np->in_stepnext = 3;
7010 
7011 		} else if (np->in_ndstmsk == 0xffffffff) {
7012 			dst_search = 0;
7013 			if (np->in_stepnext == 2)
7014 				np->in_stepnext = 3;
7015 
7016 		} else if (np->in_ndstmsk != 0xffffffff) {
7017 			if ((np->in_stepnext == 2) && (changed == -1) &&
7018 			    (natl != NULL)) {
7019 				changed = 2;
7020 				np->in_stepnext++;
7021 				np->in_dnip++;
7022 			}
7023 		}
7024 
7025 		if ((flags & IPN_TCPUDPICMP) != 0) {
7026 			if (np->in_dpnext != 0)
7027 				frnat.fin_data[1] = np->in_dpnext;
7028 
7029 			/*
7030 			 * Standard port translation.  Select next port.
7031 			 */
7032 			if ((flags & IPN_FIXEDDPORT) != 0) {
7033 				np->in_stepnext = 0;
7034 			} else if (np->in_stepnext == 3 && changed == -1) {
7035 				np->in_dpnext++;
7036 				np->in_stepnext++;
7037 				changed = 3;
7038 				if (np->in_dpnext > np->in_dpmax)
7039 					np->in_dpnext = np->in_dpmin;
7040 			}
7041 		} else {
7042 			if (np->in_stepnext == 3)
7043 				np->in_stepnext = 0;
7044 		}
7045 
7046 		/* TRACE (frnat) */
7047 		DT1(ipf_nat_rewrite_3, frinfo_t *, &frnat);
7048 
7049 		/*
7050 		 * Here we do a lookup of the connection as seen from
7051 		 * the outside.  If an IP# pair already exists, try
7052 		 * again.  So if you have A->B becomes C->B, you can
7053 		 * also have D->E become C->E but not D->B causing
7054 		 * another C->B.  Also take protocol and ports into
7055 		 * account when determining whether a pre-existing
7056 		 * NAT setup will cause an external conflict where
7057 		 * this is appropriate.
7058 		 *
7059 		 * fin_data[] is swapped around because we are doing a
7060 		 * lookup of the packet is if it were moving in the opposite
7061 		 * direction of the one we are working with now.
7062 		 */
7063 		if (flags & IPN_TCPUDP) {
7064 			swap = frnat.fin_data[0];
7065 			frnat.fin_data[0] = frnat.fin_data[1];
7066 			frnat.fin_data[1] = swap;
7067 		}
7068 		if (fin->fin_out == 1) {
7069 			natl = ipf_nat_inlookup(&frnat,
7070 						flags & ~(SI_WILDP|NAT_SEARCH),
7071 						(u_int)frnat.fin_p,
7072 						frnat.fin_dst, frnat.fin_src);
7073 
7074 		} else {
7075 			natl = ipf_nat_outlookup(&frnat,
7076 						 flags & ~(SI_WILDP|NAT_SEARCH),
7077 						 (u_int)frnat.fin_p,
7078 						 frnat.fin_dst, frnat.fin_src);
7079 		}
7080 		if (flags & IPN_TCPUDP) {
7081 			swap = frnat.fin_data[0];
7082 			frnat.fin_data[0] = frnat.fin_data[1];
7083 			frnat.fin_data[1] = swap;
7084 		}
7085 
7086 		/* TRACE natl, in_stepnext, l */
7087 		DT3(ipf_nat_rewrite_2, nat_t *, natl, ipnat_t *, np , int, l);
7088 
7089 		if ((natl != NULL) && (l > 8))	/* XXX 8 is arbitrary */
7090 			return (-1);
7091 
7092 		np->in_stepnext &= 0x3;
7093 
7094 		l++;
7095 		changed = -1;
7096 	} while (natl != NULL);
7097 
7098 	nat->nat_osrcip = fin->fin_src;
7099 	nat->nat_odstip = fin->fin_dst;
7100 	nat->nat_nsrcip = frnat.fin_src;
7101 	nat->nat_ndstip = frnat.fin_dst;
7102 
7103 	if ((flags & IPN_TCPUDP) != 0) {
7104 		nat->nat_osport = htons(fin->fin_data[0]);
7105 		nat->nat_odport = htons(fin->fin_data[1]);
7106 		nat->nat_nsport = htons(frnat.fin_data[0]);
7107 		nat->nat_ndport = htons(frnat.fin_data[1]);
7108 	} else if ((flags & IPN_ICMPQUERY) != 0) {
7109 		nat->nat_oicmpid = fin->fin_data[1];
7110 		nat->nat_nicmpid = frnat.fin_data[1];
7111 	}
7112 
7113 	return (0);
7114 }
7115 
7116 
7117 /* ------------------------------------------------------------------------ */
7118 /* Function:    nat_newdivert                                               */
7119 /* Returns:     int - -1 == error, 0 == success                             */
7120 /* Parameters:  fin(I) - pointer to packet information                      */
7121 /*              nat(I) - pointer to NAT entry                               */
7122 /*              ni(I)  - pointer to structure with misc. information needed */
7123 /*                       to create new NAT entry.                           */
7124 /* Write Lock:  ipf_nat                                                     */
7125 /*                                                                          */
7126 /* Create a new NAT  divert session as defined by the NAT rule.  This is    */
7127 /* somewhat different to other NAT session creation routines because we     */
7128 /* do not iterate through either port numbers or IP addresses, searching    */
7129 /* for a unique mapping, however, a complimentary duplicate check is made.  */
7130 /* ------------------------------------------------------------------------ */
7131 static int
ipf_nat_newdivert(fr_info_t * fin,nat_t * nat,natinfo_t * nai)7132 ipf_nat_newdivert(fr_info_t *fin, nat_t *nat, natinfo_t *nai)
7133 {
7134 	ipf_main_softc_t *softc = fin->fin_main_soft;
7135 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7136 	fr_info_t frnat;
7137 	ipnat_t *np;
7138 	nat_t *natl;
7139 	int p;
7140 
7141 	np = nai->nai_np;
7142 	bcopy((char *)fin, (char *)&frnat, sizeof(*fin));
7143 
7144 	nat->nat_pr[0] = 0;
7145 	nat->nat_osrcaddr = fin->fin_saddr;
7146 	nat->nat_odstaddr = fin->fin_daddr;
7147 	frnat.fin_saddr = htonl(np->in_snip);
7148 	frnat.fin_daddr = htonl(np->in_dnip);
7149 	if ((nat->nat_flags & IPN_TCPUDP) != 0) {
7150 		nat->nat_osport = htons(fin->fin_data[0]);
7151 		nat->nat_odport = htons(fin->fin_data[1]);
7152 	} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
7153 		nat->nat_oicmpid = fin->fin_data[1];
7154 	}
7155 
7156 	if (np->in_redir & NAT_DIVERTUDP) {
7157 		frnat.fin_data[0] = np->in_spnext;
7158 		frnat.fin_data[1] = np->in_dpnext;
7159 		frnat.fin_flx |= FI_TCPUDP;
7160 		p = IPPROTO_UDP;
7161 	} else {
7162 		frnat.fin_flx &= ~FI_TCPUDP;
7163 		p = IPPROTO_IPIP;
7164 	}
7165 
7166 	if (fin->fin_out == 1) {
7167 		natl = ipf_nat_inlookup(&frnat, 0, p,
7168 					frnat.fin_dst, frnat.fin_src);
7169 
7170 	} else {
7171 		natl = ipf_nat_outlookup(&frnat, 0, p,
7172 					 frnat.fin_dst, frnat.fin_src);
7173 	}
7174 
7175 	if (natl != NULL) {
7176 		NBUMPSIDED(fin->fin_out, ns_divert_exist);
7177 		DT3(ns_divert_exist, fr_info_t *, fin, nat_t *, nat, natinfo_t, nai);
7178 		return (-1);
7179 	}
7180 
7181 	nat->nat_nsrcaddr = frnat.fin_saddr;
7182 	nat->nat_ndstaddr = frnat.fin_daddr;
7183 	if ((nat->nat_flags & IPN_TCPUDP) != 0) {
7184 		nat->nat_nsport = htons(frnat.fin_data[0]);
7185 		nat->nat_ndport = htons(frnat.fin_data[1]);
7186 	} else if ((nat->nat_flags & IPN_ICMPQUERY) != 0) {
7187 		nat->nat_nicmpid = frnat.fin_data[1];
7188 	}
7189 
7190 	nat->nat_pr[fin->fin_out] = fin->fin_p;
7191 	nat->nat_pr[1 - fin->fin_out] = p;
7192 
7193 	if (np->in_redir & NAT_REDIRECT)
7194 		nat->nat_dir = NAT_DIVERTIN;
7195 	else
7196 		nat->nat_dir = NAT_DIVERTOUT;
7197 
7198 	return (0);
7199 }
7200 
7201 
7202 /* ------------------------------------------------------------------------ */
7203 /* Function:    nat_builddivertmp                                           */
7204 /* Returns:     int - -1 == error, 0 == success                             */
7205 /* Parameters:  softn(I) - pointer to NAT context structure                 */
7206 /*              np(I)    - pointer to a NAT rule                            */
7207 /*                                                                          */
7208 /* For divert rules, a skeleton packet representing what will be prepended  */
7209 /* to the real packet is created.  Even though we don't have the full       */
7210 /* packet here, a checksum is calculated that we update later when we       */
7211 /* fill in the final details.  At present a 0 checksum for UDP is being set */
7212 /* here because it is expected that divert will be used for localhost.      */
7213 /* ------------------------------------------------------------------------ */
7214 static int
ipf_nat_builddivertmp(ipf_nat_softc_t * softn,ipnat_t * np)7215 ipf_nat_builddivertmp(ipf_nat_softc_t *softn, ipnat_t *np)
7216 {
7217 	udphdr_t *uh;
7218 	size_t len;
7219 	ip_t *ip;
7220 
7221 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
7222 		len = sizeof(ip_t) + sizeof(udphdr_t);
7223 	else
7224 		len = sizeof(ip_t);
7225 
7226 	ALLOC_MB_T(np->in_divmp, len);
7227 	if (np->in_divmp == NULL) {
7228 		NBUMPD(ipf_nat_stats, ns_divert_build);
7229 		return (-1);
7230 	}
7231 
7232 	/*
7233 	 * First, the header to get the packet diverted to the new destination
7234 	 */
7235 	ip = MTOD(np->in_divmp, ip_t *);
7236 	IP_V_A(ip, 4);
7237 	IP_HL_A(ip, 5);
7238 	ip->ip_tos = 0;
7239 	if ((np->in_redir & NAT_DIVERTUDP) != 0)
7240 		ip->ip_p = IPPROTO_UDP;
7241 	else
7242 		ip->ip_p = IPPROTO_IPIP;
7243 	ip->ip_ttl = 255;
7244 	ip->ip_off = 0;
7245 	ip->ip_sum = 0;
7246 	ip->ip_len = htons(len);
7247 	ip->ip_id = 0;
7248 	ip->ip_src.s_addr = htonl(np->in_snip);
7249 	ip->ip_dst.s_addr = htonl(np->in_dnip);
7250 	ip->ip_sum = ipf_cksum((u_short *)ip, sizeof(*ip));
7251 
7252 	if (np->in_redir & NAT_DIVERTUDP) {
7253 		uh = (udphdr_t *)(ip + 1);
7254 		uh->uh_sum = 0;
7255 		uh->uh_ulen = 8;
7256 		uh->uh_sport = htons(np->in_spnext);
7257 		uh->uh_dport = htons(np->in_dpnext);
7258 	}
7259 
7260 	return (0);
7261 }
7262 
7263 
7264 #define	MINDECAP	(sizeof(ip_t) + sizeof(udphdr_t) + sizeof(ip_t))
7265 
7266 /* ------------------------------------------------------------------------ */
7267 /* Function:    nat_decap                                                   */
7268 /* Returns:     int - -1 == error, 0 == success                             */
7269 /* Parameters:  fin(I) - pointer to packet information                      */
7270 /*              nat(I) - pointer to current NAT session                     */
7271 /*                                                                          */
7272 /* This function is responsible for undoing a packet's encapsulation in the */
7273 /* reverse of an encap/divert rule.  After removing the outer encapsulation */
7274 /* it is necessary to call ipf_makefrip() again so that the contents of 'fin'*/
7275 /* match the "new" packet as it may still be used by IPFilter elsewhere.    */
7276 /* We use "dir" here as the basis for some of the expectations about the    */
7277 /* outer header.  If we return an error, the goal is to leave the original  */
7278 /* packet information undisturbed - this falls short at the end where we'd  */
7279 /* need to back a backup copy of "fin" - expensive.                         */
7280 /* ------------------------------------------------------------------------ */
7281 static int
ipf_nat_decap(fr_info_t * fin,nat_t * nat)7282 ipf_nat_decap(fr_info_t *fin, nat_t *nat)
7283 {
7284 	ipf_main_softc_t *softc = fin->fin_main_soft;
7285 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7286 	char *hdr;
7287 	int hlen;
7288 	int skip;
7289 	mb_t *m;
7290 
7291 	if ((fin->fin_flx & FI_ICMPERR) != 0) {
7292 		/*
7293 		 * ICMP packets don't get decapsulated, instead what we need
7294 		 * to do is change the ICMP reply from including (in the data
7295 		 * portion for errors) the encapsulated packet that we sent
7296 		 * out to something that resembles the original packet prior
7297 		 * to encapsulation.  This isn't done here - all we're doing
7298 		 * here is changing the outer address to ensure that it gets
7299 		 * targetted back to the correct system.
7300 		 */
7301 
7302 		if (nat->nat_dir & NAT_OUTBOUND) {
7303 			u_32_t sum1, sum2, sumd;
7304 
7305 			sum1 = ntohl(fin->fin_daddr);
7306 			sum2 = ntohl(nat->nat_osrcaddr);
7307 			CALC_SUMD(sum1, sum2, sumd);
7308 			fin->fin_ip->ip_dst = nat->nat_osrcip;
7309 			fin->fin_daddr = nat->nat_osrcaddr;
7310 #if !defined(_KERNEL) || SOLARIS
7311 			ipf_fix_outcksum(0, &fin->fin_ip->ip_sum, sumd, 0);
7312 #endif
7313 		}
7314 		return (0);
7315 	}
7316 
7317 	m = fin->fin_m;
7318 	skip = fin->fin_hlen;
7319 
7320 	switch (nat->nat_dir)
7321 	{
7322 	case NAT_DIVERTIN :
7323 	case NAT_DIVERTOUT :
7324 		if (fin->fin_plen < MINDECAP)
7325 			return (-1);
7326 		skip += sizeof(udphdr_t);
7327 		break;
7328 
7329 	case NAT_ENCAPIN :
7330 	case NAT_ENCAPOUT :
7331 		if (fin->fin_plen < (skip + sizeof(ip_t)))
7332 			return (-1);
7333 		break;
7334 	default :
7335 		return (-1);
7336 		/* NOTREACHED */
7337 	}
7338 
7339 	/*
7340 	 * The aim here is to keep the original packet details in "fin" for
7341 	 * as long as possible so that returning with an error is for the
7342 	 * original packet and there is little undoing work to do.
7343 	 */
7344 	if (M_LEN(m) < skip + sizeof(ip_t)) {
7345 		if (ipf_pr_pullup(fin, skip + sizeof(ip_t)) == -1)
7346 			return (-1);
7347 	}
7348 
7349 	hdr = MTOD(fin->fin_m, char *);
7350 	fin->fin_ip = (ip_t *)(hdr + skip);
7351 	hlen = IP_HL(fin->fin_ip) << 2;
7352 
7353 	if (ipf_pr_pullup(fin, skip + hlen) == -1) {
7354 		NBUMPSIDED(fin->fin_out, ns_decap_pullup);
7355 		return (-1);
7356 	}
7357 
7358 	fin->fin_hlen = hlen;
7359 	fin->fin_dlen -= skip;
7360 	fin->fin_plen -= skip;
7361 	fin->fin_ipoff += skip;
7362 
7363 	if (ipf_makefrip(hlen, (ip_t *)hdr, fin) == -1) {
7364 		NBUMPSIDED(fin->fin_out, ns_decap_bad);
7365 		return (-1);
7366 	}
7367 
7368 	return (skip);
7369 }
7370 
7371 
7372 /* ------------------------------------------------------------------------ */
7373 /* Function:    nat_nextaddr                                                */
7374 /* Returns:     int - -1 == bad input (no new address),                     */
7375 /*                     0 == success and dst has new address                 */
7376 /* Parameters:  fin(I) - pointer to packet information                      */
7377 /*              na(I)  - how to generate new address                        */
7378 /*              old(I) - original address being replaced                    */
7379 /*              dst(O) - where to put the new address                       */
7380 /* Write Lock:  ipf_nat                                                     */
7381 /*                                                                          */
7382 /* This function uses the contents of the "na" structure, in combination    */
7383 /* with "old" to produce a new address to store in "dst".  Not all of the   */
7384 /* possible uses of "na" will result in a new address.                      */
7385 /* ------------------------------------------------------------------------ */
7386 static int
ipf_nat_nextaddr(fr_info_t * fin,nat_addr_t * na,u_32_t * old,u_32_t * dst)7387 ipf_nat_nextaddr(fr_info_t *fin, nat_addr_t *na, u_32_t *old, u_32_t *dst)
7388 {
7389 	ipf_main_softc_t *softc = fin->fin_main_soft;
7390 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7391 	u_32_t new;
7392 	i6addr_t newip;
7393 	int error;
7394 
7395 	new = 0;
7396 
7397 	switch (na->na_atype)
7398 	{
7399 	case FRI_RANGE :
7400 	case FRI_NETMASKED :
7401 	case FRI_DYNAMIC :
7402 	case FRI_NORMAL :
7403 	case FRI_LOOKUP :
7404 		break;
7405 
7406 	case FRI_BROADCAST :
7407 	case FRI_PEERADDR :
7408 	case FRI_NETWORK :
7409 	default :
7410 		DT4(ns_na_atype, fr_info_t *, fin, nat_addr_t *, na, u_32_t *, old, u_32_t *, new);
7411 		return (-1);
7412 	}
7413 
7414 	error = -1;
7415 
7416 	if (na->na_atype == FRI_LOOKUP) {
7417 		if (na->na_type == IPLT_DSTLIST) {
7418 			error = ipf_dstlist_select_node(fin, na->na_ptr, dst,
7419 							NULL);
7420 		} else {
7421 			NBUMPSIDE(fin->fin_out, ns_badnextaddr);
7422 			DT4(ns_badnextaddr_1, fr_info_t *, fin, nat_addr_t *, na, u_32_t *, old, u_32_t *, new);
7423 		}
7424 
7425 	} else if (na->na_atype == IPLT_NONE) {
7426 		/*
7427 		 * 0/0 as the new address means leave it alone.
7428 		 */
7429 		if (na->na_addr[0].in4.s_addr == 0 &&
7430 		    na->na_addr[1].in4.s_addr == 0) {
7431 			new = *old;
7432 
7433 		/*
7434 		 * 0/32 means get the interface's address
7435 		 */
7436 		} else if (na->na_addr[0].in4.s_addr == 0 &&
7437 			   na->na_addr[1].in4.s_addr == 0xffffffff) {
7438 			if (ipf_ifpaddr(softc, 4, na->na_atype,
7439 					fin->fin_ifp, &newip, NULL) == -1) {
7440 				NBUMPSIDED(fin->fin_out, ns_ifpaddrfail);
7441 				DT4(ns_ifpaddrfail, fr_info_t *, fin, nat_addr_t *, na, u_32_t *, old, u_32_t *, new);
7442 				return (-1);
7443 			}
7444 			new = newip.in4.s_addr;
7445 		} else {
7446 			new = htonl(na->na_nextip);
7447 		}
7448 		*dst = new;
7449 		error = 0;
7450 
7451 	} else {
7452 		NBUMPSIDE(fin->fin_out, ns_badnextaddr);
7453 		DT4(ns_badnextaddr_2, fr_info_t *, fin, nat_addr_t *, na, u_32_t *, old, u_32_t *, new);
7454 	}
7455 
7456 	return (error);
7457 }
7458 
7459 
7460 /* ------------------------------------------------------------------------ */
7461 /* Function:    nat_nextaddrinit                                            */
7462 /* Returns:     int - 0 == success, else error number                       */
7463 /* Parameters:  softc(I) - pointer to soft context main structure           */
7464 /*              na(I)      - NAT address information for generating new addr*/
7465 /*              initial(I) - flag indicating if it is the first call for    */
7466 /*                           this "na" structure.                           */
7467 /*              ifp(I)     - network interface to derive address            */
7468 /*                           information from.                              */
7469 /*                                                                          */
7470 /* This function is expected to be called in two scenarious: when a new NAT */
7471 /* rule is loaded into the kernel and when the list of NAT rules is sync'd  */
7472 /* up with the valid network interfaces (possibly due to them changing.)    */
7473 /* To distinguish between these, the "initial" parameter is used.  If it is */
7474 /* 1 then this indicates the rule has just been reloaded and 0 for when we  */
7475 /* are updating information.  This difference is important because in       */
7476 /* instances where we are not updating address information associated with  */
7477 /* a network interface, we don't want to disturb what the "next" address to */
7478 /* come out of ipf_nat_nextaddr() will be.                                  */
7479 /* ------------------------------------------------------------------------ */
7480 static int
ipf_nat_nextaddrinit(ipf_main_softc_t * softc,char * base,nat_addr_t * na,int initial,void * ifp)7481 ipf_nat_nextaddrinit(ipf_main_softc_t *softc, char *base, nat_addr_t *na,
7482 	int initial, void *ifp)
7483 {
7484 
7485 	switch (na->na_atype)
7486 	{
7487 	case FRI_LOOKUP :
7488 		if (na->na_subtype == 0) {
7489 			na->na_ptr = ipf_lookup_res_num(softc, IPL_LOGNAT,
7490 							na->na_type,
7491 							na->na_num,
7492 							&na->na_func);
7493 		} else if (na->na_subtype == 1) {
7494 			na->na_ptr = ipf_lookup_res_name(softc, IPL_LOGNAT,
7495 							 na->na_type,
7496 							 base + na->na_num,
7497 							 &na->na_func);
7498 		}
7499 		if (na->na_func == NULL) {
7500 			IPFERROR(60060);
7501 			return (ESRCH);
7502 		}
7503 		if (na->na_ptr == NULL) {
7504 			IPFERROR(60056);
7505 			return (ESRCH);
7506 		}
7507 		break;
7508 
7509 	case FRI_DYNAMIC :
7510 	case FRI_BROADCAST :
7511 	case FRI_NETWORK :
7512 	case FRI_NETMASKED :
7513 	case FRI_PEERADDR :
7514 		if (ifp != NULL)
7515 			(void )ipf_ifpaddr(softc, 4, na->na_atype, ifp,
7516 					   &na->na_addr[0], &na->na_addr[1]);
7517 		break;
7518 
7519 	case FRI_SPLIT :
7520 	case FRI_RANGE :
7521 		if (initial)
7522 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
7523 		break;
7524 
7525 	case FRI_NONE :
7526 		na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
7527 		return (0);
7528 
7529 	case FRI_NORMAL :
7530 		na->na_addr[0].in4.s_addr &= na->na_addr[1].in4.s_addr;
7531 		break;
7532 
7533 	default :
7534 		IPFERROR(60054);
7535 		return (EINVAL);
7536 	}
7537 
7538 	if (initial && (na->na_atype == FRI_NORMAL)) {
7539 		if (na->na_addr[0].in4.s_addr == 0) {
7540 			if ((na->na_addr[1].in4.s_addr == 0xffffffff) ||
7541 			    (na->na_addr[1].in4.s_addr == 0)) {
7542 				return (0);
7543 			}
7544 		}
7545 
7546 		if (na->na_addr[1].in4.s_addr == 0xffffffff) {
7547 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr);
7548 		} else {
7549 			na->na_nextip = ntohl(na->na_addr[0].in4.s_addr) + 1;
7550 		}
7551 	}
7552 
7553 	return (0);
7554 }
7555 
7556 
7557 /* ------------------------------------------------------------------------ */
7558 /* Function:    ipf_nat_matchflush                                          */
7559 /* Returns:     int - -1 == error, 0 == success                             */
7560 /* Parameters:  softc(I) - pointer to soft context main structure           */
7561 /*              softn(I) - pointer to NAT context structure                 */
7562 /*              nat(I)   - pointer to current NAT session                   */
7563 /*                                                                          */
7564 /* ------------------------------------------------------------------------ */
7565 static int
ipf_nat_matchflush(ipf_main_softc_t * softc,ipf_nat_softc_t * softn,caddr_t data)7566 ipf_nat_matchflush(ipf_main_softc_t *softc, ipf_nat_softc_t *softn,
7567 	caddr_t data)
7568 {
7569 	int *array, flushed, error;
7570 	nat_t *nat, *natnext;
7571 	ipfobj_t obj;
7572 
7573 	error = ipf_matcharray_load(softc, data, &obj, &array);
7574 	if (error != 0)
7575 		return (error);
7576 
7577 	flushed = 0;
7578 
7579 	for (nat = softn->ipf_nat_instances; nat != NULL; nat = natnext) {
7580 		natnext = nat->nat_next;
7581 		if (ipf_nat_matcharray(nat, array, softc->ipf_ticks) == 0) {
7582 			ipf_nat_delete(softc, nat, NL_FLUSH);
7583 			flushed++;
7584 		}
7585 	}
7586 
7587 	obj.ipfo_retval = flushed;
7588 	error = BCOPYOUT(&obj, data, sizeof(obj));
7589 
7590 	KFREES(array, array[0] * sizeof(*array));
7591 
7592 	return (error);
7593 }
7594 
7595 
7596 /* ------------------------------------------------------------------------ */
7597 /* Function:    ipf_nat_matcharray                                          */
7598 /* Returns:     int - -1 == error, 0 == success                             */
7599 /* Parameters:  fin(I) - pointer to packet information                      */
7600 /*              nat(I) - pointer to current NAT session                     */
7601 /*                                                                          */
7602 /* ------------------------------------------------------------------------ */
7603 static int
ipf_nat_matcharray(nat_t * nat,int * array,u_long ticks)7604 ipf_nat_matcharray(nat_t *nat, int *array, u_long ticks)
7605 {
7606 	int i, n, *x, e, p;
7607 
7608 	e = 0;
7609 	n = array[0];
7610 	x = array + 1;
7611 
7612 	for (; n > 0; x += 3 + x[2]) {
7613 		if (x[0] == IPF_EXP_END)
7614 			break;
7615 		e = 0;
7616 
7617 		n -= x[2] + 3;
7618 		if (n < 0)
7619 			break;
7620 
7621 		p = x[0] >> 16;
7622 		if (p != 0 && p != nat->nat_pr[1])
7623 			break;
7624 
7625 		switch (x[0])
7626 		{
7627 		case IPF_EXP_IP_PR :
7628 			for (i = 0; !e && i < x[2]; i++) {
7629 				e |= (nat->nat_pr[1] == x[i + 3]);
7630 			}
7631 			break;
7632 
7633 		case IPF_EXP_IP_SRCADDR :
7634 			if (nat->nat_v[0] == 4) {
7635 				for (i = 0; !e && i < x[2]; i++) {
7636 					e |= ((nat->nat_osrcaddr & x[i + 4]) ==
7637 					      x[i + 3]);
7638 				}
7639 			}
7640 			if (nat->nat_v[1] == 4) {
7641 				for (i = 0; !e && i < x[2]; i++) {
7642 					e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
7643 					      x[i + 3]);
7644 				}
7645 			}
7646 			break;
7647 
7648 		case IPF_EXP_IP_DSTADDR :
7649 			if (nat->nat_v[0] == 4) {
7650 				for (i = 0; !e && i < x[2]; i++) {
7651 					e |= ((nat->nat_odstaddr & x[i + 4]) ==
7652 					      x[i + 3]);
7653 				}
7654 			}
7655 			if (nat->nat_v[1] == 4) {
7656 				for (i = 0; !e && i < x[2]; i++) {
7657 					e |= ((nat->nat_ndstaddr & x[i + 4]) ==
7658 					      x[i + 3]);
7659 				}
7660 			}
7661 			break;
7662 
7663 		case IPF_EXP_IP_ADDR :
7664 			for (i = 0; !e && i < x[2]; i++) {
7665 				if (nat->nat_v[0] == 4) {
7666 					e |= ((nat->nat_osrcaddr & x[i + 4]) ==
7667 					      x[i + 3]);
7668 				}
7669 				if (nat->nat_v[1] == 4) {
7670 					e |= ((nat->nat_nsrcaddr & x[i + 4]) ==
7671 					      x[i + 3]);
7672 				}
7673 				if (nat->nat_v[0] == 4) {
7674 					e |= ((nat->nat_odstaddr & x[i + 4]) ==
7675 					      x[i + 3]);
7676 				}
7677 				if (nat->nat_v[1] == 4) {
7678 					e |= ((nat->nat_ndstaddr & x[i + 4]) ==
7679 					      x[i + 3]);
7680 				}
7681 			}
7682 			break;
7683 
7684 #ifdef USE_INET6
7685 		case IPF_EXP_IP6_SRCADDR :
7686 			if (nat->nat_v[0] == 6) {
7687 				for (i = 0; !e && i < x[3]; i++) {
7688 					e |= IP6_MASKEQ(&nat->nat_osrc6,
7689 							x + i + 7, x + i + 3);
7690 				}
7691 			}
7692 			if (nat->nat_v[1] == 6) {
7693 				for (i = 0; !e && i < x[3]; i++) {
7694 					e |= IP6_MASKEQ(&nat->nat_nsrc6,
7695 							x + i + 7, x + i + 3);
7696 				}
7697 			}
7698 			break;
7699 
7700 		case IPF_EXP_IP6_DSTADDR :
7701 			if (nat->nat_v[0] == 6) {
7702 				for (i = 0; !e && i < x[3]; i++) {
7703 					e |= IP6_MASKEQ(&nat->nat_odst6,
7704 							x + i + 7,
7705 							x + i + 3);
7706 				}
7707 			}
7708 			if (nat->nat_v[1] == 6) {
7709 				for (i = 0; !e && i < x[3]; i++) {
7710 					e |= IP6_MASKEQ(&nat->nat_ndst6,
7711 							x + i + 7,
7712 							x + i + 3);
7713 				}
7714 			}
7715 			break;
7716 
7717 		case IPF_EXP_IP6_ADDR :
7718 			for (i = 0; !e && i < x[3]; i++) {
7719 				if (nat->nat_v[0] == 6) {
7720 					e |= IP6_MASKEQ(&nat->nat_osrc6,
7721 							x + i + 7,
7722 							x + i + 3);
7723 				}
7724 				if (nat->nat_v[0] == 6) {
7725 					e |= IP6_MASKEQ(&nat->nat_odst6,
7726 							x + i + 7,
7727 							x + i + 3);
7728 				}
7729 				if (nat->nat_v[1] == 6) {
7730 					e |= IP6_MASKEQ(&nat->nat_nsrc6,
7731 							x + i + 7,
7732 							x + i + 3);
7733 				}
7734 				if (nat->nat_v[1] == 6) {
7735 					e |= IP6_MASKEQ(&nat->nat_ndst6,
7736 							x + i + 7,
7737 							x + i + 3);
7738 				}
7739 			}
7740 			break;
7741 #endif
7742 
7743 		case IPF_EXP_UDP_PORT :
7744 		case IPF_EXP_TCP_PORT :
7745 			for (i = 0; !e && i < x[2]; i++) {
7746 				e |= (nat->nat_nsport == x[i + 3]) ||
7747 				     (nat->nat_ndport == x[i + 3]);
7748 			}
7749 			break;
7750 
7751 		case IPF_EXP_UDP_SPORT :
7752 		case IPF_EXP_TCP_SPORT :
7753 			for (i = 0; !e && i < x[2]; i++) {
7754 				e |= (nat->nat_nsport == x[i + 3]);
7755 			}
7756 			break;
7757 
7758 		case IPF_EXP_UDP_DPORT :
7759 		case IPF_EXP_TCP_DPORT :
7760 			for (i = 0; !e && i < x[2]; i++) {
7761 				e |= (nat->nat_ndport == x[i + 3]);
7762 			}
7763 			break;
7764 
7765 		case IPF_EXP_TCP_STATE :
7766 			for (i = 0; !e && i < x[2]; i++) {
7767 				e |= (nat->nat_tcpstate[0] == x[i + 3]) ||
7768 				     (nat->nat_tcpstate[1] == x[i + 3]);
7769 			}
7770 			break;
7771 
7772 		case IPF_EXP_IDLE_GT :
7773 			e |= (ticks - nat->nat_touched > x[3]);
7774 			break;
7775 		}
7776 		e ^= x[1];
7777 
7778 		if (!e)
7779 			break;
7780 	}
7781 
7782 	return (e);
7783 }
7784 
7785 
7786 /* ------------------------------------------------------------------------ */
7787 /* Function:    ipf_nat_gettable                                            */
7788 /* Returns:     int     - 0 = success, else error                           */
7789 /* Parameters:  softc(I) - pointer to soft context main structure           */
7790 /*              softn(I) - pointer to NAT context structure                 */
7791 /*              data(I)  - pointer to ioctl data                            */
7792 /*                                                                          */
7793 /* This function handles ioctl requests for tables of nat information.      */
7794 /* At present the only table it deals with is the hash bucket statistics.   */
7795 /* ------------------------------------------------------------------------ */
7796 static int
ipf_nat_gettable(ipf_main_softc_t * softc,ipf_nat_softc_t * softn,char * data)7797 ipf_nat_gettable(ipf_main_softc_t *softc, ipf_nat_softc_t *softn, char *data)
7798 {
7799 	ipftable_t table;
7800 	int error;
7801 
7802 	error = ipf_inobj(softc, data, NULL, &table, IPFOBJ_GTABLE);
7803 	if (error != 0)
7804 		return (error);
7805 
7806 	switch (table.ita_type)
7807 	{
7808 	case IPFTABLE_BUCKETS_NATIN :
7809 		error = COPYOUT(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
7810 				table.ita_table,
7811 				softn->ipf_nat_table_sz * sizeof(u_int));
7812 		break;
7813 
7814 	case IPFTABLE_BUCKETS_NATOUT :
7815 		error = COPYOUT(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
7816 				table.ita_table,
7817 				softn->ipf_nat_table_sz * sizeof(u_int));
7818 		break;
7819 
7820 	default :
7821 		IPFERROR(60058);
7822 		return (EINVAL);
7823 	}
7824 
7825 	if (error != 0) {
7826 		IPFERROR(60059);
7827 		error = EFAULT;
7828 	}
7829 	return (error);
7830 }
7831 
7832 
7833 /* ------------------------------------------------------------------------ */
7834 /* Function:    ipf_nat_settimeout                                          */
7835 /* Returns:     int  - 0 = success, else failure			    */
7836 /* Parameters:  softc(I) - pointer to soft context main structure           */
7837 /*              t(I) - pointer to tunable                                   */
7838 /*              p(I) - pointer to new tuning data                           */
7839 /*                                                                          */
7840 /* Apply the timeout change to the NAT timeout queues.                      */
7841 /* ------------------------------------------------------------------------ */
7842 int
ipf_nat_settimeout(struct ipf_main_softc_s * softc,ipftuneable_t * t,ipftuneval_t * p)7843 ipf_nat_settimeout(struct ipf_main_softc_s *softc, ipftuneable_t *t,
7844 	ipftuneval_t *p)
7845 {
7846 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7847 
7848 	if (!strncmp(t->ipft_name, "tcp_", 4))
7849 		return (ipf_settimeout_tcp(t, p, softn->ipf_nat_tcptq));
7850 
7851 	if (!strcmp(t->ipft_name, "udp_timeout")) {
7852 		ipf_apply_timeout(&softn->ipf_nat_udptq, p->ipftu_int);
7853 	} else if (!strcmp(t->ipft_name, "udp_ack_timeout")) {
7854 		ipf_apply_timeout(&softn->ipf_nat_udpacktq, p->ipftu_int);
7855 	} else if (!strcmp(t->ipft_name, "icmp_timeout")) {
7856 		ipf_apply_timeout(&softn->ipf_nat_icmptq, p->ipftu_int);
7857 	} else if (!strcmp(t->ipft_name, "icmp_ack_timeout")) {
7858 		ipf_apply_timeout(&softn->ipf_nat_icmpacktq, p->ipftu_int);
7859 	} else if (!strcmp(t->ipft_name, "ip_timeout")) {
7860 		ipf_apply_timeout(&softn->ipf_nat_iptq, p->ipftu_int);
7861 	} else {
7862 		IPFERROR(60062);
7863 		return (ESRCH);
7864 	}
7865 	return (0);
7866 }
7867 
7868 
7869 /* ------------------------------------------------------------------------ */
7870 /* Function:    ipf_nat_rehash                                              */
7871 /* Returns:     int  - 0 = success, else failure			    */
7872 /* Parameters:  softc(I) - pointer to soft context main structure           */
7873 /*              t(I) - pointer to tunable                                   */
7874 /*              p(I) - pointer to new tuning data                           */
7875 /*                                                                          */
7876 /* To change the size of the basic NAT table, we need to first allocate the */
7877 /* new tables (lest it fails and we've got nowhere to store all of the NAT  */
7878 /* sessions currently active) and then walk through the entire list and     */
7879 /* insert them into the table.  There are two tables here: an inbound one   */
7880 /* and an outbound one.  Each NAT entry goes into each table once.          */
7881 /* ------------------------------------------------------------------------ */
7882 int
ipf_nat_rehash(ipf_main_softc_t * softc,ipftuneable_t * t,ipftuneval_t * p)7883 ipf_nat_rehash(ipf_main_softc_t *softc, ipftuneable_t *t, ipftuneval_t *p)
7884 {
7885 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
7886 	nat_t **newtab[2], *nat, **natp;
7887 	u_int *bucketlens[2];
7888 	u_int maxbucket;
7889 	u_int newsize;
7890 	int error;
7891 	u_int hv;
7892 	int i;
7893 
7894 	newsize = p->ipftu_int;
7895 	/*
7896 	 * In case there is nothing to do...
7897 	 */
7898 	if (newsize == softn->ipf_nat_table_sz)
7899 		return (0);
7900 
7901 	newtab[0] = NULL;
7902 	newtab[1] = NULL;
7903 	bucketlens[0] = NULL;
7904 	bucketlens[1] = NULL;
7905 	/*
7906 	 * 4 tables depend on the NAT table size: the inbound looking table,
7907 	 * the outbound lookup table and the hash chain length for each.
7908 	 */
7909 	KMALLOCS(newtab[0], nat_t **, newsize * sizeof(nat_t *));
7910 	if (newtab[0] == NULL) {
7911 		error = 60063;
7912 		goto badrehash;
7913 	}
7914 
7915 	KMALLOCS(newtab[1], nat_t **, newsize * sizeof(nat_t *));
7916 	if (newtab[1] == NULL) {
7917 		error = 60064;
7918 		goto badrehash;
7919 	}
7920 
7921 	KMALLOCS(bucketlens[0], u_int *, newsize * sizeof(u_int));
7922 	if (bucketlens[0] == NULL) {
7923 		error = 60065;
7924 		goto badrehash;
7925 	}
7926 
7927 	KMALLOCS(bucketlens[1], u_int *, newsize * sizeof(u_int));
7928 	if (bucketlens[1] == NULL) {
7929 		error = 60066;
7930 		goto badrehash;
7931 	}
7932 
7933 	/*
7934 	 * Recalculate the maximum length based on the new size.
7935 	 */
7936 	for (maxbucket = 0, i = newsize; i > 0; i >>= 1)
7937 		maxbucket++;
7938 	maxbucket *= 2;
7939 
7940 	bzero((char *)newtab[0], newsize * sizeof(nat_t *));
7941 	bzero((char *)newtab[1], newsize * sizeof(nat_t *));
7942 	bzero((char *)bucketlens[0], newsize * sizeof(u_int));
7943 	bzero((char *)bucketlens[1], newsize * sizeof(u_int));
7944 
7945 	WRITE_ENTER(&softc->ipf_nat);
7946 
7947 	if (softn->ipf_nat_table[0] != NULL) {
7948 		KFREES(softn->ipf_nat_table[0],
7949 		       softn->ipf_nat_table_sz *
7950 		       sizeof(*softn->ipf_nat_table[0]));
7951 	}
7952 	softn->ipf_nat_table[0] = newtab[0];
7953 
7954 	if (softn->ipf_nat_table[1] != NULL) {
7955 		KFREES(softn->ipf_nat_table[1],
7956 		       softn->ipf_nat_table_sz *
7957 		       sizeof(*softn->ipf_nat_table[1]));
7958 	}
7959 	softn->ipf_nat_table[1] = newtab[1];
7960 
7961 	if (softn->ipf_nat_stats.ns_side[0].ns_bucketlen != NULL) {
7962 		KFREES(softn->ipf_nat_stats.ns_side[0].ns_bucketlen,
7963 		       softn->ipf_nat_table_sz * sizeof(u_int));
7964 	}
7965 	softn->ipf_nat_stats.ns_side[0].ns_bucketlen = bucketlens[0];
7966 
7967 	if (softn->ipf_nat_stats.ns_side[1].ns_bucketlen != NULL) {
7968 		KFREES(softn->ipf_nat_stats.ns_side[1].ns_bucketlen,
7969 		       softn->ipf_nat_table_sz * sizeof(u_int));
7970 	}
7971 	softn->ipf_nat_stats.ns_side[1].ns_bucketlen = bucketlens[1];
7972 
7973 #ifdef USE_INET6
7974 	if (softn->ipf_nat_stats.ns_side6[0].ns_bucketlen != NULL) {
7975 		KFREES(softn->ipf_nat_stats.ns_side6[0].ns_bucketlen,
7976 		       softn->ipf_nat_table_sz * sizeof(u_int));
7977 	}
7978 	softn->ipf_nat_stats.ns_side6[0].ns_bucketlen = bucketlens[0];
7979 
7980 	if (softn->ipf_nat_stats.ns_side6[1].ns_bucketlen != NULL) {
7981 		KFREES(softn->ipf_nat_stats.ns_side6[1].ns_bucketlen,
7982 		       softn->ipf_nat_table_sz * sizeof(u_int));
7983 	}
7984 	softn->ipf_nat_stats.ns_side6[1].ns_bucketlen = bucketlens[1];
7985 #endif
7986 
7987 	softn->ipf_nat_maxbucket = maxbucket;
7988 	softn->ipf_nat_table_sz = newsize;
7989 	/*
7990 	 * Walk through the entire list of NAT table entries and put them
7991 	 * in the new NAT table, somewhere.  Because we have a new table,
7992 	 * we need to restart the counter of how many chains are in use.
7993 	 */
7994 	softn->ipf_nat_stats.ns_side[0].ns_inuse = 0;
7995 	softn->ipf_nat_stats.ns_side[1].ns_inuse = 0;
7996 #ifdef USE_INET6
7997 	softn->ipf_nat_stats.ns_side6[0].ns_inuse = 0;
7998 	softn->ipf_nat_stats.ns_side6[1].ns_inuse = 0;
7999 #endif
8000 
8001 	for (nat = softn->ipf_nat_instances; nat != NULL; nat = nat->nat_next) {
8002 		nat->nat_hnext[0] = NULL;
8003 		nat->nat_phnext[0] = NULL;
8004 		hv = nat->nat_hv[0] % softn->ipf_nat_table_sz;
8005 
8006 		natp = &softn->ipf_nat_table[0][hv];
8007 		if (*natp) {
8008 			(*natp)->nat_phnext[0] = &nat->nat_hnext[0];
8009 		} else {
8010 			NBUMPSIDE(0, ns_inuse);
8011 		}
8012 		nat->nat_phnext[0] = natp;
8013 		nat->nat_hnext[0] = *natp;
8014 		*natp = nat;
8015 		NBUMPSIDE(0, ns_bucketlen[hv]);
8016 
8017 		nat->nat_hnext[1] = NULL;
8018 		nat->nat_phnext[1] = NULL;
8019 		hv = nat->nat_hv[1] % softn->ipf_nat_table_sz;
8020 
8021 		natp = &softn->ipf_nat_table[1][hv];
8022 		if (*natp) {
8023 			(*natp)->nat_phnext[1] = &nat->nat_hnext[1];
8024 		} else {
8025 			NBUMPSIDE(1, ns_inuse);
8026 		}
8027 		nat->nat_phnext[1] = natp;
8028 		nat->nat_hnext[1] = *natp;
8029 		*natp = nat;
8030 		NBUMPSIDE(1, ns_bucketlen[hv]);
8031 	}
8032 	RWLOCK_EXIT(&softc->ipf_nat);
8033 
8034 	return (0);
8035 
8036 badrehash:
8037 	if (bucketlens[1] != NULL) {
8038 		KFREES(bucketlens[0], newsize * sizeof(u_int));
8039 	}
8040 	if (bucketlens[0] != NULL) {
8041 		KFREES(bucketlens[0], newsize * sizeof(u_int));
8042 	}
8043 	if (newtab[0] != NULL) {
8044 		KFREES(newtab[0], newsize * sizeof(nat_t *));
8045 	}
8046 	if (newtab[1] != NULL) {
8047 		KFREES(newtab[1], newsize * sizeof(nat_t *));
8048 	}
8049 	IPFERROR(error);
8050 	return (ENOMEM);
8051 }
8052 
8053 
8054 /* ------------------------------------------------------------------------ */
8055 /* Function:    ipf_nat_rehash_rules                                        */
8056 /* Returns:     int  - 0 = success, else failure			    */
8057 /* Parameters:  softc(I) - pointer to soft context main structure           */
8058 /*              t(I) - pointer to tunable                                   */
8059 /*              p(I) - pointer to new tuning data                           */
8060 /*                                                                          */
8061 /* All of the NAT rules hang off of a hash table that is searched with a    */
8062 /* hash on address after the netmask is applied.  There is a different table*/
8063 /* for both inbound rules (rdr) and outbound (map.)  The resizing will only */
8064 /* affect one of these two tables.                                          */
8065 /* ------------------------------------------------------------------------ */
8066 int
ipf_nat_rehash_rules(ipf_main_softc_t * softc,ipftuneable_t * t,ipftuneval_t * p)8067 ipf_nat_rehash_rules(ipf_main_softc_t *softc, ipftuneable_t *t,
8068 	ipftuneval_t *p)
8069 {
8070 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
8071 	ipnat_t **newtab, *np, ***old, **npp;
8072 	u_int newsize;
8073 	u_int mask;
8074 	u_int hv;
8075 
8076 	newsize = p->ipftu_int;
8077 	/*
8078 	 * In case there is nothing to do...
8079 	 */
8080 	if (newsize == *t->ipft_pint)
8081 		return (0);
8082 
8083 	/*
8084 	 * All inbound rules have the NAT_REDIRECT bit set in in_redir and
8085 	 * all outbound rules have either NAT_MAP or MAT_MAPBLK set.
8086 	 * This if statement allows for some more generic code to be below,
8087 	 * rather than two huge gobs of code that almost do the same thing.
8088 	 */
8089 	if (t->ipft_pint == &softn->ipf_nat_rdrrules_sz) {
8090 		old = &softn->ipf_nat_rdr_rules;
8091 		mask = NAT_REDIRECT;
8092 	} else {
8093 		old = &softn->ipf_nat_map_rules;
8094 		mask = NAT_MAP|NAT_MAPBLK;
8095 	}
8096 
8097 	KMALLOCS(newtab, ipnat_t **, newsize * sizeof(ipnat_t *));
8098 	if (newtab == NULL) {
8099 		IPFERROR(60067);
8100 		return (ENOMEM);
8101 	}
8102 
8103 	bzero((char *)newtab, newsize * sizeof(ipnat_t *));
8104 
8105 	WRITE_ENTER(&softc->ipf_nat);
8106 
8107 	if (*old != NULL) {
8108 		KFREES(*old, *t->ipft_pint * sizeof(ipnat_t **));
8109 	}
8110 	*old = newtab;
8111 	*t->ipft_pint = newsize;
8112 
8113 	for (np = softn->ipf_nat_list; np != NULL; np = np->in_next) {
8114 		if ((np->in_redir & mask) == 0)
8115 			continue;
8116 
8117 		if (np->in_redir & NAT_REDIRECT) {
8118 			np->in_rnext = NULL;
8119 			hv = np->in_hv[0] % newsize;
8120 			for (npp = newtab + hv; *npp != NULL; )
8121 				npp = &(*npp)->in_rnext;
8122 			np->in_prnext = npp;
8123 			*npp = np;
8124 		}
8125 		if (np->in_redir & NAT_MAP) {
8126 			np->in_mnext = NULL;
8127 			hv = np->in_hv[1] % newsize;
8128 			for (npp = newtab + hv; *npp != NULL; )
8129 				npp = &(*npp)->in_mnext;
8130 			np->in_pmnext = npp;
8131 			*npp = np;
8132 		}
8133 
8134 	}
8135 	RWLOCK_EXIT(&softc->ipf_nat);
8136 
8137 	return (0);
8138 }
8139 
8140 
8141 /* ------------------------------------------------------------------------ */
8142 /* Function:    ipf_nat_hostmap_rehash                                      */
8143 /* Returns:     int  - 0 = success, else failure			    */
8144 /* Parameters:  softc(I) - pointer to soft context main structure           */
8145 /*              t(I) - pointer to tunable                                   */
8146 /*              p(I) - pointer to new tuning data                           */
8147 /*                                                                          */
8148 /* Allocate and populate a new hash table that will contain a reference to  */
8149 /* all of the active IP# translations currently in place.                   */
8150 /* ------------------------------------------------------------------------ */
8151 int
ipf_nat_hostmap_rehash(ipf_main_softc_t * softc,ipftuneable_t * t,ipftuneval_t * p)8152 ipf_nat_hostmap_rehash(ipf_main_softc_t *softc, ipftuneable_t *t,
8153 	ipftuneval_t *p)
8154 {
8155 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
8156 	hostmap_t *hm, **newtab;
8157 	u_int newsize;
8158 	u_int hv;
8159 
8160 	newsize = p->ipftu_int;
8161 	/*
8162 	 * In case there is nothing to do...
8163 	 */
8164 	if (newsize == *t->ipft_pint)
8165 		return (0);
8166 
8167 	KMALLOCS(newtab, hostmap_t **, newsize * sizeof(hostmap_t *));
8168 	if (newtab == NULL) {
8169 		IPFERROR(60068);
8170 		return (ENOMEM);
8171 	}
8172 
8173 	bzero((char *)newtab, newsize * sizeof(hostmap_t *));
8174 
8175 	WRITE_ENTER(&softc->ipf_nat);
8176 	if (softn->ipf_hm_maptable != NULL) {
8177 		KFREES(softn->ipf_hm_maptable,
8178 		       softn->ipf_nat_hostmap_sz * sizeof(hostmap_t *));
8179 	}
8180 	softn->ipf_hm_maptable = newtab;
8181 	softn->ipf_nat_hostmap_sz = newsize;
8182 
8183 	for (hm = softn->ipf_hm_maplist; hm != NULL; hm = hm->hm_next) {
8184 		hv = hm->hm_hv % softn->ipf_nat_hostmap_sz;
8185 		hm->hm_hnext = softn->ipf_hm_maptable[hv];
8186 		hm->hm_phnext = softn->ipf_hm_maptable + hv;
8187 		if (softn->ipf_hm_maptable[hv] != NULL)
8188 			softn->ipf_hm_maptable[hv]->hm_phnext = &hm->hm_hnext;
8189 		softn->ipf_hm_maptable[hv] = hm;
8190 	}
8191 	RWLOCK_EXIT(&softc->ipf_nat);
8192 
8193 	return (0);
8194 }
8195 
8196 
8197 /* ------------------------------------------------------------------------ */
8198 /* Function:    ipf_nat_add_tq                                              */
8199 /* Parameters:  softc(I) - pointer to soft context main structure           */
8200 /*                                                                          */
8201 /* ------------------------------------------------------------------------ */
8202 ipftq_t *
ipf_nat_add_tq(ipf_main_softc_t * softc,int ttl)8203 ipf_nat_add_tq(ipf_main_softc_t *softc, int ttl)
8204 {
8205 	ipf_nat_softc_t *softs = softc->ipf_nat_soft;
8206 
8207 	return (ipf_addtimeoutqueue(softc, &softs->ipf_nat_utqe, ttl));
8208 }
8209 
8210 /* ------------------------------------------------------------------------ */
8211 /* Function:    ipf_nat_uncreate                                            */
8212 /* Returns:     Nil                                                         */
8213 /* Parameters:  fin(I) - pointer to packet information                      */
8214 /*                                                                          */
8215 /* This function is used to remove a NAT entry from the NAT table when we   */
8216 /* decide that the create was actually in error. It is thus assumed that    */
8217 /* fin_flx will have both FI_NATED and FI_NATNEW set. Because we're dealing */
8218 /* with the translated packet (not the original), we have to reverse the    */
8219 /* lookup. Although doing the lookup is expensive (relatively speaking), it */
8220 /* is not anticipated that this will be a frequent occurance for normal     */
8221 /* traffic patterns.                                                        */
8222 /* ------------------------------------------------------------------------ */
8223 void
ipf_nat_uncreate(fr_info_t * fin)8224 ipf_nat_uncreate(fr_info_t *fin)
8225 {
8226 	ipf_main_softc_t *softc = fin->fin_main_soft;
8227 	ipf_nat_softc_t *softn = softc->ipf_nat_soft;
8228 	int nflags;
8229 	nat_t *nat;
8230 
8231 	switch (fin->fin_p)
8232 	{
8233 	case IPPROTO_TCP :
8234 		nflags = IPN_TCP;
8235 		break;
8236 	case IPPROTO_UDP :
8237 		nflags = IPN_UDP;
8238 		break;
8239 	default :
8240 		nflags = 0;
8241 		break;
8242 	}
8243 
8244 	WRITE_ENTER(&softc->ipf_nat);
8245 
8246 	if (fin->fin_out == 0) {
8247 		nat = ipf_nat_outlookup(fin, nflags, (u_int)fin->fin_p,
8248 					fin->fin_dst, fin->fin_src);
8249 	} else {
8250 		nat = ipf_nat_inlookup(fin, nflags, (u_int)fin->fin_p,
8251 				       fin->fin_src, fin->fin_dst);
8252 	}
8253 
8254 	if (nat != NULL) {
8255 		NBUMPSIDE(fin->fin_out, ns_uncreate[0]);
8256 		ipf_nat_delete(softc, nat, NL_DESTROY);
8257 	} else {
8258 		NBUMPSIDE(fin->fin_out, ns_uncreate[1]);
8259 	}
8260 
8261 	RWLOCK_EXIT(&softc->ipf_nat);
8262 }
8263 
8264 
8265 /* ------------------------------------------------------------------------ */
8266 /* Function:    ipf_nat_cmp_rules                                           */
8267 /* Returns:     int   - 0 == success, else rules do not match.              */
8268 /* Parameters:  n1(I) - first rule to compare                               */
8269 /*              n2(I) - first rule to compare                               */
8270 /*                                                                          */
8271 /* Compare two rules using pointers to each rule. A straight bcmp will not  */
8272 /* work as some fields (such as in_dst, in_pkts) actually do change once    */
8273 /* the rule has been loaded into the kernel. Whilst this function returns   */
8274 /* various non-zero returns, they're strictly to aid in debugging. Use of   */
8275 /* this function should simply care if the result is zero or not.           */
8276 /* ------------------------------------------------------------------------ */
8277 static int
ipf_nat_cmp_rules(ipnat_t * n1,ipnat_t * n2)8278 ipf_nat_cmp_rules(ipnat_t *n1, ipnat_t *n2)
8279 {
8280 	if (n1->in_size != n2->in_size)
8281 		return (1);
8282 
8283 	if (bcmp((char *)&n1->in_v, (char *)&n2->in_v,
8284 		 offsetof(ipnat_t, in_ndst) - offsetof(ipnat_t, in_v)) != 0)
8285 		return (2);
8286 
8287 	if (bcmp((char *)&n1->in_tuc, (char *)&n2->in_tuc,
8288 		 n1->in_size - offsetof(ipnat_t, in_tuc)) != 0)
8289 		return (3);
8290 	if (n1->in_ndst.na_atype != n2->in_ndst.na_atype)
8291 		return (5);
8292 	if (n1->in_ndst.na_function != n2->in_ndst.na_function)
8293 		return (6);
8294 	if (bcmp((char *)&n1->in_ndst.na_addr, (char *)&n2->in_ndst.na_addr,
8295 		 sizeof(n1->in_ndst.na_addr)))
8296 		return (7);
8297 	if (n1->in_nsrc.na_atype != n2->in_nsrc.na_atype)
8298 		return (8);
8299 	if (n1->in_nsrc.na_function != n2->in_nsrc.na_function)
8300 		return (9);
8301 	if (bcmp((char *)&n1->in_nsrc.na_addr, (char *)&n2->in_nsrc.na_addr,
8302 		 sizeof(n1->in_nsrc.na_addr)))
8303 		return (10);
8304 	if (n1->in_odst.na_atype != n2->in_odst.na_atype)
8305 		return (11);
8306 	if (n1->in_odst.na_function != n2->in_odst.na_function)
8307 		return (12);
8308 	if (bcmp((char *)&n1->in_odst.na_addr, (char *)&n2->in_odst.na_addr,
8309 		 sizeof(n1->in_odst.na_addr)))
8310 		return (13);
8311 	if (n1->in_osrc.na_atype != n2->in_osrc.na_atype)
8312 		return (14);
8313 	if (n1->in_osrc.na_function != n2->in_osrc.na_function)
8314 		return (15);
8315 	if (bcmp((char *)&n1->in_osrc.na_addr, (char *)&n2->in_osrc.na_addr,
8316 		 sizeof(n1->in_osrc.na_addr)))
8317 		return (16);
8318 	return (0);
8319 }
8320 
8321 
8322 /* ------------------------------------------------------------------------ */
8323 /* Function:    ipf_nat_rule_init                                           */
8324 /* Returns:     int   - 0 == success, else rules do not match.              */
8325 /* Parameters:  softc(I) - pointer to soft context main structure           */
8326 /*              softn(I) - pointer to NAT context structure                 */
8327 /*              n(I)     - first rule to compare                            */
8328 /*                                                                          */
8329 /* ------------------------------------------------------------------------ */
8330 static int
ipf_nat_rule_init(ipf_main_softc_t * softc,ipf_nat_softc_t * softn,ipnat_t * n)8331 ipf_nat_rule_init(ipf_main_softc_t *softc, ipf_nat_softc_t *softn,
8332 	ipnat_t *n)
8333 {
8334 	int error = 0;
8335 
8336 	if ((n->in_flags & IPN_SIPRANGE) != 0)
8337 		n->in_nsrcatype = FRI_RANGE;
8338 
8339 	if ((n->in_flags & IPN_DIPRANGE) != 0)
8340 		n->in_ndstatype = FRI_RANGE;
8341 
8342 	if ((n->in_flags & IPN_SPLIT) != 0)
8343 		n->in_ndstatype = FRI_SPLIT;
8344 
8345 	if ((n->in_redir & (NAT_MAP|NAT_REWRITE|NAT_DIVERTUDP)) != 0)
8346 		n->in_spnext = n->in_spmin;
8347 
8348 	if ((n->in_redir & (NAT_REWRITE|NAT_DIVERTUDP)) != 0) {
8349 		n->in_dpnext = n->in_dpmin;
8350 	} else if (n->in_redir == NAT_REDIRECT) {
8351 		n->in_dpnext = n->in_dpmin;
8352 	}
8353 
8354 	n->in_stepnext = 0;
8355 
8356 	switch (n->in_v[0])
8357 	{
8358 	case 4 :
8359 		error = ipf_nat_ruleaddrinit(softc, softn, n);
8360 		if (error != 0)
8361 			return (error);
8362 		break;
8363 #ifdef USE_INET6
8364 	case 6 :
8365 		error = ipf_nat6_ruleaddrinit(softc, softn, n);
8366 		if (error != 0)
8367 			return (error);
8368 		break;
8369 #endif
8370 	default :
8371 		break;
8372 	}
8373 
8374 	if (n->in_redir == (NAT_DIVERTUDP|NAT_MAP)) {
8375 		/*
8376 		 * Prerecord whether or not the destination of the divert
8377 		 * is local or not to the interface the packet is going
8378 		 * to be sent out.
8379 		 */
8380 		n->in_dlocal = ipf_deliverlocal(softc, n->in_v[1],
8381 						n->in_ifps[1], &n->in_ndstip6);
8382 	}
8383 
8384 	return (error);
8385 }
8386 
8387 
8388 /* ------------------------------------------------------------------------ */
8389 /* Function:    ipf_nat_rule_fini                                           */
8390 /* Returns:     int   - 0 == success, else rules do not match.              */
8391 /* Parameters:  softc(I) - pointer to soft context main structure           */
8392 /*              n(I)     - rule to work on                                  */
8393 /*                                                                          */
8394 /* This function is used to release any objects that were referenced during */
8395 /* the rule initialisation. This is useful both when free'ing the rule and  */
8396 /* when handling ioctls that need to initialise these fields but not        */
8397 /* actually use them after the ioctl processing has finished.               */
8398 /* ------------------------------------------------------------------------ */
8399 static void
ipf_nat_rule_fini(ipf_main_softc_t * softc,ipnat_t * n)8400 ipf_nat_rule_fini(ipf_main_softc_t *softc, ipnat_t *n)
8401 {
8402 	if (n->in_odst.na_atype == FRI_LOOKUP && n->in_odst.na_ptr != NULL)
8403 		ipf_lookup_deref(softc, n->in_odst.na_type, n->in_odst.na_ptr);
8404 
8405 	if (n->in_osrc.na_atype == FRI_LOOKUP && n->in_osrc.na_ptr != NULL)
8406 		ipf_lookup_deref(softc, n->in_osrc.na_type, n->in_osrc.na_ptr);
8407 
8408 	if (n->in_ndst.na_atype == FRI_LOOKUP && n->in_ndst.na_ptr != NULL)
8409 		ipf_lookup_deref(softc, n->in_ndst.na_type, n->in_ndst.na_ptr);
8410 
8411 	if (n->in_nsrc.na_atype == FRI_LOOKUP && n->in_nsrc.na_ptr != NULL)
8412 		ipf_lookup_deref(softc, n->in_nsrc.na_type, n->in_nsrc.na_ptr);
8413 
8414 	if (n->in_divmp != NULL)
8415 		FREE_MB_T(n->in_divmp);
8416 }
8417