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