zones: make forward policy destination bound
[project/firewall3.git] / iptables.c
1 /*
2  * firewall3 - 3rd OpenWrt UCI firewall implementation
3  *
4  *   Copyright (C) 2013 Jo-Philipp Wich <jow@openwrt.org>
5  *
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.
9  *
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.
17  */
18
19 #include "iptables.h"
20
21
22 static struct option base_opts[] = {
23         { .name = "match",  .has_arg = 1, .val = 'm' },
24         { .name = "jump",   .has_arg = 1, .val = 'j' },
25         { NULL }
26 };
27
28 static struct xtables_globals xtg = {
29         .option_offset = 0,
30         .program_version = "4",
31         .orig_opts = base_opts,
32 };
33
34 static struct xtables_globals xtg6 = {
35         .option_offset = 0,
36         .program_version = "6",
37         .orig_opts = base_opts,
38 };
39
40 /* Required by certain extensions like SNAT and DNAT */
41 int kernel_version = 0;
42
43 void
44 get_kernel_version(void)
45 {
46         static struct utsname uts;
47         int x = 0, y = 0, z = 0;
48
49         if (uname(&uts) == -1)
50                 sprintf(uts.release, "3.0.0");
51
52         sscanf(uts.release, "%d.%d.%d", &x, &y, &z);
53         kernel_version = 0x10000 * x + 0x100 * y + z;
54 }
55
56 #ifdef DISABLE_IPV6
57 #undef __ipt_module
58 #define __ipt_module(x) libxt_##x##_init, libipt_##x##_init,
59 #else
60 #undef __ipt_module
61 #define __ipt_module(x) libxt_##x##_init, libipt_##x##_init, libip6t_##x##_init,
62 #endif
63
64 static void fw3_init_extensions(void)
65 {
66         int i;
67         void (*initfuncs[])(void) = { FW3_IPT_MODULES };
68
69         for (i = 0; i < sizeof(initfuncs)/sizeof(initfuncs[0]); i++)
70                 if (initfuncs[i])
71                         initfuncs[i]();
72 }
73
74 struct fw3_ipt_handle *
75 fw3_ipt_open(enum fw3_family family, enum fw3_table table)
76 {
77         struct fw3_ipt_handle *h;
78
79         h = fw3_alloc(sizeof(*h));
80
81         xtables_init();
82
83         if (family == FW3_FAMILY_V6)
84         {
85 #ifndef DISABLE_IPV6
86                 h->family = FW3_FAMILY_V6;
87                 h->table  = table;
88                 h->handle = ip6tc_init(fw3_flag_names[table]);
89
90                 xtables_set_params(&xtg6);
91                 xtables_set_nfproto(NFPROTO_IPV6);
92 #endif
93         }
94         else
95         {
96                 h->family = FW3_FAMILY_V4;
97                 h->table  = table;
98                 h->handle = iptc_init(fw3_flag_names[table]);
99
100                 xtables_set_params(&xtg);
101                 xtables_set_nfproto(NFPROTO_IPV4);
102         }
103
104         if (!h->handle)
105         {
106                 free(h);
107                 return NULL;
108         }
109
110         fw3_xt_reset();
111         fw3_init_extensions();
112
113         return h;
114 }
115
116 static void
117 debug(struct fw3_ipt_handle *h, const char *fmt, ...)
118 {
119         va_list ap;
120
121         printf("%s -t %s ", (h->family == FW3_FAMILY_V6) ? "ip6tables" : "iptables",
122                             fw3_flag_names[h->table]);
123
124         va_start(ap, fmt);
125         vprintf(fmt, ap);
126         va_end(ap);
127 }
128
129 void
130 fw3_ipt_set_policy(struct fw3_ipt_handle *h, const char *chain,
131                    enum fw3_flag policy)
132 {
133         if (fw3_pr_debug)
134                 debug(h, "-P %s %s\n", chain, fw3_flag_names[policy]);
135
136 #ifndef DISABLE_IPV6
137         if (h->family == FW3_FAMILY_V6)
138                 ip6tc_set_policy(chain, fw3_flag_names[policy], NULL, h->handle);
139         else
140 #endif
141                 iptc_set_policy(chain, fw3_flag_names[policy], NULL, h->handle);
142 }
143
144 void
145 fw3_ipt_flush_chain(struct fw3_ipt_handle *h, const char *chain)
146 {
147         if (fw3_pr_debug)
148                 debug(h, "-F %s\n", chain);
149
150 #ifndef DISABLE_IPV6
151         if (h->family == FW3_FAMILY_V6)
152                 ip6tc_flush_entries(chain, h->handle);
153         else
154 #endif
155                 iptc_flush_entries(chain, h->handle);
156 }
157
158 static void
159 delete_rules(struct fw3_ipt_handle *h, const char *target)
160 {
161         unsigned int num;
162         const struct ipt_entry *e;
163         const char *chain;
164         const char *t;
165         bool found;
166
167 #ifndef DISABLE_IPV6
168         if (h->family == FW3_FAMILY_V6)
169         {
170                 for (chain = ip6tc_first_chain(h->handle);
171                      chain != NULL;
172                      chain = ip6tc_next_chain(h->handle))
173                 {
174                         do {
175                                 found = false;
176
177                                 const struct ip6t_entry *e6;
178                                 for (num = 0, e6 = ip6tc_first_rule(chain, h->handle);
179                                          e6 != NULL;
180                                          num++, e6 = ip6tc_next_rule(e6, h->handle))
181                                 {
182                                         t = ip6tc_get_target(e6, h->handle);
183
184                                         if (*t && !strcmp(t, target))
185                                         {
186                                                 if (fw3_pr_debug)
187                                                         debug(h, "-D %s %u\n", chain, num + 1);
188
189                                                 ip6tc_delete_num_entry(chain, num, h->handle);
190                                                 found = true;
191                                                 break;
192                                         }
193                                 }
194                         } while (found);
195                 }
196         }
197         else
198 #endif
199         {
200                 for (chain = iptc_first_chain(h->handle);
201                      chain != NULL;
202                      chain = iptc_next_chain(h->handle))
203                 {
204                         do {
205                                 found = false;
206
207                                 for (num = 0, e = iptc_first_rule(chain, h->handle);
208                                      e != NULL;
209                                          num++, e = iptc_next_rule(e, h->handle))
210                                 {
211                                         t = iptc_get_target(e, h->handle);
212
213                                         if (*t && !strcmp(t, target))
214                                         {
215                                                 if (fw3_pr_debug)
216                                                         debug(h, "-D %s %u\n", chain, num + 1);
217
218                                                 iptc_delete_num_entry(chain, num, h->handle);
219                                                 found = true;
220                                                 break;
221                                         }
222                                 }
223                         } while (found);
224                 }
225         }
226 }
227
228 void
229 fw3_ipt_delete_chain(struct fw3_ipt_handle *h, const char *chain)
230 {
231         delete_rules(h, chain);
232
233         if (fw3_pr_debug)
234                 debug(h, "-X %s\n", chain);
235
236 #ifndef DISABLE_IPV6
237         if (h->family == FW3_FAMILY_V6)
238                 ip6tc_delete_chain(chain, h->handle);
239         else
240 #endif
241                 iptc_delete_chain(chain, h->handle);
242 }
243
244 void
245 fw3_ipt_create_chain(struct fw3_ipt_handle *h, const char *fmt, ...)
246 {
247         char buf[32];
248         va_list ap;
249
250         va_start(ap, fmt);
251         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
252         va_end(ap);
253
254         if (fw3_pr_debug)
255                 debug(h, "-N %s\n", buf);
256
257         iptc_create_chain(buf, h->handle);
258 }
259
260 void
261 fw3_ipt_flush(struct fw3_ipt_handle *h)
262 {
263         const char *chain;
264
265 #ifndef DISABLE_IPV6
266         if (h->family == FW3_FAMILY_V6)
267         {
268                 for (chain = ip6tc_first_chain(h->handle);
269                      chain != NULL;
270                      chain = ip6tc_next_chain(h->handle))
271                 {
272                         ip6tc_flush_entries(chain, h->handle);
273                 }
274
275                 for (chain = ip6tc_first_chain(h->handle);
276                      chain != NULL;
277                      chain = ip6tc_next_chain(h->handle))
278                 {
279                         ip6tc_delete_chain(chain, h->handle);
280                 }
281         }
282         else
283 #endif
284         {
285                 for (chain = iptc_first_chain(h->handle);
286                      chain != NULL;
287                      chain = iptc_next_chain(h->handle))
288                 {
289                         iptc_flush_entries(chain, h->handle);
290                 }
291
292                 for (chain = iptc_first_chain(h->handle);
293                      chain != NULL;
294                      chain = iptc_next_chain(h->handle))
295                 {
296                         iptc_delete_chain(chain, h->handle);
297                 }
298         }
299 }
300
301 void
302 fw3_ipt_commit(struct fw3_ipt_handle *h)
303 {
304         int rv;
305
306 #ifndef DISABLE_IPV6
307         if (h->family == FW3_FAMILY_V6)
308         {
309                 rv = ip6tc_commit(h->handle);
310                 if (!rv)
311                         warn("ip6tc_commit(): %s", ip6tc_strerror(errno));
312         }
313         else
314 #endif
315         {
316                 rv = iptc_commit(h->handle);
317                 if (!rv)
318                         warn("iptc_commit(): %s", iptc_strerror(errno));
319         }
320 }
321
322 void
323 fw3_ipt_close(struct fw3_ipt_handle *h)
324 {
325         if (h->libv)
326         {
327                 while (h->libc > 0)
328                 {
329                         h->libc--;
330                         dlclose(h->libv[h->libc]);
331                 }
332
333                 free(h->libv);
334         }
335
336         free(h);
337 }
338
339 struct fw3_ipt_rule *
340 fw3_ipt_rule_new(struct fw3_ipt_handle *h)
341 {
342         struct fw3_ipt_rule *r;
343
344         r = fw3_alloc(sizeof(*r));
345
346         r->h = h;
347         r->argv = fw3_alloc(sizeof(char *));
348         r->argv[r->argc++] = "fw3";
349
350         return r;
351 }
352
353
354 static bool
355 is_chain(struct fw3_ipt_handle *h, const char *name)
356 {
357 #ifndef DISABLE_IPV6
358         if (h->family == FW3_FAMILY_V6)
359                 return ip6tc_is_chain(name, h->handle);
360         else
361 #endif
362                 return iptc_is_chain(name, h->handle);
363 }
364
365 static char *
366 get_protoname(struct fw3_ipt_rule *r)
367 {
368         const struct xtables_pprot *pp;
369
370         if (r->protocol)
371                 for (pp = xtables_chain_protos; pp->name; pp++)
372                         if (pp->num == r->protocol)
373                                 return (char *)pp->name;
374
375         return NULL;
376 }
377
378 static bool
379 load_extension(struct fw3_ipt_handle *h, const char *name)
380 {
381         char path[256];
382         void *lib, **tmp;
383         const char *pfx = (h->family == FW3_FAMILY_V6) ? "libip6t" : "libipt";
384
385         snprintf(path, sizeof(path), "/usr/lib/iptables/libxt_%s.so", name);
386         if (!(lib = dlopen(path, RTLD_NOW)))
387         {
388                 snprintf(path, sizeof(path), "/usr/lib/iptables/%s_%s.so", pfx, name);
389                 lib = dlopen(path, RTLD_NOW);
390         }
391
392         if (!lib)
393                 return false;
394
395         tmp = realloc(h->libv, sizeof(lib) * (h->libc + 1));
396
397         if (!tmp)
398                 return false;
399
400         h->libv = tmp;
401         h->libv[h->libc++] = lib;
402
403         return true;
404 }
405
406 static struct xtables_match *
407 find_match(struct fw3_ipt_rule *r, const char *name)
408 {
409         struct xtables_match *m;
410
411         m = xtables_find_match(name, XTF_DONT_LOAD, &r->matches);
412
413         if (!m && load_extension(r->h, name))
414                 m = xtables_find_match(name, XTF_DONT_LOAD, &r->matches);
415
416         return m;
417 }
418
419 static void
420 init_match(struct fw3_ipt_rule *r, struct xtables_match *m, bool no_clone)
421 {
422         size_t s;
423         struct xtables_globals *g;
424
425         if (!m)
426                 return;
427
428         s = XT_ALIGN(sizeof(struct xt_entry_match)) + m->size;
429
430         m->m = fw3_alloc(s);
431
432         fw3_xt_set_match_name(m);
433
434         m->m->u.user.revision = m->revision;
435         m->m->u.match_size = s;
436
437         /* free previous userspace data */
438         fw3_xt_free_match_udata(m);
439
440         if (m->init)
441                 m->init(m->m);
442
443         /* don't merge options if no_clone is set and this match is a clone */
444         if (no_clone && (m == m->next))
445                 return;
446
447         /* merge option table */
448         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
449         fw3_xt_merge_match_options(g, m);
450 }
451
452 static bool
453 need_protomatch(struct fw3_ipt_rule *r, const char *pname)
454 {
455         if (!pname)
456                 return false;
457
458         if (!xtables_find_match(pname, XTF_DONT_LOAD, NULL))
459                 return true;
460
461         return !r->protocol_loaded;
462 }
463
464 static struct xtables_match *
465 load_protomatch(struct fw3_ipt_rule *r)
466 {
467         const char *pname = get_protoname(r);
468
469         if (!need_protomatch(r, pname))
470                 return NULL;
471
472         return find_match(r, pname);
473 }
474
475 static struct xtables_target *
476 find_target(struct fw3_ipt_rule *r, const char *name)
477 {
478         struct xtables_target *t;
479
480         if (is_chain(r->h, name))
481                 return xtables_find_target(XT_STANDARD_TARGET, XTF_LOAD_MUST_SUCCEED);
482
483         t = xtables_find_target(name, XTF_DONT_LOAD);
484
485         if (!t && load_extension(r->h, name))
486                 t = xtables_find_target(name, XTF_DONT_LOAD);
487
488         return t;
489 }
490
491 static struct xtables_target *
492 get_target(struct fw3_ipt_rule *r, const char *name)
493 {
494         size_t s;
495         struct xtables_target *t;
496         struct xtables_globals *g;
497
498         t = find_target(r, name);
499
500         if (!t)
501                 return NULL;
502
503         s = XT_ALIGN(sizeof(struct xt_entry_target)) + t->size;
504         t->t = fw3_alloc(s);
505
506         fw3_xt_set_target_name(t, name);
507
508         t->t->u.user.revision = t->revision;
509         t->t->u.target_size = s;
510
511         /* free previous userspace data */
512         fw3_xt_free_target_udata(t);
513
514         if (t->init)
515                 t->init(t->t);
516
517         /* merge option table */
518         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
519         fw3_xt_merge_target_options(g, t);
520
521         r->target = t;
522
523         return t;
524 }
525
526 void
527 fw3_ipt_rule_proto(struct fw3_ipt_rule *r, struct fw3_protocol *proto)
528 {
529         uint32_t pr;
530
531         if (!proto || proto->any)
532                 return;
533
534         pr = proto->protocol;
535
536 #ifndef DISABLE_IPV6
537         if (r->h->family == FW3_FAMILY_V6)
538         {
539                 if (pr == 1)
540                         pr = 58;
541
542                 r->e6.ipv6.proto = pr;
543                 r->e6.ipv6.flags |= IP6T_F_PROTO;
544
545                 if (proto->invert)
546                         r->e6.ipv6.invflags |= XT_INV_PROTO;
547         }
548         else
549 #endif
550         {
551                 r->e.ip.proto = pr;
552
553                 if (proto->invert)
554                         r->e.ip.invflags |= XT_INV_PROTO;
555         }
556
557         r->protocol = pr;
558 }
559
560 void
561 fw3_ipt_rule_in_out(struct fw3_ipt_rule *r,
562                     struct fw3_device *in, struct fw3_device *out)
563 {
564 #ifndef DISABLE_IPV6
565         if (r->h->family == FW3_FAMILY_V6)
566         {
567                 if (in && !in->any)
568                 {
569                         xtables_parse_interface(in->name, r->e6.ipv6.iniface,
570                                                           r->e6.ipv6.iniface_mask);
571
572                         if (in->invert)
573                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_IN;
574                 }
575
576                 if (out && !out->any)
577                 {
578                         xtables_parse_interface(out->name, r->e6.ipv6.outiface,
579                                                            r->e6.ipv6.outiface_mask);
580
581                         if (out->invert)
582                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_OUT;
583                 }
584         }
585         else
586 #endif
587         {
588                 if (in && !in->any)
589                 {
590                         xtables_parse_interface(in->name, r->e.ip.iniface,
591                                                           r->e.ip.iniface_mask);
592
593                         if (in->invert)
594                                 r->e.ip.invflags |= IPT_INV_VIA_IN;
595                 }
596
597                 if (out && !out->any)
598                 {
599                         xtables_parse_interface(out->name, r->e.ip.outiface,
600                                                            r->e.ip.outiface_mask);
601
602                         if (out->invert)
603                                 r->e.ip.invflags |= IPT_INV_VIA_OUT;
604                 }
605         }
606 }
607
608
609 void
610 fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
611                       struct fw3_address *src, struct fw3_address *dest)
612 {
613         if ((src && src->range) || (dest && dest->range))
614         {
615                 fw3_ipt_rule_addarg(r, false, "-m", "iprange");
616         }
617
618         if (src && src->set)
619         {
620                 if (src->range)
621                 {
622                         fw3_ipt_rule_addarg(r, src->invert, "--src-range",
623                                             fw3_address_to_string(src, false, false));
624                 }
625 #ifndef DISABLE_IPV6
626                 else if (r->h->family == FW3_FAMILY_V6)
627                 {
628                         r->e6.ipv6.src = src->address.v6;
629                         r->e6.ipv6.smsk = src->mask.v6;
630
631                         int i;
632                         for (i = 0; i < 4; i++)
633                                 r->e6.ipv6.src.s6_addr32[i] &= r->e6.ipv6.smsk.s6_addr32[i];
634
635                         if (src->invert)
636                                 r->e6.ipv6.invflags |= IP6T_INV_SRCIP;
637                 }
638 #endif
639                 else
640                 {
641                         r->e.ip.src = src->address.v4;
642                         r->e.ip.smsk = src->mask.v4;
643
644                         r->e.ip.src.s_addr &= r->e.ip.smsk.s_addr;
645
646                         if (src->invert)
647                                 r->e.ip.invflags |= IPT_INV_SRCIP;
648                 }
649         }
650
651         if (dest && dest->set)
652         {
653                 if (dest->range)
654                 {
655                         fw3_ipt_rule_addarg(r, dest->invert, "--dst-range",
656                                             fw3_address_to_string(dest, false, false));
657                 }
658 #ifndef DISABLE_IPV6
659                 else if (r->h->family == FW3_FAMILY_V6)
660                 {
661                         r->e6.ipv6.dst = dest->address.v6;
662                         r->e6.ipv6.dmsk = dest->mask.v6;
663
664                         int i;
665                         for (i = 0; i < 4; i++)
666                                 r->e6.ipv6.dst.s6_addr32[i] &= r->e6.ipv6.dmsk.s6_addr32[i];
667
668                         if (dest->invert)
669                                 r->e6.ipv6.invflags |= IP6T_INV_DSTIP;
670                 }
671 #endif
672                 else
673                 {
674                         r->e.ip.dst = dest->address.v4;
675                         r->e.ip.dmsk = dest->mask.v4;
676
677                         r->e.ip.dst.s_addr &= r->e.ip.dmsk.s_addr;
678
679                         if (dest->invert)
680                                 r->e.ip.invflags |= IPT_INV_DSTIP;
681                 }
682         }
683 }
684
685 void
686 fw3_ipt_rule_sport_dport(struct fw3_ipt_rule *r,
687                          struct fw3_port *sp, struct fw3_port *dp)
688 {
689         char buf[sizeof("65535:65535\0")];
690
691         if ((!sp || !sp->set) && (!dp || !dp->set))
692                 return;
693
694         if (!get_protoname(r))
695                 return;
696
697         if (sp && sp->set)
698         {
699                 if (sp->port_min == sp->port_max)
700                         sprintf(buf, "%u", sp->port_min);
701                 else
702                         sprintf(buf, "%u:%u", sp->port_min, sp->port_max);
703
704                 fw3_ipt_rule_addarg(r, sp->invert, "--sport", buf);
705         }
706
707         if (dp && dp->set)
708         {
709                 if (dp->port_min == dp->port_max)
710                         sprintf(buf, "%u", dp->port_min);
711                 else
712                         sprintf(buf, "%u:%u", dp->port_min, dp->port_max);
713
714                 fw3_ipt_rule_addarg(r, dp->invert, "--dport", buf);
715         }
716 }
717
718 void
719 fw3_ipt_rule_device(struct fw3_ipt_rule *r, const char *device, bool out)
720 {
721         if (device) {
722                 struct fw3_device dev = { .any = false };
723                 strncpy(dev.name, device, sizeof(dev.name) - 1);
724                 fw3_ipt_rule_in_out(r, (out) ? NULL : &dev, (out) ? &dev : NULL);
725         }
726 }
727
728 void
729 fw3_ipt_rule_mac(struct fw3_ipt_rule *r, struct fw3_mac *mac)
730 {
731         char buf[sizeof("ff:ff:ff:ff:ff:ff\0")];
732         uint8_t *addr = mac->mac.ether_addr_octet;
733
734         if (!mac)
735                 return;
736
737         sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
738                 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
739
740         fw3_ipt_rule_addarg(r, false, "-m", "mac");
741         fw3_ipt_rule_addarg(r, mac->invert, "--mac-source", buf);
742 }
743
744 void
745 fw3_ipt_rule_icmptype(struct fw3_ipt_rule *r, struct fw3_icmptype *icmp)
746 {
747         char buf[sizeof("255/255\0")];
748
749         if (!icmp)
750                 return;
751
752 #ifndef DISABLE_IPV6
753         if (r->h->family == FW3_FAMILY_V6)
754         {
755                 if (icmp->code6_min == 0 && icmp->code6_max == 0xFF)
756                         sprintf(buf, "%u", icmp->type6);
757                 else
758                         sprintf(buf, "%u/%u", icmp->type6, icmp->code6_min);
759
760                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmpv6-type", buf);
761         }
762         else
763 #endif
764         {
765                 if (icmp->code_min == 0 && icmp->code_max == 0xFF)
766                         sprintf(buf, "%u", icmp->type);
767                 else
768                         sprintf(buf, "%u/%u", icmp->type, icmp->code_min);
769
770                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmp-type", buf);
771         }
772 }
773
774 void
775 fw3_ipt_rule_limit(struct fw3_ipt_rule *r, struct fw3_limit *limit)
776 {
777         char buf[sizeof("-4294967296/second\0")];
778
779         if (!limit || limit->rate <= 0)
780                 return;
781
782         fw3_ipt_rule_addarg(r, false, "-m", "limit");
783
784         sprintf(buf, "%u/%s", limit->rate, fw3_limit_units[limit->unit]);
785         fw3_ipt_rule_addarg(r, limit->invert, "--limit", buf);
786
787         if (limit->burst > 0)
788         {
789                 sprintf(buf, "%u", limit->burst);
790                 fw3_ipt_rule_addarg(r, limit->invert, "--limit-burst", buf);
791         }
792 }
793
794 void
795 fw3_ipt_rule_ipset(struct fw3_ipt_rule *r, struct fw3_setmatch *match)
796 {
797         char buf[sizeof("dst,dst,dst\0")];
798         char *p = buf;
799         int i = 0;
800
801         struct fw3_ipset *set;
802         struct fw3_ipset_datatype *type;
803
804         if (!match || !match->set || !match->ptr)
805                 return;
806
807         set = match->ptr;
808         list_for_each_entry(type, &set->datatypes, list)
809         {
810                 if (i >= 3)
811                         break;
812
813                 if (p > buf)
814                         *p++ = ',';
815
816                 p += sprintf(p, "%s", match->dir[i] ? match->dir[i] : type->dir);
817                 i++;
818         }
819
820         fw3_ipt_rule_addarg(r, false, "-m", "set");
821
822         fw3_ipt_rule_addarg(r, match->invert, "--match-set",
823                             set->external ? set->external : set->name);
824
825         fw3_ipt_rule_addarg(r, false, buf, NULL);
826 }
827
828 void
829 fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
830 {
831         int i;
832         struct tm empty = { 0 };
833
834         char buf[84]; /* sizeof("1,2,3,...,30,31\0") */
835         char *p;
836
837         bool d1 = memcmp(&time->datestart, &empty, sizeof(empty));
838         bool d2 = memcmp(&time->datestop, &empty, sizeof(empty));
839
840         if (!d1 && !d2 && !time->timestart && !time->timestop &&
841             !(time->monthdays & 0xFFFFFFFE) && !(time->weekdays & 0xFE))
842         {
843                 return;
844         }
845
846         fw3_ipt_rule_addarg(r, false, "-m", "time");
847
848         if (time->utc)
849                 fw3_ipt_rule_addarg(r, false, "--utc", NULL);
850
851         if (d1)
852         {
853                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestart);
854                 fw3_ipt_rule_addarg(r, false, "--datestart", buf);
855         }
856
857         if (d2)
858         {
859                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestop);
860                 fw3_ipt_rule_addarg(r, false, "--datestop", buf);
861         }
862
863         if (time->timestart)
864         {
865                 sprintf(buf, "%02d:%02d:%02d",
866                         time->timestart / 3600,
867                         time->timestart % 3600 / 60,
868                         time->timestart % 60);
869
870                 fw3_ipt_rule_addarg(r, false, "--timestart", buf);
871         }
872
873         if (time->timestop)
874         {
875                 sprintf(buf, "%02d:%02d:%02d",
876                         time->timestop / 3600,
877                         time->timestop % 3600 / 60,
878                         time->timestop % 60);
879
880                 fw3_ipt_rule_addarg(r, false, "--timestop", buf);
881         }
882
883         if (time->monthdays & 0xFFFFFFFE)
884         {
885                 for (i = 1, p = buf; i < 32; i++)
886                 {
887                         if (hasbit(time->monthdays, i))
888                         {
889                                 if (p > buf)
890                                         *p++ = ',';
891
892                                 p += sprintf(p, "%u", i);
893                         }
894                 }
895
896                 fw3_ipt_rule_addarg(r, hasbit(time->monthdays, 0), "--monthdays", buf);
897         }
898
899         if (time->weekdays & 0xFE)
900         {
901                 for (i = 1, p = buf; i < 8; i++)
902                 {
903                         if (hasbit(time->weekdays, i))
904                         {
905                                 if (p > buf)
906                                         *p++ = ',';
907
908                                 p += sprintf(p, "%u", i);
909                         }
910                 }
911
912                 fw3_ipt_rule_addarg(r, hasbit(time->weekdays, 0), "--weekdays", buf);
913         }
914 }
915
916 void
917 fw3_ipt_rule_mark(struct fw3_ipt_rule *r, struct fw3_mark *mark)
918 {
919         char buf[sizeof("0xFFFFFFFF/0xFFFFFFFF\0")];
920
921         if (!mark || !mark->set)
922                 return;
923
924         if (mark->mask < 0xFFFFFFFF)
925                 sprintf(buf, "0x%x/0x%x", mark->mark, mark->mask);
926         else
927                 sprintf(buf, "0x%x", mark->mark);
928
929         fw3_ipt_rule_addarg(r, false, "-m", "mark");
930         fw3_ipt_rule_addarg(r, mark->invert, "--mark", buf);
931 }
932
933 void
934 fw3_ipt_rule_comment(struct fw3_ipt_rule *r, const char *fmt, ...)
935 {
936         va_list ap;
937         char buf[256];
938
939         if (!fmt || !*fmt)
940                 return;
941
942         va_start(ap, fmt);
943         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
944         va_end(ap);
945
946         fw3_ipt_rule_addarg(r, false, "-m", "comment");
947         fw3_ipt_rule_addarg(r, false, "--comment", buf);
948 }
949
950 void
951 fw3_ipt_rule_extra(struct fw3_ipt_rule *r, const char *extra)
952 {
953         char *p, **tmp, *s;
954
955         if (!extra || !*extra)
956                 return;
957
958         s = fw3_strdup(extra);
959
960         for (p = strtok(s, " \t"); p; p = strtok(NULL, " \t"))
961         {
962                 tmp = realloc(r->argv, (r->argc + 1) * sizeof(*r->argv));
963
964                 if (!tmp)
965                         break;
966
967                 r->argv = tmp;
968                 r->argv[r->argc++] = fw3_strdup(p);
969         }
970
971         free(s);
972 }
973
974 #ifndef DISABLE_IPV6
975 static void
976 rule_print6(struct ip6t_entry *e)
977 {
978         char buf1[INET6_ADDRSTRLEN], buf2[INET6_ADDRSTRLEN];
979         char *pname;
980
981         if (e->ipv6.flags & IP6T_F_PROTO)
982         {
983                 if (e->ipv6.flags & XT_INV_PROTO)
984                         printf(" !");
985
986                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e6));
987
988                 if (pname)
989                         printf(" -p %s", pname);
990                 else
991                         printf(" -p %u", e->ipv6.proto);
992         }
993
994         if (e->ipv6.iniface[0])
995         {
996                 if (e->ipv6.flags & IP6T_INV_VIA_IN)
997                         printf(" !");
998
999                 printf(" -i %s", e->ipv6.iniface);
1000         }
1001
1002         if (e->ipv6.outiface[0])
1003         {
1004                 if (e->ipv6.flags & IP6T_INV_VIA_OUT)
1005                         printf(" !");
1006
1007                 printf(" -o %s", e->ipv6.outiface);
1008         }
1009
1010         if (memcmp(&e->ipv6.src, &in6addr_any, sizeof(struct in6_addr)))
1011         {
1012                 if (e->ipv6.flags & IP6T_INV_SRCIP)
1013                         printf(" !");
1014
1015                 printf(" -s %s/%s",
1016                        inet_ntop(AF_INET6, &e->ipv6.src, buf1, sizeof(buf1)),
1017                        inet_ntop(AF_INET6, &e->ipv6.smsk, buf2, sizeof(buf2)));
1018         }
1019
1020         if (memcmp(&e->ipv6.dst, &in6addr_any, sizeof(struct in6_addr)))
1021         {
1022                 if (e->ipv6.flags & IP6T_INV_DSTIP)
1023                         printf(" !");
1024
1025                 printf(" -d %s/%s",
1026                        inet_ntop(AF_INET6, &e->ipv6.dst, buf1, sizeof(buf1)),
1027                        inet_ntop(AF_INET6, &e->ipv6.dmsk, buf2, sizeof(buf2)));
1028         }
1029 }
1030 #endif
1031
1032 static void
1033 rule_print4(struct ipt_entry *e)
1034 {
1035         struct in_addr in_zero = { 0 };
1036         char buf1[sizeof("255.255.255.255\0")], buf2[sizeof("255.255.255.255\0")];
1037         char *pname;
1038
1039         if (e->ip.proto)
1040         {
1041                 if (e->ip.flags & XT_INV_PROTO)
1042                         printf(" !");
1043
1044                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e));
1045
1046                 if (pname)
1047                         printf(" -p %s", pname);
1048                 else
1049                         printf(" -p %u", e->ip.proto);
1050         }
1051
1052         if (e->ip.iniface[0])
1053         {
1054                 if (e->ip.flags & IPT_INV_VIA_IN)
1055                         printf(" !");
1056
1057                 printf(" -i %s", e->ip.iniface);
1058         }
1059
1060         if (e->ip.outiface[0])
1061         {
1062                 if (e->ip.flags & IPT_INV_VIA_OUT)
1063                         printf(" !");
1064
1065                 printf(" -o %s", e->ip.outiface);
1066         }
1067
1068         if (memcmp(&e->ip.src, &in_zero, sizeof(struct in_addr)))
1069         {
1070                 if (e->ip.flags & IPT_INV_SRCIP)
1071                         printf(" !");
1072
1073                 printf(" -s %s/%s",
1074                        inet_ntop(AF_INET, &e->ip.src, buf1, sizeof(buf1)),
1075                        inet_ntop(AF_INET, &e->ip.smsk, buf2, sizeof(buf2)));
1076         }
1077
1078         if (memcmp(&e->ip.dst, &in_zero, sizeof(struct in_addr)))
1079         {
1080                 if (e->ip.flags & IPT_INV_DSTIP)
1081                         printf(" !");
1082
1083                 printf(" -d %s/%s",
1084                        inet_ntop(AF_INET, &e->ip.dst, buf1, sizeof(buf1)),
1085                        inet_ntop(AF_INET, &e->ip.dmsk, buf2, sizeof(buf2)));
1086         }
1087 }
1088
1089 static void
1090 rule_print(struct fw3_ipt_rule *r, const char *prefix, const char *chain)
1091 {
1092         debug(r->h, "%s %s", prefix, chain);
1093
1094 #ifndef DISABLE_IPV6
1095         if (r->h->family == FW3_FAMILY_V6)
1096                 rule_print6(&r->e6);
1097         else
1098 #endif
1099                 rule_print4(&r->e);
1100
1101         fw3_xt_print_matches(&r->e.ip, r->matches);
1102         fw3_xt_print_target(&r->e.ip, r->target);
1103
1104         printf("\n");
1105 }
1106
1107 static bool
1108 parse_option(struct fw3_ipt_rule *r, int optc, bool inv)
1109 {
1110         struct xtables_rule_match *m;
1111         struct xtables_match *em;
1112
1113         /* is a target option */
1114         if (r->target && fw3_xt_has_target_parse(r->target) &&
1115                 optc >= r->target->option_offset &&
1116                 optc < (r->target->option_offset + 256))
1117         {
1118                 xtables_option_tpcall(optc, r->argv, inv, r->target, &r->e);
1119                 return false;
1120         }
1121
1122         /* try to dispatch argument to one of the match parsers */
1123         for (m = r->matches; m; m = m->next)
1124         {
1125                 em = m->match;
1126
1127                 if (m->completed || !fw3_xt_has_match_parse(em))
1128                         continue;
1129
1130                 if (optc < em->option_offset ||
1131                         optc >= (em->option_offset + 256))
1132                         continue;
1133
1134                 xtables_option_mpcall(optc, r->argv, inv, em, &r->e);
1135                 return false;
1136         }
1137
1138         /* unhandled option, might belong to a protocol match */
1139         if ((em = load_protomatch(r)) != NULL)
1140         {
1141                 init_match(r, em, false);
1142
1143                 r->protocol_loaded = true;
1144                 optind--;
1145
1146                 return true;
1147         }
1148
1149         if (optc == ':')
1150                 warn("parse_option(): option '%s' needs argument", r->argv[optind-1]);
1151
1152         if (optc == '?')
1153                 warn("parse_option(): unknown option '%s'", r->argv[optind-1]);
1154
1155         return false;
1156 }
1157
1158 void
1159 fw3_ipt_rule_addarg(struct fw3_ipt_rule *r, bool inv,
1160                     const char *k, const char *v)
1161 {
1162         int n;
1163         char **tmp;
1164
1165         if (!k)
1166                 return;
1167
1168         n = inv + !!k + !!v;
1169         tmp = realloc(r->argv, (r->argc + n) * sizeof(*tmp));
1170
1171         if (!tmp)
1172                 return;
1173
1174         r->argv = tmp;
1175
1176         if (inv)
1177                 r->argv[r->argc++] = fw3_strdup("!");
1178
1179         r->argv[r->argc++] = fw3_strdup(k);
1180
1181         if (v)
1182                 r->argv[r->argc++] = fw3_strdup(v);
1183 }
1184
1185 static unsigned char *
1186 rule_mask(struct fw3_ipt_rule *r)
1187 {
1188         size_t s;
1189         unsigned char *p, *mask = NULL;
1190         struct xtables_rule_match *m;
1191
1192 #define SZ(x) XT_ALIGN(sizeof(struct x))
1193
1194 #ifndef DISABLE_IPV6
1195         if (r->h->family == FW3_FAMILY_V6)
1196         {
1197                 s = SZ(ip6t_entry);
1198
1199                 for (m = r->matches; m; m = m->next)
1200                         s += SZ(ip6t_entry_match) + m->match->size;
1201
1202                 s += SZ(ip6t_entry_target) + r->target->size;
1203
1204                 mask = fw3_alloc(s);
1205                 memset(mask, 0xFF, SZ(ip6t_entry));
1206                 p = mask + SZ(ip6t_entry);
1207
1208                 for (m = r->matches; m; m = m->next)
1209                 {
1210                         memset(p, 0xFF, SZ(ip6t_entry_match) + m->match->userspacesize);
1211                         p += SZ(ip6t_entry_match) + m->match->size;
1212                 }
1213
1214                 memset(p, 0xFF, SZ(ip6t_entry_target) + r->target->userspacesize);
1215         }
1216         else
1217 #endif
1218         {
1219                 s = SZ(ipt_entry);
1220
1221                 for (m = r->matches; m; m = m->next)
1222                         s += SZ(ipt_entry_match) + m->match->size;
1223
1224                 s += SZ(ipt_entry_target) + r->target->size;
1225
1226                 mask = fw3_alloc(s);
1227                 memset(mask, 0xFF, SZ(ipt_entry));
1228                 p = mask + SZ(ipt_entry);
1229
1230                 for (m = r->matches; m; m = m->next)
1231                 {
1232                         memset(p, 0xFF, SZ(ipt_entry_match) + m->match->userspacesize);
1233                         p += SZ(ipt_entry_match) + m->match->size;
1234                 }
1235
1236                 memset(p, 0xFF, SZ(ipt_entry_target) + r->target->userspacesize);
1237         }
1238
1239         return mask;
1240 }
1241
1242 static void *
1243 rule_build(struct fw3_ipt_rule *r)
1244 {
1245         size_t s;
1246         struct xtables_rule_match *m;
1247
1248 #ifndef DISABLE_IPV6
1249         if (r->h->family == FW3_FAMILY_V6)
1250         {
1251                 struct ip6t_entry *e6;
1252
1253                 s = XT_ALIGN(sizeof(struct ip6t_entry));
1254
1255                 for (m = r->matches; m; m = m->next)
1256                         s += m->match->m->u.match_size;
1257
1258                 e6 = fw3_alloc(s + r->target->t->u.target_size);
1259
1260                 memcpy(e6, &r->e6, sizeof(struct ip6t_entry));
1261
1262                 e6->target_offset = s;
1263                 e6->next_offset = s + r->target->t->u.target_size;
1264
1265                 s = 0;
1266
1267                 for (m = r->matches; m; m = m->next)
1268                 {
1269                         memcpy(e6->elems + s, m->match->m, m->match->m->u.match_size);
1270                         s += m->match->m->u.match_size;
1271                 }
1272
1273                 memcpy(e6->elems + s, r->target->t, r->target->t->u.target_size);
1274
1275                 return e6;
1276         }
1277         else
1278 #endif
1279         {
1280                 struct ipt_entry *e;
1281
1282                 s = XT_ALIGN(sizeof(struct ipt_entry));
1283
1284                 for (m = r->matches; m; m = m->next)
1285                         s += m->match->m->u.match_size;
1286
1287                 e = fw3_alloc(s + r->target->t->u.target_size);
1288
1289                 memcpy(e, &r->e, sizeof(struct ipt_entry));
1290
1291                 e->target_offset = s;
1292                 e->next_offset = s + r->target->t->u.target_size;
1293
1294                 s = 0;
1295
1296                 for (m = r->matches; m; m = m->next)
1297                 {
1298                         memcpy(e->elems + s, m->match->m, m->match->m->u.match_size);
1299                         s += m->match->m->u.match_size;
1300                 }
1301
1302                 memcpy(e->elems + s, r->target->t, r->target->t->u.target_size);
1303
1304                 return e;
1305         }
1306 }
1307
1308 void
1309 __fw3_ipt_rule_append(struct fw3_ipt_rule *r, bool repl, const char *fmt, ...)
1310 {
1311         void *rule;
1312         unsigned char *mask;
1313
1314         struct xtables_rule_match *m;
1315         struct xtables_match *em;
1316         struct xtables_target *et;
1317         struct xtables_globals *g;
1318
1319         int i, optc;
1320         bool inv = false;
1321         char buf[32];
1322         va_list ap;
1323
1324         va_start(ap, fmt);
1325         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
1326         va_end(ap);
1327
1328         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
1329         g->opts = g->orig_opts;
1330
1331         optind = 0;
1332         opterr = 0;
1333
1334         while ((optc = getopt_long(r->argc, r->argv, "-:m:j:", g->opts,
1335                                    NULL)) != -1)
1336         {
1337                 switch (optc)
1338                 {
1339                 case 'm':
1340                         em = find_match(r, optarg);
1341
1342                         if (!em)
1343                         {
1344                                 warn("fw3_ipt_rule_append(): Can't find match '%s'", optarg);
1345                                 goto free;
1346                         }
1347
1348                         init_match(r, em, true);
1349                         break;
1350
1351                 case 'j':
1352                         et = get_target(r, optarg);
1353
1354                         if (!et)
1355                         {
1356                                 warn("fw3_ipt_rule_append(): Can't find target '%s'", optarg);
1357                                 goto free;
1358                         }
1359
1360                         break;
1361
1362                 case 1:
1363                         if ((optarg[0] == '!') && (optarg[1] == '\0'))
1364                         {
1365                                 optarg[0] = '\0';
1366                                 inv = true;
1367                                 continue;
1368                         }
1369
1370                         warn("fw3_ipt_rule_append(): Bad argument '%s'", optarg);
1371                         goto free;
1372
1373                 default:
1374                         if (parse_option(r, optc, inv))
1375                                 continue;
1376                         break;
1377                 }
1378
1379                 inv = false;
1380         }
1381
1382         for (m = r->matches; m; m = m->next)
1383                 xtables_option_mfcall(m->match);
1384
1385         if (r->target)
1386                 xtables_option_tfcall(r->target);
1387
1388         rule = rule_build(r);
1389
1390 #ifndef DISABLE_IPV6
1391         if (r->h->family == FW3_FAMILY_V6)
1392         {
1393                 if (repl)
1394                 {
1395                         mask = rule_mask(r);
1396
1397                         while (ip6tc_delete_entry(buf, rule, mask, r->h->handle))
1398                                 if (fw3_pr_debug)
1399                                         rule_print(r, "-D", buf);
1400
1401                         free(mask);
1402                 }
1403
1404                 if (fw3_pr_debug)
1405                         rule_print(r, "-A", buf);
1406
1407                 if (!ip6tc_append_entry(buf, rule, r->h->handle))
1408                         warn("ip6tc_append_entry(): %s", ip6tc_strerror(errno));
1409         }
1410         else
1411 #endif
1412         {
1413                 if (repl)
1414                 {
1415                         mask = rule_mask(r);
1416
1417                         while (iptc_delete_entry(buf, rule, mask, r->h->handle))
1418                                 if (fw3_pr_debug)
1419                                         rule_print(r, "-D", buf);
1420
1421                         free(mask);
1422                 }
1423
1424                 if (fw3_pr_debug)
1425                         rule_print(r, "-A", buf);
1426
1427                 if (!iptc_append_entry(buf, rule, r->h->handle))
1428                         warn("iptc_append_entry(): %s\n", iptc_strerror(errno));
1429         }
1430
1431         free(rule);
1432
1433 free:
1434         for (i = 1; i < r->argc; i++)
1435                 free(r->argv[i]);
1436
1437         free(r->argv);
1438
1439         xtables_rule_matches_free(&r->matches);
1440
1441         if (r->target)
1442                 free(r->target->t);
1443
1444         free(r);
1445
1446         /* reset all targets and matches */
1447         for (em = xtables_matches; em; em = em->next)
1448                 em->mflags = 0;
1449
1450         for (et = xtables_targets; et; et = et->next)
1451         {
1452                 et->tflags = 0;
1453                 et->used = 0;
1454         }
1455
1456         xtables_free_opts(1);
1457 }
1458
1459 struct fw3_ipt_rule *
1460 fw3_ipt_rule_create(struct fw3_ipt_handle *handle, struct fw3_protocol *proto,
1461                     struct fw3_device *in, struct fw3_device *out,
1462                     struct fw3_address *src, struct fw3_address *dest)
1463 {
1464         struct fw3_ipt_rule *r;
1465
1466         r = fw3_ipt_rule_new(handle);
1467
1468         fw3_ipt_rule_proto(r, proto);
1469         fw3_ipt_rule_in_out(r, in, out);
1470         fw3_ipt_rule_src_dest(r, src, dest);
1471
1472         return r;
1473 }