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