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 $pvefw_conf_dir = "/etc/pve/firewall";
23 my $clusterfw_conf_filename = "$pvefw_conf_dir/cluster.fw";
25 # dynamically include PVE::QemuServer and PVE::OpenVZ
26 # to avoid dependency problems
29 require PVE
::QemuServer
;
30 $have_qemu_server = 1;
36 $have_pve_manager = 1;
39 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
40 my $ipset_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
41 my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
43 my $max_alias_name_length = 64;
44 my $max_ipset_name_length = 64;
45 my $max_group_name_length = 20;
47 PVE
::JSONSchema
::register_format
('IPv4orCIDR', \
&pve_verify_ipv4_or_cidr
);
48 sub pve_verify_ipv4_or_cidr
{
49 my ($cidr, $noerr) = @_;
51 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
52 return $cidr if Net
::IP-
>new($cidr);
53 return undef if $noerr;
54 die Net
::IP
::Error
() . "\n";
56 return undef if $noerr;
57 die "value does not look like a valid IP address or CIDR network\n";
60 PVE
::JSONSchema
::register_format
('IPv4orCIDRorAlias', \
&pve_verify_ipv4_or_cidr_or_alias
);
61 sub pve_verify_ipv4_or_cidr_or_alias
{
62 my ($cidr, $noerr) = @_;
64 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
66 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
67 return $cidr if Net
::IP-
>new($cidr);
68 return undef if $noerr;
69 die Net
::IP
::Error
() . "\n";
71 return undef if $noerr;
72 die "value does not look like a valid IP address or CIDR network\n";
75 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
76 description
=> "IP set name.",
78 pattern
=> $ipset_name_pattern,
80 maxLength
=> $max_ipset_name_length,
83 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
84 description
=> "Alias name.",
86 pattern
=> $ip_alias_pattern,
88 maxLength
=> $max_alias_name_length,
91 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
92 description
=> "Log level.",
94 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
98 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
99 description
=> "Security Group name.",
101 pattern
=> $security_group_name_pattern,
103 maxLength
=> $max_group_name_length,
106 my $feature_ipset_nomatch = 0;
108 my (undef, undef, $release) = POSIX
::uname
();
109 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
110 my ($major, $minor) = ($1, $2);
111 $feature_ipset_nomatch = 1 if ($major > 3) ||
112 ($major == 3 && $minor >= 7);
119 my $nodename = PVE
::INotify
::nodename
();
121 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
123 my $default_log_level = 'nolog'; # avoid logs by default
125 my $log_level_hash = {
136 # imported/converted from: /usr/share/shorewall/macro.*
137 my $pve_fw_macros = {
140 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
141 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
144 "Auth (identd) traffic",
145 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
148 "Border Gateway Protocol traffic",
149 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
152 "BitTorrent traffic for BitTorrent 3.1 and earlier",
153 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
154 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
157 "BitTorrent traffic for BitTorrent 3.2 and later",
158 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
159 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
162 "Concurrent Versions System pserver traffic",
163 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
166 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
167 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
168 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
169 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
172 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
173 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
174 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
177 "Distributed Checksum Clearinghouse spam filtering mechanism",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
181 "Forwarded DHCP traffic",
182 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
185 "Domain Name System traffic (upd and tcp)",
186 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
187 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
190 "Distributed Compiler service",
191 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
194 "File Transfer Protocol",
195 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
198 "Finger protocol (RFC 742)",
199 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
202 "GNUnet secure peer-to-peer networking traffic",
203 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
204 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
205 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
206 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
209 "Generic Routing Encapsulation tunneling protocol",
210 { action
=> 'PARAM', proto
=> '47' },
213 "Git distributed revision control traffic",
214 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
217 "OpenPGP HTTP keyserver protocol traffic",
218 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
221 "Hypertext Transfer Protocol (WWW)",
222 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
225 "Hypertext Transfer Protocol (WWW) over SSL",
226 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
229 "Internet Cache Protocol V2 (Squid) traffic",
230 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
233 "AOL Instant Messenger traffic",
234 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
237 "Internet Message Access Protocol",
238 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
241 "Internet Message Access Protocol over SSL",
242 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
245 "IPIP capsulation traffic",
246 { action
=> 'PARAM', proto
=> '94' },
250 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
251 { action
=> 'PARAM', proto
=> '50' },
254 "IPsec authentication (AH) traffic",
255 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
256 { action
=> 'PARAM', proto
=> '51' },
259 "IPsec traffic and Nat-Traversal",
260 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
261 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
262 { action
=> 'PARAM', proto
=> '50' },
265 "Internet Relay Chat traffic",
266 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
269 "HP Jetdirect printing",
270 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
273 "Layer 2 Tunneling Protocol traffic",
274 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
277 "Lightweight Directory Access Protocol traffic",
278 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
281 "Secure Lightweight Directory Access Protocol traffic",
282 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
285 "Microsoft Notification Protocol",
286 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
289 "Microsoft SQL Server",
290 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
293 "Mail traffic (SMTP, SMTPS, Submission)",
294 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
296 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
299 "Munin networked resource monitoring traffic",
300 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
304 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
307 "NNTP traffic (Usenet).",
308 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
311 "Encrypted NNTP traffic (Usenet)",
312 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
315 "Network Time Protocol (ntpd)",
316 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
319 "OSPF multicast traffic",
320 { action
=> 'PARAM', proto
=> '89' },
324 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
327 "Symantec PCAnywere (tm)",
328 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
336 "Encrypted POP3 traffic",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
340 "Point-to-Point Tunneling Protocol",
341 { action
=> 'PARAM', proto
=> '47' },
342 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
346 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
350 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
353 "Line Printer protocol printing",
354 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
357 "Microsoft Remote Desktop Protocol traffic",
358 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
361 "Routing Information Protocol (bidirectional)",
362 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
365 "BIND remote management protocol",
366 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
369 "Razor Antispam System",
370 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
373 "Remote time retrieval (rdate)",
374 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
378 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
381 "SANE network scanning",
382 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
385 "Microsoft SMB traffic",
386 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
387 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
388 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
392 "Samba Web Administration Tool",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
396 "Simple Mail Transfer Protocol",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
400 "Encrypted Simple Mail Transfer Protocol",
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
404 "Simple Network Management Protocol",
405 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
406 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
409 "Spam Assassin SPAMD traffic",
410 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
413 "Secure shell traffic",
414 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
417 "Subversion server (svnserve)",
418 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
421 "SixXS IPv6 Deployment and Tunnel Broker",
422 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
423 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
424 { action
=> 'PARAM', proto
=> '41' },
425 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
428 "Squid web proxy traffic",
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
432 "Mail message submission traffic",
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
436 "Syslog protocol (RFC 5424) traffic",
437 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
438 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
441 "Trivial File Transfer Protocol traffic",
442 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
453 "RFC 868 Time protocol",
454 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
457 "Traceroute (for up to 30 hops) traffic",
458 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
459 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
462 "VNC traffic for VNC display's 0 - 99",
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
466 "VNC traffic from Vncservers to Vncviewers in listen mode",
467 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
470 "WWW traffic (HTTP and HTTPS)",
471 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
472 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
475 "Web Cache/Proxy traffic (port 8080)",
476 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
480 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
483 "Whois (nicname, RFC 3912) traffic",
484 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
488 my $pve_fw_parsed_macros;
489 my $pve_fw_macro_descr;
490 my $pve_fw_preferred_macro_names = {};
492 my $pve_std_chains = {
493 'PVEFW-SET-ACCEPT-MARK' => [
494 "-j MARK --set-mark 1",
496 'PVEFW-DropBroadcast' => [
497 # same as shorewall 'Broadcast'
498 # simply DROP BROADCAST/MULTICAST/ANYCAST
499 # we can use this to reduce logging
500 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
501 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
502 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
503 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
506 # same as shorewall 'reject'
507 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
508 { action
=> 'DROP', source
=> '224.0.0.0/4' },
509 { action
=> 'DROP', proto
=> 'icmp' },
510 "-p tcp -j REJECT --reject-with tcp-reset",
511 "-p udp -j REJECT --reject-with icmp-port-unreachable",
512 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
513 "-j REJECT --reject-with icmp-host-prohibited",
516 # same as shorewall 'Drop', which is equal to DROP,
517 # but REJECT/DROP some packages to reduce logging,
518 # and ACCEPT critical ICMP types
519 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
520 # we are not interested in BROADCAST/MULTICAST/ANYCAST
521 { action
=> 'PVEFW-DropBroadcast' },
522 # ACCEPT critical ICMP types
523 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
524 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
525 # Drop packets with INVALID state
526 "-m conntrack --ctstate INVALID -j DROP",
527 # Drop Microsoft SMB noise
528 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
529 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
530 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
531 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
532 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
533 # Drop new/NotSyn traffic so that it doesn't get logged
534 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
536 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
539 # same as shorewall 'Reject', which is equal to Reject,
540 # but REJECT/DROP some packages to reduce logging,
541 # and ACCEPT critical ICMP types
542 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
543 # we are not interested in BROADCAST/MULTICAST/ANYCAST
544 { action
=> 'PVEFW-DropBroadcast' },
545 # ACCEPT critical ICMP types
546 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
547 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
548 # Drop packets with INVALID state
549 "-m conntrack --ctstate INVALID -j DROP",
550 # Drop Microsoft SMB noise
551 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
552 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
553 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
554 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
555 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
556 # Drop new/NotSyn traffic so that it doesn't get logged
557 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
559 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
561 'PVEFW-tcpflags' => [
562 # same as shorewall tcpflags action.
563 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
564 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
565 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
566 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
567 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
568 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
571 # same as shorewall smurfs action
572 # Filter packets for smurfs (packets with a broadcast address as the source).
573 "-s 0.0.0.0/32 -j RETURN",
574 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
575 "-s 224.0.0.0/4 -g PVEFW-smurflog",
579 # iptables -p icmp -h
580 my $icmp_type_names = {
583 'destination-unreachable' => 1,
584 'network-unreachable' => 1,
585 'host-unreachable' => 1,
586 'protocol-unreachable' => 1,
587 'port-unreachable' => 1,
588 'fragmentation-needed' => 1,
589 'source-route-failed' => 1,
590 'network-unknown' => 1,
592 'network-prohibited' => 1,
593 'host-prohibited' => 1,
594 'TOS-network-unreachable' => 1,
595 'TOS-host-unreachable' => 1,
596 'communication-prohibited' => 1,
597 'host-precedence-violation' => 1,
598 'precedence-cutoff' => 1,
599 'source-quench' => 1,
601 'network-redirect' => 1,
602 'host-redirect' => 1,
603 'TOS-network-redirect' => 1,
604 'TOS-host-redirect' => 1,
606 'router-advertisement' => 1,
607 'router-solicitation' => 1,
608 'time-exceeded' => 1,
609 'ttl-zero-during-transit' => 1,
610 'ttl-zero-during-reassembly' => 1,
611 'parameter-problem' => 1,
612 'ip-header-bad' => 1,
613 'required-option-missing' => 1,
614 'timestamp-request' => 1,
615 'timestamp-reply' => 1,
616 'address-mask-request' => 1,
617 'address-mask-reply' => 1,
620 sub init_firewall_macros
{
622 $pve_fw_parsed_macros = {};
624 foreach my $k (keys %$pve_fw_macros) {
625 my $lc_name = lc($k);
626 my $macro = $pve_fw_macros->{$k};
627 if (!ref($macro->[0])) {
628 $pve_fw_macro_descr->{$k} = shift @$macro;
630 $pve_fw_preferred_macro_names->{$lc_name} = $k;
631 $pve_fw_parsed_macros->{$k} = $macro;
635 init_firewall_macros
();
638 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
643 sub get_etc_services
{
645 return $etc_services if $etc_services;
647 my $filename = "/etc/services";
649 my $fh = IO
::File-
>new($filename, O_RDONLY
);
651 warn "unable to read '$filename' - $!\n";
657 while (my $line = <$fh>) {
659 next if $line =~m/^#/;
660 next if ($line =~m/^\s*$/);
662 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
663 $services->{byid
}->{$2}->{name
} = $1;
664 $services->{byid
}->{$2}->{port
} = $2;
665 $services->{byid
}->{$2}->{$3} = 1;
666 $services->{byname
}->{$1} = $services->{byid
}->{$2};
672 $etc_services = $services;
675 return $etc_services;
680 sub get_etc_protocols
{
681 return $etc_protocols if $etc_protocols;
683 my $filename = "/etc/protocols";
685 my $fh = IO
::File-
>new($filename, O_RDONLY
);
687 warn "unable to read '$filename' - $!\n";
693 while (my $line = <$fh>) {
695 next if $line =~m/^#/;
696 next if ($line =~m/^\s*$/);
698 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
699 $protocols->{byid
}->{$2}->{name
} = $1;
700 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
706 $etc_protocols = $protocols;
708 return $etc_protocols;
711 my $ipv4_mask_hash_localnet = {
713 '255.255.128.0' => 17,
714 '255.255.192.0' => 18,
715 '255.255.224.0' => 19,
716 '255.255.240.0' => 20,
717 '255.255.248.0' => 21,
718 '255.255.252.0' => 22,
719 '255.255.254.0' => 23,
720 '255.255.255.0' => 24,
721 '255.255.255.128' => 25,
722 '255.255.255.192' => 26,
723 '255.255.255.224' => 27,
724 '255.255.255.240' => 28,
725 '255.255.255.248' => 29,
726 '255.255.255.252' => 30,
732 my ($new_value) = @_;
734 $__local_network = $new_value if defined($new_value);
736 return $__local_network if defined($__local_network);
739 my $nodename = PVE
::INotify
::nodename
();
741 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
743 my $testip = Net
::IP-
>new($ip);
745 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
746 foreach my $entry (@$routes) {
747 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
748 next if !defined($mask);
749 return if $mask eq '0.0.0.0';
750 my $cidr = "$entry->{dest}/$mask";
751 my $testnet = Net
::IP-
>new($cidr);
752 if ($testnet->overlaps($testip)) {
753 $__local_network = $cidr;
760 return $__local_network;
763 my $max_iptables_ipset_name_length = 27;
765 sub compute_ipset_chain_name
{
766 my ($vmid, $ipset_name) = @_;
768 $vmid = 0 if !defined($vmid);
770 my $id = "$vmid-${ipset_name}";
773 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
774 $id = PVE
::Tools
::fnv31a_hex
($id);
780 sub parse_address_list
{
783 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
784 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
788 if ($str =~ m/^${ip_alias_pattern}$/) {
789 die "alias name too long\n" if length($str) > $max_alias_name_length;
795 foreach my $elem (split(/,/, $str)) {
797 if (!Net
::IP-
>new($elem)) {
798 my $err = Net
::IP
::Error
();
799 die "invalid IP address: $err\n";
801 $iprange = 1 if $elem =~ m/-/;
804 die "you can use a range in a list\n" if $iprange && $count > 1;
807 sub parse_port_name_number_or_range
{
810 my $services = PVE
::Firewall
::get_etc_services
();
814 foreach my $item (split(/,/, $str)) {
816 if ($item =~ m/^(\d+):(\d+)$/) {
817 my ($port1, $port2) = ($1, $2);
818 die "invalid port '$port1'\n" if $port1 > 65535;
819 die "invalid port '$port2'\n" if $port2 > 65535;
820 } elsif ($item =~ m/^(\d+)$/) {
822 die "invalid port '$port'\n" if $port > 65535;
824 if ($icmp_type_names->{$item}) {
827 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
832 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
837 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
838 sub pve_fw_verify_port_spec
{
841 parse_port_name_number_or_range
($portstr);
846 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
847 sub pve_fw_verify_v4addr_spec
{
850 parse_address_list
($list);
855 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
856 sub pve_fw_verify_protocol_spec
{
859 my $protocols = get_etc_protocols
();
861 die "unknown protocol '$proto'\n" if $proto &&
862 !(defined($protocols->{byname
}->{$proto}) ||
863 defined($protocols->{byid
}->{$proto}));
869 # helper function for API
871 sub copy_opject_with_digest
{
874 my $sha = Digest
::SHA-
>new('sha1');
877 foreach my $k (sort keys %$object) {
878 my $v = $object->{$k};
879 next if !defined($v);
881 $sha->add($k, ':', $v, "\n");
884 my $digest = $sha->hexdigest;
886 $res->{digest
} = $digest;
888 return wantarray ?
($res, $digest) : $res;
891 sub copy_list_with_digest
{
894 my $sha = Digest
::SHA-
>new('sha1');
897 foreach my $entry (@$list) {
899 foreach my $k (sort keys %$entry) {
900 my $v = $entry->{$k};
901 next if !defined($v);
903 # Note: digest ignores refs ($rule->{errors})
904 $sha->add($k, ':', $v, "\n") if !ref($v); ;
909 my $digest = $sha->hexdigest;
911 foreach my $entry (@$res) {
912 $entry->{digest
} = $digest;
915 return wantarray ?
($res, $digest) : $res;
918 my $rule_properties = {
920 description
=> "Update rule at position <pos>.",
925 digest
=> get_standard_option
('pve-config-digest'),
929 enum
=> ['in', 'out', 'group'],
932 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
935 pattern
=> $security_group_name_pattern,
944 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
946 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
950 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
954 type
=> 'string', format
=> 'pve-fw-protocol-spec',
962 type
=> 'string', format
=> 'pve-fw-port-spec',
966 type
=> 'string', format
=> 'pve-fw-port-spec',
975 sub add_rule_properties
{
976 my ($properties) = @_;
978 foreach my $k (keys %$rule_properties) {
979 my $h = $rule_properties->{$k};
980 # copy data, so that we can modify later without side effects
981 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
987 sub delete_rule_properties
{
988 my ($rule, $delete_str) = @_;
990 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
991 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
992 if !defined($rule_properties->{$opt});
993 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
994 if $opt eq 'type' || $opt eq 'action';
995 delete $rule->{$opt};
1001 my $apply_macro = sub {
1002 my ($macro_name, $param, $verify) = @_;
1004 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1005 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1009 foreach my $templ (@$macro_rules) {
1011 my $param_used = {};
1012 foreach my $k (keys %$templ) {
1013 my $v = $templ->{$k};
1014 if ($v eq 'PARAM') {
1016 $param_used->{$k} = 1;
1017 } elsif ($v eq 'DEST') {
1018 $v = $param->{dest
};
1019 $param_used->{dest
} = 1;
1020 } elsif ($v eq 'SOURCE') {
1021 $v = $param->{source
};
1022 $param_used->{source
} = 1;
1026 my $msg = "missing parameter '$k' in macro '$macro_name'";
1027 raise_param_exc
({ macro => $msg }) if $verify;
1032 foreach my $k (keys %$param) {
1033 next if $k eq 'macro';
1034 next if !defined($param->{$k});
1035 next if $param_used->{$k};
1036 if (defined($rule->{$k})) {
1037 if ($rule->{$k} ne $param->{$k}) {
1038 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1039 raise_param_exc
({ $k => $msg }) if $verify;
1043 $rule->{$k} = $param->{$k};
1046 push @$rules, $rule;
1052 my $rule_env_iface_lookup = {
1061 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1063 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1065 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1066 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1068 my $errors = $rule->{errors
} || {};
1070 my $error_count = 0;
1072 my $add_error = sub {
1073 my ($param, $msg) = @_;
1075 raise_param_exc
({ $param => $msg }) if !$noerr;
1077 $errors->{$param} = $msg if !$errors->{$param};
1080 my $check_ipset_or_alias_property = sub {
1083 if (my $value = $rule->{$name}) {
1084 if ($value =~ m/^\+/) {
1085 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1086 &$add_error($name, "no such ipset '$1'")
1087 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1090 &$add_error($name, "invalid ipset name '$value'");
1092 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1093 my $alias = lc($value);
1094 &$add_error($name, "no such alias '$value'")
1095 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}))
1100 my $type = $rule->{type
};
1101 my $action = $rule->{action
};
1103 &$add_error('type', "missing property") if !$type;
1104 &$add_error('action', "missing property") if !$action;
1107 if ($type eq 'in' || $type eq 'out') {
1108 &$add_error('action', "unknown action '$action'")
1109 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1110 } elsif ($type eq 'group') {
1111 &$add_error('type', "security groups not allowed")
1113 &$add_error('action', "invalid characters in security group name")
1114 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1116 &$add_error('type', "unknown rule type '$type'");
1120 if ($rule->{iface
}) {
1121 &$add_error('type', "parameter -i not allowed for this rule type")
1123 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1124 &$add_error('iface', $@) if $@;
1125 if ($rule_env eq 'vm') {
1126 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1127 if $rule->{iface
} !~ m/^net(\d+)$/;
1128 } elsif ($rule_env eq 'ct') {
1129 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1130 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1134 if ($rule->{macro}) {
1135 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1136 $rule->{macro} = $preferred_name;
1138 &$add_error('macro', "unknown macro '$rule->{macro}'");
1142 if ($rule->{proto
}) {
1143 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1144 &$add_error('proto', $@) if $@;
1147 if ($rule->{dport
}) {
1148 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1149 &$add_error('dport', $@) if $@;
1150 &$add_error('proto', "missing property - 'dport' requires this property")
1154 if ($rule->{sport
}) {
1155 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1156 &$add_error('sport', $@) if $@;
1157 &$add_error('proto', "missing property - 'sport' requires this property")
1161 if ($rule->{source
}) {
1162 eval { parse_address_list
($rule->{source
}); };
1163 &$add_error('source', $@) if $@;
1164 &$check_ipset_or_alias_property('source');
1167 if ($rule->{dest
}) {
1168 eval { parse_address_list
($rule->{dest
}); };
1169 &$add_error('dest', $@) if $@;
1170 &$check_ipset_or_alias_property('dest');
1173 if ($rule->{macro} && !$error_count) {
1174 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1176 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1177 my $eh = $err->{errors
};
1178 foreach my $p (keys %$eh) {
1179 &$add_error($p, $eh->{$p});
1182 &$add_error('macro', "$err");
1187 $rule->{errors
} = $errors if $error_count;
1192 sub copy_rule_data
{
1193 my ($rule, $param) = @_;
1195 foreach my $k (keys %$rule_properties) {
1196 if (defined(my $v = $param->{$k})) {
1197 if ($v eq '' || $v eq '-') {
1209 my $bridge_firewall_enabled = 0;
1211 sub enable_bridge_firewall
{
1213 return if $bridge_firewall_enabled; # only once
1215 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1216 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1218 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1219 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1221 $bridge_firewall_enabled = 1;
1224 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1226 sub iptables_restore_cmdlist
{
1229 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1232 sub ipset_restore_cmdlist
{
1235 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1238 sub iptables_get_chains
{
1242 # check what chains we want to track
1243 my $is_pvefw_chain = sub {
1246 return 1 if $name =~ m/^PVEFW-\S+$/;
1248 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1250 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1252 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1254 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1255 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1267 return if $line =~ m/^#/;
1268 return if $line =~ m/^\s*$/;
1270 if ($line =~ m/^\*(\S+)$/) {
1275 return if $table ne 'filter';
1277 if ($line =~ m/^:(\S+)\s/) {
1279 return if !&$is_pvefw_chain($chain);
1280 $res->{$chain} = "unknown";
1281 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1282 my ($chain, $sig) = ($1, $2);
1283 return if !&$is_pvefw_chain($chain);
1284 $res->{$chain} = $sig;
1285 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1288 # simply ignore the rest
1293 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1295 return wantarray ?
($res, $hooks) : $res;
1298 sub iptables_chain_digest
{
1300 my $digest = Digest
::SHA-
>new('sha1');
1301 foreach my $rule (@$rules) { # order is important
1302 $digest->add($rule);
1304 return $digest->b64digest;
1307 sub ipset_chain_digest
{
1310 my $digest = Digest
::SHA-
>new('sha1');
1311 foreach my $rule (sort @$rules) { # note: sorted
1312 $digest->add($rule);
1314 return $digest->b64digest;
1317 sub ipset_get_chains
{
1325 return if $line =~ m/^#/;
1326 return if $line =~ m/^\s*$/;
1327 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1329 $line =~ s/\s+$//; # delete trailing white space
1330 push @{$chains->{$chain}}, $line;
1332 # simply ignore the rest
1337 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1339 # compute digest for each chain
1340 foreach my $chain (keys %$chains) {
1341 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1347 sub ruleset_generate_cmdstr
{
1348 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1350 return if defined($rule->{enable
}) && !$rule->{enable
};
1351 return if $rule->{errors
};
1353 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1355 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1356 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1360 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1361 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1363 my $source = $rule->{source
};
1364 my $dest = $rule->{dest
};
1367 if ($source =~ m/^\+/) {
1368 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1370 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1371 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1372 push @cmd, "-m set --match-set ${ipset_chain} src";
1373 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1374 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1375 push @cmd, "-m set --match-set ${ipset_chain} src";
1377 die "no such ipset '$name'\n";
1380 die "invalid security group name '$source'\n";
1382 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1383 my $alias = lc($source);
1384 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1385 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1386 die "no such alias '$source'\n" if !$e;
1387 push @cmd, "-s $e->{cidr}";
1388 } elsif ($source =~ m/\-/){
1389 push @cmd, "-m iprange --src-range $source";
1391 push @cmd, "-s $source";
1396 if ($dest =~ m/^\+/) {
1397 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1399 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1400 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1401 push @cmd, "-m set --match-set ${ipset_chain} dst";
1402 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1403 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1404 push @cmd, "-m set --match-set ${ipset_chain} dst";
1406 die "no such ipset '$name'\n";
1409 die "invalid security group name '$dest'\n";
1411 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1412 my $alias = lc($dest);
1413 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1414 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1415 die "no such alias '$dest'\n" if !$e;
1416 push @cmd, "-d $e->{cidr}";
1417 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1418 push @cmd, "-m iprange --dst-range $dest";
1420 push @cmd, "-d $dest";
1424 if ($rule->{proto
}) {
1425 push @cmd, "-p $rule->{proto}";
1428 $multiport++ if $nbdport > 1;
1429 $multiport++ if $nbsport > 1;
1431 push @cmd, "--match multiport" if $multiport;
1433 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1434 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1436 if ($rule->{dport
}) {
1437 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1438 # Note: we use dport to store --icmp-type
1439 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1440 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1443 if ($multiport == 2) {
1444 push @cmd, "--ports $rule->{dport}";
1446 push @cmd, "--dports $rule->{dport}";
1449 push @cmd, "--dport $rule->{dport}";
1454 if ($rule->{sport
}) {
1456 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1458 push @cmd, "--sport $rule->{sport}";
1461 } elsif ($rule->{dport
} || $rule->{sport
}) {
1462 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1463 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1466 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1468 if (my $action = $rule->{action
}) {
1469 $action = $actions->{$action} if defined($actions->{$action});
1470 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1471 push @cmd, $goto ?
"-g $action" : "-j $action";
1474 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1477 sub ruleset_generate_rule
{
1478 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1482 if ($rule->{macro}) {
1483 $rules = &$apply_macro($rule->{macro}, $rule);
1488 # update all or nothing
1491 foreach my $tmp (@$rules) {
1492 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1493 push @cmds, $cmdstr;
1497 foreach my $cmdstr (@cmds) {
1498 ruleset_addrule
($ruleset, $chain, $cmdstr);
1502 sub ruleset_generate_rule_insert
{
1503 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1505 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1507 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1508 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1512 sub ruleset_create_chain
{
1513 my ($ruleset, $chain) = @_;
1515 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1516 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1518 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1520 $ruleset->{$chain} = [];
1523 sub ruleset_chain_exist
{
1524 my ($ruleset, $chain) = @_;
1526 return $ruleset->{$chain} ?
1 : undef;
1529 sub ruleset_addrule
{
1530 my ($ruleset, $chain, $rule) = @_;
1532 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1534 push @{$ruleset->{$chain}}, "-A $chain $rule";
1537 sub ruleset_insertrule
{
1538 my ($ruleset, $chain, $rule) = @_;
1540 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1542 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1545 sub get_log_rule_base
{
1546 my ($chain, $vmid, $msg, $loglevel) = @_;
1548 die "internal error - no log level" if !defined($loglevel);
1550 $vmid = 0 if !defined($vmid);
1552 # Note: we use special format for prefix to pass further
1553 # info to log daemon (VMID, LOGVELEL and CHAIN)
1555 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1558 sub ruleset_addlog {
1559 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1561 return if !defined($loglevel);
1563 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1565 $logrule = "$rule $logrule" if defined($rule);
1567 ruleset_addrule($ruleset, $chain, $logrule);
1570 sub ruleset_add_chain_policy {
1571 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1573 if ($policy eq 'ACCEPT') {
1575 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1576 { ACCEPT => $accept_action});
1578 } elsif ($policy eq 'DROP') {
1580 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1582 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1584 ruleset_addrule($ruleset, $chain, "-j DROP
");
1585 } elsif ($policy eq 'REJECT') {
1586 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1588 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1590 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1593 die "internal error
: unknown policy
'$policy'";
1597 sub ruleset_chain_add_conn_filters {
1598 my ($ruleset, $chain, $accept) = @_;
1600 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1601 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1604 sub ruleset_chain_add_input_filters {
1605 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1607 if ($cluster_conf->{ipset}->{blacklist}){
1608 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1609 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1610 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1611 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1613 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1614 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1617 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1618 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1621 if ($options->{tcpflags}) {
1622 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1626 sub ruleset_create_vm_chain {
1627 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1629 ruleset_create_chain($ruleset, $chain);
1630 my $accept = generate_nfqueue($options);
1632 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1633 if ($direction eq 'OUT') {
1634 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1635 proto => 'udp', sport => 68, dport => 67 });
1637 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1638 proto => 'udp', sport => 67, dport => 68 });
1642 if ($direction eq 'OUT') {
1643 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1644 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1646 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1650 sub ruleset_add_group_rule {
1651 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1653 my $group = $rule->{action};
1654 my $group_chain = "GROUP-
$group-$direction";
1655 if(!ruleset_chain_exist($ruleset, $group_chain)){
1656 generate_group_rules($ruleset, $cluster_conf, $group);
1659 if ($direction eq 'OUT' && $rule->{iface_out}) {
1660 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1661 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1662 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1664 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1667 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1670 sub ruleset_generate_vm_rules {
1671 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options) = @_;
1673 my $lc_direction = lc($direction);
1675 my $in_accept = generate_nfqueue($options);
1677 foreach my $rule (@$rules) {
1678 next if $rule->{iface} && $rule->{iface} ne $netid;
1679 next if !$rule->{enable} || $rule->{errors};
1680 if ($rule->{type} eq 'group') {
1681 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1682 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1684 next if $rule->{type} ne $lc_direction;
1686 if ($direction eq 'OUT') {
1687 ruleset_generate_rule($ruleset, $chain, $rule,
1688 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1689 undef, $cluster_conf, $vmfw_conf);
1691 ruleset_generate_rule($ruleset, $chain, $rule,
1692 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1693 undef, $cluster_conf, $vmfw_conf);
1701 sub generate_nfqueue {
1704 if ($options->{ips}) {
1705 my $action = "NFQUEUE
";
1706 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1707 if (defined($3) && defined($1)) {
1708 $action .= " --queue-balance
$1:$3";
1709 } elsif (defined($1)) {
1710 $action .= " --queue-num
$1";
1713 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1720 sub ruleset_generate_vm_ipsrules {
1721 my ($ruleset, $options, $direction, $iface) = @_;
1723 if ($options->{ips} && $direction eq 'IN') {
1724 my $nfqueue = generate_nfqueue($options);
1726 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1727 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1730 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1734 sub generate_venet_rules_direction {
1735 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1737 my $lc_direction = lc($direction);
1739 my $rules = $vmfw_conf->{rules};
1741 my $options = $vmfw_conf->{options};
1742 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1744 my $chain = "venet0-
$vmid-$direction";
1746 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1748 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction);
1753 if ($direction eq 'OUT') {
1754 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1756 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1759 my $accept = generate_nfqueue($options);
1760 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1761 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1763 if ($direction eq 'OUT') {
1764 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1767 iface_in => 'venet0'});
1769 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1772 iface_out => 'venet0'});
1776 sub generate_tap_rules_direction {
1777 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1779 my $lc_direction = lc($direction);
1781 my $rules = $vmfw_conf->{rules};
1783 my $options = $vmfw_conf->{options};
1784 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1786 my $tapchain = "$iface-$direction";
1788 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1790 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options);
1792 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1797 if ($direction eq 'OUT') {
1798 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1800 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1803 my $accept = generate_nfqueue($options);
1804 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1805 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1807 # plug the tap chain to bridge chain
1808 if ($direction eq 'IN') {
1809 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
1810 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1812 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
1813 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
1817 sub enable_host_firewall {
1818 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1820 my $options = $hostfw_conf->{options};
1821 my $cluster_options = $cluster_conf->{options};
1822 my $rules = $hostfw_conf->{rules};
1823 my $cluster_rules = $cluster_conf->{rules};
1825 # host inbound firewall
1826 my $chain = "PVEFW-HOST-IN
";
1827 ruleset_create_chain($ruleset, $chain);
1829 my $loglevel = get_option_log_level($options, "log_level_in
");
1831 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1833 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1834 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1836 # we use RETURN because we need to check also tap rules
1837 my $accept_action = 'RETURN';
1839 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1841 # add host rules first, so that cluster wide rules can be overwritten
1842 foreach my $rule (@$rules, @$cluster_rules) {
1843 next if !$rule->{enable} || $rule->{errors};
1845 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1848 if ($rule->{type} eq 'group') {
1849 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1850 } elsif ($rule->{type} eq 'in') {
1851 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1852 undef, $cluster_conf, $hostfw_conf);
1856 delete $rule->{iface_in};
1859 # allow standard traffic for management ipset (includes cluster network)
1860 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
1861 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
1862 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1863 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1864 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1865 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
1867 my $localnet = local_network();
1871 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1872 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
1873 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
1876 # implement input policy
1877 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1878 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1880 # host outbound firewall
1881 $chain = "PVEFW-HOST-OUT
";
1882 ruleset_create_chain($ruleset, $chain);
1884 $loglevel = get_option_log_level($options, "log_level_out
");
1886 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1888 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1890 # we use RETURN because we may want to check other thigs later
1891 $accept_action = 'RETURN';
1893 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1895 # add host rules first, so that cluster wide rules can be overwritten
1896 foreach my $rule (@$rules, @$cluster_rules) {
1897 next if !$rule->{enable} || $rule->{errors};
1899 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1901 if ($rule->{type} eq 'group') {
1902 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1903 } elsif ($rule->{type} eq 'out') {
1904 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1905 undef, $cluster_conf, $hostfw_conf);
1909 delete $rule->{iface_out};
1912 # allow standard traffic on cluster network
1914 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1915 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
1916 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1917 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1919 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1920 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
1921 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
1924 # implement output policy
1925 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1926 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1928 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1929 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1932 sub generate_group_rules {
1933 my ($ruleset, $cluster_conf, $group) = @_;
1935 my $rules = $cluster_conf->{groups}->{$group};
1938 warn "no such security group
'$group'\n";
1939 $rules = []; # create empty chain
1942 my $chain = "GROUP-
${group
}-IN
";
1944 ruleset_create_chain($ruleset, $chain);
1945 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1947 foreach my $rule (@$rules) {
1948 next if $rule->{type} ne 'in';
1949 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1952 $chain = "GROUP-
${group
}-OUT
";
1954 ruleset_create_chain($ruleset, $chain);
1955 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1957 foreach my $rule (@$rules) {
1958 next if $rule->{type} ne 'out';
1959 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1960 # check also other tap rules later
1961 ruleset_generate_rule($ruleset, $chain, $rule,
1962 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1967 my $valid_netdev_names = {};
1968 for (my $i = 0; $i < $MAX_NETS; $i++) {
1969 $valid_netdev_names->{"net
$i"} = 1;
1973 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
1975 my $orig_line = $line;
1979 # we can add single line comments to the end of the rule
1980 if ($line =~ s/#\s*(.*?)\s*$//) {
1981 $rule->{comment} = decode('utf8', $1);
1984 # we can disable a rule when prefixed with '|'
1986 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
1988 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1989 die "unable to parse rule
: $line\n";
1991 $rule->{type} = lc($1);
1992 $rule->{action} = $2;
1994 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1995 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1996 $rule->{macro} = $1;
1997 $rule->{action} = $2;
2001 while (length($line)) {
2002 if ($line =~ s/^-i (\S+)\s*//) {
2003 $rule->{iface} = $1;
2007 last if $rule->{type} eq 'group';
2009 if ($line =~ s/^-p (\S+)\s*//) {
2010 $rule->{proto} = $1;
2014 if ($line =~ s/^-dport (\S+)\s*//) {
2015 $rule->{dport} = $1;
2019 if ($line =~ s/^-sport (\S+)\s*//) {
2020 $rule->{sport} = $1;
2023 if ($line =~ s/^-source (\S+)\s*//) {
2024 $rule->{source} = $1;
2027 if ($line =~ s/^-dest (\S+)\s*//) {
2035 die "unable to parse rule parameters
: $line\n" if length($line);
2037 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2038 if ($verbose && $rule->{errors}) {
2039 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2040 foreach my $p (keys %{$rule->{errors}}) {
2041 warn " $p: $rule->{errors
}->{$p}\n";
2048 sub parse_vmfw_option {
2053 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2055 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2058 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2060 $value = $2 ? lc($3) : '';
2061 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2064 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2068 die "can
't parse option '$line'\n"
2071 return ($opt, $value);
2074 sub parse_hostfw_option {
2079 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2081 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2084 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2086 $value = $2 ? lc($3) : '';
2087 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2091 die "can't parse option
'$line'\n"
2094 return ($opt, $value);
2097 sub parse_clusterfw_option {
2102 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2105 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2109 die "can
't parse option '$line'\n"
2112 return ($opt, $value);
2116 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2118 if ($cidr !~ m/^\d/) {
2119 my $alias = lc($cidr);
2120 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2121 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2122 return $e->{cidr} if $e;
2124 die "no such alias '$cidr'\n";
2133 # we can add single line comments to the end of the line
2134 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2136 if ($line =~ m/^(\S+)\s(\S+)$/) {
2137 my ($name, $cidr) = ($1, $2);
2139 pve_verify_ipv4_or_cidr($cidr);
2144 $data->{comment} = $comment if $comment;
2151 sub generic_fw_config_parser {
2152 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2157 my $res = $empty_conf;
2159 while (defined(my $line = <$fh>)) {
2160 next if $line =~ m/^#/;
2161 next if $line =~ m/^\s*$/;
2165 my $linenr = $fh->input_line_number();
2166 my $prefix = "$filename (line $linenr)";
2168 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2169 $section = 'options
';
2173 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2174 $section = 'aliases
';
2178 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2179 $section = 'groups
';
2183 die "security group name too long\n" if length($group) > $max_group_name_length;
2184 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2187 ($section, $group, $comment) = undef;
2188 warn "$prefix: $err";
2192 $res->{$section}->{$group} = [];
2193 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2198 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2203 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2208 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2209 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2212 ($section, $group, $comment) = undef;
2213 warn "$prefix: $err";
2217 $res->{$section}->{$group} = [];
2218 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2224 warn "$prefix: skip line - no section\n";
2228 if ($section eq 'options
') {
2231 if ($rule_env eq 'cluster
') {
2232 ($opt, $value) = parse_clusterfw_option($line);
2233 } elsif ($rule_env eq 'host
') {
2234 ($opt, $value) = parse_hostfw_option($line);
2236 ($opt, $value) = parse_vmfw_option($line);
2238 $res->{options}->{$opt} = $value;
2240 warn "$prefix: $@" if $@;
2241 } elsif ($section eq 'aliases
') {
2243 my $data = parse_alias($line);
2244 $res->{aliases}->{lc($data->{name})} = $data;
2246 warn "$prefix: $@" if $@;
2247 } elsif ($section eq 'rules
') {
2249 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2251 warn "$prefix: $err";
2254 push @{$res->{$section}}, $rule;
2255 } elsif ($section eq 'groups
') {
2257 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2259 warn "$prefix: $err";
2262 push @{$res->{$section}->{$group}}, $rule;
2263 } elsif ($section eq 'ipset
') {
2264 # we can add single line comments to the end of the rule
2265 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2267 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2272 if ($nomatch && !$feature_ipset_nomatch) {
2273 $errors->{nomatch} = "nomatch not supported by kernel";
2277 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2278 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2281 pve_verify_ipv4_or_cidr_or_alias($cidr);
2286 $errors->{cidr} = $err;
2289 my $entry = { cidr => $cidr };
2290 $entry->{nomatch} = 1 if $nomatch;
2291 $entry->{comment} = $comment if $comment;
2292 $entry->{errors} = $errors if $errors;
2294 if ($verbose && $errors) {
2295 warn "$prefix - errors in ipset '$group': $line\n";
2296 foreach my $p (keys %{$errors}) {
2297 warn " $p: $errors->{$p}\n";
2301 push @{$res->{$section}->{$group}}, $entry;
2303 warn "$prefix: skip line - unknown section\n";
2311 sub parse_hostfw_config {
2312 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2314 my $empty_conf = { rules => [], options => {}};
2316 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2319 sub parse_vmfw_config {
2320 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2327 ipset_comments => {},
2330 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2333 sub parse_clusterfw_config {
2334 my ($filename, $fh, $verbose) = @_;
2344 group_comments => {},
2346 ipset_comments => {},
2349 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2353 my ($code, @param) = @_;
2357 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2364 sub read_local_vm_config {
2369 my $vmdata = { openvz => $openvz, qemu => $qemu };
2371 my $vmlist = PVE::Cluster::get_vmlist();
2372 return $vmdata if !$vmlist || !$vmlist->{ids};
2373 my $ids = $vmlist->{ids};
2375 foreach my $vmid (keys %$ids) {
2376 next if !$vmid; # skip VE0
2377 my $d = $ids->{$vmid};
2378 next if !$d->{node} || $d->{node} ne $nodename;
2379 next if !$d->{type};
2380 if ($d->{type} eq 'openvz
') {
2381 if ($have_pve_manager) {
2382 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2383 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2384 $openvz->{$vmid} = $conf;
2387 } elsif ($d->{type} eq 'qemu
') {
2388 if ($have_qemu_server) {
2389 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2390 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2391 $qemu->{$vmid} = $conf;
2400 sub load_vmfw_conf {
2401 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2405 $dir = $pvefw_conf_dir if !defined($dir);
2407 my $filename = "$dir/$vmid.fw";
2408 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2409 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2410 $vmfw_conf->{vmid} = $vmid;
2416 my $format_rules = sub {
2417 my ($rules, $allow_iface) = @_;
2421 foreach my $rule (@$rules) {
2422 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2423 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2424 $raw .= uc($rule->{type});
2425 if ($rule->{macro}) {
2426 $raw .= " $rule->{macro}($rule->{action})";
2428 $raw .= " " . $rule->{action};
2430 if ($allow_iface && $rule->{iface}) {
2431 $raw .= " -i $rule->{iface}";
2434 if ($rule->{type} ne 'group
') {
2435 $raw .= " -source $rule->{source}" if $rule->{source};
2436 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2437 $raw .= " -p $rule->{proto}" if $rule->{proto};
2438 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2439 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2442 $raw .= " # " . encode('utf8
', $rule->{comment})
2443 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2446 die "unknown rule type '$rule->{type
}'";
2453 my $format_options = sub {
2458 $raw .= "[OPTIONS]\n\n";
2459 foreach my $opt (keys %$options) {
2460 $raw .= "$opt: $options->{$opt}\n";
2467 my $format_aliases = sub {
2472 $raw .= "[ALIASES]\n\n";
2473 foreach my $k (keys %$aliases) {
2474 my $e = $aliases->{$k};
2475 $raw .= "$e->{name} $e->{cidr}";
2476 $raw .= " # " . encode('utf8
', $e->{comment})
2477 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2485 my $format_ipsets = sub {
2490 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2491 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2492 my $utf8comment = encode('utf8
', $comment);
2493 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2495 $raw .= "[IPSET $ipset]\n\n";
2497 my $options = $fw_conf->{ipset}->{$ipset};
2500 foreach my $entry (@$options) {
2501 $nethash->{$entry->{cidr}} = $entry;
2504 foreach my $cidr (sort keys %$nethash) {
2505 my $entry = $nethash->{$cidr};
2506 my $line = $entry->{nomatch} ? '!' : '';
2507 $line .= $entry->{cidr};
2508 $line .= " # " . encode('utf8
', $entry->{comment})
2509 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2519 sub save_vmfw_conf {
2520 my ($vmid, $vmfw_conf) = @_;
2524 my $options = $vmfw_conf->{options};
2525 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2527 my $aliases = $vmfw_conf->{aliases};
2528 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2530 $raw .= &$format_ipsets($vmfw_conf) if $vmfw_conf->{ipset};
2532 my $rules = $vmfw_conf->{rules} || [];
2533 if ($rules && scalar(@$rules)) {
2534 $raw .= "[RULES]\n\n";
2535 $raw .= &$format_rules($rules, 1);
2539 mkdir $pvefw_conf_dir;
2541 my $filename = "$pvefw_conf_dir/$vmid.fw";
2542 PVE::Tools::file_set_contents($filename, $raw);
2545 sub read_vm_firewall_configs {
2546 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2548 my $vmfw_configs = {};
2550 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2551 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2552 next if !$vmfw_conf->{options}; # skip if file does not exists
2553 $vmfw_configs->{$vmid} = $vmfw_conf;
2555 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2556 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2557 next if !$vmfw_conf->{options}; # skip if file does not exists
2558 $vmfw_configs->{$vmid} = $vmfw_conf;
2561 return $vmfw_configs;
2564 sub get_option_log_level {
2565 my ($options, $k) = @_;
2567 my $v = $options->{$k};
2568 $v = $default_log_level if !defined($v);
2570 return undef if $v eq '' || $v eq 'nolog
';
2572 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2574 return $v if ($v >= 0) && ($v <= 7);
2576 warn "unknown log level ($k = '$v')\n";
2581 sub generate_std_chains {
2582 my ($ruleset, $options) = @_;
2584 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2586 # same as shorewall smurflog.
2587 my $chain = 'PVEFW-smurflog
';
2588 $pve_std_chains->{$chain} = [];
2590 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2591 push @{$pve_std_chains->{$chain}}, "-j DROP";
2593 # same as shorewall logflags action.
2594 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2595 $chain = 'PVEFW-logflags
';
2596 $pve_std_chains->{$chain} = [];
2598 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2599 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2600 push @{$pve_std_chains->{$chain}}, "-j DROP";
2602 foreach my $chain (keys %$pve_std_chains) {
2603 ruleset_create_chain($ruleset, $chain);
2604 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2606 ruleset_generate_rule($ruleset, $chain, $rule);
2608 ruleset_addrule($ruleset, $chain, $rule);
2614 sub generate_ipset_chains {
2615 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2617 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2618 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2619 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2623 sub generate_ipset {
2624 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2626 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2628 my $hashsize = scalar(@$options);
2629 if ($hashsize <= 64) {
2632 $hashsize = round_powerof2($hashsize);
2635 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
2639 foreach my $entry (@$options) {
2640 next if $entry->{errors}; # skip entries with errors
2642 my $cidr = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2643 $nethash->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2648 foreach my $cidr (sort keys %$nethash) {
2649 my $entry = $nethash->{$cidr};
2651 my $cmd = "add $name $cidr";
2652 if ($entry->{nomatch}) {
2653 if ($feature_ipset_nomatch) {
2654 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2656 warn "ignore !$cidr - nomatch not supported by kernel\n";
2659 push @{$ipset_ruleset->{$name}}, $cmd;
2664 sub round_powerof2 {
2668 $int |= $int >> $_ foreach (1,2,4,8,16);
2672 sub load_clusterfw_conf {
2673 my ($filename, $verbose) = @_;
2675 $filename = $clusterfw_conf_filename if !defined($filename);
2677 my $cluster_conf = {};
2678 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2679 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
2682 return $cluster_conf;
2685 sub save_clusterfw_conf {
2686 my ($cluster_conf) = @_;
2690 my $options = $cluster_conf->{options};
2691 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2693 my $aliases = $cluster_conf->{aliases};
2694 $raw .= &$format_aliases($aliases) if $aliases && scalar(keys %$aliases);
2696 $raw .= &$format_ipsets($cluster_conf) if $cluster_conf->{ipset};
2698 my $rules = $cluster_conf->{rules};
2699 if ($rules && scalar(@$rules)) {
2700 $raw .= "[RULES]\n\n";
2701 $raw .= &$format_rules($rules, 1);
2705 if ($cluster_conf->{groups}) {
2706 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2707 my $rules = $cluster_conf->{groups}->{$group};
2708 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2709 my $utf8comment = encode('utf8
', $comment);
2710 $raw .= "[group $group] # $utf8comment\n\n";
2712 $raw .= "[group $group]\n\n";
2715 $raw .= &$format_rules($rules, 0);
2720 mkdir $pvefw_conf_dir;
2721 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2724 sub load_hostfw_conf {
2725 my ($cluster_conf, $filename, $verbose) = @_;
2727 $filename = $hostfw_conf_filename if !defined($filename);
2729 my $hostfw_conf = {};
2730 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2731 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
2733 return $hostfw_conf;
2736 sub save_hostfw_conf {
2737 my ($hostfw_conf) = @_;
2741 my $options = $hostfw_conf->{options};
2742 $raw .= &$format_options($options) if $options && scalar(keys %$options);
2744 my $rules = $hostfw_conf->{rules};
2745 if ($rules && scalar(@$rules)) {
2746 $raw .= "[RULES]\n\n";
2747 $raw .= &$format_rules($rules, 1);
2751 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2755 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2759 if ($vmdata) { # test mode
2760 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2761 my $filename = "$testdir/cluster.fw";
2762 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2764 $filename = "$testdir/host.fw";
2765 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2767 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2768 } else { # normal operation
2769 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2771 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2773 $vmdata = read_local_vm_config();
2774 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2777 $cluster_conf->{ipset}->{venet0} = [];
2778 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
2781 if ($cluster_conf->{aliases}->{local_network}) {
2782 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2784 $localnet = local_network() || '127.0.0.0/8';
2785 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2788 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2790 return ({}, {}) if !$cluster_conf->{options}->{enable};
2794 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2795 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2797 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2799 my $hostfw_options = $hostfw_conf->{options} || {};
2801 # fixme: what log level should we use here?
2802 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2804 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2807 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2808 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2809 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2811 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2812 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2814 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2816 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2817 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2819 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2820 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2822 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2824 generate_std_chains($ruleset, $hostfw_options);
2826 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2828 my $ipset_ruleset = {};
2830 if ($hostfw_enable) {
2831 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2832 warn $@ if $@; # just to be sure - should not happen
2835 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2837 # generate firewall rules for QEMU VMs
2838 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2840 my $conf = $vmdata->{qemu}->{$vmid};
2841 my $vmfw_conf = $vmfw_configs->{$vmid};
2842 return if !$vmfw_conf;
2843 return if !$vmfw_conf->{options}->{enable};
2845 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2847 foreach my $netid (keys %$conf) {
2848 next if $netid !~ m/^net(\d+)$/;
2849 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2850 next if !$net->{firewall};
2851 my $iface = "tap${vmid}i$1";
2853 my $macaddr = $net->{macaddr};
2854 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2855 $vmfw_conf, $vmid, 'IN
');
2856 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2857 $vmfw_conf, $vmid, 'OUT
');
2860 warn $@ if $@; # just to be sure - should not happen
2863 # generate firewall rules for OpenVZ containers
2864 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2866 my $conf = $vmdata->{openvz}->{$vmid};
2868 my $vmfw_conf = $vmfw_configs->{$vmid};
2869 return if !$vmfw_conf;
2870 return if !$vmfw_conf->{options}->{enable};
2872 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2874 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2875 my $ip = $conf->{ip_address}->{value};
2877 parse_address_list($ip); # make sure we have a valid $ip list
2879 my @ips = split(',', $ip);
2881 foreach my $singleip (@ips) {
2882 my $venet0ipset = {};
2883 $venet0ipset->{cidr} = $singleip;
2884 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2887 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2888 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2891 if ($conf->{netif} && $conf->{netif}->{value}) {
2892 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2893 foreach my $netid (keys %$netif) {
2894 my $d = $netif->{$netid};
2896 my $macaddr = $d->{mac};
2897 my $iface = $d->{host_ifname};
2898 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2899 $vmfw_conf, $vmid, 'IN
');
2900 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2901 $vmfw_conf, $vmid, 'OUT
');
2905 warn $@ if $@; # just to be sure - should not happen
2908 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2909 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2912 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
2914 return ($ruleset, $ipset_ruleset);
2917 sub get_ruleset_status {
2918 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2920 my $statushash = {};
2922 foreach my $chain (sort keys %$ruleset) {
2923 my $sig = &$digest_fn($ruleset->{$chain});
2925 $statushash->{$chain}->{sig} = $sig;
2927 my $oldsig = $active_chains->{$chain};
2928 if (!defined($oldsig)) {
2929 $statushash->{$chain}->{action} = 'create
';
2931 if ($oldsig eq $sig) {
2932 $statushash->{$chain}->{action} = 'exists';
2934 $statushash->{$chain}->{action} = 'update
';
2937 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2938 foreach my $cmd (@{$ruleset->{$chain}}) {
2939 print "\t$cmd\n" if $verbose;
2943 foreach my $chain (sort keys %$active_chains) {
2944 if (!defined($ruleset->{$chain})) {
2945 my $sig = $active_chains->{$chain};
2946 $statushash->{$chain}->{action} = 'delete';
2947 $statushash->{$chain}->{sig} = $sig;
2948 print "delete $chain ($sig)\n" if $verbose;
2955 sub print_sig_rule {
2956 my ($chain, $sig) = @_;
2958 # We just use this to store a SHA1 checksum used to detect changes
2959 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2962 sub get_ruleset_cmdlist {
2963 my ($ruleset, $verbose) = @_;
2965 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2967 my ($active_chains, $hooks) = iptables_get_chains();
2968 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2970 # create missing chains first
2971 foreach my $chain (sort keys %$ruleset) {
2972 my $stat = $statushash->{$chain};
2973 die "internal error" if !$stat;
2974 next if $stat->{action} ne 'create
';
2976 $cmdlist .= ":$chain - [0:0]\n";
2979 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2980 my $chain = "PVEFW-$h";
2981 if ($ruleset->{$chain} && !$hooks->{$h}) {
2982 $cmdlist .= "-A $h -j $chain\n";
2986 foreach my $chain (sort keys %$ruleset) {
2987 my $stat = $statushash->{$chain};
2988 die "internal error" if !$stat;
2990 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2991 $cmdlist .= "-F $chain\n";
2992 foreach my $cmd (@{$ruleset->{$chain}}) {
2993 $cmdlist .= "$cmd\n";
2995 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2996 } elsif ($stat->{action
} eq 'delete') {
2997 die "internal error"; # this should not happen
2998 } elsif ($stat->{action
} eq 'exists') {
3001 die "internal error - unknown status '$stat->{action}'";
3005 foreach my $chain (keys %$statushash) {
3006 next if $statushash->{$chain}->{action
} ne 'delete';
3007 $cmdlist .= "-F $chain\n";
3009 foreach my $chain (keys %$statushash) {
3010 next if $statushash->{$chain}->{action
} ne 'delete';
3011 next if $chain eq 'PVEFW-INPUT';
3012 next if $chain eq 'PVEFW-OUTPUT';
3013 next if $chain eq 'PVEFW-FORWARD';
3014 $cmdlist .= "-X $chain\n";
3017 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3019 $cmdlist .= "COMMIT\n";
3021 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3024 sub get_ipset_cmdlist
{
3025 my ($ruleset, $verbose) = @_;
3029 my $delete_cmdlist = "";
3031 my $active_chains = ipset_get_chains
();
3032 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3034 # remove stale _swap chains
3035 foreach my $chain (keys %$active_chains) {
3036 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3037 $cmdlist .= "destroy $chain\n";
3041 foreach my $chain (sort keys %$ruleset) {
3042 my $stat = $statushash->{$chain};
3043 die "internal error" if !$stat;
3045 if ($stat->{action
} eq 'create') {
3046 foreach my $cmd (@{$ruleset->{$chain}}) {
3047 $cmdlist .= "$cmd\n";
3051 if ($stat->{action
} eq 'update') {
3052 my $chain_swap = $chain."_swap";
3054 foreach my $cmd (@{$ruleset->{$chain}}) {
3055 $cmd =~ s/$chain/$chain_swap/;
3056 $cmdlist .= "$cmd\n";
3058 $cmdlist .= "swap $chain_swap $chain\n";
3059 $cmdlist .= "flush $chain_swap\n";
3060 $cmdlist .= "destroy $chain_swap\n";
3065 foreach my $chain (keys %$statushash) {
3066 next if $statushash->{$chain}->{action
} ne 'delete';
3068 $delete_cmdlist .= "flush $chain\n";
3069 $delete_cmdlist .= "destroy $chain\n";
3072 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3074 return ($cmdlist, $delete_cmdlist, $changes);
3078 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3080 enable_bridge_firewall
();
3082 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3083 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3085 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3088 if ($ipset_changes) {
3089 print "ipset changes:\n";
3090 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3091 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3095 print "iptables changes:\n";
3100 ipset_restore_cmdlist
($ipset_create_cmdlist);
3102 iptables_restore_cmdlist
($cmdlist);
3104 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3106 # test: re-read status and check if everything is up to date
3107 my $active_chains = iptables_get_chains
();
3108 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3111 foreach my $chain (sort keys %$ruleset) {
3112 my $stat = $statushash->{$chain};
3113 if ($stat->{action
} ne 'exists') {
3114 warn "unable to update chain '$chain'\n";
3119 die "unable to apply firewall changes\n" if $errors;
3121 update_nf_conntrack_max
($hostfw_conf);
3123 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3127 sub update_nf_conntrack_max
{
3128 my ($hostfw_conf) = @_;
3130 my $max = 65536; # reasonable default
3132 my $options = $hostfw_conf->{options
} || {};
3134 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3135 $max = $options->{nf_conntrack_max
};
3136 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3139 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3140 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3142 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3144 if ($current != $max) {
3145 my $hashsize = int($max/4);
3146 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3147 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3151 sub update_nf_conntrack_tcp_timeout_established
{
3152 my ($hostfw_conf) = @_;
3154 my $options = $hostfw_conf->{options
} || {};
3156 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3158 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3161 sub remove_pvefw_chains
{
3163 my ($chash, $hooks) = iptables_get_chains
();
3164 my $cmdlist = "*filter\n";
3166 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3168 $cmdlist .= "-D $h -j PVEFW-$h\n";
3172 foreach my $chain (keys %$chash) {
3173 $cmdlist .= "-F $chain\n";
3176 foreach my $chain (keys %$chash) {
3177 $cmdlist .= "-X $chain\n";
3179 $cmdlist .= "COMMIT\n";
3181 iptables_restore_cmdlist
($cmdlist);
3183 my $ipset_chains = ipset_get_chains
();
3187 foreach my $chain (keys %$ipset_chains) {
3188 $cmdlist .= "flush $chain\n";
3189 $cmdlist .= "destroy $chain\n";
3192 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3196 my $cluster_conf = load_clusterfw_conf
();
3197 my $cluster_options = $cluster_conf->{options
};
3198 my $enable = $cluster_options->{enable
};
3202 # load required modules here
3208 my $cluster_conf = load_clusterfw_conf
();
3209 my $cluster_options = $cluster_conf->{options
};
3211 if (!$cluster_options->{enable
}) {
3212 PVE
::Firewall
::remove_pvefw_chains
();
3216 my $hostfw_conf = load_hostfw_conf
();
3218 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3220 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset);