Split runtime and config states, store runtime state in UCI format
[project/firewall3.git] / main.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 <stdio.h>
20 #include <unistd.h>
21
22 #include "options.h"
23 #include "defaults.h"
24 #include "zones.h"
25 #include "rules.h"
26 #include "redirects.h"
27 #include "forwards.h"
28 #include "ipsets.h"
29 #include "includes.h"
30 #include "ubus.h"
31
32
33 static bool print_rules = false;
34
35 static struct fw3_state *run_state = NULL;
36 static struct fw3_state *cfg_state = NULL;
37
38
39 static bool
40 build_state(bool runtime)
41 {
42         struct fw3_state *state = NULL;
43         struct uci_package *p = NULL;
44         FILE *sf;
45
46         state = malloc(sizeof(*state));
47
48         if (!state)
49                 error("Out of memory");
50
51         memset(state, 0, sizeof(*state));
52         state->uci = uci_alloc_context();
53
54         if (!state->uci)
55                 error("Out of memory");
56
57         if (runtime)
58         {
59                 sf = fopen(FW3_STATEFILE, "r");
60
61                 if (sf)
62                 {
63                         uci_import(state->uci, sf, "fw3_state", &p, true);
64                         fclose(sf);
65                 }
66
67                 if (!p)
68                 {
69                         uci_free_context(state->uci);
70                         free(state);
71
72                         return false;
73                 }
74
75                 state->statefile = true;
76
77                 run_state = state;
78         }
79         else
80         {
81                 if (!fw3_ubus_connect())
82                         error("Failed to connect to ubus");
83
84                 if (uci_load(state->uci, "firewall", &p))
85                 {
86                         uci_perror(state->uci, NULL);
87                         error("Failed to load /etc/config/firewall");
88                 }
89
90                 if (!fw3_find_command("ipset"))
91                 {
92                         warn("Unable to locate ipset utility, disabling ipset support");
93                         state->disable_ipsets = true;
94                 }
95
96                 cfg_state = state;
97         }
98
99         fw3_load_defaults(state, p);
100         fw3_load_ipsets(state, p);
101         fw3_load_zones(state, p);
102         fw3_load_rules(state, p);
103         fw3_load_redirects(state, p);
104         fw3_load_forwards(state, p);
105         fw3_load_includes(state, p);
106
107         return true;
108 }
109
110 static void
111 free_state(struct fw3_state *state)
112 {
113         struct list_head *cur, *tmp;
114
115         list_for_each_safe(cur, tmp, &state->zones)
116                 fw3_free_zone((struct fw3_zone *)cur);
117
118         list_for_each_safe(cur, tmp, &state->rules)
119                 fw3_free_rule((struct fw3_rule *)cur);
120
121         list_for_each_safe(cur, tmp, &state->redirects)
122                 fw3_free_redirect((struct fw3_redirect *)cur);
123
124         list_for_each_safe(cur, tmp, &state->forwards)
125                 fw3_free_forward((struct fw3_forward *)cur);
126
127         list_for_each_safe(cur, tmp, &state->ipsets)
128                 fw3_free_ipset((struct fw3_ipset *)cur);
129
130         list_for_each_safe(cur, tmp, &state->includes)
131                 fw3_free_include((struct fw3_include *)cur);
132
133         uci_free_context(state->uci);
134
135         free(state);
136
137         fw3_ubus_disconnect();
138 }
139
140
141 static bool
142 restore_pipe(enum fw3_family family, bool silent)
143 {
144         const char *cmd;
145
146         cmd = (family == FW3_FAMILY_V4) ? "iptables-restore" : "ip6tables-restore";
147
148         if (print_rules)
149                 return fw3_stdout_pipe();
150
151         if (!fw3_command_pipe(silent, cmd, "--lenient", "--noflush"))
152         {
153                 warn("Unable to execute %s", cmd);
154                 return false;
155         }
156
157         return true;
158 }
159
160 static bool
161 family_running(enum fw3_family family)
162 {
163         return (run_state && has(run_state->defaults.flags, family, family));
164 }
165
166 static void
167 family_set(struct fw3_state *state, enum fw3_family family, bool set)
168 {
169         if (!state)
170                 return;
171
172         if (set)
173                 set(state->defaults.flags, family, family);
174         else
175                 del(state->defaults.flags, family, family);
176 }
177
178 static int
179 stop(bool complete, bool reload)
180 {
181         FILE *ct;
182
183         int rv = 1;
184         enum fw3_family family;
185         enum fw3_table table;
186
187         if (!complete && !run_state)
188         {
189                 if (!reload)
190                         warn("The firewall appears to be stopped. "
191                                  "Use the 'flush' command to forcefully purge all rules.");
192
193                 return rv;
194         }
195
196         if (!print_rules && run_state)
197                 fw3_hotplug_zones(run_state, false);
198
199         for (family = FW3_FAMILY_V4; family <= FW3_FAMILY_V6; family++)
200         {
201                 if (!complete && !family_running(family))
202                         continue;
203
204                 if (!restore_pipe(family, true))
205                         continue;
206
207                 for (table = FW3_TABLE_FILTER; table <= FW3_TABLE_RAW; table++)
208                 {
209                         if (!fw3_has_table(family == FW3_FAMILY_V6, fw3_flag_names[table]))
210                                 continue;
211
212                         info(" * %sing %s %s table", complete ? "Flush" : "Clear",
213                              fw3_flag_names[family], fw3_flag_names[table]);
214
215                         fw3_pr("*%s\n", fw3_flag_names[table]);
216
217                         if (complete)
218                         {
219                                 fw3_flush_all(table);
220                         }
221                         else if (run_state)
222                         {
223                                 /* pass 1 */
224                                 fw3_flush_rules(run_state, family, table, reload, false);
225                                 fw3_flush_zones(run_state, family, table, reload, false);
226
227                                 /* pass 2 */
228                                 fw3_flush_rules(run_state, family, table, reload, true);
229                                 fw3_flush_zones(run_state, family, table, reload, true);
230                         }
231
232                         fw3_pr("COMMIT\n");
233                 }
234
235                 fw3_command_close();
236
237                 if (!reload && run_state)
238                 {
239                         if (fw3_command_pipe(false, "ipset", "-exist", "-"))
240                         {
241                                 fw3_destroy_ipsets(run_state, family);
242                                 fw3_command_close();
243                         }
244
245                         family_set(run_state, family, false);
246                         family_set(cfg_state, family, false);
247                 }
248
249                 rv = 0;
250         }
251
252         if (complete && (ct = fopen("/proc/net/nf_conntrack", "w")) != NULL)
253         {
254                 info(" * Flushing conntrack table ...");
255
256                 fwrite("f\n", 2, 1, ct);
257                 fclose(ct);
258         }
259
260         if (!rv && run_state)
261                 fw3_write_statefile(run_state);
262
263         return rv;
264 }
265
266 static int
267 start(bool reload)
268 {
269         int rv = 1;
270         enum fw3_family family;
271         enum fw3_table table;
272
273         if (!print_rules && !reload)
274         {
275                 if (fw3_command_pipe(false, "ipset", "-exist", "-"))
276                 {
277                         fw3_create_ipsets(cfg_state);
278                         fw3_command_close();
279                 }
280         }
281
282         for (family = FW3_FAMILY_V4; family <= FW3_FAMILY_V6; family++)
283         {
284                 if (family == FW3_FAMILY_V6 && cfg_state->defaults.disable_ipv6)
285                         continue;
286
287                 if (!print_rules && !reload && family_running(family))
288                 {
289                         warn("The %s firewall appears to be started already. "
290                              "If it is indeed empty, remove the %s file and retry.",
291                              fw3_flag_names[family], FW3_STATEFILE);
292
293                         continue;
294                 }
295
296                 if (!restore_pipe(family, false))
297                         continue;
298
299                 for (table = FW3_TABLE_FILTER; table <= FW3_TABLE_RAW; table++)
300                 {
301                         if (!fw3_has_table(family == FW3_FAMILY_V6, fw3_flag_names[table]))
302                                 continue;
303
304                         info(" * Populating %s %s table",
305                              fw3_flag_names[family], fw3_flag_names[table]);
306
307                         fw3_pr("*%s\n", fw3_flag_names[table]);
308                         fw3_print_default_chains(cfg_state, family, table, reload);
309                         fw3_print_zone_chains(cfg_state, family, table, reload);
310                         fw3_print_default_head_rules(cfg_state, family, table, reload);
311                         fw3_print_rules(cfg_state, family, table);
312                         fw3_print_redirects(cfg_state, family, table);
313                         fw3_print_forwards(cfg_state, family, table);
314                         fw3_print_zone_rules(cfg_state, family, table, reload);
315                         fw3_print_default_tail_rules(cfg_state, family, table, reload);
316                         fw3_pr("COMMIT\n");
317                 }
318
319                 fw3_print_includes(cfg_state, family, reload);
320
321                 fw3_command_close();
322                 family_set(run_state, family, true);
323                 family_set(cfg_state, family, true);
324
325                 rv = 0;
326         }
327
328         if (!rv)
329         {
330                 fw3_set_defaults(cfg_state);
331
332                 if (!print_rules)
333                 {
334                         fw3_run_includes(cfg_state, reload);
335                         fw3_hotplug_zones(cfg_state, true);
336                         fw3_write_statefile(cfg_state);
337                 }
338         }
339
340         return rv;
341 }
342
343 static int
344 lookup_network(const char *net)
345 {
346         struct fw3_zone *z;
347         struct fw3_device *d;
348
349         list_for_each_entry(z, &cfg_state->zones, list)
350         {
351                 list_for_each_entry(d, &z->networks, list)
352                 {
353                         if (!strcmp(d->name, net))
354                         {
355                                 printf("%s\n", z->name);
356                                 return 0;
357                         }
358                 }
359         }
360
361         return 1;
362 }
363
364 static int
365 lookup_device(const char *dev)
366 {
367         struct fw3_zone *z;
368         struct fw3_device *d;
369
370         list_for_each_entry(z, &cfg_state->zones, list)
371         {
372                 list_for_each_entry(d, &z->devices, list)
373                 {
374                         if (!strcmp(d->name, dev))
375                         {
376                                 printf("%s\n", z->name);
377                                 return 0;
378                         }
379                 }
380         }
381
382         return 1;
383 }
384
385 static int
386 usage(void)
387 {
388         fprintf(stderr, "fw3 [-4] [-6] [-q] print\n");
389         fprintf(stderr, "fw3 [-q] {start|stop|flush|reload|restart}\n");
390         fprintf(stderr, "fw3 [-q] network {net}\n");
391         fprintf(stderr, "fw3 [-q] device {dev}\n");
392
393         return 1;
394 }
395
396
397 int main(int argc, char **argv)
398 {
399         int ch, rv = 1;
400         struct fw3_defaults *defs = NULL;
401         enum fw3_family use_family = FW3_FAMILY_ANY;
402
403         while ((ch = getopt(argc, argv, "46dqh")) != -1)
404         {
405                 switch (ch)
406                 {
407                 case '4':
408                         use_family = FW3_FAMILY_V4;
409                         break;
410
411                 case '6':
412                         use_family = FW3_FAMILY_V6;
413                         break;
414
415                 case 'd':
416                         fw3_pr_debug = true;
417                         break;
418
419                 case 'q':
420                         freopen("/dev/null", "w", stderr);
421                         break;
422
423                 case 'h':
424                         rv = usage();
425                         goto out;
426                 }
427         }
428
429         build_state(false);
430         build_state(true);
431         defs = &cfg_state->defaults;
432
433         if (optind >= argc)
434         {
435                 rv = usage();
436                 goto out;
437         }
438
439         if (!strcmp(argv[optind], "print"))
440         {
441                 if (use_family == FW3_FAMILY_ANY)
442                         use_family = FW3_FAMILY_V4;
443                 else if (use_family == FW3_FAMILY_V6 && defs->disable_ipv6)
444                         warn("IPv6 rules globally disabled in configuration");
445
446                 freopen("/dev/null", "w", stderr);
447
448                 cfg_state->disable_ipsets = true;
449                 print_rules = true;
450
451                 rv = start(false);
452         }
453         else if (!strcmp(argv[optind], "start"))
454         {
455                 if (fw3_lock())
456                 {
457                         rv = start(false);
458                         fw3_unlock();
459                 }
460         }
461         else if (!strcmp(argv[optind], "stop"))
462         {
463                 if (fw3_lock())
464                 {
465                         rv = stop(false, false);
466                         fw3_unlock();
467                 }
468         }
469         else if (!strcmp(argv[optind], "flush"))
470         {
471                 if (fw3_lock())
472                 {
473                         rv = stop(true, false);
474                         fw3_unlock();
475                 }
476         }
477         else if (!strcmp(argv[optind], "restart"))
478         {
479                 if (fw3_lock())
480                 {
481                         stop(true, false);
482                         rv = start(false);
483
484                         fw3_unlock();
485                 }
486         }
487         else if (!strcmp(argv[optind], "reload"))
488         {
489                 if (fw3_lock())
490                 {
491                         rv = stop(false, true);
492                         rv = start(!rv);
493
494                         fw3_unlock();
495                 }
496         }
497         else if (!strcmp(argv[optind], "network") && (optind + 1) < argc)
498         {
499                 rv = lookup_network(argv[optind + 1]);
500         }
501         else if (!strcmp(argv[optind], "device") && (optind + 1) < argc)
502         {
503                 rv = lookup_device(argv[optind + 1]);
504         }
505         else
506         {
507                 rv = usage();
508         }
509
510 out:
511         if (cfg_state)
512                 free_state(cfg_state);
513
514         if (run_state)
515                 free_state(run_state);
516
517         return rv;
518 }