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 PVE
::JSONSchema
::register_format
('IPv4orCIDR', \
&pve_verify_ipv4_or_cidr
);
39 sub pve_verify_ipv4_or_cidr
{
40 my ($cidr, $noerr) = @_;
42 if ($cidr =~ m!^(?:$IPV4RE)(/(\d+))?$!) {
43 return $cidr if Net
::IP-
>new($cidr);
44 return undef if $noerr;
45 die Net
::IP
::Error
() . "\n";
47 return undef if $noerr;
48 die "value does not look like a valid IP address or CIDR network\n";
51 PVE
::JSONSchema
::register_standard_option
('ipset-name', {
52 description
=> "IP set name.",
54 pattern
=> '[A-Za-z][A-Za-z0-9\-\_]+',
59 PVE
::JSONSchema
::register_standard_option
('pve-fw-alias', {
60 description
=> "Alias name.",
62 pattern
=> '[A-Za-z][A-Za-z0-9\-\_]+',
67 PVE
::JSONSchema
::register_standard_option
('pve-fw-loglevel' => {
68 description
=> "Log level.",
70 enum
=> ['emerg', 'alert', 'crit', 'err', 'warning', 'notice', 'info', 'debug', 'nolog'],
74 my $security_group_name_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
75 my $ip_alias_pattern = '[A-Za-z][A-Za-z0-9\-\_]+';
77 PVE
::JSONSchema
::register_standard_option
('pve-security-group-name', {
78 description
=> "Security Group name.",
80 pattern
=> $security_group_name_pattern,
85 my $feature_ipset_nomatch = 0;
87 my (undef, undef, $release) = POSIX
::uname
();
88 if ($release =~ m/^(\d+)\.(\d+)\.\d+-/) {
89 my ($major, $minor) = ($1, $2);
90 $feature_ipset_nomatch = 1 if ($major > 3) ||
91 ($major == 3 && $minor >= 7);
98 my $nodename = PVE
::INotify
::nodename
();
100 my $pve_fw_lock_filename = "/var/lock/pvefw.lck";
102 my $default_log_level = 'nolog'; # avoid logs by default
104 my $log_level_hash = {
115 # imported/converted from: /usr/share/shorewall/macro.*
116 my $pve_fw_macros = {
119 { action
=> 'PARAM', proto
=> 'udp', dport
=> '10080' },
120 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10080' },
123 "Auth (identd) traffic",
124 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '113' },
127 "Border Gateway Protocol traffic",
128 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '179' },
131 "BitTorrent traffic for BitTorrent 3.1 and earlier",
132 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6889' },
133 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
136 "BitTorrent traffic for BitTorrent 3.2 and later",
137 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6881:6999' },
138 { action
=> 'PARAM', proto
=> 'udp', dport
=> '6881' },
141 "Concurrent Versions System pserver traffic",
142 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2401' },
145 "Citrix/ICA traffic (ICA, ICA Browser, CGP)",
146 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1494' },
147 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1604' },
148 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2598' },
151 "Digital Audio Access Protocol traffic (iTunes, Rythmbox daemons)",
152 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3689' },
153 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3689' },
156 "Distributed Checksum Clearinghouse spam filtering mechanism",
157 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6277' },
160 "Forwarded DHCP traffic",
161 { action
=> 'PARAM', proto
=> 'udp', dport
=> '67:68', sport
=> '67:68' },
164 "Domain Name System traffic (upd and tcp)",
165 { action
=> 'PARAM', proto
=> 'udp', dport
=> '53' },
166 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '53' },
169 "Distributed Compiler service",
170 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3632' },
173 "File Transfer Protocol",
174 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '21' },
177 "Finger protocol (RFC 742)",
178 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '79' },
181 "GNUnet secure peer-to-peer networking traffic",
182 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '2086' },
183 { action
=> 'PARAM', proto
=> 'udp', dport
=> '2086' },
184 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1080' },
185 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1080' },
188 "Generic Routing Encapsulation tunneling protocol",
189 { action
=> 'PARAM', proto
=> '47' },
192 "Git distributed revision control traffic",
193 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9418' },
196 "OpenPGP HTTP keyserver protocol traffic",
197 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '11371' },
200 "Hypertext Transfer Protocol (WWW)",
201 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
204 "Hypertext Transfer Protocol (WWW) over SSL",
205 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
208 "Internet Cache Protocol V2 (Squid) traffic",
209 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3130' },
212 "AOL Instant Messenger traffic",
213 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5190' },
216 "Internet Message Access Protocol",
217 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '143' },
220 "Internet Message Access Protocol over SSL",
221 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '993' },
224 "IPIP capsulation traffic",
225 { action
=> 'PARAM', proto
=> '94' },
229 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
230 { action
=> 'PARAM', proto
=> '50' },
233 "IPsec authentication (AH) traffic",
234 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500', sport
=> '500' },
235 { action
=> 'PARAM', proto
=> '51' },
238 "IPsec traffic and Nat-Traversal",
239 { action
=> 'PARAM', proto
=> 'udp', dport
=> '500' },
240 { action
=> 'PARAM', proto
=> 'udp', dport
=> '4500' },
241 { action
=> 'PARAM', proto
=> '50' },
244 "Internet Relay Chat traffic",
245 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6667' },
248 "HP Jetdirect printing",
249 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '9100' },
252 "Layer 2 Tunneling Protocol traffic",
253 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1701' },
256 "Lightweight Directory Access Protocol traffic",
257 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '389' },
260 "Secure Lightweight Directory Access Protocol traffic",
261 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '636' },
264 "Microsoft Notification Protocol",
265 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1863' },
268 "Microsoft SQL Server",
269 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1433' },
272 "Mail traffic (SMTP, SMTPS, Submission)",
273 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
274 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
275 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
278 "Munin networked resource monitoring traffic",
279 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '4949' },
283 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3306' },
286 "NNTP traffic (Usenet).",
287 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '119' },
290 "Encrypted NNTP traffic (Usenet)",
291 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '563' },
294 "Network Time Protocol (ntpd)",
295 { action
=> 'PARAM', proto
=> 'udp', dport
=> '123' },
298 "OSPF multicast traffic",
299 { action
=> 'PARAM', proto
=> '89' },
303 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1194' },
306 "Symantec PCAnywere (tm)",
307 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5632' },
308 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5631' },
312 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '110' },
315 "Encrypted POP3 traffic",
316 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '995' },
319 "Point-to-Point Tunneling Protocol",
320 { action
=> 'PARAM', proto
=> '47' },
321 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '1723' },
325 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
329 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5432' },
332 "Line Printer protocol printing",
333 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '515' },
336 "Microsoft Remote Desktop Protocol traffic",
337 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3389' },
340 "Routing Information Protocol (bidirectional)",
341 { action
=> 'PARAM', proto
=> 'udp', dport
=> '520' },
344 "BIND remote management protocol",
345 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '953' },
348 "Razor Antispam System",
349 { action
=> 'ACCEPT', proto
=> 'tcp', dport
=> '2703' },
352 "Remote time retrieval (rdate)",
353 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
357 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '873' },
360 "SANE network scanning",
361 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '6566' },
364 "Microsoft SMB traffic",
365 { action
=> 'PARAM', proto
=> 'udp', dport
=> '135,445' },
366 { action
=> 'PARAM', proto
=> 'udp', dport
=> '137:139' },
367 { action
=> 'PARAM', proto
=> 'udp', dport
=> '1024:65535', sport
=> '137' },
368 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '135,139,445' },
371 "Samba Web Administration Tool",
372 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '901' },
375 "Simple Mail Transfer Protocol",
376 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '25' },
379 "Encrypted Simple Mail Transfer Protocol",
380 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '465' },
383 "Simple Network Management Protocol",
384 { action
=> 'PARAM', proto
=> 'udp', dport
=> '161:162' },
385 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '161' },
388 "Spam Assassin SPAMD traffic",
389 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '783' },
392 "Secure shell traffic",
393 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '22' },
396 "Subversion server (svnserve)",
397 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3690' },
400 "SixXS IPv6 Deployment and Tunnel Broker",
401 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3874' },
402 { action
=> 'PARAM', proto
=> 'udp', dport
=> '3740' },
403 { action
=> 'PARAM', proto
=> '41' },
404 { action
=> 'PARAM', proto
=> 'udp', dport
=> '5072,8374' },
407 "Squid web proxy traffic",
408 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '3128' },
411 "Mail message submission traffic",
412 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '587' },
415 "Syslog protocol (RFC 5424) traffic",
416 { action
=> 'PARAM', proto
=> 'udp', dport
=> '514' },
417 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '514' },
420 "Trivial File Transfer Protocol traffic",
421 { action
=> 'PARAM', proto
=> 'udp', dport
=> '69' },
425 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '23' },
429 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '992' },
432 "RFC 868 Time protocol",
433 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '37' },
436 "Traceroute (for up to 30 hops) traffic",
437 { action
=> 'PARAM', proto
=> 'udp', dport
=> '33434:33524' },
438 { action
=> 'PARAM', proto
=> 'icmp', dport
=> 'echo-request' },
441 "VNC traffic for VNC display's 0 - 99",
442 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5900:5999' },
445 "VNC traffic from Vncservers to Vncviewers in listen mode",
446 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '5500' },
449 "WWW traffic (HTTP and HTTPS)",
450 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '80' },
451 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '443' },
454 "Web Cache/Proxy traffic (port 8080)",
455 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '8080' },
459 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '10000' },
462 "Whois (nicname, RFC 3912) traffic",
463 { action
=> 'PARAM', proto
=> 'tcp', dport
=> '43' },
467 my $pve_fw_parsed_macros;
468 my $pve_fw_macro_descr;
469 my $pve_fw_preferred_macro_names = {};
471 my $pve_std_chains = {
472 'PVEFW-SET-ACCEPT-MARK' => [
473 "-j MARK --set-mark 1",
475 'PVEFW-DropBroadcast' => [
476 # same as shorewall 'Broadcast'
477 # simply DROP BROADCAST/MULTICAST/ANYCAST
478 # we can use this to reduce logging
479 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
480 { action
=> 'DROP', dsttype
=> 'MULTICAST' },
481 { action
=> 'DROP', dsttype
=> 'ANYCAST' },
482 { action
=> 'DROP', dest
=> '224.0.0.0/4' },
485 # same as shorewall 'reject'
486 { action
=> 'DROP', dsttype
=> 'BROADCAST' },
487 { action
=> 'DROP', source
=> '224.0.0.0/4' },
488 { action
=> 'DROP', proto
=> 'icmp' },
489 "-p tcp -j REJECT --reject-with tcp-reset",
490 "-p udp -j REJECT --reject-with icmp-port-unreachable",
491 "-p icmp -j REJECT --reject-with icmp-host-unreachable",
492 "-j REJECT --reject-with icmp-host-prohibited",
495 # same as shorewall 'Drop', which is equal to DROP,
496 # but REJECT/DROP some packages to reduce logging,
497 # and ACCEPT critical ICMP types
498 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
499 # we are not interested in BROADCAST/MULTICAST/ANYCAST
500 { action
=> 'PVEFW-DropBroadcast' },
501 # ACCEPT critical ICMP types
502 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
503 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
504 # Drop packets with INVALID state
505 "-m conntrack --ctstate INVALID -j DROP",
506 # Drop Microsoft SMB noise
507 { action
=> 'DROP', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
508 { action
=> 'DROP', proto
=> 'udp', dport
=> '137:139'},
509 { action
=> 'DROP', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
510 { action
=> 'DROP', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
511 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
512 # Drop new/NotSyn traffic so that it doesn't get logged
513 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
515 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
518 # same as shorewall 'Reject', which is equal to Reject,
519 # but REJECT/DROP some packages to reduce logging,
520 # and ACCEPT critical ICMP types
521 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '43' }, # REJECT 'auth'
522 # we are not interested in BROADCAST/MULTICAST/ANYCAST
523 { action
=> 'PVEFW-DropBroadcast' },
524 # ACCEPT critical ICMP types
525 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'fragmentation-needed' },
526 { action
=> 'ACCEPT', proto
=> 'icmp', dport
=> 'time-exceeded' },
527 # Drop packets with INVALID state
528 "-m conntrack --ctstate INVALID -j DROP",
529 # Drop Microsoft SMB noise
530 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '135,445', nbdport
=> 2 },
531 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '137:139'},
532 { action
=> 'PVEFW-reject', proto
=> 'udp', dport
=> '1024:65535', sport
=> 137 },
533 { action
=> 'PVEFW-reject', proto
=> 'tcp', dport
=> '135,139,445', nbdport
=> 3 },
534 { action
=> 'DROP', proto
=> 'udp', dport
=> 1900 }, # UPnP
535 # Drop new/NotSyn traffic so that it doesn't get logged
536 "-p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -j DROP",
538 { action
=> 'DROP', proto
=> 'udp', sport
=> 53 },
540 'PVEFW-tcpflags' => [
541 # same as shorewall tcpflags action.
542 # Packets arriving on this interface are checked for som illegal combinations of TCP flags
543 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -g PVEFW-logflags",
544 "-p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -g PVEFW-logflags",
545 "-p tcp -m tcp --tcp-flags SYN,RST SYN,RST -g PVEFW-logflags",
546 "-p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -g PVEFW-logflags",
547 "-p tcp -m tcp --sport 0 --tcp-flags FIN,SYN,RST,ACK SYN -g PVEFW-logflags",
550 # same as shorewall smurfs action
551 # Filter packets for smurfs (packets with a broadcast address as the source).
552 "-s 0.0.0.0/32 -j RETURN",
553 "-m addrtype --src-type BROADCAST -g PVEFW-smurflog",
554 "-s 224.0.0.0/4 -g PVEFW-smurflog",
558 # iptables -p icmp -h
559 my $icmp_type_names = {
562 'destination-unreachable' => 1,
563 'network-unreachable' => 1,
564 'host-unreachable' => 1,
565 'protocol-unreachable' => 1,
566 'port-unreachable' => 1,
567 'fragmentation-needed' => 1,
568 'source-route-failed' => 1,
569 'network-unknown' => 1,
571 'network-prohibited' => 1,
572 'host-prohibited' => 1,
573 'TOS-network-unreachable' => 1,
574 'TOS-host-unreachable' => 1,
575 'communication-prohibited' => 1,
576 'host-precedence-violation' => 1,
577 'precedence-cutoff' => 1,
578 'source-quench' => 1,
580 'network-redirect' => 1,
581 'host-redirect' => 1,
582 'TOS-network-redirect' => 1,
583 'TOS-host-redirect' => 1,
585 'router-advertisement' => 1,
586 'router-solicitation' => 1,
587 'time-exceeded' => 1,
588 'ttl-zero-during-transit' => 1,
589 'ttl-zero-during-reassembly' => 1,
590 'parameter-problem' => 1,
591 'ip-header-bad' => 1,
592 'required-option-missing' => 1,
593 'timestamp-request' => 1,
594 'timestamp-reply' => 1,
595 'address-mask-request' => 1,
596 'address-mask-reply' => 1,
599 sub init_firewall_macros
{
601 $pve_fw_parsed_macros = {};
603 foreach my $k (keys %$pve_fw_macros) {
604 my $lc_name = lc($k);
605 my $macro = $pve_fw_macros->{$k};
606 if (!ref($macro->[0])) {
607 $pve_fw_macro_descr->{$k} = shift @$macro;
609 $pve_fw_preferred_macro_names->{$lc_name} = $k;
610 $pve_fw_parsed_macros->{$k} = $macro;
614 init_firewall_macros
();
617 return wantarray ?
($pve_fw_parsed_macros, $pve_fw_macro_descr): $pve_fw_parsed_macros;
622 sub get_etc_services
{
624 return $etc_services if $etc_services;
626 my $filename = "/etc/services";
628 my $fh = IO
::File-
>new($filename, O_RDONLY
);
630 warn "unable to read '$filename' - $!\n";
636 while (my $line = <$fh>) {
638 next if $line =~m/^#/;
639 next if ($line =~m/^\s*$/);
641 if ($line =~ m!^(\S+)\s+(\S+)/(tcp|udp).*$!) {
642 $services->{byid
}->{$2}->{name
} = $1;
643 $services->{byid
}->{$2}->{port
} = $2;
644 $services->{byid
}->{$2}->{$3} = 1;
645 $services->{byname
}->{$1} = $services->{byid
}->{$2};
651 $etc_services = $services;
654 return $etc_services;
659 sub get_etc_protocols
{
660 return $etc_protocols if $etc_protocols;
662 my $filename = "/etc/protocols";
664 my $fh = IO
::File-
>new($filename, O_RDONLY
);
666 warn "unable to read '$filename' - $!\n";
672 while (my $line = <$fh>) {
674 next if $line =~m/^#/;
675 next if ($line =~m/^\s*$/);
677 if ($line =~ m!^(\S+)\s+(\d+)\s+.*$!) {
678 $protocols->{byid
}->{$2}->{name
} = $1;
679 $protocols->{byname
}->{$1} = $protocols->{byid
}->{$2};
685 $etc_protocols = $protocols;
687 return $etc_protocols;
690 my $ipv4_mask_hash_localnet = {
692 '255.255.128.0' => 17,
693 '255.255.192.0' => 18,
694 '255.255.224.0' => 19,
695 '255.255.240.0' => 20,
696 '255.255.248.0' => 21,
697 '255.255.252.0' => 22,
698 '255.255.254.0' => 23,
699 '255.255.255.0' => 24,
700 '255.255.255.128' => 25,
701 '255.255.255.192' => 26,
702 '255.255.255.224' => 27,
703 '255.255.255.240' => 28,
704 '255.255.255.248' => 29,
705 '255.255.255.252' => 30,
711 my ($new_value) = @_;
713 $__local_network = $new_value if defined($new_value);
715 return $__local_network if defined($__local_network);
718 my $nodename = PVE
::INotify
::nodename
();
720 my $ip = PVE
::Cluster
::remote_node_ip
($nodename);
722 my $testip = Net
::IP-
>new($ip);
724 my $routes = PVE
::ProcFSTools
::read_proc_net_route
();
725 foreach my $entry (@$routes) {
726 my $mask = $ipv4_mask_hash_localnet->{$entry->{mask
}};
727 next if !defined($mask);
728 return if $mask eq '0.0.0.0';
729 my $cidr = "$entry->{dest}/$mask";
730 my $testnet = Net
::IP-
>new($cidr);
731 if ($testnet->overlaps($testip)) {
732 $__local_network = $cidr;
739 return $__local_network;
742 sub parse_address_list
{
745 return if $str =~ m/^(\+)(\S+)$/; # ipset ref
746 return if $str =~ m/^${ip_alias_pattern}$/;
750 foreach my $elem (split(/,/, $str)) {
752 if (!Net
::IP-
>new($elem)) {
753 my $err = Net
::IP
::Error
();
754 die "invalid IP address: $err\n";
756 $iprange = 1 if $elem =~ m/-/;
759 die "you can use a range in a list\n" if $iprange && $count > 1;
762 sub parse_port_name_number_or_range
{
765 my $services = PVE
::Firewall
::get_etc_services
();
769 foreach my $item (split(/,/, $str)) {
771 if ($item =~ m/^(\d+):(\d+)$/) {
772 my ($port1, $port2) = ($1, $2);
773 die "invalid port '$port1'\n" if $port1 > 65535;
774 die "invalid port '$port2'\n" if $port2 > 65535;
775 } elsif ($item =~ m/^(\d+)$/) {
777 die "invalid port '$port'\n" if $port > 65535;
779 if ($icmp_type_names->{$item}) {
782 die "invalid port '$item'\n" if !$services->{byname
}->{$item};
787 die "ICPM ports not allowed in port range\n" if $icmp_port && $count > 1;
792 PVE
::JSONSchema
::register_format
('pve-fw-port-spec', \
&pve_fw_verify_port_spec
);
793 sub pve_fw_verify_port_spec
{
796 parse_port_name_number_or_range
($portstr);
801 PVE
::JSONSchema
::register_format
('pve-fw-v4addr-spec', \
&pve_fw_verify_v4addr_spec
);
802 sub pve_fw_verify_v4addr_spec
{
805 parse_address_list
($list);
810 PVE
::JSONSchema
::register_format
('pve-fw-protocol-spec', \
&pve_fw_verify_protocol_spec
);
811 sub pve_fw_verify_protocol_spec
{
814 my $protocols = get_etc_protocols
();
816 die "unknown protocol '$proto'\n" if $proto &&
817 !(defined($protocols->{byname
}->{$proto}) ||
818 defined($protocols->{byid
}->{$proto}));
824 # helper function for API
826 sub copy_opject_with_digest
{
829 my $sha = Digest
::SHA-
>new('sha1');
832 foreach my $k (sort keys %$object) {
833 my $v = $object->{$k};
834 next if !defined($v);
836 $sha->add($k, ':', $v, "\n");
839 my $digest = $sha->hexdigest;
841 $res->{digest
} = $digest;
843 return wantarray ?
($res, $digest) : $res;
846 sub copy_list_with_digest
{
849 my $sha = Digest
::SHA-
>new('sha1');
852 foreach my $entry (@$list) {
854 foreach my $k (sort keys %$entry) {
855 my $v = $entry->{$k};
856 next if !defined($v);
858 # Note: digest ignores refs ($rule->{errors})
859 $sha->add($k, ':', $v, "\n") if !ref($v); ;
864 my $digest = $sha->hexdigest;
866 foreach my $entry (@$res) {
867 $entry->{digest
} = $digest;
870 return wantarray ?
($res, $digest) : $res;
873 my $rule_properties = {
875 description
=> "Update rule at position <pos>.",
880 digest
=> get_standard_option
('pve-config-digest'),
884 enum
=> ['in', 'out', 'group'],
887 description
=> "Rule action ('ACCEPT', 'DROP', 'REJECT') or security group name.",
890 pattern
=> $security_group_name_pattern,
899 iface
=> get_standard_option
('pve-iface', { optional
=> 1 }),
901 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
905 type
=> 'string', format
=> 'pve-fw-v4addr-spec',
909 type
=> 'string', format
=> 'pve-fw-protocol-spec',
917 type
=> 'string', format
=> 'pve-fw-port-spec',
921 type
=> 'string', format
=> 'pve-fw-port-spec',
930 sub add_rule_properties
{
931 my ($properties) = @_;
933 foreach my $k (keys %$rule_properties) {
934 my $h = $rule_properties->{$k};
935 # copy data, so that we can modify later without side effects
936 foreach my $opt (keys %$h) { $properties->{$k}->{$opt} = $h->{$opt}; }
942 sub delete_rule_properties
{
943 my ($rule, $delete_str) = @_;
945 foreach my $opt (PVE
::Tools
::split_list
($delete_str)) {
946 raise_param_exc
({ 'delete' => "no such property ('$opt')"})
947 if !defined($rule_properties->{$opt});
948 raise_param_exc
({ 'delete' => "unable to delete required property '$opt'"})
949 if $opt eq 'type' || $opt eq 'action';
950 delete $rule->{$opt};
956 my $apply_macro = sub {
957 my ($macro_name, $param, $verify) = @_;
959 my $macro_rules = $pve_fw_parsed_macros->{$macro_name};
960 die "unknown macro '$macro_name'\n" if !$macro_rules; # should not happen
964 foreach my $templ (@$macro_rules) {
967 foreach my $k (keys %$templ) {
968 my $v = $templ->{$k};
971 $param_used->{$k} = 1;
972 } elsif ($v eq 'DEST') {
974 $param_used->{dest
} = 1;
975 } elsif ($v eq 'SOURCE') {
976 $v = $param->{source
};
977 $param_used->{source
} = 1;
981 my $msg = "missing parameter '$k' in macro '$macro_name'";
982 raise_param_exc
({ macro => $msg }) if $verify;
987 foreach my $k (keys %$param) {
988 next if $k eq 'macro';
989 next if !defined($param->{$k});
990 next if $param_used->{$k};
991 if (defined($rule->{$k})) {
992 if ($rule->{$k} ne $param->{$k}) {
993 my $msg = "parameter '$k' already define in macro (value = '$rule->{$k}')";
994 raise_param_exc
({ $k => $msg }) if $verify;
998 $rule->{$k} = $param->{$k};
1001 push @$rules, $rule;
1007 my $rule_env_iface_lookup = {
1016 my ($rule, $cluster_conf, $fw_conf, $rule_env, $noerr) = @_;
1018 my $allow_groups = $rule_env eq 'group' ?
0 : 1;
1020 my $allow_iface = $rule_env_iface_lookup->{$rule_env};
1021 die "unknown rule_env '$rule_env'\n" if !defined($allow_iface); # should not happen
1023 my $errors = $rule->{errors
} || {};
1025 my $error_count = 0;
1027 my $add_error = sub {
1028 my ($param, $msg) = @_;
1030 raise_param_exc
({ $param => $msg }) if !$noerr;
1032 $errors->{$param} = $msg if !$errors->{$param};
1035 my $check_ipset_or_alias_property = sub {
1038 if (my $value = $rule->{$name}) {
1039 if ($value =~ m/^\+/) {
1040 if ($value =~ m/^\+(${security_group_name_pattern})$/) {
1041 &$add_error($name, "no such ipset '$1'")
1042 if !($cluster_conf->{ipset
}->{$1} || ($fw_conf && $fw_conf->{ipset
}->{$1}));
1045 &$add_error($name, "invalid security group name '$value'");
1047 } elsif ($value =~ m/^${ip_alias_pattern}$/){
1048 my $alias = lc($value);
1049 &$add_error($name, "no such alias '$value'")
1050 if !($cluster_conf->{aliases
}->{$alias} || ($fw_conf && $fw_conf->{aliases
}->{$alias}))
1055 my $type = $rule->{type
};
1056 my $action = $rule->{action
};
1058 &$add_error('type', "missing property") if !$type;
1059 &$add_error('action', "missing property") if !$action;
1062 if ($type eq 'in' || $type eq 'out') {
1063 &$add_error('action', "unknown action '$action'")
1064 if $action && ($action !~ m/^(ACCEPT|DROP|REJECT)$/);
1065 } elsif ($type eq 'group') {
1066 &$add_error('type', "security groups not allowed")
1068 &$add_error('action', "invalid characters in security group name")
1069 if $action && ($action !~ m/^${security_group_name_pattern}$/);
1071 &$add_error('type', "unknown rule type '$type'");
1075 if ($rule->{iface
}) {
1076 &$add_error('type', "parameter -i not allowed for this rule type")
1078 eval { PVE
::JSONSchema
::pve_verify_iface
($rule->{iface
}); };
1079 &$add_error('iface', $@) if $@;
1080 if ($rule_env eq 'vm') {
1081 &$add_error('iface', "value does not match the regex pattern 'net\\d+'")
1082 if $rule->{iface
} !~ m/^net(\d+)$/;
1083 } elsif ($rule_env eq 'ct') {
1084 &$add_error('iface', "value does not match the regex pattern '(venet|eth\\d+)'")
1085 if $rule->{iface
} !~ m/^(venet|eth(\d+))$/;
1089 if ($rule->{macro}) {
1090 if (my $preferred_name = $pve_fw_preferred_macro_names->{lc($rule->{macro})}) {
1091 $rule->{macro} = $preferred_name;
1093 &$add_error('macro', "unknown macro '$rule->{macro}'");
1097 if ($rule->{proto
}) {
1098 eval { pve_fw_verify_protocol_spec
($rule->{proto
}); };
1099 &$add_error('proto', $@) if $@;
1102 if ($rule->{dport
}) {
1103 eval { parse_port_name_number_or_range
($rule->{dport
}); };
1104 &$add_error('dport', $@) if $@;
1105 &$add_error('proto', "missing property - 'dport' requires this property")
1109 if ($rule->{sport
}) {
1110 eval { parse_port_name_number_or_range
($rule->{sport
}); };
1111 &$add_error('sport', $@) if $@;
1112 &$add_error('proto', "missing property - 'sport' requires this property")
1116 if ($rule->{source
}) {
1117 eval { parse_address_list
($rule->{source
}); };
1118 &$add_error('source', $@) if $@;
1119 &$check_ipset_or_alias_property('source');
1122 if ($rule->{dest
}) {
1123 eval { parse_address_list
($rule->{dest
}); };
1124 &$add_error('dest', $@) if $@;
1125 &$check_ipset_or_alias_property('dest');
1128 if ($rule->{macro} && !$error_count) {
1129 eval { &$apply_macro($rule->{macro}, $rule, 1); };
1131 if (ref($err) eq "PVE::Exception" && $err->{errors
}) {
1132 my $eh = $err->{errors
};
1133 foreach my $p (keys %$eh) {
1134 &$add_error($p, $eh->{$p});
1137 &$add_error('macro', "$err");
1142 $rule->{errors
} = $errors if $error_count;
1147 sub copy_rule_data
{
1148 my ($rule, $param) = @_;
1150 foreach my $k (keys %$rule_properties) {
1151 if (defined(my $v = $param->{$k})) {
1152 if ($v eq '' || $v eq '-') {
1164 my $bridge_firewall_enabled = 0;
1166 sub enable_bridge_firewall
{
1168 return if $bridge_firewall_enabled; # only once
1170 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-iptables", "1");
1171 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "1");
1173 # make sure syncookies are enabled (which is default on newer 3.X kernels anyways)
1174 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/ipv4/tcp_syncookies", "1");
1176 $bridge_firewall_enabled = 1;
1179 my $rule_format = "%-15s %-30s %-30s %-15s %-15s %-15s\n";
1181 sub iptables_restore_cmdlist
{
1184 run_command
("/sbin/iptables-restore -n", input
=> $cmdlist);
1187 sub ipset_restore_cmdlist
{
1190 run_command
("/usr/sbin/ipset restore", input
=> $cmdlist);
1193 sub iptables_get_chains
{
1197 # check what chains we want to track
1198 my $is_pvefw_chain = sub {
1201 return 1 if $name =~ m/^PVEFW-\S+$/;
1203 return 1 if $name =~ m/^tap\d+i\d+-(:?IN|OUT)$/;
1205 return 1 if $name =~ m/^veth\d+.\d+-(:?IN|OUT)$/; # fixme: dev name is configurable
1207 return 1 if $name =~ m/^venet0-\d+-(:?IN|OUT)$/;
1209 return 1 if $name =~ m/^fwbr\d+(v\d+)?-(:?FW|IN|OUT|IPS)$/;
1210 return 1 if $name =~ m/^GROUP-(:?[^\s\-]+)-(:?IN|OUT)$/;
1222 return if $line =~ m/^#/;
1223 return if $line =~ m/^\s*$/;
1225 if ($line =~ m/^\*(\S+)$/) {
1230 return if $table ne 'filter';
1232 if ($line =~ m/^:(\S+)\s/) {
1234 return if !&$is_pvefw_chain($chain);
1235 $res->{$chain} = "unknown";
1236 } elsif ($line =~ m/^-A\s+(\S+)\s.*--comment\s+\"PVESIG:(\S+)\"/) {
1237 my ($chain, $sig) = ($1, $2);
1238 return if !&$is_pvefw_chain($chain);
1239 $res->{$chain} = $sig;
1240 } elsif ($line =~ m/^-A\s+(INPUT|OUTPUT|FORWARD)\s+-j\s+PVEFW-\1$/) {
1243 # simply ignore the rest
1248 run_command
("/sbin/iptables-save", outfunc
=> $parser);
1250 return wantarray ?
($res, $hooks) : $res;
1253 sub iptables_chain_digest
{
1255 my $digest = Digest
::SHA-
>new('sha1');
1256 foreach my $rule (@$rules) { # order is important
1257 $digest->add($rule);
1259 return $digest->b64digest;
1262 sub ipset_chain_digest
{
1265 my $digest = Digest
::SHA-
>new('sha1');
1266 foreach my $rule (sort @$rules) { # note: sorted
1267 $digest->add($rule);
1269 return $digest->b64digest;
1272 sub ipset_get_chains
{
1280 return if $line =~ m/^#/;
1281 return if $line =~ m/^\s*$/;
1282 if ($line =~ m/^(?:\S+)\s(PVEFW-\S+)\s(?:\S+).*/) {
1284 $line =~ s/\s+$//; # delete trailing white space
1285 push @{$chains->{$chain}}, $line;
1287 # simply ignore the rest
1292 run_command
("/usr/sbin/ipset save", outfunc
=> $parser);
1294 # compute digest for each chain
1295 foreach my $chain (keys %$chains) {
1296 $res->{$chain} = ipset_chain_digest
($chains->{$chain});
1302 sub ruleset_generate_cmdstr
{
1303 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1305 return if defined($rule->{enable
}) && !$rule->{enable
};
1306 return if $rule->{errors
};
1308 die "unable to emit macro - internal error" if $rule->{macro}; # should not happen
1310 my $nbdport = defined($rule->{dport
}) ? parse_port_name_number_or_range
($rule->{dport
}) : 0;
1311 my $nbsport = defined($rule->{sport
}) ? parse_port_name_number_or_range
($rule->{sport
}) : 0;
1315 push @cmd, "-i $rule->{iface_in}" if $rule->{iface_in
};
1316 push @cmd, "-o $rule->{iface_out}" if $rule->{iface_out
};
1318 my $source = $rule->{source
};
1319 my $dest = $rule->{dest
};
1322 if ($source =~ m/^\+/) {
1323 if ($source =~ m/^\+(${security_group_name_pattern})$/) {
1324 die "no such ipset '$1'\n" if !$cluster_conf->{ipset
}->{$1};
1325 push @cmd, "-m set --match-set PVEFW-$1 src";
1327 die "invalid security group name '$source'\n";
1329 } elsif ($source =~ m/^${ip_alias_pattern}$/){
1330 my $alias = lc($source);
1331 my $e = $cluster_conf->{aliases
}->{$alias};
1332 die "no such alias $source\n" if !$e;
1333 push @cmd, "-s $e->{cidr}";
1334 } elsif ($source =~ m/\-/){
1335 push @cmd, "-m iprange --src-range $source";
1338 push @cmd, "-s $source";
1343 if ($dest =~ m/^\+/) {
1344 if ($dest =~ m/^\+(${security_group_name_pattern})$/) {
1345 die "no such ipset '$1'\n" if !$cluster_conf->{ipset
}->{$1};
1346 push @cmd, "-m set --match-set PVEFW-$1 dst";
1348 die "invalid security group name '$dest'\n";
1350 } elsif ($dest =~ m/^${ip_alias_pattern}$/){
1351 my $alias = lc($dest);
1352 my $e = $cluster_conf->{aliases
}->{$alias};
1353 die "no such alias $dest" if !$e;
1354 push @cmd, "-d $e->{cidr}";
1355 } elsif ($dest =~ m/^(\d+)\.(\d+).(\d+).(\d+)\-(\d+)\.(\d+).(\d+).(\d+)$/){
1356 push @cmd, "-m iprange --dst-range $dest";
1359 push @cmd, "-d $dest";
1363 if ($rule->{proto
}) {
1364 push @cmd, "-p $rule->{proto}";
1367 $multiport++ if $nbdport > 1;
1368 $multiport++ if $nbsport > 1;
1370 push @cmd, "--match multiport" if $multiport;
1372 die "multiport: option '--sports' cannot be used together with '--dports'\n"
1373 if ($multiport == 2) && ($rule->{dport
} ne $rule->{sport
});
1375 if ($rule->{dport
}) {
1376 if ($rule->{proto
} && $rule->{proto
} eq 'icmp') {
1377 # Note: we use dport to store --icmp-type
1378 die "unknown icmp-type '$rule->{dport}'\n" if !defined($icmp_type_names->{$rule->{dport
}});
1379 push @cmd, "-m icmp --icmp-type $rule->{dport}";
1382 if ($multiport == 2) {
1383 push @cmd, "--ports $rule->{dport}";
1385 push @cmd, "--dports $rule->{dport}";
1388 push @cmd, "--dport $rule->{dport}";
1393 if ($rule->{sport
}) {
1395 push @cmd, "--sports $rule->{sport}" if $multiport != 2;
1397 push @cmd, "--sport $rule->{sport}";
1400 } elsif ($rule->{dport
} || $rule->{sport
}) {
1401 die "destination port '$rule->{dport}', but no protocol specified\n" if $rule->{dport
};
1402 die "source port '$rule->{sport}', but no protocol specified\n" if $rule->{sport
};
1405 push @cmd, "-m addrtype --dst-type $rule->{dsttype}" if $rule->{dsttype
};
1407 if (my $action = $rule->{action
}) {
1408 $action = $actions->{$action} if defined($actions->{$action});
1409 $goto = 1 if !defined($goto) && $action eq 'PVEFW-SET-ACCEPT-MARK';
1410 push @cmd, $goto ?
"-g $action" : "-j $action";
1413 return scalar(@cmd) ?
join(' ', @cmd) : undef;
1416 sub ruleset_generate_rule
{
1417 my ($ruleset, $chain, $rule, $actions, $goto, $cluster_conf) = @_;
1421 if ($rule->{macro}) {
1422 $rules = &$apply_macro($rule->{macro}, $rule);
1427 # update all or nothing
1430 foreach my $tmp (@$rules) {
1431 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $tmp, $actions, $goto, $cluster_conf)) {
1432 push @cmds, $cmdstr;
1436 foreach my $cmdstr (@cmds) {
1437 ruleset_addrule
($ruleset, $chain, $cmdstr);
1441 sub ruleset_generate_rule_insert
{
1442 my ($ruleset, $chain, $rule, $actions, $goto) = @_;
1444 die "implement me" if $rule->{macro}; # not implemented, because not needed so far
1446 if (my $cmdstr = ruleset_generate_cmdstr
($ruleset, $chain, $rule, $actions, $goto)) {
1447 ruleset_insertrule
($ruleset, $chain, $cmdstr);
1451 sub ruleset_create_chain
{
1452 my ($ruleset, $chain) = @_;
1454 die "Invalid chain name '$chain' (28 char max)\n" if length($chain) > 28;
1455 die "chain name may not contain collons\n" if $chain =~ m/:/; # because of log format
1457 die "chain '$chain' already exists\n" if $ruleset->{$chain};
1459 $ruleset->{$chain} = [];
1462 sub ruleset_chain_exist
{
1463 my ($ruleset, $chain) = @_;
1465 return $ruleset->{$chain} ?
1 : undef;
1468 sub ruleset_addrule
{
1469 my ($ruleset, $chain, $rule) = @_;
1471 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1473 push @{$ruleset->{$chain}}, "-A $chain $rule";
1476 sub ruleset_insertrule
{
1477 my ($ruleset, $chain, $rule) = @_;
1479 die "no such chain '$chain'\n" if !$ruleset->{$chain};
1481 unshift @{$ruleset->{$chain}}, "-A $chain $rule";
1484 sub get_log_rule_base
{
1485 my ($chain, $vmid, $msg, $loglevel) = @_;
1487 die "internal error - no log level" if !defined($loglevel);
1489 $vmid = 0 if !defined($vmid);
1491 # Note: we use special format for prefix to pass further
1492 # info to log daemon (VMID, LOGVELEL and CHAIN)
1494 return "-j NFLOG --nflog-prefix \":$vmid:$loglevel:$chain: $msg\"";
1497 sub ruleset_addlog {
1498 my ($ruleset, $chain, $vmid, $msg, $loglevel, $rule) = @_;
1500 return if !defined($loglevel);
1502 my $logrule = get_log_rule_base($chain, $vmid, $msg, $loglevel);
1504 $logrule = "$rule $logrule" if defined($rule);
1506 ruleset_addrule($ruleset, $chain, $logrule);
1509 sub ruleset_add_chain_policy {
1510 my ($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action) = @_;
1512 if ($policy eq 'ACCEPT') {
1514 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT' },
1515 { ACCEPT => $accept_action});
1517 } elsif ($policy eq 'DROP') {
1519 ruleset_addrule($ruleset, $chain, "-j PVEFW-Drop
");
1521 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1523 ruleset_addrule($ruleset, $chain, "-j DROP
");
1524 } elsif ($policy eq 'REJECT') {
1525 ruleset_addrule($ruleset, $chain, "-j PVEFW-Reject
");
1527 ruleset_addlog($ruleset, $chain, $vmid, "policy
$policy: ", $loglevel);
1529 ruleset_addrule($ruleset, $chain, "-g PVEFW-reject
");
1532 die "internal error
: unknown policy
'$policy'";
1536 sub ruleset_chain_add_conn_filters {
1537 my ($ruleset, $chain, $accept) = @_;
1539 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
-j DROP
");
1540 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate RELATED
,ESTABLISHED
-j
$accept");
1543 sub ruleset_chain_add_input_filters {
1544 my ($ruleset, $chain, $options, $cluster_conf, $loglevel) = @_;
1546 if ($cluster_conf->{ipset}->{blacklist}){
1547 ruleset_addlog($ruleset, $chain, 0, "DROP
: ", $loglevel, "-m set
--match-set PVEFW-blacklist src
");
1548 ruleset_addrule($ruleset, $chain, "-m set
--match-set PVEFW-blacklist src
-j DROP
");
1551 if (!(defined($options->{nosmurfs}) && $options->{nosmurfs} == 0)) {
1552 ruleset_addrule($ruleset, $chain, "-m conntrack
--ctstate INVALID
,NEW
-j PVEFW-smurfs
");
1555 if ($options->{tcpflags}) {
1556 ruleset_addrule($ruleset, $chain, "-p tcp
-j PVEFW-tcpflags
");
1560 sub ruleset_create_vm_chain {
1561 my ($ruleset, $chain, $options, $macaddr, $direction) = @_;
1563 ruleset_create_chain($ruleset, $chain);
1564 my $accept = generate_nfqueue($options);
1566 if (!(defined($options->{dhcp}) && $options->{dhcp} == 0)) {
1567 if ($direction eq 'OUT') {
1568 ruleset_generate_rule($ruleset, $chain, { action => 'PVEFW-SET-ACCEPT-MARK',
1569 proto => 'udp', sport => 68, dport => 67 });
1571 ruleset_generate_rule($ruleset, $chain, { action => 'ACCEPT',
1572 proto => 'udp', sport => 67, dport => 68 });
1576 if ($direction eq 'OUT') {
1577 if (defined($macaddr) && !(defined($options->{macfilter}) && $options->{macfilter} == 0)) {
1578 ruleset_addrule($ruleset, $chain, "-m mac
! --mac-source
$macaddr -j DROP
");
1580 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1584 sub ruleset_add_group_rule {
1585 my ($ruleset, $cluster_conf, $chain, $rule, $direction, $action) = @_;
1587 my $group = $rule->{action};
1588 my $group_chain = "GROUP-
$group-$direction";
1589 if(!ruleset_chain_exist($ruleset, $group_chain)){
1590 generate_group_rules($ruleset, $cluster_conf, $group);
1593 if ($direction eq 'OUT' && $rule->{iface_out}) {
1594 ruleset_addrule($ruleset, $chain, "-o
$rule->{iface_out
} -j
$group_chain");
1595 } elsif ($direction eq 'IN' && $rule->{iface_in}) {
1596 ruleset_addrule($ruleset, $chain, "-i
$rule->{iface_in
} -j
$group_chain");
1598 ruleset_addrule($ruleset, $chain, "-j
$group_chain");
1601 ruleset_addrule($ruleset, $chain, "-m mark
--mark
1 -j
$action");
1604 sub ruleset_generate_vm_rules {
1605 my ($ruleset, $rules, $cluster_conf, $chain, $netid, $direction, $options) = @_;
1607 my $lc_direction = lc($direction);
1609 my $in_accept = generate_nfqueue($options);
1611 foreach my $rule (@$rules) {
1612 next if $rule->{iface} && $rule->{iface} ne $netid;
1613 next if !$rule->{enable};
1614 if ($rule->{type} eq 'group') {
1615 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, $direction,
1616 $direction eq 'OUT' ? 'RETURN' : $in_accept);
1618 next if $rule->{type} ne $lc_direction;
1620 if ($direction eq 'OUT') {
1621 ruleset_generate_rule($ruleset, $chain, $rule,
1622 { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" },
1623 undef, $cluster_conf);
1625 ruleset_generate_rule($ruleset, $chain, $rule,
1626 { ACCEPT => $in_accept , REJECT => "PVEFW-reject
" },
1627 undef, $cluster_conf);
1635 sub generate_nfqueue {
1638 if ($options->{ips}) {
1639 my $action = "NFQUEUE
";
1640 if ($options->{ips_queues} && $options->{ips_queues} =~ m/^(\d+)(:(\d+))?$/) {
1641 if (defined($3) && defined($1)) {
1642 $action .= " --queue-balance
$1:$3";
1643 } elsif (defined($1)) {
1644 $action .= " --queue-num
$1";
1647 $action .= " --queue-bypass
" if $feature_ipset_nomatch; #need kernel 3.10
1654 sub ruleset_generate_vm_ipsrules {
1655 my ($ruleset, $options, $direction, $iface) = @_;
1657 if ($options->{ips} && $direction eq 'IN') {
1658 my $nfqueue = generate_nfqueue($options);
1660 if (!ruleset_chain_exist($ruleset, "PVEFW-IPS
")) {
1661 ruleset_create_chain($ruleset, "PVEFW-IPS
");
1664 ruleset_addrule($ruleset, "PVEFW-IPS
", "-m physdev
--physdev-out
$iface --physdev-is-bridged
-j
$nfqueue");
1668 sub generate_venet_rules_direction {
1669 my ($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, $direction) = @_;
1671 my $lc_direction = lc($direction);
1673 my $rules = $vmfw_conf->{rules};
1675 my $options = $vmfw_conf->{options};
1676 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1678 my $chain = "venet0-
$vmid-$direction";
1680 ruleset_create_vm_chain($ruleset, $chain, $options, undef, $direction);
1682 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $chain, 'venet', $direction);
1687 if ($direction eq 'OUT') {
1688 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1690 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1693 my $accept = generate_nfqueue($options);
1694 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1695 ruleset_add_chain_policy($ruleset, $chain, $vmid, $policy, $loglevel, $accept_action);
1697 if ($direction eq 'OUT') {
1698 ruleset_generate_rule_insert($ruleset, "PVEFW-VENET-OUT
", {
1701 iface_in => 'venet0'});
1703 ruleset_generate_rule($ruleset, "PVEFW-VENET-IN
", {
1706 iface_out => 'venet0'});
1710 sub generate_tap_rules_direction {
1711 my ($ruleset, $cluster_conf, $iface, $netid, $macaddr, $vmfw_conf, $vmid, $direction) = @_;
1713 my $lc_direction = lc($direction);
1715 my $rules = $vmfw_conf->{rules};
1717 my $options = $vmfw_conf->{options};
1718 my $loglevel = get_option_log_level($options, "log_level_
${lc_direction
}");
1720 my $tapchain = "$iface-$direction";
1722 ruleset_create_vm_chain($ruleset, $tapchain, $options, $macaddr, $direction);
1724 ruleset_generate_vm_rules($ruleset, $rules, $cluster_conf, $tapchain, $netid, $direction, $options);
1726 ruleset_generate_vm_ipsrules($ruleset, $options, $direction, $iface);
1731 if ($direction eq 'OUT') {
1732 $policy = $options->{policy_out} || 'ACCEPT'; # allow everything by default
1734 $policy = $options->{policy_in} || 'DROP'; # allow nothing by default
1737 my $accept = generate_nfqueue($options);
1738 my $accept_action = $direction eq 'OUT' ? "PVEFW-SET-ACCEPT-MARK
" : $accept;
1739 ruleset_add_chain_policy($ruleset, $tapchain, $vmid, $policy, $loglevel, $accept_action);
1741 # plug the tap chain to bridge chain
1742 if ($direction eq 'IN') {
1743 ruleset_addrule($ruleset, "PVEFW-FWBR-IN
",
1744 "-m physdev
--physdev-is-bridged
--physdev-out
$iface -j
$tapchain");
1746 ruleset_addrule($ruleset, "PVEFW-FWBR-OUT
",
1747 "-m physdev
--physdev-is-bridged
--physdev-in
$iface -j
$tapchain");
1751 sub enable_host_firewall {
1752 my ($ruleset, $hostfw_conf, $cluster_conf) = @_;
1754 my $options = $hostfw_conf->{options};
1755 my $cluster_options = $cluster_conf->{options};
1756 my $rules = $hostfw_conf->{rules};
1757 my $cluster_rules = $cluster_conf->{rules};
1759 # host inbound firewall
1760 my $chain = "PVEFW-HOST-IN
";
1761 ruleset_create_chain($ruleset, $chain);
1763 my $loglevel = get_option_log_level($options, "log_level_in
");
1765 ruleset_addrule($ruleset, $chain, "-i lo
-j ACCEPT
");
1767 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1768 ruleset_chain_add_input_filters($ruleset, $chain, $options, $cluster_conf, $loglevel);
1770 # we use RETURN because we need to check also tap rules
1771 my $accept_action = 'RETURN';
1773 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1775 # add host rules first, so that cluster wide rules can be overwritten
1776 foreach my $rule (@$rules, @$cluster_rules) {
1777 $rule->{iface_in} = $rule->{iface} if $rule->{iface};
1779 if ($rule->{type} eq 'group') {
1780 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'IN', $accept_action);
1781 } elsif ($rule->{type} eq 'in') {
1782 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1783 undef, $cluster_conf);
1787 delete $rule->{iface_in};
1790 # allow standard traffic for management ipset (includes cluster network)
1791 my $mngmntsrc = "-m set
--match-set PVEFW-management src
";
1792 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1793 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1794 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1795 ruleset_addrule($ruleset, $chain, "$mngmntsrc -p tcp
--dport
22 -j
$accept_action"); # SSH
1797 my $localnet = local_network();
1801 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1802 ruleset_addrule($ruleset, $chain, "-s
$localnet -d
$localnet $corosync_rule");
1803 ruleset_addrule($ruleset, $chain, "-s
$localnet -m addrtype
--dst-type MULTICAST
$corosync_rule");
1806 # implement input policy
1807 my $policy = $cluster_options->{policy_in} || 'DROP'; # allow nothing by default
1808 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1810 # host outbound firewall
1811 $chain = "PVEFW-HOST-OUT
";
1812 ruleset_create_chain($ruleset, $chain);
1814 $loglevel = get_option_log_level($options, "log_level_out
");
1816 ruleset_addrule($ruleset, $chain, "-o lo
-j ACCEPT
");
1818 ruleset_chain_add_conn_filters($ruleset, $chain, 'ACCEPT');
1820 # we use RETURN because we may want to check other thigs later
1821 $accept_action = 'RETURN';
1823 ruleset_addrule($ruleset, $chain, "-p igmp
-j
$accept_action"); # important for multicast
1825 # add host rules first, so that cluster wide rules can be overwritten
1826 foreach my $rule (@$rules, @$cluster_rules) {
1827 $rule->{iface_out} = $rule->{iface} if $rule->{iface};
1829 if ($rule->{type} eq 'group') {
1830 ruleset_add_group_rule($ruleset, $cluster_conf, $chain, $rule, 'OUT', $accept_action);
1831 } elsif ($rule->{type} eq 'out') {
1832 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => $accept_action, REJECT => "PVEFW-reject
" },
1833 undef, $cluster_conf);
1837 delete $rule->{iface_out};
1840 # allow standard traffic on cluster network
1842 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
8006 -j
$accept_action"); # PVE API
1843 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
22 -j
$accept_action"); # SSH
1844 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
5900:5999 -j
$accept_action"); # PVE VNC Console
1845 ruleset_addrule($ruleset, $chain, "-d
$localnet -p tcp
--dport
3128 -j
$accept_action"); # SPICE Proxy
1847 my $corosync_rule = "-p udp
--dport
5404:5405 -j
$accept_action";
1848 ruleset_addrule($ruleset, $chain, "-d
$localnet $corosync_rule");
1849 ruleset_addrule($ruleset, $chain, "-m addrtype
--dst-type MULTICAST
$corosync_rule");
1852 # implement output policy
1853 $policy = $cluster_options->{policy_out} || 'ACCEPT'; # allow everything by default
1854 ruleset_add_chain_policy($ruleset, $chain, 0, $policy, $loglevel, $accept_action);
1856 ruleset_addrule($ruleset, "PVEFW-OUTPUT
", "-j PVEFW-HOST-OUT
");
1857 ruleset_addrule($ruleset, "PVEFW-INPUT
", "-j PVEFW-HOST-IN
");
1860 sub generate_group_rules {
1861 my ($ruleset, $cluster_conf, $group) = @_;
1863 my $rules = $cluster_conf->{groups}->{$group};
1866 warn "no such security group
'$group'\n";
1867 $rules = []; # create empty chain
1870 my $chain = "GROUP-
${group
}-IN
";
1872 ruleset_create_chain($ruleset, $chain);
1873 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1875 foreach my $rule (@$rules) {
1876 next if $rule->{type} ne 'in';
1877 ruleset_generate_rule($ruleset, $chain, $rule, { ACCEPT => "PVEFW-SET-ACCEPT-MARK
", REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1880 $chain = "GROUP-
${group
}-OUT
";
1882 ruleset_create_chain($ruleset, $chain);
1883 ruleset_addrule($ruleset, $chain, "-j MARK
--set-mark
0"); # clear mark
1885 foreach my $rule (@$rules) {
1886 next if $rule->{type} ne 'out';
1887 # we use PVEFW-SET-ACCEPT-MARK (Instead of ACCEPT) because we need to
1888 # check also other tap rules later
1889 ruleset_generate_rule($ruleset, $chain, $rule,
1890 { ACCEPT => 'PVEFW-SET-ACCEPT-MARK', REJECT => "PVEFW-reject
" }, undef, $cluster_conf);
1895 my $valid_netdev_names = {};
1896 for (my $i = 0; $i < $MAX_NETS; $i++) {
1897 $valid_netdev_names->{"net
$i"} = 1;
1901 my ($prefix, $line, $cluster_conf, $fw_conf, $rule_env, $verbose) = @_;
1905 my $orig_line = $line;
1909 # we can add single line comments to the end of the rule
1910 if ($line =~ s/#\s*(.*?)\s*$//) {
1911 $rule->{comment} = decode('utf8', $1);
1914 # we can disable a rule when prefixed with '|'
1916 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
1918 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1919 die "unable to parse rule
: $line\n";
1921 $rule->{type} = lc($1);
1922 $rule->{action} = $2;
1924 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1925 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1926 $rule->{macro} = $1;
1927 $rule->{action} = $2;
1931 while (length($line)) {
1932 if ($line =~ s/^-i (\S+)\s*//) {
1933 $rule->{iface} = $1;
1937 last if $rule->{type} eq 'group';
1939 if ($line =~ s/^-p (\S+)\s*//) {
1940 $rule->{proto} = $1;
1944 if ($line =~ s/^-dport (\S+)\s*//) {
1945 $rule->{dport} = $1;
1949 if ($line =~ s/^-sport (\S+)\s*//) {
1950 $rule->{sport} = $1;
1953 if ($line =~ s/^-source (\S+)\s*//) {
1954 $rule->{source} = $1;
1957 if ($line =~ s/^-dest (\S+)\s*//) {
1965 die "unable to parse rule parameters
: $line\n" if length($line);
1967 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
1968 if ($verbose && $rule->{errors}) {
1969 warn "$prefix - errors
in rule parameters
: $orig_line\n";
1970 foreach my $p (keys %{$rule->{errors}}) {
1971 warn " $p: $rule->{errors
}->{$p}\n";
1978 sub parse_vmfw_option {
1983 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
1985 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
1988 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
1990 $value = $2 ? lc($3) : '';
1991 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
1994 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
1999 die "can
't parse option '$line'\n"
2002 return ($opt, $value);
2005 sub parse_hostfw_option {
2010 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2012 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2015 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2017 $value = $2 ? lc($3) : '';
2018 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2023 die "can't parse option
'$line'\n"
2026 return ($opt, $value);
2029 sub parse_clusterfw_option {
2034 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2037 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2042 die "can
't parse option '$line'\n"
2045 return ($opt, $value);
2051 # we can add single line comments to the end of the line
2052 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2054 if ($line =~ m/^(\S+)\s(\S+)$/) {
2055 my ($name, $cidr) = ($1, $2);
2057 pve_verify_ipv4_or_cidr($cidr);
2062 $data->{comment} = $comment if $comment;
2069 sub parse_vm_fw_rules {
2070 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2080 while (defined(my $line = <$fh>)) {
2081 next if $line =~ m/^#/;
2082 next if $line =~ m/^\s*$/;
2084 my $linenr = $fh->input_line_number();
2085 my $prefix = "$filename (line $linenr)";
2087 if ($line =~ m/^\[(\S+)\]\s*$/i) {
2089 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
2093 warn "$prefix: skip line - no section";
2097 next if !$res->{$section}; # skip undefined section
2099 if ($section eq 'options
') {
2101 my ($opt, $value) = parse_vmfw_option($line);
2102 $res->{options}->{$opt} = $value;
2104 warn "$prefix: $@" if $@;
2108 if ($section eq 'aliases
') {
2110 my $data = parse_alias($line);
2111 $res->{aliases}->{lc($data->{name})} = $data;
2113 warn "$prefix: $@" if $@;
2118 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2120 warn "$prefix: $err";
2124 push @{$res->{$section}}, $rule;
2130 sub parse_host_fw_rules {
2131 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2133 my $res = { rules => [], options => {}};
2137 while (defined(my $line = <$fh>)) {
2138 next if $line =~ m/^#/;
2139 next if $line =~ m/^\s*$/;
2141 my $linenr = $fh->input_line_number();
2142 my $prefix = "$filename (line $linenr)";
2144 if ($line =~ m/^\[(\S+)\]\s*$/i) {
2146 warn "$prefix: ignore unknown section '$section'\n" if !$res->{$section};
2150 warn "$prefix: skip line - no section";
2154 next if !$res->{$section}; # skip undefined section
2156 if ($section eq 'options
') {
2158 my ($opt, $value) = parse_hostfw_option($line);
2159 $res->{options}->{$opt} = $value;
2161 warn "$prefix: $@" if $@;
2166 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, 'host
', $verbose); };
2168 warn "$prefix: $err";
2172 push @{$res->{$section}}, $rule;
2178 sub parse_cluster_fw_rules {
2179 my ($filename, $fh, $verbose) = @_;
2189 group_comments => {},
2191 ipset_comments => {},
2194 while (defined(my $line = <$fh>)) {
2195 next if $line =~ m/^#/;
2196 next if $line =~ m/^\s*$/;
2198 my $linenr = $fh->input_line_number();
2199 my $prefix = "$filename (line $linenr)";
2201 if ($line =~ m/^\[options\]$/i) {
2202 $section = 'options
';
2206 if ($line =~ m/^\[aliases\]$/i) {
2207 $section = 'aliases
';
2211 if ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2212 $section = 'groups
';
2215 $res->{$section}->{$group} = [];
2216 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2221 if ($line =~ m/^\[rules\]$/i) {
2226 if ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i) {
2230 $res->{$section}->{$group} = [];
2231 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2237 warn "$prefix: skip line - no section\n";
2241 if ($section eq 'options
') {
2243 my ($opt, $value) = parse_clusterfw_option($line);
2244 $res->{options}->{$opt} = $value;
2246 warn "$prefix: $@" if $@;
2247 } elsif ($section eq 'aliases
') {
2249 my $data = parse_alias($line);
2250 $res->{aliases}->{lc($data->{name})} = $data;
2252 warn "$prefix: $@" if $@;
2253 } elsif ($section eq 'rules
') {
2255 eval { $rule = parse_fw_rule($prefix, $line, $res, undef, 'cluster
', $verbose); };
2257 warn "$prefix: $err";
2260 push @{$res->{$section}}, $rule;
2261 } elsif ($section eq 'groups
') {
2263 eval { $rule = parse_fw_rule($prefix, $line, $res, undef, 'group
', $verbose); };
2265 warn "$prefix: $err";
2268 push @{$res->{$section}->{$group}}, $rule;
2269 } elsif ($section eq 'ipset
') {
2270 # we can add single line comments to the end of the rule
2271 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2273 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2277 if($cidr !~ m/^${ip_alias_pattern}$/) {
2280 eval { pve_verify_ipv4_or_cidr($cidr); };
2282 warn "$prefix: $cidr - $err";
2287 my $entry = { cidr => $cidr };
2288 $entry->{nomatch} = 1 if $nomatch;
2289 $entry->{comment} = $comment if $comment;
2291 push @{$res->{$section}->{$group}}, $entry;
2299 my ($code, @param) = @_;
2303 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2310 sub read_local_vm_config {
2315 my $vmdata = { openvz => $openvz, qemu => $qemu };
2317 my $vmlist = PVE::Cluster::get_vmlist();
2318 return $vmdata if !$vmlist || !$vmlist->{ids};
2319 my $ids = $vmlist->{ids};
2321 foreach my $vmid (keys %$ids) {
2322 next if !$vmid; # skip VE0
2323 my $d = $ids->{$vmid};
2324 next if !$d->{node} || $d->{node} ne $nodename;
2325 next if !$d->{type};
2326 if ($d->{type} eq 'openvz
') {
2327 if ($have_pve_manager) {
2328 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2329 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2330 $openvz->{$vmid} = $conf;
2333 } elsif ($d->{type} eq 'qemu
') {
2334 if ($have_qemu_server) {
2335 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2336 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2337 $qemu->{$vmid} = $conf;
2346 sub load_vmfw_conf {
2347 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2351 $dir = "/etc/pve/firewall" if !defined($dir);
2353 my $filename = "$dir/$vmid.fw";
2354 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2355 $vmfw_conf = parse_vm_fw_rules($filename, $fh, $cluster_conf, $rule_env, $verbose);
2361 my $format_rules = sub {
2362 my ($rules, $allow_iface) = @_;
2366 foreach my $rule (@$rules) {
2367 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2368 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2369 $raw .= uc($rule->{type});
2370 if ($rule->{macro}) {
2371 $raw .= " $rule->{macro}($rule->{action})";
2373 $raw .= " " . $rule->{action};
2375 if ($allow_iface && $rule->{iface}) {
2376 $raw .= " -i $rule->{iface}";
2379 if ($rule->{type} ne 'group
') {
2380 $raw .= " -source $rule->{source}" if $rule->{source};
2381 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2382 $raw .= " -p $rule->{proto}" if $rule->{proto};
2383 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2384 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2387 $raw .= " # " . encode('utf8
', $rule->{comment})
2388 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2391 die "unknown rule type '$rule->{type
}'";
2398 my $format_options = sub {
2403 $raw .= "[OPTIONS]\n\n";
2404 foreach my $opt (keys %$options) {
2405 $raw .= "$opt: $options->{$opt}\n";
2412 my $format_aliases = sub {
2417 $raw .= "[ALIASES]\n\n";
2418 foreach my $k (keys %$aliases) {
2419 my $e = $aliases->{$k};
2420 $raw .= "$e->{name} $e->{cidr}";
2421 $raw .= " # " . encode('utf8
', $e->{comment})
2422 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2430 my $format_ipset = sub {
2436 foreach my $entry (@$options) {
2437 $nethash->{$entry->{cidr}} = $entry;
2440 foreach my $cidr (sort keys %$nethash) {
2441 my $entry = $nethash->{$cidr};
2442 my $line = $entry->{nomatch} ? '!' : '';
2443 $line .= $entry->{cidr};
2444 $line .= " # " . encode('utf8
', $entry->{comment})
2445 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2452 sub save_vmfw_conf {
2453 my ($vmid, $vmfw_conf) = @_;
2457 my $options = $vmfw_conf->{options};
2458 $raw .= &$format_options($options) if scalar(keys %$options);
2460 my $aliases = $vmfw_conf->{aliases};
2461 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2463 my $rules = $vmfw_conf->{rules} || [];
2464 if (scalar(@$rules)) {
2465 $raw .= "[RULES]\n\n";
2466 $raw .= &$format_rules($rules, 1);
2470 my $filename = "/etc/pve/firewall/$vmid.fw";
2471 PVE::Tools::file_set_contents($filename, $raw);
2474 sub read_vm_firewall_configs {
2475 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2477 my $vmfw_configs = {};
2479 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2480 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2481 next if !$vmfw_conf->{options}; # skip if file does not exists
2482 $vmfw_configs->{$vmid} = $vmfw_conf;
2484 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2485 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2486 next if !$vmfw_conf->{options}; # skip if file does not exists
2487 $vmfw_configs->{$vmid} = $vmfw_conf;
2490 return $vmfw_configs;
2493 sub get_option_log_level {
2494 my ($options, $k) = @_;
2496 my $v = $options->{$k};
2497 $v = $default_log_level if !defined($v);
2499 return undef if $v eq '' || $v eq 'nolog
';
2501 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2503 return $v if ($v >= 0) && ($v <= 7);
2505 warn "unknown log level ($k = '$v')\n";
2510 sub generate_std_chains {
2511 my ($ruleset, $options) = @_;
2513 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2515 # same as shorewall smurflog.
2516 my $chain = 'PVEFW-smurflog
';
2517 $pve_std_chains->{$chain} = [];
2519 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2520 push @{$pve_std_chains->{$chain}}, "-j DROP";
2522 # same as shorewall logflags action.
2523 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2524 $chain = 'PVEFW-logflags
';
2525 $pve_std_chains->{$chain} = [];
2527 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2528 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2529 push @{$pve_std_chains->{$chain}}, "-j DROP";
2531 foreach my $chain (keys %$pve_std_chains) {
2532 ruleset_create_chain($ruleset, $chain);
2533 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2535 ruleset_generate_rule($ruleset, $chain, $rule);
2537 ruleset_addrule($ruleset, $chain, $rule);
2543 sub generate_ipset_chains {
2544 my ($ipset_ruleset, $fw_conf) = @_;
2546 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2547 generate_ipset($ipset_ruleset, "PVEFW-$ipset", $fw_conf->{ipset}->{$ipset}, $fw_conf->{aliases});
2551 sub generate_ipset {
2552 my ($ipset_ruleset, $name, $options, $aliases) = @_;
2554 my $hashsize = scalar(@$options);
2555 if ($hashsize <= 64) {
2558 $hashsize = round_powerof2($hashsize);
2561 push @{$ipset_ruleset->{$name}}, "create $name hash:net family inet hashsize $hashsize maxelem $hashsize";
2565 foreach my $entry (@$options) {
2566 my $cidr = $entry->{cidr};
2567 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2568 my $alias = lc($cidr);
2569 if ($aliases->{$alias}) {
2570 $entry->{cidr} = $aliases->{$alias}->{cidr};
2571 $nethash->{$entry->{cidr}} = $entry;
2573 warn "no such alias '$cidr'\n" if !$aliases->{$alias};
2576 $nethash->{$entry->{cidr}} = $entry;
2580 foreach my $cidr (sort keys %$nethash) {
2581 my $entry = $nethash->{$cidr};
2583 my $cmd = "add $name $cidr";
2584 if ($entry->{nomatch}) {
2585 if ($feature_ipset_nomatch) {
2586 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2588 warn "ignore !$cidr - nomatch not supported by kernel\n";
2591 push @{$ipset_ruleset->{$name}}, $cmd;
2596 sub round_powerof2 {
2600 $int |= $int >> $_ foreach (1,2,4,8,16);
2604 sub load_clusterfw_conf {
2605 my ($filename, $verbose) = @_;
2607 $filename = $clusterfw_conf_filename if !defined($filename);
2609 my $cluster_conf = {};
2610 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2611 $cluster_conf = parse_cluster_fw_rules($filename, $fh, $verbose);
2614 return $cluster_conf;
2617 sub save_clusterfw_conf {
2618 my ($cluster_conf) = @_;
2622 my $options = $cluster_conf->{options};
2623 $raw .= &$format_options($options) if scalar(keys %$options);
2625 my $aliases = $cluster_conf->{aliases};
2626 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2628 foreach my $ipset (sort keys %{$cluster_conf->{ipset}}) {
2629 if (my $comment = $cluster_conf->{ipset_comments}->{$ipset}) {
2630 my $utf8comment = encode('utf8
', $comment);
2631 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2633 $raw .= "[IPSET $ipset]\n\n";
2635 my $options = $cluster_conf->{ipset}->{$ipset};
2636 $raw .= &$format_ipset($options);
2640 my $rules = $cluster_conf->{rules};
2641 if (scalar(@$rules)) {
2642 $raw .= "[RULES]\n\n";
2643 $raw .= &$format_rules($rules, 1);
2647 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2648 my $rules = $cluster_conf->{groups}->{$group};
2649 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2650 my $utf8comment = encode('utf8
', $comment);
2651 $raw .= "[group $group] # $utf8comment\n\n";
2653 $raw .= "[group $group]\n\n";
2656 $raw .= &$format_rules($rules, 0);
2660 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2663 sub load_hostfw_conf {
2664 my ($cluster_conf, $filename, $verbose) = @_;
2666 $filename = $hostfw_conf_filename if !defined($filename);
2668 my $hostfw_conf = {};
2669 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2670 $hostfw_conf = parse_host_fw_rules($filename, $fh, $cluster_conf, $verbose);
2672 return $hostfw_conf;
2675 sub save_hostfw_conf {
2676 my ($hostfw_conf) = @_;
2680 my $options = $hostfw_conf->{options};
2681 $raw .= &$format_options($options) if scalar(keys %$options);
2683 my $rules = $hostfw_conf->{rules};
2684 if (scalar(@$rules)) {
2685 $raw .= "[RULES]\n\n";
2686 $raw .= &$format_rules($rules, 1);
2690 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2694 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2698 if ($vmdata) { # test mode
2699 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2700 my $filename = "$testdir/cluster.fw";
2701 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2703 $filename = "$testdir/host.fw";
2704 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2706 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2707 } else { # normal operation
2708 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2710 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2712 $vmdata = read_local_vm_config();
2713 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2716 $cluster_conf->{ipset}->{venet0} = [];
2719 if ($cluster_conf->{aliases}->{local_network}) {
2720 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2722 $localnet = local_network() || '127.0.0.0/8';
2723 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2726 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2730 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2731 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2733 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2735 my $hostfw_options = $hostfw_conf->{options} || {};
2737 # fixme: what log level should we use here?
2738 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2740 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2742 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2743 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
2744 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set PVEFW-venet0 src -j PVEFW-VENET-OUT");
2746 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2747 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2749 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2751 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2752 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2754 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2755 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2757 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
2759 generate_std_chains($ruleset, $hostfw_options);
2761 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2763 if ($hostfw_enable) {
2764 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2765 warn $@ if $@; # just to be sure - should not happen
2768 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set PVEFW-venet0 dst -j PVEFW-VENET-IN");
2770 # generate firewall rules for QEMU VMs
2771 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2773 my $conf = $vmdata->{qemu}->{$vmid};
2774 my $vmfw_conf = $vmfw_configs->{$vmid};
2775 return if !$vmfw_conf;
2776 return if !$vmfw_conf->{options}->{enable};
2778 foreach my $netid (keys %$conf) {
2779 next if $netid !~ m/^net(\d+)$/;
2780 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2781 next if !$net->{firewall};
2782 my $iface = "tap${vmid}i$1";
2784 my $macaddr = $net->{macaddr};
2785 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2786 $vmfw_conf, $vmid, 'IN
');
2787 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2788 $vmfw_conf, $vmid, 'OUT
');
2791 warn $@ if $@; # just to be sure - should not happen
2794 # generate firewall rules for OpenVZ containers
2795 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2797 my $conf = $vmdata->{openvz}->{$vmid};
2799 my $vmfw_conf = $vmfw_configs->{$vmid};
2800 return if !$vmfw_conf;
2801 return if !$vmfw_conf->{options}->{enable};
2803 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2804 my $ip = $conf->{ip_address}->{value};
2806 parse_address_list($ip); # make sure we have a valid $ip list
2808 my @ips = split(',', $ip);
2810 foreach my $singleip (@ips) {
2811 my $venet0ipset = {};
2812 $venet0ipset->{cidr} = $singleip;
2813 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2816 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2817 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2820 if ($conf->{netif} && $conf->{netif}->{value}) {
2821 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2822 foreach my $netid (keys %$netif) {
2823 my $d = $netif->{$netid};
2825 my $macaddr = $d->{mac};
2826 my $iface = $d->{host_ifname};
2827 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2828 $vmfw_conf, $vmid, 'IN
');
2829 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2830 $vmfw_conf, $vmid, 'OUT
');
2834 warn $@ if $@; # just to be sure - should not happen
2837 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2838 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2841 my $ipset_ruleset = {};
2842 generate_ipset_chains($ipset_ruleset, $cluster_conf);
2844 return ($ruleset, $ipset_ruleset);
2847 sub get_ruleset_status {
2848 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2850 my $statushash = {};
2852 foreach my $chain (sort keys %$ruleset) {
2853 my $sig = &$digest_fn($ruleset->{$chain});
2855 $statushash->{$chain}->{sig} = $sig;
2857 my $oldsig = $active_chains->{$chain};
2858 if (!defined($oldsig)) {
2859 $statushash->{$chain}->{action} = 'create
';
2861 if ($oldsig eq $sig) {
2862 $statushash->{$chain}->{action} = 'exists';
2864 $statushash->{$chain}->{action} = 'update
';
2867 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2868 foreach my $cmd (@{$ruleset->{$chain}}) {
2869 print "\t$cmd\n" if $verbose;
2873 foreach my $chain (sort keys %$active_chains) {
2874 if (!defined($ruleset->{$chain})) {
2875 my $sig = $active_chains->{$chain};
2876 $statushash->{$chain}->{action} = 'delete';
2877 $statushash->{$chain}->{sig} = $sig;
2878 print "delete $chain ($sig)\n" if $verbose;
2885 sub print_sig_rule {
2886 my ($chain, $sig) = @_;
2888 # We just use this to store a SHA1 checksum used to detect changes
2889 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2892 sub get_ruleset_cmdlist {
2893 my ($ruleset, $verbose) = @_;
2895 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2897 my ($active_chains, $hooks) = iptables_get_chains();
2898 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2900 # create missing chains first
2901 foreach my $chain (sort keys %$ruleset) {
2902 my $stat = $statushash->{$chain};
2903 die "internal error" if !$stat;
2904 next if $stat->{action} ne 'create
';
2906 $cmdlist .= ":$chain - [0:0]\n";
2909 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2910 if (!$hooks->{$h}) {
2911 $cmdlist .= "-A $h -j PVEFW-$h\n";
2915 foreach my $chain (sort keys %$ruleset) {
2916 my $stat = $statushash->{$chain};
2917 die "internal error" if !$stat;
2919 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2920 $cmdlist .= "-F $chain\n";
2921 foreach my $cmd (@{$ruleset->{$chain}}) {
2922 $cmdlist .= "$cmd\n";
2924 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2925 } elsif ($stat->{action
} eq 'delete') {
2926 die "internal error"; # this should not happen
2927 } elsif ($stat->{action
} eq 'exists') {
2930 die "internal error - unknown status '$stat->{action}'";
2934 foreach my $chain (keys %$statushash) {
2935 next if $statushash->{$chain}->{action
} ne 'delete';
2936 $cmdlist .= "-F $chain\n";
2938 foreach my $chain (keys %$statushash) {
2939 next if $statushash->{$chain}->{action
} ne 'delete';
2940 next if $chain eq 'PVEFW-INPUT';
2941 next if $chain eq 'PVEFW-OUTPUT';
2942 next if $chain eq 'PVEFW-FORWARD';
2943 $cmdlist .= "-X $chain\n";
2946 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
2948 $cmdlist .= "COMMIT\n";
2950 return wantarray ?
($cmdlist, $changes) : $cmdlist;
2953 sub get_ipset_cmdlist
{
2954 my ($ruleset, $verbose) = @_;
2958 my $delete_cmdlist = "";
2960 my $active_chains = ipset_get_chains
();
2961 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
2963 # remove stale _swap chains
2964 foreach my $chain (keys %$active_chains) {
2965 if ($chain =~ m/^PVEFW-\S+_swap$/) {
2966 $cmdlist .= "destroy $chain\n";
2970 foreach my $chain (sort keys %$ruleset) {
2971 my $stat = $statushash->{$chain};
2972 die "internal error" if !$stat;
2974 if ($stat->{action
} eq 'create') {
2975 foreach my $cmd (@{$ruleset->{$chain}}) {
2976 $cmdlist .= "$cmd\n";
2980 if ($stat->{action
} eq 'update') {
2981 my $chain_swap = $chain."_swap";
2983 foreach my $cmd (@{$ruleset->{$chain}}) {
2984 $cmd =~ s/$chain/$chain_swap/;
2985 $cmdlist .= "$cmd\n";
2987 $cmdlist .= "swap $chain_swap $chain\n";
2988 $cmdlist .= "flush $chain_swap\n";
2989 $cmdlist .= "destroy $chain_swap\n";
2994 foreach my $chain (keys %$statushash) {
2995 next if $statushash->{$chain}->{action
} ne 'delete';
2997 $delete_cmdlist .= "flush $chain\n";
2998 $delete_cmdlist .= "destroy $chain\n";
3001 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3003 return ($cmdlist, $delete_cmdlist, $changes);
3007 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3009 enable_bridge_firewall
();
3011 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3012 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3014 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3017 if ($ipset_changes) {
3018 print "ipset changes:\n";
3019 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3020 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3024 print "iptables changes:\n";
3029 ipset_restore_cmdlist
($ipset_create_cmdlist);
3031 iptables_restore_cmdlist
($cmdlist);
3033 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3035 # test: re-read status and check if everything is up to date
3036 my $active_chains = iptables_get_chains
();
3037 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3040 foreach my $chain (sort keys %$ruleset) {
3041 my $stat = $statushash->{$chain};
3042 if ($stat->{action
} ne 'exists') {
3043 warn "unable to update chain '$chain'\n";
3048 die "unable to apply firewall changes\n" if $errors;
3050 update_nf_conntrack_max
($hostfw_conf);
3052 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3056 sub update_nf_conntrack_max
{
3057 my ($hostfw_conf) = @_;
3059 my $max = 65536; # reasonable default
3061 my $options = $hostfw_conf->{options
} || {};
3063 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3064 $max = $options->{nf_conntrack_max
};
3065 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3068 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3069 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3071 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3073 if ($current != $max) {
3074 my $hashsize = int($max/4);
3075 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3076 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3080 sub update_nf_conntrack_tcp_timeout_established
{
3081 my ($hostfw_conf) = @_;
3083 my $options = $hostfw_conf->{options
} || {};
3085 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3087 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3090 sub remove_pvefw_chains
{
3092 my ($chash, $hooks) = iptables_get_chains
();
3093 my $cmdlist = "*filter\n";
3095 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3097 $cmdlist .= "-D $h -j PVEFW-$h\n";
3101 foreach my $chain (keys %$chash) {
3102 $cmdlist .= "-F $chain\n";
3105 foreach my $chain (keys %$chash) {
3106 $cmdlist .= "-X $chain\n";
3108 $cmdlist .= "COMMIT\n";
3110 iptables_restore_cmdlist
($cmdlist);
3114 my $cluster_conf = load_clusterfw_conf
();
3115 my $cluster_options = $cluster_conf->{options
};
3116 my $enable = $cluster_options->{enable
};
3120 # load required modules here
3126 my $cluster_conf = load_clusterfw_conf
();
3127 my $cluster_options = $cluster_conf->{options
};
3129 my $enable = $cluster_options->{enable
};
3131 die "Firewall is disabled - cannot start\n" if !$enable;
3134 PVE
::Firewall
::remove_pvefw_chains
();
3138 my $hostfw_conf = load_hostfw_conf
();
3140 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3142 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset);