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);
20 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
23 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
24 my $pvefw_conf_dir = "/etc/pve/firewall";
25 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
27 # dynamically include PVE::QemuServer and PVE::LXC
28 # to avoid dependency problems
31 require PVE
::QemuServer
;
32 require PVE
::QemuConfig
;
33 $have_qemu_server = 1;
43 my $pve_fw_status_dir = "/var/lib/pve-firewall";
45 mkdir $pve_fw_status_dir; # make sure this exists
47 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
48 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
49 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
51 my $max_alias_name_length = 64;
52 my $max_ipset_name_length = 64;
53 my $max_group_name_length = 18;
55 my $PROTOCOLS_WITH_PORTS = {
57 udplite
=> 1, 136 => 1,
63 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
64 sub pve_verify_ip_or_cidr
{
65 my ($cidr, $noerr) = @_;
67 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
68 return $cidr if Net
::IP-
>new($cidr);
69 return undef if $noerr;
70 die Net
::IP
::Error
() . "\n";
72 return undef if $noerr;
73 die "value does not look like a valid IP address or CIDR network\n";
76 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
77 sub pve_verify_ip_or_cidr_or_alias
{
78 my ($cidr, $noerr) = @_;
80 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
82 return pve_verify_ip_or_cidr
($cidr, $noerr);
85 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
86 description
=> "IP set name.",
88 pattern
=> $ipset_name_pattern,
90 maxLength
=> $max_ipset_name_length,
93 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
94 description
=> "Alias name.",
96 pattern
=> $ip_alias_pattern,
98 maxLength
=> $max_alias_name_length,
101 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
102 description
=> "Log level.",
104 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
108 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
109 description
=> "Security Group name.",
111 pattern
=> $security_group_name_pattern,
113 maxLength
=> $max_group_name_length,
116 my $feature_ipset_nomatch = 0;
118 my (undef, undef, $release) = POSIX
::uname
();
119 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
120 my ($major, $minor) = ($1, $2);
121 $feature_ipset_nomatch = 1 if ($major > 3) ||
122 ($major == 3 && $minor >= 7);
127 my $nodename = PVE
::INotify
::nodename
();
129 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
131 my $default_log_level = 'nolog'; # avoid logs by default
133 my $log_level_hash = {
144 # we need to overwrite some macros for ipv6
145 my $pve_ipv6fw_macros = {
147 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
149 'NeighborDiscovery' => [
150 "IPv6 neighbor solicitation, neighbor and router advertisement",
151 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-solicitation' },
152 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-advertisement' },
153 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-solicitation' },
154 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-advertisement' },
158 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
161 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
162 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
166 # imported/converted from: /usr/share/shorewall/macro.*
167 my $pve_fw_macros = {
170 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
171 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
174 "Auth (identd) traffic",
175 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
178 "Border Gateway Protocol traffic",
179 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
182 "BitTorrent traffic for BitTorrent 3.1 and earlier",
183 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
184 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
187 "BitTorrent traffic for BitTorrent 3.2 and later",
188 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
189 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
192 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
193 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6789' },
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6800:7300' },
197 "Concurrent Versions System pserver traffic",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
201 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
202 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
203 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
204 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
207 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
208 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
209 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
212 "Distributed Checksum Clearinghouse spam filtering mechanism",
213 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
216 "Forwarded DHCP traffic",
217 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
220 "Domain Name System traffic (upd and tcp)",
221 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
222 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
225 "Distributed Compiler service",
226 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
229 "File Transfer Protocol",
230 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
233 "Finger protocol (RFC 742)",
234 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
237 "GNUnet secure peer-to-peer networking traffic",
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
239 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
240 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
241 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
244 "Generic Routing Encapsulation tunneling protocol",
245 { action
=> 'PARAM', proto
=> '47' },
248 "Git distributed revision control traffic",
249 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
252 "OpenPGP HTTP keyserver protocol traffic",
253 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
256 "Hypertext Transfer Protocol (WWW)",
257 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
260 "Hypertext Transfer Protocol (WWW) over SSL",
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
264 "Internet Cache Protocol V2 (Squid) traffic",
265 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
268 "AOL Instant Messenger traffic",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
272 "Internet Message Access Protocol",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
276 "Internet Message Access Protocol over SSL",
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
280 "IPIP capsulation traffic",
281 { action
=> 'PARAM', proto
=> '94' },
285 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
286 { action
=> 'PARAM', proto
=> '50' },
289 "IPsec authentication (AH) traffic",
290 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
291 { action
=> 'PARAM', proto
=> '51' },
294 "IPsec traffic and Nat-Traversal",
295 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
296 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
297 { action
=> 'PARAM', proto
=> '50' },
300 "Internet Relay Chat traffic",
301 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
304 "HP Jetdirect printing",
305 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
308 "Layer 2 Tunneling Protocol traffic",
309 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
312 "Lightweight Directory Access Protocol traffic",
313 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
316 "Secure Lightweight Directory Access Protocol traffic",
317 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
320 "Microsoft Notification Protocol",
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
324 "Microsoft SQL Server",
325 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
328 "Mail traffic (SMTP, SMTPS, Submission)",
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
330 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
331 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
335 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5353' },
338 "Munin networked resource monitoring traffic",
339 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
343 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
346 "NNTP traffic (Usenet).",
347 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
350 "Encrypted NNTP traffic (Usenet)",
351 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
354 "Network Time Protocol (ntpd)",
355 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
358 "OSPF multicast traffic",
359 { action
=> 'PARAM', proto
=> '89' },
363 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
366 "Symantec PCAnywere (tm)",
367 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
368 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
372 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
375 "Encrypted POP3 traffic",
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
379 "Point-to-Point Tunneling Protocol",
380 { action
=> 'PARAM', proto
=> '47' },
381 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
385 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
392 "Line Printer protocol printing",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
396 "Microsoft Remote Desktop Protocol traffic",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
400 "Routing Information Protocol (bidirectional)",
401 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
404 "BIND remote management protocol",
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
408 "Razor Antispam System",
409 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
412 "Remote time retrieval (rdate)",
413 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
417 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
420 "SANE network scanning",
421 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
424 "Microsoft SMB traffic",
425 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
426 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
427 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
428 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
431 "Samba Web Administration Tool",
432 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
435 "Simple Mail Transfer Protocol",
436 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
439 "Encrypted Simple Mail Transfer Protocol",
440 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
443 "Simple Network Management Protocol",
444 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
445 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
448 "Spam Assassin SPAMD traffic",
449 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
452 "Secure shell traffic",
453 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
456 "Subversion server (svnserve)",
457 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
460 "SixXS IPv6 Deployment and Tunnel Broker",
461 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
462 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
463 { action
=> 'PARAM', proto
=> '41' },
464 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
467 "Squid web proxy traffic",
468 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
471 "Mail message submission traffic",
472 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
475 "Syslog protocol (RFC 5424) traffic",
476 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
477 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
480 "Trivial File Transfer Protocol traffic",
481 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
485 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
489 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
492 "RFC 868 Time protocol",
493 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
496 "Traceroute (for up to 30 hops) traffic",
497 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
498 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
501 "VNC traffic for VNC display's 0 - 99",
502 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
505 "VNC traffic from Vncservers to Vncviewers in listen mode",
506 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
509 "WWW traffic (HTTP and HTTPS)",
510 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
511 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
514 "Web Cache/Proxy traffic (port 8080)",
515 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
519 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
522 "Whois (nicname, RFC 3912) traffic",
523 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
527 my $pve_fw_parsed_macros;
528 my $pve_fw_macro_descr;
529 my $pve_fw_macro_ipversion = {};
530 my $pve_fw_preferred_macro_names = {};
532 my $FWACCEPTMARK_ON = "0x80000000/0x80000000";
533 my $FWACCEPTMARK_OFF = "0x00000000/0x80000000";
535 my $pve_std_chains = {};
536 $pve_std_chains->{4} = {
537 'PVEFW-SET-ACCEPT-MARK' => [
538 "-j MARK --set-mark $FWACCEPTMARK_ON",
540 'PVEFW-DropBroadcast' => [
541 # same as shorewall 'Broadcast'
542 # simply DROP BROADCAST/MULTICAST/ANYCAST
543 # we can use this to reduce logging
544 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
545 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
546 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
547 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
550 # same as shorewall 'reject'
551 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
552 { action
=> 'DROP', source
=> '224.0.0.0/4' },
553 { action
=> 'DROP', proto
=> 'icmp' },
554 "-p tcp -j REJECT --reject-with tcp-reset",
555 "-p udp -j REJECT --reject-with icmp-port-unreachable",
556 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
557 "-j REJECT --reject-with icmp-host-prohibited",
560 # same as shorewall 'Drop', which is equal to DROP,
561 # but REJECT/DROP some packages to reduce logging,
562 # and ACCEPT critical ICMP types
563 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
564 # we are not interested in BROADCAST/MULTICAST/ANYCAST
565 { action
=> 'PVEFW-DropBroadcast' },
566 # ACCEPT critical ICMP types
567 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
568 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
569 # Drop packets with INVALID state
570 "-m conntrack --ctstate INVALID -j DROP",
571 # Drop Microsoft SMB noise
572 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
573 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
574 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
575 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
576 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
577 # Drop new/NotSyn traffic so that it doesn't get logged
578 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
580 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
583 # same as shorewall 'Reject', which is equal to Reject,
584 # but REJECT/DROP some packages to reduce logging,
585 # and ACCEPT critical ICMP types
586 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
587 # we are not interested in BROADCAST/MULTICAST/ANYCAST
588 { action
=> 'PVEFW-DropBroadcast' },
589 # ACCEPT critical ICMP types
590 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
591 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
592 # Drop packets with INVALID state
593 "-m conntrack --ctstate INVALID -j DROP",
594 # Drop Microsoft SMB noise
595 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
596 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
597 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
598 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
599 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
600 # Drop new/NotSyn traffic so that it doesn't get logged
601 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
603 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
605 'PVEFW-tcpflags' => [
606 # same as shorewall tcpflags action.
607 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
608 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
609 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
610 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
611 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
612 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
615 # same as shorewall smurfs action
616 # Filter packets for smurfs (packets with a broadcast address as the source).
617 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
618 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
619 "-s 224.0.0.0/4 -g PVEFW-smurflog",
623 $pve_std_chains->{6} = {
624 'PVEFW-SET-ACCEPT-MARK' => [
625 "-j MARK --set-mark $FWACCEPTMARK_ON",
627 'PVEFW-DropBroadcast' => [
628 # same as shorewall 'Broadcast'
629 # simply DROP BROADCAST/MULTICAST/ANYCAST
630 # we can use this to reduce logging
631 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
632 # ipv6 addrtype does not work with kernel 2.6.32
633 #{ action => 'DROP', dsttype => 'MULTICAST' },
634 #{ action => 'DROP', dsttype => 'ANYCAST' },
635 { action
=> 'DROP', dest
=> 'ff00::/8' },
636 #{ action => 'DROP', dest => '224.0.0.0/4' },
639 # same as shorewall 'reject'
640 #{ action => 'DROP', dsttype => 'BROADCAST' },
641 #{ action => 'DROP', source => '224.0.0.0/4' },
642 { action
=> 'DROP', proto
=> 'icmpv6' },
643 "-p tcp -j REJECT --reject-with tcp-reset",
644 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
645 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
646 #"-j REJECT --reject-with icmp-host-prohibited",
649 # same as shorewall 'Drop', which is equal to DROP,
650 # but REJECT/DROP some packages to reduce logging,
651 # and ACCEPT critical ICMP types
652 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
653 # we are not interested in BROADCAST/MULTICAST/ANYCAST
654 { action
=> 'PVEFW-DropBroadcast' },
655 # ACCEPT critical ICMP types
656 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
657 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
658 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
660 # Drop packets with INVALID state
661 "-m conntrack --ctstate INVALID -j DROP",
662 # Drop Microsoft SMB noise
663 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
664 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
665 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
666 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
667 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
668 # Drop new/NotSyn traffic so that it doesn't get logged
669 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
671 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
674 # same as shorewall 'Reject', which is equal to Reject,
675 # but REJECT/DROP some packages to reduce logging,
676 # and ACCEPT critical ICMP types
677 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
678 # we are not interested in BROADCAST/MULTICAST/ANYCAST
679 { action
=> 'PVEFW-DropBroadcast' },
680 # ACCEPT critical ICMP types
681 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
682 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
683 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
685 # Drop packets with INVALID state
686 "-m conntrack --ctstate INVALID -j DROP",
687 # Drop Microsoft SMB noise
688 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
689 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
690 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
691 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
692 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
693 # Drop new/NotSyn traffic so that it doesn't get logged
694 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
696 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
698 'PVEFW-tcpflags' => [
699 # same as shorewall tcpflags action.
700 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
701 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
702 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
703 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
704 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
705 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
709 # iptables -p icmp -h
710 my $icmp_type_names = {
713 'destination-unreachable' => 1,
714 'network-unreachable' => 1,
715 'host-unreachable' => 1,
716 'protocol-unreachable' => 1,
717 'port-unreachable' => 1,
718 'fragmentation-needed' => 1,
719 'source-route-failed' => 1,
720 'network-unknown' => 1,
722 'network-prohibited' => 1,
723 'host-prohibited' => 1,
724 'TOS-network-unreachable' => 1,
725 'TOS-host-unreachable' => 1,
726 'communication-prohibited' => 1,
727 'host-precedence-violation' => 1,
728 'precedence-cutoff' => 1,
729 'source-quench' => 1,
731 'network-redirect' => 1,
732 'host-redirect' => 1,
733 'TOS-network-redirect' => 1,
734 'TOS-host-redirect' => 1,
736 'router-advertisement' => 1,
737 'router-solicitation' => 1,
738 'time-exceeded' => 1,
739 'ttl-zero-during-transit' => 1,
740 'ttl-zero-during-reassembly' => 1,
741 'parameter-problem' => 1,
742 'ip-header-bad' => 1,
743 'required-option-missing' => 1,
744 'timestamp-request' => 1,
745 'timestamp-reply' => 1,
746 'address-mask-request' => 1,
747 'address-mask-reply' => 1,
750 # ip6tables -p icmpv6 -h
752 my $icmpv6_type_names = {
754 'destination-unreachable' => 1,
756 'communication-prohibited' => 1,
757 'address-unreachable' => 1,
758 'port-unreachable' => 1,
759 'packet-too-big' => 1,
760 'time-exceeded' => 1,
761 'ttl-zero-during-transit' => 1,
762 'ttl-zero-during-reassembly' => 1,
763 'parameter-problem' => 1,
765 'unknown-header-type' => 1,
766 'unknown-option' => 1,
769 'router-solicitation' => 1,
770 'router-advertisement' => 1,
771 'neighbor-solicitation' => 1,
772 'neighbour-solicitation' => 1,
773 'neighbor-advertisement' => 1,
774 'neighbour-advertisement' => 1,
778 sub init_firewall_macros
{
780 $pve_fw_parsed_macros = {};
783 my ($k, $macro) = @_;
784 my $lc_name = lc($k);
785 $pve_fw_macro_ipversion->{$k} = 0;
786 while (!ref($macro->[0])) {
787 my $desc = shift @$macro;
788 if ($desc eq 'ipv4only') {
789 $pve_fw_macro_ipversion->{$k} = 4;
790 } elsif ($desc eq 'ipv6only') {
791 $pve_fw_macro_ipversion->{$k} = 6;
793 $pve_fw_macro_descr->{$k} = $desc;
796 $pve_fw_preferred_macro_names->{$lc_name} = $k;
797 $pve_fw_parsed_macros->{$k} = $macro;
800 foreach my $k (keys %$pve_fw_macros) {
801 &$parse($k, $pve_fw_macros->{$k});
804 foreach my $k (keys %$pve_ipv6fw_macros) {
805 next if $pve_fw_parsed_macros->{$k};
806 &$parse($k, $pve_ipv6fw_macros->{$k});
807 $pve_fw_macro_ipversion->{$k} = 6;
811 init_firewall_macros
();
814 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
819 sub get_etc_services
{
821 return $etc_services if $etc_services;
823 my $filename = "/etc/services";
825 my $fh = IO
::File-
>new($filename, O_RDONLY
);
827 warn "unable to read '$filename' - $!\n";
833 while (my $line = <$fh>) {
835 next if $line =~m/^#/;
836 next if ($line =~m/^\s*$/);
838 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
839 $services->{byid
}->{$2}->{name
} = $1;
840 $services->{byid
}->{$2}->{port
} = $2;
841 $services->{byid
}->{$2}->{$3} = 1;
842 $services->{byname
}->{$1} = $services->{byid
}->{$2};
848 $etc_services = $services;
851 return $etc_services;
856 sub get_etc_protocols
{
857 return $etc_protocols if $etc_protocols;
859 my $filename = "/etc/protocols";
861 my $fh = IO
::File-
>new($filename, O_RDONLY
);
863 warn "unable to read '$filename' - $!\n";
869 while (my $line = <$fh>) {
871 next if $line =~m/^#/;
872 next if ($line =~m/^\s*$/);
874 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
875 $protocols->{byid
}->{$2}->{name
} = $1;
876 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
882 # add special case for ICMP v6
883 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
884 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
886 $etc_protocols = $protocols;
888 return $etc_protocols;
894 my ($new_value) = @_;
896 $__local_network = $new_value if defined($new_value);
898 return $__local_network if defined($__local_network);
901 my $nodename = PVE
::INotify
::nodename
();
903 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
905 my $testip = Net
::IP-
>new($ip);
907 my $isv6 = $testip->version == 6;
908 my $routes = $isv6 ? PVE
::ProcFSTools
::read_proc_net_ipv6_route
()
909 : PVE
::ProcFSTools
::read_proc_net_route
();
910 foreach my $entry (@$routes) {
913 $mask = $entry->{prefix
};
914 next if !$mask; # skip the default route...
916 $mask = $PVE::Network
::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 my $overlap = $testnet->overlaps($testip);
922 if ($overlap == $Net::IP
::IP_B_IN_A_OVERLAP
||
923 $overlap == $Net::IP
::IP_IDENTICAL
)
925 $__local_network = $cidr;
932 return $__local_network;
935 # ipset names are limited to 31 characters,
936 # and we use '-v4' or '-v6' to indicate IP versions,
937 # and we use '_swap' suffix for atomic update,
938 # for example PVEFW-${VMID}-${ipset_name}_swap
940 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
942 sub compute_ipset_chain_name
{
943 my ($vmid, $ipset_name, $ipversion) = @_;
945 $vmid = 0 if !defined($vmid);
947 my $id = "$vmid-${ipset_name}-v$ipversion";
949 if (length($id) > $max_iptables_ipset_name_length) {
950 $id = PVE
::Tools
::fnv31a_hex
($id);
956 sub compute_ipfilter_ipset_name
{
959 return "ipfilter-$iface";
962 sub parse_address_list
{
965 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
966 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
970 if ($str =~ m/^${ip_alias_pattern}$/) {
971 die "alias name too long\n" if length($str) > $max_alias_name_length;
979 foreach my $elem (split(/,/, $str)) {
981 my $ip = Net
::IP-
>new($elem);
983 my $err = Net
::IP
::Error
();
984 die "invalid IP address: $err\n";
986 $iprange = 1 if $elem =~ m/-/;
988 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
990 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
991 if $ipversion && ($new_ipversion != $ipversion);
993 $ipversion = $new_ipversion;
996 die "you can't use a range in a list\n" if $iprange && $count > 1;
1001 sub parse_port_name_number_or_range
{
1002 my ($str, $dport) = @_;
1004 my $services = PVE
::Firewall
::get_etc_services
();
1008 foreach my $item (split(/,/, $str)) {
1010 if ($item =~ m/^(\d+):(\d+)$/) {
1011 my ($port1, $port2) = ($1, $2);
1012 die "invalid port '$port1'\n" if $port1 > 65535;
1013 die "invalid port '$port2'\n" if $port2 > 65535;
1014 } elsif ($item =~ m/^(\d+)$/) {
1016 die "invalid port '$port'\n" if $port > 65535;
1018 if ($dport && $icmp_type_names->{$item}) {
1020 } elsif ($dport && $icmpv6_type_names->{$item}) {
1023 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1028 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1033 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1034 sub pve_fw_verify_sport_spec
{
1037 parse_port_name_number_or_range
($portstr, 0);
1042 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1043 sub pve_fw_verify_dport_spec
{
1046 parse_port_name_number_or_range
($portstr, 1);
1051 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1052 sub pve_fw_verify_addr_spec
{
1055 parse_address_list
($list);
1060 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1061 sub pve_fw_verify_protocol_spec
{
1064 my $protocols = get_etc_protocols
();
1066 die "unknown protocol '$proto'\n" if $proto &&
1067 !(defined($protocols->{byname
}->{$proto}) ||
1068 defined($protocols->{byid
}->{$proto}));
1074 # helper function for API
1076 sub copy_opject_with_digest
{
1079 my $sha = Digest
::SHA-
>new('sha1');
1082 foreach my $k (sort keys %$object) {
1083 my $v = $object->{$k};
1084 next if !defined($v);
1086 $sha->add($k, ':', $v, "\n");
1089 my $digest = $sha->hexdigest;
1091 $res->{digest
} = $digest;
1093 return wantarray ?
($res, $digest) : $res;
1096 sub copy_list_with_digest
{
1099 my $sha = Digest
::SHA-
>new('sha1');
1102 foreach my $entry (@$list) {
1104 foreach my $k (sort keys %$entry) {
1105 my $v = $entry->{$k};
1106 next if !defined($v);
1108 # Note: digest ignores refs ($rule->{errors})
1109 # since Digest::SHA expects a series of bytes,
1110 # we have to encode the value here to prevent errors when
1111 # using utf8 characters (eg. in comments)
1112 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1117 my $digest = $sha->hexdigest;
1119 foreach my $entry (@$res) {
1120 $entry->{digest
} = $digest;
1123 return wantarray ?
($res, $digest) : $res;
1126 our $cluster_option_properties = {
1128 description
=> "Enable or disable the firewall cluster wide.",
1134 description
=> "Input policy.",
1137 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1140 description
=> "Output policy.",
1143 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1147 our $host_option_properties = {
1149 description
=> "Enable host firewall rules.",
1153 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1154 description
=> "Log level for incoming traffic." }),
1155 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1156 description
=> "Log level for outgoing traffic." }),
1157 tcp_flags_log_level
=> get_standard_option
('pve-fw-loglevel', {
1158 description
=> "Log level for illegal tcp flags filter." }),
1159 smurf_log_level
=> get_standard_option
('pve-fw-loglevel', {
1160 description
=> "Log level for SMURFS filter." }),
1162 description
=> "Enable SMURFS filter.",
1167 description
=> "Filter illegal combinations of TCP flags.",
1171 nf_conntrack_max
=> {
1172 description
=> "Maximum number of tracked connections.",
1177 nf_conntrack_tcp_timeout_established
=> {
1178 description
=> "Conntrack established timeout.",
1184 description
=> "Enable NDP.",
1190 our $vm_option_properties = {
1192 description
=> "Enable/disable firewall rules.",
1197 description
=> "Enable/disable MAC address filter.",
1202 description
=> "Enable DHCP.",
1207 description
=> "Enable NDP.",
1212 description
=> "Allow sending Router Advertisement.",
1217 description
=> "Enable default IP filters. " .
1218 "This is equivalent to adding an empty ipfilter-net<id> ipset " .
1219 "for every interface. Such ipsets implicitly contain sane default " .
1220 "restrictions such as restricting IPv6 link local addresses to " .
1221 "the one derived from the interface's MAC address. For containers " .
1222 "the configured IP addresses will be implicitly added.",
1227 description
=> "Input policy.",
1230 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1233 description
=> "Output policy.",
1236 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1238 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1239 description
=> "Log level for incoming traffic." }),
1240 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1241 description
=> "Log level for outgoing traffic." }),
1246 my $addr_list_descr = "This can refer to a single IP address, an IP set ('+ipsetname') or an IP alias definition. You can also specify an address range like '20.34.101.207-201.3.9.99', or a list of IP addresses and networks (entries are separated by comma). Please do not mix IPv4 and IPv6 addresses inside such lists.";
1248 my $port_descr = "You can use service names or simple numbers (0-65535), as defined in '/etc/services'. Port ranges can be specified with '\\d+:\\d+', for example '80:85', and you can use comma separated list to match several ports or ranges.";
1250 my $rule_properties = {
1252 description
=> "Update rule at position <pos>.",
1257 digest
=> get_standard_option
('pve-config-digest'),
1259 description
=> "Rule type.",
1262 enum
=> ['in', 'out', 'group'],
1265 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1268 pattern
=> $security_group_name_pattern,
1273 description
=> "Use predefined standard macro.",
1278 iface
=> get_standard_option
('pve-iface', {
1279 description
=> "Network interface name. You have to use network configuration key names for VMs and containers ('net\\d+'). Host related rules can use arbitrary strings.",
1283 description
=> "Restrict packet source address. $addr_list_descr",
1284 type
=> 'string', format
=> 'pve-fw-addr-spec',
1288 description
=> "Restrict packet destination address. $addr_list_descr",
1289 type
=> 'string', format
=> 'pve-fw-addr-spec',
1293 description
=> "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
1294 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1298 description
=> "Flag to enable/disable a rule.",
1304 description
=> "Restrict TCP/UDP source port. $port_descr",
1305 type
=> 'string', format
=> 'pve-fw-sport-spec',
1309 description
=> "Restrict TCP/UDP destination port. $port_descr",
1310 type
=> 'string', format
=> 'pve-fw-dport-spec',
1314 description
=> "Descriptive comment.",
1320 sub add_rule_properties
{
1321 my ($properties) = @_;
1323 foreach my $k (keys %$rule_properties) {
1324 my $h = $rule_properties->{$k};
1325 # copy data, so that we can modify later without side effects
1326 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1332 sub delete_rule_properties
{
1333 my ($rule, $delete_str) = @_;
1335 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1336 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1337 if !defined($rule_properties->{$opt});
1338 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1339 if $opt eq 'type' || $opt eq 'action';
1340 delete $rule->{$opt};
1346 my $apply_macro = sub {
1347 my ($macro_name, $param, $verify, $ipversion) = @_;
1349 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1350 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1352 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1353 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1356 # skip macros which are specific to another ipversion
1357 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1358 return if $ipversion != $required;
1363 foreach my $templ (@$macro_rules) {
1365 my $param_used = {};
1366 foreach my $k (keys %$templ) {
1367 my $v = $templ->{$k};
1368 if ($v eq 'PARAM') {
1370 $param_used->{$k} = 1;
1371 } elsif ($v eq 'DEST') {
1372 $v = $param->{dest
};
1373 $param_used->{dest
} = 1;
1374 } elsif ($v eq 'SOURCE') {
1375 $v = $param->{source
};
1376 $param_used->{source
} = 1;
1380 my $msg = "missing parameter '$k' in macro '$macro_name'";
1381 raise_param_exc
({ macro => $msg }) if $verify;
1386 foreach my $k (keys %$param) {
1387 next if $k eq 'macro';
1388 next if !defined($param->{$k});
1389 next if $param_used->{$k};
1390 if (defined($rule->{$k})) {
1391 if ($rule->{$k} ne $param->{$k}) {
1392 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1393 raise_param_exc
({ $k => $msg }) if $verify;
1397 $rule->{$k} = $param->{$k};
1400 push @$rules, $rule;
1406 my $rule_env_iface_lookup = {
1415 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1417 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1419 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1420 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1422 my $errors = $rule->{errors
} || {};
1424 my $error_count = 0;
1426 my $add_error = sub {
1427 my ($param, $msg) = @_;
1429 raise_param_exc
({ $param => $msg }) if !$noerr;
1431 $errors->{$param} = $msg if !$errors->{$param};
1435 my $set_ip_version = sub {
1438 die "detected mixed ipv4/ipv6 adresses in rule\n"
1439 if $ipversion && ($vers != $ipversion);
1444 my $check_ipset_or_alias_property = sub {
1445 my ($name, $expected_ipversion) = @_;
1447 if (my $value = $rule->{$name}) {
1448 if ($value =~ m/^\+/) {
1449 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1450 &$add_error($name, "no such ipset '$1'")
1451 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1454 &$add_error($name, "invalid ipset name '$value'");
1456 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1457 my $alias = lc($value);
1458 &$add_error($name, "no such alias '$value'")
1459 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1460 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1461 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1463 &$set_ip_version($e->{ipversion
});
1468 my $type = $rule->{type
};
1469 my $action = $rule->{action
};
1471 &$add_error('type', "missing property") if !$type;
1472 &$add_error('action', "missing property") if !$action;
1475 if ($type eq 'in' || $type eq 'out') {
1476 &$add_error('action', "unknown action '$action'")
1477 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1478 } elsif ($type eq 'group') {
1479 &$add_error('type', "security groups not allowed")
1481 &$add_error('action', "invalid characters in security group name")
1482 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1484 &$add_error('type', "unknown rule type '$type'");
1488 if ($rule->{iface
}) {
1489 &$add_error('type', "parameter -i not allowed for this rule type")
1491 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1492 &$add_error('iface', $@) if $@;
1493 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1494 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1495 if $rule->{iface
} !~ m/^net(\d+)$/;
1499 if ($rule->{macro}) {
1500 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1501 $rule->{macro} = $preferred_name;
1503 &$add_error('macro', "unknown macro '$rule->{macro}'");
1507 if ($rule->{proto
}) {
1508 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1509 &$add_error('proto', $@) if $@;
1510 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1511 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1514 if ($rule->{dport
}) {
1515 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1516 &$add_error('dport', $@) if $@;
1517 my $proto = $rule->{proto
};
1518 &$add_error('proto', "missing property - 'dport' requires this property")
1520 &$add_error('dport', "protocol '$proto' does not support ports")
1521 if !$PROTOCOLS_WITH_PORTS->{$proto} &&
1522 $proto ne 'icmp' && $proto ne 'icmpv6'; # special cases
1525 if ($rule->{sport
}) {
1526 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1527 &$add_error('sport', $@) if $@;
1528 my $proto = $rule->{proto
};
1529 &$add_error('proto', "missing property - 'sport' requires this property")
1531 &$add_error('sport', "protocol '$proto' does not support ports")
1532 if !$PROTOCOLS_WITH_PORTS->{$proto};
1535 if ($rule->{source
}) {
1537 my $source_ipversion = parse_address_list
($rule->{source
});
1538 &$set_ip_version($source_ipversion);
1540 &$add_error('source', $@) if $@;
1541 &$check_ipset_or_alias_property('source', $ipversion);
1544 if ($rule->{dest
}) {
1546 my $dest_ipversion = parse_address_list
($rule->{dest
});
1547 &$set_ip_version($dest_ipversion);
1549 &$add_error('dest', $@) if $@;
1550 &$check_ipset_or_alias_property('dest', $ipversion);
1553 $rule->{ipversion
} = $ipversion if $ipversion;
1555 if ($rule->{macro} && !$error_count) {
1556 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1558 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1559 my $eh = $err->{errors
};
1560 foreach my $p (keys %$eh) {
1561 &$add_error($p, $eh->{$p});
1564 &$add_error('macro', "$err");
1569 $rule->{errors
} = $errors if $error_count;
1574 sub copy_rule_data
{
1575 my ($rule, $param) = @_;
1577 foreach my $k (keys %$rule_properties) {
1578 if (defined(my $v = $param->{$k})) {
1579 if ($v eq '' || $v eq '-') {
1590 sub rules_modify_permissions
{
1591 my ($rule_env) = @_;
1593 if ($rule_env eq 'host') {
1595 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1597 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1599 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1601 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1603 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1610 sub rules_audit_permissions
{
1611 my ($rule_env) = @_;
1613 if ($rule_env eq 'host') {
1615 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1617 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1619 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1621 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1623 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1631 my $bridge_firewall_enabled = 0;
1633 sub enable_bridge_firewall
{
1635 return if $bridge_firewall_enabled; # only once
1637 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1638 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1640 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1641 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1643 $bridge_firewall_enabled = 1;
1646 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1648 sub iptables_restore_cmdlist
{
1651 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1654 sub ip6tables_restore_cmdlist
{
1657 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1660 sub ipset_restore_cmdlist
{
1663 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1666 sub iptables_get_chains
{
1667 my ($iptablescmd) = @_;
1669 $iptablescmd = "iptables" if !$iptablescmd;
1673 # check what chains we want to track
1674 my $is_pvefw_chain = sub {
1677 return 1 if $name =~ m/^PVEFW-\S+$/;
1679 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1681 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1683 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1684 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1696 return if $line =~ m/^#/;
1697 return if $line =~ m/^\s*$/;
1699 if ($line =~ m/^\*(\S+)$/) {
1704 return if $table ne 'filter';
1706 if ($line =~ m/^:(\S+)\s/) {
1708 return if !&$is_pvefw_chain($chain);
1709 $res->{$chain} = "unknown";
1710 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1711 my ($chain, $sig) = ($1, $2);
1712 return if !&$is_pvefw_chain($chain);
1713 $res->{$chain} = $sig;
1714 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1717 # simply ignore the rest
1722 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1724 return wantarray ?
($res, $hooks) : $res;
1727 sub iptables_chain_digest
{
1729 my $digest = Digest
::SHA-
>new('sha1');
1730 foreach my $rule (@$rules) { # order is important
1731 $digest->add($rule);
1733 return $digest->b64digest;
1736 sub ipset_chain_digest
{
1739 my $digest = Digest
::SHA-
>new('sha1');
1740 foreach my $rule (sort @$rules) { # note: sorted
1741 $digest->add($rule);
1743 return $digest->b64digest;
1746 sub ipset_get_chains
{
1754 return if $line =~ m/^#/;
1755 return if $line =~ m/^\s*$/;
1756 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1758 $line =~ s/\s+$//; # delete trailing white space
1759 push @{$chains->{$chain}}, $line;
1761 # simply ignore the rest
1766 run_command
("/sbin/ipset save", outfunc
=> $parser);
1768 # compute digest for each chain
1769 foreach my $chain (keys %$chains) {
1770 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1776 sub ruleset_generate_cmdstr
{
1777 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1779 return if defined($rule->{enable
}) && !$rule->{enable
};
1780 return if $rule->{errors
};
1782 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1784 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1785 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1789 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1790 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1792 my $source = $rule->{source
};
1793 my $dest = $rule->{dest
};
1796 if ($source =~ m/^\+/) {
1797 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1799 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1800 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1801 push @cmd, "-m set --match-set ${ipset_chain} src";
1802 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1803 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1804 push @cmd, "-m set --match-set ${ipset_chain} src";
1806 die "no such ipset '$name'\n";
1809 die "invalid security group name '$source'\n";
1811 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1812 my $alias = lc($source);
1813 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1814 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1815 die "no such alias '$source'\n" if !$e;
1816 push @cmd, "-s $e->{cidr}";
1817 } elsif ($source =~ m/\-/){
1818 push @cmd, "-m iprange --src-range $source";
1820 push @cmd, "-s $source";
1825 if ($dest =~ m/^\+/) {
1826 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1828 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1829 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1830 push @cmd, "-m set --match-set ${ipset_chain} dst";
1831 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1832 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1833 push @cmd, "-m set --match-set ${ipset_chain} dst";
1835 die "no such ipset '$name'\n";
1838 die "invalid security group name '$dest'\n";
1840 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1841 my $alias = lc($dest);
1842 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1843 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1844 die "no such alias '$dest'\n" if !$e;
1845 push @cmd, "-d $e->{cidr}";
1846 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1847 push @cmd, "-m iprange --dst-range $dest";
1849 push @cmd, "-d $dest";
1853 if (my $proto = $rule->{proto
}) {
1854 push @cmd, "-p $proto";
1857 $multiport++ if $nbdport > 1;
1858 $multiport++ if $nbsport > 1;
1860 push @cmd, "--match multiport" if $multiport;
1862 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1863 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1865 if ($rule->{dport
}) {
1866 if ($proto eq 'icmp') {
1867 # Note: we use dport to store --icmp-type
1868 die "unknown icmp-type '$rule->{dport}'\n"
1869 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1870 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1871 } elsif ($proto eq 'icmpv6') {
1872 # Note: we use dport to store --icmpv6-type
1873 die "unknown icmpv6-type '$rule->{dport}'\n"
1874 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1875 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1876 } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
1877 die "protocol $proto does not have ports\n";
1880 if ($multiport == 2) {
1881 push @cmd, "--ports $rule->{dport}";
1883 push @cmd, "--dports $rule->{dport}";
1886 push @cmd, "--dport $rule->{dport}";
1891 if ($rule->{sport
}) {
1892 die "protocol $proto does not have ports\n"
1893 if !$PROTOCOLS_WITH_PORTS->{$proto};
1895 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1897 push @cmd, "--sport $rule->{sport}";
1900 } elsif ($rule->{dport
} || $rule->{sport
}) {
1901 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1902 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1905 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1907 if (my $action = $rule->{action
}) {
1908 $action = $actions->{$action} if defined($actions->{$action});
1909 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1910 push @cmd, $goto ?
"-g $action" : "-j $action";
1913 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1916 sub ruleset_generate_rule
{
1917 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1921 if ($rule->{macro}) {
1922 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1927 # update all or nothing
1930 foreach my $tmp (@$rules) {
1931 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1932 push @cmds, $cmdstr;
1936 foreach my $cmdstr (@cmds) {
1937 ruleset_addrule
($ruleset, $chain, $cmdstr);
1941 sub ruleset_generate_rule_insert
{
1942 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1944 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1946 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1947 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1951 sub ruleset_create_chain
{
1952 my ($ruleset, $chain) = @_;
1954 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1955 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1957 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1959 $ruleset->{$chain} = [];
1962 sub ruleset_chain_exist
{
1963 my ($ruleset, $chain) = @_;
1965 return $ruleset->{$chain} ?
1 : undef;
1968 sub ruleset_addrule
{
1969 my ($ruleset, $chain, $rule) = @_;
1971 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1973 push @{$ruleset->{$chain}}, "-A $chain $rule";
1976 sub ruleset_insertrule
{
1977 my ($ruleset, $chain, $rule) = @_;
1979 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1981 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1984 sub get_log_rule_base
{
1985 my ($chain, $vmid, $msg, $loglevel) = @_;
1987 die "internal error - no log level" if !defined($loglevel);
1989 $vmid = 0 if !defined($vmid);
1991 # Note: we use special format for prefix to pass further
1992 # info to log daemon (VMID, LOGVELEL and CHAIN)
1994 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1997 sub ruleset_addlog {
1998 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
2000 return if !defined($loglevel);
2002 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
2004 $logrule = "$rule $logrule" if defined($rule);
2006 ruleset_addrule($ruleset, $chain, $logrule);
2009 sub ruleset_add_chain_policy {
2010 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
2012 if ($policy eq 'ACCEPT') {
2014 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
2015 { ACCEPT => $accept_action});
2017 } elsif ($policy eq 'DROP') {
2019 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
2021 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
2023 ruleset_addrule($ruleset, $chain, "-j DROP
");
2024 } elsif ($policy eq 'REJECT') {
2025 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
2027 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
2029 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
2032 die "internal error
: unknown policy
'$policy'";
2036 sub ruleset_chain_add_ndp {
2037 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
2038 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2040 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
$accept");
2041 if ($direction ne 'OUT' || $options->{radv}) {
2042 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
$accept");
2044 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
$accept");
2045 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
$accept");
2048 sub ruleset_chain_add_conn_filters {
2049 my ($ruleset, $chain, $accept) = @_;
2051 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
2052 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
2055 sub ruleset_chain_add_input_filters {
2056 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2058 if ($cluster_conf->{ipset}->{blacklist}){
2059 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
2060 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
2061 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
2062 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
2064 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
2065 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
2068 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
2069 if ($ipversion == 4) {
2070 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
2074 if ($options->{tcpflags}) {
2075 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
2079 sub ruleset_create_vm_chain {
2080 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
2082 ruleset_create_chain($ruleset, $chain);
2083 my $accept = generate_nfqueue($options);
2085 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
2086 if ($ipversion == 4) {
2087 if ($direction eq 'OUT') {
2088 ruleset_generate_rule($ruleset, $chain, $ipversion,
2089 { action => 'PVEFW-SET-ACCEPT-MARK',
2090 proto => 'udp', sport => 68, dport => 67 });
2092 ruleset_generate_rule($ruleset, $chain, $ipversion,
2093 { action => 'ACCEPT',
2094 proto => 'udp', sport => 67, dport => 68 });
2096 } elsif ($ipversion == 6) {
2097 if ($direction eq 'OUT') {
2098 ruleset_generate_rule($ruleset, $chain, $ipversion,
2099 { action => 'PVEFW-SET-ACCEPT-MARK',
2100 proto => 'udp', sport => 546, dport => 547 });
2102 ruleset_generate_rule($ruleset, $chain, $ipversion,
2103 { action => 'ACCEPT',
2104 proto => 'udp', sport => 547, dport => 546 });
2110 if ($direction eq 'OUT') {
2111 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
2112 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
2114 if ($ipversion == 6 && !$options->{radv}) {
2115 ruleset_addrule($ruleset, $chain, '-p icmpv6 --icmpv6-type router-advertisement -j DROP');
2117 if ($ipfilter_ipset) {
2118 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
2120 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2123 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
2124 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
2127 sub ruleset_add_group_rule {
2128 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
2130 my $group = $rule->{action};
2131 my $group_chain = "GROUP-
$group-$direction";
2132 if(!ruleset_chain_exist($ruleset, $group_chain)){
2133 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
2136 if ($direction eq 'OUT' && $rule->{iface_out}) {
2137 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
2138 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2139 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
2141 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
2144 ruleset_addrule($ruleset, $chain, "-m mark
--mark
$FWACCEPTMARK_ON -j
$action");
2147 sub ruleset_generate_vm_rules {
2148 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2150 my $lc_direction = lc($direction);
2152 my $in_accept = generate_nfqueue($options);
2154 foreach my $rule (@$rules) {
2155 next if $rule->{iface} && $rule->{iface} ne $netid;
2156 next if !$rule->{enable} || $rule->{errors};
2157 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2159 if ($rule->{type} eq 'group') {
2160 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2161 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2163 next if $rule->{type} ne $lc_direction;
2165 if ($direction eq 'OUT') {
2166 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2167 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2168 undef, $cluster_conf, $vmfw_conf);
2170 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2171 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2172 undef, $cluster_conf, $vmfw_conf);
2180 sub generate_nfqueue {
2183 if ($options->{ips}) {
2184 my $action = "NFQUEUE
";
2185 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2186 if (defined($3) && defined($1)) {
2187 $action .= " --queue-balance
$1:$3";
2188 } elsif (defined($1)) {
2189 $action .= " --queue-num
$1";
2192 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2199 sub ruleset_generate_vm_ipsrules {
2200 my ($ruleset, $options, $direction, $iface) = @_;
2202 if ($options->{ips} && $direction eq 'IN') {
2203 my $nfqueue = generate_nfqueue($options);
2205 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2206 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2209 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
2213 sub generate_tap_rules_direction {
2214 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2216 my $lc_direction = lc($direction);
2218 my $rules = $vmfw_conf->{rules};
2220 my $options = $vmfw_conf->{options};
2221 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2223 my $tapchain = "$iface-$direction";
2225 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2226 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2227 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2229 # create chain with mac and ip filter
2230 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2232 if ($options->{enable}) {
2233 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2235 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2240 if ($direction eq 'OUT') {
2241 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2243 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2246 my $accept = generate_nfqueue($options);
2247 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2248 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2250 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2251 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2254 # plug the tap chain to bridge chain
2255 if ($direction eq 'IN') {
2256 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2257 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2259 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2260 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2264 sub enable_host_firewall {
2265 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2267 my $options = $hostfw_conf->{options};
2268 my $cluster_options = $cluster_conf->{options};
2269 my $rules = $hostfw_conf->{rules};
2270 my $cluster_rules = $cluster_conf->{rules};
2272 # host inbound firewall
2273 my $chain = "PVEFW-HOST-IN
";
2274 ruleset_create_chain($ruleset, $chain);
2276 my $loglevel = get_option_log_level($options, "log_level_in
");
2278 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2280 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2281 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2282 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2284 # we use RETURN because we need to check also tap rules
2285 my $accept_action = 'RETURN';
2287 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2289 # add host rules first, so that cluster wide rules can be overwritten
2290 foreach my $rule (@$rules, @$cluster_rules) {
2291 next if !$rule->{enable} || $rule->{errors};
2292 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2294 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2297 if ($rule->{type} eq 'group') {
2298 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2299 } elsif ($rule->{type} eq 'in') {
2300 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2301 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2302 undef, $cluster_conf, $hostfw_conf);
2306 delete $rule->{iface_in};
2309 # allow standard traffic for management ipset (includes cluster network)
2310 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2311 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2312 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2313 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2314 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2315 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2317 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2318 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2321 if ($localnet && ($ipversion == $localnet_ver)) {
2322 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2323 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2324 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2327 # implement input policy
2328 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2329 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2331 # host outbound firewall
2332 $chain = "PVEFW-HOST-OUT
";
2333 ruleset_create_chain($ruleset, $chain);
2335 $loglevel = get_option_log_level($options, "log_level_out
");
2337 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2339 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2341 # we use RETURN because we may want to check other thigs later
2342 $accept_action = 'RETURN';
2343 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2345 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2347 # add host rules first, so that cluster wide rules can be overwritten
2348 foreach my $rule (@$rules, @$cluster_rules) {
2349 next if !$rule->{enable} || $rule->{errors};
2350 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2352 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2354 if ($rule->{type} eq 'group') {
2355 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2356 } elsif ($rule->{type} eq 'out') {
2357 ruleset_generate_rule($ruleset, $chain, $ipversion,
2358 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2359 undef, $cluster_conf, $hostfw_conf);
2363 delete $rule->{iface_out};
2366 # allow standard traffic on cluster network
2367 if ($localnet && ($ipversion == $localnet_ver)) {
2368 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2369 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2370 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2371 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2373 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2374 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2375 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2378 # implement output policy
2379 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2380 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2382 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2383 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2386 sub generate_group_rules {
2387 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2389 my $rules = $cluster_conf->{groups}->{$group};
2392 warn "no such security group
'$group'\n";
2393 $rules = []; # create empty chain
2396 my $chain = "GROUP-
${group
}-IN
";
2398 ruleset_create_chain($ruleset, $chain);
2399 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2401 foreach my $rule (@$rules) {
2402 next if $rule->{type} ne 'in';
2403 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2404 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2405 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2406 undef, $cluster_conf);
2409 $chain = "GROUP-
${group
}-OUT
";
2411 ruleset_create_chain($ruleset, $chain);
2412 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2414 foreach my $rule (@$rules) {
2415 next if $rule->{type} ne 'out';
2416 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2417 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2418 # check also other tap rules later
2419 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2420 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2421 undef, $cluster_conf);
2426 my $valid_netdev_names = {};
2427 for (my $i = 0; $i < $MAX_NETS; $i++) {
2428 $valid_netdev_names->{"net
$i"} = 1;
2431 sub get_mark_values {
2432 my ($value, $mask) = @_;
2433 $value = hex($value) if $value =~ /^0x/;
2434 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2435 $mask = 0xffffffff if !defined($mask);
2436 return ($value, $mask);
2440 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2442 my $orig_line = $line;
2446 # we can add single line comments to the end of the rule
2447 if ($line =~ s/#\s*(.*?)\s*$//) {
2448 $rule->{comment} = decode('utf8', $1);
2451 # we can disable a rule when prefixed with '|'
2453 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2455 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2456 die "unable to parse rule
: $line\n";
2458 $rule->{type} = lc($1);
2459 $rule->{action} = $2;
2461 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2462 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2463 $rule->{macro} = $1;
2464 $rule->{action} = $2;
2468 while (length($line)) {
2469 if ($line =~ s/^-i (\S+)\s*//) {
2470 $rule->{iface} = $1;
2474 last if $rule->{type} eq 'group';
2476 if ($line =~ s/^-p (\S+)\s*//) {
2477 $rule->{proto} = $1;
2481 if ($line =~ s/^-dport (\S+)\s*//) {
2482 $rule->{dport} = $1;
2486 if ($line =~ s/^-sport (\S+)\s*//) {
2487 $rule->{sport} = $1;
2490 if ($line =~ s/^-source (\S+)\s*//) {
2491 $rule->{source} = $1;
2494 if ($line =~ s/^-dest (\S+)\s*//) {
2502 die "unable to parse rule parameters
: $line\n" if length($line);
2504 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2505 if ($verbose && $rule->{errors}) {
2506 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2507 foreach my $p (keys %{$rule->{errors}}) {
2508 warn " $p: $rule->{errors
}->{$p}\n";
2515 sub parse_vmfw_option {
2520 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2522 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2525 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2527 $value = $2 ? lc($3) : '';
2528 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2531 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2535 die "can
't parse option '$line'\n"
2538 return ($opt, $value);
2541 sub parse_hostfw_option {
2546 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2548 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2551 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2553 $value = $2 ? lc($3) : '';
2554 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2558 die "can't parse option
'$line'\n"
2561 return ($opt, $value);
2564 sub parse_clusterfw_option {
2569 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2572 if (($value > 1) && ((time() - $value) > 60)) {
2575 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2579 die "can
't parse option '$line'\n"
2582 return ($opt, $value);
2586 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2588 my $alias = lc($cidr);
2589 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2590 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2592 die "no such alias '$cidr'\n" if !$e;;
2594 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2597 sub parse_ip_or_cidr {
2602 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2605 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2609 die "value does not look like a valid IP address or CIDR network\n";
2612 return wantarray ? ($cidr, $ipversion) : $cidr;
2618 # we can add single line comments to the end of the line
2619 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2621 if ($line =~ m/^(\S+)\s(\S+)$/) {
2622 my ($name, $cidr) = ($1, $2);
2625 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2630 ipversion => $ipversion,
2632 $data->{comment} = $comment if $comment;
2639 sub generic_fw_config_parser {
2640 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2645 my $res = $empty_conf;
2647 while (defined(my $line = <$fh>)) {
2648 next if $line =~ m/^#/;
2649 next if $line =~ m/^\s*$/;
2653 my $linenr = $fh->input_line_number();
2654 my $prefix = "$filename (line $linenr)";
2656 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2657 $section = 'options
';
2661 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2662 $section = 'aliases
';
2666 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2667 $section = 'groups
';
2671 die "security group name too long\n" if length($group) > $max_group_name_length;
2672 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2675 ($section, $group, $comment) = undef;
2676 warn "$prefix: $err";
2680 $res->{$section}->{$group} = [];
2681 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2686 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2691 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2696 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2697 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2700 ($section, $group, $comment) = undef;
2701 warn "$prefix: $err";
2705 $res->{$section}->{$group} = [];
2706 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2712 warn "$prefix: skip line - no section\n";
2716 if ($section eq 'options
') {
2719 if ($rule_env eq 'cluster
') {
2720 ($opt, $value) = parse_clusterfw_option($line);
2721 } elsif ($rule_env eq 'host
') {
2722 ($opt, $value) = parse_hostfw_option($line);
2724 ($opt, $value) = parse_vmfw_option($line);
2726 $res->{options}->{$opt} = $value;
2728 warn "$prefix: $@" if $@;
2729 } elsif ($section eq 'aliases
') {
2731 my $data = parse_alias($line);
2732 $res->{aliases}->{lc($data->{name})} = $data;
2734 warn "$prefix: $@" if $@;
2735 } elsif ($section eq 'rules
') {
2737 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2739 warn "$prefix: $err";
2742 push @{$res->{$section}}, $rule;
2743 } elsif ($section eq 'groups
') {
2745 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2747 warn "$prefix: $err";
2750 push @{$res->{$section}->{$group}}, $rule;
2751 } elsif ($section eq 'ipset
') {
2752 # we can add single line comments to the end of the rule
2753 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2755 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2760 if ($nomatch && !$feature_ipset_nomatch) {
2761 $errors->{nomatch} = "nomatch not supported by kernel";
2765 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2766 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2768 $cidr = parse_ip_or_cidr($cidr);
2773 $errors->{cidr} = $err;
2776 my $entry = { cidr => $cidr };
2777 $entry->{nomatch} = 1 if $nomatch;
2778 $entry->{comment} = $comment if $comment;
2779 $entry->{errors} = $errors if $errors;
2781 if ($verbose && $errors) {
2782 warn "$prefix - errors in ipset '$group': $line\n";
2783 foreach my $p (keys %{$errors}) {
2784 warn " $p: $errors->{$p}\n";
2788 push @{$res->{$section}->{$group}}, $entry;
2790 warn "$prefix: skip line - unknown section\n";
2798 sub parse_hostfw_config {
2799 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2801 my $empty_conf = { rules => [], options => {}};
2803 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2806 sub parse_vmfw_config {
2807 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2814 ipset_comments => {},
2817 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2820 sub parse_clusterfw_config {
2821 my ($filename, $fh, $verbose) = @_;
2831 group_comments => {},
2833 ipset_comments => {},
2836 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2840 my ($code, @param) = @_;
2844 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2851 sub read_local_vm_config {
2856 my $vmdata = { qemu => $qemu, lxc => $lxc };
2858 my $vmlist = PVE::Cluster::get_vmlist();
2859 return $vmdata if !$vmlist || !$vmlist->{ids};
2860 my $ids = $vmlist->{ids};
2862 foreach my $vmid (keys %$ids) {
2863 next if !$vmid; # skip VE0
2864 my $d = $ids->{$vmid};
2865 next if !$d->{node} || $d->{node} ne $nodename;
2866 next if !$d->{type};
2867 if ($d->{type} eq 'qemu
') {
2868 if ($have_qemu_server) {
2869 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2870 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2871 $qemu->{$vmid} = $conf;
2874 } elsif ($d->{type} eq 'lxc
') {
2876 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2877 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2878 $lxc->{$vmid} = $conf;
2887 sub load_vmfw_conf {
2888 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2892 $dir = $pvefw_conf_dir if !defined($dir);
2894 my $filename = "$dir/$vmid.fw";
2895 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2896 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2897 $vmfw_conf->{vmid} = $vmid;
2903 my $format_rules = sub {
2904 my ($rules, $allow_iface) = @_;
2908 foreach my $rule (@$rules) {
2909 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2910 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2911 $raw .= uc($rule->{type});
2912 if ($rule->{macro}) {
2913 $raw .= " $rule->{macro}($rule->{action})";
2915 $raw .= " " . $rule->{action};
2917 if ($allow_iface && $rule->{iface}) {
2918 $raw .= " -i $rule->{iface}";
2921 if ($rule->{type} ne 'group
') {
2922 $raw .= " -source $rule->{source}" if $rule->{source};
2923 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2924 $raw .= " -p $rule->{proto}" if $rule->{proto};
2925 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2926 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2929 $raw .= " # " . encode('utf8
', $rule->{comment})
2930 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2933 die "unknown rule type '$rule->{type
}'";
2940 my $format_options = sub {
2945 $raw .= "[OPTIONS]\n\n";
2946 foreach my $opt (keys %$options) {
2947 $raw .= "$opt: $options->{$opt}\n";
2954 my $format_aliases = sub {
2959 $raw .= "[ALIASES]\n\n";
2960 foreach my $k (keys %$aliases) {
2961 my $e = $aliases->{$k};
2962 $raw .= "$e->{name} $e->{cidr}";
2963 $raw .= " # " . encode('utf8
', $e->{comment})
2964 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2972 my $format_ipsets = sub {
2977 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2978 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2979 my $utf8comment = encode('utf8
', $comment);
2980 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2982 $raw .= "[IPSET $ipset]\n\n";
2984 my $options = $fw_conf->{ipset}->{$ipset};
2987 foreach my $entry (@$options) {
2988 $nethash->{$entry->{cidr}} = $entry;
2991 foreach my $cidr (sort keys %$nethash) {
2992 my $entry = $nethash->{$cidr};
2993 my $line = $entry->{nomatch} ? '!' : '';
2994 $line .= $entry->{cidr};
2995 $line .= " # " . encode('utf8
', $entry->{comment})
2996 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
3006 sub save_vmfw_conf {
3007 my ($vmid, $vmfw_conf) = @_;
3011 my $options = $vmfw_conf->{options};
3012 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3014 my $aliases = $vmfw_conf->{aliases};
3015 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3017 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
3019 my $rules = $vmfw_conf->{rules} || [];
3020 if ($rules && scalar(@$rules)) {
3021 $raw .= "[RULES]\n\n";
3022 $raw .= &$format_rules($rules, 1);
3026 my $filename = "$pvefw_conf_dir/$vmid.fw";
3028 mkdir $pvefw_conf_dir;
3029 PVE::Tools::file_set_contents($filename, $raw);
3035 sub remove_vmfw_conf {
3038 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3040 unlink $vmfw_conffile;
3043 sub clone_vmfw_conf {
3044 my ($vmid, $newid) = @_;
3046 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3047 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3049 if (-f $clonevm_conffile) {
3050 unlink $clonevm_conffile;
3052 if (-f $sourcevm_conffile) {
3053 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3054 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3058 sub read_vm_firewall_configs {
3059 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
3061 my $vmfw_configs = {};
3063 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3064 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
3065 next if !$vmfw_conf->{options}; # skip if file does not exists
3066 $vmfw_configs->{$vmid} = $vmfw_conf;
3068 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3069 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
3070 next if !$vmfw_conf->{options}; # skip if file does not exists
3071 $vmfw_configs->{$vmid} = $vmfw_conf;
3074 return $vmfw_configs;
3077 sub get_option_log_level {
3078 my ($options, $k) = @_;
3080 my $v = $options->{$k};
3081 $v = $default_log_level if !defined($v);
3083 return undef if $v eq '' || $v eq 'nolog
';
3085 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3087 return $v if ($v >= 0) && ($v <= 7);
3089 warn "unknown log level ($k = '$v')\n";
3094 sub generate_std_chains {
3095 my ($ruleset, $options, $ipversion) = @_;
3097 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
3099 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
3103 if ($ipversion == 4) {
3104 # same as shorewall smurflog.
3105 $chain = 'PVEFW-smurflog
';
3106 $std_chains->{$chain} = [];
3108 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3109 push @{$std_chains->{$chain}}, "-j DROP";
3112 # same as shorewall logflags action.
3113 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
3114 $chain = 'PVEFW-logflags
';
3115 $std_chains->{$chain} = [];
3117 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
3118 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3119 push @{$std_chains->{$chain}}, "-j DROP";
3121 foreach my $chain (keys %$std_chains) {
3122 ruleset_create_chain($ruleset, $chain);
3123 foreach my $rule (@{$std_chains->{$chain}}) {
3125 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
3127 ruleset_addrule($ruleset, $chain, $rule);
3133 sub generate_ipset_chains {
3134 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
3136 foreach my $ipset (keys %{$ipsets}) {
3138 my $options = $ipsets->{$ipset};
3140 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3141 if (my $ips = $device_ips->{$1}) {
3142 $options = [@$options, @$ips];
3148 foreach my $entry (@$options) {
3149 next if $entry->{errors}; # skip entries with errors
3152 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3153 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3155 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3157 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3159 # ip_compress_address takes an address only, no CIDR
3160 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3161 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3162 $cidr .= $prefix_len if defined($prefix_len);
3168 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3173 foreach my $ipversion (4, 6) {
3174 my $data = $nethash->{$ipversion};
3176 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3178 my $hashsize = scalar(@$options);
3179 if ($hashsize <= 64) {
3182 $hashsize = round_powerof2($hashsize);
3185 my $family = $ipversion == "6" ? "inet6" : "inet";
3187 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3189 foreach my $cidr (sort keys %$data) {
3190 my $entry = $data->{$cidr};
3192 my $cmd = "add $name $cidr";
3193 if ($entry->{nomatch}) {
3194 if ($feature_ipset_nomatch) {
3195 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3197 warn "ignore !$cidr - nomatch not supported by kernel\n";
3200 push @{$ipset_ruleset->{$name}}, $cmd;
3207 sub round_powerof2 {
3211 $int |= $int >> $_ foreach (1,2,4,8,16);
3215 sub load_clusterfw_conf {
3216 my ($filename, $verbose) = @_;
3218 $filename = $clusterfw_conf_filename if !defined($filename);
3220 my $cluster_conf = {};
3221 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3222 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3225 return $cluster_conf;
3228 sub save_clusterfw_conf {
3229 my ($cluster_conf) = @_;
3233 my $options = $cluster_conf->{options};
3234 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3236 my $aliases = $cluster_conf->{aliases};
3237 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3239 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3241 my $rules = $cluster_conf->{rules};
3242 if ($rules && scalar(@$rules)) {
3243 $raw .= "[RULES]\n\n";
3244 $raw .= &$format_rules($rules, 1);
3248 if ($cluster_conf->{groups}) {
3249 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3250 my $rules = $cluster_conf->{groups}->{$group};
3251 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3252 my $utf8comment = encode('utf8
', $comment);
3253 $raw .= "[group $group] # $utf8comment\n\n";
3255 $raw .= "[group $group]\n\n";
3258 $raw .= &$format_rules($rules, 0);
3264 mkdir $pvefw_conf_dir;
3265 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3267 unlink $clusterfw_conf_filename;
3271 sub load_hostfw_conf {
3272 my ($cluster_conf, $filename, $verbose) = @_;
3274 $filename = $hostfw_conf_filename if !defined($filename);
3276 my $hostfw_conf = {};
3277 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3278 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3280 return $hostfw_conf;
3283 sub save_hostfw_conf {
3284 my ($hostfw_conf) = @_;
3288 my $options = $hostfw_conf->{options};
3289 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3291 my $rules = $hostfw_conf->{rules};
3292 if ($rules && scalar(@$rules)) {
3293 $raw .= "[RULES]\n\n";
3294 $raw .= &$format_rules($rules, 1);
3299 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3301 unlink $hostfw_conf_filename;
3306 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3310 if ($vmdata) { # test mode
3311 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3312 my $filename = "$testdir/cluster.fw";
3313 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3315 $filename = "$testdir/host.fw";
3316 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3318 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3319 } else { # normal operation
3320 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3322 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3324 $vmdata = read_local_vm_config();
3325 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3328 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3331 if ($cluster_conf->{aliases}->{local_network}) {
3332 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3335 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3337 $cluster_conf->{aliases}->{local_network} = {
3338 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3341 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3343 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3344 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3345 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3347 return ($ruleset, $ipset_ruleset, $rulesetv6);
3350 sub compile_iptables_filter {
3351 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3355 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3356 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3358 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3360 my $hostfw_options = $hostfw_conf->{options} || {};
3362 # fixme: what log level should we use here?
3363 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3365 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3367 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3368 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3370 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3372 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3373 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3375 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3377 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3379 if ($hostfw_enable) {
3380 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3381 warn $@ if $@; # just to be sure - should not happen
3384 # generate firewall rules for QEMU VMs
3385 foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
3387 my $conf = $vmdata->{qemu}->{$vmid};
3388 my $vmfw_conf = $vmfw_configs->{$vmid};
3389 return if !$vmfw_conf;
3391 foreach my $netid (sort keys %$conf) {
3392 next if $netid !~ m/^net(\d+)$/;
3393 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3394 next if !$net->{firewall};
3395 my $iface = "tap${vmid}i$1";
3397 my $macaddr = $net->{macaddr};
3398 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3399 $vmfw_conf, $vmid, 'IN
', $ipversion);
3400 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3401 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3404 warn $@ if $@; # just to be sure - should not happen
3407 # generate firewall rules for LXC containers
3408 foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
3410 my $conf = $vmdata->{lxc}->{$vmid};
3411 my $vmfw_conf = $vmfw_configs->{$vmid};
3412 return if !$vmfw_conf;
3414 if ($vmfw_conf->{options}->{enable}) {
3415 foreach my $netid (sort keys %$conf) {
3416 next if $netid !~ m/^net(\d+)$/;
3417 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3418 next if !$net->{firewall};
3419 my $iface = "veth${vmid}i$1";
3420 my $macaddr = $net->{hwaddr};
3421 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3422 $vmfw_conf, $vmid, 'IN
', $ipversion);
3423 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3424 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3428 warn $@ if $@; # just to be sure - should not happen
3431 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3432 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3438 sub mac_to_linklocal {
3440 my @parts = split(/:/, $macaddr);
3441 # The standard link local address uses the fe80::/64 prefix with the
3442 # modified EUI-64 identifier derived from the MAC address by flipping the
3443 # universal/local bit and inserting FF:FE in the middle.
3445 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3446 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3447 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3450 sub compile_ipsets {
3451 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3454 if ($cluster_conf->{aliases}->{local_network}) {
3455 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3458 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3460 $cluster_conf->{aliases}->{local_network} = {
3461 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3464 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3467 my $ipset_ruleset = {};
3469 # generate ipsets for QEMU VMs
3470 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3472 my $conf = $vmdata->{qemu}->{$vmid};
3473 my $vmfw_conf = $vmfw_configs->{$vmid};
3474 return if !$vmfw_conf;
3476 # When the 'ipfilter
' option is enabled every device for which there
3477 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3479 # The reason is that ipfilter ipsets are always filled with standard
3480 # IPv6 link-local filters.
3481 my $ipsets = $vmfw_conf->{ipset};
3482 my $implicit_sets = {};
3484 my $device_ips = {};
3485 foreach my $netid (keys %$conf) {
3486 next if $netid !~ m/^net(\d+)$/;
3487 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3488 next if !$net->{firewall};
3490 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3491 $implicit_sets->{"ipfilter-$netid"} = [];
3494 my $macaddr = $net->{macaddr};
3495 my $linklocal = mac_to_linklocal($macaddr);
3496 $device_ips->{$netid} = [
3497 { cidr => $linklocal },
3498 { cidr => 'fe80
::/10', nomatch => 1 }
3502 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3503 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3505 warn $@ if $@; # just to be sure - should not happen
3508 # generate firewall rules for LXC containers
3509 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3511 my $conf = $vmdata->{lxc}->{$vmid};
3512 my $vmfw_conf = $vmfw_configs->{$vmid};
3513 return if !$vmfw_conf;
3515 # When the 'ipfilter
' option is enabled every device for which there
3516 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3518 # The reason is that ipfilter ipsets are always filled with standard
3519 # IPv6 link-local filters, as well as the IP addresses configured
3520 # for the container.
3521 my $ipsets = $vmfw_conf->{ipset};
3522 my $implicit_sets = {};
3524 my $device_ips = {};
3525 foreach my $netid (keys %$conf) {
3526 next if $netid !~ m/^net(\d+)$/;
3527 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3528 next if !$net->{firewall};
3530 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3531 $implicit_sets->{"ipfilter-$netid"} = [];
3534 my $macaddr = $net->{hwaddr};
3535 my $linklocal = mac_to_linklocal($macaddr);
3536 my $set = $device_ips->{$netid} = [
3537 { cidr => $linklocal },
3538 { cidr => 'fe80
::/10', nomatch => 1 }
3540 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3541 push @$set, { cidr => $1 };
3543 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3544 push @$set, { cidr => $1 };
3548 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3549 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3551 warn $@ if $@; # just to be sure - should not happen
3554 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3556 return $ipset_ruleset;
3559 sub get_ruleset_status {
3560 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3562 my $statushash = {};
3564 foreach my $chain (sort keys %$ruleset) {
3565 my $sig = &$digest_fn($ruleset->{$chain});
3567 $statushash->{$chain}->{sig} = $sig;
3569 my $oldsig = $active_chains->{$chain};
3570 if (!defined($oldsig)) {
3571 $statushash->{$chain}->{action} = 'create
';
3573 if ($oldsig eq $sig) {
3574 $statushash->{$chain}->{action} = 'exists';
3576 $statushash->{$chain}->{action} = 'update
';
3579 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3580 foreach my $cmd (@{$ruleset->{$chain}}) {
3581 print "\t$cmd\n" if $verbose;
3585 foreach my $chain (sort keys %$active_chains) {
3586 if (!defined($ruleset->{$chain})) {
3587 my $sig = $active_chains->{$chain};
3588 $statushash->{$chain}->{action} = 'delete';
3589 $statushash->{$chain}->{sig} = $sig;
3590 print "delete $chain ($sig)\n" if $verbose;
3597 sub print_sig_rule {
3598 my ($chain, $sig) = @_;
3600 # We just use this to store a SHA1 checksum used to detect changes
3601 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3604 sub get_ruleset_cmdlist {
3605 my ($ruleset, $verbose, $iptablescmd) = @_;
3607 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3609 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3610 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3612 # create missing chains first
3613 foreach my $chain (sort keys %$ruleset) {
3614 my $stat = $statushash->{$chain};
3615 die "internal error" if !$stat;
3616 next if $stat->{action} ne 'create
';
3618 $cmdlist .= ":$chain - [0:0]\n";
3621 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3622 my $chain = "PVEFW-$h";
3623 if ($ruleset->{$chain} && !$hooks->{$h}) {
3624 $cmdlist .= "-A $h -j $chain\n";
3628 foreach my $chain (sort keys %$ruleset) {
3629 my $stat = $statushash->{$chain};
3630 die "internal error" if !$stat;
3632 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3633 $cmdlist .= "-F $chain\n";
3634 foreach my $cmd (@{$ruleset->{$chain}}) {
3635 $cmdlist .= "$cmd\n";
3637 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3638 } elsif ($stat->{action
} eq 'delete') {
3639 die "internal error"; # this should not happen
3640 } elsif ($stat->{action
} eq 'exists') {
3643 die "internal error - unknown status '$stat->{action}'";
3647 foreach my $chain (keys %$statushash) {
3648 next if $statushash->{$chain}->{action
} ne 'delete';
3649 $cmdlist .= "-F $chain\n";
3651 foreach my $chain (keys %$statushash) {
3652 next if $statushash->{$chain}->{action
} ne 'delete';
3653 next if $chain eq 'PVEFW-INPUT';
3654 next if $chain eq 'PVEFW-OUTPUT';
3655 next if $chain eq 'PVEFW-FORWARD';
3656 $cmdlist .= "-X $chain\n";
3659 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3661 $cmdlist .= "COMMIT\n";
3663 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3666 sub get_ipset_cmdlist
{
3667 my ($ruleset, $verbose) = @_;
3671 my $delete_cmdlist = "";
3673 my $active_chains = ipset_get_chains
();
3674 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3676 # remove stale _swap chains
3677 foreach my $chain (keys %$active_chains) {
3678 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3679 $cmdlist .= "destroy $chain\n";
3683 foreach my $chain (keys %$ruleset) {
3684 my $stat = $statushash->{$chain};
3685 die "internal error" if !$stat;
3687 if ($stat->{action
} eq 'create') {
3688 foreach my $cmd (@{$ruleset->{$chain}}) {
3689 $cmdlist .= "$cmd\n";
3694 foreach my $chain (keys %$ruleset) {
3695 my $stat = $statushash->{$chain};
3696 die "internal error" if !$stat;
3698 if ($stat->{action
} eq 'update') {
3699 my $chain_swap = $chain."_swap";
3701 foreach my $cmd (@{$ruleset->{$chain}}) {
3702 $cmd =~ s/$chain/$chain_swap/;
3703 $cmdlist .= "$cmd\n";
3705 $cmdlist .= "swap $chain_swap $chain\n";
3706 $cmdlist .= "flush $chain_swap\n";
3707 $cmdlist .= "destroy $chain_swap\n";
3711 # the remove unused chains
3712 foreach my $chain (keys %$statushash) {
3713 next if $statushash->{$chain}->{action
} ne 'delete';
3715 $delete_cmdlist .= "flush $chain\n";
3716 $delete_cmdlist .= "destroy $chain\n";
3719 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3721 return ($cmdlist, $delete_cmdlist, $changes);
3725 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3727 enable_bridge_firewall
();
3729 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3730 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3732 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3733 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3736 if ($ipset_changes) {
3737 print "ipset changes:\n";
3738 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3739 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3743 print "iptables changes:\n";
3748 print "ip6tables changes:\n";
3753 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3754 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3756 ipset_restore_cmdlist
($ipset_create_cmdlist);
3758 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3759 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3761 iptables_restore_cmdlist
($cmdlist);
3763 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3764 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3766 ip6tables_restore_cmdlist
($cmdlistv6);
3768 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3769 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3771 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3773 # test: re-read status and check if everything is up to date
3774 my $active_chains = iptables_get_chains
();
3775 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3778 foreach my $chain (sort keys %$ruleset) {
3779 my $stat = $statushash->{$chain};
3780 if ($stat->{action
} ne 'exists') {
3781 warn "unable to update chain '$chain'\n";
3786 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3787 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3789 foreach my $chain (sort keys %$rulesetv6) {
3790 my $stat = $statushashv6->{$chain};
3791 if ($stat->{action
} ne 'exists') {
3792 warn "unable to update chain '$chain'\n";
3797 die "unable to apply firewall changes\n" if $errors;
3799 update_nf_conntrack_max
($hostfw_conf);
3801 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3805 sub update_nf_conntrack_max
{
3806 my ($hostfw_conf) = @_;
3808 my $max = 65536; # reasonable default
3810 my $options = $hostfw_conf->{options
} || {};
3812 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3813 $max = $options->{nf_conntrack_max
};
3814 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3817 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3818 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3820 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3822 if ($current != $max) {
3823 my $hashsize = int($max/4);
3824 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3825 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3829 sub update_nf_conntrack_tcp_timeout_established
{
3830 my ($hostfw_conf) = @_;
3832 my $options = $hostfw_conf->{options
} || {};
3834 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3836 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3839 sub remove_pvefw_chains
{
3841 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3842 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3843 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3847 sub remove_pvefw_chains_iptables
{
3848 my ($iptablescmd) = @_;
3850 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3851 my $cmdlist = "*filter\n";
3853 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3855 $cmdlist .= "-D $h -j PVEFW-$h\n";
3859 foreach my $chain (keys %$chash) {
3860 $cmdlist .= "-F $chain\n";
3863 foreach my $chain (keys %$chash) {
3864 $cmdlist .= "-X $chain\n";
3866 $cmdlist .= "COMMIT\n";
3868 if($iptablescmd eq "ip6tables") {
3869 ip6tables_restore_cmdlist
($cmdlist);
3871 iptables_restore_cmdlist
($cmdlist);
3875 sub remove_pvefw_chains_ipset
{
3877 my $ipset_chains = ipset_get_chains
();
3881 foreach my $chain (keys %$ipset_chains) {
3882 $cmdlist .= "flush $chain\n";
3883 $cmdlist .= "destroy $chain\n";
3886 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3890 my $cluster_conf = load_clusterfw_conf
();
3891 my $cluster_options = $cluster_conf->{options
};
3892 my $enable = $cluster_options->{enable
};
3896 # load required modules here
3902 my $cluster_conf = load_clusterfw_conf
();
3903 my $cluster_options = $cluster_conf->{options
};
3905 if (!$cluster_options->{enable
}) {
3906 PVE
::Firewall
::remove_pvefw_chains
();
3910 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3912 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3914 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);