parse protocols and ports
[pve-firewall.git] / PVE / Firewall.pm
1 package PVE::Firewall;
2
3 use warnings;
4 use strict;
5 use Data::Dumper;
6 use PVE::Tools;
7 use PVE::QemuServer;
8 use File::Path;
9 use IO::File;
10 use Net::IP;
11
12 use Data::Dumper;
13
14 my $macros;
15 sub 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
27 my $etc_services;
28
29 sub 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
62 my $etc_protocols;
63
64 sub 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
95 sub 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 }
105
106 sub 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
121 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
122
123 my $generate_input_rule = sub {
124 my ($zoneinfo, $rule, $net, $netid) = @_;
125
126 my $zone = $net->{zone} || die "internal error";
127 my $zid = $zoneinfo->{$zone}->{zoneref} || die "internal error";
128 my $tap = $net->{tap} || die "internal error";
129
130 my $dest = "$zid:$tap";
131
132 if ($rule->{dest}) {
133 $dest .= ":$rule->{dest}";
134 }
135
136 my $action = $rule->{service} ?
137 "$rule->{service}($rule->{action})" : $rule->{action};
138
139 my $sources = [];
140
141 if (!$rule->{source}) {
142 push @$sources, 'all';
143 } elsif ($zoneinfo->{$zone}->{type} eq 'bport') {
144 my $bridge_zone = $zoneinfo->{$zone}->{bridge_zone} || die "internal error";
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}";
156 }
157 } else {
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} || '-');
166 }
167
168 return $out;
169 };
170
171 my $generate_output_rule = sub {
172 my ($zoneinfo, $rule, $net, $netid) = @_;
173
174 my $zone = $net->{zone} || die "internal error";
175 my $zid = $zoneinfo->{$zone}->{zoneref} || die "internal error";
176 my $tap = $net->{tap} || die "internal error";
177
178 my $action = $rule->{service} ?
179 "$rule->{service}($rule->{action})" : $rule->{action};
180
181 my $dest;
182
183 if (!$rule->{dest}) {
184 $dest = 'all';
185 } else {
186 $dest = "all:$rule->{dest}";
187 }
188
189 return sprintf($rule_format, $action, "$zid:$tap", $dest,
190 $rule->{proto} || '-', $rule->{dport} || '-', $rule->{sport} || '-');
191 };
192
193 # we need complete VM configuration of all VMs (openvz/qemu)
194 # in vmdata
195
196 my $compile_shorewall = sub {
197 my ($targetdir, $vmdata, $rules) = @_;
198
199 # remove existing data ?
200 foreach my $file (qw(params zones rules interfaces maclist policy)) {
201 unlink "$targetdir/$file";
202 }
203
204 my $netinfo;
205
206 my $zoneinfo = {
207 fw => { type => 'firewall' },
208 };
209
210 my $maclist = {};
211
212 my $register_bridge;
213
214 $register_bridge = sub {
215 my ($bridge, $vlan) = @_;
216
217 my $zone = 'z' . $bridge;
218
219 return $zone if $zoneinfo->{$zone};
220
221 my $ext_zone = "z${bridge}ext";
222
223 $zoneinfo->{$zone} = {
224 type => 'bridge',
225 bridge => $bridge,
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,
241 };
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);
252 my $zone = $bridge_zone . $vmzone;
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;
263
264 return $zone;
265 };
266
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+)$/;
272 my $netnum = $1;
273 my $net = PVE::QemuServer::parse_net($conf->{$opt});
274 next if !$net;
275 die "implement me" if !$net->{bridge};
276
277 my $vmzone = $conf->{zone} || "vm$vmid";
278 $net->{tap} = "tap${vmid}i${netnum}";
279 $maclist->{$net->{tap}} = $net->{macaddr} || die "internal error";
280 $net->{zone} = &$register_bridge_port($net->{bridge}, $net->{tag}, $vmzone, $net->{tap});
281 $netinfo->{$vmid}->{$opt} = $net;
282 }
283 }
284
285 #print Dumper($netinfo);
286
287 # NOTE: zone names have length limit, so we need to
288 # translate them into shorter names
289
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
302 foreach my $z (sort keys %$zoneinfo) {
303 $zoneinfo->{$z}->{id} = &$lookup_zonename($z);
304 $zoneinfo->{$z}->{zonevar} = uc($z);
305 $zoneinfo->{$z}->{zoneref} = '$' . $zoneinfo->{$z}->{zonevar};
306 }
307
308 my $out;
309
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');
321
322 foreach my $z (sort keys %$zoneinfo) {
323 my $zid = $zoneinfo->{$z}->{zoneref};
324 if ($zoneinfo->{$z}->{type} eq 'firewall') {
325 $out .= sprintf($format, $zid, $zoneinfo->{$z}->{type}, '');
326 } elsif ($zoneinfo->{$z}->{type} eq 'bridge') {
327 $out .= sprintf($format, $zid, 'ipv4', '');
328 } elsif ($zoneinfo->{$z}->{type} eq 'bport') {
329 my $bridge_zone = $zoneinfo->{$z}->{bridge_zone} || die "internal error";
330 my $bzid = $zoneinfo->{$bridge_zone}->{zoneref} || die "internal error";
331 $out .= sprintf($format, "$zid:$bzid", 'bport', '');
332 } else {
333 die "internal error";
334 }
335 }
336
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);
340
341 # dump interfaces
342
343 $format = "%-25s %-20s %-10s %-15s\n";
344 $out = sprintf($format, '#ZONE', 'INTERFACE', 'BROADCAST', 'OPTIONS');
345
346 my $maclist_format = "%-15s %-15s %-15s\n";
347 my $macs = sprintf($maclist_format, '#DISPOSITION', 'INTERFACE', 'MACZONE');
348
349 foreach my $z (sort keys %$zoneinfo) {
350 my $zid = $zoneinfo->{$z}->{zoneref};
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";
355 $out .= sprintf($format, $zid, $bridge, 'detect', 'bridge,optional');
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";
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 }
369 }
370 } else {
371 die "internal error";
372 }
373 }
374
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
379 # dump maclist
380 PVE::Tools::file_set_contents("$targetdir/maclist", $macs);
381
382 # dump policy
383
384 $format = "%-15s %-15s %-15s %s\n";
385 $out = sprintf($format, '#SOURCE', 'DEST', 'POLICY', 'LOG');
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 }
396 $out .= sprintf($format, 'all', 'all', 'REJECT', 'info');
397
398 PVE::Tools::file_set_contents("$targetdir/policy", $out);
399
400 # dump rules
401 $out = '';
402
403 $out = sprintf($rule_format, '#ACTION', 'SOURCE', 'DEST', 'PROTO', 'DPORT', 'SPORT');
404 foreach my $vmid (sort keys %$rules) {
405 my $inrules = $rules->{$vmid}->{in};
406 my $outrules = $rules->{$vmid}->{out};
407
408 if (scalar(@$inrules)) {
409 $out .= "# IN to VM $vmid\n";
410 foreach my $rule (@$inrules) {
411 foreach my $netid (keys %{$netinfo->{$vmid}}) {
412 my $net = $netinfo->{$vmid}->{$netid};
413 next if $rule->{iface} && $rule->{iface} ne $netid;
414 $out .= &$generate_input_rule($zoneinfo, $rule, $net, $netid);
415 }
416 }
417 }
418
419 if (scalar(@$outrules)) {
420 $out .= "# OUT from VM $vmid\n";
421 foreach my $rule (@$outrules) {
422 foreach my $netid (keys %{$netinfo->{$vmid}}) {
423 my $net = $netinfo->{$vmid}->{$netid};
424 next if $rule->{iface} && $rule->{iface} ne $netid;
425 $out .= &$generate_output_rule($zoneinfo, $rule, $net, $netid);
426 }
427 }
428 }
429 }
430
431 PVE::Tools::file_set_contents("$targetdir/rules", $out);
432 };
433
434
435 sub parse_fw_rules {
436 my ($filename, $fh) = @_;
437
438 my $section;
439
440 my $res = { in => [], out => [] };
441
442 my $macros = get_shorewall_macros();
443 my $protocols = get_etc_protocols();
444
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 '-';
484 if ($proto && !(defined($protocols->{byname}->{$proto}) ||
485 defined($protocols->{byid}->{$proto}))) {
486 warn "unknown protokol '$proto'\n";
487 next;
488 }
489
490 $source = undef if $source && $source eq '-';
491 $dest = undef if $dest && $dest eq '-';
492
493 $dport = undef if $dport && $dport eq '-';
494 $sport = undef if $sport && $sport eq '-';
495
496 eval {
497 parse_address_list($source) if $source;
498 parse_address_list($dest) if $dest;
499 parse_port_name_number_or_range($dport) if $dport;
500 parse_port_name_number_or_range($sport) if $sport;
501 };
502 if (my $err = $@) {
503 warn $err;
504 next;
505
506 }
507
508
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
526 sub 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) {
535 #next if !($vmid eq '100' || $vmid eq '102');
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
547 sub 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
561 sub 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);
572
573 PVE::Tools::run_command(['shorewall', 'compile']);
574 }
575
576 sub compile_and_start {
577 my ($restart) = @_;
578
579 compile();
580
581 PVE::Tools::run_command(['shorewall', $restart ? 'restart' : 'start']);
582 }
583
584
585 1;