xref: /f-stack/tools/ipfw/nat.c (revision ebf5cedb)
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 <errno.h>
34 #include <netdb.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sysexits.h>
39 
40 #include <net/if.h>
41 #include <net/if_dl.h>
42 #include <net/route.h> /* def. of struct route */
43 #include <netinet/in.h>
44 #include <netinet/ip_fw.h>
45 #include <arpa/inet.h>
46 #include <alias.h>
47 
48 typedef int (nat_cb_t)(struct nat44_cfg_nat *cfg, void *arg);
49 static void nat_show_cfg(struct nat44_cfg_nat *n, void *arg);
50 static void nat_show_log(struct nat44_cfg_nat *n, void *arg);
51 static int nat_show_data(struct nat44_cfg_nat *cfg, void *arg);
52 static int natname_cmp(const void *a, const void *b);
53 static int nat_foreach(nat_cb_t *f, void *arg, int sort);
54 static int nat_get_cmd(char *name, uint16_t cmd, ipfw_obj_header **ooh);
55 
56 static struct _s_x nat_params[] = {
57 	{ "ip",			TOK_IP },
58 	{ "if",			TOK_IF },
59  	{ "log",		TOK_ALOG },
60  	{ "deny_in",		TOK_DENY_INC },
61  	{ "same_ports",		TOK_SAME_PORTS },
62  	{ "unreg_only",		TOK_UNREG_ONLY },
63 	{ "skip_global",	TOK_SKIP_GLOBAL },
64  	{ "reset",		TOK_RESET_ADDR },
65  	{ "reverse",		TOK_ALIAS_REV },
66  	{ "proxy_only",		TOK_PROXY_ONLY },
67 	{ "redirect_addr",	TOK_REDIR_ADDR },
68 	{ "redirect_port",	TOK_REDIR_PORT },
69 	{ "redirect_proto",	TOK_REDIR_PROTO },
70  	{ NULL, 0 }	/* terminator */
71 };
72 
73 
74 /*
75  * Search for interface with name "ifn", and fill n accordingly:
76  *
77  * n->ip	ip address of interface "ifn"
78  * n->if_name   copy of interface name "ifn"
79  */
80 static void
81 set_addr_dynamic(const char *ifn, struct nat44_cfg_nat *n)
82 {
83 	size_t needed;
84 	int mib[6];
85 	char *buf, *lim, *next;
86 	struct if_msghdr *ifm;
87 	struct ifa_msghdr *ifam;
88 	struct sockaddr_dl *sdl;
89 	struct sockaddr_in *sin;
90 	int ifIndex;
91 
92 	mib[0] = CTL_NET;
93 	mib[1] = PF_ROUTE;
94 	mib[2] = 0;
95 	mib[3] = AF_INET;
96 	mib[4] = NET_RT_IFLIST;
97 	mib[5] = 0;
98 /*
99  * Get interface data.
100  */
101 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
102 		err(1, "iflist-sysctl-estimate");
103 	buf = safe_calloc(1, needed);
104 	if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
105 		err(1, "iflist-sysctl-get");
106 	lim = buf + needed;
107 /*
108  * Loop through interfaces until one with
109  * given name is found. This is done to
110  * find correct interface index for routing
111  * message processing.
112  */
113 	ifIndex	= 0;
114 	next = buf;
115 	while (next < lim) {
116 		ifm = (struct if_msghdr *)next;
117 		next += ifm->ifm_msglen;
118 		if (ifm->ifm_version != RTM_VERSION) {
119 			if (co.verbose)
120 				warnx("routing message version %d "
121 				    "not understood", ifm->ifm_version);
122 			continue;
123 		}
124 		if (ifm->ifm_type == RTM_IFINFO) {
125 			sdl = (struct sockaddr_dl *)(ifm + 1);
126 			if (strlen(ifn) == sdl->sdl_nlen &&
127 			    strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
128 				ifIndex = ifm->ifm_index;
129 				break;
130 			}
131 		}
132 	}
133 	if (!ifIndex)
134 		errx(1, "unknown interface name %s", ifn);
135 /*
136  * Get interface address.
137  */
138 	sin = NULL;
139 	while (next < lim) {
140 		ifam = (struct ifa_msghdr *)next;
141 		next += ifam->ifam_msglen;
142 		if (ifam->ifam_version != RTM_VERSION) {
143 			if (co.verbose)
144 				warnx("routing message version %d "
145 				    "not understood", ifam->ifam_version);
146 			continue;
147 		}
148 		if (ifam->ifam_type != RTM_NEWADDR)
149 			break;
150 		if (ifam->ifam_addrs & RTA_IFA) {
151 			int i;
152 			char *cp = (char *)(ifam + 1);
153 
154 			for (i = 1; i < RTA_IFA; i <<= 1) {
155 				if (ifam->ifam_addrs & i)
156 					cp += SA_SIZE((struct sockaddr *)cp);
157 			}
158 			if (((struct sockaddr *)cp)->sa_family == AF_INET) {
159 				sin = (struct sockaddr_in *)cp;
160 				break;
161 			}
162 		}
163 	}
164 	if (sin == NULL)
165 		n->ip.s_addr = htonl(INADDR_ANY);
166 	else
167 		n->ip = sin->sin_addr;
168 	strncpy(n->if_name, ifn, IF_NAMESIZE);
169 
170 	free(buf);
171 }
172 
173 /*
174  * XXX - The following functions, macros and definitions come from natd.c:
175  * it would be better to move them outside natd.c, in a file
176  * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
177  * with it.
178  */
179 
180 /*
181  * Definition of a port range, and macros to deal with values.
182  * FORMAT:  HI 16-bits == first port in range, 0 == all ports.
183  *	  LO 16-bits == number of ports in range
184  * NOTES:   - Port values are not stored in network byte order.
185  */
186 
187 #define port_range u_long
188 
189 #define GETLOPORT(x)	((x) >> 0x10)
190 #define GETNUMPORTS(x)	((x) & 0x0000ffff)
191 #define GETHIPORT(x)	(GETLOPORT((x)) + GETNUMPORTS((x)))
192 
193 /* Set y to be the low-port value in port_range variable x. */
194 #define SETLOPORT(x,y)   ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
195 
196 /* Set y to be the number of ports in port_range variable x. */
197 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
198 
199 static void
200 StrToAddr (const char* str, struct in_addr* addr)
201 {
202 	struct hostent* hp;
203 
204 	if (inet_aton (str, addr))
205 		return;
206 #ifdef FSTACK
207 	else
208 		errx (1, "invalid addr %d", addr->s_addr);
209 #else
210 
211 	hp = gethostbyname (str);
212 	if (!hp)
213 		errx (1, "unknown host %s", str);
214 
215 	memcpy (addr, hp->h_addr, sizeof (struct in_addr));
216 #endif
217 }
218 
219 static int
220 StrToPortRange (const char* str, const char* proto, port_range *portRange)
221 {
222 	char*	   sep;
223 	struct servent*	sp;
224 	char*		end;
225 	u_short	 loPort;
226 	u_short	 hiPort;
227 
228 	/* First see if this is a service, return corresponding port if so. */
229 	sp = getservbyname (str,proto);
230 	if (sp) {
231 		SETLOPORT(*portRange, ntohs(sp->s_port));
232 		SETNUMPORTS(*portRange, 1);
233 		return 0;
234 	}
235 
236 	/* Not a service, see if it's a single port or port range. */
237 	sep = strchr (str, '-');
238 	if (sep == NULL) {
239 		SETLOPORT(*portRange, strtol(str, &end, 10));
240 		if (end != str) {
241 			/* Single port. */
242 			SETNUMPORTS(*portRange, 1);
243 			return 0;
244 		}
245 
246 		/* Error in port range field. */
247 		errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
248 	}
249 
250 	/* Port range, get the values and sanity check. */
251 	sscanf (str, "%hu-%hu", &loPort, &hiPort);
252 	SETLOPORT(*portRange, loPort);
253 	SETNUMPORTS(*portRange, 0);	/* Error by default */
254 	if (loPort <= hiPort)
255 		SETNUMPORTS(*portRange, hiPort - loPort + 1);
256 
257 	if (GETNUMPORTS(*portRange) == 0)
258 		errx (EX_DATAERR, "invalid port range %s", str);
259 
260 	return 0;
261 }
262 
263 static int
264 StrToProto (const char* str)
265 {
266 	if (!strcmp (str, "tcp"))
267 		return IPPROTO_TCP;
268 
269 	if (!strcmp (str, "udp"))
270 		return IPPROTO_UDP;
271 
272 	if (!strcmp (str, "sctp"))
273 		return IPPROTO_SCTP;
274 	errx (EX_DATAERR, "unknown protocol %s. Expected sctp, tcp or udp", str);
275 }
276 
277 static int
278 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
279 			port_range *portRange)
280 {
281 	char*	ptr;
282 
283 	ptr = strchr (str, ':');
284 	if (!ptr)
285 		errx (EX_DATAERR, "%s is missing port number", str);
286 
287 	*ptr = '\0';
288 	++ptr;
289 
290 	StrToAddr (str, addr);
291 	return StrToPortRange (ptr, proto, portRange);
292 }
293 
294 /* End of stuff taken from natd.c. */
295 
296 /*
297  * The next 3 functions add support for the addr, port and proto redirect and
298  * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
299  * and SetupProtoRedirect() from natd.c.
300  *
301  * Every setup_* function fills at least one redirect entry
302  * (struct nat44_cfg_redir) and zero or more server pool entry
303  * (struct nat44_cfg_spool) in buf.
304  *
305  * The format of data in buf is:
306  *
307  *  nat44_cfg_nat nat44_cfg_redir nat44_cfg_spool    ......  nat44_cfg_spool
308  *
309  *    -------------------------------------        ------------
310  *   |           | .....X ..... |          |         |           |  .....
311  *    ------------------------------------- ...... ------------
312  *                     ^
313  *                spool_cnt       n=0       ......   n=(X-1)
314  *
315  * len points to the amount of available space in buf
316  * space counts the memory consumed by every function
317  *
318  * XXX - Every function get all the argv params so it
319  * has to check, in optional parameters, that the next
320  * args is a valid option for the redir entry and not
321  * another token. Only redir_port and redir_proto are
322  * affected by this.
323  */
324 
325 static int
326 estimate_redir_addr(int *ac, char ***av)
327 {
328 	size_t space = sizeof(struct nat44_cfg_redir);
329 	char *sep = **av;
330 	u_int c = 0;
331 
332 	(void)ac;	/* UNUSED */
333 	while ((sep = strchr(sep, ',')) != NULL) {
334 		c++;
335 		sep++;
336 	}
337 
338 	if (c > 0)
339 		c++;
340 
341 	space += c * sizeof(struct nat44_cfg_spool);
342 
343 	return (space);
344 }
345 
346 static int
347 setup_redir_addr(char *buf, int *ac, char ***av)
348 {
349 	struct nat44_cfg_redir *r;
350 	char *sep;
351 	size_t space;
352 
353 	r = (struct nat44_cfg_redir *)buf;
354 	r->mode = REDIR_ADDR;
355 	/* Skip nat44_cfg_redir at beginning of buf. */
356 	buf = &buf[sizeof(struct nat44_cfg_redir)];
357 	space = sizeof(struct nat44_cfg_redir);
358 
359 	/* Extract local address. */
360 	if (strchr(**av, ',') != NULL) {
361 		struct nat44_cfg_spool *spool;
362 
363 		/* Setup LSNAT server pool. */
364 		r->laddr.s_addr = INADDR_NONE;
365 		sep = strtok(**av, ",");
366 		while (sep != NULL) {
367 			spool = (struct nat44_cfg_spool *)buf;
368 			space += sizeof(struct nat44_cfg_spool);
369 			StrToAddr(sep, &spool->addr);
370 			spool->port = ~0;
371 			r->spool_cnt++;
372 			/* Point to the next possible nat44_cfg_spool. */
373 			buf = &buf[sizeof(struct nat44_cfg_spool)];
374 			sep = strtok(NULL, ",");
375 		}
376 	} else
377 		StrToAddr(**av, &r->laddr);
378 	(*av)++; (*ac)--;
379 
380 	/* Extract public address. */
381 	StrToAddr(**av, &r->paddr);
382 	(*av)++; (*ac)--;
383 
384 	return (space);
385 }
386 
387 static int
388 estimate_redir_port(int *ac, char ***av)
389 {
390 	size_t space = sizeof(struct nat44_cfg_redir);
391 	char *sep = **av;
392 	u_int c = 0;
393 
394 	(void)ac;	/* UNUSED */
395 	while ((sep = strchr(sep, ',')) != NULL) {
396 		c++;
397 		sep++;
398 	}
399 
400 	if (c > 0)
401 		c++;
402 
403 	space += c * sizeof(struct nat44_cfg_spool);
404 
405 	return (space);
406 }
407 
408 static int
409 setup_redir_port(char *buf, int *ac, char ***av)
410 {
411 	struct nat44_cfg_redir *r;
412 	char *sep, *protoName, *lsnat = NULL;
413 	size_t space;
414 	u_short numLocalPorts;
415 	port_range portRange;
416 
417 	numLocalPorts = 0;
418 
419 	r = (struct nat44_cfg_redir *)buf;
420 	r->mode = REDIR_PORT;
421 	/* Skip nat44_cfg_redir at beginning of buf. */
422 	buf = &buf[sizeof(struct nat44_cfg_redir)];
423 	space = sizeof(struct nat44_cfg_redir);
424 
425 	/*
426 	 * Extract protocol.
427 	 */
428 	r->proto = StrToProto(**av);
429 	protoName = **av;
430 	(*av)++; (*ac)--;
431 
432 	/*
433 	 * Extract local address.
434 	 */
435 	if (strchr(**av, ',') != NULL) {
436 		r->laddr.s_addr = INADDR_NONE;
437 		r->lport = ~0;
438 		numLocalPorts = 1;
439 		lsnat = **av;
440 	} else {
441 		/*
442 		 * The sctp nat does not allow the port numbers to be mapped to
443 		 * new port numbers. Therefore, no ports are to be specified
444 		 * in the target port field.
445 		 */
446 		if (r->proto == IPPROTO_SCTP) {
447 			if (strchr(**av, ':'))
448 				errx(EX_DATAERR, "redirect_port:"
449 				    "port numbers do not change in sctp, so do "
450 				    "not specify them as part of the target");
451 			else
452 				StrToAddr(**av, &r->laddr);
453 		} else {
454 			if (StrToAddrAndPortRange(**av, &r->laddr, protoName,
455 			    &portRange) != 0)
456 				errx(EX_DATAERR, "redirect_port: "
457 				    "invalid local port range");
458 
459 			r->lport = GETLOPORT(portRange);
460 			numLocalPorts = GETNUMPORTS(portRange);
461 		}
462 	}
463 	(*av)++; (*ac)--;
464 
465 	/*
466 	 * Extract public port and optionally address.
467 	 */
468 	if (strchr(**av, ':') != NULL) {
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 	(*av)++; (*ac)--;
487 
488 	/*
489 	 * Extract remote address and optionally port.
490 	 */
491 	/*
492 	 * NB: isdigit(**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 && isdigit(***av)) {
496 		if (strchr(**av, ':') != NULL) {
497 			if (StrToAddrAndPortRange(**av, &r->raddr, protoName,
498 			    &portRange) != 0)
499 				errx(EX_DATAERR, "redirect_port: "
500 				    "invalid remote port range");
501 		} else {
502 			SETLOPORT(portRange, 0);
503 			SETNUMPORTS(portRange, 1);
504 			StrToAddr(**av, &r->raddr);
505 		}
506 		(*av)++; (*ac)--;
507 	} else {
508 		SETLOPORT(portRange, 0);
509 		SETNUMPORTS(portRange, 1);
510 		r->raddr.s_addr = INADDR_ANY;
511 	}
512 	r->rport = GETLOPORT(portRange);
513 	r->rport_cnt = GETNUMPORTS(portRange);
514 
515 	/*
516 	 * Make sure port ranges match up, then add the redirect ports.
517 	 */
518 	if (numLocalPorts != r->pport_cnt)
519 		errx(EX_DATAERR, "redirect_port: "
520 		    "port ranges must be equal in size");
521 
522 	/* Remote port range is allowed to be '0' which means all ports. */
523 	if (r->rport_cnt != numLocalPorts &&
524 	    (r->rport_cnt != 1 || r->rport != 0))
525 		errx(EX_DATAERR, "redirect_port: remote port must"
526 		    "be 0 or equal to local port range in size");
527 
528 	/* Setup LSNAT server pool. */
529 	if (lsnat != NULL) {
530 		struct nat44_cfg_spool *spool;
531 
532 		sep = strtok(lsnat, ",");
533 		while (sep != NULL) {
534 			spool = (struct nat44_cfg_spool *)buf;
535 			space += sizeof(struct nat44_cfg_spool);
536 			/*
537 			 * The sctp nat does not allow the port numbers to
538 			 * be mapped to new port numbers. Therefore, no ports
539 			 * are to be specified in the target port field.
540 			 */
541 			if (r->proto == IPPROTO_SCTP) {
542 				if (strchr (sep, ':')) {
543 					errx(EX_DATAERR, "redirect_port:"
544 					    "port numbers do not change in "
545 					    "sctp, so do not specify them as "
546 					    "part of the target");
547 				} else {
548 					StrToAddr(sep, &spool->addr);
549 					spool->port = r->pport;
550 				}
551 			} else {
552 				if (StrToAddrAndPortRange(sep, &spool->addr,
553 					protoName, &portRange) != 0)
554 					errx(EX_DATAERR, "redirect_port:"
555 					    "invalid local port range");
556 				if (GETNUMPORTS(portRange) != 1)
557 					errx(EX_DATAERR, "redirect_port: "
558 					    "local port must be single in "
559 					    "this context");
560 				spool->port = GETLOPORT(portRange);
561 			}
562 			r->spool_cnt++;
563 			/* Point to the next possible nat44_cfg_spool. */
564 			buf = &buf[sizeof(struct nat44_cfg_spool)];
565 			sep = strtok(NULL, ",");
566 		}
567 	}
568 
569 	return (space);
570 }
571 
572 static int
573 setup_redir_proto(char *buf, int *ac, char ***av)
574 {
575 	struct nat44_cfg_redir *r;
576 	struct protoent *protoent;
577 	size_t space;
578 
579 	r = (struct nat44_cfg_redir *)buf;
580 	r->mode = REDIR_PROTO;
581 	/* Skip nat44_cfg_redir at beginning of buf. */
582 	buf = &buf[sizeof(struct nat44_cfg_redir)];
583 	space = sizeof(struct nat44_cfg_redir);
584 
585 	/*
586 	 * Extract protocol.
587 	 */
588 	protoent = getprotobyname(**av);
589 	if (protoent == NULL)
590 		errx(EX_DATAERR, "redirect_proto: unknown protocol %s", **av);
591 	else
592 		r->proto = protoent->p_proto;
593 
594 	(*av)++; (*ac)--;
595 
596 	/*
597 	 * Extract local address.
598 	 */
599 	StrToAddr(**av, &r->laddr);
600 
601 	(*av)++; (*ac)--;
602 
603 	/*
604 	 * Extract optional public address.
605 	 */
606 	if (*ac == 0) {
607 		r->paddr.s_addr = INADDR_ANY;
608 		r->raddr.s_addr = INADDR_ANY;
609 	} else {
610 		/* see above in setup_redir_port() */
611 		if (isdigit(***av)) {
612 			StrToAddr(**av, &r->paddr);
613 			(*av)++; (*ac)--;
614 
615 			/*
616 			 * Extract optional remote address.
617 			 */
618 			/* see above in setup_redir_port() */
619 			if (*ac != 0 && isdigit(***av)) {
620 				StrToAddr(**av, &r->raddr);
621 				(*av)++; (*ac)--;
622 			}
623 		}
624 	}
625 
626 	return (space);
627 }
628 
629 static void
630 nat_show_log(struct nat44_cfg_nat *n, void *arg)
631 {
632 	char *buf;
633 
634 	buf = (char *)(n + 1);
635 	if (buf[0] != '\0')
636 		printf("nat %s: %s\n", n->name, buf);
637 }
638 
639 static void
640 nat_show_cfg(struct nat44_cfg_nat *n, void *arg)
641 {
642 	int i, cnt, off;
643 	struct nat44_cfg_redir *t;
644 	struct nat44_cfg_spool *s;
645 	caddr_t buf;
646 	struct protoent *p;
647 
648 	buf = (caddr_t)n;
649 	off = sizeof(*n);
650 	printf("ipfw nat %s config", n->name);
651 	if (strlen(n->if_name) != 0)
652 		printf(" if %s", n->if_name);
653 	else if (n->ip.s_addr != 0)
654 		printf(" ip %s", inet_ntoa(n->ip));
655 	while (n->mode != 0) {
656 		if (n->mode & PKT_ALIAS_LOG) {
657 			printf(" log");
658 			n->mode &= ~PKT_ALIAS_LOG;
659 		} else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
660 			printf(" deny_in");
661 			n->mode &= ~PKT_ALIAS_DENY_INCOMING;
662 		} else if (n->mode & PKT_ALIAS_SAME_PORTS) {
663 			printf(" same_ports");
664 			n->mode &= ~PKT_ALIAS_SAME_PORTS;
665 		} else if (n->mode & PKT_ALIAS_SKIP_GLOBAL) {
666 			printf(" skip_global");
667 			n->mode &= ~PKT_ALIAS_SKIP_GLOBAL;
668 		} else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
669 			printf(" unreg_only");
670 			n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
671 		} else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
672 			printf(" reset");
673 			n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
674 		} else if (n->mode & PKT_ALIAS_REVERSE) {
675 			printf(" reverse");
676 			n->mode &= ~PKT_ALIAS_REVERSE;
677 		} else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
678 			printf(" proxy_only");
679 			n->mode &= ~PKT_ALIAS_PROXY_ONLY;
680 		}
681 	}
682 	/* Print all the redirect's data configuration. */
683 	for (cnt = 0; cnt < n->redir_cnt; cnt++) {
684 		t = (struct nat44_cfg_redir *)&buf[off];
685 		off += sizeof(struct nat44_cfg_redir);
686 		switch (t->mode) {
687 		case REDIR_ADDR:
688 			printf(" redirect_addr");
689 			if (t->spool_cnt == 0)
690 				printf(" %s", inet_ntoa(t->laddr));
691 			else
692 				for (i = 0; i < t->spool_cnt; i++) {
693 					s = (struct nat44_cfg_spool *)&buf[off];
694 					if (i)
695 						printf(",");
696 					else
697 						printf(" ");
698 					printf("%s", inet_ntoa(s->addr));
699 					off += sizeof(struct nat44_cfg_spool);
700 				}
701 			printf(" %s", inet_ntoa(t->paddr));
702 			break;
703 		case REDIR_PORT:
704 			p = getprotobynumber(t->proto);
705 			printf(" redirect_port %s ", p->p_name);
706 			if (!t->spool_cnt) {
707 				printf("%s:%u", inet_ntoa(t->laddr), t->lport);
708 				if (t->pport_cnt > 1)
709 					printf("-%u", t->lport +
710 					    t->pport_cnt - 1);
711 			} else
712 				for (i=0; i < t->spool_cnt; i++) {
713 					s = (struct nat44_cfg_spool *)&buf[off];
714 					if (i)
715 						printf(",");
716 					printf("%s:%u", inet_ntoa(s->addr),
717 					    s->port);
718 					off += sizeof(struct nat44_cfg_spool);
719 				}
720 
721 			printf(" ");
722 			if (t->paddr.s_addr)
723 				printf("%s:", inet_ntoa(t->paddr));
724 			printf("%u", t->pport);
725 			if (!t->spool_cnt && t->pport_cnt > 1)
726 				printf("-%u", t->pport + t->pport_cnt - 1);
727 
728 			if (t->raddr.s_addr) {
729 				printf(" %s", inet_ntoa(t->raddr));
730 				if (t->rport) {
731 					printf(":%u", t->rport);
732 					if (!t->spool_cnt && t->rport_cnt > 1)
733 						printf("-%u", t->rport +
734 						    t->rport_cnt - 1);
735 				}
736 			}
737 			break;
738 		case REDIR_PROTO:
739 			p = getprotobynumber(t->proto);
740 			printf(" redirect_proto %s %s", p->p_name,
741 			    inet_ntoa(t->laddr));
742 			if (t->paddr.s_addr != 0) {
743 				printf(" %s", inet_ntoa(t->paddr));
744 				if (t->raddr.s_addr)
745 					printf(" %s", inet_ntoa(t->raddr));
746 			}
747 			break;
748 		default:
749 			errx(EX_DATAERR, "unknown redir mode");
750 			break;
751 		}
752 	}
753 	printf("\n");
754 }
755 
756 void
757 ipfw_config_nat(int ac, char **av)
758 {
759 	ipfw_obj_header *oh;
760 	struct nat44_cfg_nat *n;		/* Nat instance configuration. */
761 	int i, off, tok, ac1;
762 	char *id, *buf, **av1, *end;
763 	size_t len;
764 
765 	av++;
766 	ac--;
767 	/* Nat id. */
768 	if (ac == 0)
769 		errx(EX_DATAERR, "missing nat id");
770 	id = *av;
771 	i = (int)strtol(id, &end, 0);
772 	if (i <= 0 || *end != '\0')
773 		errx(EX_DATAERR, "illegal nat id: %s", id);
774 	av++;
775 	ac--;
776 	if (ac == 0)
777 		errx(EX_DATAERR, "missing option");
778 
779 	len = sizeof(*oh) + sizeof(*n);
780 	ac1 = ac;
781 	av1 = av;
782 	while (ac1 > 0) {
783 		tok = match_token(nat_params, *av1);
784 		ac1--;
785 		av1++;
786 		switch (tok) {
787 		case TOK_IP:
788 		case TOK_IF:
789 			ac1--;
790 			av1++;
791 			break;
792 		case TOK_ALOG:
793 		case TOK_DENY_INC:
794 		case TOK_SAME_PORTS:
795 		case TOK_SKIP_GLOBAL:
796 		case TOK_UNREG_ONLY:
797 		case TOK_RESET_ADDR:
798 		case TOK_ALIAS_REV:
799 		case TOK_PROXY_ONLY:
800 			break;
801 		case TOK_REDIR_ADDR:
802 			if (ac1 < 2)
803 				errx(EX_DATAERR, "redirect_addr: "
804 				    "not enough arguments");
805 			len += estimate_redir_addr(&ac1, &av1);
806 			av1 += 2;
807 			ac1 -= 2;
808 			break;
809 		case TOK_REDIR_PORT:
810 			if (ac1 < 3)
811 				errx(EX_DATAERR, "redirect_port: "
812 				    "not enough arguments");
813 			av1++;
814 			ac1--;
815 			len += estimate_redir_port(&ac1, &av1);
816 			av1 += 2;
817 			ac1 -= 2;
818 			/* Skip optional remoteIP/port */
819 			if (ac1 != 0 && isdigit(**av1)) {
820 				av1++;
821 				ac1--;
822 			}
823 			break;
824 		case TOK_REDIR_PROTO:
825 			if (ac1 < 2)
826 				errx(EX_DATAERR, "redirect_proto: "
827 				    "not enough arguments");
828 			len += sizeof(struct nat44_cfg_redir);
829 			av1 += 2;
830 			ac1 -= 2;
831 			/* Skip optional remoteIP/port */
832 			if (ac1 != 0 && isdigit(**av1)) {
833 				av1++;
834 				ac1--;
835 			}
836 			if (ac1 != 0 && isdigit(**av1)) {
837 				av1++;
838 				ac1--;
839 			}
840 			break;
841 		default:
842 			errx(EX_DATAERR, "unrecognised option ``%s''", av1[-1]);
843 		}
844 	}
845 
846 	if ((buf = malloc(len)) == NULL)
847 		errx(EX_OSERR, "malloc failed");
848 
849 	/* Offset in buf: save space for header at the beginning. */
850 	off = sizeof(*oh) + sizeof(*n);
851 	memset(buf, 0, len);
852 	oh = (ipfw_obj_header *)buf;
853 	n = (struct nat44_cfg_nat *)(oh + 1);
854 	oh->ntlv.head.length = sizeof(oh->ntlv);
855 	snprintf(oh->ntlv.name, sizeof(oh->ntlv.name), "%d", i);
856 	snprintf(n->name, sizeof(n->name), "%d", i);
857 
858 	while (ac > 0) {
859 		tok = match_token(nat_params, *av);
860 		ac--;
861 		av++;
862 		switch (tok) {
863 		case TOK_IP:
864 			if (ac == 0)
865 				errx(EX_DATAERR, "missing option");
866 			if (!inet_aton(av[0], &(n->ip)))
867 				errx(EX_DATAERR, "bad ip address ``%s''",
868 				    av[0]);
869 			ac--;
870 			av++;
871 			break;
872 		case TOK_IF:
873 			if (ac == 0)
874 				errx(EX_DATAERR, "missing option");
875 			set_addr_dynamic(av[0], n);
876 			ac--;
877 			av++;
878 			break;
879 		case TOK_ALOG:
880 			n->mode |= PKT_ALIAS_LOG;
881 			break;
882 		case TOK_DENY_INC:
883 			n->mode |= PKT_ALIAS_DENY_INCOMING;
884 			break;
885 		case TOK_SAME_PORTS:
886 			n->mode |= PKT_ALIAS_SAME_PORTS;
887 			break;
888 		case TOK_UNREG_ONLY:
889 			n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
890 			break;
891 		case TOK_SKIP_GLOBAL:
892 			n->mode |= PKT_ALIAS_SKIP_GLOBAL;
893 			break;
894 		case TOK_RESET_ADDR:
895 			n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
896 			break;
897 		case TOK_ALIAS_REV:
898 			n->mode |= PKT_ALIAS_REVERSE;
899 			break;
900 		case TOK_PROXY_ONLY:
901 			n->mode |= PKT_ALIAS_PROXY_ONLY;
902 			break;
903 			/*
904 			 * All the setup_redir_* functions work directly in
905 			 * the final buffer, see above for details.
906 			 */
907 		case TOK_REDIR_ADDR:
908 		case TOK_REDIR_PORT:
909 		case TOK_REDIR_PROTO:
910 			switch (tok) {
911 			case TOK_REDIR_ADDR:
912 				i = setup_redir_addr(&buf[off], &ac, &av);
913 				break;
914 			case TOK_REDIR_PORT:
915 				i = setup_redir_port(&buf[off], &ac, &av);
916 				break;
917 			case TOK_REDIR_PROTO:
918 				i = setup_redir_proto(&buf[off], &ac, &av);
919 				break;
920 			}
921 			n->redir_cnt++;
922 			off += i;
923 			break;
924 		}
925 	}
926 
927 	i = do_set3(IP_FW_NAT44_XCONFIG, &oh->opheader, len);
928 	if (i != 0)
929 		err(1, "setsockopt(%s)", "IP_FW_NAT44_XCONFIG");
930 
931 	if (!co.do_quiet) {
932 		/* After every modification, we show the resultant rule. */
933 		int _ac = 3;
934 		const char *_av[] = {"show", "config", id};
935 		ipfw_show_nat(_ac, (char **)(void *)_av);
936 	}
937 }
938 
939 struct nat_list_arg {
940 	uint16_t	cmd;
941 	int		is_all;
942 };
943 
944 static int
945 nat_show_data(struct nat44_cfg_nat *cfg, void *arg)
946 {
947 	struct nat_list_arg *nla;
948 	ipfw_obj_header *oh;
949 
950 	nla = (struct nat_list_arg *)arg;
951 
952 	switch (nla->cmd) {
953 	case IP_FW_NAT44_XGETCONFIG:
954 		if (nat_get_cmd(cfg->name, nla->cmd, &oh) != 0) {
955 			warnx("Error getting nat instance %s info", cfg->name);
956 			break;
957 		}
958 		nat_show_cfg((struct nat44_cfg_nat *)(oh + 1), NULL);
959 		free(oh);
960 		break;
961 	case IP_FW_NAT44_XGETLOG:
962 		if (nat_get_cmd(cfg->name, nla->cmd, &oh) == 0) {
963 			nat_show_log((struct nat44_cfg_nat *)(oh + 1), NULL);
964 			free(oh);
965 			break;
966 		}
967 		/* Handle error */
968 		if (nla->is_all != 0 && errno == ENOENT)
969 			break;
970 		warn("Error getting nat instance %s info", cfg->name);
971 		break;
972 	}
973 
974 	return (0);
975 }
976 
977 /*
978  * Compare nat names.
979  * Honor number comparison.
980  */
981 static int
982 natname_cmp(const void *a, const void *b)
983 {
984 	struct nat44_cfg_nat *ia, *ib;
985 
986 	ia = (struct nat44_cfg_nat *)a;
987 	ib = (struct nat44_cfg_nat *)b;
988 
989 	return (stringnum_cmp(ia->name, ib->name));
990 }
991 
992 /*
993  * Retrieves nat list from kernel,
994  * optionally sorts it and calls requested function for each table.
995  * Returns 0 on success.
996  */
997 static int
998 nat_foreach(nat_cb_t *f, void *arg, int sort)
999 {
1000 	ipfw_obj_lheader *olh;
1001 	struct nat44_cfg_nat *cfg;
1002 	size_t sz;
1003 	int i, error;
1004 
1005 	/* Start with reasonable default */
1006 	sz = sizeof(*olh) + 16 * sizeof(struct nat44_cfg_nat);
1007 
1008 	for (;;) {
1009 		if ((olh = calloc(1, sz)) == NULL)
1010 			return (ENOMEM);
1011 
1012 		olh->size = sz;
1013 		if (do_get3(IP_FW_NAT44_LIST_NAT, &olh->opheader, &sz) != 0) {
1014 			sz = olh->size;
1015 			free(olh);
1016 			if (errno == ENOMEM)
1017 				continue;
1018 			return (errno);
1019 		}
1020 
1021 		if (sort != 0)
1022 			qsort(olh + 1, olh->count, olh->objsize, natname_cmp);
1023 
1024 		cfg = (struct nat44_cfg_nat*)(olh + 1);
1025 		for (i = 0; i < olh->count; i++) {
1026 			error = f(cfg, arg); /* Ignore errors for now */
1027 			cfg = (struct nat44_cfg_nat *)((caddr_t)cfg +
1028 			    olh->objsize);
1029 		}
1030 
1031 		free(olh);
1032 		break;
1033 	}
1034 
1035 	return (0);
1036 }
1037 
1038 static int
1039 nat_get_cmd(char *name, uint16_t cmd, ipfw_obj_header **ooh)
1040 {
1041 	ipfw_obj_header *oh;
1042 	struct nat44_cfg_nat *cfg;
1043 	size_t sz;
1044 
1045 	/* Start with reasonable default */
1046 	sz = sizeof(*oh) + sizeof(*cfg) + 128;
1047 
1048 	for (;;) {
1049 		if ((oh = calloc(1, sz)) == NULL)
1050 			return (ENOMEM);
1051 		cfg = (struct nat44_cfg_nat *)(oh + 1);
1052 		oh->ntlv.head.length = sizeof(oh->ntlv);
1053 		strlcpy(oh->ntlv.name, name, sizeof(oh->ntlv.name));
1054 		strlcpy(cfg->name, name, sizeof(cfg->name));
1055 
1056 		if (do_get3(cmd, &oh->opheader, &sz) != 0) {
1057 			sz = cfg->size;
1058 			free(oh);
1059 			if (errno == ENOMEM)
1060 				continue;
1061 			return (errno);
1062 		}
1063 
1064 		*ooh = oh;
1065 		break;
1066 	}
1067 
1068 	return (0);
1069 }
1070 
1071 void
1072 ipfw_show_nat(int ac, char **av)
1073 {
1074 	ipfw_obj_header *oh;
1075 	char *name;
1076 	int cmd;
1077 	struct nat_list_arg nla;
1078 
1079 	ac--;
1080 	av++;
1081 
1082 	if (co.test_only)
1083 		return;
1084 
1085 	/* Parse parameters. */
1086 	cmd = 0; /* XXX: Change to IP_FW_NAT44_XGETLOG @ MFC */
1087 	name = NULL;
1088 	for ( ; ac != 0; ac--, av++) {
1089 		if (!strncmp(av[0], "config", strlen(av[0]))) {
1090 			cmd = IP_FW_NAT44_XGETCONFIG;
1091 			continue;
1092 		}
1093 		if (strcmp(av[0], "log") == 0) {
1094 			cmd = IP_FW_NAT44_XGETLOG;
1095 			continue;
1096 		}
1097 		if (name != NULL)
1098 			err(EX_USAGE,"only one instance name may be specified");
1099 		name = av[0];
1100 	}
1101 
1102 	if (cmd == 0)
1103 		errx(EX_USAGE, "Please specify action. Available: config,log");
1104 
1105 	if (name == NULL) {
1106 		memset(&nla, 0, sizeof(nla));
1107 		nla.cmd = cmd;
1108 		nla.is_all = 1;
1109 		nat_foreach(nat_show_data, &nla, 1);
1110 	} else {
1111 		if (nat_get_cmd(name, cmd, &oh) != 0)
1112 			err(EX_OSERR, "Error getting nat %s instance info", name);
1113 		nat_show_cfg((struct nat44_cfg_nat *)(oh + 1), NULL);
1114 		free(oh);
1115 	}
1116 }
1117 
1118