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
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
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.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
20 * $FreeBSD: head/sbin/ipfw/nat.c 187770 2009-01-27 12:01:30Z luigi $
22 * In-kernel nat support
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 #include <sys/sysctl.h>
39 #define IPFW_INTERNAL /* Access to protected structures in ip_fw.h. */
42 #include <net/if_dl.h>
43 #include <net/route.h> /* def. of struct route */
44 #include <netinet/in.h>
45 #include <netinet/ip_fw.h>
46 #include <arpa/inet.h>
49 static struct _s_x nat_params[] = {
53 { "deny_in", TOK_DENY_INC },
54 { "same_ports", TOK_SAME_PORTS },
55 { "unreg_only", TOK_UNREG_ONLY },
56 { "reset", TOK_RESET_ADDR },
57 { "reverse", TOK_ALIAS_REV },
58 { "proxy_only", TOK_PROXY_ONLY },
59 { "redirect_addr", TOK_REDIR_ADDR },
60 { "redirect_port", TOK_REDIR_PORT },
61 { "redirect_proto", TOK_REDIR_PROTO },
62 { NULL, 0 } /* terminator */
67 * Search for interface with name "ifn", and fill n accordingly:
69 * n->ip ip address of interface "ifn"
70 * n->if_name copy of interface name "ifn"
73 set_addr_dynamic(const char *ifn, struct cfg_nat *n)
77 char *buf, *lim, *next;
78 struct if_msghdr *ifm;
79 struct ifa_msghdr *ifam;
80 struct sockaddr_dl *sdl;
81 struct sockaddr_in *sin;
88 mib[4] = NET_RT_IFLIST;
93 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
94 err(1, "iflist-sysctl-estimate");
95 buf = safe_calloc(1, needed);
96 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
97 err(1, "iflist-sysctl-get");
100 * Loop through interfaces until one with
101 * given name is found. This is done to
102 * find correct interface index for routing
103 * message processing.
108 ifm = (struct if_msghdr *)next;
109 next += ifm->ifm_msglen;
110 if (ifm->ifm_version != RTM_VERSION) {
112 warnx("routing message version %d "
113 "not understood", ifm->ifm_version);
116 if (ifm->ifm_type == RTM_IFINFO) {
117 sdl = (struct sockaddr_dl *)(ifm + 1);
118 if (strlen(ifn) == sdl->sdl_nlen &&
119 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
120 ifIndex = ifm->ifm_index;
121 ifMTU = ifm->ifm_data.ifi_mtu;
127 errx(1, "unknown interface name %s", ifn);
129 * Get interface address.
133 ifam = (struct ifa_msghdr *)next;
134 next += ifam->ifam_msglen;
135 if (ifam->ifam_version != RTM_VERSION) {
137 warnx("routing message version %d "
138 "not understood", ifam->ifam_version);
141 if (ifam->ifam_type != RTM_NEWADDR)
143 if (ifam->ifam_addrs & RTA_IFA) {
145 char *cp = (char *)(ifam + 1);
147 for (i = 1; i < RTA_IFA; i <<= 1) {
148 if (ifam->ifam_addrs & i)
149 cp += SA_SIZE((struct sockaddr *)cp);
151 if (((struct sockaddr *)cp)->sa_family == AF_INET) {
152 sin = (struct sockaddr_in *)cp;
158 errx(1, "%s: cannot get interface address", ifn);
160 n->ip = sin->sin_addr;
161 strncpy(n->if_name, ifn, IF_NAMESIZE);
167 * XXX - The following functions, macros and definitions come from natd.c:
168 * it would be better to move them outside natd.c, in a file
169 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
174 * Definition of a port range, and macros to deal with values.
175 * FORMAT: HI 16-bits == first port in range, 0 == all ports.
176 * LO 16-bits == number of ports in range
177 * NOTES: - Port values are not stored in network byte order.
180 #define port_range u_long
182 #define GETLOPORT(x) ((x) >> 0x10)
183 #define GETNUMPORTS(x) ((x) & 0x0000ffff)
184 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x)))
186 /* Set y to be the low-port value in port_range variable x. */
187 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
189 /* Set y to be the number of ports in port_range variable x. */
190 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
193 StrToAddr (const char* str, struct in_addr* addr)
197 if (inet_aton (str, addr))
200 hp = gethostbyname (str);
202 errx (1, "unknown host %s", str);
204 memcpy (addr, hp->h_addr, sizeof (struct in_addr));
208 StrToPortRange (const char* str, const char* proto, port_range *portRange)
216 /* First see if this is a service, return corresponding port if so. */
217 sp = getservbyname (str,proto);
219 SETLOPORT(*portRange, ntohs(sp->s_port));
220 SETNUMPORTS(*portRange, 1);
224 /* Not a service, see if it's a single port or port range. */
225 sep = strchr (str, '-');
227 SETLOPORT(*portRange, strtol(str, &end, 10));
230 SETNUMPORTS(*portRange, 1);
234 /* Error in port range field. */
235 errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
238 /* Port range, get the values and sanity check. */
239 sscanf (str, "%hu-%hu", &loPort, &hiPort);
240 SETLOPORT(*portRange, loPort);
241 SETNUMPORTS(*portRange, 0); /* Error by default */
242 if (loPort <= hiPort)
243 SETNUMPORTS(*portRange, hiPort - loPort + 1);
245 if (GETNUMPORTS(*portRange) == 0)
246 errx (EX_DATAERR, "invalid port range %s", str);
252 StrToProto (const char* str)
254 if (!strcmp (str, "tcp"))
257 if (!strcmp (str, "udp"))
260 if (!strcmp (str, "sctp"))
262 errx (EX_DATAERR, "unknown protocol %s. Expected sctp, tcp or udp", str);
266 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
267 port_range *portRange)
271 ptr = strchr (str, ':');
273 errx (EX_DATAERR, "%s is missing port number", str);
278 StrToAddr (str, addr);
279 return StrToPortRange (ptr, proto, portRange);
282 /* End of stuff taken from natd.c. */
284 #define INC_ARGCV() do { \
292 * The next 3 functions add support for the addr, port and proto redirect and
293 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
294 * and SetupProtoRedirect() from natd.c.
296 * Every setup_* function fills at least one redirect entry
297 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool)
300 * The format of data in buf is:
303 * cfg_nat cfg_redir cfg_spool ...... cfg_spool
305 * ------------------------------------- ------------
306 * | | .....X ... | | | | .....
307 * ------------------------------------- ...... ------------
309 * spool_cnt n=0 ...... n=(X-1)
311 * len points to the amount of available space in buf
312 * space counts the memory consumed by every function
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
322 setup_redir_addr(char *spool_buf, unsigned int len,
323 int *_ac, char ***_av)
325 char **av, *sep; /* Token separator. */
326 /* Temporary buffer used to hold server pool ip's. */
327 char tmp_spool_buf[NAT_BUF_LEN];
328 int ac, space, lsnat;
330 struct cfg_spool *tmp;
336 if (len >= SOF_REDIR) {
337 r = (struct cfg_redir *)spool_buf;
338 /* Skip cfg_redir at beginning of buf. */
339 spool_buf = &spool_buf[SOF_REDIR];
344 r->mode = REDIR_ADDR;
345 /* Extract local address. */
347 errx(EX_DATAERR, "redirect_addr: missing local address");
348 sep = strchr(*av, ',');
349 if (sep) { /* LSNAT redirection syntax. */
350 r->laddr.s_addr = INADDR_NONE;
351 /* Preserve av, copy spool servers to tmp_spool_buf. */
352 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
355 StrToAddr(*av, &r->laddr);
358 /* Extract public address. */
360 errx(EX_DATAERR, "redirect_addr: missing public address");
361 StrToAddr(*av, &r->paddr);
364 /* Setup LSNAT server pool. */
366 sep = strtok(tmp_spool_buf, ",");
367 while (sep != NULL) {
368 tmp = (struct cfg_spool *)spool_buf;
373 StrToAddr(sep, &tmp->addr);
376 /* Point to the next possible cfg_spool. */
377 spool_buf = &spool_buf[SOF_SPOOL];
378 sep = strtok(NULL, ",");
383 errx(EX_DATAERR, "redirect_addr: buf is too small\n");
387 setup_redir_port(char *spool_buf, unsigned int len,
388 int *_ac, char ***_av)
390 char **av, *sep, *protoName;
391 char tmp_spool_buf[NAT_BUF_LEN];
392 int ac, space, lsnat;
394 struct cfg_spool *tmp;
395 u_short numLocalPorts;
396 port_range portRange;
404 if (len >= SOF_REDIR) {
405 r = (struct cfg_redir *)spool_buf;
406 /* Skip cfg_redir at beginning of buf. */
407 spool_buf = &spool_buf[SOF_REDIR];
412 r->mode = REDIR_PORT;
417 errx (EX_DATAERR, "redirect_port: missing protocol");
418 r->proto = StrToProto(*av);
423 * Extract local address.
426 errx (EX_DATAERR, "redirect_port: missing local address");
428 sep = strchr(*av, ',');
429 /* LSNAT redirection syntax. */
431 r->laddr.s_addr = INADDR_NONE;
434 /* Preserve av, copy spool servers to tmp_spool_buf. */
435 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
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.
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 not "
447 "specify them as part of the target");
449 StrToAddr(*av, &r->laddr);
451 if (StrToAddrAndPortRange (*av, &r->laddr, protoName,
453 errx(EX_DATAERR, "redirect_port:"
454 "invalid local port range");
456 r->lport = GETLOPORT(portRange);
457 numLocalPorts = GETNUMPORTS(portRange);
463 * Extract public port and optionally address.
466 errx (EX_DATAERR, "redirect_port: missing public port");
468 sep = strchr (*av, ':');
470 if (StrToAddrAndPortRange (*av, &r->paddr, protoName,
472 errx(EX_DATAERR, "redirect_port:"
473 "invalid public port range");
475 r->paddr.s_addr = INADDR_ANY;
476 if (StrToPortRange (*av, protoName, &portRange) != 0)
477 errx(EX_DATAERR, "redirect_port:"
478 "invalid public port range");
481 r->pport = GETLOPORT(portRange);
482 if (r->proto == IPPROTO_SCTP) { /* so the logic below still works */
483 numLocalPorts = GETNUMPORTS(portRange);
486 r->pport_cnt = GETNUMPORTS(portRange);
490 * Extract remote address and optionally port.
493 * NB: isalpha(**av) => we've to check that next parameter is really an
494 * option for this redirect entry, else stop here processing arg[cv].
496 if (ac != 0 && !isalpha(**av)) {
497 sep = strchr (*av, ':');
499 if (StrToAddrAndPortRange (*av, &r->raddr, protoName,
501 errx(EX_DATAERR, "redirect_port:"
502 "invalid remote port range");
504 SETLOPORT(portRange, 0);
505 SETNUMPORTS(portRange, 1);
506 StrToAddr (*av, &r->raddr);
510 SETLOPORT(portRange, 0);
511 SETNUMPORTS(portRange, 1);
512 r->raddr.s_addr = INADDR_ANY;
514 r->rport = GETLOPORT(portRange);
515 r->rport_cnt = GETNUMPORTS(portRange);
518 * Make sure port ranges match up, then add the redirect ports.
520 if (numLocalPorts != r->pport_cnt)
521 errx(EX_DATAERR, "redirect_port:"
522 "port ranges must be equal in size");
524 /* Remote port range is allowed to be '0' which means all ports. */
525 if (r->rport_cnt != numLocalPorts &&
526 (r->rport_cnt != 1 || r->rport != 0))
527 errx(EX_DATAERR, "redirect_port: remote port must"
528 "be 0 or equal to local port range in size");
531 * Setup LSNAT server pool.
534 sep = strtok(tmp_spool_buf, ",");
535 while (sep != NULL) {
536 tmp = (struct cfg_spool *)spool_buf;
542 * The sctp nat does not allow the port numbers to be mapped to new port numbers
543 * Therefore, no ports are to be specified in the targetport field
545 if (r->proto == IPPROTO_SCTP) {
546 if (strchr (sep, ':')) {
547 errx(EX_DATAERR, "redirect_port:"
548 "port numbers do not change in "
549 "sctp, so do not specify them as "
550 "part of the target");
552 StrToAddr(sep, &tmp->addr);
553 tmp->port = r->pport;
556 if (StrToAddrAndPortRange(sep, &tmp->addr,
557 protoName, &portRange) != 0)
558 errx(EX_DATAERR, "redirect_port:"
559 "invalid local port range");
560 if (GETNUMPORTS(portRange) != 1)
561 errx(EX_DATAERR, "redirect_port:"
562 " local port must be single in "
564 tmp->port = GETLOPORT(portRange);
567 /* Point to the next possible cfg_spool. */
568 spool_buf = &spool_buf[SOF_SPOOL];
569 sep = strtok(NULL, ",");
574 errx(EX_DATAERR, "redirect_port: buf is too small\n");
578 setup_redir_proto(char *spool_buf, unsigned int len,
579 int *_ac, char ***_av)
583 struct protoent *protoent;
588 if (len >= SOF_REDIR) {
589 r = (struct cfg_redir *)spool_buf;
590 /* Skip cfg_redir at beginning of buf. */
591 spool_buf = &spool_buf[SOF_REDIR];
596 r->mode = REDIR_PROTO;
601 errx(EX_DATAERR, "redirect_proto: missing protocol");
603 protoent = getprotobyname(*av);
604 if (protoent == NULL)
605 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av);
607 r->proto = protoent->p_proto;
612 * Extract local address.
615 errx(EX_DATAERR, "redirect_proto: missing local address");
617 StrToAddr(*av, &r->laddr);
622 * Extract optional public address.
625 r->paddr.s_addr = INADDR_ANY;
626 r->raddr.s_addr = INADDR_ANY;
628 /* see above in setup_redir_port() */
629 if (!isalpha(**av)) {
630 StrToAddr(*av, &r->paddr);
634 * Extract optional remote address.
636 /* see above in setup_redir_port() */
637 if (ac!=0 && !isalpha(**av)) {
638 StrToAddr(*av, &r->raddr);
645 errx(EX_DATAERR, "redirect_proto: buf is too small\n");
649 print_nat_config(unsigned char *buf)
652 int i, cnt, flag, off;
657 n = (struct cfg_nat *)buf;
660 printf("ipfw nat %u config", n->id);
661 if (strlen(n->if_name) != 0)
662 printf(" if %s", n->if_name);
663 else if (n->ip.s_addr != 0)
664 printf(" ip %s", inet_ntoa(n->ip));
665 while (n->mode != 0) {
666 if (n->mode & PKT_ALIAS_LOG) {
668 n->mode &= ~PKT_ALIAS_LOG;
669 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
671 n->mode &= ~PKT_ALIAS_DENY_INCOMING;
672 } else if (n->mode & PKT_ALIAS_SAME_PORTS) {
673 printf(" same_ports");
674 n->mode &= ~PKT_ALIAS_SAME_PORTS;
675 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
676 printf(" unreg_only");
677 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
678 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
680 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
681 } else if (n->mode & PKT_ALIAS_REVERSE) {
683 n->mode &= ~PKT_ALIAS_REVERSE;
684 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
685 printf(" proxy_only");
686 n->mode &= ~PKT_ALIAS_PROXY_ONLY;
689 /* Print all the redirect's data configuration. */
690 for (cnt = 0; cnt < n->redir_cnt; cnt++) {
691 t = (struct cfg_redir *)&buf[off];
695 printf(" redirect_addr");
696 if (t->spool_cnt == 0)
697 printf(" %s", inet_ntoa(t->laddr));
699 for (i = 0; i < t->spool_cnt; i++) {
700 s = (struct cfg_spool *)&buf[off];
705 printf("%s", inet_ntoa(s->addr));
708 printf(" %s", inet_ntoa(t->paddr));
711 p = getprotobynumber(t->proto);
712 printf(" redirect_port %s ", p->p_name);
714 printf("%s:%u", inet_ntoa(t->laddr), t->lport);
715 if (t->pport_cnt > 1)
716 printf("-%u", t->lport +
719 for (i=0; i < t->spool_cnt; i++) {
720 s = (struct cfg_spool *)&buf[off];
723 printf("%s:%u", inet_ntoa(s->addr),
730 printf("%s:", inet_ntoa(t->paddr));
731 printf("%u", t->pport);
732 if (!t->spool_cnt && t->pport_cnt > 1)
733 printf("-%u", t->pport + t->pport_cnt - 1);
735 if (t->raddr.s_addr) {
736 printf(" %s", inet_ntoa(t->raddr));
738 printf(":%u", t->rport);
739 if (!t->spool_cnt && t->rport_cnt > 1)
740 printf("-%u", t->rport +
746 p = getprotobynumber(t->proto);
747 printf(" redirect_proto %s %s", p->p_name,
748 inet_ntoa(t->laddr));
749 if (t->paddr.s_addr != 0) {
750 printf(" %s", inet_ntoa(t->paddr));
752 printf(" %s", inet_ntoa(t->raddr));
756 errx(EX_DATAERR, "unknown redir mode");
764 ipfw_config_nat(int ac, char **av)
766 struct cfg_nat *n; /* Nat instance configuration. */
767 int i, len, off, tok;
768 char *id, buf[NAT_BUF_LEN]; /* Buffer for serialized data. */
771 /* Offset in buf: save space for n at the beginning. */
773 memset(buf, 0, sizeof(buf));
774 n = (struct cfg_nat *)buf;
778 if (ac && isdigit(**av)) {
784 errx(EX_DATAERR, "missing nat id");
786 errx(EX_DATAERR, "missing option");
789 tok = match_token(nat_params, *av);
794 errx(EX_DATAERR, "missing option");
795 if (!inet_aton(av[0], &(n->ip)))
796 errx(EX_DATAERR, "bad ip address ``%s''",
802 errx(EX_DATAERR, "missing option");
803 set_addr_dynamic(av[0], n);
807 n->mode |= PKT_ALIAS_LOG;
810 n->mode |= PKT_ALIAS_DENY_INCOMING;
813 n->mode |= PKT_ALIAS_SAME_PORTS;
816 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
819 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
822 n->mode |= PKT_ALIAS_REVERSE;
825 n->mode |= PKT_ALIAS_PROXY_ONLY;
828 * All the setup_redir_* functions work directly in the final
829 * buffer, see above for details.
833 case TOK_REDIR_PROTO:
836 i = setup_redir_addr(&buf[off], len, &ac, &av);
839 i = setup_redir_port(&buf[off], len, &ac, &av);
841 case TOK_REDIR_PROTO:
842 i = setup_redir_proto(&buf[off], len, &ac, &av);
850 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
854 i = do_cmd(IP_FW_NAT_CFG, buf, off);
856 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
859 /* After every modification, we show the resultant rule. */
861 const char *_av[] = {"show", "config", id};
862 ipfw_show_nat(_ac, (char **)(void *)_av);
868 ipfw_show_nat(int ac, char **av)
872 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
873 int nat_cnt, redir_cnt, r;
882 lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
888 /* Parse parameters. */
889 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
890 if (!strncmp(av[0], "config", strlen(av[0]))) {
891 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
894 /* Convert command line rule #. */
895 frule = lrule = strtoul(av[0], &endptr, 10);
897 lrule = strtoul(endptr+1, &endptr, 10);
899 err(EX_USAGE, "invalid rule number: %s", av[0]);
904 while (nbytes >= nalloc) {
907 data = safe_realloc(data, nbytes);
908 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
909 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
910 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
915 nat_cnt = *((int *)data);
916 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
917 n = (struct cfg_nat *)&data[i];
918 if (frule <= n->id && lrule >= n->id)
919 print_nat_config(&data[i]);
920 i += sizeof(struct cfg_nat);
921 for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
922 e = (struct cfg_redir *)&data[i];
923 i += sizeof(struct cfg_redir) + e->spool_cnt *
924 sizeof(struct cfg_spool);
928 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
930 if (p == data + nbytes)
932 bcopy(p, &r, sizeof(int));
934 if (!(frule <= r && lrule >= r))
937 printf("nat %u: %s\n", r, p+sizeof(int));