8 use Socket
qw(AF_INET6 inet_ntop inet_pton);
10 use PVE
::Exception
qw(raise raise_param_exc);
11 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
14 use PVE
::Tools
qw($IPV4RE $IPV6RE);
21 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
24 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
25 my $pvefw_conf_dir = "/etc/pve/firewall";
26 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
28 # dynamically include PVE::QemuServer and PVE::LXC
29 # to avoid dependency problems
32 require PVE
::QemuServer
;
33 require PVE
::QemuConfig
;
34 $have_qemu_server = 1;
44 my $pve_fw_status_dir = "/var/lib/pve-firewall";
46 mkdir $pve_fw_status_dir; # make sure this exists
48 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
49 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
50 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
52 my $max_alias_name_length = 64;
53 my $max_ipset_name_length = 64;
54 my $max_group_name_length = 18;
56 my $PROTOCOLS_WITH_PORTS = {
58 udplite
=> 1, 136 => 1,
64 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
65 sub pve_verify_ip_or_cidr
{
66 my ($cidr, $noerr) = @_;
68 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
69 return $cidr if Net
::IP-
>new($cidr);
70 return undef if $noerr;
71 die Net
::IP
::Error
() . "\n";
73 return undef if $noerr;
74 die "value does not look like a valid IP address or CIDR network\n";
77 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
78 sub pve_verify_ip_or_cidr_or_alias
{
79 my ($cidr, $noerr) = @_;
81 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
83 return pve_verify_ip_or_cidr
($cidr, $noerr);
86 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
87 description
=> "IP set name.",
89 pattern
=> $ipset_name_pattern,
91 maxLength
=> $max_ipset_name_length,
94 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
95 description
=> "Alias name.",
97 pattern
=> $ip_alias_pattern,
99 maxLength
=> $max_alias_name_length,
102 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
103 description
=> "Log level.",
105 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
109 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
110 description
=> "Security Group name.",
112 pattern
=> $security_group_name_pattern,
114 maxLength
=> $max_group_name_length,
117 my $feature_ipset_nomatch = 0;
119 my (undef, undef, $release) = POSIX
::uname
();
120 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
121 my ($major, $minor) = ($1, $2);
122 $feature_ipset_nomatch = 1 if ($major > 3) ||
123 ($major == 3 && $minor >= 7);
128 my $nodename = PVE
::INotify
::nodename
();
130 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
132 my $default_log_level = 'nolog'; # avoid logs by default
134 my $log_level_hash = {
145 # we need to overwrite some macros for ipv6
146 my $pve_ipv6fw_macros = {
148 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
150 'NeighborDiscovery' => [
151 "IPv6 neighbor solicitation, neighbor and router advertisement",
152 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-solicitation' },
153 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-advertisement' },
154 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-solicitation' },
155 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-advertisement' },
159 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
162 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
163 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
167 # imported/converted from: /usr/share/shorewall/macro.*
168 my $pve_fw_macros = {
171 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
172 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
175 "Auth (identd) traffic",
176 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
179 "Border Gateway Protocol traffic",
180 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
183 "BitTorrent traffic for BitTorrent 3.1 and earlier",
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
185 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
188 "BitTorrent traffic for BitTorrent 3.2 and later",
189 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
190 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
193 "Ceph Storage Cluster traffic (Ceph Monitors, OSD & MDS Deamons)",
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6789' },
195 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6800:7300' },
198 "Concurrent Versions System pserver traffic",
199 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
202 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
203 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
204 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
205 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
208 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
209 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
210 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
213 "Distributed Checksum Clearinghouse spam filtering mechanism",
214 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
217 "Forwarded DHCP traffic",
218 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
221 "Domain Name System traffic (upd and tcp)",
222 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
223 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
226 "Distributed Compiler service",
227 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
230 "File Transfer Protocol",
231 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
234 "Finger protocol (RFC 742)",
235 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
238 "GNUnet secure peer-to-peer networking traffic",
239 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
240 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
241 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
242 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
245 "Generic Routing Encapsulation tunneling protocol",
246 { action
=> 'PARAM', proto
=> '47' },
249 "Git distributed revision control traffic",
250 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
253 "OpenPGP HTTP keyserver protocol traffic",
254 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
257 "Hypertext Transfer Protocol (WWW)",
258 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
261 "Hypertext Transfer Protocol (WWW) over SSL",
262 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
265 "Internet Cache Protocol V2 (Squid) traffic",
266 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
269 "AOL Instant Messenger traffic",
270 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
273 "Internet Message Access Protocol",
274 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
277 "Internet Message Access Protocol over SSL",
278 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
281 "IPIP capsulation traffic",
282 { action
=> 'PARAM', proto
=> '94' },
286 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
287 { action
=> 'PARAM', proto
=> '50' },
290 "IPsec authentication (AH) traffic",
291 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
292 { action
=> 'PARAM', proto
=> '51' },
295 "IPsec traffic and Nat-Traversal",
296 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
297 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
298 { action
=> 'PARAM', proto
=> '50' },
301 "Internet Relay Chat traffic",
302 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
305 "HP Jetdirect printing",
306 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
309 "Layer 2 Tunneling Protocol traffic",
310 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
313 "Lightweight Directory Access Protocol traffic",
314 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
317 "Secure Lightweight Directory Access Protocol traffic",
318 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
321 "Microsoft Notification Protocol",
322 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
325 "Microsoft SQL Server",
326 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
329 "Mail traffic (SMTP, SMTPS, Submission)",
330 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
331 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
332 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
336 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5353' },
339 "Munin networked resource monitoring traffic",
340 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
344 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
347 "NNTP traffic (Usenet).",
348 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
351 "Encrypted NNTP traffic (Usenet)",
352 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
355 "Network Time Protocol (ntpd)",
356 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
359 "OSPF multicast traffic",
360 { action
=> 'PARAM', proto
=> '89' },
364 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
367 "Symantec PCAnywere (tm)",
368 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
369 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
373 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
376 "Encrypted POP3 traffic",
377 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
380 "Point-to-Point Tunneling Protocol",
381 { action
=> 'PARAM', proto
=> '47' },
382 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
386 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
390 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
393 "Line Printer protocol printing",
394 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
397 "Microsoft Remote Desktop Protocol traffic",
398 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
401 "Routing Information Protocol (bidirectional)",
402 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
405 "BIND remote management protocol",
406 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
409 "Razor Antispam System",
410 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
413 "Remote time retrieval (rdate)",
414 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
418 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
421 "SANE network scanning",
422 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
425 "Microsoft SMB traffic",
426 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
427 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
428 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
432 "Samba Web Administration Tool",
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
436 "Simple Mail Transfer Protocol",
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
440 "Encrypted Simple Mail Transfer Protocol",
441 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
444 "Simple Network Management Protocol",
445 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
449 "Spam Assassin SPAMD traffic",
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
453 "Secure shell traffic",
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
457 "Subversion server (svnserve)",
458 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
461 "SixXS IPv6 Deployment and Tunnel Broker",
462 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
463 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
464 { action
=> 'PARAM', proto
=> '41' },
465 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
468 "Squid web proxy traffic",
469 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
472 "Mail message submission traffic",
473 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
476 "Syslog protocol (RFC 5424) traffic",
477 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
478 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
481 "Trivial File Transfer Protocol traffic",
482 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
486 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
490 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
493 "RFC 868 Time protocol",
494 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
497 "Traceroute (for up to 30 hops) traffic",
498 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
499 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
502 "VNC traffic for VNC display's 0 - 99",
503 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
506 "VNC traffic from Vncservers to Vncviewers in listen mode",
507 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
510 "WWW traffic (HTTP and HTTPS)",
511 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
512 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
515 "Web Cache/Proxy traffic (port 8080)",
516 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
520 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
523 "Whois (nicname, RFC 3912) traffic",
524 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
528 my $pve_fw_parsed_macros;
529 my $pve_fw_macro_descr;
530 my $pve_fw_macro_ipversion = {};
531 my $pve_fw_preferred_macro_names = {};
533 my $FWACCEPTMARK_ON = "0x80000000/0x80000000";
534 my $FWACCEPTMARK_OFF = "0x00000000/0x80000000";
536 my $pve_std_chains = {};
537 $pve_std_chains->{4} = {
538 'PVEFW-SET-ACCEPT-MARK' => [
539 "-j MARK --set-mark $FWACCEPTMARK_ON",
541 'PVEFW-DropBroadcast' => [
542 # same as shorewall 'Broadcast'
543 # simply DROP BROADCAST/MULTICAST/ANYCAST
544 # we can use this to reduce logging
545 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
546 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
547 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
548 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
551 # same as shorewall 'reject'
552 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
553 { action
=> 'DROP', source
=> '224.0.0.0/4' },
554 { action
=> 'DROP', proto
=> 'icmp' },
555 "-p tcp -j REJECT --reject-with tcp-reset",
556 "-p udp -j REJECT --reject-with icmp-port-unreachable",
557 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
558 "-j REJECT --reject-with icmp-host-prohibited",
561 # same as shorewall 'Drop', which is equal to DROP,
562 # but REJECT/DROP some packages to reduce logging,
563 # and ACCEPT critical ICMP types
564 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
565 # we are not interested in BROADCAST/MULTICAST/ANYCAST
566 { action
=> 'PVEFW-DropBroadcast' },
567 # ACCEPT critical ICMP types
568 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
569 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
570 # Drop packets with INVALID state
571 "-m conntrack --ctstate INVALID -j DROP",
572 # Drop Microsoft SMB noise
573 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
574 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
575 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
576 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
577 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
578 # Drop new/NotSyn traffic so that it doesn't get logged
579 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
581 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
584 # same as shorewall 'Reject', which is equal to Reject,
585 # but REJECT/DROP some packages to reduce logging,
586 # and ACCEPT critical ICMP types
587 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
588 # we are not interested in BROADCAST/MULTICAST/ANYCAST
589 { action
=> 'PVEFW-DropBroadcast' },
590 # ACCEPT critical ICMP types
591 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
592 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
593 # Drop packets with INVALID state
594 "-m conntrack --ctstate INVALID -j DROP",
595 # Drop Microsoft SMB noise
596 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
597 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
598 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
599 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
600 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
601 # Drop new/NotSyn traffic so that it doesn't get logged
602 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
604 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
606 'PVEFW-tcpflags' => [
607 # same as shorewall tcpflags action.
608 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
609 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
610 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
611 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
612 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
613 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
616 # same as shorewall smurfs action
617 # Filter packets for smurfs (packets with a broadcast address as the source).
618 "-s 0.0.0.0/32 -j RETURN", # allow DHCP
619 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
620 "-s 224.0.0.0/4 -g PVEFW-smurflog",
624 $pve_std_chains->{6} = {
625 'PVEFW-SET-ACCEPT-MARK' => [
626 "-j MARK --set-mark $FWACCEPTMARK_ON",
628 'PVEFW-DropBroadcast' => [
629 # same as shorewall 'Broadcast'
630 # simply DROP BROADCAST/MULTICAST/ANYCAST
631 # we can use this to reduce logging
632 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
633 # ipv6 addrtype does not work with kernel 2.6.32
634 #{ action => 'DROP', dsttype => 'MULTICAST' },
635 #{ action => 'DROP', dsttype => 'ANYCAST' },
636 { action
=> 'DROP', dest
=> 'ff00::/8' },
637 #{ action => 'DROP', dest => '224.0.0.0/4' },
640 # same as shorewall 'reject'
641 #{ action => 'DROP', dsttype => 'BROADCAST' },
642 #{ action => 'DROP', source => '224.0.0.0/4' },
643 { action
=> 'DROP', proto
=> 'icmpv6' },
644 "-p tcp -j REJECT --reject-with tcp-reset",
645 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
646 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
647 #"-j REJECT --reject-with icmp-host-prohibited",
650 # same as shorewall 'Drop', which is equal to DROP,
651 # but REJECT/DROP some packages to reduce logging,
652 # and ACCEPT critical ICMP types
653 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
654 # we are not interested in BROADCAST/MULTICAST/ANYCAST
655 { action
=> 'PVEFW-DropBroadcast' },
656 # ACCEPT critical ICMP types
657 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
658 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
659 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
661 # Drop packets with INVALID state
662 "-m conntrack --ctstate INVALID -j DROP",
663 # Drop Microsoft SMB noise
664 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
665 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
666 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
667 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
668 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
669 # Drop new/NotSyn traffic so that it doesn't get logged
670 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
672 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
675 # same as shorewall 'Reject', which is equal to Reject,
676 # but REJECT/DROP some packages to reduce logging,
677 # and ACCEPT critical ICMP types
678 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
679 # we are not interested in BROADCAST/MULTICAST/ANYCAST
680 { action
=> 'PVEFW-DropBroadcast' },
681 # ACCEPT critical ICMP types
682 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
683 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
684 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
686 # Drop packets with INVALID state
687 "-m conntrack --ctstate INVALID -j DROP",
688 # Drop Microsoft SMB noise
689 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
690 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
691 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
692 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
693 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
694 # Drop new/NotSyn traffic so that it doesn't get logged
695 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
697 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
699 'PVEFW-tcpflags' => [
700 # same as shorewall tcpflags action.
701 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
702 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
703 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
704 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
705 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
706 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
710 # iptables -p icmp -h
711 my $icmp_type_names = {
714 'destination-unreachable' => 1,
715 'network-unreachable' => 1,
716 'host-unreachable' => 1,
717 'protocol-unreachable' => 1,
718 'port-unreachable' => 1,
719 'fragmentation-needed' => 1,
720 'source-route-failed' => 1,
721 'network-unknown' => 1,
723 'network-prohibited' => 1,
724 'host-prohibited' => 1,
725 'TOS-network-unreachable' => 1,
726 'TOS-host-unreachable' => 1,
727 'communication-prohibited' => 1,
728 'host-precedence-violation' => 1,
729 'precedence-cutoff' => 1,
730 'source-quench' => 1,
732 'network-redirect' => 1,
733 'host-redirect' => 1,
734 'TOS-network-redirect' => 1,
735 'TOS-host-redirect' => 1,
737 'router-advertisement' => 1,
738 'router-solicitation' => 1,
739 'time-exceeded' => 1,
740 'ttl-zero-during-transit' => 1,
741 'ttl-zero-during-reassembly' => 1,
742 'parameter-problem' => 1,
743 'ip-header-bad' => 1,
744 'required-option-missing' => 1,
745 'timestamp-request' => 1,
746 'timestamp-reply' => 1,
747 'address-mask-request' => 1,
748 'address-mask-reply' => 1,
751 # ip6tables -p icmpv6 -h
753 my $icmpv6_type_names = {
755 'destination-unreachable' => 1,
757 'communication-prohibited' => 1,
758 'address-unreachable' => 1,
759 'port-unreachable' => 1,
760 'packet-too-big' => 1,
761 'time-exceeded' => 1,
762 'ttl-zero-during-transit' => 1,
763 'ttl-zero-during-reassembly' => 1,
764 'parameter-problem' => 1,
766 'unknown-header-type' => 1,
767 'unknown-option' => 1,
770 'router-solicitation' => 1,
771 'router-advertisement' => 1,
772 'neighbor-solicitation' => 1,
773 'neighbour-solicitation' => 1,
774 'neighbor-advertisement' => 1,
775 'neighbour-advertisement' => 1,
779 sub init_firewall_macros
{
781 $pve_fw_parsed_macros = {};
784 my ($k, $macro) = @_;
785 my $lc_name = lc($k);
786 $pve_fw_macro_ipversion->{$k} = 0;
787 while (!ref($macro->[0])) {
788 my $desc = shift @$macro;
789 if ($desc eq 'ipv4only') {
790 $pve_fw_macro_ipversion->{$k} = 4;
791 } elsif ($desc eq 'ipv6only') {
792 $pve_fw_macro_ipversion->{$k} = 6;
794 $pve_fw_macro_descr->{$k} = $desc;
797 $pve_fw_preferred_macro_names->{$lc_name} = $k;
798 $pve_fw_parsed_macros->{$k} = $macro;
801 foreach my $k (keys %$pve_fw_macros) {
802 &$parse($k, $pve_fw_macros->{$k});
805 foreach my $k (keys %$pve_ipv6fw_macros) {
806 next if $pve_fw_parsed_macros->{$k};
807 &$parse($k, $pve_ipv6fw_macros->{$k});
808 $pve_fw_macro_ipversion->{$k} = 6;
812 init_firewall_macros
();
815 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
820 sub get_etc_services
{
822 return $etc_services if $etc_services;
824 my $filename = "/etc/services";
826 my $fh = IO
::File-
>new($filename, O_RDONLY
);
828 warn "unable to read '$filename' - $!\n";
834 while (my $line = <$fh>) {
836 next if $line =~m/^#/;
837 next if ($line =~m/^\s*$/);
839 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
840 $services->{byid
}->{$2}->{name
} = $1;
841 $services->{byid
}->{$2}->{port
} = $2;
842 $services->{byid
}->{$2}->{$3} = 1;
843 $services->{byname
}->{$1} = $services->{byid
}->{$2};
849 $etc_services = $services;
852 return $etc_services;
857 sub get_etc_protocols
{
858 return $etc_protocols if $etc_protocols;
860 my $filename = "/etc/protocols";
862 my $fh = IO
::File-
>new($filename, O_RDONLY
);
864 warn "unable to read '$filename' - $!\n";
870 while (my $line = <$fh>) {
872 next if $line =~m/^#/;
873 next if ($line =~m/^\s*$/);
875 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
876 $protocols->{byid
}->{$2}->{name
} = $1;
877 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
883 # add special case for ICMP v6
884 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
885 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
887 $etc_protocols = $protocols;
889 return $etc_protocols;
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
};
915 next if !$mask; # skip the default route...
917 $mask = $PVE::Network
::ipv4_mask_hash_localnet-
>{$entry->{mask
}};
918 next if !defined($mask);
920 my $cidr = "$entry->{dest}/$mask";
921 my $testnet = Net
::IP-
>new($cidr);
922 my $overlap = $testnet->overlaps($testip);
923 if ($overlap == $Net::IP
::IP_B_IN_A_OVERLAP
||
924 $overlap == $Net::IP
::IP_IDENTICAL
)
926 $__local_network = $cidr;
933 return $__local_network;
936 # ipset names are limited to 31 characters,
937 # and we use '-v4' or '-v6' to indicate IP versions,
938 # and we use '_swap' suffix for atomic update,
939 # for example PVEFW-${VMID}-${ipset_name}_swap
941 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
943 sub compute_ipset_chain_name
{
944 my ($vmid, $ipset_name, $ipversion) = @_;
946 $vmid = 0 if !defined($vmid);
948 my $id = "$vmid-${ipset_name}-v$ipversion";
950 if (length($id) > $max_iptables_ipset_name_length) {
951 $id = PVE
::Tools
::fnv31a_hex
($id);
957 sub compute_ipfilter_ipset_name
{
960 return "ipfilter-$iface";
963 sub parse_address_list
{
966 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
967 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
971 if ($str =~ m/^${ip_alias_pattern}$/) {
972 die "alias name too long\n" if length($str) > $max_alias_name_length;
980 my @elements = split(/,/, $str);
981 die "extraneous commas in list\n" if $str ne join(',', @elements);
982 foreach my $elem (@elements) {
984 my $ip = Net
::IP-
>new($elem);
986 my $err = Net
::IP
::Error
();
987 die "invalid IP address: $err\n";
989 $iprange = 1 if $elem =~ m/-/;
991 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
993 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
994 if $ipversion && ($new_ipversion != $ipversion);
996 $ipversion = $new_ipversion;
999 die "you can't use a range in a list\n" if $iprange && $count > 1;
1004 sub parse_port_name_number_or_range
{
1005 my ($str, $dport) = @_;
1007 my $services = PVE
::Firewall
::get_etc_services
();
1011 my @elements = split(/,/, $str);
1012 die "extraneous commas in list\n" if $str ne join(',', @elements);
1013 foreach my $item (@elements) {
1015 if ($item =~ m/^(\d+):(\d+)$/) {
1016 my ($port1, $port2) = ($1, $2);
1017 die "invalid port '$port1'\n" if $port1 > 65535;
1018 die "invalid port '$port2'\n" if $port2 > 65535;
1019 } elsif ($item =~ m/^(\d+)$/) {
1021 die "invalid port '$port'\n" if $port > 65535;
1023 if ($dport && $icmp_type_names->{$item}) {
1025 } elsif ($dport && $icmpv6_type_names->{$item}) {
1028 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1033 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1038 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1039 sub pve_fw_verify_sport_spec
{
1042 parse_port_name_number_or_range
($portstr, 0);
1047 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1048 sub pve_fw_verify_dport_spec
{
1051 parse_port_name_number_or_range
($portstr, 1);
1056 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1057 sub pve_fw_verify_addr_spec
{
1060 parse_address_list
($list);
1065 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1066 sub pve_fw_verify_protocol_spec
{
1069 my $protocols = get_etc_protocols
();
1071 die "unknown protocol '$proto'\n" if $proto &&
1072 !(defined($protocols->{byname
}->{$proto}) ||
1073 defined($protocols->{byid
}->{$proto}));
1079 # helper function for API
1081 sub copy_opject_with_digest
{
1084 my $sha = Digest
::SHA-
>new('sha1');
1087 foreach my $k (sort keys %$object) {
1088 my $v = $object->{$k};
1089 next if !defined($v);
1091 $sha->add($k, ':', $v, "\n");
1094 my $digest = $sha->hexdigest;
1096 $res->{digest
} = $digest;
1098 return wantarray ?
($res, $digest) : $res;
1101 sub copy_list_with_digest
{
1104 my $sha = Digest
::SHA-
>new('sha1');
1107 foreach my $entry (@$list) {
1109 foreach my $k (sort keys %$entry) {
1110 my $v = $entry->{$k};
1111 next if !defined($v);
1113 # Note: digest ignores refs ($rule->{errors})
1114 # since Digest::SHA expects a series of bytes,
1115 # we have to encode the value here to prevent errors when
1116 # using utf8 characters (eg. in comments)
1117 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1122 my $digest = $sha->hexdigest;
1124 foreach my $entry (@$res) {
1125 $entry->{digest
} = $digest;
1128 return wantarray ?
($res, $digest) : $res;
1131 our $cluster_option_properties = {
1133 description
=> "Enable or disable the firewall cluster wide.",
1139 description
=> "Input policy.",
1142 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1145 description
=> "Output policy.",
1148 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1152 our $host_option_properties = {
1154 description
=> "Enable host firewall rules.",
1158 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1159 description
=> "Log level for incoming traffic." }),
1160 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1161 description
=> "Log level for outgoing traffic." }),
1162 tcp_flags_log_level
=> get_standard_option
('pve-fw-loglevel', {
1163 description
=> "Log level for illegal tcp flags filter." }),
1164 smurf_log_level
=> get_standard_option
('pve-fw-loglevel', {
1165 description
=> "Log level for SMURFS filter." }),
1167 description
=> "Enable SMURFS filter.",
1172 description
=> "Filter illegal combinations of TCP flags.",
1176 nf_conntrack_max
=> {
1177 description
=> "Maximum number of tracked connections.",
1182 nf_conntrack_tcp_timeout_established
=> {
1183 description
=> "Conntrack established timeout.",
1189 description
=> "Enable NDP.",
1195 our $vm_option_properties = {
1197 description
=> "Enable/disable firewall rules.",
1202 description
=> "Enable/disable MAC address filter.",
1207 description
=> "Enable DHCP.",
1212 description
=> "Enable NDP.",
1217 description
=> "Allow sending Router Advertisement.",
1222 description
=> "Enable default IP filters. " .
1223 "This is equivalent to adding an empty ipfilter-net<id> ipset " .
1224 "for every interface. Such ipsets implicitly contain sane default " .
1225 "restrictions such as restricting IPv6 link local addresses to " .
1226 "the one derived from the interface's MAC address. For containers " .
1227 "the configured IP addresses will be implicitly added.",
1232 description
=> "Input policy.",
1235 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1238 description
=> "Output policy.",
1241 enum
=> ['ACCEPT', 'REJECT', 'DROP'],
1243 log_level_in
=> get_standard_option
('pve-fw-loglevel', {
1244 description
=> "Log level for incoming traffic." }),
1245 log_level_out
=> get_standard_option
('pve-fw-loglevel', {
1246 description
=> "Log level for outgoing traffic." }),
1251 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.";
1253 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.";
1255 my $rule_properties = {
1257 description
=> "Update rule at position <pos>.",
1262 digest
=> get_standard_option
('pve-config-digest'),
1264 description
=> "Rule type.",
1267 enum
=> ['in', 'out', 'group'],
1270 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1273 pattern
=> $security_group_name_pattern,
1278 description
=> "Use predefined standard macro.",
1283 iface
=> get_standard_option
('pve-iface', {
1284 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.",
1288 description
=> "Restrict packet source address. $addr_list_descr",
1289 type
=> 'string', format
=> 'pve-fw-addr-spec',
1293 description
=> "Restrict packet destination address. $addr_list_descr",
1294 type
=> 'string', format
=> 'pve-fw-addr-spec',
1298 description
=> "IP protocol. You can use protocol names ('tcp'/'udp') or simple numbers, as defined in '/etc/protocols'.",
1299 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1303 description
=> "Flag to enable/disable a rule.",
1309 description
=> "Restrict TCP/UDP source port. $port_descr",
1310 type
=> 'string', format
=> 'pve-fw-sport-spec',
1314 description
=> "Restrict TCP/UDP destination port. $port_descr",
1315 type
=> 'string', format
=> 'pve-fw-dport-spec',
1319 description
=> "Descriptive comment.",
1325 sub add_rule_properties
{
1326 my ($properties) = @_;
1328 foreach my $k (keys %$rule_properties) {
1329 my $h = $rule_properties->{$k};
1330 # copy data, so that we can modify later without side effects
1331 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1337 sub delete_rule_properties
{
1338 my ($rule, $delete_str) = @_;
1340 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1341 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1342 if !defined($rule_properties->{$opt});
1343 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1344 if $opt eq 'type' || $opt eq 'action';
1345 delete $rule->{$opt};
1351 my $apply_macro = sub {
1352 my ($macro_name, $param, $verify, $ipversion) = @_;
1354 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1355 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1357 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1358 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1361 # skip macros which are specific to another ipversion
1362 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1363 return if $ipversion != $required;
1368 foreach my $templ (@$macro_rules) {
1370 my $param_used = {};
1371 foreach my $k (keys %$templ) {
1372 my $v = $templ->{$k};
1373 if ($v eq 'PARAM') {
1375 $param_used->{$k} = 1;
1376 } elsif ($v eq 'DEST') {
1377 $v = $param->{dest
};
1378 $param_used->{dest
} = 1;
1379 } elsif ($v eq 'SOURCE') {
1380 $v = $param->{source
};
1381 $param_used->{source
} = 1;
1385 my $msg = "missing parameter '$k' in macro '$macro_name'";
1386 raise_param_exc
({ macro => $msg }) if $verify;
1391 foreach my $k (keys %$param) {
1392 next if $k eq 'macro';
1393 next if !defined($param->{$k});
1394 next if $param_used->{$k};
1395 if (defined($rule->{$k})) {
1396 if ($rule->{$k} ne $param->{$k}) {
1397 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1398 raise_param_exc
({ $k => $msg }) if $verify;
1402 $rule->{$k} = $param->{$k};
1405 push @$rules, $rule;
1411 my $rule_env_iface_lookup = {
1420 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1422 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1424 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1425 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1427 my $errors = $rule->{errors
} || {};
1429 my $error_count = 0;
1431 my $add_error = sub {
1432 my ($param, $msg) = @_;
1434 raise_param_exc
({ $param => $msg }) if !$noerr;
1436 $errors->{$param} = $msg if !$errors->{$param};
1440 my $set_ip_version = sub {
1443 die "detected mixed ipv4/ipv6 adresses in rule\n"
1444 if $ipversion && ($vers != $ipversion);
1449 my $check_ipset_or_alias_property = sub {
1450 my ($name, $expected_ipversion) = @_;
1452 if (my $value = $rule->{$name}) {
1453 if ($value =~ m/^\+/) {
1454 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1455 &$add_error($name, "no such ipset '$1'")
1456 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1459 &$add_error($name, "invalid ipset name '$value'");
1461 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1462 my $alias = lc($value);
1463 &$add_error($name, "no such alias '$value'")
1464 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1465 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1466 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1468 &$set_ip_version($e->{ipversion
});
1473 my $type = $rule->{type
};
1474 my $action = $rule->{action
};
1476 &$add_error('type', "missing property") if !$type;
1477 &$add_error('action', "missing property") if !$action;
1480 if ($type eq 'in' || $type eq 'out') {
1481 &$add_error('action', "unknown action '$action'")
1482 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1483 } elsif ($type eq 'group') {
1484 &$add_error('type', "security groups not allowed")
1486 &$add_error('action', "invalid characters in security group name")
1487 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1489 &$add_error('type', "unknown rule type '$type'");
1493 if ($rule->{iface
}) {
1494 &$add_error('type', "parameter -i not allowed for this rule type")
1496 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1497 &$add_error('iface', $@) if $@;
1498 if ($rule_env eq 'vm' || $rule_env eq 'ct') {
1499 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1500 if $rule->{iface
} !~ m/^net(\d+)$/;
1504 if ($rule->{macro}) {
1505 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1506 $rule->{macro} = $preferred_name;
1508 &$add_error('macro', "unknown macro '$rule->{macro}'");
1512 if ($rule->{proto
}) {
1513 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1514 &$add_error('proto', $@) if $@;
1515 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1516 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1519 if ($rule->{dport
}) {
1520 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1521 &$add_error('dport', $@) if $@;
1522 my $proto = $rule->{proto
};
1523 &$add_error('proto', "missing property - 'dport' requires this property")
1525 &$add_error('dport', "protocol '$proto' does not support ports")
1526 if !$PROTOCOLS_WITH_PORTS->{$proto} &&
1527 $proto ne 'icmp' && $proto ne 'icmpv6'; # special cases
1530 if ($rule->{sport
}) {
1531 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1532 &$add_error('sport', $@) if $@;
1533 my $proto = $rule->{proto
};
1534 &$add_error('proto', "missing property - 'sport' requires this property")
1536 &$add_error('sport', "protocol '$proto' does not support ports")
1537 if !$PROTOCOLS_WITH_PORTS->{$proto};
1540 if ($rule->{source
}) {
1542 my $source_ipversion = parse_address_list
($rule->{source
});
1543 &$set_ip_version($source_ipversion);
1545 &$add_error('source', $@) if $@;
1546 &$check_ipset_or_alias_property('source', $ipversion);
1549 if ($rule->{dest
}) {
1551 my $dest_ipversion = parse_address_list
($rule->{dest
});
1552 &$set_ip_version($dest_ipversion);
1554 &$add_error('dest', $@) if $@;
1555 &$check_ipset_or_alias_property('dest', $ipversion);
1558 $rule->{ipversion
} = $ipversion if $ipversion;
1560 if ($rule->{macro} && !$error_count) {
1561 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1563 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1564 my $eh = $err->{errors
};
1565 foreach my $p (keys %$eh) {
1566 &$add_error($p, $eh->{$p});
1569 &$add_error('macro', "$err");
1574 $rule->{errors
} = $errors if $error_count;
1579 sub copy_rule_data
{
1580 my ($rule, $param) = @_;
1582 foreach my $k (keys %$rule_properties) {
1583 if (defined(my $v = $param->{$k})) {
1584 if ($v eq '' || $v eq '-') {
1595 sub rules_modify_permissions
{
1596 my ($rule_env) = @_;
1598 if ($rule_env eq 'host') {
1600 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1602 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1604 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1606 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1608 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1615 sub rules_audit_permissions
{
1616 my ($rule_env) = @_;
1618 if ($rule_env eq 'host') {
1620 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1622 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1624 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1626 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1628 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1636 my $bridge_firewall_enabled = 0;
1638 sub enable_bridge_firewall
{
1640 return if $bridge_firewall_enabled; # only once
1642 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1643 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1645 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1646 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1648 $bridge_firewall_enabled = 1;
1651 sub iptables_restore_cmdlist
{
1654 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1657 sub ip6tables_restore_cmdlist
{
1660 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1663 sub ipset_restore_cmdlist
{
1666 run_command
("/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1669 sub iptables_get_chains
{
1670 my ($iptablescmd) = @_;
1672 $iptablescmd = "iptables" if !$iptablescmd;
1676 # check what chains we want to track
1677 my $is_pvefw_chain = sub {
1680 return 1 if $name =~ m/^PVEFW-\S+$/;
1682 return 1 if $name =~ m/^tap\d+i\d+-(?:IN|OUT)$/;
1684 return 1 if $name =~ m/^veth\d+i\d+-(?:IN|OUT)$/;
1686 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(?:FW|IN|OUT|IPS)$/;
1687 return 1 if $name =~ m/^GROUP-(?:$security_group_name_pattern)-(?:IN|OUT)$/;
1699 return if $line =~ m/^#/;
1700 return if $line =~ m/^\s*$/;
1702 if ($line =~ m/^\*(\S+)$/) {
1707 return if $table ne 'filter';
1709 if ($line =~ m/^:(\S+)\s/) {
1711 return if !&$is_pvefw_chain($chain);
1712 $res->{$chain} = "unknown";
1713 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1714 my ($chain, $sig) = ($1, $2);
1715 return if !&$is_pvefw_chain($chain);
1716 $res->{$chain} = $sig;
1717 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1720 # simply ignore the rest
1725 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1727 return wantarray ?
($res, $hooks) : $res;
1730 sub iptables_chain_digest
{
1732 my $digest = Digest
::SHA-
>new('sha1');
1733 foreach my $rule (@$rules) { # order is important
1734 $digest->add($rule);
1736 return $digest->b64digest;
1739 sub ipset_chain_digest
{
1742 my $digest = Digest
::SHA-
>new('sha1');
1743 foreach my $rule (sort @$rules) { # note: sorted
1744 $digest->add($rule);
1746 return $digest->b64digest;
1749 sub ipset_get_chains
{
1757 return if $line =~ m/^#/;
1758 return if $line =~ m/^\s*$/;
1759 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1761 $line =~ s/\s+$//; # delete trailing white space
1762 push @{$chains->{$chain}}, $line;
1764 # simply ignore the rest
1769 run_command
("/sbin/ipset save", outfunc
=> $parser);
1771 # compute digest for each chain
1772 foreach my $chain (keys %$chains) {
1773 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1779 sub ruleset_generate_match
{
1780 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1782 return if defined($rule->{enable
}) && !$rule->{enable
};
1783 return if $rule->{errors
};
1785 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1787 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1788 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1792 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1793 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1795 my $source = $rule->{source
};
1796 my $dest = $rule->{dest
};
1799 if ($source =~ m/^\+/) {
1800 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1802 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1803 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1804 push @cmd, "-m set --match-set ${ipset_chain} src";
1805 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1806 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1807 push @cmd, "-m set --match-set ${ipset_chain} src";
1809 die "no such ipset '$name'\n";
1812 die "invalid security group name '$source'\n";
1814 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1815 my $alias = lc($source);
1816 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1817 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1818 die "no such alias '$source'\n" if !$e;
1819 push @cmd, "-s $e->{cidr}";
1820 } elsif ($source =~ m/\-/){
1821 push @cmd, "-m iprange --src-range $source";
1823 push @cmd, "-s $source";
1828 if ($dest =~ m/^\+/) {
1829 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1831 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1832 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1833 push @cmd, "-m set --match-set ${ipset_chain} dst";
1834 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1835 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1836 push @cmd, "-m set --match-set ${ipset_chain} dst";
1838 die "no such ipset '$name'\n";
1841 die "invalid security group name '$dest'\n";
1843 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1844 my $alias = lc($dest);
1845 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1846 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1847 die "no such alias '$dest'\n" if !$e;
1848 push @cmd, "-d $e->{cidr}";
1849 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1850 push @cmd, "-m iprange --dst-range $dest";
1852 push @cmd, "-d $dest";
1856 if (my $proto = $rule->{proto
}) {
1857 push @cmd, "-p $proto";
1860 $multiport++ if $nbdport > 1;
1861 $multiport++ if $nbsport > 1;
1863 push @cmd, "--match multiport" if $multiport;
1865 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1866 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1868 if ($rule->{dport
}) {
1869 if ($proto eq 'icmp') {
1870 # Note: we use dport to store --icmp-type
1871 die "unknown icmp-type '$rule->{dport}'\n"
1872 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1873 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1874 } elsif ($proto eq 'icmpv6') {
1875 # Note: we use dport to store --icmpv6-type
1876 die "unknown icmpv6-type '$rule->{dport}'\n"
1877 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1878 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1879 } elsif (!$PROTOCOLS_WITH_PORTS->{$proto}) {
1880 die "protocol $proto does not have ports\n";
1883 if ($multiport == 2) {
1884 push @cmd, "--ports $rule->{dport}";
1886 push @cmd, "--dports $rule->{dport}";
1889 push @cmd, "--dport $rule->{dport}";
1894 if ($rule->{sport
}) {
1895 die "protocol $proto does not have ports\n"
1896 if !$PROTOCOLS_WITH_PORTS->{$proto};
1898 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1900 push @cmd, "--sport $rule->{sport}";
1903 } elsif ($rule->{dport
} || $rule->{sport
}) {
1904 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1905 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1908 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1910 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1913 sub ruleset_generate_action
{
1914 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1918 if (my $action = $rule->{action
}) {
1919 $action = $actions->{$action} if defined($actions->{$action});
1920 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1921 push @cmd, $goto ?
"-g $action" : "-j $action";
1924 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1927 sub ruleset_generate_cmdstr
{
1928 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1929 my $match = ruleset_generate_match
($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1930 my $action = ruleset_generate_action
($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf);
1932 return undef if !(defined($match) or defined($action));
1933 my $ret = defined($match) ?
$match : "";
1934 $ret = "$ret $action" if defined($action);
1938 sub ruleset_generate_rule
{
1939 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1943 if ($rule->{macro}) {
1944 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1949 # update all or nothing
1953 foreach my $tmp (@$rules) {
1954 my $m = ruleset_generate_match
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1955 my $a = ruleset_generate_action
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf);
1956 if (defined $m or defined $a) {
1957 push @mstrs, defined($m) ?
$m : "";
1958 push @astrs, defined($a) ?
$a : "";
1962 for my $i (0 .. $#mstrs) {
1963 ruleset_addrule
($ruleset, $chain, $mstrs[$i], $astrs[$i]);
1967 sub ruleset_generate_rule_insert
{
1968 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1970 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1972 my $match = ruleset_generate_match
($ruleset, $chain, $ipversion, $rule, $actions, $goto);
1973 my $action = ruleset_generate_action
($ruleset, $chain, $ipversion, $rule, $actions, $goto);
1974 if (defined $match && defined $action) {
1975 ruleset_insertrule
($ruleset, $chain, $match, $action);
1979 sub ruleset_create_chain
{
1980 my ($ruleset, $chain) = @_;
1982 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1983 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1985 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1987 $ruleset->{$chain} = [];
1990 sub ruleset_chain_exist
{
1991 my ($ruleset, $chain) = @_;
1993 return $ruleset->{$chain} ?
1 : undef;
1996 sub ruleset_addrule_old
{
1997 my ($ruleset, $chain, $rule) = @_;
1999 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2001 push @{$ruleset->{$chain}}, "-A $chain $rule";
2004 sub ruleset_addrule
{
2005 my ($ruleset, $chain, $match, $action, $log, $logmsg, $vmid) = @_;
2007 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2009 if (defined($log) && $log) {
2010 my $logaction = get_log_rule_base
($chain, $vmid, $logmsg, $log);
2011 push @{$ruleset->{$chain}}, "-A $chain $match $logaction";
2013 push @{$ruleset->{$chain}}, "-A $chain $match $action";
2016 sub ruleset_insertrule
{
2017 my ($ruleset, $chain, $match, $action, $log) = @_;
2019 die "no such chain '$chain'\n" if !$ruleset->{$chain};
2021 unshift @{$ruleset->{$chain}}, "-A $chain $match $action";
2024 sub get_log_rule_base
{
2025 my ($chain, $vmid, $msg, $loglevel) = @_;
2027 $vmid = 0 if !defined($vmid);
2028 $msg = "" if !defined($msg);
2030 # Note: we use special format for prefix to pass further
2031 # info to log daemon (VMID, LOGLEVEL and CHAIN)
2033 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
2036 sub ruleset_add_chain_policy {
2037 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
2039 if ($policy eq 'ACCEPT') {
2041 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
2042 { ACCEPT => $accept_action});
2044 } elsif ($policy eq 'DROP') {
2046 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Drop
");
2048 ruleset_addrule($ruleset, $chain, "", "-j DROP
", $loglevel, "policy
$policy: ", $vmid);
2049 } elsif ($policy eq 'REJECT') {
2050 ruleset_addrule($ruleset, $chain, "", "-j PVEFW-Reject
");
2052 ruleset_addrule($ruleset, $chain, "", "-g PVEFW-reject
", $loglevel, "policy
$policy:", $vmid);
2055 die "internal error
: unknown policy
'$policy'";
2059 sub ruleset_chain_add_ndp {
2060 my ($ruleset, $chain, $ipversion, $options, $direction, $accept) = @_;
2061 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
2063 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
", $accept);
2064 if ($direction ne 'OUT' || $options->{radv}) {
2065 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
", $accept);
2067 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
", $accept);
2068 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
", $accept);
2071 sub ruleset_chain_add_conn_filters {
2072 my ($ruleset, $chain, $accept) = @_;
2074 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
", "-j DROP
");
2075 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
", "-j
$accept");
2078 sub ruleset_chain_add_input_filters {
2079 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
2081 if ($cluster_conf->{ipset}->{blacklist}){
2082 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
2083 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
2084 ruleset_addrule($ruleset, "PVEFW-blacklist
", "", "-j DROP
", $loglevel, "DROP
: ");
2086 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
2087 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
", "-j PVEFW-blacklist
");
2090 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
2091 if ($ipversion == 4) {
2092 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
", "-j PVEFW-smurfs
");
2096 if ($options->{tcpflags}) {
2097 ruleset_addrule($ruleset, $chain, "-p tcp
", "-j PVEFW-tcpflags
");
2101 sub ruleset_create_vm_chain {
2102 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
2104 ruleset_create_chain($ruleset, $chain);
2105 my $accept = generate_nfqueue($options);
2107 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
2108 if ($ipversion == 4) {
2109 if ($direction eq 'OUT') {
2110 ruleset_generate_rule($ruleset, $chain, $ipversion,
2111 { action => 'PVEFW-SET-ACCEPT-MARK',
2112 proto => 'udp', sport => 68, dport => 67 });
2114 ruleset_generate_rule($ruleset, $chain, $ipversion,
2115 { action => 'ACCEPT',
2116 proto => 'udp', sport => 67, dport => 68 });
2118 } elsif ($ipversion == 6) {
2119 if ($direction eq 'OUT') {
2120 ruleset_generate_rule($ruleset, $chain, $ipversion,
2121 { action => 'PVEFW-SET-ACCEPT-MARK',
2122 proto => 'udp', sport => 546, dport => 547 });
2124 ruleset_generate_rule($ruleset, $chain, $ipversion,
2125 { action => 'ACCEPT',
2126 proto => 'udp', sport => 547, dport => 546 });
2132 if ($direction eq 'OUT') {
2133 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
2134 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr", "-j DROP
");
2136 if ($ipversion == 6 && !$options->{radv}) {
2137 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
", "-j DROP
");
2139 if ($ipfilter_ipset) {
2140 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
", "-j DROP
");
2142 ruleset_addrule($ruleset, $chain, "", "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2145 my $accept_action = $direction eq 'OUT' ? '-g PVEFW-SET-ACCEPT-MARK' : "-j
$accept";
2146 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, $direction, $accept_action);
2149 sub ruleset_add_group_rule {
2150 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
2152 my $group = $rule->{action};
2153 my $group_chain = "GROUP-
$group-$direction";
2154 if(!ruleset_chain_exist($ruleset, $group_chain)){
2155 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
2158 if ($direction eq 'OUT' && $rule->{iface_out}) {
2159 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
}", "-j
$group_chain");
2160 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
2161 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
}", "-j
$group_chain");
2163 ruleset_addrule($ruleset, $chain, "", "-j
$group_chain");
2166 ruleset_addrule($ruleset, $chain, "-m mark
--mark
$FWACCEPTMARK_ON", "-j
$action");
2169 sub ruleset_generate_vm_rules {
2170 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
2172 my $lc_direction = lc($direction);
2174 my $in_accept = generate_nfqueue($options);
2176 foreach my $rule (@$rules) {
2177 next if $rule->{iface} && $rule->{iface} ne $netid;
2178 next if !$rule->{enable} || $rule->{errors};
2179 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2181 if ($rule->{type} eq 'group') {
2182 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
2183 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
2185 next if $rule->{type} ne $lc_direction;
2187 if ($direction eq 'OUT') {
2188 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2189 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2190 undef, $cluster_conf, $vmfw_conf);
2192 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2193 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
2194 undef, $cluster_conf, $vmfw_conf);
2202 sub generate_nfqueue {
2205 if ($options->{ips}) {
2206 my $action = "NFQUEUE
";
2207 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2208 if (defined($3) && defined($1)) {
2209 $action .= " --queue-balance
$1:$3";
2210 } elsif (defined($1)) {
2211 $action .= " --queue-num
$1";
2214 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2221 sub ruleset_generate_vm_ipsrules {
2222 my ($ruleset, $options, $direction, $iface) = @_;
2224 if ($options->{ips} && $direction eq 'IN') {
2225 my $nfqueue = generate_nfqueue($options);
2227 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2228 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2231 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
", "-j
$nfqueue");
2235 sub generate_tap_rules_direction {
2236 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2238 my $lc_direction = lc($direction);
2240 my $rules = $vmfw_conf->{rules};
2242 my $options = $vmfw_conf->{options};
2243 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2245 my $tapchain = "$iface-$direction";
2247 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2248 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2249 if $options->{ipfilter} || $vmfw_conf->{ipset}->{$ipfilter_name};
2251 # create chain with mac and ip filter
2252 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2254 if ($options->{enable}) {
2255 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2257 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2262 if ($direction eq 'OUT') {
2263 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2265 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2268 my $accept = generate_nfqueue($options);
2269 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2270 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2272 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2273 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2276 # plug the tap chain to bridge chain
2277 if ($direction eq 'IN') {
2278 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2279 "-m physdev
--physdev-is-bridged
--physdev-out
$iface", "-j
$tapchain");
2281 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2282 "-m physdev
--physdev-is-bridged
--physdev-in
$iface", "-j
$tapchain");
2286 sub enable_host_firewall {
2287 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2289 my $options = $hostfw_conf->{options};
2290 my $cluster_options = $cluster_conf->{options};
2291 my $rules = $hostfw_conf->{rules};
2292 my $cluster_rules = $cluster_conf->{rules};
2294 # host inbound firewall
2295 my $chain = "PVEFW-HOST-IN
";
2296 ruleset_create_chain($ruleset, $chain);
2298 my $loglevel = get_option_log_level($options, "log_level_in
");
2300 ruleset_addrule($ruleset, $chain, "-i lo
", "-j ACCEPT
");
2302 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2303 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'IN', '-j RETURN');
2304 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2306 # we use RETURN because we need to check also tap rules
2307 my $accept_action = 'RETURN';
2309 ruleset_addrule($ruleset, $chain, "-p igmp
", "-j
$accept_action"); # important for multicast
2311 # add host rules first, so that cluster wide rules can be overwritten
2312 foreach my $rule (@$rules, @$cluster_rules) {
2313 next if !$rule->{enable} || $rule->{errors};
2314 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2316 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2319 if ($rule->{type} eq 'group') {
2320 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2321 } elsif ($rule->{type} eq 'in') {
2322 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2323 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2324 undef, $cluster_conf, $hostfw_conf);
2328 delete $rule->{iface_in};
2331 # allow standard traffic for management ipset (includes cluster network)
2332 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2333 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2334 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006", "-j
$accept_action"); # PVE API
2335 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999", "-j
$accept_action"); # PVE VNC Console
2336 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128", "-j
$accept_action"); # SPICE Proxy
2337 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22", "-j
$accept_action"); # SSH
2339 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2340 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2343 if ($localnet && ($ipversion == $localnet_ver)) {
2344 my $corosync_rule = "-p udp
--dport
5404:5405";
2345 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule", "-j
$accept_action");
2346 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule", "-j
$accept_action");
2349 # implement input policy
2350 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2351 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2353 # host outbound firewall
2354 $chain = "PVEFW-HOST-OUT
";
2355 ruleset_create_chain($ruleset, $chain);
2357 $loglevel = get_option_log_level($options, "log_level_out
");
2359 ruleset_addrule($ruleset, $chain, "-o lo
", "-j ACCEPT
");
2361 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2363 # we use RETURN because we may want to check other thigs later
2364 $accept_action = 'RETURN';
2365 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options, 'OUT', "-j
$accept_action");
2367 ruleset_addrule($ruleset, $chain, "-p igmp
", "-j
$accept_action"); # important for multicast
2369 # add host rules first, so that cluster wide rules can be overwritten
2370 foreach my $rule (@$rules, @$cluster_rules) {
2371 next if !$rule->{enable} || $rule->{errors};
2372 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2374 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2376 if ($rule->{type} eq 'group') {
2377 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2378 } elsif ($rule->{type} eq 'out') {
2379 ruleset_generate_rule($ruleset, $chain, $ipversion,
2380 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2381 undef, $cluster_conf, $hostfw_conf);
2385 delete $rule->{iface_out};
2388 # allow standard traffic on cluster network
2389 if ($localnet && ($ipversion == $localnet_ver)) {
2390 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006", "-j
$accept_action"); # PVE API
2391 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22", "-j
$accept_action"); # SSH
2392 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999", "-j
$accept_action"); # PVE VNC Console
2393 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128", "-j
$accept_action"); # SPICE Proxy
2395 my $corosync_rule = "-p udp
--dport
5404:5405";
2396 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule", "-j
$accept_action");
2397 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule", "-j
$accept_action");
2400 # implement output policy
2401 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2402 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2404 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "", "-j PVEFW-HOST-OUT
");
2405 ruleset_addrule($ruleset, "PVEFW-INPUT
", "", "-j PVEFW-HOST-IN
");
2408 sub generate_group_rules {
2409 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2411 my $rules = $cluster_conf->{groups}->{$group};
2414 warn "no such security group
'$group'\n";
2415 $rules = []; # create empty chain
2418 my $chain = "GROUP-
${group
}-IN
";
2420 ruleset_create_chain($ruleset, $chain);
2421 ruleset_addrule($ruleset, $chain, "", "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2423 foreach my $rule (@$rules) {
2424 next if $rule->{type} ne 'in';
2425 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2426 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2427 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2428 undef, $cluster_conf);
2431 $chain = "GROUP-
${group
}-OUT
";
2433 ruleset_create_chain($ruleset, $chain);
2434 ruleset_addrule($ruleset, $chain, "", "-j MARK
--set-mark
$FWACCEPTMARK_OFF"); # clear mark
2436 foreach my $rule (@$rules) {
2437 next if $rule->{type} ne 'out';
2438 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2439 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2440 # check also other tap rules later
2441 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2442 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2443 undef, $cluster_conf);
2448 my $valid_netdev_names = {};
2449 for (my $i = 0; $i < $MAX_NETS; $i++) {
2450 $valid_netdev_names->{"net
$i"} = 1;
2453 sub get_mark_values {
2454 my ($value, $mask) = @_;
2455 $value = hex($value) if $value =~ /^0x/;
2456 $mask = hex($mask) if defined($mask) && $mask =~ /^0x/;
2457 $mask = 0xffffffff if !defined($mask);
2458 return ($value, $mask);
2462 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2464 my $orig_line = $line;
2468 # we can add single line comments to the end of the rule
2469 if ($line =~ s/#\s*(.*?)\s*$//) {
2470 $rule->{comment} = decode('utf8', $1);
2473 # we can disable a rule when prefixed with '|'
2475 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2477 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2478 die "unable to parse rule
: $line\n";
2480 $rule->{type} = lc($1);
2481 $rule->{action} = $2;
2483 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2484 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2485 $rule->{macro} = $1;
2486 $rule->{action} = $2;
2490 while (length($line)) {
2491 if ($line =~ s/^-i (\S+)\s*//) {
2492 $rule->{iface} = $1;
2496 last if $rule->{type} eq 'group';
2498 if ($line =~ s/^-p (\S+)\s*//) {
2499 $rule->{proto} = $1;
2503 if ($line =~ s/^-dport (\S+)\s*//) {
2504 $rule->{dport} = $1;
2508 if ($line =~ s/^-sport (\S+)\s*//) {
2509 $rule->{sport} = $1;
2512 if ($line =~ s/^-source (\S+)\s*//) {
2513 $rule->{source} = $1;
2516 if ($line =~ s/^-dest (\S+)\s*//) {
2524 die "unable to parse rule parameters
: $line\n" if length($line);
2526 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2527 if ($rule->{errors}) {
2528 # The verbose flag really means we're running from the CLI and want
2529 # output on the console - in the other case we really want such errors
2530 # to go into the syslog instead.
2531 my $log = $verbose ? sub { warn @_ } : sub { syslog(err => @_) };
2532 $log->("$prefix - errors
in rule parameters
: $orig_line\n");
2533 foreach my $p (keys %{$rule->{errors}}) {
2534 $log->(" $p: $rule->{errors
}->{$p}\n");
2541 sub parse_vmfw_option {
2546 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2548 if ($line =~ m/^(enable|dhcp|ndp|radv|macfilter|ipfilter|ips):\s*(0|1)\s*$/i) {
2551 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2553 $value = $2 ? lc($3) : '';
2554 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2557 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2561 die "can
't parse option '$line'\n"
2564 return ($opt, $value);
2567 sub parse_hostfw_option {
2572 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2574 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2577 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2579 $value = $2 ? lc($3) : '';
2580 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2584 die "can't parse option
'$line'\n"
2587 return ($opt, $value);
2590 sub parse_clusterfw_option {
2595 if ($line =~ m/^(enable):\s*(\d+)\s*$/i) {
2598 if (($value > 1) && ((time() - $value) > 60)) {
2601 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2605 die "can
't parse option '$line'\n"
2608 return ($opt, $value);
2612 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2614 my $alias = lc($cidr);
2615 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2616 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2618 die "no such alias '$cidr'\n" if !$e;;
2620 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2623 sub parse_ip_or_cidr {
2628 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2631 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2635 die "value does not look like a valid IP address or CIDR network\n";
2638 return wantarray ? ($cidr, $ipversion) : $cidr;
2644 # we can add single line comments to the end of the line
2645 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2647 if ($line =~ m/^(\S+)\s(\S+)$/) {
2648 my ($name, $cidr) = ($1, $2);
2651 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2656 ipversion => $ipversion,
2658 $data->{comment} = $comment if $comment;
2665 sub generic_fw_config_parser {
2666 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2671 my $res = $empty_conf;
2673 while (defined(my $line = <$fh>)) {
2674 next if $line =~ m/^#/;
2675 next if $line =~ m/^\s*$/;
2679 my $linenr = $fh->input_line_number();
2680 my $prefix = "$filename (line $linenr)";
2682 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2683 $section = 'options
';
2687 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2688 $section = 'aliases
';
2692 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2693 $section = 'groups
';
2697 die "security group name too long\n" if length($group) > $max_group_name_length;
2698 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2701 ($section, $group, $comment) = undef;
2702 warn "$prefix: $err";
2706 $res->{$section}->{$group} = [];
2707 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2712 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2717 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2722 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2723 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2726 ($section, $group, $comment) = undef;
2727 warn "$prefix: $err";
2731 $res->{$section}->{$group} = [];
2732 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2738 warn "$prefix: skip line - no section\n";
2742 if ($section eq 'options
') {
2745 if ($rule_env eq 'cluster
') {
2746 ($opt, $value) = parse_clusterfw_option($line);
2747 } elsif ($rule_env eq 'host
') {
2748 ($opt, $value) = parse_hostfw_option($line);
2750 ($opt, $value) = parse_vmfw_option($line);
2752 $res->{options}->{$opt} = $value;
2754 warn "$prefix: $@" if $@;
2755 } elsif ($section eq 'aliases
') {
2757 my $data = parse_alias($line);
2758 $res->{aliases}->{lc($data->{name})} = $data;
2760 warn "$prefix: $@" if $@;
2761 } elsif ($section eq 'rules
') {
2763 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2765 warn "$prefix: $err";
2768 push @{$res->{$section}}, $rule;
2769 } elsif ($section eq 'groups
') {
2771 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2773 warn "$prefix: $err";
2776 push @{$res->{$section}->{$group}}, $rule;
2777 } elsif ($section eq 'ipset
') {
2778 # we can add single line comments to the end of the rule
2779 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2781 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2786 if ($nomatch && !$feature_ipset_nomatch) {
2787 $errors->{nomatch} = "nomatch not supported by kernel";
2791 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2792 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2794 $cidr = parse_ip_or_cidr($cidr);
2799 $errors->{cidr} = $err;
2802 if ($cidr =~ m!/0+$!) {
2803 $errors->{cidr} = "a zero prefix is not allowed in ipset entries\n";
2806 my $entry = { cidr => $cidr };
2807 $entry->{nomatch} = 1 if $nomatch;
2808 $entry->{comment} = $comment if $comment;
2809 $entry->{errors} = $errors if $errors;
2811 if ($verbose && $errors) {
2812 warn "$prefix - errors in ipset '$group': $line\n";
2813 foreach my $p (keys %{$errors}) {
2814 warn " $p: $errors->{$p}\n";
2818 push @{$res->{$section}->{$group}}, $entry;
2820 warn "$prefix: skip line - unknown section\n";
2828 sub parse_hostfw_config {
2829 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2831 my $empty_conf = { rules => [], options => {}};
2833 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2836 sub parse_vmfw_config {
2837 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2844 ipset_comments => {},
2847 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2850 sub parse_clusterfw_config {
2851 my ($filename, $fh, $verbose) = @_;
2861 group_comments => {},
2863 ipset_comments => {},
2866 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2870 my ($code, @param) = @_;
2874 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2881 sub read_local_vm_config {
2886 my $vmdata = { qemu => $qemu, lxc => $lxc };
2888 my $vmlist = PVE::Cluster::get_vmlist();
2889 return $vmdata if !$vmlist || !$vmlist->{ids};
2890 my $ids = $vmlist->{ids};
2892 foreach my $vmid (keys %$ids) {
2893 next if !$vmid; # skip VE0
2894 my $d = $ids->{$vmid};
2895 next if !$d->{node} || $d->{node} ne $nodename;
2896 next if !$d->{type};
2897 if ($d->{type} eq 'qemu
') {
2898 if ($have_qemu_server) {
2899 my $cfspath = PVE::QemuConfig->cfs_config_path($vmid);
2900 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2901 $qemu->{$vmid} = $conf;
2904 } elsif ($d->{type} eq 'lxc
') {
2906 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
2907 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2908 $lxc->{$vmid} = $conf;
2917 sub load_vmfw_conf {
2918 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2922 $dir = $pvefw_conf_dir if !defined($dir);
2924 my $filename = "$dir/$vmid.fw";
2925 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2926 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2927 $vmfw_conf->{vmid} = $vmid;
2933 my $format_rules = sub {
2934 my ($rules, $allow_iface) = @_;
2938 foreach my $rule (@$rules) {
2939 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2940 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2941 $raw .= uc($rule->{type});
2942 if ($rule->{macro}) {
2943 $raw .= " $rule->{macro}($rule->{action})";
2945 $raw .= " " . $rule->{action};
2947 if ($allow_iface && $rule->{iface}) {
2948 $raw .= " -i $rule->{iface}";
2951 if ($rule->{type} ne 'group
') {
2952 $raw .= " -source $rule->{source}" if $rule->{source};
2953 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2954 $raw .= " -p $rule->{proto}" if $rule->{proto};
2955 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2956 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2959 $raw .= " # " . encode('utf8
', $rule->{comment})
2960 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2963 die "unknown rule type '$rule->{type
}'";
2970 my $format_options = sub {
2975 $raw .= "[OPTIONS]\n\n";
2976 foreach my $opt (keys %$options) {
2977 $raw .= "$opt: $options->{$opt}\n";
2984 my $format_aliases = sub {
2989 $raw .= "[ALIASES]\n\n";
2990 foreach my $k (keys %$aliases) {
2991 my $e = $aliases->{$k};
2992 $raw .= "$e->{name} $e->{cidr}";
2993 $raw .= " # " . encode('utf8
', $e->{comment})
2994 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
3002 my $format_ipsets = sub {
3007 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
3008 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
3009 my $utf8comment = encode('utf8
', $comment);
3010 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
3012 $raw .= "[IPSET $ipset]\n\n";
3014 my $options = $fw_conf->{ipset}->{$ipset};
3017 foreach my $entry (@$options) {
3018 $nethash->{$entry->{cidr}} = $entry;
3021 foreach my $cidr (sort keys %$nethash) {
3022 my $entry = $nethash->{$cidr};
3023 my $line = $entry->{nomatch} ? '!' : '';
3024 $line .= $entry->{cidr};
3025 $line .= " # " . encode('utf8
', $entry->{comment})
3026 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
3036 sub save_vmfw_conf {
3037 my ($vmid, $vmfw_conf) = @_;
3041 my $options = $vmfw_conf->{options};
3042 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3044 my $aliases = $vmfw_conf->{aliases};
3045 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3047 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
3049 my $rules = $vmfw_conf->{rules} || [];
3050 if ($rules && scalar(@$rules)) {
3051 $raw .= "[RULES]\n\n";
3052 $raw .= &$format_rules($rules, 1);
3056 my $filename = "$pvefw_conf_dir/$vmid.fw";
3058 mkdir $pvefw_conf_dir;
3059 PVE::Tools::file_set_contents($filename, $raw);
3065 sub remove_vmfw_conf {
3068 my $vmfw_conffile = "$pvefw_conf_dir/$vmid.fw";
3070 unlink $vmfw_conffile;
3073 sub clone_vmfw_conf {
3074 my ($vmid, $newid) = @_;
3076 my $sourcevm_conffile = "$pvefw_conf_dir/$vmid.fw";
3077 my $clonevm_conffile = "$pvefw_conf_dir/$newid.fw";
3079 if (-f $clonevm_conffile) {
3080 unlink $clonevm_conffile;
3082 if (-f $sourcevm_conffile) {
3083 my $data = PVE::Tools::file_get_contents($sourcevm_conffile);
3084 PVE::Tools::file_set_contents($clonevm_conffile, $data);
3088 sub read_vm_firewall_configs {
3089 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
3091 my $vmfw_configs = {};
3093 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3094 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
3095 next if !$vmfw_conf->{options}; # skip if file does not exists
3096 $vmfw_configs->{$vmid} = $vmfw_conf;
3098 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3099 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
3100 next if !$vmfw_conf->{options}; # skip if file does not exists
3101 $vmfw_configs->{$vmid} = $vmfw_conf;
3104 return $vmfw_configs;
3107 sub get_option_log_level {
3108 my ($options, $k) = @_;
3110 my $v = $options->{$k};
3111 $v = $default_log_level if !defined($v);
3113 return undef if $v eq '' || $v eq 'nolog
';
3115 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
3117 return $v if ($v >= 0) && ($v <= 7);
3119 warn "unknown log level ($k = '$v')\n";
3124 sub generate_std_chains {
3125 my ($ruleset, $options, $ipversion) = @_;
3127 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
3129 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
3133 if ($ipversion == 4) {
3134 # same as shorewall smurflog.
3135 $chain = 'PVEFW-smurflog
';
3136 $std_chains->{$chain} = [];
3138 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3139 push @{$std_chains->{$chain}}, "-j DROP";
3142 # same as shorewall logflags action.
3143 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
3144 $chain = 'PVEFW-logflags
';
3145 $std_chains->{$chain} = [];
3147 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
3148 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
3149 push @{$std_chains->{$chain}}, "-j DROP";
3151 foreach my $chain (keys %$std_chains) {
3152 ruleset_create_chain($ruleset, $chain);
3153 foreach my $rule (@{$std_chains->{$chain}}) {
3155 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
3157 ruleset_addrule_old($ruleset, $chain, $rule);
3163 sub generate_ipset_chains {
3164 my ($ipset_ruleset, $clusterfw_conf, $fw_conf, $device_ips, $ipsets) = @_;
3166 foreach my $ipset (keys %{$ipsets}) {
3168 my $options = $ipsets->{$ipset};
3170 if ($device_ips && $ipset =~ /^ipfilter-(net\d+)$/) {
3171 if (my $ips = $device_ips->{$1}) {
3172 $options = [@$options, @$ips];
3178 foreach my $entry (@$options) {
3179 next if $entry->{errors}; # skip entries with errors
3182 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
3183 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
3185 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
3187 #http://backreference.org/2013/03/01/ipv6-address-normalization/
3189 # ip_compress_address takes an address only, no CIDR
3190 my ($addr, $prefix_len) = ($cidr =~ m@^([^/]*)(/.*)?$@);
3191 $cidr = lc(Net::IP::ip_compress_address($addr, 6));
3192 $cidr .= $prefix_len if defined($prefix_len);
3198 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
3203 foreach my $ipversion (4, 6) {
3204 my $data = $nethash->{$ipversion};
3206 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
3208 my $hashsize = scalar(@$options);
3209 if ($hashsize <= 64) {
3212 $hashsize = round_powerof2($hashsize);
3215 my $family = $ipversion == "6" ? "inet6" : "inet";
3217 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3219 foreach my $cidr (sort keys %$data) {
3220 my $entry = $data->{$cidr};
3222 my $cmd = "add $name $cidr";
3223 if ($entry->{nomatch}) {
3224 if ($feature_ipset_nomatch) {
3225 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3227 warn "ignore !$cidr - nomatch not supported by kernel\n";
3230 push @{$ipset_ruleset->{$name}}, $cmd;
3237 sub round_powerof2 {
3241 $int |= $int >> $_ foreach (1,2,4,8,16);
3245 sub load_clusterfw_conf {
3246 my ($filename, $verbose) = @_;
3248 $filename = $clusterfw_conf_filename if !defined($filename);
3250 my $cluster_conf = {};
3251 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3252 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3255 return $cluster_conf;
3258 sub save_clusterfw_conf {
3259 my ($cluster_conf) = @_;
3263 my $options = $cluster_conf->{options};
3264 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3266 my $aliases = $cluster_conf->{aliases};
3267 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3269 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3271 my $rules = $cluster_conf->{rules};
3272 if ($rules && scalar(@$rules)) {
3273 $raw .= "[RULES]\n\n";
3274 $raw .= &$format_rules($rules, 1);
3278 if ($cluster_conf->{groups}) {
3279 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3280 my $rules = $cluster_conf->{groups}->{$group};
3281 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3282 my $utf8comment = encode('utf8
', $comment);
3283 $raw .= "[group $group] # $utf8comment\n\n";
3285 $raw .= "[group $group]\n\n";
3288 $raw .= &$format_rules($rules, 0);
3294 mkdir $pvefw_conf_dir;
3295 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3297 unlink $clusterfw_conf_filename;
3301 sub load_hostfw_conf {
3302 my ($cluster_conf, $filename, $verbose) = @_;
3304 $filename = $hostfw_conf_filename if !defined($filename);
3306 my $hostfw_conf = {};
3307 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3308 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3310 return $hostfw_conf;
3313 sub save_hostfw_conf {
3314 my ($hostfw_conf) = @_;
3318 my $options = $hostfw_conf->{options};
3319 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3321 my $rules = $hostfw_conf->{rules};
3322 if ($rules && scalar(@$rules)) {
3323 $raw .= "[RULES]\n\n";
3324 $raw .= &$format_rules($rules, 1);
3329 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3331 unlink $hostfw_conf_filename;
3336 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3340 if ($vmdata) { # test mode
3341 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3342 my $filename = "$testdir/cluster.fw";
3343 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3345 $filename = "$testdir/host.fw";
3346 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3348 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3349 } else { # normal operation
3350 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3352 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3354 $vmdata = read_local_vm_config();
3355 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3358 return ({},{},{}) if !$cluster_conf->{options}->{enable};
3361 if ($cluster_conf->{aliases}->{local_network}) {
3362 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3365 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3367 $cluster_conf->{aliases}->{local_network} = {
3368 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3371 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3373 my $ruleset = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3374 my $rulesetv6 = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3375 my $ipset_ruleset = compile_ipsets($cluster_conf, $vmfw_configs, $vmdata);
3377 return ($ruleset, $ipset_ruleset, $rulesetv6);
3380 sub compile_iptables_filter {
3381 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3385 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3386 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3388 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3390 my $hostfw_options = $hostfw_conf->{options} || {};
3392 # fixme: what log level should we use here?
3393 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3395 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3397 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3398 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3400 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+", "-j PVEFW-FWBR-IN");
3402 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3403 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+", "-j PVEFW-FWBR-OUT");
3405 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3407 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3409 if ($hostfw_enable) {
3410 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3411 warn $@ if $@; # just to be sure - should not happen
3414 # generate firewall rules for QEMU VMs
3415 foreach my $vmid (sort keys %{$vmdata->{qemu}}) {
3417 my $conf = $vmdata->{qemu}->{$vmid};
3418 my $vmfw_conf = $vmfw_configs->{$vmid};
3419 return if !$vmfw_conf;
3421 foreach my $netid (sort keys %$conf) {
3422 next if $netid !~ m/^net(\d+)$/;
3423 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3424 next if !$net->{firewall};
3425 my $iface = "tap${vmid}i$1";
3427 my $macaddr = $net->{macaddr};
3428 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3429 $vmfw_conf, $vmid, 'IN
', $ipversion);
3430 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3431 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3434 warn $@ if $@; # just to be sure - should not happen
3437 # generate firewall rules for LXC containers
3438 foreach my $vmid (sort keys %{$vmdata->{lxc}}) {
3440 my $conf = $vmdata->{lxc}->{$vmid};
3441 my $vmfw_conf = $vmfw_configs->{$vmid};
3442 return if !$vmfw_conf;
3444 if ($vmfw_conf->{options}->{enable}) {
3445 foreach my $netid (sort keys %$conf) {
3446 next if $netid !~ m/^net(\d+)$/;
3447 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3448 next if !$net->{firewall};
3449 my $iface = "veth${vmid}i$1";
3450 my $macaddr = $net->{hwaddr};
3451 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3452 $vmfw_conf, $vmid, 'IN
', $ipversion);
3453 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3454 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3458 warn $@ if $@; # just to be sure - should not happen
3461 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3462 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED", "-j PVEFW-IPS");
3468 sub mac_to_linklocal {
3470 my @parts = split(/:/, $macaddr);
3471 # The standard link local address uses the fe80::/64 prefix with the
3472 # modified EUI-64 identifier derived from the MAC address by flipping the
3473 # universal/local bit and inserting FF:FE in the middle.
3475 $parts[0] = sprintf("%02x", hex($parts[0]) ^ 0x02);
3476 my @meui64 = (@parts[0,1,2], 'ff
', 'fe
', @parts[3,4,5]);
3477 return "fe80::$parts[0]$parts[1]:$parts[2]FF:FE$parts[3]:$parts[4]$parts[5]";
3480 sub compile_ipsets {
3481 my ($cluster_conf, $vmfw_configs, $vmdata) = @_;
3484 if ($cluster_conf->{aliases}->{local_network}) {
3485 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3488 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3490 $cluster_conf->{aliases}->{local_network} = {
3491 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3494 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3497 my $ipset_ruleset = {};
3499 # generate ipsets for QEMU VMs
3500 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3502 my $conf = $vmdata->{qemu}->{$vmid};
3503 my $vmfw_conf = $vmfw_configs->{$vmid};
3504 return if !$vmfw_conf;
3506 # When the 'ipfilter
' option is enabled every device for which there
3507 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3509 # The reason is that ipfilter ipsets are always filled with standard
3510 # IPv6 link-local filters.
3511 my $ipsets = $vmfw_conf->{ipset};
3512 my $implicit_sets = {};
3514 my $device_ips = {};
3515 foreach my $netid (keys %$conf) {
3516 next if $netid !~ m/^net(\d+)$/;
3517 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3518 next if !$net->{firewall};
3520 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3521 $implicit_sets->{"ipfilter-$netid"} = [];
3524 my $macaddr = $net->{macaddr};
3525 my $linklocal = mac_to_linklocal($macaddr);
3526 $device_ips->{$netid} = [
3527 { cidr => $linklocal },
3528 { cidr => 'fe80
::/10', nomatch => 1 }
3532 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3533 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3535 warn $@ if $@; # just to be sure - should not happen
3538 # generate firewall rules for LXC containers
3539 foreach my $vmid (keys %{$vmdata->{lxc}}) {
3541 my $conf = $vmdata->{lxc}->{$vmid};
3542 my $vmfw_conf = $vmfw_configs->{$vmid};
3543 return if !$vmfw_conf;
3545 # When the 'ipfilter
' option is enabled every device for which there
3546 # is no 'ipfilter-netX
' ipset defiend gets an implicit empty default
3548 # The reason is that ipfilter ipsets are always filled with standard
3549 # IPv6 link-local filters, as well as the IP addresses configured
3550 # for the container.
3551 my $ipsets = $vmfw_conf->{ipset};
3552 my $implicit_sets = {};
3554 my $device_ips = {};
3555 foreach my $netid (keys %$conf) {
3556 next if $netid !~ m/^net(\d+)$/;
3557 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$netid});
3558 next if !$net->{firewall};
3560 if ($vmfw_conf->{options}->{ipfilter} && !$ipsets->{"ipfilter-$netid"}) {
3561 $implicit_sets->{"ipfilter-$netid"} = [];
3564 my $macaddr = $net->{hwaddr};
3565 my $linklocal = mac_to_linklocal($macaddr);
3566 my $set = $device_ips->{$netid} = [
3567 { cidr => $linklocal },
3568 { cidr => 'fe80
::/10', nomatch => 1 }
3570 if (defined($net->{ip}) && $net->{ip} =~ m!^($IPV4RE)(?:/\d+)?$!) {
3571 push @$set, { cidr => $1 };
3573 if (defined($net->{ip6}) && $net->{ip6} =~ m!^($IPV6RE)(?:/\d+)?$!) {
3574 push @$set, { cidr => $1 };
3578 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $ipsets);
3579 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf, $device_ips, $implicit_sets);
3581 warn $@ if $@; # just to be sure - should not happen
3584 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf, undef, $cluster_conf->{ipset});
3586 return $ipset_ruleset;
3589 sub get_ruleset_status {
3590 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3592 my $statushash = {};
3594 foreach my $chain (sort keys %$ruleset) {
3595 my $sig = &$digest_fn($ruleset->{$chain});
3597 $statushash->{$chain}->{sig} = $sig;
3599 my $oldsig = $active_chains->{$chain};
3600 if (!defined($oldsig)) {
3601 $statushash->{$chain}->{action} = 'create
';
3603 if ($oldsig eq $sig) {
3604 $statushash->{$chain}->{action} = 'exists';
3606 $statushash->{$chain}->{action} = 'update
';
3609 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3610 foreach my $cmd (@{$ruleset->{$chain}}) {
3611 print "\t$cmd\n" if $verbose;
3615 foreach my $chain (sort keys %$active_chains) {
3616 if (!defined($ruleset->{$chain})) {
3617 my $sig = $active_chains->{$chain};
3618 $statushash->{$chain}->{action} = 'delete';
3619 $statushash->{$chain}->{sig} = $sig;
3620 print "delete $chain ($sig)\n" if $verbose;
3627 sub print_sig_rule {
3628 my ($chain, $sig) = @_;
3630 # We just use this to store a SHA1 checksum used to detect changes
3631 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3634 sub get_ruleset_cmdlist {
3635 my ($ruleset, $verbose, $iptablescmd) = @_;
3637 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3639 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3640 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3642 # create missing chains first
3643 foreach my $chain (sort keys %$ruleset) {
3644 my $stat = $statushash->{$chain};
3645 die "internal error" if !$stat;
3646 next if $stat->{action} ne 'create
';
3648 $cmdlist .= ":$chain - [0:0]\n";
3651 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3652 my $chain = "PVEFW-$h";
3653 if ($ruleset->{$chain} && !$hooks->{$h}) {
3654 $cmdlist .= "-A $h -j $chain\n";
3658 foreach my $chain (sort keys %$ruleset) {
3659 my $stat = $statushash->{$chain};
3660 die "internal error" if !$stat;
3662 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3663 $cmdlist .= "-F $chain\n";
3664 foreach my $cmd (@{$ruleset->{$chain}}) {
3665 $cmdlist .= "$cmd\n";
3667 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3668 } elsif ($stat->{action
} eq 'delete') {
3669 die "internal error"; # this should not happen
3670 } elsif ($stat->{action
} eq 'exists') {
3673 die "internal error - unknown status '$stat->{action}'";
3677 foreach my $chain (keys %$statushash) {
3678 next if $statushash->{$chain}->{action
} ne 'delete';
3679 $cmdlist .= "-F $chain\n";
3681 foreach my $chain (keys %$statushash) {
3682 next if $statushash->{$chain}->{action
} ne 'delete';
3683 next if $chain eq 'PVEFW-INPUT';
3684 next if $chain eq 'PVEFW-OUTPUT';
3685 next if $chain eq 'PVEFW-FORWARD';
3686 $cmdlist .= "-X $chain\n";
3689 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3691 $cmdlist .= "COMMIT\n";
3693 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3696 sub get_ipset_cmdlist
{
3697 my ($ruleset, $verbose) = @_;
3701 my $delete_cmdlist = "";
3703 my $active_chains = ipset_get_chains
();
3704 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3706 # remove stale _swap chains
3707 foreach my $chain (keys %$active_chains) {
3708 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3709 $cmdlist .= "destroy $chain\n";
3713 foreach my $chain (keys %$ruleset) {
3714 my $stat = $statushash->{$chain};
3715 die "internal error" if !$stat;
3717 if ($stat->{action
} eq 'create') {
3718 foreach my $cmd (@{$ruleset->{$chain}}) {
3719 $cmdlist .= "$cmd\n";
3724 foreach my $chain (keys %$ruleset) {
3725 my $stat = $statushash->{$chain};
3726 die "internal error" if !$stat;
3728 if ($stat->{action
} eq 'update') {
3729 my $chain_swap = $chain."_swap";
3731 foreach my $cmd (@{$ruleset->{$chain}}) {
3732 $cmd =~ s/$chain/$chain_swap/;
3733 $cmdlist .= "$cmd\n";
3735 $cmdlist .= "swap $chain_swap $chain\n";
3736 $cmdlist .= "flush $chain_swap\n";
3737 $cmdlist .= "destroy $chain_swap\n";
3741 # the remove unused chains
3742 foreach my $chain (keys %$statushash) {
3743 next if $statushash->{$chain}->{action
} ne 'delete';
3745 $delete_cmdlist .= "flush $chain\n";
3746 $delete_cmdlist .= "destroy $chain\n";
3749 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3751 return ($cmdlist, $delete_cmdlist, $changes);
3755 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3757 enable_bridge_firewall
();
3759 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3760 get_ipset_cmdlist
($ipset_ruleset, $verbose);
3762 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3763 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3766 if ($ipset_changes) {
3767 print "ipset changes:\n";
3768 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3769 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3773 print "iptables changes:\n";
3778 print "ip6tables changes:\n";
3783 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3784 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3786 ipset_restore_cmdlist
($ipset_create_cmdlist);
3788 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3789 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3791 iptables_restore_cmdlist
($cmdlist);
3793 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3794 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3796 ip6tables_restore_cmdlist
($cmdlistv6);
3798 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3799 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3801 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3803 # test: re-read status and check if everything is up to date
3804 my $active_chains = iptables_get_chains
();
3805 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3808 foreach my $chain (sort keys %$ruleset) {
3809 my $stat = $statushash->{$chain};
3810 if ($stat->{action
} ne 'exists') {
3811 warn "unable to update chain '$chain'\n";
3816 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3817 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3819 foreach my $chain (sort keys %$rulesetv6) {
3820 my $stat = $statushashv6->{$chain};
3821 if ($stat->{action
} ne 'exists') {
3822 warn "unable to update chain '$chain'\n";
3827 die "unable to apply firewall changes\n" if $errors;
3829 update_nf_conntrack_max
($hostfw_conf);
3831 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3835 sub update_nf_conntrack_max
{
3836 my ($hostfw_conf) = @_;
3838 my $max = 65536; # reasonable default
3840 my $options = $hostfw_conf->{options
} || {};
3842 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3843 $max = $options->{nf_conntrack_max
};
3844 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3847 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3848 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3850 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3852 if ($current != $max) {
3853 my $hashsize = int($max/4);
3854 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3855 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3859 sub update_nf_conntrack_tcp_timeout_established
{
3860 my ($hostfw_conf) = @_;
3862 my $options = $hostfw_conf->{options
} || {};
3864 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3866 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3869 sub remove_pvefw_chains
{
3871 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3872 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3873 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3877 sub remove_pvefw_chains_iptables
{
3878 my ($iptablescmd) = @_;
3880 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3881 my $cmdlist = "*filter\n";
3883 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3885 $cmdlist .= "-D $h -j PVEFW-$h\n";
3889 foreach my $chain (keys %$chash) {
3890 $cmdlist .= "-F $chain\n";
3893 foreach my $chain (keys %$chash) {
3894 $cmdlist .= "-X $chain\n";
3896 $cmdlist .= "COMMIT\n";
3898 if($iptablescmd eq "ip6tables") {
3899 ip6tables_restore_cmdlist
($cmdlist);
3901 iptables_restore_cmdlist
($cmdlist);
3905 sub remove_pvefw_chains_ipset
{
3907 my $ipset_chains = ipset_get_chains
();
3911 foreach my $chain (keys %$ipset_chains) {
3912 $cmdlist .= "flush $chain\n";
3913 $cmdlist .= "destroy $chain\n";
3916 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3920 my $cluster_conf = load_clusterfw_conf
();
3921 my $cluster_options = $cluster_conf->{options
};
3922 my $enable = $cluster_options->{enable
};
3926 # load required modules here
3932 my $cluster_conf = load_clusterfw_conf
();
3933 my $cluster_options = $cluster_conf->{options
};
3935 if (!$cluster_options->{enable
}) {
3936 PVE
::Firewall
::remove_pvefw_chains
();
3940 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3942 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3944 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);