8 use Socket
qw(AF_INET6 inet_ntop inet_pton);
10 use PVE
::Exception
qw(raise raise_param_exc);
11 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
14 use PVE
::Tools
qw($IPV4RE $IPV6RE);
19 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
22 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
23 my $pvefw_conf_dir = "/etc/pve/firewall";
24 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
26 # dynamically include PVE::QemuServer and PVE::OpenVZ
27 # to avoid dependency problems
30 require PVE
::QemuServer
;
31 $have_qemu_server = 1;
37 $have_pve_manager = 1;
40 my $pve_fw_status_dir = "/var/lib/pve-firewall";
42 mkdir $pve_fw_status_dir; # make sure this exists
44 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
45 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
46 our $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
48 my $max_alias_name_length = 64;
49 my $max_ipset_name_length = 64;
50 my $max_group_name_length = 20;
52 PVE
::JSONSchema
::register_format
('IPorCIDR', \
&pve_verify_ip_or_cidr
);
53 sub pve_verify_ip_or_cidr
{
54 my ($cidr, $noerr) = @_;
56 if ($cidr =~ m!^(?:$IPV6RE|$IPV4RE)(/(\d+))?$!) {
57 return $cidr if Net
::IP-
>new($cidr);
58 return undef if $noerr;
59 die Net
::IP
::Error
() . "\n";
61 return undef if $noerr;
62 die "value does not look like a valid IP address or CIDR network\n";
65 PVE
::JSONSchema
::register_format
('IPorCIDRorAlias', \
&pve_verify_ip_or_cidr_or_alias
);
66 sub pve_verify_ip_or_cidr_or_alias
{
67 my ($cidr, $noerr) = @_;
69 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
71 return pve_verify_ip_or_cidr
($cidr, $noerr);
74 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
75 description
=> "IP set name.",
77 pattern
=> $ipset_name_pattern,
79 maxLength
=> $max_ipset_name_length,
82 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
83 description
=> "Alias name.",
85 pattern
=> $ip_alias_pattern,
87 maxLength
=> $max_alias_name_length,
90 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
91 description
=> "Log level.",
93 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
97 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
98 description
=> "Security Group name.",
100 pattern
=> $security_group_name_pattern,
102 maxLength
=> $max_group_name_length,
105 my $feature_ipset_nomatch = 0;
107 my (undef, undef, $release) = POSIX
::uname
();
108 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
109 my ($major, $minor) = ($1, $2);
110 $feature_ipset_nomatch = 1 if ($major > 3) ||
111 ($major == 3 && $minor >= 7);
118 my $nodename = PVE
::INotify
::nodename
();
120 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
122 my $default_log_level = 'nolog'; # avoid logs by default
124 my $log_level_hash = {
135 # we need to overwrite some macros for ipv6
136 my $pve_ipv6fw_macros = {
138 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
140 'NeighborDiscovery' => [
141 "IPv6 neighbor solicitation, neighbor and router advertisement",
142 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-solicitation' },
143 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'router-advertisement' },
144 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-solicitation' },
145 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'neighbor-advertisement' },
148 { action
=> 'PARAM', proto
=> 'udp', dport
=> '546:547', sport
=> '546:547' },
151 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
152 { action
=> 'PARAM', proto
=> 'icmpv6', dport
=> 'echo-request' },
156 # imported/converted from: /usr/share/shorewall/macro.*
157 my $pve_fw_macros = {
160 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
161 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
164 "Auth (identd) traffic",
165 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
168 "Border Gateway Protocol traffic",
169 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
172 "BitTorrent traffic for BitTorrent 3.1 and earlier",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
174 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
177 "BitTorrent traffic for BitTorrent 3.2 and later",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
179 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
182 "Concurrent Versions System pserver traffic",
183 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
186 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
187 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
188 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
189 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
192 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
193 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
194 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
197 "Distributed Checksum Clearinghouse spam filtering mechanism",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
201 "Forwarded DHCP traffic",
202 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
205 "Domain Name System traffic (upd and tcp)",
206 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
207 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
210 "Distributed Compiler service",
211 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
214 "File Transfer Protocol",
215 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
218 "Finger protocol (RFC 742)",
219 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
222 "GNUnet secure peer-to-peer networking traffic",
223 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
224 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
225 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
226 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
229 "Generic Routing Encapsulation tunneling protocol",
230 { action
=> 'PARAM', proto
=> '47' },
233 "Git distributed revision control traffic",
234 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
237 "OpenPGP HTTP keyserver protocol traffic",
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
241 "Hypertext Transfer Protocol (WWW)",
242 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
245 "Hypertext Transfer Protocol (WWW) over SSL",
246 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
249 "Internet Cache Protocol V2 (Squid) traffic",
250 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
253 "AOL Instant Messenger traffic",
254 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
257 "Internet Message Access Protocol",
258 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
261 "Internet Message Access Protocol over SSL",
262 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
265 "IPIP capsulation traffic",
266 { action
=> 'PARAM', proto
=> '94' },
270 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
271 { action
=> 'PARAM', proto
=> '50' },
274 "IPsec authentication (AH) traffic",
275 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
276 { action
=> 'PARAM', proto
=> '51' },
279 "IPsec traffic and Nat-Traversal",
280 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
281 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
282 { action
=> 'PARAM', proto
=> '50' },
285 "Internet Relay Chat traffic",
286 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
289 "HP Jetdirect printing",
290 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
293 "Layer 2 Tunneling Protocol traffic",
294 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
297 "Lightweight Directory Access Protocol traffic",
298 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
301 "Secure Lightweight Directory Access Protocol traffic",
302 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
305 "Microsoft Notification Protocol",
306 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
309 "Microsoft SQL Server",
310 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
313 "Mail traffic (SMTP, SMTPS, Submission)",
314 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
315 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
316 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
319 "Munin networked resource monitoring traffic",
320 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
324 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
327 "NNTP traffic (Usenet).",
328 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
331 "Encrypted NNTP traffic (Usenet)",
332 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
335 "Network Time Protocol (ntpd)",
336 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
339 "OSPF multicast traffic",
340 { action
=> 'PARAM', proto
=> '89' },
344 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
347 "Symantec PCAnywere (tm)",
348 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
349 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
353 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
356 "Encrypted POP3 traffic",
357 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
360 "Point-to-Point Tunneling Protocol",
361 { action
=> 'PARAM', proto
=> '47' },
362 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
366 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
370 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
373 "Line Printer protocol printing",
374 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
377 "Microsoft Remote Desktop Protocol traffic",
378 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
381 "Routing Information Protocol (bidirectional)",
382 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
385 "BIND remote management protocol",
386 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
389 "Razor Antispam System",
390 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
393 "Remote time retrieval (rdate)",
394 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
398 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
401 "SANE network scanning",
402 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
405 "Microsoft SMB traffic",
406 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
407 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
408 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
409 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
412 "Samba Web Administration Tool",
413 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
416 "Simple Mail Transfer Protocol",
417 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
420 "Encrypted Simple Mail Transfer Protocol",
421 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
424 "Simple Network Management Protocol",
425 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
426 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
429 "Spam Assassin SPAMD traffic",
430 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
433 "Secure shell traffic",
434 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
437 "Subversion server (svnserve)",
438 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
441 "SixXS IPv6 Deployment and Tunnel Broker",
442 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
443 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
444 { action
=> 'PARAM', proto
=> '41' },
445 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
448 "Squid web proxy traffic",
449 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
452 "Mail message submission traffic",
453 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
456 "Syslog protocol (RFC 5424) traffic",
457 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
458 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
461 "Trivial File Transfer Protocol traffic",
462 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
466 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
470 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
473 "RFC 868 Time protocol",
474 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
477 "Traceroute (for up to 30 hops) traffic",
478 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
479 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
482 "VNC traffic for VNC display's 0 - 99",
483 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
486 "VNC traffic from Vncservers to Vncviewers in listen mode",
487 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
490 "WWW traffic (HTTP and HTTPS)",
491 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
492 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
495 "Web Cache/Proxy traffic (port 8080)",
496 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
500 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
503 "Whois (nicname, RFC 3912) traffic",
504 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
508 my $pve_fw_parsed_macros;
509 my $pve_fw_macro_descr;
510 my $pve_fw_macro_ipversion = {};
511 my $pve_fw_preferred_macro_names = {};
513 my $pve_std_chains = {};
514 $pve_std_chains->{4} = {
515 'PVEFW-SET-ACCEPT-MARK' => [
516 "-j MARK --set-mark 1",
518 'PVEFW-DropBroadcast' => [
519 # same as shorewall 'Broadcast'
520 # simply DROP BROADCAST/MULTICAST/ANYCAST
521 # we can use this to reduce logging
522 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
523 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
524 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
525 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
528 # same as shorewall 'reject'
529 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
530 { action
=> 'DROP', source
=> '224.0.0.0/4' },
531 { action
=> 'DROP', proto
=> 'icmp' },
532 "-p tcp -j REJECT --reject-with tcp-reset",
533 "-p udp -j REJECT --reject-with icmp-port-unreachable",
534 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
535 "-j REJECT --reject-with icmp-host-prohibited",
538 # same as shorewall 'Drop', which is equal to DROP,
539 # but REJECT/DROP some packages to reduce logging,
540 # and ACCEPT critical ICMP types
541 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
542 # we are not interested in BROADCAST/MULTICAST/ANYCAST
543 { action
=> 'PVEFW-DropBroadcast' },
544 # ACCEPT critical ICMP types
545 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
546 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
547 # Drop packets with INVALID state
548 "-m conntrack --ctstate INVALID -j DROP",
549 # Drop Microsoft SMB noise
550 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
551 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
552 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
553 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
554 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
555 # Drop new/NotSyn traffic so that it doesn't get logged
556 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
558 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
561 # same as shorewall 'Reject', which is equal to Reject,
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
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
574 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
575 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
576 { action
=> 'PVEFW-reject', 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 },
583 'PVEFW-tcpflags' => [
584 # same as shorewall tcpflags action.
585 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
586 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
587 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
588 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
589 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
590 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
593 # same as shorewall smurfs action
594 # Filter packets for smurfs (packets with a broadcast address as the source).
595 "-s 0.0.0.0/32 -j RETURN",
596 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
597 "-s 224.0.0.0/4 -g PVEFW-smurflog",
601 $pve_std_chains->{6} = {
602 'PVEFW-SET-ACCEPT-MARK' => [
603 "-j MARK --set-mark 1",
605 'PVEFW-DropBroadcast' => [
606 # same as shorewall 'Broadcast'
607 # simply DROP BROADCAST/MULTICAST/ANYCAST
608 # we can use this to reduce logging
609 #{ action => 'DROP', dsttype => 'BROADCAST' }, #no broadcast in ipv6
610 # ipv6 addrtype does not work with kernel 2.6.32
611 #{ action => 'DROP', dsttype => 'MULTICAST' },
612 #{ action => 'DROP', dsttype => 'ANYCAST' },
613 { action
=> 'DROP', dest
=> 'ff00::/8' },
614 #{ action => 'DROP', dest => '224.0.0.0/4' },
617 # same as shorewall 'reject'
618 #{ action => 'DROP', dsttype => 'BROADCAST' },
619 #{ action => 'DROP', source => '224.0.0.0/4' },
620 { action
=> 'DROP', proto
=> 'icmpv6' },
621 "-p tcp -j REJECT --reject-with tcp-reset",
622 #"-p udp -j REJECT --reject-with icmp-port-unreachable",
623 #"-p icmp -j REJECT --reject-with icmp-host-unreachable",
624 #"-j REJECT --reject-with icmp-host-prohibited",
627 # same as shorewall 'Drop', which is equal to DROP,
628 # but REJECT/DROP some packages to reduce logging,
629 # and ACCEPT critical ICMP types
630 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
631 # we are not interested in BROADCAST/MULTICAST/ANYCAST
632 { action
=> 'PVEFW-DropBroadcast' },
633 # ACCEPT critical ICMP types
634 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
635 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
636 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
638 # Drop packets with INVALID state
639 "-m conntrack --ctstate INVALID -j DROP",
640 # Drop Microsoft SMB noise
641 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
642 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
643 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
644 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
645 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
646 # Drop new/NotSyn traffic so that it doesn't get logged
647 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
649 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
652 # same as shorewall 'Reject', which is equal to Reject,
653 # but REJECT/DROP some packages to reduce logging,
654 # and ACCEPT critical ICMP types
655 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
656 # we are not interested in BROADCAST/MULTICAST/ANYCAST
657 { action
=> 'PVEFW-DropBroadcast' },
658 # ACCEPT critical ICMP types
659 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'destination-unreachable' },
660 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'time-exceeded' },
661 { action
=> 'ACCEPT', proto
=> 'icmpv6', dport
=> 'packet-too-big' },
663 # Drop packets with INVALID state
664 "-m conntrack --ctstate INVALID -j DROP",
665 # Drop Microsoft SMB noise
666 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
667 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
668 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
669 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
670 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
671 # Drop new/NotSyn traffic so that it doesn't get logged
672 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
674 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
676 'PVEFW-tcpflags' => [
677 # same as shorewall tcpflags action.
678 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
679 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
680 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
681 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
682 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
683 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
687 # iptables -p icmp -h
688 my $icmp_type_names = {
691 'destination-unreachable' => 1,
692 'network-unreachable' => 1,
693 'host-unreachable' => 1,
694 'protocol-unreachable' => 1,
695 'port-unreachable' => 1,
696 'fragmentation-needed' => 1,
697 'source-route-failed' => 1,
698 'network-unknown' => 1,
700 'network-prohibited' => 1,
701 'host-prohibited' => 1,
702 'TOS-network-unreachable' => 1,
703 'TOS-host-unreachable' => 1,
704 'communication-prohibited' => 1,
705 'host-precedence-violation' => 1,
706 'precedence-cutoff' => 1,
707 'source-quench' => 1,
709 'network-redirect' => 1,
710 'host-redirect' => 1,
711 'TOS-network-redirect' => 1,
712 'TOS-host-redirect' => 1,
714 'router-advertisement' => 1,
715 'router-solicitation' => 1,
716 'time-exceeded' => 1,
717 'ttl-zero-during-transit' => 1,
718 'ttl-zero-during-reassembly' => 1,
719 'parameter-problem' => 1,
720 'ip-header-bad' => 1,
721 'required-option-missing' => 1,
722 'timestamp-request' => 1,
723 'timestamp-reply' => 1,
724 'address-mask-request' => 1,
725 'address-mask-reply' => 1,
728 # ip6tables -p icmpv6 -h
730 my $icmpv6_type_names = {
732 'destination-unreachable' => 1,
734 'communication-prohibited' => 1,
735 'address-unreachable' => 1,
736 'port-unreachable' => 1,
737 'packet-too-big' => 1,
738 'time-exceeded' => 1,
739 'ttl-zero-during-transit' => 1,
740 'ttl-zero-during-reassembly' => 1,
741 'parameter-problem' => 1,
743 'unknown-header-type' => 1,
744 'unknown-option' => 1,
747 'router-solicitation' => 1,
748 'router-advertisement' => 1,
749 'neighbor-solicitation' => 1,
750 'neighbour-solicitation' => 1,
751 'neighbor-advertisement' => 1,
752 'neighbour-advertisement' => 1,
756 sub init_firewall_macros
{
758 $pve_fw_parsed_macros = {};
761 my ($k, $macro) = @_;
762 my $lc_name = lc($k);
763 $pve_fw_macro_ipversion->{$k} = 0;
764 while (!ref($macro->[0])) {
765 my $desc = shift @$macro;
766 if ($desc eq 'ipv4only') {
767 $pve_fw_macro_ipversion->{$k} = 4;
768 } elsif ($desc eq 'ipv6only') {
769 $pve_fw_macro_ipversion->{$k} = 6;
771 $pve_fw_macro_descr->{$k} = $desc;
774 $pve_fw_preferred_macro_names->{$lc_name} = $k;
775 $pve_fw_parsed_macros->{$k} = $macro;
778 foreach my $k (keys %$pve_fw_macros) {
779 &$parse($k, $pve_fw_macros->{$k});
782 foreach my $k (keys %$pve_ipv6fw_macros) {
783 next if $pve_fw_parsed_macros->{$k};
784 &$parse($k, $pve_ipv6fw_macros->{$k});
785 $pve_fw_macro_ipversion->{$k} = 6;
789 init_firewall_macros
();
792 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
797 sub get_etc_services
{
799 return $etc_services if $etc_services;
801 my $filename = "/etc/services";
803 my $fh = IO
::File-
>new($filename, O_RDONLY
);
805 warn "unable to read '$filename' - $!\n";
811 while (my $line = <$fh>) {
813 next if $line =~m/^#/;
814 next if ($line =~m/^\s*$/);
816 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
817 $services->{byid
}->{$2}->{name
} = $1;
818 $services->{byid
}->{$2}->{port
} = $2;
819 $services->{byid
}->{$2}->{$3} = 1;
820 $services->{byname
}->{$1} = $services->{byid
}->{$2};
826 $etc_services = $services;
829 return $etc_services;
834 sub get_etc_protocols
{
835 return $etc_protocols if $etc_protocols;
837 my $filename = "/etc/protocols";
839 my $fh = IO
::File-
>new($filename, O_RDONLY
);
841 warn "unable to read '$filename' - $!\n";
847 while (my $line = <$fh>) {
849 next if $line =~m/^#/;
850 next if ($line =~m/^\s*$/);
852 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
853 $protocols->{byid
}->{$2}->{name
} = $1;
854 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
860 # add special case for ICMP v6
861 $protocols->{byid
}->{icmpv6
}->{name
} = "icmpv6";
862 $protocols->{byname
}->{icmpv6
} = $protocols->{byid
}->{icmpv6
};
864 $etc_protocols = $protocols;
866 return $etc_protocols;
869 my $ipv4_mask_hash_localnet = {
871 '255.255.128.0' => 17,
872 '255.255.192.0' => 18,
873 '255.255.224.0' => 19,
874 '255.255.240.0' => 20,
875 '255.255.248.0' => 21,
876 '255.255.252.0' => 22,
877 '255.255.254.0' => 23,
878 '255.255.255.0' => 24,
879 '255.255.255.128' => 25,
880 '255.255.255.192' => 26,
881 '255.255.255.224' => 27,
882 '255.255.255.240' => 28,
883 '255.255.255.248' => 29,
884 '255.255.255.252' => 30,
890 my ($new_value) = @_;
892 $__local_network = $new_value if defined($new_value);
894 return $__local_network if defined($__local_network);
897 my $nodename = PVE
::INotify
::nodename
();
899 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
901 my $testip = Net
::IP-
>new($ip);
903 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
904 foreach my $entry (@$routes) {
905 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
906 next if !defined($mask);
907 return if $mask eq '0.0.0.0';
908 my $cidr = "$entry->{dest}/$mask";
909 my $testnet = Net
::IP-
>new($cidr);
910 if ($testnet->overlaps($testip)) {
911 $__local_network = $cidr;
918 return $__local_network;
921 # ipset names are limited to 31 characters,
922 # and we use '-v4' or '-v6' to indicate IP versions,
923 # and we use '_swap' suffix for atomic update,
924 # for example PVEFW-${VMID}-${ipset_name}_swap
926 my $max_iptables_ipset_name_length = 31 - length("PVEFW-") - length("_swap");
928 sub compute_ipset_chain_name
{
929 my ($vmid, $ipset_name, $ipversion) = @_;
931 $vmid = 0 if !defined($vmid);
933 my $id = "$vmid-${ipset_name}-v$ipversion";
935 if (length($id) > $max_iptables_ipset_name_length) {
936 $id = PVE
::Tools
::fnv31a_hex
($id);
942 sub compute_ipfilter_ipset_name
{
945 return "ipfilter-$iface";
948 sub parse_address_list
{
951 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
952 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
956 if ($str =~ m/^${ip_alias_pattern}$/) {
957 die "alias name too long\n" if length($str) > $max_alias_name_length;
965 foreach my $elem (split(/,/, $str)) {
967 my $ip = Net
::IP-
>new($elem);
969 my $err = Net
::IP
::Error
();
970 die "invalid IP address: $err\n";
972 $iprange = 1 if $elem =~ m/-/;
974 my $new_ipversion = Net
::IP
::ip_is_ipv6
($ip->ip()) ?
6 : 4;
976 die "detected mixed ipv4/ipv6 addresses in address list '$str'\n"
977 if $ipversion && ($new_ipversion != $ipversion);
979 $ipversion = $new_ipversion;
982 die "you can't use a range in a list\n" if $iprange && $count > 1;
987 sub parse_port_name_number_or_range
{
988 my ($str, $dport) = @_;
990 my $services = PVE
::Firewall
::get_etc_services
();
994 foreach my $item (split(/,/, $str)) {
996 if ($item =~ m/^(\d+):(\d+)$/) {
997 my ($port1, $port2) = ($1, $2);
998 die "invalid port '$port1'\n" if $port1 > 65535;
999 die "invalid port '$port2'\n" if $port2 > 65535;
1000 } elsif ($item =~ m/^(\d+)$/) {
1002 die "invalid port '$port'\n" if $port > 65535;
1004 if ($dport && $icmp_type_names->{$item}) {
1006 } elsif ($dport && $icmpv6_type_names->{$item}) {
1009 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
1014 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
1019 PVE
::JSONSchema
::register_format
('pve-fw-sport-spec', \
&pve_fw_verify_sport_spec
);
1020 sub pve_fw_verify_sport_spec
{
1023 parse_port_name_number_or_range
($portstr, 0);
1028 PVE
::JSONSchema
::register_format
('pve-fw-dport-spec', \
&pve_fw_verify_dport_spec
);
1029 sub pve_fw_verify_dport_spec
{
1032 parse_port_name_number_or_range
($portstr, 1);
1037 PVE
::JSONSchema
::register_format
('pve-fw-addr-spec', \
&pve_fw_verify_addr_spec
);
1038 sub pve_fw_verify_addr_spec
{
1041 parse_address_list
($list);
1046 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
1047 sub pve_fw_verify_protocol_spec
{
1050 my $protocols = get_etc_protocols
();
1052 die "unknown protocol '$proto'\n" if $proto &&
1053 !(defined($protocols->{byname
}->{$proto}) ||
1054 defined($protocols->{byid
}->{$proto}));
1060 # helper function for API
1062 sub copy_opject_with_digest
{
1065 my $sha = Digest
::SHA-
>new('sha1');
1068 foreach my $k (sort keys %$object) {
1069 my $v = $object->{$k};
1070 next if !defined($v);
1072 $sha->add($k, ':', $v, "\n");
1075 my $digest = $sha->hexdigest;
1077 $res->{digest
} = $digest;
1079 return wantarray ?
($res, $digest) : $res;
1082 sub copy_list_with_digest
{
1085 my $sha = Digest
::SHA-
>new('sha1');
1088 foreach my $entry (@$list) {
1090 foreach my $k (sort keys %$entry) {
1091 my $v = $entry->{$k};
1092 next if !defined($v);
1094 # Note: digest ignores refs ($rule->{errors})
1095 # since Digest::SHA expects a series of bytes,
1096 # we have to encode the value here to prevent errors when
1097 # using utf8 characters (eg. in comments)
1098 $sha->add($k, ':', encode_utf8
($v), "\n") if !ref($v); ;
1103 my $digest = $sha->hexdigest;
1105 foreach my $entry (@$res) {
1106 $entry->{digest
} = $digest;
1109 return wantarray ?
($res, $digest) : $res;
1112 my $rule_properties = {
1114 description
=> "Update rule at position <pos>.",
1119 digest
=> get_standard_option
('pve-config-digest'),
1123 enum
=> ['in', 'out', 'group'],
1126 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
1129 pattern
=> $security_group_name_pattern,
1138 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
1140 type
=> 'string', format
=> 'pve-fw-addr-spec',
1144 type
=> 'string', format
=> 'pve-fw-addr-spec',
1148 type
=> 'string', format
=> 'pve-fw-protocol-spec',
1156 type
=> 'string', format
=> 'pve-fw-sport-spec',
1160 type
=> 'string', format
=> 'pve-fw-dport-spec',
1169 sub add_rule_properties
{
1170 my ($properties) = @_;
1172 foreach my $k (keys %$rule_properties) {
1173 my $h = $rule_properties->{$k};
1174 # copy data, so that we can modify later without side effects
1175 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
1181 sub delete_rule_properties
{
1182 my ($rule, $delete_str) = @_;
1184 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
1185 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
1186 if !defined($rule_properties->{$opt});
1187 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
1188 if $opt eq 'type' || $opt eq 'action';
1189 delete $rule->{$opt};
1195 my $apply_macro = sub {
1196 my ($macro_name, $param, $verify, $ipversion) = @_;
1198 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1199 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1201 if ($ipversion && ($ipversion == 6) && $pve_ipv6fw_macros->{$macro_name}) {
1202 $macro_rules = $pve_ipv6fw_macros->{$macro_name};
1205 # skip macros which are specific to another ipversion
1206 if ($ipversion && (my $required = $pve_fw_macro_ipversion->{$macro_name})) {
1207 return if $ipversion != $required;
1212 foreach my $templ (@$macro_rules) {
1214 my $param_used = {};
1215 foreach my $k (keys %$templ) {
1216 my $v = $templ->{$k};
1217 if ($v eq 'PARAM') {
1219 $param_used->{$k} = 1;
1220 } elsif ($v eq 'DEST') {
1221 $v = $param->{dest
};
1222 $param_used->{dest
} = 1;
1223 } elsif ($v eq 'SOURCE') {
1224 $v = $param->{source
};
1225 $param_used->{source
} = 1;
1229 my $msg = "missing parameter '$k' in macro '$macro_name'";
1230 raise_param_exc
({ macro => $msg }) if $verify;
1235 foreach my $k (keys %$param) {
1236 next if $k eq 'macro';
1237 next if !defined($param->{$k});
1238 next if $param_used->{$k};
1239 if (defined($rule->{$k})) {
1240 if ($rule->{$k} ne $param->{$k}) {
1241 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1242 raise_param_exc
({ $k => $msg }) if $verify;
1246 $rule->{$k} = $param->{$k};
1249 push @$rules, $rule;
1255 my $rule_env_iface_lookup = {
1264 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1266 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1268 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1269 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1271 my $errors = $rule->{errors
} || {};
1273 my $error_count = 0;
1275 my $add_error = sub {
1276 my ($param, $msg) = @_;
1278 raise_param_exc
({ $param => $msg }) if !$noerr;
1280 $errors->{$param} = $msg if !$errors->{$param};
1284 my $set_ip_version = sub {
1287 die "detected mixed ipv4/ipv6 adresses in rule\n"
1288 if $ipversion && ($vers != $ipversion);
1293 my $check_ipset_or_alias_property = sub {
1294 my ($name, $expected_ipversion) = @_;
1296 if (my $value = $rule->{$name}) {
1297 if ($value =~ m/^\+/) {
1298 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1299 &$add_error($name, "no such ipset '$1'")
1300 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1303 &$add_error($name, "invalid ipset name '$value'");
1305 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1306 my $alias = lc($value);
1307 &$add_error($name, "no such alias '$value'")
1308 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}));
1309 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1310 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1312 &$set_ip_version($e->{ipversion
});
1317 my $type = $rule->{type
};
1318 my $action = $rule->{action
};
1320 &$add_error('type', "missing property") if !$type;
1321 &$add_error('action', "missing property") if !$action;
1324 if ($type eq 'in' || $type eq 'out') {
1325 &$add_error('action', "unknown action '$action'")
1326 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1327 } elsif ($type eq 'group') {
1328 &$add_error('type', "security groups not allowed")
1330 &$add_error('action', "invalid characters in security group name")
1331 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1333 &$add_error('type', "unknown rule type '$type'");
1337 if ($rule->{iface
}) {
1338 &$add_error('type', "parameter -i not allowed for this rule type")
1340 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1341 &$add_error('iface', $@) if $@;
1342 if ($rule_env eq 'vm') {
1343 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1344 if $rule->{iface
} !~ m/^net(\d+)$/;
1345 } elsif ($rule_env eq 'ct') {
1346 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1347 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1351 if ($rule->{macro}) {
1352 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1353 $rule->{macro} = $preferred_name;
1355 &$add_error('macro', "unknown macro '$rule->{macro}'");
1359 if ($rule->{proto
}) {
1360 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1361 &$add_error('proto', $@) if $@;
1362 &$set_ip_version(4) if $rule->{proto
} eq 'icmp';
1363 &$set_ip_version(6) if $rule->{proto
} eq 'icmpv6';
1366 if ($rule->{dport
}) {
1367 eval { parse_port_name_number_or_range
($rule->{dport
}, 1); };
1368 &$add_error('dport', $@) if $@;
1369 &$add_error('proto', "missing property - 'dport' requires this property")
1373 if ($rule->{sport
}) {
1374 eval { parse_port_name_number_or_range
($rule->{sport
}, 0); };
1375 &$add_error('sport', $@) if $@;
1376 &$add_error('proto', "missing property - 'sport' requires this property")
1380 if ($rule->{source
}) {
1382 my $source_ipversion = parse_address_list
($rule->{source
});
1383 &$set_ip_version($source_ipversion);
1385 &$add_error('source', $@) if $@;
1386 &$check_ipset_or_alias_property('source', $ipversion);
1389 if ($rule->{dest
}) {
1391 my $dest_ipversion = parse_address_list
($rule->{dest
});
1392 &$set_ip_version($dest_ipversion);
1394 &$add_error('dest', $@) if $@;
1395 &$check_ipset_or_alias_property('dest', $ipversion);
1398 $rule->{ipversion
} = $ipversion if $ipversion;
1400 if ($rule->{macro} && !$error_count) {
1401 eval { &$apply_macro($rule->{macro}, $rule, 1, $ipversion); };
1403 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1404 my $eh = $err->{errors
};
1405 foreach my $p (keys %$eh) {
1406 &$add_error($p, $eh->{$p});
1409 &$add_error('macro', "$err");
1414 $rule->{errors
} = $errors if $error_count;
1419 sub copy_rule_data
{
1420 my ($rule, $param) = @_;
1422 foreach my $k (keys %$rule_properties) {
1423 if (defined(my $v = $param->{$k})) {
1424 if ($v eq '' || $v eq '-') {
1435 sub rules_modify_permissions
{
1436 my ($rule_env) = @_;
1438 if ($rule_env eq 'host') {
1440 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1442 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1444 check
=> ['perm', '/', [ 'Sys.Modify' ]],
1446 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1448 check
=> ['perm', '/vms/{vmid}', [ 'VM.Config.Network' ]],
1455 sub rules_audit_permissions
{
1456 my ($rule_env) = @_;
1458 if ($rule_env eq 'host') {
1460 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1462 } elsif ($rule_env eq 'cluster' || $rule_env eq 'group') {
1464 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1466 } elsif ($rule_env eq 'vm' || $rule_env eq 'ct') {
1468 check
=> ['perm', '/vms/{vmid}', [ 'VM.Audit' ]],
1476 my $bridge_firewall_enabled = 0;
1478 sub enable_bridge_firewall
{
1480 return if $bridge_firewall_enabled; # only once
1482 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1483 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1485 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1486 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1488 $bridge_firewall_enabled = 1;
1491 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1493 sub iptables_restore_cmdlist
{
1496 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1499 sub ip6tables_restore_cmdlist
{
1502 run_command
("/sbin/ip6tables-restore -n", input
=> $cmdlist, errmsg
=> "iptables_restore_cmdlist");
1505 sub ipset_restore_cmdlist
{
1508 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist, errmsg
=> "ipset_restore_cmdlist");
1511 sub iptables_get_chains
{
1512 my ($iptablescmd) = @_;
1514 $iptablescmd = "iptables" if !$iptablescmd;
1518 # check what chains we want to track
1519 my $is_pvefw_chain = sub {
1522 return 1 if $name =~ m/^PVEFW-\S+$/;
1524 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1526 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1528 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1530 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1531 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1543 return if $line =~ m/^#/;
1544 return if $line =~ m/^\s*$/;
1546 if ($line =~ m/^\*(\S+)$/) {
1551 return if $table ne 'filter';
1553 if ($line =~ m/^:(\S+)\s/) {
1555 return if !&$is_pvefw_chain($chain);
1556 $res->{$chain} = "unknown";
1557 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1558 my ($chain, $sig) = ($1, $2);
1559 return if !&$is_pvefw_chain($chain);
1560 $res->{$chain} = $sig;
1561 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1564 # simply ignore the rest
1569 run_command
("/sbin/$iptablescmd-save", outfunc
=> $parser);
1571 return wantarray ?
($res, $hooks) : $res;
1574 sub iptables_chain_digest
{
1576 my $digest = Digest
::SHA-
>new('sha1');
1577 foreach my $rule (@$rules) { # order is important
1578 $digest->add($rule);
1580 return $digest->b64digest;
1583 sub ipset_chain_digest
{
1586 my $digest = Digest
::SHA-
>new('sha1');
1587 foreach my $rule (sort @$rules) { # note: sorted
1588 $digest->add($rule);
1590 return $digest->b64digest;
1593 sub ipset_get_chains
{
1601 return if $line =~ m/^#/;
1602 return if $line =~ m/^\s*$/;
1603 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1605 $line =~ s/\s+$//; # delete trailing white space
1606 push @{$chains->{$chain}}, $line;
1608 # simply ignore the rest
1613 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1615 # compute digest for each chain
1616 foreach my $chain (keys %$chains) {
1617 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1623 sub ruleset_generate_cmdstr
{
1624 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1626 return if defined($rule->{enable
}) && !$rule->{enable
};
1627 return if $rule->{errors
};
1629 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1631 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}, 1) : 0;
1632 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}, 0) : 0;
1636 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1637 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1639 my $source = $rule->{source
};
1640 my $dest = $rule->{dest
};
1643 if ($source =~ m/^\+/) {
1644 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1646 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1647 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1648 push @cmd, "-m set --match-set ${ipset_chain} src";
1649 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1650 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1651 push @cmd, "-m set --match-set ${ipset_chain} src";
1653 die "no such ipset '$name'\n";
1656 die "invalid security group name '$source'\n";
1658 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1659 my $alias = lc($source);
1660 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1661 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1662 die "no such alias '$source'\n" if !$e;
1663 push @cmd, "-s $e->{cidr}";
1664 } elsif ($source =~ m/\-/){
1665 push @cmd, "-m iprange --src-range $source";
1667 push @cmd, "-s $source";
1672 if ($dest =~ m/^\+/) {
1673 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1675 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1676 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name, $ipversion);
1677 push @cmd, "-m set --match-set ${ipset_chain} dst";
1678 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1679 my $ipset_chain = compute_ipset_chain_name
(0, $name, $ipversion);
1680 push @cmd, "-m set --match-set ${ipset_chain} dst";
1682 die "no such ipset '$name'\n";
1685 die "invalid security group name '$dest'\n";
1687 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1688 my $alias = lc($dest);
1689 my $e = $fw_conf ?
$fw_conf->{aliases
}->{$alias} : undef;
1690 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1691 die "no such alias '$dest'\n" if !$e;
1692 push @cmd, "-d $e->{cidr}";
1693 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1694 push @cmd, "-m iprange --dst-range $dest";
1696 push @cmd, "-d $dest";
1700 if ($rule->{proto
}) {
1701 push @cmd, "-p $rule->{proto}";
1704 $multiport++ if $nbdport > 1;
1705 $multiport++ if $nbsport > 1;
1707 push @cmd, "--match multiport" if $multiport;
1709 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1710 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1712 if ($rule->{dport
}) {
1713 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1714 # Note: we use dport to store --icmp-type
1715 die "unknown icmp-type '$rule->{dport}'\n"
1716 if $rule->{dport
} !~ /^\d+$/ && !defined($icmp_type_names->{$rule->{dport
}});
1717 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1718 } elsif ($rule->{proto
} && $rule->{proto
} eq 'icmpv6') {
1719 # Note: we use dport to store --icmpv6-type
1720 die "unknown icmpv6-type '$rule->{dport}'\n"
1721 if $rule->{dport
} !~ /^\d+$/ && !defined($icmpv6_type_names->{$rule->{dport
}});
1722 push @cmd, "-m icmpv6 --icmpv6-type $rule->{dport}";
1725 if ($multiport == 2) {
1726 push @cmd, "--ports $rule->{dport}";
1728 push @cmd, "--dports $rule->{dport}";
1731 push @cmd, "--dport $rule->{dport}";
1736 if ($rule->{sport
}) {
1738 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1740 push @cmd, "--sport $rule->{sport}";
1743 } elsif ($rule->{dport
} || $rule->{sport
}) {
1744 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1745 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1748 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1750 if (my $action = $rule->{action
}) {
1751 $action = $actions->{$action} if defined($actions->{$action});
1752 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1753 push @cmd, $goto ?
"-g $action" : "-j $action";
1756 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1759 sub ruleset_generate_rule
{
1760 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1764 if ($rule->{macro}) {
1765 $rules = &$apply_macro($rule->{macro}, $rule, 0, $ipversion);
1770 # update all or nothing
1773 foreach my $tmp (@$rules) {
1774 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1775 push @cmds, $cmdstr;
1779 foreach my $cmdstr (@cmds) {
1780 ruleset_addrule
($ruleset, $chain, $cmdstr);
1784 sub ruleset_generate_rule_insert
{
1785 my ($ruleset, $chain, $ipversion, $rule, $actions, $goto) = @_;
1787 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1789 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $ipversion, $rule, $actions, $goto)) {
1790 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1794 sub ruleset_create_chain
{
1795 my ($ruleset, $chain) = @_;
1797 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1798 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1800 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1802 $ruleset->{$chain} = [];
1805 sub ruleset_chain_exist
{
1806 my ($ruleset, $chain) = @_;
1808 return $ruleset->{$chain} ?
1 : undef;
1811 sub ruleset_addrule
{
1812 my ($ruleset, $chain, $rule) = @_;
1814 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1816 push @{$ruleset->{$chain}}, "-A $chain $rule";
1819 sub ruleset_insertrule
{
1820 my ($ruleset, $chain, $rule) = @_;
1822 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1824 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1827 sub get_log_rule_base
{
1828 my ($chain, $vmid, $msg, $loglevel) = @_;
1830 die "internal error - no log level" if !defined($loglevel);
1832 $vmid = 0 if !defined($vmid);
1834 # Note: we use special format for prefix to pass further
1835 # info to log daemon (VMID, LOGVELEL and CHAIN)
1837 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1840 sub ruleset_addlog {
1841 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1843 return if !defined($loglevel);
1845 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1847 $logrule = "$rule $logrule" if defined($rule);
1849 ruleset_addrule($ruleset, $chain, $logrule);
1852 sub ruleset_add_chain_policy {
1853 my ($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action) = @_;
1855 if ($policy eq 'ACCEPT') {
1857 ruleset_generate_rule($ruleset, $chain, $ipversion, { action => 'ACCEPT' },
1858 { ACCEPT => $accept_action});
1860 } elsif ($policy eq 'DROP') {
1862 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1864 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1866 ruleset_addrule($ruleset, $chain, "-j DROP
");
1867 } elsif ($policy eq 'REJECT') {
1868 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1870 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1872 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1875 die "internal error
: unknown policy
'$policy'";
1879 sub ruleset_chain_add_ndp {
1880 my ($ruleset, $chain, $ipversion, $options) = @_;
1881 return if $ipversion != 6 || (defined($options->{ndp}) && !$options->{ndp});
1883 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-solicitation
-j ACCEPT
");
1884 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type router-advertisement
-j ACCEPT
");
1885 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-solicitation
-j ACCEPT
");
1886 ruleset_addrule($ruleset, $chain, "-p icmpv6
--icmpv6-type neighbor-advertisement
-j ACCEPT
");
1889 sub ruleset_chain_add_conn_filters {
1890 my ($ruleset, $chain, $accept) = @_;
1892 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1893 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1896 sub ruleset_chain_add_input_filters {
1897 my ($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel) = @_;
1899 if ($cluster_conf->{ipset}->{blacklist}){
1900 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1901 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1902 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1903 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1905 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist', $ipversion);
1906 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1909 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1910 if ($ipversion == 4) {
1911 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1915 if ($options->{tcpflags}) {
1916 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1920 sub ruleset_create_vm_chain {
1921 my ($ruleset, $chain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction) = @_;
1923 ruleset_create_chain($ruleset, $chain);
1924 my $accept = generate_nfqueue($options);
1926 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1927 if ($direction eq 'OUT') {
1928 ruleset_generate_rule($ruleset, $chain, $ipversion,
1929 { action => 'PVEFW-SET-ACCEPT-MARK',
1930 proto => 'udp', sport => 68, dport => 67 });
1932 ruleset_generate_rule($ruleset, $chain, $ipversion,
1933 { action => 'ACCEPT',
1934 proto => 'udp', sport => 67, dport => 68 });
1938 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options);
1940 if ($direction eq 'OUT') {
1941 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1942 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1944 if ($ipfilter_ipset) {
1945 ruleset_addrule($ruleset, $chain, "-m set
! --match-set
$ipfilter_ipset src
-j DROP
");
1947 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1951 sub ruleset_add_group_rule {
1952 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action, $ipversion) = @_;
1954 my $group = $rule->{action};
1955 my $group_chain = "GROUP-
$group-$direction";
1956 if(!ruleset_chain_exist($ruleset, $group_chain)){
1957 generate_group_rules($ruleset, $cluster_conf, $group, $ipversion);
1960 if ($direction eq 'OUT' && $rule->{iface_out}) {
1961 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1962 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1963 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1965 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1968 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1971 sub ruleset_generate_vm_rules {
1972 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options, $ipversion) = @_;
1974 my $lc_direction = lc($direction);
1976 my $in_accept = generate_nfqueue($options);
1978 foreach my $rule (@$rules) {
1979 next if $rule->{iface} && $rule->{iface} ne $netid;
1980 next if !$rule->{enable} || $rule->{errors};
1981 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
1983 if ($rule->{type} eq 'group') {
1984 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1985 $direction eq 'OUT' ? 'RETURN' : $in_accept, $ipversion);
1987 next if $rule->{type} ne $lc_direction;
1989 if ($direction eq 'OUT') {
1990 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
1991 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1992 undef, $cluster_conf, $vmfw_conf);
1994 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
1995 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1996 undef, $cluster_conf, $vmfw_conf);
2004 sub generate_nfqueue {
2007 if ($options->{ips}) {
2008 my $action = "NFQUEUE
";
2009 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
2010 if (defined($3) && defined($1)) {
2011 $action .= " --queue-balance
$1:$3";
2012 } elsif (defined($1)) {
2013 $action .= " --queue-num
$1";
2016 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
2023 sub ruleset_generate_vm_ipsrules {
2024 my ($ruleset, $options, $direction, $iface) = @_;
2026 if ($options->{ips} && $direction eq 'IN') {
2027 my $nfqueue = generate_nfqueue($options);
2029 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
2030 ruleset_create_chain($ruleset, "PVEFW-IPS
");
2033 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
2037 sub generate_venet_rules_direction {
2038 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction, $ipversion) = @_;
2040 my $lc_direction = lc($direction);
2042 my $rules = $vmfw_conf->{rules};
2044 my $options = $vmfw_conf->{options};
2045 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2047 my $chain = "venet0-
$vmid-$direction";
2049 ruleset_create_vm_chain($ruleset, $chain, $ipversion, $options, undef, undef, $direction);
2051 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction, undef, $ipversion);
2056 if ($direction eq 'OUT') {
2057 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2059 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2062 my $accept = generate_nfqueue($options);
2063 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2064 ruleset_add_chain_policy($ruleset, $chain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2066 if ($direction eq 'OUT') {
2067 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", $ipversion, {
2070 iface_in => 'venet0'});
2072 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", $ipversion, {
2075 iface_out => 'venet0'});
2079 sub generate_tap_rules_direction {
2080 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction, $ipversion) = @_;
2082 my $lc_direction = lc($direction);
2084 my $rules = $vmfw_conf->{rules};
2086 my $options = $vmfw_conf->{options};
2087 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
2089 my $tapchain = "$iface-$direction";
2091 my $ipfilter_name = compute_ipfilter_ipset_name($netid);
2092 my $ipfilter_ipset = compute_ipset_chain_name($vmid, $ipfilter_name, $ipversion)
2093 if $vmfw_conf->{ipset}->{$ipfilter_name};
2095 # create chain with mac and ip filter
2096 ruleset_create_vm_chain($ruleset, $tapchain, $ipversion, $options, $macaddr, $ipfilter_ipset, $direction);
2098 if ($options->{enable}) {
2099 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options, $ipversion);
2101 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
2106 if ($direction eq 'OUT') {
2107 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
2109 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
2112 my $accept = generate_nfqueue($options);
2113 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
2114 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, $policy, $loglevel, $accept_action);
2116 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : 'ACCEPT';
2117 ruleset_add_chain_policy($ruleset, $tapchain, $ipversion, $vmid, 'ACCEPT', $loglevel, $accept_action);
2120 # plug the tap chain to bridge chain
2121 if ($direction eq 'IN') {
2122 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
2123 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
2125 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
2126 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
2130 sub enable_host_firewall {
2131 my ($ruleset, $hostfw_conf, $cluster_conf, $ipversion) = @_;
2133 my $options = $hostfw_conf->{options};
2134 my $cluster_options = $cluster_conf->{options};
2135 my $rules = $hostfw_conf->{rules};
2136 my $cluster_rules = $cluster_conf->{rules};
2138 # host inbound firewall
2139 my $chain = "PVEFW-HOST-IN
";
2140 ruleset_create_chain($ruleset, $chain);
2142 my $loglevel = get_option_log_level($options, "log_level_in
");
2144 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
2146 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options);
2147 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2148 ruleset_chain_add_input_filters($ruleset, $chain, $ipversion, $options, $cluster_conf, $loglevel);
2150 # we use RETURN because we need to check also tap rules
2151 my $accept_action = 'RETURN';
2153 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2155 # add host rules first, so that cluster wide rules can be overwritten
2156 foreach my $rule (@$rules, @$cluster_rules) {
2157 next if !$rule->{enable} || $rule->{errors};
2158 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2160 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
2163 if ($rule->{type} eq 'group') {
2164 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action, $ipversion);
2165 } elsif ($rule->{type} eq 'in') {
2166 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2167 { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2168 undef, $cluster_conf, $hostfw_conf);
2172 delete $rule->{iface_in};
2175 # allow standard traffic for management ipset (includes cluster network)
2176 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
", $ipversion);
2177 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
2178 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2179 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2180 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2181 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
2183 my $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2184 my $localnet_ver = $cluster_conf->{aliases}->{local_network}->{ipversion};
2187 if ($localnet && ($ipversion == $localnet_ver)) {
2188 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2189 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
2190 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
2193 # implement input policy
2194 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
2195 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2197 # host outbound firewall
2198 $chain = "PVEFW-HOST-OUT
";
2199 ruleset_create_chain($ruleset, $chain);
2201 $loglevel = get_option_log_level($options, "log_level_out
");
2203 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
2205 ruleset_chain_add_ndp($ruleset, $chain, $ipversion, $options);
2206 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
2208 # we use RETURN because we may want to check other thigs later
2209 $accept_action = 'RETURN';
2211 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
2213 # add host rules first, so that cluster wide rules can be overwritten
2214 foreach my $rule (@$rules, @$cluster_rules) {
2215 next if !$rule->{enable} || $rule->{errors};
2216 next if $rule->{ipversion} && ($rule->{ipversion} != $ipversion);
2218 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
2220 if ($rule->{type} eq 'group') {
2221 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action, $ipversion);
2222 } elsif ($rule->{type} eq 'out') {
2223 ruleset_generate_rule($ruleset, $chain, $ipversion,
2224 $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
2225 undef, $cluster_conf, $hostfw_conf);
2229 delete $rule->{iface_out};
2232 # allow standard traffic on cluster network
2233 if ($localnet && ($ipversion == $localnet_ver)) {
2234 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
2235 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
2236 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
2237 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
2239 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
2240 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
2241 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
2244 # implement output policy
2245 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
2246 ruleset_add_chain_policy($ruleset, $chain, $ipversion, 0, $policy, $loglevel, $accept_action);
2248 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
2249 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
2252 sub generate_group_rules {
2253 my ($ruleset, $cluster_conf, $group, $ipversion) = @_;
2255 my $rules = $cluster_conf->{groups}->{$group};
2258 warn "no such security group
'$group'\n";
2259 $rules = []; # create empty chain
2262 my $chain = "GROUP-
${group
}-IN
";
2264 ruleset_create_chain($ruleset, $chain);
2265 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2267 foreach my $rule (@$rules) {
2268 next if $rule->{type} ne 'in';
2269 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2270 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2271 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
2272 undef, $cluster_conf);
2275 $chain = "GROUP-
${group
}-OUT
";
2277 ruleset_create_chain($ruleset, $chain);
2278 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
2280 foreach my $rule (@$rules) {
2281 next if $rule->{type} ne 'out';
2282 next if $rule->{ipversion} && $rule->{ipversion} ne $ipversion;
2283 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
2284 # check also other tap rules later
2285 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule,
2286 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" },
2287 undef, $cluster_conf);
2292 my $valid_netdev_names = {};
2293 for (my $i = 0; $i < $MAX_NETS; $i++) {
2294 $valid_netdev_names->{"net
$i"} = 1;
2298 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
2300 my $orig_line = $line;
2304 # we can add single line comments to the end of the rule
2305 if ($line =~ s/#\s*(.*?)\s*$//) {
2306 $rule->{comment} = decode('utf8', $1);
2309 # we can disable a rule when prefixed with '|'
2311 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
2313 $line =~ s/^(\S+)\s+(\S+)\s*// ||
2314 die "unable to parse rule
: $line\n";
2316 $rule->{type} = lc($1);
2317 $rule->{action} = $2;
2319 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
2320 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
2321 $rule->{macro} = $1;
2322 $rule->{action} = $2;
2326 while (length($line)) {
2327 if ($line =~ s/^-i (\S+)\s*//) {
2328 $rule->{iface} = $1;
2332 last if $rule->{type} eq 'group';
2334 if ($line =~ s/^-p (\S+)\s*//) {
2335 $rule->{proto} = $1;
2339 if ($line =~ s/^-dport (\S+)\s*//) {
2340 $rule->{dport} = $1;
2344 if ($line =~ s/^-sport (\S+)\s*//) {
2345 $rule->{sport} = $1;
2348 if ($line =~ s/^-source (\S+)\s*//) {
2349 $rule->{source} = $1;
2352 if ($line =~ s/^-dest (\S+)\s*//) {
2360 die "unable to parse rule parameters
: $line\n" if length($line);
2362 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2363 if ($verbose && $rule->{errors}) {
2364 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2365 foreach my $p (keys %{$rule->{errors}}) {
2366 warn " $p: $rule->{errors
}->{$p}\n";
2373 sub parse_vmfw_option {
2378 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2380 if ($line =~ m/^(enable|dhcp|ndp|macfilter|ips):\s*(0|1)\s*$/i) {
2383 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2385 $value = $2 ? lc($3) : '';
2386 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2389 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2393 die "can
't parse option '$line'\n"
2396 return ($opt, $value);
2399 sub parse_hostfw_option {
2404 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2406 if ($line =~ m/^(enable|nosmurfs|tcpflags|ndp):\s*(0|1)\s*$/i) {
2409 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2411 $value = $2 ? lc($3) : '';
2412 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2416 die "can't parse option
'$line'\n"
2419 return ($opt, $value);
2422 sub parse_clusterfw_option {
2427 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2430 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2434 die "can
't parse option '$line'\n"
2437 return ($opt, $value);
2441 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2443 my $alias = lc($cidr);
2444 my $e = $fw_conf ? $fw_conf->{aliases}->{$alias} : undef;
2445 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2447 die "no such alias '$cidr'\n" if !$e;;
2449 return wantarray ? ($e->{cidr}, $e->{ipversion}) : $e->{cidr};
2452 sub parse_ip_or_cidr {
2457 if ($cidr =~ m!^(?:$IPV6RE)(/(\d+))?$!) {
2460 } elsif ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
2464 die "value does not look like a valid IP address or CIDR network\n";
2467 return wantarray ? ($cidr, $ipversion) : $cidr;
2473 # we can add single line comments to the end of the line
2474 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2476 if ($line =~ m/^(\S+)\s(\S+)$/) {
2477 my ($name, $cidr) = ($1, $2);
2480 ($cidr, $ipversion) = parse_ip_or_cidr($cidr);
2485 ipversion => $ipversion,
2487 $data->{comment} = $comment if $comment;
2494 sub generic_fw_config_parser {
2495 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2500 my $res = $empty_conf;
2502 while (defined(my $line = <$fh>)) {
2503 next if $line =~ m/^#/;
2504 next if $line =~ m/^\s*$/;
2508 my $linenr = $fh->input_line_number();
2509 my $prefix = "$filename (line $linenr)";
2511 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2512 $section = 'options
';
2516 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2517 $section = 'aliases
';
2521 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2522 $section = 'groups
';
2526 die "security group name too long\n" if length($group) > $max_group_name_length;
2527 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2530 ($section, $group, $comment) = undef;
2531 warn "$prefix: $err";
2535 $res->{$section}->{$group} = [];
2536 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2541 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2546 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2551 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2552 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2555 ($section, $group, $comment) = undef;
2556 warn "$prefix: $err";
2560 $res->{$section}->{$group} = [];
2561 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2567 warn "$prefix: skip line - no section\n";
2571 if ($section eq 'options
') {
2574 if ($rule_env eq 'cluster
') {
2575 ($opt, $value) = parse_clusterfw_option($line);
2576 } elsif ($rule_env eq 'host
') {
2577 ($opt, $value) = parse_hostfw_option($line);
2579 ($opt, $value) = parse_vmfw_option($line);
2581 $res->{options}->{$opt} = $value;
2583 warn "$prefix: $@" if $@;
2584 } elsif ($section eq 'aliases
') {
2586 my $data = parse_alias($line);
2587 $res->{aliases}->{lc($data->{name})} = $data;
2589 warn "$prefix: $@" if $@;
2590 } elsif ($section eq 'rules
') {
2592 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2594 warn "$prefix: $err";
2597 push @{$res->{$section}}, $rule;
2598 } elsif ($section eq 'groups
') {
2600 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2602 warn "$prefix: $err";
2605 push @{$res->{$section}->{$group}}, $rule;
2606 } elsif ($section eq 'ipset
') {
2607 # we can add single line comments to the end of the rule
2608 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2610 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2615 if ($nomatch && !$feature_ipset_nomatch) {
2616 $errors->{nomatch} = "nomatch not supported by kernel";
2620 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2621 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2623 $cidr = parse_ip_or_cidr($cidr);
2628 $errors->{cidr} = $err;
2631 my $entry = { cidr => $cidr };
2632 $entry->{nomatch} = 1 if $nomatch;
2633 $entry->{comment} = $comment if $comment;
2634 $entry->{errors} = $errors if $errors;
2636 if ($verbose && $errors) {
2637 warn "$prefix - errors in ipset '$group': $line\n";
2638 foreach my $p (keys %{$errors}) {
2639 warn " $p: $errors->{$p}\n";
2643 push @{$res->{$section}->{$group}}, $entry;
2645 warn "$prefix: skip line - unknown section\n";
2653 sub parse_hostfw_config {
2654 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2656 my $empty_conf = { rules => [], options => {}};
2658 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2661 sub parse_vmfw_config {
2662 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2669 ipset_comments => {},
2672 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2675 sub parse_clusterfw_config {
2676 my ($filename, $fh, $verbose) = @_;
2686 group_comments => {},
2688 ipset_comments => {},
2691 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2695 my ($code, @param) = @_;
2699 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2706 sub read_local_vm_config {
2711 my $vmdata = { openvz => $openvz, qemu => $qemu };
2713 my $vmlist = PVE::Cluster::get_vmlist();
2714 return $vmdata if !$vmlist || !$vmlist->{ids};
2715 my $ids = $vmlist->{ids};
2717 foreach my $vmid (keys %$ids) {
2718 next if !$vmid; # skip VE0
2719 my $d = $ids->{$vmid};
2720 next if !$d->{node} || $d->{node} ne $nodename;
2721 next if !$d->{type};
2722 if ($d->{type} eq 'openvz
') {
2723 if ($have_pve_manager) {
2724 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2725 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2726 $openvz->{$vmid} = $conf;
2729 } elsif ($d->{type} eq 'qemu
') {
2730 if ($have_qemu_server) {
2731 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2732 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2733 $qemu->{$vmid} = $conf;
2742 sub load_vmfw_conf {
2743 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2747 $dir = $pvefw_conf_dir if !defined($dir);
2749 my $filename = "$dir/$vmid.fw";
2750 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2751 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2752 $vmfw_conf->{vmid} = $vmid;
2758 my $format_rules = sub {
2759 my ($rules, $allow_iface) = @_;
2763 foreach my $rule (@$rules) {
2764 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2765 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2766 $raw .= uc($rule->{type});
2767 if ($rule->{macro}) {
2768 $raw .= " $rule->{macro}($rule->{action})";
2770 $raw .= " " . $rule->{action};
2772 if ($allow_iface && $rule->{iface}) {
2773 $raw .= " -i $rule->{iface}";
2776 if ($rule->{type} ne 'group
') {
2777 $raw .= " -source $rule->{source}" if $rule->{source};
2778 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2779 $raw .= " -p $rule->{proto}" if $rule->{proto};
2780 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2781 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2784 $raw .= " # " . encode('utf8
', $rule->{comment})
2785 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2788 die "unknown rule type '$rule->{type
}'";
2795 my $format_options = sub {
2800 $raw .= "[OPTIONS]\n\n";
2801 foreach my $opt (keys %$options) {
2802 $raw .= "$opt: $options->{$opt}\n";
2809 my $format_aliases = sub {
2814 $raw .= "[ALIASES]\n\n";
2815 foreach my $k (keys %$aliases) {
2816 my $e = $aliases->{$k};
2817 $raw .= "$e->{name} $e->{cidr}";
2818 $raw .= " # " . encode('utf8
', $e->{comment})
2819 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2827 my $format_ipsets = sub {
2832 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2833 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2834 my $utf8comment = encode('utf8
', $comment);
2835 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2837 $raw .= "[IPSET $ipset]\n\n";
2839 my $options = $fw_conf->{ipset}->{$ipset};
2842 foreach my $entry (@$options) {
2843 $nethash->{$entry->{cidr}} = $entry;
2846 foreach my $cidr (sort keys %$nethash) {
2847 my $entry = $nethash->{$cidr};
2848 my $line = $entry->{nomatch} ? '!' : '';
2849 $line .= $entry->{cidr};
2850 $line .= " # " . encode('utf8
', $entry->{comment})
2851 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2861 sub save_vmfw_conf {
2862 my ($vmid, $vmfw_conf) = @_;
2866 my $options = $vmfw_conf->{options};
2867 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2869 my $aliases = $vmfw_conf->{aliases};
2870 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2872 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2874 my $rules = $vmfw_conf->{rules} || [];
2875 if ($rules && scalar(@$rules)) {
2876 $raw .= "[RULES]\n\n";
2877 $raw .= &$format_rules($rules, 1);
2881 mkdir $pvefw_conf_dir;
2883 my $filename = "$pvefw_conf_dir/$vmid.fw";
2884 PVE::Tools::file_set_contents($filename, $raw);
2887 sub read_vm_firewall_configs {
2888 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2890 my $vmfw_configs = {};
2892 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2893 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2894 next if !$vmfw_conf->{options}; # skip if file does not exists
2895 $vmfw_configs->{$vmid} = $vmfw_conf;
2897 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2898 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2899 next if !$vmfw_conf->{options}; # skip if file does not exists
2900 $vmfw_configs->{$vmid} = $vmfw_conf;
2903 return $vmfw_configs;
2906 sub get_option_log_level {
2907 my ($options, $k) = @_;
2909 my $v = $options->{$k};
2910 $v = $default_log_level if !defined($v);
2912 return undef if $v eq '' || $v eq 'nolog
';
2914 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2916 return $v if ($v >= 0) && ($v <= 7);
2918 warn "unknown log level ($k = '$v')\n";
2923 sub generate_std_chains {
2924 my ($ruleset, $options, $ipversion) = @_;
2926 my $std_chains = $pve_std_chains->{$ipversion} || die "internal error";
2928 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2932 if ($ipversion == 4) {
2933 # same as shorewall smurflog.
2934 $chain = 'PVEFW-smurflog
';
2935 $std_chains->{$chain} = [];
2937 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2938 push @{$std_chains->{$chain}}, "-j DROP";
2941 # same as shorewall logflags action.
2942 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2943 $chain = 'PVEFW-logflags
';
2944 $std_chains->{$chain} = [];
2946 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2947 push @{$std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2948 push @{$std_chains->{$chain}}, "-j DROP";
2950 foreach my $chain (keys %$std_chains) {
2951 ruleset_create_chain($ruleset, $chain);
2952 foreach my $rule (@{$std_chains->{$chain}}) {
2954 ruleset_generate_rule($ruleset, $chain, $ipversion, $rule);
2956 ruleset_addrule($ruleset, $chain, $rule);
2962 sub generate_ipset_chains {
2963 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_; #fixme
2965 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2967 my $options = $fw_conf->{ipset}->{$ipset};
2971 foreach my $entry (@$options) {
2972 next if $entry->{errors}; # skip entries with errors
2975 if ($entry->{cidr} =~ m/^${ip_alias_pattern}$/) {
2976 ($cidr, $ver) = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2978 ($cidr, $ver) = parse_ip_or_cidr($entry->{cidr});
2980 #http://backreference.org/2013/03/01/ipv6-address-normalization/
2982 my $ipv6 = inet_pton(AF_INET6, lc($cidr));
2983 $cidr = inet_ntop(AF_INET6, $ipv6);
2989 $nethash->{$ver}->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2994 foreach my $ipversion (4, 6) {
2995 my $data = $nethash->{$ipversion};
2997 my $name = compute_ipset_chain_name($fw_conf->{vmid}, $ipset, $ipversion);
2999 my $hashsize = scalar(@$options);
3000 if ($hashsize <= 64) {
3003 $hashsize = round_powerof2($hashsize);
3006 my $family = $ipversion == "6" ? "inet6" : "inet";
3008 $ipset_ruleset->{$name} = ["create $name hash:net family $family hashsize $hashsize maxelem $hashsize"];
3010 foreach my $cidr (sort keys %$data) {
3011 my $entry = $data->{$cidr};
3013 my $cmd = "add $name $cidr";
3014 if ($entry->{nomatch}) {
3015 if ($feature_ipset_nomatch) {
3016 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
3018 warn "ignore !$cidr - nomatch not supported by kernel\n";
3021 push @{$ipset_ruleset->{$name}}, $cmd;
3028 sub round_powerof2 {
3032 $int |= $int >> $_ foreach (1,2,4,8,16);
3036 sub load_clusterfw_conf {
3037 my ($filename, $verbose) = @_;
3039 $filename = $clusterfw_conf_filename if !defined($filename);
3041 my $cluster_conf = {};
3042 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3043 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
3046 return $cluster_conf;
3049 sub save_clusterfw_conf {
3050 my ($cluster_conf) = @_;
3054 my $options = $cluster_conf->{options};
3055 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3057 my $aliases = $cluster_conf->{aliases};
3058 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
3060 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
3062 my $rules = $cluster_conf->{rules};
3063 if ($rules && scalar(@$rules)) {
3064 $raw .= "[RULES]\n\n";
3065 $raw .= &$format_rules($rules, 1);
3069 if ($cluster_conf->{groups}) {
3070 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
3071 my $rules = $cluster_conf->{groups}->{$group};
3072 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
3073 my $utf8comment = encode('utf8
', $comment);
3074 $raw .= "[group $group] # $utf8comment\n\n";
3076 $raw .= "[group $group]\n\n";
3079 $raw .= &$format_rules($rules, 0);
3084 mkdir $pvefw_conf_dir;
3085 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
3088 sub load_hostfw_conf {
3089 my ($cluster_conf, $filename, $verbose) = @_;
3091 $filename = $hostfw_conf_filename if !defined($filename);
3093 my $hostfw_conf = {};
3094 if (my $fh = IO::File->new($filename, O_RDONLY)) {
3095 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
3097 return $hostfw_conf;
3100 sub save_hostfw_conf {
3101 my ($hostfw_conf) = @_;
3105 my $options = $hostfw_conf->{options};
3106 $raw .= &$format_options($options) if $options && scalar(keys %$options);
3108 my $rules = $hostfw_conf->{rules};
3109 if ($rules && scalar(@$rules)) {
3110 $raw .= "[RULES]\n\n";
3111 $raw .= &$format_rules($rules, 1);
3115 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
3119 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
3123 if ($vmdata) { # test mode
3124 my $testdir = $vmdata->{testdir} || die "no test directory specified";
3125 my $filename = "$testdir/cluster.fw";
3126 $cluster_conf = load_clusterfw_conf($filename, $verbose);
3128 $filename = "$testdir/host.fw";
3129 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
3131 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
3132 } else { # normal operation
3133 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
3135 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
3137 $vmdata = read_local_vm_config();
3138 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
3141 my ($ruleset, $ipset_ruleset) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 4, $verbose);
3142 my ($rulesetv6) = compile_iptables_filter($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, 6, $verbose);
3144 return ($ruleset, $ipset_ruleset, $rulesetv6);
3147 sub compile_iptables_filter {
3148 my ($cluster_conf, $hostfw_conf, $vmfw_configs, $vmdata, $ipversion, $verbose) = @_;
3150 $cluster_conf->{ipset}->{venet0} = [];
3151 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
', $ipversion);
3154 if ($cluster_conf->{aliases}->{local_network}) {
3155 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
3158 ($localnet, $localnet_ver) = parse_ip_or_cidr(local_network() || '127.0.0.0/8');
3160 $cluster_conf->{aliases}->{local_network} = {
3161 name => 'local_network
', cidr => $localnet, ipversion => $localnet_ver };
3164 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
3166 return ({}, {}) if !$cluster_conf->{options}->{enable};
3170 ruleset_create_chain($ruleset, "PVEFW-INPUT");
3171 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
3173 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
3175 my $hostfw_options = $hostfw_conf->{options} || {};
3177 # fixme: what log level should we use here?
3178 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
3180 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
3183 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
3184 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3185 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
3187 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
3188 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3190 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
3192 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
3193 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
3195 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
3196 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $ipversion, $hostfw_options, $cluster_conf, $loglevel);
3198 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3200 generate_std_chains($ruleset, $hostfw_options, $ipversion);
3202 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
3204 my $ipset_ruleset = {};
3206 if ($hostfw_enable) {
3207 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf, $ipversion); };
3208 warn $@ if $@; # just to be sure - should not happen
3211 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
3213 # generate firewall rules for QEMU VMs
3214 foreach my $vmid (keys %{$vmdata->{qemu}}) {
3216 my $conf = $vmdata->{qemu}->{$vmid};
3217 my $vmfw_conf = $vmfw_configs->{$vmid};
3218 return if !$vmfw_conf;
3220 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3222 foreach my $netid (keys %$conf) {
3223 next if $netid !~ m/^net(\d+)$/;
3224 my $net = PVE::QemuServer::parse_net($conf->{$netid});
3225 next if !$net->{firewall};
3226 my $iface = "tap${vmid}i$1";
3228 my $macaddr = $net->{macaddr};
3229 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3230 $vmfw_conf, $vmid, 'IN
', $ipversion);
3231 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3232 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3235 warn $@ if $@; # just to be sure - should not happen
3238 # generate firewall rules for OpenVZ containers
3239 foreach my $vmid (keys %{$vmdata->{openvz}}) {
3241 my $conf = $vmdata->{openvz}->{$vmid};
3243 my $vmfw_conf = $vmfw_configs->{$vmid};
3244 return if !$vmfw_conf;
3246 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
3248 if ($vmfw_conf->{options}->{enable}) {
3249 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
3250 my $ip = $conf->{ip_address}->{value};
3255 foreach my $singleip (split(',', $ip)) {
3256 my $singleip_ver = parse_address_list($singleip); # make sure we have a valid $ip list
3257 push @{$cluster_conf->{ipset}->{venet0}}, { cidr => $singleip };
3258 push @ips, $singleip if $singleip_ver == $ipversion;
3262 my $ip_list = join(',', @ips);
3263 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'IN
', $ipversion);
3264 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip_list, 'OUT
', $ipversion);
3269 if ($conf->{netif} && $conf->{netif}->{value}) {
3270 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
3271 foreach my $netid (keys %$netif) {
3272 my $d = $netif->{$netid};
3273 my $bridge = $d->{bridge};
3274 next if !$bridge || $bridge !~ m/^vmbr\d+(v(\d+))?f$/; # firewall enabled ?
3275 my $macaddr = $d->{mac};
3276 my $iface = $d->{host_ifname};
3277 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3278 $vmfw_conf, $vmid, 'IN
', $ipversion);
3279 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
3280 $vmfw_conf, $vmid, 'OUT
', $ipversion);
3284 warn $@ if $@; # just to be sure - should not happen
3287 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
3288 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
3291 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
3293 return ($ruleset, $ipset_ruleset);
3296 sub get_ruleset_status {
3297 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
3299 my $statushash = {};
3301 foreach my $chain (sort keys %$ruleset) {
3302 my $sig = &$digest_fn($ruleset->{$chain});
3304 $statushash->{$chain}->{sig} = $sig;
3306 my $oldsig = $active_chains->{$chain};
3307 if (!defined($oldsig)) {
3308 $statushash->{$chain}->{action} = 'create
';
3310 if ($oldsig eq $sig) {
3311 $statushash->{$chain}->{action} = 'exists';
3313 $statushash->{$chain}->{action} = 'update
';
3316 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
3317 foreach my $cmd (@{$ruleset->{$chain}}) {
3318 print "\t$cmd\n" if $verbose;
3322 foreach my $chain (sort keys %$active_chains) {
3323 if (!defined($ruleset->{$chain})) {
3324 my $sig = $active_chains->{$chain};
3325 $statushash->{$chain}->{action} = 'delete';
3326 $statushash->{$chain}->{sig} = $sig;
3327 print "delete $chain ($sig)\n" if $verbose;
3334 sub print_sig_rule {
3335 my ($chain, $sig) = @_;
3337 # We just use this to store a SHA1 checksum used to detect changes
3338 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
3341 sub get_ruleset_cmdlist {
3342 my ($ruleset, $verbose, $iptablescmd) = @_;
3344 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
3346 my ($active_chains, $hooks) = iptables_get_chains($iptablescmd);
3347 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
3349 # create missing chains first
3350 foreach my $chain (sort keys %$ruleset) {
3351 my $stat = $statushash->{$chain};
3352 die "internal error" if !$stat;
3353 next if $stat->{action} ne 'create
';
3355 $cmdlist .= ":$chain - [0:0]\n";
3358 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3359 my $chain = "PVEFW-$h";
3360 if ($ruleset->{$chain} && !$hooks->{$h}) {
3361 $cmdlist .= "-A $h -j $chain\n";
3365 foreach my $chain (sort keys %$ruleset) {
3366 my $stat = $statushash->{$chain};
3367 die "internal error" if !$stat;
3369 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
3370 $cmdlist .= "-F $chain\n";
3371 foreach my $cmd (@{$ruleset->{$chain}}) {
3372 $cmdlist .= "$cmd\n";
3374 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
3375 } elsif ($stat->{action
} eq 'delete') {
3376 die "internal error"; # this should not happen
3377 } elsif ($stat->{action
} eq 'exists') {
3380 die "internal error - unknown status '$stat->{action}'";
3384 foreach my $chain (keys %$statushash) {
3385 next if $statushash->{$chain}->{action
} ne 'delete';
3386 $cmdlist .= "-F $chain\n";
3388 foreach my $chain (keys %$statushash) {
3389 next if $statushash->{$chain}->{action
} ne 'delete';
3390 next if $chain eq 'PVEFW-INPUT';
3391 next if $chain eq 'PVEFW-OUTPUT';
3392 next if $chain eq 'PVEFW-FORWARD';
3393 $cmdlist .= "-X $chain\n";
3396 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3398 $cmdlist .= "COMMIT\n";
3400 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3403 sub get_ipset_cmdlist
{
3404 my ($ruleset, $verbose) = @_;
3408 my $delete_cmdlist = "";
3410 my $active_chains = ipset_get_chains
();
3411 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3413 # remove stale _swap chains
3414 foreach my $chain (keys %$active_chains) {
3415 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3416 $cmdlist .= "destroy $chain\n";
3420 foreach my $chain (keys %$ruleset) {
3421 my $stat = $statushash->{$chain};
3422 die "internal error" if !$stat;
3424 if ($stat->{action
} eq 'create') {
3425 foreach my $cmd (@{$ruleset->{$chain}}) {
3426 $cmdlist .= "$cmd\n";
3431 foreach my $chain (keys %$ruleset) {
3432 my $stat = $statushash->{$chain};
3433 die "internal error" if !$stat;
3435 if ($stat->{action
} eq 'update') {
3436 my $chain_swap = $chain."_swap";
3438 foreach my $cmd (@{$ruleset->{$chain}}) {
3439 $cmd =~ s/$chain/$chain_swap/;
3440 $cmdlist .= "$cmd\n";
3442 $cmdlist .= "swap $chain_swap $chain\n";
3443 $cmdlist .= "flush $chain_swap\n";
3444 $cmdlist .= "destroy $chain_swap\n";
3448 # the remove unused chains
3449 foreach my $chain (keys %$statushash) {
3450 next if $statushash->{$chain}->{action
} ne 'delete';
3452 $delete_cmdlist .= "flush $chain\n";
3453 $delete_cmdlist .= "destroy $chain\n";
3456 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3458 return ($cmdlist, $delete_cmdlist, $changes);
3462 my ($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6, $verbose) = @_;
3464 enable_bridge_firewall
();
3466 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3467 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3469 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3470 my ($cmdlistv6, $changesv6) = get_ruleset_cmdlist
($rulesetv6, $verbose, "ip6tables");
3473 if ($ipset_changes) {
3474 print "ipset changes:\n";
3475 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3476 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3480 print "iptables changes:\n";
3485 print "ip6tables changes:\n";
3490 my $tmpfile = "$pve_fw_status_dir/ipsetcmdlist1";
3491 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_create_cmdlist || '');
3493 ipset_restore_cmdlist
($ipset_create_cmdlist);
3495 $tmpfile = "$pve_fw_status_dir/ip4cmdlist";
3496 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlist || '');
3498 iptables_restore_cmdlist
($cmdlist);
3500 $tmpfile = "$pve_fw_status_dir/ip6cmdlist";
3501 PVE
::Tools
::file_set_contents
($tmpfile, $cmdlistv6 || '');
3503 ip6tables_restore_cmdlist
($cmdlistv6);
3505 $tmpfile = "$pve_fw_status_dir/ipsetcmdlist2";
3506 PVE
::Tools
::file_set_contents
($tmpfile, $ipset_delete_cmdlist || '');
3508 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3510 # test: re-read status and check if everything is up to date
3511 my $active_chains = iptables_get_chains
();
3512 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3515 foreach my $chain (sort keys %$ruleset) {
3516 my $stat = $statushash->{$chain};
3517 if ($stat->{action
} ne 'exists') {
3518 warn "unable to update chain '$chain'\n";
3523 my $active_chainsv6 = iptables_get_chains
("ip6tables");
3524 my $statushashv6 = get_ruleset_status
($rulesetv6, $active_chainsv6, \
&iptables_chain_digest
, 0);
3526 foreach my $chain (sort keys %$rulesetv6) {
3527 my $stat = $statushashv6->{$chain};
3528 if ($stat->{action
} ne 'exists') {
3529 warn "unable to update chain '$chain'\n";
3534 die "unable to apply firewall changes\n" if $errors;
3536 update_nf_conntrack_max
($hostfw_conf);
3538 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3542 sub update_nf_conntrack_max
{
3543 my ($hostfw_conf) = @_;
3545 my $max = 65536; # reasonable default
3547 my $options = $hostfw_conf->{options
} || {};
3549 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3550 $max = $options->{nf_conntrack_max
};
3551 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3554 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3555 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3557 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3559 if ($current != $max) {
3560 my $hashsize = int($max/4);
3561 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3562 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3566 sub update_nf_conntrack_tcp_timeout_established
{
3567 my ($hostfw_conf) = @_;
3569 my $options = $hostfw_conf->{options
} || {};
3571 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3573 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3576 sub remove_pvefw_chains
{
3578 PVE
::Firewall
::remove_pvefw_chains_iptables
("iptables");
3579 PVE
::Firewall
::remove_pvefw_chains_iptables
("ip6tables");
3580 PVE
::Firewall
::remove_pvefw_chains_ipset
();
3584 sub remove_pvefw_chains_iptables
{
3585 my ($iptablescmd) = @_;
3587 my ($chash, $hooks) = iptables_get_chains
($iptablescmd);
3588 my $cmdlist = "*filter\n";
3590 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3592 $cmdlist .= "-D $h -j PVEFW-$h\n";
3596 foreach my $chain (keys %$chash) {
3597 $cmdlist .= "-F $chain\n";
3600 foreach my $chain (keys %$chash) {
3601 $cmdlist .= "-X $chain\n";
3603 $cmdlist .= "COMMIT\n";
3605 if($iptablescmd eq "ip6tables") {
3606 ip6tables_restore_cmdlist
($cmdlist);
3608 iptables_restore_cmdlist
($cmdlist);
3612 sub remove_pvefw_chains_ipset
{
3614 my $ipset_chains = ipset_get_chains
();
3618 foreach my $chain (keys %$ipset_chains) {
3619 $cmdlist .= "flush $chain\n";
3620 $cmdlist .= "destroy $chain\n";
3623 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3627 my $cluster_conf = load_clusterfw_conf
();
3628 my $cluster_options = $cluster_conf->{options
};
3629 my $enable = $cluster_options->{enable
};
3633 # load required modules here
3639 my $cluster_conf = load_clusterfw_conf
();
3640 my $cluster_options = $cluster_conf->{options
};
3642 if (!$cluster_options->{enable
}) {
3643 PVE
::Firewall
::remove_pvefw_chains
();
3647 my $hostfw_conf = load_hostfw_conf
($cluster_conf);
3649 my ($ruleset, $ipset_ruleset, $rulesetv6) = compile
($cluster_conf, $hostfw_conf);
3651 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset, $rulesetv6);