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