iptables: fix possible NULL pointer access on constructing rule masks
[project/firewall3.git] / iptables.c
index 2fc8d36..f8d4d46 100644 (file)
@@ -1,7 +1,7 @@
 /*
  * firewall3 - 3rd OpenWrt UCI firewall implementation
  *
- *   Copyright (C) 2013 Jo-Philipp Wich <jow@openwrt.org>
+ *   Copyright (C) 2013 Jo-Philipp Wich <jo@mein.io>
  *
  * Permission to use, copy, modify, and/or distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
 
+#define _GNU_SOURCE /* RTLD_NEXT */
+
+/* include userspace headers */
+#include <dlfcn.h>
+#include <unistd.h>
+#include <getopt.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <sys/utsname.h>
+#include <sys/socket.h>
+
+/* prevent indirect inclusion of kernel headers */
+#define _LINUX_IF_H
+#define _LINUX_IN_H
+#define _LINUX_IN6_H
+
+/* prevent libiptc from including kernel headers */
+#define _FWCHAINS_KERNEL_HEADERS_H
+
+/* finally include libiptc and xtables */
+#include <libiptc/libiptc.h>
+#include <libiptc/libip6tc.h>
+#include <xtables.h>
+
+#include <setjmp.h>
+
+#include "options.h"
+
+/* xtables interface */
+#if (XTABLES_VERSION_CODE >= 10)
+# include "xtables-10.h"
+#elif (XTABLES_VERSION_CODE == 5)
+# include "xtables-5.h"
+#else
+# error "Unsupported xtables version"
+#endif
+
 #include "iptables.h"
 
 
+struct fw3_ipt_rule {
+       struct fw3_ipt_handle *h;
+
+       union {
+               struct ipt_entry e;
+               struct ip6t_entry e6;
+       };
+
+       struct xtables_rule_match *matches;
+       struct xtables_target *target;
+
+       int argc;
+       char **argv;
+
+       uint32_t protocol;
+       bool protocol_loaded;
+};
+
 static struct option base_opts[] = {
-       { .name = "match",  .has_arg = 1, .val = 'm' },
-       { .name = "jump",   .has_arg = 1, .val = 'j' },
-       { .name = "append", .has_arg = 1, .val = 'A' },
+       { .name = "match",         .has_arg = 1, .val = 'm' },
+       { .name = "jump",          .has_arg = 1, .val = 'j' },
+       { .name = "in-interface",  .has_arg = 1, .val = 'i' },
+       { .name = "out-interface", .has_arg = 1, .val = 'o' },
+       { .name = "source",        .has_arg = 1, .val = 's' },
+       { .name = "destination",   .has_arg = 1, .val = 'd' },
        { NULL }
 };
 
+
+static jmp_buf fw3_ipt_error_jmp;
+
+static __attribute__((noreturn))
+void fw3_ipt_error_handler(enum xtables_exittype status,
+                           const char *fmt, ...)
+{
+       va_list args;
+
+       fprintf(stderr, "     ! Exception: ");
+
+       va_start(args, fmt);
+       vfprintf(stderr, fmt, args);
+       va_end(args);
+
+       longjmp(fw3_ipt_error_jmp, status);
+}
+
 static struct xtables_globals xtg = {
        .option_offset = 0,
        .program_version = "4",
        .orig_opts = base_opts,
+       .exit_err = fw3_ipt_error_handler,
+#if XTABLES_VERSION_CODE > 10
+       .compat_rev = xtables_compatible_revision,
+#endif
 };
 
 static struct xtables_globals xtg6 = {
        .option_offset = 0,
        .program_version = "6",
        .orig_opts = base_opts,
+       .exit_err = fw3_ipt_error_handler,
+#if XTABLES_VERSION_CODE > 10
+       .compat_rev = xtables_compatible_revision,
+#endif
 };
 
+static struct {
+       bool retain;
+       int mcount, tcount;
+       struct xtables_match **matches;
+       struct xtables_target **targets;
+       void (*register_match)(struct xtables_match *);
+       void (*register_target)(struct xtables_target *);
+} xext;
+
+
 /* Required by certain extensions like SNAT and DNAT */
 int kernel_version = 0;
 
@@ -54,27 +148,20 @@ get_kernel_version(void)
        kernel_version = 0x10000 * x + 0x100 * y + z;
 }
 
-#ifdef DISABLE_IPV6
-#undef __ipt_module
-#define __ipt_module(x) libxt_##x##_init, libipt_##x##_init,
-#else
-#undef __ipt_module
-#define __ipt_module(x) libxt_##x##_init, libipt_##x##_init, libip6t_##x##_init,
-#endif
-
 static void fw3_init_extensions(void)
 {
-       int i;
-       void (*initfuncs[])(void) = { FW3_IPT_MODULES };
+       init_extensions();
+       init_extensions4();
 
-       for (i = 0; i < sizeof(initfuncs)/sizeof(initfuncs[0]); i++)
-               if (initfuncs[i])
-                       initfuncs[i]();
+#ifndef DISABLE_IPV6
+       init_extensions6();
+#endif
 }
 
 struct fw3_ipt_handle *
 fw3_ipt_open(enum fw3_family family, enum fw3_table table)
 {
+       int i;
        struct fw3_ipt_handle *h;
 
        h = fw3_alloc(sizeof(*h));
@@ -111,6 +198,14 @@ fw3_ipt_open(enum fw3_family family, enum fw3_table table)
        fw3_xt_reset();
        fw3_init_extensions();
 
+       if (xext.register_match)
+               for (i = 0; i < xext.mcount; i++)
+                       xext.register_match(xext.matches[i]);
+
+       if (xext.register_target)
+               for (i = 0; i < xext.tcount; i++)
+                       xext.register_target(xext.targets[i]);
+
        return h;
 }
 
