nat.c revision 220802
1243730Srwatson/*
2243730Srwatson * Copyright (c) 2002-2003 Luigi Rizzo
3243730Srwatson * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4243730Srwatson * Copyright (c) 1994 Ugen J.S.Antsilevich
5243730Srwatson *
6243730Srwatson * Idea and grammar partially left from:
7243730Srwatson * Copyright (c) 1993 Daniel Boulet
8243730Srwatson *
9243730Srwatson * Redistribution and use in source forms, with and without modification,
10243730Srwatson * are permitted provided that this entire comment appears intact.
11243730Srwatson *
12243730Srwatson * Redistribution in binary form may occur without any restrictions.
13243730Srwatson * Obviously, it would be nice if you gave credit where credit is due
14243730Srwatson * but requiring it would be too onerous.
15243730Srwatson *
16243730Srwatson * This software is provided ``AS IS'' without any warranties of any kind.
17243730Srwatson *
18243730Srwatson * NEW command line interface for IP firewall facility
19243730Srwatson *
20243730Srwatson * $FreeBSD: head/sbin/ipfw/nat.c 220802 2011-04-18 21:18:22Z glebius $
21243730Srwatson *
22243730Srwatson * In-kernel nat support
23243730Srwatson */
24243730Srwatson
25243730Srwatson#include <sys/types.h>
26243730Srwatson#include <sys/socket.h>
27243730Srwatson#include <sys/sysctl.h>
28243730Srwatson
29243730Srwatson#include "ipfw2.h"
30243730Srwatson
31243730Srwatson#include <ctype.h>
32243730Srwatson#include <err.h>
33243730Srwatson#include <netdb.h>
34243730Srwatson#include <stdio.h>
35243730Srwatson#include <stdlib.h>
36243730Srwatson#include <string.h>
37243730Srwatson#include <sysexits.h>
38243730Srwatson
39243730Srwatson#define IPFW_INTERNAL	/* Access to protected structures in ip_fw.h. */
40243730Srwatson
41243730Srwatson#include <net/if.h>
42243730Srwatson#include <net/if_dl.h>
43243734Srwatson#include <net/route.h> /* def. of struct route */
44243730Srwatson#include <netinet/in.h>
45243730Srwatson#include <netinet/ip_fw.h>
46243730Srwatson#include <arpa/inet.h>
47243730Srwatson#include <alias.h>
48243730Srwatson
49243730Srwatsonstatic struct _s_x nat_params[] = {
50243730Srwatson	{ "ip",			TOK_IP },
51243730Srwatson	{ "if",			TOK_IF },
52243730Srwatson 	{ "log",		TOK_ALOG },
53243730Srwatson 	{ "deny_in",		TOK_DENY_INC },
54243730Srwatson 	{ "same_ports",		TOK_SAME_PORTS },
55243730Srwatson 	{ "unreg_only",		TOK_UNREG_ONLY },
56243730Srwatson 	{ "reset",		TOK_RESET_ADDR },
57243730Srwatson 	{ "reverse",		TOK_ALIAS_REV },
58243730Srwatson 	{ "proxy_only",		TOK_PROXY_ONLY },
59243730Srwatson	{ "redirect_addr",	TOK_REDIR_ADDR },
60243730Srwatson	{ "redirect_port",	TOK_REDIR_PORT },
61243730Srwatson	{ "redirect_proto",	TOK_REDIR_PROTO },
62243730Srwatson 	{ NULL, 0 }	/* terminator */
63243730Srwatson};
64243730Srwatson
65243730Srwatson
66243730Srwatson/*
67243730Srwatson * Search for interface with name "ifn", and fill n accordingly:
68243730Srwatson *
69243730Srwatson * n->ip	ip address of interface "ifn"
70243730Srwatson * n->if_name   copy of interface name "ifn"
71243730Srwatson */
72243730Srwatsonstatic void
73243730Srwatsonset_addr_dynamic(const char *ifn, struct cfg_nat *n)
74243730Srwatson{
75243730Srwatson	size_t needed;
76243730Srwatson	int mib[6];
77243730Srwatson	char *buf, *lim, *next;
78243730Srwatson	struct if_msghdr *ifm;
79243730Srwatson	struct ifa_msghdr *ifam;
80243730Srwatson	struct sockaddr_dl *sdl;
81243730Srwatson	struct sockaddr_in *sin;
82243730Srwatson	int ifIndex, ifMTU;
83243730Srwatson
84243730Srwatson	mib[0] = CTL_NET;
85243730Srwatson	mib[1] = PF_ROUTE;
86243730Srwatson	mib[2] = 0;
87243730Srwatson	mib[3] = AF_INET;
88243730Srwatson	mib[4] = NET_RT_IFLIST;
89243730Srwatson	mib[5] = 0;
90243730Srwatson/*
91 * Get interface data.
92 */
93	if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
94		err(1, "iflist-sysctl-estimate");
95	buf = safe_calloc(1, needed);
96	if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
97		err(1, "iflist-sysctl-get");
98	lim = buf + needed;
99/*
100 * Loop through interfaces until one with
101 * given name is found. This is done to
102 * find correct interface index for routing
103 * message processing.
104 */
105	ifIndex	= 0;
106	next = buf;
107	while (next < lim) {
108		ifm = (struct if_msghdr *)next;
109		next += ifm->ifm_msglen;
110		if (ifm->ifm_version != RTM_VERSION) {
111			if (co.verbose)
112				warnx("routing message version %d "
113				    "not understood", ifm->ifm_version);
114			continue;
115		}
116		if (ifm->ifm_type == RTM_IFINFO) {
117			sdl = (struct sockaddr_dl *)(ifm + 1);
118			if (strlen(ifn) == sdl->sdl_nlen &&
119			    strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
120				ifIndex = ifm->ifm_index;
121				ifMTU = ifm->ifm_data.ifi_mtu;
122				break;
123			}
124		}
125	}
126	if (!ifIndex)
127		errx(1, "unknown interface name %s", ifn);
128/*
129 * Get interface address.
130 */
131	sin = NULL;
132	while (next < lim) {
133		ifam = (struct ifa_msghdr *)next;
134		next += ifam->ifam_msglen;
135		if (ifam->ifam_version != RTM_VERSION) {
136			if (co.verbose)
137				warnx("routing message version %d "
138				    "not understood", ifam->ifam_version);
139			continue;
140		}
141		if (ifam->ifam_type != RTM_NEWADDR)
142			break;
143		if (ifam->ifam_addrs & RTA_IFA) {
144			int i;
145			char *cp = (char *)(ifam + 1);
146
147			for (i = 1; i < RTA_IFA; i <<= 1) {
148				if (ifam->ifam_addrs & i)
149					cp += SA_SIZE((struct sockaddr *)cp);
150			}
151			if (((struct sockaddr *)cp)->sa_family == AF_INET) {
152				sin = (struct sockaddr_in *)cp;
153				break;
154			}
155		}
156	}
157	if (sin == NULL)
158		errx(1, "%s: cannot get interface address", ifn);
159
160	n->ip = sin->sin_addr;
161	strncpy(n->if_name, ifn, IF_NAMESIZE);
162
163	free(buf);
164}
165
166/*
167 * XXX - The following functions, macros and definitions come from natd.c:
168 * it would be better to move them outside natd.c, in a file
169 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
170 * with it.
171 */
172
173/*
174 * Definition of a port range, and macros to deal with values.
175 * FORMAT:  HI 16-bits == first port in range, 0 == all ports.
176 *	  LO 16-bits == number of ports in range
177 * NOTES:   - Port values are not stored in network byte order.
178 */
179
180#define port_range u_long
181
182#define GETLOPORT(x)	((x) >> 0x10)
183#define GETNUMPORTS(x)	((x) & 0x0000ffff)
184#define GETHIPORT(x)	(GETLOPORT((x)) + GETNUMPORTS((x)))
185
186/* Set y to be the low-port value in port_range variable x. */
187#define SETLOPORT(x,y)   ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
188
189/* Set y to be the number of ports in port_range variable x. */
190#define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
191
192static void
193StrToAddr (const char* str, struct in_addr* addr)
194{
195	struct hostent* hp;
196
197	if (inet_aton (str, addr))
198		return;
199
200	hp = gethostbyname (str);
201	if (!hp)
202		errx (1, "unknown host %s", str);
203
204	memcpy (addr, hp->h_addr, sizeof (struct in_addr));
205}
206
207static int
208StrToPortRange (const char* str, const char* proto, port_range *portRange)
209{
210	char*	   sep;
211	struct servent*	sp;
212	char*		end;
213	u_short	 loPort;
214	u_short	 hiPort;
215
216	/* First see if this is a service, return corresponding port if so. */
217	sp = getservbyname (str,proto);
218	if (sp) {
219		SETLOPORT(*portRange, ntohs(sp->s_port));
220		SETNUMPORTS(*portRange, 1);
221		return 0;
222	}
223
224	/* Not a service, see if it's a single port or port range. */
225	sep = strchr (str, '-');
226	if (sep == NULL) {
227		SETLOPORT(*portRange, strtol(str, &end, 10));
228		if (end != str) {
229			/* Single port. */
230			SETNUMPORTS(*portRange, 1);
231			return 0;
232		}
233
234		/* Error in port range field. */
235		errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
236	}
237
238	/* Port range, get the values and sanity check. */
239	sscanf (str, "%hu-%hu", &loPort, &hiPort);
240	SETLOPORT(*portRange, loPort);
241	SETNUMPORTS(*portRange, 0);	/* Error by default */
242	if (loPort <= hiPort)
243		SETNUMPORTS(*portRange, hiPort - loPort + 1);
244
245	if (GETNUMPORTS(*portRange) == 0)
246		errx (EX_DATAERR, "invalid port range %s", str);
247
248	return 0;
249}
250
251static int
252StrToProto (const char* str)
253{
254	if (!strcmp (str, "tcp"))
255		return IPPROTO_TCP;
256
257	if (!strcmp (str, "udp"))
258		return IPPROTO_UDP;
259
260	if (!strcmp (str, "sctp"))
261		return IPPROTO_SCTP;
262	errx (EX_DATAERR, "unknown protocol %s. Expected sctp, tcp or udp", str);
263}
264
265static int
266StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
267			port_range *portRange)
268{
269	char*	ptr;
270
271	ptr = strchr (str, ':');
272	if (!ptr)
273		errx (EX_DATAERR, "%s is missing port number", str);
274
275	*ptr = '\0';
276	++ptr;
277
278	StrToAddr (str, addr);
279	return StrToPortRange (ptr, proto, portRange);
280}
281
282/* End of stuff taken from natd.c. */
283
284#define INC_ARGCV() do {	\
285	(*_av)++;		\
286	(*_ac)--;		\
287	av = *_av;		\
288	ac = *_ac;		\
289} while(0)
290
291/*
292 * The next 3 functions add support for the addr, port and proto redirect and
293 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
294 * and SetupProtoRedirect() from natd.c.
295 *
296 * Every setup_* function fills at least one redirect entry
297 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool)
298 * in buf.
299 *
300 * The format of data in buf is:
301 *
302 *     cfg_nat    cfg_redir    cfg_spool    ......  cfg_spool
303 *
304 *    -------------------------------------        ------------
305 *   |          | .....X ... |          |         |           |  .....
306 *    ------------------------------------- ...... ------------
307 *                     ^
308 *                spool_cnt       n=0       ......   n=(X-1)
309 *
310 * len points to the amount of available space in buf
311 * space counts the memory consumed by every function
312 *
313 * XXX - Every function get all the argv params so it
314 * has to check, in optional parameters, that the next
315 * args is a valid option for the redir entry and not
316 * another token. Only redir_port and redir_proto are
317 * affected by this.
318 */
319
320static int
321setup_redir_addr(char *spool_buf, unsigned int len,
322		 int *_ac, char ***_av)
323{
324	char **av, *sep; /* Token separator. */
325	/* Temporary buffer used to hold server pool ip's. */
326	char tmp_spool_buf[NAT_BUF_LEN];
327	int ac, space, lsnat;
328	struct cfg_redir *r;
329	struct cfg_spool *tmp;
330
331	av = *_av;
332	ac = *_ac;
333	space = 0;
334	lsnat = 0;
335	if (len >= SOF_REDIR) {
336		r = (struct cfg_redir *)spool_buf;
337		/* Skip cfg_redir at beginning of buf. */
338		spool_buf = &spool_buf[SOF_REDIR];
339		space = SOF_REDIR;
340		len -= SOF_REDIR;
341	} else
342		goto nospace;
343	r->mode = REDIR_ADDR;
344	/* Extract local address. */
345	if (ac == 0)
346		errx(EX_DATAERR, "redirect_addr: missing local address");
347	sep = strchr(*av, ',');
348	if (sep) {		/* LSNAT redirection syntax. */
349		r->laddr.s_addr = INADDR_NONE;
350		/* Preserve av, copy spool servers to tmp_spool_buf. */
351		strncpy(tmp_spool_buf, *av, strlen(*av)+1);
352		lsnat = 1;
353	} else
354		StrToAddr(*av, &r->laddr);
355	INC_ARGCV();
356
357	/* Extract public address. */
358	if (ac == 0)
359		errx(EX_DATAERR, "redirect_addr: missing public address");
360	StrToAddr(*av, &r->paddr);
361	INC_ARGCV();
362
363	/* Setup LSNAT server pool. */
364	if (sep) {
365		sep = strtok(tmp_spool_buf, ",");
366		while (sep != NULL) {
367			tmp = (struct cfg_spool *)spool_buf;
368			if (len < SOF_SPOOL)
369				goto nospace;
370			len -= SOF_SPOOL;
371			space += SOF_SPOOL;
372			StrToAddr(sep, &tmp->addr);
373			tmp->port = ~0;
374			r->spool_cnt++;
375			/* Point to the next possible cfg_spool. */
376			spool_buf = &spool_buf[SOF_SPOOL];
377			sep = strtok(NULL, ",");
378		}
379	}
380	return(space);
381nospace:
382	errx(EX_DATAERR, "redirect_addr: buf is too small\n");
383}
384
385static int
386setup_redir_port(char *spool_buf, unsigned int len,
387		 int *_ac, char ***_av)
388{
389	char **av, *sep, *protoName;
390	char tmp_spool_buf[NAT_BUF_LEN];
391	int ac, space, lsnat;
392	struct cfg_redir *r;
393	struct cfg_spool *tmp;
394	u_short numLocalPorts;
395	port_range portRange;
396
397	av = *_av;
398	ac = *_ac;
399	space = 0;
400	lsnat = 0;
401	numLocalPorts = 0;
402
403	if (len >= SOF_REDIR) {
404		r = (struct cfg_redir *)spool_buf;
405		/* Skip cfg_redir at beginning of buf. */
406		spool_buf = &spool_buf[SOF_REDIR];
407		space = SOF_REDIR;
408		len -= SOF_REDIR;
409	} else
410		goto nospace;
411	r->mode = REDIR_PORT;
412	/*
413	 * Extract protocol.
414	 */
415	if (ac == 0)
416		errx (EX_DATAERR, "redirect_port: missing protocol");
417	r->proto = StrToProto(*av);
418	protoName = *av;
419	INC_ARGCV();
420
421	/*
422	 * Extract local address.
423	 */
424	if (ac == 0)
425		errx (EX_DATAERR, "redirect_port: missing local address");
426
427	sep = strchr(*av, ',');
428	/* LSNAT redirection syntax. */
429	if (sep) {
430		r->laddr.s_addr = INADDR_NONE;
431		r->lport = ~0;
432		numLocalPorts = 1;
433		/* Preserve av, copy spool servers to tmp_spool_buf. */
434		strncpy(tmp_spool_buf, *av, strlen(*av)+1);
435		lsnat = 1;
436	} else {
437		/*
438		 * The sctp nat does not allow the port numbers to be mapped to
439		 * new port numbers. Therefore, no ports are to be specified
440		 * in the target port field.
441		 */
442		if (r->proto == IPPROTO_SCTP) {
443			if (strchr (*av, ':'))
444				errx(EX_DATAERR, "redirect_port:"
445				    "port numbers do not change in sctp, so do not "
446				    "specify them as part of the target");
447			else
448				StrToAddr(*av, &r->laddr);
449		} else {
450			if (StrToAddrAndPortRange (*av, &r->laddr, protoName,
451				&portRange) != 0)
452				errx(EX_DATAERR, "redirect_port:"
453				    "invalid local port range");
454
455			r->lport = GETLOPORT(portRange);
456			numLocalPorts = GETNUMPORTS(portRange);
457		}
458	}
459	INC_ARGCV();
460
461	/*
462	 * Extract public port and optionally address.
463	 */
464	if (ac == 0)
465		errx (EX_DATAERR, "redirect_port: missing public port");
466
467	sep = strchr (*av, ':');
468	if (sep) {
469		if (StrToAddrAndPortRange (*av, &r->paddr, protoName,
470		    &portRange) != 0)
471			errx(EX_DATAERR, "redirect_port:"
472			    "invalid public port range");
473	} else {
474		r->paddr.s_addr = INADDR_ANY;
475		if (StrToPortRange (*av, protoName, &portRange) != 0)
476			errx(EX_DATAERR, "redirect_port:"
477			    "invalid public port range");
478	}
479
480	r->pport = GETLOPORT(portRange);
481	if (r->proto == IPPROTO_SCTP) { /* so the logic below still works */
482		numLocalPorts = GETNUMPORTS(portRange);
483		r->lport = r->pport;
484	}
485	r->pport_cnt = GETNUMPORTS(portRange);
486	INC_ARGCV();
487
488	/*
489	 * Extract remote address and optionally port.
490	 */
491	/*
492	 * NB: isalpha(**av) => we've to check that next parameter is really an
493	 * option for this redirect entry, else stop here processing arg[cv].
494	 */
495	if (ac != 0 && !isalpha(**av)) {
496		sep = strchr (*av, ':');
497		if (sep) {
498			if (StrToAddrAndPortRange (*av, &r->raddr, protoName,
499			    &portRange) != 0)
500				errx(EX_DATAERR, "redirect_port:"
501				    "invalid remote port range");
502		} else {
503			SETLOPORT(portRange, 0);
504			SETNUMPORTS(portRange, 1);
505			StrToAddr (*av, &r->raddr);
506		}
507		INC_ARGCV();
508	} else {
509		SETLOPORT(portRange, 0);
510		SETNUMPORTS(portRange, 1);
511		r->raddr.s_addr = INADDR_ANY;
512	}
513	r->rport = GETLOPORT(portRange);
514	r->rport_cnt = GETNUMPORTS(portRange);
515
516	/*
517	 * Make sure port ranges match up, then add the redirect ports.
518	 */
519	if (numLocalPorts != r->pport_cnt)
520		errx(EX_DATAERR, "redirect_port:"
521		    "port ranges must be equal in size");
522
523	/* Remote port range is allowed to be '0' which means all ports. */
524	if (r->rport_cnt != numLocalPorts &&
525	    (r->rport_cnt != 1 || r->rport != 0))
526		errx(EX_DATAERR, "redirect_port: remote port must"
527		    "be 0 or equal to local port range in size");
528
529	/*
530	 * Setup LSNAT server pool.
531	 */
532	if (lsnat) {
533		sep = strtok(tmp_spool_buf, ",");
534		while (sep != NULL) {
535			tmp = (struct cfg_spool *)spool_buf;
536			if (len < SOF_SPOOL)
537				goto nospace;
538			len -= SOF_SPOOL;
539			space += SOF_SPOOL;
540			/*
541			 * The sctp nat does not allow the port numbers to be mapped to new port numbers
542			 * Therefore, no ports are to be specified in the target port field
543			 */
544			if (r->proto == IPPROTO_SCTP) {
545				if (strchr (sep, ':')) {
546					errx(EX_DATAERR, "redirect_port:"
547					    "port numbers do not change in "
548					    "sctp, so do not specify them as "
549					    "part of the target");
550				} else {
551					StrToAddr(sep, &tmp->addr);
552					tmp->port = r->pport;
553				}
554			} else {
555				if (StrToAddrAndPortRange(sep, &tmp->addr,
556					protoName, &portRange) != 0)
557					errx(EX_DATAERR, "redirect_port:"
558					    "invalid local port range");
559				if (GETNUMPORTS(portRange) != 1)
560					errx(EX_DATAERR, "redirect_port: "
561					    "local port must be single in "
562					    "this context");
563				tmp->port = GETLOPORT(portRange);
564			}
565			r->spool_cnt++;
566			/* Point to the next possible cfg_spool. */
567			spool_buf = &spool_buf[SOF_SPOOL];
568			sep = strtok(NULL, ",");
569		}
570	}
571	return (space);
572nospace:
573	errx(EX_DATAERR, "redirect_port: buf is too small\n");
574}
575
576static int
577setup_redir_proto(char *spool_buf, unsigned int len,
578		 int *_ac, char ***_av)
579{
580	char **av;
581	int ac, space;
582	struct protoent *protoent;
583	struct cfg_redir *r;
584
585	av = *_av;
586	ac = *_ac;
587	if (len >= SOF_REDIR) {
588		r = (struct cfg_redir *)spool_buf;
589		/* Skip cfg_redir at beginning of buf. */
590		spool_buf = &spool_buf[SOF_REDIR];
591		space = SOF_REDIR;
592		len -= SOF_REDIR;
593	} else
594		goto nospace;
595	r->mode = REDIR_PROTO;
596	/*
597	 * Extract protocol.
598	 */
599	if (ac == 0)
600		errx(EX_DATAERR, "redirect_proto: missing protocol");
601
602	protoent = getprotobyname(*av);
603	if (protoent == NULL)
604		errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av);
605	else
606		r->proto = protoent->p_proto;
607
608	INC_ARGCV();
609
610	/*
611	 * Extract local address.
612	 */
613	if (ac == 0)
614		errx(EX_DATAERR, "redirect_proto: missing local address");
615	else
616		StrToAddr(*av, &r->laddr);
617
618	INC_ARGCV();
619
620	/*
621	 * Extract optional public address.
622	 */
623	if (ac == 0) {
624		r->paddr.s_addr = INADDR_ANY;
625		r->raddr.s_addr = INADDR_ANY;
626	} else {
627		/* see above in setup_redir_port() */
628		if (!isalpha(**av)) {
629			StrToAddr(*av, &r->paddr);
630			INC_ARGCV();
631
632			/*
633			 * Extract optional remote address.
634			 */
635			/* see above in setup_redir_port() */
636			if (ac!=0 && !isalpha(**av)) {
637				StrToAddr(*av, &r->raddr);
638				INC_ARGCV();
639			}
640		}
641	}
642	return (space);
643nospace:
644	errx(EX_DATAERR, "redirect_proto: buf is too small\n");
645}
646
647static void
648print_nat_config(unsigned char *buf)
649{
650	struct cfg_nat *n;
651	int i, cnt, flag, off;
652	struct cfg_redir *t;
653	struct cfg_spool *s;
654	struct protoent *p;
655
656	n = (struct cfg_nat *)buf;
657	flag = 1;
658	off  = sizeof(*n);
659	printf("ipfw nat %u config", n->id);
660	if (strlen(n->if_name) != 0)
661		printf(" if %s", n->if_name);
662	else if (n->ip.s_addr != 0)
663		printf(" ip %s", inet_ntoa(n->ip));
664	while (n->mode != 0) {
665		if (n->mode & PKT_ALIAS_LOG) {
666			printf(" log");
667			n->mode &= ~PKT_ALIAS_LOG;
668		} else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
669			printf(" deny_in");
670			n->mode &= ~PKT_ALIAS_DENY_INCOMING;
671		} else if (n->mode & PKT_ALIAS_SAME_PORTS) {
672			printf(" same_ports");
673			n->mode &= ~PKT_ALIAS_SAME_PORTS;
674		} else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
675			printf(" unreg_only");
676			n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
677		} else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
678			printf(" reset");
679			n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
680		} else if (n->mode & PKT_ALIAS_REVERSE) {
681			printf(" reverse");
682			n->mode &= ~PKT_ALIAS_REVERSE;
683		} else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
684			printf(" proxy_only");
685			n->mode &= ~PKT_ALIAS_PROXY_ONLY;
686		}
687	}
688	/* Print all the redirect's data configuration. */
689	for (cnt = 0; cnt < n->redir_cnt; cnt++) {
690		t = (struct cfg_redir *)&buf[off];
691		off += SOF_REDIR;
692		switch (t->mode) {
693		case REDIR_ADDR:
694			printf(" redirect_addr");
695			if (t->spool_cnt == 0)
696				printf(" %s", inet_ntoa(t->laddr));
697			else
698				for (i = 0; i < t->spool_cnt; i++) {
699					s = (struct cfg_spool *)&buf[off];
700					if (i)
701						printf(",");
702					else
703						printf(" ");
704					printf("%s", inet_ntoa(s->addr));
705					off += SOF_SPOOL;
706				}
707			printf(" %s", inet_ntoa(t->paddr));
708			break;
709		case REDIR_PORT:
710			p = getprotobynumber(t->proto);
711			printf(" redirect_port %s ", p->p_name);
712			if (!t->spool_cnt) {
713				printf("%s:%u", inet_ntoa(t->laddr), t->lport);
714				if (t->pport_cnt > 1)
715					printf("-%u", t->lport +
716					    t->pport_cnt - 1);
717			} else
718				for (i=0; i < t->spool_cnt; i++) {
719					s = (struct cfg_spool *)&buf[off];
720					if (i)
721						printf(",");
722					printf("%s:%u", inet_ntoa(s->addr),
723					    s->port);
724					off += SOF_SPOOL;
725				}
726
727			printf(" ");
728			if (t->paddr.s_addr)
729				printf("%s:", inet_ntoa(t->paddr));
730			printf("%u", t->pport);
731			if (!t->spool_cnt && t->pport_cnt > 1)
732				printf("-%u", t->pport + t->pport_cnt - 1);
733
734			if (t->raddr.s_addr) {
735				printf(" %s", inet_ntoa(t->raddr));
736				if (t->rport) {
737					printf(":%u", t->rport);
738					if (!t->spool_cnt && t->rport_cnt > 1)
739						printf("-%u", t->rport +
740						    t->rport_cnt - 1);
741				}
742			}
743			break;
744		case REDIR_PROTO:
745			p = getprotobynumber(t->proto);
746			printf(" redirect_proto %s %s", p->p_name,
747			    inet_ntoa(t->laddr));
748			if (t->paddr.s_addr != 0) {
749				printf(" %s", inet_ntoa(t->paddr));
750				if (t->raddr.s_addr)
751					printf(" %s", inet_ntoa(t->raddr));
752			}
753			break;
754		default:
755			errx(EX_DATAERR, "unknown redir mode");
756			break;
757		}
758	}
759	printf("\n");
760}
761
762void
763ipfw_config_nat(int ac, char **av)
764{
765	struct cfg_nat *n;		/* Nat instance configuration. */
766	int i, len, off, tok;
767	char *id, buf[NAT_BUF_LEN]; 	/* Buffer for serialized data. */
768
769	len = NAT_BUF_LEN;
770	/* Offset in buf: save space for n at the beginning. */
771	off = sizeof(*n);
772	memset(buf, 0, sizeof(buf));
773	n = (struct cfg_nat *)buf;
774
775	av++; ac--;
776	/* Nat id. */
777	if (ac && isdigit(**av)) {
778		id = *av;
779		i = atoi(*av);
780		ac--; av++;
781		n->id = i;
782	} else
783		errx(EX_DATAERR, "missing nat id");
784	if (ac == 0)
785		errx(EX_DATAERR, "missing option");
786
787	while (ac > 0) {
788		tok = match_token(nat_params, *av);
789		ac--; av++;
790		switch (tok) {
791		case TOK_IP:
792			if (ac == 0)
793				errx(EX_DATAERR, "missing option");
794			if (!inet_aton(av[0], &(n->ip)))
795				errx(EX_DATAERR, "bad ip address ``%s''",
796				    av[0]);
797			ac--; av++;
798			break;
799		case TOK_IF:
800			if (ac == 0)
801				errx(EX_DATAERR, "missing option");
802			set_addr_dynamic(av[0], n);
803			ac--; av++;
804			break;
805		case TOK_ALOG:
806			n->mode |= PKT_ALIAS_LOG;
807			break;
808		case TOK_DENY_INC:
809			n->mode |= PKT_ALIAS_DENY_INCOMING;
810			break;
811		case TOK_SAME_PORTS:
812			n->mode |= PKT_ALIAS_SAME_PORTS;
813			break;
814		case TOK_UNREG_ONLY:
815			n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
816			break;
817		case TOK_RESET_ADDR:
818			n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
819			break;
820		case TOK_ALIAS_REV:
821			n->mode |= PKT_ALIAS_REVERSE;
822			break;
823		case TOK_PROXY_ONLY:
824			n->mode |= PKT_ALIAS_PROXY_ONLY;
825			break;
826			/*
827			 * All the setup_redir_* functions work directly in
828			 * the final buffer, see above for details.
829			 */
830		case TOK_REDIR_ADDR:
831		case TOK_REDIR_PORT:
832		case TOK_REDIR_PROTO:
833			switch (tok) {
834			case TOK_REDIR_ADDR:
835				i = setup_redir_addr(&buf[off], len, &ac, &av);
836				break;
837			case TOK_REDIR_PORT:
838				i = setup_redir_port(&buf[off], len, &ac, &av);
839				break;
840			case TOK_REDIR_PROTO:
841				i = setup_redir_proto(&buf[off], len, &ac, &av);
842				break;
843			}
844			n->redir_cnt++;
845			off += i;
846			len -= i;
847			break;
848		default:
849			errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
850		}
851	}
852
853	i = do_cmd(IP_FW_NAT_CFG, buf, off);
854	if (i)
855		err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
856
857	if (!co.do_quiet) {
858		/* After every modification, we show the resultant rule. */
859		int _ac = 3;
860		const char *_av[] = {"show", "config", id};
861		ipfw_show_nat(_ac, (char **)(void *)_av);
862	}
863}
864
865
866void
867ipfw_show_nat(int ac, char **av)
868{
869	struct cfg_nat *n;
870	struct cfg_redir *e;
871	int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
872	int nat_cnt, redir_cnt, r;
873	uint8_t *data, *p;
874	char *endptr;
875
876	do_rule = 0;
877	nalloc = 1024;
878	size = 0;
879	data = NULL;
880	frule = 0;
881	lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
882	ac--; av++;
883
884	if (co.test_only)
885		return;
886
887	/* Parse parameters. */
888	for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
889		if (!strncmp(av[0], "config", strlen(av[0]))) {
890			cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
891			continue;
892		}
893		/* Convert command line rule #. */
894		frule = lrule = strtoul(av[0], &endptr, 10);
895		if (*endptr == '-')
896			lrule = strtoul(endptr+1, &endptr, 10);
897		if (lrule == 0)
898			err(EX_USAGE, "invalid rule number: %s", av[0]);
899		do_rule = 1;
900	}
901
902	nbytes = nalloc;
903	while (nbytes >= nalloc) {
904		nalloc = nalloc * 2;
905		nbytes = nalloc;
906		data = safe_realloc(data, nbytes);
907		if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
908			err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
909			    (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
910	}
911	if (nbytes == 0)
912		exit(0);
913	if (do_cfg) {
914		nat_cnt = *((int *)data);
915		for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
916			n = (struct cfg_nat *)&data[i];
917			if (frule <= n->id && lrule >= n->id)
918				print_nat_config(&data[i]);
919			i += sizeof(struct cfg_nat);
920			for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
921				e = (struct cfg_redir *)&data[i];
922				i += sizeof(struct cfg_redir) + e->spool_cnt *
923				    sizeof(struct cfg_spool);
924			}
925		}
926	} else {
927		for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
928			p = &data[i];
929			if (p == data + nbytes)
930				break;
931			bcopy(p, &r, sizeof(int));
932			if (do_rule) {
933				if (!(frule <= r && lrule >= r))
934					continue;
935			}
936			printf("nat %u: %s\n", r, p+sizeof(int));
937		}
938	}
939}
940