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_format
('IPv4orCIDRorAlias', \
&pve_verify_ipv4_or_cidr_or_alias
);
60 sub pve_verify_ipv4_or_cidr_or_alias
{
61 my ($cidr, $noerr) = @_;
63 return if $cidr =~ m/^(?:$ip_alias_pattern)$/;
65 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
66 return $cidr if Net
::IP-
>new($cidr);
67 return undef if $noerr;
68 die Net
::IP
::Error
() . "\n";
70 return undef if $noerr;
71 die "value does not look like a valid IP address or CIDR network\n";
74 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
75 description
=> "IP set name.",
77 pattern
=> $ipset_name_pattern,
79 maxLength
=> $max_ipset_name_length,
82 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
83 description
=> "Alias name.",
85 pattern
=> $ip_alias_pattern,
87 maxLength
=> $max_alias_name_length,
90 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
91 description
=> "Log level.",
93 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
97 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
98 description
=> "Security Group name.",
100 pattern
=> $security_group_name_pattern,
102 maxLength
=> $max_group_name_length,
105 my $feature_ipset_nomatch = 0;
107 my (undef, undef, $release) = POSIX
::uname
();
108 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
109 my ($major, $minor) = ($1, $2);
110 $feature_ipset_nomatch = 1 if ($major > 3) ||
111 ($major == 3 && $minor >= 7);
118 my $nodename = PVE
::INotify
::nodename
();
120 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
122 my $default_log_level = 'nolog'; # avoid logs by default
124 my $log_level_hash = {
135 # imported/converted from: /usr/share/shorewall/macro.*
136 my $pve_fw_macros = {
139 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
140 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
143 "Auth (identd) traffic",
144 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
147 "Border Gateway Protocol traffic",
148 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
151 "BitTorrent traffic for BitTorrent 3.1 and earlier",
152 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
153 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
156 "BitTorrent traffic for BitTorrent 3.2 and later",
157 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
158 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
161 "Concurrent Versions System pserver traffic",
162 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
165 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
166 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
167 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
168 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
171 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
172 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
173 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
176 "Distributed Checksum Clearinghouse spam filtering mechanism",
177 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
180 "Forwarded DHCP traffic",
181 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
184 "Domain Name System traffic (upd and tcp)",
185 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
186 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
189 "Distributed Compiler service",
190 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
193 "File Transfer Protocol",
194 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
197 "Finger protocol (RFC 742)",
198 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
201 "GNUnet secure peer-to-peer networking traffic",
202 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
203 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
204 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
205 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
208 "Generic Routing Encapsulation tunneling protocol",
209 { action
=> 'PARAM', proto
=> '47' },
212 "Git distributed revision control traffic",
213 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
216 "OpenPGP HTTP keyserver protocol traffic",
217 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
220 "Hypertext Transfer Protocol (WWW)",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
224 "Hypertext Transfer Protocol (WWW) over SSL",
225 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
228 "Internet Cache Protocol V2 (Squid) traffic",
229 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
232 "AOL Instant Messenger traffic",
233 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
236 "Internet Message Access Protocol",
237 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
240 "Internet Message Access Protocol over SSL",
241 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
244 "IPIP capsulation traffic",
245 { action
=> 'PARAM', proto
=> '94' },
249 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
250 { action
=> 'PARAM', proto
=> '50' },
253 "IPsec authentication (AH) traffic",
254 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
255 { action
=> 'PARAM', proto
=> '51' },
258 "IPsec traffic and Nat-Traversal",
259 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
260 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
261 { action
=> 'PARAM', proto
=> '50' },
264 "Internet Relay Chat traffic",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
268 "HP Jetdirect printing",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
272 "Layer 2 Tunneling Protocol traffic",
273 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
276 "Lightweight Directory Access Protocol traffic",
277 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
280 "Secure Lightweight Directory Access Protocol traffic",
281 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
284 "Microsoft Notification Protocol",
285 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
288 "Microsoft SQL Server",
289 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
292 "Mail traffic (SMTP, SMTPS, Submission)",
293 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
294 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
295 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
298 "Munin networked resource monitoring traffic",
299 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
303 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
306 "NNTP traffic (Usenet).",
307 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
310 "Encrypted NNTP traffic (Usenet)",
311 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
314 "Network Time Protocol (ntpd)",
315 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
318 "OSPF multicast traffic",
319 { action
=> 'PARAM', proto
=> '89' },
323 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
326 "Symantec PCAnywere (tm)",
327 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
328 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
332 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
335 "Encrypted POP3 traffic",
336 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
339 "Point-to-Point Tunneling Protocol",
340 { action
=> 'PARAM', proto
=> '47' },
341 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
345 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
349 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
352 "Line Printer protocol printing",
353 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
356 "Microsoft Remote Desktop Protocol traffic",
357 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
360 "Routing Information Protocol (bidirectional)",
361 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
364 "BIND remote management protocol",
365 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
368 "Razor Antispam System",
369 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
372 "Remote time retrieval (rdate)",
373 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
377 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
380 "SANE network scanning",
381 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
384 "Microsoft SMB traffic",
385 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
386 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
387 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
388 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
391 "Samba Web Administration Tool",
392 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
395 "Simple Mail Transfer Protocol",
396 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
399 "Encrypted Simple Mail Transfer Protocol",
400 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
403 "Simple Network Management Protocol",
404 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
405 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
408 "Spam Assassin SPAMD traffic",
409 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
412 "Secure shell traffic",
413 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
416 "Subversion server (svnserve)",
417 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
420 "SixXS IPv6 Deployment and Tunnel Broker",
421 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
422 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
423 { action
=> 'PARAM', proto
=> '41' },
424 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
427 "Squid web proxy traffic",
428 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
431 "Mail message submission traffic",
432 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
435 "Syslog protocol (RFC 5424) traffic",
436 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
437 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
440 "Trivial File Transfer Protocol traffic",
441 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
445 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
449 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
452 "RFC 868 Time protocol",
453 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
456 "Traceroute (for up to 30 hops) traffic",
457 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
458 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
461 "VNC traffic for VNC display's 0 - 99",
462 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
465 "VNC traffic from Vncservers to Vncviewers in listen mode",
466 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
469 "WWW traffic (HTTP and HTTPS)",
470 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
471 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
474 "Web Cache/Proxy traffic (port 8080)",
475 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
479 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
482 "Whois (nicname, RFC 3912) traffic",
483 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
487 my $pve_fw_parsed_macros;
488 my $pve_fw_macro_descr;
489 my $pve_fw_preferred_macro_names = {};
491 my $pve_std_chains = {
492 'PVEFW-SET-ACCEPT-MARK' => [
493 "-j MARK --set-mark 1",
495 'PVEFW-DropBroadcast' => [
496 # same as shorewall 'Broadcast'
497 # simply DROP BROADCAST/MULTICAST/ANYCAST
498 # we can use this to reduce logging
499 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
500 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
501 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
502 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
505 # same as shorewall 'reject'
506 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
507 { action
=> 'DROP', source
=> '224.0.0.0/4' },
508 { action
=> 'DROP', proto
=> 'icmp' },
509 "-p tcp -j REJECT --reject-with tcp-reset",
510 "-p udp -j REJECT --reject-with icmp-port-unreachable",
511 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
512 "-j REJECT --reject-with icmp-host-prohibited",
515 # same as shorewall 'Drop', which is equal to DROP,
516 # but REJECT/DROP some packages to reduce logging,
517 # and ACCEPT critical ICMP types
518 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
519 # we are not interested in BROADCAST/MULTICAST/ANYCAST
520 { action
=> 'PVEFW-DropBroadcast' },
521 # ACCEPT critical ICMP types
522 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
523 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
524 # Drop packets with INVALID state
525 "-m conntrack --ctstate INVALID -j DROP",
526 # Drop Microsoft SMB noise
527 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
528 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
529 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
530 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
531 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
532 # Drop new/NotSyn traffic so that it doesn't get logged
533 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
535 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
538 # same as shorewall 'Reject', which is equal to Reject,
539 # but REJECT/DROP some packages to reduce logging,
540 # and ACCEPT critical ICMP types
541 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
542 # we are not interested in BROADCAST/MULTICAST/ANYCAST
543 { action
=> 'PVEFW-DropBroadcast' },
544 # ACCEPT critical ICMP types
545 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
546 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
547 # Drop packets with INVALID state
548 "-m conntrack --ctstate INVALID -j DROP",
549 # Drop Microsoft SMB noise
550 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
551 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
552 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
553 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
554 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
555 # Drop new/NotSyn traffic so that it doesn't get logged
556 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
558 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
560 'PVEFW-tcpflags' => [
561 # same as shorewall tcpflags action.
562 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
563 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
564 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
565 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
566 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
567 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
570 # same as shorewall smurfs action
571 # Filter packets for smurfs (packets with a broadcast address as the source).
572 "-s 0.0.0.0/32 -j RETURN",
573 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
574 "-s 224.0.0.0/4 -g PVEFW-smurflog",
578 # iptables -p icmp -h
579 my $icmp_type_names = {
582 'destination-unreachable' => 1,
583 'network-unreachable' => 1,
584 'host-unreachable' => 1,
585 'protocol-unreachable' => 1,
586 'port-unreachable' => 1,
587 'fragmentation-needed' => 1,
588 'source-route-failed' => 1,
589 'network-unknown' => 1,
591 'network-prohibited' => 1,
592 'host-prohibited' => 1,
593 'TOS-network-unreachable' => 1,
594 'TOS-host-unreachable' => 1,
595 'communication-prohibited' => 1,
596 'host-precedence-violation' => 1,
597 'precedence-cutoff' => 1,
598 'source-quench' => 1,
600 'network-redirect' => 1,
601 'host-redirect' => 1,
602 'TOS-network-redirect' => 1,
603 'TOS-host-redirect' => 1,
605 'router-advertisement' => 1,
606 'router-solicitation' => 1,
607 'time-exceeded' => 1,
608 'ttl-zero-during-transit' => 1,
609 'ttl-zero-during-reassembly' => 1,
610 'parameter-problem' => 1,
611 'ip-header-bad' => 1,
612 'required-option-missing' => 1,
613 'timestamp-request' => 1,
614 'timestamp-reply' => 1,
615 'address-mask-request' => 1,
616 'address-mask-reply' => 1,
619 sub init_firewall_macros
{
621 $pve_fw_parsed_macros = {};
623 foreach my $k (keys %$pve_fw_macros) {
624 my $lc_name = lc($k);
625 my $macro = $pve_fw_macros->{$k};
626 if (!ref($macro->[0])) {
627 $pve_fw_macro_descr->{$k} = shift @$macro;
629 $pve_fw_preferred_macro_names->{$lc_name} = $k;
630 $pve_fw_parsed_macros->{$k} = $macro;
634 init_firewall_macros
();
637 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
642 sub get_etc_services
{
644 return $etc_services if $etc_services;
646 my $filename = "/etc/services";
648 my $fh = IO
::File-
>new($filename, O_RDONLY
);
650 warn "unable to read '$filename' - $!\n";
656 while (my $line = <$fh>) {
658 next if $line =~m/^#/;
659 next if ($line =~m/^\s*$/);
661 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
662 $services->{byid
}->{$2}->{name
} = $1;
663 $services->{byid
}->{$2}->{port
} = $2;
664 $services->{byid
}->{$2}->{$3} = 1;
665 $services->{byname
}->{$1} = $services->{byid
}->{$2};
671 $etc_services = $services;
674 return $etc_services;
679 sub get_etc_protocols
{
680 return $etc_protocols if $etc_protocols;
682 my $filename = "/etc/protocols";
684 my $fh = IO
::File-
>new($filename, O_RDONLY
);
686 warn "unable to read '$filename' - $!\n";
692 while (my $line = <$fh>) {
694 next if $line =~m/^#/;
695 next if ($line =~m/^\s*$/);
697 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
698 $protocols->{byid
}->{$2}->{name
} = $1;
699 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
705 $etc_protocols = $protocols;
707 return $etc_protocols;
710 my $ipv4_mask_hash_localnet = {
712 '255.255.128.0' => 17,
713 '255.255.192.0' => 18,
714 '255.255.224.0' => 19,
715 '255.255.240.0' => 20,
716 '255.255.248.0' => 21,
717 '255.255.252.0' => 22,
718 '255.255.254.0' => 23,
719 '255.255.255.0' => 24,
720 '255.255.255.128' => 25,
721 '255.255.255.192' => 26,
722 '255.255.255.224' => 27,
723 '255.255.255.240' => 28,
724 '255.255.255.248' => 29,
725 '255.255.255.252' => 30,
731 my ($new_value) = @_;
733 $__local_network = $new_value if defined($new_value);
735 return $__local_network if defined($__local_network);
738 my $nodename = PVE
::INotify
::nodename
();
740 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
742 my $testip = Net
::IP-
>new($ip);
744 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
745 foreach my $entry (@$routes) {
746 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
747 next if !defined($mask);
748 return if $mask eq '0.0.0.0';
749 my $cidr = "$entry->{dest}/$mask";
750 my $testnet = Net
::IP-
>new($cidr);
751 if ($testnet->overlaps($testip)) {
752 $__local_network = $cidr;
759 return $__local_network;
762 my $max_iptables_ipset_name_length = 27;
764 sub compute_ipset_chain_name
{
765 my ($vmid, $ipset_name) = @_;
767 $vmid = 0 if !defined($vmid);
769 my $id = "$vmid-${ipset_name}";
772 if ((length($id) + 6) > $max_iptables_ipset_name_length) {
773 $id = PVE
::Tools
::fnv31a_hex
($id);
779 sub parse_address_list
{
782 if ($str =~ m/^(\+)(\S+)$/) { # ipset ref
783 die "ipset name too long\n" if length($str) > ($max_ipset_name_length + 1);
787 if ($str =~ m/^${ip_alias_pattern}$/) {
788 die "alias name too long\n" if length($str) > $max_alias_name_length;
794 foreach my $elem (split(/,/, $str)) {
796 if (!Net
::IP-
>new($elem)) {
797 my $err = Net
::IP
::Error
();
798 die "invalid IP address: $err\n";
800 $iprange = 1 if $elem =~ m/-/;
803 die "you can use a range in a list\n" if $iprange && $count > 1;
806 sub parse_port_name_number_or_range
{
809 my $services = PVE
::Firewall
::get_etc_services
();
813 foreach my $item (split(/,/, $str)) {
815 if ($item =~ m/^(\d+):(\d+)$/) {
816 my ($port1, $port2) = ($1, $2);
817 die "invalid port '$port1'\n" if $port1 > 65535;
818 die "invalid port '$port2'\n" if $port2 > 65535;
819 } elsif ($item =~ m/^(\d+)$/) {
821 die "invalid port '$port'\n" if $port > 65535;
823 if ($icmp_type_names->{$item}) {
826 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
831 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
836 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
837 sub pve_fw_verify_port_spec
{
840 parse_port_name_number_or_range
($portstr);
845 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
846 sub pve_fw_verify_v4addr_spec
{
849 parse_address_list
($list);
854 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
855 sub pve_fw_verify_protocol_spec
{
858 my $protocols = get_etc_protocols
();
860 die "unknown protocol '$proto'\n" if $proto &&
861 !(defined($protocols->{byname
}->{$proto}) ||
862 defined($protocols->{byid
}->{$proto}));
868 # helper function for API
870 sub copy_opject_with_digest
{
873 my $sha = Digest
::SHA-
>new('sha1');
876 foreach my $k (sort keys %$object) {
877 my $v = $object->{$k};
878 next if !defined($v);
880 $sha->add($k, ':', $v, "\n");
883 my $digest = $sha->hexdigest;
885 $res->{digest
} = $digest;
887 return wantarray ?
($res, $digest) : $res;
890 sub copy_list_with_digest
{
893 my $sha = Digest
::SHA-
>new('sha1');
896 foreach my $entry (@$list) {
898 foreach my $k (sort keys %$entry) {
899 my $v = $entry->{$k};
900 next if !defined($v);
902 # Note: digest ignores refs ($rule->{errors})
903 $sha->add($k, ':', $v, "\n") if !ref($v); ;
908 my $digest = $sha->hexdigest;
910 foreach my $entry (@$res) {
911 $entry->{digest
} = $digest;
914 return wantarray ?
($res, $digest) : $res;
917 my $rule_properties = {
919 description
=> "Update rule at position <pos>.",
924 digest
=> get_standard_option
('pve-config-digest'),
928 enum
=> ['in', 'out', 'group'],
931 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
934 pattern
=> $security_group_name_pattern,
943 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
945 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
949 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
953 type
=> 'string', format
=> 'pve-fw-protocol-spec',
961 type
=> 'string', format
=> 'pve-fw-port-spec',
965 type
=> 'string', format
=> 'pve-fw-port-spec',
974 sub add_rule_properties
{
975 my ($properties) = @_;
977 foreach my $k (keys %$rule_properties) {
978 my $h = $rule_properties->{$k};
979 # copy data, so that we can modify later without side effects
980 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
986 sub delete_rule_properties
{
987 my ($rule, $delete_str) = @_;
989 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
990 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
991 if !defined($rule_properties->{$opt});
992 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
993 if $opt eq 'type' || $opt eq 'action';
994 delete $rule->{$opt};
1000 my $apply_macro = sub {
1001 my ($macro_name, $param, $verify) = @_;
1003 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
1004 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
1008 foreach my $templ (@$macro_rules) {
1010 my $param_used = {};
1011 foreach my $k (keys %$templ) {
1012 my $v = $templ->{$k};
1013 if ($v eq 'PARAM') {
1015 $param_used->{$k} = 1;
1016 } elsif ($v eq 'DEST') {
1017 $v = $param->{dest
};
1018 $param_used->{dest
} = 1;
1019 } elsif ($v eq 'SOURCE') {
1020 $v = $param->{source
};
1021 $param_used->{source
} = 1;
1025 my $msg = "missing parameter '$k' in macro '$macro_name'";
1026 raise_param_exc
({ macro => $msg }) if $verify;
1031 foreach my $k (keys %$param) {
1032 next if $k eq 'macro';
1033 next if !defined($param->{$k});
1034 next if $param_used->{$k};
1035 if (defined($rule->{$k})) {
1036 if ($rule->{$k} ne $param->{$k}) {
1037 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
1038 raise_param_exc
({ $k => $msg }) if $verify;
1042 $rule->{$k} = $param->{$k};
1045 push @$rules, $rule;
1051 my $rule_env_iface_lookup = {
1060 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1062 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1064 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1065 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1067 my $errors = $rule->{errors
} || {};
1069 my $error_count = 0;
1071 my $add_error = sub {
1072 my ($param, $msg) = @_;
1074 raise_param_exc
({ $param => $msg }) if !$noerr;
1076 $errors->{$param} = $msg if !$errors->{$param};
1079 my $check_ipset_or_alias_property = sub {
1082 if (my $value = $rule->{$name}) {
1083 if ($value =~ m/^\+/) {
1084 if ($value =~ m/^\+(${ipset_name_pattern})$/) {
1085 &$add_error($name, "no such ipset '$1'")
1086 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1089 &$add_error($name, "invalid ipset name '$value'");
1091 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1092 my $alias = lc($value);
1093 &$add_error($name, "no such alias '$value'")
1094 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}))
1099 my $type = $rule->{type
};
1100 my $action = $rule->{action
};
1102 &$add_error('type', "missing property") if !$type;
1103 &$add_error('action', "missing property") if !$action;
1106 if ($type eq 'in' || $type eq 'out') {
1107 &$add_error('action', "unknown action '$action'")
1108 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1109 } elsif ($type eq 'group') {
1110 &$add_error('type', "security groups not allowed")
1112 &$add_error('action', "invalid characters in security group name")
1113 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1115 &$add_error('type', "unknown rule type '$type'");
1119 if ($rule->{iface
}) {
1120 &$add_error('type', "parameter -i not allowed for this rule type")
1122 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1123 &$add_error('iface', $@) if $@;
1124 if ($rule_env eq 'vm') {
1125 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1126 if $rule->{iface
} !~ m/^net(\d+)$/;
1127 } elsif ($rule_env eq 'ct') {
1128 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1129 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1133 if ($rule->{macro}) {
1134 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1135 $rule->{macro} = $preferred_name;
1137 &$add_error('macro', "unknown macro '$rule->{macro}'");
1141 if ($rule->{proto
}) {
1142 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1143 &$add_error('proto', $@) if $@;
1146 if ($rule->{dport
}) {
1147 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1148 &$add_error('dport', $@) if $@;
1149 &$add_error('proto', "missing property - 'dport' requires this property")
1153 if ($rule->{sport
}) {
1154 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1155 &$add_error('sport', $@) if $@;
1156 &$add_error('proto', "missing property - 'sport' requires this property")
1160 if ($rule->{source
}) {
1161 eval { parse_address_list
($rule->{source
}); };
1162 &$add_error('source', $@) if $@;
1163 &$check_ipset_or_alias_property('source');
1166 if ($rule->{dest
}) {
1167 eval { parse_address_list
($rule->{dest
}); };
1168 &$add_error('dest', $@) if $@;
1169 &$check_ipset_or_alias_property('dest');
1172 if ($rule->{macro} && !$error_count) {
1173 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1175 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1176 my $eh = $err->{errors
};
1177 foreach my $p (keys %$eh) {
1178 &$add_error($p, $eh->{$p});
1181 &$add_error('macro', "$err");
1186 $rule->{errors
} = $errors if $error_count;
1191 sub copy_rule_data
{
1192 my ($rule, $param) = @_;
1194 foreach my $k (keys %$rule_properties) {
1195 if (defined(my $v = $param->{$k})) {
1196 if ($v eq '' || $v eq '-') {
1208 my $bridge_firewall_enabled = 0;
1210 sub enable_bridge_firewall
{
1212 return if $bridge_firewall_enabled; # only once
1214 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1215 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1217 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1218 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1220 $bridge_firewall_enabled = 1;
1223 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1225 sub iptables_restore_cmdlist
{
1228 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1231 sub ipset_restore_cmdlist
{
1234 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1237 sub iptables_get_chains
{
1241 # check what chains we want to track
1242 my $is_pvefw_chain = sub {
1245 return 1 if $name =~ m/^PVEFW-\S+$/;
1247 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1249 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1251 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1253 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1254 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1266 return if $line =~ m/^#/;
1267 return if $line =~ m/^\s*$/;
1269 if ($line =~ m/^\*(\S+)$/) {
1274 return if $table ne 'filter';
1276 if ($line =~ m/^:(\S+)\s/) {
1278 return if !&$is_pvefw_chain($chain);
1279 $res->{$chain} = "unknown";
1280 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1281 my ($chain, $sig) = ($1, $2);
1282 return if !&$is_pvefw_chain($chain);
1283 $res->{$chain} = $sig;
1284 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1287 # simply ignore the rest
1292 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1294 return wantarray ?
($res, $hooks) : $res;
1297 sub iptables_chain_digest
{
1299 my $digest = Digest
::SHA-
>new('sha1');
1300 foreach my $rule (@$rules) { # order is important
1301 $digest->add($rule);
1303 return $digest->b64digest;
1306 sub ipset_chain_digest
{
1309 my $digest = Digest
::SHA-
>new('sha1');
1310 foreach my $rule (sort @$rules) { # note: sorted
1311 $digest->add($rule);
1313 return $digest->b64digest;
1316 sub ipset_get_chains
{
1324 return if $line =~ m/^#/;
1325 return if $line =~ m/^\s*$/;
1326 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1328 $line =~ s/\s+$//; # delete trailing white space
1329 push @{$chains->{$chain}}, $line;
1331 # simply ignore the rest
1336 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1338 # compute digest for each chain
1339 foreach my $chain (keys %$chains) {
1340 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1346 sub ruleset_generate_cmdstr
{
1347 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1349 return if defined($rule->{enable
}) && !$rule->{enable
};
1350 return if $rule->{errors
};
1352 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1354 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1355 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1359 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1360 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1362 my $source = $rule->{source
};
1363 my $dest = $rule->{dest
};
1366 if ($source =~ m/^\+/) {
1367 if ($source =~ m/^\+(${ipset_name_pattern})$/) {
1369 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1370 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1371 push @cmd, "-m set --match-set ${ipset_chain} src";
1372 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1373 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1374 push @cmd, "-m set --match-set ${ipset_chain} src";
1376 die "no such ipset '$name'\n";
1379 die "invalid security group name '$source'\n";
1381 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1382 my $alias = lc($source);
1383 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1384 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1385 die "no such alias '$source'\n" if !$e;
1386 push @cmd, "-s $e->{cidr}";
1387 } elsif ($source =~ m/\-/){
1388 push @cmd, "-m iprange --src-range $source";
1390 push @cmd, "-s $source";
1395 if ($dest =~ m/^\+/) {
1396 if ($dest =~ m/^\+(${ipset_name_pattern})$/) {
1398 if ($fw_conf && $fw_conf->{ipset
}->{$name}) {
1399 my $ipset_chain = compute_ipset_chain_name
($fw_conf->{vmid
}, $name);
1400 push @cmd, "-m set --match-set ${ipset_chain} dst";
1401 } elsif ($cluster_conf && $cluster_conf->{ipset
}->{$name}) {
1402 my $ipset_chain = compute_ipset_chain_name
(0, $name);
1403 push @cmd, "-m set --match-set ${ipset_chain} dst";
1405 die "no such ipset '$name'\n";
1408 die "invalid security group name '$dest'\n";
1410 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1411 my $alias = lc($dest);
1412 my $e = $fw_conf->{aliases
}->{$alias} if $fw_conf;
1413 $e = $cluster_conf->{aliases
}->{$alias} if !$e && $cluster_conf;
1414 die "no such alias '$dest'\n" if !$e;
1415 push @cmd, "-d $e->{cidr}";
1416 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1417 push @cmd, "-m iprange --dst-range $dest";
1419 push @cmd, "-d $dest";
1423 if ($rule->{proto
}) {
1424 push @cmd, "-p $rule->{proto}";
1427 $multiport++ if $nbdport > 1;
1428 $multiport++ if $nbsport > 1;
1430 push @cmd, "--match multiport" if $multiport;
1432 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1433 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1435 if ($rule->{dport
}) {
1436 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1437 # Note: we use dport to store --icmp-type
1438 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1439 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1442 if ($multiport == 2) {
1443 push @cmd, "--ports $rule->{dport}";
1445 push @cmd, "--dports $rule->{dport}";
1448 push @cmd, "--dport $rule->{dport}";
1453 if ($rule->{sport
}) {
1455 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1457 push @cmd, "--sport $rule->{sport}";
1460 } elsif ($rule->{dport
} || $rule->{sport
}) {
1461 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1462 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1465 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1467 if (my $action = $rule->{action
}) {
1468 $action = $actions->{$action} if defined($actions->{$action});
1469 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1470 push @cmd, $goto ?
"-g $action" : "-j $action";
1473 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1476 sub ruleset_generate_rule
{
1477 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf, $fw_conf) = @_;
1481 if ($rule->{macro}) {
1482 $rules = &$apply_macro($rule->{macro}, $rule);
1487 # update all or nothing
1490 foreach my $tmp (@$rules) {
1491 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf, $fw_conf)) {
1492 push @cmds, $cmdstr;
1496 foreach my $cmdstr (@cmds) {
1497 ruleset_addrule
($ruleset, $chain, $cmdstr);
1501 sub ruleset_generate_rule_insert
{
1502 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1504 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1506 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1507 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1511 sub ruleset_create_chain
{
1512 my ($ruleset, $chain) = @_;
1514 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1515 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1517 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1519 $ruleset->{$chain} = [];
1522 sub ruleset_chain_exist
{
1523 my ($ruleset, $chain) = @_;
1525 return $ruleset->{$chain} ?
1 : undef;
1528 sub ruleset_addrule
{
1529 my ($ruleset, $chain, $rule) = @_;
1531 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1533 push @{$ruleset->{$chain}}, "-A $chain $rule";
1536 sub ruleset_insertrule
{
1537 my ($ruleset, $chain, $rule) = @_;
1539 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1541 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1544 sub get_log_rule_base
{
1545 my ($chain, $vmid, $msg, $loglevel) = @_;
1547 die "internal error - no log level" if !defined($loglevel);
1549 $vmid = 0 if !defined($vmid);
1551 # Note: we use special format for prefix to pass further
1552 # info to log daemon (VMID, LOGVELEL and CHAIN)
1554 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1557 sub ruleset_addlog {
1558 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1560 return if !defined($loglevel);
1562 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1564 $logrule = "$rule $logrule" if defined($rule);
1566 ruleset_addrule($ruleset, $chain, $logrule);
1569 sub ruleset_add_chain_policy {
1570 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1572 if ($policy eq 'ACCEPT') {
1574 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1575 { ACCEPT => $accept_action});
1577 } elsif ($policy eq 'DROP') {
1579 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1581 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1583 ruleset_addrule($ruleset, $chain, "-j DROP
");
1584 } elsif ($policy eq 'REJECT') {
1585 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1587 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1589 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1592 die "internal error
: unknown policy
'$policy'";
1596 sub ruleset_chain_add_conn_filters {
1597 my ($ruleset, $chain, $accept) = @_;
1599 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1600 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1603 sub ruleset_chain_add_input_filters {
1604 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1606 if ($cluster_conf->{ipset}->{blacklist}){
1607 if (!ruleset_chain_exist($ruleset, "PVEFW-blacklist
")) {
1608 ruleset_create_chain($ruleset, "PVEFW-blacklist
");
1609 ruleset_addlog($ruleset, "PVEFW-blacklist
", 0, "DROP
: ", $loglevel) if $loglevel;
1610 ruleset_addrule($ruleset, "PVEFW-blacklist
", "-j DROP
");
1612 my $ipset_chain = compute_ipset_chain_name(0, 'blacklist');
1613 ruleset_addrule($ruleset, $chain, "-m set
--match-set
${ipset_chain
} src
-j PVEFW-blacklist
");
1616 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1617 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1620 if ($options->{tcpflags}) {
1621 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1625 sub ruleset_create_vm_chain {
1626 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1628 ruleset_create_chain($ruleset, $chain);
1629 my $accept = generate_nfqueue($options);
1631 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1632 if ($direction eq 'OUT') {
1633 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1634 proto => 'udp', sport => 68, dport => 67 });
1636 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1637 proto => 'udp', sport => 67, dport => 68 });
1641 if ($direction eq 'OUT') {
1642 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1643 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1645 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1649 sub ruleset_add_group_rule {
1650 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1652 my $group = $rule->{action};
1653 my $group_chain = "GROUP-
$group-$direction";
1654 if(!ruleset_chain_exist($ruleset, $group_chain)){
1655 generate_group_rules($ruleset, $cluster_conf, $group);
1658 if ($direction eq 'OUT' && $rule->{iface_out}) {
1659 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1660 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1661 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1663 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1666 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1669 sub ruleset_generate_vm_rules {
1670 my ($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, $netid, $direction, $options) = @_;
1672 my $lc_direction = lc($direction);
1674 my $in_accept = generate_nfqueue($options);
1676 foreach my $rule (@$rules) {
1677 next if $rule->{iface} && $rule->{iface} ne $netid;
1678 next if !$rule->{enable} || $rule->{errors};
1679 if ($rule->{type} eq 'group') {
1680 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1681 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1683 next if $rule->{type} ne $lc_direction;
1685 if ($direction eq 'OUT') {
1686 ruleset_generate_rule($ruleset, $chain, $rule,
1687 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1688 undef, $cluster_conf, $vmfw_conf);
1690 ruleset_generate_rule($ruleset, $chain, $rule,
1691 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1692 undef, $cluster_conf, $vmfw_conf);
1700 sub generate_nfqueue {
1703 if ($options->{ips}) {
1704 my $action = "NFQUEUE
";
1705 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1706 if (defined($3) && defined($1)) {
1707 $action .= " --queue-balance
$1:$3";
1708 } elsif (defined($1)) {
1709 $action .= " --queue-num
$1";
1712 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1719 sub ruleset_generate_vm_ipsrules {
1720 my ($ruleset, $options, $direction, $iface) = @_;
1722 if ($options->{ips} && $direction eq 'IN') {
1723 my $nfqueue = generate_nfqueue($options);
1725 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1726 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1729 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1733 sub generate_venet_rules_direction {
1734 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1736 my $lc_direction = lc($direction);
1738 my $rules = $vmfw_conf->{rules};
1740 my $options = $vmfw_conf->{options};
1741 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1743 my $chain = "venet0-
$vmid-$direction";
1745 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1747 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $chain, 'venet', $direction);
1752 if ($direction eq 'OUT') {
1753 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1755 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1758 my $accept = generate_nfqueue($options);
1759 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1760 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1762 if ($direction eq 'OUT') {
1763 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1766 iface_in => 'venet0'});
1768 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1771 iface_out => 'venet0'});
1775 sub generate_tap_rules_direction {
1776 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1778 my $lc_direction = lc($direction);
1780 my $rules = $vmfw_conf->{rules};
1782 my $options = $vmfw_conf->{options};
1783 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1785 my $tapchain = "$iface-$direction";
1787 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1789 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $vmfw_conf, $tapchain, $netid, $direction, $options);
1791 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1796 if ($direction eq 'OUT') {
1797 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1799 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1802 my $accept = generate_nfqueue($options);
1803 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1804 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1806 # plug the tap chain to bridge chain
1807 if ($direction eq 'IN') {
1808 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
1809 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1811 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
1812 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
1816 sub enable_host_firewall {
1817 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1819 my $options = $hostfw_conf->{options};
1820 my $cluster_options = $cluster_conf->{options};
1821 my $rules = $hostfw_conf->{rules};
1822 my $cluster_rules = $cluster_conf->{rules};
1824 # host inbound firewall
1825 my $chain = "PVEFW-HOST-IN
";
1826 ruleset_create_chain($ruleset, $chain);
1828 my $loglevel = get_option_log_level($options, "log_level_in
");
1830 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1832 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1833 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1835 # we use RETURN because we need to check also tap rules
1836 my $accept_action = 'RETURN';
1838 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1840 # add host rules first, so that cluster wide rules can be overwritten
1841 foreach my $rule (@$rules, @$cluster_rules) {
1842 next if !$rule->{enable} || $rule->{errors};
1844 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1847 if ($rule->{type} eq 'group') {
1848 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1849 } elsif ($rule->{type} eq 'in') {
1850 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1851 undef, $cluster_conf, $hostfw_conf);
1855 delete $rule->{iface_in};
1858 # allow standard traffic for management ipset (includes cluster network)
1859 my $mngmnt_ipset_chain = compute_ipset_chain_name(0, "management
");
1860 my $mngmntsrc = "-m set
--match-set
${mngmnt_ipset_chain
} src
";
1861 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1862 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1863 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1864 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
1866 my $localnet = local_network();
1870 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1871 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
1872 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
1875 # implement input policy
1876 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1877 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1879 # host outbound firewall
1880 $chain = "PVEFW-HOST-OUT
";
1881 ruleset_create_chain($ruleset, $chain);
1883 $loglevel = get_option_log_level($options, "log_level_out
");
1885 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1887 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1889 # we use RETURN because we may want to check other thigs later
1890 $accept_action = 'RETURN';
1892 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1894 # add host rules first, so that cluster wide rules can be overwritten
1895 foreach my $rule (@$rules, @$cluster_rules) {
1896 next if !$rule->{enable} || $rule->{errors};
1898 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1900 if ($rule->{type} eq 'group') {
1901 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1902 } elsif ($rule->{type} eq 'out') {
1903 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1904 undef, $cluster_conf, $hostfw_conf);
1908 delete $rule->{iface_out};
1911 # allow standard traffic on cluster network
1913 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1914 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
1915 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1916 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1918 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1919 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
1920 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
1923 # implement output policy
1924 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1925 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1927 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1928 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1931 sub generate_group_rules {
1932 my ($ruleset, $cluster_conf, $group) = @_;
1934 my $rules = $cluster_conf->{groups}->{$group};
1937 warn "no such security group
'$group'\n";
1938 $rules = []; # create empty chain
1941 my $chain = "GROUP-
${group
}-IN
";
1943 ruleset_create_chain($ruleset, $chain);
1944 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1946 foreach my $rule (@$rules) {
1947 next if $rule->{type} ne 'in';
1948 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1951 $chain = "GROUP-
${group
}-OUT
";
1953 ruleset_create_chain($ruleset, $chain);
1954 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1956 foreach my $rule (@$rules) {
1957 next if $rule->{type} ne 'out';
1958 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1959 # check also other tap rules later
1960 ruleset_generate_rule($ruleset, $chain, $rule,
1961 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1966 my $valid_netdev_names = {};
1967 for (my $i = 0; $i < $MAX_NETS; $i++) {
1968 $valid_netdev_names->{"net
$i"} = 1;
1972 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
1976 my $orig_line = $line;
1980 # we can add single line comments to the end of the rule
1981 if ($line =~ s/#\s*(.*?)\s*$//) {
1982 $rule->{comment} = decode('utf8', $1);
1985 # we can disable a rule when prefixed with '|'
1987 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
1989 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1990 die "unable to parse rule
: $line\n";
1992 $rule->{type} = lc($1);
1993 $rule->{action} = $2;
1995 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1996 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1997 $rule->{macro} = $1;
1998 $rule->{action} = $2;
2002 while (length($line)) {
2003 if ($line =~ s/^-i (\S+)\s*//) {
2004 $rule->{iface} = $1;
2008 last if $rule->{type} eq 'group';
2010 if ($line =~ s/^-p (\S+)\s*//) {
2011 $rule->{proto} = $1;
2015 if ($line =~ s/^-dport (\S+)\s*//) {
2016 $rule->{dport} = $1;
2020 if ($line =~ s/^-sport (\S+)\s*//) {
2021 $rule->{sport} = $1;
2024 if ($line =~ s/^-source (\S+)\s*//) {
2025 $rule->{source} = $1;
2028 if ($line =~ s/^-dest (\S+)\s*//) {
2036 die "unable to parse rule parameters
: $line\n" if length($line);
2038 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2039 if ($verbose && $rule->{errors}) {
2040 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2041 foreach my $p (keys %{$rule->{errors}}) {
2042 warn " $p: $rule->{errors
}->{$p}\n";
2049 sub parse_vmfw_option {
2054 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2056 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2059 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2061 $value = $2 ? lc($3) : '';
2062 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2065 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2070 die "can
't parse option '$line'\n"
2073 return ($opt, $value);
2076 sub parse_hostfw_option {
2081 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2083 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2086 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2088 $value = $2 ? lc($3) : '';
2089 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2094 die "can't parse option
'$line'\n"
2097 return ($opt, $value);
2100 sub parse_clusterfw_option {
2105 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2108 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2113 die "can
't parse option '$line'\n"
2116 return ($opt, $value);
2122 # we can add single line comments to the end of the line
2123 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2125 if ($line =~ m/^(\S+)\s(\S+)$/) {
2126 my ($name, $cidr) = ($1, $2);
2128 pve_verify_ipv4_or_cidr($cidr);
2133 $data->{comment} = $comment if $comment;
2140 sub generic_fw_rules_parser {
2141 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2146 my $res = $empty_conf;
2148 my $ipset_option = get_standard_option('ipset-name
');
2150 while (defined(my $line = <$fh>)) {
2151 next if $line =~ m/^#/;
2152 next if $line =~ m/^\s*$/;
2154 my $linenr = $fh->input_line_number();
2155 my $prefix = "$filename (line $linenr)";
2157 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2158 $section = 'options
';
2162 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2163 $section = 'aliases
';
2167 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2168 $section = 'groups
';
2172 die "security group name too long\n" if length($group) > $max_group_name_length;
2173 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2176 ($section, $group, $comment) = undef;
2177 warn "$prefix: $err";
2181 $res->{$section}->{$group} = [];
2182 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2187 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2192 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2197 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2198 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2201 ($section, $group, $comment) = undef;
2202 warn "$prefix: $err";
2206 $res->{$section}->{$group} = [];
2207 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2213 warn "$prefix: skip line - no section\n";
2217 if ($section eq 'options
') {
2220 if ($rule_env eq 'cluster
') {
2221 ($opt, $value) = parse_clusterfw_option($line);
2222 } elsif ($rule_env eq 'host
') {
2223 ($opt, $value) = parse_hostfw_option($line);
2225 ($opt, $value) = parse_vmfw_option($line);
2227 $res->{options}->{$opt} = $value;
2229 warn "$prefix: $@" if $@;
2230 } elsif ($section eq 'aliases
') {
2232 my $data = parse_alias($line);
2233 $res->{aliases}->{lc($data->{name})} = $data;
2235 warn "$prefix: $@" if $@;
2236 } elsif ($section eq 'rules
') {
2238 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2240 warn "$prefix: $err";
2243 push @{$res->{$section}}, $rule;
2244 } elsif ($section eq 'groups
') {
2246 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2248 warn "$prefix: $err";
2251 push @{$res->{$section}->{$group}}, $rule;
2252 } elsif ($section eq 'ipset
') {
2253 # we can add single line comments to the end of the rule
2254 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2256 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2260 if($cidr !~ m/^${ip_alias_pattern}$/) {
2263 eval { pve_verify_ipv4_or_cidr($cidr); };
2265 warn "$prefix: $cidr - $err";
2270 my $entry = { cidr => $cidr };
2271 $entry->{nomatch} = 1 if $nomatch;
2272 $entry->{comment} = $comment if $comment;
2274 push @{$res->{$section}->{$group}}, $entry;
2276 warn "$prefix: skip line - unknown section\n";
2284 sub parse_host_fw_rules {
2285 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2287 my $empty_conf = { rules => [], options => {}};
2289 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2292 sub parse_vm_fw_rules {
2293 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2300 ipset_comments => {},
2303 return generic_fw_rules_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2306 sub parse_cluster_fw_rules {
2307 my ($filename, $fh, $verbose) = @_;
2317 group_comments => {},
2319 ipset_comments => {},
2322 return generic_fw_rules_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2326 my ($code, @param) = @_;
2330 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2337 sub read_local_vm_config {
2342 my $vmdata = { openvz => $openvz, qemu => $qemu };
2344 my $vmlist = PVE::Cluster::get_vmlist();
2345 return $vmdata if !$vmlist || !$vmlist->{ids};
2346 my $ids = $vmlist->{ids};
2348 foreach my $vmid (keys %$ids) {
2349 next if !$vmid; # skip VE0
2350 my $d = $ids->{$vmid};
2351 next if !$d->{node} || $d->{node} ne $nodename;
2352 next if !$d->{type};
2353 if ($d->{type} eq 'openvz
') {
2354 if ($have_pve_manager) {
2355 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2356 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2357 $openvz->{$vmid} = $conf;
2360 } elsif ($d->{type} eq 'qemu
') {
2361 if ($have_qemu_server) {
2362 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2363 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2364 $qemu->{$vmid} = $conf;
2373 sub load_vmfw_conf {
2374 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2378 $dir = "/etc/pve/firewall" if !defined($dir);
2380 my $filename = "$dir/$vmid.fw";
2381 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2382 $vmfw_conf = parse_vm_fw_rules($filename, $fh, $cluster_conf, $rule_env, $verbose);
2383 $vmfw_conf->{vmid} = $vmid;
2389 my $format_rules = sub {
2390 my ($rules, $allow_iface) = @_;
2394 foreach my $rule (@$rules) {
2395 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2396 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2397 $raw .= uc($rule->{type});
2398 if ($rule->{macro}) {
2399 $raw .= " $rule->{macro}($rule->{action})";
2401 $raw .= " " . $rule->{action};
2403 if ($allow_iface && $rule->{iface}) {
2404 $raw .= " -i $rule->{iface}";
2407 if ($rule->{type} ne 'group
') {
2408 $raw .= " -source $rule->{source}" if $rule->{source};
2409 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2410 $raw .= " -p $rule->{proto}" if $rule->{proto};
2411 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2412 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2415 $raw .= " # " . encode('utf8
', $rule->{comment})
2416 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2419 die "unknown rule type '$rule->{type
}'";
2426 my $format_options = sub {
2431 $raw .= "[OPTIONS]\n\n";
2432 foreach my $opt (keys %$options) {
2433 $raw .= "$opt: $options->{$opt}\n";
2440 my $format_aliases = sub {
2445 $raw .= "[ALIASES]\n\n";
2446 foreach my $k (keys %$aliases) {
2447 my $e = $aliases->{$k};
2448 $raw .= "$e->{name} $e->{cidr}";
2449 $raw .= " # " . encode('utf8
', $e->{comment})
2450 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2458 my $format_ipsets = sub {
2463 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2464 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2465 my $utf8comment = encode('utf8
', $comment);
2466 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2468 $raw .= "[IPSET $ipset]\n\n";
2470 my $options = $fw_conf->{ipset}->{$ipset};
2473 foreach my $entry (@$options) {
2474 $nethash->{$entry->{cidr}} = $entry;
2477 foreach my $cidr (sort keys %$nethash) {
2478 my $entry = $nethash->{$cidr};
2479 my $line = $entry->{nomatch} ? '!' : '';
2480 $line .= $entry->{cidr};
2481 $line .= " # " . encode('utf8
', $entry->{comment})
2482 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2492 sub save_vmfw_conf {
2493 my ($vmid, $vmfw_conf) = @_;
2497 my $options = $vmfw_conf->{options};
2498 $raw .= &$format_options($options) if scalar(keys %$options);
2500 my $aliases = $vmfw_conf->{aliases};
2501 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2503 $raw .= &$format_ipsets($vmfw_conf);
2505 my $rules = $vmfw_conf->{rules} || [];
2506 if (scalar(@$rules)) {
2507 $raw .= "[RULES]\n\n";
2508 $raw .= &$format_rules($rules, 1);
2512 my $filename = "/etc/pve/firewall/$vmid.fw";
2513 PVE::Tools::file_set_contents($filename, $raw);
2516 sub read_vm_firewall_configs {
2517 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2519 my $vmfw_configs = {};
2521 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2522 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2523 next if !$vmfw_conf->{options}; # skip if file does not exists
2524 $vmfw_configs->{$vmid} = $vmfw_conf;
2526 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2527 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2528 next if !$vmfw_conf->{options}; # skip if file does not exists
2529 $vmfw_configs->{$vmid} = $vmfw_conf;
2532 return $vmfw_configs;
2535 sub get_option_log_level {
2536 my ($options, $k) = @_;
2538 my $v = $options->{$k};
2539 $v = $default_log_level if !defined($v);
2541 return undef if $v eq '' || $v eq 'nolog
';
2543 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2545 return $v if ($v >= 0) && ($v <= 7);
2547 warn "unknown log level ($k = '$v')\n";
2552 sub generate_std_chains {
2553 my ($ruleset, $options) = @_;
2555 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2557 # same as shorewall smurflog.
2558 my $chain = 'PVEFW-smurflog
';
2559 $pve_std_chains->{$chain} = [];
2561 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2562 push @{$pve_std_chains->{$chain}}, "-j DROP";
2564 # same as shorewall logflags action.
2565 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2566 $chain = 'PVEFW-logflags
';
2567 $pve_std_chains->{$chain} = [];
2569 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2570 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2571 push @{$pve_std_chains->{$chain}}, "-j DROP";
2573 foreach my $chain (keys %$pve_std_chains) {
2574 ruleset_create_chain($ruleset, $chain);
2575 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2577 ruleset_generate_rule($ruleset, $chain, $rule);
2579 ruleset_addrule($ruleset, $chain, $rule);
2585 sub generate_ipset_chains {
2586 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2588 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2589 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2590 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2594 sub generate_ipset {
2595 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2597 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2599 my $hashsize = scalar(@$options);
2600 if ($hashsize <= 64) {
2603 $hashsize = round_powerof2($hashsize);
2606 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
2610 foreach my $entry (@$options) {
2611 my $cidr = $entry->{cidr};
2612 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2613 my $alias = lc($cidr);
2614 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2615 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2617 $entry->{cidr} = $e->{cidr};
2618 $nethash->{$entry->{cidr}} = $entry;
2620 warn "no such alias '$cidr'\n";
2623 $nethash->{$entry->{cidr}} = $entry;
2627 foreach my $cidr (sort keys %$nethash) {
2628 my $entry = $nethash->{$cidr};
2630 my $cmd = "add $name $cidr";
2631 if ($entry->{nomatch}) {
2632 if ($feature_ipset_nomatch) {
2633 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2635 warn "ignore !$cidr - nomatch not supported by kernel\n";
2638 push @{$ipset_ruleset->{$name}}, $cmd;
2643 sub round_powerof2 {
2647 $int |= $int >> $_ foreach (1,2,4,8,16);
2651 sub load_clusterfw_conf {
2652 my ($filename, $verbose) = @_;
2654 $filename = $clusterfw_conf_filename if !defined($filename);
2656 my $cluster_conf = {};
2657 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2658 $cluster_conf = parse_cluster_fw_rules($filename, $fh, $verbose);
2661 return $cluster_conf;
2664 sub save_clusterfw_conf {
2665 my ($cluster_conf) = @_;
2669 my $options = $cluster_conf->{options};
2670 $raw .= &$format_options($options) if scalar(keys %$options);
2672 my $aliases = $cluster_conf->{aliases};
2673 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2675 $raw .= &$format_ipsets($cluster_conf);
2677 my $rules = $cluster_conf->{rules};
2678 if (scalar(@$rules)) {
2679 $raw .= "[RULES]\n\n";
2680 $raw .= &$format_rules($rules, 1);
2684 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2685 my $rules = $cluster_conf->{groups}->{$group};
2686 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2687 my $utf8comment = encode('utf8
', $comment);
2688 $raw .= "[group $group] # $utf8comment\n\n";
2690 $raw .= "[group $group]\n\n";
2693 $raw .= &$format_rules($rules, 0);
2697 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2700 sub load_hostfw_conf {
2701 my ($cluster_conf, $filename, $verbose) = @_;
2703 $filename = $hostfw_conf_filename if !defined($filename);
2705 my $hostfw_conf = {};
2706 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2707 $hostfw_conf = parse_host_fw_rules($filename, $fh, $cluster_conf, $verbose);
2709 return $hostfw_conf;
2712 sub save_hostfw_conf {
2713 my ($hostfw_conf) = @_;
2717 my $options = $hostfw_conf->{options};
2718 $raw .= &$format_options($options) if scalar(keys %$options);
2720 my $rules = $hostfw_conf->{rules};
2721 if (scalar(@$rules)) {
2722 $raw .= "[RULES]\n\n";
2723 $raw .= &$format_rules($rules, 1);
2727 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2731 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2735 if ($vmdata) { # test mode
2736 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2737 my $filename = "$testdir/cluster.fw";
2738 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2740 $filename = "$testdir/host.fw";
2741 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2743 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2744 } else { # normal operation
2745 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2747 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2749 $vmdata = read_local_vm_config();
2750 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2753 $cluster_conf->{ipset}->{venet0} = [];
2754 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
2757 if ($cluster_conf->{aliases}->{local_network}) {
2758 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2760 $localnet = local_network() || '127.0.0.0/8';
2761 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2764 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2768 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2769 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2771 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2773 my $hostfw_options = $hostfw_conf->{options} || {};
2775 # fixme: what log level should we use here?
2776 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2778 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2781 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2782 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2783 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2785 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2786 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2788 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2790 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2791 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2793 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2794 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2796 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2798 generate_std_chains($ruleset, $hostfw_options);
2800 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2802 my $ipset_ruleset = {};
2804 if ($hostfw_enable) {
2805 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2806 warn $@ if $@; # just to be sure - should not happen
2809 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2811 # generate firewall rules for QEMU VMs
2812 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2814 my $conf = $vmdata->{qemu}->{$vmid};
2815 my $vmfw_conf = $vmfw_configs->{$vmid};
2816 return if !$vmfw_conf;
2817 return if !$vmfw_conf->{options}->{enable};
2819 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2821 foreach my $netid (keys %$conf) {
2822 next if $netid !~ m/^net(\d+)$/;
2823 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2824 next if !$net->{firewall};
2825 my $iface = "tap${vmid}i$1";
2827 my $macaddr = $net->{macaddr};
2828 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2829 $vmfw_conf, $vmid, 'IN
');
2830 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2831 $vmfw_conf, $vmid, 'OUT
');
2834 warn $@ if $@; # just to be sure - should not happen
2837 # generate firewall rules for OpenVZ containers
2838 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2840 my $conf = $vmdata->{openvz}->{$vmid};
2842 my $vmfw_conf = $vmfw_configs->{$vmid};
2843 return if !$vmfw_conf;
2844 return if !$vmfw_conf->{options}->{enable};
2846 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2848 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2849 my $ip = $conf->{ip_address}->{value};
2851 parse_address_list($ip); # make sure we have a valid $ip list
2853 my @ips = split(',', $ip);
2855 foreach my $singleip (@ips) {
2856 my $venet0ipset = {};
2857 $venet0ipset->{cidr} = $singleip;
2858 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2861 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2862 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2865 if ($conf->{netif} && $conf->{netif}->{value}) {
2866 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2867 foreach my $netid (keys %$netif) {
2868 my $d = $netif->{$netid};
2870 my $macaddr = $d->{mac};
2871 my $iface = $d->{host_ifname};
2872 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2873 $vmfw_conf, $vmid, 'IN
');
2874 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2875 $vmfw_conf, $vmid, 'OUT
');
2879 warn $@ if $@; # just to be sure - should not happen
2882 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2883 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2886 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
2888 return ($ruleset, $ipset_ruleset);
2891 sub get_ruleset_status {
2892 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2894 my $statushash = {};
2896 foreach my $chain (sort keys %$ruleset) {
2897 my $sig = &$digest_fn($ruleset->{$chain});
2899 $statushash->{$chain}->{sig} = $sig;
2901 my $oldsig = $active_chains->{$chain};
2902 if (!defined($oldsig)) {
2903 $statushash->{$chain}->{action} = 'create
';
2905 if ($oldsig eq $sig) {
2906 $statushash->{$chain}->{action} = 'exists';
2908 $statushash->{$chain}->{action} = 'update
';
2911 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2912 foreach my $cmd (@{$ruleset->{$chain}}) {
2913 print "\t$cmd\n" if $verbose;
2917 foreach my $chain (sort keys %$active_chains) {
2918 if (!defined($ruleset->{$chain})) {
2919 my $sig = $active_chains->{$chain};
2920 $statushash->{$chain}->{action} = 'delete';
2921 $statushash->{$chain}->{sig} = $sig;
2922 print "delete $chain ($sig)\n" if $verbose;
2929 sub print_sig_rule {
2930 my ($chain, $sig) = @_;
2932 # We just use this to store a SHA1 checksum used to detect changes
2933 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2936 sub get_ruleset_cmdlist {
2937 my ($ruleset, $verbose) = @_;
2939 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2941 my ($active_chains, $hooks) = iptables_get_chains();
2942 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2944 # create missing chains first
2945 foreach my $chain (sort keys %$ruleset) {
2946 my $stat = $statushash->{$chain};
2947 die "internal error" if !$stat;
2948 next if $stat->{action} ne 'create
';
2950 $cmdlist .= ":$chain - [0:0]\n";
2953 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2954 if (!$hooks->{$h}) {
2955 $cmdlist .= "-A $h -j PVEFW-$h\n";
2959 foreach my $chain (sort keys %$ruleset) {
2960 my $stat = $statushash->{$chain};
2961 die "internal error" if !$stat;
2963 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2964 $cmdlist .= "-F $chain\n";
2965 foreach my $cmd (@{$ruleset->{$chain}}) {
2966 $cmdlist .= "$cmd\n";
2968 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2969 } elsif ($stat->{action
} eq 'delete') {
2970 die "internal error"; # this should not happen
2971 } elsif ($stat->{action
} eq 'exists') {
2974 die "internal error - unknown status '$stat->{action}'";
2978 foreach my $chain (keys %$statushash) {
2979 next if $statushash->{$chain}->{action
} ne 'delete';
2980 $cmdlist .= "-F $chain\n";
2982 foreach my $chain (keys %$statushash) {
2983 next if $statushash->{$chain}->{action
} ne 'delete';
2984 next if $chain eq 'PVEFW-INPUT';
2985 next if $chain eq 'PVEFW-OUTPUT';
2986 next if $chain eq 'PVEFW-FORWARD';
2987 $cmdlist .= "-X $chain\n";
2990 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2992 $cmdlist .= "COMMIT\n";
2994 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2997 sub get_ipset_cmdlist
{
2998 my ($ruleset, $verbose) = @_;
3002 my $delete_cmdlist = "";
3004 my $active_chains = ipset_get_chains
();
3005 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3007 # remove stale _swap chains
3008 foreach my $chain (keys %$active_chains) {
3009 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3010 $cmdlist .= "destroy $chain\n";
3014 foreach my $chain (sort keys %$ruleset) {
3015 my $stat = $statushash->{$chain};
3016 die "internal error" if !$stat;
3018 if ($stat->{action
} eq 'create') {
3019 foreach my $cmd (@{$ruleset->{$chain}}) {
3020 $cmdlist .= "$cmd\n";
3024 if ($stat->{action
} eq 'update') {
3025 my $chain_swap = $chain."_swap";
3027 foreach my $cmd (@{$ruleset->{$chain}}) {
3028 $cmd =~ s/$chain/$chain_swap/;
3029 $cmdlist .= "$cmd\n";
3031 $cmdlist .= "swap $chain_swap $chain\n";
3032 $cmdlist .= "flush $chain_swap\n";
3033 $cmdlist .= "destroy $chain_swap\n";
3038 foreach my $chain (keys %$statushash) {
3039 next if $statushash->{$chain}->{action
} ne 'delete';
3041 $delete_cmdlist .= "flush $chain\n";
3042 $delete_cmdlist .= "destroy $chain\n";
3045 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3047 return ($cmdlist, $delete_cmdlist, $changes);
3051 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3053 enable_bridge_firewall
();
3055 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3056 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3058 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3061 if ($ipset_changes) {
3062 print "ipset changes:\n";
3063 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3064 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3068 print "iptables changes:\n";
3073 ipset_restore_cmdlist
($ipset_create_cmdlist);
3075 iptables_restore_cmdlist
($cmdlist);
3077 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3079 # test: re-read status and check if everything is up to date
3080 my $active_chains = iptables_get_chains
();
3081 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3084 foreach my $chain (sort keys %$ruleset) {
3085 my $stat = $statushash->{$chain};
3086 if ($stat->{action
} ne 'exists') {
3087 warn "unable to update chain '$chain'\n";
3092 die "unable to apply firewall changes\n" if $errors;
3094 update_nf_conntrack_max
($hostfw_conf);
3096 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3100 sub update_nf_conntrack_max
{
3101 my ($hostfw_conf) = @_;
3103 my $max = 65536; # reasonable default
3105 my $options = $hostfw_conf->{options
} || {};
3107 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3108 $max = $options->{nf_conntrack_max
};
3109 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3112 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3113 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3115 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3117 if ($current != $max) {
3118 my $hashsize = int($max/4);
3119 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3120 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3124 sub update_nf_conntrack_tcp_timeout_established
{
3125 my ($hostfw_conf) = @_;
3127 my $options = $hostfw_conf->{options
} || {};
3129 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3131 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3134 sub remove_pvefw_chains
{
3136 my ($chash, $hooks) = iptables_get_chains
();
3137 my $cmdlist = "*filter\n";
3139 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3141 $cmdlist .= "-D $h -j PVEFW-$h\n";
3145 foreach my $chain (keys %$chash) {
3146 $cmdlist .= "-F $chain\n";
3149 foreach my $chain (keys %$chash) {
3150 $cmdlist .= "-X $chain\n";
3152 $cmdlist .= "COMMIT\n";
3154 iptables_restore_cmdlist
($cmdlist);
3158 my $cluster_conf = load_clusterfw_conf
();
3159 my $cluster_options = $cluster_conf->{options
};
3160 my $enable = $cluster_options->{enable
};
3164 # load required modules here
3170 my $cluster_conf = load_clusterfw_conf
();
3171 my $cluster_options = $cluster_conf->{options
};
3173 my $enable = $cluster_options->{enable
};
3175 die "Firewall is disabled - cannot start\n" if !$enable;
3178 PVE
::Firewall
::remove_pvefw_chains
();
3182 my $hostfw_conf = load_hostfw_conf
();
3184 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3186 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset);