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