9 use PVE
::Exception
qw(raise raise_param_exc);
10 use PVE
::JSONSchema
qw(register_standard_option get_standard_option);
13 use PVE
::Tools
qw($IPV4RE);
18 use PVE
::Tools
qw(run_command lock_file dir_glob_foreach);
21 my $hostfw_conf_filename = "/etc/pve/local/host.fw";
22 my $clusterfw_conf_filename = "/etc/pve/firewall/cluster.fw";
24 # dynamically include PVE::QemuServer and PVE::OpenVZ
25 # to avoid dependency problems
28 require PVE
::QemuServer
;
29 $have_qemu_server = 1;
35 $have_pve_manager = 1;
38 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
39 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
40 my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
42 my $max_alias_name_length = 64;
43 my $max_ipset_name_length = 64;
44 my $max_group_name_length = 20;
46 PVE
::JSONSchema
::register_format
('IPv4orCIDR', \
&pve_verify_ipv4_or_cidr
);
47 sub pve_verify_ipv4_or_cidr
{
48 my ($cidr, $noerr) = @_;
50 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
51 return $cidr if Net
::IP-
>new($cidr);
52 return undef if $noerr;
53 die Net
::IP
::Error
() . "\n";
55 return undef if $noerr;
56 die "value does not look like a valid IP address or CIDR network\n";
59 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
60 description
=> "IP set name.",
62 pattern
=> $ipset_name_pattern,
64 maxLength
=> $max_ipset_name_length,
67 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
68 description
=> "Alias name.",
70 pattern
=> $ip_alias_pattern,
72 maxLength
=> $max_alias_name_length,
75 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
76 description
=> "Log level.",
78 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
82 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
83 description
=> "Security Group name.",
85 pattern
=> $security_group_name_pattern,
87 maxLength
=> $max_group_name_length,
90 my $feature_ipset_nomatch = 0;
92 my (undef, undef, $release) = POSIX
::uname
();
93 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
94 my ($major, $minor) = ($1, $2);
95 $feature_ipset_nomatch = 1 if ($major > 3) ||
96 ($major == 3 && $minor >= 7);
103 my $nodename = PVE
::INotify
::nodename
();
105 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
107 my $default_log_level = 'nolog'; # avoid logs by default
109 my $log_level_hash = {
120 # imported/converted from: /usr/share/shorewall/macro.*
121 my $pve_fw_macros = {
124 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
125 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
128 "Auth (identd) traffic",
129 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
132 "Border Gateway Protocol traffic",
133 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
136 "BitTorrent traffic for BitTorrent 3.1 and earlier",
137 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
138 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
141 "BitTorrent traffic for BitTorrent 3.2 and later",
142 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
143 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
146 "Concurrent Versions System pserver traffic",
147 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
150 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
151 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
152 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
153 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
156 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
157 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
158 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
161 "Distributed Checksum Clearinghouse spam filtering mechanism",
162 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
165 "Forwarded DHCP traffic",
166 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
169 "Domain Name System traffic (upd and tcp)",
170 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
171 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
174 "Distributed Compiler service",
175 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
178 "File Transfer Protocol",
179 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
182 "Finger protocol (RFC 742)",
183 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
186 "GNUnet secure peer-to-peer networking traffic",
187 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
188 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
189 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
190 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
193 "Generic Routing Encapsulation tunneling protocol",
194 { action
=> 'PARAM', proto
=> '47' },
197 "Git distributed revision control traffic",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
201 "OpenPGP HTTP keyserver protocol traffic",
202 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
205 "Hypertext Transfer Protocol (WWW)",
206 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
209 "Hypertext Transfer Protocol (WWW) over SSL",
210 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
213 "Internet Cache Protocol V2 (Squid) traffic",
214 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
217 "AOL Instant Messenger traffic",
218 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
221 "Internet Message Access Protocol",
222 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
225 "Internet Message Access Protocol over SSL",
226 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
229 "IPIP capsulation traffic",
230 { action
=> 'PARAM', proto
=> '94' },
234 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
235 { action
=> 'PARAM', proto
=> '50' },
238 "IPsec authentication (AH) traffic",
239 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
240 { action
=> 'PARAM', proto
=> '51' },
243 "IPsec traffic and Nat-Traversal",
244 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
245 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
246 { action
=> 'PARAM', proto
=> '50' },
249 "Internet Relay Chat traffic",
250 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
253 "HP Jetdirect printing",
254 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
257 "Layer 2 Tunneling Protocol traffic",
258 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
261 "Lightweight Directory Access Protocol traffic",
262 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
265 "Secure Lightweight Directory Access Protocol traffic",
266 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
269 "Microsoft Notification Protocol",
270 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
273 "Microsoft SQL Server",
274 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
277 "Mail traffic (SMTP, SMTPS, Submission)",
278 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
279 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
280 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
283 "Munin networked resource monitoring traffic",
284 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
288 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
291 "NNTP traffic (Usenet).",
292 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
295 "Encrypted NNTP traffic (Usenet)",
296 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
299 "Network Time Protocol (ntpd)",
300 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
303 "OSPF multicast traffic",
304 { action
=> 'PARAM', proto
=> '89' },
308 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
311 "Symantec PCAnywere (tm)",
312 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
313 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
317 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
320 "Encrypted POP3 traffic",
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
324 "Point-to-Point Tunneling Protocol",
325 { action
=> 'PARAM', proto
=> '47' },
326 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
330 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
334 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
337 "Line Printer protocol printing",
338 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
341 "Microsoft Remote Desktop Protocol traffic",
342 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
345 "Routing Information Protocol (bidirectional)",
346 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
349 "BIND remote management protocol",
350 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
353 "Razor Antispam System",
354 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
357 "Remote time retrieval (rdate)",
358 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
362 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
365 "SANE network scanning",
366 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
369 "Microsoft SMB traffic",
370 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
371 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
372 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
373 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
376 "Samba Web Administration Tool",
377 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
380 "Simple Mail Transfer Protocol",
381 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
384 "Encrypted Simple Mail Transfer Protocol",
385 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
388 "Simple Network Management Protocol",
389 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
390 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
393 "Spam Assassin SPAMD traffic",
394 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
397 "Secure shell traffic",
398 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
401 "Subversion server (svnserve)",
402 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
405 "SixXS IPv6 Deployment and Tunnel Broker",
406 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
407 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
408 { action
=> 'PARAM', proto
=> '41' },
409 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
412 "Squid web proxy traffic",
413 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
416 "Mail message submission traffic",
417 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
420 "Syslog protocol (RFC 5424) traffic",
421 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
422 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
425 "Trivial File Transfer Protocol traffic",
426 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
430 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
434 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
437 "RFC 868 Time protocol",
438 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
441 "Traceroute (for up to 30 hops) traffic",
442 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
443 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
446 "VNC traffic for VNC display's 0 - 99",
447 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
450 "VNC traffic from Vncservers to Vncviewers in listen mode",
451 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
454 "WWW traffic (HTTP and HTTPS)",
455 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
456 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
459 "Web Cache/Proxy traffic (port 8080)",
460 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
464 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
467 "Whois (nicname, RFC 3912) traffic",
468 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
472 my $pve_fw_parsed_macros;
473 my $pve_fw_macro_descr;
474 my $pve_fw_preferred_macro_names = {};
476 my $pve_std_chains = {
477 'PVEFW-SET-ACCEPT-MARK' => [
478 "-j MARK --set-mark 1",
480 'PVEFW-DropBroadcast' => [
481 # same as shorewall 'Broadcast'
482 # simply DROP BROADCAST/MULTICAST/ANYCAST
483 # we can use this to reduce logging
484 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
485 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
486 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
487 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
490 # same as shorewall 'reject'
491 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
492 { action
=> 'DROP', source
=> '224.0.0.0/4' },
493 { action
=> 'DROP', proto
=> 'icmp' },
494 "-p tcp -j REJECT --reject-with tcp-reset",
495 "-p udp -j REJECT --reject-with icmp-port-unreachable",
496 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
497 "-j REJECT --reject-with icmp-host-prohibited",
500 # same as shorewall 'Drop', which is equal to DROP,
501 # but REJECT/DROP some packages to reduce logging,
502 # and ACCEPT critical ICMP types
503 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
504 # we are not interested in BROADCAST/MULTICAST/ANYCAST
505 { action
=> 'PVEFW-DropBroadcast' },
506 # ACCEPT critical ICMP types
507 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
508 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
509 # Drop packets with INVALID state
510 "-m conntrack --ctstate INVALID -j DROP",
511 # Drop Microsoft SMB noise
512 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
513 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
514 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
515 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
516 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
517 # Drop new/NotSyn traffic so that it doesn't get logged
518 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
520 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
523 # same as shorewall 'Reject', which is equal to Reject,
524 # but REJECT/DROP some packages to reduce logging,
525 # and ACCEPT critical ICMP types
526 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
527 # we are not interested in BROADCAST/MULTICAST/ANYCAST
528 { action
=> 'PVEFW-DropBroadcast' },
529 # ACCEPT critical ICMP types
530 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
531 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
532 # Drop packets with INVALID state
533 "-m conntrack --ctstate INVALID -j DROP",
534 # Drop Microsoft SMB noise
535 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
536 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
537 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
538 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
539 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
540 # Drop new/NotSyn traffic so that it doesn't get logged
541 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
543 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
545 'PVEFW-tcpflags' => [
546 # same as shorewall tcpflags action.
547 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
548 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
549 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
550 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
551 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
552 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
555 # same as shorewall smurfs action
556 # Filter packets for smurfs (packets with a broadcast address as the source).
557 "-s 0.0.0.0/32 -j RETURN",
558 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
559 "-s 224.0.0.0/4 -g PVEFW-smurflog",
563 # iptables -p icmp -h
564 my $icmp_type_names = {
567 'destination-unreachable' => 1,
568 'network-unreachable' => 1,
569 'host-unreachable' => 1,
570 'protocol-unreachable' => 1,
571 'port-unreachable' => 1,
572 'fragmentation-needed' => 1,
573 'source-route-failed' => 1,
574 'network-unknown' => 1,
576 'network-prohibited' => 1,
577 'host-prohibited' => 1,
578 'TOS-network-unreachable' => 1,
579 'TOS-host-unreachable' => 1,
580 'communication-prohibited' => 1,
581 'host-precedence-violation' => 1,
582 'precedence-cutoff' => 1,
583 'source-quench' => 1,
585 'network-redirect' => 1,
586 'host-redirect' => 1,
587 'TOS-network-redirect' => 1,
588 'TOS-host-redirect' => 1,
590 'router-advertisement' => 1,
591 'router-solicitation' => 1,
592 'time-exceeded' => 1,
593 'ttl-zero-during-transit' => 1,
594 'ttl-zero-during-reassembly' => 1,
595 'parameter-problem' => 1,
596 'ip-header-bad' => 1,
597 'required-option-missing' => 1,
598 'timestamp-request' => 1,
599 'timestamp-reply' => 1,
600 'address-mask-request' => 1,
601 'address-mask-reply' => 1,
604 sub init_firewall_macros
{
606 $pve_fw_parsed_macros = {};
608 foreach my $k (keys %$pve_fw_macros) {
609 my $lc_name = lc($k);
610 my $macro = $pve_fw_macros->{$k};
611 if (!ref($macro->[0])) {
612 $pve_fw_macro_descr->{$k} = shift @$macro;
614 $pve_fw_preferred_macro_names->{$lc_name} = $k;
615 $pve_fw_parsed_macros->{$k} = $macro;
619 init_firewall_macros
();
622 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
627 sub get_etc_services
{
629 return $etc_services if $etc_services;
631 my $filename = "/etc/services";
633 my $fh = IO
::File-
>new($filename, O_RDONLY
);
635 warn "unable to read '$filename' - $!\n";
641 while (my $line = <$fh>) {
643 next if $line =~m/^#/;
644 next if ($line =~m/^\s*$/);
646 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
647 $services->{byid
}->{$2}->{name
} = $1;
648 $services->{byid
}->{$2}->{port
} = $2;
649 $services->{byid
}->{$2}->{$3} = 1;
650 $services->{byname
}->{$1} = $services->{byid
}->{$2};
656 $etc_services = $services;
659 return $etc_services;
664 sub get_etc_protocols
{
665 return $etc_protocols if $etc_protocols;
667 my $filename = "/etc/protocols";
669 my $fh = IO
::File-
>new($filename, O_RDONLY
);
671 warn "unable to read '$filename' - $!\n";
677 while (my $line = <$fh>) {
679 next if $line =~m/^#/;
680 next if ($line =~m/^\s*$/);
682 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
683 $protocols->{byid
}->{$2}->{name
} = $1;
684 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
690 $etc_protocols = $protocols;
692 return $etc_protocols;
695 my $ipv4_mask_hash_localnet = {
697 '255.255.128.0' => 17,
698 '255.255.192.0' => 18,
699 '255.255.224.0' => 19,
700 '255.255.240.0' => 20,
701 '255.255.248.0' => 21,
702 '255.255.252.0' => 22,
703 '255.255.254.0' => 23,
704 '255.255.255.0' => 24,
705 '255.255.255.128' => 25,
706 '255.255.255.192' => 26,
707 '255.255.255.224' => 27,
708 '255.255.255.240' => 28,
709 '255.255.255.248' => 29,
710 '255.255.255.252' => 30,
716 my ($new_value) = @_;
718 $__local_network = $new_value if defined($new_value);
720 return $__local_network if defined($__local_network);
723 my $nodename = PVE
::INotify
::nodename
();
725 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
727 my $testip = Net
::IP-
>new($ip);
729 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
730 foreach my $entry (@$routes) {
731 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
732 next if !defined($mask);
733 return if $mask eq '0.0.0.0';
734 my $cidr = "$entry->{dest}/$mask";
735 my $testnet = Net
::IP-
>new($cidr);
736 if ($testnet->overlaps($testip)) {
737 $__local_network = $cidr;
744 return $__local_network;
747 my $max_iptables_ipset_name_length = 27;
749 sub compute_ipset_chain_name
{
750 my ($vmid, $ipset_name) = @_;
752 $vmid = 0 if !defined($vmid);
754 my $id = "$vmid-${ipset_name}";
757 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
758 $id = PVE
::Tools
::fnv31a_hex
($id);
764 sub parse_address_list
{
767 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
768 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
772 if ($str =~ m/^${ip_alias_pattern}$/) {
773 die "alias name too long\n" if length($str) > $max_alias_name_length;
779 foreach my $elem (split(/,/, $str)) {
781 if (!Net
::IP-
>new($elem)) {
782 my $err = Net
::IP
::Error
();
783 die "invalid IP address: $err\n";
785 $iprange = 1 if $elem =~ m/-/;
788 die "you can use a range in a list\n" if $iprange && $count > 1;
791 sub parse_port_name_number_or_range
{
794 my $services = PVE
::Firewall
::get_etc_services
();
798 foreach my $item (split(/,/, $str)) {
800 if ($item =~ m/^(\d+):(\d+)$/) {
801 my ($port1, $port2) = ($1, $2);
802 die "invalid port '$port1'\n" if $port1 > 65535;
803 die "invalid port '$port2'\n" if $port2 > 65535;
804 } elsif ($item =~ m/^(\d+)$/) {
806 die "invalid port '$port'\n" if $port > 65535;
808 if ($icmp_type_names->{$item}) {
811 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
816 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
821 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
822 sub pve_fw_verify_port_spec
{
825 parse_port_name_number_or_range
($portstr);
830 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
831 sub pve_fw_verify_v4addr_spec
{
834 parse_address_list
($list);
839 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
840 sub pve_fw_verify_protocol_spec
{
843 my $protocols = get_etc_protocols
();
845 die "unknown protocol '$proto'\n" if $proto &&
846 !(defined($protocols->{byname
}->{$proto}) ||
847 defined($protocols->{byid
}->{$proto}));
853 # helper function for API
855 sub copy_opject_with_digest
{
858 my $sha = Digest
::SHA-
>new('sha1');
861 foreach my $k (sort keys %$object) {
862 my $v = $object->{$k};
863 next if !defined($v);
865 $sha->add($k, ':', $v, "\n");
868 my $digest = $sha->hexdigest;
870 $res->{digest
} = $digest;
872 return wantarray ?
($res, $digest) : $res;
875 sub copy_list_with_digest
{
878 my $sha = Digest
::SHA-
>new('sha1');
881 foreach my $entry (@$list) {
883 foreach my $k (sort keys %$entry) {
884 my $v = $entry->{$k};
885 next if !defined($v);
887 # Note: digest ignores refs ($rule->{errors})
888 $sha->add($k, ':', $v, "\n") if !ref($v); ;
893 my $digest = $sha->hexdigest;
895 foreach my $entry (@$res) {
896 $entry->{digest
} = $digest;
899 return wantarray ?
($res, $digest) : $res;
902 my $rule_properties = {
904 description
=> "Update rule at position <pos>.",
909 digest
=> get_standard_option
('pve-config-digest'),
913 enum
=> ['in', 'out', 'group'],
916 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
919 pattern
=> $security_group_name_pattern,
928 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
930 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
934 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
938 type
=> 'string', format
=> 'pve-fw-protocol-spec',
946 type
=> 'string', format
=> 'pve-fw-port-spec',
950 type
=> 'string', format
=> 'pve-fw-port-spec',
959 sub add_rule_properties
{
960 my ($properties) = @_;
962 foreach my $k (keys %$rule_properties) {
963 my $h = $rule_properties->{$k};
964 # copy data, so that we can modify later without side effects
965 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
971 sub delete_rule_properties
{
972 my ($rule, $delete_str) = @_;
974 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
975 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
976 if !defined($rule_properties->{$opt});
977 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
978 if $opt eq 'type' || $opt eq 'action';
979 delete $rule->{$opt};
985 my $apply_macro = sub {
986 my ($macro_name, $param, $verify) = @_;
988 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
989 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
993 foreach my $templ (@$macro_rules) {
996 foreach my $k (keys %$templ) {
997 my $v = $templ->{$k};
1000 $param_used->{$k} = 1;
1001 } elsif ($v eq 'DEST') {
1002 $v = $param->{dest
};
1003 $param_used->{dest
} = 1;
1004 } elsif ($v eq 'SOURCE') {
1005 $v = $param->{source
};
1006 $param_used->{source
} = 1;
1010 my $msg = "missing parameter '$k' in macro '$macro_name'";
1011 raise_param_exc
({ macro => $msg }) if $verify;
1016 foreach my $k (keys %$param) {
1017 next if $k eq 'macro';
1018 next if !defined($param->{$k});
1019 next if $param_used->{$k};
1020 if (defined($rule->{$k})) {
1021 if ($rule->{$k} ne $param->{$k}) {
1022 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1023 raise_param_exc
({ $k => $msg }) if $verify;
1027 $rule->{$k} = $param->{$k};
1030 push @$rules, $rule;
1036 my $rule_env_iface_lookup = {
1045 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1047 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1049 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1050 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1052 my $errors = $rule->{errors
} || {};
1054 my $error_count = 0;
1056 my $add_error = sub {
1057 my ($param, $msg) = @_;
1059 raise_param_exc
({ $param => $msg }) if !$noerr;
1061 $errors->{$param} = $msg if !$errors->{$param};
1064 my $check_ipset_or_alias_property = sub {
1067 if (my $value = $rule->{$name}) {
1068 if ($value =~ m/^\+/) {
1069 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1070 &$add_error($name, "no such ipset '$1'")
1071 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1074 &$add_error($name, "invalid ipset name '$value'");
1076 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1077 my $alias = lc($value);
1078 &$add_error($name, "no such alias '$value'")
1079 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}))
1084 my $type = $rule->{type
};
1085 my $action = $rule->{action
};
1087 &$add_error('type', "missing property") if !$type;
1088 &$add_error('action', "missing property") if !$action;
1091 if ($type eq 'in' || $type eq 'out') {
1092 &$add_error('action', "unknown action '$action'")
1093 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1094 } elsif ($type eq 'group') {
1095 &$add_error('type', "security groups not allowed")
1097 &$add_error('action', "invalid characters in security group name")
1098 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1100 &$add_error('type', "unknown rule type '$type'");
1104 if ($rule->{iface
}) {
1105 &$add_error('type', "parameter -i not allowed for this rule type")
1107 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1108 &$add_error('iface', $@) if $@;
1109 if ($rule_env eq 'vm') {
1110 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1111 if $rule->{iface
} !~ m/^net(\d+)$/;
1112 } elsif ($rule_env eq 'ct') {
1113 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1114 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1118 if ($rule->{macro}) {
1119 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1120 $rule->{macro} = $preferred_name;
1122 &$add_error('macro', "unknown macro '$rule->{macro}'");
1126 if ($rule->{proto
}) {
1127 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1128 &$add_error('proto', $@) if $@;
1131 if ($rule->{dport
}) {
1132 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1133 &$add_error('dport', $@) if $@;
1134 &$add_error('proto', "missing property - 'dport' requires this property")
1138 if ($rule->{sport
}) {
1139 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1140 &$add_error('sport', $@) if $@;
1141 &$add_error('proto', "missing property - 'sport' requires this property")
1145 if ($rule->{source
}) {
1146 eval { parse_address_list
($rule->{source
}); };
1147 &$add_error('source', $@) if $@;
1148 &$check_ipset_or_alias_property('source');
1151 if ($rule->{dest
}) {
1152 eval { parse_address_list
($rule->{dest
}); };
1153 &$add_error('dest', $@) if $@;
1154 &$check_ipset_or_alias_property('dest');
1157 if ($rule->{macro} && !$error_count) {
1158 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1160 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1161 my $eh = $err->{errors
};
1162 foreach my $p (keys %$eh) {
1163 &$add_error($p, $eh->{$p});
1166 &$add_error('macro', "$err");
1171 $rule->{errors
} = $errors if $error_count;
1176 sub copy_rule_data
{
1177 my ($rule, $param) = @_;
1179 foreach my $k (keys %$rule_properties) {
1180 if (defined(my $v = $param->{$k})) {
1181 if ($v eq '' || $v eq '-') {
1193 my $bridge_firewall_enabled = 0;
1195 sub enable_bridge_firewall
{
1197 return if $bridge_firewall_enabled; # only once
1199 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1200 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1202 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1203 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1205 $bridge_firewall_enabled = 1;
1208 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1210 sub iptables_restore_cmdlist
{
1213 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1216 sub ipset_restore_cmdlist
{
1219 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1222 sub iptables_get_chains
{
1226 # check what chains we want to track
1227 my $is_pvefw_chain = sub {
1230 return 1 if $name =~ m/^PVEFW-\S+$/;
1232 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1234 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1236 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1238 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1239 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1251 return if $line =~ m/^#/;
1252 return if $line =~ m/^\s*$/;
1254 if ($line =~ m/^\*(\S+)$/) {
1259 return if $table ne 'filter';
1261 if ($line =~ m/^:(\S+)\s/) {
1263 return if !&$is_pvefw_chain($chain);
1264 $res->{$chain} = "unknown";
1265 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1266 my ($chain, $sig) = ($1, $2);
1267 return if !&$is_pvefw_chain($chain);
1268 $res->{$chain} = $sig;
1269 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1272 # simply ignore the rest
1277 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1279 return wantarray ?
($res, $hooks) : $res;
1282 sub iptables_chain_digest
{
1284 my $digest = Digest
::SHA-
>new('sha1');
1285 foreach my $rule (@$rules) { # order is important
1286 $digest->add($rule);
1288 return $digest->b64digest;
1291 sub ipset_chain_digest
{
1294 my $digest = Digest
::SHA-
>new('sha1');
1295 foreach my $rule (sort @$rules) { # note: sorted
1296 $digest->add($rule);
1298 return $digest->b64digest;
1301 sub ipset_get_chains
{
1309 return if $line =~ m/^#/;
1310 return if $line =~ m/^\s*$/;
1311 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1313 $line =~ s/\s+$//; # delete trailing white space
1314 push @{$chains->{$chain}}, $line;
1316 # simply ignore the rest
1321 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1323 # compute digest for each chain
1324 foreach my $chain (keys %$chains) {
1325 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1331 sub ruleset_generate_cmdstr
{
1332 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1334 return if defined($rule->{enable
}) && !$rule->{enable
};
1335 return if $rule->{errors
};
1337 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1339 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1340 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1344 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1345 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1347 my $source = $rule->{source
};
1348 my $dest = $rule->{dest
};
1351 if ($source =~ m/^\+/) {
1352 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1354 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1355 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1356 push @cmd, "-m set --match-set ${ipset_chain} src";
1357 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1358 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1359 push @cmd, "-m set --match-set ${ipset_chain} src";
1361 die "no such ipset '$name'\n";
1364 die "invalid security group name '$source'\n";
1366 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1367 my $alias = lc($source);
1368 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1369 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1370 die "no such alias '$source'\n" if !$e;
1371 push @cmd, "-s $e->{cidr}";
1372 } elsif ($source =~ m/\-/){
1373 push @cmd, "-m iprange --src-range $source";
1375 push @cmd, "-s $source";
1380 if ($dest =~ m/^\+/) {
1381 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1383 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1384 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1385 push @cmd, "-m set --match-set ${ipset_chain} dst";
1386 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1387 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1388 push @cmd, "-m set --match-set ${ipset_chain} dst";
1390 die "no such ipset '$name'\n";
1393 die "invalid security group name '$dest'\n";
1395 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1396 my $alias = lc($dest);
1397 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1398 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1399 die "no such alias '$dest'\n" if !$e;
1400 push @cmd, "-d $e->{cidr}";
1401 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1402 push @cmd, "-m iprange --dst-range $dest";
1404 push @cmd, "-d $dest";
1408 if ($rule->{proto
}) {
1409 push @cmd, "-p $rule->{proto}";
1412 $multiport++ if $nbdport > 1;
1413 $multiport++ if $nbsport > 1;
1415 push @cmd, "--match multiport" if $multiport;
1417 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1418 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1420 if ($rule->{dport
}) {
1421 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1422 # Note: we use dport to store --icmp-type
1423 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1424 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1427 if ($multiport == 2) {
1428 push @cmd, "--ports $rule->{dport}";
1430 push @cmd, "--dports $rule->{dport}";
1433 push @cmd, "--dport $rule->{dport}";
1438 if ($rule->{sport
}) {
1440 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1442 push @cmd, "--sport $rule->{sport}";
1445 } elsif ($rule->{dport
} || $rule->{sport
}) {
1446 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1447 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1450 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1452 if (my $action = $rule->{action
}) {
1453 $action = $actions->{$action} if defined($actions->{$action});
1454 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1455 push @cmd, $goto ?
"-g $action" : "-j $action";
1458 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1461 sub ruleset_generate_rule
{
1462 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1466 if ($rule->{macro}) {
1467 $rules = &$apply_macro($rule->{macro}, $rule);
1472 # update all or nothing
1475 foreach my $tmp (@$rules) {
1476 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1477 push @cmds, $cmdstr;
1481 foreach my $cmdstr (@cmds) {
1482 ruleset_addrule
($ruleset, $chain, $cmdstr);
1486 sub ruleset_generate_rule_insert
{
1487 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1489 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1491 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1492 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1496 sub ruleset_create_chain
{
1497 my ($ruleset, $chain) = @_;
1499 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1500 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1502 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1504 $ruleset->{$chain} = [];
1507 sub ruleset_chain_exist
{
1508 my ($ruleset, $chain) = @_;
1510 return $ruleset->{$chain} ?
1 : undef;
1513 sub ruleset_addrule
{
1514 my ($ruleset, $chain, $rule) = @_;
1516 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1518 push @{$ruleset->{$chain}}, "-A $chain $rule";
1521 sub ruleset_insertrule
{
1522 my ($ruleset, $chain, $rule) = @_;
1524 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1526 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1529 sub get_log_rule_base
{
1530 my ($chain, $vmid, $msg, $loglevel) = @_;
1532 die "internal error - no log level" if !defined($loglevel);
1534 $vmid = 0 if !defined($vmid);
1536 # Note: we use special format for prefix to pass further
1537 # info to log daemon (VMID, LOGVELEL and CHAIN)
1539 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1542 sub ruleset_addlog {
1543 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1545 return if !defined($loglevel);
1547 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1549 $logrule = "$rule $logrule" if defined($rule);
1551 ruleset_addrule($ruleset, $chain, $logrule);
1554 sub ruleset_add_chain_policy {
1555 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1557 if ($policy eq 'ACCEPT') {
1559 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1560 { ACCEPT => $accept_action});
1562 } elsif ($policy eq 'DROP') {
1564 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1566 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1568 ruleset_addrule($ruleset, $chain, "-j DROP
");
1569 } elsif ($policy eq 'REJECT') {
1570 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1572 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1574 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1577 die "internal error
: unknown policy
'$policy'";
1581 sub ruleset_chain_add_conn_filters {
1582 my ($ruleset, $chain, $accept) = @_;
1584 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1585 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1588 sub ruleset_chain_add_input_filters {
1589 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1591 if ($cluster_conf->{ipset}->{blacklist}){
1592 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1593 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1594 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1595 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1597 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1598 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1601 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1602 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1605 if ($options->{tcpflags}) {
1606 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1610 sub ruleset_create_vm_chain {
1611 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1613 ruleset_create_chain($ruleset, $chain);
1614 my $accept = generate_nfqueue($options);
1616 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1617 if ($direction eq 'OUT') {
1618 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1619 proto => 'udp', sport => 68, dport => 67 });
1621 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1622 proto => 'udp', sport => 67, dport => 68 });
1626 if ($direction eq 'OUT') {
1627 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1628 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1630 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1634 sub ruleset_add_group_rule {
1635 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1637 my $group = $rule->{action};
1638 my $group_chain = "GROUP-
$group-$direction";
1639 if(!ruleset_chain_exist($ruleset, $group_chain)){
1640 generate_group_rules($ruleset, $cluster_conf, $group);
1643 if ($direction eq 'OUT' && $rule->{iface_out}) {
1644 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1645 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1646 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1648 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1651 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1654 sub ruleset_generate_vm_rules {
1655 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options) = @_;
1657 my $lc_direction = lc($direction);
1659 my $in_accept = generate_nfqueue($options);
1661 foreach my $rule (@$rules) {
1662 next if $rule->{iface} && $rule->{iface} ne $netid;
1663 next if !$rule->{enable} || $rule->{errors};
1664 if ($rule->{type} eq 'group') {
1665 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1666 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1668 next if $rule->{type} ne $lc_direction;
1670 if ($direction eq 'OUT') {
1671 ruleset_generate_rule($ruleset, $chain, $rule,
1672 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1673 undef, $cluster_conf, $vmfw_conf);
1675 ruleset_generate_rule($ruleset, $chain, $rule,
1676 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1677 undef, $cluster_conf, $vmfw_conf);
1685 sub generate_nfqueue {
1688 if ($options->{ips}) {
1689 my $action = "NFQUEUE
";
1690 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1691 if (defined($3) && defined($1)) {
1692 $action .= " --queue-balance
$1:$3";
1693 } elsif (defined($1)) {
1694 $action .= " --queue-num
$1";
1697 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1704 sub ruleset_generate_vm_ipsrules {
1705 my ($ruleset, $options, $direction, $iface) = @_;
1707 if ($options->{ips} && $direction eq 'IN') {
1708 my $nfqueue = generate_nfqueue($options);
1710 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1711 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1714 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1718 sub generate_venet_rules_direction {
1719 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1721 my $lc_direction = lc($direction);
1723 my $rules = $vmfw_conf->{rules};
1725 my $options = $vmfw_conf->{options};
1726 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1728 my $chain = "venet0-
$vmid-$direction";
1730 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1732 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction);
1737 if ($direction eq 'OUT') {
1738 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1740 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1743 my $accept = generate_nfqueue($options);
1744 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1745 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1747 if ($direction eq 'OUT') {
1748 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1751 iface_in => 'venet0'});
1753 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1756 iface_out => 'venet0'});
1760 sub generate_tap_rules_direction {
1761 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1763 my $lc_direction = lc($direction);
1765 my $rules = $vmfw_conf->{rules};
1767 my $options = $vmfw_conf->{options};
1768 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1770 my $tapchain = "$iface-$direction";
1772 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1774 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options);
1776 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1781 if ($direction eq 'OUT') {
1782 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1784 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1787 my $accept = generate_nfqueue($options);
1788 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1789 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1791 # plug the tap chain to bridge chain
1792 if ($direction eq 'IN') {
1793 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
1794 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1796 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
1797 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
1801 sub enable_host_firewall {
1802 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1804 my $options = $hostfw_conf->{options};
1805 my $cluster_options = $cluster_conf->{options};
1806 my $rules = $hostfw_conf->{rules};
1807 my $cluster_rules = $cluster_conf->{rules};
1809 # host inbound firewall
1810 my $chain = "PVEFW-HOST-IN
";
1811 ruleset_create_chain($ruleset, $chain);
1813 my $loglevel = get_option_log_level($options, "log_level_in
");
1815 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1817 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1818 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1820 # we use RETURN because we need to check also tap rules
1821 my $accept_action = 'RETURN';
1823 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1825 # add host rules first, so that cluster wide rules can be overwritten
1826 foreach my $rule (@$rules, @$cluster_rules) {
1827 next if !$rule->{enable} || $rule->{errors};
1829 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1832 if ($rule->{type} eq 'group') {
1833 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1834 } elsif ($rule->{type} eq 'in') {
1835 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1836 undef, $cluster_conf, $hostfw_conf);
1840 delete $rule->{iface_in};
1843 # allow standard traffic for management ipset (includes cluster network)
1844 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
1845 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
1846 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1847 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1848 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1849 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
1851 my $localnet = local_network();
1855 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1856 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
1857 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
1860 # implement input policy
1861 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1862 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1864 # host outbound firewall
1865 $chain = "PVEFW-HOST-OUT
";
1866 ruleset_create_chain($ruleset, $chain);
1868 $loglevel = get_option_log_level($options, "log_level_out
");
1870 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1872 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1874 # we use RETURN because we may want to check other thigs later
1875 $accept_action = 'RETURN';
1877 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1879 # add host rules first, so that cluster wide rules can be overwritten
1880 foreach my $rule (@$rules, @$cluster_rules) {
1881 next if !$rule->{enable} || $rule->{errors};
1883 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1885 if ($rule->{type} eq 'group') {
1886 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1887 } elsif ($rule->{type} eq 'out') {
1888 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1889 undef, $cluster_conf, $hostfw_conf);
1893 delete $rule->{iface_out};
1896 # allow standard traffic on cluster network
1898 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1899 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
1900 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1901 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1903 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1904 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
1905 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
1908 # implement output policy
1909 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1910 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1912 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1913 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1916 sub generate_group_rules {
1917 my ($ruleset, $cluster_conf, $group) = @_;
1919 my $rules = $cluster_conf->{groups}->{$group};
1922 warn "no such security group
'$group'\n";
1923 $rules = []; # create empty chain
1926 my $chain = "GROUP-
${group
}-IN
";
1928 ruleset_create_chain($ruleset, $chain);
1929 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1931 foreach my $rule (@$rules) {
1932 next if $rule->{type} ne 'in';
1933 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1936 $chain = "GROUP-
${group
}-OUT
";
1938 ruleset_create_chain($ruleset, $chain);
1939 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1941 foreach my $rule (@$rules) {
1942 next if $rule->{type} ne 'out';
1943 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1944 # check also other tap rules later
1945 ruleset_generate_rule($ruleset, $chain, $rule,
1946 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1951 my $valid_netdev_names = {};
1952 for (my $i = 0; $i < $MAX_NETS; $i++) {
1953 $valid_netdev_names->{"net
$i"} = 1;
1957 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
1961 my $orig_line = $line;
1965 # we can add single line comments to the end of the rule
1966 if ($line =~ s/#\s*(.*?)\s*$//) {
1967 $rule->{comment} = decode('utf8', $1);
1970 # we can disable a rule when prefixed with '|'
1972 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
1974 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1975 die "unable to parse rule
: $line\n";
1977 $rule->{type} = lc($1);
1978 $rule->{action} = $2;
1980 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1981 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1982 $rule->{macro} = $1;
1983 $rule->{action} = $2;
1987 while (length($line)) {
1988 if ($line =~ s/^-i (\S+)\s*//) {
1989 $rule->{iface} = $1;
1993 last if $rule->{type} eq 'group';
1995 if ($line =~ s/^-p (\S+)\s*//) {
1996 $rule->{proto} = $1;
2000 if ($line =~ s/^-dport (\S+)\s*//) {
2001 $rule->{dport} = $1;
2005 if ($line =~ s/^-sport (\S+)\s*//) {
2006 $rule->{sport} = $1;
2009 if ($line =~ s/^-source (\S+)\s*//) {
2010 $rule->{source} = $1;
2013 if ($line =~ s/^-dest (\S+)\s*//) {
2021 die "unable to parse rule parameters
: $line\n" if length($line);
2023 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2024 if ($verbose && $rule->{errors}) {
2025 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2026 foreach my $p (keys %{$rule->{errors}}) {
2027 warn " $p: $rule->{errors
}->{$p}\n";
2034 sub parse_vmfw_option {
2039 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2041 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2044 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2046 $value = $2 ? lc($3) : '';
2047 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2050 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2055 die "can
't parse option '$line'\n"
2058 return ($opt, $value);
2061 sub parse_hostfw_option {
2066 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2068 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2071 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2073 $value = $2 ? lc($3) : '';
2074 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2079 die "can't parse option
'$line'\n"
2082 return ($opt, $value);
2085 sub parse_clusterfw_option {
2090 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2093 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2098 die "can
't parse option '$line'\n"
2101 return ($opt, $value);
2107 # we can add single line comments to the end of the line
2108 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2110 if ($line =~ m/^(\S+)\s(\S+)$/) {
2111 my ($name, $cidr) = ($1, $2);
2113 pve_verify_ipv4_or_cidr($cidr);
2118 $data->{comment} = $comment if $comment;
2125 sub generic_fw_rules_parser {
2126 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2131 my $res = $empty_conf;
2133 my $ipset_option = get_standard_option('ipset-name
');
2135 while (defined(my $line = <$fh>)) {
2136 next if $line =~ m/^#/;
2137 next if $line =~ m/^\s*$/;
2139 my $linenr = $fh->input_line_number();
2140 my $prefix = "$filename (line $linenr)";
2142 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2143 $section = 'options
';
2147 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2148 $section = 'aliases
';
2152 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2153 $section = 'groups
';
2157 die "security group name too long\n" if length($group) > $max_group_name_length;
2158 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2161 ($section, $group, $comment) = undef;
2162 warn "$prefix: $err";
2166 $res->{$section}->{$group} = [];
2167 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2172 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2177 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2182 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2183 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2186 ($section, $group, $comment) = undef;
2187 warn "$prefix: $err";
2191 $res->{$section}->{$group} = [];
2192 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2198 warn "$prefix: skip line - no section\n";
2202 if ($section eq 'options
') {
2205 if ($rule_env eq 'cluster
') {
2206 ($opt, $value) = parse_clusterfw_option($line);
2207 } elsif ($rule_env eq 'host
') {
2208 ($opt, $value) = parse_hostfw_option($line);
2210 ($opt, $value) = parse_vmfw_option($line);
2212 $res->{options}->{$opt} = $value;
2214 warn "$prefix: $@" if $@;
2215 } elsif ($section eq 'aliases
') {
2217 my $data = parse_alias($line);
2218 $res->{aliases}->{lc($data->{name})} = $data;
2220 warn "$prefix: $@" if $@;
2221 } elsif ($section eq 'rules
') {
2223 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2225 warn "$prefix: $err";
2228 push @{$res->{$section}}, $rule;
2229 } elsif ($section eq 'groups
') {
2231 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2233 warn "$prefix: $err";
2236 push @{$res->{$section}->{$group}}, $rule;
2237 } elsif ($section eq 'ipset
') {
2238 # we can add single line comments to the end of the rule
2239 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2241 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2245 if($cidr !~ m/^${ip_alias_pattern}$/) {
2248 eval { pve_verify_ipv4_or_cidr($cidr); };
2250 warn "$prefix: $cidr - $err";
2255 my $entry = { cidr => $cidr };
2256 $entry->{nomatch} = 1 if $nomatch;
2257 $entry->{comment} = $comment if $comment;
2259 push @{$res->{$section}->{$group}}, $entry;
2261 warn "$prefix: skip line - unknown section\n";
2269 sub parse_host_fw_rules {
2270 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2272 my $empty_conf = { rules => [], options => {}};
2274 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2277 sub parse_vm_fw_rules {
2278 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2285 ipset_comments => {},
2288 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2291 sub parse_cluster_fw_rules {
2292 my ($filename, $fh, $verbose) = @_;
2302 group_comments => {},
2304 ipset_comments => {},
2307 return generic_fw_rules_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2311 my ($code, @param) = @_;
2315 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2322 sub read_local_vm_config {
2327 my $vmdata = { openvz => $openvz, qemu => $qemu };
2329 my $vmlist = PVE::Cluster::get_vmlist();
2330 return $vmdata if !$vmlist || !$vmlist->{ids};
2331 my $ids = $vmlist->{ids};
2333 foreach my $vmid (keys %$ids) {
2334 next if !$vmid; # skip VE0
2335 my $d = $ids->{$vmid};
2336 next if !$d->{node} || $d->{node} ne $nodename;
2337 next if !$d->{type};
2338 if ($d->{type} eq 'openvz
') {
2339 if ($have_pve_manager) {
2340 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2341 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2342 $openvz->{$vmid} = $conf;
2345 } elsif ($d->{type} eq 'qemu
') {
2346 if ($have_qemu_server) {
2347 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2348 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2349 $qemu->{$vmid} = $conf;
2358 sub load_vmfw_conf {
2359 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2363 $dir = "/etc/pve/firewall" if !defined($dir);
2365 my $filename = "$dir/$vmid.fw";
2366 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2367 $vmfw_conf = parse_vm_fw_rules($filename, $fh, $cluster_conf, $rule_env, $verbose);
2368 $vmfw_conf->{vmid} = $vmid;
2374 my $format_rules = sub {
2375 my ($rules, $allow_iface) = @_;
2379 foreach my $rule (@$rules) {
2380 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2381 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2382 $raw .= uc($rule->{type});
2383 if ($rule->{macro}) {
2384 $raw .= " $rule->{macro}($rule->{action})";
2386 $raw .= " " . $rule->{action};
2388 if ($allow_iface && $rule->{iface}) {
2389 $raw .= " -i $rule->{iface}";
2392 if ($rule->{type} ne 'group
') {
2393 $raw .= " -source $rule->{source}" if $rule->{source};
2394 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2395 $raw .= " -p $rule->{proto}" if $rule->{proto};
2396 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2397 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2400 $raw .= " # " . encode('utf8
', $rule->{comment})
2401 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2404 die "unknown rule type '$rule->{type
}'";
2411 my $format_options = sub {
2416 $raw .= "[OPTIONS]\n\n";
2417 foreach my $opt (keys %$options) {
2418 $raw .= "$opt: $options->{$opt}\n";
2425 my $format_aliases = sub {
2430 $raw .= "[ALIASES]\n\n";
2431 foreach my $k (keys %$aliases) {
2432 my $e = $aliases->{$k};
2433 $raw .= "$e->{name} $e->{cidr}";
2434 $raw .= " # " . encode('utf8
', $e->{comment})
2435 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2443 my $format_ipsets = sub {
2448 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2449 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2450 my $utf8comment = encode('utf8
', $comment);
2451 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2453 $raw .= "[IPSET $ipset]\n\n";
2455 my $options = $fw_conf->{ipset}->{$ipset};
2458 foreach my $entry (@$options) {
2459 $nethash->{$entry->{cidr}} = $entry;
2462 foreach my $cidr (sort keys %$nethash) {
2463 my $entry = $nethash->{$cidr};
2464 my $line = $entry->{nomatch} ? '!' : '';
2465 $line .= $entry->{cidr};
2466 $line .= " # " . encode('utf8
', $entry->{comment})
2467 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2477 sub save_vmfw_conf {
2478 my ($vmid, $vmfw_conf) = @_;
2482 my $options = $vmfw_conf->{options};
2483 $raw .= &$format_options($options) if scalar(keys %$options);
2485 my $aliases = $vmfw_conf->{aliases};
2486 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2488 $raw .= &$format_ipsets($vmfw_conf);
2490 my $rules = $vmfw_conf->{rules} || [];
2491 if (scalar(@$rules)) {
2492 $raw .= "[RULES]\n\n";
2493 $raw .= &$format_rules($rules, 1);
2497 my $filename = "/etc/pve/firewall/$vmid.fw";
2498 PVE::Tools::file_set_contents($filename, $raw);
2501 sub read_vm_firewall_configs {
2502 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2504 my $vmfw_configs = {};
2506 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2507 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2508 next if !$vmfw_conf->{options}; # skip if file does not exists
2509 $vmfw_configs->{$vmid} = $vmfw_conf;
2511 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2512 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2513 next if !$vmfw_conf->{options}; # skip if file does not exists
2514 $vmfw_configs->{$vmid} = $vmfw_conf;
2517 return $vmfw_configs;
2520 sub get_option_log_level {
2521 my ($options, $k) = @_;
2523 my $v = $options->{$k};
2524 $v = $default_log_level if !defined($v);
2526 return undef if $v eq '' || $v eq 'nolog
';
2528 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2530 return $v if ($v >= 0) && ($v <= 7);
2532 warn "unknown log level ($k = '$v')\n";
2537 sub generate_std_chains {
2538 my ($ruleset, $options) = @_;
2540 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2542 # same as shorewall smurflog.
2543 my $chain = 'PVEFW-smurflog
';
2544 $pve_std_chains->{$chain} = [];
2546 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2547 push @{$pve_std_chains->{$chain}}, "-j DROP";
2549 # same as shorewall logflags action.
2550 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2551 $chain = 'PVEFW-logflags
';
2552 $pve_std_chains->{$chain} = [];
2554 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2555 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2556 push @{$pve_std_chains->{$chain}}, "-j DROP";
2558 foreach my $chain (keys %$pve_std_chains) {
2559 ruleset_create_chain($ruleset, $chain);
2560 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2562 ruleset_generate_rule($ruleset, $chain, $rule);
2564 ruleset_addrule($ruleset, $chain, $rule);
2570 sub generate_ipset_chains {
2571 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2573 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2574 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2575 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2579 sub generate_ipset {
2580 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2582 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2584 my $hashsize = scalar(@$options);
2585 if ($hashsize <= 64) {
2588 $hashsize = round_powerof2($hashsize);
2591 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
2595 foreach my $entry (@$options) {
2596 my $cidr = $entry->{cidr};
2597 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2598 my $alias = lc($cidr);
2599 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2600 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2602 $entry->{cidr} = $e->{cidr};
2603 $nethash->{$entry->{cidr}} = $entry;
2605 warn "no such alias '$cidr'\n";
2608 $nethash->{$entry->{cidr}} = $entry;
2612 foreach my $cidr (sort keys %$nethash) {
2613 my $entry = $nethash->{$cidr};
2615 my $cmd = "add $name $cidr";
2616 if ($entry->{nomatch}) {
2617 if ($feature_ipset_nomatch) {
2618 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2620 warn "ignore !$cidr - nomatch not supported by kernel\n";
2623 push @{$ipset_ruleset->{$name}}, $cmd;
2628 sub round_powerof2 {
2632 $int |= $int >> $_ foreach (1,2,4,8,16);
2636 sub load_clusterfw_conf {
2637 my ($filename, $verbose) = @_;
2639 $filename = $clusterfw_conf_filename if !defined($filename);
2641 my $cluster_conf = {};
2642 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2643 $cluster_conf = parse_cluster_fw_rules($filename, $fh, $verbose);
2646 return $cluster_conf;
2649 sub save_clusterfw_conf {
2650 my ($cluster_conf) = @_;
2654 my $options = $cluster_conf->{options};
2655 $raw .= &$format_options($options) if scalar(keys %$options);
2657 my $aliases = $cluster_conf->{aliases};
2658 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2660 $raw .= &$format_ipsets($cluster_conf);
2662 my $rules = $cluster_conf->{rules};
2663 if (scalar(@$rules)) {
2664 $raw .= "[RULES]\n\n";
2665 $raw .= &$format_rules($rules, 1);
2669 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2670 my $rules = $cluster_conf->{groups}->{$group};
2671 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2672 my $utf8comment = encode('utf8
', $comment);
2673 $raw .= "[group $group] # $utf8comment\n\n";
2675 $raw .= "[group $group]\n\n";
2678 $raw .= &$format_rules($rules, 0);
2682 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2685 sub load_hostfw_conf {
2686 my ($cluster_conf, $filename, $verbose) = @_;
2688 $filename = $hostfw_conf_filename if !defined($filename);
2690 my $hostfw_conf = {};
2691 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2692 $hostfw_conf = parse_host_fw_rules($filename, $fh, $cluster_conf, $verbose);
2694 return $hostfw_conf;
2697 sub save_hostfw_conf {
2698 my ($hostfw_conf) = @_;
2702 my $options = $hostfw_conf->{options};
2703 $raw .= &$format_options($options) if scalar(keys %$options);
2705 my $rules = $hostfw_conf->{rules};
2706 if (scalar(@$rules)) {
2707 $raw .= "[RULES]\n\n";
2708 $raw .= &$format_rules($rules, 1);
2712 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2716 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2720 if ($vmdata) { # test mode
2721 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2722 my $filename = "$testdir/cluster.fw";
2723 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2725 $filename = "$testdir/host.fw";
2726 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2728 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2729 } else { # normal operation
2730 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2732 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2734 $vmdata = read_local_vm_config();
2735 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2738 $cluster_conf->{ipset}->{venet0} = [];
2739 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
2742 if ($cluster_conf->{aliases}->{local_network}) {
2743 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2745 $localnet = local_network() || '127.0.0.0/8';
2746 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2749 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2753 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2754 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2756 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2758 my $hostfw_options = $hostfw_conf->{options} || {};
2760 # fixme: what log level should we use here?
2761 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2763 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2766 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2767 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2768 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2770 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2771 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2773 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2775 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2776 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2778 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2779 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2781 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2783 generate_std_chains($ruleset, $hostfw_options);
2785 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2787 my $ipset_ruleset = {};
2789 if ($hostfw_enable) {
2790 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2791 warn $@ if $@; # just to be sure - should not happen
2794 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2796 # generate firewall rules for QEMU VMs
2797 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2799 my $conf = $vmdata->{qemu}->{$vmid};
2800 my $vmfw_conf = $vmfw_configs->{$vmid};
2801 return if !$vmfw_conf;
2802 return if !$vmfw_conf->{options}->{enable};
2804 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2806 foreach my $netid (keys %$conf) {
2807 next if $netid !~ m/^net(\d+)$/;
2808 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2809 next if !$net->{firewall};
2810 my $iface = "tap${vmid}i$1";
2812 my $macaddr = $net->{macaddr};
2813 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2814 $vmfw_conf, $vmid, 'IN
');
2815 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2816 $vmfw_conf, $vmid, 'OUT
');
2819 warn $@ if $@; # just to be sure - should not happen
2822 # generate firewall rules for OpenVZ containers
2823 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2825 my $conf = $vmdata->{openvz}->{$vmid};
2827 my $vmfw_conf = $vmfw_configs->{$vmid};
2828 return if !$vmfw_conf;
2829 return if !$vmfw_conf->{options}->{enable};
2831 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2833 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2834 my $ip = $conf->{ip_address}->{value};
2836 parse_address_list($ip); # make sure we have a valid $ip list
2838 my @ips = split(',', $ip);
2840 foreach my $singleip (@ips) {
2841 my $venet0ipset = {};
2842 $venet0ipset->{cidr} = $singleip;
2843 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2846 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2847 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2850 if ($conf->{netif} && $conf->{netif}->{value}) {
2851 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2852 foreach my $netid (keys %$netif) {
2853 my $d = $netif->{$netid};
2855 my $macaddr = $d->{mac};
2856 my $iface = $d->{host_ifname};
2857 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2858 $vmfw_conf, $vmid, 'IN
');
2859 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2860 $vmfw_conf, $vmid, 'OUT
');
2864 warn $@ if $@; # just to be sure - should not happen
2867 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2868 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2871 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
2873 return ($ruleset, $ipset_ruleset);
2876 sub get_ruleset_status {
2877 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2879 my $statushash = {};
2881 foreach my $chain (sort keys %$ruleset) {
2882 my $sig = &$digest_fn($ruleset->{$chain});
2884 $statushash->{$chain}->{sig} = $sig;
2886 my $oldsig = $active_chains->{$chain};
2887 if (!defined($oldsig)) {
2888 $statushash->{$chain}->{action} = 'create
';
2890 if ($oldsig eq $sig) {
2891 $statushash->{$chain}->{action} = 'exists';
2893 $statushash->{$chain}->{action} = 'update
';
2896 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2897 foreach my $cmd (@{$ruleset->{$chain}}) {
2898 print "\t$cmd\n" if $verbose;
2902 foreach my $chain (sort keys %$active_chains) {
2903 if (!defined($ruleset->{$chain})) {
2904 my $sig = $active_chains->{$chain};
2905 $statushash->{$chain}->{action} = 'delete';
2906 $statushash->{$chain}->{sig} = $sig;
2907 print "delete $chain ($sig)\n" if $verbose;
2914 sub print_sig_rule {
2915 my ($chain, $sig) = @_;
2917 # We just use this to store a SHA1 checksum used to detect changes
2918 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2921 sub get_ruleset_cmdlist {
2922 my ($ruleset, $verbose) = @_;
2924 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2926 my ($active_chains, $hooks) = iptables_get_chains();
2927 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2929 # create missing chains first
2930 foreach my $chain (sort keys %$ruleset) {
2931 my $stat = $statushash->{$chain};
2932 die "internal error" if !$stat;
2933 next if $stat->{action} ne 'create
';
2935 $cmdlist .= ":$chain - [0:0]\n";
2938 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2939 if (!$hooks->{$h}) {
2940 $cmdlist .= "-A $h -j PVEFW-$h\n";
2944 foreach my $chain (sort keys %$ruleset) {
2945 my $stat = $statushash->{$chain};
2946 die "internal error" if !$stat;
2948 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2949 $cmdlist .= "-F $chain\n";
2950 foreach my $cmd (@{$ruleset->{$chain}}) {
2951 $cmdlist .= "$cmd\n";
2953 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2954 } elsif ($stat->{action
} eq 'delete') {
2955 die "internal error"; # this should not happen
2956 } elsif ($stat->{action
} eq 'exists') {
2959 die "internal error - unknown status '$stat->{action}'";
2963 foreach my $chain (keys %$statushash) {
2964 next if $statushash->{$chain}->{action
} ne 'delete';
2965 $cmdlist .= "-F $chain\n";
2967 foreach my $chain (keys %$statushash) {
2968 next if $statushash->{$chain}->{action
} ne 'delete';
2969 next if $chain eq 'PVEFW-INPUT';
2970 next if $chain eq 'PVEFW-OUTPUT';
2971 next if $chain eq 'PVEFW-FORWARD';
2972 $cmdlist .= "-X $chain\n";
2975 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2977 $cmdlist .= "COMMIT\n";
2979 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2982 sub get_ipset_cmdlist
{
2983 my ($ruleset, $verbose) = @_;
2987 my $delete_cmdlist = "";
2989 my $active_chains = ipset_get_chains
();
2990 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2992 # remove stale _swap chains
2993 foreach my $chain (keys %$active_chains) {
2994 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2995 $cmdlist .= "destroy $chain\n";
2999 foreach my $chain (sort keys %$ruleset) {
3000 my $stat = $statushash->{$chain};
3001 die "internal error" if !$stat;
3003 if ($stat->{action
} eq 'create') {
3004 foreach my $cmd (@{$ruleset->{$chain}}) {
3005 $cmdlist .= "$cmd\n";
3009 if ($stat->{action
} eq 'update') {
3010 my $chain_swap = $chain."_swap";
3012 foreach my $cmd (@{$ruleset->{$chain}}) {
3013 $cmd =~ s/$chain/$chain_swap/;
3014 $cmdlist .= "$cmd\n";
3016 $cmdlist .= "swap $chain_swap $chain\n";
3017 $cmdlist .= "flush $chain_swap\n";
3018 $cmdlist .= "destroy $chain_swap\n";
3023 foreach my $chain (keys %$statushash) {
3024 next if $statushash->{$chain}->{action
} ne 'delete';
3026 $delete_cmdlist .= "flush $chain\n";
3027 $delete_cmdlist .= "destroy $chain\n";
3030 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3032 return ($cmdlist, $delete_cmdlist, $changes);
3036 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3038 enable_bridge_firewall
();
3040 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3041 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3043 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3046 if ($ipset_changes) {
3047 print "ipset changes:\n";
3048 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3049 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3053 print "iptables changes:\n";
3058 ipset_restore_cmdlist
($ipset_create_cmdlist);
3060 iptables_restore_cmdlist
($cmdlist);
3062 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3064 # test: re-read status and check if everything is up to date
3065 my $active_chains = iptables_get_chains
();
3066 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3069 foreach my $chain (sort keys %$ruleset) {
3070 my $stat = $statushash->{$chain};
3071 if ($stat->{action
} ne 'exists') {
3072 warn "unable to update chain '$chain'\n";
3077 die "unable to apply firewall changes\n" if $errors;
3079 update_nf_conntrack_max
($hostfw_conf);
3081 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3085 sub update_nf_conntrack_max
{
3086 my ($hostfw_conf) = @_;
3088 my $max = 65536; # reasonable default
3090 my $options = $hostfw_conf->{options
} || {};
3092 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3093 $max = $options->{nf_conntrack_max
};
3094 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3097 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3098 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3100 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3102 if ($current != $max) {
3103 my $hashsize = int($max/4);
3104 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3105 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3109 sub update_nf_conntrack_tcp_timeout_established
{
3110 my ($hostfw_conf) = @_;
3112 my $options = $hostfw_conf->{options
} || {};
3114 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3116 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3119 sub remove_pvefw_chains
{
3121 my ($chash, $hooks) = iptables_get_chains
();
3122 my $cmdlist = "*filter\n";
3124 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3126 $cmdlist .= "-D $h -j PVEFW-$h\n";
3130 foreach my $chain (keys %$chash) {
3131 $cmdlist .= "-F $chain\n";
3134 foreach my $chain (keys %$chash) {
3135 $cmdlist .= "-X $chain\n";
3137 $cmdlist .= "COMMIT\n";
3139 iptables_restore_cmdlist
($cmdlist);
3143 my $cluster_conf = load_clusterfw_conf
();
3144 my $cluster_options = $cluster_conf->{options
};
3145 my $enable = $cluster_options->{enable
};
3149 # load required modules here
3155 my $cluster_conf = load_clusterfw_conf
();
3156 my $cluster_options = $cluster_conf->{options
};
3158 my $enable = $cluster_options->{enable
};
3160 die "Firewall is disabled - cannot start\n" if !$enable;
3163 PVE
::Firewall
::remove_pvefw_chains
();
3167 my $hostfw_conf = load_hostfw_conf
();
3169 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3171 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset);