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