@@ -143,30 +238,21 @@ fw3_ipt_set_policy(struct fw3_ipt_handle *h, const char *chain,
 }
 
 void
-fw3_ipt_delete_chain(struct fw3_ipt_handle *h, const char *chain)
+fw3_ipt_flush_chain(struct fw3_ipt_handle *h, const char *chain)
 {
        if (fw3_pr_debug)
-       {
                debug(h, "-F %s\n", chain);
-               debug(h, "-X %s\n", chain);
-       }
 
 #ifndef DISABLE_IPV6
        if (h->family == FW3_FAMILY_V6)
-       {
-               if (ip6tc_flush_entries(chain, h->handle))
-                       ip6tc_delete_chain(chain, h->handle);
-       }
+               ip6tc_flush_entries(chain, h->handle);
        else
 #endif
-       {
-               if (iptc_flush_entries(chain, h->handle))
-                       iptc_delete_chain(chain, h->handle);
-       }
+               iptc_flush_entries(chain, h->handle);
 }
 
-void
-fw3_ipt_delete_rules(struct fw3_ipt_handle *h, const char *target)
+static void
+delete_rules(struct fw3_ipt_handle *h, const char *target)
 {
        unsigned int num;
        const struct ipt_entry *e;
@@ -236,6 +322,102 @@ fw3_ipt_delete_rules(struct fw3_ipt_handle *h, const char *target)
 }
 
 void
+fw3_ipt_delete_chain(struct fw3_ipt_handle *h, const char *chain)
+{
+       delete_rules(h, chain);
+
+       if (fw3_pr_debug)
+               debug(h, "-X %s\n", chain);
+
+#ifndef DISABLE_IPV6
+       if (h->family == FW3_FAMILY_V6)
+               ip6tc_delete_chain(chain, h->handle);
+       else
+#endif
+               iptc_delete_chain(chain, h->handle);
+}
+
+static bool
+has_rule_tag(const void *base, unsigned int start, unsigned int end)
+{
+       unsigned int i;
+       const struct xt_entry_match *em;
+
+       for (i = start; i < end; i += em->u.match_size)
+       {
+               em = base + i;
+
+               if (strcmp(em->u.user.name, "comment"))
+                       continue;
+
+               if (!memcmp(em->data, "!fw3", 4))
+                       return true;
+       }
+
+       return false;
+}
+
+void
+fw3_ipt_delete_id_rules(struct fw3_ipt_handle *h, const char *chain)
+{
+       unsigned int num;
+       const struct ipt_entry *e;
+       bool found;
+
+#ifndef DISABLE_IPV6
+       if (h->family == FW3_FAMILY_V6)
+       {
+               if (!ip6tc_is_chain(chain, h->handle))
+                       return;
+
+               do {
+                       found = false;
+
+                       const struct ip6t_entry *e6;
+                       for (num = 0, e6 = ip6tc_first_rule(chain, h->handle);
+                                e6 != NULL;
+                                num++, e6 = ip6tc_next_rule(e6, h->handle))
+                       {
+                               if (has_rule_tag(e6, sizeof(*e6), e6->target_offset))
+                               {
+                                       if (fw3_pr_debug)
+                                               debug(h, "-D %s %u\n", chain, num + 1);
+
+                                       ip6tc_delete_num_entry(chain, num, h->handle);
+                                       found = true;
+                                       break;
+                               }
+                       }
+               } while (found);
+       }
+       else
+#endif
+       {
+               if (!iptc_is_chain(chain, h->handle))
+                       return;
+
+               do {
+                       found = false;
+
+                       for (num = 0, e = iptc_first_rule(chain, h->handle);
+                                e != NULL;
+                                num++, e = iptc_next_rule(e, h->handle))
+                       {
+                               if (has_rule_tag(e, sizeof(*e), e->target_offset))
+                               {
+                                       if (fw3_pr_debug)
+                                               debug(h, "-D %s %u\n", chain, num + 1);
+
+                                       iptc_delete_num_entry(chain, num, h->handle);
+                                       found = true;
+                                       break;
+                               }
+                       }
+               } while (found);
+       }
+}
+
+void
 fw3_ipt_create_chain(struct fw3_ipt_handle *h, const char *fmt, ...)
 {
        char buf[32];
@@ -292,6 +474,69 @@ fw3_ipt_flush(struct fw3_ipt_handle *h)
        }
 }
 
