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