xref: /freebsd/sbin/ipfw/nat.c (revision d184218c)
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$
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 
49 static 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  */
73 static void
74 set_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 
193 static void
194 StrToAddr (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 
208 static int
209 StrToPortRange (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 
252 static int
253 StrToProto (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 
266 static int
267 StrToAddrAndPortRange (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 
314 static int
315 estimate_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 	(void)ac;	/* UNUSED */
322 	while ((sep = strchr(sep, ',')) != NULL) {
323 		c++;
324 		sep++;
325 	}
326 
327 	if (c > 0)
328 		c++;
329 
330 	space += c * sizeof(struct cfg_spool);
331 
332 	return (space);
333 }
334 
335 static int
336 setup_redir_addr(char *buf, int *ac, char ***av)
337 {
338 	struct cfg_redir *r;
339 	char *sep;
340 	size_t space;
341 
342 	r = (struct cfg_redir *)buf;
343 	r->mode = REDIR_ADDR;
344 	/* Skip cfg_redir at beginning of buf. */
345 	buf = &buf[sizeof(struct cfg_redir)];
346 	space = sizeof(struct cfg_redir);
347 
348 	/* Extract local address. */
349 	if (strchr(**av, ',') != NULL) {
350 		struct cfg_spool *spool;
351 
352 		/* Setup LSNAT server pool. */
353 		r->laddr.s_addr = INADDR_NONE;
354 		sep = strtok(**av, ",");
355 		while (sep != NULL) {
356 			spool = (struct cfg_spool *)buf;
357 			space += sizeof(struct cfg_spool);
358 			StrToAddr(sep, &spool->addr);
359 			spool->port = ~0;
360 			r->spool_cnt++;
361 			/* Point to the next possible cfg_spool. */
362 			buf = &buf[sizeof(struct cfg_spool)];
363 			sep = strtok(NULL, ",");
364 		}
365 	} else
366 		StrToAddr(**av, &r->laddr);
367 	(*av)++; (*ac)--;
368 
369 	/* Extract public address. */
370 	StrToAddr(**av, &r->paddr);
371 	(*av)++; (*ac)--;
372 
373 	return (space);
374 }
375 
376 static int
377 estimate_redir_port(int *ac, char ***av)
378 {
379 	size_t space = sizeof(struct cfg_redir);
380 	char *sep = **av;
381 	u_int c = 0;
382 
383 	(void)ac;	/* UNUSED */
384 	while ((sep = strchr(sep, ',')) != NULL) {
385 		c++;
386 		sep++;
387 	}
388 
389 	if (c > 0)
390 		c++;
391 
392 	space += c * sizeof(struct cfg_spool);
393 
394 	return (space);
395 }
396 
397 static int
398 setup_redir_port(char *buf, int *ac, char ***av)
399 {
400 	struct cfg_redir *r;
401 	char *sep, *protoName, *lsnat = NULL;
402 	size_t space;
403 	u_short numLocalPorts;
404 	port_range portRange;
405 
406 	numLocalPorts = 0;
407 
408 	r = (struct cfg_redir *)buf;
409 	r->mode = REDIR_PORT;
410 	/* Skip cfg_redir at beginning of buf. */
411 	buf = &buf[sizeof(struct cfg_redir)];
412 	space = sizeof(struct cfg_redir);
413 
414 	/*
415 	 * Extract protocol.
416 	 */
417 	r->proto = StrToProto(**av);
418 	protoName = **av;
419 	(*av)++; (*ac)--;
420 
421 	/*
422 	 * Extract local address.
423 	 */
424 	if (strchr(**av, ',') != NULL) {
425 		r->laddr.s_addr = INADDR_NONE;
426 		r->lport = ~0;
427 		numLocalPorts = 1;
428 		lsnat = **av;
429 	} else {
430 		/*
431 		 * The sctp nat does not allow the port numbers to be mapped to
432 		 * new port numbers. Therefore, no ports are to be specified
433 		 * in the target port field.
434 		 */
435 		if (r->proto == IPPROTO_SCTP) {
436 			if (strchr(**av, ':'))
437 				errx(EX_DATAERR, "redirect_port:"
438 				    "port numbers do not change in sctp, so do "
439 				    "not specify them as part of the target");
440 			else
441 				StrToAddr(**av, &r->laddr);
442 		} else {
443 			if (StrToAddrAndPortRange(**av, &r->laddr, protoName,
444 			    &portRange) != 0)
445 				errx(EX_DATAERR, "redirect_port: "
446 				    "invalid local port range");
447 
448 			r->lport = GETLOPORT(portRange);
449 			numLocalPorts = GETNUMPORTS(portRange);
450 		}
451 	}
452 	(*av)++; (*ac)--;
453 
454 	/*
455 	 * Extract public port and optionally address.
456 	 */
457 	if (strchr(**av, ':') != NULL) {
458 		if (StrToAddrAndPortRange(**av, &r->paddr, protoName,
459 		    &portRange) != 0)
460 			errx(EX_DATAERR, "redirect_port: "
461 			    "invalid public port range");
462 	} else {
463 		r->paddr.s_addr = INADDR_ANY;
464 		if (StrToPortRange(**av, protoName, &portRange) != 0)
465 			errx(EX_DATAERR, "redirect_port: "
466 			    "invalid public port range");
467 	}
468 
469 	r->pport = GETLOPORT(portRange);
470 	if (r->proto == IPPROTO_SCTP) { /* so the logic below still works */
471 		numLocalPorts = GETNUMPORTS(portRange);
472 		r->lport = r->pport;
473 	}
474 	r->pport_cnt = GETNUMPORTS(portRange);
475 	(*av)++; (*ac)--;
476 
477 	/*
478 	 * Extract remote address and optionally port.
479 	 */
480 	/*
481 	 * NB: isdigit(**av) => we've to check that next parameter is really an
482 	 * option for this redirect entry, else stop here processing arg[cv].
483 	 */
484 	if (*ac != 0 && isdigit(***av)) {
485 		if (strchr(**av, ':') != NULL) {
486 			if (StrToAddrAndPortRange(**av, &r->raddr, protoName,
487 			    &portRange) != 0)
488 				errx(EX_DATAERR, "redirect_port: "
489 				    "invalid remote port range");
490 		} else {
491 			SETLOPORT(portRange, 0);
492 			SETNUMPORTS(portRange, 1);
493 			StrToAddr(**av, &r->raddr);
494 		}
495 		(*av)++; (*ac)--;
496 	} else {
497 		SETLOPORT(portRange, 0);
498 		SETNUMPORTS(portRange, 1);
499 		r->raddr.s_addr = INADDR_ANY;
500 	}
501 	r->rport = GETLOPORT(portRange);
502 	r->rport_cnt = GETNUMPORTS(portRange);
503 
504 	/*
505 	 * Make sure port ranges match up, then add the redirect ports.
506 	 */
507 	if (numLocalPorts != r->pport_cnt)
508 		errx(EX_DATAERR, "redirect_port: "
509 		    "port ranges must be equal in size");
510 
511 	/* Remote port range is allowed to be '0' which means all ports. */
512 	if (r->rport_cnt != numLocalPorts &&
513 	    (r->rport_cnt != 1 || r->rport != 0))
514 		errx(EX_DATAERR, "redirect_port: remote port must"
515 		    "be 0 or equal to local port range in size");
516 
517 	/* Setup LSNAT server pool. */
518 	if (lsnat != NULL) {
519 		struct cfg_spool *spool;
520 
521 		sep = strtok(lsnat, ",");
522 		while (sep != NULL) {
523 			spool = (struct cfg_spool *)buf;
524 			space += sizeof(struct cfg_spool);
525 			/*
526 			 * The sctp nat does not allow the port numbers to
527 			 * be mapped to new port numbers. Therefore, no ports
528 			 * are to be specified in the target port field.
529 			 */
530 			if (r->proto == IPPROTO_SCTP) {
531 				if (strchr (sep, ':')) {
532 					errx(EX_DATAERR, "redirect_port:"
533 					    "port numbers do not change in "
534 					    "sctp, so do not specify them as "
535 					    "part of the target");
536 				} else {
537 					StrToAddr(sep, &spool->addr);
538 					spool->port = r->pport;
539 				}
540 			} else {
541 				if (StrToAddrAndPortRange(sep, &spool->addr,
542 					protoName, &portRange) != 0)
543 					errx(EX_DATAERR, "redirect_port:"
544 					    "invalid local port range");
545 				if (GETNUMPORTS(portRange) != 1)
546 					errx(EX_DATAERR, "redirect_port: "
547 					    "local port must be single in "
548 					    "this context");
549 				spool->port = GETLOPORT(portRange);
550 			}
551 			r->spool_cnt++;
552 			/* Point to the next possible cfg_spool. */
553 			buf = &buf[sizeof(struct cfg_spool)];
554 			sep = strtok(NULL, ",");
555 		}
556 	}
557 
558 	return (space);
559 }
560 
561 static int
562 setup_redir_proto(char *buf, int *ac, char ***av)
563 {
564 	struct cfg_redir *r;
565 	struct protoent *protoent;
566 	size_t space;
567 
568 	r = (struct cfg_redir *)buf;
569 	r->mode = REDIR_PROTO;
570 	/* Skip cfg_redir at beginning of buf. */
571 	buf = &buf[sizeof(struct cfg_redir)];
572 	space = sizeof(struct cfg_redir);
573 
574 	/*
575 	 * Extract protocol.
576 	 */
577 	protoent = getprotobyname(**av);
578 	if (protoent == NULL)
579 		errx(EX_DATAERR, "redirect_proto: unknown protocol %s", **av);
580 	else
581 		r->proto = protoent->p_proto;
582 
583 	(*av)++; (*ac)--;
584 
585 	/*
586 	 * Extract local address.
587 	 */
588 	StrToAddr(**av, &r->laddr);
589 
590 	(*av)++; (*ac)--;
591 
592 	/*
593 	 * Extract optional public address.
594 	 */
595 	if (*ac == 0) {
596 		r->paddr.s_addr = INADDR_ANY;
597 		r->raddr.s_addr = INADDR_ANY;
598 	} else {
599 		/* see above in setup_redir_port() */
600 		if (isdigit(***av)) {
601 			StrToAddr(**av, &r->paddr);
602 			(*av)++; (*ac)--;
603 
604 			/*
605 			 * Extract optional remote address.
606 			 */
607 			/* see above in setup_redir_port() */
608 			if (*ac != 0 && isdigit(***av)) {
609 				StrToAddr(**av, &r->raddr);
610 				(*av)++; (*ac)--;
611 			}
612 		}
613 	}
614 
615 	return (space);
616 }
617 
618 static void
619 print_nat_config(unsigned char *buf)
620 {
621 	struct cfg_nat *n;
622 	int i, cnt, flag, off;
623 	struct cfg_redir *t;
624 	struct cfg_spool *s;
625 	struct protoent *p;
626 
627 	n = (struct cfg_nat *)buf;
628 	flag = 1;
629 	off  = sizeof(*n);
630 	printf("ipfw nat %u config", n->id);
631 	if (strlen(n->if_name) != 0)
632 		printf(" if %s", n->if_name);
633 	else if (n->ip.s_addr != 0)
634 		printf(" ip %s", inet_ntoa(n->ip));
635 	while (n->mode != 0) {
636 		if (n->mode & PKT_ALIAS_LOG) {
637 			printf(" log");
638 			n->mode &= ~PKT_ALIAS_LOG;
639 		} else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
640 			printf(" deny_in");
641 			n->mode &= ~PKT_ALIAS_DENY_INCOMING;
642 		} else if (n->mode & PKT_ALIAS_SAME_PORTS) {
643 			printf(" same_ports");
644 			n->mode &= ~PKT_ALIAS_SAME_PORTS;
645 		} else if (n->mode & PKT_ALIAS_SKIP_GLOBAL) {
646 			printf(" skip_global");
647 			n->mode &= ~PKT_ALIAS_SKIP_GLOBAL;
648 		} else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
649 			printf(" unreg_only");
650 			n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
651 		} else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
652 			printf(" reset");
653 			n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
654 		} else if (n->mode & PKT_ALIAS_REVERSE) {
655 			printf(" reverse");
656 			n->mode &= ~PKT_ALIAS_REVERSE;
657 		} else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
658 			printf(" proxy_only");
659 			n->mode &= ~PKT_ALIAS_PROXY_ONLY;
660 		}
661 	}
662 	/* Print all the redirect's data configuration. */
663 	for (cnt = 0; cnt < n->redir_cnt; cnt++) {
664 		t = (struct cfg_redir *)&buf[off];
665 		off += SOF_REDIR;
666 		switch (t->mode) {
667 		case REDIR_ADDR:
668 			printf(" redirect_addr");
669 			if (t->spool_cnt == 0)
670 				printf(" %s", inet_ntoa(t->laddr));
671 			else
672 				for (i = 0; i < t->spool_cnt; i++) {
673 					s = (struct cfg_spool *)&buf[off];
674 					if (i)
675 						printf(",");
676 					else
677 						printf(" ");
678 					printf("%s", inet_ntoa(s->addr));
679 					off += SOF_SPOOL;
680 				}
681 			printf(" %s", inet_ntoa(t->paddr));
682 			break;
683 		case REDIR_PORT:
684 			p = getprotobynumber(t->proto);
685 			printf(" redirect_port %s ", p->p_name);
686 			if (!t->spool_cnt) {
687 				printf("%s:%u", inet_ntoa(t->laddr), t->lport);
688 				if (t->pport_cnt > 1)
689 					printf("-%u", t->lport +
690 					    t->pport_cnt - 1);
691 			} else
692 				for (i=0; i < t->spool_cnt; i++) {
693 					s = (struct cfg_spool *)&buf[off];
694 					if (i)
695 						printf(",");
696 					printf("%s:%u", inet_ntoa(s->addr),
697 					    s->port);
698 					off += SOF_SPOOL;
699 				}
700 
701 			printf(" ");
702 			if (t->paddr.s_addr)
703 				printf("%s:", inet_ntoa(t->paddr));
704 			printf("%u", t->pport);
705 			if (!t->spool_cnt && t->pport_cnt > 1)
706 				printf("-%u", t->pport + t->pport_cnt - 1);
707 
708 			if (t->raddr.s_addr) {
709 				printf(" %s", inet_ntoa(t->raddr));
710 				if (t->rport) {
711 					printf(":%u", t->rport);
712 					if (!t->spool_cnt && t->rport_cnt > 1)
713 						printf("-%u", t->rport +
714 						    t->rport_cnt - 1);
715 				}
716 			}
717 			break;
718 		case REDIR_PROTO:
719 			p = getprotobynumber(t->proto);
720 			printf(" redirect_proto %s %s", p->p_name,
721 			    inet_ntoa(t->laddr));
722 			if (t->paddr.s_addr != 0) {
723 				printf(" %s", inet_ntoa(t->paddr));
724 				if (t->raddr.s_addr)
725 					printf(" %s", inet_ntoa(t->raddr));
726 			}
727 			break;
728 		default:
729 			errx(EX_DATAERR, "unknown redir mode");
730 			break;
731 		}
732 	}
733 	printf("\n");
734 }
735 
736 void
737 ipfw_config_nat(int ac, char **av)
738 {
739 	struct cfg_nat *n;		/* Nat instance configuration. */
740 	int i, off, tok, ac1;
741 	char *id, *buf, **av1, *end;
742 	size_t len;
743 
744 	av++;
745 	ac--;
746 	/* Nat id. */
747 	if (ac == 0)
748 		errx(EX_DATAERR, "missing nat id");
749 	id = *av;
750 	i = (int)strtol(id, &end, 0);
751 	if (i <= 0 || *end != '\0')
752 		errx(EX_DATAERR, "illegal nat id: %s", id);
753 	av++;
754 	ac--;
755 	if (ac == 0)
756 		errx(EX_DATAERR, "missing option");
757 
758 	len = sizeof(struct cfg_nat);
759 	ac1 = ac;
760 	av1 = av;
761 	while (ac1 > 0) {
762 		tok = match_token(nat_params, *av1);
763 		ac1--;
764 		av1++;
765 		switch (tok) {
766 		case TOK_IP:
767 		case TOK_IF:
768 			ac1--;
769 			av1++;
770 			break;
771 		case TOK_ALOG:
772 		case TOK_DENY_INC:
773 		case TOK_SAME_PORTS:
774 		case TOK_SKIP_GLOBAL:
775 		case TOK_UNREG_ONLY:
776 		case TOK_RESET_ADDR:
777 		case TOK_ALIAS_REV:
778 		case TOK_PROXY_ONLY:
779 			break;
780 		case TOK_REDIR_ADDR:
781 			if (ac1 < 2)
782 				errx(EX_DATAERR, "redirect_addr: "
783 				    "not enough arguments");
784 			len += estimate_redir_addr(&ac1, &av1);
785 			av1 += 2;
786 			ac1 -= 2;
787 			break;
788 		case TOK_REDIR_PORT:
789 			if (ac1 < 3)
790 				errx(EX_DATAERR, "redirect_port: "
791 				    "not enough arguments");
792 			av1++;
793 			ac1--;
794 			len += estimate_redir_port(&ac1, &av1);
795 			av1 += 2;
796 			ac1 -= 2;
797 			/* Skip optional remoteIP/port */
798 			if (ac1 != 0 && isdigit(**av1)) {
799 				av1++;
800 				ac1--;
801 			}
802 			break;
803 		case TOK_REDIR_PROTO:
804 			if (ac1 < 2)
805 				errx(EX_DATAERR, "redirect_proto: "
806 				    "not enough arguments");
807 			len += sizeof(struct cfg_redir);
808 			av1 += 2;
809 			ac1 -= 2;
810 			/* Skip optional remoteIP/port */
811 			if (ac1 != 0 && isdigit(**av1)) {
812 				av1++;
813 				ac1--;
814 			}
815 			if (ac1 != 0 && isdigit(**av1)) {
816 				av1++;
817 				ac1--;
818 			}
819 			break;
820 		default:
821 			errx(EX_DATAERR, "unrecognised option ``%s''", av1[-1]);
822 		}
823 	}
824 
825 	if ((buf = malloc(len)) == NULL)
826 		errx(EX_OSERR, "malloc failed");
827 
828 	/* Offset in buf: save space for n at the beginning. */
829 	off = sizeof(*n);
830 	memset(buf, 0, len);
831 	n = (struct cfg_nat *)buf;
832 	n->id = i;
833 
834 	while (ac > 0) {
835 		tok = match_token(nat_params, *av);
836 		ac--;
837 		av++;
838 		switch (tok) {
839 		case TOK_IP:
840 			if (ac == 0)
841 				errx(EX_DATAERR, "missing option");
842 			if (!inet_aton(av[0], &(n->ip)))
843 				errx(EX_DATAERR, "bad ip address ``%s''",
844 				    av[0]);
845 			ac--;
846 			av++;
847 			break;
848 		case TOK_IF:
849 			if (ac == 0)
850 				errx(EX_DATAERR, "missing option");
851 			set_addr_dynamic(av[0], n);
852 			ac--;
853 			av++;
854 			break;
855 		case TOK_ALOG:
856 			n->mode |= PKT_ALIAS_LOG;
857 			break;
858 		case TOK_DENY_INC:
859 			n->mode |= PKT_ALIAS_DENY_INCOMING;
860 			break;
861 		case TOK_SAME_PORTS:
862 			n->mode |= PKT_ALIAS_SAME_PORTS;
863 			break;
864 		case TOK_UNREG_ONLY:
865 			n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
866 			break;
867 		case TOK_SKIP_GLOBAL:
868 			n->mode |= PKT_ALIAS_SKIP_GLOBAL;
869 			break;
870 		case TOK_RESET_ADDR:
871 			n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
872 			break;
873 		case TOK_ALIAS_REV:
874 			n->mode |= PKT_ALIAS_REVERSE;
875 			break;
876 		case TOK_PROXY_ONLY:
877 			n->mode |= PKT_ALIAS_PROXY_ONLY;
878 			break;
879 			/*
880 			 * All the setup_redir_* functions work directly in
881 			 * the final buffer, see above for details.
882 			 */
883 		case TOK_REDIR_ADDR:
884 		case TOK_REDIR_PORT:
885 		case TOK_REDIR_PROTO:
886 			switch (tok) {
887 			case TOK_REDIR_ADDR:
888 				i = setup_redir_addr(&buf[off], &ac, &av);
889 				break;
890 			case TOK_REDIR_PORT:
891 				i = setup_redir_port(&buf[off], &ac, &av);
892 				break;
893 			case TOK_REDIR_PROTO:
894 				i = setup_redir_proto(&buf[off], &ac, &av);
895 				break;
896 			}
897 			n->redir_cnt++;
898 			off += i;
899 			break;
900 		}
901 	}
902 
903 	i = do_cmd(IP_FW_NAT_CFG, buf, off);
904 	if (i)
905 		err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
906 
907 	if (!co.do_quiet) {
908 		/* After every modification, we show the resultant rule. */
909 		int _ac = 3;
910 		const char *_av[] = {"show", "config", id};
911 		ipfw_show_nat(_ac, (char **)(void *)_av);
912 	}
913 }
914 
915 
916 void
917 ipfw_show_nat(int ac, char **av)
918 {
919 	struct cfg_nat *n;
920 	struct cfg_redir *e;
921 	int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
922 	int nat_cnt, redir_cnt, r;
923 	uint8_t *data, *p;
924 	char *endptr;
925 
926 	do_rule = 0;
927 	nalloc = 1024;
928 	size = 0;
929 	data = NULL;
930 	frule = 0;
931 	lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
932 	ac--;
933 	av++;
934 
935 	if (co.test_only)
936 		return;
937 
938 	/* Parse parameters. */
939 	for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
940 		if (!strncmp(av[0], "config", strlen(av[0]))) {
941 			cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
942 			continue;
943 		}
944 		/* Convert command line rule #. */
945 		frule = lrule = strtoul(av[0], &endptr, 10);
946 		if (*endptr == '-')
947 			lrule = strtoul(endptr+1, &endptr, 10);
948 		if (lrule == 0)
949 			err(EX_USAGE, "invalid rule number: %s", av[0]);
950 		do_rule = 1;
951 	}
952 
953 	nbytes = nalloc;
954 	while (nbytes >= nalloc) {
955 		nalloc = nalloc * 2;
956 		nbytes = nalloc;
957 		data = safe_realloc(data, nbytes);
958 		if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
959 			err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
960 			    (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
961 	}
962 	if (nbytes == 0)
963 		exit(0);
964 	if (do_cfg) {
965 		nat_cnt = *((int *)data);
966 		for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
967 			n = (struct cfg_nat *)&data[i];
968 			if (frule <= n->id && lrule >= n->id)
969 				print_nat_config(&data[i]);
970 			i += sizeof(struct cfg_nat);
971 			for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
972 				e = (struct cfg_redir *)&data[i];
973 				i += sizeof(struct cfg_redir) + e->spool_cnt *
974 				    sizeof(struct cfg_spool);
975 			}
976 		}
977 	} else {
978 		for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
979 			p = &data[i];
980 			if (p == data + nbytes)
981 				break;
982 			bcopy(p, &r, sizeof(int));
983 			if (do_rule) {
984 				if (!(frule <= r && lrule >= r))
985 					continue;
986 			}
987 			printf("nat %u: %s\n", r, p+sizeof(int));
988 		}
989 	}
990 }
991