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 { "skip_global", TOK_SKIP_GLOBAL },
57 { "reset", TOK_RESET_ADDR },
58 { "reverse", TOK_ALIAS_REV },
59 { "proxy_only", TOK_PROXY_ONLY },
60 { "redirect_addr", TOK_REDIR_ADDR },
61 { "redirect_port", TOK_REDIR_PORT },
62 { "redirect_proto", TOK_REDIR_PROTO },
63 { NULL, 0 } /* terminator */
68 * Search for interface with name "ifn", and fill n accordingly:
70 * n->ip ip address of interface "ifn"
71 * n->if_name copy of interface name "ifn"
74 set_addr_dynamic(const char *ifn, struct cfg_nat *n)
78 char *buf, *lim, *next;
79 struct if_msghdr *ifm;
80 struct ifa_msghdr *ifam;
81 struct sockaddr_dl *sdl;
82 struct sockaddr_in *sin;
89 mib[4] = NET_RT_IFLIST;
94 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
95 err(1, "iflist-sysctl-estimate");
96 buf = safe_calloc(1, needed);
97 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
98 err(1, "iflist-sysctl-get");
101 * Loop through interfaces until one with
102 * given name is found. This is done to
103 * find correct interface index for routing
104 * message processing.
109 ifm = (struct if_msghdr *)next;
110 next += ifm->ifm_msglen;
111 if (ifm->ifm_version != RTM_VERSION) {
113 warnx("routing message version %d "
114 "not understood", ifm->ifm_version);
117 if (ifm->ifm_type == RTM_IFINFO) {
118 sdl = (struct sockaddr_dl *)(ifm + 1);
119 if (strlen(ifn) == sdl->sdl_nlen &&
120 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
121 ifIndex = ifm->ifm_index;
122 ifMTU = ifm->ifm_data.ifi_mtu;
128 errx(1, "unknown interface name %s", ifn);
130 * Get interface address.
134 ifam = (struct ifa_msghdr *)next;
135 next += ifam->ifam_msglen;
136 if (ifam->ifam_version != RTM_VERSION) {
138 warnx("routing message version %d "
139 "not understood", ifam->ifam_version);
142 if (ifam->ifam_type != RTM_NEWADDR)
144 if (ifam->ifam_addrs & RTA_IFA) {
146 char *cp = (char *)(ifam + 1);
148 for (i = 1; i < RTA_IFA; i <<= 1) {
149 if (ifam->ifam_addrs & i)
150 cp += SA_SIZE((struct sockaddr *)cp);
152 if (((struct sockaddr *)cp)->sa_family == AF_INET) {
153 sin = (struct sockaddr_in *)cp;
159 n->ip.s_addr = htonl(INADDR_ANY);
161 n->ip = sin->sin_addr;
162 strncpy(n->if_name, ifn, IF_NAMESIZE);
168 * XXX - The following functions, macros and definitions come from natd.c:
169 * it would be better to move them outside natd.c, in a file
170 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
175 * Definition of a port range, and macros to deal with values.
176 * FORMAT: HI 16-bits == first port in range, 0 == all ports.
177 * LO 16-bits == number of ports in range
178 * NOTES: - Port values are not stored in network byte order.
181 #define port_range u_long
183 #define GETLOPORT(x) ((x) >> 0x10)
184 #define GETNUMPORTS(x) ((x) & 0x0000ffff)
185 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x)))
187 /* Set y to be the low-port value in port_range variable x. */
188 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
190 /* Set y to be the number of ports in port_range variable x. */
191 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
194 StrToAddr (const char* str, struct in_addr* addr)
198 if (inet_aton (str, addr))
201 hp = gethostbyname (str);
203 errx (1, "unknown host %s", str);
205 memcpy (addr, hp->h_addr, sizeof (struct in_addr));
209 StrToPortRange (const char* str, const char* proto, port_range *portRange)
217 /* First see if this is a service, return corresponding port if so. */
218 sp = getservbyname (str,proto);
220 SETLOPORT(*portRange, ntohs(sp->s_port));
221 SETNUMPORTS(*portRange, 1);
225 /* Not a service, see if it's a single port or port range. */
226 sep = strchr (str, '-');
228 SETLOPORT(*portRange, strtol(str, &end, 10));
231 SETNUMPORTS(*portRange, 1);
235 /* Error in port range field. */
236 errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
239 /* Port range, get the values and sanity check. */
240 sscanf (str, "%hu-%hu", &loPort, &hiPort);
241 SETLOPORT(*portRange, loPort);
242 SETNUMPORTS(*portRange, 0); /* Error by default */
243 if (loPort <= hiPort)
244 SETNUMPORTS(*portRange, hiPort - loPort + 1);
246 if (GETNUMPORTS(*portRange) == 0)
247 errx (EX_DATAERR, "invalid port range %s", str);
253 StrToProto (const char* str)
255 if (!strcmp (str, "tcp"))
258 if (!strcmp (str, "udp"))
261 if (!strcmp (str, "sctp"))
263 errx (EX_DATAERR, "unknown protocol %s. Expected sctp, tcp or udp", str);
267 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
268 port_range *portRange)
272 ptr = strchr (str, ':');
274 errx (EX_DATAERR, "%s is missing port number", str);
279 StrToAddr (str, addr);
280 return StrToPortRange (ptr, proto, portRange);
283 /* End of stuff taken from natd.c. */
286 * The next 3 functions add support for the addr, port and proto redirect and
287 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
288 * and SetupProtoRedirect() from natd.c.
290 * Every setup_* function fills at least one redirect entry
291 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool)
294 * The format of data in buf is:
296 * cfg_nat cfg_redir cfg_spool ...... cfg_spool
298 * ------------------------------------- ------------
299 * | | .....X ... | | | | .....
300 * ------------------------------------- ...... ------------
302 * spool_cnt n=0 ...... n=(X-1)
304 * len points to the amount of available space in buf
305 * space counts the memory consumed by every function
307 * XXX - Every function get all the argv params so it
308 * has to check, in optional parameters, that the next
309 * args is a valid option for the redir entry and not
310 * another token. Only redir_port and redir_proto are
315 estimate_redir_addr(int *ac, char ***av)
317 size_t space = sizeof(struct cfg_redir);
321 (void)ac; /* UNUSED */
322 while ((sep = strchr(sep, ',')) != NULL) {
330 space += c * sizeof(struct cfg_spool);
336 setup_redir_addr(char *buf, int *ac, char ***av)
342 r = (struct cfg_redir *)buf;
343 r->mode = REDIR_ADDR;
344 /* Skip cfg_redir at beginning of buf. */
345 buf = &buf[sizeof(struct cfg_redir)];
346 space = sizeof(struct cfg_redir);
348 /* Extract local address. */
349 if (strchr(**av, ',') != NULL) {
350 struct cfg_spool *spool;
352 /* Setup LSNAT server pool. */
353 r->laddr.s_addr = INADDR_NONE;
354 sep = strtok(**av, ",");
355 while (sep != NULL) {
356 spool = (struct cfg_spool *)buf;
357 space += sizeof(struct cfg_spool);
358 StrToAddr(sep, &spool->addr);
361 /* Point to the next possible cfg_spool. */
362 buf = &buf[sizeof(struct cfg_spool)];
363 sep = strtok(NULL, ",");
366 StrToAddr(**av, &r->laddr);
369 /* Extract public address. */
370 StrToAddr(**av, &r->paddr);
377 estimate_redir_port(int *ac, char ***av)
379 size_t space = sizeof(struct cfg_redir);
383 (void)ac; /* UNUSED */
384 while ((sep = strchr(sep, ',')) != NULL) {
392 space += c * sizeof(struct cfg_spool);
398 setup_redir_port(char *buf, int *ac, char ***av)
401 char *sep, *protoName, *lsnat = NULL;
403 u_short numLocalPorts;
404 port_range portRange;
408 r = (struct cfg_redir *)buf;
409 r->mode = REDIR_PORT;
410 /* Skip cfg_redir at beginning of buf. */
411 buf = &buf[sizeof(struct cfg_redir)];
412 space = sizeof(struct cfg_redir);
417 r->proto = StrToProto(**av);
422 * Extract local address.
424 if (strchr(**av, ',') != NULL) {
425 r->laddr.s_addr = INADDR_NONE;
431 * The sctp nat does not allow the port numbers to be mapped to
432 * new port numbers. Therefore, no ports are to be specified
433 * in the target port field.
435 if (r->proto == IPPROTO_SCTP) {
436 if (strchr(**av, ':'))
437 errx(EX_DATAERR, "redirect_port:"
438 "port numbers do not change in sctp, so do "
439 "not specify them as part of the target");
441 StrToAddr(**av, &r->laddr);
443 if (StrToAddrAndPortRange(**av, &r->laddr, protoName,
445 errx(EX_DATAERR, "redirect_port: "
446 "invalid local port range");
448 r->lport = GETLOPORT(portRange);
449 numLocalPorts = GETNUMPORTS(portRange);
455 * Extract public port and optionally address.
457 if (strchr(**av, ':') != NULL) {
458 if (StrToAddrAndPortRange(**av, &r->paddr, protoName,
460 errx(EX_DATAERR, "redirect_port: "
461 "invalid public port range");
463 r->paddr.s_addr = INADDR_ANY;
464 if (StrToPortRange(**av, protoName, &portRange) != 0)
465 errx(EX_DATAERR, "redirect_port: "
466 "invalid public port range");
469 r->pport = GETLOPORT(portRange);
470 if (r->proto == IPPROTO_SCTP) { /* so the logic below still works */
471 numLocalPorts = GETNUMPORTS(portRange);
474 r->pport_cnt = GETNUMPORTS(portRange);
478 * Extract remote address and optionally port.
481 * NB: isdigit(**av) => we've to check that next parameter is really an
482 * option for this redirect entry, else stop here processing arg[cv].
484 if (*ac != 0 && isdigit(***av)) {
485 if (strchr(**av, ':') != NULL) {
486 if (StrToAddrAndPortRange(**av, &r->raddr, protoName,
488 errx(EX_DATAERR, "redirect_port: "
489 "invalid remote port range");
491 SETLOPORT(portRange, 0);
492 SETNUMPORTS(portRange, 1);
493 StrToAddr(**av, &r->raddr);
497 SETLOPORT(portRange, 0);
498 SETNUMPORTS(portRange, 1);
499 r->raddr.s_addr = INADDR_ANY;
501 r->rport = GETLOPORT(portRange);
502 r->rport_cnt = GETNUMPORTS(portRange);
505 * Make sure port ranges match up, then add the redirect ports.
507 if (numLocalPorts != r->pport_cnt)
508 errx(EX_DATAERR, "redirect_port: "
509 "port ranges must be equal in size");
511 /* Remote port range is allowed to be '0' which means all ports. */
512 if (r->rport_cnt != numLocalPorts &&
513 (r->rport_cnt != 1 || r->rport != 0))
514 errx(EX_DATAERR, "redirect_port: remote port must"
515 "be 0 or equal to local port range in size");
517 /* Setup LSNAT server pool. */
519 struct cfg_spool *spool;
521 sep = strtok(lsnat, ",");
522 while (sep != NULL) {
523 spool = (struct cfg_spool *)buf;
524 space += sizeof(struct cfg_spool);
526 * The sctp nat does not allow the port numbers to
527 * be mapped to new port numbers. Therefore, no ports
528 * are to be specified in the target port field.
530 if (r->proto == IPPROTO_SCTP) {
531 if (strchr (sep, ':')) {
532 errx(EX_DATAERR, "redirect_port:"
533 "port numbers do not change in "
534 "sctp, so do not specify them as "
535 "part of the target");
537 StrToAddr(sep, &spool->addr);
538 spool->port = r->pport;
541 if (StrToAddrAndPortRange(sep, &spool->addr,
542 protoName, &portRange) != 0)
543 errx(EX_DATAERR, "redirect_port:"
544 "invalid local port range");
545 if (GETNUMPORTS(portRange) != 1)
546 errx(EX_DATAERR, "redirect_port: "
547 "local port must be single in "
549 spool->port = GETLOPORT(portRange);
552 /* Point to the next possible cfg_spool. */
553 buf = &buf[sizeof(struct cfg_spool)];
554 sep = strtok(NULL, ",");
562 setup_redir_proto(char *buf, int *ac, char ***av)
565 struct protoent *protoent;
568 r = (struct cfg_redir *)buf;
569 r->mode = REDIR_PROTO;
570 /* Skip cfg_redir at beginning of buf. */
571 buf = &buf[sizeof(struct cfg_redir)];
572 space = sizeof(struct cfg_redir);
577 protoent = getprotobyname(**av);
578 if (protoent == NULL)
579 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", **av);
581 r->proto = protoent->p_proto;
586 * Extract local address.
588 StrToAddr(**av, &r->laddr);
593 * Extract optional public address.
596 r->paddr.s_addr = INADDR_ANY;
597 r->raddr.s_addr = INADDR_ANY;
599 /* see above in setup_redir_port() */
600 if (isdigit(***av)) {
601 StrToAddr(**av, &r->paddr);
605 * Extract optional remote address.
607 /* see above in setup_redir_port() */
608 if (*ac != 0 && isdigit(***av)) {
609 StrToAddr(**av, &r->raddr);
619 print_nat_config(unsigned char *buf)
622 int i, cnt, flag, off;
627 n = (struct cfg_nat *)buf;
630 printf("ipfw nat %u config", n->id);
631 if (strlen(n->if_name) != 0)
632 printf(" if %s", n->if_name);
633 else if (n->ip.s_addr != 0)
634 printf(" ip %s", inet_ntoa(n->ip));
635 while (n->mode != 0) {
636 if (n->mode & PKT_ALIAS_LOG) {
638 n->mode &= ~PKT_ALIAS_LOG;
639 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
641 n->mode &= ~PKT_ALIAS_DENY_INCOMING;
642 } else if (n->mode & PKT_ALIAS_SAME_PORTS) {
643 printf(" same_ports");
644 n->mode &= ~PKT_ALIAS_SAME_PORTS;
645 } else if (n->mode & PKT_ALIAS_SKIP_GLOBAL) {
646 printf(" skip_global");
647 n->mode &= ~PKT_ALIAS_SKIP_GLOBAL;
648 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
649 printf(" unreg_only");
650 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
651 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
653 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
654 } else if (n->mode & PKT_ALIAS_REVERSE) {
656 n->mode &= ~PKT_ALIAS_REVERSE;
657 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
658 printf(" proxy_only");
659 n->mode &= ~PKT_ALIAS_PROXY_ONLY;
662 /* Print all the redirect's data configuration. */
663 for (cnt = 0; cnt < n->redir_cnt; cnt++) {
664 t = (struct cfg_redir *)&buf[off];
668 printf(" redirect_addr");
669 if (t->spool_cnt == 0)
670 printf(" %s", inet_ntoa(t->laddr));
672 for (i = 0; i < t->spool_cnt; i++) {
673 s = (struct cfg_spool *)&buf[off];
678 printf("%s", inet_ntoa(s->addr));
681 printf(" %s", inet_ntoa(t->paddr));
684 p = getprotobynumber(t->proto);
685 printf(" redirect_port %s ", p->p_name);
687 printf("%s:%u", inet_ntoa(t->laddr), t->lport);
688 if (t->pport_cnt > 1)
689 printf("-%u", t->lport +
692 for (i=0; i < t->spool_cnt; i++) {
693 s = (struct cfg_spool *)&buf[off];
696 printf("%s:%u", inet_ntoa(s->addr),
703 printf("%s:", inet_ntoa(t->paddr));
704 printf("%u", t->pport);
705 if (!t->spool_cnt && t->pport_cnt > 1)
706 printf("-%u", t->pport + t->pport_cnt - 1);
708 if (t->raddr.s_addr) {
709 printf(" %s", inet_ntoa(t->raddr));
711 printf(":%u", t->rport);
712 if (!t->spool_cnt && t->rport_cnt > 1)
713 printf("-%u", t->rport +
719 p = getprotobynumber(t->proto);
720 printf(" redirect_proto %s %s", p->p_name,
721 inet_ntoa(t->laddr));
722 if (t->paddr.s_addr != 0) {
723 printf(" %s", inet_ntoa(t->paddr));
725 printf(" %s", inet_ntoa(t->raddr));
729 errx(EX_DATAERR, "unknown redir mode");
737 ipfw_config_nat(int ac, char **av)
739 struct cfg_nat *n; /* Nat instance configuration. */
740 int i, off, tok, ac1;
741 char *id, *buf, **av1, *end;
748 errx(EX_DATAERR, "missing nat id");
750 i = (int)strtol(id, &end, 0);
751 if (i <= 0 || *end != '\0')
752 errx(EX_DATAERR, "illegal nat id: %s", id);
756 errx(EX_DATAERR, "missing option");
758 len = sizeof(struct cfg_nat);
762 tok = match_token(nat_params, *av1);
774 case TOK_SKIP_GLOBAL:
782 errx(EX_DATAERR, "redirect_addr: "
783 "not enough arguments");
784 len += estimate_redir_addr(&ac1, &av1);
790 errx(EX_DATAERR, "redirect_port: "
791 "not enough arguments");
794 len += estimate_redir_port(&ac1, &av1);
797 /* Skip optional remoteIP/port */
798 if (ac1 != 0 && isdigit(**av1)) {
803 case TOK_REDIR_PROTO:
805 errx(EX_DATAERR, "redirect_proto: "
806 "not enough arguments");
807 len += sizeof(struct cfg_redir);
810 /* Skip optional remoteIP/port */
811 if (ac1 != 0 && isdigit(**av1)) {
815 if (ac1 != 0 && isdigit(**av1)) {
821 errx(EX_DATAERR, "unrecognised option ``%s''", av1[-1]);
825 if ((buf = malloc(len)) == NULL)
826 errx(EX_OSERR, "malloc failed");
828 /* Offset in buf: save space for n at the beginning. */
831 n = (struct cfg_nat *)buf;
835 tok = match_token(nat_params, *av);
841 errx(EX_DATAERR, "missing option");
842 if (!inet_aton(av[0], &(n->ip)))
843 errx(EX_DATAERR, "bad ip address ``%s''",
850 errx(EX_DATAERR, "missing option");
851 set_addr_dynamic(av[0], n);
856 n->mode |= PKT_ALIAS_LOG;
859 n->mode |= PKT_ALIAS_DENY_INCOMING;
862 n->mode |= PKT_ALIAS_SAME_PORTS;
865 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
867 case TOK_SKIP_GLOBAL:
868 n->mode |= PKT_ALIAS_SKIP_GLOBAL;
871 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
874 n->mode |= PKT_ALIAS_REVERSE;
877 n->mode |= PKT_ALIAS_PROXY_ONLY;
880 * All the setup_redir_* functions work directly in
881 * the final buffer, see above for details.
885 case TOK_REDIR_PROTO:
888 i = setup_redir_addr(&buf[off], &ac, &av);
891 i = setup_redir_port(&buf[off], &ac, &av);
893 case TOK_REDIR_PROTO:
894 i = setup_redir_proto(&buf[off], &ac, &av);
903 i = do_cmd(IP_FW_NAT_CFG, buf, off);
905 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
908 /* After every modification, we show the resultant rule. */
910 const char *_av[] = {"show", "config", id};
911 ipfw_show_nat(_ac, (char **)(void *)_av);
917 ipfw_show_nat(int ac, char **av)
921 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
922 int nat_cnt, redir_cnt, r;
931 lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
938 /* Parse parameters. */
939 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
940 if (!strncmp(av[0], "config", strlen(av[0]))) {
941 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
944 /* Convert command line rule #. */
945 frule = lrule = strtoul(av[0], &endptr, 10);
947 lrule = strtoul(endptr+1, &endptr, 10);
949 err(EX_USAGE, "invalid rule number: %s", av[0]);
954 while (nbytes >= nalloc) {
957 data = safe_realloc(data, nbytes);
958 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
959 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
960 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
965 nat_cnt = *((int *)data);
966 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
967 n = (struct cfg_nat *)&data[i];
968 if (frule <= n->id && lrule >= n->id)
969 print_nat_config(&data[i]);
970 i += sizeof(struct cfg_nat);
971 for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
972 e = (struct cfg_redir *)&data[i];
973 i += sizeof(struct cfg_redir) + e->spool_cnt *
974 sizeof(struct cfg_spool);
978 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
980 if (p == data + nbytes)
982 bcopy(p, &r, sizeof(int));
984 if (!(frule <= r && lrule >= r))
987 printf("nat %u: %s\n", r, p+sizeof(int));