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);
21 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
23 use Storable
qw(dclone);
25 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
26 my $pvefw_conf_dir = "/etc/pve/firewall";
27 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
29 # dynamically include PVE::QemuServer and PVE::LXC
30 # to avoid dependency problems
33 require PVE
::QemuServer
;
34 require PVE
::QemuConfig
;
35 $have_qemu_server = 1;
45 my $pve_fw_status_dir = "/var/lib/pve-firewall";
47 mkdir $pve_fw_status_dir; # make sure this exists
49 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
50 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
51 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
53 my $max_alias_name_length = 64;
54 my $max_ipset_name_length = 64;
55 my $max_group_name_length = 18;
57 my $PROTOCOLS_WITH_PORTS = {
59 udplite
=> 1, 136 => 1,
65 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
66 sub pve_verify_ip_or_cidr
{
67 my ($cidr, $noerr) = @_;
69 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
70 return $cidr if Net
::IP-
>new($cidr);
71 return undef if $noerr;
72 die Net
::IP
::Error
() . "\n";
74 return undef if $noerr;
75 die "value does not look like a valid IP address or CIDR network\n";
78 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
79 sub pve_verify_ip_or_cidr_or_alias
{
80 my ($cidr, $noerr) = @_;
82 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
84 return pve_verify_ip_or_cidr
($cidr, $noerr);
87 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
88 description
=> "IP set name.",
90 pattern
=> $ipset_name_pattern,
92 maxLength
=> $max_ipset_name_length,
95 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
96 description
=> "Alias name.",
98 pattern
=> $ip_alias_pattern,
100 maxLength
=> $max_alias_name_length,
103 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
104 description
=> "Log level.",
106 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
110 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
111 description
=> "Security Group name.",
113 pattern
=> $security_group_name_pattern,
115 maxLength
=> $max_group_name_length,
118 my $feature_ipset_nomatch = 0;
120 my (undef, undef, $release) = POSIX
::uname
();
121 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
122 my ($major, $minor) = ($1, $2);
123 $feature_ipset_nomatch = 1 if ($major > 3) ||
124 ($major == 3 && $minor >= 7);
129 my $nodename = PVE
::INotify
::nodename
();
131 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
133 my $default_log_level = 'nolog'; # avoid logs by default
135 my $log_level_hash = {
153 # log => optional, loglevel
154 # logmsg => optional, logmsg - overwrites default
157 # match => optional, overwrites generation of match
158 # target => optional, overwrites action
160 # we need to overwrite some macros for ipv6
161 my $pve_ipv6fw_macros = {
163 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
165 'NeighborDiscovery' => [
166 "IPv6 neighbor solicitation, neighbor and router advertisement",
167 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-solicitation' },
168 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-advertisement' },
169 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-solicitation' },
170 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-advertisement' },
174 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
177 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
178 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
182 # imported/converted from: /usr/share/shorewall/macro.*
183 my $pve_fw_macros = {
186 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
187 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
190 "Auth (identd) traffic",
191 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
194 "Border Gateway Protocol traffic",
195 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
198 "BitTorrent traffic for BitTorrent 3.1 and earlier",
199 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
200 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
203 "BitTorrent traffic for BitTorrent 3.2 and later",
204 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
205 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
208 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
209 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6789' },
210 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6800:7300' },
213 "Concurrent Versions System pserver traffic",
214 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
217 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
218 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
219 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
220 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
223 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
224 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
225 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
228 "Distributed Checksum Clearinghouse spam filtering mechanism",
229 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
232 "Forwarded DHCP traffic",
233 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
236 "Domain Name System traffic (upd and tcp)",
237 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
241 "Distributed Compiler service",
242 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
245 "File Transfer Protocol",
246 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
249 "Finger protocol (RFC 742)",
250 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
253 "GNUnet secure peer-to-peer networking traffic",
254 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
255 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
256 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
257 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
260 "Generic Routing Encapsulation tunneling protocol",
261 { action
=> 'PARAM', proto
=> '47' },
264 "Git distributed revision control traffic",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
268 "OpenPGP HTTP keyserver protocol traffic",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
272 "Hypertext Transfer Protocol (WWW)",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
276 "Hypertext Transfer Protocol (WWW) over SSL",
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
280 "Internet Cache Protocol V2 (Squid) traffic",
281 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
284 "AOL Instant Messenger traffic",
285 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
288 "Internet Message Access Protocol",
289 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
292 "Internet Message Access Protocol over SSL",
293 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
296 "IPIP capsulation traffic",
297 { action
=> 'PARAM', proto
=> '94' },
301 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
302 { action
=> 'PARAM', proto
=> '50' },
305 "IPsec authentication (AH) traffic",
306 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
307 { action
=> 'PARAM', proto
=> '51' },
310 "IPsec traffic and Nat-Traversal",
311 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
312 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
313 { action
=> 'PARAM', proto
=> '50' },
316 "Internet Relay Chat traffic",
317 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
320 "HP Jetdirect printing",
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
324 "Layer 2 Tunneling Protocol traffic",
325 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
328 "Lightweight Directory Access Protocol traffic",
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
332 "Secure Lightweight Directory Access Protocol traffic",
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
336 "Microsoft Notification Protocol",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
340 "Microsoft SQL Server",
341 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
344 "Mail traffic (SMTP, SMTPS, Submission)",
345 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
346 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
347 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
351 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5353' },
354 "Munin networked resource monitoring traffic",
355 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
359 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
362 "NNTP traffic (Usenet).",
363 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
366 "Encrypted NNTP traffic (Usenet)",
367 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
370 "Network Time Protocol (ntpd)",
371 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
374 "OSPF multicast traffic",
375 { action
=> 'PARAM', proto
=> '89' },
379 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
382 "Symantec PCAnywere (tm)",
383 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
384 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
388 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
391 "Encrypted POP3 traffic",
392 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
395 "Point-to-Point Tunneling Protocol",
396 { action
=> 'PARAM', proto
=> '47' },
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
401 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
408 "Line Printer protocol printing",
409 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
412 "Microsoft Remote Desktop Protocol traffic",
413 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
416 "Routing Information Protocol (bidirectional)",
417 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
420 "BIND remote management protocol",
421 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
424 "Razor Antispam System",
425 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
428 "Remote time retrieval (rdate)",
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
436 "SANE network scanning",
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
440 "Microsoft SMB traffic",
441 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
442 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
443 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
444 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
447 "Samba Web Administration Tool",
448 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
451 "Simple Mail Transfer Protocol",
452 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
455 "Encrypted Simple Mail Transfer Protocol",
456 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
459 "Simple Network Management Protocol",
460 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
461 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
464 "Spam Assassin SPAMD traffic",
465 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
468 "Secure shell traffic",
469 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
472 "Subversion server (svnserve)",
473 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
476 "SixXS IPv6 Deployment and Tunnel Broker",
477 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
478 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
479 { action
=> 'PARAM', proto
=> '41' },
480 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
483 "Squid web proxy traffic",
484 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
487 "Mail message submission traffic",
488 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
491 "Syslog protocol (RFC 5424) traffic",
492 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
493 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
496 "Trivial File Transfer Protocol traffic",
497 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
501 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
505 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
508 "RFC 868 Time protocol",
509 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
512 "Traceroute (for up to 30 hops) traffic",
513 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
514 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
517 "VNC traffic for VNC display's 0 - 99",
518 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
521 "VNC traffic from Vncservers to Vncviewers in listen mode",
522 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
525 "WWW traffic (HTTP and HTTPS)",
526 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
527 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
530 "Web Cache/Proxy traffic (port 8080)",
531 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
535 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
538 "Whois (nicname, RFC 3912) traffic",
539 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
543 my $pve_fw_parsed_macros;
544 my $pve_fw_macro_descr;
545 my $pve_fw_macro_ipversion = {};
546 my $pve_fw_preferred_macro_names = {};
548 my $FWACCEPTMARK_ON = "0x80000000/0x80000000";
549 my $FWACCEPTMARK_OFF = "0x00000000/0x80000000";
551 my $pve_std_chains = {};
552 my $pve_std_chains_conf = {};
553 $pve_std_chains_conf->{4} = {
554 'PVEFW-SET-ACCEPT-MARK' => [
555 { target
=> "-j MARK --set-mark $FWACCEPTMARK_ON" },
557 'PVEFW-DropBroadcast' => [
558 # same as shorewall 'Broadcast'
559 # simply DROP BROADCAST/MULTICAST/ANYCAST
560 # we can use this to reduce logging
561 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
562 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
563 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
564 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
567 # same as shorewall 'reject'
568 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
569 { action
=> 'DROP', source
=> '224.0.0.0/4' },
570 { action
=> 'DROP', proto
=> 'icmp' },
571 { match
=> '-p tcp', target
=> '-j REJECT --reject-with tcp-reset' },
572 { match
=> '-p udp', target
=> '-j REJECT --reject-with icmp-port-unreachable' },
573 { match
=> '-p icmp', target
=> '-j REJECT --reject-with icmp-host-unreachable' },
574 { target
=> '-j REJECT --reject-with icmp-host-prohibited' },
577 # same as shorewall 'Drop', which is equal to DROP,
578 # but REJECT/DROP some packages to reduce logging,
579 # and ACCEPT critical ICMP types
580 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
581 # we are not interested in BROADCAST/MULTICAST/ANYCAST
582 { action
=> 'PVEFW-DropBroadcast' },
583 # ACCEPT critical ICMP types
584 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
585 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
586 # Drop packets with INVALID state
587 { action
=> 'DROP', match
=> '-m conntrack --ctstate INVALID', },
588 # Drop Microsoft SMB noise
589 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445' },
590 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139' },
591 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
592 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445' },
593 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
594 # Drop new/NotSyn traffic so that it doesn't get logged
595 { action
=> 'DROP', match
=> '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
597 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
600 # same as shorewall 'Reject', which is equal to Reject,
601 # but REJECT/DROP some packages to reduce logging,
602 # and ACCEPT critical ICMP types
603 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
604 # we are not interested in BROADCAST/MULTICAST/ANYCAST
605 { action
=> 'PVEFW-DropBroadcast' },
606 # ACCEPT critical ICMP types
607 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
608 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
609 # Drop packets with INVALID state
610 { action
=> 'DROP', match
=> '-m conntrack --ctstate INVALID', },
611 # Drop Microsoft SMB noise
612 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445' },
613 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
614 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
615 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445' },
616 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
617 # Drop new/NotSyn traffic so that it doesn't get logged
618 { action
=> 'DROP', match
=> '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
620 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
622 'PVEFW-tcpflags' => [
623 # same as shorewall tcpflags action.
624 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
625 { match
=> '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG', target
=> '-g PVEFW-logflags' },
626 { match
=> '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE', target
=> '-g PVEFW-logflags' },
627 { match
=> '-p tcp -m tcp --tcp-flags SYN,RST SYN,RST', target
=> '-g PVEFW-logflags' },
628 { match
=> '-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN', target
=> '-g PVEFW-logflags' },
629 { match
=> '-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN', target
=> '-g PVEFW-logflags' },
632 # same as shorewall smurfs action
633 # Filter packets for smurfs (packets with a broadcast address as the source).
634 { match
=> '-s 0.0.0.0/32', target
=> '-j RETURN' }, # allow DHCP
635 { match
=> '-m addrtype --src-type BROADCAST', target
=> '-g PVEFW-smurflog' },
636 { match
=> '-s 224.0.0.0/4', target
=> '-g PVEFW-smurflog' },
638 'PVEFW-smurflog' => [
639 { action
=> 'DROP', logmsg
=> 'DROP: ' },
641 'PVEFW-logflags' => [
642 { action
=> 'DROP', logmsg
=> 'DROP: ' },
646 $pve_std_chains_conf->{6} = {
647 'PVEFW-SET-ACCEPT-MARK' => [
648 { target
=> "-j MARK --set-mark $FWACCEPTMARK_ON" },
650 'PVEFW-DropBroadcast' => [
651 # same as shorewall 'Broadcast'
652 # simply DROP BROADCAST/MULTICAST/ANYCAST
653 # we can use this to reduce logging
654 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
655 # ipv6 addrtype does not work with kernel 2.6.32
656 #{ action => 'DROP', dsttype => 'MULTICAST' },
657 #{ action => 'DROP', dsttype => 'ANYCAST' },
658 { action
=> 'DROP', dest
=> 'ff00::/8' },
659 #{ action => 'DROP', dest => '224.0.0.0/4' },
662 # same as shorewall 'reject'
663 #{ action => 'DROP', dsttype => 'BROADCAST' },
664 #{ action => 'DROP', source => '224.0.0.0/4' },
665 { action
=> 'DROP', proto
=> 'icmpv6' },
666 { match
=> '-p tcp', target
=> '-j REJECT --reject-with tcp-reset' },
667 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
668 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
669 #"-j REJECT --reject-with icmp-host-prohibited",
672 # same as shorewall 'Drop', which is equal to DROP,
673 # but REJECT/DROP some packages to reduce logging,
674 # and ACCEPT critical ICMP types
675 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
676 # we are not interested in BROADCAST/MULTICAST/ANYCAST
677 { action
=> 'PVEFW-DropBroadcast' },
678 # ACCEPT critical ICMP types
679 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
680 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
681 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
682 # Drop packets with INVALID state
683 { action
=> 'DROP', match
=> '-m conntrack --ctstate INVALID', },
684 # Drop Microsoft SMB noise
685 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445' },
686 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
687 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
688 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445' },
689 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
690 # Drop new/NotSyn traffic so that it doesn't get logged
691 { action
=> 'DROP', match
=> '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
693 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
696 # same as shorewall 'Reject', which is equal to Reject,
697 # but REJECT/DROP some packages to reduce logging,
698 # and ACCEPT critical ICMP types
699 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
700 # we are not interested in BROADCAST/MULTICAST/ANYCAST
701 { action
=> 'PVEFW-DropBroadcast' },
702 # ACCEPT critical ICMP types
703 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
704 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
705 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
706 # Drop packets with INVALID state
707 { action
=> 'DROP', match
=> '-m conntrack --ctstate INVALID', },
708 # Drop Microsoft SMB noise
709 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445' },
710 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139' },
711 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
712 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445' },
713 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
714 # Drop new/NotSyn traffic so that it doesn't get logged
715 { action
=> 'DROP', match
=> '-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN' },
717 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
719 'PVEFW-tcpflags' => [
720 # same as shorewall tcpflags action.
721 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
722 { match
=> '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG', target
=> '-g PVEFW-logflags' },
723 { match
=> '-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE', target
=> '-g PVEFW-logflags' },
724 { match
=> '-p tcp -m tcp --tcp-flags SYN,RST SYN,RST', target
=> '-g PVEFW-logflags' },
725 { match
=> '-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN', target
=> '-g PVEFW-logflags' },
726 { match
=> '-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN', target
=> '-g PVEFW-logflags' },
728 'PVEFW-logflags' => [
729 { action
=> 'DROP', logmsg
=> 'DROP: ' },
733 # iptables -p icmp -h
734 my $icmp_type_names = {
737 'destination-unreachable' => 1,
738 'network-unreachable' => 1,
739 'host-unreachable' => 1,
740 'protocol-unreachable' => 1,
741 'port-unreachable' => 1,
742 'fragmentation-needed' => 1,
743 'source-route-failed' => 1,
744 'network-unknown' => 1,
746 'network-prohibited' => 1,
747 'host-prohibited' => 1,
748 'TOS-network-unreachable' => 1,
749 'TOS-host-unreachable' => 1,
750 'communication-prohibited' => 1,
751 'host-precedence-violation' => 1,
752 'precedence-cutoff' => 1,
753 'source-quench' => 1,
755 'network-redirect' => 1,
756 'host-redirect' => 1,
757 'TOS-network-redirect' => 1,
758 'TOS-host-redirect' => 1,
760 'router-advertisement' => 1,
761 'router-solicitation' => 1,
762 'time-exceeded' => 1,
763 'ttl-zero-during-transit' => 1,
764 'ttl-zero-during-reassembly' => 1,
765 'parameter-problem' => 1,
766 'ip-header-bad' => 1,
767 'required-option-missing' => 1,
768 'timestamp-request' => 1,
769 'timestamp-reply' => 1,
770 'address-mask-request' => 1,
771 'address-mask-reply' => 1,
774 # ip6tables -p icmpv6 -h
776 my $icmpv6_type_names = {
778 'destination-unreachable' => 1,
780 'communication-prohibited' => 1,
781 'address-unreachable' => 1,
782 'port-unreachable' => 1,
783 'packet-too-big' => 1,
784 'time-exceeded' => 1,
785 'ttl-zero-during-transit' => 1,
786 'ttl-zero-during-reassembly' => 1,
787 'parameter-problem' => 1,
789 'unknown-header-type' => 1,
790 'unknown-option' => 1,
793 'router-solicitation' => 1,
794 'router-advertisement' => 1,
795 'neighbor-solicitation' => 1,
796 'neighbour-solicitation' => 1,
797 'neighbor-advertisement' => 1,
798 'neighbour-advertisement' => 1,
802 sub init_firewall_macros
{
804 $pve_fw_parsed_macros = {};
807 my ($k, $macro) = @_;
808 my $lc_name = lc($k);
809 $pve_fw_macro_ipversion->{$k} = 0;
810 while (!ref($macro->[0])) {
811 my $desc = shift @$macro;
812 if ($desc eq 'ipv4only') {
813 $pve_fw_macro_ipversion->{$k} = 4;
814 } elsif ($desc eq 'ipv6only') {
815 $pve_fw_macro_ipversion->{$k} = 6;
817 $pve_fw_macro_descr->{$k} = $desc;
820 $pve_fw_preferred_macro_names->{$lc_name} = $k;
821 $pve_fw_parsed_macros->{$k} = $macro;
824 foreach my $k (keys %$pve_fw_macros) {
825 &$parse($k, $pve_fw_macros->{$k});
828 foreach my $k (keys %$pve_ipv6fw_macros) {
829 next if $pve_fw_parsed_macros->{$k};
830 &$parse($k, $pve_ipv6fw_macros->{$k});
831 $pve_fw_macro_ipversion->{$k} = 6;
835 init_firewall_macros
();
838 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
843 sub get_etc_services
{
845 return $etc_services if $etc_services;
847 my $filename = "/etc/services";
849 my $fh = IO
::File-
>new($filename, O_RDONLY
);
851 warn "unable to read '$filename' - $!\n";
857 while (my $line = <$fh>) {
859 next if $line =~m/^#/;
860 next if ($line =~m/^\s*$/);
862 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
863 $services->{byid
}->{$2}->{name
} = $1;
864 $services->{byid
}->{$2}->{port
} = $2;
865 $services->{byid
}->{$2}->{$3} = 1;
866 $services->{byname
}->{$1} = $services->{byid
}->{$2};
872 $etc_services = $services;
875 return $etc_services;
880 sub get_etc_protocols
{
881 return $etc_protocols if $etc_protocols;
883 my $filename = "/etc/protocols";
885 my $fh = IO
::File-
>new($filename, O_RDONLY
);
887 warn "unable to read '$filename' - $!\n";
893 while (my $line = <$fh>) {
895 next if $line =~m/^#/;
896 next if ($line =~m/^\s*$/);
898 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
899 $protocols->{byid
}->{$2}->{name
} = $1;
900 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
906 # add special case for ICMP v6
907 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
908 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
910 $etc_protocols = $protocols;
912 return $etc_protocols;
918 my ($new_value) = @_;
920 $__local_network = $new_value if defined($new_value);
922 return $__local_network if defined($__local_network);
925 my $nodename = PVE
::INotify
::nodename
();
927 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
929 my $testip = Net
::IP-
>new($ip);
931 my $isv6 = $testip->version == 6;
932 my $routes = $isv6 ? PVE
::ProcFSTools
::read_proc_net_ipv6_route
()
933 : PVE
::ProcFSTools
::read_proc_net_route
();
934 foreach my $entry (@$routes) {
937 $mask = $entry->{prefix
};
938 next if !$mask; # skip the default route...
940 $mask = $PVE::Network
::ipv4_mask_hash_localnet-
>{$entry->{mask
}};
941 next if !defined($mask);
943 my $cidr = "$entry->{dest}/$mask";
944 my $testnet = Net
::IP-
>new($cidr);
945 my $overlap = $testnet->overlaps($testip);
946 if ($overlap == $Net::IP
::IP_B_IN_A_OVERLAP
||
947 $overlap == $Net::IP
::IP_IDENTICAL
)
949 $__local_network = $cidr;
956 return $__local_network;
959 # ipset names are limited to 31 characters,
960 # and we use '-v4' or '-v6' to indicate IP versions,
961 # and we use '_swap' suffix for atomic update,
962 # for example PVEFW-${VMID}-${ipset_name}_swap
964 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
966 sub compute_ipset_chain_name
{
967 my ($vmid, $ipset_name, $ipversion) = @_;
969 $vmid = 0 if !defined($vmid);
971 my $id = "$vmid-${ipset_name}-v$ipversion";
973 if (length($id) > $max_iptables_ipset_name_length) {
974 $id = PVE
::Tools
::fnv31a_hex
($id);
980 sub compute_ipfilter_ipset_name
{
983 return "ipfilter-$iface";
986 sub parse_address_list
{
989 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
990 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
994 if ($str =~ m/^${ip_alias_pattern}$/) {
995 die "alias name too long\n" if length($str) > $max_alias_name_length;
1003 my @elements = split(/,/, $str);
1004 die "extraneous commas in list\n" if $str ne join(',', @elements);
1005 foreach my $elem (@elements) {
1007 my $ip = Net
::IP-
>new($elem);
1009 my $err = Net
::IP
::Error
();
1010 die "invalid IP address: $err\n";
1012 $iprange = 1 if $elem =~ m/-/;
1014 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
1016 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
1017 if $ipversion && ($new_ipversion != $ipversion);
1019 $ipversion = $new_ipversion;
1022 die "you can't use a range in a list\n" if $iprange && $count > 1;
1027 sub parse_port_name_number_or_range
{
1028 my ($str, $dport) = @_;
1030 my $services = PVE
::Firewall
::get_etc_services
();
1034 my @elements = split(/,/, $str);
1035 die "extraneous commas in list\n" if $str ne join(',', @elements);
1036 foreach my $item (@elements) {
1038 if ($item =~ m/^(\d+):(\d+)$/) {
1039 my ($port1, $port2) = ($1, $2);
1040 die "invalid port '$port1'\n" if $port1 > 65535;
1041 die "invalid port '$port2'\n" if $port2 > 65535;
1042 } elsif ($item =~ m/^(\d+)$/) {
1044 die "invalid port '$port'\n" if $port > 65535;
1046 if ($dport && $icmp_type_names->{$item}) {
1048 } elsif ($dport && $icmpv6_type_names->{$item}) {
1051 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1056 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1061 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1062 sub pve_fw_verify_sport_spec
{
1065 parse_port_name_number_or_range
($portstr, 0);
1070 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1071 sub pve_fw_verify_dport_spec
{
1074 parse_port_name_number_or_range
($portstr, 1);
1079 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1080 sub pve_fw_verify_addr_spec
{
1083 parse_address_list
($list);
1088 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1089 sub pve_fw_verify_protocol_spec
{
1092 my $protocols = get_etc_protocols
();
1094 die "unknown protocol '$proto'\n" if $proto &&
1095 !(defined($protocols->{byname
}->{$proto}) ||
1096 defined($protocols->{byid
}->{$proto}));
1102 # helper function for API
1104 sub copy_opject_with_digest
{
1107 my $sha = Digest
::SHA-
>new('sha1');
1110 foreach my $k (sort keys %$object) {
1111 my $v = $object->{$k};
1112 next if !defined($v);
1114 $sha->add($k, ':', $v, "\n");
1117 my $digest = $sha->hexdigest;
1119 $res->{digest
} = $digest;
1121 return wantarray ?
($res, $digest) : $res;
1124 sub copy_list_with_digest
{
1127 my $sha = Digest
::SHA-
>new('sha1');
1130 foreach my $entry (@$list) {
1132 foreach my $k (sort keys %$entry) {
1133 my $v = $entry->{$k};
1134 next if !defined($v);
1136 # Note: digest ignores refs ($rule->{errors})
1137 # since Digest::SHA expects a series of bytes,
1138 # we have to encode the value here to prevent errors when
1139 # using utf8 characters (eg. in comments)
1140 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1145 my $digest = $sha->hexdigest;
1147 foreach my $entry (@$res) {
1148 $entry->{digest
} = $digest;
1151 return wantarray ?
($res, $digest) : $res;
1154 our $cluster_option_properties = {
1156 description
=> "Enable or disable the firewall cluster wide.",
1162 description
=> "Input policy.",
1165 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1168 description
=> "Output policy.",
1171 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1175 our $host_option_properties = {
1177 description
=> "Enable host firewall rules.",
1181 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1182 description
=> "Log level for incoming traffic." }),
1183 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1184 description
=> "Log level for outgoing traffic." }),
1185 tcp_flags_log_level
=> get_standard_option
('pve-fw-loglevel', {
1186 description
=> "Log level for illegal tcp flags filter." }),
1187 smurf_log_level
=> get_standard_option
('pve-fw-loglevel', {
1188 description
=> "Log level for SMURFS filter." }),
1190 description
=> "Enable SMURFS filter.",
1195 description
=> "Filter illegal combinations of TCP flags.",
1199 nf_conntrack_max
=> {
1200 description
=> "Maximum number of tracked connections.",
1205 nf_conntrack_tcp_timeout_established
=> {
1206 description
=> "Conntrack established timeout.",
1212 description
=> "Enable NDP.",
1218 our $vm_option_properties = {
1220 description
=> "Enable/disable firewall rules.",
1225 description
=> "Enable/disable MAC address filter.",
1230 description
=> "Enable DHCP.",
1235 description
=> "Enable NDP.",
1240 description
=> "Allow sending Router Advertisement.",
1245 description
=> "Enable default IP filters. " .
1246 "This is equivalent to adding an empty ipfilter-net<id> ipset " .
1247 "for every interface. Such ipsets implicitly contain sane default " .
1248 "restrictions such as restricting IPv6 link local addresses to " .
1249 "the one derived from the interface's MAC address. For containers " .
1250 "the configured IP addresses will be implicitly added.",
1255 description
=> "Input policy.",
1258 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1261 description
=> "Output policy.",
1264 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1266 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1267 description
=> "Log level for incoming traffic." }),
1268 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1269 description
=> "Log level for outgoing traffic." }),
1274 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.";
1276 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.";
1278 my $rule_properties = {
1280 description
=> "Update rule at position <pos>.",
1285 digest
=> get_standard_option
('pve-config-digest'),
1287 description
=> "Rule type.",
1290 enum
=> ['in', 'out', 'group'],
1293 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1296 pattern
=> $security_group_name_pattern,
1301 description
=> "Use predefined standard macro.",
1306 iface
=> get_standard_option
('pve-iface', {
1307 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.",
1311 description
=> "Restrict packet source address. $addr_list_descr",
1312 type
=> 'string', format
=> 'pve-fw-addr-spec',
1316 description
=> "Restrict packet destination address. $addr_list_descr",
1317 type
=> 'string', format
=> 'pve-fw-addr-spec',
1321 description
=> "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
1322 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1326 description
=> "Flag to enable/disable a rule.",
1332 description
=> "Restrict TCP/UDP source port. $port_descr",
1333 type
=> 'string', format
=> 'pve-fw-sport-spec',
1337 description
=> "Restrict TCP/UDP destination port. $port_descr",
1338 type
=> 'string', format
=> 'pve-fw-dport-spec',
1342 description
=> "Descriptive comment.",
1348 sub add_rule_properties
{
1349 my ($properties) = @_;
1351 foreach my $k (keys %$rule_properties) {
1352 my $h = $rule_properties->{$k};
1353 # copy data, so that we can modify later without side effects
1354 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1360 sub delete_rule_properties
{
1361 my ($rule, $delete_str) = @_;
1363 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1364 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1365 if !defined($rule_properties->{$opt});
1366 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1367 if $opt eq 'type' || $opt eq 'action';
1368 delete $rule->{$opt};
1374 my $apply_macro = sub {
1375 my ($macro_name, $param, $verify, $ipversion) = @_;
1377 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1378 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1380 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1381 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1384 # skip macros which are specific to another ipversion
1385 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1386 return if $ipversion != $required;
1391 foreach my $templ (@$macro_rules) {
1393 my $param_used = {};
1394 foreach my $k (keys %$templ) {
1395 my $v = $templ->{$k};
1396 if ($v eq 'PARAM') {
1398 $param_used->{$k} = 1;
1399 } elsif ($v eq 'DEST') {
1400 $v = $param->{dest
};
1401 $param_used->{dest
} = 1;
1402 } elsif ($v eq 'SOURCE') {
1403 $v = $param->{source
};
1404 $param_used->{source
} = 1;
1408 my $msg = "missing parameter '$k' in macro '$macro_name'";
1409 raise_param_exc
({ macro => $msg }) if $verify;
1414 foreach my $k (keys %$param) {
1415 next if $k eq 'macro';
1416 next if !defined($param->{$k});
1417 next if $param_used->{$k};
1418 if (defined($rule->{$k})) {
1419 if ($rule->{$k} ne $param->{$k}) {
1420 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1421 raise_param_exc
({ $k => $msg }) if $verify;
1425 $rule->{$k} = $param->{$k};
1428 push @$rules, $rule;
1434 my $rule_env_iface_lookup = {
1443 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1445 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1447 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1448 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1450 my $errors = $rule->{errors
} || {};
1452 my $error_count = 0;
1454 my $add_error = sub {
1455 my ($param, $msg) = @_;
1457 raise_param_exc
({ $param => $msg }) if !$noerr;
1459 $errors->{$param} = $msg if !$errors->{$param};
1463 my $set_ip_version = sub {
1466 die "detected mixed ipv4/ipv6 adresses in rule\n"
1467 if $ipversion && ($vers != $ipversion);
1472 my $check_ipset_or_alias_property = sub {
1473 my ($name, $expected_ipversion) = @_;
1475 if (my $value = $rule->{$name}) {
1476 if ($value =~ m/^\+/) {
1477 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1478 &$add_error($name, "no such ipset '$1'")
1479 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1482 &$add_error($name, "invalid ipset name '$value'");
1484 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1485 my $alias = lc($value);
1486 &$add_error($name, "no such alias '$value'")
1487 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1488 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1489 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1491 &$set_ip_version($e->{ipversion
});
1496 my $type = $rule->{type
};
1497 my $action = $rule->{action
};
1499 &$add_error('type', "missing property") if !$type;
1500 &$add_error('action', "missing property") if !$action;
1503 if ($type eq 'in' || $type eq 'out') {
1504 &$add_error('action', "unknown action '$action'")
1505 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1506 } elsif ($type eq 'group') {
1507 &$add_error('type', "security groups not allowed")
1509 &$add_error('action', "invalid characters in security group name")
1510 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1512 &$add_error('type', "unknown rule type '$type'");
1516 if ($rule->{iface
}) {
1517 &$add_error('type', "parameter -i not allowed for this rule type")
1519 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1520 &$add_error('iface', $@) if $@;
1521 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1522 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1523 if $rule->{iface
} !~ m/^net(\d+)$/;
1527 if ($rule->{macro}) {
1528 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1529 $rule->{macro} = $preferred_name;
1531 &$add_error('macro', "unknown macro '$rule->{macro}'");
1535 if ($rule->{proto
}) {
1536 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1537 &$add_error('proto', $@) if $@;
1538 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1539 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1542 if ($rule->{dport
}) {
1543 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1544 &$add_error('dport', $@) if $@;
1545 my $proto = $rule->{proto
};
1546 &$add_error('proto', "missing property - 'dport' requires this property")
1548 &$add_error('dport', "protocol '$proto' does not support ports")
1549 if !$PROTOCOLS_WITH_PORTS->{$proto} &&
1550 $proto ne 'icmp' && $proto ne 'icmpv6'; # special cases
1553 if ($rule->{sport
}) {
1554 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1555 &$add_error('sport', $@) if $@;
1556 my $proto = $rule->{proto
};
1557 &$add_error('proto', "missing property - 'sport' requires this property")
1559 &$add_error('sport', "protocol '$proto' does not support ports")
1560 if !$PROTOCOLS_WITH_PORTS->{$proto};
1563 if ($rule->{source
}) {
1565 my $source_ipversion = parse_address_list
($rule->{source
});
1566 &$set_ip_version($source_ipversion);
1568 &$add_error('source', $@) if $@;
1569 &$check_ipset_or_alias_property('source', $ipversion);
1572 if ($rule->{dest
}) {
1574 my $dest_ipversion = parse_address_list
($rule->{dest
});
1575 &$set_ip_version($dest_ipversion);
1577 &$add_error('dest', $@) if $@;
1578 &$check_ipset_or_alias_property('dest', $ipversion);
1581 $rule->{ipversion
} = $ipversion if $ipversion;
1583 if ($rule->{macro} && !$error_count) {
1584 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1586 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1587 my $eh = $err->{errors
};
1588 foreach my $p (keys %$eh) {
1589 &$add_error($p, $eh->{$p});
1592 &$add_error('macro', "$err");
1597 $rule->{errors
} = $errors if $error_count;
1602 sub copy_rule_data
{
1603 my ($rule, $param) = @_;
1605 foreach my $k (keys %$rule_properties) {
1606 if (defined(my $v = $param->{$k})) {
1607 if ($v eq '' || $v eq '-') {
1618 sub rules_modify_permissions
{
1619 my ($rule_env) = @_;
1621 if ($rule_env eq 'host') {
1623 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1625 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1627 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1629 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1631 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1638 sub rules_audit_permissions
{
1639 my ($rule_env) = @_;
1641 if ($rule_env eq 'host') {
1643 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1645 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1647 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1649 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1651 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1659 my $bridge_firewall_enabled = 0;
1661 sub enable_bridge_firewall
{
1663 return if $bridge_firewall_enabled; # only once
1665 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1666 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1668 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1669 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1671 $bridge_firewall_enabled = 1;
1674 sub iptables_restore_cmdlist
{
1677 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1680 sub ip6tables_restore_cmdlist
{
1683 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1686 sub ipset_restore_cmdlist
{
1689 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1692 sub iptables_get_chains
{
1693 my ($iptablescmd) = @_;
1695 $iptablescmd = "iptables" if !$iptablescmd;
1699 # check what chains we want to track
1700 my $is_pvefw_chain = sub {
1703 return 1 if $name =~ m/^PVEFW-\S+$/;
1705 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1707 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1709 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1710 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1722 return if $line =~ m/^#/;
1723 return if $line =~ m/^\s*$/;
1725 if ($line =~ m/^\*(\S+)$/) {
1730 return if $table ne 'filter';
1732 if ($line =~ m/^:(\S+)\s/) {
1734 return if !&$is_pvefw_chain($chain);
1735 $res->{$chain} = "unknown";
1736 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1737 my ($chain, $sig) = ($1, $2);
1738 return if !&$is_pvefw_chain($chain);
1739 $res->{$chain} = $sig;
1740 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1743 # simply ignore the rest
1748 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1750 return wantarray ?
($res, $hooks) : $res;
1753 sub iptables_chain_digest
{
1755 my $digest = Digest
::SHA-
>new('sha1');
1756 foreach my $rule (@$rules) { # order is important
1757 $digest->add($rule);
1759 return $digest->b64digest;
1762 sub ipset_chain_digest
{
1765 my $digest = Digest
::SHA-
>new('sha1');
1766 foreach my $rule (sort @$rules) { # note: sorted
1767 $digest->add($rule);
1769 return $digest->b64digest;
1772 sub ipset_get_chains
{
1780 return if $line =~ m/^#/;
1781 return if $line =~ m/^\s*$/;
1782 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1784 $line =~ s/\s+$//; # delete trailing white space
1785 push @{$chains->{$chain}}, $line;
1787 # simply ignore the rest
1792 run_command
("/sbin/ipset save", outfunc
=> $parser);
1794 # compute digest for each chain
1795 foreach my $chain (keys %$chains) {
1796 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1802 sub ruleset_generate_match
{
1803 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1805 return if defined($rule->{enable
}) && !$rule->{enable
};
1806 return if $rule->{errors
};
1808 return $rule->{match
} if defined $rule->{match
};
1810 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1812 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1813 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1817 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1818 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1820 my $source = $rule->{source
};
1821 my $dest = $rule->{dest
};
1824 if ($source =~ m/^\+/) {
1825 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1827 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1828 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1829 push @cmd, "-m set --match-set ${ipset_chain} src";
1830 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1831 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1832 push @cmd, "-m set --match-set ${ipset_chain} src";
1834 die "no such ipset '$name'\n";
1837 die "invalid security group name '$source'\n";
1839 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1840 my $alias = lc($source);
1841 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1842 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1843 die "no such alias '$source'\n" if !$e;
1844 push @cmd, "-s $e->{cidr}";
1845 } elsif ($source =~ m/\-/){
1846 push @cmd, "-m iprange --src-range $source";
1848 push @cmd, "-s $source";
1853 if ($dest =~ m/^\+/) {
1854 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1856 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1857 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1858 push @cmd, "-m set --match-set ${ipset_chain} dst";
1859 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1860 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1861 push @cmd, "-m set --match-set ${ipset_chain} dst";
1863 die "no such ipset '$name'\n";
1866 die "invalid security group name '$dest'\n";
1868 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1869 my $alias = lc($dest);
1870 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1871 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1872 die "no such alias '$dest'\n" if !$e;
1873 push @cmd, "-d $e->{cidr}";
1874 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1875 push @cmd, "-m iprange --dst-range $dest";
1877 push @cmd, "-d $dest";
1881 if (my $proto = $rule->{proto
}) {
1882 push @cmd, "-p $proto";
1885 $multiport++ if $nbdport > 1;
1886 $multiport++ if $nbsport > 1;
1888 push @cmd, "--match multiport" if $multiport;
1890 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1891 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1893 if ($rule->{dport
}) {
1894 if ($proto eq 'icmp') {
1895 # Note: we use dport to store --icmp-type
1896 die "unknown icmp-type '$rule->{dport}'\n"
1897 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1898 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1899 } elsif ($proto eq 'icmpv6') {
1900 # Note: we use dport to store --icmpv6-type
1901 die "unknown icmpv6-type '$rule->{dport}'\n"
1902 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1903 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1904 } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
1905 die "protocol $proto does not have ports\n";
1908 if ($multiport == 2) {
1909 push @cmd, "--ports $rule->{dport}";
1911 push @cmd, "--dports $rule->{dport}";
1914 push @cmd, "--dport $rule->{dport}";
1919 if ($rule->{sport
}) {
1920 die "protocol $proto does not have ports\n"
1921 if !$PROTOCOLS_WITH_PORTS->{$proto};
1923 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1925 push @cmd, "--sport $rule->{sport}";
1928 } elsif ($rule->{dport
} || $rule->{sport
}) {
1929 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1930 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1933 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1935 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1938 sub ruleset_generate_action
{
1939 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1941 return $rule->{target
} if defined $rule->{target
};
1945 if (my $action = $rule->{action
}) {
1946 $action = $actions->{$action} if defined($actions->{$action});
1947 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1948 push @cmd, $goto ?
"-g $action" : "-j $action";
1951 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1954 sub ruleset_generate_cmdstr
{
1955 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1956 my $match = ruleset_generate_match
($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1957 my $action = ruleset_generate_action
($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1959 return undef if !(defined($match) or defined($action));
1960 my $ret = defined($match) ?
$match : "";
1961 $ret = "$ret $action" if defined($action);
1965 sub ruleset_generate_rule
{
1966 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1970 if ($rule->{macro}) {
1971 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1976 # update all or nothing
1978 # fixme: lots of temporary ugliness
1983 foreach my $tmp (@$rules) {
1984 my $m = ruleset_generate_match
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1985 my $a = ruleset_generate_action
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1986 if (defined $m or defined $a) {
1987 push @mstrs, defined($m) ?
$m : "";
1988 push @astrs, defined($a) ?
$a : "";
1989 push @logging, $tmp->{log};
1990 push @logmsg, $tmp->{logmsg
};
1994 for my $i (0 .. $#mstrs) {
1995 ruleset_addrule
($ruleset, $chain, $mstrs[$i], $astrs[$i], $logging[$i], $logmsg[$i]);
1999 sub ruleset_generate_rule_insert
{
2000 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
2002 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
2004 my $match = ruleset_generate_match
($ruleset, $chain, $ipversion, $rule, $actions, $goto);
2005 my $action = ruleset_generate_action
($ruleset, $chain, $ipversion, $rule, $actions, $goto);
2006 if (defined $match && defined $action) {
2007 ruleset_insertrule
($ruleset, $chain, $match, $action);
2011 sub ruleset_create_chain
{
2012 my ($ruleset, $chain) = @_;
2014 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
2015 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
2017 die "chain '$chain' already exists\n" if $ruleset->{$chain};
2019 $ruleset->{$chain} = [];
2022 sub ruleset_chain_exist
{
2023 my ($ruleset, $chain) = @_;
2025 return $ruleset->{$chain} ?
1 : undef;
2028 sub ruleset_addrule
{
2029 my ($ruleset, $chain, $match, $action, $log, $logmsg, $vmid) = @_;
2031 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2033 if (defined($log) && $log) {
2034 my $logaction = get_log_rule_base
($chain, $vmid, $logmsg, $log);
2035 push @{$ruleset->{$chain}}, "-A $chain $match $logaction";
2037 push @{$ruleset->{$chain}}, "-A $chain $match $action";
2040 sub ruleset_insertrule
{
2041 my ($ruleset, $chain, $match, $action, $log) = @_;
2043 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2045 unshift @{$ruleset->{$chain}}, "-A $chain $match $action";
2048 sub get_log_rule_base
{
2049 my ($chain, $vmid, $msg, $loglevel) = @_;
2051 $vmid = 0 if !defined($vmid);
2052 $msg = "" if !defined($msg);
2054 # Note: we use special format for prefix to pass further
2055 # info to log daemon (VMID, LOGLEVEL and CHAIN)
2057 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
2060 sub ruleset_add_chain_policy {
2061 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
2063 if ($policy eq 'ACCEPT') {
2065 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
2066 { ACCEPT => $accept_action});
2068 } elsif ($policy eq 'DROP') {
2070 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Drop
");
2072 ruleset_addrule($ruleset, $chain, "", "-j DROP
", $loglevel, "policy
$policy: ", $vmid);
2073 } elsif ($policy eq 'REJECT') {
2074 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Reject
");
2076 ruleset_addrule($ruleset, $chain, "", "-g PVEFW-reject
", $loglevel, "policy
$policy:", $vmid);
2079 die "internal error
: unknown policy
'$policy'";
2083 sub ruleset_chain_add_ndp {
2084 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
2085 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2087 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
", $accept);
2088 if ($direction ne 'OUT' || $options->{radv}) {
2089 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
", $accept);
2091 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
", $accept);
2092 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
", $accept);
2095 sub ruleset_chain_add_conn_filters {
2096 my ($ruleset, $chain, $accept) = @_;
2098 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
", "-j DROP
");
2099 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
", "-j
$accept");
2102 sub ruleset_chain_add_input_filters {
2103 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2105 if ($cluster_conf->{ipset}->{blacklist}){
2106 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
2107 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
2108 ruleset_addrule($ruleset, "PVEFW-blacklist
", "", "-j DROP
", $loglevel, "DROP
: ");
2110 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
2111 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
", "-j PVEFW-blacklist
");
2114 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
2115 if ($ipversion == 4) {
2116 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
", "-j PVEFW-smurfs
");
2120 if ($options->{tcpflags}) {
2121 ruleset_addrule($ruleset, $chain, "-p tcp
", "-j PVEFW-tcpflags
");
2125 sub ruleset_create_vm_chain {
2126 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
2128 ruleset_create_chain($ruleset, $chain);
2129 my $accept = generate_nfqueue($options);
2131 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
2132 if ($ipversion == 4) {
2133 if ($direction eq 'OUT') {
2134 ruleset_generate_rule($ruleset, $chain, $ipversion,
2135 { action => 'PVEFW-SET-ACCEPT-MARK',
2136 proto => 'udp', sport => 68, dport => 67 });
2138 ruleset_generate_rule($ruleset, $chain, $ipversion,
2139 { action => 'ACCEPT',
2140 proto => 'udp', sport => 67, dport => 68 });
2142 } elsif ($ipversion == 6) {
2143 if ($direction eq 'OUT') {
2144 ruleset_generate_rule($ruleset, $chain, $ipversion,
2145 { action => 'PVEFW-SET-ACCEPT-MARK',
2146 proto => 'udp', sport => 546, dport => 547 });
2148 ruleset_generate_rule($ruleset, $chain, $ipversion,
2149 { action => 'ACCEPT',
2150 proto => 'udp', sport => 547, dport => 546 });
2156 if ($direction eq 'OUT') {
2157 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
2158 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr", "-j DROP
");
2160 if ($ipversion == 6 && !$options->{radv}) {
2161 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
", "-j DROP
");
2163 if ($ipfilter_ipset) {
2164 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
", "-j DROP
");
2166 ruleset_addrule($ruleset, $chain, "", "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2169 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
2170 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
2173 sub ruleset_add_group_rule {
2174 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
2176 my $group = $rule->{action};
2177 my $group_chain = "GROUP-
$group-$direction";
2178 if(!ruleset_chain_exist($ruleset, $group_chain)){
2179 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
2182 if ($direction eq 'OUT' && $rule->{iface_out}) {
2183 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
}", "-j
$group_chain");
2184 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2185 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
}", "-j
$group_chain");
2187 ruleset_addrule($ruleset, $chain, "", "-j
$group_chain");
2190 ruleset_addrule($ruleset, $chain, "-m mark
--mark
$FWACCEPTMARK_ON", "-j
$action");
2193 sub ruleset_generate_vm_rules {
2194 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2196 my $lc_direction = lc($direction);
2198 my $in_accept = generate_nfqueue($options);
2200 foreach my $rule (@$rules) {
2201 next if $rule->{iface} && $rule->{iface} ne $netid;
2202 next if !$rule->{enable} || $rule->{errors};
2203 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2205 if ($rule->{type} eq 'group') {
2206 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2207 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2209 next if $rule->{type} ne $lc_direction;
2211 if ($direction eq 'OUT') {
2212 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2213 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2214 undef, $cluster_conf, $vmfw_conf);
2216 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2217 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2218 undef, $cluster_conf, $vmfw_conf);
2226 sub generate_nfqueue {
2229 if ($options->{ips}) {
2230 my $action = "NFQUEUE
";
2231 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2232 if (defined($3) && defined($1)) {
2233 $action .= " --queue-balance
$1:$3";
2234 } elsif (defined($1)) {
2235 $action .= " --queue-num
$1";
2238 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2245 sub ruleset_generate_vm_ipsrules {
2246 my ($ruleset, $options, $direction, $iface) = @_;
2248 if ($options->{ips} && $direction eq 'IN') {
2249 my $nfqueue = generate_nfqueue($options);
2251 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2252 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2255 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
", "-j
$nfqueue");
2259 sub generate_tap_rules_direction {
2260 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2262 my $lc_direction = lc($direction);
2264 my $rules = $vmfw_conf->{rules};
2266 my $options = $vmfw_conf->{options};
2267 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2269 my $tapchain = "$iface-$direction";
2271 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2272 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2273 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2275 # create chain with mac and ip filter
2276 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2278 if ($options->{enable}) {
2279 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2281 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2286 if ($direction eq 'OUT') {
2287 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2289 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2292 my $accept = generate_nfqueue($options);
2293 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2294 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2296 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2297 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2300 # plug the tap chain to bridge chain
2301 if ($direction eq 'IN') {
2302 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2303 "-m physdev
--physdev-is-bridged
--physdev-out
$iface", "-j
$tapchain");
2305 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2306 "-m physdev
--physdev-is-bridged
--physdev-in
$iface", "-j
$tapchain");
2310 sub enable_host_firewall {
2311 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2313 my $options = $hostfw_conf->{options};
2314 my $cluster_options = $cluster_conf->{options};
2315 my $rules = $hostfw_conf->{rules};
2316 my $cluster_rules = $cluster_conf->{rules};
2318 # host inbound firewall
2319 my $chain = "PVEFW-HOST-IN
";
2320 ruleset_create_chain($ruleset, $chain);
2322 my $loglevel = get_option_log_level($options, "log_level_in
");
2324 ruleset_addrule($ruleset, $chain, "-i lo
", "-j ACCEPT
");
2326 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2327 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2328 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2330 # we use RETURN because we need to check also tap rules
2331 my $accept_action = 'RETURN';
2333 ruleset_addrule($ruleset, $chain, "-p igmp
", "-j
$accept_action"); # important for multicast
2335 # add host rules first, so that cluster wide rules can be overwritten
2336 foreach my $rule (@$rules, @$cluster_rules) {
2337 next if !$rule->{enable} || $rule->{errors};
2338 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2340 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2343 if ($rule->{type} eq 'group') {
2344 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2345 } elsif ($rule->{type} eq 'in') {
2346 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2347 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2348 undef, $cluster_conf, $hostfw_conf);
2352 delete $rule->{iface_in};
2355 # allow standard traffic for management ipset (includes cluster network)
2356 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2357 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2358 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006", "-j
$accept_action"); # PVE API
2359 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999", "-j
$accept_action"); # PVE VNC Console
2360 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128", "-j
$accept_action"); # SPICE Proxy
2361 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22", "-j
$accept_action"); # SSH
2363 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2364 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2367 if ($localnet && ($ipversion == $localnet_ver)) {
2368 my $corosync_rule = "-p udp
--dport
5404:5405";
2369 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule", "-j
$accept_action");
2370 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule", "-j
$accept_action");
2373 # implement input policy
2374 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2375 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2377 # host outbound firewall
2378 $chain = "PVEFW-HOST-OUT
";
2379 ruleset_create_chain($ruleset, $chain);
2381 $loglevel = get_option_log_level($options, "log_level_out
");
2383 ruleset_addrule($ruleset, $chain, "-o lo
", "-j ACCEPT
");
2385 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2387 # we use RETURN because we may want to check other thigs later
2388 $accept_action = 'RETURN';
2389 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2391 ruleset_addrule($ruleset, $chain, "-p igmp
", "-j
$accept_action"); # important for multicast
2393 # add host rules first, so that cluster wide rules can be overwritten
2394 foreach my $rule (@$rules, @$cluster_rules) {
2395 next if !$rule->{enable} || $rule->{errors};
2396 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2398 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2400 if ($rule->{type} eq 'group') {
2401 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2402 } elsif ($rule->{type} eq 'out') {
2403 ruleset_generate_rule($ruleset, $chain, $ipversion,
2404 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2405 undef, $cluster_conf, $hostfw_conf);
2409 delete $rule->{iface_out};
2412 # allow standard traffic on cluster network
2413 if ($localnet && ($ipversion == $localnet_ver)) {
2414 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006", "-j
$accept_action"); # PVE API
2415 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22", "-j
$accept_action"); # SSH
2416 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999", "-j
$accept_action"); # PVE VNC Console
2417 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128", "-j
$accept_action"); # SPICE Proxy
2419 my $corosync_rule = "-p udp
--dport
5404:5405";
2420 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule", "-j
$accept_action");
2421 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule", "-j
$accept_action");
2424 # implement output policy
2425 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2426 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2428 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "", "-j PVEFW-HOST-OUT
");
2429 ruleset_addrule($ruleset, "PVEFW-INPUT
", "", "-j PVEFW-HOST-IN
");
2432 sub generate_group_rules {
2433 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2435 my $rules = $cluster_conf->{groups}->{$group};
2438 warn "no such security group
'$group'\n";
2439 $rules = []; # create empty chain
2442 my $chain = "GROUP-
${group
}-IN
";
2444 ruleset_create_chain($ruleset, $chain);
2445 ruleset_addrule($ruleset, $chain, "", "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2447 foreach my $rule (@$rules) {
2448 next if $rule->{type} ne 'in';
2449 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2450 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2451 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2452 undef, $cluster_conf);
2455 $chain = "GROUP-
${group
}-OUT
";
2457 ruleset_create_chain($ruleset, $chain);
2458 ruleset_addrule($ruleset, $chain, "", "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2460 foreach my $rule (@$rules) {
2461 next if $rule->{type} ne 'out';
2462 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2463 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2464 # check also other tap rules later
2465 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2466 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2467 undef, $cluster_conf);
2472 my $valid_netdev_names = {};
2473 for (my $i = 0; $i < $MAX_NETS; $i++) {
2474 $valid_netdev_names->{"net
$i"} = 1;
2477 sub get_mark_values {
2478 my ($value, $mask) = @_;
2479 $value = hex($value) if $value =~ /^0x/;
2480 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2481 $mask = 0xffffffff if !defined($mask);
2482 return ($value, $mask);
2486 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2488 my $orig_line = $line;
2492 # we can add single line comments to the end of the rule
2493 if ($line =~ s/#\s*(.*?)\s*$//) {
2494 $rule->{comment} = decode('utf8', $1);
2497 # we can disable a rule when prefixed with '|'
2499 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2501 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2502 die "unable to parse rule
: $line\n";
2504 $rule->{type} = lc($1);
2505 $rule->{action} = $2;
2507 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2508 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2509 $rule->{macro} = $1;
2510 $rule->{action} = $2;
2514 while (length($line)) {
2515 if ($line =~ s/^-i (\S+)\s*//) {
2516 $rule->{iface} = $1;
2520 last if $rule->{type} eq 'group';
2522 if ($line =~ s/^-p (\S+)\s*//) {
2523 $rule->{proto} = $1;
2527 if ($line =~ s/^-dport (\S+)\s*//) {
2528 $rule->{dport} = $1;
2532 if ($line =~ s/^-sport (\S+)\s*//) {
2533 $rule->{sport} = $1;
2536 if ($line =~ s/^-source (\S+)\s*//) {
2537 $rule->{source} = $1;
2540 if ($line =~ s/^-dest (\S+)\s*//) {
2548 die "unable to parse rule parameters
: $line\n" if length($line);
2550 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2551 if ($rule->{errors}) {
2552 # The verbose flag really means we're running from the CLI and want
2553 # output on the console - in the other case we really want such errors
2554 # to go into the syslog instead.
2555 my $log = $verbose ? sub { warn @_ } : sub { syslog(err => @_) };
2556 $log->("$prefix - errors
in rule parameters
: $orig_line\n");
2557 foreach my $p (keys %{$rule->{errors}}) {
2558 $log->(" $p: $rule->{errors
}->{$p}\n");
2565 sub parse_vmfw_option {
2570 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2572 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2575 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2577 $value = $2 ? lc($3) : '';
2578 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2581 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2585 die "can
't parse option '$line'\n"
2588 return ($opt, $value);
2591 sub parse_hostfw_option {
2596 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2598 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2601 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2603 $value = $2 ? lc($3) : '';
2604 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2608 die "can't parse option
'$line'\n"
2611 return ($opt, $value);
2614 sub parse_clusterfw_option {
2619 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2622 if (($value > 1) && ((time() - $value) > 60)) {
2625 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2629 die "can
't parse option '$line'\n"
2632 return ($opt, $value);
2636 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2638 my $alias = lc($cidr);
2639 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2640 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2642 die "no such alias '$cidr'\n" if !$e;;
2644 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2647 sub parse_ip_or_cidr {
2652 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2655 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2659 die "value does not look like a valid IP address or CIDR network\n";
2662 return wantarray ? ($cidr, $ipversion) : $cidr;
2668 # we can add single line comments to the end of the line
2669 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2671 if ($line =~ m/^(\S+)\s(\S+)$/) {
2672 my ($name, $cidr) = ($1, $2);
2675 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2680 ipversion => $ipversion,
2682 $data->{comment} = $comment if $comment;
2689 sub generic_fw_config_parser {
2690 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2695 my $res = $empty_conf;
2697 while (defined(my $line = <$fh>)) {
2698 next if $line =~ m/^#/;
2699 next if $line =~ m/^\s*$/;
2703 my $linenr = $fh->input_line_number();
2704 my $prefix = "$filename (line $linenr)";
2706 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2707 $section = 'options
';
2711 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2712 $section = 'aliases
';
2716 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2717 $section = 'groups
';
2721 die "security group name too long\n" if length($group) > $max_group_name_length;
2722 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2725 ($section, $group, $comment) = undef;
2726 warn "$prefix: $err";
2730 $res->{$section}->{$group} = [];
2731 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2736 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2741 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2746 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2747 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2750 ($section, $group, $comment) = undef;
2751 warn "$prefix: $err";
2755 $res->{$section}->{$group} = [];
2756 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2762 warn "$prefix: skip line - no section\n";
2766 if ($section eq 'options
') {
2769 if ($rule_env eq 'cluster
') {
2770 ($opt, $value) = parse_clusterfw_option($line);
2771 } elsif ($rule_env eq 'host
') {
2772 ($opt, $value) = parse_hostfw_option($line);
2774 ($opt, $value) = parse_vmfw_option($line);
2776 $res->{options}->{$opt} = $value;
2778 warn "$prefix: $@" if $@;
2779 } elsif ($section eq 'aliases
') {
2781 my $data = parse_alias($line);
2782 $res->{aliases}->{lc($data->{name})} = $data;
2784 warn "$prefix: $@" if $@;
2785 } elsif ($section eq 'rules
') {
2787 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2789 warn "$prefix: $err";
2792 push @{$res->{$section}}, $rule;
2793 } elsif ($section eq 'groups
') {
2795 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2797 warn "$prefix: $err";
2800 push @{$res->{$section}->{$group}}, $rule;
2801 } elsif ($section eq 'ipset
') {
2802 # we can add single line comments to the end of the rule
2803 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2805 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2810 if ($nomatch && !$feature_ipset_nomatch) {
2811 $errors->{nomatch} = "nomatch not supported by kernel";
2815 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2816 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2818 $cidr = parse_ip_or_cidr($cidr);
2823 $errors->{cidr} = $err;
2826 if ($cidr =~ m!/0+$!) {
2827 $errors->{cidr} = "a zero prefix is not allowed in ipset entries\n";
2830 my $entry = { cidr => $cidr };
2831 $entry->{nomatch} = 1 if $nomatch;
2832 $entry->{comment} = $comment if $comment;
2833 $entry->{errors} = $errors if $errors;
2835 if ($verbose && $errors) {
2836 warn "$prefix - errors in ipset '$group': $line\n";
2837 foreach my $p (keys %{$errors}) {
2838 warn " $p: $errors->{$p}\n";
2842 push @{$res->{$section}->{$group}}, $entry;
2844 warn "$prefix: skip line - unknown section\n";
2852 sub parse_hostfw_config {
2853 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2855 my $empty_conf = { rules => [], options => {}};
2857 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2860 sub parse_vmfw_config {
2861 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2868 ipset_comments => {},
2871 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2874 sub parse_clusterfw_config {
2875 my ($filename, $fh, $verbose) = @_;
2885 group_comments => {},
2887 ipset_comments => {},
2890 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2894 my ($code, @param) = @_;
2898 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2905 sub read_local_vm_config {
2910 my $vmdata = { qemu => $qemu, lxc => $lxc };
2912 my $vmlist = PVE::Cluster::get_vmlist();
2913 return $vmdata if !$vmlist || !$vmlist->{ids};
2914 my $ids = $vmlist->{ids};
2916 foreach my $vmid (keys %$ids) {
2917 next if !$vmid; # skip VE0
2918 my $d = $ids->{$vmid};
2919 next if !$d->{node} || $d->{node} ne $nodename;
2920 next if !$d->{type};
2921 if ($d->{type} eq 'qemu
') {
2922 if ($have_qemu_server) {
2923 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2924 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2925 $qemu->{$vmid} = $conf;
2928 } elsif ($d->{type} eq 'lxc
') {
2930 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2931 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2932 $lxc->{$vmid} = $conf;
2941 sub load_vmfw_conf {
2942 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2946 $dir = $pvefw_conf_dir if !defined($dir);
2948 my $filename = "$dir/$vmid.fw";
2949 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2950 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2951 $vmfw_conf->{vmid} = $vmid;
2957 my $format_rules = sub {
2958 my ($rules, $allow_iface) = @_;
2962 foreach my $rule (@$rules) {
2963 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2964 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2965 $raw .= uc($rule->{type});
2966 if ($rule->{macro}) {
2967 $raw .= " $rule->{macro}($rule->{action})";
2969 $raw .= " " . $rule->{action};
2971 if ($allow_iface && $rule->{iface}) {
2972 $raw .= " -i $rule->{iface}";
2975 if ($rule->{type} ne 'group
') {
2976 $raw .= " -source $rule->{source}" if $rule->{source};
2977 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2978 $raw .= " -p $rule->{proto}" if $rule->{proto};
2979 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2980 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2983 $raw .= " # " . encode('utf8
', $rule->{comment})
2984 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2987 die "unknown rule type '$rule->{type
}'";
2994 my $format_options = sub {
2999 $raw .= "[OPTIONS]\n\n";
3000 foreach my $opt (keys %$options) {
3001 $raw .= "$opt: $options->{$opt}\n";
3008 my $format_aliases = sub {
3013 $raw .= "[ALIASES]\n\n";
3014 foreach my $k (keys %$aliases) {
3015 my $e = $aliases->{$k};
3016 $raw .= "$e->{name} $e->{cidr}";
3017 $raw .= " # " . encode('utf8
', $e->{comment})
3018 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
3026 my $format_ipsets = sub {
3031 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
3032 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
3033 my $utf8comment = encode('utf8
', $comment);
3034 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
3036 $raw .= "[IPSET $ipset]\n\n";
3038 my $options = $fw_conf->{ipset}->{$ipset};
3041 foreach my $entry (@$options) {
3042 $nethash->{$entry->{cidr}} = $entry;
3045 foreach my $cidr (sort keys %$nethash) {
3046 my $entry = $nethash->{$cidr};
3047 my $line = $entry->{nomatch} ? '!' : '';
3048 $line .= $entry->{cidr};
3049 $line .= " # " . encode('utf8
', $entry->{comment})
3050 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
3060 sub save_vmfw_conf {
3061 my ($vmid, $vmfw_conf) = @_;
3065 my $options = $vmfw_conf->{options};
3066 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3068 my $aliases = $vmfw_conf->{aliases};
3069 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3071 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
3073 my $rules = $vmfw_conf->{rules} || [];
3074 if ($rules && scalar(@$rules)) {
3075 $raw .= "[RULES]\n\n";
3076 $raw .= &$format_rules($rules, 1);
3080 my $filename = "$pvefw_conf_dir/$vmid.fw";
3082 mkdir $pvefw_conf_dir;
3083 PVE::Tools::file_set_contents($filename, $raw);
3089 sub remove_vmfw_conf {
3092 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3094 unlink $vmfw_conffile;
3097 sub clone_vmfw_conf {
3098 my ($vmid, $newid) = @_;
3100 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3101 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3103 if (-f $clonevm_conffile) {
3104 unlink $clonevm_conffile;
3106 if (-f $sourcevm_conffile) {
3107 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3108 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3112 sub read_vm_firewall_configs {
3113 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
3115 my $vmfw_configs = {};
3117 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3118 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
3119 next if !$vmfw_conf->{options}; # skip if file does not exists
3120 $vmfw_configs->{$vmid} = $vmfw_conf;
3122 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3123 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
3124 next if !$vmfw_conf->{options}; # skip if file does not exists
3125 $vmfw_configs->{$vmid} = $vmfw_conf;
3128 return $vmfw_configs;
3131 sub get_option_log_level {
3132 my ($options, $k) = @_;
3134 my $v = $options->{$k};
3135 $v = $default_log_level if !defined($v);
3137 return undef if $v eq '' || $v eq 'nolog
';
3139 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3141 return $v if ($v >= 0) && ($v <= 7);
3143 warn "unknown log level ($k = '$v')\n";
3148 sub generate_std_chains {
3149 my ($ruleset, $options, $ipversion) = @_;
3151 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
3153 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
3154 my $chain = 'PVEFW-smurflog
';
3155 if ( $std_chains->{$chain} ) {
3156 foreach my $r (@{$std_chains->{$chain}}) {
3157 $r->{log} = $loglevel;
3161 # same as shorewall logflags action.
3162 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
3163 $chain = 'PVEFW-logflags
';
3164 if ( $std_chains->{$chain} ) {
3165 foreach my $r (@{$std_chains->{$chain}}) {
3166 $r->{log} = $loglevel;
3170 foreach my $chain (keys %$std_chains) {
3171 ruleset_create_chain($ruleset, $chain);
3172 foreach my $rule (@{$std_chains->{$chain}}) {
3174 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
3176 die "rule $rule as string - should not happen";
3182 sub generate_ipset_chains {
3183 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
3185 foreach my $ipset (keys %{$ipsets}) {
3187 my $options = $ipsets->{$ipset};
3189 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3190 if (my $ips = $device_ips->{$1}) {
3191 $options = [@$options, @$ips];
3197 foreach my $entry (@$options) {
3198 next if $entry->{errors}; # skip entries with errors
3201 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3202 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3204 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3206 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3208 # ip_compress_address takes an address only, no CIDR
3209 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3210 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3211 $cidr .= $prefix_len if defined($prefix_len);
3217 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3222 foreach my $ipversion (4, 6) {
3223 my $data = $nethash->{$ipversion};
3225 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3227 my $hashsize = scalar(@$options);
3228 if ($hashsize <= 64) {
3231 $hashsize = round_powerof2($hashsize);
3234 my $family = $ipversion == "6" ? "inet6" : "inet";
3236 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3238 foreach my $cidr (sort keys %$data) {
3239 my $entry = $data->{$cidr};
3241 my $cmd = "add $name $cidr";
3242 if ($entry->{nomatch}) {
3243 if ($feature_ipset_nomatch) {
3244 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3246 warn "ignore !$cidr - nomatch not supported by kernel\n";
3249 push @{$ipset_ruleset->{$name}}, $cmd;
3256 sub round_powerof2 {
3260 $int |= $int >> $_ foreach (1,2,4,8,16);
3264 sub load_clusterfw_conf {
3265 my ($filename, $verbose) = @_;
3267 $filename = $clusterfw_conf_filename if !defined($filename);
3269 my $cluster_conf = {};
3270 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3271 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3274 return $cluster_conf;
3277 sub save_clusterfw_conf {
3278 my ($cluster_conf) = @_;
3282 my $options = $cluster_conf->{options};
3283 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3285 my $aliases = $cluster_conf->{aliases};
3286 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3288 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3290 my $rules = $cluster_conf->{rules};
3291 if ($rules && scalar(@$rules)) {
3292 $raw .= "[RULES]\n\n";
3293 $raw .= &$format_rules($rules, 1);
3297 if ($cluster_conf->{groups}) {
3298 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3299 my $rules = $cluster_conf->{groups}->{$group};
3300 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3301 my $utf8comment = encode('utf8
', $comment);
3302 $raw .= "[group $group] # $utf8comment\n\n";
3304 $raw .= "[group $group]\n\n";
3307 $raw .= &$format_rules($rules, 0);
3313 mkdir $pvefw_conf_dir;
3314 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3316 unlink $clusterfw_conf_filename;
3320 sub load_hostfw_conf {
3321 my ($cluster_conf, $filename, $verbose) = @_;
3323 $filename = $hostfw_conf_filename if !defined($filename);
3325 my $hostfw_conf = {};
3326 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3327 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3329 return $hostfw_conf;
3332 sub save_hostfw_conf {
3333 my ($hostfw_conf) = @_;
3337 my $options = $hostfw_conf->{options};
3338 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3340 my $rules = $hostfw_conf->{rules};
3341 if ($rules && scalar(@$rules)) {
3342 $raw .= "[RULES]\n\n";
3343 $raw .= &$format_rules($rules, 1);
3348 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3350 unlink $hostfw_conf_filename;
3355 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3359 # fixme: once we read standard chains from config this needs to be put in test/standard cases below
3360 $pve_std_chains = dclone($pve_std_chains_conf);
3362 if ($vmdata) { # test mode
3363 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3364 my $filename = "$testdir/cluster.fw";
3365 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3367 $filename = "$testdir/host.fw";
3368 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3370 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3371 } else { # normal operation
3372 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3374 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3376 $vmdata = read_local_vm_config();
3377 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3380 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3383 if ($cluster_conf->{aliases}->{local_network}) {
3384 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3387 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3389 $cluster_conf->{aliases}->{local_network} = {
3390 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3393 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3395 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3396 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3397 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3399 return ($ruleset, $ipset_ruleset, $rulesetv6);
3402 sub compile_iptables_filter {
3403 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3407 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3408 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3410 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3412 my $hostfw_options = $hostfw_conf->{options} || {};
3414 # fixme: what log level should we use here?
3415 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3417 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3419 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3420 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3422 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+", "-j PVEFW-FWBR-IN");
3424 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3425 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+", "-j PVEFW-FWBR-OUT");
3427 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3429 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3431 if ($hostfw_enable) {
3432 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3433 warn $@ if $@; # just to be sure - should not happen
3436 # generate firewall rules for QEMU VMs
3437 foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
3439 my $conf = $vmdata->{qemu}->{$vmid};
3440 my $vmfw_conf = $vmfw_configs->{$vmid};
3441 return if !$vmfw_conf;
3443 foreach my $netid (sort keys %$conf) {
3444 next if $netid !~ m/^net(\d+)$/;
3445 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3446 next if !$net->{firewall};
3447 my $iface = "tap${vmid}i$1";
3449 my $macaddr = $net->{macaddr};
3450 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3451 $vmfw_conf, $vmid, 'IN
', $ipversion);
3452 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3453 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3456 warn $@ if $@; # just to be sure - should not happen
3459 # generate firewall rules for LXC containers
3460 foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
3462 my $conf = $vmdata->{lxc}->{$vmid};
3463 my $vmfw_conf = $vmfw_configs->{$vmid};
3464 return if !$vmfw_conf;
3466 if ($vmfw_conf->{options}->{enable}) {
3467 foreach my $netid (sort keys %$conf) {
3468 next if $netid !~ m/^net(\d+)$/;
3469 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3470 next if !$net->{firewall};
3471 my $iface = "veth${vmid}i$1";
3472 my $macaddr = $net->{hwaddr};
3473 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3474 $vmfw_conf, $vmid, 'IN
', $ipversion);
3475 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3476 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3480 warn $@ if $@; # just to be sure - should not happen
3483 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3484 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED", "-j PVEFW-IPS");
3490 sub mac_to_linklocal {
3492 my @parts = split(/:/, $macaddr);
3493 # The standard link local address uses the fe80::/64 prefix with the
3494 # modified EUI-64 identifier derived from the MAC address by flipping the
3495 # universal/local bit and inserting FF:FE in the middle.
3497 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3498 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3499 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3502 sub compile_ipsets {
3503 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3506 if ($cluster_conf->{aliases}->{local_network}) {
3507 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3510 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3512 $cluster_conf->{aliases}->{local_network} = {
3513 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3516 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3519 my $ipset_ruleset = {};
3521 # generate ipsets for QEMU VMs
3522 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3524 my $conf = $vmdata->{qemu}->{$vmid};
3525 my $vmfw_conf = $vmfw_configs->{$vmid};
3526 return if !$vmfw_conf;
3528 # When the 'ipfilter
' option is enabled every device for which there
3529 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3531 # The reason is that ipfilter ipsets are always filled with standard
3532 # IPv6 link-local filters.
3533 my $ipsets = $vmfw_conf->{ipset};
3534 my $implicit_sets = {};
3536 my $device_ips = {};
3537 foreach my $netid (keys %$conf) {
3538 next if $netid !~ m/^net(\d+)$/;
3539 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3540 next if !$net->{firewall};
3542 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3543 $implicit_sets->{"ipfilter-$netid"} = [];
3546 my $macaddr = $net->{macaddr};
3547 my $linklocal = mac_to_linklocal($macaddr);
3548 $device_ips->{$netid} = [
3549 { cidr => $linklocal },
3550 { cidr => 'fe80
::/10', nomatch => 1 }
3554 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3555 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3557 warn $@ if $@; # just to be sure - should not happen
3560 # generate firewall rules for LXC containers
3561 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3563 my $conf = $vmdata->{lxc}->{$vmid};
3564 my $vmfw_conf = $vmfw_configs->{$vmid};
3565 return if !$vmfw_conf;
3567 # When the 'ipfilter
' option is enabled every device for which there
3568 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3570 # The reason is that ipfilter ipsets are always filled with standard
3571 # IPv6 link-local filters, as well as the IP addresses configured
3572 # for the container.
3573 my $ipsets = $vmfw_conf->{ipset};
3574 my $implicit_sets = {};
3576 my $device_ips = {};
3577 foreach my $netid (keys %$conf) {
3578 next if $netid !~ m/^net(\d+)$/;
3579 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3580 next if !$net->{firewall};
3582 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3583 $implicit_sets->{"ipfilter-$netid"} = [];
3586 my $macaddr = $net->{hwaddr};
3587 my $linklocal = mac_to_linklocal($macaddr);
3588 my $set = $device_ips->{$netid} = [
3589 { cidr => $linklocal },
3590 { cidr => 'fe80
::/10', nomatch => 1 }
3592 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3593 push @$set, { cidr => $1 };
3595 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3596 push @$set, { cidr => $1 };
3600 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3601 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3603 warn $@ if $@; # just to be sure - should not happen
3606 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3608 return $ipset_ruleset;
3611 sub get_ruleset_status {
3612 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3614 my $statushash = {};
3616 foreach my $chain (sort keys %$ruleset) {
3617 my $sig = &$digest_fn($ruleset->{$chain});
3619 $statushash->{$chain}->{sig} = $sig;
3621 my $oldsig = $active_chains->{$chain};
3622 if (!defined($oldsig)) {
3623 $statushash->{$chain}->{action} = 'create
';
3625 if ($oldsig eq $sig) {
3626 $statushash->{$chain}->{action} = 'exists';
3628 $statushash->{$chain}->{action} = 'update
';
3631 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3632 foreach my $cmd (@{$ruleset->{$chain}}) {
3633 print "\t$cmd\n" if $verbose;
3637 foreach my $chain (sort keys %$active_chains) {
3638 if (!defined($ruleset->{$chain})) {
3639 my $sig = $active_chains->{$chain};
3640 $statushash->{$chain}->{action} = 'delete';
3641 $statushash->{$chain}->{sig} = $sig;
3642 print "delete $chain ($sig)\n" if $verbose;
3649 sub print_sig_rule {
3650 my ($chain, $sig) = @_;
3652 # We just use this to store a SHA1 checksum used to detect changes
3653 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3656 sub get_ruleset_cmdlist {
3657 my ($ruleset, $verbose, $iptablescmd) = @_;
3659 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3661 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3662 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3664 # create missing chains first
3665 foreach my $chain (sort keys %$ruleset) {
3666 my $stat = $statushash->{$chain};
3667 die "internal error" if !$stat;
3668 next if $stat->{action} ne 'create
';
3670 $cmdlist .= ":$chain - [0:0]\n";
3673 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3674 my $chain = "PVEFW-$h";
3675 if ($ruleset->{$chain} && !$hooks->{$h}) {
3676 $cmdlist .= "-A $h -j $chain\n";
3680 foreach my $chain (sort keys %$ruleset) {
3681 my $stat = $statushash->{$chain};
3682 die "internal error" if !$stat;
3684 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3685 $cmdlist .= "-F $chain\n";
3686 foreach my $cmd (@{$ruleset->{$chain}}) {
3687 $cmdlist .= "$cmd\n";
3689 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3690 } elsif ($stat->{action
} eq 'delete') {
3691 die "internal error"; # this should not happen
3692 } elsif ($stat->{action
} eq 'exists') {
3695 die "internal error - unknown status '$stat->{action}'";
3699 foreach my $chain (keys %$statushash) {
3700 next if $statushash->{$chain}->{action
} ne 'delete';
3701 $cmdlist .= "-F $chain\n";
3703 foreach my $chain (keys %$statushash) {
3704 next if $statushash->{$chain}->{action
} ne 'delete';
3705 next if $chain eq 'PVEFW-INPUT';
3706 next if $chain eq 'PVEFW-OUTPUT';
3707 next if $chain eq 'PVEFW-FORWARD';
3708 $cmdlist .= "-X $chain\n";
3711 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3713 $cmdlist .= "COMMIT\n";
3715 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3718 sub get_ipset_cmdlist
{
3719 my ($ruleset, $verbose) = @_;
3723 my $delete_cmdlist = "";
3725 my $active_chains = ipset_get_chains
();
3726 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3728 # remove stale _swap chains
3729 foreach my $chain (keys %$active_chains) {
3730 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3731 $cmdlist .= "destroy $chain\n";
3735 foreach my $chain (keys %$ruleset) {
3736 my $stat = $statushash->{$chain};
3737 die "internal error" if !$stat;
3739 if ($stat->{action
} eq 'create') {
3740 foreach my $cmd (@{$ruleset->{$chain}}) {
3741 $cmdlist .= "$cmd\n";
3746 foreach my $chain (keys %$ruleset) {
3747 my $stat = $statushash->{$chain};
3748 die "internal error" if !$stat;
3750 if ($stat->{action
} eq 'update') {
3751 my $chain_swap = $chain."_swap";
3753 foreach my $cmd (@{$ruleset->{$chain}}) {
3754 $cmd =~ s/$chain/$chain_swap/;
3755 $cmdlist .= "$cmd\n";
3757 $cmdlist .= "swap $chain_swap $chain\n";
3758 $cmdlist .= "flush $chain_swap\n";
3759 $cmdlist .= "destroy $chain_swap\n";
3763 # the remove unused chains
3764 foreach my $chain (keys %$statushash) {
3765 next if $statushash->{$chain}->{action
} ne 'delete';
3767 $delete_cmdlist .= "flush $chain\n";
3768 $delete_cmdlist .= "destroy $chain\n";
3771 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3773 return ($cmdlist, $delete_cmdlist, $changes);
3777 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3779 enable_bridge_firewall
();
3781 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3782 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3784 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3785 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3788 if ($ipset_changes) {
3789 print "ipset changes:\n";
3790 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3791 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3795 print "iptables changes:\n";
3800 print "ip6tables changes:\n";
3805 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3806 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3808 ipset_restore_cmdlist
($ipset_create_cmdlist);
3810 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3811 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3813 iptables_restore_cmdlist
($cmdlist);
3815 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3816 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3818 ip6tables_restore_cmdlist
($cmdlistv6);
3820 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3821 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3823 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3825 # test: re-read status and check if everything is up to date
3826 my $active_chains = iptables_get_chains
();
3827 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3830 foreach my $chain (sort keys %$ruleset) {
3831 my $stat = $statushash->{$chain};
3832 if ($stat->{action
} ne 'exists') {
3833 warn "unable to update chain '$chain'\n";
3838 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3839 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3841 foreach my $chain (sort keys %$rulesetv6) {
3842 my $stat = $statushashv6->{$chain};
3843 if ($stat->{action
} ne 'exists') {
3844 warn "unable to update chain '$chain'\n";
3849 die "unable to apply firewall changes\n" if $errors;
3851 update_nf_conntrack_max
($hostfw_conf);
3853 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3857 sub update_nf_conntrack_max
{
3858 my ($hostfw_conf) = @_;
3860 my $max = 65536; # reasonable default
3862 my $options = $hostfw_conf->{options
} || {};
3864 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3865 $max = $options->{nf_conntrack_max
};
3866 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3869 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3870 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3872 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3874 if ($current != $max) {
3875 my $hashsize = int($max/4);
3876 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3877 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3881 sub update_nf_conntrack_tcp_timeout_established
{
3882 my ($hostfw_conf) = @_;
3884 my $options = $hostfw_conf->{options
} || {};
3886 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3888 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3891 sub remove_pvefw_chains
{
3893 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3894 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3895 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3899 sub remove_pvefw_chains_iptables
{
3900 my ($iptablescmd) = @_;
3902 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3903 my $cmdlist = "*filter\n";
3905 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3907 $cmdlist .= "-D $h -j PVEFW-$h\n";
3911 foreach my $chain (keys %$chash) {
3912 $cmdlist .= "-F $chain\n";
3915 foreach my $chain (keys %$chash) {
3916 $cmdlist .= "-X $chain\n";
3918 $cmdlist .= "COMMIT\n";
3920 if($iptablescmd eq "ip6tables") {
3921 ip6tables_restore_cmdlist
($cmdlist);
3923 iptables_restore_cmdlist
($cmdlist);
3927 sub remove_pvefw_chains_ipset
{
3929 my $ipset_chains = ipset_get_chains
();
3933 foreach my $chain (keys %$ipset_chains) {
3934 $cmdlist .= "flush $chain\n";
3935 $cmdlist .= "destroy $chain\n";
3938 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3942 my $cluster_conf = load_clusterfw_conf
();
3943 my $cluster_options = $cluster_conf->{options
};
3944 my $enable = $cluster_options->{enable
};
3948 # load required modules here
3954 my $cluster_conf = load_clusterfw_conf
();
3955 my $cluster_options = $cluster_conf->{options
};
3957 if (!$cluster_options->{enable
}) {
3958 PVE
::Firewall
::remove_pvefw_chains
();
3962 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3964 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3966 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);