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