8 use Socket
qw(AF_INET6 inet_ntop inet_pton);
10 use PVE
::Exception
qw(raise raise_param_exc);
11 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
14 use PVE
::Tools
qw($IPV4RE $IPV6RE);
19 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
22 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
23 my $pvefw_conf_dir = "/etc/pve/firewall";
24 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
26 # dynamically include PVE::QemuServer and PVE::LXC
27 # to avoid dependency problems
30 require PVE
::QemuServer
;
31 require PVE
::QemuConfig
;
32 $have_qemu_server = 1;
42 my $pve_fw_status_dir = "/var/lib/pve-firewall";
44 mkdir $pve_fw_status_dir; # make sure this exists
46 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
47 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
48 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
50 my $max_alias_name_length = 64;
51 my $max_ipset_name_length = 64;
52 my $max_group_name_length = 20;
54 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
55 sub pve_verify_ip_or_cidr
{
56 my ($cidr, $noerr) = @_;
58 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
59 return $cidr if Net
::IP-
>new($cidr);
60 return undef if $noerr;
61 die Net
::IP
::Error
() . "\n";
63 return undef if $noerr;
64 die "value does not look like a valid IP address or CIDR network\n";
67 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
68 sub pve_verify_ip_or_cidr_or_alias
{
69 my ($cidr, $noerr) = @_;
71 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
73 return pve_verify_ip_or_cidr
($cidr, $noerr);
76 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
77 description
=> "IP set name.",
79 pattern
=> $ipset_name_pattern,
81 maxLength
=> $max_ipset_name_length,
84 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
85 description
=> "Alias name.",
87 pattern
=> $ip_alias_pattern,
89 maxLength
=> $max_alias_name_length,
92 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
93 description
=> "Log level.",
95 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
99 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
100 description
=> "Security Group name.",
102 pattern
=> $security_group_name_pattern,
104 maxLength
=> $max_group_name_length,
107 my $feature_ipset_nomatch = 0;
109 my (undef, undef, $release) = POSIX
::uname
();
110 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
111 my ($major, $minor) = ($1, $2);
112 $feature_ipset_nomatch = 1 if ($major > 3) ||
113 ($major == 3 && $minor >= 7);
118 my $nodename = PVE
::INotify
::nodename
();
120 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
122 my $default_log_level = 'nolog'; # avoid logs by default
124 my $log_level_hash = {
135 # we need to overwrite some macros for ipv6
136 my $pve_ipv6fw_macros = {
138 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
140 'NeighborDiscovery' => [
141 "IPv6 neighbor solicitation, neighbor and router advertisement",
142 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-solicitation' },
143 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-advertisement' },
144 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-solicitation' },
145 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-advertisement' },
149 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
152 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
153 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
157 # imported/converted from: /usr/share/shorewall/macro.*
158 my $pve_fw_macros = {
161 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
162 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
165 "Auth (identd) traffic",
166 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
169 "Border Gateway Protocol traffic",
170 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
173 "BitTorrent traffic for BitTorrent 3.1 and earlier",
174 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
175 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
178 "BitTorrent traffic for BitTorrent 3.2 and later",
179 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
180 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
183 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6789' },
185 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6800:7300' },
188 "Concurrent Versions System pserver traffic",
189 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
192 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
193 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
194 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
195 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
198 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
199 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
200 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
203 "Distributed Checksum Clearinghouse spam filtering mechanism",
204 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
207 "Forwarded DHCP traffic",
208 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
211 "Domain Name System traffic (upd and tcp)",
212 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
213 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
216 "Distributed Compiler service",
217 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
220 "File Transfer Protocol",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
224 "Finger protocol (RFC 742)",
225 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
228 "GNUnet secure peer-to-peer networking traffic",
229 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
230 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
231 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
232 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
235 "Generic Routing Encapsulation tunneling protocol",
236 { action
=> 'PARAM', proto
=> '47' },
239 "Git distributed revision control traffic",
240 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
243 "OpenPGP HTTP keyserver protocol traffic",
244 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
247 "Hypertext Transfer Protocol (WWW)",
248 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
251 "Hypertext Transfer Protocol (WWW) over SSL",
252 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
255 "Internet Cache Protocol V2 (Squid) traffic",
256 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
259 "AOL Instant Messenger traffic",
260 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
263 "Internet Message Access Protocol",
264 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
267 "Internet Message Access Protocol over SSL",
268 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
271 "IPIP capsulation traffic",
272 { action
=> 'PARAM', proto
=> '94' },
276 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
277 { action
=> 'PARAM', proto
=> '50' },
280 "IPsec authentication (AH) traffic",
281 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
282 { action
=> 'PARAM', proto
=> '51' },
285 "IPsec traffic and Nat-Traversal",
286 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
287 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
288 { action
=> 'PARAM', proto
=> '50' },
291 "Internet Relay Chat traffic",
292 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
295 "HP Jetdirect printing",
296 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
299 "Layer 2 Tunneling Protocol traffic",
300 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
303 "Lightweight Directory Access Protocol traffic",
304 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
307 "Secure Lightweight Directory Access Protocol traffic",
308 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
311 "Microsoft Notification Protocol",
312 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
315 "Microsoft SQL Server",
316 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
319 "Mail traffic (SMTP, SMTPS, Submission)",
320 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
322 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
325 "Munin networked resource monitoring traffic",
326 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
330 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
333 "NNTP traffic (Usenet).",
334 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
337 "Encrypted NNTP traffic (Usenet)",
338 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
341 "Network Time Protocol (ntpd)",
342 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
345 "OSPF multicast traffic",
346 { action
=> 'PARAM', proto
=> '89' },
350 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
353 "Symantec PCAnywere (tm)",
354 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
355 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
359 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
362 "Encrypted POP3 traffic",
363 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
366 "Point-to-Point Tunneling Protocol",
367 { action
=> 'PARAM', proto
=> '47' },
368 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
372 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
379 "Line Printer protocol printing",
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
383 "Microsoft Remote Desktop Protocol traffic",
384 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
387 "Routing Information Protocol (bidirectional)",
388 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
391 "BIND remote management protocol",
392 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
395 "Razor Antispam System",
396 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
399 "Remote time retrieval (rdate)",
400 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
404 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
407 "SANE network scanning",
408 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
411 "Microsoft SMB traffic",
412 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
413 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
414 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
415 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
418 "Samba Web Administration Tool",
419 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
422 "Simple Mail Transfer Protocol",
423 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
426 "Encrypted Simple Mail Transfer Protocol",
427 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
430 "Simple Network Management Protocol",
431 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
432 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
435 "Spam Assassin SPAMD traffic",
436 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
439 "Secure shell traffic",
440 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
443 "Subversion server (svnserve)",
444 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
447 "SixXS IPv6 Deployment and Tunnel Broker",
448 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
449 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
450 { action
=> 'PARAM', proto
=> '41' },
451 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
454 "Squid web proxy traffic",
455 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
458 "Mail message submission traffic",
459 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
462 "Syslog protocol (RFC 5424) traffic",
463 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
464 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
467 "Trivial File Transfer Protocol traffic",
468 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
472 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
476 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
479 "RFC 868 Time protocol",
480 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
483 "Traceroute (for up to 30 hops) traffic",
484 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
485 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
488 "VNC traffic for VNC display's 0 - 99",
489 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
492 "VNC traffic from Vncservers to Vncviewers in listen mode",
493 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
496 "WWW traffic (HTTP and HTTPS)",
497 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
498 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
501 "Web Cache/Proxy traffic (port 8080)",
502 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
506 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
509 "Whois (nicname, RFC 3912) traffic",
510 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
514 my $pve_fw_parsed_macros;
515 my $pve_fw_macro_descr;
516 my $pve_fw_macro_ipversion = {};
517 my $pve_fw_preferred_macro_names = {};
519 my $FWACCEPTMARK_ON = "0x80000000/0x80000000";
520 my $FWACCEPTMARK_OFF = "0x00000000/0x80000000";
522 my $pve_std_chains = {};
523 $pve_std_chains->{4} = {
524 'PVEFW-SET-ACCEPT-MARK' => [
525 "-j MARK --set-mark $FWACCEPTMARK_ON",
527 'PVEFW-DropBroadcast' => [
528 # same as shorewall 'Broadcast'
529 # simply DROP BROADCAST/MULTICAST/ANYCAST
530 # we can use this to reduce logging
531 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
532 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
533 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
534 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
537 # same as shorewall 'reject'
538 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
539 { action
=> 'DROP', source
=> '224.0.0.0/4' },
540 { action
=> 'DROP', proto
=> 'icmp' },
541 "-p tcp -j REJECT --reject-with tcp-reset",
542 "-p udp -j REJECT --reject-with icmp-port-unreachable",
543 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
544 "-j REJECT --reject-with icmp-host-prohibited",
547 # same as shorewall 'Drop', which is equal to DROP,
548 # but REJECT/DROP some packages to reduce logging,
549 # and ACCEPT critical ICMP types
550 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
551 # we are not interested in BROADCAST/MULTICAST/ANYCAST
552 { action
=> 'PVEFW-DropBroadcast' },
553 # ACCEPT critical ICMP types
554 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
555 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
556 # Drop packets with INVALID state
557 "-m conntrack --ctstate INVALID -j DROP",
558 # Drop Microsoft SMB noise
559 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
560 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
561 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
562 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
563 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
564 # Drop new/NotSyn traffic so that it doesn't get logged
565 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
567 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
570 # same as shorewall 'Reject', which is equal to Reject,
571 # but REJECT/DROP some packages to reduce logging,
572 # and ACCEPT critical ICMP types
573 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
574 # we are not interested in BROADCAST/MULTICAST/ANYCAST
575 { action
=> 'PVEFW-DropBroadcast' },
576 # ACCEPT critical ICMP types
577 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
578 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
579 # Drop packets with INVALID state
580 "-m conntrack --ctstate INVALID -j DROP",
581 # Drop Microsoft SMB noise
582 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
583 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
584 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
585 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
586 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
587 # Drop new/NotSyn traffic so that it doesn't get logged
588 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
590 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
592 'PVEFW-tcpflags' => [
593 # same as shorewall tcpflags action.
594 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
595 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
596 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
597 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
598 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
599 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
602 # same as shorewall smurfs action
603 # Filter packets for smurfs (packets with a broadcast address as the source).
604 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
605 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
606 "-s 224.0.0.0/4 -g PVEFW-smurflog",
610 $pve_std_chains->{6} = {
611 'PVEFW-SET-ACCEPT-MARK' => [
612 "-j MARK --set-mark $FWACCEPTMARK_ON",
614 'PVEFW-DropBroadcast' => [
615 # same as shorewall 'Broadcast'
616 # simply DROP BROADCAST/MULTICAST/ANYCAST
617 # we can use this to reduce logging
618 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
619 # ipv6 addrtype does not work with kernel 2.6.32
620 #{ action => 'DROP', dsttype => 'MULTICAST' },
621 #{ action => 'DROP', dsttype => 'ANYCAST' },
622 { action
=> 'DROP', dest
=> 'ff00::/8' },
623 #{ action => 'DROP', dest => '224.0.0.0/4' },
626 # same as shorewall 'reject'
627 #{ action => 'DROP', dsttype => 'BROADCAST' },
628 #{ action => 'DROP', source => '224.0.0.0/4' },
629 { action
=> 'DROP', proto
=> 'icmpv6' },
630 "-p tcp -j REJECT --reject-with tcp-reset",
631 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
632 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
633 #"-j REJECT --reject-with icmp-host-prohibited",
636 # same as shorewall 'Drop', which is equal to DROP,
637 # but REJECT/DROP some packages to reduce logging,
638 # and ACCEPT critical ICMP types
639 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
640 # we are not interested in BROADCAST/MULTICAST/ANYCAST
641 { action
=> 'PVEFW-DropBroadcast' },
642 # ACCEPT critical ICMP types
643 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
644 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
645 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
647 # Drop packets with INVALID state
648 "-m conntrack --ctstate INVALID -j DROP",
649 # Drop Microsoft SMB noise
650 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
651 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
652 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
653 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
654 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
655 # Drop new/NotSyn traffic so that it doesn't get logged
656 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
658 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
661 # same as shorewall 'Reject', which is equal to Reject,
662 # but REJECT/DROP some packages to reduce logging,
663 # and ACCEPT critical ICMP types
664 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
665 # we are not interested in BROADCAST/MULTICAST/ANYCAST
666 { action
=> 'PVEFW-DropBroadcast' },
667 # ACCEPT critical ICMP types
668 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
669 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
670 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
672 # Drop packets with INVALID state
673 "-m conntrack --ctstate INVALID -j DROP",
674 # Drop Microsoft SMB noise
675 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
676 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
677 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
678 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
679 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
680 # Drop new/NotSyn traffic so that it doesn't get logged
681 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
683 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
685 'PVEFW-tcpflags' => [
686 # same as shorewall tcpflags action.
687 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
688 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
689 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
690 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
691 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
692 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
696 # iptables -p icmp -h
697 my $icmp_type_names = {
700 'destination-unreachable' => 1,
701 'network-unreachable' => 1,
702 'host-unreachable' => 1,
703 'protocol-unreachable' => 1,
704 'port-unreachable' => 1,
705 'fragmentation-needed' => 1,
706 'source-route-failed' => 1,
707 'network-unknown' => 1,
709 'network-prohibited' => 1,
710 'host-prohibited' => 1,
711 'TOS-network-unreachable' => 1,
712 'TOS-host-unreachable' => 1,
713 'communication-prohibited' => 1,
714 'host-precedence-violation' => 1,
715 'precedence-cutoff' => 1,
716 'source-quench' => 1,
718 'network-redirect' => 1,
719 'host-redirect' => 1,
720 'TOS-network-redirect' => 1,
721 'TOS-host-redirect' => 1,
723 'router-advertisement' => 1,
724 'router-solicitation' => 1,
725 'time-exceeded' => 1,
726 'ttl-zero-during-transit' => 1,
727 'ttl-zero-during-reassembly' => 1,
728 'parameter-problem' => 1,
729 'ip-header-bad' => 1,
730 'required-option-missing' => 1,
731 'timestamp-request' => 1,
732 'timestamp-reply' => 1,
733 'address-mask-request' => 1,
734 'address-mask-reply' => 1,
737 # ip6tables -p icmpv6 -h
739 my $icmpv6_type_names = {
741 'destination-unreachable' => 1,
743 'communication-prohibited' => 1,
744 'address-unreachable' => 1,
745 'port-unreachable' => 1,
746 'packet-too-big' => 1,
747 'time-exceeded' => 1,
748 'ttl-zero-during-transit' => 1,
749 'ttl-zero-during-reassembly' => 1,
750 'parameter-problem' => 1,
752 'unknown-header-type' => 1,
753 'unknown-option' => 1,
756 'router-solicitation' => 1,
757 'router-advertisement' => 1,
758 'neighbor-solicitation' => 1,
759 'neighbour-solicitation' => 1,
760 'neighbor-advertisement' => 1,
761 'neighbour-advertisement' => 1,
765 sub init_firewall_macros
{
767 $pve_fw_parsed_macros = {};
770 my ($k, $macro) = @_;
771 my $lc_name = lc($k);
772 $pve_fw_macro_ipversion->{$k} = 0;
773 while (!ref($macro->[0])) {
774 my $desc = shift @$macro;
775 if ($desc eq 'ipv4only') {
776 $pve_fw_macro_ipversion->{$k} = 4;
777 } elsif ($desc eq 'ipv6only') {
778 $pve_fw_macro_ipversion->{$k} = 6;
780 $pve_fw_macro_descr->{$k} = $desc;
783 $pve_fw_preferred_macro_names->{$lc_name} = $k;
784 $pve_fw_parsed_macros->{$k} = $macro;
787 foreach my $k (keys %$pve_fw_macros) {
788 &$parse($k, $pve_fw_macros->{$k});
791 foreach my $k (keys %$pve_ipv6fw_macros) {
792 next if $pve_fw_parsed_macros->{$k};
793 &$parse($k, $pve_ipv6fw_macros->{$k});
794 $pve_fw_macro_ipversion->{$k} = 6;
798 init_firewall_macros
();
801 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
806 sub get_etc_services
{
808 return $etc_services if $etc_services;
810 my $filename = "/etc/services";
812 my $fh = IO
::File-
>new($filename, O_RDONLY
);
814 warn "unable to read '$filename' - $!\n";
820 while (my $line = <$fh>) {
822 next if $line =~m/^#/;
823 next if ($line =~m/^\s*$/);
825 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
826 $services->{byid
}->{$2}->{name
} = $1;
827 $services->{byid
}->{$2}->{port
} = $2;
828 $services->{byid
}->{$2}->{$3} = 1;
829 $services->{byname
}->{$1} = $services->{byid
}->{$2};
835 $etc_services = $services;
838 return $etc_services;
843 sub get_etc_protocols
{
844 return $etc_protocols if $etc_protocols;
846 my $filename = "/etc/protocols";
848 my $fh = IO
::File-
>new($filename, O_RDONLY
);
850 warn "unable to read '$filename' - $!\n";
856 while (my $line = <$fh>) {
858 next if $line =~m/^#/;
859 next if ($line =~m/^\s*$/);
861 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
862 $protocols->{byid
}->{$2}->{name
} = $1;
863 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
869 # add special case for ICMP v6
870 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
871 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
873 $etc_protocols = $protocols;
875 return $etc_protocols;
878 my $ipv4_mask_hash_localnet = {
880 '255.255.128.0' => 17,
881 '255.255.192.0' => 18,
882 '255.255.224.0' => 19,
883 '255.255.240.0' => 20,
884 '255.255.248.0' => 21,
885 '255.255.252.0' => 22,
886 '255.255.254.0' => 23,
887 '255.255.255.0' => 24,
888 '255.255.255.128' => 25,
889 '255.255.255.192' => 26,
890 '255.255.255.224' => 27,
891 '255.255.255.240' => 28,
892 '255.255.255.248' => 29,
893 '255.255.255.252' => 30,
899 my ($new_value) = @_;
901 $__local_network = $new_value if defined($new_value);
903 return $__local_network if defined($__local_network);
906 my $nodename = PVE
::INotify
::nodename
();
908 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
910 my $testip = Net
::IP-
>new($ip);
912 my $isv6 = $testip->version == 6;
913 my $routes = $isv6 ? PVE
::ProcFSTools
::read_proc_net_ipv6_route
()
914 : PVE
::ProcFSTools
::read_proc_net_route
();
915 foreach my $entry (@$routes) {
918 $mask = $entry->{prefix
};
920 $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
921 next if !defined($mask);
923 my $cidr = "$entry->{dest}/$mask";
924 my $testnet = Net
::IP-
>new($cidr);
925 if ($testnet->overlaps($testip) == $Net::IP
::IP_B_IN_A_OVERLAP
) {
926 $__local_network = $cidr;
933 return $__local_network;
936 # ipset names are limited to 31 characters,
937 # and we use '-v4' or '-v6' to indicate IP versions,
938 # and we use '_swap' suffix for atomic update,
939 # for example PVEFW-${VMID}-${ipset_name}_swap
941 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
943 sub compute_ipset_chain_name
{
944 my ($vmid, $ipset_name, $ipversion) = @_;
946 $vmid = 0 if !defined($vmid);
948 my $id = "$vmid-${ipset_name}-v$ipversion";
950 if (length($id) > $max_iptables_ipset_name_length) {
951 $id = PVE
::Tools
::fnv31a_hex
($id);
957 sub compute_ipfilter_ipset_name
{
960 return "ipfilter-$iface";
963 sub parse_address_list
{
966 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
967 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
971 if ($str =~ m/^${ip_alias_pattern}$/) {
972 die "alias name too long\n" if length($str) > $max_alias_name_length;
980 foreach my $elem (split(/,/, $str)) {
982 my $ip = Net
::IP-
>new($elem);
984 my $err = Net
::IP
::Error
();
985 die "invalid IP address: $err\n";
987 $iprange = 1 if $elem =~ m/-/;
989 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
991 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
992 if $ipversion && ($new_ipversion != $ipversion);
994 $ipversion = $new_ipversion;
997 die "you can't use a range in a list\n" if $iprange && $count > 1;
1002 sub parse_port_name_number_or_range
{
1003 my ($str, $dport) = @_;
1005 my $services = PVE
::Firewall
::get_etc_services
();
1009 foreach my $item (split(/,/, $str)) {
1011 if ($item =~ m/^(\d+):(\d+)$/) {
1012 my ($port1, $port2) = ($1, $2);
1013 die "invalid port '$port1'\n" if $port1 > 65535;
1014 die "invalid port '$port2'\n" if $port2 > 65535;
1015 } elsif ($item =~ m/^(\d+)$/) {
1017 die "invalid port '$port'\n" if $port > 65535;
1019 if ($dport && $icmp_type_names->{$item}) {
1021 } elsif ($dport && $icmpv6_type_names->{$item}) {
1024 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1029 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1034 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1035 sub pve_fw_verify_sport_spec
{
1038 parse_port_name_number_or_range
($portstr, 0);
1043 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1044 sub pve_fw_verify_dport_spec
{
1047 parse_port_name_number_or_range
($portstr, 1);
1052 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1053 sub pve_fw_verify_addr_spec
{
1056 parse_address_list
($list);
1061 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1062 sub pve_fw_verify_protocol_spec
{
1065 my $protocols = get_etc_protocols
();
1067 die "unknown protocol '$proto'\n" if $proto &&
1068 !(defined($protocols->{byname
}->{$proto}) ||
1069 defined($protocols->{byid
}->{$proto}));
1075 # helper function for API
1077 sub copy_opject_with_digest
{
1080 my $sha = Digest
::SHA-
>new('sha1');
1083 foreach my $k (sort keys %$object) {
1084 my $v = $object->{$k};
1085 next if !defined($v);
1087 $sha->add($k, ':', $v, "\n");
1090 my $digest = $sha->hexdigest;
1092 $res->{digest
} = $digest;
1094 return wantarray ?
($res, $digest) : $res;
1097 sub copy_list_with_digest
{
1100 my $sha = Digest
::SHA-
>new('sha1');
1103 foreach my $entry (@$list) {
1105 foreach my $k (sort keys %$entry) {
1106 my $v = $entry->{$k};
1107 next if !defined($v);
1109 # Note: digest ignores refs ($rule->{errors})
1110 # since Digest::SHA expects a series of bytes,
1111 # we have to encode the value here to prevent errors when
1112 # using utf8 characters (eg. in comments)
1113 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1118 my $digest = $sha->hexdigest;
1120 foreach my $entry (@$res) {
1121 $entry->{digest
} = $digest;
1124 return wantarray ?
($res, $digest) : $res;
1127 our $cluster_option_properties = {
1129 description
=> "Enable or disable the firewall cluster wide.",
1135 description
=> "Input policy.",
1138 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1141 description
=> "Output policy.",
1144 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1148 our $host_option_properties = {
1150 description
=> "Enable host firewall rules.",
1154 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1155 description
=> "Log level for incoming traffic." }),
1156 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1157 description
=> "Log level for outgoing traffic." }),
1158 tcp_flags_log_level
=> get_standard_option
('pve-fw-loglevel', {
1159 description
=> "Log level for illegal tcp flags filter." }),
1160 smurf_log_level
=> get_standard_option
('pve-fw-loglevel', {
1161 description
=> "Log level for SMURFS filter." }),
1163 description
=> "Enable SMURFS filter.",
1168 description
=> "Filter illegal combinations of TCP flags.",
1172 nf_conntrack_max
=> {
1173 description
=> "Maximum number of tracked connections.",
1178 nf_conntrack_tcp_timeout_established
=> {
1179 description
=> "Conntrack established timeout.",
1185 description
=> "Enable NDP.",
1191 our $vm_option_properties = {
1193 description
=> "Enable/disable firewall rules.",
1198 description
=> "Enable/disable MAC address filter.",
1203 description
=> "Enable DHCP.",
1208 description
=> "Enable NDP.",
1213 description
=> "Allow sending Router Advertisement.",
1218 description
=> "Enable default IP filters. " .
1219 "This is equivalent to adding an empty ipfilter-net<id> ipset " .
1220 "for every interface. Such ipsets implicitly contain sane default " .
1221 "restrictions such as restricting IPv6 link local addresses to " .
1222 "the one derived from the interface's MAC address. For containers " .
1223 "the configured IP addresses will be implicitly added.",
1228 description
=> "Input policy.",
1231 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1234 description
=> "Output policy.",
1237 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1239 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1240 description
=> "Log level for incoming traffic." }),
1241 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1242 description
=> "Log level for outgoing traffic." }),
1247 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.";
1249 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.";
1251 my $rule_properties = {
1253 description
=> "Update rule at position <pos>.",
1258 digest
=> get_standard_option
('pve-config-digest'),
1262 enum
=> ['in', 'out', 'group'],
1265 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1268 pattern
=> $security_group_name_pattern,
1277 iface
=> get_standard_option
('pve-iface', {
1278 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.",
1282 description
=> "Restrict packet source address. $addr_list_descr",
1283 type
=> 'string', format
=> 'pve-fw-addr-spec',
1287 description
=> "Restrict packet destination address. $addr_list_descr",
1288 type
=> 'string', format
=> 'pve-fw-addr-spec',
1292 description
=> "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
1293 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1302 description
=> "Restrict TCP/UDP source port. $port_descr",
1303 type
=> 'string', format
=> 'pve-fw-sport-spec',
1307 description
=> "Restrict TCP/UDP destination port. $port_descr",
1308 type
=> 'string', format
=> 'pve-fw-dport-spec',
1317 sub add_rule_properties
{
1318 my ($properties) = @_;
1320 foreach my $k (keys %$rule_properties) {
1321 my $h = $rule_properties->{$k};
1322 # copy data, so that we can modify later without side effects
1323 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1329 sub delete_rule_properties
{
1330 my ($rule, $delete_str) = @_;
1332 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1333 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1334 if !defined($rule_properties->{$opt});
1335 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1336 if $opt eq 'type' || $opt eq 'action';
1337 delete $rule->{$opt};
1343 my $apply_macro = sub {
1344 my ($macro_name, $param, $verify, $ipversion) = @_;
1346 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1347 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1349 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1350 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1353 # skip macros which are specific to another ipversion
1354 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1355 return if $ipversion != $required;
1360 foreach my $templ (@$macro_rules) {
1362 my $param_used = {};
1363 foreach my $k (keys %$templ) {
1364 my $v = $templ->{$k};
1365 if ($v eq 'PARAM') {
1367 $param_used->{$k} = 1;
1368 } elsif ($v eq 'DEST') {
1369 $v = $param->{dest
};
1370 $param_used->{dest
} = 1;
1371 } elsif ($v eq 'SOURCE') {
1372 $v = $param->{source
};
1373 $param_used->{source
} = 1;
1377 my $msg = "missing parameter '$k' in macro '$macro_name'";
1378 raise_param_exc
({ macro => $msg }) if $verify;
1383 foreach my $k (keys %$param) {
1384 next if $k eq 'macro';
1385 next if !defined($param->{$k});
1386 next if $param_used->{$k};
1387 if (defined($rule->{$k})) {
1388 if ($rule->{$k} ne $param->{$k}) {
1389 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1390 raise_param_exc
({ $k => $msg }) if $verify;
1394 $rule->{$k} = $param->{$k};
1397 push @$rules, $rule;
1403 my $rule_env_iface_lookup = {
1412 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1414 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1416 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1417 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1419 my $errors = $rule->{errors
} || {};
1421 my $error_count = 0;
1423 my $add_error = sub {
1424 my ($param, $msg) = @_;
1426 raise_param_exc
({ $param => $msg }) if !$noerr;
1428 $errors->{$param} = $msg if !$errors->{$param};
1432 my $set_ip_version = sub {
1435 die "detected mixed ipv4/ipv6 adresses in rule\n"
1436 if $ipversion && ($vers != $ipversion);
1441 my $check_ipset_or_alias_property = sub {
1442 my ($name, $expected_ipversion) = @_;
1444 if (my $value = $rule->{$name}) {
1445 if ($value =~ m/^\+/) {
1446 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1447 &$add_error($name, "no such ipset '$1'")
1448 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1451 &$add_error($name, "invalid ipset name '$value'");
1453 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1454 my $alias = lc($value);
1455 &$add_error($name, "no such alias '$value'")
1456 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1457 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1458 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1460 &$set_ip_version($e->{ipversion
});
1465 my $type = $rule->{type
};
1466 my $action = $rule->{action
};
1468 &$add_error('type', "missing property") if !$type;
1469 &$add_error('action', "missing property") if !$action;
1472 if ($type eq 'in' || $type eq 'out') {
1473 &$add_error('action', "unknown action '$action'")
1474 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1475 } elsif ($type eq 'group') {
1476 &$add_error('type', "security groups not allowed")
1478 &$add_error('action', "invalid characters in security group name")
1479 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1481 &$add_error('type', "unknown rule type '$type'");
1485 if ($rule->{iface
}) {
1486 &$add_error('type', "parameter -i not allowed for this rule type")
1488 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1489 &$add_error('iface', $@) if $@;
1490 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1491 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1492 if $rule->{iface
} !~ m/^net(\d+)$/;
1496 if ($rule->{macro}) {
1497 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1498 $rule->{macro} = $preferred_name;
1500 &$add_error('macro', "unknown macro '$rule->{macro}'");
1504 if ($rule->{proto
}) {
1505 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1506 &$add_error('proto', $@) if $@;
1507 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1508 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1511 if ($rule->{dport
}) {
1512 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1513 &$add_error('dport', $@) if $@;
1514 &$add_error('proto', "missing property - 'dport' requires this property")
1518 if ($rule->{sport
}) {
1519 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1520 &$add_error('sport', $@) if $@;
1521 &$add_error('proto', "missing property - 'sport' requires this property")
1525 if ($rule->{source
}) {
1527 my $source_ipversion = parse_address_list
($rule->{source
});
1528 &$set_ip_version($source_ipversion);
1530 &$add_error('source', $@) if $@;
1531 &$check_ipset_or_alias_property('source', $ipversion);
1534 if ($rule->{dest
}) {
1536 my $dest_ipversion = parse_address_list
($rule->{dest
});
1537 &$set_ip_version($dest_ipversion);
1539 &$add_error('dest', $@) if $@;
1540 &$check_ipset_or_alias_property('dest', $ipversion);
1543 $rule->{ipversion
} = $ipversion if $ipversion;
1545 if ($rule->{macro} && !$error_count) {
1546 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1548 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1549 my $eh = $err->{errors
};
1550 foreach my $p (keys %$eh) {
1551 &$add_error($p, $eh->{$p});
1554 &$add_error('macro', "$err");
1559 $rule->{errors
} = $errors if $error_count;
1564 sub copy_rule_data
{
1565 my ($rule, $param) = @_;
1567 foreach my $k (keys %$rule_properties) {
1568 if (defined(my $v = $param->{$k})) {
1569 if ($v eq '' || $v eq '-') {
1580 sub rules_modify_permissions
{
1581 my ($rule_env) = @_;
1583 if ($rule_env eq 'host') {
1585 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1587 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1589 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1591 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1593 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1600 sub rules_audit_permissions
{
1601 my ($rule_env) = @_;
1603 if ($rule_env eq 'host') {
1605 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1607 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1609 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1611 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1613 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1621 my $bridge_firewall_enabled = 0;
1623 sub enable_bridge_firewall
{
1625 return if $bridge_firewall_enabled; # only once
1627 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1628 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1630 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1631 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1633 $bridge_firewall_enabled = 1;
1636 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1638 sub iptables_restore_cmdlist
{
1641 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1644 sub ip6tables_restore_cmdlist
{
1647 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1650 sub ipset_restore_cmdlist
{
1653 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1656 sub iptables_get_chains
{
1657 my ($iptablescmd) = @_;
1659 $iptablescmd = "iptables" if !$iptablescmd;
1663 # check what chains we want to track
1664 my $is_pvefw_chain = sub {
1667 return 1 if $name =~ m/^PVEFW-\S+$/;
1669 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1671 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1673 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1674 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1686 return if $line =~ m/^#/;
1687 return if $line =~ m/^\s*$/;
1689 if ($line =~ m/^\*(\S+)$/) {
1694 return if $table ne 'filter';
1696 if ($line =~ m/^:(\S+)\s/) {
1698 return if !&$is_pvefw_chain($chain);
1699 $res->{$chain} = "unknown";
1700 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1701 my ($chain, $sig) = ($1, $2);
1702 return if !&$is_pvefw_chain($chain);
1703 $res->{$chain} = $sig;
1704 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1707 # simply ignore the rest
1712 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1714 return wantarray ?
($res, $hooks) : $res;
1717 sub iptables_chain_digest
{
1719 my $digest = Digest
::SHA-
>new('sha1');
1720 foreach my $rule (@$rules) { # order is important
1721 $digest->add($rule);
1723 return $digest->b64digest;
1726 sub ipset_chain_digest
{
1729 my $digest = Digest
::SHA-
>new('sha1');
1730 foreach my $rule (sort @$rules) { # note: sorted
1731 $digest->add($rule);
1733 return $digest->b64digest;
1736 sub ipset_get_chains
{
1744 return if $line =~ m/^#/;
1745 return if $line =~ m/^\s*$/;
1746 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1748 $line =~ s/\s+$//; # delete trailing white space
1749 push @{$chains->{$chain}}, $line;
1751 # simply ignore the rest
1756 run_command
("/sbin/ipset save", outfunc
=> $parser);
1758 # compute digest for each chain
1759 foreach my $chain (keys %$chains) {
1760 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1766 sub ruleset_generate_cmdstr
{
1767 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1769 return if defined($rule->{enable
}) && !$rule->{enable
};
1770 return if $rule->{errors
};
1772 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1774 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1775 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1779 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1780 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1782 my $source = $rule->{source
};
1783 my $dest = $rule->{dest
};
1786 if ($source =~ m/^\+/) {
1787 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1789 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1790 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1791 push @cmd, "-m set --match-set ${ipset_chain} src";
1792 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1793 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1794 push @cmd, "-m set --match-set ${ipset_chain} src";
1796 die "no such ipset '$name'\n";
1799 die "invalid security group name '$source'\n";
1801 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1802 my $alias = lc($source);
1803 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1804 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1805 die "no such alias '$source'\n" if !$e;
1806 push @cmd, "-s $e->{cidr}";
1807 } elsif ($source =~ m/\-/){
1808 push @cmd, "-m iprange --src-range $source";
1810 push @cmd, "-s $source";
1815 if ($dest =~ m/^\+/) {
1816 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1818 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1819 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1820 push @cmd, "-m set --match-set ${ipset_chain} dst";
1821 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1822 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1823 push @cmd, "-m set --match-set ${ipset_chain} dst";
1825 die "no such ipset '$name'\n";
1828 die "invalid security group name '$dest'\n";
1830 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1831 my $alias = lc($dest);
1832 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1833 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1834 die "no such alias '$dest'\n" if !$e;
1835 push @cmd, "-d $e->{cidr}";
1836 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1837 push @cmd, "-m iprange --dst-range $dest";
1839 push @cmd, "-d $dest";
1843 if ($rule->{proto
}) {
1844 push @cmd, "-p $rule->{proto}";
1847 $multiport++ if $nbdport > 1;
1848 $multiport++ if $nbsport > 1;
1850 push @cmd, "--match multiport" if $multiport;
1852 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1853 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1855 if ($rule->{dport
}) {
1856 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1857 # Note: we use dport to store --icmp-type
1858 die "unknown icmp-type '$rule->{dport}'\n"
1859 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1860 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1861 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1862 # Note: we use dport to store --icmpv6-type
1863 die "unknown icmpv6-type '$rule->{dport}'\n"
1864 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1865 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1868 if ($multiport == 2) {
1869 push @cmd, "--ports $rule->{dport}";
1871 push @cmd, "--dports $rule->{dport}";
1874 push @cmd, "--dport $rule->{dport}";
1879 if ($rule->{sport
}) {
1881 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1883 push @cmd, "--sport $rule->{sport}";
1886 } elsif ($rule->{dport
} || $rule->{sport
}) {
1887 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1888 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1891 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1893 if (my $action = $rule->{action
}) {
1894 $action = $actions->{$action} if defined($actions->{$action});
1895 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1896 push @cmd, $goto ?
"-g $action" : "-j $action";
1899 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1902 sub ruleset_generate_rule
{
1903 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1907 if ($rule->{macro}) {
1908 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1913 # update all or nothing
1916 foreach my $tmp (@$rules) {
1917 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1918 push @cmds, $cmdstr;
1922 foreach my $cmdstr (@cmds) {
1923 ruleset_addrule
($ruleset, $chain, $cmdstr);
1927 sub ruleset_generate_rule_insert
{
1928 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1930 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1932 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1933 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1937 sub ruleset_create_chain
{
1938 my ($ruleset, $chain) = @_;
1940 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1941 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1943 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1945 $ruleset->{$chain} = [];
1948 sub ruleset_chain_exist
{
1949 my ($ruleset, $chain) = @_;
1951 return $ruleset->{$chain} ?
1 : undef;
1954 sub ruleset_addrule
{
1955 my ($ruleset, $chain, $rule) = @_;
1957 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1959 push @{$ruleset->{$chain}}, "-A $chain $rule";
1962 sub ruleset_insertrule
{
1963 my ($ruleset, $chain, $rule) = @_;
1965 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1967 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1970 sub get_log_rule_base
{
1971 my ($chain, $vmid, $msg, $loglevel) = @_;
1973 die "internal error - no log level" if !defined($loglevel);
1975 $vmid = 0 if !defined($vmid);
1977 # Note: we use special format for prefix to pass further
1978 # info to log daemon (VMID, LOGVELEL and CHAIN)
1980 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1983 sub ruleset_addlog {
1984 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1986 return if !defined($loglevel);
1988 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1990 $logrule = "$rule $logrule" if defined($rule);
1992 ruleset_addrule($ruleset, $chain, $logrule);
1995 sub ruleset_add_chain_policy {
1996 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1998 if ($policy eq 'ACCEPT') {
2000 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
2001 { ACCEPT => $accept_action});
2003 } elsif ($policy eq 'DROP') {
2005 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
2007 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
2009 ruleset_addrule($ruleset, $chain, "-j DROP
");
2010 } elsif ($policy eq 'REJECT') {
2011 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
2013 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
2015 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
2018 die "internal error
: unknown policy
'$policy'";
2022 sub ruleset_chain_add_ndp {
2023 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
2024 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2026 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
$accept");
2027 if ($direction ne 'OUT' || $options->{radv}) {
2028 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
$accept");
2030 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
$accept");
2031 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
$accept");
2034 sub ruleset_chain_add_conn_filters {
2035 my ($ruleset, $chain, $accept) = @_;
2037 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
2038 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
2041 sub ruleset_chain_add_input_filters {
2042 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2044 if ($cluster_conf->{ipset}->{blacklist}){
2045 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
2046 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
2047 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
2048 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
2050 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
2051 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
2054 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
2055 if ($ipversion == 4) {
2056 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
2060 if ($options->{tcpflags}) {
2061 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
2065 sub ruleset_create_vm_chain {
2066 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
2068 ruleset_create_chain($ruleset, $chain);
2069 my $accept = generate_nfqueue($options);
2071 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
2072 if ($ipversion == 4) {
2073 if ($direction eq 'OUT') {
2074 ruleset_generate_rule($ruleset, $chain, $ipversion,
2075 { action => 'PVEFW-SET-ACCEPT-MARK',
2076 proto => 'udp', sport => 68, dport => 67 });
2078 ruleset_generate_rule($ruleset, $chain, $ipversion,
2079 { action => 'ACCEPT',
2080 proto => 'udp', sport => 67, dport => 68 });
2082 } elsif ($ipversion == 6) {
2083 if ($direction eq 'OUT') {
2084 ruleset_generate_rule($ruleset, $chain, $ipversion,
2085 { action => 'PVEFW-SET-ACCEPT-MARK',
2086 proto => 'udp', sport => 546, dport => 547 });
2088 ruleset_generate_rule($ruleset, $chain, $ipversion,
2089 { action => 'ACCEPT',
2090 proto => 'udp', sport => 547, dport => 546 });
2096 if ($direction eq 'OUT') {
2097 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
2098 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
2100 if ($ipversion == 6 && !$options->{radv}) {
2101 ruleset_addrule($ruleset, $chain, '-p icmpv6 --icmpv6-type router-advertisement -j DROP');
2103 if ($ipfilter_ipset) {
2104 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
2106 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2109 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
2110 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
2113 sub ruleset_add_group_rule {
2114 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
2116 my $group = $rule->{action};
2117 my $group_chain = "GROUP-
$group-$direction";
2118 if(!ruleset_chain_exist($ruleset, $group_chain)){
2119 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
2122 if ($direction eq 'OUT' && $rule->{iface_out}) {
2123 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
2124 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2125 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
2127 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
2130 ruleset_addrule($ruleset, $chain, "-m mark
--mark
$FWACCEPTMARK_ON -j
$action");
2133 sub ruleset_generate_vm_rules {
2134 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2136 my $lc_direction = lc($direction);
2138 my $in_accept = generate_nfqueue($options);
2140 foreach my $rule (@$rules) {
2141 next if $rule->{iface} && $rule->{iface} ne $netid;
2142 next if !$rule->{enable} || $rule->{errors};
2143 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2145 if ($rule->{type} eq 'group') {
2146 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2147 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2149 next if $rule->{type} ne $lc_direction;
2151 if ($direction eq 'OUT') {
2152 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2153 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2154 undef, $cluster_conf, $vmfw_conf);
2156 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2157 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2158 undef, $cluster_conf, $vmfw_conf);
2166 sub generate_nfqueue {
2169 if ($options->{ips}) {
2170 my $action = "NFQUEUE
";
2171 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2172 if (defined($3) && defined($1)) {
2173 $action .= " --queue-balance
$1:$3";
2174 } elsif (defined($1)) {
2175 $action .= " --queue-num
$1";
2178 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2185 sub ruleset_generate_vm_ipsrules {
2186 my ($ruleset, $options, $direction, $iface) = @_;
2188 if ($options->{ips} && $direction eq 'IN') {
2189 my $nfqueue = generate_nfqueue($options);
2191 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2192 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2195 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
2199 sub generate_tap_rules_direction {
2200 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2202 my $lc_direction = lc($direction);
2204 my $rules = $vmfw_conf->{rules};
2206 my $options = $vmfw_conf->{options};
2207 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2209 my $tapchain = "$iface-$direction";
2211 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2212 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2213 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2215 # create chain with mac and ip filter
2216 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2218 if ($options->{enable}) {
2219 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2221 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2226 if ($direction eq 'OUT') {
2227 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2229 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2232 my $accept = generate_nfqueue($options);
2233 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2234 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2236 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2237 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2240 # plug the tap chain to bridge chain
2241 if ($direction eq 'IN') {
2242 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2243 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2245 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2246 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2250 sub enable_host_firewall {
2251 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2253 my $options = $hostfw_conf->{options};
2254 my $cluster_options = $cluster_conf->{options};
2255 my $rules = $hostfw_conf->{rules};
2256 my $cluster_rules = $cluster_conf->{rules};
2258 # host inbound firewall
2259 my $chain = "PVEFW-HOST-IN
";
2260 ruleset_create_chain($ruleset, $chain);
2262 my $loglevel = get_option_log_level($options, "log_level_in
");
2264 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2266 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2267 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2268 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2270 # we use RETURN because we need to check also tap rules
2271 my $accept_action = 'RETURN';
2273 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2275 # add host rules first, so that cluster wide rules can be overwritten
2276 foreach my $rule (@$rules, @$cluster_rules) {
2277 next if !$rule->{enable} || $rule->{errors};
2278 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2280 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2283 if ($rule->{type} eq 'group') {
2284 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2285 } elsif ($rule->{type} eq 'in') {
2286 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2287 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2288 undef, $cluster_conf, $hostfw_conf);
2292 delete $rule->{iface_in};
2295 # allow standard traffic for management ipset (includes cluster network)
2296 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2297 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2298 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2299 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2300 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2301 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2303 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2304 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2307 if ($localnet && ($ipversion == $localnet_ver)) {
2308 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2309 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2310 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2313 # implement input policy
2314 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2315 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2317 # host outbound firewall
2318 $chain = "PVEFW-HOST-OUT
";
2319 ruleset_create_chain($ruleset, $chain);
2321 $loglevel = get_option_log_level($options, "log_level_out
");
2323 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2325 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2327 # we use RETURN because we may want to check other thigs later
2328 $accept_action = 'RETURN';
2329 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2331 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2333 # add host rules first, so that cluster wide rules can be overwritten
2334 foreach my $rule (@$rules, @$cluster_rules) {
2335 next if !$rule->{enable} || $rule->{errors};
2336 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2338 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2340 if ($rule->{type} eq 'group') {
2341 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2342 } elsif ($rule->{type} eq 'out') {
2343 ruleset_generate_rule($ruleset, $chain, $ipversion,
2344 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2345 undef, $cluster_conf, $hostfw_conf);
2349 delete $rule->{iface_out};
2352 # allow standard traffic on cluster network
2353 if ($localnet && ($ipversion == $localnet_ver)) {
2354 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2355 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2356 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2357 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2359 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2360 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2361 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2364 # implement output policy
2365 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2366 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2368 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2369 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2372 sub generate_group_rules {
2373 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2375 my $rules = $cluster_conf->{groups}->{$group};
2378 warn "no such security group
'$group'\n";
2379 $rules = []; # create empty chain
2382 my $chain = "GROUP-
${group
}-IN
";
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 'in';
2389 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2390 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2391 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2392 undef, $cluster_conf);
2395 $chain = "GROUP-
${group
}-OUT
";
2397 ruleset_create_chain($ruleset, $chain);
2398 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2400 foreach my $rule (@$rules) {
2401 next if $rule->{type} ne 'out';
2402 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2403 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2404 # check also other tap rules later
2405 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2406 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2407 undef, $cluster_conf);
2412 my $valid_netdev_names = {};
2413 for (my $i = 0; $i < $MAX_NETS; $i++) {
2414 $valid_netdev_names->{"net
$i"} = 1;
2417 sub get_mark_values {
2418 my ($value, $mask) = @_;
2419 $value = hex($value) if $value =~ /^0x/;
2420 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2421 $mask = 0xffffffff if !defined($mask);
2422 return ($value, $mask);
2426 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2428 my $orig_line = $line;
2432 # we can add single line comments to the end of the rule
2433 if ($line =~ s/#\s*(.*?)\s*$//) {
2434 $rule->{comment} = decode('utf8', $1);
2437 # we can disable a rule when prefixed with '|'
2439 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2441 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2442 die "unable to parse rule
: $line\n";
2444 $rule->{type} = lc($1);
2445 $rule->{action} = $2;
2447 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2448 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2449 $rule->{macro} = $1;
2450 $rule->{action} = $2;
2454 while (length($line)) {
2455 if ($line =~ s/^-i (\S+)\s*//) {
2456 $rule->{iface} = $1;
2460 last if $rule->{type} eq 'group';
2462 if ($line =~ s/^-p (\S+)\s*//) {
2463 $rule->{proto} = $1;
2467 if ($line =~ s/^-dport (\S+)\s*//) {
2468 $rule->{dport} = $1;
2472 if ($line =~ s/^-sport (\S+)\s*//) {
2473 $rule->{sport} = $1;
2476 if ($line =~ s/^-source (\S+)\s*//) {
2477 $rule->{source} = $1;
2480 if ($line =~ s/^-dest (\S+)\s*//) {
2488 die "unable to parse rule parameters
: $line\n" if length($line);
2490 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2491 if ($verbose && $rule->{errors}) {
2492 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2493 foreach my $p (keys %{$rule->{errors}}) {
2494 warn " $p: $rule->{errors
}->{$p}\n";
2501 sub parse_vmfw_option {
2506 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2508 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2511 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2513 $value = $2 ? lc($3) : '';
2514 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2517 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2521 die "can
't parse option '$line'\n"
2524 return ($opt, $value);
2527 sub parse_hostfw_option {
2532 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2534 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2537 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2539 $value = $2 ? lc($3) : '';
2540 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2544 die "can't parse option
'$line'\n"
2547 return ($opt, $value);
2550 sub parse_clusterfw_option {
2555 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2558 if (($value > 1) && ((time() - $value) > 60)) {
2561 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2565 die "can
't parse option '$line'\n"
2568 return ($opt, $value);
2572 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2574 my $alias = lc($cidr);
2575 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2576 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2578 die "no such alias '$cidr'\n" if !$e;;
2580 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2583 sub parse_ip_or_cidr {
2588 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2591 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2595 die "value does not look like a valid IP address or CIDR network\n";
2598 return wantarray ? ($cidr, $ipversion) : $cidr;
2604 # we can add single line comments to the end of the line
2605 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2607 if ($line =~ m/^(\S+)\s(\S+)$/) {
2608 my ($name, $cidr) = ($1, $2);
2611 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2616 ipversion => $ipversion,
2618 $data->{comment} = $comment if $comment;
2625 sub generic_fw_config_parser {
2626 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2631 my $res = $empty_conf;
2633 while (defined(my $line = <$fh>)) {
2634 next if $line =~ m/^#/;
2635 next if $line =~ m/^\s*$/;
2639 my $linenr = $fh->input_line_number();
2640 my $prefix = "$filename (line $linenr)";
2642 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2643 $section = 'options
';
2647 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2648 $section = 'aliases
';
2652 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2653 $section = 'groups
';
2657 die "security group name too long\n" if length($group) > $max_group_name_length;
2658 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2661 ($section, $group, $comment) = undef;
2662 warn "$prefix: $err";
2666 $res->{$section}->{$group} = [];
2667 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2672 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2677 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2682 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2683 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2686 ($section, $group, $comment) = undef;
2687 warn "$prefix: $err";
2691 $res->{$section}->{$group} = [];
2692 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2698 warn "$prefix: skip line - no section\n";
2702 if ($section eq 'options
') {
2705 if ($rule_env eq 'cluster
') {
2706 ($opt, $value) = parse_clusterfw_option($line);
2707 } elsif ($rule_env eq 'host
') {
2708 ($opt, $value) = parse_hostfw_option($line);
2710 ($opt, $value) = parse_vmfw_option($line);
2712 $res->{options}->{$opt} = $value;
2714 warn "$prefix: $@" if $@;
2715 } elsif ($section eq 'aliases
') {
2717 my $data = parse_alias($line);
2718 $res->{aliases}->{lc($data->{name})} = $data;
2720 warn "$prefix: $@" if $@;
2721 } elsif ($section eq 'rules
') {
2723 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2725 warn "$prefix: $err";
2728 push @{$res->{$section}}, $rule;
2729 } elsif ($section eq 'groups
') {
2731 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2733 warn "$prefix: $err";
2736 push @{$res->{$section}->{$group}}, $rule;
2737 } elsif ($section eq 'ipset
') {
2738 # we can add single line comments to the end of the rule
2739 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2741 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2746 if ($nomatch && !$feature_ipset_nomatch) {
2747 $errors->{nomatch} = "nomatch not supported by kernel";
2751 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2752 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2754 $cidr = parse_ip_or_cidr($cidr);
2759 $errors->{cidr} = $err;
2762 my $entry = { cidr => $cidr };
2763 $entry->{nomatch} = 1 if $nomatch;
2764 $entry->{comment} = $comment if $comment;
2765 $entry->{errors} = $errors if $errors;
2767 if ($verbose && $errors) {
2768 warn "$prefix - errors in ipset '$group': $line\n";
2769 foreach my $p (keys %{$errors}) {
2770 warn " $p: $errors->{$p}\n";
2774 push @{$res->{$section}->{$group}}, $entry;
2776 warn "$prefix: skip line - unknown section\n";
2784 sub parse_hostfw_config {
2785 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2787 my $empty_conf = { rules => [], options => {}};
2789 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2792 sub parse_vmfw_config {
2793 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2800 ipset_comments => {},
2803 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2806 sub parse_clusterfw_config {
2807 my ($filename, $fh, $verbose) = @_;
2817 group_comments => {},
2819 ipset_comments => {},
2822 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2826 my ($code, @param) = @_;
2830 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2837 sub read_local_vm_config {
2842 my $vmdata = { qemu => $qemu, lxc => $lxc };
2844 my $vmlist = PVE::Cluster::get_vmlist();
2845 return $vmdata if !$vmlist || !$vmlist->{ids};
2846 my $ids = $vmlist->{ids};
2848 foreach my $vmid (keys %$ids) {
2849 next if !$vmid; # skip VE0
2850 my $d = $ids->{$vmid};
2851 next if !$d->{node} || $d->{node} ne $nodename;
2852 next if !$d->{type};
2853 if ($d->{type} eq 'qemu
') {
2854 if ($have_qemu_server) {
2855 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2856 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2857 $qemu->{$vmid} = $conf;
2860 } elsif ($d->{type} eq 'lxc
') {
2862 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2863 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2864 $lxc->{$vmid} = $conf;
2873 sub load_vmfw_conf {
2874 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2878 $dir = $pvefw_conf_dir if !defined($dir);
2880 my $filename = "$dir/$vmid.fw";
2881 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2882 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2883 $vmfw_conf->{vmid} = $vmid;
2889 my $format_rules = sub {
2890 my ($rules, $allow_iface) = @_;
2894 foreach my $rule (@$rules) {
2895 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2896 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2897 $raw .= uc($rule->{type});
2898 if ($rule->{macro}) {
2899 $raw .= " $rule->{macro}($rule->{action})";
2901 $raw .= " " . $rule->{action};
2903 if ($allow_iface && $rule->{iface}) {
2904 $raw .= " -i $rule->{iface}";
2907 if ($rule->{type} ne 'group
') {
2908 $raw .= " -source $rule->{source}" if $rule->{source};
2909 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2910 $raw .= " -p $rule->{proto}" if $rule->{proto};
2911 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2912 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2915 $raw .= " # " . encode('utf8
', $rule->{comment})
2916 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2919 die "unknown rule type '$rule->{type
}'";
2926 my $format_options = sub {
2931 $raw .= "[OPTIONS]\n\n";
2932 foreach my $opt (keys %$options) {
2933 $raw .= "$opt: $options->{$opt}\n";
2940 my $format_aliases = sub {
2945 $raw .= "[ALIASES]\n\n";
2946 foreach my $k (keys %$aliases) {
2947 my $e = $aliases->{$k};
2948 $raw .= "$e->{name} $e->{cidr}";
2949 $raw .= " # " . encode('utf8
', $e->{comment})
2950 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2958 my $format_ipsets = sub {
2963 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2964 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2965 my $utf8comment = encode('utf8
', $comment);
2966 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2968 $raw .= "[IPSET $ipset]\n\n";
2970 my $options = $fw_conf->{ipset}->{$ipset};
2973 foreach my $entry (@$options) {
2974 $nethash->{$entry->{cidr}} = $entry;
2977 foreach my $cidr (sort keys %$nethash) {
2978 my $entry = $nethash->{$cidr};
2979 my $line = $entry->{nomatch} ? '!' : '';
2980 $line .= $entry->{cidr};
2981 $line .= " # " . encode('utf8
', $entry->{comment})
2982 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2992 sub save_vmfw_conf {
2993 my ($vmid, $vmfw_conf) = @_;
2997 my $options = $vmfw_conf->{options};
2998 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3000 my $aliases = $vmfw_conf->{aliases};
3001 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3003 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
3005 my $rules = $vmfw_conf->{rules} || [];
3006 if ($rules && scalar(@$rules)) {
3007 $raw .= "[RULES]\n\n";
3008 $raw .= &$format_rules($rules, 1);
3012 my $filename = "$pvefw_conf_dir/$vmid.fw";
3014 mkdir $pvefw_conf_dir;
3015 PVE::Tools::file_set_contents($filename, $raw);
3021 sub remove_vmfw_conf {
3024 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3026 unlink $vmfw_conffile;
3029 sub clone_vmfw_conf {
3030 my ($vmid, $newid) = @_;
3032 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3033 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3035 if (-f $clonevm_conffile) {
3036 unlink $clonevm_conffile;
3038 if (-f $sourcevm_conffile) {
3039 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3040 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3044 sub read_vm_firewall_configs {
3045 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
3047 my $vmfw_configs = {};
3049 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3050 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
3051 next if !$vmfw_conf->{options}; # skip if file does not exists
3052 $vmfw_configs->{$vmid} = $vmfw_conf;
3054 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3055 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
3056 next if !$vmfw_conf->{options}; # skip if file does not exists
3057 $vmfw_configs->{$vmid} = $vmfw_conf;
3060 return $vmfw_configs;
3063 sub get_option_log_level {
3064 my ($options, $k) = @_;
3066 my $v = $options->{$k};
3067 $v = $default_log_level if !defined($v);
3069 return undef if $v eq '' || $v eq 'nolog
';
3071 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3073 return $v if ($v >= 0) && ($v <= 7);
3075 warn "unknown log level ($k = '$v')\n";
3080 sub generate_std_chains {
3081 my ($ruleset, $options, $ipversion) = @_;
3083 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
3085 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
3089 if ($ipversion == 4) {
3090 # same as shorewall smurflog.
3091 $chain = 'PVEFW-smurflog
';
3092 $std_chains->{$chain} = [];
3094 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3095 push @{$std_chains->{$chain}}, "-j DROP";
3098 # same as shorewall logflags action.
3099 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
3100 $chain = 'PVEFW-logflags
';
3101 $std_chains->{$chain} = [];
3103 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
3104 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3105 push @{$std_chains->{$chain}}, "-j DROP";
3107 foreach my $chain (keys %$std_chains) {
3108 ruleset_create_chain($ruleset, $chain);
3109 foreach my $rule (@{$std_chains->{$chain}}) {
3111 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
3113 ruleset_addrule($ruleset, $chain, $rule);
3119 sub generate_ipset_chains {
3120 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
3122 foreach my $ipset (keys %{$ipsets}) {
3124 my $options = $ipsets->{$ipset};
3126 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3127 if (my $ips = $device_ips->{$1}) {
3128 $options = [@$options, @$ips];
3134 foreach my $entry (@$options) {
3135 next if $entry->{errors}; # skip entries with errors
3138 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3139 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3141 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3143 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3145 # ip_compress_address takes an address only, no CIDR
3146 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3147 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3148 $cidr .= $prefix_len if defined($prefix_len);
3154 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3159 foreach my $ipversion (4, 6) {
3160 my $data = $nethash->{$ipversion};
3162 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3164 my $hashsize = scalar(@$options);
3165 if ($hashsize <= 64) {
3168 $hashsize = round_powerof2($hashsize);
3171 my $family = $ipversion == "6" ? "inet6" : "inet";
3173 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3175 foreach my $cidr (sort keys %$data) {
3176 my $entry = $data->{$cidr};
3178 my $cmd = "add $name $cidr";
3179 if ($entry->{nomatch}) {
3180 if ($feature_ipset_nomatch) {
3181 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3183 warn "ignore !$cidr - nomatch not supported by kernel\n";
3186 push @{$ipset_ruleset->{$name}}, $cmd;
3193 sub round_powerof2 {
3197 $int |= $int >> $_ foreach (1,2,4,8,16);
3201 sub load_clusterfw_conf {
3202 my ($filename, $verbose) = @_;
3204 $filename = $clusterfw_conf_filename if !defined($filename);
3206 my $cluster_conf = {};
3207 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3208 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3211 return $cluster_conf;
3214 sub save_clusterfw_conf {
3215 my ($cluster_conf) = @_;
3219 my $options = $cluster_conf->{options};
3220 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3222 my $aliases = $cluster_conf->{aliases};
3223 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3225 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3227 my $rules = $cluster_conf->{rules};
3228 if ($rules && scalar(@$rules)) {
3229 $raw .= "[RULES]\n\n";
3230 $raw .= &$format_rules($rules, 1);
3234 if ($cluster_conf->{groups}) {
3235 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3236 my $rules = $cluster_conf->{groups}->{$group};
3237 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3238 my $utf8comment = encode('utf8
', $comment);
3239 $raw .= "[group $group] # $utf8comment\n\n";
3241 $raw .= "[group $group]\n\n";
3244 $raw .= &$format_rules($rules, 0);
3250 mkdir $pvefw_conf_dir;
3251 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3253 unlink $clusterfw_conf_filename;
3257 sub load_hostfw_conf {
3258 my ($cluster_conf, $filename, $verbose) = @_;
3260 $filename = $hostfw_conf_filename if !defined($filename);
3262 my $hostfw_conf = {};
3263 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3264 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3266 return $hostfw_conf;
3269 sub save_hostfw_conf {
3270 my ($hostfw_conf) = @_;
3274 my $options = $hostfw_conf->{options};
3275 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3277 my $rules = $hostfw_conf->{rules};
3278 if ($rules && scalar(@$rules)) {
3279 $raw .= "[RULES]\n\n";
3280 $raw .= &$format_rules($rules, 1);
3285 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3287 unlink $hostfw_conf_filename;
3292 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3296 if ($vmdata) { # test mode
3297 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3298 my $filename = "$testdir/cluster.fw";
3299 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3301 $filename = "$testdir/host.fw";
3302 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3304 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3305 } else { # normal operation
3306 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3308 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3310 $vmdata = read_local_vm_config();
3311 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3314 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3317 if ($cluster_conf->{aliases}->{local_network}) {
3318 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3321 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3323 $cluster_conf->{aliases}->{local_network} = {
3324 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3327 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3329 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3330 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3331 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3333 return ($ruleset, $ipset_ruleset, $rulesetv6);
3336 sub compile_iptables_filter {
3337 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3341 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3342 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3344 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3346 my $hostfw_options = $hostfw_conf->{options} || {};
3348 # fixme: what log level should we use here?
3349 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3351 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3353 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3354 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3356 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3358 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3359 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3361 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3363 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3365 if ($hostfw_enable) {
3366 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3367 warn $@ if $@; # just to be sure - should not happen
3370 # generate firewall rules for QEMU VMs
3371 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3373 my $conf = $vmdata->{qemu}->{$vmid};
3374 my $vmfw_conf = $vmfw_configs->{$vmid};
3375 return if !$vmfw_conf;
3377 foreach my $netid (keys %$conf) {
3378 next if $netid !~ m/^net(\d+)$/;
3379 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3380 next if !$net->{firewall};
3381 my $iface = "tap${vmid}i$1";
3383 my $macaddr = $net->{macaddr};
3384 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3385 $vmfw_conf, $vmid, 'IN
', $ipversion);
3386 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3387 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3390 warn $@ if $@; # just to be sure - should not happen
3393 # generate firewall rules for LXC containers
3394 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3396 my $conf = $vmdata->{lxc}->{$vmid};
3397 my $vmfw_conf = $vmfw_configs->{$vmid};
3398 return if !$vmfw_conf;
3400 if ($vmfw_conf->{options}->{enable}) {
3401 foreach my $netid (keys %$conf) {
3402 next if $netid !~ m/^net(\d+)$/;
3403 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3404 next if !$net->{firewall};
3405 my $iface = "veth${vmid}i$1";
3406 my $macaddr = $net->{hwaddr};
3407 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3408 $vmfw_conf, $vmid, 'IN
', $ipversion);
3409 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3410 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3414 warn $@ if $@; # just to be sure - should not happen
3417 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3418 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3424 sub mac_to_linklocal {
3426 my @parts = split(/:/, $macaddr);
3427 # The standard link local address uses the fe80::/64 prefix with the
3428 # modified EUI-64 identifier derived from the MAC address by flipping the
3429 # universal/local bit and inserting FF:FE in the middle.
3431 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3432 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3433 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3436 sub compile_ipsets {
3437 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3440 if ($cluster_conf->{aliases}->{local_network}) {
3441 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3444 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3446 $cluster_conf->{aliases}->{local_network} = {
3447 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3450 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3453 my $ipset_ruleset = {};
3455 # generate ipsets for QEMU VMs
3456 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3458 my $conf = $vmdata->{qemu}->{$vmid};
3459 my $vmfw_conf = $vmfw_configs->{$vmid};
3460 return if !$vmfw_conf;
3462 # When the 'ipfilter
' option is enabled every device for which there
3463 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3465 # The reason is that ipfilter ipsets are always filled with standard
3466 # IPv6 link-local filters.
3467 my $ipsets = $vmfw_conf->{ipset};
3468 my $implicit_sets = {};
3470 my $device_ips = {};
3471 foreach my $netid (keys %$conf) {
3472 next if $netid !~ m/^net(\d+)$/;
3473 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3474 next if !$net->{firewall};
3476 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3477 $implicit_sets->{"ipfilter-$netid"} = [];
3480 my $macaddr = $net->{macaddr};
3481 my $linklocal = mac_to_linklocal($macaddr);
3482 $device_ips->{$netid} = [
3483 { cidr => $linklocal },
3484 { cidr => 'fe80
::/10', nomatch => 1 }
3488 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3489 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3491 warn $@ if $@; # just to be sure - should not happen
3494 # generate firewall rules for LXC containers
3495 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3497 my $conf = $vmdata->{lxc}->{$vmid};
3498 my $vmfw_conf = $vmfw_configs->{$vmid};
3499 return if !$vmfw_conf;
3501 # When the 'ipfilter
' option is enabled every device for which there
3502 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3504 # The reason is that ipfilter ipsets are always filled with standard
3505 # IPv6 link-local filters, as well as the IP addresses configured
3506 # for the container.
3507 my $ipsets = $vmfw_conf->{ipset};
3508 my $implicit_sets = {};
3510 my $device_ips = {};
3511 foreach my $netid (keys %$conf) {
3512 next if $netid !~ m/^net(\d+)$/;
3513 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3514 next if !$net->{firewall};
3516 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3517 $implicit_sets->{"ipfilter-$netid"} = [];
3520 my $macaddr = $net->{hwaddr};
3521 my $linklocal = mac_to_linklocal($macaddr);
3522 my $set = $device_ips->{$netid} = [
3523 { cidr => $linklocal },
3524 { cidr => 'fe80
::/10', nomatch => 1 }
3526 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3527 push @$set, { cidr => $1 };
3529 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3530 push @$set, { cidr => $1 };
3534 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3535 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3537 warn $@ if $@; # just to be sure - should not happen
3540 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3542 return $ipset_ruleset;
3545 sub get_ruleset_status {
3546 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3548 my $statushash = {};
3550 foreach my $chain (sort keys %$ruleset) {
3551 my $sig = &$digest_fn($ruleset->{$chain});
3553 $statushash->{$chain}->{sig} = $sig;
3555 my $oldsig = $active_chains->{$chain};
3556 if (!defined($oldsig)) {
3557 $statushash->{$chain}->{action} = 'create
';
3559 if ($oldsig eq $sig) {
3560 $statushash->{$chain}->{action} = 'exists';
3562 $statushash->{$chain}->{action} = 'update
';
3565 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3566 foreach my $cmd (@{$ruleset->{$chain}}) {
3567 print "\t$cmd\n" if $verbose;
3571 foreach my $chain (sort keys %$active_chains) {
3572 if (!defined($ruleset->{$chain})) {
3573 my $sig = $active_chains->{$chain};
3574 $statushash->{$chain}->{action} = 'delete';
3575 $statushash->{$chain}->{sig} = $sig;
3576 print "delete $chain ($sig)\n" if $verbose;
3583 sub print_sig_rule {
3584 my ($chain, $sig) = @_;
3586 # We just use this to store a SHA1 checksum used to detect changes
3587 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3590 sub get_ruleset_cmdlist {
3591 my ($ruleset, $verbose, $iptablescmd) = @_;
3593 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3595 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3596 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3598 # create missing chains first
3599 foreach my $chain (sort keys %$ruleset) {
3600 my $stat = $statushash->{$chain};
3601 die "internal error" if !$stat;
3602 next if $stat->{action} ne 'create
';
3604 $cmdlist .= ":$chain - [0:0]\n";
3607 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3608 my $chain = "PVEFW-$h";
3609 if ($ruleset->{$chain} && !$hooks->{$h}) {
3610 $cmdlist .= "-A $h -j $chain\n";
3614 foreach my $chain (sort keys %$ruleset) {
3615 my $stat = $statushash->{$chain};
3616 die "internal error" if !$stat;
3618 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3619 $cmdlist .= "-F $chain\n";
3620 foreach my $cmd (@{$ruleset->{$chain}}) {
3621 $cmdlist .= "$cmd\n";
3623 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3624 } elsif ($stat->{action
} eq 'delete') {
3625 die "internal error"; # this should not happen
3626 } elsif ($stat->{action
} eq 'exists') {
3629 die "internal error - unknown status '$stat->{action}'";
3633 foreach my $chain (keys %$statushash) {
3634 next if $statushash->{$chain}->{action
} ne 'delete';
3635 $cmdlist .= "-F $chain\n";
3637 foreach my $chain (keys %$statushash) {
3638 next if $statushash->{$chain}->{action
} ne 'delete';
3639 next if $chain eq 'PVEFW-INPUT';
3640 next if $chain eq 'PVEFW-OUTPUT';
3641 next if $chain eq 'PVEFW-FORWARD';
3642 $cmdlist .= "-X $chain\n";
3645 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3647 $cmdlist .= "COMMIT\n";
3649 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3652 sub get_ipset_cmdlist
{
3653 my ($ruleset, $verbose) = @_;
3657 my $delete_cmdlist = "";
3659 my $active_chains = ipset_get_chains
();
3660 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3662 # remove stale _swap chains
3663 foreach my $chain (keys %$active_chains) {
3664 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3665 $cmdlist .= "destroy $chain\n";
3669 foreach my $chain (keys %$ruleset) {
3670 my $stat = $statushash->{$chain};
3671 die "internal error" if !$stat;
3673 if ($stat->{action
} eq 'create') {
3674 foreach my $cmd (@{$ruleset->{$chain}}) {
3675 $cmdlist .= "$cmd\n";
3680 foreach my $chain (keys %$ruleset) {
3681 my $stat = $statushash->{$chain};
3682 die "internal error" if !$stat;
3684 if ($stat->{action
} eq 'update') {
3685 my $chain_swap = $chain."_swap";
3687 foreach my $cmd (@{$ruleset->{$chain}}) {
3688 $cmd =~ s/$chain/$chain_swap/;
3689 $cmdlist .= "$cmd\n";
3691 $cmdlist .= "swap $chain_swap $chain\n";
3692 $cmdlist .= "flush $chain_swap\n";
3693 $cmdlist .= "destroy $chain_swap\n";
3697 # the remove unused chains
3698 foreach my $chain (keys %$statushash) {
3699 next if $statushash->{$chain}->{action
} ne 'delete';
3701 $delete_cmdlist .= "flush $chain\n";
3702 $delete_cmdlist .= "destroy $chain\n";
3705 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3707 return ($cmdlist, $delete_cmdlist, $changes);
3711 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3713 enable_bridge_firewall
();
3715 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3716 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3718 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3719 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3722 if ($ipset_changes) {
3723 print "ipset changes:\n";
3724 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3725 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3729 print "iptables changes:\n";
3734 print "ip6tables changes:\n";
3739 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3740 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3742 ipset_restore_cmdlist
($ipset_create_cmdlist);
3744 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3745 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3747 iptables_restore_cmdlist
($cmdlist);
3749 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3750 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3752 ip6tables_restore_cmdlist
($cmdlistv6);
3754 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3755 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3757 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3759 # test: re-read status and check if everything is up to date
3760 my $active_chains = iptables_get_chains
();
3761 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3764 foreach my $chain (sort keys %$ruleset) {
3765 my $stat = $statushash->{$chain};
3766 if ($stat->{action
} ne 'exists') {
3767 warn "unable to update chain '$chain'\n";
3772 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3773 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3775 foreach my $chain (sort keys %$rulesetv6) {
3776 my $stat = $statushashv6->{$chain};
3777 if ($stat->{action
} ne 'exists') {
3778 warn "unable to update chain '$chain'\n";
3783 die "unable to apply firewall changes\n" if $errors;
3785 update_nf_conntrack_max
($hostfw_conf);
3787 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3791 sub update_nf_conntrack_max
{
3792 my ($hostfw_conf) = @_;
3794 my $max = 65536; # reasonable default
3796 my $options = $hostfw_conf->{options
} || {};
3798 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3799 $max = $options->{nf_conntrack_max
};
3800 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3803 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3804 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3806 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3808 if ($current != $max) {
3809 my $hashsize = int($max/4);
3810 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3811 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3815 sub update_nf_conntrack_tcp_timeout_established
{
3816 my ($hostfw_conf) = @_;
3818 my $options = $hostfw_conf->{options
} || {};
3820 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3822 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3825 sub remove_pvefw_chains
{
3827 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3828 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3829 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3833 sub remove_pvefw_chains_iptables
{
3834 my ($iptablescmd) = @_;
3836 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3837 my $cmdlist = "*filter\n";
3839 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3841 $cmdlist .= "-D $h -j PVEFW-$h\n";
3845 foreach my $chain (keys %$chash) {
3846 $cmdlist .= "-F $chain\n";
3849 foreach my $chain (keys %$chash) {
3850 $cmdlist .= "-X $chain\n";
3852 $cmdlist .= "COMMIT\n";
3854 if($iptablescmd eq "ip6tables") {
3855 ip6tables_restore_cmdlist
($cmdlist);
3857 iptables_restore_cmdlist
($cmdlist);
3861 sub remove_pvefw_chains_ipset
{
3863 my $ipset_chains = ipset_get_chains
();
3867 foreach my $chain (keys %$ipset_chains) {
3868 $cmdlist .= "flush $chain\n";
3869 $cmdlist .= "destroy $chain\n";
3872 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3876 my $cluster_conf = load_clusterfw_conf
();
3877 my $cluster_options = $cluster_conf->{options
};
3878 my $enable = $cluster_options->{enable
};
3882 # load required modules here
3888 my $cluster_conf = load_clusterfw_conf
();
3889 my $cluster_options = $cluster_conf->{options
};
3891 if (!$cluster_options->{enable
}) {
3892 PVE
::Firewall
::remove_pvefw_chains
();
3896 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3898 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3900 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);