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