ubus: fix interface name and proto lookup
[project/firewall3.git] / utils.c
1 /*
2 * firewall3 - 3rd OpenWrt UCI firewall implementation
3 *
4 * Copyright (C) 2013 Jo-Philipp Wich <jo@mein.io>
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, struct ifaddrs *ifaddr)
418 {
419 struct fw3_device *dev;
420 struct fw3_address *sub;
421 struct ifaddrs *ifa;
422 enum fw3_family fam = FW3_FAMILY_ANY;
423
424 char *p, buf[INET6_ADDRSTRLEN];
425
426 struct uci_ptr ptr = { .p = dest };
427
428 if (!z->enabled)
429 return;
430
431 if (fw3_no_table(z->flags[0]) && !fw3_no_table(z->flags[1]))
432 fam = FW3_FAMILY_V6;
433 else if (!fw3_no_table(z->flags[0]) && fw3_no_table(z->flags[1]))
434 fam = FW3_FAMILY_V4;
435 else if (fw3_no_table(z->flags[0]) && fw3_no_table(z->flags[1]))
436 return;
437
438 uci_add_section(ctx, dest, "zone", &ptr.s);
439
440 ptr.o = NULL;
441 ptr.option = "name";
442 ptr.value = z->name;
443 uci_set(ctx, &ptr);
444
445 ptr.o = NULL;
446 ptr.option = "input";
447 ptr.value = fw3_flag_names[z->policy_input];
448 uci_set(ctx, &ptr);
449
450 ptr.o = NULL;
451 ptr.option = "output";
452 ptr.value = fw3_flag_names[z->policy_output];
453 uci_set(ctx, &ptr);
454
455 ptr.o = NULL;
456 ptr.option = "forward";
457 ptr.value = fw3_flag_names[z->policy_forward];
458 uci_set(ctx, &ptr);
459
460 ptr.o = NULL;
461 ptr.option = "masq";
462 ptr.value = z->masq ? "1" : "0";
463 uci_set(ctx, &ptr);
464
465 ptr.o = NULL;
466 ptr.option = "mtu_fix";
467 ptr.value = z->mtu_fix ? "1" : "0";
468 uci_set(ctx, &ptr);
469
470 ptr.o = NULL;
471 ptr.option = "custom_chains";
472 ptr.value = z->custom_chains ? "1" : "0";
473 uci_set(ctx, &ptr);
474
475 if (fam != FW3_FAMILY_ANY)
476 {
477 ptr.o = NULL;
478 ptr.option = "family";
479 ptr.value = fw3_flag_names[fam];
480 uci_set(ctx, &ptr);
481 }
482
483 ptr.o = NULL;
484 ptr.option = "device";
485
486 fw3_foreach(dev, &z->devices)
487 {
488 if (!dev)
489 continue;
490
491 p = buf;
492
493 if (dev->invert)
494 p += sprintf(p, "!");
495
496 if (*dev->network)
497 p += sprintf(p, "%s@%s", dev->name, dev->network);
498 else
499 p += sprintf(p, "%s", dev->name);
500
501 ptr.value = buf;
502 uci_add_list(ctx, &ptr);
503 }
504
505 ptr.o = NULL;
506 ptr.option = "subnet";
507
508 fw3_foreach(sub, &z->subnets)
509 {
510 if (!sub)
511 continue;
512
513 ptr.value = fw3_address_to_string(sub, true, false);
514 uci_add_list(ctx, &ptr);
515 }
516
517 ptr.o = NULL;
518 ptr.option = "__addrs";
519
520 fw3_foreach(dev, &z->devices)
521 {
522 if (!dev)
523 continue;
524
525 for (ifa = ifaddr; ifa; ifa = ifa->ifa_next)
526 {
527 if (!ifa->ifa_addr || strcmp(dev->name, ifa->ifa_name))
528 continue;
529
530 if (ifa->ifa_addr->sa_family == AF_INET)
531 inet_ntop(AF_INET,
532 &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr,
533 buf, sizeof(buf));
534 else if (ifa->ifa_addr->sa_family == AF_INET6)
535 inet_ntop(AF_INET6,
536 &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr,
537 buf, sizeof(buf));
538 else
539 continue;
540
541 ptr.value = buf;
542 uci_add_list(ctx, &ptr);
543 }
544 }
545
546 sprintf(buf, "0x%x", z->flags[0]);
547 ptr.o = NULL;
548 ptr.option = "__flags_v4";
549 ptr.value = buf;
550 uci_set(ctx, &ptr);
551
552 sprintf(buf, "0x%x", z->flags[1]);
553 ptr.o = NULL;
554 ptr.option = "__flags_v6";
555 ptr.value = buf;
556 uci_set(ctx, &ptr);
557 }
558
559 static void
560 write_ipset_uci(struct uci_context *ctx, struct fw3_ipset *s,
561 struct uci_package *dest)
562 {
563 struct fw3_ipset_datatype *type;
564
565 char buf[sizeof("65535-65535\0")];
566
567 struct uci_ptr ptr = { .p = dest };
568
569 if (!s->enabled || s->external)
570 return;
571
572 uci_add_section(ctx, dest, "ipset", &ptr.s);
573
574 ptr.o = NULL;
575 ptr.option = "name";
576 ptr.value = s->name;
577 uci_set(ctx, &ptr);
578
579 ptr.o = NULL;
580 ptr.option = "storage";
581 ptr.value = fw3_ipset_method_names[s->method];
582 uci_set(ctx, &ptr);
583
584 list_for_each_entry(type, &s->datatypes, list)
585 {
586 sprintf(buf, "%s_%s", type->dir, fw3_ipset_type_names[type->type]);
587 ptr.o = NULL;
588 ptr.option = "match";
589 ptr.value = buf;
590 uci_add_list(ctx, &ptr);
591 }
592
593 if (s->iprange.set)
594 {
595 ptr.o = NULL;
596 ptr.option = "iprange";
597 ptr.value = fw3_address_to_string(&s->iprange, false, false);
598 uci_set(ctx, &ptr);
599 }
600
601 if (s->portrange.set)
602 {
603 sprintf(buf, "%u-%u", s->portrange.port_min, s->portrange.port_max);
604 ptr.o = NULL;
605 ptr.option = "portrange";
606 ptr.value = buf;
607 uci_set(ctx, &ptr);
608 }
609 }
610
611 void
612 fw3_write_statefile(void *state)
613 {
614 FILE *sf;
615 struct fw3_state *s = state;
616 struct fw3_zone *z;
617 struct fw3_ipset *i;
618 struct ifaddrs *ifaddr;
619
620 struct uci_package *p;
621
622 if (fw3_no_family(s->defaults.flags[0]) &&
623 fw3_no_family(s->defaults.flags[1]))
624 {
625 unlink(FW3_STATEFILE);
626 }
627 else
628 {
629 sf = fopen(FW3_STATEFILE, "w+");
630
631 if (!sf)
632 {
633 warn("Cannot create state %s: %s", FW3_STATEFILE, strerror(errno));
634 return;
635 }
636
637 if (getifaddrs(&ifaddr))
638 {
639 warn("Cannot get interface addresses: %s", strerror(errno));
640 ifaddr = NULL;
641 }
642
643 if ((p = uci_lookup_package(s->uci, "fw3_state")) != NULL)
644 uci_unload(s->uci, p);
645
646 uci_import(s->uci, sf, "fw3_state", NULL, true);
647
648 if ((p = uci_lookup_package(s->uci, "fw3_state")) != NULL)
649 {
650 write_defaults_uci(s->uci, &s->defaults, p);
651
652 list_for_each_entry(z, &s->zones, list)
653 write_zone_uci(s->uci, z, p, ifaddr);
654
655 list_for_each_entry(i, &s->ipsets, list)
656 write_ipset_uci(s->uci, i, p);
657
658 uci_export(s->uci, sf, p, true);
659 uci_unload(s->uci, p);
660 }
661
662 fsync(fileno(sf));
663 fclose(sf);
664
665 if (ifaddr)
666 freeifaddrs(ifaddr);
667 }
668 }
669
670
671 void
672 fw3_free_object(void *obj, const void *opts)
673 {
674 const struct fw3_option *ol;
675 struct list_head *list, *cur, *tmp;
676
677 for (ol = opts; ol->name; ol++)
678 {
679 if (!ol->elem_size)
680 continue;
681
682 list = (struct list_head *)((char *)obj + ol->offset);
683 list_for_each_safe(cur, tmp, list)
684 {
685 list_del(cur);
686 free(cur);
687 }
688 }
689
690 free(obj);
691 }
692
693 void
694 fw3_free_list(struct list_head *head)
695 {
696 struct list_head *entry, *tmp;
697
698 if (!head)
699 return;
700
701 list_for_each_safe(entry, tmp, head)
702 {
703 list_del(entry);
704 free(entry);
705 }
706
707 free(head);
708 }
709
710 bool
711 fw3_hotplug(bool add, void *zone, void *device)
712 {
713 struct fw3_zone *z = zone;
714 struct fw3_device *d = device;
715
716 if (!*d->network)
717 return false;
718
719 switch (fork())
720 {
721 case -1:
722 warn("Unable to fork(): %s\n", strerror(errno));
723 return false;
724
725 case 0:
726 break;
727
728 default:
729 return true;
730 }
731
732 close(0);
733 close(1);
734 close(2);
735 if (chdir("/")) {};
736
737 clearenv();
738 setenv("ACTION", add ? "add" : "remove", 1);
739 setenv("ZONE", z->name, 1);
740 setenv("INTERFACE", d->network, 1);
741 setenv("DEVICE", d->name, 1);
742
743 execl(FW3_HOTPLUG, FW3_HOTPLUG, "firewall", NULL);
744
745 /* unreached */
746 return false;
747 }
748
749 int
750 fw3_netmask2bitlen(int family, void *mask)
751 {
752 int bits;
753 struct in_addr *v4;
754 struct in6_addr *v6;
755
756 if (family == FW3_FAMILY_V6)
757 for (bits = 0, v6 = mask;
758 bits < 128 && (v6->s6_addr[bits / 8] << (bits % 8)) & 128;
759 bits++);
760 else
761 for (bits = 0, v4 = mask;
762 bits < 32 && (ntohl(v4->s_addr) << bits) & 0x80000000;
763 bits++);
764
765 return bits;
766 }
767
768 bool
769 fw3_bitlen2netmask(int family, int bits, void *mask)
770 {
771 int i;
772 uint8_t rem, b;
773 struct in_addr *v4;
774 struct in6_addr *v6;
775
776 if (family == FW3_FAMILY_V6)
777 {
778 if (bits < -128 || bits > 128)
779 return false;
780
781 v6 = mask;
782 rem = abs(bits);
783
784 for (i = 0; i < sizeof(v6->s6_addr); i++)
785 {
786 b = (rem > 8) ? 8 : rem;
787 v6->s6_addr[i] = (uint8_t)(0xFF << (8 - b));
788 rem -= b;
789 }
790
791 if (bits < 0)
792 for (i = 0; i < sizeof(v6->s6_addr); i++)
793 v6->s6_addr[i] = ~v6->s6_addr[i];
794 }
795 else
796 {
797 if (bits < -32 || bits > 32)
798 return false;
799
800 v4 = mask;
801 v4->s_addr = bits ? htonl(~((1 << (32 - abs(bits))) - 1)) : 0;
802
803 if (bits < 0)
804 v4->s_addr = ~v4->s_addr;
805 }
806
807 return true;
808 }
809
810 void
811 fw3_flush_conntrack(void *state)
812 {
813 bool found;
814 struct fw3_state *s = state;
815 struct fw3_address *addr;
816 struct fw3_device *dev;
817 struct fw3_zone *zone;
818 struct ifaddrs *ifaddr, *ifa;
819 struct sockaddr_in *sin;
820 struct sockaddr_in6 *sin6;
821 char buf[INET6_ADDRSTRLEN];
822 FILE *ct;
823
824 if (!state)
825 {
826 if ((ct = fopen("/proc/net/nf_conntrack", "w")) != NULL)
827 {
828 info(" * Flushing conntrack table ...");
829
830 fwrite("f\n", 1, 2, ct);
831 fclose(ct);
832 }
833
834 return;
835 }
836
837 if (getifaddrs(&ifaddr))
838 {
839 warn("Cannot get interface addresses: %s", strerror(errno));
840 return;
841 }
842
843 if ((ct = fopen("/proc/net/nf_conntrack", "w")) != NULL)
844 {
845 list_for_each_entry(zone, &s->zones, list)
846 list_for_each_entry(addr, &zone->old_addrs, list)
847 {
848 found = false;
849
850 list_for_each_entry(dev, &zone->devices, list)
851 {
852 for (ifa = ifaddr; ifa && !found; ifa = ifa->ifa_next)
853 {
854 if (!ifa->ifa_addr || strcmp(dev->name, ifa->ifa_name))
855 continue;
856
857 sin = (struct sockaddr_in *)ifa->ifa_addr;
858 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
859
860 if (addr->family == FW3_FAMILY_V4 &&
861 sin->sin_family == AF_INET)
862 {
863 found = !memcmp(&addr->address.v4, &sin->sin_addr,
864 sizeof(sin->sin_addr));
865 }
866 else if (addr->family == FW3_FAMILY_V6 &&
867 sin6->sin6_family == AF_INET6)
868 {
869 found = !memcmp(&addr->address.v6, &sin6->sin6_addr,
870 sizeof(sin6->sin6_addr));
871 }
872 }
873
874 if (found)
875 break;
876 }
877
878 if (!found)
879 {
880 inet_ntop(addr->family == FW3_FAMILY_V4 ? AF_INET : AF_INET6,
881 &addr->address.v4, buf, sizeof(buf));
882
883 info(" * Flushing conntrack: %s", buf);
884 fprintf(ct, "%s\n", buf);
885 }
886 }
887
888 fclose(ct);
889 }
890
891 freeifaddrs(ifaddr);
892 }