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