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