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