+static bool
+chain_is_empty(struct fw3_ipt_handle *h, const char *chain)
+{
+#ifndef DISABLE_IPV6
+       if (h->family == FW3_FAMILY_V6)
+               return (!ip6tc_builtin(chain, h->handle) &&
+                       !ip6tc_first_rule(chain, h->handle));
+#endif
+
+       return (!iptc_builtin(chain, h->handle) &&
+               !iptc_first_rule(chain, h->handle));
+}
+
+void
+fw3_ipt_gc(struct fw3_ipt_handle *h)
+{
+       const char *chain;
+       bool found;
+
+#ifndef DISABLE_IPV6
+       if (h->family == FW3_FAMILY_V6)
+       {
+               do {
+                       found = false;
+
+                       for (chain = ip6tc_first_chain(h->handle);
+                                chain != NULL;
+                                chain = ip6tc_next_chain(h->handle))
+                       {
+                               if (!chain_is_empty(h, chain))
+                                       continue;
+
+                               fw3_ipt_delete_chain(h, chain);
+                               found = true;
+                               break;
+                       }
+               } while(found);
+       }
+       else
+#endif
+       {
+               do {
+                       found = false;
+
+                       for (chain = iptc_first_chain(h->handle);
+                                chain != NULL;
+                                chain = iptc_next_chain(h->handle))
+                       {
+                               warn("C=%s\n", chain);
+
+                               if (!chain_is_empty(h, chain))
+                                       continue;
+
+                               warn("D=%s\n", chain);
+
+                               fw3_ipt_delete_chain(h, chain);
+                               found = true;
+                               break;
+                       }
+               } while (found);
+       }
+}
+
 void
 fw3_ipt_commit(struct fw3_ipt_handle *h)
 {
@@ -302,27 +547,20 @@ fw3_ipt_commit(struct fw3_ipt_handle *h)
        {
                rv = ip6tc_commit(h->handle);
                if (!rv)
-                       fprintf(stderr, "ip6tc_commit(): %s\n", ip6tc_strerror(errno));
+                       warn("ip6tc_commit(): %s", ip6tc_strerror(errno));
        }
        else
 #endif
        {
                rv = iptc_commit(h->handle);
                if (!rv)
-                       fprintf(stderr, "iptc_commit(): %s\n", iptc_strerror(errno));
-       }
-
-       if (h->libv)
-       {
-               while (h->libc > 0)
-               {
-                       h->libc--;
-                       dlclose(h->libv[h->libc]);
-               }
-
-               free(h->libv);
+                       warn("iptc_commit(): %s", iptc_strerror(errno));
        }
+}
 
+void
+fw3_ipt_close(struct fw3_ipt_handle *h)
+{
        free(h);
 }
 
@@ -365,43 +603,14 @@ get_protoname(struct fw3_ipt_rule *r)
        return NULL;
 }
 
-static bool
-load_extension(struct fw3_ipt_handle *h, const char *name)
-{
-       char path[256];
-       void *lib, **tmp;
-       const char *pfx = (h->family == FW3_FAMILY_V6) ? "libip6t" : "libipt";
-
-       snprintf(path, sizeof(path), "/usr/lib/iptables/libxt_%s.so", name);
-       if (!(lib = dlopen(path, RTLD_NOW)))
-       {
-               snprintf(path, sizeof(path), "/usr/lib/iptables/%s_%s.so", pfx, name);
-               lib = dlopen(path, RTLD_NOW);
-       }
-
-       if (!lib)
-               return false;
-
-       tmp = realloc(h->libv, sizeof(lib) * (h->libc + 1));
-
-       if (!tmp)
-               return false;
-
-       h->libv = tmp;
-       h->libv[h->libc++] = lib;
-
-       return true;
-}
-
 static struct xtables_match *
 find_match(struct fw3_ipt_rule *r, const char *name)
 {
        struct xtables_match *m;
 
-       m = xtables_find_match(name, XTF_DONT_LOAD, &r->matches);
-
-       if (!m && load_extension(r->h, name))
-               m = xtables_find_match(name, XTF_DONT_LOAD, &r->matches);
+       xext.retain = true;
+       m = xtables_find_match(name, XTF_TRY_LOAD, &r->matches);
+       xext.retain = false;
 
        return m;
 }
@@ -467,13 +676,14 @@ find_target(struct fw3_ipt_rule *r, const char *name)
 {
        struct xtables_target *t;
 
-       if (is_chain(r->h, name))
-               return xtables_find_target(XT_STANDARD_TARGET, XTF_LOAD_MUST_SUCCEED);
+       xext.retain = true;
 
-       t = xtables_find_target(name, XTF_DONT_LOAD);
+       if (is_chain(r->h, name))
+               t = xtables_find_target(XT_STANDARD_TARGET, XTF_TRY_LOAD);
+       else
+               t = xtables_find_target(name, XTF_TRY_LOAD);
 
-       if (!t && load_extension(r->h, name))
-               t = xtables_find_target(name, XTF_DONT_LOAD);
+       xext.retain = false;
 
        return t;
 }
@@ -596,31 +806,6 @@ fw3_ipt_rule_in_out(struct fw3_ipt_rule *r,
 }
 
 
-static void
-ip4prefix2mask(int prefix, struct in_addr *mask)
-{
-       mask->s_addr = htonl(~((1 << (32 - prefix)) - 1));
-}
-
-#ifndef DISABLE_IPV6
-static void
-ip6prefix2mask(int prefix, struct in6_addr *mask)
-{
-       char *p = (char *)mask;
-
-       if (prefix > 0)
-       {
-               memset(p, 0xff, prefix / 8);
-               memset(p + (prefix / 8) + 1, 0, (128 - prefix) / 8);
-               p[prefix / 8] = 0xff << (8 - (prefix & 7));
-       }
-       else
-       {
-               memset(mask, 0, sizeof(*mask));
-       }
-}
-#endif
-
 void
 fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
                       struct fw3_address *src, struct fw3_address *dest)
@@ -635,13 +820,13 @@ fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
                if (src->range)
                {
                        fw3_ipt_rule_addarg(r, src->invert, "--src-range",
-                                           fw3_address_to_string(src, false));
+                                           fw3_address_to_string(src, false, false));
                }
 #ifndef DISABLE_IPV6
                else if (r->h->family == FW3_FAMILY_V6)
                {
                        r->e6.ipv6.src = src->address.v6;
-                       ip6prefix2mask(src->mask, &r->e6.ipv6.smsk);
+                       r->e6.ipv6.smsk = src->mask.v6;
 
                        int i;
                        for (i = 0; i < 4; i++)
@@ -654,7 +839,7 @@ fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
                else
                {
                        r->e.ip.src = src->address.v4;
-                       ip4prefix2mask(src->mask, &r->e.ip.smsk);
+                       r->e.ip.smsk = src->mask.v4;
 
                        r->e.ip.src.s_addr &= r->e.ip.smsk.s_addr;
 
@@ -668,13 +853,13 @@ fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
                if (dest->range)
                {
                        fw3_ipt_rule_addarg(r, dest->invert, "--dst-range",
-                                           fw3_address_to_string(dest, false));
+                                           fw3_address_to_string(dest, false, false));
                }
 #ifndef DISABLE_IPV6
                else if (r->h->family == FW3_FAMILY_V6)
                {
                        r->e6.ipv6.dst = dest->address.v6;
-                       ip6prefix2mask(dest->mask, &r->e6.ipv6.dmsk);
+                       r->e6.ipv6.dmsk = dest->mask.v6;
 
                        int i;
                        for (i = 0; i < 4; i++)
@@ -687,7 +872,7 @@ fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
                else
                {
                        r->e.ip.dst = dest->address.v4;
-                       ip4prefix2mask(dest->mask, &r->e.ip.dmsk);
+                       r->e.ip.dmsk = dest->mask.v4;
 
                        r->e.ip.dst.s_addr &= r->e.ip.dmsk.s_addr;
 
@@ -731,13 +916,29 @@ fw3_ipt_rule_sport_dport(struct fw3_ipt_rule *r,
 }
 
 void
+fw3_ipt_rule_device(struct fw3_ipt_rule *r, const char *device, bool out)
+{
+       if (device) {
+               struct fw3_device dev = { .any = false };
+               strncpy(dev.name, device, sizeof(dev.name) - 1);
+               fw3_ipt_rule_in_out(r, (out) ? NULL : &dev, (out) ? &dev : NULL);
+       }
+}
+
+void
 fw3_ipt_rule_mac(struct fw3_ipt_rule *r, struct fw3_mac *mac)
 {
+       char buf[sizeof("ff:ff:ff:ff:ff:ff\0")];
+       uint8_t *addr = mac->mac.ether_addr_octet;
+
        if (!mac)
                return;
 
+       sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
+               addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
+
        fw3_ipt_rule_addarg(r, false, "-m", "mac");
-       fw3_ipt_rule_addarg(r, mac->invert, "--mac-source", ether_ntoa(&mac->mac));
+       fw3_ipt_rule_addarg(r, mac->invert, "--mac-source", buf);
 }
 
 void
@@ -791,34 +992,50 @@ fw3_ipt_rule_limit(struct fw3_ipt_rule *r, struct fw3_limit *limit)
 }
 
 void
-fw3_ipt_rule_ipset(struct fw3_ipt_rule *r, struct fw3_ipset *ipset,
-                   bool invert)
+fw3_ipt_rule_ipset(struct fw3_ipt_rule *r, struct fw3_setmatch *match)
 {
        char buf[sizeof("dst,dst,dst\0")];
        char *p = buf;
+       int i = 0;
 
+       struct fw3_ipset *set;
        struct fw3_ipset_datatype *type;
 
-       if (!ipset)
+       if (!match || !match->set || !match->ptr)
                return;
 
-       list_for_each_entry(type, &ipset->datatypes, list)
+       set = match->ptr;
+       list_for_each_entry(type, &set->datatypes, list)
        {
+               if (i >= 3)
+                       break;
+
                if (p > buf)
                        *p++ = ',';
 
-               p += sprintf(p, "%s", type->dest ? "dst" : "src");
+               p += sprintf(p, "%s", match->dir[i] ? match->dir[i] : type->dir);
+               i++;
        }
 
        fw3_ipt_rule_addarg(r, false, "-m", "set");
 
-       fw3_ipt_rule_addarg(r, invert, "--match-set",
-                           ipset->external ? ipset->external : ipset->name);
+       fw3_ipt_rule_addarg(r, match->invert, "--match-set",
+                           set->external ? set->external : set->name);
 
        fw3_ipt_rule_addarg(r, false, buf, NULL);
 }
 
 void
+fw3_ipt_rule_helper(struct fw3_ipt_rule *r, struct fw3_cthelpermatch *match)
+{
+       if (!match || !match->set || !match->ptr)
+               return;
+
+       fw3_ipt_rule_addarg(r, false, "-m", "helper");
+       fw3_ipt_rule_addarg(r, match->invert, "--helper", match->ptr->name);
+}
+
+void
 fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
 {
        int i;
@@ -838,8 +1055,8 @@ fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
 
        fw3_ipt_rule_addarg(r, false, "-m", "time");
 
-       if (time->utc)
-               fw3_ipt_rule_addarg(r, false, "--utc", NULL);
+       if (!time->utc)
+               fw3_ipt_rule_addarg(r, false, "--kerneltz", NULL);
 
        if (d1)
        {
@@ -877,7 +1094,7 @@ fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
        {
                for (i = 1, p = buf; i < 32; i++)
                {
-                       if (hasbit(time->monthdays, i))
+                       if (fw3_hasbit(time->monthdays, i))
                        {
                                if (p > buf)
                                        *p++ = ',';
@@ -886,14 +1103,14 @@ fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
                        }
                }
 
-               fw3_ipt_rule_addarg(r, hasbit(time->monthdays, 0), "--monthdays", buf);
+               fw3_ipt_rule_addarg(r, fw3_hasbit(time->monthdays, 0), "--monthdays", buf);
        }
 
        if (time->weekdays & 0xFE)
        {
                for (i = 1, p = buf; i < 8; i++)
                {
-                       if (hasbit(time->weekdays, i))
+                       if (fw3_hasbit(time->weekdays, i))
                        {
                                if (p > buf)
                                        *p++ = ',';
@@ -902,7 +1119,7 @@ fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
                        }
                }
 
-               fw3_ipt_rule_addarg(r, hasbit(time->weekdays, 0), "--weekdays", buf);
+               fw3_ipt_rule_addarg(r, fw3_hasbit(time->weekdays, 0), "--weekdays", buf);
        }
 }
 
@@ -968,12 +1185,12 @@ fw3_ipt_rule_extra(struct fw3_ipt_rule *r, const char *extra)
 static void
 rule_print6(struct ip6t_entry *e)
 {
-       char buf[INET6_ADDRSTRLEN];
+       char buf1[INET6_ADDRSTRLEN], buf2[INET6_ADDRSTRLEN];
        char *pname;
 
        if (e->ipv6.flags & IP6T_F_PROTO)
        {
-               if (e->ipv6.flags & XT_INV_PROTO)
+               if (e->ipv6.invflags & XT_INV_PROTO)
                        printf(" !");
 
                pname = get_protoname(container_of(e, struct fw3_ipt_rule, e6));
@@ -986,7 +1203,7 @@ rule_print6(struct ip6t_entry *e)
 
        if (e->ipv6.iniface[0])
        {
-               if (e->ipv6.flags & IP6T_INV_VIA_IN)
+               if (e->ipv6.invflags & IP6T_INV_VIA_IN)
                        printf(" !");
 
                printf(" -i %s", e->ipv6.iniface);
@@ -994,7 +1211,7 @@ rule_print6(struct ip6t_entry *e)
 
        if (e->ipv6.outiface[0])
        {
-               if (e->ipv6.flags & IP6T_INV_VIA_OUT)
+               if (e->ipv6.invflags & IP6T_INV_VIA_OUT)
                        printf(" !");
 
                printf(" -o %s", e->ipv6.outiface);
@@ -1002,20 +1219,22 @@ rule_print6(struct ip6t_entry *e)
 
        if (memcmp(&e->ipv6.src, &in6addr_any, sizeof(struct in6_addr)))
        {
-               if (e->ipv6.flags & IP6T_INV_SRCIP)
+               if (e->ipv6.invflags & IP6T_INV_SRCIP)
                        printf(" !");
 
-               printf(" -s %s/%u", inet_ntop(AF_INET6, &e->ipv6.src, buf, sizeof(buf)),
-                                   xtables_ip6mask_to_cidr(&e->ipv6.smsk));
+               printf(" -s %s/%s",
+                      inet_ntop(AF_INET6, &e->ipv6.src, buf1, sizeof(buf1)),
+                      inet_ntop(AF_INET6, &e->ipv6.smsk, buf2, sizeof(buf2)));
        }
 
        if (memcmp(&e->ipv6.dst, &in6addr_any, sizeof(struct in6_addr)))
        {
-               if (e->ipv6.flags & IP6T_INV_DSTIP)
+               if (e->ipv6.invflags & IP6T_INV_DSTIP)
                        printf(" !");
 
-               printf(" -d %s/%u", inet_ntop(AF_INET6, &e->ipv6.dst, buf, sizeof(buf)),
-                                   xtables_ip6mask_to_cidr(&e->ipv6.dmsk));
+               printf(" -d %s/%s",
+                      inet_ntop(AF_INET6, &e->ipv6.dst, buf1, sizeof(buf1)),
+                      inet_ntop(AF_INET6, &e->ipv6.dmsk, buf2, sizeof(buf2)));
        }
 }
 #endif
@@ -1024,12 +1243,12 @@ static void
 rule_print4(struct ipt_entry *e)
 {
        struct in_addr in_zero = { 0 };
-       char buf[sizeof("255.255.255.255\0")];
+       char buf1[sizeof("255.255.255.255\0")], buf2[sizeof("255.255.255.255\0")];
        char *pname;
 
        if (e->ip.proto)
        {
-               if (e->ip.flags & XT_INV_PROTO)
+               if (e->ip.invflags & XT_INV_PROTO)
                        printf(" !");
 
                pname = get_protoname(container_of(e, struct fw3_ipt_rule, e));
@@ -1042,7 +1261,7 @@ rule_print4(struct ipt_entry *e)
 
        if (e->ip.iniface[0])
        {
-               if (e->ip.flags & IPT_INV_VIA_IN)
+               if (e->ip.invflags & IPT_INV_VIA_IN)
                        printf(" !");
 
                printf(" -i %s", e->ip.iniface);
@@ -1050,7 +1269,7 @@ rule_print4(struct ipt_entry *e)
 
        if (e->ip.outiface[0])
        {
-               if (e->ip.flags & IPT_INV_VIA_OUT)
+               if (e->ip.invflags & IPT_INV_VIA_OUT)
                        printf(" !");
 
                printf(" -o %s", e->ip.outiface);
@@ -1058,31 +1277,29 @@ rule_print4(struct ipt_entry *e)
 
        if (memcmp(&e->ip.src, &in_zero, sizeof(struct in_addr)))
        {
-               if (e->ip.flags & IPT_INV_SRCIP)
+               if (e->ip.invflags & IPT_INV_SRCIP)
                        printf(" !");
 
-               printf(" -s %s/%u", inet_ntop(AF_INET, &e->ip.src, buf, sizeof(buf)),
-                                   xtables_ipmask_to_cidr(&e->ip.smsk));
+               printf(" -s %s/%s",
+                      inet_ntop(AF_INET, &e->ip.src, buf1, sizeof(buf1)),
+                      inet_ntop(AF_INET, &e->ip.smsk, buf2, sizeof(buf2)));
        }
 
        if (memcmp(&e->ip.dst, &in_zero, sizeof(struct in_addr)))
        {
-               if (e->ip.flags & IPT_INV_DSTIP)
+               if (e->ip.invflags & IPT_INV_DSTIP)
                        printf(" !");
 
-               printf(" -d %s/%u", inet_ntop(AF_INET, &e->ip.dst, buf, sizeof(buf)),
-                                   xtables_ipmask_to_cidr(&e->ip.dmsk));
+               printf(" -d %s/%s",
+                      inet_ntop(AF_INET, &e->ip.dst, buf1, sizeof(buf1)),
+                      inet_ntop(AF_INET, &e->ip.dmsk, buf2, sizeof(buf2)));
        }
 }
 
 static void
-rule_print(struct fw3_ipt_rule *r, const char *chain)
+rule_print(struct fw3_ipt_rule *r, const char *prefix, const char *chain)
 {
-       struct xtables_rule_match *rm;
-       struct xtables_match *m;
-       struct xtables_target *t;
-
-       debug(r->h, "-A %s", chain);
+       debug(r->h, "%s %s", prefix, chain);
 
 #ifndef DISABLE_IPV6
        if (r->h->family == FW3_FAMILY_V6)
@@ -1091,23 +1308,8 @@ rule_print(struct fw3_ipt_rule *r, const char *chain)
 #endif
                rule_print4(&r->e);
 
-       for (rm = r->matches; rm; rm = rm->next)
-       {
-               m = rm->match;
-               printf(" -m %s", fw3_xt_get_match_name(m));
-
-               if (m->save)
-                       m->save(&r->e.ip, m->m);
-       }
-
-       if (r->target)
-       {
-               t = r->target;
-               printf(" -j %s", fw3_xt_get_target_name(t));
-
-               if (t->save)
-                       t->save(&r->e.ip, t->t);
-       }
+       fw3_xt_print_matches(&r->e.ip, r->matches);
+       fw3_xt_print_target(&r->e.ip, r->target);
 
        printf("\n");
 }
@@ -1155,12 +1357,10 @@ parse_option(struct fw3_ipt_rule *r, int optc, bool inv)
        }
 
        if (optc == ':')
-               fprintf(stderr, "parse_option(): option '%s' needs argument\n",
-                       r->argv[optind-1]);
+               warn("parse_option(): option '%s' needs argument", r->argv[optind-1]);
 
        if (optc == '?')
-               fprintf(stderr, "parse_option(): unknown option '%s'\n",
-                       r->argv[optind-1]);
+               warn("parse_option(): unknown option '%s'", r->argv[optind-1]);
 
        return false;
 }
@@ -1192,15 +1392,178 @@ fw3_ipt_rule_addarg(struct fw3_ipt_rule *r, bool inv,
                r->argv[r->argc++] = fw3_strdup(v);
 }
 
-void
-fw3_ipt_rule_append(struct fw3_ipt_rule *r, const char *fmt, ...)
+static unsigned char *
+rule_mask(struct fw3_ipt_rule *r)
 {
        size_t s;
+       unsigned char *p, *mask = NULL;
+       struct xtables_rule_match *m;
+
+#define SZ(x) XT_ALIGN(sizeof(struct x))
+
+#ifndef DISABLE_IPV6
+       if (r->h->family == FW3_FAMILY_V6)
+       {
+               s = SZ(ip6t_entry);
+
+               for (m = r->matches; m; m = m->next)
+                       s += SZ(ip6t_entry_match) + m->match->size;
+
+               s += SZ(ip6t_entry_target);
+               if (r->target)
+                       s += r->target->size;
+
+               mask = fw3_alloc(s);
+               memset(mask, 0xFF, SZ(ip6t_entry));
+               p = mask + SZ(ip6t_entry);
+
+               for (m = r->matches; m; m = m->next)
+               {
+                       memset(p, 0xFF, SZ(ip6t_entry_match) + m->match->userspacesize);
+                       p += SZ(ip6t_entry_match) + m->match->size;
+               }
+
+               memset(p, 0xFF, SZ(ip6t_entry_target) + (r->target ? r->target->userspacesize : 0));
+       }
+       else
+#endif
+       {
+               s = SZ(ipt_entry);
+
+               for (m = r->matches; m; m = m->next)
+                       s += SZ(ipt_entry_match) + m->match->size;
+
+               s += SZ(ipt_entry_target);
+               if (r->target)
+                       s += r->target->size;
+
+               mask = fw3_alloc(s);
+               memset(mask, 0xFF, SZ(ipt_entry));
+               p = mask + SZ(ipt_entry);
+
+               for (m = r->matches; m; m = m->next)
+               {
+                       memset(p, 0xFF, SZ(ipt_entry_match) + m->match->userspacesize);
+                       p += SZ(ipt_entry_match) + m->match->size;
+               }
+
+               memset(p, 0xFF, SZ(ipt_entry_target) + (r->target ? r->target->userspacesize : 0));
+       }
+
+       return mask;
+}
+
+static void *
+rule_build(struct fw3_ipt_rule *r)
+{
+       size_t s, target_size = (r->target) ? r->target->t->u.target_size : 0;
+       struct xtables_rule_match *m;
+
+#ifndef DISABLE_IPV6
+       if (r->h->family == FW3_FAMILY_V6)
+       {
+               struct ip6t_entry *e6;
+
+               s = XT_ALIGN(sizeof(struct ip6t_entry));
+
+               for (m = r->matches; m; m = m->next)
+                       s += m->match->m->u.match_size;
+
+               e6 = fw3_alloc(s + target_size);
+
+               memcpy(e6, &r->e6, sizeof(struct ip6t_entry));
+
+               e6->target_offset = s;
+               e6->next_offset = s + target_size;
+
+               s = 0;
+
+               for (m = r->matches; m; m = m->next)
+               {
+                       memcpy(e6->elems + s, m->match->m, m->match->m->u.match_size);
+                       s += m->match->m->u.match_size;
+               }
+
+               if (target_size)
+                       memcpy(e6->elems + s, r->target->t, target_size);
+
+               return e6;
+       }
+       else
+#endif
+       {
+               struct ipt_entry *e;
+
+               s = XT_ALIGN(sizeof(struct ipt_entry));
+
+               for (m = r->matches; m; m = m->next)
+                       s += m->match->m->u.match_size;
+
+               e = fw3_alloc(s + target_size);
+
+               memcpy(e, &r->e, sizeof(struct ipt_entry));
+
+               e->target_offset = s;
+               e->next_offset = s + target_size;
+
+               s = 0;
+
+               for (m = r->matches; m; m = m->next)
+               {
+                       memcpy(e->elems + s, m->match->m, m->match->m->u.match_size);
+                       s += m->match->m->u.match_size;
+               }
+
+               if (target_size)
+                       memcpy(e->elems + s, r->target->t, target_size);
+
+               return e;
+       }
+}
+
+static void
+set_rule_tag(struct fw3_ipt_rule *r)
+{
+       int i;
+       char *p, **tmp;
+       const char *tag = "!fw3";
+
+       for (i = 0; i < r->argc; i++)
+               if (!strcmp(r->argv[i], "--comment") && (i + 1) < r->argc)
+                       if (asprintf(&p, "%s: %s", tag, r->argv[i + 1]) > 0)
+                       {
+                               free(r->argv[i + 1]);
+                               r->argv[i + 1] = p;
+                               return;
+                       }
+
+       tmp = realloc(r->argv, (r->argc + 4) * sizeof(*r->argv));
+
+       if (tmp)
+       {
+               r->argv = tmp;
+               r->argv[r->argc++] = fw3_strdup("-m");
+               r->argv[r->argc++] = fw3_strdup("comment");
+               r->argv[r->argc++] = fw3_strdup("--comment");
+               r->argv[r->argc++] = fw3_strdup(tag);
+       }
+}
+
+void
+__fw3_ipt_rule_append(struct fw3_ipt_rule *r, bool repl, const char *fmt, ...)
+{
+       void *rule;
+       unsigned char *mask;
+
        struct xtables_rule_match *m;
        struct xtables_match *em;
        struct xtables_target *et;
        struct xtables_globals *g;
-       struct ipt_entry *e;
+
+       struct fw3_device dev;
+       struct fw3_address addr;
+
+       enum xtables_exittype status;
 
        int i, optc;
        bool inv = false;
@@ -1217,7 +1580,18 @@ fw3_ipt_rule_append(struct fw3_ipt_rule *r, const char *fmt, ...)
        optind = 0;
        opterr = 0;
 
-       while ((optc = getopt_long(r->argc, r->argv, "m:j:", g->opts, NULL)) != -1)
+       status = setjmp(fw3_ipt_error_jmp);
+
+       if (status > 0)
+       {
+               info("     ! Skipping due to previous exception (code %u)", status);
+               goto free;
+       }
+
+       set_rule_tag(r);
+
+       while ((optc = getopt_long(r->argc, r->argv, "-:m:j:i:o:s:d:", g->opts,
+                                  NULL)) != -1)
        {
                switch (optc)
                {
@@ -1226,7 +1600,7 @@ fw3_ipt_rule_append(struct fw3_ipt_rule *r, const char *fmt, ...)
 
                        if (!em)
                        {
-                               fprintf(stderr, "fw3_ipt_rule_append(): Can't find match '%s'\n", optarg);
+                               warn("fw3_ipt_rule_append(): Can't find match '%s'", optarg);
                                goto free;
                        }
 
@@ -1238,21 +1612,50 @@ fw3_ipt_rule_append(struct fw3_ipt_rule *r, const char *fmt, ...)
 
                        if (!et)
                        {
-                               fprintf(stderr, "fw3_ipt_rule_append(): Can't find target '%s'\n", optarg);
+                               warn("fw3_ipt_rule_append(): Can't find target '%s'", optarg);
+                               goto free;
+                       }
+
+                       break;
+
+               case 'i':
+               case 'o':
+                       if (!fw3_parse_device(&dev, optarg, false) ||
+                           dev.any || dev.invert || *dev.network)
+                       {
+                               warn("fw3_ipt_rule_append(): Bad argument '%s'", optarg);
+                               goto free;
+                       }
+
+                       dev.invert = inv;
+                       fw3_ipt_rule_in_out(r, (optc == 'i') ? &dev : NULL,
+                                              (optc == 'o') ? &dev : NULL);
+                       break;
+
+               case 's':
+               case 'd':
+                       if (!fw3_parse_address(&addr, optarg, false) ||
+                           addr.range || addr.invert)
+                       {
+                               warn("fw3_ipt_rule_append(): Bad argument '%s'", optarg);
                                goto free;
                        }
 
+                       addr.invert = inv;
+                       fw3_ipt_rule_src_dest(r, (optc == 's') ? &addr : NULL,
+                                                (optc == 'd') ? &addr : NULL);
                        break;
 
                case 1:
                        if ((optarg[0] == '!') && (optarg[1] == '\0'))
                        {
+                               optarg[0] = '\0';
                                inv = true;
                                continue;
                        }
 
-                       fprintf(stderr, "fw3_ipt_rule_append(): Bad argument '%s'\n", optarg);
-                       return;
+                       warn("fw3_ipt_rule_append(): Bad argument '%s'", optarg);
+                       goto free;
 
                default:
                        if (parse_option(r, optc, inv))
@@ -1269,69 +1672,51 @@ fw3_ipt_rule_append(struct fw3_ipt_rule *r, const char *fmt, ...)
        if (r->target)
                xtables_option_tfcall(r->target);
 
-       if (fw3_pr_debug)
-               rule_print(r, buf);
+       rule = rule_build(r);
 
 #ifndef DISABLE_IPV6
        if (r->h->family == FW3_FAMILY_V6)
        {
-               struct ip6t_entry *e6;
-
-               s = XT_ALIGN(sizeof(struct ip6t_entry));
-
-               for (m = r->matches; m; m = m->next)
-                       s += m->match->m->u.match_size;
-
-               e6 = fw3_alloc(s + r->target->t->u.target_size);
-
-               memcpy(e6, &r->e6, sizeof(struct ip6t_entry));
-
-               e6->target_offset = s;
-               e6->next_offset = s + r->target->t->u.target_size;
+               if (repl)
+               {
+                       mask = rule_mask(r);
 
-               s = 0;
+                       while (ip6tc_delete_entry(buf, rule, mask, r->h->handle))
+                               if (fw3_pr_debug)
+                                       rule_print(r, "-D", buf);
 
-               for (m = r->matches; m; m = m->next)
-               {
-                       memcpy(e6->elems + s, m->match->m, m->match->m->u.match_size);
-                       s += m->match->m->u.match_size;
+                       free(mask);
                }
 
-               memcpy(e6->elems + s, r->target->t, r->target->t->u.target_size);
-               ip6tc_append_entry(buf, e6, r->h->handle);
-               free(e6);
+               if (fw3_pr_debug)
+                       rule_print(r, "-A", buf);
+
+               if (!ip6tc_append_entry(buf, rule, r->h->handle))
+                       warn("ip6tc_append_entry(): %s", ip6tc_strerror(errno));
        }
        else
 #endif
        {
-               s = XT_ALIGN(sizeof(struct ipt_entry));
-
-               for (m = r->matches; m; m = m->next)
-                       s += m->match->m->u.match_size;
-
-               e = fw3_alloc(s + r->target->t->u.target_size);
-
-               memcpy(e, &r->e, sizeof(struct ipt_entry));
-
-               e->target_offset = s;
-               e->next_offset = s + r->target->t->u.target_size;
+               if (repl)
+               {
+                       mask = rule_mask(r);
 
-               s = 0;
+                       while (iptc_delete_entry(buf, rule, mask, r->h->handle))
+                               if (fw3_pr_debug)
+                                       rule_print(r, "-D", buf);
 
-               for (m = r->matches; m; m = m->next)
-               {
-                       memcpy(e->elems + s, m->match->m, m->match->m->u.match_size);
-                       s += m->match->m->u.match_size;
+                       free(mask);
                }
 
-               memcpy(e->elems + s, r->target->t, r->target->t->u.target_size);
-
-               if (!iptc_append_entry(buf, e, r->h->handle))
-                       fprintf(stderr, "iptc_append_entry(): %s\n", iptc_strerror(errno));
+               if (fw3_pr_debug)
+                       rule_print(r, "-A", buf);
 
-               free(e);
+               if (!iptc_append_entry(buf, rule, r->h->handle))
+                       warn("iptc_append_entry(): %s\n", iptc_strerror(errno));
        }
 
+       free(rule);
+
 free:
        for (i = 1; i < r->argc; i++)
                free(r->argv[i]);
@@ -1373,3 +1758,63 @@ fw3_ipt_rule_create(struct fw3_ipt_handle *handle, struct fw3_protocol *proto,
 
        return r;
 }
+
+void
+xtables_register_match(struct xtables_match *me)
+{
+       int i;
+       static struct xtables_match **tmp;
+
+       if (!xext.register_match)
+               xext.register_match = dlsym(RTLD_NEXT, "xtables_register_match");
+
+       if (!xext.register_match)
+               return;
+
+       xext.register_match(me);
+
+       if (xext.retain)
+       {
+               for (i = 0; i < xext.mcount; i++)
+                       if (xext.matches[i] == me)
+                               return;
+
+               tmp = realloc(xext.matches, sizeof(me) * (xext.mcount + 1));
+
+               if (!tmp)
+                       return;
+
+               xext.matches = tmp;
+               xext.matches[xext.mcount++] = me;
+       }
+}
+
+void
+xtables_register_target(struct xtables_target *me)
+{
+       int i;
+       static struct xtables_target **tmp;
+
+       if (!xext.register_target)
+               xext.register_target = dlsym(RTLD_NEXT, "xtables_register_target");
+
+       if (!xext.register_target)
+               return;
+
+       xext.register_target(me);
+
+       if (xext.retain)
+       {
+               for (i = 0; i < xext.tcount; i++)
+                       if (xext.targets[i] == me)
+                               return;
+
+               tmp = realloc(xext.targets, sizeof(me) * (xext.tcount + 1));
+
+               if (!tmp)
+                       return;
+
+               xext.targets = tmp;
+               xext.targets[xext.tcount++] = me;
+       }
+}