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