Clarify zone names
[pve-firewall.git] / PVE / Firewall.pm
CommitLineData
b6360c3f
DM
1package PVE::Firewall;
2
3use warnings;
4use strict;
5use Data::Dumper;
f789653a 6use PVE::Tools;
b6360c3f 7use PVE::QemuServer;
5e1267a5
DM
8use File::Path;
9use IO::File;
ecbea048
DM
10use Net::IP;
11
5e1267a5 12use Data::Dumper;
b6360c3f 13
9aab3127
DM
14my $macros;
15sub get_shorewall_macros {
16
17 return $macros if $macros;
18
19 foreach my $path (</usr/share/shorewall/macro.*>) {
20 if ($path =~ m|/macro\.(\S+)$|) {
21 $macros->{$1} = 1;
22 }
23 }
24 return $macros;
25}
26
fcba0beb
DM
27my $etc_services;
28
29sub get_etc_services {
30
31 return $etc_services if $etc_services;
32
33 my $filename = "/etc/services";
34
35 my $fh = IO::File->new($filename, O_RDONLY);
36 if (!$fh) {
37 warn "unable to read '$filename' - $!\n";
38 return {};
39 }
40
41 my $services = {};
42
43 while (my $line = <$fh>) {
44 chomp ($line);
45 next if $line =~m/^#/;
46 next if ($line =~m/^\s*$/);
47
48 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
49 $services->{byid}->{$2}->{name} = $1;
50 $services->{byid}->{$2}->{$3} = 1;
51 $services->{byname}->{$1} = $services->{byid}->{$2};
52 }
53 }
54
55 close($fh);
56
57 $etc_services = $services;
58
59 return $etc_services;
60}
61
62my $etc_protocols;
63
64sub get_etc_protocols {
65 return $etc_protocols if $etc_protocols;
66
67 my $filename = "/etc/protocols";
68
69 my $fh = IO::File->new($filename, O_RDONLY);
70 if (!$fh) {
71 warn "unable to read '$filename' - $!\n";
72 return {};
73 }
74
75 my $protocols = {};
76
77 while (my $line = <$fh>) {
78 chomp ($line);
79 next if $line =~m/^#/;
80 next if ($line =~m/^\s*$/);
81
82 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
83 $protocols->{byid}->{$2}->{name} = $1;
84 $protocols->{byname}->{$1} = $protocols->{byid}->{$2};
85 }
86 }
87
88 close($fh);
89
90 $etc_protocols = $protocols;
91
92 return $etc_protocols;
93}
94
ecbea048
DM
95sub parse_address_list {
96 my ($str) = @_;
97
98 foreach my $aor (split(/,/, $str)) {
99 if (!Net::IP->new($aor)) {
100 my $err = Net::IP::Error();
101 die "invalid IP address: $err\n";
102 }
103 }
104}
dddd9413 105
fcba0beb
DM
106sub parse_port_name_number_or_range {
107 my ($str) = @_;
108
109 my $services = PVE::Firewall::get_etc_services();
110
111 foreach my $item (split(/,/, $str)) {
112 foreach my $pon (split(':', $item, 2)) {
113 next if $pon =~ m/^\d+$/ && $pon > 0 && $pon < 65536;
114 next if defined($services->{byname}->{$pon});
115 die "invalid port '$pon'\n";
116 }
117 }
118
119}
120
8cebfa6f 121my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
dddd9413
DM
122
123my $generate_input_rule = sub {
124 my ($zoneinfo, $rule, $net, $netid) = @_;
125
dddd9413 126 my $zone = $net->{zone} || die "internal error";
a8195f4f 127 my $zid = $zoneinfo->{$zone}->{zoneref} || die "internal error";
dddd9413 128 my $tap = $net->{tap} || die "internal error";
9aab3127 129
8cebfa6f
DM
130 my $dest = "$zid:$tap";
131
132 if ($rule->{dest}) {
133 $dest .= ":$rule->{dest}";
134 }
135
9aab3127
DM
136 my $action = $rule->{service} ?
137 "$rule->{service}($rule->{action})" : $rule->{action};
138
b9b06789 139 my $sources = [];
8cebfa6f 140
b9b06789
DM
141 if (!$rule->{source}) {
142 push @$sources, 'all';
143 } elsif ($zoneinfo->{$zone}->{type} eq 'bport') {
8cebfa6f 144 my $bridge_zone = $zoneinfo->{$zone}->{bridge_zone} || die "internal error";
b9b06789
DM
145 my $zoneref = $zoneinfo->{$bridge_zone}->{zoneref} || die "internal error";
146
147 # using 'all' does not work, so we create one rule for
148 # each related zone on the same bridge
149 push @$sources, "${zoneref}:$rule->{source}";
150 foreach my $z (keys %$zoneinfo) {
151 next if $z eq $zone;
152 next if !$zoneinfo->{$z}->{bridge_zone};
153 next if $zoneinfo->{$z}->{bridge_zone} ne $bridge_zone;
154 $zoneref = $zoneinfo->{$z}->{zoneref} || die "internal error";
155 push @$sources, "${zoneref}:$rule->{source}";
8cebfa6f
DM
156 }
157 } else {
b9b06789
DM
158 push @$sources, "all:$rule->{source}";
159 }
160
161 my $out = '';
162
163 foreach my $source (@$sources) {
164 $out .= sprintf($rule_format, $action, $source, $dest, $rule->{proto} || '-',
165 $rule->{dport} || '-', $rule->{sport} || '-');
8cebfa6f
DM
166 }
167
b9b06789 168 return $out;
dddd9413
DM
169};
170
171my $generate_output_rule = sub {
172 my ($zoneinfo, $rule, $net, $netid) = @_;
173
dddd9413 174 my $zone = $net->{zone} || die "internal error";
a8195f4f 175 my $zid = $zoneinfo->{$zone}->{zoneref} || die "internal error";
dddd9413 176 my $tap = $net->{tap} || die "internal error";
9aab3127
DM
177
178 my $action = $rule->{service} ?
179 "$rule->{service}($rule->{action})" : $rule->{action};
dddd9413 180
8cebfa6f
DM
181 my $dest;
182
183 if (!$rule->{dest}) {
9a4644fa 184 $dest = 'all';
8cebfa6f 185 } else {
9a4644fa 186 $dest = "all:$rule->{dest}";
8cebfa6f
DM
187 }
188
189 return sprintf($rule_format, $action, "$zid:$tap", $dest,
dddd9413
DM
190 $rule->{proto} || '-', $rule->{dport} || '-', $rule->{sport} || '-');
191};
192
b6360c3f
DM
193# we need complete VM configuration of all VMs (openvz/qemu)
194# in vmdata
195
5e1267a5 196my $compile_shorewall = sub {
dddd9413 197 my ($targetdir, $vmdata, $rules) = @_;
b6360c3f 198
80bfe1ff 199 # remove existing data ?
a8195f4f 200 foreach my $file (qw(params zones rules interfaces maclist policy)) {
80bfe1ff
DM
201 unlink "$targetdir/$file";
202 }
203
b6360c3f
DM
204 my $netinfo;
205
886aba9c
DM
206 my $zoneinfo = {
207 fw => { type => 'firewall' },
208 };
209
026a6466
DM
210 my $maclist = {};
211
35081236
DM
212 my $register_bridge;
213
214 $register_bridge = sub {
215 my ($bridge, $vlan) = @_;
f789653a 216
1b6a0a59 217 my $zone = $bridge;
f789653a
DM
218
219 return $zone if $zoneinfo->{$zone};
220
1b6a0a59 221 my $ext_zone = "${bridge}_ext";
8cebfa6f 222
f789653a
DM
223 $zoneinfo->{$zone} = {
224 type => 'bridge',
225 bridge => $bridge,
8cebfa6f
DM
226 bridge_ext_zone => $ext_zone,
227 };
228
229 # physical input devices
230 my $dir = "/sys/class/net/$bridge/brif";
231 my $physical = {};
232 PVE::Tools::dir_glob_foreach($dir, '((eth|bond).+)', sub {
233 my ($slave) = @_;
234 $physical->{$slave} = 1;
235 });
236
237 $zoneinfo->{$ext_zone} = {
238 type => 'bport',
239 bridge_zone => $zone,
240 ifaces => $physical,
f789653a 241 };
35081236
DM
242
243 return &$register_bridge("${bridge}v${vlan}") if defined($vlan);
244
245 return $zone;
246 };
247
248 my $register_bridge_port = sub {
249 my ($bridge, $vlan, $vmzone, $tap) = @_;
250
251 my $bridge_zone = &$register_bridge($bridge, $vlan);
1b6a0a59 252 my $zone = $bridge_zone . '_' . $vmzone;
35081236
DM
253
254 if (!$zoneinfo->{$zone}) {
255 $zoneinfo->{$zone} = {
256 type => 'bport',
257 bridge_zone => $bridge_zone,
258 ifaces => {},
259 };
260 }
261
262 $zoneinfo->{$zone}->{ifaces}->{$tap} = 1;
f789653a
DM
263
264 return $zone;
265 };
266
b6360c3f
DM
267 foreach my $vmid (keys %{$vmdata->{qemu}}) {
268 $netinfo->{$vmid} = {};
269 my $conf = $vmdata->{qemu}->{$vmid};
270 foreach my $opt (keys %$conf) {
271 next if $opt !~ m/^net(\d+)$/;
dddd9413 272 my $netnum = $1;
b6360c3f
DM
273 my $net = PVE::QemuServer::parse_net($conf->{$opt});
274 next if !$net;
886aba9c 275 die "implement me" if !$net->{bridge};
886aba9c 276
f789653a 277 my $vmzone = $conf->{zone} || "vm$vmid";
dddd9413 278 $net->{tap} = "tap${vmid}i${netnum}";
026a6466 279 $maclist->{$net->{tap}} = $net->{macaddr} || die "internal error";
dddd9413
DM
280 $net->{zone} = &$register_bridge_port($net->{bridge}, $net->{tag}, $vmzone, $net->{tap});
281 $netinfo->{$vmid}->{$opt} = $net;
886aba9c
DM
282 }
283 }
284
285 #print Dumper($netinfo);
286
f789653a 287 # NOTE: zone names have length limit, so we need to
886aba9c
DM
288 # translate them into shorter names
289
f789653a
DM
290 my $zoneid = 0;
291 my $zonemap = { fw => 'fw' };
292
293 my $lookup_zonename = sub {
294 my ($zone) = @_;
295
296 return $zonemap->{$zone} if defined($zonemap->{$zone});
297 $zonemap->{$zone} = 'z' . $zoneid++;
298
299 return $zonemap->{$zone};
300 };
301
dddd9413
DM
302 foreach my $z (sort keys %$zoneinfo) {
303 $zoneinfo->{$z}->{id} = &$lookup_zonename($z);
a8195f4f
DM
304 $zoneinfo->{$z}->{zonevar} = uc($z);
305 $zoneinfo->{$z}->{zoneref} = '$' . $zoneinfo->{$z}->{zonevar};
dddd9413
DM
306 }
307
f789653a 308 my $out;
886aba9c 309
a8195f4f
DM
310 # dump params file
311 $out = "# PVE zones\n";
312 foreach my $z (sort keys %$zoneinfo) {
313 $out .= "$zoneinfo->{$z}->{zonevar}=$zoneinfo->{$z}->{id}\n";
314 }
315 PVE::Tools::file_set_contents("$targetdir/params", $out);
316
317 # dump zone file
318
319 my $format = "%-30s %-10s %-15s\n";
320 $out = sprintf($format, '#ZONE', 'TYPE', 'OPTIONS');
f789653a 321
886aba9c 322 foreach my $z (sort keys %$zoneinfo) {
a8195f4f 323 my $zid = $zoneinfo->{$z}->{zoneref};
f789653a 324 if ($zoneinfo->{$z}->{type} eq 'firewall') {
a8195f4f 325 $out .= sprintf($format, $zid, $zoneinfo->{$z}->{type}, '');
f789653a 326 } elsif ($zoneinfo->{$z}->{type} eq 'bridge') {
a8195f4f 327 $out .= sprintf($format, $zid, 'ipv4', '');
f789653a
DM
328 } elsif ($zoneinfo->{$z}->{type} eq 'bport') {
329 my $bridge_zone = $zoneinfo->{$z}->{bridge_zone} || die "internal error";
a8195f4f
DM
330 my $bzid = $zoneinfo->{$bridge_zone}->{zoneref} || die "internal error";
331 $out .= sprintf($format, "$zid:$bzid", 'bport', '');
f789653a
DM
332 } else {
333 die "internal error";
334 }
886aba9c
DM
335 }
336
f789653a
DM
337 $out .= sprintf("#LAST LINE - ADD YOUR ENTRIES ABOVE THIS ONE - DO NOT REMOVE\n");
338
339 PVE::Tools::file_set_contents("$targetdir/zones", $out);
886aba9c 340
f789653a 341 # dump interfaces
886aba9c 342
a8195f4f
DM
343 $format = "%-25s %-20s %-10s %-15s\n";
344 $out = sprintf($format, '#ZONE', 'INTERFACE', 'BROADCAST', 'OPTIONS');
f789653a 345
026a6466
DM
346 my $maclist_format = "%-15s %-15s %-15s\n";
347 my $macs = sprintf($maclist_format, '#DISPOSITION', 'INTERFACE', 'MACZONE');
348
886aba9c 349 foreach my $z (sort keys %$zoneinfo) {
a8195f4f 350 my $zid = $zoneinfo->{$z}->{zoneref};
f789653a
DM
351 if ($zoneinfo->{$z}->{type} eq 'firewall') {
352 # do nothing;
353 } elsif ($zoneinfo->{$z}->{type} eq 'bridge') {
354 my $bridge = $zoneinfo->{$z}->{bridge} || die "internal error";
a8195f4f 355 $out .= sprintf($format, $zid, $bridge, 'detect', 'bridge,optional');
f789653a
DM
356 } elsif ($zoneinfo->{$z}->{type} eq 'bport') {
357 my $ifaces = $zoneinfo->{$z}->{ifaces};
358 foreach my $iface (sort keys %$ifaces) {
359 my $bridge_zone = $zoneinfo->{$z}->{bridge_zone} || die "internal error";
360 my $bridge = $zoneinfo->{$bridge_zone}->{bridge} || die "internal error";
361 my $iftxt = "$bridge:$iface";
8cebfa6f
DM
362
363 if ($maclist->{$iface}) {
364 $out .= sprintf($format, $zid, $iftxt, '-', 'maclist');
365 $macs .= sprintf($maclist_format, 'ACCEPT', $iface, $maclist->{$iface});
366 } else {
367 $out .= sprintf($format, $zid, $iftxt, '-', '');
368 }
f789653a
DM
369 }
370 } else {
371 die "internal error";
b6360c3f
DM
372 }
373 }
374
f789653a
DM
375 $out .= sprintf("#LAST LINE - ADD YOUR ENTRIES ABOVE THIS ONE - DO NOT REMOVE\n");
376
377 PVE::Tools::file_set_contents("$targetdir/interfaces", $out);
378
026a6466
DM
379 # dump maclist
380 PVE::Tools::file_set_contents("$targetdir/maclist", $macs);
381
f789653a
DM
382 # dump policy
383
384 $format = "%-15s %-15s %-15s %s\n";
385 $out = sprintf($format, '#SOURCE', 'DEST', 'POLICY', 'LOG');
8cebfa6f
DM
386 $out .= sprintf($format, 'fw', 'all', 'ACCEPT', '');
387
388 # we need to disable intra-zone traffic on bridges. Else traffic
389 # from untracked interfaces simply pass the firewall
390 foreach my $z (sort keys %$zoneinfo) {
391 my $zid = $zoneinfo->{$z}->{zoneref};
392 if ($zoneinfo->{$z}->{type} eq 'bridge') {
393 $out .= sprintf($format, $zid, $zid, 'REJECT', 'info');
394 }
395 }
f789653a 396 $out .= sprintf($format, 'all', 'all', 'REJECT', 'info');
886aba9c 397
f789653a 398 PVE::Tools::file_set_contents("$targetdir/policy", $out);
886aba9c 399
dddd9413
DM
400 # dump rules
401 $out = '';
402
403 $out = sprintf($rule_format, '#ACTION', 'SOURCE', 'DEST', 'PROTO', 'DPORT', 'SPORT');
404 foreach my $vmid (sort keys %$rules) {
78db5872
DM
405 my $inrules = $rules->{$vmid}->{in};
406 my $outrules = $rules->{$vmid}->{out};
407
408 if (scalar(@$inrules)) {
409 $out .= "# IN to VM $vmid\n";
dddd9413
DM
410 foreach my $rule (@$inrules) {
411 foreach my $netid (keys %{$netinfo->{$vmid}}) {
412 my $net = $netinfo->{$vmid}->{$netid};
9a4644fa 413 next if $rule->{iface} && $rule->{iface} ne $netid;
dddd9413
DM
414 $out .= &$generate_input_rule($zoneinfo, $rule, $net, $netid);
415 }
416 }
417 }
418
78db5872
DM
419 if (scalar(@$outrules)) {
420 $out .= "# OUT from VM $vmid\n";
dddd9413
DM
421 foreach my $rule (@$outrules) {
422 foreach my $netid (keys %{$netinfo->{$vmid}}) {
423 my $net = $netinfo->{$vmid}->{$netid};
9a4644fa 424 next if $rule->{iface} && $rule->{iface} ne $netid;
dddd9413
DM
425 $out .= &$generate_output_rule($zoneinfo, $rule, $net, $netid);
426 }
427 }
428 }
429 }
430
431 PVE::Tools::file_set_contents("$targetdir/rules", $out);
5e1267a5
DM
432};
433
434
435sub parse_fw_rules {
436 my ($filename, $fh) = @_;
437
438 my $section;
439
440 my $res = { in => [], out => [] };
441
fcba0beb
DM
442 my $macros = get_shorewall_macros();
443 my $protocols = get_etc_protocols();
444
5e1267a5
DM
445 while (defined(my $line = <$fh>)) {
446 next if $line =~ m/^#/;
447 next if $line =~ m/^\s*$/;
448
449 if ($line =~ m/^\[(in|out)\]\s*$/i) {
450 $section = lc($1);
451 next;
452 }
453 next if !$section;
454
455 my ($action, $iface, $source, $dest, $proto, $dport, $sport) =
456 split(/\s+/, $line);
457
458 if (!$action) {
459 warn "skip incomplete line\n";
460 next;
461 }
462
463 my $service;
464 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
465 # OK
466 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
467 ($service, $action) = ($1, $2);
468 if (!$macros->{$service}) {
469 warn "unknown service '$service'\n";
470 next;
471 }
472 } else {
473 warn "unknown action '$action'\n";
474 next;
475 }
476
477 $iface = undef if $iface && $iface eq '-';
478 if ($iface && $iface !~ m/^(net0|net1|net2|net3|net4|net5)$/) {
479 warn "unknown interface '$iface'\n";
480 next;
481 }
482
483 $proto = undef if $proto && $proto eq '-';
fcba0beb
DM
484 if ($proto && !(defined($protocols->{byname}->{$proto}) ||
485 defined($protocols->{byid}->{$proto}))) {
5e1267a5
DM
486 warn "unknown protokol '$proto'\n";
487 next;
488 }
489
490 $source = undef if $source && $source eq '-';
5e1267a5 491 $dest = undef if $dest && $dest eq '-';
5e1267a5
DM
492
493 $dport = undef if $dport && $dport eq '-';
494 $sport = undef if $sport && $sport eq '-';
495
ecbea048
DM
496 eval {
497 parse_address_list($source) if $source;
498 parse_address_list($dest) if $dest;
fcba0beb
DM
499 parse_port_name_number_or_range($dport) if $dport;
500 parse_port_name_number_or_range($sport) if $sport;
ecbea048
DM
501 };
502 if (my $err = $@) {
503 warn $err;
504 next;
505
506 }
507
508
5e1267a5
DM
509 my $rule = {
510 action => $action,
511 service => $service,
512 iface => $iface,
513 source => $source,
514 dest => $dest,
515 proto => $proto,
516 dport => $dport,
517 sport => $sport,
518 };
519
520 push @{$res->{$section}}, $rule;
521 }
522
523 return $res;
524}
525
526sub read_local_vm_config {
527
528 my $openvz = {};
529
530 my $qemu = {};
531
532 my $list = PVE::QemuServer::config_list();
533
534 foreach my $vmid (keys %$list) {
b9b06789 535 #next if !($vmid eq '100' || $vmid eq '102');
5e1267a5
DM
536 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
537 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
538 $qemu->{$vmid} = $conf;
539 }
540 }
541
542 my $vmdata = { openvz => $openvz, qemu => $qemu };
543
544 return $vmdata;
545};
546
547sub read_vm_firewall_rules {
548 my ($vmdata) = @_;
549 my $rules = {};
550 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
551 my $filename = "/etc/pve/firewall/$vmid.fw";
552 my $fh = IO::File->new($filename, O_RDONLY);
553 next if !$fh;
554
555 $rules->{$vmid} = parse_fw_rules($filename, $fh);
556 }
557
558 return $rules;
559}
560
561sub compile {
562
563 my $vmdata = read_local_vm_config();
564 my $rules = read_vm_firewall_rules($vmdata);
565
566 # print Dumper($vmdata);
567
568 my $swdir = '/etc/shorewall';
569 mkdir $swdir;
570
571 &$compile_shorewall($swdir, $vmdata, $rules);
b6360c3f 572
5e1267a5 573 PVE::Tools::run_command(['shorewall', 'compile']);
b6360c3f
DM
574}
575
5e1267a5
DM
576sub compile_and_start {
577 my ($restart) = @_;
886aba9c 578
5e1267a5 579 compile();
b6360c3f 580
5e1267a5 581 PVE::Tools::run_command(['shorewall', $restart ? 'restart' : 'start']);
b6360c3f
DM
582}
583
584
5851;