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