8 use Socket
qw(AF_INET6 inet_ntop inet_pton);
10 use PVE
::Exception
qw(raise raise_param_exc);
11 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
14 use PVE
::Tools
qw($IPV4RE $IPV6RE);
20 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
23 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
24 my $pvefw_conf_dir = "/etc/pve/firewall";
25 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
27 # dynamically include PVE::QemuServer and PVE::LXC
28 # to avoid dependency problems
31 require PVE
::QemuServer
;
32 require PVE
::QemuConfig
;
33 $have_qemu_server = 1;
43 my $pve_fw_status_dir = "/var/lib/pve-firewall";
45 mkdir $pve_fw_status_dir; # make sure this exists
47 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
48 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
49 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
51 my $max_alias_name_length = 64;
52 my $max_ipset_name_length = 64;
53 my $max_group_name_length = 18;
55 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
56 sub pve_verify_ip_or_cidr
{
57 my ($cidr, $noerr) = @_;
59 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
60 return $cidr if Net
::IP-
>new($cidr);
61 return undef if $noerr;
62 die Net
::IP
::Error
() . "\n";
64 return undef if $noerr;
65 die "value does not look like a valid IP address or CIDR network\n";
68 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
69 sub pve_verify_ip_or_cidr_or_alias
{
70 my ($cidr, $noerr) = @_;
72 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
74 return pve_verify_ip_or_cidr
($cidr, $noerr);
77 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
78 description
=> "IP set name.",
80 pattern
=> $ipset_name_pattern,
82 maxLength
=> $max_ipset_name_length,
85 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
86 description
=> "Alias name.",
88 pattern
=> $ip_alias_pattern,
90 maxLength
=> $max_alias_name_length,
93 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
94 description
=> "Log level.",
96 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
100 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
101 description
=> "Security Group name.",
103 pattern
=> $security_group_name_pattern,
105 maxLength
=> $max_group_name_length,
108 my $feature_ipset_nomatch = 0;
110 my (undef, undef, $release) = POSIX
::uname
();
111 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
112 my ($major, $minor) = ($1, $2);
113 $feature_ipset_nomatch = 1 if ($major > 3) ||
114 ($major == 3 && $minor >= 7);
119 my $nodename = PVE
::INotify
::nodename
();
121 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
123 my $default_log_level = 'nolog'; # avoid logs by default
125 my $log_level_hash = {
136 # we need to overwrite some macros for ipv6
137 my $pve_ipv6fw_macros = {
139 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
141 'NeighborDiscovery' => [
142 "IPv6 neighbor solicitation, neighbor and router advertisement",
143 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-solicitation' },
144 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-advertisement' },
145 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-solicitation' },
146 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-advertisement' },
150 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
153 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
154 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
158 # imported/converted from: /usr/share/shorewall/macro.*
159 my $pve_fw_macros = {
162 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
163 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
166 "Auth (identd) traffic",
167 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
170 "Border Gateway Protocol traffic",
171 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
174 "BitTorrent traffic for BitTorrent 3.1 and earlier",
175 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
176 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
179 "BitTorrent traffic for BitTorrent 3.2 and later",
180 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
181 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
184 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
185 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6789' },
186 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6800:7300' },
189 "Concurrent Versions System pserver traffic",
190 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
193 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
195 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
196 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
199 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
200 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
201 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
204 "Distributed Checksum Clearinghouse spam filtering mechanism",
205 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
208 "Forwarded DHCP traffic",
209 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
212 "Domain Name System traffic (upd and tcp)",
213 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
214 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
217 "Distributed Compiler service",
218 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
221 "File Transfer Protocol",
222 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
225 "Finger protocol (RFC 742)",
226 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
229 "GNUnet secure peer-to-peer networking traffic",
230 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
231 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
232 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
233 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
236 "Generic Routing Encapsulation tunneling protocol",
237 { action
=> 'PARAM', proto
=> '47' },
240 "Git distributed revision control traffic",
241 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
244 "OpenPGP HTTP keyserver protocol traffic",
245 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
248 "Hypertext Transfer Protocol (WWW)",
249 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
252 "Hypertext Transfer Protocol (WWW) over SSL",
253 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
256 "Internet Cache Protocol V2 (Squid) traffic",
257 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
260 "AOL Instant Messenger traffic",
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
264 "Internet Message Access Protocol",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
268 "Internet Message Access Protocol over SSL",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
272 "IPIP capsulation traffic",
273 { action
=> 'PARAM', proto
=> '94' },
277 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
278 { action
=> 'PARAM', proto
=> '50' },
281 "IPsec authentication (AH) traffic",
282 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
283 { action
=> 'PARAM', proto
=> '51' },
286 "IPsec traffic and Nat-Traversal",
287 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
288 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
289 { action
=> 'PARAM', proto
=> '50' },
292 "Internet Relay Chat traffic",
293 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
296 "HP Jetdirect printing",
297 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
300 "Layer 2 Tunneling Protocol traffic",
301 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
304 "Lightweight Directory Access Protocol traffic",
305 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
308 "Secure Lightweight Directory Access Protocol traffic",
309 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
312 "Microsoft Notification Protocol",
313 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
316 "Microsoft SQL Server",
317 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
320 "Mail traffic (SMTP, SMTPS, Submission)",
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
322 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
323 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
327 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5353' },
330 "Munin networked resource monitoring traffic",
331 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
335 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
338 "NNTP traffic (Usenet).",
339 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
342 "Encrypted NNTP traffic (Usenet)",
343 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
346 "Network Time Protocol (ntpd)",
347 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
350 "OSPF multicast traffic",
351 { action
=> 'PARAM', proto
=> '89' },
355 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
358 "Symantec PCAnywere (tm)",
359 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
360 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
364 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
367 "Encrypted POP3 traffic",
368 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
371 "Point-to-Point Tunneling Protocol",
372 { action
=> 'PARAM', proto
=> '47' },
373 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
377 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
381 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
384 "Line Printer protocol printing",
385 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
388 "Microsoft Remote Desktop Protocol traffic",
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
392 "Routing Information Protocol (bidirectional)",
393 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
396 "BIND remote management protocol",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
400 "Razor Antispam System",
401 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
404 "Remote time retrieval (rdate)",
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
409 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
412 "SANE network scanning",
413 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
416 "Microsoft SMB traffic",
417 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
418 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
419 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
420 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
423 "Samba Web Administration Tool",
424 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
427 "Simple Mail Transfer Protocol",
428 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
431 "Encrypted Simple Mail Transfer Protocol",
432 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
435 "Simple Network Management Protocol",
436 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
440 "Spam Assassin SPAMD traffic",
441 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
444 "Secure shell traffic",
445 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
448 "Subversion server (svnserve)",
449 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
452 "SixXS IPv6 Deployment and Tunnel Broker",
453 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
454 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
455 { action
=> 'PARAM', proto
=> '41' },
456 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
459 "Squid web proxy traffic",
460 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
463 "Mail message submission traffic",
464 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
467 "Syslog protocol (RFC 5424) traffic",
468 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
469 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
472 "Trivial File Transfer Protocol traffic",
473 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
477 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
481 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
484 "RFC 868 Time protocol",
485 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
488 "Traceroute (for up to 30 hops) traffic",
489 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
490 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
493 "VNC traffic for VNC display's 0 - 99",
494 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
497 "VNC traffic from Vncservers to Vncviewers in listen mode",
498 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
501 "WWW traffic (HTTP and HTTPS)",
502 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
503 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
506 "Web Cache/Proxy traffic (port 8080)",
507 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
511 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
514 "Whois (nicname, RFC 3912) traffic",
515 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
519 my $pve_fw_parsed_macros;
520 my $pve_fw_macro_descr;
521 my $pve_fw_macro_ipversion = {};
522 my $pve_fw_preferred_macro_names = {};
524 my $FWACCEPTMARK_ON = "0x80000000/0x80000000";
525 my $FWACCEPTMARK_OFF = "0x00000000/0x80000000";
527 my $pve_std_chains = {};
528 $pve_std_chains->{4} = {
529 'PVEFW-SET-ACCEPT-MARK' => [
530 "-j MARK --set-mark $FWACCEPTMARK_ON",
532 'PVEFW-DropBroadcast' => [
533 # same as shorewall 'Broadcast'
534 # simply DROP BROADCAST/MULTICAST/ANYCAST
535 # we can use this to reduce logging
536 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
537 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
538 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
539 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
542 # same as shorewall 'reject'
543 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
544 { action
=> 'DROP', source
=> '224.0.0.0/4' },
545 { action
=> 'DROP', proto
=> 'icmp' },
546 "-p tcp -j REJECT --reject-with tcp-reset",
547 "-p udp -j REJECT --reject-with icmp-port-unreachable",
548 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
549 "-j REJECT --reject-with icmp-host-prohibited",
552 # same as shorewall 'Drop', which is equal to DROP,
553 # but REJECT/DROP some packages to reduce logging,
554 # and ACCEPT critical ICMP types
555 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
556 # we are not interested in BROADCAST/MULTICAST/ANYCAST
557 { action
=> 'PVEFW-DropBroadcast' },
558 # ACCEPT critical ICMP types
559 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
560 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
561 # Drop packets with INVALID state
562 "-m conntrack --ctstate INVALID -j DROP",
563 # Drop Microsoft SMB noise
564 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
565 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
566 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
567 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
568 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
569 # Drop new/NotSyn traffic so that it doesn't get logged
570 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
572 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
575 # same as shorewall 'Reject', which is equal to Reject,
576 # but REJECT/DROP some packages to reduce logging,
577 # and ACCEPT critical ICMP types
578 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
579 # we are not interested in BROADCAST/MULTICAST/ANYCAST
580 { action
=> 'PVEFW-DropBroadcast' },
581 # ACCEPT critical ICMP types
582 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
583 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
584 # Drop packets with INVALID state
585 "-m conntrack --ctstate INVALID -j DROP",
586 # Drop Microsoft SMB noise
587 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
588 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
589 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
590 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
591 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
592 # Drop new/NotSyn traffic so that it doesn't get logged
593 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
595 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
597 'PVEFW-tcpflags' => [
598 # same as shorewall tcpflags action.
599 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
600 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
601 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
602 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
603 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
604 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
607 # same as shorewall smurfs action
608 # Filter packets for smurfs (packets with a broadcast address as the source).
609 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
610 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
611 "-s 224.0.0.0/4 -g PVEFW-smurflog",
615 $pve_std_chains->{6} = {
616 'PVEFW-SET-ACCEPT-MARK' => [
617 "-j MARK --set-mark $FWACCEPTMARK_ON",
619 'PVEFW-DropBroadcast' => [
620 # same as shorewall 'Broadcast'
621 # simply DROP BROADCAST/MULTICAST/ANYCAST
622 # we can use this to reduce logging
623 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
624 # ipv6 addrtype does not work with kernel 2.6.32
625 #{ action => 'DROP', dsttype => 'MULTICAST' },
626 #{ action => 'DROP', dsttype => 'ANYCAST' },
627 { action
=> 'DROP', dest
=> 'ff00::/8' },
628 #{ action => 'DROP', dest => '224.0.0.0/4' },
631 # same as shorewall 'reject'
632 #{ action => 'DROP', dsttype => 'BROADCAST' },
633 #{ action => 'DROP', source => '224.0.0.0/4' },
634 { action
=> 'DROP', proto
=> 'icmpv6' },
635 "-p tcp -j REJECT --reject-with tcp-reset",
636 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
637 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
638 #"-j REJECT --reject-with icmp-host-prohibited",
641 # same as shorewall 'Drop', which is equal to DROP,
642 # but REJECT/DROP some packages to reduce logging,
643 # and ACCEPT critical ICMP types
644 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
645 # we are not interested in BROADCAST/MULTICAST/ANYCAST
646 { action
=> 'PVEFW-DropBroadcast' },
647 # ACCEPT critical ICMP types
648 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
649 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
650 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
652 # Drop packets with INVALID state
653 "-m conntrack --ctstate INVALID -j DROP",
654 # Drop Microsoft SMB noise
655 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
656 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
657 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
658 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
659 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
660 # Drop new/NotSyn traffic so that it doesn't get logged
661 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
663 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
666 # same as shorewall 'Reject', which is equal to Reject,
667 # but REJECT/DROP some packages to reduce logging,
668 # and ACCEPT critical ICMP types
669 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
670 # we are not interested in BROADCAST/MULTICAST/ANYCAST
671 { action
=> 'PVEFW-DropBroadcast' },
672 # ACCEPT critical ICMP types
673 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
674 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
675 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
677 # Drop packets with INVALID state
678 "-m conntrack --ctstate INVALID -j DROP",
679 # Drop Microsoft SMB noise
680 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
681 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
682 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
683 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
684 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
685 # Drop new/NotSyn traffic so that it doesn't get logged
686 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
688 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
690 'PVEFW-tcpflags' => [
691 # same as shorewall tcpflags action.
692 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
693 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
694 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
695 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
696 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
697 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
701 # iptables -p icmp -h
702 my $icmp_type_names = {
705 'destination-unreachable' => 1,
706 'network-unreachable' => 1,
707 'host-unreachable' => 1,
708 'protocol-unreachable' => 1,
709 'port-unreachable' => 1,
710 'fragmentation-needed' => 1,
711 'source-route-failed' => 1,
712 'network-unknown' => 1,
714 'network-prohibited' => 1,
715 'host-prohibited' => 1,
716 'TOS-network-unreachable' => 1,
717 'TOS-host-unreachable' => 1,
718 'communication-prohibited' => 1,
719 'host-precedence-violation' => 1,
720 'precedence-cutoff' => 1,
721 'source-quench' => 1,
723 'network-redirect' => 1,
724 'host-redirect' => 1,
725 'TOS-network-redirect' => 1,
726 'TOS-host-redirect' => 1,
728 'router-advertisement' => 1,
729 'router-solicitation' => 1,
730 'time-exceeded' => 1,
731 'ttl-zero-during-transit' => 1,
732 'ttl-zero-during-reassembly' => 1,
733 'parameter-problem' => 1,
734 'ip-header-bad' => 1,
735 'required-option-missing' => 1,
736 'timestamp-request' => 1,
737 'timestamp-reply' => 1,
738 'address-mask-request' => 1,
739 'address-mask-reply' => 1,
742 # ip6tables -p icmpv6 -h
744 my $icmpv6_type_names = {
746 'destination-unreachable' => 1,
748 'communication-prohibited' => 1,
749 'address-unreachable' => 1,
750 'port-unreachable' => 1,
751 'packet-too-big' => 1,
752 'time-exceeded' => 1,
753 'ttl-zero-during-transit' => 1,
754 'ttl-zero-during-reassembly' => 1,
755 'parameter-problem' => 1,
757 'unknown-header-type' => 1,
758 'unknown-option' => 1,
761 'router-solicitation' => 1,
762 'router-advertisement' => 1,
763 'neighbor-solicitation' => 1,
764 'neighbour-solicitation' => 1,
765 'neighbor-advertisement' => 1,
766 'neighbour-advertisement' => 1,
770 sub init_firewall_macros
{
772 $pve_fw_parsed_macros = {};
775 my ($k, $macro) = @_;
776 my $lc_name = lc($k);
777 $pve_fw_macro_ipversion->{$k} = 0;
778 while (!ref($macro->[0])) {
779 my $desc = shift @$macro;
780 if ($desc eq 'ipv4only') {
781 $pve_fw_macro_ipversion->{$k} = 4;
782 } elsif ($desc eq 'ipv6only') {
783 $pve_fw_macro_ipversion->{$k} = 6;
785 $pve_fw_macro_descr->{$k} = $desc;
788 $pve_fw_preferred_macro_names->{$lc_name} = $k;
789 $pve_fw_parsed_macros->{$k} = $macro;
792 foreach my $k (keys %$pve_fw_macros) {
793 &$parse($k, $pve_fw_macros->{$k});
796 foreach my $k (keys %$pve_ipv6fw_macros) {
797 next if $pve_fw_parsed_macros->{$k};
798 &$parse($k, $pve_ipv6fw_macros->{$k});
799 $pve_fw_macro_ipversion->{$k} = 6;
803 init_firewall_macros
();
806 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
811 sub get_etc_services
{
813 return $etc_services if $etc_services;
815 my $filename = "/etc/services";
817 my $fh = IO
::File-
>new($filename, O_RDONLY
);
819 warn "unable to read '$filename' - $!\n";
825 while (my $line = <$fh>) {
827 next if $line =~m/^#/;
828 next if ($line =~m/^\s*$/);
830 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
831 $services->{byid
}->{$2}->{name
} = $1;
832 $services->{byid
}->{$2}->{port
} = $2;
833 $services->{byid
}->{$2}->{$3} = 1;
834 $services->{byname
}->{$1} = $services->{byid
}->{$2};
840 $etc_services = $services;
843 return $etc_services;
848 sub get_etc_protocols
{
849 return $etc_protocols if $etc_protocols;
851 my $filename = "/etc/protocols";
853 my $fh = IO
::File-
>new($filename, O_RDONLY
);
855 warn "unable to read '$filename' - $!\n";
861 while (my $line = <$fh>) {
863 next if $line =~m/^#/;
864 next if ($line =~m/^\s*$/);
866 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
867 $protocols->{byid
}->{$2}->{name
} = $1;
868 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
874 # add special case for ICMP v6
875 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
876 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
878 $etc_protocols = $protocols;
880 return $etc_protocols;
886 my ($new_value) = @_;
888 $__local_network = $new_value if defined($new_value);
890 return $__local_network if defined($__local_network);
893 my $nodename = PVE
::INotify
::nodename
();
895 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
897 my $testip = Net
::IP-
>new($ip);
899 my $isv6 = $testip->version == 6;
900 my $routes = $isv6 ? PVE
::ProcFSTools
::read_proc_net_ipv6_route
()
901 : PVE
::ProcFSTools
::read_proc_net_route
();
902 foreach my $entry (@$routes) {
905 $mask = $entry->{prefix
};
907 $mask = $PVE::Network
::ipv4_mask_hash_localnet-
>{$entry->{mask
}};
908 next if !defined($mask);
910 my $cidr = "$entry->{dest}/$mask";
911 my $testnet = Net
::IP-
>new($cidr);
912 if ($testnet->overlaps($testip) == $Net::IP
::IP_B_IN_A_OVERLAP
) {
913 $__local_network = $cidr;
920 return $__local_network;
923 # ipset names are limited to 31 characters,
924 # and we use '-v4' or '-v6' to indicate IP versions,
925 # and we use '_swap' suffix for atomic update,
926 # for example PVEFW-${VMID}-${ipset_name}_swap
928 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
930 sub compute_ipset_chain_name
{
931 my ($vmid, $ipset_name, $ipversion) = @_;
933 $vmid = 0 if !defined($vmid);
935 my $id = "$vmid-${ipset_name}-v$ipversion";
937 if (length($id) > $max_iptables_ipset_name_length) {
938 $id = PVE
::Tools
::fnv31a_hex
($id);
944 sub compute_ipfilter_ipset_name
{
947 return "ipfilter-$iface";
950 sub parse_address_list
{
953 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
954 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
958 if ($str =~ m/^${ip_alias_pattern}$/) {
959 die "alias name too long\n" if length($str) > $max_alias_name_length;
967 foreach my $elem (split(/,/, $str)) {
969 my $ip = Net
::IP-
>new($elem);
971 my $err = Net
::IP
::Error
();
972 die "invalid IP address: $err\n";
974 $iprange = 1 if $elem =~ m/-/;
976 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
978 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
979 if $ipversion && ($new_ipversion != $ipversion);
981 $ipversion = $new_ipversion;
984 die "you can't use a range in a list\n" if $iprange && $count > 1;
989 sub parse_port_name_number_or_range
{
990 my ($str, $dport) = @_;
992 my $services = PVE
::Firewall
::get_etc_services
();
996 foreach my $item (split(/,/, $str)) {
998 if ($item =~ m/^(\d+):(\d+)$/) {
999 my ($port1, $port2) = ($1, $2);
1000 die "invalid port '$port1'\n" if $port1 > 65535;
1001 die "invalid port '$port2'\n" if $port2 > 65535;
1002 } elsif ($item =~ m/^(\d+)$/) {
1004 die "invalid port '$port'\n" if $port > 65535;
1006 if ($dport && $icmp_type_names->{$item}) {
1008 } elsif ($dport && $icmpv6_type_names->{$item}) {
1011 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1016 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1021 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1022 sub pve_fw_verify_sport_spec
{
1025 parse_port_name_number_or_range
($portstr, 0);
1030 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1031 sub pve_fw_verify_dport_spec
{
1034 parse_port_name_number_or_range
($portstr, 1);
1039 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1040 sub pve_fw_verify_addr_spec
{
1043 parse_address_list
($list);
1048 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1049 sub pve_fw_verify_protocol_spec
{
1052 my $protocols = get_etc_protocols
();
1054 die "unknown protocol '$proto'\n" if $proto &&
1055 !(defined($protocols->{byname
}->{$proto}) ||
1056 defined($protocols->{byid
}->{$proto}));
1062 # helper function for API
1064 sub copy_opject_with_digest
{
1067 my $sha = Digest
::SHA-
>new('sha1');
1070 foreach my $k (sort keys %$object) {
1071 my $v = $object->{$k};
1072 next if !defined($v);
1074 $sha->add($k, ':', $v, "\n");
1077 my $digest = $sha->hexdigest;
1079 $res->{digest
} = $digest;
1081 return wantarray ?
($res, $digest) : $res;
1084 sub copy_list_with_digest
{
1087 my $sha = Digest
::SHA-
>new('sha1');
1090 foreach my $entry (@$list) {
1092 foreach my $k (sort keys %$entry) {
1093 my $v = $entry->{$k};
1094 next if !defined($v);
1096 # Note: digest ignores refs ($rule->{errors})
1097 # since Digest::SHA expects a series of bytes,
1098 # we have to encode the value here to prevent errors when
1099 # using utf8 characters (eg. in comments)
1100 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1105 my $digest = $sha->hexdigest;
1107 foreach my $entry (@$res) {
1108 $entry->{digest
} = $digest;
1111 return wantarray ?
($res, $digest) : $res;
1114 our $cluster_option_properties = {
1116 description
=> "Enable or disable the firewall cluster wide.",
1122 description
=> "Input policy.",
1125 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1128 description
=> "Output policy.",
1131 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1135 our $host_option_properties = {
1137 description
=> "Enable host firewall rules.",
1141 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1142 description
=> "Log level for incoming traffic." }),
1143 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1144 description
=> "Log level for outgoing traffic." }),
1145 tcp_flags_log_level
=> get_standard_option
('pve-fw-loglevel', {
1146 description
=> "Log level for illegal tcp flags filter." }),
1147 smurf_log_level
=> get_standard_option
('pve-fw-loglevel', {
1148 description
=> "Log level for SMURFS filter." }),
1150 description
=> "Enable SMURFS filter.",
1155 description
=> "Filter illegal combinations of TCP flags.",
1159 nf_conntrack_max
=> {
1160 description
=> "Maximum number of tracked connections.",
1165 nf_conntrack_tcp_timeout_established
=> {
1166 description
=> "Conntrack established timeout.",
1172 description
=> "Enable NDP.",
1178 our $vm_option_properties = {
1180 description
=> "Enable/disable firewall rules.",
1185 description
=> "Enable/disable MAC address filter.",
1190 description
=> "Enable DHCP.",
1195 description
=> "Enable NDP.",
1200 description
=> "Allow sending Router Advertisement.",
1205 description
=> "Enable default IP filters. " .
1206 "This is equivalent to adding an empty ipfilter-net<id> ipset " .
1207 "for every interface. Such ipsets implicitly contain sane default " .
1208 "restrictions such as restricting IPv6 link local addresses to " .
1209 "the one derived from the interface's MAC address. For containers " .
1210 "the configured IP addresses will be implicitly added.",
1215 description
=> "Input policy.",
1218 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1221 description
=> "Output policy.",
1224 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1226 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1227 description
=> "Log level for incoming traffic." }),
1228 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1229 description
=> "Log level for outgoing traffic." }),
1234 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.";
1236 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.";
1238 my $rule_properties = {
1240 description
=> "Update rule at position <pos>.",
1245 digest
=> get_standard_option
('pve-config-digest'),
1247 description
=> "Rule type.",
1250 enum
=> ['in', 'out', 'group'],
1253 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1256 pattern
=> $security_group_name_pattern,
1261 description
=> "Use predefined standard macro.",
1266 iface
=> get_standard_option
('pve-iface', {
1267 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.",
1271 description
=> "Restrict packet source address. $addr_list_descr",
1272 type
=> 'string', format
=> 'pve-fw-addr-spec',
1276 description
=> "Restrict packet destination address. $addr_list_descr",
1277 type
=> 'string', format
=> 'pve-fw-addr-spec',
1281 description
=> "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
1282 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1286 description
=> "Flag to enable/disable a rule.",
1292 description
=> "Restrict TCP/UDP source port. $port_descr",
1293 type
=> 'string', format
=> 'pve-fw-sport-spec',
1297 description
=> "Restrict TCP/UDP destination port. $port_descr",
1298 type
=> 'string', format
=> 'pve-fw-dport-spec',
1302 description
=> "Descriptive comment.",
1308 sub add_rule_properties
{
1309 my ($properties) = @_;
1311 foreach my $k (keys %$rule_properties) {
1312 my $h = $rule_properties->{$k};
1313 # copy data, so that we can modify later without side effects
1314 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1320 sub delete_rule_properties
{
1321 my ($rule, $delete_str) = @_;
1323 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1324 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1325 if !defined($rule_properties->{$opt});
1326 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1327 if $opt eq 'type' || $opt eq 'action';
1328 delete $rule->{$opt};
1334 my $apply_macro = sub {
1335 my ($macro_name, $param, $verify, $ipversion) = @_;
1337 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1338 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1340 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1341 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1344 # skip macros which are specific to another ipversion
1345 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1346 return if $ipversion != $required;
1351 foreach my $templ (@$macro_rules) {
1353 my $param_used = {};
1354 foreach my $k (keys %$templ) {
1355 my $v = $templ->{$k};
1356 if ($v eq 'PARAM') {
1358 $param_used->{$k} = 1;
1359 } elsif ($v eq 'DEST') {
1360 $v = $param->{dest
};
1361 $param_used->{dest
} = 1;
1362 } elsif ($v eq 'SOURCE') {
1363 $v = $param->{source
};
1364 $param_used->{source
} = 1;
1368 my $msg = "missing parameter '$k' in macro '$macro_name'";
1369 raise_param_exc
({ macro => $msg }) if $verify;
1374 foreach my $k (keys %$param) {
1375 next if $k eq 'macro';
1376 next if !defined($param->{$k});
1377 next if $param_used->{$k};
1378 if (defined($rule->{$k})) {
1379 if ($rule->{$k} ne $param->{$k}) {
1380 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1381 raise_param_exc
({ $k => $msg }) if $verify;
1385 $rule->{$k} = $param->{$k};
1388 push @$rules, $rule;
1394 my $rule_env_iface_lookup = {
1403 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1405 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1407 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1408 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1410 my $errors = $rule->{errors
} || {};
1412 my $error_count = 0;
1414 my $add_error = sub {
1415 my ($param, $msg) = @_;
1417 raise_param_exc
({ $param => $msg }) if !$noerr;
1419 $errors->{$param} = $msg if !$errors->{$param};
1423 my $set_ip_version = sub {
1426 die "detected mixed ipv4/ipv6 adresses in rule\n"
1427 if $ipversion && ($vers != $ipversion);
1432 my $check_ipset_or_alias_property = sub {
1433 my ($name, $expected_ipversion) = @_;
1435 if (my $value = $rule->{$name}) {
1436 if ($value =~ m/^\+/) {
1437 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1438 &$add_error($name, "no such ipset '$1'")
1439 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1442 &$add_error($name, "invalid ipset name '$value'");
1444 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1445 my $alias = lc($value);
1446 &$add_error($name, "no such alias '$value'")
1447 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1448 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1449 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1451 &$set_ip_version($e->{ipversion
});
1456 my $type = $rule->{type
};
1457 my $action = $rule->{action
};
1459 &$add_error('type', "missing property") if !$type;
1460 &$add_error('action', "missing property") if !$action;
1463 if ($type eq 'in' || $type eq 'out') {
1464 &$add_error('action', "unknown action '$action'")
1465 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1466 } elsif ($type eq 'group') {
1467 &$add_error('type', "security groups not allowed")
1469 &$add_error('action', "invalid characters in security group name")
1470 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1472 &$add_error('type', "unknown rule type '$type'");
1476 if ($rule->{iface
}) {
1477 &$add_error('type', "parameter -i not allowed for this rule type")
1479 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1480 &$add_error('iface', $@) if $@;
1481 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1482 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1483 if $rule->{iface
} !~ m/^net(\d+)$/;
1487 if ($rule->{macro}) {
1488 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1489 $rule->{macro} = $preferred_name;
1491 &$add_error('macro', "unknown macro '$rule->{macro}'");
1495 if ($rule->{proto
}) {
1496 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1497 &$add_error('proto', $@) if $@;
1498 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1499 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1502 if ($rule->{dport
}) {
1503 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1504 &$add_error('dport', $@) if $@;
1505 &$add_error('proto', "missing property - 'dport' requires this property")
1509 if ($rule->{sport
}) {
1510 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1511 &$add_error('sport', $@) if $@;
1512 &$add_error('proto', "missing property - 'sport' requires this property")
1516 if ($rule->{source
}) {
1518 my $source_ipversion = parse_address_list
($rule->{source
});
1519 &$set_ip_version($source_ipversion);
1521 &$add_error('source', $@) if $@;
1522 &$check_ipset_or_alias_property('source', $ipversion);
1525 if ($rule->{dest
}) {
1527 my $dest_ipversion = parse_address_list
($rule->{dest
});
1528 &$set_ip_version($dest_ipversion);
1530 &$add_error('dest', $@) if $@;
1531 &$check_ipset_or_alias_property('dest', $ipversion);
1534 $rule->{ipversion
} = $ipversion if $ipversion;
1536 if ($rule->{macro} && !$error_count) {
1537 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1539 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1540 my $eh = $err->{errors
};
1541 foreach my $p (keys %$eh) {
1542 &$add_error($p, $eh->{$p});
1545 &$add_error('macro', "$err");
1550 $rule->{errors
} = $errors if $error_count;
1555 sub copy_rule_data
{
1556 my ($rule, $param) = @_;
1558 foreach my $k (keys %$rule_properties) {
1559 if (defined(my $v = $param->{$k})) {
1560 if ($v eq '' || $v eq '-') {
1571 sub rules_modify_permissions
{
1572 my ($rule_env) = @_;
1574 if ($rule_env eq 'host') {
1576 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1578 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1580 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1582 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1584 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1591 sub rules_audit_permissions
{
1592 my ($rule_env) = @_;
1594 if ($rule_env eq 'host') {
1596 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1598 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1600 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1602 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1604 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1612 my $bridge_firewall_enabled = 0;
1614 sub enable_bridge_firewall
{
1616 return if $bridge_firewall_enabled; # only once
1618 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1619 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1621 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1622 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1624 $bridge_firewall_enabled = 1;
1627 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1629 sub iptables_restore_cmdlist
{
1632 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1635 sub ip6tables_restore_cmdlist
{
1638 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1641 sub ipset_restore_cmdlist
{
1644 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1647 sub iptables_get_chains
{
1648 my ($iptablescmd) = @_;
1650 $iptablescmd = "iptables" if !$iptablescmd;
1654 # check what chains we want to track
1655 my $is_pvefw_chain = sub {
1658 return 1 if $name =~ m/^PVEFW-\S+$/;
1660 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1662 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1664 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1665 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1677 return if $line =~ m/^#/;
1678 return if $line =~ m/^\s*$/;
1680 if ($line =~ m/^\*(\S+)$/) {
1685 return if $table ne 'filter';
1687 if ($line =~ m/^:(\S+)\s/) {
1689 return if !&$is_pvefw_chain($chain);
1690 $res->{$chain} = "unknown";
1691 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1692 my ($chain, $sig) = ($1, $2);
1693 return if !&$is_pvefw_chain($chain);
1694 $res->{$chain} = $sig;
1695 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1698 # simply ignore the rest
1703 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1705 return wantarray ?
($res, $hooks) : $res;
1708 sub iptables_chain_digest
{
1710 my $digest = Digest
::SHA-
>new('sha1');
1711 foreach my $rule (@$rules) { # order is important
1712 $digest->add($rule);
1714 return $digest->b64digest;
1717 sub ipset_chain_digest
{
1720 my $digest = Digest
::SHA-
>new('sha1');
1721 foreach my $rule (sort @$rules) { # note: sorted
1722 $digest->add($rule);
1724 return $digest->b64digest;
1727 sub ipset_get_chains
{
1735 return if $line =~ m/^#/;
1736 return if $line =~ m/^\s*$/;
1737 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1739 $line =~ s/\s+$//; # delete trailing white space
1740 push @{$chains->{$chain}}, $line;
1742 # simply ignore the rest
1747 run_command
("/sbin/ipset save", outfunc
=> $parser);
1749 # compute digest for each chain
1750 foreach my $chain (keys %$chains) {
1751 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1757 sub ruleset_generate_cmdstr
{
1758 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1760 return if defined($rule->{enable
}) && !$rule->{enable
};
1761 return if $rule->{errors
};
1763 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1765 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1766 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1770 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1771 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1773 my $source = $rule->{source
};
1774 my $dest = $rule->{dest
};
1777 if ($source =~ m/^\+/) {
1778 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1780 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1781 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1782 push @cmd, "-m set --match-set ${ipset_chain} src";
1783 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1784 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1785 push @cmd, "-m set --match-set ${ipset_chain} src";
1787 die "no such ipset '$name'\n";
1790 die "invalid security group name '$source'\n";
1792 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1793 my $alias = lc($source);
1794 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1795 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1796 die "no such alias '$source'\n" if !$e;
1797 push @cmd, "-s $e->{cidr}";
1798 } elsif ($source =~ m/\-/){
1799 push @cmd, "-m iprange --src-range $source";
1801 push @cmd, "-s $source";
1806 if ($dest =~ m/^\+/) {
1807 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1809 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1810 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1811 push @cmd, "-m set --match-set ${ipset_chain} dst";
1812 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1813 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1814 push @cmd, "-m set --match-set ${ipset_chain} dst";
1816 die "no such ipset '$name'\n";
1819 die "invalid security group name '$dest'\n";
1821 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1822 my $alias = lc($dest);
1823 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1824 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1825 die "no such alias '$dest'\n" if !$e;
1826 push @cmd, "-d $e->{cidr}";
1827 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1828 push @cmd, "-m iprange --dst-range $dest";
1830 push @cmd, "-d $dest";
1834 if (my $proto = $rule->{proto
}) {
1835 push @cmd, "-p $proto";
1838 $multiport++ if $nbdport > 1;
1839 $multiport++ if $nbsport > 1;
1841 push @cmd, "--match multiport" if $multiport;
1843 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1844 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1846 if ($rule->{dport
}) {
1847 if ($proto eq 'icmp') {
1848 # Note: we use dport to store --icmp-type
1849 die "unknown icmp-type '$rule->{dport}'\n"
1850 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1851 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1852 } elsif ($proto eq 'icmpv6') {
1853 # Note: we use dport to store --icmpv6-type
1854 die "unknown icmpv6-type '$rule->{dport}'\n"
1855 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1856 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1859 if ($multiport == 2) {
1860 push @cmd, "--ports $rule->{dport}";
1862 push @cmd, "--dports $rule->{dport}";
1865 push @cmd, "--dport $rule->{dport}";
1870 if ($rule->{sport
}) {
1872 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1874 push @cmd, "--sport $rule->{sport}";
1877 } elsif ($rule->{dport
} || $rule->{sport
}) {
1878 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1879 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1882 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1884 if (my $action = $rule->{action
}) {
1885 $action = $actions->{$action} if defined($actions->{$action});
1886 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1887 push @cmd, $goto ?
"-g $action" : "-j $action";
1890 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1893 sub ruleset_generate_rule
{
1894 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1898 if ($rule->{macro}) {
1899 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1904 # update all or nothing
1907 foreach my $tmp (@$rules) {
1908 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1909 push @cmds, $cmdstr;
1913 foreach my $cmdstr (@cmds) {
1914 ruleset_addrule
($ruleset, $chain, $cmdstr);
1918 sub ruleset_generate_rule_insert
{
1919 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1921 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1923 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1924 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1928 sub ruleset_create_chain
{
1929 my ($ruleset, $chain) = @_;
1931 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1932 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1934 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1936 $ruleset->{$chain} = [];
1939 sub ruleset_chain_exist
{
1940 my ($ruleset, $chain) = @_;
1942 return $ruleset->{$chain} ?
1 : undef;
1945 sub ruleset_addrule
{
1946 my ($ruleset, $chain, $rule) = @_;
1948 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1950 push @{$ruleset->{$chain}}, "-A $chain $rule";
1953 sub ruleset_insertrule
{
1954 my ($ruleset, $chain, $rule) = @_;
1956 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1958 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1961 sub get_log_rule_base
{
1962 my ($chain, $vmid, $msg, $loglevel) = @_;
1964 die "internal error - no log level" if !defined($loglevel);
1966 $vmid = 0 if !defined($vmid);
1968 # Note: we use special format for prefix to pass further
1969 # info to log daemon (VMID, LOGVELEL and CHAIN)
1971 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1974 sub ruleset_addlog {
1975 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1977 return if !defined($loglevel);
1979 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1981 $logrule = "$rule $logrule" if defined($rule);
1983 ruleset_addrule($ruleset, $chain, $logrule);
1986 sub ruleset_add_chain_policy {
1987 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1989 if ($policy eq 'ACCEPT') {
1991 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
1992 { ACCEPT => $accept_action});
1994 } elsif ($policy eq 'DROP') {
1996 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1998 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
2000 ruleset_addrule($ruleset, $chain, "-j DROP
");
2001 } elsif ($policy eq 'REJECT') {
2002 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
2004 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
2006 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
2009 die "internal error
: unknown policy
'$policy'";
2013 sub ruleset_chain_add_ndp {
2014 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
2015 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2017 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
$accept");
2018 if ($direction ne 'OUT' || $options->{radv}) {
2019 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
$accept");
2021 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
$accept");
2022 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
$accept");
2025 sub ruleset_chain_add_conn_filters {
2026 my ($ruleset, $chain, $accept) = @_;
2028 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
2029 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
2032 sub ruleset_chain_add_input_filters {
2033 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2035 if ($cluster_conf->{ipset}->{blacklist}){
2036 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
2037 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
2038 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
2039 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
2041 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
2042 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
2045 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
2046 if ($ipversion == 4) {
2047 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
2051 if ($options->{tcpflags}) {
2052 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
2056 sub ruleset_create_vm_chain {
2057 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
2059 ruleset_create_chain($ruleset, $chain);
2060 my $accept = generate_nfqueue($options);
2062 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
2063 if ($ipversion == 4) {
2064 if ($direction eq 'OUT') {
2065 ruleset_generate_rule($ruleset, $chain, $ipversion,
2066 { action => 'PVEFW-SET-ACCEPT-MARK',
2067 proto => 'udp', sport => 68, dport => 67 });
2069 ruleset_generate_rule($ruleset, $chain, $ipversion,
2070 { action => 'ACCEPT',
2071 proto => 'udp', sport => 67, dport => 68 });
2073 } elsif ($ipversion == 6) {
2074 if ($direction eq 'OUT') {
2075 ruleset_generate_rule($ruleset, $chain, $ipversion,
2076 { action => 'PVEFW-SET-ACCEPT-MARK',
2077 proto => 'udp', sport => 546, dport => 547 });
2079 ruleset_generate_rule($ruleset, $chain, $ipversion,
2080 { action => 'ACCEPT',
2081 proto => 'udp', sport => 547, dport => 546 });
2087 if ($direction eq 'OUT') {
2088 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
2089 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
2091 if ($ipversion == 6 && !$options->{radv}) {
2092 ruleset_addrule($ruleset, $chain, '-p icmpv6 --icmpv6-type router-advertisement -j DROP');
2094 if ($ipfilter_ipset) {
2095 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
2097 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2100 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
2101 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
2104 sub ruleset_add_group_rule {
2105 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
2107 my $group = $rule->{action};
2108 my $group_chain = "GROUP-
$group-$direction";
2109 if(!ruleset_chain_exist($ruleset, $group_chain)){
2110 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
2113 if ($direction eq 'OUT' && $rule->{iface_out}) {
2114 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
2115 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2116 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
2118 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
2121 ruleset_addrule($ruleset, $chain, "-m mark
--mark
$FWACCEPTMARK_ON -j
$action");
2124 sub ruleset_generate_vm_rules {
2125 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2127 my $lc_direction = lc($direction);
2129 my $in_accept = generate_nfqueue($options);
2131 foreach my $rule (@$rules) {
2132 next if $rule->{iface} && $rule->{iface} ne $netid;
2133 next if !$rule->{enable} || $rule->{errors};
2134 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2136 if ($rule->{type} eq 'group') {
2137 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2138 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2140 next if $rule->{type} ne $lc_direction;
2142 if ($direction eq 'OUT') {
2143 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2144 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2145 undef, $cluster_conf, $vmfw_conf);
2147 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2148 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2149 undef, $cluster_conf, $vmfw_conf);
2157 sub generate_nfqueue {
2160 if ($options->{ips}) {
2161 my $action = "NFQUEUE
";
2162 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2163 if (defined($3) && defined($1)) {
2164 $action .= " --queue-balance
$1:$3";
2165 } elsif (defined($1)) {
2166 $action .= " --queue-num
$1";
2169 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2176 sub ruleset_generate_vm_ipsrules {
2177 my ($ruleset, $options, $direction, $iface) = @_;
2179 if ($options->{ips} && $direction eq 'IN') {
2180 my $nfqueue = generate_nfqueue($options);
2182 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2183 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2186 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
2190 sub generate_tap_rules_direction {
2191 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2193 my $lc_direction = lc($direction);
2195 my $rules = $vmfw_conf->{rules};
2197 my $options = $vmfw_conf->{options};
2198 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2200 my $tapchain = "$iface-$direction";
2202 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2203 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2204 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2206 # create chain with mac and ip filter
2207 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2209 if ($options->{enable}) {
2210 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2212 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2217 if ($direction eq 'OUT') {
2218 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2220 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2223 my $accept = generate_nfqueue($options);
2224 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2225 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2227 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2228 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2231 # plug the tap chain to bridge chain
2232 if ($direction eq 'IN') {
2233 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2234 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2236 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2237 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2241 sub enable_host_firewall {
2242 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2244 my $options = $hostfw_conf->{options};
2245 my $cluster_options = $cluster_conf->{options};
2246 my $rules = $hostfw_conf->{rules};
2247 my $cluster_rules = $cluster_conf->{rules};
2249 # host inbound firewall
2250 my $chain = "PVEFW-HOST-IN
";
2251 ruleset_create_chain($ruleset, $chain);
2253 my $loglevel = get_option_log_level($options, "log_level_in
");
2255 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2257 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2258 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2259 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2261 # we use RETURN because we need to check also tap rules
2262 my $accept_action = 'RETURN';
2264 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2266 # add host rules first, so that cluster wide rules can be overwritten
2267 foreach my $rule (@$rules, @$cluster_rules) {
2268 next if !$rule->{enable} || $rule->{errors};
2269 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2271 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2274 if ($rule->{type} eq 'group') {
2275 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2276 } elsif ($rule->{type} eq 'in') {
2277 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2278 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2279 undef, $cluster_conf, $hostfw_conf);
2283 delete $rule->{iface_in};
2286 # allow standard traffic for management ipset (includes cluster network)
2287 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2288 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2289 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2290 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2291 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2292 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2294 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2295 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2298 if ($localnet && ($ipversion == $localnet_ver)) {
2299 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2300 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2301 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2304 # implement input policy
2305 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2306 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2308 # host outbound firewall
2309 $chain = "PVEFW-HOST-OUT
";
2310 ruleset_create_chain($ruleset, $chain);
2312 $loglevel = get_option_log_level($options, "log_level_out
");
2314 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2316 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2318 # we use RETURN because we may want to check other thigs later
2319 $accept_action = 'RETURN';
2320 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2322 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2324 # add host rules first, so that cluster wide rules can be overwritten
2325 foreach my $rule (@$rules, @$cluster_rules) {
2326 next if !$rule->{enable} || $rule->{errors};
2327 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2329 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2331 if ($rule->{type} eq 'group') {
2332 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2333 } elsif ($rule->{type} eq 'out') {
2334 ruleset_generate_rule($ruleset, $chain, $ipversion,
2335 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2336 undef, $cluster_conf, $hostfw_conf);
2340 delete $rule->{iface_out};
2343 # allow standard traffic on cluster network
2344 if ($localnet && ($ipversion == $localnet_ver)) {
2345 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2346 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2347 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2348 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2350 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2351 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2352 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2355 # implement output policy
2356 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2357 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2359 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2360 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2363 sub generate_group_rules {
2364 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2366 my $rules = $cluster_conf->{groups}->{$group};
2369 warn "no such security group
'$group'\n";
2370 $rules = []; # create empty chain
2373 my $chain = "GROUP-
${group
}-IN
";
2375 ruleset_create_chain($ruleset, $chain);
2376 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2378 foreach my $rule (@$rules) {
2379 next if $rule->{type} ne 'in';
2380 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2381 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2382 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2383 undef, $cluster_conf);
2386 $chain = "GROUP-
${group
}-OUT
";
2388 ruleset_create_chain($ruleset, $chain);
2389 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2391 foreach my $rule (@$rules) {
2392 next if $rule->{type} ne 'out';
2393 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2394 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2395 # check also other tap rules later
2396 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2397 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2398 undef, $cluster_conf);
2403 my $valid_netdev_names = {};
2404 for (my $i = 0; $i < $MAX_NETS; $i++) {
2405 $valid_netdev_names->{"net
$i"} = 1;
2408 sub get_mark_values {
2409 my ($value, $mask) = @_;
2410 $value = hex($value) if $value =~ /^0x/;
2411 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2412 $mask = 0xffffffff if !defined($mask);
2413 return ($value, $mask);
2417 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2419 my $orig_line = $line;
2423 # we can add single line comments to the end of the rule
2424 if ($line =~ s/#\s*(.*?)\s*$//) {
2425 $rule->{comment} = decode('utf8', $1);
2428 # we can disable a rule when prefixed with '|'
2430 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2432 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2433 die "unable to parse rule
: $line\n";
2435 $rule->{type} = lc($1);
2436 $rule->{action} = $2;
2438 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2439 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2440 $rule->{macro} = $1;
2441 $rule->{action} = $2;
2445 while (length($line)) {
2446 if ($line =~ s/^-i (\S+)\s*//) {
2447 $rule->{iface} = $1;
2451 last if $rule->{type} eq 'group';
2453 if ($line =~ s/^-p (\S+)\s*//) {
2454 $rule->{proto} = $1;
2458 if ($line =~ s/^-dport (\S+)\s*//) {
2459 $rule->{dport} = $1;
2463 if ($line =~ s/^-sport (\S+)\s*//) {
2464 $rule->{sport} = $1;
2467 if ($line =~ s/^-source (\S+)\s*//) {
2468 $rule->{source} = $1;
2471 if ($line =~ s/^-dest (\S+)\s*//) {
2479 die "unable to parse rule parameters
: $line\n" if length($line);
2481 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2482 if ($verbose && $rule->{errors}) {
2483 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2484 foreach my $p (keys %{$rule->{errors}}) {
2485 warn " $p: $rule->{errors
}->{$p}\n";
2492 sub parse_vmfw_option {
2497 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2499 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2502 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2504 $value = $2 ? lc($3) : '';
2505 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2508 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2512 die "can
't parse option '$line'\n"
2515 return ($opt, $value);
2518 sub parse_hostfw_option {
2523 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2525 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2528 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2530 $value = $2 ? lc($3) : '';
2531 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2535 die "can't parse option
'$line'\n"
2538 return ($opt, $value);
2541 sub parse_clusterfw_option {
2546 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2549 if (($value > 1) && ((time() - $value) > 60)) {
2552 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2556 die "can
't parse option '$line'\n"
2559 return ($opt, $value);
2563 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2565 my $alias = lc($cidr);
2566 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2567 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2569 die "no such alias '$cidr'\n" if !$e;;
2571 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2574 sub parse_ip_or_cidr {
2579 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2582 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2586 die "value does not look like a valid IP address or CIDR network\n";
2589 return wantarray ? ($cidr, $ipversion) : $cidr;
2595 # we can add single line comments to the end of the line
2596 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2598 if ($line =~ m/^(\S+)\s(\S+)$/) {
2599 my ($name, $cidr) = ($1, $2);
2602 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2607 ipversion => $ipversion,
2609 $data->{comment} = $comment if $comment;
2616 sub generic_fw_config_parser {
2617 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2622 my $res = $empty_conf;
2624 while (defined(my $line = <$fh>)) {
2625 next if $line =~ m/^#/;
2626 next if $line =~ m/^\s*$/;
2630 my $linenr = $fh->input_line_number();
2631 my $prefix = "$filename (line $linenr)";
2633 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2634 $section = 'options
';
2638 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2639 $section = 'aliases
';
2643 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2644 $section = 'groups
';
2648 die "security group name too long\n" if length($group) > $max_group_name_length;
2649 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2652 ($section, $group, $comment) = undef;
2653 warn "$prefix: $err";
2657 $res->{$section}->{$group} = [];
2658 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2663 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2668 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2673 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2674 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2677 ($section, $group, $comment) = undef;
2678 warn "$prefix: $err";
2682 $res->{$section}->{$group} = [];
2683 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2689 warn "$prefix: skip line - no section\n";
2693 if ($section eq 'options
') {
2696 if ($rule_env eq 'cluster
') {
2697 ($opt, $value) = parse_clusterfw_option($line);
2698 } elsif ($rule_env eq 'host
') {
2699 ($opt, $value) = parse_hostfw_option($line);
2701 ($opt, $value) = parse_vmfw_option($line);
2703 $res->{options}->{$opt} = $value;
2705 warn "$prefix: $@" if $@;
2706 } elsif ($section eq 'aliases
') {
2708 my $data = parse_alias($line);
2709 $res->{aliases}->{lc($data->{name})} = $data;
2711 warn "$prefix: $@" if $@;
2712 } elsif ($section eq 'rules
') {
2714 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2716 warn "$prefix: $err";
2719 push @{$res->{$section}}, $rule;
2720 } elsif ($section eq 'groups
') {
2722 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2724 warn "$prefix: $err";
2727 push @{$res->{$section}->{$group}}, $rule;
2728 } elsif ($section eq 'ipset
') {
2729 # we can add single line comments to the end of the rule
2730 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2732 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2737 if ($nomatch && !$feature_ipset_nomatch) {
2738 $errors->{nomatch} = "nomatch not supported by kernel";
2742 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2743 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2745 $cidr = parse_ip_or_cidr($cidr);
2750 $errors->{cidr} = $err;
2753 my $entry = { cidr => $cidr };
2754 $entry->{nomatch} = 1 if $nomatch;
2755 $entry->{comment} = $comment if $comment;
2756 $entry->{errors} = $errors if $errors;
2758 if ($verbose && $errors) {
2759 warn "$prefix - errors in ipset '$group': $line\n";
2760 foreach my $p (keys %{$errors}) {
2761 warn " $p: $errors->{$p}\n";
2765 push @{$res->{$section}->{$group}}, $entry;
2767 warn "$prefix: skip line - unknown section\n";
2775 sub parse_hostfw_config {
2776 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2778 my $empty_conf = { rules => [], options => {}};
2780 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2783 sub parse_vmfw_config {
2784 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2791 ipset_comments => {},
2794 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2797 sub parse_clusterfw_config {
2798 my ($filename, $fh, $verbose) = @_;
2808 group_comments => {},
2810 ipset_comments => {},
2813 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2817 my ($code, @param) = @_;
2821 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2828 sub read_local_vm_config {
2833 my $vmdata = { qemu => $qemu, lxc => $lxc };
2835 my $vmlist = PVE::Cluster::get_vmlist();
2836 return $vmdata if !$vmlist || !$vmlist->{ids};
2837 my $ids = $vmlist->{ids};
2839 foreach my $vmid (keys %$ids) {
2840 next if !$vmid; # skip VE0
2841 my $d = $ids->{$vmid};
2842 next if !$d->{node} || $d->{node} ne $nodename;
2843 next if !$d->{type};
2844 if ($d->{type} eq 'qemu
') {
2845 if ($have_qemu_server) {
2846 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2847 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2848 $qemu->{$vmid} = $conf;
2851 } elsif ($d->{type} eq 'lxc
') {
2853 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2854 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2855 $lxc->{$vmid} = $conf;
2864 sub load_vmfw_conf {
2865 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2869 $dir = $pvefw_conf_dir if !defined($dir);
2871 my $filename = "$dir/$vmid.fw";
2872 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2873 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2874 $vmfw_conf->{vmid} = $vmid;
2880 my $format_rules = sub {
2881 my ($rules, $allow_iface) = @_;
2885 foreach my $rule (@$rules) {
2886 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2887 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2888 $raw .= uc($rule->{type});
2889 if ($rule->{macro}) {
2890 $raw .= " $rule->{macro}($rule->{action})";
2892 $raw .= " " . $rule->{action};
2894 if ($allow_iface && $rule->{iface}) {
2895 $raw .= " -i $rule->{iface}";
2898 if ($rule->{type} ne 'group
') {
2899 $raw .= " -source $rule->{source}" if $rule->{source};
2900 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2901 $raw .= " -p $rule->{proto}" if $rule->{proto};
2902 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2903 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2906 $raw .= " # " . encode('utf8
', $rule->{comment})
2907 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2910 die "unknown rule type '$rule->{type
}'";
2917 my $format_options = sub {
2922 $raw .= "[OPTIONS]\n\n";
2923 foreach my $opt (keys %$options) {
2924 $raw .= "$opt: $options->{$opt}\n";
2931 my $format_aliases = sub {
2936 $raw .= "[ALIASES]\n\n";
2937 foreach my $k (keys %$aliases) {
2938 my $e = $aliases->{$k};
2939 $raw .= "$e->{name} $e->{cidr}";
2940 $raw .= " # " . encode('utf8
', $e->{comment})
2941 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2949 my $format_ipsets = sub {
2954 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2955 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2956 my $utf8comment = encode('utf8
', $comment);
2957 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2959 $raw .= "[IPSET $ipset]\n\n";
2961 my $options = $fw_conf->{ipset}->{$ipset};
2964 foreach my $entry (@$options) {
2965 $nethash->{$entry->{cidr}} = $entry;
2968 foreach my $cidr (sort keys %$nethash) {
2969 my $entry = $nethash->{$cidr};
2970 my $line = $entry->{nomatch} ? '!' : '';
2971 $line .= $entry->{cidr};
2972 $line .= " # " . encode('utf8
', $entry->{comment})
2973 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2983 sub save_vmfw_conf {
2984 my ($vmid, $vmfw_conf) = @_;
2988 my $options = $vmfw_conf->{options};
2989 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2991 my $aliases = $vmfw_conf->{aliases};
2992 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2994 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2996 my $rules = $vmfw_conf->{rules} || [];
2997 if ($rules && scalar(@$rules)) {
2998 $raw .= "[RULES]\n\n";
2999 $raw .= &$format_rules($rules, 1);
3003 my $filename = "$pvefw_conf_dir/$vmid.fw";
3005 mkdir $pvefw_conf_dir;
3006 PVE::Tools::file_set_contents($filename, $raw);
3012 sub remove_vmfw_conf {
3015 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3017 unlink $vmfw_conffile;
3020 sub clone_vmfw_conf {
3021 my ($vmid, $newid) = @_;
3023 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3024 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3026 if (-f $clonevm_conffile) {
3027 unlink $clonevm_conffile;
3029 if (-f $sourcevm_conffile) {
3030 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3031 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3035 sub read_vm_firewall_configs {
3036 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
3038 my $vmfw_configs = {};
3040 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3041 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
3042 next if !$vmfw_conf->{options}; # skip if file does not exists
3043 $vmfw_configs->{$vmid} = $vmfw_conf;
3045 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3046 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
3047 next if !$vmfw_conf->{options}; # skip if file does not exists
3048 $vmfw_configs->{$vmid} = $vmfw_conf;
3051 return $vmfw_configs;
3054 sub get_option_log_level {
3055 my ($options, $k) = @_;
3057 my $v = $options->{$k};
3058 $v = $default_log_level if !defined($v);
3060 return undef if $v eq '' || $v eq 'nolog
';
3062 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3064 return $v if ($v >= 0) && ($v <= 7);
3066 warn "unknown log level ($k = '$v')\n";
3071 sub generate_std_chains {
3072 my ($ruleset, $options, $ipversion) = @_;
3074 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
3076 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
3080 if ($ipversion == 4) {
3081 # same as shorewall smurflog.
3082 $chain = 'PVEFW-smurflog
';
3083 $std_chains->{$chain} = [];
3085 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3086 push @{$std_chains->{$chain}}, "-j DROP";
3089 # same as shorewall logflags action.
3090 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
3091 $chain = 'PVEFW-logflags
';
3092 $std_chains->{$chain} = [];
3094 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
3095 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3096 push @{$std_chains->{$chain}}, "-j DROP";
3098 foreach my $chain (keys %$std_chains) {
3099 ruleset_create_chain($ruleset, $chain);
3100 foreach my $rule (@{$std_chains->{$chain}}) {
3102 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
3104 ruleset_addrule($ruleset, $chain, $rule);
3110 sub generate_ipset_chains {
3111 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
3113 foreach my $ipset (keys %{$ipsets}) {
3115 my $options = $ipsets->{$ipset};
3117 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3118 if (my $ips = $device_ips->{$1}) {
3119 $options = [@$options, @$ips];
3125 foreach my $entry (@$options) {
3126 next if $entry->{errors}; # skip entries with errors
3129 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3130 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3132 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3134 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3136 # ip_compress_address takes an address only, no CIDR
3137 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3138 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3139 $cidr .= $prefix_len if defined($prefix_len);
3145 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3150 foreach my $ipversion (4, 6) {
3151 my $data = $nethash->{$ipversion};
3153 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3155 my $hashsize = scalar(@$options);
3156 if ($hashsize <= 64) {
3159 $hashsize = round_powerof2($hashsize);
3162 my $family = $ipversion == "6" ? "inet6" : "inet";
3164 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3166 foreach my $cidr (sort keys %$data) {
3167 my $entry = $data->{$cidr};
3169 my $cmd = "add $name $cidr";
3170 if ($entry->{nomatch}) {
3171 if ($feature_ipset_nomatch) {
3172 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3174 warn "ignore !$cidr - nomatch not supported by kernel\n";
3177 push @{$ipset_ruleset->{$name}}, $cmd;
3184 sub round_powerof2 {
3188 $int |= $int >> $_ foreach (1,2,4,8,16);
3192 sub load_clusterfw_conf {
3193 my ($filename, $verbose) = @_;
3195 $filename = $clusterfw_conf_filename if !defined($filename);
3197 my $cluster_conf = {};
3198 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3199 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3202 return $cluster_conf;
3205 sub save_clusterfw_conf {
3206 my ($cluster_conf) = @_;
3210 my $options = $cluster_conf->{options};
3211 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3213 my $aliases = $cluster_conf->{aliases};
3214 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3216 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3218 my $rules = $cluster_conf->{rules};
3219 if ($rules && scalar(@$rules)) {
3220 $raw .= "[RULES]\n\n";
3221 $raw .= &$format_rules($rules, 1);
3225 if ($cluster_conf->{groups}) {
3226 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3227 my $rules = $cluster_conf->{groups}->{$group};
3228 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3229 my $utf8comment = encode('utf8
', $comment);
3230 $raw .= "[group $group] # $utf8comment\n\n";
3232 $raw .= "[group $group]\n\n";
3235 $raw .= &$format_rules($rules, 0);
3241 mkdir $pvefw_conf_dir;
3242 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3244 unlink $clusterfw_conf_filename;
3248 sub load_hostfw_conf {
3249 my ($cluster_conf, $filename, $verbose) = @_;
3251 $filename = $hostfw_conf_filename if !defined($filename);
3253 my $hostfw_conf = {};
3254 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3255 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3257 return $hostfw_conf;
3260 sub save_hostfw_conf {
3261 my ($hostfw_conf) = @_;
3265 my $options = $hostfw_conf->{options};
3266 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3268 my $rules = $hostfw_conf->{rules};
3269 if ($rules && scalar(@$rules)) {
3270 $raw .= "[RULES]\n\n";
3271 $raw .= &$format_rules($rules, 1);
3276 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3278 unlink $hostfw_conf_filename;
3283 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3287 if ($vmdata) { # test mode
3288 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3289 my $filename = "$testdir/cluster.fw";
3290 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3292 $filename = "$testdir/host.fw";
3293 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3295 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3296 } else { # normal operation
3297 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3299 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3301 $vmdata = read_local_vm_config();
3302 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3305 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3308 if ($cluster_conf->{aliases}->{local_network}) {
3309 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3312 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3314 $cluster_conf->{aliases}->{local_network} = {
3315 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3318 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3320 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3321 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3322 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3324 return ($ruleset, $ipset_ruleset, $rulesetv6);
3327 sub compile_iptables_filter {
3328 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3332 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3333 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3335 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3337 my $hostfw_options = $hostfw_conf->{options} || {};
3339 # fixme: what log level should we use here?
3340 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3342 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3344 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3345 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3347 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3349 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3350 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3352 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3354 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3356 if ($hostfw_enable) {
3357 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3358 warn $@ if $@; # just to be sure - should not happen
3361 # generate firewall rules for QEMU VMs
3362 foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
3364 my $conf = $vmdata->{qemu}->{$vmid};
3365 my $vmfw_conf = $vmfw_configs->{$vmid};
3366 return if !$vmfw_conf;
3368 foreach my $netid (sort keys %$conf) {
3369 next if $netid !~ m/^net(\d+)$/;
3370 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3371 next if !$net->{firewall};
3372 my $iface = "tap${vmid}i$1";
3374 my $macaddr = $net->{macaddr};
3375 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3376 $vmfw_conf, $vmid, 'IN
', $ipversion);
3377 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3378 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3381 warn $@ if $@; # just to be sure - should not happen
3384 # generate firewall rules for LXC containers
3385 foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
3387 my $conf = $vmdata->{lxc}->{$vmid};
3388 my $vmfw_conf = $vmfw_configs->{$vmid};
3389 return if !$vmfw_conf;
3391 if ($vmfw_conf->{options}->{enable}) {
3392 foreach my $netid (sort keys %$conf) {
3393 next if $netid !~ m/^net(\d+)$/;
3394 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3395 next if !$net->{firewall};
3396 my $iface = "veth${vmid}i$1";
3397 my $macaddr = $net->{hwaddr};
3398 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3399 $vmfw_conf, $vmid, 'IN
', $ipversion);
3400 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3401 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3405 warn $@ if $@; # just to be sure - should not happen
3408 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3409 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3415 sub mac_to_linklocal {
3417 my @parts = split(/:/, $macaddr);
3418 # The standard link local address uses the fe80::/64 prefix with the
3419 # modified EUI-64 identifier derived from the MAC address by flipping the
3420 # universal/local bit and inserting FF:FE in the middle.
3422 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3423 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3424 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3427 sub compile_ipsets {
3428 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3431 if ($cluster_conf->{aliases}->{local_network}) {
3432 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3435 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3437 $cluster_conf->{aliases}->{local_network} = {
3438 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3441 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3444 my $ipset_ruleset = {};
3446 # generate ipsets for QEMU VMs
3447 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3449 my $conf = $vmdata->{qemu}->{$vmid};
3450 my $vmfw_conf = $vmfw_configs->{$vmid};
3451 return if !$vmfw_conf;
3453 # When the 'ipfilter
' option is enabled every device for which there
3454 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3456 # The reason is that ipfilter ipsets are always filled with standard
3457 # IPv6 link-local filters.
3458 my $ipsets = $vmfw_conf->{ipset};
3459 my $implicit_sets = {};
3461 my $device_ips = {};
3462 foreach my $netid (keys %$conf) {
3463 next if $netid !~ m/^net(\d+)$/;
3464 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3465 next if !$net->{firewall};
3467 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3468 $implicit_sets->{"ipfilter-$netid"} = [];
3471 my $macaddr = $net->{macaddr};
3472 my $linklocal = mac_to_linklocal($macaddr);
3473 $device_ips->{$netid} = [
3474 { cidr => $linklocal },
3475 { cidr => 'fe80
::/10', nomatch => 1 }
3479 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3480 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3482 warn $@ if $@; # just to be sure - should not happen
3485 # generate firewall rules for LXC containers
3486 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3488 my $conf = $vmdata->{lxc}->{$vmid};
3489 my $vmfw_conf = $vmfw_configs->{$vmid};
3490 return if !$vmfw_conf;
3492 # When the 'ipfilter
' option is enabled every device for which there
3493 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3495 # The reason is that ipfilter ipsets are always filled with standard
3496 # IPv6 link-local filters, as well as the IP addresses configured
3497 # for the container.
3498 my $ipsets = $vmfw_conf->{ipset};
3499 my $implicit_sets = {};
3501 my $device_ips = {};
3502 foreach my $netid (keys %$conf) {
3503 next if $netid !~ m/^net(\d+)$/;
3504 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3505 next if !$net->{firewall};
3507 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3508 $implicit_sets->{"ipfilter-$netid"} = [];
3511 my $macaddr = $net->{hwaddr};
3512 my $linklocal = mac_to_linklocal($macaddr);
3513 my $set = $device_ips->{$netid} = [
3514 { cidr => $linklocal },
3515 { cidr => 'fe80
::/10', nomatch => 1 }
3517 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3518 push @$set, { cidr => $1 };
3520 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3521 push @$set, { cidr => $1 };
3525 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3526 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3528 warn $@ if $@; # just to be sure - should not happen
3531 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3533 return $ipset_ruleset;
3536 sub get_ruleset_status {
3537 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3539 my $statushash = {};
3541 foreach my $chain (sort keys %$ruleset) {
3542 my $sig = &$digest_fn($ruleset->{$chain});
3544 $statushash->{$chain}->{sig} = $sig;
3546 my $oldsig = $active_chains->{$chain};
3547 if (!defined($oldsig)) {
3548 $statushash->{$chain}->{action} = 'create
';
3550 if ($oldsig eq $sig) {
3551 $statushash->{$chain}->{action} = 'exists';
3553 $statushash->{$chain}->{action} = 'update
';
3556 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3557 foreach my $cmd (@{$ruleset->{$chain}}) {
3558 print "\t$cmd\n" if $verbose;
3562 foreach my $chain (sort keys %$active_chains) {
3563 if (!defined($ruleset->{$chain})) {
3564 my $sig = $active_chains->{$chain};
3565 $statushash->{$chain}->{action} = 'delete';
3566 $statushash->{$chain}->{sig} = $sig;
3567 print "delete $chain ($sig)\n" if $verbose;
3574 sub print_sig_rule {
3575 my ($chain, $sig) = @_;
3577 # We just use this to store a SHA1 checksum used to detect changes
3578 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3581 sub get_ruleset_cmdlist {
3582 my ($ruleset, $verbose, $iptablescmd) = @_;
3584 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3586 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3587 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3589 # create missing chains first
3590 foreach my $chain (sort keys %$ruleset) {
3591 my $stat = $statushash->{$chain};
3592 die "internal error" if !$stat;
3593 next if $stat->{action} ne 'create
';
3595 $cmdlist .= ":$chain - [0:0]\n";
3598 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3599 my $chain = "PVEFW-$h";
3600 if ($ruleset->{$chain} && !$hooks->{$h}) {
3601 $cmdlist .= "-A $h -j $chain\n";
3605 foreach my $chain (sort keys %$ruleset) {
3606 my $stat = $statushash->{$chain};
3607 die "internal error" if !$stat;
3609 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3610 $cmdlist .= "-F $chain\n";
3611 foreach my $cmd (@{$ruleset->{$chain}}) {
3612 $cmdlist .= "$cmd\n";
3614 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3615 } elsif ($stat->{action
} eq 'delete') {
3616 die "internal error"; # this should not happen
3617 } elsif ($stat->{action
} eq 'exists') {
3620 die "internal error - unknown status '$stat->{action}'";
3624 foreach my $chain (keys %$statushash) {
3625 next if $statushash->{$chain}->{action
} ne 'delete';
3626 $cmdlist .= "-F $chain\n";
3628 foreach my $chain (keys %$statushash) {
3629 next if $statushash->{$chain}->{action
} ne 'delete';
3630 next if $chain eq 'PVEFW-INPUT';
3631 next if $chain eq 'PVEFW-OUTPUT';
3632 next if $chain eq 'PVEFW-FORWARD';
3633 $cmdlist .= "-X $chain\n";
3636 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3638 $cmdlist .= "COMMIT\n";
3640 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3643 sub get_ipset_cmdlist
{
3644 my ($ruleset, $verbose) = @_;
3648 my $delete_cmdlist = "";
3650 my $active_chains = ipset_get_chains
();
3651 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3653 # remove stale _swap chains
3654 foreach my $chain (keys %$active_chains) {
3655 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3656 $cmdlist .= "destroy $chain\n";
3660 foreach my $chain (keys %$ruleset) {
3661 my $stat = $statushash->{$chain};
3662 die "internal error" if !$stat;
3664 if ($stat->{action
} eq 'create') {
3665 foreach my $cmd (@{$ruleset->{$chain}}) {
3666 $cmdlist .= "$cmd\n";
3671 foreach my $chain (keys %$ruleset) {
3672 my $stat = $statushash->{$chain};
3673 die "internal error" if !$stat;
3675 if ($stat->{action
} eq 'update') {
3676 my $chain_swap = $chain."_swap";
3678 foreach my $cmd (@{$ruleset->{$chain}}) {
3679 $cmd =~ s/$chain/$chain_swap/;
3680 $cmdlist .= "$cmd\n";
3682 $cmdlist .= "swap $chain_swap $chain\n";
3683 $cmdlist .= "flush $chain_swap\n";
3684 $cmdlist .= "destroy $chain_swap\n";
3688 # the remove unused chains
3689 foreach my $chain (keys %$statushash) {
3690 next if $statushash->{$chain}->{action
} ne 'delete';
3692 $delete_cmdlist .= "flush $chain\n";
3693 $delete_cmdlist .= "destroy $chain\n";
3696 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3698 return ($cmdlist, $delete_cmdlist, $changes);
3702 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3704 enable_bridge_firewall
();
3706 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3707 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3709 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3710 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3713 if ($ipset_changes) {
3714 print "ipset changes:\n";
3715 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3716 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3720 print "iptables changes:\n";
3725 print "ip6tables changes:\n";
3730 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3731 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3733 ipset_restore_cmdlist
($ipset_create_cmdlist);
3735 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3736 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3738 iptables_restore_cmdlist
($cmdlist);
3740 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3741 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3743 ip6tables_restore_cmdlist
($cmdlistv6);
3745 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3746 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3748 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3750 # test: re-read status and check if everything is up to date
3751 my $active_chains = iptables_get_chains
();
3752 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3755 foreach my $chain (sort keys %$ruleset) {
3756 my $stat = $statushash->{$chain};
3757 if ($stat->{action
} ne 'exists') {
3758 warn "unable to update chain '$chain'\n";
3763 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3764 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3766 foreach my $chain (sort keys %$rulesetv6) {
3767 my $stat = $statushashv6->{$chain};
3768 if ($stat->{action
} ne 'exists') {
3769 warn "unable to update chain '$chain'\n";
3774 die "unable to apply firewall changes\n" if $errors;
3776 update_nf_conntrack_max
($hostfw_conf);
3778 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3782 sub update_nf_conntrack_max
{
3783 my ($hostfw_conf) = @_;
3785 my $max = 65536; # reasonable default
3787 my $options = $hostfw_conf->{options
} || {};
3789 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3790 $max = $options->{nf_conntrack_max
};
3791 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3794 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3795 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3797 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3799 if ($current != $max) {
3800 my $hashsize = int($max/4);
3801 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3802 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3806 sub update_nf_conntrack_tcp_timeout_established
{
3807 my ($hostfw_conf) = @_;
3809 my $options = $hostfw_conf->{options
} || {};
3811 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3813 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3816 sub remove_pvefw_chains
{
3818 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3819 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3820 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3824 sub remove_pvefw_chains_iptables
{
3825 my ($iptablescmd) = @_;
3827 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3828 my $cmdlist = "*filter\n";
3830 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3832 $cmdlist .= "-D $h -j PVEFW-$h\n";
3836 foreach my $chain (keys %$chash) {
3837 $cmdlist .= "-F $chain\n";
3840 foreach my $chain (keys %$chash) {
3841 $cmdlist .= "-X $chain\n";
3843 $cmdlist .= "COMMIT\n";
3845 if($iptablescmd eq "ip6tables") {
3846 ip6tables_restore_cmdlist
($cmdlist);
3848 iptables_restore_cmdlist
($cmdlist);
3852 sub remove_pvefw_chains_ipset
{
3854 my $ipset_chains = ipset_get_chains
();
3858 foreach my $chain (keys %$ipset_chains) {
3859 $cmdlist .= "flush $chain\n";
3860 $cmdlist .= "destroy $chain\n";
3863 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3867 my $cluster_conf = load_clusterfw_conf
();
3868 my $cluster_options = $cluster_conf->{options
};
3869 my $enable = $cluster_options->{enable
};
3873 # load required modules here
3879 my $cluster_conf = load_clusterfw_conf
();
3880 my $cluster_options = $cluster_conf->{options
};
3882 if (!$cluster_options->{enable
}) {
3883 PVE
::Firewall
::remove_pvefw_chains
();
3887 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3889 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3891 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);