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' },
148 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
151 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
152 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
156 # imported/converted from: /usr/share/shorewall/macro.*
157 my $pve_fw_macros = {
160 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
161 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
164 "Auth (identd) traffic",
165 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
168 "Border Gateway Protocol traffic",
169 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
172 "BitTorrent traffic for BitTorrent 3.1 and earlier",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
174 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
177 "BitTorrent traffic for BitTorrent 3.2 and later",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
179 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
182 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
183 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6789' },
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6800:7300' },
187 "Concurrent Versions System pserver traffic",
188 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
191 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
192 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
193 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
197 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
199 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
202 "Distributed Checksum Clearinghouse spam filtering mechanism",
203 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
206 "Forwarded DHCP traffic",
207 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
210 "Domain Name System traffic (upd and tcp)",
211 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
212 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
215 "Distributed Compiler service",
216 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
219 "File Transfer Protocol",
220 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
223 "Finger protocol (RFC 742)",
224 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
227 "GNUnet secure peer-to-peer networking traffic",
228 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
229 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
230 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
231 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
234 "Generic Routing Encapsulation tunneling protocol",
235 { action
=> 'PARAM', proto
=> '47' },
238 "Git distributed revision control traffic",
239 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
242 "OpenPGP HTTP keyserver protocol traffic",
243 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
246 "Hypertext Transfer Protocol (WWW)",
247 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
250 "Hypertext Transfer Protocol (WWW) over SSL",
251 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
254 "Internet Cache Protocol V2 (Squid) traffic",
255 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
258 "AOL Instant Messenger traffic",
259 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
262 "Internet Message Access Protocol",
263 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
266 "Internet Message Access Protocol over SSL",
267 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
270 "IPIP capsulation traffic",
271 { action
=> 'PARAM', proto
=> '94' },
275 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
276 { action
=> 'PARAM', proto
=> '50' },
279 "IPsec authentication (AH) traffic",
280 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
281 { action
=> 'PARAM', proto
=> '51' },
284 "IPsec traffic and Nat-Traversal",
285 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
286 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
287 { action
=> 'PARAM', proto
=> '50' },
290 "Internet Relay Chat traffic",
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
294 "HP Jetdirect printing",
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
298 "Layer 2 Tunneling Protocol traffic",
299 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
302 "Lightweight Directory Access Protocol traffic",
303 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
306 "Secure Lightweight Directory Access Protocol traffic",
307 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
310 "Microsoft Notification Protocol",
311 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
314 "Microsoft SQL Server",
315 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
318 "Mail traffic (SMTP, SMTPS, Submission)",
319 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
320 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
324 "Munin networked resource monitoring traffic",
325 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
332 "NNTP traffic (Usenet).",
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
336 "Encrypted NNTP traffic (Usenet)",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
340 "Network Time Protocol (ntpd)",
341 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
344 "OSPF multicast traffic",
345 { action
=> 'PARAM', proto
=> '89' },
349 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
352 "Symantec PCAnywere (tm)",
353 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
354 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
358 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
361 "Encrypted POP3 traffic",
362 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
365 "Point-to-Point Tunneling Protocol",
366 { action
=> 'PARAM', proto
=> '47' },
367 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
371 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
375 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
378 "Line Printer protocol printing",
379 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
382 "Microsoft Remote Desktop Protocol traffic",
383 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
386 "Routing Information Protocol (bidirectional)",
387 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
390 "BIND remote management protocol",
391 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
394 "Razor Antispam System",
395 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
398 "Remote time retrieval (rdate)",
399 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
403 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
406 "SANE network scanning",
407 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
410 "Microsoft SMB traffic",
411 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
412 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
413 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
414 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
417 "Samba Web Administration Tool",
418 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
421 "Simple Mail Transfer Protocol",
422 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
425 "Encrypted Simple Mail Transfer Protocol",
426 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
429 "Simple Network Management Protocol",
430 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
431 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
434 "Spam Assassin SPAMD traffic",
435 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
438 "Secure shell traffic",
439 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
442 "Subversion server (svnserve)",
443 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
446 "SixXS IPv6 Deployment and Tunnel Broker",
447 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
448 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
449 { action
=> 'PARAM', proto
=> '41' },
450 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
453 "Squid web proxy traffic",
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
457 "Mail message submission traffic",
458 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
461 "Syslog protocol (RFC 5424) traffic",
462 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
466 "Trivial File Transfer Protocol traffic",
467 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
471 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
475 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
478 "RFC 868 Time protocol",
479 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
482 "Traceroute (for up to 30 hops) traffic",
483 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
484 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
487 "VNC traffic for VNC display's 0 - 99",
488 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
491 "VNC traffic from Vncservers to Vncviewers in listen mode",
492 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
495 "WWW traffic (HTTP and HTTPS)",
496 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
497 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
500 "Web Cache/Proxy traffic (port 8080)",
501 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
505 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
508 "Whois (nicname, RFC 3912) traffic",
509 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
513 my $pve_fw_parsed_macros;
514 my $pve_fw_macro_descr;
515 my $pve_fw_macro_ipversion = {};
516 my $pve_fw_preferred_macro_names = {};
518 my $pve_std_chains = {};
519 $pve_std_chains->{4} = {
520 'PVEFW-SET-ACCEPT-MARK' => [
521 "-j MARK --set-mark 1",
523 'PVEFW-DropBroadcast' => [
524 # same as shorewall 'Broadcast'
525 # simply DROP BROADCAST/MULTICAST/ANYCAST
526 # we can use this to reduce logging
527 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
528 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
529 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
530 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
533 # same as shorewall 'reject'
534 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
535 { action
=> 'DROP', source
=> '224.0.0.0/4' },
536 { action
=> 'DROP', proto
=> 'icmp' },
537 "-p tcp -j REJECT --reject-with tcp-reset",
538 "-p udp -j REJECT --reject-with icmp-port-unreachable",
539 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
540 "-j REJECT --reject-with icmp-host-prohibited",
543 # same as shorewall 'Drop', which is equal to DROP,
544 # but REJECT/DROP some packages to reduce logging,
545 # and ACCEPT critical ICMP types
546 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
547 # we are not interested in BROADCAST/MULTICAST/ANYCAST
548 { action
=> 'PVEFW-DropBroadcast' },
549 # ACCEPT critical ICMP types
550 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
551 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
552 # Drop packets with INVALID state
553 "-m conntrack --ctstate INVALID -j DROP",
554 # Drop Microsoft SMB noise
555 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
556 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
557 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
558 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
559 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
560 # Drop new/NotSyn traffic so that it doesn't get logged
561 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
563 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
566 # same as shorewall 'Reject', which is equal to Reject,
567 # but REJECT/DROP some packages to reduce logging,
568 # and ACCEPT critical ICMP types
569 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
570 # we are not interested in BROADCAST/MULTICAST/ANYCAST
571 { action
=> 'PVEFW-DropBroadcast' },
572 # ACCEPT critical ICMP types
573 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
574 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
575 # Drop packets with INVALID state
576 "-m conntrack --ctstate INVALID -j DROP",
577 # Drop Microsoft SMB noise
578 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
579 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
580 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
581 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
582 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
583 # Drop new/NotSyn traffic so that it doesn't get logged
584 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
586 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
588 'PVEFW-tcpflags' => [
589 # same as shorewall tcpflags action.
590 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
591 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
592 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
593 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
594 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
595 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
598 # same as shorewall smurfs action
599 # Filter packets for smurfs (packets with a broadcast address as the source).
600 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
601 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
602 "-s 224.0.0.0/4 -g PVEFW-smurflog",
606 $pve_std_chains->{6} = {
607 'PVEFW-SET-ACCEPT-MARK' => [
608 "-j MARK --set-mark 1",
610 'PVEFW-DropBroadcast' => [
611 # same as shorewall 'Broadcast'
612 # simply DROP BROADCAST/MULTICAST/ANYCAST
613 # we can use this to reduce logging
614 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
615 # ipv6 addrtype does not work with kernel 2.6.32
616 #{ action => 'DROP', dsttype => 'MULTICAST' },
617 #{ action => 'DROP', dsttype => 'ANYCAST' },
618 { action
=> 'DROP', dest
=> 'ff00::/8' },
619 #{ action => 'DROP', dest => '224.0.0.0/4' },
622 # same as shorewall 'reject'
623 #{ action => 'DROP', dsttype => 'BROADCAST' },
624 #{ action => 'DROP', source => '224.0.0.0/4' },
625 { action
=> 'DROP', proto
=> 'icmpv6' },
626 "-p tcp -j REJECT --reject-with tcp-reset",
627 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
628 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
629 #"-j REJECT --reject-with icmp-host-prohibited",
632 # same as shorewall 'Drop', which is equal to DROP,
633 # but REJECT/DROP some packages to reduce logging,
634 # and ACCEPT critical ICMP types
635 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
636 # we are not interested in BROADCAST/MULTICAST/ANYCAST
637 { action
=> 'PVEFW-DropBroadcast' },
638 # ACCEPT critical ICMP types
639 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
640 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
641 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
643 # Drop packets with INVALID state
644 "-m conntrack --ctstate INVALID -j DROP",
645 # Drop Microsoft SMB noise
646 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
647 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
648 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
649 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
650 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
651 # Drop new/NotSyn traffic so that it doesn't get logged
652 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
654 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
657 # same as shorewall 'Reject', which is equal to Reject,
658 # but REJECT/DROP some packages to reduce logging,
659 # and ACCEPT critical ICMP types
660 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
661 # we are not interested in BROADCAST/MULTICAST/ANYCAST
662 { action
=> 'PVEFW-DropBroadcast' },
663 # ACCEPT critical ICMP types
664 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
665 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
666 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
668 # Drop packets with INVALID state
669 "-m conntrack --ctstate INVALID -j DROP",
670 # Drop Microsoft SMB noise
671 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
672 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
673 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
674 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
675 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
676 # Drop new/NotSyn traffic so that it doesn't get logged
677 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
679 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
681 'PVEFW-tcpflags' => [
682 # same as shorewall tcpflags action.
683 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
684 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
685 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
686 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
687 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
688 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
692 # iptables -p icmp -h
693 my $icmp_type_names = {
696 'destination-unreachable' => 1,
697 'network-unreachable' => 1,
698 'host-unreachable' => 1,
699 'protocol-unreachable' => 1,
700 'port-unreachable' => 1,
701 'fragmentation-needed' => 1,
702 'source-route-failed' => 1,
703 'network-unknown' => 1,
705 'network-prohibited' => 1,
706 'host-prohibited' => 1,
707 'TOS-network-unreachable' => 1,
708 'TOS-host-unreachable' => 1,
709 'communication-prohibited' => 1,
710 'host-precedence-violation' => 1,
711 'precedence-cutoff' => 1,
712 'source-quench' => 1,
714 'network-redirect' => 1,
715 'host-redirect' => 1,
716 'TOS-network-redirect' => 1,
717 'TOS-host-redirect' => 1,
719 'router-advertisement' => 1,
720 'router-solicitation' => 1,
721 'time-exceeded' => 1,
722 'ttl-zero-during-transit' => 1,
723 'ttl-zero-during-reassembly' => 1,
724 'parameter-problem' => 1,
725 'ip-header-bad' => 1,
726 'required-option-missing' => 1,
727 'timestamp-request' => 1,
728 'timestamp-reply' => 1,
729 'address-mask-request' => 1,
730 'address-mask-reply' => 1,
733 # ip6tables -p icmpv6 -h
735 my $icmpv6_type_names = {
737 'destination-unreachable' => 1,
739 'communication-prohibited' => 1,
740 'address-unreachable' => 1,
741 'port-unreachable' => 1,
742 'packet-too-big' => 1,
743 'time-exceeded' => 1,
744 'ttl-zero-during-transit' => 1,
745 'ttl-zero-during-reassembly' => 1,
746 'parameter-problem' => 1,
748 'unknown-header-type' => 1,
749 'unknown-option' => 1,
752 'router-solicitation' => 1,
753 'router-advertisement' => 1,
754 'neighbor-solicitation' => 1,
755 'neighbour-solicitation' => 1,
756 'neighbor-advertisement' => 1,
757 'neighbour-advertisement' => 1,
761 sub init_firewall_macros
{
763 $pve_fw_parsed_macros = {};
766 my ($k, $macro) = @_;
767 my $lc_name = lc($k);
768 $pve_fw_macro_ipversion->{$k} = 0;
769 while (!ref($macro->[0])) {
770 my $desc = shift @$macro;
771 if ($desc eq 'ipv4only') {
772 $pve_fw_macro_ipversion->{$k} = 4;
773 } elsif ($desc eq 'ipv6only') {
774 $pve_fw_macro_ipversion->{$k} = 6;
776 $pve_fw_macro_descr->{$k} = $desc;
779 $pve_fw_preferred_macro_names->{$lc_name} = $k;
780 $pve_fw_parsed_macros->{$k} = $macro;
783 foreach my $k (keys %$pve_fw_macros) {
784 &$parse($k, $pve_fw_macros->{$k});
787 foreach my $k (keys %$pve_ipv6fw_macros) {
788 next if $pve_fw_parsed_macros->{$k};
789 &$parse($k, $pve_ipv6fw_macros->{$k});
790 $pve_fw_macro_ipversion->{$k} = 6;
794 init_firewall_macros
();
797 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
802 sub get_etc_services
{
804 return $etc_services if $etc_services;
806 my $filename = "/etc/services";
808 my $fh = IO
::File-
>new($filename, O_RDONLY
);
810 warn "unable to read '$filename' - $!\n";
816 while (my $line = <$fh>) {
818 next if $line =~m/^#/;
819 next if ($line =~m/^\s*$/);
821 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
822 $services->{byid
}->{$2}->{name
} = $1;
823 $services->{byid
}->{$2}->{port
} = $2;
824 $services->{byid
}->{$2}->{$3} = 1;
825 $services->{byname
}->{$1} = $services->{byid
}->{$2};
831 $etc_services = $services;
834 return $etc_services;
839 sub get_etc_protocols
{
840 return $etc_protocols if $etc_protocols;
842 my $filename = "/etc/protocols";
844 my $fh = IO
::File-
>new($filename, O_RDONLY
);
846 warn "unable to read '$filename' - $!\n";
852 while (my $line = <$fh>) {
854 next if $line =~m/^#/;
855 next if ($line =~m/^\s*$/);
857 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
858 $protocols->{byid
}->{$2}->{name
} = $1;
859 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
865 # add special case for ICMP v6
866 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
867 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
869 $etc_protocols = $protocols;
871 return $etc_protocols;
874 my $ipv4_mask_hash_localnet = {
876 '255.255.128.0' => 17,
877 '255.255.192.0' => 18,
878 '255.255.224.0' => 19,
879 '255.255.240.0' => 20,
880 '255.255.248.0' => 21,
881 '255.255.252.0' => 22,
882 '255.255.254.0' => 23,
883 '255.255.255.0' => 24,
884 '255.255.255.128' => 25,
885 '255.255.255.192' => 26,
886 '255.255.255.224' => 27,
887 '255.255.255.240' => 28,
888 '255.255.255.248' => 29,
889 '255.255.255.252' => 30,
895 my ($new_value) = @_;
897 $__local_network = $new_value if defined($new_value);
899 return $__local_network if defined($__local_network);
902 my $nodename = PVE
::INotify
::nodename
();
904 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
906 my $testip = Net
::IP-
>new($ip);
908 my $isv6 = $testip->version == 6;
909 my $routes = $isv6 ? PVE
::ProcFSTools
::read_proc_net_ipv6_route
()
910 : PVE
::ProcFSTools
::read_proc_net_route
();
911 foreach my $entry (@$routes) {
914 $mask = $entry->{prefix
};
916 $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
917 next if !defined($mask);
919 my $cidr = "$entry->{dest}/$mask";
920 my $testnet = Net
::IP-
>new($cidr);
921 if ($testnet->overlaps($testip) == $Net::IP
::IP_B_IN_A_OVERLAP
) {
922 $__local_network = $cidr;
929 return $__local_network;
932 # ipset names are limited to 31 characters,
933 # and we use '-v4' or '-v6' to indicate IP versions,
934 # and we use '_swap' suffix for atomic update,
935 # for example PVEFW-${VMID}-${ipset_name}_swap
937 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
939 sub compute_ipset_chain_name
{
940 my ($vmid, $ipset_name, $ipversion) = @_;
942 $vmid = 0 if !defined($vmid);
944 my $id = "$vmid-${ipset_name}-v$ipversion";
946 if (length($id) > $max_iptables_ipset_name_length) {
947 $id = PVE
::Tools
::fnv31a_hex
($id);
953 sub compute_ipfilter_ipset_name
{
956 return "ipfilter-$iface";
959 sub parse_address_list
{
962 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
963 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
967 if ($str =~ m/^${ip_alias_pattern}$/) {
968 die "alias name too long\n" if length($str) > $max_alias_name_length;
976 foreach my $elem (split(/,/, $str)) {
978 my $ip = Net
::IP-
>new($elem);
980 my $err = Net
::IP
::Error
();
981 die "invalid IP address: $err\n";
983 $iprange = 1 if $elem =~ m/-/;
985 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
987 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
988 if $ipversion && ($new_ipversion != $ipversion);
990 $ipversion = $new_ipversion;
993 die "you can't use a range in a list\n" if $iprange && $count > 1;
998 sub parse_port_name_number_or_range
{
999 my ($str, $dport) = @_;
1001 my $services = PVE
::Firewall
::get_etc_services
();
1005 foreach my $item (split(/,/, $str)) {
1007 if ($item =~ m/^(\d+):(\d+)$/) {
1008 my ($port1, $port2) = ($1, $2);
1009 die "invalid port '$port1'\n" if $port1 > 65535;
1010 die "invalid port '$port2'\n" if $port2 > 65535;
1011 } elsif ($item =~ m/^(\d+)$/) {
1013 die "invalid port '$port'\n" if $port > 65535;
1015 if ($dport && $icmp_type_names->{$item}) {
1017 } elsif ($dport && $icmpv6_type_names->{$item}) {
1020 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1025 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1030 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1031 sub pve_fw_verify_sport_spec
{
1034 parse_port_name_number_or_range
($portstr, 0);
1039 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1040 sub pve_fw_verify_dport_spec
{
1043 parse_port_name_number_or_range
($portstr, 1);
1048 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1049 sub pve_fw_verify_addr_spec
{
1052 parse_address_list
($list);
1057 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1058 sub pve_fw_verify_protocol_spec
{
1061 my $protocols = get_etc_protocols
();
1063 die "unknown protocol '$proto'\n" if $proto &&
1064 !(defined($protocols->{byname
}->{$proto}) ||
1065 defined($protocols->{byid
}->{$proto}));
1071 # helper function for API
1073 sub copy_opject_with_digest
{
1076 my $sha = Digest
::SHA-
>new('sha1');
1079 foreach my $k (sort keys %$object) {
1080 my $v = $object->{$k};
1081 next if !defined($v);
1083 $sha->add($k, ':', $v, "\n");
1086 my $digest = $sha->hexdigest;
1088 $res->{digest
} = $digest;
1090 return wantarray ?
($res, $digest) : $res;
1093 sub copy_list_with_digest
{
1096 my $sha = Digest
::SHA-
>new('sha1');
1099 foreach my $entry (@$list) {
1101 foreach my $k (sort keys %$entry) {
1102 my $v = $entry->{$k};
1103 next if !defined($v);
1105 # Note: digest ignores refs ($rule->{errors})
1106 # since Digest::SHA expects a series of bytes,
1107 # we have to encode the value here to prevent errors when
1108 # using utf8 characters (eg. in comments)
1109 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1114 my $digest = $sha->hexdigest;
1116 foreach my $entry (@$res) {
1117 $entry->{digest
} = $digest;
1120 return wantarray ?
($res, $digest) : $res;
1124 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.";
1126 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.";
1128 my $rule_properties = {
1130 description
=> "Update rule at position <pos>.",
1135 digest
=> get_standard_option
('pve-config-digest'),
1139 enum
=> ['in', 'out', 'group'],
1142 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1145 pattern
=> $security_group_name_pattern,
1154 iface
=> get_standard_option
('pve-iface', {
1155 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.",
1159 description
=> "Restrict packet source address. $addr_list_descr",
1160 type
=> 'string', format
=> 'pve-fw-addr-spec',
1164 description
=> "Restrict packet destination address. $addr_list_descr",
1165 type
=> 'string', format
=> 'pve-fw-addr-spec',
1169 description
=> "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
1170 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1179 description
=> "Restrict TCP/UDP source port. $port_descr",
1180 type
=> 'string', format
=> 'pve-fw-sport-spec',
1184 description
=> "Restrict TCP/UDP destination port. $port_descr",
1185 type
=> 'string', format
=> 'pve-fw-dport-spec',
1194 sub add_rule_properties
{
1195 my ($properties) = @_;
1197 foreach my $k (keys %$rule_properties) {
1198 my $h = $rule_properties->{$k};
1199 # copy data, so that we can modify later without side effects
1200 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1206 sub delete_rule_properties
{
1207 my ($rule, $delete_str) = @_;
1209 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1210 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1211 if !defined($rule_properties->{$opt});
1212 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1213 if $opt eq 'type' || $opt eq 'action';
1214 delete $rule->{$opt};
1220 my $apply_macro = sub {
1221 my ($macro_name, $param, $verify, $ipversion) = @_;
1223 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1224 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1226 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1227 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1230 # skip macros which are specific to another ipversion
1231 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1232 return if $ipversion != $required;
1237 foreach my $templ (@$macro_rules) {
1239 my $param_used = {};
1240 foreach my $k (keys %$templ) {
1241 my $v = $templ->{$k};
1242 if ($v eq 'PARAM') {
1244 $param_used->{$k} = 1;
1245 } elsif ($v eq 'DEST') {
1246 $v = $param->{dest
};
1247 $param_used->{dest
} = 1;
1248 } elsif ($v eq 'SOURCE') {
1249 $v = $param->{source
};
1250 $param_used->{source
} = 1;
1254 my $msg = "missing parameter '$k' in macro '$macro_name'";
1255 raise_param_exc
({ macro => $msg }) if $verify;
1260 foreach my $k (keys %$param) {
1261 next if $k eq 'macro';
1262 next if !defined($param->{$k});
1263 next if $param_used->{$k};
1264 if (defined($rule->{$k})) {
1265 if ($rule->{$k} ne $param->{$k}) {
1266 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1267 raise_param_exc
({ $k => $msg }) if $verify;
1271 $rule->{$k} = $param->{$k};
1274 push @$rules, $rule;
1280 my $rule_env_iface_lookup = {
1289 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1291 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1293 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1294 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1296 my $errors = $rule->{errors
} || {};
1298 my $error_count = 0;
1300 my $add_error = sub {
1301 my ($param, $msg) = @_;
1303 raise_param_exc
({ $param => $msg }) if !$noerr;
1305 $errors->{$param} = $msg if !$errors->{$param};
1309 my $set_ip_version = sub {
1312 die "detected mixed ipv4/ipv6 adresses in rule\n"
1313 if $ipversion && ($vers != $ipversion);
1318 my $check_ipset_or_alias_property = sub {
1319 my ($name, $expected_ipversion) = @_;
1321 if (my $value = $rule->{$name}) {
1322 if ($value =~ m/^\+/) {
1323 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1324 &$add_error($name, "no such ipset '$1'")
1325 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1328 &$add_error($name, "invalid ipset name '$value'");
1330 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1331 my $alias = lc($value);
1332 &$add_error($name, "no such alias '$value'")
1333 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1334 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1335 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1337 &$set_ip_version($e->{ipversion
});
1342 my $type = $rule->{type
};
1343 my $action = $rule->{action
};
1345 &$add_error('type', "missing property") if !$type;
1346 &$add_error('action', "missing property") if !$action;
1349 if ($type eq 'in' || $type eq 'out') {
1350 &$add_error('action', "unknown action '$action'")
1351 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1352 } elsif ($type eq 'group') {
1353 &$add_error('type', "security groups not allowed")
1355 &$add_error('action', "invalid characters in security group name")
1356 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1358 &$add_error('type', "unknown rule type '$type'");
1362 if ($rule->{iface
}) {
1363 &$add_error('type', "parameter -i not allowed for this rule type")
1365 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1366 &$add_error('iface', $@) if $@;
1367 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1368 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1369 if $rule->{iface
} !~ m/^net(\d+)$/;
1373 if ($rule->{macro}) {
1374 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1375 $rule->{macro} = $preferred_name;
1377 &$add_error('macro', "unknown macro '$rule->{macro}'");
1381 if ($rule->{proto
}) {
1382 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1383 &$add_error('proto', $@) if $@;
1384 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1385 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1388 if ($rule->{dport
}) {
1389 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1390 &$add_error('dport', $@) if $@;
1391 &$add_error('proto', "missing property - 'dport' requires this property")
1395 if ($rule->{sport
}) {
1396 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1397 &$add_error('sport', $@) if $@;
1398 &$add_error('proto', "missing property - 'sport' requires this property")
1402 if ($rule->{source
}) {
1404 my $source_ipversion = parse_address_list
($rule->{source
});
1405 &$set_ip_version($source_ipversion);
1407 &$add_error('source', $@) if $@;
1408 &$check_ipset_or_alias_property('source', $ipversion);
1411 if ($rule->{dest
}) {
1413 my $dest_ipversion = parse_address_list
($rule->{dest
});
1414 &$set_ip_version($dest_ipversion);
1416 &$add_error('dest', $@) if $@;
1417 &$check_ipset_or_alias_property('dest', $ipversion);
1420 $rule->{ipversion
} = $ipversion if $ipversion;
1422 if ($rule->{macro} && !$error_count) {
1423 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1425 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1426 my $eh = $err->{errors
};
1427 foreach my $p (keys %$eh) {
1428 &$add_error($p, $eh->{$p});
1431 &$add_error('macro', "$err");
1436 $rule->{errors
} = $errors if $error_count;
1441 sub copy_rule_data
{
1442 my ($rule, $param) = @_;
1444 foreach my $k (keys %$rule_properties) {
1445 if (defined(my $v = $param->{$k})) {
1446 if ($v eq '' || $v eq '-') {
1457 sub rules_modify_permissions
{
1458 my ($rule_env) = @_;
1460 if ($rule_env eq 'host') {
1462 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1464 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1466 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1468 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1470 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1477 sub rules_audit_permissions
{
1478 my ($rule_env) = @_;
1480 if ($rule_env eq 'host') {
1482 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1484 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1486 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1488 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1490 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1498 my $bridge_firewall_enabled = 0;
1500 sub enable_bridge_firewall
{
1502 return if $bridge_firewall_enabled; # only once
1504 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1505 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1507 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1508 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1510 $bridge_firewall_enabled = 1;
1513 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1515 sub iptables_restore_cmdlist
{
1518 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1521 sub ip6tables_restore_cmdlist
{
1524 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1527 sub ipset_restore_cmdlist
{
1530 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1533 sub iptables_get_chains
{
1534 my ($iptablescmd) = @_;
1536 $iptablescmd = "iptables" if !$iptablescmd;
1540 # check what chains we want to track
1541 my $is_pvefw_chain = sub {
1544 return 1 if $name =~ m/^PVEFW-\S+$/;
1546 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1548 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1550 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1551 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1563 return if $line =~ m/^#/;
1564 return if $line =~ m/^\s*$/;
1566 if ($line =~ m/^\*(\S+)$/) {
1571 return if $table ne 'filter';
1573 if ($line =~ m/^:(\S+)\s/) {
1575 return if !&$is_pvefw_chain($chain);
1576 $res->{$chain} = "unknown";
1577 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1578 my ($chain, $sig) = ($1, $2);
1579 return if !&$is_pvefw_chain($chain);
1580 $res->{$chain} = $sig;
1581 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1584 # simply ignore the rest
1589 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1591 return wantarray ?
($res, $hooks) : $res;
1594 sub iptables_chain_digest
{
1596 my $digest = Digest
::SHA-
>new('sha1');
1597 foreach my $rule (@$rules) { # order is important
1598 $digest->add($rule);
1600 return $digest->b64digest;
1603 sub ipset_chain_digest
{
1606 my $digest = Digest
::SHA-
>new('sha1');
1607 foreach my $rule (sort @$rules) { # note: sorted
1608 $digest->add($rule);
1610 return $digest->b64digest;
1613 sub ipset_get_chains
{
1621 return if $line =~ m/^#/;
1622 return if $line =~ m/^\s*$/;
1623 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1625 $line =~ s/\s+$//; # delete trailing white space
1626 push @{$chains->{$chain}}, $line;
1628 # simply ignore the rest
1633 run_command
("/sbin/ipset save", outfunc
=> $parser);
1635 # compute digest for each chain
1636 foreach my $chain (keys %$chains) {
1637 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1643 sub ruleset_generate_cmdstr
{
1644 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1646 return if defined($rule->{enable
}) && !$rule->{enable
};
1647 return if $rule->{errors
};
1649 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1651 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1652 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1656 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1657 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1659 my $source = $rule->{source
};
1660 my $dest = $rule->{dest
};
1663 if ($source =~ m/^\+/) {
1664 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1666 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1667 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1668 push @cmd, "-m set --match-set ${ipset_chain} src";
1669 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1670 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1671 push @cmd, "-m set --match-set ${ipset_chain} src";
1673 die "no such ipset '$name'\n";
1676 die "invalid security group name '$source'\n";
1678 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1679 my $alias = lc($source);
1680 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1681 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1682 die "no such alias '$source'\n" if !$e;
1683 push @cmd, "-s $e->{cidr}";
1684 } elsif ($source =~ m/\-/){
1685 push @cmd, "-m iprange --src-range $source";
1687 push @cmd, "-s $source";
1692 if ($dest =~ m/^\+/) {
1693 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1695 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1696 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1697 push @cmd, "-m set --match-set ${ipset_chain} dst";
1698 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1699 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1700 push @cmd, "-m set --match-set ${ipset_chain} dst";
1702 die "no such ipset '$name'\n";
1705 die "invalid security group name '$dest'\n";
1707 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1708 my $alias = lc($dest);
1709 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1710 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1711 die "no such alias '$dest'\n" if !$e;
1712 push @cmd, "-d $e->{cidr}";
1713 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1714 push @cmd, "-m iprange --dst-range $dest";
1716 push @cmd, "-d $dest";
1720 if ($rule->{proto
}) {
1721 push @cmd, "-p $rule->{proto}";
1724 $multiport++ if $nbdport > 1;
1725 $multiport++ if $nbsport > 1;
1727 push @cmd, "--match multiport" if $multiport;
1729 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1730 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1732 if ($rule->{dport
}) {
1733 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1734 # Note: we use dport to store --icmp-type
1735 die "unknown icmp-type '$rule->{dport}'\n"
1736 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1737 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1738 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1739 # Note: we use dport to store --icmpv6-type
1740 die "unknown icmpv6-type '$rule->{dport}'\n"
1741 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1742 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1745 if ($multiport == 2) {
1746 push @cmd, "--ports $rule->{dport}";
1748 push @cmd, "--dports $rule->{dport}";
1751 push @cmd, "--dport $rule->{dport}";
1756 if ($rule->{sport
}) {
1758 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1760 push @cmd, "--sport $rule->{sport}";
1763 } elsif ($rule->{dport
} || $rule->{sport
}) {
1764 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1765 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1768 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1770 if (my $action = $rule->{action
}) {
1771 $action = $actions->{$action} if defined($actions->{$action});
1772 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1773 push @cmd, $goto ?
"-g $action" : "-j $action";
1776 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1779 sub ruleset_generate_rule
{
1780 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1784 if ($rule->{macro}) {
1785 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1790 # update all or nothing
1793 foreach my $tmp (@$rules) {
1794 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1795 push @cmds, $cmdstr;
1799 foreach my $cmdstr (@cmds) {
1800 ruleset_addrule
($ruleset, $chain, $cmdstr);
1804 sub ruleset_generate_rule_insert
{
1805 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1807 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1809 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1810 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1814 sub ruleset_create_chain
{
1815 my ($ruleset, $chain) = @_;
1817 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1818 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1820 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1822 $ruleset->{$chain} = [];
1825 sub ruleset_chain_exist
{
1826 my ($ruleset, $chain) = @_;
1828 return $ruleset->{$chain} ?
1 : undef;
1831 sub ruleset_addrule
{
1832 my ($ruleset, $chain, $rule) = @_;
1834 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1836 push @{$ruleset->{$chain}}, "-A $chain $rule";
1839 sub ruleset_insertrule
{
1840 my ($ruleset, $chain, $rule) = @_;
1842 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1844 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1847 sub get_log_rule_base
{
1848 my ($chain, $vmid, $msg, $loglevel) = @_;
1850 die "internal error - no log level" if !defined($loglevel);
1852 $vmid = 0 if !defined($vmid);
1854 # Note: we use special format for prefix to pass further
1855 # info to log daemon (VMID, LOGVELEL and CHAIN)
1857 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1860 sub ruleset_addlog {
1861 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1863 return if !defined($loglevel);
1865 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1867 $logrule = "$rule $logrule" if defined($rule);
1869 ruleset_addrule($ruleset, $chain, $logrule);
1872 sub ruleset_add_chain_policy {
1873 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1875 if ($policy eq 'ACCEPT') {
1877 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
1878 { ACCEPT => $accept_action});
1880 } elsif ($policy eq 'DROP') {
1882 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1884 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1886 ruleset_addrule($ruleset, $chain, "-j DROP
");
1887 } elsif ($policy eq 'REJECT') {
1888 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1890 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1892 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1895 die "internal error
: unknown policy
'$policy'";
1899 sub ruleset_chain_add_ndp {
1900 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
1901 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
1903 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
$accept");
1904 if ($direction ne 'OUT' || $options->{radv}) {
1905 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
$accept");
1907 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
$accept");
1908 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
$accept");
1911 sub ruleset_chain_add_conn_filters {
1912 my ($ruleset, $chain, $accept) = @_;
1914 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1915 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1918 sub ruleset_chain_add_input_filters {
1919 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
1921 if ($cluster_conf->{ipset}->{blacklist}){
1922 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1923 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1924 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1925 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1927 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
1928 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1931 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1932 if ($ipversion == 4) {
1933 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1937 if ($options->{tcpflags}) {
1938 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1942 sub ruleset_create_vm_chain {
1943 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1945 ruleset_create_chain($ruleset, $chain);
1946 my $accept = generate_nfqueue($options);
1948 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1949 if ($ipversion == 4) {
1950 if ($direction eq 'OUT') {
1951 ruleset_generate_rule($ruleset, $chain, $ipversion,
1952 { action => 'PVEFW-SET-ACCEPT-MARK',
1953 proto => 'udp', sport => 68, dport => 67 });
1955 ruleset_generate_rule($ruleset, $chain, $ipversion,
1956 { action => 'ACCEPT',
1957 proto => 'udp', sport => 67, dport => 68 });
1959 } elsif ($ipversion == 6) {
1960 if ($direction eq 'OUT') {
1961 ruleset_generate_rule($ruleset, $chain, $ipversion,
1962 { action => 'PVEFW-SET-ACCEPT-MARK',
1963 proto => 'udp', sport => 546, dport => 547 });
1965 ruleset_generate_rule($ruleset, $chain, $ipversion,
1966 { action => 'ACCEPT',
1967 proto => 'udp', sport => 547, dport => 546 });
1973 if ($direction eq 'OUT') {
1974 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1975 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1977 if ($ipversion == 6 && !$options->{radv}) {
1978 ruleset_addrule($ruleset, $chain, '-p icmpv6 --icmpv6-type router-advertisement -j DROP');
1980 if ($ipfilter_ipset) {
1981 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
1983 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1986 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
1987 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
1990 sub ruleset_add_group_rule {
1991 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1993 my $group = $rule->{action};
1994 my $group_chain = "GROUP-
$group-$direction";
1995 if(!ruleset_chain_exist($ruleset, $group_chain)){
1996 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1999 if ($direction eq 'OUT' && $rule->{iface_out}) {
2000 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
2001 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2002 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
2004 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
2007 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
2010 sub ruleset_generate_vm_rules {
2011 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2013 my $lc_direction = lc($direction);
2015 my $in_accept = generate_nfqueue($options);
2017 foreach my $rule (@$rules) {
2018 next if $rule->{iface} && $rule->{iface} ne $netid;
2019 next if !$rule->{enable} || $rule->{errors};
2020 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2022 if ($rule->{type} eq 'group') {
2023 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2024 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2026 next if $rule->{type} ne $lc_direction;
2028 if ($direction eq 'OUT') {
2029 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2030 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2031 undef, $cluster_conf, $vmfw_conf);
2033 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2034 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2035 undef, $cluster_conf, $vmfw_conf);
2043 sub generate_nfqueue {
2046 if ($options->{ips}) {
2047 my $action = "NFQUEUE
";
2048 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2049 if (defined($3) && defined($1)) {
2050 $action .= " --queue-balance
$1:$3";
2051 } elsif (defined($1)) {
2052 $action .= " --queue-num
$1";
2055 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2062 sub ruleset_generate_vm_ipsrules {
2063 my ($ruleset, $options, $direction, $iface) = @_;
2065 if ($options->{ips} && $direction eq 'IN') {
2066 my $nfqueue = generate_nfqueue($options);
2068 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2069 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2072 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
2076 sub generate_tap_rules_direction {
2077 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2079 my $lc_direction = lc($direction);
2081 my $rules = $vmfw_conf->{rules};
2083 my $options = $vmfw_conf->{options};
2084 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2086 my $tapchain = "$iface-$direction";
2088 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2089 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2090 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2092 # create chain with mac and ip filter
2093 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2095 if ($options->{enable}) {
2096 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2098 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2103 if ($direction eq 'OUT') {
2104 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2106 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2109 my $accept = generate_nfqueue($options);
2110 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2111 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2113 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2114 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2117 # plug the tap chain to bridge chain
2118 if ($direction eq 'IN') {
2119 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2120 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2122 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2123 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2127 sub enable_host_firewall {
2128 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2130 my $options = $hostfw_conf->{options};
2131 my $cluster_options = $cluster_conf->{options};
2132 my $rules = $hostfw_conf->{rules};
2133 my $cluster_rules = $cluster_conf->{rules};
2135 # host inbound firewall
2136 my $chain = "PVEFW-HOST-IN
";
2137 ruleset_create_chain($ruleset, $chain);
2139 my $loglevel = get_option_log_level($options, "log_level_in
");
2141 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2143 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2144 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2145 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2147 # we use RETURN because we need to check also tap rules
2148 my $accept_action = 'RETURN';
2150 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2152 # add host rules first, so that cluster wide rules can be overwritten
2153 foreach my $rule (@$rules, @$cluster_rules) {
2154 next if !$rule->{enable} || $rule->{errors};
2155 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2157 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2160 if ($rule->{type} eq 'group') {
2161 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2162 } elsif ($rule->{type} eq 'in') {
2163 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2164 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2165 undef, $cluster_conf, $hostfw_conf);
2169 delete $rule->{iface_in};
2172 # allow standard traffic for management ipset (includes cluster network)
2173 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2174 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2175 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2176 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2177 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2178 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2180 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2181 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2184 if ($localnet && ($ipversion == $localnet_ver)) {
2185 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2186 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2187 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2190 # implement input policy
2191 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2192 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2194 # host outbound firewall
2195 $chain = "PVEFW-HOST-OUT
";
2196 ruleset_create_chain($ruleset, $chain);
2198 $loglevel = get_option_log_level($options, "log_level_out
");
2200 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2202 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2204 # we use RETURN because we may want to check other thigs later
2205 $accept_action = 'RETURN';
2206 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2208 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2210 # add host rules first, so that cluster wide rules can be overwritten
2211 foreach my $rule (@$rules, @$cluster_rules) {
2212 next if !$rule->{enable} || $rule->{errors};
2213 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2215 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2217 if ($rule->{type} eq 'group') {
2218 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2219 } elsif ($rule->{type} eq 'out') {
2220 ruleset_generate_rule($ruleset, $chain, $ipversion,
2221 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2222 undef, $cluster_conf, $hostfw_conf);
2226 delete $rule->{iface_out};
2229 # allow standard traffic on cluster network
2230 if ($localnet && ($ipversion == $localnet_ver)) {
2231 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2232 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2233 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2234 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2236 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2237 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2238 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2241 # implement output policy
2242 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2243 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2245 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2246 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2249 sub generate_group_rules {
2250 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2252 my $rules = $cluster_conf->{groups}->{$group};
2255 warn "no such security group
'$group'\n";
2256 $rules = []; # create empty chain
2259 my $chain = "GROUP-
${group
}-IN
";
2261 ruleset_create_chain($ruleset, $chain);
2262 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2264 foreach my $rule (@$rules) {
2265 next if $rule->{type} ne 'in';
2266 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2267 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2268 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2269 undef, $cluster_conf);
2272 $chain = "GROUP-
${group
}-OUT
";
2274 ruleset_create_chain($ruleset, $chain);
2275 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2277 foreach my $rule (@$rules) {
2278 next if $rule->{type} ne 'out';
2279 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2280 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2281 # check also other tap rules later
2282 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2283 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2284 undef, $cluster_conf);
2289 my $valid_netdev_names = {};
2290 for (my $i = 0; $i < $MAX_NETS; $i++) {
2291 $valid_netdev_names->{"net
$i"} = 1;
2295 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2297 my $orig_line = $line;
2301 # we can add single line comments to the end of the rule
2302 if ($line =~ s/#\s*(.*?)\s*$//) {
2303 $rule->{comment} = decode('utf8', $1);
2306 # we can disable a rule when prefixed with '|'
2308 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2310 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2311 die "unable to parse rule
: $line\n";
2313 $rule->{type} = lc($1);
2314 $rule->{action} = $2;
2316 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2317 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2318 $rule->{macro} = $1;
2319 $rule->{action} = $2;
2323 while (length($line)) {
2324 if ($line =~ s/^-i (\S+)\s*//) {
2325 $rule->{iface} = $1;
2329 last if $rule->{type} eq 'group';
2331 if ($line =~ s/^-p (\S+)\s*//) {
2332 $rule->{proto} = $1;
2336 if ($line =~ s/^-dport (\S+)\s*//) {
2337 $rule->{dport} = $1;
2341 if ($line =~ s/^-sport (\S+)\s*//) {
2342 $rule->{sport} = $1;
2345 if ($line =~ s/^-source (\S+)\s*//) {
2346 $rule->{source} = $1;
2349 if ($line =~ s/^-dest (\S+)\s*//) {
2357 die "unable to parse rule parameters
: $line\n" if length($line);
2359 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2360 if ($verbose && $rule->{errors}) {
2361 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2362 foreach my $p (keys %{$rule->{errors}}) {
2363 warn " $p: $rule->{errors
}->{$p}\n";
2370 sub parse_vmfw_option {
2375 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2377 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2380 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2382 $value = $2 ? lc($3) : '';
2383 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2386 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2390 die "can
't parse option '$line'\n"
2393 return ($opt, $value);
2396 sub parse_hostfw_option {
2401 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2403 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2406 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2408 $value = $2 ? lc($3) : '';
2409 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2413 die "can't parse option
'$line'\n"
2416 return ($opt, $value);
2419 sub parse_clusterfw_option {
2424 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2427 if (($value > 1) && ((time() - $value) > 60)) {
2430 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2434 die "can
't parse option '$line'\n"
2437 return ($opt, $value);
2441 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2443 my $alias = lc($cidr);
2444 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2445 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2447 die "no such alias '$cidr'\n" if !$e;;
2449 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2452 sub parse_ip_or_cidr {
2457 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2460 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2464 die "value does not look like a valid IP address or CIDR network\n";
2467 return wantarray ? ($cidr, $ipversion) : $cidr;
2473 # we can add single line comments to the end of the line
2474 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2476 if ($line =~ m/^(\S+)\s(\S+)$/) {
2477 my ($name, $cidr) = ($1, $2);
2480 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2485 ipversion => $ipversion,
2487 $data->{comment} = $comment if $comment;
2494 sub generic_fw_config_parser {
2495 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2500 my $res = $empty_conf;
2502 while (defined(my $line = <$fh>)) {
2503 next if $line =~ m/^#/;
2504 next if $line =~ m/^\s*$/;
2508 my $linenr = $fh->input_line_number();
2509 my $prefix = "$filename (line $linenr)";
2511 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2512 $section = 'options
';
2516 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2517 $section = 'aliases
';
2521 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2522 $section = 'groups
';
2526 die "security group name too long\n" if length($group) > $max_group_name_length;
2527 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2530 ($section, $group, $comment) = undef;
2531 warn "$prefix: $err";
2535 $res->{$section}->{$group} = [];
2536 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2541 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2546 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2551 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2552 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2555 ($section, $group, $comment) = undef;
2556 warn "$prefix: $err";
2560 $res->{$section}->{$group} = [];
2561 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2567 warn "$prefix: skip line - no section\n";
2571 if ($section eq 'options
') {
2574 if ($rule_env eq 'cluster
') {
2575 ($opt, $value) = parse_clusterfw_option($line);
2576 } elsif ($rule_env eq 'host
') {
2577 ($opt, $value) = parse_hostfw_option($line);
2579 ($opt, $value) = parse_vmfw_option($line);
2581 $res->{options}->{$opt} = $value;
2583 warn "$prefix: $@" if $@;
2584 } elsif ($section eq 'aliases
') {
2586 my $data = parse_alias($line);
2587 $res->{aliases}->{lc($data->{name})} = $data;
2589 warn "$prefix: $@" if $@;
2590 } elsif ($section eq 'rules
') {
2592 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2594 warn "$prefix: $err";
2597 push @{$res->{$section}}, $rule;
2598 } elsif ($section eq 'groups
') {
2600 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2602 warn "$prefix: $err";
2605 push @{$res->{$section}->{$group}}, $rule;
2606 } elsif ($section eq 'ipset
') {
2607 # we can add single line comments to the end of the rule
2608 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2610 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2615 if ($nomatch && !$feature_ipset_nomatch) {
2616 $errors->{nomatch} = "nomatch not supported by kernel";
2620 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2621 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2623 $cidr = parse_ip_or_cidr($cidr);
2628 $errors->{cidr} = $err;
2631 my $entry = { cidr => $cidr };
2632 $entry->{nomatch} = 1 if $nomatch;
2633 $entry->{comment} = $comment if $comment;
2634 $entry->{errors} = $errors if $errors;
2636 if ($verbose && $errors) {
2637 warn "$prefix - errors in ipset '$group': $line\n";
2638 foreach my $p (keys %{$errors}) {
2639 warn " $p: $errors->{$p}\n";
2643 push @{$res->{$section}->{$group}}, $entry;
2645 warn "$prefix: skip line - unknown section\n";
2653 sub parse_hostfw_config {
2654 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2656 my $empty_conf = { rules => [], options => {}};
2658 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2661 sub parse_vmfw_config {
2662 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2669 ipset_comments => {},
2672 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2675 sub parse_clusterfw_config {
2676 my ($filename, $fh, $verbose) = @_;
2686 group_comments => {},
2688 ipset_comments => {},
2691 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2695 my ($code, @param) = @_;
2699 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2706 sub read_local_vm_config {
2711 my $vmdata = { qemu => $qemu, lxc => $lxc };
2713 my $vmlist = PVE::Cluster::get_vmlist();
2714 return $vmdata if !$vmlist || !$vmlist->{ids};
2715 my $ids = $vmlist->{ids};
2717 foreach my $vmid (keys %$ids) {
2718 next if !$vmid; # skip VE0
2719 my $d = $ids->{$vmid};
2720 next if !$d->{node} || $d->{node} ne $nodename;
2721 next if !$d->{type};
2722 if ($d->{type} eq 'qemu
') {
2723 if ($have_qemu_server) {
2724 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2725 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2726 $qemu->{$vmid} = $conf;
2729 } elsif ($d->{type} eq 'lxc
') {
2731 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2732 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2733 $lxc->{$vmid} = $conf;
2742 sub load_vmfw_conf {
2743 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2747 $dir = $pvefw_conf_dir if !defined($dir);
2749 my $filename = "$dir/$vmid.fw";
2750 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2751 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2752 $vmfw_conf->{vmid} = $vmid;
2758 my $format_rules = sub {
2759 my ($rules, $allow_iface) = @_;
2763 foreach my $rule (@$rules) {
2764 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2765 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2766 $raw .= uc($rule->{type});
2767 if ($rule->{macro}) {
2768 $raw .= " $rule->{macro}($rule->{action})";
2770 $raw .= " " . $rule->{action};
2772 if ($allow_iface && $rule->{iface}) {
2773 $raw .= " -i $rule->{iface}";
2776 if ($rule->{type} ne 'group
') {
2777 $raw .= " -source $rule->{source}" if $rule->{source};
2778 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2779 $raw .= " -p $rule->{proto}" if $rule->{proto};
2780 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2781 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2784 $raw .= " # " . encode('utf8
', $rule->{comment})
2785 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2788 die "unknown rule type '$rule->{type
}'";
2795 my $format_options = sub {
2800 $raw .= "[OPTIONS]\n\n";
2801 foreach my $opt (keys %$options) {
2802 $raw .= "$opt: $options->{$opt}\n";
2809 my $format_aliases = sub {
2814 $raw .= "[ALIASES]\n\n";
2815 foreach my $k (keys %$aliases) {
2816 my $e = $aliases->{$k};
2817 $raw .= "$e->{name} $e->{cidr}";
2818 $raw .= " # " . encode('utf8
', $e->{comment})
2819 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2827 my $format_ipsets = sub {
2832 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2833 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2834 my $utf8comment = encode('utf8
', $comment);
2835 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2837 $raw .= "[IPSET $ipset]\n\n";
2839 my $options = $fw_conf->{ipset}->{$ipset};
2842 foreach my $entry (@$options) {
2843 $nethash->{$entry->{cidr}} = $entry;
2846 foreach my $cidr (sort keys %$nethash) {
2847 my $entry = $nethash->{$cidr};
2848 my $line = $entry->{nomatch} ? '!' : '';
2849 $line .= $entry->{cidr};
2850 $line .= " # " . encode('utf8
', $entry->{comment})
2851 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2861 sub save_vmfw_conf {
2862 my ($vmid, $vmfw_conf) = @_;
2866 my $options = $vmfw_conf->{options};
2867 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2869 my $aliases = $vmfw_conf->{aliases};
2870 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2872 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2874 my $rules = $vmfw_conf->{rules} || [];
2875 if ($rules && scalar(@$rules)) {
2876 $raw .= "[RULES]\n\n";
2877 $raw .= &$format_rules($rules, 1);
2881 my $filename = "$pvefw_conf_dir/$vmid.fw";
2883 mkdir $pvefw_conf_dir;
2884 PVE::Tools::file_set_contents($filename, $raw);
2890 sub remove_vmfw_conf {
2893 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
2895 unlink $vmfw_conffile;
2898 sub clone_vmfw_conf {
2899 my ($vmid, $newid) = @_;
2901 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
2902 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
2904 if (-f $clonevm_conffile) {
2905 unlink $clonevm_conffile;
2907 if (-f $sourcevm_conffile) {
2908 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
2909 PVE::Tools::file_set_contents($clonevm_conffile, $data);
2913 sub read_vm_firewall_configs {
2914 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2916 my $vmfw_configs = {};
2918 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2919 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2920 next if !$vmfw_conf->{options}; # skip if file does not exists
2921 $vmfw_configs->{$vmid} = $vmfw_conf;
2923 foreach my $vmid (keys %{$vmdata->{lxc}}) {
2924 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2925 next if !$vmfw_conf->{options}; # skip if file does not exists
2926 $vmfw_configs->{$vmid} = $vmfw_conf;
2929 return $vmfw_configs;
2932 sub get_option_log_level {
2933 my ($options, $k) = @_;
2935 my $v = $options->{$k};
2936 $v = $default_log_level if !defined($v);
2938 return undef if $v eq '' || $v eq 'nolog
';
2940 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2942 return $v if ($v >= 0) && ($v <= 7);
2944 warn "unknown log level ($k = '$v')\n";
2949 sub generate_std_chains {
2950 my ($ruleset, $options, $ipversion) = @_;
2952 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2954 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2958 if ($ipversion == 4) {
2959 # same as shorewall smurflog.
2960 $chain = 'PVEFW-smurflog
';
2961 $std_chains->{$chain} = [];
2963 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2964 push @{$std_chains->{$chain}}, "-j DROP";
2967 # same as shorewall logflags action.
2968 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2969 $chain = 'PVEFW-logflags
';
2970 $std_chains->{$chain} = [];
2972 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2973 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2974 push @{$std_chains->{$chain}}, "-j DROP";
2976 foreach my $chain (keys %$std_chains) {
2977 ruleset_create_chain($ruleset, $chain);
2978 foreach my $rule (@{$std_chains->{$chain}}) {
2980 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
2982 ruleset_addrule($ruleset, $chain, $rule);
2988 sub generate_ipset_chains {
2989 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
2991 foreach my $ipset (keys %{$ipsets}) {
2993 my $options = $ipsets->{$ipset};
2995 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
2996 if (my $ips = $device_ips->{$1}) {
2997 $options = [@$options, @$ips];
3003 foreach my $entry (@$options) {
3004 next if $entry->{errors}; # skip entries with errors
3007 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3008 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3010 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3012 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3014 # ip_compress_address takes an address only, no CIDR
3015 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3016 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3017 $cidr .= $prefix_len if defined($prefix_len);
3023 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3028 foreach my $ipversion (4, 6) {
3029 my $data = $nethash->{$ipversion};
3031 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3033 my $hashsize = scalar(@$options);
3034 if ($hashsize <= 64) {
3037 $hashsize = round_powerof2($hashsize);
3040 my $family = $ipversion == "6" ? "inet6" : "inet";
3042 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3044 foreach my $cidr (sort keys %$data) {
3045 my $entry = $data->{$cidr};
3047 my $cmd = "add $name $cidr";
3048 if ($entry->{nomatch}) {
3049 if ($feature_ipset_nomatch) {
3050 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3052 warn "ignore !$cidr - nomatch not supported by kernel\n";
3055 push @{$ipset_ruleset->{$name}}, $cmd;
3062 sub round_powerof2 {
3066 $int |= $int >> $_ foreach (1,2,4,8,16);
3070 sub load_clusterfw_conf {
3071 my ($filename, $verbose) = @_;
3073 $filename = $clusterfw_conf_filename if !defined($filename);
3075 my $cluster_conf = {};
3076 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3077 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3080 return $cluster_conf;
3083 sub save_clusterfw_conf {
3084 my ($cluster_conf) = @_;
3088 my $options = $cluster_conf->{options};
3089 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3091 my $aliases = $cluster_conf->{aliases};
3092 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3094 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3096 my $rules = $cluster_conf->{rules};
3097 if ($rules && scalar(@$rules)) {
3098 $raw .= "[RULES]\n\n";
3099 $raw .= &$format_rules($rules, 1);
3103 if ($cluster_conf->{groups}) {
3104 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3105 my $rules = $cluster_conf->{groups}->{$group};
3106 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3107 my $utf8comment = encode('utf8
', $comment);
3108 $raw .= "[group $group] # $utf8comment\n\n";
3110 $raw .= "[group $group]\n\n";
3113 $raw .= &$format_rules($rules, 0);
3119 mkdir $pvefw_conf_dir;
3120 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3122 unlink $clusterfw_conf_filename;
3126 sub load_hostfw_conf {
3127 my ($cluster_conf, $filename, $verbose) = @_;
3129 $filename = $hostfw_conf_filename if !defined($filename);
3131 my $hostfw_conf = {};
3132 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3133 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3135 return $hostfw_conf;
3138 sub save_hostfw_conf {
3139 my ($hostfw_conf) = @_;
3143 my $options = $hostfw_conf->{options};
3144 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3146 my $rules = $hostfw_conf->{rules};
3147 if ($rules && scalar(@$rules)) {
3148 $raw .= "[RULES]\n\n";
3149 $raw .= &$format_rules($rules, 1);
3154 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3156 unlink $hostfw_conf_filename;
3161 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3165 if ($vmdata) { # test mode
3166 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3167 my $filename = "$testdir/cluster.fw";
3168 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3170 $filename = "$testdir/host.fw";
3171 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3173 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3174 } else { # normal operation
3175 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3177 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3179 $vmdata = read_local_vm_config();
3180 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3183 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3186 if ($cluster_conf->{aliases}->{local_network}) {
3187 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3190 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3192 $cluster_conf->{aliases}->{local_network} = {
3193 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3196 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3198 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3199 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3200 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3202 return ($ruleset, $ipset_ruleset, $rulesetv6);
3205 sub compile_iptables_filter {
3206 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3210 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3211 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3213 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3215 my $hostfw_options = $hostfw_conf->{options} || {};
3217 # fixme: what log level should we use here?
3218 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3220 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3222 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3223 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3225 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3227 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3228 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3230 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3232 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3234 if ($hostfw_enable) {
3235 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3236 warn $@ if $@; # just to be sure - should not happen
3239 # generate firewall rules for QEMU VMs
3240 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3242 my $conf = $vmdata->{qemu}->{$vmid};
3243 my $vmfw_conf = $vmfw_configs->{$vmid};
3244 return if !$vmfw_conf;
3246 foreach my $netid (keys %$conf) {
3247 next if $netid !~ m/^net(\d+)$/;
3248 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3249 next if !$net->{firewall};
3250 my $iface = "tap${vmid}i$1";
3252 my $macaddr = $net->{macaddr};
3253 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3254 $vmfw_conf, $vmid, 'IN
', $ipversion);
3255 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3256 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3259 warn $@ if $@; # just to be sure - should not happen
3262 # generate firewall rules for LXC containers
3263 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3265 my $conf = $vmdata->{lxc}->{$vmid};
3266 my $vmfw_conf = $vmfw_configs->{$vmid};
3267 return if !$vmfw_conf;
3269 if ($vmfw_conf->{options}->{enable}) {
3270 foreach my $netid (keys %$conf) {
3271 next if $netid !~ m/^net(\d+)$/;
3272 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3273 next if !$net->{firewall};
3274 my $iface = "veth${vmid}i$1";
3275 my $macaddr = $net->{hwaddr};
3276 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3277 $vmfw_conf, $vmid, 'IN
', $ipversion);
3278 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3279 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3283 warn $@ if $@; # just to be sure - should not happen
3286 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3287 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3293 sub mac_to_linklocal {
3295 my @parts = split(/:/, $macaddr);
3296 # The standard link local address uses the fe80::/64 prefix with the
3297 # modified EUI-64 identifier derived from the MAC address by flipping the
3298 # universal/local bit and inserting FF:FE in the middle.
3300 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3301 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3302 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3305 sub compile_ipsets {
3306 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3309 if ($cluster_conf->{aliases}->{local_network}) {
3310 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3313 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3315 $cluster_conf->{aliases}->{local_network} = {
3316 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3319 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3322 my $ipset_ruleset = {};
3324 # generate ipsets for QEMU VMs
3325 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3327 my $conf = $vmdata->{qemu}->{$vmid};
3328 my $vmfw_conf = $vmfw_configs->{$vmid};
3329 return if !$vmfw_conf;
3331 # When the 'ipfilter
' option is enabled every device for which there
3332 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3334 # The reason is that ipfilter ipsets are always filled with standard
3335 # IPv6 link-local filters.
3336 my $ipsets = $vmfw_conf->{ipset};
3337 my $implicit_sets = {};
3339 my $device_ips = {};
3340 foreach my $netid (keys %$conf) {
3341 next if $netid !~ m/^net(\d+)$/;
3342 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3343 next if !$net->{firewall};
3345 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3346 $implicit_sets->{"ipfilter-$netid"} = [];
3349 my $macaddr = $net->{macaddr};
3350 my $linklocal = mac_to_linklocal($macaddr);
3351 $device_ips->{$netid} = [
3352 { cidr => $linklocal },
3353 { cidr => 'fe80
::/10', nomatch => 1 }
3357 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3358 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3360 warn $@ if $@; # just to be sure - should not happen
3363 # generate firewall rules for LXC containers
3364 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3366 my $conf = $vmdata->{lxc}->{$vmid};
3367 my $vmfw_conf = $vmfw_configs->{$vmid};
3368 return if !$vmfw_conf;
3370 # When the 'ipfilter
' option is enabled every device for which there
3371 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3373 # The reason is that ipfilter ipsets are always filled with standard
3374 # IPv6 link-local filters, as well as the IP addresses configured
3375 # for the container.
3376 my $ipsets = $vmfw_conf->{ipset};
3377 my $implicit_sets = {};
3379 my $device_ips = {};
3380 foreach my $netid (keys %$conf) {
3381 next if $netid !~ m/^net(\d+)$/;
3382 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3383 next if !$net->{firewall};
3385 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3386 $implicit_sets->{"ipfilter-$netid"} = [];
3389 my $macaddr = $net->{hwaddr};
3390 my $linklocal = mac_to_linklocal($macaddr);
3391 my $set = $device_ips->{$netid} = [
3392 { cidr => $linklocal },
3393 { cidr => 'fe80
::/10', nomatch => 1 }
3395 if ($net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3396 push @$set, { cidr => $1 };
3398 if ($net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3399 push @$set, { cidr => $1 };
3403 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3404 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3406 warn $@ if $@; # just to be sure - should not happen
3409 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3411 return $ipset_ruleset;
3414 sub get_ruleset_status {
3415 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3417 my $statushash = {};
3419 foreach my $chain (sort keys %$ruleset) {
3420 my $sig = &$digest_fn($ruleset->{$chain});
3422 $statushash->{$chain}->{sig} = $sig;
3424 my $oldsig = $active_chains->{$chain};
3425 if (!defined($oldsig)) {
3426 $statushash->{$chain}->{action} = 'create
';
3428 if ($oldsig eq $sig) {
3429 $statushash->{$chain}->{action} = 'exists';
3431 $statushash->{$chain}->{action} = 'update
';
3434 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3435 foreach my $cmd (@{$ruleset->{$chain}}) {
3436 print "\t$cmd\n" if $verbose;
3440 foreach my $chain (sort keys %$active_chains) {
3441 if (!defined($ruleset->{$chain})) {
3442 my $sig = $active_chains->{$chain};
3443 $statushash->{$chain}->{action} = 'delete';
3444 $statushash->{$chain}->{sig} = $sig;
3445 print "delete $chain ($sig)\n" if $verbose;
3452 sub print_sig_rule {
3453 my ($chain, $sig) = @_;
3455 # We just use this to store a SHA1 checksum used to detect changes
3456 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3459 sub get_ruleset_cmdlist {
3460 my ($ruleset, $verbose, $iptablescmd) = @_;
3462 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3464 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3465 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3467 # create missing chains first
3468 foreach my $chain (sort keys %$ruleset) {
3469 my $stat = $statushash->{$chain};
3470 die "internal error" if !$stat;
3471 next if $stat->{action} ne 'create
';
3473 $cmdlist .= ":$chain - [0:0]\n";
3476 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3477 my $chain = "PVEFW-$h";
3478 if ($ruleset->{$chain} && !$hooks->{$h}) {
3479 $cmdlist .= "-A $h -j $chain\n";
3483 foreach my $chain (sort keys %$ruleset) {
3484 my $stat = $statushash->{$chain};
3485 die "internal error" if !$stat;
3487 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3488 $cmdlist .= "-F $chain\n";
3489 foreach my $cmd (@{$ruleset->{$chain}}) {
3490 $cmdlist .= "$cmd\n";
3492 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3493 } elsif ($stat->{action
} eq 'delete') {
3494 die "internal error"; # this should not happen
3495 } elsif ($stat->{action
} eq 'exists') {
3498 die "internal error - unknown status '$stat->{action}'";
3502 foreach my $chain (keys %$statushash) {
3503 next if $statushash->{$chain}->{action
} ne 'delete';
3504 $cmdlist .= "-F $chain\n";
3506 foreach my $chain (keys %$statushash) {
3507 next if $statushash->{$chain}->{action
} ne 'delete';
3508 next if $chain eq 'PVEFW-INPUT';
3509 next if $chain eq 'PVEFW-OUTPUT';
3510 next if $chain eq 'PVEFW-FORWARD';
3511 $cmdlist .= "-X $chain\n";
3514 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3516 $cmdlist .= "COMMIT\n";
3518 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3521 sub get_ipset_cmdlist
{
3522 my ($ruleset, $verbose) = @_;
3526 my $delete_cmdlist = "";
3528 my $active_chains = ipset_get_chains
();
3529 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3531 # remove stale _swap chains
3532 foreach my $chain (keys %$active_chains) {
3533 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3534 $cmdlist .= "destroy $chain\n";
3538 foreach my $chain (keys %$ruleset) {
3539 my $stat = $statushash->{$chain};
3540 die "internal error" if !$stat;
3542 if ($stat->{action
} eq 'create') {
3543 foreach my $cmd (@{$ruleset->{$chain}}) {
3544 $cmdlist .= "$cmd\n";
3549 foreach my $chain (keys %$ruleset) {
3550 my $stat = $statushash->{$chain};
3551 die "internal error" if !$stat;
3553 if ($stat->{action
} eq 'update') {
3554 my $chain_swap = $chain."_swap";
3556 foreach my $cmd (@{$ruleset->{$chain}}) {
3557 $cmd =~ s/$chain/$chain_swap/;
3558 $cmdlist .= "$cmd\n";
3560 $cmdlist .= "swap $chain_swap $chain\n";
3561 $cmdlist .= "flush $chain_swap\n";
3562 $cmdlist .= "destroy $chain_swap\n";
3566 # the remove unused chains
3567 foreach my $chain (keys %$statushash) {
3568 next if $statushash->{$chain}->{action
} ne 'delete';
3570 $delete_cmdlist .= "flush $chain\n";
3571 $delete_cmdlist .= "destroy $chain\n";
3574 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3576 return ($cmdlist, $delete_cmdlist, $changes);
3580 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3582 enable_bridge_firewall
();
3584 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3585 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3587 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3588 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3591 if ($ipset_changes) {
3592 print "ipset changes:\n";
3593 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3594 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3598 print "iptables changes:\n";
3603 print "ip6tables changes:\n";
3608 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3609 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3611 ipset_restore_cmdlist
($ipset_create_cmdlist);
3613 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3614 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3616 iptables_restore_cmdlist
($cmdlist);
3618 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3619 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3621 ip6tables_restore_cmdlist
($cmdlistv6);
3623 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3624 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3626 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3628 # test: re-read status and check if everything is up to date
3629 my $active_chains = iptables_get_chains
();
3630 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3633 foreach my $chain (sort keys %$ruleset) {
3634 my $stat = $statushash->{$chain};
3635 if ($stat->{action
} ne 'exists') {
3636 warn "unable to update chain '$chain'\n";
3641 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3642 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3644 foreach my $chain (sort keys %$rulesetv6) {
3645 my $stat = $statushashv6->{$chain};
3646 if ($stat->{action
} ne 'exists') {
3647 warn "unable to update chain '$chain'\n";
3652 die "unable to apply firewall changes\n" if $errors;
3654 update_nf_conntrack_max
($hostfw_conf);
3656 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3660 sub update_nf_conntrack_max
{
3661 my ($hostfw_conf) = @_;
3663 my $max = 65536; # reasonable default
3665 my $options = $hostfw_conf->{options
} || {};
3667 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3668 $max = $options->{nf_conntrack_max
};
3669 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3672 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3673 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3675 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3677 if ($current != $max) {
3678 my $hashsize = int($max/4);
3679 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3680 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3684 sub update_nf_conntrack_tcp_timeout_established
{
3685 my ($hostfw_conf) = @_;
3687 my $options = $hostfw_conf->{options
} || {};
3689 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3691 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3694 sub remove_pvefw_chains
{
3696 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3697 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3698 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3702 sub remove_pvefw_chains_iptables
{
3703 my ($iptablescmd) = @_;
3705 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3706 my $cmdlist = "*filter\n";
3708 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3710 $cmdlist .= "-D $h -j PVEFW-$h\n";
3714 foreach my $chain (keys %$chash) {
3715 $cmdlist .= "-F $chain\n";
3718 foreach my $chain (keys %$chash) {
3719 $cmdlist .= "-X $chain\n";
3721 $cmdlist .= "COMMIT\n";
3723 if($iptablescmd eq "ip6tables") {
3724 ip6tables_restore_cmdlist
($cmdlist);
3726 iptables_restore_cmdlist
($cmdlist);
3730 sub remove_pvefw_chains_ipset
{
3732 my $ipset_chains = ipset_get_chains
();
3736 foreach my $chain (keys %$ipset_chains) {
3737 $cmdlist .= "flush $chain\n";
3738 $cmdlist .= "destroy $chain\n";
3741 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3745 my $cluster_conf = load_clusterfw_conf
();
3746 my $cluster_options = $cluster_conf->{options
};
3747 my $enable = $cluster_options->{enable
};
3751 # load required modules here
3757 my $cluster_conf = load_clusterfw_conf
();
3758 my $cluster_options = $cluster_conf->{options
};
3760 if (!$cluster_options->{enable
}) {
3761 PVE
::Firewall
::remove_pvefw_chains
();
3765 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3767 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3769 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);