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' },
326 "Munin networked resource monitoring traffic",
327 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
331 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
334 "NNTP traffic (Usenet).",
335 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
338 "Encrypted NNTP traffic (Usenet)",
339 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
342 "Network Time Protocol (ntpd)",
343 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
346 "OSPF multicast traffic",
347 { action
=> 'PARAM', proto
=> '89' },
351 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
354 "Symantec PCAnywere (tm)",
355 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
356 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
360 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
363 "Encrypted POP3 traffic",
364 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
367 "Point-to-Point Tunneling Protocol",
368 { action
=> 'PARAM', proto
=> '47' },
369 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
373 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
377 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
380 "Line Printer protocol printing",
381 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
384 "Microsoft Remote Desktop Protocol traffic",
385 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
388 "Routing Information Protocol (bidirectional)",
389 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
392 "BIND remote management protocol",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
396 "Razor Antispam System",
397 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
400 "Remote time retrieval (rdate)",
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
408 "SANE network scanning",
409 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
412 "Microsoft SMB traffic",
413 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
414 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
415 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
416 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
419 "Samba Web Administration Tool",
420 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
423 "Simple Mail Transfer Protocol",
424 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
427 "Encrypted Simple Mail Transfer Protocol",
428 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
431 "Simple Network Management Protocol",
432 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
436 "Spam Assassin SPAMD traffic",
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
440 "Secure shell traffic",
441 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
444 "Subversion server (svnserve)",
445 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
448 "SixXS IPv6 Deployment and Tunnel Broker",
449 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
450 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
451 { action
=> 'PARAM', proto
=> '41' },
452 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
455 "Squid web proxy traffic",
456 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
459 "Mail message submission traffic",
460 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
463 "Syslog protocol (RFC 5424) traffic",
464 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
465 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
468 "Trivial File Transfer Protocol traffic",
469 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
473 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
477 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
480 "RFC 868 Time protocol",
481 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
484 "Traceroute (for up to 30 hops) traffic",
485 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
486 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
489 "VNC traffic for VNC display's 0 - 99",
490 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
493 "VNC traffic from Vncservers to Vncviewers in listen mode",
494 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
497 "WWW traffic (HTTP and HTTPS)",
498 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
499 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
502 "Web Cache/Proxy traffic (port 8080)",
503 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
507 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
510 "Whois (nicname, RFC 3912) traffic",
511 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
515 my $pve_fw_parsed_macros;
516 my $pve_fw_macro_descr;
517 my $pve_fw_macro_ipversion = {};
518 my $pve_fw_preferred_macro_names = {};
520 my $FWACCEPTMARK_ON = "0x80000000/0x80000000";
521 my $FWACCEPTMARK_OFF = "0x00000000/0x80000000";
523 my $pve_std_chains = {};
524 $pve_std_chains->{4} = {
525 'PVEFW-SET-ACCEPT-MARK' => [
526 "-j MARK --set-mark $FWACCEPTMARK_ON",
528 'PVEFW-DropBroadcast' => [
529 # same as shorewall 'Broadcast'
530 # simply DROP BROADCAST/MULTICAST/ANYCAST
531 # we can use this to reduce logging
532 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
533 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
534 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
535 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
538 # same as shorewall 'reject'
539 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
540 { action
=> 'DROP', source
=> '224.0.0.0/4' },
541 { action
=> 'DROP', proto
=> 'icmp' },
542 "-p tcp -j REJECT --reject-with tcp-reset",
543 "-p udp -j REJECT --reject-with icmp-port-unreachable",
544 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
545 "-j REJECT --reject-with icmp-host-prohibited",
548 # same as shorewall 'Drop', which is equal to DROP,
549 # but REJECT/DROP some packages to reduce logging,
550 # and ACCEPT critical ICMP types
551 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
552 # we are not interested in BROADCAST/MULTICAST/ANYCAST
553 { action
=> 'PVEFW-DropBroadcast' },
554 # ACCEPT critical ICMP types
555 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
556 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
557 # Drop packets with INVALID state
558 "-m conntrack --ctstate INVALID -j DROP",
559 # Drop Microsoft SMB noise
560 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
561 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
562 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
563 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
564 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
565 # Drop new/NotSyn traffic so that it doesn't get logged
566 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
568 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
571 # same as shorewall 'Reject', which is equal to Reject,
572 # but REJECT/DROP some packages to reduce logging,
573 # and ACCEPT critical ICMP types
574 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
575 # we are not interested in BROADCAST/MULTICAST/ANYCAST
576 { action
=> 'PVEFW-DropBroadcast' },
577 # ACCEPT critical ICMP types
578 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
579 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
580 # Drop packets with INVALID state
581 "-m conntrack --ctstate INVALID -j DROP",
582 # Drop Microsoft SMB noise
583 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
584 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
585 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
586 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
587 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
588 # Drop new/NotSyn traffic so that it doesn't get logged
589 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
591 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
593 'PVEFW-tcpflags' => [
594 # same as shorewall tcpflags action.
595 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
596 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
597 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
598 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
599 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
600 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
603 # same as shorewall smurfs action
604 # Filter packets for smurfs (packets with a broadcast address as the source).
605 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
606 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
607 "-s 224.0.0.0/4 -g PVEFW-smurflog",
611 $pve_std_chains->{6} = {
612 'PVEFW-SET-ACCEPT-MARK' => [
613 "-j MARK --set-mark $FWACCEPTMARK_ON",
615 'PVEFW-DropBroadcast' => [
616 # same as shorewall 'Broadcast'
617 # simply DROP BROADCAST/MULTICAST/ANYCAST
618 # we can use this to reduce logging
619 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
620 # ipv6 addrtype does not work with kernel 2.6.32
621 #{ action => 'DROP', dsttype => 'MULTICAST' },
622 #{ action => 'DROP', dsttype => 'ANYCAST' },
623 { action
=> 'DROP', dest
=> 'ff00::/8' },
624 #{ action => 'DROP', dest => '224.0.0.0/4' },
627 # same as shorewall 'reject'
628 #{ action => 'DROP', dsttype => 'BROADCAST' },
629 #{ action => 'DROP', source => '224.0.0.0/4' },
630 { action
=> 'DROP', proto
=> 'icmpv6' },
631 "-p tcp -j REJECT --reject-with tcp-reset",
632 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
633 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
634 #"-j REJECT --reject-with icmp-host-prohibited",
637 # same as shorewall 'Drop', which is equal to DROP,
638 # but REJECT/DROP some packages to reduce logging,
639 # and ACCEPT critical ICMP types
640 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
641 # we are not interested in BROADCAST/MULTICAST/ANYCAST
642 { action
=> 'PVEFW-DropBroadcast' },
643 # ACCEPT critical ICMP types
644 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
645 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
646 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
648 # Drop packets with INVALID state
649 "-m conntrack --ctstate INVALID -j DROP",
650 # Drop Microsoft SMB noise
651 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
652 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
653 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
654 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
655 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
656 # Drop new/NotSyn traffic so that it doesn't get logged
657 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
659 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
662 # same as shorewall 'Reject', which is equal to Reject,
663 # but REJECT/DROP some packages to reduce logging,
664 # and ACCEPT critical ICMP types
665 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
666 # we are not interested in BROADCAST/MULTICAST/ANYCAST
667 { action
=> 'PVEFW-DropBroadcast' },
668 # ACCEPT critical ICMP types
669 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
670 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
671 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
673 # Drop packets with INVALID state
674 "-m conntrack --ctstate INVALID -j DROP",
675 # Drop Microsoft SMB noise
676 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
677 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
678 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
679 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
680 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
681 # Drop new/NotSyn traffic so that it doesn't get logged
682 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
684 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
686 'PVEFW-tcpflags' => [
687 # same as shorewall tcpflags action.
688 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
689 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
690 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
691 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
692 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
693 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
697 # iptables -p icmp -h
698 my $icmp_type_names = {
701 'destination-unreachable' => 1,
702 'network-unreachable' => 1,
703 'host-unreachable' => 1,
704 'protocol-unreachable' => 1,
705 'port-unreachable' => 1,
706 'fragmentation-needed' => 1,
707 'source-route-failed' => 1,
708 'network-unknown' => 1,
710 'network-prohibited' => 1,
711 'host-prohibited' => 1,
712 'TOS-network-unreachable' => 1,
713 'TOS-host-unreachable' => 1,
714 'communication-prohibited' => 1,
715 'host-precedence-violation' => 1,
716 'precedence-cutoff' => 1,
717 'source-quench' => 1,
719 'network-redirect' => 1,
720 'host-redirect' => 1,
721 'TOS-network-redirect' => 1,
722 'TOS-host-redirect' => 1,
724 'router-advertisement' => 1,
725 'router-solicitation' => 1,
726 'time-exceeded' => 1,
727 'ttl-zero-during-transit' => 1,
728 'ttl-zero-during-reassembly' => 1,
729 'parameter-problem' => 1,
730 'ip-header-bad' => 1,
731 'required-option-missing' => 1,
732 'timestamp-request' => 1,
733 'timestamp-reply' => 1,
734 'address-mask-request' => 1,
735 'address-mask-reply' => 1,
738 # ip6tables -p icmpv6 -h
740 my $icmpv6_type_names = {
742 'destination-unreachable' => 1,
744 'communication-prohibited' => 1,
745 'address-unreachable' => 1,
746 'port-unreachable' => 1,
747 'packet-too-big' => 1,
748 'time-exceeded' => 1,
749 'ttl-zero-during-transit' => 1,
750 'ttl-zero-during-reassembly' => 1,
751 'parameter-problem' => 1,
753 'unknown-header-type' => 1,
754 'unknown-option' => 1,
757 'router-solicitation' => 1,
758 'router-advertisement' => 1,
759 'neighbor-solicitation' => 1,
760 'neighbour-solicitation' => 1,
761 'neighbor-advertisement' => 1,
762 'neighbour-advertisement' => 1,
766 sub init_firewall_macros
{
768 $pve_fw_parsed_macros = {};
771 my ($k, $macro) = @_;
772 my $lc_name = lc($k);
773 $pve_fw_macro_ipversion->{$k} = 0;
774 while (!ref($macro->[0])) {
775 my $desc = shift @$macro;
776 if ($desc eq 'ipv4only') {
777 $pve_fw_macro_ipversion->{$k} = 4;
778 } elsif ($desc eq 'ipv6only') {
779 $pve_fw_macro_ipversion->{$k} = 6;
781 $pve_fw_macro_descr->{$k} = $desc;
784 $pve_fw_preferred_macro_names->{$lc_name} = $k;
785 $pve_fw_parsed_macros->{$k} = $macro;
788 foreach my $k (keys %$pve_fw_macros) {
789 &$parse($k, $pve_fw_macros->{$k});
792 foreach my $k (keys %$pve_ipv6fw_macros) {
793 next if $pve_fw_parsed_macros->{$k};
794 &$parse($k, $pve_ipv6fw_macros->{$k});
795 $pve_fw_macro_ipversion->{$k} = 6;
799 init_firewall_macros
();
802 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
807 sub get_etc_services
{
809 return $etc_services if $etc_services;
811 my $filename = "/etc/services";
813 my $fh = IO
::File-
>new($filename, O_RDONLY
);
815 warn "unable to read '$filename' - $!\n";
821 while (my $line = <$fh>) {
823 next if $line =~m/^#/;
824 next if ($line =~m/^\s*$/);
826 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
827 $services->{byid
}->{$2}->{name
} = $1;
828 $services->{byid
}->{$2}->{port
} = $2;
829 $services->{byid
}->{$2}->{$3} = 1;
830 $services->{byname
}->{$1} = $services->{byid
}->{$2};
836 $etc_services = $services;
839 return $etc_services;
844 sub get_etc_protocols
{
845 return $etc_protocols if $etc_protocols;
847 my $filename = "/etc/protocols";
849 my $fh = IO
::File-
>new($filename, O_RDONLY
);
851 warn "unable to read '$filename' - $!\n";
857 while (my $line = <$fh>) {
859 next if $line =~m/^#/;
860 next if ($line =~m/^\s*$/);
862 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
863 $protocols->{byid
}->{$2}->{name
} = $1;
864 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
870 # add special case for ICMP v6
871 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
872 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
874 $etc_protocols = $protocols;
876 return $etc_protocols;
882 my ($new_value) = @_;
884 $__local_network = $new_value if defined($new_value);
886 return $__local_network if defined($__local_network);
889 my $nodename = PVE
::INotify
::nodename
();
891 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
893 my $testip = Net
::IP-
>new($ip);
895 my $isv6 = $testip->version == 6;
896 my $routes = $isv6 ? PVE
::ProcFSTools
::read_proc_net_ipv6_route
()
897 : PVE
::ProcFSTools
::read_proc_net_route
();
898 foreach my $entry (@$routes) {
901 $mask = $entry->{prefix
};
903 $mask = $PVE::Network
::ipv4_mask_hash_localnet-
>{$entry->{mask
}};
904 next if !defined($mask);
906 my $cidr = "$entry->{dest}/$mask";
907 my $testnet = Net
::IP-
>new($cidr);
908 if ($testnet->overlaps($testip) == $Net::IP
::IP_B_IN_A_OVERLAP
) {
909 $__local_network = $cidr;
916 return $__local_network;
919 # ipset names are limited to 31 characters,
920 # and we use '-v4' or '-v6' to indicate IP versions,
921 # and we use '_swap' suffix for atomic update,
922 # for example PVEFW-${VMID}-${ipset_name}_swap
924 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
926 sub compute_ipset_chain_name
{
927 my ($vmid, $ipset_name, $ipversion) = @_;
929 $vmid = 0 if !defined($vmid);
931 my $id = "$vmid-${ipset_name}-v$ipversion";
933 if (length($id) > $max_iptables_ipset_name_length) {
934 $id = PVE
::Tools
::fnv31a_hex
($id);
940 sub compute_ipfilter_ipset_name
{
943 return "ipfilter-$iface";
946 sub parse_address_list
{
949 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
950 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
954 if ($str =~ m/^${ip_alias_pattern}$/) {
955 die "alias name too long\n" if length($str) > $max_alias_name_length;
963 foreach my $elem (split(/,/, $str)) {
965 my $ip = Net
::IP-
>new($elem);
967 my $err = Net
::IP
::Error
();
968 die "invalid IP address: $err\n";
970 $iprange = 1 if $elem =~ m/-/;
972 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
974 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
975 if $ipversion && ($new_ipversion != $ipversion);
977 $ipversion = $new_ipversion;
980 die "you can't use a range in a list\n" if $iprange && $count > 1;
985 sub parse_port_name_number_or_range
{
986 my ($str, $dport) = @_;
988 my $services = PVE
::Firewall
::get_etc_services
();
992 foreach my $item (split(/,/, $str)) {
994 if ($item =~ m/^(\d+):(\d+)$/) {
995 my ($port1, $port2) = ($1, $2);
996 die "invalid port '$port1'\n" if $port1 > 65535;
997 die "invalid port '$port2'\n" if $port2 > 65535;
998 } elsif ($item =~ m/^(\d+)$/) {
1000 die "invalid port '$port'\n" if $port > 65535;
1002 if ($dport && $icmp_type_names->{$item}) {
1004 } elsif ($dport && $icmpv6_type_names->{$item}) {
1007 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1012 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1017 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1018 sub pve_fw_verify_sport_spec
{
1021 parse_port_name_number_or_range
($portstr, 0);
1026 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1027 sub pve_fw_verify_dport_spec
{
1030 parse_port_name_number_or_range
($portstr, 1);
1035 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1036 sub pve_fw_verify_addr_spec
{
1039 parse_address_list
($list);
1044 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1045 sub pve_fw_verify_protocol_spec
{
1048 my $protocols = get_etc_protocols
();
1050 die "unknown protocol '$proto'\n" if $proto &&
1051 !(defined($protocols->{byname
}->{$proto}) ||
1052 defined($protocols->{byid
}->{$proto}));
1058 # helper function for API
1060 sub copy_opject_with_digest
{
1063 my $sha = Digest
::SHA-
>new('sha1');
1066 foreach my $k (sort keys %$object) {
1067 my $v = $object->{$k};
1068 next if !defined($v);
1070 $sha->add($k, ':', $v, "\n");
1073 my $digest = $sha->hexdigest;
1075 $res->{digest
} = $digest;
1077 return wantarray ?
($res, $digest) : $res;
1080 sub copy_list_with_digest
{
1083 my $sha = Digest
::SHA-
>new('sha1');
1086 foreach my $entry (@$list) {
1088 foreach my $k (sort keys %$entry) {
1089 my $v = $entry->{$k};
1090 next if !defined($v);
1092 # Note: digest ignores refs ($rule->{errors})
1093 # since Digest::SHA expects a series of bytes,
1094 # we have to encode the value here to prevent errors when
1095 # using utf8 characters (eg. in comments)
1096 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1101 my $digest = $sha->hexdigest;
1103 foreach my $entry (@$res) {
1104 $entry->{digest
} = $digest;
1107 return wantarray ?
($res, $digest) : $res;
1110 our $cluster_option_properties = {
1112 description
=> "Enable or disable the firewall cluster wide.",
1118 description
=> "Input policy.",
1121 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1124 description
=> "Output policy.",
1127 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1131 our $host_option_properties = {
1133 description
=> "Enable host firewall rules.",
1137 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1138 description
=> "Log level for incoming traffic." }),
1139 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1140 description
=> "Log level for outgoing traffic." }),
1141 tcp_flags_log_level
=> get_standard_option
('pve-fw-loglevel', {
1142 description
=> "Log level for illegal tcp flags filter." }),
1143 smurf_log_level
=> get_standard_option
('pve-fw-loglevel', {
1144 description
=> "Log level for SMURFS filter." }),
1146 description
=> "Enable SMURFS filter.",
1151 description
=> "Filter illegal combinations of TCP flags.",
1155 nf_conntrack_max
=> {
1156 description
=> "Maximum number of tracked connections.",
1161 nf_conntrack_tcp_timeout_established
=> {
1162 description
=> "Conntrack established timeout.",
1168 description
=> "Enable NDP.",
1174 our $vm_option_properties = {
1176 description
=> "Enable/disable firewall rules.",
1181 description
=> "Enable/disable MAC address filter.",
1186 description
=> "Enable DHCP.",
1191 description
=> "Enable NDP.",
1196 description
=> "Allow sending Router Advertisement.",
1201 description
=> "Enable default IP filters. " .
1202 "This is equivalent to adding an empty ipfilter-net<id> ipset " .
1203 "for every interface. Such ipsets implicitly contain sane default " .
1204 "restrictions such as restricting IPv6 link local addresses to " .
1205 "the one derived from the interface's MAC address. For containers " .
1206 "the configured IP addresses will be implicitly added.",
1211 description
=> "Input policy.",
1214 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1217 description
=> "Output policy.",
1220 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1222 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1223 description
=> "Log level for incoming traffic." }),
1224 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1225 description
=> "Log level for outgoing traffic." }),
1230 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.";
1232 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.";
1234 my $rule_properties = {
1236 description
=> "Update rule at position <pos>.",
1241 digest
=> get_standard_option
('pve-config-digest'),
1243 description
=> "Rule type.",
1246 enum
=> ['in', 'out', 'group'],
1249 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1252 pattern
=> $security_group_name_pattern,
1257 description
=> "Use predefined standard macro.",
1262 iface
=> get_standard_option
('pve-iface', {
1263 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.",
1267 description
=> "Restrict packet source address. $addr_list_descr",
1268 type
=> 'string', format
=> 'pve-fw-addr-spec',
1272 description
=> "Restrict packet destination address. $addr_list_descr",
1273 type
=> 'string', format
=> 'pve-fw-addr-spec',
1277 description
=> "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
1278 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1282 description
=> "Flag to enable/disable a rule.",
1288 description
=> "Restrict TCP/UDP source port. $port_descr",
1289 type
=> 'string', format
=> 'pve-fw-sport-spec',
1293 description
=> "Restrict TCP/UDP destination port. $port_descr",
1294 type
=> 'string', format
=> 'pve-fw-dport-spec',
1298 description
=> "Descriptive comment.",
1304 sub add_rule_properties
{
1305 my ($properties) = @_;
1307 foreach my $k (keys %$rule_properties) {
1308 my $h = $rule_properties->{$k};
1309 # copy data, so that we can modify later without side effects
1310 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1316 sub delete_rule_properties
{
1317 my ($rule, $delete_str) = @_;
1319 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1320 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1321 if !defined($rule_properties->{$opt});
1322 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1323 if $opt eq 'type' || $opt eq 'action';
1324 delete $rule->{$opt};
1330 my $apply_macro = sub {
1331 my ($macro_name, $param, $verify, $ipversion) = @_;
1333 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1334 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1336 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1337 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1340 # skip macros which are specific to another ipversion
1341 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1342 return if $ipversion != $required;
1347 foreach my $templ (@$macro_rules) {
1349 my $param_used = {};
1350 foreach my $k (keys %$templ) {
1351 my $v = $templ->{$k};
1352 if ($v eq 'PARAM') {
1354 $param_used->{$k} = 1;
1355 } elsif ($v eq 'DEST') {
1356 $v = $param->{dest
};
1357 $param_used->{dest
} = 1;
1358 } elsif ($v eq 'SOURCE') {
1359 $v = $param->{source
};
1360 $param_used->{source
} = 1;
1364 my $msg = "missing parameter '$k' in macro '$macro_name'";
1365 raise_param_exc
({ macro => $msg }) if $verify;
1370 foreach my $k (keys %$param) {
1371 next if $k eq 'macro';
1372 next if !defined($param->{$k});
1373 next if $param_used->{$k};
1374 if (defined($rule->{$k})) {
1375 if ($rule->{$k} ne $param->{$k}) {
1376 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1377 raise_param_exc
({ $k => $msg }) if $verify;
1381 $rule->{$k} = $param->{$k};
1384 push @$rules, $rule;
1390 my $rule_env_iface_lookup = {
1399 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1401 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1403 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1404 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1406 my $errors = $rule->{errors
} || {};
1408 my $error_count = 0;
1410 my $add_error = sub {
1411 my ($param, $msg) = @_;
1413 raise_param_exc
({ $param => $msg }) if !$noerr;
1415 $errors->{$param} = $msg if !$errors->{$param};
1419 my $set_ip_version = sub {
1422 die "detected mixed ipv4/ipv6 adresses in rule\n"
1423 if $ipversion && ($vers != $ipversion);
1428 my $check_ipset_or_alias_property = sub {
1429 my ($name, $expected_ipversion) = @_;
1431 if (my $value = $rule->{$name}) {
1432 if ($value =~ m/^\+/) {
1433 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1434 &$add_error($name, "no such ipset '$1'")
1435 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1438 &$add_error($name, "invalid ipset name '$value'");
1440 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1441 my $alias = lc($value);
1442 &$add_error($name, "no such alias '$value'")
1443 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1444 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1445 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1447 &$set_ip_version($e->{ipversion
});
1452 my $type = $rule->{type
};
1453 my $action = $rule->{action
};
1455 &$add_error('type', "missing property") if !$type;
1456 &$add_error('action', "missing property") if !$action;
1459 if ($type eq 'in' || $type eq 'out') {
1460 &$add_error('action', "unknown action '$action'")
1461 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1462 } elsif ($type eq 'group') {
1463 &$add_error('type', "security groups not allowed")
1465 &$add_error('action', "invalid characters in security group name")
1466 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1468 &$add_error('type', "unknown rule type '$type'");
1472 if ($rule->{iface
}) {
1473 &$add_error('type', "parameter -i not allowed for this rule type")
1475 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1476 &$add_error('iface', $@) if $@;
1477 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1478 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1479 if $rule->{iface
} !~ m/^net(\d+)$/;
1483 if ($rule->{macro}) {
1484 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1485 $rule->{macro} = $preferred_name;
1487 &$add_error('macro', "unknown macro '$rule->{macro}'");
1491 if ($rule->{proto
}) {
1492 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1493 &$add_error('proto', $@) if $@;
1494 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1495 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1498 if ($rule->{dport
}) {
1499 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1500 &$add_error('dport', $@) if $@;
1501 &$add_error('proto', "missing property - 'dport' requires this property")
1505 if ($rule->{sport
}) {
1506 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1507 &$add_error('sport', $@) if $@;
1508 &$add_error('proto', "missing property - 'sport' requires this property")
1512 if ($rule->{source
}) {
1514 my $source_ipversion = parse_address_list
($rule->{source
});
1515 &$set_ip_version($source_ipversion);
1517 &$add_error('source', $@) if $@;
1518 &$check_ipset_or_alias_property('source', $ipversion);
1521 if ($rule->{dest
}) {
1523 my $dest_ipversion = parse_address_list
($rule->{dest
});
1524 &$set_ip_version($dest_ipversion);
1526 &$add_error('dest', $@) if $@;
1527 &$check_ipset_or_alias_property('dest', $ipversion);
1530 $rule->{ipversion
} = $ipversion if $ipversion;
1532 if ($rule->{macro} && !$error_count) {
1533 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1535 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1536 my $eh = $err->{errors
};
1537 foreach my $p (keys %$eh) {
1538 &$add_error($p, $eh->{$p});
1541 &$add_error('macro', "$err");
1546 $rule->{errors
} = $errors if $error_count;
1551 sub copy_rule_data
{
1552 my ($rule, $param) = @_;
1554 foreach my $k (keys %$rule_properties) {
1555 if (defined(my $v = $param->{$k})) {
1556 if ($v eq '' || $v eq '-') {
1567 sub rules_modify_permissions
{
1568 my ($rule_env) = @_;
1570 if ($rule_env eq 'host') {
1572 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1574 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1576 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1578 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1580 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1587 sub rules_audit_permissions
{
1588 my ($rule_env) = @_;
1590 if ($rule_env eq 'host') {
1592 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1594 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1596 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1598 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1600 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1608 my $bridge_firewall_enabled = 0;
1610 sub enable_bridge_firewall
{
1612 return if $bridge_firewall_enabled; # only once
1614 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1615 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1617 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1618 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1620 $bridge_firewall_enabled = 1;
1623 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1625 sub iptables_restore_cmdlist
{
1628 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1631 sub ip6tables_restore_cmdlist
{
1634 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1637 sub ipset_restore_cmdlist
{
1640 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1643 sub iptables_get_chains
{
1644 my ($iptablescmd) = @_;
1646 $iptablescmd = "iptables" if !$iptablescmd;
1650 # check what chains we want to track
1651 my $is_pvefw_chain = sub {
1654 return 1 if $name =~ m/^PVEFW-\S+$/;
1656 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1658 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1660 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1661 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1673 return if $line =~ m/^#/;
1674 return if $line =~ m/^\s*$/;
1676 if ($line =~ m/^\*(\S+)$/) {
1681 return if $table ne 'filter';
1683 if ($line =~ m/^:(\S+)\s/) {
1685 return if !&$is_pvefw_chain($chain);
1686 $res->{$chain} = "unknown";
1687 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1688 my ($chain, $sig) = ($1, $2);
1689 return if !&$is_pvefw_chain($chain);
1690 $res->{$chain} = $sig;
1691 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1694 # simply ignore the rest
1699 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1701 return wantarray ?
($res, $hooks) : $res;
1704 sub iptables_chain_digest
{
1706 my $digest = Digest
::SHA-
>new('sha1');
1707 foreach my $rule (@$rules) { # order is important
1708 $digest->add($rule);
1710 return $digest->b64digest;
1713 sub ipset_chain_digest
{
1716 my $digest = Digest
::SHA-
>new('sha1');
1717 foreach my $rule (sort @$rules) { # note: sorted
1718 $digest->add($rule);
1720 return $digest->b64digest;
1723 sub ipset_get_chains
{
1731 return if $line =~ m/^#/;
1732 return if $line =~ m/^\s*$/;
1733 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1735 $line =~ s/\s+$//; # delete trailing white space
1736 push @{$chains->{$chain}}, $line;
1738 # simply ignore the rest
1743 run_command
("/sbin/ipset save", outfunc
=> $parser);
1745 # compute digest for each chain
1746 foreach my $chain (keys %$chains) {
1747 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1753 sub ruleset_generate_cmdstr
{
1754 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1756 return if defined($rule->{enable
}) && !$rule->{enable
};
1757 return if $rule->{errors
};
1759 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1761 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1762 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1766 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1767 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1769 my $source = $rule->{source
};
1770 my $dest = $rule->{dest
};
1773 if ($source =~ m/^\+/) {
1774 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1776 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1777 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1778 push @cmd, "-m set --match-set ${ipset_chain} src";
1779 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1780 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1781 push @cmd, "-m set --match-set ${ipset_chain} src";
1783 die "no such ipset '$name'\n";
1786 die "invalid security group name '$source'\n";
1788 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1789 my $alias = lc($source);
1790 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1791 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1792 die "no such alias '$source'\n" if !$e;
1793 push @cmd, "-s $e->{cidr}";
1794 } elsif ($source =~ m/\-/){
1795 push @cmd, "-m iprange --src-range $source";
1797 push @cmd, "-s $source";
1802 if ($dest =~ m/^\+/) {
1803 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1805 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1806 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1807 push @cmd, "-m set --match-set ${ipset_chain} dst";
1808 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1809 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1810 push @cmd, "-m set --match-set ${ipset_chain} dst";
1812 die "no such ipset '$name'\n";
1815 die "invalid security group name '$dest'\n";
1817 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1818 my $alias = lc($dest);
1819 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1820 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1821 die "no such alias '$dest'\n" if !$e;
1822 push @cmd, "-d $e->{cidr}";
1823 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1824 push @cmd, "-m iprange --dst-range $dest";
1826 push @cmd, "-d $dest";
1830 if ($rule->{proto
}) {
1831 push @cmd, "-p $rule->{proto}";
1834 $multiport++ if $nbdport > 1;
1835 $multiport++ if $nbsport > 1;
1837 push @cmd, "--match multiport" if $multiport;
1839 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1840 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1842 if ($rule->{dport
}) {
1843 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1844 # Note: we use dport to store --icmp-type
1845 die "unknown icmp-type '$rule->{dport}'\n"
1846 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1847 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1848 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1849 # Note: we use dport to store --icmpv6-type
1850 die "unknown icmpv6-type '$rule->{dport}'\n"
1851 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1852 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1855 if ($multiport == 2) {
1856 push @cmd, "--ports $rule->{dport}";
1858 push @cmd, "--dports $rule->{dport}";
1861 push @cmd, "--dport $rule->{dport}";
1866 if ($rule->{sport
}) {
1868 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1870 push @cmd, "--sport $rule->{sport}";
1873 } elsif ($rule->{dport
} || $rule->{sport
}) {
1874 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1875 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1878 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1880 if (my $action = $rule->{action
}) {
1881 $action = $actions->{$action} if defined($actions->{$action});
1882 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1883 push @cmd, $goto ?
"-g $action" : "-j $action";
1886 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1889 sub ruleset_generate_rule
{
1890 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1894 if ($rule->{macro}) {
1895 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1900 # update all or nothing
1903 foreach my $tmp (@$rules) {
1904 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1905 push @cmds, $cmdstr;
1909 foreach my $cmdstr (@cmds) {
1910 ruleset_addrule
($ruleset, $chain, $cmdstr);
1914 sub ruleset_generate_rule_insert
{
1915 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1917 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1919 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1920 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1924 sub ruleset_create_chain
{
1925 my ($ruleset, $chain) = @_;
1927 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1928 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1930 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1932 $ruleset->{$chain} = [];
1935 sub ruleset_chain_exist
{
1936 my ($ruleset, $chain) = @_;
1938 return $ruleset->{$chain} ?
1 : undef;
1941 sub ruleset_addrule
{
1942 my ($ruleset, $chain, $rule) = @_;
1944 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1946 push @{$ruleset->{$chain}}, "-A $chain $rule";
1949 sub ruleset_insertrule
{
1950 my ($ruleset, $chain, $rule) = @_;
1952 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1954 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1957 sub get_log_rule_base
{
1958 my ($chain, $vmid, $msg, $loglevel) = @_;
1960 die "internal error - no log level" if !defined($loglevel);
1962 $vmid = 0 if !defined($vmid);
1964 # Note: we use special format for prefix to pass further
1965 # info to log daemon (VMID, LOGVELEL and CHAIN)
1967 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1970 sub ruleset_addlog {
1971 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1973 return if !defined($loglevel);
1975 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1977 $logrule = "$rule $logrule" if defined($rule);
1979 ruleset_addrule($ruleset, $chain, $logrule);
1982 sub ruleset_add_chain_policy {
1983 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1985 if ($policy eq 'ACCEPT') {
1987 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
1988 { ACCEPT => $accept_action});
1990 } elsif ($policy eq 'DROP') {
1992 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1994 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1996 ruleset_addrule($ruleset, $chain, "-j DROP
");
1997 } elsif ($policy eq 'REJECT') {
1998 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
2000 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
2002 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
2005 die "internal error
: unknown policy
'$policy'";
2009 sub ruleset_chain_add_ndp {
2010 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
2011 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2013 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
$accept");
2014 if ($direction ne 'OUT' || $options->{radv}) {
2015 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
$accept");
2017 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
$accept");
2018 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
$accept");
2021 sub ruleset_chain_add_conn_filters {
2022 my ($ruleset, $chain, $accept) = @_;
2024 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
2025 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
2028 sub ruleset_chain_add_input_filters {
2029 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2031 if ($cluster_conf->{ipset}->{blacklist}){
2032 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
2033 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
2034 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
2035 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
2037 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
2038 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
2041 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
2042 if ($ipversion == 4) {
2043 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
2047 if ($options->{tcpflags}) {
2048 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
2052 sub ruleset_create_vm_chain {
2053 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
2055 ruleset_create_chain($ruleset, $chain);
2056 my $accept = generate_nfqueue($options);
2058 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
2059 if ($ipversion == 4) {
2060 if ($direction eq 'OUT') {
2061 ruleset_generate_rule($ruleset, $chain, $ipversion,
2062 { action => 'PVEFW-SET-ACCEPT-MARK',
2063 proto => 'udp', sport => 68, dport => 67 });
2065 ruleset_generate_rule($ruleset, $chain, $ipversion,
2066 { action => 'ACCEPT',
2067 proto => 'udp', sport => 67, dport => 68 });
2069 } elsif ($ipversion == 6) {
2070 if ($direction eq 'OUT') {
2071 ruleset_generate_rule($ruleset, $chain, $ipversion,
2072 { action => 'PVEFW-SET-ACCEPT-MARK',
2073 proto => 'udp', sport => 546, dport => 547 });
2075 ruleset_generate_rule($ruleset, $chain, $ipversion,
2076 { action => 'ACCEPT',
2077 proto => 'udp', sport => 547, dport => 546 });
2083 if ($direction eq 'OUT') {
2084 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
2085 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
2087 if ($ipversion == 6 && !$options->{radv}) {
2088 ruleset_addrule($ruleset, $chain, '-p icmpv6 --icmpv6-type router-advertisement -j DROP');
2090 if ($ipfilter_ipset) {
2091 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
2093 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2096 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
2097 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
2100 sub ruleset_add_group_rule {
2101 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
2103 my $group = $rule->{action};
2104 my $group_chain = "GROUP-
$group-$direction";
2105 if(!ruleset_chain_exist($ruleset, $group_chain)){
2106 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
2109 if ($direction eq 'OUT' && $rule->{iface_out}) {
2110 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
2111 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2112 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
2114 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
2117 ruleset_addrule($ruleset, $chain, "-m mark
--mark
$FWACCEPTMARK_ON -j
$action");
2120 sub ruleset_generate_vm_rules {
2121 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2123 my $lc_direction = lc($direction);
2125 my $in_accept = generate_nfqueue($options);
2127 foreach my $rule (@$rules) {
2128 next if $rule->{iface} && $rule->{iface} ne $netid;
2129 next if !$rule->{enable} || $rule->{errors};
2130 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2132 if ($rule->{type} eq 'group') {
2133 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2134 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2136 next if $rule->{type} ne $lc_direction;
2138 if ($direction eq 'OUT') {
2139 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2140 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2141 undef, $cluster_conf, $vmfw_conf);
2143 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2144 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2145 undef, $cluster_conf, $vmfw_conf);
2153 sub generate_nfqueue {
2156 if ($options->{ips}) {
2157 my $action = "NFQUEUE
";
2158 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2159 if (defined($3) && defined($1)) {
2160 $action .= " --queue-balance
$1:$3";
2161 } elsif (defined($1)) {
2162 $action .= " --queue-num
$1";
2165 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2172 sub ruleset_generate_vm_ipsrules {
2173 my ($ruleset, $options, $direction, $iface) = @_;
2175 if ($options->{ips} && $direction eq 'IN') {
2176 my $nfqueue = generate_nfqueue($options);
2178 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2179 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2182 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
2186 sub generate_tap_rules_direction {
2187 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2189 my $lc_direction = lc($direction);
2191 my $rules = $vmfw_conf->{rules};
2193 my $options = $vmfw_conf->{options};
2194 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2196 my $tapchain = "$iface-$direction";
2198 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2199 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2200 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2202 # create chain with mac and ip filter
2203 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2205 if ($options->{enable}) {
2206 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2208 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2213 if ($direction eq 'OUT') {
2214 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2216 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2219 my $accept = generate_nfqueue($options);
2220 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2221 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2223 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2224 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2227 # plug the tap chain to bridge chain
2228 if ($direction eq 'IN') {
2229 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2230 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2232 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2233 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2237 sub enable_host_firewall {
2238 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2240 my $options = $hostfw_conf->{options};
2241 my $cluster_options = $cluster_conf->{options};
2242 my $rules = $hostfw_conf->{rules};
2243 my $cluster_rules = $cluster_conf->{rules};
2245 # host inbound firewall
2246 my $chain = "PVEFW-HOST-IN
";
2247 ruleset_create_chain($ruleset, $chain);
2249 my $loglevel = get_option_log_level($options, "log_level_in
");
2251 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2253 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2254 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2255 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2257 # we use RETURN because we need to check also tap rules
2258 my $accept_action = 'RETURN';
2260 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2262 # add host rules first, so that cluster wide rules can be overwritten
2263 foreach my $rule (@$rules, @$cluster_rules) {
2264 next if !$rule->{enable} || $rule->{errors};
2265 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2267 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2270 if ($rule->{type} eq 'group') {
2271 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2272 } elsif ($rule->{type} eq 'in') {
2273 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2274 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2275 undef, $cluster_conf, $hostfw_conf);
2279 delete $rule->{iface_in};
2282 # allow standard traffic for management ipset (includes cluster network)
2283 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2284 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2285 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2286 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2287 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2288 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2290 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2291 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2294 if ($localnet && ($ipversion == $localnet_ver)) {
2295 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2296 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2297 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2300 # implement input policy
2301 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2302 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2304 # host outbound firewall
2305 $chain = "PVEFW-HOST-OUT
";
2306 ruleset_create_chain($ruleset, $chain);
2308 $loglevel = get_option_log_level($options, "log_level_out
");
2310 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2312 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2314 # we use RETURN because we may want to check other thigs later
2315 $accept_action = 'RETURN';
2316 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2318 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2320 # add host rules first, so that cluster wide rules can be overwritten
2321 foreach my $rule (@$rules, @$cluster_rules) {
2322 next if !$rule->{enable} || $rule->{errors};
2323 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2325 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2327 if ($rule->{type} eq 'group') {
2328 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2329 } elsif ($rule->{type} eq 'out') {
2330 ruleset_generate_rule($ruleset, $chain, $ipversion,
2331 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2332 undef, $cluster_conf, $hostfw_conf);
2336 delete $rule->{iface_out};
2339 # allow standard traffic on cluster network
2340 if ($localnet && ($ipversion == $localnet_ver)) {
2341 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2342 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2343 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2344 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2346 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2347 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2348 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2351 # implement output policy
2352 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2353 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2355 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2356 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2359 sub generate_group_rules {
2360 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2362 my $rules = $cluster_conf->{groups}->{$group};
2365 warn "no such security group
'$group'\n";
2366 $rules = []; # create empty chain
2369 my $chain = "GROUP-
${group
}-IN
";
2371 ruleset_create_chain($ruleset, $chain);
2372 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2374 foreach my $rule (@$rules) {
2375 next if $rule->{type} ne 'in';
2376 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2377 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2378 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2379 undef, $cluster_conf);
2382 $chain = "GROUP-
${group
}-OUT
";
2384 ruleset_create_chain($ruleset, $chain);
2385 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2387 foreach my $rule (@$rules) {
2388 next if $rule->{type} ne 'out';
2389 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2390 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2391 # check also other tap rules later
2392 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2393 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2394 undef, $cluster_conf);
2399 my $valid_netdev_names = {};
2400 for (my $i = 0; $i < $MAX_NETS; $i++) {
2401 $valid_netdev_names->{"net
$i"} = 1;
2404 sub get_mark_values {
2405 my ($value, $mask) = @_;
2406 $value = hex($value) if $value =~ /^0x/;
2407 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2408 $mask = 0xffffffff if !defined($mask);
2409 return ($value, $mask);
2413 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2415 my $orig_line = $line;
2419 # we can add single line comments to the end of the rule
2420 if ($line =~ s/#\s*(.*?)\s*$//) {
2421 $rule->{comment} = decode('utf8', $1);
2424 # we can disable a rule when prefixed with '|'
2426 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2428 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2429 die "unable to parse rule
: $line\n";
2431 $rule->{type} = lc($1);
2432 $rule->{action} = $2;
2434 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2435 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2436 $rule->{macro} = $1;
2437 $rule->{action} = $2;
2441 while (length($line)) {
2442 if ($line =~ s/^-i (\S+)\s*//) {
2443 $rule->{iface} = $1;
2447 last if $rule->{type} eq 'group';
2449 if ($line =~ s/^-p (\S+)\s*//) {
2450 $rule->{proto} = $1;
2454 if ($line =~ s/^-dport (\S+)\s*//) {
2455 $rule->{dport} = $1;
2459 if ($line =~ s/^-sport (\S+)\s*//) {
2460 $rule->{sport} = $1;
2463 if ($line =~ s/^-source (\S+)\s*//) {
2464 $rule->{source} = $1;
2467 if ($line =~ s/^-dest (\S+)\s*//) {
2475 die "unable to parse rule parameters
: $line\n" if length($line);
2477 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2478 if ($verbose && $rule->{errors}) {
2479 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2480 foreach my $p (keys %{$rule->{errors}}) {
2481 warn " $p: $rule->{errors
}->{$p}\n";
2488 sub parse_vmfw_option {
2493 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2495 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2498 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2500 $value = $2 ? lc($3) : '';
2501 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2504 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2508 die "can
't parse option '$line'\n"
2511 return ($opt, $value);
2514 sub parse_hostfw_option {
2519 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2521 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2524 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2526 $value = $2 ? lc($3) : '';
2527 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2531 die "can't parse option
'$line'\n"
2534 return ($opt, $value);
2537 sub parse_clusterfw_option {
2542 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2545 if (($value > 1) && ((time() - $value) > 60)) {
2548 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2552 die "can
't parse option '$line'\n"
2555 return ($opt, $value);
2559 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2561 my $alias = lc($cidr);
2562 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2563 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2565 die "no such alias '$cidr'\n" if !$e;;
2567 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2570 sub parse_ip_or_cidr {
2575 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2578 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2582 die "value does not look like a valid IP address or CIDR network\n";
2585 return wantarray ? ($cidr, $ipversion) : $cidr;
2591 # we can add single line comments to the end of the line
2592 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2594 if ($line =~ m/^(\S+)\s(\S+)$/) {
2595 my ($name, $cidr) = ($1, $2);
2598 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2603 ipversion => $ipversion,
2605 $data->{comment} = $comment if $comment;
2612 sub generic_fw_config_parser {
2613 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2618 my $res = $empty_conf;
2620 while (defined(my $line = <$fh>)) {
2621 next if $line =~ m/^#/;
2622 next if $line =~ m/^\s*$/;
2626 my $linenr = $fh->input_line_number();
2627 my $prefix = "$filename (line $linenr)";
2629 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2630 $section = 'options
';
2634 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2635 $section = 'aliases
';
2639 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2640 $section = 'groups
';
2644 die "security group name too long\n" if length($group) > $max_group_name_length;
2645 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2648 ($section, $group, $comment) = undef;
2649 warn "$prefix: $err";
2653 $res->{$section}->{$group} = [];
2654 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2659 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2664 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2669 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2670 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2673 ($section, $group, $comment) = undef;
2674 warn "$prefix: $err";
2678 $res->{$section}->{$group} = [];
2679 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2685 warn "$prefix: skip line - no section\n";
2689 if ($section eq 'options
') {
2692 if ($rule_env eq 'cluster
') {
2693 ($opt, $value) = parse_clusterfw_option($line);
2694 } elsif ($rule_env eq 'host
') {
2695 ($opt, $value) = parse_hostfw_option($line);
2697 ($opt, $value) = parse_vmfw_option($line);
2699 $res->{options}->{$opt} = $value;
2701 warn "$prefix: $@" if $@;
2702 } elsif ($section eq 'aliases
') {
2704 my $data = parse_alias($line);
2705 $res->{aliases}->{lc($data->{name})} = $data;
2707 warn "$prefix: $@" if $@;
2708 } elsif ($section eq 'rules
') {
2710 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2712 warn "$prefix: $err";
2715 push @{$res->{$section}}, $rule;
2716 } elsif ($section eq 'groups
') {
2718 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2720 warn "$prefix: $err";
2723 push @{$res->{$section}->{$group}}, $rule;
2724 } elsif ($section eq 'ipset
') {
2725 # we can add single line comments to the end of the rule
2726 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2728 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2733 if ($nomatch && !$feature_ipset_nomatch) {
2734 $errors->{nomatch} = "nomatch not supported by kernel";
2738 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2739 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2741 $cidr = parse_ip_or_cidr($cidr);
2746 $errors->{cidr} = $err;
2749 my $entry = { cidr => $cidr };
2750 $entry->{nomatch} = 1 if $nomatch;
2751 $entry->{comment} = $comment if $comment;
2752 $entry->{errors} = $errors if $errors;
2754 if ($verbose && $errors) {
2755 warn "$prefix - errors in ipset '$group': $line\n";
2756 foreach my $p (keys %{$errors}) {
2757 warn " $p: $errors->{$p}\n";
2761 push @{$res->{$section}->{$group}}, $entry;
2763 warn "$prefix: skip line - unknown section\n";
2771 sub parse_hostfw_config {
2772 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2774 my $empty_conf = { rules => [], options => {}};
2776 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2779 sub parse_vmfw_config {
2780 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2787 ipset_comments => {},
2790 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2793 sub parse_clusterfw_config {
2794 my ($filename, $fh, $verbose) = @_;
2804 group_comments => {},
2806 ipset_comments => {},
2809 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2813 my ($code, @param) = @_;
2817 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2824 sub read_local_vm_config {
2829 my $vmdata = { qemu => $qemu, lxc => $lxc };
2831 my $vmlist = PVE::Cluster::get_vmlist();
2832 return $vmdata if !$vmlist || !$vmlist->{ids};
2833 my $ids = $vmlist->{ids};
2835 foreach my $vmid (keys %$ids) {
2836 next if !$vmid; # skip VE0
2837 my $d = $ids->{$vmid};
2838 next if !$d->{node} || $d->{node} ne $nodename;
2839 next if !$d->{type};
2840 if ($d->{type} eq 'qemu
') {
2841 if ($have_qemu_server) {
2842 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2843 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2844 $qemu->{$vmid} = $conf;
2847 } elsif ($d->{type} eq 'lxc
') {
2849 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2850 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2851 $lxc->{$vmid} = $conf;
2860 sub load_vmfw_conf {
2861 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2865 $dir = $pvefw_conf_dir if !defined($dir);
2867 my $filename = "$dir/$vmid.fw";
2868 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2869 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2870 $vmfw_conf->{vmid} = $vmid;
2876 my $format_rules = sub {
2877 my ($rules, $allow_iface) = @_;
2881 foreach my $rule (@$rules) {
2882 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2883 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2884 $raw .= uc($rule->{type});
2885 if ($rule->{macro}) {
2886 $raw .= " $rule->{macro}($rule->{action})";
2888 $raw .= " " . $rule->{action};
2890 if ($allow_iface && $rule->{iface}) {
2891 $raw .= " -i $rule->{iface}";
2894 if ($rule->{type} ne 'group
') {
2895 $raw .= " -source $rule->{source}" if $rule->{source};
2896 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2897 $raw .= " -p $rule->{proto}" if $rule->{proto};
2898 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2899 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2902 $raw .= " # " . encode('utf8
', $rule->{comment})
2903 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2906 die "unknown rule type '$rule->{type
}'";
2913 my $format_options = sub {
2918 $raw .= "[OPTIONS]\n\n";
2919 foreach my $opt (keys %$options) {
2920 $raw .= "$opt: $options->{$opt}\n";
2927 my $format_aliases = sub {
2932 $raw .= "[ALIASES]\n\n";
2933 foreach my $k (keys %$aliases) {
2934 my $e = $aliases->{$k};
2935 $raw .= "$e->{name} $e->{cidr}";
2936 $raw .= " # " . encode('utf8
', $e->{comment})
2937 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2945 my $format_ipsets = sub {
2950 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2951 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2952 my $utf8comment = encode('utf8
', $comment);
2953 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2955 $raw .= "[IPSET $ipset]\n\n";
2957 my $options = $fw_conf->{ipset}->{$ipset};
2960 foreach my $entry (@$options) {
2961 $nethash->{$entry->{cidr}} = $entry;
2964 foreach my $cidr (sort keys %$nethash) {
2965 my $entry = $nethash->{$cidr};
2966 my $line = $entry->{nomatch} ? '!' : '';
2967 $line .= $entry->{cidr};
2968 $line .= " # " . encode('utf8
', $entry->{comment})
2969 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2979 sub save_vmfw_conf {
2980 my ($vmid, $vmfw_conf) = @_;
2984 my $options = $vmfw_conf->{options};
2985 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2987 my $aliases = $vmfw_conf->{aliases};
2988 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2990 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2992 my $rules = $vmfw_conf->{rules} || [];
2993 if ($rules && scalar(@$rules)) {
2994 $raw .= "[RULES]\n\n";
2995 $raw .= &$format_rules($rules, 1);
2999 my $filename = "$pvefw_conf_dir/$vmid.fw";
3001 mkdir $pvefw_conf_dir;
3002 PVE::Tools::file_set_contents($filename, $raw);
3008 sub remove_vmfw_conf {
3011 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3013 unlink $vmfw_conffile;
3016 sub clone_vmfw_conf {
3017 my ($vmid, $newid) = @_;
3019 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3020 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3022 if (-f $clonevm_conffile) {
3023 unlink $clonevm_conffile;
3025 if (-f $sourcevm_conffile) {
3026 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3027 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3031 sub read_vm_firewall_configs {
3032 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
3034 my $vmfw_configs = {};
3036 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3037 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
3038 next if !$vmfw_conf->{options}; # skip if file does not exists
3039 $vmfw_configs->{$vmid} = $vmfw_conf;
3041 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3042 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
3043 next if !$vmfw_conf->{options}; # skip if file does not exists
3044 $vmfw_configs->{$vmid} = $vmfw_conf;
3047 return $vmfw_configs;
3050 sub get_option_log_level {
3051 my ($options, $k) = @_;
3053 my $v = $options->{$k};
3054 $v = $default_log_level if !defined($v);
3056 return undef if $v eq '' || $v eq 'nolog
';
3058 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3060 return $v if ($v >= 0) && ($v <= 7);
3062 warn "unknown log level ($k = '$v')\n";
3067 sub generate_std_chains {
3068 my ($ruleset, $options, $ipversion) = @_;
3070 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
3072 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
3076 if ($ipversion == 4) {
3077 # same as shorewall smurflog.
3078 $chain = 'PVEFW-smurflog
';
3079 $std_chains->{$chain} = [];
3081 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3082 push @{$std_chains->{$chain}}, "-j DROP";
3085 # same as shorewall logflags action.
3086 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
3087 $chain = 'PVEFW-logflags
';
3088 $std_chains->{$chain} = [];
3090 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
3091 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3092 push @{$std_chains->{$chain}}, "-j DROP";
3094 foreach my $chain (keys %$std_chains) {
3095 ruleset_create_chain($ruleset, $chain);
3096 foreach my $rule (@{$std_chains->{$chain}}) {
3098 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
3100 ruleset_addrule($ruleset, $chain, $rule);
3106 sub generate_ipset_chains {
3107 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
3109 foreach my $ipset (keys %{$ipsets}) {
3111 my $options = $ipsets->{$ipset};
3113 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3114 if (my $ips = $device_ips->{$1}) {
3115 $options = [@$options, @$ips];
3121 foreach my $entry (@$options) {
3122 next if $entry->{errors}; # skip entries with errors
3125 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3126 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3128 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3130 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3132 # ip_compress_address takes an address only, no CIDR
3133 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3134 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3135 $cidr .= $prefix_len if defined($prefix_len);
3141 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3146 foreach my $ipversion (4, 6) {
3147 my $data = $nethash->{$ipversion};
3149 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3151 my $hashsize = scalar(@$options);
3152 if ($hashsize <= 64) {
3155 $hashsize = round_powerof2($hashsize);
3158 my $family = $ipversion == "6" ? "inet6" : "inet";
3160 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3162 foreach my $cidr (sort keys %$data) {
3163 my $entry = $data->{$cidr};
3165 my $cmd = "add $name $cidr";
3166 if ($entry->{nomatch}) {
3167 if ($feature_ipset_nomatch) {
3168 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3170 warn "ignore !$cidr - nomatch not supported by kernel\n";
3173 push @{$ipset_ruleset->{$name}}, $cmd;
3180 sub round_powerof2 {
3184 $int |= $int >> $_ foreach (1,2,4,8,16);
3188 sub load_clusterfw_conf {
3189 my ($filename, $verbose) = @_;
3191 $filename = $clusterfw_conf_filename if !defined($filename);
3193 my $cluster_conf = {};
3194 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3195 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3198 return $cluster_conf;
3201 sub save_clusterfw_conf {
3202 my ($cluster_conf) = @_;
3206 my $options = $cluster_conf->{options};
3207 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3209 my $aliases = $cluster_conf->{aliases};
3210 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3212 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3214 my $rules = $cluster_conf->{rules};
3215 if ($rules && scalar(@$rules)) {
3216 $raw .= "[RULES]\n\n";
3217 $raw .= &$format_rules($rules, 1);
3221 if ($cluster_conf->{groups}) {
3222 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3223 my $rules = $cluster_conf->{groups}->{$group};
3224 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3225 my $utf8comment = encode('utf8
', $comment);
3226 $raw .= "[group $group] # $utf8comment\n\n";
3228 $raw .= "[group $group]\n\n";
3231 $raw .= &$format_rules($rules, 0);
3237 mkdir $pvefw_conf_dir;
3238 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3240 unlink $clusterfw_conf_filename;
3244 sub load_hostfw_conf {
3245 my ($cluster_conf, $filename, $verbose) = @_;
3247 $filename = $hostfw_conf_filename if !defined($filename);
3249 my $hostfw_conf = {};
3250 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3251 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3253 return $hostfw_conf;
3256 sub save_hostfw_conf {
3257 my ($hostfw_conf) = @_;
3261 my $options = $hostfw_conf->{options};
3262 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3264 my $rules = $hostfw_conf->{rules};
3265 if ($rules && scalar(@$rules)) {
3266 $raw .= "[RULES]\n\n";
3267 $raw .= &$format_rules($rules, 1);
3272 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3274 unlink $hostfw_conf_filename;
3279 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3283 if ($vmdata) { # test mode
3284 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3285 my $filename = "$testdir/cluster.fw";
3286 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3288 $filename = "$testdir/host.fw";
3289 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3291 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3292 } else { # normal operation
3293 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3295 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3297 $vmdata = read_local_vm_config();
3298 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3301 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3304 if ($cluster_conf->{aliases}->{local_network}) {
3305 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3308 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3310 $cluster_conf->{aliases}->{local_network} = {
3311 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3314 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3316 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3317 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3318 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3320 return ($ruleset, $ipset_ruleset, $rulesetv6);
3323 sub compile_iptables_filter {
3324 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3328 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3329 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3331 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3333 my $hostfw_options = $hostfw_conf->{options} || {};
3335 # fixme: what log level should we use here?
3336 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3338 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3340 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3341 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3343 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3345 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3346 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3348 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3350 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3352 if ($hostfw_enable) {
3353 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3354 warn $@ if $@; # just to be sure - should not happen
3357 # generate firewall rules for QEMU VMs
3358 foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
3360 my $conf = $vmdata->{qemu}->{$vmid};
3361 my $vmfw_conf = $vmfw_configs->{$vmid};
3362 return if !$vmfw_conf;
3364 foreach my $netid (sort keys %$conf) {
3365 next if $netid !~ m/^net(\d+)$/;
3366 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3367 next if !$net->{firewall};
3368 my $iface = "tap${vmid}i$1";
3370 my $macaddr = $net->{macaddr};
3371 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3372 $vmfw_conf, $vmid, 'IN
', $ipversion);
3373 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3374 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3377 warn $@ if $@; # just to be sure - should not happen
3380 # generate firewall rules for LXC containers
3381 foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
3383 my $conf = $vmdata->{lxc}->{$vmid};
3384 my $vmfw_conf = $vmfw_configs->{$vmid};
3385 return if !$vmfw_conf;
3387 if ($vmfw_conf->{options}->{enable}) {
3388 foreach my $netid (sort keys %$conf) {
3389 next if $netid !~ m/^net(\d+)$/;
3390 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3391 next if !$net->{firewall};
3392 my $iface = "veth${vmid}i$1";
3393 my $macaddr = $net->{hwaddr};
3394 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3395 $vmfw_conf, $vmid, 'IN
', $ipversion);
3396 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3397 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3401 warn $@ if $@; # just to be sure - should not happen
3404 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3405 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3411 sub mac_to_linklocal {
3413 my @parts = split(/:/, $macaddr);
3414 # The standard link local address uses the fe80::/64 prefix with the
3415 # modified EUI-64 identifier derived from the MAC address by flipping the
3416 # universal/local bit and inserting FF:FE in the middle.
3418 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3419 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3420 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3423 sub compile_ipsets {
3424 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3427 if ($cluster_conf->{aliases}->{local_network}) {
3428 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3431 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3433 $cluster_conf->{aliases}->{local_network} = {
3434 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3437 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3440 my $ipset_ruleset = {};
3442 # generate ipsets for QEMU VMs
3443 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3445 my $conf = $vmdata->{qemu}->{$vmid};
3446 my $vmfw_conf = $vmfw_configs->{$vmid};
3447 return if !$vmfw_conf;
3449 # When the 'ipfilter
' option is enabled every device for which there
3450 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3452 # The reason is that ipfilter ipsets are always filled with standard
3453 # IPv6 link-local filters.
3454 my $ipsets = $vmfw_conf->{ipset};
3455 my $implicit_sets = {};
3457 my $device_ips = {};
3458 foreach my $netid (keys %$conf) {
3459 next if $netid !~ m/^net(\d+)$/;
3460 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3461 next if !$net->{firewall};
3463 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3464 $implicit_sets->{"ipfilter-$netid"} = [];
3467 my $macaddr = $net->{macaddr};
3468 my $linklocal = mac_to_linklocal($macaddr);
3469 $device_ips->{$netid} = [
3470 { cidr => $linklocal },
3471 { cidr => 'fe80
::/10', nomatch => 1 }
3475 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3476 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3478 warn $@ if $@; # just to be sure - should not happen
3481 # generate firewall rules for LXC containers
3482 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3484 my $conf = $vmdata->{lxc}->{$vmid};
3485 my $vmfw_conf = $vmfw_configs->{$vmid};
3486 return if !$vmfw_conf;
3488 # When the 'ipfilter
' option is enabled every device for which there
3489 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3491 # The reason is that ipfilter ipsets are always filled with standard
3492 # IPv6 link-local filters, as well as the IP addresses configured
3493 # for the container.
3494 my $ipsets = $vmfw_conf->{ipset};
3495 my $implicit_sets = {};
3497 my $device_ips = {};
3498 foreach my $netid (keys %$conf) {
3499 next if $netid !~ m/^net(\d+)$/;
3500 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3501 next if !$net->{firewall};
3503 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3504 $implicit_sets->{"ipfilter-$netid"} = [];
3507 my $macaddr = $net->{hwaddr};
3508 my $linklocal = mac_to_linklocal($macaddr);
3509 my $set = $device_ips->{$netid} = [
3510 { cidr => $linklocal },
3511 { cidr => 'fe80
::/10', nomatch => 1 }
3513 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3514 push @$set, { cidr => $1 };
3516 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3517 push @$set, { cidr => $1 };
3521 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3522 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3524 warn $@ if $@; # just to be sure - should not happen
3527 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3529 return $ipset_ruleset;
3532 sub get_ruleset_status {
3533 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3535 my $statushash = {};
3537 foreach my $chain (sort keys %$ruleset) {
3538 my $sig = &$digest_fn($ruleset->{$chain});
3540 $statushash->{$chain}->{sig} = $sig;
3542 my $oldsig = $active_chains->{$chain};
3543 if (!defined($oldsig)) {
3544 $statushash->{$chain}->{action} = 'create
';
3546 if ($oldsig eq $sig) {
3547 $statushash->{$chain}->{action} = 'exists';
3549 $statushash->{$chain}->{action} = 'update
';
3552 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3553 foreach my $cmd (@{$ruleset->{$chain}}) {
3554 print "\t$cmd\n" if $verbose;
3558 foreach my $chain (sort keys %$active_chains) {
3559 if (!defined($ruleset->{$chain})) {
3560 my $sig = $active_chains->{$chain};
3561 $statushash->{$chain}->{action} = 'delete';
3562 $statushash->{$chain}->{sig} = $sig;
3563 print "delete $chain ($sig)\n" if $verbose;
3570 sub print_sig_rule {
3571 my ($chain, $sig) = @_;
3573 # We just use this to store a SHA1 checksum used to detect changes
3574 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3577 sub get_ruleset_cmdlist {
3578 my ($ruleset, $verbose, $iptablescmd) = @_;
3580 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3582 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3583 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3585 # create missing chains first
3586 foreach my $chain (sort keys %$ruleset) {
3587 my $stat = $statushash->{$chain};
3588 die "internal error" if !$stat;
3589 next if $stat->{action} ne 'create
';
3591 $cmdlist .= ":$chain - [0:0]\n";
3594 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3595 my $chain = "PVEFW-$h";
3596 if ($ruleset->{$chain} && !$hooks->{$h}) {
3597 $cmdlist .= "-A $h -j $chain\n";
3601 foreach my $chain (sort keys %$ruleset) {
3602 my $stat = $statushash->{$chain};
3603 die "internal error" if !$stat;
3605 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3606 $cmdlist .= "-F $chain\n";
3607 foreach my $cmd (@{$ruleset->{$chain}}) {
3608 $cmdlist .= "$cmd\n";
3610 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3611 } elsif ($stat->{action
} eq 'delete') {
3612 die "internal error"; # this should not happen
3613 } elsif ($stat->{action
} eq 'exists') {
3616 die "internal error - unknown status '$stat->{action}'";
3620 foreach my $chain (keys %$statushash) {
3621 next if $statushash->{$chain}->{action
} ne 'delete';
3622 $cmdlist .= "-F $chain\n";
3624 foreach my $chain (keys %$statushash) {
3625 next if $statushash->{$chain}->{action
} ne 'delete';
3626 next if $chain eq 'PVEFW-INPUT';
3627 next if $chain eq 'PVEFW-OUTPUT';
3628 next if $chain eq 'PVEFW-FORWARD';
3629 $cmdlist .= "-X $chain\n";
3632 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3634 $cmdlist .= "COMMIT\n";
3636 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3639 sub get_ipset_cmdlist
{
3640 my ($ruleset, $verbose) = @_;
3644 my $delete_cmdlist = "";
3646 my $active_chains = ipset_get_chains
();
3647 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3649 # remove stale _swap chains
3650 foreach my $chain (keys %$active_chains) {
3651 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3652 $cmdlist .= "destroy $chain\n";
3656 foreach my $chain (keys %$ruleset) {
3657 my $stat = $statushash->{$chain};
3658 die "internal error" if !$stat;
3660 if ($stat->{action
} eq 'create') {
3661 foreach my $cmd (@{$ruleset->{$chain}}) {
3662 $cmdlist .= "$cmd\n";
3667 foreach my $chain (keys %$ruleset) {
3668 my $stat = $statushash->{$chain};
3669 die "internal error" if !$stat;
3671 if ($stat->{action
} eq 'update') {
3672 my $chain_swap = $chain."_swap";
3674 foreach my $cmd (@{$ruleset->{$chain}}) {
3675 $cmd =~ s/$chain/$chain_swap/;
3676 $cmdlist .= "$cmd\n";
3678 $cmdlist .= "swap $chain_swap $chain\n";
3679 $cmdlist .= "flush $chain_swap\n";
3680 $cmdlist .= "destroy $chain_swap\n";
3684 # the remove unused chains
3685 foreach my $chain (keys %$statushash) {
3686 next if $statushash->{$chain}->{action
} ne 'delete';
3688 $delete_cmdlist .= "flush $chain\n";
3689 $delete_cmdlist .= "destroy $chain\n";
3692 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3694 return ($cmdlist, $delete_cmdlist, $changes);
3698 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3700 enable_bridge_firewall
();
3702 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3703 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3705 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3706 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3709 if ($ipset_changes) {
3710 print "ipset changes:\n";
3711 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3712 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3716 print "iptables changes:\n";
3721 print "ip6tables changes:\n";
3726 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3727 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3729 ipset_restore_cmdlist
($ipset_create_cmdlist);
3731 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3732 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3734 iptables_restore_cmdlist
($cmdlist);
3736 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3737 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3739 ip6tables_restore_cmdlist
($cmdlistv6);
3741 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3742 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3744 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3746 # test: re-read status and check if everything is up to date
3747 my $active_chains = iptables_get_chains
();
3748 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3751 foreach my $chain (sort keys %$ruleset) {
3752 my $stat = $statushash->{$chain};
3753 if ($stat->{action
} ne 'exists') {
3754 warn "unable to update chain '$chain'\n";
3759 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3760 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3762 foreach my $chain (sort keys %$rulesetv6) {
3763 my $stat = $statushashv6->{$chain};
3764 if ($stat->{action
} ne 'exists') {
3765 warn "unable to update chain '$chain'\n";
3770 die "unable to apply firewall changes\n" if $errors;
3772 update_nf_conntrack_max
($hostfw_conf);
3774 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3778 sub update_nf_conntrack_max
{
3779 my ($hostfw_conf) = @_;
3781 my $max = 65536; # reasonable default
3783 my $options = $hostfw_conf->{options
} || {};
3785 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3786 $max = $options->{nf_conntrack_max
};
3787 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3790 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3791 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3793 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3795 if ($current != $max) {
3796 my $hashsize = int($max/4);
3797 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3798 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3802 sub update_nf_conntrack_tcp_timeout_established
{
3803 my ($hostfw_conf) = @_;
3805 my $options = $hostfw_conf->{options
} || {};
3807 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3809 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3812 sub remove_pvefw_chains
{
3814 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3815 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3816 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3820 sub remove_pvefw_chains_iptables
{
3821 my ($iptablescmd) = @_;
3823 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3824 my $cmdlist = "*filter\n";
3826 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3828 $cmdlist .= "-D $h -j PVEFW-$h\n";
3832 foreach my $chain (keys %$chash) {
3833 $cmdlist .= "-F $chain\n";
3836 foreach my $chain (keys %$chash) {
3837 $cmdlist .= "-X $chain\n";
3839 $cmdlist .= "COMMIT\n";
3841 if($iptablescmd eq "ip6tables") {
3842 ip6tables_restore_cmdlist
($cmdlist);
3844 iptables_restore_cmdlist
($cmdlist);
3848 sub remove_pvefw_chains_ipset
{
3850 my $ipset_chains = ipset_get_chains
();
3854 foreach my $chain (keys %$ipset_chains) {
3855 $cmdlist .= "flush $chain\n";
3856 $cmdlist .= "destroy $chain\n";
3859 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3863 my $cluster_conf = load_clusterfw_conf
();
3864 my $cluster_options = $cluster_conf->{options
};
3865 my $enable = $cluster_options->{enable
};
3869 # load required modules here
3875 my $cluster_conf = load_clusterfw_conf
();
3876 my $cluster_options = $cluster_conf->{options
};
3878 if (!$cluster_options->{enable
}) {
3879 PVE
::Firewall
::remove_pvefw_chains
();
3883 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3885 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3887 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);