zones: make forward policy destination bound
[project/firewall3.git] / utils.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 #define _GNU_SOURCE
20 #include "utils.h"
21 #include "options.h"
22
23 #include "zones.h"
24 #include "ipsets.h"
25
26
27 static int lock_fd = -1;
28 static pid_t pipe_pid = -1;
29 static FILE *pipe_fd = NULL;
30
31 bool fw3_pr_debug = false;
32
33
34 static void
35 warn_elem_section_name(struct uci_section *s, bool find_name)
36 {
37         int i = 0;
38         struct uci_option *o;
39         struct uci_element *tmp;
40
41         if (s->anonymous)
42         {
43                 uci_foreach_element(&s->package->sections, tmp)
44                 {
45                         if (strcmp(uci_to_section(tmp)->type, s->type))
46                                 continue;
47
48                         if (&s->e == tmp)
49                                 break;
50
51                         i++;
52                 }
53
54                 fprintf(stderr, "@%s[%d]", s->type, i);
55
56                 if (find_name)
57                 {
58                         uci_foreach_element(&s->options, tmp)
59                         {
60                                 o = uci_to_option(tmp);
61
62                                 if (!strcmp(tmp->name, "name") && (o->type == UCI_TYPE_STRING))
63                                 {
64                                         fprintf(stderr, " (%s)", o->v.string);
65                                         break;
66                                 }
67                         }
68                 }
69         }
70         else
71         {
72                 fprintf(stderr, "'%s'", s->e.name);
73         }
74
75         if (find_name)
76                 fprintf(stderr, " ");
77 }
78
79 void
80 warn_elem(struct uci_element *e, const char *format, ...)
81 {
82         if (e->type == UCI_TYPE_SECTION)
83         {
84                 fprintf(stderr, "Warning: Section ");
85                 warn_elem_section_name(uci_to_section(e), true);
86         }
87         else if (e->type == UCI_TYPE_OPTION)
88         {
89                 fprintf(stderr, "Warning: Option ");
90                 warn_elem_section_name(uci_to_option(e)->section, false);
91                 fprintf(stderr, ".%s ", e->name);
92         }
93
94     va_list argptr;
95     va_start(argptr, format);
96     vfprintf(stderr, format, argptr);
97     va_end(argptr);
98
99         fprintf(stderr, "\n");
100 }
101
102 void
103 warn(const char* format, ...)
104 {
105         fprintf(stderr, "Warning: ");
106     va_list argptr;
107     va_start(argptr, format);
108     vfprintf(stderr, format, argptr);
109     va_end(argptr);
110         fprintf(stderr, "\n");
111 }
112
113 void
114 error(const char* format, ...)
115 {
116         fprintf(stderr, "Error: ");
117     va_list argptr;
118     va_start(argptr, format);
119     vfprintf(stderr, format, argptr);
120     va_end(argptr);
121         fprintf(stderr, "\n");
122
123         exit(1);
124 }
125
126 void
127 info(const char* format, ...)
128 {
129         va_list argptr;
130     va_start(argptr, format);
131     vfprintf(stderr, format, argptr);
132     va_end(argptr);
133         fprintf(stderr, "\n");
134 }
135
136 void *
137 fw3_alloc(size_t size)
138 {
139         void *mem;
140
141         mem = calloc(1, size);
142
143         if (!mem)
144                 error("Out of memory while allocating %d bytes", size);
145
146         return mem;
147 }
148
149 char *
150 fw3_strdup(const char *s)
151 {
152         char *ns;
153
154         ns = strdup(s);
155
156         if (!ns)
157                 error("Out of memory while duplicating string '%s'", s);
158
159         return ns;
160 }
161
162 const char *
163 fw3_find_command(const char *cmd)
164 {
165         struct stat s;
166         int plen = 0, clen = strlen(cmd) + 1;
167         char *search, *p;
168         static char path[PATH_MAX];
169
170         if (!stat(cmd, &s) && S_ISREG(s.st_mode))
171                 return cmd;
172
173         search = getenv("PATH");
174
175         if (!search)
176                 search = "/bin:/usr/bin:/sbin:/usr/sbin";
177
178         p = search;
179
180         do
181         {
182                 if (*p != ':' && *p != '\0')
183                         continue;
184
185                 plen = p - search;
186
187                 if ((plen + clen) >= sizeof(path))
188                         continue;
189
190                 strncpy(path, search, plen);
191                 sprintf(path + plen, "/%s", cmd);
192
193                 if (!stat(path, &s) && S_ISREG(s.st_mode))
194                         return path;
195
196                 search = p + 1;
197         }
198         while (*p++);
199
200         return NULL;
201 }
202
203 bool
204 fw3_stdout_pipe(void)
205 {
206         pipe_fd = stdout;
207         return true;
208 }
209
210 bool
211 __fw3_command_pipe(bool silent, const char *command, ...)
212 {
213         pid_t pid;
214         va_list argp;
215         int pfds[2];
216         int argn;
217         char *arg, **args, **tmp;
218
219         command = fw3_find_command(command);
220
221         if (!command)
222                 return false;
223
224         if (pipe(pfds))
225                 return false;
226
227         argn = 2;
228         args = calloc(argn, sizeof(arg));
229
230         if (!args)
231                 return false;
232
233         args[0] = (char *)command;
234         args[1] = NULL;
235
236         va_start(argp, command);
237
238         while ((arg = va_arg(argp, char *)) != NULL)
239         {
240                 tmp = realloc(args, ++argn * sizeof(arg));
241
242                 if (!tmp)
243                         break;
244
245                 args = tmp;
246                 args[argn-2] = arg;
247                 args[argn-1] = NULL;
248         }
249
250         va_end(argp);
251
252         switch ((pid = fork()))
253         {
254         case -1:
255                 return false;
256
257         case 0:
258                 dup2(pfds[0], 0);
259
260                 close(pfds[0]);
261                 close(pfds[1]);
262
263                 close(1);
264
265                 if (silent)
266                         close(2);
267
268                 execv(command, args);
269
270         default:
271                 signal(SIGPIPE, SIG_IGN);
272                 pipe_pid = pid;
273                 close(pfds[0]);
274                 fcntl(pfds[1], F_SETFD, fcntl(pfds[1], F_GETFD) | FD_CLOEXEC);
275         }
276
277         pipe_fd = fdopen(pfds[1], "w");
278         return true;
279 }
280
281 void
282 fw3_pr(const char *fmt, ...)
283 {
284         va_list args;
285
286         if (fw3_pr_debug && pipe_fd != stdout)
287         {
288                 va_start(args, fmt);
289                 vfprintf(stderr, fmt, args);
290                 va_end(args);
291         }
292
293         va_start(args, fmt);
294         vfprintf(pipe_fd, fmt, args);
295         va_end(args);
296 }
297
298 void
299 fw3_command_close(void)
300 {
301         if (pipe_fd && pipe_fd != stdout)
302                 fclose(pipe_fd);
303
304         if (pipe_pid > -1)
305                 waitpid(pipe_pid, NULL, 0);
306
307         signal(SIGPIPE, SIG_DFL);
308
309         pipe_fd = NULL;
310         pipe_pid = -1;
311 }
312
313 bool
314 fw3_has_table(bool ipv6, const char *table)
315 {
316         FILE *f;
317
318         char line[12];
319         bool seen = false;
320
321         const char *path = ipv6
322                 ? "/proc/net/ip6_tables_names" : "/proc/net/ip_tables_names";
323
324         if (!(f = fopen(path, "r")))
325                 return false;
326
327         while (fgets(line, sizeof(line), f))
328         {
329                 if (!strncmp(line, table, strlen(table)))
330                 {
331                         seen = true;
332                         break;
333                 }
334         }
335
336         fclose(f);
337
338         return seen;
339 }
340
341
342 bool
343 fw3_lock(void)
344 {
345         lock_fd = open(FW3_LOCKFILE, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
346
347         if (lock_fd < 0)
348         {
349                 warn("Cannot create lock file %s: %s", FW3_LOCKFILE, strerror(errno));
350                 return false;
351         }
352
353         if (flock(lock_fd, LOCK_EX))
354         {
355                 warn("Cannot acquire exclusive lock: %s", strerror(errno));
356                 return false;
357         }
358
359         return true;
360 }
361
362 void
363 fw3_unlock(void)
364 {
365         if (lock_fd < 0)
366                 return;
367
368         if (flock(lock_fd, LOCK_UN))
369                 warn("Cannot release exclusive lock: %s", strerror(errno));
370
371         close(lock_fd);
372         unlink(FW3_LOCKFILE);
373
374         lock_fd = -1;
375 }
376
377
378 static void
379 write_defaults_uci(struct uci_context *ctx, struct fw3_defaults *d,
380                    struct uci_package *dest)
381 {
382         char buf[sizeof("0xffffffff\0")];
383         struct uci_ptr ptr = { .p = dest };
384
385         uci_add_section(ctx, dest, "defaults", &ptr.s);
386
387         ptr.o      = NULL;
388         ptr.option = "input";
389         ptr.value  = fw3_flag_names[d->policy_input];
390         uci_set(ctx, &ptr);
391
392         ptr.o      = NULL;
393         ptr.option = "output";
394         ptr.value  = fw3_flag_names[d->policy_output];
395         uci_set(ctx, &ptr);
396
397         ptr.o      = NULL;
398         ptr.option = "forward";
399         ptr.value  = fw3_flag_names[d->policy_forward];
400         uci_set(ctx, &ptr);
401
402         sprintf(buf, "0x%x", d->flags[0]);
403         ptr.o      = NULL;
404         ptr.option = "__flags_v4";
405         ptr.value  = buf;
406         uci_set(ctx, &ptr);
407
408         sprintf(buf, "0x%x", d->flags[1]);
409         ptr.o      = NULL;
410         ptr.option = "__flags_v6";
411         ptr.value  = buf;
412         uci_set(ctx, &ptr);
413 }
414
415 static void
416 write_zone_uci(struct uci_context *ctx, struct fw3_zone *z,
417                struct uci_package *dest)
418 {
419         struct fw3_device *dev;
420         struct fw3_address *sub;
421         enum fw3_family fam = FW3_FAMILY_ANY;
422
423         char *p, buf[34];
424
425         struct uci_ptr ptr = { .p = dest };
426
427         if (!z->enabled)
428                 return;
429
430         if (fw3_no_table(z->flags[0]) && !fw3_no_table(z->flags[1]))
431                 fam = FW3_FAMILY_V6;
432         else if (!fw3_no_table(z->flags[0]) && fw3_no_table(z->flags[1]))
433                 fam = FW3_FAMILY_V4;
434         else if (fw3_no_table(z->flags[0]) && fw3_no_table(z->flags[1]))
435                 return;
436
437         uci_add_section(ctx, dest, "zone", &ptr.s);
438
439         ptr.o      = NULL;
440         ptr.option = "name";
441         ptr.value  = z->name;
442         uci_set(ctx, &ptr);
443
444         ptr.o      = NULL;
445         ptr.option = "input";
446         ptr.value  = fw3_flag_names[z->policy_input];
447         uci_set(ctx, &ptr);
448
449         ptr.o      = NULL;
450         ptr.option = "output";
451         ptr.value  = fw3_flag_names[z->policy_output];
452         uci_set(ctx, &ptr);
453
454         ptr.o      = NULL;
455         ptr.option = "forward";
456         ptr.value  = fw3_flag_names[z->policy_forward];
457         uci_set(ctx, &ptr);
458
459         ptr.o      = NULL;
460         ptr.option = "masq";
461         ptr.value  = z->masq ? "1" : "0";
462         uci_set(ctx, &ptr);
463
464         ptr.o      = NULL;
465         ptr.option = "conntrack";
466         ptr.value  = z->conntrack ? "1" : "0";
467         uci_set(ctx, &ptr);
468
469         ptr.o      = NULL;
470         ptr.option = "mtu_fix";
471         ptr.value  = z->mtu_fix ? "1" : "0";
472         uci_set(ctx, &ptr);
473
474         ptr.o      = NULL;
475         ptr.option = "custom_chains";
476         ptr.value  = z->custom_chains ? "1" : "0";
477         uci_set(ctx, &ptr);
478
479         if (fam != FW3_FAMILY_ANY)
480         {
481                 ptr.o      = NULL;
482                 ptr.option = "family";
483                 ptr.value  = fw3_flag_names[fam];
484                 uci_set(ctx, &ptr);
485         }
486
487         ptr.o      = NULL;
488         ptr.option = "device";
489
490         fw3_foreach(dev, &z->devices)
491         {
492                 if (!dev)
493                         continue;
494
495                 p = buf;
496
497                 if (dev->invert)
498                         p += sprintf(p, "!");
499
500                 if (*dev->network)
501                         p += sprintf(p, "%s@%s", dev->name, dev->network);
502                 else
503                         p += sprintf(p, "%s", dev->name);
504
505                 ptr.value = buf;
506                 uci_add_list(ctx, &ptr);
507         }
508
509         ptr.o      = NULL;
510         ptr.option = "subnet";
511
512         fw3_foreach(sub, &z->subnets)
513         {
514                 if (!sub)
515                         continue;
516
517                 ptr.value = fw3_address_to_string(sub, true, false);
518                 uci_add_list(ctx, &ptr);
519         }
520
521         sprintf(buf, "0x%x", z->flags[0]);
522         ptr.o      = NULL;
523         ptr.option = "__flags_v4";
524         ptr.value  = buf;
525         uci_set(ctx, &ptr);
526
527         sprintf(buf, "0x%x", z->flags[1]);
528         ptr.o      = NULL;
529         ptr.option = "__flags_v6";
530         ptr.value  = buf;
531         uci_set(ctx, &ptr);
532 }
533
534 static void
535 write_ipset_uci(struct uci_context *ctx, struct fw3_ipset *s,
536                 struct uci_package *dest)
537 {
538         struct fw3_ipset_datatype *type;
539
540         char buf[sizeof("65535-65535\0")];
541
542         struct uci_ptr ptr = { .p = dest };
543
544         if (!s->enabled || s->external)
545                 return;
546
547         uci_add_section(ctx, dest, "ipset", &ptr.s);
548
549         ptr.o      = NULL;
550         ptr.option = "name";
551         ptr.value  = s->name;
552         uci_set(ctx, &ptr);
553
554         ptr.o      = NULL;
555         ptr.option = "storage";
556         ptr.value  = fw3_ipset_method_names[s->method];
557         uci_set(ctx, &ptr);
558
559         list_for_each_entry(type, &s->datatypes, list)
560         {
561                 sprintf(buf, "%s_%s", type->dir, fw3_ipset_type_names[type->type]);
562                 ptr.o      = NULL;
563                 ptr.option = "match";
564                 ptr.value  = buf;
565                 uci_add_list(ctx, &ptr);
566         }
567
568         if (s->iprange.set)
569         {
570                 ptr.o      = NULL;
571                 ptr.option = "iprange";
572                 ptr.value  = fw3_address_to_string(&s->iprange, false, false);
573                 uci_set(ctx, &ptr);
574         }
575
576         if (s->portrange.set)
577         {
578                 sprintf(buf, "%u-%u", s->portrange.port_min, s->portrange.port_max);
579                 ptr.o      = NULL;
580                 ptr.option = "portrange";
581                 ptr.value  = buf;
582                 uci_set(ctx, &ptr);
583         }
584 }
585
586 void
587 fw3_write_statefile(void *state)
588 {
589         FILE *sf;
590         struct fw3_state *s = state;
591         struct fw3_zone *z;
592         struct fw3_ipset *i;
593
594         struct uci_package *p;
595
596         if (fw3_no_family(s->defaults.flags[0]) &&
597             fw3_no_family(s->defaults.flags[1]))
598         {
599                 unlink(FW3_STATEFILE);
600         }
601         else
602         {
603                 sf = fopen(FW3_STATEFILE, "w+");
604
605                 if (!sf)
606                 {
607                         warn("Cannot create state %s: %s", FW3_STATEFILE, strerror(errno));
608                         return;
609                 }
610
611                 if ((p = uci_lookup_package(s->uci, "fw3_state")) != NULL)
612                         uci_unload(s->uci, p);
613
614                 uci_import(s->uci, sf, "fw3_state", NULL, true);
615
616                 if ((p = uci_lookup_package(s->uci, "fw3_state")) != NULL)
617                 {
618                         write_defaults_uci(s->uci, &s->defaults, p);
619
620                         list_for_each_entry(z, &s->zones, list)
621                                 write_zone_uci(s->uci, z, p);
622
623                         list_for_each_entry(i, &s->ipsets, list)
624                                 write_ipset_uci(s->uci, i, p);
625
626                         uci_export(s->uci, sf, p, true);
627                         uci_unload(s->uci, p);
628                 }
629
630                 fsync(fileno(sf));
631                 fclose(sf);
632         }
633 }
634
635
636 void
637 fw3_free_object(void *obj, const void *opts)
638 {
639         const struct fw3_option *ol;
640         struct list_head *list, *cur, *tmp;
641
642         for (ol = opts; ol->name; ol++)
643         {
644                 if (!ol->elem_size)
645                         continue;
646
647                 list = (struct list_head *)((char *)obj + ol->offset);
648                 list_for_each_safe(cur, tmp, list)
649                 {
650                         list_del(cur);
651                         free(cur);
652                 }
653         }
654
655         free(obj);
656 }
657
658 void
659 fw3_free_list(struct list_head *head)
660 {
661         struct list_head *entry, *tmp;
662
663         if (!head)
664                 return;
665
666         list_for_each_safe(entry, tmp, head)
667         {
668                 list_del(entry);
669                 free(entry);
670         }
671
672         free(head);
673 }
674
675 bool
676 fw3_hotplug(bool add, void *zone, void *device)
677 {
678         struct fw3_zone *z = zone;
679         struct fw3_device *d = device;
680
681         if (!*d->network)
682                 return false;
683
684         switch (fork())
685         {
686         case -1:
687                 warn("Unable to fork(): %s\n", strerror(errno));
688                 return false;
689
690         case 0:
691                 break;
692
693         default:
694                 return true;
695         }
696
697         close(0);
698         close(1);
699         close(2);
700         if (chdir("/")) {};
701
702         clearenv();
703         setenv("ACTION",    add ? "add" : "remove", 1);
704         setenv("ZONE",      z->name,                1);
705         setenv("INTERFACE", d->network,             1);
706         setenv("DEVICE",    d->name,                1);
707
708         execl(FW3_HOTPLUG, FW3_HOTPLUG, "firewall", NULL);
709
710         /* unreached */
711         return false;
712 }
713
714 int
715 fw3_netmask2bitlen(int family, void *mask)
716 {
717         int bits;
718         struct in_addr *v4;
719         struct in6_addr *v6;
720
721         if (family == FW3_FAMILY_V6)
722                 for (bits = 0, v6 = mask;
723                      bits < 128 && (v6->s6_addr[bits / 8] << (bits % 8)) & 128;
724                      bits++);
725         else
726                 for (bits = 0, v4 = mask;
727                      bits < 32 && (ntohl(v4->s_addr) << bits) & 0x80000000;
728                      bits++);
729
730         return bits;
731 }
732
733 bool
734 fw3_bitlen2netmask(int family, int bits, void *mask)
735 {
736         int i;
737         struct in_addr *v4;
738         struct in6_addr *v6;
739
740         if (family == FW3_FAMILY_V6)
741         {
742                 if (bits < -128 || bits > 128)
743                         return false;
744
745                 v6 = mask;
746                 i = abs(bits);
747
748                 memset(v6->s6_addr, 0xff, i / 8);
749                 memset(v6->s6_addr + (i / 8) + 1, 0, (128 - i) / 8);
750                 v6->s6_addr[i / 8] = 0xff << (8 - (i & 7));
751
752                 if (bits < 0)
753                         for (i = 0; i < 16; i++)
754                                 v6->s6_addr[i] = ~v6->s6_addr[i];
755         }
756         else
757         {
758                 if (bits < -32 || bits > 32)
759                         return false;
760
761                 v4 = mask;
762                 v4->s_addr = htonl(~((1 << (32 - abs(bits))) - 1));
763
764                 if (bits < 0)
765                         v4->s_addr = ~v4->s_addr;
766         }
767
768         return true;
769 }