2 * firewall3 - 3rd OpenWrt UCI firewall implementation
4 * Copyright (C) 2013 Jo-Philipp Wich <jo@mein.io>
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 static int lock_fd = -1;
28 static pid_t pipe_pid = -1;
29 static FILE *pipe_fd = NULL;
31 bool fw3_pr_debug = false;
35 warn_elem_section_name(struct uci_section *s, bool find_name)
39 struct uci_element *tmp;
43 uci_foreach_element(&s->package->sections, tmp)
45 if (strcmp(uci_to_section(tmp)->type, s->type))
54 fprintf(stderr, "@%s[%d]", s->type, i);
58 uci_foreach_element(&s->options, tmp)
60 o = uci_to_option(tmp);
62 if (!strcmp(tmp->name, "name") && (o->type == UCI_TYPE_STRING))
64 fprintf(stderr, " (%s)", o->v.string);
72 fprintf(stderr, "'%s'", s->e.name);
80 warn_elem(struct uci_element *e, const char *format, ...)
82 if (e->type == UCI_TYPE_SECTION)
84 fprintf(stderr, "Warning: Section ");
85 warn_elem_section_name(uci_to_section(e), true);
87 else if (e->type == UCI_TYPE_OPTION)
89 fprintf(stderr, "Warning: Option ");
90 warn_elem_section_name(uci_to_option(e)->section, false);
91 fprintf(stderr, ".%s ", e->name);
95 va_start(argptr, format);
96 vfprintf(stderr, format, argptr);
99 fprintf(stderr, "\n");
103 warn(const char* format, ...)
105 fprintf(stderr, "Warning: ");
107 va_start(argptr, format);
108 vfprintf(stderr, format, argptr);
110 fprintf(stderr, "\n");
114 error(const char* format, ...)
116 fprintf(stderr, "Error: ");
118 va_start(argptr, format);
119 vfprintf(stderr, format, argptr);
121 fprintf(stderr, "\n");
127 info(const char* format, ...)
130 va_start(argptr, format);
131 vfprintf(stderr, format, argptr);
133 fprintf(stderr, "\n");
137 fw3_alloc(size_t size)
141 mem = calloc(1, size);
144 error("Out of memory while allocating %d bytes", size);
150 fw3_strdup(const char *s)
157 error("Out of memory while duplicating string '%s'", s);
163 fw3_find_command(const char *cmd)
166 int plen = 0, clen = strlen(cmd) + 1;
168 static char path[PATH_MAX];
170 if (!stat(cmd, &s) && S_ISREG(s.st_mode))
173 search = getenv("PATH");
176 search = "/bin:/usr/bin:/sbin:/usr/sbin";
182 if (*p != ':' && *p != '\0')
187 if ((plen + clen) >= sizeof(path))
190 strncpy(path, search, plen);
191 sprintf(path + plen, "/%s", cmd);
193 if (!stat(path, &s) && S_ISREG(s.st_mode))
204 fw3_stdout_pipe(void)
211 __fw3_command_pipe(bool silent, const char *command, ...)
217 char *arg, **args, **tmp;
219 command = fw3_find_command(command);
228 args = calloc(argn, sizeof(arg));
233 args[0] = (char *)command;
236 va_start(argp, command);
238 while ((arg = va_arg(argp, char *)) != NULL)
240 tmp = realloc(args, ++argn * sizeof(arg));
252 switch ((pid = fork()))
268 execv(command, args);
271 signal(SIGPIPE, SIG_IGN);
274 fcntl(pfds[1], F_SETFD, fcntl(pfds[1], F_GETFD) | FD_CLOEXEC);
277 pipe_fd = fdopen(pfds[1], "w");
282 fw3_pr(const char *fmt, ...)
286 if (fw3_pr_debug && pipe_fd != stdout)
289 vfprintf(stderr, fmt, args);
294 vfprintf(pipe_fd, fmt, args);
299 fw3_command_close(void)
301 if (pipe_fd && pipe_fd != stdout)
305 waitpid(pipe_pid, NULL, 0);
307 signal(SIGPIPE, SIG_DFL);
314 fw3_has_table(bool ipv6, const char *table)
321 const char *path = ipv6
322 ? "/proc/net/ip6_tables_names" : "/proc/net/ip_tables_names";
324 if (!(f = fopen(path, "r")))
327 while (fgets(line, sizeof(line), f))
329 if (!strncmp(line, table, strlen(table)))
345 lock_fd = open(FW3_LOCKFILE, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
349 warn("Cannot create lock file %s: %s", FW3_LOCKFILE, strerror(errno));
353 if (flock(lock_fd, LOCK_EX))
355 warn("Cannot acquire exclusive lock: %s", strerror(errno));
368 if (flock(lock_fd, LOCK_UN))
369 warn("Cannot release exclusive lock: %s", strerror(errno));
372 unlink(FW3_LOCKFILE);
379 write_defaults_uci(struct uci_context *ctx, struct fw3_defaults *d,
380 struct uci_package *dest)
382 char buf[sizeof("0xffffffff\0")];
383 struct uci_ptr ptr = { .p = dest };
385 uci_add_section(ctx, dest, "defaults", &ptr.s);
388 ptr.option = "input";
389 ptr.value = fw3_flag_names[d->policy_input];
393 ptr.option = "output";
394 ptr.value = fw3_flag_names[d->policy_output];
398 ptr.option = "forward";
399 ptr.value = fw3_flag_names[d->policy_forward];
402 sprintf(buf, "0x%x", d->flags[0]);
404 ptr.option = "__flags_v4";
408 sprintf(buf, "0x%x", d->flags[1]);
410 ptr.option = "__flags_v6";
416 write_zone_uci(struct uci_context *ctx, struct fw3_zone *z,
417 struct uci_package *dest, struct ifaddrs *ifaddr)
419 struct fw3_device *dev;
420 struct fw3_address *sub;
422 enum fw3_family fam = FW3_FAMILY_ANY;
424 char *p, buf[INET6_ADDRSTRLEN];
426 struct uci_ptr ptr = { .p = dest };
431 if (fw3_no_table(z->flags[0]) && !fw3_no_table(z->flags[1]))
433 else if (!fw3_no_table(z->flags[0]) && fw3_no_table(z->flags[1]))
435 else if (fw3_no_table(z->flags[0]) && fw3_no_table(z->flags[1]))
438 uci_add_section(ctx, dest, "zone", &ptr.s);
446 ptr.option = "input";
447 ptr.value = fw3_flag_names[z->policy_input];
451 ptr.option = "output";
452 ptr.value = fw3_flag_names[z->policy_output];
456 ptr.option = "forward";
457 ptr.value = fw3_flag_names[z->policy_forward];
462 ptr.value = z->masq ? "1" : "0";
466 ptr.option = "mtu_fix";
467 ptr.value = z->mtu_fix ? "1" : "0";
471 ptr.option = "custom_chains";
472 ptr.value = z->custom_chains ? "1" : "0";
475 if (fam != FW3_FAMILY_ANY)
478 ptr.option = "family";
479 ptr.value = fw3_flag_names[fam];
484 ptr.option = "device";
486 fw3_foreach(dev, &z->devices)
494 p += sprintf(p, "!");
497 p += sprintf(p, "%s@%s", dev->name, dev->network);
499 p += sprintf(p, "%s", dev->name);
502 uci_add_list(ctx, &ptr);
506 ptr.option = "subnet";
508 fw3_foreach(sub, &z->subnets)
513 ptr.value = fw3_address_to_string(sub, true, false);
514 uci_add_list(ctx, &ptr);
518 ptr.option = "__addrs";
520 fw3_foreach(dev, &z->devices)
525 for (ifa = ifaddr; ifa; ifa = ifa->ifa_next)
527 if (!ifa->ifa_addr || strcmp(dev->name, ifa->ifa_name))
530 if (ifa->ifa_addr->sa_family == AF_INET)
532 &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
534 else if (ifa->ifa_addr->sa_family == AF_INET6)
536 &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr,
542 uci_add_list(ctx, &ptr);
546 sprintf(buf, "0x%x", z->flags[0]);
548 ptr.option = "__flags_v4";
552 sprintf(buf, "0x%x", z->flags[1]);
554 ptr.option = "__flags_v6";
560 write_ipset_uci(struct uci_context *ctx, struct fw3_ipset *s,
561 struct uci_package *dest)
563 struct fw3_ipset_datatype *type;
565 char buf[sizeof("65535-65535\0")];
567 struct uci_ptr ptr = { .p = dest };
569 if (!s->enabled || s->external)
572 uci_add_section(ctx, dest, "ipset", &ptr.s);
580 ptr.option = "storage";
581 ptr.value = fw3_ipset_method_names[s->method];
584 list_for_each_entry(type, &s->datatypes, list)
586 sprintf(buf, "%s_%s", type->dir, fw3_ipset_type_names[type->type]);
588 ptr.option = "match";
590 uci_add_list(ctx, &ptr);
596 ptr.option = "iprange";
597 ptr.value = fw3_address_to_string(&s->iprange, false, false);
601 if (s->portrange.set)
603 sprintf(buf, "%u-%u", s->portrange.port_min, s->portrange.port_max);
605 ptr.option = "portrange";
612 fw3_write_statefile(void *state)
615 struct fw3_state *s = state;
618 struct ifaddrs *ifaddr;
620 struct uci_package *p;
622 if (fw3_no_family(s->defaults.flags[0]) &&
623 fw3_no_family(s->defaults.flags[1]))
625 unlink(FW3_STATEFILE);
629 sf = fopen(FW3_STATEFILE, "w+");
633 warn("Cannot create state %s: %s", FW3_STATEFILE, strerror(errno));
637 if (getifaddrs(&ifaddr))
639 warn("Cannot get interface addresses: %s", strerror(errno));
643 if ((p = uci_lookup_package(s->uci, "fw3_state")) != NULL)
644 uci_unload(s->uci, p);
646 uci_import(s->uci, sf, "fw3_state", NULL, true);
648 if ((p = uci_lookup_package(s->uci, "fw3_state")) != NULL)
650 write_defaults_uci(s->uci, &s->defaults, p);
652 list_for_each_entry(z, &s->zones, list)
653 write_zone_uci(s->uci, z, p, ifaddr);
655 list_for_each_entry(i, &s->ipsets, list)
656 write_ipset_uci(s->uci, i, p);
658 uci_export(s->uci, sf, p, true);
659 uci_unload(s->uci, p);
672 fw3_free_object(void *obj, const void *opts)
674 const struct fw3_option *ol;
675 struct list_head *list, *cur, *tmp;
677 for (ol = opts; ol->name; ol++)
682 list = (struct list_head *)((char *)obj + ol->offset);
683 list_for_each_safe(cur, tmp, list)
694 fw3_free_list(struct list_head *head)
696 struct list_head *entry, *tmp;
701 list_for_each_safe(entry, tmp, head)
711 fw3_hotplug(bool add, void *zone, void *device)
713 struct fw3_zone *z = zone;
714 struct fw3_device *d = device;
722 warn("Unable to fork(): %s\n", strerror(errno));
738 setenv("ACTION", add ? "add" : "remove", 1);
739 setenv("ZONE", z->name, 1);
740 setenv("INTERFACE", d->network, 1);
741 setenv("DEVICE", d->name, 1);
743 execl(FW3_HOTPLUG, FW3_HOTPLUG, "firewall", NULL);
750 fw3_netmask2bitlen(int family, void *mask)
756 if (family == FW3_FAMILY_V6)
757 for (bits = 0, v6 = mask;
758 bits < 128 && (v6->s6_addr[bits / 8] << (bits % 8)) & 128;
761 for (bits = 0, v4 = mask;
762 bits < 32 && (ntohl(v4->s_addr) << bits) & 0x80000000;
769 fw3_bitlen2netmask(int family, int bits, void *mask)
776 if (family == FW3_FAMILY_V6)
778 if (bits < -128 || bits > 128)
784 for (i = 0; i < sizeof(v6->s6_addr); i++)
786 b = (rem > 8) ? 8 : rem;
787 v6->s6_addr[i] = (uint8_t)(0xFF << (8 - b));
792 for (i = 0; i < sizeof(v6->s6_addr); i++)
793 v6->s6_addr[i] = ~v6->s6_addr[i];
797 if (bits < -32 || bits > 32)
801 v4->s_addr = bits ? htonl(~((1 << (32 - abs(bits))) - 1)) : 0;
804 v4->s_addr = ~v4->s_addr;
811 fw3_flush_conntrack(void *state)
814 struct fw3_state *s = state;
815 struct fw3_address *addr;
816 struct fw3_device *dev;
817 struct fw3_zone *zone;
818 struct ifaddrs *ifaddr, *ifa;
819 struct sockaddr_in *sin;
820 struct sockaddr_in6 *sin6;
821 char buf[INET6_ADDRSTRLEN];
826 if ((ct = fopen("/proc/net/nf_conntrack", "w")) != NULL)
828 info(" * Flushing conntrack table ...");
830 fwrite("f\n", 1, 2, ct);
837 if (getifaddrs(&ifaddr))
839 warn("Cannot get interface addresses: %s", strerror(errno));
843 if ((ct = fopen("/proc/net/nf_conntrack", "w")) != NULL)
845 list_for_each_entry(zone, &s->zones, list)
846 list_for_each_entry(addr, &zone->old_addrs, list)
850 list_for_each_entry(dev, &zone->devices, list)
852 for (ifa = ifaddr; ifa && !found; ifa = ifa->ifa_next)
854 if (!ifa->ifa_addr || strcmp(dev->name, ifa->ifa_name))
857 sin = (struct sockaddr_in *)ifa->ifa_addr;
858 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
860 if (addr->family == FW3_FAMILY_V4 &&
861 sin->sin_family == AF_INET)
863 found = !memcmp(&addr->address.v4, &sin->sin_addr,
864 sizeof(sin->sin_addr));
866 else if (addr->family == FW3_FAMILY_V6 &&
867 sin6->sin6_family == AF_INET6)
869 found = !memcmp(&addr->address.v6, &sin6->sin6_addr,
870 sizeof(sin6->sin6_addr));
880 inet_ntop(addr->family == FW3_FAMILY_V4 ? AF_INET : AF_INET6,
881 &addr->address.v4, buf, sizeof(buf));
883 info(" * Flushing conntrack: %s", buf);
884 fprintf(ct, "%s\n", buf);