8 use Socket
qw(AF_INET6 inet_ntop inet_pton);
10 use PVE
::Exception
qw(raise raise_param_exc);
11 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
14 use PVE
::Tools
qw($IPV4RE $IPV6RE);
19 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
22 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
23 my $pvefw_conf_dir = "/etc/pve/firewall";
24 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
26 # dynamically include PVE::QemuServer and PVE::LXC
27 # to avoid dependency problems
30 require PVE
::QemuServer
;
31 require PVE
::QemuConfig
;
32 $have_qemu_server = 1;
42 my $pve_fw_status_dir = "/var/lib/pve-firewall";
44 mkdir $pve_fw_status_dir; # make sure this exists
46 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
47 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
48 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
50 my $max_alias_name_length = 64;
51 my $max_ipset_name_length = 64;
52 my $max_group_name_length = 20;
54 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
55 sub pve_verify_ip_or_cidr
{
56 my ($cidr, $noerr) = @_;
58 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
59 return $cidr if Net
::IP-
>new($cidr);
60 return undef if $noerr;
61 die Net
::IP
::Error
() . "\n";
63 return undef if $noerr;
64 die "value does not look like a valid IP address or CIDR network\n";
67 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
68 sub pve_verify_ip_or_cidr_or_alias
{
69 my ($cidr, $noerr) = @_;
71 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
73 return pve_verify_ip_or_cidr
($cidr, $noerr);
76 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
77 description
=> "IP set name.",
79 pattern
=> $ipset_name_pattern,
81 maxLength
=> $max_ipset_name_length,
84 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
85 description
=> "Alias name.",
87 pattern
=> $ip_alias_pattern,
89 maxLength
=> $max_alias_name_length,
92 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
93 description
=> "Log level.",
95 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
99 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
100 description
=> "Security Group name.",
102 pattern
=> $security_group_name_pattern,
104 maxLength
=> $max_group_name_length,
107 my $feature_ipset_nomatch = 0;
109 my (undef, undef, $release) = POSIX
::uname
();
110 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
111 my ($major, $minor) = ($1, $2);
112 $feature_ipset_nomatch = 1 if ($major > 3) ||
113 ($major == 3 && $minor >= 7);
118 my $nodename = PVE
::INotify
::nodename
();
120 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
122 my $default_log_level = 'nolog'; # avoid logs by default
124 my $log_level_hash = {
135 # we need to overwrite some macros for ipv6
136 my $pve_ipv6fw_macros = {
138 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
140 'NeighborDiscovery' => [
141 "IPv6 neighbor solicitation, neighbor and router advertisement",
142 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-solicitation' },
143 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-advertisement' },
144 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-solicitation' },
145 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-advertisement' },
148 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
151 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
152 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
156 # imported/converted from: /usr/share/shorewall/macro.*
157 my $pve_fw_macros = {
160 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
161 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
164 "Auth (identd) traffic",
165 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
168 "Border Gateway Protocol traffic",
169 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
172 "BitTorrent traffic for BitTorrent 3.1 and earlier",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
174 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
177 "BitTorrent traffic for BitTorrent 3.2 and later",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
179 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
182 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
183 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6789' },
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6800:7300' },
187 "Concurrent Versions System pserver traffic",
188 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
191 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
192 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
193 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
197 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
199 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
202 "Distributed Checksum Clearinghouse spam filtering mechanism",
203 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
206 "Forwarded DHCP traffic",
207 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
210 "Domain Name System traffic (upd and tcp)",
211 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
212 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
215 "Distributed Compiler service",
216 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
219 "File Transfer Protocol",
220 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
223 "Finger protocol (RFC 742)",
224 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
227 "GNUnet secure peer-to-peer networking traffic",
228 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
229 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
230 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
231 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
234 "Generic Routing Encapsulation tunneling protocol",
235 { action
=> 'PARAM', proto
=> '47' },
238 "Git distributed revision control traffic",
239 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
242 "OpenPGP HTTP keyserver protocol traffic",
243 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
246 "Hypertext Transfer Protocol (WWW)",
247 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
250 "Hypertext Transfer Protocol (WWW) over SSL",
251 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
254 "Internet Cache Protocol V2 (Squid) traffic",
255 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
258 "AOL Instant Messenger traffic",
259 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
262 "Internet Message Access Protocol",
263 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
266 "Internet Message Access Protocol over SSL",
267 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
270 "IPIP capsulation traffic",
271 { action
=> 'PARAM', proto
=> '94' },
275 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
276 { action
=> 'PARAM', proto
=> '50' },
279 "IPsec authentication (AH) traffic",
280 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
281 { action
=> 'PARAM', proto
=> '51' },
284 "IPsec traffic and Nat-Traversal",
285 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
286 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
287 { action
=> 'PARAM', proto
=> '50' },
290 "Internet Relay Chat traffic",
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
294 "HP Jetdirect printing",
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
298 "Layer 2 Tunneling Protocol traffic",
299 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
302 "Lightweight Directory Access Protocol traffic",
303 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
306 "Secure Lightweight Directory Access Protocol traffic",
307 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
310 "Microsoft Notification Protocol",
311 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
314 "Microsoft SQL Server",
315 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
318 "Mail traffic (SMTP, SMTPS, Submission)",
319 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
320 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
324 "Munin networked resource monitoring traffic",
325 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
332 "NNTP traffic (Usenet).",
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
336 "Encrypted NNTP traffic (Usenet)",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
340 "Network Time Protocol (ntpd)",
341 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
344 "OSPF multicast traffic",
345 { action
=> 'PARAM', proto
=> '89' },
349 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
352 "Symantec PCAnywere (tm)",
353 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
354 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
358 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
361 "Encrypted POP3 traffic",
362 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
365 "Point-to-Point Tunneling Protocol",
366 { action
=> 'PARAM', proto
=> '47' },
367 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
371 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
375 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
378 "Line Printer protocol printing",
379 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
382 "Microsoft Remote Desktop Protocol traffic",
383 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
386 "Routing Information Protocol (bidirectional)",
387 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
390 "BIND remote management protocol",
391 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
394 "Razor Antispam System",
395 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
398 "Remote time retrieval (rdate)",
399 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
403 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
406 "SANE network scanning",
407 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
410 "Microsoft SMB traffic",
411 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
412 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
413 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
414 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
417 "Samba Web Administration Tool",
418 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
421 "Simple Mail Transfer Protocol",
422 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
425 "Encrypted Simple Mail Transfer Protocol",
426 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
429 "Simple Network Management Protocol",
430 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
431 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
434 "Spam Assassin SPAMD traffic",
435 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
438 "Secure shell traffic",
439 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
442 "Subversion server (svnserve)",
443 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
446 "SixXS IPv6 Deployment and Tunnel Broker",
447 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
448 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
449 { action
=> 'PARAM', proto
=> '41' },
450 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
453 "Squid web proxy traffic",
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
457 "Mail message submission traffic",
458 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
461 "Syslog protocol (RFC 5424) traffic",
462 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
466 "Trivial File Transfer Protocol traffic",
467 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
471 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
475 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
478 "RFC 868 Time protocol",
479 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
482 "Traceroute (for up to 30 hops) traffic",
483 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
484 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
487 "VNC traffic for VNC display's 0 - 99",
488 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
491 "VNC traffic from Vncservers to Vncviewers in listen mode",
492 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
495 "WWW traffic (HTTP and HTTPS)",
496 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
497 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
500 "Web Cache/Proxy traffic (port 8080)",
501 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
505 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
508 "Whois (nicname, RFC 3912) traffic",
509 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
513 my $pve_fw_parsed_macros;
514 my $pve_fw_macro_descr;
515 my $pve_fw_macro_ipversion = {};
516 my $pve_fw_preferred_macro_names = {};
518 my $pve_std_chains = {};
519 $pve_std_chains->{4} = {
520 'PVEFW-SET-ACCEPT-MARK' => [
521 "-j MARK --set-mark 1",
523 'PVEFW-DropBroadcast' => [
524 # same as shorewall 'Broadcast'
525 # simply DROP BROADCAST/MULTICAST/ANYCAST
526 # we can use this to reduce logging
527 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
528 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
529 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
530 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
533 # same as shorewall 'reject'
534 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
535 { action
=> 'DROP', source
=> '224.0.0.0/4' },
536 { action
=> 'DROP', proto
=> 'icmp' },
537 "-p tcp -j REJECT --reject-with tcp-reset",
538 "-p udp -j REJECT --reject-with icmp-port-unreachable",
539 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
540 "-j REJECT --reject-with icmp-host-prohibited",
543 # same as shorewall 'Drop', which is equal to DROP,
544 # but REJECT/DROP some packages to reduce logging,
545 # and ACCEPT critical ICMP types
546 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
547 # we are not interested in BROADCAST/MULTICAST/ANYCAST
548 { action
=> 'PVEFW-DropBroadcast' },
549 # ACCEPT critical ICMP types
550 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
551 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
552 # Drop packets with INVALID state
553 "-m conntrack --ctstate INVALID -j DROP",
554 # Drop Microsoft SMB noise
555 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
556 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
557 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
558 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
559 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
560 # Drop new/NotSyn traffic so that it doesn't get logged
561 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
563 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
566 # same as shorewall 'Reject', which is equal to Reject,
567 # but REJECT/DROP some packages to reduce logging,
568 # and ACCEPT critical ICMP types
569 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
570 # we are not interested in BROADCAST/MULTICAST/ANYCAST
571 { action
=> 'PVEFW-DropBroadcast' },
572 # ACCEPT critical ICMP types
573 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
574 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
575 # Drop packets with INVALID state
576 "-m conntrack --ctstate INVALID -j DROP",
577 # Drop Microsoft SMB noise
578 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
579 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
580 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
581 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
582 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
583 # Drop new/NotSyn traffic so that it doesn't get logged
584 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
586 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
588 'PVEFW-tcpflags' => [
589 # same as shorewall tcpflags action.
590 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
591 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
592 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
593 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
594 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
595 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
598 # same as shorewall smurfs action
599 # Filter packets for smurfs (packets with a broadcast address as the source).
600 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
601 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
602 "-s 224.0.0.0/4 -g PVEFW-smurflog",
606 $pve_std_chains->{6} = {
607 'PVEFW-SET-ACCEPT-MARK' => [
608 "-j MARK --set-mark 1",
610 'PVEFW-DropBroadcast' => [
611 # same as shorewall 'Broadcast'
612 # simply DROP BROADCAST/MULTICAST/ANYCAST
613 # we can use this to reduce logging
614 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
615 # ipv6 addrtype does not work with kernel 2.6.32
616 #{ action => 'DROP', dsttype => 'MULTICAST' },
617 #{ action => 'DROP', dsttype => 'ANYCAST' },
618 { action
=> 'DROP', dest
=> 'ff00::/8' },
619 #{ action => 'DROP', dest => '224.0.0.0/4' },
622 # same as shorewall 'reject'
623 #{ action => 'DROP', dsttype => 'BROADCAST' },
624 #{ action => 'DROP', source => '224.0.0.0/4' },
625 { action
=> 'DROP', proto
=> 'icmpv6' },
626 "-p tcp -j REJECT --reject-with tcp-reset",
627 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
628 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
629 #"-j REJECT --reject-with icmp-host-prohibited",
632 # same as shorewall 'Drop', which is equal to DROP,
633 # but REJECT/DROP some packages to reduce logging,
634 # and ACCEPT critical ICMP types
635 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
636 # we are not interested in BROADCAST/MULTICAST/ANYCAST
637 { action
=> 'PVEFW-DropBroadcast' },
638 # ACCEPT critical ICMP types
639 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
640 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
641 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
643 # Drop packets with INVALID state
644 "-m conntrack --ctstate INVALID -j DROP",
645 # Drop Microsoft SMB noise
646 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
647 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
648 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
649 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
650 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
651 # Drop new/NotSyn traffic so that it doesn't get logged
652 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
654 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
657 # same as shorewall 'Reject', which is equal to Reject,
658 # but REJECT/DROP some packages to reduce logging,
659 # and ACCEPT critical ICMP types
660 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
661 # we are not interested in BROADCAST/MULTICAST/ANYCAST
662 { action
=> 'PVEFW-DropBroadcast' },
663 # ACCEPT critical ICMP types
664 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
665 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
666 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
668 # Drop packets with INVALID state
669 "-m conntrack --ctstate INVALID -j DROP",
670 # Drop Microsoft SMB noise
671 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
672 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
673 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
674 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
675 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
676 # Drop new/NotSyn traffic so that it doesn't get logged
677 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
679 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
681 'PVEFW-tcpflags' => [
682 # same as shorewall tcpflags action.
683 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
684 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
685 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
686 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
687 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
688 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
692 # iptables -p icmp -h
693 my $icmp_type_names = {
696 'destination-unreachable' => 1,
697 'network-unreachable' => 1,
698 'host-unreachable' => 1,
699 'protocol-unreachable' => 1,
700 'port-unreachable' => 1,
701 'fragmentation-needed' => 1,
702 'source-route-failed' => 1,
703 'network-unknown' => 1,
705 'network-prohibited' => 1,
706 'host-prohibited' => 1,
707 'TOS-network-unreachable' => 1,
708 'TOS-host-unreachable' => 1,
709 'communication-prohibited' => 1,
710 'host-precedence-violation' => 1,
711 'precedence-cutoff' => 1,
712 'source-quench' => 1,
714 'network-redirect' => 1,
715 'host-redirect' => 1,
716 'TOS-network-redirect' => 1,
717 'TOS-host-redirect' => 1,
719 'router-advertisement' => 1,
720 'router-solicitation' => 1,
721 'time-exceeded' => 1,
722 'ttl-zero-during-transit' => 1,
723 'ttl-zero-during-reassembly' => 1,
724 'parameter-problem' => 1,
725 'ip-header-bad' => 1,
726 'required-option-missing' => 1,
727 'timestamp-request' => 1,
728 'timestamp-reply' => 1,
729 'address-mask-request' => 1,
730 'address-mask-reply' => 1,
733 # ip6tables -p icmpv6 -h
735 my $icmpv6_type_names = {
737 'destination-unreachable' => 1,
739 'communication-prohibited' => 1,
740 'address-unreachable' => 1,
741 'port-unreachable' => 1,
742 'packet-too-big' => 1,
743 'time-exceeded' => 1,
744 'ttl-zero-during-transit' => 1,
745 'ttl-zero-during-reassembly' => 1,
746 'parameter-problem' => 1,
748 'unknown-header-type' => 1,
749 'unknown-option' => 1,
752 'router-solicitation' => 1,
753 'router-advertisement' => 1,
754 'neighbor-solicitation' => 1,
755 'neighbour-solicitation' => 1,
756 'neighbor-advertisement' => 1,
757 'neighbour-advertisement' => 1,
761 sub init_firewall_macros
{
763 $pve_fw_parsed_macros = {};
766 my ($k, $macro) = @_;
767 my $lc_name = lc($k);
768 $pve_fw_macro_ipversion->{$k} = 0;
769 while (!ref($macro->[0])) {
770 my $desc = shift @$macro;
771 if ($desc eq 'ipv4only') {
772 $pve_fw_macro_ipversion->{$k} = 4;
773 } elsif ($desc eq 'ipv6only') {
774 $pve_fw_macro_ipversion->{$k} = 6;
776 $pve_fw_macro_descr->{$k} = $desc;
779 $pve_fw_preferred_macro_names->{$lc_name} = $k;
780 $pve_fw_parsed_macros->{$k} = $macro;
783 foreach my $k (keys %$pve_fw_macros) {
784 &$parse($k, $pve_fw_macros->{$k});
787 foreach my $k (keys %$pve_ipv6fw_macros) {
788 next if $pve_fw_parsed_macros->{$k};
789 &$parse($k, $pve_ipv6fw_macros->{$k});
790 $pve_fw_macro_ipversion->{$k} = 6;
794 init_firewall_macros
();
797 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
802 sub get_etc_services
{
804 return $etc_services if $etc_services;
806 my $filename = "/etc/services";
808 my $fh = IO
::File-
>new($filename, O_RDONLY
);
810 warn "unable to read '$filename' - $!\n";
816 while (my $line = <$fh>) {
818 next if $line =~m/^#/;
819 next if ($line =~m/^\s*$/);
821 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
822 $services->{byid
}->{$2}->{name
} = $1;
823 $services->{byid
}->{$2}->{port
} = $2;
824 $services->{byid
}->{$2}->{$3} = 1;
825 $services->{byname
}->{$1} = $services->{byid
}->{$2};
831 $etc_services = $services;
834 return $etc_services;
839 sub get_etc_protocols
{
840 return $etc_protocols if $etc_protocols;
842 my $filename = "/etc/protocols";
844 my $fh = IO
::File-
>new($filename, O_RDONLY
);
846 warn "unable to read '$filename' - $!\n";
852 while (my $line = <$fh>) {
854 next if $line =~m/^#/;
855 next if ($line =~m/^\s*$/);
857 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
858 $protocols->{byid
}->{$2}->{name
} = $1;
859 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
865 # add special case for ICMP v6
866 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
867 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
869 $etc_protocols = $protocols;
871 return $etc_protocols;
874 my $ipv4_mask_hash_localnet = {
876 '255.255.128.0' => 17,
877 '255.255.192.0' => 18,
878 '255.255.224.0' => 19,
879 '255.255.240.0' => 20,
880 '255.255.248.0' => 21,
881 '255.255.252.0' => 22,
882 '255.255.254.0' => 23,
883 '255.255.255.0' => 24,
884 '255.255.255.128' => 25,
885 '255.255.255.192' => 26,
886 '255.255.255.224' => 27,
887 '255.255.255.240' => 28,
888 '255.255.255.248' => 29,
889 '255.255.255.252' => 30,
895 my ($new_value) = @_;
897 $__local_network = $new_value if defined($new_value);
899 return $__local_network if defined($__local_network);
902 my $nodename = PVE
::INotify
::nodename
();
904 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
906 my $testip = Net
::IP-
>new($ip);
908 my $isv6 = $testip->version == 6;
909 my $routes = $isv6 ? PVE
::ProcFSTools
::read_proc_net_ipv6_route
()
910 : PVE
::ProcFSTools
::read_proc_net_route
();
911 foreach my $entry (@$routes) {
914 $mask = $entry->{prefix
};
916 $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
917 next if !defined($mask);
919 my $cidr = "$entry->{dest}/$mask";
920 my $testnet = Net
::IP-
>new($cidr);
921 if ($testnet->overlaps($testip) == $Net::IP
::IP_B_IN_A_OVERLAP
) {
922 $__local_network = $cidr;
929 return $__local_network;
932 # ipset names are limited to 31 characters,
933 # and we use '-v4' or '-v6' to indicate IP versions,
934 # and we use '_swap' suffix for atomic update,
935 # for example PVEFW-${VMID}-${ipset_name}_swap
937 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
939 sub compute_ipset_chain_name
{
940 my ($vmid, $ipset_name, $ipversion) = @_;
942 $vmid = 0 if !defined($vmid);
944 my $id = "$vmid-${ipset_name}-v$ipversion";
946 if (length($id) > $max_iptables_ipset_name_length) {
947 $id = PVE
::Tools
::fnv31a_hex
($id);
953 sub compute_ipfilter_ipset_name
{
956 return "ipfilter-$iface";
959 sub parse_address_list
{
962 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
963 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
967 if ($str =~ m/^${ip_alias_pattern}$/) {
968 die "alias name too long\n" if length($str) > $max_alias_name_length;
976 foreach my $elem (split(/,/, $str)) {
978 my $ip = Net
::IP-
>new($elem);
980 my $err = Net
::IP
::Error
();
981 die "invalid IP address: $err\n";
983 $iprange = 1 if $elem =~ m/-/;
985 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
987 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
988 if $ipversion && ($new_ipversion != $ipversion);
990 $ipversion = $new_ipversion;
993 die "you can't use a range in a list\n" if $iprange && $count > 1;
998 sub parse_port_name_number_or_range
{
999 my ($str, $dport) = @_;
1001 my $services = PVE
::Firewall
::get_etc_services
();
1005 foreach my $item (split(/,/, $str)) {
1007 if ($item =~ m/^(\d+):(\d+)$/) {
1008 my ($port1, $port2) = ($1, $2);
1009 die "invalid port '$port1'\n" if $port1 > 65535;
1010 die "invalid port '$port2'\n" if $port2 > 65535;
1011 } elsif ($item =~ m/^(\d+)$/) {
1013 die "invalid port '$port'\n" if $port > 65535;
1015 if ($dport && $icmp_type_names->{$item}) {
1017 } elsif ($dport && $icmpv6_type_names->{$item}) {
1020 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1025 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1030 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1031 sub pve_fw_verify_sport_spec
{
1034 parse_port_name_number_or_range
($portstr, 0);
1039 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1040 sub pve_fw_verify_dport_spec
{
1043 parse_port_name_number_or_range
($portstr, 1);
1048 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1049 sub pve_fw_verify_addr_spec
{
1052 parse_address_list
($list);
1057 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1058 sub pve_fw_verify_protocol_spec
{
1061 my $protocols = get_etc_protocols
();
1063 die "unknown protocol '$proto'\n" if $proto &&
1064 !(defined($protocols->{byname
}->{$proto}) ||
1065 defined($protocols->{byid
}->{$proto}));
1071 # helper function for API
1073 sub copy_opject_with_digest
{
1076 my $sha = Digest
::SHA-
>new('sha1');
1079 foreach my $k (sort keys %$object) {
1080 my $v = $object->{$k};
1081 next if !defined($v);
1083 $sha->add($k, ':', $v, "\n");
1086 my $digest = $sha->hexdigest;
1088 $res->{digest
} = $digest;
1090 return wantarray ?
($res, $digest) : $res;
1093 sub copy_list_with_digest
{
1096 my $sha = Digest
::SHA-
>new('sha1');
1099 foreach my $entry (@$list) {
1101 foreach my $k (sort keys %$entry) {
1102 my $v = $entry->{$k};
1103 next if !defined($v);
1105 # Note: digest ignores refs ($rule->{errors})
1106 # since Digest::SHA expects a series of bytes,
1107 # we have to encode the value here to prevent errors when
1108 # using utf8 characters (eg. in comments)
1109 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1114 my $digest = $sha->hexdigest;
1116 foreach my $entry (@$res) {
1117 $entry->{digest
} = $digest;
1120 return wantarray ?
($res, $digest) : $res;
1123 my $rule_properties = {
1125 description
=> "Update rule at position <pos>.",
1130 digest
=> get_standard_option
('pve-config-digest'),
1134 enum
=> ['in', 'out', 'group'],
1137 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1140 pattern
=> $security_group_name_pattern,
1149 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
1151 type
=> 'string', format
=> 'pve-fw-addr-spec',
1155 type
=> 'string', format
=> 'pve-fw-addr-spec',
1159 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1168 type
=> 'string', format
=> 'pve-fw-sport-spec',
1172 type
=> 'string', format
=> 'pve-fw-dport-spec',
1181 sub add_rule_properties
{
1182 my ($properties) = @_;
1184 foreach my $k (keys %$rule_properties) {
1185 my $h = $rule_properties->{$k};
1186 # copy data, so that we can modify later without side effects
1187 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1193 sub delete_rule_properties
{
1194 my ($rule, $delete_str) = @_;
1196 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1197 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1198 if !defined($rule_properties->{$opt});
1199 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1200 if $opt eq 'type' || $opt eq 'action';
1201 delete $rule->{$opt};
1207 my $apply_macro = sub {
1208 my ($macro_name, $param, $verify, $ipversion) = @_;
1210 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1211 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1213 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1214 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1217 # skip macros which are specific to another ipversion
1218 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1219 return if $ipversion != $required;
1224 foreach my $templ (@$macro_rules) {
1226 my $param_used = {};
1227 foreach my $k (keys %$templ) {
1228 my $v = $templ->{$k};
1229 if ($v eq 'PARAM') {
1231 $param_used->{$k} = 1;
1232 } elsif ($v eq 'DEST') {
1233 $v = $param->{dest
};
1234 $param_used->{dest
} = 1;
1235 } elsif ($v eq 'SOURCE') {
1236 $v = $param->{source
};
1237 $param_used->{source
} = 1;
1241 my $msg = "missing parameter '$k' in macro '$macro_name'";
1242 raise_param_exc
({ macro => $msg }) if $verify;
1247 foreach my $k (keys %$param) {
1248 next if $k eq 'macro';
1249 next if !defined($param->{$k});
1250 next if $param_used->{$k};
1251 if (defined($rule->{$k})) {
1252 if ($rule->{$k} ne $param->{$k}) {
1253 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1254 raise_param_exc
({ $k => $msg }) if $verify;
1258 $rule->{$k} = $param->{$k};
1261 push @$rules, $rule;
1267 my $rule_env_iface_lookup = {
1276 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1278 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1280 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1281 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1283 my $errors = $rule->{errors
} || {};
1285 my $error_count = 0;
1287 my $add_error = sub {
1288 my ($param, $msg) = @_;
1290 raise_param_exc
({ $param => $msg }) if !$noerr;
1292 $errors->{$param} = $msg if !$errors->{$param};
1296 my $set_ip_version = sub {
1299 die "detected mixed ipv4/ipv6 adresses in rule\n"
1300 if $ipversion && ($vers != $ipversion);
1305 my $check_ipset_or_alias_property = sub {
1306 my ($name, $expected_ipversion) = @_;
1308 if (my $value = $rule->{$name}) {
1309 if ($value =~ m/^\+/) {
1310 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1311 &$add_error($name, "no such ipset '$1'")
1312 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1315 &$add_error($name, "invalid ipset name '$value'");
1317 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1318 my $alias = lc($value);
1319 &$add_error($name, "no such alias '$value'")
1320 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1321 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1322 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1324 &$set_ip_version($e->{ipversion
});
1329 my $type = $rule->{type
};
1330 my $action = $rule->{action
};
1332 &$add_error('type', "missing property") if !$type;
1333 &$add_error('action', "missing property") if !$action;
1336 if ($type eq 'in' || $type eq 'out') {
1337 &$add_error('action', "unknown action '$action'")
1338 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1339 } elsif ($type eq 'group') {
1340 &$add_error('type', "security groups not allowed")
1342 &$add_error('action', "invalid characters in security group name")
1343 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1345 &$add_error('type', "unknown rule type '$type'");
1349 if ($rule->{iface
}) {
1350 &$add_error('type', "parameter -i not allowed for this rule type")
1352 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1353 &$add_error('iface', $@) if $@;
1354 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1355 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1356 if $rule->{iface
} !~ m/^net(\d+)$/;
1360 if ($rule->{macro}) {
1361 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1362 $rule->{macro} = $preferred_name;
1364 &$add_error('macro', "unknown macro '$rule->{macro}'");
1368 if ($rule->{proto
}) {
1369 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1370 &$add_error('proto', $@) if $@;
1371 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1372 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1375 if ($rule->{dport
}) {
1376 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1377 &$add_error('dport', $@) if $@;
1378 &$add_error('proto', "missing property - 'dport' requires this property")
1382 if ($rule->{sport
}) {
1383 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1384 &$add_error('sport', $@) if $@;
1385 &$add_error('proto', "missing property - 'sport' requires this property")
1389 if ($rule->{source
}) {
1391 my $source_ipversion = parse_address_list
($rule->{source
});
1392 &$set_ip_version($source_ipversion);
1394 &$add_error('source', $@) if $@;
1395 &$check_ipset_or_alias_property('source', $ipversion);
1398 if ($rule->{dest
}) {
1400 my $dest_ipversion = parse_address_list
($rule->{dest
});
1401 &$set_ip_version($dest_ipversion);
1403 &$add_error('dest', $@) if $@;
1404 &$check_ipset_or_alias_property('dest', $ipversion);
1407 $rule->{ipversion
} = $ipversion if $ipversion;
1409 if ($rule->{macro} && !$error_count) {
1410 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1412 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1413 my $eh = $err->{errors
};
1414 foreach my $p (keys %$eh) {
1415 &$add_error($p, $eh->{$p});
1418 &$add_error('macro', "$err");
1423 $rule->{errors
} = $errors if $error_count;
1428 sub copy_rule_data
{
1429 my ($rule, $param) = @_;
1431 foreach my $k (keys %$rule_properties) {
1432 if (defined(my $v = $param->{$k})) {
1433 if ($v eq '' || $v eq '-') {
1444 sub rules_modify_permissions
{
1445 my ($rule_env) = @_;
1447 if ($rule_env eq 'host') {
1449 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1451 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1453 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1455 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1457 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1464 sub rules_audit_permissions
{
1465 my ($rule_env) = @_;
1467 if ($rule_env eq 'host') {
1469 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1471 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1473 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1475 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1477 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1485 my $bridge_firewall_enabled = 0;
1487 sub enable_bridge_firewall
{
1489 return if $bridge_firewall_enabled; # only once
1491 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1492 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1494 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1495 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1497 $bridge_firewall_enabled = 1;
1500 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1502 sub iptables_restore_cmdlist
{
1505 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1508 sub ip6tables_restore_cmdlist
{
1511 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1514 sub ipset_restore_cmdlist
{
1517 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1520 sub iptables_get_chains
{
1521 my ($iptablescmd) = @_;
1523 $iptablescmd = "iptables" if !$iptablescmd;
1527 # check what chains we want to track
1528 my $is_pvefw_chain = sub {
1531 return 1 if $name =~ m/^PVEFW-\S+$/;
1533 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1535 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1537 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1538 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1550 return if $line =~ m/^#/;
1551 return if $line =~ m/^\s*$/;
1553 if ($line =~ m/^\*(\S+)$/) {
1558 return if $table ne 'filter';
1560 if ($line =~ m/^:(\S+)\s/) {
1562 return if !&$is_pvefw_chain($chain);
1563 $res->{$chain} = "unknown";
1564 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1565 my ($chain, $sig) = ($1, $2);
1566 return if !&$is_pvefw_chain($chain);
1567 $res->{$chain} = $sig;
1568 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1571 # simply ignore the rest
1576 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1578 return wantarray ?
($res, $hooks) : $res;
1581 sub iptables_chain_digest
{
1583 my $digest = Digest
::SHA-
>new('sha1');
1584 foreach my $rule (@$rules) { # order is important
1585 $digest->add($rule);
1587 return $digest->b64digest;
1590 sub ipset_chain_digest
{
1593 my $digest = Digest
::SHA-
>new('sha1');
1594 foreach my $rule (sort @$rules) { # note: sorted
1595 $digest->add($rule);
1597 return $digest->b64digest;
1600 sub ipset_get_chains
{
1608 return if $line =~ m/^#/;
1609 return if $line =~ m/^\s*$/;
1610 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1612 $line =~ s/\s+$//; # delete trailing white space
1613 push @{$chains->{$chain}}, $line;
1615 # simply ignore the rest
1620 run_command
("/sbin/ipset save", outfunc
=> $parser);
1622 # compute digest for each chain
1623 foreach my $chain (keys %$chains) {
1624 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1630 sub ruleset_generate_cmdstr
{
1631 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1633 return if defined($rule->{enable
}) && !$rule->{enable
};
1634 return if $rule->{errors
};
1636 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1638 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1639 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1643 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1644 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1646 my $source = $rule->{source
};
1647 my $dest = $rule->{dest
};
1650 if ($source =~ m/^\+/) {
1651 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1653 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1654 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1655 push @cmd, "-m set --match-set ${ipset_chain} src";
1656 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1657 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1658 push @cmd, "-m set --match-set ${ipset_chain} src";
1660 die "no such ipset '$name'\n";
1663 die "invalid security group name '$source'\n";
1665 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1666 my $alias = lc($source);
1667 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1668 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1669 die "no such alias '$source'\n" if !$e;
1670 push @cmd, "-s $e->{cidr}";
1671 } elsif ($source =~ m/\-/){
1672 push @cmd, "-m iprange --src-range $source";
1674 push @cmd, "-s $source";
1679 if ($dest =~ m/^\+/) {
1680 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1682 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1683 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1684 push @cmd, "-m set --match-set ${ipset_chain} dst";
1685 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1686 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1687 push @cmd, "-m set --match-set ${ipset_chain} dst";
1689 die "no such ipset '$name'\n";
1692 die "invalid security group name '$dest'\n";
1694 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1695 my $alias = lc($dest);
1696 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1697 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1698 die "no such alias '$dest'\n" if !$e;
1699 push @cmd, "-d $e->{cidr}";
1700 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1701 push @cmd, "-m iprange --dst-range $dest";
1703 push @cmd, "-d $dest";
1707 if ($rule->{proto
}) {
1708 push @cmd, "-p $rule->{proto}";
1711 $multiport++ if $nbdport > 1;
1712 $multiport++ if $nbsport > 1;
1714 push @cmd, "--match multiport" if $multiport;
1716 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1717 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1719 if ($rule->{dport
}) {
1720 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1721 # Note: we use dport to store --icmp-type
1722 die "unknown icmp-type '$rule->{dport}'\n"
1723 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1724 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1725 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1726 # Note: we use dport to store --icmpv6-type
1727 die "unknown icmpv6-type '$rule->{dport}'\n"
1728 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1729 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1732 if ($multiport == 2) {
1733 push @cmd, "--ports $rule->{dport}";
1735 push @cmd, "--dports $rule->{dport}";
1738 push @cmd, "--dport $rule->{dport}";
1743 if ($rule->{sport
}) {
1745 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1747 push @cmd, "--sport $rule->{sport}";
1750 } elsif ($rule->{dport
} || $rule->{sport
}) {
1751 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1752 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1755 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1757 if (my $action = $rule->{action
}) {
1758 $action = $actions->{$action} if defined($actions->{$action});
1759 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1760 push @cmd, $goto ?
"-g $action" : "-j $action";
1763 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1766 sub ruleset_generate_rule
{
1767 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1771 if ($rule->{macro}) {
1772 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1777 # update all or nothing
1780 foreach my $tmp (@$rules) {
1781 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1782 push @cmds, $cmdstr;
1786 foreach my $cmdstr (@cmds) {
1787 ruleset_addrule
($ruleset, $chain, $cmdstr);
1791 sub ruleset_generate_rule_insert
{
1792 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1794 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1796 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1797 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1801 sub ruleset_create_chain
{
1802 my ($ruleset, $chain) = @_;
1804 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1805 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1807 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1809 $ruleset->{$chain} = [];
1812 sub ruleset_chain_exist
{
1813 my ($ruleset, $chain) = @_;
1815 return $ruleset->{$chain} ?
1 : undef;
1818 sub ruleset_addrule
{
1819 my ($ruleset, $chain, $rule) = @_;
1821 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1823 push @{$ruleset->{$chain}}, "-A $chain $rule";
1826 sub ruleset_insertrule
{
1827 my ($ruleset, $chain, $rule) = @_;
1829 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1831 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1834 sub get_log_rule_base
{
1835 my ($chain, $vmid, $msg, $loglevel) = @_;
1837 die "internal error - no log level" if !defined($loglevel);
1839 $vmid = 0 if !defined($vmid);
1841 # Note: we use special format for prefix to pass further
1842 # info to log daemon (VMID, LOGVELEL and CHAIN)
1844 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1847 sub ruleset_addlog {
1848 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1850 return if !defined($loglevel);
1852 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1854 $logrule = "$rule $logrule" if defined($rule);
1856 ruleset_addrule($ruleset, $chain, $logrule);
1859 sub ruleset_add_chain_policy {
1860 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1862 if ($policy eq 'ACCEPT') {
1864 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
1865 { ACCEPT => $accept_action});
1867 } elsif ($policy eq 'DROP') {
1869 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1871 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1873 ruleset_addrule($ruleset, $chain, "-j DROP
");
1874 } elsif ($policy eq 'REJECT') {
1875 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1877 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1879 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1882 die "internal error
: unknown policy
'$policy'";
1886 sub ruleset_chain_add_ndp {
1887 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
1888 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
1890 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
$accept");
1891 if ($direction ne 'OUT' || $options->{radv}) {
1892 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
$accept");
1894 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
$accept");
1895 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
$accept");
1898 sub ruleset_chain_add_conn_filters {
1899 my ($ruleset, $chain, $accept) = @_;
1901 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1902 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1905 sub ruleset_chain_add_input_filters {
1906 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
1908 if ($cluster_conf->{ipset}->{blacklist}){
1909 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1910 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1911 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1912 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1914 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
1915 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1918 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1919 if ($ipversion == 4) {
1920 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1924 if ($options->{tcpflags}) {
1925 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1929 sub ruleset_create_vm_chain {
1930 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1932 ruleset_create_chain($ruleset, $chain);
1933 my $accept = generate_nfqueue($options);
1935 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1936 if ($ipversion == 4) {
1937 if ($direction eq 'OUT') {
1938 ruleset_generate_rule($ruleset, $chain, $ipversion,
1939 { action => 'PVEFW-SET-ACCEPT-MARK',
1940 proto => 'udp', sport => 68, dport => 67 });
1942 ruleset_generate_rule($ruleset, $chain, $ipversion,
1943 { action => 'ACCEPT',
1944 proto => 'udp', sport => 67, dport => 68 });
1946 } elsif ($ipversion == 6) {
1947 if ($direction eq 'OUT') {
1948 ruleset_generate_rule($ruleset, $chain, $ipversion,
1949 { action => 'PVEFW-SET-ACCEPT-MARK',
1950 proto => 'udp', sport => 546, dport => 547 });
1952 ruleset_generate_rule($ruleset, $chain, $ipversion,
1953 { action => 'ACCEPT',
1954 proto => 'udp', sport => 547, dport => 546 });
1960 if ($direction eq 'OUT') {
1961 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1962 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1964 if ($ipversion == 6 && !$options->{radv}) {
1965 ruleset_addrule($ruleset, $chain, '-p icmpv6 --icmpv6-type router-advertisement -j DROP');
1967 if ($ipfilter_ipset) {
1968 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
1970 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1973 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
1974 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
1977 sub ruleset_add_group_rule {
1978 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1980 my $group = $rule->{action};
1981 my $group_chain = "GROUP-
$group-$direction";
1982 if(!ruleset_chain_exist($ruleset, $group_chain)){
1983 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1986 if ($direction eq 'OUT' && $rule->{iface_out}) {
1987 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1988 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1989 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1991 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1994 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1997 sub ruleset_generate_vm_rules {
1998 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2000 my $lc_direction = lc($direction);
2002 my $in_accept = generate_nfqueue($options);
2004 foreach my $rule (@$rules) {
2005 next if $rule->{iface} && $rule->{iface} ne $netid;
2006 next if !$rule->{enable} || $rule->{errors};
2007 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2009 if ($rule->{type} eq 'group') {
2010 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2011 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2013 next if $rule->{type} ne $lc_direction;
2015 if ($direction eq 'OUT') {
2016 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2017 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2018 undef, $cluster_conf, $vmfw_conf);
2020 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2021 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2022 undef, $cluster_conf, $vmfw_conf);
2030 sub generate_nfqueue {
2033 if ($options->{ips}) {
2034 my $action = "NFQUEUE
";
2035 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2036 if (defined($3) && defined($1)) {
2037 $action .= " --queue-balance
$1:$3";
2038 } elsif (defined($1)) {
2039 $action .= " --queue-num
$1";
2042 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2049 sub ruleset_generate_vm_ipsrules {
2050 my ($ruleset, $options, $direction, $iface) = @_;
2052 if ($options->{ips} && $direction eq 'IN') {
2053 my $nfqueue = generate_nfqueue($options);
2055 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2056 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2059 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
2063 sub generate_tap_rules_direction {
2064 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2066 my $lc_direction = lc($direction);
2068 my $rules = $vmfw_conf->{rules};
2070 my $options = $vmfw_conf->{options};
2071 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2073 my $tapchain = "$iface-$direction";
2075 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2076 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2077 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2079 # create chain with mac and ip filter
2080 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2082 if ($options->{enable}) {
2083 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2085 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2090 if ($direction eq 'OUT') {
2091 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2093 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2096 my $accept = generate_nfqueue($options);
2097 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2098 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2100 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2101 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2104 # plug the tap chain to bridge chain
2105 if ($direction eq 'IN') {
2106 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2107 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2109 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2110 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2114 sub enable_host_firewall {
2115 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2117 my $options = $hostfw_conf->{options};
2118 my $cluster_options = $cluster_conf->{options};
2119 my $rules = $hostfw_conf->{rules};
2120 my $cluster_rules = $cluster_conf->{rules};
2122 # host inbound firewall
2123 my $chain = "PVEFW-HOST-IN
";
2124 ruleset_create_chain($ruleset, $chain);
2126 my $loglevel = get_option_log_level($options, "log_level_in
");
2128 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2130 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2131 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2132 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2134 # we use RETURN because we need to check also tap rules
2135 my $accept_action = 'RETURN';
2137 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2139 # add host rules first, so that cluster wide rules can be overwritten
2140 foreach my $rule (@$rules, @$cluster_rules) {
2141 next if !$rule->{enable} || $rule->{errors};
2142 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2144 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2147 if ($rule->{type} eq 'group') {
2148 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2149 } elsif ($rule->{type} eq 'in') {
2150 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2151 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2152 undef, $cluster_conf, $hostfw_conf);
2156 delete $rule->{iface_in};
2159 # allow standard traffic for management ipset (includes cluster network)
2160 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2161 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2162 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2163 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2164 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2165 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2167 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2168 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2171 if ($localnet && ($ipversion == $localnet_ver)) {
2172 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2173 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2174 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2177 # implement input policy
2178 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2179 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2181 # host outbound firewall
2182 $chain = "PVEFW-HOST-OUT
";
2183 ruleset_create_chain($ruleset, $chain);
2185 $loglevel = get_option_log_level($options, "log_level_out
");
2187 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2189 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2191 # we use RETURN because we may want to check other thigs later
2192 $accept_action = 'RETURN';
2193 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2195 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2197 # add host rules first, so that cluster wide rules can be overwritten
2198 foreach my $rule (@$rules, @$cluster_rules) {
2199 next if !$rule->{enable} || $rule->{errors};
2200 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2202 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2204 if ($rule->{type} eq 'group') {
2205 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2206 } elsif ($rule->{type} eq 'out') {
2207 ruleset_generate_rule($ruleset, $chain, $ipversion,
2208 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2209 undef, $cluster_conf, $hostfw_conf);
2213 delete $rule->{iface_out};
2216 # allow standard traffic on cluster network
2217 if ($localnet && ($ipversion == $localnet_ver)) {
2218 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2219 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2220 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2221 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2223 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2224 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2225 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2228 # implement output policy
2229 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2230 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2232 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2233 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2236 sub generate_group_rules {
2237 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2239 my $rules = $cluster_conf->{groups}->{$group};
2242 warn "no such security group
'$group'\n";
2243 $rules = []; # create empty chain
2246 my $chain = "GROUP-
${group
}-IN
";
2248 ruleset_create_chain($ruleset, $chain);
2249 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2251 foreach my $rule (@$rules) {
2252 next if $rule->{type} ne 'in';
2253 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2254 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2255 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2256 undef, $cluster_conf);
2259 $chain = "GROUP-
${group
}-OUT
";
2261 ruleset_create_chain($ruleset, $chain);
2262 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2264 foreach my $rule (@$rules) {
2265 next if $rule->{type} ne 'out';
2266 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2267 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2268 # check also other tap rules later
2269 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2270 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2271 undef, $cluster_conf);
2276 my $valid_netdev_names = {};
2277 for (my $i = 0; $i < $MAX_NETS; $i++) {
2278 $valid_netdev_names->{"net
$i"} = 1;
2282 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2284 my $orig_line = $line;
2288 # we can add single line comments to the end of the rule
2289 if ($line =~ s/#\s*(.*?)\s*$//) {
2290 $rule->{comment} = decode('utf8', $1);
2293 # we can disable a rule when prefixed with '|'
2295 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2297 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2298 die "unable to parse rule
: $line\n";
2300 $rule->{type} = lc($1);
2301 $rule->{action} = $2;
2303 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2304 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2305 $rule->{macro} = $1;
2306 $rule->{action} = $2;
2310 while (length($line)) {
2311 if ($line =~ s/^-i (\S+)\s*//) {
2312 $rule->{iface} = $1;
2316 last if $rule->{type} eq 'group';
2318 if ($line =~ s/^-p (\S+)\s*//) {
2319 $rule->{proto} = $1;
2323 if ($line =~ s/^-dport (\S+)\s*//) {
2324 $rule->{dport} = $1;
2328 if ($line =~ s/^-sport (\S+)\s*//) {
2329 $rule->{sport} = $1;
2332 if ($line =~ s/^-source (\S+)\s*//) {
2333 $rule->{source} = $1;
2336 if ($line =~ s/^-dest (\S+)\s*//) {
2344 die "unable to parse rule parameters
: $line\n" if length($line);
2346 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2347 if ($verbose && $rule->{errors}) {
2348 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2349 foreach my $p (keys %{$rule->{errors}}) {
2350 warn " $p: $rule->{errors
}->{$p}\n";
2357 sub parse_vmfw_option {
2362 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2364 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2367 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2369 $value = $2 ? lc($3) : '';
2370 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2373 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2377 die "can
't parse option '$line'\n"
2380 return ($opt, $value);
2383 sub parse_hostfw_option {
2388 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2390 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2393 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2395 $value = $2 ? lc($3) : '';
2396 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2400 die "can't parse option
'$line'\n"
2403 return ($opt, $value);
2406 sub parse_clusterfw_option {
2411 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2414 if (($value > 1) && ((time() - $value) > 60)) {
2417 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2421 die "can
't parse option '$line'\n"
2424 return ($opt, $value);
2428 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2430 my $alias = lc($cidr);
2431 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2432 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2434 die "no such alias '$cidr'\n" if !$e;;
2436 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2439 sub parse_ip_or_cidr {
2444 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2447 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2451 die "value does not look like a valid IP address or CIDR network\n";
2454 return wantarray ? ($cidr, $ipversion) : $cidr;
2460 # we can add single line comments to the end of the line
2461 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2463 if ($line =~ m/^(\S+)\s(\S+)$/) {
2464 my ($name, $cidr) = ($1, $2);
2467 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2472 ipversion => $ipversion,
2474 $data->{comment} = $comment if $comment;
2481 sub generic_fw_config_parser {
2482 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2487 my $res = $empty_conf;
2489 while (defined(my $line = <$fh>)) {
2490 next if $line =~ m/^#/;
2491 next if $line =~ m/^\s*$/;
2495 my $linenr = $fh->input_line_number();
2496 my $prefix = "$filename (line $linenr)";
2498 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2499 $section = 'options
';
2503 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2504 $section = 'aliases
';
2508 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2509 $section = 'groups
';
2513 die "security group name too long\n" if length($group) > $max_group_name_length;
2514 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2517 ($section, $group, $comment) = undef;
2518 warn "$prefix: $err";
2522 $res->{$section}->{$group} = [];
2523 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2528 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2533 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2538 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2539 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2542 ($section, $group, $comment) = undef;
2543 warn "$prefix: $err";
2547 $res->{$section}->{$group} = [];
2548 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2554 warn "$prefix: skip line - no section\n";
2558 if ($section eq 'options
') {
2561 if ($rule_env eq 'cluster
') {
2562 ($opt, $value) = parse_clusterfw_option($line);
2563 } elsif ($rule_env eq 'host
') {
2564 ($opt, $value) = parse_hostfw_option($line);
2566 ($opt, $value) = parse_vmfw_option($line);
2568 $res->{options}->{$opt} = $value;
2570 warn "$prefix: $@" if $@;
2571 } elsif ($section eq 'aliases
') {
2573 my $data = parse_alias($line);
2574 $res->{aliases}->{lc($data->{name})} = $data;
2576 warn "$prefix: $@" if $@;
2577 } elsif ($section eq 'rules
') {
2579 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2581 warn "$prefix: $err";
2584 push @{$res->{$section}}, $rule;
2585 } elsif ($section eq 'groups
') {
2587 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2589 warn "$prefix: $err";
2592 push @{$res->{$section}->{$group}}, $rule;
2593 } elsif ($section eq 'ipset
') {
2594 # we can add single line comments to the end of the rule
2595 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2597 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2602 if ($nomatch && !$feature_ipset_nomatch) {
2603 $errors->{nomatch} = "nomatch not supported by kernel";
2607 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2608 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2610 $cidr = parse_ip_or_cidr($cidr);
2615 $errors->{cidr} = $err;
2618 my $entry = { cidr => $cidr };
2619 $entry->{nomatch} = 1 if $nomatch;
2620 $entry->{comment} = $comment if $comment;
2621 $entry->{errors} = $errors if $errors;
2623 if ($verbose && $errors) {
2624 warn "$prefix - errors in ipset '$group': $line\n";
2625 foreach my $p (keys %{$errors}) {
2626 warn " $p: $errors->{$p}\n";
2630 push @{$res->{$section}->{$group}}, $entry;
2632 warn "$prefix: skip line - unknown section\n";
2640 sub parse_hostfw_config {
2641 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2643 my $empty_conf = { rules => [], options => {}};
2645 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2648 sub parse_vmfw_config {
2649 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2656 ipset_comments => {},
2659 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2662 sub parse_clusterfw_config {
2663 my ($filename, $fh, $verbose) = @_;
2673 group_comments => {},
2675 ipset_comments => {},
2678 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2682 my ($code, @param) = @_;
2686 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2693 sub read_local_vm_config {
2698 my $vmdata = { qemu => $qemu, lxc => $lxc };
2700 my $vmlist = PVE::Cluster::get_vmlist();
2701 return $vmdata if !$vmlist || !$vmlist->{ids};
2702 my $ids = $vmlist->{ids};
2704 foreach my $vmid (keys %$ids) {
2705 next if !$vmid; # skip VE0
2706 my $d = $ids->{$vmid};
2707 next if !$d->{node} || $d->{node} ne $nodename;
2708 next if !$d->{type};
2709 if ($d->{type} eq 'qemu
') {
2710 if ($have_qemu_server) {
2711 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2712 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2713 $qemu->{$vmid} = $conf;
2716 } elsif ($d->{type} eq 'lxc
') {
2718 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2719 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2720 $lxc->{$vmid} = $conf;
2729 sub load_vmfw_conf {
2730 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2734 $dir = $pvefw_conf_dir if !defined($dir);
2736 my $filename = "$dir/$vmid.fw";
2737 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2738 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2739 $vmfw_conf->{vmid} = $vmid;
2745 my $format_rules = sub {
2746 my ($rules, $allow_iface) = @_;
2750 foreach my $rule (@$rules) {
2751 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2752 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2753 $raw .= uc($rule->{type});
2754 if ($rule->{macro}) {
2755 $raw .= " $rule->{macro}($rule->{action})";
2757 $raw .= " " . $rule->{action};
2759 if ($allow_iface && $rule->{iface}) {
2760 $raw .= " -i $rule->{iface}";
2763 if ($rule->{type} ne 'group
') {
2764 $raw .= " -source $rule->{source}" if $rule->{source};
2765 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2766 $raw .= " -p $rule->{proto}" if $rule->{proto};
2767 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2768 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2771 $raw .= " # " . encode('utf8
', $rule->{comment})
2772 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2775 die "unknown rule type '$rule->{type
}'";
2782 my $format_options = sub {
2787 $raw .= "[OPTIONS]\n\n";
2788 foreach my $opt (keys %$options) {
2789 $raw .= "$opt: $options->{$opt}\n";
2796 my $format_aliases = sub {
2801 $raw .= "[ALIASES]\n\n";
2802 foreach my $k (keys %$aliases) {
2803 my $e = $aliases->{$k};
2804 $raw .= "$e->{name} $e->{cidr}";
2805 $raw .= " # " . encode('utf8
', $e->{comment})
2806 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2814 my $format_ipsets = sub {
2819 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2820 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2821 my $utf8comment = encode('utf8
', $comment);
2822 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2824 $raw .= "[IPSET $ipset]\n\n";
2826 my $options = $fw_conf->{ipset}->{$ipset};
2829 foreach my $entry (@$options) {
2830 $nethash->{$entry->{cidr}} = $entry;
2833 foreach my $cidr (sort keys %$nethash) {
2834 my $entry = $nethash->{$cidr};
2835 my $line = $entry->{nomatch} ? '!' : '';
2836 $line .= $entry->{cidr};
2837 $line .= " # " . encode('utf8
', $entry->{comment})
2838 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2848 sub save_vmfw_conf {
2849 my ($vmid, $vmfw_conf) = @_;
2853 my $options = $vmfw_conf->{options};
2854 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2856 my $aliases = $vmfw_conf->{aliases};
2857 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2859 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2861 my $rules = $vmfw_conf->{rules} || [];
2862 if ($rules && scalar(@$rules)) {
2863 $raw .= "[RULES]\n\n";
2864 $raw .= &$format_rules($rules, 1);
2868 my $filename = "$pvefw_conf_dir/$vmid.fw";
2870 mkdir $pvefw_conf_dir;
2871 PVE::Tools::file_set_contents($filename, $raw);
2877 sub remove_vmfw_conf {
2880 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
2882 unlink $vmfw_conffile;
2885 sub clone_vmfw_conf {
2886 my ($vmid, $newid) = @_;
2888 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
2889 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
2891 if (-f $clonevm_conffile) {
2892 unlink $clonevm_conffile;
2894 if (-f $sourcevm_conffile) {
2895 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
2896 PVE::Tools::file_set_contents($clonevm_conffile, $data);
2900 sub read_vm_firewall_configs {
2901 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2903 my $vmfw_configs = {};
2905 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2906 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2907 next if !$vmfw_conf->{options}; # skip if file does not exists
2908 $vmfw_configs->{$vmid} = $vmfw_conf;
2910 foreach my $vmid (keys %{$vmdata->{lxc}}) {
2911 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2912 next if !$vmfw_conf->{options}; # skip if file does not exists
2913 $vmfw_configs->{$vmid} = $vmfw_conf;
2916 return $vmfw_configs;
2919 sub get_option_log_level {
2920 my ($options, $k) = @_;
2922 my $v = $options->{$k};
2923 $v = $default_log_level if !defined($v);
2925 return undef if $v eq '' || $v eq 'nolog
';
2927 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2929 return $v if ($v >= 0) && ($v <= 7);
2931 warn "unknown log level ($k = '$v')\n";
2936 sub generate_std_chains {
2937 my ($ruleset, $options, $ipversion) = @_;
2939 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2941 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2945 if ($ipversion == 4) {
2946 # same as shorewall smurflog.
2947 $chain = 'PVEFW-smurflog
';
2948 $std_chains->{$chain} = [];
2950 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2951 push @{$std_chains->{$chain}}, "-j DROP";
2954 # same as shorewall logflags action.
2955 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2956 $chain = 'PVEFW-logflags
';
2957 $std_chains->{$chain} = [];
2959 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2960 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2961 push @{$std_chains->{$chain}}, "-j DROP";
2963 foreach my $chain (keys %$std_chains) {
2964 ruleset_create_chain($ruleset, $chain);
2965 foreach my $rule (@{$std_chains->{$chain}}) {
2967 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
2969 ruleset_addrule($ruleset, $chain, $rule);
2975 sub generate_ipset_chains {
2976 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
2978 foreach my $ipset (keys %{$ipsets}) {
2980 my $options = $ipsets->{$ipset};
2982 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
2983 if (my $ips = $device_ips->{$1}) {
2984 $options = [@$options, @$ips];
2990 foreach my $entry (@$options) {
2991 next if $entry->{errors}; # skip entries with errors
2994 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2995 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2997 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
2999 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3001 # ip_compress_address takes an address only, no CIDR
3002 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3003 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3004 $cidr .= $prefix_len if defined($prefix_len);
3010 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3015 foreach my $ipversion (4, 6) {
3016 my $data = $nethash->{$ipversion};
3018 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3020 my $hashsize = scalar(@$options);
3021 if ($hashsize <= 64) {
3024 $hashsize = round_powerof2($hashsize);
3027 my $family = $ipversion == "6" ? "inet6" : "inet";
3029 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3031 foreach my $cidr (sort keys %$data) {
3032 my $entry = $data->{$cidr};
3034 my $cmd = "add $name $cidr";
3035 if ($entry->{nomatch}) {
3036 if ($feature_ipset_nomatch) {
3037 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3039 warn "ignore !$cidr - nomatch not supported by kernel\n";
3042 push @{$ipset_ruleset->{$name}}, $cmd;
3049 sub round_powerof2 {
3053 $int |= $int >> $_ foreach (1,2,4,8,16);
3057 sub load_clusterfw_conf {
3058 my ($filename, $verbose) = @_;
3060 $filename = $clusterfw_conf_filename if !defined($filename);
3062 my $cluster_conf = {};
3063 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3064 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3067 return $cluster_conf;
3070 sub save_clusterfw_conf {
3071 my ($cluster_conf) = @_;
3075 my $options = $cluster_conf->{options};
3076 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3078 my $aliases = $cluster_conf->{aliases};
3079 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3081 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3083 my $rules = $cluster_conf->{rules};
3084 if ($rules && scalar(@$rules)) {
3085 $raw .= "[RULES]\n\n";
3086 $raw .= &$format_rules($rules, 1);
3090 if ($cluster_conf->{groups}) {
3091 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3092 my $rules = $cluster_conf->{groups}->{$group};
3093 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3094 my $utf8comment = encode('utf8
', $comment);
3095 $raw .= "[group $group] # $utf8comment\n\n";
3097 $raw .= "[group $group]\n\n";
3100 $raw .= &$format_rules($rules, 0);
3106 mkdir $pvefw_conf_dir;
3107 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3109 unlink $clusterfw_conf_filename;
3113 sub load_hostfw_conf {
3114 my ($cluster_conf, $filename, $verbose) = @_;
3116 $filename = $hostfw_conf_filename if !defined($filename);
3118 my $hostfw_conf = {};
3119 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3120 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3122 return $hostfw_conf;
3125 sub save_hostfw_conf {
3126 my ($hostfw_conf) = @_;
3130 my $options = $hostfw_conf->{options};
3131 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3133 my $rules = $hostfw_conf->{rules};
3134 if ($rules && scalar(@$rules)) {
3135 $raw .= "[RULES]\n\n";
3136 $raw .= &$format_rules($rules, 1);
3141 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3143 unlink $hostfw_conf_filename;
3148 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3152 if ($vmdata) { # test mode
3153 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3154 my $filename = "$testdir/cluster.fw";
3155 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3157 $filename = "$testdir/host.fw";
3158 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3160 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3161 } else { # normal operation
3162 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3164 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3166 $vmdata = read_local_vm_config();
3167 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3170 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3173 if ($cluster_conf->{aliases}->{local_network}) {
3174 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3177 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3179 $cluster_conf->{aliases}->{local_network} = {
3180 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3183 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3185 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3186 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3187 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3189 return ($ruleset, $ipset_ruleset, $rulesetv6);
3192 sub compile_iptables_filter {
3193 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3197 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3198 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3200 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3202 my $hostfw_options = $hostfw_conf->{options} || {};
3204 # fixme: what log level should we use here?
3205 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3207 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3209 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3210 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3212 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3214 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3215 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3217 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3219 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3221 if ($hostfw_enable) {
3222 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3223 warn $@ if $@; # just to be sure - should not happen
3226 # generate firewall rules for QEMU VMs
3227 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3229 my $conf = $vmdata->{qemu}->{$vmid};
3230 my $vmfw_conf = $vmfw_configs->{$vmid};
3231 return if !$vmfw_conf;
3233 foreach my $netid (keys %$conf) {
3234 next if $netid !~ m/^net(\d+)$/;
3235 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3236 next if !$net->{firewall};
3237 my $iface = "tap${vmid}i$1";
3239 my $macaddr = $net->{macaddr};
3240 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3241 $vmfw_conf, $vmid, 'IN
', $ipversion);
3242 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3243 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3246 warn $@ if $@; # just to be sure - should not happen
3249 # generate firewall rules for LXC containers
3250 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3252 my $conf = $vmdata->{lxc}->{$vmid};
3253 my $vmfw_conf = $vmfw_configs->{$vmid};
3254 return if !$vmfw_conf;
3256 if ($vmfw_conf->{options}->{enable}) {
3257 foreach my $netid (keys %$conf) {
3258 next if $netid !~ m/^net(\d+)$/;
3259 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3260 next if !$net->{firewall};
3261 my $iface = "veth${vmid}i$1";
3262 my $macaddr = $net->{hwaddr};
3263 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3264 $vmfw_conf, $vmid, 'IN
', $ipversion);
3265 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3266 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3270 warn $@ if $@; # just to be sure - should not happen
3273 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3274 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3280 sub mac_to_linklocal {
3282 my @parts = split(/:/, $macaddr);
3283 # The standard link local address uses the fe80::/64 prefix with the
3284 # modified EUI-64 identifier derived from the MAC address by flipping the
3285 # universal/local bit and inserting FF:FE in the middle.
3287 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3288 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3289 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3292 sub compile_ipsets {
3293 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3296 if ($cluster_conf->{aliases}->{local_network}) {
3297 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3300 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3302 $cluster_conf->{aliases}->{local_network} = {
3303 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3306 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3309 my $ipset_ruleset = {};
3311 # generate ipsets for QEMU VMs
3312 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3314 my $conf = $vmdata->{qemu}->{$vmid};
3315 my $vmfw_conf = $vmfw_configs->{$vmid};
3316 return if !$vmfw_conf;
3318 # When the 'ipfilter
' option is enabled every device for which there
3319 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3321 # The reason is that ipfilter ipsets are always filled with standard
3322 # IPv6 link-local filters.
3323 my $ipsets = $vmfw_conf->{ipset};
3324 my $implicit_sets = {};
3326 my $device_ips = {};
3327 foreach my $netid (keys %$conf) {
3328 next if $netid !~ m/^net(\d+)$/;
3329 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3330 next if !$net->{firewall};
3332 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3333 $implicit_sets->{"ipfilter-$netid"} = [];
3336 my $macaddr = $net->{macaddr};
3337 my $linklocal = mac_to_linklocal($macaddr);
3338 $device_ips->{$netid} = [
3339 { cidr => $linklocal },
3340 { cidr => 'fe80
::/10', nomatch => 1 }
3344 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3345 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3347 warn $@ if $@; # just to be sure - should not happen
3350 # generate firewall rules for LXC containers
3351 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3353 my $conf = $vmdata->{lxc}->{$vmid};
3354 my $vmfw_conf = $vmfw_configs->{$vmid};
3355 return if !$vmfw_conf;
3357 # When the 'ipfilter
' option is enabled every device for which there
3358 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3360 # The reason is that ipfilter ipsets are always filled with standard
3361 # IPv6 link-local filters, as well as the IP addresses configured
3362 # for the container.
3363 my $ipsets = $vmfw_conf->{ipset};
3364 my $implicit_sets = {};
3366 my $device_ips = {};
3367 foreach my $netid (keys %$conf) {
3368 next if $netid !~ m/^net(\d+)$/;
3369 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3370 next if !$net->{firewall};
3372 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3373 $implicit_sets->{"ipfilter-$netid"} = [];
3376 my $macaddr = $net->{hwaddr};
3377 my $linklocal = mac_to_linklocal($macaddr);
3378 my $set = $device_ips->{$netid} = [
3379 { cidr => $linklocal },
3380 { cidr => 'fe80
::/10', nomatch => 1 }
3382 if ($net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3383 push @$set, { cidr => $1 };
3385 if ($net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3386 push @$set, { cidr => $1 };
3390 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3391 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3393 warn $@ if $@; # just to be sure - should not happen
3396 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3398 return $ipset_ruleset;
3401 sub get_ruleset_status {
3402 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3404 my $statushash = {};
3406 foreach my $chain (sort keys %$ruleset) {
3407 my $sig = &$digest_fn($ruleset->{$chain});
3409 $statushash->{$chain}->{sig} = $sig;
3411 my $oldsig = $active_chains->{$chain};
3412 if (!defined($oldsig)) {
3413 $statushash->{$chain}->{action} = 'create
';
3415 if ($oldsig eq $sig) {
3416 $statushash->{$chain}->{action} = 'exists';
3418 $statushash->{$chain}->{action} = 'update
';
3421 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3422 foreach my $cmd (@{$ruleset->{$chain}}) {
3423 print "\t$cmd\n" if $verbose;
3427 foreach my $chain (sort keys %$active_chains) {
3428 if (!defined($ruleset->{$chain})) {
3429 my $sig = $active_chains->{$chain};
3430 $statushash->{$chain}->{action} = 'delete';
3431 $statushash->{$chain}->{sig} = $sig;
3432 print "delete $chain ($sig)\n" if $verbose;
3439 sub print_sig_rule {
3440 my ($chain, $sig) = @_;
3442 # We just use this to store a SHA1 checksum used to detect changes
3443 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3446 sub get_ruleset_cmdlist {
3447 my ($ruleset, $verbose, $iptablescmd) = @_;
3449 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3451 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3452 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3454 # create missing chains first
3455 foreach my $chain (sort keys %$ruleset) {
3456 my $stat = $statushash->{$chain};
3457 die "internal error" if !$stat;
3458 next if $stat->{action} ne 'create
';
3460 $cmdlist .= ":$chain - [0:0]\n";
3463 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3464 my $chain = "PVEFW-$h";
3465 if ($ruleset->{$chain} && !$hooks->{$h}) {
3466 $cmdlist .= "-A $h -j $chain\n";
3470 foreach my $chain (sort keys %$ruleset) {
3471 my $stat = $statushash->{$chain};
3472 die "internal error" if !$stat;
3474 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3475 $cmdlist .= "-F $chain\n";
3476 foreach my $cmd (@{$ruleset->{$chain}}) {
3477 $cmdlist .= "$cmd\n";
3479 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3480 } elsif ($stat->{action
} eq 'delete') {
3481 die "internal error"; # this should not happen
3482 } elsif ($stat->{action
} eq 'exists') {
3485 die "internal error - unknown status '$stat->{action}'";
3489 foreach my $chain (keys %$statushash) {
3490 next if $statushash->{$chain}->{action
} ne 'delete';
3491 $cmdlist .= "-F $chain\n";
3493 foreach my $chain (keys %$statushash) {
3494 next if $statushash->{$chain}->{action
} ne 'delete';
3495 next if $chain eq 'PVEFW-INPUT';
3496 next if $chain eq 'PVEFW-OUTPUT';
3497 next if $chain eq 'PVEFW-FORWARD';
3498 $cmdlist .= "-X $chain\n";
3501 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3503 $cmdlist .= "COMMIT\n";
3505 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3508 sub get_ipset_cmdlist
{
3509 my ($ruleset, $verbose) = @_;
3513 my $delete_cmdlist = "";
3515 my $active_chains = ipset_get_chains
();
3516 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3518 # remove stale _swap chains
3519 foreach my $chain (keys %$active_chains) {
3520 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3521 $cmdlist .= "destroy $chain\n";
3525 foreach my $chain (keys %$ruleset) {
3526 my $stat = $statushash->{$chain};
3527 die "internal error" if !$stat;
3529 if ($stat->{action
} eq 'create') {
3530 foreach my $cmd (@{$ruleset->{$chain}}) {
3531 $cmdlist .= "$cmd\n";
3536 foreach my $chain (keys %$ruleset) {
3537 my $stat = $statushash->{$chain};
3538 die "internal error" if !$stat;
3540 if ($stat->{action
} eq 'update') {
3541 my $chain_swap = $chain."_swap";
3543 foreach my $cmd (@{$ruleset->{$chain}}) {
3544 $cmd =~ s/$chain/$chain_swap/;
3545 $cmdlist .= "$cmd\n";
3547 $cmdlist .= "swap $chain_swap $chain\n";
3548 $cmdlist .= "flush $chain_swap\n";
3549 $cmdlist .= "destroy $chain_swap\n";
3553 # the remove unused chains
3554 foreach my $chain (keys %$statushash) {
3555 next if $statushash->{$chain}->{action
} ne 'delete';
3557 $delete_cmdlist .= "flush $chain\n";
3558 $delete_cmdlist .= "destroy $chain\n";
3561 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3563 return ($cmdlist, $delete_cmdlist, $changes);
3567 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3569 enable_bridge_firewall
();
3571 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3572 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3574 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3575 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3578 if ($ipset_changes) {
3579 print "ipset changes:\n";
3580 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3581 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3585 print "iptables changes:\n";
3590 print "ip6tables changes:\n";
3595 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3596 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3598 ipset_restore_cmdlist
($ipset_create_cmdlist);
3600 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3601 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3603 iptables_restore_cmdlist
($cmdlist);
3605 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3606 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3608 ip6tables_restore_cmdlist
($cmdlistv6);
3610 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3611 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3613 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3615 # test: re-read status and check if everything is up to date
3616 my $active_chains = iptables_get_chains
();
3617 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3620 foreach my $chain (sort keys %$ruleset) {
3621 my $stat = $statushash->{$chain};
3622 if ($stat->{action
} ne 'exists') {
3623 warn "unable to update chain '$chain'\n";
3628 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3629 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3631 foreach my $chain (sort keys %$rulesetv6) {
3632 my $stat = $statushashv6->{$chain};
3633 if ($stat->{action
} ne 'exists') {
3634 warn "unable to update chain '$chain'\n";
3639 die "unable to apply firewall changes\n" if $errors;
3641 update_nf_conntrack_max
($hostfw_conf);
3643 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3647 sub update_nf_conntrack_max
{
3648 my ($hostfw_conf) = @_;
3650 my $max = 65536; # reasonable default
3652 my $options = $hostfw_conf->{options
} || {};
3654 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3655 $max = $options->{nf_conntrack_max
};
3656 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3659 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3660 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3662 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3664 if ($current != $max) {
3665 my $hashsize = int($max/4);
3666 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3667 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3671 sub update_nf_conntrack_tcp_timeout_established
{
3672 my ($hostfw_conf) = @_;
3674 my $options = $hostfw_conf->{options
} || {};
3676 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3678 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3681 sub remove_pvefw_chains
{
3683 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3684 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3685 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3689 sub remove_pvefw_chains_iptables
{
3690 my ($iptablescmd) = @_;
3692 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3693 my $cmdlist = "*filter\n";
3695 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3697 $cmdlist .= "-D $h -j PVEFW-$h\n";
3701 foreach my $chain (keys %$chash) {
3702 $cmdlist .= "-F $chain\n";
3705 foreach my $chain (keys %$chash) {
3706 $cmdlist .= "-X $chain\n";
3708 $cmdlist .= "COMMIT\n";
3710 if($iptablescmd eq "ip6tables") {
3711 ip6tables_restore_cmdlist
($cmdlist);
3713 iptables_restore_cmdlist
($cmdlist);
3717 sub remove_pvefw_chains_ipset
{
3719 my $ipset_chains = ipset_get_chains
();
3723 foreach my $chain (keys %$ipset_chains) {
3724 $cmdlist .= "flush $chain\n";
3725 $cmdlist .= "destroy $chain\n";
3728 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3732 my $cluster_conf = load_clusterfw_conf
();
3733 my $cluster_options = $cluster_conf->{options
};
3734 my $enable = $cluster_options->{enable
};
3738 # load required modules here
3744 my $cluster_conf = load_clusterfw_conf
();
3745 my $cluster_options = $cluster_conf->{options
};
3747 if (!$cluster_options->{enable
}) {
3748 PVE
::Firewall
::remove_pvefw_chains
();
3752 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3754 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3756 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);