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