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