9 use PVE
::JSONSchema
qw(get_standard_option);
17 use PVE
::Tools
qw(run_command lock_file);
20 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
21 my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
23 # dynamically include PVE::QemuServer and PVE::OpenVZ
24 # to avoid dependency problems
27 require PVE
::QemuServer
;
28 $have_qemu_server = 1;
34 $have_pve_manager = 1;
37 my $feature_ipset_nomatch = 0;
39 my (undef, undef, $release) = POSIX
::uname
();
40 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
41 my ($major, $minor) = ($1, $2);
42 $feature_ipset_nomatch = 1 if ($major > 3) ||
43 ($major == 3 && $minor >= 7);
50 my $nodename = PVE
::INotify
::nodename
();
52 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
53 my $pve_fw_status_filename = "/var/lib/pve-firewall/pvefw.status";
55 my $default_log_level = 'info';
57 my $log_level_hash = {
68 # imported/converted from: /usr/share/shorewall/macro.*
72 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
73 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
76 "Auth (identd) traffic",
77 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
80 "Border Gateway Protocol traffic",
81 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
84 "BitTorrent traffic for BitTorrent 3.1 and earlier",
85 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
86 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
89 "BitTorrent traffic for BitTorrent 3.2 and later",
90 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
91 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
94 "Concurrent Versions System pserver traffic",
95 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
98 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
99 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
100 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
101 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
104 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
105 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
106 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
109 "Distributed Checksum Clearinghouse spam filtering mechanism",
110 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
113 "Forwarded DHCP traffic (bidirectional)",
114 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
115 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
118 "Domain Name System traffic (upd and tcp)",
119 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
120 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
123 "Distributed Compiler service",
124 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
127 "File Transfer Protocol",
128 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
131 "Finger protocol (RFC 742)",
132 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
135 "GNUnet secure peer-to-peer networking traffic",
136 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
137 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
138 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
139 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
142 "Generic Routing Encapsulation tunneling protocol (bidirectional)",
143 { action
=> 'PARAM', proto
=> '47' },
144 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
147 "Git distributed revision control traffic",
148 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
151 "OpenPGP HTTP keyserver protocol traffic",
152 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
155 "Hypertext Transfer Protocol (WWW)",
156 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
159 "Hypertext Transfer Protocol (WWW) over SSL",
160 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
163 "Internet Cache Protocol V2 (Squid) traffic",
164 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
167 "AOL Instant Messenger traffic",
168 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
171 "Internet Message Access Protocol",
172 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
175 "Internet Message Access Protocol over SSL",
176 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
179 "IPIP capsulation traffic (bidirectional)",
180 { action
=> 'PARAM', proto
=> '94' },
181 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '94' },
184 "IPsec traffic (bidirectional)",
185 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
186 { action
=> 'PARAM', proto
=> '50' },
187 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
188 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
191 "IPsec authentication (AH) traffic (bidirectional)",
192 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
193 { action
=> 'PARAM', proto
=> '51' },
194 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500', sport
=> '500' },
195 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '51' },
198 "IPsec traffic and Nat-Traversal (bidirectional)",
199 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
200 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
201 { action
=> 'PARAM', proto
=> '50' },
202 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '500' },
203 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '4500' },
204 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '50' },
207 "Internet Relay Chat traffic",
208 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
211 "HP Jetdirect printing",
212 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
215 "Layer 2 Tunneling Protocol traffic",
216 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
217 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1701' },
220 "Lightweight Directory Access Protocol traffic",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
224 "Secure Lightweight Directory Access Protocol traffic",
225 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
228 "Microsoft Notification Protocol",
229 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
232 "Microsoft SQL Server",
233 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
236 "Mail traffic (SMTP, SMTPS, Submission)",
237 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
239 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
242 "Munin networked resource monitoring traffic",
243 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
247 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
250 "NNTP traffic (Usenet).",
251 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
254 "Encrypted NNTP traffic (Usenet)",
255 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
258 "Network Time Protocol (ntpd)",
259 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
262 "Bi-directional NTP (for NTP peers)",
263 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
264 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '123' },
267 "OSPF multicast traffic",
268 { action
=> 'PARAM', proto
=> '89' },
272 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
275 "Symantec PCAnywere (tm)",
276 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
281 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
284 "Encrypted POP3 traffic",
285 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
288 "Point-to-Point Tunneling Protocol",
289 { action
=> 'PARAM', proto
=> '47' },
290 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> '47' },
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
295 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
299 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
302 "Line Printer protocol printing",
303 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
306 "Microsoft Remote Desktop Protocol traffic",
307 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
310 "Routing Information Protocol (bidirectional)",
311 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
312 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '520' },
315 "BIND remote management protocol",
316 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
319 "Razor Antispam System",
320 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
323 "Remote time retrieval (rdate)",
324 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
328 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
331 "SANE network scanning",
332 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
335 "Microsoft SMB traffic",
336 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
337 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
338 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
339 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
342 "Microsoft SMB traffic (bidirectional)",
343 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
344 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
345 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
346 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
347 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '135,445' },
348 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '137:139' },
349 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
350 { action
=> 'PARAM', source
=> 'DEST', dest
=> 'SOURCE', proto
=> 'tcp', dport
=> '135,139,445' },
353 "Samba Web Administration Tool",
354 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
357 "Simple Mail Transfer Protocol",
358 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
361 "Encrypted Simple Mail Transfer Protocol",
362 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
365 "Simple Network Management Protocol",
366 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
367 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
370 "Spam Assassin SPAMD traffic",
371 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
374 "Secure shell traffic",
375 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
378 "Subversion server (svnserve)",
379 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
382 "SixXS IPv6 Deployment and Tunnel Broker",
383 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
384 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
385 { action
=> 'PARAM', proto
=> '41' },
386 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
389 "Squid web proxy traffic",
390 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
393 "Mail message submission traffic",
394 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
397 "Syslog protocol (RFC 5424) traffic",
398 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
399 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
402 "Trivial File Transfer Protocol traffic",
403 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
407 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
411 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
414 "RFC 868 Time protocol",
415 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
418 "Traceroute (for up to 30 hops) traffic",
419 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
420 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
423 "VNC traffic for VNC display's 0 - 9",
424 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5909' },
427 "VNC traffic from Vncservers to Vncviewers in listen mode",
428 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
431 "WWW traffic (HTTP and HTTPS)",
432 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
436 "Web Cache/Proxy traffic (port 8080)",
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
441 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
444 "Whois (nicname, RFC 3912) traffic",
445 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
449 my $pve_fw_parsed_macros;
450 my $pve_fw_macro_descr;
451 my $pve_fw_preferred_macro_names = {};
453 my $pve_std_chains = {
454 'PVEFW-SET-ACCEPT-MARK' => [
455 "-j MARK --set-mark 1",
457 'PVEFW-DropBroadcast' => [
458 # same as shorewall 'Broadcast'
459 # simply DROP BROADCAST/MULTICAST/ANYCAST
460 # we can use this to reduce logging
461 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
462 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
463 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
464 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
467 # same as shorewall 'reject'
468 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
469 { action
=> 'DROP', source
=> '224.0.0.0/4' },
470 { action
=> 'DROP', proto
=> 'icmp' },
471 "-p tcp -j REJECT --reject-with tcp-reset",
472 "-p udp -j REJECT --reject-with icmp-port-unreachable",
473 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
474 "-j REJECT --reject-with icmp-host-prohibited",
477 # same as shorewall 'Drop', which is equal to DROP,
478 # but REJECT/DROP some packages to reduce logging,
479 # and ACCEPT critical ICMP types
480 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
481 # we are not interested in BROADCAST/MULTICAST/ANYCAST
482 { action
=> 'PVEFW-DropBroadcast' },
483 # ACCEPT critical ICMP types
484 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
485 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
486 # Drop packets with INVALID state
487 "-m conntrack --ctstate INVALID -j DROP",
488 # Drop Microsoft SMB noise
489 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
490 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
491 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
492 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
493 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
494 # Drop new/NotSyn traffic so that it doesn't get logged
495 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
497 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
500 # same as shorewall 'Reject', which is equal to Reject,
501 # but REJECT/DROP some packages to reduce logging,
502 # and ACCEPT critical ICMP types
503 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
504 # we are not interested in BROADCAST/MULTICAST/ANYCAST
505 { action
=> 'PVEFW-DropBroadcast' },
506 # ACCEPT critical ICMP types
507 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
508 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
509 # Drop packets with INVALID state
510 "-m conntrack --ctstate INVALID -j DROP",
511 # Drop Microsoft SMB noise
512 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
513 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
514 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
515 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
516 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
517 # Drop new/NotSyn traffic so that it doesn't get logged
518 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
520 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
522 'PVEFW-tcpflags' => [
523 # same as shorewall tcpflags action.
524 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
525 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
526 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
527 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
528 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
529 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
532 # same as shorewall smurfs action
533 # Filter packets for smurfs (packets with a broadcast address as the source).
534 "-s 0.0.0.0/32 -j RETURN",
535 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
536 "-s 224.0.0.0/4 -g PVEFW-smurflog",
540 # iptables -p icmp -h
541 my $icmp_type_names = {
544 'destination-unreachable' => 1,
545 'network-unreachable' => 1,
546 'host-unreachable' => 1,
547 'protocol-unreachable' => 1,
548 'port-unreachable' => 1,
549 'fragmentation-needed' => 1,
550 'source-route-failed' => 1,
551 'network-unknown' => 1,
553 'network-prohibited' => 1,
554 'host-prohibited' => 1,
555 'TOS-network-unreachable' => 1,
556 'TOS-host-unreachable' => 1,
557 'communication-prohibited' => 1,
558 'host-precedence-violation' => 1,
559 'precedence-cutoff' => 1,
560 'source-quench' => 1,
562 'network-redirect' => 1,
563 'host-redirect' => 1,
564 'TOS-network-redirect' => 1,
565 'TOS-host-redirect' => 1,
567 'router-advertisement' => 1,
568 'router-solicitation' => 1,
569 'time-exceeded' => 1,
570 'ttl-zero-during-transit' => 1,
571 'ttl-zero-during-reassembly' => 1,
572 'parameter-problem' => 1,
573 'ip-header-bad' => 1,
574 'required-option-missing' => 1,
575 'timestamp-request' => 1,
576 'timestamp-reply' => 1,
577 'address-mask-request' => 1,
578 'address-mask-reply' => 1,
581 sub init_firewall_macros
{
583 $pve_fw_parsed_macros = {};
585 foreach my $k (keys %$pve_fw_macros) {
586 my $lc_name = lc($k);
587 my $macro = $pve_fw_macros->{$k};
588 if (!ref($macro->[0])) {
589 $pve_fw_macro_descr->{$k} = shift @$macro;
591 $pve_fw_preferred_macro_names->{$lc_name} = $k;
592 $pve_fw_parsed_macros->{$k} = $macro;
596 init_firewall_macros
();
599 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
604 sub get_etc_services
{
606 return $etc_services if $etc_services;
608 my $filename = "/etc/services";
610 my $fh = IO
::File-
>new($filename, O_RDONLY
);
612 warn "unable to read '$filename' - $!\n";
618 while (my $line = <$fh>) {
620 next if $line =~m/^#/;
621 next if ($line =~m/^\s*$/);
623 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
624 $services->{byid
}->{$2}->{name
} = $1;
625 $services->{byid
}->{$2}->{port
} = $2;
626 $services->{byid
}->{$2}->{$3} = 1;
627 $services->{byname
}->{$1} = $services->{byid
}->{$2};
633 $etc_services = $services;
636 return $etc_services;
641 sub get_etc_protocols
{
642 return $etc_protocols if $etc_protocols;
644 my $filename = "/etc/protocols";
646 my $fh = IO
::File-
>new($filename, O_RDONLY
);
648 warn "unable to read '$filename' - $!\n";
654 while (my $line = <$fh>) {
656 next if $line =~m/^#/;
657 next if ($line =~m/^\s*$/);
659 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
660 $protocols->{byid
}->{$2}->{name
} = $1;
661 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
667 $etc_protocols = $protocols;
669 return $etc_protocols;
672 sub parse_address_list
{
675 return if $str !~ m/^(\+)(\S+)$/; # ipset ref
679 foreach my $elem (split(/,/, $str)) {
681 if (!Net
::IP-
>new($elem)) {
682 my $err = Net
::IP
::Error
();
683 die "invalid IP address: $err\n";
685 $iprange = 1 if $elem =~ m/-/;
688 die "you can use a range in a list\n" if $iprange && $count > 1;
691 sub parse_port_name_number_or_range
{
694 my $services = PVE
::Firewall
::get_etc_services
();
696 foreach my $item (split(/,/, $str)) {
700 foreach my $pon (split(':', $item, 2)) {
701 $pon = $services->{byname
}->{$pon}->{port
} if $services->{byname
}->{$pon}->{port
};
702 if ($pon =~ m/^\d+$/){
703 die "invalid port '$pon'\n" if $pon < 0 && $pon > 65535;
704 die "port '$pon' must be bigger than port '$oldpon' \n" if $oldpon && ($pon < $oldpon);
707 die "invalid port $services->{byname}->{$pon}\n" if !$services->{byname
}->{$pon};
715 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
716 sub pve_fw_verify_port_spec
{
719 parse_port_name_number_or_range
($portstr);
724 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
725 sub pve_fw_verify_v4addr_spec
{
728 parse_address_list
($list);
733 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
734 sub pve_fw_verify_protocol_spec
{
737 my $protocols = get_etc_protocols
();
739 die "unknown protocol '$proto'\n" if $proto &&
740 !(defined($protocols->{byname
}->{$proto}) ||
741 defined($protocols->{byid
}->{$proto}));
747 # helper function for API
749 my $rule_properties = {
751 description
=> "Update rule at position <pos>.",
765 enum
=> ['in', 'out', 'group'],
770 enum
=> ['ACCEPT', 'DROP', 'REJECT'],
777 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
779 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
783 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
787 type
=> 'string', format
=> 'pve-fw-protocol-spec',
795 type
=> 'string', format
=> 'pve-fw-port-spec',
799 type
=> 'string', format
=> 'pve-fw-port-spec',
808 sub cleanup_fw_rule
{
809 my ($rule, $digest, $pos) = @_;
813 foreach my $k (keys %$rule) {
814 next if !$rule_properties->{$k};
816 next if !defined($v);
818 $r->{digest
} = $digest;
825 sub add_rule_properties
{
826 my ($properties) = @_;
828 foreach my $k (keys %$rule_properties) {
829 my $h = $rule_properties->{$k};
830 # copy data, so that we can modify later without side effects
831 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
837 sub delete_rule_properties
{
838 my ($rule, $delete_str) = @_;
840 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
841 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
842 if !defined($rule_properties->{$opt});
843 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
844 if $opt eq 'type' || $opt eq 'action';
845 delete $rule->{$opt};
852 my ($rule, $param) = @_;
854 foreach my $k (keys %$rule_properties) {
855 if (defined(my $v = $param->{$k})) {
856 if ($v eq '' || $v eq '-') {
869 my $bridge_firewall_enabled = 0;
871 sub enable_bridge_firewall
{
873 return if $bridge_firewall_enabled; # only once
875 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
876 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
878 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
879 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
881 $bridge_firewall_enabled = 1;
884 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
886 sub iptables_restore_cmdlist
{
889 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
892 sub ipset_restore_cmdlist
{
895 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
898 sub iptables_get_chains
{
902 # check what chains we want to track
903 my $is_pvefw_chain = sub {
906 return 1 if $name =~ m/^PVEFW-\S+$/;
908 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
910 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
912 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
914 return 1 if $name =~ m/^vmbr\d+-(:?FW|IN|OUT|IPS)$/;
915 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
927 return if $line =~ m/^#/;
928 return if $line =~ m/^\s*$/;
930 if ($line =~ m/^\*(\S+)$/) {
935 return if $table ne 'filter';
937 if ($line =~ m/^:(\S+)\s/) {
939 return if !&$is_pvefw_chain($chain);
940 $res->{$chain} = "unknown";
941 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
942 my ($chain, $sig) = ($1, $2);
943 return if !&$is_pvefw_chain($chain);
944 $res->{$chain} = $sig;
945 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
948 # simply ignore the rest
953 run_command
("/sbin/iptables-save", outfunc
=> $parser);
955 return wantarray ?
($res, $hooks) : $res;
958 sub iptables_chain_digest
{
960 my $digest = Digest
::SHA-
>new('sha1');
961 foreach my $rule (@$rules) { # order is important
964 return $digest->b64digest;
967 sub ipset_chain_digest
{
970 my $digest = Digest
::SHA-
>new('sha1');
971 foreach my $rule (sort @$rules) { # note: sorted
974 return $digest->b64digest;
977 sub ipset_get_chains
{
985 return if $line =~ m/^#/;
986 return if $line =~ m/^\s*$/;
987 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
989 $line =~ s/\s+$//; # delete trailing white space
990 push @{$chains->{$chain}}, $line;
992 # simply ignore the rest
997 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
999 # compute digest for each chain
1000 foreach my $chain (keys %$chains) {
1001 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1007 sub ruleset_generate_cmdstr
{
1008 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1010 return if defined($rule->{enable
}) && !$rule->{enable
};
1012 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1014 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1015 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1019 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1020 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1022 my $source = $rule->{source
};
1023 my $dest = $rule->{dest
};
1026 if ($source =~ m/^(\+)(\S+)$/) {
1027 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1028 push @cmd, "-m set --match-set PVEFW-$2 src";
1030 } elsif ($source =~ m/\-/){
1031 push @cmd, "-m iprange --src-range $source";
1034 push @cmd, "-s $source";
1039 if ($dest =~ m/^(\+)(\S+)$/) {
1040 die "no such ipset $2" if !$cluster_conf->{ipset
}->{$2};
1041 push @cmd, "-m set --match-set PVEFW-$2 dst";
1043 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1044 push @cmd, "-m iprange --dst-range $dest";
1047 push @cmd, "-s $dest";
1051 if ($rule->{proto
}) {
1052 push @cmd, "-p $rule->{proto}";
1055 $multiport++ if $nbdport > 1;
1056 $multiport++ if $nbsport > 1;
1058 push @cmd, "--match multiport" if $multiport;
1060 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1061 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1063 if ($rule->{dport
}) {
1064 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1065 # Note: we use dport to store --icmp-type
1066 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1067 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1070 if ($multiport == 2) {
1071 push @cmd, "--ports $rule->{dport}";
1073 push @cmd, "--dports $rule->{dport}";
1076 push @cmd, "--dport $rule->{dport}";
1081 if ($rule->{sport
}) {
1083 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1085 push @cmd, "--sport $rule->{sport}";
1088 } elsif ($rule->{dport
} || $rule->{sport
}) {
1089 warn "ignoring destination port '$rule->{dport}' - no protocol specified\n" if $rule->{dport
};
1090 warn "ignoring source port '$rule->{sport}' - no protocol specified\n" if $rule->{sport
};
1093 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1095 if (my $action = $rule->{action
}) {
1096 $action = $actions->{$action} if defined($actions->{$action});
1097 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1098 push @cmd, $goto ?
"-g $action" : "-j $action";
1101 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1104 my $apply_macro = sub {
1105 my ($macro_name, $param) = @_;
1107 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1108 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1112 foreach my $templ (@$macro_rules) {
1114 my $param_used = {};
1115 foreach my $k (keys %$templ) {
1116 my $v = $templ->{$k};
1117 if ($v eq 'PARAM') {
1119 $param_used->{$k} = 1;
1120 } elsif ($v eq 'DEST') {
1121 $v = $param->{dest
};
1122 $param_used->{dest
} = 1;
1123 } elsif ($v eq 'SOURCE') {
1124 $v = $param->{source
};
1125 $param_used->{source
} = 1;
1128 die "missing parameter '$k' in macro '$macro_name'\n" if !defined($v);
1131 foreach my $k (keys %$param) {
1132 next if $k eq 'macro';
1133 next if !defined($param->{$k});
1134 next if $param_used->{$k};
1135 if (defined($rule->{$k})) {
1136 die "parameter '$k' already define in macro (value = '$rule->{$k}')\n"
1137 if $rule->{$k} ne $param->{$k};
1139 $rule->{$k} = $param->{$k};
1142 push @$rules, $rule;
1148 sub ruleset_generate_rule
{
1149 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1153 if ($rule->{macro}) {
1154 $rules = &$apply_macro($rule->{macro}, $rule);
1159 foreach my $tmp (@$rules) {
1160 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1161 ruleset_addrule
($ruleset, $chain, $cmdstr);
1166 sub ruleset_generate_rule_insert
{
1167 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1169 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1171 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1172 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1176 sub ruleset_create_chain
{
1177 my ($ruleset, $chain) = @_;
1179 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1180 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1182 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1184 $ruleset->{$chain} = [];
1187 sub ruleset_chain_exist
{
1188 my ($ruleset, $chain) = @_;
1190 return $ruleset->{$chain} ?
1 : undef;
1193 sub ruleset_addrule
{
1194 my ($ruleset, $chain, $rule) = @_;
1196 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1198 push @{$ruleset->{$chain}}, "-A $chain $rule";
1201 sub ruleset_insertrule
{
1202 my ($ruleset, $chain, $rule) = @_;
1204 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1206 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1209 sub get_log_rule_base
{
1210 my ($chain, $vmid, $msg, $loglevel) = @_;
1212 die "internal error - no log level" if !defined($loglevel);
1214 $vmid = 0 if !defined($vmid);
1216 # Note: we use special format for prefix to pass further
1217 # info to log daemon (VMID, LOGVELEL and CHAIN)
1219 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1222 sub ruleset_addlog {
1223 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1225 return if !defined($loglevel);
1227 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1229 $logrule = "$rule $logrule" if defined($rule);
1231 ruleset_addrule($ruleset, $chain, $logrule)
1234 sub generate_bridge_chains {
1235 my ($ruleset, $hostfw_conf, $bridge, $routing_table) = @_;
1237 my $options = $hostfw_conf->{options} || {};
1239 die "error
: detected direct route to bridge
'$bridge'\n"
1240 if !$options->{allow_bridge_route} && $routing_table->{$bridge};
1242 if (!ruleset_chain_exist($ruleset, "$bridge-FW
")) {
1243 ruleset_create_chain($ruleset, "$bridge-FW
");
1244 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-FW
");
1245 ruleset_addrule($ruleset, "PVEFW-FORWARD
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-FW
");
1248 if (!ruleset_chain_exist($ruleset, "$bridge-OUT
")) {
1249 ruleset_create_chain($ruleset, "$bridge-OUT
");
1250 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-in
-j
$bridge-OUT
");
1251 ruleset_insertrule($ruleset, "PVEFW-INPUT
", "-i
$bridge -m physdev
--physdev-is-in
-j
$bridge-OUT
");
1254 if (!ruleset_chain_exist($ruleset, "$bridge-IN
")) {
1255 ruleset_create_chain($ruleset, "$bridge-IN
");
1256 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j
$bridge-IN
");
1257 ruleset_addrule($ruleset, "$bridge-FW
", "-m mark
--mark
1 -j ACCEPT
");
1258 # accept traffic to unmanaged bridge ports
1259 ruleset_addrule($ruleset, "$bridge-FW
", "-m physdev
--physdev-is-out
-j ACCEPT
");
1263 sub ruleset_add_chain_policy {
1264 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1266 if ($policy eq 'ACCEPT') {
1268 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1269 { ACCEPT => $accept_action});
1271 } elsif ($policy eq 'DROP') {
1273 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1275 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1277 ruleset_addrule($ruleset, $chain, "-j DROP
");
1278 } elsif ($policy eq 'REJECT') {
1279 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1281 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1283 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1286 die "internal error
: unknown policy
'$policy'";
1290 sub ruleset_create_vm_chain {
1291 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1293 ruleset_create_chain($ruleset, $chain);
1294 my $accept = generate_nfqueue($options);
1296 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1297 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1300 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1301 if ($direction eq 'OUT') {
1302 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1303 proto => 'udp', sport => 68, dport => 67 });
1305 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1306 proto => 'udp', sport => 67, dport => 68 });
1310 if ($options->{tcpflags}) {
1311 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1314 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1315 if ($direction eq 'OUT') {
1316 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-g PVEFW-SET-ACCEPT-MARK
");
1318 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1321 if ($direction eq 'OUT') {
1322 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1323 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1325 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1329 sub ruleset_generate_vm_rules {
1330 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1332 my $lc_direction = lc($direction);
1334 foreach my $rule (@$rules) {
1335 next if $rule->{iface} && $rule->{iface} ne $netid;
1336 next if !$rule->{enable};
1337 if ($rule->{type} eq 'group') {
1338 my $group_chain = "GROUP-
$rule->{action
}-$direction";
1339 if(!ruleset_chain_exist($ruleset, $group_chain)){
1340 generate_group_rules($ruleset, $cluster_conf, $rule->{action});
1342 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1343 if ($direction eq 'OUT'){
1344 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j RETURN
");
1346 my $accept = generate_nfqueue($options);
1347 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$accept");
1351 next if $rule->{type} ne $lc_direction;
1352 if ($direction eq 'OUT') {
1353 ruleset_generate_rule($ruleset, $chain, $rule,
1354 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1356 my $accept = generate_nfqueue($options);
1357 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept , REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1363 sub generate_nfqueue {
1367 if($options->{ips}){
1368 $action = "NFQUEUE
";
1369 if($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1370 if(defined($3) && defined($1)) {
1371 $action .= " --queue-balance
$1:$3";
1372 }elsif (defined($1)) {
1373 $action .= " --queue-num
$1";
1376 $action .= " --queue-bypass
";
1384 sub ruleset_generate_vm_ipsrules {
1385 my ($ruleset, $options, $direction, $iface, $bridge) = @_;
1387 if ($options->{ips} && $direction eq 'IN') {
1388 my $nfqueue = generate_nfqueue($options);
1390 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1391 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1394 if (!ruleset_chain_exist($ruleset, "$bridge-IPS
")) {
1395 ruleset_create_chain($ruleset, "$bridge-IPS
");
1396 ruleset_insertrule($ruleset, "PVEFW-IPS
", "-o
$bridge -m physdev
--physdev-is-out
-j
$bridge-IPS
");
1399 ruleset_addrule($ruleset, "$bridge-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1403 sub generate_venet_rules_direction {
1404 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1406 parse_address_list($ip); # make sure we have a valid $ip list
1408 my $lc_direction = lc($direction);
1410 my $rules = $vmfw_conf->{rules};
1412 my $options = $vmfw_conf->{options};
1413 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1415 my $chain = "venet0-
$vmid-$direction";
1417 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1419 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1424 if ($direction eq 'OUT') {
1425 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1427 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1430 my $accept = generate_nfqueue($options);
1431 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1432 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1434 # plug into FORWARD, INPUT and OUTPUT chain
1435 if ($direction eq 'OUT') {
1436 ruleset_generate_rule_insert($ruleset, "PVEFW-FORWARD
", {
1439 iface_in => 'venet0'});
1441 ruleset_generate_rule_insert($ruleset, "PVEFW-INPUT
", {
1444 iface_in => 'venet0'});
1446 ruleset_generate_rule($ruleset, "PVEFW-FORWARD
", {
1449 iface_out => 'venet0'});
1451 ruleset_generate_rule($ruleset, "PVEFW-OUTPUT
", {
1454 iface_out => 'venet0'});
1458 sub generate_tap_rules_direction {
1459 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $bridge, $direction) = @_;
1461 my $lc_direction = lc($direction);
1463 my $rules = $vmfw_conf->{rules};
1465 my $options = $vmfw_conf->{options};
1466 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1468 my $tapchain = "$iface-$direction";
1470 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1472 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1474 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface, $bridge);
1479 if ($direction eq 'OUT') {
1480 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1482 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1485 my $accept = generate_nfqueue($options);
1486 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1487 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1489 # plug the tap chain to bridge chain
1490 if ($direction eq 'IN') {
1491 ruleset_insertrule($ruleset, "$bridge-IN
",
1492 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1494 ruleset_insertrule($ruleset, "$bridge-OUT
",
1495 "-m physdev
--physdev-in
$iface -j
$tapchain");
1499 sub enable_host_firewall {
1500 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1502 # fixme: allow security groups
1504 my $options = $hostfw_conf->{options};
1505 my $rules = $hostfw_conf->{rules};
1507 # host inbound firewall
1508 my $chain = "PVEFW-HOST-IN
";
1509 ruleset_create_chain($ruleset, $chain);
1511 my $loglevel = get_option_log_level($options, "log_level_in
");
1513 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1514 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1517 if ($options->{tcpflags}) {
1518 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1521 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1522 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1523 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1524 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1525 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1526 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1528 # we use RETURN because we need to check also tap rules
1529 my $accept_action = 'RETURN';
1531 foreach my $rule (@$rules) {
1532 next if $rule->{type} ne 'in';
1533 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1536 # implement input policy
1537 my $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1538 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1540 # host outbound firewall
1541 $chain = "PVEFW-HOST-OUT
";
1542 ruleset_create_chain($ruleset, $chain);
1544 $loglevel = get_option_log_level($options, "log_level_out
");
1546 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1547 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j ACCEPT
");
1548 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1549 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
-j ACCEPT
");
1550 ruleset_addrule($ruleset, $chain, "-p udp
-m conntrack
--ctstate NEW
--dport
5404:5405 -j ACCEPT
");
1551 ruleset_addrule($ruleset, $chain, "-p udp
-m udp
--dport
9000 -j ACCEPT
"); #corosync
1553 # we use RETURN because we may want to check other thigs later
1554 $accept_action = 'RETURN';
1556 foreach my $rule (@$rules) {
1557 next if $rule->{type} ne 'out';
1558 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1561 # implement output policy
1562 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1563 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1565 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1566 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1569 sub generate_group_rules {
1570 my ($ruleset, $cluster_conf, $group) = @_;
1571 die "no such security group
'$group'\n" if !$cluster_conf->{groups}->{$group};
1573 my $rules = $cluster_conf->{groups}->{$group};
1575 my $chain = "GROUP-
${group
}-IN
";
1577 ruleset_create_chain($ruleset, $chain);
1578 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1580 foreach my $rule (@$rules) {
1581 next if $rule->{type} ne 'in';
1582 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1585 $chain = "GROUP-
${group
}-OUT
";
1587 ruleset_create_chain($ruleset, $chain);
1588 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1590 foreach my $rule (@$rules) {
1591 next if $rule->{type} ne 'out';
1592 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1593 # check also other tap rules later
1594 ruleset_generate_rule($ruleset, $chain, $rule,
1595 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1600 my $valid_netdev_names = {};
1601 for (my $i = 0; $i < $MAX_NETS; $i++) {
1602 $valid_netdev_names->{"net
$i"} = 1;
1606 my ($line, $need_iface, $allow_groups) = @_;
1608 my ($type, $action, $iface, $source, $dest, $proto, $dport, $sport);
1610 # we can add single line comments to the end of the rule
1611 my $comment = decode('utf8', $1) if $line =~ s/#\s*(.*?)\s*$//;
1613 # we can disable a rule when prefixed with '|'
1616 $enable = 0 if $line =~ s/^\|//;
1618 my @data = split(/\s+/, $line);
1619 my $expected_elements = $need_iface ? 8 : 7;
1621 die "wrong number of rule elements
\n" if scalar(@data) > $expected_elements;
1624 ($type, $action, $iface, $source, $dest, $proto, $dport, $sport) = @data
1626 ($type, $action, $source, $dest, $proto, $dport, $sport) = @data;
1629 die "incomplete rule
\n" if ! ($type && $action);
1635 if ($type eq 'in' || $type eq 'out') {
1636 if ($action =~ m/^(ACCEPT|DROP|REJECT)$/) {
1638 } elsif ($action =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1640 my $preferred_name = $pve_fw_preferred_macro_names->{lc($1)};
1641 die "unknown
macro '$1'\n" if !$preferred_name;
1642 $macro = $preferred_name;
1644 die "unknown action
'$action'\n";
1646 } elsif ($type eq 'group') {
1647 die "wrong number of rule elements
\n" if scalar(@data) != 3;
1648 die "groups disabled
\n" if !$allow_groups;
1650 die "invalid characters
in group name
\n" if $action !~ m/^[A-Za-z0-9_\-]+$/;
1652 die "unknown rule type
'$type'\n";
1656 $iface = undef if $iface && $iface eq '-';
1659 $proto = undef if $proto && $proto eq '-';
1660 pve_fw_verify_protocol_spec($proto) if $proto;
1662 $source = undef if $source && $source eq '-';
1663 $dest = undef if $dest && $dest eq '-';
1665 $dport = undef if $dport && $dport eq '-';
1666 $sport = undef if $sport && $sport eq '-';
1668 parse_port_name_number_or_range($dport) if defined($dport);
1669 parse_port_name_number_or_range($sport) if defined($sport);
1671 parse_address_list($source) if $source;
1672 parse_address_list($dest) if $dest;
1677 comment => $comment,
1689 sub parse_vmfw_option {
1694 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1696 if ($line =~ m/^(enable|dhcp|macfilter|nosmurfs|tcpflags|ips):\s*(0|1)\s*$/i) {
1699 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1701 $value = $2 ? lc($3) : '';
1702 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1705 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1710 die "can
't parse option '$line'\n"
1713 return ($opt, $value);
1716 sub parse_hostfw_option {
1721 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
1723 if ($line =~ m/^(enable|dhcp|nosmurfs|tcpflags|allow_bridge_route|optimize):\s*(0|1)\s*$/i) {
1726 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
1728 $value = $2 ? lc($3) : '';
1729 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1732 } elsif ($line =~ m/^(nf_conntrack_max):\s*(\d+)\s*$/i) {
1737 die "can't parse option
'$line'\n"
1740 return ($opt, $value);
1743 sub parse_clusterfw_option {
1748 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
1753 die "can
't parse option '$line'\n"
1756 return ($opt, $value);
1759 sub parse_vm_fw_rules {
1760 my ($filename, $fh) = @_;
1762 my $res = { rules => [], options => {}};
1766 my $digest = Digest::SHA->new('sha1
');
1768 while (defined(my $line = <$fh>)) {
1769 $digest->add($line);
1771 next if $line =~ m/^#/;
1772 next if $line =~ m/^\s*$/;
1774 my $linenr = $fh->input_line_number();
1775 my $prefix = "$filename (line $linenr)";
1777 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1779 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1783 warn "$prefix: skip line - no section";
1787 next if !$res->{$section}; # skip undefined section
1789 if ($section eq 'options
') {
1791 my ($opt, $value) = parse_vmfw_option($line);
1792 $res->{options}->{$opt} = $value;
1794 warn "$prefix: $@" if $@;
1799 eval { $rule = parse_fw_rule($line, 1, 1); };
1801 warn "$prefix: $err";
1805 push @{$res->{$section}}, $rule;
1808 $res->{digest} = $digest->b64digest;
1813 sub parse_host_fw_rules {
1814 my ($filename, $fh) = @_;
1816 my $res = { rules => [], options => {}};
1820 my $digest = Digest::SHA->new('sha1
');
1822 while (defined(my $line = <$fh>)) {
1823 $digest->add($line);
1825 next if $line =~ m/^#/;
1826 next if $line =~ m/^\s*$/;
1828 my $linenr = $fh->input_line_number();
1829 my $prefix = "$filename (line $linenr)";
1831 if ($line =~ m/^\[(\S+)\]\s*$/i) {
1833 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
1837 warn "$prefix: skip line - no section";
1841 next if !$res->{$section}; # skip undefined section
1843 if ($section eq 'options
') {
1845 my ($opt, $value) = parse_hostfw_option($line);
1846 $res->{options}->{$opt} = $value;
1848 warn "$prefix: $@" if $@;
1853 eval { $rule = parse_fw_rule($line, 1, 1); };
1855 warn "$prefix: $err";
1859 push @{$res->{$section}}, $rule;
1862 $res->{digest} = $digest->b64digest;
1867 sub parse_cluster_fw_rules {
1868 my ($filename, $fh) = @_;
1873 my $res = { rules => [], options => {}, groups => {}, ipset => {} };
1875 my $digest = Digest::SHA->new('sha1
');
1877 while (defined(my $line = <$fh>)) {
1878 $digest->add($line);
1880 next if $line =~ m/^#/;
1881 next if $line =~ m/^\s*$/;
1883 my $linenr = $fh->input_line_number();
1884 my $prefix = "$filename (line $linenr)";
1886 if ($line =~ m/^\[options\]$/i) {
1887 $section = 'options
';
1891 if ($line =~ m/^\[group\s+(\S+)\]\s*$/i) {
1892 $section = 'groups
';
1897 if ($line =~ m/^\[rules\]$/i) {
1902 if ($line =~ m/^\[ipset\s+(\S+)\]\s*$/i) {
1909 warn "$prefix: skip line - no section\n";
1913 if ($section eq 'options
') {
1915 my ($opt, $value) = parse_clusterfw_option($line);
1916 $res->{options}->{$opt} = $value;
1918 warn "$prefix: $@" if $@;
1919 } elsif ($section eq 'rules
') {
1921 eval { $rule = parse_fw_rule($line, 1, 1); };
1923 warn "$prefix: $err";
1926 push @{$res->{$section}}, $rule;
1927 } elsif ($section eq 'groups
') {
1929 eval { $rule = parse_fw_rule($line, 0, 0); };
1931 warn "$prefix: $err";
1934 push @{$res->{$section}->{$group}}, $rule;
1935 } elsif ($section eq 'ipset
') {
1937 $line =~ m/^(\!)?\s*((\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?)/;
1942 warn "$prefix: $line is not an valid ip address\n";
1945 if (!Net::IP->new($ip)) {
1946 warn "$prefix: $line is not an valid ip address\n";
1951 if ($feature_ipset_nomatch) {
1952 push @{$res->{$section}->{$group}}, "$ip nomatch";
1954 warn "$prefix: ignore $line - nomatch not supported by kernel\n";
1957 push @{$res->{$section}->{$group}}, $ip;
1962 $res->{digest} = $digest->b64digest;
1967 my ($code, @param) = @_;
1971 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
1978 sub read_local_vm_config {
1983 my $vmdata = { openvz => $openvz, qemu => $qemu };
1985 my $vmlist = PVE::Cluster::get_vmlist();
1986 return $vmdata if !$vmlist || !$vmlist->{ids};
1987 my $ids = $vmlist->{ids};
1989 foreach my $vmid (keys %$ids) {
1990 next if !$vmid; # skip VE0
1991 my $d = $ids->{$vmid};
1992 next if !$d->{node} || $d->{node} ne $nodename;
1993 next if !$d->{type};
1994 if ($d->{type} eq 'openvz
') {
1995 if ($have_pve_manager) {
1996 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
1997 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
1998 $openvz->{$vmid} = $conf;
2001 } elsif ($d->{type} eq 'qemu
') {
2002 if ($have_qemu_server) {
2003 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2004 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2005 $qemu->{$vmid} = $conf;
2014 sub load_vmfw_conf {
2019 my $filename = "/etc/pve/firewall/$vmid.fw";
2020 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2021 $vmfw_conf = parse_vm_fw_rules($filename, $fh);
2027 my $format_rules = sub {
2028 my ($rules, $need_iface) = @_;
2032 foreach my $rule (@$rules) {
2033 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
') {
2034 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2035 $raw .= uc($rule->{type});
2036 $raw .= " " . $rule->{action};
2037 $raw .= " " . ($rule->{iface} || '-') if $need_iface;
2038 $raw .= " " . ($rule->{source} || '-');
2039 $raw .= " " . ($rule->{dest} || '-');
2040 $raw .= " " . ($rule->{proto} || '-');
2041 $raw .= " " . ($rule->{dport} || '-');
2042 $raw .= " " . ($rule->{sport} || '-');
2043 $raw .= " # " . encode('utf8
', $rule->{comment})
2044 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2047 die "implement me '$rule->{type
}'";
2054 my $format_options = sub {
2059 $raw .= "[OPTIONS]\n\n";
2060 foreach my $opt (keys %$options) {
2061 $raw .= "$opt: $options->{$opt}\n";
2068 sub save_vmfw_conf {
2069 my ($vmid, $vmfw_conf) = @_;
2073 my $options = $vmfw_conf->{options};
2074 $raw .= &$format_options($options) if scalar(keys %$options);
2076 my $rules = $vmfw_conf->{rules};
2077 if (scalar(@$rules)) {
2078 $raw .= "[RULES]\n\n";
2079 $raw .= &$format_rules($rules, 1);
2083 my $filename = "/etc/pve/firewall/$vmid.fw";
2084 PVE::Tools::file_set_contents($filename, $raw);
2087 sub read_vm_firewall_configs {
2089 my $vmfw_configs = {};
2091 foreach my $vmid (keys %{$vmdata->{qemu}}, keys %{$vmdata->{openvz}}) {
2092 my $vmfw_conf = load_vmfw_conf($vmid);
2093 next if !$vmfw_conf->{options}; # skip if file does not exists
2094 $vmfw_configs->{$vmid} = $vmfw_conf;
2097 return $vmfw_configs;
2100 sub get_option_log_level {
2101 my ($options, $k) = @_;
2103 my $v = $options->{$k};
2104 $v = $default_log_level if !defined($v);
2106 return undef if $v eq '' || $v eq 'nolog
';
2108 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2110 return $v if ($v >= 0) && ($v <= 7);
2112 warn "unknown log level ($k = '$v')\n";
2117 sub generate_std_chains {
2118 my ($ruleset, $options) = @_;
2120 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2122 # same as shorewall smurflog.
2123 my $chain = 'PVEFW-smurflog
';
2125 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2126 push @{$pve_std_chains->{$chain}}, "-j DROP";
2128 # same as shorewall logflags action.
2129 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2130 $chain = 'PVEFW-logflags
';
2131 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2132 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2133 push @{$pve_std_chains->{$chain}}, "-j DROP";
2135 foreach my $chain (keys %$pve_std_chains) {
2136 ruleset_create_chain($ruleset, $chain);
2137 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2139 ruleset_generate_rule($ruleset, $chain, $rule);
2141 ruleset_addrule($ruleset, $chain, $rule);
2147 sub generate_ipset_chains {
2148 my ($ipset_ruleset, $fw_conf) = @_;
2150 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2151 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset});
2155 sub generate_ipset {
2156 my ($ipset_ruleset, $name, $options) = @_;
2158 my $hashsize = scalar(@$options);
2159 if ($hashsize <= 64) {
2162 $hashsize = round_powerof2($hashsize);
2165 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2167 foreach my $ip (@$options) {
2168 push @{$ipset_ruleset->{$name}}, "add $name $ip";
2172 sub round_powerof2 {
2176 $int |= $int >> $_ foreach (1,2,4,8,16);
2180 sub save_pvefw_status {
2183 die "unknown status '$status' - internal error"
2184 if $status !~ m/^(stopped|active)$/;
2186 mkdir dirname($pve_fw_status_filename);
2187 PVE::Tools::file_set_contents($pve_fw_status_filename, $status);
2190 sub read_pvefw_status {
2192 my $status = 'unknown
';
2194 return 'stopped
' if ! -f $pve_fw_status_filename;
2197 $status = PVE::Tools::file_get_contents($pve_fw_status_filename);
2204 # fixme: move to pve-common PVE::ProcFSTools
2205 sub read_proc_net_route {
2206 my $filename = "/proc/net/route";
2210 my $fh = IO::File->new ($filename, "r");
2211 return $res if !$fh;
2213 my $int_to_quad = sub {
2214 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
2217 while (defined(my $line = <$fh>)) {
2218 next if $line =~/^Iface\s+Destination/; # skip head
2219 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
2220 push @{$res->{$iface}}, {
2221 dest => &$int_to_quad(hex($dest)),
2222 gateway => &$int_to_quad(hex($gateway)),
2223 mask => &$int_to_quad(hex($mask)),
2232 sub load_clusterfw_conf {
2234 my $cluster_conf = {};
2235 if (my $fh = IO::File->new($clusterfw_conf_filename, O_RDONLY)) {
2236 $cluster_conf = parse_cluster_fw_rules($clusterfw_conf_filename, $fh);
2239 return $cluster_conf;
2242 sub save_clusterfw_conf {
2243 my ($cluster_conf) = @_;
2247 my $options = $cluster_conf->{options};
2248 $raw .= &$format_options($options) if scalar(keys %$options);
2252 my $rules = $cluster_conf->{rules};
2253 if (scalar(@$rules)) {
2254 $raw .= "[RULES]\n\n";
2255 $raw .= &$format_rules($rules, 1);
2259 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2260 my $rules = $cluster_conf->{groups}->{$group};
2261 $raw .= "[group $group]\n\n";
2262 $raw .= &$format_rules($rules, 0);
2266 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2269 sub load_hostfw_conf {
2271 my $hostfw_conf = {};
2272 if (my $fh = IO::File->new($hostfw_conf_filename, O_RDONLY)) {
2273 $hostfw_conf = parse_host_fw_rules($hostfw_conf_filename, $fh);
2275 return $hostfw_conf;
2278 sub save_hostfw_conf {
2279 my ($hostfw_conf) = @_;
2283 my $options = $hostfw_conf->{options};
2284 $raw .= &$format_options($options) if scalar(keys %$options);
2286 my $rules = $hostfw_conf->{rules};
2287 if (scalar(@$rules)) {
2288 $raw .= "[RULES]\n\n";
2289 $raw .= &$format_rules($rules, 1);
2293 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2297 my $vmdata = read_local_vm_config();
2298 my $vmfw_configs = read_vm_firewall_configs($vmdata);
2300 my $routing_table = read_proc_net_route();
2302 my $cluster_conf = load_clusterfw_conf();
2304 my $ipset_ruleset = {};
2305 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2309 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2310 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2312 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2314 my $hostfw_conf = load_hostfw_conf();
2315 my $hostfw_options = $hostfw_conf->{options} || {};
2317 generate_std_chains($ruleset, $hostfw_options);
2319 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2321 enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf) if $hostfw_enable;
2323 # generate firewall rules for QEMU VMs
2324 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2325 my $conf = $vmdata->{qemu}->{$vmid};
2326 my $vmfw_conf = $vmfw_configs->{$vmid};
2327 next if !$vmfw_conf;
2328 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2330 foreach my $netid (keys %$conf) {
2331 next if $netid !~ m/^net(\d+)$/;
2332 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2334 my $iface = "tap${vmid}i$1";
2336 my $bridge = $net->{bridge};
2337 next if !$bridge; # fixme: ?
2339 $bridge .= "v$net->{tag}" if $net->{tag};
2341 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2343 my $macaddr = $net->{macaddr};
2344 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2345 $vmfw_conf, $vmid, $bridge, 'IN
');
2346 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2347 $vmfw_conf, $vmid, $bridge, 'OUT
');
2351 # generate firewall rules for OpenVZ containers
2352 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2353 my $conf = $vmdata->{openvz}->{$vmid};
2355 my $vmfw_conf = $vmfw_configs->{$vmid};
2356 next if !$vmfw_conf;
2357 next if defined($vmfw_conf->{options}->{enable}) && ($vmfw_conf->{options}->{enable} == 0);
2359 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2360 my $ip = $conf->{ip_address}->{value};
2361 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2362 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2365 if ($conf->{netif} && $conf->{netif}->{value}) {
2366 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2367 foreach my $netid (keys %$netif) {
2368 my $d = $netif->{$netid};
2369 my $bridge = $d->{bridge};
2371 warn "no bridge device for CT $vmid iface '$netid'\n";
2375 generate_bridge_chains($ruleset, $hostfw_conf, $bridge, $routing_table);
2377 my $macaddr = $d->{mac};
2378 my $iface = $d->{host_ifname};
2379 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2380 $vmfw_conf, $vmid, $bridge, 'IN
');
2381 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2382 $vmfw_conf, $vmid, $bridge, 'OUT
');
2387 if($hostfw_options->{optimize}){
2389 my $accept = ruleset_chain_exist($ruleset, "PVEFW-IPS") ? "PVEFW-IPS" : "ACCEPT";
2390 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j $accept");
2391 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate INVALID -j DROP");
2394 # fixme: what log level should we use here?
2395 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2397 # fixme: should we really block inter-bridge traffic?
2399 # always allow traffic from containers?
2400 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -j RETURN");
2402 # disable interbridge routing
2403 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j PVEFW-Drop");
2404 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j PVEFW-Drop");
2405 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-o vmbr+");
2406 ruleset_addlog($ruleset, "PVEFW-FORWARD", 0, "DROP: ", $loglevel, "-i vmbr+");
2407 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o vmbr+ -j DROP");
2408 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i vmbr+ -j DROP");
2410 return wantarray ? ($ruleset, $hostfw_conf, $ipset_ruleset) : $ruleset;
2413 sub get_ruleset_status {
2414 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2416 my $statushash = {};
2418 foreach my $chain (sort keys %$ruleset) {
2419 my $sig = &$digest_fn($ruleset->{$chain});
2421 $statushash->{$chain}->{sig} = $sig;
2423 my $oldsig = $active_chains->{$chain};
2424 if (!defined($oldsig)) {
2425 $statushash->{$chain}->{action} = 'create
';
2427 if ($oldsig eq $sig) {
2428 $statushash->{$chain}->{action} = 'exists';
2430 $statushash->{$chain}->{action} = 'update
';
2433 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2434 foreach my $cmd (@{$ruleset->{$chain}}) {
2435 print "\t$cmd\n" if $verbose;
2439 foreach my $chain (sort keys %$active_chains) {
2440 if (!defined($ruleset->{$chain})) {
2441 my $sig = $active_chains->{$chain};
2442 $statushash->{$chain}->{action} = 'delete';
2443 $statushash->{$chain}->{sig} = $sig;
2444 print "delete $chain ($sig)\n" if $verbose;
2451 sub print_sig_rule {
2452 my ($chain, $sig) = @_;
2454 # We just use this to store a SHA1 checksum used to detect changes
2455 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2458 sub get_ruleset_cmdlist {
2459 my ($ruleset, $verbose) = @_;
2461 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2463 my ($active_chains, $hooks) = iptables_get_chains();
2464 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2466 # create missing chains first
2467 foreach my $chain (sort keys %$ruleset) {
2468 my $stat = $statushash->{$chain};
2469 die "internal error" if !$stat;
2470 next if $stat->{action} ne 'create
';
2472 $cmdlist .= ":$chain - [0:0]\n";
2475 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2476 if (!$hooks->{$h}) {
2477 $cmdlist .= "-A $h -j PVEFW-$h\n";
2481 foreach my $chain (sort keys %$ruleset) {
2482 my $stat = $statushash->{$chain};
2483 die "internal error" if !$stat;
2485 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2486 $cmdlist .= "-F $chain\n";
2487 foreach my $cmd (@{$ruleset->{$chain}}) {
2488 $cmdlist .= "$cmd\n";
2490 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2491 } elsif ($stat->{action
} eq 'delete') {
2492 die "internal error"; # this should not happen
2493 } elsif ($stat->{action
} eq 'exists') {
2496 die "internal error - unknown status '$stat->{action}'";
2500 foreach my $chain (keys %$statushash) {
2501 next if $statushash->{$chain}->{action
} ne 'delete';
2502 $cmdlist .= "-F $chain\n";
2504 foreach my $chain (keys %$statushash) {
2505 next if $statushash->{$chain}->{action
} ne 'delete';
2506 next if $chain eq 'PVEFW-INPUT';
2507 next if $chain eq 'PVEFW-OUTPUT';
2508 next if $chain eq 'PVEFW-FORWARD';
2509 $cmdlist .= "-X $chain\n";
2512 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2514 $cmdlist .= "COMMIT\n";
2516 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2519 sub get_ipset_cmdlist
{
2520 my ($ruleset, $verbose) = @_;
2524 my $delete_cmdlist = "";
2526 my $active_chains = ipset_get_chains
();
2527 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2529 foreach my $chain (sort keys %$ruleset) {
2530 my $stat = $statushash->{$chain};
2531 die "internal error" if !$stat;
2533 if ($stat->{action
} eq 'create') {
2534 foreach my $cmd (@{$ruleset->{$chain}}) {
2535 $cmdlist .= "$cmd\n";
2539 if ($stat->{action
} eq 'update') {
2540 my $chain_swap = $chain."_swap";
2542 foreach my $cmd (@{$ruleset->{$chain}}) {
2543 $cmd =~ s/$chain/$chain_swap/;
2544 $cmdlist .= "$cmd\n";
2546 $cmdlist .= "swap $chain_swap $chain\n";
2547 $cmdlist .= "flush $chain_swap\n";
2548 $cmdlist .= "destroy $chain_swap\n";
2553 foreach my $chain (keys %$statushash) {
2554 next if $statushash->{$chain}->{action
} ne 'delete';
2556 $delete_cmdlist .= "flush $chain\n";
2557 $delete_cmdlist .= "destroy $chain\n";
2560 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
2562 return ($cmdlist, $delete_cmdlist, $changes);
2566 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
2568 enable_bridge_firewall
();
2570 update_nf_conntrack_max
($hostfw_conf);
2572 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
2573 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
2575 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
2578 if ($ipset_changes) {
2579 print "ipset changes:\n";
2580 print $ipset_create_cmdlist if $ipset_create_cmdlist;
2581 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
2585 print "iptables changes:\n";
2590 ipset_restore_cmdlist
($ipset_create_cmdlist);
2592 iptables_restore_cmdlist
($cmdlist);
2594 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
2596 # test: re-read status and check if everything is up to date
2597 my $active_chains = iptables_get_chains
();
2598 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
2601 foreach my $chain (sort keys %$ruleset) {
2602 my $stat = $statushash->{$chain};
2603 if ($stat->{action
} ne 'exists') {
2604 warn "unable to update chain '$chain'\n";
2609 die "unable to apply firewall changes\n" if $errors;
2612 sub update_nf_conntrack_max
{
2613 my ($hostfw_conf) = @_;
2615 my $max = 65536; # reasonable default
2617 my $options = $hostfw_conf->{options
} || {};
2619 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
2620 $max = $options->{nf_conntrack_max
};
2621 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
2624 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
2625 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
2627 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
2629 if ($current != $max) {
2630 my $hashsize = int($max/4);
2631 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
2632 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
2636 sub remove_pvefw_chains
{
2638 my ($chash, $hooks) = iptables_get_chains
();
2639 my $cmdlist = "*filter\n";
2641 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2643 $cmdlist .= "-D $h -j PVEFW-$h\n";
2647 foreach my $chain (keys %$chash) {
2648 $cmdlist .= "-F $chain\n";
2651 foreach my $chain (keys %$chash) {
2652 $cmdlist .= "-X $chain\n";
2654 $cmdlist .= "COMMIT\n";
2656 iptables_restore_cmdlist
($cmdlist);
2660 my ($start, $verbose) = @_;
2663 my $status = read_pvefw_status
();
2665 my ($ruleset, $hostfw_conf, $ipset_ruleset) = compile
();
2667 if ($start || $status eq 'active') {
2669 save_pvefw_status
('active') if ($status ne 'active');
2671 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $verbose);
2673 print "Firewall not active (status = $status)\n" if $verbose;