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
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:
302 * cfg_nat cfg_redir cfg_spool ...... cfg_spool
304 * ------------------------------------- ------------
305 * | | .....X ... | | | | .....
306 * ------------------------------------- ...... ------------
308 * spool_cnt n=0 ...... n=(X-1)
310 * len points to the amount of available space in buf
311 * space counts the memory consumed by every function
313 * XXX - Every function get all the argv params so it
314 * has to check, in optional parameters, that the next
315 * args is a valid option for the redir entry and not
316 * another token. Only redir_port and redir_proto are
321 setup_redir_addr(char *spool_buf, unsigned int len,
322 int *_ac, char ***_av)
324 char **av, *sep; /* Token separator. */
325 /* Temporary buffer used to hold server pool ip's. */
326 char tmp_spool_buf[NAT_BUF_LEN];
327 int ac, space, lsnat;
329 struct cfg_spool *tmp;
335 if (len >= SOF_REDIR) {
336 r = (struct cfg_redir *)spool_buf;
337 /* Skip cfg_redir at beginning of buf. */
338 spool_buf = &spool_buf[SOF_REDIR];
343 r->mode = REDIR_ADDR;
344 /* Extract local address. */
346 errx(EX_DATAERR, "redirect_addr: missing local address");
347 sep = strchr(*av, ',');
348 if (sep) { /* LSNAT redirection syntax. */
349 r->laddr.s_addr = INADDR_NONE;
350 /* Preserve av, copy spool servers to tmp_spool_buf. */
351 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
354 StrToAddr(*av, &r->laddr);
357 /* Extract public address. */
359 errx(EX_DATAERR, "redirect_addr: missing public address");
360 StrToAddr(*av, &r->paddr);
363 /* Setup LSNAT server pool. */
365 sep = strtok(tmp_spool_buf, ",");
366 while (sep != NULL) {
367 tmp = (struct cfg_spool *)spool_buf;
372 StrToAddr(sep, &tmp->addr);
375 /* Point to the next possible cfg_spool. */
376 spool_buf = &spool_buf[SOF_SPOOL];
377 sep = strtok(NULL, ",");
382 errx(EX_DATAERR, "redirect_addr: buf is too small\n");
386 setup_redir_port(char *spool_buf, unsigned int len,
387 int *_ac, char ***_av)
389 char **av, *sep, *protoName;
390 char tmp_spool_buf[NAT_BUF_LEN];
391 int ac, space, lsnat;
393 struct cfg_spool *tmp;
394 u_short numLocalPorts;
395 port_range portRange;
403 if (len >= SOF_REDIR) {
404 r = (struct cfg_redir *)spool_buf;
405 /* Skip cfg_redir at beginning of buf. */
406 spool_buf = &spool_buf[SOF_REDIR];
411 r->mode = REDIR_PORT;
416 errx (EX_DATAERR, "redirect_port: missing protocol");
417 r->proto = StrToProto(*av);
422 * Extract local address.
425 errx (EX_DATAERR, "redirect_port: missing local address");
427 sep = strchr(*av, ',');
428 /* LSNAT redirection syntax. */
430 r->laddr.s_addr = INADDR_NONE;
433 /* Preserve av, copy spool servers to tmp_spool_buf. */
434 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
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.
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 not "
446 "specify them as part of the target");
448 StrToAddr(*av, &r->laddr);
450 if (StrToAddrAndPortRange (*av, &r->laddr, protoName,
452 errx(EX_DATAERR, "redirect_port:"
453 "invalid local port range");
455 r->lport = GETLOPORT(portRange);
456 numLocalPorts = GETNUMPORTS(portRange);
462 * Extract public port and optionally address.
465 errx (EX_DATAERR, "redirect_port: missing public port");
467 sep = strchr (*av, ':');
469 if (StrToAddrAndPortRange (*av, &r->paddr, protoName,
471 errx(EX_DATAERR, "redirect_port:"
472 "invalid public port range");
474 r->paddr.s_addr = INADDR_ANY;
475 if (StrToPortRange (*av, protoName, &portRange) != 0)
476 errx(EX_DATAERR, "redirect_port:"
477 "invalid public port range");
480 r->pport = GETLOPORT(portRange);
481 if (r->proto == IPPROTO_SCTP) { /* so the logic below still works */
482 numLocalPorts = GETNUMPORTS(portRange);
485 r->pport_cnt = GETNUMPORTS(portRange);
489 * Extract remote address and optionally port.
492 * NB: isalpha(**av) => we've to check that next parameter is really an
493 * option for this redirect entry, else stop here processing arg[cv].
495 if (ac != 0 && !isalpha(**av)) {
496 sep = strchr (*av, ':');
498 if (StrToAddrAndPortRange (*av, &r->raddr, protoName,
500 errx(EX_DATAERR, "redirect_port:"
501 "invalid remote port range");
503 SETLOPORT(portRange, 0);
504 SETNUMPORTS(portRange, 1);
505 StrToAddr (*av, &r->raddr);
509 SETLOPORT(portRange, 0);
510 SETNUMPORTS(portRange, 1);
511 r->raddr.s_addr = INADDR_ANY;
513 r->rport = GETLOPORT(portRange);
514 r->rport_cnt = GETNUMPORTS(portRange);
517 * Make sure port ranges match up, then add the redirect ports.
519 if (numLocalPorts != r->pport_cnt)
520 errx(EX_DATAERR, "redirect_port:"
521 "port ranges must be equal in size");
523 /* Remote port range is allowed to be '0' which means all ports. */
524 if (r->rport_cnt != numLocalPorts &&
525 (r->rport_cnt != 1 || r->rport != 0))
526 errx(EX_DATAERR, "redirect_port: remote port must"
527 "be 0 or equal to local port range in size");
530 * Setup LSNAT server pool.
533 sep = strtok(tmp_spool_buf, ",");
534 while (sep != NULL) {
535 tmp = (struct cfg_spool *)spool_buf;
541 * The sctp nat does not allow the port numbers to be mapped to new port numbers
542 * Therefore, no ports are to be specified in the target port field
544 if (r->proto == IPPROTO_SCTP) {
545 if (strchr (sep, ':')) {
546 errx(EX_DATAERR, "redirect_port:"
547 "port numbers do not change in "
548 "sctp, so do not specify them as "
549 "part of the target");
551 StrToAddr(sep, &tmp->addr);
552 tmp->port = r->pport;
555 if (StrToAddrAndPortRange(sep, &tmp->addr,
556 protoName, &portRange) != 0)
557 errx(EX_DATAERR, "redirect_port:"
558 "invalid local port range");
559 if (GETNUMPORTS(portRange) != 1)
560 errx(EX_DATAERR, "redirect_port: "
561 "local port must be single in "
563 tmp->port = GETLOPORT(portRange);
566 /* Point to the next possible cfg_spool. */
567 spool_buf = &spool_buf[SOF_SPOOL];
568 sep = strtok(NULL, ",");
573 errx(EX_DATAERR, "redirect_port: buf is too small\n");
577 setup_redir_proto(char *spool_buf, unsigned int len,
578 int *_ac, char ***_av)
582 struct protoent *protoent;
587 if (len >= SOF_REDIR) {
588 r = (struct cfg_redir *)spool_buf;
589 /* Skip cfg_redir at beginning of buf. */
590 spool_buf = &spool_buf[SOF_REDIR];
595 r->mode = REDIR_PROTO;
600 errx(EX_DATAERR, "redirect_proto: missing protocol");
602 protoent = getprotobyname(*av);
603 if (protoent == NULL)
604 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av);
606 r->proto = protoent->p_proto;
611 * Extract local address.
614 errx(EX_DATAERR, "redirect_proto: missing local address");
616 StrToAddr(*av, &r->laddr);
621 * Extract optional public address.
624 r->paddr.s_addr = INADDR_ANY;
625 r->raddr.s_addr = INADDR_ANY;
627 /* see above in setup_redir_port() */
628 if (!isalpha(**av)) {
629 StrToAddr(*av, &r->paddr);
633 * Extract optional remote address.
635 /* see above in setup_redir_port() */
636 if (ac!=0 && !isalpha(**av)) {
637 StrToAddr(*av, &r->raddr);
644 errx(EX_DATAERR, "redirect_proto: buf is too small\n");
648 print_nat_config(unsigned char *buf)
651 int i, cnt, flag, off;
656 n = (struct cfg_nat *)buf;
659 printf("ipfw nat %u config", n->id);
660 if (strlen(n->if_name) != 0)
661 printf(" if %s", n->if_name);
662 else if (n->ip.s_addr != 0)
663 printf(" ip %s", inet_ntoa(n->ip));
664 while (n->mode != 0) {
665 if (n->mode & PKT_ALIAS_LOG) {
667 n->mode &= ~PKT_ALIAS_LOG;
668 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
670 n->mode &= ~PKT_ALIAS_DENY_INCOMING;
671 } else if (n->mode & PKT_ALIAS_SAME_PORTS) {
672 printf(" same_ports");
673 n->mode &= ~PKT_ALIAS_SAME_PORTS;
674 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
675 printf(" unreg_only");
676 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
677 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
679 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
680 } else if (n->mode & PKT_ALIAS_REVERSE) {
682 n->mode &= ~PKT_ALIAS_REVERSE;
683 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
684 printf(" proxy_only");
685 n->mode &= ~PKT_ALIAS_PROXY_ONLY;
688 /* Print all the redirect's data configuration. */
689 for (cnt = 0; cnt < n->redir_cnt; cnt++) {
690 t = (struct cfg_redir *)&buf[off];
694 printf(" redirect_addr");
695 if (t->spool_cnt == 0)
696 printf(" %s", inet_ntoa(t->laddr));
698 for (i = 0; i < t->spool_cnt; i++) {
699 s = (struct cfg_spool *)&buf[off];
704 printf("%s", inet_ntoa(s->addr));
707 printf(" %s", inet_ntoa(t->paddr));
710 p = getprotobynumber(t->proto);
711 printf(" redirect_port %s ", p->p_name);
713 printf("%s:%u", inet_ntoa(t->laddr), t->lport);
714 if (t->pport_cnt > 1)
715 printf("-%u", t->lport +
718 for (i=0; i < t->spool_cnt; i++) {
719 s = (struct cfg_spool *)&buf[off];
722 printf("%s:%u", inet_ntoa(s->addr),
729 printf("%s:", inet_ntoa(t->paddr));
730 printf("%u", t->pport);
731 if (!t->spool_cnt && t->pport_cnt > 1)
732 printf("-%u", t->pport + t->pport_cnt - 1);
734 if (t->raddr.s_addr) {
735 printf(" %s", inet_ntoa(t->raddr));
737 printf(":%u", t->rport);
738 if (!t->spool_cnt && t->rport_cnt > 1)
739 printf("-%u", t->rport +
745 p = getprotobynumber(t->proto);
746 printf(" redirect_proto %s %s", p->p_name,
747 inet_ntoa(t->laddr));
748 if (t->paddr.s_addr != 0) {
749 printf(" %s", inet_ntoa(t->paddr));
751 printf(" %s", inet_ntoa(t->raddr));
755 errx(EX_DATAERR, "unknown redir mode");
763 ipfw_config_nat(int ac, char **av)
765 struct cfg_nat *n; /* Nat instance configuration. */
766 int i, len, off, tok;
767 char *id, buf[NAT_BUF_LEN]; /* Buffer for serialized data. */
770 /* Offset in buf: save space for n at the beginning. */
772 memset(buf, 0, sizeof(buf));
773 n = (struct cfg_nat *)buf;
777 if (ac && isdigit(**av)) {
783 errx(EX_DATAERR, "missing nat id");
785 errx(EX_DATAERR, "missing option");
788 tok = match_token(nat_params, *av);
793 errx(EX_DATAERR, "missing option");
794 if (!inet_aton(av[0], &(n->ip)))
795 errx(EX_DATAERR, "bad ip address ``%s''",
801 errx(EX_DATAERR, "missing option");
802 set_addr_dynamic(av[0], n);
806 n->mode |= PKT_ALIAS_LOG;
809 n->mode |= PKT_ALIAS_DENY_INCOMING;
812 n->mode |= PKT_ALIAS_SAME_PORTS;
815 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
818 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
821 n->mode |= PKT_ALIAS_REVERSE;
824 n->mode |= PKT_ALIAS_PROXY_ONLY;
827 * All the setup_redir_* functions work directly in
828 * the final buffer, see above for details.
832 case TOK_REDIR_PROTO:
835 i = setup_redir_addr(&buf[off], len, &ac, &av);
838 i = setup_redir_port(&buf[off], len, &ac, &av);
840 case TOK_REDIR_PROTO:
841 i = setup_redir_proto(&buf[off], len, &ac, &av);
849 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
853 i = do_cmd(IP_FW_NAT_CFG, buf, off);
855 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
858 /* After every modification, we show the resultant rule. */
860 const char *_av[] = {"show", "config", id};
861 ipfw_show_nat(_ac, (char **)(void *)_av);
867 ipfw_show_nat(int ac, char **av)
871 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
872 int nat_cnt, redir_cnt, r;
881 lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
887 /* Parse parameters. */
888 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
889 if (!strncmp(av[0], "config", strlen(av[0]))) {
890 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
893 /* Convert command line rule #. */
894 frule = lrule = strtoul(av[0], &endptr, 10);
896 lrule = strtoul(endptr+1, &endptr, 10);
898 err(EX_USAGE, "invalid rule number: %s", av[0]);
903 while (nbytes >= nalloc) {
906 data = safe_realloc(data, nbytes);
907 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
908 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
909 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
914 nat_cnt = *((int *)data);
915 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
916 n = (struct cfg_nat *)&data[i];
917 if (frule <= n->id && lrule >= n->id)
918 print_nat_config(&data[i]);
919 i += sizeof(struct cfg_nat);
920 for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
921 e = (struct cfg_redir *)&data[i];
922 i += sizeof(struct cfg_redir) + e->spool_cnt *
923 sizeof(struct cfg_spool);
927 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
929 if (p == data + nbytes)
931 bcopy(p, &r, sizeof(int));
933 if (!(frule <= r && lrule >= r))
936 printf("nat %u: %s\n", r, p+sizeof(int));