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