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) = @_;
1974 my $orig_line = $line;
1978 # we can add single line comments to the end of the rule
1979 if ($line =~ s/#\s*(.*?)\s*$//) {
1980 $rule->{comment} = decode('utf8', $1);
1983 # we can disable a rule when prefixed with '|'
1985 $rule->{enable} = $line =~ s/^\|// ? 0 : 1;
1987 $line =~ s/^(\S+)\s+(\S+)\s*// ||
1988 die "unable to parse rule
: $line\n";
1990 $rule->{type} = lc($1);
1991 $rule->{action} = $2;
1993 if ($rule->{type} eq 'in' || $rule->{type} eq 'out') {
1994 if ($rule->{action} =~ m/^(\S+)\((ACCEPT|DROP|REJECT)\)$/) {
1995 $rule->{macro} = $1;
1996 $rule->{action} = $2;
2000 while (length($line)) {
2001 if ($line =~ s/^-i (\S+)\s*//) {
2002 $rule->{iface} = $1;
2006 last if $rule->{type} eq 'group';
2008 if ($line =~ s/^-p (\S+)\s*//) {
2009 $rule->{proto} = $1;
2013 if ($line =~ s/^-dport (\S+)\s*//) {
2014 $rule->{dport} = $1;
2018 if ($line =~ s/^-sport (\S+)\s*//) {
2019 $rule->{sport} = $1;
2022 if ($line =~ s/^-source (\S+)\s*//) {
2023 $rule->{source} = $1;
2026 if ($line =~ s/^-dest (\S+)\s*//) {
2034 die "unable to parse rule parameters
: $line\n" if length($line);
2036 $rule = verify_rule($rule, $cluster_conf, $fw_conf, $rule_env, 1);
2037 if ($verbose && $rule->{errors}) {
2038 warn "$prefix - errors
in rule parameters
: $orig_line\n";
2039 foreach my $p (keys %{$rule->{errors}}) {
2040 warn " $p: $rule->{errors
}->{$p}\n";
2047 sub parse_vmfw_option {
2052 my $loglevels = "emerg
|alert
|crit
|err
|warning
|notice
|info
|debug
|nolog
";
2054 if ($line =~ m/^(enable|dhcp|macfilter|ips):\s*(0|1)\s*$/i) {
2057 } elsif ($line =~ m/^(log_level_in|log_level_out):\s*(($loglevels)\s*)?$/i) {
2059 $value = $2 ? lc($3) : '';
2060 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2063 } elsif ($line =~ m/^(ips_queues):\s*((\d+)(:(\d+))?)\s*$/i) {
2067 die "can
't parse option '$line'\n"
2070 return ($opt, $value);
2073 sub parse_hostfw_option {
2078 my $loglevels = "emerg|alert|crit|err|warning|notice|info|debug|nolog";
2080 if ($line =~ m/^(enable|nosmurfs|tcpflags):\s*(0|1)\s*$/i) {
2083 } elsif ($line =~ m/^(log_level_in|log_level_out|tcp_flags_log_level|smurf_log_level):\s*(($loglevels)\s*)?$/i) {
2085 $value = $2 ? lc($3) : '';
2086 } elsif ($line =~ m/^(nf_conntrack_max|nf_conntrack_tcp_timeout_established):\s*(\d+)\s*$/i) {
2090 die "can't parse option
'$line'\n"
2093 return ($opt, $value);
2096 sub parse_clusterfw_option {
2101 if ($line =~ m/^(enable):\s*(0|1)\s*$/i) {
2104 } elsif ($line =~ m/^(policy_(in|out)):\s*(ACCEPT|DROP|REJECT)\s*$/i) {
2108 die "can
't parse option '$line'\n"
2111 return ($opt, $value);
2115 my ($clusterfw_conf, $fw_conf, $cidr) = @_;
2117 if ($cidr !~ m/^\d/) {
2118 my $alias = lc($cidr);
2119 my $e = $fw_conf->{aliases}->{$alias} if $fw_conf;
2120 $e = $clusterfw_conf->{aliases}->{$alias} if !$e && $clusterfw_conf;
2121 return $e->{cidr} if $e;
2123 die "no such alias '$cidr'\n";
2132 # we can add single line comments to the end of the line
2133 my $comment = decode('utf8
', $1) if $line =~ s/\s*#\s*(.*?)\s*$//;
2135 if ($line =~ m/^(\S+)\s(\S+)$/) {
2136 my ($name, $cidr) = ($1, $2);
2138 pve_verify_ipv4_or_cidr($cidr);
2143 $data->{comment} = $comment if $comment;
2150 sub generic_fw_config_parser {
2151 my ($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env) = @_;
2156 my $res = $empty_conf;
2158 while (defined(my $line = <$fh>)) {
2159 next if $line =~ m/^#/;
2160 next if $line =~ m/^\s*$/;
2164 my $linenr = $fh->input_line_number();
2165 my $prefix = "$filename (line $linenr)";
2167 if ($empty_conf->{options} && ($line =~ m/^\[options\]$/i)) {
2168 $section = 'options
';
2172 if ($empty_conf->{aliases} && ($line =~ m/^\[aliases\]$/i)) {
2173 $section = 'aliases
';
2177 if ($empty_conf->{groups} && ($line =~ m/^\[group\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2178 $section = 'groups
';
2182 die "security group name too long\n" if length($group) > $max_group_name_length;
2183 die "invalid security group name '$group'\n" if $group !~ m/^${security_group_name_pattern}$/;
2186 ($section, $group, $comment) = undef;
2187 warn "$prefix: $err";
2191 $res->{$section}->{$group} = [];
2192 $res->{group_comments}->{$group} = decode('utf8
', $comment)
2197 if ($empty_conf->{rules} && ($line =~ m/^\[rules\]$/i)) {
2202 if ($empty_conf->{ipset} && ($line =~ m/^\[ipset\s+(\S+)\]\s*(?:#\s*(.*?)\s*)?$/i)) {
2207 die "ipset name too long\n" if length($group) > $max_ipset_name_length;
2208 die "invalid ipset name '$group'\n" if $group !~ m/^${ipset_name_pattern}$/;
2211 ($section, $group, $comment) = undef;
2212 warn "$prefix: $err";
2216 $res->{$section}->{$group} = [];
2217 $res->{ipset_comments}->{$group} = decode('utf8
', $comment)
2223 warn "$prefix: skip line - no section\n";
2227 if ($section eq 'options
') {
2230 if ($rule_env eq 'cluster
') {
2231 ($opt, $value) = parse_clusterfw_option($line);
2232 } elsif ($rule_env eq 'host
') {
2233 ($opt, $value) = parse_hostfw_option($line);
2235 ($opt, $value) = parse_vmfw_option($line);
2237 $res->{options}->{$opt} = $value;
2239 warn "$prefix: $@" if $@;
2240 } elsif ($section eq 'aliases
') {
2242 my $data = parse_alias($line);
2243 $res->{aliases}->{lc($data->{name})} = $data;
2245 warn "$prefix: $@" if $@;
2246 } elsif ($section eq 'rules
') {
2248 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, $res, $rule_env, $verbose); };
2250 warn "$prefix: $err";
2253 push @{$res->{$section}}, $rule;
2254 } elsif ($section eq 'groups
') {
2256 eval { $rule = parse_fw_rule($prefix, $line, $cluster_conf, undef, 'group
', $verbose); };
2258 warn "$prefix: $err";
2261 push @{$res->{$section}->{$group}}, $rule;
2262 } elsif ($section eq 'ipset
') {
2263 # we can add single line comments to the end of the rule
2264 my $comment = decode('utf8
', $1) if $line =~ s/#\s*(.*?)\s*$//;
2266 $line =~ m/^(\!)?\s*(\S+)\s*$/;
2271 if ($nomatch && !$feature_ipset_nomatch) {
2272 $errors->{nomatch} = "nomatch not supported by kernel";
2276 if ($cidr =~ m/^${ip_alias_pattern}$/) {
2277 resolve_alias($cluster_conf, $res, $cidr); # make sure alias exists
2280 pve_verify_ipv4_or_cidr_or_alias($cidr);
2285 $errors->{cidr} = $err;
2288 my $entry = { cidr => $cidr };
2289 $entry->{nomatch} = 1 if $nomatch;
2290 $entry->{comment} = $comment if $comment;
2291 $entry->{errors} = $errors if $errors;
2293 if ($verbose && $errors) {
2294 warn "$prefix - errors in ipset '$group': $line\n";
2295 foreach my $p (keys %{$errors}) {
2296 warn " $p: $errors->{$p}\n";
2300 push @{$res->{$section}->{$group}}, $entry;
2302 warn "$prefix: skip line - unknown section\n";
2310 sub parse_hostfw_config {
2311 my ($filename, $fh, $cluster_conf, $verbose) = @_;
2313 my $empty_conf = { rules => [], options => {}};
2315 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, 'host
');
2318 sub parse_vmfw_config {
2319 my ($filename, $fh, $cluster_conf, $rule_env, $verbose) = @_;
2326 ipset_comments => {},
2329 return generic_fw_config_parser($filename, $fh, $verbose, $cluster_conf, $empty_conf, $rule_env);
2332 sub parse_clusterfw_config {
2333 my ($filename, $fh, $verbose) = @_;
2343 group_comments => {},
2345 ipset_comments => {},
2348 return generic_fw_config_parser($filename, $fh, $verbose, $empty_conf, $empty_conf, 'cluster
');
2352 my ($code, @param) = @_;
2356 my $res = lock_file($pve_fw_lock_filename, $timeout, $code, @param);
2363 sub read_local_vm_config {
2368 my $vmdata = { openvz => $openvz, qemu => $qemu };
2370 my $vmlist = PVE::Cluster::get_vmlist();
2371 return $vmdata if !$vmlist || !$vmlist->{ids};
2372 my $ids = $vmlist->{ids};
2374 foreach my $vmid (keys %$ids) {
2375 next if !$vmid; # skip VE0
2376 my $d = $ids->{$vmid};
2377 next if !$d->{node} || $d->{node} ne $nodename;
2378 next if !$d->{type};
2379 if ($d->{type} eq 'openvz
') {
2380 if ($have_pve_manager) {
2381 my $cfspath = PVE::OpenVZ::cfs_config_path($vmid);
2382 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2383 $openvz->{$vmid} = $conf;
2386 } elsif ($d->{type} eq 'qemu
') {
2387 if ($have_qemu_server) {
2388 my $cfspath = PVE::QemuServer::cfs_config_path($vmid);
2389 if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
2390 $qemu->{$vmid} = $conf;
2399 sub load_vmfw_conf {
2400 my ($cluster_conf, $rule_env, $vmid, $dir, $verbose) = @_;
2404 $dir = "/etc/pve/firewall" if !defined($dir);
2406 my $filename = "$dir/$vmid.fw";
2407 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2408 $vmfw_conf = parse_vmfw_config($filename, $fh, $cluster_conf, $rule_env, $verbose);
2409 $vmfw_conf->{vmid} = $vmid;
2415 my $format_rules = sub {
2416 my ($rules, $allow_iface) = @_;
2420 foreach my $rule (@$rules) {
2421 if ($rule->{type} eq 'in' || $rule->{type} eq 'out
' || $rule->{type} eq 'group
') {
2422 $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
2423 $raw .= uc($rule->{type});
2424 if ($rule->{macro}) {
2425 $raw .= " $rule->{macro}($rule->{action})";
2427 $raw .= " " . $rule->{action};
2429 if ($allow_iface && $rule->{iface}) {
2430 $raw .= " -i $rule->{iface}";
2433 if ($rule->{type} ne 'group
') {
2434 $raw .= " -source $rule->{source}" if $rule->{source};
2435 $raw .= " -dest $rule->{dest}" if $rule->{dest};
2436 $raw .= " -p $rule->{proto}" if $rule->{proto};
2437 $raw .= " -dport $rule->{dport}" if $rule->{dport};
2438 $raw .= " -sport $rule->{sport}" if $rule->{sport};
2441 $raw .= " # " . encode('utf8
', $rule->{comment})
2442 if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
2445 die "unknown rule type '$rule->{type
}'";
2452 my $format_options = sub {
2457 $raw .= "[OPTIONS]\n\n";
2458 foreach my $opt (keys %$options) {
2459 $raw .= "$opt: $options->{$opt}\n";
2466 my $format_aliases = sub {
2471 $raw .= "[ALIASES]\n\n";
2472 foreach my $k (keys %$aliases) {
2473 my $e = $aliases->{$k};
2474 $raw .= "$e->{name} $e->{cidr}";
2475 $raw .= " # " . encode('utf8
', $e->{comment})
2476 if $e->{comment} && $e->{comment} !~ m/^\s*$/;
2484 my $format_ipsets = sub {
2489 foreach my $ipset (sort keys %{$fw_conf->{ipset}}) {
2490 if (my $comment = $fw_conf->{ipset_comments}->{$ipset}) {
2491 my $utf8comment = encode('utf8
', $comment);
2492 $raw .= "[IPSET $ipset] # $utf8comment\n\n";
2494 $raw .= "[IPSET $ipset]\n\n";
2496 my $options = $fw_conf->{ipset}->{$ipset};
2499 foreach my $entry (@$options) {
2500 $nethash->{$entry->{cidr}} = $entry;
2503 foreach my $cidr (sort keys %$nethash) {
2504 my $entry = $nethash->{$cidr};
2505 my $line = $entry->{nomatch} ? '!' : '';
2506 $line .= $entry->{cidr};
2507 $line .= " # " . encode('utf8
', $entry->{comment})
2508 if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
2518 sub save_vmfw_conf {
2519 my ($vmid, $vmfw_conf) = @_;
2523 my $options = $vmfw_conf->{options};
2524 $raw .= &$format_options($options) if scalar(keys %$options);
2526 my $aliases = $vmfw_conf->{aliases};
2527 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2529 $raw .= &$format_ipsets($vmfw_conf);
2531 my $rules = $vmfw_conf->{rules} || [];
2532 if (scalar(@$rules)) {
2533 $raw .= "[RULES]\n\n";
2534 $raw .= &$format_rules($rules, 1);
2538 my $filename = "/etc/pve/firewall/$vmid.fw";
2539 PVE::Tools::file_set_contents($filename, $raw);
2542 sub read_vm_firewall_configs {
2543 my ($cluster_conf, $vmdata, $dir, $verbose) = @_;
2545 my $vmfw_configs = {};
2547 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2548 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'vm
', $vmid, $dir, $verbose);
2549 next if !$vmfw_conf->{options}; # skip if file does not exists
2550 $vmfw_configs->{$vmid} = $vmfw_conf;
2552 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2553 my $vmfw_conf = load_vmfw_conf($cluster_conf, 'ct
', $vmid, $dir, $verbose);
2554 next if !$vmfw_conf->{options}; # skip if file does not exists
2555 $vmfw_configs->{$vmid} = $vmfw_conf;
2558 return $vmfw_configs;
2561 sub get_option_log_level {
2562 my ($options, $k) = @_;
2564 my $v = $options->{$k};
2565 $v = $default_log_level if !defined($v);
2567 return undef if $v eq '' || $v eq 'nolog
';
2569 $v = $log_level_hash->{$v} if defined($log_level_hash->{$v});
2571 return $v if ($v >= 0) && ($v <= 7);
2573 warn "unknown log level ($k = '$v')\n";
2578 sub generate_std_chains {
2579 my ($ruleset, $options) = @_;
2581 my $loglevel = get_option_log_level($options, 'smurf_log_level
');
2583 # same as shorewall smurflog.
2584 my $chain = 'PVEFW-smurflog
';
2585 $pve_std_chains->{$chain} = [];
2587 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2588 push @{$pve_std_chains->{$chain}}, "-j DROP";
2590 # same as shorewall logflags action.
2591 $loglevel = get_option_log_level($options, 'tcp_flags_log_level
');
2592 $chain = 'PVEFW-logflags
';
2593 $pve_std_chains->{$chain} = [];
2595 # fixme: is this correctly logged by pvewf-logger? (ther is no --log-ip-options for NFLOG)
2596 push @{$pve_std_chains->{$chain}}, get_log_rule_base($chain, 0, "DROP: ", $loglevel) if $loglevel;
2597 push @{$pve_std_chains->{$chain}}, "-j DROP";
2599 foreach my $chain (keys %$pve_std_chains) {
2600 ruleset_create_chain($ruleset, $chain);
2601 foreach my $rule (@{$pve_std_chains->{$chain}}) {
2603 ruleset_generate_rule($ruleset, $chain, $rule);
2605 ruleset_addrule($ruleset, $chain, $rule);
2611 sub generate_ipset_chains {
2612 my ($ipset_ruleset, $clusterfw_conf, $fw_conf) = @_;
2614 foreach my $ipset (keys %{$fw_conf->{ipset}}) {
2615 my $ipset_chain = compute_ipset_chain_name($fw_conf->{vmid}, $ipset);
2616 generate_ipset($ipset_ruleset, $ipset_chain, $fw_conf->{ipset}->{$ipset}, $clusterfw_conf, $fw_conf);
2620 sub generate_ipset {
2621 my ($ipset_ruleset, $name, $options, $clusterfw_conf, $fw_conf) = @_;
2623 die "duplicate ipset chain '$name'\n" if defined($ipset_ruleset->{$name});
2625 my $hashsize = scalar(@$options);
2626 if ($hashsize <= 64) {
2629 $hashsize = round_powerof2($hashsize);
2632 $ipset_ruleset->{$name} = ["create $name hash:net family inet hashsize $hashsize maxelem $hashsize"];
2636 foreach my $entry (@$options) {
2637 next if $entry->{errors}; # skip entries with errors
2639 my $cidr = resolve_alias($clusterfw_conf, $fw_conf, $entry->{cidr});
2640 $nethash->{$cidr} = { cidr => $cidr, nomatch => $entry->{nomatch} };
2645 foreach my $cidr (sort keys %$nethash) {
2646 my $entry = $nethash->{$cidr};
2648 my $cmd = "add $name $cidr";
2649 if ($entry->{nomatch}) {
2650 if ($feature_ipset_nomatch) {
2651 push @{$ipset_ruleset->{$name}}, "$cmd nomatch";
2653 warn "ignore !$cidr - nomatch not supported by kernel\n";
2656 push @{$ipset_ruleset->{$name}}, $cmd;
2661 sub round_powerof2 {
2665 $int |= $int >> $_ foreach (1,2,4,8,16);
2669 sub load_clusterfw_conf {
2670 my ($filename, $verbose) = @_;
2672 $filename = $clusterfw_conf_filename if !defined($filename);
2674 my $cluster_conf = {};
2675 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2676 $cluster_conf = parse_clusterfw_config($filename, $fh, $verbose);
2679 return $cluster_conf;
2682 sub save_clusterfw_conf {
2683 my ($cluster_conf) = @_;
2687 my $options = $cluster_conf->{options};
2688 $raw .= &$format_options($options) if scalar(keys %$options);
2690 my $aliases = $cluster_conf->{aliases};
2691 $raw .= &$format_aliases($aliases) if scalar(keys %$aliases);
2693 $raw .= &$format_ipsets($cluster_conf);
2695 my $rules = $cluster_conf->{rules};
2696 if (scalar(@$rules)) {
2697 $raw .= "[RULES]\n\n";
2698 $raw .= &$format_rules($rules, 1);
2702 foreach my $group (sort keys %{$cluster_conf->{groups}}) {
2703 my $rules = $cluster_conf->{groups}->{$group};
2704 if (my $comment = $cluster_conf->{group_comments}->{$group}) {
2705 my $utf8comment = encode('utf8
', $comment);
2706 $raw .= "[group $group] # $utf8comment\n\n";
2708 $raw .= "[group $group]\n\n";
2711 $raw .= &$format_rules($rules, 0);
2715 PVE::Tools::file_set_contents($clusterfw_conf_filename, $raw);
2718 sub load_hostfw_conf {
2719 my ($cluster_conf, $filename, $verbose) = @_;
2721 $filename = $hostfw_conf_filename if !defined($filename);
2723 my $hostfw_conf = {};
2724 if (my $fh = IO::File->new($filename, O_RDONLY)) {
2725 $hostfw_conf = parse_hostfw_config($filename, $fh, $cluster_conf, $verbose);
2727 return $hostfw_conf;
2730 sub save_hostfw_conf {
2731 my ($hostfw_conf) = @_;
2735 my $options = $hostfw_conf->{options};
2736 $raw .= &$format_options($options) if scalar(keys %$options);
2738 my $rules = $hostfw_conf->{rules};
2739 if (scalar(@$rules)) {
2740 $raw .= "[RULES]\n\n";
2741 $raw .= &$format_rules($rules, 1);
2745 PVE::Tools::file_set_contents($hostfw_conf_filename, $raw);
2749 my ($cluster_conf, $hostfw_conf, $vmdata, $verbose) = @_;
2753 if ($vmdata) { # test mode
2754 my $testdir = $vmdata->{testdir} || die "no test directory specified";
2755 my $filename = "$testdir/cluster.fw";
2756 $cluster_conf = load_clusterfw_conf($filename, $verbose);
2758 $filename = "$testdir/host.fw";
2759 $hostfw_conf = load_hostfw_conf($cluster_conf, $filename, $verbose);
2761 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, $testdir, $verbose);
2762 } else { # normal operation
2763 $cluster_conf = load_clusterfw_conf(undef, $verbose) if !$cluster_conf;
2765 $hostfw_conf = load_hostfw_conf($cluster_conf, undef, $verbose) if !$hostfw_conf;
2767 $vmdata = read_local_vm_config();
2768 $vmfw_configs = read_vm_firewall_configs($cluster_conf, $vmdata, undef, $verbose);
2771 $cluster_conf->{ipset}->{venet0} = [];
2772 my $venet0_ipset_chain = compute_ipset_chain_name(0, 'venet0
');
2775 if ($cluster_conf->{aliases}->{local_network}) {
2776 $localnet = $cluster_conf->{aliases}->{local_network}->{cidr};
2778 $localnet = local_network() || '127.0.0.0/8';
2779 $cluster_conf->{aliases}->{local_network} = { cidr => $localnet };
2782 push @{$cluster_conf->{ipset}->{management}}, { cidr => $localnet };
2784 return ({}, {}) if !$cluster_conf->{options}->{enable};
2788 ruleset_create_chain($ruleset, "PVEFW-INPUT");
2789 ruleset_create_chain($ruleset, "PVEFW-OUTPUT");
2791 ruleset_create_chain($ruleset, "PVEFW-FORWARD");
2793 my $hostfw_options = $hostfw_conf->{options} || {};
2795 # fixme: what log level should we use here?
2796 my $loglevel = get_option_log_level($hostfw_options, "log_level_out");
2798 ruleset_chain_add_conn_filters($ruleset, "PVEFW-FORWARD", "ACCEPT");
2801 ruleset_create_chain($ruleset, "PVEFW-VENET-OUT");
2802 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2803 ruleset_addrule($ruleset, "PVEFW-INPUT", "-i venet0 -m set --match-set ${venet0_ipset_chain} src -j PVEFW-VENET-OUT");
2805 ruleset_create_chain($ruleset, "PVEFW-FWBR-IN");
2806 ruleset_chain_add_input_filters($ruleset, "PVEFW-FWBR-IN", $hostfw_options, $cluster_conf, $loglevel);
2808 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-in fwln+ -j PVEFW-FWBR-IN");
2810 ruleset_create_chain($ruleset, "PVEFW-FWBR-OUT");
2811 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-m physdev --physdev-is-bridged --physdev-out fwln+ -j PVEFW-FWBR-OUT");
2813 ruleset_create_chain($ruleset, "PVEFW-VENET-IN");
2814 ruleset_chain_add_input_filters($ruleset, "PVEFW-VENET-IN", $hostfw_options, $cluster_conf, $loglevel);
2816 ruleset_addrule($ruleset, "PVEFW-FORWARD", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2818 generate_std_chains($ruleset, $hostfw_options);
2820 my $hostfw_enable = !(defined($hostfw_options->{enable}) && ($hostfw_options->{enable} == 0));
2822 my $ipset_ruleset = {};
2824 if ($hostfw_enable) {
2825 eval { enable_host_firewall($ruleset, $hostfw_conf, $cluster_conf); };
2826 warn $@ if $@; # just to be sure - should not happen
2829 ruleset_addrule($ruleset, "PVEFW-OUTPUT", "-o venet0 -m set --match-set ${venet0_ipset_chain} dst -j PVEFW-VENET-IN");
2831 # generate firewall rules for QEMU VMs
2832 foreach my $vmid (keys %{$vmdata->{qemu}}) {
2834 my $conf = $vmdata->{qemu}->{$vmid};
2835 my $vmfw_conf = $vmfw_configs->{$vmid};
2836 return if !$vmfw_conf;
2837 return if !$vmfw_conf->{options}->{enable};
2839 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2841 foreach my $netid (keys %$conf) {
2842 next if $netid !~ m/^net(\d+)$/;
2843 my $net = PVE::QemuServer::parse_net($conf->{$netid});
2844 next if !$net->{firewall};
2845 my $iface = "tap${vmid}i$1";
2847 my $macaddr = $net->{macaddr};
2848 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2849 $vmfw_conf, $vmid, 'IN
');
2850 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2851 $vmfw_conf, $vmid, 'OUT
');
2854 warn $@ if $@; # just to be sure - should not happen
2857 # generate firewall rules for OpenVZ containers
2858 foreach my $vmid (keys %{$vmdata->{openvz}}) {
2860 my $conf = $vmdata->{openvz}->{$vmid};
2862 my $vmfw_conf = $vmfw_configs->{$vmid};
2863 return if !$vmfw_conf;
2864 return if !$vmfw_conf->{options}->{enable};
2866 generate_ipset_chains($ipset_ruleset, $cluster_conf, $vmfw_conf);
2868 if ($conf->{ip_address} && $conf->{ip_address}->{value}) {
2869 my $ip = $conf->{ip_address}->{value};
2871 parse_address_list($ip); # make sure we have a valid $ip list
2873 my @ips = split(',', $ip);
2875 foreach my $singleip (@ips) {
2876 my $venet0ipset = {};
2877 $venet0ipset->{cidr} = $singleip;
2878 push @{$cluster_conf->{ipset}->{venet0}}, $venet0ipset;
2881 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'IN
');
2882 generate_venet_rules_direction($ruleset, $cluster_conf, $vmfw_conf, $vmid, $ip, 'OUT
');
2885 if ($conf->{netif} && $conf->{netif}->{value}) {
2886 my $netif = PVE::OpenVZ::parse_netif($conf->{netif}->{value});
2887 foreach my $netid (keys %$netif) {
2888 my $d = $netif->{$netid};
2890 my $macaddr = $d->{mac};
2891 my $iface = $d->{host_ifname};
2892 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2893 $vmfw_conf, $vmid, 'IN
');
2894 generate_tap_rules_direction($ruleset, $cluster_conf, $iface, $netid, $macaddr,
2895 $vmfw_conf, $vmid, 'OUT
');
2899 warn $@ if $@; # just to be sure - should not happen
2902 if(ruleset_chain_exist($ruleset, "PVEFW-IPS")){
2903 ruleset_insertrule($ruleset, "PVEFW-FORWARD", "-m conntrack --ctstate RELATED,ESTABLISHED -j PVEFW-IPS");
2906 generate_ipset_chains($ipset_ruleset, undef, $cluster_conf);
2908 return ($ruleset, $ipset_ruleset);
2911 sub get_ruleset_status {
2912 my ($ruleset, $active_chains, $digest_fn, $verbose) = @_;
2914 my $statushash = {};
2916 foreach my $chain (sort keys %$ruleset) {
2917 my $sig = &$digest_fn($ruleset->{$chain});
2919 $statushash->{$chain}->{sig} = $sig;
2921 my $oldsig = $active_chains->{$chain};
2922 if (!defined($oldsig)) {
2923 $statushash->{$chain}->{action} = 'create
';
2925 if ($oldsig eq $sig) {
2926 $statushash->{$chain}->{action} = 'exists';
2928 $statushash->{$chain}->{action} = 'update
';
2931 print "$statushash->{$chain}->{action} $chain ($sig)\n" if $verbose;
2932 foreach my $cmd (@{$ruleset->{$chain}}) {
2933 print "\t$cmd\n" if $verbose;
2937 foreach my $chain (sort keys %$active_chains) {
2938 if (!defined($ruleset->{$chain})) {
2939 my $sig = $active_chains->{$chain};
2940 $statushash->{$chain}->{action} = 'delete';
2941 $statushash->{$chain}->{sig} = $sig;
2942 print "delete $chain ($sig)\n" if $verbose;
2949 sub print_sig_rule {
2950 my ($chain, $sig) = @_;
2952 # We just use this to store a SHA1 checksum used to detect changes
2953 return "-A $chain -m comment --comment \"PVESIG:$sig\"\n";
2956 sub get_ruleset_cmdlist {
2957 my ($ruleset, $verbose) = @_;
2959 my $cmdlist = "*filter\n"; # we pass this to iptables-restore;
2961 my ($active_chains, $hooks) = iptables_get_chains();
2962 my $statushash = get_ruleset_status($ruleset, $active_chains, \&iptables_chain_digest, $verbose);
2964 # create missing chains first
2965 foreach my $chain (sort keys %$ruleset) {
2966 my $stat = $statushash->{$chain};
2967 die "internal error" if !$stat;
2968 next if $stat->{action} ne 'create
';
2970 $cmdlist .= ":$chain - [0:0]\n";
2973 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
2974 my $chain = "PVEFW-$h";
2975 if ($ruleset->{$chain} && !$hooks->{$h}) {
2976 $cmdlist .= "-A $h -j $chain\n";
2980 foreach my $chain (sort keys %$ruleset) {
2981 my $stat = $statushash->{$chain};
2982 die "internal error" if !$stat;
2984 if ($stat->{action
} eq 'update' || $stat->{action
} eq 'create') {
2985 $cmdlist .= "-F $chain\n";
2986 foreach my $cmd (@{$ruleset->{$chain}}) {
2987 $cmdlist .= "$cmd\n";
2989 $cmdlist .= print_sig_rule
($chain, $stat->{sig
});
2990 } elsif ($stat->{action
} eq 'delete') {
2991 die "internal error"; # this should not happen
2992 } elsif ($stat->{action
} eq 'exists') {
2995 die "internal error - unknown status '$stat->{action}'";
2999 foreach my $chain (keys %$statushash) {
3000 next if $statushash->{$chain}->{action
} ne 'delete';
3001 $cmdlist .= "-F $chain\n";
3003 foreach my $chain (keys %$statushash) {
3004 next if $statushash->{$chain}->{action
} ne 'delete';
3005 next if $chain eq 'PVEFW-INPUT';
3006 next if $chain eq 'PVEFW-OUTPUT';
3007 next if $chain eq 'PVEFW-FORWARD';
3008 $cmdlist .= "-X $chain\n";
3011 my $changes = $cmdlist ne "*filter\n" ?
1 : 0;
3013 $cmdlist .= "COMMIT\n";
3015 return wantarray ?
($cmdlist, $changes) : $cmdlist;
3018 sub get_ipset_cmdlist
{
3019 my ($ruleset, $verbose) = @_;
3023 my $delete_cmdlist = "";
3025 my $active_chains = ipset_get_chains
();
3026 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&ipset_chain_digest
, $verbose);
3028 # remove stale _swap chains
3029 foreach my $chain (keys %$active_chains) {
3030 if ($chain =~ m/^PVEFW-\S+_swap$/) {
3031 $cmdlist .= "destroy $chain\n";
3035 foreach my $chain (sort keys %$ruleset) {
3036 my $stat = $statushash->{$chain};
3037 die "internal error" if !$stat;
3039 if ($stat->{action
} eq 'create') {
3040 foreach my $cmd (@{$ruleset->{$chain}}) {
3041 $cmdlist .= "$cmd\n";
3045 if ($stat->{action
} eq 'update') {
3046 my $chain_swap = $chain."_swap";
3048 foreach my $cmd (@{$ruleset->{$chain}}) {
3049 $cmd =~ s/$chain/$chain_swap/;
3050 $cmdlist .= "$cmd\n";
3052 $cmdlist .= "swap $chain_swap $chain\n";
3053 $cmdlist .= "flush $chain_swap\n";
3054 $cmdlist .= "destroy $chain_swap\n";
3059 foreach my $chain (keys %$statushash) {
3060 next if $statushash->{$chain}->{action
} ne 'delete';
3062 $delete_cmdlist .= "flush $chain\n";
3063 $delete_cmdlist .= "destroy $chain\n";
3066 my $changes = ($cmdlist || $delete_cmdlist) ?
1 : 0;
3068 return ($cmdlist, $delete_cmdlist, $changes);
3072 my ($ruleset, $hostfw_conf, $ipset_ruleset, $verbose) = @_;
3074 enable_bridge_firewall
();
3076 my ($ipset_create_cmdlist, $ipset_delete_cmdlist, $ipset_changes) =
3077 get_ipset_cmdlist
($ipset_ruleset, undef, $verbose);
3079 my ($cmdlist, $changes) = get_ruleset_cmdlist
($ruleset, $verbose);
3082 if ($ipset_changes) {
3083 print "ipset changes:\n";
3084 print $ipset_create_cmdlist if $ipset_create_cmdlist;
3085 print $ipset_delete_cmdlist if $ipset_delete_cmdlist;
3089 print "iptables changes:\n";
3094 ipset_restore_cmdlist
($ipset_create_cmdlist);
3096 iptables_restore_cmdlist
($cmdlist);
3098 ipset_restore_cmdlist
($ipset_delete_cmdlist) if $ipset_delete_cmdlist;
3100 # test: re-read status and check if everything is up to date
3101 my $active_chains = iptables_get_chains
();
3102 my $statushash = get_ruleset_status
($ruleset, $active_chains, \
&iptables_chain_digest
, 0);
3105 foreach my $chain (sort keys %$ruleset) {
3106 my $stat = $statushash->{$chain};
3107 if ($stat->{action
} ne 'exists') {
3108 warn "unable to update chain '$chain'\n";
3113 die "unable to apply firewall changes\n" if $errors;
3115 update_nf_conntrack_max
($hostfw_conf);
3117 update_nf_conntrack_tcp_timeout_established
($hostfw_conf);
3121 sub update_nf_conntrack_max
{
3122 my ($hostfw_conf) = @_;
3124 my $max = 65536; # reasonable default
3126 my $options = $hostfw_conf->{options
} || {};
3128 if (defined($options->{nf_conntrack_max
}) && ($options->{nf_conntrack_max
} > $max)) {
3129 $max = $options->{nf_conntrack_max
};
3130 $max = int(($max+ 8191)/8192)*8192; # round to multiples of 8192
3133 my $filename_nf_conntrack_max = "/proc/sys/net/nf_conntrack_max";
3134 my $filename_hashsize = "/sys/module/nf_conntrack/parameters/hashsize";
3136 my $current = int(PVE
::Tools
::file_read_firstline
($filename_nf_conntrack_max) || $max);
3138 if ($current != $max) {
3139 my $hashsize = int($max/4);
3140 PVE
::ProcFSTools
::write_proc_entry
($filename_hashsize, $hashsize);
3141 PVE
::ProcFSTools
::write_proc_entry
($filename_nf_conntrack_max, $max);
3145 sub update_nf_conntrack_tcp_timeout_established
{
3146 my ($hostfw_conf) = @_;
3148 my $options = $hostfw_conf->{options
} || {};
3150 my $value = defined($options->{nf_conntrack_tcp_timeout_established
}) ?
$options->{nf_conntrack_tcp_timeout_established
} : 432000;
3152 PVE
::ProcFSTools
::write_proc_entry
("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", $value);
3155 sub remove_pvefw_chains
{
3157 my ($chash, $hooks) = iptables_get_chains
();
3158 my $cmdlist = "*filter\n";
3160 foreach my $h (qw(INPUT OUTPUT FORWARD)) {
3162 $cmdlist .= "-D $h -j PVEFW-$h\n";
3166 foreach my $chain (keys %$chash) {
3167 $cmdlist .= "-F $chain\n";
3170 foreach my $chain (keys %$chash) {
3171 $cmdlist .= "-X $chain\n";
3173 $cmdlist .= "COMMIT\n";
3175 iptables_restore_cmdlist
($cmdlist);
3177 my $ipset_chains = ipset_get_chains
();
3181 foreach my $chain (keys %$ipset_chains) {
3182 $cmdlist .= "flush $chain\n";
3183 $cmdlist .= "destroy $chain\n";
3186 ipset_restore_cmdlist
($cmdlist) if $cmdlist;
3190 my $cluster_conf = load_clusterfw_conf
();
3191 my $cluster_options = $cluster_conf->{options
};
3192 my $enable = $cluster_options->{enable
};
3196 # load required modules here
3202 my $cluster_conf = load_clusterfw_conf
();
3203 my $cluster_options = $cluster_conf->{options
};
3205 if (!$cluster_options->{enable
}) {
3206 PVE
::Firewall
::remove_pvefw_chains
();
3210 my $hostfw_conf = load_hostfw_conf
();
3212 my ($ruleset, $ipset_ruleset) = compile
($cluster_conf, $hostfw_conf);
3214 apply_ruleset
($ruleset, $hostfw_conf, $ipset_ruleset);