Use zone_name_src_ACTION chain for input rules with non-wildcard source
[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
316 void
317 fw3_ipt_close(struct fw3_ipt_handle *h)
318 {
319         if (h->libv)
320         {
321                 while (h->libc > 0)
322                 {
323                         h->libc--;
324                         dlclose(h->libv[h->libc]);
325                 }
326
327                 free(h->libv);
328         }
329
330         free(h);
331 }
332
333 struct fw3_ipt_rule *
334 fw3_ipt_rule_new(struct fw3_ipt_handle *h)
335 {
336         struct fw3_ipt_rule *r;
337
338         r = fw3_alloc(sizeof(*r));
339
340         r->h = h;
341         r->argv = fw3_alloc(sizeof(char *));
342         r->argv[r->argc++] = "fw3";
343
344         return r;
345 }
346
347
348 static bool
349 is_chain(struct fw3_ipt_handle *h, const char *name)
350 {
351 #ifndef DISABLE_IPV6
352         if (h->family == FW3_FAMILY_V6)
353                 return ip6tc_is_chain(name, h->handle);
354         else
355 #endif
356                 return iptc_is_chain(name, h->handle);
357 }
358
359 static char *
360 get_protoname(struct fw3_ipt_rule *r)
361 {
362         const struct xtables_pprot *pp;
363
364         if (r->protocol)
365                 for (pp = xtables_chain_protos; pp->name; pp++)
366                         if (pp->num == r->protocol)
367                                 return (char *)pp->name;
368
369         return NULL;
370 }
371
372 static bool
373 load_extension(struct fw3_ipt_handle *h, const char *name)
374 {
375         char path[256];
376         void *lib, **tmp;
377         const char *pfx = (h->family == FW3_FAMILY_V6) ? "libip6t" : "libipt";
378
379         snprintf(path, sizeof(path), "/usr/lib/iptables/libxt_%s.so", name);
380         if (!(lib = dlopen(path, RTLD_NOW)))
381         {
382                 snprintf(path, sizeof(path), "/usr/lib/iptables/%s_%s.so", pfx, name);
383                 lib = dlopen(path, RTLD_NOW);
384         }
385
386         if (!lib)
387                 return false;
388
389         tmp = realloc(h->libv, sizeof(lib) * (h->libc + 1));
390
391         if (!tmp)
392                 return false;
393
394         h->libv = tmp;
395         h->libv[h->libc++] = lib;
396
397         return true;
398 }
399
400 static struct xtables_match *
401 find_match(struct fw3_ipt_rule *r, const char *name)
402 {
403         struct xtables_match *m;
404
405         m = xtables_find_match(name, XTF_DONT_LOAD, &r->matches);
406
407         if (!m && load_extension(r->h, name))
408                 m = xtables_find_match(name, XTF_DONT_LOAD, &r->matches);
409
410         return m;
411 }
412
413 static void
414 init_match(struct fw3_ipt_rule *r, struct xtables_match *m, bool no_clone)
415 {
416         size_t s;
417         struct xtables_globals *g;
418
419         if (!m)
420                 return;
421
422         s = XT_ALIGN(sizeof(struct xt_entry_match)) + m->size;
423
424         m->m = fw3_alloc(s);
425
426         fw3_xt_set_match_name(m);
427
428         m->m->u.user.revision = m->revision;
429         m->m->u.match_size = s;
430
431         /* free previous userspace data */
432         fw3_xt_free_match_udata(m);
433
434         if (m->init)
435                 m->init(m->m);
436
437         /* don't merge options if no_clone is set and this match is a clone */
438         if (no_clone && (m == m->next))
439                 return;
440
441         /* merge option table */
442         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
443         fw3_xt_merge_match_options(g, m);
444 }
445
446 static bool
447 need_protomatch(struct fw3_ipt_rule *r, const char *pname)
448 {
449         if (!pname)
450                 return false;
451
452         if (!xtables_find_match(pname, XTF_DONT_LOAD, NULL))
453                 return true;
454
455         return !r->protocol_loaded;
456 }
457
458 static struct xtables_match *
459 load_protomatch(struct fw3_ipt_rule *r)
460 {
461         const char *pname = get_protoname(r);
462
463         if (!need_protomatch(r, pname))
464                 return NULL;
465
466         return find_match(r, pname);
467 }
468
469 static struct xtables_target *
470 find_target(struct fw3_ipt_rule *r, const char *name)
471 {
472         struct xtables_target *t;
473
474         if (is_chain(r->h, name))
475                 return xtables_find_target(XT_STANDARD_TARGET, XTF_LOAD_MUST_SUCCEED);
476
477         t = xtables_find_target(name, XTF_DONT_LOAD);
478
479         if (!t && load_extension(r->h, name))
480                 t = xtables_find_target(name, XTF_DONT_LOAD);
481
482         return t;
483 }
484
485 static struct xtables_target *
486 get_target(struct fw3_ipt_rule *r, const char *name)
487 {
488         size_t s;
489         struct xtables_target *t;
490         struct xtables_globals *g;
491
492         t = find_target(r, name);
493
494         if (!t)
495                 return NULL;
496
497         s = XT_ALIGN(sizeof(struct xt_entry_target)) + t->size;
498         t->t = fw3_alloc(s);
499
500         fw3_xt_set_target_name(t, name);
501
502         t->t->u.user.revision = t->revision;
503         t->t->u.target_size = s;
504
505         /* free previous userspace data */
506         fw3_xt_free_target_udata(t);
507
508         if (t->init)
509                 t->init(t->t);
510
511         /* merge option table */
512         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
513         fw3_xt_merge_target_options(g, t);
514
515         r->target = t;
516
517         return t;
518 }
519
520 void
521 fw3_ipt_rule_proto(struct fw3_ipt_rule *r, struct fw3_protocol *proto)
522 {
523         uint32_t pr;
524
525         if (!proto || proto->any)
526                 return;
527
528         pr = proto->protocol;
529
530 #ifndef DISABLE_IPV6
531         if (r->h->family == FW3_FAMILY_V6)
532         {
533                 if (pr == 1)
534                         pr = 58;
535
536                 r->e6.ipv6.proto = pr;
537                 r->e6.ipv6.flags |= IP6T_F_PROTO;
538
539                 if (proto->invert)
540                         r->e6.ipv6.invflags |= XT_INV_PROTO;
541         }
542         else
543 #endif
544         {
545                 r->e.ip.proto = pr;
546
547                 if (proto->invert)
548                         r->e.ip.invflags |= XT_INV_PROTO;
549         }
550
551         r->protocol = pr;
552 }
553
554 void
555 fw3_ipt_rule_in_out(struct fw3_ipt_rule *r,
556                     struct fw3_device *in, struct fw3_device *out)
557 {
558 #ifndef DISABLE_IPV6
559         if (r->h->family == FW3_FAMILY_V6)
560         {
561                 if (in && !in->any)
562                 {
563                         xtables_parse_interface(in->name, r->e6.ipv6.iniface,
564                                                           r->e6.ipv6.iniface_mask);
565
566                         if (in->invert)
567                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_IN;
568                 }
569
570                 if (out && !out->any)
571                 {
572                         xtables_parse_interface(out->name, r->e6.ipv6.outiface,
573                                                            r->e6.ipv6.outiface_mask);
574
575                         if (out->invert)
576                                 r->e6.ipv6.invflags |= IP6T_INV_VIA_OUT;
577                 }
578         }
579         else
580 #endif
581         {
582                 if (in && !in->any)
583                 {
584                         xtables_parse_interface(in->name, r->e.ip.iniface,
585                                                           r->e.ip.iniface_mask);
586
587                         if (in->invert)
588                                 r->e.ip.invflags |= IPT_INV_VIA_IN;
589                 }
590
591                 if (out && !out->any)
592                 {
593                         xtables_parse_interface(out->name, r->e.ip.outiface,
594                                                            r->e.ip.outiface_mask);
595
596                         if (out->invert)
597                                 r->e.ip.invflags |= IPT_INV_VIA_OUT;
598                 }
599         }
600 }
601
602
603 static void
604 ip4prefix2mask(int prefix, struct in_addr *mask)
605 {
606         mask->s_addr = htonl(~((1 << (32 - prefix)) - 1));
607 }
608
609 #ifndef DISABLE_IPV6
610 static void
611 ip6prefix2mask(int prefix, struct in6_addr *mask)
612 {
613         char *p = (char *)mask;
614
615         if (prefix > 0)
616         {
617                 memset(p, 0xff, prefix / 8);
618                 memset(p + (prefix / 8) + 1, 0, (128 - prefix) / 8);
619                 p[prefix / 8] = 0xff << (8 - (prefix & 7));
620         }
621         else
622         {
623                 memset(mask, 0, sizeof(*mask));
624         }
625 }
626 #endif
627
628 void
629 fw3_ipt_rule_src_dest(struct fw3_ipt_rule *r,
630                       struct fw3_address *src, struct fw3_address *dest)
631 {
632         if ((src && src->range) || (dest && dest->range))
633         {
634                 fw3_ipt_rule_addarg(r, false, "-m", "iprange");
635         }
636
637         if (src && src->set)
638         {
639                 if (src->range)
640                 {
641                         fw3_ipt_rule_addarg(r, src->invert, "--src-range",
642                                             fw3_address_to_string(src, false));
643                 }
644 #ifndef DISABLE_IPV6
645                 else if (r->h->family == FW3_FAMILY_V6)
646                 {
647                         r->e6.ipv6.src = src->address.v6;
648                         ip6prefix2mask(src->mask, &r->e6.ipv6.smsk);
649
650                         int i;
651                         for (i = 0; i < 4; i++)
652                                 r->e6.ipv6.src.s6_addr32[i] &= r->e6.ipv6.smsk.s6_addr32[i];
653
654                         if (src->invert)
655                                 r->e6.ipv6.invflags |= IP6T_INV_SRCIP;
656                 }
657 #endif
658                 else
659                 {
660                         r->e.ip.src = src->address.v4;
661                         ip4prefix2mask(src->mask, &r->e.ip.smsk);
662
663                         r->e.ip.src.s_addr &= r->e.ip.smsk.s_addr;
664
665                         if (src->invert)
666                                 r->e.ip.invflags |= IPT_INV_SRCIP;
667                 }
668         }
669
670         if (dest && dest->set)
671         {
672                 if (dest->range)
673                 {
674                         fw3_ipt_rule_addarg(r, dest->invert, "--dst-range",
675                                             fw3_address_to_string(dest, false));
676                 }
677 #ifndef DISABLE_IPV6
678                 else if (r->h->family == FW3_FAMILY_V6)
679                 {
680                         r->e6.ipv6.dst = dest->address.v6;
681                         ip6prefix2mask(dest->mask, &r->e6.ipv6.dmsk);
682
683                         int i;
684                         for (i = 0; i < 4; i++)
685                                 r->e6.ipv6.dst.s6_addr32[i] &= r->e6.ipv6.dmsk.s6_addr32[i];
686
687                         if (dest->invert)
688                                 r->e6.ipv6.invflags |= IP6T_INV_DSTIP;
689                 }
690 #endif
691                 else
692                 {
693                         r->e.ip.dst = dest->address.v4;
694                         ip4prefix2mask(dest->mask, &r->e.ip.dmsk);
695
696                         r->e.ip.dst.s_addr &= r->e.ip.dmsk.s_addr;
697
698                         if (dest->invert)
699                                 r->e.ip.invflags |= IPT_INV_DSTIP;
700                 }
701         }
702 }
703
704 void
705 fw3_ipt_rule_sport_dport(struct fw3_ipt_rule *r,
706                          struct fw3_port *sp, struct fw3_port *dp)
707 {
708         char buf[sizeof("65535:65535\0")];
709
710         if ((!sp || !sp->set) && (!dp || !dp->set))
711                 return;
712
713         if (!get_protoname(r))
714                 return;
715
716         if (sp && sp->set)
717         {
718                 if (sp->port_min == sp->port_max)
719                         sprintf(buf, "%u", sp->port_min);
720                 else
721                         sprintf(buf, "%u:%u", sp->port_min, sp->port_max);
722
723                 fw3_ipt_rule_addarg(r, sp->invert, "--sport", buf);
724         }
725
726         if (dp && dp->set)
727         {
728                 if (dp->port_min == dp->port_max)
729                         sprintf(buf, "%u", dp->port_min);
730                 else
731                         sprintf(buf, "%u:%u", dp->port_min, dp->port_max);
732
733                 fw3_ipt_rule_addarg(r, dp->invert, "--dport", buf);
734         }
735 }
736
737 void
738 fw3_ipt_rule_mac(struct fw3_ipt_rule *r, struct fw3_mac *mac)
739 {
740         if (!mac)
741                 return;
742
743         fw3_ipt_rule_addarg(r, false, "-m", "mac");
744         fw3_ipt_rule_addarg(r, mac->invert, "--mac-source", ether_ntoa(&mac->mac));
745 }
746
747 void
748 fw3_ipt_rule_icmptype(struct fw3_ipt_rule *r, struct fw3_icmptype *icmp)
749 {
750         char buf[sizeof("255/255\0")];
751
752         if (!icmp)
753                 return;
754
755 #ifndef DISABLE_IPV6
756         if (r->h->family == FW3_FAMILY_V6)
757         {
758                 if (icmp->code6_min == 0 && icmp->code6_max == 0xFF)
759                         sprintf(buf, "%u", icmp->type6);
760                 else
761                         sprintf(buf, "%u/%u", icmp->type6, icmp->code6_min);
762
763                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmpv6-type", buf);
764         }
765         else
766 #endif
767         {
768                 if (icmp->code_min == 0 && icmp->code_max == 0xFF)
769                         sprintf(buf, "%u", icmp->type);
770                 else
771                         sprintf(buf, "%u/%u", icmp->type, icmp->code_min);
772
773                 fw3_ipt_rule_addarg(r, icmp->invert, "--icmp-type", buf);
774         }
775 }
776
777 void
778 fw3_ipt_rule_limit(struct fw3_ipt_rule *r, struct fw3_limit *limit)
779 {
780         char buf[sizeof("-4294967296/second\0")];
781
782         if (!limit || limit->rate <= 0)
783                 return;
784
785         fw3_ipt_rule_addarg(r, false, "-m", "limit");
786
787         sprintf(buf, "%u/%s", limit->rate, fw3_limit_units[limit->unit]);
788         fw3_ipt_rule_addarg(r, limit->invert, "--limit", buf);
789
790         if (limit->burst > 0)
791         {
792                 sprintf(buf, "%u", limit->burst);
793                 fw3_ipt_rule_addarg(r, limit->invert, "--limit-burst", buf);
794         }
795 }
796
797 void
798 fw3_ipt_rule_ipset(struct fw3_ipt_rule *r, struct fw3_setmatch *match)
799 {
800         char buf[sizeof("dst,dst,dst\0")];
801         char *p = buf;
802         int i = 0;
803
804         struct fw3_ipset *set;
805         struct fw3_ipset_datatype *type;
806
807         if (!match || !match->set || !match->ptr)
808                 return;
809
810         set = match->ptr;
811         list_for_each_entry(type, &set->datatypes, list)
812         {
813                 if (i >= 3)
814                         break;
815
816                 if (p > buf)
817                         *p++ = ',';
818
819                 p += sprintf(p, "%s", match->dir[i] ? match->dir[i] : type->dir);
820                 i++;
821         }
822
823         fw3_ipt_rule_addarg(r, false, "-m", "set");
824
825         fw3_ipt_rule_addarg(r, match->invert, "--match-set",
826                             set->external ? set->external : set->name);
827
828         fw3_ipt_rule_addarg(r, false, buf, NULL);
829 }
830
831 void
832 fw3_ipt_rule_time(struct fw3_ipt_rule *r, struct fw3_time *time)
833 {
834         int i;
835         struct tm empty = { 0 };
836
837         char buf[84]; /* sizeof("1,2,3,...,30,31\0") */
838         char *p;
839
840         bool d1 = memcmp(&time->datestart, &empty, sizeof(empty));
841         bool d2 = memcmp(&time->datestop, &empty, sizeof(empty));
842
843         if (!d1 && !d2 && !time->timestart && !time->timestop &&
844             !(time->monthdays & 0xFFFFFFFE) && !(time->weekdays & 0xFE))
845         {
846                 return;
847         }
848
849         fw3_ipt_rule_addarg(r, false, "-m", "time");
850
851         if (time->utc)
852                 fw3_ipt_rule_addarg(r, false, "--utc", NULL);
853
854         if (d1)
855         {
856                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestart);
857                 fw3_ipt_rule_addarg(r, false, "--datestart", buf);
858         }
859
860         if (d2)
861         {
862                 strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time->datestop);
863                 fw3_ipt_rule_addarg(r, false, "--datestop", buf);
864         }
865
866         if (time->timestart)
867         {
868                 sprintf(buf, "%02d:%02d:%02d",
869                         time->timestart / 3600,
870                         time->timestart % 3600 / 60,
871                         time->timestart % 60);
872
873                 fw3_ipt_rule_addarg(r, false, "--timestart", buf);
874         }
875
876         if (time->timestop)
877         {
878                 sprintf(buf, "%02d:%02d:%02d",
879                         time->timestop / 3600,
880                         time->timestop % 3600 / 60,
881                         time->timestop % 60);
882
883                 fw3_ipt_rule_addarg(r, false, "--timestop", buf);
884         }
885
886         if (time->monthdays & 0xFFFFFFFE)
887         {
888                 for (i = 1, p = buf; i < 32; i++)
889                 {
890                         if (hasbit(time->monthdays, i))
891                         {
892                                 if (p > buf)
893                                         *p++ = ',';
894
895                                 p += sprintf(p, "%u", i);
896                         }
897                 }
898
899                 fw3_ipt_rule_addarg(r, hasbit(time->monthdays, 0), "--monthdays", buf);
900         }
901
902         if (time->weekdays & 0xFE)
903         {
904                 for (i = 1, p = buf; i < 8; i++)
905                 {
906                         if (hasbit(time->weekdays, i))
907                         {
908                                 if (p > buf)
909                                         *p++ = ',';
910
911                                 p += sprintf(p, "%u", i);
912                         }
913                 }
914
915                 fw3_ipt_rule_addarg(r, hasbit(time->weekdays, 0), "--weekdays", buf);
916         }
917 }
918
919 void
920 fw3_ipt_rule_mark(struct fw3_ipt_rule *r, struct fw3_mark *mark)
921 {
922         char buf[sizeof("0xFFFFFFFF/0xFFFFFFFF\0")];
923
924         if (!mark || !mark->set)
925                 return;
926
927         if (mark->mask < 0xFFFFFFFF)
928                 sprintf(buf, "0x%x/0x%x", mark->mark, mark->mask);
929         else
930                 sprintf(buf, "0x%x", mark->mark);
931
932         fw3_ipt_rule_addarg(r, false, "-m", "mark");
933         fw3_ipt_rule_addarg(r, mark->invert, "--mark", buf);
934 }
935
936 void
937 fw3_ipt_rule_comment(struct fw3_ipt_rule *r, const char *fmt, ...)
938 {
939         va_list ap;
940         char buf[256];
941
942         if (!fmt || !*fmt)
943                 return;
944
945         va_start(ap, fmt);
946         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
947         va_end(ap);
948
949         fw3_ipt_rule_addarg(r, false, "-m", "comment");
950         fw3_ipt_rule_addarg(r, false, "--comment", buf);
951 }
952
953 void
954 fw3_ipt_rule_extra(struct fw3_ipt_rule *r, const char *extra)
955 {
956         char *p, **tmp, *s;
957
958         if (!extra || !*extra)
959                 return;
960
961         s = fw3_strdup(extra);
962
963         for (p = strtok(s, " \t"); p; p = strtok(NULL, " \t"))
964         {
965                 tmp = realloc(r->argv, (r->argc + 1) * sizeof(*r->argv));
966
967                 if (!tmp)
968                         break;
969
970                 r->argv = tmp;
971                 r->argv[r->argc++] = fw3_strdup(p);
972         }
973
974         free(s);
975 }
976
977 #ifndef DISABLE_IPV6
978 static void
979 rule_print6(struct ip6t_entry *e)
980 {
981         char buf[INET6_ADDRSTRLEN];
982         char *pname;
983
984         if (e->ipv6.flags & IP6T_F_PROTO)
985         {
986                 if (e->ipv6.flags & XT_INV_PROTO)
987                         printf(" !");
988
989                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e6));
990
991                 if (pname)
992                         printf(" -p %s", pname);
993                 else
994                         printf(" -p %u", e->ipv6.proto);
995         }
996
997         if (e->ipv6.iniface[0])
998         {
999                 if (e->ipv6.flags & IP6T_INV_VIA_IN)
1000                         printf(" !");
1001
1002                 printf(" -i %s", e->ipv6.iniface);
1003         }
1004
1005         if (e->ipv6.outiface[0])
1006         {
1007                 if (e->ipv6.flags & IP6T_INV_VIA_OUT)
1008                         printf(" !");
1009
1010                 printf(" -o %s", e->ipv6.outiface);
1011         }
1012
1013         if (memcmp(&e->ipv6.src, &in6addr_any, sizeof(struct in6_addr)))
1014         {
1015                 if (e->ipv6.flags & IP6T_INV_SRCIP)
1016                         printf(" !");
1017
1018                 printf(" -s %s/%u", inet_ntop(AF_INET6, &e->ipv6.src, buf, sizeof(buf)),
1019                                     xtables_ip6mask_to_cidr(&e->ipv6.smsk));
1020         }
1021
1022         if (memcmp(&e->ipv6.dst, &in6addr_any, sizeof(struct in6_addr)))
1023         {
1024                 if (e->ipv6.flags & IP6T_INV_DSTIP)
1025                         printf(" !");
1026
1027                 printf(" -d %s/%u", inet_ntop(AF_INET6, &e->ipv6.dst, buf, sizeof(buf)),
1028                                     xtables_ip6mask_to_cidr(&e->ipv6.dmsk));
1029         }
1030 }
1031 #endif
1032
1033 static void
1034 rule_print4(struct ipt_entry *e)
1035 {
1036         struct in_addr in_zero = { 0 };
1037         char buf[sizeof("255.255.255.255\0")];
1038         char *pname;
1039
1040         if (e->ip.proto)
1041         {
1042                 if (e->ip.flags & XT_INV_PROTO)
1043                         printf(" !");
1044
1045                 pname = get_protoname(container_of(e, struct fw3_ipt_rule, e));
1046
1047                 if (pname)
1048                         printf(" -p %s", pname);
1049                 else
1050                         printf(" -p %u", e->ip.proto);
1051         }
1052
1053         if (e->ip.iniface[0])
1054         {
1055                 if (e->ip.flags & IPT_INV_VIA_IN)
1056                         printf(" !");
1057
1058                 printf(" -i %s", e->ip.iniface);
1059         }
1060
1061         if (e->ip.outiface[0])
1062         {
1063                 if (e->ip.flags & IPT_INV_VIA_OUT)
1064                         printf(" !");
1065
1066                 printf(" -o %s", e->ip.outiface);
1067         }
1068
1069         if (memcmp(&e->ip.src, &in_zero, sizeof(struct in_addr)))
1070         {
1071                 if (e->ip.flags & IPT_INV_SRCIP)
1072                         printf(" !");
1073
1074                 printf(" -s %s/%u", inet_ntop(AF_INET, &e->ip.src, buf, sizeof(buf)),
1075                                     xtables_ipmask_to_cidr(&e->ip.smsk));
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/%u", inet_ntop(AF_INET, &e->ip.dst, buf, sizeof(buf)),
1084                                     xtables_ipmask_to_cidr(&e->ip.dmsk));
1085         }
1086 }
1087
1088 static void
1089 rule_print(struct fw3_ipt_rule *r, const char *chain)
1090 {
1091         debug(r->h, "-A %s", chain);
1092
1093 #ifndef DISABLE_IPV6
1094         if (r->h->family == FW3_FAMILY_V6)
1095                 rule_print6(&r->e6);
1096         else
1097 #endif
1098                 rule_print4(&r->e);
1099
1100         fw3_xt_print_matches(&r->e.ip, r->matches);
1101         fw3_xt_print_target(&r->e.ip, r->target);
1102
1103         printf("\n");
1104 }
1105
1106 static bool
1107 parse_option(struct fw3_ipt_rule *r, int optc, bool inv)
1108 {
1109         struct xtables_rule_match *m;
1110         struct xtables_match *em;
1111
1112         /* is a target option */
1113         if (r->target && fw3_xt_has_target_parse(r->target) &&
1114                 optc >= r->target->option_offset &&
1115                 optc < (r->target->option_offset + 256))
1116         {
1117                 xtables_option_tpcall(optc, r->argv, inv, r->target, &r->e);
1118                 return false;
1119         }
1120
1121         /* try to dispatch argument to one of the match parsers */
1122         for (m = r->matches; m; m = m->next)
1123         {
1124                 em = m->match;
1125
1126                 if (m->completed || !fw3_xt_has_match_parse(em))
1127                         continue;
1128
1129                 if (optc < em->option_offset ||
1130                         optc >= (em->option_offset + 256))
1131                         continue;
1132
1133                 xtables_option_mpcall(optc, r->argv, inv, em, &r->e);
1134                 return false;
1135         }
1136
1137         /* unhandled option, might belong to a protocol match */
1138         if ((em = load_protomatch(r)) != NULL)
1139         {
1140                 init_match(r, em, false);
1141
1142                 r->protocol_loaded = true;
1143                 optind--;
1144
1145                 return true;
1146         }
1147
1148         if (optc == ':')
1149                 fprintf(stderr, "parse_option(): option '%s' needs argument\n",
1150                         r->argv[optind-1]);
1151
1152         if (optc == '?')
1153                 fprintf(stderr, "parse_option(): unknown option '%s'\n",
1154                         r->argv[optind-1]);
1155
1156         return false;
1157 }
1158
1159 void
1160 fw3_ipt_rule_addarg(struct fw3_ipt_rule *r, bool inv,
1161                     const char *k, const char *v)
1162 {
1163         int n;
1164         char **tmp;
1165
1166         if (!k)
1167                 return;
1168
1169         n = inv + !!k + !!v;
1170         tmp = realloc(r->argv, (r->argc + n) * sizeof(*tmp));
1171
1172         if (!tmp)
1173                 return;
1174
1175         r->argv = tmp;
1176
1177         if (inv)
1178                 r->argv[r->argc++] = fw3_strdup("!");
1179
1180         r->argv[r->argc++] = fw3_strdup(k);
1181
1182         if (v)
1183                 r->argv[r->argc++] = fw3_strdup(v);
1184 }
1185
1186 void
1187 fw3_ipt_rule_append(struct fw3_ipt_rule *r, const char *fmt, ...)
1188 {
1189         size_t s;
1190         struct xtables_rule_match *m;
1191         struct xtables_match *em;
1192         struct xtables_target *et;
1193         struct xtables_globals *g;
1194         struct ipt_entry *e;
1195
1196         int i, optc;
1197         bool inv = false;
1198         char buf[32];
1199         va_list ap;
1200
1201         va_start(ap, fmt);
1202         vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
1203         va_end(ap);
1204
1205         g = (r->h->family == FW3_FAMILY_V6) ? &xtg6 : &xtg;
1206         g->opts = g->orig_opts;
1207
1208         optind = 0;
1209         opterr = 0;
1210
1211         while ((optc = getopt_long(r->argc, r->argv, "m:j:", g->opts, NULL)) != -1)
1212         {
1213                 switch (optc)
1214                 {
1215                 case 'm':
1216                         em = find_match(r, optarg);
1217
1218                         if (!em)
1219                         {
1220                                 fprintf(stderr, "fw3_ipt_rule_append(): Can't find match '%s'\n", optarg);
1221                                 goto free;
1222                         }
1223
1224                         init_match(r, em, true);
1225                         break;
1226
1227                 case 'j':
1228                         et = get_target(r, optarg);
1229
1230                         if (!et)
1231                         {
1232                                 fprintf(stderr, "fw3_ipt_rule_append(): Can't find target '%s'\n", optarg);
1233                                 goto free;
1234                         }
1235
1236                         break;
1237
1238                 case 1:
1239                         if ((optarg[0] == '!') && (optarg[1] == '\0'))
1240                         {
1241                                 inv = true;
1242                                 continue;
1243                         }
1244
1245                         fprintf(stderr, "fw3_ipt_rule_append(): Bad argument '%s'\n", optarg);
1246                         return;
1247
1248                 default:
1249                         if (parse_option(r, optc, inv))
1250                                 continue;
1251                         break;
1252                 }
1253
1254                 inv = false;
1255         }
1256
1257         for (m = r->matches; m; m = m->next)
1258                 xtables_option_mfcall(m->match);
1259
1260         if (r->target)
1261                 xtables_option_tfcall(r->target);
1262
1263         if (fw3_pr_debug)
1264                 rule_print(r, buf);
1265
1266 #ifndef DISABLE_IPV6
1267         if (r->h->family == FW3_FAMILY_V6)
1268         {
1269                 struct ip6t_entry *e6;
1270
1271                 s = XT_ALIGN(sizeof(struct ip6t_entry));
1272
1273                 for (m = r->matches; m; m = m->next)
1274                         s += m->match->m->u.match_size;
1275
1276                 e6 = fw3_alloc(s + r->target->t->u.target_size);
1277
1278                 memcpy(e6, &r->e6, sizeof(struct ip6t_entry));
1279
1280                 e6->target_offset = s;
1281                 e6->next_offset = s + r->target->t->u.target_size;
1282
1283                 s = 0;
1284
1285                 for (m = r->matches; m; m = m->next)
1286                 {
1287                         memcpy(e6->elems + s, m->match->m, m->match->m->u.match_size);
1288                         s += m->match->m->u.match_size;
1289                 }
1290
1291                 memcpy(e6->elems + s, r->target->t, r->target->t->u.target_size);
1292                 ip6tc_append_entry(buf, e6, r->h->handle);
1293                 free(e6);
1294         }
1295         else
1296 #endif
1297         {
1298                 s = XT_ALIGN(sizeof(struct ipt_entry));
1299
1300                 for (m = r->matches; m; m = m->next)
1301                         s += m->match->m->u.match_size;
1302
1303                 e = fw3_alloc(s + r->target->t->u.target_size);
1304
1305                 memcpy(e, &r->e, sizeof(struct ipt_entry));
1306
1307                 e->target_offset = s;
1308                 e->next_offset = s + r->target->t->u.target_size;
1309
1310                 s = 0;
1311
1312                 for (m = r->matches; m; m = m->next)
1313                 {
1314                         memcpy(e->elems + s, m->match->m, m->match->m->u.match_size);
1315                         s += m->match->m->u.match_size;
1316                 }
1317
1318                 memcpy(e->elems + s, r->target->t, r->target->t->u.target_size);
1319
1320                 if (!iptc_append_entry(buf, e, r->h->handle))
1321                         fprintf(stderr, "iptc_append_entry(): %s\n", iptc_strerror(errno));
1322
1323                 free(e);
1324         }
1325
1326 free:
1327         for (i = 1; i < r->argc; i++)
1328                 free(r->argv[i]);
1329
1330         free(r->argv);
1331
1332         xtables_rule_matches_free(&r->matches);
1333
1334         if (r->target)
1335                 free(r->target->t);
1336
1337         free(r);
1338
1339         /* reset all targets and matches */
1340         for (em = xtables_matches; em; em = em->next)
1341                 em->mflags = 0;
1342
1343         for (et = xtables_targets; et; et = et->next)
1344         {
1345                 et->tflags = 0;
1346                 et->used = 0;
1347         }
1348
1349         xtables_free_opts(1);
1350 }
1351
1352 struct fw3_ipt_rule *
1353 fw3_ipt_rule_create(struct fw3_ipt_handle *handle, struct fw3_protocol *proto,
1354                     struct fw3_device *in, struct fw3_device *out,
1355                     struct fw3_address *src, struct fw3_address *dest)
1356 {
1357         struct fw3_ipt_rule *r;
1358
1359         r = fw3_ipt_rule_new(handle);
1360
1361         fw3_ipt_rule_proto(r, proto);
1362         fw3_ipt_rule_in_out(r, in, out);
1363         fw3_ipt_rule_src_dest(r, src, dest);
1364
1365         return r;
1366 }